forked from fastify/session
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fastifySession.js
276 lines (244 loc) · 7.93 KB
/
fastifySession.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
'use strict'
const fp = require('fastify-plugin')
const idGenerator = require('./idGenerator')()
const Store = require('./store')
const Session = require('./session')
const isConnectionSecure = require('./isConnectionSecure')
function fastifySession (fastify, options, next) {
const error = checkOptions(options)
if (error) {
return next(error)
}
options = ensureDefaults(options)
const sessionStore = options.store
const cookieSigner = options.signer
const cookieName = options.cookieName
const cookiePrefix = options.cookiePrefix
const hasCookiePrefix = typeof cookiePrefix === 'string' && cookiePrefix.length !== 0
const cookiePrefixLength = hasCookiePrefix && cookiePrefix.length
// Decorator function takes cookieOpts so we can customize on per-session basis.
fastify.decorate('decryptSession', (sessionId, request, cookieOpts, callback) => {
if (typeof cookieOpts === 'function') {
callback = cookieOpts
cookieOpts = {}
}
const cookie = { ...options.cookie, ...cookieOpts }
decryptSession(sessionId, { ...options, cookie }, request, callback)
})
fastify.decorateRequest('sessionStore', { getter: () => sessionStore })
fastify.decorateRequest('session', null)
fastify.addHook('onRequest', onRequest(options))
fastify.addHook('onSend', onSend(options))
next()
function decryptSession (sessionId, options, request, done) {
const cookieOpts = options.cookie
const idGenerator = options.idGenerator
const unsignedCookie = cookieSigner.unsign(sessionId)
if (unsignedCookie.valid === false) {
request.session = new Session(
sessionStore,
request,
idGenerator,
cookieOpts,
cookieSigner
)
done()
return
}
const decryptedSessionId = unsignedCookie.value
sessionStore.get(decryptedSessionId, (err, session) => {
if (err) {
if (err.code === 'ENOENT') {
request.session = new Session(
sessionStore,
request,
idGenerator,
cookieOpts,
cookieSigner
)
done()
} else {
done(err)
}
return
}
if (!session) {
request.session = new Session(
sessionStore,
request,
idGenerator,
cookieOpts,
cookieSigner
)
done()
return
}
const restoredSession = new Session(
sessionStore,
request,
idGenerator,
cookieOpts,
cookieSigner,
session,
decryptedSessionId
)
if (restoredSession.cookie.expires && restoredSession.cookie.expires.getTime() <= Date.now()) {
restoredSession.destroy(err => {
if (err) {
done(err)
return
}
restoredSession.regenerate(done)
})
return
}
request.session = restoredSession
done()
})
}
const getCookieSessionId = hasCookiePrefix
? function getCookieSessionId (request) {
const cookieValue = request.cookies[cookieName]
return (
cookieValue &&
cookieValue.startsWith(cookiePrefix) &&
cookieValue.slice(cookiePrefixLength)
)
}
: function getCookieSessionId (request) {
return request.cookies[cookieName]
}
function onRequest (options) {
const cookieOpts = options.cookie
const idGenerator = options.idGenerator
return function handleSession (request, reply, done) {
request.session = {}
const url = request.raw.url.split('?', 1)[0]
if (verifyPath(url, cookieOpts.path || '/') === false) {
done()
return
}
const cookieSessionId = getCookieSessionId(request)
if (!cookieSessionId) {
request.session = new Session(
sessionStore,
request,
idGenerator,
cookieOpts,
cookieSigner
)
done()
} else {
decryptSession(cookieSessionId, options, request, done)
}
}
}
function onSend (options) {
const cookieOpts = options.cookie
const saveUninitializedSession = options.saveUninitialized
const rollingSessions = options.rolling
return function saveSession (request, reply, payload, done) {
const session = request.session
if (!session || !session.sessionId || !session.encryptedSessionId) {
done()
return
}
const cookieSessionId = getCookieSessionId(request)
const saveSession = shouldSaveSession(request, cookieSessionId, saveUninitializedSession, rollingSessions)
const isInsecureConnection = cookieOpts.secure === true && isConnectionSecure(request) === false
const sessionIdWithPrefix = hasCookiePrefix ? `${cookiePrefix}${session.encryptedSessionId}` : session.encryptedSessionId
if (!saveSession || isInsecureConnection) {
// if a session cookie is set, but has a different ID, clear it
if (cookieSessionId && cookieSessionId !== session.encryptedSessionId) {
reply.clearCookie(cookieName, { domain: cookieOpts.domain })
}
if (session.isSaved()) {
reply.setCookie(
cookieName,
sessionIdWithPrefix,
// we need to remove extra properties to align the same with `express-session`
session.cookie.toJSON()
)
}
done()
return
}
session.save((err) => {
if (err) {
done(err)
return
}
reply.setCookie(
cookieName,
sessionIdWithPrefix,
// we need to remove extra properties to align the same with `express-session`
session.cookie.toJSON()
)
done()
})
}
}
function checkOptions (options) {
if (!options.secret) {
return new Error('the secret option is required!')
}
if (typeof options.secret === 'string' && options.secret.length < 32) {
return new Error('the secret must have length 32 or greater')
}
if (Array.isArray(options.secret) && options.secret.length === 0) {
return new Error('at least one secret is required')
}
}
function ensureDefaults (options) {
const opts = {}
opts.store = options.store || new Store()
opts.idGenerator = options.idGenerator || idGenerator
opts.cookieName = options.cookieName || 'sessionId'
opts.cookie = options.cookie || {}
opts.cookie.secure = option(opts.cookie, 'secure', true)
opts.rolling = option(options, 'rolling', true)
opts.saveUninitialized = option(options, 'saveUninitialized', true)
opts.algorithm = options.algorithm || 'sha256'
opts.signer = typeof options.secret === 'string' || Array.isArray(options.secret)
? new (require('@fastify/cookie').Signer)(options.secret, opts.algorithm)
: options.secret
opts.cookiePrefix = option(options, 'cookiePrefix', '')
return opts
}
function shouldSaveSession (request, cookieId, saveUninitializedSession, rollingSessions) {
return cookieId !== request.session.encryptedSessionId
? saveUninitializedSession || request.session.isModified()
: rollingSessions || request.session.isModified()
}
function option (options, key, def) {
return options[key] === undefined ? def : options[key]
}
function verifyPath (path, cookiePath) {
if (path === cookiePath) {
return true
}
const pathLength = path.length
const cookiePathLength = cookiePath.length
if (pathLength <= cookiePathLength) {
return false
} else if (path.startsWith(cookiePath)) {
if (path[cookiePathLength] === '/') {
return true
} else if (cookiePath[cookiePathLength - 1] === '/') {
return true
}
}
return false
}
}
module.exports = fp(fastifySession, {
fastify: '4.x',
name: '@fastify/session',
dependencies: [
'@fastify/cookie'
]
})
module.exports.default = fastifySession
module.exports.fastifySession = fastifySession
module.exports.Store = Store
module.exports.MemoryStore = Store