@jini-ai/http-kit 0.7.1 → 0.7.3-next.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 (70) hide show
  1. package/CHANGELOG.md +2 -2
  2. package/README.md +6 -6
  3. package/dist/adapter.d.ts +7 -50
  4. package/dist/adapter.js +12 -54
  5. package/dist/api-security-middleware.d.ts +0 -16
  6. package/dist/api-security-middleware.js +2 -18
  7. package/dist/index.d.ts +10 -15
  8. package/dist/index.js +7 -10
  9. package/dist/internal-error.d.ts +42 -0
  10. package/dist/internal-error.js +48 -0
  11. package/dist/local-daemon-request.d.ts +11 -4
  12. package/dist/local-daemon-request.js +1 -28
  13. package/dist/middleware.d.ts +1 -0
  14. package/dist/middleware.js +1 -0
  15. package/dist/node-bridge.d.ts +108 -0
  16. package/dist/node-bridge.js +356 -0
  17. package/dist/observability.d.ts +3 -14
  18. package/dist/origin.d.ts +13 -30
  19. package/dist/origin.js +13 -13
  20. package/dist/range.d.ts +53 -0
  21. package/dist/range.js +93 -0
  22. package/dist/rate-limit.d.ts +1 -13
  23. package/dist/rate-limit.js +5 -2
  24. package/dist/request.d.ts +2 -13
  25. package/dist/request.js +0 -13
  26. package/dist/response.d.ts +8 -7
  27. package/dist/response.js +0 -36
  28. package/dist/route-registration-guard.d.ts +14 -0
  29. package/dist/route-registration-guard.js +17 -0
  30. package/dist/run-credentials.d.ts +73 -0
  31. package/dist/run-credentials.js +71 -0
  32. package/dist/settings/contracts.d.ts +49 -0
  33. package/dist/settings/contracts.js +2 -0
  34. package/dist/settings/http-request.d.ts +36 -0
  35. package/dist/settings/http-request.js +50 -0
  36. package/dist/settings/http.d.ts +10 -0
  37. package/dist/settings/http.js +216 -0
  38. package/dist/settings/index.d.ts +4 -0
  39. package/dist/settings/index.js +3 -0
  40. package/dist/settings/shared.d.ts +16 -0
  41. package/dist/settings/shared.js +16 -0
  42. package/dist/settings/stream.d.ts +25 -0
  43. package/dist/settings/stream.js +180 -0
  44. package/dist/sse.d.ts +1 -15
  45. package/dist/sse.js +77 -72
  46. package/dist/trust-proxy.d.ts +36 -0
  47. package/dist/trust-proxy.js +45 -0
  48. package/dist/types.d.ts +4 -52
  49. package/dist/types.js +1 -4
  50. package/package.json +24 -14
  51. package/dist/raw-sse.d.ts +0 -49
  52. package/dist/raw-sse.js +0 -92
  53. package/dist/verified-origin/configured-origin.d.ts +0 -37
  54. package/dist/verified-origin/configured-origin.js +0 -99
  55. package/dist/verified-origin/index.d.ts +0 -7
  56. package/dist/verified-origin/index.js +0 -6
  57. package/dist/verified-origin/loopback-host.d.ts +0 -9
  58. package/dist/verified-origin/loopback-host.js +0 -17
  59. package/dist/verified-origin/origin.d.ts +0 -64
  60. package/dist/verified-origin/origin.js +0 -162
  61. package/dist/verified-origin/ports.d.ts +0 -38
  62. package/dist/verified-origin/ports.js +0 -2
  63. package/dist/verified-origin/repo.memory.d.ts +0 -32
  64. package/dist/verified-origin/repo.memory.js +0 -34
  65. package/dist/verified-origin/site-path.d.ts +0 -113
  66. package/dist/verified-origin/site-path.js +0 -188
  67. package/dist/verified-origin/types.d.ts +0 -33
  68. package/dist/verified-origin/types.js +0 -30
  69. package/dist/verified-origin.d.ts +0 -2
  70. package/dist/verified-origin.js +0 -2
package/CHANGELOG.md CHANGED
@@ -142,7 +142,7 @@
142
142
  The route was named `agui-stream` from when Jini's own run-event protocol was mistakenly branded as
143
143
  AG-UI; the TypeScript symbols were renamed to `GenUi` on 2026-07-27, but the URL was deliberately left
144
144
  un-renamed on the assumption it was a wire contract an already-deployed client might be calling. A
145
- 2026-08-18 audit found zero callers anywhere — no client in this repo or in `Tovu` ever requested it,
145
+ 2026-08-18 audit found zero callers anywhere — no client in this repo or in the first host ever requested it,
146
146
  `examples/reference-web`'s daemon only registered the route without anything ever calling it, and
147
147
  `@jini-ai/http-kit` has never been published to npm, so no external integrator could depend on it either.
148
148
  Rather than carry a dead, confusingly-named route indefinitely, it was removed outright.
@@ -241,7 +241,7 @@
241
241
 
242
242
  ### Patch Changes
243
243
 
244
- - 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).
244
+ - Host clean-up release (2026-10-08): code the first host moved into Jini, plus the Jini clean-up (see the commit log since 0.4.0).
245
245
 
246
246
  ## 0.4.0 — 2026-10-02
247
247
 
package/README.md CHANGED
@@ -18,11 +18,11 @@ There is no daemon, agent-runtime or CMS dependency.
18
18
 
19
19
  ## Surface
20
20
 
