@johnhenry/sitefile 0.0.1 → 0.0.3

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.
Files changed (130) hide show
  1. package/CHANGELOG.md +480 -3
  2. package/README.md +70 -21
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/canonical.d.ts +16 -0
  6. package/lib/src/canonical.js +46 -0
  7. package/lib/src/car.d.ts +34 -0
  8. package/lib/src/car.js +203 -0
  9. package/lib/src/checklinks.js +8 -2
  10. package/lib/src/cli/bake.js +4 -3
  11. package/lib/src/cli/build-image.d.ts +1 -0
  12. package/lib/src/cli/build-image.js +1 -0
  13. package/lib/src/cli/common.js +4 -1
  14. package/lib/src/cli/hosts.d.ts +5 -0
  15. package/lib/src/cli/hosts.js +78 -0
  16. package/lib/src/cli/images.js +23 -5
  17. package/lib/src/cli/import-config.d.ts +2 -0
  18. package/lib/src/cli/import-config.js +56 -0
  19. package/lib/src/cli/index.d.ts +3 -1
  20. package/lib/src/cli/index.js +31 -2
  21. package/lib/src/cli/integrity.d.ts +2 -0
  22. package/lib/src/cli/integrity.js +77 -0
  23. package/lib/src/cli/network.d.ts +7 -0
  24. package/lib/src/cli/network.js +14 -3
  25. package/lib/src/cli/serve-keys.d.ts +39 -0
  26. package/lib/src/cli/serve-keys.js +106 -0
  27. package/lib/src/cli/serve-worker.js +46 -8
  28. package/lib/src/cli/servers.d.ts +124 -1
  29. package/lib/src/cli/servers.js +705 -62
  30. package/lib/src/cli/up.d.ts +2 -0
  31. package/lib/src/cli/up.js +193 -0
  32. package/lib/src/cli/watch.d.ts +14 -1
  33. package/lib/src/cli/watch.js +20 -3
  34. package/lib/src/cli.js +138 -18
  35. package/lib/src/csp.d.ts +17 -0
  36. package/lib/src/csp.js +52 -0
  37. package/lib/src/dictionary.d.ts +16 -0
  38. package/lib/src/dictionary.js +89 -0
  39. package/lib/src/epub.d.ts +5 -0
  40. package/lib/src/epub.js +113 -0
  41. package/lib/src/errors.d.ts +22 -9
  42. package/lib/src/errors.js +20 -1
  43. package/lib/src/executor.d.ts +31 -1
  44. package/lib/src/executor.js +192 -22
  45. package/lib/src/explain.js +33 -3
  46. package/lib/src/export-for.d.ts +42 -0
  47. package/lib/src/export-for.js +466 -0
  48. package/lib/src/export-formats.d.ts +2 -2
  49. package/lib/src/export-formats.js +52 -2
  50. package/lib/src/fingerprint.d.ts +3 -1
  51. package/lib/src/fingerprint.js +32 -5
  52. package/lib/src/host-config.d.ts +34 -0
  53. package/lib/src/host-config.js +645 -0
  54. package/lib/src/hosts.d.ts +47 -0
  55. package/lib/src/hosts.js +106 -0
  56. package/lib/src/index.d.ts +1 -1
  57. package/lib/src/index.js +1 -1
  58. package/lib/src/integrity.d.ts +115 -0
  59. package/lib/src/integrity.js +273 -0
  60. package/lib/src/language/ast.d.ts +116 -3
  61. package/lib/src/language/ast.js +7 -1
  62. package/lib/src/language/parser.js +176 -7
  63. package/lib/src/language/validate.js +21 -0
  64. package/lib/src/links.d.ts +33 -0
  65. package/lib/src/links.js +271 -3
  66. package/lib/src/lint.d.ts +1 -1
  67. package/lib/src/lint.js +26 -1
  68. package/lib/src/mime-data.d.ts +2 -0
  69. package/lib/src/mime-data.js +92 -0
  70. package/lib/src/oci.d.ts +20 -2
  71. package/lib/src/oci.js +70 -28
  72. package/lib/src/outdated.d.ts +3 -0
  73. package/lib/src/outdated.js +4 -4
  74. package/lib/src/planner.d.ts +69 -2
  75. package/lib/src/planner.js +150 -8
  76. package/lib/src/plugins/cache.d.ts +11 -0
  77. package/lib/src/plugins/cache.js +29 -0
  78. package/lib/src/plugins/host.d.ts +51 -2
  79. package/lib/src/plugins/host.js +144 -18
  80. package/lib/src/plugins/wasm.js +1 -3
  81. package/lib/src/portable.d.ts +8 -0
  82. package/lib/src/portable.js +47 -0
  83. package/lib/src/precache.d.ts +33 -0
  84. package/lib/src/precache.js +75 -0
  85. package/lib/src/precompress.d.ts +19 -0
  86. package/lib/src/precompress.js +35 -0
  87. package/lib/src/qr.d.ts +18 -0
  88. package/lib/src/qr.js +372 -0
  89. package/lib/src/registry-ops.js +4 -2
  90. package/lib/src/reload-client.d.ts +2 -0
  91. package/lib/src/reload-client.js +304 -0
  92. package/lib/src/resources/archive.d.ts +36 -0
  93. package/lib/src/resources/archive.js +338 -67
  94. package/lib/src/resources/convert.js +3 -1
  95. package/lib/src/resources/https.d.ts +9 -1
  96. package/lib/src/resources/https.js +36 -0
  97. package/lib/src/resources/network.d.ts +25 -3
  98. package/lib/src/resources/network.js +77 -6
  99. package/lib/src/secrets.d.ts +12 -3
  100. package/lib/src/secrets.js +18 -5
  101. package/lib/src/serve-auth.d.ts +32 -0
  102. package/lib/src/serve-auth.js +112 -0
  103. package/lib/src/serve-rules.d.ts +83 -7
  104. package/lib/src/serve-rules.js +264 -53
  105. package/lib/src/server.d.ts +437 -10
  106. package/lib/src/server.js +1236 -52
  107. package/lib/src/servers-file.d.ts +36 -0
  108. package/lib/src/servers-file.js +101 -0
  109. package/lib/src/servers.d.ts +109 -7
  110. package/lib/src/servers.js +151 -29
  111. package/lib/src/single-file.d.ts +12 -0
  112. package/lib/src/single-file.js +147 -0
  113. package/lib/src/site.d.ts +54 -0
  114. package/lib/src/site.js +204 -6
  115. package/lib/src/store.js +9 -5
  116. package/lib/src/swbn.d.ts +10 -0
  117. package/lib/src/swbn.js +86 -0
  118. package/lib/src/toml.d.ts +17 -0
  119. package/lib/src/toml.js +323 -0
  120. package/lib/src/wacz.d.ts +6 -0
  121. package/lib/src/wacz.js +96 -0
  122. package/lib/src/warc.d.ts +28 -0
  123. package/lib/src/warc.js +252 -0
  124. package/lib/src/watch.d.ts +12 -1
  125. package/lib/src/watch.js +67 -1
  126. package/lib/src/wbn.d.ts +9 -1
  127. package/lib/src/wbn.js +23 -33
  128. package/lib/src/zstd.d.ts +4 -0
  129. package/lib/src/zstd.js +328 -0
  130. package/package.json +1 -1
