@zero2webmaster/starter-kit 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z2w-starter-kit
2
2
 
3
- **Version:** 0.22.0 | **Framework:** 2.19.0
3
+ **Version:** 0.23.0 | **Framework:** 2.19.0
4
4
 
5
5
  > Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
6
6
 
@@ -83,7 +83,8 @@ The Claude Code skill at `~/.claude/skills/instantiate-z2w-project/SKILL.md` and
83
83
 
84
84
  ## Status
85
85
 
86
- - **v0.22.0 (current)** reshapes every emitted `.env.example` / `.env.local` so the line you came to fill in is the one you see. Kerry, 2026-08-16: the `# ── Database (Neon Postgres) ─────…` ruler *"is usually too long and therefore doesn't look like anything useful"*, and eighteen lines of explanation sat between the header and `DATABASE_URL=`. Headers are now a plain `# Database (Neon Postgres)`, and each block leads with its assignments and carries its prose directly underneath. **Per block rather than per file, which was Kerry's call between two readings of his own note** — collecting every variable at the top of the file would put the pooled-connection warning a screen away from the person about to paste the wrong connection string, and that warning only works where it is read. **Not a trim: every explanatory sentence survives, reworded and moved**, and there is a control test that unwraps the comment prose and asserts the load-bearing warnings are all still present, because a layout change is exactly where a paragraph goes missing unnoticed. Verified by loading the emitted file with Node's real dotenv parser — all 13 variables read back — not by grepping the template.
86
+ - **v0.23.0 (current)** makes every scaffolded web app defend its own head. `audit-engine` measured 26 reachable Z2W surfaces on 2026-08-20: **22 carried none of the five baseline security headers**, while `leaderboard` carried five of five — so this was a lift from a passing in-house implementation rather than a design exercise. Every `nextjs` scaffold now emits `lib/security-headers.mjs`, applied to every route by a new `async headers()` in **both** `next.config.mjs` variants, and `cf-pages` goes from two of five to five of five. **The CSP is assembled from the origins the scaffold actually loads**, each gated on the input that ships the feature: Fathom unconditionally, Turnstile in `script-src` *and* `frame-src` when the project takes cards (the widget is an iframe, so allowing only the script leaves an uncompletable card path), Sentry in `connect-src` alone when observability is on. **It ships enforcing rather than Report-Only** — a considered deviation from the retrofit-oriented rule, reasoned in the emitted comments, because a scaffold has no live traffic to break and a header that blocks nothing is just a note asking someone to finish later. Alongside it, `lib/json-ld.ts` closes the `JSON.stringify`-into-a-`<script>` sink: not because the scaffold's own JSON-LD was exploitable (it holds a brand name and an env URL) but because the Pro-SEO extension's *documented example* fed a post title — database content — straight into it, which is the exact stored XSS found live in `z2w-social`. **A scaffold's examples are copied more often than its code is read.** Verified on the artifact: real `next build`, all six headers `curl`-confirmed on a home page, a child page and an API route, and headless Chrome reporting zero CSP violations — with a positive control proving the detector fires.
87
+ - **v0.22.0** reshapes every emitted `.env.example` / `.env.local` so the line you came to fill in is the one you see. Kerry, 2026-08-16: the `# ── Database (Neon Postgres) ─────…` ruler *"is usually too long and therefore doesn't look like anything useful"*, and eighteen lines of explanation sat between the header and `DATABASE_URL=`. Headers are now a plain `# Database (Neon Postgres)`, and each block leads with its assignments and carries its prose directly underneath. **Per block rather than per file, which was Kerry's call between two readings of his own note** — collecting every variable at the top of the file would put the pooled-connection warning a screen away from the person about to paste the wrong connection string, and that warning only works where it is read. **Not a trim: every explanatory sentence survives, reworded and moved**, and there is a control test that unwraps the comment prose and asserts the load-bearing warnings are all still present, because a layout change is exactly where a paragraph goes missing unnoticed. Verified by loading the emitted file with Node's real dotenv parser — all 13 variables read back — not by grepping the template.
87
88
  - **v0.21.0** makes the external audience gate say what actually went wrong. Its refusal named exactly one cause — *"a heading was probably renamed upstream"* — for a state that has two, and `project-creator`, the only consumer that resolves Templates from a version-**pinned** package rather than from Kerry's disk, hits the other one every time: at AGENTS v2.15.0 the `## Keeping This Framework Current` section simply did not exist yet, so every outside-brand scaffold refused in their production while they hunted a rename that never happened. Each gated section now declares the Templates version that first shipped it, the gate derives a minimum from those declarations, and the error distinguishes **version skew** (upgrade Templates) from **unexplained** (fix the section list). The throw is deliberately not softened. Same release: the standards decision log is now gate-aware — a standard whose whole section the gate removed reports `removed-by-audience-gate` instead of `inserted-inline`, because the old log let a preview UI tell an outside customer it had "Skill Vault awareness" in a file that no longer mentioned it; and a new `privateReferences` finding separates a surviving line that *instructs* the reader into the private Skill Vault from one that merely points at a missing section — one hit at Templates v2.18.0 and zero at v2.19.0, which removed that sentence upstream during the same session, demoting the finding into the milder dangling-reference class rather than making the check inert. No emitted file changes by a byte.
88
89
  - **v0.20.0** emits `lib/csv-export.ts` and an enforcing `test/csv-export.test.ts` into **every** Next.js scaffold, with no capability flag. A CSV cell beginning `=`, `+`, `-` or `@` is evaluated as a formula by Excel and Google Sheets, so an unguarded export is code execution on the machine of whoever opens it — arriving through a file the app itself told them to download. A survey of 53 Z2W repos found 1 pass and 12 fail, and all 12 grew their export months after the project was scaffolded, which is why this one ships unconditionally rather than behind a flag: "this app will export CSV" is not knowable at scaffold time the way "this app takes cards" is. The emitted test greps for any file serving `text/csv` that skips the helper, so the guard survives the next person who adds an export. Same release: `scripts/rollup-integrations.mjs` now reads markdown tables and `**We CONSUME:**` headings, recovering 18 real dependency edges the ecosystem map had been missing, with none lost.
