@zero2webmaster/starter-kit 0.19.1 → 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 +8 -4
- package/dist/audience.d.ts +108 -0
- package/dist/audience.js +132 -0
- package/dist/scaffolders/cf-pages.js +29 -1
- package/dist/scaffolders/common.d.ts +1 -1
- package/dist/scaffolders/common.js +20 -12
- package/dist/scaffolders/nextjs.js +733 -15
- package/dist/scaffolders/node-service.js +10 -7
- package/dist/scaffolders/pro-seo-extension.js +46 -4
- package/dist/scaffolders/python-service.js +3 -2
- package/dist/standards.d.ts +28 -1
- package/dist/summary.js +45 -2
- package/dist/writer.d.ts +14 -0
- package/dist/writer.js +53 -7
- package/package.json +1 -1
- package/scripts/rollup-integrations.mjs +107 -7
|
@@ -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;
|
|
@@ -487,6 +978,207 @@ const TSCONFIG_TEMPLATE = `{
|
|
|
487
978
|
* costs bundle size) but the STATED CONSEQUENCE was wrong, so the emitted
|
|
488
979
|
* comment says what was actually measured. Reported back to grantor.
|
|
489
980
|
*/
|
|
981
|
+
/**
|
|
982
|
+
* CSV export, with the spreadsheet-formula guard built in.
|
|
983
|
+
*
|
|
984
|
+
* WHY THIS IS EMITTED UNCONDITIONALLY, and why that is the unusual choice here.
|
|
985
|
+
*
|
|
986
|
+
* `audit-engine` surveyed 53 repos on 2026-08-15 against clones refreshed to live
|
|
987
|
+
* HEAD and found CSV export to be the portfolio's weakest surface: **1 pass, 12
|
|
988
|
+
* fail**. Every one of `backup-engine`, `contest-management`, `file-server`,
|
|
989
|
+
* `grantor`, `z2w-admin-suite`, `z2w-ai-suite`, `z2w-board-suite`, `z2w-forms`,
|
|
990
|
+
* `z2w-multi-lingual`, `z2w-science-suite`, `z2w-seller-suite` and `audit-engine`
|
|
991
|
+
* itself writes untrusted text into a CSV with no leading-character guard.
|
|
992
|
+
* `z2w-member-match`'s `src/lib/csv-export.ts` is the single pass, and this file
|
|
993
|
+
* is that module, ported.
|
|
994
|
+
*
|
|
995
|
+
* Every other conditional standard this scaffolder emits gates on something
|
|
996
|
+
* knowable at scaffold time — `acceptsCards`, `sendsEmail`, `hasWebUi`. **"This
|
|
997
|
+
* app will export CSV" is not knowable at scaffold time**, and that is the whole
|
|
998
|
+
* argument: all 12 grew their export MONTHS after instantiation, which is exactly
|
|
999
|
+
* the moment someone reaches for `.join(",")` and nobody is thinking about
|
|
1000
|
+
* spreadsheets. A flag would have protected none of them. It is 37 dependency-free
|
|
1001
|
+
* lines, pure and DB-free, so the cost of shipping it to a project that never
|
|
1002
|
+
* exports anything is a file nobody imports.
|
|
1003
|
+
*
|
|
1004
|
+
* The threat is not theoretical and is not XSS: a cell beginning `=`, `+`, `-` or
|
|
1005
|
+
* `@` is evaluated as a FORMULA by Excel and Google Sheets when the file is opened,
|
|
1006
|
+
* so `=cmd|'/c calc'!A1` in a name field is code execution on the admin's laptop,
|
|
1007
|
+
* arriving through a file our own app told them to download. The guard fires on the
|
|
1008
|
+
* LEADING character only, so `a=b`, `1-2` and `O'Brien` all survive byte-identical.
|
|
1009
|
+
*/
|
|
1010
|
+
const CSV_EXPORT_TEMPLATE = `/**
|
|
1011
|
+
* CSV serialization for exports.
|
|
1012
|
+
*
|
|
1013
|
+
* Pure and DB-free so it can be unit-tested without a database, and so it can sit
|
|
1014
|
+
* behind any route handler, server action or script that needs to hand a person a
|
|
1015
|
+
* spreadsheet.
|
|
1016
|
+
*
|
|
1017
|
+
* ⚠️ THE LEADING-CHARACTER GUARD IS THE POINT — do not "simplify" it away.
|
|
1018
|
+
* A field beginning \`=\`, \`+\`, \`-\` or \`@\` is interpreted by Excel and Google
|
|
1019
|
+
* Sheets as a FORMULA, not as text. So a name recorded as \`=cmd|'/c calc'!A1\`
|
|
1020
|
+
* becomes code execution on the machine of whoever opens the export — through a
|
|
1021
|
+
* file this app told them to download. Prefixing with a single quote makes the
|
|
1022
|
+
* spreadsheet treat the cell as text and is invisible in the rendered sheet.
|
|
1023
|
+
*
|
|
1024
|
+
* Anything a user, an importer or an upstream system of record put into your
|
|
1025
|
+
* database is untrusted input for this purpose, which in practice is every column
|
|
1026
|
+
* worth exporting.
|
|
1027
|
+
*/
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* Quote one CSV field per RFC 4180, with the spreadsheet-formula guard applied first.
|
|
1031
|
+
*
|
|
1032
|
+
* Order matters: the guard runs BEFORE quoting, so a field that needs both gets the
|
|
1033
|
+
* apostrophe INSIDE the quotes where the spreadsheet will see it.
|
|
1034
|
+
*/
|
|
1035
|
+
export function csvField(value: unknown): string {
|
|
1036
|
+
if (value === null || value === undefined) return "";
|
|
1037
|
+
let s = String(value);
|
|
1038
|
+
// Leading character only — "a=b", "1-2" and "O'Brien" must pass through untouched.
|
|
1039
|
+
// Tab and carriage return are in the class because a leading one of either can
|
|
1040
|
+
// still start a formula once the spreadsheet trims the cell.
|
|
1041
|
+
if (/^[=+\\-@\\t\\r]/.test(s)) s = "'" + s;
|
|
1042
|
+
if (/[",\\r\\n]/.test(s)) s = '"' + s.replace(/"/g, '""') + '"';
|
|
1043
|
+
return s;
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
/**
|
|
1047
|
+
* Serialize rows to a complete CSV document.
|
|
1048
|
+
*
|
|
1049
|
+
* Emits CRLF line endings and a trailing newline per RFC 4180, and a UTF-8 BOM so
|
|
1050
|
+
* Excel on Windows renders non-ASCII names correctly instead of mojibake. The BOM
|
|
1051
|
+
* is not decoration — without it, any name outside ASCII arrives visibly corrupted
|
|
1052
|
+
* for the largest group of people who will ever open one of these files.
|
|
1053
|
+
*/
|
|
1054
|
+
export function toCsv(headers: string[], rows: unknown[][]): string {
|
|
1055
|
+
const lines = [headers.map(csvField).join(",")];
|
|
1056
|
+
for (const row of rows) lines.push(row.map(csvField).join(","));
|
|
1057
|
+
return "\\uFEFF" + lines.join("\\r\\n") + "\\r\\n";
|
|
1058
|
+
}
|
|
1059
|
+
`;
|
|
1060
|
+
/**
|
|
1061
|
+
* The emitted enforcement half of the CSV standard.
|
|
1062
|
+
*
|
|
1063
|
+
* Same doctrine as the form-standards test: a helper that makes the right thing
|
|
1064
|
+
* easy is not a guarantee — only a test fails the build on the NEXT export someone
|
|
1065
|
+
* hand-rolls. `audit-engine` made this point about their own adoption in the same
|
|
1066
|
+
* message: they added a test asserting the writer actually *calls* the guard,
|
|
1067
|
+
* "a helper nobody calls is not a fix."
|
|
1068
|
+
*
|
|
1069
|
+
* So this file does two jobs, and the second is the load-bearing one:
|
|
1070
|
+
* 1. behaviour — the guard fires where it should and, just as importantly, does
|
|
1071
|
+
* NOT fire on `a=b` / `1-2` / `O'Brien`;
|
|
1072
|
+
* 2. a source grep that fails when a route hands back `text/csv` without going
|
|
1073
|
+
* through `csvField`. That is the check that catches the export written in
|
|
1074
|
+
* six months by someone who never read this file.
|
|
1075
|
+
*/
|
|
1076
|
+
const CSV_EXPORT_TEST_TEMPLATE = `/**
|
|
1077
|
+
* CSV export standard, enforced as tests rather than as a convention someone has
|
|
1078
|
+
* to remember.
|
|
1079
|
+
*
|
|
1080
|
+
* The rule: **every value written into a CSV goes through \`csvField()\`.** A cell
|
|
1081
|
+
* beginning \`=\`, \`+\`, \`-\` or \`@\` is a FORMULA to Excel and Google Sheets, so an
|
|
1082
|
+
* unguarded export is code execution on the machine of whoever opens it.
|
|
1083
|
+
*
|
|
1084
|
+
* Measured across the {{brand_name}} portfolio on 2026-08-15: of 13 repos with a
|
|
1085
|
+
* CSV writer, ONE had the guard. This test is here so this project stays that one.
|
|
1086
|
+
*/
|
|
1087
|
+
import { describe, it, expect } from "vitest";
|
|
1088
|
+
import { readFileSync, readdirSync, existsSync } from "node:fs";
|
|
1089
|
+
import { join, dirname } from "node:path";
|
|
1090
|
+
import { fileURLToPath } from "node:url";
|
|
1091
|
+
import { csvField, toCsv } from "../lib/csv-export";
|
|
1092
|
+
|
|
1093
|
+
// NOT \`__dirname\` — this package is "type": "module", where it is undefined.
|
|
1094
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
1095
|
+
|
|
1096
|
+
/** Every .ts/.tsx file under the project's own source directories. */
|
|
1097
|
+
function sourceFiles(dir: string): string[] {
|
|
1098
|
+
const abs = join(ROOT, dir);
|
|
1099
|
+
if (!existsSync(abs)) return [];
|
|
1100
|
+
const out: string[] = [];
|
|
1101
|
+
for (const e of readdirSync(abs, { withFileTypes: true })) {
|
|
1102
|
+
if (e.name === "node_modules" || e.name.startsWith(".")) continue;
|
|
1103
|
+
const rel = join(dir, e.name);
|
|
1104
|
+
if (e.isDirectory()) out.push(...sourceFiles(rel));
|
|
1105
|
+
else if (/\\.tsx?$/.test(e.name)) out.push(rel);
|
|
1106
|
+
}
|
|
1107
|
+
return out;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
const SOURCES = [...sourceFiles("app"), ...sourceFiles("lib"), ...sourceFiles("components")];
|
|
1111
|
+
const read = (f: string) => readFileSync(join(ROOT, f), "utf8");
|
|
1112
|
+
|
|
1113
|
+
describe("csvField: the spreadsheet-formula guard", () => {
|
|
1114
|
+
it("prefixes the four formula-starting characters", () => {
|
|
1115
|
+
for (const dangerous of ["=1+1", "+1", "-1", "@SUM(A1)", "=cmd|'/c calc'!A1"]) {
|
|
1116
|
+
expect(csvField(dangerous)).toBe("'" + dangerous);
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
|
|
1120
|
+
it("🔴 CONTROL — leaves ordinary text that merely CONTAINS those characters alone", () => {
|
|
1121
|
+
// The guard is on the LEADING character. A rule that fired anywhere would
|
|
1122
|
+
// corrupt real data — and a corrupted export is a silent bug, because nobody
|
|
1123
|
+
// diffs a spreadsheet against the database.
|
|
1124
|
+
for (const fine of ["a=b", "1-2", "O'Brien", "x@y.com", "Smith, Jr."]) {
|
|
1125
|
+
expect(csvField(fine).replace(/^"|"$/g, "").replace(/""/g, '"')).toBe(fine);
|
|
1126
|
+
expect(csvField(fine).startsWith("'")).toBe(false);
|
|
1127
|
+
}
|
|
1128
|
+
});
|
|
1129
|
+
|
|
1130
|
+
it("quotes and doubles per RFC 4180", () => {
|
|
1131
|
+
expect(csvField('say "hi"')).toBe('"say ""hi"""');
|
|
1132
|
+
expect(csvField("a,b")).toBe('"a,b"');
|
|
1133
|
+
expect(csvField("line1\\nline2")).toBe('"line1\\nline2"');
|
|
1134
|
+
});
|
|
1135
|
+
|
|
1136
|
+
it("empty and nullish become an empty field, never the string 'null'", () => {
|
|
1137
|
+
expect(csvField(null)).toBe("");
|
|
1138
|
+
expect(csvField(undefined)).toBe("");
|
|
1139
|
+
expect(csvField("")).toBe("");
|
|
1140
|
+
});
|
|
1141
|
+
|
|
1142
|
+
it("a guarded field that ALSO needs quoting gets the apostrophe inside the quotes", () => {
|
|
1143
|
+
// Order matters. Quote-then-guard would put the apostrophe outside, where the
|
|
1144
|
+
// spreadsheet never sees it, and the cell evaluates as a formula anyway.
|
|
1145
|
+
expect(csvField("=A1,B1")).toBe(\`"'=A1,B1"\`);
|
|
1146
|
+
});
|
|
1147
|
+
});
|
|
1148
|
+
|
|
1149
|
+
describe("toCsv: the document", () => {
|
|
1150
|
+
it("emits a UTF-8 BOM so Excel on Windows does not mojibake non-ASCII names", () => {
|
|
1151
|
+
expect(toCsv(["name"], [["Ana Muñoz"]]).charCodeAt(0)).toBe(0xfeff);
|
|
1152
|
+
});
|
|
1153
|
+
|
|
1154
|
+
it("emits CRLF line endings and a trailing newline", () => {
|
|
1155
|
+
expect(toCsv(["a", "b"], [[1, 2]])).toBe("\\uFEFFa,b\\r\\n1,2\\r\\n");
|
|
1156
|
+
});
|
|
1157
|
+
|
|
1158
|
+
it("guards the HEADERS too, not only the rows", () => {
|
|
1159
|
+
// Headers are user-controlled whenever a report lets someone pick columns.
|
|
1160
|
+
expect(toCsv(["=evil"], [])).toContain("'=evil");
|
|
1161
|
+
});
|
|
1162
|
+
});
|
|
1163
|
+
|
|
1164
|
+
describe("nothing hand-rolls a CSV around the guard", () => {
|
|
1165
|
+
it("actually has source files to check", () => {
|
|
1166
|
+
// An empty list would make the grep below vacuously green.
|
|
1167
|
+
expect(SOURCES.length).toBeGreaterThan(0);
|
|
1168
|
+
});
|
|
1169
|
+
|
|
1170
|
+
it("every file that serves text/csv imports csvField or toCsv", () => {
|
|
1171
|
+
// This is the check that matters in six months. \`lib/csv-export.ts\` makes the
|
|
1172
|
+
// right thing easy; only this makes the wrong thing fail the build.
|
|
1173
|
+
const offenders = SOURCES.filter((f) => {
|
|
1174
|
+
const src = read(f);
|
|
1175
|
+
if (!/text\\/csv/.test(src)) return false;
|
|
1176
|
+
return !/\\b(csvField|toCsv)\\b/.test(src);
|
|
1177
|
+
});
|
|
1178
|
+
expect(offenders).toEqual([]);
|
|
1179
|
+
});
|
|
1180
|
+
});
|
|
1181
|
+
`;
|
|
490
1182
|
const FORM_BITS_TEMPLATE = `/**
|
|
491
1183
|
* Shared form primitives that encode the {{brand_name}} form standards.
|
|
492
1184
|
*
|
|
@@ -1914,9 +2606,11 @@ describe("card-path bot protection", () => {
|
|
|
1914
2606
|
* lifted with thanks; each is a mistake a first-timer makes exactly once.
|
|
1915
2607
|
*/
|
|
1916
2608
|
const NEON_DB_ENV_BLOCK = `
|
|
1917
|
-
#
|
|
1918
|
-
|
|
1919
|
-
|
|
2609
|
+
# Database (Neon Postgres)
|
|
2610
|
+
|
|
2611
|
+
DATABASE_URL=postgresql://user:pass@host-pooler.region.aws.neon.tech/dbname?sslmode=require
|
|
2612
|
+
|
|
2613
|
+
# Copy from https://console.neon.tech/ → your project → Connection Details.
|
|
1920
2614
|
#
|
|
1921
2615
|
# Use the POOLED connection string (the host contains \`-pooler\`). A serverless
|
|
1922
2616
|
# app opens a connection per invocation; the direct endpoint runs out.
|
|
@@ -1931,10 +2625,13 @@ const NEON_DB_ENV_BLOCK = `
|
|
|
1931
2625
|
# \`/api/health\` must never touch the database (per [[neon-postgres]] — routine
|
|
1932
2626
|
# probes burn the Free tier's 100 CU-hour quota and defeat scale-to-zero). The
|
|
1933
2627
|
# scaffolded health route is DB-free; keep it that way.
|
|
1934
|
-
DATABASE_URL=postgresql://user:pass@host-pooler.region.aws.neon.tech/dbname?sslmode=require
|
|
1935
2628
|
`;
|
|
1936
2629
|
const CARD_PATH_ENV_BLOCK = `
|
|
1937
|
-
#
|
|
2630
|
+
# Card-path bot protection (Cloudflare Turnstile)
|
|
2631
|
+
|
|
2632
|
+
NEXT_PUBLIC_TURNSTILE_SITE_KEY=
|
|
2633
|
+
TURNSTILE_SECRET_KEY=
|
|
2634
|
+
|
|
1938
2635
|
# Create a widget: https://dash.cloudflare.com/?to=/:account/turnstile
|
|
1939
2636
|
#
|
|
1940
2637
|
# Set BOTH or NEITHER. A half-configured pair is worse than neither — the widget
|
|
@@ -1943,8 +2640,6 @@ const CARD_PATH_ENV_BLOCK = `
|
|
|
1943
2640
|
#
|
|
1944
2641
|
# Cloudflare's always-passes / always-blocks TEST keys are the right thing to use
|
|
1945
2642
|
# in development: https://developers.cloudflare.com/turnstile/troubleshooting/testing/
|
|
1946
|
-
NEXT_PUBLIC_TURNSTILE_SITE_KEY=
|
|
1947
|
-
TURNSTILE_SECRET_KEY=
|
|
1948
2643
|
`;
|
|
1949
2644
|
/**
|
|
1950
2645
|
* Vitest config for the scaffolded project.
|
|
@@ -2438,6 +3133,7 @@ const APP_LAYOUT_TEMPLATE = `// Root layout — SEO baseline wiring per Z2W stan
|
|
|
2438
3133
|
|
|
2439
3134
|
import type { Metadata, Viewport } from "next";
|
|
2440
3135
|
import { Analytics } from "@/lib/analytics/Analytics";
|
|
3136
|
+
import { serializeJsonLd } from "@/lib/json-ld";
|
|
2441
3137
|
|
|
2442
3138
|
// Global styles. Body typography (18px / 1.5, per the standing Zero2Webmaster
|
|
2443
3139
|
// readability rule) lives in this file, NOT as an inline style on <body>, so
|
|
@@ -2492,9 +3188,14 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2492
3188
|
{/* Canonical URLs are emitted per page by Next.js's Metadata API via
|
|
2493
3189
|
\`alternates.canonical\` — do NOT add a literal canonical link here,
|
|
2494
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. */}
|
|
2495
3196
|
<script
|
|
2496
3197
|
type="application/ld+json"
|
|
2497
|
-
dangerouslySetInnerHTML={{ __html:
|
|
3198
|
+
dangerouslySetInnerHTML={{ __html: serializeJsonLd(organizationJsonLd) }}
|
|
2498
3199
|
/>
|
|
2499
3200
|
</head>
|
|
2500
3201
|
<body>
|
|
@@ -3208,13 +3909,15 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
|
|
|
3208
3909
|
const ENV_EXAMPLE_TEMPLATE = `# {{slug}} — example environment variables.
|
|
3209
3910
|
# Copy to \`.env.local\` and fill in real values.
|
|
3210
3911
|
|
|
3211
|
-
# Site URL (used by metadataBase + sitemap + robots).
|
|
3212
|
-
# In production, set this to your live domain.
|
|
3213
3912
|
NEXT_PUBLIC_SITE_URL=https://{{slug}}.example.com
|
|
3214
|
-
|
|
3215
|
-
# Fathom Analytics site ID (per [[fathom-analytics]] convention).
|
|
3216
|
-
# One Fathom site = one deployment.
|
|
3217
3913
|
NEXT_PUBLIC_FATHOM_SITE_ID=
|
|
3914
|
+
|
|
3915
|
+
# NEXT_PUBLIC_SITE_URL — used by metadataBase + sitemap + robots. In production
|
|
3916
|
+
# set this to your live domain; leaving the placeholder publishes example.com
|
|
3917
|
+
# URLs in your sitemap on the first deploy.
|
|
3918
|
+
#
|
|
3919
|
+
# NEXT_PUBLIC_FATHOM_SITE_ID — per [[fathom-analytics]]. One Fathom site = one
|
|
3920
|
+
# deployment.
|
|
3218
3921
|
`;
|
|
3219
3922
|
/**
|
|
3220
3923
|
* The `CANONICAL_HOSTS` allowlist seam.
|
|
@@ -3231,7 +3934,10 @@ NEXT_PUBLIC_FATHOM_SITE_ID=
|
|
|
3231
3934
|
* pointer at the recipe, in the file the next agent actually opens.
|
|
3232
3935
|
*/
|
|
3233
3936
|
const CANONICAL_HOSTS_ENV_BLOCK = `
|
|
3234
|
-
#
|
|
3937
|
+
# Canonical host allowlist
|
|
3938
|
+
|
|
3939
|
+
CANONICAL_HOSTS=
|
|
3940
|
+
|
|
3235
3941
|
# Comma-separated list of the hostnames this deployment legitimately answers on.
|
|
3236
3942
|
# Normalize to lowercase when you parse it.
|
|
3237
3943
|
#
|
|
@@ -3249,7 +3955,6 @@ const CANONICAL_HOSTS_ENV_BLOCK = `
|
|
|
3249
3955
|
# NODE_ENV !== "production" so preview deployments and localhost keep working.
|
|
3250
3956
|
#
|
|
3251
3957
|
# Copy-paste recipe + the isKnownHost() helper: [[z2w-magic-link-auth]] §0 rule 2b.
|
|
3252
|
-
CANONICAL_HOSTS=
|
|
3253
3958
|
`;
|
|
3254
3959
|
/**
|
|
3255
3960
|
* Merge the email SDK deps into an already-substituted package.json string.
|
|
@@ -3332,6 +4037,10 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
3332
4037
|
path: "lib/seo/canonical-host.mjs",
|
|
3333
4038
|
content: sub(CANONICAL_HOST_MODULE_TEMPLATE, inputs, opts, spec),
|
|
3334
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 },
|
|
3335
4044
|
{
|
|
3336
4045
|
path: "lib/seo/page-metadata.ts",
|
|
3337
4046
|
content: sub(PAGE_METADATA_MODULE_TEMPLATE, inputs, opts, spec),
|
|
@@ -3345,6 +4054,15 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
3345
4054
|
path: "test/form-standards.test.ts",
|
|
3346
4055
|
content: sub(FORM_STANDARDS_TEST_TEMPLATE, inputs, opts, spec),
|
|
3347
4056
|
},
|
|
4057
|
+
// UNCONDITIONAL, unlike every other conditional standard here — see the note
|
|
4058
|
+
// above CSV_EXPORT_TEMPLATE. "This app will export CSV" is not knowable at
|
|
4059
|
+
// scaffold time, and all 12 repos that failed the 2026-08-15 survey grew their
|
|
4060
|
+
// export months after instantiation. A flag would have protected none of them.
|
|
4061
|
+
{ path: "lib/csv-export.ts", content: sub(CSV_EXPORT_TEMPLATE, inputs, opts, spec) },
|
|
4062
|
+
{
|
|
4063
|
+
path: "test/csv-export.test.ts",
|
|
4064
|
+
content: sub(CSV_EXPORT_TEST_TEMPLATE, inputs, opts, spec),
|
|
4065
|
+
},
|
|
3348
4066
|
...(hasObservability
|
|
3349
4067
|
? [
|
|
3350
4068
|
{
|