@caelo-cms/shared 0.11.8 → 0.11.10

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 (134) hide show
  1. package/certs/aws-rds-global.pem +2888 -0
  2. package/certs/cloudsql-global.pem +1897 -0
  3. package/dist/ai-tools.d.ts +2 -2
  4. package/dist/body-cap.d.ts +35 -0
  5. package/dist/body-cap.d.ts.map +1 -0
  6. package/dist/body-cap.js +63 -0
  7. package/dist/body-cap.js.map +1 -0
  8. package/dist/build-page.d.ts +4 -4
  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/client-address.d.ts +69 -0
  13. package/dist/client-address.d.ts.map +1 -0
  14. package/dist/client-address.js +99 -0
  15. package/dist/client-address.js.map +1 -0
  16. package/dist/content.d.ts +6 -6
  17. package/dist/content.d.ts.map +1 -1
  18. package/dist/content.js +8 -1
  19. package/dist/content.js.map +1 -1
  20. package/dist/context.d.ts +8 -0
  21. package/dist/context.d.ts.map +1 -1
  22. package/dist/database-tls.d.ts +64 -0
  23. package/dist/database-tls.d.ts.map +1 -0
  24. package/dist/database-tls.js +95 -0
  25. package/dist/database-tls.js.map +1 -0
  26. package/dist/database-url.d.ts +2 -15
  27. package/dist/database-url.d.ts.map +1 -1
  28. package/dist/database-url.js +14 -1
  29. package/dist/database-url.js.map +1 -1
  30. package/dist/index.d.ts +7 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +7 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/interim-forwarded-host.d.ts +15 -0
  35. package/dist/interim-forwarded-host.d.ts.map +1 -0
  36. package/dist/interim-forwarded-host.js +16 -0
  37. package/dist/interim-forwarded-host.js.map +1 -0
  38. package/dist/json-security-headers.d.ts +23 -0
  39. package/dist/json-security-headers.d.ts.map +1 -0
  40. package/dist/json-security-headers.js +53 -0
  41. package/dist/json-security-headers.js.map +1 -0
  42. package/dist/lists/fields.d.ts +6 -0
  43. package/dist/lists/fields.d.ts.map +1 -1
  44. package/dist/lists/fields.js +70 -7
  45. package/dist/lists/fields.js.map +1 -1
  46. package/dist/lists/index.d.ts +1 -0
  47. package/dist/lists/index.d.ts.map +1 -1
  48. package/dist/lists/index.js +1 -0
  49. package/dist/lists/index.js.map +1 -1
  50. package/dist/lists/list-type.d.ts +28 -6
  51. package/dist/lists/list-type.d.ts.map +1 -1
  52. package/dist/lists/list-type.js +43 -15
  53. package/dist/lists/list-type.js.map +1 -1
  54. package/dist/lists/overlay-scope.d.ts +68 -0
  55. package/dist/lists/overlay-scope.d.ts.map +1 -0
  56. package/dist/lists/overlay-scope.js +56 -0
  57. package/dist/lists/overlay-scope.js.map +1 -0
  58. package/dist/lists/query-merge.d.ts +27 -0
  59. package/dist/lists/query-merge.d.ts.map +1 -0
  60. package/dist/lists/query-merge.js +53 -0
  61. package/dist/lists/query-merge.js.map +1 -0
  62. package/dist/lists/resolve.d.ts +1 -0
  63. package/dist/lists/resolve.d.ts.map +1 -1
  64. package/dist/lists/resolve.js +11 -25
  65. package/dist/lists/resolve.js.map +1 -1
  66. package/dist/lists/scope.d.ts +4 -1
  67. package/dist/lists/scope.d.ts.map +1 -1
  68. package/dist/pool-budget.d.ts +10 -0
  69. package/dist/pool-budget.d.ts.map +1 -1
  70. package/dist/pool-budget.js +15 -0
  71. package/dist/pool-budget.js.map +1 -1
  72. package/dist/redirect-emit-gcp.d.ts +16 -8
  73. package/dist/redirect-emit-gcp.d.ts.map +1 -1
  74. package/dist/redirect-emit-gcp.js +22 -11
  75. package/dist/redirect-emit-gcp.js.map +1 -1
  76. package/dist/release-manifest.d.ts +18 -2
  77. package/dist/release-manifest.d.ts.map +1 -1
  78. package/dist/release-manifest.js +32 -4
  79. package/dist/release-manifest.js.map +1 -1
  80. package/dist/session-cookie.d.ts +88 -0
  81. package/dist/session-cookie.d.ts.map +1 -0
  82. package/dist/session-cookie.js +151 -0
  83. package/dist/session-cookie.js.map +1 -0
  84. package/dist/staging-plugin-stub.d.ts +28 -0
  85. package/dist/staging-plugin-stub.d.ts.map +1 -0
  86. package/dist/staging-plugin-stub.js +34 -0
  87. package/dist/staging-plugin-stub.js.map +1 -0
  88. package/dist/template-engine.d.ts.map +1 -1
  89. package/dist/template-engine.js +4 -1
  90. package/dist/template-engine.js.map +1 -1
  91. package/dist/version.d.ts +2 -2
  92. package/dist/version.d.ts.map +1 -1
  93. package/dist/version.js +1 -1
  94. package/dist/version.js.map +1 -1
  95. package/package.json +2 -1
  96. package/src/body-cap.test.ts +44 -0
  97. package/src/body-cap.ts +83 -0
  98. package/src/change-journal.ts +1 -0
  99. package/src/client-address.test.ts +90 -0
  100. package/src/client-address.ts +111 -0
  101. package/src/content.test.ts +54 -0
  102. package/src/content.ts +10 -1
  103. package/src/context.ts +8 -0
  104. package/src/database-tls.test.ts +83 -0
  105. package/src/database-tls.ts +99 -0
  106. package/src/database-url.test.ts +49 -11
  107. package/src/database-url.ts +21 -1
  108. package/src/index.ts +7 -0
  109. package/src/interim-forwarded-host.ts +16 -0
  110. package/src/json-security-headers.test.ts +31 -0
  111. package/src/json-security-headers.ts +53 -0
  112. package/src/lists/fields.ts +88 -7
  113. package/src/lists/index.ts +1 -0
  114. package/src/lists/list-type.ts +53 -18
  115. package/src/lists/lists.test.ts +70 -0
  116. package/src/lists/overlay-scope.test.ts +140 -0
  117. package/src/lists/overlay-scope.ts +120 -0
  118. package/src/lists/pagination.test.ts +15 -0
  119. package/src/lists/query-merge.ts +84 -0
  120. package/src/lists/resolve.test.ts +24 -4
  121. package/src/lists/resolve.ts +12 -33
  122. package/src/lists/scope.ts +4 -2
  123. package/src/pool-budget.test.ts +17 -3
  124. package/src/pool-budget.ts +19 -0
  125. package/src/redirect-emit-gcp.ts +24 -11
  126. package/src/redirect-emit.test.ts +6 -5
  127. package/src/release-manifest.ts +33 -4
  128. package/src/session-cookie.test.ts +96 -0
  129. package/src/session-cookie.ts +163 -0
  130. package/src/staging-plugin-stub.test.ts +23 -0
  131. package/src/staging-plugin-stub.ts +37 -0
  132. package/src/template-engine-lists.test.ts +27 -1
  133. package/src/template-engine.ts +4 -1
  134. package/src/version.ts +1 -1
