@anvil-di/bellows 0.0.4 → 0.0.6
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/LICENSE +1 -1
- package/dist/authz.d.ts +28 -0
- package/dist/authz.d.ts.map +1 -0
- package/dist/authz.js +2 -0
- package/dist/authz.js.map +1 -0
- package/dist/decorators.d.ts +36 -4
- package/dist/decorators.d.ts.map +1 -1
- package/dist/decorators.js +38 -0
- package/dist/decorators.js.map +1 -1
- package/dist/errors.d.ts +95 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +143 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/dist/routes.d.ts +68 -2
- package/dist/routes.d.ts.map +1 -1
- package/dist/routes.js +123 -7
- package/dist/routes.js.map +1 -1
- package/dist/schema.d.ts +75 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js.map +1 -1
- package/dist/sse.d.ts +46 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +92 -0
- package/dist/sse.js.map +1 -0
- package/package.json +3 -2
- package/src/authz.ts +32 -0
- package/src/decorators.ts +48 -25
- package/src/dual-decorators.test.ts +43 -0
- package/src/errors.test.ts +149 -0
- package/src/errors.ts +186 -0
- package/src/index.test.ts +733 -1
- package/src/index.ts +3 -0
- package/src/routes.ts +209 -7
- package/src/schema.ts +87 -1
- package/src/sse.test.ts +129 -0
- package/src/sse.ts +101 -0
package/dist/routes.js
CHANGED
|
@@ -1,26 +1,142 @@
|
|
|
1
|
-
import { Router } from "express";
|
|
1
|
+
import express, { Router, } from "express";
|
|
2
|
+
import { errorHandler } from "./errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Build the combined authn → authz `RequestHandler` for a route, or
|
|
5
|
+
* `undefined` when neither is declared (so undeclared routes are unaffected).
|
|
6
|
+
*/
|
|
7
|
+
function buildAuthHandler(authn = [], authz = []) {
|
|
8
|
+
if (authn.length === 0 && authz.length === 0) {
|
|
9
|
+
return undefined;
|
|
10
|
+
}
|
|
11
|
+
return (req, res, next) => {
|
|
12
|
+
void (async () => {
|
|
13
|
+
let user;
|
|
14
|
+
if (authn.length > 0) {
|
|
15
|
+
let identified = false;
|
|
16
|
+
for (const service of authn) {
|
|
17
|
+
const result = await service.identify(req);
|
|
18
|
+
if (result.identified) {
|
|
19
|
+
identified = true;
|
|
20
|
+
user = result.user;
|
|
21
|
+
break;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (!identified) {
|
|
25
|
+
res.status(401).json({ error: "unauthorized" });
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (authz.length > 0) {
|
|
30
|
+
let allowed = false;
|
|
31
|
+
for (const service of authz) {
|
|
32
|
+
const decision = await service.authorize(req, user);
|
|
33
|
+
if (decision === "allow") {
|
|
34
|
+
allowed = true;
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
if (decision === "deny") {
|
|
38
|
+
break;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (!allowed) {
|
|
42
|
+
res.status(403).json({ error: "forbidden" });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
res.locals.user = user;
|
|
47
|
+
next();
|
|
48
|
+
})();
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Build the body-parser `RequestHandler` for a route's `bodyParser` kind. All
|
|
53
|
+
* variants share a `verify` callback that stashes the exact wire bytes on
|
|
54
|
+
* `req.rawBody`, so `RawBody` params work whether or not the route also
|
|
55
|
+
* parses `req.body` via `Body<S>`/`FormBody<S>`/the two-arg `Body<S, C>` form.
|
|
56
|
+
*/
|
|
57
|
+
function bodyParserMiddleware(kind) {
|
|
58
|
+
const verify = (req, _res, buf) => {
|
|
59
|
+
req.rawBody = buf;
|
|
60
|
+
};
|
|
61
|
+
if (typeof kind === "object") {
|
|
62
|
+
const { contentType, decode } = kind;
|
|
63
|
+
const rawParser = express.raw({ type: contentType, verify });
|
|
64
|
+
return (req, res, next) => {
|
|
65
|
+
rawParser(req, res, (err) => {
|
|
66
|
+
if (err) {
|
|
67
|
+
next(err);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
// Content-Type didn't match `contentType` — express.raw() left
|
|
71
|
+
// req.body untouched (no other parser ran), so there's nothing to
|
|
72
|
+
// decode; the route's S.safeParse(req.body) will reject it as
|
|
73
|
+
// expected.
|
|
74
|
+
if (!Buffer.isBuffer(req.body)) {
|
|
75
|
+
next();
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
req.body = decode(req.body);
|
|
80
|
+
}
|
|
81
|
+
catch (decodeError) {
|
|
82
|
+
next(decodeError);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
next();
|
|
86
|
+
});
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
switch (kind) {
|
|
90
|
+
case "json":
|
|
91
|
+
return express.json({ verify });
|
|
92
|
+
case "urlencoded":
|
|
93
|
+
return express.urlencoded({ extended: true, verify });
|
|
94
|
+
case "raw":
|
|
95
|
+
return express.raw({ type: "*/*", verify });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
2
98
|
/** Returns an Express Router with all routes from `routes` registered on it. */
|
|
3
|
-
export function bellowsRoutes(routes) {
|
|
99
|
+
export function bellowsRoutes(routes, hooks = {}) {
|
|
4
100
|
const router = Router();
|
|
101
|
+
if (hooks.onRequest) {
|
|
102
|
+
router.use(hooks.onRequest);
|
|
103
|
+
}
|
|
104
|
+
if (hooks.onResponse) {
|
|
105
|
+
const onResponse = hooks.onResponse;
|
|
106
|
+
router.use((req, res, next) => {
|
|
107
|
+
res.on("finish", () => onResponse(req, res));
|
|
108
|
+
next();
|
|
109
|
+
});
|
|
110
|
+
}
|
|
5
111
|
for (const route of routes) {
|
|
112
|
+
const authHandler = buildAuthHandler(route.authn, route.authz);
|
|
113
|
+
const handlers = [
|
|
114
|
+
...(route.bodyParser ? [bodyParserMiddleware(route.bodyParser)] : []),
|
|
115
|
+
...(authHandler ? [authHandler] : []),
|
|
116
|
+
...(route.middleware ?? []),
|
|
117
|
+
route.handler,
|
|
118
|
+
];
|
|
6
119
|
switch (route.method) {
|
|
7
120
|
case "GET":
|
|
8
|
-
router.get(route.path,
|
|
121
|
+
router.get(route.path, ...handlers);
|
|
9
122
|
break;
|
|
10
123
|
case "POST":
|
|
11
|
-
router.post(route.path,
|
|
124
|
+
router.post(route.path, ...handlers);
|
|
12
125
|
break;
|
|
13
126
|
case "PUT":
|
|
14
|
-
router.put(route.path,
|
|
127
|
+
router.put(route.path, ...handlers);
|
|
15
128
|
break;
|
|
16
129
|
case "DELETE":
|
|
17
|
-
router.delete(route.path,
|
|
130
|
+
router.delete(route.path, ...handlers);
|
|
18
131
|
break;
|
|
19
132
|
case "PATCH":
|
|
20
|
-
router.patch(route.path,
|
|
133
|
+
router.patch(route.path, ...handlers);
|
|
21
134
|
break;
|
|
22
135
|
}
|
|
23
136
|
}
|
|
137
|
+
if (hooks.errorHandler !== false) {
|
|
138
|
+
router.use(hooks.errorHandler ?? errorHandler);
|
|
139
|
+
}
|
|
24
140
|
return router;
|
|
25
141
|
}
|
|
26
142
|
//# sourceMappingURL=routes.js.map
|
package/dist/routes.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"routes.js","sourceRoot":"","sources":["../src/routes.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EACd,MAAM,GAKP,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA8D3C;;;GAGG;AACH,SAAS,gBAAgB,CACvB,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chema?(): JSONSchema7;
|
|
12
12
|
}
|
|
13
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Decodes a non-JSON, non-form request body into the value that `S` then
|
|
15
|
+
* validates via `Body<S, C>`. `contentType` must be a literal-initialized
|
|
16
|
+
* property (not a getter) — same constraint as `ResponseCodec`, for the same
|
|
17
|
+
* reason: codegen resolves it statically to build the `OpenAPI` spec (runtime
|
|
18
|
+
* body-parser selection always reads `contentType`/calls `decode` off the
|
|
19
|
+
* object itself).
|
|
20
|
+
*/
|
|
21
|
+
export interface RequestCodec<T> {
|
|
22
|
+
readonly contentType: string;
|
|
23
|
+
decode(raw: Buffer): T;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Validates `req.body` against `S`. The optional second type argument `C`
|
|
27
|
+
* decodes the raw request body with a `RequestCodec` first instead of
|
|
28
|
+
* assuming JSON — `bellowsRoutes` mounts `express.raw()` scoped to
|
|
29
|
+
* `C.contentType` for the route and calls `C.decode()` before validation.
|
|
30
|
+
* `C` must decode into exactly the type `S` validates — this is enforced at
|
|
31
|
+
* compile time by the `RequestCodec<Body<S>>` bound.
|
|
32
|
+
*
|
|
33
|
+
* ```ts
|
|
34
|
+
* const twimlRequestCodec: RequestCodec<GatherCallback> = {
|
|
35
|
+
* contentType: "application/xml",
|
|
36
|
+
* decode: parseTwimlRequest,
|
|
37
|
+
* };
|
|
38
|
+
*
|
|
39
|
+
* @Post("/webhooks/gather")
|
|
40
|
+
* gather(body: Body<typeof GatherCallbackSchema, typeof twimlRequestCodec>): void { ... }
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export type Body<S extends Validator<unknown>, C extends RequestCodec<S extends Validator<infer T> ? T : never> = never> = S extends Validator<infer T> ? T : never;
|
|
14
44
|
export type Query<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
|
|
15
45
|
export type Params<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
|
|
16
46
|
export type Responds<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
|
|
47
|
+
/**
|
|
48
|
+
* `application/x-www-form-urlencoded` counterpart to `Body<S>` — validates
|
|
49
|
+
* `req.body` the same way, but tells codegen/OpenAPI the route expects a form
|
|
50
|
+
* body instead of JSON, and to mount `express.urlencoded()` for the route.
|
|
51
|
+
*/
|
|
52
|
+
export type FormBody<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
|
|
53
|
+
/** Validates `req.headers` against `S`. Keys must be lower-case, matching
|
|
54
|
+
* Node/Express's own header casing (e.g. `"x-twilio-signature"`). */
|
|
55
|
+
export type Headers<S extends Validator<unknown>> = S extends Validator<infer T> ? T : never;
|
|
56
|
+
/**
|
|
57
|
+
* Injects the raw, unparsed request body bytes captured before any body
|
|
58
|
+
* parsing. `bellowsRoutes` populates `req.rawBody` for any route that
|
|
59
|
+
* declares this param, via a `verify` callback on whichever body-parser it
|
|
60
|
+
* mounts for the route (`express.raw()` if `RawBody` is the only body param
|
|
61
|
+
* declared, `express.json()`/`express.urlencoded()` if paired with `Body<S>`/
|
|
62
|
+
* `FormBody<S>`).
|
|
63
|
+
*/
|
|
64
|
+
export type RawBody = Buffer;
|
|
65
|
+
/**
|
|
66
|
+
* Serializes a validated `Responds<S>` value into a non-JSON response body.
|
|
67
|
+
* `contentType` must be a literal-initialized property (not a getter) —
|
|
68
|
+
* codegen resolves it statically to build the `OpenAPI` spec, so a computed
|
|
69
|
+
* value can't be read at build time.
|
|
70
|
+
*/
|
|
71
|
+
export interface ResponseCodec<T> {
|
|
72
|
+
readonly contentType: string;
|
|
73
|
+
encode(value: T): string | Buffer;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Like `Responds<S>`, but serializes the validated return value with `C`
|
|
77
|
+
* instead of `res.json()`. `C` must encode exactly the type `S` validates —
|
|
78
|
+
* this is enforced at compile time by the `ResponseCodec<Responds<S>>` bound.
|
|
79
|
+
*
|
|
80
|
+
* ```ts
|
|
81
|
+
* const twimlCodec: ResponseCodec<TwimlResponse> = {
|
|
82
|
+
* contentType: "application/xml",
|
|
83
|
+
* encode: renderTwiml,
|
|
84
|
+
* };
|
|
85
|
+
*
|
|
86
|
+
* @Post("/webhooks/gather")
|
|
87
|
+
* async gather(req: Request): Promise<Produces<typeof TwimlResponseSchema, typeof twimlCodec>> { ... }
|
|
88
|
+
* ```
|
|
89
|
+
*/
|
|
90
|
+
export type Produces<S extends Validator<unknown>, C extends ResponseCodec<Responds<S>>> = Responds<S>;
|
|
17
91
|
export declare function withJsonSchema<T>(validator: Validator<T>, schema: JSONSchema7): Validator<T> & {
|
|
18
92
|
jsonSchema(): JSONSchema7;
|
|
19
93
|
};
|
package/dist/schema.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,YAAY,EAAE,WAAW,EAAE,CAAC;AAE5B,MAAM,WAAW,SAAS,CAAC,CAAC;IAC1B,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,IAAI,EAAE,CAAC,CAAA;KAAE,GAAG;QAAE,OAAO,EAAE,KAAK,CAAC;QAAC,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC;IAC3F,UAAU,CAAC,IAAI,WAAW,CAAC;CAC5B;AAED,MAAM,MAAM,
|
|
1
|
+
{"version":3,"file":"schema.d.ts","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,YAAY,EAAE,WAAW,EAAE,CAAC;AAE5B,MAAM,WAAW,SAAS,CAAC,CAAC;IAC1B,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG;QAAE,OAAO,EAAE,IAAI,CAAC;QAAC,IAAI,EAAE,CAAC,CAAA;KAAE,GAAG;QAAE,O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AAC,IAAI,CAAC,SAAS,SAAS,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;AAE7F;;;;;;;GAOG;AACH,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC;AAE7B;;;;;GAKG;AACH,MAAM,WAAW,aAAa,CAAC,CAAC;IAC9B,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,MAAM,CAAC,KAAK,EAAE,CAAC,GAAG,MAAM,GAAG,MAAM,CAAC;CACnC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,MAAM,QAAQ,CAClB,CAAC,SAAS,SAAS,CAAC,OAAO,CAAC,EAC5B,CAAC,SAAS,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAClC,QAAQ,CAAC,CAAC,CAAC,CAAC;AAEhB,wBAAgB,cAAc,CAAC,CAAC,EAC9B,SAAS,EAAE,SAAS,CAAC,CAAC,CAAC,EACvB,MAAM,EAAE,WAAW,GAClB,SAAS,CAAC,CAAC,CAAC,GAAG;IAAE,UAAU,IAAI,WAAW,CAAA;CAAE,CAK9C"}
|
package/dist/schema.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"schema.js","sourceRoot":"","sources":["../src/schema.ts"],"names":[],"mappings":"AAoGA,MAAM,UAAU,cAAc,CAC5B,SAAuB,EACvB,MAAmB;IAEnB,OAAO;QACL,SAAS,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC;QAChD,UAAU,EAAE,GAAG,EAAE,CAAC,MAAM;KACzB,CAAC;AACJ,CAAC"}
|
package/dist/sse.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Request, Response } from "express";
|
|
2
|
+
export interface SseSendOptions {
|
|
3
|
+
/** `event:` field — the client-side listener name (defaults to `"message"`). */
|
|
4
|
+
event?: string;
|
|
5
|
+
/** `id:` field — sets `EventSource.lastEventId` for reconnects. */
|
|
6
|
+
id?: string;
|
|
7
|
+
/** `retry:` field — reconnection delay in ms the client should use. */
|
|
8
|
+
retry?: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* An `AbortSignal` that fires when the client disconnects (`req`'s underlying
|
|
12
|
+
* socket closes). Shared by `SseStream` and available standalone for handlers
|
|
13
|
+
* that inject `AbortSignal` without an `SseStream` — e.g. a non-SSE chunked
|
|
14
|
+
* streaming handler that only needs disconnect-driven cleanup.
|
|
15
|
+
*/
|
|
16
|
+
export declare function disconnectSignal(req: Request): AbortSignal;
|
|
17
|
+
/**
|
|
18
|
+
* Wraps `res` for a Server-Sent Events route (`@Sse`). Handles the
|
|
19
|
+
* `text/event-stream` handshake, event framing, keep-alive pings, and
|
|
20
|
+
* exposes `signal` so the handler can clean up subscriptions when the
|
|
21
|
+
* client disconnects.
|
|
22
|
+
*
|
|
23
|
+
* Construction does not write anything — call `open()` once the handler is
|
|
24
|
+
* ready to commit to a streaming response (e.g. after validating params).
|
|
25
|
+
*/
|
|
26
|
+
export declare class SseStream {
|
|
27
|
+
private readonly res;
|
|
28
|
+
readonly signal: AbortSignal;
|
|
29
|
+
private closed;
|
|
30
|
+
private keepAliveTimer;
|
|
31
|
+
constructor(res: Response, signal: AbortSignal);
|
|
32
|
+
/**
|
|
33
|
+
* Sets SSE headers and flushes them immediately so the client sees an open
|
|
34
|
+
* connection before the first event. Starts the keep-alive ping interval
|
|
35
|
+
* unless `keepAliveMs` is `false`.
|
|
36
|
+
*/
|
|
37
|
+
open(keepAliveMs?: number | false): this;
|
|
38
|
+
/** Writes one SSE event frame. Objects are JSON-encoded; strings are sent as-is. */
|
|
39
|
+
send(data: unknown, opts?: SseSendOptions): void;
|
|
40
|
+
/** Writes an SSE comment line — invisible to `EventSource` listeners, used for keep-alive. */
|
|
41
|
+
comment(text?: string): void;
|
|
42
|
+
/** Ends the response. Safe to call more than once, or after client disconnect. */
|
|
43
|
+
close(): void;
|
|
44
|
+
private teardown;
|
|
45
|
+
}
|
|
46
|
+
//# sourceMappingURL=sse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAKjD,MAAM,WAAW,cAAc;IAC7B,gFAAgF;IAChF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,mEAAmE;IACnE,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,uEAAuE;IACvE,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,GAAG,WAAW,CAI1D;AAED;;;;;;;;GAQG;AACH,qBAAa,SAAS;IAMlB,OAAO,CAAC,QAAQ,CAAC,GAAG;IALtB,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,cAAc,CAA6C;gBAGhD,GAAG,EAAE,QAAQ,EAC9B,MAAM,EAAE,WAAW;IAMrB;;;;OAIG;IACH,IAAI,CAAC,WAAW,GAAE,MAAM,GAAG,KAA4B,GAAG,IAAI;IAiB9D,oFAAoF;IACpF,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,GAAE,cAAmB,GAAG,IAAI;IAWpD,8FAA8F;IAC9F,OAAO,CAAC,IAAI,SAAK,GAAG,IAAI;IAKxB,kFAAkF;IAClF,KAAK,IAAI,IAAI;IAMb,OAAO,CAAC,QAAQ;CAKjB"}
|
package/dist/sse.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/** Default interval for keep-alive comment pings, in milliseconds. */
|
|
2
|
+
const DEFAULT_KEEPALIVE_MS = 15_000;
|
|
3
|
+
/**
|
|
4
|
+
* An `AbortSignal` that fires when the client disconnects (`req`'s underlying
|
|
5
|
+
* socket closes). Shared by `SseStream` and available standalone for handlers
|
|
6
|
+
* that inject `AbortSignal` without an `SseStream` — e.g. a non-SSE chunked
|
|
7
|
+
* streaming handler that only needs disconnect-driven cleanup.
|
|
8
|
+
*/
|
|
9
|
+
export function disconnectSignal(req) {
|
|
10
|
+
const controller = new AbortController();
|
|
11
|
+
req.on("close", () => controller.abort());
|
|
12
|
+
return controller.signal;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Wraps `res` for a Server-Sent Events route (`@Sse`). Handles the
|
|
16
|
+
* `text/event-stream` handshake, event framing, keep-alive pings, and
|
|
17
|
+
* exposes `signal` so the handler can clean up subscriptions when the
|
|
18
|
+
* client disconnects.
|
|
19
|
+
*
|
|
20
|
+
* Construction does not write anything — call `open()` once the handler is
|
|
21
|
+
* ready to commit to a streaming response (e.g. after validating params).
|
|
22
|
+
*/
|
|
23
|
+
export class SseStream {
|
|
24
|
+
res;
|
|
25
|
+
signal;
|
|
26
|
+
closed = false;
|
|
27
|
+
keepAliveTimer;
|
|
28
|
+
constructor(res, signal) {
|
|
29
|
+
this.res = res;
|
|
30
|
+
this.signal = signal;
|
|
31
|
+
signal.addEventListener("abort", () => this.teardown());
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Sets SSE headers and flushes them immediately so the client sees an open
|
|
35
|
+
* connection before the first event. Starts the keep-alive ping interval
|
|
36
|
+
* unless `keepAliveMs` is `false`.
|
|
37
|
+
*/
|
|
38
|
+
open(keepAliveMs = DEFAULT_KEEPALIVE_MS) {
|
|
39
|
+
if (this.res.headersSent)
|
|
40
|
+
return this;
|
|
41
|
+
this.res.status(200);
|
|
42
|
+
this.res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
|
43
|
+
this.res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
44
|
+
this.res.setHeader("Connection", "keep-alive");
|
|
45
|
+
// Disables response buffering on nginx-fronted deployments, which would
|
|
46
|
+
// otherwise hold the stream open with no bytes reaching the client.
|
|
47
|
+
this.res.setHeader("X-Accel-Buffering", "no");
|
|
48
|
+
this.res.flushHeaders();
|
|
49
|
+
if (keepAliveMs !== false) {
|
|
50
|
+
this.keepAliveTimer = setInterval(() => this.comment("ping"), keepAliveMs);
|
|
51
|
+
this.keepAliveTimer.unref?.();
|
|
52
|
+
}
|
|
53
|
+
return this;
|
|
54
|
+
}
|
|
55
|
+
/** Writes one SSE event frame. Objects are JSON-encoded; strings are sent as-is. */
|
|
56
|
+
send(data, opts = {}) {
|
|
57
|
+
if (this.closed)
|
|
58
|
+
return;
|
|
59
|
+
let frame = "";
|
|
60
|
+
if (opts.id !== undefined)
|
|
61
|
+
frame += `id: ${opts.id}\n`;
|
|
62
|
+
if (opts.event !== undefined)
|
|
63
|
+
frame += `event: ${opts.event}\n`;
|
|
64
|
+
if (opts.retry !== undefined)
|
|
65
|
+
frame += `retry: ${opts.retry}\n`;
|
|
66
|
+
const payload = typeof data === "string" ? data : JSON.stringify(data);
|
|
67
|
+
for (const line of payload.split("\n"))
|
|
68
|
+
frame += `data: ${line}\n`;
|
|
69
|
+
this.res.write(`${frame}\n`);
|
|
70
|
+
}
|
|
71
|
+
/** Writes an SSE comment line — invisible to `EventSource` listeners, used for keep-alive. */
|
|
72
|
+
comment(text = "") {
|
|
73
|
+
if (this.closed)
|
|
74
|
+
return;
|
|
75
|
+
this.res.write(`: ${text}\n\n`);
|
|
76
|
+
}
|
|
77
|
+
/** Ends the response. Safe to call more than once, or after client disconnect. */
|
|
78
|
+
close() {
|
|
79
|
+
if (this.closed)
|
|
80
|
+
return;
|
|
81
|
+
this.teardown();
|
|
82
|
+
this.res.end();
|
|
83
|
+
}
|
|
84
|
+
teardown() {
|
|
85
|
+
if (this.closed)
|
|
86
|
+
return;
|
|
87
|
+
this.closed = true;
|
|
88
|
+
if (this.keepAliveTimer)
|
|
89
|
+
clearInterval(this.keepAliveT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YAAE,OAAO;QACxB,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,IAAI,MAAM,CAAC,CAAC;IAClC,CAAC;IAED,kFAAkF;IAClF,KAAK;QACH,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,IAAI,CAAC,QAAQ,EAAE,CAAC;QAChB,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC;IACjB,CAAC;IAEO,QAAQ;QACd,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO;QACxB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,IAAI,IAAI,CAAC,cAAc;YAAE,aAAa,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IAC9D,CAAC;CACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anvil-di/bellows",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.6",
|
|
4
4
|
"description": "Runtime types and decorator stubs for anvil-bellows NestJS-style controller codegen.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"src"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@anvil-di/bellows-cli": "0.0.
|
|
21
|
+
"@anvil-di/bellows-cli": "0.0.6"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
24
|
"express": ">=4"
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/express": "^5.0.0",
|
|
28
28
|
"@types/json-schema": "^7.0.15",
|
|
29
|
+
"express": "^5.0.0",
|
|
29
30
|
"typescript": "^5.7.2",
|
|
30
31
|
"vitest": "^2.1.8",
|
|
31
32
|
"zod": "^3.23.0"
|
package/src/authz.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Request } from "express";
|
|
2
|
+
|
|
3
|
+
export interface AuthnResult<U = unknown> {
|
|
4
|
+
identified: boolean;
|
|
5
|
+
user?: U;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* `Scheme` is never evaluated at runtime — it's read directly off the
|
|
10
|
+
* `implements AuthnService<User, "bearerAuth">` clause by anvil-bellows'
|
|
11
|
+
* codegen to populate the OpenAPI `security` requirement for routes that
|
|
12
|
+
* declare this service via `@Authn(...)`.
|
|
13
|
+
*/
|
|
14
|
+
export interface AuthnService<U = unknown, Scheme extends string = never> {
|
|
15
|
+
identify(req: Request): AuthnResult<U> | Promise<AuthnResult<U>>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type AuthzDecision = "allow" | "deny" | "next";
|
|
19
|
+
|
|
20
|
+
export interface AuthzService {
|
|
21
|
+
authorize(req: Request, user: unknown): AuthzDecision | Promise<AuthzDecision>;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Marks a handler parameter for injection of the identified user
|
|
26
|
+
* (`res.locals.user`, set by the route's `@Authn` cascade). `T` is a pure
|
|
27
|
+
* type-level marker — anvil-bellows' codegen statically verifies `T`
|
|
28
|
+
* identity-matches the `U` declared by every `@Authn` service on the route
|
|
29
|
+
* (`implements AuthnService<U, Scheme>`), rejecting the route at build time
|
|
30
|
+
* if they disagree or can't be resolved. At runtime this is just `T`.
|
|
31
|
+
*/
|
|
32
|
+
export type AuthnUser<T> = T;
|
package/src/decorators.ts
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import type { RequestHandler } from "express";
|
|
2
|
+
import type { AuthnService, AuthzService } from "./authz.js";
|
|
2
3
|
|
|
3
4
|
export type ExpressMiddleware = RequestHandler;
|
|
4
5
|
|
|
6
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
7
|
+
type AuthnServiceClass = new (...args: never[]) => AuthnService<any, any>;
|
|
8
|
+
type AuthzServiceClass = new (...args: never[]) => AuthzService;
|
|
9
|
+
|
|
5
10
|
export function Controller(
|
|
6
11
|
_path: string,
|
|
7
12
|
): <T extends abstract new (...args: never[]) => unknown>(
|
|
@@ -56,20 +61,30 @@ export function Patch(
|
|
|
56
61
|
return (target, _ctx) => target;
|
|
57
62
|
}
|
|
58
63
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
export function Middleware(
|
|
68
|
-
...fns: ExpressMiddleware[]
|
|
64
|
+
/**
|
|
65
|
+
* Marks a route as a Server-Sent Events stream (`text/event-stream`) rather
|
|
66
|
+
* than a buffered JSON response. Registered as a `GET` route. The handler
|
|
67
|
+
* must return `void`/`Promise<void>` and manages the connection itself via
|
|
68
|
+
* an injected `SseStream` param — see `@anvil-di/bellows`'s `SseStream`.
|
|
69
|
+
*/
|
|
70
|
+
export function Sse(
|
|
71
|
+
_path: string,
|
|
69
72
|
): <This, Args extends readonly unknown[], Return>(
|
|
70
73
|
target: (this: This, ...args: Args) => Return,
|
|
71
74
|
ctx: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
|
|
72
|
-
) => (this: This, ...args: Args) => Return
|
|
75
|
+
) => (this: This, ...args: Args) => Return {
|
|
76
|
+
return (target, _ctx) => target;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Usable as either a class or method decorator: `@Middleware(fn) class Ctrl {}`
|
|
81
|
+
* or `@Middleware(fn) handler() {}`. Deliberately has no typed overloads —
|
|
82
|
+
* TS's decorator-overload resolution always binds the first matching
|
|
83
|
+
* signature regardless of the actual target, so a class-decorator overload
|
|
84
|
+
* and a method-decorator overload with identical outer parameter lists can't
|
|
85
|
+
* coexist (whichever is declared second fails to typecheck at its call
|
|
86
|
+
* sites). A single loosely-typed signature checks correctly at both.
|
|
87
|
+
*/
|
|
73
88
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
74
89
|
export function Middleware(..._fns: ExpressMiddleware[]): any {
|
|
75
90
|
return (target: unknown) => target;
|
|
@@ -94,25 +109,33 @@ export function Returns(
|
|
|
94
109
|
return (target, _ctx) => target;
|
|
95
110
|
}
|
|
96
111
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
target: T,
|
|
102
|
-
ctx: ClassDecoratorContext<T>,
|
|
103
|
-
) => T;
|
|
104
|
-
// Method-decorator overload: `@Security("bearer") handler() {}`
|
|
105
|
-
export function Security(
|
|
106
|
-
scheme: string,
|
|
107
|
-
): <This, Args extends readonly unknown[], Return>(
|
|
108
|
-
target: (this: This, ...args: Args) => Return,
|
|
109
|
-
ctx: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return>,
|
|
110
|
-
) => (this: This, ...args: Args) => Return;
|
|
112
|
+
/**
|
|
113
|
+
* Usable as either a class or method decorator — see the note on
|
|
114
|
+
* `Middleware`'s signature above for why this has no typed overloads.
|
|
115
|
+
*/
|
|
111
116
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
112
117
|
export function Security(_scheme: string): any {
|
|
113
118
|
return (target: unknown) => target;
|
|
114
119
|
}
|
|
115
120
|
|
|
121
|
+
/**
|
|
122
|
+
* Usable as either a class or method decorator — see the note on
|
|
123
|
+
* `Middleware`'s signature above for why this has no typed overloads.
|
|
124
|
+
*/
|
|
125
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
126
|
+
export function Authn(..._services: AuthnServiceClass[]): any {
|
|
127
|
+
return (target: unknown) => target;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Usable as either a class or method decorator — see the note on
|
|
132
|
+
* `Middleware`'s signature above for why this has no typed overloads.
|
|
133
|
+
*/
|
|
134
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
135
|
+
export function Authz(..._services: AuthzServiceClass[]): any {
|
|
136
|
+
return (target: unknown) => target;
|
|
137
|
+
}
|
|
138
|
+
|
|
116
139
|
export function Deprecated(
|
|
117
140
|
_reason?: string,
|
|
118
141
|
): <This, Args extends readonly unknown[], Return>(
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { Authn, Authz, Middleware, Security } from "./decorators.js";
|
|
3
|
+
import type { AuthnResult, AuthnService, AuthzDecision, AuthzService } from "./authz.js";
|
|
4
|
+
|
|
5
|
+
// Regression test for a TS decorator-overload bug: `Authn`/`Authz`/`Middleware`/
|
|
6
|
+
// `Security` must typecheck when applied as BOTH a class decorator and a
|
|
7
|
+
// method decorator in the same compilation unit. Overloaded signatures with
|
|
8
|
+
// identical outer parameter lists can't be disambiguated by TS's decorator
|
|
9
|
+
// checker (it always binds the first match regardless of target), so these
|
|
10
|
+
// decorators are intentionally loosely typed — this file exists to catch a
|
|
11
|
+
// regression to typed overloads at compile time.
|
|
12
|
+
|
|
13
|
+
class NoopAuthn implements AuthnService<{ id: string }, "bearerAuth"> {
|
|
14
|
+
identify(): AuthnResult<{ id: string }> {
|
|
15
|
+
return { identified: false };
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
class NoopAuthz implements AuthzService {
|
|
20
|
+
authorize(): AuthzDecision {
|
|
21
|
+
return "next";
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const noopMiddleware = (_req: unknown, _res: unknown, next: () => void): void => next();
|
|
26
|
+
|
|
27
|
+
@Authn(NoopAuthn)
|
|
28
|
+
@Authz(NoopAuthz)
|
|
29
|
+
@Middleware(noopMiddleware)
|
|
30
|
+
@Security("bearerAuth")
|
|
31
|
+
class ClassLevelController {
|
|
32
|
+
@Authn(NoopAuthn)
|
|
33
|
+
@Authz(NoopAuthz)
|
|
34
|
+
@Middleware(noopMiddleware)
|
|
35
|
+
@Security("bearerAuth")
|
|
36
|
+
handler(): void {}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
describe("dual class/method decorators", () => {
|
|
40
|
+
it("compiles and constructs at both levels", () => {
|
|
41
|
+
expect(new ClassLevelController()).toBeInstanceOf(ClassLevelController);
|
|
42
|
+
});
|
|
43
|
+
});
|