@jini-ai/http-kit 0.7.3-next.2 → 0.7.3-next.3

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 CHANGED
@@ -23,6 +23,7 @@ There is no daemon, agent-runtime or CMS dependency.
23
23
  - Origin and bearer guards, including core's canonical origin validation and Node token comparison.
24
24
  - Cursor-aware and raw SSE primitives, route registration inventory and `mountPackHttp`.
25
25
  - `./rate-limit`, `./middleware`, `./observability` and `./range`.
26
+ - `./dev-proxy` exports `createDevProxyRequestHandler({ devProxyUrl, basePath })`, `createDevProxyUpgradeListener({ devProxyUrl, basePath })` (the host decides whether to attach it; the module reads no environment), `resolveDevProxyPath({ url, basePath })` and `stripHopByHopHeaders(headers)`: a streaming same-origin reverse proxy to a frontend dev server, including the WebSocket HMR upgrade.
26
27
 
27
28
  - `rate-limit` exports `createRateLimiter({ profile, clock, store })`,
28
29
  `createMemoryCounterStore({})`, and `resolveClientIp({ source, policy })`.
@@ -72,9 +73,57 @@ The async limiter uses core `Clock.nowMs()` and keeps non-empty-key validation.
72
73
  requests; route labels are read at response completion.
73
74
 
74
75
 