21
- - Route specs, `ok({ value })`, `err({ error })`, `defineJsonRoute` and `mountJsonRoute`.
22
- - Request parsing, `validationError`, `sendJson`, `sendApiError` and `statusForError`.
21
+ - The Express `mountJsonRoute` and its route-spec shapes; the framework-free vocabulary (`Result`, `jsonRoute`, `validationError`, `statusForError`, origin checks, SSE stream) is `@jini-ai/core/contracts/server`.
22
+ - Express request parsing, `sendJson` and `sendApiError`.
23
23
  - Origin and bearer guards, including core's canonical origin validation and Node token comparison.
24
24
  - Cursor-aware and raw SSE primitives, route registration inventory and `mountPackHttp`.
25
- - `./rate-limit`, `./middleware`, `./verified-origin` and `./observability`.
25
+ - `./rate-limit`, `./middleware`, `./observability` and `./range`.
26
26
 
27
27
  - `rate-limit` exports `createRateLimiter({ profile, clock, store })`,
28
28
  `createMemoryCounterStore({})`, and `resolveClientIp({ source, policy })`.
@@ -51,7 +51,7 @@ no consumer used it and maintaining every route twice imposed recurring work. It
51
51
  and rationale remain on `future/fastify-transport` in `FASTIFY-TRANSPORT-PARKED.md`.
52
52
 
53
53
  Settings routes and their CMS adapters now live at `@jini-ai/cms/http/settings`; this
54
- package has no CMS dependency. `./verified-origin`
54
+ package has no CMS dependency. The verified-origin registry (`@jini-ai/core/contracts/server/verified-origin`)
55
55
  is a separate canonical-origin registry with required configuration evidence and
56
56
  repository ports; it does not infer trust from request headers. Its canonical-origin
57
57
  request type is `VerifiedOriginRequestContext`.
@@ -67,8 +67,8 @@ Bearer gates require their environment and token variable names in argument one;
67
67
  The async limiter uses core `Clock.nowMs()` and keeps non-empty-key validation.
68
68
 
69
69
  `./observability` supplies `applyRequestTracking` and
70
- `createRequestTrackingMiddleware` over the diagnostics-compatible
71
- `HttpRequestObservabilityPort`. Mount first to include refusals and unmatched
70
+ `createRequestTrackingMiddleware` over core's
71
+ `ObservabilityPort` (`Pick<ObservabilityPort, 'trackRequest'>`). Mount first to include refusals and unmatched
72
72
  requests; route labels are read at response completion.
73
73
 
74
74
 
package/dist/adapter.d.ts CHANGED
@@ -1,54 +1,11 @@
1
- import type { Express } from 'express';
2
- import { type ApiError } from '@jini-ai/protocol';
3
- import { type OriginContext } from './origin.js';
4
- import type { JsonRouteSpec } from './types.js';
5
- export interface AdapterInternalErrorContext {
6
- /** HTTP method of the route whose handler threw. */
7
- readonly method: string;
8
- /** Registered path of the route whose handler threw. */
9
- readonly path: string;
10
- /** Echoed back to the caller as the response's `requestId`, so an operator can tie a user's report to this log line. */
11
- readonly correlationId: string;
12
- /** The exception exactly as thrown — never sent to the caller. */
13
- readonly error: unknown;
14
- }
15
- /** Server startup state a mounted route needs to evaluate its same-origin guard. */
16
- export interface AdapterContext extends OriginContext {
17
- /**
18
- * Host-owned sink for the real exception behind a generic `INTERNAL_ERROR` response (SEC-005).
19
- * Defaults to `console.error`. Mirrors the per-module `onInternalError` seams (`connectors.ts`,
20
- * `delegated-tools.ts`, …); this one is the catch-all for a route that throws outside its own
21
- * guarded path.
22
- */
23
- readonly onInternalError?: (context: AdapterInternalErrorContext) => void;
24
- }
25
1
  /**
26
- * Thrown by a route's `handle` — or by anything it calls, at any depth — to bypass the SEC-005
27
- * redaction below with an `ApiError` the throwing code has already decided is safe for the caller
28
- * to see. This is the general-purpose version of a carve-out every consuming module of this catch
29
- * otherwise hand-rolls for itself: `attachments.ts`'s `AttachmentRejectedError`/
30
- * `respondToUploadFailure`, and `delegated-tools.ts`'s `errorKind: 'validation'` split on
31
- * `ToolExecutionResult`, both exist because nothing at THIS layer distinguished "the code that threw
32
- * already classified this as caller-safe" from "something unanticipated happened" — so a route with
33
- * no such local carve-out has no way to disclose even a deliberately-safe failure, and everything it
34
- * throws redacts identically to a stray filesystem or driver error.
35
- *
36
- * Prefer returning `err(apiError)` from `handle` when the failure is anticipated at that point —
37
- * that path already reaches the caller with full fidelity and never touches this catch at all. This
38
- * class exists for the same kind of failure discovered a level deeper: inside an awaited call
39
- * `handle` itself did not (or could not) wrap in its own `try`.
40
- *
41
- * Not a way to defeat SEC-005: the only way to reach the branch that reads this class is for code to
42
- * construct one itself, naming the exact `ApiError` — code and message — it is choosing to disclose.
43
- * Any thrown value that is not this class (including a plain `Error` with an actionable-looking
44
- * message) still redacts exactly as before; nothing here widens what a route can leak by accident.
2
+ * The module's top orchestration layer: wires request parsing, the same-origin guard, a route's
3
+ * `handle`, and response serialization into a single Express route handler. This is the only
4
+ * file in the module that knows about Express `req`/`res` on the mounting side.
45
5
  */
