@jini-ai/http-kit 0.3.8 → 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 (58) 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 +9 -78
  12. package/dist/delegated-tools.js +27 -95
  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
@@ -13,7 +13,7 @@ const GUARDED_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'options', 'al
13
13
  * @complexity O(1) — a single `Set` lookup.
14
14
  * @overallScore 100/100
15
15
  */
16
- export function guardedRouteKey(method, path, guardedRouteKeys) {
16
+ export function guardedRouteKey({ method, path, guardedRouteKeys }, _optional = {}) {
17
17
  if (typeof path !== 'string')
18
18
  return null;
19
19
  const key = `${method.toUpperCase()} ${path}`;
@@ -34,7 +34,7 @@ export function guardedRouteKey(method, path, guardedRouteKeys) {
34
34
  * @complexity O(1) setup (patches 8 fixed methods); each wrapped call is O(1) beyond the wrapped original.
35
35
  * @overallScore 100/100
36
36
  */
37
- export function installRouteRegistrationGuard(app, options = {}) {
37
+ export function installRouteRegistrationGuard({ app }, options = {}) {
38
38
  const guardedRouteKeys = options.guardedRouteKeys ?? new Set();
39
39
  const seen = new Set();
40
40
  const inventory = [];
@@ -45,7 +45,7 @@ export function installRouteRegistrationGuard(app, options = {}) {
45
45
  if (typeof path === 'string') {
46
46
  inventory.push({ method: method.toUpperCase(), path });
47
47
  }
48
- const key = guardedRouteKey(method, path, guardedRouteKeys);
48
+ const key = guardedRouteKey({ method, path, guardedRouteKeys });
49
49
  if (key) {
50
50
  if (seen.has(key)) {
51
51
  throw new Error(`duplicate guarded route registration: ${key}`);
@@ -61,11 +61,11 @@ export function installRouteRegistrationGuard(app, options = {}) {
61
61
  *
62
62
  * @param app - An app the guard was installed on. Safe to call on an app with no guard installed
63
63
  * (returns an empty array rather than throwing).
64
- * @returns A fresh array copy each call — the caller can never mutate the guard's own internal inventory through the returned reference.
64
+ * @returns A fresh array with copied entries each call — the caller can never mutate the guard's own internal inventory through the returned reference.
65
65
  * @complexity O(n) in the number of routes registered so far.
66
66
  * @overallScore 100/100
67
67
  */
68
- export function getRouteRegistrationInventory(app) {
69
- return [...(app[routeInventorySymbol] ?? [])];
68
+ export function getRouteRegistrationInventory({ app }, _optional = {}) {
69
+ return (app[routeInventorySymbol] ?? []).map((entry) => ({ ...entry }));
70
70
  }
71
71
  //# sourceMappingURL=route-registration-guard.js.map
package/dist/sse.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * Before this file, the only SSE machinery in this package was inlined
5
5
  * directly inside `runs.ts`'s `registerRunEventStream` (a bounded-queue,
6
6
  * backpressure-aware `res.write`/`'drain'` state machine with Last-Event-ID
7
- * replay support) — see `source-map.md`'s 2026-07-19 "generic lifecycle SSE
7
+ * replay support) — see `archived provenance ledger`'s 2026-07-19 "generic lifecycle SSE
8
8
  * projection" note and the many "requires SSE (deferred)" verdicts against
9
9
  * `chat.ts`/`memory.ts`/`terminal.ts` in the routes-classification table.
10
10
  * `createSseChannel` below is that same state machine, generalized over any
@@ -41,11 +41,17 @@ export interface CreateSseChannelOptions<E extends SseEvent> {
41
41
  /** Queued-event ceiling before the connection is dropped. Defaults to {@link DEFAULT_MAX_QUEUED_SSE_EVENTS}. */
42
42
  readonly maxQueuedEvents?: number;
43
43
  /** When true for a given event, the channel ends the stream immediately after writing it (matches `runs.ts`'s `'end'`-kind auto-close). Omit for a channel that only ends on client disconnect/overflow/explicit `end()`. */
44
- readonly isEndEvent?: (event: E) => boolean;
44
+ readonly isEndEvent?: ({ event }: {
45
+ event: E;
46
+ }) => boolean;
45
47
  /** Overrides the wire format. Defaults to {@link defaultFormatEvent}. */
46
- readonly formatEvent?: (event: E) => string;
48
+ readonly formatEvent?: ({ event }: {
49
+ event: E;
50
+ }) => string;
47
51
  /** Invoked once, synchronously, if `res.write` throws mid-flush — lets a caller log the real error without it crossing back into whatever produced the event (mirrors `runs.ts`'s `RunHttpDeps.onInternalError` seam, but this primitive itself stays logging-free: silent by default, matching a transport channel's "never throw back through the producer" contract). */
48
- readonly onWriteError?: (error: unknown) => void;
52
+ readonly onWriteError?: ({ error }: {
53
+ error: unknown;
54
+ }) => void;
49
55
  }
50
56
  export interface SseChannel<E extends SseEvent> {
51
57
  /**
@@ -55,7 +61,9 @@ export interface SseChannel<E extends SseEvent> {
55
61
  * replay history before opening the stream — the client's very first
56
62
  * flush then already contains that backlog.
57
63
  */
58
- readonly enqueue: (event: E) => void;
64
+ readonly enqueue: ({ event }: {
65
+ readonly event: E;
66
+ }, _optional?: Record<string, never>) => void;
59
67
  /**
60
68
  * Writes SSE headers (`200`, `text/event-stream`, `Cache-Control: no-cache,
61
69
  * no-transform`, `Connection: keep-alive`) and starts draining the queue.
@@ -93,7 +101,9 @@ export interface SseChannel<E extends SseEvent> {
93
101
  * overflow/write failure). Safe to call after the channel is already
94
102
  * closed — the callback then runs immediately, synchronously.
95
103
  */
96
- readonly onClose: (callback: () => void) => void;
104
+ readonly onClose: ({ callback }: {
105
+ readonly callback: () => void;
106
+ }, _optional?: Record<string, never>) => void;
97
107
  }
98
108
  /**
99
109
  * Builds a bounded, backpressure-aware SSE channel over an Express `Response`.
@@ -122,7 +132,9 @@ export interface SseChannel<E extends SseEvent> {
122
132
  * @complexity `enqueue`/`open`/`end` are O(1) amortized; a full queue drain is O(events written).
123
133
  * @overallScore 100/100
124
134
  */
125
- export declare function createSseChannel<E extends SseEvent>(res: ServerResponse, options?: CreateSseChannelOptions<E>): SseChannel<E>;
135
+ export declare function createSseChannel<E extends SseEvent>({ res }: {
136
+ readonly res: ServerResponse;
137
+ }, options?: CreateSseChannelOptions<E>): SseChannel<E>;
126
138
  /** Reads a reconnect cursor from the standard `Last-Event-ID` header, falling back to an `afterCursor` query parameter. Shared by any SSE route that supports reconnect replay (the header takes precedence since it is what browsers set automatically on `EventSource` reconnect). */
127
139
  export declare function requestedAfterCursor(req: {
128
140
  get(name: string): string | undefined;
@@ -132,8 +144,12 @@ export declare function requestedAfterCursor(req: {
132
144
  * Writes an `ApiError`, wrapped in the standard `{ error }` envelope, directly onto a raw
133
145
  * `ServerResponse` — for the narrow window before an `SseChannel` has opened (so Express's own
134
146
  * `res.json()` response wrapper isn't safe to use yet). Produces the identical
135
- * `createApiErrorResponse(error)` envelope shape `response.ts`'s `sendApiError`/`sendJson` do —
147
+ * `createApiErrorResponse({ error: error })` envelope shape `response.ts`'s `sendApiError`/`sendJson` do —
136
148
  * this just writes that same shape without going through Express's response helper.
137
149
  */
138
- export declare function sendRawApiError(res: ServerResponse, status: number, error: ApiError): void;
150
+ export declare function sendRawApiError({ res, status, error }: {
151
+ readonly res: ServerResponse;
152
+ readonly status: number;
153
+ readonly error: ApiError;
154
+ }, _optional?: Record<string, never>): void;
139
155
  //# sourceMappingURL=sse.d.ts.map
package/dist/sse.js CHANGED
@@ -40,9 +40,9 @@ function defaultFormatEvent(event) {
40
40
  * @complexity `enqueue`/`open`/`end` are O(1) amortized; a full queue drain is O(events written).
41
41
  * @overallScore 100/100
42
42
  */
43
- export function createSseChannel(res, options = {}) {
43
+ export function createSseChannel({ res }, options = {}) {
44
44
  const maxQueuedEvents = options.maxQueuedEvents ?? DEFAULT_MAX_QUEUED_SSE_EVENTS;
45
- const formatEvent = options.formatEvent ?? defaultFormatEvent;
45
+ const formatEvent = options.formatEvent ?? (({ event }) => defaultFormatEvent(event));
46
46
  const queue = [];
47
47
  let flowing = false;
48
48
  let writable = true;
@@ -70,24 +70,24 @@ export function createSseChannel(res, options = {}) {
70
70
  const event = queue.shift();
71
71
  let wroteOk;
72
72
  try {
73
- wroteOk = res.write(formatEvent(event));
73
+ wroteOk = res.write(formatEvent({ event }));
74
74
  }
75
75
  catch (error) {
76
76
  // A dead/broken transport must never throw back through whatever is producing events —
77
77
  // stop this channel only.
78
- options.onWriteError?.(error);
78
+ options.onWriteError?.({ error });
79
79
  end();
80
80
  return;
81
81
  }
82
82
  if (wroteOk === false)
83
83
  writable = false;
84
- if (options.isEndEvent?.(event)) {
84
+ if (options.isEndEvent?.({ event })) {
85
85
  end();
86
86
  return;
87
87
  }
88
88
  }
89
89
  };
90
- const enqueue = (event) => {
90
+ const enqueue = ({ event }) => {
91
91
  if (closed)
92
92
  return;
93
93
  if (queue.length >= maxQueuedEvents) {
@@ -118,7 +118,7 @@ export function createSseChannel(res, options = {}) {
118
118
  // still wants to send a *non-SSE* response — e.g. a JSON error — after discovering a subscribe
119
119
  // failed needs `isClosed()` to be observable without the response having been touched yet).
120
120
  res.on('close', markClosed);
121
- const onClose = (callback) => {
121
+ const onClose = ({ callback }) => {
122
122
  if (closed) {
123
123
  callback();
124
124
  return;
@@ -146,12 +146,12 @@ export function requestedAfterCursor(req) {
146
146
  * Writes an `ApiError`, wrapped in the standard `{ error }` envelope, directly onto a raw
147
147
  * `ServerResponse` — for the narrow window before an `SseChannel` has opened (so Express's own
148
148
  * `res.json()` response wrapper isn't safe to use yet). Produces the identical
149
- * `createApiErrorResponse(error)` envelope shape `response.ts`'s `sendApiError`/`sendJson` do —
149
+ * `createApiErrorResponse({ error: error })` envelope shape `response.ts`'s `sendApiError`/`sendJson` do —
150
150
  * this just writes that same shape without going through Express's response helper.
151
151
  */
152
- export function sendRawApiError(res, status, error) {
152
+ export function sendRawApiError({ res, status, error }, _optional = {}) {
153
153
  res.statusCode = status;
154
154
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
155
- res.end(JSON.stringify(createApiErrorResponse(error)));
155
+ res.end(JSON.stringify(createApiErrorResponse({ error: error })));
156
156
  }
157
157
  //# sourceMappingURL=sse.js.map
@@ -7,8 +7,8 @@
7
7
  * narrowing. `@jini-ai/mcp`'s `search_tools`/`describe_tool` tool defs proxy these two routes,
8
8
  * exactly mirroring how `run-tools.ts`'s tools proxy `runs.ts`.
9
9
  *
10
- * This module does not depend on `@jini-ai/sqlite` or `better-sqlite3` — `ToolCatalogQuery` is a
11
- * plain injected interface, structurally compatible with `@jini-ai/sqlite`'s
10
+ * This module does not depend on `@jini-ai/sqlite-chat` or `better-sqlite3` — `ToolCatalogQuery` is a
11
+ * plain injected interface, structurally compatible with `@jini-ai/sqlite-chat`'s
12
12
  * `searchToolCatalog`/`getToolCatalogEntry` so a caller wires those in with zero adapter code,
13
13
  * matching `db-ops.ts`'s established convention.
14
14
  *
@@ -32,7 +32,7 @@ export interface ToolCatalogEntry {
32
32
  readonly inputSchema?: unknown;
33
33
  readonly source: string;
34
34
  }
35
- /** Structurally identical to `@jini-ai/sqlite`'s `searchToolCatalog`/`getToolCatalogEntry` — defined locally so this package incurs no `better-sqlite3` dependency. */
35
+ /** Structurally identical to `@jini-ai/sqlite-chat`'s `searchToolCatalog`/`getToolCatalogEntry` — defined locally so this package incurs no `better-sqlite3` dependency. */
36
36
  export interface ToolCatalogQuery {
37
37
  readonly search: (query: string, limit?: number) => readonly ToolCatalogSearchHit[];
38
38
  readonly describe: (id: string) => ToolCatalogEntry | null;
package/dist/types.d.ts CHANGED
@@ -3,23 +3,22 @@
3
3
  * (`JsonRouteSpec`, `InputParser`, `Handler`, `HttpMethod`, `RouteInputContext`) every other
4
4
  * module in this package depends on.
5
5
  */
6
+ import type { Result as CoreResult } from '@jini-ai/core/primitives';
6
7
  import type { ApiError } from '@jini-ai/protocol';
7
8
  /**
8
9
  * A discriminated success/failure envelope used throughout the module in place of throwing.
9
10
  * Route parsing, handling, and origin checks all resolve to a `Result` so the Adapter can fold
10
11
  * every failure mode into one error-handling pipeline.
11
12
  */
12
- export type Result<T, E = ApiError> = {
13
- ok: true;
14
- value: T;
15
- } | {
16
- ok: false;
17
- error: E;
18
- };
13
+ export type Result<T, E = ApiError> = CoreResult<T, E>;
19
14
  /** Builds a successful `Result` carrying `value`. */
20
- export declare const ok: <T, E = ApiError>(value: T) => Result<T, E>;
15
+ export declare const ok: <T, E = ApiError>({ value }: {
16
+ readonly value: T;
17
+ }, _optional?: Record<string, never>) => Result<T, E>;
21
18
  /** Builds a failed `Result` carrying `error`. */
22
- export declare const err: <T = never, E = ApiError>(error: E) => Result<T, E>;
19
+ export declare const err: <T = never, E = ApiError>({ error }: {
20
+ readonly error: E;
21
+ }, _optional?: Record<string, never>) => Result<T, E>;
23
22
  /**
24
23
  * The normalized shape of a raw HTTP request handed to a route's `parse` function: body, query,
25
24
  * and params, decoupled from any framework `Request` type so parsers are unit-testable without
@@ -36,11 +35,14 @@ export type InputParser<Input> = (raw: RouteInputContext) => Result<Input>;
36
35
  * Handles a parsed `Input` (plus injected `Deps`) and produces a `Result<Output>`.
37
36
  *
38
37
  * `signal` is optional and additive: it aborts if the underlying HTTP request's connection drops
39
- * before the Adapter has written a response (see `mountJsonRoute` in `adapter.ts`) — a route with
40
- * no long-running or delegated work has no reason to read it, and every existing 2-arg handler
41
- * stays a valid `Handler` unchanged (TS accepts a callback that ignores trailing parameters).
38
+ * before the Adapter has written a response (see `mountJsonRoute` in `adapter.ts`) — handlers read it from their optional arguments when they perform cancellable work.
42
39
  */
43
- export type Handler<Input, Output, Deps> = (input: Input, deps: Deps, signal?: AbortSignal) => Promise<Result<Output>> | Result<Output>;
40
+ export type Handler<Input, Output, Deps> = (requiredArgs: {
41
+ readonly input: Input;
42
+ readonly deps: Deps;
43
+ }, optionalArgs?: {
44
+ readonly signal?: AbortSignal | undefined;
45
+ }) => Promise<Result<Output>> | Result<Output>;
44
46
  /** HTTP verbs the Adapter can mount a `JsonRouteSpec` under. */
45
47
  export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch';
46
48
  /**
package/dist/types.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /** Builds a successful `Result` carrying `value`. */
2
- export const ok = (value) => ({ ok: true, value });
2
+ export const ok = ({ value }, _optional = {}) => ({ ok: true, value });
3
3
  /** Builds a failed `Result` carrying `error`. */
4
- export const err = (error) => ({ ok: false, error });
4
+ export const err = ({ error }, _optional = {}) => ({ ok: false, error });
5
5
  //# sourceMappingURL=types.js.map
@@ -0,0 +1,37 @@
1
+ import { type VerifiedOrigin } from "./types.js";
2
+ /** Operator declaration is evidence of configured trust, not DNS or ownership proof. */
3
+ export interface ConfiguredOriginRequired {
4
+ env: Readonly<Record<string, string | undefined>>;
5
+ envVarName: string;
6
+ clock: {
7
+ nowIso(): string;
8
+ };
9
+ warn: (message: string) => void;
10
+ }
11
+ /** Accept a caller-named operator declaration or return undefined with a refusal warning.
12
+ * No ambient environment lookup. The injected clock stamps accepted evidence only.
13
+ * @complexity O(configured URL length) time/space; no network or storage effects.
14
+ * @example resolveConfiguredOrigin({ env, envVarName: "APP_PUBLIC_URL", clock, warn });
15
+ */
16
+ export declare function resolveConfiguredOrigin(required: ConfiguredOriginRequired): VerifiedOrigin | undefined;
17
+ export type OriginBootPlan = {
18
+ kind: "configured";
19
+ origin: VerifiedOrigin;
20
+ } | {
21
+ kind: "dev-seed";
22
+ } | {
23
+ kind: "none";
24
+ };
25
+ export interface OriginBootRequired extends ConfiguredOriginRequired {
26
+ /** The host decides whether this runtime may seed a development capability. */
27
+ allowDevSeed: () => boolean;
28
+ missingOriginWarning: string;
29
+ }
30
+ /** Pure boot decision; registration effects and runtime selection stay in the host. */
31
+ /** Choose configured evidence, an allowed development seed, or no registration.
32
+ * Warnings use caller-supplied policy; registration effects remain host-owned.
33
+ * @complexity O(configured URL length) time/space.
34
+ * @example planOriginBoot({ env, envVarName, clock, warn, allowDevSeed, missingOriginWarning });
35
+ */
36
+ export declare function planOriginBoot(required: OriginBootRequired): OriginBootPlan;
37
+ //# sourceMappingURL=configured-origin.d.ts.map
@@ -0,0 +1,112 @@
1
+ import { hasForbiddenRawUrlCharacter } from "./origin.js";
2
+ import { createVerifiedOrigin } from "./types.js";
3
+ /**
4
+ * Loopback (including *.localhost and 127.0.0.0/8) cannot represent a public deployment. Rejecting
5
+ * it also prevents a shared public-URL setting from overriding development TLS-derived schemes
6
+ * with a workspace-setting HTTPS origin on a server that only answers HTTP.
7
+ * Private network ranges remain valid: intranet deployments can legitimately use private hosts.
8
+ */
9
+ const LOOPBACK_HOSTS = new Set(["localhost", "0.0.0.0", "::1", "[::1]", "::", "[::]"]);
10
+ const LOOPBACK_IPV4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
11
+ function isLoopbackHost(host) {
12
+ if (LOOPBACK_HOSTS.has(host))
13
+ return true;
14
+ if (host.endsWith(".localhost"))
15
+ return true;
16
+ return LOOPBACK_IPV4.test(host);
17
+ }
18
+ // Match candidate-origin normalization so a trailing DNS dot has one meaning across decisions.
19
+ function normalizeHost(hostname) {
20
+ const lowered = hostname.toLowerCase();
21
+ return lowered.endsWith(".") ? lowered.slice(0, -1) : lowered;
22
+ }
23
+ // Reject ambiguous raw characters before parsing can erase them; use the redirect predicate
24
+ // rather than introducing a second URL acceptance rule.
25
+ function parseConfiguredUrl(raw) {
26
+ if (hasForbiddenRawUrlCharacter({ raw }))
27
+ return null;
28
+ try {
29
+ return new URL(raw);
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ // Workspace-setting evidence permits HTTPS only. Refuse HTTP before constructing evidence so
36
+ // an invalid operator setting cannot make origin construction throw during boot.
37
+ function refusalReason(url) {
38
+ if (url.protocol !== "https:")
39
+ return "its scheme must be https";
40
+ if (url.username !== "" || url.password !== "")
41
+ return "it carries a userinfo component";
42
+ if (url.search !== "" || url.hash !== "")
43
+ return "it carries a query string or fragment";
44
+ const host = normalizeHost(url.hostname);
45
+ if (host === "")
46
+ return "its host is empty";
47
+ if (isLoopbackHost(host))
48
+ return `'${host}' is a loopback host, not a public origin`;
49
+ return null;
50
+ }
51
+ // Omit absent port/basePath keys entirely: explicit undefined differs from an omitted optional
52
+ // property under strict equality, and storage adapters preserve that distinction.
53
+ function buildConfiguredOrigin(url, now) {
54
+ const candidate = {
55
+ scheme: "https",
56
+ host: normalizeHost(url.hostname),
57
+ verifiedAt: now,
58
+ source: "workspace-setting",
59
+ };
60
+ if (url.port !== "")
61
+ candidate.port = Number(url.port);
62
+ const basePath = url.pathname.replace(/\/+$/, "");
63
+ if (basePath !== "")
64
+ candidate.basePath = basePath;
65
+ return createVerifiedOrigin(candidate);
66
+ }
67
+ // Environment authority already controls deployed code; accepting an operator declaration adds
68
+ // no request-derived authority. Never feed a request-host fallback into this durable trust root.
69
+ // Malformed values leave no evidence, with one diagnostic warning; unset/blank local settings stay
70
+ // quiet. Use the host's boot clock so this evidence and other boot rows carry the same timestamp.
71
+ /** Accept a caller-named operator declaration or return undefined with a refusal warning.
72
+ * No ambient environment lookup. The injected clock stamps accepted evidence only.
73
+ * @complexity O(configured URL length) time/space; no network or storage effects.
74
+ * @example resolveConfiguredOrigin({ env, envVarName: "APP_PUBLIC_URL", clock, warn });
75
+ */
76
+ export function resolveConfiguredOrigin(required) {
77
+ const { env, envVarName, clock, warn } = required;
78
+ const raw = env[envVarName]?.trim();
79
+ if (!raw)
80
+ return undefined;
81
+ const refuse = (reason) => {
82
+ warn(`${envVarName} is set but was refused as this deployment's public origin (${reason}); ` +
83
+ `no origin was registered from it. Value: ${raw}`);
84
+ return undefined;
85
+ };
86
+ const url = parseConfiguredUrl(raw);
87
+ if (!url)
88
+ return refuse("it is not a parseable URL");
89
+ const reason = refusalReason(url);
90
+ if (reason)
91
+ return refuse(reason);
92
+ return buildConfiguredOrigin(url, clock.nowIso());
93
+ }
94
+ // A disallowed development seed must produce no registration: persisting localhost in a public
95
+ // deployment poisons generated links, and find-or-create storage can preserve the row forever.
96
+ // Avoiding new seeds does not repair old rows; registering accepted configured evidence does.
97
+ /** Pure boot decision; registration effects and runtime selection stay in the host. */
98
+ /** Choose configured evidence, an allowed development seed, or no registration.
99
+ * Warnings use caller-supplied policy; registration effects remain host-owned.
100
+ * @complexity O(configured URL length) time/space.
101
+ * @example planOriginBoot({ env, envVarName, clock, warn, allowDevSeed, missingOriginWarning });
102
+ */
103
+ export function planOriginBoot(required) {
104
+ const origin = resolveConfiguredOrigin(required);
105
+ if (origin)
106
+ return { kind: "configured", origin };
107
+ if (required.allowDevSeed())
108
+ return { kind: "dev-seed" };
109
+ required.warn(required.missingOriginWarning);
110
+ return { kind: "none" };
111
+ }
112
+ //# sourceMappingURL=configured-origin.js.map
@@ -0,0 +1,6 @@
1
+ export { type OriginScheme, type OriginSource, type VerifiedOrigin, InsecureOriginSourceError, OriginNotVerifiedError, createVerifiedOrigin, } from "./types.js";
2
+ export type { VerifiedOriginRequestContext, RedirectTargetContext, EgressTargetContext, OriginRegistryPort, OriginSettingRepoPort, } from "./ports.js";
3
+ export { OriginRegistry, hasForbiddenRawUrlCharacter, isSameOrigin, normalizeOriginCandidate, type NormalizedTarget, type OriginRegistryDeps, } from "./origin.js";
4
+ export { InMemoryOriginSettingRepo, type OriginSettingSeed } from "./repo.memory.js";
5
+ export { planOriginBoot, resolveConfiguredOrigin, type ConfiguredOriginRequired, type OriginBootRequired, type OriginBootPlan, } from "./configured-origin.js";
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ export { InsecureOriginSourceError, OriginNotVerifiedError, createVerifiedOrigin, } from "./types.js";
2
+ export { OriginRegistry, hasForbiddenRawUrlCharacter, isSameOrigin, normalizeOriginCandidate, } from "./origin.js";
3
+ export { InMemoryOriginSettingRepo } from "./repo.memory.js";
4
+ export { planOriginBoot, resolveConfiguredOrigin, } from "./configured-origin.js";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,65 @@
1
+ import type { VerifiedOriginRequestContext, OriginRegistryPort, OriginSettingRepoPort, RedirectTargetContext, EgressTargetContext } from "./ports.js";
2
+ import { OriginNotVerifiedError, type VerifiedOrigin } from "./types.js";
3
+ export { OriginNotVerifiedError };
4
+ export interface NormalizedTarget {
5
+ scheme: "https" | "http";
6
+ host: string;
7
+ port: number;
8
+ }
9
+ /** Reject parser-ambiguous backslashes, whitespace and controls before URL normalization.
10
+ * @complexity O(raw.length) time, O(1) space; pure.
11
+ * @example hasForbiddenRawUrlCharacter({ raw: "/a b" }); // true
12
+ */
13
+ export declare function hasForbiddenRawUrlCharacter({ raw }: {
14
+ raw: string;
15
+ }): boolean;
16
+ /** Normalize absolute HTTP(S) candidates, refusing ambiguous input and userinfo with null.
17
+ * HTTP normalization enables development same-origin checks; cross-origin decisions require HTTPS.
18
+ * @complexity O(rawUrl.length) time; parser-bound space. Pure; parse errors return null.
19
+ * @example normalizeOriginCandidate({ rawUrl: "https://Example.com./path" });
20
+ */
21
+ export declare function normalizeOriginCandidate({ rawUrl }: {
22
+ rawUrl: string;
23
+ }): NormalizedTarget | null;
24
+ /** Compare scheme, normalized host and effective port against trusted evidence.
25
+ * The target must already be normalized by normalizeOriginCandidate; basePath is not an origin boundary.
26
+ * @complexity O(canonical.host.length) time and space; pure.
27
+ * @example isSameOrigin({ target, canonical });
28
+ */
29
+ export declare function isSameOrigin({ target, canonical }: {
30
+ target: NormalizedTarget;
31
+ canonical: VerifiedOrigin;
32
+ }): boolean;
33
+ export interface OriginRegistryDeps {
34
+ repo: OriginSettingRepoPort;
35
+ }
36
+ /** Canonical-origin and independent redirect/egress decisions over caller-owned storage.
37
+ * @example new OriginRegistry({ repo });
38
+ */
39
+ export declare class OriginRegistry implements OriginRegistryPort {
40
+ private readonly repo;
41
+ constructor(deps: OriginRegistryDeps);
42
+ /** Resolve stored evidence or throw OriginNotVerifiedError; never derive trust from request headers.
43
+ * One repository lookup; O(1) additional time/space excluding the adapter.
44
+ */
45
+ canonicalOrigin(ctx: VerifiedOriginRequestContext): Promise<VerifiedOrigin>;
46
+ /** Allow the canonical origin or an exact redirect-allowlist HTTPS host; errors return false.
47
+ * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
48
+ */
49
+ isAllowedRedirectTarget({ context: ctx, url }: {
50
+ context: RedirectTargetContext;
51
+ url: string;
52
+ }): Promise<boolean>;
53
+ /** Apply the same fail-closed rule using the separate egress destination allowlist.
54
+ * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
55
+ */
56
+ isAllowedEgressTarget({ context: ctx, url }: {
57
+ context: EgressTargetContext;
58
+ url: string;
59
+ }): Promise<boolean>;
60
+ /** Normalize before looking up trust, then check same origin before the HTTPS-only host allowlist.
61
+ * Storage/parse errors return false; O(URL length + allowlist host bytes) time/space.
62
+ */
63
+ private isAllowedTarget;
64
+ }
65
+ //# sourceMappingURL=origin.d.ts.map
@@ -0,0 +1,151 @@
1
+ import { OriginNotVerifiedError, createVerifiedOrigin } from "./types.js";
2
+ export { OriginNotVerifiedError };
3
+ /**
4
+ * Check the original string before the WHATWG parser strips whitespace/controls or converts a
5
+ * backslash to a slash. A stored backslash plus a request tail can become a browser-followed
6
+ * cross-host Location even when a parsed-path check sees only slashes. Storage validation and
7
+ * redirect reads must use this same raw predicate; checking a reserialized url.href checks too late.
8
+ */
9
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: control chars are the POINT — F3 requires rejecting C0/DEL and backslash in a raw candidate URL before the WHATWG parser silently strips them. See this constant's own doc comment. See docs/decisions/DR-001-redirect-normalization.md.
10
+ const FORBIDDEN_RAW_CHARS = /[\\\s\x00-\x1F\x7F]/;
11
+ /** Reject parser-ambiguous backslashes, whitespace and controls before URL normalization.
12
+ * @complexity O(raw.length) time, O(1) space; pure.
13
+ * @example hasForbiddenRawUrlCharacter({ raw: "/a b" }); // true
14
+ */
15
+ export function hasForbiddenRawUrlCharacter({ raw }) {
16
+ return FORBIDDEN_RAW_CHARS.test(raw);
17
+ }
18
+ function parseCandidateUrl(rawUrl) {
19
+ if (typeof rawUrl !== "string" || rawUrl.length === 0)
20
+ return null;
21
+ if (hasForbiddenRawUrlCharacter({ raw: rawUrl }))
22
+ return null;
23
+ try {
24
+ return new URL(rawUrl);
25
+ }
26
+ catch {
27
+ return null;
28
+ }
29
+ }
30
+ function schemeOf(parsed) {
31
+ if (parsed.protocol === "https:")
32
+ return "https";
33
+ if (parsed.protocol === "http:")
34
+ return "http";
35
+ return null;
36
+ }
37
+ function defaultPortFor(scheme) {
38
+ return scheme === "https" ? 443 : 80;
39
+ }
40
+ // Explicit ports and scheme defaults (443 for HTTPS, 80 for HTTP) must compare identically.
41
+ function resolvePort(parsed, scheme) {
42
+ const port = parsed.port ? Number(parsed.port) : defaultPortFor(scheme);
43
+ if (!Number.isInteger(port) || port <= 0)
44
+ return null;
45
+ return port;
46
+ }
47
+ // WHATWG parsing performs IDNA/case normalization; the remaining single trailing DNS dot must
48
+ // be removed consistently from candidates, trusted origins and allowlists.
49
+ /** Normalize absolute HTTP(S) candidates, refusing ambiguous input and userinfo with null.
50
+ * HTTP normalization enables development same-origin checks; cross-origin decisions require HTTPS.
51
+ * @complexity O(rawUrl.length) time; parser-bound space. Pure; parse errors return null.
52
+ * @example normalizeOriginCandidate({ rawUrl: "https://Example.com./path" });
53
+ */
54
+ export function normalizeOriginCandidate({ rawUrl }) {
55
+ const parsed = parseCandidateUrl(rawUrl);
56
+ if (!parsed)
57
+ return null;
58
+ const scheme = schemeOf(parsed);
59
+ if (!scheme)
60
+ return null;
61
+ if (parsed.username !== "" || parsed.password !== "")
62
+ return null;
63
+ const host = stripTrailingDot(parsed.hostname.toLowerCase());
64
+ if (!host)
65
+ return null;
66
+ const port = resolvePort(parsed, scheme);
67
+ if (port === null)
68
+ return null;
69
+ return { scheme, host, port };
70
+ }
71
+ function stripTrailingDot(host) {
72
+ return host.endsWith(".") ? host.slice(0, -1) : host;
73
+ }
74
+ function effectivePort(origin) {
75
+ return origin.port ?? (origin.scheme === "https" ? 443 : 80);
76
+ }
77
+ // URL.origin strings preserve a trailing dot: https://site. and https://site reach the same
78
+ // server even though browsers keep their cookie/script origins separate. This destination rule
79
+ // compares normalized hosts so redirect validation and reserved-destination checks cannot disagree.
80
+ /** Compare scheme, normalized host and effective port against trusted evidence.
81
+ * The target must already be normalized by normalizeOriginCandidate; basePath is not an origin boundary.
82
+ * @complexity O(canonical.host.length) time and space; pure.
83
+ * @example isSameOrigin({ target, canonical });
84
+ */
85
+ export function isSameOrigin({ target, canonical }) {
86
+ if (canonical.scheme !== target.scheme)
87
+ return false;
88
+ if (stripTrailingDot(canonical.host.toLowerCase()) !== target.host)
89
+ return false;
90
+ return effectivePort(canonical) === target.port;
91
+ }
92
+ /** Canonical-origin and independent redirect/egress decisions over caller-owned storage.
93
+ * @example new OriginRegistry({ repo });
94
+ */
95
+ export class OriginRegistry {
96
+ repo;
97
+ constructor(deps) {
98
+ this.repo = deps.repo;
99
+ }
100
+ // This repository selects one origin per workspace; optional site/locale/origin keys do not
101
+ // currently select a different origin. Missing evidence must not trigger request-host guessing.
102
+ /** Resolve stored evidence or throw OriginNotVerifiedError; never derive trust from request headers.
103
+ * One repository lookup; O(1) additional time/space excluding the adapter.
104
+ */
105
+ async canonicalOrigin(ctx) {
106
+ const origin = await this.repo.findByWorkspaceId({ workspaceId: ctx.workspaceId });
107
+ if (!origin) {
108
+ throw new OriginNotVerifiedError({ message: `no verified origin registered for workspace '${ctx.workspaceId}'` });
109
+ }
110
+ return createVerifiedOrigin(origin);
111
+ }
112
+ /** Allow the canonical origin or an exact redirect-allowlist HTTPS host; errors return false.
113
+ * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
114
+ */
115
+ async isAllowedRedirectTarget({ context: ctx, url }) {
116
+ return this.isAllowedTarget(ctx, url, (workspaceId) => this.repo.findRedirectAllowlist({ workspaceId }));
117
+ }
118
+ /** Apply the same fail-closed rule using the separate egress destination allowlist.
119
+ * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
120
+ */
121
+ async isAllowedEgressTarget({ context: ctx, url }) {
122
+ return this.isAllowedTarget(ctx, url, (workspaceId) => this.repo.findEgressAllowlist({ workspaceId }));
123
+ }
124
+ /** Normalize before looking up trust, then check same origin before the HTTPS-only host allowlist.
125
+ * Storage/parse errors return false; O(URL length + allowlist host bytes) time/space.
126
+ */
127
+ async isAllowedTarget(ctx, rawUrl, loadAllowlist) {
128
+ try {
129
+ const target = normalizeOriginCandidate({ rawUrl });
130
+ if (!target)
131
+ return false;
132
+ const canonical = await this.canonicalOrigin({ workspaceId: ctx.workspaceId, ...(ctx.siteId === undefined ? {} : { siteId: ctx.siteId }) });
133
+ if (isSameOrigin({ target, canonical }))
134
+ return true;
135
+ // Cross-origin allowlist path is https-only, unconditionally — the. See docs/decisions/DR-001-redirect-normalization.md.
136
+ // dev-capability http exception above applies ONLY to the same-origin comparison, never
137
+ // to a cross-origin allowlisted target. See docs/decisions/DR-001-redirect-normalization.md.
138
+ if (target.scheme !== "https")
139
+ return false;
140
+ const allowlist = await loadAllowlist(ctx.workspaceId);
141
+ const allowSet = new Set(allowlist.map((host) => stripTrailingDot(host.trim().toLowerCase())));
142
+ return allowSet.has(target.host);
143
+ }
144
+ catch {
145
+ // Fail closed: an unverified origin, a repo error, or any unexpected
146
+ // exception must never be treated as "allowed".
147
+ return false;
148
+ }
149
+ }
150
+ }
151
+ //# sourceMappingURL=origin.js.map