@jini-ai/http-kit 0.3.8 → 0.4.1

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 (60) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/README.md +71 -98
  3. package/dist/adapter.d.ts +21 -6
  4. package/dist/adapter.js +47 -17
  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 +9 -78
  12. package/dist/delegated-tools.js +27 -95
  13. package/dist/index.d.ts +21 -70
  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 +52 -15
  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 +7 -0
  47. package/dist/verified-origin/index.js +6 -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/site-path.d.ts +113 -0
  55. package/dist/verified-origin/site-path.js +179 -0
  56. package/dist/verified-origin/types.d.ts +33 -0
  57. package/dist/verified-origin/types.js +23 -0
  58. package/dist/verified-origin.d.ts +2 -0
  59. package/dist/verified-origin.js +2 -0
  60. package/package.json +52 -11
package/CHANGELOG.md ADDED
@@ -0,0 +1,177 @@
1
+ # @jini-ai/http-kit
2
+
3
+ ## 0.4.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Tovu clean-up release (2026-10-08): code Tovu moved into Jini, plus the Jini clean-up (see the commit log since 0.4.0).
8
+
9
+ ## 0.4.0 — 2026-10-02
10
+
11
+ ### BREAKING
12
+
13
+ - 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.
14
+ - 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.
15
+
16
+ ## Unreleased
17
+
18
+ ### Build compatibility
19
+
20
+ - Align HTTP pack test registrars with core's second-argument contributions API
21
+ and supply the required origin environment variable names in the guard fixture.
22
+
23
+ ### BREAKING — capability-owned HTTP
24
+
25
+ - Daemon route packs, helpers and the live route manifest move to `@jini-ai/daemon/http`.
26
+ - Read-only policy moves to `@jini-ai/daemon/read-only-tools`; delegated policy facades and
27
+ `./read-only-tools` / `./run-credentials` entries are removed.
28
+ - Runtime dependencies no longer include daemon or agent-runtime. Generic request, response
29
+ and origin primitives are public for capability-owned packs.
30
+
31
+ ### HTTP transport consolidation
32
+
33
+ - BREAKING: Move settings routes, contracts and CMS adapters from `./settings` and the
34
+ root barrel to `@jini-ai/cms/http/settings`; remove the CMS dependency.
35
+ - BREAKING: Origin helpers now use core's `{ config, env }` API. Guard contexts require
36
+ explicit environments and host-selected allowed-origin, web-port and bind-host variable names.
37
+ Bearer middleware requires its environment and token configuration in argument one.
38
+ Strict bearer options contain only path exemptions; ambient environment defaults are removed.
39
+ - BREAKING: Remove the compat `sendApiError` and root `sendCompatApiError` writer.
40
+ Use `sendApiError({ res, status, error })` with the retained error constructors.
41
+ - BREAKING: Rename verified-origin's `OriginContext` to `VerifiedOriginRequestContext`;
42
+ rate limiter clocks implement core `nowMs()` instead of `nowIso()`.
43
+ - Reuse core `Result` and bind core's timing-safe comparison port to Node crypto under
44
+ the existing public `timingSafeTokenMatch` name.
45
+ - BREAKING: DB tool registration reads only operations from argument one; policy,
46
+ confirmation and timeout come exclusively from argument two.
47
+ - Preserve async limiting and invalid-key rejection. Regression and parity tests written;
48
+ verification deferred by owner directive.
49
+
50
+ ### HTTP contract corrections
51
+
52
+ - Fix delegated-tool read-only preflight forwarding so unverified registrations
53
+ retain the shared fail-closed refusal.
54
+ - Reject query, fragment and backslash delimiters in local daemon authorities
55
+ before URL parsing can discard or reinterpret them.
56
+ - Finish the DB, memory and tool-catalog argument conversion, including route
57
+ handlers and helper/port calls. Native event-emitter methods retain their ABI.
58
+ DB factory options now work in argument two; inline options remain supported.
59
+ - Return isolated route-inventory entries and use the documented default of 20
60
+ for negative routine-history limits instead of clamping them to 1.
61
+ - Correct pack callback, route-spec construction and attachment rejection docs;
62
+ classified server failures remain redacted. Regression tests are written but
63
+ unrun under the owner's directive. No version bump.
64
+
65
+ ### Integration of extracted subpaths
66
+
67
+ - Complete the Node export/runtime map and root barrels for `./rate-limit`,
68
+ `./middleware`, `./read-only-tools`, `./settings`, `./verified-origin`,
69
+ `./run-credentials`, and `./observability`. Settings uses the existing CMS
70
+ contracts through a new `@jini-ai/cms` dependency; lockfile reconciliation is pending.
71
+ - Add Express adapters for daemon authorization, delegated-body binding, ownership
72
+ and scoped listing over injected policies, plus request tracking over injected hooks.
73
+ - Reconcile protocol error helpers, core read-only classification, payment options,
74
+ media-generation options and cancellation context forwarding. No version bump.
75
+
76
+ ### BREAKING
77
+
78
+ - Existing public functions, factories, constructors, route handlers and local
79
+ ports now use required argument objects and optional argument objects. Call
80
+ handlers with `({ input, deps }, { signal? })`; call registrars with
81
+ `({ app, deps, adapter })`. Export names and response/event formats remain unchanged.
82
+ The earlier signature-compatibility note above predates this conversion.
83
+ - Payment ports accept charge fields followed by optional description; media
84
+ engines accept `{ surface, model }` followed by generation options. Read-only
85
+ ID generators accept `{}`. Verified-origin errors take `{ message }`.
86
+ - Protected `db-ops.ts`, `memory.ts` and `tool-catalog.ts` previously required
87
+ their owner-lane conversion; the HTTP contract corrections above complete it.
88
+ This source integration has not been tested or built; resolve the remaining
89
+ consumer handoff in `INTEGRATION-http-kit.md` before publishing.
90
+
91
+ - Add `./rate-limit` with fixed-window budgets, periodic stale-key eviction,
92
+ required clock/async counter-store ports, and explicit client-IP trust policy.
93
+ - Add `./middleware` with a parsed-JSON byte limit and required host response wording.
94
+ - Add `./read-only-tools` with required registry, executor, denial-ID and message
95
+ ports. Consolidate route and nested-dispatch checks into one fail-closed rule;
96
+ existing delegated-tool names, signatures and messages remain compatible.
97
+
98
+ ## 0.2.1
99
+
100
+ ### Patch Changes
101
+
102
+ - Add top-level `main`/`types` fields alongside the existing `exports` map. A consumer on
103
+ TypeScript's classic `moduleResolution: "node"` (node10) — which ignores `package.json#exports`
104
+ entirely — could not resolve this package's types at all (`TS2307: Cannot find module`) even
105
+ after the previous exports-map fix restored `require()` at runtime; type resolution and runtime
106
+ resolution are separate algorithms. Verified against a real external consumer (whose
107
+ tsconfig uses this legacy resolution mode): adding these two fields, with its tsconfig completely
108
+ unchanged, made the error disappear. Also fixes absolute-path `require()` (distinct from a bare
109
+ specifier, which already worked) for the same reason — `main` was previously absent.
110
+
111
+ Purely additive: every modern resolver (Node's own runtime `exports` resolution, TypeScript's
112
+ `bundler`/`node16`/`nodenext`) prefers `exports` over `main`/`types` when both are present, so
113
+ this changes nothing for a consumer already on a modern resolver.
114
+
115
+ - Updated dependencies
116
+ - @jini-ai/protocol@0.1.2
117
+ - @jini-ai/core@0.1.2
118
+ - @jini-ai/daemon@0.2.1
119
+ - @jini-ai/agent-runtime@0.2.1
120
+ - @jini-ai/platform@0.1.2
121
+
122
+ ## 0.2.0
123
+
124
+ ### Minor Changes
125
+
126
+ - e181b22: Enforce flat-package domain/runtime/admission metadata, invert optional capability dependencies,
127
+ inject failure-contained run-stream encoders, clean up provisional replay subscribers, and add a
128
+ neutral node-host HTTP-extension composition seam.
129
+ - 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.
130
+
131
+ ### Patch Changes
132
+
133
+ - Add a `"default"` export condition to every published package's `exports` map — every one of
134
+ them lacked it, which meant `require()` failed with `ERR_PACKAGE_PATH_NOT_EXPORTED` for any
135
+ CommonJS consumer (found via a real external integration attempt; Node needs `require(esm)`
136
+ support, i.e. Node >=22.12, for this to resolve).
137
+
138
+ `@jini-ai/agent-runtime`:
139
+
140
+ - **New**: `RuntimeBuildOptions.permissionMode` (`'bypass' | 'restricted'`) lets a caller opt a
141
+ run OUT of the auto-approve-every-permission-prompt flag every def with one
142
+ (`bypassPermissions` / `--yolo` / `--dangerously-skip-permissions`) previously pushed
143
+ unconditionally, with no way to turn it off. Omitting it keeps today's default (bypass)
144
+ behavior unchanged.
145
+ - **New**: `ClaudeStreamEvent`, `CopilotStreamEvent`, and `QoderEvent` are now real exported
146
+ discriminated unions instead of `Record<string, unknown>` — a real external consumer guessed a
147
+ nonexistent field name (`event.text` instead of the actual `event.delta`) against the old
148
+ untyped sink and silently lost every streamed token with no compile or runtime error.
149
+ - Fixed a doc/implementation mismatch in `claude-stream.ts`: the module doc claimed `tool_result`
150
+ events carry `{ tool_use_id, content, is_error }`; the actual emitted shape is
151
+ `{ toolUseId, content, isError }`.
152
+
153
+ `@jini-ai/daemon`: `AgentExecutorRunInput.permissionMode` forwards the new
154
+ `RuntimeBuildOptions.permissionMode` through to `buildArgs`, so a host can actually reach the new
155
+ opt-out from the daemon's real run-input surface, not just from `@jini-ai/agent-runtime` in
156
+ isolation.
157
+
158
+ `@jini-ai/agentic`: `setAtPointer` no longer throws on a malformed (e.g. missing leading `/`)
159
+ `updateDataModel` path — degrades to a no-op like its sibling `getAtPointer`, matching this
160
+ package's own "a bad binding must not crash the renderer" contract. That path is agent-authored
161
+ wire data with no error boundary above it in any host, so the uncaught throw could unmount an
162
+ entire chat UI from ~40 bytes of malformed input.
163
+
164
+ `@jini-ai/chat-react`: a local (client-resolved) A2UI button action is no longer a silent no-op —
165
+ `A2uiSurfaceCard` now surfaces the resolved value. New `ExtEventErrorBoundary` confines a
166
+ `kind: 'ext'` event group's renderer to its own card instead of letting a render/effect-phase
167
+ throw from agent-controlled content unmount the whole chat root (there was no error boundary
168
+ anywhere in this package or its hosts before this).
169
+
170
+ - Updated dependencies
171
+ - Updated dependencies [e181b22]
172
+ - Updated dependencies [0d15314]
173
+ - @jini-ai/protocol@0.1.1
174
+ - @jini-ai/core@0.1.1
175
+ - @jini-ai/platform@0.1.1
176
+ - @jini-ai/agent-runtime@0.2.0
177
+ - @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,33 @@ 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`).
57
+ * @param optionalArgs - Origin/success policy and optional injected host ports.
58
+ * @returns A fresh route spec; never mutates either argument.
59
+ * @complexity O(1) time/space for the fixed spec fields.
54
60
  */
55
- export declare function defineJsonRoute<Input, Output, Deps>(spec: JsonRouteSpec<Input, Output, Deps>): JsonRouteSpec<Input, Output, Deps>;
61
+ 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>;
56
62
  /**
57
63
  * Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
58
64
  * about req/res; the route's parse and handle functions operate on `RouteInputContext` and
59
- * `Deps` respectively, so they are unit testable without Express.
65
+ * `Deps` respectively, so they are unit testable without Express. Optional host ports preserve
66
+ * workspace/auth/error policy without coupling this toolkit to a domain. An origin context is
67
+ * required only for routes that opt into the same-origin guard.
68
+ * @returns Void; registers one handler, without starting a listener.
69
+ * @complexity O(1) setup and per-request overhead, plus parsing, host ports and handling.
60
70
  */
61
- export declare function mountJsonRoute<Input, Output, Deps>(app: Express, spec: JsonRouteSpec<Input, Output, Deps>, deps: Deps, adapter: AdapterContext): void;
71
+ export declare function mountJsonRoute<Input, Output, Deps, Context = undefined>({ app, spec, deps, adapter }: {
72
+ readonly app: Express;
73
+ readonly spec: JsonRouteSpec<Input, Output, Deps, Context>;
74
+ readonly deps: Deps;
75
+ readonly adapter?: AdapterContext;
76
+ }, _optional?: Record<string, never>): void;
62
77
  //# sourceMappingURL=adapter.d.ts.map
package/dist/adapter.js CHANGED
@@ -35,28 +35,37 @@ 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`).
49
+ * @param optionalArgs - Origin/success policy and optional injected host ports.
50
+ * @returns A fresh route spec; never mutates either argument.
51
+ * @complexity O(1) time/space for the fixed spec fields.
48
52
  */
