@caelo-cms/shared 0.11.13 → 0.11.14

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.
@@ -5,13 +5,17 @@
5
5
  *
6
6
  * One pure module shared by the two sides of the gate:
7
7
  *
8
- * - the admin, which issues "Open staging" tokens and shows the Owner the
9
- * crawler credentials (basic auth, secret header) it derives here;
10
- * - the gateway (gcp-firebase), which verifies every staging request
11
- * against the same rules before it proxies to the staged build.
8
+ * - the admin, which issues "Open staging" tokens and per-run tokens and
9
+ * shows the Owner the crawler credentials (basic auth, secret header) it
10
+ * derives here;
11
+ * - the staging gateway (#1330), which verifies every request on every host
12
+ * against the same rules before it serves the staged build.
12
13
  *
13
14
  * Every secret is derived from ONE shared key, the `staging-gate-secret`
14
- * in Secret Manager (`CAELO_STAGING_GATE_SECRET` on admin + gateway):
15
+ * (Secret Manager on the cloud installs, `CAELO_STAGING_GATE_SECRET` on the
16
+ * admin). The staging gateway reads it from its own database, where the
17
+ * admin publishes it (`published_staging_site`, #1331); no gateway holds it
18
+ * in its env:
15
19
  *
16
20
  * - Crawler credentials are `HMAC(key, kind + nonce)`. The database keeps
17
21
  * only the random nonce, so a database read alone reveals no credential,
@@ -25,12 +29,42 @@
25
29
  * so the module runs unchanged in Bun, Node and the admin's SvelteKit build.
26
30
  */
27
31
 
28
- /** Cookie the gateway sets on `staging.<domain>` after "Open staging". */
29
- export const STAGING_SESSION_COOKIE = "caelo_staging_access";
32
+ import { readSessionCookie, SESSION_ENTRY } from "./session-cookie.js";
33
+
34
+ /**
35
+ * The staging session lives in the `staging` entry of the one `__session`
36
+ * cookie (session-cookie.ts): the only cookie Firebase Hosting forwards over
37
+ * the staging site's rewrite (#1325 P0, E13 a), so every provider uses it.
38
+ */
39
+ export const STAGING_SESSION_ENTRY = SESSION_ENTRY.staging;
40
+
41
+ /**
42
+ * #1330 — the request header the admin's own staging clients (the capture
43
+ * job, the Stage's serve check) send their per-run token in
44
+ * ({@link signStagingRunToken}). Never a crawler credential, never the key.
45
+ */
46
+ export const STAGING_RUN_TOKEN_HEADER = "X-Caelo-Staging-Run";
47
+
48
+ /** What a per-run staging token may be used for. */
49
+ export type StagingRunPurpose = "capture" | "check";
50
+
51
+ /**
52
+ * The longest a per-run token may live. The admin mints one per capture or
53
+ * serve check; the gateway refuses one that claims a longer life, so a token
54
+ * that leaks from a job's input is worthless soon after.
55
+ */
56
+ export const STAGING_RUN_TOKEN_MAX_TTL_SECONDS = 15 * 60;
30
57
 
31
58
  /** Path on the staging host that turns an "Open staging" token into the session cookie. */
32
59
  export const STAGING_ACCESS_PATH = "/_caelo/staging-access";
33
60
 
61
+ /**
62
+ * #1330 — path on the staging gateway that answers the admin's serve check:
63
+ * with a per-run `check` token, the run id whose manifest a staging
64
+ * location holds (`?location=_slots/a`). Nothing else answers there.
65
+ */
66
+ export const STAGING_CHECK_PATH = "/_caelo/staging-check";
67
+
34
68
  /** How long an "Open staging" link stays usable. Short: it travels in a URL. */
35
69
  export const STAGING_OPEN_TOKEN_TTL_SECONDS = 120;
36
70
 
@@ -40,8 +74,12 @@ export const STAGING_SESSION_TTL_SECONDS = 12 * 60 * 60;
40
74
  /** Default name of the secret request header crawlers can send. */
41
75
  export const DEFAULT_STAGING_HEADER_NAME = "X-Caelo-Staging-Key";
42
76
 
43
- /** The access modes of the gate. Any one satisfied lets a request in. */
44
- export type StagingAccessMode = "cookie" | "basic-auth" | "header" | "ip";
77
+ /**
78
+ * The access modes of the gate. Any one satisfied lets a request in.
79
+ * `run-token` is the admin's own (capture and serve checks, #1330): always
80
+ * on, short-lived, minted per run.
81
+ */
82
+ export type StagingAccessMode = "cookie" | "basic-auth" | "header" | "ip" | "run-token";
45
83
 
46
84
  /** The gate's settings as stored (`staging_access`, migration 0251). */
47
85
  export interface StagingAccessSettings {
@@ -168,6 +206,56 @@ export async function verifyStagingToken(
168
206
  return valid && exp > nowSeconds;
169
207
  }
170
208
 
209
+ /**
210
+ * #1330 — a per-run token for one of the admin's own staging clients:
211
+ * `run.<purpose>.<runId>.<expiresAt>.<mac>`. Scoped to its purpose and
212
+ * stateless like the session token; `runId` names the run that asked, for
213
+ * the logs. The admin hands it to the capture job or its serve check, which
214
+ * send it ONLY on requests to the staging origin ({@link STAGING_RUN_TOKEN_HEADER}).
215
+ *
216
+ * @throws when `runId` is not a plain id or the lifetime exceeds {@link STAGING_RUN_TOKEN_MAX_TTL_SECONDS}.
217
+ */
218
+ export async function signStagingRunToken(
219
+ secret: string,
220
+ purpose: StagingRunPurpose,
221
+ runId: string,
222
+ expiresAtSeconds: number,
223
+ nowSeconds: number,
224
+ ): Promise<string> {
225
+ if (!/^[A-Za-z0-9-]{1,64}$/.test(runId))
226
+ throw new Error(`staging run token: bad run id "${runId}"`);
227
+ const exp = Math.floor(expiresAtSeconds);
228
+ if (exp - nowSeconds > STAGING_RUN_TOKEN_MAX_TTL_SECONDS) {
229
+ throw new Error(
230
+ `staging run token: a lifetime of ${exp - nowSeconds}s exceeds ${STAGING_RUN_TOKEN_MAX_TTL_SECONDS}s`,
231
+ );
232
+ }
233
+ const mac = base64Url(await hmacBytes(secret, `caelo-staging-run:${purpose}:${runId}:${exp}`));
234
+ return `run.${purpose}.${runId}.${exp}.${mac}`;
235
+ }
236
+
237
+ /** The purpose and run of a valid, unexpired per-run token, or null. */
238
+ export async function verifyStagingRunToken(
239
+ secret: string,
240
+ token: string,
241
+ nowSeconds: number,
242
+ ): Promise<{ readonly purpose: StagingRunPurpose; readonly runId: string } | null> {
243
+ const parts = token.split(".");
244
+ if (parts.length !== 5) return null;
245
+ const [tag, purpose, runId, expRaw, mac] = parts as [string, string, string, string, string];
246
+ if (tag !== "run" || (purpose !== "capture" && purpose !== "check")) return null;
247
+ if (!/^[A-Za-z0-9-]{1,64}$/.test(runId) || !/^\d{1,12}$/.test(expRaw)) return null;
248
+ const exp = Number(expRaw);
249
+ const expected = base64Url(
250
+ await hmacBytes(secret, `caelo-staging-run:${purpose}:${runId}:${exp}`),
251
+ );
252
+ const valid = constantTimeEqual(mac, expected);
253
+ if (!valid || exp <= nowSeconds || exp - nowSeconds > STAGING_RUN_TOKEN_MAX_TTL_SECONDS) {
254
+ return null;
255
+ }
256
+ return { purpose, runId };
257
+ }
258
+
171
259
  // ─── IP allowlist ─────────────────────────────────────────────────────
172
260
 
173
261
  function parseIpv4(s: string): number[] | null {
@@ -273,23 +361,18 @@ export function parseBasicAuthorization(
273
361
  return { user: decoded.slice(0, i), password: decoded.slice(i + 1) };
274
362
  }
275
363
 
276
- /** The value of cookie `name` in a `Cookie` header, or null. */
277
- export function readCookie(header: string | null, name: string): string | null {
278
- if (!header) return null;
279
- for (const part of header.split(/;\s*/)) {
280
- const eq = part.indexOf("=");
281
- if (eq > 0 && part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
282
- }
283
- return null;
284
- }
285
-
286
364
  /** The request facts the gate looks at. */
287
365
  export interface StagingAccessRequest {
288
366
  readonly cookieHeader: string | null;
289
367
  readonly authorizationHeader: string | null;
290
368
  /** Reads a request header by (case-insensitive) name. */
291
369
  readonly header: (name: string) => string | null;
292
- /** The client address the platform vouches for, or null when unknown. */
370
+ /**
371
+ * The client address the platform vouches for, or null when unknown — and
372
+ * null where no address can be trusted (gcp-firebase: the address behind
373
+ * the Hosting rewrite is a Google proxy, #1325), which turns the IP
374
+ * allowlist off.
375
+ */
293
376
  readonly clientIp: string | null;
294
377
  }
295
378
 
@@ -308,7 +391,9 @@ export async function decideStagingAccess(args: {
308
391
  const granted: StagingAccessMode[] = [];
309
392
 
310
393
  if (settings.cookieEnabled) {
311
- const token = readCookie(request.cookieHeader, STAGING_SESSION_COOKIE);
394
+ const token = readSessionCookie(request.cookieHeader, args.nowSeconds).get(
395
+ STAGING_SESSION_ENTRY,
396
+ )?.value;
312
397
  if (token && (await verifyStagingToken(secret, token, "session", args.nowSeconds))) {
313
398
  granted.push("cookie");
314
399
  }
@@ -327,6 +412,11 @@ export async function decideStagingAccess(args: {
327
412
  }
328
413
  const ip = request.clientIp;
329
414
  if (ip && settings.ipAllowlist.some((c) => ipMatchesCidr(ip, c))) granted.push("ip");
415
+ // Only a capture token opens the site; a check token answers the serve
416
+ // check (STAGING_CHECK_PATH) and nothing else.
417
+ const runToken = request.header(STAGING_RUN_TOKEN_HEADER);
418
+ const run = runToken ? await verifyStagingRunToken(secret, runToken, args.nowSeconds) : null;
419
+ if (run?.purpose === "capture") granted.push("run-token");
330
420
 
331
421
  const via = granted[0];
332
422
  if (via) return { allowed: true, via, satisfied: granted };
@@ -357,6 +447,17 @@ export function safeStagingNextPath(next: string | null): string {
357
447
  return `${url.pathname}${url.search}${url.hash}`;
358
448
  }
359
449
 
450
+ /**
451
+ * #1325 — whether the staging gate can trust a client address on
452
+ * `provider`. Behind the gcp-firebase Hosting rewrite the address Cloud Run
453
+ * vouches for is a Google front-end proxy that changes per request, so an
454
+ * IP allowlist there would admit nobody or, with a forgeable entry, anybody:
455
+ * the admin refuses to enable it and the gateway never matches it.
456
+ */
457
+ export function stagingIpAllowlistSupported(provider: string | undefined): boolean {
458
+ return provider !== "gcp-firebase";
459
+ }
460
+
360
461
  // ─── the staging host setting ─────────────────────────────────────────
361
462
 
362
463
  /**
@@ -367,14 +468,6 @@ export function defaultStagingHost(domain: string): string {
367
468
  return `staging.${domain.trim().toLowerCase().replace(/\.$/, "")}`;
368
469
  }
369
470
 
370
- /**
371
- * Longest host a Cloud Run domain mapping accepts — the gcp-firebase
372
- * gateway is mapped to the staging host, so a longer one would be stored,
373
- * rendered into every staged build and then never answer.
374
- * https://cloud.google.com/run/docs/mapping-custom-domains#limitations
375
- */
376
- export const CLOUD_RUN_DOMAIN_MAPPING_MAX_HOST_LENGTH = 64;
377
-
378
471
  const FQDN =
379
472
  /^(?=.{4,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
380
473
 
@@ -387,9 +480,7 @@ export function normalizeStagingHost(host: string): string {
387
480
  * Why `host` cannot be the staging host, or null when it can. It must be a
388
481
  * bare fully-qualified domain name (no scheme, port or path) and must not be
389
482
  * the live site's host or an admin host — staging would otherwise shadow
390
- * the site or the admin it is served next to. On gcp-firebase (`provider`)
391
- * it must also fit a Cloud Run domain mapping
392
- * ({@link CLOUD_RUN_DOMAIN_MAPPING_MAX_HOST_LENGTH} characters).
483
+ * the site or the admin it is served next to.
393
484
  *
394
485
  * @example
395
486
  * stagingHostProblem("preview.example.com", { liveHosts: ["example.com"], adminHosts: ["admin.example.com"] })
@@ -398,15 +489,11 @@ export function normalizeStagingHost(host: string): string {
398
489
  export function stagingHostProblem(
399
490
  host: string,
400
491
  reserved: { readonly liveHosts: readonly string[]; readonly adminHosts: readonly string[] },
401
- opts: { readonly provider?: string | undefined } = {},
402
492
  ): string | null {
403
493
  const h = normalizeStagingHost(host);
404
494
  if (!FQDN.test(h)) {
405
495
  return `"${host}" is not a valid host name — use a bare domain such as staging.example.com (no https://, port or path)`;
406
496
  }
407
- if (opts.provider === "gcp-firebase" && h.length > CLOUD_RUN_DOMAIN_MAPPING_MAX_HOST_LENGTH) {
408
- return `"${h}" is ${h.length} characters long; on gcp-firebase the staging host is served through a Cloud Run domain mapping, which accepts at most ${CLOUD_RUN_DOMAIN_MAPPING_MAX_HOST_LENGTH} — pick a shorter host (e.g. stg.<your domain>, or a shorter domain you own)`;
409
- }
410
497
  const norm = (list: readonly string[]) => list.map(normalizeStagingHost).filter(Boolean);
411
498
  if (norm(reserved.liveHosts).includes(h)) {
412
499
  return `"${h}" is the live site's host — staging needs a host of its own (e.g. staging.${h})`;
package/src/version.ts CHANGED
@@ -22,7 +22,7 @@
22
22
  * follow standard SemVer.
23
23
  */
24
24
 
25
- export const CAELO_VERSION = "0.11.13";
25
+ export const CAELO_VERSION = "0.11.14";
26
26
 
27
27
  /**
28
28
  * Deprecated alias for back-compat — early P17 work spelled this
@@ -1,15 +0,0 @@
1
- /**
2
- * FIXME(issue #1331): the header the MCP-Auth-Proxy's interim forwarder
3
- * (apps/mcp-auth-proxy server.ts) sets to the host a client asked for, and
4
- * the visitor gateway's staging gate (apps/api-gateway staging-proxy.ts)
5
- * reads. One name for both ends of the contract.
6
- *
7
- * On gcp-firebase the Cloud Run service `gateway` became the MCP-Auth-Proxy
8
- * (#1328, E13 a), while an existing staging domain mapping (#650) and the
9
- * live release's Firebase `/api/**` rewrite still point at it. The proxy
10
- * streams that traffic to the data gateway's run.app URL; Cloud Run routes
11
- * by Host, so the original host travels in this header. Removed with the
12
- * staging cutover (P3b-3).
13
- */
14
- export declare const INTERIM_FORWARDED_HOST_HEADER = "x-caelo-forwarded-host";
15
- //# sourceMappingURL=interim-forwarded-host.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"interim-forwarded-host.d.ts","sourceRoot":"","sources":["../src/interim-forwarded-host.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,6BAA6B,2BAA2B,CAAC"}
@@ -1,16 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
- /**
3
- * FIXME(issue #1331): the header the MCP-Auth-Proxy's interim forwarder
4
- * (apps/mcp-auth-proxy server.ts) sets to the host a client asked for, and
5
- * the visitor gateway's staging gate (apps/api-gateway staging-proxy.ts)
6
- * reads. One name for both ends of the contract.
7
- *
8
- * On gcp-firebase the Cloud Run service `gateway` became the MCP-Auth-Proxy
9
- * (#1328, E13 a), while an existing staging domain mapping (#650) and the
10
- * live release's Firebase `/api/**` rewrite still point at it. The proxy
11
- * streams that traffic to the data gateway's run.app URL; Cloud Run routes
12
- * by Host, so the original host travels in this header. Removed with the
13
- * staging cutover (P3b-3).
14
- */
15
- export const INTERIM_FORWARDED_HOST_HEADER = "x-caelo-forwarded-host";
16
- //# sourceMappingURL=interim-forwarded-host.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"interim-forwarded-host.js","sourceRoot":"","sources":["../src/interim-forwarded-host.ts"],"names":[],"mappings":"AAAA,mCAAmC;AAEnC;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,wBAAwB,CAAC"}
@@ -1,16 +0,0 @@
1
- // SPDX-License-Identifier: MPL-2.0
2
-
3
- /**
4
- * FIXME(issue #1331): the header the MCP-Auth-Proxy's interim forwarder
5
- * (apps/mcp-auth-proxy server.ts) sets to the host a client asked for, and
6
- * the visitor gateway's staging gate (apps/api-gateway staging-proxy.ts)
7
- * reads. One name for both ends of the contract.
8
- *
9
- * On gcp-firebase the Cloud Run service `gateway` became the MCP-Auth-Proxy
10
- * (#1328, E13 a), while an existing staging domain mapping (#650) and the
11
- * live release's Firebase `/api/**` rewrite still point at it. The proxy
12
- * streams that traffic to the data gateway's run.app URL; Cloud Run routes
13
- * by Host, so the original host travels in this header. Removed with the
14
- * staging cutover (P3b-3).
15
- */
16
- export const INTERIM_FORWARDED_HOST_HEADER = "x-caelo-forwarded-host";