@luhtech/site-template 0.23.1 → 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.
package/README.md CHANGED
@@ -425,6 +425,87 @@ Two bins go with it:
425
425
  install chromium`. `SiteLayout` emits the web-app meta for an installable
426
426
  site.
427
427
 
428
+ ## A content-security policy arrives as a response header (0.24.0)
429
+
430
+ Astro renders a hash-based policy as a `<meta>` element at the end of `<head>`, so anything earlier in `<head>` is not covered by it. That includes SiteLayout's no-js script, the fonts stylesheet and a page's head slot. A header comes before the document, so it covers all of it.
431
+
432
+ `@luhtech/site-template/integrations/nginx-csp-headers` is a static adapter that declares Astro's `staticHeaders` feature. With it, Astro hands each page's policy to the adapter and leaves out the meta. At build the integration writes one nginx `map` from each page's request path to its policy: `/`, `/x`, `/x/` and `/x/index.html`, matching what `try_files` serves. The site's nginx sends that value as one header.
433
+
434
+ ```js
435
+ // astro.config.mjs
436
+ import nginxCspHeaders from '@luhtech/site-template/integrations/nginx-csp-headers';
437
+ export default defineConfig({
438
+ integrations: [nginxCspHeaders({ headerOnly: ["frame-ancestors 'none'"] })],
439
+ security: { csp: { /* directives and hashes as before */ } },
440
+ });
441
+ ```
442
+
443
+ ```nginx
444
+ # nginx.conf (server-level include of conf.d is http context)
445
+ include /etc/nginx/csp-map.conf; # copied from nginx/csp-map.conf at image build
446
+ server {
447
+ location / { add_header Content-Security-Policy $luhtech_csp always; ... }
448
+ }
449
+ ```
450
+
451
+ - `outFile` sets where the map is written, relative to the project root. The default, `nginx/csp-map.conf`, sits outside `dist/` so it is never served.
452
+ - `variable` names the nginx variable. The default is `luhtech_csp`.
453
+ - `headerOnly` lists directives only a header can carry, such as `frame-ancestors`. They are appended to every page's policy, and they are also the value on every other response.
454
+ - The policy text is Astro's own; nothing edits or loosens it.
455
+ - The build fails when:
456
+ - `security.csp` is off;
457
+ - output is not static, or `build.format` is not `directory`;
458
+ - any page has no policy;
459
+ - a value carries a `$` or a line break.
460
+ - The map is sorted, so identical input gives a byte-identical file.
461
+ - Serving costs one hash lookup per response.
462
+ - The integration sets the site's adapter, so it cannot be combined with another adapter.
463
+
464
+ ## A content-security policy covers the animated marks, by opt-in (0.23.3)
465
+
466
+ An animated venture mark inlines its own `<style>`, which Astro does not hash, and `VentureMark`
467
+ renders too late to register a hash itself: the policy meta is written before the body renders. A site
468
+ whose `astro.config` enables `security.csp` passes `cspMarkHashes` to `SiteLayout`:
469
+
470
+ ```astro
471
+ <SiteLayout site={site} page={page} brand={brand} cspMarkHashes>
472
+ ```
473
+
474
+ The layout then registers the SHA-256 hash of every `<style>` body in the generated marks
475
+ (`ventureMarkStyleHashes()` in `src/lib/ventureMarkCsp.ts`, computed from the same markup the component
476
+ inlines, never hand-typed) before the meta renders. The setting is off by default: a site without a
477
+ policy never reads the page's CSP context, so its build logs no `[csp] context.csp was used` warning.
478
+ Setting it without `security.csp` fails the build. A site that computed these hashes in its own
479
+ `astro.config` can drop that code once it opts in.
480
+
481
+ ## On a phone, a wide connection graph scrolls sideways at its drawn size (0.23.3)
482
+
483
+ Below the `md` breakpoint (768px) a connection graph holds at least its natural width (the `width` and
484
+ `height` of its viewBox) and fills a wider column, so its node text stays at drawn size; when it is wider
485
+ than the column it scrolls sideways inside a keyboard-focusable region (`role="region"`, labelled,
486
+ `tabindex="0"`) in its figure, and the page itself never scrolls sideways. From `md` up it scales to its
487
+ column as before. The viewBox and the layout are unchanged, and the markup carries no `style` attribute,
488
+ which a hash policy refuses.
489
+
490
+ ## A venture mark's fallback carries no inline handler (0.23.2)
491
+
492
+ `VentureMark.astro` falls back to the static `/brand/{brandRef}-mark.svg` for a
493
+ venture with no animated mark. Through 0.23.1 it hid a missing file with
494
+ `<img onerror="this.style.display='none'">`: an inline event handler, which a
495
+ hash-based content-security policy refuses, and a 404 request on every view of
496
+ a site that does not ship the file. From 0.23.2 the component decides at build,
497
+ from the site's own `public/brand/` (`src/lib/ventureMarkCsp.ts`
498
+ `staticMarkShipped`, the same check SiteLayout makes for its icon files), and
499
+ renders nothing when the file is absent. Nothing changes for a site that ships
500
+ its static marks. `test/ventureMarkCsp.test.mjs` proves the present and absent
501
+ cases and that the component emits no `on*` attribute.
502
+
503
+ An animated mark's own `<style>` is still inlined with `set:html`, which Astro
504
+ does not hash; a site with a hash policy lists those hashes itself (desconops.org
505
+ computes them in `astro.config.mjs` from this package's generated marks). Moving
506
+ that into the template is held for a ruling: see desconops-org
507
+ `d-2026-12-02-do-site-template-csp-marks`.
508
+
428
509
  ## A connection graph with a cycle lays out at its true width (0.23.1)
429
510
 
430
511
  `ConnectionGraph` layered by longest-path relaxation, which on a cycle
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luhtech/site-template",
3
- "version": "0.23.1",
3
+ "version": "0.24.0",
4
4
  "description": "Shared Astro component library + content-instance contract for LuhTech venture marketing sites -- one template renders every site from content/page.schema.json + content/site.schema.json instances.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -25,6 +25,7 @@
25
25
  "./lib/paperLanding": "./src/lib/paperLanding.ts",
26
26
  "./lib/figureLabel": "./src/lib/figureLabel.ts",
27
27
  "./layouts/SiteLayout.astro": "./src/layouts/SiteLayout.astro",
28
+ "./integrations/nginx-csp-headers": "./src/integrations/nginx-csp-headers.mjs",
28
29
  "./components/*": "./src/components/*",
29
30
  "./components/sections/*": "./src/components/sections/*"
30
31
  },
@@ -7,12 +7,15 @@
7
7
  // animation overriding another's, e.g. a shared "logo-cell-in" name
8
8
  // colliding across ventures) once pulled into VENTURE_MARKS via
9
9
  // bin/luhtech-sync-animated-marks.mjs; falls back to the static
10
- // /brand/{brandRef}-mark.svg file (onerror-hidden if even that's missing)
11
- // for every venture that doesn't have one yet. Not every venture needs an
12
- // animated mark for this to work; it degrades honestly per-venture
10
+ // /brand/{brandRef}-mark.svg file for every venture that doesn't have one
11
+ // yet, and renders nothing when the site does not ship that file either
12
+ // (decided at build, 0.23.2 -- no inline onerror handler, no 404 request).
13
+ // Not every venture needs an animated mark for this to work; it degrades
14
+ // honestly per-venture
13
15
  // instead of assuming universal coverage. An animated mark replays when
14
16
  // clicked (data-mark-replay="venture", SiteLayout's installMarkReplay, 0.22.0).
15
17
  import { VENTURE_MARKS } from '../lib/venture-marks.generated';
18
+ import { staticMarkPath, staticMarkShipped } from '../lib/ventureMarkCsp';
16
19
 
17
20
  export interface Props {
18
21
  brandRef: string;
@@ -20,15 +23,10 @@ export interface Props {
20
23
  }
21
24
  const { brandRef, class: className = 'h-6 w-6 mb-2' } = Astro.props;
22
25
  const animated = VENTURE_MARKS[brandRef];
26
+ const staticShipped = !animated && staticMarkShipped(brandRef);
23
27
  ---
24
28
  {animated ? (
25
29
  <svg xmlns="http://www.w3.org/2000/svg" viewBox={animated.viewBox} class={className} role="img" aria-label={brandRef} data-mark-replay="venture" set:html={animated.markup} />
26
- ) : (
27
- <img
28
- src={`/brand/${brandRef}-mark.svg`}
29
- alt=""
30
- class={className}
31
- loading="lazy"
32
- onerror="this.style.display='none'"
33
- />
34
- )}
30
+ ) : staticShipped ? (
31
+ <img src={staticMarkPath(brandRef)} alt="" class={className} loading="lazy" />
32
+ ) : null}
@@ -32,7 +32,11 @@ export interface Props {
32
32
  edges: Edge[];
33
33
  class?: string;
34
34
  }
35
- const { diagramId, nodes, edges, class: className = 'w-full h-auto' } = Astro.props;
35
+ // 0.23.3: below md (768px) the graph holds at least its natural width (width/height from its viewBox) and
36
+ // fills a wider column (min-w-full), so on a phone its node text stays at drawn size and the graph scrolls
37
+ // sideways inside a keyboard-focusable region instead of shrinking; from md up it scales to its column as
38
+ // before. No style attribute, which a hash policy refuses.
39
+ const { diagramId, nodes, edges, class: className = 'w-full h-auto max-md:w-auto max-md:min-w-full max-md:max-w-none' } = Astro.props;
36
40
 
37
41
  const selfLoops = edges.filter((e) => e.from === e.to);
38
42
 
@@ -179,9 +183,18 @@ const ariaLabel = `Connection graph: ${nodes.length} nodes -- ${nodes.map((n) =>
179
183
  .map((e) => `${nodes.find((n) => n.id === e.from)?.label ?? e.from} to ${nodes.find((n) => n.id === e.to)?.label ?? e.to}${e.label ? ` (${e.label})` : ''}`)
180
184
  .join('; ')}.`;
181
185
  ---
186
+ <div
187
+ class="overflow-x-auto focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent-primary focus-visible:rounded"
188
+ role="region"
189
+ aria-label="Connection graph (scrolls sideways when wider than the page)"
190
+ tabindex="0"
191
+ data-graph-scroll
192
+ >
182
193
  <svg
183
194
  xmlns="http://www.w3.org/2000/svg"
184
195
  viewBox={`0 0 ${width} ${height}`}
196
+ width={width}
197
+ height={height}
185
198
  class={className}
186
199
  role="img"
187
200
  aria-label={ariaLabel}
@@ -268,3 +281,4 @@ const ariaLabel = `Connection graph: ${nodes.length} nodes -- ${nodes.map((n) =>
268
281
  </g>
269
282
  ))}