89
90
  - **v0.19.1** emits a `:disabled` rule for **buttons** in `app/globals.css`, so a disabled button still looks disabled after the author gives buttons a brand fill. The scaffold ships no button styling of its own, so today the browser's grey rendering still applies — the trap opens on the author's first `background`/`color`, which overrides that grey and leaves `:disabled` a state with no appearance: the button looks pressable, the click does nothing, and the user concludes the app is broken. A sibling Z2W app shipped exactly that across ~50 screens behind a clean typecheck, a green build and 1,051 passing tests, because it is a rendered-pixel property no unit test holds. Includes the `:hover` cancel people forget — a `filter: brightness()` hover happily re-brightens a dimmed button at the moment the user is deciding to click. Verified on real pixels via CDP with `:hover` forced, and canary-verified by stripping the rule from a live scaffold.
@@ -130,4 +131,4 @@ Inquiries: kerry@zero2webmaster.com.
130
131
  ---
131
132
 
132
133
  *Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
133
- *Version: 0.22.0 | Last Updated: 2026-08-20*
134
+ *Version: 0.23.0 | Last Updated: 2026-08-20*
@@ -166,9 +166,37 @@ const HEADERS_TEMPLATE = `# Cloudflare Pages headers for {{slug}}.
166
166
  # Production (live domain): no special header — sitemap + robots.txt govern.
167
167
  # Preview deploys (*.pages.dev): noindex.
168
168
 
169
+ # ── The five-header baseline ─────────────────────────────────────────────
170
+ # Measured by \`audit-engine\` on 2026-08-20: 22 of 26 reachable Z2W surfaces
171
+ # carried NONE of these. They are config-only and none of them can break
172
+ # rendering, so there is no reason for a new site to ship without them.
173
+ #
174
+ # X-Frame-Options is DENY here, not SAMEORIGIN. A brochure site has no reason
175
+ # to frame itself, and DENY is what pairs with \`frame-ancestors 'none'\` below
176
+ # — the two say the same thing to two generations of browser, and shipping one
177
+ # without the other is a silent downgrade on whichever half you dropped. If
178
+ # this site genuinely needs to be embedded, change BOTH.
179
+ #
180
+ # The CSP is ENFORCING rather than Report-Only, which is a deliberate
181
+ # deviation from [[web-security-headers]]. That skill's two-wave rule protects
182
+ # a LIVE app being retrofitted, where a wrong directive is an outage. This site
183
+ # has never been deployed and every origin below is one this scaffold actually
184
+ # emits: Fathom's script, and nothing else. \`'unsafe-inline'\` covers the inline
185
+ # <style> block and the inline JSON-LD block that index.html ships.
186
+ #
187
+ # 🔴 If you add an external script, font, style or beacon, the browser console
188
+ # names the directive that blocked it — add the origin here rather than
189
+ # deleting the policy. To debug a stubborn one, temporarily rename the header
190
+ # to Content-Security-Policy-Report-Only, reproduce, read the console, and put
191
+ # it back. Verify a deploy at https://securityheaders.com.
192
+
169
193
  /*
170
- X-Frame-Options: SAMEORIGIN
194
+ Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
195
+ X-Content-Type-Options: nosniff
196
+ X-Frame-Options: DENY
171
197
  Referrer-Policy: strict-origin-when-cross-origin
198
+ Permissions-Policy: camera=(), microphone=(), geolocation=(), interest-cohort=()
199
+ Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.usefathom.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self'; connect-src 'self' https://cdn.usefathom.com; form-action 'self'; frame-ancestors 'none'; base-uri 'self'; object-src 'none'
172
200
 
173
201
  https://*.pages.dev/*
174
202
  X-Robots-Tag: noindex, nofollow
@@ -185,9 +185,486 @@ export function isIndexableDeployment(env = process.env) {
185
185
  return env.VERCEL_ENV === "production" && canonicalHost(env.NEXT_PUBLIC_SITE_URL) !== "";
186
186
  }
187
187
  `;
