@mednours/backon 0.7.1 → 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.
Files changed (66) hide show
  1. package/dist/auth-core.d.ts +36 -5
  2. package/dist/auth-core.d.ts.map +1 -1
  3. package/dist/cache-control-core.d.ts +17 -0
  4. package/dist/cache-control-core.d.ts.map +1 -0
  5. package/dist/cache-control.d.ts +9 -0
  6. package/dist/cache-control.d.ts.map +1 -0
  7. package/dist/create-app.d.ts +8 -0
  8. package/dist/create-app.d.ts.map +1 -1
  9. package/dist/define-route.d.ts +1 -1
  10. package/dist/define-route.d.ts.map +1 -1
  11. package/dist/error.d.ts.map +1 -1
  12. package/dist/express/cache-control.d.ts +9 -0
  13. package/dist/express/cache-control.d.ts.map +1 -0
  14. package/dist/express/create-app.d.ts +5 -0
  15. package/dist/express/create-app.d.ts.map +1 -1
  16. package/dist/express/define-route.d.ts +1 -1
  17. package/dist/express/define-route.d.ts.map +1 -1
  18. package/dist/express/index.d.ts +4 -1
  19. package/dist/express/index.d.ts.map +1 -1
  20. package/dist/express/index.js +181 -32
  21. package/dist/express/openapi.d.ts.map +1 -1
  22. package/dist/express/rate-limit.d.ts +6 -0
  23. package/dist/express/rate-limit.d.ts.map +1 -1
  24. package/dist/express/require-auth.d.ts +2 -11
  25. package/dist/express/require-auth.d.ts.map +1 -1
  26. package/dist/express/router-registry.d.ts.map +1 -1
  27. package/dist/express/stream.d.ts.map +1 -1
  28. package/dist/express/upload.d.ts.map +1 -1
  29. package/dist/index.d.ts +5 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +216 -43
  32. package/dist/openapi-core.d.ts +1 -1
  33. package/dist/openapi-core.d.ts.map +1 -1
  34. package/dist/openapi.d.ts.map +1 -1
  35. package/dist/rate-limit-core.d.ts +5 -1
  36. package/dist/rate-limit-core.d.ts.map +1 -1
  37. package/dist/rate-limit.d.ts +6 -0
  38. package/dist/rate-limit.d.ts.map +1 -1
  39. package/dist/require-auth.d.ts +3 -14
  40. package/dist/require-auth.d.ts.map +1 -1
  41. package/dist/serve.d.ts +12 -1
  42. package/dist/serve.d.ts.map +1 -1
  43. package/dist/stream.d.ts.map +1 -1
  44. package/dist/upload.d.ts.map +1 -1
  45. package/dist/websocket.d.ts.map +1 -1
  46. package/package.json +13 -14
  47. package/src/auth-core.ts +108 -9
  48. package/src/cache-control-core.ts +32 -0
  49. package/src/cache-control.ts +18 -0
  50. package/src/create-app.ts +25 -9
  51. package/src/define-route.ts +17 -5
  52. package/src/express/cache-control.ts +22 -0
  53. package/src/express/create-app.ts +24 -6
  54. package/src/express/define-route.ts +4 -4
  55. package/src/express/index.ts +5 -1
  56. package/src/express/openapi.ts +7 -5
  57. package/src/express/rate-limit.ts +15 -4
  58. package/src/express/require-auth.ts +11 -14
  59. package/src/express/router-registry.ts +6 -2
  60. package/src/index.ts +6 -1
  61. package/src/openapi-core.ts +24 -7
  62. package/src/openapi.ts +8 -3
  63. package/src/rate-limit-core.ts +29 -1
  64. package/src/rate-limit.ts +15 -6
  65. package/src/require-auth.ts +10 -17
  66. package/src/serve.ts +48 -16
package/src/index.ts CHANGED
@@ -14,7 +14,11 @@ export { logger } from "./logger";
14
14
  export { requireEnv } from "./require-env";
15
15
 
16
16
  export { requireAuth } from "./require-auth";
17
- export type { VerifyJwtOptions } from "./auth-core";
17
+ export { signJwt } from "./auth-core";
18
+ export type { VerifyJwtOptions, SignJwtOptions } from "./auth-core";
19
+
20
+ export { cacheControl } from "./cache-control";
21
+ export type { CacheControlOptions } from "./cache-control";
18
22
 
19
23
  export { rateLimit } from "./rate-limit";
20
24
  export type { RateLimitOptions } from "./rate-limit";
@@ -42,3 +46,4 @@ export type { BackonContext, Env } from "./types";
42
46
  */
43
47
  export { Hono } from "hono";
44
48
  export type { Next } from "hono";
49
+ export { setCookie, getCookie, deleteCookie, setSignedCookie, getSignedCookie } from "hono/cookie";
@@ -1,5 +1,4 @@
1
- import { zodToJsonSchema } from "zod-to-json-schema";
2
- import type { ZodType } from "zod";
1
+ import { z, type ZodType } from "zod";
3
2
 
