@caelo-cms/shared 0.11.20 → 0.12.1

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.
Files changed (109) hide show
  1. package/dist/ai-tools.d.ts +4 -0
  2. package/dist/ai-tools.d.ts.map +1 -1
  3. package/dist/ai-tools.js +6 -0
  4. package/dist/ai-tools.js.map +1 -1
  5. package/dist/bug-intake.d.ts +15 -0
  6. package/dist/bug-intake.d.ts.map +1 -1
  7. package/dist/bug-intake.js +14 -0
  8. package/dist/bug-intake.js.map +1 -1
  9. package/dist/change-journal.d.ts.map +1 -1
  10. package/dist/change-journal.js +1 -0
  11. package/dist/change-journal.js.map +1 -1
  12. package/dist/context.d.ts +26 -0
  13. package/dist/context.d.ts.map +1 -1
  14. package/dist/context.js +2 -1
  15. package/dist/context.js.map +1 -1
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +2 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/link-refs.d.ts +18 -2
  21. package/dist/link-refs.d.ts.map +1 -1
  22. package/dist/link-refs.js +24 -6
  23. package/dist/link-refs.js.map +1 -1
  24. package/dist/lists/address.d.ts +6 -0
  25. package/dist/lists/address.d.ts.map +1 -1
  26. package/dist/lists/address.js +9 -1
  27. package/dist/lists/address.js.map +1 -1
  28. package/dist/lists/resolve-values.d.ts +11 -0
  29. package/dist/lists/resolve-values.d.ts.map +1 -1
  30. package/dist/lists/resolve-values.js +19 -0
  31. package/dist/lists/resolve-values.js.map +1 -1
  32. package/dist/lists/resolve.d.ts +5 -0
  33. package/dist/lists/resolve.d.ts.map +1 -1
  34. package/dist/lists/resolve.js +7 -0
  35. package/dist/lists/resolve.js.map +1 -1
  36. package/dist/owner-setup-token.d.ts +28 -0
  37. package/dist/owner-setup-token.d.ts.map +1 -0
  38. package/dist/owner-setup-token.js +41 -0
  39. package/dist/owner-setup-token.js.map +1 -0
  40. package/dist/redirect-emit-front-door.d.ts.map +1 -1
  41. package/dist/redirect-emit-front-door.js +4 -0
  42. package/dist/redirect-emit-front-door.js.map +1 -1
  43. package/dist/redirect-emit-gcp.d.ts +8 -0
  44. package/dist/redirect-emit-gcp.d.ts.map +1 -1
  45. package/dist/redirect-emit-gcp.js +4 -1
  46. package/dist/redirect-emit-gcp.js.map +1 -1
  47. package/dist/redirect-plan.d.ts +2 -2
  48. package/dist/redirect-plan.d.ts.map +1 -1
  49. package/dist/redirect-plan.js +13 -4
  50. package/dist/redirect-plan.js.map +1 -1
  51. package/dist/redirect-target.d.ts +57 -7
  52. package/dist/redirect-target.d.ts.map +1 -1
  53. package/dist/redirect-target.js +130 -8
  54. package/dist/redirect-target.js.map +1 -1
  55. package/dist/seo.d.ts +21 -0
  56. package/dist/seo.d.ts.map +1 -1
  57. package/dist/seo.js +21 -0
  58. package/dist/seo.js.map +1 -1
  59. package/dist/site-security-headers.d.ts +323 -0
  60. package/dist/site-security-headers.d.ts.map +1 -0
  61. package/dist/site-security-headers.js +424 -0
  62. package/dist/site-security-headers.js.map +1 -0
  63. package/dist/staged-site.d.ts +11 -0
  64. package/dist/staged-site.d.ts.map +1 -1
  65. package/dist/staged-site.js +26 -0
  66. package/dist/staged-site.js.map +1 -1
  67. package/dist/template-engine.d.ts +7 -0
  68. package/dist/template-engine.d.ts.map +1 -1
  69. package/dist/template-engine.js +38 -1
  70. package/dist/template-engine.js.map +1 -1
  71. package/dist/template-sections.d.ts +23 -1
  72. package/dist/template-sections.d.ts.map +1 -1
  73. package/dist/template-sections.js +124 -17
  74. package/dist/template-sections.js.map +1 -1
  75. package/dist/version.d.ts +2 -2
  76. package/dist/version.d.ts.map +1 -1
  77. package/dist/version.js +1 -1
  78. package/dist/version.js.map +1 -1
  79. package/package.json +1 -1
  80. package/src/ai-tools.ts +7 -0
  81. package/src/bug-intake.ts +16 -0
  82. package/src/change-journal.ts +1 -0
  83. package/src/context.ts +28 -0
  84. package/src/index.ts +2 -0
  85. package/src/link-refs.test.ts +38 -4
  86. package/src/link-refs.ts +39 -6
  87. package/src/lists/address.ts +16 -1
  88. package/src/lists/lists.test.ts +2 -0
  89. package/src/lists/resolve-values.ts +19 -0
  90. package/src/lists/resolve.test.ts +8 -0
  91. package/src/lists/resolve.ts +8 -0
  92. package/src/owner-setup-token.ts +49 -0
  93. package/src/redirect-emit-front-door.ts +6 -0
  94. package/src/redirect-emit-gcp.ts +12 -1
  95. package/src/redirect-emit.test.ts +44 -0
  96. package/src/redirect-plan.test.ts +57 -0
  97. package/src/redirect-plan.ts +12 -5
  98. package/src/redirect-target.test.ts +110 -4
  99. package/src/redirect-target.ts +142 -8
  100. package/src/seo.test.ts +24 -0
  101. package/src/seo.ts +25 -0
  102. package/src/site-security-headers.test.ts +263 -0
  103. package/src/site-security-headers.ts +509 -0
  104. package/src/staged-site.ts +30 -0
  105. package/src/template-engine-link-field.test.ts +148 -0
  106. package/src/template-engine-lists.test.ts +1 -1
  107. package/src/template-engine.ts +41 -1
  108. package/src/template-sections.ts +136 -20
  109. package/src/version.ts +1 -1
