@oxog/spark 1.1.1 → 1.2.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +632 -315
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1068 -956
  6. package/src/core/context.js +1098 -830
  7. package/src/core/middleware.js +303 -217
  8. package/src/index.js +183 -280
  9. package/src/middleware/body-parser.js +482 -526
  10. package/src/middleware/cache.js +177 -170
  11. package/src/middleware/compression.js +177 -182
  12. package/src/middleware/cors.js +176 -95
  13. package/src/middleware/health.js +219 -218
  14. package/src/middleware/logger.js +195 -194
  15. package/src/middleware/metrics.js +339 -327
  16. package/src/middleware/rate-limit.js +367 -319
  17. package/src/middleware/security.js +442 -332
  18. package/src/middleware/session.js +647 -529
  19. package/src/middleware/static.js +404 -299
  20. package/src/router/layer.js +197 -117
  21. package/src/router/route.js +149 -123
  22. package/src/router/router.js +703 -755
  23. package/src/utils/async-handler.js +145 -147
  24. package/src/utils/context-pool.js +83 -82
  25. package/src/utils/regex-validator.js +187 -163
  26. package/src/utils/safe-json.js +110 -0
  27. package/types/index.d.ts +536 -291
  28. package/dist/LICENSE +0 -21
  29. package/dist/README.md +0 -242
  30. package/dist/core/application.js +0 -959
  31. package/dist/core/context.js +0 -833
  32. package/dist/core/middleware.js +0 -220
  33. package/dist/core/request.js +0 -335
  34. package/dist/core/response.js +0 -377
  35. package/dist/index.js +0 -280
  36. package/dist/middleware/body-parser.js +0 -528
  37. package/dist/middleware/cache.js +0 -173
  38. package/dist/middleware/compression.js +0 -185
  39. package/dist/middleware/cors.js +0 -97
  40. package/dist/middleware/health.js +0 -221
  41. package/dist/middleware/index.js +0 -23
  42. package/dist/middleware/logger.js +0 -197
  43. package/dist/middleware/metrics.js +0 -330
  44. package/dist/middleware/rate-limit.js +0 -322
  45. package/dist/middleware/security.js +0 -335
  46. package/dist/middleware/session.js +0 -532
  47. package/dist/middleware/static.js +0 -301
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -119
  50. package/dist/router/route.js +0 -125
  51. package/dist/router/router.js +0 -758
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -150
  54. package/dist/utils/cache.js +0 -443
  55. package/dist/utils/context-pool.js +0 -85
  56. package/dist/utils/error-types.js +0 -134
  57. package/dist/utils/http.js +0 -415
  58. package/dist/utils/regex-validator.js +0 -166
  59. package/src/core/request.js +0 -335
  60. package/src/core/response.js +0 -377
  61. package/src/middleware/index.js +0 -23
  62. package/src/utils/cache.js +0 -443
  63. package/src/utils/error-types.js +0 -134
  64. 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
