├── .eslintignore ├── .eslintrc ├── .github └── workflows │ └── tests.yml ├── .gitignore ├── .mocharc.yml ├── .npmignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── SECURITY.md ├── docs ├── ExpressOAuthServer.html ├── fonts │ ├── OpenSans-Bold-webfont.eot │ ├── OpenSans-Bold-webfont.svg │ ├── OpenSans-Bold-webfont.woff │ ├── OpenSans-BoldItalic-webfont.eot │ ├── OpenSans-BoldItalic-webfont.svg │ ├── OpenSans-BoldItalic-webfont.woff │ ├── OpenSans-Italic-webfont.eot │ ├── OpenSans-Italic-webfont.svg │ ├── OpenSans-Italic-webfont.woff │ ├── OpenSans-Light-webfont.eot │ ├── OpenSans-Light-webfont.svg │ ├── OpenSans-Light-webfont.woff │ ├── OpenSans-LightItalic-webfont.eot │ ├── OpenSans-LightItalic-webfont.svg │ ├── OpenSans-LightItalic-webfont.woff │ ├── OpenSans-Regular-webfont.eot │ ├── OpenSans-Regular-webfont.svg │ └── OpenSans-Regular-webfont.woff ├── global.html ├── index.html ├── index.js.html ├── scripts │ ├── linenumber.js │ └── prettify │ │ ├── Apache-License-2.0.txt │ │ ├── lang-css.js │ │ └── prettify.js └── styles │ ├── jsdoc-default.css │ ├── prettify-jsdoc.css │ └── prettify-tomorrow.css ├── index.d.ts ├── index.js ├── jsdoc.conf.json ├── package-lock.json ├── package.json └── test ├── integration └── index_test.js └── unit └── index_test.js /.eslintignore: -------------------------------------------------------------------------------- 1 | .github 2 | .nyc_output 3 | coverage 4 | docs 5 | node_modules 6 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint:recommended", 3 | "root": true, 4 | "env": { 5 | "node": true, 6 | "mocha": true, 7 | "es6": true 8 | }, 9 | "parserOptions": { 10 | "ecmaVersion": "latest", 11 | "sourceType": "module", 12 | "ecmaFeatures" : { 13 | "globalReturn": false, 14 | "impliedStrict": true, 15 | "jsx": false 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | # This workflow runs standard unit tests to ensure basic integrity and avoid 4 | # regressions on pull-requests (and pushes) 5 | 6 | on: 7 | push: 8 | branches: 9 | - master # allthough master is push protected we still keep it 10 | - development 11 | pull_request: # runs on all PR 12 | 13 | jobs: 14 | unittest: 15 | name: unit tests 16 | runs-on: ubuntu-latest 17 | strategy: 18 | matrix: 19 | node: [16, 18, 20] 20 | steps: 21 | - name: Checkout ${{ matrix.node }} 22 | uses: actions/checkout@v3 23 | 24 | - name: Setup node ${{ matrix.node }} 25 | uses: actions/setup-node@v3 26 | with: 27 | node-version: ${{ matrix.node }} 28 | 29 | - name: Cache dependencies ${{ matrix.node }} 30 | uses: actions/cache@v3 31 | with: 32 | path: ~/.npm 33 | key: ${{ runner.os }}-node-${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }} 34 | restore-keys: | 35 | ${{ runner.os }}-node-${{ matrix.node }} 36 | - run: npm ci 37 | - run: npm run lint 38 | - run: npm run test:coverage 39 | - run: npm run build:docs 40 | 41 | # with the following action we enforce PRs to have a high coverage 42 | # and ensure, changes are tested well enough so that coverage won't fail 43 | - name: check coverage 44 | uses: VeryGoodOpenSource/very_good_coverage@v1.2.0 45 | with: 46 | path: './coverage/lcov.info' 47 | min_coverage: 95 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | docs/_build/ 3 | __pycache__/ 4 | *.pyc 5 | lib-cov 6 | *.seed 7 | *.log 8 | *.csv 9 | *.dat 10 | *.out 11 | *.pid 12 | *.gz 13 | *.iml 14 | 15 | .idea 16 | .jshint 17 | .DS_Store 18 | 19 | pids 20 | logs 21 | results 22 | 23 | lib/dockerImage/keys 24 | coverage 25 | npm-debug.log*~ 26 | \#*\# 27 | /.emacs.desktop 28 | /.emacs.desktop.lock 29 | .elc 30 | auto-save-list 31 | tramp 32 | .\#* 33 | .vscode 34 | 35 | # Org-mode 36 | .org-id-locations 37 | *_archive 38 | 39 | # coverage 40 | .nyc_output 41 | 42 | package-lock.json 43 | yarn.lock 44 | -------------------------------------------------------------------------------- /.mocharc.yml: -------------------------------------------------------------------------------- 1 | recursive: true 2 | reporter: "spec" 3 | retries: 0 4 | slow: 20 5 | timeout: 2000 6 | ui: "bdd" 7 | exit: true 8 | # require: test/assertions 9 | # for more options see here https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.yml 10 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | test/ 2 | examples/ 3 | package-lock.json 4 | yarn.lock 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 4.0.0 4 | 5 | - bump minimal node to 16 6 | - upgrade @node-oauth/oauth2-server to 5.1.0 7 | - drop bluebird dependency 8 | - upgrade all deps / dev-deps 9 | - refactor all code to minimum es6 10 | - use native async/await 11 | 12 | 13 | ## 3.0.0 14 | - use @node-oauth/oauth2-server 15 | - update all dependencies to latest 16 | - add code coverage to tests 17 | - add GitHub actions CI 18 | - replace jshint with eslint 19 | 20 | --- 21 | These previous versions are from the forked `oauthjs` org. 22 | We did not publish them are related in any way to these publications. 23 | 24 | ## 2.0.0 25 | * Refactor for v3.0.0 of node-oauth2-server 26 | 27 | ## 1.0.0 28 | * Initial Release 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 - Today Node-OAuth contributors; Formerly: Seegno and contributors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

Express OAuth Server

3 |
4 | 5 |

6 | Complete, compliant and well tested module for implementing an OAuth2 Server/Provider with express in Node.js. 7 |