4
3
  export interface OpenApiOptions {
5
4
  /** Defaults to "API". */
@@ -32,12 +31,16 @@ function paramNames(path: string): string[] {
32
31
  .filter((name): name is string => name !== undefined);
33
32
  }
34
33
 
34
+ function toOpenApiSchema(schema: ZodType<unknown>): Record<string, unknown> {
35
+ return z.toJSONSchema(schema, { target: "openapi-3.0", unrepresentable: "any" }) as Record<string, unknown>;
36
+ }
37
+
35
38
  function buildOperation(path: string, schema: RouteSchemaLike): Record<string, unknown> {
36
39
  const operation: Record<string, unknown> = { responses: { "200": { description: "Success" } } };
37
40
  const parameters: unknown[] = [];
38
41
 
39
42
  if (schema.params) {
40
- const jsonSchema = zodToJsonSchema(schema.params, { target: "openApi3" }) as Record<string, any>;
43
+ const jsonSchema = toOpenApiSchema(schema.params) as Record<string, any>;
41
44
  for (const name of paramNames(path)) {
42
45
  parameters.push({
43
46
  name,
@@ -49,7 +52,7 @@ function buildOperation(path: string, schema: RouteSchemaLike): Record<string, u
49
52
  }
50
53
 
51
54
  if (schema.query) {
52
- const jsonSchema = zodToJsonSchema(schema.query, { target: "openApi3" }) as Record<string, any>;
55
+ const jsonSchema = toOpenApiSchema(schema.query) as Record<string, any>;
53
56
  const required = new Set(jsonSchema.required ?? []);
54
57
  for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
55
58
  parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
@@ -61,7 +64,7 @@ function buildOperation(path: string, schema: RouteSchemaLike): Record<string, u
61
64
  if (schema.body) {
62
65
  operation.requestBody = {
63
66
  required: true,
64
- content: { "application/json": { schema: zodToJsonSchema(schema.body, { target: "openApi3" }) } },
67
+ content: { "application/json": { schema: toOpenApiSchema(schema.body) } },
65
68
  };
66
69
  }
67
70
 
@@ -97,6 +100,20 @@ export function buildOpenApiDocument(routes: CollectedRoute[], options: OpenApiO
97
100
  };
98
101
  }
99
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
+
100
117
  function pageShell(title: string, config: Record<string, unknown>): string {
101
118
  // showDeveloperTools defaults to "localhost" in Scalar itself, which shows
102
119
  // a Configure/Share/Deploy toolbar above the reference — promotion for
@@ -106,7 +123,7 @@ function pageShell(title: string, config: Record<string, unknown>): string {
106
123
  return `<!doctype html>
107
124
  <html>
108
125
  <head>
109
- <title>${title}</title>
126
+ <title>${escapeHtml(title)}</title>
110
127
  <meta charset="utf-8" />
111
128
  <meta name="viewport" content="width=device-width, initial-scale=1" />
112
129
  </head>
@@ -114,7 +131,7 @@ function pageShell(title: string, config: Record<string, unknown>): string {
114
131
  <div id="api-reference"></div>
115
132
  <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
116
133
  <script>
117
- Scalar.createApiReference("#api-reference", ${JSON.stringify(fullConfig)});
134
+ Scalar.createApiReference("#api-reference", ${serializeInlineJson(fullConfig)});
118
135
  </script>
119
136
  </body>
120
137
  </html>
package/src/openapi.ts CHANGED
@@ -35,7 +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`;
39
- app.get(specPath, (c) => c.json(generateOpenApiSpec(app, options)));
40
- app.get(path, (c) => c.html(apiReferenceHtmlInline(generateOpenApiSpec(app, options), options.title)));
38
+ const basePath = path === "/" ? "" : path.replace(/\/+$/, "");
39
+ const docPath = basePath || "/";
40
+ const specPath = `${basePath}/openapi.json`;
41
+ const spec = generateOpenApiSpec(app, options);
42
+ const specJson = JSON.stringify(spec);
43
+ const html = apiReferenceHtmlInline(spec, options.title);
44
+ app.get(specPath, (c) => c.body(specJson, 200, { "Content-Type": "application/json; charset=UTF-8" }));
45
+ app.get(docPath, (c) => c.html(html));
41
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
  }
@@ -1,29 +1,22 @@
1
1
  import type { Context, Next } from "hono";
2
2
  import type { Env } from "./types";
3
3
  import { AppError } from "./error";
4
- import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "./auth-core";
4
+ import { extractAuthToken, verifyJwt, type VerifyJwtOptions } from "./auth-core";
5
5
 
6
6
  /**
7
- * Verifies a bearer JWT and stashes the decoded payload on the context as
8
- * `auth`, retrievable in any handler downstream via `c.get("auth")`. Throws
9
- * AppError(401, "unauthorized") if the header is missing, malformed, or the
10
- * token fails verification (bad signature, expired, wrong algorithm) —
11
- * createApp()'s error handler turns that into the standard error JSON shape,
12
- * same as any other AppError.
13
- *
14
- * This is verification only: issuing tokens (login, signup, refresh
15
- * rotation, revocation) is left to the consuming project, since that's
16
- * genuinely different per project and baking in an opinion there risks
17
- * being wrong for whatever project actually uses it. Apply it per-route or
18
- * per-group, not globally:
19
- *
20
- * protectedRoutes.use("*", requireAuth({ secret: process.env.JWT_SECRET! }));
7
+ * Verifies a bearer (or optional cookie) JWT and stashes the decoded payload
8
+ * on the context as `auth`, retrievable in any handler downstream via
9
+ * `c.get("auth")`. Throws AppError(401, "unauthorized") if missing or invalid.
21
10
  */
22
11
  export function requireAuth(options: VerifyJwtOptions) {
23
12
  return async function requireAuthMiddleware(c: Context<Env>, next: Next) {
24
- const token = extractBearerToken(c.req.header("authorization"));
13
+ const token = await extractAuthToken(c.req.header("authorization"), c.req.header("cookie"), options);
25
14
  if (!token) {
26
- throw new AppError(401, "unauthorized", "Missing or malformed Authorization header");
15
+ throw new AppError(
16
+ 401,
17
+ "unauthorized",
18
+ options.cookieName ? "Missing authentication token" : "Missing or malformed Authorization header"
19
+ );
27
20
  }
28
21
 
29
22
  try {
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
  }