├── .github └── workflows │ └── node.js.yml ├── .gitignore ├── .nvmrc ├── LICENSE ├── README.md ├── handler.js ├── package-lock.json ├── package.json ├── serverless.yml ├── src ├── dao │ ├── key.js │ └── user.js ├── lib │ ├── crypto.js │ ├── delay.js │ ├── http.js │ └── verify.js └── service │ ├── dynamodb.js │ ├── email.js │ └── twilio.js └── test ├── integration ├── dynamodb.spec.js └── rest.spec.js └── unit ├── crypto.spec.js ├── delay.spec.js ├── email.spec.js ├── http.spec.js ├── key.spec.js ├── twilio.spec.js ├── user.spec.js └── verify.spec.js /.github/workflows/node.js.yml: -------------------------------------------------------------------------------- 1 | name: Node.js CI 2 | 3 | on: push 4 | 5 | env: 6 | SERVERLESS_ACCESS_KEY: ${{ secrets.SERVERLESS_ACCESS_KEY }} 7 | 8 | jobs: 9 | 10 | build: 11 | runs-on: ubuntu-22.04 12 | strategy: 13 | matrix: 14 | node-version: [16.x] 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Use Node.js ${{ matrix.node-version }} 18 | uses: actions/setup-node@v3 19 | with: 20 | node-version: ${{ matrix.node-version }} 21 | - run: npm ci 22 | - run: npm run build --if-present 23 | - run: npm test 24 | 25 | deploy: 26 | needs: build 27 | if: ${{ github.ref == 'refs/heads/master' }} 28 | runs-on: ubuntu-22.04 29 | strategy: 30 | matrix: 31 | node-version: [16.x] 32 | steps: 33 | - uses: actions/checkout@v3 34 | - name: Use Node.js ${{ matrix.node-version }} 35 | uses: actions/setup-node@v3 36 | with: 37 | node-version: ${{ matrix.node-version }} 38 | - run: npm ci 39 | - name: serverless deploy 40 | uses: serverless/github-action@v3.1 41 | with: 42 | args: deploy 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 16 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # photon-keyserver ![Node.js CI](https://github.com/photon-sdk/photon-keyserver/workflows/Node.js%20CI/badge.svg?branch=master) 2 | 2FA server for encrypted private key backup 3 | 4 | ## Usage & API docs 5 | 6 | The easiest way to consume this service is to use the client library [photon-sdk/photon-lib](https://github.com/photon-sdk/photon-lib). 7 | 8 | If you want to use the REST api directly, the [keyserver](https://github.com/photon-sdk/photon-lib/blob/master/src/keyserver.js) client module provides some good documentation. More examples can be found in the [integration tests](https://github.com/photon-sdk/photon-keyserver/blob/master/test/integration/rest.spec.js). 9 | 10 | ## Setup 11 | 12 | ```bash 13 | nvm use 14 | ``` 15 | 16 | ```bash 17 | npm install 18 | ``` 19 | 20 | ## Run tests 21 | 22 | ```bash 23 | npm test 24 | ``` 25 | 26 | ## Start local instance 27 | 28 | ```bash 29 | npm start 30 | ``` 31 | -------------------------------------------------------------------------------- /handler.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview implements functions to handle http requests 3 | */ 4 | 5 | 'use strict' 6 | 7 | const keyDao = require('./src/dao/key') 8 | const userDao = require('./src/dao/user') 9 | const email = require('./src/service/email') 10 | const twilio = require('./src/service/twilio') 11 | const dynamo = require('./src/service/dynamodb') 12 | const { path, body, auth, response, error } = require('./src/lib/http') 13 | const { ops, isOp, isPhone, isEmail, isCode, isId, isPin } = require('./src/lib/verify') 14 | 15 | dynamo.init() 16 | twilio.init() 17 | email.init() 18 | 19 | // 20 | // Key functions 21 | // 22 | 23 | exports.createKey = async (event) => { 24 | try { 25 | const { pin } = body(event) 26 | if (!isPin(pin)) { 27 | return error(400, 'Invalid request') 28 | } 29 | const id = await keyDao.create({ pin }) 30 | return response(201, { id }) 31 | } catch (err) { 32 | return error(500, 'Error creating key', err) 33 | } 34 | } 35 | 36 | exports.getKey = async (event) => { 37 | try { 38 | const pin = auth(event).pass 39 | const { keyId } = path(event) 40 | if (!isId(keyId) || !isPin(pin)) { 41 | return error(400, 'Invalid request') 42 | } 43 | const { key, delay } = await keyDao.get({ id: keyId, pin }) 44 | if (delay) { 45 | return response(429, { message: 'Rate limit until', delay }) 46 | } 47 | if (!key) { 48 | return error(404, 'Invalid params') 49 | } 50 | const { id, encryptionKey } = key 51 | return response(200, { id, encryptionKey }) 52 | } catch (err) { 53 | return error(500, 'Error reading key', err) 54 | } 55 | } 56 | 57 | exports.changePin = async (event) => { 58 | try { 59 | const pin = auth(event).pass 60 | const { keyId } = path(event) 61 | const { newPin } = body(event) 62 | if (!isId(keyId) || !isPin(pin) || !isPin(newPin)) { 63 | return error(400, 'Invalid request') 64 | } 65 | const { success, delay } = await keyDao.changePin({ id: keyId, pin, newPin }) 66 | if (delay) { 67 | return response(429, { message: 'Rate limit until', delay }) 68 | } 69 | if (!success) { 70 | return error(404, 'Invalid params') 71 | } 72 | return response(200, 'Success') 73 | } catch (err) { 74 | return error(500, 'Error changing pin', err) 75 | } 76 | } 77 | 78 | // 79 | // User functions 80 | // 81 | 82 | exports.createUser = async (event) => { 83 | try { 84 | const pin = auth(event).pass 85 | const { keyId } = path(event) 86 | const { userId } = body(event) 87 | if ( 88 | (!isPhone(userId) && !isEmail(userId)) || 89 | !isId(keyId) || 90 | !isPin(pin) 91 | ) { 92 | return error(400, 'Invalid request') 93 | } 94 | const { key, delay } = await keyDao.get({ id: keyId, pin }) 95 | if (delay) { 96 | return response(429, { message: 'Rate limit until', delay }) 97 | } 98 | if (!key) { 99 | return error(404, 'Invalid params') 100 | } 101 | const { salt } = key 102 | const user = await userDao.getVerified({ userId, salt }) 103 | if (user) { 104 | return response(409, 'User id already exists') 105 | } 106 | const code = await userDao.create({ userId, salt }) 107 | if (isPhone(userId)) { 108 | await twilio.send({ userId, code }) 109 | } else { 110 | await email.send({ userId, code }) 111 | } 112 | return response(201, 'Success') 113 | } catch (err) { 114 | return error(500, 'Error creating user', err) 115 | } 116 | } 117 | 118 | exports.verifyUser = async (event) => { 119 | try { 120 | const { keyId, userId } = path(event) 121 | const { code, op, newPin } = body(event) 122 | if ( 123 | (!isPhone(userId) && !isEmail(userId)) || 124 | !isId(keyId) || 125 | !isCode(code) || 126 | !isOp(op) 127 | ) { 128 | return error(400, 'Invalid request') 129 | } 130 | const salt = await keyDao.getSalt({ id: keyId }) 131 | if (!salt) { 132 | return error(404, 'Invalid params') 133 | } 134 | const { success, delay } = await userDao.verify({ userId, salt, code, op }) 135 | if (delay) { 136 | return response(429, { message: 'Rate limit until', delay }) 137 | } 138 | if (!success) { 139 | return error(404, 'Invalid params') 140 | } 141 | if (op === ops.RESET_PIN) { 142 | const { success, delay } = await keyDao.resetPin({ id: keyId, newPin }) 143 | if (delay) { 144 | return response(423, { message: 'Time locked until', delay }) 145 | } 146 | if (!success) { 147 | return error(304, 'Invalid new pin') 148 | } 149 | } 150 | return response(200, 'Success') 151 | } catch (err) { 152 | return error(500, 'Error verifying user', err) 153 | } 154 | } 155 | 156 | exports.resetPin = async (event) => { 157 | try { 158 | const { keyId, userId } = path(event) 159 | if ( 160 | (!isPhone(userId) && !isEmail(userId)) || 161 | !isId(keyId) 162 | ) { 163 | return error(400, 'Invalid request') 164 | } 165 | const salt = await keyDao.getSalt({ id: keyId }) 166 | if (!salt) { 167 | return error(404, 'Invalid params') 168 | } 169 | const code = await userDao.setNewCode({ userId, salt, op: ops.RESET_PIN }) 170 | if (!code) { 171 | return error(404, 'Invalid params') 172 | } 173 | if (isPhone(userId)) { 174 | await twilio.send({ userId, code }) 175 | } else { 176 | await email.send({ userId, code }) 177 | } 178 | return response(200, 'Success') 179 | } catch (err) { 180 | return error(500, 'Error resetting pin', err) 181 | } 182 | } 183 | 184 | exports.removeUser = async (event) => { 185 | try { 186 | const pin = auth(event).pass 187 | const { keyId, userId } = path(event) 188 | if ( 189 | (!isPhone(userId) && !isEmail(userId)) || 190 | !isId(keyId) || 191 | !isPin(pin) 192 | ) { 193 | return error(400, 'Invalid request') 194 | } 195 | const { key, delay } = await keyDao.get({ id: keyId, pin }) 196 | if (delay) { 197 | return response(429, { message: 'Rate limit until', delay }) 198 | } 199 | if (!key) { 200 | return error(404, 'Invalid params') 201 | } 202 | const { salt } = key 203 | await userDao.remove({ userId, salt }) 204 | return response(200, 'Success') 205 | } catch (err) { 206 | return error(500, 'Error deleting user', err) 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "photon-keyserver", 3 | "version": "0.0.1", 4 | "license": "MIT", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/photon-sdk/photon-keyserver.git" 8 | }, 9 | "scripts": { 10 | "postinstall": "sls dynamodb install", 11 | "start": "IS_OFFLINE=true sls offline start", 12 | "test": "npm run test:lint && npm run test:unit && npm run test:ci", 13 | "test:lint": "standard *.js 'src/**/*.js' 'test/**/*.js'", 14 | "test:unit": "mocha test/unit/", 15 | "test:integration": "IS_OFFLINE=true DYNAMODB_TABLE_KEY=photonsdk-keyserver-prod-key DYNAMODB_TABLE_USER=photonsdk-keyserver-prod-user mocha test/integration/", 16 | "test:ci": "npm start & P1=$! && wait-on tcp:3000 && npm run test:integration && kill $P1" 17 | }, 18 | "dependencies": { 19 | "aws-sdk": "^2.1354.0", 20 | "twilio": "^4.9.0", 21 | "uuid": "^9.0.0" 22 | }, 23 | "devDependencies": { 24 | "dynamodb-localhost": "https://github.com/99x/dynamodb-localhost#db30898f8c40932c7177be7b2f1a81360d12876d", 25 | "frisbee": "^3.1.0", 26 | "mocha": "^10.2.0", 27 | "serverless": "^3.29.0", 28 | "serverless-domain-manager": "^6.4.4", 29 | "serverless-dynamodb-local": "^0.2.40", 30 | "serverless-offline": "^12.0.4", 31 | "sinon": "^15.0.3", 32 | "standard": "^17.0.0", 33 | "unexpected": "^13.1.0", 34 | "wait-on": "^7.0.1" 35 | }, 36 | "overrides": { 37 | "serverless-dynamodb-local": { 38 | "dynamodb-localhost": "https://github.com/99x/dynamodb-localhost#db30898f8c40932c7177be7b2f1a81360d12876d" 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /serverless.yml: -------------------------------------------------------------------------------- 1 | service: photonsdk-keyserver 2 | app: photonsdk 3 | org: hasedev 4 | frameworkVersion: '3' 5 | 6 | plugins: 7 | - serverless-domain-manager 8 | - serverless-dynamodb-local 9 | - serverless-offline 10 | 11 | provider: 12 | name: aws 13 | runtime: nodejs16.x 14 | stage: prod 15 | region: eu-central-1 16 | environment: 17 | TWILIO_ACCOUNT_SID: ${param:TWILIO_ACCOUNT_SID} 18 | TWILIO_AUTH_TOKEN: ${param:TWILIO_AUTH_TOKEN} 19 | TWILIO_FROM_NUMBER: ${param:TWILIO_FROM_NUMBER} 20 | SES_FROM_EMAIL: ${param:SES_FROM_EMAIL} 21 | SES_REGION: ${opt:region, self:provider.region} 22 | DYNAMODB_TABLE_KEY: ${self:service}-${opt:stage, self:provider.stage}-key 23 | DYNAMODB_TABLE_USER: ${self:service}-${opt:stage, self:provider.stage}-user 24 | iam: 25 | role: 26 | statements: 27 | - Effect: Allow 28 | Action: 29 | - dynamodb:Query 30 | - dynamodb:Scan 31 | - dynamodb:GetItem 32 | - dynamodb:PutItem 33 | - dynamodb:UpdateItem 34 | - dynamodb:DeleteItem 35 | Resource: 36 | - "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE_KEY}" 37 | - "arn:aws:dynamodb:${opt:region, self:provider.region}:*:table/${self:provider.environment.DYNAMODB_TABLE_USER}" 38 | - Effect: Allow 39 | Action: 40 | - ses:SendEmail 41 | - ses:SendRawEmail 42 | Resource: 43 | - "*" 44 | 45 | functions: 46 | createKey: 47 | handler: handler.createKey 48 | events: 49 | - http: 50 | path: /v2/key 51 | method: post 52 | getKey: 53 | handler: handler.getKey 54 | events: 55 | - http: 56 | path: /v2/key/{keyId} 57 | method: get 58 | changePin: 59 | handler: handler.changePin 60 | events: 61 | - http: 62 | path: /v2/key/{keyId} 63 | method: put 64 | createUser: 65 | handler: handler.createUser 66 | events: 67 | - http: 68 | path: /v2/key/{keyId}/user 69 | method: post 70 | verifyUser: 71 | handler: handler.verifyUser 72 | events: 73 | - http: 74 | path: /v2/key/{keyId}/user/{userId} 75 | method: put 76 | resetPin: 77 | handler: handler.resetPin 78 | events: 79 | - http: 80 | path: /v2/key/{keyId}/user/{userId}/reset 81 | method: get 82 | removeUser: 83 | handler: handler.removeUser 84 | events: 85 | - http: 86 | path: /v2/key/{keyId}/user/{userId} 87 | method: delete 88 | 89 | resources: 90 | Resources: 91 | KeyDynamoDbTable: 92 | Type: 'AWS::DynamoDB::Table' 93 | DeletionPolicy: Retain 94 | Properties: 95 | AttributeDefinitions: 96 | - 97 | AttributeName: id 98 | AttributeType: S 99 | KeySchema: 100 | - 101 | AttributeName: id 102 | KeyType: HASH 103 | BillingMode: PAY_PER_REQUEST 104 | TableName: ${self:provider.environment.DYNAMODB_TABLE_KEY} 105 | UserDynamoDbTable: 106 | Type: 'AWS::DynamoDB::Table' 107 | DeletionPolicy: Retain 108 | Properties: 109 | AttributeDefinitions: 110 | - 111 | AttributeName: id 112 | AttributeType: S 113 | KeySchema: 114 | - 115 | AttributeName: id 116 | KeyType: HASH 117 | BillingMode: PAY_PER_REQUEST 118 | TableName: ${self:provider.environment.DYNAMODB_TABLE_USER} 119 | 120 | custom: 121 | customDomain: 122 | domainName: keys.photonsdk.com 123 | certificateName: '*.photonsdk.com' 124 | basePath: '' 125 | stage: ${self:provider.stage} 126 | createRoute53Record: true 127 | endpointType: 'regional' 128 | securityPolicy: tls_1_2 129 | apiType: rest 130 | autoDomain: false 131 | dynamodb: 132 | stages: 133 | - prod 134 | start: 135 | port: 8000 136 | inMemory: true 137 | heapInitial: 200m 138 | heapMax: 1g 139 | migrate: true 140 | seed: true 141 | convertEmptyValues: true -------------------------------------------------------------------------------- /src/dao/key.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview represents data access object for reading/writing private key documents from the datastore. 3 | */ 4 | 5 | 'use strict' 6 | 7 | const { v4: uuid } = require('uuid') 8 | const { isPin } = require('../lib/verify') 9 | const dynamo = require('../service/dynamodb') 10 | const { generateKey, generateSalt, createHash } = require('../lib/crypto') 11 | const { checkRateLimit, resetRateLimit, checkTimeLock, resetTimeLock } = require('../lib/delay') 12 | 13 | /** 14 | * Database documents have the format: 15 | * { 16 | * id: '550e8400-e29b-11d4-a716-446655440000', // a randomly generated UUID 17 | * encryptionKey: '6eDnFZxXrYKYyfrz33OqBNeSo3aaLilO+R+my4hYM40=', 18 | * pin: 'sxeKxQtdiVDM7y0d1sPE2IFTsJ8XuURrDVOfZ8F7zYg=', // hash of the pin 19 | * salt: 'D5gbqhTTz49Q08T6Y50Cy8ea4fSvcaFzJ2eJOgxX4SA=', // used in pin hashing 20 | * } 21 | */ 22 | const TABLE = process.env.DYNAMODB_TABLE_KEY 23 | 24 | exports.create = async ({ pin }) => { 25 | const id = uuid() 26 | const encryptionKey = await generateKey() 27 | const salt = await generateSalt() 28 | pin = await _hashPin(pin, salt) 29 | const key = { 30 | id, 31 | encryptionKey, 32 | pin, 33 | salt 34 | } 35 | resetTimeLock(key) 36 | resetRateLimit(key) 37 | await dynamo.put(TABLE, key) 38 | return id 39 | } 40 | 41 | exports.getSalt = async ({ id }) => { 42 | const key = await dynamo.get(TABLE, { id }) 43 | return key ? key.salt : null 44 | } 45 | 46 | exports.get = async ({ id, pin }) => { 47 | const { key, delay } = await this._getKeyRateLimited({ id, pin }) 48 | if (!key) { 49 | return { key, delay } 50 | } 51 | await dynamo.put(TABLE, key) 52 | return { key, delay } 53 | } 54 | 55 | exports.changePin = async ({ id, pin, newPin }) => { 56 | const { key, delay } = await this._getKeyRateLimited({ id, pin }) 57 | if (!key) { 58 | return { success: false, delay } 59 | } 60 | key.pin = await _hashPin(newPin, key.salt) 61 | await dynamo.put(TABLE, key) 62 | return { success: true } 63 | } 64 | 65 | exports.resetPin = async ({ id, newPin }) => { 66 | const key = await dynamo.get(TABLE, { id }) 67 | if (!key) { 68 | return { success: false } 69 | } 70 | const delay = checkTimeLock(key) 71 | await dynamo.put(TABLE, key) 72 | if (delay) { 73 | return { success: false, delay } 74 | } 75 | if (!isPin(newPin)) { 76 | return { success: false } 77 | } 78 | key.pin = await _hashPin(newPin, key.salt) 79 | resetTimeLock(key) 80 | await dynamo.put(TABLE, key) 81 | return { success: true } 82 | } 83 | 84 | exports.remove = async ({ id, pin }) => { 85 | const { key, delay } = await this._getKeyRateLimited({ id, pin }) 86 | if (!key) { 87 | return { success: false, delay } 88 | } 89 | await dynamo.remove(TABLE, { id }) 90 | return { success: true } 91 | } 92 | 93 | // 94 | // helper functions 95 | // 96 | 97 | exports._getKeyRateLimited = async ({ id, pin }) => { 98 | const key = await dynamo.get(TABLE, { id }) 99 | if (!key) { 100 | return { key: null } 101 | } 102 | const delay = checkRateLimit(key) 103 | await dynamo.put(TABLE, key) 104 | pin = await _hashPin(pin, key.salt) 105 | if (delay || key.pin !== pin) { 106 | return { key: null, delay } 107 | } 108 | resetRateLimit(key) 109 | return { key } 110 | } 111 | 112 | const _hashPin = async (pin, salt) => { 113 | return pin ? createHash(pin, salt) : null 114 | } 115 | -------------------------------------------------------------------------------- /src/dao/user.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview represents data access object for reading/writing user id documents from the datastore. 3 | */ 4 | 5 | 'use strict' 6 | 7 | const { ops } = require('../lib/verify') 8 | const dynamo = require('../service/dynamodb') 9 | const { generateCode, createHash } = require('../lib/crypto') 10 | const { checkRateLimit, resetRateLimit } = require('../lib/delay') 11 | 12 | /** 13 | * Database documents have the format: 14 | * { 15 | * id: '6Ec52IZrNB+te2YRdpIqVet4zzziz1ypu/iGyPF6DhA=', // hash of userId (with key's salt) 16 | * op: 'verify', // the operation which needs to be verified with a code 17 | * code: '123456', // random 6 char code used to prove ownership 18 | * verified: true, // if the user ID has been verified 19 | * } 20 | */ 21 | const TABLE = process.env.DYNAMODB_TABLE_USER 22 | 23 | exports.create = async ({ userId, salt }) => { 24 | const code = await generateCode() 25 | const id = await createHash(userId, salt) 26 | const user = { 27 | id, 28 | op: ops.VERIFY, 29 | code, 30 | verified: false 31 | } 32 | resetRateLimit(user) 33 | await dynamo.put(TABLE, user) 34 | return code 35 | } 36 | 37 | exports.get = async ({ userId, salt }) => { 38 | const id = await createHash(userId, salt) 39 | return dynamo.get(TABLE, { id }) 40 | } 41 | 42 | exports.getVerified = async ({ userId, salt }) => { 43 | const user = await this.get({ userId, salt }) 44 | if (!user || !user.verified) { 45 | return null 46 | } 47 | return user 48 | } 49 | 50 | exports.verify = async ({ userId, salt, code, op }) => { 51 | const user = await this.get({ userId, salt }) 52 | if (!user || user.op !== op) { 53 | return { success: false } 54 | } 55 | const delay = checkRateLimit(user) 56 | await dynamo.put(TABLE, user) 57 | if (delay || user.code !== code) { 58 | return { success: false, delay } 59 | } 60 | user.op = null 61 | user.verified = true 62 | user.code = await generateCode() 63 | resetRateLimit(user) 64 | await dynamo.put(TABLE, user) 65 | return { success: true } 66 | } 67 | 68 | exports.setNewCode = async ({ userId, salt, op }) => { 69 | const user = await this.get({ userId, salt }) 70 | if (!user || !user.verified) { 71 | return null 72 | } 73 | user.op = op 74 | user.code = await generateCode() 75 | await dynamo.put(TABLE, user) 76 | return user.code 77 | } 78 | 79 | exports.remove = async ({ userId, salt }) => { 80 | const id = await createHash(userId, salt) 81 | const user = await dynamo.get(TABLE, { id }) 82 | if (!user) { 83 | throw new Error('User id not found') 84 | } 85 | return dynamo.remove(TABLE, { id }) 86 | } 87 | -------------------------------------------------------------------------------- /src/lib/crypto.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview security and cryptography functions 3 | */ 4 | 5 | 'use strict' 6 | 7 | const crypto = require('crypto') 8 | const { promisify } = require('util') 9 | 10 | exports.generateCode = async () => { 11 | const buf = await promisify(crypto.randomBytes)(4) 12 | const str = parseInt(buf.toString('hex'), 16).toString() 13 | return str.substr(str.length - 6).padStart(6, '0') 14 | } 15 | 16 | exports.generateKey = async () => { 17 | const buf = await promisify(crypto.randomBytes)(32) 18 | return buf.toString('base64') 19 | } 20 | 21 | exports.generateSalt = async () => this.generateKey() 22 | 23 | exports.createHash = async (secret, salt) => { 24 | salt = Buffer.from(salt, 'base64') 25 | if (!secret || salt.length !== 32) { 26 | throw new Error('Invalid args') 27 | } 28 | const buf = await promisify(crypto.scrypt)(secret, salt, 32) 29 | return buf.toString('base64') 30 | } 31 | -------------------------------------------------------------------------------- /src/lib/delay.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview implements rate limiting on database documents to mitigate 3 | * brute force attacks. Rate limit attributes can be added to any document 4 | * and must be persisted to be database between requests. 5 | */ 6 | 7 | 'use strict' 8 | 9 | const { isDateISOString } = require('../lib/verify') 10 | 11 | /** 12 | * Database documents have the format: 13 | * { 14 | * lockedUntil: '2020-07-09T03:33:47.980Z', // pin reset is locked until this time 15 | * firstInvalid: '2020-06-09T03:33:47.980Z', // time of first failed verify request 16 | * invalidCount: 3, // the number of failed verify requests (including firstInvalid) 17 | * } 18 | */ 19 | 20 | exports.resetRateLimit = doc => { 21 | doc.firstInvalid = null 22 | doc.invalidCount = 0 23 | } 24 | 25 | exports.checkRateLimit = doc => { 26 | if (!doc.firstInvalid) { 27 | doc.firstInvalid = new Date().toISOString() 28 | } 29 | doc.invalidCount++ 30 | const delay = this._addDays(doc.firstInvalid, 7) // one week 31 | let rateLimit 32 | if (this._isRateLimit(doc.invalidCount) && !this._isDelayOver(delay)) { 33 | rateLimit = true 34 | } else if (this._isRateLimit(doc.invalidCount) && this._isDelayOver(delay)) { 35 | this.resetRateLimit(doc) 36 | rateLimit = false 37 | } else { 38 | rateLimit = false 39 | } 40 | return rateLimit ? delay.toISOString() : null 41 | } 42 | 43 | exports._isRateLimit = invalidCount => invalidCount > 10 // until rate limit is hit 44 | 45 | exports._isDelayOver = delay => delay <= new Date() 46 | 47 | exports._addDays = (date, days) => { 48 | if (!isDateISOString(date) || !Number.isInteger(days)) { 49 | throw new Error('Invalid args') 50 | } 51 | const result = new Date(date) 52 | result.setDate(result.getDate() + days) 53 | return result 54 | } 55 | 56 | // 57 | // Time lock 58 | // 59 | 60 | exports.resetTimeLock = doc => { 61 | doc.lockedUntil = null 62 | } 63 | 64 | exports.checkTimeLock = doc => { 65 | if (!doc.lockedUntil) { 66 | const now = new Date().toISOString() 67 | doc.lockedUntil = this._addDays(now, 30).toISOString() // one month 68 | } 69 | const isLocked = !this._isDelayOver(new Date(doc.lockedUntil)) 70 | return isLocked ? doc.lockedUntil : null 71 | } 72 | -------------------------------------------------------------------------------- /src/lib/http.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview http request parser functions 3 | */ 4 | 5 | 'use strict' 6 | 7 | exports.body = event => { 8 | return JSON.parse(event.body || '{}') 9 | } 10 | 11 | exports.path = event => { 12 | const path = {} 13 | Object.keys(event.pathParameters || {}).forEach(key => { 14 | path[key] = decodeURIComponent(event.pathParameters[key]) 15 | }) 16 | return path 17 | } 18 | 19 | exports.query = event => { 20 | const query = {} 21 | Object.keys(event.queryStringParameters || {}).forEach(key => { 22 | query[key] = decodeURIComponent(event.queryStringParameters[key]) 23 | }) 24 | return query 25 | } 26 | 27 | exports.auth = event => { 28 | const basic = 'Basic ' 29 | if (!event.headers.Authorization || !event.headers.Authorization.includes(basic)) { 30 | return { user: null, pass: null } 31 | } 32 | const authBase64 = event.headers.Authorization.replace('Basic ', '') 33 | const authStr = Buffer.from(authBase64, 'base64').toString('utf8') 34 | const [user, pass] = authStr.split(':') 35 | return { user, pass } 36 | } 37 | 38 | exports.response = (status, body = {}) => ({ 39 | statusCode: status, 40 | body: JSON.stringify(typeof body === 'string' ? { message: body } : body) 41 | }) 42 | 43 | exports.error = (status, message, err) => { 44 | if (err) { 45 | console.error(err) 46 | } 47 | return this.response(status, message) 48 | } 49 | -------------------------------------------------------------------------------- /src/lib/verify.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview verification functions 3 | */ 4 | 5 | 'use strict' 6 | 7 | exports.ops = Object.freeze({ 8 | VERIFY: 'verify', 9 | RESET_PIN: 'reset-pin' 10 | }) 11 | 12 | exports.isOp = o => { 13 | return Object.values(this.ops).includes(o) 14 | } 15 | 16 | exports.isPhone = o => { 17 | return /^\+[1-9]\d{1,14}$/.test(o) 18 | } 19 | 20 | exports.isEmail = o => { 21 | const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 22 | return re.test(o) 23 | } 24 | 25 | exports.isCode = o => { 26 | return /^\d{6}$/.test(o) 27 | } 28 | 29 | exports.isId = o => { 30 | return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(o) 31 | } 32 | 33 | exports.isPin = o => { 34 | return o ? /^.{4,256}$/.test(o) : false 35 | } 36 | 37 | exports.isDateISOString = o => { 38 | return /^\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)$/.test(o) 39 | } 40 | -------------------------------------------------------------------------------- /src/service/dynamodb.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview the AWS DynamoDB service for storing documents. 3 | */ 4 | 5 | 'use strict' 6 | 7 | const AWS = require('aws-sdk') 8 | 9 | let _client 10 | 11 | exports.init = () => { 12 | let options = {} 13 | if (process.env.IS_OFFLINE) { 14 | options = { 15 | region: 'localhost', 16 | endpoint: 'http://localhost:8000', 17 | accessKeyId: 'akid', 18 | secretAccessKey: 'secret' 19 | } 20 | } 21 | _client = new AWS.DynamoDB.DocumentClient(options) 22 | } 23 | 24 | exports.put = async (TableName, Item) => { 25 | return _client.put({ TableName, Item }).promise() 26 | } 27 | 28 | exports.get = async (TableName, Key) => { 29 | const doc = await _client.get({ TableName, Key }).promise() 30 | return doc.Item || null 31 | } 32 | 33 | exports.remove = async (TableName, Key) => { 34 | return _client.delete({ TableName, Key }).promise() 35 | } 36 | -------------------------------------------------------------------------------- /src/service/email.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview the AWS SES service for sending Email messages. 3 | */ 4 | 5 | 'use strict' 6 | 7 | const AWS = require('aws-sdk') 8 | const { isEmail, isCode } = require('../lib/verify') 9 | 10 | let _client 11 | 12 | exports.init = (clientStub) => { 13 | if (clientStub) { 14 | _client = clientStub 15 | } else if (process.env.IS_OFFLINE) { 16 | _client = { sendEmail: (_, cb) => cb() } 17 | } else { 18 | _client = new AWS.SES({ region: process.env.SES_REGION }) 19 | } 20 | } 21 | 22 | exports.send = async ({ userId, code }) => { 23 | if (!isEmail(userId) || !isCode(code)) { 24 | throw new Error('Invalid args') 25 | } 26 | const options = { 27 | Source: process.env.SES_FROM_EMAIL, 28 | Destination: { 29 | ToAddresses: [userId] 30 | }, 31 | Message: { 32 | Body: { 33 | Text: { 34 | Data: `Your verification code is: ${code}` 35 | } 36 | }, 37 | Subject: { 38 | Data: 'Verify your email address' 39 | } 40 | } 41 | } 42 | return new Promise((resolve, reject) => { 43 | _client.sendEmail(options, (err, data) => { 44 | if (err) { 45 | reject(err) 46 | } else { 47 | resolve(data) 48 | } 49 | }) 50 | }) 51 | } 52 | -------------------------------------------------------------------------------- /src/service/twilio.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileOverview the Twilio service for sending SMS messages. 3 | */ 4 | 5 | 'use strict' 6 | 7 | const twilio = require('twilio') 8 | const { isPhone, isCode } = require('../lib/verify') 9 | 10 | let _client 11 | 12 | exports.init = (clientStub) => { 13 | if (clientStub) { 14 | _client = clientStub 15 | } else if (process.env.IS_OFFLINE) { 16 | _client = { messages: { create: () => {} } } 17 | } else { 18 | const accountSid = process.env.TWILIO_ACCOUNT_SID 19 | const authToken = process.env.TWILIO_AUTH_TOKEN 20 | _client = twilio(accountSid, authToken) 21 | } 22 | } 23 | 24 | exports.send = async ({ userId, code }) => { 25 | if (!isPhone(userId) || !isCode(code)) { 26 | throw new Error('Invalid args') 27 | } 28 | const sms = { 29 | to: userId, 30 | body: `Your verification code is: ${code}`, 31 | from: process.env.TWILIO_FROM_NUMBER 32 | } 33 | return _client.messages.create(sms) 34 | } 35 | -------------------------------------------------------------------------------- /test/integration/dynamodb.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const expect = require('unexpected') 6 | const dynamo = require('../../src/service/dynamodb') 7 | 8 | describe('DynamoDB Service integration test', () => { 9 | const TABLE = 'photonsdk-keyserver-prod-key' 10 | 11 | before(async () => { 12 | dynamo.init() 13 | }) 14 | 15 | describe('put', () => { 16 | it('store a new item', async () => { 17 | const response = await dynamo.put(TABLE, { id: 'foo' }) 18 | expect(response, 'to be ok') 19 | }) 20 | 21 | it('overwrite an existing item', async () => { 22 | const response = await dynamo.put(TABLE, { id: 'foo', bar: 'baz' }) 23 | expect(response, 'to be ok') 24 | }) 25 | 26 | it('fail on invalid args', async () => { 27 | await expect(dynamo.put(), 'to be rejected with', /Missing/) 28 | }) 29 | }) 30 | 31 | describe('get', () => { 32 | it('read item by id', async () => { 33 | const item = await dynamo.get(TABLE, { id: 'foo' }) 34 | expect(item.bar, 'to equal', 'baz') 35 | }) 36 | 37 | it('fail on invalid args', async () => { 38 | await expect(dynamo.get(), 'to be rejected with', /Missing/) 39 | }) 40 | }) 41 | 42 | describe('remove', () => { 43 | it('delete item by id', async () => { 44 | const response = await dynamo.remove(TABLE, { id: 'foo' }) 45 | expect(response, 'to be ok') 46 | const item = await dynamo.get(TABLE, { id: 'foo' }) 47 | expect(item, 'to equal', null) 48 | }) 49 | 50 | it('fail on invalid args', async () => { 51 | await expect(dynamo.remove(), 'to be rejected with', /Missing/) 52 | }) 53 | }) 54 | }) 55 | -------------------------------------------------------------------------------- /test/integration/rest.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const Frisbee = require('frisbee') 6 | const expect = require('unexpected') 7 | const keyDao = require('../../src/dao/key') 8 | const userDao = require('../../src/dao/user') 9 | const dynamo = require('../../src/service/dynamodb') 10 | 11 | describe('REST api integration test', () => { 12 | const userId = '+4917512345678' 13 | const pin1 = '1234' 14 | const pin2 = '5678' 15 | let client 16 | let keyId 17 | let code1 18 | let code2 19 | 20 | before(async () => { 21 | dynamo.init() 22 | client = new Frisbee({ 23 | baseURI: 'http://localhost:3000/prod', 24 | headers: { 25 | Accept: 'application/json', 26 | 'Content-Type': 'application/json' 27 | } 28 | }) 29 | }) 30 | 31 | after(async () => { 32 | const { success } = await keyDao.remove({ id: keyId, pin: pin2 }) 33 | expect(success, 'to be', true) 34 | }) 35 | 36 | describe('POST: create new key', () => { 37 | it('handle invalid pin', async () => { 38 | const response = await client.post('/v2/key', { 39 | body: { 40 | pin: '123' 41 | } 42 | }) 43 | expect(response.status, 'to be', 400) 44 | }) 45 | 46 | it('create key document', async () => { 47 | const response = await client.post('/v2/key', { 48 | body: { 49 | pin: pin1 50 | } 51 | }) 52 | keyId = response.body.id 53 | expect(keyId, 'to be ok') 54 | expect(response.status, 'to be', 201) 55 | }) 56 | }) 57 | 58 | describe('GET: read key', () => { 59 | it('return 400 for invalid key id', async () => { 60 | client.auth('', pin1) 61 | const response = await client.get('/v2/key/invalid') 62 | expect(response.status, 'to be', 400) 63 | }) 64 | 65 | it('handle empty auth headers', async () => { 66 | client.auth() 67 | const response = await client.get(`/v2/key/${keyId}`) 68 | expect(response.status, 'to be', 400) 69 | }) 70 | 71 | it('get 404 for wrong pin', async () => { 72 | client.auth('', pin2) 73 | const response = await client.get(`/v2/key/${keyId}`) 74 | expect(response.status, 'to be', 404) 75 | }) 76 | 77 | it('read encryption key', async () => { 78 | client.auth('', pin1) 79 | const response = await client.get(`/v2/key/${keyId}`) 80 | expect(response.status, 'to be', 200) 81 | const { id, encryptionKey } = response.body 82 | expect(id, 'to be', keyId) 83 | expect(Buffer.from(encryptionKey, 'base64').length, 'to be', 32) 84 | }) 85 | }) 86 | 87 | describe('PUT: change pin', () => { 88 | it('return 400 for invalid key id', async () => { 89 | client.auth('', pin1) 90 | const response = await client.put('/v2/key/invalid', { 91 | body: { 92 | newPin: pin2 93 | } 94 | }) 95 | expect(response.status, 'to be', 400) 96 | }) 97 | 98 | it('handle invalid pin', async () => { 99 | client.auth('', '123') 100 | const response = await client.put(`/v2/key/${keyId}`, { 101 | body: { 102 | newPin: pin2 103 | } 104 | }) 105 | expect(response.status, 'to be', 400) 106 | }) 107 | 108 | it('handle invalid new pin', async () => { 109 | client.auth('', pin1) 110 | const response = await client.put(`/v2/key/${keyId}`, { 111 | body: { 112 | newPin: '567' 113 | } 114 | }) 115 | expect(response.status, 'to be', 400) 116 | }) 117 | 118 | it('should not find with wrong pin', async () => { 119 | client.auth('', pin2) 120 | const response = await client.put(`/v2/key/${keyId}`, { 121 | body: { 122 | newPin: pin2 123 | } 124 | }) 125 | expect(response.status, 'to be', 404) 126 | }) 127 | 128 | it('change to another pin', async () => { 129 | client.auth('', pin1) 130 | const response = await client.put(`/v2/key/${keyId}`, { 131 | body: { 132 | newPin: pin2 133 | } 134 | }) 135 | expect(response.status, 'to be', 200) 136 | }) 137 | }) 138 | 139 | describe('GET: read key with new pin', () => { 140 | it('old pin should not work anymore', async () => { 141 | client.auth('', pin1) 142 | const response = await client.get(`/v2/key/${keyId}`) 143 | expect(response.status, 'to be', 404) 144 | }) 145 | 146 | it('read key with new pin', async () => { 147 | client.auth('', pin2) 148 | const response = await client.get(`/v2/key/${keyId}`) 149 | expect(response.status, 'to be', 200) 150 | expect(response.body.encryptionKey, 'to be ok') 151 | }) 152 | }) 153 | 154 | describe('POST: create new user', () => { 155 | it('return 400 for invalid key id', async () => { 156 | client.auth('', pin2) 157 | const response = await client.post('/v2/key/invalid/user', { 158 | body: { 159 | userId 160 | } 161 | }) 162 | expect(response.status, 'to be', 400) 163 | }) 164 | 165 | it('return 400 for invalid user id', async () => { 166 | client.auth('', pin2) 167 | const response = await client.post(`/v2/key/${keyId}/user`, { 168 | body: { 169 | userId: 'invalid' 170 | } 171 | }) 172 | expect(response.status, 'to be', 400) 173 | }) 174 | 175 | it('return 400 for invalid pin', async () => { 176 | client.auth('', '') 177 | const response = await client.post(`/v2/key/${keyId}/user`, { 178 | body: { 179 | userId 180 | } 181 | }) 182 | expect(response.status, 'to be', 400) 183 | }) 184 | 185 | it('old pin should not work anymore', async () => { 186 | client.auth('', pin1) 187 | const response = await client.post(`/v2/key/${keyId}/user`, { 188 | body: { 189 | userId 190 | } 191 | }) 192 | expect(response.status, 'to be', 404) 193 | }) 194 | 195 | it('should create new user', async () => { 196 | client.auth('', pin2) 197 | const response = await client.post(`/v2/key/${keyId}/user`, { 198 | body: { 199 | userId 200 | } 201 | }) 202 | expect(response.status, 'to be', 201) 203 | }) 204 | 205 | after(async () => { 206 | const salt = await keyDao.getSalt({ id: keyId }) 207 | code1 = (await userDao.get({ userId, salt })).code 208 | expect(code1, 'to be ok') 209 | }) 210 | }) 211 | 212 | describe('PUT: verify new user', () => { 213 | it('return 400 for invalid user id', async () => { 214 | const response = await client.put(`/v2/key/${keyId}/user/invalid`, { 215 | body: { 216 | code: code1, 217 | op: 'verify' 218 | } 219 | }) 220 | expect(response.status, 'to be', 400) 221 | }) 222 | 223 | it('return 400 for invalid key id', async () => { 224 | const response = await client.put(`/v2/key/invalid/user/${userId}`, { 225 | body: { 226 | code: code1, 227 | op: 'verify' 228 | } 229 | }) 230 | expect(response.status, 'to be', 400) 231 | }) 232 | 233 | it('return 400 for invalid code', async () => { 234 | const response = await client.put(`/v2/key/${keyId}/user/${userId}`, { 235 | body: { 236 | code: 'invalid', 237 | op: 'verify' 238 | } 239 | }) 240 | expect(response.status, 'to be', 400) 241 | }) 242 | 243 | it('return 400 for invalid op', async () => { 244 | const response = await client.put(`/v2/key/${keyId}/user/${userId}`, { 245 | body: { 246 | code: code1, 247 | op: 'invalid-op' 248 | } 249 | }) 250 | expect(response.status, 'to be', 400) 251 | }) 252 | 253 | it('return 404 for incorrect code', async () => { 254 | const response = await client.put(`/v2/key/${keyId}/user/${userId}`, { 255 | body: { 256 | code: '000000', 257 | op: 'verify' 258 | } 259 | }) 260 | expect(response.status, 'to be', 404) 261 | }) 262 | 263 | it('verify user with correct op', async () => { 264 | const response = await client.put(`/v2/key/${keyId}/user/${userId}`, { 265 | body: { 266 | code: code1, 267 | op: 'verify' 268 | } 269 | }) 270 | expect(response.status, 'to be', 200) 271 | }) 272 | }) 273 | 274 | describe('POST: create user again', () => { 275 | it('should return 409 if user id already exists', async () => { 276 | client.auth('', pin2) 277 | const response = await client.post(`/v2/key/${keyId}/user`, { 278 | body: { 279 | userId 280 | } 281 | }) 282 | expect(response.status, 'to be', 409) 283 | }) 284 | }) 285 | 286 | describe('GET: reset pin using verified user', () => { 287 | before(() => { 288 | client.auth() 289 | }) 290 | 291 | it('return 400 for invalid key id', async () => { 292 | const response = await client.get(`/v2/key/invalid/user/${userId}/reset`) 293 | expect(response.status, 'to be', 400) 294 | }) 295 | 296 | it('return 400 for invalid user id', async () => { 297 | const response = await client.get(`/v2/key/${keyId}/user/invalid/reset`) 298 | expect(response.status, 'to be', 400) 299 | }) 300 | 301 | it('return 404 for wrong user id', async () => { 302 | const response = await client.get(`/v2/key/${keyId}/user/+4917512345679/reset`) 303 | expect(response.status, 'to be', 404) 304 | }) 305 | 306 | it('should request reset pin', async () => { 307 | const response = await client.get(`/v2/key/${keyId}/user/${userId}/reset`) 308 | expect(response.status, 'to be', 200) 309 | }) 310 | 311 | after(async () => { 312 | const salt = await keyDao.getSalt({ id: keyId }) 313 | code2 = (await userDao.get({ userId, salt })).code 314 | expect(code2, 'to be ok') 315 | expect(code2, 'not to be', code1) 316 | }) 317 | }) 318 | 319 | describe('PUT: verify pin reset', () => { 320 | it('set time lock on key for 30 days', async () => { 321 | const response = await client.put(`/v2/key/${keyId}/user/${userId}`, { 322 | body: { 323 | code: code2, 324 | op: 'reset-pin' 325 | } 326 | }) 327 | expect(response.status, 'to be', 423) 328 | expect(response.body.message, 'to match', /locked until/) 329 | expect(response.body.delay, 'to be ok') 330 | }) 331 | }) 332 | 333 | describe('DELETE: remove user', () => { 334 | it('return 400 for invalid user id', async () => { 335 | client.auth('', pin1) 336 | const response = await client.delete(`/v2/key/${keyId}/user/invalid`) 337 | expect(response.status, 'to be', 400) 338 | }) 339 | 340 | it('return 400 for invalid key id', async () => { 341 | client.auth('', pin1) 342 | const response = await client.delete(`/v2/key/invalid/user/${userId}`) 343 | expect(response.status, 'to be', 400) 344 | }) 345 | 346 | it('return 400 for no pin', async () => { 347 | client.auth() 348 | const response = await client.delete(`/v2/key/${keyId}/user/${userId}`) 349 | expect(response.status, 'to be', 400) 350 | }) 351 | 352 | it('not delete with wrong pin', async () => { 353 | client.auth('', pin1) 354 | const response = await client.delete(`/v2/key/${keyId}/user/${userId}`) 355 | expect(response.status, 'to be', 404) 356 | }) 357 | 358 | it('delete user with correct pin', async () => { 359 | client.auth('', pin2) 360 | const response = await client.delete(`/v2/key/${keyId}/user/${userId}`) 361 | expect(response.status, 'to be', 200) 362 | }) 363 | }) 364 | }) 365 | -------------------------------------------------------------------------------- /test/unit/crypto.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const sinon = require('sinon') 6 | const expect = require('unexpected') 7 | const crypto = require('crypto') 8 | const lib = require('../../src/lib/crypto') 9 | 10 | describe('Crypto Lib unit test', () => { 11 | let sandbox 12 | 13 | beforeEach(() => { 14 | sandbox = sinon.createSandbox() 15 | }) 16 | 17 | afterEach(() => { 18 | sandbox.restore() 19 | }) 20 | 21 | describe('generateCode', () => { 22 | it('returns a random 6 digit string', async () => { 23 | const code = await lib.generateCode() 24 | expect(code, 'to match', /^\d{6}$/) 25 | }) 26 | 27 | it('fail on crypto error', async () => { 28 | sandbox.stub(crypto, 'randomBytes').yields(new Error('boom')) 29 | await expect(lib.generateCode(), 'to be rejected with', 'boom') 30 | }) 31 | }) 32 | 33 | describe('generateKey', () => { 34 | it('returns a random 32 byte base64 encoded string', async () => { 35 | const key = await lib.generateKey() 36 | expect(Buffer.from(key, 'base64').length, 'to be', 32) 37 | }) 38 | 39 | it('fail on crypto error', async () => { 40 | sandbox.stub(crypto, 'randomBytes').yields(new Error('boom')) 41 | await expect(lib.generateKey(), 'to be rejected with', 'boom') 42 | }) 43 | }) 44 | 45 | describe('generateSalt', () => { 46 | it('returns a random 32 byte base64 encoded string', async () => { 47 | const salt = await lib.generateSalt() 48 | expect(Buffer.from(salt, 'base64').length, 'to be', 32) 49 | }) 50 | 51 | it('fail on crypto error', async () => { 52 | sandbox.stub(crypto, 'randomBytes').yields(new Error('boom')) 53 | await expect(lib.generateSalt(), 'to be rejected with', 'boom') 54 | }) 55 | }) 56 | 57 | describe('createHash', () => { 58 | const phone = '+4917512345678' 59 | const salt = 'tOJwVFGDzfUgkYnIqM4wg51oQ5/yZ56w0lE4lA0pIXU=' 60 | 61 | it('creates the same hash', async () => { 62 | const result = 'ImS3Zs1tdXD/1O95aQ8kVvVXNxW1bwSg+Z/ov9WVaEw=' 63 | const hash = await lib.createHash(phone, salt) 64 | expect(hash, 'to equal', result) 65 | }) 66 | 67 | it('fail on crypto error', async () => { 68 | sandbox.stub(crypto, 'scrypt').yields(new Error('boom')) 69 | await expect(lib.createHash(phone, salt), 'to be rejected with', 'boom') 70 | }) 71 | }) 72 | }) 73 | -------------------------------------------------------------------------------- /test/unit/delay.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const expect = require('unexpected') 6 | const { _addDays } = require('../../src/lib/delay') 7 | 8 | describe('Delay Lib unit test', () => { 9 | describe('addDays', () => { 10 | it('add days to ISO date string', () => { 11 | const date = _addDays('2020-06-09T03:33:47.980Z', 2) 12 | expect(date.toISOString(), 'to be', '2020-06-11T03:33:47.980Z') 13 | }) 14 | 15 | it('fail on invalid input', () => { 16 | expect(_addDays.bind(), 'to throw', /Invalid/) 17 | }) 18 | }) 19 | }) 20 | -------------------------------------------------------------------------------- /test/unit/email.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const sinon = require('sinon') 6 | const expect = require('unexpected') 7 | const email = require('../../src/service/email') 8 | 9 | describe('Email Service unit test', () => { 10 | let clientStub 11 | const userId = 'jon.smith@example.com' 12 | const code = '123456' 13 | 14 | beforeEach(() => { 15 | clientStub = { sendEmail: sinon.stub() } 16 | email.init(clientStub) 17 | }) 18 | 19 | describe('send', () => { 20 | it('fail on invalid args', async () => { 21 | await expect(email.send({}), 'to be rejected with', /Invalid/) 22 | }) 23 | 24 | it('fail on email error', async () => { 25 | clientStub.sendEmail.yields(new Error('boom')) 26 | await expect(email.send({ userId, code }), 'to be rejected with', /boom/) 27 | }) 28 | 29 | it('send email message', async () => { 30 | clientStub.sendEmail.yields() 31 | await email.send({ userId, code }) 32 | expect(clientStub.sendEmail.callCount, 'to be', 1) 33 | }) 34 | }) 35 | }) 36 | -------------------------------------------------------------------------------- /test/unit/http.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const sinon = require('sinon') 6 | const expect = require('unexpected') 7 | const http = require('../../src/lib/http') 8 | 9 | describe('HTTP Lib unit test', () => { 10 | let sandbox 11 | 12 | beforeEach(() => { 13 | sandbox = sinon.createSandbox() 14 | }) 15 | 16 | afterEach(() => { 17 | sandbox.restore() 18 | }) 19 | 20 | describe('body', () => { 21 | it('parse the json body', async () => { 22 | const event = { body: '{"foo":"bar"}' } 23 | const { foo } = http.body(event) 24 | expect(foo, 'to be', 'bar') 25 | }) 26 | 27 | it('return empty object for null', async () => { 28 | const event = { body: null } 29 | const body = http.body(event) 30 | expect(body, 'to equal', {}) 31 | }) 32 | }) 33 | 34 | describe('path', () => { 35 | it('parse the path parameters', async () => { 36 | const event = { pathParameters: { foo: '%2B123' } } 37 | const { foo } = http.path(event) 38 | expect(foo, 'to be', '+123') 39 | }) 40 | 41 | it('return empty object for null', async () => { 42 | const event = { pathParameters: null } 43 | const path = http.path(event) 44 | expect(path, 'to equal', {}) 45 | }) 46 | }) 47 | 48 | describe('query', () => { 49 | it('parse the query parameters', async () => { 50 | const event = { queryStringParameters: { foo: '%2B123' } } 51 | const { foo } = http.query(event) 52 | expect(foo, 'to be', '+123') 53 | }) 54 | 55 | it('return empty object for null', async () => { 56 | const event = { queryStringParameters: null } 57 | const query = http.query(event) 58 | expect(query, 'to equal', {}) 59 | }) 60 | }) 61 | 62 | describe('auth', () => { 63 | it('parse the auth parameters', async () => { 64 | const event = { headers: { Authorization: 'Basic dXNlcjoxMjM0' } } 65 | const { user, pass } = http.auth(event) 66 | expect(user, 'to be', 'user') 67 | expect(pass, 'to be', '1234') 68 | }) 69 | 70 | it('return empty object for null', async () => { 71 | const event = { headers: {} } 72 | const { user, pass } = http.auth(event) 73 | expect(user, 'to be', null) 74 | expect(pass, 'to be', null) 75 | }) 76 | }) 77 | 78 | describe('response', () => { 79 | it('return stringified json response', async () => { 80 | const res = http.response(200, { foo: 'bar' }) 81 | expect(res.statusCode, 'to be', 200) 82 | expect(res.body, 'to be', '{"foo":"bar"}') 83 | }) 84 | 85 | it('return wrap string message in json response', async () => { 86 | const res = http.response(200, 'foo') 87 | expect(res.statusCode, 'to be', 200) 88 | expect(res.body, 'to be', '{"message":"foo"}') 89 | }) 90 | 91 | it('return empty response object for null', async () => { 92 | const res = http.response(200) 93 | expect(res.statusCode, 'to be', 200) 94 | expect(res.body, 'to be', '{}') 95 | }) 96 | }) 97 | 98 | describe('error', () => { 99 | beforeEach(() => { 100 | sandbox.stub(console, 'error') 101 | }) 102 | 103 | it('return response message and log error', async () => { 104 | const res = http.error(500, 'Oh no!', new Error('Boom!')) 105 | expect(res.statusCode, 'to be', 500) 106 | expect(res.body, 'to be', '{"message":"Oh no!"}') 107 | expect(console.error.callCount, 'to be', 1) 108 | }) 109 | 110 | it('return response message and not log error', async () => { 111 | const res = http.error(500, 'Oh no!') 112 | expect(res.statusCode, 'to be', 500) 113 | expect(res.body, 'to be', '{"message":"Oh no!"}') 114 | expect(console.error.callCount, 'to be', 0) 115 | }) 116 | }) 117 | }) 118 | -------------------------------------------------------------------------------- /test/unit/key.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const sinon = require('sinon') 6 | const expect = require('unexpected') 7 | const keyDao = require('../../src/dao/key') 8 | const dynamo = require('../../src/service/dynamodb') 9 | const { checkTimeLock } = require('../../src/lib/delay') 10 | const { isId, isDateISOString } = require('../../src/lib/verify') 11 | 12 | describe('Key DAO unit test', () => { 13 | const id = '8abe1a93-6a9c-490c-bbd5-d7f11a4a9c8f' 14 | const encryptionKey = '0U5oq0rzOGAwJAkKpUxbfJx6uleL6F80q0CJQYmpVYY=' 15 | const pin = '1234' 16 | const newPin = '5678' 17 | const salt = 'KhepHQfa0cNlA88ESlGfVuvWjkvCypkVbVdLseXGpRg=' 18 | const reBase64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/ 19 | let sandbox 20 | 21 | beforeEach(() => { 22 | sandbox = sinon.createSandbox() 23 | sandbox.stub(dynamo) 24 | }) 25 | 26 | afterEach(() => { 27 | sandbox.restore() 28 | }) 29 | 30 | describe('create', () => { 31 | it('fail on dynamo error', async () => { 32 | dynamo.put.rejects(new Error('boom')) 33 | await expect(keyDao.create({ pin }), 'to be rejected with', 'boom') 34 | }) 35 | 36 | it('store a new key (with pin)', async () => { 37 | const id = await keyDao.create({ pin }) 38 | expect(isId(id), 'to be ok') 39 | expect(dynamo.put.callCount, 'to equal', 1) 40 | sinon.assert.calledWith(dynamo.put, sinon.match.any, { 41 | id: sinon.match.string, 42 | encryptionKey: sinon.match(reBase64), 43 | pin: sinon.match(reBase64), 44 | salt: sinon.match(reBase64), 45 | lockedUntil: null, 46 | firstInvalid: null, 47 | invalidCount: 0 48 | }) 49 | }) 50 | 51 | it('store a new key (no pin)', async () => { 52 | const id = await keyDao.create({ pin: undefined }) 53 | expect(isId(id), 'to be ok') 54 | expect(dynamo.put.callCount, 'to equal', 1) 55 | sinon.assert.calledWith(dynamo.put, sinon.match.any, { 56 | id: sinon.match.string, 57 | encryptionKey: sinon.match(reBase64), 58 | pin: null, 59 | salt: sinon.match(reBase64), 60 | lockedUntil: null, 61 | firstInvalid: null, 62 | invalidCount: 0 63 | }) 64 | }) 65 | }) 66 | 67 | describe('getSalt', () => { 68 | it('fail on dynamo error', async () => { 69 | dynamo.get.rejects(new Error('boom')) 70 | await expect(keyDao.getSalt({ id }), 'to be rejected with', 'boom') 71 | }) 72 | 73 | it('return null if no key was found', async () => { 74 | dynamo.get.resolves(null) 75 | const s = await keyDao.getSalt({ id }) 76 | expect(s, 'to be', null) 77 | }) 78 | 79 | it('return the key salt', async () => { 80 | dynamo.get.resolves({ id, salt }) 81 | const s = await keyDao.getSalt({ id }) 82 | expect(s, 'to be', salt) 83 | }) 84 | }) 85 | 86 | describe('get', () => { 87 | it('fail on dynamo error', async () => { 88 | dynamo.get.rejects(new Error('boom')) 89 | await expect(keyDao.get({ id, pin }), 'to be rejected with', 'boom') 90 | }) 91 | 92 | it('key for id not found', async () => { 93 | dynamo.get.resolves(null) 94 | const { key, delay } = await keyDao.get({ id, pin }) 95 | expect(key, 'to be', null) 96 | expect(delay, 'to be', undefined) 97 | expect(dynamo.put.callCount, 'to equal', 0) 98 | }) 99 | 100 | it('return null for wrong pin (rate limit not hit)', async () => { 101 | dynamo.get.resolves({ 102 | id, 103 | encryptionKey, 104 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 105 | salt, 106 | lockedUntil: null, 107 | firstInvalid: null, 108 | invalidCount: 9 109 | }) 110 | const { key, delay } = await keyDao.get({ id, pin: '5678' }) 111 | expect(key, 'to be', null) 112 | expect(delay, 'to be', null) 113 | expect(dynamo.put.callCount, 'to equal', 1) 114 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 115 | firstInvalid: sinon.match.string, 116 | invalidCount: 10 117 | }) 118 | }) 119 | 120 | it('return null for wrong pin (rate limit hit)', async () => { 121 | dynamo.get.resolves({ 122 | id, 123 | encryptionKey, 124 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 125 | salt, 126 | lockedUntil: null, 127 | firstInvalid: null, 128 | invalidCount: 10 129 | }) 130 | const { key, delay } = await keyDao.get({ id, pin: '5678' }) 131 | expect(key, 'to be', null) 132 | expect(isDateISOString(delay), 'to be', true) 133 | expect(dynamo.put.callCount, 'to equal', 1) 134 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 135 | firstInvalid: sinon.match.string, 136 | invalidCount: 11 137 | }) 138 | }) 139 | 140 | it('return null for correct pin (rate limit hit)', async () => { 141 | dynamo.get.resolves({ 142 | id, 143 | encryptionKey, 144 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 145 | salt, 146 | lockedUntil: null, 147 | firstInvalid: null, 148 | invalidCount: 10 149 | }) 150 | const { key, delay } = await keyDao.get({ id, pin }) 151 | expect(key, 'to be', null) 152 | expect(isDateISOString(delay), 'to be', true) 153 | expect(dynamo.put.callCount, 'to equal', 1) 154 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 155 | firstInvalid: sinon.match.string, 156 | invalidCount: 11 157 | }) 158 | }) 159 | 160 | it('reset rate limit after delay is over', async () => { 161 | dynamo.get.resolves({ 162 | id, 163 | encryptionKey, 164 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 165 | salt, 166 | lockedUntil: null, 167 | firstInvalid: '2020-06-01T03:33:47.980Z', 168 | invalidCount: 10 169 | }) 170 | const { key, delay } = await keyDao.get({ id, pin }) 171 | expect(key.id, 'to be', id) 172 | expect(delay, 'to be', undefined) 173 | expect(dynamo.put.callCount, 'to equal', 2) 174 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 175 | firstInvalid: null, 176 | invalidCount: 0 177 | }) 178 | }) 179 | 180 | it('read item by id', async () => { 181 | dynamo.get.resolves({ 182 | id, 183 | encryptionKey, 184 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 185 | salt, 186 | lockedUntil: null, 187 | firstInvalid: null, 188 | invalidCount: 1 189 | }) 190 | const { key, delay } = await keyDao.get({ id, pin }) 191 | expect(key.id, 'to be', id) 192 | expect(delay, 'to be', undefined) 193 | expect(dynamo.put.callCount, 'to equal', 2) 194 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 195 | firstInvalid: null, 196 | invalidCount: 0 197 | }) 198 | }) 199 | }) 200 | 201 | describe('changePin', () => { 202 | it('fail on dynamo error', async () => { 203 | dynamo.get.rejects(new Error('boom')) 204 | await expect(keyDao.changePin({ id, pin, newPin }), 'to be rejected with', 'boom') 205 | }) 206 | 207 | it('key for id not found', async () => { 208 | dynamo.get.resolves(null) 209 | const { success, delay } = await keyDao.changePin({ id, pin, newPin }) 210 | expect(success, 'to be', false) 211 | expect(delay, 'to be', undefined) 212 | expect(dynamo.put.callCount, 'to equal', 0) 213 | }) 214 | 215 | it('return false for wrong pin (rate limit not hit)', async () => { 216 | dynamo.get.resolves({ 217 | id, 218 | encryptionKey, 219 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 220 | salt, 221 | lockedUntil: null, 222 | firstInvalid: null, 223 | invalidCount: 9 224 | }) 225 | const { success, delay } = await keyDao.changePin({ id, pin: '5678', newPin }) 226 | expect(success, 'to be', false) 227 | expect(delay, 'to be', null) 228 | expect(dynamo.put.callCount, 'to equal', 1) 229 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 230 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 231 | firstInvalid: sinon.match.string, 232 | invalidCount: 10 233 | }) 234 | }) 235 | 236 | it('return false for wrong pin (rate limit hit)', async () => { 237 | dynamo.get.resolves({ 238 | id, 239 | encryptionKey, 240 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 241 | salt, 242 | lockedUntil: null, 243 | firstInvalid: null, 244 | invalidCount: 10 245 | }) 246 | const { success, delay } = await keyDao.changePin({ id, pin: '5678', newPin }) 247 | expect(success, 'to be', false) 248 | expect(isDateISOString(delay), 'to be', true) 249 | expect(dynamo.put.callCount, 'to equal', 1) 250 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 251 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 252 | firstInvalid: sinon.match.string, 253 | invalidCount: 11 254 | }) 255 | }) 256 | 257 | it('return false for correct pin (rate limit hit)', async () => { 258 | dynamo.get.resolves({ 259 | id, 260 | encryptionKey, 261 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 262 | salt, 263 | lockedUntil: null, 264 | firstInvalid: null, 265 | invalidCount: 10 266 | }) 267 | const { success, delay } = await keyDao.changePin({ id, pin, newPin }) 268 | expect(success, 'to be', false) 269 | expect(isDateISOString(delay), 'to be', true) 270 | expect(dynamo.put.callCount, 'to equal', 1) 271 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 272 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 273 | firstInvalid: sinon.match.string, 274 | invalidCount: 11 275 | }) 276 | }) 277 | 278 | it('reset rate limit and update pin after delay is over', async () => { 279 | dynamo.get.resolves({ 280 | id, 281 | encryptionKey, 282 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 283 | salt, 284 | lockedUntil: null, 285 | firstInvalid: '2020-06-01T03:33:47.980Z', 286 | invalidCount: 10 287 | }) 288 | const { success, delay } = await keyDao.changePin({ id, pin, newPin }) 289 | expect(success, 'to be', true) 290 | expect(delay, 'to be', undefined) 291 | expect(dynamo.put.callCount, 'to equal', 2) 292 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 293 | pin: 'Y5mBdHc6k0/xo8LlAT7XhjksPbVv/AvG8p8bteoPJxU=', 294 | firstInvalid: null, 295 | invalidCount: 0 296 | }) 297 | }) 298 | 299 | it('set empty pin to null', async () => { 300 | dynamo.get.resolves({ 301 | id, 302 | encryptionKey, 303 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 304 | salt, 305 | lockedUntil: null, 306 | firstInvalid: null, 307 | invalidCount: 1 308 | }) 309 | const { success, delay } = await keyDao.changePin({ id, pin, newPin: '' }) 310 | expect(success, 'to be', true) 311 | expect(delay, 'to be', undefined) 312 | expect(dynamo.put.callCount, 'to equal', 2) 313 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 314 | pin: null, 315 | firstInvalid: null, 316 | invalidCount: 0 317 | }) 318 | }) 319 | }) 320 | 321 | describe('resetPin', () => { 322 | it('fail on dynamo error', async () => { 323 | dynamo.get.rejects(new Error('boom')) 324 | await expect(keyDao.resetPin({ id, newPin }), 'to be rejected with', 'boom') 325 | }) 326 | 327 | it('key for id not found', async () => { 328 | dynamo.get.resolves(null) 329 | const { success, delay } = await keyDao.resetPin({ id, newPin }) 330 | expect(success, 'to be', false) 331 | expect(delay, 'to be', undefined) 332 | expect(dynamo.put.callCount, 'to equal', 0) 333 | }) 334 | 335 | it('return false for first request (time lock not set)', async () => { 336 | dynamo.get.resolves({ 337 | id, 338 | encryptionKey, 339 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 340 | salt, 341 | lockedUntil: null, 342 | firstInvalid: null, 343 | invalidCount: 9 344 | }) 345 | const { success, delay } = await keyDao.resetPin({ id, newPin }) 346 | expect(success, 'to be', false) 347 | expect(isDateISOString(delay), 'to be', true) 348 | expect(dynamo.put.callCount, 'to equal', 1) 349 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 350 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 351 | lockedUntil: sinon.match.string, 352 | firstInvalid: null, 353 | invalidCount: 9 354 | }) 355 | }) 356 | 357 | it('return false for second request (time lock already set)', async () => { 358 | const key = { 359 | id, 360 | encryptionKey, 361 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 362 | salt, 363 | lockedUntil: null, 364 | firstInvalid: null, 365 | invalidCount: 9 366 | } 367 | checkTimeLock(key) 368 | expect(isDateISOString(key.lockedUntil), 'to be', true) 369 | dynamo.get.resolves(key) 370 | await new Promise(resolve => setTimeout(resolve, 10)) 371 | const { success, delay } = await keyDao.resetPin({ id, newPin }) 372 | expect(success, 'to be', false) 373 | expect(isDateISOString(delay), 'to be', true) 374 | expect(dynamo.put.callCount, 'to equal', 1) 375 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 376 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 377 | lockedUntil: key.lockedUntil, 378 | firstInvalid: null, 379 | invalidCount: 9 380 | }) 381 | }) 382 | 383 | it('should not accept invalid new pin', async () => { 384 | dynamo.get.resolves({ 385 | id, 386 | encryptionKey, 387 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 388 | salt, 389 | lockedUntil: '2020-06-01T03:33:47.980Z', 390 | firstInvalid: null, 391 | invalidCount: 10 392 | }) 393 | const { success, delay } = await keyDao.resetPin({ id, newPin: '567' }) 394 | expect(success, 'to be', false) 395 | expect(delay, 'to be', undefined) 396 | expect(dynamo.put.callCount, 'to equal', 1) 397 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 398 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 399 | lockedUntil: '2020-06-01T03:33:47.980Z', 400 | firstInvalid: null, 401 | invalidCount: 10 402 | }) 403 | }) 404 | 405 | it('reset time lock and update pin after delay', async () => { 406 | dynamo.get.resolves({ 407 | id, 408 | encryptionKey, 409 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 410 | salt, 411 | lockedUntil: '2020-06-01T03:33:47.980Z', 412 | firstInvalid: null, 413 | invalidCount: 10 414 | }) 415 | const { success, delay } = await keyDao.resetPin({ id, newPin }) 416 | expect(success, 'to be', true) 417 | expect(delay, 'to be', undefined) 418 | expect(dynamo.put.callCount, 'to equal', 2) 419 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 420 | pin: 'Y5mBdHc6k0/xo8LlAT7XhjksPbVv/AvG8p8bteoPJxU=', 421 | lockedUntil: null, 422 | firstInvalid: null, 423 | invalidCount: 10 424 | }) 425 | }) 426 | }) 427 | 428 | describe('remove', () => { 429 | it('fail on dynamo error', async () => { 430 | dynamo.get.rejects(new Error('boom')) 431 | await expect(keyDao.remove({ id, pin, newPin }), 'to be rejected with', 'boom') 432 | expect(dynamo.remove.callCount, 'to equal', 0) 433 | }) 434 | 435 | it('key for id not found', async () => { 436 | dynamo.get.resolves(null) 437 | const { success, delay } = await keyDao.remove({ id, pin, newPin }) 438 | expect(success, 'to be', false) 439 | expect(delay, 'to be', undefined) 440 | expect(dynamo.put.callCount, 'to equal', 0) 441 | expect(dynamo.remove.callCount, 'to equal', 0) 442 | }) 443 | 444 | it('return false for wrong pin (rate limit not hit)', async () => { 445 | dynamo.get.resolves({ 446 | id, 447 | encryptionKey, 448 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 449 | salt, 450 | lockedUntil: null, 451 | firstInvalid: null, 452 | invalidCount: 9 453 | }) 454 | const { success, delay } = await keyDao.remove({ id, pin: '5678', newPin }) 455 | expect(success, 'to be', false) 456 | expect(delay, 'to be', null) 457 | expect(dynamo.put.callCount, 'to equal', 1) 458 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 459 | firstInvalid: sinon.match.string, 460 | invalidCount: 10 461 | }) 462 | expect(dynamo.remove.callCount, 'to equal', 0) 463 | }) 464 | 465 | it('return false for wrong pin (rate limit hit)', async () => { 466 | dynamo.get.resolves({ 467 | id, 468 | encryptionKey, 469 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 470 | salt, 471 | lockedUntil: null, 472 | firstInvalid: null, 473 | invalidCount: 10 474 | }) 475 | const { success, delay } = await keyDao.remove({ id, pin: '5678', newPin }) 476 | expect(success, 'to be', false) 477 | expect(isDateISOString(delay), 'to be', true) 478 | expect(dynamo.put.callCount, 'to equal', 1) 479 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 480 | firstInvalid: sinon.match.string, 481 | invalidCount: 11 482 | }) 483 | expect(dynamo.remove.callCount, 'to equal', 0) 484 | }) 485 | 486 | it('return false for correct pin (rate limit hit)', async () => { 487 | dynamo.get.resolves({ 488 | id, 489 | encryptionKey, 490 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 491 | salt, 492 | lockedUntil: null, 493 | firstInvalid: null, 494 | invalidCount: 10 495 | }) 496 | const { success, delay } = await keyDao.remove({ id, pin, newPin }) 497 | expect(success, 'to be', false) 498 | expect(isDateISOString(delay), 'to be', true) 499 | expect(dynamo.put.callCount, 'to equal', 1) 500 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 501 | firstInvalid: sinon.match.string, 502 | invalidCount: 11 503 | }) 504 | expect(dynamo.remove.callCount, 'to equal', 0) 505 | }) 506 | 507 | it('reset rate limit after delay is over', async () => { 508 | dynamo.get.resolves({ 509 | id, 510 | encryptionKey, 511 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 512 | salt, 513 | lockedUntil: null, 514 | firstInvalid: '2020-06-01T03:33:47.980Z', 515 | invalidCount: 10 516 | }) 517 | const { success, delay } = await keyDao.remove({ id, pin, newPin }) 518 | expect(success, 'to be', true) 519 | expect(delay, 'to be', undefined) 520 | expect(dynamo.put.callCount, 'to equal', 1) 521 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 522 | firstInvalid: null, 523 | invalidCount: 0 524 | }) 525 | expect(dynamo.remove.callCount, 'to equal', 1) 526 | }) 527 | 528 | it('delete key from database', async () => { 529 | dynamo.get.resolves({ 530 | id, 531 | encryptionKey, 532 | pin: 'S4ysSX7HTDuI94BavlJV0EG2QKjYfiHseYrJ5J5fIK8=', 533 | salt, 534 | lockedUntil: null, 535 | firstInvalid: null, 536 | invalidCount: 1 537 | }) 538 | const { success, delay } = await keyDao.remove({ id, pin, newPin }) 539 | expect(success, 'to be', true) 540 | expect(delay, 'to be', undefined) 541 | expect(dynamo.put.callCount, 'to equal', 1) 542 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 543 | firstInvalid: null, 544 | invalidCount: 0 545 | }) 546 | expect(dynamo.remove.callCount, 'to equal', 1) 547 | }) 548 | }) 549 | }) 550 | -------------------------------------------------------------------------------- /test/unit/twilio.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const sinon = require('sinon') 6 | const expect = require('unexpected') 7 | const twilio = require('../../src/service/twilio') 8 | 9 | describe('Twilio Service unit test', () => { 10 | let clientStub 11 | const userId = '+4917512345678' 12 | const code = '123456' 13 | 14 | beforeEach(() => { 15 | clientStub = { messages: { create: sinon.stub() } } 16 | twilio.init(clientStub) 17 | }) 18 | 19 | describe('send', () => { 20 | it('fail on invalid args', async () => { 21 | await expect(twilio.send({}), 'to be rejected with', /Invalid/) 22 | }) 23 | 24 | it('fail on twilio error', async () => { 25 | clientStub.messages.create.rejects(new Error('boom')) 26 | await expect(twilio.send({ userId, code }), 'to be rejected with', /boom/) 27 | }) 28 | 29 | it('send sms message', async () => { 30 | await twilio.send({ userId, code }) 31 | expect(clientStub.messages.create.callCount, 'to be', 1) 32 | }) 33 | }) 34 | }) 35 | -------------------------------------------------------------------------------- /test/unit/user.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const sinon = require('sinon') 6 | const expect = require('unexpected') 7 | const verify = require('../../src/lib/verify') 8 | const dynamo = require('../../src/service/dynamodb') 9 | const userDao = require('../../src/dao/user') 10 | 11 | describe('User DAO unit test', () => { 12 | let sandbox 13 | const userId = '+4917512345678' 14 | const salt = 'KhepHQfa0cNlA88ESlGfVuvWjkvCypkVbVdLseXGpRg=' 15 | const op = 'verify' 16 | const code1 = '123456' 17 | const code2 = '654321' 18 | 19 | beforeEach(() => { 20 | sandbox = sinon.createSandbox() 21 | sandbox.stub(dynamo) 22 | }) 23 | 24 | afterEach(() => { 25 | sandbox.restore() 26 | }) 27 | 28 | describe('create', () => { 29 | it('fail on dynamo error', async () => { 30 | dynamo.put.rejects(new Error('boom')) 31 | await expect(userDao.create({ userId, salt }), 'to be rejected with', /boom/) 32 | }) 33 | 34 | it('store a new user', async () => { 35 | const code = await userDao.create({ userId, salt }) 36 | expect(code, 'to match', /^\d{6}$/) 37 | expect(dynamo.put.callCount, 'to equal', 1) 38 | sinon.assert.calledWith(dynamo.put, sinon.match.any, { 39 | id: 'lE7uuK/qN3bkm1UPrVFfkA3PVxe48zq1WKGC2BdlkjI=', 40 | op: 'verify', 41 | code, 42 | verified: false, 43 | firstInvalid: null, 44 | invalidCount: 0 45 | }) 46 | }) 47 | }) 48 | 49 | describe('get', () => { 50 | it('fail on invalid args', async () => { 51 | await expect(userDao.get({}), 'to be rejected with', /argument must be/) 52 | }) 53 | 54 | it('return null if no user is found', async () => { 55 | dynamo.get.resolves(null) 56 | const user = await userDao.get({ userId, salt }) 57 | expect(user, 'to be', null) 58 | }) 59 | 60 | it('fail on dynamo get error', async () => { 61 | dynamo.get.rejects(new Error('boom')) 62 | await expect(userDao.get({ userId, salt }), 'to be rejected with', /boom/) 63 | }) 64 | 65 | it('return a user', async () => { 66 | dynamo.get.resolves({ id: 'some-id' }) 67 | const user = await userDao.get({ userId, salt }) 68 | expect(user.id, 'to be', 'some-id') 69 | }) 70 | }) 71 | 72 | describe('getVerified', () => { 73 | it('fail on dynamo get error', async () => { 74 | dynamo.get.rejects(new Error('boom')) 75 | await expect(userDao.getVerified({ userId, salt }), 'to be rejected with', /boom/) 76 | }) 77 | 78 | it('return null if no user is found', async () => { 79 | dynamo.get.resolves(null) 80 | const user = await userDao.getVerified({ userId, salt }) 81 | expect(user, 'to be', null) 82 | }) 83 | 84 | it('return null for unverified user', async () => { 85 | dynamo.get.resolves({ verified: false }) 86 | const user = await userDao.getVerified({ userId, salt }) 87 | expect(user, 'to be', null) 88 | }) 89 | 90 | it('return a verified user', async () => { 91 | dynamo.get.resolves({ verified: true }) 92 | const user = await userDao.getVerified({ userId, salt }) 93 | expect(user, 'to be ok') 94 | }) 95 | }) 96 | 97 | describe('verify', () => { 98 | it('return null if no user is found', async () => { 99 | dynamo.get.resolves(null) 100 | const { success, delay } = await userDao.verify({ userId, salt, op, code: code1 }) 101 | expect(success, 'to be', false) 102 | expect(delay, 'to be', undefined) 103 | expect(dynamo.put.callCount, 'to equal', 0) 104 | }) 105 | 106 | it('not verify a user with incorrect code (no rate limit)', async () => { 107 | dynamo.get.resolves({ 108 | op, 109 | code: code2, 110 | verified: false, 111 | invalidCount: 9 112 | }) 113 | const { success, delay } = await userDao.verify({ userId, salt, op, code: code1 }) 114 | expect(success, 'to be', false) 115 | expect(delay, 'to be', null) 116 | expect(dynamo.put.callCount, 'to equal', 1) 117 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 118 | invalidCount: 10, 119 | firstInvalid: sinon.match.string 120 | }) 121 | }) 122 | 123 | it('rate limit brute forcing of incorrect code', async () => { 124 | dynamo.get.resolves({ 125 | op, 126 | code: code2, 127 | verified: false, 128 | invalidCount: 10 129 | }) 130 | const { success, delay } = await userDao.verify({ userId, salt, op, code: code1 }) 131 | expect(success, 'to be', false) 132 | expect(verify.isDateISOString(delay), 'to be', true) 133 | expect(dynamo.put.callCount, 'to equal', 1) 134 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 135 | invalidCount: 11, 136 | firstInvalid: sinon.match.string 137 | }) 138 | }) 139 | 140 | it('rate limit brute forcing of correct code', async () => { 141 | dynamo.get.resolves({ 142 | op, 143 | code: code1, 144 | verified: false, 145 | invalidCount: 10 146 | }) 147 | const { success, delay } = await userDao.verify({ userId, salt, op, code: code1 }) 148 | expect(success, 'to be', false) 149 | expect(verify.isDateISOString(delay), 'to be', true) 150 | expect(dynamo.put.callCount, 'to equal', 1) 151 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 152 | invalidCount: 11, 153 | firstInvalid: sinon.match.string 154 | }) 155 | }) 156 | 157 | it('reset rate limit after time delay is over', async () => { 158 | dynamo.get.resolves({ 159 | op, 160 | code: code2, 161 | verified: false, 162 | invalidCount: 10, 163 | firstInvalid: '2020-06-01T03:33:47.980Z' 164 | }) 165 | const { success, delay } = await userDao.verify({ userId, salt, op, code: code1 }) 166 | expect(success, 'to be', false) 167 | expect(delay, 'to be', null) 168 | expect(dynamo.put.callCount, 'to equal', 1) 169 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 170 | invalidCount: 0, 171 | firstInvalid: null 172 | }) 173 | }) 174 | 175 | it('not verify a user with incorrect op', async () => { 176 | dynamo.get.resolves({ 177 | op: 'remove', 178 | code: code1, 179 | verified: false 180 | }) 181 | const { success, delay } = await userDao.verify({ userId, salt, op, code: code1 }) 182 | expect(success, 'to be', false) 183 | expect(delay, 'to be', undefined) 184 | expect(dynamo.put.callCount, 'to equal', 0) 185 | }) 186 | 187 | it('fail on dynamo get error', async () => { 188 | dynamo.get.rejects(new Error('boom')) 189 | await expect(userDao.verify({ userId, salt, op, code: code1 }), 'to be rejected with', /boom/) 190 | }) 191 | 192 | it('fail on dynamo put error', async () => { 193 | dynamo.get.resolves({ 194 | op, 195 | code: code1, 196 | verified: false 197 | }) 198 | dynamo.put.rejects(new Error('boom')) 199 | await expect(userDao.verify({ userId, salt, op, code: code1 }), 'to be rejected with', /boom/) 200 | }) 201 | 202 | it('verify a user with correct code', async () => { 203 | dynamo.get.resolves({ 204 | op, 205 | code: code1, 206 | verified: false, 207 | invalidCount: 1 208 | }) 209 | const { success, delay } = await userDao.verify({ userId, salt, op, code: code1 }) 210 | expect(success, 'to be', true) 211 | expect(delay, 'to be', undefined) 212 | expect(dynamo.put.callCount, 'to equal', 2) 213 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 214 | verified: true, 215 | invalidCount: 0, 216 | firstInvalid: null 217 | }) 218 | }) 219 | }) 220 | 221 | describe('setNewCode', () => { 222 | it('fail if no user is found', async () => { 223 | dynamo.get.resolves(null) 224 | const code = await userDao.setNewCode({ userId, salt, op }) 225 | expect(code, 'to be', null) 226 | expect(dynamo.put.callCount, 'to equal', 0) 227 | }) 228 | 229 | it('fail if user is not verified', async () => { 230 | dynamo.get.resolves({ verified: false }) 231 | const code = await userDao.setNewCode({ userId, salt, op }) 232 | expect(code, 'to be', null) 233 | expect(dynamo.put.callCount, 'to equal', 0) 234 | }) 235 | 236 | it('fail on dynamo get error', async () => { 237 | dynamo.get.rejects(new Error('boom')) 238 | await expect(userDao.setNewCode({ userId, salt, op }), 'to be rejected with', /boom/) 239 | }) 240 | 241 | it('fail on dynamo put error', async () => { 242 | dynamo.get.resolves({ verified: true }) 243 | dynamo.put.rejects(new Error('boom')) 244 | await expect(userDao.setNewCode({ userId, salt, op }), 'to be rejected with', /boom/) 245 | }) 246 | 247 | it('set a new code and persist', async () => { 248 | dynamo.get.resolves({ 249 | code: 'old', 250 | verified: true, 251 | invalidCount: 6, 252 | firstInvalid: '2020-06-01T03:33:47.980Z' 253 | }) 254 | const code = await userDao.setNewCode({ userId, salt, op }) 255 | expect(code, 'to match', /^\d{6}$/) 256 | expect(dynamo.put.callCount, 'to equal', 1) 257 | sinon.assert.calledWithMatch(dynamo.put, sinon.match.any, { 258 | op, 259 | code, 260 | verified: true, 261 | firstInvalid: '2020-06-01T03:33:47.980Z', 262 | invalidCount: 6 263 | }) 264 | }) 265 | }) 266 | 267 | describe('remove', () => { 268 | it('fail on invalid args', async () => { 269 | await expect(userDao.remove({}), 'to be rejected with', /argument must be/) 270 | }) 271 | 272 | it('fail if no user is found', async () => { 273 | dynamo.get.resolves(null) 274 | await expect(userDao.remove({ userId, salt }), 'to be rejected with', /not found/) 275 | expect(dynamo.remove.callCount, 'to equal', 0) 276 | }) 277 | 278 | it('fail on dynamo get error', async () => { 279 | dynamo.get.rejects(new Error('boom')) 280 | await expect(userDao.remove({ userId, salt }), 'to be rejected with', /boom/) 281 | expect(dynamo.remove.callCount, 'to equal', 0) 282 | }) 283 | 284 | it('remove user from table', async () => { 285 | dynamo.get.resolves({ id: 'some-id' }) 286 | await userDao.remove({ userId, salt }) 287 | expect(dynamo.remove.callCount, 'to equal', 1) 288 | sinon.assert.calledWith(dynamo.remove, sinon.match.any, { 289 | id: 'lE7uuK/qN3bkm1UPrVFfkA3PVxe48zq1WKGC2BdlkjI=' 290 | }) 291 | }) 292 | }) 293 | }) 294 | -------------------------------------------------------------------------------- /test/unit/verify.spec.js: -------------------------------------------------------------------------------- 1 | /* eslint-env mocha */ 2 | 3 | 'use strict' 4 | 5 | const expect = require('unexpected') 6 | const verify = require('../../src/lib/verify') 7 | 8 | describe('Verify Lib unit test', () => { 9 | describe('isOp', () => { 10 | it('returns true for a string op', () => { 11 | expect(verify.isOp('verify'), 'to be', true) 12 | }) 13 | 14 | it('returns true for a enum ops', () => { 15 | expect(verify.isOp(verify.ops.VERIFY), 'to be', true) 16 | }) 17 | 18 | it('returns false for an op', () => { 19 | expect(verify.isOp('invalid'), 'to be', false) 20 | }) 21 | 22 | it('returns false for null', () => { 23 | expect(verify.isOp(null), 'to be', false) 24 | }) 25 | 26 | it('returns false for undefined', () => { 27 | expect(verify.isOp(undefined), 'to be', false) 28 | }) 29 | 30 | it('returns false for empty string', () => { 31 | expect(verify.isOp(''), 'to be', false) 32 | }) 33 | }) 34 | 35 | describe('isPhone', () => { 36 | it('returns true for a valid phone number', () => { 37 | expect(verify.isPhone('+4917512345678'), 'to be', true) 38 | }) 39 | 40 | it('returns false for an invalid phone number', () => { 41 | expect(verify.isPhone('+04917512345678'), 'to be', false) 42 | }) 43 | 44 | it('returns false for an invalid phone number', () => { 45 | expect(verify.isPhone('+4'), 'to be', false) 46 | }) 47 | 48 | it('returns false for an invalid phone number', () => { 49 | expect(verify.isPhone('004917512345678'), 'to be', false) 50 | }) 51 | 52 | it('returns false for null', () => { 53 | expect(verify.isPhone(null), 'to be', false) 54 | }) 55 | 56 | it('returns false for undefined', () => { 57 | expect(verify.isPhone(undefined), 'to be', false) 58 | }) 59 | 60 | it('returns false for empty string', () => { 61 | expect(verify.isPhone(''), 'to be', false) 62 | }) 63 | }) 64 | 65 | describe('isEmail', () => { 66 | it('returns true for a valid email address', () => { 67 | expect(verify.isEmail('jon.smith@example.com'), 'to be', true) 68 | }) 69 | 70 | it('returns false for an invalid email address', () => { 71 | expect(verify.isEmail('@example.com'), 'to be', false) 72 | }) 73 | 74 | it('returns false for an invalid email address', () => { 75 | expect(verify.isEmail('jon.smith@examplecom'), 'to be', false) 76 | }) 77 | 78 | it('returns false for an invalid email address', () => { 79 | expect(verify.isEmail('jon.smithexample.com'), 'to be', false) 80 | }) 81 | 82 | it('returns false for null', () => { 83 | expect(verify.isEmail(null), 'to be', false) 84 | }) 85 | 86 | it('returns false for undefined', () => { 87 | expect(verify.isEmail(undefined), 'to be', false) 88 | }) 89 | 90 | it('returns false for object', () => { 91 | expect(verify.isEmail({}), 'to be', false) 92 | }) 93 | 94 | it('returns false for empty string', () => { 95 | expect(verify.isEmail(''), 'to be', false) 96 | }) 97 | }) 98 | 99 | describe('isCode', () => { 100 | it('returns true for a valid code', () => { 101 | expect(verify.isCode('000000'), 'to be', true) 102 | }) 103 | 104 | it('returns false for a non digit code', () => { 105 | expect(verify.isCode('00000a'), 'to be', false) 106 | }) 107 | 108 | it('returns false for a code that is too short', () => { 109 | expect(verify.isCode('00000'), 'to be', false) 110 | }) 111 | 112 | it('returns false for a code that is too long', () => { 113 | expect(verify.isCode('0000000'), 'to be', false) 114 | }) 115 | 116 | it('returns false for null', () => { 117 | expect(verify.isCode(null), 'to be', false) 118 | }) 119 | 120 | it('returns false for undefined', () => { 121 | expect(verify.isCode(undefined), 'to be', false) 122 | }) 123 | 124 | it('returns false for empty string', () => { 125 | expect(verify.isCode(''), 'to be', false) 126 | }) 127 | }) 128 | 129 | describe('isId', () => { 130 | it('returns true for a valid uuid', () => { 131 | expect(verify.isId('8abe1a93-6a9c-490c-bbd5-d7f11a4a9c8f'), 'to be', true) 132 | }) 133 | 134 | it('returns false for an upper case uuid', () => { 135 | expect(verify.isId('8ABE1A93-6A9C-490C-BBD5-D7F11A4A9C8F'), 'to be', false) 136 | }) 137 | 138 | it('returns false for an invalid uuid', () => { 139 | expect(verify.isId('8abe1a93-6a9c-490c-bbd5-d7f11a4a9c8'), 'to be', false) 140 | }) 141 | 142 | it('returns false for null', () => { 143 | expect(verify.isId(null), 'to be', false) 144 | }) 145 | 146 | it('returns false for undefined', () => { 147 | expect(verify.isId(undefined), 'to be', false) 148 | }) 149 | 150 | it('returns false for empty string', () => { 151 | expect(verify.isId(''), 'to be', false) 152 | }) 153 | }) 154 | 155 | describe('isPin', () => { 156 | it('returns true for a four digits', () => { 157 | expect(verify.isPin('1234'), 'to be', true) 158 | }) 159 | 160 | it('returns true for a password', () => { 161 | expect(verify.isPin('#!Pa$$wörD'), 'to be', true) 162 | }) 163 | 164 | it('returns true for a passphrase', () => { 165 | expect(verify.isPin('this is a passphrase'), 'to be', true) 166 | }) 167 | 168 | it('returns false for only three digits', () => { 169 | expect(verify.isPin('123'), 'to be', false) 170 | }) 171 | 172 | it('returns false for a new line', () => { 173 | expect(verify.isPin('1234\n'), 'to be', false) 174 | }) 175 | 176 | it('returns false if pin is too long', () => { 177 | const pin = new Array(257).fill('0').join('') 178 | expect(verify.isPin(pin), 'to be', false) 179 | }) 180 | 181 | it('returns false for null', () => { 182 | expect(verify.isPin(null), 'to be', false) 183 | }) 184 | 185 | it('returns false for undefined', () => { 186 | expect(verify.isPin(undefined), 'to be', false) 187 | }) 188 | 189 | it('returns false for empty string', () => { 190 | expect(verify.isPin(''), 'to be', false) 191 | }) 192 | }) 193 | 194 | describe('isDateISOString', () => { 195 | it('returns true for a valid date string', () => { 196 | expect(verify.isDateISOString('2020-06-09T03:33:47.980Z'), 'to be', true) 197 | }) 198 | 199 | it('returns false for an invalid date string', () => { 200 | expect(verify.isDateISOString('2020-06-09T03:33:47.980'), 'to be', false) 201 | }) 202 | 203 | it('returns false for null', () => { 204 | expect(verify.isDateISOString(null), 'to be', false) 205 | }) 206 | 207 | it('returns false for undefined', () => { 208 | expect(verify.isDateISOString(undefined), 'to be', false) 209 | }) 210 | 211 | it('returns false for empty string', () => { 212 | expect(verify.isDateISOString(''), 'to be', false) 213 | }) 214 | }) 215 | }) 216 | --------------------------------------------------------------------------------