Skip to content

Commit

Permalink
Refactor to koa middleware style (#61)
Browse files Browse the repository at this point in the history
* update .gitignore file 🐞 ..

* update LICENSE 🗝 ..

* cleanup ❌ ..

* linter rules 💅🏻 ..

* update travis pipeline 🏗 ..

* better pkg.json 🎗 ..

* refactor src to koa-mw-style 🚀 ..

* update test code 🧪 ..

* update README.md 📋 ..

* add yarn locks 🔮 ..

* fix xo linter rules --pkg.json 🎗 ..
  • Loading branch information
3imed-jaberi authored Jul 1, 2022
1 parent 9219e70 commit 3d5a2dc
Show file tree
Hide file tree
Showing 13 changed files with 173 additions and 141 deletions.
9 changes: 0 additions & 9 deletions .babelrc

This file was deleted.

9 changes: 0 additions & 9 deletions .editorconfig

This file was deleted.

5 changes: 4 additions & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"extends": ["eslint:recommended", "plugin:node/recommended"],
"extends": [
"eslint:recommended",
"plugin:node/recommended"
],
"rules": {
"no-unsafe-finally": "warn",
"no-cond-assign": "warn",
Expand Down
31 changes: 21 additions & 10 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,12 +1,23 @@

# osx
# OS #
###################
.DS_Store
.idea
Thumbs.db
tmp/
temp/


# Node.js #
###################
node_modules
package-lock.json
npm-debug.log
yarn-debug.log
yarn-error.log


# project
node_modules/
logs
*.log
npm-debug.log*
*.idea
coverage/
lib
# NYC #
###################
coverage
*.lcov
.nyc_output
1 change: 0 additions & 1 deletion .npmignore

This file was deleted.

5 changes: 3 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
language: node_js
node_js:
- '8'
- '10'
- 10
- 12
- 14
script:
npm run test-coverage
after_success:
Expand Down
21 changes: 16 additions & 5 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,9 +1,20 @@
The MIT License
(The MIT License)

Copyright (c) 2014- Jonathan Ong <[email protected]> and Nick Baugh <[email protected]>
Copyright (c) 2014 Jonathan Ong <[email protected]> && Nick Baugh <[email protected]>

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:
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 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.
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.
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ yarn add koa-csrf
app.use(bodyParser());

// add the CSRF middleware
app.use(new CSRF({
app.use(CSRF({
invalidTokenMessage: 'Invalid CSRF token',
invalidTokenStatusCode: 403,
excludedMethods: [ 'GET', 'HEAD', 'OPTIONS' ],
Expand Down Expand Up @@ -121,9 +121,10 @@ yarn add koa-csrf

## Contributors

| Name | Website |
| -------------- | --------------------------------- |
| **Nick Baugh** | <https://github.com/niftylettuce> |
| Name | Website |
| --------------- | --------------------------------- |
| **Nick Baugh** | <https://github.com/niftylettuce> |
| **Imed Jaberi** | <https://www.3imed-jaberi.com/> |


## License
Expand Down
101 changes: 101 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*!
* koa-csrf
*
* Copyright(c) 2020 koa contributors
* MIT Licensed
*/

'use strict';

/**
* Module dependencies.
*/
const csrf = require('csrf');

/**
* Expose `CSRF()`.
*/

module.exports = CSRF;

/**
*
*/
function CSRF(opts = {}) {
const tokens = csrf(opts);

opts = {
invalidTokenMessage: 'Invalid CSRF token',
invalidTokenStatusCode: 403,
excludedMethods: ['GET', 'HEAD', 'OPTIONS'],
disableQuery: false,
...opts
};

return function(ctx, next) {
Object.defineProperty(ctx, 'csrf', {
get: () => {
if (ctx._csrf) {
return ctx._csrf;
}

if (!ctx.session) {
return null;
}

if (!ctx.session.secret) {
ctx.session.secret = tokens.secretSync();
}

ctx._csrf = tokens.create(ctx.session.secret);

return ctx._csrf;
}
});

Object.defineProperty(ctx.response, 'csrf', {
get: () => ctx.csrf
});

if (opts.excludedMethods.indexOf(ctx.method) !== -1) {
return next();
}

if (!ctx.session.secret) {
ctx.session.secret = tokens.secretSync();
}

const bodyToken =
ctx.request.body && typeof ctx.request.body._csrf === 'string'
? ctx.request.body._csrf
: false;

const token =
bodyToken ||
(!this.opts.disableQuery && ctx.query && ctx.query._csrf) ||
ctx.get('csrf-token') ||
ctx.get('xsrf-token') ||
ctx.get('x-csrf-token') ||
ctx.get('x-xsrf-token');

if (!token) {
return ctx.throw(
opts.invalidTokenStatusCode,
typeof opts.invalidTokenMessage === 'function'
? opts.invalidTokenMessage(ctx)
: opts.invalidTokenMessage
);
}

if (!tokens.verify(ctx.session.secret, token)) {
return ctx.throw(
opts.invalidTokenStatusCode,
typeof opts.invalidTokenMessage === 'function'
? opts.invalidTokenMessage(ctx)
: opts.invalidTokenMessage
);
}

return next();
};
}
5 changes: 3 additions & 2 deletions test/test.js → index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const session = require('koa-generic-session');
const convert = require('koa-convert');
const supertest = require('supertest');

const CSRF = require('..');
const CSRF = require('.');

const tokenRegExp = /^\w+-[\w+/-]+/;

Expand All @@ -17,7 +17,8 @@ test.before.cb(t => {
app.keys = ['a', 'b'];
app.use(convert(session()));
app.use(bodyParser());
app.use(new CSRF());
// eslint-disable-next-line new-cap
app.use(CSRF());
app.use((ctx, next) => {
if (!['GET', 'POST'].includes(ctx.method)) return next();
if (ctx.method === 'GET') {
Expand Down
32 changes: 19 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,17 @@
"name": "Nick Baugh",
"email": "[email protected]",
"url": "https://github.com/niftylettuce"
},
{
"name": "Imed Jaberi",
"email": "[email protected]",
"url": "https://www.3imed-jaberi.com/"
}
],
"dependencies": {
"csrf": "^3.1.0"
},
"devDependencies": {
"@babel/cli": "^7.6.0",
"@babel/core": "^7.6.0",
"@babel/preset-env": "^7.6.0",
"@commitlint/cli": "latest",
"@commitlint/config-conventional": "latest",
"ava": "2.3.0",
Expand All @@ -50,10 +52,10 @@
"xo": "latest"
},
"engines": {
"node": ">= 6.4"
"node": ">= 10"
},
"files": [
"lib"
"index.js"
],
"homepage": "https://github.com/koajs/csrf",
"husky": {
Expand All @@ -71,6 +73,7 @@
"koa@2",
"koa@next",
"koanext",
"middelware",
"next",
"request",
"security",
Expand All @@ -91,7 +94,7 @@
"git add"
]
},
"main": "lib/index.js",
"main": "index.js",
"remarkConfig": {
"plugins": [
"preset-github"
Expand All @@ -100,20 +103,23 @@
"repository": "koajs/csrf",
"scripts": {
"ava": "cross-env NODE_ENV=test ava",
"build": "npm run build:clean && npm run build:lib",
"build:clean": "rimraf lib",
"build:lib": "babel src --out-dir lib",
"coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov",
"lint": "xo && remark . -qfo && eslint lib",
"lint": "xo --fix && remark . -qfo && eslint index.*",
"nyc": "cross-env NODE_ENV=test nyc ava",
"test": "npm run build && npm run lint && npm run ava",
"test-coverage": "npm run build && npm run lint && npm run nyc"
"test": "npm run lint && npm run ava",
"test-coverage": "npm run lint && npm run nyc"
},
"xo": {
"prettier": true,
"space": true,
"extends": [
"xo-lass"
]
],
"rules": {
"node/no-mixed-requires": "off",
"node/no-new-require": "off",
"node/no-path-concat": "off",
"unicorn/prevent-abbreviations": "off"
}
}
}
Loading

0 comments on commit 3d5a2dc

Please sign in to comment.