@jini-ai/http-kit 0.3.8 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +177 -0
  2. package/README.md +71 -98
  3. package/dist/adapter.d.ts +21 -6
  4. package/dist/adapter.js +47 -17
  5. package/dist/api-security-middleware.d.ts +27 -17
  6. package/dist/api-security-middleware.js +27 -36
  7. package/dist/compat.d.ts +12 -17
  8. package/dist/compat.js +4 -12
  9. package/dist/db-ops.d.ts +3 -3
  10. package/dist/db-ops.js +3 -3
  11. package/dist/delegated-tools.d.ts +9 -78
  12. package/dist/delegated-tools.js +27 -95
  13. package/dist/index.d.ts +21 -70
  14. package/dist/index.js +12 -32
  15. package/dist/local-daemon-request.d.ts +18 -8
  16. package/dist/local-daemon-request.js +23 -32
  17. package/dist/memory.d.ts +1 -1
  18. package/dist/middleware.d.ts +20 -0
  19. package/dist/middleware.js +21 -0
  20. package/dist/observability.d.ts +29 -0
  21. package/dist/observability.js +22 -0
  22. package/dist/origin.d.ts +8 -6
  23. package/dist/origin.js +8 -5
  24. package/dist/pack-http.d.ts +12 -8
  25. package/dist/pack-http.js +3 -3
  26. package/dist/rate-limit.d.ts +97 -0
  27. package/dist/rate-limit.js +94 -0
  28. package/dist/raw-sse.d.ts +7 -2
  29. package/dist/raw-sse.js +6 -7
  30. package/dist/read-only-tools.d.ts +67 -0
  31. package/dist/read-only-tools.js +59 -0
  32. package/dist/remote-run-events.js +1 -1
  33. package/dist/request.d.ts +8 -2
  34. package/dist/request.js +4 -4
  35. package/dist/response.d.ts +16 -4
  36. package/dist/response.js +7 -5
  37. package/dist/route-registration-guard.d.ts +13 -5
  38. package/dist/route-registration-guard.js +6 -6
  39. package/dist/sse.d.ts +25 -9
  40. package/dist/sse.js +10 -10
  41. package/dist/tool-catalog.d.ts +3 -3
  42. package/dist/types.d.ts +52 -15
  43. package/dist/types.js +2 -2
  44. package/dist/verified-origin/configured-origin.d.ts +37 -0
  45. package/dist/verified-origin/configured-origin.js +112 -0
  46. package/dist/verified-origin/index.d.ts +7 -0
  47. package/dist/verified-origin/index.js +6 -0
  48. package/dist/verified-origin/origin.d.ts +65 -0
  49. package/dist/verified-origin/origin.js +151 -0
  50. package/dist/verified-origin/ports.d.ts +40 -0
  51. package/dist/verified-origin/ports.js +2 -0
  52. package/dist/verified-origin/repo.memory.d.ts +34 -0
  53. package/dist/verified-origin/repo.memory.js +34 -0
  54. package/dist/verified-origin/site-path.d.ts +113 -0
  55. package/dist/verified-origin/site-path.js +179 -0
  56. package/dist/verified-origin/types.d.ts +33 -0
  57. package/dist/verified-origin/types.js +23 -0
  58. package/dist/verified-origin.d.ts +2 -0
  59. package/dist/verified-origin.js +2 -0
  60. package/package.json +52 -11
package/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,23 @@
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';
8
+ import type { Response } from 'express';
7
9
  /**
8
10
  * A discriminated success/failure envelope used throughout the module in place of throwing.
9
11
  * Route parsing, handling, and origin checks all resolve to a `Result` so the Adapter can fold
10
12
  * every failure mode into one error-handling pipeline.
11
13
  */
12
- export type Result<T, E = ApiError> = {
13
- ok: true;
14
- value: T;
15
- } | {
16
- ok: false;
17
- error: E;
18
- };
14
+ export type Result<T, E = ApiError> = CoreResult<T, E>;
19
15
  /** Builds a successful `Result` carrying `value`. */
