@jini-ai/http-kit 0.3.7 → 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.
Files changed (92) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +71 -98
  3. package/dist/adapter.d.ts +13 -5
  4. package/dist/adapter.js +17 -15
  5. package/dist/api-security-middleware.d.ts +27 -17
  6. package/dist/api-security-middleware.js +27 -36
  7. package/dist/compat.d.ts +12 -17
  8. package/dist/compat.js +4 -12
  9. package/dist/db-ops.d.ts +3 -3
  10. package/dist/db-ops.js +3 -3
  11. package/dist/delegated-tools.d.ts +31 -78
  12. package/dist/delegated-tools.js +62 -101
  13. package/dist/index.d.ts +140 -59
  14. package/dist/index.js +12 -32
  15. package/dist/local-daemon-request.d.ts +18 -8
  16. package/dist/local-daemon-request.js +23 -32
  17. package/dist/memory.d.ts +1 -1
  18. package/dist/middleware.d.ts +20 -0
  19. package/dist/middleware.js +21 -0
  20. package/dist/observability.d.ts +29 -0
  21. package/dist/observability.js +22 -0
  22. package/dist/origin.d.ts +8 -6
  23. package/dist/origin.js +8 -5
  24. package/dist/pack-http.d.ts +12 -8
  25. package/dist/pack-http.js +3 -3
  26. package/dist/rate-limit.d.ts +97 -0
  27. package/dist/rate-limit.js +94 -0
  28. package/dist/raw-sse.d.ts +7 -2
  29. package/dist/raw-sse.js +6 -7
  30. package/dist/read-only-tools.d.ts +67 -0
  31. package/dist/read-only-tools.js +59 -0
  32. package/dist/remote-run-events.js +1 -1
  33. package/dist/request.d.ts +8 -2
  34. package/dist/request.js +4 -4
  35. package/dist/response.d.ts +16 -4
  36. package/dist/response.js +7 -5
  37. package/dist/route-registration-guard.d.ts +13 -5
  38. package/dist/route-registration-guard.js +6 -6
  39. package/dist/sse.d.ts +25 -9
  40. package/dist/sse.js +10 -10
  41. package/dist/tool-catalog.d.ts +3 -3
  42. package/dist/types.d.ts +15 -13
  43. package/dist/types.js +2 -2
  44. package/dist/verified-origin/configured-origin.d.ts +37 -0
  45. package/dist/verified-origin/configured-origin.js +112 -0
  46. package/dist/verified-origin/index.d.ts +6 -0
  47. package/dist/verified-origin/index.js +5 -0
  48. package/dist/verified-origin/origin.d.ts +65 -0
  49. package/dist/verified-origin/origin.js +151 -0
  50. package/dist/verified-origin/ports.d.ts +40 -0
  51. package/dist/verified-origin/ports.js +2 -0
  52. package/dist/verified-origin/repo.memory.d.ts +34 -0
  53. package/dist/verified-origin/repo.memory.js +34 -0
  54. package/dist/verified-origin/types.d.ts +33 -0
  55. package/dist/verified-origin/types.js +23 -0
  56. package/dist/verified-origin.d.ts +2 -0
  57. package/dist/verified-origin.js +2 -0
  58. package/package.json +36 -9
  59. package/dist/express/run-stream.d.ts +0 -15
  60. package/dist/express/run-stream.js +0 -11
  61. package/dist/express-index.d.ts +0 -32
  62. package/dist/express-index.js +0 -14
  63. package/dist/fastify/adapter.d.ts +0 -31
  64. package/dist/fastify/adapter.js +0 -64
  65. package/dist/fastify/agents.d.ts +0 -13
  66. package/dist/fastify/agents.js +0 -7
  67. package/dist/fastify/api-security-middleware.d.ts +0 -64
  68. package/dist/fastify/api-security-middleware.js +0 -139
  69. package/dist/fastify/compat.d.ts +0 -22
  70. package/dist/fastify/compat.js +0 -16
  71. package/dist/fastify/daemon-status.d.ts +0 -22
  72. package/dist/fastify/daemon-status.js +0 -9
  73. package/dist/fastify/host-tools.d.ts +0 -13
  74. package/dist/fastify/host-tools.js +0 -8
  75. package/dist/fastify/index.d.ts +0 -36
  76. package/dist/fastify/index.js +0 -18
  77. package/dist/fastify/local-daemon-request.d.ts +0 -43
  78. package/dist/fastify/local-daemon-request.js +0 -155
  79. package/dist/fastify/origin.d.ts +0 -21
  80. package/dist/fastify/origin.js +0 -14
  81. package/dist/fastify/request.d.ts +0 -20
  82. package/dist/fastify/request.js +0 -25
  83. package/dist/fastify/response.d.ts +0 -20
  84. package/dist/fastify/response.js +0 -41
  85. package/dist/fastify/route-registration-guard.d.ts +0 -70
  86. package/dist/fastify/route-registration-guard.js +0 -69
  87. package/dist/fastify/run-stream.d.ts +0 -18
  88. package/dist/fastify/run-stream.js +0 -10
  89. package/dist/fastify/runs.d.ts +0 -17
  90. package/dist/fastify/runs.js +0 -33
  91. package/dist/run-stream.d.ts +0 -60
  92. package/dist/run-stream.js +0 -108