46
- export declare class ClientFacingError extends Error {
47
- readonly apiError: ApiError;
48
- constructor({ apiError }: {
49
- readonly apiError: ApiError;
50
- }, _optional?: Record<string, never>);
51
- }
6
+ import type { Express } from 'express';
7
+ import { type RouteHostContext } from '@jini-ai/core/contracts/server';
8
+ import type { JsonRouteSpec } from './types.js';
52
9
  /**
53
10
  * Combines required route fields and optional settings into a fresh spec while pinning its generic
54
11
  * parameters at the definition site so callers do not have to repeat them. Optional settings take
@@ -72,6 +29,6 @@ export declare function mountJsonRoute<Input, Output, Deps, Context = undefined>
72
29
  readonly app: Express;
73
30
  readonly spec: JsonRouteSpec<Input, Output, Deps, Context>;
74
31
  readonly deps: Deps;
75
- readonly adapter?: AdapterContext;
32
+ readonly adapter?: RouteHostContext;
76
33
  }, _optional?: Record<string, never>): void;
77
34
  //# sourceMappingURL=adapter.d.ts.map
package/dist/adapter.js CHANGED
@@ -1,49 +1,8 @@
1
- /**
2
- * The module's top orchestration layer: wires request parsing, the same-origin guard, a route's
3
- * `handle`, and response serialization into a single Express route handler. This is the only
4
- * file in the module that knows about Express `req`/`res` on the mounting side.
5
- */
6
- import { inspect } from 'node:util';
7
- import { redactSecrets } from '@jini-ai/core';
8
- import { randomUUID } from 'node:crypto';
9
- import { createApiError } from '@jini-ai/protocol';
1
+ import { ClientFacingError, statusForError } from '@jini-ai/core/contracts/server';
2
+ import { reportRouteInternalError } from './internal-error.js';
10
3
  import { rawInput } from './request.js';
11
- import { sendApiError, sendJson, statusForError } from './response.js';
12
- import { guardSameOrigin } from './origin.js';
13
- function defaultInternalErrorSink(context) {
14
- // Exceptions can echo credentials; inspect preserves stacks and codes before shared redaction.
15
- // eslint-disable-next-line no-console
16
- console.error(`[@jini-ai/http-kit] internal error (${context.method.toUpperCase()} ${context.path}, correlationId=${context.correlationId})`, redactSecrets({ input: inspect(context.error) }, { redactPii: false }));
17
- }
18
- /**
19
- * Thrown by a route's `handle` — or by anything it calls, at any depth — to bypass the SEC-005
20
- * redaction below with an `ApiError` the throwing code has already decided is safe for the caller
21
- * to see. This is the general-purpose version of a carve-out every consuming module of this catch
22
- * otherwise hand-rolls for itself: `attachments.ts`'s `AttachmentRejectedError`/
23
- * `respondToUploadFailure`, and `delegated-tools.ts`'s `errorKind: 'validation'` split on
24
- * `ToolExecutionResult`, both exist because nothing at THIS layer distinguished "the code that threw
25
- * already classified this as caller-safe" from "something unanticipated happened" — so a route with
26
- * no such local carve-out has no way to disclose even a deliberately-safe failure, and everything it
27
- * throws redacts identically to a stray filesystem or driver error.
28
- *
29
- * Prefer returning `err(apiError)` from `handle` when the failure is anticipated at that point —
30
- * that path already reaches the caller with full fidelity and never touches this catch at all. This
31
- * class exists for the same kind of failure discovered a level deeper: inside an awaited call
32
- * `handle` itself did not (or could not) wrap in its own `try`.
33
- *
34
- * Not a way to defeat SEC-005: the only way to reach the branch that reads this class is for code to
35
- * construct one itself, naming the exact `ApiError` — code and message — it is choosing to disclose.
36
- * Any thrown value that is not this class (including a plain `Error` with an actionable-looking
37
- * message) still redacts exactly as before; nothing here widens what a route can leak by accident.
38
- */
39
- export class ClientFacingError extends Error {
40
- apiError;
41
- constructor({ apiError }, _optional = {}) {
42
- super(apiError.message);
43
- this.name = 'ClientFacingError';
44
- this.apiError = apiError;
45
- }
46
- }
4
+ import { sendApiError, sendJson } from './response.js';
5
+ import { passesSameOriginGuard } from './origin.js';
47
6
  /**
48
7
  * Combines required route fields and optional settings into a fresh spec while pinning its generic
49
8
  * parameters at the definition site so callers do not have to repeat them. Optional settings take
@@ -121,11 +80,7 @@ function allowRouteOrigin({ req, res, spec, adapter }, _optional = {}) {
121
80
  return true;
122
81
  if (!adapter)
123
82
  throw new Error('same-origin adapter context is required');
124
- const origin = guardSameOrigin({ req, origin: adapter });
125
- if (origin.ok)
126
- return true;
127
- sendApiError({ res, status: statusForError({ error: origin.error }), error: origin.error });
128
- return false;
83
+ return passesSameOriginGuard({ req, res, origin: adapter });
129
84
  }
130
85
  function sendRouteResult({ res, result, spec, signal }, _optional = {}) {
131
86
  // `signal` can only have been aborted by `onResponseClose` firing while the
@@ -162,9 +117,12 @@ function sendRouteException({ res, spec, adapter, error: e }, _optional = {}) {
162
117
  // mounted ahead of the security middleware and exempted from the bearer gate, an unauthorized
163
118
  // caller could read it too, simply by getting a readiness dependency to fail. The real error
164
119
  // still reaches the operator through the sink, correlated to what the caller was told.
165
- const correlationId = randomUUID();
166
- const sink = adapter?.onInternalError ?? defaultInternalErrorSink;
167
- sink({ method: spec.method, path: spec.path, correlationId, error: e });
168
- sendApiError({ res, status: 500, error: createApiError({ code: 'INTERNAL_ERROR', message: 'The server could not finish this request. Check whether your change was saved, then copy the request ID and report this problem.' }, { requestId: correlationId }) });
120
+ // Exceptions can echo credentials: the host sink gets the original; the default line prints class and code only.
121
+ const apiError = reportRouteInternalError({
122
+ report: { method: spec.method, path: spec.path, error: e },
123
+ logSource: `${spec.method.toUpperCase()} ${spec.path}`,
124
+ message: 'The server could not finish this request. Check whether your change was saved, then copy the request ID and report this problem.',
125
+ }, { onInternalError: adapter?.onInternalError });
126
+ sendApiError({ res, status: 500, error: apiError });
169
127
  }
170
128
  //# sourceMappingURL=adapter.js.map
@@ -1,21 +1,5 @@
1
1
  import type { Express, NextFunction, Request, Response } from 'express';
2
2
  import { type OriginValidationEnvConfig, type ApiTokenAuthEnvConfig } from '@jini-ai/core';
3
- /**
4
- * Extracts the token from an `Authorization: Bearer <token>` header value. The scheme is
5
- * case-insensitive per RFC 7235 §2.1; the token itself is not.
6
- *
7
- * Shared by every bearer gate in this package so the accepted header grammar is defined exactly
8
- * once — three separate copies of this regex is three chances for them to disagree about what
9
- * counts as a well-formed header.
10
- *
11
- * @param header - The raw `Authorization` header value, or `undefined` when absent.
12
- * @returns The token, or `null` when the header is absent or not a well-formed bearer header.
13
- * @complexity O(n) in the header length.
14
- * @overallScore 100/100
15
- */
16
- export declare function bearerTokenFromHeader({ header }: {
17
- readonly header: string | undefined;
18
- }, _optional?: Record<string, never>): string | null;
19
3
  /**
20
4
  * Constant-time token comparison. Length is compared first and NOT in constant time — that leaks
21
5
  * only the expected token's length, which for a generated secret is fixed and not itself a secret,
@@ -23,7 +23,8 @@
23
23
  */