package/src/index.ts CHANGED
@@ -57,6 +57,7 @@ export * from "./markup-structure.js";
57
57
  export * from "./mcp-access.js";
58
58
  export * from "./media.js";
59
59
  export * from "./nested-module-render.js";
60
+ export * from "./owner-setup-token.js";
60
61
  export * from "./page-log.js";
61
62
  export * from "./phase-timer.js";
62
63
  export * from "./platform-updates.js";
@@ -82,6 +83,7 @@ export * from "./safe-keys.js";
82
83
  export * from "./screenshot-capture.js";
83
84
  export * from "./seo.js";
84
85
  export * from "./session-cookie.js";
86
+ export * from "./site-security-headers.js";
85
87
  export * from "./skills.js";
86
88
  export * from "./snapshots.js";
87
89
  export * from "./source-text-transport.js";
@@ -552,7 +552,7 @@ const EN_SOLO = "c1111111-1111-4111-8111-111111111111";
552
552
  const EN_HOME = "d1111111-1111-4111-8111-111111111111";
553
553
  const DE_HOME = "d2222222-2222-4222-8222-222222222222";
554
554
 
555
- function variantIndex(env: "preview" | "staging" = "staging") {
555
+ function variantIndex(env: "preview" | "staging" | "production" = "staging") {
556
556
  return createSiteLinkIndex({
557
557
  env,
558
558
  pageUrlStyle: "directory",
@@ -634,13 +634,47 @@ describe("page variants (link-resolve) — links go to the rendering page's vari
634
634
  const missing: string[] = [];
635
635
  const out = resolveLinkRefsInHtml(
636
636
  `<a href="caelo:page/${EN_SOLO}">Solo</a>`,
637
- variantIndex().forPage(DE_HOME),
637
+ variantIndex("production").forPage(DE_HOME),
638
638
  missing,
639
639
  );
640
640
  expect(out).toBe(`<a href="caelo:page/${EN_SOLO}">Solo</a>`);
641
641
  expect(missing).toEqual([`link-variant-missing:page/${EN_SOLO}:de`]);
642
642
  expect(linkIssueSeverity("preview", "no-variant")).toBe("block");
643
- expect(linkIssueSeverity("staging", "no-variant")).toBe("block");
643
+ expect(linkIssueSeverity("staging", "no-variant")).toBe("warning");
644
+ expect(linkIssueSeverity("production", "no-variant")).toBe("block");
645
+ });
646
+
647
+ it("a staging build links the target in its own language and reports it (#1240)", () => {
648
+ const missing: string[] = [];
649
+ const resolver = variantIndex("staging").forPage(DE_HOME);
650
+ const out = resolveLinkRefsInHtml(
651
+ `<a href="caelo:page/${EN_SOLO}#team">Solo</a>`,
652
+ resolver,
653
+ missing,
654
+ );
655
+ expect(out).toBe('<a href="/solo/#team">Solo</a>');
656
+ expect(missing).toEqual([]);
657
+ expect(resolver.observed[0]?.resolution).toEqual({
658
+ status: "no-variant",
659
+ variant: "de",
660
+ staged: { url: "/solo/#team", pageId: EN_SOLO },
661
+ });
662
+ });
663
+
664
+ it("the editor preview keeps flagging it: only a staging build links across (#1240)", () => {
665
+ for (const env of ["preview", "production"] as const) {
666
+ expect(variantIndex(env).forPage(DE_HOME).resolve(pageRef(EN_SOLO))).toEqual({
667
+ status: "no-variant",
668
+ variant: "de",
669
+ staged: null,
670
+ });
671
+ }
672
+ });
673
+
674
+ it("names the pages of a variant", () => {
675
+ expect(variantIndex().pagesInVariant("de")).toContain(DE_HOME);
676
+ expect(variantIndex().pagesInVariant("de")).not.toContain(EN_SOLO);
677
+ expect(variantIndex().pagesInVariant("fr")).toEqual([]);
644
678
  });
645
679
 
646
680
  it("maps nothing for a page no plugin has an opinion about, or a render outside a page", () => {
@@ -713,7 +747,7 @@ describe("page variants (link-resolve) — links go to the rendering page's vari
713
747
  templateCss: "",
714
748
  blocks: [],
715
749
  lists,
716
- linkResolver: variantIndex().forPage(DE_ABOUT),
750
+ linkResolver: variantIndex("production").forPage(DE_ABOUT),
717
751
  });
718
752
  expect(unstamp(out.html)).toContain('<a href="/de/ueber/">About</a>');
719
753
  expect(out.moduleFailures).toEqual([
package/src/link-refs.ts CHANGED
@@ -49,7 +49,10 @@
49
49
  * wherever the link lives (module HTML, rich text, link fields, link
50
50
  * lists, nav-menu sets, chrome). A target with no sibling in that
51
51
  * variant is a loud failure (`link-variant-missing:page/<id>:<variant>`),
52
- * never a silent link into another language.
52
+ * never a silent link into another language. One staged exception
53
+ * (maintainer decision on #1240): a staging build links the target in its
54
+ * own language so the staged site stays clickable for review; every such
55
+ * link is reported, and production refuses it.
53
56
  *
54
57
  * Seams for the later rollout steps:
55
58
  * - E (data migration): {@link mapLinkRefsDeep} / the canonicaliser's
@@ -346,8 +349,17 @@ export type LinkResolution =
346
349
  * variant (a German page linking to a page that has no German
347
350
  * version). Not rendered — linking into another variant instead is
348
351
  * exactly the silent fallback CLAUDE.md §2 forbids.
352
+ *
353
+ * The one exception is `staged` (#1240), set only in a staging build:
354
+ * the link goes to the target in its own language so the staged site
355
+ * stays clickable. It is no silent fallback: staging is not public, the
356
+ * build reports every such link, and that report blocks Publish live.
349
357
  */
350
- | { readonly status: "no-variant"; readonly variant: string };
358
+ | {
359
+ readonly status: "no-variant";
360
+ readonly variant: string;
361
+ readonly staged: { readonly url: string; readonly pageId: string } | null;
362
+ };
351
363
 
352
364
  /**
353
365
  * Turns references into URLs for ONE rendering page. Synchronous: the
@@ -443,6 +455,7 @@ export function resolveLinkRefsInHtml(
443
455
  return raw;
444
456
  }
445
457
  if (r.status === "no-variant") {
458
+ if (r.staged !== null) return r.staged.url;
446
459
  missing.push(`${LINK_VARIANT_MISSING}:${linkRefTargetKey(ref)}:${r.variant}`);
447
460
  return raw;
448
461
  }
@@ -456,14 +469,17 @@ export function resolveLinkRefsInHtml(
456
469
  * everywhere; an unpublished one is a warning at Stage and blocks
457
470
  * Publish live / promote. The editor preview shows drafts, so nothing
458
471
  * there is an issue beyond a missing target. A target without a sibling
459
- * in the rendering page's variant counts as missing: there is no page
460
- * the link could go to.
472
+ * in the rendering page's variant is handled like a draft target
473
+ * (maintainer decision on #1240, revising #724): the operator may publish
474
+ * a language version first and translate its targets right after, so a
475
+ * Stage reports it and Publish live blocks. The preview keeps flagging it.
461
476
  */
462
477
  export function linkIssueSeverity(
463
478
  env: LinkRenderEnv,
464
479
  status: LinkResolution["status"],
465
480
  ): "block" | "warning" | null {
466
- if (status === "missing" || status === "no-variant") return "block";
481
+ if (status === "missing") return "block";
482
+ if (status === "no-variant") return env === "staging" ? "warning" : "block";
467
483
  if (status === "unpublished") {
468
484
  if (env === "production") return "block";
469
485
  if (env === "staging") return "warning";
@@ -538,6 +554,11 @@ export interface SiteLinkIndex {
538
554
  * {@link RecordingLinkResolver}.
539
555
  */
540
556
  forPage(renderingPageId: string | null): RecordingLinkResolver;
557
+ /**
558
+ * The pages rendered in `variant`: where a stored value that belongs to
559
+ * one variant, not to a page, shows (a language's own chrome).
560
+ */
561
+ pagesInVariant(variant: string): readonly string[];
541
562
  /** The page's public path (no style applied), or null when unknown. */
542
563
  pathOf(pageId: string): string | null;
543
564
  }
@@ -607,7 +628,17 @@ export function createSiteLinkIndex(input: SiteLinkIndexInput): SiteLinkIndex {
607
628
  if (!pages.has(ref.pageId)) return { status: "missing" };
608
629
  const pageId = pageInVariant(ref.pageId, variant);
609
630
  const page = pageId === null ? undefined : pages.get(pageId);
610
- if (pageId === null || !page) return { status: "no-variant", variant: variant as string };
631
+ if (pageId === null || !page) {
632
+ const referenced = pages.get(ref.pageId);
633
+ return {
634
+ status: "no-variant",
635
+ variant: variant as string,
636
+ staged:
637
+ input.env === "staging" && referenced
638
+ ? { url: pageRefUrl(ref, referenced.path, input.pageUrlStyle), pageId: ref.pageId }
639
+ : null,
640
+ };
641
+ }
611
642
  const url = pageRefUrl(ref, page.path, input.pageUrlStyle);
612
643
  if (input.env !== "preview" && page.status !== "published") {
613
644
  return { status: "unpublished", url, pageId };
@@ -617,6 +648,8 @@ export function createSiteLinkIndex(input: SiteLinkIndexInput): SiteLinkIndex {
617
648
  return {
618
649
  env: input.env,
619
650
  pathOf: (pageId) => pages.get(pageId)?.path ?? null,
651
+ pagesInVariant: (variant) =>
652
+ [...variants].flatMap(([id, v]) => (v.variant === variant && pages.has(id) ? [id] : [])),
620
653
  forPage: (renderingPageId) => {
621
654
  const observed: ObservedLinkResolution[] = [];
622
655
  const variant =
@@ -24,6 +24,13 @@ export type ValueAddress =
24
24
  readonly itemField: string;
25
25
  }
26
26
  | { readonly kind: "pageProp"; readonly pageId: string; readonly field: string }
27
+ | {
28
+ /** An entry of a plugin list source (`{{#name}}`), by its stable entry id. */
29
+ readonly kind: "pluginSource";
30
+ readonly source: string;
31
+ readonly itemId: string;
32
+ readonly field: string;
33
+ }
27
34
  | {
28
35
  readonly kind: "listTypeField";
29
36
  readonly listTypeId: string;
@@ -32,11 +39,14 @@ export type ValueAddress =
32
39
  };
33
40
 
34
41
  const SEG = "[a-z0-9_-]+";
42
+ /** A plugin source's entry id (`list-source-resolution.ts`), wider than a stored id. */
43
+ const SOURCE_ENTRY = "[A-Za-z0-9_.:-]{1,128}";
35
44
  const ADDRESS_RE = new RegExp(
36
45
  `^(?:list/(${SEG})/item/(${SEG})/(${SEG})` +
37
46
  `|instance/(${SEG})/(${SEG})/item/(${SEG})/(${SEG})` +
38
47
  `|page/(${SEG})/props/(${SEG})` +
39
- `|list_type/(${SEG})/node/(${SEG})/(${SEG}))$`,
48
+ `|list_type/(${SEG})/node/(${SEG})/(${SEG})` +
49
+ `|source/(${SEG})/item/(${SOURCE_ENTRY})/(${SEG}))$`,
40
50
  );
41
51
 
42
52
  /** Format an address as its canonical string. */
@@ -48,6 +58,8 @@ export function formatValueAddress(a: ValueAddress): string {
48
58
  return `instance/${a.contentInstanceId}/${a.field}/item/${a.itemId}/${a.itemField}`;
49
59
  case "pageProp":
50
60
  return `page/${a.pageId}/props/${a.field}`;
61
+ case "pluginSource":
62
+ return `source/${a.source}/item/${a.itemId}/${a.field}`;
51
63
  case "listTypeField":
52
64
  return `list_type/${a.listTypeId}/node/${a.node}/${a.field}`;
53
65
  }
@@ -71,5 +83,8 @@ export function parseValueAddress(s: string): ValueAddress | null {
71
83
  if (m[10] && m[11] && m[12]) {
72
84
  return { kind: "listTypeField", listTypeId: m[10], node: m[11], field: m[12] };
73
85
  }
86
+ if (m[13] && m[14] && m[15]) {
87
+ return { kind: "pluginSource", source: m[13], itemId: m[14], field: m[15] };
88
+ }
74
89
  return null;
75
90
  }
@@ -374,6 +374,8 @@ describe("page types and addresses", () => {
374
374
  `instance/${LIST}/features/item/${ITEM}/text`,
375
375
  `page/${PAGE}/props/author`,
376
376
  `list_type/${LIST}/node/entry/label`,
377
+ "source/consent_categories/item/necessary/label",
378
+ "source/consent_vendors/item/tag:abc.1/purpose",
377
379
  ]) {
378
380
  const a = parseValueAddress(s);
379
381
  expect(a).not.toBeNull();
@@ -82,6 +82,25 @@ export function emptyValueOf(field: FieldDef): ScopeValue {
82
82
  }
83
83
  }
84
84
 
85
+ /** The dot paths of a link value ({@link linkValue}): `{{f.href}}`, `{{f.target}}`, `{{f.title}}`. */
86
+ export const LINK_VALUE_KEYS = ["href", "target", "title"] as const;
87
+
88
+ /**
89
+ * A module `link` field's stored value (a URL string or `{ href, target? }`)
90
+ * as a link; no value reads as an empty href. Null for anything else: a
91
+ * shape the field cannot render, which the engine reports.
92
+ */
93
+ export function parseLinkFieldValue(
94
+ raw: unknown,
95
+ ): { readonly href: string; readonly target?: string } | null {
96
+ if (raw === undefined || raw === null) return { href: "" };
97
+ if (typeof raw === "string") return { href: raw };
98
+ if (typeof raw !== "object") return null;
99
+ const { href, target } = raw as { href?: unknown; target?: unknown };
100
+ if (typeof href !== "string") return null;
101
+ return typeof target === "string" ? { href, target } : { href };
102
+ }
103
+
85
104
  /** Scope value of a link: bare = href, plus `href`, `target`, `title` (internal page title). */
86
105
  export function linkValue(
87
106
  v: { readonly href: string; readonly target?: string },
@@ -297,6 +297,14 @@ describe("render dependencies", () => {
297
297
  });
298
298
  });
299
299
 
300
+ it("#1433 — a module link field's internal target is a dependency of the page", () => {
301
+ const ctx = page(PAGE.home);
302
+ ctx.linkScope({ href: "https://example.com/" });
303
+ expect(ctx.deps().pages).toEqual([]);
304
+ ctx.linkScope({ href: `caelo:page/${PAGE.team}` });
305
+ expect(ctx.deps().pages).toEqual([PAGE.team]);
306
+ });
307
+
300
308
  it("records only what the render reached (lazy)", () => {
301
309
  const ctx = page(PAGE.home);
302
310
  const mega = entries(ctx, {
@@ -201,6 +201,8 @@ export interface ListPageContext {
201
201
  resolveField(field: ListFieldSpec, value: unknown, holder: ListHolder): ListFieldResolution;
202
202
  /** `{{page.*}}`: the rendering page as a record scope; null outside a page. */
203
203
  pageScope(): ScopeValue | null;
204
+ /** A module `link` field's value as a scope (`{{f.href}}`, `{{f.title}}`, #1433). */
205
+ linkScope(link: { readonly href: string; readonly target?: string }): ScopeValue;
204
206
  /**
205
207
  * `{{site_text.<key>}}`: the site texts (entries of every list of type
206
208
  * {@link SITE_TEXTS_LIST_TYPE}) in the rendering page's variant. An
@@ -1337,6 +1339,12 @@ function createPageContext(
1337
1339
  pageId,
1338
1340
  resolveField,
1339
1341
  siteTextScope,
1342
+ linkScope: (link) => {
1343
+ // `{{f.title}}` shows the target's title: its edit must rebuild this page.
1344
+ const ref = link.href.length > 0 ? parseLinkRef(link.href) : null;
1345
+ if (ref?.kind === "page") depPages.add(ref.pageId);
1346
+ return linkValue(link, data);
1347
+ },
1340
1348
  breadcrumbTrail: () => trail,
1341
1349
  pageScope: () => {
1342
1350
  if (pageScopeMemo === undefined) {
@@ -0,0 +1,49 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * The Owner setup token between the installer and a Google Cloud admin
5
+ * (#1476). The CLI stores it in Secret Manager as the last step of an install
6
+ * (and on `setup-link`); the admin reads it there when `/setup` is opened and
7
+ * inserts it through `owner_bootstrap_tokens.insert`. Both sides meet on the
8
+ * definitions in this file.
9
+ */
10
+
11
+ import { z } from "zod";
12
+
13
+ /**
14
+ * Secret Manager id of the token. Equals
15
+ * `gcpSecretId(GCP_STACK_ENV, "owner-bootstrap-token")`; provisioning pins that
16
+ * in a test, because the admin must not depend on the provisioning package.
17
+ */
18
+ export const OWNER_BOOTSTRAP_TOKEN_SECRET = "caelo-production-owner-bootstrap-token";
19
+
20
+ /** A token as it is stored: the same shape as self-hosted's `pending-token.json`. */
21
+ export const OwnerBootstrapTokenSchema = z.object({
22
+ token: z.string().regex(/^[0-9a-f]{64}$/),
23
+ expiresAt: z.string().datetime(),
24
+ });
25
+
26
+ /** One Owner bootstrap token and when it stops working. */
27
+ export type OwnerBootstrapToken = z.infer<typeof OwnerBootstrapTokenSchema>;
28
+
29
+ /** Parse a stored token; null when `raw` is not one. */
30
+ export function parseOwnerBootstrapToken(raw: string): OwnerBootstrapToken | null {
31
+ let value: unknown;
32
+ try {
33
+ value = JSON.parse(raw);
34
+ } catch {
35
+ return null;
36
+ }
37
+ const parsed = OwnerBootstrapTokenSchema.safeParse(value);
38
+ return parsed.success ? parsed.data : null;
39
+ }
40
+
41
+ /** The link the Owner opens. `adminUrl` is a bare origin. */
42
+ export function ownerSetupLink(adminUrl: string, token: string): string {
43
+ return `${adminUrl}/setup?token=${token}`;
44
+ }
45
+
46
+ /** The command that gives a late Owner a working link, from any signed-in terminal. */
47
+ export function ownerSetupLinkCommand(projectId: string): string {
48
+ return `bunx @caelo-cms/provisioning setup-link --project ${projectId}`;
49
+ }
@@ -17,6 +17,7 @@
17
17
  */
18
18
 
19
19
  import type { PlannedRedirect, RedirectPlan, RedirectStatusCode } from "./redirect-plan.js";
20
+ import { isExternalRedirectTarget } from "./redirect-target.js";
20
21
 
21
22
  /** Rules per rule set / per route on Front Door Standard and Premium. */
22
23
  export const FRONT_DOOR_MAX_RULES = 100;
@@ -85,6 +86,11 @@ export function frontDoorRedirectRules(plan: RedirectPlan): FrontDoorRedirectRul
85
86
  }
86
87
 
87
88
  function toRule(r: PlannedRedirect, order: number): FrontDoorRedirectRule {
89
+ if (isExternalRedirectTarget(r.location)) {
90
+ throw new Error(
91
+ `redirect-emit-front-door: the redirect ${r.fromPath} → ${r.location} leaves the site, which this rule shape cannot express. External redirects are refused on azure until its publisher exists (#750); delete the row with bulk_delete_redirects.`,
92
+ );
93
+ }
88
94
  const { path, query, fragment } = splitLocation(r.location);
89
95
  return {
90
96
  // Rule names: letters and digits only, starting with a letter.
@@ -22,12 +22,20 @@
22
22
  * would turn linked URLs into 404s without anyone noticing. Going past the
23
23
  * quota is tracked in #751.
24
24
  *
25
+ * An external target (#1358) is the same rule with a `hostRedirect`, and
26
+ * costs the same budget. `pathRedirect` stays set: without it the load
27
+ * balancer keeps the request's path. `httpsRedirect` stays unset: the API
28
+ * refuses it on a TargetHttpsProxy, and the site's plain-http URL map
29
+ * upgrades to https before a request gets here, so the `Location` scheme is
30
+ * https already.
31
+ *
25
32
  * Rules this module owns are recognised by their `urlRedirect` (the stack's
26
33
  * own rules route to a service), so re-applying a plan replaces exactly the
27
34
  * previous plan's rules and keeps everything else in the path matcher.
28
35
  */
29
36
 
30
37
  import type { PlannedRedirect, RedirectPlan, RedirectStatusCode } from "./redirect-plan.js";
38
+ import { isExternalRedirectTarget } from "./redirect-target.js";
31
39
 
32
40
  /** Path rules per path matcher (URL map quota, global external ALB). */
33
41
  export const GCP_URL_MAP_MAX_PATH_RULES = 1000;
@@ -54,6 +62,7 @@ export interface GcpPathRule {
54
62
  readonly paths: readonly string[];
55
63
  readonly service?: string;
56
64
  readonly urlRedirect?: {
65
+ readonly hostRedirect?: string;
57
66
  readonly pathRedirect?: string;
58
67
  readonly redirectResponseCode?: GcpRedirectResponseCode;
59
68
  readonly stripQuery?: boolean;
@@ -107,10 +116,12 @@ function toPathRule(r: PlannedRedirect): GcpPathRule {
107
116
  `redirect-emit-gcp: the redirect ${r.fromPath} → ${r.location} targets a URL with a query string or fragment, which a GCP URL-map redirect cannot carry. Point it at the page's path with bulk_create_redirects (upsert), then publish again.`,
108
117
  );
109
118
  }
119
+ const external = isExternalRedirectTarget(r.location) ? new URL(r.location) : null;
110
120
  return {
111
121
  paths: [...r.matchPaths],
112
122
  urlRedirect: {
113
- pathRedirect: r.location,
123
+ ...(external ? { hostRedirect: external.hostname } : {}),
124
+ pathRedirect: external ? external.pathname : r.location,
114
125
  redirectResponseCode: RESPONSE_CODE[r.statusCode],
115
126
  // The visitor's query string rides along, like on every provider.
116
127
  stripQuery: false,
@@ -292,3 +292,47 @@ describe("Front Door rules", () => {
292
292
  expect(() => frontDoorRedirectRules(planOf(rows))).toThrow(FrontDoorRuleLimitError);
293
293
  });
294
294
  });
295
+
296
+ describe("external targets (#1358)", () => {
297
+ const plan = (location: string) => ({
298
+ redirects: [
299
+ {
300
+ fromPath: "/termin",
301
+ matchPaths: ["/termin", "/termin/"],
302
+ location,
303
+ statusCode: 302 as const,
304
+ preserveQuery: !/[?#]/.test(location),
305
+ },
306
+ ],
307
+ gone: [],
308
+ shadowedByBuild: [],
309
+ });
310
+
311
+ it("Caddy redirects to the absolute address and carries the visitor's query", () => {
312
+ const out = emitCaddyRedirects(plan("https://calendar.example/book"));
313
+ expect(out).toContain("\t/termin https://calendar.example/book{?query} 302");
314
+ });
315
+
316
+ it("a GCP rule sets host and path, and no httpsRedirect (refused on an https proxy)", () => {
317
+ expect(gcpRedirectPathRules(plan("https://calendar.example/book/ab12"))).toEqual([
318
+ {
319
+ paths: ["/termin", "/termin/"],
320
+ urlRedirect: {
321
+ hostRedirect: "calendar.example",
322
+ pathRedirect: "/book/ab12",
323
+ redirectResponseCode: "FOUND",
324
+ stripQuery: false,
325
+ },
326
+ },
327
+ ]);
328
+ });
329
+
330
+ it("a bare host still sets a path: else the load balancer keeps the request's", () => {
331
+ const rule = gcpRedirectPathRules(plan("https://calendar.example"))[0];
332
+ expect(rule?.urlRedirect?.pathRedirect).toBe("/");
333
+ });
334
+
335
+ it("Front Door refuses one instead of emitting a broken rule", () => {
336
+ expect(() => frontDoorRedirectRules(plan("https://calendar.example/"))).toThrow("#750");
337
+ });
338
+ });
@@ -178,3 +178,60 @@ describe("redirectFromPathSpellings", () => {
178
178
  expect(redirectFromPathSpellings("/")).toEqual(["/"]);
179
179
  });
180
180
  });
181
+
182
+ describe("external targets (#1358)", () => {
183
+ const external = (rows: [string, string, number][]) =>
184
+ buildRedirectPlan({
185
+ rows: rows.map(([fromPath, toPath, statusCode]) => ({ fromPath, toPath, statusCode })),
186
+ pageUrlStyle: "directory",
187
+ servedFiles: new Set(["index.html"]),
188
+ });
189
+
190
+ it("keeps the address as approved: no slash added, the visitor's query rides along", () => {
191
+ const plan = external([["/termin", "https://calendar.example/book", 302]]);
192
+ expect(plan.redirects).toEqual([
193
+ {
194
+ fromPath: "/termin",
195
+ matchPaths: ["/termin", "/termin/"],
196
+ location: "https://calendar.example/book",
197
+ statusCode: 302,
198
+ preserveQuery: true,
199
+ },
200
+ ]);
201
+ });
202
+
203
+ it("a target with its own query carries no visitor query", () => {
204
+ const plan = external([["/t", "https://calendar.example/b?gv=true", 302]]);
205
+ expect(plan.redirects[0]?.preserveQuery).toBe(false);
206
+ });
207
+
208
+ it("a chain ends at the address and collapses onto it", () => {
209
+ const plan = external([
210
+ ["/a", "/b", 301],
211
+ ["/b", "https://calendar.example/", 302],
212
+ ]);
213
+ expect(plan.redirects.find((r) => r.fromPath === "/a")).toMatchObject({
214
+ location: "https://calendar.example/",
215
+ statusCode: 302,
216
+ });
217
+ });
218
+
219
+ it("the build still wins, and an address is never an unserved path", () => {
220
+ const plan = external([
221
+ ["/", "https://calendar.example/", 302],
222
+ ["/x", "https://calendar.example/", 302],
223
+ ]);
224
+ expect(plan.shadowedByBuild).toEqual(["/"]);
225
+ expect(redirectsToUnservedPaths(plan, new Set())).toEqual([]);
226
+ });
227
+
228
+ it("refuses a stored row in a form that was never approved", () => {
229
+ expect(() => external([["/x", "http://evil.example/", 302]])).toThrow("must start with '/'");
230
+ expect(() => external([["/x", "https://a@evil.example/", 302]])).toThrow("credentials");
231
+ });
232
+
233
+ it("survives the _redirects file the providers read", () => {
234
+ const rows = [{ fromPath: "/t", toPath: "https://a.example/b?c=d", statusCode: 302 }];
235
+ expect(parseRedirectsFile(formatRedirectsFile(rows))).toEqual(rows);
236
+ });
237
+ });
@@ -30,12 +30,17 @@
30
30
  * `/`; the Location points there directly (the host would otherwise add
31
31
  * a second hop). The visitor's query string is carried over unless the
32
32
  * target has its own query or fragment.
33
+ * - **External targets** (#1358). An Owner-approved `https` address stays
34
+ * exactly as approved: no trailing slash is added, and a chain ends there.
35
+ * A same-site row pointing at a row with an external target collapses to
36
+ * that address in one hop. The visitor's query string rides along under
37
+ * the same rule as for a path.
33
38
  * - **410.** Rows with status 410 become `gone` entries. Layers that can
34
39
  * answer a bare status (Caddy, CloudFront) send 410; the others answer
35
40
  * the 404 a path without a file gets anyway.
36
41
  */
37
42
 
38
- import { redirectTargetIssue } from "./redirect-target.js";
43
+ import { isExternalRedirectTarget, servableRedirectTargetIssue } from "./redirect-target.js";
39
44
  import { trimTrailingSlashes } from "./url.js";
40
45
 
41
46
  /** The redirect statuses the redirects table stores (besides 410). */
@@ -57,7 +62,7 @@ export interface PlannedRedirect {
57
62
  readonly fromPath: string;
58
63
  /** Every request path this entry answers, exactly (`/old`, `/old/`). */
59
64
  readonly matchPaths: readonly string[];
60
- /** The Location header value (a same-site path, see module comment). */
65
+ /** The Location header value: a same-site path or an approved https URL. */
61
66
  readonly location: string;
62
67
  readonly statusCode: RedirectStatusCode;
63
68
  /** Append the request's query string to {@link location}. */
@@ -180,7 +185,7 @@ export function buildRedirectPlan(args: BuildRedirectPlanArgs): RedirectPlan {
180
185
 
181
186
  /**
182
187
  * The planned redirects whose Location is a same-site path the build does
183
- * not serve (#1157). Redirects reach the live site on save, pages only with
188
+ * not serve (#1157; an external address is the destination's business). Redirects reach the live site on save, pages only with
184
189
  * Publish live, so a redirect to a page that is still a draft answers 404 at
185
190
  * its target until that page is published. Callers report these; they are
186
191
  * not an error. Paths under `/api/` are answered by the gateway, not the
@@ -195,6 +200,7 @@ export function redirectsToUnservedPaths(
195
200
  servedFiles: ReadonlySet<string>,
196
201
  ): PlannedRedirect[] {
197
202
  return plan.redirects.filter((r) => {
203
+ if (isExternalRedirectTarget(r.location)) return false;
198
204
  const path = pathBeforeQuery(r.location);
199
205
  if (path === "/api" || path.startsWith("/api/")) return false;
200
206
  if (looksLikeFile(path)) return !servedFiles.has(path.slice(1));
@@ -239,7 +245,7 @@ function normaliseRows(rows: readonly RedirectTableRow[]): NormalisedRow[] {
239
245
  );
240
246
  }
241
247
  if (statusCode !== GONE_STATUS) {
242
- const targetIssue = redirectTargetIssue(toPath);
248
+ const targetIssue = servableRedirectTargetIssue(toPath);
243
249
  if (targetIssue) throw new Error(`redirect-plan: the redirect for ${shown}: ${targetIssue}`);
244
250
  }
245
251
  const bare = stripTrailingSlash(fromPath);
@@ -269,7 +275,7 @@ function collapseChain(
269
275
  for (;;) {
270
276
  // A target with its own query or fragment is a different URL than the
271
277
  // path the next row matches; the chain ends there.
272
- if (/[?#]/.test(target)) break;
278
+ if (/[?#]/.test(target) || isExternalRedirectTarget(target)) break;
273
279
  const next = live.get(stripTrailingSlash(target));
274
280
  if (!next || next.statusCode === GONE_STATUS) break;
275
281
  if (visited.includes(next.bare)) {
@@ -331,6 +337,7 @@ function servedByBuild(bare: string, servedFiles: ReadonlySet<string>): boolean
331
337
  * with an extension in its last segment) and URLs with a query or fragment
332
338
  * stay as they are. */
333
339
  function locationFor(toPath: string, pageUrlStyle: RedirectPageUrlStyle): string {
340
+ if (isExternalRedirectTarget(toPath)) return toPath;
334
341
  if (pageUrlStyle !== "directory" || toPath.endsWith("/")) return toPath;
335
342
  if (/[?#]/.test(toPath) || looksLikeFile(toPath)) return toPath;
336
343
  return `${toPath}/`;