@zero2webmaster/starter-kit 0.22.0 → 0.24.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.
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
// allowlist stub in `.env.example`. This CLI emits no auth code, so it plants the
|
|
47
47
|
// seam + the pointer at [[z2w-magic-link-auth]] §0 rule 2b rather than a check —
|
|
48
48
|
// see CANONICAL_HOSTS_ENV_BLOCK for why that is the honest half.
|
|
49
|
-
import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
|
|
49
|
+
import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, accessibleOn, contrastRatio, readableInkOn, resolveBrandSpec, SENTRY_DEPS, NEON_DRIVER_DEP, sub, } from "./common.js";
|
|
50
50
|
const NARRATIVE = `## What this is
|
|
51
51
|
|
|
52
52
|
\`{{slug}}\` is a Next.js App Router project scaffolded under the {{brand_name}} brand. The 7-item SEO baseline (per Z2W standing org requirement 2026-05-30) is wired in at instantiation.
|
|
@@ -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;
|
|
@@ -817,6 +1308,16 @@ export function Field({
|
|
|
817
1308
|
);
|
|
818
1309
|
}
|
|
819
1310
|
`;
|
|
1311
|
+
/**
|
|
1312
|
+
* The page background every emitted surface is ultimately drawn on.
|
|
1313
|
+
*
|
|
1314
|
+
* It is a NAMED CONSTANT rather than an inline `"#ffffff"` because the emitted
|
|
1315
|
+
* contrast test enumerates SURFACES, and the failure mode it exists to prevent
|
|
1316
|
+
* is exactly a check that assumes one background. If a future theme makes the
|
|
1317
|
+
* page a tint, changing it here changes what `--brand-focus` is measured against
|
|
1318
|
+
* — which is the behaviour that was missing.
|
|
1319
|
+
*/
|
|
1320
|
+
const PAGE_SURFACE = "#ffffff";
|
|
820
1321
|
/**
|
|
821
1322
|
* Global stylesheet. Built by a function rather than substituted from a flat
|
|
822
1323
|
* template because ONE value has to be computed from the brand hex rather than
|
|
@@ -830,6 +1331,11 @@ export function Field({
|
|
|
830
1331
|
*/
|
|
831
1332
|
function globalsCss(primaryColor) {
|
|
832
1333
|
const onPrimary = readableInkOn(primaryColor);
|
|
1334
|
+
// The focus ring is a STATE indicator, so it has a 3:1 floor against the page
|
|
1335
|
+
// it is drawn on (WCAG 2.1 SC 1.4.11). Most brand primaries do not clear it on
|
|
1336
|
+
// white — see `accessibleOn` for the measured list, which includes Z2W's and
|
|
1337
|
+
// STF's own greens. Derived here, at scaffold time, from the actual hex.
|
|
1338
|
+
const brandFocus = accessibleOn(primaryColor, PAGE_SURFACE, 3);
|
|
833
1339
|
return `/* Global styles.
|
|
834
1340
|
*
|
|
835
1341
|
* Body typography lives here, not as an inline style on <body>, so there is ONE
|
|
@@ -843,12 +1349,35 @@ function globalsCss(primaryColor) {
|
|
|
843
1349
|
scaffold time — do not hand-edit to match a sibling project, whose primary
|
|
844
1350
|
may sit on the other side of the luminance threshold. */
|
|
845
1351
|
--brand-on-primary: ${onPrimary};
|
|
1352
|
+
/* The brand primary, darkened or lightened just far enough to clear 3:1
|
|
1353
|
+
against the page — same hue, different lightness. Use it for anything whose
|
|
1354
|
+
visibility is REQUIRED rather than decorative: focus rings, the active edge
|
|
1355
|
+
of a control, a state chip's border.
|
|
1356
|
+
|
|
1357
|
+
Measured on ${PAGE_SURFACE} at scaffold time: the brand primary scores
|
|
1358
|
+
${contrastRatio(primaryColor, PAGE_SURFACE).toFixed(2)}:1, this scores
|
|
1359
|
+
${contrastRatio(brandFocus, PAGE_SURFACE).toFixed(2)}:1. When the two
|
|
1360
|
+
variables hold the SAME value, the brand primary already cleared the bar on
|
|
1361
|
+
its own and nothing was changed.
|
|
1362
|
+
|
|
1363
|
+
DO NOT collapse these two variables back into one. They are different
|
|
1364
|
+
because they answer to different rules: one is the author's brand, the other
|
|
1365
|
+
has a measured floor. \`test/contrast.test.ts\` fails if this one stops
|
|
1366
|
+
clearing it. */
|
|
1367
|
+
--brand-focus: ${brandFocus};
|
|
846
1368
|
--brand-ink: #3f3c36;
|
|
847
1369
|
/* Input border. #ccc on white is ~1.6:1, below the 3:1 WCAG 2.1 minimum for a
|
|
848
1370
|
UI component boundary — i.e. the edge of the box is genuinely not visible,
|
|
849
1371
|
not merely subtle. #8f8b81 clears 3:1. */
|
|
850
1372
|
--field-border: #8f8b81;
|
|
851
1373
|
--field-border-hover: #6f6b62;
|
|
1374
|
+
/* The page itself. Named so \`test/contrast.test.ts\` can enumerate SURFACES
|
|
1375
|
+
rather than assume one — the whole point of that file. */
|
|
1376
|
+
--page-surface: ${PAGE_SURFACE};
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
body {
|
|
1380
|
+
background: var(--page-surface);
|
|
852
1381
|
}
|
|
853
1382
|
|
|
854
1383
|
html {
|
|
@@ -925,13 +1454,20 @@ body {
|
|
|
925
1454
|
}
|
|
926
1455
|
|
|
927
1456
|
/* A 2px focus ring so keyboard position stays obvious against the now-darker
|
|
928
|
-
resting edge.
|
|
1457
|
+
resting edge.
|
|
1458
|
+
|
|
1459
|
+
\`--brand-focus\`, NOT \`--brand-primary\`. The ring is drawn on the page
|
|
1460
|
+
surface (\`outline-offset\` puts a 1px gap of page between it and the box), so
|
|
1461
|
+
it is measured against the page — and most brand greens, golds and oranges sit
|
|
1462
|
+
around 2:1 there. Using the raw brand primary here made focusing a field
|
|
1463
|
+
REDUCE the visibility of its boundary, since the resting \`--field-border\` is
|
|
1464
|
+
a measured 3.40:1. That was a real shipped defect, not a hypothetical. */
|
|
929
1465
|
.form-field input:focus-visible,
|
|
930
1466
|
.form-field textarea:focus-visible,
|
|
931
1467
|
.form-field select:focus-visible {
|
|
932
|
-
outline: 2px solid var(--brand-
|
|
1468
|
+
outline: 2px solid var(--brand-focus);
|
|
933
1469
|
outline-offset: 1px;
|
|
934
|
-
border-color: var(--brand-
|
|
1470
|
+
border-color: var(--brand-focus);
|
|
935
1471
|
}
|
|
936
1472
|
|
|
937
1473
|
.form-field input:disabled,
|
|
@@ -2245,6 +2781,562 @@ export {};
|
|
|
2245
2781
|
* `fileURLToPath(import.meta.url)`. grantor's original used `__dirname` because
|
|
2246
2782
|
* that project is CommonJS; copying it verbatim would throw at run time.
|
|
2247
2783
|
*/
|
|
2784
|
+
const CONTRAST_MODULE_TEMPLATE = `/**
|
|
2785
|
+
* WCAG 2.1 contrast math, and the rule for WHICH THRESHOLD a given piece of
|
|
2786
|
+
* text has to clear.
|
|
2787
|
+
*
|
|
2788
|
+
* Adding a color to this project should be a measurable act rather than a taste
|
|
2789
|
+
* call. \`test/contrast.test.ts\` is this module's first consumer; your own
|
|
2790
|
+
* design-system code is the intended second — call \`meetsContrast()\` when you
|
|
2791
|
+
* introduce a swatch, rather than eyeballing it.
|
|
2792
|
+
*
|
|
2793
|
+
* THE LESSON THIS FILE ENCODES, and it was expensive: contrast is a property of
|
|
2794
|
+
* a PAIR, not of a color. A palette validator that checks every swatch against
|
|
2795
|
+
* white reports a clean pass while shipping unreadable text, because the swatch
|
|
2796
|
+
* is not rendered on white — it is rendered on the tint panel three components
|
|
2797
|
+
* down. So the unit of measurement here is SURFACE x TEXT-ROLE x THRESHOLD, and
|
|
2798
|
+
* all three vary independently. One swatch can clear 3:1 and fail 4.5:1 on the
|
|
2799
|
+
* very same background.
|
|
2800
|
+
*/
|
|
2801
|
+
|
|
2802
|
+
/** WCAG 2.1 relative luminance of an \`#rgb\` / \`#rrggbb\` color. */
|
|
2803
|
+
export function relativeLuminance(hex: string): number {
|
|
2804
|
+
const h = hex.trim().replace(/^#/, "");
|
|
2805
|
+
const full =
|
|
2806
|
+
h.length === 3
|
|
2807
|
+
? h
|
|
2808
|
+
.split("")
|
|
2809
|
+
.map((c) => c + c)
|
|
2810
|
+
.join("")
|
|
2811
|
+
: h;
|
|
2812
|
+
if (!/^[0-9a-fA-F]{6}$/.test(full)) {
|
|
2813
|
+
// Refusing is the point. A color this module cannot parse must not quietly
|
|
2814
|
+
// score 0 and sail through a >= comparison as if it had been measured.
|
|
2815
|
+
throw new Error("relativeLuminance: not a hex color: " + hex);
|
|
2816
|
+
}
|
|
2817
|
+
const channel = (pair: string): number => {
|
|
2818
|
+
const srgb = parseInt(pair, 16) / 255;
|
|
2819
|
+
return srgb <= 0.03928 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;
|
|
2820
|
+
};
|
|
2821
|
+
return (
|
|
2822
|
+
0.2126 * channel(full.slice(0, 2)) +
|
|
2823
|
+
0.7152 * channel(full.slice(2, 4)) +
|
|
2824
|
+
0.0722 * channel(full.slice(4, 6))
|
|
2825
|
+
);
|
|
2826
|
+
}
|
|
2827
|
+
|
|
2828
|
+
/** WCAG 2.1 contrast ratio between two colors. 1:1 identical, 21:1 black/white. */
|
|
2829
|
+
export function contrastRatio(a: string, b: string): number {
|
|
2830
|
+
const la = relativeLuminance(a);
|
|
2831
|
+
const lb = relativeLuminance(b);
|
|
2832
|
+
const [hi, lo] = la > lb ? [la, lb] : [lb, la];
|
|
2833
|
+
return (hi + 0.05) / (lo + 0.05);
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
/** AA for body-sized text. */
|
|
2837
|
+
export const AA_TEXT = 4.5;
|
|
2838
|
+
/** AA for large-scale text only. */
|
|
2839
|
+
export const AA_LARGE_TEXT = 3;
|
|
2840
|
+
/** AA for non-text: UI component boundaries, state indicators, focus rings. */
|
|
2841
|
+
export const AA_NON_TEXT = 3;
|
|
2842
|
+
|
|
2843
|
+
/**
|
|
2844
|
+
* WCAG "large scale" text: 18pt, or 14pt bold. At the CSS reference 96dpi those
|
|
2845
|
+
* are 24px and 18.66px.
|
|
2846
|
+
*
|
|
2847
|
+
* READ THE 18px CASE CAREFULLY, because it is the one everyone gets wrong. The
|
|
2848
|
+
* standing {{brand_name}} readability rule sets body text at 18px or more, and
|
|
2849
|
+
* "18" next to "18pt" invites the conclusion that body copy qualifies for the
|
|
2850
|
+
* relaxed 3:1 bar. It does not: 18px is 13.5pt, so ordinary body copy needs the
|
|
2851
|
+
* full 4.5:1. The relaxed bar starts at 24px, or at 18.66px when bold.
|
|
2852
|
+
*/
|
|
2853
|
+
export function isLargeText(fontPx: number, fontWeight: number): boolean {
|
|
2854
|
+
return fontPx >= 24 || (fontPx >= 18.66 && fontWeight >= 700);
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
/**
|
|
2858
|
+
* What a pair is being used for. The third axis — a threshold is DERIVED from
|
|
2859
|
+
* the role, never chosen per swatch.
|
|
2860
|
+
*/
|
|
2861
|
+
export type ContrastRole =
|
|
2862
|
+
| { kind: "text"; fontPx: number; fontWeight: number }
|
|
2863
|
+
| { kind: "non-text" };
|
|
2864
|
+
|
|
2865
|
+
/** The ratio \`role\` must clear. */
|
|
2866
|
+
export function requiredRatio(role: ContrastRole): number {
|
|
2867
|
+
if (role.kind === "non-text") return AA_NON_TEXT;
|
|
2868
|
+
return isLargeText(role.fontPx, role.fontWeight) ? AA_LARGE_TEXT : AA_TEXT;
|
|
2869
|
+
}
|
|
2870
|
+
|
|
2871
|
+
/** Whether \`fg\` on \`bg\` is good enough for \`role\`. */
|
|
2872
|
+
export function meetsContrast(fg: string, bg: string, role: ContrastRole): boolean {
|
|
2873
|
+
return contrastRatio(fg, bg) >= requiredRatio(role);
|
|
2874
|
+
}
|
|
2875
|
+
`;
|
|
2876
|
+
const CONTRAST_TEST_TEMPLATE = `/**
|
|
2877
|
+
* Per-SURFACE contrast, enforced on the stylesheet this project actually ships.
|
|
2878
|
+
*
|
|
2879
|
+
* WHY THIS FILE IS SHAPED THE WAY IT IS. The obvious version of this test walks
|
|
2880
|
+
* the palette and checks each color against white. That version passes while the
|
|
2881
|
+
* app ships unreadable text, because a color is not rendered on "the palette" —
|
|
2882
|
+
* it is rendered on a specific surface, and this stylesheet has five of them
|
|
2883
|
+
* (the page, the field fill, the disabled field fill, the help panel, the code
|
|
2884
|
+
* tint) plus a sixth that varies per brand (the brand fill itself).
|
|
2885
|
+
*
|
|
2886
|
+
* So the unit here is a PAIR: one text role, one surface, one threshold. All
|
|
2887
|
+
* three vary. \\\`--brand-ink\\\` is measured four times, on four different
|
|
2888
|
+
* backgrounds, because that is four different questions.
|
|
2889
|
+
*
|
|
2890
|
+
* Everything is READ FROM \\\`app/globals.css\\\`, never restated here. A test that
|
|
2891
|
+
* asserts \\\`toMatch(/--field-border:\\\\s*#8f8b81/)\\\` is checking the SPELLING of
|
|
2892
|
+
* a decision; this one re-derives the MEASUREMENT, so changing a hex to another
|
|
2893
|
+
* hex is caught if and only if it actually breaks something. Font sizes and
|
|
2894
|
+
* weights are read from the CSS too, which is what makes the threshold axis real
|
|
2895
|
+
* rather than a number someone typed next to a color.
|
|
2896
|
+
*/
|
|
2897
|
+
import { describe, it, expect } from "vitest";
|
|
2898
|
+
import { readFileSync } from "node:fs";
|
|
2899
|
+
import { join, dirname } from "node:path";
|
|
2900
|
+
import { fileURLToPath } from "node:url";
|
|
2901
|
+
import {
|
|
2902
|
+
contrastRatio,
|
|
2903
|
+
isLargeText,
|
|
2904
|
+
meetsContrast,
|
|
2905
|
+
requiredRatio,
|
|
2906
|
+
type ContrastRole,
|
|
2907
|
+
} from "../lib/a11y/contrast";
|
|
2908
|
+
|
|
2909
|
+
// NOT \\\`__dirname\\\` — this package is "type": "module", where it is undefined.
|
|
2910
|
+
const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
2911
|
+
const CSS_RAW = readFileSync(join(ROOT, "app/globals.css"), "utf8");
|
|
2912
|
+
|
|
2913
|
+
// Comments in this stylesheet quote example hexes on purpose ("#ccc on white is
|
|
2914
|
+
// ~1.6:1"). Those are prose, not shipped colors, and the completeness scan below
|
|
2915
|
+
// would spend its life reporting them. Strip comments before any scan — and do it
|
|
2916
|
+
// once, here, so no individual check can forget to.
|
|
2917
|
+
const CSS = CSS_RAW.replace(/\\/\\*[\\s\\S]*?\\*\\//g, "");
|
|
2918
|
+
|
|
2919
|
+
/** Every rule body whose selector list contains \\\`selector\\\` as a whole entry. */
|
|
2920
|
+
function ruleBodies(selector: string): string[] {
|
|
2921
|
+
const out: string[] = [];
|
|
2922
|
+
const re = /([^{}]+)\\{([^}]*)\\}/g;
|
|
2923
|
+
let m: RegExpExecArray | null;
|
|
2924
|
+
while ((m = re.exec(CSS)) !== null) {
|
|
2925
|
+
const selectors = m[1].split(",").map((s) => s.trim());
|
|
2926
|
+
if (selectors.includes(selector)) out.push(m[2]);
|
|
2927
|
+
}
|
|
2928
|
+
return out;
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
/**
|
|
2932
|
+
* One declaration, from the rules for \\\`selector\\\`. Later rules win, matching the
|
|
2933
|
+
* cascade for equal specificity.
|
|
2934
|
+
*
|
|
2935
|
+
* THROWS when absent, and that is the design. A missing declaration means the
|
|
2936
|
+
* pair table has drifted from the stylesheet, and the honest report for that is
|
|
2937
|
+
* a failure — not a skipped row, and certainly not a default that happens to
|
|
2938
|
+
* pass ([[zero-is-not-a-pass]]).
|
|
2939
|
+
*/
|
|
2940
|
+
function decl(selector: string, prop: string): string {
|
|
2941
|
+
const bodies = ruleBodies(selector);
|
|
2942
|
+
if (bodies.length === 0) {
|
|
2943
|
+
throw new Error("contrast table names a selector that is not in globals.css: " + selector);
|
|
2944
|
+
}
|
|
2945
|
+
const re = new RegExp("(?:^|;)\\\\s*" + prop + "\\\\s*:\\\\s*([^;]+)");
|
|
2946
|
+
let found: string | null = null;
|
|
2947
|
+
for (const body of bodies) {
|
|
2948
|
+
const m = re.exec(body);
|
|
2949
|
+
if (m) found = m[1].trim();
|
|
2950
|
+
}
|
|
2951
|
+
if (found === null) {
|
|
2952
|
+
throw new Error("no \\\`" + prop + "\\\` declared for selector: " + selector);
|
|
2953
|
+
}
|
|
2954
|
+
return found;
|
|
2955
|
+
}
|
|
2956
|
+
|
|
2957
|
+
function declOr(selector: string, prop: string, fallback: string): string {
|
|
2958
|
+
try {
|
|
2959
|
+
return decl(selector, prop);
|
|
2960
|
+
} catch {
|
|
2961
|
+
return fallback;
|
|
2962
|
+
}
|
|
2963
|
+
}
|
|
2964
|
+
|
|
2965
|
+
/** Expand \\\`#abc\\\` to \\\`#aabbcc\\\`, lowercase. */
|
|
2966
|
+
function expand(hex: string): string {
|
|
2967
|
+
const h = hex.replace(/^#/, "").toLowerCase();
|
|
2968
|
+
return "#" + (h.length === 3 ? h.split("").map((c) => c + c).join("") : h);
|
|
2969
|
+
}
|
|
2970
|
+
|
|
2971
|
+
/** Resolve a \\\`var(--x)\\\` reference against \\\`:root\\\`, recursively. */
|
|
2972
|
+
function resolveToken(token: string, seen: string[] = []): string {
|
|
2973
|
+
const v = token.trim();
|
|
2974
|
+
const varRef = /^var\\(\\s*(--[\\w-]+)\\s*\\)$/.exec(v);
|
|
2975
|
+
if (varRef) {
|
|
2976
|
+
const name = varRef[1];
|
|
2977
|
+
if (seen.includes(name)) throw new Error("circular custom property: " + name);
|
|
2978
|
+
return colorIn(decl(":root", name), [...seen, name]);
|
|
2979
|
+
}
|
|
2980
|
+
if (/^#[0-9a-fA-F]{3}$/.test(v) || /^#[0-9a-fA-F]{6}$/.test(v)) return expand(v);
|
|
2981
|
+
// Deliberately NOT a silent skip. \\\`rgb()\\\`, \\\`hsl()\\\`, \\\`color-mix()\\\` and named
|
|
2982
|
+
// colors are all perfectly good CSS and this scanner cannot measure any of
|
|
2983
|
+
// them — so it says so and fails, rather than reporting a pass it did not earn.
|
|
2984
|
+
throw new Error("not a measurable color (use a hex, or teach this test): " + token);
|
|
2985
|
+
}
|
|
2986
|
+
|
|
2987
|
+
/** Pull the color out of a value, shorthand included (\\\`2px solid var(--x)\\\`). */
|
|
2988
|
+
function colorIn(value: string, seen: string[] = []): string {
|
|
2989
|
+
const direct = value.trim();
|
|
2990
|
+
if (/^(var\\(|#)/.test(direct) && !/\\s/.test(direct)) return resolveToken(direct, seen);
|
|
2991
|
+
const m = /var\\(\\s*--[\\w-]+\\s*\\)|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3}\\b/.exec(direct);
|
|
2992
|
+
if (!m) throw new Error("no color token in value: " + value);
|
|
2993
|
+
return resolveToken(m[0], seen);
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
/** The color a property resolves to, for a selector. */
|
|
2997
|
+
const color = (selector: string, prop: string): string => colorIn(decl(selector, prop));
|
|
2998
|
+
const px = (v: string): number => parseFloat(v);
|
|
2999
|
+
|
|
3000
|
+
const PAGE = color(":root", "--page-surface");
|
|
3001
|
+
|
|
3002
|
+
interface Pair {
|
|
3003
|
+
/** Plain-English description, used as the failure message. */
|
|
3004
|
+
what: string;
|
|
3005
|
+
/** The CSS selector or custom property this row models. */
|
|
3006
|
+
where: string;
|
|
3007
|
+
fg: string;
|
|
3008
|
+
bg: string;
|
|
3009
|
+
role: ContrastRole;
|
|
3010
|
+
}
|
|
3011
|
+
|
|
3012
|
+
// ---------------------------------------------------------------------------
|
|
3013
|
+
// THE PAIRS. Surface x text-role x threshold, one row each.
|
|
3014
|
+
//
|
|
3015
|
+
// This table is hand-maintained ON PURPOSE. "Which text sits on which surface"
|
|
3016
|
+
// is a fact about the rendered DOM, and no amount of stylesheet parsing can
|
|
3017
|
+
// recover it. What the test CAN do — and does, below — is prove the table has
|
|
3018
|
+
// not fallen behind the stylesheet: every color in globals.css must appear in
|
|
3019
|
+
// this table or in the exempt table, so a new surface cannot arrive unmeasured.
|
|
3020
|
+
// ---------------------------------------------------------------------------
|
|
3021
|
+
const PAIRS: Pair[] = [
|
|
3022
|
+
{
|
|
3023
|
+
what: "body copy on the page",
|
|
3024
|
+
where: "body",
|
|
3025
|
+
fg: color("body", "color"),
|
|
3026
|
+
bg: PAGE,
|
|
3027
|
+
role: {
|
|
3028
|
+
kind: "text",
|
|
3029
|
+
fontPx: px(decl("body", "font-size")),
|
|
3030
|
+
fontWeight: px(declOr("body", "font-weight", "400")),
|
|
3031
|
+
},
|
|
3032
|
+
},
|
|
3033
|
+
{
|
|
3034
|
+
what: "field label on the page",
|
|
3035
|
+
where: ".form-field label",
|
|
3036
|
+
fg: color(".form-field label", "color"),
|
|
3037
|
+
bg: PAGE,
|
|
3038
|
+
role: {
|
|
3039
|
+
kind: "text",
|
|
3040
|
+
fontPx: px(decl(".form-field label", "font-size")),
|
|
3041
|
+
fontWeight: px(decl(".form-field label", "font-weight")),
|
|
3042
|
+
},
|
|
3043
|
+
},
|
|
3044
|
+
{
|
|
3045
|
+
what: "typed text on the field fill",
|
|
3046
|
+
where: ".form-field input",
|
|
3047
|
+
fg: color(".form-field input", "color"),
|
|
3048
|
+
bg: color(".form-field input", "background"),
|
|
3049
|
+
role: {
|
|
3050
|
+
kind: "text",
|
|
3051
|
+
fontPx: px(decl(".form-field input", "font-size")),
|
|
3052
|
+
fontWeight: 400,
|
|
3053
|
+
},
|
|
3054
|
+
},
|
|
3055
|
+
{
|
|
3056
|
+
// A disabled field is exempt from the NON-TEXT rule, never from the TEXT
|
|
3057
|
+
// rule — the value in a disabled field still has to be readable, which is
|
|
3058
|
+
// usually the whole reason it is on screen.
|
|
3059
|
+
what: "text in a DISABLED field, on the disabled fill",
|
|
3060
|
+
where: ".form-field input:disabled",
|
|
3061
|
+
fg: color(".form-field input:disabled", "color"),
|
|
3062
|
+
bg: color(".form-field input:disabled", "background"),
|
|
3063
|
+
role: {
|
|
3064
|
+
kind: "text",
|
|
3065
|
+
fontPx: px(decl(".form-field input", "font-size")),
|
|
3066
|
+
fontWeight: 400,
|
|
3067
|
+
},
|
|
3068
|
+
},
|
|
3069
|
+
{
|
|
3070
|
+
// Sized by the label it sits in, not by itself.
|
|
3071
|
+
what: "the required-marker asterisk on the page",
|
|
3072
|
+
where: ".req-mark",
|
|
3073
|
+
fg: color(".req-mark", "color"),
|
|
3074
|
+
bg: PAGE,
|
|
3075
|
+
role: {
|
|
3076
|
+
kind: "text",
|
|
3077
|
+
fontPx: px(decl(".form-field label", "font-size")),
|
|
3078
|
+
fontWeight: px(decl(".req-mark", "font-weight")),
|
|
3079
|
+
},
|
|
3080
|
+
},
|
|
3081
|
+
{
|
|
3082
|
+
what: "the help-hint trigger on the page",
|
|
3083
|
+
where: ".info-hint > summary",
|
|
3084
|
+
fg: color(".info-hint > summary", "color"),
|
|
3085
|
+
bg: PAGE,
|
|
3086
|
+
role: {
|
|
3087
|
+
kind: "text",
|
|
3088
|
+
fontPx: px(decl(".info-hint", "font-size")),
|
|
3089
|
+
fontWeight: px(decl(".info-hint > summary", "font-weight")),
|
|
3090
|
+
},
|
|
3091
|
+
},
|
|
3092
|
+
{
|
|
3093
|
+
// THE BRAND-DEPENDENT ROW. Every other pair is fixed at scaffold time; this
|
|
3094
|
+
// one has the author's brand hex as its BACKGROUND, so it is the row that
|
|
3095
|
+
// can pass for one project and fail for the next. A 13px glyph, so the full
|
|
3096
|
+
// 4.5:1 applies however bold it is.
|
|
3097
|
+
what: "the 'i' glyph on the BRAND FILL",
|
|
3098
|
+
where: ".info-hint-icon",
|
|
3099
|
+
fg: color(".info-hint-icon", "color"),
|
|
3100
|
+
bg: color(".info-hint-icon", "background"),
|
|
3101
|
+
role: {
|
|
3102
|
+
kind: "text",
|
|
3103
|
+
fontPx: px(decl(".info-hint-icon", "font-size")),
|
|
3104
|
+
fontWeight: px(decl(".info-hint-icon", "font-weight")),
|
|
3105
|
+
},
|
|
3106
|
+
},
|
|
3107
|
+
{
|
|
3108
|
+
what: "help-panel body text on the PANEL (not on the page)",
|
|
3109
|
+
where: ".info-hint-body",
|
|
3110
|
+
fg: color(".info-hint-body", "color"),
|
|
3111
|
+
bg: color(".info-hint-body", "background"),
|
|
3112
|
+
role: {
|
|
3113
|
+
kind: "text",
|
|
3114
|
+
fontPx: px(decl(".info-hint-body", "font-size")),
|
|
3115
|
+
fontWeight: 400,
|
|
3116
|
+
},
|
|
3117
|
+
},
|
|
3118
|
+
{
|
|
3119
|
+
// The same ink as the row above, on a different surface, at a smaller size.
|
|
3120
|
+
// This is the pair a per-palette validator structurally cannot see.
|
|
3121
|
+
what: "inline code on the CODE TINT inside the help panel",
|
|
3122
|
+
where: ".info-hint-body code",
|
|
3123
|
+
fg: color(".info-hint-body", "color"),
|
|
3124
|
+
bg: color(".info-hint-body code", "background"),
|
|
3125
|
+
role: {
|
|
3126
|
+
kind: "text",
|
|
3127
|
+
fontPx: px(decl(".info-hint-body code", "font-size")),
|
|
3128
|
+
fontWeight: 400,
|
|
3129
|
+
},
|
|
3130
|
+
},
|
|
3131
|
+
|
|
3132
|
+
// --- non-text: boundaries and state (WCAG 2.1 SC 1.4.11) -----------------
|
|
3133
|
+
{
|
|
3134
|
+
what: "the resting edge of a field, against the page",
|
|
3135
|
+
where: "--field-border",
|
|
3136
|
+
fg: color(":root", "--field-border"),
|
|
3137
|
+
bg: PAGE,
|
|
3138
|
+
role: { kind: "non-text" },
|
|
3139
|
+
},
|
|
3140
|
+
{
|
|
3141
|
+
what: "the hovered edge of a field, against the page",
|
|
3142
|
+
where: "--field-border-hover",
|
|
3143
|
+
fg: color(":root", "--field-border-hover"),
|
|
3144
|
+
bg: PAGE,
|
|
3145
|
+
role: { kind: "non-text" },
|
|
3146
|
+
},
|
|
3147
|
+
{
|
|
3148
|
+
// \\\`outline-offset\\\` puts a 1px gap of PAGE between the ring and the box, so
|
|
3149
|
+
// the ring is measured against the page and not against the field fill.
|
|
3150
|
+
// This row is why \\\`--brand-focus\\\` exists as a separate variable.
|
|
3151
|
+
what: "the keyboard FOCUS RING, against the page",
|
|
3152
|
+
where: ".form-field input:focus-visible (outline)",
|
|
3153
|
+
fg: color(".form-field input:focus-visible", "outline"),
|
|
3154
|
+
bg: PAGE,
|
|
3155
|
+
role: { kind: "non-text" },
|
|
3156
|
+
},
|
|
3157
|
+
{
|
|
3158
|
+
what: "the focused field's own border, against the page",
|
|
3159
|
+
where: ".form-field input:focus-visible (border-color)",
|
|
3160
|
+
fg: color(".form-field input:focus-visible", "border-color"),
|
|
3161
|
+
bg: PAGE,
|
|
3162
|
+
role: { kind: "non-text" },
|
|
3163
|
+
},
|
|
3164
|
+
];
|
|
3165
|
+
|
|
3166
|
+
// ---------------------------------------------------------------------------
|
|
3167
|
+
// EXEMPT. Colors that are in the stylesheet and deliberately NOT held to a
|
|
3168
|
+
// ratio. Each needs a reason, because an exempt list is precisely where a real
|
|
3169
|
+
// failure hides — "we decided this one does not count" is indistinguishable
|
|
3170
|
+
// from "we forgot this one" unless the decision is written down.
|
|
3171
|
+
// ---------------------------------------------------------------------------
|
|
3172
|
+
const EXEMPT: Array<{ color: string; where: string; why: string }> = [
|
|
3173
|
+
{
|
|
3174
|
+
color: color(".form-field input:disabled", "border-color"),
|
|
3175
|
+
where: ".form-field input:disabled (border-color)",
|
|
3176
|
+
why:
|
|
3177
|
+
"WCAG 2.1 SC 1.4.11 exempts an inactive user interface component in so " +
|
|
3178
|
+
"many words. Forcing 3:1 here would make a disabled field look MORE " +
|
|
3179
|
+
"present than an enabled one.",
|
|
3180
|
+
},
|
|
3181
|
+
{
|
|
3182
|
+
color: colorIn(decl(".info-hint-body", "border")),
|
|
3183
|
+
where: ".info-hint-body (border)",
|
|
3184
|
+
why:
|
|
3185
|
+
"Decorative container edge. It carries no state, and it is not required " +
|
|
3186
|
+
"to identify the panel — the panel's own text does that, and the 4px " +
|
|
3187
|
+
"brand stripe on its left gives it its shape.",
|
|
3188
|
+
},
|
|
3189
|
+
{
|
|
3190
|
+
color: color(":root", "--brand-primary"),
|
|
3191
|
+
where: "--brand-primary as a decorative fill / accent stripe",
|
|
3192
|
+
why:
|
|
3193
|
+
"The author's brand color, used as the info-icon fill and the panel's " +
|
|
3194
|
+
"left stripe. Both are decorative next to a text label that carries the " +
|
|
3195
|
+
"meaning, so SC 1.4.11 does not apply to the SHAPES. The GLYPH painted " +
|
|
3196
|
+
"on this fill is a different question and is measured in PAIRS above.",
|
|
3197
|
+
},
|
|
3198
|
+
];
|
|
3199
|
+
|
|
3200
|
+
describe("the contrast math itself", () => {
|
|
3201
|
+
// A broken ratio function makes every assertion below meaningless while
|
|
3202
|
+
// leaving them all green, so it is pinned against published values first.
|
|
3203
|
+
it("reproduces known WCAG ratios", () => {
|
|
3204
|
+
expect(contrastRatio("#000000", "#ffffff")).toBeCloseTo(21, 5);
|
|
3205
|
+
expect(contrastRatio("#ffffff", "#ffffff")).toBeCloseTo(1, 5);
|
|
3206
|
+
// #767676 is the canonical "just passes AA on white" grey.
|
|
3207
|
+
expect(contrastRatio("#767676", "#ffffff")).toBeGreaterThanOrEqual(4.5);
|
|
3208
|
+
expect(contrastRatio("#777777", "#ffffff")).toBeLessThan(4.5);
|
|
3209
|
+
// Order must not matter.
|
|
3210
|
+
expect(contrastRatio("#8a4b08", "#ffffff")).toBeCloseTo(
|
|
3211
|
+
contrastRatio("#ffffff", "#8a4b08"),
|
|
3212
|
+
10,
|
|
3213
|
+
);
|
|
3214
|
+
});
|
|
3215
|
+
|
|
3216
|
+
it("REFUSES a color it cannot measure instead of scoring it zero", () => {
|
|
3217
|
+
// An unparseable color that quietly returns 0 luminance would read as
|
|
3218
|
+
// maximum contrast against white and pass every check in this file.
|
|
3219
|
+
expect(() => contrastRatio("rgb(0 0 0)", "#ffffff")).toThrow();
|
|
3220
|
+
expect(() => contrastRatio("tomato", "#ffffff")).toThrow();
|
|
3221
|
+
});
|
|
3222
|
+
|
|
3223
|
+
it("detects a failing pair (the assertions above point the right way)", () => {
|
|
3224
|
+
// #ccc on white is ~1.6:1. If this reads as a pass, every other assertion
|
|
3225
|
+
// in this file is decorative.
|
|
3226
|
+
expect(meetsContrast("#cccccc", "#ffffff", { kind: "non-text" })).toBe(false);
|
|
3227
|
+
expect(meetsContrast("#cccccc", "#ffffff", { kind: "text", fontPx: 18, fontWeight: 400 })).toBe(
|
|
3228
|
+
false,
|
|
3229
|
+
);
|
|
3230
|
+
expect(meetsContrast("#3f3c36", "#ffffff", { kind: "text", fontPx: 18, fontWeight: 400 })).toBe(
|
|
3231
|
+
true,
|
|
3232
|
+
);
|
|
3233
|
+
});
|
|
3234
|
+
|
|
3235
|
+
it("does not treat 18px body copy as WCAG large text", () => {
|
|
3236
|
+
// The {{brand_name}} readability rule says body 18px+, and "18" invites the
|
|
3237
|
+
// wrong conclusion: 18px is 13.5pt, so it needs the full 4.5:1. The relaxed
|
|
3238
|
+
// 3:1 bar begins at 24px, or 18.66px when bold.
|
|
3239
|
+
expect(isLargeText(18, 400)).toBe(false);
|
|
3240
|
+
expect(isLargeText(18, 700)).toBe(false);
|
|
3241
|
+
expect(isLargeText(19, 700)).toBe(true);
|
|
3242
|
+
expect(isLargeText(24, 400)).toBe(true);
|
|
3243
|
+
expect(requiredRatio({ kind: "text", fontPx: 18, fontWeight: 400 })).toBe(4.5);
|
|
3244
|
+
expect(requiredRatio({ kind: "text", fontPx: 24, fontWeight: 400 })).toBe(3);
|
|
3245
|
+
expect(requiredRatio({ kind: "non-text" })).toBe(3);
|
|
3246
|
+
});
|
|
3247
|
+
});
|
|
3248
|
+
|
|
3249
|
+
describe("per-surface contrast", () => {
|
|
3250
|
+
it("has pairs to check, on more than one surface, at more than one threshold", () => {
|
|
3251
|
+
// Three separate ways this file could go vacuously green: an empty table, a
|
|
3252
|
+
// table that only ever looks at the page background (the exact bug this
|
|
3253
|
+
// file exists to prevent), and a table where every row happens to want the
|
|
3254
|
+
// same threshold, which would hide a broken requiredRatio().
|
|
3255
|
+
expect(PAIRS.length).toBeGreaterThan(8);
|
|
3256
|
+
expect(new Set(PAIRS.map((p) => p.bg)).size).toBeGreaterThan(2);
|
|
3257
|
+
const thresholds = new Set(PAIRS.map((p) => requiredRatio(p.role)));
|
|
3258
|
+
expect(thresholds).toContain(4.5);
|
|
3259
|
+
expect(thresholds).toContain(3);
|
|
3260
|
+
});
|
|
3261
|
+
|
|
3262
|
+
it.each(PAIRS.map((p) => [p.what, p] as const))("%s clears its threshold", (_what, pair) => {
|
|
3263
|
+
const need = requiredRatio(pair.role);
|
|
3264
|
+
const got = contrastRatio(pair.fg, pair.bg);
|
|
3265
|
+
expect(
|
|
3266
|
+
got >= need,
|
|
3267
|
+
pair.what +
|
|
3268
|
+
" (" +
|
|
3269
|
+
pair.where +
|
|
3270
|
+
"): " +
|
|
3271
|
+
pair.fg +
|
|
3272
|
+
" on " +
|
|
3273
|
+
pair.bg +
|
|
3274
|
+
" is " +
|
|
3275
|
+
// 3 decimals, not 2: a ratio of 4.4999 renders as "4.50:1, needs 4.5:1",
|
|
3276
|
+
// which reads like a rounding bug in the test rather than a real miss.
|
|
3277
|
+
got.toFixed(3) +
|
|
3278
|
+
":1, needs " +
|
|
3279
|
+
need +
|
|
3280
|
+
":1",
|
|
3281
|
+
).toBe(true);
|
|
3282
|
+
});
|
|
3283
|
+
|
|
3284
|
+
it("measures --brand-ink on every surface it is actually painted on", () => {
|
|
3285
|
+
// The headline case. One ink, four backgrounds, four questions — and a
|
|
3286
|
+
// palette-shaped check would have asked only the first.
|
|
3287
|
+
const ink = color(":root", "--brand-ink");
|
|
3288
|
+
const surfaces = PAIRS.filter((p) => p.fg === ink).map((p) => p.bg);
|
|
3289
|
+
expect(new Set(surfaces).size).toBeGreaterThanOrEqual(3);
|
|
3290
|
+
});
|
|
3291
|
+
|
|
3292
|
+
it("the focus ring is NOT the raw brand primary", () => {
|
|
3293
|
+
// The defect this variable was introduced to fix. Most brand greens, golds
|
|
3294
|
+
// and oranges land near 2:1 on white, so a ring painted in --brand-primary
|
|
3295
|
+
// made FOCUSING a field reduce the visibility of its boundary. The pair
|
|
3296
|
+
// assertions above would catch a regression numerically; this one names it,
|
|
3297
|
+
// so the failure says what went wrong instead of just which ratio slipped.
|
|
3298
|
+
const ring = decl(".form-field input:focus-visible", "outline");
|
|
3299
|
+
expect(ring).toContain("var(--brand-focus)");
|
|
3300
|
+
expect(ring).not.toContain("var(--brand-primary)");
|
|
3301
|
+
});
|
|
3302
|
+
});
|
|
3303
|
+
|
|
3304
|
+
describe("the pair table has not fallen behind the stylesheet", () => {
|
|
3305
|
+
it("every color in globals.css is either measured or explicitly exempt", () => {
|
|
3306
|
+
// THIS is the check that makes the rest trustworthy. Without it, adding a
|
|
3307
|
+
// surface to the stylesheet leaves the table silently incomplete and the
|
|
3308
|
+
// suite green — which is how a per-palette validator fails, one level up.
|
|
3309
|
+
const declared = new Set<string>();
|
|
3310
|
+
const re = /#[0-9a-fA-F]{6}\\b|#[0-9a-fA-F]{3}\\b/g;
|
|
3311
|
+
let m: RegExpExecArray | null;
|
|
3312
|
+
while ((m = re.exec(CSS)) !== null) declared.add(expand(m[0]));
|
|
3313
|
+
expect(declared.size).toBeGreaterThan(6);
|
|
3314
|
+
|
|
3315
|
+
const accounted = new Set<string>([
|
|
3316
|
+
...PAIRS.flatMap((p) => [p.fg, p.bg]),
|
|
3317
|
+
...EXEMPT.map((e) => e.color),
|
|
3318
|
+
]);
|
|
3319
|
+
const unaccounted = [...declared].filter((c) => !accounted.has(c));
|
|
3320
|
+
expect(
|
|
3321
|
+
unaccounted,
|
|
3322
|
+
"these colors are in app/globals.css but no pair measures them. Add a row " +
|
|
3323
|
+
"to PAIRS naming the surface each one is painted on — or to EXEMPT with " +
|
|
3324
|
+
"a reason, in test/contrast.test.ts",
|
|
3325
|
+
).toEqual([]);
|
|
3326
|
+
});
|
|
3327
|
+
|
|
3328
|
+
it("every exempt color gives a reason", () => {
|
|
3329
|
+
// An exempt row without a stated reason is a silent suppression.
|
|
3330
|
+
for (const e of EXEMPT) {
|
|
3331
|
+
expect(e.why.length, e.where + " is exempt without saying why").toBeGreaterThan(40);
|
|
3332
|
+
expect(/1\\.4\\.11|decorative|inactive/i.test(e.why), e.where + ": " + e.why).toBe(true);
|
|
3333
|
+
}
|
|
3334
|
+
// The exempt list is small on purpose. If it is growing, the stylesheet is
|
|
3335
|
+
// accumulating colors nobody measured.
|
|
3336
|
+
expect(EXEMPT.length).toBeLessThanOrEqual(5);
|
|
3337
|
+
});
|
|
3338
|
+
});
|
|
3339
|
+
`;
|
|
2248
3340
|
const FORM_STANDARDS_TEST_TEMPLATE = `/**
|
|
2249
3341
|
* {{brand_name}} form standards, enforced as tests rather than as a convention
|
|
2250
3342
|
* someone has to remember:
|
|
@@ -2642,6 +3734,7 @@ const APP_LAYOUT_TEMPLATE = `// Root layout — SEO baseline wiring per Z2W stan
|
|
|
2642
3734
|
|
|
2643
3735
|
import type { Metadata, Viewport } from "next";
|
|
2644
3736
|
import { Analytics } from "@/lib/analytics/Analytics";
|
|
3737
|
+
import { serializeJsonLd } from "@/lib/json-ld";
|
|
2645
3738
|
|
|
2646
3739
|
// Global styles. Body typography (18px / 1.5, per the standing Zero2Webmaster
|
|
2647
3740
|
// readability rule) lives in this file, NOT as an inline style on <body>, so
|
|
@@ -2696,9 +3789,14 @@ export default function RootLayout({ children }: { children: React.ReactNode })
|
|
|
2696
3789
|
{/* Canonical URLs are emitted per page by Next.js's Metadata API via
|
|
2697
3790
|
\`alternates.canonical\` — do NOT add a literal canonical link here,
|
|
2698
3791
|
it would produce a SECOND, conflicting canonical on every page. */}
|
|
3792
|
+
{/* Routed through serializeJsonLd (lib/json-ld.ts), NOT bare
|
|
3793
|
+
JSON.stringify. This particular object holds only a scaffold-time
|
|
3794
|
+
brand name and an env-var URL, so nothing user-controlled reaches
|
|
3795
|
+
it today -- but this is the block every future JSON-LD gets copied
|
|
3796
|
+
from, and the copy WILL carry database content. See the module. */}
|
|
2699
3797
|
<script
|
|
2700
3798
|
type="application/ld+json"
|
|
2701
|
-
dangerouslySetInnerHTML={{ __html:
|
|
3799
|
+
dangerouslySetInnerHTML={{ __html: serializeJsonLd(organizationJsonLd) }}
|
|
2702
3800
|
/>
|
|
2703
3801
|
</head>
|
|
2704
3802
|
<body>
|
|
@@ -3540,6 +4638,10 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
3540
4638
|
path: "lib/seo/canonical-host.mjs",
|
|
3541
4639
|
content: sub(CANONICAL_HOST_MODULE_TEMPLATE, inputs, opts, spec),
|
|
3542
4640
|
},
|
|
4641
|
+
{ path: "lib/security-headers.mjs", content: securityHeadersModule(inputs) },
|
|
4642
|
+
{ path: "lib/json-ld.ts", content: JSON_LD_MODULE_TEMPLATE },
|
|
4643
|
+
{ path: "test/security-headers.test.ts", content: SECURITY_HEADERS_TEST_TEMPLATE },
|
|
4644
|
+
{ path: "test/json-ld.test.ts", content: JSON_LD_TEST_TEMPLATE },
|
|
3543
4645
|
{
|
|
3544
4646
|
path: "lib/seo/page-metadata.ts",
|
|
3545
4647
|
content: sub(PAGE_METADATA_MODULE_TEMPLATE, inputs, opts, spec),
|
|
@@ -3549,6 +4651,17 @@ export function scaffoldNextjs(inputs, opts) {
|
|
|
3549
4651
|
{ path: "test/server-only.stub.ts", content: SERVER_ONLY_STUB_TEMPLATE },
|
|
3550
4652
|
{ path: "app/globals.css", content: globalsCss(spec.primaryColor) },
|
|
3551
4653
|
{ path: "components/FormBits.tsx", content: sub(FORM_BITS_TEMPLATE, inputs, opts, spec) },
|
|
4654
|
+
// The contrast pair table and the math it uses. Emitted unconditionally: the
|
|
4655
|
+
// stylesheet it measures is emitted unconditionally, and a project whose
|
|
4656
|
+
// palette is unmeasured is exactly the project that needs measuring.
|
|
4657
|
+
{
|
|
4658
|
+
path: "lib/a11y/contrast.ts",
|
|
4659
|
+
content: sub(CONTRAST_MODULE_TEMPLATE, inputs, opts, spec),
|
|
4660
|
+
},
|
|
4661
|
+
{
|
|
4662
|
+
path: "test/contrast.test.ts",
|
|
4663
|
+
content: sub(CONTRAST_TEST_TEMPLATE, inputs, opts, spec),
|
|
4664
|
+
},
|
|
3552
4665
|
{
|
|
3553
4666
|
path: "test/form-standards.test.ts",
|
|
3554
4667
|
content: sub(FORM_STANDARDS_TEST_TEMPLATE, inputs, opts, spec),
|