188
+ /**
189
+ * The browser-reachable origins this scaffold can actually load, in one place.
190
+ *
191
+ * Each is here because a file this CLI emits references it — not because a
192
+ * checklist mentioned it. A CSP assembled from anything looser than that is
193
+ * either too tight (it blocks a feature we shipped) or too loose (it permits
194
+ * origins nothing asks for), and both failures are invisible until a browser
195
+ * runs the page.
196
+ */
197
+ const FATHOM_ORIGIN = "https://cdn.usefathom.com";
198
+ const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
199
+ // Sentry's ingest host is region-scoped inside the DSN (`o0.ingest.us.sentry.io`,
200
+ // `.de.`, or the bare `.ingest.sentry.io`). A region-specific entry would be
201
+ // silently wrong for a project whose org lives elsewhere — and "silently" is the
202
+ // operative word: a CSP-blocked error report means the reporter goes quiet at
203
+ // exactly the moment something is broken, with nothing in the UI to say so.
204
+ const SENTRY_ORIGIN = "https://*.sentry.io";
205
+ /**
206
+ * Build the emitted `lib/security-headers.mjs`.
207
+ *
208
+ * WHY THIS IS A MODULE AND NOT A LITERAL IN `next.config.mjs`
209
+ * ----------------------------------------------------------
210
+ * Same reason as `lib/seo/canonical-host.mjs`: a value that a test must be able
211
+ * to EXECUTE cannot live inside a config file that only Next.js loads. This repo
212
+ * has shipped a syntactically broken emitted test behind 1,079 green assertions
213
+ * (v0.20.0) and an `og:image` regression behind a passing `toContain` (v0.7.0),
214
+ * both for the same structural reason — `expect(TEMPLATE).toContain(...)` asserts
215
+ * the string we wrote, never the artifact the consumer runs. A standalone module
216
+ * can be imported and called, so the emitted test asserts on a real CSP string
217
+ * built by real code, and so can ours.
218
+ *
219
+ * WHY THE CSP IS ENFORCED RATHER THAN Report-Only — A DELIBERATE DEVIATION
220
+ * -----------------------------------------------------------------------
221
+ * [[web-security-headers]] mandates shipping `Content-Security-Policy-Report-Only`
222
+ * first and flipping to enforcing once watched in a browser. That rule was written
223
+ * from `leaderboard` RETROFITTING a CSP onto a live app, where a wrong directive
224
+ * takes production down and the two-wave dance is what makes it survivable.
225
+ *
226
+ * A scaffold inverts every term of that trade:
227
+ * - There is no live traffic to break. The app has never been deployed.
228
+ * - We KNOW every origin it can reach, because we emitted every file that
229
+ * loads one (the three constants above), and each is gated on the same input
230
+ * that decides whether the feature ships at all.
231
+ * - Report-Only in a scaffold protects nobody. It is a header that blocks
232
+ * nothing plus a comment asking a future author to finish the job — and this
233
+ * project's own doctrine is to make the wrong thing INEXPRESSIBLE rather than
234
+ * to leave a note (the v0.9.0 form primitives, the v0.19.1 `:disabled` rule).
235
+ * `audit-engine` measured 22 of 26 live Z2W surfaces carrying NONE of these
236
+ * five headers, which is what a decade of leaving notes buys.
237
+ * - The failure mode is now loud and early instead of silent and late. An author
238
+ * who adds an external script sees it blocked in their own console on their
239
+ * own machine, on day one, with the directive named in the message.
240
+ *
241
+ * So it ships enforcing, and it is verified the way the skill demands — a real
242
+ * `next build`, a real browser, a real console read — just on our side of the
243
+ * handoff instead of the author's.
244
+ */
245
+ function securityHeadersModule(inputs) {
246
+ const acceptsCards = inputs.acceptsCards === true;
247
+ const hasObservability = inputs.hasObservability === true;
248
+ const pwa = inputs.hasWebUi === true;
249
+ const scriptSrc = ["'self'", "'unsafe-inline'", FATHOM_ORIGIN];
250
+ const connectSrc = ["'self'", FATHOM_ORIGIN];
251
+ const frameSrc = [];
252
+ if (acceptsCards) {
253
+ // Turnstile loads its script AND renders the widget in an iframe. Allowing
254
+ // only the script leaves an invisible checkbox and a card path that cannot
255
+ // be completed -- `default-src 'self'` is what blocks the frame.
256
+ scriptSrc.push(TURNSTILE_ORIGIN);
257
+ frameSrc.push(TURNSTILE_ORIGIN);
258
+ }
259
+ if (hasObservability)
260
+ connectSrc.push(SENTRY_ORIGIN);
261
+ const directives = [
262
+ { name: "default-src", values: ["'self'"], why: "Everything not named below is same-origin only." },
263
+ {
264
+ name: "script-src",
265
+ values: scriptSrc,
266
+ why: "'unsafe-inline' is REQUIRED, not lazy: the App Router injects inline\n" +
267
+ "// hydration and RSC-flight scripts on every page, so the alternative is a\n" +
268
+ "// nonce-issuing middleware -- which a Neon-backed app must keep DB-free to\n" +
269
+ "// preserve scale-to-zero ([[neon-postgres]]). It is acceptable here only\n" +
270
+ "// because this scaffold has no user-controlled HTML sink: the one\n" +
271
+ "// `dangerouslySetInnerHTML` it emits goes through `serializeJsonLd()` in\n" +
272
+ "// lib/json-ld.ts. 🔴 IF YOU ADD A SINK THAT RENDERS USER TEXT, ESCAPING IS\n" +
273
+ "// THE CONTROL AND THIS POLICY IS ONLY DEFENCE IN DEPTH -- 'unsafe-inline'\n" +
274
+ "// permits the injected payload by definition, and even a nonce does not\n" +
275
+ "// help, because a `</script` break-out runs as MARKUP, not as a script.\n" +
276
+ "// See [[json-stringify-is-not-html-escaping]].",
277
+ },
278
+ {
279
+ name: "style-src",
280
+ values: ["'self'", "'unsafe-inline'"],
281
+ why: "Next.js inline styles plus this project's inline brand CSS custom properties.",
282
+ },
283
+ {
284
+ name: "img-src",
285
+ values: ["'self'", "data:", "https:"],
286
+ why: "`data:` covers inline SVG and data-URI icons. `https:` is deliberate\n" +
287
+ "// breadth: the first image an author adds is usually remote, and a\n" +
288
+ "// CSP-blocked <img> reads as a broken build rather than as a policy.",
289
+ },
290
+ { name: "font-src", values: ["'self'"], why: "Self-hosted fonts only. Add the origin here if you adopt a remote font." },
291
+ {
292
+ name: "connect-src",
293
+ values: connectSrc,
294
+ why: "Browser-side fetches. Server-side calls (Neon, Airtable, Stripe, SES)\n" +
295
+ "// never appear in a CSP -- they do not happen in a browser.",
296
+ },
297
+ { name: "form-action", values: ["'self'"], why: "Server Actions post same-origin; nothing should post elsewhere." },
298
+ {
299
+ name: "frame-ancestors",
300
+ values: ["'none'"],
301
+ why: "Clickjacking. Pairs with X-Frame-Options: DENY for older browsers.",
302
+ },
303
+ { name: "base-uri", values: ["'self'"], why: "Stops a <base> tag rewriting every relative URL on the page." },
304
+ { name: "object-src", values: ["'none'"], why: "No Flash/applet/embed surface, ever." },
305
+ ];
306
+ if (frameSrc.length > 0) {
307
+ directives.push({
308
+ name: "frame-src",
309
+ values: frameSrc,
310
+ why: "The Cloudflare Turnstile widget is an iframe. Without this the card path cannot be completed.",
311
+ });
312
+ }
313
+ if (pwa) {
314
+ // worker-src and manifest-src both FALL BACK through child-src/default-src,
315
+ // so 'self' is already permitted and these two lines change no behaviour
316
+ // today. They are stated anyway because the fallback chain is exactly what
317
+ // breaks when a later directive is added -- and a service worker that stops
318
+ // registering is a silent loss of the whole offline story.
319
+ directives.push({ name: "worker-src", values: ["'self'"], why: "The PWA service worker in public/sw.js." }, { name: "manifest-src", values: ["'self'"], why: "public/manifest.json, the thing that makes the app installable." });
320
+ }
321
+ const directiveSource = directives
322
+ // Continuation lines in a multi-line rationale need the same indent as the
323
+ // first, or the emitted object reads as if the comment escaped its entry.
324
+ .map((d) => {
325
+ const why = d.why.split("\n").join("\n ");
326
+ return ` // ${why}\n ${JSON.stringify(d.name)}: [${d.values.map((v) => JSON.stringify(v)).join(", ")}],`;
327
+ })
328
+ .join("\n");
329
+ return `// Security headers for this app, applied to every route by next.config.mjs.
330
+ //
331
+ // Emitted as .mjs deliberately, exactly like lib/seo/canonical-host.mjs:
332
+ // next.config.mjs is plain ESM loaded before any TypeScript exists. tsconfig.json
333
+ // sets \`allowJs: true\`, so test/security-headers.test.ts type-checks it too.
334
+ //
335
+ // Baseline: OWASP Secure Headers + the Z2W standard in [[web-security-headers]],
336
+ // whose reference implementation is the \`leaderboard\` app. Measured by
337
+ // \`audit-engine\` on 2026-08-20: 22 of 26 reachable Z2W surfaces carried NONE of
338
+ // these five headers, and \`leaderboard\` carried five of five. This file is the
339
+ // second half of that -- the baseline arrives with the scaffold instead of with a
340
+ // retrofit session someone has to schedule.
341
+ //
342
+ // 🔴 THE CSP HERE IS ENFORCING, NOT Report-Only, AND THAT IS A CONSIDERED CHOICE.
343
+ // The skill says to ship Report-Only first and flip after watching a browser. That
344
+ // rule protects a LIVE app being retrofitted. This app has never been deployed,
345
+ // and every origin below is one this scaffold actually loads. If you add an
346
+ // external script, style, font, image host or beacon, the browser console names
347
+ // the directive that blocked it -- fix it here rather than deleting the policy.
348
+ // To debug a stubborn one, rename the header below to
349
+ // "Content-Security-Policy-Report-Only", reproduce, read the console, change it
350
+ // back. Verify a deploy with https://securityheaders.com.
351
+
352
+ /**
353
+ * The Content-Security-Policy, one directive per entry.
354
+ *
355
+ * Exported as DATA rather than a finished string so a test can assert on the
356
+ * directive it means, instead of substring-matching a 400-character header and
357
+ * passing for the wrong reason.
358
+ */
359
+ export const cspDirectives = {
360
+ ${directiveSource}
361
+ };
362
+
363
+ /**
364
+ * Serialise the directive map into a CSP header value.
365
+ *
366
+ * @param {Record<string, string[]>} [directives] defaults to cspDirectives
367
+ * @returns {string}
368
+ */
369
+ export function contentSecurityPolicy(directives = cspDirectives) {
370
+ return Object.entries(directives)
371
+ .map(([name, values]) => name + " " + values.join(" "))
372
+ .join("; ");
373
+ }
374
+
375
+ /**
376
+ * The headers applied to every route.
377
+ *
378
+ * HSTS is included even though Vercel already sets it, because this project is
379
+ * meant to survive a move off Vercel ([[portable-stack]]) and a header that
380
+ * exists only by grace of the current host is not part of the app. \`preload\` is
381
+ * inert until the domain is submitted to hstspreload.org, so it is safe to carry.
382
+ */
383
+ export const securityHeaders = [
384
+ { key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains; preload" },
385
+ { key: "X-Content-Type-Options", value: "nosniff" },
386
+ { key: "X-Frame-Options", value: "DENY" },
387
+ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
388
+ { key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=(), interest-cohort=()" },
389
+ { key: "Content-Security-Policy", value: contentSecurityPolicy() },
390
+ ];
391
+ `;
392
+ }
393
+ /**
394
+ * `lib/json-ld.ts` — the one gate every JSON-LD block goes through.
395
+ *
396
+ * WHY THIS IS EMITTED AT ALL, given the scaffold's own JSON-LD is safe.
397
+ * The `organizationJsonLd` block in `app/layout.tsx` is built from a
398
+ * scaffold-time brand name and an env-var site URL, so no user string reaches
399
+ * it and it was never exploitable. What made this worth shipping is that the
400
+ * scaffold TEACHES the shape: the Pro-SEO extension's documented usage example
401
+ * feeds `post.title` -- database content -- straight into
402
+ * `JSON.stringify` inside a `<script>`. That is not a hypothetical; it is the
403
+ * exact live stored XSS `z2w-social` found on 2026-08-14, reachable by any
404
+ * signed-in member against every visitor including an admin.
405
+ *
406
+ * A scaffold's examples are copied more often than its code is read, so an
407
+ * unsafe example is a defect with a wider blast radius than an unsafe function.
408
+ * [[json-stringify-is-not-html-escaping]] §8 names six Z2W repos that should
409
+ * check themselves for it -- all six were scaffolded from patterns this CLI
410
+ * owns, which makes the gate belong here rather than in six retrofits.
411
+ */
412
+ const JSON_LD_MODULE_TEMPLATE = `// The single gate for JSON-LD. Every \`application/ld+json\` block in this app
413
+ // MUST go through \`serializeJsonLd\` -- test/json-ld.test.ts fails the build if one
414
+ // does not.
415
+ //
416
+ // THE MECHANISM, because the fix looks like superstition until you see it:
417
+ // \`JSON.stringify\` escapes what JSON needs escaped -- quotes, backslashes,
418
+ // control characters. It does NOT escape \`<\`, and it is right not to: \`<\` is a
419
+ // legal character in a JSON string. But the HTML parser does not parse JSON.
420
+ // Inside a \`<script>\` element it scans the raw bytes for \`</script\`, and the
421
+ // moment it finds one it ENDS the script and parses the rest as markup. It does
422
+ // not care that the sequence was "inside a string" -- from the parser's position
423
+ // there is no string.
424
+ //
425
+ // JSON.stringify({ name: 'Kerry</scr' + 'ipt><img src=x onerror=alert(1)>' })
426
+ // -> a closed script tag followed by a live <img onerror>, from a display name.
427
+ //
428
+ // JSON-LD is the dangerous sink and the easiest to miss, for three reasons that
429
+ // compound: it is built from database content BY DEFINITION, it looks safe (a
430
+ // serializer inside a script tag -- no concatenation, no interpolation, none of
431
+ // the tells anyone is trained to spot), and nobody ever looks at it again
432
+ // because it exists for crawlers.
433
+ //
434
+ // 🔴 A CSP DOES NOT SAVE YOU HERE, which is why the escaping is the control and
435
+ // lib/security-headers.mjs is only defence in depth: \`'unsafe-inline'\` permits
436
+ // the payload by definition, and even a nonce-based policy would not help --
437
+ // the payload breaks OUT of the script element and runs as markup, not as an
438
+ // inline script.
439
+ //
440
+ // Full mechanism, detection grep and positive-control discipline:
441
+ // [[json-stringify-is-not-html-escaping]].
442
+
443
+ /**
444
+ * Serialise a value for embedding in a \`<script type="application/ld+json">\`.
445
+ *
446
+ * The three replacements are each an EQUIVALENT ENCODING of the same character
447
+ * inside a JSON string, so \`JSON.parse\` round-trips to an identical value and
448
+ * Google, unfurlers and schema validators read exactly what they read before.
449
+ * There is no SEO cost, which is why there is no reason to defer it.
450
+ *
451
+ * - \`<\` -> \`\\\\u003c\` closes the \`</script\` break-out above. Escaping \`<\` alone
452
+ * is sufficient; \`>\` and \`&\` add noise without adding safety.
453
+ * - U+2028 / U+2029 are legal in a JSON string but are LINE TERMINATORS to a
454
+ * JavaScript parser. They break a state-hydration blob rather than a JSON-LD
455
+ * one, but escaping them is free.
456
+ *
457
+ * ⚠️ Written as \`\\\\u2028\` escapes rather than literal characters on purpose. A
458
+ * raw U+2028 in a source file -- even inside the comment that explains it --
459
+ * ends the line as far as esbuild is concerned, and the error it reports points
460
+ * at a line that looks completely fine, because the character is invisible.
461
+ */
462
+ export function serializeJsonLd(data: unknown): string {
463
+ return JSON.stringify(data)
464
+ .replace(/</g, "\\\\u003c")
465
+ .replace(/\\u2028/g, "\\\\u2028")
466
+ .replace(/\\u2029/g, "\\\\u2029");
467
+ }
468
+ `;
469
+ const SECURITY_HEADERS_TEST_TEMPLATE = `/**
470
+ * The security-header baseline, asserted on the module next.config.mjs actually
471
+ * serves rather than on a copy of its values.
472
+ *
473
+ * WHY THESE ASSERTIONS PARSE INSTEAD OF SUBSTRING-MATCHING. A CSP is one long
474
+ * string, so \\\`expect(csp).toContain("'self'")\\\` passes for any directive in the
475
+ * policy -- including a directive you did not mean to check. Worse, a regex like
476
+ * /script-src[^;]*unsafe-inline/ reads as anchored and is not: it happily matches
477
+ * across a directive boundary. So the header is parsed into a map first and every
478
+ * assertion names one directive's OWN value list.
479
+ */
480
+ import { describe, it, expect } from "vitest";
481
+ import { readFileSync } from "node:fs";
482
+ import { join, dirname } from "node:path";
483
+ import { fileURLToPath } from "node:url";
484
+ import { cspDirectives, contentSecurityPolicy, securityHeaders } from "../lib/security-headers.mjs";
485
+
486
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
487
+
488
+ /** Parse a CSP header value into { directive: [values] }. */
489
+ function parseCsp(header: string): Record<string, string[]> {
490
+ const out: Record<string, string[]> = {};
491
+ for (const part of header.split(";")) {
492
+ const bits = part.trim().split(" ").filter(Boolean);
493
+ if (bits.length > 0) out[bits[0]] = bits.slice(1);
494
+ }
495
+ return out;
496
+ }
497
+
498
+ describe("security headers", () => {
499
+ it("serves the five baseline headers", () => {
500
+ const keys = securityHeaders.map((h) => h.key);
501
+ for (const k of [
502
+ "Strict-Transport-Security",
503
+ "X-Content-Type-Options",
504
+ "X-Frame-Options",
505
+ "Referrer-Policy",
506
+ "Permissions-Policy",
507
+ ]) {
508
+ expect(keys).toContain(k);
509
+ }
510
+ });
511
+
512
+ it("ships the CSP ENFORCING, not Report-Only", () => {
513
+ const keys = securityHeaders.map((h) => h.key);
514
+ expect(keys).toContain("Content-Security-Policy");
515
+ // A Report-Only header blocks nothing. If a future change needs to debug the
516
+ // policy, rename it TEMPORARILY -- this test is the thing that stops the
517
+ // temporary rename from becoming permanent.
518
+ expect(keys.filter((k) => k.endsWith("-Report-Only"))).toEqual([]);
519
+ });
520
+
521
+ it("locks the clickjacking pair together", () => {
522
+ // X-Frame-Options: DENY and frame-ancestors 'none' say the same thing to two
523
+ // generations of browser. Shipping one without the other is a silent
524
+ // downgrade on whichever half you dropped.
525
+ const xfo = securityHeaders.find((h) => h.key === "X-Frame-Options");
526
+ expect(xfo?.value).toBe("DENY");
527
+ expect(parseCsp(contentSecurityPolicy())["frame-ancestors"]).toEqual(["'none'"]);
528
+ });
529
+
530
+ it("gives every directive at least one value", () => {
531
+ // A directive present with NO values is not a permissive directive, it is a
532
+ // policy that allows NOTHING for that resource type -- an easy way to take
533
+ // the app down while the header still looks correct.
534
+ for (const [name, values] of Object.entries(cspDirectives)) {
535
+ expect(values.length, name + " has no values").toBeGreaterThan(0);
536
+ }
537
+ });
538
+
539
+ it("keeps every external origin in the directive that needs it", () => {
540
+ const csp = parseCsp(contentSecurityPolicy());
541
+ // Fathom is loaded by lib/analytics/Analytics.tsx, which this project always
542
+ // emits -- it no-ops until NEXT_PUBLIC_FATHOM_SITE_ID is set. If the origin
543
+ // were missing, analytics would break the day someone set that variable,
544
+ // which is the worst possible time to discover it.
545
+ expect(csp["script-src"]).toContain("https://cdn.usefathom.com");
546
+ expect(csp["connect-src"]).toContain("https://cdn.usefathom.com");
547
+ // Nothing external belongs in these two.
548
+ expect(csp["style-src"].filter((v) => v.startsWith("https://"))).toEqual([]);
549
+ expect(csp["form-action"]).toEqual(["'self'"]);
550
+ });
551
+
552
+ it("is the policy next.config.mjs actually applies", () => {
553
+ // The module can be perfect and unwired. This asserts the config imports it
554
+ // and hands it to headers(), which is the only reason any of it reaches a
555
+ // browser.
556
+ const config = readFileSync(join(ROOT, "next.config.mjs"), "utf8");
557
+ expect(config).toContain("./lib/security-headers.mjs");
558
+ expect(config).toContain("securityHeaders");
559
+ expect(config).toContain("async headers()");
560
+ });
561
+
562
+ it("POSITIVE CONTROL: the parser detects a directive it should reject", () => {
563
+ // Without this, deleting an assertion above leaves a suite that passes while
564
+ // measuring nothing. Prove the parser can actually see a bad policy.
565
+ const broken = parseCsp("default-src 'self'; frame-ancestors 'self'");
566
+ expect(broken["frame-ancestors"]).toEqual(["'self'"]);
567
+ expect(broken["frame-ancestors"]).not.toEqual(["'none'"]);
568
+ });
569
+ });
570
+ `;
571
+ const JSON_LD_TEST_TEMPLATE = `/**
572
+ * The JSON-LD gate: no \\\`application/ld+json\\\` block may reach the HTML without
573
+ * going through serializeJsonLd().
574
+ *
575
+ * This exists because the sink is invisible. JSON-LD is built from database
576
+ * content by definition, it looks safe (a serializer inside a script tag), and
577
+ * nobody reads it again because it exists for crawlers. A typecheck, a build, a
578
+ * unit test on its CONTENT and a 200 response all pass while it is exploitable.
579
+ */
580
+ import { describe, it, expect } from "vitest";
581
+ import { readFileSync, readdirSync, existsSync } from "node:fs";
582
+ import { join, dirname } from "node:path";
583
+ import { fileURLToPath } from "node:url";
584
+ import { serializeJsonLd } from "../lib/json-ld";
585
+
586
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
587
+ const HOSTILE = "Kerry</scr" + "ipt><img src=x onerror=alert(1)>";
588
+ const U2028 = String.fromCharCode(0x2028);
589
+
590
+ /** Every source file under the project's own directories. */
591
+ function sourceFiles(dir: string): string[] {
592
+ const abs = join(ROOT, dir);
593
+ if (!existsSync(abs)) return [];
594
+ const out: string[] = [];
595
+ for (const e of readdirSync(abs, { withFileTypes: true })) {
596
+ if (e.name === "node_modules" || e.name.startsWith(".")) continue;
597
+ const rel = join(dir, e.name);
598
+ if (e.isDirectory()) out.push(...sourceFiles(rel));
599
+ else if (e.name.endsWith(".ts") || e.name.endsWith(".tsx")) out.push(rel);
600
+ }
601
+ return out;
602
+ }
603
+
604
+ const FILES = ["app", "lib", "components"].flatMap((d) => sourceFiles(d));
605
+
606
+ describe("JSON-LD escaping gate", () => {
607
+ it("escapes the script-closing sequence", () => {
608
+ const out = serializeJsonLd({ name: HOSTILE });
609
+ expect(out.toLowerCase()).not.toContain("</script");
610
+ });
611
+
612
+ it("round-trips to the identical value, so there is no SEO cost", () => {
613
+ // The escape is an equivalent encoding of the same character inside a JSON
614
+ // string. Crawlers and validators read exactly what they read before, which
615
+ // is why there is never a reason to defer this fix.
616
+ const value = { name: HOSTILE, nested: { list: [HOSTILE, 1, true, null] } };
617
+ expect(JSON.parse(serializeJsonLd(value))).toEqual(value);
618
+ });
619
+
620
+ it("escapes the JavaScript line terminators", () => {
621
+ const out = serializeJsonLd({ t: "a" + U2028 + "b" });
622
+ expect(out).not.toContain(U2028);
623
+ });
624
+
625
+ it("no source file injects JSON.stringify straight into HTML", () => {
626
+ // The gate only works if every call site uses it. This is what catches the
627
+ // NEXT JSON-LD block somebody adds by copying one from a tutorial.
628
+ const offenders = FILES.filter((f) =>
629
+ readFileSync(join(ROOT, f), "utf8").includes("__html: JSON.stringify"),
630
+ );
631
+ expect(offenders).toEqual([]);
632
+ });
633
+
634
+ it("every ld+json surface routes through the gate", () => {
635
+ const surfaces = FILES.filter((f) =>
636
+ readFileSync(join(ROOT, f), "utf8").includes("application/ld+json"),
637
+ );
638
+ // If this is empty the check measured nothing -- the scaffold ships one in
639
+ // app/layout.tsx, so zero means the file moved and this test went blind.
640
+ expect(surfaces.length).toBeGreaterThan(0);
641
+ for (const f of surfaces) {
642
+ expect(readFileSync(join(ROOT, f), "utf8"), f + " bypasses serializeJsonLd").toContain(
643
+ "serializeJsonLd",
644
+ );
645
+ }
646
+ });
647
+
648
+ it("no source file contains a raw U+2028", () => {
649
+ // A literal U+2028 ends the line as far as esbuild is concerned, and the
650
+ // error it reports points at a line that looks completely fine because the
651
+ // character is invisible. The hazard can break the module documenting it.
652
+ const offenders = FILES.filter((f) => readFileSync(join(ROOT, f), "utf8").includes(U2028));
653
+ expect(offenders).toEqual([]);
654
+ });
655
+
656
+ it("POSITIVE CONTROL: the unfixed serializer IS detected", () => {
657
+ // If this ever fails, the checks above cannot see the bug they exist for and
658
+ // every one of them is decorative.
659
+ const preFix = (d: unknown) => JSON.stringify(d);
660
+ expect(preFix({ name: HOSTILE }).toLowerCase()).toContain("</script");
661
+ });
662
+ });
663
+ `;
188
664
  const NEXT_CONFIG_TEMPLATE = `/** @type {import('next').NextConfig} */
189
665
 
190
666
  import { canonicalHost } from "./lib/seo/canonical-host.mjs";
667
+ import { securityHeaders } from "./lib/security-headers.mjs";
191
668
 
192
669
  // SEO: redirect EVERY auto-assigned PRODUCTION *.vercel.app alias to the custom
193
670
  // domain so none is crawled as an indexable duplicate of the whole site
@@ -215,6 +692,12 @@ const isVercelProduction = process.env.VERCEL_ENV === "production";
215
692
 
216
693
  const nextConfig = {
217
694
  reactStrictMode: true,
695
+ // Every route, including API responses (harmless there) and static assets.
696
+ // Applied from lib/security-headers.mjs so test/security-headers.test.ts can
697
+ // EXECUTE the same values this config serves, rather than re-describing them.
698
+ async headers() {
699
+ return [{ source: "/:path*", headers: securityHeaders }];
700
+ },
218
701
  async redirects() {
219
702
  const host = canonicalHost(process.env.NEXT_PUBLIC_SITE_URL);
220
703
  // Only in production, and only once a real custom domain is configured.
@@ -247,6 +730,8 @@ export default nextConfig;
247
730
  */
248
731
  const NEXT_CONFIG_HOST_ROUTED_TEMPLATE = `/** @type {import('next').NextConfig} */
