@mednours/backon 0.8.0 → 0.9.0

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 +1 @@
1
- {"version":3,"file":"auth-core.d.ts","sourceRoot":"","sources":["../src/auth-core.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAE7D;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,mDAAmD;IACnD,MAAM,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,GAAG,CAAC,EAAE,kBAAkB,CAAC;IACzB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,cAAc;IAC7B,qCAAqC;IACrC,MAAM,EAAE,MAAM,CAAC;IACf,iDAAiD;IACjD,GAAG,CAAC,EAAE,kBAAkB,CAAC;IACzB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAKD,mFAAmF;AACnF,wBAAgB,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC,CAMrF;AAED,gHAAgH;AAChH,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,UAAU,CAAC,CAEvF;AAED,8GAA8G;AAC9G,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAKjF;AAED,6FAA6F;AAC7F,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAepG;AAED,kGAAkG;AAClG,wBAA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AAM,GAAG,SAAS,CAIjF;AAED,6FAA6F;AAC7F,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAepG;AAED,kGAAkG;AAClG,wBAAsB,uBAAuB,CAAC,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA0B9G;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CACpC,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,OAAO,EAAE,gBAAgB,GACxB,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAY7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../src/create-app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAO5B,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAUD;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,oDAgDvD"}
1
+ {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../src/create-app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAO5B,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,MAAM,WAAW,gBAAgB;IAC/B;;;;OAIG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE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AC9D;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,WAAW,CAAC,CAAC,GAAG,SAAS,EAAE,CAAC,GAAG,SAAS,EAAE,CAAC,GAAG,SAAS,EACrE,MAAM,EAAE,WAAW,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAC5B,OAAO,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAC7B,cAAc,CAiDhB"}
@@ -1 +1 @@
1
- {"version":3,"file":"cache-control.d.ts","sourceRoot":"","sources":["../../src/express/cache-control.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAA2B,KAAK,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE1F,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,UAEV,OAAO,OAAO,QAAQ,QAAQ,YAAY,KAAG,IAAI,CAM/F"}
1
+ {"version":3,"file":"cache-control.d.ts","sourceRoot":"","sources":["../../src/express/cache-control.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAA2B,KAAK,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAE1F,YAAY,EAAE,mBAAmB,EAAE,CAAC;AAEpC;;;GAGG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,mBAAmB,UAEV,OAAO,OAAO,QAAQ,QAAQ,YAAY,KAAG,IAAI,CAU/F"}
@@ -1 +1 @@
1
- {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../../src/express/create-app.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,KAAK,OAAO,EAAkD,MAAM,SAAS,CAAC;AAShG,MAAM,WAAW,gBAAgB;IAC/B,sGAAsG;IACtG,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAUD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,GAAG,OAAO,CA4BjE;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAwBrD"}
1
+ {"version":3,"file":"create-app.d.ts","sourceRoot":"","sources":["../../src/express/create-app.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,KAAK,OAAO,EAAkD,MAAM,SAAS,CAAC;AAShG,MAAM,WAAW,gBAAgB;IAC/B,sGAAsG;IACtG,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,uDAAuD;IACvD,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB;;;OAGG;IACH,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAUD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,GAAG,OAAO,CA4BjE;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,IAAI,CAgCrD"}
@@ -67,8 +67,12 @@ function trackRoutes(target) {
67
67
  if (typeof originalUse === "function") {
68
68
  const boundUse = originalUse.bind(tracked);
69
69
  tracked.use = (...args) => {
70
- if (typeof args[0] === "string" && isTracked(args[1])) {
71
- tracked.__backonEntries.push({ type: "mount", prefix: args[0], target: args[1] });
70
+ const prefix = typeof args[0] === "string" ? args[0] : "";
71
+ const candidates = typeof args[0] === "string" ? args.slice(1) : args;
72
+ for (const candidate of candidates) {
73
+ if (isTracked(candidate)) {
74
+ tracked.__backonEntries.push({ type: "mount", prefix, target: candidate });
75
+ }
72
76
  }
73
77
  return boundUse(...args);
74
78
  };
@@ -96,7 +100,7 @@ var DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024;
96
100
  function resolveAllowedOrigins(options) {
97
101
  if (options.allowedOrigins) return options.allowedOrigins;
98
102
  const fromEnv = process.env.ALLOWED_ORIGINS;
99
- return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
103
+ return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()).filter(Boolean) : [];
100
104
  }
101
105
  function createApp(options = {}) {
102
106
  const app = trackRoutes(express());
@@ -117,7 +121,11 @@ function createApp(options = {}) {
117
121
  return app;
118
122
  }
119
123
  function attachErrorHandler(app) {
120
- app.use((err, _req, res, _next) => {
124
+ app.use((err, _req, res, next) => {
125
+ if (res.headersSent) {
126
+ next(err);
127
+ return;
128
+ }
121
129
  if (err instanceof AppError) {
122
130
  logger.warn(
123
131
  { requestId: res.locals.requestId, code: err.code, details: err.details },
@@ -126,11 +134,16 @@ function attachErrorHandler(app) {
126
134
  res.status(err.statusCode).json({ error: { code: err.code, message: err.message, details: err.details } });
127
135
  return;
128
136
  }
129
- const status = err?.status ?? err?.statusCode;
137
+ const errObj = err;
138
+ const status = errObj?.status ?? errObj?.statusCode;
130
139
  if (status === 413) {
131
140
  res.status(413).json({ error: { code: "payload_too_large", message: "Request body too large" } });
132
141
  return;
133
142
  }
143
+ if (status === 400 && errObj?.type === "entity.parse.failed") {
144
+ res.status(400).json({ error: { code: "invalid_body", message: "Invalid JSON request body" } });
145
+ return;
146
+ }
134
147
  logger.error({ requestId: res.locals.requestId, err }, "unhandled error");
135
148
  res.status(500).json({ error: { code: "internal_error", message: "Something went wrong" } });
136
149
  });
@@ -260,9 +273,8 @@ function verifyJwt(token, options) {
260
273
  }
261
274
  function extractBearerToken(header) {
262
275
  if (!header) return void 0;
263
- const [scheme, token] = header.split(" ");
264
- if (scheme?.toLowerCase() !== "bearer" || !token) return void 0;
265
- return token;
276
+ const match = header.trim().match(/^Bearer\s+(\S+)$/i);
277
+ return match ? match[1] : void 0;
266
278
  }
267
279
  function parseCookieHeader(cookieHeader, name) {
268
280
  if (!cookieHeader) return void 0;
@@ -360,27 +372,47 @@ function buildCacheControlHeader(options) {
360
372
  function cacheControl(options) {
361
373
  const headerValue = buildCacheControlHeader(options);
362
374
  return function cacheControlMiddleware(_req, res, next) {
363
- if (!res.getHeader("Cache-Control")) {
364
- res.setHeader("Cache-Control", headerValue);
365
- }
375
+ const origWriteHead = res.writeHead.bind(res);
376
+ res.writeHead = (...args) => {
377
+ if (res.statusCode < 400 && !res.getHeader("Cache-Control")) {
378
+ res.setHeader("Cache-Control", headerValue);
379
+ }
380
+ return origWriteHead(...args);
381
+ };
366
382
  next();
367
383
  };
368
384
  }
369
385
 
370
386
  // src/rate-limit-core.ts
387
+ var DEFAULT_MAX_KEYS = 1e4;
388
+ function extractForwardedIp(forwardedFor, realIp) {
389
+ const firstForwarded = forwardedFor?.split(",").map((part) => part.trim()).find((part) => part.length > 0);
390
+ if (firstForwarded) return firstForwarded;
391
+ const trimmedRealIp = realIp?.trim();
392
+ return trimmedRealIp || void 0;
393
+ }
371
394
  var RateLimiter = class {
372
- constructor(windowMs, max) {
395
+ constructor(windowMs, max, maxKeys = DEFAULT_MAX_KEYS) {
373
396
  this.windowMs = windowMs;
374
397
  this.max = max;
398
+ this.maxKeys = maxKeys;
375
399
  }
376
400
  windowMs;
377
401
  max;
402
+ maxKeys;
378
403
  buckets = /* @__PURE__ */ new Map();
379
404
  checksSinceSweep = 0;
380
405
  check(key, now = Date.now()) {
381
406
  this.maybeSweep(now);
382
407
  let bucket = this.buckets.get(key);
383
408
  if (!bucket || bucket.resetAt <= now) {
409
+ if (!bucket && this.buckets.size >= this.maxKeys) {
410
+ this.sweepExpired(now);
411
+ if (this.buckets.size >= this.maxKeys) {
412
+ const oldestKey = this.buckets.keys().next().value;
413
+ if (oldestKey !== void 0) this.buckets.delete(oldestKey);
414
+ }
415
+ }
384
416
  bucket = { count: 0, resetAt: now + this.windowMs };
385
417
  this.buckets.set(key, bucket);
386
418
  }
@@ -395,6 +427,9 @@ var RateLimiter = class {
395
427
  this.checksSinceSweep += 1;
396
428
  if (this.checksSinceSweep < 1e3) return;
397
429
  this.checksSinceSweep = 0;
430
+ this.sweepExpired(now);
431
+ }
432
+ sweepExpired(now) {
398
433
  for (const [key, bucket] of this.buckets) {
399
434
  if (bucket.resetAt <= now) this.buckets.delete(key);
400
435
  }
@@ -406,7 +441,8 @@ var DEFAULT_WINDOW_MS = 6e4;
406
441
  var DEFAULT_MAX = 60;
407
442
  function rateLimit(options = {}) {
408
443
  const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
409
- const keyGenerator = options.keyGenerator ?? defaultKey;
444
+ const trustProxy = options.trustProxy ?? false;
445
+ const keyGenerator = options.keyGenerator ?? ((req) => defaultKey(req, trustProxy));
410
446
  return function rateLimitMiddleware(req, res, next) {
411
447
  const result = limiter.check(keyGenerator(req));
412
448
  if (!result.allowed) {
@@ -417,8 +453,12 @@ function rateLimit(options = {}) {
417
453
  next();
418
454
  };
419
455
  }
420
- function defaultKey(req) {
421
- return req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? req.ip ?? "unknown";
456
+ function defaultKey(req, trustProxy) {
457
+ if (trustProxy) {
458
+ const forwarded = extractForwardedIp(req.header("x-forwarded-for"), req.header("x-real-ip"));
459
+ if (forwarded) return forwarded;
460
+ }
461
+ return req.ip || "unknown";
422
462
  }
423
463
 
424
464
  // src/express/router.ts
@@ -536,12 +576,18 @@ function buildOpenApiDocument(routes, options) {
536
576
  paths
537
577
  };
538
578
  }
579
+ function escapeHtml(value) {
580
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
581
+ }
582
+ function serializeInlineJson(value) {
583
+ return JSON.stringify(value).replace(/</g, "\\u003c");
584
+ }
539
585
  function pageShell(title, config) {
540
586
  const fullConfig = { showDeveloperTools: "never", ...config };
541
587
  return `<!doctype html>
542
588
  <html>
543
589
  <head>
544
- <title>${title}</title>
590
+ <title>${escapeHtml(title)}</title>
545
591
  <meta charset="utf-8" />
546
592
  <meta name="viewport" content="width=device-width, initial-scale=1" />
547
593
  </head>
@@ -549,7 +595,7 @@ function pageShell(title, config) {
549
595
  <div id="api-reference"></div>
550
596
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
551
597
  <script>
552
- Scalar.createApiReference("#api-reference", ${JSON.stringify(fullConfig)});
598
+ Scalar.createApiReference("#api-reference", ${serializeInlineJson(fullConfig)});
553
599
  </script>
554
600
  </body>
555
601
  </html>
@@ -568,11 +614,13 @@ function generateOpenApiSpec(app, options = {}) {
568
614
  return buildOpenApiDocument(routes, options);
569
615
  }
570
616
  function serveApiDocs(app, path = "/docs", options = {}) {
571
- const specPath = `${path}/openapi.json`;
617
+ const basePath = path === "/" ? "" : path.replace(/\/+$/, "");
618
+ const docPath = basePath || "/";
619
+ const specPath = `${basePath}/openapi.json`;
572
620
  const spec = generateOpenApiSpec(app, options);
573
621
  const html = apiReferenceHtmlInline(spec, options.title);
574
622
  app.get(specPath, (_req, res) => res.json(spec));
575
- app.get(path, (_req, res) => res.type("html").send(html));
623
+ app.get(docPath, (_req, res) => res.type("html").send(html));
576
624
  }
577
625
  export {
578
626
  AppError,
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/express/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,iBAAiB,CAAC;AAGzB;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGvG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAM7F"}
1
+ {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/express/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,iBAAiB,CAAC;AAGzB;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGvG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAQ7F"}
@@ -4,6 +4,12 @@ export interface RateLimitOptions {
4
4
  windowMs?: number;
5
5
  /** Max requests allowed per key within the window. Defaults to 60. */
6
6
  max?: number;
7
+ /**
8
+ * Trust `X-Forwarded-For` / `X-Real-IP` headers when deriving the default key.
9
+ * Off by default because untrusted clients can spoof those headers; enable
10
+ * only when running behind a reverse proxy that sets/overwrites them.
11
+ */
12
+ trustProxy?: boolean;
7
13
  /** How to derive the bucket key from a request. Defaults to the caller's IP. */
8
14
  keyGenerator?: (req: Request) => string;
9
15
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../../src/express/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAI/D,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CAAC;CACzC;AAKD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,SAIb,OAAO,OAAO,QAAQ,QAAQ,YAAY,UASpF"}
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../../src/express/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAI/D,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CAAC;CACzC;AAKD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,SAKb,OAAO,OAAO,QAAQ,QAAQ,YAAY,UASpF"}
@@ -1 +1 @@
1
- {"version":3,"file":"router-registry.d.ts","sourceRoot":"","sources":["../../src/express/router-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,MAAM,UAAU,GAClB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,GACjE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,aAAa,CAAA;CAAE,CAAC;AAE7D,MAAM,WAAW,aAAa;IAC5B,eAAe,EAAE,UAAU,EAAE,CAAC;CAC/B;AAYD,oHAAoH;AACpH,wBAAgB,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,aAAa,CAmC1E;AAOD,sHAAsH;AACtH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,aAAa,EACnB,MAAM,SAAK,GACV,KAAK,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CAU3D"}
1
+ {"version":3,"file":"router-registry.d.ts","sourceRoot":"","sources":["../../src/express/router-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,MAAM,UAAU,GAClB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,GACjE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,aAAa,CAAA;CAAE,CAAC;AAE7D,MAAM,WAAW,aAAa;IAC5B,eAAe,EAAE,UAAU,EAAE,CAAC;CAC/B;AAYD,oHAAoH;AACpH,wBAAgB,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,aAAa,CAuC1E;AAOD,sHAAsH;AACtH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,aAAa,EACnB,MAAM,SAAK,GACV,KAAK,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CAU3D"}
package/dist/index.js CHANGED
@@ -49,7 +49,7 @@ var DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024;
49
49
  function resolveAllowedOrigins(options) {
50
50
  if (options.allowedOrigins) return options.allowedOrigins;
51
51
  const fromEnv = process.env.ALLOWED_ORIGINS;
52
- return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
52
+ return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()).filter(Boolean) : [];
53
53
  }
54
54
  function createApp(options = {}) {
55
55
  const app = new Hono();
@@ -63,13 +63,18 @@ function createApp(options = {}) {
63
63
  })
64
64
  );
65
65
  app.use("*", compress());
66
- app.use(
67
- "*",
68
- bodyLimit({
69
- maxSize: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES,
70
- onError: (c) => c.json({ error: { code: "payload_too_large", message: "Request body too large" } }, 413)
71
- })
72
- );
66
+ const jsonBodyLimit = bodyLimit({
67
+ maxSize: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES,
68
+ onError: (c) => c.json({ error: { code: "payload_too_large", message: "Request body too large" } }, 413)
69
+ });
70
+ app.use("*", async (c, next) => {
71
+ const contentType = c.req.header("content-type")?.toLowerCase() ?? "";
72
+ if (contentType.startsWith("multipart/form-data")) {
73
+ await next();
74
+ return;
75
+ }
76
+ return jsonBodyLimit(c, next);
77
+ });
73
78
  app.get("/health", (c) => c.json({ status: "ok" }));
74
79
  app.onError((err, c) => {
75
80
  if (err instanceof AppError) {
@@ -86,21 +91,43 @@ function createApp(options = {}) {
86
91
  }
87
92
 
88
93
  // src/serve.ts
89
- async function serve(app, port = Number(process.env.PORT) || 3e3) {
90
- const isBun = typeof Bun !== "undefined";
91
- const server = isBun ? await serveOnBun(app, port) : await serveOnNode(app, port);
92
- logger.info({ port, runtime: isBun ? "bun" : "node" }, "backon app listening");
94
+ function resolveBoundPort(server, fallback) {
95
+ if (typeof server.port === "number") return server.port;
96
+ const addr = server.address?.();
97
+ if (addr && typeof addr === "object" && typeof addr.port === "number") return addr.port;
98
+ return fallback;
99
+ }
100
+ async function closeServerGracefully(server) {
101
+ if (server.stop) {
102
+ await server.stop(false);
103
+ return;
104
+ }
105
+ if (server.close) {
106
+ await new Promise((resolve) => {
107
+ server.close(() => resolve());
108
+ });
109
+ }
110
+ }
111
+ function createShutdownHandler(server, exit = (code) => process.exit(code)) {
93
112
  let shuttingDown = false;
94
- const shutdown = (signal) => {
113
+ return async (signal) => {
95
114
  if (shuttingDown) return;
96
115
  shuttingDown = true;
97
116
  logger.info({ signal }, "shutting down");
98
- server.stop?.();
99
- server.close?.();
100
- process.exit(0);
117
+ await closeServerGracefully(server);
118
+ exit(0);
101
119
  };
102
- process.on("SIGTERM", () => shutdown("SIGTERM"));
103
- process.on("SIGINT", () => shutdown("SIGINT"));
120
+ }
121
+ async function serve(app, port = Number(process.env.PORT) || 3e3) {
122
+ const isBun = typeof Bun !== "undefined";
123
+ const server = isBun ? await serveOnBun(app, port) : await serveOnNode(app, port);
124
+ const boundPort = resolveBoundPort(server, port);
125
+ logger.info({ port: boundPort, runtime: isBun ? "bun" : "node" }, "backon app listening");
126
+ const shutdown = createShutdownHandler(server);
127
+ const onSigterm = () => void shutdown("SIGTERM");
128
+ const onSigint = () => void shutdown("SIGINT");
129
+ process.once("SIGTERM", onSigterm);
130
+ process.once("SIGINT", onSigint);
104
131
  return server;
105
132
  }
106
133
  async function serveOnBun(app, port) {
@@ -129,7 +156,17 @@ function defineRoute(schema, handler) {
129
156
  if (schema.body) {
130
157
  const contentLength = c.req.header("content-length");
131
158
  const hasBody = c.req.raw.body !== null && contentLength !== "0";
132
- const raw = hasBody ? await c.req.json().catch(() => ({})) : {};
159
+ let raw = {};
160
+ if (hasBody) {
161
+ const text = await c.req.text();
162
+ if (text.length > 0) {
163
+ try {
164
+ raw = JSON.parse(text);
165
+ } catch {
166
+ throw new AppError(400, "invalid_body", "Invalid JSON request body");
167
+ }
168
+ }
169
+ }
133
170
  const parsed = schema.body.safeParse(raw);
134
171
  if (!parsed.success) {
135
172
  throw new AppError(400, "invalid_body", "Request body failed validation", z.flattenError(parsed.error));
@@ -182,9 +219,8 @@ function verifyJwt(token, options) {
182
219
  }
183
220
  function extractBearerToken(header) {
184
221
  if (!header) return void 0;
185
- const [scheme, token] = header.split(" ");
186
- if (scheme?.toLowerCase() !== "bearer" || !token) return void 0;
187
- return token;
222
+ const match = header.trim().match(/^Bearer\s+(\S+)$/i);
223
+ return match ? match[1] : void 0;
188
224
  }
189
225
  function parseCookieHeader(cookieHeader, name) {
190
226
  if (!cookieHeader) return void 0;
@@ -280,26 +316,42 @@ function cacheControl(options) {
280
316
  const headerValue = buildCacheControlHeader(options);
281
317
  return async function cacheControlMiddleware(c, next) {
282
318
  await next();
283
- if (!c.res.headers.has("cache-control")) {
319
+ if (c.res.status < 400 && !c.res.headers.has("cache-control")) {
284
320
  c.header("Cache-Control", headerValue);
285
321
  }
286
322
  };
287
323
  }
288
324
 
289
325
  // src/rate-limit-core.ts
326
+ var DEFAULT_MAX_KEYS = 1e4;
327
+ function extractForwardedIp(forwardedFor, realIp) {
328
+ const firstForwarded = forwardedFor?.split(",").map((part) => part.trim()).find((part) => part.length > 0);
329
+ if (firstForwarded) return firstForwarded;
330
+ const trimmedRealIp = realIp?.trim();
331
+ return trimmedRealIp || void 0;
332
+ }
290
333
  var RateLimiter = class {
291
- constructor(windowMs, max) {
334
+ constructor(windowMs, max, maxKeys = DEFAULT_MAX_KEYS) {
292
335
  this.windowMs = windowMs;
293
336
  this.max = max;
337
+ this.maxKeys = maxKeys;
294
338
  }
295
339
  windowMs;
296
340
  max;
341
+ maxKeys;
297
342
  buckets = /* @__PURE__ */ new Map();
298
343
  checksSinceSweep = 0;
299
344
  check(key, now = Date.now()) {
300
345
  this.maybeSweep(now);
301
346
  let bucket = this.buckets.get(key);
302
347
  if (!bucket || bucket.resetAt <= now) {
348
+ if (!bucket && this.buckets.size >= this.maxKeys) {
349
+ this.sweepExpired(now);
350
+ if (this.buckets.size >= this.maxKeys) {
351
+ const oldestKey = this.buckets.keys().next().value;
352
+ if (oldestKey !== void 0) this.buckets.delete(oldestKey);
353
+ }
354
+ }
303
355
  bucket = { count: 0, resetAt: now + this.windowMs };
304
356
  this.buckets.set(key, bucket);
305
357
  }
@@ -314,6 +366,9 @@ var RateLimiter = class {
314
366
  this.checksSinceSweep += 1;
315
367
  if (this.checksSinceSweep < 1e3) return;
316
368
  this.checksSinceSweep = 0;
369
+ this.sweepExpired(now);
370
+ }
371
+ sweepExpired(now) {
317
372
  for (const [key, bucket] of this.buckets) {
318
373
  if (bucket.resetAt <= now) this.buckets.delete(key);
319
374
  }
@@ -325,7 +380,8 @@ var DEFAULT_WINDOW_MS = 6e4;
325
380
  var DEFAULT_MAX = 60;
326
381
  function rateLimit(options = {}) {
327
382
  const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
328
- const keyGenerator = options.keyGenerator ?? defaultKey;
383
+ const trustProxy = options.trustProxy ?? false;
384
+ const keyGenerator = options.keyGenerator ?? ((c) => defaultKey(c, trustProxy));
329
385
  return async function rateLimitMiddleware(c, next) {
330
386
  const result = limiter.check(keyGenerator(c));
331
387
  if (!result.allowed) {
@@ -337,8 +393,12 @@ function rateLimit(options = {}) {
337
393
  await next();
338
394
  };
339
395
  }
340
- function defaultKey(c) {
341
- return c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? c.req.header("x-real-ip") ?? "unknown";
396
+ function defaultKey(c, trustProxy) {
397
+ if (trustProxy) {
398
+ const forwarded = extractForwardedIp(c.req.header("x-forwarded-for"), c.req.header("x-real-ip"));
399
+ if (forwarded) return forwarded;
400
+ }
401
+ return "unknown";
342
402
  }
343
403
 
344
404
  // src/websocket.ts
@@ -459,12 +519,18 @@ function buildOpenApiDocument(routes, options) {
459
519
  paths
460
520
  };
461
521
  }
522
+ function escapeHtml(value) {
523
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
524
+ }
525
+ function serializeInlineJson(value) {
526
+ return JSON.stringify(value).replace(/</g, "\\u003c");
527
+ }
462
528
  function pageShell(title, config) {
463
529
  const fullConfig = { showDeveloperTools: "never", ...config };
464
530
  return `<!doctype html>
465
531
  <html>
466
532
  <head>
467
- <title>${title}</title>
533
+ <title>${escapeHtml(title)}</title>
468
534
  <meta charset="utf-8" />
469
535
  <meta name="viewport" content="width=device-width, initial-scale=1" />
470
536
  </head>
@@ -472,7 +538,7 @@ function pageShell(title, config) {
472
538
  <div id="api-reference"></div>
473
539
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
474
540
  <script>
475
- Scalar.createApiReference("#api-reference", ${JSON.stringify(fullConfig)});
541
+ Scalar.createApiReference("#api-reference", ${serializeInlineJson(fullConfig)});
476
542
  </script>
477
543
  </body>
478
544
  </html>
@@ -496,12 +562,14 @@ function generateOpenApiSpec(app, options = {}) {
496
562
  return buildOpenApiDocument(routes, options);
497
563
  }
498
564
  function serveApiDocs(app, path = "/docs", options = {}) {
499
- const specPath = `${path}/openapi.json`;
565
+ const basePath = path === "/" ? "" : path.replace(/\/+$/, "");
566
+ const docPath = basePath || "/";
567
+ const specPath = `${basePath}/openapi.json`;
500
568
  const spec = generateOpenApiSpec(app, options);
501
569
  const specJson = JSON.stringify(spec);
502
570
  const html = apiReferenceHtmlInline(spec, options.title);
503
571
  app.get(specPath, (c) => c.body(specJson, 200, { "Content-Type": "application/json; charset=UTF-8" }));
504
- app.get(path, (c) => c.html(html));
572
+ app.get(docPath, (c) => c.html(html));
505
573
  }
506
574
 
507
575
  // src/index.ts
@@ -1 +1 @@
1
- {"version":3,"file":"openapi-core.d.ts","sourceRoot":"","sources":["../src/openapi-core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAK,KAAK,OAAO,EAAE,MAAM,KAAK,CAAC;AAEtC,MAAM,WAAW,cAAc;IAC7B,yBAAyB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2BAA2B;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACxB,KAAK,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACzB,MAAM,CAAC,EAAE,OAAO,CA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1B;AAED,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AAgDD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAmB/G;AAwCD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,SAAkB,GAAG,MAAM,CAEjF;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,SAAkB,GAAG,MAAM,CAErG"}
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../src/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAgD,KAAK,cAAc,EAAuB,MAAM,gBAAgB,CAAC;AAGxH,YAAY,EAAE,cAAc,EAAE,CAAC;AAI/B;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUzG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAO/F"}
1
+ {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../src/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAgD,KAAK,cAAc,EAAuB,MAAM,gBAAgB,CAAC;AAGxH,YAAY,EAAE,cAAc,EAAE,CAAC;AAI/B;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUzG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAS/F"}
@@ -14,14 +14,18 @@ export interface RateLimitCheckResult {
14
14
  /** Milliseconds until this key's window resets. Only meaningful when allowed is false. */
15
15
  retryAfterMs: number;
16
16
  }
17
+ /** Extracts the leftmost non-empty client IP from proxy headers, ignoring blank values. */
18
+ export declare function extractForwardedIp(forwardedFor: string | undefined, realIp: string | undefined): string | undefined;
17
19
  export declare class RateLimiter {
18
20
  private readonly windowMs;
19
21
  private readonly max;
22
+ private readonly maxKeys;
20
23
  private readonly buckets;
21
24
  private checksSinceSweep;
22
- constructor(windowMs: number, max: number);
25
+ constructor(windowMs: number, max: number, maxKeys?: number);
23
26
  check(key: string, now?: number): RateLimitCheckResult;
24
27
  /** Opportunistic cleanup so long-lived processes don't accumulate one bucket per distinct key forever. */
25
28
  private maybeSweep;
29
+ private sweepExpired;
26
30
  }
27
31
  //# sourceMappingURL=rate-limit-core.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limit-core.d.ts","sourceRoot":"","sources":["../src/rate-limit-core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,0FAA0F;IAC1F,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,qBAAa,WAAW;IAKpB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,GAAG;IALtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IACrD,OAAO,CAAC,gBAAgB,CAAK;IAE7B,YACmB,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EAC1B;IAEJ,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAmB,GAAG,oBAAoB,CAejE;IAED,0GAA0G;IAC1G,OAAO,CAAC,UAAU;CASnB"}
1
+ {"version":3,"file":"rate-limit-core.d.ts","sourceRoot":"","sources":["../src/rate-limit-core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,0FAA0F;IAC1F,YAAY,EAAE,MAAM,CAAC;CACtB;AAID,2FAA2F;AAC3F,wBAAgB,kBAAkB,CAChC,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,MAAM,EAAE,MAAM,GAAG,SAAS,GACzB,MAAM,GAAG,SAAS,CAQpB;AAED,qBAAa,WAAW;IAKpB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAN1B,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IACrD,OAAO,CAAC,gBAAgB,CAAK;IAE7B,YACmB,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,MAAyB,EACjD;IAEJ,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAmB,GAAG,oBAAoB,CAuBjE;IAED,0GAA0G;IAC1G,OAAO,CAAC,UAAU;IAOlB,OAAO,CAAC,YAAY;CAKrB"}
@@ -5,6 +5,12 @@ export interface RateLimitOptions {
5
5
  windowMs?: number;
6
6
  /** Max requests allowed per key within the window. Defaults to 60. */
7
7
  max?: number;
8
+ /**
9
+ * Trust `X-Forwarded-For` / `X-Real-IP` headers when deriving the default key.
10
+ * Off by default because untrusted clients can spoof those headers; enable
11
+ * only when running behind a reverse proxy that sets/overwrites them.
12
+ */
13
+ trustProxy?: boolean;
8
14
  /** How to derive the bucket key from a request. Defaults to the caller's IP. */
9
15
  keyGenerator?: (c: Context<Env>) => string;
10
16
  }
@@ -1 +1 @@
1
- {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAInC,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC;CAC5C;AAKD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,OAIT,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,mBAUtE"}
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAInC,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC;CAC5C;AAKD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,OAKT,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,mBAUtE"}
package/dist/serve.d.ts CHANGED
@@ -2,9 +2,20 @@ import type { Hono } from "hono";
2
2
  import type { Env } from "./types";
3
3
  /** The bits of Bun's/`@hono/node-server`'s return value shutdown actually needs — not either library's real type, just the overlap. */
4
4
  interface StoppableServer {
5
- stop?: () => void;
5
+ stop?: (closeActiveConnections?: boolean) => void | Promise<void>;
6
6
  close?: (callback?: (err?: Error) => void) => void;
7
+ port?: number;
8
+ address?: () => {
9
+ port?: number;
10
+ } | string | null;
7
11
  }
12
+ /** Stops accepting new connections and waits for in-flight requests to complete. */
13
+ export declare function closeServerGracefully(server: StoppableServer): Promise<void>;
14
+ /**
15
+ * Creates a signal-safe shutdown handler that stops accepting new connections,
16
+ * waits for in-flight requests to finish, and then invokes `exit(0)`.
17
+ */
18
+ export declare function createShutdownHandler(server: StoppableServer, exit?: (code: number) => void): (signal: string) => Promise<void>;
8
19
  /**
9
20
  * Starts the app — `Bun.serve()` when running under Bun (the default, and
10
21
  * the faster of the two), `@hono/node-server`'s `serve()` when running
@@ -1 +1 @@
1
- {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,uIAAuI;AACvI,UAAU,eAAe;IACvB,IAAI,CAAC,EAAE,MAAM,IAAI,CAAC;IAClB,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,KAAK,IAAI,KAAK,IAAI,CAAC;CACpD;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,GAAE,MAAyC,4BAuB1F;AAWD,wBAAsB,UAAU,CAAC,GAAG,EAAE,IAAI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C,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAGvF;AAED,wBAAsB,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAWxF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mednours/backon",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Opinionated backend framework wrapper, Bun-first but Node-compatible. Wraps Hono (default) or Express (via @mednours/backon/express) with the same baked-in security, logging, and validation defaults.",
6
6
  "license": "MIT",
package/src/auth-core.ts CHANGED
@@ -61,9 +61,8 @@ export function verifyJwt(token: string, options: VerifyJwtOptions): Promise<JWT
61
61
  /** Pulls the token out of a `Bearer <token>` Authorization header, or undefined if it's missing/malformed. */
62
62
  export function extractBearerToken(header: string | undefined): string | undefined {
63
63
  if (!header) return undefined;
64
- const [scheme, token] = header.split(" ");
65
- if (scheme?.toLowerCase() !== "bearer" || !token) return undefined;
66
- return token;
64
+ const match = header.trim().match(/^Bearer\s+(\S+)$/i);
65
+ return match ? match[1] : undefined;
67
66
  }
68
67
 
69
68
  /** Parses one named cookie from a raw `Cookie` request header, decoding percent-encoding. */
@@ -11,7 +11,7 @@ export function cacheControl(options: CacheControlOptions) {
11
11
  const headerValue = buildCacheControlHeader(options);
12
12
  return async function cacheControlMiddleware(c: Context, next: Next) {
13
13
  await next();
14
- if (!c.res.headers.has("cache-control")) {
14
+ if (c.res.status < 400 && !c.res.headers.has("cache-control")) {
15
15
  c.header("Cache-Control", headerValue);
16
16
  }
17
17
  };
package/src/create-app.ts CHANGED
@@ -31,7 +31,7 @@ const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
31
31
  function resolveAllowedOrigins(options: CreateAppOptions): string[] {
32
32
  if (options.allowedOrigins) return options.allowedOrigins;
33
33
  const fromEnv = process.env.ALLOWED_ORIGINS;
34
- return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
34
+ return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()).filter(Boolean) : [];
35
35
  }
36
36
 
37
37
  /**
@@ -57,14 +57,21 @@ export function createApp(options: CreateAppOptions = {}) {
57
57
  })
58
58
  );
59
59
  app.use("*", compress());
60
- app.use(
61
- "*",
62
- bodyLimit({
63
- maxSize: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES,
64
- onError: (c) =>
65
- c.json({ error: { code: "payload_too_large", message: "Request body too large" } }, 413),
66
- })
67
- );
60
+ const jsonBodyLimit = bodyLimit({
61
+ maxSize: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES,
62
+ onError: (c) =>
63
+ c.json({ error: { code: "payload_too_large", message: "Request body too large" } }, 413),
64
+ });
65
+ app.use("*", async (c, next) => {
66
+ // Multipart uploads enforce their own maxFileSizeBytes inside defineUpload(),
67
+ // matching the Express adapter where express.json() only caps JSON bodies.
68
+ const contentType = c.req.header("content-type")?.toLowerCase() ?? "";
69
+ if (contentType.startsWith("multipart/form-data")) {
70
+ await next();
71
+ return;
72
+ }
73
+ return jsonBodyLimit(c, next);
74
+ });
68
75
 
69
76
  // Registered here, before createApp() returns, so it always gets the
70
77
  // middleware above (logging, secure headers, CORS, compression, body
@@ -55,7 +55,17 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
55
55
  if (schema.body) {
56
56
  const contentLength = c.req.header("content-length");
57
57
  const hasBody = c.req.raw.body !== null && contentLength !== "0";
58
- const raw = hasBody ? await c.req.json().catch(() => ({})) : {};
58
+ let raw: unknown = {};
59
+ if (hasBody) {
60
+ const text = await c.req.text();
61
+ if (text.length > 0) {
62
+ try {
63
+ raw = JSON.parse(text);
64
+ } catch {
65
+ throw new AppError(400, "invalid_body", "Invalid JSON request body");
66
+ }
67
+ }
68
+ }
59
69
  const parsed = schema.body.safeParse(raw);
60
70
  if (!parsed.success) {
61
71
  throw new AppError(400, "invalid_body", "Request body failed validation", z.flattenError(parsed.error));
@@ -10,9 +10,13 @@ export type { CacheControlOptions };
10
10
  export function cacheControl(options: CacheControlOptions) {
11
11
  const headerValue = buildCacheControlHeader(options);
12
12
  return function cacheControlMiddleware(_req: Request, res: Response, next: NextFunction): void {
13
- if (!res.getHeader("Cache-Control")) {
14
- res.setHeader("Cache-Control", headerValue);
15
- }
13
+ const origWriteHead = res.writeHead.bind(res) as (...args: unknown[]) => Response;
14
+ (res as unknown as { writeHead: (...args: unknown[]) => Response }).writeHead = (...args: unknown[]) => {
15
+ if (res.statusCode < 400 && !res.getHeader("Cache-Control")) {
16
+ res.setHeader("Cache-Control", headerValue);
17
+ }
18
+ return origWriteHead(...args);
19
+ };
16
20
  next();
17
21
  };
18
22
  }
@@ -24,7 +24,7 @@ const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
24
24
  function resolveAllowedOrigins(options: CreateAppOptions): string[] {
25
25
  if (options.allowedOrigins) return options.allowedOrigins;
26
26
  const fromEnv = process.env.ALLOWED_ORIGINS;
27
- return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
27
+ return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()).filter(Boolean) : [];
28
28
  }
29
29
 
30
30
  /**
@@ -84,7 +84,12 @@ export function createApp(options: CreateAppOptions = {}): Express {
84
84
  * 500 without leaking internals.
85
85
  */
86
86
  export function attachErrorHandler(app: Express): void {
87
- app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
87
+ app.use((err: unknown, _req: Request, res: Response, next: NextFunction) => {
88
+ if (res.headersSent) {
89
+ next(err);
90
+ return;
91
+ }
92
+
88
93
  if (err instanceof AppError) {
89
94
  logger.warn(
90
95
  { requestId: res.locals.requestId, code: err.code, details: err.details },
@@ -96,13 +101,16 @@ export function attachErrorHandler(app: Express): void {
96
101
  return;
97
102
  }
98
103
 
99
- const status =
100
- (err as { status?: number; statusCode?: number } | undefined)?.status ??
101
- (err as { statusCode?: number } | undefined)?.statusCode;
104
+ const errObj = err as { status?: number; statusCode?: number; type?: string } | undefined;
105
+ const status = errObj?.status ?? errObj?.statusCode;
102
106
  if (status === 413) {
103
107
  res.status(413).json({ error: { code: "payload_too_large", message: "Request body too large" } });
104
108
  return;
105
109
  }
110
+ if (status === 400 && errObj?.type === "entity.parse.failed") {
111
+ res.status(400).json({ error: { code: "invalid_body", message: "Invalid JSON request body" } });
112
+ return;
113
+ }
106
114
 
107
115
  logger.error({ requestId: res.locals.requestId, err }, "unhandled error");
108
116
  res.status(500).json({ error: { code: "internal_error", message: "Something went wrong" } });
@@ -29,9 +29,11 @@ export function generateOpenApiSpec(app: Express, options: OpenApiOptions = {}):
29
29
  * serveApiDocs(app, "/docs", { title: "My API" });
30
30
  */
31
31
  export function serveApiDocs(app: Express, path = "/docs", options: OpenApiOptions = {}): void {
32
- const specPath = `${path}/openapi.json`;
32
+ const basePath = path === "/" ? "" : path.replace(/\/+$/, "");
33
+ const docPath = basePath || "/";
34
+ const specPath = `${basePath}/openapi.json`;
33
35
  const spec = generateOpenApiSpec(app, options);
34
36
  const html = apiReferenceHtmlInline(spec, options.title);
35
37
  app.get(specPath, (_req, res) => res.json(spec));
36
- app.get(path, (_req, res) => res.type("html").send(html));
38
+ app.get(docPath, (_req, res) => res.type("html").send(html));
37
39
  }
@@ -1,12 +1,18 @@
1
1
  import type { Request, Response, NextFunction } from "express";
2
2
  import { AppError } from "../error";
3
- import { RateLimiter } from "../rate-limit-core";
3
+ import { extractForwardedIp, RateLimiter } from "../rate-limit-core";
4
4
 
5
5
  export interface RateLimitOptions {
6
6
  /** Window size in ms. Defaults to 60_000 (1 minute). */
7
7
  windowMs?: number;
8
8
  /** Max requests allowed per key within the window. Defaults to 60. */
9
9
  max?: number;
10
+ /**
11
+ * Trust `X-Forwarded-For` / `X-Real-IP` headers when deriving the default key.
12
+ * Off by default because untrusted clients can spoof those headers; enable
13
+ * only when running behind a reverse proxy that sets/overwrites them.
14
+ */
15
+ trustProxy?: boolean;
10
16
  /** How to derive the bucket key from a request. Defaults to the caller's IP. */
11
17
  keyGenerator?: (req: Request) => string;
12
18
  }
@@ -22,7 +28,8 @@ const DEFAULT_MAX = 60;
22
28
  */
23
29
  export function rateLimit(options: RateLimitOptions = {}) {
24
30
  const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
25
- const keyGenerator = options.keyGenerator ?? defaultKey;
31
+ const trustProxy = options.trustProxy ?? false;
32
+ const keyGenerator = options.keyGenerator ?? ((req) => defaultKey(req, trustProxy));
26
33
 
27
34
  return function rateLimitMiddleware(req: Request, res: Response, next: NextFunction) {
28
35
  const result = limiter.check(keyGenerator(req));
@@ -35,6 +42,10 @@ export function rateLimit(options: RateLimitOptions = {}) {
35
42
  };
36
43
  }
37
44
 
38
- function defaultKey(req: Request): string {
39
- return req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? req.ip ?? "unknown";
45
+ function defaultKey(req: Request, trustProxy: boolean): string {
46
+ if (trustProxy) {
47
+ const forwarded = extractForwardedIp(req.header("x-forwarded-for"), req.header("x-real-ip"));
48
+ if (forwarded) return forwarded;
49
+ }
50
+ return req.ip || "unknown";
40
51
  }
@@ -57,8 +57,12 @@ export function trackRoutes<T extends object>(target: T): T & TrackedRouter {
57
57
  if (typeof originalUse === "function") {
58
58
  const boundUse = originalUse.bind(tracked);
59
59
  (tracked as Record<string, unknown>).use = (...args: unknown[]) => {
60
- if (typeof args[0] === "string" && isTracked(args[1])) {
61
- tracked.__backonEntries.push({ type: "mount", prefix: args[0], target: args[1] });
60
+ const prefix = typeof args[0] === "string" ? args[0] : "";
61
+ const candidates = typeof args[0] === "string" ? args.slice(1) : args;
62
+ for (const candidate of candidates) {
63
+ if (isTracked(candidate)) {
64
+ tracked.__backonEntries.push({ type: "mount", prefix, target: candidate });
65
+ }
62
66
  }
63
67
  return boundUse(...args);
64
68
  };
@@ -100,6 +100,20 @@ export function buildOpenApiDocument(routes: CollectedRoute[], options: OpenApiO
100
100
  };
101
101
  }
102
102
 
103
+ function escapeHtml(value: string): string {
104
+ return value
105
+ .replace(/&/g, "&amp;")
106
+ .replace(/</g, "&lt;")
107
+ .replace(/>/g, "&gt;")
108
+ .replace(/"/g, "&quot;")
109
+ .replace(/'/g, "&#39;");
110
+ }
111
+
112
+ function serializeInlineJson(value: unknown): string {
113
+ // Escape "<" so strings like "</script>" inside title/description/schemas cannot break out of the script tag.
114
+ return JSON.stringify(value).replace(/</g, "\\u003c");
115
+ }
116
+
103
117
  function pageShell(title: string, config: Record<string, unknown>): string {
104
118
  // showDeveloperTools defaults to "localhost" in Scalar itself, which shows
105
119
  // a Configure/Share/Deploy toolbar above the reference — promotion for
@@ -109,7 +123,7 @@ function pageShell(title: string, config: Record<string, unknown>): string {
109
123
  return `<!doctype html>
110
124
  <html>
111
125
  <head>
112
- <title>${title}</title>
126
+ <title>${escapeHtml(title)}</title>
113
127
  <meta charset="utf-8" />
114
128
  <meta name="viewport" content="width=device-width, initial-scale=1" />
115
129
  </head>
@@ -117,7 +131,7 @@ function pageShell(title: string, config: Record<string, unknown>): string {
117
131
  <div id="api-reference"></div>
118
132
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
119
133
  <script>
120
- Scalar.createApiReference("#api-reference", ${JSON.stringify(fullConfig)});
134
+ Scalar.createApiReference("#api-reference", ${serializeInlineJson(fullConfig)});
121
135
  </script>
122
136
  </body>
123
137
  </html>
package/src/openapi.ts CHANGED
@@ -35,10 +35,12 @@ export function generateOpenApiSpec(app: Hono<any>, options: OpenApiOptions = {}
35
35
  * serveApiDocs(app, "/docs", { title: "My API" });
36
36
  */
37
37
  export function serveApiDocs(app: Hono<any>, path = "/docs", options: OpenApiOptions = {}): void {
38
- const specPath = `${path}/openapi.json`;
38
+ const basePath = path === "/" ? "" : path.replace(/\/+$/, "");
39
+ const docPath = basePath || "/";
40
+ const specPath = `${basePath}/openapi.json`;
39
41
  const spec = generateOpenApiSpec(app, options);
40
42
  const specJson = JSON.stringify(spec);
41
43
  const html = apiReferenceHtmlInline(spec, options.title);
42
44
  app.get(specPath, (c) => c.body(specJson, 200, { "Content-Type": "application/json; charset=UTF-8" }));
43
- app.get(path, (c) => c.html(html));
45
+ app.get(docPath, (c) => c.html(html));
44
46
  }
@@ -21,13 +21,30 @@ export interface RateLimitCheckResult {
21
21
  retryAfterMs: number;
22
22
  }
23
23
 
24
+ const DEFAULT_MAX_KEYS = 10_000;
25
+
26
+ /** Extracts the leftmost non-empty client IP from proxy headers, ignoring blank values. */
27
+ export function extractForwardedIp(
28
+ forwardedFor: string | undefined,
29
+ realIp: string | undefined
30
+ ): string | undefined {
31
+ const firstForwarded = forwardedFor
32
+ ?.split(",")
33
+ .map((part) => part.trim())
34
+ .find((part) => part.length > 0);
35
+ if (firstForwarded) return firstForwarded;
36
+ const trimmedRealIp = realIp?.trim();
37
+ return trimmedRealIp || undefined;
38
+ }
39
+
24
40
  export class RateLimiter {
25
41
  private readonly buckets = new Map<string, Bucket>();
26
42
  private checksSinceSweep = 0;
27
43
 
28
44
  constructor(
29
45
  private readonly windowMs: number,
30
- private readonly max: number
46
+ private readonly max: number,
47
+ private readonly maxKeys: number = DEFAULT_MAX_KEYS
31
48
  ) {}
32
49
 
33
50
  check(key: string, now: number = Date.now()): RateLimitCheckResult {
@@ -35,6 +52,14 @@ export class RateLimiter {
35
52
 
36
53
  let bucket = this.buckets.get(key);
37
54
  if (!bucket || bucket.resetAt <= now) {
55
+ if (!bucket && this.buckets.size >= this.maxKeys) {
56
+ this.sweepExpired(now);
57
+ // If still at capacity after sweeping expired entries, evict the oldest key to keep memory bounded.
58
+ if (this.buckets.size >= this.maxKeys) {
59
+ const oldestKey = this.buckets.keys().next().value;
60
+ if (oldestKey !== undefined) this.buckets.delete(oldestKey);
61
+ }
62
+ }
38
63
  bucket = { count: 0, resetAt: now + this.windowMs };
39
64
  this.buckets.set(key, bucket);
40
65
  }
@@ -52,7 +77,10 @@ export class RateLimiter {
52
77
  this.checksSinceSweep += 1;
53
78
  if (this.checksSinceSweep < 1000) return;
54
79
  this.checksSinceSweep = 0;
80
+ this.sweepExpired(now);
81
+ }
55
82
 
83
+ private sweepExpired(now: number): void {
56
84
  for (const [key, bucket] of this.buckets) {
57
85
  if (bucket.resetAt <= now) this.buckets.delete(key);
58
86
  }
package/src/rate-limit.ts CHANGED
@@ -1,13 +1,19 @@
1
1
  import type { Context, Next } from "hono";
2
2
  import type { Env } from "./types";
3
3
  import { AppError } from "./error";
4
- import { RateLimiter } from "./rate-limit-core";
4
+ import { extractForwardedIp, RateLimiter } from "./rate-limit-core";
5
5
 
6
6
  export interface RateLimitOptions {
7
7
  /** Window size in ms. Defaults to 60_000 (1 minute). */
8
8
  windowMs?: number;
9
9
  /** Max requests allowed per key within the window. Defaults to 60. */
10
10
  max?: number;
11
+ /**
12
+ * Trust `X-Forwarded-For` / `X-Real-IP` headers when deriving the default key.
13
+ * Off by default because untrusted clients can spoof those headers; enable
14
+ * only when running behind a reverse proxy that sets/overwrites them.
15
+ */
16
+ trustProxy?: boolean;
11
17
  /** How to derive the bucket key from a request. Defaults to the caller's IP. */
12
18
  keyGenerator?: (c: Context<Env>) => string;
13
19
  }
@@ -32,7 +38,8 @@ const DEFAULT_MAX = 60;
32
38
  */
33
39
  export function rateLimit(options: RateLimitOptions = {}) {
34
40
  const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
35
- const keyGenerator = options.keyGenerator ?? defaultKey;
41
+ const trustProxy = options.trustProxy ?? false;
42
+ const keyGenerator = options.keyGenerator ?? ((c) => defaultKey(c, trustProxy));
36
43
 
37
44
  return async function rateLimitMiddleware(c: Context<Env>, next: Next) {
38
45
  const result = limiter.check(keyGenerator(c));
@@ -46,8 +53,10 @@ export function rateLimit(options: RateLimitOptions = {}) {
46
53
  };
47
54
  }
48
55
 
49
- function defaultKey(c: Context<Env>): string {
50
- return (
51
- c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? c.req.header("x-real-ip") ?? "unknown"
52
- );
56
+ function defaultKey(c: Context<Env>, trustProxy: boolean): string {
57
+ if (trustProxy) {
58
+ const forwarded = extractForwardedIp(c.req.header("x-forwarded-for"), c.req.header("x-real-ip"));
59
+ if (forwarded) return forwarded;
60
+ }
61
+ return "unknown";
53
62
  }
package/src/serve.ts CHANGED
@@ -4,8 +4,48 @@ import type { Env } from "./types";
4
4
 
5
5
  /** The bits of Bun's/`@hono/node-server`'s return value shutdown actually needs — not either library's real type, just the overlap. */
6
6
  interface StoppableServer {
7
- stop?: () => void;
7
+ stop?: (closeActiveConnections?: boolean) => void | Promise<void>;
8
8
  close?: (callback?: (err?: Error) => void) => void;
9
+ port?: number;
10
+ address?: () => { port?: number } | string | null;
11
+ }
12
+
13
+ function resolveBoundPort(server: StoppableServer, fallback: number): number {
14
+ if (typeof server.port === "number") return server.port;
15
+ const addr = server.address?.();
16
+ if (addr && typeof addr === "object" && typeof addr.port === "number") return addr.port;
17
+ return fallback;
18
+ }
19
+
20
+ /** Stops accepting new connections and waits for in-flight requests to complete. */
21
+ export async function closeServerGracefully(server: StoppableServer): Promise<void> {
22
+ if (server.stop) {
23
+ await server.stop(false);
24
+ return;
25
+ }
26
+ if (server.close) {
27
+ await new Promise<void>((resolve) => {
28
+ server.close!(() => resolve());
29
+ });
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Creates a signal-safe shutdown handler that stops accepting new connections,
35
+ * waits for in-flight requests to finish, and then invokes `exit(0)`.
36
+ */
37
+ export function createShutdownHandler(
38
+ server: StoppableServer,
39
+ exit: (code: number) => void = (code) => process.exit(code)
40
+ ): (signal: string) => Promise<void> {
41
+ let shuttingDown = false;
42
+ return async (signal: string) => {
43
+ if (shuttingDown) return;
44
+ shuttingDown = true;
45
+ logger.info({ signal }, "shutting down");
46
+ await closeServerGracefully(server);
47
+ exit(0);
48
+ };
9
49
  }
10
50
 
11
51
  /**
@@ -34,23 +74,15 @@ export async function serve(app: Hono<Env>, port: number = Number(process.env.PO
34
74
  const isBun = typeof Bun !== "undefined";
35
75
  const server: StoppableServer = isBun ? await serveOnBun(app, port) : await serveOnNode(app, port);
36
76
 
37
- logger.info({ port, runtime: isBun ? "bun" : "node" }, "backon app listening");
77
+ const boundPort = resolveBoundPort(server, port);
78
+ logger.info({ port: boundPort, runtime: isBun ? "bun" : "node" }, "backon app listening");
38
79
 
39
- let shuttingDown = false;
40
- const shutdown = (signal: string) => {
41
- if (shuttingDown) return;
42
- shuttingDown = true;
43
- logger.info({ signal }, "shutting down");
44
- // Bun.serve()'s stop() and @hono/node-server's close() are both
45
- // "stop accepting new connections, let in-flight ones finish" — same
46
- // intent, different method name depending which one is present.
47
- server.stop?.();
48
- server.close?.();
49
- process.exit(0);
50
- };
80
+ const shutdown = createShutdownHandler(server);
81
+ const onSigterm = () => void shutdown("SIGTERM");
82
+ const onSigint = () => void shutdown("SIGINT");
51
83
 
52
- process.on("SIGTERM", () => shutdown("SIGTERM"));
53
- process.on("SIGINT", () => shutdown("SIGINT"));
84
+ process.once("SIGTERM", onSigterm);
85
+ process.once("SIGINT", onSigint);
54
86
 
55
87
  return server;
56
88
  }