@threadedstack/wmd-web 0.1.38 → 0.1.41

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 (68) hide show
  1. package/README.md +239 -2
  2. package/RELEASE.json +97 -53
  3. package/guest/arm64/Image +1 -1
  4. package/guest/arm64/Image-4k +1 -1
  5. package/guest/arm64/initramfs.cpio.gz +0 -0
  6. package/package.json +3 -3
  7. package/src/boot.js +321 -12
  8. package/src/edge/auto.js +77 -0
  9. package/src/edge/base.js +10 -0
  10. package/src/edge/bridge.js +76 -7
  11. package/src/edge/ctl.js +21 -4
  12. package/src/edge/error-kind.js +6 -0
  13. package/src/edge/frame-code.gen.js +6 -0
  14. package/src/edge/frame.js +58 -15
  15. package/src/edge/msg.js +3 -0
  16. package/src/edge/own/adapter.js +208 -19
  17. package/src/edge/own/exit-now.js +62 -0
  18. package/src/edge/own/fs-own-route.js +40 -3
  19. package/src/edge/own/fs-stats.js +11 -0
  20. package/src/edge/own/hub.js +125 -14
  21. package/src/edge/own/loader.js +3 -2
  22. package/src/edge/own/marks.js +158 -0
  23. package/src/edge/own/net-host.js +873 -0
  24. package/src/edge/own/node-globals.js +142 -0
  25. package/src/edge/own/pool.js +30 -1
  26. package/src/edge/own/service-receiver.js +7 -1
  27. package/src/edge/own/shim-post.js +38 -0
  28. package/src/edge/own/worker.js +34 -1
  29. package/src/edge/page.js +448 -25
  30. package/src/edge/pins.gen.js +17 -0
  31. package/src/edge/pins.js +21 -0
  32. package/src/edge/plan.js +45 -9
  33. package/src/edge/python-module.js +18 -0
  34. package/src/edge/python-pins.js +64 -0
  35. package/src/edge/python-plan.js +280 -0
  36. package/src/edge/python-source.js +34 -0
  37. package/src/edge/runtime.js +13 -2
  38. package/src/edge/sbx/cap.js +36 -0
  39. package/src/edge/sbx/common.js +186 -0
  40. package/src/edge/sbx/doc.js +121 -0
  41. package/src/edge/sbx/files.js +112 -0
  42. package/src/edge/sbx/frame.js +126 -0
  43. package/src/edge/sbx/gate.js +115 -0
  44. package/src/edge/sbx/sha256.js +68 -0
  45. package/src/edge/sbx/worker-entry.js +36 -0
  46. package/src/edge/sems.js +113 -0
  47. package/src/edge/service-host.js +57 -5
  48. package/src/edge/service-port.js +79 -5
  49. package/src/edge/setup.js +275 -0
  50. package/src/edge/shim.js +3 -1
  51. package/src/edge/watch.js +101 -0
  52. package/src/edge/worker.js +31 -2
  53. package/src/gowasm/boot-setup.js +175 -0
  54. package/src/gowasm/make-pins-module.mjs +35 -0
  55. package/src/gowasm/pins-data.js +162 -0
  56. package/src/gowasm/setup.js +167 -0
  57. package/src/gowasm/twin-fetch.js +27 -0
  58. package/src/host/chan-service.js +33 -6
  59. package/src/host/chan-services.js +29 -4
  60. package/src/host/ckpt.js +78 -0
  61. package/src/host/csp-reason.js +64 -0
  62. package/src/host/ctl.js +30 -8
  63. package/src/host/edge-go.js +94 -4
  64. package/src/host/edge-host.js +58 -3
  65. package/src/host/gowasm-guard.js +11 -1
  66. package/src/host/gowasm-worker.js +90 -35
  67. package/src/host/pinned-fetch.js +436 -0
  68. package/wmdpack.wasm +0 -0
@@ -17,12 +17,19 @@
17
17
  // Paths are the container's absolute paths; in the in-memory file system they have no leading slash (the one
18
18
  // preopen is "/"). The inputs are kept between runs (the same archives are read by many compiles), at most cacheBytes.
19
19
  import { MemFs, runWasi } from '../registry/wasi-mem.js'
20
- import { makeBeat, verifyModule } from './gowasm-guard.js'
20
+ import { TWIN_WAIT_MS, makeBeat, verifyModule } from './gowasm-guard.js'
21
+ import { fetchPinned } from './pinned-fetch.js'
22
+ import { cspWatch } from './csp-reason.js'
21
23
 
22
24
  const modules = new Map() // sha256 (lower case) -> {url, module?: WebAssembly.Module, bad?: string}
25
+ let globalSources = null // the ordered sources the page gave (pinned-fetch.js); none: each module's own url
23
26
  let firstModule = null // the sha256 of the module a run that names none uses
24
27
  let cacheCap = 192 << 20
25
28
  let beatMs = 200
29
+ let waitMs = TWIN_WAIT_MS // the longest a run waits for a module that is not loaded (X6 default part 5); past it the run is answered `loading`
30
+ let fetchKnobs = {} // stallMs, sourceMs (timeoutMs), loadMs (allMs): tests only
31
+ let diedSaid = false
32
+ const csp = cspWatch(self) // X6 fix 10: a source the page's policy blocked says so in its reason
26
33
  let port = null