package/lib/src/oci.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { readFile } from 'node:fs/promises';
2
3
  import path from 'node:path';
3
4
  import { gunzipSync } from 'node:zlib';
@@ -46,8 +47,16 @@ export const ANN = {
46
47
  files: 'dev.sitefile.files',
47
48
  size: 'dev.sitefile.size',
48
49
  stored: 'dev.sitefile.created',
50
+ /** The number of site layers (`--oci-layers`, issue #214); absent means one. */
51
+ layers: 'dev.sitefile.layers',
49
52
  };
53
+ /** Most site layers `--oci-layers` accepts. */
54
+ export const MAX_OCI_LAYERS = 64;
50
55
  const EPOCH_ISO = '1970-01-01T00:00:00Z';
56
+ /** The site layer (0-based, of `n`) a file belongs to: the first 4 bytes of SHA-256 of its path, mod n. */
57
+ export function layerOf(path, n) {
58
+ return n <= 1 ? 0 : createHash('sha256').update(path).digest().readUInt32BE(0) % n;
59
+ }
51
60
  /** JSON with sorted keys and no whitespace. */
52
61
  export function canonicalJson(v) {
53
62
  if (v === null || typeof v !== 'object')
@@ -81,14 +90,23 @@ function isoOf(epoch) {
81
90
  export function buildOciImage(tree, options = {}) {
82
91
  const root = normalizeOciRoot(options.root);
83
92
  const { os, arch } = parsePlatform(options.platform);
84
- const layerTree = Tree.fromFiles(tree.mountedAt(root));
85
93
  const segs = root === '/' ? [] : root.slice(1).split('/');
86
94
  const dirs = segs.map((_, i) => segs.slice(0, i + 1).join('/'));
87
- const tar = writeTar(layerTree, { epoch: options.epoch ?? 0, dirs });
88
95
  const uncompressed = options.compression === 'none';
89
- const layerBytes = uncompressed ? tar : gzipTar(tar);
90
- const diffId = sha256(tar);
91
- const layerDigest = uncompressed ? diffId : sha256(layerBytes);
96
+ const n = options.layers ?? 1;
97
+ if (!Number.isSafeInteger(n) || n < 1 || n > MAX_OCI_LAYERS)
98
+ throw new SitefileError('E_USAGE', `--oci-layers expects an integer from 1 to ${MAX_OCI_LAYERS}`);
99
+ // Every layer carries the root's parent directories; with one layer this is the image it always was.
100
+ const parts = Array.from({ length: n }, () => []);
101
+ for (const [p, f] of tree.entries())
102
+ parts[layerOf(p, n)].push([p, f]);
103
+ const site = parts.map((files) => {
104
+ const tar = writeTar(Tree.fromFiles(Tree.fromFiles(files).mountedAt(root)), { epoch: options.epoch ?? 0, dirs });
105
+ const bytes = uncompressed ? tar : gzipTar(tar);
106
+ const diffId = sha256(tar);
107
+ return { bytes, diffId, digest: uncompressed ? diffId : sha256(bytes) };
108
+ });
109
+ const { bytes: layerBytes, diffId, digest: layerDigest } = site[0];
92
110
  const size = tree.entries().reduce((n, [, f]) => n + f.bytes.byteLength, 0);
93
111
  const base = options.base;
94
112
  const baseCfg = base?.config ?? {};
@@ -99,6 +117,8 @@ export function buildOciImage(tree, options = {}) {
99
117
  if (typeof v === 'string')
100
118
  labels[k] = v;
101
119
  labels[ANN.root] = root;
120
+ if (n > 1)
121
+ labels[ANN.layers] = String(n);
102
122
  if (options.title)
103
123
  labels[ANN.title] = options.title;
104
124
  if (options.source)
@@ -127,7 +147,7 @@ export function buildOciImage(tree, options = {}) {
127
147
  os: base && typeof baseCfg.os === 'string' ? baseCfg.os : os,
128
148
  created,
129
149
  config: { ...baseInner, Labels: labels },
130
- rootfs: { type: 'layers', diff_ids: [...baseDiffIds, diffId] },
150
+ rootfs: { type: 'layers', diff_ids: [...baseDiffIds, ...site.map((l) => l.diffId)] },
131
151
  history: [...baseHistory, { created: isoOf(options.epoch), created_by: 'sitefile', comment: 'static site files', author: 'sitefile' }],
132
152
  }));
133
153
  const configDigest = sha256(configBytes);
@@ -142,10 +162,11 @@ export function buildOciImage(tree, options = {}) {
142
162
  schemaVersion: 2,
143
163
  mediaType: MEDIA.manifest,
144
164
  config: { mediaType: MEDIA.config, digest: configDigest, size: configBytes.byteLength },
145
- layers: [...baseLayers, { mediaType: uncompressed ? MEDIA.layerTar : MEDIA.layer, digest: layerDigest, size: layerBytes.byteLength }],
165
+ layers: [...baseLayers, ...site.map((l) => ({ mediaType: uncompressed ? MEDIA.layerTar : MEDIA.layer, digest: l.digest, size: l.bytes.byteLength }))],
146
166
  annotations,
147
167
  }));