20
- export declare const ok: <T, E = ApiError>(value: T) => Result<T, E>;
16
+ export declare const ok: <T, E = ApiError>({ value }: {
17
+ readonly value: T;
18
+ }, _optional?: Record<string, never>) => Result<T, E>;
21
19
  /** Builds a failed `Result` carrying `error`. */
22
- export declare const err: <T = never, E = ApiError>(error: E) => Result<T, E>;
20
+ export declare const err: <T = never, E = ApiError>({ error }: {
21
+ readonly error: E;
22
+ }, _optional?: Record<string, never>) => Result<T, E>;
23
23
  /**
24
24
  * The normalized shape of a raw HTTP request handed to a route's `parse` function: body, query,
25
25
  * and params, decoupled from any framework `Request` type so parsers are unit-testable without
@@ -36,23 +36,60 @@ export type InputParser<Input> = (raw: RouteInputContext) => Result<Input>;
36
36
  * Handles a parsed `Input` (plus injected `Deps`) and produces a `Result<Output>`.
37
37
  *
38
38
  * `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).
39
+ * 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
40
  */
43
- export type Handler<Input, Output, Deps> = (input: Input, deps: Deps, signal?: AbortSignal) => Promise<Result<Output>> | Result<Output>;
41
+ export type Handler<Input, Output, Deps, Context = undefined> = (requiredArgs: {
42
+ readonly input: Input;
43
+ readonly deps: Deps;
44
+ readonly context?: Context | undefined;
45
+ readonly authorize?: JsonRouteAuthorize;
46
+ }, optionalArgs?: {
47
+ readonly signal?: AbortSignal | undefined;
48
+ }) => Promise<Result<Output>> | Result<Output>;
44
49
  /** HTTP verbs the Adapter can mount a `JsonRouteSpec` under. */
45
50
  export type HttpMethod = 'get' | 'post' | 'put' | 'delete' | 'patch';
51
+ /** Explicit authorization remains at the route's chosen point, preserving validation precedence. */
52
+ export type JsonRouteAuthorize = (requiredArgs: {
53
+ readonly permission: string;
54
+ readonly entityType: string;
55
+ }, optionalArgs?: Record<string, never>) => Promise<void>;
56
+ /** Host-owned workspace, authentication/authorization and exception policy.
57
+ * Guards throw on rejection; the error port owns their wire envelope. Without an error port the
58
+ * adapter retains its caller-safe-error and SEC-005 redaction policy. Authentication can await
59
+ * host readiness; it runs after workspace rejection and before parsing or handling.
60
+ */
61
+ export interface JsonRoutePorts<Deps, Context = undefined> {
62
+ readonly workspace?: (requiredArgs: {
63
+ readonly raw: RouteInputContext;
64
+ readonly deps: Deps;
65
+ }) => void | Promise<void>;
66
+ readonly authenticate?: (requiredArgs: {
67
+ readonly raw: RouteInputContext;
68
+ readonly res: Response;
69
+ readonly deps: Deps;
70
+ }) => Context | Promise<Context>;
71
+ readonly authorize?: (requiredArgs: {
72
+ readonly context: Context | undefined;
73
+ readonly deps: Deps;
74
+ readonly permission: string;
75
+ readonly entityType: string;
76
+ }) => void | Promise<void>;
77
+ readonly onError?: (requiredArgs: {
78
+ readonly res: Response;
79
+ readonly error: unknown;
80
+ }) => void;
81
+ }
46
82
  /**
47
83
  * Declarative description of one JSON route: how to parse input, how to handle it, and whether
48
84
  * it requires a same-origin request. Consumed by `mountJsonRoute` in `adapter.ts`.
49
85
  */