270
283
  </svg>
284
+ </div>
@@ -0,0 +1,125 @@
1
+ // @luhtech/site-template -- each page's content-security policy as an nginx response header.
2
+ //
3
+ // Astro renders a hash-based policy as a <meta> element at the END of <head>
4
+ // (astro/dist/runtime/server/render/head.js renderAllHeadContent), so anything ahead of it in
5
+ // <head> -- SiteLayout's no-js script, the fonts stylesheet, a page's head slot -- is not
6
+ // governed by it. When the site's adapter declares adapterFeatures.staticHeaders, Astro sends
7
+ // the policy to the adapter instead (cspDestination 'adapter'): it omits the meta, and the
8
+ // astro:build:generated hook receives every static page's response headers (routeToHeaders).
9
+ // A header precedes the document, so it governs all of it.
10
+ //
11
+ // This integration is that adapter for a static site served by nginx. At build it writes one
12
+ // nginx `map` from each page's request path to its policy; the site's nginx.conf includes the
13
+ // map at http level and sends `add_header Content-Security-Policy $<variable> always;`.
14
+ // The policy text is Astro's own; nothing here edits or loosens it. A page without a policy
15
+ // fails the build: with the meta gone, a page that ships without the header has no policy.
16
+ // The map is generated at build, so serving it costs one hash lookup per response.
17
+
18
+ import { mkdirSync, writeFileSync } from 'node:fs';
19
+ import { dirname, isAbsolute, join } from 'node:path';
20
+ import { fileURLToPath } from 'node:url';
21
+
22
+ const NAME = '@luhtech/site-template/nginx-csp-headers';
23
+ const VARIABLE = /^[a-z_][a-z0-9_]*$/;
24
+
25
+ /** A value nginx will read back verbatim inside double quotes. A `$` would be read as a
26
+ * variable and a line break would split the directive, so either fails rather than being
27
+ * rewritten. */
28
+ function quote(value, where) {
29
+ if (/[\u0000-\u001f\u007f]/.test(value)) throw new Error(`${NAME}: ${where} carries a control character`);
30
+ if (value.includes('$')) throw new Error(`${NAME}: ${where} carries '$', which nginx reads as a variable`);
31
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
32
+ }
33
+
34
+ /** Every request path nginx serves a page under, for Astro's directory build format:
35
+ * '/' -> '/', '/index.html'; '/ledger' -> '/ledger', '/ledger/', '/ledger/index.html'.
36
+ * nginx's try_files rewrites $uri to the index file, so the map keys all three. */
37
+ export function requestPaths(pathname) {
38
+ if (typeof pathname !== 'string' || !pathname.startsWith('/')) {
39
+ throw new Error(`${NAME}: page path ${JSON.stringify(pathname)} is not absolute`);
40
+ }
41
+ const base = pathname.replace(/\/+$/, '');
42
+ if (base === '') return ['/', '/index.html'];
43
+ return [base, `${base}/`, `${base}/index.html`];
44
+ }
45
+
46
+ /**
47
+ * The nginx map for a set of pages.
48
+ * @param {Array<[string, string]>} pages [pathname, policy] for every static page
49
+ * @param {{ variable?: string, headerOnly?: string[] }} [options]
50
+ * variable: the nginx variable the map sets (default luhtech_csp).
51
+ * headerOnly: directives a header can carry and a meta cannot (e.g. "frame-ancestors 'none'"),
52
+ * appended to every page's policy and sent alone on every other response.
53
+ * @returns {string}
54
+ */
55
+ export function renderNginxCspMap(pages, options = {}) {
56
+ const variable = options.variable ?? 'luhtech_csp';
57
+ if (!VARIABLE.test(variable)) throw new Error(`${NAME}: variable ${JSON.stringify(variable)} is not an nginx variable name`);
58
+ const headerOnly = (options.headerOnly ?? []).map((d) => String(d).trim()).filter(Boolean);
59
+ if (!Array.isArray(pages) || pages.length === 0) {
60
+ throw new Error(`${NAME}: no static page carried a content-security policy; enable security.csp in astro.config`);
61
+ }
62
+ const rows = new Map();
63
+ for (const [pathname, policy] of pages) {
64
+ if (typeof policy !== 'string' || policy.trim() === '') {
65
+ throw new Error(`${NAME}: page ${pathname} has no content-security policy; it would ship without one`);
66
+ }
67
+ const value = [policy.trim().replace(/;\s*$/, ''), ...headerOnly].join('; ');
68
+ for (const path of requestPaths(pathname)) {
69
+ if (rows.has(path) && rows.get(path) !== value) throw new Error(`${NAME}: ${path} maps to two different policies`);
70
+ rows.set(path, value);
71
+ }
72
+ }
73
+ const keys = [...rows.keys()].sort();
74
+ const width = Math.max(...keys.map((k) => quote(k, 'a path').length));
75
+ const lines = [
76
+ `# Generated by ${NAME} at build -- do not edit. Include at http level; send with:`,
77
+ `# add_header Content-Security-Policy $${variable} always;`,
78
+ `map $uri $${variable} {`,
79
+ ` default ${quote(headerOnly.join('; '), 'the default')};`,
80
+ ...keys.map((k) => ` ${quote(k, 'a path').padEnd(width)} ${quote(rows.get(k), `the policy of ${k}`)};`),
81
+ '}',
82
+ '',
83
+ ];
84
+ return lines.join('\n');
85
+ }
86
+
87
+ /**
88
+ * The integration: makes the site's adapter declare staticHeaders, and writes the map.
89
+ * @param {{ outFile?: string, variable?: string, headerOnly?: string[] }} [options]
90
+ * outFile: where the map is written, relative to the project root (default nginx/csp-map.conf),
91
+ * kept out of the served dist/.
92
+ */
93
+ export default function nginxCspHeaders(options = {}) {
94
+ const outFile = options.outFile ?? 'nginx/csp-map.conf';
95
+ let root;
96
+ return {
97
+ name: NAME,
98
+ hooks: {
99
+ 'astro:config:done': ({ config, setAdapter }) => {
100
+ if (config.output !== 'static') throw new Error(`${NAME}: the site must build static output`);
101
+ if (config.build.format !== 'directory') throw new Error(`${NAME}: only build.format 'directory' is supported`);
102
+ if (!config.security?.csp) throw new Error(`${NAME}: security.csp must be enabled`);
103
+ root = fileURLToPath(config.root);
104
+ setAdapter({
105
+ name: NAME,
106
+ entrypointResolution: 'auto',
107
+ supportedAstroFeatures: {
108
+ staticOutput: 'stable',
109
+ hybridOutput: 'unsupported',
110
+ serverOutput: 'unsupported',
111
+ sharpImageService: 'stable',
112
+ },
113
+ adapterFeatures: { buildOutput: 'static', staticHeaders: true },
114
+ });
115
+ },
116
+ 'astro:build:generated': ({ routeToHeaders, logger }) => {
117
+ const pages = [...routeToHeaders].map(([pathname, { headers }]) => [pathname, headers.get('content-security-policy')]);
118
+ const file = isAbsolute(outFile) ? outFile : join(root, outFile);
119
+ mkdirSync(dirname(file), { recursive: true });
120
+ writeFileSync(file, renderNginxCspMap(pages, options));
121
+ logger.info(`content-security policy of ${pages.length} page(s) written to ${outFile}`);
122
+ },
123
+ },
124
+ };
125
+ }
@@ -15,14 +15,30 @@ import { existsSync } from 'node:fs';
15
15
  import { join } from 'node:path';
