@luhtech/site-template 0.23.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.
- package/README.md +95 -1
- package/package.json +2 -1
- package/src/components/VentureMark.astro +10 -12
- package/src/components/diagrams/ConnectionGraph.astro +67 -23
- package/src/integrations/nginx-csp-headers.mjs +125 -0
- package/src/layouts/SiteLayout.astro +17 -1
- package/src/lib/graphLayout.ts +96 -0
- package/src/lib/ventureMarkCsp.ts +38 -0
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@ schema: each site repo validates its instances in its own CI against
|
|
|
8
8
|
schema-registry (the reusable `content-validate.yml` workflow), so an invalid
|
|
9
9
|
instance fails that site's CI instead of shipping.
|
|
10
10
|
|
|
11
|
-
Current release: **0.23.
|
|
11
|
+
Current release: **0.23.1** on npmjs.com. Every release is a
|
|
12
12
|
`site-template-v*` tag, published by `.github/workflows/publish.yml`; CI
|
|
13
13
|
(`.github/workflows/ci.yml`) runs `npm install` + `npm test` on every PR and
|
|
14
14
|
push to `main`.
|
|
@@ -425,6 +425,100 @@ 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
|
+
|
|
509
|
+
## A connection graph with a cycle lays out at its true width (0.23.1)
|
|
510
|
+
|
|
511
|
+
`ConnectionGraph` layered by longest-path relaxation, which on a cycle
|
|
512
|
+
(design -> ... -> operate -> design) pushed the cycle's nodes one column
|
|
513
|
+
right on every pass: desconops.org's five-node three-loops figure came out
|
|
514
|
+
13000 units wide. `layerGraph` (`src/lib/graphLayout.ts`) now breaks each
|
|
515
|
+
cycle first -- a depth-first search in node order marks the edge that closes
|
|
516
|
+
it -- and layers the rest in one topological pass; both are linear in nodes
|
|
517
|
+
plus edges and give the same layout for the same record. A cycle-closing
|
|
518
|
+
edge draws as a dashed return path under the graph, its label beneath. An
|
|
519
|
+
acyclic graph lays out exactly as before (`test/graphLayout.test.mjs` checks
|
|
520
|
+
300 random ones against the old layering).
|
|
521
|
+
|
|
428
522
|
## A figure renders its label (0.23.0)
|
|
429
523
|
|
|
430
524
|
content/page 2.9.0 and whitepaper 1.4.0 give a figure a `label` (what the
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@luhtech/site-template",
|
|
3
|
-
"version": "0.
|
|
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
|
|
11
|
-
//
|
|
12
|
-
//
|
|
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
|
-
|
|
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}
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
// any real nodes[]/edges[] input -- not hand-tuned to one graph. Self-loops
|
|
11
11
|
// (a node citing itself, e.g. "a decision supersedes a decision") are
|
|
12
12
|
// excluded from layering and drawn as a small loop above the node instead.
|
|
13
|
+
// An edge that closes a longer cycle (operate -> design in a three-loop
|
|
14
|
+
// record) is found by src/lib/graphLayout.ts, kept out of layering, and drawn
|
|
15
|
+
// as a dashed return path under the graph -- see layerGraph's own note.
|
|
13
16
|
export interface Node {
|
|
14
17
|
id: string;
|
|
15
18
|
label: string;
|
|
@@ -22,36 +25,30 @@ export interface Edge {
|
|
|
22
25
|
to: string;
|
|
23
26
|
label?: string;
|
|
24
27
|
}
|
|
28
|
+
import { layerGraph } from '../../lib/graphLayout';
|
|
25
29
|
export interface Props {
|
|
26
30
|
diagramId: string;
|
|
27
31
|
nodes: Node[];
|
|
28
32
|
edges: Edge[];
|
|
29
33
|
class?: string;
|
|
30
34
|
}
|
|
31
|
-
|
|
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;
|
|
32
40
|
|
|
33
41
|
const selfLoops = edges.filter((e) => e.from === e.to);
|
|
34
|
-
const crossEdges = edges.filter((e) => e.from !== e.to);
|
|
35
42
|
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const want = (layer.get(e.from) ?? 0) + 1;
|
|
46
|
-
if (want > (layer.get(e.to) ?? 0)) {
|
|
47
|
-
layer.set(e.to, want);
|
|
48
|
-
changed = true;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
if (!changed) break;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
const maxLayer = Math.max(...Array.from(layer.values()), 0);
|
|
43
|
+
// Layering and cycle-breaking: src/lib/graphLayout.ts (O(nodes + edges),
|
|
44
|
+
// deterministic). Forward edges are drawn left to right; an edge that closes a
|
|
45
|
+
// cycle is a return edge, drawn under the graph.
|
|
46
|
+
const { layer, maxLayer, backEdges } = layerGraph(
|
|
47
|
+
nodes.map((n) => n.id),
|
|
48
|
+
edges,
|
|
49
|
+
);
|
|
50
|
+
const crossEdges = edges.filter((e, i) => e.from !== e.to && !backEdges.has(i));
|
|
51
|
+
const returnEdges = edges.filter((_, i) => backEdges.has(i));
|
|
55
52
|
const columns: Node[][] = Array.from({ length: maxLayer + 1 }, () => []);
|
|
56
53
|
for (const n of nodes) columns[layer.get(n.id) ?? 0].push(n);
|
|
57
54
|
|
|
@@ -107,8 +104,19 @@ columns.forEach((col, ci) => {
|
|
|
107
104
|
});
|
|
108
105
|
});
|
|
109
106
|
|
|
110
|
-
|
|
111
|
-
|
|
107
|
+
// A return edge's label runs under the whole graph, so the canvas is at least
|
|
108
|
+
// as wide as the longest one (same ~5.4px/char estimate as COL_GAP).
|
|
109
|
+
const longestReturnLabel = Math.max(0, ...returnEdges.filter((e) => e.label).map((e) => e.label!.length));
|
|
110
|
+
const width = Math.max(
|
|
111
|
+
PAD_X * 2 + (maxLayer + 1) * NODE_W + maxLayer * COL_GAP,
|
|
112
|
+
longestReturnLabel * 5.4 + PAD * 2,
|
|
113
|
+
);
|
|
114
|
+
// Each return edge runs along its own track under the nodes, its label just
|
|
115
|
+
// below the track; reserved only when the graph has one, so every acyclic
|
|
116
|
+
// diagram's canvas stays exactly as tight as before.
|
|
117
|
+
const RETURN_TRACK = 26;
|
|
118
|
+
const RETURN_ROOM = returnEdges.length > 0 ? returnEdges.length * RETURN_TRACK + 14 : 0;
|
|
119
|
+
const height = topPad + PAD + colHeight + RETURN_ROOM;
|
|
112
120
|
|
|
113
121
|
// Cubic bezier from the right edge of `from` to the left edge of `to`
|
|
114
122
|
// (forward, cross-column edges), or a vertical bow between two nodes in
|
|
@@ -141,6 +149,23 @@ const drawnCrossEdges = crossEdges
|
|
|
141
149
|
})
|
|
142
150
|
.filter((e): e is NonNullable<typeof e> => e !== null);
|
|
143
151
|
|
|
152
|
+
// A return edge leaves the bottom of its source, runs along its track and
|
|
153
|
+
// rises into the bottom of its target, with rounded corners.
|
|
154
|
+
const drawnReturnEdges = returnEdges
|
|
155
|
+
.map((e, ti) => {
|
|
156
|
+
const from = positions.get(e.from);
|
|
157
|
+
const to = positions.get(e.to);
|
|
158
|
+
if (!from || !to) return null;
|
|
159
|
+
const yRun = topPad + colHeight + 18 + ti * RETURN_TRACK;
|
|
160
|
+
const r = 8;
|
|
161
|
+
const dir = to.cx < from.cx ? -1 : 1;
|
|
162
|
+
const fb = from.y + NODE_H;
|
|
163
|
+
const tb = to.y + NODE_H;
|
|
164
|
+
const path = `M ${from.cx} ${fb} L ${from.cx} ${yRun - r} Q ${from.cx} ${yRun} ${from.cx + dir * r} ${yRun} L ${to.cx - dir * r} ${yRun} Q ${to.cx} ${yRun} ${to.cx} ${yRun - r} L ${to.cx} ${tb + 2}`;
|
|
165
|
+
return { ...e, path, lx: (from.cx + to.cx) / 2, ly: yRun + 12 };
|
|
166
|
+
})
|
|
167
|
+
.filter((e): e is NonNullable<typeof e> => e !== null);
|
|
168
|
+
|
|
144
169
|
const drawnSelfLoops = selfLoops
|
|
145
170
|
.map((e) => {
|
|
146
171
|
const at = positions.get(e.from);
|
|
@@ -158,9 +183,18 @@ const ariaLabel = `Connection graph: ${nodes.length} nodes -- ${nodes.map((n) =>
|
|
|
158
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})` : ''}`)
|
|
159
184
|
.join('; ')}.`;
|
|
160
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
|
+
>
|
|
161
193
|
<svg
|
|
162
194
|
xmlns="http://www.w3.org/2000/svg"
|
|
163
195
|
viewBox={`0 0 ${width} ${height}`}
|
|
196
|
+
width={width}
|
|
197
|
+
height={height}
|
|
164
198
|
class={className}
|
|
165
199
|
role="img"
|
|
166
200
|
aria-label={ariaLabel}
|
|
@@ -188,6 +222,15 @@ const ariaLabel = `Connection graph: ${nodes.length} nodes -- ${nodes.map((n) =>
|
|
|
188
222
|
</g>
|
|
189
223
|
))}
|
|
190
224
|
|
|
225
|
+
{drawnReturnEdges.map((e) => (
|
|
226
|
+
<g class="text-ink/50">
|
|
227
|
+
<path d={e.path} fill="none" stroke="currentColor" stroke-width="1.25" stroke-opacity="0.4" stroke-dasharray="4 3" marker-end={`url(#${markerId})`} />
|
|
228
|
+
{e.label && (
|
|
229
|
+
<text x={e.lx} y={e.ly} text-anchor="middle" font-family="JetBrains Mono, monospace" font-size="9" fill="currentColor" fill-opacity="0.65">{e.label}</text>
|
|
230
|
+
)}
|
|
231
|
+
</g>
|
|
232
|
+
))}
|
|
233
|
+
|
|
191
234
|
{drawnSelfLoops.map((e) => (
|
|
192
235
|
<g class="text-ink/50">
|
|
193
236
|
<path d={e.path} fill="none" stroke="currentColor" stroke-width="1.25" stroke-opacity="0.4" marker-end={`url(#${markerId})`} />
|
|
@@ -238,3 +281,4 @@ const ariaLabel = `Connection graph: ${nodes.length} nodes -- ${nodes.map((n) =>
|
|
|
238
281
|
</g>
|
|
239
282
|
))}
|
|
240
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,96 @@
|
|
|
1
|
+
// Layering for ConnectionGraph: which column each node sits in, and which
|
|
2
|
+
// edges close a cycle.
|
|
3
|
+
//
|
|
4
|
+
// A layered (Sugiyama-style) layout needs an acyclic graph. Real records are
|
|
5
|
+
// not always one: a loop such as design -> release -> construct -> operate ->
|
|
6
|
+
// design closes back on its start. Layering such a graph by longest-path
|
|
7
|
+
// relaxation pushes every node in the cycle one column further right on each
|
|
8
|
+
// pass, so the canvas grows with the pass count (found live: desconops.org's
|
|
9
|
+
// three-loops figure, 5 nodes, laid out 13000 units wide).
|
|
10
|
+
//
|
|
11
|
+
// So the cycle is broken first, the standard way: a depth-first search in node
|
|
12
|
+
// order marks each edge that reaches a node still on the search stack as a back
|
|
13
|
+
// edge. The remaining forward edges form a DAG, layered by longest path in one
|
|
14
|
+
// topological pass. Back edges are not lost: the component draws each one as a
|
|
15
|
+
// return path under the graph. Both passes are O(nodes + edges), and the result
|
|
16
|
+
// depends only on node and edge order, so the same record always draws the same.
|
|
17
|
+
// A graph with no cycle has no back edges and lays out exactly as before.
|
|
18
|
+
|
|
19
|
+
export interface LayoutEdge {
|
|
20
|
+
from: string;
|
|
21
|
+
to: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface GraphLayering {
|
|
25
|
+
/** column index per node id, 0 for a node with no forward incoming edge */
|
|
26
|
+
layer: Map<string, number>;
|
|
27
|
+
/** the highest column index */
|
|
28
|
+
maxLayer: number;
|
|
29
|
+
/** indexes into the edges array of the edges that close a cycle */
|
|
30
|
+
backEdges: Set<number>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function layerGraph(nodeIds: readonly string[], edges: readonly LayoutEdge[]): GraphLayering {
|
|
34
|
+
const known = new Set(nodeIds);
|
|
35
|
+
const out = new Map<string, number[]>(nodeIds.map((id) => [id, []]));
|
|
36
|
+
edges.forEach((e, i) => {
|
|
37
|
+
if (e.from !== e.to && known.has(e.from) && known.has(e.to)) out.get(e.from)!.push(i);
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// Depth-first search, iterative so a long chain cannot overflow the stack.
|
|
41
|
+
// Roots are taken in node order: nodes with no incoming edge first, so a
|
|
42
|
+
// graph's natural start stays in column 0, then any node not yet reached.
|
|
43
|
+
const hasIncoming = new Set<string>();
|
|
44
|
+
for (const e of edges) if (e.from !== e.to && known.has(e.from)) hasIncoming.add(e.to);
|
|
45
|
+
const roots = [...nodeIds.filter((id) => !hasIncoming.has(id)), ...nodeIds];
|
|
46
|
+
|
|
47
|
+
const state = new Map<string, 0 | 1 | 2>(); // 0 unseen, 1 on stack, 2 done
|
|
48
|
+
const backEdges = new Set<number>();
|
|
49
|
+
for (const root of roots) {
|
|
50
|
+
if (state.get(root)) continue;
|
|
51
|
+
const stack: Array<{ id: string; next: number }> = [{ id: root, next: 0 }];
|
|
52
|
+
state.set(root, 1);
|
|
53
|
+
while (stack.length) {
|
|
54
|
+
const top = stack[stack.length - 1];
|
|
55
|
+
const outs = out.get(top.id)!;
|
|
56
|
+
if (top.next < outs.length) {
|
|
57
|
+
const ei = outs[top.next++];
|
|
58
|
+
const to = edges[ei].to;
|
|
59
|
+
const s = state.get(to) ?? 0;
|
|
60
|
+
if (s === 1) backEdges.add(ei);
|
|
61
|
+
else if (s === 0) {
|
|
62
|
+
state.set(to, 1);
|
|
63
|
+
stack.push({ id: to, next: 0 });
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
state.set(top.id, 2);
|
|
67
|
+
stack.pop();
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Longest-path layering over the forward edges, in topological order (Kahn).
|
|
73
|
+
const indeg = new Map<string, number>(nodeIds.map((id) => [id, 0]));
|
|
74
|
+
const fwd = new Map<string, string[]>(nodeIds.map((id) => [id, []]));
|
|
75
|
+
out.forEach((list, from) => {
|
|
76
|
+
for (const ei of list) {
|
|
77
|
+
if (backEdges.has(ei)) continue;
|
|
78
|
+
fwd.get(from)!.push(edges[ei].to);
|
|
79
|
+
indeg.set(edges[ei].to, indeg.get(edges[ei].to)! + 1);
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
const layer = new Map<string, number>(nodeIds.map((id) => [id, 0]));
|
|
83
|
+
const queue = nodeIds.filter((id) => indeg.get(id) === 0);
|
|
84
|
+
for (let qi = 0; qi < queue.length; qi++) {
|
|
85
|
+
const id = queue[qi];
|
|
86
|
+
for (const to of fwd.get(id)!) {
|
|
87
|
+
layer.set(to, Math.max(layer.get(to)!, layer.get(id)! + 1));
|
|
88
|
+
indeg.set(to, indeg.get(to)! - 1);
|
|
89
|
+
if (indeg.get(to) === 0) queue.push(to);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
let maxLayer = 0;
|
|
94
|
+
for (const l of layer.values()) if (l > maxLayer) maxLayer = l;
|
|
95
|
+
return { layer, maxLayer, backEdges };
|
|
96
|
+
}
|
|
@@ -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
|
+
}
|