package/CHANGELOG.md ADDED
@@ -0,0 +1,171 @@
1
+ # @jini-ai/http-kit
2
+
3
+ ## 0.4.0 — 2026-10-02
4
+
5
+ ### BREAKING
6
+
7
+ - Domain settings and daemon route packs moved to cms/http/settings and daemon/http. Origin validation is canonical in core and the read-only tool gate belongs to daemon.
8
+ - Distribution includes runtime output, release documentation and required assets only. Process records and per-job neutrality checks are no longer part of the package surface.
9
+
10
+ ## Unreleased
11
+
12
+ ### Build compatibility
13
+
14
+ - Align HTTP pack test registrars with core's second-argument contributions API
15
+ and supply the required origin environment variable names in the guard fixture.
16
+
17
+ ### BREAKING — capability-owned HTTP
18
+
19
+ - Daemon route packs, helpers and the live route manifest move to `@jini-ai/daemon/http`.
20
+ - Read-only policy moves to `@jini-ai/daemon/read-only-tools`; delegated policy facades and
21
+ `./read-only-tools` / `./run-credentials` entries are removed.
22
+ - Runtime dependencies no longer include daemon or agent-runtime. Generic request, response
23
+ and origin primitives are public for capability-owned packs.
24
+
25
+ ### HTTP transport consolidation
26
+
27
+ - BREAKING: Move settings routes, contracts and CMS adapters from `./settings` and the
28
+ root barrel to `@jini-ai/cms/http/settings`; remove the CMS dependency.
29
+ - BREAKING: Origin helpers now use core's `{ config, env }` API. Guard contexts require
30
+ explicit environments and host-selected allowed-origin, web-port and bind-host variable names.
31
+ Bearer middleware requires its environment and token configuration in argument one.
32
+ Strict bearer options contain only path exemptions; ambient environment defaults are removed.
33
+ - BREAKING: Remove the compat `sendApiError` and root `sendCompatApiError` writer.
34
+ Use `sendApiError({ res, status, error })` with the retained error constructors.
35
+ - BREAKING: Rename verified-origin's `OriginContext` to `VerifiedOriginRequestContext`;
36
+ rate limiter clocks implement core `nowMs()` instead of `nowIso()`.
37
+ - Reuse core `Result` and bind core's timing-safe comparison port to Node crypto under
38
+ the existing public `timingSafeTokenMatch` name.
39
+ - BREAKING: DB tool registration reads only operations from argument one; policy,
40
+ confirmation and timeout come exclusively from argument two.
41
+ - Preserve async limiting and invalid-key rejection. Regression and parity tests written;
42
+ verification deferred by owner directive.
43
+
44
+ ### HTTP contract corrections
45
+
46
+ - Fix delegated-tool read-only preflight forwarding so unverified registrations
47
+ retain the shared fail-closed refusal.
48
+ - Reject query, fragment and backslash delimiters in local daemon authorities
49
+ before URL parsing can discard or reinterpret them.
50
+ - Finish the DB, memory and tool-catalog argument conversion, including route
51
+ handlers and helper/port calls. Native event-emitter methods retain their ABI.
52
+ DB factory options now work in argument two; inline options remain supported.
53
+ - Return isolated route-inventory entries and use the documented default of 20
54
+ for negative routine-history limits instead of clamping them to 1.
55
+ - Correct pack callback, route-spec construction and attachment rejection docs;
56
+ classified server failures remain redacted. Regression tests are written but
57
+ unrun under the owner's directive. No version bump.
58
+
59
+ ### Integration of extracted subpaths
60
+
61
+ - Complete the Node export/runtime map and root barrels for `./rate-limit`,
62
+ `./middleware`, `./read-only-tools`, `./settings`, `./verified-origin`,
63
+ `./run-credentials`, and `./observability`. Settings uses the existing CMS
64
+ contracts through a new `@jini-ai/cms` dependency; lockfile reconciliation is pending.
65
+ - Add Express adapters for daemon authorization, delegated-body binding, ownership
66
+ and scoped listing over injected policies, plus request tracking over injected hooks.
67
+ - Reconcile protocol error helpers, core read-only classification, payment options,
68
+ media-generation options and cancellation context forwarding. No version bump.
69
+
70
+ ### BREAKING
71
+
72
+ - Existing public functions, factories, constructors, route handlers and local
73
+ ports now use required argument objects and optional argument objects. Call
74
+ handlers with `({ input, deps }, { signal? })`; call registrars with
75
+ `({ app, deps, adapter })`. Export names and response/event formats remain unchanged.
76
+ The earlier signature-compatibility note above predates this conversion.
77
+ - Payment ports accept charge fields followed by optional description; media
78
+ engines accept `{ surface, model }` followed by generation options. Read-only
79
+ ID generators accept `{}`. Verified-origin errors take `{ message }`.
80
+ - Protected `db-ops.ts`, `memory.ts` and `tool-catalog.ts` previously required
81
+ their owner-lane conversion; the HTTP contract corrections above complete it.
82
+ This source integration has not been tested or built; resolve the remaining
83
+ consumer handoff in `INTEGRATION-http-kit.md` before publishing.
84
+
85
+ - Add `./rate-limit` with fixed-window budgets, periodic stale-key eviction,
86
+ required clock/async counter-store ports, and explicit client-IP trust policy.
87
+ - Add `./middleware` with a parsed-JSON byte limit and required host response wording.
88
+ - Add `./read-only-tools` with required registry, executor, denial-ID and message
89
+ ports. Consolidate route and nested-dispatch checks into one fail-closed rule;
90
+ existing delegated-tool names, signatures and messages remain compatible.
91
+
92
+ ## 0.2.1
93
+
94
+ ### Patch Changes
95
+
96
+ - Add top-level `main`/`types` fields alongside the existing `exports` map. A consumer on
97
+ TypeScript's classic `moduleResolution: "node"` (node10) — which ignores `package.json#exports`
98
+ entirely — could not resolve this package's types at all (`TS2307: Cannot find module`) even
99
+ after the previous exports-map fix restored `require()` at runtime; type resolution and runtime
100
+ resolution are separate algorithms. Verified against a real external consumer (whose
101
+ tsconfig uses this legacy resolution mode): adding these two fields, with its tsconfig completely
102
+ unchanged, made the error disappear. Also fixes absolute-path `require()` (distinct from a bare
103
+ specifier, which already worked) for the same reason — `main` was previously absent.
104
+
105
+ Purely additive: every modern resolver (Node's own runtime `exports` resolution, TypeScript's
106
+ `bundler`/`node16`/`nodenext`) prefers `exports` over `main`/`types` when both are present, so
107
+ this changes nothing for a consumer already on a modern resolver.
108
+
109
+ - Updated dependencies
110
+ - @jini-ai/protocol@0.1.2
111
+ - @jini-ai/core@0.1.2
112
+ - @jini-ai/daemon@0.2.1
113
+ - @jini-ai/agent-runtime@0.2.1
114
+ - @jini-ai/platform@0.1.2
115
+
116
+ ## 0.2.0
117
+
118
+ ### Minor Changes
119
+
120
+ - e181b22: Enforce flat-package domain/runtime/admission metadata, invert optional capability dependencies,
121
+ inject failure-contained run-stream encoders, clean up provisional replay subscribers, and add a
122
+ neutral node-host HTTP-extension composition seam.
123
+ - 0d15314: Add a neutral Composer footer slot for host-owned controls, forward an optional host-selected model through every AgentExecutor runtime transport, expose daemon-owned live agent/model discovery with an explicit rescan route, and recognize Claude Code's partial-stream `message_delta` turn boundary so successful stream-json runs close cleanly.
124
+
125
+ ### Patch Changes
126
+
127
+ - Add a `"default"` export condition to every published package's `exports` map — every one of
128
+ them lacked it, which meant `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED` for any
129
+ CommonJS consumer (found via a real external integration attempt; Node needs `require(esm)`
130
+ support, i.e. Node >=22.12, for this to resolve).
131
+
132
+ `@jini-ai/agent-runtime`:
133
+
134
+ - **New**: `RuntimeBuildOptions.permissionMode` (`'bypass' | 'restricted'`) lets a caller opt a
135
+ run OUT of the auto-approve-every-permission-prompt flag every def with one
136
+ (`bypassPermissions` / `--yolo` / `--dangerously-skip-permissions`) previously pushed
137
+ unconditionally, with no way to turn it off. Omitting it keeps today's default (bypass)
138
+ behavior unchanged.
139
+ - **New**: `ClaudeStreamEvent`, `CopilotStreamEvent`, and `QoderEvent` are now real exported
140
+ discriminated unions instead of `Record<string, unknown>` — a real external consumer guessed a
141
+ nonexistent field name (`event.text` instead of the actual `event.delta`) against the old
142
+ untyped sink and silently lost every streamed token with no compile or runtime error.
143
+ - Fixed a doc/implementation mismatch in `claude-stream.ts`: the module doc claimed `tool_result`
144
+ events carry `{ tool_use_id, content, is_error }`; the actual emitted shape is
145
+ `{ toolUseId, content, isError }`.
146
+
147
+ `@jini-ai/daemon`: `AgentExecutorRunInput.permissionMode` forwards the new
148
+ `RuntimeBuildOptions.permissionMode` through to `buildArgs`, so a host can actually reach the new
149
+ opt-out from the daemon's real run-input surface, not just from `@jini-ai/agent-runtime` in
150
+ isolation.
151
+
152
+ `@jini-ai/agentic`: `setAtPointer` no longer throws on a malformed (e.g. missing leading `/`)
153
+ `updateDataModel` path — degrades to a no-op like its sibling `getAtPointer`, matching this
154
+ package's own "a bad binding must not crash the renderer" contract. That path is agent-authored
155
+ wire data with no error boundary above it in any host, so the uncaught throw could unmount an
156
+ entire chat UI from ~40 bytes of malformed input.
157
+
158
+ `@jini-ai/chat-react`: a local (client-resolved) A2UI button action is no longer a silent no-op —
159
+ `A2uiSurfaceCard` now surfaces the resolved value. New `ExtEventErrorBoundary` confines a
160
+ `kind: 'ext'` event group's renderer to its own card instead of letting a render/effect-phase
161
+ throw from agent-controlled content unmount the whole chat root (there was no error boundary
162
+ anywhere in this package or its hosts before this).
163
+
164
+ - Updated dependencies
165
+ - Updated dependencies [e181b22]
166
+ - Updated dependencies [0d15314]
167
+ - @jini-ai/protocol@0.1.1
168
+ - @jini-ai/core@0.1.1
169
+ - @jini-ai/platform@0.1.1
170
+ - @jini-ai/agent-runtime@0.2.0
171
+ - @jini-ai/daemon@0.2.0
package/README.md CHANGED
@@ -1,11 +1,10 @@
1
1
  # @jini-ai/http-kit