16
16
  import type { LoadedBrand } from '../content/loadBrand.js';
17
17
  import { ICON_FILES, buildSeoHead, type SiteDevices } from '../lib/seoHead.js';
18
+ import { ventureMarkStyleHashes } from '../lib/ventureMarkCsp.ts';
18
19
 
19
20
  export interface Props {
20
21
  site: LoadedSite;
21
22
  page: LoadedPage;
22
23
  /** Optional: supplies og:site_name and theme-color. */
23
24
  brand?: LoadedBrand;
25
+ /**
26
+ * Opt-in (0.23.3), for a site whose astro.config enables security.csp: registers every animated
27
+ * venture mark's inline <style> hash with the page's policy before the policy meta renders
28
+ * (VentureMark itself renders too late to). Off by default, so a site without a policy never
29
+ * reads the page CSP context and logs no warning. Turning it on without security.csp fails the build.
30
+ */
31
+ cspMarkHashes?: boolean;
32
+ }
33
+ const { site, page, brand, cspMarkHashes = false } = Astro.props as Props;
34
+
35
+ if (cspMarkHashes) {
36
+ const csp = Astro.csp;
37
+ if (!csp) {
38
+ throw new Error('SiteLayout cspMarkHashes is set, but the site has no security.csp in astro.config');
39
+ }
40
+ for (const hash of ventureMarkStyleHashes()) csp.insertStyleHash(hash);
24
41
  }
