@k9o/extension-runtime 1.5.0 → 1.6.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.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/bff-hook-discriminator.ts +3 -2
- package/src/client.ts +19 -1
- package/src/http.ts +75 -6
- package/src/index.ts +21 -0
- package/src/insecure-http.ts +575 -0
- package/src/namespaces/auth-migrations.ts +176 -0
- package/src/namespaces/bff.ts +12 -2
- package/src/namespaces/credentials.ts +8 -0
- package/src/namespaces/files.ts +96 -0
- package/src/namespaces/vectors.ts +108 -9
|
@@ -0,0 +1,575 @@
|
|
|
1
|
+
// The shared client helper for plain http off loopback, the same in every TypeScript client. Keep it identical to the helper in the k9o-core client package; only this first line differs.
|
|
2
|
+
/**
|
|
3
|
+
* Plain http off loopback: the one rule every TypeScript client takes.
|
|
4
|
+
*
|
|
5
|
+
* A base URL that is `http:` and whose host is not loopback is refused when a client is built, unless the caller opts in
|
|
6
|
+
* on purpose. Loopback is a string match on the host, never a DNS answer: `localhost`, `127.0.0.1`, `[::1]` and any
|
|
7
|
+
* `*.localhost`. `localhost.evil.com` is not loopback, and neither is `127.0.0.2`.
|
|
8
|
+
*
|
|
9
|
+
* The opt-in is the environment variable `K9O_ALLOW_INSECURE_HTTP` set to exactly `1` or `true`, or the client option
|
|
10
|
+
* `allowInsecureHttp: true`. An explicit option wins over the environment in either direction. The opt-in is never
|
|
11
|
+
* read from or written to a stored profile. When it lets a non-loopback http host through, one warning per process per
|
|
12
|
+
* host names the host and nothing else.
|
|
13
|
+
*
|
|
14
|
+
* Redirects follow one policy (see {@link classifyRedirect} and {@link fetchWithRedirectPolicy}): a redirect to plain
|
|
15
|
+
* http off loopback is refused unless the hop is http to http under the opt-in, an https to http hop is always
|
|
16
|
+
* refused, a cross-origin hop drops every header that is not on a short allow-list, and a same-origin hop keeps them.
|
|
17
|
+
*
|
|
18
|
+
* This module imports nothing, so a package that cannot depend on the whole of `@k9o/core` can bundle it alone.
|
|
19
|
+
* Callers wrap {@link InsecureHttpRefusal} and {@link RedirectRefusal} in their own error class.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/** The environment variable that opts a process in to plain http off loopback. Only `1` and `true` turn it on. */
|
|
23
|
+
export const INSECURE_HTTP_ENV = "K9O_ALLOW_INSECURE_HTTP";
|
|
24
|
+
|
|
25
|
+
/** The fixed hint on a refused base URL. It names the opt-in and carries no part of the URL. */
|
|
26
|
+
export const INSECURE_HTTP_HINT =
|
|
27
|
+
"Use an https:// base URL. An install that serves only plain http can opt in with K9O_ALLOW_INSECURE_HTTP=1 or the client option allowInsecureHttp: true; credentials and tokens then travel unencrypted.";
|
|
28
|
+
|
|
29
|
+
/** The error code on a refused base URL (the existing base-URL code). */
|
|
30
|
+
export const INSECURE_HTTP_CODE = "K9O_INVALID_BASE_URL";
|
|
31
|
+
|
|
32
|
+
/** The error code on a refused redirect. */
|
|
33
|
+
export const REDIRECT_REFUSED_CODE = "K9O_REDIRECT_REFUSED";
|
|
34
|
+
|
|
35
|
+
/** The most redirects a single request follows. */
|
|
36
|
+
export const MAX_REDIRECTS = 5;
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* True when `hostname` is a loopback host by name: `localhost`, `127.0.0.1`, `[::1]`, or a name ending in `.localhost`
|
|
40
|
+
* with at least one label before it. A string match only: nothing is resolved. Case-insensitive.
|
|
41
|
+
*/
|
|
42
|
+
export function isLoopbackHost(hostname: string): boolean {
|
|
43
|
+
const h = hostname.toLowerCase();
|
|
44
|
+
if (h === "localhost" || h === "127.0.0.1" || h === "[::1]") return true;
|
|
45
|
+
return h.length > ".localhost".length && h.endsWith(".localhost") && !h.startsWith(".");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** True only for the exact strings `1` and `true`. Anything else, including `yes`, `TRUE`, `0` and an empty string, is off. */
|
|
49
|
+
export function parseInsecureHttpOptIn(value: string | null | undefined): boolean {
|
|
50
|
+
return value === "1" || value === "true";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type EnvLike = Readonly<Record<string, string | undefined>>;
|
|
54
|
+
|
|
55
|
+
function processEnv(): EnvLike | undefined {
|
|
56
|
+
const p = (globalThis as { process?: { env?: EnvLike } }).process;
|
|
57
|
+
return p !== undefined && p !== null && typeof p.env === "object" && p.env !== null ? p.env : undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The opt-in as the environment states it (`K9O_ALLOW_INSECURE_HTTP`). False where there is no environment (a browser). */
|
|
61
|
+
export function insecureHttpOptInFromEnv(env: EnvLike | undefined = processEnv()): boolean {
|
|
62
|
+
return parseInsecureHttpOptIn(env?.[INSECURE_HTTP_ENV]);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The effective opt-in for one client. An explicit `true` or `false` wins over the environment. Left unset, the
|
|
67
|
+
* environment decides. Any other value (a string, a number, null) is off: the opt-in fails closed.
|
|
68
|
+
*/
|
|
69
|
+
export function resolveInsecureHttpOptIn(option: unknown, env: EnvLike | undefined = processEnv()): boolean {
|
|
70
|
+
if (option === true) return true;
|
|
71
|
+
if (option !== undefined) return false;
|
|
72
|
+
return insecureHttpOptInFromEnv(env);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** What the rule says about a base URL. */
|
|
76
|
+
export type BaseUrlTransport = "allowed" | "refused" | "allowed-with-warning";
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Classify a base URL under the rule. `https:` is allowed for any host. `http:` is allowed for a loopback host, allowed
|
|
80
|
+
* with a warning for any other host when `optIn` is true, and refused otherwise. A URL that does not parse, or names
|
|
81
|
+
* another scheme, is refused. Pure.
|
|
82
|
+
*/
|
|
83
|
+
export function classifyBaseUrlTransport(baseUrl: string, optIn: boolean): BaseUrlTransport {
|
|
84
|
+
let u: URL;
|
|
85
|
+
try {
|
|
86
|
+
u = new URL(baseUrl);
|
|
87
|
+
} catch {
|
|
88
|
+
return "refused";
|
|
89
|
+
}
|
|
90
|
+
if (u.protocol === "https:") return "allowed";
|
|
91
|
+
if (u.protocol !== "http:") return "refused";
|
|
92
|
+
if (isLoopbackHost(u.hostname)) return "allowed";
|
|
93
|
+
return optIn ? "allowed-with-warning" : "refused";
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The fields of a refused base URL, for the caller's own error class. `context.host` is the host as typed (with its port). */
|
|
97
|
+
export type InsecureHttpRefusal = {
|
|
98
|
+
code: typeof INSECURE_HTTP_CODE;
|
|
99
|
+
message: string;
|
|
100
|
+
recommendation: string;
|
|
101
|
+
context: { host: string };
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
/** The refusal for `host` (hostname and port, never a path, query or credential). */
|
|
105
|
+
export function insecureHttpRefusal(host: string): InsecureHttpRefusal {
|
|
106
|
+
return {
|
|
107
|
+
code: INSECURE_HTTP_CODE,
|
|
108
|
+
message: `Plain http to ${host} is refused: it is not a loopback host, so credentials and tokens would travel unencrypted.`,
|
|
109
|
+
recommendation: INSECURE_HTTP_HINT,
|
|
110
|
+
context: { host },
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The one warning line for `host`. It names the host and nothing else. */
|
|
115
|
+
export function insecureHttpWarning(host: string): string {
|
|
116
|
+
return `warning: ${host} is reached over plain http; credentials and tokens travel unencrypted. Set up TLS where you can.`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const WARNED_KEY = Symbol.for("k9o.insecure-http.warned-hosts");
|
|
120
|
+
|
|
121
|
+
function warnedHosts(): Set<string> {
|
|
122
|
+
const g = globalThis as unknown as Record<symbol, Set<string> | undefined>;
|
|
123
|
+
let s = g[WARNED_KEY];
|
|
124
|
+
if (s === undefined) {
|
|
125
|
+
s = new Set<string>();
|
|
126
|
+
g[WARNED_KEY] = s;
|
|
127
|
+
}
|
|
128
|
+
return s;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Standard error where the runtime has one (Node, Bun, the CLI), else `console.warn` (a browser, React Native). */
|
|
132
|
+
function defaultWarn(line: string): void {
|
|
133
|
+
const p = (globalThis as { process?: { stderr?: { write?: (s: string) => unknown } } }).process;
|
|
134
|
+
if (p !== undefined && p !== null && typeof p.stderr?.write === "function") {
|
|
135
|
+
p.stderr.write(`${line}\n`);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
// eslint-disable-next-line no-console
|
|
139
|
+
console.warn(line);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Print {@link insecureHttpWarning} for `host` once per process (to standard error, or `console.warn` where there is none). The set of warned hosts lives on `globalThis`, so two
|
|
144
|
+
* copies of this module in one process (a bundled one and an installed one) still warn once. Returns true when it printed.
|
|
145
|
+
*/
|
|
146
|
+
export function warnInsecureHttpOnce(host: string, sink: (line: string) => void = defaultWarn): boolean {
|
|
147
|
+
const key = host.toLowerCase();
|
|
148
|
+
const seen = warnedHosts();
|
|
149
|
+
if (seen.has(key)) return false;
|
|
150
|
+
seen.add(key);
|
|
151
|
+
sink(insecureHttpWarning(host));
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Tests only: forget which hosts were warned about. */
|
|
156
|
+
export function _resetInsecureHttpWarningsForTest(): void {
|
|
157
|
+
warnedHosts().clear();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Options for {@link checkBaseUrlTransport}. */
|
|
161
|
+
export type BaseUrlTransportOptions = {
|
|
162
|
+
/** The client option. `true` or `false` wins over the environment; unset, the environment decides. */
|
|
163
|
+
allowInsecureHttp?: boolean | undefined;
|
|
164
|
+
/** The environment to read; defaults to `process.env` where there is one. */
|
|
165
|
+
env?: EnvLike | undefined;
|
|
166
|
+
/** Where the warning goes; defaults to `console.warn`. */
|
|
167
|
+
warn?: ((line: string) => void) | undefined;
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/** The outcome of {@link checkBaseUrlTransport}. `refusal` is set exactly when `verdict` is `refused`. */
|
|
171
|
+
export type BaseUrlTransportCheck = {
|
|
172
|
+
verdict: BaseUrlTransport;
|
|
173
|
+
/** Hostname and port of the base URL as parsed; empty when it does not parse. */
|
|
174
|
+
host: string;
|
|
175
|
+
refusal: InsecureHttpRefusal | null;
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Apply the rule to a base URL at client construction: classify it, print the once-per-host warning when the opt-in
|
|
180
|
+
* lets a non-loopback http host through, and return the refusal (not thrown) otherwise. A URL that does not parse is
|
|
181
|
+
* left to the caller's shape check: the verdict is `refused` with a refusal naming an empty host.
|
|
182
|
+
*/
|
|
183
|
+
export function checkBaseUrlTransport(baseUrl: string, options: BaseUrlTransportOptions = {}): BaseUrlTransportCheck {
|
|
184
|
+
const optIn = resolveInsecureHttpOptIn(options.allowInsecureHttp, options.env ?? processEnv());
|
|
185
|
+
const verdict = classifyBaseUrlTransport(baseUrl, optIn);
|
|
186
|
+
let host = "";
|
|
187
|
+
try {
|
|
188
|
+
host = new URL(baseUrl).host;
|
|
189
|
+
} catch {
|
|
190
|
+
host = "";
|
|
191
|
+
}
|
|
192
|
+
if (verdict === "allowed-with-warning") warnInsecureHttpOnce(host, options.warn);
|
|
193
|
+
return { verdict, host, refusal: verdict === "refused" ? insecureHttpRefusal(host) : null };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* The headers a cross-origin redirect hop keeps. Everything else is dropped: `authorization`, `dpop`, `cookie`,
|
|
198
|
+
* `proxy-authorization`, `x-api-key`, every `x-k9o-*` header (step-up proofs, reveal challenges, org and project
|
|
199
|
+
* context) and any header this list does not name. An allow-list, so a credential header added later is dropped too.
|
|
200
|
+
*/
|
|
201
|
+
export const REDIRECT_KEEP_HEADERS: ReadonlySet<string> = new Set([
|
|
202
|
+
"accept",
|
|
203
|
+
"accept-encoding",
|
|
204
|
+
"accept-language",
|
|
205
|
+
"cache-control",
|
|
206
|
+
"pragma",
|
|
207
|
+
"if-none-match",
|
|
208
|
+
"if-modified-since",
|
|
209
|
+
"if-match",
|
|
210
|
+
"if-unmodified-since",
|
|
211
|
+
"if-range",
|
|
212
|
+
"range",
|
|
213
|
+
"user-agent",
|
|
214
|
+
"traceparent",
|
|
215
|
+
"tracestate",
|
|
216
|
+
"k9o-api-version",
|
|
217
|
+
]);
|
|
218
|
+
|
|
219
|
+
/** True for any header a cross-origin hop drops: every name not on {@link REDIRECT_KEEP_HEADERS}. Case-insensitive. */
|
|
220
|
+
export function isCredentialHeader(name: string): boolean {
|
|
221
|
+
return !REDIRECT_KEEP_HEADERS.has(name.toLowerCase());
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
type HeaderSource = Headers | ReadonlyArray<readonly [string, string]> | Readonly<Record<string, string>> | undefined;
|
|
225
|
+
|
|
226
|
+
function headerEntries(h: HeaderSource): Array<[string, string]> {
|
|
227
|
+
if (h === undefined) return [];
|
|
228
|
+
if (typeof Headers !== "undefined" && h instanceof Headers) {
|
|
229
|
+
const out: Array<[string, string]> = [];
|
|
230
|
+
h.forEach((v, k) => out.push([k, v]));
|
|
231
|
+
return out;
|
|
232
|
+
}
|
|
233
|
+
if (Array.isArray(h)) return (h as ReadonlyArray<readonly [string, string]>).map(([k, v]) => [k, v]);
|
|
234
|
+
return Object.entries(h as Record<string, string>);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** A copy of `headers` with only the {@link REDIRECT_KEEP_HEADERS} names, lower-cased. */
|
|
238
|
+
export function stripCredentialHeaders(headers: HeaderSource): Record<string, string> {
|
|
239
|
+
const out: Record<string, string> = {};
|
|
240
|
+
for (const [k, v] of headerEntries(headers)) {
|
|
241
|
+
const n = k.toLowerCase();
|
|
242
|
+
if (!isCredentialHeader(n)) out[n] = v;
|
|
243
|
+
}
|
|
244
|
+
return out;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** What to do with one redirect hop. */
|
|
248
|
+
export type RedirectDecision = "follow-keep-credentials" | "follow-drop-credentials" | "refuse";
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Decide one redirect hop from `from` to `to` (both absolute). Pure.
|
|
252
|
+
* - `to` that does not parse, is not http(s), or carries userinfo: refuse.
|
|
253
|
+
* - `https:` to `http:`: refuse, whatever the host (a downgrade).
|
|
254
|
+
* - `http:` to `http:` off loopback: refuse unless `optIn`.
|
|
255
|
+
* - Otherwise follow; keep credentials only when the origin (scheme, host, port) is unchanged.
|
|
256
|
+
*/
|
|
257
|
+
export function classifyRedirect(from: string, to: string, optIn: boolean): RedirectDecision {
|
|
258
|
+
let f: URL;
|
|
259
|
+
let t: URL;
|
|
260
|
+
try {
|
|
261
|
+
f = new URL(from);
|
|
262
|
+
t = new URL(to);
|
|
263
|
+
} catch {
|
|
264
|
+
return "refuse";
|
|
265
|
+
}
|
|
266
|
+
if (t.protocol !== "https:" && t.protocol !== "http:") return "refuse";
|
|
267
|
+
if (t.username !== "" || t.password !== "") return "refuse";
|
|
268
|
+
if (t.protocol === "http:") {
|
|
269
|
+
if (f.protocol !== "http:") return "refuse";
|
|
270
|
+
if (!isLoopbackHost(t.hostname) && !optIn) return "refuse";
|
|
271
|
+
}
|
|
272
|
+
return f.origin === t.origin ? "follow-keep-credentials" : "follow-drop-credentials";
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The fields of a refused redirect, for the caller's own error class. Names the status and the Location's origin, never its path or query. */
|
|
276
|
+
export type RedirectRefusal = {
|
|
277
|
+
code: typeof REDIRECT_REFUSED_CODE;
|
|
278
|
+
message: string;
|
|
279
|
+
recommendation: string | null;
|
|
280
|
+
context: { status: number; locationOrigin: string | null; reason: RedirectRefusalReason };
|
|
281
|
+
status: number;
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
/** Why a redirect was refused. */
|
|
285
|
+
export type RedirectRefusalReason =
|
|
286
|
+
| "no_location"
|
|
287
|
+
| "bad_location"
|
|
288
|
+
| "downgrade"
|
|
289
|
+
| "insecure_http"
|
|
290
|
+
| "body_cross_origin"
|
|
291
|
+
| "loop"
|
|
292
|
+
| "too_many"
|
|
293
|
+
| "not_a_redirect"
|
|
294
|
+
| "opaque"
|
|
295
|
+
| "runtime_followed"
|
|
296
|
+
| "cross_origin";
|
|
297
|
+
|
|
298
|
+
function originOf(location: string, base: string): string | null {
|
|
299
|
+
try {
|
|
300
|
+
const u = new URL(location, base);
|
|
301
|
+
return u.protocol === "http:" || u.protocol === "https:" ? u.origin : u.protocol;
|
|
302
|
+
} catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Build the refusal for a hop. */
|
|
308
|
+
export function redirectRefusal(status: number, locationOrigin: string | null, reason: RedirectRefusalReason): RedirectRefusal {
|
|
309
|
+
const where = locationOrigin === null ? "no usable Location" : `Location ${locationOrigin}`;
|
|
310
|
+
const why: Record<RedirectRefusalReason, string> = {
|
|
311
|
+
no_location: "the response has no Location",
|
|
312
|
+
bad_location: "the Location is not an http(s) URL",
|
|
313
|
+
downgrade: "it leaves https for plain http",
|
|
314
|
+
insecure_http: "it goes to plain http off loopback",
|
|
315
|
+
body_cross_origin: "it would send the request body to another origin",
|
|
316
|
+
loop: "it loops",
|
|
317
|
+
too_many: `more than ${MAX_REDIRECTS} redirects`,
|
|
318
|
+
not_a_redirect: "this status is not a redirect the client follows",
|
|
319
|
+
opaque: "this runtime hides the redirect from the client",
|
|
320
|
+
runtime_followed: "the runtime followed it on its own, to a target the policy refuses or with credentials to another origin",
|
|
321
|
+
cross_origin: "it goes to another origin, and this read stays on one origin",
|
|
322
|
+
};
|
|
323
|
+
return {
|
|
324
|
+
code: REDIRECT_REFUSED_CODE,
|
|
325
|
+
message: `The server answered ${status === 0 ? "with a redirect" : status} (${where}); not followed: ${why[reason]}.`,
|
|
326
|
+
recommendation: reason === "downgrade" || reason === "insecure_http" ? "Serve the redirect target over https." : null,
|
|
327
|
+
context: { status, locationOrigin, reason },
|
|
328
|
+
status,
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
const FOLLOWED = new Set([301, 302, 303, 307, 308]);
|
|
333
|
+
|
|
334
|
+
/** The request a {@link fetchWithRedirectPolicy} hop sends. */
|
|
335
|
+
export type PolicyRequestInit = {
|
|
336
|
+
method: string;
|
|
337
|
+
headers: Record<string, string>;
|
|
338
|
+
body?: unknown;
|
|
339
|
+
signal?: AbortSignal | null | undefined;
|
|
340
|
+
[extra: string]: unknown;
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
/** Options for {@link fetchWithRedirectPolicy}. */
|
|
344
|
+
export type RedirectPolicyOptions = {
|
|
345
|
+
/** The effective opt-in for this client (already resolved). */
|
|
346
|
+
allowInsecureHttp: boolean;
|
|
347
|
+
/** Turns a refusal into the caller's error. Defaults to a plain `Error` carrying the fields. */
|
|
348
|
+
makeError?: ((refusal: RedirectRefusal) => Error) | undefined;
|
|
349
|
+
/** Defaults to {@link MAX_REDIRECTS}. */
|
|
350
|
+
maxRedirects?: number | undefined;
|
|
351
|
+
};
|
|
352
|
+
|
|
353
|
+
function defaultMakeError(r: RedirectRefusal): Error {
|
|
354
|
+
return Object.assign(new Error(r.message), r);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** A copy of `h` without the named headers (case-insensitive). Other names keep their case. */
|
|
358
|
+
function withoutHeaders(h: Record<string, string>, names: ReadonlyArray<string>): Record<string, string> {
|
|
359
|
+
const out: Record<string, string> = {};
|
|
360
|
+
for (const [k, v] of Object.entries(h)) if (!names.includes(k.toLowerCase())) out[k] = v;
|
|
361
|
+
return out;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Send a request and follow redirects under the policy, by hand (`redirect: "manual"`), so the runtime never forwards
|
|
366
|
+
* a header on its own. Per hop:
|
|
367
|
+
* - 301, 302, 303, 307, 308 with an http(s) `Location` are decided by {@link classifyRedirect}. A cross-origin hop
|
|
368
|
+
* keeps only {@link REDIRECT_KEEP_HEADERS}. 303 (and 301/302 after a POST) become a GET without a body; 307 and 308
|
|
369
|
+
* keep the method and body, and a hop that would send a body to another origin is refused.
|
|
370
|
+
* - 304 and every non-3xx response are returned as they are.
|
|
371
|
+
* - Any other 3xx, a missing or unusable `Location`, a loop, or more than `maxRedirects` hops is refused with
|
|
372
|
+
* {@link REDIRECT_REFUSED_CODE}, naming the status and the Location's origin only.
|
|
373
|
+
* - A browser hides a manual redirect (`opaqueredirect`). A GET or HEAD that carries no header outside the allow-list
|
|
374
|
+
* and no body is then sent again with the browser following, and its final URL is checked against the policy;
|
|
375
|
+
* anything else is refused.
|
|
376
|
+
* - A runtime that follows redirects itself despite `manual` (React Native) is caught after the fact from
|
|
377
|
+
* `response.redirected` and `response.url`: the answer is refused when the hop breaks the policy or took credentials
|
|
378
|
+
* to another origin. The request has then already been sent; only the answer is withheld.
|
|
379
|
+
*/
|
|
380
|
+
export async function fetchWithRedirectPolicy(
|
|
381
|
+
fetchImpl: typeof globalThis.fetch,
|
|
382
|
+
url: string,
|
|
383
|
+
init: PolicyRequestInit,
|
|
384
|
+
options: RedirectPolicyOptions,
|
|
385
|
+
): Promise<Response> {
|
|
386
|
+
const makeError = options.makeError ?? defaultMakeError;
|
|
387
|
+
const max = options.maxRedirects ?? MAX_REDIRECTS;
|
|
388
|
+
let current = url;
|
|
389
|
+
let method = init.method.toUpperCase();
|
|
390
|
+
let headers: Record<string, string> = { ...init.headers };
|
|
391
|
+
let body = init.body;
|
|
392
|
+
const visited = new Set<string>([current]);
|
|
393
|
+
for (let hop = 0; ; hop++) {
|
|
394
|
+
const reqInit: Record<string, unknown> = { ...init, method, headers, redirect: "manual" };
|
|
395
|
+
if (body === undefined) delete reqInit["body"];
|
|
396
|
+
else reqInit["body"] = body;
|
|
397
|
+
const res = await fetchImpl(current, reqInit as Parameters<typeof fetchImpl>[1]);
|
|
398
|
+
|
|
399
|
+
if (res.type === "opaqueredirect") {
|
|
400
|
+
const credentialFree = (method === "GET" || method === "HEAD") && body === undefined && Object.keys(headers).every((k) => !isCredentialHeader(k));
|
|
401
|
+
if (!credentialFree) throw makeError(redirectRefusal(0, null, "opaque"));
|
|
402
|
+
const followed = await fetchImpl(current, { ...reqInit, redirect: "follow" } as Parameters<typeof fetchImpl>[1]);
|
|
403
|
+
const finalUrl = typeof followed.url === "string" && followed.url !== "" ? followed.url : current;
|
|
404
|
+
if (classifyRedirect(current, finalUrl, options.allowInsecureHttp) === "refuse") {
|
|
405
|
+
throw makeError(redirectRefusal(followed.status, originOf(finalUrl, current), new URL(current).protocol === "https:" ? "downgrade" : "insecure_http"));
|
|
406
|
+
}
|
|
407
|
+
return followed;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
if (res.status < 300 || res.status > 399 || res.status === 304) {
|
|
411
|
+
// A runtime that ignores `redirect: "manual"` (React Native's fetch) follows on its own and reports where it ended.
|
|
412
|
+
// The hop has already happened, so this can only refuse the answer: a refused hop, or a cross-origin hop that took
|
|
413
|
+
// credentials with it, is an error rather than a response.
|
|
414
|
+
if (res.redirected === true && typeof res.url === "string" && res.url !== "" && res.url !== current) {
|
|
415
|
+
const decision = classifyRedirect(current, res.url, options.allowInsecureHttp);
|
|
416
|
+
const carried = Object.keys(headers).some((k) => isCredentialHeader(k)) || body !== undefined;
|
|
417
|
+
if (decision === "refuse" || (decision === "follow-drop-credentials" && carried)) {
|
|
418
|
+
throw makeError(redirectRefusal(0, originOf(res.url, current), "runtime_followed"));
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
return res;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
const location = res.headers.get("location");
|
|
425
|
+
if (!FOLLOWED.has(res.status)) {
|
|
426
|
+
throw makeError(redirectRefusal(res.status, location === null ? null : originOf(location, current), "not_a_redirect"));
|
|
427
|
+
}
|
|
428
|
+
if (location === null || location.trim() === "") throw makeError(redirectRefusal(res.status, null, "no_location"));
|
|
429
|
+
let next: URL;
|
|
430
|
+
try {
|
|
431
|
+
next = new URL(location, current);
|
|
432
|
+
} catch {
|
|
433
|
+
throw makeError(redirectRefusal(res.status, null, "bad_location"));
|
|
434
|
+
}
|
|
435
|
+
const nextOrigin = originOf(next.toString(), current);
|
|
436
|
+
const decision = classifyRedirect(current, next.toString(), options.allowInsecureHttp);
|
|
437
|
+
if (decision === "refuse") {
|
|
438
|
+
const badShape = (next.protocol !== "http:" && next.protocol !== "https:") || next.username !== "" || next.password !== "";
|
|
439
|
+
const reason: RedirectRefusalReason = badShape
|
|
440
|
+
? "bad_location"
|
|
441
|
+
: new URL(current).protocol === "https:"
|
|
442
|
+
? "downgrade"
|
|
443
|
+
: "insecure_http";
|
|
444
|
+
throw makeError(redirectRefusal(res.status, nextOrigin, reason));
|
|
445
|
+
}
|
|
446
|
+
if (hop + 1 > max) throw makeError(redirectRefusal(res.status, nextOrigin, "too_many"));
|
|
447
|
+
const nextUrl = next.toString();
|
|
448
|
+
if (visited.has(nextUrl)) throw makeError(redirectRefusal(res.status, nextOrigin, "loop"));
|
|
449
|
+
visited.add(nextUrl);
|
|
450
|
+
|
|
451
|
+
// Method and body, as fetch does: 303 → GET (HEAD stays HEAD); 301/302 after a POST → GET; 307/308 unchanged.
|
|
452
|
+
if ((res.status === 303 && method !== "HEAD") || ((res.status === 301 || res.status === 302) && method === "POST")) {
|
|
453
|
+
method = "GET";
|
|
454
|
+
body = undefined;
|
|
455
|
+
headers = withoutHeaders(headers, ["content-type", "content-length"]);
|
|
456
|
+
}
|
|
457
|
+
if (decision === "follow-drop-credentials") {
|
|
458
|
+
if (body !== undefined) throw makeError(redirectRefusal(res.status, nextOrigin, "body_cross_origin"));
|
|
459
|
+
headers = stripCredentialHeaders(headers);
|
|
460
|
+
}
|
|
461
|
+
// Drain the redirect's body so the connection can be reused; a failure here does not matter.
|
|
462
|
+
try {
|
|
463
|
+
await res.body?.cancel();
|
|
464
|
+
} catch {
|
|
465
|
+
/* ignore */
|
|
466
|
+
}
|
|
467
|
+
current = nextUrl;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Wrap a fetch so every hop of one read stays on `origin` (a signing-key set: keys read from another origin are not the
|
|
473
|
+
* keys asked for). Use it as the `fetchImpl` of {@link fetchWithRedirectPolicy}, which already refuses a downgrade and
|
|
474
|
+
* plain http off loopback. Per hop:
|
|
475
|
+
* - a request to another origin is never sent;
|
|
476
|
+
* - a 3xx whose `Location` names another origin is refused before it is followed;
|
|
477
|
+
* - an answer the runtime reached on its own (a browser's followed redirect, React Native's fetch) is refused when its
|
|
478
|
+
* `url` is another origin.
|
|
479
|
+
* A refusal is `makeError(redirectRefusal(status, locationOrigin, "cross_origin"))`.
|
|
480
|
+
*/
|
|
481
|
+
export function sameOriginOnlyFetch(
|
|
482
|
+
fetchImpl: typeof globalThis.fetch,
|
|
483
|
+
origin: string,
|
|
484
|
+
makeError: (refusal: RedirectRefusal) => Error = defaultMakeError,
|
|
485
|
+
): typeof globalThis.fetch {
|
|
486
|
+
const originOrNull = (u: string, base?: string): string | null => {
|
|
487
|
+
try {
|
|
488
|
+
return new URL(u, base).origin;
|
|
489
|
+
} catch {
|
|
490
|
+
return null;
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
return (async (input: Parameters<typeof globalThis.fetch>[0], init?: Parameters<typeof globalThis.fetch>[1]) => {
|
|
494
|
+
const target = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
495
|
+
const targetOrigin = originOrNull(target);
|
|
496
|
+
if (targetOrigin !== origin) throw makeError(redirectRefusal(0, targetOrigin, "cross_origin"));
|
|
497
|
+
const res = await fetchImpl(input, init);
|
|
498
|
+
if (res.status >= 300 && res.status <= 399 && res.status !== 304) {
|
|
499
|
+
const location = res.headers.get("location");
|
|
500
|
+
const next = location === null ? null : originOrNull(location, target);
|
|
501
|
+
if (next !== null && next !== origin) throw makeError(redirectRefusal(res.status, next, "cross_origin"));
|
|
502
|
+
}
|
|
503
|
+
if (typeof res.url === "string" && res.url !== "") {
|
|
504
|
+
const reached = originOrNull(res.url);
|
|
505
|
+
if (reached !== origin) throw makeError(redirectRefusal(0, reached, "cross_origin"));
|
|
506
|
+
}
|
|
507
|
+
return res;
|
|
508
|
+
}) as typeof globalThis.fetch;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Wrap a fetch so a route that answers only at its home region can be followed to that region, once, and nowhere else.
|
|
513
|
+
* Use it as the `fetchImpl` of {@link fetchWithRedirectPolicy}. It is for a route whose answer is a `308` to the home
|
|
514
|
+
* region's host (the request, with its body and its credential, must go there), where the general policy would drop the
|
|
515
|
+
* credential or refuse the body on a hop to another origin.
|
|
516
|
+
*
|
|
517
|
+
* Per call:
|
|
518
|
+
* - a `308` is followed exactly once, by this wrapper, with the same method, headers (the credential included) and body;
|
|
519
|
+
* - the target must be `https`, carry no userinfo, port or fragment, keep the request's path and query exactly, sit on a
|
|
520
|
+
* host other than the one asked, and be accepted by `isHomeHost(askedHostname, targetHostname)`, which the caller
|
|
521
|
+
* defines as "the same organization's gateway host family". Anything else is refused with the credential unsent;
|
|
522
|
+
* - any other redirect, a second `308`, and an opaque redirect are refused. The general policy never sees a redirect.
|
|
523
|
+
* A refusal names the target's origin only, never its path or query.
|
|
524
|
+
*/
|
|
525
|
+
export function homeRegionFetch(
|
|
526
|
+
fetchImpl: typeof globalThis.fetch,
|
|
527
|
+
isHomeHost: (askedHostname: string, targetHostname: string) => boolean,
|
|
528
|
+
makeError: (refusal: RedirectRefusal) => Error = defaultMakeError,
|
|
529
|
+
): typeof globalThis.fetch {
|
|
530
|
+
const refuse = (status: number, origin: string | null, reason: RedirectRefusalReason, why: string): Error => {
|
|
531
|
+
const r = redirectRefusal(status, origin, reason);
|
|
532
|
+
return makeError({ ...r, message: `The server answered ${status === 0 ? "with a redirect" : status} (${origin === null ? "no usable Location" : `Location ${origin}`}); not followed: ${why}.`, recommendation: null });
|
|
533
|
+
};
|
|
534
|
+
const target = (asked: string, location: string | null): { url: string } | { origin: string | null; why: string; reason: RedirectRefusalReason } => {
|
|
535
|
+
if (location === null || location.trim() === "") return { origin: null, why: "the response has no Location", reason: "no_location" };
|
|
536
|
+
let from: URL;
|
|
537
|
+
let to: URL;
|
|
538
|
+
try {
|
|
539
|
+
from = new URL(asked);
|
|
540
|
+
to = new URL(location, asked);
|
|
541
|
+
} catch {
|
|
542
|
+
return { origin: null, why: "the Location is not a URL", reason: "bad_location" };
|
|
543
|
+
}
|
|
544
|
+
const origin = to.protocol === "http:" || to.protocol === "https:" ? to.origin : to.protocol;
|
|
545
|
+
if (to.protocol !== "https:" || to.username !== "" || to.password !== "" || to.port !== "" || to.hash !== "") {
|
|
546
|
+
return { origin, why: "the target is not a plain https gateway host", reason: "bad_location" };
|
|
547
|
+
}
|
|
548
|
+
if (to.hostname === from.hostname || to.pathname + to.search !== from.pathname + from.search || !isHomeHost(from.hostname, to.hostname)) {
|
|
549
|
+
return { origin, why: "the target is not this organization's home-region gateway host for the same request", reason: "cross_origin" };
|
|
550
|
+
}
|
|
551
|
+
return { url: to.toString() };
|
|
552
|
+
};
|
|
553
|
+
let followed = false;
|
|
554
|
+
const wrapped = (async (input: Parameters<typeof globalThis.fetch>[0], init?: Parameters<typeof globalThis.fetch>[1]) => {
|
|
555
|
+
const asked = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
|
|
556
|
+
const res = await fetchImpl(input, init);
|
|
557
|
+
if (res.type === "opaqueredirect") throw refuse(0, null, "opaque", "this runtime hides the redirect from the client");
|
|
558
|
+
if (res.status < 300 || res.status > 399 || res.status === 304) return res;
|
|
559
|
+
const location = res.headers.get("location");
|
|
560
|
+
if (res.status !== 308 || followed) {
|
|
561
|
+
const o = (() => { try { return location === null ? null : new URL(location, asked).origin; } catch { return null; } })();
|
|
562
|
+
throw refuse(res.status, o, followed ? "too_many" : "not_a_redirect", followed ? "a second redirect is not followed" : "only the 308 to the home region is followed");
|
|
563
|
+
}
|
|
564
|
+
const t = target(asked, location);
|
|
565
|
+
if (!("url" in t)) throw refuse(308, t.origin, t.reason, t.why);
|
|
566
|
+
followed = true;
|
|
567
|
+
try {
|
|
568
|
+
await res.body?.cancel();
|
|
569
|
+
} catch {
|
|
570
|
+
/* ignore */
|
|
571
|
+
}
|
|
572
|
+
return wrapped(t.url, init);
|
|
573
|
+
}) as typeof globalThis.fetch;
|
|
574
|
+
return wrapped;
|
|
575
|
+
}
|