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.
@@ -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,7 +226,7 @@ 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) => {
@@ -235,23 +236,70 @@ function writeWebResponseToUws(res: any, webRes: Response): void {
235
236
  if (typeof anyHeaders.getSetCookie === 'function') {
236
237
  const cookies: string[] = anyHeaders.getSetCookie();
237
238
  for (let i = 0; i < cookies.length; i++) {
238
- res.writeHeader('set-cookie', cookies[i]);
239
+ res.writeHeader('set-cookie', cookies[i]!);
239
240
  }
240
241
  }
242
+ }
243
+
244
+ function writeWebResponseToUws(res: any, webRes: Response, isAborted?: () => boolean): void {
241
245
  if (!webRes.body) {
242
- res.end();
246
+ if (isAborted?.()) return;
247
+ res.cork(() => {
248
+ writeUwsHeaders(res, webRes);
249
+ res.end();
250
+ });
243
251
  return;
244
252
  }
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
- );
253
+
254
+ const reader = webRes.body.getReader();
255
+ let headersSent = false;
256
+
257
+ const pump = (): void => {
258
+ reader.read().then(
259
+ ({ value, done }) => {
260
+ if (isAborted?.()) {
261
+ try { reader.cancel(); } catch {}
262
+ return;
263
+ }
264
+ if (done) {
265
+ res.cork(() => {
266
+ if (!headersSent) {
267
+ writeUwsHeaders(res, webRes);
268
+ headersSent = true;
269
+ }
270
+ res.end();
271
+ });
272
+ return;
273
+ }
274
+ if (value && value.byteLength > 0) {
275
+ const chunk = Buffer.from(value.buffer, value.byteOffset, value.byteLength);
276
+ let ok = true;
277
+ res.cork(() => {
278
+ if (!headersSent) {
279
+ writeUwsHeaders(res, webRes);
280
+ headersSent = true;
281
+ }
282
+ ok = res.write(chunk);
283
+ });
284
+ if (!ok && typeof res.onWritable === 'function') {
285
+ res.onWritable(() => {
286
+ pump();
287
+ return true;
288
+ });
289
+ return;
290
+ }
291
+ }
292
+ pump();
293
+ },
294
+ () => {
295
+ if (!isAborted?.()) {
296
+ try { res.close(); } catch {}
297
+ }
298
+ }
299
+ );
300
+ };
301
+
302
+ pump();
255
303
  }
256
304
 
