-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
index.js
386 lines (308 loc) · 10.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
'use strict'
const fp = require('fastify-plugin')
const sodium = require('sodium-native')
const kObj = Symbol('object')
const kCookieOptions = Symbol('cookie options')
// allows us to use property getters and setters as well as get and set methods on session object
const sessionProxyHandler = {
get (target, prop) {
// Calling functions eg request[sessionName].get('key') or request[sessionName].set('key', 'value')
if (typeof target[prop] === 'function') {
return new Proxy(target[prop], {
apply (applyTarget, thisArg, args) {
return Reflect.apply(applyTarget, target, args)
}
})
}
// accessing own properties, eg request[sessionName].changed
if (Object.hasOwn(target, prop)) {
return target[prop]
}
// accessing session property
return target.get(prop)
},
set (target, prop, value) {
// modifying own properties, eg request[sessionName].changed
if (Object.hasOwn(target, prop)) {
target[prop] = value
return true
}
// modifying session property
target.set(prop, value)
return true
}
}
function fastifySecureSession (fastify, options, next) {
if (!Array.isArray(options)) {
options = [options]
}
let defaultSessionName
let defaultSecret
const sessionNames = new Map()
for (const sessionOptions of options) {
const sessionName = sessionOptions.sessionName || 'session'
const cookieName = sessionOptions.cookieName || sessionName
const expiry = sessionOptions.expiry || 86401 // 24 hours
const cookieOptions = sessionOptions.cookieOptions || sessionOptions.cookie || {}
if (cookieOptions.httpOnly === undefined) {
cookieOptions.httpOnly = true
}
let key
if (sessionOptions.secret && !sessionOptions.key) {
if (Buffer.byteLength(sessionOptions.secret) < 32) {
return next(new Error('secret must be at least 32 bytes'))
}
key = Buffer.allocUnsafe(sodium.crypto_secretbox_KEYBYTES)
// static salt to be used for key derivation, not great for security,
// but better than nothing
let salt = Buffer.from('mq9hDxBVDbspDR6nLfFT1g==', 'base64')
if (sessionOptions.salt) {
salt = (Buffer.isBuffer(sessionOptions.salt)) ? sessionOptions.salt : Buffer.from(sessionOptions.salt, 'ascii')
}
if (Buffer.byteLength(salt) !== sodium.crypto_pwhash_SALTBYTES) {
return next(new Error('salt must be length ' + sodium.crypto_pwhash_SALTBYTES))
}
sodium.crypto_pwhash(key,
Buffer.from(sessionOptions.secret),
salt,
sodium.crypto_pwhash_OPSLIMIT_MODERATE,
sodium.crypto_pwhash_MEMLIMIT_MODERATE,
sodium.crypto_pwhash_ALG_DEFAULT)
defaultSecret = sessionOptions.secret
}
if (sessionOptions.key) {
key = sessionOptions.key
if (typeof key === 'string') {
key = Buffer.from(key, 'base64')
} else if (Array.isArray(key)) {
try {
key = key.map(ensureBufferKey)
} catch (error) {
return next(error)
}
} else if (!Buffer.isBuffer(key)) {
return next(new Error('key must be a string or a Buffer'))
}
if (!Array.isArray(key) && isBufferKeyLengthInvalid(key)) {
return next(new Error(`key must be ${sodium.crypto_secretbox_KEYBYTES} bytes`))
} else if (Array.isArray(key) && key.every(isBufferKeyLengthInvalid)) {
return next(new Error(`key lengths must be ${sodium.crypto_secretbox_KEYBYTES} bytes`))
}
const outputHash = Buffer.alloc(sodium.crypto_generichash_BYTES)
if (Array.isArray(key)) {
sodium.crypto_generichash(outputHash, key[0])
} else {
sodium.crypto_generichash(outputHash, key)
}
defaultSecret = outputHash.toString('hex')
}
if (!key) {
return next(new Error('key or secret must specified'))
}
if (!Array.isArray(key)) {
key = [key]
}
// just to add something to the shape
// TODO verify if it helps the perf
fastify.decorateRequest(sessionName, null)
sessionNames.set(sessionName, {
cookieName,
cookieOptions,
key,
expiry
})
if (!defaultSessionName) {
defaultSessionName = sessionName
}
}
fastify.decorate('decodeSecureSession', (cookie, log = fastify.log, sessionName = defaultSessionName) => {
if (cookie === undefined) {
// there is no cookie
log.trace('@fastify/secure-session: there is no cookie, creating an empty session')
return null
}
if (!sessionNames.has(sessionName)) {
throw new Error('Unknown session key.')
}
const { key, expiry } = sessionNames.get(sessionName)
// do not use destructuring or it will deopt
const split = cookie.split(';')
const cyphertextB64 = split[0]
const nonceB64 = split[1]
if (split.length <= 1) {
// the cookie is malformed
log.debug('@fastify/secure-session: the cookie is malformed, creating an empty session')
return null
}
const cipher = Buffer.from(cyphertextB64, 'base64')
const nonce = Buffer.from(nonceB64, 'base64')
if (cipher.length < sodium.crypto_secretbox_MACBYTES) {
// not long enough
log.debug('@fastify/secure-session: the cipher is not long enough, creating an empty session')
return null
}
if (nonce.length !== sodium.crypto_secretbox_NONCEBYTES) {
// the length is not correct
log.debug('@fastify/secure-session: the nonce does not have the required length, creating an empty session')
return null
}
const msg = Buffer.allocUnsafe(cipher.length - sodium.crypto_secretbox_MACBYTES)
let signingKeyRotated = false
const decodeSuccess = key.some((k, i) => {
const decoded = sodium.crypto_secretbox_open_easy(msg, cipher, nonce, k)
signingKeyRotated = decoded && i > 0
return decoded
})
if (!decodeSuccess) {
// unable to decrypt
log.debug('@fastify/secure-session: unable to decrypt, creating an empty session')
return null
}
const parsed = JSON.parse(msg)
if ((parsed.__ts + expiry) * 1000 - Date.now() <= 0) {
// maximum validity is reached, resetting
log.debug('@fastify/secure-session: expiry reached')
return null
}
const session = new Proxy(new Session(parsed), sessionProxyHandler)
session.changed = signingKeyRotated
return session
})
fastify.decorate('createSecureSession', (data) => new Proxy(new Session(data), sessionProxyHandler))
fastify.decorate('encodeSecureSession', (session, sessionName = defaultSessionName) => {
if (!sessionNames.has(sessionName)) {
throw new Error('Unknown session key.')
}
const { key } = sessionNames.get(sessionName)
const nonce = genNonce()
const msg = Buffer.from(JSON.stringify(session[kObj]))
const cipher = Buffer.allocUnsafe(msg.length + sodium.crypto_secretbox_MACBYTES)
sodium.crypto_secretbox_easy(cipher, msg, nonce, key[0])
return cipher.toString('base64') + ';' + nonce.toString('base64')
})
if (fastify.hasPlugin('@fastify/cookie')) {
fastify
.register(fp(addHooks))
} else {
fastify
.register(require('@fastify/cookie'), {
secret: defaultSecret
})
.register(fp(addHooks))
}
next()
function addHooks (fastify, options, next) {
// the hooks must be registered after @fastify/cookie hooks
fastify.addHook('onRequest', (request, reply, next) => {
for (const [sessionName, { cookieName, cookieOptions }] of sessionNames.entries()) {
let cookie = request.cookies[cookieName]
if (cookie !== undefined && cookieOptions.signed === true) {
const unsignedCookie = fastify.unsignCookie(cookie)
if (unsignedCookie.valid === true) {
cookie = unsignedCookie.value
}
}
const result = fastify.decodeSecureSession(cookie, request.log, sessionName)
request[sessionName] = result || new Proxy(new Session({}), sessionProxyHandler)
}
next()
})
fastify.addHook('onSend', (request, reply, payload, next) => {
for (const [sessionName, { cookieName, cookieOptions }] of sessionNames.entries()) {
const session = request[sessionName]
if (!session || !session.changed) {
// nothing to do
request.log.trace('@fastify/secure-session: there is no session or the session didn\'t change, leaving it as is')
continue
} else if (session.deleted) {
request.log.debug('@fastify/secure-session: deleting session')
const tmpCookieOptions = Object.assign(
{},
cookieOptions,
session[kCookieOptions],
{ expires: new Date(0), maxAge: 0 }
)
reply.setCookie(cookieName, '', tmpCookieOptions)
continue
}
request.log.trace('@fastify/secure-session: setting session')
reply.setCookie(
cookieName,
fastify.encodeSecureSession(session, sessionName),
Object.assign({}, cookieOptions, session[kCookieOptions])
)
}
next()
})
next()
}
}
class Session {
constructor (obj) {
this[kObj] = obj
this[kCookieOptions] = null
this.changed = false
this.deleted = false
if (this[kObj].__ts === undefined) {
this[kObj].__ts = Math.round(Date.now() / 1000)
}
}
get (key) {
return this[kObj][key]
}
set (key, value) {
this.changed = true
this[kObj][key] = value
}
delete () {
this.changed = true
this.deleted = true
}
options (opts) {
this[kCookieOptions] = opts
}
data () {
const copy = {
...this[kObj]
}
delete copy.__ts
return copy
}
touch () {
this.changed = true
}
regenerate (ignoredFields) {
for (const key of Object.keys(this[kObj])) {
if (key === '__ts' || (Array.isArray(ignoredFields) && ignoredFields.includes(key))) {
continue
}
delete this[kObj][key]
}
this.changed = true
}
}
function genNonce () {
const buf = Buffer.allocUnsafe(sodium.crypto_secretbox_NONCEBYTES)
sodium.randombytes_buf(buf)
return buf
}
function ensureBufferKey (k) {
if (Buffer.isBuffer(k)) {
return k
}
if (typeof k !== 'string') {
throw new Error('Key must be string or buffer')
}
return Buffer.from(k, 'base64')
}
function isBufferKeyLengthInvalid (k) {
// the key should be strictly equals to sodium.crypto_secretbox_KEYBYTES
// or this will result in a runtime error when encoding the session
return k.length !== sodium.crypto_secretbox_KEYBYTES
}
module.exports = fp(fastifySecureSession, {
fastify: '5.x',
name: '@fastify/secure-session'
})
module.exports.default = fastifySecureSession
module.exports.fastifySecureSession = fastifySecureSession