- .map(key => `${key} ${policy[key].join(' ')}`)
106
- .join('; ');
107
-
108
- ctx.set('Content-Security-Policy', policyString);
109
- }
110
-
111
- function setFrameguard(ctx, options) {
112
- if (options === true) {
113
- ctx.set('X-Frame-Options', 'DENY');
114
- } else if (typeof options === 'string') {
115
- ctx.set('X-Frame-Options', options);
116
- } else if (typeof options === 'object') {
117
- if (options.action === 'allow-from') {
118
- ctx.set('X-Frame-Options', `ALLOW-FROM ${options.domain}`);
119
- } else {
120
- ctx.set('X-Frame-Options', options.action || 'DENY');
121
- }
122
- }
123
- }
124
-
125
- function setHSTS(ctx, options) {
126
- const defaults = {
127
- maxAge: 31536000, // 1 year
128
- includeSubDomains: true,
129
- preload: false
130
- };
131
-
132
- const opts = typeof options === 'object' ? { ...defaults, ...options } : defaults;
133
-
134
- let hstsHeader = `max-age=${opts.maxAge}`;
135
-
136
- if (opts.includeSubDomains) {
137
- hstsHeader += '; includeSubDomains';
138
- }
139
-
140
- if (opts.preload) {
141
- hstsHeader += '; preload';
142
- }
143
-
144
- ctx.set('Strict-Transport-Security', hstsHeader);
145
- }
146
-
147
- function setReferrerPolicy(ctx, options) {
148
- const policy = typeof options === 'string' ? options : 'no-referrer';
149
- ctx.set('Referrer-Policy', policy);
150
- }
151
-
152
- function csrf(options = {}) {
153
- const opts = {
154
- secret: options.secret || throwMissingCsrfSecretError(),
155
- cookie: options.cookie !== false,
156
- cookieName: options.cookieName || '_csrf',
157
- headerName: options.headerName || 'x-csrf-token',
158
- bodyName: options.bodyName || '_csrf',
159
- value: options.value,
160
- sessionKey: options.sessionKey || 'csrfSecret',
161
- ignoreMethods: options.ignoreMethods || ['GET', 'HEAD', 'OPTIONS'],
162
- ...options
163
- };
164
-
165
- return async (ctx, next) => {
166
- if (opts.ignoreMethods.includes(ctx.method)) {
167
- return next();
168
- }
169
-
170
- const secret = getSecret(ctx, opts);
171
- const token = getTokenFromRequest(ctx, opts);
172
-
173
- if (!token) {
174
- return ctx.status(403).json({ error: 'CSRF token missing' });
175
- }
176
-
177
- if (!verifyToken(token, secret)) {
178
- return ctx.status(403).json({ error: 'Invalid CSRF token' });
179
- }
180
-
181
- await next();
182
- };
183
- }
184
-
185
- function generateSecret() {
186
- return crypto.randomBytes(32).toString('hex');
187
- }
188
-
189
- function generateToken(secret) {
190
- const salt = crypto.randomBytes(8).toString('hex');
191
- const hash = crypto.createHash('sha256').update(salt + secret).digest('hex');
192
- return salt + hash;
193
- }
194
-
195
- function verifyToken(token, secret) {
196
- if (!token || typeof token !== 'string') {
197
- return false;
198
- }
199
-
200
- // Token format: 16 char salt + 64 char hash = 80 chars total
201
- if (token.length !== 80) {
202
- return false;
203
- }
204
-
205
- const salt = token.slice(0, 16);
206
- const hash = token.slice(16);
207
- const expected = crypto.createHash('sha256').update(salt + secret).digest('hex');
208
-
209
- return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(expected));
210
- }
211
-
212
- function getSecret(ctx, opts) {
213
- if (ctx.session && ctx.session[opts.sessionKey]) {
214
- return ctx.session[opts.sessionKey];
215
- }
216
-
217
- const secret = opts.secret || generateSecret();
218
-
219
- if (ctx.session) {
220
- ctx.session[opts.sessionKey] = secret;
221
- }
222
-
223
- return secret;
224
- }
225
-
226
- function getTokenFromRequest(ctx, opts) {
227
- return ctx.get(opts.headerName) ||
228
- (ctx.body && ctx.body[opts.bodyName]) ||
229
- (ctx.cookies && ctx.cookies[opts.cookieName]);
230
- }
231
-
232
- function csrfToken(ctx, options = {}) {
233
- const opts = {
234
- secret: options.secret || generateSecret(),
235
- sessionKey: options.sessionKey || 'csrfSecret',
236
- ...options
237
- };
238
-
239
- const secret = getSecret(ctx, opts);
240
- return generateToken(secret);
241
- }
242
-
243
- function xssProtection(options = {}) {
244
- const opts = {
245
- escapeHtml: options.escapeHtml !== false,
246
- escapeJson: options.escapeJson !== false,
247
- ...options
248
- };
249
-
250
- return async (ctx, next) => {
251
- if (opts.escapeHtml) {
252
- const originalHtml = ctx.html;
253
- ctx.html = function(data) {
254
- return originalHtml.call(this, escapeHtml(data));
255
- };
256
- }
257
-
258
- if (opts.escapeJson) {
259
- const originalJson = ctx.json;
260
- ctx.json = function(data) {
261
- return originalJson.call(this, escapeJsonValues(data));
262
- };
263
- }
264
-
265
- await next();
266
- };
267
- }
268
-
269
- function escapeHtml(text) {
270
- const map = {
271
- '&': '&',
272
- '<': '&lt;',
273
- '>': '&gt;',
274
- '"': '&quot;',
275
- "'": '&#39;'
276
- };
277
-
278
- return String(text).replace(/[&<>"']/g, (s) => map[s]);
279
- }
280
-
281
- function escapeJsonValues(obj) {
282
- if (typeof obj === 'string') {
283
- return escapeHtml(obj);
284
- }
285
-
286
- if (Array.isArray(obj)) {
287
- return obj.map(escapeJsonValues);
288
- }
289
-
290
- if (obj && typeof obj === 'object') {
291
- const escaped = {};
292
- for (const [key, value] of Object.entries(obj)) {
293
- escaped[key] = escapeJsonValues(value);
294
- }
295
- return escaped;
296
- }
297
-
298
- return obj;
299
- }
300
-
301
- function requestSizeLimit(options = {}) {
302
- const opts = {
303
- limit: options.limit || 1024 * 1024, // 1MB
304
- message: options.message || 'Request too large',
305
- statusCode: options.statusCode || 413,
306
- ...options
307
- };
308
-
309
- return async (ctx, next) => {
310
- const contentLength = parseInt(ctx.get('content-length') || '0');
311
-
312
- if (contentLength > opts.limit) {
313
- return ctx.status(opts.statusCode).json({
314
- error: 'Request Too Large',
315
- message: opts.message
316
- });
317
- }
318
-
319
- await next();
320
- };
321
- }
322
-
323
- function throwMissingCsrfSecretError() {
324
- throw new Error(
325
- 'CSRF secret is required for security. ' +
326
- 'Please provide a secret in the csrf options: ' +
327
- 'csrf({ secret: "your-secret-here" })'
328
- );
329
- }
330
-
331
- module.exports = security;
332
- module.exports.csrf = csrf;
333
- module.exports.csrfToken = csrfToken;
334
- module.exports.xssProtection = xssProtection;
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
+ '&': '&amp;',
363
+ '<': '&lt;',
364
+ '>': '&gt;',
365
+ '"': '&quot;',
366
+ "'": '&#39;'
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;