barejs 0.2.1 → 0.2.4

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.
@@ -1,6 +1,7 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { join } from 'node:path';
3
3
  import type { ServeOptions, ServerHandle } from './types';
4
+ import { matchWsRoute, type WebSocketRouteHandler } from '../core/ws-match';
4
5
 
5
6
  export interface UwsRouteEntry {
6
7
  method: string;
@@ -225,33 +226,82 @@ class UwsContext {
225
226
  }
226
227
  }
227
228
 
228
- function writeWebResponseToUws(res: any, webRes: Response): void {
229
+ function writeUwsHeaders(res: any, webRes: Response): void {
229
230
  const status = webRes.status;
230
231
  if (status !== 200) res.writeStatus(statusLine(status));
231
232
  webRes.headers.forEach((value, key) => {
232
- res.writeHeader(key, value);
233
+ if (key !== 'content-length' && key !== 'transfer-encoding') {
234
+ res.writeHeader(key, value);
235
+ }
233
236
  });
234
237
  const anyHeaders = webRes.headers as any;
235
238
  if (typeof anyHeaders.getSetCookie === 'function') {
236
239
  const cookies: string[] = anyHeaders.getSetCookie();
237
240
  for (let i = 0; i < cookies.length; i++) {
238
- res.writeHeader('set-cookie', cookies[i]);
241
+ res.writeHeader('set-cookie', cookies[i]!);
239
242
  }
240
243
  }
244
+ }
245
+
246
+ function writeWebResponseToUws(res: any, webRes: Response, isAborted?: () => boolean): void {
241
247
  if (!webRes.body) {
242
- res.end();
248
+ if (isAborted?.()) return;
249
+ res.cork(() => {
250
+ writeUwsHeaders(res, webRes);
251
+ res.end();
252
+ });
243
253
  return;
244
254
  }
245
- webRes.arrayBuffer().then(
246
- (buf) => {
247
- res.cork(() => {
248
- res.end(Buffer.from(buf));
249
- });
250
- },
251
- () => {
252
- try { res.close(); } catch {}
253
- }
254
- );
255
+
256
+ const reader = webRes.body.getReader();
257
+ let headersSent = false;
258
+
259
+ const pump = (): void => {
260
+ reader.read().then(
261
+ ({ value, done }) => {
262
+ if (isAborted?.()) {
263
+ try { reader.cancel(); } catch {}
264
+ return;
265
+ }
266
+ if (done) {
267
+ res.cork(() => {
268
+ if (!headersSent) {
269
+ writeUwsHeaders(res, webRes);
270
+ headersSent = true;
271
+ }
272
+ res.end();
273
+ });
274
+ return;
275
+ }
276
+ if (value && value.byteLength > 0) {
277
+ const chunk = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
278
+ let ok = true;
279
+ res.cork(() => {
280
+ if (!headersSent) {
281
+ writeUwsHeaders(res, webRes);
282
+ headersSent = true;
283
+ }
284
+ ok = res.write(chunk);
285
+ });
286
+ if (!ok && typeof res.onWritable === 'function') {
287
+ res.onWritable(() => {
288
+ pump();
289
+ return true;
290
+ });
291
+ return;
292
+ }
293
+ }
294
+ pump();
295
+ },
296
+ () => {
297
+ if (!isAborted?.()) {
298
+ try { res.close(); } catch {}
299
+ }
300
+ }
301
+ );
302
+ };
303
+
304
+ pump();
255
305
  }
256
306
 
257
307
  function writeOutToUws(res: any, ctx: UwsContext | null, out: any): void {
@@ -302,6 +352,7 @@ export function serveUws(
302
352
  const isProd = process.env.NODE_ENV === 'production';
303
353
  const pool: UwsContext[] = [];
304
354
  const maxPool = 4096;
355
+ let inFlight = 0;
305
356
 
306
357
  // Tier 1: Direct uWS fast-path for bodyless methods (GET, HEAD, DELETE, OPTIONS)
307
358
  if (opts.uwsRoutes) {
@@ -434,6 +485,7 @@ export function serveUws(
434
485
 
435
486
  const dispatchFetch = (bodyBuf?: Buffer) => {
436
487
  if (aborted) return;
488
+ inFlight++;
437
489
  const webReq = new Request(fullUrl, {
438
490
  method,
439
491
  headers,
@@ -441,38 +493,12 @@ export function serveUws(
441
493
  });
442
494
  Promise.resolve(opts.fetch(webReq, peerIp)).then(
443
495
  (webRes) => {
496
+ inFlight = Math.max(0, inFlight - 1);
444
497
  if (aborted) return;
445
- if (!webRes.body) {
446
- res.cork(() => {
447
- writeWebResponseToUws(res, webRes);
448
- });
449
- return;
450
- }
451
- webRes.arrayBuffer().then(
452
- (buf) => {
453
- if (aborted) return;
454
- res.cork(() => {
455
- const status = webRes.status;
456
- if (status !== 200) res.writeStatus(statusLine(status));
457
- webRes.headers.forEach((value, key) => {
458
- res.writeHeader(key, value);
459
- });
460
- const anyHeaders = webRes.headers as any;
461
- if (typeof anyHeaders.getSetCookie === 'function') {
462
- const cookies: string[] = anyHeaders.getSetCookie();
463
- for (let i = 0; i < cookies.length; i++) {
464
- res.writeHeader('set-cookie', cookies[i]);
465
- }
466
- }
467
- res.end(Buffer.from(buf));
468
- });
469
- },
470
- () => {
471
- if (!aborted) try { res.close(); } catch {}
472
- }
473
- );
498
+ writeWebResponseToUws(res, webRes, () => aborted);
474
499
  },
475
500
  (e) => {
501
+ inFlight = Math.max(0, inFlight - 1);
476
502
  if (!aborted) res.cork(() => writeUwsError(res, e));
477
503
  }
478
504
  );
@@ -490,7 +516,7 @@ export function serveUws(
490
516
 
491
517
  res.onData((ab: ArrayBuffer, isLast: boolean) => {
492
518
  if (aborted || rejected) return;
493
- const chunk = Buffer.from(ab);
519
+ const chunk = Buffer.from(new Uint8Array(ab));
494
520
  totalLen += chunk.length;
495
521
  if (totalLen > maxBody) {
496
522
  rejected = true;
@@ -508,6 +534,73 @@ export function serveUws(
508
534
  });
509
535
  });
510
536
 
537
+ if (opts.ws) {
538
+ const wsCfg = opts.ws;
539
+ const getWrapped = (ws: any) => {
540
+ const ud = ws.getUserData();
541
+ if (!ud.wrapped) {
542
+ ud.wrapped = {
543
+ data: ud.handler,
544
+ send(data: any, isBinary?: boolean) {
545
+ return ws.send(data, isBinary ?? (typeof data !== 'string'));
546
+ },
547
+ subscribe(topic: string) {
548
+ return typeof ws.subscribe === 'function' ? ws.subscribe(topic) : false;
549
+ },
550
+ unsubscribe(topic: string) {
551
+ return typeof ws.unsubscribe === 'function' ? ws.unsubscribe(topic) : false;
552
+ },
553
+ publish(topic: string, data: any, isBinary?: boolean) {
554
+ return typeof ws.publish === 'function' ? ws.publish(topic, data, isBinary ?? (typeof data !== 'string')) : false;
555
+ },
556
+ close(code?: number, reason?: string) {
557
+ if (typeof ws.end === 'function') ws.end(code, reason);
558
+ else if (typeof ws.close === 'function') ws.close();
559
+ },
560
+ raw: ws
561
+ };
562
+ }
563
+ return ud.wrapped;
564
+ };
565
+
566
+ app.ws('/*', {
567
+ upgrade(res: any, req: any, context: any) {
568
+ const urlPath = req.getUrl();
569
+ const queryStr = req.getQuery();
570
+ const fullUrl = `http://localhost${urlPath}${queryStr ? `?${queryStr}` : ''}`;
571
+ const matched = matchWsRoute(wsCfg.routes, fullUrl);
572
+ if (!matched) {
573
+ res.writeStatus('404 Not Found').end();
574
+ return;
575
+ }
576
+ const handler: any = matched.params
577
+ ? { ...matched.handler, params: matched.params }
578
+ : matched.handler;
579
+ res.upgrade(
580
+ { handler, wrapped: null },
581
+ req.getHeader('sec-websocket-key'),
582
+ req.getHeader('sec-websocket-protocol'),
583
+ req.getHeader('sec-websocket-extensions'),
584
+ context
585
+ );
586
+ },
587
+ open(ws: any) {
588
+ wsCfg.adapter.open(getWrapped(ws));
589
+ },
590
+ message(ws: any, msg: ArrayBuffer, isBinary: boolean) {
591
+ const payload = isBinary ? new Uint8Array(msg) : Buffer.from(msg).toString('utf8');
592
+ wsCfg.adapter.message(getWrapped(ws), payload);
593
+ },
594
+ drain(ws: any) {
595
+ wsCfg.adapter.drain(getWrapped(ws));
596
+ },
597
+ close(ws: any, code: number, message: ArrayBuffer) {
598
+ const reason = message && message.byteLength > 0 ? Buffer.from(message).toString('utf8') : '';
599
+ wsCfg.adapter.close(getWrapped(ws), code, reason);
600
+ }
601
+ });
602
+ }
603
+
511
604
  let listenSocket: any = null;
512
605
  let boundPort = opts.port;
513
606
 
@@ -536,11 +629,20 @@ export function serveUws(
536
629
  }
537
630
  };
538
631
 
632
+ const drainFn = async (timeoutMs: number = 5000) => {
633
+ stopFn();
634
+ const deadline = Date.now() + timeoutMs;
635
+ while (inFlight > 0 && Date.now() < deadline) {
636
+ await new Promise((r) => setTimeout(r, 10));
637
+ }
638
+ };
639
+
539
640
  Object.defineProperty(app, 'port', {
540
641
  get: () => boundPort,
541
642
  configurable: true
542
643
  });
543
644
  app.stop = stopFn;
645
+ app.drain = drainFn;
544
646
  app.ready = ready;
545
647
 
546
648
  return {
@@ -548,7 +650,8 @@ export function serveUws(
548
650
  return boundPort;
549
651
  },
550
652
  stop: stopFn,
653
+ drain: drainFn,
551
654
  raw: app,
552
655
  ready
553
- } as ServerHandle & { ready: Promise<void> };
656
+ } as ServerHandle & { ready: Promise<void>; drain: (timeoutMs?: number) => Promise<void> };
554
657
  }
@@ -351,10 +351,11 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
351
351
  return checkClaimsAndRevocation(ctx, decoded, token, next);
352
352
  };
353
353
 
354
- if (customRevoked || revocationStore) {
355
- return async (ctx: any, next: any) => verifySync(ctx, next);
356
- }
357
- return verifySync;
354
+ const mw = customRevoked || revocationStore
355
+ ? async (ctx: any, next: any) => verifySync(ctx, next)
356
+ : verifySync;
357
+ (mw as any).__isBareAuth = true;
358
+ return mw;
358
359
  }
359
360
 
360
361
  // Asymmetric (RS256 / ES256) and/or JWKS verification path
@@ -426,7 +427,7 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
426
427
  return imported;
427
428
  };
428
429
 
429
- return async (ctx: any, next: any) => {
430
+ const mw = async (ctx: any, next: any) => {
430
431
  const authHeader = ctx.req.headers.get('Authorization');
431
432
  if (!authHeader?.startsWith('Bearer ')) {
432
433
  return ctx.status(401).send("Bearer token required");
@@ -498,6 +499,8 @@ export const bareAuth = (secretOrOpts: string | BareAuthOptions) => {
498
499
  }
499
500
  return checkClaimsAndRevocation(ctx, decoded, token, next);
500
501
  };
502
+ (mw as any).__isBareAuth = true;
503
+ return mw;
501
504
  };
502
505
 
503
506
  const sha256 = (value: string): Buffer => createHash('sha256').update(value).digest();
@@ -510,7 +513,7 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
510
513
  const expectedUserHash = sha256(credentials.user);
511
514
  const expectedPassHash = sha256(credentials.pass);
512
515
 
513
- return async (ctx: any, next: Next) => {
516
+ const mw = async (ctx: any, next: Next) => {
514
517
  const authHeader = ctx.req.headers.get('Authorization');
515
518
  if (!authHeader?.startsWith('Basic ')) {
516
519
  return ctx.status(401).json({ status: 'error', message: 'Basic Auth required' });
@@ -537,6 +540,8 @@ export const basicAuth = (credentials: { user: string; pass: string }) => {
537
540
 
538
541
  return ctx.status(401).json({ status: 'error', message: 'Invalid credentials' });
539
542
  };
543
+ (mw as any).__isBasicAuth = true;
544
+ return mw;
540
545
  };
541
546
 
542
547
  /**
@@ -69,6 +69,8 @@ const extractSchema = (schema: any): Record<string, any> => {
69
69
  export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {}) => {
70
70
  const paths: Record<string, Record<string, any>> = {};
71
71
  const excluded = new Set<string>(['/docs', '/docs/json', ...(options.excludePaths || [])]);
72
+ let usesBearer = false;
73
+ let usesBasic = false;
72
74
 
73
75
  for (const route of routes) {
74
76
  if (excluded.has(route.path)) continue;
@@ -86,9 +88,18 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
86
88
  let responseSchema: any = undefined;
87
89
  let detail: any = undefined;
88
90
  let paramSchemaObj: Record<string, any> | null = null;
91
+ const routeSecurity: any[] = [];
89
92
 
90
93
  for (const h of route.handlers) {
91
94
  if (!h) continue;
95
+ if ((h as any).__isBareAuth) {
96
+ usesBearer = true;
97
+ routeSecurity.push({ bearerAuth: [] });
98
+ }
99
+ if ((h as any).__isBasicAuth) {
100
+ usesBasic = true;
101
+ routeSecurity.push({ basicAuth: [] });
102
+ }
92
103
  const rs = (h as any).__routeSchemas;
93
104
  if (rs) {
94
105
  if (rs.detail) detail = rs.detail;
@@ -144,6 +155,7 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
144
155
  summary: detail?.summary || `${route.method} ${openApiPath}`,
145
156
  ...(detail?.description ? { description: detail.description } : {}),
146
157
  ...(detail?.tags ? { tags: detail.tags } : {}),
158
+ ...(routeSecurity.length ? { security: routeSecurity } : {}),
147
159
  ...(allParams.length ? { parameters: allParams } : {}),
148
160
  ...(requestBody ? { requestBody } : {}),
149
161
  responses: {
@@ -157,6 +169,11 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
157
169
  };
158
170
  }
159
171
 
172
+ const autoSchemes: Record<string, any> = {};
173
+ if (usesBearer) autoSchemes.bearerAuth = { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' };
174
+ if (usesBasic) autoSchemes.basicAuth = { type: 'http', scheme: 'basic' };
175
+ const mergedSchemes = { ...autoSchemes, ...(options.securitySchemes || {}) };
176
+
160
177
  return {
161
178
  openapi: '3.1.0',
162
179
  info: {
@@ -166,8 +183,8 @@ export const generateOpenAPISpec = (routes: any[], options: OpenAPIOptions = {})
166
183
  },
167
184
  ...(options.servers?.length ? { servers: options.servers } : {}),
168
185
  ...(options.tags?.length ? { tags: options.tags } : {}),
169
- ...(options.securitySchemes
170
- ? { components: { securitySchemes: options.securitySchemes } }
186
+ ...(Object.keys(mergedSchemes).length > 0
187
+ ? { components: { securitySchemes: mergedSchemes } }
171
188
  : {}),
172
189
  ...(options.security?.length ? { security: options.security } : {}),
173
190
  paths
@@ -14,6 +14,10 @@ export interface StaticOptions {
14
14
  etag?: boolean;
15
15
  /** Optional LRU metadata cache for realpath, stat, and ETag to avoid repeated syscalls */
16
16
  cacheMetadata?: boolean | StaticMetadataCacheOptions;
17
+ /** Enable Single Page Application fallback to index.html for unmatched GET/HEAD routes */
18
+ spa?: boolean;
19
+ /** Custom fallback file relative to root when spa is true (default: 'index.html') */
20
+ spaFallback?: string;
17
21
  }
18
22
 
19
23
  interface StaticMetaEntry {
@@ -31,12 +35,42 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
31
35
  const maxAge = options.maxAge ?? 3600;
32
36
  const enableEtag = options.etag !== false;
33
37
 
34
- const cacheOpt = options.cacheMetadata;
38
+ const cacheOpt = options.cacheMetadata !== undefined
39
+ ? options.cacheMetadata
40
+ : process.env.NODE_ENV === 'production';
35
41
  const useCache = Boolean(cacheOpt);
36
42
  const cacheMax = typeof cacheOpt === 'object' ? (cacheOpt.maxEntries ?? 1000) : 1000;
37
43
  const cacheTtl = typeof cacheOpt === 'object' ? (cacheOpt.ttlMs ?? 30_000) : 30_000;
38
44
  const metaCache = useCache ? new Map<string, StaticMetaEntry>() : null;
39
45
 
46
+ const serveSpaFallback = async (next: any): Promise<Response | undefined> => {
47
+ const downstream = await next?.();
48
+ if (downstream instanceof Response && downstream.status !== 404) return downstream;
49
+ if (!options.spa) return downstream;
50
+ const fallbackName = (options.spaFallback ?? 'index.html').replace(/^\/+/, '');
51
+ const fallbackPath = resolve(rootDir, fallbackName);
52
+ if (fallbackPath !== rootDir && !fallbackPath.startsWith(rootPrefix)) return downstream;
53
+ try {
54
+ const [realRoot, resolvedFallback] = await Promise.all([
55
+ (realRootPromise ??= realpath(rootDir)),
56
+ realpath(fallbackPath)
57
+ ]);
58
+ const realPrefix = realRoot.endsWith(sep) ? realRoot : realRoot + sep;
59
+ if (resolvedFallback !== realRoot && !resolvedFallback.startsWith(realPrefix)) return downstream;
60
+ const st = await stat(resolvedFallback);
61
+ if (st.isDirectory()) return downstream;
62
+ const file = runtime.openFile(resolvedFallback);
63
+ return new Response(file.full(), {
64
+ headers: {
65
+ 'Content-Type': file.type || 'text/html; charset=utf-8',
66
+ 'Cache-Control': 'no-cache'
67
+ }
68
+ });
69
+ } catch {
70
+ return downstream;
71
+ }
72
+ };
73
+
40
74
  const mw = async (ctx: any, next: any) => {
41
75
  const method = ctx.req.method;
42
76
  if (method !== 'GET' && method !== 'HEAD') return next?.();
@@ -91,7 +125,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
91
125
  return ctx.status(403).send('Forbidden');
92
126
  }
93
127
  const st = await stat(resolvedFile);
94
- if (st.isDirectory()) return next?.();
128
+ if (st.isDirectory()) return (options.spa && ctx._isStaticFallback) ? serveSpaFallback(next) : next?.();
95
129
  realFile = resolvedFile;
96
130
  fileSize = st.size;
97
131
  mtimeMs = Math.floor(st.mtimeMs);
@@ -112,7 +146,7 @@ export const staticFile = (root: string = 'public', options: StaticOptions = {})
112
146
  }
113
147
  } catch {
114
148
  realRootPromise = null;
115
- return next?.();
149
+ return (options.spa && ctx._isStaticFallback) ? serveSpaFallback(next) : next?.();
116
150
  }
117
151
  }
118
152