├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── bin └── server ├── lazymention.json.sample ├── lib ├── app.js ├── get.js ├── persistence.js └── webmention.js ├── npm-shrinkwrap.json ├── package.json ├── test ├── app-test.js ├── data │ ├── entry-1.html │ ├── entry-2.html │ ├── entry-3.html │ ├── h-feed-with-blank-a-tag.html │ └── h-feed-with-h-entries.html ├── get-test.js ├── lib │ ├── app.js │ ├── http.js │ ├── log.js │ └── persistence.js ├── persistence-test.js ├── submission-test.js ├── whitelist-test.js └── z-webmention-test.js └── tsconfig.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | 6 | # Runtime data 7 | pids 8 | *.pid 9 | *.seed 10 | *.pid.lock 11 | 12 | # Directory for instrumented libs generated by jscoverage/JSCover 13 | lib-cov 14 | 15 | # Coverage directory used by tools like istanbul 16 | coverage 17 | coverage-root 18 | 19 | # nyc test coverage 20 | .nyc_output 21 | 22 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 23 | .grunt 24 | 25 | # node-waf configuration 26 | .lock-wscript 27 | 28 | # Compiled binary addons (http://nodejs.org/api/addons.html) 29 | build/Release 30 | 31 | # Dependency directories 32 | node_modules 33 | jspm_packages 34 | 35 | # Optional npm cache directory 36 | .npm 37 | 38 | # Optional eslint cache 39 | .eslintcache 40 | 41 | # Optional REPL history 42 | .node_repl_history 43 | 44 | # Output of 'npm pack' 45 | *.tgz 46 | 47 | # Yarn Integrity file 48 | .yarn-integrity 49 | 50 | # TypeScript builds 51 | dist/ 52 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - 6 4 | - 8 5 | - 9 6 | - 10 7 | before_install: 8 | - npm install -g npm@5 9 | - npm install -g greenkeeper-lockfile@1 10 | before_script: greenkeeper-lockfile-update && npm run prepare 11 | script: npm test && npm run test:install 12 | # See greenkeeperio/greenkeeper-lockfile#87 for why we pipe to /dev/null 13 | after_script: "./node_modules/.bin/coveralls < coverage/lcov.info && greenkeeper-lockfile-upload > /dev/null" 14 | env: 15 | global: 16 | secure: m+cKinrp0YC4XuG/QD7mnHR1DWWwV6gTSR2tkxJXbollN+qjSltopgysTyppKsmyZf+rYtUc+YFzdwLu/soXZogxBiKBjxGfHAhUM33sAkPt9K2sGOLQU4QW6ZCUHnVYAxhJRebvKaYUST+VUPyO8Le4v4j7Evvmy8DiL3W7CjYL4+nu3ZRSjUiQd3LFIbZ1lJP+ihVwV3kyCl/IRMeh8YADRKWyefqKLyzC3MC3OR53AohDP0+UXy5xyUV/USlIX06GcsjoGex9vK3xh0mKPxB/goiAlNxqvG+V5DLRTT2cdRe7y7b5iFYRoYbddVzvgsZFD60qPQiBdqShPw792i78Yh3qng7G6pkEik6sS8KMEzVk4yVZahNxVBcNEMw5mjPCLCDfwFtk4+3RnY4PTX4Ro3TQAKOildjG+/10GpmfktrcMo0vRat18WTRr0XbKS2vUdkoMrGuSTjvNHTxrAoh+chsFBlJLxc+Ba4GKfVKwMagvYwAE0n6XUiUQV47N1U71x5AqGaTDTBtFXVIMrwQyBOqazJEMce/mjqaatiwF8EAElJrMj9FM7mhhc7ACBuz9yduUqUk4cCBezfy5TdqC6epjYmW13UVK3eVSnMXP97QmqtynH54wAUlN29UqB3v8PSn+q5zesSYkMgQKRWFOQULirB56PW3jN9a1KE= 17 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # lazymention changelog 2 | 3 | lazymention follows [Semantic Versioning 2.0.0][semver]. Specifically, the following things are considered to be semver-major if changed in a backwards-incompatible way: 4 | 5 | * Configuration value names, semantics, requirements and format 6 | * The public HTTP API 7 | * The embedding API, including the state the router embed expects to have available 8 | * Supported Node.js versions 9 | * This list of items 10 | 11 | Changes to everything else are not considered breaking. Notably, these are _not_ considered breaking: 12 | 13 | * Log messages 14 | 15 | If you think something that isn't in the first list should be covered, or aren't sure about something, please feel free to file an issue and I'll clarify the policy - this list could surely be more precise. 16 | 17 | ## 2.0.0 - future 18 | 19 | ### Breaking 20 | 21 | * Drop Node 4, 5, and 7 support 22 | 23 | ## 1.0.1 - 2018-12-06 24 | 25 | ### Changed 26 | 27 | * Various small improvements to documentation 28 | 29 | ### Fixed 30 | 31 | * Fix crash on relative URLs 32 | 33 | ## 1.0.0 - 2017-12-29 34 | 35 | * Initial release 36 | 37 | [semver]: https://semver.org/spec/v2.0.0.html 38 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at alex@strugee.net. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | 663 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # lazymention 2 | 3 | [![Build Status](https://travis-ci.org/strugee/lazymention.svg?branch=master)](https://travis-ci.org/strugee/lazymention) 4 | [![Coverage Status](https://coveralls.io/repos/github/strugee/lazymention/badge.svg?branch=master)](https://coveralls.io/github/strugee/lazymention?branch=master) 5 | [![NSP Status](https://nodesecurity.io/orgs/strugee/projects/530261ab-11a8-4f24-8b9f-55c005d0424e/badge)](https://nodesecurity.io/orgs/strugee/projects/530261ab-11a8-4f24-8b9f-55c005d0424e) 6 | [![Greenkeeper badge](https://badges.greenkeeper.io/strugee/lazymention.svg)](https://greenkeeper.io/) 7 | 8 | tl;dr: Support WebSub and Webmention on a static site 9 | 10 | lazymention is a daemon that you run on a server. When you publish to your static [IndieWeb][] site, you ping lazymention, and it will poll your site, parse the microformats2 markup, and send Webmentions and WebSub notifications for content it hasn't seen before. 11 | 12 | Webmention functionality is currently done. WebSub is planned for the future. 13 | 14 | ## Installation 15 | 16 | $ npm install -g --production lazymention 17 | 18 | ## Limitations 19 | 20 | lazymention makes some maintainability tradeoffs that may result in denial-of-service problems if you allow input from sites you don't trust. Specifically: 21 | 22 | * lazymention buffers all HTML pages in memory before parsing microformats2. In the future it may also retrieve multiple HTML pages per job. This may lead to high memory usage. 23 | * lazymention's handling of microformats2 structures within pages is rather brittle. For example, if you mark an element as both an `h-entry` _and_ an `h-feed`, lazymention will probably crash. I will take PRs to fix these problems, especially those caused by nonmalicious markup, but in the meantime your process will be very dead. 24 | * lazymention does not bother to check if it's sending Webmentions to `localhost` or loopback addresses. See the [Security Considerations section][] of the Webmention spec. 25 | 26 | Please be aware of these constraints before running lazymention in production. The `domains` option should help with this. 27 | 28 | Also, lazymention has no idea how to recurse into subpages of indexes. In the real world, I expect that this will not actually be a real problem. 29 | 30 | ## Running 31 | 32 | lazymention will install a command called, fittingly, `lazymention`. You need to provide, at minimum, a storage location (you can do this on the CLI by passing `-s`), but not configuring anything else will give you a daemon running on port 8000, which is probably no good. 33 | 34 | You can provide configuration options in three ways: CLI flags, environment variables, and JSON configuration files - CLI flags override environment variables and environment variables override JSON configs. The default config file location is `/etc/lazymention.json`, but you can override this by passing `-c `. There's a sample file called `lazymention.json.sample` but be sure to actually look at it; lazymention won't work for you if you don't adjust it a little bit. 35 | 36 | If you configure with environment variables, just prefix the configuration values with `LAZYMENTION_`. CLI flags are just prefixed with `--`, as you'd expect - just run `lazymention --help` if this is confusing. You can pass more than one value for `--domains` (e.g. `--domains example.com example.net`), as well as passing `--domains` more than once (e.g. `--domains example.com --domains example.net`). If you need to specify more than one domain via environment variables, separate them using `,`. 37 | 38 | You should also set `NODE_ENV=production` in the environment, regardless of how you're configuring lazymention. 39 | 40 | ### Configuration values 41 | 42 | Here's what you can configure: 43 | 44 | | Name | Description | Type | Default | 45 | | ---------- | ------------------------------------------------------------ | ------------- | --------- | 46 | | `storage` | Where to put data. Must be read/writable by the server user. | String | None | 47 | | `port` | Port for the HTTP server to bind to. | Number | 8000 | 48 | | `address` | Address for the HTTP server to bind to. | String | `0.0.0.0` | 49 | | `logger` | Whether to have the logger write logs. | Boolean | True | 50 | | `logfile` | Where to write logs to. | String | stdout | 51 | | `logLevel` | [Bunyan loglevel][] for the logger. | String | `info` | 52 | | `domains` | Whitelist of domains to allow in job submissions. | Array |None | 53 | 54 | The `storage` and `domains` options are required. If you don't want to use a whitelist you can set `domains` to `[]`, but you're _strongly_ discouraged from doing so because of the security implications. In fact, the reason you have to set this manually is to make sure you know what you're doing. 55 | 56 | ## Using the API 57 | 58 | There's exactly one API endpoint, `/jobs/submit`. To trigger lazymention, POST to this endpoint with a JSON payload in the body. The JSON should contain a `url` key whose value is the URL to crawl. 59 | 60 | If everything goes well, you'll get back 202 Accepted. If something went wrong, you'll get back 400 Bad Request, unless the domain of the URL you provided isn't in the whitelist in which case you'll get 403 Forbidden. 61 | 62 | In the future the reponse will contain a URL that lets you check the status of your job, but in the meantime all you get back is a lame 2xx status code. 63 | 64 | ### API clients 65 | 66 | There's currently one API client, [`ping-lazymention`][]. It's nice for [gulp][] tasks. 67 | 68 | Have you written another client? Please send a Pull Request updating this section! 69 | 70 | ## Embedding 71 | 72 | lazymention has an embedding API, in case you want to reuse its functionality in another Node app. You can access both the overall Express application or just the job submission route. 73 | 74 | It is safe to concurrently embed unlimited instances of either in the same process so long as they don't share the same data directory. 75 | 76 | Note: your app would have to be AGPL 3.0 or later to comply with the licensing terms, but if this is a big problem I might consider relaxing the requirements so just ping me. 77 | 78 | ### Express application 79 | 80 | Available as `require('lazymention').makeApp()`. You need to pass three arguments. In order: 81 | 82 | 1. A configurations object that contains, at minimum, a `domain` key with the appropriate value 83 | 2. A [Bunyan][] `Logger` object (or compatible) 84 | 3. A persistence factory function (see below) 85 | 86 | Not providing these options as specified will raise `AssertionError`. 87 | 88 | The Express app is configured to parse JSON bodies and to compress response bodies. You can't disable the former because it's required for anything useful to happen and you can't disable the latter because that's a bad idea. 89 | 90 | `req.log` is configured to be a Bunyan child log and `req.config` is set to the app's config. The API is mounted at `/jobs/submit`, just like the standalone daemon. 91 | 92 | ### Express `Router` 93 | 94 | Available as `require('lazymention').makeRouter()`. You need to pass a single argument, a persistence factory function (see below). Not providing this argument will raise `AssertionError`. 95 | 96 | The Router expects certain things: 97 | 98 | 1. A `req.body` with something useful in it (how to populate this is up to you) 99 | 2. A Bunyan `Logger` (or compatible) available as `req.log` 100 | 3. A configuration object available as `req.config` and containing, at minimum, a `domains` key 101 | 102 | Everything else is up to you. 103 | 104 | ### Persistence layer 105 | 106 | To work with the embedding API you are required to provide some layer for persistence. You can do whatever you want in this layer; the default implementation reads and writes flat files. You can either reuse the default or implement your own. 107 | 108 | You can get to the default implementation with `require('lazymention').persistence()`. Calling this will return a factory function configured with the filesystem `` you provided. 109 | 110 | If you don't want to use the default implementation, you need to write a factory function. This function will be passed a single parameter, a child of the Bunyan `Logger` object you passed. Keep in mind that it will be invoked with a different `Logger` for each request, so connecting out to a database or whatever each and every time this is invoked is probably a terrible idea. 111 | 112 | When invoked, your factory function should return an object with two keys, `get` and `set`. `set` must be a function that takes a namespace (string), key (string), an object to set as the value of that key, and a callback with signature `(err)`. `get` must be a function that takes a namespace, a lookup key and a callback with signature `(err, data)`, `data` being the object that was set with `set`. 113 | 114 | Values are guaranteed to be JSON-serializable but otherwise there are no restrictions on what they can be. 115 | 116 | ## Author 117 | 118 | AJ Jordan 119 | 120 | ## License 121 | 122 | AGPL 3.0 or later 123 | 124 | [IndieWeb]: https://indieweb.org/ 125 | [Security Considerations section]: https://www.w3.org/TR/webmention/#security-considerations 126 | [Bunyan loglevel]: https://github.com/trentm/node-bunyan#levels 127 | [`ping-lazymention`]: https://github.com/strugee/ping-lazymention/ 128 | [gulp]: https://gulpjs.com/ 129 | [Bunyan]: https://github.com/trentm/node-bunyan 130 | -------------------------------------------------------------------------------- /bin/server: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | 5 | Copyright 2017 AJ Jordan . 6 | 7 | This file is part of lazymention. 8 | 9 | lazymention is free software: you can redistribute it and/or modify it 10 | under the terms of the GNU Affero General Public License as published 11 | by the Free Software Foundation, either version 3 of the License, or 12 | (at your option) any later version. 13 | 14 | lazymention is distributed in the hope that it will be useful, but 15 | WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 17 | Affero General Public License for more details. 18 | 19 | You should have received a copy of the GNU Affero General Public 20 | License along with lazymention. If not, see 21 | . 22 | 23 | */ 24 | 25 | 'use strict'; 26 | 27 | var makeApp = require('../dist/app.js').makeApp, 28 | createDbFactory = require('../dist/persistence'), 29 | bunyan = require('bunyan'); 30 | 31 | var agpl_notice = ['Copyright (C) 2017 AJ Jordan .', 32 | 'License AGPLv3+: GNU Affero GPL version 3 or later .', 33 | 'This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.'].join('\n'); 34 | 35 | var argv = require('yargs') 36 | .usage('Usage: $0 [options]') 37 | .alias({'help': 'h', 'config': 'c', 'port': 'p', 'address': 'a', 'storage': 's'}) 38 | .describe({ 39 | port: 'Port that the HTTP server will bind to', 40 | address: 'Address that the HTTP server will bind to', 41 | storage: 'Writable filesytem directory the daemon will persist state to', 42 | domains: 'Whitelist of domains to allow in job submissions', 43 | logger: 'Whether to write logs', 44 | logfile: 'Full path to the file to stream logs (Bunyan-formatted JSON) to', 45 | logLevel: 'Bunyan loglevel (https://github.com/trentm/node-bunyan#levels)' 46 | }) 47 | .default({ 48 | config: '/etc/lazymention.json', 49 | address: '0.0.0.0', 50 | port: 8000, 51 | logger: true, 52 | logLevel: 'info' 53 | }) 54 | .boolean('logger') 55 | .number('port') 56 | .string(['address', 'storage', 'logfile', 'logLevel']) 57 | .array('domains') 58 | .demandOption(['storage', 'domains']) 59 | .config() 60 | .env('LAZYMENTION') 61 | .help() 62 | .version() 63 | .epilog(agpl_notice) 64 | .argv; 65 | 66 | // Clean up argv.domains in case it's set via the environment; see yargs/yargs#821 67 | // XXX use process.env to do something a little more intelligent here 68 | if (argv.domains.length === 1) { 69 | argv.domains = argv.domains[0].split(',').map(str => str.trim()); 70 | } 71 | 72 | console.log(agpl_notice); 73 | 74 | var logParams = { 75 | name: 'lazymention', 76 | serializers: { 77 | err: bunyan.stdSerializers.err, 78 | req: bunyan.stdSerializers.req, 79 | res: bunyan.stdSerializers.res 80 | }, 81 | level: argv.logLevel 82 | }; 83 | 84 | if (argv.logger === false) { 85 | logParams.streams = [{path: "/dev/null"}]; 86 | } else if (argv.logfile) { 87 | logParams.streams = [{path: argv.logfile}]; 88 | } else { 89 | logParams.streams = [{stream: process.stdout}]; 90 | } 91 | 92 | var log = bunyan.createLogger(logParams), 93 | createDb = createDbFactory(argv.storage), 94 | app = makeApp(argv, log, createDb); 95 | 96 | var server = app.listen(argv.port, argv.address, function() { 97 | var host = server.address().address; 98 | var port = server.address().port; 99 | log.info('Server listening at http://' + host + ':' + port + '/'); 100 | }); 101 | 102 | server.on('error', log.error.bind(log)); 103 | -------------------------------------------------------------------------------- /lazymention.json.sample: -------------------------------------------------------------------------------- 1 | { 2 | "domains": ["example.com"], 3 | "storage": "/var/local/lazymention", 4 | "port": 8000, 5 | "address": "0.0.0.0", 6 | "logfile": "/var/log/lazymention.json.log" 7 | } 8 | -------------------------------------------------------------------------------- /lib/app.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var express = require('express'), 26 | compression = require('compression'), 27 | _ = require('lodash'), 28 | uuid = require('uuid'), 29 | crawl = require('crawl-mf2'), 30 | url = require('url'), 31 | assert = require('assert'), 32 | createWebmentionDispatcher = require('./webmention'), 33 | createGetter = require('./get'), 34 | persistence = require('./persistence'); // Not used, only exported 35 | 36 | function makeRouter(createDb) { 37 | assert(typeof createDb === 'function'); 38 | 39 | var router = express.Router(); 40 | 41 | router.use(function(req, res, next) { 42 | req.db = createDb(req.log); 43 | next(); 44 | }); 45 | 46 | router.post('/submit', function(req, res, next) { 47 | var webmention = createWebmentionDispatcher(req.log, req.db), 48 | get = createGetter(req.log); 49 | 50 | req.log.info({req: req}, 'Handling incoming request.'); 51 | 52 | // TODO assign a URL for status checks 53 | 54 | if (_.isEmpty(req.body)) { 55 | res.status(400); 56 | res.end('JSON object was empty, or wrong Content-Type provided'); 57 | req.log.info({res: res}, 'Returning error due to malformed request JSON.'); 58 | return; 59 | } 60 | 61 | var target = req.body.url; 62 | 63 | if (!target) { 64 | res.status(400); 65 | res.end('No URL provided'); 66 | req.log.info({res: res}, 'Returning error due to missing URL in request.'); 67 | return; 68 | } 69 | 70 | var hostname = url.parse(target).hostname; 71 | if (req.config.domains.length > 0 && !req.config.domains.includes(hostname)) { 72 | res.status(403); 73 | res.end('Domain ' + hostname + ' not in server whitelist'); 74 | req.log.info({res: res, domain: hostname}, 'Returning Forbidden due to domain not in whitelist.'); 75 | return; 76 | } 77 | 78 | res.status(202); 79 | 80 | req.log.info({url: target}, 'Triggered Webmention processing from inbound request.'); 81 | 82 | // XXX UA 83 | var crawler = crawl(target); 84 | 85 | crawler.on('error', function(err) { 86 | req.warn({err: err}, 'Error while crawling microformats2.'); 87 | }); 88 | 89 | // XXX update status throughout this bit 90 | crawler.on('h-entry', function(url, node) { 91 | req.log.info('Found canonical h-entry; triggering Webmention processing.'); 92 | // XXX pass an updated timestamp 93 | webmention(url, 0, node.properties.content[0].html, function(err) { 94 | if (err) { 95 | req.log.error({err: err}, 'Error during Webmention processing.'); 96 | // XXX update status 97 | return; 98 | } 99 | 100 | // TODO update status check URL, etc. 101 | req.log.info('Finished Webmention processing.'); 102 | }); 103 | }); 104 | 105 | res.end(); 106 | req.log.info({res: res}, 'Jobs queued; returning success.'); 107 | }); 108 | 109 | return router; 110 | } 111 | 112 | function makeApp(config, _log, createDb) { 113 | assert(typeof config === 'object'); 114 | assert(typeof _log === 'object'); 115 | assert(typeof _log.info === 'function'); 116 | assert(typeof createDb === 'function'); 117 | 118 | var app = express(), 119 | router = makeRouter(createDb); 120 | 121 | app.use(compression()); 122 | app.use(express.json()); 123 | 124 | app.use(function(req, res, next) { 125 | // XXX pass this into modules 126 | req.log = _log.child({req_id: uuid.v4()}); 127 | req.config = config; 128 | next(); 129 | }); 130 | 131 | app.use('/jobs/', router); 132 | 133 | return app; 134 | } 135 | 136 | module.exports.makeApp = makeApp; 137 | module.exports.makeRouter = makeRouter; 138 | module.exports.persistence = persistence; 139 | -------------------------------------------------------------------------------- /lib/get.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var _http = require('follow-redirects').http, 26 | https = require('follow-redirects').https, 27 | url = require('url'), 28 | concat = require('concat-stream'), 29 | pkg = require('../package.json'), 30 | uuid = require('uuid'); 31 | 32 | module.exports = function createGetter(_retrievalLog) { 33 | var retrievalLog = _retrievalLog.child({component: 'get'}); 34 | 35 | return function get(path, callback) { 36 | var opts = url.parse(path), 37 | useHTTP = opts.protocol === 'http:', 38 | log = retrievalLog.child({job_id: uuid.v4()}); 39 | 40 | log.debug({url: path}, 'Retrieving URL with HTTP GET over ' + (useHTTP ? 'HTTP.' : 'TLS.')); 41 | 42 | var http = useHTTP ? _http : https; 43 | 44 | opts.headers = { 45 | 'User-Agent': 'node.js/' + process.versions.node + ' ' + pkg.name + '/' + pkg.version 46 | }; 47 | 48 | var req = http.get(opts); 49 | 50 | req.on('response', function(res) { 51 | log.debug({res: res}, 'Received response.'); 52 | if (res.statusCode < 200 || res.statusCode >= 300) { 53 | callback(new Error('Request to ' + path + ' returned HTTP ' + res.statusCode)); 54 | return; 55 | } 56 | 57 | res.pipe(concat(function(buf) { 58 | callback(undefined, buf.toString()); 59 | })); 60 | }); 61 | 62 | req.on('error', function(err) { 63 | log.debug({err: err}, 'Encountered error during request.'); 64 | callback(err); 65 | }); 66 | }; 67 | 68 | }; 69 | -------------------------------------------------------------------------------- /lib/persistence.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var assert = require('assert'), 26 | fs = require('fs'), 27 | path = require('path'), 28 | slashEscape = require('slash-escape'), 29 | writeFileAtomic = require('write-file-atomic'), 30 | uuid = require('uuid'); 31 | 32 | function computePath(storagePath, key) { 33 | // 'undefined' here because there was a bug and we have to keep backwards compat 34 | return path.join(storagePath, slashEscape.escape(key + '_undefined.json')); 35 | } 36 | 37 | function createPersistenceDbFactory(storagePath) { 38 | /* 39 | 40 | This is a simple filesystem-backed persistence layer for lazymention. Each key 41 | corresponds to one file - the filename is set to the slash-escaped key and the 42 | value is serialized to JSON and written to the file. 43 | 44 | The factory is initialized with a filesystem storage path and an in-memory cache 45 | backed by a Map. When a write occurs, the cache is updated and a file is written 46 | atomically. When a read occurs, the cache is checked and if there's a hit, the 47 | callback is scheduled for invocation with the result. If there's a miss, the 48 | disk is read. If there's a result the contents of the relevant file are 49 | deserialized and passed to the callback; if not an empty object is passed 50 | instead. Note that this means that you're always guaranteed to get an object 51 | back and it will just be empty if nothing's been set before. 52 | 53 | Note also that the in-memory cache serves two extremely important functions - it 54 | acts as a performance boost, but it also serves as a consistency construct that 55 | eliminates the need for any sort of locking. Because Node.js is single-threaded, 56 | a write is guaranteed to update the cache in the same tick of the event 57 | loop. Any code that would perform a read while the disk write is still in 58 | progress will hit the cache and not the disk, and so get back the new, correct 59 | result. 60 | 61 | */ 62 | 63 | var cache = new Map(); 64 | 65 | return function createPersistenceDb(_dbLog) { 66 | var dbLog = _dbLog.child({component: 'persistence'}); 67 | 68 | return { 69 | get: function(namespace, _key, cb) { 70 | assert(storagePath); 71 | 72 | var log = dbLog.child({job_id: uuid.v4()}), 73 | key = namespace + '_' + _key; 74 | 75 | log.debug({key: key}, 'Retrieving key.'); 76 | 77 | // XXX should we cache empty results? 78 | if (cache.has(key)) { 79 | log.trace({key: key}, 'Returning key from in-memory cache.'); 80 | process.nextTick(cb.bind(undefined, undefined, cache.get(key))); 81 | return; 82 | } 83 | 84 | fs.readFile(computePath(storagePath, key), function(err, data) { 85 | // XXX make sure it was the leaf of the directory tree 86 | if (err && err.code === 'ENOENT') { 87 | log.debug('Key does not exist; returning empty store.'); 88 | cb(undefined, {}); 89 | return; 90 | } 91 | 92 | if (err) { 93 | log.error({err: err}, 'Error retrieving key.'); 94 | cb(err); 95 | return; 96 | } 97 | 98 | data = JSON.parse(data.toString()); 99 | log.debug({value: data}, 'Retrieved key.'); 100 | cb(undefined, data); 101 | }); 102 | }, 103 | set: function(namespace, _key, data, cb) { 104 | assert(storagePath); 105 | 106 | if (!cb) cb = function() {}; 107 | 108 | var log = dbLog.child({job_id: uuid.v4()}), 109 | key = namespace + '_' + _key; 110 | 111 | log.debug({key: key, value: data}, 'Setting key.'); 112 | 113 | cache.set(key, data); 114 | 115 | writeFileAtomic(computePath(storagePath, key), JSON.stringify(data), function(err) { 116 | if (err) { 117 | // XXX should we do something more drastic here? Maybe restore the old value or crash? 118 | log.error({err: err}, 'Error setting key; in-memory cache is out-of-sync!'); 119 | } else { 120 | log.debug('Set key.'); 121 | } 122 | 123 | cb(err); 124 | }); 125 | } 126 | }; 127 | }; 128 | } 129 | 130 | module.exports = createPersistenceDbFactory; 131 | -------------------------------------------------------------------------------- /lib/webmention.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var cheerio = require('cheerio'), 26 | webmention = require('send-webmention'), 27 | _ = require('lodash'), 28 | uuid = require('uuid'), 29 | URLToolkit = require('url-toolkit'); 30 | 31 | module.exports = function createWebmentionDispatcher(_log, db) { 32 | _log = _log.child({component: 'webmention'}); 33 | 34 | return function sendWebmention(sourceUrl, updatedTimestamp, html, cb) { 35 | var log = _log.child({job_id: uuid.v4()}); 36 | 37 | log.info({url: sourceUrl}, 'Processing Webmentions for URL.'); 38 | 39 | db.get('PAGE', sourceUrl, function(err, data) { 40 | if (err) { 41 | cb(err); 42 | return; 43 | } 44 | 45 | if (data.lastSentWebmention > updatedTimestamp) { 46 | log.debug({ 47 | lastSent: data.lastSentWebmention, 48 | postTimestamp: updatedTimestamp 49 | }, 'Ignoring URL because we\'ve seen this post before.'); 50 | cb(); 51 | return; 52 | } 53 | 54 | var $ = cheerio.load(html); 55 | 56 | var links = $('a'), 57 | jobs = 0; 58 | 59 | links.each(function(idx, el) { 60 | // XXX should we try to check for malformed URLs in a more generic way...? 61 | if (el.attribs.href.length === 0) { 62 | log.debug('Dropping attempt to send Webmention to empty href.'); 63 | return; 64 | } 65 | 66 | // XXX log `el` with a nice Bunyan formatter 67 | var target = URLToolkit.buildAbsoluteURL(sourceUrl, el.attribs.href); 68 | log.debug({target: target}, 'Attempting to send Webmention.'); 69 | jobs++; 70 | webmention(sourceUrl, target, function(err, result) { 71 | if (err) { 72 | log.error({target: target, err: err}, 'Error sending Webmention.'); 73 | cb(err); 74 | return; 75 | } 76 | 77 | // TODO maybe do something intellingent with result 78 | 79 | log.debug({ 80 | target: el.attribs.href, 81 | success: result.success, 82 | status_code: (result.res || {statusCode: undefined}).statusCode 83 | }, 'Finished Webmention send attempt.'); 84 | 85 | jobs--; 86 | 87 | // XXX should we do some sort of db merge instead? 88 | if (jobs === 0) { 89 | log.debug('Completed Webmention processing.'); 90 | db.set('PAGE', sourceUrl, _.assign(data, { 91 | // Normalize to seconds 92 | lastSentWebmention: Date.now() / 1000 93 | }), cb); 94 | } 95 | }); 96 | }); 97 | 98 | if (jobs === 0) { 99 | log.debug('Nothing to do; completed Webmention processing.'); 100 | process.nextTick(cb); 101 | } 102 | }); 103 | }; 104 | }; 105 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lazymention", 3 | "version": "1.0.1", 4 | "description": "Support WebSub and Webmention on a static site", 5 | "main": "lib/app.js", 6 | "bin": { 7 | "lazymention": "./bin/server" 8 | }, 9 | "scripts": { 10 | "build": "tsc", 11 | "prepare": "npm run build", 12 | "test": "npm run build && nyc -r lcov -r text perjury test/*-test.js", 13 | "test:install": "npm install -g . && type lazymention", 14 | "watch": "tsc -w" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/strugee/lazymention.git" 19 | }, 20 | "keywords": [ 21 | "webmention", 22 | "websub", 23 | "indieweb", 24 | "staticsite", 25 | "daemon" 26 | ], 27 | "author": "AJ Jordan ", 28 | "license": "AGPL-3.0+", 29 | "bugs": { 30 | "url": "https://github.com/strugee/lazymention/issues" 31 | }, 32 | "homepage": "https://github.com/strugee/lazymention#readme", 33 | "dependencies": { 34 | "bunyan": "^1.8.12", 35 | "cheerio": "^1.0.0-rc.2", 36 | "compression": "^1.7.1", 37 | "concat-stream": "^1.6.0", 38 | "crawl-mf2": "github:strugee/node-crawl-mf2", 39 | "express": "^4.16.2", 40 | "follow-redirects": "^1.2.5", 41 | "lodash": "^4.17.11", 42 | "microformat-node": "^2.0.1", 43 | "send-webmention": "^2.0.0", 44 | "slash-escape": "^1.0.0", 45 | "url-toolkit": "^2.1.2", 46 | "uuid": "^3.1.0", 47 | "write-file-atomic": "^2.3.0", 48 | "yargs": "^10.0.3" 49 | }, 50 | "devDependencies": { 51 | "coveralls": "^3.0.1", 52 | "mock-fs": "^4.4.2", 53 | "nyc": "^13.3.0", 54 | "perjury": "^1.1.4", 55 | "proxyquire": "^2.0.1", 56 | "sinon": "^4.1.2", 57 | "typescript": "^2.6.2" 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /test/app-test.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var vows = require('perjury'), 26 | assert = vows.assert, 27 | express = require('express'), 28 | noopLog = require('./lib/log'), 29 | db = require('../dist/persistence'); 30 | 31 | vows.describe('app module test').addBatch({ 32 | 'When we get the app module': { 33 | topic: function() { 34 | return require('../dist/app'); 35 | }, 36 | 'it works': function(err) { 37 | assert.ifError(err); 38 | }, 39 | 'it exports an Express application factory function': function(err, app) { 40 | assert.isFunction(app.makeApp); 41 | }, 42 | 'it exports an Express Router factory function': function(err, app) { 43 | assert.isFunction(app.makeRouter); 44 | }, 45 | 'it exports the default persistence layer implementation': function(err, app) { 46 | assert.isFunction(app.persistence); 47 | }, 48 | 'and we call makeApp()': { 49 | topic: function(app) { 50 | return app.makeApp({}, noopLog, db('/tmp')); 51 | }, 52 | 'it works': function(err) { 53 | assert.ifError(err); 54 | }, 55 | 'it returns an Express application': function(err, app) { 56 | assert.isFunction(app); 57 | assert.isFunction(app.listen); 58 | } 59 | }, 60 | 'and we call makeRouter()': { 61 | topic: function(app) { 62 | return app.makeRouter(db(noopLog, '/tmp')); 63 | }, 64 | 'it works': function(err) { 65 | assert.ifError(err); 66 | }, 67 | 'it exports an Express Router': function(err, router) { 68 | assert.isFunction(router); 69 | assert.isTrue(express.Router.isPrototypeOf(router)); 70 | } 71 | } 72 | } 73 | }).export(module); 74 | -------------------------------------------------------------------------------- /test/data/entry-1.html: -------------------------------------------------------------------------------- 1 |
2 |

