Skip to content
This repository was archived by the owner on Sep 14, 2022. It is now read-only.

throw error when the user repeatedly call csurf in same middleware #230

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ function csurf (options) {
var ignoreMethod = getIgnoredMethods(ignoreMethods)

return function csrf (req, res, next) {
if (verifyCsurfIsInitializedRepeatedly(req, cookie)) {
return next(new Error('csurf({cookie: true}) or csurf({cookie: {}}}) is repeatedly called with same middleware in the cooke mode, first validation will result in the invalid token'))
}

// validate the configuration against request
if (!verifyConfiguration(req, sessionKey, cookie)) {
return next(new Error('misconfigured csrf'))
Expand Down Expand Up @@ -295,3 +299,24 @@ function verifyConfiguration (req, sessionKey, cookie) {

return true
}

/**
* Check csurf initialization status.
* This function is only used in cookie mode.
* @param {IncomingMessage} req
* @param {Object} cookie
* @returns {boolean} csurf is initializaed repeatedly or not in cookie mode.
* @api private
*/

function verifyCsurfIsInitializedRepeatedly (req, cookie) {
if (!cookie) {
return false
}
var _name = '@@isCsurfInitialized@@'
if (!req[_name]) {
req[_name] = true
return false
}
return true
}
14 changes: 14 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,20 @@ describe('csurf', function () {
.expect(200, done)
})
})

it('should return error when call csurf twice in middleware.', function (done) {
var app = connect()
app.use(cookieParser('keyboard cat'))
app.use(csurf({ cookie: true }))
app.use(csurf({ cookie: true }))
app.use(function (req, res) {
res.end(req.csrfToken() || 'none')
})

request(app)
.get('/')
.expect(500, /csurf\({cookie: true}\) or csurf\({cookie: {}}}\) is repeatedly called with same middleware in the cooke mode, first validation will result in the invalid token/, done)
})
})

describe('when an object', function () {
Expand Down