249
732
 
733
+ import { securityHeaders } from "./lib/security-headers.mjs";
734
+
250
735
  // HOST-ROUTED MULTI-TENANT APP — the incoming Host selects the tenant.
251
736
  //
252
737
  // NOTE the deliberate ABSENCE of the *.vercel.app → custom-domain alias redirect
@@ -259,6 +744,12 @@ const NEXT_CONFIG_HOST_ROUTED_TEMPLATE = `/** @type {import('next').NextConfig}
259
744
 
260
745
  const nextConfig = {
261
746
  reactStrictMode: true,
747
+ // Every route, including API responses (harmless there) and static assets.
748
+ // Applied from lib/security-headers.mjs so test/security-headers.test.ts can
749
+ // EXECUTE the same values this config serves, rather than re-describing them.
750
+ async headers() {
751
+ return [{ source: "/:path*", headers: securityHeaders }];
752
+ },
262
753
  };
263
754
 
264
755
  export default nextConfig;
@@ -2642,6 +3133,7 @@ const APP_LAYOUT_TEMPLATE = `// Root layout — SEO baseline wiring per Z2W stan
2642
3133
 
2643
3134
  import type { Metadata, Viewport } from "next";
2644
3135
  import { Analytics } from "@/lib/analytics/Analytics";