Fascinating entry 1

3 |

Blah blah blah!

4 |
5 | -------------------------------------------------------------------------------- /test/data/entry-2.html: -------------------------------------------------------------------------------- 1 |
2 |

Another interesting entry 2

3 |

Lorem ipsum dolor sit amet???

4 |
5 | -------------------------------------------------------------------------------- /test/data/entry-3.html: -------------------------------------------------------------------------------- 1 |
2 |

Malformed entry 3

3 |

Look ma! A link with no href!

4 |
5 | -------------------------------------------------------------------------------- /test/data/h-feed-with-blank-a-tag.html: -------------------------------------------------------------------------------- 1 |
2 |

Blog

3 | 9 |
10 | -------------------------------------------------------------------------------- /test/data/h-feed-with-h-entries.html: -------------------------------------------------------------------------------- 1 |
2 |

Blog

3 | 9 | 15 |
16 | -------------------------------------------------------------------------------- /test/get-test.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var vows = require('perjury'), 26 | assert = vows.assert, 27 | http = require('http'), 28 | noopLog = require('./lib/log'), 29 | pkg = require('../package.json'); 30 | 31 | vows.describe('HTTP retrieval module').addBatch({ 32 | 'When we set up a dummy HTTP server': { 33 | topic: function() { 34 | var cb = this.callback, 35 | server = http.createServer(function(req, res) { 36 | if (req.url === '/generate_404') { 37 | res.statusCode = 404; 38 | res.end(); 39 | return; 40 | } 41 | 42 | if (req.url === '/get_ua') { 43 | res.end(req.headers['user-agent']); 44 | return; 45 | } 46 | 47 | res.end('Hello IndieWeb!'); 48 | }); 49 | 50 | server.listen(57810, function(err) { 51 | cb(err, server); 52 | }); 53 | }, 54 | teardown: function(server) { 55 | if (server && server.close) { 56 | server.close(this.callback); 57 | } 58 | }, 59 | 'it works': function(err, server) { 60 | assert.ifError(err); 61 | assert.isObject(server); 62 | }, 63 | 'and we require the module': { 64 | topic: function() { 65 | return require('../dist/get'); 66 | }, 67 | 'it works': function(err) { 68 | assert.ifError(err); 69 | }, 70 | 'it exports a factory function': function(err, createGetter) { 71 | assert.isFunction(createGetter); 72 | }, 73 | 'and we create a getter': { 74 | topic: function(createGetter) { 75 | return createGetter(noopLog); 76 | }, 77 | 'it works': function(err) { 78 | assert.ifError(err); 79 | }, 80 | 'we get back a function': function(err, get) { 81 | assert.isFunction(get); 82 | }, 83 | 'and we retrieve a URL from the dummy server': { 84 | topic: function(get) { 85 | get('http://localhost:57810', this.callback); 86 | }, 87 | 'it works': function(err) { 88 | assert.ifError(err); 89 | }, 90 | 'we get the right data back': function(err, data) { 91 | assert.isString(data); 92 | assert.equal(data, 'Hello IndieWeb!'); 93 | } 94 | }, 95 | 'and we try retrieving from a nonexistant server': { 96 | topic: function(get) { 97 | var cb = this.callback; 98 | 99 | get('http://localhost:29834', function(err, data) { 100 | if (data) { 101 | cb(new Error('unexpected success'), data); 102 | return; 103 | } 104 | 105 | cb(undefined, err); 106 | }); 107 | }, 108 | 'it works': function(err) { 109 | assert.ifError(err); 110 | }, 111 | 'the error is propogated back to us': function(err, result) { 112 | assert.isTrue(result instanceof Error); 113 | assert.equal('ECONNREFUSED', result.errno); 114 | } 115 | }, 116 | 'and we retrieve a route that returns 404': { 117 | topic: function(get) { 118 | var cb = this.callback; 119 | 120 | get('http://localhost:57810/generate_404', function(err, data) { 121 | if (data) { 122 | cb(new Error('unexpected success'), data); 123 | return; 124 | } 125 | 126 | cb(undefined, err); 127 | }); 128 | }, 129 | 'it works': function(err) { 130 | assert.ifError(err); 131 | }, 132 | 'the 4xx status code triggers an error condition': function(err, result) { 133 | assert.isTrue(result instanceof Error); 134 | assert.isTrue(result.message.includes('returned HTTP 404')); 135 | } 136 | }, 137 | 'and we ask what User Agent we send': { 138 | topic: function(get) { 139 | get('http://localhost:57810/get_ua', this.callback); 140 | }, 141 | 'it works': function(err) { 142 | assert.ifError(err); 143 | }, 144 | 'we sent the right User-Agent': function(err, data) { 145 | assert.isTrue(data.includes('node.js/')); 146 | assert.isTrue(data.includes('lazymention/' + pkg.version)); 147 | } 148 | } 149 | } 150 | } 151 | } 152 | }).export(module); 153 | -------------------------------------------------------------------------------- /test/lib/app.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | // TODO test this file 26 | 27 | var assert = require('perjury').assert, 28 | noopLog = require('./log'), 29 | memoryPersistence = require('./persistence').memoryPersistence, 30 | _ = require('lodash'); 31 | 32 | function configureAppSetup(config) { 33 | return { 34 | topic: function() { 35 | var app = require('../../dist/app').makeApp(_.defaults(config, { 36 | domains: [] 37 | }), noopLog, memoryPersistence()), 38 | cb = this.callback; 39 | 40 | var server = app.listen(config.port || 5320, config.address || 'localhost', function(err) { 41 | cb(err, server); 42 | }); 43 | }, 44 | teardown: function(app) { 45 | if (app && app.close) { 46 | app.close(this.callback); 47 | } 48 | }, 49 | 'it works': function(err, app) { 50 | assert.ifError(err); 51 | } 52 | }; 53 | } 54 | 55 | function wrapAppSetup(config, obj) { 56 | if (!obj) { 57 | obj = config; 58 | config = {}; 59 | } 60 | 61 | return _.assign({}, configureAppSetup(config), obj); 62 | } 63 | 64 | module.exports.wrapAppSetup = wrapAppSetup; 65 | -------------------------------------------------------------------------------- /test/lib/http.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | // TODO test this file 26 | 27 | var http = require('http'); 28 | 29 | function httpPost(port, path, data, headers, callback) { 30 | // Make port optional 31 | if (typeof port === 'string') { 32 | callback = headers; 33 | headers = data; 34 | data = path; 35 | path = port; 36 | port = 5320; 37 | } 38 | 39 | // Make headers optional 40 | if (!callback) { 41 | callback = headers; 42 | headers = {}; 43 | } 44 | 45 | var opts = { 46 | port: port, 47 | host: 'localhost', 48 | method: 'POST', 49 | path: path, 50 | headers: headers 51 | }; 52 | 53 | var req = http.request(opts, function(res) { 54 | callback(undefined, res); 55 | }); 56 | 57 | req.on('error', function(err) { 58 | callback(err); 59 | }); 60 | 61 | req.end(data); 62 | }; 63 | 64 | function httpPostJSON(port, path, data, callback) { 65 | if (typeof port === 'string') { 66 | callback = data; 67 | data = path; 68 | path = port; 69 | port = 5320; 70 | } 71 | 72 | httpPost(port, path, JSON.stringify(data), {'Content-Type': 'application/json'}, callback); 73 | }; 74 | 75 | module.exports.post = httpPost; 76 | module.exports.postJSON = httpPostJSON; 77 | -------------------------------------------------------------------------------- /test/lib/log.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | // TODO test this file 26 | 27 | var bunyan = require('bunyan'); 28 | 29 | module.exports = new bunyan({name: 'noop', streams: []}); 30 | -------------------------------------------------------------------------------- /test/lib/persistence.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | // TODO test this file 26 | 27 | var assert = require('perjury').assert, 28 | _ = require('lodash'), 29 | mockFs = require('mock-fs'); 30 | 31 | function buildMockSetup(configurePath) { 32 | return { 33 | topic: function(passthrough) { 34 | mockFs({ 35 | '/tmp': mockFs.directory() 36 | }); 37 | return passthrough; 38 | }, 39 | teardown: function(app) { 40 | mockFs.restore(); 41 | return true; 42 | }, 43 | 'it works': function(err, app) { 44 | assert.ifError(err); 45 | } 46 | }; 47 | }; 48 | 49 | function wrapFsMocks(configurePath, obj) { 50 | if (!obj) { 51 | obj = configurePath; 52 | configurePath = true; 53 | } 54 | 55 | return _.assign({}, buildMockSetup(configurePath), obj); 56 | } 57 | 58 | function makeInMemoryPersistence() { 59 | var store = new Map(); 60 | 61 | return function() { 62 | return { 63 | get: function(namespace, key, cb) { 64 | process.nextTick(cb.bind(undefined, undefined, store.get(namespace + key) || {})); 65 | }, 66 | set: function(namespace, key, data, cb) { 67 | store.set(namespace + key, data); 68 | process.nextTick(cb); 69 | 70 | } 71 | }; 72 | }; 73 | } 74 | 75 | module.exports.wrapFsMocks = wrapFsMocks; 76 | module.exports.memoryPersistence = makeInMemoryPersistence; 77 | -------------------------------------------------------------------------------- /test/persistence-test.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var vows = require('perjury'), 26 | assert = vows.assert, 27 | _ = require('lodash'), 28 | noopLog = require('./lib/log'), 29 | persistenceutil = require('./lib/persistence'), 30 | wrapFsMocks = persistenceutil.wrapFsMocks; 31 | 32 | var getNonexistantKey = { 33 | topic: function(db) { 34 | db.get('TEST', 'lolnope', this.callback); 35 | }, 36 | 'it worked': function(err) { 37 | assert.ifError(err); 38 | }, 39 | 'it gave us an empty object': function(err, result) { 40 | assert.isObject(result); 41 | assert.isTrue(_.isEmpty(result)); 42 | } 43 | }; 44 | 45 | var getKey = { 46 | topic: function(db) { 47 | db.get('TEST', 'meaning_of_life', this.callback); 48 | }, 49 | 'it worked': function(err) { 50 | assert.ifError(err); 51 | }, 52 | 'it has the value we set': function(err, result) { 53 | assert.isNumber(result); 54 | assert.equal(result, 42); 55 | } 56 | }; 57 | 58 | vows.describe('persistence module').addBatch({ 59 | 'When we require the module': { 60 | topic: function() { 61 | return require('../dist/persistence'); 62 | }, 63 | 'it works': function(err) { 64 | assert.ifError(err); 65 | }, 66 | // I hate this so damn much 67 | 'it exports a factory creation function': function(err, createDbFactory) { 68 | assert.isFunction(createDbFactory); 69 | }, 70 | 'and we create a persistence database factory': { 71 | topic: function(createDbFactory) { 72 | debugger; 73 | return createDbFactory('/tmp'); 74 | }, 75 | 'it we get back a factory function': function(err, createDb) { 76 | assert.isFunction(createDb); 77 | }, 78 | 'and we create a persistence database instance': { 79 | topic: function(createDb) { 80 | return createDb(noopLog); 81 | }, 82 | 'it has the right functions': function(err, db) { 83 | assert.isFunction(db.get); 84 | assert.isFunction(db.set); 85 | }, 86 | 'and we mock out the `fs` module': wrapFsMocks(false, { 87 | 'and we set a key': { 88 | topic: function(db) { 89 | var cb = this.callback; 90 | db.set('TEST', 'meaning_of_life', 42, function(err) { 91 | cb(err, db); 92 | }); 93 | }, 94 | 'it works': function(err) { 95 | assert.ifError(err); 96 | }, 97 | 'and we get the key': getKey, 98 | 'and we get the key from a different namespace': { 99 | topic: function(db) { 100 | db.get('TSET', 'meaning_of_life', this.callback); 101 | }, 102 | 'it worked': function(err) { 103 | assert.ifError(err); 104 | }, 105 | 'it gave us an empty object': function(err, result) { 106 | assert.isObject(result); 107 | assert.isTrue(_.isEmpty(result)); 108 | } 109 | } 110 | }, 111 | 'and we set a key with a slash': { 112 | topic: function(db) { 113 | var cb = this.callback; 114 | db.set('TEST', 'lazymention/subkey', {foo: 'bar'}, function(err) { 115 | cb(err, db); 116 | }); 117 | }, 118 | 'it works': function(err) { 119 | assert.ifError(err); 120 | }, 121 | 'and we get the key': { 122 | topic: function(db) { 123 | db.get('TEST', 'lazymention/subkey', this.callback); 124 | }, 125 | 'it worked': function(err, obj) { 126 | assert.ifError(err); 127 | assert.equal(obj.foo, 'bar'); 128 | } 129 | }, 130 | 'and we set up a new instance to bust the cache': { 131 | topic: function() { 132 | return require('../dist/persistence')('/tmp')(noopLog); 133 | }, 134 | 'it worked': function(err) { 135 | assert.ifError(err); 136 | }, 137 | 'and we get a key': getKey, 138 | 'and we get a nonexistant key': getNonexistantKey 139 | } 140 | }, 141 | 'and we get a nonexistant key': getNonexistantKey 142 | }) 143 | } 144 | } 145 | } 146 | }).export(module); 147 | -------------------------------------------------------------------------------- /test/submission-test.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var vows = require('perjury'), 26 | assert = vows.assert, 27 | express = require('express'), 28 | path = require('path'), 29 | httputil = require('./lib/http'), 30 | apputil = require('./lib/app'), 31 | wrapAppSetup = apputil.wrapAppSetup; 32 | 33 | // XXX also assert on an OPTIONS request 34 | 35 | vows.describe('submission test').addBatch({ 36 | 'When we set up a server to serve posts': { 37 | topic: function() { 38 | var app = express(), 39 | cb = this.callback; 40 | 41 | app.use(express.static(path.join(__dirname, 'data'), { 42 | extensions: ['html'] 43 | })); 44 | 45 | var server = app.listen(17140, function(err) { 46 | cb(err, server); 47 | }); 48 | }, 49 | teardown: function(server) { 50 | if (server && server.close) { 51 | server.close(this.callback); 52 | } 53 | }, 54 | 'it works': function(err) { 55 | assert.ifError(err); 56 | }, 57 | 'and we set up the app': wrapAppSetup({ 58 | 'and we HTTP POST to /jobs/submit': { 59 | topic: function(app) { 60 | httputil.postJSON('/jobs/submit', 61 | { 62 | url: 'http://localhost:17140/h-feed-with-h-entries.html' 63 | }, 64 | // We set a timeout because otherwise the 65 | // response handler returns 202 Accepted 66 | // immediately, Perjury finishes the rest 67 | // of the tests and exits, and the rest of 68 | // the response handler doesn't have time 69 | // to run. 70 | // 71 | // This is obviously a dirty hack because 72 | // we don't have proper end-to-end 73 | // Webmention tests, but that's the way 74 | // things are at the moment. 75 | setTimeout.bind(undefined, this.callback, 500)); 76 | }, 77 | 'it works': function(err) { 78 | assert.ifError(err); 79 | }, 80 | 'it returns 202 Accepted': function(err, res) { 81 | assert.equal(res.statusCode, 202); 82 | } 83 | }, 84 | 'and we HTTP POST to /jobs/submit with invalid JSON': { 85 | topic: function(app) { 86 | httputil.post('/jobs/submit', '{lol syntax}', this.callback); 87 | }, 88 | 'it works': function(err) { 89 | assert.ifError(err); 90 | }, 91 | 'it returns 400 Bad Request': function(err, res) { 92 | assert.equal(res.statusCode, 400); 93 | } 94 | 95 | }, 96 | 'and we HTTP POST to /jobs/submit with an empty body': { 97 | topic: function(app) { 98 | httputil.post('/jobs/submit', '', this.callback); 99 | }, 100 | 'it works': function(err) { 101 | assert.ifError(err); 102 | }, 103 | 'it returns 400 Bad Request': function(err, res) { 104 | assert.equal(res.statusCode, 400); 105 | } 106 | 107 | }, 108 | 'and we HTTP POST to /jobs/submit without a URL parameter': { 109 | topic: function(app) { 110 | httputil.postJSON('/jobs/submit', {urlll: 'http://typos.com'}, this.callback); 111 | }, 112 | 'it works': function(err) { 113 | assert.ifError(err); 114 | }, 115 | 'it returns 400 Bad Request': function(err, res) { 116 | assert.equal(res.statusCode, 400); 117 | } 118 | } 119 | }) 120 | } 121 | }).export(module); 122 | -------------------------------------------------------------------------------- /test/whitelist-test.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | var vows = require('perjury'), 26 | assert = vows.assert, 27 | express = require('express'), 28 | path = require('path'), 29 | httputil = require('./lib/http'), 30 | apputil = require('./lib/app'), 31 | wrapAppSetup = apputil.wrapAppSetup; 32 | 33 | function postToSubmit(port, key, fn) { 34 | var obj = { 35 | topic: function(app) { 36 | httputil.postJSON(port, '/jobs/submit', 37 | { 38 | url: 'http://localhost:17140/h-feed-with-h-entries.html' 39 | }, 40 | // We set a timeout because otherwise the 41 | // response handler returns 202 Accepted 42 | // immediately, Perjury finishes the rest 43 | // of the tests and exits, and the rest of 44 | // the response handler doesn't have time 45 | // to run. 46 | // 47 | // This is obviously a dirty hack because 48 | // we don't have proper end-to-end 49 | // Webmention tests, but that's the way 50 | // things are at the moment. 51 | setTimeout.bind(undefined, this.callback, 500)); 52 | }, 53 | 'it works': function(err) { 54 | assert.ifError(err); 55 | } 56 | }; 57 | 58 | obj[key] = fn; 59 | 60 | return obj; 61 | } 62 | 63 | vows.describe('domain whitelist test').addBatch({ 64 | 'When we set up a server to serve posts': { 65 | topic: function() { 66 | var app = express(), 67 | cb = this.callback; 68 | 69 | app.use(express.static(path.join(__dirname, 'data'), { 70 | extensions: ['html'] 71 | })); 72 | 73 | var server = app.listen(17140, function(err) { 74 | cb(err, server); 75 | }); 76 | }, 77 | teardown: function(server) { 78 | if (server && server.close) { 79 | console.log('running whitelist teardown'); 80 | server.close(this.callback); 81 | } 82 | }, 83 | 'it works': function(err) { 84 | assert.ifError(err); 85 | }, 86 | 'and we set up the app with notlocalhost in the whitelist': wrapAppSetup({domains: ['notlocalhost']}, { 87 | 'and we HTTP POST to /jobs/submit': postToSubmit(5320, 'it returns 403 Forbidden', function(err, res) { 88 | assert.equal(res.statusCode, 403); 89 | }) 90 | }), 91 | 'and we set up the app with localhost in the whitelist': wrapAppSetup({port: 5321, domains: ['localhost']}, { 92 | 'and we HTTP POST to /jobs/submit': postToSubmit(5321, 'it returns 202 Accepted', function(err, res) { 93 | assert.equal(res.statusCode, 202); 94 | }) 95 | }), 96 | 'and we set up the app with an empty whitelist': wrapAppSetup({port: 5322, domains: []}, { 97 | 'and we HTTP POST to /jobs/submit': postToSubmit(5322, 'it returns 202 Accepted', function(err, res) { 98 | assert.equal(res.statusCode, 202); 99 | }) 100 | }) 101 | } 102 | }).export(module); 103 | -------------------------------------------------------------------------------- /test/z-webmention-test.js: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2017 AJ Jordan . 4 | 5 | This file is part of lazymention. 6 | 7 | lazymention is free software: you can redistribute it and/or modify it 8 | under the terms of the GNU Affero General Public License as published 9 | by the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | lazymention is distributed in the hope that it will be useful, but 13 | WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 15 | Affero General Public License for more details. 16 | 17 | You should have received a copy of the GNU Affero General Public 18 | License along with lazymention. If not, see 19 | . 20 | 21 | */ 22 | 23 | 'use strict'; 24 | 25 | /* 26 | 27 | Yes, this file starts with a z. This is so that this test is ordered 28 | the absolute last in the test suite. 29 | 30 | The reason we need to do this is because it mucks with the global 31 | state by mocking out the `send-webmention` module with a Sinon 32 | spy. That bit of state _leaks_ out of the test and into the 33 | environment, where it's hit by other tests trying to fire 34 | callbacks. This means that a *completely separate test* will actually 35 | jump into this test by calling its Perjury callback, and this does in 36 | fact happen when the ordering is right. So we go with the cheesy 37 | solution and simply (vaguely) guarantee that it's ordered last, so 38 | everybody else is done with the global environment by the time we go 39 | and fuck it all up with this terrifying hellscape of funhouse mirrors 40 | and scary clowns. 41 | 42 | Yes, this is a god-awful design. Yes, I am quite ashamed of it. Yes, I 43 | plan to fix it up eventually. No, I don't have time right now. 44 | 45 | */ 46 | 47 | var vows = require('perjury'), 48 | assert = vows.assert, 49 | mockFs = require('mock-fs'), 50 | proxyquire = require('proxyquire'), 51 | sinon = require('sinon'), 52 | noopLog = require('./lib/log'), 53 | persistenceutil = require('./lib/persistence'), 54 | db = require('../dist/persistence')('/tmp')(noopLog), 55 | wrapFsMocks = persistenceutil.wrapFsMocks, 56 | data = { 57 | singleLink: 'So cute!', 58 | multipleLinks: 'Even cuter! I love cats too!', 59 | noHref: 'It\'s yikes-worthy!', 60 | noLinks: 'I have absolutely no links at all.' 61 | }; 62 | 63 | var clock; 64 | 65 | vows.describe('Webmention module').addBatch({ 66 | 'When we require the module with all our mocks': { 67 | topic: function() { 68 | // XXX is this coupling too much to implementation? 69 | var spy = sinon.spy(function(source, destination, cb) { 70 | cb(undefined, {success: true}); 71 | }), 72 | module = proxyquire('../dist/webmention', { 73 | 'send-webmention': spy 74 | }); 75 | 76 | clock = sinon.useFakeTimers(150 * 1000); 77 | 78 | return [spy, module]; 79 | }, 80 | teardown: function() { 81 | return clock.restore(); 82 | }, 83 | 'it works': function(err) { 84 | assert.ifError(err); 85 | }, 86 | 'it exports a factory function': function(err, webmention) { 87 | assert.isFunction(webmention[1]); 88 | }, 89 | 'and we create a Webmention sender': { 90 | topic: function(fns) { 91 | return [fns[0], fns[1](noopLog, db)]; 92 | }, 93 | 'it works': function(err) { 94 | assert.ifError(err); 95 | }, 96 | 'we get a function back': function(err, webmention) { 97 | assert.isFunction(webmention[1]); 98 | }, 99 | 'and we set up persistence mocks': wrapFsMocks({ 100 | 'and we call the module with a post': { 101 | topic: function(fns) { 102 | var webmention = fns[1], 103 | cb = this.callback; 104 | 105 | webmention('http://example.com/socute', 106 | 100, 107 | data.singleLink, 108 | function(err) { 109 | cb(err, fns); 110 | }); 111 | }, 112 | 'it works': function(err) { 113 | assert.ifError(err); 114 | }, 115 | 'the spy was called': function(err, fns) { 116 | var spy = fns[0]; 117 | assert.isTrue(spy.calledOnce); 118 | // XXX assert arguments 119 | }, 120 | 'and we call it with the same data': { 121 | topic: function(fns) { 122 | var webmention = fns[1], 123 | cb = this.callback; 124 | 125 | webmention('http://example.com/socute', 126 | // Note: these are smaller because JS dates are in milliseconds but we're passing seconds 127 | 100, 128 | data.singleLink, 129 | function(err) { 130 | cb(err, fns); 131 | }); 132 | }, 133 | 'it works': function(err) { 134 | assert.ifError(err); 135 | }, 136 | 'the spy wasn\'t called again': function(err, fns) { 137 | var spy = fns[0]; 138 | assert.isTrue(spy.calledOnce); 139 | }, 140 | 'and we call it with a newer timestamp': { 141 | topic: function(fns) { 142 | var webmention = fns[1], 143 | cb = this.callback; 144 | 145 | // This shouldn't matter, but just in case, we set the clock to be past the edited timestamp 146 | clock.tick(100 * 1000); 147 | 148 | webmention('http://example.com/socute', 149 | 200, 150 | data.singleLink, 151 | function(err) { 152 | cb(err, fns); 153 | }); 154 | }, 155 | teardown: function() { 156 | return clock.tick(-100 * 1000); 157 | }, 158 | 'it works': function(err) { 159 | assert.ifError(err); 160 | }, 161 | 'the spy was called a second time': function(err, fns) { 162 | var spy = fns[0]; 163 | assert.isTrue(spy.calledTwice); 164 | // XXX assert arguments 165 | }, 166 | // XXX find a way to not nest this so deeply - it 167 | // has to be this way currently so the Sinon spy is 168 | // called in the right order 169 | 'and we call it with a post with multiple links': { 170 | topic: function(fns) { 171 | var webmention = fns[1], 172 | cb = this.callback; 173 | 174 | webmention('http://example.com/morecuteness', 175 | 200, 176 | data.multipleLinks, 177 | function(err) { 178 | cb(err, fns); 179 | }); 180 | }, 181 | 'it works': function(err) { 182 | assert.ifError(err); 183 | }, 184 | 'the spy was called two more times': function(err, fns) { 185 | var spy = fns[0]; 186 | assert.equal(spy.callCount, 4); 187 | // XXX args 188 | }, 189 | 'and we call the module with a post that has a blank ': { 190 | topic: function(fns) { 191 | var webmention = fns[1], 192 | cb = this.callback; 193 | 194 | webmention('http://malformed.technology/everything_is_terrible', 195 | 200, 196 | data.noHref, 197 | function(err) { 198 | cb(err, fns); 199 | }); 200 | }, 201 | 'it works': function(err) { 202 | assert.ifError(err); 203 | }, 204 | 'the spy wasn\'t called again': function(err, fns) { 205 | var spy = fns[0]; 206 | assert.equal(spy.callCount, 4); 207 | // XXX args 208 | } 209 | }, 210 | 'and we call the module with a post that has no links at all': { 211 | topic: function(fns) { 212 | var webmention = fns[1], 213 | cb = this.callback; 214 | 215 | webmention('http://ordinary.net/bland_post', 216 | 200, 217 | data.noLinks, 218 | function(err) { 219 | cb(err, fns); 220 | }); 221 | }, 222 | 'it works': function(err) { 223 | assert.ifError(err); 224 | }, 225 | 'the spy wasn\'t called again': function(err, fns) { 226 | var spy = fns[0]; 227 | assert.equal(spy.callCount, 4); 228 | // XXX args 229 | } 230 | } 231 | } 232 | } 233 | } 234 | } 235 | }) 236 | } 237 | } 238 | }).export(module); 239 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "./dist/", 4 | "sourceMap": true, 5 | "strictNullChecks": true, 6 | "module": "commonjs", 7 | "target": "es5", 8 | "allowJs": true 9 | }, 10 | "include": [ 11 | "./lib/" 12 | ] 13 | } 14 | --------------------------------------------------------------------------------