148
- return { manifestBytes, manifestDigest: sha256(manifestBytes), configBytes, configDigest, layerBytes, layerDigest, diffId, root, baseLayers };
168
+ const extraLayers = n > 1 ? new Map(site.slice(1).map((l) => [l.digest, l.bytes])) : undefined;
169
+ return { manifestBytes, manifestDigest: sha256(manifestBytes), configBytes, configDigest, layerBytes, layerDigest, diffId, root, baseLayers, ...(extraLayers ? { extraLayers } : {}) };
149
170
  }
150
171
  function isRecord(v) {
151
172
  return typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -213,7 +234,7 @@ baseBlobs = new Map(), referrers = []) {
213
234
  { digest: img.manifestDigest, size: img.manifestBytes.byteLength, ...(refName ? { extra: exportNameAnnotations(refName) } : {}) },
214
235
  ...referrers.map((r) => ({ digest: r.descriptor.digest, size: r.descriptor.size, artifactType: r.descriptor.artifactType, extra: r.descriptor.annotations })),
215
236
  ];
216
- const blobs = new Map([[img.manifestDigest, img.manifestBytes], [img.configDigest, img.configBytes], [img.layerDigest, img.layerBytes], ...baseBlobs]);
237
+ const blobs = new Map([[img.manifestDigest, img.manifestBytes], [img.configDigest, img.configBytes], [img.layerDigest, img.layerBytes], ...(img.extraLayers ?? []), ...baseBlobs]);
217
238
  for (const r of referrers)
218
239
  for (const [d, b] of r.blobs)
219
240
  blobs.set(d, b);