@@ -72,34 +72,35 @@ describe("databaseUrlFromEnv", () => {
72
72
 
73
73
  it("composes the URL from the plain URL var + its secret-mounted password var (cloud)", () => {
74
74
  const env = {
75
- ADMIN_DATABASE_URL: "postgresql://admin_role@10.20.0.3:5432/cms_admin?sslmode=require",
75
+ ADMIN_DATABASE_URL:
76
+ "postgresql://admin_role@i1.p.europe-west1.sql-psa.goog:5432/cms_admin?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem",
76
77
  ADMIN_DATABASE_PASSWORD: "s3cret",
77
78
  };
78
79
  expect(databaseUrlFromEnv(["ADMIN_DATABASE_URL"], env)).toBe(
79
- "postgresql://admin_role:s3cret@10.20.0.3:5432/cms_admin?sslmode=require",
80
+ "postgresql://admin_role:s3cret@i1.p.europe-west1.sql-psa.goog:5432/cms_admin?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem",
80
81
  );
81
82
  });
82
83
 
83
84
  it("uses the password var that belongs to the URL var it picked", () => {
84
85
  const env = {
85
- PUBLIC_DATABASE_URL: "postgresql://public_role@h:5432/cms_public",
86
+ PUBLIC_DATABASE_URL: "postgresql://public_role@h:5432/cms_public?sslmode=verify-full",
86
87
  PUBLIC_DATABASE_PASSWORD: "pub",
87
88
  // Not consulted: it pairs with PUBLIC_ADMIN_DATABASE_URL, which is unset.
88
89
  PUBLIC_ADMIN_DATABASE_PASSWORD: "adm",
89
90
  };
90
91
  expect(databaseUrlFromEnv(["PUBLIC_ADMIN_DATABASE_URL", "PUBLIC_DATABASE_URL"], env)).toBe(
91
- "postgresql://public_role:pub@h:5432/cms_public",
92
+ "postgresql://public_role:pub@h:5432/cms_public?sslmode=verify-full",
92
93
  );
93
94
  });
94
95
 
95
96
  it("prefers the first URL var that is set", () => {
96
97
  const env = {
97
- PUBLIC_ADMIN_DATABASE_URL: "postgresql://admin_role@h:5432/cms_public",
98
+ PUBLIC_ADMIN_DATABASE_URL: "postgresql://admin_role@h:5432/cms_public?sslmode=verify-full",
98
99
  PUBLIC_ADMIN_DATABASE_PASSWORD: "adm",
99
- PUBLIC_DATABASE_URL: "postgresql://public_role@h:5432/cms_public",
100
+ PUBLIC_DATABASE_URL: "postgresql://public_role@h:5432/cms_public?sslmode=verify-full",
100
101
  };
101
102
  expect(databaseUrlFromEnv(["PUBLIC_ADMIN_DATABASE_URL", "PUBLIC_DATABASE_URL"], env)).toBe(
102
- "postgresql://admin_role:adm@h:5432/cms_public",
103
+ "postgresql://admin_role:adm@h:5432/cms_public?sslmode=verify-full",
103
104
  );
104
105
  });
105
106
 
@@ -111,7 +112,7 @@ describe("databaseUrlFromEnv", () => {
111
112
 
112
113
  it("fails loudly when both the URL and the password var carry a password", () => {
113
114
  const env = {
114
- ADMIN_DATABASE_URL: "postgres://admin_role:inline@h/cms_admin",
115
+ ADMIN_DATABASE_URL: "postgres://admin_role:inline@h/cms_admin?sslmode=verify-full",
115
116
  ADMIN_DATABASE_PASSWORD: "mounted",
116
117
  };
117
118
  expect(() => databaseUrlFromEnv(["ADMIN_DATABASE_URL"], env)).toThrow(
@@ -122,10 +123,47 @@ describe("databaseUrlFromEnv", () => {
122
123
 
123
124
  describe("cloudSqlIamDatabaseUrls", () => {
124
125
  it("logs in as the service account's IAM database user with the token as password", () => {
125
- expect(cloudSqlIamDatabaseUrls("10.0.0.3", "job@p.iam.gserviceaccount.com", "ya29/x")).toEqual({
126
+ expect(
127
+ cloudSqlIamDatabaseUrls(
128
+ "i1.p.europe-west1.sql-psa.goog",
129
+ "job@p.iam.gserviceaccount.com",
130
+ "ya29/x",
131
+ ),
132
+ ).toEqual({
126
133
  user: "job@p.iam",
127
- admin: "postgresql://job%40p.iam:ya29%2Fx@10.0.0.3:5432/cms_admin?sslmode=require",
128
- public: "postgresql://job%40p.iam:ya29%2Fx@10.0.0.3:5432/cms_public?sslmode=require",
134
+ admin:
135
+ "postgresql://job%40p.iam:ya29%2Fx@i1.p.europe-west1.sql-psa.goog:5432/cms_admin?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem",
136
+ public:
137
+ "postgresql://job%40p.iam:ya29%2Fx@i1.p.europe-west1.sql-psa.goog:5432/cms_public?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem",
129
138
  });
130
139
  });
140
+
141
+ it("refuses an IP host: the shared-CA certificate names only the instance's DNS name", () => {
142
+ expect(() => cloudSqlIamDatabaseUrls("10.0.0.3", "job@p.iam.gserviceaccount.com", "t")).toThrow(
143
+ /names only its DNS name.*cms-provision upgrade/,
144
+ );
145
+ });
146
+ });
147
+
148
+ describe("databaseUrlFromEnv TLS (#1338)", () => {
149
+ it("refuses a remote host without verify-full and names the variable", () => {
150
+ for (const mode of ["", "?sslmode=require", "?sslmode=verify-ca", "?sslmode=disable"]) {
151
+ expect(() =>
152
+ databaseUrlFromEnv(["PUBLIC_DATABASE_URL"], {
153
+ PUBLIC_DATABASE_URL: `postgres://public_role:x@postgres:5432/cms_public${mode}`,
154
+ }),
155
+ ).toThrow(/PUBLIC_DATABASE_URL reaches postgres .*verify-full/);
156
+ }
157
+ });
158
+
159
+ it("lets loopback hosts and unix sockets connect without TLS (dev, CI, tests)", () => {
160
+ for (const url of [
161
+ "postgres://a:x@localhost:5432/d",
162
+ "postgres://a:x@127.0.0.1:5541/d",
163
+ "postgres://a:x@[::1]:5432/d",
164
+ "postgres://a:x@sockethost/d?host=/var/run/postgresql",
165
+ ]) {
166
+ expect(databaseUrlFromEnv(["U_URL"], { U_URL: url })).toBe(url);
167
+ }
168
+ });
131
169
  });
@@ -13,9 +13,20 @@
13
13
  * password is a Secret Manager reference, so the password never shows up in
14
14
  * the service's configuration or its revision history.
15
15
  *
16
+ * A URL that reaches a database on another machine must ask for
17
+ * `sslmode=verify-full` (database-tls.ts, #1338); {@link databaseUrlFromEnv}
18
+ * refuses one that does not.
19
+ *
16
20
  * Pure module — no I/O.
17
21
  */
18
22
 
23
+ import {
24
+ CLOUD_SQL_CA_BUNDLE,
25
+ databaseTlsProblem,
26
+ isIpLiteral,
27
+ verifyFullQuery,
28
+ } from "./database-tls.js";
29
+
19
30
  /** The `<NAME>_PASSWORD` var that pairs with a `<NAME>_URL` var. */
20
31
  export function databasePasswordVar(urlVar: string): string {
21
32
  if (!urlVar.endsWith("_URL")) {
@@ -75,6 +86,8 @@ export function databaseUrlFromEnv(
75
86
  for (const urlVar of urlVars) {
76
87
  const url = env[urlVar];
77
88
  if (!url) continue;
89
+ const tls = databaseTlsProblem(url, urlVar);
90
+ if (tls) throw new Error(tls);
78
91
  const passwordVar = databasePasswordVar(urlVar);
79
92
  const password = env[passwordVar];
80
93
  return password ? withDatabasePassword(url, password, `${urlVar} (with ${passwordVar})`) : url;
@@ -87,6 +100,8 @@ export function databaseUrlFromEnv(
87
100
  * how the in-cloud jobs (the operator-access sync job, the upgrader job)
88
101
  * connect: the user is the service account email without
89
102
  * `.gserviceaccount.com`, the password a short-lived OAuth access token.
103
+ * TLS is verify-full against Google's Cloud SQL shared-CA bundle, so `host`
104
+ * must be the instance's DNS name (its certificate names no IP).
90
105
  *
91
106
  * @example
92
107
  * cloudSqlIamDatabaseUrls("10.0.0.3", "job@p.iam.gserviceaccount.com", "ya29.x").user
@@ -97,8 +112,13 @@ export function cloudSqlIamDatabaseUrls(
97
112
  serviceAccountEmail: string,
98
113
  accessToken: string,
99
114
  ): { admin: string; public: string; user: string } {
115
+ if (isIpLiteral(host)) {
116
+ throw new Error(
117
+ `the Cloud SQL host is the IP address ${host}, but the instance's certificate names only its DNS name, so a verify-full connection to it cannot succeed (#1338). Run the converge (\`cms-provision upgrade\`, or Install update for a cloud-setup release) — it moves the services onto the DNS name — then retry.`,
118
+ );
119
+ }
100
120
  const user = serviceAccountEmail.replace(/\.gserviceaccount\.com$/, "");
101
121
  const url = (db: string) =>
102
- `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(accessToken)}@${host}:5432/${db}?sslmode=require`;
122
+ `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(accessToken)}@${host}:5432/${db}?${verifyFullQuery(CLOUD_SQL_CA_BUNDLE)}`;
103
123
  return { admin: url("cms_admin"), public: url("cms_public"), user };
104
124
  }
package/src/index.ts CHANGED
@@ -6,10 +6,12 @@ export * from "./ai-tools.js";
6
6
  export * from "./auth-forms.js";
7
7
  export * from "./auto-update.js";
8
8
  export * from "./base-css.js";
9
+ export * from "./body-cap.js";
9
10
  export * from "./bug-intake.js";
10
11
  export * from "./build-page.js";
11
12
  export * from "./cap-failures.js";
12
13
  export * from "./change-journal.js";
14
+ export * from "./client-address.js";
13
15
  export * from "./cloud-shell-install.js";
14
16
  export * from "./content.js";
15
17
  export * from "./context.js";
@@ -17,6 +19,7 @@ export * from "./css-gradient-scan.js";
17
19
  export * from "./css-scope-scan.js";
18
20
  export * from "./css-var-aliases.js";
19
21
  export * from "./css-var-scan.js";
22
+ export * from "./database-tls.js";
20
23
  export * from "./database-url.js";
21
24
  export * from "./design-draft-shell.js";
22
25
  export * from "./document-language.js";
@@ -33,6 +36,8 @@ export * from "./google-oauth.js";
33
36
  export * from "./id-safe-truncate.js";
34
37
  export * from "./image-capabilities.js";
35
38
  export * from "./interactions.js";
39
+ export * from "./interim-forwarded-host.js";
40
+ export * from "./json-security-headers.js";
36
41
  export * from "./link-canonicalise.js";
37
42
  export * from "./link-refs.js";
38
43
  export * from "./lists/index.js";
@@ -76,11 +81,13 @@ export * from "./run-batched.js";
76
81
  export * from "./safe-keys.js";
77
82
  export * from "./screenshot-capture.js";
78
83
  export * from "./seo.js";
84
+ export * from "./session-cookie.js";
79
85
  export * from "./skills.js";
80
86
  export * from "./snapshots.js";
81
87
  export * from "./source-text-transport.js";
82
88
  export * from "./stage-status.js";
83
89
  export * from "./staging-gate.js";
90
+ export * from "./staging-plugin-stub.js";
84
91
  export * from "./static-cache-policy.js";
85
92
  export * from "./static-security-headers.js";
86
93
  export * from "./strip-cdata.js";
@@ -0,0 +1,16 @@
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";
@@ -0,0 +1,31 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ import { describe, expect, it } from "bun:test";
4
+ import { JSON_SECURITY_HEADERS, withJsonSecurityHeaders } from "./json-security-headers.js";
5
+
6
+ describe("withJsonSecurityHeaders", () => {
7
+ it("adds every header to a JSON answer and keeps one already set", () => {
8
+ const res = withJsonSecurityHeaders(
9
+ new Response("{}", {
10
+ headers: { "content-type": "application/json; charset=utf-8", "referrer-policy": "origin" },
11
+ }),
12
+ );
13
+ expect(res.headers.get("referrer-policy")).toBe("origin");
14
+ expect(res.headers.get("x-frame-options")).toBe(JSON_SECURITY_HEADERS["X-Frame-Options"] ?? "");
15
+ expect(res.headers.get("x-content-type-options")).toBe("nosniff");
16
+ });
17
+
18
+ it("leaves a non-JSON answer as it is", () => {
19
+ const res = withJsonSecurityHeaders(
20
+ new Response("data: x\n\n", { headers: { "content-type": "text/event-stream" } }),
21
+ );
22
+ expect(res.headers.get("x-frame-options")).toBeNull();
23
+ });
24
+
25
+ it("rebuilds an answer with immutable headers around the same body", async () => {
26
+ const upstream = Response.json({ ok: true });
27
+ const res = withJsonSecurityHeaders(upstream);
28
+ expect(res.headers.get("content-security-policy")).toContain("default-src 'none'");
29
+ expect(await res.json()).toEqual({ ok: true });
30
+ });
31
+ });
@@ -0,0 +1,53 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Security headers of a public service's JSON answers (#1326, #763 L2): the
5
+ * visitor gateway's and the MCP-Auth-Proxy's (#1328).
6
+ *
7
+ * A JSON answer is data, never a document: it must not be sniffed into
8
+ * HTML or script, framed, or handed to another origin's page. The headers
9
+ * say so to the browser on every JSON response, whichever route produced
10
+ * it. Pure Web APIs, so both services share the one definition.
11
+ */
12
+
13
+ /** The headers every JSON response carries. */
14
+ export const JSON_SECURITY_HEADERS: Readonly<Record<string, string>> = {
15
+ "X-Content-Type-Options": "nosniff",
16
+ // Nothing in a JSON answer may load or run anything, nor be framed.
17
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
18
+ "X-Frame-Options": "DENY",
19
+ "Referrer-Policy": "no-referrer",
20
+ "Cross-Origin-Resource-Policy": "same-origin",
21
+ };
22
+
23
+ /** Whether `res` is a JSON answer (any `application/json` or `+json` type). */
24
+ export function isJsonResponse(res: Response): boolean {
25
+ const type = (res.headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
26
+ return type === "application/json" || type.endsWith("+json");
27
+ }
28
+
29
+ /** Set the {@link JSON_SECURITY_HEADERS} on `headers`, keeping a value already set. */
30
+ export function addJsonSecurityHeaders(headers: Headers): void {
31
+ for (const [name, value] of Object.entries(JSON_SECURITY_HEADERS)) {
32
+ if (!headers.has(name)) headers.set(name, value);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * `res` with the JSON security headers when it is JSON, else `res` as it
38
+ * is. A response whose headers are immutable (one passed through from a
39
+ * `fetch`) is rebuilt around the same body stream, so a streamed answer
40
+ * stays streamed.
41
+ */
42
+ export function withJsonSecurityHeaders(res: Response): Response {
43
+ if (!isJsonResponse(res)) return res;
44
+ if (Object.keys(JSON_SECURITY_HEADERS).every((h) => res.headers.has(h))) return res;
45
+ try {
46
+ addJsonSecurityHeaders(res.headers);
47
+ return res;
48
+ } catch {
49
+ const headers = new Headers(res.headers);
50
+ addJsonSecurityHeaders(headers);
51
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
52
+ }
53
+ }
@@ -197,8 +197,20 @@ export function validateFieldValue(field: FieldDef, value: unknown, path: string
197
197
  ? [{ path, message: `"${field.name}" is required (${field.type}) — set a value.` }]
198
198
  : [];
199
199
  }
200
- const bad = (expected: string): ListIssue[] => [
201
- { path, message: `"${field.name}" must be ${expected}, got ${describe(value)}.` },
200
+ // #1265 — for an object-shaped value, say WHAT is wrong in it (the Zod
201
+ // issues) instead of "got object", which names nothing to fix.
202
+ const bad = (
203
+ expected: string,
204
+ error?: z.ZodError,
205
+ keyHints?: Readonly<Record<string, string>>,
206
+ ): ListIssue[] => [
207
+ {
208
+ path,
209
+ message:
210
+ error !== undefined && isPlainObject(value)
211
+ ? `"${field.name}" must be ${expected} — ${describeObjectIssues(error, value, keyHints)}.`
212
+ : `"${field.name}" must be ${expected}, got ${describe(value)}.`,
213
+ },
202
214
  ];
203
215
  switch (field.type) {
204
216
  case "text":
@@ -212,7 +224,9 @@ export function validateFieldValue(field: FieldDef, value: unknown, path: string
212
224
  }
213
225
  case "link": {
214
226
  const r = linkValueSchema.safeParse(value);
215
- return r.success ? [] : bad('{ href, target? } (href like "/about" or "https://…")');
227
+ return r.success
228
+ ? []
229
+ : bad('{ href, target? } (href like "/about" or "https://…")', r.error, LINK_KEY_HINTS);
216
230
  }
217
231
  case "media":
218
232
  return typeof value === "string" && MEDIA_REF_RE.test(value)
@@ -238,10 +252,10 @@ export function validateFieldValue(field: FieldDef, value: unknown, path: string
238
252
  : bad("an ISO date YYYY-MM-DD");
239
253
  case "icon":
240
254
  return typeof value === "string" && ICON_RE.test(value) ? [] : bad("an icon name");
241
- case "module":
242
- return embeddedModuleValueSchema.safeParse(value).success
243
- ? []
244
- : bad("{ moduleId, contentInstanceId }");
255
+ case "module": {
256
+ const r = embeddedModuleValueSchema.safeParse(value);
257
+ return r.success ? [] : bad("{ moduleId, contentInstanceId }", r.error);
258
+ }
245
259
  case "term": {
246
260
  if (
247
261
  !Array.isArray(value) ||
@@ -285,6 +299,73 @@ export function checkFieldDef(field: FieldDef, path: string): ListIssue[] {
285
299
  return issues;
286
300
  }
287
301
 
302
+ /** Keys a link value is often written with instead of `href`. */
303
+ const LINK_KEY_HINTS: Readonly<Record<string, string>> = {
304
+ url: "put the address in href",
305
+ link: "put the address in href",
306
+ path: "put the address in href",
307
+ to: "put the address in href",
308
+ label: "the link text is its own field, not part of the link value",
309
+ text: "the link text is its own field, not part of the link value",
310
+ };
311
+
312
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
313
+ return typeof value === "object" && value !== null && !Array.isArray(value);
314
+ }
315
+
316
+ /**
317
+ * The Zod issues of an object value, in the caller's terms: `unknown key
318
+ * "url" (put the address in href), href missing, target must be "_self" |
319
+ * "_blank" (got "new")`.
320
+ */
321
+ export function describeObjectIssues(
322
+ error: z.ZodError,
323
+ value: Record<string, unknown>,
324
+ keyHints: Readonly<Record<string, string>> = {},
325
+ ): string {
326
+ const parts: string[] = [];
327
+ for (const issue of error.issues) {
328
+ const key = issue.path.map(String).join(".");
329
+ const got = issue.path.length > 0 ? value[String(issue.path[0])] : value;
330
+ switch (issue.code) {
331
+ case "unrecognized_keys":
332
+ for (const k of issue.keys) {
333
+ const hint = keyHints[k];
334
+ parts.push(`unknown key "${k}"${hint ? ` (${hint})` : ""}`);
335
+ }
336
+ break;
337
+ case "invalid_type":
338
+ parts.push(
339
+ got === undefined
340
+ ? `${key} missing`
341
+ : `${key} must be a ${issue.expected}, got ${describe(got)}`,
342
+ );
343
+ break;
344
+ case "invalid_value":
345
+ parts.push(
346
+ `${key} must be ${issue.values.map((v) => JSON.stringify(v)).join(" | ")} (got ${describe(got)})`,
347
+ );
348
+ break;
349
+ case "too_small":
350
+ parts.push(
351
+ typeof got === "string" && got.length === 0
352
+ ? `${key} is empty`
353
+ : `${key} must have at least ${String(issue.minimum)} characters`,
354
+ );
355
+ break;
356
+ case "too_big":
357
+ parts.push(`${key} must have at most ${String(issue.maximum)} characters`);
358
+ break;
359
+ case "invalid_format":
360
+ parts.push(`${key} must be a ${issue.format} (got ${describe(got)})`);
361
+ break;
362
+ default:
363
+ parts.push(key.length > 0 ? `${key}: ${issue.message}` : issue.message);
364
+ }
365
+ }
366
+ return parts.length > 0 ? parts.join(", ") : "an object of another shape";
367
+ }
368
+
288
369
  function describe(value: unknown): string {
289
370
  if (Array.isArray(value)) return "an array";
290
371
  if (value === null) return "null";
@@ -8,6 +8,7 @@ export * from "./fields.js";
8
8
  export * from "./item-attr.js";
9
9
  export * from "./items.js";
10
10
  export * from "./list-type.js";
11
+ export * from "./overlay-scope.js";
11
12
  export * from "./page-type.js";
12
13
  export * from "./paginated-render.js";
13
14
  export * from "./pagination.js";
@@ -82,12 +82,60 @@ export type PageQuery = z.infer<typeof pageQuerySchema>;
82
82
  /** Partial query: defaults on a node, or the knobs an entry overrides. */
83
83
  export const pageQueryPartialSchema = pageQuerySchema.partial();
84
84
 
85
+ /** A complete query source, as the AI-facing examples and refusals show it. */
86
+ export const QUERY_SOURCE_EXAMPLE =
87
+ '{kind:"query", defaults:{page_type:"<slug>", order:"published_desc", limit:10}}';
88
+
89
+ /**
90
+ * The same for a paginated field: no `limit` — `paginate.per_page` is the
91
+ * page size, and a limit next to paginate is refused.
92
+ */
93
+ export const PAGINATED_QUERY_SOURCE_EXAMPLE =
94
+ '{kind:"query", defaults:{page_type:"<slug>", order:"published_desc"}} with paginate:{} on the field (no limit; paginate.per_page is the page size)';
95
+
96
+ /**
97
+ * #1281 — the knobs a query source's `defaults` must carry so it renders
98
+ * without any placement value: `order` always, `limit` unless the field
99
+ * is paginated (its page size is the limit). An editable knob is only an
100
+ * override, never a substitute: a placement that does not set it would
101
+ * leave the query incomplete. Returns the AI-actionable refusal, or null.
102
+ *
103
+ * @param where `"paginated"` — a module list field with `paginate`;
104
+ * `"field"` — any other module list field (may opt into paginate);
105
+ * `"node"` — a list-type node (never paginated).
106
+ */
107
+ export function missingQueryDefaults(
108
+ defaults: { readonly order?: unknown; readonly limit?: unknown },
109
+ where: "paginated" | "field" | "node",
110
+ ): string | null {
111
+ const missing: string[] = [];
112
+ if (defaults.order === undefined) {
113
+ missing.push(
114
+ 'order ("published_desc", "published_asc", "title_asc", or "prop_desc:<property>" / "prop_asc:<property>")',
115
+ );
116
+ }
117
+ if (where !== "paginated" && defaults.limit === undefined) {
118
+ missing.push(
119
+ where === "field"
120
+ ? "limit (1–50; for an overview of every matching page instead: no limit and `paginate:{}` on the list field)"
121
+ : "limit (1–50)",
122
+ );
123
+ }
124
+ if (missing.length === 0) return null;
125
+ const example = where === "paginated" ? PAGINATED_QUERY_SOURCE_EXAMPLE : QUERY_SOURCE_EXAMPLE;
126
+ return `a query source needs ${missing.join(" and ")} in source.defaults — e.g. ${example}.`;
127
+ }
128
+
85
129
  export const sourceDefSchema = z.discriminatedUnion("kind", [
86
130
  z
87
131
  .object({
88
132
  kind: z.literal("query"),
89
- /** Which query parts an editor (or the AI) may set per entry/placement. */
90
- editable: z.array(z.enum(QUERY_KNOBS)).max(QUERY_KNOBS.length),
133
+ /**
134
+ * Which query parts an editor (or the AI) may set per entry/placement.
135
+ * Optional, default none (#1304): most sources fix every knob, and a
136
+ * required empty array only produced refused tool calls.
137
+ */
138
+ editable: z.array(z.enum(QUERY_KNOBS)).max(QUERY_KNOBS.length).default([]),
91
139
  defaults: pageQueryPartialSchema,
92
140
  })
93
141
  .strict(),
@@ -227,22 +275,9 @@ export function checkListTypeDef(def: ListTypeDef): ListIssue[] {
227
275
  const q = pageQueryPartialSchema.safeParse(node.source.defaults);
228
276
  if (!q.success) {
229
277
  issues.push({ path: `${at}.source.defaults`, message: "query defaults are invalid." });
230
- } else if (
231
- node.source.defaults.order === undefined &&
232
- !node.source.editable.includes("order")
233
- ) {
234
- issues.push({
235
- path: `${at}.source`,
236
- message: 'a query source needs a default "order" or "order" in editable.',
237
- });
238
- } else if (
239
- node.source.defaults.limit === undefined &&
240
- !node.source.editable.includes("limit")
241
- ) {
242
- issues.push({
243
- path: `${at}.source`,
244
- message: 'a query source needs a default "limit" or "limit" in editable.',
245
- });
278
+ } else {
279
+ const missing = missingQueryDefaults(node.source.defaults, "node");
280
+ if (missing !== null) issues.push({ path: `${at}.source.defaults`, message: missing });
246
281
  }
247
282
  }
248
283
  }
@@ -112,6 +112,44 @@ describe("field values", () => {
112
112
  expect(validateFieldValue(f, v, "p").length === 0).toBe(ok);
113
113
  }
114
114
  });
115
+ // #1265 — an object value that does not fit says what is wrong in it,
116
+ // not just "got object".
117
+ describe("object-shaped values name the problem", () => {
118
+ const link: FieldDef = { name: "link", label: "Link", type: "link" };
119
+ const mod: FieldDef = { name: "cta", label: "CTA", type: "module" };
120
+ const msg = (f: FieldDef, v: unknown) => validateFieldValue(f, v, "p")[0]?.message ?? "";
121
+
122
+ it("unknown key", () => {
123
+ const m = msg(link, { url: "/about" });
124
+ expect(m).toContain('unknown key "url" (put the address in href)');
125
+ expect(m).toContain("href missing");
126
+ expect(m).not.toContain("got object");
127
+ });
128
+ it("href missing", () => {
129
+ expect(msg(link, { target: "_blank" })).toContain("href missing");
130
+ });
131
+ it("target outside the enum", () => {
132
+ expect(msg(link, { href: "/a", target: "new" })).toContain(
133
+ 'target must be "_self" | "_blank" (got "new")',
134
+ );
135
+ });
136
+ it("href of the wrong type or empty", () => {
137
+ expect(msg(link, { href: 5 })).toContain("href must be a string, got number");
138
+ expect(msg(link, { href: "" })).toContain("href is empty");
139
+ });
140
+ it("a non-object still says what it got", () => {
141
+ expect(msg(link, "/about")).toContain('got "/about"');
142
+ });
143
+ it("module value", () => {
144
+ const m = msg(mod, { moduleId: "x" });
145
+ expect(m).toContain("moduleId must be a uuid");
146
+ expect(m).toContain("contentInstanceId missing");
147
+ expect(msg(mod, { moduleId: PAGE, contentInstanceId: ITEM, extra: 1 })).toContain(
148
+ 'unknown key "extra"',
149
+ );
150
+ });
151
+ });
152
+
115
153
  it("rejects reserved names and invalid defaults", () => {
116
154
  expect(checkFieldDef({ name: "is_open", label: "x", type: "boolean" }, "f")).toHaveLength(1);
117
155
  expect(checkFieldDef({ name: "depth", label: "x", type: "number" }, "f")).toHaveLength(1);
@@ -150,6 +188,34 @@ describe("list type definitions", () => {
150
188
  expect(paths).toContain("nodes.column.current_from");
151
189
  expect(paths).toContain("nodes.column");
152
190
  });
191
+ // #1281 — an editable knob is an override, not a default: an entry that
192
+ // does not set it would leave the query incomplete.
193
+ it("requires order and limit in a query node's defaults, naming the fix", () => {
194
+ const withSource = (source: unknown): ListTypeDef =>
195
+ listTypeDefSchema.parse({
196
+ slug: "teasers",
197
+ name: "Teasers",
198
+ purpose: "p",
199
+ role: "content",
200
+ root: { allow: ["news"] },
201
+ nodes: { news: { label: "News", fields: [], source } },
202
+ });
203
+ const issues = checkListTypeDef(
204
+ withSource({ kind: "query", editable: ["order", "limit"], defaults: { page_type: "news" } }),
205
+ );
206
+ expect(issues).toHaveLength(1);
207
+ expect(issues[0]?.path).toBe("nodes.news.source.defaults");
208
+ expect(issues[0]?.message).toContain("needs order");
209
+ expect(issues[0]?.message).toContain("and limit (1–50) in source.defaults");
210
+ expect(
211
+ checkListTypeDef(
212
+ withSource({
213
+ kind: "query",
214
+ defaults: { page_type: "news", order: "published_desc", limit: 3 },
215
+ }),
216
+ ),
217
+ ).toEqual([]);
218
+ });
153
219
  it("requires name+slug on vocabulary entries", () => {
154
220
  const t: ListTypeDef = {
155
221
  slug: "v",
@@ -318,6 +384,10 @@ describe("page types and addresses", () => {
318
384
  });
319
385
 
320
386
  describe("source definitions", () => {
387
+ it("a query source's editable is optional and means none (#1304)", () => {
388
+ const r = sourceDefSchema.parse({ kind: "query", defaults: { order: "title_asc", limit: 5 } });
389
+ expect(r).toEqual({ kind: "query", editable: [], defaults: { order: "title_asc", limit: 5 } });
390
+ });
321
391
  it("a plugin source written as a system source is refused with the plugin form (PR #1121 e2e)", () => {
322
392
  const r = sourceDefSchema.safeParse({ kind: "system", name: "consent_categories" });
323
393
  expect(r.success).toBe(false);