@johnhenry/sitefile 0.0.2 → 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 +467 -0
  2. package/README.md +55 -6
  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 +141 -16
  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
@@ -0,0 +1,147 @@
1
+ import { SitefileError } from './errors.js';
2
+ import { encodePath, resolveReference, scanCss, scanHtml } from './links.js';
3
+ import { mimeTypeFor, validateBaseUrl } from './wbn.js';
4
+ /**
5
+ * Single-file page exports (issue #210): `EXPORT … AS html` inlines every asset a page references as a
6
+ * `data:` URI; `AS mhtml` writes the page and those assets as one multipart/related (MHTML) file.
7
+ *
8
+ * The page is `/index.html` of the exported tree, or the file the EXPORT path names. Its references are
9
+ * found with the FINGERPRINT scanner (src/links.ts): every URL in an attribute (`src`, `srcset`, `href`
10
+ * of <link>, `poster`, …) and in its CSS (`<style>`, `style=""`) is an asset, except `href` of <a> and
11
+ * <area> (navigation, kept as written), and references to other HTML files (pages, not assets). A stylesheet's own `url()` and `@import` references are inlined
12
+ * into it first, recursively. External (http, https, `//`) and non-file URLs (`data:`, `mailto:`, `#x`)
13
+ * are kept as written; a reference to a file that is not in the tree, or to a directory, fails with
14
+ * E_EXPORT. Scripts are inlined byte for byte (what they load at run time is not followed).
15
+ */
16
+ const NAVIGATION = new Set(['a href', 'area href']);
17
+ const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
18
+ const enc = new TextEncoder();
19
+ function text(tree, path) {
20
+ const n = tree.get(path);
21
+ if (!n)
22
+ throw new SitefileError('E_EXPORT', `single-file export: '${path}' does not exist`);
23
+ try {
24
+ return UTF8.decode(n.bytes);
25
+ }
26
+ catch {
27
+ throw new SitefileError('E_EXPORT', `single-file export: '${path}' is not valid UTF-8`);
28
+ }
29
+ }
30
+ /** `data:` media type: the wbn MIME table's type, without spaces. */
31
+ const mediaType = (path) => mimeTypeFor(path).replace(/ /g, '');
32
+ const isCss = (path) => path.toLowerCase().endsWith('.css');
33
+ /** The file a reference names when it is an asset to inline (undefined: keep as written). */
34
+ function assetOf(r, from) {
35
+ if (r.element !== undefined && NAVIGATION.has(r.element))
36
+ return undefined;
37
+ const t = resolveReference(r.url, from, '/');
38
+ if (t.kind !== 'internal')
39
+ return undefined;
40
+ if (t.dir)
41
+ throw new SitefileError('E_EXPORT', `single-file export: cannot inline '${r.url}' in ${from}:${r.line}: it names a directory`);
42
+ // Pages are documents, not assets (a canonical or alternate <link>, an <iframe>): kept as written.
43
+ if (/\.html?$/i.test(t.path))
44
+ return undefined;
45
+ const hash = r.url.indexOf('#');
46
+ return { path: t.path, fragment: hash === -1 ? '' : r.url.slice(hash) };
47
+ }
48
+ function missing(r, from, path) {
49
+ return new SitefileError('E_EXPORT', `single-file export: cannot inline '${r.url}' in ${from}:${r.line}: no file ${path} in the exported tree`);
50
+ }
51
+ /** The exported page: the EXPORT path's file, else `/index.html`. */
52
+ function pageOf(tree, page) {
53
+ const p = page ?? '/index.html';
54
+ if (!tree.get(p))
55
+ throw new SitefileError('E_EXPORT', `single-file export: the exported tree has no ${p} (export a directory with an index.html, or name the page: EXPORT /page.html AS html)`);
56
+ return p;
57
+ }
58
+ /** `EXPORT … AS html`: the page with every asset inlined as a data: URI. */
59
+ export function writeSingleFile(tree, page) {
60
+ const p = pageOf(tree, page);
61
+ const uris = new Map();
62
+ const dataUri = (path, stack) => {
63
+ const known = uris.get(path);
64
+ if (known !== undefined)
65
+ return known;
66
+ const node = tree.get(path);
67
+ const bytes = isCss(path) ? enc.encode(inlineCss(path, [...stack, path])) : node.bytes;
68
+ const uri = `data:${mediaType(path)};base64,${Buffer.from(bytes).toString('base64')}`;
69
+ uris.set(path, uri);
70
+ return uri;
71
+ };
72
+ const rewrite = (src, refs, from, stack) => {
73
+ let out = '';
74
+ let at = 0;
75
+ for (const r of refs) {
76
+ const a = assetOf(r, from);
77
+ if (!a)
78
+ continue;
79
+ if (!tree.get(a.path))
80
+ throw missing(r, from, a.path);
81
+ if (stack.includes(a.path))
82
+ throw new SitefileError('E_EXPORT', `single-file export: ${from} imports ${a.path}, which imports it back (a cycle)`);
83
+ out += src.slice(at, r.start) + dataUri(a.path, stack) + a.fragment;
84
+ at = r.end;
85
+ }
86
+ return out + src.slice(at);
87
+ };
88
+ const inlineCss = (path, stack) => {
89
+ const css = text(tree, path);
90
+ return rewrite(css, scanCss(css), path, stack);
91
+ };
92
+ const html = text(tree, p);
93
+ return enc.encode(rewrite(html, scanHtml(html), p, [p]));
94
+ }
95
+ /** The default MHTML base URL (no EXPORT BASE or --base-url). */
96
+ export const MHTML_DEFAULT_BASE = 'https://site.invalid/';
97
+ /** The page and every asset it references (through CSS too), each once, in the order first referenced. */
98
+ function assetsOf(tree, page) {
99
+ const out = [page];
100
+ const visit = (from) => {
101
+ const src = text(tree, from);
102
+ const refs = from === page || !isCss(from) ? scanHtml(src) : scanCss(src);
103
+ for (const r of refs) {
104
+ const a = assetOf(r, from);
105
+ if (!a)
106
+ continue;
107
+ if (!tree.get(a.path))
108
+ throw missing(r, from, a.path);
109
+ if (out.includes(a.path))
110
+ continue;
111
+ out.push(a.path);
112
+ if (isCss(a.path))
113
+ visit(a.path);
114
+ }
115
+ };
116
+ visit(page);
117
+ return out;
118
+ }
119
+ const BOUNDARY = '----MultipartBoundary--sitefile----';
120
+ function base64Lines(bytes) {
121
+ const b = Buffer.from(bytes).toString('base64');
122
+ let out = '';
123
+ for (let i = 0; i < b.length; i += 76)
124
+ out += b.slice(i, i + 76) + '\r\n';
125
+ return out;
126
+ }
127
+ /**
128
+ * `EXPORT … AS mhtml [BASE <url>]`: the page and its assets as MHTML (RFC 2557 multipart/related, as
129
+ * Chrome saves "Webpage, Single File"): each part base64 with its Content-Type and an absolute
130
+ * Content-Location under the base URL (default `https://site.invalid/`), the page first. References
131
+ * are kept as written; the browser resolves them against the page's Content-Location.
132
+ */
133
+ export function writeMhtml(tree, page, baseUrl) {
134
+ const p = pageOf(tree, page);
135
+ const base = validateBaseUrl(baseUrl ?? MHTML_DEFAULT_BASE);
136
+ const url = (path) => base + encodePath(path.slice(1));
137
+ let out = `From: <Saved by sitefile>\r\nSnapshot-Content-Location: ${url(p)}\r\nMIME-Version: 1.0\r\n` +
138
+ `Content-Type: multipart/related;\r\n\ttype="text/html";\r\n\tboundary="${BOUNDARY}"\r\n\r\n`;
139
+ for (const path of assetsOf(tree, p)) {
140
+ out +=
141
+ `--${BOUNDARY}\r\nContent-Type: ${mimeTypeFor(path)}\r\nContent-Transfer-Encoding: base64\r\nContent-Location: ${url(path)}\r\n\r\n` +
142
+ base64Lines(tree.get(path).bytes) +
143
+ '\r\n';
144
+ }
145
+ return enc.encode(out + `--${BOUNDARY}--\r\n`);
146
+ }
147
+ //# sourceMappingURL=single-file.js.map
package/lib/src/site.d.ts CHANGED
@@ -10,8 +10,24 @@ export declare function checkBaseUrl(raw: string, what: string, span: SourceSpan
10
10
  export declare function pageUrl(base: string, path: string): string;
11
11
  /** Escape text for XML content and attribute values; characters XML 1.0 forbids become U+FFFD. */
12
12
  export declare function xmlEscape(s: string): string;
13
+ /** The sitemaps.org limits of one sitemap file: 50,000 URLs and 50 MiB (52,428,800 bytes) uncompressed. */
14
+ export declare const SITEMAP_LIMITS: {
15
+ readonly urls: 50000;
16
+ readonly bytes: 52428800;
17
+ };
13
18
  /** sitemaps.org XML for every `.html` file in the tree except `/404.html`, sorted by path. */
14
19
  export declare function sitemapXml(tree: Tree, base: string): string;
20
+ /** `/sitemap.xml` -> `/sitemap-2.xml`: the n-th part of a split sitemap (before the extension, or at the end). */
21
+ export declare function sitemapPart(dest: string, n: number): string;
22
+ /**
23
+ * The sitemap files for the tree: one at `dest` when it is within `limits`, or else a sitemap index at
24
+ * `dest` and the parts (`sitemapPart`) it lists, each with at most `limits.urls` URLs and `limits.bytes`
25
+ * bytes (a part is closed when the next URL would pass either limit).
26
+ */
27
+ export declare function sitemapFiles(tree: Tree, base: string, dest: string, limits?: {
28
+ urls: number;
29
+ bytes: number;
30
+ }): Array<[string, string]>;
15
31
  export interface FeedDate {
16
32
  /** RFC 3339 form written to the feed. */
17
33
  readonly text: string;
@@ -58,3 +74,41 @@ export declare function checkHeaderValue(raw: string, name: string, span: Source
58
74
  export declare function redirectsFile(rules: readonly RedirectRule[]): string;
59
75
  /** `/_headers`: one block per path pattern (in order of first use), its headers indented in source order. */
60
76
  export declare function headersFile(rules: readonly HeaderRule[]): string;
77
+ /** The `Cache-Control` of a fingerprinted file: its name changes with its content, so it never goes stale. */
78
+ export declare const IMMUTABLE = "public, max-age=31536000, immutable";
79
+ /** The `Cache-Control` of a page: revalidate on every request, so it always names the current assets. */
80
+ export declare const NO_CACHE = "no-cache";
81
+ export declare function cacheHeaderRules(files: readonly string[], hashed: ReadonlySet<string>): HeaderRule[];
82
+ /** `/robots.txt` (RFC 9309) for every user agent: the rules in order (an empty `Disallow:` when none), then a `Sitemap:` line per URL. */
83
+ export declare function robotsTxt(rules: ReadonlyArray<{
84
+ readonly allow: boolean;
85
+ readonly path: string;
86
+ }>, sitemaps: readonly string[]): string;
87
+ /** A security.txt URI field: one of `schemes` (lowercase, with their `:` or `://`), no spaces or control characters. */
88
+ export declare function checkFieldUri(raw: string, field: string, schemes: readonly string[], span: SourceSpan): string;
89
+ export interface SecurityTxt {
90
+ readonly contact: readonly string[];
91
+ /** RFC 3339, as {@link parseFeedDate} writes it. */
92
+ readonly expires: string;
93
+ readonly encryption: readonly string[];
94
+ readonly policy: readonly string[];
95
+ }
96
+ /** RFC 9116 `security.txt`: Contact lines, Expires, then Encryption and Policy lines, in source order. */
97
+ export declare function securityTxt(s: SecurityTxt): string;
98
+ /** Check a CSP POLICY: non-empty, no control characters (so it cannot break a header line), no `,` (which would make it two policies). */
99
+ export declare function checkCspPolicy(raw: string, span: SourceSpan): string;
100
+ /**
101
+ * A page's policy: `base` with `'sha256-…'` sources for its inline scripts and styles (deduplicated, in page
102
+ * order) added to `script-src` and `style-src`. A directive the base already has gets the hashes appended;
103
+ * otherwise one is added (`script-src 'self' …`) when the page has hashes of that kind. Directives are
104
+ * joined with `; `.
105
+ */
106
+ export declare function cspPolicy(base: string, scriptHashes: readonly string[], styleHashes: readonly string[]): string;
107
+ /** The `_headers` paths of a page URL: `/a/index.html` -> `/a/`, `/a/index.html`; `/b.html` -> `/b.html`, `/b`; others as they are. */
108
+ export declare function pagePatterns(url: string): string[];
109
+ /** `<meta http-equiv="Content-Security-Policy" content="…">`, with `&` and `"` of the policy escaped. */
110
+ export declare function cspMeta(policy: string): string;
111
+ /** Check a MIME extension: `.` and letters, digits, `+`, `-` or `_` (`.usdz`, `.tar-gz`); returned in lowercase. */
112
+ export declare function checkMimeExtension(raw: string, span: SourceSpan): string;
113
+ /** Check a MIME media type: `type/subtype`, both RFC 6838 restricted names (no parameters); returned in lowercase. */
114
+ export declare function checkMimeType(raw: string, span: SourceSpan): string;
package/lib/src/site.js CHANGED
@@ -31,17 +31,62 @@ export function xmlEscape(s) {
31
31
  function utf8Compare(a, b) {
32
32
  return Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'));
33
33
  }
34
+ const SITEMAP_HEAD = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';
35
+ const SITEMAP_TAIL = '</urlset>\n';
36
+ /** The sitemaps.org limits of one sitemap file: 50,000 URLs and 50 MiB (52,428,800 bytes) uncompressed. */
37
+ export const SITEMAP_LIMITS = { urls: 50_000, bytes: 52_428_800 };
34
38
  /** sitemaps.org XML for every `.html` file in the tree except `/404.html`, sorted by path. */
35
39
  export function sitemapXml(tree, base) {
36
- const paths = tree
40
+ return SITEMAP_HEAD + sitemapEntries(tree, base).join('') + SITEMAP_TAIL;
41
+ }
42
+ function sitemapEntries(tree, base) {
43
+ return tree
37
44
  .entries()
38
45
  .map(([p]) => p)
39
46
  .filter((p) => p.endsWith('.html') && p !== '/404.html')
40
- .sort(utf8Compare);
41
- let out = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';
42
- for (const p of paths)
43
- out += ` <url><loc>${xmlEscape(pageUrl(base, p))}</loc></url>\n`;
44
- return out + '</urlset>\n';
47
+ .sort(utf8Compare)
48
+ .map((p) => ` <url><loc>${xmlEscape(pageUrl(base, p))}</loc></url>\n`);
49
+ }
50
+ /** `/sitemap.xml` -> `/sitemap-2.xml`: the n-th part of a split sitemap (before the extension, or at the end). */
51
+ export function sitemapPart(dest, n) {
52
+ const slash = dest.lastIndexOf('/');
53
+ const dot = dest.lastIndexOf('.');
54
+ return dot > slash + 1 ? `${dest.slice(0, dot)}-${n}${dest.slice(dot)}` : `${dest}-${n}`;
55
+ }
56
+ /**
57
+ * The sitemap files for the tree: one at `dest` when it is within `limits`, or else a sitemap index at
58
+ * `dest` and the parts (`sitemapPart`) it lists, each with at most `limits.urls` URLs and `limits.bytes`
59
+ * bytes (a part is closed when the next URL would pass either limit).
60
+ */
61
+ export function sitemapFiles(tree, base, dest, limits = SITEMAP_LIMITS) {
62
+ const entries = sitemapEntries(tree, base);
63
+ const frame = utf8Length(SITEMAP_HEAD) + utf8Length(SITEMAP_TAIL);
64
+ const sizes = entries.map(utf8Length);
65
+ const total = frame + sizes.reduce((a, b) => a + b, 0);
66
+ if (entries.length <= limits.urls && total <= limits.bytes)
67
+ return [[dest, SITEMAP_HEAD + entries.join('') + SITEMAP_TAIL]];
68
+ const parts = [];
69
+ let cur = [];
70
+ let bytes = frame;
71
+ entries.forEach((e, i) => {
72
+ if (cur.length > 0 && (cur.length >= limits.urls || bytes + sizes[i] > limits.bytes)) {
73
+ parts.push(cur);
74
+ cur = [];
75
+ bytes = frame;
76
+ }
77
+ cur.push(e);
78
+ bytes += sizes[i];
79
+ });
80
+ if (cur.length > 0)
81
+ parts.push(cur);
82
+ const out = parts.map((p, i) => [sitemapPart(dest, i + 1), SITEMAP_HEAD + p.join('') + SITEMAP_TAIL]);
83
+ let index = '<?xml version="1.0" encoding="UTF-8"?>\n<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n';
84
+ for (const [p] of out)
85
+ index += ` <sitemap><loc>${xmlEscape(pageUrl(base, p))}</loc></sitemap>\n`;
86
+ return [[dest, index + '</sitemapindex>\n'], ...out];
87
+ }
88
+ function utf8Length(s) {
89
+ return Buffer.byteLength(s, 'utf8');
45
90
  }
46
91
  function daysFromCivil(y, m, d) {
47
92
  const yy = m <= 2 ? y - 1 : y;
@@ -166,4 +211,157 @@ export function headersFile(rules) {
166
211
  out += `${pattern}\n${lines.join('')}`;
167
212
  return out;
168
213
  }
214
+ // ---------------------------------------------------------------- FINGERPRINT cache headers
215
+ /** The `Cache-Control` of a fingerprinted file: its name changes with its content, so it never goes stale. */
216
+ export const IMMUTABLE = 'public, max-age=31536000, immutable';
217
+ /** The `Cache-Control` of a page: revalidate on every request, so it always names the current assets. */
218
+ export const NO_CACHE = 'no-cache';
219
+ /**
220
+ * The `/_headers` rules EXPORT adds for FINGERPRINT (docs/LANGUAGE.md, "Fingerprinting"). `files` are the
221
+ * URL paths of every file in the exported directory, `hashed` those of the fingerprinted ones. A
222
+ * fingerprinted file gets `Cache-Control: public, max-age=31536000, immutable`, by a `/dir/*` rule for the
223
+ * topmost directory (below the root) that holds only fingerprinted files, or else by its own path; pages
224
+ * get `Cache-Control: no-cache` through `/`, `/*/ ` and `; /*.html` (each only when a page it matches
225
+ * exists). Paths with spaces or control characters are left out (a `_headers` path cannot hold them).
226
+ * Rules are in path order (UTF-8), immutable ones first; none when nothing is fingerprinted.
227
+ */
228
+ export function cacheHeaderRules(files, hashed) {
229
+ const ok = (p) => !SPACE_OR_CONTROL.test(p);
230
+ const sorted = [...files].sort(utf8Compare);
231
+ const counts = new Map();
232
+ for (const f of sorted) {
233
+ const segs = f.split('/');
234
+ for (let k = 2; k < segs.length; k++) {
235
+ const d = segs.slice(0, k).join('/');
236
+ const c = counts.get(d) ?? { total: 0, hashed: 0 };
237
+ c.total++;
238
+ if (hashed.has(f))
239
+ c.hashed++;
240
+ counts.set(d, c);
241
+ }
242
+ }
243
+ const out = [];
244
+ const seen = new Set();
245
+ const add = (pattern, value) => {
246
+ if (seen.has(pattern) || !ok(pattern))
247
+ return;
248
+ seen.add(pattern);
249
+ out.push({ pattern, name: 'Cache-Control', value });
250
+ };
251
+ for (const f of sorted) {
252
+ if (!hashed.has(f))
253
+ continue;
254
+ const segs = f.split('/');
255
+ let pattern = f;
256
+ for (let k = 2; k < segs.length; k++) {
257
+ const d = segs.slice(0, k).join('/');
258
+ const c = counts.get(d);
259
+ if (c.total === c.hashed) {
260
+ pattern = d + '/*';
261
+ break;
262
+ }
263
+ }
264
+ add(pattern, IMMUTABLE);
265
+ }
266
+ if (out.length === 0)
267
+ return out;
268
+ const pages = sorted.filter((f) => /\.html$/i.test(f));
269
+ if (pages.includes('/index.html'))
270
+ add('/', NO_CACHE);
271
+ if (pages.some((f) => f !== '/index.html' && /\/index\.html$/i.test(f)))
272
+ add('/*/', NO_CACHE);
273
+ if (pages.length > 0)
274
+ add('/*.html', NO_CACHE);
275
+ return out;
276
+ }
277
+ // ---------------------------------------------------------------- robots.txt and security.txt
278
+ /** `/robots.txt` (RFC 9309) for every user agent: the rules in order (an empty `Disallow:` when none), then a `Sitemap:` line per URL. */
279
+ export function robotsTxt(rules, sitemaps) {
280
+ let out = 'User-agent: *\n';
281
+ if (rules.length === 0)
282
+ out += 'Disallow:\n';
283
+ for (const r of rules)
284
+ out += `${r.allow ? 'Allow' : 'Disallow'}: ${r.path}\n`;
285
+ if (sitemaps.length > 0)
286
+ out += '\n' + sitemaps.map((u) => `Sitemap: ${u}\n`).join('');
287
+ return out;
288
+ }
289
+ /** A security.txt URI field: one of `schemes` (lowercase, with their `:` or `://`), no spaces or control characters. */
290
+ export function checkFieldUri(raw, field, schemes, span) {
291
+ const lower = raw.toLowerCase();
292
+ if (SPACE_OR_CONTROL.test(raw) || !schemes.some((s) => lower.startsWith(s) && raw.length > s.length)) {
293
+ throw new SitefileError('E_VALIDATION', `SECURITY_TXT ${field} '${raw}' must be a ${schemes.map((s) => s.replace(/\/\/$/, '//…')).join(', ')} URI with no spaces`, span);
294
+ }
295
+ return raw;
296
+ }
297
+ /** RFC 9116 `security.txt`: Contact lines, Expires, then Encryption and Policy lines, in source order. */
298
+ export function securityTxt(s) {
299
+ return [
300
+ ...s.contact.map((v) => `Contact: ${v}\n`),
301
+ `Expires: ${s.expires}\n`,
302
+ ...s.encryption.map((v) => `Encryption: ${v}\n`),
303
+ ...s.policy.map((v) => `Policy: ${v}\n`),
304
+ ].join('');
305
+ }
306
+ // ---------------------------------------------------------------- CSP
307
+ /** Check a CSP POLICY: non-empty, no control characters (so it cannot break a header line), no `,` (which would make it two policies). */
308
+ export function checkCspPolicy(raw, span) {
309
+ const v = raw.replace(/^[ \t]+|[ \t]+$/g, '');
310
+ if (CONTROL.test(raw) || v === '' || v.includes(',')) {
311
+ throw new SitefileError('E_VALIDATION', `CSP POLICY '${raw}' must be a non-empty policy without control characters or commas (directives separated by ';')`, span);
312
+ }
313
+ return v;
314
+ }
315
+ /**
316
+ * A page's policy: `base` with `'sha256-…'` sources for its inline scripts and styles (deduplicated, in page
317
+ * order) added to `script-src` and `style-src`. A directive the base already has gets the hashes appended;
318
+ * otherwise one is added (`script-src 'self' …`) when the page has hashes of that kind. Directives are
319
+ * joined with `; `.
320
+ */
321
+ export function cspPolicy(base, scriptHashes, styleHashes) {
322
+ const directives = base
323
+ .split(';')
324
+ .map((d) => d.replace(/^[ \t]+|[ \t]+$/g, ''))
325
+ .filter((d) => d !== '');
326
+ const add = (name, hashes) => {
327
+ if (hashes.length === 0)
328
+ return;
329
+ const sources = [...new Set(hashes)].map((h) => `'${h}'`).join(' ');
330
+ const at = directives.findIndex((d) => d.split(/[ \t]+/)[0].toLowerCase() === name);
331
+ if (at === -1)
332
+ directives.push(`${name} 'self' ${sources}`);
333
+ else
334
+ directives[at] = `${directives[at]} ${sources}`;
335
+ };
336
+ add('script-src', scriptHashes);
337
+ add('style-src', styleHashes);
338
+ return directives.join('; ');
339
+ }
340
+ /** The `_headers` paths of a page URL: `/a/index.html` -> `/a/`, `/a/index.html`; `/b.html` -> `/b.html`, `/b`; others as they are. */
341
+ export function pagePatterns(url) {
342
+ if (url.endsWith('/index.html'))
343
+ return [url.slice(0, -'index.html'.length), url];
344
+ if (url.endsWith('.html'))
345
+ return [url, url.slice(0, -'.html'.length)];
346
+ return [url];
347
+ }
348
+ /** `<meta http-equiv="Content-Security-Policy" content="…">`, with `&` and `"` of the policy escaped. */
349
+ export function cspMeta(policy) {
350
+ return `<meta http-equiv="Content-Security-Policy" content="${policy.replace(/&/g, '&amp;').replace(/"/g, '&quot;')}">`;
351
+ }
352
+ // ---------------------------------------------------------------- MIME
353
+ /** Check a MIME extension: `.` and letters, digits, `+`, `-` or `_` (`.usdz`, `.tar-gz`); returned in lowercase. */
354
+ export function checkMimeExtension(raw, span) {
355
+ if (!/^\.[A-Za-z0-9+_-]+$/.test(raw)) {
356
+ throw new SitefileError('E_VALIDATION', `MIME extension '${raw}' must be a dot and letters, digits, '+', '-' or '_' (e.g. .usdz)`, span);
357
+ }
358
+ return raw.toLowerCase();
359
+ }
360
+ /** Check a MIME media type: `type/subtype`, both RFC 6838 restricted names (no parameters); returned in lowercase. */
361
+ export function checkMimeType(raw, span) {
362
+ if (!/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}$/.test(raw)) {
363
+ throw new SitefileError('E_VALIDATION', `MIME type '${raw}' must be type/subtype (e.g. model/vnd.usdz+zip), without parameters`, span);
364
+ }
365
+ return raw.toLowerCase();
366
+ }
169
367
  //# sourceMappingURL=site.js.map
package/lib/src/store.js CHANGED
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { decodeReferrersIndex, encodeReferrersIndex } from './attest.js';
6
6
  import { sha256 } from './digest.js';
7
7
  import { SitefileError } from './errors.js';
8
- import { ANN, blobPathOf, buildOciImage, decodeIndex, encodeIndex, extractImageFiles, layoutTree, OCI_LAYOUT_BYTES, parseConfig, parseManifest, siteLayerIndex, } from './oci.js';
8
+ import { ANN, blobPathOf, buildOciImage, decodeIndex, encodeIndex, extractImageFiles, layoutTree, OCI_LAYOUT_BYTES, parseConfig, parseManifest, siteLayerIndex, siteLayerIndices, } from './oci.js';
9
9
  import { looksLikeImageId, parseLocalRef, refKey } from './ref.js';
10
10
  const HEX64 = /^[0-9a-f]{64}$/;
11
11
  export function resolveStoreHome(env = process.env) {
@@ -261,6 +261,8 @@ export class Store {
261
261
  const img = buildOciImage(tree, options);
262
262
  return this.withLock(async () => {
263
263
  await this.putBlob(img.layerDigest, img.layerBytes);
264
+ for (const [d, b] of img.extraLayers ?? [])
265
+ await this.putBlob(d, b);
264
266
  await this.putBlob(img.configDigest, img.configBytes);
265
267
  await this.putBlob(img.manifestDigest, img.manifestBytes);
266
268
  const entries = await this.readIndex();
@@ -309,11 +311,13 @@ export class Store {
309
311
  async loadTree(id, o = {}) {
310
312
  const d = await this.details(id);
311
313
  const origin = o.origin ?? `image:${shortId(id)}`;
312
- const layer = d.manifest.layers[siteLayerIndex(d.manifest, d.config)];
313
- if (!layer)
314
+ const layers = siteLayerIndices(d.manifest, d.config).map((i) => d.manifest.layers[i]);
315
+ if (layers.length === 0)
314
316
  throw new SitefileError('E_STORE', `${origin}: not a Sitefile image (it has ${d.manifest.layers.length} layers and no site layer)`);
315
- const bytes = await this.readBlob(layer.digest, layer.size);
316
- return extractImageFiles(d.manifest, d.config, bytes, origin, o.root);
317
+ const blobs = [];
318
+ for (const l of layers)
319
+ blobs.push(await this.readBlob(l.digest, l.size));
320
+ return extractImageFiles(d.manifest, d.config, blobs, origin, o.root);
317
321
  }
318
322
  /**
319
323
  * The image as a standalone OCI layout Tree (for `save`), optionally annotated with a tag.
@@ -0,0 +1,10 @@
1
+ import type { Tree } from './tree.js';
2
+ /** The 32-byte Ed25519 seed of a PEM PKCS #8 private key, or undefined. */
3
+ export declare function parseEd25519Pem(pem: string): Uint8Array | undefined;
4
+ /** The Web Bundle ID of an Ed25519 public key. */
5
+ export declare function webBundleId(publicKey: Uint8Array): string;
6
+ /** `keyPem` is the secret's value; `keyId` names it in errors. */
7
+ export declare function writeSignedWebBundle(tree: Tree, keyPem: string, keyId: string): {
8
+ bytes: Uint8Array;
9
+ id: string;
10
+ };
@@ -0,0 +1,86 @@
1
+ import { createHash, createPrivateKey, createPublicKey, sign } from 'node:crypto';
2
+ import { cborArray, cborBytes, cborMap, cborText } from './cbor.js';
3
+ import { SitefileError } from './errors.js';
4
+ import { writeWebBundleAt } from './wbn.js';
5
+ /**
6
+ * `EXPORT … AS swbn KEY <secret-id>` (issue #207): a Signed Web Bundle for Isolated Web Apps.
7
+ *
8
+ * The key is a build secret (`--secret id=<id>,src=key.pem`): an unencrypted Ed25519 private key in
9
+ * PEM, PKCS #8 (`openssl genpkey -algorithm ed25519`). It is never written anywhere. The Web Bundle ID
10
+ * is base32 (RFC 4648, lower case, no padding) of the public key and the Ed25519 type suffix
11
+ * `00 01 02`; the bundle is the tree's Web Bundle (b2) at `isolated-app://<id>/`. In front of it goes
12
+ * the integrity block (v2, deterministic CBOR):
13
+ *
14
+ * [ h'F09F968BF09F93A6', h'32620000', {"webBundleId": id}, [[{"ed25519PublicKey": pk}, signature]] ]
15
+ *
16
+ * The signature is Ed25519 over the length-prefixed (8-byte big-endian) concatenation of the SHA-512
17
+ * of the bundle, the integrity block with an empty signature stack, and the signature attributes, as
18
+ * the WICG integrity-signature explainer and `wbn-sign` define it. Ed25519 is deterministic, so the
19
+ * same tree and key give the same bytes.
20
+ */
21
+ const MAGIC = new Uint8Array([0xf0, 0x9f, 0x96, 0x8b, 0xf0, 0x9f, 0x93, 0xa6]);
22
+ const VERSION_B2 = new Uint8Array([0x32, 0x62, 0x00, 0x00]);
23
+ /** DER of a PKCS #8 Ed25519 private key, before its 32-byte seed. */
24
+ const PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
25
+ /** The 32-byte Ed25519 seed of a PEM PKCS #8 private key, or undefined. */
26
+ export function parseEd25519Pem(pem) {
27
+ const m = /-----BEGIN PRIVATE KEY-----([A-Za-z0-9+/=\s]+)-----END PRIVATE KEY-----/.exec(pem);
28
+ if (!m)
29
+ return undefined;
30
+ const der = Buffer.from(m[1].replace(/\s+/g, ''), 'base64');
31
+ if (der.length !== 48 || !der.subarray(0, 16).equals(PKCS8_PREFIX))
32
+ return undefined;
33
+ return new Uint8Array(der.subarray(16));
34
+ }
35
+ const B32 = 'abcdefghijklmnopqrstuvwxyz234567';
36
+ function base32(bytes) {
37
+ let out = '';
38
+ let bits = 0;
39
+ let value = 0;
40
+ for (const b of bytes) {
41
+ value = (value << 8) | b;
42
+ bits += 8;
43
+ while (bits >= 5) {
44
+ out += B32[(value >>> (bits - 5)) & 31];
45
+ bits -= 5;
46
+ }
47
+ value &= (1 << bits) - 1;
48
+ }
49
+ if (bits > 0)
50
+ out += B32[(value << (5 - bits)) & 31];
51
+ return out;
52
+ }
53
+ function keyPair(seed) {
54
+ const privateKey = createPrivateKey({ key: Buffer.concat([PKCS8_PREFIX, seed]), format: 'der', type: 'pkcs8' });
55
+ const jwk = createPublicKey(privateKey).export({ format: 'jwk' });
56
+ return { privateKey, publicKey: new Uint8Array(Buffer.from(jwk.x, 'base64url')) };
57
+ }
58
+ /** The Web Bundle ID of an Ed25519 public key. */
59
+ export function webBundleId(publicKey) {
60
+ return base32(new Uint8Array([...publicKey, 0x00, 0x01, 0x02]));
61
+ }
62
+ function be64(n) {
63
+ const b = Buffer.alloc(8);
64
+ b.writeBigUInt64BE(BigInt(n));
65
+ return b;
66
+ }
67
+ /** `keyPem` is the secret's value; `keyId` names it in errors. */
68
+ export function writeSignedWebBundle(tree, keyPem, keyId) {
69
+ const seed = parseEd25519Pem(keyPem);
70
+ if (!seed) {
71
+ throw new SitefileError('E_SECRET', `EXPORT ... KEY ${keyId}: the secret is not an unencrypted Ed25519 private key in PEM (PKCS #8, as 'openssl genpkey -algorithm ed25519' writes)`);
72
+ }
73
+ const { privateKey, publicKey } = keyPair(seed);
74
+ const id = webBundleId(publicKey);
75
+ const bundle = writeWebBundleAt(tree, `isolated-app://${id}/`);
76
+ const attributes = cborMap([[cborText('webBundleId'), cborText(id)]]);
77
+ const head = [cborBytes(MAGIC), cborBytes(VERSION_B2), attributes];
78
+ const stripped = cborArray([...head, cborArray([])]);
79
+ const sigAttributes = cborMap([[cborText('ed25519PublicKey'), cborBytes(publicKey)]]);
80
+ const hash = createHash('sha512').update(bundle).digest();
81
+ const toSign = Buffer.concat([be64(hash.length), hash, be64(stripped.length), stripped, be64(sigAttributes.length), sigAttributes]);
82
+ const signature = sign(null, toSign, privateKey);
83
+ const block = cborArray([...head, cborArray([cborArray([sigAttributes, cborBytes(signature)])])]);
84
+ return { bytes: Buffer.concat([block, bundle]), id };
85
+ }
86
+ //# sourceMappingURL=swbn.js.map
@@ -0,0 +1,17 @@
1
+ /**
2
+ * A TOML subset, enough for host config files (netlify.toml, wrangler.toml; issue #204). Ported as
3
+ * rust/src/toml.rs; both give the same values and the same errors.
4
+ *
5
+ * Supported: comments, `[table]` and `[[array.of.tables]]` headers (a header path through an array of
6
+ * tables goes into its last element, as `[headers.values]` after `[[headers]]`), bare and quoted keys,
7
+ * dotted keys, basic strings (with `\b \t \n \f \r \" \\ \uXXXX \UXXXXXXXX`), literal strings, decimal
8
+ * integers and floats (`_` separators), booleans, arrays (over several lines, trailing comma allowed) and
9
+ * inline tables. Not supported (an E_DATA error): multi-line strings, dates and times, hex/octal/binary
10
+ * integers, `inf`/`nan`.
11
+ */
12
+ export type TomlValue = string | number | boolean | TomlValue[] | TomlTable;
13
+ export interface TomlTable {
14
+ [key: string]: TomlValue;
15
+ }
16
+ /** Parse a TOML document (the subset above). Errors are E_DATA `file:line: message`. */
17
+ export declare function parseToml(text: string, file: string): TomlTable;