@oxog/spark 1.1.0 → 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 -293
  2. package/LICENSE +20 -20
  3. package/README.md +288 -241
  4. package/package.json +83 -89
  5. package/src/core/application.js +1070 -956
  6. package/src/core/context.js +1100 -830
  7. package/src/core/middleware.js +305 -217
  8. package/src/index.js +183 -278
  9. package/src/middleware/body-parser.js +484 -526
  10. package/src/middleware/cache.js +179 -170
  11. package/src/middleware/compression.js +179 -182
  12. package/src/middleware/cors.js +178 -95
  13. package/src/middleware/health.js +221 -218
  14. package/src/middleware/logger.js +197 -194
  15. package/src/middleware/metrics.js +341 -327
  16. package/src/middleware/rate-limit.js +369 -319
  17. package/src/middleware/security.js +444 -332
  18. package/src/middleware/session.js +649 -529
  19. package/src/middleware/static.js +406 -299
  20. package/src/router/layer.js +199 -117
  21. package/src/router/route.js +151 -123
  22. package/src/router/router.js +705 -755
  23. package/src/utils/async-handler.js +147 -144
  24. package/src/utils/context-pool.js +85 -82
  25. package/src/utils/regex-validator.js +189 -176
  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 -957
  31. package/dist/core/context.js +0 -831
  32. package/dist/core/middleware.js +0 -218
  33. package/dist/core/request.js +0 -333
  34. package/dist/core/response.js +0 -375
  35. package/dist/index.js +0 -278
  36. package/dist/middleware/body-parser.js +0 -526
  37. package/dist/middleware/cache.js +0 -171
  38. package/dist/middleware/compression.js +0 -183
  39. package/dist/middleware/cors.js +0 -95
  40. package/dist/middleware/health.js +0 -219
  41. package/dist/middleware/index.js +0 -21
  42. package/dist/middleware/logger.js +0 -195
  43. package/dist/middleware/metrics.js +0 -328
  44. package/dist/middleware/rate-limit.js +0 -320
  45. package/dist/middleware/security.js +0 -333
  46. package/dist/middleware/session.js +0 -530
  47. package/dist/middleware/static.js +0 -299
  48. package/dist/package.json +0 -62
  49. package/dist/router/layer.js +0 -117
  50. package/dist/router/route.js +0 -123
  51. package/dist/router/router.js +0 -756
  52. package/dist/types/index.d.ts +0 -291
  53. package/dist/utils/async-handler.js +0 -145
  54. package/dist/utils/cache.js +0 -441
  55. package/dist/utils/context-pool.js +0 -83
  56. package/dist/utils/error-types.js +0 -132
  57. package/dist/utils/http.js +0 -413
  58. package/dist/utils/regex-validator.js +0 -177
  59. package/src/core/request.js +0 -333
  60. package/src/core/response.js +0 -375
  61. package/src/middleware/index.js +0 -21
  62. package/src/utils/cache.js +0 -441
  63. package/src/utils/error-types.js +0 -132
  64. package/src/utils/http.js +0 -413
