@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/dist/index.d.ts CHANGED
@@ -3,11 +3,8 @@
3
3
  *
4
4
  * JSON-route transport for a `@jini-ai/core` daemon composition: the `Result`/route-spec types,
5
5
  * request parsing, response serialization, the same-origin guard, the Express-mounting Adapter,
6
- * legacy-shaped compat error helpers, a route-pack registrar, generic daemon status/shutdown
7
- * routes, and every route pack this package ships (runs, agents, host-tools, memory, routines,
8
- * db-ops, terminals, model-proxy, active-context, delegated-tools) — all exported flat at this
9
- * root, the load-bearing surface every consumer (including `@jini-ai/server`'s
10
- * `createLocalNodeDaemon`) imports from directly.
6
+ * error metadata helpers and a route-pack registrar. Domain route packs are owned by
7
+ * their capabilities and exposed through their HTTP entries.
11
8
  *
12
9
  * This package supported a switchable `express`/`fastify` HTTP transport from 2026-07-19 through
13
10
  * 2026-07-22; it was removed since nothing ever consumed `transport: 'fastify'` in practice, and
@@ -15,12 +12,137 @@
15
12
  * Fastify mounting sibling" tax on every future addition to this package. The removed
16
13
  * implementation is preserved, unchanged, on the `future/fastify-transport` branch — see
17
14
  * `FASTIFY-TRANSPORT-PARKED.md` at the repo root of that branch for the full reasoning and how to