27
34
  const cache = new Map() // abs path -> {key, bytes, used}
28
35
  let clock = 0
@@ -61,55 +68,102 @@ const cacheBytes = () => {
61
68
  return n
62
69
  }
63
70
 
71
+ /** A module url as the Worker's own place sees it (a table may give one relative to the page); one that cannot be made absolute goes on as it is and is refused. */
72
+ const absoluteUrl = u => {
73
+ try {
74
+ return new URL(u, self.location?.href).href
75
+ } catch {
76
+ return String(u)
77
+ }
78
+ }
79
+
64
80
  /**
65
- * The module with this sha256, fetched, hashed against that sha256 and compiled (once). Returns {module} or {error, fatal}: fatal is a
66
- * module that is not the one the table names (the twin is off for the machine), else it could not be fetched or compiled.
81
+ * The module with this sha256, fetched, hashed against that sha256 and compiled: ONCE per module per Worker (X6 default part 5: the promise is kept, so a run that
82
+ * gave up waiting, or a second run, starts no second download). Resolves {module, wasmBytes, fetchMs, compileMs} or {error, fatal}: fatal is a module that is not
83
+ * the one the table names or that no source could give (the twin is off for the machine), else it could not be compiled. When the load ends the Worker says so
84
+ * to the page: {t:'loaded'}, or {t:'died', fatal:true} (once, with the reason of each source).
67
85
  */
