@threadedstack/wmd-web 0.1.37 → 0.1.39

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.
@@ -0,0 +1,35 @@
1
+ // Writes src/gowasm/pins-data.js from src/gowasm/pins.json (the one file scripts/gowasm/pins.mjs and the release workflow keep): the pins as a JS module,
2
+ // so that a bundler cannot separate the code from its pins and no request is made for them. `node src/gowasm/make-pins-module.mjs` regenerates it;
3
+ // `--check` exits 1 when the module is not what pins.json would give (a unit test, x6-boot.test.js, says the same). The PACKAGES part below the marker is
4
+ // kept as it is: it names, per Go release, the npm package that holds the twin and is filled in by hand when the package exists.
5
+ import { readFileSync, writeFileSync } from 'node:fs'
6
+
7
+ const here = new URL('.', import.meta.url)
8
+ const MARK = '// ---- the part below is written by hand (make-pins-module.mjs keeps it) ----'
9
+ const pins = JSON.parse(readFileSync(new URL('pins.json', here), 'utf8'))
10
+ const head = `// GENERATED from src/gowasm/pins.json by src/gowasm/make-pins-module.mjs: do not edit above the marker. A unit test (x6-boot.test.js) says the two are equal.
11
+ // The pins of the Go compiler's Wasm twin as a JS module: per Go release the twin's sha256 and size and, per architecture, the sha256 of the guest's own
12
+ // compile with its path in the image. No import: a bundler cannot separate this code from its pins.
13
+ export const PINS = ${JSON.stringify(pins, null, 2)}
14
+
15
+ `
16
+ let tail = `${MARK}
17
+ /**
18
+ * Per Go release (key: the release, like '1.25.14'): the npm package that holds the twin, as {name, version}. A release with no entry has no package: a
19
+ * source that needs one ({name} in its url) is skipped for it with a reason, and a plain base still works. The planned shape:
20
+ * name '@threadedstack/wmd-gowasm', version '<go release>-<revision>', the twin at 'compile-<go release>.wasm' inside it (PINS releases[...].twin.file).
21
+ */
22
+ export const PACKAGES = {}
23
+ `
24
+ let old = ''
25
+ try {
26
+ old = readFileSync(new URL('pins-data.js', here), 'utf8')
27
+ } catch {}
28
+ if (old.includes(MARK)) tail = old.slice(old.indexOf(MARK))
29
+ const out = head + tail
30
+ if (process.argv.includes('--check')) {
31
+ if (old !== out) {
32
+ console.error('pins-data.js is not what pins.json gives')
33
+ process.exit(1)
34
+ }
35
+ } else writeFileSync(new URL('pins-data.js', here), out)
@@ -0,0 +1,162 @@
1
+ // GENERATED from src/gowasm/pins.json by src/gowasm/make-pins-module.mjs: do not edit above the marker. A unit test (x6-boot.test.js) says the two are equal.
2
+ // The pins of the Go compiler's Wasm twin as a JS module: per Go release the twin's sha256 and size and, per architecture, the sha256 of the guest's own
3
+ // compile with its path in the image. No import: a bundler cannot separate this code from its pins.
4
+ export const PINS = {
5
+ "version": 1,
6
+ "release": {
7
+ "repo": "threadedstack/wmd-releases",
8
+ "tag": "gowasm-modules",
9
+ "baseUrl": "https://github.com/threadedstack/wmd-releases/releases/download/gowasm-modules",
10
+ "redirectHosts": [
11
+ "github.com",
12
+ "objects.githubusercontent.com",
13
+ "release-assets.githubusercontent.com"
14
+ ]
15
+ },
16
+ "releases": {
17
+ "1.25.14": {
18
+ "twin": {
19
+ "file": "compile-1.25.14.wasm",
20
+ "sha256": "b758cab40ddb2027f6579e5d15b444b06f75b0e748b9c17c85b15663d2c29d39",
21
+ "size": 41102658
22
+ },
23
+ "notices": {
24
+ "file": "compile-1.25.14.NOTICES.txt",
25
+ "sha256": "9d543a6292351d6172e18d67affeb2fe502111a3bfb560a009acf3e67b466189",
26
+ "size": 4925
27
+ },
28
+ "tools": {
29
+ "8e43c7337f0092969078696e9d291ffbe1646187510324359b29faf15d7a6700": {
30
+ "name": "compile",
31
+ "path": "/usr/local/go/pkg/tool/linux_arm64/compile",
32
+ "arch": "arm64",
33
+ "size": 20271801,
34
+ "goVersion": "1.25.14",
35
+ "check": {
36
+ "passed": true,
37
+ "script": "scripts/gowasm/check-twin.sh",
38
+ "compiles": 94,
39
+ "identical": 94,
40
+ "variant": [],
41
+ "referenceVsGuest": null
42
+ }
43
+ },
44
+ "7c4c460753bc9cff43a87858b9510fbc82daeeb05ddf8afd6c4518b6dc6d5497": {
45
+ "name": "compile",
46
+ "path": "/usr/local/go/pkg/tool/linux_amd64/compile",
47
+ "arch": "amd64",
48
+ "size": 21654239,
49
+ "goVersion": "1.25.14",
50
+ "check": {
51
+ "passed": true,
52
+ "script": "scripts/gowasm/check-twin.sh",
53
+ "compiles": 94,
54
+ "identical": 94,
55
+ "variant": [],
56
+ "referenceVsGuest": null
57
+ }
58
+ }
59
+ }
60
+ },
61
+ "1.26.11": {
62
+ "twin": {
63
+ "file": "compile-1.26.11.wasm",
64
+ "sha256": "50a941beef8a134a2d24091afb272c0d68efc600da68b79109fd6b32b5e8054e",
65
+ "size": 48090349
66
+ },
67
+ "notices": {
68
+ "file": "compile-1.26.11.NOTICES.txt",
69
+ "sha256": "bc1b393922fe1555772d5fe70f17ea96f2ccb7386544444696a0c1982b9ec80b",
70
+ "size": 4925
71
+ },
72
+ "tools": {
73
+ "fcd8ab38428db95acaa3e732570798c354ccbf8521394396acc29549c3e69d68": {
74
+ "name": "compile",
75
+ "path": "/usr/local/go/pkg/tool/linux_arm64/compile",
76
+ "arch": "arm64",
77
+ "size": 24254837,
78
+ "goVersion": "1.26.11",
79
+ "check": {
80
+ "passed": true,
81
+ "script": "scripts/gowasm/check-twin.sh",
82
+ "compiles": 96,
83
+ "identical": 96,
84
+ "variant": [],
85
+ "referenceVsGuest": null
86
+ }
87
+ },
88
+ "896a17923b901c9581505c08e8ed1c5a2a6b1b519beb457ceb106f1b59373329": {
89
+ "name": "compile",
90
+ "path": "/usr/local/go/pkg/tool/linux_amd64/compile",
91
+ "arch": "amd64",
92
+ "size": 25787792,
93
+ "goVersion": "1.26.11",
94
+ "check": {
95
+ "passed": true,
96
+ "script": "scripts/gowasm/check-twin.sh",
97
+ "compiles": 96,
98
+ "identical": 96,
99
+ "variant": [],
100
+ "referenceVsGuest": null
101
+ }
102
+ }
103
+ }
104
+ },
105
+ "1.27.4": {
106
+ "twin": {
107
+ "file": "compile-1.27.4.wasm",
108
+ "sha256": "4d623c4a04c2b4e115106f18c0ad0b8d0a4c797940d9edd94ec5a79e92b610ca",
109
+ "size": 52519098
110
+ },
111
+ "notices": {
112
+ "file": "compile-1.27.4.NOTICES.txt",
113
+ "sha256": "a02e47842837f5c99a0f07a6ca96e7dcaee4c67433a20a60b610d6da865bd600",
114
+ "size": 4919
115
+ },
116
+ "tools": {
117
+ "4070e0e743ba23672219a3687a1f9bfb489fa5c95bfb6584b4f33932339f92ef": {
118
+ "name": "compile",
119
+ "path": "/usr/local/go/pkg/tool/linux_arm64/compile",
120
+ "arch": "arm64",
121
+ "size": 26606430,
122
+ "goVersion": "1.27.4",
123
+ "check": {
124
+ "passed": true,
125
+ "script": "scripts/gowasm/check-twin.sh",
126
+ "compiles": 95,
127
+ "identical": 95,
128
+ "variant": [],
129
+ "referenceVsGuest": null
130
+ }
131
+ },
132
+ "40307e5f5c65a4b4220bbf35dbe014348780589ea2964003f0bf318fa14640e1": {
133
+ "name": "compile",
134
+ "path": "/usr/local/go/pkg/tool/linux_amd64/compile",
135
+ "arch": "amd64",
136
+ "size": 28272322,
137
+ "goVersion": "1.27.4",
138
+ "check": {
139
+ "passed": true,
140
+ "script": "scripts/gowasm/check-twin.sh",
141
+ "compiles": 95,
142
+ "identical": 95,
143
+ "variant": [],
144
+ "referenceVsGuest": null
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ // ---- the part below is written by hand (make-pins-module.mjs keeps it) ----
153
+ /**
154
+ * Per Go release (key: the release, like '1.25.14'): the npm package that holds the twin, as {name, version}. A release with no entry has no package: a
155
+ * source that needs one ({name} in its url) is skipped for it with a reason, and a plain base still works. The planned shape:
156
+ * name '@threadedstack/wmd-gowasm', version '<go release>-<revision>', the twin at 'compile-<go release>.wasm' inside it (PINS releases[...].twin.file).
157
+ */
158
+ export const PACKAGES = {
159
+ '1.25.14': { name: '@threadedstack/wmd-gowasm', version: '1.25.14-1' },
160
+ '1.26.11': { name: '@threadedstack/wmd-gowasm', version: '1.26.11-1' },
161
+ '1.27.4': { name: '@threadedstack/wmd-gowasm', version: '1.27.4-1' },
162
+ }
@@ -0,0 +1,164 @@
1
+ // X6 default part 2, item H, and part 3: the Go compiler's Wasm twin for a page that embeds the package. bootWmd does the whole setup alone
2
+ // (src/gowasm/boot-setup.js, twinForBoot, which uses planOf below); an embedder writes no twin line. This module is also the entry of the test page
3
+ // (page/ckpt.js, gowasmSetup) and holds what both share:
4
+ // planOf({ sources, pins, packages, limits }) the table made in memory from the pins (src/gowasm/pins-data.js, a JS module: no request) and the
5
+ // ordered sources (src/host/pinned-fetch.js: tgz of the npm registry, file under a base, url)
6
+ // tableFromPins(pins, packages, sources) the table
7
+ // GOWASM_SOURCES_DEFAULT ONE constant: the sources used when the embedder names none. null for now: with none, the twin is off
8
+ // The twin's module is fetched by the twin's Worker on first use from the first source that gives the pinned sha256, and kept in Cache Storage.
9
+ // `gowasmSetup({ table: '/own/tools.json' })` is the override that reads a table an app serves itself, with its own modules.
10
+ // The module imports the table's guard and the pins alone, none of the twin's machine code (edge-go.js, its error texts, yamux): the twin's code is
11
+ // loaded by the channel service's Worker, only for a machine that got a `gowasm` service field. It never throws into its caller.
12
+ import { loadToolsTable, normalizeTable, toolsTableProblem } from '../host/gowasm-guard.js'
13
+ import { PACKAGES, PINS } from './pins-data.js'
14
+
15
+ /**
16
+ * The sources the twin's modules are fetched from when the embedder names none: ONE constant. `null` for now (the public package does not exist yet): with no
17
+ * sources and no table the twin is off, silently for a boot that named nothing. The flip sets it to the ordered list, the npm registry first:
18
+ * [{ kind: 'tgz', url: 'https://registry.npmjs.org/{name}/-/{file}-{version}.tgz' }, { kind: 'file', base: 'https://cdn.jsdelivr.net/npm/{name}@{version}' },
19
+ * { kind: 'file', base: 'https://unpkg.com/{name}@{version}' }]. Only the pins (pins-data.js PACKAGES) say which package and version.
20
+ */
21
+ export const GOWASM_SOURCES_DEFAULT = null
22
+
23
+ /** Why a list of sources cannot be used, or null. A list is [{kind: 'tgz', url} | {kind: 'file', base} | {kind: 'url', url}]; https and http only. */
24
+ export function sourcesProblem(sources) {
25
+ if (!Array.isArray(sources) || !sources.length) return 'the list of sources is empty or is not a list'
26
+ for (const x of sources) {
27
+ const text = x && x.kind === 'file' ? x.base : x && (x.kind === 'tgz' || x.kind === 'url') ? x.url : undefined
28
+ if (typeof text !== 'string' || !text) return `a source is not {kind: 'tgz'|'url', url} or {kind: 'file', base}: ${JSON.stringify(x)?.slice(0, 80)}`
29
+ if (!/^https?:\/\//i.test(text)) return `a source is not an http(s) url: ${text.slice(0, 80)}`
30
+ }
31
+ return null
32
+ }
33
+
34
+ /**
35
+ * The table the page used to read from tools.json, made in memory from the pins: the guest compile's sha256 (the key) -> its name, path and architecture,
36
+ * and the twin of its release: its file name, sha256 and size (the size bounds the fetch) and, when `packages` names one for the release, the npm package
37
+ * that holds it ({name, version}). `sources` is the ordered list the Worker tries (src/host/pinned-fetch.js).
38
+ */
39
+ export function tableFromPins(pins, packages, sources) {
40
+ const tools = {}
41
+ for (const [ver, rel] of Object.entries(pins.releases)) {
42
+ const pkg = packages && packages[ver] ? { name: packages[ver].name, version: packages[ver].version } : undefined
43
+ for (const [sha, t] of Object.entries(rel.tools)) {
44
+ tools[sha] = { name: t.name, path: t.path, arch: t.arch, goVersion: t.goVersion, wasmUrl: rel.twin.file, wasmPath: rel.twin.file, wasmSha256: rel.twin.sha256, wasmSize: rel.twin.size, ...(pkg ? { wasmPkg: pkg } : {}) }
45
+ }
46
+ }
47
+ return { tools, sources }
48
+ }
49
+
50
+ /** The pins are the pins of the twin: releases, each with a twin file and its tools. */
51
+ const pinsProblem = p => {
52
+ const rels = p && typeof p === 'object' && p.releases && typeof p.releases === 'object' ? Object.values(p.releases) : []
53
+ if (!rels.length || !rels.every(x => x && x.twin && typeof x.twin.file === 'string' && /^[0-9a-f]{64}$/i.test(String(x.twin.sha256)) && x.tools && typeof x.tools === 'object')) return 'the pins have no releases of the twin'
54
+ return null
55
+ }
56
+
57
+ /**
58
+ * The plan from the pins and a list of sources, with no request: {table, edge, service(mounts)} or {why}.
59
+ * @param {{sources: object[], pins?: object, packages?: object, limits?: object}} o
60
+ */
61
+ export function planOf({ sources, pins = PINS, packages = PACKAGES, limits = {} }) {
62
+ const bad = sourcesProblem(sources)
63
+ if (bad) return { why: bad }
64
+ const pb = pinsProblem(pins)
65
+ if (pb) return { why: pb }
66
+ const table = tableFromPins(pins, packages, sources.map(x => ({ ...x })))
67
+ const tb = toolsTableProblem(table)
68
+ if (tb) return { why: `the table made from the pins ${tb}` }
69
+ return { table, edge: gowasmEdgeOf(table), service: mounts => gowasmServiceOf(table, limits, mounts) }
70
+ }
71
+
72
+ /** The time limit of the table's fetch when `limits.readyLimitMs` is not given: the machine's ready limit (READY_LIMIT_MS of src/host/edge-go.js, tested to be equal). */
73
+ export const TABLE_LIMIT_MS = 60_000
74
+
75
+ /** The limits an embedder may name (0 or absent: the twin's own default; the two flags off). */
76
+ export const GOWASM_LIMITS = { beatLimitMs: 0, readyLimitMs: 0, runLimitMs: 0, earlyReply: false, lateFallbackAt: 0 }
77
+
78
+ const defaultFetchJson = async (u, signal) => {
79
+ const r = await fetch(u, { cache: 'no-store', signal })
80
+ if (!r.ok) throw new Error(`GET ${u}: ${r.status}`)
81
+ return r.json()
82
+ }
83
+
84
+ /**
85
+ * The `gowasm` field of the 9P service (bootWmd channels.services[]): the table, the limits, and the destinations of every mount of the bundle.
86
+ * Each limit goes on under the name the GoEdge constructor takes (src/host/chan-service.js), 0 meaning its default.
87
+ */
88
+ export function gowasmServiceOf(table, limits, mounts) {
89
+ // one module for every tool (wasmUrl, wasmSha256 at the top) goes on as it always did; a module per tool goes on as a list of
90
+ // modules, the ones to load at start, and the tools with their own module (src/host/gowasm-guard.js normalizeTable)
91
+ const n = normalizeTable(table)
92
+ const l = { ...GOWASM_LIMITS, ...limits }
93
+ return {
94
+ ...(n.legacy ? { wasmUrl: table.wasmUrl, wasmSha256: table.wasmSha256 } : { modules: n.modules, preload: n.preload }),
95
+ beatLimitMs: Number(l.beatLimitMs) | 0,
96
+ readyLimitMs: Number(l.readyLimitMs) | 0,
97
+ runLimitMs: Number(l.runLimitMs) | 0,
98
+ tools: n.tools,
99
+ ...(table.sources ? { sources: table.sources } : {}),
100
+ cacheBytes: table.cacheBytes,
101
+ maxReruns: table.maxReruns,
102
+ earlyReply: l.earlyReply === true,
103
+ lateFallbackAt: Number(l.lateFallbackAt) | 0,
104
+ mounts,
105
+ }
106
+ }
107
+
108
+ /** The `edge` option of containerBundle: the stub stands in the container for each of the table's tools (one pair per place in the image). */
109
+ export const gowasmEdgeOf = table => {
110
+ const seen = new Set()
111
+ const tools = Object.values(table.tools).filter(t => {
112
+ const k = `${t.name} ${t.path}`
113
+ if (seen.has(k)) return false
114
+ seen.add(k)
115
+ return true
116
+ })
117
+ // sorted: the spec text (and so a checkpoint's boot key) follows the tools, not the order the pins list them in or which releases are pinned
118
+ tools.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
119
+ return { tools }
120
+ }
121
+
122
+ /**
123
+ * The entry of the test page (and of a caller that wants the plan itself).
124
+ * @param {object} o
125
+ * @param {string} [o.table] the url of a table (tools.json) the embedder serves itself, with the twin's modules: the override
126
+ * @param {object[]} [o.sources] the ordered sources (default GOWASM_SOURCES_DEFAULT); `base` is one file source
127
+ * @param {string} [o.base] one file source: <base>/<file>
128
+ * @param {boolean} [o.gowasm] false: off, asks for nothing
129
+ * @param {object} [o.limits] beatLimitMs, readyLimitMs (also the table's time limit, default 60000), runLimitMs, earlyReply, lateFallbackAt
130
+ * @param {function} [o.fetchJson] (url, signal) -> parsed JSON, for the table override only
131
+ * @param {function} [o.onEvent] ({t: 'gowasm-off', why, machine}) once, for a plan that is off for a reason the user should see
132
+ * @param {number} [o.machine] the machine's count, copied into the event
133
+ * @returns {Promise<{use: boolean, reason: string, edge: object|undefined, service: function|undefined, table: object|null}>}
134
+ */
135
+ export async function gowasmSetup(o = {}) {
136
+ const { table: url, base, sources: given, gowasm, limits = {}, fetchJson = defaultFetchJson, onEvent = () => {}, machine = 0, pins, packages } = o || {}
137
+ const off = (reason, say) => {
138
+ if (say) {
139
+ try {
140
+ onEvent({ t: 'gowasm-off', why: reason, machine })
141
+ } catch {
142
+ // a handler of the embedder must not decide the plan
143
+ }
144
+ }
145
+ return { use: false, reason, edge: undefined, service: undefined, table: null }
146
+ }
147
+ try {
148
+ if (gowasm === false) return off('the twin is switched off (gowasm: false)', false)
149
+ const sources = given ?? (base ? [{ kind: 'file', base }] : GOWASM_SOURCES_DEFAULT)
150
+ if (!url && !sources) return off('no table is stated: no table url and no sources were given, so none is asked for', true)
151
+ if (url) {
152
+ const r = await loadToolsTable({ fetchJson, url, limitMs: Number(limits.readyLimitMs) || TABLE_LIMIT_MS })
153
+ if (!r.table) return off(r.why, true)
154
+ const edge = gowasmEdgeOf(r.table)
155
+ gowasmServiceOf(r.table, limits, []) // a table that cannot be turned into a service field is found now, not at the boot
156
+ return { use: true, reason: '', edge, service: mounts => gowasmServiceOf(r.table, limits, mounts), table: r.table }
157
+ }
158
+ const plan = planOf({ sources, pins, packages, limits })
159
+ if (plan.why) return off(`the twin's setup is not usable: ${plan.why}`, true)
160
+ return { use: true, reason: '', edge: plan.edge, service: plan.service, table: plan.table }
161
+ } catch (e) {
162
+ return off(`the twin's setup failed: ${(e && e.message) || e}`, true)
163
+ }
164
+ }
@@ -0,0 +1,27 @@
1
+ // X6 default part 2, item H, now a thin user of src/host/pinned-fetch.js (part 3, item 2): one module at one url, the shape the first design had.
2
+ // fetchTwin never throws and never waits without a limit: {bytes, from: 'cache' | 'network'} or {error}. Kept for its tests and for a table that
3
+ // names a module by a url; the twin's Worker calls fetchPinned itself with the sources the pins give.
4
+ import { fetchPinned, MAX_PINNED_BYTES, PINNED_CACHE_NAME, PINNED_STALL_MS, PINNED_TOTAL_MS, pinnedCacheKey } from '../host/pinned-fetch.js'
5
+
6
+ export const TWIN_CACHE_NAME = PINNED_CACHE_NAME
7
+ /** The most a twin without a pinned size may be (the three pinned ones are about 41 to 53 MB). */
8
+ export const MAX_TWIN_BYTES = MAX_PINNED_BYTES
9
+ export const TWIN_TOTAL_MS = PINNED_TOTAL_MS
10
+ export const TWIN_STALL_MS = PINNED_STALL_MS
11
+ /** The Cache Storage key of a module: a url of the page's own origin that holds the sha256 (never fetched). */
12
+ export const twinCacheKey = pinnedCacheKey
13
+
14
+ /**
15
+ * @param {object} o
16
+ * @param {string} o.url the module's url (http or https; relative to the page is not accepted)
17
+ * @param {string} o.sha256 the pinned hash (64 hex digits)
18
+ * @param {number} [o.size] the pinned size in bytes
19
+ * @param {string[]} [o.schemes] the url schemes accepted (default https and http)
20
+ * @returns {Promise<{bytes: ArrayBuffer, from: string} | {error: string}>}
21
+ */
22
+ export async function fetchTwin(o) {
23
+ const { url, sha256, size, ...rest } = o || {}
24
+ const r = await fetchPinned({ ...rest, cacheKeyOf: rest.cacheKeyOf || twinCacheKey, files: [{ path: 'twin', sha256, size }], sources: [{ kind: 'url', url }] })
25
+ if (r.error) return { error: r.error }
26
+ return { bytes: r.files.twin, from: r.from.twin === 'cache' ? 'cache' : 'network' }
27
+ }
@@ -44,11 +44,15 @@
44
44
 
45
45
  import { H_DOORBELL, H_SVC, SVC_RUNNING, markServiceDead } from './chan.js'
46
46
  import { ChanHost } from './chan-services.js'
47
- import { EDGE_CONTAINER_DIR, EDGE_STUB } from './ctl.js'
48
47
  import { Pack, bytesSource } from '../fs/pack.js'
49
48
  import { Overlay } from '../fs/overlay.js'
50
49
  import { seedEntry } from '../fs/seed.js'
51
50
  import { exportUpper } from '../fs/upper-pack.js'
51
+ // The stub's two places, as in ctl.js (EDGE_CONTAINER_DIR, EDGE_STUB, which internal/engine/edge.go also names). Not imported: a Worker fetches each of
52
+ // its modules itself, and ctl.js (a large module the page has already) was one request more than a page without the twin made (X6 default part 2,
53
+ // item E; check 7's F4). web/test/unit/x6-def2.test.js says that these two are ctl.js's.
54
+ const EDGE_CONTAINER_DIR = '/dev/.wmd-edge'
55
+ const EDGE_STUB = '/sbin/wmd-edgestub'
52
56
  // X5 (edge=1 only): the edge modules are loaded by init() when the machine has `edge`, and by nothing else (check5 F8)
53
57
  let EdgePorts, EdgeService, EdgeHost, checkpointRefusal
54
58
 
@@ -292,6 +296,12 @@ async function init(m) {
292
296
  }
293
297
  // X6 (default off): the compiler hand-off, for the 9P service that has a gowasm table
294
298
  const goSvc = m.gowasmPort ? (m.services || []).find(s => s.gowasm && fs[s.port]) : null
299
+ // X6 part 3: a service that has a twin table and no twin Worker (the page could not start it): its stub mounts must not reach the guest
300
+ if (!m.gowasmPort) for (const s of m.services || []) if (s.gowasm && !s.gowasm.off && fs[s.port]) noTwin(fs[s.port], s.gowasm.tools, `no twin Worker: ${m.gowasmWhy || 'the page started none'}`)
301
+ // X6 default part 6: a machine restored from a checkpoint taken with the twin, in a boot that has the twin off (gowasm.off holds the reason, the page started no
302
+ // Worker): the stub mounts STAY (the guest's memory has them), a GoEdge is built that is off from the start, and it answers each stub with the fallback by the
303
+ // same guard (edge-go.js #serve) as a twin that went off during the machine's life. No prune, no port, nothing of the twin is fetched.
304
+ const offSvc = !m.gowasmPort ? (m.services || []).find(s => s.gowasm && s.gowasm.off && fs[s.port]) : null
295
305
  let goMod = null
296
306
  if (goSvc) {
297
307
  // X6 fix 4, item 6: loaded only for a machine with the switch on (a page without gowasm=1 asks for none of the twin's modules)
@@ -320,8 +330,22 @@ async function init(m) {
320
330
  mounts: goSvc.gowasm.mounts || null,
321
331
  })
322
332
  goEdge.pruneBundle() // an image with no Go compile: its stub mounts go out of the bundle before the guest starts the container
333
+ await goEdge.pruneUnpinned() // a Go release the pins do not name: its stubs go out too (the guest runs it alone), one calm event
323
334
  bindGoPort(m.gowasmPort)
324
335
  }
336
+ if (offSvc) {
337
+ twinOffWhy = offSvc.gowasm.off // the stats carry it as gowasmOff, as for noTwin
338
+ const loaded = await loadWithin(async () => await import('./edge-go.js'), offSvc.gowasm.readyLimitMs || IMPORT_LIMIT_MS, './edge-go.js')
339
+ if (loaded.mod) {
340
+ goEdge = new loaded.mod.GoEdge({ fs: fs[offSvc.port], root: offSvc.at || '', tools: offSvc.gowasm.tools, post: () => {}, onRecord: rec => self.postMessage({ t: 'gowasm', rec }), mounts: offSvc.gowasm.mounts || null, off: offSvc.gowasm.off })
341
+ // fix 10 (F1): the stub mounts of a tool the image does not hold go out of the spec before the guest reads it, as in the on branch: a cold machine of an image
342
+ // without Go (a base snapshot that was refused after its header) must not get a bind whose source is missing. A machine that really restored has the checkpoint's own tree
343
+ // (its spec was pruned the same way when it was taken), so this changes nothing there. pruneUnpinned (a hash of each tool) is not needed to start: a stub of an unpinned tool
344
+ // is answered with the fallback by the off GoEdge.
345
+ goEdge.pruneBundle()
346
+ }
347
+ // edge-go.js not loadable: no host for the stub, which then runs its own compile (the state of any restore without a twin before this part)
348
+ }
325
349
  host = new ChanHost(sab, { fs, consoleInputBytes: m.consoleInputBytes, yamuxPorts, netPost, restore, edge: goEdge, edgeAccept })
326
350
  if (m.lockName && self.navigator?.locks?.request) {
327
351
  self.navigator.locks.request(m.lockName, () => {
package/src/host/ckpt.js CHANGED
@@ -90,6 +90,58 @@ export async function bootKeyOf({ vmKey, argv, env, preopen, files, services, ma
90
90
  return { key: await sha256Hex(new TextEncoder().encode(JSON.stringify(desc))), desc }
91
91
  }
92
92
 
93
+ /**
94
+ * X24 default (#70): a boot description (bootKeyOf's desc) with another RAM layout: the environment entry WMD_RAM_FLAT=1 (kept last, where
95
+ * bootWmd puts it) present or not, and the memory maximum. Nothing else changes.
96
+ */
97
+ export function bootDescForLayout(desc, { flat, maxPages }) {
98
+ const env = (desc.env || []).filter(e => e !== 'WMD_RAM_FLAT=1')
99
+ if (flat) env.push('WMD_RAM_FLAT=1')
100
+ return { ...desc, env, maxPages }
101
+ }
102
+
103
+ /** X24 default: the key and description of the boot that bootDesc describes, in another RAM layout (no file or pack is read again). */
104
+ export async function bootKeyForLayout(desc, layout) {
105
+ const d = bootDescForLayout(desc, layout)
106
+ return { key: await sha256Hex(new TextEncoder().encode(JSON.stringify(d))), desc: d }
107
+ }
108
+
109
+ /**
110
+ * X6 default part 4: which of these texts of one file did the checkpoint's boot have? `texts` is {name: text} (text: a string or bytes) for the file `path`
111
+ * of service number `index` (the 9P service whose port is `port`); the answer is the name whose sample key (the one bootKeyOf records) is the key the
112
+ * header's boot description holds for that file, or null: no description (a checkpoint from before bootDesc existed), no such service or port, no such
113
+ * file, or a text that is none of them. It is the only thing read of the header: a feature that adds mounts to the container's spec (the Go twin, the
114
+ * node edge of X5) makes the spec text in each variant it can run in and asks this which one the checkpoint had; the checks of the restore (the whole key,
115
+ * the packs) stay as they are. Two names with the same text answer the first.
116
+ */
117
+ export async function specChoice(h, index, port, path, texts) {
118
+ const s = h && typeof h === 'object' && h.bootDesc && typeof h.bootDesc === 'object' && Array.isArray(h.bootDesc.services) ? h.bootDesc.services[index] : null
119
+ const rec = s && typeof s === 'object' && s.port === port && s.bundle && typeof s.bundle === 'object' ? s.bundle[path] : null
120
+ if (typeof rec !== 'string' || !texts || typeof texts !== 'object') return null
121
+ for (const [name, text] of Object.entries(texts)) {
122
+ if (typeof text !== 'string' && !(text instanceof Uint8Array)) continue
123
+ if ((await sampleKey(typeof text === 'string' ? new TextEncoder().encode(text) : text)) === rec) return name
124
+ }
125
+ return null
126
+ }
127
+
128
+ /**
129
+ * X6 default part 4: the key and description of the boot that `desc` describes with other texts of some services' files: `keys` is {serviceIndex:
130
+ * {path: sampleKey}} or, for the Go twin's one file, {serviceIndex: sampleKey of bundle/config/config.json}; the RAM layout is bootKeyForLayout's. No file
131
+ * is read again (a restore that keeps its boot files, and the preflight of vm.restore()).
132
+ */
133
+ export async function bootKeyForChoice(desc, layout, keys) {
134
+ const base = bootDescForLayout(desc, layout)
135
+ const services = (base.services || []).map((s, i) => {
136
+ const k = keys && keys[i]
137
+ if (k === undefined || k === null) return s
138
+ const set = typeof k === 'string' ? { 'bundle/config/config.json': k } : k
139
+ return { ...s, bundle: { ...s.bundle, ...set } }
140
+ })
141
+ const d = { ...base, services }
142
+ return { key: await sha256Hex(new TextEncoder().encode(JSON.stringify(d))), desc: d }
143
+ }
144
+
93
145
  /** The ports a resume writes for the guest (vm_resume_args), from the command line. */
94
146
  export function resumePorts(args) {
95
147
  const get = name => {
@@ -304,6 +356,41 @@ export function bootDescLayoutOnly(a, b) {
304
356
  return JSON.stringify(a) !== JSON.stringify(b) && rest(a) === rest(b)
305
357
  }
306
358
 
359
+ // a boot description as bootKeyOf writes it is 5 levels deep (desc, services, a service, its bundle, a key's value)
360
+ const DESC_MAX_DEPTH = 32
361
+ /** Whether `v` holds an object nested `max` levels or more below it (walked without recursion: the input is untrusted). */
362
+ function deeperThan(v, max) {
363
+ const todo = [[v, 0]]
364
+ while (todo.length) {
365
+ const [x, depth] = todo.pop()
366
+ if (!x || typeof x !== 'object') continue
367
+ if (depth >= max) return true
368
+ for (const k of Object.keys(x)) todo.push([x[k], depth + 1])
369
+ }
370
+ return false
371
+ }
372
+
373
+ /**
374
+ * Fix 10 (F2): whether a boot description that a header carries is not the shape bootKeyOf writes: not a plain object, `services` not a list, a service that is
375
+ * not a plain object or whose `bundle` is not one, or objects nested deeper than any boot writes. A missing description (a checkpoint from before bootDesc existed) is not damaged, it is old.
376
+ */
377
+ export function bootDescDamaged(d) {
378
+ if (d === undefined) return false
379
+ if (!d || typeof d !== 'object' || Array.isArray(d)) return true
380
+ if (!Array.isArray(d.services)) return true
381
+ if (deeperThan(d, DESC_MAX_DEPTH)) return true // (the comparisons below walk it by recursion: a header nested without end must not reach them)
382
+ return d.services.some(s => !s || typeof s !== 'object' || Array.isArray(s) || (s.bundle !== undefined && (!s.bundle || typeof s.bundle !== 'object' || Array.isArray(s.bundle))))
383
+ }
384
+
385
+ /** X6 part 4: whether two boot descriptions differ only in a service's bundle/config/config.json key (the container's spec text). */
386
+ export function bootDescSpecOnly(a, b) {
387
+ if (bootDescDamaged(a) || bootDescDamaged(b)) return false
388
+ if (!a || !b || typeof a !== 'object' || typeof b !== 'object' || !Array.isArray(a.services) || a.services.length !== (b.services || []).length) return false
389
+ // a header is untrusted: a service that is not an object, or whose bundle is not one, is kept as it is (the two then differ and the answer is false)
390
+ const strip = d => JSON.stringify({ ...d, services: d.services.map(s => (s && typeof s === 'object' && !Array.isArray(s) ? { ...s, bundle: { ...(s.bundle && typeof s.bundle === 'object' ? s.bundle : {}), 'bundle/config/config.json': 0 } } : s)) })
391
+ return JSON.stringify(a) !== JSON.stringify(b) && strip(a) === strip(b)
392
+ }
393
+
307
394
  /** The part of the fit check that needs only vm.wasm's key: a snapshot from another vm.wasm is refused before anything else is read of it. */
308
395
  export function checkVmKeyFits(h, vmKey) {
309
396
  if (h.format !== FORMAT_VERSION) throw new CheckpointError('version', `checkpoint format ${h.format}; this build restores format ${FORMAT_VERSION}`)
@@ -318,11 +405,18 @@ export function checkCheckpointFits(h, { vmKey, bootKey, bootDesc, maxPages, ram
318
405
  throw new CheckpointError('stale', `this checkpoint was taken with a different vm.wasm (${String(h.vmKey).slice(0, 12)}, this boot has ${String(vmKey).slice(0, 12)}): its memory image is the old emulator's and cannot be restored; take a new one`)
319
406
  }
320
407
  if (h.bootKey !== bootKey) {
408
+ // a header is untrusted input: a boot description of another shape than bootKeyOf writes is a damaged header, said as such (and read no further)
409
+ if (bootDescDamaged(h.bootDesc)) throw new CheckpointError('stale', "this checkpoint's header holds a damaged boot description (not the shape a boot writes), so it cannot be the one this boot made: take a new checkpoint")
321
410
  const diff = bootDescDiff(h.bootDesc, bootDesc)
322
411
  // X24: only the RAM layout differs (memory 0 or a memory of its own, or the memory maximum): say so, not "a different kernel ..."
323
412
  if (diff && bootDescLayoutOnly(h.bootDesc, bootDesc)) {
324
413
  throw new CheckpointError('stale', `this checkpoint was taken with a different RAM layout than this boot (the guest's RAM in memory 0 or in a memory of its own, or another memory maximum); restore it only with the same layout: the same ramInMemory0, flatRam and allowLargeRam settings as when it was taken (differs: ${diff})`)
325
414
  }
415
+ // the container's spec text (bundle/config/config.json) is the only difference: say what is known, and nothing about why (a changed command or environment, a
416
+ // volume, or a boot that adds or leaves out stub mounts of a helper: this function cannot tell which)
417
+ if (diff && bootDescSpecOnly(h.bootDesc, bootDesc)) {
418
+ throw new CheckpointError('stale', "this checkpoint was taken with a different container spec than this boot has (bundle/config/config.json is not the one the checkpoint was taken with, and nothing else differs): restore it only with the same spec, or take a new checkpoint")
419
+ }
326
420
  throw new CheckpointError('stale', `this checkpoint was taken by a boot with a different kernel, initramfs, command line, environment, image layers or bundle files than this one; restore it only into the same configuration${diff ? ` (differs: ${diff})` : ''}`)
327
421
  }
328
422
  if (h.memPages > maxPages) throw new CheckpointError('stale', `this checkpoint's memory is ${h.memPages} pages and this boot's maximum is ${maxPages}`)
@@ -0,0 +1,64 @@
1
+ // X6 fix 10 (F4): the reason of a source that the page's Content-Security-Policy blocked. A blocked fetch rejects with the same TypeError ("Failed to fetch")
2
+ // as a dead network, so the text says nothing; the browser tells the policy's side through a `securitypolicyviolation` event. cspWatch listens for it in the
3
+ // scope that fetches (the Worker's global scope; the page's document forwards its own events with add(), for a browser that fires it there) and explains a
4
+ // source that threw: the policy blocked it, which directive, which origin to add, or that the app can name a source of its own. It changes no event type.
5
+
6
+ const MAX = 32
7
+ // the directives that govern a fetch (connect-src; default-src where an engine names the fallback it applied)
8
+ const FETCH_DIRECTIVES = new Set(['connect-src', 'default-src'])
9
+ // the event is queued as a task by the browser: it may arrive after the fetch has rejected, so a network error waits for it up to this long (a dead network pays it once per source)
10
+ const EVENT_WAIT_MS = 40
11
+
12
+ /**
13
+ * @param {{addEventListener: Function}|null} scope where the violations fire (self in a Worker); null: none is listened for
14
+ * @param {{origin?: string}} [o] the scope's own origin (a source of it is never a policy block)
15
+ */
16
+ export function cspWatch(scope, o = {}) {
17
+ const seen = []
18
+ const own = o.origin ?? (typeof self !== 'undefined' && self.location && self.location.origin) ?? ''
19
+ const add = e => {
20
+ if (!e || typeof e !== 'object' || typeof e.blockedURI !== 'string' || e.disposition === 'report') return
21
+ // only what governs a fetch: the app's own violations of other directives (an image, a script of the same origin) say nothing about a source's request,
22
+ // and they do not push a source's violation out of the list
23
+ const directive = String(e.effectiveDirective || e.violatedDirective || 'connect-src').split(' ')[0]
24
+ if (!FETCH_DIRECTIVES.has(directive)) return
25
+ if (seen.length >= MAX) seen.shift()
26
+ seen.push({ blocked: e.blockedURI, directive })
27
+ }
28
+ try {
29
+ scope?.addEventListener?.('securitypolicyviolation', add)
30
+ } catch {
31
+ // a scope that cannot be listened to: only the plain hint is left
32
+ }
33
+ const originOf = u => {
34
+ try {
35
+ const x = new URL(u)
36
+ return x.origin === 'null' ? '' : x.origin
37
+ } catch {
38
+ return ''
39
+ }
40
+ }
41
+ return {
42
+ add,
43
+ count: () => seen.length,
44
+ /** The reason text for a source (`url`) whose fetch threw `err`, or null when this says nothing more than the error does. */
45
+ async explain(url, err) {
46
+ const origin = originOf(url)
47
+ const find = () => origin && seen.find(v => v.blocked === url || originOf(v.blocked) === origin)
48
+ let hit = find()
49
+ if (!hit && origin && err instanceof TypeError) {
50
+ for (let waited = 0; !hit && waited < (o.waitMs ?? EVENT_WAIT_MS); waited += 5) {
51
+ await new Promise(r => setTimeout(r, 5))
52
+ hit = find()
53
+ }
54
+ }
55
+ if (hit) {
56
+ return `the page's Content-Security-Policy blocked it (${hit.directive}): add ${origin} to ${hit.directive} in the page's policy, or name a source of your own that the policy allows (gowasm: { sources: [...] })`
57
+ }
58
+ if (origin && own && origin !== own && err instanceof TypeError) {
59
+ return `could not be fetched: ${err.message} (a network error: if the page has a Content-Security-Policy, its connect-src must list ${origin}, or the app names a source of its own)`
60
+ }
61
+ return null
62
+ },
63
+ }
64
+ }