@gameslate/sdk 0.3.20 → 0.3.22

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.
package/README.md CHANGED
@@ -36,6 +36,7 @@ cd gameslate-mygame && yarn install && yarn check
36
36
  manifest.json id, name, version, sdkApi, games (where their files usually are, and any downloads)
37
37
  live.ts default export: { id, packs, sources }: game data and memory readers
38
38
  assets.ts optional, default export: { id, extractors }: maps and meshes from the player's files
39
+ wasm/*.wasm optional: WebAssembly modules for hot loops, built by the repo's own toolchain
39
40
  ```
40
41
 
41
42
  ```bash
@@ -74,6 +75,12 @@ the input `downloads/<id>`; the player sees it among the plugin's permissions.
74
75
 
75
76
  `0.3.x` speaks plugin contract (`sdkApi`) 3: new 0.3 versions add tools, never change the contract. The core refuses a plugin built for another contract.
76
77
 
78
+ - **0.3.22** (not yet published): plugins may bundle WebAssembly. `gameslate-plugin build`
79
+ copies `wasm/*.wasm` into the build and pins each in the manifest's `wasm`; code calls them with
80
+ `wasmModule('<file>.wasm')` (`call`, `read`, `write`, `memoryBytes`). A module may import only
81
+ `env.memory` and, in asset code, `gameslate.input_read`; the core caps its memory and stops a
82
+ call at the time budget. `InputFile.handle` names an input to `input_read`. The build skill's
83
+ "WebAssembly for hot loops" has the toolchain flags.
77
84
  - **0.3.19** (not yet published): no plugin code runs outside the sandbox.
78
85
  - `extract` (`afterAssets`, `pythonExtract`) is gone from the contract: the manifest schema is
79
86
  strict and refuses it, and `gameslate-plugin build` refuses an `extract.ts`;
@@ -25,3 +25,7 @@ export function buildPlugin(options: BuildPluginOptions): Promise<BuiltManifest>
25
25
  export function zipEntries(
26
26
  entries: Array<{ name: string; data: Uint8Array; mode?: number }>,
27
27
  ): Buffer;
28
+
29
+ /** The loader's limits on a plugin's WebAssembly, checked at build time too. */
30
+ export const MAX_WASM_MODULES: number;
31
+ export const MAX_WASM_BYTES: number;
@@ -1,3 +1,4 @@
1
+ /* global WebAssembly */
1
2
  import * as esbuild from 'esbuild';
2
3
  import { createHash } from 'node:crypto';
3
4
  import fs from 'node:fs';
@@ -13,6 +14,10 @@ export { zipEntries } from './zip.mjs';
13
14
  * core loads, with a manifest carrying each code file's hash:
14
15
  * live.js live.ts's default export behind `exposeToHost`, for the core's QuickJS sandbox
15
16
  * assets.js assets.ts's default export behind `exposeAssetsToHost`, for extraction jobs
17
+ * *.wasm the plugin's WebAssembly modules, copied from its `wasm/` folder (built there by
18
+ * the plugin repo's own toolchain) and listed in the manifest's `wasm` with their
19
+ * hashes; the code calls them through `wasmModule('<file>.wasm')`. An invalid
20
+ * module fails the build; the core checks its imports when it loads the plugin.
16
21
  * THIRD_PARTY_LICENSES.txt the licence of every npm package the code files bundle (one
17
22
  * without a licence file fails the build), and THIRD_PARTY_NOTICES.md copied from
18
23
  * the plugin's repository (beside its plugin folder) when it has one
@@ -33,6 +38,12 @@ const LIVE_FILE = 'live.js';
33
38
  const ASSETS_FILE = 'assets.js';
34
39
  const LICENCES_FILE = 'THIRD_PARTY_LICENSES.txt';
35
40
  const NOTICES_FILE = 'THIRD_PARTY_NOTICES.md';
41
+ const WASM_DIR = 'wasm';
42
+ /* the loader's limits (MAX_WASM_MODULES in src/plugin-manifest.ts, WASM_MAX_MODULE_BYTES in
43
+ * src/host/wasm-host.ts; wasm-plugin.test.ts checks they agree), so a build the core would
44
+ * refuse fails here */
45
+ export const MAX_WASM_MODULES = 4;
46
+ export const MAX_WASM_BYTES = 8 * 1024 * 1024;
36
47
 