257
305
  function writeOutToUws(res: any, ctx: UwsContext | null, out: any): void {
@@ -302,6 +350,7 @@ export function serveUws(
302
350
  const isProd = process.env.NODE_ENV === 'production';
303
351
  const pool: UwsContext[] = [];
304
352
  const maxPool = 4096;
353
+ let inFlight = 0;
305
354
 
306
355
  // Tier 1: Direct uWS fast-path for bodyless methods (GET, HEAD, DELETE, OPTIONS)
307
356
  if (opts.uwsRoutes) {
@@ -434,6 +483,7 @@ export function serveUws(
434
483
 
435
484
  const dispatchFetch = (bodyBuf?: Buffer) => {
436
485
  if (aborted) return;
486
+ inFlight++;
437
487
  const webReq = new Request(fullUrl, {
438
488
  method,
439
489
  headers,
@@ -441,38 +491,12 @@ export function serveUws(
441
491
  });
442
492
  Promise.resolve(opts.fetch(webReq, peerIp)).then(
443
493
  (webRes) => {
494
+ inFlight = Math.max(0, inFlight - 1);
444
495
  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
- );
496
+ writeWebResponseToUws(res, webRes, () => aborted);
474
497
  },
475
498
  (e) => {
499
+ inFlight = Math.max(0, inFlight - 1);
476
500
  if (!aborted) res.cork(() => writeUwsError(res, e));
477
501
  }
478
502
  );
@@ -508,6 +532,73 @@ export function serveUws(
508
532
  });
509
533
  });
510
534
 
535
+ if (opts.ws) {
536
+ const wsCfg = opts.ws;
537
+ const getWrapped = (ws: any) => {
538
+ const ud = ws.getUserData();
539
+ if (!ud.wrapped) {
540
+ ud.wrapped = {
541
+ data: ud.handler,
542
+ send(data: any, isBinary?: boolean) {
543
+ return ws.send(data, isBinary ?? (typeof data !== 'string'));
544
+ },
545
+ subscribe(topic: string) {
546
+ return typeof ws.subscribe === 'function' ? ws.subscribe(topic) : false;
547
+ },
548
+ unsubscribe(topic: string) {
549
+ return typeof ws.unsubscribe === 'function' ? ws.unsubscribe(topic) : false;
550
+ },
551
+ publish(topic: string, data: any, isBinary?: boolean) {
552
+ return typeof ws.publish === 'function' ? ws.publish(topic, data, isBinary ?? (typeof data !== 'string')) : false;
553
+ },
554
+ close(code?: number, reason?: string) {
555
+ if (typeof ws.end === 'function') ws.end(code, reason);
556
+ else if (typeof ws.close === 'function') ws.close();
557
+ },
558
+ raw: ws
559
+ };
560
+ }
561
+ return ud.wrapped;
562
+ };
563
+
564
+ app.ws('/*', {
565
+ upgrade(res: any, req: any, context: any) {
566
+ const urlPath = req.getUrl();
567
+ const queryStr = req.getQuery();
568
+ const fullUrl = `http://localhost${urlPath}${queryStr ? `?${queryStr}` : ''}`;
569
+ const matched = matchWsRoute(wsCfg.routes, fullUrl);
570
+ if (!matched) {
571
+ res.writeStatus('404 Not Found').end();
572
+ return;
573
+ }
574
+ const handler: any = matched.params
575
+ ? { ...matched.handler, params: matched.params }
576
+ : matched.handler;
577
+ res.upgrade(
578
+ { handler, wrapped: null },
579
+ req.getHeader('sec-websocket-key'),
580
+ req.getHeader('sec-websocket-protocol'),
581
+ req.getHeader('sec-websocket-extensions'),
582
+ context
583
+ );
584
+ },
585
+ open(ws: any) {
586
+ wsCfg.adapter.open(getWrapped(ws));
587
+ },
588
+ message(ws: any, msg: ArrayBuffer, isBinary: boolean) {
589
+ const payload = isBinary ? new Uint8Array(msg) : Buffer.from(msg).toString('utf8');
590
+ wsCfg.adapter.message(getWrapped(ws), payload);
591
+ },
592
+ drain(ws: any) {
593
+ wsCfg.adapter.drain(getWrapped(ws));
594
+ },
595
+ close(ws: any, code: number, message: ArrayBuffer) {
596
+ const reason = message && message.byteLength > 0 ? Buffer.from(message).toString('utf8') : '';
597
+ wsCfg.adapter.close(getWrapped(ws), code, reason);
598
+ }
599
+ });
600
+ }
601
+
511
602
  let listenSocket: any = null;
512
603
  let boundPort = opts.port;
513
604
 
@@ -536,11 +627,20 @@ export function serveUws(
536
627
  }
537
628
  };
538
629
 
630
+ const drainFn = async (timeoutMs: number = 5000) => {
631
+ stopFn();
632
+ const deadline = Date.now() + timeoutMs;
633
+ while (inFlight > 0 && Date.now() < deadline) {
634
+ await new Promise((r) => setTimeout(r, 10));
635
+ }
636
+ };
637
+
539
638
  Object.defineProperty(app, 'port', {
540
639
  get: () => boundPort,
541
640
  configurable: true
542
641
  });
543
642
  app.stop = stopFn;
643
+ app.drain = drainFn;
544
644
  app.ready = ready;
545
645
 
546
646
  return {
@@ -548,7 +648,8 @@ export function serveUws(
548
648
  return boundPort;
549
649
  },
550
650
  stop: stopFn,
651
+ drain: drainFn,
551
652
  raw: app,
552
653
  ready
553
- } as ServerHandle & { ready: Promise<void> };
654
+ } as ServerHandle & { ready: Promise<void>; drain: (timeoutMs?: number) => Promise<void> };
554
655
  }
@@ -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