24
24
  import { timingSafeEqual } from 'node:crypto';
25
25
  import { apiTokenFromEnv, allowedBrowserPorts, isAllowedBrowserOrigin, timingSafeTokenMatch as compareTokenWithPort, isApiTokenMiddlewareEnabled, } from '@jini-ai/core';
26
- import { isLoopbackPeerAddress } from './local-daemon-request.js';
26
+ import { bearerTokenFromHeader } from '@jini-ai/core/contracts/server';
27
+ import { isLoopbackPeerAddress } from '@jini-ai/core/net';
27
28
  /** Health/readiness/version probes stay reachable without a bearer token so monitoring never needs one. Both the mount-relative and `/api`-prefixed forms are listed because this middleware is always registered via `app.use('/api', ...)`, under which Express strips the `/api` prefix from `req.path` for a request to `/api/health` — the prefixed form is kept for parity with the origin module's own set rather than dropped as dead, in case a future caller mounts this middleware unprefixed. */
28
29
  const OPEN_PROBE_PATHS = new Set([
29
30
  '/health',
@@ -33,23 +34,6 @@ const OPEN_PROBE_PATHS = new Set([
33
34
  '/version',
34
35
  '/api/version',
35
36
  ]);
36
- const BEARER_TOKEN_PATTERN = /^Bearer\s+(\S+)\s*$/i;
37
- /**
38
- * Extracts the token from an `Authorization: Bearer <token>` header value. The scheme is
39
- * case-insensitive per RFC 7235 §2.1; the token itself is not.
40
- *
41
- * Shared by every bearer gate in this package so the accepted header grammar is defined exactly
42
- * once — three separate copies of this regex is three chances for them to disagree about what
43
- * counts as a well-formed header.
44
- *
45
- * @param header - The raw `Authorization` header value, or `undefined` when absent.
46
- * @returns The token, or `null` when the header is absent or not a well-formed bearer header.
47
- * @complexity O(n) in the header length.
48
- * @overallScore 100/100
49
- */
50
- export function bearerTokenFromHeader({ header }, _optional = {}) {
51
- return BEARER_TOKEN_PATTERN.exec(header ?? '')?.[1] ?? null;
52
- }
53
37
  /**
54
38
  * Constant-time token comparison. Length is compared first and NOT in constant time — that leaks
55
39
  * only the expected token's length, which for a generated secret is fixed and not itself a secret,
package/dist/index.d.ts CHANGED
@@ -9,29 +9,24 @@
9
9
  * owns sending. See the capability owners for raw-stream uploads, bodyless cleanup, attachment
10
10
  * rejection mapping and host-owned claim/cleanup lifecycle rather than duplicating those rules here.
11
11
  */
12
- export type { Handler, HttpMethod, InputParser, JsonRouteSpec, JsonRoutePorts, JsonRouteAuthorize, Result, RouteInputContext, } from './types.js';
13
- export { err, ok } from './types.js';
14
- export type { ParsedHostHeader, RequestWithOriginHeaders, } from '@jini-ai/core';
15
- export { allowedBrowserPorts, assertValidAllowedOrigins, configuredAllowedHosts, configuredAllowedOrigins, isAllowedBrowserHost, isAllowedBrowserOrigin, isIpLiteralHostname, isLoopbackOrPrivateLanHost, isLocalSameOrigin, isPrivateIpv4, parseHostHeader, } from '@jini-ai/core';
16
- export type { AdapterContext } from './adapter.js';
17
- export { ClientFacingError, defineJsonRoute, mountJsonRoute } from './adapter.js';
12
+ export type { JsonRouteSpec, JsonRoutePorts } from './types.js';
13
+ export { defineJsonRoute, mountJsonRoute } from './adapter.js';
14
+ export type { RouteInternalErrorContext, RouteInternalErrorSink } from './internal-error.js';
15
+ export { reportRouteInternalError } from './internal-error.js';
18
16
  export type { InstallRouteRegistrationGuardOptions, RouteRegistration } from './route-registration-guard.js';
19
- export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, } from './route-registration-guard.js';
20
- export type { CreateSseChannelOptions, SseChannel, SseEvent } from './sse.js';
21
- export { createSseChannel, DEFAULT_MAX_QUEUED_SSE_EVENTS, requestedAfterCursor, sendRawApiError } from './sse.js';
22
- export type { CreateSseResponseOptions, SseConnection } from './raw-sse.js';
23
- export { createSseResponse } from './raw-sse.js';
17
+ export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, recordRouteRegistrations, } from './route-registration-guard.js';
18
+ export type { CreateSseChannelOptions, SseChannel } from './sse.js';
19
+ export { createSseChannel, requestedAfterCursor, sendRawApiError } from './sse.js';
24
20
  export { mountPackHttp } from './pack-http.js';
