@steve31415/baselib 3.67.0 → 3.69.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/dist/auth.d.ts CHANGED
@@ -3,11 +3,17 @@ import { type Logger } from './log-core.js';
3
3
  import { ServiceCaller, S2sOptions } from './s2s.js';
4
4
  export declare const DEFAULT_AUTH_URL = "https://auth.apps.snewman.net";
5
5
  export declare const SESSION_COOKIE = "pw_session";
6
+ /** The cookie of a guest session. Only a `guestAccess` mount ever reads it. */
7
+ export declare const GUEST_COOKIE = "pw_guest";
6
8
  /** The `code` in a 403 JSON body when a signed-in user is refused by the
7
9
  * app's userAccess policy (as opposed to any other 403). */
8
10
  export declare const ACCESS_DENIED_CODE = "app_access_denied";
9
- /** A user's fleet role, assigned in auth's users table. */
10
- export type UserRole = 'owner' | 'invited';
11
+ /** A user's fleet role, assigned in auth's users table. A 'guest' is not a
12
+ * fleet user: an app that admits guests vouched for them at sign-in, and
13
+ * only a `guestAccess` mount ever yields one. */
14
+ export type UserRole = 'owner' | 'invited' | 'guest';
15
+ /** The roles a full (fleet) session can carry: every role but 'guest'. */
16
+ export type FullRole = Exclude<UserRole, 'guest'>;
11
17
  /** Which signed-in users an app admits. 'owner' (the default): only the
12
18
  * fleet owner(s). 'invited': any active fleet user. */
13
19
  export type UserAccessPolicy = 'owner' | 'invited';
@@ -17,6 +23,10 @@ export interface AuthedUser {
17
23
  name?: string;
18
24
  userId?: string;
19
25
  role: UserRole;
26
+ /** The Google Workspace domain the auth service verified for this session
27
+ * (whoami's `domain`). Absent for a personal account, and once the
28
+ * verification is too old for auth to report it. */
29
+ domain?: string;
20
30
  }
21
31
  export type Identity = AuthedUser | ServiceCaller;