@@ -1,333 +1,445 @@
1
- const crypto = require('crypto');
2
-
3
- function security(options = {}) {
4
- const opts = {
5
- contentSecurityPolicy: options.contentSecurityPolicy !== false,
6
- crossOriginEmbedderPolicy: options.crossOriginEmbedderPolicy !== false,
7
- crossOriginOpenerPolicy: options.crossOriginOpenerPolicy !== false,
8
- crossOriginResourcePolicy: options.crossOriginResourcePolicy !== false,
9
- dnsPrefetchControl: options.dnsPrefetchControl !== false,
10
- frameguard: options.frameguard !== false,
11
- hidePoweredBy: options.hidePoweredBy !== false,
12
- hsts: options.hsts !== false,
13
- ieNoOpen: options.ieNoOpen !== false,
14
- noSniff: options.noSniff !== false,
15
- originAgentCluster: options.originAgentCluster !== false,
16
- permittedCrossDomainPolicies: options.permittedCrossDomainPolicies !== false,
17
- referrerPolicy: options.referrerPolicy !== false,
18
- xssFilter: options.xssFilter !== false,
19
- ...options
20
- };
21
-
22
- return async (ctx, next) => {
23
- if (opts.contentSecurityPolicy) {
24
- setContentSecurityPolicy(ctx, opts.contentSecurityPolicy);
25
- }
26
-
27
- if (opts.crossOriginEmbedderPolicy) {
28
- ctx.set('Cross-Origin-Embedder-Policy', 'require-corp');
29
- }
30
-
31
- if (opts.crossOriginOpenerPolicy) {
32
- ctx.set('Cross-Origin-Opener-Policy', 'same-origin');
33
- }
34
-
35
- if (opts.crossOriginResourcePolicy) {
36
- ctx.set('Cross-Origin-Resource-Policy', 'same-origin');
37
- }
38
-
39
- if (opts.dnsPrefetchControl) {
40
- ctx.set('X-DNS-Prefetch-Control', 'off');
41
- }
42
-
43
- if (opts.frameguard) {
44
- setFrameguard(ctx, opts.frameguard);
45
- }
46
-
47
- if (opts.hidePoweredBy) {
48
- ctx.removeHeader('X-Powered-By');
49
- }
50
-
51
- if (opts.hsts) {
52
- setHSTS(ctx, opts.hsts);
53
- }
54
-
55
- if (opts.ieNoOpen) {
56
- ctx.set('X-Download-Options', 'noopen');
57
- }
58
-
59
- if (opts.noSniff) {
60
- ctx.set('X-Content-Type-Options', 'nosniff');
61
- }
62
-
63
- if (opts.originAgentCluster) {
64
- ctx.set('Origin-Agent-Cluster', '?1');
65
- }
66
-
67
- if (opts.permittedCrossDomainPolicies) {
68
- ctx.set('X-Permitted-Cross-Domain-Policies', 'none');
69
- }
70
-
71
- if (opts.referrerPolicy) {
72
- setReferrerPolicy(ctx, opts.referrerPolicy);
73
- }
74
-
75
- if (opts.xssFilter) {
76
- ctx.set('X-XSS-Protection', '1; mode=block');
77
- }
78
-
79
- await next();
80
- };
81
- }
82
-
83
- function setContentSecurityPolicy(ctx, options) {
84
- const defaultPolicy = {
85
- 'default-src': ["'self'"],
86
- 'script-src': ["'self'"],
87
- 'style-src': ["'self'", "'unsafe-inline'"],
88
- 'img-src': ["'self'", 'data:', 'https:'],
89
- 'font-src': ["'self'"],
90
- 'connect-src': ["'self'"],
91
- 'media-src': ["'self'"],
92
- 'object-src': ["'none'"],
93
- 'child-src': ["'self'"],
94
- 'frame-ancestors': ["'none'"],
95
- 'form-action': ["'self'"],
96
- 'base-uri': ["'self'"],
97
- 'manifest-src': ["'self'"]
98
- };
99
-
100
- const policy = typeof options === 'object' ? { ...defaultPolicy, ...options } : defaultPolicy;
101
-
102
- const policyString = Object.keys(policy)
103
- .map(key => `${key} ${policy[key].join(' ')}`)
104
- .join('; ');
105
-
106
- ctx.set('Content-Security-Policy', policyString);
107
- }
108
-
109
- function setFrameguard(ctx, options) {
110
- if (options === true) {
111
- ctx.set('X-Frame-Options', 'DENY');
112
- } else if (typeof options === 'string') {
113
- ctx.set('X-Frame-Options', options);
114
- } else if (typeof options === 'object') {
115
- if (options.action === 'allow-from') {
116
- ctx.set('X-Frame-Options', `ALLOW-FROM ${options.domain}`);
117
- } else {
118
- ctx.set('X-Frame-Options', options.action || 'DENY');
119
- }
120
- }
121
- }
122
-
123
- function setHSTS(ctx, options) {
124
- const defaults = {
125
- maxAge: 31536000, // 1 year
126
- includeSubDomains: true,
127
- preload: false
128
- };
129
-
130
- const opts = typeof options === 'object' ? { ...defaults, ...options } : defaults;
131
-
132
- let hstsHeader = `max-age=${opts.maxAge}`;
133
-
134
- if (opts.includeSubDomains) {
135
- hstsHeader += '; includeSubDomains';
136
- }
137
-
138
- if (opts.preload) {
139
- hstsHeader += '; preload';
140
- }
141
-
142
- ctx.set('Strict-Transport-Security', hstsHeader);
143
- }
144
-
145
- function setReferrerPolicy(ctx, options) {
146
- const policy = typeof options === 'string' ? options : 'no-referrer';
147
- ctx.set('Referrer-Policy', policy);
148
- }
149
-
150
- function csrf(options = {}) {
151
- const opts = {
152
- secret: options.secret || throwMissingCsrfSecretError(),
153
- cookie: options.cookie !== false,
154
- cookieName: options.cookieName || '_csrf',
155
- headerName: options.headerName || 'x-csrf-token',
156
- bodyName: options.bodyName || '_csrf',
157
- value: options.value,
158
- sessionKey: options.sessionKey || 'csrfSecret',
159
- ignoreMethods: options.ignoreMethods || ['GET', 'HEAD', 'OPTIONS'],
160
- ...options
161
- };
162
-
163
- return async (ctx, next) => {
164
- if (opts.ignoreMethods.includes(ctx.method)) {
165
- return next();
166
- }
167
-
168
- const secret = getSecret(ctx, opts);
169
- const token = getTokenFromRequest(ctx, opts);
170
-
171
- if (!token) {
172
- return ctx.status(403).json({ error: 'CSRF token missing' });
173
- }
174
-
175
- if (!verifyToken(token, secret)) {
176
- return ctx.status(403).json({ error: 'Invalid CSRF token' });
177
- }
178
-
179
- await next();
180
- };
181
- }
182
-
183
- function generateSecret() {
184
- return crypto.randomBytes(32).toString('hex');
185
- }
186
-
187
- function generateToken(secret) {
188
- const salt = crypto.randomBytes(8).toString('hex');
189
- const hash = crypto.createHash('sha256').update(salt + secret).digest('hex');
190
- return salt + hash;
191
- }
192
-
193
- function verifyToken(token, secret) {
194
- if (!token || typeof token !== 'string') {
195
- return false;
196
- }
197
-
198
- // Token format: 16 char salt + 64 char hash = 80 chars total
199
- if (token.length !== 80) {
200
- return false;
201
- }
202
-
203
- const salt = token.slice(0, 16);
204
- const hash = token.slice(16);
205
- const expected = crypto.createHash('sha256').update(salt + secret).digest('hex');
206
-
207
- return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(expected));
208
- }
209
-
210
- function getSecret(ctx, opts) {
211
- if (ctx.session && ctx.session[opts.sessionKey]) {
212
- return ctx.session[opts.sessionKey];
213
- }
214
-
215
- const secret = opts.secret || generateSecret();
216
-
217
- if (ctx.session) {
218
- ctx.session[opts.sessionKey] = secret;
219
- }
220
-
221
- return secret;
222
- }
223
-
224
- function getTokenFromRequest(ctx, opts) {
225
- return ctx.get(opts.headerName) ||
226
- (ctx.body && ctx.body[opts.bodyName]) ||
227
- (ctx.cookies && ctx.cookies[opts.cookieName]);
228
- }
229
-
230
- function csrfToken(ctx, options = {}) {
231
- const opts = {
232
- secret: options.secret || generateSecret(),
233
- sessionKey: options.sessionKey || 'csrfSecret',
234
- ...options
235
- };
236
-
237
- const secret = getSecret(ctx, opts);
238
- return generateToken(secret);
239
- }
240
-
241
- function xssProtection(options = {}) {
242
- const opts = {
243
- escapeHtml: options.escapeHtml !== false,
244
- escapeJson: options.escapeJson !== false,
245
- ...options
246
- };
247
-
248
- return async (ctx, next) => {
249
- if (opts.escapeHtml) {
250
- const originalHtml = ctx.html;
251
- ctx.html = function(data) {
252
- return originalHtml.call(this, escapeHtml(data));
253
- };
254
- }
255
-
256
- if (opts.escapeJson) {
257
- const originalJson = ctx.json;
258
- ctx.json = function(data) {
259
- return originalJson.call(this, escapeJsonValues(data));
260
- };
261
- }
262
-
263
- await next();
264
- };
265
- }
266
-
267
- function escapeHtml(text) {
268
- const map = {
269
- '&': '&',
270
- '<': '&lt;',
271
- '>': '&gt;',
272
- '"': '&quot;',
273
- "'": '&#39;'
274
- };
275
-
276
- return String(text).replace(/[&<>"']/g, (s) => map[s]);
277
- }
278
-
279
- function escapeJsonValues(obj) {
280
- if (typeof obj === 'string') {
281
- return escapeHtml(obj);
282
- }
283
-
284
- if (Array.isArray(obj)) {
285
- return obj.map(escapeJsonValues);
286
- }
287
-
288
- if (obj && typeof obj === 'object') {
289
- const escaped = {};
290
- for (const [key, value] of Object.entries(obj)) {
291
- escaped[key] = escapeJsonValues(value);
292
- }
293
- return escaped;
294
- }
295
-
296
- return obj;
297
- }
298
-
299
- function requestSizeLimit(options = {}) {
300
- const opts = {
301
- limit: options.limit || 1024 * 1024, // 1MB
302
- message: options.message || 'Request too large',
303
- statusCode: options.statusCode || 413,
304
- ...options
305
- };
306
-
307
- return async (ctx, next) => {
308
- const contentLength = parseInt(ctx.get('content-length') || '0');
309
-
310
- if (contentLength > opts.limit) {
311
- return ctx.status(opts.statusCode).json({
312
- error: 'Request Too Large',
313
- message: opts.message
314
- });
315
- }
316
-
317
- await next();
318
- };
319
- }
320
-
321
- function throwMissingCsrfSecretError() {
322
- throw new Error(
323
- 'CSRF secret is required for security. ' +
324
- 'Please provide a secret in the csrf options: ' +
325
- 'csrf({ secret: "your-secret-here" })'
326
- );
327
- }
328
-
329
- module.exports = security;
330
- module.exports.csrf = csrf;
331
- module.exports.csrfToken = csrfToken;
332
- module.exports.xssProtection = xssProtection;
1
+ 'use strict';
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
+ .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;
333
445
  module.exports.requestSizeLimit = requestSizeLimit;