barejs 0.2.1 → 0.2.3

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.
@@ -18,6 +18,20 @@ export interface NotFoundResponse {
18
18
  message: string;
19
19
  [key: string]: any;
20
20
  }
21
+ export interface UseLogEntry {
22
+ level: 'info' | 'warn' | 'error';
23
+ timestamp: string;
24
+ method: string;
25
+ path: string;
26
+ status: number;
27
+ durationMs: number;
28
+ ip?: string;
29
+ }
30
+ export interface UseLogOptions {
31
+ enabled?: boolean;
32
+ format?: 'pretty' | 'json';
33
+ onLog?: (entry: UseLogEntry) => void;
34
+ }
21
35
  type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (ctx: Context & Derived & {
22
36
  body: S extends {
23
37
  body: infer B;
@@ -66,6 +80,8 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
66
80
  private hotFetch?;
67
81
  private compiled;
68
82
  private _useLog;
83
+ private _logFormat;
84
+ private _logSink?;
69
85
  private _trustProxyBox;
70
86
  protected _onRouteMutate(): void;
71
87
  private errorHandler?;
@@ -73,16 +89,20 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
73
89
  private startHooks;
74
90
  private stopHooks;
75
91
  private drainHooks;
92
+ private requestHooks;
93
+ private responseHooks;
76
94
  private crons;
77
95
  private server?;
78
96
  private shutdownHandler?;
79
97
  private ipcDrainHandler?;
80
98
  private _draining;
81
99
  private wsAdapter;
82
- useLog(enabled?: boolean): this;
100
+ useLog(enabledOrOptions?: boolean | UseLogOptions): this;
83
101
  onStart(fn: () => void | Promise<void>): this;
84
102
  onStop(fn: () => void | Promise<void>): this;
85
103
  onDrain(fn: () => void | Promise<void>): this;
104
+ onRequest(fn: (req: Request, peerIp?: string) => void | Response | Promise<void | Response>): this;
105
+ onResponse(fn: (req: Request, res: Response, durationMs: number) => void | Response | Promise<void | Response>): this;
86
106
  /**
87
107
  * Gracefully drains the server by running all onDrain hooks and stopping
88
108
  * the server while allowing in-flight requests to complete.
@@ -101,7 +121,7 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
101
121
  setNotFound(handler: () => NotFoundResponse): void;
102
122
  onError(handler: (err: any, ctx: Context) => any): this;
103
123
  ws(path: string, handler: WebSocketRouteHandler): this;
104
- docs(path?: string, options?: OpenAPIOptions): this;
124
+ docs(pathOrOptions?: string | OpenAPIOptions, options?: OpenAPIOptions): this;
105
125
  rpc(path: string, procedures: Record<string, (params: any, ctx: Context) => any>, options?: {
106
126
  maxBatchSize?: number;
107
127
  }): this;
@@ -132,13 +152,21 @@ export declare class BareJS<Derived extends Record<string, any> = {}, Routes ext
132
152
  */
133
153
  request(path: string, init?: RequestInit): Promise<Response>;
134
154
  name: string;
135
- trustProxy(enabled?: boolean): this;
155
+ trustProxy(enabled?: boolean | string[]): this;
136
156
  private buildBunRoutes;
137
157
  private buildUwsRoutes;
138
158
  listen(port?: number, hostname?: string, reusePort?: boolean, options?: {
139
159
  maxRequestBodySize?: number;
140
- trustProxy?: boolean;
160
+ trustProxy?: boolean | string[];
141
161
  engine?: 'auto' | 'http' | 'uws';
142
162
  }): any;
163
+ listenCluster(port?: number, workers?: number, hostname?: string, options?: {
164
+ maxRequestBodySize?: number;
165
+ trustProxy?: boolean | string[];
166
+ engine?: 'auto' | 'http' | 'uws';
167
+ }): Promise<{
168
+ stop: () => Promise<void> | void;
169
+ workers: number;
170
+ }>;
143
171
  }
144
172
  export { Context, typebox, t };
@@ -53,6 +53,7 @@ export interface UploadStreamPart {
53
53
  stream?: ReadableStream<Uint8Array>;
54
54
  value?: string;
55
55
  }
56
+ export declare function isTrustedProxyIp(peerIp: string | undefined, trustProxy: boolean | string[]): boolean;
56
57
  export declare class Context {
57
58
  req: Request;
58
59
  params: Params;
@@ -65,9 +66,9 @@ export declare class Context {
65
66
  _setCookies: string[] | undefined;
66
67
  _requestId: string | undefined;
67
68
  _peerIp: string | undefined;
68
- _trustProxy: boolean;
69
+ _trustProxy: boolean | string[];
69
70
  _detached: boolean;
70
- constructor(trustProxy?: boolean);
71
+ constructor(trustProxy?: boolean | string[]);
71
72
  get query(): Record<string, string>;
72
73
  /** All values for a (possibly repeated) query key, in order. */
73
74
  queryAll(key: string): string[];
@@ -18,7 +18,9 @@ export declare const generateOpenAPISpec: (routes: any[], options?: OpenAPIOptio
18
18
  paths: Record<string, Record<string, any>>;
19
19
  security?: Record<string, string[]>[] | undefined;
20
20
  components?: {
21
- securitySchemes: Record<string, Record<string, any>>;
21
+ securitySchemes: {
22
+ [x: string]: any;
23
+ };
22
24
  } | undefined;
23
25
  tags?: {
24
26
  name: string;
@@ -9,5 +9,9 @@ export interface StaticOptions {
9
9
  etag?: boolean;
10
10
  /** Optional LRU metadata cache for realpath, stat, and ETag to avoid repeated syscalls */
11
11
  cacheMetadata?: boolean | StaticMetadataCacheOptions;
12
+ /** Enable Single Page Application fallback to index.html for unmatched GET/HEAD routes */
13
+ spa?: boolean;
14
+ /** Custom fallback file relative to root when spa is true (default: 'index.html') */
15
+ spaFallback?: string;
12
16
  }
13
17
  export declare const staticFile: (root?: string, options?: StaticOptions) => (ctx: any, next: any) => Promise<any>;
package/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # BareJS (`barejs`) — AI Quick Reference (`llms.txt`)
2
2
 
3
- > BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection), and **Deno** with built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **Full Multi-Runtime Test Suite (427 tests / 6,279 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
3
+ > BareJS is an ultra-fast, zero-allocation JIT-compiled web framework for **Bun** (`>= 1.1` with `Bun.serve({ routes })`), **Node.js** (`>= 20` via `barejs/node` with optional `uWebSockets.js` auto-detection), and **Deno** with built-in security (Argon2id/scrypt, HS256/RS256/ES256 JWT, HMAC-signed HttpOnly cookies, CSRF, Rate Limiting, Circuit Breaker, Idempotency-Key double-charge protection, Singleflight request coalescing, Mass-Assignment `stripUnknown`, Native Gzip/Brotli/Zstd `compress`, `app.cron`, Security Headers, DoS limits) and **Full Multi-Runtime Test Suite (434 tests / 6,321 assertions verified in CI across Bun, Node.js 20/22, and Deno 2)**.
4
4
 
5
5
  ## 1. Installation & Minimal App (Bun, Node.js, Deno)
6
6
  ```ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "barejs",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "author": "xarhang",
5
5
  "description": "Batteries-included web framework for Bun, Node.js, and Deno with O(1) JIT routing, TypeBox/Zod validation, OpenAPI 3.1, WebSockets, JSON-RPC 2.0, and built-in security.",
6
6
  "main": "./dist/index.js",
package/src/core/bare.ts CHANGED
@@ -69,6 +69,22 @@ export interface NotFoundResponse {
69
69
  [key: string]: any;
70
70
  }
71
71
 
72
+ export interface UseLogEntry {
73
+ level: 'info' | 'warn' | 'error';
74
+ timestamp: string;
75
+ method: string;
76
+ path: string;
77
+ status: number;
78
+ durationMs: number;
79
+ ip?: string;
80
+ }
81
+
82
+ export interface UseLogOptions {
83
+ enabled?: boolean;
84
+ format?: 'pretty' | 'json';
85
+ onLog?: (entry: UseLogEntry) => void;
86
+ }
87
+
72
88
  type TypedRouteHandler<Derived, S extends RouteSchemas, Res> = (
73
89
  ctx: Context & Derived & {
74
90
  body: S extends { body: infer B } ? InferSchema<B> : any;
@@ -110,7 +126,9 @@ export class BareJS<
110
126
  private hotFetch?: (req: Request, peerIp?: string) => any;
111
127
  private compiled = false;
112
128
  private _useLog: boolean = false;
113
- private _trustProxyBox = { val: false };
129
+ private _logFormat: 'pretty' | 'json' = 'pretty';
130
+ private _logSink?: (entry: UseLogEntry) => void;
131
+ private _trustProxyBox: { val: boolean | string[] } = { val: false };
114
132
 
115
133
  protected override _onRouteMutate(): void {
116
134
  if (this.compiled) {
@@ -123,6 +141,8 @@ export class BareJS<
123
141
  private startHooks: (() => void | Promise<void>)[] = [];
124
142
  private stopHooks: (() => void | Promise<void>)[] = [];
125
143
  private drainHooks: (() => void | Promise<void>)[] = [];
144
+ private requestHooks: Array<(req: Request, peerIp?: string) => void | Response | Promise<void | Response>> = [];
145
+ private responseHooks: Array<(req: Request, res: Response, durationMs: number) => void | Response | Promise<void | Response>> = [];
126
146
  private crons: Array<{ name: string; timer: ReturnType<typeof setInterval> }> = [];
127
147
  private server?: ServerHandle;
128
148
  private shutdownHandler?: () => Promise<void>;
@@ -135,8 +155,16 @@ export class BareJS<
135
155
  drain(ws: any) { ws.data?.drain?.(ws); }
136
156
  };
137
157
 
138
- public useLog(enabled: boolean = true): this {
139
- this._useLog = enabled;
158
+ public useLog(enabledOrOptions: boolean | UseLogOptions = true): this {
159
+ if (typeof enabledOrOptions === 'boolean') {
160
+ this._useLog = enabledOrOptions;
161
+ this._logFormat = 'pretty';
162
+ this._logSink = undefined;
163
+ } else {
164
+ this._useLog = enabledOrOptions.enabled ?? true;
165
+ this._logFormat = enabledOrOptions.format ?? 'pretty';
166
+ this._logSink = enabledOrOptions.onLog;
167
+ }
140
168
  this._onRouteMutate();
141
169
  return this;
142
170
  }
@@ -156,6 +184,18 @@ export class BareJS<
156
184
  return this;
157
185
  }
158
186
 
187
+ public onRequest(fn: (req: Request, peerIp?: string) => void | Response | Promise<void | Response>): this {
188
+ this.requestHooks.push(fn);
189
+ this._onRouteMutate();
190
+ return this;
191
+ }
192
+
193
+ public onResponse(fn: (req: Request, res: Response, durationMs: number) => void | Response | Promise<void | Response>): this {
194
+ this.responseHooks.push(fn);
195
+ this._onRouteMutate();
196
+ return this;
197
+ }
198
+
159
199
  /**
160
200
  * Gracefully drains the server by running all onDrain hooks and stopping
161
201
  * the server while allowing in-flight requests to complete.
@@ -279,15 +319,17 @@ export class BareJS<
279
319
  return this;
280
320
  }
281
321
 
282
- public docs(path: string = '/docs', options: OpenAPIOptions = {}): this {
322
+ public docs(pathOrOptions: string | OpenAPIOptions = '/docs', options: OpenAPIOptions = {}): this {
323
+ const path = typeof pathOrOptions === 'string' ? pathOrOptions : '/docs';
324
+ const opts = typeof pathOrOptions === 'string' ? options : pathOrOptions;
283
325
  const basePath = ('/' + path).replace(/\/+/g, '/').replace(/\/$/, '') || '/docs';
284
326
  const jsonPath = `${basePath}/json`;
285
327
  let cachedSpec: string | null = null;
286
- const html = renderDocsHTML(jsonPath, options.title || `${this.name} API Docs`);
328
+ const html = renderDocsHTML(jsonPath, opts.title || `${this.name} API Docs`);
287
329
 
288
330
  this.get(jsonPath, () => {
289
331
  if (!cachedSpec) {
290
- cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, excludePaths: [basePath, jsonPath], ...options }));
332
+ cachedSpec = JSON.stringify(generateOpenAPISpec(this.routes, { title: this.name, excludePaths: [basePath, jsonPath], ...opts }));
291
333
  }
292
334
  return new Response(cachedSpec, {
293
335
  status: 200,
@@ -1031,6 +1073,7 @@ export class BareJS<
1031
1073
  const hasStaticMw = this.groupMiddleware.some((m: any) => m.__isStatic);
1032
1074
  const runStatic = hasStaticMw
1033
1075
  ? async (ctx: Context) => {
1076
+ (ctx as any)._isStaticFallback = true;
1034
1077
  const mws = this.groupMiddleware;
1035
1078
  const dispatch = async (idx: number): Promise<Response | undefined> => {
1036
1079
  if (idx >= mws.length) return undefined;
@@ -1048,7 +1091,11 @@ export class BareJS<
1048
1091
  if (!nextCalled) return dispatch(idx + 1);
1049
1092
  return undefined;
1050
1093
  };
1051
- return dispatch(0);
1094
+ try {
1095
+ return await dispatch(0);
1096
+ } finally {
1097
+ (ctx as any)._isStaticFallback = false;
1098
+ }
1052
1099
  }
1053
1100
  : undefined;
1054
1101
 
@@ -1083,10 +1130,33 @@ export class BareJS<
1083
1130
 
1084
1131
  const poolState = this._poolState;
1085
1132
  const trustProxyBox = this._trustProxyBox;
1086
- const args = ['pool', 'poolState', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyBox', ...(isDevUaf ? ['wrapUaf'] : []), ...(hasGlobalMw ? ['runGlobalOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...(apply404Cors ? ['apply404Cors'] : []), ...hNames];
1087
- const values = [pool, poolState, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyBox, ...(isDevUaf ? [wrapUaf] : []), ...(hasGlobalMw ? [runGlobalOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...(apply404Cors ? [apply404Cors] : []), ...hoistedHandlers];
1133
+ const emitStructuredLog = isLog && (this._logFormat === 'json' || this._logSink !== undefined)
1134
+ ? (method: string, rawUrl: string, status: number, durationMs: number, peerIp?: string) => {
1135
+ const idx = rawUrl.indexOf('/', 8);
1136
+ const qIdx = idx === -1 ? -1 : rawUrl.indexOf('?', idx);
1137
+ const path = idx === -1 ? '/' : (qIdx === -1 ? rawUrl.slice(idx) : rawUrl.slice(idx, qIdx));
1138
+ const entry: UseLogEntry = {
1139
+ level: status >= 500 ? 'error' : status >= 400 ? 'warn' : 'info',
1140
+ timestamp: new Date().toISOString(),
1141
+ method,
1142
+ path,
1143
+ status,
1144
+ durationMs: Number(durationMs.toFixed(3)),
1145
+ ...(peerIp ? { ip: peerIp } : {})
1146
+ };
1147
+ if (this._logSink) this._logSink(entry);
1148
+ else console.log(JSON.stringify(entry));
1149
+ }
1150
+ : undefined;
1151
+ const args = ['pool', 'poolState', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyBox', ...(emitStructuredLog ? ['emitStructuredLog'] : []), ...(isDevUaf ? ['wrapUaf'] : []), ...(hasGlobalMw ? ['runGlobalOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...(apply404Cors ? ['apply404Cors'] : []), ...hNames];
1152
+ const values = [pool, poolState, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyBox, ...(emitStructuredLog ? [emitStructuredLog] : []), ...(isDevUaf ? [wrapUaf] : []), ...(hasGlobalMw ? [runGlobalOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...(apply404Cors ? [apply404Cors] : []), ...hoistedHandlers];
1088
1153
 
1089
- const logInit = isLog ? `
1154
+ const logInit = isLog
1155
+ ? emitStructuredLog
1156
+ ? `
1157
+ const start = performance.now();
1158
+ const doLog = (status) => emitStructuredLog(method, url, status, performance.now() - start, peerIp);`
1159
+ : `
1090
1160
  const start = performance.now();
1091
1161
  const doLog = (status) => {
1092
1162
  const duration = (performance.now() - start).toFixed(3);
@@ -1097,7 +1167,8 @@ export class BareJS<
1097
1167
  \`\${status >= 400 ? '\\x1b[33m' : '\\x1b[32m'}\${status}\\x1b[0m \` +
1098
1168
  \`\\x1b[90m(\${duration}ms)\\x1b[0m\`
1099
1169
  );
1100
- };` : '';
1170
+ };`
1171
+ : '';
1101
1172
 
1102
1173
  const compactHelpers = useCompactEmit
1103
1174
  ? `
@@ -1182,6 +1253,25 @@ export class BareJS<
1182
1253
  } else {
1183
1254
  this.hotFetch = compiledFetch;
1184
1255
  }
1256
+ if (this.requestHooks.length > 0 || this.responseHooks.length > 0) {
1257
+ const innerFetch = this.hotFetch!;
1258
+ const reqHooks = this.requestHooks.slice();
1259
+ const resHooks = this.responseHooks.slice();
1260
+ this.hotFetch = async (req: Request, peerIp?: string) => {
1261
+ const start = performance.now();
1262
+ for (let i = 0; i < reqHooks.length; i++) {
1263
+ const maybeRes = await reqHooks[i]!(req, peerIp);
1264
+ if (maybeRes instanceof Response) return maybeRes;
1265
+ }
1266
+ let res: Response = await innerFetch(req, peerIp);
1267
+ const durationMs = performance.now() - start;
1268
+ for (let i = 0; i < resHooks.length; i++) {
1269
+ const updated = await resHooks[i]!(req, res, durationMs);
1270
+ if (updated instanceof Response) res = updated;
1271
+ }
1272
+ return res;
1273
+ };
1274
+ }
1185
1275
  this.compiled = true;
1186
1276
  this.fetch = this.hotFetch!;
1187
1277
  }
@@ -1212,7 +1302,7 @@ export class BareJS<
1212
1302
  }
1213
1303
  public name: string = "App";
1214
1304
 
1215
- public trustProxy(enabled: boolean = true): this {
1305
+ public trustProxy(enabled: boolean | string[] = true): this {
1216
1306
  this._trustProxyBox.val = enabled;
1217
1307
  for (let i = 0; i < this.pool.length; i++) {
1218
1308
  const ctx = this.pool[i];
@@ -1225,6 +1315,8 @@ export class BareJS<
1225
1315
  if (
1226
1316
  this._useLog ||
1227
1317
  this.groupMiddleware.length > 0 ||
1318
+ this.requestHooks.length > 0 ||
1319
+ this.responseHooks.length > 0 ||
1228
1320
  this.errorHandler !== undefined ||
1229
1321
  this._trustProxyBox.val ||
1230
1322
  this._hasDerive ||
@@ -1353,6 +1445,8 @@ export class BareJS<
1353
1445
  if (
1354
1446
  this._useLog ||
1355
1447
  this.groupMiddleware.length > 0 ||
1448
+ this.requestHooks.length > 0 ||
1449
+ this.responseHooks.length > 0 ||
1356
1450
  this.errorHandler !== undefined ||
1357
1451
  this._trustProxyBox.val ||
1358
1452
  this._hasDerive ||
@@ -1410,7 +1504,7 @@ export class BareJS<
1410
1504
  port?: number,
1411
1505
  hostname: string = '0.0.0.0',
1412
1506
  reusePort: boolean = true,
1413
- options: { maxRequestBodySize?: number; trustProxy?: boolean; engine?: 'auto' | 'http' | 'uws' } = {}
1507
+ options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws' } = {}
1414
1508
  ) {
1415
1509
  if (options.trustProxy !== undefined) {
1416
1510
  this.trustProxy(options.trustProxy);
@@ -1493,6 +1587,64 @@ export class BareJS<
1493
1587
  process.on("message", onIpcMessage);
1494
1588
  return server.raw;
1495
1589
  }
1590
+
1591
+ public async listenCluster(
1592
+ port?: number,
1593
+ workers?: number,
1594
+ hostname: string = '0.0.0.0',
1595
+ options: { maxRequestBodySize?: number; trustProxy?: boolean | string[]; engine?: 'auto' | 'http' | 'uws' } = {}
1596
+ ): Promise<{ stop: () => Promise<void> | void; workers: number }> {
1597
+ const os = await import('node:os');
1598
+ const count = Math.max(1, workers ?? (typeof os.availableParallelism === 'function' ? os.availableParallelism() : os.cpus().length));
1599
+
1600
+ if (runtime.name === 'bun') {
1601
+ const bunGlobal = (globalThis as any).Bun;
1602
+ if (process.env.BARE_CLUSTER_WORKER === '1' || count === 1) {
1603
+ this.listen(port, hostname, true, options);
1604
+ return { stop: () => this.stop(false), workers: 1 };
1605
+ }
1606
+ const children: any[] = [];
1607
+ for (let i = 1; i < count; i++) {
1608
+ children.push(
1609
+ bunGlobal.spawn([process.execPath, ...process.argv.slice(1)], {
1610
+ env: { ...process.env, BARE_CLUSTER_WORKER: '1' },
1611
+ stdout: 'inherit',
1612
+ stderr: 'inherit'
1613
+ })
1614
+ );
1615
+ }
1616
+ this.listen(port, hostname, true, options);
1617
+ return {
1618
+ workers: count,
1619
+ stop: async () => {
1620
+ for (const c of children) {
1621
+ try { c.kill(); } catch {}
1622
+ }
1623
+ await this.stop(false);
1624
+ }
1625
+ };
1626
+ }
1627
+
1628
+ const clusterMod: any = await import('node:cluster');
1629
+ const cluster = clusterMod.default ?? clusterMod;
1630
+ if (cluster.isPrimary && count > 1) {
1631
+ const spawned: any[] = [];
1632
+ for (let i = 0; i < count; i++) {
1633
+ spawned.push(cluster.fork());
1634
+ }
1635
+ return {
1636
+ workers: count,
1637
+ stop: () => {
1638
+ for (const w of spawned) {
1639
+ try { w.kill(); } catch {}
1640
+ }
1641
+ }
1642
+ };
1643
+ }
1644
+
1645
+ this.listen(port, hostname, true, options);
1646
+ return { stop: () => this.stop(false), workers: count };
1647
+ }
1496
1648
  }
1497
1649
 
1498
1650
  export { Context, typebox, t };
@@ -84,6 +84,39 @@ export interface UploadStreamPart {
84
84
  value?: string;
85
85
  }
86
86
 
87
+ function ipv4ToInt(ip: string): number | null {
88
+ const parts = ip.split('.');
89
+ if (parts.length !== 4) return null;
90
+ let n = 0;
91
+ for (let i = 0; i < 4; i++) {
92
+ const v = Number(parts[i]);
93
+ if (!Number.isInteger(v) || v < 0 || v > 255) return null;
94
+ n = (n << 8) | v;
95
+ }
96
+ return n >>> 0;
97
+ }
98
+
99
+ export function isTrustedProxyIp(peerIp: string | undefined, trustProxy: boolean | string[]): boolean {
100
+ if (trustProxy === true) return true;
101
+ if (!trustProxy || !Array.isArray(trustProxy) || trustProxy.length === 0 || !peerIp) return false;
102
+ const normalized = peerIp.startsWith('::ffff:') ? peerIp.slice(7) : peerIp;
103
+ const peerInt = ipv4ToInt(normalized);
104
+ for (let i = 0; i < trustProxy.length; i++) {
105
+ const rule = trustProxy[i]!;
106
+ if (rule === normalized || rule === peerIp) return true;
107
+ const slash = rule.indexOf('/');
108
+ if (slash !== -1 && peerInt !== null) {
109
+ const baseInt = ipv4ToInt(rule.slice(0, slash));
110
+ const bits = Number(rule.slice(slash + 1));
111
+ if (baseInt !== null && Number.isInteger(bits) && bits >= 0 && bits <= 32) {
112
+ const mask = bits === 0 ? 0 : (0xffffffff << (32 - bits)) >>> 0;
113
+ if ((peerInt & mask) === (baseInt & mask)) return true;
114
+ }
115
+ }
116
+ }
117
+ return false;
118
+ }
119
+
87
120
  export class Context {
88
121
  public req!: Request;
89
122
  public params: Params = {};
@@ -96,9 +129,9 @@ export class Context {
96
129
  public _setCookies: string[] | undefined = undefined;
97
130
  public _requestId: string | undefined = undefined;
98
131
  public _peerIp: string | undefined = undefined;
99
- public _trustProxy: boolean = false;
132
+ public _trustProxy: boolean | string[] = false;
100
133
  public _detached: boolean = false;
101
- constructor(trustProxy: boolean = false) {
134
+ constructor(trustProxy: boolean | string[] = false) {
102
135
  this._trustProxy = trustProxy;
103
136
  }
104
137
 
@@ -586,7 +619,7 @@ export class Context {
586
619
  }
587
620
 
588
621
  public get ip(): string {
589
- if (this._trustProxy) {
622
+ if (isTrustedProxyIp(this._peerIp, this._trustProxy)) {
590
623
  const xff = this.req?.headers?.get('x-forwarded-for');
591
624
  if (xff) {
592
625
  const first = xff.split(',')[0]?.trim();
@@ -11,39 +11,47 @@ export const bunDriver: RuntimeDriver = {
11
11
  serve(opts: ServeOptions): ServerHandle {
12
12
  const wsCfg = opts.ws;
13
13
  const routes = opts.routes;
14
- const server = wsCfg
15
- ? Bun.serve<WebSocketRouteHandler>({
16
- port: opts.port,
17
- hostname: opts.hostname,
18
- reusePort: opts.reusePort,
19
- maxRequestBodySize: opts.maxRequestBodySize,
20
- ...(routes ? { routes } : {}),
21
- fetch(req: Request, srv: any) {
22
- if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
23
- const matched = matchWsRoute(wsCfg.routes, req.url);
24
- if (
25
- matched &&
26
- srv.upgrade(req, {
27
- data: matched.params ? { ...matched.handler, params: matched.params } : matched.handler
28
- })
29
- ) {
30
- return undefined as any;
14
+ let server: any;
15
+ try {
16
+ server = wsCfg
17
+ ? Bun.serve<WebSocketRouteHandler>({
18
+ port: opts.port,
19
+ hostname: opts.hostname,
20
+ reusePort: opts.reusePort,
21
+ maxRequestBodySize: opts.maxRequestBodySize,
22
+ ...(routes ? { routes } : {}),
23
+ fetch(req: Request, srv: any) {
24
+ if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
25
+ const matched = matchWsRoute(wsCfg.routes, req.url);
26
+ if (
27
+ matched &&
28
+ srv.upgrade(req, {
29
+ data: matched.params ? { ...matched.handler, params: matched.params } : matched.handler
30
+ })
31
+ ) {
32
+ return undefined as any;
33
+ }
31
34
  }
35
+ return opts.fetch(req, srv?.requestIP?.(req)?.address);
36
+ },
37
+ websocket: wsCfg.adapter
38
+ })
39
+ : Bun.serve({
40
+ port: opts.port,
41
+ hostname: opts.hostname,
42
+ reusePort: opts.reusePort,
43
+ maxRequestBodySize: opts.maxRequestBodySize,
44
+ ...(routes ? { routes } : {}),
45
+ fetch(req: Request, srv: any) {
46
+ return opts.fetch(req, srv?.requestIP?.(req)?.address);
32
47
  }
33
- return opts.fetch(req, srv?.requestIP?.(req)?.address);
34
- },
35
- websocket: wsCfg.adapter
36
- })
37
- : Bun.serve({
38
- port: opts.port,
39
- hostname: opts.hostname,
40
- reusePort: opts.reusePort,
41
- maxRequestBodySize: opts.maxRequestBodySize,
42
- ...(routes ? { routes } : {}),
43
- fetch(req: Request, srv: any) {
44
- return opts.fetch(req, srv?.requestIP?.(req)?.address);
45
- }
46
- });
48
+ });
49
+ } catch (err: any) {
50
+ if (err?.code === 'EADDRINUSE' || /in use/i.test(err?.message || '')) {
51
+ throw new Error(`[BareJS] Port ${opts.port} is already in use on ${opts.hostname}. Choose a different port or stop the existing process.`);
52
+ }
53
+ throw err;
54
+ }
47
55
 
48
56
  return {
49
57
  stop(closeActiveConnections = false) {
@@ -197,7 +197,7 @@ export const nodeDriver: RuntimeDriver = {
197
197
  name: 'node',
198
198
 
199
199
  serve(opts: ServeOptions): ServerHandle {
200
- if (opts.engine !== 'http' && !opts.ws) {
200
+ if (opts.engine !== 'http') {
201
201
  const uwsMod = tryLoadUws();
202
202
  if (uwsMod) {
203
203
  return serveUws(opts, uwsMod);
@@ -462,9 +462,23 @@ export const nodeDriver: RuntimeDriver = {
462
462
  }
463
463
  server.listen(listenOpts);
464
464
 
465
- const ready = new Promise<void>((resolve) => {
466
- if (server.listening) resolve();
467
- else server.once('listening', () => resolve());
465
+ const ready = new Promise<void>((resolve, reject) => {
466
+ if (server.listening) {
467
+ resolve();
468
+ return;
469
+ }
470
+ const onErr = (err: any) => {
471
+ if (err?.code === 'EADDRINUSE') {
472
+ reject(new Error(`[BareJS] Port ${opts.port} is already in use on ${opts.hostname}. Choose a different port or stop the existing process.`));
473
+ } else {
474
+ reject(err);
475
+ }
476
+ };
477
+ server.once('error', onErr);
478
+ server.once('listening', () => {
479
+ server.removeListener('error', onErr);
480
+ resolve();
481
+ });
468
482
  });
469
483
 
470
484
  const stopFn = (closeActiveConnections = false) =>