50
- export interface JsonRouteSpec<Input, Output, Deps> {
86
+ export interface JsonRouteSpec<Input, Output, Deps, Context = undefined> {
51
87
  method: HttpMethod;
52
88
  path: string;
53
89
  requireSameOrigin?: boolean;
54
90
  parse: InputParser<Input>;
55
- handle: Handler<Input, Output, Deps>;
91
+ handle: Handler<Input, Output, Deps, Context>;
56
92
  successStatus?: number;
93
+ ports?: JsonRoutePorts<Deps, Context>;
57
94
  }
58
95
  //# sourceMappingURL=types.d.ts.map
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,7 @@
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
+ export { hasControlCharacter, checkSitePathname, checkSiteRelativeTarget, type SitePathCheck, type SiteRelativeTargetCheck, } from "./site-path.js";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,6 @@
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
+ export { hasControlCharacter, checkSitePathname, checkSiteRelativeTarget, } from "./site-path.js";
6
+ //# 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
@@ -0,0 +1,40 @@
1
+ type UUID = string;
2
+ import type { VerifiedOrigin } from "./types.js";
3
+ export interface VerifiedOriginRequestContext {
4
+ workspaceId: UUID;
5
+ siteId?: UUID;
6
+ locale?: string;
7
+ }
8
+ export interface RedirectTargetContext {
9
+ workspaceId: UUID;
10
+ siteId?: UUID;
11
+ originKey?: string;
12
+ }
13
+ export interface EgressTargetContext {
14
+ workspaceId: UUID;
15
+ siteId?: UUID;
16
+ }
17
+ export interface OriginRegistryPort {
18
+ canonicalOrigin(ctx: VerifiedOriginRequestContext): Promise<VerifiedOrigin>;
19
+ isAllowedRedirectTarget(required: {
20
+ context: RedirectTargetContext;
21
+ url: string;
22
+ }): Promise<boolean>;
23
+ isAllowedEgressTarget(required: {
24
+ context: EgressTargetContext;
25
+ url: string;
26
+ }): Promise<boolean>;
27
+ }
28
+ export interface OriginSettingRepoPort {
29
+ findByWorkspaceId(required: {
30
+ workspaceId: UUID;
31
+ }): Promise<VerifiedOrigin | null>;
32
+ findRedirectAllowlist(required: {
33
+ workspaceId: UUID;
34
+ }): Promise<string[]>;
35
+ findEgressAllowlist(required: {
36
+ workspaceId: UUID;
37
+ }): Promise<string[]>;
38
+ }
39
+ export {};
40
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,34 @@
1
+ type UUID = string;
2
+ import type { OriginSettingRepoPort } from "./ports.js";
3
+ import { type VerifiedOrigin } from "./types.js";
4
+ export interface OriginSettingSeed {
5
+ workspaceId: UUID;
6
+ origin: VerifiedOrigin;
7
+ /** Exact-match hosts trusted for cross-origin redirects; independent of third-party egress. */
8
+ redirectAllowlist?: string[];
9
+ /** Exact-match hosts trusted for third-party egress; redirect permission alone does not grant it. */
10
+ egressAllowlist?: string[];
11
+ }
12
+ /** Seeded read adapter that returns copies of origins and lists to protect stored trust.
13
+ * Reads are O(1) for an origin, O(k) for an allowlist; construction is O(total seed host bytes).
14
+ * @example new InMemoryOriginSettingRepo({ seeds: [{ workspaceId, origin }] });
15
+ */
16
+ export declare class InMemoryOriginSettingRepo implements OriginSettingRepoPort {
17
+ private readonly origins;
18
+ private readonly redirectAllowlists;
19
+ private readonly egressAllowlists;
20
+ constructor({ seeds }: {
21
+ seeds: readonly OriginSettingSeed[];
22
+ });
23
+ findByWorkspaceId({ workspaceId }: {
24
+ workspaceId: UUID;
25
+ }): Promise<VerifiedOrigin | null>;
26
+ findRedirectAllowlist({ workspaceId }: {
27
+ workspaceId: UUID;
28
+ }): Promise<string[]>;
29
+ findEgressAllowlist({ workspaceId }: {
30
+ workspaceId: UUID;
31
+ }): Promise<string[]>;
32
+ }
33
+ export {};
34
+ //# sourceMappingURL=repo.memory.d.ts.map