3136
+ import { serializeJsonLd } from "@/lib/json-ld";
2645
3137
 
2646
3138
  // Global styles. Body typography (18px / 1.5, per the standing Zero2Webmaster
2647
3139
  // readability rule) lives in this file, NOT as an inline style on <body>, so
@@ -2696,9 +3188,14 @@ export default function RootLayout({ children }: { children: React.ReactNode })
2696
3188
  {/* Canonical URLs are emitted per page by Next.js's Metadata API via
2697
3189
  \`alternates.canonical\` — do NOT add a literal canonical link here,
2698
3190
  it would produce a SECOND, conflicting canonical on every page. */}
3191
+ {/* Routed through serializeJsonLd (lib/json-ld.ts), NOT bare
3192
+ JSON.stringify. This particular object holds only a scaffold-time
3193
+ brand name and an env-var URL, so nothing user-controlled reaches
3194
+ it today -- but this is the block every future JSON-LD gets copied
3195
+ from, and the copy WILL carry database content. See the module. */}
2699
3196
  <script
2700
3197
  type="application/ld+json"
2701
- dangerouslySetInnerHTML={{ __html: JSON.stringify(organizationJsonLd) }}
3198
+ dangerouslySetInnerHTML={{ __html: serializeJsonLd(organizationJsonLd) }}
2702
3199
  />
