@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.
- package/dist/auth-core.d.ts +36 -5
- package/dist/auth-core.d.ts.map +1 -1
- package/dist/cache-control-core.d.ts +17 -0
- package/dist/cache-control-core.d.ts.map +1 -0
- package/dist/cache-control.d.ts +9 -0
- package/dist/cache-control.d.ts.map +1 -0
- package/dist/create-app.d.ts +8 -0
- package/dist/create-app.d.ts.map +1 -1
- package/dist/define-route.d.ts +1 -1
- package/dist/define-route.d.ts.map +1 -1
- package/dist/error.d.ts.map +1 -1
- package/dist/express/cache-control.d.ts +9 -0
- package/dist/express/cache-control.d.ts.map +1 -0
- package/dist/express/create-app.d.ts +5 -0
- package/dist/express/create-app.d.ts.map +1 -1
- package/dist/express/define-route.d.ts +1 -1
- package/dist/express/define-route.d.ts.map +1 -1
- package/dist/express/index.d.ts +4 -1
- package/dist/express/index.d.ts.map +1 -1
- package/dist/express/index.js +181 -32
- package/dist/express/openapi.d.ts.map +1 -1
- package/dist/express/rate-limit.d.ts +6 -0
- package/dist/express/rate-limit.d.ts.map +1 -1
- package/dist/express/require-auth.d.ts +2 -11
- package/dist/express/require-auth.d.ts.map +1 -1
- package/dist/express/router-registry.d.ts.map +1 -1
- package/dist/express/stream.d.ts.map +1 -1
- package/dist/express/upload.d.ts.map +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +216 -43
- package/dist/openapi-core.d.ts +1 -1
- package/dist/openapi-core.d.ts.map +1 -1
- package/dist/openapi.d.ts.map +1 -1
- package/dist/rate-limit-core.d.ts +5 -1
- package/dist/rate-limit-core.d.ts.map +1 -1
- package/dist/rate-limit.d.ts +6 -0
- package/dist/rate-limit.d.ts.map +1 -1
- package/dist/require-auth.d.ts +3 -14
- package/dist/require-auth.d.ts.map +1 -1
- package/dist/serve.d.ts +12 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/stream.d.ts.map +1 -1
- package/dist/upload.d.ts.map +1 -1
- package/dist/websocket.d.ts.map +1 -1
- package/package.json +13 -14
- package/src/auth-core.ts +108 -9
- package/src/cache-control-core.ts +32 -0
- package/src/cache-control.ts +18 -0
- package/src/create-app.ts +25 -9
- package/src/define-route.ts +17 -5
- package/src/express/cache-control.ts +22 -0
- package/src/express/create-app.ts +24 -6
- package/src/express/define-route.ts +4 -4
- package/src/express/index.ts +5 -1
- package/src/express/openapi.ts +7 -5
- package/src/express/rate-limit.ts +15 -4
- package/src/express/require-auth.ts +11 -14
- package/src/express/router-registry.ts +6 -2
- package/src/index.ts +6 -1
- package/src/openapi-core.ts +24 -7
- package/src/openapi.ts +8 -3
- package/src/rate-limit-core.ts +29 -1
- package/src/rate-limit.ts +15 -6
- package/src/require-auth.ts +10 -17
- 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
|
|
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";
|
package/src/openapi-core.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import {
|
|
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 =
|
|
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 =
|
|
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:
|
|
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, "&")
|
|
106
|
+
.replace(/</g, "<")
|
|
107
|
+
.replace(/>/g, ">")
|
|
108
|
+
.replace(/"/g, """)
|
|
109
|
+
.replace(/'/g, "'");
|
|
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", ${
|
|
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
|
|
39
|
-
|
|
40
|
-
|
|
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
|
}
|
package/src/rate-limit-core.ts
CHANGED
|
@@ -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
|
|
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
|
|
50
|
-
|
|
51
|
-
c.req.header("x-forwarded-for")
|
|
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/require-auth.ts
CHANGED
|
@@ -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 {
|
|
4
|
+
import { extractAuthToken, verifyJwt, type VerifyJwtOptions } from "./auth-core";
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
|
-
* Verifies a bearer JWT and stashes the decoded payload
|
|
8
|
-
* `auth`, retrievable in any handler downstream via
|
|
9
|
-
* AppError(401, "unauthorized") if
|
|
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 =
|
|
13
|
+
const token = await extractAuthToken(c.req.header("authorization"), c.req.header("cookie"), options);
|
|
25
14
|
if (!token) {
|
|
26
|
-
throw new AppError(
|
|
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
|
-
|
|
77
|
+
const boundPort = resolveBoundPort(server, port);
|
|
78
|
+
logger.info({ port: boundPort, runtime: isBun ? "bun" : "node" }, "backon app listening");
|
|
38
79
|
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
|
|
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.
|
|
53
|
-
process.
|
|
84
|
+
process.once("SIGTERM", onSigterm);
|
|
85
|
+
process.once("SIGINT", onSigint);
|
|
54
86
|
|
|
55
87
|
return server;
|
|
56
88
|
}
|