@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
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Opinionated backend framework wrapper for Bun. Two adapters, same names,
|
|
|
4
4
|
same JSON error shape, same defaults — pick per project:
|
|
5
5
|
|
|
6
6
|
- `@mednours/backon` (default export) — wraps [Hono](https://hono.dev)
|
|
7
|
-
- `@mednours/backon/express` — wraps [Express](https://expressjs.com); requires `express`, `cors`, `helmet`, and `compression` as peer dependencies in
|
|
7
|
+
- `@mednours/backon/express` — wraps [Express](https://expressjs.com); requires `express`, `cors`, `helmet`, and `compression` as peer dependencies in the consuming project
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
@@ -42,7 +42,7 @@ serve(app);
|
|
|
42
42
|
|
|
43
43
|
## `defineRoute(schema, handler)`
|
|
44
44
|
|
|
45
|
-
Validates `body`/`query`/`params` against Zod schemas before
|
|
45
|
+
Validates `body`/`query`/`params` against Zod schemas before the handler runs, and hands the handler already-parsed, typed data. On failure it throws `AppError(400, "invalid_body" | "invalid_query" | "invalid_params", ...)` with the Zod error attached as `details`, caught automatically by `createApp()`'s error handler.
|
|
46
46
|
|
|
47
47
|
```ts
|
|
48
48
|
app.post(
|
|
@@ -57,7 +57,7 @@ app.post(
|
|
|
57
57
|
|
|
58
58
|
Runs on Bun's native server (Express adapter: Node's http server via Express's own `app.listen`) with graceful shutdown wired to `SIGTERM`/`SIGINT` — new connections stop being accepted and in-flight requests finish before exit.
|
|
59
59
|
|
|
60
|
-
**Express-specific:** `serve(app)` also registers the central error handler
|
|
60
|
+
**Express-specific:** `serve(app)` also registers the central error handler. Do this *after* every route is registered, not inside `createApp()` — Express's error-handling middleware only catches errors from routes registered *before* it, the opposite of Hono's `onError()`. When not using this `serve()` (wrapping the app for a serverless platform, or a `supertest` suite), call `attachErrorHandler(app)` directly, after every route.
|
|
61
61
|
|
|
62
62
|
```ts
|
|
63
63
|
import { createApp, defineRoute, serve } from "@mednours/backon/express";
|
|
@@ -75,6 +75,138 @@ app.get(
|
|
|
75
75
|
serve(app); // attaches the error handler, then app.listen()
|
|
76
76
|
```
|
|
77
77
|
|
|
78
|
+
## `requireEnv(schema)`
|
|
79
|
+
|
|
80
|
+
Validates `process.env` against a Zod schema once, at startup, and returns the parsed (typed) result. Fails fast with every missing/invalid var named in one error, instead of the app booting cleanly and only crashing later on whichever request happens to touch a var nobody set.
|
|
81
|
+
|
|
82
|
+
```ts
|
|
83
|
+
import { z } from "zod";
|
|
84
|
+
import { requireEnv } from "@mednours/backon";
|
|
85
|
+
|
|
86
|
+
export const env = requireEnv(
|
|
87
|
+
z.object({
|
|
88
|
+
DATABASE_URL: z.string().url(),
|
|
89
|
+
PORT: z.coerce.number().default(3000),
|
|
90
|
+
})
|
|
91
|
+
);
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## `requireAuth(options)`
|
|
95
|
+
|
|
96
|
+
Verifies a bearer JWT and makes the decoded payload available on the context — `c.get("auth")` (Hono) or `res.locals.auth` (Express, or `c.get("auth")` inside a `defineRoute` handler). Throws `AppError(401, "unauthorized", ...)` if the header is missing, malformed, or the token fails verification (bad signature, expired, wrong algorithm). Built on `hono/jwt` rather than a new dependency, since `hono` is already a hard dependency of this package regardless of which adapter is in use.
|
|
97
|
+
|
|
98
|
+
This is verification only — issuing tokens (login, signup, refresh rotation, revocation) is left to the consuming project, since that's genuinely different per project and baking in an opinion there risks being wrong for whatever actually uses it. The algorithm defaults to `HS256` and must be set explicitly rather than trusted from the token's own header — trusting that is how `alg: none` and algorithm-confusion attacks work.
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { requireAuth } from "@mednours/backon";
|
|
102
|
+
|
|
103
|
+
app.use("/api/*", requireAuth({ secret: process.env.JWT_SECRET! }));
|
|
104
|
+
app.get("/api/me", (c) => c.json({ auth: c.get("auth") }));
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## `rateLimit(options)`
|
|
108
|
+
|
|
109
|
+
In-memory token-bucket rate limiter. Throws `AppError(429, "rate_limited", ...)` once a key exceeds `max` requests within `windowMs`, with a `Retry-After` header set to when the window resets. Defaults to 60 requests per minute, keyed by the caller's IP; override either with `options`.
|
|
110
|
+
|
|
111
|
+
**Per-process state** — resets on restart and doesn't share counts across multiple instances or serverless invocations. Fine for a single long-running server; for anything horizontally scaled, back it with Redis instead.
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { rateLimit } from "@mednours/backon";
|
|
115
|
+
|
|
116
|
+
app.use("/auth/login", rateLimit({ windowMs: 60_000, max: 5 })); // tighter limit on a login route
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## `defineWebSocket(handlers)`
|
|
120
|
+
|
|
121
|
+
Registers a WebSocket route with `onOpen`/`onMessage`/`onClose` handlers, each getting a `ws` handle with `.send()`/`.close()`.
|
|
122
|
+
|
|
123
|
+
On Hono, the handshake happens at `Bun.serve()`'s own level (an HTTP upgrade, not an ordinary request/response cycle), so this only works with the `serve()` this package exports — it passes `hono/bun`'s websocket handler into `Bun.serve()` under the hood. Register it like any other route:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
app.get("/ws", defineWebSocket({
|
|
127
|
+
onMessage: (ws, data) => ws.send(`echo: ${data}`),
|
|
128
|
+
}));
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
On Express, there is no route-level concept of an HTTP upgrade — only the `ws` package's own server has one, and that server doesn't exist until `serve()` is actually listening. The signature differs slightly to reflect this: it takes `app` and a `path` instead of being handed to `app.get()`, and can be called any time before `serve()`.
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { defineWebSocket, serve } from "@mednours/backon/express";
|
|
135
|
+
|
|
136
|
+
defineWebSocket(app, "/ws", {
|
|
137
|
+
onMessage: (ws, data) => ws.send(`echo: ${data}`),
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
serve(app); // attaches a WebSocketServer per registered path once the real http.Server exists
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## `defineStream(handler)`
|
|
144
|
+
|
|
145
|
+
Registers a route that writes its response in chunks as they become available, instead of building one body in memory and returning it all at once — server-sent events, a large export, anything too slow or too big to buffer first. The handler gets a `write(chunk)` function.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
app.get("/export", defineStream(async (c, write) => {
|
|
149
|
+
for (const row of rows) await write(JSON.stringify(row) + "\n");
|
|
150
|
+
}));
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Set a Content-Type via `c.header()` before the first `write()` if the default (left to the client to infer) isn't right for what's being sent.
|
|
154
|
+
|
|
155
|
+
## `defineUpload(options, handler)`
|
|
156
|
+
|
|
157
|
+
Parses a `multipart/form-data` request, validating each file against `maxFileSizeBytes`/`allowedMimeTypes` before the handler runs — the same "validate first, throw `AppError(400, ...)` on failure" contract as `defineRoute()`, just for files instead of a JSON body. Fields uploaded more than once under the same name all land under that field's array, so `files.avatar` is always an array, even with one file. MIME type checks compare only the base type, ignoring parameters like `;charset=utf-8` on the Content-Type header.
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
app.post(
|
|
161
|
+
"/avatar",
|
|
162
|
+
defineUpload(
|
|
163
|
+
{ maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
|
|
164
|
+
async (c, { files }) => c.json({ uploaded: files.avatar.length })
|
|
165
|
+
)
|
|
166
|
+
);
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
On Express, this is built on `multer` with in-memory storage (never written to disk — the handler decides what happens to the data), since Express has no built-in multipart parser the way Hono's `c.req.parseBody()` is. `multer` is an optional peer dependency, only required when `defineUpload` is actually used.
|
|
170
|
+
|
|
171
|
+
## `generateOpenApiSpec(app)` / `serveApiDocs(app, path, options)`
|
|
172
|
+
|
|
173
|
+
Builds an OpenAPI 3.0 document from the routes registered on `app`, using the same Zod schemas `defineRoute()` validates against — the spec is derived from the schemas actually enforced at runtime instead of a hand-written document that can drift out of sync with them. A route with no schema (a plain handler, `/health`, a WebSocket route) is skipped, since there is nothing to describe past its existence.
|
|
174
|
+
|
|
175
|
+
`serveApiDocs` mounts the document as JSON plus a rendered reference page built on [Scalar](https://github.com/scalar/scalar), loaded from a CDN rather than bundled as a dependency. Call it after every other route is registered, same registration-order rule as anything else reading the app's route table.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { serveApiDocs } from "@mednours/backon";
|
|
179
|
+
|
|
180
|
+
serveApiDocs(app, "/docs", { title: "My API" });
|
|
181
|
+
// GET /docs/openapi.json -> the raw spec
|
|
182
|
+
// GET /docs -> a rendered API reference page
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`apiReferenceHtml(specUrl, title?)`, the page `serveApiDocs` renders, is also exported directly — useful for a build step that writes the spec and the reference page to static files instead of serving them from a running app:
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { writeFileSync } from "node:fs";
|
|
189
|
+
import { generateOpenApiSpec, apiReferenceHtml } from "@mednours/backon";
|
|
190
|
+
import { app } from "./src/app";
|
|
191
|
+
|
|
192
|
+
writeFileSync("openapi.json", JSON.stringify(generateOpenApiSpec(app, { title: "My API" }), null, 2));
|
|
193
|
+
writeFileSync("docs.html", apiReferenceHtml("./openapi.json", "My API"));
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
On Express, routes are read from a registry `createApp()` and `Router()` (exported from `@mednours/backon/express`) both populate as routes are added — using Express's own unwrapped `express.Router()` instead means those routes won't appear in the generated spec.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
import { createApp, Router, defineRoute, serveApiDocs, serve } from "@mednours/backon/express";
|
|
200
|
+
|
|
201
|
+
const app = createApp();
|
|
202
|
+
const users = Router();
|
|
203
|
+
users.get("/", defineRoute({}, (c) => c.json({ users: [] })));
|
|
204
|
+
app.use("/users", users);
|
|
205
|
+
|
|
206
|
+
serveApiDocs(app, "/docs", { title: "My API" });
|
|
207
|
+
serve(app);
|
|
208
|
+
```
|
|
209
|
+
|
|
78
210
|
## Requirements
|
|
79
211
|
|
|
80
212
|
Bun >= 1.3. This package ships TypeScript source directly (no build step) since it's Bun-only by design.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mednours/backon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Opinionated backend framework wrapper for Bun. Wraps Hono (default) or Express (via @mednours/backon/express) with the same baked-in security, logging, and validation defaults.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -33,19 +33,24 @@
|
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"hono": "^4.6.14",
|
|
35
35
|
"pino": "^9.5.0",
|
|
36
|
-
"zod": "^3.
|
|
36
|
+
"zod": "^3.25.28",
|
|
37
|
+
"zod-to-json-schema": "^3.25.2"
|
|
37
38
|
},
|
|
38
39
|
"peerDependencies": {
|
|
39
40
|
"express": "^4.21.0",
|
|
40
41
|
"cors": "^2.8.5",
|
|
41
42
|
"helmet": "^8.0.0",
|
|
42
|
-
"compression": "^1.7.5"
|
|
43
|
+
"compression": "^1.7.5",
|
|
44
|
+
"ws": "^8.18.0",
|
|
45
|
+
"multer": "^1.4.5"
|
|
43
46
|
},
|
|
44
47
|
"peerDependenciesMeta": {
|
|
45
48
|
"express": { "optional": true },
|
|
46
49
|
"cors": { "optional": true },
|
|
47
50
|
"helmet": { "optional": true },
|
|
48
|
-
"compression": { "optional": true }
|
|
51
|
+
"compression": { "optional": true },
|
|
52
|
+
"ws": { "optional": true },
|
|
53
|
+
"multer": { "optional": true }
|
|
49
54
|
},
|
|
50
55
|
"devDependencies": {
|
|
51
56
|
"@types/bun": "latest",
|
|
@@ -53,11 +58,15 @@
|
|
|
53
58
|
"@types/cors": "^2.8.17",
|
|
54
59
|
"@types/compression": "^1.7.5",
|
|
55
60
|
"@types/supertest": "^6.0.2",
|
|
61
|
+
"@types/ws": "^8.5.13",
|
|
62
|
+
"@types/multer": "^1.4.12",
|
|
56
63
|
"typescript": "^5.7.2",
|
|
57
64
|
"express": "^4.21.0",
|
|
58
65
|
"cors": "^2.8.5",
|
|
59
66
|
"helmet": "^8.0.0",
|
|
60
67
|
"compression": "^1.7.5",
|
|
68
|
+
"ws": "^8.18.0",
|
|
69
|
+
"multer": "^1.4.5-lts.1",
|
|
61
70
|
"supertest": "^7.0.0"
|
|
62
71
|
}
|
|
63
72
|
}
|
package/src/auth-core.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { verify } from "hono/jwt";
|
|
2
|
+
import type { JWTPayload } from "hono/utils/jwt/types";
|
|
3
|
+
import type { SignatureAlgorithm } from "hono/utils/jwt/jwa";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Shared by the Hono and Express requireAuth() middleware — the actual JWT
|
|
7
|
+
* verification is identical, only how each framework reads the incoming
|
|
8
|
+
* request and reports failure differs. Built on hono/jwt's verify() rather
|
|
9
|
+
* than a new dependency, since hono is already a hard dependency of backon
|
|
10
|
+
* regardless of which framework (Hono or Express) a project picked.
|
|
11
|
+
*/
|
|
12
|
+
export interface VerifyJwtOptions {
|
|
13
|
+
/** Secret used to verify the token's signature. */
|
|
14
|
+
secret: string;
|
|
15
|
+
/**
|
|
16
|
+
* Algorithm to verify with. Defaults to HS256. Deliberately not inferred
|
|
17
|
+
* from the token's own header — trusting that is how "alg: none" and
|
|
18
|
+
* algorithm-confusion attacks work, so backon always verifies against an
|
|
19
|
+
* algorithm the server chose, never one the token claims for itself.
|
|
20
|
+
*/
|
|
21
|
+
alg?: SignatureAlgorithm;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const DEFAULT_ALG: SignatureAlgorithm = "HS256";
|
|
25
|
+
|
|
26
|
+
/** Verifies a JWT's signature and standard claims (exp/nbf/iat), returns its payload. Throws on any failure. */
|
|
27
|
+
export function verifyJwt(token: string, options: VerifyJwtOptions): Promise<JWTPayload> {
|
|
28
|
+
return verify(token, options.secret, options.alg ?? DEFAULT_ALG);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Pulls the token out of a `Bearer <token>` Authorization header, or undefined if it's missing/malformed. */
|
|
32
|
+
export function extractBearerToken(header: string | undefined): string | undefined {
|
|
33
|
+
if (!header) return undefined;
|
|
34
|
+
const [scheme, token] = header.split(" ");
|
|
35
|
+
if (scheme?.toLowerCase() !== "bearer" || !token) return undefined;
|
|
36
|
+
return token;
|
|
37
|
+
}
|
package/src/create-app.ts
CHANGED
|
@@ -33,8 +33,8 @@ function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
|
33
33
|
* that turns AppError (or anything else) into a consistent JSON shape.
|
|
34
34
|
*
|
|
35
35
|
* This is the "small opinionated helpers" layer agreed on for v1 — enough to
|
|
36
|
-
*
|
|
37
|
-
*
|
|
36
|
+
* justify a dedicated package instead of importing hono directly, without
|
|
37
|
+
* trying to cover every possible use case up front.
|
|
38
38
|
*/
|
|
39
39
|
export function createApp(options: CreateAppOptions = {}) {
|
|
40
40
|
const app = new Hono<Env>();
|
|
@@ -59,14 +59,14 @@ export function createApp(options: CreateAppOptions = {}) {
|
|
|
59
59
|
|
|
60
60
|
// Registered here, before createApp() returns, so it always gets the
|
|
61
61
|
// middleware above (logging, secure headers, CORS, compression, body
|
|
62
|
-
// limit). It deliberately does NOT get middleware
|
|
63
|
-
//
|
|
62
|
+
// limit). It deliberately does NOT get middleware added afterward in the
|
|
63
|
+
// project's own app.ts (app.use('*', someMiddleware) only wraps routes
|
|
64
64
|
// registered after that call) — verified by hand, this is Hono's own
|
|
65
65
|
// registration-order behavior, not something backon adds. That's the
|
|
66
66
|
// right default for a liveness check: an uptime monitor shouldn't get
|
|
67
|
-
// blocked by app-specific middleware like auth.
|
|
68
|
-
//
|
|
69
|
-
//
|
|
67
|
+
// blocked by app-specific middleware like auth. For /health behind its
|
|
68
|
+
// own middleware too, register a separate route instead of relying on
|
|
69
|
+
// this one.
|
|
70
70
|
app.get("/health", (c) => c.json({ status: "ok" }));
|
|
71
71
|
|
|
72
72
|
app.onError((err, c) => {
|
package/src/define-route.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { ZodType } from "zod";
|
|
|
2
2
|
import { AppError } from "./error";
|
|
3
3
|
import type { BackonContext } from "./types";
|
|
4
4
|
|
|
5
|
-
/** Zod schemas for the parts of a request worth validating. All optional — skip
|
|
5
|
+
/** Zod schemas for the parts of a request worth validating. All optional — skip whatever isn't needed. */
|
|
6
6
|
export interface RouteSchema<B = undefined, Q = undefined, P = undefined> {
|
|
7
7
|
body?: ZodType<B>;
|
|
8
8
|
query?: ZodType<Q>;
|
|
@@ -20,15 +20,25 @@ export type RouteHandler<B, Q, P> = (
|
|
|
20
20
|
data: RouteData<B, Q, P>
|
|
21
21
|
) => Response | Promise<Response>;
|
|
22
22
|
|
|
23
|
+
/** A defineRoute()-wrapped handler, carrying its own schema for generateOpenApiSpec() to read back later. */
|
|
24
|
+
export interface RouteHandlerFn {
|
|
25
|
+
(c: BackonContext): Promise<Response>;
|
|
26
|
+
__backonRouteSchema?: RouteSchema<unknown, unknown, unknown>;
|
|
27
|
+
}
|
|
28
|
+
|
|
23
29
|
/**
|
|
24
30
|
* Wraps a handler with request validation against zod schemas. On failure,
|
|
25
31
|
* throws AppError(400, ...) with the zod error attached as `details` —
|
|
26
32
|
* createApp()'s error handler turns that into the standard error JSON shape,
|
|
27
33
|
* so individual routes never write their own "if invalid, return 400" code.
|
|
28
34
|
*
|
|
35
|
+
* The schema is also attached to the returned function as
|
|
36
|
+
* `__backonRouteSchema`, purely for generateOpenApiSpec() to read back —
|
|
37
|
+
* nothing about validation depends on it.
|
|
38
|
+
*
|
|
29
39
|
* Usage in a *.controller.ts file:
|
|
30
40
|
*
|
|
31
|
-
*
|
|
41
|
+
* const getTelemetry = defineRoute(
|
|
32
42
|
* { query: z.object({ deviceId: z.string() }) },
|
|
33
43
|
* async (c, { query }) => c.json({ deviceId: query.deviceId })
|
|
34
44
|
* );
|
|
@@ -36,8 +46,8 @@ export type RouteHandler<B, Q, P> = (
|
|
|
36
46
|
export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
37
47
|
schema: RouteSchema<B, Q, P>,
|
|
38
48
|
handler: RouteHandler<B, Q, P>
|
|
39
|
-
) {
|
|
40
|
-
|
|
49
|
+
): RouteHandlerFn {
|
|
50
|
+
const wrapped: RouteHandlerFn = async (c: BackonContext): Promise<Response> => {
|
|
41
51
|
let body = undefined as B;
|
|
42
52
|
let query = undefined as Q;
|
|
43
53
|
let params = undefined as P;
|
|
@@ -71,4 +81,6 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
|
71
81
|
|
|
72
82
|
return handler(c, { body, query, params });
|
|
73
83
|
};
|
|
84
|
+
wrapped.__backonRouteSchema = schema as RouteSchema<unknown, unknown, unknown>;
|
|
85
|
+
return wrapped;
|
|
74
86
|
}
|
|
@@ -5,6 +5,7 @@ import compression from "compression";
|
|
|
5
5
|
import { AppError } from "../error";
|
|
6
6
|
import { logger } from "../logger";
|
|
7
7
|
import { requestLogger } from "./logger";
|
|
8
|
+
import { trackRoutes } from "./router-registry";
|
|
8
9
|
|
|
9
10
|
export interface CreateAppOptions {
|
|
10
11
|
/** Allowed CORS origins. Defaults to ALLOWED_ORIGINS env var (comma-separated), closed by default. */
|
|
@@ -31,16 +32,19 @@ function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
|
31
32
|
* 4-argument signature and only lets it catch errors from routes/middleware
|
|
32
33
|
* registered BEFORE it — the opposite of Hono's onError(), which is
|
|
33
34
|
* registration-order-independent. If the error handler were added here,
|
|
34
|
-
* inside createApp(), it would never see errors from
|
|
35
|
-
* afterward in
|
|
36
|
-
* `serve()` calls attachErrorHandler()
|
|
37
|
-
* server, once
|
|
38
|
-
*
|
|
39
|
-
* serverless handler or a supertest suite — call attachErrorHandler(app)
|
|
40
|
-
*
|
|
35
|
+
* inside createApp(), it would never see errors from routes added
|
|
36
|
+
* afterward in the project's own app.ts, exactly the routes it exists to
|
|
37
|
+
* catch. `serve()` calls attachErrorHandler() automatically, right before
|
|
38
|
+
* starting the server, once every route is guaranteed to already be
|
|
39
|
+
* registered. When not using backon's serve() — e.g. wrapping this app for
|
|
40
|
+
* a serverless handler or a supertest suite — call attachErrorHandler(app)
|
|
41
|
+
* directly, after every route, before the app is used.
|
|
41
42
|
*/
|
|
42
43
|
export function createApp(options: CreateAppOptions = {}): Express {
|
|
43
|
-
|
|
44
|
+
// Instrumented before anything else is registered, so every route this
|
|
45
|
+
// app (or a Router() mounted onto it) adds afterward — including /health
|
|
46
|
+
// below — is tracked for generateOpenApiSpec(). See router-registry.ts.
|
|
47
|
+
const app = trackRoutes(express());
|
|
44
48
|
|
|
45
49
|
app.use(requestLogger);
|
|
46
50
|
app.use(helmet());
|
|
@@ -51,9 +55,9 @@ export function createApp(options: CreateAppOptions = {}): Express {
|
|
|
51
55
|
app.use(compression());
|
|
52
56
|
app.use(express.json({ limit: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES }));
|
|
53
57
|
|
|
54
|
-
// Same reasoning as the Hono version's /health: registered before
|
|
55
|
-
//
|
|
56
|
-
//
|
|
58
|
+
// Same reasoning as the Hono version's /health: registered before any
|
|
59
|
+
// project-specific middleware, so it gets logging/security/CORS/compression
|
|
60
|
+
// but nothing added afterward. Right default for a liveness check.
|
|
57
61
|
app.get("/health", (_req, res) => {
|
|
58
62
|
res.json({ status: "ok" });
|
|
59
63
|
});
|
|
@@ -28,17 +28,27 @@ export type RouteHandler<B, Q, P> = (
|
|
|
28
28
|
data: RouteData<B, Q, P>
|
|
29
29
|
) => unknown | Promise<unknown>;
|
|
30
30
|
|
|
31
|
+
/** A defineRoute()-wrapped Express handler, carrying its own schema for generateOpenApiSpec() to read back later. */
|
|
32
|
+
export interface RouteHandlerFn {
|
|
33
|
+
(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
34
|
+
__backonRouteSchema?: RouteSchema<unknown, unknown, unknown>;
|
|
35
|
+
}
|
|
36
|
+
|
|
31
37
|
/**
|
|
32
38
|
* Same contract as the Hono defineRoute: validates body/query/params
|
|
33
39
|
* against zod schemas and throws AppError(400, ...) on failure. Requires
|
|
34
40
|
* createApp()'s express.json() middleware to have already run so
|
|
35
41
|
* req.body is parsed — see create-app.ts.
|
|
42
|
+
*
|
|
43
|
+
* The schema is also attached to the returned function as
|
|
44
|
+
* `__backonRouteSchema`, purely for generateOpenApiSpec() to read back —
|
|
45
|
+
* nothing about validation depends on it.
|
|
36
46
|
*/
|
|
37
47
|
export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
38
48
|
schema: RouteSchema<B, Q, P>,
|
|
39
49
|
handler: RouteHandler<B, Q, P>
|
|
40
|
-
) {
|
|
41
|
-
|
|
50
|
+
): RouteHandlerFn {
|
|
51
|
+
const wrapped: RouteHandlerFn = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
42
52
|
try {
|
|
43
53
|
let body = undefined as B;
|
|
44
54
|
let query = undefined as Q;
|
|
@@ -74,4 +84,6 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
|
74
84
|
next(err);
|
|
75
85
|
}
|
|
76
86
|
};
|
|
87
|
+
wrapped.__backonRouteSchema = schema as RouteSchema<unknown, unknown, unknown>;
|
|
88
|
+
return wrapped;
|
|
77
89
|
}
|
package/src/express/index.ts
CHANGED
|
@@ -11,10 +11,35 @@ 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
|
+
|
|
14
22
|
export type { BackonContext } from "./types";
|
|
15
23
|
|
|
24
|
+
export { Router } from "./router";
|
|
25
|
+
|
|
16
26
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
27
|
+
* Request/Response/NextFunction are for writing plain Express middleware
|
|
28
|
+
* itself — BackonContext only exists inside defineRoute() handlers,
|
|
29
|
+
* middleware always operates at the framework's own req/res/next layer,
|
|
30
|
+
* there's no getting around that by wrapping it.
|
|
19
31
|
*/
|
|
20
|
-
export {
|
|
32
|
+
export type { Request, Response, NextFunction } from "express";
|
|
33
|
+
|
|
34
|
+
export { defineWebSocket } from "./websocket";
|
|
35
|
+
export type { WebSocketHandlers } from "./websocket";
|
|
36
|
+
|
|
37
|
+
export { defineStream } from "./stream";
|
|
38
|
+
export type { StreamWriter } from "./stream";
|
|
39
|
+
|
|
40
|
+
export { defineUpload } from "./upload";
|
|
41
|
+
export type { UploadOptions, UploadHandler } from "./upload";
|
|
42
|
+
|
|
43
|
+
export { generateOpenApiSpec, serveApiDocs } from "./openapi";
|
|
44
|
+
export type { OpenApiOptions } from "../openapi-core";
|
|
45
|
+
export { apiReferenceHtml } from "../openapi-core";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Express } from "express";
|
|
2
|
+
import { buildOpenApiDocument, apiReferenceHtml, type OpenApiOptions, type CollectedRoute } from "../openapi-core";
|
|
3
|
+
import { collectRoutes, type TrackedRouter } from "./router-registry";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Reads every route recorded by trackRoutes() (see router-registry.ts) —
|
|
7
|
+
* meaning createApp()'s own app, and any @mednours/backon/express Router()
|
|
8
|
+
* mounted onto it — and builds an OpenAPI document from whichever ones
|
|
9
|
+
* were wrapped in defineRoute(), the only ones carrying a schema.
|
|
10
|
+
*/
|
|
11
|
+
export function generateOpenApiSpec(app: Express, options: OpenApiOptions = {}): Record<string, unknown> {
|
|
12
|
+
const routes = collectRoutes(app as unknown as TrackedRouter) as CollectedRoute[];
|
|
13
|
+
return buildOpenApiDocument(routes, options);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Mounts two routes: the OpenAPI document itself as JSON, and a page that
|
|
18
|
+
* renders it. Call after every other route is registered on `app` —
|
|
19
|
+
* routes added afterward won't be reflected in either.
|
|
20
|
+
*
|
|
21
|
+
* serveApiDocs(app, "/docs", { title: "My API" });
|
|
22
|
+
*/
|
|
23
|
+
export function serveApiDocs(app: Express, path = "/docs", options: OpenApiOptions = {}): void {
|
|
24
|
+
const specPath = `${path}/openapi.json`;
|
|
25
|
+
app.get(specPath, (_req, res) => res.json(generateOpenApiSpec(app, options)));
|
|
26
|
+
app.get(path, (_req, res) => res.type("html").send(apiReferenceHtml(specPath, options.title)));
|
|
27
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import { AppError } from "../error";
|
|
3
|
+
import { RateLimiter } from "../rate-limit-core";
|
|
4
|
+
|
|
5
|
+
export interface RateLimitOptions {
|
|
6
|
+
/** Window size in ms. Defaults to 60_000 (1 minute). */
|
|
7
|
+
windowMs?: number;
|
|
8
|
+
/** Max requests allowed per key within the window. Defaults to 60. */
|
|
9
|
+
max?: number;
|
|
10
|
+
/** How to derive the bucket key from a request. Defaults to the caller's IP. */
|
|
11
|
+
keyGenerator?: (req: Request) => string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const DEFAULT_WINDOW_MS = 60_000;
|
|
15
|
+
const DEFAULT_MAX = 60;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Express equivalent of the Hono rateLimit(): same in-memory token-bucket
|
|
19
|
+
* limiter, same per-process caveat (see rate-limit-core.ts), calls
|
|
20
|
+
* next(AppError(429, "rate_limited")) once a key exceeds `max` requests in
|
|
21
|
+
* the current window, with a Retry-After header set to when it resets.
|
|
22
|
+
*/
|
|
23
|
+
export function rateLimit(options: RateLimitOptions = {}) {
|
|
24
|
+
const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
|
|
25
|
+
const keyGenerator = options.keyGenerator ?? defaultKey;
|
|
26
|
+
|
|
27
|
+
return function rateLimitMiddleware(req: Request, res: Response, next: NextFunction) {
|
|
28
|
+
const result = limiter.check(keyGenerator(req));
|
|
29
|
+
if (!result.allowed) {
|
|
30
|
+
res.setHeader("Retry-After", String(Math.ceil(result.retryAfterMs / 1000)));
|
|
31
|
+
next(new AppError(429, "rate_limited", "Too many requests", { retryAfterMs: result.retryAfterMs }));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
next();
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function defaultKey(req: Request): string {
|
|
39
|
+
return req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? req.ip ?? "unknown";
|
|
40
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import { AppError } from "../error";
|
|
3
|
+
import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "../auth-core";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Express equivalent of the Hono requireAuth: verifies a bearer JWT and
|
|
7
|
+
* stashes the decoded payload on res.locals.auth — readable via
|
|
8
|
+
* `c.get("auth")` in a defineRoute handler (BackonContext.get() reads
|
|
9
|
+
* res.locals) or directly as `res.locals.auth` in plain Express middleware.
|
|
10
|
+
* Calls next(AppError(401, "unauthorized")) on a missing, malformed, or
|
|
11
|
+
* invalid token; requires attachErrorHandler(app) to be registered
|
|
12
|
+
* downstream (serve() does this automatically — see create-app.ts).
|
|
13
|
+
*
|
|
14
|
+
* Verification only, same as the Hono version — issuing tokens is left to
|
|
15
|
+
* the consuming project. Apply per-route or per-router, not necessarily
|
|
16
|
+
* globally.
|
|
17
|
+
*/
|
|
18
|
+
export function requireAuth(options: VerifyJwtOptions) {
|
|
19
|
+
return async function requireAuthMiddleware(req: Request, res: Response, next: NextFunction) {
|
|
20
|
+
const token = extractBearerToken(req.header("authorization"));
|
|
21
|
+
if (!token) {
|
|
22
|
+
next(new AppError(401, "unauthorized", "Missing or malformed Authorization header"));
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
res.locals.auth = await verifyJwt(token, options);
|
|
28
|
+
} catch {
|
|
29
|
+
next(new AppError(401, "unauthorized", "Invalid or expired token"));
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
next();
|
|
34
|
+
};
|
|
35
|
+
}
|