@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.
- package/CHANGELOG.md +632 -315
- package/LICENSE +20 -20
- package/README.md +288 -241
- package/package.json +83 -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 +703 -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 +536 -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,322 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
const DEFAULT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
|
|
4
|
-
const DEFAULT_MAX_REQUESTS = 100;
|
|
5
|
-
const DEFAULT_MESSAGE = 'Too many requests, please try again later.';
|
|
6
|
-
|
|
7
|
-
class MemoryStore {
|
|
8
|
-
constructor() {
|
|
9
|
-
this.store = new Map();
|
|
10
|
-
this.resetTimes = new Map();
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
async incr(key, windowMs) {
|
|
14
|
-
const now = Date.now();
|
|
15
|
-
const resetTime = this.resetTimes.get(key) || now;
|
|
16
|
-
|
|
17
|
-
if (now > resetTime) {
|
|
18
|
-
this.store.set(key, 1);
|
|
19
|
-
this.resetTimes.set(key, now + windowMs);
|
|
20
|
-
return { totalHits: 1, resetTime: now + windowMs };
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
const current = this.store.get(key) || 0;
|
|
24
|
-
const newCount = current + 1;
|
|
25
|
-
this.store.set(key, newCount);
|
|
26
|
-
|
|
27
|
-
return { totalHits: newCount, resetTime };
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
async decrement(key) {
|
|
31
|
-
const current = this.store.get(key) || 0;
|
|
32
|
-
if (current > 0) {
|
|
33
|
-
this.store.set(key, current - 1);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
async reset(key) {
|
|
38
|
-
this.store.delete(key);
|
|
39
|
-
this.resetTimes.delete(key);
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
cleanup() {
|
|
43
|
-
const now = Date.now();
|
|
44
|
-
for (const [key, resetTime] of this.resetTimes) {
|
|
45
|
-
if (now > resetTime) {
|
|
46
|
-
this.store.delete(key);
|
|
47
|
-
this.resetTimes.delete(key);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
function rateLimit(options = {}) {
|
|
54
|
-
const opts = {
|
|
55
|
-
windowMs: options.windowMs || DEFAULT_WINDOW_MS,
|
|
56
|
-
max: options.max || DEFAULT_MAX_REQUESTS,
|
|
57
|
-
message: options.message || DEFAULT_MESSAGE,
|
|
58
|
-
statusCode: options.statusCode || 429,
|
|
59
|
-
headers: options.headers !== false,
|
|
60
|
-
keyGenerator: options.keyGenerator || defaultKeyGenerator,
|
|
61
|
-
handler: options.handler || defaultHandler,
|
|
62
|
-
onLimitReached: options.onLimitReached,
|
|
63
|
-
skipSuccessfulRequests: options.skipSuccessfulRequests || false,
|
|
64
|
-
skipFailedRequests: options.skipFailedRequests || false,
|
|
65
|
-
store: options.store || new MemoryStore(),
|
|
66
|
-
...options
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
// Start cleanup interval
|
|
70
|
-
let cleanupInterval;
|
|
71
|
-
if (opts.store.cleanup) {
|
|
72
|
-
// Use smaller interval for cleanup (1/4 of window)
|
|
73
|
-
const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
|
|
74
|
-
cleanupInterval = setInterval(() => {
|
|
75
|
-
opts.store.cleanup();
|
|
76
|
-
}, cleanupPeriod);
|
|
77
|
-
|
|
78
|
-
// Allow cleanup interval to be stopped when server shuts down
|
|
79
|
-
if (cleanupInterval.unref) {
|
|
80
|
-
cleanupInterval.unref();
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
const middleware = async (ctx, next) => {
|
|
85
|
-
const key = opts.keyGenerator(ctx);
|
|
86
|
-
const { totalHits, resetTime } = await opts.store.incr(key, opts.windowMs);
|
|
87
|
-
|
|
88
|
-
if (opts.headers) {
|
|
89
|
-
ctx.set('X-RateLimit-Limit', opts.max);
|
|
90
|
-
ctx.set('X-RateLimit-Remaining', Math.max(0, opts.max - totalHits));
|
|
91
|
-
ctx.set('X-RateLimit-Reset', new Date(resetTime).toISOString());
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
if (totalHits <= opts.max) {
|
|
95
|
-
await next();
|
|
96
|
-
|
|
97
|
-
if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
|
|
98
|
-
await opts.store.decrement(key);
|
|
99
|
-
}
|
|
100
|
-
} else {
|
|
101
|
-
if (opts.onLimitReached) {
|
|
102
|
-
opts.onLimitReached(ctx, opts);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
return opts.handler(ctx, opts);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
if (opts.skipFailedRequests && ctx.statusCode >= 400) {
|
|
109
|
-
await opts.store.decrement(key);
|
|
110
|
-
}
|
|
111
|
-
};
|
|
112
|
-
|
|
113
|
-
// Attach cleanup method to middleware for manual cleanup
|
|
114
|
-
middleware.cleanup = () => {
|
|
115
|
-
if (cleanupInterval) {
|
|
116
|
-
clearInterval(cleanupInterval);
|
|
117
|
-
cleanupInterval = null;
|
|
118
|
-
}
|
|
119
|
-
if (opts.store.cleanup) {
|
|
120
|
-
opts.store.cleanup();
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
|
|
124
|
-
// Attach store for external access if needed
|
|
125
|
-
middleware.store = opts.store;
|
|
126
|
-
|
|
127
|
-
return middleware;
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
function defaultKeyGenerator(ctx) {
|
|
131
|
-
return ctx.ip();
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
function defaultHandler(ctx, opts) {
|
|
135
|
-
ctx.set('Retry-After', Math.round(opts.windowMs / 1000));
|
|
136
|
-
ctx.status(opts.statusCode).json({
|
|
137
|
-
error: 'Too Many Requests',
|
|
138
|
-
message: opts.message
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
function slowDown(options = {}) {
|
|
143
|
-
const opts = {
|
|
144
|
-
windowMs: options.windowMs || DEFAULT_WINDOW_MS,
|
|
145
|
-
delayAfter: options.delayAfter || 1,
|
|
146
|
-
delayMs: options.delayMs || 1000,
|
|
147
|
-
maxDelayMs: options.maxDelayMs || 60000,
|
|
148
|
-
skipSuccessfulRequests: options.skipSuccessfulRequests || false,
|
|
149
|
-
skipFailedRequests: options.skipFailedRequests || false,
|
|
150
|
-
keyGenerator: options.keyGenerator || defaultKeyGenerator,
|
|
151
|
-
store: options.store || new MemoryStore(),
|
|
152
|
-
...options
|
|
153
|
-
};
|
|
154
|
-
|
|
155
|
-
// Start cleanup interval for slowDown store
|
|
156
|
-
let cleanupInterval;
|
|
157
|
-
if (opts.store.cleanup) {
|
|
158
|
-
const cleanupPeriod = Math.max(60000, Math.floor(opts.windowMs / 4));
|
|
159
|
-
cleanupInterval = setInterval(() => {
|
|
160
|
-
opts.store.cleanup();
|
|
161
|
-
}, cleanupPeriod);
|
|
162
|
-
|
|
163
|
-
if (cleanupInterval.unref) {
|
|
164
|
-
cleanupInterval.unref();
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const middleware = async (ctx, next) => {
|
|
169
|
-
const key = opts.keyGenerator(ctx);
|
|
170
|
-
const { totalHits } = await opts.store.incr(key, opts.windowMs);
|
|
171
|
-
|
|
172
|
-
if (totalHits > opts.delayAfter) {
|
|
173
|
-
const delay = Math.min(
|
|
174
|
-
(totalHits - opts.delayAfter) * opts.delayMs,
|
|
175
|
-
opts.maxDelayMs
|
|
176
|
-
);
|
|
177
|
-
|
|
178
|
-
await new Promise(resolve => setTimeout(resolve, delay));
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
await next();
|
|
182
|
-
|
|
183
|
-
if (opts.skipSuccessfulRequests && ctx.statusCode >= 200 && ctx.statusCode < 300) {
|
|
184
|
-
await opts.store.decrement(key);
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
if (opts.skipFailedRequests && ctx.statusCode >= 400) {
|
|
188
|
-
await opts.store.decrement(key);
|
|
189
|
-
}
|
|
190
|
-
};
|
|
191
|
-
|
|
192
|
-
// Attach cleanup method
|
|
193
|
-
middleware.cleanup = () => {
|
|
194
|
-
if (cleanupInterval) {
|
|
195
|
-
clearInterval(cleanupInterval);
|
|
196
|
-
cleanupInterval = null;
|
|
197
|
-
}
|
|
198
|
-
if (opts.store.cleanup) {
|
|
199
|
-
opts.store.cleanup();
|
|
200
|
-
}
|
|
201
|
-
};
|
|
202
|
-
|
|
203
|
-
middleware.store = opts.store;
|
|
204
|
-
|
|
205
|
-
return middleware;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
class TokenBucket {
|
|
209
|
-
constructor(capacity, refillRate, refillPeriod = 1000) {
|
|
210
|
-
this.capacity = capacity;
|
|
211
|
-
this.tokens = capacity;
|
|
212
|
-
this.refillRate = refillRate;
|
|
213
|
-
this.refillPeriod = refillPeriod;
|
|
214
|
-
this.lastRefill = Date.now();
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
consume(tokens = 1) {
|
|
218
|
-
this.refill();
|
|
219
|
-
|
|
220
|
-
if (this.tokens >= tokens) {
|
|
221
|
-
this.tokens -= tokens;
|
|
222
|
-
return true;
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
return false;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
refill() {
|
|
229
|
-
const now = Date.now();
|
|
230
|
-
const timePassed = now - this.lastRefill;
|
|
231
|
-
const tokensToAdd = Math.floor(timePassed / this.refillPeriod * this.refillRate);
|
|
232
|
-
|
|
233
|
-
if (tokensToAdd > 0) {
|
|
234
|
-
this.tokens = Math.min(this.capacity, this.tokens + tokensToAdd);
|
|
235
|
-
this.lastRefill = now;
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function tokenBucket(options = {}) {
|
|
241
|
-
const opts = {
|
|
242
|
-
capacity: options.capacity || 10,
|
|
243
|
-
refillRate: options.refillRate || 1,
|
|
244
|
-
refillPeriod: options.refillPeriod || 1000,
|
|
245
|
-
keyGenerator: options.keyGenerator || defaultKeyGenerator,
|
|
246
|
-
message: options.message || DEFAULT_MESSAGE,
|
|
247
|
-
statusCode: options.statusCode || 429,
|
|
248
|
-
cleanupPeriod: options.cleanupPeriod || 300000, // 5 minutes
|
|
249
|
-
maxBuckets: options.maxBuckets || 10000, // Maximum number of buckets to prevent memory leak
|
|
250
|
-
...options
|
|
251
|
-
};
|
|
252
|
-
|
|
253
|
-
const buckets = new Map();
|
|
254
|
-
const lastActivity = new Map();
|
|
255
|
-
|
|
256
|
-
// Cleanup old buckets
|
|
257
|
-
const cleanupInterval = setInterval(() => {
|
|
258
|
-
const now = Date.now();
|
|
259
|
-
const keysToDelete = [];
|
|
260
|
-
|
|
261
|
-
for (const [key, timestamp] of lastActivity) {
|
|
262
|
-
if (now - timestamp > opts.cleanupPeriod) {
|
|
263
|
-
keysToDelete.push(key);
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
for (const key of keysToDelete) {
|
|
268
|
-
buckets.delete(key);
|
|
269
|
-
lastActivity.delete(key);
|
|
270
|
-
}
|
|
271
|
-
}, Math.max(60000, opts.cleanupPeriod / 4));
|
|
272
|
-
|
|
273
|
-
if (cleanupInterval.unref) {
|
|
274
|
-
cleanupInterval.unref();
|
|
275
|
-
}
|
|
276
|
-
|
|
277
|
-
const middleware = async (ctx, next) => {
|
|
278
|
-
const key = opts.keyGenerator(ctx);
|
|
279
|
-
|
|
280
|
-
// Prevent unlimited growth
|
|
281
|
-
if (!buckets.has(key) && buckets.size >= opts.maxBuckets) {
|
|
282
|
-
// Remove oldest bucket
|
|
283
|
-
const oldestKey = lastActivity.entries().next().value?.[0];
|
|
284
|
-
if (oldestKey) {
|
|
285
|
-
buckets.delete(oldestKey);
|
|
286
|
-
lastActivity.delete(oldestKey);
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
if (!buckets.has(key)) {
|
|
291
|
-
buckets.set(key, new TokenBucket(opts.capacity, opts.refillRate, opts.refillPeriod));
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
const bucket = buckets.get(key);
|
|
295
|
-
lastActivity.set(key, Date.now());
|
|
296
|
-
|
|
297
|
-
if (bucket.consume()) {
|
|
298
|
-
await next();
|
|
299
|
-
} else {
|
|
300
|
-
ctx.status(opts.statusCode).json({
|
|
301
|
-
error: 'Too Many Requests',
|
|
302
|
-
message: opts.message
|
|
303
|
-
});
|
|
304
|
-
}
|
|
305
|
-
};
|
|
306
|
-
|
|
307
|
-
// Attach cleanup method
|
|
308
|
-
middleware.cleanup = () => {
|
|
309
|
-
if (cleanupInterval) {
|
|
310
|
-
clearInterval(cleanupInterval);
|
|
311
|
-
}
|
|
312
|
-
buckets.clear();
|
|
313
|
-
lastActivity.clear();
|
|
314
|
-
};
|
|
315
|
-
|
|
316
|
-
return middleware;
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
module.exports = rateLimit;
|
|
320
|
-
module.exports.slowDown = slowDown;
|
|
321
|
-
module.exports.tokenBucket = tokenBucket;
|
|
322
|
-
module.exports.MemoryStore = MemoryStore;
|
|
@@ -1,335 +0,0 @@
|
|
|
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
|
-
.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
|
-
'<': '<',
|
|
273
|
-
'>': '>',
|
|
274
|
-
'"': '"',
|
|
275
|
-
"'": '''
|
|
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;
|
|
335
|
-
module.exports.requestSizeLimit = requestSizeLimit;
|