@caelo-cms/shared 0.11.21 → 0.12.2

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 (115) 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/static-security-headers.d.ts +10 -7
  68. package/dist/static-security-headers.d.ts.map +1 -1
  69. package/dist/static-security-headers.js +10 -7
  70. package/dist/static-security-headers.js.map +1 -1
  71. package/dist/template-engine.d.ts +7 -0
  72. package/dist/template-engine.d.ts.map +1 -1
  73. package/dist/template-engine.js +38 -1
  74. package/dist/template-engine.js.map +1 -1
  75. package/dist/template-sections.d.ts +23 -1
  76. package/dist/template-sections.d.ts.map +1 -1
  77. package/dist/template-sections.js +124 -17
  78. package/dist/template-sections.js.map +1 -1
  79. package/dist/version.d.ts +2 -2
  80. package/dist/version.d.ts.map +1 -1
  81. package/dist/version.js +1 -1
  82. package/dist/version.js.map +1 -1
  83. package/package.json +1 -1
  84. package/src/ai-tools.ts +7 -0
  85. package/src/bug-intake.ts +16 -0
  86. package/src/change-journal.ts +1 -0
  87. package/src/context.ts +28 -0
  88. package/src/index.ts +2 -0
  89. package/src/link-refs.test.ts +38 -4
  90. package/src/link-refs.ts +39 -6
  91. package/src/lists/address.ts +16 -1
  92. package/src/lists/lists.test.ts +2 -0
  93. package/src/lists/resolve-values.ts +19 -0
  94. package/src/lists/resolve.test.ts +8 -0
  95. package/src/lists/resolve.ts +8 -0
  96. package/src/owner-setup-token.ts +49 -0
  97. package/src/redirect-emit-front-door.ts +6 -0
  98. package/src/redirect-emit-gcp.ts +12 -1
  99. package/src/redirect-emit.test.ts +44 -0
  100. package/src/redirect-plan.test.ts +57 -0
  101. package/src/redirect-plan.ts +12 -5
  102. package/src/redirect-target.test.ts +110 -4
  103. package/src/redirect-target.ts +142 -8
  104. package/src/seo.test.ts +24 -0
  105. package/src/seo.ts +25 -0
  106. package/src/site-security-headers.test.ts +263 -0
  107. package/src/site-security-headers.ts +509 -0
  108. package/src/staged-site.ts +30 -0
  109. package/src/static-security-headers.test.ts +12 -1
  110. package/src/static-security-headers.ts +10 -7
  111. package/src/template-engine-link-field.test.ts +148 -0
  112. package/src/template-engine-lists.test.ts +1 -1
  113. package/src/template-engine.ts +41 -1
  114. package/src/template-sections.ts +136 -20
  115. package/src/version.ts +1 -1
@@ -1,7 +1,15 @@
1
1
  // SPDX-License-Identifier: MPL-2.0
2
2
 
3
3
  import { describe, expect, it } from "bun:test";
4
- import { redirectTargetIssue, redirectTargetPathSchema } from "./redirect-target.js";
4
+ import {
5
+ externalRedirectHostIssue,
6
+ externalRedirectProviderIssue,
7
+ externalRedirectTargetIssue,
8
+ isExternalRedirectTarget,
9
+ redirectTargetIssue,
10
+ redirectTargetPathSchema,
11
+ servableRedirectTargetIssue,
12
+ } from "./redirect-target.js";
5
13
 
