Skip to content

Commit 39353b1

Browse files
author
Yuji Sugiura
authored
Use crypto.timingSafeEqual() instead of secure-compare module (#40)
* Use crypto.timingSafeEqual() * Just try/catch Node core api
1 parent 146f88c commit 39353b1

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

Diff for: package.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,7 @@
3737
"tsd": "^0.11.0"
3838
},
3939
"dependencies": {
40-
"fastify-plugin": "^2.0.0",
41-
"secure-compare": "^3.0.1"
40+
"fastify-plugin": "^2.0.0"
4241
},
4342
"tsd": {
4443
"directory": "test",

Diff for: plugin.js

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use strict'
22

3+
const crypto = require('crypto')
34
const fp = require('fastify-plugin')
4-
const compare = require('secure-compare')
55

66
function factory (options) {
77
const defaultOptions = {
@@ -80,6 +80,16 @@ function authenticate (keys, key) {
8080
return keys.findIndex((a) => compare(a, key)) !== -1
8181
}
8282

83+
// perform constant-time comparison to prevent timing attacks
84+
function compare (a, b) {
85+
try {
86+
// may throw if they have different length, can't convert to Buffer, etc...
87+
return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
88+
} catch {
89+
return false
90+
}
91+
}
92+
8393
function plugin (fastify, options, next) {
8494
fastify.addHook('onRequest', factory(options))
8595
next()

0 commit comments

Comments
 (0)