@anvil-di/bellows 0.0.3 → 0.0.5

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/src/index.ts CHANGED
@@ -2,3 +2,6 @@ export * from "./decorators.js";
2
2
  export * from "./schema.js";
3
3
  export * from "./routes.js";
4
4
  export * from "./hook.js";
5
+ export * from "./authz.js";
6
+ export * from "./errors.js";
7
+ export * from "./sse.js";
package/src/routes.ts CHANGED
@@ -1,22 +1,224 @@
1
- import { Router, type Request, type Response } from "express";
1
+ import express, {
2
+ Router,
3
+ type ErrorRequestHandler,
4
+ type Request,
5
+ type RequestHandler,
6
+ type Response,
7
+ } from "express";
8
+ import type { AuthnService, AuthzService } from "./authz.js";
9
+ import { errorHandler } from "./errors.js";
10
+
11
+ declare global {
12
+ namespace Express {
13
+ interface Request {
14
+ /** Raw request body bytes, captured by the body parser `bellowsRoutes`
15
+ * mounts for any route declaring a `RawBody` param. */
16
+ rawBody?: Buffer;
17
+ }
18
+ }
19
+ }
2
20
 
3
21
  export interface RouteDefinition {
4
22
  method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
5
23
  path: string;
24
+ /**
25
+ * Which body parser to mount for this route, derived by codegen from its
26
+ * `Body<S>`/`FormBody<S>`/`RawBody`/two-arg `Body<S, C>` params: `"json"`
27
+ * or `"urlencoded"` populate `req.body` via Express's built-in parsers,
28
+ * `"raw"` leaves `req.body` as the raw `Buffer` (no parsed param declared
29
+ * alongside `RawBody`), and the `{ kind: "codec", ... }` form — from
30
+ * `Body<S, C>` — mounts `express.raw()` scoped to `contentType` and
31
+ * replaces `req.body` with `decode()`'s result before the handler's
32
+ * `S.safeParse(req.body)` runs. All variants also capture the exact wire
33
+ * bytes into `req.rawBody`. Absent when the route declares none of those
34
+ * params — unaffected, as before.
35
+ */
36
+ bodyParser?:
37
+ | "json"
38
+ | "urlencoded"
39
+ | "raw"
40
+ | {
41
+ kind: "codec";
42
+ contentType: string;
43
+ decode: (raw: Buffer) => unknown;
44
+ };
45
+ /**
46
+ * Ordered authentication cascade from `@Authn(...)` decorators (class-level
47
+ * first, then method-level). The first service whose `identify()` returns
48
+ * `identified: true` wins and its `user` becomes `res.locals.user`. When
49
+ * this is non-empty and none identify the requester, the route fails
50
+ * closed with 401 — undeclared (empty/absent) means no authn check runs.
51
+ */
52
+ authn?: AuthnService[];
53
+ /**
54
+ * Ordered authorization cascade from `@Authz(...)` decorators (class-level
55
+ * first, then method-level), run only after authn succeeds (or when no
56
+ * `authn` is declared). The first non-`"next"` decision wins. When this is
57
+ * non-empty and every service returns `"next"` (or one returns `"deny"`),
58
+ * the route fails closed with 403 — undeclared means no authz check runs.
59
+ */
60
+ authz?: AuthzService[];
61
+ /**
62
+ * Ordered middleware run after authn/authz and before `handler`, from
63
+ * `@Middleware(...)` decorators (class-level first, then method-level). A
64
+ * middleware that doesn't call `next()` short-circuits the request —
65
+ * standard Express semantics.
66
+ */
67
+ middleware?: RequestHandler[];
6
68
  handler: (req: Request, res: Response) => void | Promise<void>;
7
69
  }
8
70
 
