Skip to content

Commit

Permalink
Use crypto.timingSafeEqual() instead of secure-compare module (#40)
Browse files Browse the repository at this point in the history
* Use crypto.timingSafeEqual()

* Just try/catch Node core api
  • Loading branch information
Yuji Sugiura committed May 28, 2020
1 parent 146f88c commit 39353b1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,7 @@
"tsd": "^0.11.0"
},
"dependencies": {
"fastify-plugin": "^2.0.0",
"secure-compare": "^3.0.1"
"fastify-plugin": "^2.0.0"
},
"tsd": {
"directory": "test",
Expand Down
12 changes: 11 additions & 1 deletion plugin.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict'

const crypto = require('crypto')
const fp = require('fastify-plugin')
const compare = require('secure-compare')

function factory (options) {
const defaultOptions = {
Expand Down Expand Up @@ -80,6 +80,16 @@ function authenticate (keys, key) {
return keys.findIndex((a) => compare(a, key)) !== -1
}

// perform constant-time comparison to prevent timing attacks
function compare (a, b) {
try {
// may throw if they have different length, can't convert to Buffer, etc...
return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
} catch {
return false
}
}

function plugin (fastify, options, next) {
fastify.addHook('onRequest', factory(options))
next()
Expand Down

0 comments on commit 39353b1

Please sign in to comment.