8 | 9 |
10 | 11 | [![Tests](https://github.com/node-oauth/express-oauth-server/actions/workflows/tests.yml/badge.svg)](https://github.com/node-oauth/express-oauth-server/actions/workflows/tests.yml) 12 | [![CodeQL](https://github.com/node-oauth/express-oauth-server/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/node-oauth/express-oauth-server/actions/workflows/github-code-scanning/codeql) 13 | [![Project Status: Active – The project has reached a stable, usable state and is being actively developed.](https://www.repostatus.org/badges/latest/active.svg)](https://www.repostatus.org/#active) 14 | [![npm Version](https://img.shields.io/npm/v/@node-oauth/express-oauth-server?label=version)](https://www.npmjs.com/package/@node-oauth/oauth2-server) 15 | [![npm Downloads/Week](https://img.shields.io/npm/dw/@node-oauth/express-oauth-server)](https://www.npmjs.com/package/@node-oauth/oauth2-server) 16 | ![GitHub](https://img.shields.io/github/license/node-oauth/express-oauth-server) 17 | 18 |
19 | 20 |
21 | 22 | [API Docs](https://node-oauth.github.io/express-oauth-server/) 23 | · 24 | [NPM Link](https://www.npmjs.com/package/@node-oauth/express-oauth-server) 25 | · 26 | [Node OAuth2 Server](https://github.com/node-oauth/node-oauth2-server) 27 | 28 |
29 | 30 | ## About 31 | 32 | This package wraps the [@node-oauth/oauth2-server](https://github.com/node-oauth/node-oauth2-server) into an 33 | express compatible middleware. 34 | It's a maintained and up-to-date fork from the former 35 | [oauthjs/express-oauth-server](https://github.com/oauthjs/express-oauth-server). 36 | 37 | 38 | ## Installation 39 | 40 | ```shell 41 | $ npm install @node-oauth/express-oauth-server 42 | ``` 43 | 44 | ## Quick Start 45 | 46 | The module provides two middlewares - one for granting tokens and another to authorize them. 47 | `@node-oauth/express-oauth-server` and, consequently `@node-oauth/oauth2-server`, 48 | expect the request body to be parsed already. 49 | The following example uses `body-parser` but you may opt for an alternative library. 50 | 51 | ```js 52 | const bodyParser = require('body-parser'); 53 | const express = require('express'); 54 | const OAuthServer = require('@node-oauth/express-oauth-server'); 55 | 56 | const app = express(); 57 | 58 | app.oauth = new OAuthServer({ 59 | model: {}, // See https://github.com/node-oauth/node-oauth2-server for specification 60 | }); 61 | 62 | app.use(bodyParser.json()); 63 | app.use(bodyParser.urlencoded({ extended: false })); 64 | app.use(app.oauth.authorize()); 65 | 66 | app.use(function(req, res) { 67 | res.send('Secret area'); 68 | }); 69 | 70 | app.listen(3000); 71 | ``` 72 | 73 | ## Options 74 | 75 | > Note: The following options **extend** the default options from `@node-oauth/oauth2-server`! 76 | > You can read more about all possible options in the 77 | > [@node-oauth/oauth2-server documentation](https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html) 78 | 79 | ``` 80 | const options = { 81 | useErrorHandler: false, 82 | continueMiddleware: false, 83 | } 84 | ``` 85 | 86 | - `useErrorHandler` 87 | (_type: boolean_ default: false) 88 | 89 | If false, an error response will be rendered by this component. 90 | Set this value to true to allow your own express error handler to handle the error. 91 | 92 | - `continueMiddleware` 93 | (_type: boolean default: false_) 94 | 95 | The `authorize()` and `token()` middlewares will both render their 96 | result to the response and end the pipeline. 97 | next() will only be called if this is set to true. 98 | 99 | **Note:** You cannot modify the response since the headers have already been sent. 100 | 101 | `authenticate()` does not modify the response and will always call next() 102 | 103 | ## Migration notes 104 | 105 | Beginning with **version 4.0** this package brings some potentially breaking changes: 106 | 107 | - dropped old es5 code; moved to native async/await 108 | - requires node >= 16 109 | - ships with [@node-oauth/oauth2-server](https://github.com/node-oauth/node-oauth2-server) 5.x 110 | - no express version pinned but declared as `'*'` peer dependency, so it should not cause conflicts with your express version 111 | 112 | ## More Examples 113 | 114 | For more examples, please visit [our dedicated "examples" repo](https://github.com/node-oauth/node-oauth2-server-examples) 115 | , which also contains express examples. 116 | 117 | ## License 118 | 119 | MIT, see [license file](./LICENSE). 120 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 3.x.x | :white_check_mark: | 11 | | < 3 | :x: | 12 | 13 | ## Reporting a Vulnerability 14 | 15 | Report security vulnerabilities to info@jankuester.com 16 | 17 | Please specify exactly how the vulnerability is to be exploited so we can estimate how severe the consequences can be (unless you also can specify them, too). 18 | 19 | Please note that we need to reproduce the vulnerability (as like with bugs) in order to safely fix it. 20 | 21 | A fix will be implemented in private until we can ensure the vulnerability is closed. A new release will immediately be published. 22 | If you want to provide a fix please let us know in the e-mail so we can setup a completely private repository to work on it together. 23 | 24 | Finally, all security fixes will also require to pass all tests and audits. 25 | -------------------------------------------------------------------------------- /docs/ExpressOAuthServer.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Class: ExpressOAuthServer 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Class: ExpressOAuthServer

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

ExpressOAuthServer(optionsopt)

32 | 33 |

Complete, compliant and well tested express wrapper for @node-oauth/oauth2-server in node.js. 34 | The module provides two middlewares - one for granting tokens and another to authorize them. 35 | @node-oauth/express-oauth-server and, consequently @node-oauth/oauth2-server, 36 | expect the request body to be parsed already. 37 | The following example uses body-parser but you may opt for an alternative library.

38 | 39 | 40 |
41 | 42 |
43 |
44 | 45 | 46 | 47 | 48 |

Constructor

49 | 50 | 51 | 52 |

new ExpressOAuthServer(optionsopt)

53 | 54 | 55 | 56 | 57 | 58 | 59 |
60 |

Creates a new OAuth2 server that will be bound to this class' middlewares. 61 | Constructor takes several options as arguments. 62 | The following describes only options, specific to this module. 63 | For all other options, please read the docs from @node-oauth/oauth2-server:

64 |
65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 |
Parameters:
75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 112 | 113 | 114 | 123 | 124 | 125 | 126 | 127 | 227 | 228 | 229 | 230 | 231 |
NameTypeAttributesDescription
options 105 | 106 | 107 | object 108 | 109 | 110 | 111 | 115 | 116 | <optional>
117 | 118 | 119 | 120 | 121 | 122 |

optional options

128 |
Properties
129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 166 | 167 | 168 | 177 | 178 | 179 | 180 | 181 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 200 | 201 | 202 | 211 | 212 | 213 | 214 | 215 | 220 | 221 | 222 | 223 | 224 |
NameTypeAttributesDescription
useErrorHandler 159 | 160 | 161 | boolean 162 | 163 | 164 | 165 | 169 | 170 | <optional>
171 | 172 | 173 | 174 | 175 | 176 |

If false, an error response will be rendered by this component. 182 | Set this value to true to allow your own express error handler to handle the error.

continueMiddleware 193 | 194 | 195 | boolean 196 | 197 | 198 | 199 | 203 | 204 | <optional>
205 | 206 | 207 | 208 | 209 | 210 |

The authorize() and token() middlewares will both render their 216 | result to the response and end the pipeline. 217 | next() will only be called if this is set to true. 218 | Note: You cannot modify the response since the headers have already been sent. 219 | authenticate() does not modify the response and will always call next()

225 | 226 |
232 | 233 | 234 | 235 | 236 | 237 | 238 |
239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 |
Source:
266 |
269 | 270 | 271 | 272 | 273 | 274 |
See:
275 |
276 | 279 |
280 | 281 | 282 | 283 |
284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 |
Example
304 | 305 |
const bodyParser = require('body-parser');
306 | const express = require('express');
307 | const OAuthServer = require('@node-oauth/express-oauth-server');
308 | 
309 | const app = express();
310 | 
311 | app.oauth = new OAuthServer({
312 |   model: {}, // See https://github.com/node-oauth/node-oauth2-server for specification
313 | });
314 | 
315 | app.use(bodyParser.json());
316 | app.use(bodyParser.urlencoded({ extended: false }));
317 | app.use(app.oauth.authorize());
318 | 
319 | app.use(function(req, res) {
320 |   res.send('Secret area');
321 | });
322 | 
323 | app.listen(3000);
324 | 325 | 326 | 327 | 328 |
329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 |

Methods

346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 |

authenticate(optionsopt) → {function}

354 | 355 | 356 | 357 | 358 | 359 | 360 |
361 |

Authentication Middleware. 362 | Returns a middleware that will validate a token.

363 |
364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 |
Parameters:
374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 411 | 412 | 413 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 |
NameTypeAttributesDescription
options 404 | 405 | 406 | object 407 | 408 | 409 | 410 | 414 | 415 | <optional>
416 | 417 | 418 | 419 | 420 | 421 |

will be passed to the authenticate-handler as options, see linked docs

432 | 433 | 434 | 435 | 436 | 437 | 438 |
439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 |
Source:
466 |
469 | 470 | 471 | 472 | 473 | 474 |
See:
475 |
476 | 479 |
480 | 481 | 482 | 483 |
484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 |
Returns:
500 | 501 | 502 | 503 | 504 |
505 |
506 | Type 507 |
508 |
509 | 510 | function 511 | 512 | 513 |
514 |
515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 |

authorize(optionsopt) → {function}

529 | 530 | 531 | 532 | 533 | 534 | 535 |
536 |

Authorization Middleware. 537 | Returns a middleware that will authorize a client to request tokens.

538 |
539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 |
Parameters:
549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 586 | 587 | 588 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 |
NameTypeAttributesDescription
options 579 | 580 | 581 | object 582 | 583 | 584 | 585 | 589 | 590 | <optional>
591 | 592 | 593 | 594 | 595 | 596 |

will be passed to the authorize-handler as options, see linked docs

607 | 608 | 609 | 610 | 611 | 612 | 613 |
614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 |
Source:
641 |
644 | 645 | 646 | 647 | 648 | 649 |
See:
650 |
651 | 654 |
655 | 656 | 657 | 658 |
659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | 671 | 672 | 673 | 674 |
Returns:
675 | 676 | 677 | 678 | 679 |
680 |
681 | Type 682 |
683 |
684 | 685 | function 686 | 687 | 688 |
689 |
690 | 691 | 692 | 693 | 694 | 695 | 696 | 697 | 698 | 699 | 700 | 701 | 702 | 703 |

token(optionsopt) → {function}

704 | 705 | 706 | 707 | 708 | 709 | 710 |
711 |

Grant Middleware. 712 | Returns middleware that will grant tokens to valid requests.

713 |
714 | 715 | 716 | 717 | 718 | 719 | 720 | 721 | 722 | 723 |
Parameters:
724 | 725 | 726 | 727 | 728 | 729 | 730 | 731 | 732 | 733 | 734 | 735 | 736 | 737 | 738 | 739 | 740 | 741 | 742 | 743 | 744 | 745 | 746 | 747 | 748 | 749 | 750 | 751 | 752 | 753 | 761 | 762 | 763 | 772 | 773 | 774 | 775 | 776 | 777 | 778 | 779 | 780 | 781 |
NameTypeAttributesDescription
options 754 | 755 | 756 | object 757 | 758 | 759 | 760 | 764 | 765 | <optional>
766 | 767 | 768 | 769 | 770 | 771 |

will be passed to the token-handler as options, see linked docs

782 | 783 | 784 | 785 | 786 | 787 | 788 |
789 | 790 | 791 | 792 | 793 | 794 | 795 | 796 | 797 | 798 | 799 | 800 | 801 | 802 | 803 | 804 | 805 | 806 | 807 | 808 | 809 | 810 | 811 | 812 | 813 | 814 | 815 |
Source:
816 |
819 | 820 | 821 | 822 | 823 | 824 |
See:
825 |
826 | 829 |
830 | 831 | 832 | 833 |
834 | 835 | 836 | 837 | 838 | 839 | 840 | 841 | 842 | 843 | 844 | 845 | 846 | 847 | 848 | 849 |
Returns:
850 | 851 | 852 | 853 | 854 |
855 |
856 | Type 857 |
858 |
859 | 860 | function 861 | 862 | 863 |
864 |
865 | 866 | 867 | 868 | 869 | 870 | 871 | 872 | 873 | 874 | 875 | 876 | 877 | 878 |
879 | 880 |
881 | 882 | 883 | 884 | 885 |
886 | 887 | 890 | 891 |
892 | 893 | 896 | 897 | 898 | 899 | 900 | -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Bold-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Bold-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Bold-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-BoldItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-BoldItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-BoldItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Italic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Italic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Italic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Light-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Light-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Light-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-LightItalic-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-LightItalic-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-LightItalic-webfont.woff -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Regular-webfont.eot -------------------------------------------------------------------------------- /docs/fonts/OpenSans-Regular-webfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/node-oauth/express-oauth-server/5fb0f6f264f410242c1dd59daf50c8d097e58b31/docs/fonts/OpenSans-Regular-webfont.woff -------------------------------------------------------------------------------- /docs/global.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Global 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Global

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 |
30 | 31 |

32 | 33 | 34 |
35 | 36 |
37 |
38 | 39 | 40 | 41 | 42 | 43 | 44 |
45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 |
78 | 79 | 80 | 81 | 82 |
83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 |

Members

98 | 99 | 100 | 101 |

(constant) InvalidArgumentError

102 | 103 | 104 | 105 | 106 |
107 |

Module dependencies.

108 |
109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 |
117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 |
Source:
144 |
147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 |
155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 |
170 | 171 |
172 | 173 | 174 | 175 | 176 |
177 | 178 | 181 | 182 |
183 | 184 | 187 | 188 | 189 | 190 | 191 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Home 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Home

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 |

30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 |
46 |
47 |

Express OAuth Server

48 |
49 |

50 | Complete, compliant and well tested module for implementing an OAuth2 Server/Provider with express in Node.js. 51 |

52 |
53 |

Tests 54 | CodeQL 55 | Project Status: Active – The project has reached a stable, usable state and is being actively developed. 56 | npm Version 57 | npm Downloads/Week 58 | GitHub

59 |
60 |
61 |

API Docs 62 | · 63 | NPM Link 64 | · 65 | Node OAuth2 Server

66 |
67 |

About

68 |

This package wraps the @node-oauth/oauth2-server into an 69 | express compatible middleware. 70 | It's a maintained and up-to-date fork from the former 71 | oauthjs/express-oauth-server.

72 |

Installation

73 |
$ npm install @node-oauth/express-oauth-server
 74 | 
75 |

Quick Start

76 |

The module provides two middlewares - one for granting tokens and another to authorize them. 77 | @node-oauth/express-oauth-server and, consequently @node-oauth/oauth2-server, 78 | expect the request body to be parsed already. 79 | The following example uses body-parser but you may opt for an alternative library.

80 |
const bodyParser = require('body-parser');
 81 | const express = require('express');
 82 | const OAuthServer = require('@node-oauth/express-oauth-server');
 83 | 
 84 | const app = express();
 85 | 
 86 | app.oauth = new OAuthServer({
 87 |   model: {}, // See https://github.com/node-oauth/node-oauth2-server for specification
 88 | });
 89 | 
 90 | app.use(bodyParser.json());
 91 | app.use(bodyParser.urlencoded({ extended: false }));
 92 | app.use(app.oauth.authorize());
 93 | 
 94 | app.use(function(req, res) {
 95 |   res.send('Secret area');
 96 | });
 97 | 
 98 | app.listen(3000);
 99 | 
100 |

Options

101 |
102 |

Note: The following options extend the default options from @node-oauth/oauth2-sever! 103 | You can read more about all possible options in the 104 | @node-oauth/oauth2-sever documentation

105 |
106 |
const options = { 
107 |   useErrorHandler: false, 
108 |   continueMiddleware: false,
109 | }
110 | 
111 |
    112 |
  • 113 |

    useErrorHandler 114 | (type: boolean default: false)

    115 |

    If false, an error response will be rendered by this component. 116 | Set this value to true to allow your own express error handler to handle the error.

    117 |
  • 118 |
  • 119 |

    continueMiddleware 120 | (type: boolean default: false)

    121 |

    The authorize() and token() middlewares will both render their 122 | result to the response and end the pipeline. 123 | next() will only be called if this is set to true.

    124 |

    Note: You cannot modify the response since the headers have already been sent.

    125 |

    authenticate() does not modify the response and will always call next()

    126 |
  • 127 |
128 |

Migration notes

129 |

Beginning with version 4.0 this package brings some potentially breaking changes:

130 |
    131 |
  • dropped old es5 code; moved to native async/await
  • 132 |
  • requires node >= 16
  • 133 |
  • ships with @node-oauth/oauth2-server 5.x
  • 134 |
  • no express version pinned but declared as '*' peer dependency, so it should not cause conflicts with your express version
  • 135 |
136 |

More Examples

137 |

For more examples, please visit our dedicated "examples" repo 138 | , which also contains express examples.

139 |

License

140 |

MIT, see license file.

141 |
142 | 143 | 144 | 145 | 146 | 147 | 148 |
149 | 150 | 153 | 154 |
155 | 156 | 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /docs/index.js.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSDoc: Source: index.js 6 | 7 | 8 | 9 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 |

Source: index.js

21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 |
29 |
/**
 30 |  * Module dependencies.
 31 |  */
 32 | 
 33 | const InvalidArgumentError = require('@node-oauth/oauth2-server/lib/errors/invalid-argument-error');
 34 | const NodeOAuthServer = require('@node-oauth/oauth2-server');
 35 | const Request = require('@node-oauth/oauth2-server').Request;
 36 | const Response = require('@node-oauth/oauth2-server').Response;
 37 | const UnauthorizedRequestError = require('@node-oauth/oauth2-server/lib/errors/unauthorized-request-error');
 38 | 
 39 | /**
 40 |  * Complete, compliant and well tested express wrapper for @node-oauth/oauth2-server in node.js.
 41 |  * The module provides two middlewares - one for granting tokens and another to authorize them.
 42 |  * `@node-oauth/express-oauth-server` and, consequently `@node-oauth/oauth2-server`,
 43 |  * expect the request body to be parsed already.
 44 |  * The following example uses `body-parser` but you may opt for an alternative library.
 45 |  *
 46 |  * @class
 47 |  * @example
 48 |  * const bodyParser = require('body-parser');
 49 |  * const express = require('express');
 50 |  * const OAuthServer = require('@node-oauth/express-oauth-server');
 51 |  *
 52 |  * const app = express();
 53 |  *
 54 |  * app.oauth = new OAuthServer({
 55 |  *   model: {}, // See https://github.com/node-oauth/node-oauth2-server for specification
 56 |  * });
 57 |  *
 58 |  * app.use(bodyParser.json());
 59 |  * app.use(bodyParser.urlencoded({ extended: false }));
 60 |  * app.use(app.oauth.authorize());
 61 |  *
 62 |  * app.use(function(req, res) {
 63 |  *   res.send('Secret area');
 64 |  * });
 65 |  *
 66 |  * app.listen(3000);
 67 |  */
 68 | class ExpressOAuthServer {
 69 |   /**
 70 |    * Creates a new OAuth2 server that will be bound to this class' middlewares.
 71 |    * Constructor takes several options as arguments.
 72 |    * The following describes only options, specific to this module.
 73 |    * For all other options, please read the docs from `@node-oauth/oauth2-server`:
 74 |    * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html
 75 |    * @constructor
 76 |    * @param options {object=} optional options
 77 |    * @param options.useErrorHandler {boolean=} If false, an error response will be rendered by this component.
 78 |    *   Set this value to true to allow your own express error handler to handle the error.
 79 |    * @param options.continueMiddleware {boolean=} The `authorize()` and `token()` middlewares will both render their
 80 |    *   result to the response and end the pipeline.
 81 |    *   next() will only be called if this is set to true.
 82 |    *   **Note:** You cannot modify the response since the headers have already been sent.
 83 |    *   `authenticate()` does not modify the response and will always call next()
 84 |    */
 85 |   constructor(options = {}) {
 86 |     if (!options.model) {
 87 |       throw new InvalidArgumentError('Missing parameter: `model`');
 88 |     }
 89 | 
 90 |     this.useErrorHandler = !!options.useErrorHandler;
 91 |     delete options.useErrorHandler;
 92 | 
 93 |     this.continueMiddleware = !!options.continueMiddleware;
 94 |     delete options.continueMiddleware;
 95 | 
 96 |     this.server = new NodeOAuthServer(options);
 97 |   }
 98 | 
 99 |   /**
100 |    * Authentication Middleware.
101 |    * Returns a middleware that will validate a token.
102 |    *
103 |    * @param options {object=} will be passed to the authenticate-handler as options, see linked docs
104 |    * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html#authenticate-request-response-options
105 |    * @see: https://tools.ietf.org/html/rfc6749#section-7
106 |    * @return {function(req, res, next):Promise.<Object>}
107 |    */
108 |   authenticate(options) {
109 |     const fn = async function(req, res, next) {
110 |       const request = new Request(req);
111 |       const response = new Response(res);
112 | 
113 |       let token
114 | 
115 |       try {
116 |         token = await this.server.authenticate(request, response, options);
117 |       } catch (e) {
118 |         return handleError.call(this, e, req, res, null, next);
119 |       }
120 | 
121 |       res.locals.oauth = { token };
122 |       next();
123 |     };
124 | 
125 |     return fn.bind(this);
126 |   }
127 | 
128 |   /**
129 |    * Authorization Middleware.
130 |    * Returns a middleware that will authorize a client to request tokens.
131 |    *
132 |    * @param options {object=} will be passed to the authorize-handler as options, see linked docs
133 |    * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html#authorize-request-response-options
134 |    * @see: https://tools.ietf.org/html/rfc6749#section-3.1
135 |    * @return {function(req, res, next):Promise.<Object>}
136 |    */
137 |   authorize(options) {
138 |     const fn = async function(req, res, next) {
139 |       const request = new Request(req);
140 |       const response = new Response(res);
141 | 
142 |       let code
143 | 
144 |       try {
145 |         code = await this.server.authorize(request, response, options);
146 |       } catch (e) {
147 |         return handleError.call(this, e, req, res, response, next);
148 |       }
149 | 
150 |       res.locals.oauth = { code };
151 |       if (this.continueMiddleware) {
152 |         next();
153 |       }
154 | 
155 |       return handleResponse.call(this, req, res, response);
156 |     };
157 | 
158 |     return fn.bind(this);
159 |   }
160 | 
161 |   /**
162 |    * Grant Middleware.
163 |    * Returns middleware that will grant tokens to valid requests.
164 |    *
165 |    * @param options {object=} will be passed to the token-handler as options, see linked docs
166 |    * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html#token-request-response-options
167 |    * @see: https://tools.ietf.org/html/rfc6749#section-3.2
168 |    * @return {function(req, res, next):Promise.<Object>}
169 |    */
170 |   token(options) {
171 |     const fn = async function(req, res, next) {
172 |       const request = new Request(req);
173 |       const response = new Response(res);
174 | 
175 |       let token
176 | 
177 |       try {
178 |         token = await this.server.token(request, response, options);
179 |       } catch (e) {
180 |         return handleError.call(this, e, req, res, response, next);
181 |       }
182 | 
183 |       res.locals.oauth = { token };
184 |       if (this.continueMiddleware) {
185 |         next();
186 |       }
187 | 
188 |       return handleResponse.call(this, req, res, response);
189 |     };
190 | 
191 |     return fn.bind(this);
192 |   }
193 | }
194 | 
195 | /**
196 |  * Handle response.
197 |  * @private
198 |  */
199 | const handleResponse = function(req, res, response) {
200 |   if (response.status === 302) {
201 |     const location = response.headers.location;
202 |     delete response.headers.location;
203 |     res.set(response.headers);
204 |     res.redirect(location);
205 |   } else {
206 |     res.set(response.headers);
207 |     res.status(response.status).send(response.body);
208 |   }
209 | };
210 | 
211 | /**
212 |  * Handle error.
213 |  * @private
214 |  */
215 | const handleError = function(e, req, res, response, next) {
216 |   if (this.useErrorHandler === true) {
217 |     next(e);
218 |   } else {
219 |     if (response) {
220 |       res.set(response.headers);
221 |     }
222 | 
223 |     res.status(e.code);
224 | 
225 |     if (e instanceof UnauthorizedRequestError) {
226 |       return res.send();
227 |     }
228 | 
229 |     res.send({ error: e.name, error_description: e.message });
230 |   }
231 | };
232 | 
233 | /**
234 |  * Export constructor.
235 |  * @private
236 |  */
237 | 
238 | module.exports = ExpressOAuthServer;
239 | 
240 |
241 |
242 | 243 | 244 | 245 | 246 |
247 | 248 | 251 | 252 |
253 | 254 | 257 | 258 | 259 | 260 | 261 | 262 | -------------------------------------------------------------------------------- /docs/scripts/linenumber.js: -------------------------------------------------------------------------------- 1 | /*global document */ 2 | (() => { 3 | const source = document.getElementsByClassName('prettyprint source linenums'); 4 | let i = 0; 5 | let lineNumber = 0; 6 | let lineId; 7 | let lines; 8 | let totalLines; 9 | let anchorHash; 10 | 11 | if (source && source[0]) { 12 | anchorHash = document.location.hash.substring(1); 13 | lines = source[0].getElementsByTagName('li'); 14 | totalLines = lines.length; 15 | 16 | for (; i < totalLines; i++) { 17 | lineNumber++; 18 | lineId = `line${lineNumber}`; 19 | lines[i].id = lineId; 20 | if (lineId === anchorHash) { 21 | lines[i].className += ' selected'; 22 | } 23 | } 24 | } 25 | })(); 26 | -------------------------------------------------------------------------------- /docs/scripts/prettify/Apache-License-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /docs/scripts/prettify/lang-css.js: -------------------------------------------------------------------------------- 1 | PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\f\r ]+/,null," \t\r\n "]],[["str",/^"(?:[^\n\f\r"\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*"/,null],["str",/^'(?:[^\n\f\r'\\]|\\(?:\r\n?|\n|\f)|\\[\S\s])*'/,null],["lang-css-str",/^url\(([^"')]*)\)/i],["kwd",/^(?:url|rgb|!important|@import|@page|@media|@charset|inherit)(?=[^\w-]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*)\s*:/i],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["com", 2 | /^(?:<\!--|--\>)/],["lit",/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],["lit",/^#[\da-f]{3,6}/i],["pln",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i],["pun",/^[^\s\w"']+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[["kwd",/^-?(?:[_a-z]|\\[\da-f]+ ?)(?:[\w-]|\\\\[\da-f]+ ?)*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[["str",/^[^"')]+/]]),["css-str"]); 3 | -------------------------------------------------------------------------------- /docs/scripts/prettify/prettify.js: -------------------------------------------------------------------------------- 1 | var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; 2 | (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= 3 | [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), 9 | l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, 10 | q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, 11 | q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, 12 | "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), 13 | a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} 14 | for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], 18 | "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], 19 | H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], 20 | J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ 21 | I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), 22 | ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", 23 | /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), 24 | ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", 25 | hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= 26 | !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p th:last-child { border-right: 1px solid #ddd; } 224 | 225 | .ancestors, .attribs { color: #999; } 226 | .ancestors a, .attribs a 227 | { 228 | color: #999 !important; 229 | text-decoration: none; 230 | } 231 | 232 | .clear 233 | { 234 | clear: both; 235 | } 236 | 237 | .important 238 | { 239 | font-weight: bold; 240 | color: #950B02; 241 | } 242 | 243 | .yes-def { 244 | text-indent: -1000px; 245 | } 246 | 247 | .type-signature { 248 | color: #aaa; 249 | } 250 | 251 | .name, .signature { 252 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 253 | } 254 | 255 | .details { margin-top: 14px; border-left: 2px solid #DDD; } 256 | .details dt { width: 120px; float: left; padding-left: 10px; padding-top: 6px; } 257 | .details dd { margin-left: 70px; } 258 | .details ul { margin: 0; } 259 | .details ul { list-style-type: none; } 260 | .details li { margin-left: 30px; padding-top: 6px; } 261 | .details pre.prettyprint { margin: 0 } 262 | .details .object-value { padding-top: 0; } 263 | 264 | .description { 265 | margin-bottom: 1em; 266 | margin-top: 1em; 267 | } 268 | 269 | .code-caption 270 | { 271 | font-style: italic; 272 | font-size: 107%; 273 | margin: 0; 274 | } 275 | 276 | .source 277 | { 278 | border: 1px solid #ddd; 279 | width: 80%; 280 | overflow: auto; 281 | } 282 | 283 | .prettyprint.source { 284 | width: inherit; 285 | } 286 | 287 | .source code 288 | { 289 | font-size: 100%; 290 | line-height: 18px; 291 | display: block; 292 | padding: 4px 12px; 293 | margin: 0; 294 | background-color: #fff; 295 | color: #4D4E53; 296 | } 297 | 298 | .prettyprint code span.line 299 | { 300 | display: inline-block; 301 | } 302 | 303 | .prettyprint.linenums 304 | { 305 | padding-left: 70px; 306 | -webkit-user-select: none; 307 | -moz-user-select: none; 308 | -ms-user-select: none; 309 | user-select: none; 310 | } 311 | 312 | .prettyprint.linenums ol 313 | { 314 | padding-left: 0; 315 | } 316 | 317 | .prettyprint.linenums li 318 | { 319 | border-left: 3px #ddd solid; 320 | } 321 | 322 | .prettyprint.linenums li.selected, 323 | .prettyprint.linenums li.selected * 324 | { 325 | background-color: lightyellow; 326 | } 327 | 328 | .prettyprint.linenums li * 329 | { 330 | -webkit-user-select: text; 331 | -moz-user-select: text; 332 | -ms-user-select: text; 333 | user-select: text; 334 | } 335 | 336 | .params .name, .props .name, .name code { 337 | color: #4D4E53; 338 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 339 | font-size: 100%; 340 | } 341 | 342 | .params td.description > p:first-child, 343 | .props td.description > p:first-child 344 | { 345 | margin-top: 0; 346 | padding-top: 0; 347 | } 348 | 349 | .params td.description > p:last-child, 350 | .props td.description > p:last-child 351 | { 352 | margin-bottom: 0; 353 | padding-bottom: 0; 354 | } 355 | 356 | .disabled { 357 | color: #454545; 358 | } 359 | -------------------------------------------------------------------------------- /docs/styles/prettify-jsdoc.css: -------------------------------------------------------------------------------- 1 | /* JSDoc prettify.js theme */ 2 | 3 | /* plain text */ 4 | .pln { 5 | color: #000000; 6 | font-weight: normal; 7 | font-style: normal; 8 | } 9 | 10 | /* string content */ 11 | .str { 12 | color: #006400; 13 | font-weight: normal; 14 | font-style: normal; 15 | } 16 | 17 | /* a keyword */ 18 | .kwd { 19 | color: #000000; 20 | font-weight: bold; 21 | font-style: normal; 22 | } 23 | 24 | /* a comment */ 25 | .com { 26 | font-weight: normal; 27 | font-style: italic; 28 | } 29 | 30 | /* a type name */ 31 | .typ { 32 | color: #000000; 33 | font-weight: normal; 34 | font-style: normal; 35 | } 36 | 37 | /* a literal value */ 38 | .lit { 39 | color: #006400; 40 | font-weight: normal; 41 | font-style: normal; 42 | } 43 | 44 | /* punctuation */ 45 | .pun { 46 | color: #000000; 47 | font-weight: bold; 48 | font-style: normal; 49 | } 50 | 51 | /* lisp open bracket */ 52 | .opn { 53 | color: #000000; 54 | font-weight: bold; 55 | font-style: normal; 56 | } 57 | 58 | /* lisp close bracket */ 59 | .clo { 60 | color: #000000; 61 | font-weight: bold; 62 | font-style: normal; 63 | } 64 | 65 | /* a markup tag name */ 66 | .tag { 67 | color: #006400; 68 | font-weight: normal; 69 | font-style: normal; 70 | } 71 | 72 | /* a markup attribute name */ 73 | .atn { 74 | color: #006400; 75 | font-weight: normal; 76 | font-style: normal; 77 | } 78 | 79 | /* a markup attribute value */ 80 | .atv { 81 | color: #006400; 82 | font-weight: normal; 83 | font-style: normal; 84 | } 85 | 86 | /* a declaration */ 87 | .dec { 88 | color: #000000; 89 | font-weight: bold; 90 | font-style: normal; 91 | } 92 | 93 | /* a variable name */ 94 | .var { 95 | color: #000000; 96 | font-weight: normal; 97 | font-style: normal; 98 | } 99 | 100 | /* a function name */ 101 | .fun { 102 | color: #000000; 103 | font-weight: bold; 104 | font-style: normal; 105 | } 106 | 107 | /* Specify class=linenums on a pre to get line numbering */ 108 | ol.linenums { 109 | margin-top: 0; 110 | margin-bottom: 0; 111 | } 112 | -------------------------------------------------------------------------------- /docs/styles/prettify-tomorrow.css: -------------------------------------------------------------------------------- 1 | /* Tomorrow Theme */ 2 | /* Original theme - https://github.com/chriskempson/tomorrow-theme */ 3 | /* Pretty printing styles. Used with prettify.js. */ 4 | /* SPAN elements with the classes below are added by prettyprint. */ 5 | /* plain text */ 6 | .pln { 7 | color: #4d4d4c; } 8 | 9 | @media screen { 10 | /* string content */ 11 | .str { 12 | color: #718c00; } 13 | 14 | /* a keyword */ 15 | .kwd { 16 | color: #8959a8; } 17 | 18 | /* a comment */ 19 | .com { 20 | color: #8e908c; } 21 | 22 | /* a type name */ 23 | .typ { 24 | color: #4271ae; } 25 | 26 | /* a literal value */ 27 | .lit { 28 | color: #f5871f; } 29 | 30 | /* punctuation */ 31 | .pun { 32 | color: #4d4d4c; } 33 | 34 | /* lisp open bracket */ 35 | .opn { 36 | color: #4d4d4c; } 37 | 38 | /* lisp close bracket */ 39 | .clo { 40 | color: #4d4d4c; } 41 | 42 | /* a markup tag name */ 43 | .tag { 44 | color: #c82829; } 45 | 46 | /* a markup attribute name */ 47 | .atn { 48 | color: #f5871f; } 49 | 50 | /* a markup attribute value */ 51 | .atv { 52 | color: #3e999f; } 53 | 54 | /* a declaration */ 55 | .dec { 56 | color: #f5871f; } 57 | 58 | /* a variable name */ 59 | .var { 60 | color: #c82829; } 61 | 62 | /* a function name */ 63 | .fun { 64 | color: #4271ae; } } 65 | /* Use higher contrast and text-weight for printable form. */ 66 | @media print, projection { 67 | .str { 68 | color: #060; } 69 | 70 | .kwd { 71 | color: #006; 72 | font-weight: bold; } 73 | 74 | .com { 75 | color: #600; 76 | font-style: italic; } 77 | 78 | .typ { 79 | color: #404; 80 | font-weight: bold; } 81 | 82 | .lit { 83 | color: #044; } 84 | 85 | .pun, .opn, .clo { 86 | color: #440; } 87 | 88 | .tag { 89 | color: #006; 90 | font-weight: bold; } 91 | 92 | .atn { 93 | color: #404; } 94 | 95 | .atv { 96 | color: #060; } } 97 | /* Style */ 98 | /* 99 | pre.prettyprint { 100 | background: white; 101 | font-family: Consolas, Monaco, 'Andale Mono', monospace; 102 | font-size: 12px; 103 | line-height: 1.5; 104 | border: 1px solid #ccc; 105 | padding: 10px; } 106 | */ 107 | 108 | /* Specify class=linenums on a pre to get line numbering */ 109 | ol.linenums { 110 | margin-top: 0; 111 | margin-bottom: 0; } 112 | 113 | /* IE indents via margin-left */ 114 | li.L0, 115 | li.L1, 116 | li.L2, 117 | li.L3, 118 | li.L4, 119 | li.L5, 120 | li.L6, 121 | li.L7, 122 | li.L8, 123 | li.L9 { 124 | /* */ } 125 | 126 | /* Alternate shading for lines */ 127 | li.L1, 128 | li.L3, 129 | li.L5, 130 | li.L7, 131 | li.L9 { 132 | /* */ } 133 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | // Type definitions for @node-oauth/express-oauth-server 3.0.0 2 | // Project: https://github.com/node-oauth/express-oauth-server 3 | // Definitions by: Arne Schubert 4 | // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped 5 | // TypeScript Version: 2.3 6 | 7 | import * as express from "express"; 8 | import * as OAuth2Server from "@node-oauth/oauth2-server"; 9 | 10 | declare namespace ExpressOAuthServer { 11 | interface Options extends OAuth2Server.ServerOptions { 12 | useErrorHandler?: boolean | undefined; 13 | continueMiddleware?: boolean | undefined; 14 | } 15 | } 16 | 17 | declare class ExpressOAuthServer { 18 | server: OAuth2Server; 19 | 20 | constructor(options: ExpressOAuthServer.Options); 21 | 22 | authenticate( 23 | options?: OAuth2Server.AuthenticateOptions 24 | ): ( 25 | request: express.Request, 26 | response: express.Response, 27 | next: express.NextFunction 28 | ) => Promise; 29 | 30 | authorize( 31 | options?: OAuth2Server.AuthorizeOptions 32 | ): ( 33 | request: express.Request, 34 | response: express.Response, 35 | next: express.NextFunction 36 | ) => Promise; 37 | 38 | token( 39 | options?: OAuth2Server.TokenOptions 40 | ): ( 41 | request: express.Request, 42 | response: express.Response, 43 | next: express.NextFunction 44 | ) => Promise; 45 | } 46 | 47 | export = ExpressOAuthServer; 48 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | 5 | const InvalidArgumentError = require('@node-oauth/oauth2-server/lib/errors/invalid-argument-error'); 6 | const NodeOAuthServer = require('@node-oauth/oauth2-server'); 7 | const Request = require('@node-oauth/oauth2-server').Request; 8 | const Response = require('@node-oauth/oauth2-server').Response; 9 | const UnauthorizedRequestError = require('@node-oauth/oauth2-server/lib/errors/unauthorized-request-error'); 10 | 11 | /** 12 | * Complete, compliant and well tested express wrapper for @node-oauth/oauth2-server in node.js. 13 | * The module provides two middlewares - one for granting tokens and another to authorize them. 14 | * `@node-oauth/express-oauth-server` and, consequently `@node-oauth/oauth2-server`, 15 | * expect the request body to be parsed already. 16 | * The following example uses `body-parser` but you may opt for an alternative library. 17 | * 18 | * @class 19 | * @example 20 | * const bodyParser = require('body-parser'); 21 | * const express = require('express'); 22 | * const OAuthServer = require('@node-oauth/express-oauth-server'); 23 | * 24 | * const app = express(); 25 | * 26 | * app.oauth = new OAuthServer({ 27 | * model: {}, // See https://github.com/node-oauth/node-oauth2-server for specification 28 | * }); 29 | * 30 | * app.use(bodyParser.json()); 31 | * app.use(bodyParser.urlencoded({ extended: false })); 32 | * app.use(app.oauth.authorize()); 33 | * 34 | * app.use(function(req, res) { 35 | * res.send('Secret area'); 36 | * }); 37 | * 38 | * app.listen(3000); 39 | */ 40 | class ExpressOAuthServer { 41 | /** 42 | * Creates a new OAuth2 server that will be bound to this class' middlewares. 43 | * Constructor takes several options as arguments. 44 | * The following describes only options, specific to this module. 45 | * For all other options, please read the docs from `@node-oauth/oauth2-server`: 46 | * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html 47 | * @constructor 48 | * @param options {object=} optional options 49 | * @param options.useErrorHandler {boolean=} If false, an error response will be rendered by this component. 50 | * Set this value to true to allow your own express error handler to handle the error. 51 | * @param options.continueMiddleware {boolean=} The `authorize()` and `token()` middlewares will both render their 52 | * result to the response and end the pipeline. 53 | * next() will only be called if this is set to true. 54 | * **Note:** You cannot modify the response since the headers have already been sent. 55 | * `authenticate()` does not modify the response and will always call next() 56 | */ 57 | constructor(options = {}) { 58 | if (!options.model) { 59 | throw new InvalidArgumentError('Missing parameter: `model`'); 60 | } 61 | 62 | this.useErrorHandler = !!options.useErrorHandler; 63 | delete options.useErrorHandler; 64 | 65 | this.continueMiddleware = !!options.continueMiddleware; 66 | delete options.continueMiddleware; 67 | 68 | this.server = new NodeOAuthServer(options); 69 | } 70 | 71 | /** 72 | * Authentication Middleware. 73 | * Returns a middleware that will validate a token. 74 | * 75 | * @param options {object=} will be passed to the authenticate-handler as options, see linked docs 76 | * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html#authenticate-request-response-options 77 | * @see: https://tools.ietf.org/html/rfc6749#section-7 78 | * @return {function(req, res, next):Promise.} 79 | */ 80 | authenticate(options) { 81 | const fn = async function(req, res, next) { 82 | const request = new Request(req); 83 | const response = new Response(res); 84 | 85 | let token 86 | 87 | try { 88 | token = await this.server.authenticate(request, response, options); 89 | } catch (e) { 90 | return handleError.call(this, e, req, res, null, next); 91 | } 92 | 93 | res.locals.oauth = { token }; 94 | next(); 95 | }; 96 | 97 | return fn.bind(this); 98 | } 99 | 100 | /** 101 | * Authorization Middleware. 102 | * Returns a middleware that will authorize a client to request tokens. 103 | * 104 | * @param options {object=} will be passed to the authorize-handler as options, see linked docs 105 | * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html#authorize-request-response-options 106 | * @see: https://tools.ietf.org/html/rfc6749#section-3.1 107 | * @return {function(req, res, next):Promise.} 108 | */ 109 | authorize(options) { 110 | const fn = async function(req, res, next) { 111 | const request = new Request(req); 112 | const response = new Response(res); 113 | 114 | let code 115 | 116 | try { 117 | code = await this.server.authorize(request, response, options); 118 | } catch (e) { 119 | return handleError.call(this, e, req, res, response, next); 120 | } 121 | 122 | res.locals.oauth = { code }; 123 | if (this.continueMiddleware) { 124 | next(); 125 | } 126 | 127 | return handleResponse.call(this, req, res, response); 128 | }; 129 | 130 | return fn.bind(this); 131 | } 132 | 133 | /** 134 | * Grant Middleware. 135 | * Returns middleware that will grant tokens to valid requests. 136 | * 137 | * @param options {object=} will be passed to the token-handler as options, see linked docs 138 | * @see https://node-oauthoauth2-server.readthedocs.io/en/master/api/oauth2-server.html#token-request-response-options 139 | * @see: https://tools.ietf.org/html/rfc6749#section-3.2 140 | * @return {function(req, res, next):Promise.} 141 | */ 142 | token(options) { 143 | const fn = async function(req, res, next) { 144 | const request = new Request(req); 145 | const response = new Response(res); 146 | 147 | let token 148 | 149 | try { 150 | token = await this.server.token(request, response, options); 151 | } catch (e) { 152 | return handleError.call(this, e, req, res, response, next); 153 | } 154 | 155 | res.locals.oauth = { token }; 156 | if (this.continueMiddleware) { 157 | next(); 158 | } 159 | 160 | return handleResponse.call(this, req, res, response); 161 | }; 162 | 163 | return fn.bind(this); 164 | } 165 | } 166 | 167 | /** 168 | * Handle response. 169 | * @private 170 | */ 171 | const handleResponse = function(req, res, response) { 172 | if (response.status === 302) { 173 | const location = response.headers.location; 174 | delete response.headers.location; 175 | res.set(response.headers); 176 | res.redirect(location); 177 | } else { 178 | res.set(response.headers); 179 | res.status(response.status).send(response.body); 180 | } 181 | }; 182 | 183 | /** 184 | * Handle error. 185 | * @private 186 | */ 187 | const handleError = function(e, req, res, response, next) { 188 | if (this.useErrorHandler === true) { 189 | next(e); 190 | } else { 191 | if (response) { 192 | res.set(response.headers); 193 | } 194 | 195 | res.status(e.code); 196 | 197 | if (e instanceof UnauthorizedRequestError) { 198 | return res.send(); 199 | } 200 | 201 | res.send({ error: e.name, error_description: e.message }); 202 | } 203 | }; 204 | 205 | /** 206 | * Export constructor. 207 | * @private 208 | */ 209 | 210 | module.exports = ExpressOAuthServer; 211 | -------------------------------------------------------------------------------- /jsdoc.conf.json: -------------------------------------------------------------------------------- 1 | { 2 | "tags": { 3 | "allowUnknownTags": true, 4 | "dictionaries": ["jsdoc", "closure"] 5 | }, 6 | "source": { 7 | "include": ["."], 8 | "exclude": [ 9 | ".nyc_output", 10 | "examples", 11 | ".github", 12 | "coverage", 13 | "test", 14 | "docs", 15 | "node_modules" 16 | ], 17 | "includePattern": ".+\\.js(doc|x)?$", 18 | "excludePattern": "(^|\\/|\\\\)_" 19 | }, 20 | "plugins": [ 21 | "plugins/markdown" 22 | ], 23 | "opts": { 24 | "destination": "./docs", 25 | "recurse": true, 26 | "readme": "./README.md" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@node-oauth/express-oauth-server", 3 | "version": "4.1.3", 4 | "description": "OAuth provider for express", 5 | "main": "index.js", 6 | "typings": "index.d.ts", 7 | "scripts": { 8 | "lint": "npx eslint -c .eslintrc ./", 9 | "lint:fix": "npx eslint . --fix", 10 | "test": "NODE_ENV=test ./node_modules/.bin/mocha 'test/**/*_test.js'", 11 | "test-debug": "NODE_ENV=test ./node_modules/.bin/mocha --inspect --debug-brk 'test/**/*_test.js'", 12 | "test:watch": "NODE_ENV=test ./node_modules/.bin/mocha --watch 'test/**/*_test.js'", 13 | "test:coverage": "NODE_ENV=test nyc --reporter=html --reporter=lcov --reporter=text ./node_modules/.bin/mocha 'test/**/*_test.js'", 14 | "build:docs": "jsdoc -c jsdoc.conf.json" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "git://github.com/node-oauth/express-oauth-server.git" 19 | }, 20 | "files": [ 21 | "index.js", 22 | "index.d.ts" 23 | ], 24 | "keywords": [ 25 | "express", 26 | "oauth", 27 | "oauth2", 28 | "@node-oauth", 29 | "oauth2-server" 30 | ], 31 | "contributors": [ 32 | "Nuno Sousa ", 33 | "Jan Küster " 34 | ], 35 | "license": "MIT", 36 | "dependencies": { 37 | "@node-oauth/oauth2-server": "^5.2.0" 38 | }, 39 | "peerDependencies": { 40 | "express": "*" 41 | }, 42 | "devDependencies": { 43 | "body-parser": "^1.20.2", 44 | "eslint": "^8.57.1", 45 | "express": "^5.0.1", 46 | "jsdoc": "^4.0.4", 47 | "mocha": "^11.1.0", 48 | "nyc": "^17.1.0", 49 | "should": "^13.2.3", 50 | "sinon": "^19.0.2", 51 | "supertest": "^7.0.0" 52 | }, 53 | "engines": { 54 | "node": ">=16" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /test/integration/index_test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | 5 | const ExpressOAuthServer = require('../../'); 6 | const InvalidArgumentError = require('@node-oauth/oauth2-server/lib/errors/invalid-argument-error'); 7 | const UnauthorizedRequestError = require('@node-oauth/oauth2-server/lib/errors/unauthorized-request-error'); 8 | const NodeOAuthServer = require('@node-oauth/oauth2-server'); 9 | const bodyparser = require('body-parser'); 10 | const express = require('express'); 11 | const request = require('supertest'); 12 | const should = require('should'); 13 | const sinon = require('sinon'); 14 | 15 | /** 16 | * Test `ExpressOAuthServer`. 17 | */ 18 | 19 | describe('ExpressOAuthServer', function() { 20 | let app; 21 | 22 | beforeEach(function() { 23 | app = express(); 24 | 25 | app.use(bodyparser.json()); 26 | app.use(bodyparser.urlencoded({ extended: false })); 27 | }); 28 | 29 | describe('constructor()', function() { 30 | it('should throw an error if `model` is missing', function() { 31 | try { 32 | new ExpressOAuthServer(); 33 | 34 | should.fail(); 35 | } catch (e) { 36 | e.should.be.an.instanceOf(InvalidArgumentError); 37 | e.message.should.equal('Missing parameter: `model`'); 38 | } 39 | }); 40 | 41 | it('should set the `server`', function() { 42 | const oauth = new ExpressOAuthServer({ model: {} }); 43 | oauth.server.should.be.an.instanceOf(NodeOAuthServer); 44 | }); 45 | }); 46 | 47 | describe('authenticate()', function() { 48 | it('should return an error if `model` is empty', function(done) { 49 | const oauth = new ExpressOAuthServer({ model: {} }); 50 | app.use(oauth.authenticate()); 51 | request(app.listen()) 52 | .get('/') 53 | .expect({ error: 'invalid_argument', error_description: 'Invalid argument: model does not implement `getAccessToken()`' }) 54 | .end(done); 55 | }); 56 | 57 | it('should authenticate the request', function(done) { 58 | const tokenExpires = new Date(); 59 | tokenExpires.setDate(tokenExpires.getDate() + 1); 60 | 61 | const token = { user: {}, accessTokenExpiresAt: tokenExpires }; 62 | const model = { 63 | getAccessToken: function() { 64 | return token; 65 | } 66 | }; 67 | const oauth = new ExpressOAuthServer({ model }); 68 | 69 | app.use(oauth.authenticate()); 70 | 71 | app.use(function(req, res, next) { 72 | res.send(); 73 | 74 | next(); 75 | }); 76 | 77 | request(app.listen()) 78 | .get('/') 79 | .set('Authorization', 'Bearer foobar') 80 | .expect(200) 81 | .end(done); 82 | }); 83 | 84 | it('should return opaque error if the request lacks proper authentication', function(done) { 85 | const model = { 86 | getAccessToken: function() { 87 | throw new UnauthorizedRequestError(); 88 | } 89 | }; 90 | const oauth = new ExpressOAuthServer({ model }); 91 | app.use(oauth.authenticate()); 92 | 93 | request(app.listen()) 94 | .get('/') 95 | .set('Authorization', 'Bearer foobar') 96 | .expect(401, function (err, res) { 97 | (err === null).should.eql(true); 98 | (res.body.error === undefined).should.eql(true); 99 | done(); 100 | }); 101 | }); 102 | 103 | it('should cache the authorization token', function(done) { 104 | const tokenExpires = new Date(); 105 | tokenExpires.setDate(tokenExpires.getDate() + 1); 106 | const token = { user: {}, accessTokenExpiresAt: tokenExpires }; 107 | const model = { 108 | getAccessToken: function() { 109 | return token; 110 | } 111 | }; 112 | const oauth = new ExpressOAuthServer({ model }); 113 | 114 | app.use(oauth.authenticate()); 115 | 116 | const spy = sinon.spy(function(req, res, next) { 117 | res.locals.oauth.token.should.equal(token); 118 | res.send(token); 119 | next(); 120 | }); 121 | app.use(spy); 122 | 123 | request(app.listen()) 124 | .get('/') 125 | .set('Authorization', 'Bearer foobar') 126 | .expect(200, function(err /*, res */){ 127 | spy.called.should.be.True(); 128 | done(err); 129 | }); 130 | }); 131 | }); 132 | 133 | describe('authorize()', function() { 134 | it('should cache the authorization code', function(done) { 135 | const tokenExpires = new Date(); 136 | tokenExpires.setDate(tokenExpires.getDate() + 1); 137 | 138 | const code = { authorizationCode: 123 }; 139 | const model = { 140 | getAccessToken: function() { 141 | return { user: {}, accessTokenExpiresAt: tokenExpires }; 142 | }, 143 | getClient: function() { 144 | return { grants: ['authorization_code'], redirectUris: ['http://example.com'] }; 145 | }, 146 | saveAuthorizationCode: function() { 147 | return code; 148 | } 149 | }; 150 | const oauth = new ExpressOAuthServer({ model, continueMiddleware: true }); 151 | 152 | app.use(oauth.authorize()); 153 | 154 | const spy = sinon.spy(function(req, res, next) { 155 | res.locals.oauth.code.should.equal(code); 156 | next(); 157 | }); 158 | app.use(spy); 159 | 160 | request(app.listen()) 161 | .post('/?state=foobiz') 162 | .set('Authorization', 'Bearer foobar') 163 | .send({ client_id: 12345, response_type: 'code' }) 164 | .expect(302, function(err /*, res */){ 165 | spy.called.should.be.True(); 166 | done(err); 167 | }); 168 | }); 169 | 170 | it('should return an error', function(done) { 171 | const model = { 172 | getAccessToken: function() { 173 | return { user: {}, accessTokenExpiresAt: new Date() }; 174 | }, 175 | getClient: function() { 176 | return { grants: ['authorization_code'], redirectUris: ['http://example.com'] }; 177 | }, 178 | saveAuthorizationCode: function() { 179 | return {}; 180 | } 181 | }; 182 | const oauth = new ExpressOAuthServer({ model }); 183 | 184 | app.use(oauth.authorize()); 185 | 186 | request(app.listen()) 187 | .post('/?state=foobiz') 188 | .set('Authorization', 'Bearer foobar') 189 | .send({ client_id: 12345 }) 190 | .expect(400, function(err, res) { 191 | res.body.error.should.eql('invalid_request'); 192 | res.body.error_description.should.eql('Missing parameter: `response_type`'); 193 | done(err); 194 | }); 195 | }); 196 | 197 | it('should return a `location` header with the code', function(done) { 198 | const model = { 199 | getAccessToken: function() { 200 | return { user: {}, accessTokenExpiresAt: new Date() }; 201 | }, 202 | getClient: function() { 203 | return { grants: ['authorization_code'], redirectUris: ['http://example.com'] }; 204 | }, 205 | saveAuthorizationCode: function() { 206 | return { authorizationCode: 123 }; 207 | } 208 | }; 209 | const oauth = new ExpressOAuthServer({ model }); 210 | 211 | app.use(oauth.authorize()); 212 | 213 | request(app.listen()) 214 | .post('/?state=foobiz') 215 | .set('Authorization', 'Bearer foobar') 216 | .send({ client_id: 12345, response_type: 'code' }) 217 | .expect('location', 'http://example.com/?code=123&state=foobiz') 218 | .end(done); 219 | }); 220 | 221 | it('should use error handler', function(done) { 222 | const model = { 223 | getAccessToken: function() { 224 | return { user: {}, accessTokenExpiresAt: new Date() }; 225 | }, 226 | getClient: function() { 227 | return { grants: ['authorization_code'], redirectUris: ['http://example.com'] }; 228 | }, 229 | saveAuthorizationCode: function() { 230 | return {}; 231 | } 232 | }; 233 | const oauth = new ExpressOAuthServer({ model, useErrorHandler: true }); 234 | 235 | app.use(oauth.authorize()); 236 | app.use(function (err, req, res, next) { 237 | err.status.should.eql(400); 238 | err.name.should.eql('invalid_request'); 239 | err.message.should.eql('Missing parameter: `response_type`'); 240 | (typeof next === 'function').should.eql(true); 241 | done(); 242 | }); 243 | 244 | request(app.listen()) 245 | .post('/?state=foobiz') 246 | .set('Authorization', 'Bearer foobar') 247 | .send({ client_id: 12345 }) 248 | .expect(500, function(err, res) { 249 | (err === null).should.eql(true); 250 | (res.body.error === undefined).should.eql(true); 251 | }); 252 | }); 253 | 254 | it('should return an error if `model` is empty', function(done) { 255 | const oauth = new ExpressOAuthServer({ model: {} }); 256 | 257 | app.use(oauth.authorize()); 258 | 259 | request(app) 260 | .post('/') 261 | .expect({ error: 'invalid_argument', error_description: 'Invalid argument: model does not implement `getClient()`' }) 262 | .end(done); 263 | }); 264 | }); 265 | 266 | describe('token()', function() { 267 | it('should cache the authorization token', function(done) { 268 | const token = { accessToken: 'foobar', client: {}, user: {} }; 269 | const model = { 270 | getClient: function() { 271 | return { grants: ['password'] }; 272 | }, 273 | getUser: function() { 274 | return {}; 275 | }, 276 | saveToken: function() { 277 | return token; 278 | } 279 | }; 280 | const oauth = new ExpressOAuthServer({ model, continueMiddleware: true }); 281 | 282 | app.use(oauth.token()); 283 | const spy = sinon.spy(function(req, res, next) { 284 | res.locals.oauth.token.should.equal(token); 285 | 286 | next(); 287 | }); 288 | app.use(spy); 289 | 290 | request(app.listen()) 291 | .post('/') 292 | .send('client_id=foo&client_secret=bar&grant_type=password&username=qux&password=biz') 293 | .expect({ access_token: 'foobar', token_type: 'Bearer' }) 294 | .expect(200, function(err /*, res */){ 295 | spy.called.should.be.True(); 296 | done(err); 297 | }); 298 | }); 299 | 300 | it('should return an `access_token`', function(done) { 301 | const model = { 302 | getClient: function() { 303 | return { grants: ['password'] }; 304 | }, 305 | getUser: function() { 306 | return {}; 307 | }, 308 | saveToken: function() { 309 | return { accessToken: 'foobar', client: {}, user: {} }; 310 | } 311 | }; 312 | sinon.spy(); 313 | const oauth = new ExpressOAuthServer({ model, continueMiddleware: true }); 314 | 315 | app.use(oauth.token()); 316 | request(app.listen()) 317 | .post('/') 318 | .send('client_id=foo&client_secret=bar&grant_type=password&username=qux&password=biz') 319 | .expect({ access_token: 'foobar', token_type: 'Bearer' }) 320 | .end(done); 321 | }); 322 | 323 | it('should return a `refresh_token`', function(done) { 324 | const model = { 325 | getClient: function() { 326 | return { grants: ['password'] }; 327 | }, 328 | getUser: function() { 329 | return {}; 330 | }, 331 | saveToken: function() { 332 | return { accessToken: 'foobar', client: {}, refreshToken: 'foobiz', user: {} }; 333 | } 334 | }; 335 | const oauth = new ExpressOAuthServer({ model }); 336 | 337 | app.use(oauth.token()); 338 | 339 | request(app.listen()) 340 | .post('/') 341 | .send('client_id=foo&client_secret=bar&grant_type=password&username=qux&password=biz') 342 | .expect({ access_token: 'foobar', refresh_token: 'foobiz', token_type: 'Bearer' }) 343 | .end(done); 344 | }); 345 | 346 | it('should return an error if `model` is empty', function(done) { 347 | const oauth = new ExpressOAuthServer({ model: {} }); 348 | 349 | app.use(oauth.token()) 350 | 351 | request(app.listen()) 352 | .post('/') 353 | .expect({ error: 'invalid_argument', error_description: 'Invalid argument: model does not implement `getClient()`' }) 354 | .end(done); 355 | }); 356 | }); 357 | }); 358 | -------------------------------------------------------------------------------- /test/unit/index_test.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Module dependencies. 3 | */ 4 | 5 | const ExpressOAuthServer = require('../../'); 6 | const Request = require('@node-oauth/oauth2-server').Request; 7 | const Response = require('@node-oauth/oauth2-server').Response; 8 | const express = require('express'); 9 | const request = require('supertest'); 10 | const sinon = require('sinon'); 11 | const should = require('should'); 12 | 13 | /** 14 | * Test `ExpressOAuthServer`. 15 | */ 16 | 17 | describe('ExpressOAuthServer', function() { 18 | let app; 19 | 20 | beforeEach(function() { 21 | app = express(); 22 | }); 23 | 24 | describe('authenticate()', function() { 25 | it('should call `authenticate()`', function(done) { 26 | const oauth = new ExpressOAuthServer({ model: {} }); 27 | 28 | sinon.stub(oauth.server, 'authenticate').returns({}); 29 | 30 | app.use(oauth.authenticate()); 31 | 32 | request(app.listen()) 33 | .get('/') 34 | .end(function() { 35 | oauth.server.authenticate.callCount.should.equal(1); 36 | oauth.server.authenticate.firstCall.args.should.have.length(3); 37 | oauth.server.authenticate.firstCall.args[0].should.be.an.instanceOf(Request); 38 | oauth.server.authenticate.firstCall.args[1].should.be.an.instanceOf(Response); 39 | should.not.exist(oauth.server.authenticate.firstCall.args[2]) 40 | oauth.server.authenticate.restore(); 41 | 42 | done(); 43 | }); 44 | }); 45 | 46 | it('should call `authenticate()` with options', function(done) { 47 | const oauth = new ExpressOAuthServer({ model: {} }); 48 | 49 | sinon.stub(oauth.server, 'authenticate').returns({}); 50 | 51 | app.use(oauth.authenticate({options: true})); 52 | 53 | request(app.listen()) 54 | .get('/') 55 | .end(function() { 56 | oauth.server.authenticate.callCount.should.equal(1); 57 | oauth.server.authenticate.firstCall.args.should.have.length(3); 58 | oauth.server.authenticate.firstCall.args[0].should.be.an.instanceOf(Request); 59 | oauth.server.authenticate.firstCall.args[1].should.be.an.instanceOf(Response); 60 | oauth.server.authenticate.firstCall.args[2].should.eql({options: true}); 61 | oauth.server.authenticate.restore(); 62 | done(); 63 | }); 64 | }); 65 | }); 66 | 67 | describe('authorize()', function() { 68 | it('should call `authorize()` and end middleware execution', function(done) { 69 | const nextMiddleware = sinon.spy() 70 | const oauth = new ExpressOAuthServer({ model: {} }); 71 | 72 | sinon.stub(oauth.server, 'authorize').returns({}); 73 | 74 | app.use(oauth.authorize()); 75 | app.use(nextMiddleware); 76 | 77 | request(app.listen()) 78 | .get('/') 79 | .end(function() { 80 | oauth.server.authorize.callCount.should.equal(1); 81 | oauth.server.authorize.firstCall.args.should.have.length(3); 82 | oauth.server.authorize.firstCall.args[0].should.be.an.instanceOf(Request); 83 | oauth.server.authorize.firstCall.args[1].should.be.an.instanceOf(Response); 84 | should.not.exist(oauth.server.authorize.firstCall.args[2]); 85 | oauth.server.authorize.restore(); 86 | nextMiddleware.called.should.be.false(); 87 | done(); 88 | }); 89 | }); 90 | 91 | it('should call `authorize()` and continue middleware chain', function(done) { 92 | const nextMiddleware = sinon.spy() 93 | const oauth = new ExpressOAuthServer({ model: {}, continueMiddleware: true }); 94 | 95 | sinon.stub(oauth.server, 'authorize').returns({}); 96 | 97 | app.use(oauth.authorize()); 98 | app.use(nextMiddleware); 99 | 100 | request(app.listen()) 101 | .get('/') 102 | .end(function() { 103 | oauth.server.authorize.callCount.should.equal(1); 104 | oauth.server.authorize.firstCall.args.should.have.length(3); 105 | oauth.server.authorize.firstCall.args[0].should.be.an.instanceOf(Request); 106 | oauth.server.authorize.firstCall.args[1].should.be.an.instanceOf(Response); 107 | should.not.exist(oauth.server.authorize.firstCall.args[2]); 108 | oauth.server.authorize.restore(); 109 | nextMiddleware.called.should.be.true(); 110 | nextMiddleware.args[0].length.should.eql(3); 111 | done(); 112 | }); 113 | }); 114 | 115 | it('should call `authorize()` with options', function(done) { 116 | const oauth = new ExpressOAuthServer({ model: {} }); 117 | 118 | sinon.stub(oauth.server, 'authorize').returns({}); 119 | 120 | app.use(oauth.authorize({options: true})); 121 | 122 | request(app.listen()) 123 | .get('/') 124 | .end(function() { 125 | oauth.server.authorize.callCount.should.equal(1); 126 | oauth.server.authorize.firstCall.args.should.have.length(3); 127 | oauth.server.authorize.firstCall.args[0].should.be.an.instanceOf(Request); 128 | oauth.server.authorize.firstCall.args[1].should.be.an.instanceOf(Response); 129 | oauth.server.authorize.firstCall.args[2].should.eql({options: true}); 130 | oauth.server.authorize.restore(); 131 | done(); 132 | }); 133 | }); 134 | }); 135 | 136 | describe('token()', function() { 137 | it('should call `token()` and end middleware chain', function(done) { 138 | const nextMiddleware = sinon.spy() 139 | const oauth = new ExpressOAuthServer({ model: {} }); 140 | 141 | sinon.stub(oauth.server, 'token').returns({}); 142 | 143 | app.use(oauth.token()); 144 | app.use(nextMiddleware); 145 | 146 | request(app.listen()) 147 | .get('/') 148 | .end(function() { 149 | oauth.server.token.callCount.should.equal(1); 150 | oauth.server.token.firstCall.args.should.have.length(3); 151 | oauth.server.token.firstCall.args[0].should.be.an.instanceOf(Request); 152 | oauth.server.token.firstCall.args[1].should.be.an.instanceOf(Response); 153 | should.not.exist(oauth.server.token.firstCall.args[2]); 154 | oauth.server.token.restore(); 155 | nextMiddleware.called.should.be.false(); 156 | done(); 157 | }); 158 | }); 159 | 160 | it('should call `token()` and continue middleware chain', function(done) { 161 | const nextMiddleware = sinon.spy() 162 | const oauth = new ExpressOAuthServer({ model: {}, continueMiddleware: true }); 163 | 164 | sinon.stub(oauth.server, 'token').returns({}); 165 | 166 | app.use(oauth.token()); 167 | app.use(nextMiddleware); 168 | 169 | request(app.listen()) 170 | .get('/') 171 | .end(function() { 172 | oauth.server.token.callCount.should.equal(1); 173 | oauth.server.token.firstCall.args.should.have.length(3); 174 | oauth.server.token.firstCall.args[0].should.be.an.instanceOf(Request); 175 | oauth.server.token.firstCall.args[1].should.be.an.instanceOf(Response); 176 | should.not.exist(oauth.server.token.firstCall.args[2]); 177 | oauth.server.token.restore(); 178 | nextMiddleware.called.should.be.true(); 179 | nextMiddleware.args[0].length.should.eql(3); 180 | done(); 181 | }); 182 | }); 183 | 184 | it('should call `token()` with options', function(done) { 185 | const oauth = new ExpressOAuthServer({ model: {} }); 186 | 187 | sinon.stub(oauth.server, 'token').returns({}); 188 | 189 | app.use(oauth.token({options: true})); 190 | 191 | request(app.listen()) 192 | .get('/') 193 | .end(function() { 194 | oauth.server.token.callCount.should.equal(1); 195 | oauth.server.token.firstCall.args.should.have.length(3); 196 | oauth.server.token.firstCall.args[0].should.be.an.instanceOf(Request); 197 | oauth.server.token.firstCall.args[1].should.be.an.instanceOf(Response); 198 | oauth.server.token.firstCall.args[2].should.eql({options: true}); 199 | oauth.server.token.restore(); 200 | done(); 201 | }); 202 | }); 203 | }); 204 | }); 205 | --------------------------------------------------------------------------------