@steve31415/baselib 5.3.0 → 5.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/deploy/config.d.ts +4 -0
- package/dist/deploy/config.js +8 -0
- package/dist/deploy/deploy.js +10 -2
- package/dist/deploy/plan.d.ts +11 -0
- package/dist/deploy/plan.js +18 -0
- package/dist/fetch-guard.d.ts +50 -0
- package/dist/fetch-guard.js +215 -0
- package/package.json +5 -1
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@ What it provides and why: `docs/SPEC.md`. How it's put together:
|
|
|
7
7
|
|
|
8
8
|
Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`, `s2s`, `db`, `http`, `sync`,
|
|
9
9
|
`app-update`, `llm`, `email`, `twitter`, `hub` (the connection hub's server core, app notifier, per-request hint batch `HubHints` and daemon-token mint; `hub/testing` a local hub for tests), `hub-daemon` (the daemons' hub client), `code-manifest` and
|
|
10
|
-
`client-version`, `outside-bytes` (bytes an outsider chose, served by signed link) and `outside-text` (the marking helper for
|
|
10
|
+
`client-version`, `outside-bytes` (bytes an outsider chose, served by signed link), `fetch-guard` (the `fetch` for URLs an outsider can influence: public addresses only, every redirect hop re-checked) and `outside-text` (the marking helper for
|
|
11
11
|
text an outsider wrote on its way to a model; portable). Browser exports: `log-browser`, `rum`, `slow-fetch`, `sync-browser`, `app-update-browser`, and
|
|
12
12
|
`extension-self-update`.
|
|
13
13
|
|
package/dist/deploy/config.d.ts
CHANGED
|
@@ -3,6 +3,10 @@ export declare const DEFAULT_PROJECT = "plasticine-prod";
|
|
|
3
3
|
export declare const DEFAULT_ACCOUNT = "coding-agent@plasticine-prod.iam.gserviceaccount.com";
|
|
4
4
|
/** App and service names (also the database and log `app` values). */
|
|
5
5
|
export declare const NAME: RegExp;
|
|
6
|
+
/** The test-bypass switch (`config.ts` `authMode()`): no deployed service may
|
|
7
|
+
* carry it in any form, so the deploy refuses it wherever it can see it
|
|
8
|
+
* (W14 of the 2026-12-03 security review; since 5.4.0). */
|
|
9
|
+
export declare const TEST_BYPASS_VAR = "AUTH_MODE";
|
|
6
10
|
export declare function validateConfig(raw: unknown): DeployConfig;
|
|
7
11
|
export declare function loadConfig(repoRoot: string): Promise<DeployConfig>;
|
|
8
12
|
export declare function loadHooks(repoRoot: string, config: DeployConfig): Promise<DeployHooks>;
|
package/dist/deploy/config.js
CHANGED
|
@@ -8,6 +8,10 @@ export const DEFAULT_ACCOUNT = `coding-agent@${DEFAULT_PROJECT}.iam.gserviceacco
|
|
|
8
8
|
/** App and service names (also the database and log `app` values). */
|
|
9
9
|
export const NAME = /^[a-z][a-z0-9-]{1,30}$/;
|
|
10
10
|
const PREFIX = /^[a-z0-9][a-z0-9/_-]*\/$/;
|
|
11
|
+
/** The test-bypass switch (`config.ts` `authMode()`): no deployed service may
|
|
12
|
+
* carry it in any form, so the deploy refuses it wherever it can see it
|
|
13
|
+
* (W14 of the 2026-12-03 security review; since 5.4.0). */
|
|
14
|
+
export const TEST_BYPASS_VAR = 'AUTH_MODE';
|
|
11
15
|
function fail(detail) {
|
|
12
16
|
throw new Error(`deploy.config.json invalid: ${detail}`);
|
|
13
17
|
}
|
|
@@ -52,12 +56,16 @@ export function validateConfig(raw) {
|
|
|
52
56
|
c.services.forEach((s, i) => validateService(s, i));
|
|
53
57
|
if (c.updateSecrets) {
|
|
54
58
|
for (const [key, value] of Object.entries(c.updateSecrets)) {
|
|
59
|
+
if (key === TEST_BYPASS_VAR)
|
|
60
|
+
fail(`updateSecrets.${key} (the test bypass is never deployed)`);
|
|
55
61
|
if (!/^[A-Z0-9_]+$/.test(key) || !/^[a-z0-9-]+--[a-z0-9-]+:[0-9]+$/.test(value))
|
|
56
62
|
fail(`updateSecrets.${key} (want <secret-name>:<numeric version>)`);
|
|
57
63
|
}
|
|
58
64
|
}
|
|
59
65
|
if (c.updateEnv) {
|
|
60
66
|
for (const [key, value] of Object.entries(c.updateEnv)) {
|
|
67
|
+
if (key === TEST_BYPASS_VAR)
|
|
68
|
+
fail(`updateEnv.${key} (the test bypass is never deployed)`);
|
|
61
69
|
if (!/^[A-Z][A-Z0-9_]*$/.test(key) || key === 'BUILD_ID')
|
|
62
70
|
fail(`updateEnv.${key} (key)`);
|
|
63
71
|
if (typeof value !== 'string' || /[|\n]/.test(value))
|
package/dist/deploy/deploy.js
CHANGED
|
@@ -9,11 +9,11 @@ import { createHash } from 'node:crypto';
|
|
|
9
9
|
import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
|
|
10
10
|
import { hostname } from 'node:os';
|
|
11
11
|
import { join, resolve } from 'node:path';
|
|
12
|
-
import { DEFAULT_ACCOUNT, loadConfig, loadHooks } from './config.js';
|
|
12
|
+
import { DEFAULT_ACCOUNT, loadConfig, loadHooks, TEST_BYPASS_VAR } from './config.js';
|
|
13
13
|
import { CommandFailure, must, mustJson } from './exec.js';
|
|
14
14
|
import { openEvidence, PhaseTimer } from './evidence.js';
|
|
15
15
|
import { acquireLock, clearHold, publishRetainedAssets, readHold, readReleaseRecord, releaseLock, verifyLock, writeReleaseRecord, } from './gcs.js';
|
|
16
|
-
import { consistentBaseSha, readServingState, servingRevisionName, SHA40, strayTrafficPin } from './plan.js';
|
|
16
|
+
import { consistentBaseSha, dockerfileSetsTestBypass, readServingState, servingRevisionName, SHA40, strayTrafficPin, templateSetsTestBypass, } from './plan.js';
|
|
17
17
|
import { writeDeployMarker } from './deploy-marker.js';
|
|
18
18
|
const RELEASE_DEADLINE_MS = 25 * 60_000;
|
|
19
19
|
const IMAGE_DIGEST = /@sha256:[0-9a-f]{64}$/;
|
|
@@ -140,6 +140,11 @@ export async function runDeploy(options) {
|
|
|
140
140
|
await mkdir(join(options.repoRoot, '.deploy'), { recursive: true });
|
|
141
141
|
await writeFile(stampPath, `${lockHash}\n`);
|
|
142
142
|
}
|
|
143
|
+
// The test bypass is refused in deploy.config.json (validateConfig), in
|
|
144
|
+
// the image (here) and in each live service's template (below); the
|
|
145
|
+
// app's boot check (assertBootSafety) stays the last line (W14, 5.4.0).
|
|
146
|
+
if (dockerfileSetsTestBypass(await readFile(join(options.repoRoot, 'Dockerfile'), 'utf8')))
|
|
147
|
+
throw new Error(`the Dockerfile mentions ${TEST_BYPASS_VAR}, the test bypass; deployed images never set it`);
|
|
143
148
|
const holdUri = `gs://${config.bucket}/${config.app}/deploy.hold`;
|
|
144
149
|
const hold = await readHold(runner, holdUri);
|
|
145
150
|
if (hold && hold.heldShas.includes(sha) && !overrideHold) {
|
|
@@ -153,6 +158,9 @@ export async function runDeploy(options) {
|
|
|
153
158
|
await evidence.save(`${service.name}-before.json`, JSON.stringify(described, null, 2));
|
|
154
159
|
serving.push(state);
|
|
155
160
|
servingDescribed.push(described);
|
|
161
|
+
if (templateSetsTestBypass(described))
|
|
162
|
+
throw new Error(`${service.name}: the live service sets ${TEST_BYPASS_VAR}, the test bypass; remove it ` +
|
|
163
|
+
`(gcloud run services update ${service.name} --remove-env-vars=${TEST_BYPASS_VAR}) and find out who set it`);
|
|
156
164
|
}
|
|
157
165
|
const base = consistentBaseSha(serving, sha);
|
|
158
166
|
if (!base.ok)
|
package/dist/deploy/plan.d.ts
CHANGED
|
@@ -41,6 +41,17 @@ export declare function pickRevisionForSha(revisions: unknown[], targetSha: stri
|
|
|
41
41
|
revision: string;
|
|
42
42
|
imageDigest: string;
|
|
43
43
|
} | null;
|
|
44
|
+
/** Whether a `gcloud run services describe --format=json` template sets the
|
|
45
|
+
* test-bypass variable on any container, by value or from a secret. The
|
|
46
|
+
* template is what the deploy's `services update` builds the next revision
|
|
47
|
+
* from, and the update only adds variables, so a bypass set out of band
|
|
48
|
+
* would ride along into every later release. Since 5.4.0 (W14). */
|
|
49
|
+
export declare function templateSetsTestBypass(described: unknown): boolean;
|
|
50
|
+
/** Whether a Dockerfile mentions the test-bypass variable on any line that is
|
|
51
|
+
* not a comment (an `ENV`, an `ARG`, a continuation line of either). No
|
|
52
|
+
* fleet Dockerfile mentions it (checked 2026-12-04), so any mention is
|
|
53
|
+
* refused rather than parsed. Since 5.4.0 (W14). */
|
|
54
|
+
export declare function dockerfileSetsTestBypass(dockerfile: string): boolean;
|
|
44
55
|
/** The one revision carrying 100% of traffic in a `gcloud run services
|
|
45
56
|
* describe --format=json`, from *observed* traffic (`status.traffic`, never
|
|
46
57
|
* `spec.traffic`, which is only the desired state). */
|
package/dist/deploy/plan.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Pure decision logic for pw-deploy/pw-rollback: everything here is
|
|
2
2
|
// side-effect-free so the concurrency-sensitive choices (lock staleness,
|
|
3
3
|
// rollback targeting, serving-state consistency) are unit-tested directly.
|
|
4
|
+
import { TEST_BYPASS_VAR } from './config.js';
|
|
4
5
|
import { mustJson } from './exec.js';
|
|
5
6
|
export const SHA40 = /^[0-9a-f]{40}$/;
|
|
6
7
|
/** Lock staleness is judged from the GCS object's server-side timeCreated,
|
|
@@ -102,6 +103,23 @@ export function pickRevisionForSha(revisions, targetSha) {
|
|
|
102
103
|
matches.sort((a, b) => b.created - a.created);
|
|
103
104
|
return matches[0] ? { revision: matches[0].revision, imageDigest: matches[0].imageDigest } : null;
|
|
104
105
|
}
|
|
106
|
+
/** Whether a `gcloud run services describe --format=json` template sets the
|
|
107
|
+
* test-bypass variable on any container, by value or from a secret. The
|
|
108
|
+
* template is what the deploy's `services update` builds the next revision
|
|
109
|
+
* from, and the update only adds variables, so a bypass set out of band
|
|
110
|
+
* would ride along into every later release. Since 5.4.0 (W14). */
|
|
111
|
+
export function templateSetsTestBypass(described) {
|
|
112
|
+
const containers = described.spec?.template?.spec?.containers ?? [];
|
|
113
|
+
return containers.some((c) => (c.env ?? []).some((e) => e.name === TEST_BYPASS_VAR));
|
|
114
|
+
}
|
|
115
|
+
/** Whether a Dockerfile mentions the test-bypass variable on any line that is
|
|
116
|
+
* not a comment (an `ENV`, an `ARG`, a continuation line of either). No
|
|
117
|
+
* fleet Dockerfile mentions it (checked 2026-12-04), so any mention is
|
|
118
|
+
* refused rather than parsed. Since 5.4.0 (W14). */
|
|
119
|
+
export function dockerfileSetsTestBypass(dockerfile) {
|
|
120
|
+
const word = new RegExp(`\\b${TEST_BYPASS_VAR}\\b`);
|
|
121
|
+
return dockerfile.split('\n').some((line) => !/^\s*#/.test(line) && word.test(line));
|
|
122
|
+
}
|
|
105
123
|
/** The one revision carrying 100% of traffic in a `gcloud run services
|
|
106
124
|
* describe --format=json`, from *observed* traffic (`status.traffic`, never
|
|
107
125
|
* `spec.traffic`, which is only the desired state). */
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type LookupFunction } from 'node:net';
|
|
2
|
+
/**
|
|
3
|
+
* Thrown when a URL or a resolved address points somewhere the guard never
|
|
4
|
+
* lets a fetch reach. `target` is the host name or address refused.
|
|
5
|
+
*/
|
|
6
|
+
export declare class BlockedAddressError extends Error {
|
|
7
|
+
readonly target: string;
|
|
8
|
+
constructor(target: string);
|
|
9
|
+
}
|
|
10
|
+
/** True for an IP address the guard must not connect to; also true for
|
|
11
|
+
* anything that is not an IP address at all (refuse rather than guess). */
|
|
12
|
+
export declare function isBlockedAddress(address: string): boolean;
|
|
13
|
+
/**
|
|
14
|
+
* A `net` lookup that rejects blocked host names and fails the connection
|
|
15
|
+
* when any resolved address is blocked. It runs inside the connection's own
|
|
16
|
+
* DNS lookup, so a rebinding answer cannot slip past an earlier check.
|
|
17
|
+
* `resolve` is injectable for tests; it defaults to the system resolver.
|
|
18
|
+
*/
|
|
19
|
+
export declare function guardedLookup(resolve?: LookupFunction): LookupFunction;
|
|
20
|
+
export interface GuardedFetchOptions {
|
|
21
|
+
/** DNS resolver behind the guarded lookup (tests); default: the system's. */
|
|
22
|
+
resolve?: LookupFunction;
|
|
23
|
+
/** Redirect hops followed when the caller leaves `redirect` at `follow`
|
|
24
|
+
* (default 20, the Fetch standard's limit). */
|
|
25
|
+
maxRedirects?: number;
|
|
26
|
+
/** Tests only: the fetch each checked hop is sent through, with the
|
|
27
|
+
* guard's dispatcher in its init (default: the global fetch). Lets a test
|
|
28
|
+
* stand a local server in for a public host; the checks run regardless. */
|
|
29
|
+
transport?: typeof fetch;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A `fetch` that only reaches public http(s) addresses. Make one per process
|
|
33
|
+
* (each holds its own connection pool) or use `publicFetch`.
|
|
34
|
+
*
|
|
35
|
+
* With `redirect: 'follow'` (the default) it follows redirects itself,
|
|
36
|
+
* checking every hop, and applies the Fetch standard's rules: 303 (and 301
|
|
37
|
+
* or 302 after a POST) becomes a body-less GET; 307 and 308 resend the
|
|
38
|
+
* method and body; a cross-origin hop drops Authorization, Cookie and
|
|
39
|
+
* Proxy-Authorization. A streamed body cannot be resent, so a 307 or 308
|
|
40
|
+
* after one fails. The final response's `url` is the last hop's and its
|
|
41
|
+
* `redirected` is true. With `redirect: 'manual'` or `'error'` the caller
|
|
42
|
+
* sees the 3xx and fetches the next hop through this same function.
|
|
43
|
+
*
|
|
44
|
+
* A refusal rejects with `BlockedAddressError` (also when it happened at
|
|
45
|
+
* connect, which undici would otherwise wrap as "fetch failed"); a non-http
|
|
46
|
+
* protocol rejects with a TypeError.
|
|
47
|
+
*/
|
|
48
|
+
export declare function guardedFetch(options?: GuardedFetchOptions): typeof fetch;
|
|
49
|
+
/** The process-wide guarded fetch (`guardedFetch()` with the defaults). */
|
|
50
|
+
export declare const publicFetch: typeof fetch;
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
// The fetch guard: a `fetch` for URLs an outsider can influence (a feed, a
|
|
2
|
+
// page, a link in a message, an unsubscribe target). It reaches only public
|
|
3
|
+
// http(s) addresses: never loopback, a private or link-local range (which
|
|
4
|
+
// holds Cloud Run's metadata server), CGNAT, multicast or a reserved range,
|
|
5
|
+
// on the first request or on any redirect hop. Lifted from Corpus's
|
|
6
|
+
// `sources/network.ts` (2026-10-15) by the 2026-12-03 security review (W4);
|
|
7
|
+
// since 5.4.0. The rule that server-side fetches of outsider-influenced URLs
|
|
8
|
+
// go through it is in plasticine-way docs/SECURITY.md.
|
|
9
|
+
//
|
|
10
|
+
// How it holds:
|
|
11
|
+
// - Host names are checked inside the connection's own DNS lookup
|
|
12
|
+
// (`guardedLookup`), on every address the answer holds, so a rebinding
|
|
13
|
+
// answer (public at a pre-check, private at connect) cannot slip past.
|
|
14
|
+
// - Node's connect skips the lookup for IP-literal hosts (verified 2026-10-15
|
|
15
|
+
// against undici 7.30 and 2026-12-04 against Node 22's own undici 6), so
|
|
16
|
+
// literals (every spelling the URL parser accepts) are checked before the
|
|
17
|
+
// request.
|
|
18
|
+
// - Redirects are followed here, one hop at a time, so each hop's URL takes
|
|
19
|
+
// both checks again. Automatic following inside undici would connect to a
|
|
20
|
+
// literal redirect target without the lookup.
|
|
21
|
+
import { lookup as dnsLookup } from 'node:dns';
|
|
22
|
+
import { BlockList, isIP } from 'node:net';
|
|
23
|
+
import { Agent } from 'undici';
|
|
24
|
+
/**
|
|
25
|
+
* Thrown when a URL or a resolved address points somewhere the guard never
|
|
26
|
+
* lets a fetch reach. `target` is the host name or address refused.
|
|
27
|
+
*/
|
|
28
|
+
export class BlockedAddressError extends Error {
|
|
29
|
+
target;
|
|
30
|
+
constructor(target) {
|
|
31
|
+
super(`Blocked address: ${target}`);
|
|
32
|
+
this.target = target;
|
|
33
|
+
this.name = 'BlockedAddressError';
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// Separate lists: a BlockList checks IPv4 addresses against IPv6 rules too
|
|
37
|
+
// (via the mapped form), so one shared list would let ::ffff:0:0/96 block all
|
|
38
|
+
// of IPv4. Mapped IPv6 addresses are unwrapped and checked as IPv4 instead.
|
|
39
|
+
const blockedV4 = new BlockList();
|
|
40
|
+
for (const [network, prefix] of [
|
|
41
|
+
['0.0.0.0', 8], // "this network", including the unspecified address
|
|
42
|
+
['10.0.0.0', 8], // RFC 1918
|
|
43
|
+
['100.64.0.0', 10], // CGNAT
|
|
44
|
+
['127.0.0.0', 8], // loopback
|
|
45
|
+
['169.254.0.0', 16], // link-local, including the metadata server
|
|
46
|
+
['172.16.0.0', 12], // RFC 1918
|
|
47
|
+
['192.168.0.0', 16], // RFC 1918
|
|
48
|
+
['224.0.0.0', 4], // multicast
|
|
49
|
+
['240.0.0.0', 4], // reserved, including broadcast
|
|
50
|
+
])
|
|
51
|
+
blockedV4.addSubnet(network, prefix, 'ipv4');
|
|
52
|
+
const blockedV6 = new BlockList();
|
|
53
|
+
for (const [network, prefix] of [
|
|
54
|
+
// Unspecified, loopback and the deprecated IPv4-compatible forms (::a.b.c.d).
|
|
55
|
+
['::', 96],
|
|
56
|
+
['64:ff9b::', 96], // NAT64: embeds an IPv4 address we cannot vet
|
|
57
|
+
['fc00::', 7], // unique local
|
|
58
|
+
['fe80::', 10], // link-local
|
|
59
|
+
['ff00::', 8], // multicast
|
|
60
|
+
])
|
|
61
|
+
blockedV6.addSubnet(network, prefix, 'ipv6');
|
|
62
|
+
const blockedHostnames = new Set(['metadata.google.internal', 'metadata']);
|
|
63
|
+
/** True for an IP address the guard must not connect to; also true for
|
|
64
|
+
* anything that is not an IP address at all (refuse rather than guess). */
|
|
65
|
+
export function isBlockedAddress(address) {
|
|
66
|
+
const bare = address.split('%')[0]; // drop an IPv6 zone id
|
|
67
|
+
const family = isIP(bare);
|
|
68
|
+
if (family === 4)
|
|
69
|
+
return blockedV4.check(bare, 'ipv4');
|
|
70
|
+
if (family !== 6)
|
|
71
|
+
return true;
|
|
72
|
+
// The URL parser canonicalizes every spelling of an IPv4-mapped address
|
|
73
|
+
// (::ffff:127.0.0.1, ::FFFF:7f00:0001, …) to ::ffff:hhhh:hhhh.
|
|
74
|
+
const canonical = new URL(`http://[${bare}]/`).hostname.slice(1, -1);
|
|
75
|
+
const mapped = /^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/.exec(canonical);
|
|
76
|
+
if (mapped) {
|
|
77
|
+
const [high, low] = [parseInt(mapped[1], 16), parseInt(mapped[2], 16)];
|
|
78
|
+
return isBlockedAddress([high >> 8, high & 255, low >> 8, low & 255].join('.'));
|
|
79
|
+
}
|
|
80
|
+
return blockedV6.check(bare, 'ipv6');
|
|
81
|
+
}
|
|
82
|
+
function isBlockedHostname(hostname) {
|
|
83
|
+
return blockedHostnames.has(hostname.toLowerCase().replace(/\.$/, ''));
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* A `net` lookup that rejects blocked host names and fails the connection
|
|
87
|
+
* when any resolved address is blocked. It runs inside the connection's own
|
|
88
|
+
* DNS lookup, so a rebinding answer cannot slip past an earlier check.
|
|
89
|
+
* `resolve` is injectable for tests; it defaults to the system resolver.
|
|
90
|
+
*/
|
|
91
|
+
export function guardedLookup(resolve = dnsLookup) {
|
|
92
|
+
return (hostname, options, callback) => {
|
|
93
|
+
if (isBlockedHostname(hostname))
|
|
94
|
+
return callback(new BlockedAddressError(hostname), '', 0);
|
|
95
|
+
resolve(hostname, options, (error, address, family) => {
|
|
96
|
+
if (error)
|
|
97
|
+
return callback(error, address, family);
|
|
98
|
+
const addresses = Array.isArray(address) ? address.map((entry) => entry.address) : [address];
|
|
99
|
+
const bad = addresses.find(isBlockedAddress);
|
|
100
|
+
if (bad !== undefined || addresses.length === 0)
|
|
101
|
+
return callback(new BlockedAddressError(bad ?? hostname), '', 0);
|
|
102
|
+
callback(null, address, family);
|
|
103
|
+
});
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** Refuses a URL the guard never fetches: a protocol other than http(s), a
|
|
107
|
+
* blocked host name, or a blocked IP literal. */
|
|
108
|
+
function checkUrl(url) {
|
|
109
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
110
|
+
throw new TypeError(`Unsupported protocol: ${url.protocol}`);
|
|
111
|
+
const host = url.hostname.replace(/^\[(.*)\]$/, '$1');
|
|
112
|
+
if (isBlockedHostname(host) || (isIP(host) && isBlockedAddress(host)))
|
|
113
|
+
throw new BlockedAddressError(host);
|
|
114
|
+
}
|
|
115
|
+
function blockedCause(error) {
|
|
116
|
+
for (let e = error, depth = 0; e instanceof Error && depth < 5; depth++) {
|
|
117
|
+
if (e instanceof BlockedAddressError)
|
|
118
|
+
return e;
|
|
119
|
+
e = e.cause;
|
|
120
|
+
}
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
const REDIRECTS = new Set([301, 302, 303, 307, 308]);
|
|
124
|
+
/** Headers a cross-origin redirect drops, as undici's own following does. */
|
|
125
|
+
const CREDENTIAL_HEADERS = ['authorization', 'cookie', 'proxy-authorization'];
|
|
126
|
+
/** Headers that describe a body, dropped when a redirect turns the request into a GET. */
|
|
127
|
+
const BODY_HEADERS = ['content-type', 'content-length', 'content-encoding', 'content-language', 'content-location'];
|
|
128
|
+
/**
|
|
129
|
+
* A `fetch` that only reaches public http(s) addresses. Make one per process
|
|
130
|
+
* (each holds its own connection pool) or use `publicFetch`.
|
|
131
|
+
*
|
|
132
|
+
* With `redirect: 'follow'` (the default) it follows redirects itself,
|
|
133
|
+
* checking every hop, and applies the Fetch standard's rules: 303 (and 301
|
|
134
|
+
* or 302 after a POST) becomes a body-less GET; 307 and 308 resend the
|
|
135
|
+
* method and body; a cross-origin hop drops Authorization, Cookie and
|
|
136
|
+
* Proxy-Authorization. A streamed body cannot be resent, so a 307 or 308
|
|
137
|
+
* after one fails. The final response's `url` is the last hop's and its
|
|
138
|
+
* `redirected` is true. With `redirect: 'manual'` or `'error'` the caller
|
|
139
|
+
* sees the 3xx and fetches the next hop through this same function.
|
|
140
|
+
*
|
|
141
|
+
* A refusal rejects with `BlockedAddressError` (also when it happened at
|
|
142
|
+
* connect, which undici would otherwise wrap as "fetch failed"); a non-http
|
|
143
|
+
* protocol rejects with a TypeError.
|
|
144
|
+
*/
|
|
145
|
+
export function guardedFetch(options = {}) {
|
|
146
|
+
const dispatcher = new Agent({ connect: { lookup: guardedLookup(options.resolve) } });
|
|
147
|
+
const maxRedirects = options.maxRedirects ?? 20;
|
|
148
|
+
const transport = options.transport ?? fetch;
|
|
149
|
+
async function once(input, init) {
|
|
150
|
+
checkUrl(new URL(input instanceof Request ? input.url : input));
|
|
151
|
+
try {
|
|
152
|
+
// `dispatcher` is Node's (undici's) extension of RequestInit, absent from the DOM type.
|
|
153
|
+
return await transport(input, { ...init, dispatcher });
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
throw blockedCause(error) ?? error;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
return async (input, init) => {
|
|
160
|
+
const mode = init?.redirect ?? (input instanceof Request ? input.redirect : 'follow');
|
|
161
|
+
if (mode !== 'follow')
|
|
162
|
+
return once(input, init);
|
|
163
|
+
// Follow by hand. A Request input is flattened into a URL and an init
|
|
164
|
+
// (its body buffered) so that each hop can be rebuilt.
|
|
165
|
+
let url;
|
|
166
|
+
let method;
|
|
167
|
+
let headers;
|
|
168
|
+
let body;
|
|
169
|
+
if (input instanceof Request) {
|
|
170
|
+
url = new URL(input.url);
|
|
171
|
+
method = init?.method ?? input.method;
|
|
172
|
+
headers = new Headers(init?.headers ?? input.headers);
|
|
173
|
+
body = init?.body !== undefined ? init.body : input.body ? await input.arrayBuffer() : undefined;
|
|
174
|
+
init = { signal: input.signal, ...init };
|
|
175
|
+
}
|
|
176
|
+
else {
|
|
177
|
+
url = new URL(input);
|
|
178
|
+
method = init?.method ?? 'GET';
|
|
179
|
+
headers = new Headers(init?.headers);
|
|
180
|
+
body = init?.body;
|
|
181
|
+
}
|
|
182
|
+
for (let hop = 0;; hop++) {
|
|
183
|
+
const response = await once(url, { ...init, method, headers, body, redirect: 'manual' });
|
|
184
|
+
const location = response.headers.get('location');
|
|
185
|
+
if (!REDIRECTS.has(response.status) || location === null) {
|
|
186
|
+
if (hop > 0)
|
|
187
|
+
Object.defineProperty(response, 'redirected', { value: true });
|
|
188
|
+
return response;
|
|
189
|
+
}
|
|
190
|
+
await response.body?.cancel().catch(() => { });
|
|
191
|
+
if (hop >= maxRedirects)
|
|
192
|
+
throw new TypeError(`Too many redirects (more than ${maxRedirects})`);
|
|
193
|
+
const next = new URL(location, url);
|
|
194
|
+
if (response.status === 303 ? method.toUpperCase() !== 'HEAD' : [301, 302].includes(response.status) && method.toUpperCase() === 'POST') {
|
|
195
|
+
method = 'GET';
|
|
196
|
+
body = undefined;
|
|
197
|
+
for (const name of BODY_HEADERS)
|
|
198
|
+
headers.delete(name);
|
|
199
|
+
}
|
|
200
|
+
else if (body instanceof ReadableStream) {
|
|
201
|
+
throw new TypeError(`Cannot resend a streamed body across a ${response.status} redirect`);
|
|
202
|
+
}
|
|
203
|
+
if (next.origin !== url.origin)
|
|
204
|
+
for (const name of CREDENTIAL_HEADERS)
|
|
205
|
+
headers.delete(name);
|
|
206
|
+
url = next;
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
let shared;
|
|
211
|
+
/** The process-wide guarded fetch (`guardedFetch()` with the defaults). */
|
|
212
|
+
export const publicFetch = (input, init) => {
|
|
213
|
+
shared ??= guardedFetch();
|
|
214
|
+
return shared(input, init);
|
|
215
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@steve31415/baselib",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.4.0",
|
|
4
4
|
"description": "Plasticine new-world shared platform library: logging, auth, service-to-service auth, db, HTTP, sync, app updates",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -57,6 +57,10 @@
|
|
|
57
57
|
"types": "./dist/outside-bytes.d.ts",
|
|
58
58
|
"default": "./dist/outside-bytes.js"
|
|
59
59
|
},
|
|
60
|
+
"./fetch-guard": {
|
|
61
|
+
"types": "./dist/fetch-guard.d.ts",
|
|
62
|
+
"default": "./dist/fetch-guard.js"
|
|
63
|
+
},
|
|
60
64
|
"./outside-text": {
|
|
61
65
|
"types": "./dist/outside-text.d.ts",
|
|
62
66
|
"default": "./dist/outside-text.js"
|