18
- * revive it. See `source-map.md` for this package's full provenance and scope-decision notes.
15
+ * revive it. See `archived provenance ledger` for this package's full provenance and scope-decision notes.
16
+
17
+ * Archived provenance rationale:
18
+ * ## Design decisions
19
+ *
20
+ * **1. `compat.ts` was ported despite having no current Jini call site.** OD's
21
+ * `compat/api-errors.ts` exists only because `server.ts`'s routes — written
22
+ * before `JsonRouteSpec` existed — call error helpers with a different argument
23
+ * shape than the rest of the module; Jini's `@jini/http` has no such legacy
24
+ * call sites of its own. It was kept anyway for two reasons: (a) the task brief
25
+ * explicitly named `api-errors.ts` in its file list, and (b) extraction-plan.md
26
+ * §4's OD-sync mechanism (hollow re-exports + patch canary) depends on Jini's
27
+ * port carrying the *same public surface* as the OD module it patch-routes
28
+ * against — dropping an exported symbol here would be exactly the kind of
29
+ * silent divergence that mechanism exists to catch. A future host application
30
+ * with its own legacy hand-mounted routes (mirroring OD's `server.ts`) is the
31
+ * plausible real consumer; until then it is inert, imported-but-unused code,
32
+ * which is an acceptable cost for sync fidelity in a package whose whole
33
+ * purpose is to be a faithful patch target.
34
+ *
35
+ * **2. `mountPackHttp` (route-pack registrar) is new, not a lift.** OD's
36
+ * `http/` module has no concept of "packs" — it predates `@jini/core`'s typed
37
+ * DI-token composition contract entirely; `server.ts` mounts every route by
38
+ * hand. Per extraction-plan.md §3's description of `@jini/http` as containing
39
+ * a "route-pack registrar," and per the task brief's explicit instruction to
40
+ * check `packages/core/src/pack.ts` and compose with it rather than inventing a
41
+ * separate pattern, `mountPackHttp(app, packs, daemon)` was built fresh: it
42
+ * iterates the same `packs` array passed to `createDaemon` and calls each
43
+ * pack's optional `Pack.http(app, services)` registrar (declared in
44
+ * `@jini/core`'s `pack.ts` with `app` deliberately typed `unknown` so the
45
+ * kernel never depends on Express) with the *same* Express `app` and the
46
+ * *same* composed `services` object `@jini/cli`'s eventual CLI registrar would
47
+ * receive via `Pack.cli` — satisfying extraction-plan.md §2.3's "both
48
+ * transports call one shared app-service" invariant. Packs with no `http`
49
+ * registrar are silently skipped (a CLI-only or headless pack is not an error).
50
+ *
51
+ * **3. `ExecutionDelegate` injection is explicitly out of scope, not
52
+ * overlooked.** Extraction-plan.md §3 describes `@jini/http` as also
53
+ * "injects `ExecutionDelegate`" (§2.5's tool-execution-boundary confirm/authorize
54
+ * callback pair, transport-specific by design). `ToolExecutor` now exists in
55
+ * `@jini/daemon`, but the external CLI stream currently reports a tool use after
56
+ * the CLI has executed it; it is not a pre-execution request/response protocol.
57
+ * This transport therefore does not pretend to inject a post-hoc callback as an
58
+ * authorization gate. A controlled agent protocol is a real, named follow-up.
59
+ *
60
+ * **4. `ERROR_STATUS_BY_CODE` was re-scoped to `@jini/protocol`'s codes, not
61
+ * copied 1:1.** See the `src/response.ts` file-map row above for the exact
62
+ * additions/removals. This keeps the status-mapping table honest about which
63
+ * codes are actually reachable through `@jini/protocol`'s `ApiErrorCode` type
64
+ * (an open string type — a pack's own codes still type-check and simply fall
65
+ * back to the conservative 500 default, same as OD's unmapped-code behavior).
66
+ *
67
+ * ### Design decision: deliberately duplicated, not a shared interface — with one exception
68
+ *
69
+ * `express/` and `fastify/`'s nine matching files (`adapter`, `api-security-middleware`, `compat`,
70
+ * `daemon-status`, `index`, `local-daemon-request`, `origin`, `request`, `response`,
71
+ * `route-registration-guard`) are **independent implementations of the same job, not two adapters
72
+ * behind one shared interface.** This was a deliberate choice, not an oversight: Express's
73
+ * middleware-chain model (`(req, res, next) => void`, `res.json(...)`, `app.use(...)`) and Fastify's
74
+ * hook/plugin model (`onRequest`/`onRoute` hooks, `reply.send(...)`, schema-validated route options)
75
+ * are different enough in shape that forcing them behind one abstraction would either leak one
76
+ * framework's idioms into the other's native surface, or flatten both down to a lowest-common-
77
+ * denominator API that fights each framework's own strengths (Fastify's schema-based validation and
78
+ * radix-tree routing, in particular, are not expressible through an Express-shaped adapter without
79
+ * losing most of their value). Each subtree is written the way an engineer fluent in that framework
80
+ * would write it, and each is independently tested to 100% coverage.
81
+ *
82
+ * **The one exception: `fastify/daemon-status.ts` reuses `express/daemon-status.ts`'s route-spec
83
+ * data directly** — `daemonStatusRoute`/`daemonShutdownRoute` are pure `defineJsonRoute`-shaped
84
+ * data plus framework-agnostic `parse`/`handle` functions (see that file's own doc). They never
85
+ * reference Express at runtime: `express/daemon-status.ts` only imports `type { Express }` for one
86
+ * parameter type, and TypeScript's `verbatimModuleSyntax` erases type-only imports from the compiled
87
+ * output entirely — verified there is zero runtime `express` dependency pulled into the `fastify/`
88
+ * subtree by this reuse. `fastify/daemon-status.ts`'s own job is only the Fastify-specific mounting
89
+ * wrapper (`registerDaemonStatusRoutes`, calling `./adapter.js`'s Fastify `mountJsonRoute`). This is
90
+ * the single case where sharing was correct instead of duplication: the route *data* (path, method,
91
+ * input parser, pure handler) has no framework opinion in it at all — only the *mounting glue* does,
92
+ * and that glue is what actually differs and stays independent per subtree.
93
+ *
94
+ * ### Merge note (2026-07-22, later the same day): four more audit-fix sections below merged in from a second, parallel cloud session
95
+ *
96
+ * The sections immediately below (`delegated-tools.ts` barrel export, `media.ts`, and the
97
+ * `runs.ts`/`terminals.ts` coverage pass) were written on a branch (`fix/audit-6-fixes-20260722`) that
98
+ * forked from `main` *before* the Fastify-transport-split merge above landed, so they were authored
99
+ * against the pre-split flat-file layout. They merged in cleanly with no logical conflict — the
100
+ * route-pack files they touch (`delegated-tools.ts`, `runs.ts`, `terminals.ts`) are exactly the ones
101
+ * this merge's "Corrected layout" section above kept flat at the package root, not moved into
102
+ * `express/`, so every path/import reference below is still accurate post-merge. `media.ts` (new in
103
+ * that branch) is likewise flat at the root and barrel-exported the same way. None of these four
104
+ * sections needed any correction for the Fastify split; see `server/archived provenance ledger`'s own merge note
105
+ * for the one piece that did (the six route packs `media.ts` joins are wired Express-only for now,
106
+ * deliberately, per this repo's owner's explicit instruction to table Fastify parity for the newly
107
+ * merged route packs — tracked as follow-up work, not silently dropped).
108
+ *
109
+ * ### Design decisions
110
+ *
111
+ * **`StoredAttachment` mirrors `@jini-ai/chat-core`'s `ChatAttachment` instead of importing it.** Same
112
+ * reasoning as `media.ts` declaring its own `MediaTask`/`MediaDispatchEngine` rather than depending on
113
+ * `@jini-ai/media`: a `jini.domain: "server"` transport package should not acquire a dependency on a
114
+ * *domain* package (`chat`) to describe an upload that is not chat-specific. There is no cycle — the edge
115
+ * would be legal — it is simply the wrong direction, and it would be the first `server` → `chat` package
116
+ * edge in the graph. The drift risk that makes a mirror tempting to avoid is paid for with a test instead
117
+ * of a dependency: `attachments.test.ts` holds a compile-time assignability assertion in **both**
118
+ * directions against the real `ChatAttachment` (`@jini-ai/chat-core` is a **devDependency** only, so
119
+ * nothing is added to the published dependency graph). A field added, removed, renamed, or retyped on
120
+ * either side fails the build.
121
+ *
122
+ * **Hand-mounted, not `defineJsonRoute`/`mountJsonRoute`.** Two hard reasons: the upload reads the raw
123
+ * request stream, so a JSON-parsed `req.body` is precisely what must *not* have happened; and the cleanup
124
+ * answers `204` with no body, which a JSON responder cannot express. `requireSameOrigin` is therefore a
125
+ * dep flag (defaulting to `true`) rather than a spec field, evaluated through the same `guardSameOrigin`.
126
+ *
127
+ * **Run-lifecycle wiring stays host-owned**, following `@jini-ai/daemon`'s `createRunScopedContextStore`
128
+ * precedent exactly: there is no generic post-run-start hook to auto-wire into, and inventing one for this
129
+ * would be a larger and worse change than documenting ten lines. The module doc carries the pattern
130
+ * (claim in `onRunStarted`, thread into `AgentExecutor.run()`'s pre-existing
131
+ * `imagePaths`/`extraAllowedDirs`/`uploadRoot`, `cleanupRun` in a `finally`). `daemon.ts` in the example is
132
+ * the live reference.
133
+ *
134
+ * **Typed rejections replaced substring matching.** The example's route decided status codes with
135
+ * `message.includes('20 MB') || message.includes('limited to') || ...` across a module boundary. Since one
136
+ * package now owns both the store and the routes, `AttachmentRejectedError.reason` maps to a status in one
137
+ * table. The externally-visible status mapping is unchanged (quota → 413, bad batch → 400, integrity →
138
+ * redacted 500); it is just no longer coupled to message wording. Reasons that describe a broken or
139
+ * hostile server-side state never expose their real message over HTTP, but exist so a host catching a
140
+ * rejection from `claim()` outside HTTP can still classify it.
19
141
  */
20
142
  export type { Handler, HttpMethod, InputParser, JsonRouteSpec, Result, RouteInputContext, } from './types.js';
21
143
  export { err, ok } from './types.js';
22
- export type { ParsedHostHeader, RequestWithOriginHeaders, } from './origin-validation.js';
23
- export { allowedBrowserPorts, assertValidAllowedOrigins, configuredAllowedHosts, configuredAllowedOrigins, isAllowedBrowserHost, isAllowedBrowserOrigin, isIpLiteralHostname, isLoopbackOrPrivateLanHost, isLocalSameOrigin, isPrivateIpv4, parseHostHeader, } from './origin-validation.js';
144
+ export type { ParsedHostHeader, RequestWithOriginHeaders, } from '@jini-ai/core';
145
+ export { allowedBrowserPorts, assertValidAllowedOrigins, configuredAllowedHosts, configuredAllowedOrigins, isAllowedBrowserHost, isAllowedBrowserOrigin, isIpLiteralHostname, isLoopbackOrPrivateLanHost, isLocalSameOrigin, isPrivateIpv4, parseHostHeader, } from '@jini-ai/core';
24
146
  export type { AdapterContext } from './adapter.js';
25
147
  export { ClientFacingError, defineJsonRoute, mountJsonRoute } from './adapter.js';
26
148
  export type { InstallRouteRegistrationGuardOptions, RouteRegistration } from './route-registration-guard.js';
@@ -29,58 +151,17 @@ export type { CreateSseChannelOptions, SseChannel, SseEvent } from './sse.js';
29
151
  export { createSseChannel, DEFAULT_MAX_QUEUED_SSE_EVENTS, requestedAfterCursor, sendRawApiError } from './sse.js';
30
152
  export type { CreateSseResponseOptions, SseConnection } from './raw-sse.js';
31
153
  export { createSseResponse } from './raw-sse.js';
32
- export type { ResolveWorkspaceRootOptions, WorkspaceRootRequest, WorkspaceRootResolver, } from './workspace-root.js';
33
- export { denyAllWorkspaceRoots, resolveWorkspaceRoot, WorkspaceRootDeniedError } from './workspace-root.js';
34
154
  export { mountPackHttp } from './pack-http.js';
35
- export type { RunCancellationService } from './cancel-owned-runs.js';
36
- export { cancelRunsOwnedBy } from './cancel-owned-runs.js';
37
- export type { ActiveContextDeps, ActiveContextResource } from './active-context.js';
38
- export { ACTIVE_CONTEXT_TTL_MS, getActiveRoute, registerActiveContextRoutes, setActiveRoute, } from './active-context.js';
39
- export type { CatalogueEntry, HostEditor, HostEditorsResponse, HostToolLaunchPlan, HostToolProbeEnv, LaunchHostToolResult, Platform, RealPlatform, } from './host-tools.js';
40
- export { applicableForPlatform, CATALOGUE, currentPlatform, defaultProbeEnv, hostEditorsRoute, launchHostTool, listAvailableEditors, pathDirs, probeCommandOnPath, probeMacBundle, registerHostToolsRoutes, resolveEntry, resolveHostToolLaunchPlan, } from './host-tools.js';
41
155
  export type { ApiBearerAuthMiddlewareDeps, ApiOriginGuardMiddlewareDeps, StrictBearerTokenDeps, } from './api-security-middleware.js';
42
156
  export { bearerTokenFromHeader, registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware, requireStrictBearerToken, timingSafeTokenMatch, } from './api-security-middleware.js';
43
- export { isLoopbackHostname, isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
44
- export type { DaemonShutdownResponse, DaemonStatusDeps, DaemonStatusResponse, } from './daemon-status.js';
45
- export { daemonShutdownRoute, daemonStatusRoute, registerDaemonStatusRoutes } from './daemon-status.js';
46
- export type { RunCancelResponse, RunCreateRequest, RunHttpDeps, RunInternalErrorContext, RunListResponse, RunStartContext, RunStartHandler, RunStartResponse, RunStatusResponse, } from './runs.js';
47
- export { registerRunEventStream, registerRunRoutes, RUN_EVENTS_ROUTE_PATH, runCancelRoute, runListRoute, runStartRoute, runStatusRoute, } from './runs.js';
48
- export { JINI_ROUTE_MANIFEST, manifestRoutesForFamilies, routeFamilyManifest } from './route-manifest.js';
49
- export type { AgentListResponse, AgentModelSummary, AgentsHttpDeps, AgentSummary } from './agents.js';
50
- export { agentListRoute, agentRescanRoute, registerAgentRoutes } from './agents.js';
51
- export type { MemoryChangeEmitter, MemoryConfigResponse, MemoryDeleteEntryResponse, MemoryEntryInput, MemoryEntryResponse, MemoryExtractionLog, MemoryExtractionsResponse, MemoryHttpDeps, MemoryIndexResponse, MemoryNoteEntry, MemoryNoteEntrySummary, MemoryNoteStore, MemoryNoteStoreOptions, MemoryOverviewResponse, MemoryRemovedResponse, MemoryTreeNode, MemoryTreeNodePatch, MemoryTreeResponse, MemoryUpdateTreeNodeResponse, MemoryVerificationsResponse, MemoryVerifyLog, } from './memory.js';
52
- export { memoryClearExtractionsRoute, memoryClearVerificationsRoute, memoryCreateEntryRoute, memoryDeleteEntryRoute, memoryListExtractionsRoute, memoryListVerificationsRoute, memoryOverviewRoute, memoryReadEntryRoute, memoryRemoveExtractionRoute, memoryRemoveVerificationRoute, memoryTreeRoute, memoryUpdateEntryRoute, memoryUpdateTreeNodeRoute, memoryWriteConfigRoute, memoryWriteIndexRoute, registerMemoryEventStream, registerMemoryRoutes, } from './memory.js';
53
- export type { RoutineDeleteResponse, RoutineHttpDeps, RoutineListResponse, RoutineResponse, RoutineRunNowResponse, RoutineRunsResponse, RoutineScheduler, } from './routines.js';
54
- export { registerRoutineRoutes, routineCreateRoute, routineDeleteRoute, routineGetRoute, routineListRoute, routineRunNowRoute, routineRunsListRoute, routineUpdateRoute, } from './routines.js';
55
- export type { CreateDaemonDbToolRegistrationsOptions, DaemonDbHttpDeps, DaemonDbInternalErrorContext, DaemonDbOperations, DaemonDbStatusReport, DaemonDbTableInfo, DaemonDbToolRegistrations, DaemonDbVacuumResult, DbIntegrityIssue, DbIntegrityIssueKind, DbIntegrityReport, } from './db-ops.js';
56
- export { createDaemonDbToolRegistrations, daemonDbInspectRoute, daemonDbVacuumRoute, daemonDbVerifyRoute, DB_INSPECT_TOOL_ID, DB_VACUUM_TOOL_ID, DB_VERIFY_TOOL_ID, denyAllDaemonDbPolicy, registerDaemonDbRoutes, } from './db-ops.js';
57
- export type { ToolCatalogEntry, ToolCatalogHttpDeps, ToolCatalogQuery, ToolCatalogSearchHit, } from './tool-catalog.js';
58
- export { registerToolCatalogRoutes, toolCatalogDescribeRoute, toolCatalogSearchRoute, } from './tool-catalog.js';
59
- export type { ComponentCatalogEntry, ComponentCatalogHttpDeps, ComponentCatalogQuery, ComponentCatalogSearchHit, } from './component-catalog.js';
60
- export { registerComponentCatalogRoutes, componentCatalogDescribeRoute, componentCatalogSearchRoute, } from './component-catalog.js';
61
- export type { DelegatedToolExecuteRequest, DelegatedToolExecuteResponse, DelegatedToolsHttpDeps, DelegatedToolsInternalErrorContext, } from './delegated-tools.js';
62
- export { delegatedToolExecuteRoute, readOnlyRefusalMessage, READ_ONLY_UNVERIFIABLE_MESSAGE, registerDelegatedToolRoutes, } from './delegated-tools.js';
63
- export type { RemoteRunEventHttpDeps, RemoteRunEventResponse, RemoteToolBridgeTokenConfig, RemoteToolResultRequest, RemoteToolUseRequest, } from './remote-run-events.js';
64
- export { registerRemoteRunEventRoutes, remoteToolResultRoute, remoteToolUseRoute, requireRemoteToolBridgeToken, } from './remote-run-events.js';
65
- export type { FrontendSessionAttachedEvent, FrontendSessionErrorEvent, FrontendSessionInvocationEvent, FrontendSessionResponseBody, FrontendSessionResponseRequest, FrontendSessionStreamEvent, FrontendSessionsHttpDeps, } from './frontend-sessions.js';
66
- export { FRONTEND_SESSION_RESPONSE_ROUTE_PATH, FRONTEND_SESSION_STREAM_ROUTE_PATH, frontendSessionResponseRoute, handleFrontendSessionStream, parseCapabilityQuery, registerFrontendSessionRoutes, } from './frontend-sessions.js';
67
- export { createFrontendControl } from './frontend-control.js';
68
- export type { CreateFrontendControlOptions, FrontendBindErrorContext, FrontendControl, FrontendHttpExtension, } from './frontend-control.js';
69
- export type { TerminalActionResponse, TerminalCreateRequest, TerminalListResponse, TerminalsHttpDeps, TerminalsInternalErrorContext, } from './terminals.js';
70
- export { registerTerminalEventStream, registerTerminalRoutes, terminalCreateRoute, terminalDeleteRoute, terminalKillRoute, terminalListRoute, terminalResizeRoute, terminalStdinRoute, } from './terminals.js';
71
- export type { ModelProxyHttpDeps, ModelProxyInternalErrorContext } from './model-proxy.js';
72
- export { registerModelProxyRoutes } from './model-proxy.js';
73
- export type { HealthHttpDeps, HealthReadinessResult, LivenessResponse, ReadinessResponse, VersionResponse } from './health.js';
74
- export { apiHealthRoute, apiReadyRoute, apiVersionInfoRoute, healthRoute, readyRoute, registerHealthRoutes, versionInfoRoute, } from './health.js';
75
- export type { AuthCredentials, AuthProvider, AuthSession, AuthUser, Charge, ChargeInput, ChargeStatus, ConnectorsAuthSessionResponse, ConnectorsAuthUserResponse, ConnectorsAuthVerifyResponse, ConnectorsChargeResponse, ConnectorsDbQueryResponse, ConnectorsDbRecordResponse, ConnectorsHttpDeps, ConnectorsInternalErrorContext, ConnectorsOkResponse, ConnectorsStorageGetResponse, ConnectorsStorageListResponse, ConnectorsStorageMetaResponse, DbProvider, DbQuery, DbRecord, PaymentsProvider, RealtimeProvider, StorageObjectMeta, StorageProvider, StoragePutOptions, } from './connectors.js';
76
- export { connectorsAuthSessionRoute, connectorsAuthSignInRoute, connectorsAuthSignOutRoute, connectorsAuthSignUpRoute, connectorsDbDeleteRoute, connectorsDbGetRoute, connectorsDbInsertRoute, connectorsDbQueryRoute, connectorsDbUpdateRoute, connectorsPaymentsChargeRoute, connectorsPaymentsGetRoute, connectorsPaymentsRefundRoute, connectorsRealtimePublishRoute, connectorsStorageDeleteRoute, connectorsStorageGetRoute, connectorsStorageListRoute, connectorsStoragePutRoute, registerConnectorsRoutes, } from './connectors.js';
77
- export type { ResearchHttpDeps, ResearchInternalErrorContext, ResearchProviderCredentials, ResearchSearchResponse, ResearchSource, } from './research.js';
78
- export { registerResearchRoutes, researchSearchRoute } from './research.js';
79
- export type { MediaGenerateResponse, MediaHttpDeps, MediaInternalErrorContext, MediaTaskDeleteResponse, MediaTaskListResponse, MediaTaskResponse, } from './media.js';
80
- export { mediaGenerateRoute, mediaTaskDeleteRoute, mediaTaskGetRoute, mediaTaskListRoute, registerMediaRoutes, } from './media.js';
81
- export type { AttachmentClaim, AttachmentRejectionReason, AttachmentsHttpDeps, AttachmentsInternalErrorContext, AttachmentStore, AttachmentUploadResponse, CreateDiskAttachmentStoreOptions, ObservedAttachmentIdentity, PendingAttachmentSummary, RecordedAttachmentIdentity, StoredAttachment, } from './attachments.js';
82
- export { ATTACHMENTS_ROUTE_PATH, AttachmentRejectedError, createDiskAttachmentStore, detectAttachmentKind, handleAttachmentCleanup, handleAttachmentUpload, isUnchangedAttachment, registerAttachmentRoutes, sanitizeAttachmentName, writeBoundedAttachmentBody, } from './attachments.js';
83
- export type { XaiAuthStatusResponse, XaiHttpDeps, XaiInternalErrorContext, XaiOauthStartResponse, XaiOkResponse, XaiSearchResponse, } from './xai.js';
84
- export { registerXaiRoutes, xaiAuthStatusRoute, xaiOauthCancelRoute, xaiOauthCompleteRoute, xaiOauthDisconnectRoute, xaiOauthStartRoute, xaiSearchRoute, } from './xai.js';
85
- export { createCompatApiError, createCompatApiErrorResponse, sendApiError as sendCompatApiError, } from './compat.js';
157
+ export { isLoopbackHostname } from '@jini-ai/platform/net';
158
+ export { isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
159
+ export { createCompatApiError, createCompatApiErrorResponse, } from './compat.js';
160
+ export * from './rate-limit.js';
161
+ export * from './middleware.js';
162
+ export * from './verified-origin.js';
163
+ export * from './observability.js';
164
+ export * from './request.js';
165
+ export * from './response.js';
166
+ export * from './origin.js';
86
167
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,40 +1,20 @@
1
1
  export { err, ok } from './types.js';
2
- export { allowedBrowserPorts, assertValidAllowedOrigins, configuredAllowedHosts, configuredAllowedOrigins, isAllowedBrowserHost, isAllowedBrowserOrigin, isIpLiteralHostname, isLoopbackOrPrivateLanHost, isLocalSameOrigin, isPrivateIpv4, parseHostHeader, } from './origin-validation.js';
2
+ export { allowedBrowserPorts, assertValidAllowedOrigins, configuredAllowedHosts, configuredAllowedOrigins, isAllowedBrowserHost, isAllowedBrowserOrigin, isIpLiteralHostname, isLoopbackOrPrivateLanHost, isLocalSameOrigin, isPrivateIpv4, parseHostHeader, } from '@jini-ai/core';
3
3
  export { ClientFacingError, defineJsonRoute, mountJsonRoute } from './adapter.js';
4
4
  export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, } from './route-registration-guard.js';
5
5
  export { createSseChannel, DEFAULT_MAX_QUEUED_SSE_EVENTS, requestedAfterCursor, sendRawApiError } from './sse.js';
6
6
  export { createSseResponse } from './raw-sse.js';
7
- export { denyAllWorkspaceRoots, resolveWorkspaceRoot, WorkspaceRootDeniedError } from './workspace-root.js';
8
7
  export { mountPackHttp } from './pack-http.js';
9
- export { cancelRunsOwnedBy } from './cancel-owned-runs.js';
10
- export { ACTIVE_CONTEXT_TTL_MS, getActiveRoute, registerActiveContextRoutes, setActiveRoute, } from './active-context.js';
11
- export { applicableForPlatform, CATALOGUE, currentPlatform, defaultProbeEnv, hostEditorsRoute, launchHostTool, listAvailableEditors, pathDirs, probeCommandOnPath, probeMacBundle, registerHostToolsRoutes, resolveEntry, resolveHostToolLaunchPlan, } from './host-tools.js';
12
8
  export { bearerTokenFromHeader, registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware, requireStrictBearerToken, timingSafeTokenMatch, } from './api-security-middleware.js';
13
- export { isLoopbackHostname, isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
14
- export { daemonShutdownRoute, daemonStatusRoute, registerDaemonStatusRoutes } from './daemon-status.js';
15
- export { registerRunEventStream, registerRunRoutes, RUN_EVENTS_ROUTE_PATH, runCancelRoute, runListRoute, runStartRoute, runStatusRoute, } from './runs.js';
16
- export { JINI_ROUTE_MANIFEST, manifestRoutesForFamilies, routeFamilyManifest } from './route-manifest.js';
17
- export { agentListRoute, agentRescanRoute, registerAgentRoutes } from './agents.js';
18
- export { memoryClearExtractionsRoute, memoryClearVerificationsRoute, memoryCreateEntryRoute, memoryDeleteEntryRoute, memoryListExtractionsRoute, memoryListVerificationsRoute, memoryOverviewRoute, memoryReadEntryRoute, memoryRemoveExtractionRoute, memoryRemoveVerificationRoute, memoryTreeRoute, memoryUpdateEntryRoute, memoryUpdateTreeNodeRoute, memoryWriteConfigRoute, memoryWriteIndexRoute, registerMemoryEventStream, registerMemoryRoutes, } from './memory.js';
19
- export { registerRoutineRoutes, routineCreateRoute, routineDeleteRoute, routineGetRoute, routineListRoute, routineRunNowRoute, routineRunsListRoute, routineUpdateRoute, } from './routines.js';
20
- export { createDaemonDbToolRegistrations, daemonDbInspectRoute, daemonDbVacuumRoute, daemonDbVerifyRoute, DB_INSPECT_TOOL_ID, DB_VACUUM_TOOL_ID, DB_VERIFY_TOOL_ID, denyAllDaemonDbPolicy, registerDaemonDbRoutes, } from './db-ops.js';
21
- export { registerToolCatalogRoutes, toolCatalogDescribeRoute, toolCatalogSearchRoute, } from './tool-catalog.js';
22
- export { registerComponentCatalogRoutes, componentCatalogDescribeRoute, componentCatalogSearchRoute, } from './component-catalog.js';
23
- export { delegatedToolExecuteRoute, readOnlyRefusalMessage, READ_ONLY_UNVERIFIABLE_MESSAGE, registerDelegatedToolRoutes, } from './delegated-tools.js';
24
- export { registerRemoteRunEventRoutes, remoteToolResultRoute, remoteToolUseRoute, requireRemoteToolBridgeToken, } from './remote-run-events.js';
25
- export { FRONTEND_SESSION_RESPONSE_ROUTE_PATH, FRONTEND_SESSION_STREAM_ROUTE_PATH, frontendSessionResponseRoute, handleFrontendSessionStream, parseCapabilityQuery, registerFrontendSessionRoutes, } from './frontend-sessions.js';
26
- export { createFrontendControl } from './frontend-control.js';
27
- export { registerTerminalEventStream, registerTerminalRoutes, terminalCreateRoute, terminalDeleteRoute, terminalKillRoute, terminalListRoute, terminalResizeRoute, terminalStdinRoute, } from './terminals.js';
28
- export { registerModelProxyRoutes } from './model-proxy.js';
29
- export { apiHealthRoute, apiReadyRoute, apiVersionInfoRoute, healthRoute, readyRoute, registerHealthRoutes, versionInfoRoute, } from './health.js';
30
- export { connectorsAuthSessionRoute, connectorsAuthSignInRoute, connectorsAuthSignOutRoute, connectorsAuthSignUpRoute, connectorsDbDeleteRoute, connectorsDbGetRoute, connectorsDbInsertRoute, connectorsDbQueryRoute, connectorsDbUpdateRoute, connectorsPaymentsChargeRoute, connectorsPaymentsGetRoute, connectorsPaymentsRefundRoute, connectorsRealtimePublishRoute, connectorsStorageDeleteRoute, connectorsStorageGetRoute, connectorsStorageListRoute, connectorsStoragePutRoute, registerConnectorsRoutes, } from './connectors.js';
31
- export { registerResearchRoutes, researchSearchRoute } from './research.js';
32
- export { mediaGenerateRoute, mediaTaskDeleteRoute, mediaTaskGetRoute, mediaTaskListRoute, registerMediaRoutes, } from './media.js';
33
- export { ATTACHMENTS_ROUTE_PATH, AttachmentRejectedError, createDiskAttachmentStore, detectAttachmentKind, handleAttachmentCleanup, handleAttachmentUpload, isUnchangedAttachment, registerAttachmentRoutes, sanitizeAttachmentName, writeBoundedAttachmentBody, } from './attachments.js';
34
- export { registerXaiRoutes, xaiAuthStatusRoute, xaiOauthCancelRoute, xaiOauthCompleteRoute, xaiOauthDisconnectRoute, xaiOauthStartRoute, xaiSearchRoute, } from './xai.js';
35
- // Legacy-shaped compat error helpers (separate code/message/init call shape). `sendApiError`
36
- // above (from `response.ts`) takes a single `ApiError` object; this compat `sendApiError` takes
37
- // `(code, message, init)` — same job, different call-site generation, so it is re-exported here
38
- // under a distinct name to avoid a duplicate export.
39
- export { createCompatApiError, createCompatApiErrorResponse, sendApiError as sendCompatApiError, } from './compat.js';
9
+ export { isLoopbackHostname } from '@jini-ai/platform/net';
10
+ export { isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
11
+ export { createCompatApiError, createCompatApiErrorResponse, } from './compat.js';
12
+ export * from './rate-limit.js';
13
+ export * from './middleware.js';
14
+ export * from './verified-origin.js';
15
+ export * from './observability.js';
16
+ // Generic request/response and origin primitives used by capability-owned route packs.
17
+ export * from './request.js';
18
+ export * from './response.js';
19
+ export * from './origin.js';
40
20
  //# sourceMappingURL=index.js.map
@@ -12,14 +12,18 @@ interface LocalDaemonValidationError {
12
12
  message: string;
13
13
  details: Record<string, string>;
14
14
  }
15
- /** Parses a `Host`-header-shaped authority string, rejecting anything with a path/userinfo/query. */
16
- export declare function normalizeLocalAuthority(value: unknown): LocalAuthority | null;
17
- /** True when `hostname` is `localhost`, an IPv6 loopback literal, or a `127.0.0.0/8` IPv4 literal. */
18
- export declare function isLoopbackHostname(hostname: unknown): boolean;
15
+ /** Parses a `Host`-header-shaped authority string, rejecting anything with a path/userinfo/query/fragment. */
16
+ export declare function normalizeLocalAuthority({ value }: {
17
+ readonly value: unknown;
18
+ }, _optional?: Record<string, never>): LocalAuthority | null;
19
19
  /** True when `address` (typically `req.socket.remoteAddress`) is a loopback peer, unwrapping an IPv4-mapped IPv6 prefix first. */
20
- export declare function isLoopbackPeerAddress(address: unknown): boolean;
20
+ export declare function isLoopbackPeerAddress({ address }: {
21
+ readonly address: unknown;
22
+ }, _optional?: Record<string, never>): boolean;
21
23
  /** Parses an `Origin` header value into its origin string, requiring a bare `scheme://loopback-host[:port]` with no path/query/userinfo. */
22
- export declare function localOriginFromHeader(value: unknown): string | null;
24
+ export declare function localOriginFromHeader({ value }: {
25
+ readonly value: unknown;
26
+ }, _optional?: Record<string, never>): string | null;
23
27
  /**
24
28
  * Validates that `req` is a loopback request: the TCP peer address, the `Host`
25
29
  * header, and (when present) the `Origin` header must all resolve to a
@@ -30,7 +34,9 @@ export declare function localOriginFromHeader(value: unknown): string | null;
30
34
  * `null` when the request carried none); otherwise `{ ok: false, message, details }` naming which
31
35
  * check failed.
32
36
  */
33
- export declare function validateLocalDaemonRequest(req: Request): LocalDaemonValidation | LocalDaemonValidationError;
37
+ export declare function validateLocalDaemonRequest({ req }: {
38
+ readonly req: Request;
39
+ }, _optional?: Record<string, never>): LocalDaemonValidation | LocalDaemonValidationError;
34
40
  /**
35
41
  * Express middleware that rejects any non-loopback request with a 403, and
36
42
  * otherwise sets permissive same-machine CORS headers before calling `next()`.
@@ -39,6 +45,10 @@ export declare function validateLocalDaemonRequest(req: Request): LocalDaemonVal
39
45
  * @param res - The response to reject on, or set CORS headers on before continuing.
40
46
  * @param next - Called when the request validates as loopback.
41
47
  */
42
- export declare function requireLocalDaemonRequest(req: Request, res: Response, next: NextFunction): void | Response;
48
+ export declare function requireLocalDaemonRequest({ req, res, next }: {
49
+ readonly req: Request;
50
+ readonly res: Response;
51
+ readonly next: NextFunction;
52
+ }, _optional?: Record<string, never>): void | Response;
43
53
  export {};
44
54
  //# sourceMappingURL=local-daemon-request.d.ts.map
@@ -10,16 +10,20 @@
10
10
  * allow-list configuration.
11
11
  */
12
12
  import net from 'node:net';
13
- import { sendApiError } from './compat.js';
14
- /** Parses a `Host`-header-shaped authority string, rejecting anything with a path/userinfo/query. */
15
- export function normalizeLocalAuthority(value) {
13
+ import { isLoopbackHostname } from '@jini-ai/platform/net';
14
+ import { createCompatApiError } from './compat.js';
15
+ import { sendApiError } from './response.js';
16
+ /** Parses a `Host`-header-shaped authority string, rejecting anything with a path/userinfo/query/fragment. */
17
+ export function normalizeLocalAuthority({ value }, _optional = {}) {
16
18
  if (typeof value !== 'string')
17
19
  return null;
18
20
  const trimmed = value.trim();
19
- if (!trimmed || /[\s/@]/.test(trimmed) || trimmed.includes(','))
21
+ if (!trimmed || /[\s/@?\\#]/.test(trimmed) || trimmed.includes(','))
20
22
  return null;
21
23
  try {
22
- // The guard above already rejects any `/`, `@`, or whitespace in `trimmed`, and the WHATWG
24
+ // Reject delimiters before parsing: WHATWG URL parsing would otherwise silently discard a
25
+ // query/fragment (including a bare `?`/`#`) or turn a backslash into a path separator.
26
+ // The guard above already rejects any path delimiter, `@`, or whitespace in `trimmed`, and the WHATWG
23
27
  // URL parser requires a non-empty host for an `http:` URL — so `parsed.hostname` is always
24
28
  // non-empty and `parsed.pathname` is always `/` for every `trimmed` value that reaches this
25
29
  // line without throwing. `hostname` below can still end up empty after stripping a trailing
@@ -34,29 +38,15 @@ export function normalizeLocalAuthority(value) {
34
38
  return null;
35
39
  }
36
40
  }
37
- /** True when `hostname` is `localhost`, an IPv6 loopback literal, or a `127.0.0.0/8` IPv4 literal. */
38
- export function isLoopbackHostname(hostname) {
39
- const normalized = String(hostname || '')
40
- .toLowerCase()
41
- .replace(/^\[|\]$/g, '')
42
- .replace(/\.$/, '');
43
- if (normalized === 'localhost')
44
- return true;
45
- if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1')
46
- return true;
47
- if (net.isIP(normalized) === 4)
48
- return normalized === '127.0.0.1' || normalized.startsWith('127.');
49
- return false;
50
- }
51
41
  /** True when `address` (typically `req.socket.remoteAddress`) is a loopback peer, unwrapping an IPv4-mapped IPv6 prefix first. */
52
- export function isLoopbackPeerAddress(address) {
42
+ export function isLoopbackPeerAddress({ address }, _optional = {}) {
53
43
  if (typeof address !== 'string')
54
44
  return false;
55
45
  const normalized = address.trim().toLowerCase().replace(/^\[|\]$/g, '');
56
46
  if (!normalized)
57
47
  return false;
58
48
  if (normalized.startsWith('::ffff:'))
59
- return isLoopbackPeerAddress(normalized.slice('::ffff:'.length));
49
+ return isLoopbackPeerAddress({ address: normalized.slice('::ffff:'.length) });
60
50
  if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1')
61
51
  return true;
62
52
  if (net.isIP(normalized) === 4)
@@ -64,7 +54,7 @@ export function isLoopbackPeerAddress(address) {
64
54
  return false;
65
55
  }
66
56
  /** Parses an `Origin` header value into its origin string, requiring a bare `scheme://loopback-host[:port]` with no path/query/userinfo. */
67
- export function localOriginFromHeader(value) {
57
+ export function localOriginFromHeader({ value }, _optional = {}) {
68
58
  if (typeof value !== 'string')
69
59
  return null;
70
60
  const trimmed = value.trim();
@@ -76,7 +66,7 @@ export function localOriginFromHeader(value) {
76
66
  return null;
77
67
  if (parsed.pathname !== '/' || parsed.search || parsed.hash || parsed.username || parsed.password)
78
68
  return null;
79
- if (!isLoopbackHostname(parsed.hostname))
69
+ if (!isLoopbackHostname({ hostname: parsed.hostname }))
80
70
  return null;
81
71
  return parsed.origin;
82
72
  }
@@ -94,16 +84,16 @@ export function localOriginFromHeader(value) {
94
84
  * `null` when the request carried none); otherwise `{ ok: false, message, details }` naming which
95
85
  * check failed.
96
86
  */
97
- export function validateLocalDaemonRequest(req) {
98
- if (!isLoopbackPeerAddress(req.socket?.remoteAddress)) {
87
+ export function validateLocalDaemonRequest({ req }, _optional = {}) {
88
+ if (!isLoopbackPeerAddress({ address: req.socket?.remoteAddress })) {
99
89
  return {
100
90
  ok: false,
101
91
  message: 'request peer must be a loopback address',
102
92
  details: { peer: 'remoteAddress' },
103
93
  };
104
94
  }
105
- const host = normalizeLocalAuthority(req.get('host'));
106
- if (!host || !isLoopbackHostname(host.hostname)) {
95
+ const host = normalizeLocalAuthority({ value: req.get('host') });
96
+ if (!host || !isLoopbackHostname({ hostname: host.hostname })) {
107
97
  return {
108
98
  ok: false,
109
99
  message: 'request host must be a loopback daemon address',
@@ -111,14 +101,14 @@ export function validateLocalDaemonRequest(req) {
111
101
  };
112
102
  }
113
103
  const originHeader = req.get('origin');
114
- if (originHeader !== undefined && !localOriginFromHeader(originHeader)) {
104
+ if (originHeader !== undefined && !localOriginFromHeader({ value: originHeader })) {
115
105
  return {
116
106
  ok: false,
117
107
  message: 'request origin must be a loopback daemon origin',
118
108
  details: { header: 'origin' },
119
109
  };
120
110
  }
121
- return { ok: true, origin: localOriginFromHeader(originHeader) };
111
+ return { ok: true, origin: localOriginFromHeader({ value: originHeader }) };
122
112
  }
123
113
  /**
124
114
  * Express middleware that rejects any non-loopback request with a 403, and
@@ -128,10 +118,11 @@ export function validateLocalDaemonRequest(req) {
128
118
  * @param res - The response to reject on, or set CORS headers on before continuing.
129
119
  * @param next - Called when the request validates as loopback.
130
120
  */
131
- export function requireLocalDaemonRequest(req, res, next) {
132
- const validation = validateLocalDaemonRequest(req);
121
+ export function requireLocalDaemonRequest({ req, res, next }, _optional = {}) {
122
+ const validation = validateLocalDaemonRequest({ req });
133
123
  if (!validation.ok) {
134
- return sendApiError(res, 403, 'FORBIDDEN', validation.message, { details: validation.details });
124
+ sendApiError({ res, status: 403, error: createCompatApiError({ code: 'FORBIDDEN', message: validation.message }, { details: validation.details }) });
125
+ return;
135
126
  }
136
127
  res.setHeader('Vary', 'Origin');
137
128
  if (validation.origin) {
package/dist/memory.d.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  * importing `@jini-ai/memory` directly would fail `pnpm guard`'s R7 check
17
17
  * outright (the same constraint `packages/media/src/sqlite-task-store.ts`'s
18
18
  * `ADS-memory/reports/proposals/PROP-media-durable-tasks-2026-07-21.md`
19
- * documents for `@jini-ai/sqlite`/`@jini-ai/media`). The types below
19
+ * documents for `@jini-ai/sqlite-chat`/`@jini-ai/media`). The types below
20
20
  * (`MemoryNoteStore`/`MemoryExtractionLog`/`MemoryVerifyLog`) are local,
21
21
  * structural mirrors of `@jini-ai/memory`'s real `NoteStore`/`ExtractionLog`/
22
22
  * `VerifyLog` interfaces — a real `@jini-ai/memory` instance satisfies them
@@ -0,0 +1,20 @@
1
+ import type { RequestHandler } from 'express';
2
+ /** Host response wording and envelope, evaluated only for an oversized body. */
3
+ export type ErrorResponseFactory = (required: {
4
+ maxBytes: number;
5
+ bodyBytes: number;
6
+ }) => unknown;
7
+ export interface BodySizeLimitRequired {
8
+ readonly maxBytes: number;
9
+ readonly errorResponseFactory: ErrorResponseFactory;
10
+ }
11
+ export type BodySizeLimitOptional = Record<string, never>;
12
+ /**
13
+ * Enforces a route-specific UTF-8 byte ceiling on already-parsed JSON.
14
+ * Mount after the host JSON parser, whose allocation ceiling remains necessary.
15
+ * Null and undefined preserve the original empty-object serialization fallback.
16
+ * @param required - Byte ceiling and required host error-response wording.
17
+ * @returns Express middleware; oversized requests receive 413 without next().
18
+ */
19
+ export declare function rejectOversizedJsonBody({ maxBytes, errorResponseFactory }: BodySizeLimitRequired, _optional?: BodySizeLimitOptional): RequestHandler;
20
+ //# sourceMappingURL=middleware.d.ts.map
@@ -0,0 +1,21 @@
1
+ // A second express.json({ limit }) silently skips a body already parsed upstream, so it cannot
2
+ // tighten a route's limit. Re-measure the serialized bytes here; the upstream parser must still
3
+ // bound initial allocation. Reject before next() so an oversized body never reaches a write.
4
+ /**
5
+ * Enforces a route-specific UTF-8 byte ceiling on already-parsed JSON.
6
+ * Mount after the host JSON parser, whose allocation ceiling remains necessary.
7
+ * Null and undefined preserve the original empty-object serialization fallback.
8
+ * @param required - Byte ceiling and required host error-response wording.
9
+ * @returns Express middleware; oversized requests receive 413 without next().
10
+ */
11
+ export function rejectOversizedJsonBody({ maxBytes, errorResponseFactory }, _optional = {}) {
12
+ return (req, res, next) => {
13
+ const bodyBytes = Buffer.byteLength(JSON.stringify(req.body ?? {}), 'utf8');
14
+ if (bodyBytes > maxBytes) {
15
+ res.status(413).json(errorResponseFactory({ maxBytes, bodyBytes }));
16
+ return;
17
+ }
18
+ next();
19
+ };
20
+ }
21
+ //# sourceMappingURL=middleware.js.map
@@ -0,0 +1,29 @@
1
+ import type { Express, RequestHandler } from 'express';
2
+ /** Structural port satisfied by diagnostics/observability, with host-owned logging and tracing. */
3
+ export interface HttpRequestObservabilityPort {
4
+ trackRequest(required: {
5
+ method: string;
6
+ path: string;
7
+ }): {
8
+ end(required: {
9
+ statusCode: number;
10
+ routePattern: string;
11
+ }): void;
12
+ };
13
+ }
14
+ /** Track requests before routing and read the mount-aware route pattern at response completion.
15
+ * Unmatched paths use a fixed label so attacker-selected paths do not become metric labels.
16
+ * Each response completes its tracker once; hook error policy belongs to the injected adapter.
17
+ * @complexity O(1) per request, excluding injected hooks and Express routing.
18
+ */
19
+ export declare function createRequestTrackingMiddleware({ observability }: {
20
+ observability: HttpRequestObservabilityPort;
21
+ }): RequestHandler;
22
+ /** Mount first, before serving gates and routes, so refusals and unmatched requests are measured.
23
+ * @complexity O(1) registration; effects are restricted to Express middleware registration.
24
+ */
25
+ export declare function applyRequestTracking({ app, observability }: {
26
+ app: Express;
27
+ observability: HttpRequestObservabilityPort;
28
+ }): void;
29
+ //# sourceMappingURL=observability.d.ts.map
@@ -0,0 +1,22 @@
1
+ /** Track requests before routing and read the mount-aware route pattern at response completion.
2
+ * Unmatched paths use a fixed label so attacker-selected paths do not become metric labels.
3
+ * Each response completes its tracker once; hook error policy belongs to the injected adapter.
4
+ * @complexity O(1) per request, excluding injected hooks and Express routing.
5
+ */
6
+ export function createRequestTrackingMiddleware({ observability }) {
7
+ return (req, res, next) => {
8
+ const tracker = observability.trackRequest({ method: req.method, path: req.path });
9
+ res.once('finish', () => {
10
+ const routePattern = req.route ? `${req.baseUrl}${req.route.path}` : 'unmatched';
11
+ tracker.end({ statusCode: res.statusCode, routePattern });
12
+ });
13
+ next();
14
+ };
15
+ }
16
+ /** Mount first, before serving gates and routes, so refusals and unmatched requests are measured.
17
+ * @complexity O(1) registration; effects are restricted to Express middleware registration.
18
+ */
19
+ export function applyRequestTracking({ app, observability }) {
20
+ app.use(createRequestTrackingMiddleware({ observability }));
21
+ }
22
+ //# sourceMappingURL=observability.js.map
package/dist/origin.d.ts CHANGED
@@ -3,17 +3,16 @@
3
3
  * the Adapter can treat an origin failure the same as a parse/handle failure.
4
4
  */
5
5
  import type { Request } from 'express';
6
+ import { type OriginValidationEnvConfig } from '@jini-ai/core';
6
7
  import { type Result } from './types.js';
7
8
  /** The subset of server startup state `guardSameOrigin` needs: the resolved local port, and the
8
9
  * environment the origin policy is read from. */
9
- export interface OriginContext {
10
+ export interface OriginContext extends OriginValidationEnvConfig {
10
11
  resolvedPortRef: {
11
12
  current: number;
12
13
  };
13
14
  /**
14
- * Environment `JINI_BIND_HOST`, `JINI_ALLOWED_ORIGINS` and `JINI_WEB_PORT` are read from.
15
- *
16
- * @default `process.env`
15
+ * Host-supplied environment; the host also names the bind-host, allowed-origin and web-port vars.
17
16
  *
18
17
  * Present because a host can inject its own environment (`@jini-ai/server`'s
19
18
  * `createLocalNodeDaemon`/`composeJiniKernel` `env` option), and that injection already reaches
@@ -22,11 +21,14 @@ export interface OriginContext {
22
21
  * the host configured and the per-route guard then rejects it, or a bind host the host never set
23
22
  * decides what counts as same-origin.
24
23
  */
25
- env?: NodeJS.ProcessEnv;
24
+ env: NodeJS.ProcessEnv;
26
25
  }
27
26
  /**
28
27
  * Wraps `isLocalSameOrigin` so the HTTP Adapter can fold the origin decision into the same
29
28
  * error-handling pipeline as parse/handle failures.
30
29
  */
31
- export declare function guardSameOrigin(req: Request, origin: OriginContext): Result<void>;
30
+ export declare function guardSameOrigin({ req, origin }: {
31
+ readonly req: Request;
32
+ readonly origin: OriginContext;
33
+ }, _optional?: Record<string, never>): Result<void>;
32
34
  //# sourceMappingURL=origin.d.ts.map