@oxog/spark 1.1.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 (63) hide show
  1. package/CHANGELOG.md +294 -0
  2. package/LICENSE +21 -0
  3. package/README.md +242 -0
  4. package/dist/LICENSE +21 -0
  5. package/dist/README.md +242 -0
  6. package/dist/core/application.js +957 -0
  7. package/dist/core/context.js +831 -0
  8. package/dist/core/middleware.js +218 -0
  9. package/dist/core/request.js +333 -0
  10. package/dist/core/response.js +375 -0
  11. package/dist/index.js +278 -0
  12. package/dist/middleware/body-parser.js +526 -0
  13. package/dist/middleware/cache.js +171 -0
  14. package/dist/middleware/compression.js +183 -0
  15. package/dist/middleware/cors.js +95 -0
  16. package/dist/middleware/health.js +219 -0
  17. package/dist/middleware/index.js +21 -0
  18. package/dist/middleware/logger.js +195 -0
  19. package/dist/middleware/metrics.js +328 -0
  20. package/dist/middleware/rate-limit.js +320 -0
  21. package/dist/middleware/security.js +333 -0
  22. package/dist/middleware/session.js +530 -0
  23. package/dist/middleware/static.js +299 -0
  24. package/dist/package.json +62 -0
  25. package/dist/router/layer.js +117 -0
  26. package/dist/router/route.js +123 -0
  27. package/dist/router/router.js +756 -0
  28. package/dist/types/index.d.ts +291 -0
  29. package/dist/utils/async-handler.js +145 -0
  30. package/dist/utils/cache.js +441 -0
  31. package/dist/utils/context-pool.js +83 -0
  32. package/dist/utils/error-types.js +132 -0
  33. package/dist/utils/http.js +413 -0
  34. package/dist/utils/regex-validator.js +177 -0
  35. package/package.json +89 -0
  36. package/src/core/application.js +957 -0
  37. package/src/core/context.js +831 -0
  38. package/src/core/middleware.js +218 -0
  39. package/src/core/request.js +333 -0
  40. package/src/core/response.js +375 -0
  41. package/src/index.js +278 -0
  42. package/src/middleware/body-parser.js +526 -0
  43. package/src/middleware/cache.js +171 -0
  44. package/src/middleware/compression.js +183 -0
  45. package/src/middleware/cors.js +95 -0
  46. package/src/middleware/health.js +219 -0
  47. package/src/middleware/index.js +21 -0
  48. package/src/middleware/logger.js +195 -0
  49. package/src/middleware/metrics.js +328 -0
  50. package/src/middleware/rate-limit.js +320 -0
  51. package/src/middleware/security.js +333 -0
  52. package/src/middleware/session.js +530 -0
  53. package/src/middleware/static.js +299 -0
  54. package/src/router/layer.js +117 -0
  55. package/src/router/route.js +123 -0
  56. package/src/router/router.js +756 -0
  57. package/src/utils/async-handler.js +145 -0
  58. package/src/utils/cache.js +441 -0
  59. package/src/utils/context-pool.js +83 -0
  60. package/src/utils/error-types.js +132 -0
  61. package/src/utils/http.js +413 -0
  62. package/src/utils/regex-validator.js +177 -0
  63. package/types/index.d.ts +291 -0
@@ -0,0 +1,333 @@
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;