@steve31415/baselib 5.3.0 → 5.5.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 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/auth.js CHANGED
@@ -125,7 +125,7 @@ export function requireIdentity(opts) {
125
125
  // working as designed (an s2s grant denial is ERROR because it usually
126
126
  // means a missing grant during development).
127
127
  const accessDenied = (c, user) => {
128
- opts.logger?.warn('user access denied', { email: user.email, policy, path: c.req.path });
128
+ opts.logger?.warn('user access denied', { email: user.email, policy, path: truncate(c.req.path, 200) });
129
129
  c.header('cache-control', 'no-store');
130
130
  if (isApi(c)) {
131
131
  return c.json({ error: 'not enabled for this account', code: ACCESS_DENIED_CODE, email: user.email }, 403);
package/dist/connector.js CHANGED
@@ -21,7 +21,7 @@ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/
21
21
  import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
22
22
  import { createMiddleware } from 'hono/factory';
23
23
  import { ACCESS_DENIED_CODE, parseFullRole, userAllowed } from './auth.js';
24
- import { serializeError } from './log-core.js';
24
+ import { serializeError, truncate } from './log-core.js';
25
25
  import { cleanOutsideText, markOutsideText } from './outside-text.js';
26
26
  import { insufficientScope } from './oauth-resource.js';
27
27
  import { RateLimiter, resolveS2sCaller } from './s2s.js';
@@ -89,7 +89,7 @@ export function requireForwardedConnectorUser(opts) {
89
89
  if (!user) {
90
90
  opts.logger?.warn('connector identity headers missing or malformed', {
91
91
  caller: resolved.caller.email,
92
- path: c.req.path,
92
+ path: truncate(c.req.path, 200),
93
93
  });
94
94
  return c.json({ error: 'connector identity headers missing' }, 400);
95
95
  }
@@ -97,7 +97,7 @@ export function requireForwardedConnectorUser(opts) {
97
97
  opts.logger?.warn('connector user access denied', {
98
98
  email: user.email,
99
99
  policy: opts.userAccess,
100
- path: c.req.path,
100
+ path: truncate(c.req.path, 200),
101
101
  });
102
102
  return c.json({ error: 'not enabled for this account', code: ACCESS_DENIED_CODE, email: user.email }, 403);
103
103
  }
@@ -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>;
@@ -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))
@@ -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)
@@ -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). */
@@ -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/dist/http.js CHANGED
@@ -21,7 +21,7 @@ export function requestLogging(logger, options = {}) {
21
21
  await next();
22
22
  const identity = c.var.identity;
23
23
  const extra = Object.entries(options.meta?.(c) ?? {}).filter(([, value]) => value !== undefined);
24
- logger.info(`${c.req.method} ${c.req.path} ${c.res.status}`, {
24
+ logger.info(`${c.req.method} ${truncate(c.req.path, 200)} ${c.res.status}`, {
25
25
  method: c.req.method,
26
26
  path: truncate(c.req.path, 200),
27
27
  status: c.res.status,
@@ -63,10 +63,11 @@ export function addHealth(app) {
63
63
  * has it). */
64
64
  export function errorHandler(logger) {
65
65
  return (err, c) => {
66
- logger.error(`unhandled error in ${c.req.method} ${c.req.path}`, {
66
+ const path = truncate(c.req.path, 200);
67
+ logger.error(`unhandled error in ${c.req.method} ${path}`, {
67
68
  error: err,
68
69
  method: c.req.method,
69
- path: c.req.path,
70
+ path,
70
71
  });
71
72
  const wantsJson = c.req.path.startsWith('/api/') || (c.req.header('accept') ?? '').includes('application/json');
72
73
  return wantsJson ? c.json({ error: 'internal error' }, 500) : c.text('Internal error', 500);
@@ -1,6 +1,6 @@
1
1
  import type { Context } from 'hono';
2
2
  import type { FullRole, UserAccessPolicy } from './auth.js';
3
- import type { Logger } from './log-core.js';
3
+ import { type Logger } from './log-core.js';
4
4
  import { serviceFetch } from './s2s.js';
5
5
  /** The exact shape of an access token: the prefix plus 32 random bytes in
6
6
  * base64url. Anything else is refused before any cache or network work. */
@@ -31,6 +31,7 @@ import { createHash } from 'node:crypto';
31
31
  import { createMiddleware } from 'hono/factory';
32
32
  import { ACCESS_DENIED_CODE, DEFAULT_AUTH_URL, parseFullRole, userAllowed } from './auth.js';
33
33
  import { authMode } from './config.js';
34
+ import { truncate } from './log-core.js';
34
35
  import { forwardedClientIp } from './http.js';
35
36
  import { RateLimiter, serviceFetch } from './s2s.js';
36
37
  /** The exact shape of an access token: the prefix plus 32 random bytes in
@@ -150,13 +151,13 @@ export function requireConnectorUser(opts) {
150
151
  opts.logger?.warn('connector user access denied', {
151
152
  email: user.email,
152
153
  policy,
153
- path: c.req.path,
154
+ path: truncate(c.req.path, 200),
154
155
  });
155
156
  c.header('cache-control', 'no-store');
156
157
  return c.json({ error: 'not enabled for this account', code: ACCESS_DENIED_CODE, email: user.email }, 403);
157
158
  }
158
159
  if (!limiter.allow(user.email)) {
159
- opts.logger?.warn('connector rate limit exceeded', { email: user.email, path: c.req.path });
160
+ opts.logger?.warn('connector rate limit exceeded', { email: user.email, path: truncate(c.req.path, 200) });
160
161
  return rateLimited(c);
161
162
  }
162
163
  // A copy per request: the cached identity is shared, and a Set typed
@@ -202,7 +203,7 @@ export function requireConnectorUser(opts) {
202
203
  // concurrent junk cannot overshoot it. Over budget is a 429, never a 401:
203
204
  // a client holding a good token must not be told to discard it.
204
205
  if (!sourceBudget.allow(forwardedClientIp(c, resourceHost))) {
205
- opts.logger?.warn('connector introspection budget exhausted', { path: c.req.path });
206
+ opts.logger?.warn('connector introspection budget exhausted', { path: truncate(c.req.path, 200) });
206
207
  return rateLimited(c);
207
208
  }
208
209
  let res;
package/dist/s2s.js CHANGED
@@ -116,6 +116,8 @@ export function redactToken(message, token) {
116
116
  * Shared by s2sAuth() and auth.ts's requireIdentity(). */
117
117
  export async function resolveS2sCaller(opts, headers, method, path) {
118
118
  let email;
119
+ // The request's path is the caller's text: bounded in every log line.
120
+ const logPath = truncate(path, 200);
119
121
  if (authMode() === 'test') {
120
122
  email = headers.testCaller;
121
123
  if (!email)
@@ -128,7 +130,7 @@ export async function resolveS2sCaller(opts, headers, method, path) {
128
130
  if (CONNECTOR_TOKEN.test(m[1])) {
129
131
  // A connector token on a route that takes service callers: refused here
130
132
  // so it never reaches the verifier, whose errors quote the token.
131
- opts.logger?.warn('connector token presented on a service route', { path });
133
+ opts.logger?.warn('connector token presented on a service route', { path: logPath });
132
134
  return { failure: { status: 401, error: 'invalid token' } };
133
135
  }
134
136
  try {
@@ -147,7 +149,7 @@ export async function resolveS2sCaller(opts, headers, method, path) {
147
149
  // redacted message only (PW LESSONS 2026-09-02 — log the shape, never
148
150
  // the credential). Found by Mirror's device-key design review.
149
151
  opts.logger?.warn('s2s token verification failed', {
150
- path,
152
+ path: logPath,
151
153
  reason: redactToken(err instanceof Error ? err.message : String(err), m[1]),
152
154
  tokenLength: m[1].length,
153
155
  tokenHashPrefix: createHash('sha256').update(m[1]).digest('hex').slice(0, 8),
@@ -156,13 +158,13 @@ export async function resolveS2sCaller(opts, headers, method, path) {
156
158
  }
157
159
  }
158
160
  if (!opts.limiter.allow(email)) {
159
- opts.logger?.warn('s2s rate limit exceeded', { caller: email, path });
161
+ opts.logger?.warn('s2s rate limit exceeded', { caller: email, path: logPath });
160
162
  return { failure: { status: 429, error: 'rate limit exceeded' } };
161
163
  }
162
164
  if (!grantAllows(opts.grants, email, method, path)) {
163
165
  // ERROR by policy: a denied identity is either an attack or a missing
164
166
  // grant during development — both deserve attention.
165
- opts.logger?.error('s2s call denied by grants', { caller: email, method, path });
167
+ opts.logger?.error('s2s call denied by grants', { caller: email, method, path: logPath });
166
168
  return { failure: { status: 403, error: `${email} is not granted ${method} ${path}` } };
167
169
  }
168
170
  return { caller: { type: 's2s', email } };
@@ -57,7 +57,7 @@ function withAgeCap(events, path, maxAgeMs, graceMs, logger) {
57
57
  if (cutAt === null || logged)
58
58
  return;
59
59
  logged = true;
60
- logger.info('socket age cap', { path, ageMs: Math.round(cutAt - openedAt), terminated });
60
+ logger.info('socket age cap', { path: truncate(path, 200), ageMs: Math.round(cutAt - openedAt), terminated });
61
61
  };
62
62
  const cut = (ws) => {
63
63
  ageTimer = null;
@@ -28,8 +28,10 @@ export interface SyncEventsRequestOptions<C extends EventBody, S extends EventBo
28
28
  * (`applied` + committed events, `duplicate` + the stored event, `rejected`
29
29
  * + error) and a contiguous catch-up from `lastSeq`, read after the commits:
30
30
  * `events` + `currentSeq`, or `reload: true` when too far behind. Throws
31
- * `SyncError('bad_request')` for a malformed batch (answer 400), and
32
- * `SyncUnavailableError` when the database fails (answer 5xx; the client
33
- * retries, and what committed before the failure comes back as duplicates).
34
- * Events committed before such a failure still get `afterCommit`. */
31
+ * `SyncError('bad_request')` for a malformed batch (answer 400; a
32
+ * `clientGuid` over 128 characters included). An event whose `eventGuid` is
33
+ * not a canonical UUID is `rejected` / `invalid_payload` without reaching
34
+ * the engine. Throws `SyncUnavailableError` when the database fails (answer
35
+ * 5xx; the client retries, and what committed before the failure comes
36
+ * back as duplicates). Events committed before such a failure still get `afterCommit`. */
35
37
  export declare function handleSyncEventsRequest<C extends EventBody, S extends EventBody>(options: SyncEventsRequestOptions<C, S>): Promise<HttpEventsResponse<S>>;
@@ -8,6 +8,14 @@ function eventGuid(value) {
8
8
  const candidate = record(value);
9
9
  return typeof candidate?.eventGuid === 'string' ? candidate.eventGuid : '';
10
10
  }
11
+ /** A canonical UUID of any version (the fleet's clients send v4 and v7),
12
+ * either case: the shape of the `uuid` column the default schema stores
13
+ * GUIDs in. Anything else would reach the engine's duplicate check and fail
14
+ * there as a Postgres data exception, logged with the client's text. */
15
+ const CANONICAL_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
16
+ /** The longest `clientGuid` a batch may carry (the fleet sends a 36-character
17
+ * UUID); it is stored with every event of the batch. */
18
+ const MAX_CLIENT_GUID_LENGTH = 128;
11
19
  function parserError(error) {
12
20
  return error instanceof SyncError
13
21
  ? { code: error.code, message: error.message }
@@ -21,10 +29,12 @@ function parserError(error) {
21
29
  * (`applied` + committed events, `duplicate` + the stored event, `rejected`
22
30
  * + error) and a contiguous catch-up from `lastSeq`, read after the commits:
23
31
  * `events` + `currentSeq`, or `reload: true` when too far behind. Throws
24
- * `SyncError('bad_request')` for a malformed batch (answer 400), and
25
- * `SyncUnavailableError` when the database fails (answer 5xx; the client
26
- * retries, and what committed before the failure comes back as duplicates).
27
- * Events committed before such a failure still get `afterCommit`. */
32
+ * `SyncError('bad_request')` for a malformed batch (answer 400; a
33
+ * `clientGuid` over 128 characters included). An event whose `eventGuid` is
34
+ * not a canonical UUID is `rejected` / `invalid_payload` without reaching
35
+ * the engine. Throws `SyncUnavailableError` when the database fails (answer
36
+ * 5xx; the client retries, and what committed before the failure comes
37
+ * back as duplicates). Events committed before such a failure still get `afterCommit`. */
28
38
  export async function handleSyncEventsRequest(options) {
29
39
  const batch = parseBatch(options.body);
30
40
  const committed = { applied: [], duplicates: [] };
@@ -57,6 +67,7 @@ function parseBatch(request) {
57
67
  if (!envelope ||
58
68
  typeof envelope.clientGuid !== 'string' ||
59
69
  envelope.clientGuid.length === 0 ||
70
+ envelope.clientGuid.length > MAX_CLIENT_GUID_LENGTH ||
60
71
  !Array.isArray(envelope.events)) {
61
72
  throw new SyncError('bad_request', 'invalid event batch');
62
73
  }
@@ -83,6 +94,14 @@ async function applyBatch(engine, scopeKey, batch, parseClientEvent, committed)
83
94
  outcomes.push({ eventGuid: guid, status: 'rejected', error: parserError(error) });
84
95
  continue;
85
96
  }
97
+ if (!CANONICAL_UUID.test(event.eventGuid)) {
98
+ outcomes.push({
99
+ eventGuid: event.eventGuid,
100
+ status: 'rejected',
101
+ error: { code: 'invalid_payload', message: 'eventGuid must be a UUID' },
102
+ });
103
+ continue;
104
+ }
86
105
  const outcome = await engine.apply(scopeKey, batch.clientGuid, event);
87
106
  if (outcome.kind === 'rejected') {
88
107
  outcomes.push({ eventGuid: event.eventGuid, status: 'rejected', error: outcome.error });
@@ -2,6 +2,10 @@ export interface EventBody<TType extends string = string, TPayload = unknown> {
2
2
  type: TType;
3
3
  payload: TPayload;
4
4
  }
5
+ /** `eventGuid` is the event's idempotency key: a canonical UUID of any
6
+ * version (36 characters, 8-4-4-4-12 hex digits, either case), as the
7
+ * default schema's `uuid` column stores it. `handleSyncEventsRequest`
8
+ * rejects any other shape as `invalid_payload` before the engine runs. */
5
9
  export type ClientEvent<TBody extends EventBody> = {
6
10
  eventGuid: string;
7
11
  } & TBody;
@@ -27,6 +31,9 @@ export declare class SyncUnavailableError extends Error {
27
31
  constructor(cause: unknown);
28
32
  }
29
33
  export interface HttpEventsRequest<T extends EventBody> {
34
+ /** The sending tab's identity (the fleet sends a UUID), stored with every
35
+ * event it triggers: 1 to 128 characters, or the whole batch is refused
36
+ * as `bad_request`. */
30
37
  clientGuid: string;
31
38
  events: ClientEvent<T>[];
32
39
  /** The tab's current sequence (every `SyncClient` POST). A request that
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "5.3.0",
3
+ "version": "5.5.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"