@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 +0,0 @@
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;
333
- module.exports.requestSizeLimit = requestSizeLimit;