37
48
  /*
38
49
  * Resolves bare imports (`@gameslate/sdk`, `earcut`) the way Node does, from the importing file's
@@ -90,6 +101,38 @@ async function buildSandboxed({ srcDir, entry, expose, outfile, alias }) {
90
101
  return inputsOf(srcDir, result);
91
102
  }
92
103
 
104
+ /* Copies the plugin's prebuilt WebAssembly modules into the build; their manifest entries. The
105
+ * folder holds built modules only, so a misnamed one fails here rather than when code calls it. */
106
+ function copyWasm(srcDir, outDir, manifest) {
107
+ const dir = path.join(srcDir, WASM_DIR);
108
+ if (!fs.existsSync(dir)) {
109
+ if (manifest.wasm)
110
+ throw new Error(
111
+ `manifest.json lists wasm, but there is no ${WASM_DIR}/ folder to build it from`,
112
+ );
113
+ return [];
114
+ }
115
+ const files = fs.readdirSync(dir).sort();
116
+ const stray = files.find(f => !/^[A-Za-z0-9_][A-Za-z0-9_.-]*\.wasm$/.test(f));
117
+ if (stray)
118
+ throw new Error(
119
+ `${WASM_DIR}/${stray}: the folder holds only built modules, named like palette.wasm`,
120
+ );
121
+ if (files.length > MAX_WASM_MODULES)
122
+ throw new Error(
123
+ `${WASM_DIR}/ holds ${files.length} modules; a plugin may bundle ${MAX_WASM_MODULES}`,
124
+ );
125
+ return files.map(file => {
126
+ const bytes = fs.readFileSync(path.join(dir, file));
127
+ if (bytes.length > MAX_WASM_BYTES)
128
+ throw new Error(`${WASM_DIR}/${file} is over ${MAX_WASM_BYTES} bytes`);
129
+ if (!WebAssembly.validate(bytes))
130
+ throw new Error(`${WASM_DIR}/${file} is not a valid WebAssembly module`);
131
+ fs.writeFileSync(path.join(outDir, file), bytes);
132
+ return { file, sha256: createHash('sha256').update(bytes).digest('hex') };
133
+ });
134
+ }
135
+
93
136
  /**
94
137
  * Builds `srcDir` into `outDir` (replaced). `testedWith`: the core versions it was tested with.
95
138
  * `alias`: esbuild aliases for the sandbox builds (a monorepo pointing at sources). Returns the
@@ -113,6 +156,9 @@ export async function buildPlugin({ srcDir, outDir, testedWith, alias = {}, rele
113
156
  alias,
114
157
  });
115
158
  const built = { ...manifest, testedWith, code: { file: LIVE_FILE, sha256: hashOf(live) } };
159
+ const wasm = copyWasm(srcDir, outDir, manifest);
160
+ if (wasm.length) built.wasm = wasm;
161
+ else delete built.wasm;
116
162
  if (fs.existsSync(path.join(srcDir, 'assets.ts'))) {
117
163
  const out = path.join(outDir, ASSETS_FILE);
118
164
  bundled.push(
@@ -2,7 +2,7 @@ import { execFile, spawn } from 'node:child_process';
2
2
  import dgram from 'node:dgram';
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
- import { firstBusyUdpPort, RETROARCH_UDP_PORTS } from '../lib/host/index.js';
5
+ import { firstBusyUdpPort, launchPrefixFor, RETROARCH_UDP_PORTS } from '../lib/host/index.js';
6
6
 
7
7
  /*
8
8
  * The real effects of `gameslate-plugin verify` (src/host/verify.ts has the steps and their
@@ -57,9 +57,8 @@ function started(child, stop) {
57
57
  });
58
58
  }
59
59
 
60
- /* The emulator's own pid: the child, or the launch wrapper's child when there's a prefix. */
61
- function emulatorPid(child, wrapped) {
62
- if (!wrapped) return child.pid;
60
+ /* The emulator's own pid: the launch wrapper's child. */
61
+ function emulatorPid(child) {
63
62
  const children = `/proc/${child.pid}/task/${child.pid}/children`;
64
63
  const pid = Number(fs.readFileSync(children, 'utf8').trim().split(/\s+/)[0]);
65
64
  if (!pid) throw new Error('the launch wrapper started no emulator');
@@ -68,13 +67,17 @@ function emulatorPid(child, wrapped) {
68
67
 
69
68
  async function launchEmulator(spec, at, log) {
70
69
  const { command, launchPrefix } = spec.emulator;
71
- const [first, ...rest] = [...launchPrefix, ...command];
70
+ const prefix = launchPrefixFor(launchPrefix, gameslatePath(spec, at), process.execPath);
71
+ const [first, ...rest] = [...prefix, ...command];
72
72
  const child = spawn(first, rest, { stdio: 'ignore', cwd: at('.') });
73
73
  log(`started ${path.basename(command[0])} (pid ${child.pid})`);
74
74
  await started(child, null);
75
- return { pid: emulatorPid(child, launchPrefix.length > 0), stop: () => child.kill('SIGTERM') };
75
+ return { pid: emulatorPid(child), stop: () => child.kill('SIGTERM') };
76
76
  }
77
77
 
78
+ /* the spec's dist/gameslate.mjs, resolved beside the spec */
79
+ const gameslatePath = (spec, at) => (spec.gameslate ? at(spec.gameslate) : undefined);
80
+
78
81
  /* a `gameslate drive` command; a frame's file goes beside the spec */
79
82
  function drive(spec, at, args) {
80
83
  if (!spec.gameslate) throw new Error('steps need "gameslate": the path to dist/gameslate.mjs');
@@ -98,7 +101,8 @@ function launchRetroArch(spec, at, log) {
98
101
  if (!ra) return Promise.resolve({ stop: () => undefined });
99
102
  const args = ['-L', at(ra.core), at(ra.rom), '-e', String(ra.stateSlot)];
100
103
  if (ra.config) args.push('--appendconfig', at(ra.config));
101
- const [first, ...rest] = [...ra.launchPrefix, at(ra.binary), ...args];
104
+ const prefix = launchPrefixFor(ra.launchPrefix, gameslatePath(spec, at), process.execPath);
105
+ const [first, ...rest] = [...prefix, at(ra.binary), ...args];
102
106
  const child = spawn(first, rest, { stdio: 'ignore' });
103
107
  log(`started RetroArch (pid ${child.pid}) on state slot ${ra.stateSlot}`);
104
108
  return new Promise((resolve, reject) => {
package/lib/assets.d.ts CHANGED
@@ -1972,4 +1972,7 @@ export interface InputFile {
1972
1972
  readonly name: string;
1973
1973
  readonly size: number;
1974
1974
  read(offset: number, length: number): Uint8Array;
1975
+ /** what the plugin's WebAssembly passes to `gameslate.input_read` to read this file straight
1976
+ * into its memory. Set by the core; a test's hand-made input has none. */
1977
+ readonly handle?: number;
1975
1978
  }
@@ -1,5 +1,6 @@
1
1
  import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
2
2
  import { type AssetList, type AssetOutputWire, type InputPick, type SandboxInputFile } from '../index.js';
3
+ import type { WasmFile, WasmHostFunctions } from './wasm-host.js';
3
4
  export declare const ASSET_LIMITS: {
4
5
  readonly memoryBytes: number;
5
6
  readonly stackBytes: number;
@@ -14,7 +15,12 @@ export declare const ASSET_LIMITS: {
14
15
  readonly maxReadBytes: number;
15
16
  /** all output bytes of one asset */
16
17
  readonly maxOutputBytes: number;
18
+ /** each WebAssembly module's memory, beside the interpreter's */
19
+ readonly wasmMemoryBytes: number;
17
20
  };
21
+ /** What asset code's WebAssembly may import from `gameslate`: an input range read into its
22
+ * memory, `input_read(handle: i32, offset: i64, length: i32, ptr: i32)`. */
23
+ export declare function assetWasmFunctions(inputs: InputSet): WasmHostFunctions;
18
24
  /** The player's files for one run, opened by the core and read by range. */
19
25
  /** An input's name as the plugin sees it: relative to the folder the player picked (`mods/x.o2r`),
20
26
  * or just the file's name when files were picked one by one. */
@@ -31,6 +37,9 @@ export declare class InputSet {
31
37
  /** what the guest sees: handles, names and sizes, never paths */
32
38
  describe(): SandboxInputFile[];
33
39
  read(handle: number, offset: number, length: number): Uint8Array;
40
+ /** Reads `target.length` bytes from `offset` into `target` (a WebAssembly module's memory). */
41
+ readInto(handle: number, offset: number, target: Uint8Array): void;
42
+ private checkedFile;
34
43
  close(): void;
35
44
  }
36
45
  export interface BuiltAsset {
@@ -49,6 +58,8 @@ export declare class AssetSandbox {
49
58
  code: string;
50
59
  inputs: InputSet;
51
60
  log: (line: string) => void;
61
+ /** the plugin's WebAssembly modules, checked against its manifest */
62
+ wasm?: readonly WasmFile[];
52
63
  });
53
64
  /** whether it broke a limit (out of memory, over budget) and refuses every call from now on */
54
65
  get switchedOff(): boolean;
@@ -5,7 +5,9 @@ import { QuickJsGuest } from './quickjs-guest.js';
5
5
  /*
6
6
  * A plugin's asset code in its own QuickJS runtime, for one extraction run. Its capabilities:
7
7
  * ranged reads of the files the core opened for this run, and handing back output bytes. No
8
- * paths, no writes: the job's writer validates and stores what comes back.
8
+ * paths, no writes: the job's writer validates and stores what comes back. Its WebAssembly
9
+ * modules get one capability, `gameslate.input_read`, which reads an input range straight into
10
+ * the module's memory.
9
11
  */
10
12
  export const ASSET_LIMITS = {
11
13
  /* a whole campaign's levels, textures and atlas stay parsed for the run */
@@ -22,7 +24,27 @@ export const ASSET_LIMITS = {
22
24
  maxReadBytes: 64 * 1024 * 1024,
23
25
  /** all output bytes of one asset */
24
26
  maxOutputBytes: 256 * 1024 * 1024,
27
+ /** each WebAssembly module's memory, beside the interpreter's */
28
+ wasmMemoryBytes: 1024 * 1024 * 1024,
25
29
  };
30
+ /** What asset code's WebAssembly may import from `gameslate`: an input range read into its
31
+ * memory, `input_read(handle: i32, offset: i64, length: i32, ptr: i32)`. */
32
+ export function assetWasmFunctions(inputs) {
33
+ return memory => ({
34
+ input_read: (handle, offset, length, ptr) => {
35
+ if (typeof handle !== 'number' || typeof length !== 'number' || typeof ptr !== 'number')
36
+ throw new Error('input_read takes (i32 handle, i64 offset, i32 length, i32 ptr)');
37
+ if (typeof offset !== 'bigint' && typeof offset !== 'number')
38
+ throw new Error('input_read takes (i32 handle, i64 offset, i32 length, i32 ptr)');
39
+ const view = memory();
40
+ const at = ptr >>> 0;
41
+ const count = length >>> 0;
42
+ if (at + count > view.length)
43
+ throw new Error("input_read past the end of the module's memory");
44
+ inputs.readInto(handle, Number(offset), view.subarray(at, at + count));
45
+ },
46
+ });
47
+ }
26
48
  /** The player's files for one run, opened by the core and read by range. */
27
49
  /** An input's name as the plugin sees it: relative to the folder the player picked (`mods/x.o2r`),
28
50
  * or just the file's name when files were picked one by one. */
@@ -55,6 +77,17 @@ export class InputSet {
55
77
  return this.files.map((f, i) => ({ handle: i + 1, name: f.name, size: f.size }));
56
78
  }
57
79
  read(handle, offset, length) {
80
+ this.checkedFile(handle, offset, length);
81
+ const out = new Uint8Array(length);
82
+ this.readInto(handle, offset, out);
83
+ return out;
84
+ }
85
+ /** Reads `target.length` bytes from `offset` into `target` (a WebAssembly module's memory). */
86
+ readInto(handle, offset, target) {
87
+ const file = this.checkedFile(handle, offset, target.length);
88
+ fs.readSync(file.fd, target, 0, target.length, offset);
89
+ }
90
+ checkedFile(handle, offset, length) {
58
91
  const file = this.files[handle - 1];
59
92
  if (!file)
60
93
  throw new Error('no such input');
@@ -66,9 +99,7 @@ export class InputSet {
66
99
  }
67
100
  if (offset + length > file.size)
68
101
  throw new Error(`a read past the end of ${file.name}`);
69
- const out = new Uint8Array(length);
70
- fs.readSync(file.fd, out, 0, length, offset);
71
- return out;
102
+ return file;
72
103
  }
73
104
  close() {
74
105
  for (const f of this.files)
@@ -83,7 +114,7 @@ export class AssetSandbox {
83
114
  name;
84
115
  inputs;
85
116
  constructor(quickJs, opts) {
86
- const { name, code, log } = opts;
117
+ const { name, code, log, wasm = [] } = opts;
87
118
  this.name = name;
88
119
  this.inputs = opts.inputs;
89
120
  this.guest = new QuickJsGuest(quickJs, {
@@ -93,6 +124,12 @@ export class AssetSandbox {
93
124
  limits: ASSET_LIMITS,
94
125
  apiGlobal: '__gsAssets',
95
126
  host: { __gsAssetsHost: this.capabilities() },
127
+ wasm: {
128
+ modules: wasm,
129
+ functions: assetWasmFunctions(opts.inputs),
130
+ maxMemoryBytes: ASSET_LIMITS.wasmMemoryBytes,
131
+ maxReadBytes: ASSET_LIMITS.maxReadBytes,
132
+ },
96
133
  log,
97
134
  });
98
135
  }
@@ -7,3 +7,4 @@ export * from './verify.js';
7
7
  export * from './addresses.js';
8
8
  export * from './udp-ports.js';
9
9
  export * from './game-support.js';
10
+ export * from './wasm-host.js';
package/lib/host/index.js CHANGED
@@ -11,3 +11,4 @@ export * from './verify.js';
11
11
  export * from './addresses.js';
12
12
  export * from './udp-ports.js';
13
13
  export * from './game-support.js';
14
+ export * from './wasm-host.js';
@@ -1,6 +1,7 @@
1
1
  import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
2
2
  import { type PluginManifest } from '../plugin-manifest.js';
3
3
  import type { PluginModule } from '../plugin/index.js';
4
+ import { type WasmFile } from './wasm-host.js';
4
5
  export type ManifestResult = {
5
6
  manifest: PluginManifest;
6
7
  } | {
@@ -11,9 +12,11 @@ export interface InspectedPlugin {
11
12
  manifest: PluginManifest;
12
13
  /** the live code running in its sandbox, as the core uses it */
13
14
  live: PluginModule;
14
- /** the asset code and the games it extracts for (jobs load it again per run) */
15
+ /** the asset code, its WebAssembly, and the games it extracts for (jobs load it again per
16
+ * run) */
15
17
  assets: {
16
18
  code: string;
19
+ wasm: WasmFile[];
17
20
  games: string[];
18
21
  } | null;
19
22
  /** the games it carries registry data for (`registry/games/<gameId>/`) */
@@ -2,8 +2,9 @@ import { createHash } from 'node:crypto';
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { PluginManifestSchema, SDK_API } from '../plugin-manifest.js';
5
- import { AssetSandbox, InputSet } from './asset-sandbox.js';
6
- import { PluginSandbox } from './live-sandbox.js';
5
+ import { ASSET_LIMITS, AssetSandbox, assetWasmFunctions, InputSet } from './asset-sandbox.js';
6
+ import { PluginSandbox, SANDBOX_LIMITS } from './live-sandbox.js';
7
+ import { wasmImportNames, wasmModuleProblem } from './wasm-host.js';
7
8
  import { inspectPluginRegistry } from './plugin-registry.js';
8
9
  export function readPluginManifest(dir) {
9
10
  let raw;
@@ -21,26 +22,79 @@ export function readPluginManifest(dir) {
21
22
  const issues = parsed.error.issues.map(i => `${i.path.join('.')} ${i.message}`).join('; ');
22
23
  return { problem: `invalid manifest: ${issues}` };
23
24
  }
24
- /** Why a code file can't be trusted (missing, or not the file the manifest hashed), or null. */
25
- function codeProblem(dir, code) {
25
+ /** A code file's bytes, or why it can't be trusted (missing, or not the file the manifest
26
+ * hashed). */
27
+ function pinnedFile(dir, code) {
26
28
  const file = path.join(dir, code.file);
27
29
  if (!fs.existsSync(file))
28
30
  return `code file ${code.file} is missing`;
29
- const sha = createHash('sha256').update(fs.readFileSync(file)).digest('hex');
30
- return sha === code.sha256 ? null : `${code.file} doesn't match its hash`;
31
+ const bytes = new Uint8Array(fs.readFileSync(file));
32
+ const sha = createHash('sha256').update(bytes).digest('hex');
33
+ return sha === code.sha256 ? bytes : `${code.file} doesn't match its hash`;
34
+ }
35
+ function codeProblem(dir, code) {
36
+ const pinned = pinnedFile(dir, code);
37
+ return typeof pinned === 'string' ? pinned : null;
38
+ }
39
+ /* What the plugin's modules may import and how much memory they may start with: asset code's
40
+ * allow-list when it has asset code (live code's is empty), checked again per sandbox when a
41
+ * module is instantiated. */
42
+ function wasmAllowance(manifest) {
43
+ if (!manifest.assets)
44
+ return { allowed: new Set(), maxMemoryBytes: SANDBOX_LIMITS.wasmMemoryBytes };
45
+ const none = new InputSet([]);
46
+ try {
47
+ const allowed = wasmImportNames(assetWasmFunctions(none));
48
+ return { allowed, maxMemoryBytes: ASSET_LIMITS.wasmMemoryBytes };
49
+ }
50
+ finally {
51
+ none.close();
52
+ }
53
+ }
54
+ /** The plugin's WebAssembly modules, each matching its hash and the allow-list, or why not. */
55
+ function loadWasm(dir, manifest) {
56
+ const { allowed, maxMemoryBytes } = wasmAllowance(manifest);
57
+ const modules = [];
58
+ for (const entry of manifest.wasm ?? []) {
59
+ const bytes = pinnedFile(dir, entry);
60
+ if (typeof bytes === 'string')
61
+ return bytes;
62
+ const problem = wasmModuleProblem(bytes, allowed, maxMemoryBytes);
63
+ if (problem)
64
+ return `${entry.file}: ${problem}`;
65
+ modules.push({ file: entry.file, bytes });
66
+ }
67
+ return modules;
31
68
  }
32
69
  function describedProblem(manifest, d) {
33
70
  if (d.id !== manifest.id)
34
71
  return `its code says it is ${d.id}`;
35
72
  const games = new Set(manifest.games.map(g => g.id));
36
73
  const stray = [...d.sources.map(s => s.gameId), ...d.packs.map(p => p.id)].filter(id => !games.has(id));
37
- return stray.length
38
- ? `its code covers games its manifest doesn't list (${stray.join(', ')})`
74
+ if (stray.length)
75
+ return `its code covers games its manifest doesn't list (${stray.join(', ')})`;
76
+ return undeclaredBuilds(manifest, d);
77
+ }
78
+ /* The builds a source matches are what the player consented to read: a source may match only
79
+ * builds its game's manifest entry lists (a manifest from before builds were declared lists none,
80
+ * and is not checked). */
81
+ function undeclaredBuilds(manifest, d) {
82
+ const declared = new Map(manifest.games.flatMap(g => g.builds ? [[g.id, new Set(g.builds.map(b => b.id))]] : []));
83
+ const undeclared = d.sources.flatMap(s => {
84
+ const builds = declared.get(s.gameId);
85
+ if (!builds)
86
+ return [];
87
+ return s.supportedBuildIds
88
+ .filter(([id]) => !builds.has(id))
89
+ .map(([id]) => `${s.gameId} ${id}`);
90
+ });
91
+ return undeclared.length
92
+ ? `its code reads builds its manifest doesn't list (${undeclared.join(', ')})`
39
93
  : null;
40
94
  }
41
- function loadLive(quickJs, dir, manifest, log) {
95
+ function loadLive(quickJs, dir, manifest, { wasm, log }) {
42
96
  const code = fs.readFileSync(path.join(dir, manifest.code.file), 'utf8');
43
- const sandbox = new PluginSandbox(quickJs, code, manifest.id, { log });
97
+ const sandbox = new PluginSandbox(quickJs, code, manifest.id, { log, wasm });
44
98
  try {
45
99
  const description = sandbox.describe();
46
100
  const problem = describedProblem(manifest, description);
@@ -54,19 +108,19 @@ function loadLive(quickJs, dir, manifest, log) {
54
108
  throw e;
55
109
  }
56
110
  }
57
- function loadAssets(quickJs, dir, manifest, log) {
111
+ function loadAssets(quickJs, dir, manifest, { wasm, log }) {
58
112
  if (!manifest.assets)
59
113
  return null;
60
114
  const code = fs.readFileSync(path.join(dir, manifest.assets.file), 'utf8');
61
115
  const inputs = new InputSet([]);
62
- const sandbox = new AssetSandbox(quickJs, { name: manifest.id, code, inputs, log });
116
+ const sandbox = new AssetSandbox(quickJs, { name: manifest.id, code, inputs, log, wasm });
63
117
  try {
64
118
  const games = sandbox.games();
65
119
  const listed = new Set(manifest.games.map(g => g.id));
66
120
  const stray = games.filter(g => !listed.has(g));
67
121
  return stray.length
68
122
  ? `its asset code covers games its manifest doesn't list (${stray.join(', ')})`
69
- : { code, games };
123
+ : { code, wasm, games };
70
124
  }
71
125
  finally {
72
126
  sandbox.dispose();
@@ -83,6 +137,9 @@ export function inspectPlugin(quickJs, dir, manifest, opts) {
83
137
  .find(reason => reason !== null);
84
138
  if (bad)
85
139
  return bad;
140
+ const wasm = loadWasm(dir, manifest);
141
+ if (typeof wasm === 'string')
142
+ return wasm;
86
143
  const registry = inspectPluginRegistry(dir, manifest);
87
144
  if (typeof registry === 'string')
88
145
  return registry;
@@ -91,12 +148,12 @@ export function inspectPlugin(quickJs, dir, manifest, opts) {
91
148
  : [
92
149
  `${manifest.id} ${manifest.version} wasn't tested with core ${opts.coreVersion} (tested: ${manifest.testedWith.join(', ') || 'none'}); it may not work`,
93
150
  ];
94
- const live = loadLive(quickJs, dir, manifest, opts.log);
151
+ const live = loadLive(quickJs, dir, manifest, { wasm, log: opts.log });
95
152
  if (typeof live === 'string')
96
153
  return live;
97
154
  let assets;
98
155
  try {
99
- assets = loadAssets(quickJs, dir, manifest, opts.log);
156
+ assets = loadAssets(quickJs, dir, manifest, { wasm, log: opts.log });
100
157
  }
101
158
  catch (e) {
102
159
  live.sandbox.dispose();
@@ -1,6 +1,7 @@
1
1
  import type { QuickJSWASMModule } from 'quickjs-emscripten-core';
2
2
  import { type SandboxDescription } from '../index.js';
3
3
  import type { PluginModule } from '../plugin/index.js';
4
+ import type { WasmFile } from './wasm-host.js';
4
5
  export { loadQuickJs } from './quickjs-guest.js';
5
6
  export declare const SANDBOX_LIMITS: {
6
7
  readonly memoryBytes: number;
@@ -9,6 +10,8 @@ export declare const SANDBOX_LIMITS: {
9
10
  readonly callMs: 250;
10
11
  /** the largest single memory read a plugin may ask for */
11
12
  readonly maxReadBytes: number;
13
+ /** each WebAssembly module's memory (live code's modules import nothing else) */
14
+ readonly wasmMemoryBytes: number;
12
15
  };
13
16
  /** One plugin's live code in its own runtime. */
14
17
  export declare class PluginSandbox {
@@ -19,6 +22,7 @@ export declare class PluginSandbox {
19
22
  private readonly restarts;
20
23
  private readonly log;
21
24
  private readonly now;
25
+ private readonly wasm;
22
26
  private readonly memories;
23
27
  private readonly sessionGames;
24
28
  private nextHandle;
@@ -26,6 +30,7 @@ export declare class PluginSandbox {
26
30
  constructor(quickJs: QuickJSWASMModule, code: string, name: string, opts: {
27
31
  log: (line: string) => void;
28
32
  now?: () => number;
33
+ wasm?: readonly WasmFile[];
29
34
  });
30
35
  private newGuest;
31
36
  private restartIfSwitchedOff;
@@ -25,6 +25,8 @@ export const SANDBOX_LIMITS = {
25
25
  callMs: 250,
26
26
  /** the largest single memory read a plugin may ask for */
27
27
  maxReadBytes: 16 * 1024 * 1024,
28
+ /** each WebAssembly module's memory (live code's modules import nothing else) */
29
+ wasmMemoryBytes: 16 * 1024 * 1024,
28
30
  };
29
31
  /** One plugin's live code in its own runtime. */
30
32
  export class PluginSandbox {
@@ -35,6 +37,7 @@ export class PluginSandbox {
35
37
  restarts = [];
36
38
  log;
37
39
  now;
40
+ wasm;
38
41
  memories = new Map();
39
42
  sessionGames = new Map();
40
43
  nextHandle = 1;
@@ -46,6 +49,7 @@ export class PluginSandbox {
46
49
  this.name = name;
47
50
  this.log = opts.log;
48
51
  this.now = opts.now ?? Date.now;
52
+ this.wasm = opts.wasm ?? [];
49
53
  this.guest = this.newGuest();
50
54
  }
51
55
  newGuest() {
@@ -57,6 +61,12 @@ export class PluginSandbox {
57
61
  limits: SANDBOX_LIMITS,
58
62
  apiGlobal: '__gs',
59
63
  host: { __gsHost: this.memoryCapabilities() },
64
+ wasm: {
65
+ modules: this.wasm,
66
+ functions: () => ({}),
67
+ maxMemoryBytes: SANDBOX_LIMITS.wasmMemoryBytes,
68
+ maxReadBytes: SANDBOX_LIMITS.maxReadBytes,
69
+ },
60
70
  log,
61
71
  });
62
72
  }
@@ -1,4 +1,5 @@
1
1
  import { type QuickJSContext, type QuickJSHandle, type QuickJSWASMModule } from 'quickjs-emscripten-core';
2
+ import { type WasmSetup } from './wasm-host.js';
2
3
  /** The QuickJS engine: the copy next to the daemon's bundle, else the installed package's. */
3
4
  export declare function loadQuickJs(): Promise<QuickJSWASMModule>;
4
5
  export interface GuestLimits {
@@ -15,6 +16,7 @@ export declare class QuickJsGuest {
15
16
  private readonly runtime;
16
17
  private readonly api;
17
18
  private disabled;
19
+ private deadline;
18
20
  private corrupted;
19
21
  constructor(quickJs: QuickJSWASMModule, opts: {
20
22
  name: string;
@@ -25,6 +27,8 @@ export declare class QuickJsGuest {
25
27
  apiGlobal: string;
26
28
  /** host functions, by global object name (the guest's only capabilities) */
27
29
  host: Record<string, Record<string, HostFunction>>;
30
+ /** the plugin's WebAssembly modules and what they may import */
31
+ wasm?: WasmSetup;
28
32
  log: (line: string) => void;
29
33
  });
30
34
  /** Calls a guest function within the budget; its JSON-able result, dumped to the host. */
@@ -34,6 +38,7 @@ export declare class QuickJsGuest {
34
38
  dispose(): void;
35
39
  private disable;
36
40
  private callGuest;
41
+ private wasmFunctions;
37
42
  private withBudget;
38
43
  private guestError;
39
44
  private install;
@@ -4,11 +4,13 @@ import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import releaseSync from '@jitl/quickjs-wasmfile-release-sync';
6
6
  import { newQuickJSWASMModuleFromVariant, newVariant, shouldInterruptAfterDeadline, } from 'quickjs-emscripten-core';
7
+ import { WasmInstances } from './wasm-host.js';
7
8
  /*
8
9
  * One piece of plugin code in its own QuickJS runtime (WebAssembly): no file system, network,
9
10
  * process or module loader, only the host functions the caller installs. Every call has a time
10
11
  * budget and the runtime a memory cap. A guest that runs out of memory, is interrupted or overruns
11
- * its budget is switched off for good: its next call fails at once.
12
+ * its budget is switched off for good: its next call fails at once. A plugin's WebAssembly modules
13
+ * (wasm-host.ts) are reached through `__gsWasm`, within the same budget.
12
14
  */
13
15
  const WASM_FILE = 'quickjs.wasm';
14
16
  /** The QuickJS engine: the copy next to the daemon's bundle, else the installed package's. */
@@ -30,6 +32,8 @@ export class QuickJsGuest {
30
32
  runtime;
31
33
  api;
32
34
  disabled = null;
35
+ /* when the guest call running now must end (Date.now() time) */
36
+ deadline = 0;
33
37
  /* runaway guest recursion exhausts the host's stack mid-call and leaves the runtime holding
34
38
  * objects it can't account for: freeing it then aborts the whole QuickJS module */
35
39
  corrupted = false;
@@ -42,6 +46,8 @@ export class QuickJsGuest {
42
46
  try {
43
47
  for (const [global, fns] of Object.entries(opts.host))
44
48
  this.install(global, fns);
49
+ if (opts.wasm)
50
+ this.install('__gsWasm', this.wasmFunctions(opts.wasm));
45
51
  this.withBudget(opts.limits.loadMs, () => {
46
52
  const loaded = this.vm.evalCode(opts.code, `${opts.name}/${opts.file}`);
47
53
  if (loaded.error)
@@ -117,8 +123,53 @@ export class QuickJsGuest {
117
123
  result.value.dispose();
118
124
  return value;
119
125
  }
126
+ /* The guest's way into its WebAssembly: numbers and byte ranges, each call within what is
127
+ * left of the guest call's budget. A module that overruns it switches the guest off, even if
128
+ * the guest catches the error. */
129
+ wasmFunctions(setup) {
130
+ const vm = this.vm;
131
+ const wasm = new WasmInstances(setup, reason => this.disable(reason));
132
+ const left = () => this.deadline - Date.now();
133
+ const text = (h) => {
134
+ if (vm.typeof(h) !== 'string')
135
+ throw new Error('a WebAssembly file is named by a string');
136
+ return vm.getString(h);
137
+ };
138
+ /* quickjs-emscripten reports anything but an ArrayBuffer as out of memory */
139
+ const arrayBuffer = (h) => {
140
+ try {
141
+ return vm.getArrayBuffer(h);
142
+ }
143
+ catch {
144
+ throw new Error('WebAssembly write takes an ArrayBuffer');
145
+ }
146
+ };
147
+ const num = (h) => {
148
+ if (vm.typeof(h) !== 'number')
149
+ throw new Error('WebAssembly takes only numbers');
150
+ return vm.getNumber(h);
151
+ };
152
+ return {
153
+ call: (file, fn, ...args) => {
154
+ const result = wasm.call(text(file), text(fn), args.map(num), left());
155
+ return result === undefined ? undefined : vm.newNumber(result);
156
+ },
157
+ read: (file, ptr, length) => vm.newArrayBuffer(wasm.read(text(file), num(ptr), num(length), left()).buffer),
158
+ write: (file, ptr, data) => {
159
+ const bytes = arrayBuffer(data);
160
+ try {
161
+ wasm.write(text(file), num(ptr), bytes.value, left());
162
+ }
163
+ finally {
164
+ bytes.dispose();
165
+ }
166
+ },
167
+ memoryBytes: file => vm.newNumber(wasm.memoryBytes(text(file), left())),
168
+ };
169
+ }
120
170
  withBudget(ms, run) {
121
- this.runtime.setInterruptHandler(shouldInterruptAfterDeadline(Date.now() + ms));
171
+ this.deadline = Date.now() + ms;
172
+ this.runtime.setInterruptHandler(shouldInterruptAfterDeadline(this.deadline));
122
173
  try {
123
174
  return run();
124
175
  }