[
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: [MichielDeMey]\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\n\nupdates:\n  # Maintain dependencies for npm\n  - package-ecosystem: \"npm\"\n    directory: \"/\"\n    schedule:\n      interval: \"daily\"\n    labels:\n      - 'dependencies'\n"
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "content": "name: \"CodeQL\"\n\non:\n  push:\n    branches: [ master ]\n  pull_request:\n    # The branches below must be a subset of the branches above\n    branches: [ master ]\n  schedule:\n    - cron: '42 15 * * 5'\n\njobs:\n  analyze:\n    name: Analyze\n    runs-on: ubuntu-latest\n\n    strategy:\n      fail-fast: false\n      matrix:\n        language: [ 'javascript' ]\n        # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]\n        # Learn more:\n        # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed\n\n    steps:\n    - name: Checkout repository\n      uses: actions/checkout@v2\n\n    # Initializes the CodeQL tools for scanning.\n    - name: Initialize CodeQL\n      uses: github/codeql-action/init@v1\n      with:\n        languages: ${{ matrix.language }}\n        # If you wish to specify custom queries, you can do so here or in a config file.\n        # By default, queries listed here will override any specified in a config file.\n        # Prefix the list here with \"+\" to use these queries and those in the config file.\n        # queries: ./path/to/local/query, your-org/your-repo/queries@main\n\n    # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).\n    # If this step fails, then you should remove it and run the build manually (see below)\n    - name: Autobuild\n      uses: github/codeql-action/autobuild@v1\n\n    # ℹ️ Command-line programs to run using the OS shell.\n    # 📚 https://git.io/JvXDl\n\n    # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines\n    #    and modify them (or add more) to build your code if your project\n    #    uses a compiled language\n\n    #- run: |\n    #   make bootstrap\n    #   make release\n\n    - name: Perform CodeQL Analysis\n      uses: github/codeql-action/analyze@v1\n"
  },
  {
    "path": ".github/workflows/node.js.yml",
    "content": "# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node\n# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions\n\nname: Node.js CI\n\non:\n  push:\n    branches: [ master ]\n  pull_request:\n    branches: [ master ]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node-version: [10.x, 12.x, 14.x, 15.x, 16.x, 18.x]\n        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/\n\n    steps:\n    - uses: actions/checkout@v2\n    - name: Use Node.js ${{ matrix.node-version }}\n      uses: actions/setup-node@v1\n      with:\n        node-version: ${{ matrix.node-version }}\n    - run: npm install # npm ci is not available on all NPM versions\n    - run: npm run build --if-present\n    - run: npm test\n    - name: Upload Codecov\n      uses: codecov/codecov-action@v1\n      with:\n        token: ${{ secrets.CODECOV_TOKEN }}\n        directory: coverage/\n        fail_ci_if_error: true\n"
  },
  {
    "path": ".gitignore",
    "content": "*.log\ncoverage/\nnode_modules/\n.nyc_output\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "Copyright (c) 2015 Michiel De Mey <de.mey.michiel@gmail.com>\n\n\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\n\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\n\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# Express JWT Permissions\n\n[![Node.js CI](https://github.com/MichielDeMey/express-jwt-permissions/workflows/Node.js%20CI/badge.svg)](https://github.com/MichielDeMey/express-jwt-permissions/actions?query=workflow%3A%22Node.js+CI%22)\n[![CodeQL](https://github.com/MichielDeMey/express-jwt-permissions/actions/workflows/codeql-analysis.yml/badge.svg?branch=master)](https://github.com/MichielDeMey/express-jwt-permissions/actions/workflows/codeql-analysis.yml)\n[![codecov](https://codecov.io/gh/MichielDeMey/express-jwt-permissions/branch/master/graph/badge.svg?token=UXWXehGp1x)](https://codecov.io/gh/MichielDeMey/express-jwt-permissions)\n[![npm](https://img.shields.io/npm/dm/express-jwt-permissions.svg?maxAge=2592000)](https://www.npmjs.com/package/express-jwt-permissions)\n[![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/MichielDeMey)\n\n[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)\n\nMiddleware that checks JWT tokens for permissions, recommended to be used in conjunction with [express-jwt](https://github.com/auth0/express-jwt).\n\n## Install\n\n```\nnpm install express-jwt-permissions --save\n```\n\n## Usage\n\nThis middleware assumes you already have a JWT authentication middleware such as [express-jwt](https://github.com/auth0/express-jwt).\n\nThe middleware will check a decoded JWT token to see if a token has permissions to make a certain request.\n\nPermissions should be described as an array of strings inside the JWT token, or as a space-delimited [OAuth 2.0 Access Token Scope](https://tools.ietf.org/html/rfc6749#section-3.3) string.\n\n```json\n\"permissions\": [\n  \"status\",\n  \"user:read\",\n  \"user:write\"\n]\n```\n\n```json\n\"scope\": \"status user:read user:write\"\n```\n\nIf your JWT structure looks different you should map or reduce the results to produce a simple Array or String of permissions.\n\n### Using permission Array\nTo verify a permission for all routes using an array:\n\n```javascript\nvar guard = require('express-jwt-permissions')()\n\napp.use(guard.check('admin'))\n```\n\nIf you require different permissions per route, you can set the middleware per route.\n\n```javascript\nvar guard = require('express-jwt-permissions')()\n\napp.get('/status', guard.check('status'), function(req, res) { ... })\napp.get('/user', guard.check(['user:read']), function(req, res) { ... })\n```\n\nLogical combinations of required permissions can be made using nested arrays.\n\nSingle string\n```js\n// Required: \"admin\"\napp.use(guard.check(\n  'admin'\n))\n```\n\nArray of strings\n\n```javascript\n// Required: \"read\" AND \"write\"\napp.use(guard.check(\n  ['read', 'write']\n))\n```\n\nArray of arrays of strings\n\n```javascript\n// Required: \"read\" OR \"write\"\napp.use(guard.check([\n  ['read'],\n  ['write']\n]))\n\n// Required: \"admin\" OR (\"read\" AND \"write\")\napp.use(guard.check([\n  ['admin'],\n  ['read', 'write']\n]))\n```\n\n### Configuration\nTo set where the module can find the user property (default `req.user`) you can set the `requestProperty` option.\n\nTo set where the module can find the permissions property inside the `requestProperty` object (default `permissions`), set the `permissionsProperty` option.\n\nExample:\n\nConsider you've set your permissions as `scope` on `req.identity`, your JWT structure looks like:\n\n```json\n\"scope\": \"user:read user:write\"\n```\n\nYou can pass the configuration into the module:\n\n```javascript\nvar guard = require('express-jwt-permissions')({\n  requestProperty: 'identity',\n  permissionsProperty: 'scope'\n})\n\napp.use(guard.check('user:read'))\n```\n\n## Error handling\n\nThe default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:\n\n```javascript\napp.use(guard.check('admin'))\n\napp.use(function (err, req, res, next) {\n  if (err.code === 'permission_denied') {\n    res.status(403).send('Forbidden');\n  }\n});\n```\n\n**Note** that your error handling middleware should be defined after the jwt-permissions middleware.\n\n## Excluding paths\n\nThis library has integration with [express-unless](https://github.com/jfromaniello/express-unless) to allow excluding paths, please refer to their [usage](https://github.com/jfromaniello/express-unless#usage).\n\n```javascript\nconst checkForPermissions = guard\n  .check(['admin'])\n  .unless({ path: '/not-secret' })\n\napp.use(checkForPermissions)\n```\n\n## Tests\n\n```\n$ npm install\n$ npm test\n```\n\n## License\n\nThis project is licensed under the MIT license. See the [LICENSE](LICENSE.txt) file for more info.\n"
  },
  {
    "path": "error.d.ts",
    "content": "declare class UnauthorizedError extends Error {\n  public code: string;\n  public status: number;\n  public inner: Error;\n\n  public constructor(code: string, error: Error);\n}\n\nexport = UnauthorizedError;\n"
  },
  {
    "path": "error.js",
    "content": "const util = require('util')\n\nmodule.exports = function UnauthorizedError (code, error) {\n  Error.captureStackTrace(this, this.constructor)\n\n  this.name = this.constructor.name\n  this.message = error.message\n\n  this.code = code\n  this.status = 403\n  this.inner = error\n}\n\nutil.inherits(module.exports, Error)\n"
  },
  {
    "path": "index.d.ts",
    "content": "import { RequestHandler } from \"express\";\n\ndeclare interface GuardOptions {\n  requestProperty?: string\n  permissionsProperty?: string\n}\n\ndeclare class Guard {\n  public constructor(options?: GuardOptions);\n\n  public check(required: string | string[] | string[][]): RequestHandler;\n}\n\ndeclare function guardFactory(options?: GuardOptions): Guard;\n\ndeclare namespace guardFactory {\n}\n\nexport = guardFactory;\n"
  },
  {
    "path": "index.js",
    "content": "const util = require('util')\nconst get = require('lodash.get')\n\nconst UnauthorizedError = require('./error')\nconst PermissionError = new UnauthorizedError(\n  'permission_denied', { message: 'Permission denied' }\n)\n\nconst Guard = function (options) {\n  const defaults = {\n    requestProperty: 'user',\n    permissionsProperty: 'permissions'\n  }\n\n  this._options = Object.assign({}, defaults, options)\n}\n\nfunction isString (value) {\n  return typeof value === 'string'\n}\n\nfunction isArray (value) {\n  return value instanceof Array\n}\n\nGuard.prototype = {\n\n  check: function (required) {\n    if (isString(required)) {\n      required = [[required]]\n    } else if (isArray(required) && required.every(isString)) {\n      required = [required]\n    }\n\n    const _middleware = function _middleware (req, res, next) {\n      const self = this\n      const options = self._options\n\n      if (!options.requestProperty) {\n        return next(new UnauthorizedError('request_property_undefined', {\n          message: 'requestProperty hasn\\'t been defined. Check your configuration.'\n        }))\n      }\n\n      const user = get(req, options.requestProperty, undefined)\n      if (!user) {\n        return next(new UnauthorizedError('user_object_not_found', {\n          message: util.format('user object \"%s\" was not found. Check your configuration.', options.requestProperty)\n        }))\n      }\n\n      let permissions = get(user, options.permissionsProperty, undefined)\n      if (!permissions) {\n        return next(new UnauthorizedError('permissions_not_found', {\n          message: 'Could not find permissions for user. Bad configuration?'\n        }))\n      }\n\n      if (typeof permissions === 'string') {\n        permissions = permissions.split(' ')\n      }\n\n      if (!Array.isArray(permissions)) {\n        return next(new UnauthorizedError('permissions_invalid', {\n          message: 'Permissions should be an Array or String. Bad format?'\n        }))\n      }\n\n      const sufficient = required.some(function (required) {\n        return required.every(function (permission) {\n          return permissions.indexOf(permission) !== -1\n        })\n      })\n\n      next(!sufficient ? PermissionError : null)\n    }.bind(this)\n\n    _middleware.unless = require('express-unless').unless\n\n    return _middleware\n  }\n}\n\nmodule.exports = function (options) {\n  return new Guard(options)\n}\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"express-jwt-permissions\",\n  \"version\": \"1.3.7\",\n  \"description\": \"Express middleware for JWT permissions\",\n  \"main\": \"./index.js\",\n  \"typings\": \"index.d.ts\",\n  \"scripts\": {\n    \"lint\": \"standard\",\n    \"test\": \"npm run lint && tap test/*.js --100 --coverage-report=lcovonly\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/MichielDeMey/express-jwt-permissions.git\"\n  },\n  \"bugs\": \"https://github.com/MichielDeMey/express-jwt-permissions/issues\",\n  \"keywords\": [\n    \"express\",\n    \"middleware\",\n    \"JWT\",\n    \"permissions\",\n    \"authorization\",\n    \"token\",\n    \"security\"\n  ],\n  \"author\": \"Michiel De Mey <de.mey.michiel@gmail.com> (https://demey.io)\",\n  \"contributors\": [\n    {\n      \"name\": \"Gilles De Mey\",\n      \"email\": \"gilles.de.mey@gmail.com\"\n    }\n  ],\n  \"license\": \"MIT\",\n  \"devDependencies\": {\n    \"@types/express\": \"^4.17.14\",\n    \"standard\": \"^17.0.0\",\n    \"tap\": \"^16.3.0\"\n  },\n  \"dependencies\": {\n    \"express-unless\": \"^2.0.0\",\n    \"lodash.get\": \"^4.4.2\"\n  },\n  \"engines\": {\n    \"node\": \">=0.10\"\n  }\n}\n"
  },
  {
    "path": "test/test.js",
    "content": "const tap = require('tap')\nconst test = tap.test\nconst guard = require('../index')()\n\nconst res = {}\n\ntest('no user object present, should throw', function (t) {\n  const req = {}\n  guard.check(['ping'])(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n    t.ok(err.code === 'user_object_not_found', 'correct error code')\n    t.end()\n  })\n})\n\ntest('incorrect user object present, should throw', function (t) {\n  t.plan(1)\n  const guard = require('../index')({\n    requestProperty: 'identity',\n    permissionsProperty: 'bar'\n  })\n  const req = { user: { scopes: ['foobar'] } }\n  guard.check('ping')(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n    t.ok(err.code === 'user_object_not_found', 'correct error code')\n    t.end()\n  })\n})\n\ntest('valid permissions [Array] notation', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: ['ping'] } }\n  guard.check(['ping'])(req, res, t.error)\n})\n\ntest('valid multiple permissions', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: ['foo', 'bar'] } }\n  guard.check(['foo', 'bar'])(req, res, t.error)\n})\n\ntest('valid permissions [String] notation', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: ['ping'] } }\n  guard.check('ping')(req, res, t.error)\n})\n\ntest('invalid permissions [Object] notation', function (t) {\n  const req = { user: { permissions: { ping: true } } }\n  guard.check('ping')(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n    t.ok(err.code === 'permissions_invalid', 'correct error code')\n    t.end()\n  })\n})\n\ntest('permissions array not found', function (t) {\n  const req = { user: {} }\n  guard.check('ping')(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n    t.ok(err.code === 'permissions_not_found', 'correct error code')\n    t.end()\n  })\n})\n\ntest('invalid requestProperty with custom options', function (t) {\n  const guard = require('../index')({\n    requestProperty: undefined,\n    permissionsProperty: 'scopes'\n  })\n  const req = { identity: { scopes: ['ping'] } }\n  guard.check('ping')(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n\n    t.ok(err.code === 'request_property_undefined', 'correct error code')\n    t.end()\n  })\n})\n\ntest('valid permissions with custom options', function (t) {\n  t.plan(1)\n  const guard = require('../index')({\n    requestProperty: 'identity',\n    permissionsProperty: 'scopes'\n  })\n  const req = { identity: { scopes: ['ping'] } }\n  guard.check('ping')(req, res, t.error)\n})\n\ntest('valid requestProperty of level 1', function (t) {\n  t.plan(1)\n  const guard = require('../index')({\n    requestProperty: 'identity',\n    permissionsProperty: 'scopes'\n  })\n  const req = { identity: { scopes: ['ping'] } }\n  guard.check('ping')(req, res, t.error)\n})\n\ntest('valid requestProperty of level n', function (t) {\n  t.plan(1)\n  const guard = require('../index')({\n    requestProperty: 'token.identity',\n    permissionsProperty: 'scopes'\n  })\n  const req = { token: { identity: { scopes: ['ping'] } } }\n  guard.check('ping')(req, res, t.error)\n})\n\ntest('invalid permissions [Array] notation', function (t) {\n  const req = { user: { permissions: ['ping'] } }\n  guard.check('foo')(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n\n    t.ok(err.code === 'permission_denied', 'correct error code')\n    t.end()\n  })\n})\n\ntest('invalid required multiple permissions', function (t) {\n  const req = { user: { permissions: ['foo'] } }\n  guard.check(['foo', 'bar'])(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n\n    t.ok(err.code === 'permission_denied', 'correct error code')\n    t.end()\n  })\n})\n\ntest('valid permissions with deep permissionsProperty', function (t) {\n  t.plan(1)\n  const guard = require('../index')({\n    requestProperty: 'identity',\n    permissionsProperty: 'scopes.permissions'\n  })\n  const req = { identity: { scopes: { permissions: ['ping'] } } }\n  guard.check('ping')(req, res, t.error)\n})\n\ntest('invalid permissions with deep permissionsProperty', function (t) {\n  const guard = require('../index')({\n    requestProperty: 'identity',\n    permissionsProperty: 'scopes.permissions'\n  })\n  const req = { identity: { scopes: { permissions: ['ping'] } } }\n  guard.check('foo')(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n\n    t.ok(err.code === 'permission_denied', 'correct error code')\n    t.end()\n  })\n})\n\ntest('valid permissions with very deep permissionsProperty', function (t) {\n  t.plan(1)\n  const guard = require('../index')({\n    requestProperty: 'identity',\n    permissionsProperty: 'scopes.permissions.this.is.deep'\n  })\n  const req = { identity: { scopes: { permissions: { this: { is: { deep: ['ping'] } } } } } }\n  guard.check('ping')(req, res, t.error)\n})\n\ntest('OAuth space-delimited scopes', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: 'ping foo bar' } }\n  guard.check('foo')(req, res, t.error)\n})\n\ntest('valid boolean \"OR\" with single required permissions', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: 'ping foo bar' } }\n  guard.check([['nope'], ['ping']])(req, res, t.error)\n})\n\ntest('valid boolean \"OR\" with single and multiple required permissions', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: 'ping foo bar' } }\n  guard.check([['nope'], ['ping', 'foo']])(req, res, t.error)\n})\n\ntest('invalid boolean \"OR\" with single required permissions', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: 'ping foo bar' } }\n  guard.check([['nope'], ['nada']])(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n\n    t.ok(err.code === 'permission_denied', 'correct error code')\n    t.end()\n  })\n})\n\ntest('invalid boolean \"OR\" with multiple partial required permissions', function (t) {\n  t.plan(1)\n  const req = { user: { permissions: 'ping foo bar' } }\n  guard.check([['nope', 'foo'], ['nada', 'bar']])(req, res, function (err) {\n    if (!err) return t.end('should throw an error')\n\n    t.ok(err.code === 'permission_denied', 'correct error code')\n    t.end()\n  })\n})\n\ntest('express unless integration', function (t) {\n  t.plan(2)\n\n  const skipReq = { user: { permissions: [] }, url: '/not-secret' }\n  guard\n    .check(['foo'])\n    .unless({ path: '/not-secret' })(skipReq, res, t.error)\n\n  const doNotSkipReq = { user: { permissions: [] }, url: '/secret' }\n  guard\n    .check(['foo'])\n    .unless({ path: '/not-secret' })(doNotSkipReq, res, function (err) {\n      if (!err) return t.end('should throw an error')\n\n      t.ok(err.code === 'permission_denied', 'correct error code')\n      t.end()\n    })\n})\n"
  }
]