49
- export function defineJsonRoute(spec) {
53
+ export function defineJsonRoute(requiredArgs, optionalArgs = {}) {
54
+ const spec = { ...requiredArgs, ...optionalArgs };
50
55
  return spec;
51
56
  }
52
57
  /**
53
58
  * Mounts one JsonRouteSpec on an Express app. The Adapter is the only code here that knows
54
59
  * about req/res; the route's parse and handle functions operate on `RouteInputContext` and
55
- * `Deps` respectively, so they are unit testable without Express.
60
+ * `Deps` respectively, so they are unit testable without Express. Optional host ports preserve
61
+ * workspace/auth/error policy without coupling this toolkit to a domain. An origin context is
62
+ * required only for routes that opt into the same-origin guard.
63
+ * @returns Void; registers one handler, without starting a listener.
64
+ * @complexity O(1) setup and per-request overhead, plus parsing, host ports and handling.
56
65
  */
57
- export function mountJsonRoute(app, spec, deps, adapter) {
66
+ export function mountJsonRoute({ app, spec, deps, adapter }, _optional = {}) {
58
67
  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`,
68
+ // The client-disconnect signal a `handle` can opt into via optional arguments. Observed on `res`,
60
69
  // not `req` — `sse.ts` already established why for this exact "detect a disconnect before
61
70
  // ever writing a response" shape (its own doc: safe to register "before `open` is ever
62
71
  // called"). `req`'s own `'close'` was tried first here and reverted: on a REAL socket, a
@@ -74,19 +83,34 @@ export function mountJsonRoute(app, spec, deps, adapter) {
74
83
  // which is the correct behavior for a double that never fires `close` anyway.
75
84
  res.on?.('close', onResponseClose);
76
85
  try {
86
+ const raw = rawInput({ req });
87
+ if (spec.ports?.workspace)
88
+ await spec.ports.workspace({ raw, deps });
77
89
  if (spec.requireSameOrigin) {
78
- const origin = guardSameOrigin(req, adapter);
90
+ if (!adapter)
91
+ throw new Error('same-origin adapter context is required');
92
+ const origin = guardSameOrigin({ req, origin: adapter });
79
93
  if (!origin.ok) {
80
- sendApiError(res, statusForError(origin.error), origin.error);
94
+ sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
81
95
  return;
82
96
  }
83
97
  }
84
- const parsed = spec.parse(rawInput(req));
98
+ let context;
99
+ if (spec.ports?.authenticate)
100
+ context = await spec.ports.authenticate({ raw, res, deps });
101
+ const parsed = spec.parse(raw);
85
102
  if (!parsed.ok) {
86
- sendApiError(res, statusForError(parsed.error), parsed.error);
103
+ sendApiError({ res, status: statusForError({ error: parsed.error }), error: parsed.error });
87
104
  return;
88
105
  }
89
- const result = await spec.handle(parsed.value, deps, abortController.signal);
106
+ // The route chooses where authorization occurs: reads may authorize before validation,
107
+ // while writes must reject an inconsistent tenant target before asking for a permission.
108
+ const authorize = async ({ permission, entityType }) => {
109
+ if (!spec.ports?.authorize)
110
+ throw new Error('JSON route authorizer is required');
111
+ await spec.ports.authorize({ context, deps, permission, entityType });
112
+ };
113
+ const result = await spec.handle({ input: parsed.value, deps, context, authorize }, { signal: abortController.signal });
90
114
  // `abortController.signal` can only have been aborted by `onResponseClose` firing while the
91
115
  // `await` above was pending — nothing here runs concurrently with it — so this unambiguously
92
116
  // means the client was already gone before any response was sent. Writing one now would be
@@ -95,17 +119,23 @@ export function mountJsonRoute(app, spec, deps, adapter) {
95
119
  if (abortController.signal.aborted)
96
120
  return;
97
121
  if (!result.ok) {
98
- sendApiError(res, statusForError(result.error), result.error);
122
+ sendApiError({ res, status: statusForError({ error: result.error }), error: result.error });
99
123
  return;
100
124
  }
101
- sendJson(res, spec.successStatus ?? 200, result.value);
125
+ sendJson({ res, status: spec.successStatus ?? 200, body: result.value });
102
126
  }
103
127
  catch (e) {
128
+ // An explicit host error port owns exception classification and serialization, including
129
+ // its guard rejections. Hosts without it retain the SEC-005 policy below unchanged.
130
+ if (spec.ports?.onError) {
131
+ spec.ports.onError({ res, error: e });
132
+ return;
133
+ }
104
134
  // A route (or something it called) already classified this failure as safe to disclose —
105
135
  // see `ClientFacingError`'s own doc. Sent verbatim, at its own status; never routed to the
106
136
  // SEC-005 sink below, because nothing unanticipated happened.
107
137
  if (e instanceof ClientFacingError) {
108
- sendApiError(res, statusForError(e.apiError), e.apiError);
138
+ sendApiError({ res, status: statusForError({ error: e.apiError }), error: e.apiError });
109
139
  return;
110
140
  }
111
141
  // SEC-005. This catch exists for exceptions no route anticipated, which makes it precisely
@@ -116,9 +146,9 @@ export function mountJsonRoute(app, spec, deps, adapter) {
116
146
  // caller could read it too, simply by getting a readiness dependency to fail. The real error
117
147
  // still reaches the operator through the sink, correlated to what the caller was told.
118
148
  const correlationId = randomUUID();
119
- const sink = adapter.onInternalError ?? defaultInternalErrorSink;
149
+ const sink = adapter?.onInternalError ?? defaultInternalErrorSink;
120
150
  sink({ method: spec.method, path: spec.path, correlationId, error: e });
121
- sendApiError(res, 500, createApiError('INTERNAL_ERROR', 'an internal error occurred', { requestId: correlationId }));
151
+ sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'an internal error occurred' }, { requestId: correlationId }) });
122
152
  }
123
153
  finally {
124
154
  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