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
package/src/core/bare.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BareRouter } from './router';
|
|
1
|
+
import { BareRouter, type InferSchema } from './router';
|
|
2
2
|
import { RadixNode } from './radix';
|
|
3
3
|
import { Context } from './context';
|
|
4
4
|
import { Type as typebox, Type as t } from '@sinclair/typebox';
|
|
@@ -6,6 +6,15 @@ import { join } from "node:path";
|
|
|
6
6
|
import { readFileSync } from "node:fs";
|
|
7
7
|
import { bootstrapConfig } from "./loader";
|
|
8
8
|
import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
|
|
9
|
+
import type { RouteSchemas } from "../security/validators";
|
|
10
|
+
import type { RouteSchema } from "../client/index";
|
|
11
|
+
|
|
12
|
+
export interface CronOptions {
|
|
13
|
+
/** Execute the cron job immediately upon registration (default: false) */
|
|
14
|
+
runOnStart?: boolean;
|
|
15
|
+
/** Optional error handler when the cron callback throws or rejects */
|
|
16
|
+
onError?: (err: any) => void;
|
|
17
|
+
}
|
|
9
18
|
|
|
10
19
|
export interface WebSocketRouteHandler {
|
|
11
20
|
open?: (ws: any) => void;
|
|
@@ -19,7 +28,40 @@ export interface NotFoundResponse {
|
|
|
19
28
|
message: string;
|
|
20
29
|
[key: string]: any;
|
|
21
30
|
}
|
|
22
|
-
|
|
31
|
+
|
|
32
|
+
type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (
|
|
33
|
+
ctx: Context & Derived & {
|
|
34
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
35
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, string>;
|
|
36
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
37
|
+
}
|
|
38
|
+
) => Res | Promise<Res>;
|
|
39
|
+
|
|
40
|
+
type AddRoute<Derived extends Record<string, any>, Routes extends RouteSchema, M extends string> = {
|
|
41
|
+
<P extends string, S extends RouteSchemas, Res = S extends { response: infer R } ? InferSchema<R> : any>(
|
|
42
|
+
path: P,
|
|
43
|
+
schemas: S,
|
|
44
|
+
handler: TypedRouteHandler<Derived, S, Res>
|
|
45
|
+
): BareJS<Derived, Routes & Record<`${M} ${P}`, {
|
|
46
|
+
method: M;
|
|
47
|
+
path: P;
|
|
48
|
+
params: S extends { params: infer Pa } ? InferSchema<Pa> : Record<string, any>;
|
|
49
|
+
query: S extends { query: infer Q } ? InferSchema<Q> : Record<string, any>;
|
|
50
|
+
headers: S extends { headers: infer H } ? InferSchema<H> : Record<string, string>;
|
|
51
|
+
body: S extends { body: infer B } ? InferSchema<B> : any;
|
|
52
|
+
response: S extends { response: infer R } ? InferSchema<R> : Awaited<Res>;
|
|
53
|
+
}>>;
|
|
54
|
+
<P extends string, Res = any>(
|
|
55
|
+
path: P,
|
|
56
|
+
...handlers: any[]
|
|
57
|
+
): BareJS<Derived, Routes & Record<`${M} ${P}`, { method: M; path: P; response: Awaited<Res> }>>;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export class BareJS<
|
|
61
|
+
Derived extends Record<string, any> = {},
|
|
62
|
+
Routes extends RouteSchema = {}
|
|
63
|
+
> extends BareRouter<Routes> {
|
|
64
|
+
declare readonly __routes: Routes;
|
|
23
65
|
private tree = new RadixNode();
|
|
24
66
|
private pool: Context[] = [];
|
|
25
67
|
// private poolIdx = 0;
|
|
@@ -31,6 +73,7 @@ export class BareJS extends BareRouter {
|
|
|
31
73
|
private wsRoutes = new Map<string, WebSocketRouteHandler>();
|
|
32
74
|
private startHooks: (() => void | Promise<void>)[] = [];
|
|
33
75
|
private stopHooks: (() => void | Promise<void>)[] = [];
|
|
76
|
+
private crons: Array<{ name: string; timer: ReturnType<typeof setInterval> }> = [];
|
|
34
77
|
private server?: ReturnType<typeof Bun.serve>;
|
|
35
78
|
private shutdownHandler?: () => Promise<void>;
|
|
36
79
|
private wsAdapter = {
|
|
@@ -55,7 +98,42 @@ export class BareJS extends BareRouter {
|
|
|
55
98
|
return this;
|
|
56
99
|
}
|
|
57
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Built-in overlap-safe background interval scheduler.
|
|
103
|
+
* Automatically cleared when app.stop() is called.
|
|
104
|
+
*/
|
|
105
|
+
public cron(
|
|
106
|
+
name: string,
|
|
107
|
+
intervalMs: number,
|
|
108
|
+
fn: () => void | Promise<void>,
|
|
109
|
+
options: CronOptions = {}
|
|
110
|
+
): this {
|
|
111
|
+
let running = false;
|
|
112
|
+
const tick = async () => {
|
|
113
|
+
if (running) return;
|
|
114
|
+
running = true;
|
|
115
|
+
try {
|
|
116
|
+
await fn();
|
|
117
|
+
} catch (err) {
|
|
118
|
+
options.onError?.(err);
|
|
119
|
+
} finally {
|
|
120
|
+
running = false;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
const timer = setInterval(tick, intervalMs);
|
|
124
|
+
this.crons.push({ name, timer });
|
|
125
|
+
if (options.runOnStart) {
|
|
126
|
+
void tick();
|
|
127
|
+
}
|
|
128
|
+
return this;
|
|
129
|
+
}
|
|
130
|
+
|
|
58
131
|
public async stop(closeActiveConnections = false): Promise<void> {
|
|
132
|
+
for (const c of this.crons) {
|
|
133
|
+
clearInterval(c.timer);
|
|
134
|
+
}
|
|
135
|
+
this.crons.length = 0;
|
|
136
|
+
|
|
59
137
|
if (this.shutdownHandler) {
|
|
60
138
|
process.off("SIGINT", this.shutdownHandler);
|
|
61
139
|
process.off("SIGTERM", this.shutdownHandler);
|
|
@@ -178,8 +256,22 @@ export class BareJS extends BareRouter {
|
|
|
178
256
|
}
|
|
179
257
|
|
|
180
258
|
|
|
259
|
+
declare public get: AddRoute<Derived, Routes, 'GET'>;
|
|
260
|
+
declare public post: AddRoute<Derived, Routes, 'POST'>;
|
|
261
|
+
declare public put: AddRoute<Derived, Routes, 'PUT'>;
|
|
262
|
+
declare public patch: AddRoute<Derived, Routes, 'PATCH'>;
|
|
263
|
+
declare public delete: AddRoute<Derived, Routes, 'DELETE'>;
|
|
264
|
+
declare public options: AddRoute<Derived, Routes, 'OPTIONS'>;
|
|
265
|
+
declare public head: AddRoute<Derived, Routes, 'HEAD'>;
|
|
266
|
+
declare public all: AddRoute<Derived, Routes, 'ALL'>;
|
|
267
|
+
|
|
268
|
+
declare public use: {
|
|
269
|
+
<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareJS<Derived, Routes & R2>;
|
|
270
|
+
(mw: any): BareJS<Derived, Routes>;
|
|
271
|
+
};
|
|
272
|
+
|
|
181
273
|
private _hasDerive = false;
|
|
182
|
-
public derive<T extends Record<string, any>>(fn: (ctx: Context) => Promise<T> | T):
|
|
274
|
+
public derive<T extends Record<string, any>>(fn: (ctx: Context & Derived) => Promise<T> | T): BareJS<Derived & T, Routes> {
|
|
183
275
|
this._hasDerive = true;
|
|
184
276
|
this.use(async (ctx: any, next: any) => {
|
|
185
277
|
const derived = await fn(ctx);
|
|
@@ -196,7 +288,7 @@ export class BareJS extends BareRouter {
|
|
|
196
288
|
}
|
|
197
289
|
return next();
|
|
198
290
|
});
|
|
199
|
-
return this;
|
|
291
|
+
return this as any;
|
|
200
292
|
}
|
|
201
293
|
|
|
202
294
|
// inherited use() from BareRouter handles router merging now
|
|
@@ -224,11 +316,31 @@ export class BareJS extends BareRouter {
|
|
|
224
316
|
};
|
|
225
317
|
}
|
|
226
318
|
|
|
319
|
+
const cbMw = pipeline.find((fn) => fn?.__circuitBreaker);
|
|
320
|
+
if (cbMw) {
|
|
321
|
+
const runWithBreaker = cbMw.__circuitBreaker;
|
|
322
|
+
const innerPipeline = pipeline.filter((fn) => !fn?.__circuitBreaker);
|
|
323
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
324
|
+
return (ctx: Context, doLog?: any) => runWithBreaker(() => innerCompiled(ctx, doLog));
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const compMw = pipeline.find((fn) => fn?.__compress);
|
|
328
|
+
if (compMw) {
|
|
329
|
+
const applyCompress = compMw.__compress;
|
|
330
|
+
const innerPipeline = pipeline.filter((fn) => !fn?.__compress);
|
|
331
|
+
const innerCompiled = this.compileHandler(innerPipeline, isLog);
|
|
332
|
+
return async (ctx: Context, doLog?: any) => {
|
|
333
|
+
const res = await innerCompiled(ctx, doLog);
|
|
334
|
+
return applyCompress(ctx, res);
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
|
|
227
338
|
const len = pipeline.length;
|
|
228
339
|
const rFilterMw = pipeline.find((fn) => fn?.__responseFilter);
|
|
229
340
|
const rFilter = rFilterMw?.__responseFilter;
|
|
230
341
|
const idemMw = pipeline.find((fn) => fn?.__idempotencyCommit);
|
|
231
342
|
const idemCommit = idemMw?.__idempotencyCommit;
|
|
343
|
+
const idemRelease = idemMw?.__idempotencyRelease;
|
|
232
344
|
|
|
233
345
|
// Static ResponseInit for 200 OK (Zero Allocation)
|
|
234
346
|
const json200 = { status: 200, headers: { "content-type": "application/json" } };
|
|
@@ -241,6 +353,7 @@ export class BareJS extends BareRouter {
|
|
|
241
353
|
const finalizeCode = `
|
|
242
354
|
${rFilter ? 'res = rFilter(res);' : ''}
|
|
243
355
|
if (res instanceof Response) {
|
|
356
|
+
${idemRelease ? 'idemRelease(ctx);' : ''}
|
|
244
357
|
if (ctx._headers) {
|
|
245
358
|
for (const k in ctx._headers) {
|
|
246
359
|
if (!res.headers.has(k)) res.headers.set(k, ctx._headers[k]);
|
|
@@ -284,19 +397,56 @@ export class BareJS extends BareRouter {
|
|
|
284
397
|
|
|
285
398
|
const argSig = isLog ? 'ctx, doLog' : 'ctx';
|
|
286
399
|
|
|
400
|
+
const extraNames = [
|
|
401
|
+
...(rFilter ? ['rFilter'] : []),
|
|
402
|
+
...(idemCommit ? ['idemCommit'] : []),
|
|
403
|
+
...(idemRelease ? ['idemRelease'] : [])
|
|
404
|
+
];
|
|
405
|
+
const extraVals = [
|
|
406
|
+
...(rFilter ? [rFilter] : []),
|
|
407
|
+
...(idemCommit ? [idemCommit] : []),
|
|
408
|
+
...(idemRelease ? [idemRelease] : [])
|
|
409
|
+
];
|
|
410
|
+
|
|
411
|
+
const wrapIdem = (compiled: Function): Function => {
|
|
412
|
+
if (!idemRelease) return compiled;
|
|
413
|
+
return (ctx: Context, doLog?: any) => {
|
|
414
|
+
try {
|
|
415
|
+
const out = compiled(ctx, doLog);
|
|
416
|
+
if (out && typeof out.then === 'function') {
|
|
417
|
+
return out.then(
|
|
418
|
+
(v: any) => v,
|
|
419
|
+
(err: any) => {
|
|
420
|
+
idemRelease(ctx);
|
|
421
|
+
throw err;
|
|
422
|
+
}
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
return out;
|
|
426
|
+
} catch (err) {
|
|
427
|
+
idemRelease(ctx);
|
|
428
|
+
throw err;
|
|
429
|
+
}
|
|
430
|
+
};
|
|
431
|
+
};
|
|
432
|
+
|
|
287
433
|
if (len === 1) {
|
|
288
434
|
const fn0 = pipeline[0]!;
|
|
289
435
|
if (fn0.constructor.name === 'AsyncFunction') {
|
|
290
|
-
return
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
436
|
+
return wrapIdem(
|
|
437
|
+
new Function('fn0', 'json200', 'text200', ...extraNames, `return async function(${argSig}) {
|
|
438
|
+
const res = await fn0(ctx);
|
|
439
|
+
${finalizeCode}
|
|
440
|
+
}`)(fn0, json200, text200, ...extraVals)
|
|
441
|
+
);
|
|
294
442
|
}
|
|
295
|
-
return
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
443
|
+
return wrapIdem(
|
|
444
|
+
new Function('fn0', 'json200', 'text200', ...extraNames, `return function(${argSig}) {
|
|
445
|
+
const res = fn0(ctx);
|
|
446
|
+
if (res && res.then) return res.then(v => { const res = v; ${finalizeCode} });
|
|
447
|
+
${finalizeCode}
|
|
448
|
+
}`)(fn0, json200, text200, ...extraVals)
|
|
449
|
+
);
|
|
300
450
|
}
|
|
301
451
|
|
|
302
452
|
// Check async
|
|
@@ -336,7 +486,9 @@ export class BareJS extends BareRouter {
|
|
|
336
486
|
? `return async function(${argSig})`
|
|
337
487
|
: `return function(${argSig})`;
|
|
338
488
|
|
|
339
|
-
return
|
|
489
|
+
return wrapIdem(
|
|
490
|
+
new Function(...fnNames, 'noop', 'json200', 'text200', ...extraNames, `${fnHeader} { ${code} }`)(...pipeline, noop, json200, text200, ...extraVals)
|
|
491
|
+
);
|
|
340
492
|
}
|
|
341
493
|
|
|
342
494
|
public compile() {
|
|
@@ -538,13 +690,27 @@ export class BareJS extends BareRouter {
|
|
|
538
690
|
};
|
|
539
691
|
public name: string = "App";
|
|
540
692
|
|
|
541
|
-
public
|
|
542
|
-
|
|
693
|
+
public trustProxy(enabled: boolean = true): this {
|
|
694
|
+
for (let i = 0; i < this.pool.length; i++) {
|
|
695
|
+
this.pool[i]!._trustProxy = enabled;
|
|
696
|
+
}
|
|
697
|
+
return this;
|
|
698
|
+
}
|
|
543
699
|
|
|
700
|
+
public listen(
|
|
701
|
+
port?: number,
|
|
702
|
+
hostname: string = '0.0.0.0',
|
|
703
|
+
reusePort: boolean = true,
|
|
704
|
+
options: { maxRequestBodySize?: number; trustProxy?: boolean } = {}
|
|
705
|
+
) {
|
|
706
|
+
if (!this.compiled) this.compile();
|
|
707
|
+
if (options.trustProxy !== undefined) {
|
|
708
|
+
this.trustProxy(options.trustProxy);
|
|
709
|
+
}
|
|
710
|
+
const maxRequestBodySize = options.maxRequestBodySize ?? 10 * 1024 * 1024;
|
|
544
711
|
|
|
545
712
|
const { BARE_CONFIG } = require("./config");
|
|
546
713
|
|
|
547
|
-
|
|
548
714
|
const finalPort = port || BARE_CONFIG.port || 3000;
|
|
549
715
|
const isProd = process.env.NODE_ENV === 'production';
|
|
550
716
|
|
|
@@ -571,15 +737,44 @@ export class BareJS extends BareRouter {
|
|
|
571
737
|
port: finalPort,
|
|
572
738
|
hostname,
|
|
573
739
|
reusePort,
|
|
740
|
+
maxRequestBodySize,
|
|
574
741
|
fetch(req: Request, srv: any) {
|
|
575
|
-
if (req.headers.get('upgrade') === 'websocket') {
|
|
742
|
+
if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
576
743
|
const url = req.url;
|
|
577
744
|
const s = url.indexOf('/', 8);
|
|
578
745
|
const q = s === -1 ? -1 : url.indexOf('?', s);
|
|
579
746
|
const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
|
|
580
747
|
const normalized = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
|
|
581
|
-
|
|
582
|
-
|
|
748
|
+
let handler = wsRoutes.get(normalized);
|
|
749
|
+
let params: Record<string, string> | undefined;
|
|
750
|
+
if (!handler) {
|
|
751
|
+
const reqParts = normalized.split('/').filter(Boolean);
|
|
752
|
+
for (const [pattern, h] of wsRoutes) {
|
|
753
|
+
if (!pattern.includes(':') && !pattern.includes('*')) continue;
|
|
754
|
+
const patParts = pattern.split('/').filter(Boolean);
|
|
755
|
+
const matched: Record<string, string> = {};
|
|
756
|
+
let ok = true;
|
|
757
|
+
for (let i = 0; i < patParts.length; i++) {
|
|
758
|
+
const pp = patParts[i]!;
|
|
759
|
+
if (pp === '*') {
|
|
760
|
+
matched['*'] = reqParts.slice(i).join('/');
|
|
761
|
+
break;
|
|
762
|
+
}
|
|
763
|
+
if (i >= reqParts.length) { ok = false; break; }
|
|
764
|
+
if (pp.startsWith(':')) {
|
|
765
|
+
matched[pp.slice(1)] = reqParts[i]!;
|
|
766
|
+
} else if (pp !== reqParts[i]) {
|
|
767
|
+
ok = false; break;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
if (ok && (patParts.includes('*') || patParts.length === reqParts.length)) {
|
|
771
|
+
handler = h;
|
|
772
|
+
params = matched;
|
|
773
|
+
break;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
if (handler && srv.upgrade(req, { data: params ? { ...handler, params } : handler })) {
|
|
583
778
|
return undefined as any;
|
|
584
779
|
}
|
|
585
780
|
}
|
|
@@ -591,6 +786,7 @@ export class BareJS extends BareRouter {
|
|
|
591
786
|
port: finalPort,
|
|
592
787
|
hostname,
|
|
593
788
|
reusePort,
|
|
789
|
+
maxRequestBodySize,
|
|
594
790
|
fetch: baseFetch
|
|
595
791
|
});
|
|
596
792
|
|
package/src/core/context.ts
CHANGED
|
@@ -52,6 +52,8 @@ export class Context {
|
|
|
52
52
|
public _cookies: Record<string, string> | undefined = undefined;
|
|
53
53
|
public _setCookies: string[] | undefined = undefined;
|
|
54
54
|
public _requestId: string | undefined = undefined;
|
|
55
|
+
public _peerIp: string | undefined = undefined;
|
|
56
|
+
public _trustProxy: boolean = true;
|
|
55
57
|
constructor() { }
|
|
56
58
|
|
|
57
59
|
public get query(): Record<string, string> {
|
|
@@ -217,6 +219,7 @@ export class Context {
|
|
|
217
219
|
this._cookies = undefined;
|
|
218
220
|
this._setCookies = undefined;
|
|
219
221
|
this.body = undefined;
|
|
222
|
+
this._peerIp = undefined;
|
|
220
223
|
return this;
|
|
221
224
|
}
|
|
222
225
|
|
|
@@ -368,13 +371,15 @@ export class Context {
|
|
|
368
371
|
}
|
|
369
372
|
|
|
370
373
|
public get ip(): string {
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
374
|
+
if (this._trustProxy) {
|
|
375
|
+
const xff = this.req?.headers?.get('x-forwarded-for');
|
|
376
|
+
if (xff) return xff.split(',')[0]!.trim();
|
|
377
|
+
const forwarded =
|
|
378
|
+
this.req?.headers?.get('x-real-ip') ||
|
|
379
|
+
this.req?.headers?.get('cf-connecting-ip');
|
|
380
|
+
if (forwarded) return forwarded;
|
|
381
|
+
}
|
|
382
|
+
return this._peerIp || '127.0.0.1';
|
|
378
383
|
}
|
|
379
384
|
|
|
380
385
|
public async upload(options: UploadOptions = {}): Promise<UploadResult> {
|
package/src/core/router.ts
CHANGED
|
@@ -5,9 +5,17 @@ import {
|
|
|
5
5
|
} from '../core/context';
|
|
6
6
|
import { schemaValidator, type RouteSchemas } from '../security/validators';
|
|
7
7
|
|
|
8
|
+
import type { RouteSchema } from '../client/index';
|
|
9
|
+
|
|
8
10
|
type HandlersChain = (Middleware | Handler | RouteSchemas)[];
|
|
9
11
|
|
|
10
|
-
export
|
|
12
|
+
export type InferSchema<S> =
|
|
13
|
+
S extends { static: infer T } ? T
|
|
14
|
+
: S extends { _output: infer T } ? T
|
|
15
|
+
: any;
|
|
16
|
+
|
|
17
|
+
export class BareRouter<Routes extends RouteSchema = {}> {
|
|
18
|
+
declare readonly __routes: Routes;
|
|
11
19
|
public routes: any[] = [];
|
|
12
20
|
|
|
13
21
|
constructor(
|
|
@@ -15,7 +23,7 @@ export class BareRouter {
|
|
|
15
23
|
public groupMiddleware: any[] = []
|
|
16
24
|
) { }
|
|
17
25
|
|
|
18
|
-
|
|
26
|
+
protected _add(method: string, path: string, handlers: HandlersChain) {
|
|
19
27
|
let fullPath = (this.prefix + "/" + path)
|
|
20
28
|
.replace(/\/+/g, "/");
|
|
21
29
|
|
|
@@ -39,27 +47,35 @@ export class BareRouter {
|
|
|
39
47
|
return this;
|
|
40
48
|
}
|
|
41
49
|
|
|
42
|
-
public get = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
|
|
43
|
-
public post = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
|
|
44
|
-
public put = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
|
|
45
|
-
public patch = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
|
|
46
|
-
public delete = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
|
|
47
|
-
public options = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
|
|
50
|
+
public get: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("GET", path, h);
|
|
51
|
+
public post: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("POST", path, h);
|
|
52
|
+
public put: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("PUT", path, h);
|
|
53
|
+
public patch: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("PATCH", path, h);
|
|
54
|
+
public delete: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("DELETE", path, h);
|
|
55
|
+
public options: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("OPTIONS", path, h);
|
|
56
|
+
public head: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => this._add("HEAD", path, h);
|
|
57
|
+
public all: (path: string, ...h: any[]) => any = (path: string, ...h: HandlersChain) => {
|
|
58
|
+
for (const m of ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]) {
|
|
59
|
+
this._add(m, path, h);
|
|
60
|
+
}
|
|
61
|
+
return this;
|
|
62
|
+
};
|
|
48
63
|
|
|
49
64
|
public group = (path: string, ...args: any[]) => {
|
|
50
65
|
const callback = args.pop();
|
|
51
66
|
const middleware = args;
|
|
52
67
|
|
|
53
|
-
|
|
54
68
|
const newPrefix = (this.prefix + "/" + path).replace(/\/+/g, "/");
|
|
55
69
|
const subRouter = new BareRouter(newPrefix, [...this.groupMiddleware, ...middleware]);
|
|
56
70
|
|
|
57
71
|
callback(subRouter);
|
|
58
72
|
this.routes.push(...subRouter.routes);
|
|
59
73
|
return this;
|
|
60
|
-
};
|
|
74
|
+
};
|
|
61
75
|
|
|
62
|
-
public use(mw:
|
|
76
|
+
public use<R2 extends RouteSchema = {}>(mw: BareRouter<R2>): BareRouter<Routes & R2>;
|
|
77
|
+
public use(mw: any): BareRouter<Routes>;
|
|
78
|
+
public use(mw: any): any {
|
|
63
79
|
if (mw instanceof BareRouter || (mw && mw.routes)) {
|
|
64
80
|
this.routes.push(...mw.routes);
|
|
65
81
|
} else if (mw && typeof mw.install === 'function') {
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
|
-
export { BareJS, type WebSocketRouteHandler } from './core/bare';
|
|
9
|
+
export { BareJS, type WebSocketRouteHandler, type CronOptions } from './core/bare';
|
|
10
|
+
export { BareRouter, type InferSchema } from './core/router';
|
|
10
11
|
|
|
11
12
|
/**
|
|
12
13
|
* Plugin Interface for BareJS
|
|
@@ -58,20 +59,22 @@ export {
|
|
|
58
59
|
};
|
|
59
60
|
|
|
60
61
|
// --- 5. Middlewares & Utilities ---
|
|
61
|
-
|
|
62
|
+
export { logger, type LoggerOptions, type LogEntry } from './utils/logger';
|
|
63
|
+
export { healthcheck, type HealthcheckOptions, type HealthCheckFn } from './utils/health';
|
|
62
64
|
export { cors } from './security/cors';
|
|
63
65
|
export { csrf, type CsrfOptions } from './security/csrf';
|
|
64
66
|
export { timeout, type TimeoutOptions } from './security/timeout';
|
|
65
67
|
export { rateLimit, type RateLimitOptions } from './security/rateLimit';
|
|
66
68
|
export { idempotency, createSingleflight, type IdempotencyOptions } from './security/idempotency';
|
|
69
|
+
export { circuitBreaker, type CircuitBreakerOptions, type CircuitState } from './security/resilience';
|
|
67
70
|
export { securityHeaders, type SecurityHeadersOptions } from './security/headers';
|
|
68
71
|
export { staticFile, type StaticOptions } from './utils/static';
|
|
72
|
+
export { compress, type CompressOptions } from './utils/compress';
|
|
69
73
|
export { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from './utils/openapi';
|
|
70
|
-
export { BareRouter } from './core/router';
|
|
71
74
|
|
|
72
75
|
// --- 6. Authentication (Bun Native) ---
|
|
73
76
|
// Always deploy using process.env [2026-01-06]
|
|
74
|
-
export { bareAuth, createToken, basicAuth, hasRole } from './security/auth';
|
|
77
|
+
export { bareAuth, createToken, basicAuth, hasRole, revokeToken, isTokenRevoked, type BareAuthOptions } from './security/auth';
|
|
75
78
|
// --- 7. Hashing ---
|
|
76
79
|
export { Hash as Password, Hash } from './security/hash';
|
|
77
80
|
|
|
@@ -81,5 +84,6 @@ export {
|
|
|
81
84
|
type BareClient,
|
|
82
85
|
type BareClientOptions,
|
|
83
86
|
type ClientRequestOptions,
|
|
87
|
+
type RouteEndpoint,
|
|
84
88
|
type RouteSchema
|
|
85
89
|
} from './client/index';
|
package/src/security/auth.ts
CHANGED
|
@@ -54,13 +54,62 @@ export const createToken = async (payload: object, secret: string): Promise<stri
|
|
|
54
54
|
return `${data}.${encodedSig}`;
|
|
55
55
|
};
|
|
56
56
|
|
|
57
|
+
const revokedTokens = new Map<string, number>();
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Revoke a JWT token or JTI for ttlMs (default: 1 hour).
|
|
61
|
+
*/
|
|
62
|
+
export const revokeToken = (tokenOrJti: string, ttlMs: number = 3600_000): void => {
|
|
63
|
+
if (revokedTokens.size >= 10_000) {
|
|
64
|
+
const now = Date.now();
|
|
65
|
+
for (const [k, exp] of revokedTokens) {
|
|
66
|
+
if (now >= exp) revokedTokens.delete(k);
|
|
67
|
+
}
|
|
68
|
+
if (revokedTokens.size >= 10_000) {
|
|
69
|
+
const oldest = revokedTokens.keys().next().value;
|
|
70
|
+
if (oldest !== undefined) revokedTokens.delete(oldest);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
revokedTokens.set(tokenOrJti, Date.now() + ttlMs);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export const isTokenRevoked = (tokenOrJti: string): boolean => {
|
|
77
|
+
const exp = revokedTokens.get(tokenOrJti);
|
|
78
|
+
if (exp === undefined) return false;
|
|
79
|
+
if (Date.now() >= exp) {
|
|
80
|
+
revokedTokens.delete(tokenOrJti);
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
return true;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export interface BareAuthOptions {
|
|
87
|
+
secret: string;
|
|
88
|
+
isRevoked?: (payload: any, token: string) => boolean | Promise<boolean>;
|
|
89
|
+
}
|
|
90
|
+
|
|
57
91
|
/**
|
|
58
92
|
* 1. BARE TOKEN AUTH (Standard JWT Middleware)
|
|
59
93
|
* High-performance, constant-time JWT middleware for BareJS
|
|
60
94
|
*/
|
|
61
|
-
export const bareAuth = (secretOrOpts: string |
|
|
95
|
+
export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
|
|
62
96
|
const secret = typeof secretOrOpts === 'string' ? secretOrOpts : secretOrOpts.secret;
|
|
63
|
-
|
|
97
|
+
const customRevoked = typeof secretOrOpts === 'object' ? secretOrOpts.isRevoked : undefined;
|
|
98
|
+
|
|
99
|
+
const finishAuth = (ctx: any, decoded: any, next: any) => {
|
|
100
|
+
ctx.set('user', decoded);
|
|
101
|
+
if (Array.isArray(next)) {
|
|
102
|
+
if (next.length === 0) return;
|
|
103
|
+
const [current, ...rest] = next;
|
|
104
|
+
return current(ctx, rest);
|
|
105
|
+
}
|
|
106
|
+
if (typeof next === 'function') {
|
|
107
|
+
return next();
|
|
108
|
+
}
|
|
109
|
+
return;
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const verifySync = (ctx: any, next: any) => {
|
|
64
113
|
const authHeader = ctx.req.headers.get('Authorization');
|
|
65
114
|
|
|
66
115
|
if (!authHeader?.startsWith('Bearer ')) {
|
|
@@ -101,23 +150,30 @@ export const bareAuth = (secretOrOpts: string | { secret: string }) => {
|
|
|
101
150
|
return ctx.status(401).send("Token not active");
|
|
102
151
|
}
|
|
103
152
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
if (Array.isArray(next)) {
|
|
107
|
-
if (next.length === 0) return;
|
|
108
|
-
const [current, ...rest] = next;
|
|
109
|
-
return current(ctx, rest);
|
|
153
|
+
if (isTokenRevoked(token) || (decoded?.jti && isTokenRevoked(String(decoded.jti)))) {
|
|
154
|
+
return ctx.status(401).send("Token revoked");
|
|
110
155
|
}
|
|
111
156
|
|
|
112
|
-
if (
|
|
113
|
-
|
|
157
|
+
if (customRevoked) {
|
|
158
|
+
const rev = customRevoked(decoded, token);
|
|
159
|
+
if (rev && typeof (rev as Promise<boolean>).then === 'function') {
|
|
160
|
+
return (rev as Promise<boolean>).then((isRev) =>
|
|
161
|
+
isRev ? ctx.status(401).send("Token revoked") : finishAuth(ctx, decoded, next)
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
if (rev) return ctx.status(401).send("Token revoked");
|
|
114
165
|
}
|
|
115
166
|
|
|
116
|
-
return;
|
|
167
|
+
return finishAuth(ctx, decoded, next);
|
|
117
168
|
} catch {
|
|
118
169
|
return ctx.status(401).send("Token verification failed");
|
|
119
170
|
}
|
|
120
171
|
};
|
|
172
|
+
|
|
173
|
+
if (customRevoked) {
|
|
174
|
+
return async (ctx: any, next: any) => verifySync(ctx, next);
|
|
175
|
+
}
|
|
176
|
+
return verifySync;
|
|
121
177
|
};
|
|
122
178
|
|
|
123
179
|
const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
|
package/src/security/hash.ts
CHANGED
|
@@ -5,8 +5,14 @@ export const Hash = {
|
|
|
5
5
|
make: (data: string): Promise<string> =>
|
|
6
6
|
Bun.password.hash(data, BARE_CONFIG.hash),
|
|
7
7
|
|
|
8
|
-
verify: (data: string, hash: string): Promise<boolean> =>
|
|
9
|
-
|
|
8
|
+
verify: async (data: string, hash: string): Promise<boolean> => {
|
|
9
|
+
if (!hash || typeof hash !== 'string') return false;
|
|
10
|
+
try {
|
|
11
|
+
return await Bun.password.verify(data, hash);
|
|
12
|
+
} catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
},
|
|
10
16
|
|
|
11
17
|
needsRehash: (hash: string): boolean => {
|
|
12
18
|
const { algorithm, memoryCost, timeCost } = BARE_CONFIG.hash;
|