6
14
  describe("redirectTargetIssue (#657)", () => {
7
15
  it.each([
@@ -21,10 +29,10 @@ describe("redirectTargetIssue (#657)", () => {
21
29
  expect(redirectTargetIssue(path)).toBeNull();
22
30
  });
23
31
 
24
- it("rejects a path without a leading slash and says external targets are unsupported", () => {
32
+ it("rejects a path without a leading slash and points at the approved route", () => {
25
33
  const issue = redirectTargetIssue("https://example.com/x");
26
34
  expect(issue).toContain("must start with '/'");
27
- expect(issue).toContain("external (other-domain) redirect targets are not supported");
35
+ expect(issue).toContain("propose_external_redirect");
28
36
  expect(redirectTargetIssue("pricing")).toContain("must start with '/'");
29
37
  });
30
38
 
@@ -56,7 +64,7 @@ describe("redirectTargetIssue (#657)", () => {
56
64
  const issue = redirectTargetIssue(path);
57
65
  expect(issue).toContain("embeds a full URL");
58
66
  expect(issue).toContain(`use its path '${suggested}'`);
59
- expect(issue).toContain("external (other-domain) redirect targets are not supported");
67
+ expect(issue).toContain("propose_external_redirect");
60
68
  });
61
69
 
62
70
  it.each(["/https:/example.com/x", "/https:example.com", "/http:"])(
@@ -89,3 +97,101 @@ describe("redirectTargetPathSchema", () => {
89
97
  expect(redirectTargetPathSchema.safeParse(`/${"a".repeat(500)}`).success).toBe(false);
90
98
  });
91
99
  });
100
+
101
+ describe("externalRedirectTargetIssue (#1358)", () => {
102
+ it.each([
103
+ "https://calendar.example/",
104
+ "https://calendar.example",
105
+ "https://calendar.example/book/ab12",
106
+ "https://a.b.example/x?gv=true&y=1#top",
107
+ "https://xn--bcher-kva.example/x",
108
+ "https://example.com/caf%C3%A9",
109
+ ])("accepts %p", (url) => {
110
+ expect(externalRedirectTargetIssue(url)).toBeNull();
111
+ });
112
+
113
+ it.each([
114
+ ["http://calendar.example/", "https"],
115
+ ["HTTPS://calendar.example/", "https"],
116
+ ["javascript:alert(1)", "https"],
117
+ ["//calendar.example/", "https"],
118
+ ["https:/calendar.example/", "https"],
119
+ ["https://site.example@evil.example/", "credentials"],
120
+ ["https://user:pw@evil.example/", "credentials"],
121
+ ["https://calendar.example:8443/", "port"],
122
+ ["https://127.0.0.1/", "public host"],
123
+ ["https://2130706433/", "public host"],
124
+ ["https://[::1]/", "public host"],
125
+ ["https://localhost/", "public host"],
126
+ ["https://site.example./", "public host"],
127
+ ["https://intranet/", "public host"],
128
+ ["https://db.internal/", "public host"],
129
+ ["https://calendar.example/a/../b", "plain form"],
130
+ ["https://calendar.example/a/%2e%2e/b", "plain form"],
131
+ ["https://CALENDAR.example/", "plain form"],
132
+ ["https://cal%65ndar.example/", "plain form"],
133
+ ["https://bücher.example/", "plain form"],
134
+ ["https://calendar.example/a b", "space"],
135
+ ["https://calendar.example/\\evil", "space"],
136
+ ["https://calendar.example/{x}", "space"],
137
+ ["https://calendar.example/\tx", "space"],
138
+ ["https://calendar.example/\nLocation: https://evil.example", "space"],
139
+ ])("refuses %p", (url, why) => {
140
+ expect(externalRedirectTargetIssue(url)).toContain(why);
141
+ });
142
+
143
+ it("refuses an address longer than a URL map can hold", () => {
144
+ expect(externalRedirectTargetIssue(`https://a.example/${"x".repeat(1000)}`)).toContain(
145
+ "longer",
146
+ );
147
+ });
148
+ });
149
+
150
+ describe("externalRedirectHostIssue (#1358)", () => {
151
+ const hosts = new Map([
152
+ ["site.example", "this site"],
153
+ ["admin.site.example", "the Caelo admin"],
154
+ ]);
155
+
156
+ it("refuses the install's hosts, says which, and passes every other", () => {
157
+ expect(externalRedirectHostIssue("https://site.example/x", hosts)).toContain("is this site");
158
+ expect(externalRedirectHostIssue("https://admin.site.example/", hosts)).toContain("admin");
159
+ expect(externalRedirectHostIssue("https://www.site.example/", hosts)).toBeNull();
160
+ });
161
+ });
162
+
163
+ describe("externalRedirectProviderIssue (#1358)", () => {
164
+ it("serves it on self-hosted and Firebase, query included", () => {
165
+ for (const provider of [undefined, "", "self-hosted", "gcp-firebase"]) {
166
+ expect(externalRedirectProviderIssue("https://a.example/x?y=1#z", provider)).toBeNull();
167
+ }
168
+ });
169
+
170
+ it("serves a plain address on gcp and refuses a query or fragment there", () => {
171
+ expect(externalRedirectProviderIssue("https://a.example/x", "gcp")).toBeNull();
172
+ expect(externalRedirectProviderIssue("https://a.example/x?y=1", "gcp")).toContain("query");
173
+ expect(externalRedirectProviderIssue("https://a.example/x#y", "gcp")).toContain("fragment");
174
+ expect(externalRedirectProviderIssue("https://a.example/x?", "gcp")).toContain("query");
175
+ expect(externalRedirectProviderIssue("https://a.example/x#", "gcp")).toContain("fragment");
176
+ });
177
+
178
+ it("refuses on aws and azure with the issue, and throws on an unknown provider", () => {
179
+ expect(externalRedirectProviderIssue("https://a.example/", "aws")).toContain("/749");
180
+ expect(externalRedirectProviderIssue("https://a.example/", "azure")).toContain("/750");
181
+ expect(() => externalRedirectProviderIssue("https://a.example/", "x")).toThrow("unknown");
182
+ });
183
+ });
184
+
185
+ describe("the two doors (#1358)", () => {
186
+ it("routine writes refuse an external target, serving accepts the approved form only", () => {
187
+ const url = "https://calendar.example/book";
188
+ expect(isExternalRedirectTarget(url)).toBe(true);
189
+ expect(redirectTargetPathSchema.safeParse(url).success).toBe(false);
190
+ expect(redirectTargetIssue(url)).toContain("propose_external_redirect");
191
+ expect(servableRedirectTargetIssue(url)).toBeNull();
192
+ expect(servableRedirectTargetIssue("/a")).toBeNull();
193
+ expect(servableRedirectTargetIssue("http://calendar.example/")).not.toBeNull();
194
+ expect(servableRedirectTargetIssue("https://a@b.example/")).not.toBeNull();
195
+ expect(servableRedirectTargetIssue("//evil.example/")).not.toBeNull();
196
+ });
197
+ });
@@ -1,10 +1,9 @@
1
1
  // SPDX-License-Identifier: MPL-2.0
2
2
 
3
3
  /**
4
- * The one validator for a redirect's TARGET (`toPath`) — issue #657.
4
+ * The validators for a redirect's TARGET (`toPath`) — issues #657, #1358.
5
5
  *
6
- * Caelo redirects only ever point at a path on the same site: the
7
- * `redirects` table has no external-URL field, and every surface that
6
+ * A routine redirect points at a path on the same site. Every surface that
8
7
  * serves the table (the admin's 404 fallback, the generator's
9
8
  * `_redirects` / `_redirects.caddy`, the per-provider emitters) writes
10
9
  * `toPath` verbatim into a `Location` header. "Starts with `/`" is not
@@ -20,10 +19,18 @@
20
19
  * URL, so `/\t/host` collapses to `//host`; the `_redirects` formats
21
20
  * are whitespace-delimited and the emitters already refuse them.
22
21
  *
23
- * Every write path (redirects.create / create_many, page delete with
24
- * `disposition: 'redirect'`, the AI tool schemas, the import composer)
25
- * and every serving path (static generator, admin 404 fallback) calls
26
- * this, so a value rejected at write time can never be served either.
22
+ * Every routine write path (redirects.create / create_many, page delete
23
+ * with `disposition: 'redirect'`, the AI tool schemas, the import composer)
24
+ * calls {@link redirectTargetIssue}, so none of them can store anything but
25
+ * a same-site path.
26
+ *
27
+ * #1358 — the one exception is an `https` address on another domain, written
28
+ * only by `redirects.execute_proposal` after an Owner's approval
29
+ * (CLAUDE.md §11.A). {@link externalRedirectTargetIssue} holds its form: one
30
+ * canonical spelling, so that what the Owner reads is exactly where a
31
+ * browser goes. Serving paths accept both kinds through
32
+ * {@link servableRedirectTargetIssue}, so a value that is neither can never
33
+ * be served.
27
34
  */
28
35
 
29
36
  import { z } from "zod";
@@ -40,7 +47,134 @@ const SCHEME_PREFIX = /^([A-Za-z][A-Za-z0-9+.-]*):/;
40
47
  const WEB_SCHEMES = new Set(["http", "https"]);
41
48
 
42
49
  const EXTERNAL_NOT_SUPPORTED =
43
- "Redirects can only target a path on this site (e.g. '/pricing'); external (other-domain) redirect targets are not supported. If the destination is a page on this site, pass only its path.";
50
+ "This call only takes a path on this site (e.g. '/pricing'). A redirect to another domain needs the Owner's approval: use propose_external_redirect with the https address. If the destination is a page on this site, pass only its path.";
51
+
52
+ /** Longest external target: a URL-map `pathRedirect` holds 1024 characters. */
53
+ const EXTERNAL_REDIRECT_MAX_LENGTH = 1000;
54
+
55
+ /** Characters no serving layer can carry literally, or that hide a URL's meaning. */
56
+ const EXTERNAL_UNSAFE = /[\s\p{Cc}\\{}"`<>^|]/u;
57
+
58
+ /** A host no browser on the internet can reach, or an address instead of a name. */
59
+ const NON_PUBLIC_HOST =
60
+ /^(\[.*\]|\d{1,3}(\.\d{1,3}){3}|localhost|[^.]+|.+\.(localhost|local|internal))$/i;
61
+
62
+ /** True when a stored target is a URL, not a path on this site. */
63
+ export function isExternalRedirectTarget(target: string): boolean {
64
+ return target.startsWith("https://");
65
+ }
66
+
67
+ /**
68
+ * Return why `url` is not a valid external redirect target, or `null` when
69
+ * it is. Only `https`, no credentials, no port, a public host name, and the
70
+ * URL's one canonical spelling: that refuses `https://a.example/x/../y`,
71
+ * `%2e%2e` segments, an upper-case or percent-encoded host and every other
72
+ * form where the text the Owner approves differs from where a browser lands.
73
+ *
74
+ * @example
75
+ * externalRedirectTargetIssue("https://calendar.example/book") // null
76
+ * externalRedirectTargetIssue("https://our.site@evil.example/") // "... credentials ..."
77
+ * externalRedirectTargetIssue("http://calendar.example/") // "... https ..."
78
+ */
79
+ export function externalRedirectTargetIssue(url: string): string | null {
80
+ const shown = JSON.stringify(url);
81
+ if (url.length > EXTERNAL_REDIRECT_MAX_LENGTH) {
82
+ return `The address is longer than ${EXTERNAL_REDIRECT_MAX_LENGTH} characters, which not every hosting can serve. Use a shorter one.`;
83
+ }
84
+ if (!url.startsWith("https://")) {
85
+ return `${shown} must be a full https address (https://example.com/page); other schemes are refused.`;
86
+ }
87
+ if (EXTERNAL_UNSAFE.test(url)) {
88
+ return `${shown} contains a space, a control character or one of \\ { } " \` < > ^ |. Percent-encode it or remove it.`;
89
+ }
90
+ let parsed: URL;
91
+ try {
92
+ parsed = new URL(url);
93
+ } catch {
94
+ return `${shown} is not a valid address.`;
95
+ }
96
+ if (parsed.username !== "" || parsed.password !== "") {
97
+ return `${shown} carries credentials before the host; browsers then go to what follows the '@', not to what the address seems to name. Pass the address without them.`;
98
+ }
99
+ if (parsed.port !== "") {
100
+ return `${shown} names a port, which not every hosting can serve. Use an address on the standard https port.`;
101
+ }
102
+ // A final dot is the same host to DNS, and would pass every host comparison.
103
+ if (parsed.hostname.endsWith(".") || NON_PUBLIC_HOST.test(parsed.hostname)) {
104
+ return `${shown} does not name a public host. Use a domain name; IP addresses and internal names are refused.`;
105
+ }
106
+ if (parsed.href !== url && parsed.href !== `${url}/`) {
107
+ return `${shown} is not in its plain form, so it may lead somewhere else than it reads. A browser reads it as ${parsed.href}: pass that if it is what you mean.`;
108
+ }
109
+ return null;
110
+ }
111
+
112
+ /**
113
+ * Return why an otherwise valid external `url` may not be used on this
114
+ * install: its host is one of the install's own. Compares the parsed,
115
+ * lower-cased host, which is what a browser connects to.
116
+ *
117
+ * @param installHosts lower-case host → what it is ("the Caelo admin", …).
118
+ */
119
+ export function externalRedirectHostIssue(
120
+ url: string,
121
+ installHosts: ReadonlyMap<string, string>,
122
+ ): string | null {
123
+ const host = new URL(url).hostname;
124
+ const what = installHosts.get(host);
125
+ if (what === undefined) return null;
126
+ return what === "this site"
127
+ ? `${host} is this site. Use bulk_create_redirects with the path only.`
128
+ : `${host} is ${what}, which a redirect may not point at.`;
129
+ }
130
+
131
+ /**
132
+ * Return why `provider`'s hosting cannot serve this external target, or
133
+ * `null` when it can. Refused at the proposal, because one rule a provider
134
+ * cannot express would stop the sync of the whole table.
135
+ *
136
+ * - `gcp`: the URL map carries a host and a path. It stores a query in
137
+ * `pathRedirect`, but how the load balancer answers one is unverified, so
138
+ * it stays refused like every target with a query there.
139
+ * - `aws`, `azure`: no publisher exists yet (#749, #750). Their redirect
140
+ * writing must add this when it lands.
141
+ *
142
+ * @param provider `CAELO_PROVIDER`; empty = self-hosted.
143
+ */
144
+ export function externalRedirectProviderIssue(url: string, provider?: string): string | null {
145
+ switch (provider) {
146
+ case undefined:
147
+ case "":
148
+ case "self-hosted":
149
+ case "gcp-firebase":
150
+ return null;
151
+ case "gcp": {
152
+ // The literal characters, as the plan decides: `/book?` has an empty
153
+ // `URL.search`, and one row the emitter refuses stops the whole sync.
154
+ return !/[?#]/.test(url)
155
+ ? null
156
+ : `The GCP load balancer serves an external redirect without a query string or fragment. Use an address without '?…' and '#…', or a short link at the destination.`;
157
+ }
158
+ case "aws":
159
+ case "azure":
160
+ return `Redirects to another domain are not available on ${provider} yet: Caelo has no publisher there (https://github.com/caelo-cms/caelo-cms/issues/${provider === "aws" ? 749 : 750}).`;
161
+ default:
162
+ throw new Error(
163
+ `externalRedirectProviderIssue: unknown CAELO_PROVIDER='${provider}'. Expected one of: self-hosted | gcp | gcp-firebase | aws | azure.`,
164
+ );
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Return why a stored target cannot be served, or `null` when it can: a
170
+ * same-site path, or an external address in its approved form. What serving
171
+ * layers call; write paths call {@link redirectTargetIssue}.
172
+ */
173
+ export function servableRedirectTargetIssue(target: string): string | null {
174
+ return isExternalRedirectTarget(target)
175
+ ? externalRedirectTargetIssue(target)
176
+ : redirectTargetIssue(target);
177
+ }
44
178
 
45
179
  /**
46
180
  * Return why `toPath` is not a safe same-site redirect target, or `null`
package/src/seo.test.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  breadcrumbJsonLdItems,
6
6
  checkPublicSiteBaseUrl,
7
7
  injectSeoIntoHead,
8
+ pickShareImage,
8
9
  renderSeoHead,
9
10
  resolveCanonicalUrl,
10
11
  seoAutofillInputSchema,
@@ -460,3 +461,26 @@ describe("BreadcrumbList JSON-LD (#1142)", () => {
460
461
  expect(breadcrumbJsonLdItems(null, () => null)).toEqual([]);
461
462
  });
462
463
  });
464
+
465
+ describe("#1452 pickShareImage", () => {
466
+ const levels = { page: "own", language: "lang", site: "site" };
467
+
468
+ it("a page's own image wins, then its language, then the site", () => {
469
+ expect(pickShareImage(levels)).toEqual({ source: "page", assetId: "own" });
470
+ expect(pickShareImage({ ...levels, page: null })).toEqual({
471
+ source: "language",
472
+ assetId: "lang",
473
+ });
474
+ expect(pickShareImage({ ...levels, page: null, language: null })).toEqual({
475
+ source: "site",
476
+ assetId: "site",
477
+ });
478
+ });
479
+
480
+ it("with no level set a page has no image", () => {
481
+ expect(pickShareImage({ page: null, language: null, site: null })).toEqual({
482
+ source: "none",
483
+ assetId: null,
484
+ });
485
+ });
486
+ });
package/src/seo.ts CHANGED
@@ -110,6 +110,31 @@ export const siteSeoProposalInputSchema = z
110
110
  );
111
111
  export type SiteSeoProposalInput = z.infer<typeof siteSeoProposalInputSchema>;
112
112
 
113
+ /** Where a page's social-share image comes from (#1452). */
114
+ export const SHARE_IMAGE_SOURCES = ["page", "language", "site", "none"] as const;
115
+ export type ShareImageSource = (typeof SHARE_IMAGE_SOURCES)[number];
116
+
117
+ /**
118
+ * Which image a page's `og:image` shows (#1452). Its own image always wins,
119
+ * then the default of its language (a plugin's answer), then the site
120
+ * default (the active theme's `socialShare` slot). The defaults are stored
121
+ * data the Owner set, read at render time: nothing is copied onto the page,
122
+ * so a page's stored SEO never changes because a default did.
123
+ *
124
+ * @returns the asset to render and where it came from; `none` when no level
125
+ * holds an image, and the page then ships without `og:image`.
126
+ */
127
+ export function pickShareImage(levels: {
128
+ readonly page: string | null;
129
+ readonly language: string | null;
130
+ readonly site: string | null;
131
+ }): { readonly source: ShareImageSource; readonly assetId: string | null } {
132
+ if (levels.page !== null) return { source: "page", assetId: levels.page };
133
+ if (levels.language !== null) return { source: "language", assetId: levels.language };
134
+ if (levels.site !== null) return { source: "site", assetId: levels.site };
135
+ return { source: "none", assetId: null };
136
+ }
137
+
113
138
  /** Result of {@link checkPublicSiteBaseUrl}. */
114
139
  export type PublicSiteBaseUrlCheck = { ok: true; url: string } | { ok: false; message: string };
115
140
 
@@ -0,0 +1,263 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ import { describe, expect, it } from "bun:test";
4
+ import { readFileSync } from "node:fs";
5
+ import { resolve } from "node:path";
6
+ import {
7
+ composeSiteHeaders,
8
+ cspOriginSchema,
9
+ DEFAULT_SITE_SECURITY_POLICY,
10
+ EMPTY_CSP_FACTS,
11
+ emitCaddySiteHeaders,
12
+ enforceBlockers,
13
+ gcpBackendBucketHeaders,
14
+ parseSiteHeaderSet,
15
+ SITE_DOCUMENT_PATH_PATTERN,
16
+ SITE_HEADERS_MAX_BYTES,
17
+ type SiteCspFacts,
18
+ SiteHeadersTooLargeError,
19
+ siteSecurityPolicySchema,
20
+ } from "./site-security-headers.js";
21
+ import { SVG_PATH_PATTERN } from "./static-security-headers.js";
22
+
23
+ const FACTS: SiteCspFacts = {
24
+ ...EMPTY_CSP_FACTS,
25
+ origins: {
26
+ script: ["https://cdn.vendor.com"],
27
+ frame: ["https://www.youtube-nocookie.com"],
28
+ img: ["https://media.example.com"],
29
+ },
30
+ inlineScriptHashes: ["'sha256-abc='"],
31
+ };
32
+
33
+ const manyHashes = (n: number): string[] =>
34
+ Array.from({ length: n }, (_, i) => `'sha256-${String(i).padStart(43, "0")}='`);
35
+
36
+ describe("composeSiteHeaders", () => {
37
+ it("report_only: the full CSP only reports; what cannot break a script is enforced", () => {
38
+ const { headers } = composeSiteHeaders(DEFAULT_SITE_SECURITY_POLICY, FACTS);
39
+ expect(headers["Content-Security-Policy"]).toBe(
40
+ "frame-ancestors 'self'; base-uri 'self'; object-src 'none'",
41
+ );
42
+ const report = headers["Content-Security-Policy-Report-Only"] ?? "";
43
+ expect(report).toContain("script-src 'self' 'sha256-abc=' https://cdn.vendor.com");
44
+ expect(report).toContain("frame-src 'self' https://www.youtube-nocookie.com");
45
+ expect(report).toContain("img-src 'self' data: blob: https://media.example.com");
46
+ });
47
+
48
+ it("no script-src of any mode carries unsafe-inline or unsafe-eval", () => {
49
+ for (const cspMode of ["report_only", "enforce"] as const) {
50
+ const { headers } = composeSiteHeaders({ ...DEFAULT_SITE_SECURITY_POLICY, cspMode }, FACTS);
51
+ const csp =
52
+ headers["Content-Security-Policy-Report-Only"] ?? headers["Content-Security-Policy"] ?? "";
53
+ expect(csp.match(/script-src[^;]*/)?.[0]).not.toContain("unsafe");
54
+ }
55
+ });
56
+
57
+ it("enforce: one CSP, nothing report-only left", () => {
58
+ const { headers } = composeSiteHeaders(
59
+ { ...DEFAULT_SITE_SECURITY_POLICY, cspMode: "enforce" },
60
+ FACTS,
61
+ );
62
+ expect(headers["Content-Security-Policy-Report-Only"]).toBeUndefined();
63
+ expect(headers["Content-Security-Policy"]).toContain("script-src 'self'");
64
+ expect(headers["Content-Security-Policy"]).toContain("frame-ancestors 'self'");
65
+ });
66
+
67
+ it("safe defaults on every install", () => {
68
+ const { headers, hsts } = composeSiteHeaders(DEFAULT_SITE_SECURITY_POLICY, EMPTY_CSP_FACTS);
69
+ expect(headers["Referrer-Policy"]).toBe("strict-origin-when-cross-origin");
70
+ expect(headers["X-Frame-Options"]).toBe("SAMEORIGIN");
71
+ expect(headers["Permissions-Policy"]).toContain("camera=()");
72
+ expect(headers["Permissions-Policy"]).toContain("geolocation=()");
73
+ // Video embeds rely on these.
74
+ expect(headers["Permissions-Policy"]).not.toContain("autoplay");
75
+ expect(headers["Permissions-Policy"]).not.toContain("fullscreen");
76
+ expect(hsts).toBe("max-age=31536000");
77
+ });
78
+
79
+ it("a listed frame ancestor drops X-Frame-Options, which cannot say it", () => {
80
+ const { headers } = composeSiteHeaders(
81
+ { ...DEFAULT_SITE_SECURITY_POLICY, frameAncestors: ["https://partner.example.com"] },
82
+ EMPTY_CSP_FACTS,
83
+ );
84
+ expect(headers["X-Frame-Options"]).toBeUndefined();
85
+ expect(headers["Content-Security-Policy"]).toContain(
86
+ "frame-ancestors 'self' https://partner.example.com",
87
+ );
88
+ });
89
+
90
+ it("an allowed feature is self-only, and extra sources join the derived ones", () => {
91
+ const { headers } = composeSiteHeaders(
92
+ {
93
+ ...DEFAULT_SITE_SECURITY_POLICY,
94
+ allowedFeatures: ["geolocation"],
95
+ extraSources: { connect: ["https://api.vendor.com"] },
96
+ },
97
+ EMPTY_CSP_FACTS,
98
+ );
99
+ expect(headers["Permissions-Policy"]).toContain("geolocation=(self)");
100
+ expect(headers["Content-Security-Policy-Report-Only"]).toContain(
101
+ "connect-src 'self' https://api.vendor.com",
102
+ );
103
+ });
104
+
105
+ it("a document with an object keeps it; max-age 0 sends no HSTS", () => {
106
+ const set = composeSiteHeaders(
107
+ {
108
+ ...DEFAULT_SITE_SECURITY_POLICY,
109
+ hsts: { maxAgeSeconds: 0, includeSubdomains: false, preload: false },
110
+ },
111
+ { ...EMPTY_CSP_FACTS, objectOrigins: ["https://pdf.example.com"] },
112
+ );
113
+ expect(set.headers["Content-Security-Policy"]).toContain("object-src https://pdf.example.com");
114
+ expect(set.hsts).toBeNull();
115
+ });
116
+ });
117
+
118
+ describe("the header budget", () => {
119
+ const facts = { ...EMPTY_CSP_FACTS, inlineScriptHashes: manyHashes(200) };
120
+
121
+ it("enforce refuses a policy that does not fit, naming the way out", () => {
122
+ expect(() =>
123
+ composeSiteHeaders({ ...DEFAULT_SITE_SECURITY_POLICY, cspMode: "enforce" }, facts),
124
+ ).toThrow(SiteHeadersTooLargeError);
125
+ });
126
+
127
+ it("report_only keeps the site building and says so", () => {
128
+ const set = composeSiteHeaders(DEFAULT_SITE_SECURITY_POLICY, facts);
129
+ expect(set.cspCut).toBe(true);
130
+ expect(set.headers["Content-Security-Policy-Report-Only"]).not.toContain("sha256");
131
+ expect(enforceBlockers(set)).toContain("the full CSP does not fit a response header");
132
+ });
133
+
134
+ it("report_only with too many origins drops the report-only header, keeps the baseline", () => {
135
+ const origins = Array.from({ length: 400 }, (_, i) => `https://host${i}.example.com`);
136
+ const set = composeSiteHeaders(DEFAULT_SITE_SECURITY_POLICY, {
137
+ ...EMPTY_CSP_FACTS,
138
+ origins: { img: origins },
139
+ });
140
+ expect(set.cspCut).toBe(true);
141
+ expect(set.headers["Content-Security-Policy-Report-Only"]).toBeUndefined();
142
+ expect(set.headers["Content-Security-Policy"]).toContain("frame-ancestors");
143
+ const bytes = Object.entries(set.headers).reduce((n, [k, v]) => n + k.length + v.length, 0);
144
+ expect(bytes).toBeLessThanOrEqual(SITE_HEADERS_MAX_BYTES);
145
+ });
146
+ });
147
+
148
+ describe("SITE_DOCUMENT_PATH_PATTERN", () => {
149
+ const doc = new RegExp(SITE_DOCUMENT_PATH_PATTERN);
150
+ const svg = new RegExp(SVG_PATH_PATTERN);
151
+
152
+ it.each([
153
+ "/",
154
+ "/about",
155
+ "/about/",
156
+ "/about.html",
157
+ "/a",
158
+ "/ap",
159
+ "/apiary",
160
+ "/apiary/x",
161
+ "/api.html",
162
+ "/de/produkte/",
163
+ "/de/produkte",
164
+ "/de/produkte.html",
165
+ "/v1.2/notes/",
166
+ ])("%s is a document", (path) => {
167
+ expect(doc.test(path)).toBe(true);
168
+ });
169
+
170
+ it.each([
171
+ "/api",
172
+ "/api/",
173
+ "/api/plugin/forms/submit",
174
+ "/_assets/x.0123456789abcdef.js",
175
+ "/_caelo/plugin/a/b.js",
176
+ "/robots.txt",
177
+ "/sitemap.xml",
178
+ "/logo.svg",
179
+ "/a/logo.SVG",
180
+ "/favicon.ico",
181
+ "/data/ips.json",
182
+ ])("%s is not", (path) => {
183
+ expect(doc.test(path)).toBe(false);
184
+ });
185
+
186
+ it("no path matches both it and the SVG entry (Firebase names no winner)", () => {
187
+ for (const path of ["/x.svg", "/a/b.svg", "/x.SVG", "/x.svg/", "/x.svg.html", "/a.b/c.svg"]) {
188
+ expect(doc.test(path) && svg.test(path)).toBe(false);
189
+ }
190
+ });
191
+
192
+ it("uses no RE2-forbidden syntax", () => {
193
+ expect(SITE_DOCUMENT_PATH_PATTERN).not.toMatch(/\(\?[=!<]/);
194
+ });
195
+ });
196
+
197
+ describe("host forms", () => {
198
+ const set = composeSiteHeaders(DEFAULT_SITE_SECURITY_POLICY, FACTS);
199
+
200
+ it("Caddy: on documents only, HSTS included, quoted", () => {
201
+ const snippet = emitCaddySiteHeaders(set);
202
+ expect(snippet).toContain("not path /api/* /_*");
203
+ expect(snippet).toContain("not path *.svg");
204
+ expect(snippet).toContain('header @caelo_documents Referrer-Policy "strict-origin-when');
205
+ expect(snippet).toContain('header @caelo_documents Strict-Transport-Security "max-age=');
206
+ expect(set.headers["Content-Security-Policy-Report-Only"]).not.toContain('"');
207
+ });
208
+
209
+ it("Caddy: refuses a value that would end the string or expand a placeholder", () => {
210
+ for (const bad of ['a"b', "{env.SECRET}", "a\\b", "a\nb"]) {
211
+ const broken = { ...set, headers: { ...set.headers, "X-Frame-Options": bad } };
212
+ expect(() => emitCaddySiteHeaders(broken)).toThrow(/Caddyfile cannot carry/);
213
+ }
214
+ });
215
+
216
+ it("gcp: nosniff first, one Name: value per header", () => {
217
+ const list = gcpBackendBucketHeaders(set);
218
+ expect(list[0]).toBe("X-Content-Type-Options: nosniff");
219
+ expect(list).toContain("X-Frame-Options: SAMEORIGIN");
220
+ expect(list).toContain("Strict-Transport-Security: max-age=31536000");
221
+ });
222
+
223
+ it("a build file round-trips", () => {
224
+ expect(parseSiteHeaderSet(JSON.stringify(set))).toEqual(set);
225
+ });
226
+ });
227
+
228
+ describe("the policy", () => {
229
+ it.each([
230
+ "'unsafe-inline'",
231
+ "'unsafe-eval'",
232
+ "*",
233
+ "data:",
234
+ "https:",
235
+ "http://example.com",
236
+ "https://example.com/path",
237
+ "https://Example.com",
238
+ "https://example.com; script-src *",
239
+ ])("refuses %s as an origin", (value) => {
240
+ expect(cspOriginSchema.safeParse(value).success).toBe(false);
241
+ });
242
+
243
+ it.each(["https://example.com", "https://*.example.com", "wss://a.example.com:8443"])(
244
+ "takes %s",
245
+ (value) => {
246
+ expect(cspOriginSchema.safeParse(value).success).toBe(true);
247
+ },
248
+ );
249
+
250
+ it("the migration stores DEFAULT_SITE_SECURITY_POLICY", () => {
251
+ const sql = readFileSync(
252
+ resolve(
253
+ import.meta.dir,
254
+ "../../migrations/migrations/cms_admin/0639_site_security_headers.sql",
255
+ ),
256
+ "utf8",
257
+ );
258
+ const stored = sql.match(/DEFAULT '(\{[\s\S]*?\})'::jsonb/)?.[1];
259
+ expect(siteSecurityPolicySchema.parse(JSON.parse(stored ?? ""))).toEqual(
260
+ DEFAULT_SITE_SECURITY_POLICY,
261
+ );
262
+ });
263
+ });