@mednours/backon 0.1.0 → 0.4.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/README.md +135 -3
- package/package.json +13 -4
- package/src/auth-core.ts +37 -0
- package/src/create-app.ts +7 -7
- package/src/define-route.ts +16 -4
- package/src/express/create-app.ts +15 -11
- package/src/express/define-route.ts +14 -2
- package/src/express/index.ts +28 -3
- package/src/express/openapi.ts +27 -0
- package/src/express/rate-limit.ts +40 -0
- package/src/express/require-auth.ts +35 -0
- package/src/express/router-registry.ts +89 -0
- package/src/express/router.ts +13 -0
- package/src/express/serve.ts +6 -2
- package/src/express/stream.ts +31 -0
- package/src/express/upload.ts +67 -0
- package/src/express/websocket.ts +47 -0
- package/src/index.ts +25 -4
- package/src/logger.ts +2 -2
- package/src/openapi-core.ts +115 -0
- package/src/openapi.ts +38 -0
- package/src/rate-limit-core.ts +60 -0
- package/src/rate-limit.ts +53 -0
- package/src/require-auth.ts +38 -0
- package/src/require-env.ts +31 -0
- package/src/serve.ts +6 -1
- package/src/stream.ts +26 -0
- package/src/types.ts +4 -1
- package/src/upload.ts +62 -0
- package/src/websocket.ts +28 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backs generateOpenApiSpec() on the Express adapter. Express's own router
|
|
3
|
+
* tree (app._router.stack) is undocumented, version-specific, and awkward
|
|
4
|
+
* to walk correctly through nested Router() mounts — reconstructing a
|
|
5
|
+
* mount's full path from its compiled matching regexp is lossy in general.
|
|
6
|
+
* Rather than reflect into that, backon's own Router() (exported from
|
|
7
|
+
* @mednours/backon/express instead of express directly) and createApp()'s
|
|
8
|
+
* returned app both get instrumented here: every get/post/put/patch/delete
|
|
9
|
+
* call records its own path, method, and schema (if any); every use(prefix,
|
|
10
|
+
* subRouter) call records the mount so the full path can be composed by
|
|
11
|
+
* simple string concatenation, not regexp decoding.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type MountEntry =
|
|
15
|
+
| { type: "route"; method: string; path: string; schema?: unknown }
|
|
16
|
+
| { type: "mount"; prefix: string; target: TrackedRouter };
|
|
17
|
+
|
|
18
|
+
export interface TrackedRouter {
|
|
19
|
+
__backonEntries: MountEntry[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const TRACKED_METHODS = ["get", "post", "put", "patch", "delete", "options", "head"] as const;
|
|
23
|
+
|
|
24
|
+
function isTracked(value: unknown): value is TrackedRouter {
|
|
25
|
+
// An Express app or Router() instance is itself a callable function, not
|
|
26
|
+
// a plain object — `typeof` on either is "function", so both need
|
|
27
|
+
// accepting here, not just "object".
|
|
28
|
+
if (value === null || (typeof value !== "object" && typeof value !== "function")) return false;
|
|
29
|
+
return Array.isArray((value as TrackedRouter).__backonEntries);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Wraps get/post/put/patch/delete/use on an Express app or Router, delegating to the real method in every case. */
|
|
33
|
+
export function trackRoutes<T extends object>(target: T): T & TrackedRouter {
|
|
34
|
+
if (isTracked(target)) return target;
|
|
35
|
+
|
|
36
|
+
const tracked = target as T & TrackedRouter;
|
|
37
|
+
tracked.__backonEntries = [];
|
|
38
|
+
|
|
39
|
+
for (const method of TRACKED_METHODS) {
|
|
40
|
+
const original = (tracked as Record<string, unknown>)[method];
|
|
41
|
+
if (typeof original !== "function") continue;
|
|
42
|
+
const boundOriginal = original.bind(tracked);
|
|
43
|
+
(tracked as Record<string, unknown>)[method] = (path: unknown, ...handlers: unknown[]) => {
|
|
44
|
+
// Express overloads .get() specifically: called with a single
|
|
45
|
+
// argument, it's a settings getter (`app.get('query parser fn')`),
|
|
46
|
+
// not a route — Express's own lazy router init calls it that way
|
|
47
|
+
// internally. Only handlers.length > 0 is ever a real registration.
|
|
48
|
+
if (typeof path === "string" && handlers.length > 0) {
|
|
49
|
+
const last = handlers[handlers.length - 1] as { __backonRouteSchema?: unknown } | undefined;
|
|
50
|
+
tracked.__backonEntries.push({ type: "route", method, path, schema: last?.__backonRouteSchema });
|
|
51
|
+
}
|
|
52
|
+
return boundOriginal(path, ...handlers);
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const originalUse = (tracked as Record<string, unknown>).use;
|
|
57
|
+
if (typeof originalUse === "function") {
|
|
58
|
+
const boundUse = originalUse.bind(tracked);
|
|
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] });
|
|
62
|
+
}
|
|
63
|
+
return boundUse(...args);
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return tracked;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function joinPaths(prefix: string, path: string): string {
|
|
71
|
+
const joined = `${prefix.replace(/\/$/, "")}/${path.replace(/^\//, "")}`;
|
|
72
|
+
return joined.replace(/\/+$/, "") || "/";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Recursively resolves every tracked route to its full path, following mount entries down through nested routers. */
|
|
76
|
+
export function collectRoutes(
|
|
77
|
+
root: TrackedRouter,
|
|
78
|
+
prefix = ""
|
|
79
|
+
): Array<{ method: string; path: string; schema?: unknown }> {
|
|
80
|
+
const results: Array<{ method: string; path: string; schema?: unknown }> = [];
|
|
81
|
+
for (const entry of root.__backonEntries) {
|
|
82
|
+
if (entry.type === "route") {
|
|
83
|
+
results.push({ method: entry.method, path: joinPaths(prefix, entry.path), schema: entry.schema });
|
|
84
|
+
} else {
|
|
85
|
+
results.push(...collectRoutes(entry.target, joinPaths(prefix, entry.prefix)));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return results;
|
|
89
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Router as expressRouter, type Router as ExpressRouterType } from "express";
|
|
2
|
+
import { trackRoutes, type TrackedRouter } from "./router-registry";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Same as Express's own Router() in every way that matters at runtime —
|
|
6
|
+
* this calls it directly — but instrumented so generateOpenApiSpec() can
|
|
7
|
+
* walk the route tree it produces. Exported from @mednours/backon/express
|
|
8
|
+
* instead of importing Router from 'express' directly is what makes that
|
|
9
|
+
* tracking possible; both behave identically otherwise.
|
|
10
|
+
*/
|
|
11
|
+
export function Router(...args: Parameters<typeof expressRouter>): ExpressRouterType & TrackedRouter {
|
|
12
|
+
return trackRoutes(expressRouter(...args));
|
|
13
|
+
}
|
package/src/express/serve.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Express } from "express";
|
|
2
2
|
import { attachErrorHandler } from "./create-app";
|
|
3
|
+
import { attachWebSockets } from "./websocket";
|
|
3
4
|
import { logger } from "../logger";
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -7,9 +8,11 @@ import { logger } from "../logger";
|
|
|
7
8
|
* wires graceful shutdown, same contract as the Hono adapter's serve().
|
|
8
9
|
*
|
|
9
10
|
* Also calls attachErrorHandler(app) first — see the note on createApp()
|
|
10
|
-
* for why that can't happen until every route is registered.
|
|
11
|
+
* for why that can't happen until every route is registered. When not
|
|
11
12
|
* using this serve() (e.g. exporting the app for a serverless platform or a
|
|
12
|
-
* supertest suite), call attachErrorHandler(app)
|
|
13
|
+
* supertest suite), call attachErrorHandler(app) directly instead — and, if
|
|
14
|
+
* any defineWebSocket() routes were registered, attachWebSockets(app,
|
|
15
|
+
* server) too, once a real http.Server exists.
|
|
13
16
|
*/
|
|
14
17
|
export function serve(app: Express, port: number = Number(process.env.PORT) || 3000) {
|
|
15
18
|
attachErrorHandler(app);
|
|
@@ -17,6 +20,7 @@ export function serve(app: Express, port: number = Number(process.env.PORT) || 3
|
|
|
17
20
|
const server = app.listen(port, () => {
|
|
18
21
|
logger.info({ port }, "backon app listening");
|
|
19
22
|
});
|
|
23
|
+
attachWebSockets(app, server);
|
|
20
24
|
|
|
21
25
|
let shuttingDown = false;
|
|
22
26
|
const shutdown = (signal: string) => {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import { createContext, type BackonContext } from "./types";
|
|
3
|
+
|
|
4
|
+
export type StreamWriter = (chunk: string | Uint8Array) => void;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Same contract as the Hono defineStream: the handler writes chunks as they
|
|
8
|
+
* become available instead of returning one body all at once. Underneath,
|
|
9
|
+
* this is just res.write() — Node's response object is a writable stream
|
|
10
|
+
* regardless of any framework sitting on top of it.
|
|
11
|
+
*
|
|
12
|
+
* app.get("/export", defineStream(async (c, write) => {
|
|
13
|
+
* for (const row of rows) write(JSON.stringify(row) + "\n");
|
|
14
|
+
* }));
|
|
15
|
+
*
|
|
16
|
+
* Set a Content-Type via c.header() before the first write() if the default
|
|
17
|
+
* (left to the browser/client to infer) isn't right for what's being sent.
|
|
18
|
+
*/
|
|
19
|
+
export function defineStream(handler: (c: BackonContext, write: StreamWriter) => Promise<void> | void) {
|
|
20
|
+
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
21
|
+
try {
|
|
22
|
+
const ctx = createContext(req, res);
|
|
23
|
+
await handler(ctx, (chunk) => {
|
|
24
|
+
res.write(chunk);
|
|
25
|
+
});
|
|
26
|
+
res.end();
|
|
27
|
+
} catch (err) {
|
|
28
|
+
next(err);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import multer, { type Multer } from "multer";
|
|
3
|
+
import { AppError } from "../error";
|
|
4
|
+
import { createContext, type BackonContext } from "./types";
|
|
5
|
+
|
|
6
|
+
/** Content-Type headers can carry parameters ("text/plain;charset=utf-8") — comparisons only care about the type itself. */
|
|
7
|
+
function baseMimeType(type: string): string {
|
|
8
|
+
return type.split(";")[0]?.trim() ?? type;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface UploadOptions {
|
|
12
|
+
/** Rejects any file over this size with a 400. Unset means no limit. */
|
|
13
|
+
maxFileSizeBytes?: number;
|
|
14
|
+
/** Rejects any file whose type isn't in this list with a 400. Unset means no restriction. */
|
|
15
|
+
allowedMimeTypes?: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type UploadHandler = (
|
|
19
|
+
c: BackonContext,
|
|
20
|
+
data: { files: Record<string, Express.Multer.File[]> }
|
|
21
|
+
) => unknown | Promise<unknown>;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Same contract as the Hono defineUpload: parses a multipart/form-data
|
|
25
|
+
* request, validates each file against maxFileSizeBytes/allowedMimeTypes,
|
|
26
|
+
* throws AppError(400, ...) on the first violation. Built on multer (kept
|
|
27
|
+
* in memory, not written to disk — same "handler decides what happens to
|
|
28
|
+
* the data" philosophy as everything else here) since Express has no
|
|
29
|
+
* built-in multipart parser the way Hono's c.req.parseBody() is.
|
|
30
|
+
*
|
|
31
|
+
* app.post("/avatar", defineUpload(
|
|
32
|
+
* { maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
|
|
33
|
+
* async (c, { files }) => c.json({ uploaded: files.avatar.length })
|
|
34
|
+
* ));
|
|
35
|
+
*/
|
|
36
|
+
export function defineUpload(options: UploadOptions, handler: UploadHandler) {
|
|
37
|
+
const upload: Multer = multer({
|
|
38
|
+
storage: multer.memoryStorage(),
|
|
39
|
+
limits: options.maxFileSizeBytes !== undefined ? { fileSize: options.maxFileSizeBytes } : undefined,
|
|
40
|
+
});
|
|
41
|
+
const parseMultipart = upload.any();
|
|
42
|
+
|
|
43
|
+
return (req: Request, res: Response, next: NextFunction): void => {
|
|
44
|
+
parseMultipart(req, res, async (err: unknown) => {
|
|
45
|
+
if (err) {
|
|
46
|
+
const code = (err as { code?: string }).code === "LIMIT_FILE_SIZE" ? "file_too_large" : "invalid_upload";
|
|
47
|
+
next(new AppError(400, code, err instanceof Error ? err.message : "Upload failed"));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
const filesByField: Record<string, Express.Multer.File[]> = {};
|
|
53
|
+
for (const file of (req.files as Express.Multer.File[]) ?? []) {
|
|
54
|
+
if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(baseMimeType(file.mimetype))) {
|
|
55
|
+
throw new AppError(400, "unsupported_file_type", `${file.originalname} has unsupported type "${file.mimetype}"`);
|
|
56
|
+
}
|
|
57
|
+
(filesByField[file.fieldname] ??= []).push(file);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const ctx = createContext(req, res);
|
|
61
|
+
await handler(ctx, { files: filesByField });
|
|
62
|
+
} catch (handlerErr) {
|
|
63
|
+
next(handlerErr);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Server } from "node:http";
|
|
2
|
+
import type { IncomingMessage } from "node:http";
|
|
3
|
+
import { WebSocketServer, type WebSocket, type RawData } from "ws";
|
|
4
|
+
|
|
5
|
+
/** Handlers for one WebSocket route. `ws.send()`/`ws.close()` match the shape the Hono adapter's handlers get, too. */
|
|
6
|
+
export interface WebSocketHandlers {
|
|
7
|
+
onOpen?: (ws: WebSocket, req: IncomingMessage) => void;
|
|
8
|
+
onMessage?: (ws: WebSocket, data: RawData) => void;
|
|
9
|
+
onClose?: (ws: WebSocket) => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface PendingRegistration {
|
|
13
|
+
path: string;
|
|
14
|
+
handlers: WebSocketHandlers;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const pending = new WeakMap<object, PendingRegistration[]>();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Registers a WebSocket route. Unlike Hono's version, this can't be
|
|
21
|
+
* registered as a normal GET route — Express has no route-level concept of
|
|
22
|
+
* an HTTP upgrade, only `ws`'s own server does, and that server doesn't
|
|
23
|
+
* exist until serve() has actually started listening. Call this on `app`
|
|
24
|
+
* any time before serve(); it's wired up once serve() has a real
|
|
25
|
+
* http.Server to attach to:
|
|
26
|
+
*
|
|
27
|
+
* defineWebSocket(app, "/ws", {
|
|
28
|
+
* onMessage: (ws, data) => ws.send(`echo: ${data}`),
|
|
29
|
+
* });
|
|
30
|
+
*/
|
|
31
|
+
export function defineWebSocket(app: object, path: string, handlers: WebSocketHandlers): void {
|
|
32
|
+
const list = pending.get(app) ?? [];
|
|
33
|
+
list.push({ path, handlers });
|
|
34
|
+
pending.set(app, list);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Called by serve() once the real http.Server exists — attaches one `ws` WebSocketServer per registered path. */
|
|
38
|
+
export function attachWebSockets(app: object, server: Server): void {
|
|
39
|
+
for (const { path, handlers } of pending.get(app) ?? []) {
|
|
40
|
+
const wss = new WebSocketServer({ server, path });
|
|
41
|
+
wss.on("connection", (ws, req) => {
|
|
42
|
+
handlers.onOpen?.(ws, req);
|
|
43
|
+
if (handlers.onMessage) ws.on("message", (data) => handlers.onMessage?.(ws, data));
|
|
44
|
+
if (handlers.onClose) ws.on("close", () => handlers.onClose?.(ws));
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -11,13 +11,34 @@ export type { ErrorResponseBody } from "./error";
|
|
|
11
11
|
|
|
12
12
|
export { logger } from "./logger";
|
|
13
13
|
|
|
14
|
+
export { requireEnv } from "./require-env";
|
|
15
|
+
|
|
16
|
+
export { requireAuth } from "./require-auth";
|
|
17
|
+
export type { VerifyJwtOptions } from "./auth-core";
|
|
18
|
+
|
|
19
|
+
export { rateLimit } from "./rate-limit";
|
|
20
|
+
export type { RateLimitOptions } from "./rate-limit";
|
|
21
|
+
|
|
22
|
+
export { defineWebSocket } from "./websocket";
|
|
23
|
+
export type { WebSocketHandlers } from "./websocket";
|
|
24
|
+
|
|
25
|
+
export { defineStream } from "./stream";
|
|
26
|
+
export type { StreamWriter } from "./stream";
|
|
27
|
+
|
|
28
|
+
export { defineUpload } from "./upload";
|
|
29
|
+
export type { UploadOptions, UploadHandler } from "./upload";
|
|
30
|
+
|
|
31
|
+
export { generateOpenApiSpec, serveApiDocs } from "./openapi";
|
|
32
|
+
export type { OpenApiOptions } from "./openapi";
|
|
33
|
+
export { apiReferenceHtml } from "./openapi-core";
|
|
34
|
+
|
|
14
35
|
export type { BackonContext, Env } from "./types";
|
|
15
36
|
|
|
16
37
|
/**
|
|
17
|
-
* Re-exported so generated projects (and anything
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
38
|
+
* Re-exported so generated projects (and anything built on backon) never
|
|
39
|
+
* need to depend on 'hono' directly, even for the parts backon doesn't add
|
|
40
|
+
* opinions to yet — like building a sub-router with `new Hono()` for a
|
|
41
|
+
* single resource's routes.
|
|
21
42
|
*/
|
|
22
43
|
export { Hono } from "hono";
|
|
23
44
|
export type { Next } from "hono";
|
package/src/logger.ts
CHANGED
|
@@ -5,8 +5,8 @@ import type { Env } from "./types";
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Structured logger. pino instead of console.log because it's fast enough to
|
|
8
|
-
* leave on in production and gives
|
|
9
|
-
* console.log output
|
|
8
|
+
* leave on in production and gives structured (JSON) lines for free —
|
|
9
|
+
* console.log output isn't queryable later, structured log lines are.
|
|
10
10
|
*/
|
|
11
11
|
export const logger = pino({
|
|
12
12
|
level: process.env.LOG_LEVEL ?? "info",
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
2
|
+
import type { ZodType } from "zod";
|
|
3
|
+
|
|
4
|
+
export interface OpenApiOptions {
|
|
5
|
+
/** Defaults to "API". */
|
|
6
|
+
title?: string;
|
|
7
|
+
/** Defaults to "0.1.0". */
|
|
8
|
+
version?: string;
|
|
9
|
+
description?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RouteSchemaLike {
|
|
13
|
+
body?: ZodType<unknown>;
|
|
14
|
+
query?: ZodType<unknown>;
|
|
15
|
+
params?: ZodType<unknown>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface CollectedRoute {
|
|
19
|
+
method: string;
|
|
20
|
+
path: string;
|
|
21
|
+
schema?: RouteSchemaLike;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Converts a framework's own param syntax (Hono and Express both use `:id`) to OpenAPI's `{id}`. */
|
|
25
|
+
export function toOpenApiPath(path: string): string {
|
|
26
|
+
return path.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function paramNames(path: string): string[] {
|
|
30
|
+
return [...path.matchAll(/:([A-Za-z0-9_]+)/g)]
|
|
31
|
+
.map((match) => match[1])
|
|
32
|
+
.filter((name): name is string => name !== undefined);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function buildOperation(path: string, schema: RouteSchemaLike): Record<string, unknown> {
|
|
36
|
+
const operation: Record<string, unknown> = { responses: { "200": { description: "Success" } } };
|
|
37
|
+
const parameters: unknown[] = [];
|
|
38
|
+
|
|
39
|
+
if (schema.params) {
|
|
40
|
+
const jsonSchema = zodToJsonSchema(schema.params, { target: "openApi3" }) as Record<string, any>;
|
|
41
|
+
for (const name of paramNames(path)) {
|
|
42
|
+
parameters.push({
|
|
43
|
+
name,
|
|
44
|
+
in: "path",
|
|
45
|
+
required: true,
|
|
46
|
+
schema: jsonSchema.properties?.[name] ?? { type: "string" },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (schema.query) {
|
|
52
|
+
const jsonSchema = zodToJsonSchema(schema.query, { target: "openApi3" }) as Record<string, any>;
|
|
53
|
+
const required = new Set(jsonSchema.required ?? []);
|
|
54
|
+
for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
|
|
55
|
+
parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (parameters.length) operation.parameters = parameters;
|
|
60
|
+
|
|
61
|
+
if (schema.body) {
|
|
62
|
+
operation.requestBody = {
|
|
63
|
+
required: true,
|
|
64
|
+
content: { "application/json": { schema: zodToJsonSchema(schema.body, { target: "openApi3" }) } },
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return operation;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Builds an OpenAPI 3.0 document from a flat list of routes, each carrying
|
|
73
|
+
* the same Zod schema defineRoute() validates against — the spec is derived
|
|
74
|
+
* from the schemas actually enforced at runtime instead of a hand-written
|
|
75
|
+
* document that can drift out of sync with them. A route with no schema
|
|
76
|
+
* (a plain handler, /health, a WebSocket route) is skipped, since there is
|
|
77
|
+
* nothing to describe past its existence.
|
|
78
|
+
*/
|
|
79
|
+
export function buildOpenApiDocument(routes: CollectedRoute[], options: OpenApiOptions): Record<string, unknown> {
|
|
80
|
+
const paths: Record<string, Record<string, unknown>> = {};
|
|
81
|
+
|
|
82
|
+
for (const route of routes) {
|
|
83
|
+
if (!route.schema) continue;
|
|
84
|
+
const openApiPath = toOpenApiPath(route.path);
|
|
85
|
+
paths[openApiPath] ??= {};
|
|
86
|
+
paths[openApiPath][route.method.toLowerCase()] = buildOperation(route.path, route.schema);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
openapi: "3.0.3",
|
|
91
|
+
info: {
|
|
92
|
+
title: options.title ?? "API",
|
|
93
|
+
version: options.version ?? "0.1.0",
|
|
94
|
+
...(options.description ? { description: options.description } : {}),
|
|
95
|
+
},
|
|
96
|
+
paths,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A minimal page that renders an OpenAPI document with Scalar, loaded from a CDN rather than bundled as a dependency. */
|
|
101
|
+
export function apiReferenceHtml(specUrl: string, title = "API Reference"): string {
|
|
102
|
+
return `<!doctype html>
|
|
103
|
+
<html>
|
|
104
|
+
<head>
|
|
105
|
+
<title>${title}</title>
|
|
106
|
+
<meta charset="utf-8" />
|
|
107
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
108
|
+
</head>
|
|
109
|
+
<body>
|
|
110
|
+
<script id="api-reference" data-url="${specUrl}"></script>
|
|
111
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
112
|
+
</body>
|
|
113
|
+
</html>
|
|
114
|
+
`;
|
|
115
|
+
}
|
package/src/openapi.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Hono } from "hono";
|
|
2
|
+
import { buildOpenApiDocument, apiReferenceHtml, type OpenApiOptions, type CollectedRoute } from "./openapi-core";
|
|
3
|
+
import type { RouteHandlerFn } from "./define-route";
|
|
4
|
+
|
|
5
|
+
export type { OpenApiOptions };
|
|
6
|
+
|
|
7
|
+
const HTTP_METHODS = new Set(["get", "post", "put", "patch", "delete", "options", "head"]);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Reads every route registered on `app` (including ones mounted through
|
|
11
|
+
* nested `.route()` calls, since Hono copies a sub-app's own route entries
|
|
12
|
+
* onto the parent) and builds an OpenAPI document from whichever ones were
|
|
13
|
+
* wrapped in defineRoute() — those are the only ones carrying a schema.
|
|
14
|
+
*/
|
|
15
|
+
export function generateOpenApiSpec(app: Hono<any>, options: OpenApiOptions = {}): Record<string, unknown> {
|
|
16
|
+
const routes: CollectedRoute[] = app.routes
|
|
17
|
+
.filter((route) => HTTP_METHODS.has(route.method.toLowerCase()))
|
|
18
|
+
.map((route) => ({
|
|
19
|
+
method: route.method,
|
|
20
|
+
path: route.path,
|
|
21
|
+
schema: (route.handler as RouteHandlerFn).__backonRouteSchema,
|
|
22
|
+
}));
|
|
23
|
+
|
|
24
|
+
return buildOpenApiDocument(routes, options);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Mounts two routes: the OpenAPI document itself as JSON, and a page that
|
|
29
|
+
* renders it. Call after every other route is registered — same
|
|
30
|
+
* registration-order rule as any other route reading from `app.routes`.
|
|
31
|
+
*
|
|
32
|
+
* serveApiDocs(app, "/docs", { title: "My API" });
|
|
33
|
+
*/
|
|
34
|
+
export function serveApiDocs(app: Hono<any>, path = "/docs", options: OpenApiOptions = {}): void {
|
|
35
|
+
const specPath = `${path}/openapi.json`;
|
|
36
|
+
app.get(specPath, (c) => c.json(generateOpenApiSpec(app, options)));
|
|
37
|
+
app.get(path, (c) => c.html(apiReferenceHtml(specPath, options.title)));
|
|
38
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plain in-memory token-bucket limiter, shared by the Hono and Express
|
|
3
|
+
* rate-limit middleware — the bucket bookkeeping is identical, only how
|
|
4
|
+
* each framework reads a request and reports 429 differs.
|
|
5
|
+
*
|
|
6
|
+
* NOTE: this is per-process state. It resets on restart and does not share
|
|
7
|
+
* counts across multiple instances (a multi-dyno deploy, serverless
|
|
8
|
+
* functions, etc). Fine for a single long-running server; for anything
|
|
9
|
+
* horizontally scaled, back this with Redis instead — this class exists to
|
|
10
|
+
* make that swap easy (same `check()` contract), not to rule it out.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
interface Bucket {
|
|
14
|
+
count: number;
|
|
15
|
+
resetAt: number;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface RateLimitCheckResult {
|
|
19
|
+
allowed: boolean;
|
|
20
|
+
/** Milliseconds until this key's window resets. Only meaningful when allowed is false. */
|
|
21
|
+
retryAfterMs: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export class RateLimiter {
|
|
25
|
+
private readonly buckets = new Map<string, Bucket>();
|
|
26
|
+
private checksSinceSweep = 0;
|
|
27
|
+
|
|
28
|
+
constructor(
|
|
29
|
+
private readonly windowMs: number,
|
|
30
|
+
private readonly max: number
|
|
31
|
+
) {}
|
|
32
|
+
|
|
33
|
+
check(key: string, now: number = Date.now()): RateLimitCheckResult {
|
|
34
|
+
this.maybeSweep(now);
|
|
35
|
+
|
|
36
|
+
let bucket = this.buckets.get(key);
|
|
37
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
38
|
+
bucket = { count: 0, resetAt: now + this.windowMs };
|
|
39
|
+
this.buckets.set(key, bucket);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
bucket.count += 1;
|
|
43
|
+
|
|
44
|
+
if (bucket.count > this.max) {
|
|
45
|
+
return { allowed: false, retryAfterMs: bucket.resetAt - now };
|
|
46
|
+
}
|
|
47
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Opportunistic cleanup so long-lived processes don't accumulate one bucket per distinct key forever. */
|
|
51
|
+
private maybeSweep(now: number): void {
|
|
52
|
+
this.checksSinceSweep += 1;
|
|
53
|
+
if (this.checksSinceSweep < 1000) return;
|
|
54
|
+
this.checksSinceSweep = 0;
|
|
55
|
+
|
|
56
|
+
for (const [key, bucket] of this.buckets) {
|
|
57
|
+
if (bucket.resetAt <= now) this.buckets.delete(key);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Context, Next } from "hono";
|
|
2
|
+
import type { Env } from "./types";
|
|
3
|
+
import { AppError } from "./error";
|
|
4
|
+
import { RateLimiter } from "./rate-limit-core";
|
|
5
|
+
|
|
6
|
+
export interface RateLimitOptions {
|
|
7
|
+
/** Window size in ms. Defaults to 60_000 (1 minute). */
|
|
8
|
+
windowMs?: number;
|
|
9
|
+
/** Max requests allowed per key within the window. Defaults to 60. */
|
|
10
|
+
max?: number;
|
|
11
|
+
/** How to derive the bucket key from a request. Defaults to the caller's IP. */
|
|
12
|
+
keyGenerator?: (c: Context<Env>) => string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const DEFAULT_WINDOW_MS = 60_000;
|
|
16
|
+
const DEFAULT_MAX = 60;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* In-memory token-bucket rate limiter. Throws AppError(429, "rate_limited")
|
|
20
|
+
* once a key exceeds `max` requests in the current window, with a
|
|
21
|
+
* Retry-After header set to when the window resets.
|
|
22
|
+
*
|
|
23
|
+
* NOTE: per-process state — resets on restart, and doesn't share counts
|
|
24
|
+
* across multiple instances or serverless invocations. Fine for a single
|
|
25
|
+
* long-running server; for anything horizontally scaled, swap in a
|
|
26
|
+
* Redis-backed limiter instead.
|
|
27
|
+
*
|
|
28
|
+
* Apply per-route or per-group, not necessarily globally — a login route
|
|
29
|
+
* usually wants a tighter limit than the rest of the API:
|
|
30
|
+
*
|
|
31
|
+
* auth.use("/login", rateLimit({ windowMs: 60_000, max: 5 }));
|
|
32
|
+
*/
|
|
33
|
+
export function rateLimit(options: RateLimitOptions = {}) {
|
|
34
|
+
const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
|
|
35
|
+
const keyGenerator = options.keyGenerator ?? defaultKey;
|
|
36
|
+
|
|
37
|
+
return async function rateLimitMiddleware(c: Context<Env>, next: Next) {
|
|
38
|
+
const result = limiter.check(keyGenerator(c));
|
|
39
|
+
if (!result.allowed) {
|
|
40
|
+
c.header("Retry-After", String(Math.ceil(result.retryAfterMs / 1000)));
|
|
41
|
+
throw new AppError(429, "rate_limited", "Too many requests", {
|
|
42
|
+
retryAfterMs: result.retryAfterMs,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
await next();
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
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
|
+
);
|
|
53
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Context, Next } from "hono";
|
|
2
|
+
import type { Env } from "./types";
|
|
3
|
+
import { AppError } from "./error";
|
|
4
|
+
import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "./auth-core";
|
|
5
|
+
|
|
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! }));
|
|
21
|
+
*/
|
|
22
|
+
export function requireAuth(options: VerifyJwtOptions) {
|
|
23
|
+
return async function requireAuthMiddleware(c: Context<Env>, next: Next) {
|
|
24
|
+
const token = extractBearerToken(c.req.header("authorization"));
|
|
25
|
+
if (!token) {
|
|
26
|
+
throw new AppError(401, "unauthorized", "Missing or malformed Authorization header");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
const payload = await verifyJwt(token, options);
|
|
31
|
+
c.set("auth", payload);
|
|
32
|
+
} catch {
|
|
33
|
+
throw new AppError(401, "unauthorized", "Invalid or expired token");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
await next();
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { ZodType } from "zod";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Validates process.env against a Zod schema once, at startup, and returns
|
|
5
|
+
* the parsed result. Fails fast with every missing/invalid var named in one
|
|
6
|
+
* error, instead of the app booting cleanly and only crashing later on
|
|
7
|
+
* whichever request happens to be the first to touch a var nobody set.
|
|
8
|
+
*
|
|
9
|
+
* Usage, typically in src/config/env.ts:
|
|
10
|
+
*
|
|
11
|
+
* import { z } from "zod";
|
|
12
|
+
* import { requireEnv } from "@mednours/backon";
|
|
13
|
+
*
|
|
14
|
+
* export const env = requireEnv(z.object({
|
|
15
|
+
* DATABASE_URL: z.string().url(),
|
|
16
|
+
* PORT: z.coerce.number().default(3000),
|
|
17
|
+
* }));
|
|
18
|
+
*
|
|
19
|
+
* `env.DATABASE_URL` is then typed as `string`, not `string | undefined` —
|
|
20
|
+
* everywhere else in the app can trust it's actually there.
|
|
21
|
+
*/
|
|
22
|
+
export function requireEnv<T>(schema: ZodType<T>): T {
|
|
23
|
+
const parsed = schema.safeParse(process.env);
|
|
24
|
+
if (!parsed.success) {
|
|
25
|
+
const issues = parsed.error.issues
|
|
26
|
+
.map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`)
|
|
27
|
+
.join("\n");
|
|
28
|
+
throw new Error(`Invalid environment variables:\n${issues}`);
|
|
29
|
+
}
|
|
30
|
+
return parsed.data;
|
|
31
|
+
}
|