@johnhenry/sitefile 0.0.2 → 0.0.4

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 (136) hide show
  1. package/CHANGELOG.md +516 -0
  2. package/README.md +59 -9
  3. package/lib/src/archive-writers.d.ts +12 -2
  4. package/lib/src/archive-writers.js +53 -10
  5. package/lib/src/bake.d.ts +2 -0
  6. package/lib/src/bake.js +30 -1
  7. package/lib/src/bcrypt.d.ts +25 -0
  8. package/lib/src/bcrypt.js +201 -0
  9. package/lib/src/canonical.d.ts +19 -0
  10. package/lib/src/canonical.js +60 -0
  11. package/lib/src/car.d.ts +34 -0
  12. package/lib/src/car.js +203 -0
  13. package/lib/src/checklinks.js +8 -2
  14. package/lib/src/cli/bake.js +4 -3
  15. package/lib/src/cli/build-image.d.ts +1 -0
  16. package/lib/src/cli/build-image.js +1 -0
  17. package/lib/src/cli/common.js +4 -1
  18. package/lib/src/cli/hosts.d.ts +5 -0
  19. package/lib/src/cli/hosts.js +78 -0
  20. package/lib/src/cli/images.js +23 -5
  21. package/lib/src/cli/import-config.d.ts +2 -0
  22. package/lib/src/cli/import-config.js +56 -0
  23. package/lib/src/cli/index.d.ts +6 -1
  24. package/lib/src/cli/index.js +34 -2
  25. package/lib/src/cli/integrity.d.ts +2 -0
  26. package/lib/src/cli/integrity.js +77 -0
  27. package/lib/src/cli/network.d.ts +7 -0
  28. package/lib/src/cli/network.js +14 -3
  29. package/lib/src/cli/serve-keys.d.ts +39 -0
  30. package/lib/src/cli/serve-keys.js +106 -0
  31. package/lib/src/cli/serve-worker.js +119 -8
  32. package/lib/src/cli/servers.d.ts +130 -1
  33. package/lib/src/cli/servers.js +754 -72
  34. package/lib/src/cli/up.d.ts +2 -0
  35. package/lib/src/cli/up.js +193 -0
  36. package/lib/src/cli/watch.d.ts +14 -1
  37. package/lib/src/cli/watch.js +20 -3
  38. package/lib/src/cli.js +138 -18
  39. package/lib/src/csp.d.ts +17 -0
  40. package/lib/src/csp.js +52 -0
  41. package/lib/src/dictionary.d.ts +16 -0
  42. package/lib/src/dictionary.js +89 -0
  43. package/lib/src/epub.d.ts +5 -0
  44. package/lib/src/epub.js +113 -0
  45. package/lib/src/errors.d.ts +22 -9
  46. package/lib/src/errors.js +20 -1
  47. package/lib/src/executor.d.ts +31 -1
  48. package/lib/src/executor.js +231 -24
  49. package/lib/src/explain.js +33 -3
  50. package/lib/src/export-for.d.ts +42 -0
  51. package/lib/src/export-for.js +466 -0
  52. package/lib/src/export-formats.d.ts +2 -2
  53. package/lib/src/export-formats.js +52 -2
  54. package/lib/src/fingerprint.d.ts +3 -1
  55. package/lib/src/fingerprint.js +32 -5
  56. package/lib/src/host-config.d.ts +34 -0
  57. package/lib/src/host-config.js +645 -0
  58. package/lib/src/hosts.d.ts +47 -0
  59. package/lib/src/hosts.js +106 -0
  60. package/lib/src/hreflang.d.ts +25 -0
  61. package/lib/src/hreflang.js +72 -0
  62. package/lib/src/index.d.ts +1 -1
  63. package/lib/src/index.js +1 -1
  64. package/lib/src/integrity.d.ts +115 -0
  65. package/lib/src/integrity.js +273 -0
  66. package/lib/src/language/ast.d.ts +126 -3
  67. package/lib/src/language/ast.js +7 -1
  68. package/lib/src/language/parser.js +189 -7
  69. package/lib/src/language/validate.js +24 -0
  70. package/lib/src/links.d.ts +47 -0
  71. package/lib/src/links.js +289 -3
  72. package/lib/src/lint.d.ts +1 -1
  73. package/lib/src/lint.js +26 -1
  74. package/lib/src/mime-data.d.ts +2 -0
  75. package/lib/src/mime-data.js +92 -0
  76. package/lib/src/oci.d.ts +20 -2
  77. package/lib/src/oci.js +70 -28
  78. package/lib/src/outdated.d.ts +3 -0
  79. package/lib/src/outdated.js +4 -4
  80. package/lib/src/planner.d.ts +87 -2
  81. package/lib/src/planner.js +189 -8
  82. package/lib/src/plugins/cache.d.ts +11 -0
  83. package/lib/src/plugins/cache.js +29 -0
  84. package/lib/src/plugins/host.d.ts +51 -2
  85. package/lib/src/plugins/host.js +141 -16
  86. package/lib/src/plugins/wasm.js +1 -3
  87. package/lib/src/portable.d.ts +8 -0
  88. package/lib/src/portable.js +47 -0
  89. package/lib/src/precache.d.ts +33 -0
  90. package/lib/src/precache.js +75 -0
  91. package/lib/src/precompress.d.ts +19 -0
  92. package/lib/src/precompress.js +35 -0
  93. package/lib/src/qr.d.ts +18 -0
  94. package/lib/src/qr.js +372 -0
  95. package/lib/src/registry-ops.js +4 -2
  96. package/lib/src/reload-client.d.ts +2 -0
  97. package/lib/src/reload-client.js +419 -0
  98. package/lib/src/resources/archive.d.ts +37 -1
  99. package/lib/src/resources/archive.js +353 -71
  100. package/lib/src/resources/convert.js +3 -1
  101. package/lib/src/resources/https.d.ts +9 -1
  102. package/lib/src/resources/https.js +36 -0
  103. package/lib/src/resources/network.d.ts +25 -3
  104. package/lib/src/resources/network.js +77 -6
  105. package/lib/src/secrets.d.ts +12 -3
  106. package/lib/src/secrets.js +18 -5
  107. package/lib/src/serve-auth.d.ts +33 -0
  108. package/lib/src/serve-auth.js +120 -0
  109. package/lib/src/serve-rules.d.ts +83 -7
  110. package/lib/src/serve-rules.js +264 -53
  111. package/lib/src/server.d.ts +529 -11
  112. package/lib/src/server.js +1439 -57
  113. package/lib/src/servers-file.d.ts +36 -0
  114. package/lib/src/servers-file.js +101 -0
  115. package/lib/src/servers.d.ts +115 -7
  116. package/lib/src/servers.js +151 -29
  117. package/lib/src/single-file.d.ts +12 -0
  118. package/lib/src/single-file.js +147 -0
  119. package/lib/src/site.d.ts +58 -0
  120. package/lib/src/site.js +216 -5
  121. package/lib/src/store.js +9 -5
  122. package/lib/src/swbn.d.ts +10 -0
  123. package/lib/src/swbn.js +86 -0
  124. package/lib/src/toml.d.ts +17 -0
  125. package/lib/src/toml.js +323 -0
  126. package/lib/src/wacz.d.ts +6 -0
  127. package/lib/src/wacz.js +96 -0
  128. package/lib/src/warc.d.ts +28 -0
  129. package/lib/src/warc.js +252 -0
  130. package/lib/src/watch.d.ts +12 -1
  131. package/lib/src/watch.js +67 -1
  132. package/lib/src/wbn.d.ts +9 -1
  133. package/lib/src/wbn.js +23 -33
  134. package/lib/src/zstd.d.ts +4 -0
  135. package/lib/src/zstd.js +328 -0
  136. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