25
- const { site, page, brand } = Astro.props as Props;
26
42
 
27
43
  // Icon/manifest links are emitted only for files the site really ships in
28
44
  // public/ (generated by luhtech-sync-icons), so a site that hasn't run it
@@ -0,0 +1,38 @@
1
+ // A venture mark under a hash-based content-security policy (0.23.2).
2
+ //
3
+ // VentureMark.astro falls back to the static /brand/{id}-mark.svg for a venture with no
4
+ // animated mark. Before 0.23.2 it hid a missing file with an inline onerror handler, which a
5
+ // hash policy refuses and which cost a 404 request on every view. staticMarkShipped decides at
6
+ // build, from the site's own public/ (as SiteLayout already checks its icon files), whether the
7
+ // file exists, so the page carries no handler and never requests a file that is not there.
8
+ //
9
+ // 0.23.3: an animated mark inlines its own <style>, which Astro does not hash. A site whose page carries
10
+ // a hash policy opts in with SiteLayout's cspMarkHashes, and the layout registers ventureMarkStyleHashes()
11
+ // -- computed from the same generated markup VentureMark inlines, never hand-typed -- before the policy
12
+ // meta renders. A site without a policy never opts in, so the layout never reads Astro.csp and the build
13
+ // logs no '[csp] context.csp was used ... but CSP was not configured' warning.
14
+ import { createHash } from 'node:crypto';
15
+ import { existsSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { VENTURE_MARKS, type VentureMarkEntry } from './venture-marks.generated.ts';
18
+
19
+ /** The static mark's public path for a venture. */
20
+ export function staticMarkPath(brandRef: string): string {
21
+ return `/brand/${brandRef}-mark.svg`;
22
+ }
23
+
24
+ /** Whether the site ships the static mark, read from its public/ directory at build. */
25
+ export function staticMarkShipped(brandRef: string, siteRoot: string = process.cwd()): boolean {
26
+ return existsSync(join(siteRoot, 'public', 'brand', `${brandRef}-mark.svg`));
27
+ }
28
+
29
+ /** The CSP source of every <style> body in the animated marks: 'sha256-<base64>' per distinct body. */
30
+ export function ventureMarkStyleHashes(marks: Record<string, VentureMarkEntry> = VENTURE_MARKS): string[] {
31
+ const hashes = new Set<string>();
32
+ for (const { markup } of Object.values(marks)) {
33
+ for (const style of markup.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)) {
34
+ hashes.add(`sha256-${createHash('sha256').update(style[1], 'utf8').digest('base64')}`);
35
+ }
36
+ }
37
+ return [...hashes];
38
+ }