-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
144 lines (123 loc) · 4.48 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
'use strict'
const assert = require('node:assert')
const fp = require('fastify-plugin')
const CSRF = require('@fastify/csrf')
const createError = require('@fastify/error')
const MissingCSRFSecretError = createError('FST_CSRF_MISSING_SECRET', 'Missing csrf secret', 403)
const InvalidCSRFTokenError = createError('FST_CSRF_INVALID_TOKEN', 'Invalid csrf token', 403)
const defaultOptions = {
cookieKey: '_csrf',
cookieOpts: { path: '/', sameSite: true, httpOnly: true },
sessionKey: '_csrf',
getToken: getTokenDefault,
getUserInfo: getUserInfoDefault,
sessionPlugin: '@fastify/cookie'
}
async function fastifyCsrfProtection (fastify, opts) {
const {
cookieKey,
cookieOpts,
sessionKey,
getToken,
getUserInfo,
sessionPlugin
} = Object.assign({}, defaultOptions, opts)
const csrfOpts = opts && opts.csrfOpts ? opts.csrfOpts : {}
assert(typeof cookieKey === 'string', 'cookieKey should be a string')
assert(typeof sessionKey === 'string', 'sessionKey should be a string')
assert(typeof getToken === 'function', 'getToken should be a function')
assert(typeof getUserInfo === 'function', 'getUserInfo should be a function')
assert(typeof cookieOpts === 'object', 'cookieOpts should be a object')
assert(
['@fastify/cookie', '@fastify/session', '@fastify/secure-session'].includes(sessionPlugin),
"sessionPlugin should be one of the following: '@fastify/cookie', '@fastify/session', '@fastify/secure-session'"
)
if (opts.getUserInfo) {
csrfOpts.userInfo = true
}
if (sessionPlugin === '@fastify/cookie' && csrfOpts.userInfo) {
assert(csrfOpts.hmacKey, 'csrfOpts.hmacKey is required')
}
const tokens = new CSRF(csrfOpts)
const isCookieSigned = cookieOpts && cookieOpts.signed
if (sessionPlugin === '@fastify/secure-session') {
fastify.decorateReply('generateCsrf', generateCsrfSecureSession)
} else if (sessionPlugin === '@fastify/session') {
fastify.decorateReply('generateCsrf', generateCsrfSession)
} else {
fastify.decorateReply('generateCsrf', generateCsrfCookie)
}
fastify.decorate('csrfProtection', csrfProtection)
let getSecret
if (sessionPlugin === '@fastify/secure-session') {
getSecret = function getSecret (req, reply) { return req.session.get(sessionKey) }
} else if (sessionPlugin === '@fastify/session') {
getSecret = function getSecret (req, reply) { return req.session[sessionKey] }
} else {
getSecret = function getSecret (req, reply) {
return isCookieSigned
? reply.unsignCookie(req.cookies[cookieKey] || '').value
: req.cookies[cookieKey]
}
}
function generateCsrfCookie (opts) {
let secret = isCookieSigned
? this.unsignCookie(this.request.cookies[cookieKey] || '').value
: this.request.cookies[cookieKey]
const userInfo = opts ? opts.userInfo : undefined
if (!secret) {
secret = tokens.secretSync()
this.setCookie(cookieKey, secret, Object.assign({}, cookieOpts, opts))
}
return tokens.create(secret, userInfo)
}
function generateCsrfSecureSession (opts) {
let secret = this.request.session.get(sessionKey)
if (!secret) {
secret = tokens.secretSync()
this.request.session.set(sessionKey, secret)
}
const userInfo = opts ? opts.userInfo : undefined
if (opts) {
this.request.session.options(opts)
}
return tokens.create(secret, userInfo)
}
function generateCsrfSession (opts) {
let secret = this.request.session[sessionKey]
const userInfo = opts ? opts.userInfo : undefined
if (!secret) {
secret = tokens.secretSync()
this.request.session[sessionKey] = secret
}
return tokens.create(secret, userInfo)
}
function csrfProtection (req, reply, next) {
const secret = getSecret(req, reply)
if (!secret) {
req.log.warn('Missing csrf secret')
return reply.send(new MissingCSRFSecretError())
}
if (!tokens.verify(secret, getToken(req), getUserInfo(req))) {
req.log.warn('Invalid csrf token')
return reply.send(new InvalidCSRFTokenError())
}
next()
}
}
function getTokenDefault (req) {
return (req.body && req.body._csrf) ||
req.headers['csrf-token'] ||
req.headers['xsrf-token'] ||
req.headers['x-csrf-token'] ||
req.headers['x-xsrf-token']
}
function getUserInfoDefault (req) {
return undefined
}
module.exports = fp(fastifyCsrfProtection, {
fastify: '5.x',
name: '@fastify/csrf-protection'
})
module.exports.default = fastifyCsrfProtection
module.exports.fastifyCsrfProtection = fastifyCsrfProtection