@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
@@ -1,99 +0,0 @@
1
- import { trimCharsEnd } from '@jini-ai/core/primitives';
2
- import { hasForbiddenRawUrlCharacter } from "./origin.js";
3
- import { createVerifiedOrigin } from "./types.js";
4
- import { isLoopbackHost } from "./loopback-host.js";
5
- // Match candidate-origin normalization so a trailing DNS dot has one meaning across decisions.
6
- function normalizeHost(hostname) {
7
- const lowered = hostname.toLowerCase();
8
- return lowered.endsWith(".") ? lowered.slice(0, -1) : lowered;
9
- }
10
- // Reject ambiguous raw characters before parsing can erase them; use the redirect predicate
11
- // rather than introducing a second URL acceptance rule.
12
- function parseConfiguredUrl(raw) {
13
- if (hasForbiddenRawUrlCharacter({ raw }))
14
- return null;
15
- try {
16
- return new URL(raw);
17
- }
18
- catch {
19
- return null;
20
- }
21
- }
22
- // Workspace-setting evidence permits HTTPS only. Refuse HTTP before constructing evidence so
23
- // an invalid operator setting cannot make origin construction throw during boot.
24
- function refusalReason(url) {
25
- if (url.protocol !== "https:")
26
- return "its scheme must be https";
27
- if (url.username !== "" || url.password !== "")
28
- return "it carries a userinfo component";
29
- if (url.search !== "" || url.hash !== "")
30
- return "it carries a query string or fragment";
31
- const host = normalizeHost(url.hostname);
32
- if (host === "")
33
- return "its host is empty";
34
- if (isLoopbackHost({ host }))
35
- return `'${host}' is a loopback host, not a public origin`;
36
- return null;
37
- }
38
- // Omit absent port/basePath keys entirely: explicit undefined differs from an omitted optional
39
- // property under strict equality, and storage adapters preserve that distinction.
40
- function buildConfiguredOrigin(url, now) {
41
- const candidate = {
42
- scheme: "https",
43
- host: normalizeHost(url.hostname),
44
- verifiedAt: now,
45
- source: "workspace-setting",
46
- };
47
- if (url.port !== "")
48
- candidate.port = Number(url.port);
49
- const basePath = trimCharsEnd({ text: url.pathname, chars: "/" });
50
- if (basePath !== "")
51
- candidate.basePath = basePath;
52
- return createVerifiedOrigin(candidate);
53
- }
54
- // Environment authority already controls deployed code; accepting an operator declaration adds
55
- // no request-derived authority. Never feed a request-host fallback into this durable trust root.
56
- // Malformed values leave no evidence, with one diagnostic warning; unset/blank local settings stay
57
- // quiet. Use the host's boot clock so this evidence and other boot rows carry the same timestamp.
58
- /** Accept a caller-named operator declaration or return undefined with a refusal warning.
59
- * No ambient environment lookup. The injected clock stamps accepted evidence only.
60
- * @complexity O(configured URL length) time/space; no network or storage effects.
61
- * @example resolveConfiguredOrigin({ env, envVarName: "APP_PUBLIC_URL", clock, warn });
62
- */
63
- export function resolveConfiguredOrigin(required) {
64
- const { env, envVarName, clock, warn } = required;
65
- const raw = env[envVarName]?.trim();
66
- if (!raw)
67
- return undefined;
68
- const refuse = (reason) => {
69
- warn(`${envVarName} is set but was refused as this deployment's public origin (${reason}); ` +
70
- `no origin was registered from it. Value: ${raw}`);
71
- return undefined;
72
- };
73
- const url = parseConfiguredUrl(raw);
74
- if (!url)
75
- return refuse("it is not a parseable URL");
76
- const reason = refusalReason(url);
77
- if (reason)
78
- return refuse(reason);
79
- return buildConfiguredOrigin(url, clock.nowIso());
80
- }
81
- // A disallowed development seed must produce no registration: persisting localhost in a public
82
- // deployment poisons generated links, and find-or-create storage can preserve the row forever.
83
- // Avoiding new seeds does not repair old rows; registering accepted configured evidence does.
84
- /** Pure boot decision; registration effects and runtime selection stay in the host. */
85
- /** Choose configured evidence, an allowed development seed, or no registration.
86
- * Warnings use caller-supplied policy; registration effects remain host-owned.
87
- * @complexity O(configured URL length) time/space.
88
- * @example planOriginBoot({ env, envVarName, clock, warn, allowDevSeed, missingOriginWarning });
89
- */
90
- export function planOriginBoot(required) {
91
- const origin = resolveConfiguredOrigin(required);
92
- if (origin)
93
- return { kind: "configured", origin };
94
- if (required.allowDevSeed())
95
- return { kind: "dev-seed" };
96
- required.warn(required.missingOriginWarning);
97
- return { kind: "none" };
98
- }
99
- //# sourceMappingURL=configured-origin.js.map
@@ -1,7 +0,0 @@
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
@@ -1,6 +0,0 @@
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
@@ -1,9 +0,0 @@
1
- /** Public identity must not name a development listener. Normalize URL spellings first so
2
- * shortened IPv4 and IPv4-mapped IPv6 cannot bypass the same rule used for localhost.
3
- * Private intranet hosts remain valid. Invalid hosts are left to the caller's URL validation.
4
- * @complexity O(host bytes), pure; parse failures return false.
5
- */
6
- export declare function isLoopbackHost({ host }: {
7
- host: string;
8
- }, _options?: {}): boolean;
9
- //# sourceMappingURL=loopback-host.d.ts.map
@@ -1,17 +0,0 @@
1
- /** Public identity must not name a development listener. Normalize URL spellings first so
2
- * shortened IPv4 and IPv4-mapped IPv6 cannot bypass the same rule used for localhost.
3
- * Private intranet hosts remain valid. Invalid hosts are left to the caller's URL validation.
4
- * @complexity O(host bytes), pure; parse failures return false.
5
- */
6
- export function isLoopbackHost({ host }, _options = {}) {
7
- let hostname;
8
- const authority = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
9
- try {
10
- hostname = new URL(`http://${authority}`).hostname.toLowerCase().replace(/\.$/, "");
11
- }
12
- catch {
13
- return false;
14
- }
15
- return /^(?:localhost|.*\.localhost|127\.\d+\.\d+\.\d+|0\.0\.0\.0|\[(?:::1|::|::ffff:7f[\da-f]{2}:[\da-f]+)\])$/.test(hostname);
16
- }
17
- //# sourceMappingURL=loopback-host.js.map
@@ -1,64 +0,0 @@
1
- import type { VerifiedOriginRequestContext, OriginRegistryPort, OriginSettingRepoPort, RedirectTargetContext, EgressTargetContext } from "./ports.js";
2
- import { type VerifiedOrigin } from "./types.js";
3
- export interface NormalizedTarget {
4
- scheme: "https" | "http";
5
- host: string;
6
- port: number;
7
- }
8
- /** Reject parser-ambiguous backslashes, whitespace and controls before URL normalization.
9
- * @complexity O(raw.length) time, O(1) space; pure.
10
- * @example hasForbiddenRawUrlCharacter({ raw: "/a b" }); // true
11
- */
12
- export declare function hasForbiddenRawUrlCharacter({ raw }: {
13
- raw: string;
14
- }): boolean;
15
- /** Normalize absolute HTTP(S) candidates, refusing ambiguous input and userinfo with null.
16
- * HTTP normalization enables development same-origin checks; cross-origin decisions require HTTPS.
17
- * @complexity O(rawUrl.length) time; parser-bound space. Pure; parse errors return null.
18
- * @example normalizeOriginCandidate({ rawUrl: "https://Example.com./path" });
19
- */
20
- export declare function normalizeOriginCandidate({ rawUrl }: {
21
- rawUrl: string;
22
- }): NormalizedTarget | null;
23
- /** Compare scheme, normalized host and effective port against trusted evidence.
24
- * The target must already be normalized by normalizeOriginCandidate; basePath is not an origin boundary.
25
- * @complexity O(canonical.host.length) time and space; pure.
26
- * @example isSameOrigin({ target, canonical });
27
- */
28
- export declare function isSameOrigin({ target, canonical }: {
29
- target: NormalizedTarget;
30
- canonical: VerifiedOrigin;
31
- }): boolean;
32
- export interface OriginRegistryDeps {
33
- repo: OriginSettingRepoPort;
34
- }
35
- /** Canonical-origin and independent redirect/egress decisions over caller-owned storage.
36
- * @example new OriginRegistry({ repo });
37
- */
38
- export declare class OriginRegistry implements OriginRegistryPort {
39
- private readonly repo;
40
- constructor(deps: OriginRegistryDeps);
41
- /** Resolve stored evidence or throw OriginNotVerifiedError; never derive trust from request headers.
42
- * One repository lookup; O(1) additional time/space excluding the adapter.
43
- */
44
- canonicalOrigin(ctx: VerifiedOriginRequestContext): Promise<VerifiedOrigin>;
45
- /** Allow the canonical origin or an exact redirect-allowlist HTTPS host; errors return false.
46
- * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
47
- */
48
- isAllowedRedirectTarget({ context: ctx, url }: {
49
- context: RedirectTargetContext;
50
- url: string;
51
- }): Promise<boolean>;
52
- /** Apply the same fail-closed rule using the separate egress destination allowlist.
53
- * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
54
- */
55
- isAllowedEgressTarget({ context: ctx, url }: {
56
- context: EgressTargetContext;
57
- url: string;
58
- }): Promise<boolean>;
59
- /** Normalize before looking up trust, then check same origin before the HTTPS-only host allowlist.
60
- * Storage/parse errors return false; O(URL length + allowlist host bytes) time/space.
61
- */
62
- private isAllowedTarget;
63
- }
64
- //# sourceMappingURL=origin.d.ts.map
@@ -1,162 +0,0 @@
1
- import { OriginNotVerifiedError, createVerifiedOrigin } from "./types.js";
2
- /**
3
- * Check the original string before the WHATWG parser strips whitespace/controls or converts a
4
- * backslash to a slash. A stored backslash plus a request tail can become a browser-followed
5
- * cross-host Location even when a parsed-path check sees only slashes. Storage validation and
6
- * redirect reads must use this same raw predicate; checking a reserialized url.href checks too late.
7
- */
8
- // 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.
9
- const FORBIDDEN_RAW_CHARS = /[\\\s\x00-\x08\x0E-\x1F\x7F]/;
10
- /** Reject parser-ambiguous backslashes, whitespace and controls before URL normalization.
11
- * @complexity O(raw.length) time, O(1) space; pure.
12
- * @example hasForbiddenRawUrlCharacter({ raw: "/a b" }); // true
13
- */
14
- export function hasForbiddenRawUrlCharacter({ raw }) {
15
- return FORBIDDEN_RAW_CHARS.test(raw);
16
- }
17
- function parseCandidateUrl(rawUrl) {
18
- if (typeof rawUrl !== "string" || rawUrl.length === 0)
19
- return null;
20
- if (hasForbiddenRawUrlCharacter({ raw: rawUrl }))
21
- return null;
22
- try {
23
- return new URL(rawUrl);
24
- }
25
- catch {
26
- return null;
27
- }
28
- }
29
- function schemeOf(parsed) {
30
- if (parsed.protocol === "https:")
31
- return "https";
32
- if (parsed.protocol === "http:")
33
- return "http";
34
- return null;
35
- }
36
- function defaultPortFor(scheme) {
37
- return scheme === "https" ? 443 : 80;
38
- }
39
- // Explicit ports and scheme defaults (443 for HTTPS, 80 for HTTP) must compare identically.
40
- function resolvePort(parsed, scheme) {
41
- const port = parsed.port ? Number(parsed.port) : defaultPortFor(scheme);
42
- if (!Number.isInteger(port) || port <= 0)
43
- return null;
44
- return port;
45
- }
46
- // WHATWG parsing performs IDNA/case normalization; the remaining single trailing DNS dot must
47
- // be removed consistently from candidates, trusted origins and allowlists.
48
- /** Normalize absolute HTTP(S) candidates, refusing ambiguous input and userinfo with null.
49
- * HTTP normalization enables development same-origin checks; cross-origin decisions require HTTPS.
50
- * @complexity O(rawUrl.length) time; parser-bound space. Pure; parse errors return null.
51
- * @example normalizeOriginCandidate({ rawUrl: "https://Example.com./path" });
52
- */
53
- export function normalizeOriginCandidate({ rawUrl }) {
54
- const parsed = parseCandidateUrl(rawUrl);
55
- if (!parsed)
56
- return null;
57
- const scheme = schemeOf(parsed);
58
- if (!scheme)
59
- return null;
60
- if (parsed.username !== "" || parsed.password !== "")
61
- return null;
62
- const host = stripTrailingDot(parsed.hostname.toLowerCase());
63
- if (!host)
64
- return null;
65
- const port = resolvePort(parsed, scheme);
66
- if (port === null)
67
- return null;
68
- return { scheme, host, port };
69
- }
70
- function stripTrailingDot(host) {
71
- return host.endsWith(".") ? host.slice(0, -1) : host;
72
- }
73
- /** Normalize a bare allowlisted host through the candidate's WHATWG/IDNA policy.
74
- * URL delimiters and ports are not host entries; colons are valid only inside bracketed IPv6.
75
- * Returns null for invalid entries; pure, O(host.length) time and space.
76
- */
77
- function normalizeAllowlistedHost({ host }, _optional = {}) {
78
- const value = host.trim();
79
- if (/[/\\?#@%]/u.test(value))
80
- return null;
81
- if (value.includes(":") && !value.endsWith("]"))
82
- return null;
83
- return normalizeOriginCandidate({ rawUrl: `https://${value}` })?.host ?? null;
84
- }
85
- function effectivePort(origin) {
86
- return origin.port ?? (origin.scheme === "https" ? 443 : 80);
87
- }
88
- // URL.origin strings preserve a trailing dot: https://site. and https://site reach the same
89
- // server even though browsers keep their cookie/script origins separate. This destination rule
90
- // compares normalized hosts so redirect validation and reserved-destination checks cannot disagree.
91
- /** Compare scheme, normalized host and effective port against trusted evidence.
92
- * The target must already be normalized by normalizeOriginCandidate; basePath is not an origin boundary.
93
- * @complexity O(canonical.host.length) time and space; pure.
94
- * @example isSameOrigin({ target, canonical });
95
- */
96
- export function isSameOrigin({ target, canonical }) {
97
- if (canonical.scheme !== target.scheme)
98
- return false;
99
- if (stripTrailingDot(canonical.host.toLowerCase()) !== target.host)
100
- return false;
101
- return effectivePort(canonical) === target.port;
102
- }
103
- /** Canonical-origin and independent redirect/egress decisions over caller-owned storage.
104
- * @example new OriginRegistry({ repo });
105
- */
106
- export class OriginRegistry {
107
- repo;
108
- constructor(deps) {
109
- this.repo = deps.repo;
110
- }
111
- // This repository selects one origin per workspace; optional site/locale/origin keys do not
112
- // currently select a different origin. Missing evidence must not trigger request-host guessing.
113
- /** Resolve stored evidence or throw OriginNotVerifiedError; never derive trust from request headers.
114
- * One repository lookup; O(1) additional time/space excluding the adapter.
115
- */
116
- async canonicalOrigin(ctx) {
117
- const origin = await this.repo.findByWorkspaceId({ workspaceId: ctx.workspaceId });
118
- if (!origin) {
119
- throw new OriginNotVerifiedError({ message: `no verified origin registered for workspace '${ctx.workspaceId}'` });
120
- }
121
- return createVerifiedOrigin(origin);
122
- }
123
- /** Allow the canonical origin or an exact redirect-allowlist HTTPS host; errors return false.
124
- * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
125
- */
126
- async isAllowedRedirectTarget({ context: ctx, url }) {
127
- return this.isAllowedTarget(ctx, url, (workspaceId) => this.repo.findRedirectAllowlist({ workspaceId }));
128
- }
129
- /** Apply the same fail-closed rule using the separate egress destination allowlist.
130
- * @complexity O(URL length + allowlist host bytes) time/space; at most two repository reads.
131
- */
132
- async isAllowedEgressTarget({ context: ctx, url }) {
133
- return this.isAllowedTarget(ctx, url, (workspaceId) => this.repo.findEgressAllowlist({ workspaceId }));
134
- }
135
- /** Normalize before looking up trust, then check same origin before the HTTPS-only host allowlist.
136
- * Storage/parse errors return false; O(URL length + allowlist host bytes) time/space.
137
- */
138
- async isAllowedTarget(ctx, rawUrl, loadAllowlist) {
139
- try {
140
- const target = normalizeOriginCandidate({ rawUrl });
141
- if (!target)
142
- return false;
143
- const canonical = await this.canonicalOrigin({ workspaceId: ctx.workspaceId, ...(ctx.siteId === undefined ? {} : { siteId: ctx.siteId }) });
144
- if (isSameOrigin({ target, canonical }))
145
- return true;
146
- // Cross-origin allowlist path is https-only, unconditionally — the. See docs/decisions/DR-001-redirect-normalization.md.
147
- // dev-capability http exception above applies ONLY to the same-origin comparison, never
148
- // to a cross-origin allowlisted target. See docs/decisions/DR-001-redirect-normalization.md.
149
- if (target.scheme !== "https")
150
- return false;
151
- const allowlist = await loadAllowlist(ctx.workspaceId);
152
- const allowSet = new Set(allowlist.map((host) => normalizeAllowlistedHost({ host })));
153
- return allowSet.has(target.host);
154
- }
155
- catch {
156
- // Fail closed: an unverified origin, a repo error, or any unexpected
157
- // exception must never be treated as "allowed".
158
- return false;
159
- }
160
- }
161
- }
162
- //# sourceMappingURL=origin.js.map
@@ -1,38 +0,0 @@
1
- import type { VerifiedOrigin } from "./types.js";
2
- export interface VerifiedOriginRequestContext {
3
- workspaceId: string;
4
- siteId?: string;
5
- locale?: string;
6
- }
7
- export interface RedirectTargetContext {
8
- workspaceId: string;
9
- siteId?: string;
10
- originKey?: string;
11
- }
12
- export interface EgressTargetContext {
13
- workspaceId: string;
14
- siteId?: string;
15
- }
16
- export interface OriginRegistryPort {
17
- canonicalOrigin(ctx: VerifiedOriginRequestContext): Promise<VerifiedOrigin>;
18
- isAllowedRedirectTarget(required: {
19
- context: RedirectTargetContext;
20
- url: string;
21
- }): Promise<boolean>;
22
- isAllowedEgressTarget(required: {
23
- context: EgressTargetContext;
24
- url: string;
25
- }): Promise<boolean>;
26
- }
27
- export interface OriginSettingRepoPort {
28
- findByWorkspaceId(required: {
29
- workspaceId: string;
30
- }): Promise<VerifiedOrigin | null>;
31
- findRedirectAllowlist(required: {
32
- workspaceId: string;
33
- }): Promise<string[]>;
34
- findEgressAllowlist(required: {
35
- workspaceId: string;
36
- }): Promise<string[]>;
37
- }
38
- //# sourceMappingURL=ports.d.ts.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=ports.js.map
@@ -1,32 +0,0 @@
1
- import type { OriginSettingRepoPort } from "./ports.js";
2
- import { type VerifiedOrigin } from "./types.js";
3
- export interface OriginSettingSeed {
4
- workspaceId: string;
5
- origin: VerifiedOrigin;
6
- /** Exact-match hosts trusted for cross-origin redirects; independent of third-party egress. */
7
- redirectAllowlist?: string[];
8
- /** Exact-match hosts trusted for third-party egress; redirect permission alone does not grant it. */
9
- egressAllowlist?: string[];
10
- }
11
- /** Seeded read adapter that returns copies of origins and lists to protect stored trust.
12
- * Reads are O(1) for an origin, O(k) for an allowlist; construction is O(total seed host bytes).
13
- * @example new InMemoryOriginSettingRepo({ seeds: [{ workspaceId, origin }] });
14
- */
15
- export declare class InMemoryOriginSettingRepo implements OriginSettingRepoPort {
16
- private readonly origins;
17
- private readonly redirectAllowlists;
18
- private readonly egressAllowlists;
19
- constructor({ seeds }: {
20
- seeds: readonly OriginSettingSeed[];
21
- });
22
- findByWorkspaceId({ workspaceId }: {
23
- workspaceId: string;
24
- }): Promise<VerifiedOrigin | null>;
25
- findRedirectAllowlist({ workspaceId }: {
26
- workspaceId: string;
27
- }): Promise<string[]>;
28
- findEgressAllowlist({ workspaceId }: {
29
- workspaceId: string;
30
- }): Promise<string[]>;
31
- }
32
- //# sourceMappingURL=repo.memory.d.ts.map
@@ -1,34 +0,0 @@
1
- import { createVerifiedOrigin } from "./types.js";
2
- /** Seeded read adapter that returns copies of origins and lists to protect stored trust.
3
- * Reads are O(1) for an origin, O(k) for an allowlist; construction is O(total seed host bytes).
4
- * @example new InMemoryOriginSettingRepo({ seeds: [{ workspaceId, origin }] });
5
- */
6
- export class InMemoryOriginSettingRepo {
7
- origins;
8
- redirectAllowlists;
9
- egressAllowlists;
10
- constructor({ seeds }) {
11
- this.origins = new Map();
12
- this.redirectAllowlists = new Map();
13
- this.egressAllowlists = new Map();
14
- for (const seed of seeds) {
15
- this.origins.set(seed.workspaceId, createVerifiedOrigin(seed.origin));
16
- this.redirectAllowlists.set(seed.workspaceId, normalizeHostList(seed.redirectAllowlist));
17
- this.egressAllowlists.set(seed.workspaceId, normalizeHostList(seed.egressAllowlist));
18
- }
19
- }
20
- async findByWorkspaceId({ workspaceId }) {
21
- const origin = this.origins.get(workspaceId);
22
- return origin ? { ...origin } : null;
23
- }
24
- async findRedirectAllowlist({ workspaceId }) {
25
- return [...(this.redirectAllowlists.get(workspaceId) ?? [])];
26
- }
27
- async findEgressAllowlist({ workspaceId }) {
28
- return [...(this.egressAllowlists.get(workspaceId) ?? [])];
29
- }
30
- }
31
- function normalizeHostList(hosts) {
32
- return (hosts ?? []).map((host) => host.trim().toLowerCase());
33
- }
34
- //# sourceMappingURL=repo.memory.js.map
@@ -1,113 +0,0 @@
1
- /**
2
- * @file Shared site-path checks: decoded, dot-resolved segments and origin tracking.
3
- *
4
- * Why the rule is not `path.startsWith("/admin")`:
5
- * - `/administer-survey` is ordinary site content and must keep working, so the comparison is per
6
- * SEGMENT, not per prefix.
7
- * - `/%61dmin` is compared AFTER one percent-decode, not on the raw bytes. Express (which routes on
8
- * the raw path) and browsers (which do not decode `%61` in a path) do NOT treat it as `/admin`; a
9
- * proxy or server that decodes before routing does. Refusing it is deliberate over-refusal — the
10
- * safe direction for a rule whose job is to keep public redirects and fetches off the admin
11
- * surface.
12
- * - `/ADMIN` reaches the same Express mount (Express matches paths case-insensitively by default),
13
- * so the comparison is case-folded.
14
- * - `/blog/../admin` is `/admin` by the time a browser issues the request, so dot segments are
15
- * resolved first.
16
- *
17
- */
18
- /** {@link checkSitePathname}'s verdict. Every arm is a refusal except `ok`. */
19
- export type SitePathCheck = {
20
- kind: "ok";
21
- }
22
- /** `decodeURIComponent` threw — a stray or truncated `%` sequence. */
23
- | {
24
- kind: "malformed-encoding";
25
- }
26
- /** Decodes to a backslash (a `/` to URL parsers) or a C0/C1 control character (CR/LF splitting). */
27
- | {
28
- kind: "disallowed-character";
29
- } | {
30
- kind: "reserved";
31
- surface: string;
32
- };
33
- /** {@link checkSiteRelativeTarget}'s verdict — {@link SitePathCheck} plus the two structural arms
34
- * that only apply when the input is still a raw, unparsed reference. */
35
- export type SiteRelativeTargetCheck = SitePathCheck
36
- /** `new URL()` could not parse it at all. */
37
- | {
38
- kind: "unparseable";
39
- }
40
- /** Parses, but resolves to a DIFFERENT host — e.g. `/\evil.example`, which starts with a single
41
- * slash yet is `//evil.example` to a URL parser, so a `startsWith("//")` test never sees it. */
42
- | {
43
- kind: "off-origin";
44
- };
45
- /**
46
- * Whether `value` contains a C0 or C1 control character.
47
- *
48
- * CR/LF in a request target is HTTP request splitting and in a `Location` header is response
49
- * splitting; NUL and friends are path-truncation tricks.
50
- *
51
- * @param required.value - Any string, already decoded or not.
52
- * @returns `true` if any code unit is in `U+0000`–`U+001F` or `U+007F`–`U+009F`.
53
- * @complexity O(n) in the string length.
54
- * @example hasControlCharacter({ value: "/ok" }, {}); // => false
55
- */
56
- export declare function hasControlCharacter({ value }: {
57
- value: string;
58
- }, _optional?: Record<string, never>): boolean;
59
- /**
60
- * Classify an already-parsed URL's pathname against the admin application's URL space.
61
- *
62
- * Takes the {@link URL} itself, not a bare pathname string, so this cannot be handed a raw,
63
- * unparsed reference by accident: a string has no way to prove it went through `new URL()` first,
64
- * and this rule's whole design (see the module doc) depends on comparing the DECODED, dot-resolved
65
- * form a URL parser would actually produce. A caller that only has a raw string — a stored redirect
66
- * target, anything from user input — must go through {@link checkSiteRelativeTarget} instead, which
67
- * parses it (and rejects what doesn't parse) before this check ever runs.
68
- *
69
- * PRECONDITION: the caller has already established that `url` is on the site's own origin. This
70
- * function reads only `pathname`, so `new URL("//admin", base)` (host `admin`, pathname `/`)
71
- * returns `ok`. It deliberately does not compare origins itself: `platform/routing` cannot use
72
- * `features/origin`'s normalizer, and a string `URL.origin` comparison is wrong for redirect
73
- * candidates (`https://site./admin`). Callers: `checkSiteRelativeTarget` (probe-origin check),
74
- * `site-inspection`'s `resolveWithinOrigin`, and `features/redirects/reserved-destination.ts` (the
75
- * origin oracle's `isSameOrigin`).
76
- *
77
- * @param required.url - An already-parsed `URL`; only `url.pathname` is read.
78
- * @param required.reservedSegments - First segments reserved by the host, stored case-folded.
79
- * @returns `{ kind: "ok" }` when it is ordinary site content; otherwise the arm naming the refusal.
80
- * @complexity O(n) in the pathname length.
81
- * @example checkSitePathname({ url: new URL("/administer-survey", "http://x.invalid"), reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "ok" }
82
- * @example checkSitePathname({ url: new URL("/%61dmin/settings", "http://x.invalid"), reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "reserved", surface: "admin" }
83
- */
84
- export declare function checkSitePathname({ url, reservedSegments }: {
85
- url: URL;
86
- reservedSegments: ReadonlySet<string>;
87
- }, _optional?: Record<string, never>): SitePathCheck;
88
- /**
89
- * Classify a raw, site-relative reference (a stored redirect target, a caller-supplied path)
90
- * against the admin application's URL space, including the structural check that it is site-
91
- * relative at all.
92
- *
93
- * The structural pass runs FIRST and matters on its own: `/\evil.example` begins with exactly one
94
- * slash, so a `startsWith("//")` or scheme test calls it site-relative, while `new URL()` — and
95
- * every browser following a `Location` — reads the backslash as a separator and lands on
96
- * `evil.example`. Resolving against a probe origin and asserting the origin TRACKED that base is a
97
- * structural answer to that instead of a pattern someone has to keep correct — done against two
98
- * different bases so the probe origin itself is not a nameable way to pass (see
99
- * {@link PROBE_ORIGIN}).
100
- *
101
- * @param required.raw - The untrusted reference, expected to be site-relative.
102
- * @param required.reservedSegments - First segments reserved by the host, stored case-folded.
103
- * @returns `{ kind: "ok" }` when it stays on this site and names ordinary content; otherwise the
104
- * arm naming the refusal.
105
- * @complexity O(n) in the reference length.
106
- * @example checkSiteRelativeTarget({ raw: "/new", reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "ok" }
107
- * @example checkSiteRelativeTarget({ raw: "/\\evil.example", reservedSegments: new Set(["admin", "api"]) }, {}); // => { kind: "off-origin" }
108
- */
109
- export declare function checkSiteRelativeTarget({ raw, reservedSegments }: {
110
- raw: string;
111
- reservedSegments: ReadonlySet<string>;
112
- }, _optional?: Record<string, never>): SiteRelativeTargetCheck;
113
- //# sourceMappingURL=site-path.d.ts.map