25
21
  export type { ApiBearerAuthMiddlewareDeps, ApiOriginGuardMiddlewareDeps, StrictBearerTokenDeps, } from './api-security-middleware.js';
26
- export { bearerTokenFromHeader, registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware, requireStrictBearerToken, timingSafeTokenMatch, } from './api-security-middleware.js';
27
- export { isLoopbackHostname } from '@jini-ai/platform/net';
28
- export { isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
22
+ export { registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware, requireStrictBearerToken, timingSafeTokenMatch, } from './api-security-middleware.js';
23
+ export { localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
29
24
  export { createCompatApiError, createCompatApiErrorResponse, } from './compat.js';
30
25
  export * from './rate-limit.js';
31
26
  export * from './middleware.js';
32
- export * from './verified-origin.js';
33
27
  export * from './observability.js';
34
28
  export * from './request.js';
35
29
  export * from './response.js';
36
30
  export * from './origin.js';
31
+ export * from './trust-proxy.js';
37
32
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,20 +1,17 @@
1
- export { err, ok } from './types.js';
2
- export { allowedBrowserPorts, assertValidAllowedOrigins, configuredAllowedHosts, configuredAllowedOrigins, isAllowedBrowserHost, isAllowedBrowserOrigin, isIpLiteralHostname, isLoopbackOrPrivateLanHost, isLocalSameOrigin, isPrivateIpv4, parseHostHeader, } from '@jini-ai/core';
3
- export { ClientFacingError, defineJsonRoute, mountJsonRoute } from './adapter.js';
4
- export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, } from './route-registration-guard.js';
5
- export { createSseChannel, DEFAULT_MAX_QUEUED_SSE_EVENTS, requestedAfterCursor, sendRawApiError } from './sse.js';
6
- export { createSseResponse } from './raw-sse.js';
1
+ export { defineJsonRoute, mountJsonRoute } from './adapter.js';
2
+ export { reportRouteInternalError } from './internal-error.js';
3
+ export { getRouteRegistrationInventory, guardedRouteKey, installRouteRegistrationGuard, recordRouteRegistrations, } from './route-registration-guard.js';
4
+ export { createSseChannel, requestedAfterCursor, sendRawApiError } from './sse.js';
7
5
  export { mountPackHttp } from './pack-http.js';
8
- export { bearerTokenFromHeader, registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware, requireStrictBearerToken, timingSafeTokenMatch, } from './api-security-middleware.js';
9
- export { isLoopbackHostname } from '@jini-ai/platform/net';
10
- export { isLoopbackPeerAddress, localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
6
+ export { registerApiBearerAuthMiddleware, registerApiOriginGuardMiddleware, requireStrictBearerToken, timingSafeTokenMatch, } from './api-security-middleware.js';
7
+ export { localOriginFromHeader, normalizeLocalAuthority, requireLocalDaemonRequest, validateLocalDaemonRequest, } from './local-daemon-request.js';
11
8
  export { createCompatApiError, createCompatApiErrorResponse, } from './compat.js';
12
9
  export * from './rate-limit.js';
13
10
  export * from './middleware.js';
14
- export * from './verified-origin.js';
15
11
  export * from './observability.js';
16
12
  // Generic request/response and origin primitives used by capability-owned route packs.
17
13
  export * from './request.js';
18
14
  export * from './response.js';
19
15
  export * from './origin.js';
16
+ export * from './trust-proxy.js';
20
17
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,42 @@
1
+ import { type ApiError } from '@jini-ai/protocol';
2
+ /** What every host `onInternalError` sink receives besides the route's own fields: never shown to the caller.
3
+ * This is the host channel: the full error, the request ID the caller copies and the operation
4
+ * label, so the host can store one full record (under its own redaction) that the ID finds. */
5
+ export interface RouteInternalErrorContext {
6
+ readonly correlationId: string;
7
+ readonly error: unknown;
8
+ /** The operation label the default line prints (`run-start`, `connectors/auth.list`). Optional so
9
+ * hosts and route packs that build a context themselves stay assignable. */
10
+ readonly logSource?: string;
11
+ }
12
+ /** A host sink for one route's incidents. Hosts apply their own redaction policy here. */
13
+ export type RouteInternalErrorSink<C extends RouteInternalErrorContext = RouteInternalErrorContext & {
14
+ readonly source: string;
15
+ }> = (context: C) => void;
16
+ /**
17
+ * The one incident path for an unexpected failure inside a Jini HTTP route (SEC-005): the host
18
+ * sink gets the real error, the route's own fields (`runId`, ...) and the operation label under a
19
+ * fresh request ID (or the default log gets its class/code only); the caller gets
20
+ * `message` (plain words: what failed + what to do) and the same ID, never the raw error.
21
+ * Every route pack's `onInternalError` seam goes through here, so the sink-failure and default-log
22
+ * behaviour is the same everywhere.
23
+ * @param required.report The route's own context fields (`source`, `runId`, `batchId`, ...) and `error`.
24
+ * @param required.logSource Label of the default log line, e.g. `run-start` or `connectors/auth.list`.
25
+ * @param required.message Caller-facing plain words. Never the raw error or a generic "internal error".
26
+ * @param optional.onInternalError Host sink. A throwing sink never replaces the answer.
27
+ * @returns The `INTERNAL_ERROR` ApiError carrying `requestId`.
28
+ * @complexity O(1) besides the sink.
29
+ */
30
+ export declare function reportRouteInternalError<E extends {
31
+ readonly error: unknown;
32
+ }>(required: {
33
+ readonly report: E;
34
+ readonly logSource: string;
35
+ readonly message: string;
36
+ }, { onInternalError }?: {
37
+ readonly onInternalError?: ((context: E & {
38
+ readonly correlationId: string;
39
+ readonly logSource: string;
40
+ }) => void) | undefined;
41
+ }): ApiError;
42
+ //# sourceMappingURL=internal-error.d.ts.map
@@ -0,0 +1,48 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { describeErrorForLog } from '@jini-ai/core';
3
+ import { createApiError } from '@jini-ai/protocol';
4
+ /**
5
+ * The one incident path for an unexpected failure inside a Jini HTTP route (SEC-005): the host
6
+ * sink gets the real error, the route's own fields (`runId`, ...) and the operation label under a
7
+ * fresh request ID (or the default log gets its class/code only); the caller gets
8
+ * `message` (plain words: what failed + what to do) and the same ID, never the raw error.
9
+ * Every route pack's `onInternalError` seam goes through here, so the sink-failure and default-log
10
+ * behaviour is the same everywhere.
11
+ * @param required.report The route's own context fields (`source`, `runId`, `batchId`, ...) and `error`.
12
+ * @param required.logSource Label of the default log line, e.g. `run-start` or `connectors/auth.list`.
13
+ * @param required.message Caller-facing plain words. Never the raw error or a generic "internal error".
14
+ * @param optional.onInternalError Host sink. A throwing sink never replaces the answer.
15
+ * @returns The `INTERNAL_ERROR` ApiError carrying `requestId`.
16
+ * @complexity O(1) besides the sink.
17
+ */
18
+ export function reportRouteInternalError(required, { onInternalError } = {}) {
19
+ // `logSource` has its own key, so a route field named `operation` or `source` is never overwritten.
20
+ const context = { ...required.report, correlationId: randomUUID(), logSource: required.logSource };
21
+ deliverRouteInternalError({ context, logSource: required.logSource }, { onInternalError });
22
+ return createApiError({ code: 'INTERNAL_ERROR', message: required.message }, { requestId: context.correlationId });
23
+ }
24
+ function deliverRouteInternalError({ context, logSource }, { onInternalError }) {
25
+ if (onInternalError === undefined) {
26
+ logRouteInternalError({ context, logSource });
27
+ return;
28
+ }
29
+ try {
30
+ onInternalError(context);
31
+ }
32
+ catch (sinkError) {
33
+ // The host sink failed: the default log still records the original incident, then the
34
+ // sink's own failure, so neither is lost and the route still answers.
35
+ logRouteInternalError({ context, logSource });
36
+ // eslint-disable-next-line no-console
37
+ console.error(`[@jini-ai/http-kit] internal error sink failed (${logSource}, correlationId=${context.correlationId})`, describeErrorForLog({ err: sinkError }));
38
+ }
39
+ }
40
+ function logRouteInternalError({ context, logSource }) {
41
+ // Default sink of a library route; hosts inject their own through `onInternalError`.
42
+ // Safe metadata only (class + constant code + request ID): a route's error can quote request
43
+ // input or a credential that no default redaction pattern recognises. The host sink gets the
44
+ // original error and decides what its own log may keep.
45
+ // eslint-disable-next-line no-console
46
+ console.error(`[@jini-ai/http-kit] internal error (${logSource}, correlationId=${context.correlationId})`, describeErrorForLog({ err: context.error }));
47
+ }
48
+ //# sourceMappingURL=internal-error.js.map
@@ -1,3 +1,14 @@
1
+ /**
2
+ * @module local-daemon-request
3
+ *
4
+ * A loopback-only request guard: validates that a request's peer address,
5
+ * `Host` header, and (if present) `Origin` header are all loopback, and sets
6
+ * the CORS headers a same-machine caller needs. Distinct from `./origin.js`'s
7
+ * `guardSameOrigin` (which checks a browser tab's origin against a configured
8
+ * allow-list) — this guard instead restricts an endpoint to same-machine
9
+ * callers only (e.g. a local companion process), regardless of origin
10
+ * allow-list configuration.
11
+ */
1
12
  import type { NextFunction, Request, Response } from 'express';
2
13
  interface LocalAuthority {
3
14
  hostname: string;
@@ -16,10 +27,6 @@ interface LocalDaemonValidationError {
16
27
  export declare function normalizeLocalAuthority({ value }: {
17
28
  readonly value: unknown;
18
29
  }, _optional?: Record<string, never>): LocalAuthority | null;
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 }: {
21
- readonly address: unknown;
22
- }, _optional?: Record<string, never>): boolean;
23
30
  /** Parses an `Origin` header value into its origin string, requiring a bare `scheme://loopback-host[:port]` with no path/query/userinfo. */
24
31
  export declare function localOriginFromHeader({ value }: {
25
32
  readonly value: unknown;
@@ -1,16 +1,4 @@
1
- /**
2
- * @module local-daemon-request
3
- *
4
- * A loopback-only request guard: validates that a request's peer address,
5
- * `Host` header, and (if present) `Origin` header are all loopback, and sets
6
- * the CORS headers a same-machine caller needs. Distinct from `./origin.js`'s
7
- * `guardSameOrigin` (which checks a browser tab's origin against a configured
8
- * allow-list) — this guard instead restricts an endpoint to same-machine
9
- * callers only (e.g. a local companion process), regardless of origin
10
- * allow-list configuration.
11
- */
12
- import net from 'node:net';
13
- import { isLoopbackHostname } from '@jini-ai/platform/net';
1
+ import { isLoopbackHostname, isLoopbackPeerAddress } from '@jini-ai/core/net';
14
2
  import { createCompatApiError } from './compat.js';
15
3
  import { sendApiError } from './response.js';
16
4
  /** Parses a `Host`-header-shaped authority string, rejecting anything with a path/userinfo/query/fragment. */
@@ -38,21 +26,6 @@ export function normalizeLocalAuthority({ value }, _optional = {}) {
38
26
  return null;
39
27
  }
40
28
  }
41
- /** True when `address` (typically `req.socket.remoteAddress`) is a loopback peer, unwrapping an IPv4-mapped IPv6 prefix first. */
42
- export function isLoopbackPeerAddress({ address }, _optional = {}) {
43
- if (typeof address !== 'string')
44
- return false;
45
- const normalized = address.trim().toLowerCase().replace(/^\[|\]$/g, '');
46
- if (!normalized)
47
- return false;
48
- if (normalized.startsWith('::ffff:'))
49
- return isLoopbackPeerAddress({ address: normalized.slice('::ffff:'.length) });
50
- if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1')
51
- return true;
52
- if (net.isIP(normalized) === 4)
53
- return normalized === '127.0.0.1' || normalized.startsWith('127.');
54
- return false;
55
- }
56
29
  function isBareHttpOrigin({ parsed }, _optional = {}) {
57
30
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
58
31
  return false;
@@ -17,4 +17,5 @@ export type BodySizeLimitOptional = Record<string, never>;
17
17
  * @returns Express middleware; oversized requests receive 413 without next().
18
18
  */
19
19
  export declare function rejectOversizedJsonBody({ maxBytes, errorResponseFactory }: BodySizeLimitRequired, _optional?: BodySizeLimitOptional): RequestHandler;
20
+ export { createDaemonAuthMiddleware, createRunOwnershipMiddleware, createOwnedRunListHandler, type RunAccessDecision, type DaemonAuthRequired, type RunOwnershipRequired, type OwnedRunListRequired, } from './run-credentials.js';
20
21
  //# sourceMappingURL=middleware.d.ts.map
@@ -18,4 +18,5 @@ export function rejectOversizedJsonBody({ maxBytes, errorResponseFactory }, _opt
18
18
  next();
19
19
  };
20
20
  }
21
+ export { createDaemonAuthMiddleware, createRunOwnershipMiddleware, createOwnedRunListHandler, } from './run-credentials.js';
21
22
  //# sourceMappingURL=middleware.js.map
@@ -0,0 +1,108 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type SecretRedactionPattern } from '@jini-ai/core';
3
+ import { type Server } from '@jini-ai/core/contracts/server';
4
+ /** Optional per-request hints from a host framework that already touched the request. */
5
+ export interface NodeDispatchOptions {
6
+ /** Hand unmatched requests (`next()`) and handler failures (`next(error)`) to the host. */
7
+ readonly next?: (error?: unknown) => void;
8
+ /** `scheme://host` for `Request.url`; a host behind a trusted proxy passes its own view. Defaults to `http://<Host header>`. */
9
+ readonly origin?: string;
10
+ /**
11
+ * The body an upstream parser already produced (Express: `req.body`). Used only when that
12
+ * parser has consumed the stream: a `Buffer`/`Uint8Array` is passed on byte for byte, a string
13
+ * as text, anything else as JSON. Without this, a converted route behind a blanket
14
+ * `express.json()` would see an empty body.
15
+ */
16
+ readonly parsedBody?: unknown;
17
+ /**
18
+ * Trusted per-request values the host's own code established before this request reached the
19
+ * dispatcher (Express: `res.locals`, where host authentication put the signed-in principal).
20
+ * Handlers and middleware get a fresh `locals` seeded with these. Only values the host itself
21
+ * set belong here, never anything rebuilt from request headers or body: the routes behind the
22
+ * dispatcher trust them as the host's verdict.
23
+ */
24
+ readonly locals?: Readonly<Record<string, unknown>>;
25
+ }
26
+ /** One unhandled failure, with the reference its 500 answer showed the caller. */
27
+ export interface UnhandledErrorReport {
28
+ readonly error: unknown;
29
+ /** Also in the plain-words 500 body (when one could still be sent), so a pasted reference finds this log line. */
30
+ readonly reference: string;
31
+ }
32
+ /** Optional settings for {@link createNodeDispatcher}. */
33
+ export interface NodeDispatcherOptions {
34
+ /**
35
+ * Where a handler failure goes when no `next` was given, and where a failure after the headers
36
+ * were sent always goes (default: redacted, to stderr). A sink that throws is contained: the
37
+ * dispatcher writes one fixed line to stderr instead and carries on.
38
+ */
39
+ readonly onUnhandledError?: (required: UnhandledErrorReport) => void;
40
+ /**
41
+ * Extra credential shapes the default stderr sink masks on top of the shared redactor's own.
42
+ * Jini stays vendor-neutral and knows no host's key formats, so the host injects them (a
43
+ * host passes its own API key shape). Ignored when `onUnhandledError` is given: that sink owns redaction.
44
+ */
45
+ readonly redactionPatterns?: readonly SecretRedactionPattern[];
46
+ /**
47
+ * For a host that replaces Express routes with route lists and must keep answering what Express
48
+ * answered. Paths match as Express 4 matches by default (fixed segments ignore letter case, one
49
+ * trailing slash is accepted); a `:name` segment that is not valid percent-encoding is a 400
50
+ * (handed to the host as an error with `status` 400 when `next` is given, so its own error page
51
+ * answers, otherwise a plain-words 400); and an OPTIONS request for a path some route owns is
52
+ * answered here, 200 with `Allow` and the methods as the body, as Express answered it. That last
53
+ * answer is for a host with no CORS layer above the dispatcher: a CORS layer answers a preflight
54
+ * itself and the request never gets here. Default `false`: exact paths, and OPTIONS goes to the host.
55
+ */
56
+ readonly expressCompatible?: boolean;
57
+ }
58
+ export interface NodeDispatcher {
59
+ /** Register routes here; they are served by `handle`. */
60
+ readonly server: Server;
61
+ /** Serves one request. Never rejects: every failure is answered or handed to `next(error)`. */
62
+ handle(requiredArgs: {
63
+ readonly incoming: IncomingMessage;
64
+ readonly out: ServerResponse;
65
+ }, optionalArgs?: NodeDispatchOptions): Promise<void>;
66
+ }
67
+ /**
68
+ * Largest size a body of `parserLimitBytes` can have after the bridge re-serializes it. See JSON_RESERIALIZE_MAX_EXPANSION.
69
+ * A host with a JSON parser in front of the dispatcher passes this as the route-side body limit:
70
+ * the parser has already applied the real limit to the bytes on the wire, and the route limit
71
+ * only has to be large enough never to refuse a body the parser accepted.
72
+ */
73
+ export declare function maxReserializedJsonBytes(required: {
74
+ parserLimitBytes: number;
75
+ }, _optional?: Record<string, never>): number;
76
+ /**
77
+ * The headers of a Node request as web `Headers`: the one view of a header every route handler is given.
78
+ * A host that reads headers outside the bridge (its own route calling code that takes a web request)
79
+ * builds them with this, so a header reads the same either way. Node has already joined a repeated
80
+ * header (`cookie` with `; `, most others with `, `); one it keeps as a list (`set-cookie`) becomes one entry per value.
81
+ * @param required.incoming - The request as Node read it; its headers are copied at the moment of the call.
82
+ * @complexity O(headers) time and space; no I/O.
83
+ */
84
+ export declare function nodeRequestHeaders({ incoming }: {
85
+ readonly incoming: Pick<IncomingMessage, 'headers'>;
86
+ }, _optional?: Record<string, never>): Headers;
87
+ /**
88
+ * Writes a web `Response` to a Node `ServerResponse`: status, headers (each `Set-Cookie` on its own line), then the
89
+ * body with backpressure, headers flushed before the first chunk so a stream reaches the client before its first event.
90
+ * For a host that builds its own `Response` and answers through Node (Express) instead of registering a route, so it
91
+ * gets the same writer the dispatcher uses. `headOnly` writes the head and drops the body (a `HEAD` answer). A client
92
+ * that leaves cancels the body's producer; a body that fails mid-way rejects, and the caller cuts the connection.
93
+ * @throws When the body stream itself fails.
94
+ */
95
+ export declare function sendWebResponse({ response, res }: {
96
+ response: Response;
97
+ res: ServerResponse;
98
+ }, { headOnly }?: {
99
+ headOnly?: boolean;
100
+ }): Promise<void>;
101
+ /**
102
+ * Creates a dispatcher with an empty route table.
103
+ * @param optional.onUnhandledError - Where a handler failure goes when no `next` was given, with the reference its 500 shows (default: redacted, to stderr).
104
+ * @param optional.redactionPatterns - Host key shapes the default stderr sink also masks.
105
+ * @param optional.expressCompatible - Keep Express's answers for path spellings, a bad percent-escape and OPTIONS (see {@link NodeDispatcherOptions}).
106
+ */
107
+ export declare function createNodeDispatcher(_required?: Record<string, never>, { onUnhandledError, redactionPatterns, expressCompatible }?: NodeDispatcherOptions): NodeDispatcher;
108
+ //# sourceMappingURL=node-bridge.d.ts.map