68
- async function loadModule(sha) {
86
+ function loadModule(sha) {
69
87
  const e = modules.get(sha)
70
- if (!e) return { error: `the table names no module ${String(sha).slice(0, 12)}...` }
71
- if (e.module) return { module: e.module }
72
- if (e.bad) return { error: e.bad, fatal: e.fatal }
88
+ if (!e) return Promise.resolve({ error: `the table names no module ${String(sha).slice(0, 12)}...` })
89
+ if (e.module) return Promise.resolve({ module: e.module })
90
+ if (e.bad) return Promise.resolve({ error: e.bad, fatal: e.fatal })
91
+ if (!e.loadP) {
92
+ e.loadP = doLoad(sha, e).then(l => {
93
+ if (l.error) {
94
+ if (l.fatal && !diedSaid) {
95
+ diedSaid = true
96
+ port.postMessage({ t: 'died', why: l.error, fatal: true })
97
+ }
98
+ } else {
99
+ port.postMessage({ t: 'loaded', sha, wasmBytes: l.wasmBytes, fetchMs: l.fetchMs, compileMs: l.compileMs })
100
+ }
101
+ return l
102
+ })
103
+ }
104
+ return e.loadP
105
+ }
106
+
107
+ async function doLoad(sha, e) {
73
108
  const t0 = performance.now()
74
109
  try {
75
- const resp = await fetch(e.url)
76
- if (!resp.ok) throw new Error(`${e.url}: HTTP ${resp.status}`)
77
- const bytes = await resp.arrayBuffer()
78
- const t1 = performance.now()
79
- // the module is the one tools.json names, or it is not compiled: the page's server is the only thing that gives it
80
- const v = await verifyModule(bytes, sha)
81
- if (!v.ok) {
82
- e.bad = `the twin module does not match its hash: ${v.why}`
110
+ // X6 default part 3, item 2: the bytes come from an ordered list of sources that are not trusted (src/host/pinned-fetch.js): a tarball of the npm registry,
111
+ // a file under a base, or the table's own url; the first that gives the pinned sha256 and size wins, and a good one is kept in Cache Storage
112
+ const sources = e.sources || globalSources || [{ kind: 'url', url: absoluteUrl(e.url) }]
113
+ const path = e.path || String(e.url || 'twin.wasm').split('/').pop() || 'twin.wasm'
114
+ let last = -1e9
115
+ const onProgress = bytes => {
116
+ const t = performance.now()
117
+ if (t - last < 250) return
118
+ last = t
119
+ port?.postMessage({ t: 'loading', sha, bytes })
120
+ }
121
+ const got = await fetchPinned({ files: [{ path, sha256: sha, size: e.size }], pkg: e.pkg ?? null, sources, schemes: ['https:', 'http:', 'data:', 'blob:'], onProgress, explain: (u, err) => csp.explain(u, err), ...(fetchKnobs.stallMs ? { stallMs: fetchKnobs.stallMs } : {}), ...(fetchKnobs.sourceMs ? { timeoutMs: fetchKnobs.sourceMs } : {}), ...(fetchKnobs.loadMs ? { allMs: fetchKnobs.loadMs } : {}) })
122
+ if (got.error) {
123
+ // every source failed (or the cache and the sources together): the twin is off for the machine, with the reason of each source in one text
124
+ e.bad = `the twin module could not be had: ${got.error}`
83
125
  e.fatal = true
84
126
  return { error: e.bad, fatal: true }
85
127
  }
128
+ const bytes = got.files[path]
129
+ const t1 = performance.now()
86
130
  e.module = await WebAssembly.compile(bytes)
87
131
  return { module: e.module, wasmBytes: bytes.byteLength, fetchMs: t1 - t0, compileMs: performance.now() - t1 }
88
132
  } catch (err) {
133
+ // the bytes passed the hash check, so a compile that throws (an engine out of memory, a module this engine cannot take) will throw again: the twin is off for
134
+ // the machine, once, with the real reason (a page that was told `loading` must not wait for ever), and nothing is downloaded a second time
89
135
  e.bad = `the twin did not load: ${(err && err.message) || err}`
90
- return { error: e.bad }
136
+ e.fatal = true
137
+ return { error: e.bad, fatal: true }
91
138
  }
92
139
  }
93
140
 
94
- /** A run whose module is not loaded yet loads it first, beating while it does (the page's watchdog counts beats); then compileOnce. */
141
+ /**
142
+ * A run whose module is not loaded starts the load (once), beating while it waits for it, at most waitMs: past that it is answered `loading` (not a failure: the
143
+ * guest compiles it) and the load goes on. Then compileOnce.
144
+ */
95
145
  async function runMessage(m) {
96
146
  if (m.t !== 'run') return compileOnce(m, null)
97
147
  const sha = (m.module ?? firstModule)?.toLowerCase()
98
148
  const e = modules.get(sha)
99
149
  if (!e) return { t: 'done', id: m.id, infra: `the table names no module ${String(sha).slice(0, 12)}...`, held: heldList() }
100
- let timer = null
101
- if (!e.module && !e.bad) timer = setInterval(() => port.postMessage({ t: 'beat', id: m.id }), beatMs)
102
150
  let l
103
- try {
104
- l = await loadModule(sha)
105
- } finally {
106
- clearInterval(timer)
151
+ if (e.module || e.bad) l = await loadModule(sha)
152
+ else {
153
+ const timer = setInterval(() => port.postMessage({ t: 'beat', id: m.id }), beatMs)
154
+ let wait = null
155
+ try {
156
+ const gate = new Promise(r => (wait = setTimeout(() => r(null), waitMs)))
157
+ l = await Promise.race([loadModule(sha), gate])
158
+ } finally {
159
+ clearInterval(timer)
160
+ clearTimeout(wait)
161
+ }
162
+ if (l === null) return { t: 'done', id: m.id, loading: true, module: sha, held: heldList() }
107
163
  }
108
164
  if (l.error) {
109
- if (l.fatal) {
110
- port.postMessage({ t: 'died', why: l.error, fatal: true })
111
- return null
112
- }
165
+ // a module no source could give: loadModule said so to the page once ({t:'died', fatal}); this run has no answer to give
166
+ if (l.fatal) return null
113
167
  return { t: 'done', id: m.id, infra: l.error, held: heldList() }
114
168
  }
115
169
  return compileOnce(m, l.module)
@@ -152,22 +206,22 @@ function compileOnce(m, module) {
152
206
  }
153
207
 
154
208
  self.onmessage = async ({ data: m }) => {
209
+ if (m.t === 'csp') return csp.add(m.violation) // the page's document saw the violation (a browser that does not fire it in the Worker)
155
210
  if (m.t !== 'init') return
156
211
  port = m.port
157
212
  cacheCap = m.cacheBytes ?? cacheCap
158
213
  beatMs = m.beatMs ?? beatMs
214
+ waitMs = m.waitMs ?? waitMs
215
+ fetchKnobs = { stallMs: m.stallMs, sourceMs: m.sourceMs, loadMs: m.loadMs }
216
+ globalSources = Array.isArray(m.sources) && m.sources.length ? m.sources : null
159
217
  try {
160
218
  // one module (the table's own wasmUrl and wasmSha256, which may be missing: the verifier then refuses) or a list of them
161
219
  const list = m.modules || [{ url: m.wasmUrl, sha256: m.wasmSha256 }]
162
- for (const x of list) modules.set(typeof x.sha256 === 'string' ? x.sha256.toLowerCase() : `none:${modules.size}`, { url: x.url })
220
+ for (const x of list) modules.set(typeof x.sha256 === 'string' ? x.sha256.toLowerCase() : `none:${modules.size}`, { url: x.url, size: x.size, path: x.path, pkg: x.pkg })
163
221
  firstModule = [...modules.keys()][0]
222
+ // X6 default part 5: a preloaded module starts loading now and the Worker says ready at once: the network never holds `ready` (a compile that comes before the
223
+ // module is there waits for it at most waitMs, then goes to the guest)
164
224
  const pre = m.modules ? m.preload || [] : [firstModule]
165
- let first = null
166
- for (const sha of pre) {
167
- const l = await loadModule(String(sha).toLowerCase())
168
- if (l.error) return port.postMessage({ t: 'died', why: l.error, fatal: l.fatal })
169
- first ??= l
170
- }
171
225
  // a table keyed by a sha256 that is no digest at all (the one-module shape with no wasmSha256) is refused by the verifier above
172
226
  port.onmessage = async e => {
173
227
  let r
@@ -178,7 +232,8 @@ self.onmessage = async ({ data: m }) => {
178
232
  }
179
233
  if (r) port.postMessage(r, (r.outs || []).map(o => o.bytes.buffer))
180
234
  }
181
- port.postMessage({ t: 'ready', wasmBytes: first?.wasmBytes ?? 0, fetchMs: first?.fetchMs ?? 0, compileMs: first?.compileMs ?? 0, loaded: pre.length })
235
+ port.postMessage({ t: 'ready', wasmBytes: 0, fetchMs: 0, compileMs: 0, loaded: 0, loading: pre.length })
236
+ for (const sha of pre) void loadModule(String(sha).toLowerCase())
182
237
  } catch (err) {
183
238
  port.postMessage({ t: 'died', why: `the twin did not load: ${(err && err.message) || err}` })
184
239
  }
@@ -0,0 +1,436 @@
1
+ // Pinned files from sources this library does not trust. A caller names the files it needs (a path, the sha256 and the size each must have) and an
2
+ // ordered list of sources; the first source that gives EVERY file with its pinned sha256 and size wins. A source that fails, stalls, is too big or gives
3
+ // a wrong hash is left for the next, with one reason kept per source. Nothing here throws and nothing waits without a limit.
4
+ //
5
+ // Source kinds (the url texts may hold {name}, {version} and {file}, from the package the pins name; {file} is the name without its scope):
6
+ // { kind: 'tgz', url } an npm registry tarball: the body goes through DecompressionStream('gzip') and a small tar reader that picks the pinned
7
+ // paths ('package/<path>') in one pass, bounded by the tarball bound and the pinned sizes
8
+ // { kind: 'file', base } a plain file at <base>/<path> (a mirror, a CDN of the package, the consumer's own copy)
9
+ // { kind: 'url', url } one file at exactly this url (the table of an embedder that serves its own twin, a data: url in tests)
10
+ // A good fetch is kept in Cache Storage of the page's own origin under a key that holds the sha256, read back after a new hash check; a damaged entry
11
+ // is removed; storage that is missing or throws means a fetch each time. Used by the twin's Worker (X6) and shared with X5.
12
+ const hexOf = buf => [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, '0')).join('')
13
+ const sha256Of = async bytes => hexOf(await crypto.subtle.digest('SHA-256', bytes))
14
+
15
+ export const PINNED_CACHE_NAME = 'wmd-gowasm-twin-v1'
16
+ /** The most one pinned file may be when its pin names no size (file sources only; a tar entry's size must be pinned). */
17
+ export const MAX_PINNED_BYTES = 128 * 1024 * 1024
18
+ /** What a tarball may hold beyond the pinned files (headers, the notices, package.json): added to the pinned sizes for both bounds. */
19
+ export const TAR_OVERHEAD = 8 * 1024 * 1024
20
+ export const PINNED_TOTAL_MS = 300_000
21
+ /**
22
+ * X6 default part 5: ONE bound over all the sources of one fetch, taken from the first byte asked for (ms). Each source keeps its own PINNED_TOTAL_MS, but a source
23
+ * gets no more than what is left of this, and when it has passed no further source is asked. The largest twin (Go 1.27.4) is 52.5 MB: one source's 300 s lets a link
24
+ * of 1.4 Mbit/s bring it in; 600 s lets two sources each be tried to their full bound (a first that trickles and a second that works), and a list of three can no
25
+ * longer take 900 s. Past it the twin is off for the machine and the guest compiles.
26
+ */
27
+ export const PINNED_ALL_MS = 600_000
28
+ // the longest a source may send no byte (and no response headers) before the next source is asked: a slow link still sends bytes, a dead one does not;
29
+ // measured: the never-answering first source cost the twin 30.2 to 30.3 s (cell c, three browsers), the build itself was not held
30
+ export const PINNED_STALL_MS = 30_000
31
+ const PAX_MAX = 8192
32
+
33
+ const originOf = () => {
34
+ const o = globalThis.location && globalThis.location.origin
35
+ return typeof o === 'string' && /^https?:/.test(o) ? o : 'https://wmd.invalid'
36
+ }
37
+ /** The Cache Storage key of a file: a url of the page's own origin that holds the sha256 (never fetched). */
38
+ export const pinnedCacheKey = sha => `${originOf()}/.wmd-gowasm-twin/${String(sha).toLowerCase()}`
39
+
40
+ const schemeOf = u => {
41
+ try {
42
+ return new URL(u).protocol
43
+ } catch {
44
+ return ''
45
+ }
46
+ }
47
+ const label = u => {
48
+ try {
49
+ const x = new URL(u)
50
+ return x.origin === 'null' ? `${x.protocol}${x.pathname.slice(0, 40)}...` : `${x.origin}${x.pathname}`.slice(0, 160)
51
+ } catch {
52
+ return String(u).slice(0, 80)
53
+ }
54
+ }
55
+ const msg = e => (e && e.message) || String(e)
56
+
57
+ /** A url template made of the package the pins name; null when it needs a package there is none of. */
58
+ function expand(t, pkg) {
59
+ if (!/\{(name|version|file)\}/.test(t)) return t
60
+ if (!pkg || typeof pkg.name !== 'string' || typeof pkg.version !== 'string' || !pkg.name || !pkg.version) return null
61
+ return t.replace(/\{name\}/g, pkg.name).replace(/\{version\}/g, pkg.version).replace(/\{file\}/g, pkg.name.replace(/^@[^/]+\//, ''))
62
+ }
63
+
64
+ class Fail extends Error {}
65
+
66
+ /** One body, read to its end: bounded in size (cap) and in silence (stallMs); chunks go to `sink`. Throws Fail. */
67
+ async function pump(resp, { cap, stallMs, ctl, sink, progress }) {
68
+ const reader = resp.body.getReader()
69
+ let got = 0
70
+ for (;;) {
71
+ let timer
72
+ const stall = new Promise(r => (timer = setTimeout(() => r({ stalled: true }), stallMs)))
73
+ let step
74
+ try {
75
+ step = await Promise.race([reader.read(), stall])
76
+ } finally {
77
+ clearTimeout(timer)
78
+ }
79
+ if (step.stalled) {
80
+ reader.cancel().catch(() => {})
81
+ ctl.abort()
82
+ throw new Fail(`the source stalled: no data for ${stallMs} ms after ${got} bytes`)
83
+ }
84
+ if (step.done) return got
85
+ got += step.value.byteLength
86
+ if (got > cap) {
87
+ reader.cancel().catch(() => {})
88
+ ctl.abort()
89
+ throw new Fail(`the body is longer than the bound of ${cap} bytes`)
90
+ }
91
+ await sink(step.value)
92
+ if (progress) progress(got)
93
+ }
94
+ }
95
+
96
+ /**
97
+ * X6 default part 5: the response headers wait for no more than the stall bound either (a source that accepts the connection and says nothing used to
98
+ * hold the fetch until the source's whole PINNED_TOTAL_MS).
99
+ */
100
+ async function fetchHeaders(fetchFn, url, init, stallMs, ctl) {
101
+ let timer
102
+ const stall = new Promise((_, rej) => (timer = setTimeout(() => (ctl.abort(), rej(new Fail(`the source stalled: no answer for ${stallMs} ms`))), stallMs)))
103
+ try {
104
+ return await Promise.race([fetchFn(url, init), stall])
105
+ } finally {
106
+ clearTimeout(timer)
107
+ }
108
+ }
109
+
110
+ // ---- the tar reader ---------------------------------------------------------------------------------------------------------------------
111
+ const field = (h, from, to) => {
112
+ let end = from
113
+ while (end < to && h[end] !== 0) end++
114
+ return new TextDecoder().decode(h.subarray(from, end))
115
+ }
116
+ function parseSize(h) {
117
+ if (h[124] & 0x80) {
118
+ // base-256: only a size that fits 48 bits is read, and anything past the bound is refused by the caller
119
+ let n = 0
120
+ for (let i = 125; i < 136; i++) n = n * 256 + h[i]
121
+ return Number.isSafeInteger(n) ? n : Infinity
122
+ }
123
+ const t = field(h, 124, 136).trim()
124
+ return /^[0-7]+$/.test(t) ? parseInt(t, 8) : NaN
125
+ }
126
+ function checksumOk(h) {
127
+ let sum = 0
128
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i]
129
+ const t = field(h, 148, 156).trim()
130
+ return /^[0-7]+$/.test(t) && parseInt(t, 8) === sum
131
+ }
132
+ const isZero = h => h.every(b => b === 0)
133
+
134
+ /**
135
+ * An incremental tar reader. feed(chunk) gives bytes in; finish() says whether the archive ended properly. `wants`: [{path, sha256, size}]; an entry
136
+ * named `package/<path>` is kept (its size field must be the pinned size), every other entry is skipped without being held. The total of bytes taken
137
+ * in is bounded by `maxUnpacked`.
138
+ */
139
+ function tarReader(wants, maxUnpacked) {
140
+ const want = new Map(wants.map(w => [`package/${w.path}`, w]))
141
+ const found = new Map()
142
+ const seen = new Set()
143
+ let buf = new Uint8Array(0)
144
+ let total = 0
145
+ let state = 'header'
146
+ let ended = false
147
+ let cur = null // {name, want, left, pad, data, at, kind}
148
+ let nextName = null
149
+ const append = chunk => {
150
+ if (!buf.length) buf = chunk
151
+ else {
152
+ const n = new Uint8Array(buf.length + chunk.length)
153
+ n.set(buf)
154
+ n.set(chunk, buf.length)
155
+ buf = n
156
+ }
157
+ }
158
+ const nameOf = (h, override) => {
159
+ if (override) return override
160
+ const n = field(h, 0, 100)
161
+ const p = field(h, 257, 263).startsWith('ustar') ? field(h, 345, 500) : ''
162
+ return p ? `${p}/${n}` : n
163
+ }
164
+ return {
165
+ feed(chunk) {
166
+ total += chunk.length
167
+ if (total > maxUnpacked) throw new Fail(`the archive unpacks to more than the bound of ${maxUnpacked} bytes`)
168
+ if (ended) return
169
+ append(chunk)
170
+ for (;;) {
171
+ if (state === 'header') {
172
+ if (buf.length < 512) return
173
+ const h = buf.subarray(0, 512)
174
+ buf = buf.subarray(512)
175
+ if (isZero(h)) {
176
+ ended = true
177
+ buf = new Uint8Array(0)
178
+ return
179
+ }
180
+ if (!checksumOk(h)) throw new Fail('a tar header has a wrong checksum')
181
+ const size = parseSize(h)
182
+ const type = String.fromCharCode(h[156] || 48)
183
+ if (!Number.isFinite(size) || size < 0 || size > maxUnpacked) throw new Fail(`a tar entry's size field (${size}) is beyond the bound`)
184
+ const padN = (512 - (size % 512)) % 512
185
+ if (type === 'x' || type === 'g' || type === 'L') {
186
+ if (size > PAX_MAX) throw new Fail(`a tar ${type === 'L' ? 'long name' : 'extended header'} is longer than ${PAX_MAX} bytes`)
187
+ cur = { kind: type, left: size, pad: padN, data: new Uint8Array(size), at: 0 }
188
+ } else {
189
+ const name = nameOf(h, nextName)
190
+ nextName = null
191
+ const w = want.get(name)
192
+ if (w) {
193
+ if (seen.has(name)) throw new Fail(`${w.path} is in the archive more than once`)
194
+ seen.add(name)
195
+ if (type !== '0') throw new Fail(`${w.path} is not a regular file in the archive`)
196
+ if (size !== w.size) throw new Fail(`${w.path}: the tar size field is ${size}, not the pinned ${w.size}`)
197
+ cur = { kind: 'want', want: w, left: size, pad: padN, data: new Uint8Array(size), at: 0 }
198
+ } else cur = { kind: 'skip', left: size, pad: padN }
199
+ }
200
+ state = 'data'
201
+ }
202
+ if (state === 'data') {
203
+ const n = Math.min(cur.left, buf.length)
204
+ if (cur.data) cur.data.set(buf.subarray(0, n), cur.at)
205
+ cur.at = (cur.at || 0) + n
206
+ cur.left -= n
207
+ buf = buf.subarray(n)
208
+ if (cur.left > 0) return
209
+ state = 'pad'
210
+ }
211
+ if (state === 'pad') {
212
+ const n = Math.min(cur.pad, buf.length)
213
+ cur.pad -= n
214
+ buf = buf.subarray(n)
215
+ if (cur.pad > 0) return
216
+ if (cur.kind === 'want') found.set(cur.want.path, cur.data)
217
+ else if (cur.kind === 'L') nextName = field(cur.data, 0, cur.data.length)
218
+ else if (cur.kind === 'x') {
219
+ const text = new TextDecoder().decode(cur.data)
220
+ let p = 0
221
+ while (p < text.length) {
222
+ const sp = text.indexOf(' ', p)
223
+ const len = Number(text.slice(p, sp))
224
+ if (!(sp > p) || !(len > 0)) break
225
+ const rec = text.slice(sp + 1, p + len - 1)
226
+ const eq = rec.indexOf('=')
227
+ if (eq > 0 && rec.slice(0, eq) === 'path') nextName = rec.slice(eq + 1)
228
+ p += len
229
+ }
230
+ }
231
+ cur = null
232
+ state = 'header'
233
+ }
234
+ }
235
+ },
236
+ finish() {
237
+ if (!ended) throw new Fail(state === 'header' && !buf.length ? 'the archive ends early (no end marker)' : 'the archive ends early (inside an entry)')
238
+ const missing = wants.filter(w => !found.has(w.path)).map(w => w.path)
239
+ if (missing.length) throw new Fail(`${missing.join(', ')} not in the archive`)
240
+ return found
241
+ },
242
+ }
243
+ }
244
+
245
+ async function fromTgz({ url, files, fetchFn, ctl, stallMs, tarballMax, unpackedMax, late, progress }) {
246
+ if (typeof DecompressionStream !== 'function') throw new Fail('this browser has no DecompressionStream')
247
+ const resp = await fetchHeaders(fetchFn, url, { mode: 'cors', credentials: 'omit', cache: 'no-store', redirect: 'follow', signal: ctl.signal }, stallMs, ctl)
248
+ checkResponse(resp, url)
249
+ const declared = Number(resp.headers && resp.headers.get && resp.headers.get('content-length'))
250
+ if (declared > tarballMax) throw new Fail(`the body is longer than the bound of ${tarballMax} bytes (content-length ${declared})`)
251
+ const reader = tarReader(files, unpackedMax)
252
+ const ds = new DecompressionStream('gzip')
253
+ const writer = ds.writable.getWriter()
254
+ let problem = null
255
+ const note = e => {
256
+ if (!problem) problem = e instanceof Fail ? e : new Fail(`the gzip body is damaged: ${msg(e)}`)
257
+ ctl.abort()
258
+ writer.abort(problem).catch(() => {})
259
+ }
260
+ const out = (async () => {
261
+ const r = ds.readable.getReader()
262
+ try {
263
+ for (;;) {
264
+ const s = await r.read()
265
+ if (s.done) return
266
+ reader.feed(s.value)
267
+ }
268
+ } catch (e) {
269
+ note(e)
270
+ }
271
+ })()
272
+ try {
273
+ await pump(resp, { cap: tarballMax, stallMs, ctl, sink: chunk => writer.write(chunk), progress })
274
+ await writer.close()
275
+ } catch (e) {
276
+ note(e)
277
+ }
278
+ await out
279
+ if (problem) throw problem
280
+ if (late()) throw new Fail('the source did not answer in time')
281
+ try {
282
+ return reader.finish()
283
+ } catch (e) {
284
+ if (e instanceof Fail) throw e
285
+ throw new Fail(msg(e))
286
+ }
287
+ }
288
+
289
+ function checkResponse(resp, url) {
290
+ if (resp.status !== 200) throw new Fail(`HTTP ${resp.status}`)
291
+ if (resp.url && schemeOf(resp.url) !== schemeOf(url)) throw new Fail(`redirected to another scheme (${schemeOf(resp.url)})`)
292
+ if (!resp.body) throw new Fail('no body')
293
+ }
294
+
295
+ async function fromFile({ url, file, fetchFn, ctl, stallMs, progress }) {
296
+ const cap = file.size === undefined ? MAX_PINNED_BYTES : file.size
297
+ const resp = await fetchHeaders(fetchFn, url, { mode: 'cors', credentials: 'omit', cache: 'no-store', redirect: 'follow', signal: ctl.signal }, stallMs, ctl)
298
+ checkResponse(resp, url)
299
+ const declared = Number(resp.headers && resp.headers.get && resp.headers.get('content-length'))
300
+ if (declared > cap) throw new Fail(`the body is longer than the pinned ${cap} bytes (content-length ${declared})`)
301
+ const chunks = []
302
+ const got = await pump(resp, { cap, stallMs, ctl, sink: c => void chunks.push(c), progress }).catch(e => {
303
+ if (e instanceof Fail) throw new Fail(e.message.replace('the bound of', 'the pinned').replace(/ bytes$/, ' bytes'))
304
+ throw e
305
+ })
306
+ if (file.size !== undefined && got !== file.size) throw new Fail(`the body is shorter than the pinned ${file.size} bytes (${got})`)
307
+ const out = new Uint8Array(got)
308
+ let at = 0
309
+ for (const c of chunks) (out.set(c, at), (at += c.byteLength))
310
+ return out
311
+ }
312
+
313
+ const joinUrl = (base, path) => `${String(base).replace(/\/+$/, '')}/${path}`
314
+
315
+ async function fromCache({ cacheStorage, files, cacheKeyOf }) {
316
+ const got = {}
317
+ let cache = null
318
+ try {
319
+ if (!cacheStorage) return got
320
+ cache = await cacheStorage.open(PINNED_CACHE_NAME)
321
+ } catch {
322
+ return got
323
+ }
324
+ for (const f of files) {
325
+ const key = cacheKeyOf(f.sha256)
326
+ try {
327
+ const hit = await cache.match(key)
328
+ if (!hit) continue
329
+ const bytes = await hit.arrayBuffer()
330
+ if ((f.size === undefined || bytes.byteLength === f.size) && (await sha256Of(bytes)) === String(f.sha256).toLowerCase()) got[f.path] = bytes
331
+ else await cache.delete(key) // damaged or not the file it is named for: gone
332
+ } catch {
333
+ try {
334
+ await cache.delete(key)
335
+ } catch {
336
+ // storage that throws is storage that is not there
337
+ }
338
+ }
339
+ }
340
+ return got
341
+ }
342
+
343
+ /**
344
+ * @param {object} o
345
+ * @param {{path: string, sha256: string, size?: number}[]} o.files what is needed; a tar entry is 'package/<path>'
346
+ * @param {{name: string, version: string}|null} [o.pkg] the package the pins name (for the {name} {version} {file} of a source)
347
+ * @param {object[]} o.sources ordered: {kind:'tgz', url} | {kind:'file', base} | {kind:'url', url}
348
+ * @returns {Promise<{files: Object<string, ArrayBuffer>, from: Object<string, string>, source: string, reasons: {source: string, why: string}[]} | {error: string, reasons: {source: string, why: string}[]}>}
349
+ */
350
+ export async function fetchPinned(o) {
351
+ const reasons = []
352
+ try {
353
+ const { files, pkg = null, sources, fetchFn = (...a) => fetch(...a), cacheStorage = globalThis.caches, cacheKeyOf = pinnedCacheKey, timeoutMs = PINNED_TOTAL_MS, stallMs = PINNED_STALL_MS, allMs = PINNED_ALL_MS, onProgress = null, schemes = ['https:', 'http:'] } = o || {}
354
+ if (!Array.isArray(files) || !files.length) return { error: 'no file was asked for', reasons }
355
+ if (!Array.isArray(sources) || !sources.length) return { error: 'no source is named', reasons }
356
+ const have = await fromCache({ cacheStorage, files, cacheKeyOf })
357
+ const from = {}
358
+ for (const p of Object.keys(have)) from[p] = 'cache'
359
+ const missing = files.filter(f => !(f.path in have))
360
+ if (!missing.length) return { files: have, from, source: 'cache', reasons }
361
+ const pinned = files.reduce((n, f) => n + (f.size || 0), 0)
362
+ const began = Date.now()
363
+ let allHit = false
364
+ for (const src of sources) {
365
+ const left = allMs - (Date.now() - began)
366
+ if (left <= 0) {
367
+ allHit = true
368
+ break
369
+ }
370
+ const why = r => (reasons.push({ source: r.source, why: r.why }), null)
371
+ const kind = src && src.kind
372
+ const raw = kind === 'tgz' || kind === 'url' ? src.url : kind === 'file' ? src.base : null
373
+ if (raw === null || typeof raw !== 'string') {
374
+ why({ source: `${kind || 'source'}`, why: 'a source of an unknown kind or with no url' })
375
+ continue
376
+ }
377
+ const text = expand(raw, pkg)
378
+ if (text === null) {
379
+ why({ source: label(raw), why: 'the pins name no package (name and version) for this file, which this source needs' })
380
+ continue
381
+ }
382
+ if (!schemes.includes(schemeOf(text))) {
383
+ why({ source: label(text), why: `not an ${schemes.map(x => x.slice(0, -1)).join('/')} url` })
384
+ continue
385
+ }
386
+ const ctl = new AbortController()
387
+ let isLate = false
388
+ const limit = Math.min(timeoutMs, left)
389
+ const timer = setTimeout(() => ((isLate = true), ctl.abort()), limit)
390
+ const name = `${kind} ${label(text)}`
391
+ try {
392
+ let got = {}
393
+ if (kind === 'tgz') {
394
+ const tarballMax = src.tarballMax ?? o.tarballMax ?? pinned + TAR_OVERHEAD
395
+ const unpackedMax = o.unpackedMax ?? pinned + TAR_OVERHEAD
396
+ if (missing.some(f => !Number.isInteger(f.size))) throw new Fail('a file inside a tarball needs a pinned size')
397
+ const found = await fromTgz({ url: text, files: missing, fetchFn, ctl, stallMs, tarballMax, unpackedMax, late: () => isLate, progress: onProgress })
398
+ for (const [p, b] of found) got[p] = b
399
+ } else {
400
+ for (const f of missing) got[f.path] = await fromFile({ url: kind === 'url' ? text : joinUrl(text, f.path), file: f, fetchFn, ctl, stallMs, progress: onProgress })
401
+ }
402
+ for (const f of missing) {
403
+ const b = got[f.path]
404
+ if (!b) throw new Fail(`${f.path} was not given`)
405
+ const bytes = b instanceof ArrayBuffer ? b : b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)
406
+ const got12 = await sha256Of(bytes)
407
+ if (got12 !== String(f.sha256).toLowerCase()) throw new Fail(`${f.path} does not match its pin (sha256 ${got12.slice(0, 12)}..., pinned ${String(f.sha256).toLowerCase().slice(0, 12)}...)`)
408
+ have[f.path] = bytes
409
+ from[f.path] = name
410
+ }
411
+ try {
412
+ if (cacheStorage) {
413
+ const cache = await cacheStorage.open(PINNED_CACHE_NAME)
414
+ for (const f of missing) await cache.put(cacheKeyOf(f.sha256), new Response(have[f.path], { headers: { 'content-type': 'application/octet-stream' } }))
415
+ }
416
+ } catch {
417
+ // no storage, or no room: the next boot fetches again
418
+ }
419
+ return { files: have, from, source: name, reasons }
420
+ } catch (e) {
421
+ const said = !isLate && !(e instanceof Fail) && typeof o.explain === 'function' ? await o.explain(text, e) : null // fix 10 (F4): the page's policy, when it blocked the source
422
+ const text2 = e instanceof Fail ? e.message : isLate ? `no answer within ${limit} ms` : said || `could not be fetched: ${msg(e)}`
423
+ why({ source: name, why: isLate && !(e instanceof Fail) ? `did not answer within ${limit} ms${limit < timeoutMs ? ' (what is left of the overall bound)' : ''}` : isLate && /stalled|in time/.test(text2) ? text2 : text2 })
424
+ for (const f of missing) delete have[f.path]
425
+ } finally {
426
+ clearTimeout(timer)
427
+ }
428
+ }
429
+ if (Date.now() - began >= allMs) allHit = true
430
+ if (allHit) reasons.push({ source: 'all sources', why: `the overall bound of ${allMs} ms passed${sources.length > reasons.length ? ' (the sources not asked are left out)' : ''}` })
431
+ const one = reasons.map(r => `${r.source}: ${r.why}`).join('; ')
432
+ return { error: reasons.length === 1 ? reasons[0].why : `no source gave the file: ${one}`, reasons }
433
+ } catch (e) {
434
+ return { error: `the pinned files could not be fetched: ${msg(e)}`, reasons }
435
+ }
436
+ }
package/wmdpack.wasm CHANGED
Binary file