@steve31415/baselib 4.0.0 → 5.0.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
@@ -10,6 +10,14 @@ Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`,
10
10
  `client-version`. Browser exports: `log-browser`, `rum`, `slow-fetch`, `sync-browser`, `app-update-browser`, and
11
11
  `extension-self-update`.
12
12
 
13
+ `auth`'s `requireIdentity` also holds every cookie-authenticated write and
14
+ socket handshake to the app's own origin (plus a checked-in
15
+ `allowedOrigins`), and `http`'s `startServer` puts the default security
16
+ headers on every response, with `contentSecurityPolicy()` for app shells —
17
+ both since 5.0.0 (`~/plasticine-way/docs/SECURITY.md`, "Browser-facing
18
+ rules"). `socket-age` caps socket age and, with `capSocketMessageSize`,
19
+ incoming message size.
20
+
13
21
  `sync` provides the Postgres event-log and server protocol primitives, and
14
22
  `handleSyncEventsRequest`, the one handler for every app's
15
23
  `POST /api/sync/events`; `sync-browser` provides the IndexedDB outbox and
@@ -1,13 +1,23 @@
1
+ /** The dataset pages log to; the browser token can write nowhere else but `rum`. */
2
+ export declare const BROWSER_LOG_DATASET = "browser";
1
3
  export interface AppShell {
2
4
  html: string;
3
5
  etag: string;
4
6
  buildId: string;
7
+ /** CSP hash sources of the shell's inline scripts, for
8
+ * `contentSecurityPolicy({ scriptHashes })`. */
9
+ scriptHashes: string[];
5
10
  }
6
11
  export interface LoadAppShellOptions {
7
12
  staticDir: string;
8
13
  app: string;
9
- dataset: string;
10
14
  buildId: string;
15
+ /** The page's log token. Default `process.env.AXIOM_BROWSER_TOKEN` (the
16
+ * browser-only token, `shared--axiom-browser-token`). A value equal to
17
+ * `process.env.AXIOM_INGEST_TOKEN`, the server's token, is never
18
+ * rendered: the browser token stands in (no token if there is none) and
19
+ * one error goes to stderr. Since 5.0.0 there is no `dataset` option:
20
+ * pages always log to BROWSER_LOG_DATASET. */
11
21
  logToken?: string;
12
22
  meta?: ReadonlyArray<readonly [name: string, value: string]>;
13
23
  }
@@ -1,8 +1,16 @@
1
1
  // Production app-shell rendering. The fully rendered bytes are held for the
2
2
  // process lifetime by consumers: build identity and logging configuration are
3
3
  // revision constants, and a stable body gives browsers a useful strong ETag.
4
+ //
5
+ // Since 5.0.0 a shell logs only with the browser token, to the `browser`
6
+ // dataset (PW docs/OPERATIONS.md, "Browser-written events"): the token is in
7
+ // the page, so anyone who loads it can write with it, and the server's own
8
+ // ingest token must never be there.
4
9
  import { createHash } from 'node:crypto';
5
10
  import { readFile } from 'node:fs/promises';
11
+ import { inlineScriptHashes } from '../security-headers.js';
12
+ /** The dataset pages log to; the browser token can write nowhere else but `rum`. */
13
+ export const BROWSER_LOG_DATASET = 'browser';
6
14
  function escapeAttribute(value) {
7
15
  return value
8
16
  .replaceAll('&', '&amp;')
@@ -10,12 +18,30 @@ function escapeAttribute(value) {
10
18
  .replaceAll('<', '&lt;')
11
19
  .replaceAll('>', '&gt;');
12
20
  }
21
+ /** The token a shell may carry: `logToken` or the browser token, unless it
22
+ * is the server's ingest token. */
23
+ function pageLogToken(app, logToken) {
24
+ const browserToken = process.env.AXIOM_BROWSER_TOKEN || undefined;
25
+ const token = logToken || browserToken;
26
+ const serverToken = process.env.AXIOM_INGEST_TOKEN;
27
+ if (token && serverToken && token === serverToken) {
28
+ // Not a throw: a shell that cannot render is every page of the app down.
29
+ // The browser token stands in (no token at all if there is none).
30
+ const instead = browserToken && browserToken !== serverToken ? browserToken : undefined;
31
+ console.error(`loadAppShell(${app}): refused to put the server's Axiom ingest token in the page; ` +
32
+ `${instead ? 'used AXIOM_BROWSER_TOKEN instead' : 'the shell carries no log token'}. ` +
33
+ 'Stop passing it: PW docs/OPERATIONS.md, "Browser-written events".');
34
+ return instead;
35
+ }
36
+ return token;
37
+ }
13
38
  export async function loadAppShell(opts) {
39
+ const logToken = pageLogToken(opts.app, opts.logToken);
14
40
  const metas = [
15
41
  ['pw-log-app', opts.app],
16
- ['pw-log-dataset', opts.dataset],
42
+ ['pw-log-dataset', BROWSER_LOG_DATASET],
17
43
  ['pw-build-id', opts.buildId],
18
- ...(opts.logToken ? [['pw-log-token', opts.logToken]] : []),
44
+ ...(logToken ? [['pw-log-token', logToken]] : []),
19
45
  ...(opts.meta ?? []),
20
46
  ];
21
47
  const renderedMetas = metas
@@ -24,7 +50,7 @@ export async function loadAppShell(opts) {
24
50
  const source = await readFile(`${opts.staticDir}/index.html`, 'utf8');
25
51
  const html = source.replace('</head>', `${renderedMetas}</head>`);
26
52
  const digest = createHash('sha256').update(html).digest('base64url');
27
- return { html, etag: `"${digest}"`, buildId: opts.buildId };
53
+ return { html, etag: `"${digest}"`, buildId: opts.buildId, scriptHashes: inlineScriptHashes(html) };
28
54
  }
29
55
  /** If-None-Match uses weak comparison for GET/HEAD, even for a strong ETag. */
30
56
  export function etagMatches(header, etag) {
package/dist/auth.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import type { Context } from 'hono';
2
2
  import { type Logger } from './log-core.js';
3
3
  import { ServiceCaller, S2sOptions } from './s2s.js';
4
+ import { type AllowedOrigins, type OriginCheckMode } from './origin-check.js';
5
+ export * from './origin-check.js';
4
6
  export declare const DEFAULT_AUTH_URL = "https://auth.apps.snewman.net";
5
7
  export declare const SESSION_COOKIE = "pw_session";
6
8
  /** The cookie of a guest session. Only a `guestAccess` mount ever reads it. */
@@ -8,6 +10,10 @@ export declare const GUEST_COOKIE = "pw_guest";
8
10
  /** The `code` in a 403 JSON body when a signed-in user is refused by the
9
11
  * app's userAccess policy (as opposed to any other 403). */
10
12
  export declare const ACCESS_DENIED_CODE = "app_access_denied";
13
+ /** The most whoami answers one requireIdentity mount keeps. */
14
+ export declare const WHOAMI_CACHE_MAX_ENTRIES = 5000;
15
+ /** A guest's default request ceiling per minute on a guestAccess mount. */
16
+ export declare const GUEST_RATE_LIMIT_PER_MIN = 300;
11
17
  /** A user's fleet role, assigned in auth's users table. A 'guest' is not a
12
18
  * fleet user: an app that admits guests vouched for them at sign-in, and
13
19
  * only a `guestAccess` mount ever yields one. */
@@ -49,6 +55,8 @@ export interface RequireIdentityOptions extends S2sOptions {
49
55
  hitMs?: number;
50
56
  missMs?: number;
51
57
  };
58
+ /** Tests: the whoami cache's bound (default WHOAMI_CACHE_MAX_ENTRIES). */
59
+ cacheMaxEntries?: number;
52
60
  /** Which signed-in users this app admits. Default 'owner': only users
53
61
  * whose auth role is owner. Pass 'invited' only for an app that is
54
62
  * multi-user by design, and say so in its SPEC. Applies to browser
@@ -63,6 +71,20 @@ export interface RequireIdentityOptions extends S2sOptions {
63
71
  * and admitted with role 'guest' whatever `userAccess` says — so every
64
72
  * route under the mount must decide for itself what a guest may reach. */
65
73
  guestAccess?: boolean;
74
+ /** Requests a minute one guest (by email) may make on this mount; past
75
+ * it, 429 and one WARN `guest rate limit exceeded` per guest per minute.
76
+ * Default GUEST_RATE_LIMIT_PER_MIN (300). */
77
+ guestRateLimit?: number;
78
+ /** Origins besides this app's own (`audience`) whose pages may send
79
+ * cookie-authenticated writes and socket handshakes to this mount — a
80
+ * reviewed, checked-in statement of trust like the grants (a browser
81
+ * extension's `chrome-extension://<id>`). origin-check.ts. */
82
+ allowedOrigins?: AllowedOrigins;
83
+ /** 'enforce' (default): a cross-origin write or socket handshake from an
84
+ * origin not allowed is refused with 403 `cross_origin_refused`.
85
+ * 'report': the same WARN, `enforced: false`, and the request goes on —
86
+ * only for an app's first days on baselib 5. */
87
+ originCheck?: OriginCheckMode;
66
88
  }
67
89
  /** The one place the policy is evaluated. It names the roles it admits, so
68
90
  * a 'guest' is refused under every policy: the guest path of a
package/dist/auth.js CHANGED
@@ -11,14 +11,21 @@
11
11
  // 2. Authorization: Bearer → service-to-service OIDC (s2s.ts).
12
12
  // 3. pw_session cookie → whoami call to the auth service, cached
13
13
  // in-instance (10 min hits / 30 s misses — the old-world numbers),
14
- // one call per cookie at a time (concurrent misses share it).
15
- // Every call (never a cache hit) logs one INFO 'session check' event
16
- // saying why the cache could not answer and what the call cost the
17
- // waiting request (~/migration/research/whoami-latency-2026-10-30.md).
14
+ // one call per session token at a time (concurrent misses share it).
15
+ // Only a value shaped like one of auth's tokens (32 random bytes,
16
+ // base64url: 43 characters) is a session; any other value is no
17
+ // session at all and never costs an auth call. The cache is keyed by
18
+ // the token (hashed), not by the whole Cookie header, and holds at
19
+ // most WHOAMI_CACHE_MAX_ENTRIES entries (expired ones go first, then
20
+ // the oldest). Every call (never a cache hit) logs one INFO 'session
21
+ // check' event saying why the cache could not answer and what the
22
+ // call cost the waiting request
23
+ // (~/migration/research/whoami-latency-2026-10-30.md).
18
24
  // 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):
25
+ // no signed-in user (no pw_session token, or whoami answered 401):
20
26
  // pw_guest cookie → whoami?guest=1, cached, single-flighted and logged
21
- // like step 3 under keys of its own.
27
+ // like step 3 under keys of its own. An admitted guest is held to
28
+ // `guestRateLimit` requests a minute (since 5.0.0).
22
29
  //
23
30
  // Then the user-access policy: by default an app admits only users whose
24
31
  // auth role is 'owner'; `userAccess: 'invited'` admits any active fleet
@@ -26,6 +33,11 @@
26
33
  // so a port that forgets the question is closed, not open. Service callers
27
34
  // are governed by grants, not by this policy.
28
35
  //
36
+ // Then the origin check (origin-check.ts, since 5.0.0), on every user a
37
+ // browser's cookie or the test bypass yields: a write or socket handshake
38
+ // from another origin is refused with 403 unless the mount lists that
39
+ // origin in `allowedOrigins`.
40
+ //
29
41
  // Guests (role 'guest') are people outside the fleet whom one app let in —
30
42
  // a Notes page shared with them. The auth service gives them a session of
31
43
  // its own kind in its own cookie, so the policy above never sees one and
@@ -44,6 +56,8 @@ import { authMode } from './config.js';
44
56
  import { truncate } from './log-core.js';
45
57
  import { RateLimiter, resolveS2sCaller } from './s2s.js';
46
58
  import { fleetAddressState, fleetFetch } from './fleet-dns.js';
59
+ import { checkRequestOrigin, originGate } from './origin-check.js';
60
+ export * from './origin-check.js';
47
61
  export const DEFAULT_AUTH_URL = 'https://auth.apps.snewman.net';
48
62
  export const SESSION_COOKIE = 'pw_session';
49
63
  /** The cookie of a guest session. Only a `guestAccess` mount ever reads it. */
@@ -51,6 +65,13 @@ export const GUEST_COOKIE = 'pw_guest';
51
65
  /** The `code` in a 403 JSON body when a signed-in user is refused by the
52
66
  * app's userAccess policy (as opposed to any other 403). */
53
67
  export const ACCESS_DENIED_CODE = 'app_access_denied';
68
+ /** The most whoami answers one requireIdentity mount keeps. */
69
+ export const WHOAMI_CACHE_MAX_ENTRIES = 5_000;
70
+ /** A guest's default request ceiling per minute on a guestAccess mount. */
71
+ export const GUEST_RATE_LIMIT_PER_MIN = 300;
72
+ /** The shape of the auth service's session tokens (randomBytes(32) as
73
+ * base64url). A cookie value of any other shape is not a session. */
74
+ const SESSION_TOKEN = /^[A-Za-z0-9_-]{43}$/;
54
75
  /** The one place the policy is evaluated. It names the roles it admits, so
55
76
  * a 'guest' is refused under every policy: the guest path of a
56
77
  * `guestAccess` mount is the only way one is admitted. */
@@ -71,7 +92,14 @@ export function requireIdentity(opts) {
71
92
  const policy = opts.userAccess ?? 'owner';
72
93
  const guestAccess = opts.guestAccess === true;
73
94
  const limiter = new RateLimiter(opts.rateLimitPerMin ?? 600);
74
- // Both keyed by cacheKey(): a session kind plus the request's cookies.
95
+ const guestLimit = opts.guestRateLimit ?? GUEST_RATE_LIMIT_PER_MIN;
96
+ const guestLimiter = new RateLimiter(guestLimit);
97
+ const originCheckMode = opts.originCheck ?? 'enforce';
98
+ // Validated here, so a malformed allowedOrigins entry stops the app at boot.
99
+ const sameOrigin = originGate({ origin: opts.audience, allowedOrigins: opts.allowedOrigins });
100
+ const cacheMax = opts.cacheMaxEntries ?? WHOAMI_CACHE_MAX_ENTRIES;
101
+ // Both keyed by cacheKey(): a session kind plus the session token's hash.
102
+ // Map order is fill order (remember() re-inserts), so the oldest is first.
75
103
  const cache = new Map();
76
104
  // The whoami call in flight per cache key (single-flight).
77
105
  const inFlight = new Map();
@@ -107,11 +135,24 @@ export function requireIdentity(opts) {
107
135
  return createMiddleware(async (c, next) => {
108
136
  // A user from a guest session is admitted as a guest whatever the
109
137
  // policy says, and as nothing else; every other user goes through the
110
- // policy, which never admits a guest.
138
+ // policy, which never admits a guest. Then the origin check (every user
139
+ // here came from a browser's cookie or the test bypass), then a guest's
140
+ // rate limit.
111
141
  const admit = (user, session = 'full') => {
112
142
  const allowed = session === 'guest' ? user.role === 'guest' : userAllowed(policy, user);
113
143
  if (!allowed)
114
144
  return accessDenied(c, user);
145
+ const refusal = checkRequestOrigin(c, sameOrigin, { mode: originCheckMode, logger: opts.logger, email: user.email });
146
+ if (refusal)
147
+ return refusal;
148
+ if (session === 'guest') {
149
+ const { allowed: withinLimit, firstRefusal } = guestLimiter.check(user.email);
150
+ if (!withinLimit) {
151
+ if (firstRefusal)
152
+ opts.logger?.warn('guest rate limit exceeded', { email: user.email, path: truncate(c.req.path, 200), limitPerMin: guestLimit });
153
+ return isApi(c) ? c.json({ error: 'rate limit exceeded' }, 429) : c.text('Too many requests', 429);
154
+ }
155
+ }
115
156
  c.set('identity', user);
116
157
  c.set('user', user);
117
158
  return next();
@@ -150,15 +191,17 @@ export function requireIdentity(opts) {
150
191
  }
151
192
  // Browser session path. The fleet session is asked first; the guest
152
193
  // 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).
194
+ // signed-in fleet session (no pw_session token, or one whoami refused).
154
195
  const cookieHeader = c.req.header('cookie') ?? '';
155
196
  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);
197
+ const fullToken = sessionToken(cookieHeader, SESSION_COOKIE);
198
+ if (fullToken)
199
+ sessions.push({ session: 'full', token: fullToken });
200
+ const guestToken = guestAccess ? sessionToken(cookieHeader, GUEST_COOKIE) : undefined;
201
+ if (guestToken)
202
+ sessions.push({ session: 'guest', token: guestToken });
203
+ for (const { session, token } of sessions) {
204
+ const outcome = await lookup(c, session, token, cookieHeader);
162
205
  if (outcome.kind === 'user')
163
206
  return admit(outcome.user, session);
164
207
  // A fault ends the request: a fleet lookup that failed is never
@@ -168,16 +211,33 @@ export function requireIdentity(opts) {
168
211
  }
169
212
  return unauthenticated(c);
170
213
  });
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;
214
+ // Each kind of session has keys of its own, so an answer for one kind is
215
+ // never served for the other. The token is hashed: the map holds no
216
+ // credential.
217
+ function cacheKey(session, token) {
218
+ return `${session}:${createHash('sha256').update(token).digest('hex')}`;
219
+ }
220
+ // Store an answer within the bound: when full, expired entries go first,
221
+ // then the oldest.
222
+ function remember(key, entry) {
223
+ cache.delete(key);
224
+ if (cache.size >= cacheMax) {
225
+ const now = Date.now();
226
+ for (const [k, e] of cache)
227
+ if (e.expires <= now)
228
+ cache.delete(k);
229
+ for (const k of cache.keys()) {
230
+ if (cache.size < cacheMax)
231
+ break;
232
+ cache.delete(k);
233
+ }
234
+ }
235
+ cache.set(key, entry);
176
236
  }
177
237
  // What whoami says about one of a request's sessions: from the cache, or
178
238
  // from one call. Nothing here awaits before the flight is registered.
179
- async function lookup(c, session, cookieHeader) {
180
- const key = cacheKey(session, cookieHeader);
239
+ async function lookup(c, session, token, cookieHeader) {
240
+ const key = cacheKey(session, token);
181
241
  const cached = cache.get(key);
182
242
  if (cached && cached.expires > Date.now()) {
183
243
  hitsSinceLastCall++;
@@ -194,7 +254,7 @@ export function requireIdentity(opts) {
194
254
  return flight.outcome;
195
255
  }
196
256
  const joiners = { count: 0 };
197
- const outcome = callWhoami(c, session, key, cached, cookieHeader, joiners).finally(() => inFlight.delete(key));
257
+ const outcome = callWhoami(c, session, key, token, cached, cookieHeader, joiners).finally(() => inFlight.delete(key));
198
258
  inFlight.set(key, { outcome, joiners });
199
259
  return outcome;
200
260
  }
@@ -202,8 +262,9 @@ export function requireIdentity(opts) {
202
262
  // waiting request pays its full latency. One INFO event per call (a few
203
263
  // hundred a day fleet-wide; never per hit or per joined request), with a
204
264
  // fixed vocabulary of keys and nothing from the cookie but how many
205
- // cookies the header carries (a changing header defeats the cache).
206
- async function callWhoami(c, session, key, cached, cookieHeader, joiners) {
265
+ // cookies the header carries. The call sends auth the one session cookie
266
+ // it is about, never the rest of the header.
267
+ async function callWhoami(c, session, key, token, cached, cookieHeader, joiners) {
207
268
  const started = Date.now();
208
269
  const cacheState = !cached ? 'absent' : cached.user ? 'expired-user' : 'expired-unauthenticated';
209
270
  // Whether this call must look up the auth host's address (absent) or has
@@ -242,7 +303,7 @@ export function requireIdentity(opts) {
242
303
  try {
243
304
  // auth answers from pw_guest only when asked to; from pw_session otherwise.
244
305
  res = await whoamiFetch(`${authUrl}/api/whoami${session === 'guest' ? '?guest=1' : ''}`, {
245
- headers: { cookie: cookieHeader },
306
+ headers: { cookie: `${session === 'guest' ? GUEST_COOKIE : SESSION_COOKIE}=${token}` },
246
307
  });
247
308
  }
248
309
  catch (err) {
@@ -276,18 +337,34 @@ export function requireIdentity(opts) {
276
337
  ...(typeof data.domain === 'string' && data.domain ? { domain: data.domain } : {}),
277
338
  };
278
339
  const now = Date.now();
279
- cache.set(key, { expires: now + hitMs, filled: now, user });
340
+ remember(key, { expires: now + hitMs, filled: now, user });
280
341
  return { kind: 'user', user };
281
342
  }
282
343
  if (res.status === 401) {
283
344
  const now = Date.now();
284
- cache.set(key, { expires: now + missMs, filled: now });
345
+ remember(key, { expires: now + missMs, filled: now });
285
346
  return { kind: 'unauthenticated' };
286
347
  }
287
348
  opts.logger?.error('auth service error', { meta_status: res.status });
288
349
  return { kind: 'unavailable' };
289
350
  }
290
351
  }
352
+ /** The first value of cookie `name` in a Cookie header that is shaped like
353
+ * a session token; undefined when there is none. Where a browser sends
354
+ * two (a stale host-only cookie beside the fleet one), a malformed first
355
+ * value does not hide a good second one, and auth is asked about exactly
356
+ * the token chosen here. */
357
+ function sessionToken(cookieHeader, name) {
358
+ for (const part of cookieHeader.split(';')) {
359
+ const eq = part.indexOf('=');
360
+ if (eq < 0 || part.slice(0, eq).trim() !== name)
361
+ continue;
362
+ const value = part.slice(eq + 1).trim();
363
+ if (SESSION_TOKEN.test(value))
364
+ return value;
365
+ }
366
+ return undefined;
367
+ }
291
368
  // The fleet-wide "not enabled" page, in the auth service's plain style so
292
369
  // every app shows the same thing. Carries nothing but the request's host,
293
370
  // the user's address, and the configured auth URL.
package/dist/http.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Hono, Context } from 'hono';
2
2
  import { serve } from '@hono/node-server';
3
3
  import type { Logger } from './log-core.js';
4
+ export * from './security-headers.js';
4
5
  export interface RequestLoggingOptions {
5
6
  /** Extra fields for the exit line, read after the handler (e.g. the hub's
6
7
  * `?app=`, so one service's sockets can be told apart by app); fields
@@ -35,11 +36,13 @@ export declare function requestLogging(logger: Logger, options?: RequestLoggingO
35
36
  * through the load balancer. */
36
37
  export declare function forwardedClientIp(c: Context, canonicalHost: string): string;
37
38
  export declare function addHealth(app: Hono): void;
38
- /** app.onError handler: log with full context, return a plain 500. */
39
+ /** app.onError handler: log with full context, return a plain 500 that
40
+ * says nothing about the error (since 5.0.0: an error's message can carry
41
+ * internals — a query, a path, another user's data — and the log already
42
+ * has it). */
39
43
  export declare function errorHandler(logger: Logger): (err: Error, c: Context) => (Response & import("hono").TypedResponse<{
40
44
  error: string;
41
- detail: string;
42
- }, 500, "json">) | (Response & import("hono").TypedResponse<`Internal error: ${string}`, 500, "text">);
45
+ }, 500, "json">) | (Response & import("hono").TypedResponse<"Internal error", 500, "text">);
43
46
  export interface StartServerOptions {
44
47
  app: Hono;
45
48
  logger: Logger;
@@ -52,7 +55,8 @@ export interface StartServerOptions {
52
55
  beforeExit?: () => Promise<unknown>;
53
56
  }
54
57
  /** Standard entry point: safety check, crash logging (logUncaughtErrors),
55
- * serve, graceful SIGTERM shutdown
58
+ * serve with the default security headers on every response
59
+ * (security-headers.ts, since 5.0.0), graceful SIGTERM shutdown
56
60
  * (stop accepting, then `beforeExit`, then flush all loggers, then exit). Returns the Node
57
61
  * server so callers can attach protocol upgrades (e.g. @hono/node-ws's
58
62
  * injectWebSocket). */
package/dist/http.js CHANGED
@@ -1,11 +1,14 @@
1
1
  // HTTP service plumbing: request logging, health endpoint, error handler,
2
- // and the standard server entry point with graceful shutdown.
2
+ // security headers, and the standard server entry point with graceful
3
+ // shutdown.
3
4
  import { createMiddleware } from 'hono/factory';
4
5
  import { serve } from '@hono/node-server';
5
6
  import { trackActivity } from './activity.js';
6
7
  import { assertBootSafety } from './config.js';
7
8
  import { flushAllLoggers, logUncaughtErrors } from './log.js';
8
9
  import { truncate } from './log-core.js';
10
+ import { withSecurityHeaders } from './security-headers.js';
11
+ export * from './security-headers.js';
9
12
  /** One INFO line per request on exit (method, path, status, elapsed,
10
13
  * identity, plus `options.meta`); /health excluded. Entry-point detail
11
14
  * beyond this (key parameters, outcomes) is the handler's job per
@@ -54,7 +57,10 @@ export function addHealth(app) {
54
57
  revision: process.env.K_REVISION ?? 'local',
55
58
  }));
56
59
  }
57
- /** app.onError handler: log with full context, return a plain 500. */
60
+ /** app.onError handler: log with full context, return a plain 500 that
61
+ * says nothing about the error (since 5.0.0: an error's message can carry
62
+ * internals — a query, a path, another user's data — and the log already
63
+ * has it). */
58
64
  export function errorHandler(logger) {
59
65
  return (err, c) => {
60
66
  logger.error(`unhandled error in ${c.req.method} ${c.req.path}`, {
@@ -63,13 +69,12 @@ export function errorHandler(logger) {
63
69
  path: c.req.path,
64
70
  });
65
71
  const wantsJson = c.req.path.startsWith('/api/') || (c.req.header('accept') ?? '').includes('application/json');
66
- return wantsJson
67
- ? c.json({ error: 'internal error', detail: String(err.message ?? err) }, 500)
68
- : c.text(`Internal error: ${String(err.message ?? err)}`, 500);
72
+ return wantsJson ? c.json({ error: 'internal error' }, 500) : c.text('Internal error', 500);
69
73
  };
70
74
  }
71
75
  /** Standard entry point: safety check, crash logging (logUncaughtErrors),
72
- * serve, graceful SIGTERM shutdown
76
+ * serve with the default security headers on every response
77
+ * (security-headers.ts, since 5.0.0), graceful SIGTERM shutdown
73
78
  * (stop accepting, then `beforeExit`, then flush all loggers, then exit). Returns the Node
74
79
  * server so callers can attach protocol upgrades (e.g. @hono/node-ws's
75
80
  * injectWebSocket). */
@@ -80,7 +85,7 @@ export function startServer(opts) {
80
85
  // Every request counts as activity (activity.ts), and wrapping registers
81
86
  // the logger's activity source: every event from here on says whether
82
87
  // Cloud Run had CPU allocated at the time.
83
- const server = serve({ fetch: trackActivity(opts.app.fetch), port }, (info) => {
88
+ const server = serve({ fetch: trackActivity(withSecurityHeaders(opts.app.fetch)), port }, (info) => {
84
89
  opts.logger.info('server started', { port: info.port });
85
90
  });
86
91
  process.once('SIGTERM', () => {
@@ -3,7 +3,7 @@ import type { UpgradeWebSocket } from 'hono/ws';
3
3
  import type pg from 'pg';
4
4
  import { type RequireIdentityOptions } from '../auth.js';
5
5
  import { type Logger } from '../log.js';
6
- import { type SocketAgeCapOptions } from '../socket-age.js';
6
+ import { type SocketAgeCapOptions, type WebSocketServerLike } from '../socket-age.js';
7
7
  import type { Grants } from '../s2s.js';
8
8
  import { type DbBroadcastBridgeOptions } from '../sync/db-bridge.js';
9
9
  /** The hub database's one table (the hub repo's first migration carries the
@@ -52,15 +52,11 @@ export interface HubOptions {
52
52
  upgradeWebSocket: UpgradeWebSocket;
53
53
  /** The upgrader's `ws` server (`createNodeWebSocket(...).wss`): the hub
54
54
  * caps its incoming frame size (ws's default is 100 MiB). */
55
- webSocketServer?: {
56
- options: {
57
- maxPayload?: number;
58
- };
59
- };
55
+ webSocketServer?: WebSocketServerLike;
60
56
  /** Passed through to requireIdentity (authUrl, whoamiFetch, verifyClient,
61
57
  * rateLimitPerMin…). The hub admits invited users for sockets, and never
62
58
  * a guest. */
63
- identity?: Partial<Omit<RequireIdentityOptions, 'audience' | 'grants' | 'logger' | 'userAccess' | 'guestAccess'>>;
59
+ identity?: Partial<Omit<RequireIdentityOptions, 'audience' | 'grants' | 'logger' | 'userAccess' | 'guestAccess' | 'allowedOrigins' | 'originCheck'>>;
64
60
  /** Injectable for tests. */
65
61
  bridge?: Partial<Pick<DbBroadcastBridgeOptions, 'heartbeatMs' | 'heartbeatTimeoutMs' | 'reconnectDelaysMs'>>;
66
62
  /** Monotonic milliseconds (tests). */
@@ -31,7 +31,7 @@ import { createMiddleware } from 'hono/factory';
31
31
  import { requireIdentity } from '../auth.js';
32
32
  import { forwardedClientIp } from '../http.js';
33
33
  import { serializeError } from '../log.js';
34
- import { capSocketAge } from '../socket-age.js';
34
+ import { capSocketAge, capSocketMessageSize } from '../socket-age.js';
35
35
  import { DbBroadcastBridge } from '../sync/db-bridge.js';
36
36
  import { isDaemonId } from './mint.js';
37
37
  import { checkHint, isAppName } from './types.js';
@@ -86,10 +86,14 @@ export function createHub(app, opts) {
86
86
  logger,
87
87
  userAccess: 'invited',
88
88
  guestAccess: false,
89
+ // Pages of every fleet app open sockets here, so the origin check
90
+ // admits the family; the socket route's own check (originCheck below)
91
+ // then holds each socket to its own app's origin.
92
+ allowedOrigins: (origin) => originMatchesSomeApp(origin, opts),
89
93
  });
90
94
  const serviceAccount = new RegExp(`^([a-z][a-z0-9-]*)-svc@${escapeRegExp(opts.serviceAccountDomain)}$`);
91
95
  if (opts.webSocketServer)
92
- opts.webSocketServer.options.maxPayload = HUB_SOCKET_MAX_PAYLOAD;
96
+ capSocketMessageSize(opts.webSocketServer, { maxBytes: HUB_SOCKET_MAX_PAYLOAD, logger });
93
97
  // app → user → sockets
94
98
  const sockets = new Map();
95
99
  const waits = new Map();
@@ -517,12 +521,21 @@ export function createHub(app, opts) {
517
521
  function workResponse(ref) {
518
522
  return Response.json({ kind: 'work', ...(ref !== undefined ? { ref } : {}) });
519
523
  }
524
+ const LOCAL_ORIGIN = /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
525
+ /** Whether `origin` is some fleet app's page origin (or, with
526
+ * allowLocalOrigins, a local one). */
527
+ function originMatchesSomeApp(origin, opts) {
528
+ const m = /^https:\/\/([a-z][a-z0-9-]*)\.(.+)$/.exec(origin);
529
+ if (m && m[2] === opts.appDomain && isAppName(m[1]))
530
+ return true;
531
+ return opts.allowLocalOrigins === true && LOCAL_ORIGIN.test(origin);
532
+ }
520
533
  function originAllowed(origin, appName, opts) {
521
534
  if (!origin)
522
535
  return false;
523
536
  if (origin === `https://${appName}.${opts.appDomain}`)
524
537
  return true;
525
- return opts.allowLocalOrigins === true && /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin);
538
+ return opts.allowLocalOrigins === true && LOCAL_ORIGIN.test(origin);
526
539
  }
527
540
  function intParam(value, min, max, fallback) {
528
541
  if (value === undefined || !/^\d+$/.test(value))
@@ -4,12 +4,17 @@
4
4
  // inject it:
5
5
  //
6
6
  // <meta name="pw-log-app" content="auth">
7
- // <meta name="pw-log-dataset" content="apps">
8
- // <meta name="pw-log-token" content="...ingest-only, dataset-scoped...">
7
+ // <meta name="pw-log-dataset" content="browser">
8
+ // <meta name="pw-log-token" content="...the browser token...">
9
9
  // <meta name="pw-build-id" content="...deployment identity...">
10
10
  //
11
- // The token is ingest-only and dataset-scoped by design — visible to any
12
- // signed-in user, able to do nothing but add log events.
11
+ // The token is the browser-only one (`shared--axiom-browser-token`: ingest
12
+ // into `browser` and `rum`, nothing else), public by design: anyone who
13
+ // loads a page can read it and write events with it, as any app, at any
14
+ // level. So pages log to their own dataset, `browser` (the default here
15
+ // since 5.0.0), never with the servers' token or into their datasets, and
16
+ // what a browser row says is data, never evidence of what a server did
17
+ // (PW docs/OPERATIONS.md, "Browser-written events").
13
18
  //
14
19
  // Every event also carries two top-level fields saying where it came from,
15
20
  // because browser events have no request to join on (2026-10-03, radar: telling
@@ -145,7 +150,7 @@ function metaContent(name) {
145
150
  }
146
151
  export function createBrowserLogger(opts = {}) {
147
152
  const app = opts.app ?? metaContent('pw-log-app') ?? 'unknown';
148
- const dataset = opts.dataset ?? metaContent('pw-log-dataset') ?? 'apps';
153
+ const dataset = opts.dataset ?? metaContent('pw-log-dataset') ?? 'browser';
149
154
  const token = opts.token ?? metaContent('pw-log-token');
150
155
  const baseUrl = opts.baseUrl ?? 'https://api.axiom.co';
151
156
  const buildId = metaContent('pw-build-id');
@@ -2,9 +2,11 @@ import type { Runner } from '../deploy/types.js';
2
2
  import { type CliIo } from './cli.js';
3
3
  export declare const AXIOM_QUERY_URL = "https://api.axiom.co/v1/datasets/_apl?format=tabular";
4
4
  export declare const QUERY_TOKEN_SECRET = "shared--axiom-query-token";
5
- export declare const USAGE = "usage: pw-logs [options] [APL tail]\nQuery the fleet's Axiom logs (query-only token from Secret Manager).\n\n -d, --dataset <name> apps (default) | platform | rum\n -a, --app <name> app filter; default: the enclosing repo's deploy.config.json for\n apps/rum (\"all\" for none); platform has no default \u2014 it is keyed\n by GCP service name, not app, and a Cloud Run Job's service (e.g.\n radar-cf-probe, corpus-build) rarely equals its owning app's repo\n name, so pass -a explicitly there or you get every service\n -l, --level <level> debug | info | warn | error; add \"+\" for that level and above (warn+)\n -s, --since <when> window start: duration back from now (30m, 6h, 3d) or timestamp (default 1h)\n -u, --until <when> window end, same forms (default now)\n -n, --limit <n> rows to return (default 200); events are the newest, printed oldest first\n --json print events (or aggregation rows) as a JSON array\n --all text mode: show every field (batch ids, full build_id)\n --apl print the query that would run and exit\n -h, --help\n\nThe tail is appended to the generated pipeline. The newest-first ordering\nis added only when the tail just filters or reshapes events (where, extend,\nproject-away/keep/rename, mv-expand, parse); a summarize, project, order or\ntake stage of your own decides the order. The limit always applies.\nExamples:\n pw-logs -l error -s 6h\n pw-logs -a chime \"where meta.user == 'x' | where message has 'sync'\"\n pw-logs -a all -l warn+ -s 24h \"summarize n=count() by app, message\"\n pw-logs -d platform -s 3d \"where severity != 'INFO'\"\nFields: apps = app, level, message, source, build_id, meta.* (a map: query\nsub-keys with dot notation, cast for summarize by \u2014 tostring(meta.user));\nplatform = service, severity, text, revision; rum = app, metric, value,\nrating, path, build_id.";
5
+ export declare const USAGE = "usage: pw-logs [options] [APL tail]\nQuery the fleet's Axiom logs (query-only token from Secret Manager).\n\n -d, --dataset <name> apps (default: servers' apps and pages' browser together, each row's\n dataset in \"dataset\") | browser | platform | rum\n -a, --app <name> app filter; default: the enclosing repo's deploy.config.json for\n apps/rum (\"all\" for none); platform has no default \u2014 it is keyed\n by GCP service name, not app, and a Cloud Run Job's service (e.g.\n radar-cf-probe, corpus-build) rarely equals its owning app's repo\n name, so pass -a explicitly there or you get every service\n -l, --level <level> debug | info | warn | error; add \"+\" for that level and above (warn+)\n -s, --since <when> window start: duration back from now (30m, 6h, 3d) or timestamp (default 1h)\n -u, --until <when> window end, same forms (default now)\n -n, --limit <n> rows to return (default 200); events are the newest, printed oldest first\n --json print events (or aggregation rows) as a JSON array\n --all text mode: show every field (batch ids, full build_id)\n --apl print the query that would run and exit\n -h, --help\n\nThe tail is appended to the generated pipeline. The newest-first ordering\nis added only when the tail just filters or reshapes events (where, extend,\nproject-away/keep/rename, mv-expand, parse); a summarize, project, order or\ntake stage of your own decides the order. The limit always applies.\nExamples:\n pw-logs -l error -s 6h\n pw-logs -a chime \"where meta.user == 'x' | where message has 'sync'\"\n pw-logs -a all -l warn+ -s 24h \"summarize n=count() by app, message\"\n pw-logs -d platform -s 3d \"where severity != 'INFO'\"\nFields: apps = app, level, message, source, build_id, dataset, meta.* (a map:\nquery sub-keys with dot notation, cast for summarize by \u2014 tostring(meta.user));\nbrowser = the same, without dataset; platform = service, severity, text,\nrevision; rum = app, metric, value, rating, path, build_id. Rows from pages\n(dataset browser) are written with a public token: data, never evidence of\nwhat a server did.";
6
6
  type Fields = Record<string, unknown>;
7
7
  interface DatasetSpec {
8
+ /** The query's first stage, when it is not just the dataset by name. */
9
+ from?: string;
8
10
  appField: string;
9
11
  levelField: string;
10
12
  /** Ascending severity order; --level maps onto it. */
@@ -19,6 +21,9 @@ interface DatasetSpec {
19
21
  /** Fields hidden in text mode unless --all. */
20
22
  quiet: string[];
21
23
  }
24
+ /** Servers' events and pages' events, each row stamped with its source
25
+ * dataset (`dataset`). */
26
+ export declare const APP_EVENTS_FROM = "union withsource=dataset ['apps'], ['browser']";
22
27
  export declare const DATASETS: Record<string, DatasetSpec>;
23
28
  export declare function datasetSpec(name: string): DatasetSpec;
24
29
  export interface LogsQuery {