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