2
2
 
3
- A toolkit of composable Express route packs and a JSON-route transport for a `@jini-ai/core`
4
- daemon composition: request parsing, response serialization, a same-origin guard, SSE streaming,
5
- and a ready-to-mount set of kernel route packs (runs, agents, memory, routines, terminals, and
6
- more). This package does **not** open a listener itself — a host (your own Express app, or
7
- `@jini-ai/server`'s `createLocalNodeDaemon`, which is the one assembled preset that does bind a
8
- port) mounts these route-registrars onto its own `app`.
3
+ Framework-level HTTP transport, guards and route-pack registration, with no domain.
4
+ Request parsing, response serialization, same-origin validation, SSE and Express mounting
5
+ are reusable primitives. The host mounts them onto its own app; the package opens no listener.
6
+ Daemon routes and their manifest now live in `@jini-ai/daemon/http`, and tool attenuation
7
+ lives in `@jini-ai/daemon/read-only-tools`. CMS settings live in `@jini-ai/cms/http/settings`.
9
8
 
10
9
  ## Install
11
10
 
@@ -13,95 +12,69 @@ port) mounts these route-registrars onto its own `app`.
13
12
  npm install @jini-ai/http-kit express
14
13
  ```
15
14
 
16
- `express` is a regular dependency (`^4.21.0`) pulled in automatically; you still need it installed
17
- in your own app if you're calling its types directly. `@jini-ai/agent-runtime`, `@jini-ai/core`,
18
- `@jini-ai/daemon`, `@jini-ai/platform`, and `@jini-ai/protocol` are also regular dependencies — no
19
- optional peers.
20
-
21
- ## What you get
22
-
23
- - **Route-spec primitives** — `JsonRouteSpec`/`InputParser`/`Handler`/`HttpMethod`/
24
- `RouteInputContext`, the `Result<T, E>` envelope (`ok`/`err`), and `defineJsonRoute`/
25
- `mountJsonRoute` (the Adapter — the only code here that touches Express `req`/`res` directly).
26
- - **Origin and auth guards** — `origin-validation`'s host/origin classifiers
27
- (`isLocalSameOrigin`, `isAllowedBrowserOrigin`, `parseHostHeader`, `isPrivateIpv4`, ...),
28
- `registerApiBearerAuthMiddleware`/`registerApiOriginGuardMiddleware`, and
29
- `requireLocalDaemonRequest`/`validateLocalDaemonRequest` for daemon-local-only routes.
30
- - **Streaming** — `createSseChannel` (cursor-replayable SSE with a bounded queue) and
31
- `createSseResponse` (raw, unbuffered SSE, used by the frontend-session stream).
32
- - **Pack composition glue** — `mountPackHttp(app, packs, daemon)` calls every composed
33
- `@jini-ai/core` pack's own `http(app, services)` registrar with the services `createDaemon`
34
- already resolved for it; `cancelRunsOwnedBy` and `installRouteRegistrationGuard`/
35
- `getRouteRegistrationInventory` (duplicate-route detection) support that composition.
36
- - **Daemon lifecycle routes** — `registerDaemonStatusRoutes` (`daemonStatusRoute`,
37
- `daemonShutdownRoute`) and `registerHealthRoutes` (`/health`, `/ready`, `/version` and their
38
- `/api`-prefixed twins — deliberately open, unauthenticated probes).
39
- - **Kernel route packs, ready to mount** — one `register*Routes` function per concern: runs
40
- (`registerRunRoutes`), agents (`registerAgentRoutes`), memory (`registerMemoryRoutes`),
41
- routines (`registerRoutineRoutes`), terminals (`registerTerminalRoutes`), db-ops
42
- (`registerDaemonDbRoutes` + tool registrations), tool catalog (`registerToolCatalogRoutes`),
43
- delegated tools (`registerDelegatedToolRoutes`), remote run events
44
- (`registerRemoteRunEventRoutes`), frontend sessions (`registerFrontendSessionRoutes`), active
45
- context (`registerActiveContextRoutes`), host tools (`registerHostToolsRoutes`), model proxy
46
- (`registerModelProxyRoutes`), connectors — auth/db/payments/storage/realtime provider seams
47
- (`registerConnectorsRoutes`), research (`registerResearchRoutes`), media
48
- (`registerMediaRoutes`), and xai (`registerXaiRoutes`). Each exports its own `*HttpDeps` type so
49
- you inject exactly the backing services it needs.
50
- - **Workspace root resolution** — `resolveWorkspaceRoot`/`denyAllWorkspaceRoots`/
51
- `WorkspaceRootDeniedError`.
52
- - **Legacy-shaped compat errors** — `createCompatApiError`/`createCompatApiErrorResponse`/
53
- `sendCompatApiError`, a `(code, message, init)` call shape kept alongside the main `ApiError`
54
- envelope for call sites generated against the older shape.
55
-
56
- ## Usage
57
-
58
- ```ts
59
- import express from 'express';
60
- import {
61
- defineJsonRoute,
62
- mountJsonRoute,
63
- registerHealthRoutes,
64
- ok,
65
- type AdapterContext,
66
- } from '@jini-ai/http-kit';
67
-
68
- const app = express();
69
- app.use(express.json());
70
-
71
- const adapter: AdapterContext = { resolvedPortRef: { current: 4000 } };
72
-
73
- // Ready-to-mount kernel routes: GET /health, /ready, /version (+ /api-prefixed twins).
74
- registerHealthRoutes(app, { getVersion: () => '1.0.0' }, adapter);
75
-
76
- // A custom route built on the same Result/JsonRouteSpec pipeline.
77
- const echoRoute = defineJsonRoute<{ msg: string }, { echoed: string }, void>({
78
- method: 'post',
79
- path: '/echo',
80
- parse: (raw) => ok({ msg: String((raw.body as { msg?: unknown })?.msg ?? '') }),
81
- handle: (input) => ok({ echoed: input.msg }),
82
- });
83
- mountJsonRoute(app, echoRoute, undefined, adapter);
84
-
85
- app.listen(4000);
86
- ```
87
-
88
- ## What's swappable
89
-
90
- Every route pack takes its backing services as an injected `*HttpDeps` object (e.g.
91
- `HealthHttpDeps.getVersion`/`checkReadiness`, `RunHttpDeps`, `MemoryHttpDeps`) rather than reaching
92
- for a global — swap in whatever implementation your host provides. `JsonRouteSpec.parse`/`handle`
93
- are themselves the seam for a fully custom route. Fixed and not meant to be replaced: the Express
94
- mounting mechanics in `adapter.ts` (this package does not support a non-Express framework — a
95
- prior switchable Fastify transport was removed on 2026-07-22; see `source-map.md` and
96
- `FASTIFY-TRANSPORT-PARKED.md` on the `future/fastify-transport` branch if reviving it), and the
97
- `Result`/`ApiError` error-handling pipeline every route folds into.
98
-
99
- ## Runtime
100
-
101
- `jini.runtime: "node"` — mounts onto a real Express `app`, uses Node's `express` types throughout.
102
- ESM only — ships `"type": "module"` with no CommonJS `require` build.
103
-
104
- ## Provenance
105
-
106
- See [source-map.md](./source-map.md) for per-file provenance and scope decisions. Apache-2.0,
107
- inherited from Open Design — see the repo `NOTICE`.
15
+ Regular dependencies are core, platform, protocol and Express. There is no daemon,
16
+ agent-runtime or CMS dependency.
17
+
18
+ ## Surface
19
+
20
+ - Route specs, `ok({ value })`, `err({ error })`, `defineJsonRoute` and `mountJsonRoute`.
21
+ - Request parsing, `validationError`, `sendJson`, `sendApiError` and `statusForError`.
22
+ - Origin and bearer guards, including core's canonical origin validation and Node token comparison.
23
+ - Cursor-aware and raw SSE primitives, route registration inventory and `mountPackHttp`.
24
+ - `./rate-limit`, `./middleware`, `./verified-origin` and `./observability`.
25
+
26
+ - `rate-limit` exports `createRateLimiter({ profile, clock, store })`,
27
+ `createMemoryCounterStore({})`, and `resolveClientIp({ source, policy })`.
28
+ Await `limiter.check({ key })` and `limiter.size({})`. Each limiter owns a
29
+ dedicated async counter store and serializes its checks across storage awaits.
30
+ Window/max/burst values and proxy trust policy are supplied by the host.
31
+ - `middleware` exports `rejectOversizedJsonBody({ maxBytes, errorResponseFactory })`.
32
+ Mount it after JSON parsing. The response factory receives `{ maxBytes, bodyBytes }`
33
+ and returns the host's error envelope; oversized bodies receive status 413.
34
+ The host parser still owns the limit on memory allocated while parsing.
35
+
36
+ ## Replaceable seams
37
+
38
+ `JsonRouteSpec.parse` and `handle` let hosts supply custom request handling. Pack services
39
+ are resolved by core before the HTTP registrar sees them. Duplicate-route detection catches
40
+ collisions during mounting, rather than letting the first registration silently win.
41
+ The Result/ApiError pipeline folds anticipated errors into one response path; unexpected
42
+ exceptions remain redacted with host-owned diagnostic reporting.
43
+
44
+ Define packs with `definePack({ name, deps, services }, { http })` from core;
45
+ the HTTP registrar belongs in the optional second argument. Mount the composed
46
+ packs with `mountPackHttp({ app, packs, daemon })`.
47
+
48
+ Express mounting is fixed. A switchable Fastify transport was removed on 2026-07-22 because
49
+ no consumer used it and maintaining every route twice imposed recurring work. Its implementation
50
+ and rationale remain on `future/fastify-transport` in `FASTIFY-TRANSPORT-PARKED.md`.
51
+
52
+ Settings routes and their CMS adapters now live at `@jini-ai/cms/http/settings`; this
53
+ package has no CMS dependency. `./verified-origin`
54
+ is a separate canonical-origin registry with required configuration evidence and
55
+ repository ports; it does not infer trust from request headers. Its canonical-origin
56
+ request type is `VerifiedOriginRequestContext`.
57
+
58
+ Origin guards require `env`, `allowedOriginsEnvVar`, `webPortEnvVar` and `bindHostEnvVar`
59
+ in the required context/dependencies. The host selects these names; the guards never
60
+ read ambient environment state. Core owns the validation functions and requires
61
+ `{ config, env }` for configured-origin parsing. Parsing stays lenient per request;
62
+ `assertValidAllowedOrigins({ config, env })` is strict at boot.
63
+ Bearer gates require their environment and token variable names in argument one;
64
+ `trustLoopbackPeers` and strict `exemptPaths` remain argument-two options.
65
+ `timingSafeTokenMatch` binds core's injected comparison port to `node:crypto`.
66
+ The async limiter uses core `Clock.nowMs()` and keeps non-empty-key validation.
67
+
68
+ `./observability` supplies `applyRequestTracking` and
69
+ `createRequestTrackingMiddleware` over the diagnostics-compatible
70
+ `HttpRequestObservabilityPort`. Mount first to include refusals and unmatched
71
+ requests; route labels are read at response completion.
72
+
73
+
74
+ See [API.md](https://github.com/AINSEP/Jini/blob/main/packages/http-kit/API.md) for required/optional object contracts. Node runtime, ESM only.
75
+ Apache-2.0; see the repository NOTICE.
76
+
77
+ ## Design decisions
78
+
79
+ - [Reject ambiguous redirect URLs before normalization](docs/decisions/DR-001-redirect-normalization.md).
80
+ - [Background error reporting must contain its own storage failures](docs/decisions/DR-002-background-failure-containment.md).
package/dist/adapter.d.ts CHANGED
@@ -45,18 +45,26 @@ export interface AdapterContext extends OriginContext {
45
45
  */
46
46
  export declare class ClientFacingError extends Error {
47
47
  readonly apiError: ApiError;
48
- constructor(apiError: ApiError);
48
+ constructor({ apiError }: {
49
+ readonly apiError: ApiError;
50
+ }, _optional?: Record<string, never>);
49
51
  }
50
52
  /**
51
- * Identity function that pins a route spec's generic parameters at the definition site so
52
- * callers do not have to repeat them. The returned spec is consumed by `mountJsonRoute` (live)
53
+ * Combines required route fields and optional settings into a fresh spec while pinning its generic
54
+ * parameters at the definition site so callers do not have to repeat them. Optional settings take
55
+ * precedence. The returned spec is consumed by `mountJsonRoute` (live)
53
56
  * and by tests (direct invocation of `route.parse` / `route.handle`).
54
57
  */
55
- export declare function defineJsonRoute<Input, Output, Deps>(spec: JsonRouteSpec<Input, Output, Deps>): JsonRouteSpec<Input, Output, Deps>;
58
+ export declare function defineJsonRoute<Input, Output, Deps>(requiredArgs: Omit<JsonRouteSpec<Input, Output, Deps>, 'requireSameOrigin' | 'successStatus'>, optionalArgs?: Pick<JsonRouteSpec<Input, Output, Deps>, 'requireSameOrigin' | 'successStatus'>): JsonRouteSpec<Input, Output, Deps>;
56
59
  /**
57
60
  * Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
58
61
  * about req/res; the route's parse and handle functions operate on `RouteInputContext` and
59
62
  * `Deps` respectively, so they are unit testable without Express.
60
63
  */
61
- export declare function mountJsonRoute<Input, Output, Deps>(app: Express, spec: JsonRouteSpec<Input, Output, Deps>, deps: Deps, adapter: AdapterContext): void;
64
+ export declare function mountJsonRoute<Input, Output, Deps>({ app, spec, deps, adapter }: {
65
+ readonly app: Express;
66
+ readonly spec: JsonRouteSpec<Input, Output, Deps>;
67
+ readonly deps: Deps;
68
+ readonly adapter: AdapterContext;
69
+ }, _optional?: Record<string, never>): void;
62
70
  //# sourceMappingURL=adapter.d.ts.map
package/dist/adapter.js CHANGED
@@ -35,18 +35,20 @@ function defaultInternalErrorSink(context) {
35
35
  */
36
36
  export class ClientFacingError extends Error {
37
37
  apiError;
38
- constructor(apiError) {
38
+ constructor({ apiError }, _optional = {}) {
39
39
  super(apiError.message);
40
40
  this.name = 'ClientFacingError';
41
41
  this.apiError = apiError;
42
42
  }
43
43
  }
44
44
  /**
45
- * Identity function that pins a route spec's generic parameters at the definition site so
46
- * callers do not have to repeat them. The returned spec is consumed by `mountJsonRoute` (live)
45
+ * Combines required route fields and optional settings into a fresh spec while pinning its generic
46
+ * parameters at the definition site so callers do not have to repeat them. Optional settings take
47
+ * precedence. The returned spec is consumed by `mountJsonRoute` (live)
47
48
  * and by tests (direct invocation of `route.parse` / `route.handle`).
48
49
  */
49
- export function defineJsonRoute(spec) {
50
+ export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
51
+ const spec = { ...requiredArgs, ...optionalArgs };
50
52
  return spec;
51
53
  }
52
54
  /**
@@ -54,9 +56,9 @@ export function defineJsonRoute(spec) {
54
56
  * about req/res; the route's parse and handle functions operate on `RouteInputContext` and
55
57
  * `Deps` respectively, so they are unit testable without Express.
56
58
  */
57
- export function mountJsonRoute(app, spec, deps, adapter) {
59
+ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
58
60
  app[spec.method](spec.path, async (req, res) => {
59
- // The client-disconnect signal a `handle` can opt into via its 3rd param. Observed on `res`,
61
+ // The client-disconnect signal a `handle` can opt into via optional arguments. Observed on `res`,
60
62
  // not `req` — `sse.ts` already established why for this exact "detect a disconnect before
61
63
  // ever writing a response" shape (its own doc: safe to register "before `open` is ever
62
64
  // called"). `req`'s own `'close'` was tried first here and reverted: on a REAL socket, a
@@ -75,18 +77,18 @@ export function mountJsonRoute(app, spec, deps, adapter) {
75
77
  res.on?.('close', onResponseClose);
76
78
  try {
77
79
  if (spec.requireSameOrigin) {
78
- const origin = guardSameOrigin(req, adapter);
80
+ const origin = guardSameOrigin({ req, origin: adapter });
79
81
  if (!origin.ok) {
80
- sendApiError(res, statusForError(origin.error), origin.error);
82
+ sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
81
83
  return;
82
84
  }
83
85
  }
84
- const parsed = spec.parse(rawInput(req));
86
+ const parsed = spec.parse(rawInput({ req }));
85
87
  if (!parsed.ok) {
86
- sendApiError(res, statusForError(parsed.error), parsed.error);
88
+ sendApiError({ res, status: statusForError({ error: parsed.error }), error: parsed.error });
87
89
  return;
88
90
  }
89
- const result = await spec.handle(parsed.value, deps, abortController.signal);
91
+ const result = await spec.handle({ input: parsed.value, deps }, { signal: abortController.signal });
90
92
  // `abortController.signal` can only have been aborted by `onResponseClose` firing while the
91
93
  // `await` above was pending — nothing here runs concurrently with it — so this unambiguously
92
94
  // means the client was already gone before any response was sent. Writing one now would be
@@ -95,17 +97,17 @@ export function mountJsonRoute(app, spec, deps, adapter) {
95
97
  if (abortController.signal.aborted)
96
98
  return;
97
99
  if (!result.ok) {
98
- sendApiError(res, statusForError(result.error), result.error);
100
+ sendApiError({ res, status: statusForError({ error: result.error }), error: result.error });
99
101
  return;
100
102
  }
101
- sendJson(res, spec.successStatus ?? 200, result.value);
103
+ sendJson({ res, status: spec.successStatus ?? 200, body: result.value });
102
104
  }
103
105
  catch (e) {
104
106
  // A route (or something it called) already classified this failure as safe to disclose —
105
107
  // see `ClientFacingError`'s own doc. Sent verbatim, at its own status; never routed to the
106
108
  // SEC-005 sink below, because nothing unanticipated happened.
107
109
  if (e instanceof ClientFacingError) {
108
- sendApiError(res, statusForError(e.apiError), e.apiError);
110
+ sendApiError({ res, status: statusForError({ error: e.apiError }), error: e.apiError });
109
111
  return;
110
112
  }
111
113
  // SEC-005. This catch exists for exceptions no route anticipated, which makes it precisely
@@ -118,7 +120,7 @@ export function mountJsonRoute(app, spec, deps, adapter) {
118
120
  const correlationId = randomUUID();
119
121
  const sink = adapter.onInternalError ?? defaultInternalErrorSink;
120
122
  sink({ method: spec.method, path: spec.path, correlationId, error: e });
121
- sendApiError(res, 500, createApiError('INTERNAL_ERROR', 'an internal error occurred', { requestId: correlationId }));
123
+ sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'an internal error occurred' }, { requestId: correlationId }) });
122
124
  }
123
125
  finally {
124
126
  res.off?.('close', onResponseClose);
@@ -1,5 +1,5 @@
1
1
  import type { Express, NextFunction, Request, Response } from 'express';
2
- import { type ApiTokenAuthEnvConfig } from '@jini-ai/core';
2
+ import { type OriginValidationEnvConfig, type ApiTokenAuthEnvConfig } from '@jini-ai/core';
3
3
  /**
4
4
  * Extracts the token from an `Authorization: Bearer <token>` header value. The scheme is
5
5
  * case-insensitive per RFC 7235 §2.1; the token itself is not.
@@ -13,7 +13,9 @@ import { type ApiTokenAuthEnvConfig } from '@jini-ai/core';
13
13
  * @complexity O(n) in the header length.
14
14
  * @overallScore 100/100
15
15
  */
16
- export declare function bearerTokenFromHeader(header: string | undefined): string | null;
16
+ export declare function bearerTokenFromHeader({ header }: {
17
+ readonly header: string | undefined;
18
+ }, _optional?: Record<string, never>): string | null;
17
19
  /**
18
20
  * Constant-time token comparison. Length is compared first and NOT in constant time — that leaks
19
21
  * only the expected token's length, which for a generated secret is fixed and not itself a secret,
@@ -31,12 +33,15 @@ export declare function bearerTokenFromHeader(header: string | undefined): strin
31
33
  * @complexity O(n) in the token length, with no data-dependent early exit.
32
34
  * @overallScore 100/100
33
35
  */
34
- export declare function timingSafeTokenMatch(presented: string, expected: string): boolean;
36
+ export declare function timingSafeTokenMatch({ presented, expected }: {
37
+ readonly presented: string;
38
+ readonly expected: string;
39
+ }, _optional?: Record<string, never>): boolean;
35
40
  export interface ApiBearerAuthMiddlewareDeps {
36
- /** Env var names for the token/disable flags. Defaults to `JINI_API_TOKEN` / `JINI_DISABLE_API_AUTH`. */
37
- tokenConfig?: ApiTokenAuthEnvConfig;
38
- /** Defaults to `process.env`. Threaded through so tests never have to mutate real process env. */
39
- env?: NodeJS.ProcessEnv;
41
+ /** Host-supplied env var names for the token/disable flags. */
42
+ tokenConfig: ApiTokenAuthEnvConfig;
43
+ /** Host-supplied environment; tests and hosts use the same explicit seam. */
44
+ env: NodeJS.ProcessEnv;
40
45
  /**
41
46
  * Whether an unproxied loopback peer may skip the bearer check. Defaults to `true` — the
42
47
  * affordance a desktop UI or local CLI talking to its own daemon relies on.
@@ -58,21 +63,23 @@ export interface ApiBearerAuthMiddlewareDeps {
58
63
  * request is rejected with 401 before reaching any route handler.
59
64
  *
60
65
  * @param app - The Express app to register the gate on.
61
- * @param deps - See {@link ApiBearerAuthMiddlewareDeps}. Both fields are optional; omitting `deps`
62
- * entirely reads `JINI_API_TOKEN`/`JINI_DISABLE_API_AUTH` from real `process.env`.
66
+ * @param requiredArgs - App, environment and host-selected token env var names.
67
+ * @param deps - Optional loopback trust policy; see {@link ApiBearerAuthMiddlewareDeps}.
63
68
  * @returns Nothing. Registers zero middleware (a deliberate no-op, not a bug) when no token is configured.
64
69
  * @complexity Setup is O(1). Each gated request is O(1) (one Set lookup, one regex match).
65
70
  * @overallScore 100/100
66
71
  */
67
- export declare function registerApiBearerAuthMiddleware(app: Express, deps?: ApiBearerAuthMiddlewareDeps): void;
72
+ export declare function registerApiBearerAuthMiddleware({ app, tokenConfig, env }: {
73
+ readonly app: Express;
74
+ } & Pick<ApiBearerAuthMiddlewareDeps, 'tokenConfig' | 'env'>, deps?: Pick<ApiBearerAuthMiddlewareDeps, 'trustLoopbackPeers'>): void;
68
75
  export interface StrictBearerTokenDeps {
69
76
  /**
70
77
  * Env var carrying the expected token. Required with no default: a gate this strict must name the
71
78
  * secret it enforces, and this package has no business guessing a host's env-var name.
72
79
  */
73
80
  readonly tokenEnvVar: string;
74
- /** Defaults to `process.env`. Threaded through so tests never have to mutate real process env. */
75
- readonly env?: NodeJS.ProcessEnv;
81
+ /** Host-supplied environment; tests and hosts use the same explicit seam. */
82
+ readonly env: NodeJS.ProcessEnv;
76
83
  /**
77
84
  * Exact request paths this gate does not apply to. Defaults to none — this is a gate-everything
78
85
  * primitive, and each exemption must be opted into explicitly at the mount site with a stated
@@ -117,16 +124,16 @@ export interface StrictBearerTokenDeps {
117
124
  * than defended against in code: normalizing `req.baseUrl + req.path` here would silently accept both
118
125
  * mount styles and remove the caller's ability to reason about which paths its entries refer to.
119
126
  */
120
- export declare function requireStrictBearerToken(deps: StrictBearerTokenDeps): (req: Request, res: Response, next: NextFunction) => void;
121
- export interface ApiOriginGuardMiddlewareDeps {
127
+ export declare function requireStrictBearerToken(requiredArgs: Omit<StrictBearerTokenDeps, 'exemptPaths'>, optionalArgs?: Pick<StrictBearerTokenDeps, 'exemptPaths'>): (req: Request, res: Response, next: NextFunction) => void;
128
+ export interface ApiOriginGuardMiddlewareDeps extends OriginValidationEnvConfig {
122
129
  /** The host this daemon is bound to — compared against a request's `Host`/`Origin` headers. */
123
130
  host: string;
124
131
  /** Extra allow-listed origins (e.g. a reverse-proxy's public origin). Defaults to none. */
125
132
  extraAllowedOrigins?: readonly string[];
126
133
  /** Returns the daemon's resolved listen port, or a falsy value before it has resolved. */
127
134
  getResolvedPort: () => number | null | undefined;
128
- /** Defaults to `process.env`. Threaded through so `JINI_WEB_PORT` is testable without mutating real process env. */
129
- env?: NodeJS.ProcessEnv;
135
+ /** Host-supplied environment; port env var names are supplied by the host too. */
136
+ env: NodeJS.ProcessEnv;
130
137
  }
131
138
  /**
132
139
  * Registers an unconditional cross-origin gate on every `/api/*` route: non-browser clients (no
@@ -142,5 +149,8 @@ export interface ApiOriginGuardMiddlewareDeps {
142
149
  * @complexity Setup is O(1). Each gated request is O(p) in the number of allowed ports (typically 1-2).
143
150
  * @overallScore 100/100
144
151
  */
145
- export declare function registerApiOriginGuardMiddleware(app: Express, deps: ApiOriginGuardMiddlewareDeps): void;
152
+ export declare function registerApiOriginGuardMiddleware({ app, deps }: {
153
+ readonly app: Express;
154
+ readonly deps: ApiOriginGuardMiddlewareDeps;
155
+ }, _optional?: Record<string, never>): void;
146
156
  //# sourceMappingURL=api-security-middleware.d.ts.map