@@ -263,9 +284,23 @@ export function parseConfig(bytes) {
263
284
  * carries the `dev.sitefile.root` label (built with BASE). -1 when the image is not a Sitefile image.
264
285
  */
265
286
  export function siteLayerIndex(m, cfg) {
287
+ return siteLayerIndices(m, cfg)[0] ?? -1;
288
+ }
289
+ /**
290
+ * Indices of every layer holding site files: the last `dev.sitefile.layers` layers (`--oci-layers`),
291
+ * else the one {@link siteLayerIndex} names; empty when the image is not a Sitefile image.
292
+ */
293
+ export function siteLayerIndices(m, cfg) {
294
+ const raw = cfg.labels[ANN.layers];
295
+ if (raw !== undefined && cfg.labels[ANN.root] !== undefined) {
296
+ const n = /^[1-9][0-9]{0,1}$/.test(raw) ? Number(raw) : 0;
297
+ if (n < 1 || n > MAX_OCI_LAYERS || n > m.layers.length)
298
+ return [];
299
+ return Array.from({ length: n }, (_, i) => m.layers.length - n + i);
300
+ }
266
301
  if (m.layers.length === 1)
267
- return 0;
268
- return m.layers.length > 1 && cfg.labels[ANN.root] !== undefined ? m.layers.length - 1 : -1;
302
+ return [0];
303
+ return m.layers.length > 1 && cfg.labels[ANN.root] !== undefined ? [m.layers.length - 1] : [];
269
304
  }
270
305
  /**
271
306
  * Decode a site image's files, verifying the layer digest and diff_id.
@@ -273,28 +308,35 @@ export function siteLayerIndex(m, cfg) {
273
308
  * `dev.sitefile.root` label, else `/`), or under `rootOverride` (`FROM image … AT <dir>`).
274
309
  */
275
310
  export async function extractImageFiles(m, cfg, layerBytes, origin, rootOverride) {
276
- const idx = siteLayerIndex(m, cfg);
277
- const layer = m.layers[idx];
278
- if (idx < 0 || !layer || (layer.mediaType !== MEDIA.layer && layer.mediaType !== MEDIA.layerTar)) {
311
+ const blobs = layerBytes instanceof Uint8Array ? [layerBytes] : layerBytes;
312
+ const indices = siteLayerIndices(m, cfg);
313
+ if (indices.length === 0 || indices.length !== blobs.length || indices.some((i) => m.layers[i]?.mediaType !== MEDIA.layer && m.layers[i]?.mediaType !== MEDIA.layerTar)) {
279
314
  throw new SitefileError('E_STORE', `${origin}: not a Sitefile image (only single-layer tar or tar+gzip images, or images built with BASE, hold site files)`);
280
315
  }
281
- if (sha256(layerBytes) !== layer.digest || layerBytes.byteLength !== layer.size) {
282
- throw new SitefileError('E_STORE', `${origin}: layer blob does not match its digest`);
283
- }
284
- let tar = layerBytes;
285
- if (layer.mediaType === MEDIA.layer) {
286
- try {
287
- tar = new Uint8Array(gunzipSync(layerBytes));
316
+ const root = rootOverride ?? cfg.labels[ANN.root] ?? '/';
317
+ let files = [];
318
+ for (const [k, idx] of indices.entries()) {
319
+ const layer = m.layers[idx];
320
+ const bytes = blobs[k];
321
+ if (sha256(bytes) !== layer.digest || bytes.byteLength !== layer.size) {
322
+ throw new SitefileError('E_STORE', `${origin}: layer blob does not match its digest`);
288
323
  }
289
- catch (e) {
290
- throw new SitefileError('E_STORE', `${origin}: layer is not valid gzip`, undefined, { cause: e });
324
+ let tar = bytes;
325
+ if (layer.mediaType === MEDIA.layer) {
326
+ try {
327
+ tar = new Uint8Array(gunzipSync(bytes));
328
+ }
329
+ catch (e) {
330
+ throw new SitefileError('E_STORE', `${origin}: layer is not valid gzip`, undefined, { cause: e });
331
+ }
291
332
  }
333
+ if (sha256(tar) !== cfg.diffIds[idx])
334
+ throw new SitefileError('E_STORE', `${origin}: layer content does not match the config diff_id`);
335
+ const all = await extractArchive(tar, origin, { maxEntries: 1_000_000, maxTotalBytes: 8 * 2 ** 30, maxRatio: Number.MAX_SAFE_INTEGER });
336
+ files = files.concat(all.subtree(normalizeVirtual(root).path).entries());
292
337
  }
293
- if (sha256(tar) !== cfg.diffIds[idx])
294
- throw new SitefileError('E_STORE', `${origin}: layer content does not match the config diff_id`);
295
- const root = rootOverride ?? cfg.labels[ANN.root] ?? '/';
296
- const all = await extractArchive(tar, origin, { maxEntries: 1_000_000, maxTotalBytes: 8 * 2 ** 30, maxRatio: Number.MAX_SAFE_INTEGER });
297
- return all.subtree(normalizeVirtual(root).path);
338
+ // Site layers hold disjoint paths; were one repeated, the upper layer wins, as in a container.
339
+ return Tree.empty.withFiles(files, 'overwrite');
298
340
  }
299
341
  /**
300
342
  * Label values for an image built from `contextDir`: the title (directory name),
@@ -1,3 +1,4 @@
1
+ import { type Needs } from './errors.js';
1
2
  import { type BuildOptions } from './executor.js';
2
3
  /**
3
4
  * `sitefile outdated` (issue #104): report, for every remote input, whether what it points at today
@@ -32,9 +33,11 @@ export interface OutdatedEntry {
32
33
  readonly status: OutdatedStatus;
33
34
  /** Images only (BASE and FROM image): a greater version-like tag of the same shape. */
34
35
  readonly newerTag: string | null;
36
+ /** `needs` only when the error carries one (E_HOST_BLOCKED: the host to allow). */
35
37
  readonly error: {
36
38
  readonly code: string;
37
39
  readonly message: string;
40
+ readonly needs?: Needs;
38
41
  } | null;
39
42
  }
40
43
  export interface OutdatedReport {
@@ -49,7 +49,7 @@ export function newerVersionTag(current, tags) {
49
49
  }
50
50
  function errorOf(e, secrets) {
51
51
  if (isSitefileError(e))
52
- return { code: e.code, message: redactSecrets(e.detail, secrets) };
52
+ return { code: e.code, message: redactSecrets(e.detail, secrets), ...(e.needs ? { needs: { kind: e.needs.kind, name: e.needs.name, flag: e.needs.flag } } : {}) };
53
53
  throw redactError(e, secrets);
54
54
  }
55
55
  /** An entry with its keys in the documented order (the JSON output is compared across implementations). */
@@ -89,7 +89,7 @@ export async function outdated(options) {
89
89
  }
90
90
  else {
91
91
  try {
92
- const originHeaders = secretHeaders(spec, options.secrets);
92
+ const originHeaders = secretHeaders(spec, options.secrets, { url: loc.repo, network: policy.network });
93
93
  const latest = await resolveRef(loc.repo, loc.ref, { policy, span: spec.span, ...(originHeaders ? { originHeaders } : {}) });
94
94
  inputs.push(entry({ ...row, latest, status: statusOf(pin, latest), error: null }));
95
95
  }
@@ -105,7 +105,7 @@ export async function outdated(options) {
105
105
  const pinnedBy = spec.integrity ? 'integrity' : locked ? 'lockfile' : null;
106
106
  const row = { kind: 'import', name, source: url, pin, pinnedBy, newerTag: null };
107
107
  try {
108
- const originHeaders = secretHeaders(spec, options.secrets);
108
+ const originHeaders = secretHeaders(spec, options.secrets, { url, network: policy.network });
109
109
  const { bytes } = await fetchRemote(url, policy, undefined, originHeaders ? { originHeaders } : {});
110
110
  const latest = sha256(bytes);
111
111
  inputs.push(entry({ ...row, latest, status: statusOf(pin, latest), error: null }));
@@ -120,7 +120,7 @@ export async function outdated(options) {
120
120
  let sub;
121
121
  try {
122
122
  sub = await readImportedSitefile(spec, source, importedStageRefs(sp.stages), async (s, loc) => {
123
- const originHeaders = secretHeaders(s, options.secrets);
123
+ const originHeaders = secretHeaders(s, options.secrets, { url: loc.repo, network: policy.network });
124
124
  const want = loc.commit ?? lock?.getGit(loc.url)?.commit;
125
125
  const objs = await fetchGitCommit(loc.repo, loc.ref, want, { policy, span: s.span, ...(originHeaders ? { originHeaders } : {}) }, limits);
126
126
  return { commit: objs.commit, selection: selectGitPath(objs, loc, limits, s.span) };
@@ -1,5 +1,5 @@
1
1
  import { type SourceSpan } from './errors.js';
2
- import { type EscapeMode, type RedirectStatus, type ExportFormat, type ImportKind, type OciCompression, type Operand, type Program } from './language/ast.js';
2
+ import { type EscapeMode, type RedirectStatus, type ExportFormat, type ExportHost, type ImportKind, type OciCompression, type Operand, type PrecompressFormat, type Program } from './language/ast.js';
3
3
  import { type Scalar } from './values.js';
4
4
  import { type GitLocation } from './resources/git.js';
5
5
  import type { TemplateNode } from './render.js';
@@ -101,14 +101,32 @@ export interface RedirectSpec {
101
101
  readonly overwrite: boolean;
102
102
  readonly span: SourceSpan;
103
103
  }
104
- /** A HEADER, evaluated; written to `/_headers` at EXPORT. */
104
+ /** A HEADER (or a MIME, as a `Content-Type` rule), evaluated; written to `/_headers` at EXPORT. */
105
105
  export interface HeaderSpec {
106
106
  readonly pattern: string;
107
107
  readonly name: string;
108
108
  readonly value: string;
109
109
  readonly overwrite: boolean;
110
110
  readonly span: SourceSpan;
111
+ /** Set for a MIME line (names it in origins and `why`). */
112
+ readonly instruction?: 'MIME';
111
113
  }
114
+ /** A file whose text the planner wrote (ROBOTS: `/robots.txt`, SECURITY_TXT: `/.well-known/security.txt`). */
115
+ export interface TextFileOperation<K extends 'ROBOTS' | 'SECURITY_TXT'> {
116
+ readonly kind: K;
117
+ readonly dest: string;
118
+ readonly text: string;
119
+ readonly overwrite: boolean;
120
+ readonly span: SourceSpan;
121
+ }
122
+ /** A CSP, evaluated: the base policy (checked) and where the per-page policies go. */
123
+ export interface CspSpec {
124
+ readonly policy: string;
125
+ readonly meta: boolean;
126
+ readonly span: SourceSpan;
127
+ }
128
+ /** CSP's base policy when POLICY is not given: same-origin resources only, no plugins, no `<base>` hijacking. */
129
+ export declare const DEFAULT_CSP = "default-src 'self'; base-uri 'self'; object-src 'none'";
112
130
  export type Operation = {
113
131
  /** Report the references in the tree's HTML and CSS files that point at nothing. */
114
132
  readonly kind: 'CHECKLINKS';
@@ -126,10 +144,40 @@ export type Operation = {
126
144
  readonly patterns: readonly string[];
127
145
  /** `MANIFEST <dest>`: the JSON map of old to new paths. */
128
146
  readonly manifest?: string;
147
+ /** `INTEGRITY`: add `integrity="sha384-…"` to the script and stylesheet tags that load a renamed file. */
148
+ readonly integrity?: true;
129
149
  /** The EXPORT path: absolute references (`/img/a.png`) in HTML and CSS name files below it. */
130
150
  readonly root: string;
131
151
  readonly overwrite: boolean;
132
152
  readonly span: SourceSpan;
153
+ } | TextFileOperation<'ROBOTS'> | TextFileOperation<'SECURITY_TXT'> | {
154
+ /** Add a canonical link to every page below `root` that has none. */
155
+ readonly kind: 'CANONICAL';
156
+ /** Checked base URL without trailing slashes. */
157
+ readonly base: string;
158
+ readonly pretty: boolean;
159
+ /** The EXPORT path: a page's URL is its path below it. */
160
+ readonly root: string;
161
+ readonly span: SourceSpan;
162
+ } | {
163
+ /** Write a `.gz` sidecar for each matching compressible file of at least `min` bytes, when smaller. */
164
+ readonly kind: 'PRECOMPRESS';
165
+ readonly formats: readonly PrecompressFormat[];
166
+ /** Checked absolute patterns, NFC; a trailing `/` became `/**`. */
167
+ readonly patterns: readonly string[];
168
+ readonly min: number;
169
+ readonly overwrite: boolean;
170
+ readonly span: SourceSpan;
171
+ } | {
172
+ /** A precache manifest of the files matching `patterns` (checked, NFC), written to `dest` and/or injected into `into`. */
173
+ readonly kind: 'PRECACHE';
174
+ readonly patterns: readonly string[];
175
+ readonly dest?: string;
176
+ readonly into?: string;
177
+ /** The EXPORT path: URLs are paths below it. */
178
+ readonly root: string;
179
+ readonly overwrite: boolean;
180
+ readonly span: SourceSpan;
133
181
  } | {
134
182
  /** sitemaps.org XML of the `.html` files in the tree at this point. */
135
183
  readonly kind: 'SITEMAP';
@@ -261,10 +309,27 @@ export interface Plan {
261
309
  readonly exportRoot: string | undefined;
262
310
  /** `COMPRESSION` clause of EXPORT ... AS oci or wbn (undefined: gzip for oci, none for wbn). */
263
311
  readonly exportCompression: OciCompression | undefined;
312
+ /** `KEY <secret-id>` of EXPORT ... AS swbn: the --secret holding the signing key. */
313
+ readonly exportKey?: string;
314
+ /** `FOR <host>` of EXPORT: which host's files the REDIRECT and HEADER rules become (undefined: `_redirects`/`_headers`). */
315
+ readonly exportFor?: {
316
+ readonly host: ExportHost;
317
+ readonly span: SourceSpan;
318
+ };
264
319
  /** REDIRECT lines in source order (any stage); EXPORT writes them to `/_redirects`. */
265
320
  readonly redirects: readonly RedirectSpec[];
266
321
  /** HEADER lines in source order (any stage); EXPORT writes them to `/_headers`. */
267
322
  readonly headers: readonly HeaderSpec[];
323
+ /**
324
+ * Set when EXPORT adds `Cache-Control` lines for the fingerprinted files (and the pages) to `/_headers`:
325
+ * the Sitefile has a FINGERPRINT, none of them says `--no-cache-headers`, and no HEADER sets
326
+ * `Cache-Control` itself. `span` is the first FINGERPRINT's (the origin of the lines).
327
+ */
328
+ readonly cacheHeaders?: {
329
+ readonly span: SourceSpan;
330
+ };
331
+ /** The CSP instruction (any stage): EXPORT adds a policy for every exported page. */
332
+ readonly csp?: CspSpec;
268
333
  readonly warnings: readonly string[];
269
334
  /**
270
335
  * `--target <stage>`: the build stops after this stage and exports its whole tree (see {@link targetPlan}).
@@ -284,6 +349,8 @@ export declare function plan(program: Program, buildArgs?: Readonly<Record<strin
284
349
  * name is a usage error that lists the named stages.
285
350
  */
286
351
  export declare function targetPlan(p: Plan, name: string): Plan;
352
+ /** PRECOMPRESS leaves smaller files alone: below about 1 KiB compression saves little. */
353
+ export declare const DEFAULT_PRECOMPRESS_MIN = 1024;
287
354
  /** A reference to a stage of an imported Sitefile (`FROM theme+assets`, `COPY --from=theme+assets …`). */
288
355
  export interface ImportedStageRef {
289
356
  /** `theme+assets` */
@@ -3,10 +3,12 @@ import { importedStage, isFragment, isImageBase, isInline, stageNames } from './
3
3
  import { normalizeLocal, normalizeVirtual } from './paths.js';
4
4
  import { parseRef } from './ref.js';
5
5
  import { checkPattern } from './fingerprint.js';
6
- import { checkBaseUrl, checkHeaderName, checkHeaderValue, checkRedirectTarget, checkSitePath } from './site.js';
6
+ import { checkBaseUrl, checkFieldUri, checkCspPolicy, checkHeaderName, checkHeaderValue, checkMimeExtension, checkMimeType, checkRedirectTarget, checkSitePath, pageUrl, parseFeedDate, robotsTxt, securityTxt } from './site.js';
7
7
  import { coerce, evaluateOperand } from './values.js';
8
8
  import { isGitUri, parseGitUri } from './resources/git.js';
9
9
  import { parseFragmentBody } from './language/validate.js';
10
+ /** CSP's base policy when POLICY is not given: same-origin resources only, no plugins, no `<base>` hijacking. */
11
+ export const DEFAULT_CSP = "default-src 'self'; base-uri 'self'; object-src 'none'";
10
12
  const URL_RE = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//;
11
13
  const IMPORT_REF_RE = /^([A-Za-z_][A-Za-z0-9_]*):(.*)$/s;
12
14
  /**
@@ -22,6 +24,11 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
22
24
  const tools = [];
23
25
  const redirects = [];
24
26
  const headers = [];
27
+ const fingerprints = [];
28
+ const sitemapUrls = [];
29
+ const robots = [];
30
+ let csp;
31
+ const mimes = new Map();
25
32
  const warnings = [];
26
33
  const declaredArgs = new Set();
27
34
  const allStageNames = stageNames(program.instructions);
@@ -32,6 +39,8 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
32
39
  let exportBase;
33
40
  let exportRoot;
34
41
  let exportCompression;
42
+ let exportKey;
43
+ let exportFor;
35
44
  const bind = (name, raw, type, span, what) => {
36
45
  vars.set(name, coerce(raw, type, span, what));
37
46
  };
@@ -185,14 +194,76 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
185
194
  break;
186
195
  case 'SITEMAP': {
187
196
  const base = checkBaseUrl(evaluateOperand(ins.base, vars), 'SITEMAP BASE', ins.base.span);
188
- operations().push({ kind: 'SITEMAP', base, dest: fileDest(ins.dest, vars, '/sitemap.xml', 'SITEMAP'), overwrite: ins.overwrite, span: ins.span });
197
+ const dest = fileDest(ins.dest, vars, '/sitemap.xml', 'SITEMAP');
198
+ sitemapUrls.push(pageUrl(base, dest));
199
+ operations().push({ kind: 'SITEMAP', base, dest, overwrite: ins.overwrite, span: ins.span });
200
+ break;
201
+ }
202
+ case 'ROBOTS': {
203
+ const rules = ins.rules.map((r) => ({ allow: r.allow, path: checkSitePath(evaluateOperand(r.path, vars), `ROBOTS ${r.allow ? 'ALLOW' : 'DISALLOW'} path`, r.path.span) }));
204
+ const op = { kind: 'ROBOTS', dest: fileDest(ins.dest, vars, '/robots.txt', 'ROBOTS'), text: robotsTxt(rules, []), overwrite: ins.overwrite, span: ins.span };
205
+ operations().push(op);
206
+ // The Sitemap lines name every SITEMAP of the Sitefile, also later ones: filled in below.
207
+ if (ins.sitemap)
208
+ robots.push({ op, rules, stage: stages.length - 1 });
209
+ break;
210
+ }
211
+ case 'SECURITY_TXT': {
212
+ const raw = evaluateOperand(ins.expires, vars);
213
+ const date = parseFeedDate(raw);
214
+ if (!date)
215
+ throw new SitefileError('E_VALIDATION', `SECURITY_TXT EXPIRES '${raw}' must be a date (YYYY-MM-DD) or an RFC 3339 date-time; durations are not accepted, so the file is the same on every build`, ins.expires.span);
216
+ const now = Date.now() / 1000;
217
+ if (date.seconds <= now)
218
+ warnings.push(`${program.file}:${ins.span.line}: SECURITY_TXT EXPIRES ${raw} is in the past, so security.txt is already stale (RFC 9116); set a later date`);
219
+ else if (date.seconds - now < 30 * 86400)
220
+ warnings.push(`${program.file}:${ins.span.line}: SECURITY_TXT EXPIRES ${raw} is less than 30 days away; set a later date before it passes`);
221
+ const uri = (o, field, schemes) => checkFieldUri(evaluateOperand(o, vars), field, schemes, o.span);
222
+ const text = securityTxt({
223
+ contact: ins.contact.map((o) => uri(o, 'CONTACT', ['mailto:', 'tel:', 'https://'])),
224
+ expires: date.text,
225
+ encryption: ins.encryption.map((o) => uri(o, 'ENCRYPTION', ['https://', 'openpgp4fpr:', 'dns:'])),
226
+ policy: ins.policy.map((o) => uri(o, 'POLICY', ['https://'])),
227
+ });
228
+ operations().push({ kind: 'SECURITY_TXT', dest: fileDest(ins.dest, vars, '/.well-known/security.txt', 'SECURITY_TXT'), text, overwrite: ins.overwrite, span: ins.span });
189
229
  break;
190
230
  }
191
231
  case 'FINGERPRINT': {
192
232
  const patterns = ins.patterns.map((o) => checkPattern(evaluateOperand(o, vars), o.span));
193
233
  const manifest = ins.manifest ? fileDest(ins.manifest, vars, '', 'FINGERPRINT MANIFEST') : undefined;
194
234
  // `root` is the EXPORT path, filled in below (EXPORT is the last instruction).
195
- operations().push({ kind: 'FINGERPRINT', patterns, ...(manifest !== undefined ? { manifest } : {}), root: '/', overwrite: ins.overwrite, span: ins.span });
235
+ operations().push({
236
+ kind: 'FINGERPRINT',
237
+ patterns,
238
+ ...(manifest !== undefined ? { manifest } : {}),
239
+ ...(ins.integrity && { integrity: true }),
240
+ root: '/',
241
+ overwrite: ins.overwrite,
242
+ span: ins.span,
243
+ });
244
+ fingerprints.push({ span: ins.span, headers: !ins.noCacheHeaders });
245
+ break;
246
+ }
247
+ case 'CANONICAL':
248
+ // `root` is the EXPORT path, filled in below.
249
+ operations().push({ kind: 'CANONICAL', base: checkBaseUrl(evaluateOperand(ins.base, vars), 'CANONICAL BASE', ins.base.span), pretty: ins.pretty, root: '/', span: ins.span });
250
+ break;
251
+ case 'PRECOMPRESS':
252
+ operations().push({
253
+ kind: 'PRECOMPRESS',
254
+ formats: ins.formats,
255
+ patterns: ins.patterns.map((o) => checkPattern(evaluateOperand(o, vars), o.span, 'PRECOMPRESS')),
256
+ min: ins.min ? minSize(ins.min, vars) : DEFAULT_PRECOMPRESS_MIN,
257
+ overwrite: ins.overwrite,
258
+ span: ins.span,
259
+ });
260
+ break;
261
+ case 'PRECACHE': {
262
+ const patterns = ins.patterns.map((o) => checkPattern(evaluateOperand(o, vars), o.span, 'PRECACHE'));
263
+ const into = ins.into ? fileDest(ins.into, vars, '', 'PRECACHE INTO') : undefined;
264
+ const dest = ins.dest || !into ? fileDest(ins.dest, vars, '/sw-manifest.json', 'PRECACHE') : undefined;
265
+ // `root` is the EXPORT path, filled in below.
266
+ operations().push({ kind: 'PRECACHE', patterns, ...(dest !== undefined ? { dest } : {}), ...(into !== undefined ? { into } : {}), root: '/', overwrite: ins.overwrite, span: ins.span });
196
267
  break;
197
268
  }
198
269
  case 'CHECKLINKS':
@@ -233,6 +304,22 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
233
304
  });
234
305
  break;
235
306
  }
307
+ case 'CSP': {
308
+ if (csp)
309
+ throw new SitefileError('E_VALIDATION', `CSP given twice (line ${csp.span.line} already sets the policy)`, ins.span);
310
+ const policy = ins.policy ? checkCspPolicy(evaluateOperand(ins.policy, vars), ins.policy.span) : DEFAULT_CSP;
311
+ csp = { policy, meta: ins.meta, span: ins.span };
312
+ break;
313
+ }
314
+ case 'MIME': {
315
+ const ext = checkMimeExtension(evaluateOperand(ins.ext, vars), ins.ext.span);
316
+ const prior = mimes.get(ext);
317
+ if (prior !== undefined)
318
+ throw new SitefileError('E_VALIDATION', `MIME ${ext} given twice (line ${prior} already sets its type)`, ins.ext.span);
319
+ mimes.set(ext, ins.span.line);
320
+ headers.push({ pattern: `/*${ext}`, name: 'Content-Type', value: checkMimeType(evaluateOperand(ins.type, vars), ins.type.span), overwrite: false, span: ins.span, instruction: 'MIME' });
321
+ break;
322
+ }
236
323
  case 'EXPORT':
237
324
  exportPath = normalizeVirtual(evaluateOperand(ins.path, vars), ins.path.span, 'EXPORT path').path;
238
325
  exportFormat = ins.format;
@@ -240,15 +327,34 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
240
327
  if (ins.at && ins.format !== 'oci')
241
328
  throw new SitefileError('E_VALIDATION', 'EXPORT ... AT applies only to AS oci', ins.at.span);
242
329
  exportRoot = ins.at ? normalizeVirtual(evaluateOperand(ins.at, vars), ins.at.span, 'EXPORT AT path').path : undefined;
243
- if (ins.compression && ins.format !== 'oci' && ins.format !== 'wbn')
244
- throw new SitefileError('E_VALIDATION', 'EXPORT ... COMPRESSION applies only to AS oci and AS wbn', ins.compression.span);
330
+ if (ins.compression && ins.format !== 'oci' && ins.format !== 'wbn' && ins.format !== 'warc')
331
+ throw new SitefileError('E_VALIDATION', 'EXPORT ... COMPRESSION applies only to AS oci, AS wbn and AS warc', ins.compression.span);
245
332
  exportCompression = ins.compression?.value;
333
+ if (ins.key && ins.format !== 'swbn')
334
+ throw new SitefileError('E_VALIDATION', 'EXPORT ... KEY applies only to AS swbn', ins.key.span);
335
+ if (ins.format === 'swbn' && !ins.key)
336
+ throw new SitefileError('E_VALIDATION', 'EXPORT ... AS swbn needs KEY <secret-id>: the --secret that holds the Ed25519 signing key', ins.span);
337
+ exportKey = ins.key?.id;
338
+ if (ins.forHost && !['directory', 'zip', 'tar', 'tgz'].includes(ins.format)) {
339
+ throw new SitefileError('E_VALIDATION', `EXPORT ... FOR applies only to AS directory, zip, tar and tgz, not ${ins.format}`, ins.forHost.span);
340
+ }
341
+ exportFor = ins.forHost ? { host: ins.forHost.value, span: ins.forHost.span } : undefined;
246
342
  break;
247
343
  }
248
344
  }
345
+ for (const r of robots) {
346
+ if (sitemapUrls.length === 0)
347
+ throw new SitefileError('E_VALIDATION', 'ROBOTS … SITEMAP: the Sitefile has no SITEMAP to point to (add SITEMAP BASE <url>, or leave out SITEMAP)', r.op.span);
348
+ const ops = stages[r.stage].operations;
349
+ ops[ops.indexOf(r.op)] = { ...r.op, text: robotsTxt(r.rules, [...new Set(sitemapUrls)]) };
350
+ }
351
+ const cspHeader = headers.find((h) => h.name.toLowerCase() === 'content-security-policy');
352
+ if (csp && cspHeader) {
353
+ throw new SitefileError('E_VALIDATION', `CSP and the HEADER on line ${cspHeader.span.line} both set Content-Security-Policy; keep one (put your policy in CSP POLICY "…")`, csp.span);
354
+ }
249
355
  for (const st of stages) {
250
356
  st.operations.forEach((op, i) => {
251
- if (op.kind === 'FINGERPRINT')
357
+ if (op.kind === 'FINGERPRINT' || op.kind === 'CANONICAL' || op.kind === 'PRECACHE')
252
358
  st.operations[i] = { ...op, root: exportPath ?? '/' };
253
359
  if (op.kind === 'CHECKLINKS')
254
360
  st.operations[i] = { ...op, root: exportPath ?? '/', redirects: redirects.map((r) => r.from) };
@@ -268,7 +374,32 @@ export function plan(program, buildArgs = {}, argSource = (n) => `--build-arg ${
268
374
  // validate() guarantees both; this keeps the types honest.
269
375
  throw new SitefileError('E_VALIDATION', 'a Sitefile needs FROM and EXPORT');
270
376
  }
271
- return { file: program.file, stages, vars, fragments, imports: [...imports.values()], plugins, tools, exportPath, exportFormat, exportBase, exportRoot, exportCompression, redirects, headers, warnings };
377
+ // FINGERPRINT's Cache-Control lines: unless turned off, or a HEADER already sets Cache-Control.
378
+ const firstFingerprint = fingerprints[0];
379
+ const cacheHeaders = firstFingerprint && fingerprints.every((f) => f.headers) && !headers.some((h) => h.name.toLowerCase() === 'cache-control')
380
+ ? { span: firstFingerprint.span }
381
+ : undefined;
382
+ return {
383
+ file: program.file,
384
+ stages,
385
+ vars,
386
+ fragments,
387
+ imports: [...imports.values()],
388
+ plugins,
389
+ tools,
390
+ exportPath,
391
+ exportFormat,
392
+ exportBase,
393
+ exportRoot,
394
+ exportCompression,
395
+ ...(exportKey !== undefined ? { exportKey } : {}),
396
+ ...(exportFor ? { exportFor } : {}),
397
+ redirects,
398
+ headers,
399
+ ...(cacheHeaders ? { cacheHeaders } : {}),
400
+ ...(csp ? { csp } : {}),
401
+ warnings,
402
+ };
272
403
  }
273
404
  /**
274
405
  * `--target <name>`: keep the stages up to and including the named one, and export that stage's whole tree
@@ -284,7 +415,8 @@ export function targetPlan(p, name) {
284
415
  ? `--target '${name}' does not name a stage (stages: ${names.join(', ')})`
285
416
  : `--target '${name}' does not name a stage (the Sitefile has no named stages; name one with FROM … AS <name>)`);
286
417
  }
287
- return { ...p, stages: p.stages.slice(0, index + 1), exportPath: '/', redirects: [], headers: [], target: name };
418
+ const { cacheHeaders: _, csp: _csp, ...rest } = p;
419
+ return { ...rest, stages: p.stages.slice(0, index + 1), exportPath: '/', redirects: [], headers: [], target: name };
288
420
  }
289
421
  /** `IMPORT … SCHEMA <path>`: a local `.json`, `.yaml` or `.yml` file in the build context. */
290
422
  function schemaSpec(name, op, vars, span) {
@@ -313,6 +445,16 @@ function pageSize(op, vars) {
313
445
  }
314
446
  return Number(raw);
315
447
  }
448
+ /** PRECOMPRESS leaves smaller files alone: below about 1 KiB compression saves little. */
449
+ export const DEFAULT_PRECOMPRESS_MIN = 1024;
450
+ /** `PRECOMPRESS … MIN <bytes>`: a whole number of bytes. */
451
+ function minSize(op, vars) {
452
+ const raw = evaluateOperand(op, vars);
453
+ if (!/^(0|[1-9][0-9]{0,9})$/.test(raw)) {
454
+ throw new SitefileError('E_VALIDATION', `PRECOMPRESS … MIN: '${raw}' is not a size (a whole number of bytes from 0 to 9999999999)`, op.span);
455
+ }
456
+ return Number(raw);
457
+ }
316
458
  /** `TO <dest>` of SITEMAP/FEED or `MANIFEST <dest>` of FINGERPRINT (a file path), or the default. */
317
459
  function fileDest(op, vars, fallback, what) {
318
460
  if (!op)
@@ -89,6 +89,17 @@ export declare class TransformCache {
89
89
  /** Entries, blobs and bytes per plugin, sorted by name (entries that record none first). Reads no blob. */
90
90
  usageByPlugin(): Promise<PluginCacheUsage[]>;
91
91
  }
92
+ /**
93
+ * What INTEGRITY on a JavaScript plugin pins: `sha256:` + digestFolder of the plugin's folder.
94
+ * Refused (a message, not a digest) when the folder holds anything but regular files and
95
+ * directories (a symlink could change what an import resolves to without changing any file) or
96
+ * is over digestFolder's limits.
97
+ */
98
+ export declare function pluginFolderIntegrity(dir: string): Promise<{
99
+ digest: string;
100
+ } | {
101
+ problem: string;
102
+ }>;
92
103
  /** Digest of every regular file under `dir` (a plugin can read all of them, so any may change its output). */
93
104
  export declare function digestFolder(dir: string, limits?: {
94
105
  files: number;
@@ -298,6 +298,35 @@ export class TransformCache {
298
298
  return out;
299
299
  }
300
300
  }
301
+ /**
302
+ * What INTEGRITY on a JavaScript plugin pins: `sha256:` + digestFolder of the plugin's folder.
303
+ * Refused (a message, not a digest) when the folder holds anything but regular files and
304
+ * directories (a symlink could change what an import resolves to without changing any file) or
305
+ * is over digestFolder's limits.
306
+ */
307
+ export async function pluginFolderIntegrity(dir) {
308
+ const other = async (rel) => {
309
+ const entries = (await readdir(path.join(dir, rel), { withFileTypes: true })).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
310
+ for (const e of entries) {
311
+ const r = rel ? `${rel}/${e.name}` : e.name;
312
+ if (e.isDirectory()) {
313
+ const found = await other(r);
314
+ if (found !== undefined)
315
+ return found;
316
+ }
317
+ else if (!e.isFile())
318
+ return r;
319
+ }
320
+ return undefined;
321
+ };
322
+ const odd = await other('');
323
+ if (odd !== undefined)
324
+ return { problem: `contains ${odd}, which is not a regular file or directory (a pinned folder can hold only those)` };
325
+ const hex = await digestFolder(dir);
326
+ if (hex === undefined)
327
+ return { problem: 'is too large to pin (more than 2000 files or 128 MiB)' };
328
+ return { digest: `sha256:${hex}` };
329
+ }
301
330
  /** Digest of every regular file under `dir` (a plugin can read all of them, so any may change its output). */
302
331
  export async function digestFolder(dir, limits = { files: 2000, bytes: 128 * 1024 * 1024 }) {
303
332
  const h = createHash('sha256');