@oxog/spark 1.1.1 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +656 -315
- package/LICENSE +20 -20
- package/README.md +288 -241
- package/package.json +90 -89
- package/src/core/application.js +1068 -956
- package/src/core/context.js +1098 -830
- package/src/core/middleware.js +303 -217
- package/src/index.js +183 -280
- package/src/middleware/body-parser.js +482 -526
- package/src/middleware/cache.js +177 -170
- package/src/middleware/compression.js +177 -182
- package/src/middleware/cors.js +176 -95
- package/src/middleware/health.js +219 -218
- package/src/middleware/logger.js +195 -194
- package/src/middleware/metrics.js +339 -327
- package/src/middleware/rate-limit.js +367 -319
- package/src/middleware/security.js +442 -332
- package/src/middleware/session.js +647 -529
- package/src/middleware/static.js +404 -299
- package/src/router/layer.js +197 -117
- package/src/router/route.js +149 -123
- package/src/router/router.js +705 -755
- package/src/utils/async-handler.js +145 -147
- package/src/utils/context-pool.js +83 -82
- package/src/utils/regex-validator.js +187 -163
- package/src/utils/safe-json.js +110 -0
- package/types/index.d.ts +538 -291
- package/dist/LICENSE +0 -21
- package/dist/README.md +0 -242
- package/dist/core/application.js +0 -959
- package/dist/core/context.js +0 -833
- package/dist/core/middleware.js +0 -220
- package/dist/core/request.js +0 -335
- package/dist/core/response.js +0 -377
- package/dist/index.js +0 -280
- package/dist/middleware/body-parser.js +0 -528
- package/dist/middleware/cache.js +0 -173
- package/dist/middleware/compression.js +0 -185
- package/dist/middleware/cors.js +0 -97
- package/dist/middleware/health.js +0 -221
- package/dist/middleware/index.js +0 -23
- package/dist/middleware/logger.js +0 -197
- package/dist/middleware/metrics.js +0 -330
- package/dist/middleware/rate-limit.js +0 -322
- package/dist/middleware/security.js +0 -335
- package/dist/middleware/session.js +0 -532
- package/dist/middleware/static.js +0 -301
- package/dist/package.json +0 -62
- package/dist/router/layer.js +0 -119
- package/dist/router/route.js +0 -125
- package/dist/router/router.js +0 -758
- package/dist/types/index.d.ts +0 -291
- package/dist/utils/async-handler.js +0 -150
- package/dist/utils/cache.js +0 -443
- package/dist/utils/context-pool.js +0 -85
- package/dist/utils/error-types.js +0 -134
- package/dist/utils/http.js +0 -415
- package/dist/utils/regex-validator.js +0 -166
- package/src/core/request.js +0 -335
- package/src/core/response.js +0 -377
- package/src/middleware/index.js +0 -23
- package/src/utils/cache.js +0 -443
- package/src/utils/error-types.js +0 -134
- package/src/utils/http.js +0 -415
|
@@ -1,335 +1,445 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const crypto = require('crypto');
|
|
4
|
-
|
|
5
|
-
function security(options = {}) {
|
|
6
|
-
const opts = {
|
|
7
|
-
contentSecurityPolicy: options.contentSecurityPolicy !== false,
|
|
8
|
-
crossOriginEmbedderPolicy: options.crossOriginEmbedderPolicy !== false,
|
|
9
|
-
crossOriginOpenerPolicy: options.crossOriginOpenerPolicy !== false,
|
|
10
|
-
crossOriginResourcePolicy: options.crossOriginResourcePolicy !== false,
|
|
11
|
-
dnsPrefetchControl: options.dnsPrefetchControl !== false,
|
|
12
|
-
frameguard: options.frameguard !== false,
|
|
13
|
-
hidePoweredBy: options.hidePoweredBy !== false,
|
|
14
|
-
hsts: options.hsts !== false,
|
|
15
|
-
ieNoOpen: options.ieNoOpen !== false,
|
|
16
|
-
noSniff: options.noSniff !== false,
|
|
17
|
-
originAgentCluster: options.originAgentCluster !== false,
|
|
18
|
-
permittedCrossDomainPolicies: options.permittedCrossDomainPolicies !== false,
|
|
19
|
-
referrerPolicy: options.referrerPolicy !== false,
|
|
20
|
-
xssFilter: options.xssFilter !== false,
|
|
21
|
-
...options
|
|
22
|
-
};
|
|
23
|
-
|
|
24
|
-
return async (ctx, next) => {
|
|
25
|
-
if (opts.contentSecurityPolicy) {
|
|
26
|
-
setContentSecurityPolicy(ctx, opts.contentSecurityPolicy);
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
if (opts.crossOriginEmbedderPolicy) {
|
|
30
|
-
ctx.set('Cross-Origin-Embedder-Policy', 'require-corp');
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
if (opts.crossOriginOpenerPolicy) {
|
|
34
|
-
ctx.set('Cross-Origin-Opener-Policy', 'same-origin');
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
if (opts.crossOriginResourcePolicy) {
|
|
38
|
-
ctx.set('Cross-Origin-Resource-Policy', 'same-origin');
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
if (opts.dnsPrefetchControl) {
|
|
42
|
-
ctx.set('X-DNS-Prefetch-Control', 'off');
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
if (opts.frameguard) {
|
|
46
|
-
setFrameguard(ctx, opts.frameguard);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
if (opts.hidePoweredBy) {
|
|
50
|
-
ctx.removeHeader('X-Powered-By');
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
if (opts.hsts) {
|
|
54
|
-
setHSTS(ctx, opts.hsts);
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
if (opts.ieNoOpen) {
|
|
58
|
-
ctx.set('X-Download-Options', 'noopen');
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
if (opts.noSniff) {
|
|
62
|
-
ctx.set('X-Content-Type-Options', 'nosniff');
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
if (opts.originAgentCluster) {
|
|
66
|
-
ctx.set('Origin-Agent-Cluster', '?1');
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
if (opts.permittedCrossDomainPolicies) {
|
|
70
|
-
ctx.set('X-Permitted-Cross-Domain-Policies', 'none');
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
if (opts.referrerPolicy) {
|
|
74
|
-
setReferrerPolicy(ctx, opts.referrerPolicy);
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
if (opts.xssFilter) {
|
|
78
|
-
ctx.set('X-XSS-Protection', '1; mode=block');
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
await next();
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
function setContentSecurityPolicy(ctx, options) {
|
|
86
|
-
const defaultPolicy = {
|
|
87
|
-
'default-src': ["'self'"],
|
|
88
|
-
'script-src': ["'self'"],
|
|
89
|
-
'style-src': ["'self'", "'unsafe-inline'"],
|
|
90
|
-
'img-src': ["'self'", 'data:', 'https:'],
|
|
91
|
-
'font-src': ["'self'"],
|
|
92
|
-
'connect-src': ["'self'"],
|
|
93
|
-
'media-src': ["'self'"],
|
|
94
|
-
'object-src': ["'none'"],
|
|
95
|
-
'child-src': ["'self'"],
|
|
96
|
-
'frame-ancestors': ["'none'"],
|
|
97
|
-
'form-action': ["'self'"],
|
|
98
|
-
'base-uri': ["'self'"],
|
|
99
|
-
'manifest-src': ["'self'"]
|
|
100
|
-
};
|
|
101
|
-
|
|
102
|
-
const policy = typeof options === 'object' ? { ...defaultPolicy, ...options } : defaultPolicy;
|
|
103
|
-
|
|
104
|
-
const policyString = Object.keys(policy)
|
|
105
|
-
.
|
|
106
|
-
.join('
|
|
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
|
-
function
|
|
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
|
-
|
|
3
|
+
const crypto = require('crypto');
|
|
4
|
+
|
|
5
|
+
function security(options = {}) {
|
|
6
|
+
const opts = {
|
|
7
|
+
contentSecurityPolicy: options.contentSecurityPolicy !== false,
|
|
8
|
+
crossOriginEmbedderPolicy: options.crossOriginEmbedderPolicy !== false,
|
|
9
|
+
crossOriginOpenerPolicy: options.crossOriginOpenerPolicy !== false,
|
|
10
|
+
crossOriginResourcePolicy: options.crossOriginResourcePolicy !== false,
|
|
11
|
+
dnsPrefetchControl: options.dnsPrefetchControl !== false,
|
|
12
|
+
frameguard: options.frameguard !== false,
|
|
13
|
+
hidePoweredBy: options.hidePoweredBy !== false,
|
|
14
|
+
hsts: options.hsts !== false,
|
|
15
|
+
ieNoOpen: options.ieNoOpen !== false,
|
|
16
|
+
noSniff: options.noSniff !== false,
|
|
17
|
+
originAgentCluster: options.originAgentCluster !== false,
|
|
18
|
+
permittedCrossDomainPolicies: options.permittedCrossDomainPolicies !== false,
|
|
19
|
+
referrerPolicy: options.referrerPolicy !== false,
|
|
20
|
+
xssFilter: options.xssFilter !== false,
|
|
21
|
+
...options
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
return async (ctx, next) => {
|
|
25
|
+
if (opts.contentSecurityPolicy) {
|
|
26
|
+
setContentSecurityPolicy(ctx, opts.contentSecurityPolicy);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (opts.crossOriginEmbedderPolicy) {
|
|
30
|
+
ctx.set('Cross-Origin-Embedder-Policy', 'require-corp');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (opts.crossOriginOpenerPolicy) {
|
|
34
|
+
ctx.set('Cross-Origin-Opener-Policy', 'same-origin');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (opts.crossOriginResourcePolicy) {
|
|
38
|
+
ctx.set('Cross-Origin-Resource-Policy', 'same-origin');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (opts.dnsPrefetchControl) {
|
|
42
|
+
ctx.set('X-DNS-Prefetch-Control', 'off');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
if (opts.frameguard) {
|
|
46
|
+
setFrameguard(ctx, opts.frameguard);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (opts.hidePoweredBy) {
|
|
50
|
+
ctx.removeHeader('X-Powered-By');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (opts.hsts) {
|
|
54
|
+
setHSTS(ctx, opts.hsts);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (opts.ieNoOpen) {
|
|
58
|
+
ctx.set('X-Download-Options', 'noopen');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (opts.noSniff) {
|
|
62
|
+
ctx.set('X-Content-Type-Options', 'nosniff');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (opts.originAgentCluster) {
|
|
66
|
+
ctx.set('Origin-Agent-Cluster', '?1');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (opts.permittedCrossDomainPolicies) {
|
|
70
|
+
ctx.set('X-Permitted-Cross-Domain-Policies', 'none');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (opts.referrerPolicy) {
|
|
74
|
+
setReferrerPolicy(ctx, opts.referrerPolicy);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (opts.xssFilter) {
|
|
78
|
+
ctx.set('X-XSS-Protection', '1; mode=block');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
await next();
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function setContentSecurityPolicy(ctx, options) {
|
|
86
|
+
const defaultPolicy = {
|
|
87
|
+
'default-src': ["'self'"],
|
|
88
|
+
'script-src': ["'self'"],
|
|
89
|
+
'style-src': ["'self'", "'unsafe-inline'"],
|
|
90
|
+
'img-src': ["'self'", 'data:', 'https:'],
|
|
91
|
+
'font-src': ["'self'"],
|
|
92
|
+
'connect-src': ["'self'"],
|
|
93
|
+
'media-src': ["'self'"],
|
|
94
|
+
'object-src': ["'none'"],
|
|
95
|
+
'child-src': ["'self'"],
|
|
96
|
+
'frame-ancestors': ["'none'"],
|
|
97
|
+
'form-action': ["'self'"],
|
|
98
|
+
'base-uri': ["'self'"],
|
|
99
|
+
'manifest-src': ["'self'"]
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const policy = typeof options === 'object' ? { ...defaultPolicy, ...options } : defaultPolicy;
|
|
103
|
+
|
|
104
|
+
const policyString = Object.keys(policy)
|
|
105
|
+
.filter(key => policy[key] !== false && policy[key] !== null && policy[key] !== undefined)
|
|
106
|
+
.map(key => `${key} ${[].concat(policy[key]).join(' ')}`.trim())
|
|
107
|
+
.join('; ');
|
|
108
|
+
|
|
109
|
+
ctx.set('Content-Security-Policy', policyString);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function setFrameguard(ctx, options) {
|
|
113
|
+
if (options === true) {
|
|
114
|
+
ctx.set('X-Frame-Options', 'DENY');
|
|
115
|
+
} else if (typeof options === 'string') {
|
|
116
|
+
ctx.set('X-Frame-Options', options);
|
|
117
|
+
} else if (typeof options === 'object') {
|
|
118
|
+
if (options.action === 'allow-from') {
|
|
119
|
+
// SECURITY FIX: Validate domain to prevent header injection
|
|
120
|
+
if (!options.domain || typeof options.domain !== 'string') {
|
|
121
|
+
throw new Error('Frameguard domain must be a valid string');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Check for CRLF injection attempts
|
|
125
|
+
if (options.domain.includes('\r') || options.domain.includes('\n')) {
|
|
126
|
+
throw new Error('Invalid domain: CRLF characters not allowed');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Validate domain format (basic check for valid hostname)
|
|
130
|
+
const domainRegex = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
|
|
131
|
+
if (!domainRegex.test(options.domain) && !options.domain.startsWith('http://') && !options.domain.startsWith('https://')) {
|
|
132
|
+
throw new Error('Invalid domain format');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
ctx.set('X-Frame-Options', `ALLOW-FROM ${options.domain}`);
|
|
136
|
+
} else {
|
|
137
|
+
ctx.set('X-Frame-Options', options.action || 'DENY');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function setHSTS(ctx, options) {
|
|
143
|
+
const defaults = {
|
|
144
|
+
maxAge: 31536000, // 1 year
|
|
145
|
+
includeSubDomains: true,
|
|
146
|
+
preload: false
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const opts = typeof options === 'object' ? { ...defaults, ...options } : defaults;
|
|
150
|
+
|
|
151
|
+
let hstsHeader = `max-age=${opts.maxAge}`;
|
|
152
|
+
|
|
153
|
+
if (opts.includeSubDomains) {
|
|
154
|
+
hstsHeader += '; includeSubDomains';
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (opts.preload) {
|
|
158
|
+
hstsHeader += '; preload';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
ctx.set('Strict-Transport-Security', hstsHeader);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function setReferrerPolicy(ctx, options) {
|
|
165
|
+
const policy = typeof options === 'string' ? options : 'no-referrer';
|
|
166
|
+
ctx.set('Referrer-Policy', policy);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* CSRF protection middleware.
|
|
171
|
+
*
|
|
172
|
+
* Every client gets its own random CSRF secret: it is kept in the session
|
|
173
|
+
* (`ctx.session[sessionKey]`) when a session middleware runs first, otherwise
|
|
174
|
+
* in an HttpOnly, SameSite=Strict cookie (`cookieName`, default `_csrf`).
|
|
175
|
+
* Tokens are `salt + HMAC(secret option, salt + client secret)`, so a token
|
|
176
|
+
* issued to one client is useless for another, and a token cannot be forged
|
|
177
|
+
* without the server secret.
|
|
178
|
+
*
|
|
179
|
+
* State-changing requests (methods not in `ignoreMethods`) must send a token in
|
|
180
|
+
* the `x-csrf-token` header (`headerName`) or the `_csrf` body field
|
|
181
|
+
* (`bodyName`); cookies are never accepted as the token because browsers
|
|
182
|
+
* attach them to cross-site requests. Get a token for the current client with
|
|
183
|
+
* `ctx.csrfToken()` (or `csrfToken(ctx)`).
|
|
184
|
+
*
|
|
185
|
+
* @param {Object} options - Options
|
|
186
|
+
* @param {string} options.secret - Server secret (required)
|
|
187
|
+
* @param {string} [options.cookieName='_csrf'] - Cookie holding the client secret when there is no session
|
|
188
|
+
* @param {Object} [options.cookieOptions] - Extra options for that cookie (e.g. { secure: true })
|
|
189
|
+
* @param {string} [options.headerName='x-csrf-token'] - Request header carrying the token
|
|
190
|
+
* @param {string} [options.bodyName='_csrf'] - Body field carrying the token
|
|
191
|
+
* @param {string} [options.sessionKey='csrfSecret'] - Session key holding the client secret
|
|
192
|
+
* @param {string[]} [options.ignoreMethods=['GET','HEAD','OPTIONS']] - Methods that skip verification
|
|
193
|
+
* @returns {Function} Middleware
|
|
194
|
+
*/
|
|
195
|
+
function csrf(options = {}) {
|
|
196
|
+
const opts = {
|
|
197
|
+
...options,
|
|
198
|
+
secret: options.secret || throwMissingCsrfSecretError(),
|
|
199
|
+
cookieName: options.cookieName || '_csrf',
|
|
200
|
+
headerName: (options.headerName || 'x-csrf-token').toLowerCase(),
|
|
201
|
+
bodyName: options.bodyName || '_csrf',
|
|
202
|
+
sessionKey: options.sessionKey || 'csrfSecret',
|
|
203
|
+
ignoreMethods: (options.ignoreMethods || ['GET', 'HEAD', 'OPTIONS']).map(m => m.toUpperCase())
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
return async (ctx, next) => {
|
|
207
|
+
const clientSecret = getClientSecret(ctx, opts);
|
|
208
|
+
|
|
209
|
+
ctx.csrfToken = () => generateToken(clientSecret, opts.secret);
|
|
210
|
+
ctx.state.csrfToken = ctx.csrfToken;
|
|
211
|
+
|
|
212
|
+
if (opts.ignoreMethods.includes(ctx.method)) {
|
|
213
|
+
return next();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const token = getTokenFromRequest(ctx, opts);
|
|
217
|
+
|
|
218
|
+
if (!token) {
|
|
219
|
+
return ctx.status(403).json({ error: 'CSRF token missing' });
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (!verifyToken(token, clientSecret, opts.secret)) {
|
|
223
|
+
return ctx.status(403).json({ error: 'Invalid CSRF token' });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
return next();
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function generateSecret() {
|
|
231
|
+
return crypto.randomBytes(32).toString('hex');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Return the client's CSRF secret, creating it when missing.
|
|
236
|
+
*
|
|
237
|
+
* @private
|
|
238
|
+
*/
|
|
239
|
+
function getClientSecret(ctx, opts) {
|
|
240
|
+
if (ctx.session) {
|
|
241
|
+
if (typeof ctx.session[opts.sessionKey] !== 'string' || !ctx.session[opts.sessionKey]) {
|
|
242
|
+
ctx.session[opts.sessionKey] = generateSecret();
|
|
243
|
+
}
|
|
244
|
+
return ctx.session[opts.sessionKey];
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const existing = ctx.cookies && ctx.cookies[opts.cookieName];
|
|
248
|
+
if (typeof existing === 'string' && /^[a-f0-9]{64}$/.test(existing)) {
|
|
249
|
+
return existing;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const secret = generateSecret();
|
|
253
|
+
ctx.setCookie(opts.cookieName, secret, {
|
|
254
|
+
path: '/',
|
|
255
|
+
httpOnly: true,
|
|
256
|
+
sameSite: 'Strict',
|
|
257
|
+
...(opts.cookieOptions || {})
|
|
258
|
+
});
|
|
259
|
+
return secret;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function tokenDigest(salt, clientSecret, serverSecret) {
|
|
263
|
+
return crypto.createHmac('sha256', String(serverSecret)).update(`${salt}.${clientSecret}`).digest('hex');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Create a CSRF token bound to a client secret.
|
|
268
|
+
*
|
|
269
|
+
* @param {string} clientSecret - Per-client secret
|
|
270
|
+
* @param {string} [serverSecret] - Server secret (defaults to the client secret)
|
|
271
|
+
* @returns {string} Token (80 hex characters)
|
|
272
|
+
*/
|
|
273
|
+
function generateToken(clientSecret, serverSecret = clientSecret) {
|
|
274
|
+
const salt = crypto.randomBytes(8).toString('hex');
|
|
275
|
+
return salt + tokenDigest(salt, clientSecret, serverSecret);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Verify a CSRF token in constant time.
|
|
280
|
+
*
|
|
281
|
+
* @param {string} token - Token from the request
|
|
282
|
+
* @param {string} clientSecret - Per-client secret
|
|
283
|
+
* @param {string} [serverSecret] - Server secret (defaults to the client secret)
|
|
284
|
+
* @returns {boolean}
|
|
285
|
+
*/
|
|
286
|
+
function verifyToken(token, clientSecret, serverSecret = clientSecret) {
|
|
287
|
+
if (!token || typeof token !== 'string' || !/^[a-f0-9]{80}$/.test(token) || !clientSecret) {
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
const salt = token.slice(0, 16);
|
|
292
|
+
const hashBuffer = Buffer.from(token.slice(16), 'hex');
|
|
293
|
+
const expectedBuffer = Buffer.from(tokenDigest(salt, clientSecret, serverSecret), 'hex');
|
|
294
|
+
|
|
295
|
+
return hashBuffer.length === expectedBuffer.length && crypto.timingSafeEqual(hashBuffer, expectedBuffer);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function getTokenFromRequest(ctx, opts) {
|
|
299
|
+
const header = ctx.get(opts.headerName);
|
|
300
|
+
if (typeof header === 'string' && header) {
|
|
301
|
+
return header;
|
|
302
|
+
}
|
|
303
|
+
const body = ctx.body;
|
|
304
|
+
if (body && typeof body === 'object' && typeof body[opts.bodyName] === 'string') {
|
|
305
|
+
return body[opts.bodyName];
|
|
306
|
+
}
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Create a CSRF token for the current client.
|
|
312
|
+
*
|
|
313
|
+
* Inside a request handled by the csrf() middleware this is the same as
|
|
314
|
+
* `ctx.csrfToken()`.
|
|
315
|
+
*
|
|
316
|
+
* @param {Context} ctx - Request context
|
|
317
|
+
* @param {Object} [options={}] - Must include `secret` (and `sessionKey` /
|
|
318
|
+
* `cookieName` if customised) when csrf() has not run for this request
|
|
319
|
+
* @returns {string} Token
|
|
320
|
+
*/
|
|
321
|
+
function csrfToken(ctx, options = {}) {
|
|
322
|
+
if (typeof ctx.csrfToken === 'function') {
|
|
323
|
+
return ctx.csrfToken();
|
|
324
|
+
}
|
|
325
|
+
const opts = {
|
|
326
|
+
...options,
|
|
327
|
+
secret: options.secret || throwMissingCsrfSecretError(),
|
|
328
|
+
cookieName: options.cookieName || '_csrf',
|
|
329
|
+
sessionKey: options.sessionKey || 'csrfSecret'
|
|
330
|
+
};
|
|
331
|
+
return generateToken(getClientSecret(ctx, opts), opts.secret);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function xssProtection(options = {}) {
|
|
335
|
+
const opts = {
|
|
336
|
+
escapeHtml: options.escapeHtml !== false,
|
|
337
|
+
escapeJson: options.escapeJson !== false,
|
|
338
|
+
...options
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
return async (ctx, next) => {
|
|
342
|
+
if (opts.escapeHtml) {
|
|
343
|
+
const originalHtml = ctx.html;
|
|
344
|
+
ctx.html = function(data) {
|
|
345
|
+
return originalHtml.call(this, escapeHtml(data));
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (opts.escapeJson) {
|
|
350
|
+
const originalJson = ctx.json;
|
|
351
|
+
ctx.json = function(data) {
|
|
352
|
+
return originalJson.call(this, escapeJsonValues(data));
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
await next();
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function escapeHtml(text) {
|
|
361
|
+
const map = {
|
|
362
|
+
'&': '&',
|
|
363
|
+
'<': '<',
|
|
364
|
+
'>': '>',
|
|
365
|
+
'"': '"',
|
|
366
|
+
"'": '''
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
return String(text).replace(/[&<>"']/g, (s) => map[s]);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function escapeJsonValues(obj) {
|
|
373
|
+
if (typeof obj === 'string') {
|
|
374
|
+
return escapeHtml(obj);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
if (Array.isArray(obj)) {
|
|
378
|
+
return obj.map(escapeJsonValues);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (obj && typeof obj === 'object') {
|
|
382
|
+
const escaped = {};
|
|
383
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
384
|
+
// defineProperty keeps an own "__proto__" key from replacing the prototype
|
|
385
|
+
Object.defineProperty(escaped, key, {
|
|
386
|
+
value: escapeJsonValues(value),
|
|
387
|
+
enumerable: true,
|
|
388
|
+
writable: true,
|
|
389
|
+
configurable: true
|
|
390
|
+
});
|
|
391
|
+
}
|
|
392
|
+
return escaped;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
return obj;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Reject requests whose Content-Length exceeds a limit (413).
|
|
400
|
+
*
|
|
401
|
+
* Only the declared Content-Length is checked; chunked bodies have none, so
|
|
402
|
+
* use bodyParser's `limit` (which counts the bytes actually received) to cap
|
|
403
|
+
* those.
|
|
404
|
+
*
|
|
405
|
+
* @param {Object} [options={}] - Options
|
|
406
|
+
* @param {number} [options.limit=1048576] - Maximum Content-Length in bytes
|
|
407
|
+
* @param {string} [options.message] - Message in the error response
|
|
408
|
+
* @param {number} [options.statusCode=413] - Status code
|
|
409
|
+
* @returns {Function} Middleware
|
|
410
|
+
*/
|
|
411
|
+
function requestSizeLimit(options = {}) {
|
|
412
|
+
const opts = {
|
|
413
|
+
limit: options.limit || 1024 * 1024, // 1MB
|
|
414
|
+
message: options.message || 'Request too large',
|
|
415
|
+
statusCode: options.statusCode || 413,
|
|
416
|
+
...options
|
|
417
|
+
};
|
|
418
|
+
|
|
419
|
+
return async (ctx, next) => {
|
|
420
|
+
const contentLength = parseInt(ctx.get('content-length') || '0', 10);
|
|
421
|
+
|
|
422
|
+
if (contentLength > opts.limit) {
|
|
423
|
+
return ctx.status(opts.statusCode).json({
|
|
424
|
+
error: 'Request Too Large',
|
|
425
|
+
message: opts.message
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
await next();
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function throwMissingCsrfSecretError() {
|
|
434
|
+
throw new Error(
|
|
435
|
+
'CSRF secret is required for security. ' +
|
|
436
|
+
'Please provide a secret in the csrf options: ' +
|
|
437
|
+
'csrf({ secret: "your-secret-here" })'
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
module.exports = security;
|
|
442
|
+
module.exports.csrf = csrf;
|
|
443
|
+
module.exports.csrfToken = csrfToken;
|
|
444
|
+
module.exports.xssProtection = xssProtection;
|
|
335
445
|
module.exports.requestSizeLimit = requestSizeLimit;
|