71
+ /**
72
+ * Build the combined authn → authz `RequestHandler` for a route, or
73
+ * `undefined` when neither is declared (so undeclared routes are unaffected).
74
+ */
75
+ function buildAuthHandler(
76
+ authn: AuthnService[] = [],
77
+ authz: AuthzService[] = [],
78
+ ): RequestHandler | undefined {
79
+ if (authn.length === 0 && authz.length === 0) {
80
+ return undefined;
81
+ }
82
+ return (req, res, next) => {
83
+ void (async () => {
84
+ let user: unknown;
85
+ if (authn.length > 0) {
86
+ let identified = false;
87
+ for (const service of authn) {
88
+ const result = await service.identify(req);
89
+ if (result.identified) {
90
+ identified = true;
91
+ user = result.user;
92
+ break;
93
+ }
94
+ }
95
+ if (!identified) {
96
+ res.status(401).json({ error: "unauthorized" });
97
+ return;
98
+ }
99
+ }
100
+ if (authz.length > 0) {
101
+ let allowed = false;
102
+ for (const service of authz) {
103
+ const decision = await service.authorize(req, user);
104
+ if (decision === "allow") {
105
+ allowed = true;
106
+ break;
107
+ }
108
+ if (decision === "deny") {
109
+ break;
110
+ }
111
+ }
112
+ if (!allowed) {
113
+ res.status(403).json({ error: "forbidden" });
114
+ return;
115
+ }
116
+ }
117
+ res.locals.user = user;
118
+ next();
119
+ })();
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Build the body-parser `RequestHandler` for a route's `bodyParser` kind. All
125
+ * variants share a `verify` callback that stashes the exact wire bytes on
126
+ * `req.rawBody`, so `RawBody` params work whether or not the route also
127
+ * parses `req.body` via `Body<S>`/`FormBody<S>`/the two-arg `Body<S, C>` form.
128
+ */
129
+ function bodyParserMiddleware(kind: NonNullable<RouteDefinition["bodyParser"]>): RequestHandler {
130
+ const verify = (req: Request, _res: Response, buf: Buffer): void => {
131
+ req.rawBody = buf;
132
+ };
133
+ if (typeof kind === "object") {
134
+ const { contentType, decode } = kind;
135
+ const rawParser = express.raw({ type: contentType, verify });
136
+ return (req, res, next) => {
137
+ rawParser(req, res, (err: unknown) => {
138
+ if (err) {
139
+ next(err);
140
+ return;
141
+ }
142
+ // Content-Type didn't match `contentType` — express.raw() left
143
+ // req.body untouched (no other parser ran), so there's nothing to
144
+ // decode; the route's S.safeParse(req.body) will reject it as
145
+ // expected.
146
+ if (!Buffer.isBuffer(req.body)) {
147
+ next();
148
+ return;
149
+ }
150
+ try {
151
+ req.body = decode(req.body);
152
+ } catch (decodeError) {
153
+ next(decodeError);
154
+ return;
155
+ }
156
+ next();
157
+ });
158
+ };
159
+ }
160
+ switch (kind) {
161
+ case "json":
162
+ return express.json({ verify });
163
+ case "urlencoded":
164
+ return express.urlencoded({ extended: true, verify });
165
+ case "raw":
166
+ return express.raw({ type: "*/*", verify });
167
+ }
168
+ }
169
+
170
+ /** Request-lifecycle hooks that apply to every route registered via `bellowsRoutes`. */
171
+ export interface BellowsHooks {
172
+ /** Runs before any route's middleware/handler, for every request. */
173
+ onRequest?: RequestHandler;
174
+ /** Runs after the response has been sent, for every request. */
175
+ onResponse?: (req: Request, res: Response) => void;
176
+ /**
177
+ * Error-handling middleware registered after all routes, so an `HttpError`
178
+ * thrown (or passed to `next`) by any route's auth handler, middleware, or
179
+ * handler is converted to a response — Express 5 forwards rejected
180
+ * promises from async handlers automatically. Defaults to `errorHandler`
181
+ * from `./errors.js`. Pass `false` to opt out, e.g. when a shared instance
182
+ * is mounted once on the parent app instead of per-router.
183
+ */
184
+ errorHandler?: ErrorRequestHandler | false;
185
+ }
186
+
9
187
  /** Returns an Express Router with all routes from `routes` registered on it. */
10
- export function bellowsRoutes(routes: Iterable<RouteDefinition>): Router {
188
+ export function bellowsRoutes(routes: Iterable<RouteDefinition>, hooks: BellowsHooks = {}): Router {
11
189
  const router = Router();
190
+
191
+ if (hooks.onRequest) {
192
+ router.use(hooks.onRequest);
193
+ }
194
+ if (hooks.onResponse) {
195
+ const onResponse = hooks.onResponse;
196
+ router.use((req, res, next) => {
197
+ res.on("finish", () => onResponse(req, res));
198
+ next();
199
+ });
200
+ }
201
+
12
202
  for (const route of routes) {
203
+ const authHandler = buildAuthHandler(route.authn, route.authz);
204
+ const handlers: RequestHandler[] = [
205
+ ...(route.bodyParser ? [bodyParserMiddleware(route.bodyParser)] : []),
206
+ ...(authHandler ? [authHandler] : []),
207
+ ...(route.middleware ?? []),
208
+ route.handler,
209
+ ];
13
210
  switch (route.method) {
14
- case "GET": router.get(route.path, route.handler); break;
15
- case "POST": router.post(route.path, route.handler); break;
16
- case "PUT": router.put(route.path, route.handler); break;
17
- case "DELETE": router.delete(route.path, route.handler); break;
18
- case "PATCH": router.patch(route.path, route.handler); break;
211
+ case "GET": router.get(route.path, ...handlers); break;
212
+ case "POST": router.post(route.path, ...handlers); break;
213
+ case "PUT": router.put(route.path, ...handlers); break;
214
+ case "DELETE": router.delete(route.path, ...handlers); break;
215
+ case "PATCH": router.patch(route.path, ...handlers); break;
19
216
  }
20
217
  }
218
+
219
+ if (hooks.errorHandler !== false) {
220
+ router.use(hooks.errorHandler ?? errorHandler);
221
+ }
222
+
21
223
  return router;
22
224
  }
package/src/schema.ts CHANGED
@@ -7,11 +7,97 @@ export interface Validator<T> {
7
7
  jsonSchema?(): JSONSchema7;
8
8
  }
9
9
 
10
- export type Body<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
10
+ /**
11
+ * Decodes a non-JSON, non-form request body into the value that `S` then
12
+ * validates via `Body<S, C>`. `contentType` must be a literal-initialized
13
+ * property (not a getter) — same constraint as `ResponseCodec`, for the same
14
+ * reason: codegen resolves it statically to build the `OpenAPI` spec (runtime
15
+ * body-parser selection always reads `contentType`/calls `decode` off the
16
+ * object itself).
17
+ */
18
+ export interface RequestCodec<T> {
19
+ readonly contentType: string;
20
+ decode(raw: Buffer): T;
21
+ }
22
+
23
+ /**
24
+ * Validates `req.body` against `S`. The optional second type argument `C`
25
+ * decodes the raw request body with a `RequestCodec` first instead of
26
+ * assuming JSON — `bellowsRoutes` mounts `express.raw()` scoped to
27
+ * `C.contentType` for the route and calls `C.decode()` before validation.
28
+ * `C` must decode into exactly the type `S` validates — this is enforced at
29
+ * compile time by the `RequestCodec<Body<S>>` bound.
30
+ *
31
+ * ```ts
32
+ * const twimlRequestCodec: RequestCodec<GatherCallback> = {
33
+ * contentType: "application/xml",
34
+ * decode: parseTwimlRequest,
35
+ * };
36
+ *
37
+ * @Post("/webhooks/gather")
38
+ * gather(body: Body<typeof GatherCallbackSchema, typeof twimlRequestCodec>): void { ... }
39
+ * ```
40
+ */
41
+ export type Body<
42
+ S extends Validator<unknown>,
43
+ C extends RequestCodec<S extends Validator<infer T> ? T : never> = never,
44
+ > = S extends Validator<infer T> ? T : never;
11
45
  export type Query<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
12
46
  export type Params<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
13
47
  export type Responds<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
14
48
 
49
+ /**
50
+ * `application/x-www-form-urlencoded` counterpart to `Body<S>` — validates
51
+ * `req.body` the same way, but tells codegen/OpenAPI the route expects a form
52
+ * body instead of JSON, and to mount `express.urlencoded()` for the route.
53
+ */
54
+ export type FormBody<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
55
+
56
+ /** Validates `req.headers` against `S`. Keys must be lower-case, matching
57
+ * Node/Express's own header casing (e.g. `"x-twilio-signature"`). */
58
+ export type Headers<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
59
+
60
+ /**
61
+ * Injects the raw, unparsed request body bytes captured before any body
62
+ * parsing. `bellowsRoutes` populates `req.rawBody` for any route that
63
+ * declares this param, via a `verify` callback on whichever body-parser it
64
+ * mounts for the route (`express.raw()` if `RawBody` is the only body param
65
+ * declared, `express.json()`/`express.urlencoded()` if paired with `Body<S>`/
66
+ * `FormBody<S>`).
67
+ */
68
+ export type RawBody = Buffer;
69
+
70
+ /**
71
+ * Serializes a validated `Responds<S>` value into a non-JSON response body.
72
+ * `contentType` must be a literal-initialized property (not a getter) —
73
+ * codegen resolves it statically to build the `OpenAPI` spec, so a computed
74
+ * value can't be read at build time.
75
+ */
76
+ export interface ResponseCodec<T> {
77
+ readonly contentType: string;
78
+ encode(value: T): string | Buffer;
79
+ }
80
+
81
+ /**
82
+ * Like `Responds<S>`, but serializes the validated return value with `C`
83
+ * instead of `res.json()`. `C` must encode exactly the type `S` validates —
84
+ * this is enforced at compile time by the `ResponseCodec<Responds<S>>` bound.
85
+ *
86
+ * ```ts
87
+ * const twimlCodec: ResponseCodec<TwimlResponse> = {
88
+ * contentType: "application/xml",
89
+ * encode: renderTwiml,
90
+ * };
91
+ *
92
+ * @Post("/webhooks/gather")
93
+ * async gather(req: Request): Promise<Produces<typeof TwimlResponseSchema, typeof twimlCodec>> { ... }
94
+ * ```
95
+ */
96
+ export type Produces<
97
+ S extends Validator<unknown>,
98
+ C extends ResponseCodec<Responds<S>>,
99
+ > = Responds<S>;
100
+
15
101
  export function withJsonSchema<T>(
16
102
  validator: Validator<T>,
17
103
  schema: JSONSchema7,
@@ -0,0 +1,129 @@
1
+ import { EventEmitter } from "node:events";
2
+ import type { Request, Response } from "express";
3
+ import { describe, expect, it, vi } from "vitest";
4
+ import { disconnectSignal, SseStream } from "./sse.js";
5
+
6
+ function mockReq(): Request {
7
+ return new EventEmitter() as unknown as Request;
8
+ }
9
+
10
+ function mockRes(): Response {
11
+ const res = {
12
+ headersSent: false,
13
+ status: vi.fn().mockReturnThis(),
14
+ setHeader: vi.fn().mockReturnThis(),
15
+ flushHeaders: vi.fn(),
16
+ write: vi.fn(),
17
+ end: vi.fn(),
18
+ };
19
+ return res as unknown as Response;
20
+ }
21
+
22
+ describe("disconnectSignal", () => {
23
+ it("is not aborted before the request closes", () => {
24
+ const req = mockReq();
25
+ const signal = disconnectSignal(req);
26
+ expect(signal.aborted).toBe(false);
27
+ });
28
+
29
+ it("aborts when the request emits close", () => {
30
+ const req = mockReq();
31
+ const signal = disconnectSignal(req);
32
+ (req as unknown as EventEmitter).emit("close");
33
+ expect(signal.aborted).toBe(true);
34
+ });
35
+ });
36
+
37
+ describe("SseStream", () => {
38
+ it("open() sets SSE headers and flushes them", () => {
39
+ const res = mockRes();
40
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
41
+ stream.open();
42
+
43
+ expect(res.status).toHaveBeenCalledWith(200);
44
+ expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "text/event-stream; charset=utf-8");
45
+ expect(res.setHeader).toHaveBeenCalledWith("Cache-Control", "no-cache, no-transform");
46
+ expect(res.setHeader).toHaveBeenCalledWith("Connection", "keep-alive");
47
+ expect(res.flushHeaders).toHaveBeenCalled();
48
+ });
49
+
50
+ it("open() is a no-op if headers were already sent", () => {
51
+ const res = mockRes();
52
+ (res as unknown as { headersSent: boolean }).headersSent = true;
53
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
54
+ stream.open();
55
+
56
+ expect(res.status).not.toHaveBeenCalled();
57
+ expect(res.flushHeaders).not.toHaveBeenCalled();
58
+ });
59
+
60
+ it("send() frames a string payload as a data line", () => {
61
+ const res = mockRes();
62
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
63
+ stream.send("hello");
64
+
65
+ expect(res.write).toHaveBeenCalledWith("data: hello\n\n");
66
+ });
67
+
68
+ it("send() JSON-encodes non-string payloads", () => {
69
+ const res = mockRes();
70
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
71
+ stream.send({ progress: 42 });
72
+
73
+ expect(res.write).toHaveBeenCalledWith('data: {"progress":42}\n\n');
74
+ });
75
+
76
+ it("send() includes event/id/retry fields when given", () => {
77
+ const res = mockRes();
78
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
79
+ stream.send("tick", { event: "progress", id: "42", retry: 3000 });
80
+
81
+ expect(res.write).toHaveBeenCalledWith("id: 42\nevent: progress\nretry: 3000\ndata: tick\n\n");
82
+ });
83
+
84
+ it("send() splits multi-line payloads into multiple data: lines", () => {
85
+ const res = mockRes();
86
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
87
+ stream.send("line1\nline2");
88
+
89
+ expect(res.write).toHaveBeenCalledWith("data: line1\ndata: line2\n\n");
90
+ });
91
+
92
+ it("comment() writes an SSE comment line", () => {
93
+ const res = mockRes();
94
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
95
+ stream.comment("ping");
96
+
97
+ expect(res.write).toHaveBeenCalledWith(": ping\n\n");
98
+ });
99
+
100
+ it("close() ends the response and is idempotent", () => {
101
+ const res = mockRes();
102
+ const stream = new SseStream(res, disconnectSignal(mockReq()));
103
+ stream.close();
104
+ stream.close();
105
+
106
+ expect(res.end).toHaveBeenCalledTimes(1);
107
+ });
108
+
109
+ it("stops writing after the client disconnects", () => {
110
+ const req = mockReq();
111
+ const res = mockRes();
112
+ const stream = new SseStream(res, disconnectSignal(req));
113
+ (req as unknown as EventEmitter).emit("close");
114
+
115
+ stream.send("late event");
116
+ stream.comment("late ping");
117
+
118
+ expect(res.write).not.toHaveBeenCalled();
119
+ });
120
+
121
+ it("exposes the signal passed at construction", () => {
122
+ const req = mockReq();
123
+ const res = mockRes();
124
+ const signal = disconnectSignal(req);
125
+ const stream = new SseStream(res, signal);
126
+
127
+ expect(stream.signal).toBe(signal);
128
+ });
129
+ });
package/src/sse.ts ADDED
@@ -0,0 +1,101 @@
1
+ import type { Request, Response } from "express";
2
+
3
+ /** Default interval for keep-alive comment pings, in milliseconds. */
4
+ const DEFAULT_KEEPALIVE_MS = 15_000;
5
+
6
+ export interface SseSendOptions {
7
+ /** `event:` field — the client-side listener name (defaults to `"message"`). */
8
+ event?: string;
9
+ /** `id:` field — sets `EventSource.lastEventId` for reconnects. */
10
+ id?: string;
11
+ /** `retry:` field — reconnection delay in ms the client should use. */
12
+ retry?: number;
13
+ }
14
+
15
+ /**
16
+ * An `AbortSignal` that fires when the client disconnects (`req`'s underlying
17
+ * socket closes). Shared by `SseStream` and available standalone for handlers
18
+ * that inject `AbortSignal` without an `SseStream` — e.g. a non-SSE chunked
19
+ * streaming handler that only needs disconnect-driven cleanup.
20
+ */
21
+ export function disconnectSignal(req: Request): AbortSignal {
22
+ const controller = new AbortController();
23
+ req.on("close", () => controller.abort());
24
+ return controller.signal;
25
+ }
26
+
27
+ /**
28
+ * Wraps `res` for a Server-Sent Events route (`@Sse`). Handles the
29
+ * `text/event-stream` handshake, event framing, keep-alive pings, and
30
+ * exposes `signal` so the handler can clean up subscriptions when the
31
+ * client disconnects.
32
+ *
33
+ * Construction does not write anything — call `open()` once the handler is
34
+ * ready to commit to a streaming response (e.g. after validating params).
35
+ */
36
+ export class SseStream {
37
+ readonly signal: AbortSignal;
38
+ private closed = false;
39
+ private keepAliveTimer: ReturnType<typeof setInterval> | undefined;
40
+
41
+ constructor(
42
+ private readonly res: Response,
43
+ signal: AbortSignal,
44
+ ) {
45
+ this.signal = signal;
46
+ signal.addEventListener("abort", () => this.teardown());
47
+ }
48
+
49
+ /**
50
+ * Sets SSE headers and flushes them immediately so the client sees an open
51
+ * connection before the first event. Starts the keep-alive ping interval
52
+ * unless `keepAliveMs` is `false`.
53
+ */
54
+ open(keepAliveMs: number | false = DEFAULT_KEEPALIVE_MS): this {
55
+ if (this.res.headersSent) return this;
56
+ this.res.status(200);
57
+ this.res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
58
+ this.res.setHeader("Cache-Control", "no-cache, no-transform");
59
+ this.res.setHeader("Connection", "keep-alive");
60
+ // Disables response buffering on nginx-fronted deployments, which would
61
+ // otherwise hold the stream open with no bytes reaching the client.
62
+ this.res.setHeader("X-Accel-Buffering", "no");
63
+ this.res.flushHeaders();
64
+ if (keepAliveMs !== false) {
65
+ this.keepAliveTimer = setInterval(() => this.comment("ping"), keepAliveMs);
66
+ this.keepAliveTimer.unref?.();
67
+ }
68
+ return this;
69
+ }
70
+
71
+ /** Writes one SSE event frame. Objects are JSON-encoded; strings are sent as-is. */
72
+ send(data: unknown, opts: SseSendOptions = {}): void {
73
+ if (this.closed) return;
74
+ let frame = "";
75
+ if (opts.id !== undefined) frame += `id: ${opts.id}\n`;
76
+ if (opts.event !== undefined) frame += `event: ${opts.event}\n`;
77
+ if (opts.retry !== undefined) frame += `retry: ${opts.retry}\n`;
78
+ const payload = typeof data === "string" ? data : JSON.stringify(data);
79
+ for (const line of payload.split("\n")) frame += `data: ${line}\n`;
80
+ this.res.write(`${frame}\n`);
81
+ }
82
+
83
+ /** Writes an SSE comment line — invisible to `EventSource` listeners, used for keep-alive. */
84
+ comment(text = ""): void {
85
+ if (this.closed) return;
86
+ this.res.write(`: ${text}\n\n`);
87
+ }
88
+
89
+ /** Ends the response. Safe to call more than once, or after client disconnect. */
90
+ close(): void {
91
+ if (this.closed) return;
92
+ this.teardown();
93
+ this.res.end();
94
+ }
95
+
96
+ private teardown(): void {
97
+ if (this.closed) return;
98
+ this.closed = true;
99
+ if (this.keepAliveTimer) clearInterval(this.keepAliveTimer);
100
+ }
101
+ }