22
32
  declare module 'hono' {
@@ -45,7 +55,20 @@ export interface RequireIdentityOptions extends S2sOptions {
45
55
  * sessions and the test bypass alike; service callers are governed by
46
56
  * grants, not by this. */
47
57
  userAccess?: UserAccessPolicy;
58
+ /** Admits guest sessions on this mount, in addition to whatever
59
+ * `userAccess` admits. Default false: the `pw_guest` cookie is never
60
+ * read, no guest lookup is ever made, and a guest is simply not signed
61
+ * in. With true, a request without a signed-in fleet session that
62
+ * carries a `pw_guest` cookie is resolved through whoami's guest answer
63
+ * and admitted with role 'guest' whatever `userAccess` says — so every
64
+ * route under the mount must decide for itself what a guest may reach. */
65
+ guestAccess?: boolean;
48
66
  }
49
- /** The one place the policy is evaluated. */
67
+ /** The one place the policy is evaluated. It names the roles it admits, so
68
+ * a 'guest' is refused under every policy: the guest path of a
69
+ * `guestAccess` mount is the only way one is admitted. */
50
70
  export declare function userAllowed(policy: UserAccessPolicy, user: Pick<AuthedUser, 'role'>): boolean;
71
+ /** A full session's role from an untrusted value. Anything else — 'guest'
72
+ * included — is undefined, which every caller treats as "no usable role". */
73
+ export declare function parseFullRole(value: unknown): FullRole | undefined;
51
74
  export declare function requireIdentity(opts: RequireIdentityOptions): import("hono").MiddlewareHandler<any, string, {}, Response>;
package/dist/auth.js CHANGED
@@ -4,9 +4,10 @@
4
4
  // Resolves who is calling, in order:
5
5
  // 1. Test bypass (AUTH_MODE=test): X-Test-S2S-Caller → service caller;
6
6
  // X-Test-User header or TEST_USER env → user, with the fleet role from
7
- // X-Test-User-Role / TEST_USER_ROLE (default 'invited'). Credential
8
- // verification is bypassed; authorization (grants, the userAccess
9
- // policy, app-level checks) still runs.
7
+ // X-Test-User-Role / TEST_USER_ROLE (default 'invited') and the domain
8
+ // from X-Test-User-Domain / TEST_USER_DOMAIN. Credential verification
9
+ // is bypassed; authorization (grants, the userAccess policy, guest
10
+ // admission, app-level checks) still runs.
10
11
  // 2. Authorization: Bearer → service-to-service OIDC (s2s.ts).
11
12
  // 3. pw_session cookie → whoami call to the auth service, cached
12
13
  // in-instance (10 min hits / 30 s misses — the old-world numbers),
@@ -14,6 +15,10 @@
14
15
  // Every call (never a cache hit) logs one INFO 'session check' event
15
16
  // saying why the cache could not answer and what the call cost the
16
17
  // waiting request (~/migration/research/whoami-latency-2026-10-30.md).
18
+ // 4. Only on a mount with `guestAccess: true`, and only when step 3 found
19
+ // no signed-in user (no pw_session cookie, or whoami answered 401):
20
+ // pw_guest cookie → whoami?guest=1, cached, single-flighted and logged
21
+ // like step 3 under keys of its own.
17
22
  //
18
23
  // Then the user-access policy: by default an app admits only users whose
19
24
  // auth role is 'owner'; `userAccess: 'invited'` admits any active fleet
@@ -21,11 +26,18 @@
21
26
  // so a port that forgets the question is closed, not open. Service callers
22
27
  // are governed by grants, not by this policy.
23
28
  //
29
+ // Guests (role 'guest') are people outside the fleet whom one app let in —
30
+ // a Notes page shared with them. The auth service gives them a session of
31
+ // its own kind in its own cookie, so the policy above never sees one and
32
+ // never admits one: an app that has not set `guestAccess` treats a guest as
33
+ // signed out, and one that has must decide per route what a guest reaches.
34
+ //
24
35
  // Unauthenticated: APIs get 401 JSON, pages redirect to the auth service's
25
36
  // login with a return URL. Denied users get 403 (JSON with a stable `code`
26
37
  // on APIs, a plain "not enabled" page otherwise). Auth-service *failures*
27
- // (network, 5xx, a whoami answer with no role) return 503 and never
28
- // redirect — a redirect on failure loops forever (old-world lesson).
38
+ // (network, 5xx, a whoami answer with no role or with a role its cookie
39
+ // cannot carry) return 503 and never redirect — a redirect on failure loops
40
+ // forever (old-world lesson).
29
41
  import { createHash } from 'node:crypto';
30
42
  import { createMiddleware } from 'hono/factory';
31
43
  import { authMode } from './config.js';
@@ -34,14 +46,20 @@ import { RateLimiter, resolveS2sCaller } from './s2s.js';
34
46
  import { fleetAddressState, fleetFetch } from './fleet-dns.js';
35
47
  export const DEFAULT_AUTH_URL = 'https://auth.apps.snewman.net';
36
48
  export const SESSION_COOKIE = 'pw_session';
49
+ /** The cookie of a guest session. Only a `guestAccess` mount ever reads it. */
50
+ export const GUEST_COOKIE = 'pw_guest';
37
51
  /** The `code` in a 403 JSON body when a signed-in user is refused by the
38
52
  * app's userAccess policy (as opposed to any other 403). */
39
53
  export const ACCESS_DENIED_CODE = 'app_access_denied';
40
- /** The one place the policy is evaluated. */
54
+ /** The one place the policy is evaluated. It names the roles it admits, so
55
+ * a 'guest' is refused under every policy: the guest path of a
56
+ * `guestAccess` mount is the only way one is admitted. */
41
57
  export function userAllowed(policy, user) {
42
- return policy === 'invited' || user.role === 'owner';
58
+ return user.role === 'owner' || (policy === 'invited' && user.role === 'invited');
43
59
  }
44
- function parseRole(value) {
60
+ /** A full session's role from an untrusted value. Anything else — 'guest'
61
+ * included — is undefined, which every caller treats as "no usable role". */
62
+ export function parseFullRole(value) {
45
63
  return value === 'owner' || value === 'invited' ? value : undefined;
46
64
  }
47
65
  export function requireIdentity(opts) {
@@ -51,7 +69,9 @@ export function requireIdentity(opts) {
51
69
  const hitMs = opts.cacheTtl?.hitMs ?? 600_000;
52
70
  const missMs = opts.cacheTtl?.missMs ?? 30_000;
53
71
  const policy = opts.userAccess ?? 'owner';
72
+ const guestAccess = opts.guestAccess === true;
54
73
  const limiter = new RateLimiter(opts.rateLimitPerMin ?? 600);
74
+ // Both keyed by cacheKey(): a session kind plus the request's cookies.
55
75
  const cache = new Map();
56
76
  // The whoami call in flight per cache key (single-flight).
57
77
  const inFlight = new Map();
@@ -85,8 +105,12 @@ export function requireIdentity(opts) {
85
105
  return c.html(accessDeniedPage({ host: c.req.header('host') ?? 'This app', email: user.email, authUrl }), 403);
86
106
  };
87
107
  return createMiddleware(async (c, next) => {
88
- const admit = (user) => {
89
- if (!userAllowed(policy, user))
108
+ // A user from a guest session is admitted as a guest whatever the
109
+ // policy says, and as nothing else; every other user goes through the
110
+ // policy, which never admits a guest.
111
+ const admit = (user, session = 'full') => {
112
+ const allowed = session === 'guest' ? user.role === 'guest' : userAllowed(policy, user);
113
+ if (!allowed)
90
114
  return accessDenied(c, user);
91
115
  c.set('identity', user);
92
116
  c.set('user', user);
@@ -98,8 +122,17 @@ export function requireIdentity(opts) {
98
122
  const email = c.req.header('x-test-user') ?? process.env.TEST_USER;
99
123
  if (!email)
100
124
  return unauthenticated(c);
101
- const role = parseRole(c.req.header('x-test-user-role') ?? process.env.TEST_USER_ROLE) ?? 'invited';
102
- return admit({ type: 'user', email, role });
125
+ const role = c.req.header('x-test-user-role') ?? process.env.TEST_USER_ROLE;
126
+ const domain = c.req.header('x-test-user-domain') ?? process.env.TEST_USER_DOMAIN;
127
+ const user = { type: 'user', email, ...(domain ? { domain } : {}) };
128
+ if (role === 'guest') {
129
+ // As in production: a mount that does not admit guests sees no
130
+ // session at all for one.
131
+ if (!guestAccess)
132
+ return unauthenticated(c);
133
+ return admit({ ...user, role }, 'guest');
134
+ }
135
+ return admit({ ...user, role: parseFullRole(role) ?? 'invited' });
103
136
  }
104
137
  // Service-to-service path.
105
138
  if (c.req.header('authorization') || c.req.header('x-test-s2s-caller')) {
@@ -115,46 +148,62 @@ export function requireIdentity(opts) {
115
148
  c.set('identity', resolved.caller);
116
149
  return next();
117
150
  }
118
- // Browser session path.
151
+ // Browser session path. The fleet session is asked first; the guest
152
+ // session only on a guestAccess mount, and only for a request with no
153
+ // signed-in fleet session (no pw_session cookie, or one whoami refused).
119
154
  const cookieHeader = c.req.header('cookie') ?? '';
120
- if (!/(?:^|;\s*)pw_session=/.test(cookieHeader))
121
- return unauthenticated(c);
122
- const key = createHash('sha256').update(cookieHeader).digest('hex');
155
+ const sessions = [];
156
+ if (/(?:^|;\s*)pw_session=/.test(cookieHeader))
157
+ sessions.push('full');
158
+ if (guestAccess && /(?:^|;\s*)pw_guest=/.test(cookieHeader))
159
+ sessions.push('guest');
160
+ for (const session of sessions) {
161
+ const outcome = await lookup(c, session, cookieHeader);
162
+ if (outcome.kind === 'user')
163
+ return admit(outcome.user, session);
164
+ // A fault ends the request: a fleet lookup that failed is never
165
+ // answered from the guest session instead.
166
+ if (outcome.kind === 'unavailable')
167
+ return c.json({ error: 'auth service unavailable' }, 503);
168
+ }
169
+ return unauthenticated(c);
170
+ });
171
+ // Guest answers live under keys no fleet key can equal (a bare hash), so
172
+ // an answer for one kind of session is never served for the other.
173
+ function cacheKey(session, cookieHeader) {
174
+ const hash = createHash('sha256').update(cookieHeader).digest('hex');
175
+ return session === 'guest' ? `guest:${hash}` : hash;
176
+ }
177
+ // What whoami says about one of a request's sessions: from the cache, or
178
+ // from one call. Nothing here awaits before the flight is registered.
179
+ async function lookup(c, session, cookieHeader) {
180
+ const key = cacheKey(session, cookieHeader);
123
181
  const cached = cache.get(key);
124
182
  if (cached && cached.expires > Date.now()) {
125
183
  hitsSinceLastCall++;
126
- if (!cached.user)
127
- return unauthenticated(c);
128
- return admit(cached.user);
184
+ return cached.user ? { kind: 'user', user: cached.user } : { kind: 'unauthenticated' };
129
185
  }
130
186
  // Single-flight: a request that misses while a call for the same cookie
131
187
  // is already in flight shares that call's answer instead of making its
132
188
  // own (30% of calls were such duplicates). Every request still gets an
133
189
  // answer fetched during its own lifetime, so what is admitted does not
134
- // change; the answer is applied per request below.
190
+ // change; the answer is applied per request by the caller.
135
191
  const flight = inFlight.get(key);
136
192
  if (flight) {
137
193
  flight.joiners.count++;
138
- return settle(await flight.outcome);
194
+ return flight.outcome;
139
195
  }
140
196
  const joiners = { count: 0 };
141
- const outcome = callWhoami(c, key, cached, cookieHeader, joiners).finally(() => inFlight.delete(key));
197
+ const outcome = callWhoami(c, session, key, cached, cookieHeader, joiners).finally(() => inFlight.delete(key));
142
198
  inFlight.set(key, { outcome, joiners });
143
- return settle(await outcome);
144
- function settle(outcome) {
145
- if (outcome.kind === 'user')
146
- return admit(outcome.user);
147
- if (outcome.kind === 'unauthenticated')
148
- return unauthenticated(c);
149
- return c.json({ error: 'auth service unavailable' }, 503);
150
- }
151
- });
199
+ return outcome;
200
+ }
152
201
  // One whoami call, whose answer every request that joined it shares. The
153
202
  // waiting request pays its full latency. One INFO event per call (a few
154
203
  // hundred a day fleet-wide; never per hit or per joined request), with a
155
204
  // fixed vocabulary of keys and nothing from the cookie but how many
156
205
  // cookies the header carries (a changing header defeats the cache).
157
- async function callWhoami(c, key, cached, cookieHeader, joiners) {
206
+ async function callWhoami(c, session, key, cached, cookieHeader, joiners) {
158
207
  const started = Date.now();
159
208
  const cacheState = !cached ? 'absent' : cached.user ? 'expired-user' : 'expired-unauthenticated';
160
209
  // Whether this call must look up the auth host's address (absent) or has
@@ -162,6 +211,7 @@ export function requireIdentity(opts) {
162
211
  // background); undefined for a non-fleet authUrl.
163
212
  const authAddress = fleetAddressState(authHost);
164
213
  const callFields = {
214
+ guest: session === 'guest',
165
215
  cacheState,
166
216
  ...(cached ? { entryAgeMs: started - cached.filled } : {}),
167
217
  hitsSinceLastCall,
@@ -190,7 +240,10 @@ export function requireIdentity(opts) {
190
240
  };
191
241
  let res;
192
242
  try {
193
- res = await whoamiFetch(`${authUrl}/api/whoami`, { headers: { cookie: cookieHeader } });
243
+ // auth answers from pw_guest only when asked to; from pw_session otherwise.
244
+ res = await whoamiFetch(`${authUrl}/api/whoami${session === 'guest' ? '?guest=1' : ''}`, {
245
+ headers: { cookie: cookieHeader },
246
+ });
194
247
  }
195
248
  catch (err) {
196
249
  callEnded(0);
@@ -200,15 +253,28 @@ export function requireIdentity(opts) {
200
253
  callEnded(res.status);
201
254
  if (res.ok) {
202
255
  const data = (await res.json());
203
- const role = parseRole(data.role);
256
+ // Each kind of session carries its own roles: the guest session only
257
+ // 'guest', the fleet session never.
258
+ const role = session === 'guest' ? (data.role === 'guest' ? 'guest' : undefined) : parseFullRole(data.role);
204
259
  if (!role) {
205
260
  // An auth service from before roles existed (a rollback), or a
206
- // protocol change: a fault, not an "invited" answer. Fail closed,
207
- // loudly, and without caching so recovery is instant.
208
- opts.logger?.error('whoami answer has no role', { email: data.email, role: data.role });
261
+ // protocol change — a guest answering for the fleet cookie, a fleet
262
+ // user for the guest cookie: a fault, not an "invited" answer. Fail
263
+ // closed, loudly, and without caching so recovery is instant.
264
+ opts.logger?.error(session === 'guest' ? 'guest whoami answer has the wrong role' : 'whoami answer has no role', {
265
+ email: data.email,
266
+ role: data.role,
267
+ });
209
268
  return { kind: 'unavailable' };
210
269
  }
211
- const user = { type: 'user', email: data.email, name: data.name, userId: data.user_id, role };
270
+ const user = {
271
+ type: 'user',
272
+ email: data.email,
273
+ name: data.name,
274
+ userId: data.user_id,
275
+ role,
276
+ ...(typeof data.domain === 'string' && data.domain ? { domain: data.domain } : {}),
277
+ };
212
278
  const now = Date.now();
213
279
  cache.set(key, { expires: now + hitMs, filled: now, user });
214
280
  return { kind: 'user', user };
@@ -20,7 +20,8 @@ export declare const CONNECTOR_HEADERS: {
20
20
  /** The headers that carry `user` to an app (the front door's side). */
21
21
  export declare function connectorIdentityHeaders(user: ConnectorUser): Record<string, string>;
22
22
  /** The identity the headers assert, or null when any required one is
23
- * missing or malformed. Header values are what the front door set; an
23
+ * missing or malformed — a role other than owner or invited included, so
24
+ * no guest is ever asserted. Header values are what the front door set; an
24
25
  * attacker who can set them has already passed the s2s check. */
25
26
  export declare function parseConnectorIdentityHeaders(header: (name: string) => string | undefined): ConnectorUser | null;
26
27
  export interface ForwardedConnectorOptions {
package/dist/connector.js CHANGED
@@ -20,7 +20,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
20
20
  import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
21
21
  import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
22
22
  import { createMiddleware } from 'hono/factory';
23
- import { ACCESS_DENIED_CODE, userAllowed } from './auth.js';
23
+ import { ACCESS_DENIED_CODE, parseFullRole, userAllowed } from './auth.js';
24
24
  import { serializeError } from './log-core.js';
25
25
  import { insufficientScope } from './oauth-resource.js';
26
26
  import { RateLimiter, resolveS2sCaller } from './s2s.js';
@@ -46,15 +46,13 @@ export function connectorIdentityHeaders(user) {
46
46
  ...(user.name ? { [CONNECTOR_HEADERS.name]: user.name } : {}),
47
47
  };
48
48
  }
49
- function parseRole(value) {
50
- return value === 'owner' || value === 'invited' ? value : undefined;
51
- }
52
49
  /** The identity the headers assert, or null when any required one is
53
- * missing or malformed. Header values are what the front door set; an
50
+ * missing or malformed — a role other than owner or invited included, so
51
+ * no guest is ever asserted. Header values are what the front door set; an
54
52
  * attacker who can set them has already passed the s2s check. */
55
53
  export function parseConnectorIdentityHeaders(header) {
56
54
  const email = header(CONNECTOR_HEADERS.user);
57
- const role = parseRole(header(CONNECTOR_HEADERS.role));
55
+ const role = parseFullRole(header(CONNECTOR_HEADERS.role));
58
56
  const clientId = header(CONNECTOR_HEADERS.client);
59
57
  const grantId = header(CONNECTOR_HEADERS.grant);
60
58
  const scope = header(CONNECTOR_HEADERS.scope);
@@ -2,17 +2,18 @@
2
2
  // preflight -> lock -> build -> assets -> seal -> [image build ‖ gates] ->
3
3
  // fence -> per-service update + explicit traffic pin -> hooks/smoke/log check
4
4
  // -> release record -> unlock. A failure before the traffic switch leaves the
5
- // old revision serving; after it, the failure is reported with the rollback
6
- // command printed.
5
+ // old revision serving; a failed switch also puts the traffic pin back on it
6
+ // (a stray pin left by an earlier run is re-pinned before the update); after
7
+ // the switch, the failure is reported with the rollback command printed.
7
8
  import { createHash } from 'node:crypto';
8
9
  import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
9
10
  import { hostname } from 'node:os';
10
11
  import { join, resolve } from 'node:path';
11
12
  import { DEFAULT_ACCOUNT, loadConfig, loadHooks } from './config.js';
12
- import { must, mustJson } from './exec.js';
13
+ import { CommandFailure, must, mustJson } from './exec.js';
13
14
  import { openEvidence, PhaseTimer } from './evidence.js';
14
15
  import { acquireLock, clearHold, publishRetainedAssets, readHold, readReleaseRecord, releaseLock, verifyLock, writeReleaseRecord, } from './gcs.js';
15
- import { consistentBaseSha, readServingState, SHA40 } from './plan.js';
16
+ import { consistentBaseSha, readServingState, SHA40, strayTrafficPin } from './plan.js';
16
17
  import { writeDeployMarker } from './deploy-marker.js';
17
18
  const RELEASE_DEADLINE_MS = 25 * 60_000;
18
19
  const IMAGE_DIGEST = /@sha256:[0-9a-f]{64}$/;
@@ -109,10 +110,12 @@ export async function runDeploy(options) {
109
110
  'a rollback moved traffic off it. Deploy a fix, or pass --override-hold.');
110
111
  }
111
112
  const serving = [];
113
+ const servingDescribed = [];
112
114
  for (const service of config.services) {
113
115
  const { described, state } = await readServingState(runner, gcloudBase, config.region, service.name);
114
116
  await evidence.save(`${service.name}-before.json`, JSON.stringify(described, null, 2));
115
117
  serving.push(state);
118
+ servingDescribed.push(described);
116
119
  }
117
120
  const base = consistentBaseSha(serving, sha);
118
121
  if (!base.ok)
@@ -267,6 +270,37 @@ export async function runDeploy(options) {
267
270
  }
268
271
  if (hooks.preRelease)
269
272
  await hooks.preRelease(ctx);
273
+ const pinTraffic = (name, revision) => runner('gcloud', [
274
+ 'run', 'services', 'update-traffic', name,
275
+ ...gcloudBase, '--region', config.region, '--quiet', '--format=json',
276
+ '--to-revisions', `${revision}=100`,
277
+ ]);
278
+ const repinCommand = (name, revision) => `gcloud run services update-traffic ${name} --project ${config.project} ` +
279
+ `--region ${config.region} --to-revisions ${revision}=100`;
280
+ // A failed `update-traffic` leaves the service's desired traffic pinned
281
+ // to the revision that failed while the old one goes on serving; the
282
+ // service then reports not ready and every later `services update`
283
+ // fails on the dead revision (notes, 2026-11-20). Put the pin back on
284
+ // the revision that served when this deploy started, which is still
285
+ // serving: the observed traffic never moved.
286
+ const restoreTrafficPin = async (name, revision, failedRevision) => {
287
+ if (!lock || !(await verifyLock(runner, lock))) {
288
+ log(`${name}: traffic switch to ${failedRevision} failed; NOT restoring the pin to ${revision} ` +
289
+ 'because the deploy lock was lost (another deploy or rollback owns the service now)');
290
+ return;
291
+ }
292
+ const restored = await pinTraffic(name, revision);
293
+ await evidence.save(`${name}-traffic-restore.json`, restored.stdout + restored.stderr);
294
+ if (restored.code === 0) {
295
+ log(`${name}: traffic switch to ${failedRevision} failed; restored the traffic pin to ` +
296
+ `${revision}, which still serves`);
297
+ }
298
+ else {
299
+ const tail = (restored.stderr.trim() || restored.stdout.trim()).slice(-500);
300
+ log(`${name}: traffic switch to ${failedRevision} failed AND restoring the pin to ${revision} ` +
301
+ `failed (${tail}); every deploy fails until: ${repinCommand(name, revision)}`);
302
+ }
303
+ };
270
304
  const deployed = [];
271
305
  for (const [index, service] of config.services.entries()) {
272
306
  const current = serving[index];
@@ -277,6 +311,20 @@ export async function runDeploy(options) {
277
311
  });
278
312
  continue;
279
313
  }
314
+ const stray = strayTrafficPin(servingDescribed[index], current.revision);
315
+ if (stray) {
316
+ // An earlier release's failed traffic switch whose pin was not put
317
+ // back (that run was killed, or its restore failed): `services
318
+ // update` would fail on it, so re-pin to what serves first.
319
+ const repinned = await pinTraffic(service.name, current.revision);
320
+ if (repinned.code !== 0) {
321
+ const tail = (repinned.stderr.trim() || repinned.stdout.trim()).slice(-1500);
322
+ throw new CommandFailure(`${service.name}: traffic is pinned to ${stray} while ${current.revision} serves, and ` +
323
+ `re-pinning failed; every deploy fails until: ${repinCommand(service.name, current.revision)}\n${tail}`, repinned);
324
+ }
325
+ log(`${service.name}: traffic was pinned to ${stray} while ${current.revision} served ` +
326
+ `(left by an earlier failed release); re-pinned to ${current.revision}`);
327
+ }
280
328
  // One --update-env-vars with gcloud's alternate-delimiter form (^|^ …)
281
329
  // so declared values may contain commas; '|' is rejected by validateConfig.
282
330
  const envPairs = [`BUILD_ID=${sha}`, ...Object.entries(config.updateEnv ?? {}).map(([k, v]) => `${k}=${v}`)];
@@ -304,7 +352,15 @@ export async function runDeploy(options) {
304
352
  throw new Error(`${service.name}: expected a new revision, got ${newRevision || 'none'}`);
305
353
  }
306
354
  // On a traffic-pinned service, `services update` can return before the
307
- // 0%-traffic revision reports Ready — poll the revision itself.
355
+ // 0%-traffic revision reports Ready — poll the revision itself. Ready
356
+ // here proves only the configuration and image import: Cloud Run starts
357
+ // no instance of a revision without traffic (notes-00156-dkv reported
358
+ // Ready 5 s before its first instance existed, and that instance exited
359
+ // at startup). The boot check is `update-traffic` below: Cloud Run starts
360
+ // the revision and moves no traffic unless its startup probe passes,
361
+ // for min-instance and scale-to-zero services alike (2026-11-20
362
+ // investigation; a revision-tag URL is no alternative while ingress is
363
+ // internal-and-cloud-load-balancing, as for all but one service).
308
364
  let ready = false;
309
365
  let lastCondition = '';
310
366
  for (let attempt = 0; attempt < 60; attempt += 1) {
@@ -325,11 +381,14 @@ export async function runDeploy(options) {
325
381
  if (!ready) {
326
382
  throw new Error(`${service.name}: revision ${newRevision} is not ready (${lastCondition})`);
327
383
  }
328
- await must(runner, 'gcloud', [
329
- 'run', 'services', 'update-traffic', service.name,
330
- ...gcloudBase, '--region', config.region, '--quiet', '--format=json',
331
- '--to-revisions', `${newRevision}=100`,
332
- ]);
384
+ const switched = await pinTraffic(service.name, newRevision);
385
+ await evidence.save(`${service.name}-traffic.json`, switched.stdout + switched.stderr);
386
+ if (switched.code !== 0) {
387
+ await restoreTrafficPin(service.name, current.revision, newRevision);
388
+ const tail = (switched.stderr.trim() || switched.stdout.trim()).slice(-1500);
389
+ throw new CommandFailure(`${service.name}: traffic switch to ${newRevision} failed (exit ${switched.code}); ` +
390
+ `${current.revision} still serves\n${tail}`, switched);
391
+ }
333
392
  trafficMoved = true;
334
393
  log(`${service.name}: serving ${newRevision}`);
335
394
  deployed.push({ name: service.name, revision: newRevision, imageDigest, updated: true });
@@ -45,6 +45,19 @@ export declare function pickRevisionForSha(revisions: unknown[], targetSha: stri
45
45
  * describe --format=json`, from *observed* traffic (`status.traffic`, never
46
46
  * `spec.traffic`, which is only the desired state). */
47
47
  export declare function servingRevisionName(service: string, described: unknown): string;
48
+ /** A traffic pin that routes somewhere other than the revision actually
49
+ * serving, in a `gcloud run services describe --format=json`: the desired
50
+ * state (`spec.traffic`) names another revision (or the latest one) for a
51
+ * share of traffic while observed traffic (`status.traffic`) stays on
52
+ * `servingRevision`. Returns that target, or null when the pin agrees.
53
+ * Entries carrying no traffic (tags at 0%) are ignored.
54
+ *
55
+ * It arises when `update-traffic` fails: Cloud Run keeps the new pin in
56
+ * the spec although the old revision goes on serving, the service reports
57
+ * not ready, and every later `services update` fails on the dead revision
58
+ * (notes, 2026-11-20: a pin to notes-00156-dkv, whose container exited at
59
+ * startup, failed the next deploy's update of a healthy revision). */
60
+ export declare function strayTrafficPin(described: unknown, servingRevision: string): string | null;
48
61
  /**
49
62
  * Extract serving state from a `gcloud run services describe --format=json`.
50
63
  *
@@ -113,6 +113,30 @@ export function servingRevisionName(service, described) {
113
113
  }
114
114
  return active[0].revisionName;
115
115
  }
116
+ /** A traffic pin that routes somewhere other than the revision actually
117
+ * serving, in a `gcloud run services describe --format=json`: the desired
118
+ * state (`spec.traffic`) names another revision (or the latest one) for a
119
+ * share of traffic while observed traffic (`status.traffic`) stays on
120
+ * `servingRevision`. Returns that target, or null when the pin agrees.
121
+ * Entries carrying no traffic (tags at 0%) are ignored.
122
+ *
123
+ * It arises when `update-traffic` fails: Cloud Run keeps the new pin in
124
+ * the spec although the old revision goes on serving, the service reports
125
+ * not ready, and every later `services update` fails on the dead revision
126
+ * (notes, 2026-11-20: a pin to notes-00156-dkv, whose container exited at
127
+ * startup, failed the next deploy's update of a healthy revision). */
128
+ export function strayTrafficPin(described, servingRevision) {
129
+ const spec = described.spec?.traffic ?? [];
130
+ for (const target of spec) {
131
+ if ((target.percent ?? 0) <= 0)
132
+ continue;
133
+ if (target.latestRevision)
134
+ return 'the latest revision';
135
+ if (target.revisionName && target.revisionName !== servingRevision)
136
+ return target.revisionName;
137
+ }
138
+ return null;
139
+ }
116
140
  /**
117
141
  * Extract serving state from a `gcloud run services describe --format=json`.
118
142
  *
package/dist/email.d.ts CHANGED
@@ -24,8 +24,15 @@ export interface SendEmailResult {
24
24
  ok: boolean;
25
25
  /** Resend's message id, when the send succeeded and the response parsed. */
26
26
  emailId?: string;
27
- /** Human-readable failure description, present when `ok` is false. */
27
+ /** Human-readable failure description, present when `ok` is false. For a
28
+ * refused send it quotes Resend's answer, which is Resend's text, not
29
+ * ours: a caller that sends with `logContent: false` should not log it. */
28
30
  error?: string;
31
+ /** Resend's HTTP status when it answered and refused the send. Absent for
32
+ * a failure with no answer (not configured, network, timeout). A caller
33
+ * that retries can tell a rejection it will never win (4xx other than
34
+ * 408, 409 and 429) from one worth another attempt. */
35
+ status?: number;
29
36
  }
30
37
  export interface EmailDeps {
31
38
  /** Resend API key. Falsy means "email not configured": logged at ERROR with
@@ -48,13 +55,23 @@ export interface EmailDeps {
48
55
  * the email unique (e.g. `digest:<user>:<date>`), never from the
49
56
  * attempt. See the header of this file for the verified semantics. */
50
57
  idempotencyKey?: string;
58
+ /** Whether log lines may carry the message's content. Default true: every
59
+ * line has the subject, and a failure's ERROR has a preview of the bodies
60
+ * and Resend's answer, so the send can be redone by hand. False: no line
61
+ * written here contains the subject or any part of the text or HTML
62
+ * body, on success or failure — it logs their lengths instead, and of
63
+ * Resend's answer to a refused send only the status, the length and the
64
+ * error `name`. The recipient, `context` and `idempotencyKey` are logged
65
+ * either way, so keep content out of those. */
66
+ logContent?: boolean;
51
67
  }
52
68
  export declare const DEFAULT_EMAIL_TIMEOUT_MS = 30000;
53
69
  /**
54
70
  * Send one email through Resend. Never throws: every failure is an ERROR
55
- * log (with enough of the message to redo the send by hand) and an
56
- * `{ ok: false, error }` result the caller surfaces where it matters. That
57
- * includes a timeout (`deps.timeoutMs`), after which the email may
58
- * nevertheless have been delivered.
71
+ * log (with enough of the message to redo the send by hand, unless
72
+ * `deps.logContent` is false) and an `{ ok: false, error }` result the
73
+ * caller surfaces where it matters. That includes a timeout
74
+ * (`deps.timeoutMs`), after which the email may nevertheless have been
75
+ * delivered.
59
76
  */
60
77
  export declare function sendEmail(msg: EmailMessage, deps: EmailDeps): Promise<SendEmailResult>;
package/dist/email.js CHANGED
@@ -25,9 +25,30 @@
25
25
  // the first is still in flight is 409 `concurrent_idempotent_requests`
26
26
  // (retry later); a key over 256 characters is 400 `invalid_idempotency_key`.
27
27
  // All three are failures: none confirms that this message was accepted.
28
+ //
29
+ // `logContent: false` (3.68.0) is for mail whose words are other people's
30
+ // (Notes' comment digests): the logs then carry sizes and Resend's status,
31
+ // never the subject, the bodies, or Resend's own prose about the message.
32
+ // Such a caller gives up "redone by hand" and owns its retries.
28
33
  import { serializeError, truncate } from './log-core.js';
29
34
  export const RESEND_API_URL = 'https://api.resend.com/emails';
30
35
  export const DEFAULT_EMAIL_TIMEOUT_MS = 30_000;
36
+ /** What a no-content log line says about Resend's answer to a refused send:
37
+ * its length and its machine-readable `name` (`validation_error`, …). The
38
+ * rest is Resend's prose, which may quote the message. */
39
+ function refusalFacts(body) {
40
+ let name;
41
+ try {
42
+ name = JSON.parse(body)?.name;
43
+ }
44
+ catch {
45
+ // Not JSON: the length is all there is to say.
46
+ }
47
+ return {
48
+ responseLength: body.length,
49
+ ...(typeof name === 'string' && /^[a-z0-9_]{1,64}$/.test(name) ? { errorName: name } : {}),
50
+ };
51
+ }
31
52
  /** The JSON body of Resend's `POST /emails`: optional fields are omitted
32
53
  * rather than sent empty. */
33
54
  function resendRequestBody(msg) {
@@ -51,25 +72,28 @@ function resendRequestBody(msg) {
51
72
  }
52
73
  /**
53
74
  * Send one email through Resend. Never throws: every failure is an ERROR
54
- * log (with enough of the message to redo the send by hand) and an
55
- * `{ ok: false, error }` result the caller surfaces where it matters. That
56
- * includes a timeout (`deps.timeoutMs`), after which the email may
57
- * nevertheless have been delivered.
75
+ * log (with enough of the message to redo the send by hand, unless
76
+ * `deps.logContent` is false) and an `{ ok: false, error }` result the
77
+ * caller surfaces where it matters. That includes a timeout
78
+ * (`deps.timeoutMs`), after which the email may nevertheless have been
79
+ * delivered.
58
80
  */
59
81
  export async function sendEmail(msg, deps) {
60
82
  const { logger } = deps;
61
83
  const fetchImpl = deps.fetchImpl ?? fetch;
62
84
  const timeoutMs = deps.timeoutMs ?? DEFAULT_EMAIL_TIMEOUT_MS;
85
+ const logContent = deps.logContent ?? true;
63
86
  const base = {
64
87
  to: msg.to,
65
- subject: truncate(msg.subject, 200),
88
+ ...(logContent ? { subject: truncate(msg.subject, 200) } : { subjectLength: msg.subject.length }),
66
89
  textLength: msg.text?.length ?? 0,
67
90
  htmlLength: msg.html?.length ?? 0,
68
91
  attachmentCount: msg.attachments?.length ?? 0,
69
92
  ...(deps.idempotencyKey !== undefined ? { idempotencyKey: deps.idempotencyKey } : {}),
70
93
  ...deps.context,
71
94
  };
72
- const preview = { text: truncate(msg.text ?? '', 500), html: truncate(msg.html ?? '', 500) };
95
+ // Added to a failure's ERROR, where nothing else records what was not sent.
96
+ const preview = logContent ? { text: truncate(msg.text ?? '', 500), html: truncate(msg.html ?? '', 500) } : {};
73
97
  if (!msg.text && !msg.html) {
74
98
  logger.error('email_rejected_no_body', base);
75
99
  return { ok: false, error: 'sendEmail requires a non-empty `text` or `html` body' };
@@ -96,8 +120,9 @@ export async function sendEmail(msg, deps) {
96
120
  const body = await res.text().catch(() => '');
97
121
  if (!res.ok) {
98
122
  const bodyPreview = truncate(body, 500);
99
- logger.error('email_send_failed', { ...base, status: res.status, body: bodyPreview, elapsedMs, ...preview });
100
- return { ok: false, error: `Resend API ${res.status}: ${bodyPreview}` };
123
+ const answer = logContent ? { body: bodyPreview } : refusalFacts(body);
124
+ logger.error('email_send_failed', { ...base, status: res.status, ...answer, elapsedMs, ...preview });
125
+ return { ok: false, error: `Resend API ${res.status}: ${bodyPreview}`, status: res.status };
101
126
  }
102
127
  let emailId;
103
128
  try {
@@ -58,8 +58,9 @@ export interface HubOptions {
58
58
  };
59
59
  };
60
60
  /** Passed through to requireIdentity (authUrl, whoamiFetch, verifyClient,
61
- * rateLimitPerMin…). The hub admits invited users for sockets. */
62
- identity?: Partial<Omit<RequireIdentityOptions, 'audience' | 'grants' | 'logger' | 'userAccess'>>;
61
+ * rateLimitPerMin…). The hub admits invited users for sockets, and never
62
+ * a guest. */
63
+ identity?: Partial<Omit<RequireIdentityOptions, 'audience' | 'grants' | 'logger' | 'userAccess' | 'guestAccess'>>;
63
64
  /** Injectable for tests. */
64
65
  bridge?: Partial<Pick<DbBroadcastBridgeOptions, 'heartbeatMs' | 'heartbeatTimeoutMs' | 'reconnectDelaysMs'>>;
65
66
  /** Monotonic milliseconds (tests). */
@@ -85,6 +85,7 @@ export function createHub(app, opts) {
85
85
  grants: opts.grants,
86
86
  logger,
87
87
  userAccess: 'invited',
88
+ guestAccess: false,
88
89
  });
89
90
  const serviceAccount = new RegExp(`^([a-z][a-z0-9-]*)-svc@${escapeRegExp(opts.serviceAccountDomain)}$`);
90
91
  if (opts.webSocketServer)
@@ -1,5 +1,5 @@
1
1
  import type { Context } from 'hono';
2
- import type { UserAccessPolicy, UserRole } from './auth.js';
2
+ import type { FullRole, UserAccessPolicy } from './auth.js';
3
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
@@ -11,7 +11,7 @@ export interface ConnectorUser {
11
11
  email: string;
12
12
  name?: string;
13
13
  userId?: string;
14
- role: UserRole;
14
+ role: FullRole;
15
15
  scopes: ReadonlySet<string>;
16
16
  /** The OAuth client the user approved (e.g. Claude's client ID URL). */
17
17
  clientId: string;
@@ -13,6 +13,10 @@
13
13
  // 1. Test bypass (AUTH_MODE=test): X-Test-Connector-User (+ -Role, -Scope).
14
14
  // Credential verification is bypassed; the access policy and the app's
15
15
  // scope checks still run.
16
+ //
17
+ // A connector user is never a guest (auth.ts): the auth service issues a
18
+ // guest no token, and a 'guest' role in an introspection answer is as
19
+ // malformed as any role outside owner/invited.
16
20
  // 2. Authorization: Bearer pwat_… → introspection at the auth service over
17
21
  // s2s OIDC, cached in-instance (5 min hits, capped by the token's own
18
22
  // expiry / 30 s misses, bounded LRU). Introspections are budgeted per
@@ -25,7 +29,7 @@
25
29
  // non-200, a malformed answer) is 503 and is never cached.
26
30
  import { createHash } from 'node:crypto';
27
31
  import { createMiddleware } from 'hono/factory';
28
- import { ACCESS_DENIED_CODE, DEFAULT_AUTH_URL, userAllowed } from './auth.js';
32
+ import { ACCESS_DENIED_CODE, DEFAULT_AUTH_URL, parseFullRole, userAllowed } from './auth.js';
29
33
  import { authMode } from './config.js';
30
34
  import { forwardedClientIp } from './http.js';
31
35
  import { RateLimiter, serviceFetch } from './s2s.js';
@@ -116,9 +120,6 @@ class LruCache {
116
120
  }
117
121
  }
118
122
  }
119
- function parseRole(value) {
120
- return value === 'owner' || value === 'invited' ? value : undefined;
121
- }
122
123
  function parseScopes(value) {
123
124
  return new Set(typeof value === 'string' ? value.split(' ').filter(Boolean) : []);
124
125
  }
@@ -167,11 +168,15 @@ export function requireConnectorUser(opts) {
167
168
  const email = c.req.header('x-test-connector-user');
168
169
  if (!email)
169
170
  return unauthorized(c, opts);
171
+ const role = c.req.header('x-test-connector-role');
172
+ // As in production, where a guest holds no connector token.
173
+ if (role === 'guest')
174
+ return unauthorized(c, opts);
170
175
  const scope = c.req.header('x-test-connector-scope');
171
176
  return admit({
172
177
  type: 'connector',
173
178
  email,
174
- role: parseRole(c.req.header('x-test-connector-role')) ?? 'invited',
179
+ role: parseFullRole(role) ?? 'invited',
175
180
  scopes: scope === undefined ? new Set(opts.scopes) : parseScopes(scope),
176
181
  clientId: 'test-client',
177
182
  grantId: 'test-grant',
@@ -229,7 +234,7 @@ export function requireConnectorUser(opts) {
229
234
  opts.logger?.warn('connector token is for another resource', { resource: data.resource });
230
235
  return reject();
231
236
  }
232
- const role = parseRole(data.role);
237
+ const role = parseFullRole(data.role);
233
238
  const expMs = typeof data.exp === 'number' ? data.exp * 1000 : NaN;
234
239
  if (!role ||
235
240
  !nonEmptyString(data.email) ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@steve31415/baselib",
3
- "version": "3.67.0",
3
+ "version": "3.69.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",