barejs 0.1.50 → 0.1.51
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/README.md +47 -10
- package/dist/index.js +92 -91
- package/dist/types/client/index.d.ts +23 -23
- package/dist/types/core/bare.d.ts +74 -4
- package/dist/types/core/context.d.ts +2 -0
- package/dist/types/core/router.d.ts +19 -9
- package/dist/types/index.d.ts +8 -4
- package/dist/types/security/auth.d.ts +10 -3
- package/dist/types/security/resilience.d.ts +17 -0
- package/dist/types/security/validators.d.ts +2 -0
- package/dist/types/utils/compress.d.ts +12 -0
- package/dist/types/utils/health.d.ts +17 -0
- package/dist/types/utils/logger.d.ts +22 -0
- package/dist/types/utils/openapi.d.ts +23 -1
- package/llms.txt +1 -1
- package/package.json +1 -1
- package/src/client/index.ts +58 -17
- package/src/core/bare.ts +216 -20
- package/src/core/context.ts +12 -7
- package/src/core/router.ts +27 -11
- package/src/index.ts +8 -4
- package/src/security/auth.ts +67 -11
- package/src/security/hash.ts +8 -2
- package/src/security/idempotency.ts +22 -3
- package/src/security/rateLimit.ts +1 -6
- package/src/security/resilience.ts +91 -0
- package/src/security/validators.ts +4 -1
- package/src/utils/compress.ts +49 -0
- package/src/utils/health.ts +65 -0
- package/src/utils/logger.ts +66 -0
- package/src/utils/openapi.ts +10 -0
- package/src/utils/static.ts +11 -2
|
@@ -28,13 +28,23 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
28
28
|
const inFlight = new Set<string>();
|
|
29
29
|
|
|
30
30
|
const mw: Middleware = (ctx: Context) => {
|
|
31
|
-
const
|
|
32
|
-
if (!
|
|
31
|
+
const rawKey = ctx.req.headers.get(headerName);
|
|
32
|
+
if (!rawKey) {
|
|
33
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const rawUrl = ctx.req.url;
|
|
38
|
+
const s = rawUrl.indexOf('/', 8);
|
|
39
|
+
const q = s === -1 ? -1 : rawUrl.indexOf('?', s);
|
|
40
|
+
const path = s === -1 ? '/' : (q === -1 ? rawUrl.slice(s) : rawUrl.slice(s, q));
|
|
41
|
+
const key = `${ctx.req.method}:${path}:${rawKey}`;
|
|
33
42
|
|
|
34
43
|
const now = Date.now();
|
|
35
44
|
const existing = cache.get(key);
|
|
36
45
|
if (existing) {
|
|
37
46
|
if (now < existing.expiresAt) {
|
|
47
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
38
48
|
return Response.json(existing.body, {
|
|
39
49
|
status: existing.status,
|
|
40
50
|
headers: { 'X-Idempotent-Replayed': 'true' }
|
|
@@ -44,6 +54,7 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
44
54
|
}
|
|
45
55
|
|
|
46
56
|
if (inFlight.has(key)) {
|
|
57
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
47
58
|
return Response.json(
|
|
48
59
|
{ status: 'error', code: 'IDEMPOTENT_IN_FLIGHT', message: 'Duplicate request is currently in flight' },
|
|
49
60
|
{ status: 409 }
|
|
@@ -52,13 +63,13 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
52
63
|
|
|
53
64
|
inFlight.add(key);
|
|
54
65
|
(ctx as any)._idempotencyKey = key;
|
|
55
|
-
(ctx as any)._idemInFlight = inFlight;
|
|
56
66
|
return undefined;
|
|
57
67
|
};
|
|
58
68
|
|
|
59
69
|
(mw as any).__idempotencyCommit = (ctx: Context, resVal: any, status: number) => {
|
|
60
70
|
const key = (ctx as any)._idempotencyKey;
|
|
61
71
|
if (!key) return;
|
|
72
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
62
73
|
inFlight.delete(key);
|
|
63
74
|
if (status >= 200 && status < 300 && !(resVal instanceof Response)) {
|
|
64
75
|
if (cache.size >= maxKeys) {
|
|
@@ -73,6 +84,14 @@ export const idempotency = (options: IdempotencyOptions = {}): Middleware => {
|
|
|
73
84
|
}
|
|
74
85
|
};
|
|
75
86
|
|
|
87
|
+
(mw as any).__idempotencyRelease = (ctx: Context) => {
|
|
88
|
+
const key = (ctx as any)._idempotencyKey;
|
|
89
|
+
if (key) {
|
|
90
|
+
(ctx as any)._idempotencyKey = undefined;
|
|
91
|
+
inFlight.delete(key);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
76
95
|
return mw;
|
|
77
96
|
};
|
|
78
97
|
|
|
@@ -18,12 +18,7 @@ export const rateLimit = (options: RateLimitOptions = {}): Middleware => {
|
|
|
18
18
|
const max = options.max ?? 100;
|
|
19
19
|
const message = options.message ?? 'Too many requests, please try again later.';
|
|
20
20
|
const maxEntries = options.maxEntries ?? 10_000;
|
|
21
|
-
const keyGenerator =
|
|
22
|
-
options.keyGenerator ??
|
|
23
|
-
((ctx: Context) =>
|
|
24
|
-
ctx.req.headers.get('x-forwarded-for')?.split(',')[0]?.trim() ||
|
|
25
|
-
ctx.req.headers.get('x-real-ip') ||
|
|
26
|
-
'global');
|
|
21
|
+
const keyGenerator = options.keyGenerator ?? ((ctx: Context) => ctx.ip);
|
|
27
22
|
|
|
28
23
|
const buckets = new Map<string, RateBucket>();
|
|
29
24
|
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export type CircuitState = 'CLOSED' | 'OPEN' | 'HALF_OPEN';
|
|
4
|
+
|
|
5
|
+
export interface CircuitBreakerOptions {
|
|
6
|
+
/** Number of consecutive failures before opening the circuit (default: 5) */
|
|
7
|
+
failureThreshold?: number;
|
|
8
|
+
/** Cooldown in milliseconds before transitioning from OPEN to HALF_OPEN (default: 30000) */
|
|
9
|
+
resetTimeoutMs?: number;
|
|
10
|
+
/** Custom predicate to determine if a response or error counts as a failure */
|
|
11
|
+
isFailure?: (res: any, err?: any) => boolean;
|
|
12
|
+
/** Optional callback fired when circuit state changes */
|
|
13
|
+
onStateChange?: (from: CircuitState, to: CircuitState) => void;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Lightweight Circuit Breaker middleware.
|
|
18
|
+
* Protects downstream databases and external APIs from cascading failures.
|
|
19
|
+
*/
|
|
20
|
+
export const circuitBreaker = (options: CircuitBreakerOptions = {}): Middleware => {
|
|
21
|
+
const failureThreshold = options.failureThreshold ?? 5;
|
|
22
|
+
const resetTimeoutMs = options.resetTimeoutMs ?? 30_000;
|
|
23
|
+
const isFailure = options.isFailure ?? ((res: any, err?: any) => Boolean(err) || (res instanceof Response && res.status >= 500));
|
|
24
|
+
|
|
25
|
+
let state: CircuitState = 'CLOSED';
|
|
26
|
+
let failures = 0;
|
|
27
|
+
let openedAt = 0;
|
|
28
|
+
let halfOpenInFlight = false;
|
|
29
|
+
|
|
30
|
+
const setState = (nextState: CircuitState) => {
|
|
31
|
+
if (state !== nextState) {
|
|
32
|
+
const prev = state;
|
|
33
|
+
state = nextState;
|
|
34
|
+
options.onStateChange?.(prev, nextState);
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const runWithBreaker = async (exec: () => any) => {
|
|
39
|
+
if (state === 'OPEN') {
|
|
40
|
+
const elapsed = Date.now() - openedAt;
|
|
41
|
+
if (elapsed < resetTimeoutMs) {
|
|
42
|
+
const retryAfterSec = Math.max(1, Math.ceil((resetTimeoutMs - elapsed) / 1000));
|
|
43
|
+
return Response.json(
|
|
44
|
+
{ status: 'error', code: 'CIRCUIT_OPEN', message: 'Service temporarily unavailable' },
|
|
45
|
+
{ status: 503, headers: { 'Retry-After': String(retryAfterSec) } }
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
setState('HALF_OPEN');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
let isHalfOpenProbe = false;
|
|
52
|
+
if (state === 'HALF_OPEN') {
|
|
53
|
+
if (halfOpenInFlight) {
|
|
54
|
+
return Response.json(
|
|
55
|
+
{ status: 'error', code: 'CIRCUIT_OPEN', message: 'Service temporarily unavailable' },
|
|
56
|
+
{ status: 503, headers: { 'Retry-After': '1' } }
|
|
57
|
+
);
|
|
58
|
+
}
|
|
59
|
+
halfOpenInFlight = true;
|
|
60
|
+
isHalfOpenProbe = true;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
try {
|
|
64
|
+
const res = await exec();
|
|
65
|
+
if (isFailure(res)) {
|
|
66
|
+
failures++;
|
|
67
|
+
if (isHalfOpenProbe || failures >= failureThreshold) {
|
|
68
|
+
openedAt = Date.now();
|
|
69
|
+
setState('OPEN');
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
failures = 0;
|
|
73
|
+
if (isHalfOpenProbe) setState('CLOSED');
|
|
74
|
+
}
|
|
75
|
+
return res;
|
|
76
|
+
} catch (err) {
|
|
77
|
+
failures++;
|
|
78
|
+
if (isHalfOpenProbe || failures >= failureThreshold) {
|
|
79
|
+
openedAt = Date.now();
|
|
80
|
+
setState('OPEN');
|
|
81
|
+
}
|
|
82
|
+
throw err;
|
|
83
|
+
} finally {
|
|
84
|
+
if (isHalfOpenProbe) halfOpenInFlight = false;
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const mw: Middleware = (_ctx: Context, next?: Next) => runWithBreaker(() => (next ? next() : undefined));
|
|
89
|
+
(mw as any).__circuitBreaker = runWithBreaker;
|
|
90
|
+
return mw;
|
|
91
|
+
};
|
|
@@ -163,6 +163,8 @@ export interface RouteSchemas {
|
|
|
163
163
|
params?: any;
|
|
164
164
|
headers?: any;
|
|
165
165
|
response?: any;
|
|
166
|
+
/** Strip undeclared properties from validated body using JIT projector (prevents Mass Assignment) */
|
|
167
|
+
stripUnknown?: boolean;
|
|
166
168
|
detail?: RouteDetail;
|
|
167
169
|
maxBodySize?: number;
|
|
168
170
|
}
|
|
@@ -269,6 +271,7 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
269
271
|
const queryCheck = schemas.query ? compileSingleSchema(schemas.query) : null;
|
|
270
272
|
const paramsCheck = schemas.params ? compileSingleSchema(schemas.params) : null;
|
|
271
273
|
const headersCheck = schemas.headers ? compileSingleSchema(schemas.headers) : null;
|
|
274
|
+
const bodyProjector = schemas.stripUnknown && schemas.body ? compileProjector(schemas.body) : null;
|
|
272
275
|
const responseFilter = schemas.response ? createResponseFilter(schemas.response) : null;
|
|
273
276
|
const maxBodySize = schemas.maxBodySize ?? 1048576;
|
|
274
277
|
|
|
@@ -320,7 +323,7 @@ export const schemaValidator = (schemas: RouteSchemas): Middleware => {
|
|
|
320
323
|
}
|
|
321
324
|
const r = bodyCheck(body);
|
|
322
325
|
if (!r.ok) return errorJSON({ status: 'error', code: 'VALIDATION_FAILED', error: r.error });
|
|
323
|
-
ctx.body = r.data;
|
|
326
|
+
ctx.body = bodyProjector ? bodyProjector(r.data) : r.data;
|
|
324
327
|
|
|
325
328
|
return next ? next() : undefined;
|
|
326
329
|
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Context, Middleware, Next } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface CompressOptions {
|
|
4
|
+
/** Minimum response size in bytes before gzip compression is applied (default: 1024) */
|
|
5
|
+
minSize?: number;
|
|
6
|
+
/** Gzip compression level 0-9 (default: 6) */
|
|
7
|
+
level?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Zero-dependency Gzip compression middleware powered by Bun.gzipSync (native C/Zig).
|
|
12
|
+
* Skips streaming SSE responses, already-encoded responses, and payloads below minSize.
|
|
13
|
+
*/
|
|
14
|
+
export const compress = (options: CompressOptions = {}): Middleware => {
|
|
15
|
+
const minSize = options.minSize ?? 1024;
|
|
16
|
+
const level = options.level ?? 6;
|
|
17
|
+
|
|
18
|
+
const applyCompress = async (ctx: Context, res: any) => {
|
|
19
|
+
if (ctx.req.method === 'HEAD') return res;
|
|
20
|
+
const accept = ctx.req.headers.get('accept-encoding');
|
|
21
|
+
if (!accept || !accept.includes('gzip')) return res;
|
|
22
|
+
if (!(res instanceof Response)) return res;
|
|
23
|
+
if (res.status === 204 || res.status === 304) return res;
|
|
24
|
+
if (res.headers.has('content-encoding')) return res;
|
|
25
|
+
|
|
26
|
+
const ct = res.headers.get('content-type') || '';
|
|
27
|
+
if (ct.includes('text/event-stream')) return res;
|
|
28
|
+
|
|
29
|
+
const buf = await res.arrayBuffer();
|
|
30
|
+
if (buf.byteLength < minSize) {
|
|
31
|
+
return new Response(buf, { status: res.status, headers: res.headers });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const gz = Bun.gzipSync(new Uint8Array(buf), { level });
|
|
35
|
+
const headers = new Headers(res.headers);
|
|
36
|
+
headers.set('Content-Encoding', 'gzip');
|
|
37
|
+
headers.set('Vary', 'Accept-Encoding');
|
|
38
|
+
headers.delete('Content-Length');
|
|
39
|
+
|
|
40
|
+
return new Response(gz, { status: res.status, headers });
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const mw: Middleware = async (ctx: Context, next?: Next) => {
|
|
44
|
+
const res = await (next ? next() : undefined);
|
|
45
|
+
return applyCompress(ctx, res);
|
|
46
|
+
};
|
|
47
|
+
(mw as any).__compress = applyCompress;
|
|
48
|
+
return mw;
|
|
49
|
+
};
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { BarePlugin } from '../index';
|
|
2
|
+
|
|
3
|
+
export type HealthCheckFn = () => boolean | Promise<boolean>;
|
|
4
|
+
|
|
5
|
+
export interface HealthcheckOptions {
|
|
6
|
+
/** Liveness endpoint path (default: '/health') */
|
|
7
|
+
path?: string;
|
|
8
|
+
/** Optional readiness endpoint path (e.g. '/ready') */
|
|
9
|
+
readyPath?: string;
|
|
10
|
+
/** Optional version string to include in response */
|
|
11
|
+
version?: string;
|
|
12
|
+
/** Named dependency checks (e.g. { db: () => pingDb() }) */
|
|
13
|
+
checks?: Record<string, HealthCheckFn>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Built-in Healthcheck & Readiness plugin for BareJS.
|
|
18
|
+
* Registers /health (and optional /ready) returning 200 OK or 503 Service Unavailable.
|
|
19
|
+
*/
|
|
20
|
+
export const healthcheck = (options: HealthcheckOptions = {}): BarePlugin => {
|
|
21
|
+
const path = options.path ?? '/health';
|
|
22
|
+
const readyPath = options.readyPath;
|
|
23
|
+
const checks = options.checks;
|
|
24
|
+
const startedAt = Date.now();
|
|
25
|
+
|
|
26
|
+
const evaluate = async () => {
|
|
27
|
+
const checkResults: Record<string, 'ok' | 'fail'> = {};
|
|
28
|
+
let healthy = true;
|
|
29
|
+
|
|
30
|
+
if (checks) {
|
|
31
|
+
const entries = Object.entries(checks);
|
|
32
|
+
await Promise.all(
|
|
33
|
+
entries.map(async ([name, fn]) => {
|
|
34
|
+
try {
|
|
35
|
+
const ok = await fn();
|
|
36
|
+
checkResults[name] = ok ? 'ok' : 'fail';
|
|
37
|
+
if (!ok) healthy = false;
|
|
38
|
+
} catch {
|
|
39
|
+
checkResults[name] = 'fail';
|
|
40
|
+
healthy = false;
|
|
41
|
+
}
|
|
42
|
+
})
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const payload: Record<string, any> = {
|
|
47
|
+
status: healthy ? 'ok' : 'degraded',
|
|
48
|
+
uptimeMs: Date.now() - startedAt,
|
|
49
|
+
timestamp: new Date().toISOString()
|
|
50
|
+
};
|
|
51
|
+
if (options.version) payload.version = options.version;
|
|
52
|
+
if (checks) payload.checks = checkResults;
|
|
53
|
+
|
|
54
|
+
return Response.json(payload, { status: healthy ? 200 : 503 });
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
return {
|
|
58
|
+
install(app: any) {
|
|
59
|
+
app.get(path, evaluate);
|
|
60
|
+
if (readyPath && readyPath !== path) {
|
|
61
|
+
app.get(readyPath, evaluate);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Context, Middleware } from '../core/context';
|
|
2
|
+
|
|
3
|
+
export interface LogEntry {
|
|
4
|
+
timestamp: string;
|
|
5
|
+
method: string;
|
|
6
|
+
path: string;
|
|
7
|
+
requestId?: string;
|
|
8
|
+
ip?: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface LoggerOptions {
|
|
12
|
+
/** Output format: 'pretty' (default) or 'json' */
|
|
13
|
+
format?: 'pretty' | 'json';
|
|
14
|
+
/** Attach X-Request-Id response header from ctx.requestId (default: true) */
|
|
15
|
+
requestId?: boolean;
|
|
16
|
+
/** Skip logging for matching requests */
|
|
17
|
+
skip?: (ctx: Context, path: string) => boolean;
|
|
18
|
+
/** Custom log sink (defaults to console.log) */
|
|
19
|
+
onLog?: (entry: LogEntry) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const getPath = (rawUrl: string): string => {
|
|
23
|
+
const s = rawUrl.indexOf('/', 8);
|
|
24
|
+
if (s === -1) return '/';
|
|
25
|
+
const q = rawUrl.indexOf('?', s);
|
|
26
|
+
return q === -1 ? rawUrl.slice(s) : rawUrl.slice(s, q);
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Lightweight structured/pretty request logger & X-Request-Id middleware.
|
|
31
|
+
*/
|
|
32
|
+
export const logger = (options: LoggerOptions = {}): Middleware => {
|
|
33
|
+
const format = options.format ?? 'pretty';
|
|
34
|
+
const attachId = options.requestId ?? true;
|
|
35
|
+
const skip = options.skip;
|
|
36
|
+
const sink = options.onLog;
|
|
37
|
+
|
|
38
|
+
return (ctx: Context, next) => {
|
|
39
|
+
const path = getPath(ctx.req.url);
|
|
40
|
+
if (skip?.(ctx, path)) return next();
|
|
41
|
+
|
|
42
|
+
const reqId = attachId ? ctx.requestId : undefined;
|
|
43
|
+
if (reqId) {
|
|
44
|
+
ctx.setHeader('x-request-id', reqId);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const entry: LogEntry = {
|
|
48
|
+
timestamp: new Date().toISOString(),
|
|
49
|
+
method: ctx.req.method,
|
|
50
|
+
path,
|
|
51
|
+
...(reqId ? { requestId: reqId } : {}),
|
|
52
|
+
ip: ctx.ip
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
if (sink) {
|
|
56
|
+
sink(entry);
|
|
57
|
+
} else if (format === 'json') {
|
|
58
|
+
console.log(JSON.stringify(entry));
|
|
59
|
+
} else {
|
|
60
|
+
const idPart = reqId ? ` [${reqId.slice(0, 8)}]` : '';
|
|
61
|
+
console.log(`[${entry.timestamp}] ${entry.method} ${entry.path}${idPart}`);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
return next();
|
|
65
|
+
};
|
|
66
|
+
};
|
package/src/utils/openapi.ts
CHANGED
|
@@ -2,6 +2,10 @@ export interface OpenAPIOptions {
|
|
|
2
2
|
title?: string;
|
|
3
3
|
version?: string;
|
|
4
4
|
description?: string;
|
|
5
|
+
servers?: Array<{ url: string; description?: string }>;
|
|
6
|
+
tags?: Array<{ name: string; description?: string }>;
|
|
7
|
+
securitySchemes?: Record<string, Record<string, any>>;
|
|
8
|
+
security?: Array<Record<string, string[]>>;
|
|
5
9
|
}
|
|
6
10
|
|
|
7
11
|
const zodToJsonSchema = (schema: any): Record<string, any> => {
|
|
@@ -129,6 +133,12 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
|
|
|
129
133
|
version: options.version || '1.0.0',
|
|
130
134
|
...(options.description ? { description: options.description } : {})
|
|
131
135
|
},
|
|
136
|
+
...(options.servers?.length ? { servers: options.servers } : {}),
|
|
137
|
+
...(options.tags?.length ? { tags: options.tags } : {}),
|
|
138
|
+
...(options.securitySchemes
|
|
139
|
+
? { components: { securitySchemes: options.securitySchemes } }
|
|
140
|
+
: {}),
|
|
141
|
+
...(options.security?.length ? { security: options.security } : {}),
|
|
132
142
|
paths
|
|
133
143
|
};
|
|
134
144
|
};
|
package/src/utils/static.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { resolve, sep } from 'node:path';
|
|
2
|
-
import { stat } from 'node:fs/promises';
|
|
2
|
+
import { stat, realpath } from 'node:fs/promises';
|
|
3
3
|
|
|
4
4
|
export interface StaticOptions {
|
|
5
5
|
maxAge?: number;
|
|
@@ -9,6 +9,7 @@ export interface StaticOptions {
|
|
|
9
9
|
export const staticFile = (root: string = 'public', options: StaticOptions = {}) => {
|
|
10
10
|
const rootDir = resolve(process.cwd(), root);
|
|
11
11
|
const rootPrefix = rootDir.endsWith(sep) ? rootDir : rootDir + sep;
|
|
12
|
+
let realRootPromise: Promise<string> | null = null;
|
|
12
13
|
const maxAge = options.maxAge ?? 3600;
|
|
13
14
|
const enableEtag = options.etag !== false;
|
|
14
15
|
|
|
@@ -44,7 +45,15 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
|
|
|
44
45
|
let fileSize = 0;
|
|
45
46
|
let mtimeMs = 0;
|
|
46
47
|
try {
|
|
47
|
-
const
|
|
48
|
+
const [realRoot, realFile] = await Promise.all([
|
|
49
|
+
(realRootPromise ??= realpath(rootDir)),
|
|
50
|
+
realpath(filePath)
|
|
51
|
+
]);
|
|
52
|
+
const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
|
|
53
|
+
if (realFile !== realRoot && !realFile.startsWith(realPrefix)) {
|
|
54
|
+
return ctx.status(403).send('Forbidden');
|
|
55
|
+
}
|
|
56
|
+
const st = await stat(realFile);
|
|
48
57
|
if (st.isDirectory()) return next();
|
|
49
58
|
fileSize = st.size;
|
|
50
59
|
mtimeMs = Math.floor(st.mtimeMs);
|