76
+ ## Wiring
77
+
78
+ `mountJsonRoute({ app, spec, deps })` takes a server-neutral spec (`defineJsonRoute`, from
79
+ `@jini-ai/core/contracts/server`) plus the route's own small deps type; host policy arrives as
80
+ `spec.ports` (`workspace`, `authenticate`, `authorize`, `onError`, `onReturnedError`). A handler
81
+ calls `authorize({ permission, entityType }, { entityId })` at its chosen point; a by-id route
82
+ passes `entityId` and the port receives it as its second argument, while an id-free call reaches
83
+ the port with the required arguments alone. Example: the CMS redirects specs, mounted by a host
84
+ whose `authorize` port hands `entityId` to its RBAC check. `entityType` is optional; when the
85
+ handler omits it the port's arguments carry no `entityType` key.
86
+
87
+ Request context and replies (opt-in per spec; a spec that declares none behaves exactly as before):
88
+
89
+ - `readHeaders: ['Idempotency-Key']` hands `raw.headers` (lower-cased keys, absent headers left out).
90
+ - `requestFacts: true` hands `raw.facts`, resolved per request by the host's injected
91
+ `ports.requestFacts({ req, deps })` (its proxy-trust answer). Mounting such a spec without that
92
+ port throws at mount time.
93
+ - `responseHeaders: { 'cache-control': 'no-store' }` is set on every answer of the route, before
94
+ the body cap and workspace gates, so refusals carry it too.
95
+ - A handler returns core's `routeReply({ status, body?, headers? })` for 429 + `Retry-After`,
96
+ 304 + `ETag`, or a bare 204: headers are set, and with no `body` the answer is `res.status(s).send()`.
97
+ - A raw spec's `raw.readBody({ type: 'raw', mediaType, limit })` / `({ type: 'urlencoded', limit })` reads
98
+ the body only when the handler calls it — after its gates — through Express's own `raw` / `urlencoded`
99
+ parser (never inflating), answering `{ ok, value }` or a neutral `refusal` (`too-large` with its limit,
100
+ `media-type`, `unsupported-encoding`, `malformed`, `aborted`, `size-mismatch`, `unreadable`, and
101
+ `incompatible-read` for a later call whose options differ from the first, since the stream is read
102
+ once; identical options reuse the first outcome). The host
103
+ registers NO parser ahead of such a mount; one registered ahead still wins (the read reports its body).
104
+
105
+ Raw routes: `mountRawRoute({ app, spec, deps, adapter })` with a `defineRawRoute` spec serves HTML,
106
+ streams, uploads, downloads and redirects that set cookies. It takes the same `ports` and opt-ins
107
+ and runs the same gates in the same order as `mountJsonRoute`; `handle({ raw, deps, context,
108
+ authorize }, { signal })` returns a web `Response`, written back with every header (each
109
+ `Set-Cookie` separately) and its body (streamed, and cancelled when the client leaves). `raw.body`
110
+ is whatever the host's per-route parser left (`express.raw` gives a `Buffer`). It mounts with
111
+ `app[method](path)`, never `app.use`, so route-table inventories see one route per spec.
112
+ A raw spec that sets `bufferedReply: true` is not streamed: its whole body is read and answered through
113
+ Express's `res.send(Buffer)`, so it gets `Content-Length`, the host app's ETag (Express's default weak one)
114
+ and a bodiless 304 for a fresh GET/HEAD (`If-None-Match` / `If-Modified-Since`), exactly as a hand-written
115
+ `res.send` route did (`raw-route-buffered.test.ts` compares both on the wire). Without it nothing changes.
116
+
117
+ A spec whose `successStatus` is a no-content status (204, 205, 304) answers with
118
+ `res.status(status).end()` and no body; every other success status is written through `res.json`.
119
+
75
120
  See [API.md](https://github.com/AINSEP/Jini/blob/main/packages/http-kit/API.md) for required/optional object contracts. Node runtime, ESM only.
76
121
  Apache-2.0; see the repository NOTICE.
77
122
 
123
+ `authenticate` may answer `undefined` when the request carries no principal yet; the handler then
124
+ gets no `context` and the host's `authorize` port decides. A host uses that to keep a body refusal
125
+ from `parse` ahead of its missing-session failure (`adapter-ports.test.ts` pins the order).
126
+
78
127
  ## Design decisions
79
128
 
80
129
  - [Reject ambiguous redirect URLs before normalization](docs/decisions/DR-001-redirect-normalization.md).
@@ -0,0 +1,101 @@
1
+ import type { Request, Response } from 'express';
2
+ import { type RouteInputContext, type ServerApiError } from '@jini-ai/core/contracts/server';
3
+ import type { JsonRoutePorts, JsonRouteSpec, RouteMountOptions, RouteRequestOptIns } from './types.js';
4
+ /**
5
+ * A spec that opts into request facts needs the host's resolver: refusing at mount means a missing
6
+ * port is a boot failure, never a route that silently runs without the client address.
7
+ * @throws When `spec.requestFacts` is set and `spec.ports.requestFacts` is not.
8
+ */
9
+ export declare function assertRequestFactsPort({ spec }: {
10
+ readonly spec: Pick<RouteRequestOptIns, 'requestFacts'> & {
11
+ readonly path: string;
12
+ readonly ports?: {
13
+ readonly requestFacts?: unknown;
14
+ } | undefined;
15
+ };
16
+ }, _optional?: Record<string, never>): void;
17
+ /**
18
+ * The deps one request runs with: the host's `requestDeps` binding (`RouteMountOptions`) evaluated for
19
+ * this request, or the mounted deps unchanged when the mount declared none.
20
+ * @complexity O(1) plus the host binding.
21
+ */
22
+ export declare function requestScopedDeps<Deps>({ req, res, deps }: {
23
+ readonly req: Request;
24
+ readonly res: Response;
25
+ readonly deps: Deps;
26
+ }, { requestDeps }?: Pick<RouteMountOptions<Deps>, 'requestDeps'>): Deps;
27
+ /**
28
+ * The spec's `admittedResponseHeaders` for this request, called right after the workspace port: only an
29
+ * admitted request carries them, so the workspace refusal (a throw from that port) never does.
30
+ * Synchronous, so a mount without a workspace port keeps its tick order (adapter-pins.test.ts).
31
+ * @complexity O(h) in the header count.
32
+ */
33
+ export declare function applyAdmittedResponseHeaders({ res, raw, spec }: {
34
+ readonly res: Response;
35
+ readonly raw: RouteInputContext;
36
+ readonly spec: Pick<RouteRequestOptIns, 'admittedResponseHeaders'>;
37
+ }, _optional?: Record<string, never>): void;
38
+ /** Sets static or reply headers; a no-op without any, so a route that declares none writes nothing extra.
39
+ * `Vary` is appended (Express `res.vary`), never overwritten: a host middleware may already vary the
40
+ * answer (dev CORS adds `Origin`), and replacing it would let a cache serve one origin's answer to another. */
41
+ export declare function applyResponseHeaders({ res, headers }: {
42
+ readonly res: Response;
43
+ readonly headers: Readonly<Record<string, string>> | undefined;
44
+ }, _optional?: Record<string, never>): void;
45
+ /**
46
+ * The route's `RouteInputContext` with only the opt-ins its spec declared: `raw.headers` for
47
+ * `readHeaders`, `raw.facts` (resolved by the host port, with `req` and `deps`) for `requestFacts`.
48
+ * Synchronous, so the gates after it keep their tick order.
49
+ */
50
+ export declare function routeRequestInput<Deps, Context>({ req, spec, deps }: {
51
+ readonly req: Request;
52
+ readonly spec: Pick<RouteRequestOptIns, 'readHeaders' | 'requestFacts'> & {
53
+ readonly ports?: JsonRoutePorts<Deps, Context> | undefined;
54
+ };
55
+ readonly deps: Deps;
56
+ }, _optional?: Record<string, never>): RouteInputContext;
57
+ /**
58
+ * Enforces the spec's `maxBodyBytes`, answering 413 with core's plain-words refusal when exceeded.
59
+ * Why here and not in the parser: the host's `express.json()` already read the body with its own,
60
+ * usually larger, limit, and a second parser skips a parsed body — so without this check the
61
+ * route's declared ceiling was silently lost. The body is measured re-serialized, the same bytes
62
+ * core's `jsonRoute` limits when mounted behind `node-bridge`, so both mount paths agree. A spec
63
+ * cap above the host parser's limit is effectively clamped to it: the parser refuses first.
64
+ * GET/HEAD are exempt, as in core.
65
+ * The host's `ports.payloadTooLarge`, when mounted, writes the 413 instead of core's envelope.
66
+ * @returns `false` when the refusal was written and the route must stop.
67
+ * @complexity O(n) in the body size for the re-serialization; only when a cap is declared.
68
+ */
69
+ export declare function allowRouteBody({ req, res, spec }: {
70
+ readonly req: Request;
71
+ readonly res: Response;
72
+ readonly spec: Pick<JsonRouteSpec<unknown, unknown, unknown>, 'maxBodyBytes'> & {
73
+ readonly ports?: {
74
+ readonly payloadTooLarge?: JsonRoutePorts<unknown>['payloadTooLarge'];
75
+ } | undefined;
76
+ };
77
+ }, _optional?: Record<string, never>): boolean;
78
+ /** A body over the spec's cap: the ceiling it broke and core's refusal for it. */
79
+ interface BodyRefusal {
80
+ readonly maxBytes: number;
81
+ readonly error: ServerApiError;
82
+ }
83
+ /** The body-cap decision of {@link allowRouteBody} without the write, so reporter mode can end the
84
+ * operation before the 413 goes out. `undefined` admits the request. */
85
+ export declare function routeBodyRefusal({ req, spec }: {
86
+ readonly req: Request;
87
+ readonly spec: Pick<JsonRouteSpec<unknown, unknown, unknown>, 'maxBodyBytes'>;
88
+ }): BodyRefusal | undefined;
89
+ /** Writes a body-cap refusal: the host's own 413 body when `ports.payloadTooLarge` is mounted (its
90
+ * admin client reads it); absent, core's envelope is unchanged. */
91
+ export declare function writeBodyRefusal({ res, spec, refusal }: {
92
+ readonly res: Response;
93
+ readonly spec: {
94
+ readonly ports?: {
95
+ readonly payloadTooLarge?: JsonRoutePorts<unknown>['payloadTooLarge'];
96
+ } | undefined;
97
+ };
98
+ readonly refusal: BodyRefusal;
99
+ }): void;
100
+ export {};
101
+ //# sourceMappingURL=adapter-request.d.ts.map
@@ -0,0 +1,100 @@
1
+ import { payloadTooLargeError, statusForError } from '@jini-ai/core/contracts/server';
2
+ import { rawInput } from './request.js';
3
+ import { sendApiError } from './response.js';
4
+ /**
5
+ * A spec that opts into request facts needs the host's resolver: refusing at mount means a missing
6
+ * port is a boot failure, never a route that silently runs without the client address.
7
+ * @throws When `spec.requestFacts` is set and `spec.ports.requestFacts` is not.
8
+ */
9
+ export function assertRequestFactsPort({ spec }, _optional = {}) {
10
+ if (spec.requestFacts && !spec.ports?.requestFacts)
11
+ throw new Error(`route ${spec.path} opts into requestFacts but no requestFacts port is mounted`);
12
+ }
13
+ /**
14
+ * The deps one request runs with: the host's `requestDeps` binding (`RouteMountOptions`) evaluated for
15
+ * this request, or the mounted deps unchanged when the mount declared none.
16
+ * @complexity O(1) plus the host binding.
17
+ */
18
+ export function requestScopedDeps({ req, res, deps }, { requestDeps } = {}) {
19
+ return requestDeps ? requestDeps({ req, res, deps }) : deps;
20
+ }
21
+ /**
22
+ * The spec's `admittedResponseHeaders` for this request, called right after the workspace port: only an
23
+ * admitted request carries them, so the workspace refusal (a throw from that port) never does.
24
+ * Synchronous, so a mount without a workspace port keeps its tick order (adapter-pins.test.ts).
25
+ * @complexity O(h) in the header count.
26
+ */
27
+ export function applyAdmittedResponseHeaders({ res, raw, spec }, _optional = {}) {
28
+ if (spec.admittedResponseHeaders)
29
+ applyResponseHeaders({ res, headers: spec.admittedResponseHeaders(raw) });
30
+ }
31
+ /** Sets static or reply headers; a no-op without any, so a route that declares none writes nothing extra.
32
+ * `Vary` is appended (Express `res.vary`), never overwritten: a host middleware may already vary the
33
+ * answer (dev CORS adds `Origin`), and replacing it would let a cache serve one origin's answer to another. */
34
+ export function applyResponseHeaders({ res, headers }, _optional = {}) {
35
+ if (!headers)
36
+ return;
37
+ for (const [name, value] of Object.entries(headers)) {
38
+ if (name.toLowerCase() === 'vary')
39
+ res.vary(value);
40
+ else
41
+ res.setHeader(name, value);
42
+ }
43
+ }
44
+ /**
45
+ * The route's `RouteInputContext` with only the opt-ins its spec declared: `raw.headers` for
46
+ * `readHeaders`, `raw.facts` (resolved by the host port, with `req` and `deps`) for `requestFacts`.
47
+ * Synchronous, so the gates after it keep their tick order.
48
+ */
49
+ export function routeRequestInput({ req, spec, deps }, _optional = {}) {
50
+ const facts = spec.requestFacts ? spec.ports?.requestFacts?.({ req, deps }) : undefined;
51
+ return rawInput({ req }, { ...(spec.readHeaders === undefined ? {} : { headers: spec.readHeaders }), ...(facts === undefined ? {} : { facts }) });
52
+ }
53
+ /** UTF-8 size of a body the host's parser already read: the bytes themselves, or its JSON re-serialization. */
54
+ function parsedBodyBytes(body) {
55
+ if (body === undefined || body === null)
56
+ return 0;
57
+ if (body instanceof Uint8Array)
58
+ return body.byteLength;
59
+ return new TextEncoder().encode(typeof body === 'string' ? body : JSON.stringify(body)).byteLength;
60
+ }
61
+ /**
62
+ * Enforces the spec's `maxBodyBytes`, answering 413 with core's plain-words refusal when exceeded.
63
+ * Why here and not in the parser: the host's `express.json()` already read the body with its own,
64
+ * usually larger, limit, and a second parser skips a parsed body — so without this check the
65
+ * route's declared ceiling was silently lost. The body is measured re-serialized, the same bytes
66
+ * core's `jsonRoute` limits when mounted behind `node-bridge`, so both mount paths agree. A spec
67
+ * cap above the host parser's limit is effectively clamped to it: the parser refuses first.
68
+ * GET/HEAD are exempt, as in core.
69
+ * The host's `ports.payloadTooLarge`, when mounted, writes the 413 instead of core's envelope.
70
+ * @returns `false` when the refusal was written and the route must stop.
71
+ * @complexity O(n) in the body size for the re-serialization; only when a cap is declared.
72
+ */
73
+ export function allowRouteBody({ req, res, spec }, _optional = {}) {
74
+ const refusal = routeBodyRefusal({ req, spec });
75
+ if (!refusal)
76
+ return true;
77
+ writeBodyRefusal({ res, spec, refusal });
78
+ return false;
79
+ }
80
+ /** The body-cap decision of {@link allowRouteBody} without the write, so reporter mode can end the
81
+ * operation before the 413 goes out. `undefined` admits the request. */
82
+ export function routeBodyRefusal({ req, spec }) {
83
+ const maxBytes = spec.maxBodyBytes;
84
+ if (maxBytes === undefined || req.method === 'GET' || req.method === 'HEAD')
85
+ return undefined;
86
+ if (parsedBodyBytes(req.body) <= maxBytes)
87
+ return undefined;
88
+ return { maxBytes, error: payloadTooLargeError({ maxBytes }) };
89
+ }
90
+ /** Writes a body-cap refusal: the host's own 413 body when `ports.payloadTooLarge` is mounted (its
91
+ * admin client reads it); absent, core's envelope is unchanged. */
92
+ export function writeBodyRefusal({ res, spec, refusal }) {
93
+ // The host's own 413 body (its admin client reads it); absent, core's envelope below is unchanged.
94
+ if (spec.ports?.payloadTooLarge) {
95
+ spec.ports.payloadTooLarge({ res, maxBytes: refusal.maxBytes });
96
+ return;
97
+ }
98
+ sendApiError({ res, status: statusForError({ error: refusal.error }), error: refusal.error });
99
+ }
100
+ //# sourceMappingURL=adapter-request.js.map
package/dist/adapter.d.ts CHANGED
@@ -3,19 +3,19 @@
3
3
  * `handle`, and response serialization into a single Express route handler. This is the only
4
4
  * file in the module that knows about Express `req`/`res` on the mounting side.
5
5
  */
6
- import type { Express } from 'express';
7
- import { type RouteHostContext } from '@jini-ai/core/contracts/server';
8
- import type { JsonRouteSpec } from './types.js';
6
+ import type { Express, Request, Response } from 'express';
7
+ import { type JsonRouteAuthorize, type RouteHostContext } from '@jini-ai/core/contracts/server';
8
+ import type { JsonRoutePorts, JsonRouteSpec, RouteMountOptions, RouteRequestOptIns, RouteDepsSource } from './types.js';
9
9
  /**
10
10
  * Combines required route fields and optional settings into a fresh spec while pinning its generic
11
11
  * parameters at the definition site so callers do not have to repeat them. Optional settings take
12
12
  * precedence. The returned spec is consumed by `mountJsonRoute` (live)
13
13
  * and by tests (direct invocation of `route.parse` / `route.handle`).
14
- * @param optionalArgs - Origin/success policy and optional injected host ports.
14
+ * @param optionalArgs - Origin/success policy, body ceiling and optional injected host ports.
15
15
  * @returns A fresh route spec; never mutates either argument.
16
16
  * @complexity O(1) time/space for the fixed spec fields.
17
17
  */
18
- export declare function defineJsonRoute<Input, Output, Deps, Context = undefined>(requiredArgs: Omit<JsonRouteSpec<Input, Output, Deps, Context>, 'requireSameOrigin' | 'successStatus' | 'ports'>, optionalArgs?: Pick<JsonRouteSpec<Input, Output, Deps, Context>, 'requireSameOrigin' | 'successStatus' | 'ports'>): JsonRouteSpec<Input, Output, Deps, Context>;
18
+ export declare function defineJsonRoute<Input, Output, Deps, Context = undefined>(requiredArgs: Omit<JsonRouteSpec<Input, Output, Deps, Context>, 'requireSameOrigin' | 'successStatus' | 'ports' | 'maxBodyBytes'>, optionalArgs?: Pick<JsonRouteSpec<Input, Output, Deps, Context>, 'requireSameOrigin' | 'successStatus' | 'ports' | 'maxBodyBytes' | keyof RouteRequestOptIns>): JsonRouteSpec<Input, Output, Deps, Context>;
19
19
  /**
20
20
  * Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
21
21
  * about req/res; the route's parse and handle functions operate on `RouteInputContext` and
@@ -25,10 +25,34 @@ export declare function defineJsonRoute<Input, Output, Deps, Context = undefined
25
25
  * @returns Void; registers one handler, without starting a listener.
26
26
  * @complexity O(1) setup and per-request overhead, plus parsing, host ports and handling.
27
27
  */
28
- export declare function mountJsonRoute<Input, Output, Deps, Context = undefined>({ app, spec, deps, adapter }: {
28
+ export declare function mountJsonRoute<Input, Output, Deps, Context = undefined>(required: {
29
29
  readonly app: Express;
30
30
  readonly spec: JsonRouteSpec<Input, Output, Deps, Context>;
31
- readonly deps: Deps;
32
31
  readonly adapter?: RouteHostContext;
32
+ } & RouteDepsSource<Deps>, optional?: RouteMountOptions<Deps>): void;
33
+ /**
34
+ * The `authorize` a handler calls. The route chooses where authorization occurs: reads may
35
+ * authorize before validation, while writes must reject an inconsistent tenant target before
36
+ * asking for a permission. A by-id route's scope (`entityId`) reaches the host port; an id-free
37
+ * call reaches it with the required arguments alone, exactly as before scopes existed. Likewise an
38
+ * `entityType` reaches it only when the handler named one (list-style permissions name none).
39
+ * @complexity O(1) plus the injected host authorizer.
40
+ */
41
+ export declare function routeAuthorize<Deps, Context>({ ports, deps, context }: {
42
+ readonly ports: JsonRoutePorts<Deps, Context> | undefined;
43
+ readonly deps: Deps;
44
+ readonly context: Context | undefined;
45
+ }, _optional?: Record<string, never>): JsonRouteAuthorize;
46
+ export declare function allowRouteOrigin({ req, res, spec, adapter }: {
47
+ readonly req: Request;
48
+ readonly res: Response;
49
+ readonly spec: Pick<JsonRouteSpec<unknown, unknown, unknown>, 'requireSameOrigin'>;
50
+ readonly adapter: RouteHostContext | undefined;
51
+ }, _optional?: Record<string, never>): boolean;
52
+ export declare function sendRouteException<Deps, Context>({ res, spec, adapter, error: e }: {
53
+ readonly res: Response;
54
+ readonly spec: Pick<JsonRouteSpec<unknown, unknown, Deps, Context>, 'method' | 'path' | 'ports'>;
55
+ readonly adapter: RouteHostContext | undefined;
56
+ readonly error: unknown;
33
57
  }, _optional?: Record<string, never>): void;
34
58
  //# sourceMappingURL=adapter.d.ts.map