2703
3200
  </head>
2704
3201
  <body>
@@ -3540,6 +4037,10 @@ export function scaffoldNextjs(inputs, opts) {
3540
4037
  path: "lib/seo/canonical-host.mjs",
3541
4038
  content: sub(CANONICAL_HOST_MODULE_TEMPLATE, inputs, opts, spec),
3542
4039
  },
4040
+ { path: "lib/security-headers.mjs", content: securityHeadersModule(inputs) },
4041
+ { path: "lib/json-ld.ts", content: JSON_LD_MODULE_TEMPLATE },
4042
+ { path: "test/security-headers.test.ts", content: SECURITY_HEADERS_TEST_TEMPLATE },
4043
+ { path: "test/json-ld.test.ts", content: JSON_LD_TEST_TEMPLATE },
3543
4044
  {
3544
4045
  path: "lib/seo/page-metadata.ts",
3545
4046
  content: sub(PAGE_METADATA_MODULE_TEMPLATE, inputs, opts, spec),
@@ -54,7 +54,7 @@ function jsonLdHelpers() {
54
54
  //
55
55
  // Usage (Next.js App Router):
56
56
  //
57
- // import { articleJsonLd } from "@/seo/json-ld";
57
+ // import { articleJsonLd, serializeJsonLd } from "@/seo/json-ld";
58
58
  // export default function Page() {
59
59
  // const ld = articleJsonLd({
60
60
  // headline: "Post title",
@@ -63,8 +63,47 @@ function jsonLdHelpers() {
63
63
  // image: "https://example.com/og.png",
64
64
  // url: "https://example.com/posts/post-title",
65
65
  // });
66
- // return <>{/* page body */}<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(ld) }} /></>;
66
+ // return <>{/* page body */}<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: serializeJsonLd(ld) }} /></>;
67
67
  // }
68
+ //
69
+ // 🔴 SERIALIZE WITH \`serializeJsonLd\`, NEVER WITH BARE \`JSON.stringify\`. These
70
+ // builders are fed CONTENT -- \`headline: post.title\`, an author name, a product
71
+ // description -- so they are fed DATABASE CONTENT, which makes them
72
+ // user-controlled by construction rather than by accident.
73
+ //
74
+ // \`JSON.stringify\` escapes what JSON needs escaped and does NOT escape \`<\`,
75
+ // correctly, because \`<\` is legal in a JSON string. But the HTML parser does not
76
+ // parse JSON: inside a <script> element it scans the raw bytes for \`</script\` and
77
+ // ENDS the element the moment it finds one, parsing the rest as markup. A headline
78
+ // containing that sequence closes the tag and runs whatever follows it.
79
+ // \`z2w-social\` found exactly this live on 2026-08-14 -- stored XSS reachable by
80
+ // any signed-in member against every visitor, admins included -- and it had passed
81
+ // a typecheck, a build, unit tests on the JSON-LD content, and a 200 response,
82
+ // because a serializer inside a script tag reads as the handled path.
83
+ //
84
+ // A CSP does not save you: \`'unsafe-inline'\` permits it by definition, and even a
85
+ // nonce does not, because the payload runs as MARKUP rather than as a script.
86
+ // Escaping is the control. See [[json-stringify-is-not-html-escaping]].
87
+
88
+ /**
89
+ * Serialise a JSON-LD object for embedding in a <script> tag.
90
+ *
91
+ * Each replacement is an equivalent encoding of the same character inside a JSON
92
+ * string, so \`JSON.parse\` round-trips identically and crawlers, unfurlers and
93
+ * schema validators read exactly what they read before. There is no SEO cost,
94
+ * which is why there is no reason to defer it.
95
+ *
96
+ * U+2028/U+2029 are legal in JSON but are line terminators to a JavaScript
97
+ * parser. Written as escapes, never as literal characters: a raw U+2028 ends the
98
+ * line as far as esbuild is concerned, and the error it reports points at a line
99
+ * that looks completely fine because the character is invisible.
100
+ */
101
+ export function serializeJsonLd(data: unknown): string {
102
+ return JSON.stringify(data)
103
+ .replace(/</g, "\\\\u003c")
104
+ .replace(/\\u2028/g, "\\\\u2028")
105
+ .replace(/\\u2029/g, "\\\\u2029");
106
+ }
68
107
 
69
108
  export interface ArticleJsonLdInput {
70
109
  headline: string;
@@ -713,7 +752,7 @@ Add the following to your \`package.json\` scripts:
713
752
  ${inputs.projectType === "nextjs"
714
753
  ? `\`\`\`tsx
715
754
  // app/posts/[slug]/page.tsx
716
- import { articleJsonLd } from "@/seo/json-ld";
755
+ import { articleJsonLd, serializeJsonLd } from "@/seo/json-ld";
717
756
 
718
757
  export default async function PostPage({ params }: { params: { slug: string } }) {
719
758
  const post = await loadPost(params.slug);
@@ -727,9 +766,12 @@ export default async function PostPage({ params }: { params: { slug: string } })
727
766
  return (
728
767
  <article>
729
768
  {/* ... post body ... */}
769
+ {/* serializeJsonLd, never bare JSON.stringify: \`post.title\` is database
770
+ content, and JSON.stringify does not escape the \`</script\` sequence
771
+ that ends the element. See the note in src/seo/json-ld.ts. */}
730
772
  <script
731
773
  type="application/ld+json"
732
- dangerouslySetInnerHTML={{ __html: JSON.stringify(ld) }}
774
+ dangerouslySetInnerHTML={{ __html: serializeJsonLd(ld) }}
733
775
  />
734
776
  </article>
735
777
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.",
5
5
  "author": {
6
6
  "name": "Dr. Kerry Kriger",