- import { gunzip as gunzipCb, inflateRaw as inflateRawCb } from 'node:zlib';
1
+ import { closeSync, fstatSync, openSync, readSync } from 'node:fs';
2
+ import { crc32, gunzip as gunzipCb, inflateRaw as inflateRawCb, inflateRawSync, zstdDecompress as zstdDecompressCb } from 'node:zlib';
2
3
  import { promisify } from 'node:util';
3
4
  import { SitefileError } from '../errors.js';
4
5
  import { normalizeVirtual } from '../paths.js';
@@ -9,10 +10,11 @@ import { isWebBundle, readWebBundle, webBundleToTree } from './wbn-reader.js';
9
10
  const RATIO_FLOOR = 1024 * 1024;
10
11
  const gunzipAsync = promisify(gunzipCb);
11
12
  const inflateRawAsync = promisify(inflateRawCb);
13
+ const zstdDecompressAsync = promisify(zstdDecompressCb);
12
14
  /** Tar framing per entry, worst case: header + padding + a pax/GNU long-name header and its padding. */
13
15
  const TAR_OVERHEAD_PER_ENTRY = 4 * 512;
14
16
  /**
15
- * Extract a tar, tar.gz/tgz, zip or Web Bundle (b1/b2) archive into a Tree. The format is detected
17
+ * Extract a tar, tar.gz/tgz, tar.zst/tzst, zip or Web Bundle (b1/b2, plain or gzip-wrapped) archive into a Tree. The format is detected
16
18
  * from magic bytes, never from the name. Nothing is inflated beyond the limits,
17
19
  * and unsafe entries (absolute or `..` paths, backslashes, NUL, symlinks, hard
18
20
  * links, devices) are rejected, not skipped. A single top-level directory is
@@ -21,6 +23,31 @@ const TAR_OVERHEAD_PER_ENTRY = 4 * 512;
21
23
  export async function extractArchive(bytes, origin, limits = DEFAULT_ARCHIVE_LIMITS, span) {
22
24
  if (isWebBundle(bytes))
23
25
  return webBundleToTree(readWebBundle(bytes, origin, limits, span), origin, span);
26
+ const { add, files } = collector(origin, limits, span, true);
27
+ const compression = isGzip(bytes) ? 'gzip' : isZstd(bytes) ? 'zstd' : undefined;
28
+ if (compression) {
29
+ const inner = await decompress(compression, bytes, origin, limits, span);
30
+ // gzip(application/webbundle), as @johnhenry/fileable (encode="wbn") and packfile's toArchive() write it
31
+ if (isWebBundle(inner))
32
+ return webBundleToTree(readWebBundle(inner, origin, limits, span), origin, span);
33
+ if (!isTar(inner))
34
+ throw new SitefileError('E_TYPE', `${origin}: ${compression} content is not a tar archive`, span);
35
+ readTar(inner, origin, limits, span, add);
36
+ }
37
+ else if (isZip(bytes)) {
38
+ await readZip(bytes, origin, limits, span, add);
39
+ }
40
+ else if (isTar(bytes)) {
41
+ readTar(bytes, origin, limits, span, add);
42
+ }
43
+ else {
44
+ const what = otherFormat(bytes);
45
+ throw new SitefileError('E_TYPE', `${origin}: not a recognized archive (${what ?? 'expected tar, tar.gz, tar.zst, zip or web bundle'})`, span);
46
+ }
47
+ return Tree.fromFiles(files);
48
+ }
49
+ /** Collects archive entries into files, enforcing paths, conflicts and the limits. `retain` false keeps only digests. */
50
+ function collector(origin, limits, span, retain) {
24
51
  const files = new Map();
25
52
  const dirs = new Set();
26
53
  let total = 0;
@@ -42,26 +69,52 @@ export async function extractArchive(bytes, origin, limits = DEFAULT_ARCHIVE_LIM
42
69
  if (total > limits.maxTotalBytes) {
43
70
  throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: archive expands beyond ${limits.maxTotalBytes} bytes`, span);
44
71
  }
45
- files.set(path, makeFile(data, `${origin}:${name}`, mode));
72
+ const node = makeFile(data, `${origin}:${name}`, mode);
73
+ files.set(path, retain ? node : { ...node, bytes: EMPTY });
46
74
  };
47
- if (isGzip(bytes)) {
48
- const tar = await gunzip(bytes, origin, limits, span);
49
- if (!isTar(tar))
50
- throw new SitefileError('E_TYPE', `${origin}: gzip content is not a tar archive`, span);
51
- readTar(tar, origin, limits, span, add);
52
- }
53
- else if (isZip(bytes)) {
54
- await readZip(bytes, origin, limits, span, add);
55
- }
56
- else if (isTar(bytes)) {
57
- readTar(bytes, origin, limits, span, add);
58
- }
59
- else {
60
- throw new SitefileError('E_TYPE', `${origin}: not a recognized archive (expected tar, tar.gz, zip or web bundle)`, span);
61
- }
62
- return Tree.fromFiles(files);
75
+ return { add, files };
76
+ }
77
+ const EMPTY = new Uint8Array(0);
78
+ /**
79
+ * OS metadata that archivers and file managers add next to real files: macOS
80
+ * resource forks (`__MACOSX/`, AppleDouble `._name`), Finder's `.DS_Store` and
81
+ * custom folder `Icon\r`, and Windows' `Thumbs.db` and `desktop.ini`
82
+ * (case-insensitive, as Windows writes them).
83
+ */
84
+ export function isOsMetadata(path) {
85
+ const segs = path.split('/');
86
+ if (segs.includes('__MACOSX'))
87
+ return true;
88
+ const base = segs[segs.length - 1] ?? '';
89
+ const lower = base.toLowerCase();
90
+ return base.startsWith('._') || base === '.DS_Store' || base === 'Icon\r' || lower === 'thumbs.db' || lower === 'desktop.ini';
91
+ }
92
+ /** `tree` without its OS metadata files ({@link isOsMetadata}), and how many were dropped. */
93
+ export function withoutOsMetadata(tree) {
94
+ const kept = tree.entries().filter(([p]) => !isOsMetadata(p));
95
+ const skipped = tree.size - kept.length;
96
+ return { tree: skipped === 0 ? tree : Tree.fromFiles(kept), skipped };
97
+ }
98
+ /** The warning for {@link withoutOsMetadata} dropping `skipped` files of `what`. */
99
+ export function osMetadataWarning(what, skipped) {
100
+ return `${what}: skipped ${skipped} OS metadata ${skipped === 1 ? 'file' : 'files'} (__MACOSX, ._*, .DS_Store, Thumbs.db, desktop.ini, Icon\\r); --keep-os-metadata keeps them`;
101
+ }
102
+ /** Formats sitefile does not read, by magic bytes: what the file is and what to do instead. */
103
+ function otherFormat(b) {
104
+ const starts = (...m) => b.length >= m.length && m.every((x, i) => b[i] === x);
105
+ if (starts(0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00))
106
+ return 'it is xz-compressed, e.g. .tar.xz; recompress it as .tar.gz or zip';
107
+ if (starts(0x42, 0x5a, 0x68) && b.length > 3 && b[3] >= 0x31 && b[3] <= 0x39)
108
+ return 'it is bzip2-compressed, e.g. .tar.bz2; recompress it as .tar.gz or zip';
109
+ if (starts(0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c))
110
+ return 'it is a 7z archive; convert it to zip or tar';
111
+ if (starts(0x52, 0x61, 0x72, 0x21, 0x1a, 0x07))
112
+ return 'it is a RAR archive; convert it to zip or tar';
113
+ return undefined;
63
114
  }
64
115
  const isGzip = (b) => b.length > 2 && b[0] === 0x1f && b[1] === 0x8b;
116
+ /** A Zstandard frame (RFC 8878); a stream that starts with a skippable frame is not recognized. */
117
+ const isZstd = (b) => b.length >= 4 && b[0] === 0x28 && b[1] === 0xb5 && b[2] === 0x2f && b[3] === 0xfd;
65
118
  const isZip = (b) => b.length >= 4 && b[0] === 0x50 && b[1] === 0x4b && ((b[2] === 3 && b[3] === 4) || (b[2] === 5 && b[3] === 6));
66
119
  const isTar = (b) => b.length >= 512 &&
67
120
  (ascii(b, 257, 262) === 'ustar' ||
@@ -83,14 +136,20 @@ function archivePath(name, span) {
83
136
  throw bad("'..' segment");
84
137
  return normalizeVirtual('/' + name, span, 'archive entry').path;
85
138
  }
86
- // ------------------------------------------------------------------ gzip
87
- async function gunzip(bytes, origin, limits, span) {
139
+ // ------------------------------------------------------------ gzip, zstd
140
+ /**
141
+ * Decompress a gzip or zstd stream within the limits (the same ratio and size caps for both). zstd is
142
+ * Node's libzstd (frames that need a window over 128 MiB are refused; rust/src/resources/archive.rs
143
+ * matches what it accepts).
144
+ */
145
+ async function decompress(kind, bytes, origin, limits, span) {
88
146
  const byRatio = Math.max(bytes.length * limits.maxRatio, RATIO_FLOOR);
89
147
  // The inflated stream is tar: file data plus headers and padding for every entry.
90
148
  const byTotal = limits.maxTotalBytes + (limits.maxEntries + 2) * TAR_OVERHEAD_PER_ENTRY;
91
149
  try {
92
150
  // Async so a large archive doesn't stall other imports' sockets and timers.
93
- return await gunzipAsync(bytes, { maxOutputLength: Math.min(byRatio, byTotal) });
151
+ const options = { maxOutputLength: Math.min(byRatio, byTotal) };
152
+ return kind === 'gzip' ? await gunzipAsync(bytes, options) : await zstdDecompressAsync(bytes, options);
94
153
  }
95
154
  catch (e) {
96
155
  throw inflateError(e, origin, byRatio <= byTotal, limits, span);
@@ -211,52 +270,156 @@ function parsePax(data, bad) {
211
270
  }
212
271
  return out;
213
272
  }
214
- async function readZip(b, origin, limits, span, add) {
273
+ /** IBM437, bytes 0x80–0xFF (0x00–0x7F are ASCII). */
274
+ const CP437_HIGH = '\u00c7\u00fc\u00e9\u00e2\u00e4\u00e0\u00e5\u00e7\u00ea\u00eb\u00e8\u00ef\u00ee\u00ec\u00c4\u00c5' +
275
+ '\u00c9\u00e6\u00c6\u00f4\u00f6\u00f2\u00fb\u00f9\u00ff\u00d6\u00dc\u00a2\u00a3\u00a5\u20a7\u0192' +
276
+ '\u00e1\u00ed\u00f3\u00fa\u00f1\u00d1\u00aa\u00ba\u00bf\u2310\u00ac\u00bd\u00bc\u00a1\u00ab\u00bb' +
277
+ '\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255d\u255c\u255b\u2510' +
278
+ '\u2514\u2534\u252c\u251c\u2500\u253c\u255e\u255f\u255a\u2554\u2569\u2566\u2560\u2550\u256c\u2567' +
279
+ '\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256b\u256a\u2518\u250c\u2588\u2584\u258c\u2590\u2580' +
280
+ '\u03b1\u00df\u0393\u03c0\u03a3\u03c3\u00b5\u03c4\u03a6\u0398\u03a9\u03b4\u221e\u03c6\u03b5\u2229' +
281
+ '\u2261\u00b1\u2265\u2264\u2320\u2321\u00f7\u2248\u00b0\u2219\u00b7\u221a\u207f\u00b2\u25a0\u00a0';
282
+ /** Strict UTF-8 (a BOM is kept), or undefined. */
283
+ function utf8Strict(b) {
284
+ try {
285
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(b);
286
+ }
287
+ catch {
288
+ return undefined;
289
+ }
290
+ }
291
+ /**
292
+ * A zip entry name (APPNOTE 4.4.4, 4.6.9, appendix D). With general-purpose bit 11 it is UTF-8.
293
+ * Without it: the Info-ZIP Unicode Path field (0x7075, version 1) when its CRC-32 matches the raw
294
+ * name; else the raw name as UTF-8 when it is valid UTF-8 (macOS, 7-Zip and many tools write UTF-8
295
+ * without the flag; CP437 text of non-ASCII letters is practically never valid UTF-8); else IBM437.
296
+ */
297
+ function zipName(raw, flags, extra) {
298
+ if (flags & 0x800)
299
+ return Buffer.from(raw).toString('utf8');
300
+ for (let i = 0; i + 4 <= extra.length;) {
301
+ const id = extra[i] | (extra[i + 1] << 8);
302
+ const size = extra[i + 2] | (extra[i + 3] << 8);
303
+ if (i + 4 + size > extra.length)
304
+ break;
305
+ if (id === 0x7075 && size >= 5 && extra[i + 4] === 1) {
306
+ const stored = (extra[i + 5] | (extra[i + 6] << 8) | (extra[i + 7] << 16) | (extra[i + 8] << 24)) >>> 0;
307
+ const name = stored === crc32(raw) ? utf8Strict(extra.subarray(i + 9, i + 4 + size)) : undefined;
308
+ if (name !== undefined)
309
+ return name;
310
+ }
311
+ i += 4 + size;
312
+ }
313
+ const utf8 = utf8Strict(raw);
314
+ if (utf8 !== undefined)
315
+ return utf8;
316
+ let out = '';
317
+ for (const c of raw)
318
+ out += c < 0x80 ? String.fromCharCode(c) : CP437_HIGH[c - 0x80];
319
+ return out;
320
+ }
321
+ /** The data of the first extra field `id` in `extra`, or undefined. */
322
+ function extraField(extra, id) {
323
+ for (let i = 0; i + 4 <= extra.length;) {
324
+ const size = extra[i + 2] | (extra[i + 3] << 8);
325
+ if (i + 4 + size > extra.length)
326
+ return undefined;
327
+ if ((extra[i] | (extra[i + 1] << 8)) === id)
328
+ return extra.subarray(i + 4, i + 4 + size);
329
+ i += 4 + size;
330
+ }
331
+ return undefined;
332
+ }
333
+ /** A little-endian 64-bit integer as a number (values beyond 2^53 are rounded; they fail the limits anyway). */
334
+ const u64 = (b, at) => Number(new DataView(b.buffer, b.byteOffset, b.byteLength).getBigUint64(at, true));
335
+ const memorySource = (b) => ({ length: b.length, read: (at, len) => b.subarray(at, at + len) });
336
+ /**
337
+ * Read and check a zip's central directory and local headers (no entry data): sizes and
338
+ * counts against the limits, ZIP64 records, names, unsafe entry types, local headers that
339
+ * disagree with the central directory, overlapping entries. In central-directory order.
340
+ */
341
+ function zipIndex(src, origin, limits, span) {
215
342
  const bad = (why) => new SitefileError('E_ARCHIVE', `${origin}: ${why}`, span);
216
- const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
343
+ const r16 = (at) => { const x = src.read(at, 2); return x[0] | (x[1] << 8); };
344
+ const r32 = (at) => { const x = src.read(at, 4); return (x[0] | (x[1] << 8) | (x[2] << 16) | (x[3] << 24)) >>> 0; };
345
+ const r64 = (at) => u64(src.read(at, 8), 0);
346
+ const length = src.length;
217
347
  let eocd = -1;
218
- for (let i = b.length - 22; i >= Math.max(0, b.length - 22 - 0xffff); i--) {
219
- if (v.getUint32(i, true) === 0x06054b50) {
220
- eocd = i;
221
- break;
348
+ {
349
+ // The end record is in the last 22 + 65535 bytes (its comment is at most 65535 bytes).
350
+ const from = Math.max(0, length - 22 - 0xffff);
351
+ const tail = length >= 22 ? src.read(from, length - from) : new Uint8Array(0);
352
+ for (let i = tail.length - 22; i >= 0; i--) {
353
+ if (tail[i] === 0x50 && tail[i + 1] === 0x4b && tail[i + 2] === 5 && tail[i + 3] === 6) {
354
+ eocd = from + i;
355
+ break;
356
+ }
222
357
  }
223
358
  }
224
359
  if (eocd < 0)
225
360
  throw bad('zip end-of-central-directory record not found');
226
- const count = v.getUint16(eocd + 10, true);
227
- let p = v.getUint32(eocd + 16, true);
228
- if (count === 0xffff || p === 0xffffffff)
229
- throw bad('zip64 archives are not supported');
361
+ let count = r16(eocd + 10);
362
+ let p = r32(eocd + 16);
363
+ // ZIP64 (APPNOTE 4.3.14-4.3.15): a locator right before the end record points at the zip64 end
364
+ // record, whose counts and offsets replace the 16- and 32-bit ones. Streaming writers add it even to small archives.
365
+ if (eocd >= 20 && r32(eocd - 20) === 0x07064b50) {
366
+ const r = r64(eocd - 12);
367
+ if (r > length - 56 || r32(r) !== 0x06064b50)
368
+ throw bad('corrupt zip64 end-of-central-directory record');
369
+ count = r64(r + 32);
370
+ p = r64(r + 48);
371
+ }
230
372
  if (count > limits.maxEntries) {
231
373
  throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: archive has more than ${limits.maxEntries} entries`, span);
232
374
  }
233
375
  const list = [];
234
376
  let declared = 0;
235
377
  for (let i = 0; i < count; i++) {
236
- if (p + 46 > b.length || v.getUint32(p, true) !== 0x02014b50)
378
+ if (p + 46 > length || r32(p) !== 0x02014b50)
237
379
  throw bad('corrupt zip central directory');
238
- const nameLen = v.getUint16(p + 28, true);
239
- const advance = 46 + nameLen + v.getUint16(p + 30, true) + v.getUint16(p + 32, true);
240
- if (p + advance > b.length)
380
+ const nameLen = r16(p + 28);
381
+ const extraLen = r16(p + 30);
382
+ const advance = 46 + nameLen + extraLen + r16(p + 32);
383
+ if (p + advance > length)
241
384
  throw bad('corrupt zip central directory');
242
- const unix = v.getUint16(p + 4, true) >> 8 === 3;
243
- const attr = v.getUint32(p + 38, true) >>> 16;
385
+ const unix = r16(p + 4) >> 8 === 3;
386
+ const attr = r32(p + 38) >>> 16;
244
387
  const fileType = attr & 0o170000;
245
- const name = Buffer.from(b.subarray(p + 46, p + 46 + nameLen)).toString('utf8');
388
+ const flags = r16(p + 8);
389
+ const rawName = src.read(p + 46, nameLen);
390
+ const extra = src.read(p + 46 + nameLen, extraLen);
391
+ const name = zipName(rawName, flags, extra);
246
392
  const e = {
247
393
  name,
248
- method: v.getUint16(p + 10, true),
249
- csize: v.getUint32(p + 20, true),
250
- usize: v.getUint32(p + 24, true),
251
- local: v.getUint32(p + 42, true),
394
+ rawName,
395
+ method: r16(p + 10),
396
+ crc: r32(p + 16),
397
+ csize: r32(p + 20),
398
+ usize: r32(p + 24),
399
+ local: r32(p + 42),
252
400
  mode: unix ? attr & 0o7777 : 0o644,
253
401
  // Some tools mark directories only by mode, without a trailing slash.
254
402
  isDir: name.endsWith('/') || (unix && fileType === 0o040000),
255
403
  };
256
- if (v.getUint16(p + 8, true) & 1)
404
+ if (flags & 1)
257
405
  throw bad(`encrypted zip entry '${e.name}' is not supported`);
258
- if (e.csize === 0xffffffff || e.usize === 0xffffffff)
259
- throw bad('zip64 archives are not supported');
406
+ // ZIP64 extra field (0x0001): the 64-bit values of the fields that are 0xffffffff, in this order.
407
+ if (e.usize === 0xffffffff || e.csize === 0xffffffff || e.local === 0xffffffff) {
408
+ const z = extraField(extra, 0x0001);
409
+ let at = 0;
410
+ const next = () => {
411
+ if (!z || at + 8 > z.length)
412
+ throw bad(`corrupt zip64 extra field for '${e.name}'`);
413
+ at += 8;
414
+ return u64(z, at - 8);
415
+ };
416
+ if (e.usize === 0xffffffff)
417
+ e.usize = next();
418
+ if (e.csize === 0xffffffff)
419
+ e.csize = next();
420
+ if (e.local === 0xffffffff)
421
+ e.local = next();
422
+ }
260
423
  if (unix && fileType !== 0 && fileType !== 0o100000 && fileType !== 0o040000) {
261
424
  throw new SitefileError('E_ARCHIVE_UNSAFE', `unsafe archive entry '${e.name}': symlink or special file entries are not allowed`, span);
262
425
  }
@@ -267,40 +430,159 @@ async function readZip(b, origin, limits, span, add) {
267
430
  if (declared > limits.maxTotalBytes) {
268
431
  throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: archive expands beyond ${limits.maxTotalBytes} bytes`, span);
269
432
  }
270
- if (declared > Math.max(b.length * limits.maxRatio, RATIO_FLOOR)) {
433
+ if (declared > Math.max(length * limits.maxRatio, RATIO_FLOOR)) {
271
434
  throw new SitefileError('E_ARCHIVE_LIMIT', `${origin}: compression ratio exceeds ${limits.maxRatio}:1`, span);
272
435
  }
436
+ // Every local header must agree with its central record, and no two entries' bytes may overlap:
437
+ // otherwise other tools (unzip, browsers, Archive Utility) would see different files (#184).
438
+ const unsafe = (e, why) => new SitefileError('E_ARCHIVE_UNSAFE', `unsafe archive entry '${e.name}': ${why}`, span);
439
+ const spans = [];
273
440
  for (const e of list) {
274
- if (e.isDir) {
275
- add(e.name, 'dir', new Uint8Array(0), 0o755);
276
- continue;
277
- }
278
441
  const h = e.local;
279
- if (h + 30 > b.length || v.getUint32(h, true) !== 0x04034b50)
442
+ if (h + 30 > length || r32(h) !== 0x04034b50)
280
443
  throw bad(`corrupt zip local header for '${e.name}'`);
281
- const start = h + 30 + v.getUint16(h + 26, true) + v.getUint16(h + 28, true);
282
- if (start + e.csize > b.length)
444
+ const nameLen = r16(h + 26);
445
+ const start = h + 30 + nameLen + r16(h + 28);
446
+ if (start + e.csize > length)
283
447
  throw bad(`truncated zip entry '${e.name}'`);
284
- const raw = b.subarray(start, start + e.csize);
285
- let data;
286
- if (e.method === 0) {
287
- data = raw;
288
- }
289
- else if (e.method === 8) {
290
- try {
291
- // Headers can lie: never inflate more than the declared size.
292
- data = await inflateRawAsync(raw, { maxOutputLength: Math.max(e.usize, 1) });
293
- }
294
- catch (err) {
295
- throw inflateError(err, origin, false, limits, span);
448
+ if (Buffer.compare(src.read(h + 30, nameLen), e.rawName) !== 0)
449
+ throw unsafe(e, 'its local header has a different name');
450
+ if (r16(h + 8) !== e.method)
451
+ throw unsafe(e, 'its local header has a different compression method');
452
+ // With a data descriptor (bit 3) the local sizes may be zero; the descriptor follows the data.
453
+ if (!(r16(h + 6) & 8)) {
454
+ let csize = r32(h + 18);
455
+ let usize = r32(h + 22);
456
+ if (csize === 0xffffffff || usize === 0xffffffff) {
457
+ // A local ZIP64 extra field holds both sizes (APPNOTE 4.5.3); Python's force_zip64 writes one.
458
+ const z = extraField(src.read(h + 30 + nameLen, start - (h + 30 + nameLen)), 0x0001);
459
+ if (z && z.length >= 16)
460
+ [usize, csize] = [u64(z, 0), u64(z, 8)];
296
461
  }
462
+ if (csize !== e.csize || usize !== e.usize)
463
+ throw unsafe(e, 'its local header has different sizes');
297
464
  }
298
- else {
299
- throw bad(`zip entry '${e.name}' uses unsupported compression method ${e.method}`);
465
+ spans.push({ e, from: h, start, end: start + e.csize });
466
+ }
467
+ const byOffset = [...spans].sort((a, c) => a.from - c.from);
468
+ for (let i = 1; i < byOffset.length; i++) {
469
+ const prev = byOffset[i - 1];
470
+ const cur = byOffset[i];
471
+ if (cur.from < prev.end)
472
+ throw unsafe(cur.e, `its data overlaps entry '${prev.e.name}'`);
473
+ }
474
+ return spans.map(({ e, start }) => ({ e, start }));
475
+ }
476
+ /** Check an inflated (or stored) entry against its header: size and CRC-32. */
477
+ function checkZipData(data, e, bad) {
478
+ if (data.length !== e.usize)
479
+ throw bad(`zip entry '${e.name}' size does not match its header`);
480
+ // Inflate cannot notice a corrupt stored entry; the CRC-32 can.
481
+ if (crc32(data) !== e.crc)
482
+ throw bad(`zip entry '${e.name}' fails its CRC-32 check`);
483
+ return data;
484
+ }
485
+ /** An entry's bytes, inflated (never beyond its declared size) and checked. */
486
+ async function zipData(src, { e, start }, origin, limits, span) {
487
+ const bad = (why) => new SitefileError('E_ARCHIVE', `${origin}: ${why}`, span);
488
+ const raw = src.read(start, e.csize);
489
+ let data;
490
+ if (e.method === 0) {
491
+ data = raw;
492
+ }
493
+ else if (e.method === 8) {
494
+ try {
495
+ // Headers can lie: never inflate more than the declared size.
496
+ data = await inflateRawAsync(raw, { maxOutputLength: Math.max(e.usize, 1) });
300
497
  }
301
- if (data.length !== e.usize)
302
- throw bad(`zip entry '${e.name}' size does not match its header`);
303
- add(e.name, 'file', data, e.mode);
498
+ catch (err) {
499
+ throw inflateError(err, origin, false, limits, span);
500
+ }
501
+ }
502
+ else {
503
+ throw bad(`zip entry '${e.name}' uses unsupported compression method ${e.method}`);
504
+ }
505
+ return checkZipData(data, e, bad);
506
+ }
507
+ async function readZip(b, origin, limits, span, add) {
508
+ const src = memorySource(b);
509
+ for (const s of zipIndex(src, origin, limits, span)) {
510
+ if (s.e.isDir) {
511
+ add(s.e.name, 'dir', EMPTY, 0o755);
512
+ continue;
513
+ }
514
+ add(s.e.name, 'file', await zipData(src, s, origin, limits, span), s.e.mode);
515
+ }
516
+ }
517
+ /**
518
+ * Open a zip file for serving without extracting it into memory: the central directory and
519
+ * local headers are read and checked as {@link extractArchive} checks them, and every entry is
520
+ * inflated once (one at a time) for its CRC-32, digest and the limits. Afterwards only the
521
+ * entry index is held; `read` reads an entry from the file on demand. A file that changed on
522
+ * disk since is reported as `E_ARCHIVE` by `read`.
523
+ */
524
+ export async function openZipFile(file, origin, limits = DEFAULT_ARCHIVE_LIMITS) {
525
+ const fd = openSync(file, 'r');
526
+ try {
527
+ const length = fstatSync(fd).size;
528
+ const src = {
529
+ length,
530
+ read(at, len) {
531
+ const buf = Buffer.alloc(len);
532
+ let got = 0;
533
+ while (got < len) {
534
+ const n = readSync(fd, buf, got, len - got, at + got);
535
+ if (n === 0)
536
+ throw new SitefileError('E_ARCHIVE', `${origin}: the file changed while it was read`);
537
+ got += n;
538
+ }
539
+ return buf;
540
+ },
541
+ };
542
+ const { add, files } = collector(origin, limits, undefined, false);
543
+ const byPath = new Map();
544
+ for (const s of zipIndex(src, origin, limits, undefined)) {
545
+ if (s.e.isDir) {
546
+ add(s.e.name, 'dir', EMPTY, 0o755);
547
+ continue;
548
+ }
549
+ add(s.e.name, 'file', await zipData(src, s, origin, limits, undefined), s.e.mode);
550
+ byPath.set(archivePath(s.e.name), s);
551
+ }
552
+ const tree = Tree.fromFiles(files);
553
+ const bad = (why) => new SitefileError('E_ARCHIVE', `${origin}: ${why}`);
554
+ return {
555
+ tree,
556
+ read(path) {
557
+ const s = byPath.get(path);
558
+ if (!s)
559
+ return undefined;
560
+ const raw = src.read(s.start, s.e.csize);
561
+ let data = raw;
562
+ if (s.e.method === 8) {
563
+ try {
564
+ data = inflateRawSync(raw, { maxOutputLength: Math.max(s.e.usize, 1) });
565
+ }
566
+ catch {
567
+ throw bad(`zip entry '${s.e.name}' changed since the server started`);
568
+ }
569
+ }
570
+ if (data.length !== s.e.usize || crc32(data) !== s.e.crc)
571
+ throw bad(`zip entry '${s.e.name}' changed since the server started`);
572
+ return data;
573
+ },
574
+ deflated(path) {
575
+ const s = byPath.get(path);
576
+ if (!s || s.e.method !== 8)
577
+ return undefined;
578
+ return { deflate: src.read(s.start, s.e.csize), crc: s.e.crc, size: s.e.usize };
579
+ },
580
+ close: () => closeSync(fd),
581
+ };
582
+ }
583
+ catch (e) {
584
+ closeSync(fd);
585
+ throw e;
304
586
  }
305
587
  }
306
588
  //# sourceMappingURL=archive.js.map
@@ -1,6 +1,7 @@
1
1
  import { SitefileError } from '../errors.js';
2
2
  import { sha256 } from '../digest.js';
3
3
  import { extractArchive } from './archive.js';
4
+ import { looksLikeWarc, readWarc } from '../warc.js';
4
5
  import { markdownDocument } from './documents.js';
5
6
  import { bundleValue } from './bundle-data.js';
6
7
  import { readWebBundle } from './wbn-reader.js';
@@ -21,7 +22,8 @@ export async function bytesToResource(bytes, kind, info, span, archiveLimits = D
21
22
  const provenance = info.resolvedUrl === undefined ? { uri: info.uri, digest } : { uri: info.uri, resolvedUrl: info.resolvedUrl, digest };
22
23
  if (kind === 'tree') {
23
24
  // The provenance digest is that of the archive bytes, which is what pins and the lockfile cover.
24
- return { kind: 'tree', tree: await extractArchive(bytes, info.uri, archiveLimits, span), provenance };
25
+ const tree = looksLikeWarc(bytes) ? readWarc(bytes, info.uri, archiveLimits, span) : await extractArchive(bytes, info.uri, archiveLimits, span);
26
+ return { kind: 'tree', tree, provenance };
25
27
  }
26
28
  if (kind === 'markdown') {
27
29
  return { kind: 'value', format: 'markdown', value: markdownDocument(bytes, '/' + info.basename, info.uri, span), provenance };
@@ -9,6 +9,9 @@ export interface FetchResult {
9
9
  readonly finalUrl: string;
10
10
  /** Media type essence from `content-type` (lowercase, parameters removed). */
11
11
  readonly mediaType?: string;
12
+ /** `raw` requests only: the status and the response headers (lowercase names, values in order). */
13
+ readonly status?: number;
14
+ readonly headers?: ReadonlyArray<readonly [string, readonly string[]]>;
12
15
  }
13
16
  /**
14
17
  * What to send. `headers` go to every hop; `originHeaders` (credentials: IMPORT … SECRET) only to hops
@@ -16,7 +19,12 @@ export interface FetchResult {
16
19
  * A request with a body (POST) never follows redirects (E_REDIRECT).
17
20
  */
18
21
  export interface FetchRequest {
19
- readonly method?: 'GET' | 'POST';
22
+ readonly method?: 'GET' | 'POST' | 'HEAD';
23
+ /**
24
+ * One hop only, for `serve`'s proxy rules: redirects are not followed, every status and content
25
+ * encoding is returned as it is (with the headers), and the body is still size- and time-limited.
26
+ */
27
+ readonly raw?: boolean;
20
28
  readonly body?: Uint8Array;
21
29
  readonly headers?: Readonly<Record<string, string>>;
22
30
  readonly originHeaders?: Readonly<Record<string, string>>;
@@ -127,6 +127,42 @@ export async function fetchRemote(url, policy, span, request = {}) {
127
127
  const headers = current.origin === origin ? { ...request.headers, ...request.originHeaders } : { ...request.headers };
128
128
  const res = await openHop(current, policy, controller.signal, state, span, timeoutError, method, headers, request.body);
129
129
  const status = res.statusCode ?? 0;
130
+ if (request.raw) {
131
+ const chunks = [];
132
+ let total = 0;
133
+ try {
134
+ for await (const chunk of res) {
135
+ total += chunk.length;
136
+ if (total > policy.maxBytes) {
137
+ res.destroy();
138
+ throw new SitefileError('E_TOO_LARGE', `${redactUrl(current)} exceeded the limit of ${policy.maxBytes} bytes`, span);
139
+ }
140
+ chunks.push(chunk);
141
+ }
142
+ }
143
+ catch (e) {
144
+ if (isSitefileError(e))
145
+ throw e;
146
+ if (controller.signal.aborted)
147
+ throw timeoutError();
148
+ if (state.failure)
149
+ throw state.failure;
150
+ throw new SitefileError('E_FETCH', `error reading ${redactUrl(current)}: ${e.message}`, span, { cause: e });
151
+ }
152
+ if (controller.signal.aborted)
153
+ throw timeoutError();
154
+ const grouped = [];
155
+ for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
156
+ const name = res.rawHeaders[i].toLowerCase();
157
+ const found = grouped.find(([n]) => n === name);
158
+ if (found)
159
+ found[1].push(res.rawHeaders[i + 1]);
160
+ else
161
+ grouped.push([name, [res.rawHeaders[i + 1]]]);
162
+ }
163
+ const buf = Buffer.concat(chunks, total);
164
+ return { bytes: new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength), finalUrl: current.href, status, headers: grouped };
165
+ }
130
166
  if (REDIRECT_STATUSES.has(status) && method !== 'GET') {
131
167
  res.destroy();
132
168
  throw new SitefileError('E_REDIRECT', `${method} ${redactUrl(current)} was redirected (HTTP ${status}); redirects are only followed for GET`, span);
@@ -14,6 +14,14 @@ export interface NetworkSettings {
14
14
  readonly allowHosts?: readonly string[] | undefined;
15
15
  /** Hosts never contacted; a deny rule beats an allow rule. */
16
16
  readonly denyHosts?: readonly string[] | undefined;
17
+ /**
18
+ * Strict network mode (`--network strict`, `SITEFILE_NETWORK=strict`): every host must match an
19
+ * allow-hosts rule, also when there is none (so nothing is contacted), and an `IMPORT … SECRET` needs
20
+ * a {@link secretHosts} rule for its host.
21
+ */
22
+ readonly strict?: boolean | undefined;
23
+ /** `<secret id>=<host pattern>` (`--allow-secret-host`): where, in strict mode, that secret may be sent. */
24
+ readonly secretHosts?: readonly string[] | undefined;
17
25
  /** Time limit for establishing the TCP connection (to the target, or to the proxy), ms. */
18
26
  readonly connectTimeoutMs?: number | undefined;
19
27
  /** Longest wait for data once connected (idle time), ms. */
@@ -49,6 +57,15 @@ export declare function urlPort(url: URL): number;
49
57
  * Throws E_HOST_BLOCKED naming the rule; a deny rule beats an allow rule.
50
58
  */
51
59
  export declare function checkHostRules(url: URL, network: NetworkSettings | undefined, shown: string, span?: SourceSpan): void;
60
+ /** True when `host:port` may be contacted under `network`'s host rules (see {@link checkHostRules}). */
61
+ export declare function hostAllowed(host: string, port: number, network: NetworkSettings | undefined): boolean;
62
+ /**
63
+ * Before an `IMPORT … SECRET` request to `target` (the import's own origin, the only one its secrets are
64
+ * sent to): in strict network mode each secret needs an `--allow-secret-host <id>=<pattern>` that matches
65
+ * the host. Throws E_HOST_BLOCKED with a `needs`. Nothing is checked outside strict mode, and a host the
66
+ * host rules refuse is left to the request itself (its E_HOST_BLOCKED asks for `--allow-hosts` first).
67
+ */
68
+ export declare function checkSecretHosts(importName: string, secretIds: readonly string[], target: string, network: NetworkSettings | undefined, span?: SourceSpan): void;
52
69
  /** The proxy to use for `url`, or undefined for a direct connection (no proxy, or a no-proxy match). */
53
70
  export declare function proxyFor(url: URL, network: NetworkSettings | undefined): ProxyConfig | undefined;
54
71
  /** A usage problem in `network` (bad proxy URL, host pattern or timeout), or undefined. */
@@ -58,13 +75,18 @@ export declare function parseFetchTimeout(raw: string): {
58
75
  connectTimeoutMs?: number;
59
76
  readTimeoutMs?: number;
60
77
  };
78
+ /** Parse a network mode (`open` or `strict`; empty: unset); `what` names the source in the E_USAGE message. */
79
+ export declare function parseNetworkMode(raw: string, what: string): boolean | undefined;
61
80
  /**
62
81
  * Network settings from `SITEFILE_PROXY`, `SITEFILE_NO_PROXY`, `SITEFILE_ALLOW_HOSTS`,
63
- * `SITEFILE_DENY_HOSTS` (comma- or space-separated) and `SITEFILE_FETCH_TIMEOUT`. Empty values are unset.
64
- * `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` are never read.
82
+ * `SITEFILE_DENY_HOSTS` (comma- or space-separated), `SITEFILE_FETCH_TIMEOUT` and `SITEFILE_NETWORK`
83
+ * (`open` or `strict`). Empty values are unset. `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` are never read.
65
84
  */
66
85
  export declare function networkFromEnv(env?: NodeJS.ProcessEnv): NetworkSettings;
67
- /** `over` on top of `base`: the proxy and timeouts are replaced, the host lists are joined (duplicates dropped). */
86
+ /**
87
+ * `over` on top of `base`: the proxy and timeouts are replaced, the host lists are joined (duplicates
88
+ * dropped), and strict mode is on when either is strict.
89
+ */
68
90
  export declare function mergeNetwork(base: NetworkSettings, over: NetworkSettings): NetworkSettings;
69
91
  /** True when any setting is present. */
70
92
  export declare function hasNetworkSettings(n: NetworkSettings | undefined): boolean;