@gameslate/sdk 0.3.21 → 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(
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,13 +22,49 @@ 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)
@@ -55,9 +92,9 @@ function undeclaredBuilds(manifest, d) {
55
92
  ? `its code reads builds its manifest doesn't list (${undeclared.join(', ')})`
56
93
  : null;
57
94
  }
58
- function loadLive(quickJs, dir, manifest, log) {
95
+ function loadLive(quickJs, dir, manifest, { wasm, log }) {
59
96
  const code = fs.readFileSync(path.join(dir, manifest.code.file), 'utf8');
60
- const sandbox = new PluginSandbox(quickJs, code, manifest.id, { log });
97
+ const sandbox = new PluginSandbox(quickJs, code, manifest.id, { log, wasm });
61
98
  try {
62
99
  const description = sandbox.describe();
63
100
  const problem = describedProblem(manifest, description);
@@ -71,19 +108,19 @@ function loadLive(quickJs, dir, manifest, log) {
71
108
  throw e;
72
109
  }
73
110
  }
74
- function loadAssets(quickJs, dir, manifest, log) {
111
+ function loadAssets(quickJs, dir, manifest, { wasm, log }) {
75
112
  if (!manifest.assets)
76
113
  return null;
77
114
  const code = fs.readFileSync(path.join(dir, manifest.assets.file), 'utf8');
78
115
  const inputs = new InputSet([]);
79
- const sandbox = new AssetSandbox(quickJs, { name: manifest.id, code, inputs, log });
116
+ const sandbox = new AssetSandbox(quickJs, { name: manifest.id, code, inputs, log, wasm });
80
117
  try {
81
118
  const games = sandbox.games();
82
119
  const listed = new Set(manifest.games.map(g => g.id));
83
120
  const stray = games.filter(g => !listed.has(g));
84
121
  return stray.length
85
122
  ? `its asset code covers games its manifest doesn't list (${stray.join(', ')})`
86
- : { code, games };
123
+ : { code, wasm, games };
87
124
  }
88
125
  finally {
89
126
  sandbox.dispose();
@@ -100,6 +137,9 @@ export function inspectPlugin(quickJs, dir, manifest, opts) {
100
137
  .find(reason => reason !== null);
101
138
  if (bad)
102
139
  return bad;
140
+ const wasm = loadWasm(dir, manifest);
141
+ if (typeof wasm === 'string')
142
+ return wasm;
103
143
  const registry = inspectPluginRegistry(dir, manifest);
104
144
  if (typeof registry === 'string')
105
145
  return registry;
@@ -108,12 +148,12 @@ export function inspectPlugin(quickJs, dir, manifest, opts) {
108
148
  : [
109
149
  `${manifest.id} ${manifest.version} wasn't tested with core ${opts.coreVersion} (tested: ${manifest.testedWith.join(', ') || 'none'}); it may not work`,
110
150
  ];
111
- const live = loadLive(quickJs, dir, manifest, opts.log);
151
+ const live = loadLive(quickJs, dir, manifest, { wasm, log: opts.log });
112
152
  if (typeof live === 'string')
113
153
  return live;
114
154
  let assets;
115
155
  try {
116
- assets = loadAssets(quickJs, dir, manifest, opts.log);
156
+ assets = loadAssets(quickJs, dir, manifest, { wasm, log: opts.log });
117
157
  }
118
158
  catch (e) {
119
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
  }
@@ -1015,6 +1015,12 @@ export declare const VerifySpecSchema: z.ZodObject<{
1015
1015
  } | {
1016
1016
  waitMs: number;
1017
1017
  })[];
1018
+ memory: {
1019
+ counter: string;
1020
+ size: 2 | 1 | 4;
1021
+ address: number;
1022
+ signed: boolean;
1023
+ }[];
1018
1024
  timeoutMs: number;
1019
1025
  game: string;
1020
1026
  daemon: {
@@ -1039,12 +1045,7 @@ export declare const VerifySpecSchema: z.ZodObject<{
1039
1045
  variant?: string | undefined;
1040
1046
  equipped?: string | null | undefined;
1041
1047
  };
1042
- memory: {
1043
- counter: string;
1044
- size: 2 | 1 | 4;
1045
- address: number;
1046
- signed: boolean;
1047
- }[];
1048
+ gameslate?: string | undefined;
1048
1049
  retroarch?: {
1049
1050
  binary: string;
1050
1051
  core: string;
@@ -1058,7 +1059,6 @@ export declare const VerifySpecSchema: z.ZodObject<{
1058
1059
  launchPrefix: string[];
1059
1060
  command: string[];
1060
1061
  } | undefined;
1061
- gameslate?: string | undefined;
1062
1062
  ui?: {
1063
1063
  url: string;
1064
1064
  tabs: ("Map" | "Inventory" | "Missions" | "Ref")[];
@@ -1149,6 +1149,13 @@ export declare const VerifySpecSchema: z.ZodObject<{
1149
1149
  } | {
1150
1150
  waitMs: number;
1151
1151
  })[] | undefined;
1152
+ memory?: {
1153
+ counter: string;
1154
+ size: 2 | 1 | 4;
1155
+ address: string;
1156
+ signed?: boolean | undefined;
1157
+ }[] | undefined;
1158
+ gameslate?: string | undefined;
1152
1159
  timeoutMs?: number | undefined;
1153
1160
  retroarch?: {
1154
1161
  binary: string;
@@ -1163,7 +1170,6 @@ export declare const VerifySpecSchema: z.ZodObject<{
1163
1170
  command: string[];
1164
1171
  launchPrefix?: string[] | undefined;
1165
1172
  } | undefined;
1166
- gameslate?: string | undefined;
1167
1173
  daemon?: {
1168
1174
  url?: string | undefined;
1169
1175
  } | undefined;
@@ -1172,12 +1178,6 @@ export declare const VerifySpecSchema: z.ZodObject<{
1172
1178
  tabs?: string[] | undefined;
1173
1179
  } | undefined;
1174
1180
  settleMs?: number | undefined;
1175
- memory?: {
1176
- counter: string;
1177
- size: 2 | 1 | 4;
1178
- address: string;
1179
- signed?: boolean | undefined;
1180
- }[] | undefined;
1181
1181
  }>;
1182
1182
  export type VerifySpec = z.infer<typeof VerifySpecSchema>;
1183
1183
  type MemoryCheck = VerifySpec['memory'][number];
@@ -0,0 +1,51 @@
1
+ export declare const WASM_PAGE_BYTES: number;
2
+ /** the module the sandbox's capabilities are imported from */
3
+ export declare const WASM_HOST_MODULE = "gameslate";
4
+ /** the largest module a plugin may bundle */
5
+ export declare const WASM_MAX_MODULE_BYTES: number;
6
+ export interface WasmFile {
7
+ file: string;
8
+ bytes: Uint8Array<ArrayBuffer>;
9
+ }
10
+ /** A sandbox's capabilities as functions a module imports from `gameslate`, given a view of
11
+ * the module's memory as it is now (memory.grow replaces the buffer). */
12
+ export type WasmHostFunctions = (memory: () => Uint8Array) => Record<string, WebAssembly.ImportValue>;
13
+ export interface WasmSetup {
14
+ modules: readonly WasmFile[];
15
+ functions: WasmHostFunctions;
16
+ /** the most memory one module's instance may have */
17
+ maxMemoryBytes: number;
18
+ /** the largest range one `read` copies out to the guest */
19
+ maxReadBytes: number;
20
+ }
21
+ /** The function names a sandbox's modules may import from `gameslate`. */
22
+ export declare const wasmImportNames: (functions: WasmHostFunctions) => ReadonlySet<string>;
23
+ /**
24
+ * Why `bytes` can't run in a sandbox whose capabilities are `allowed` (function names imported
25
+ * from `gameslate`) and whose modules get at most `maxMemoryBytes`, or null.
26
+ */
27
+ export declare function wasmModuleProblem(bytes: Uint8Array<ArrayBuffer>, allowed: ReadonlySet<string>, maxMemoryBytes: number): string | null;
28
+ /** One sandbox's modules, instantiated when first used and called within a time budget. */
29
+ export declare class WasmInstances {
30
+ private readonly setup;
31
+ /** called once when a module overran its budget and was stopped */
32
+ private readonly onStopped;
33
+ private readonly instances;
34
+ private readonly global;
35
+ private readonly context;
36
+ private stopped;
37
+ private readonly allowed;
38
+ constructor(setup: WasmSetup,
39
+ /** called once when a module overran its budget and was stopped */
40
+ onStopped: (reason: string) => void);
41
+ /** Calls export `fn` of `file` with numbers; its number result (undefined for none). */
42
+ call(file: string, fn: string, args: readonly number[], ms: number): number | undefined;
43
+ /** A copy of `length` bytes of `file`'s memory from `ptr`. */
44
+ read(file: string, ptr: number, length: number, ms: number): Uint8Array;
45
+ write(file: string, ptr: number, bytes: Uint8Array, ms: number): void;
46
+ memoryBytes(file: string, ms: number): number;
47
+ private memoryOf;
48
+ private range;
49
+ private instance;
50
+ private timed;
51
+ }
@@ -0,0 +1,270 @@
1
+ import vm from 'node:vm';
2
+ /*
3
+ * A plugin's own WebAssembly modules ("Closing the sandbox" item 3 in
4
+ * docs/plugin-architecture.md), for work too slow in the QuickJS interpreter. The host's V8
5
+ * compiles and runs them, and the plugin's QuickJS code calls their exports with numbers and
6
+ * copies byte ranges in and out of their memory (quickjs-guest.ts bridges the two).
7
+ *
8
+ * What keeps them as boxed in as the QuickJS code:
9
+ * - Imports: a module may import only `env.memory` and the sandbox's capabilities as functions
10
+ * from `gameslate` (the allow-list). No WASI, no other function, table or global: checked with
11
+ * `WebAssembly.Module.imports` when the plugin loads and again when the module is instantiated.
12
+ * - Memory: the core owns it. A module that defines its own memory is refused (its maximum
13
+ * couldn't be enforced); the one it imports is created with the sandbox's maximum, so a
14
+ * `memory.grow` past it returns -1.
15
+ * - Time: every call, and the instantiation (a start function), runs under the guest call's
16
+ * deadline in a `vm` script with a timeout, whose watchdog stops V8 mid-loop. A module that was
17
+ * stopped is never called again and its guest is switched off.
18
+ * - Values: only numbers cross; an export that returns anything else (a function reference) is
19
+ * refused, so no host object reaches the guest.
20
+ */
21
+ export const WASM_PAGE_BYTES = 64 * 1024;
22
+ /** the one memory a module may import: what wasm-ld (Rust, C) and AssemblyScript name it with
23
+ * --import-memory */
24
+ const MEMORY_MODULE = 'env';
25
+ const MEMORY_NAME = 'memory';
26
+ /** the module the sandbox's capabilities are imported from */
27
+ export const WASM_HOST_MODULE = 'gameslate';
28
+ /** the largest module a plugin may bundle */
29
+ export const WASM_MAX_MODULE_BYTES = 8 * 1024 * 1024;
30
+ /** The function names a sandbox's modules may import from `gameslate`. */
31
+ export const wasmImportNames = (functions) => new Set(Object.keys(functions(() => new Uint8Array(0))));
32
+ /* A cursor over a module's bytes: LEB128 numbers and names. */
33
+ class ModuleReader {
34
+ bytes;
35
+ pos = 8; /* past the magic number and version */
36
+ constructor(bytes) {
37
+ this.bytes = bytes;
38
+ }
39
+ byte() {
40
+ const byte = this.bytes[this.pos++];
41
+ if (byte === undefined)
42
+ throw new Error('a read past the end of the module');
43
+ return byte;
44
+ }
45
+ u32() {
46
+ let result = 0;
47
+ for (let shift = 0;; shift += 7) {
48
+ const byte = this.byte();
49
+ result += (byte & 0x7f) * 2 ** shift;
50
+ if (byte < 0x80)
51
+ return result;
52
+ }
53
+ }
54
+ skipName() {
55
+ const length = this.u32();
56
+ this.pos += length;
57
+ }
58
+ }
59
+ /* The import section's memory, if any. Only called on imports that passed the allow-list, so
60
+ * they are functions and memories only. */
61
+ function importedMemory(r) {
62
+ for (let n = r.u32(); n > 0; n--) {
63
+ r.skipName();
64
+ r.skipName();
65
+ const kind = r.byte();
66
+ if (kind === 0)
67
+ r.u32();
68
+ else if (kind !== 2)
69
+ throw new Error(`an import of kind ${kind} got past the allow-list`);
70
+ else {
71
+ const flags = r.byte();
72
+ /* 0: min only; 1: min and max; anything else is shared or 64-bit */
73
+ if (flags !== 0 && flags !== 1)
74
+ return 'unsupported';
75
+ const minPages = r.u32();
76
+ /* one memory at most: the allow-list has one name and refuses it twice */
77
+ return { minPages, maxPages: flags === 1 ? r.u32() : null };
78
+ }
79
+ }
80
+ return null;
81
+ }
82
+ /* What the binary says about memory, which `WebAssembly.Module` doesn't reflect: whether it
83
+ * defines one, and the limits of the one it imports. */
84
+ function memoryLayout(bytes) {
85
+ const r = new ModuleReader(bytes);
86
+ let defines = false;
87
+ let imported = null;
88
+ while (r.pos < bytes.length) {
89
+ const id = r.byte();
90
+ const size = r.u32();
91
+ const end = r.pos + size;
92
+ if (id === 5)
93
+ defines = r.u32() > 0;
94
+ if (id === 2)
95
+ imported = importedMemory(r);
96
+ r.pos = end;
97
+ }
98
+ return { defines, imported };
99
+ }
100
+ /**
101
+ * Why `bytes` can't run in a sandbox whose capabilities are `allowed` (function names imported
102
+ * from `gameslate`) and whose modules get at most `maxMemoryBytes`, or null.
103
+ */
104
+ export function wasmModuleProblem(bytes, allowed, maxMemoryBytes) {
105
+ const checked = checkedModule(bytes, allowed, maxMemoryBytes);
106
+ return typeof checked === 'string' ? checked : null;
107
+ }
108
+ /* The compiled module, or why it can't run (see wasmModuleProblem). */
109
+ function checkedModule(bytes, allowed, maxMemoryBytes) {
110
+ if (bytes.byteLength > WASM_MAX_MODULE_BYTES)
111
+ return `it is over ${WASM_MAX_MODULE_BYTES} bytes`;
112
+ if (!WebAssembly.validate(bytes))
113
+ return 'it is not a valid WebAssembly module';
114
+ const compiled = new WebAssembly.Module(bytes);
115
+ const seen = new Set();
116
+ for (const imp of WebAssembly.Module.imports(compiled)) {
117
+ const name = `${imp.module}.${imp.name}`;
118
+ const isMemory = imp.module === MEMORY_MODULE && imp.name === MEMORY_NAME && imp.kind === 'memory';
119
+ const isCapability = imp.module === WASM_HOST_MODULE && allowed.has(imp.name) && imp.kind === 'function';
120
+ if (!isMemory && !isCapability) {
121
+ const list = [`${MEMORY_MODULE}.${MEMORY_NAME}`, ...allowed].join(', ');
122
+ return `it imports ${name} (${imp.kind}); a module may import only ${list}`;
123
+ }
124
+ if (seen.has(name))
125
+ return `it imports ${name} twice`;
126
+ seen.add(name);
127
+ }
128
+ const layout = memoryLayout(bytes);
129
+ if (layout.defines)
130
+ return 'it defines its own memory: import env.memory instead (link with --import-memory)';
131
+ if (layout.imported === 'unsupported')
132
+ return 'its memory is shared or 64-bit';
133
+ if (layout.imported && layout.imported.minPages * WASM_PAGE_BYTES > maxMemoryBytes)
134
+ return `it starts with more memory than a module may have (${maxMemoryBytes} bytes)`;
135
+ return compiled;
136
+ }
137
+ const TIMED_CALL = new vm.Script('__gsRun()');
138
+ const TIMEOUT_CODE = 'ERR_SCRIPT_EXECUTION_TIMEOUT';
139
+ /** One sandbox's modules, instantiated when first used and called within a time budget. */
140
+ export class WasmInstances {
141
+ setup;
142
+ onStopped;
143
+ instances = new Map();
144
+ /* the timed script's global object: createContext makes this object the context */
145
+ global = {};
146
+ context = vm.createContext(this.global);
147
+ stopped = null;
148
+ allowed;
149
+ constructor(setup,
150
+ /** called once when a module overran its budget and was stopped */
151
+ onStopped) {
152
+ this.setup = setup;
153
+ this.onStopped = onStopped;
154
+ this.allowed = wasmImportNames(setup.functions);
155
+ }
156
+ /** Calls export `fn` of `file` with numbers; its number result (undefined for none). */
157
+ call(file, fn, args, ms) {
158
+ return this.timed(ms, `${file} ${fn}`, () => {
159
+ const { exports } = this.instance(file);
160
+ const exported = exports[fn];
161
+ /* an exports object has no prototype, so only its own names are found */
162
+ if (typeof exported !== 'function')
163
+ throw new Error(`${file} exports no function ${fn}`);
164
+ return numberResult(file, fn, Reflect.apply(exported, undefined, args));
165
+ });
166
+ }
167
+ /** A copy of `length` bytes of `file`'s memory from `ptr`. */
168
+ read(file, ptr, length, ms) {
169
+ /* the copy lands in the interpreter's heap outside its memory limit, like an input read */
170
+ if (length > this.setup.maxReadBytes)
171
+ throw new Error(`a WebAssembly read of ${length} bytes is over the limit`);
172
+ return this.timed(ms, file, () => this.range(file, ptr, length).slice());
173
+ }
174
+ write(file, ptr, bytes, ms) {
175
+ this.timed(ms, file, () => this.range(file, ptr, bytes.length).set(bytes));
176
+ }
177
+ memoryBytes(file, ms) {
178
+ return this.timed(ms, file, () => this.memoryOf(file).buffer.byteLength);
179
+ }
180
+ memoryOf(file) {
181
+ const { memory } = this.instance(file);
182
+ if (!memory)
183
+ throw new Error(`${file} has no memory (it imports no env.memory)`);
184
+ return memory;
185
+ }
186
+ range(file, ptr, length) {
187
+ const memory = new Uint8Array(this.memoryOf(file).buffer);
188
+ if (!Number.isInteger(ptr) || !Number.isInteger(length) || ptr < 0 || length < 0)
189
+ throw new Error('a memory range needs a whole-number pointer and length');
190
+ if (ptr + length > memory.length)
191
+ throw new Error(`a range past the end of ${file}'s memory`);
192
+ return memory.subarray(ptr, ptr + length);
193
+ }
194
+ instance(file) {
195
+ const existing = this.instances.get(file);
196
+ if (existing)
197
+ return existing;
198
+ const found = this.setup.modules.find(m => m.file === file);
199
+ if (!found)
200
+ throw new Error(`the plugin bundles no WebAssembly module ${file}`);
201
+ const { maxMemoryBytes } = this.setup;
202
+ const compiled = checkedModule(found.bytes, this.allowed, maxMemoryBytes);
203
+ if (typeof compiled === 'string')
204
+ throw new Error(`${file}: ${compiled}`);
205
+ const limits = memoryLayout(found.bytes).imported;
206
+ if (limits === 'unsupported')
207
+ throw new Error(`${file}: its memory is shared or 64-bit`);
208
+ const capPages = Math.floor(maxMemoryBytes / WASM_PAGE_BYTES);
209
+ const memory = limits
210
+ ? new WebAssembly.Memory({
211
+ initial: limits.minPages,
212
+ maximum: Math.min(capPages, limits.maxPages ?? capPages),
213
+ })
214
+ : null;
215
+ const view = () => {
216
+ if (!memory)
217
+ throw new Error(`${file} has no memory (it imports no env.memory)`);
218
+ return new Uint8Array(memory.buffer);
219
+ };
220
+ const imports = {
221
+ [MEMORY_MODULE]: memory ? { [MEMORY_NAME]: memory } : {},
222
+ [WASM_HOST_MODULE]: this.setup.functions(view),
223
+ };
224
+ const instance = new WebAssembly.Instance(compiled, imports);
225
+ const made = { exports: instance.exports, memory };
226
+ this.instances.set(file, made);
227
+ return made;
228
+ }
229
+ /* `run` with a watchdog: past `ms` V8 is stopped wherever it is, even inside a loop with no
230
+ * calls in it, and the error comes back here */
231
+ timed(ms, what, run) {
232
+ if (this.stopped)
233
+ throw new Error(`WebAssembly is switched off: ${this.stopped}`);
234
+ const timeout = Math.ceil(ms);
235
+ if (timeout < 1)
236
+ throw new Error(`no time left in the budget for ${what}`);
237
+ const results = [];
238
+ this.global.__gsRun = () => {
239
+ results.push({ value: run() });
240
+ };
241
+ try {
242
+ TIMED_CALL.runInContext(this.context, { timeout });
243
+ }
244
+ catch (e) {
245
+ /* Node marks its watchdog's error by this code (checked by shape: the error can come
246
+ * from another realm) */
247
+ if (typeof e === 'object' && e !== null && 'code' in e && e.code === TIMEOUT_CODE) {
248
+ this.stopped = `${what} ran past its ${timeout} ms budget and was stopped`;
249
+ this.instances.clear();
250
+ this.onStopped(this.stopped);
251
+ throw new Error(this.stopped);
252
+ }
253
+ throw e;
254
+ }
255
+ finally {
256
+ this.global.__gsRun = undefined;
257
+ }
258
+ const [result] = results;
259
+ if (!result)
260
+ throw new Error(`${what} returned nothing`);
261
+ return result.value;
262
+ }
263
+ }
264
+ function numberResult(file, fn, value) {
265
+ if (typeof value === 'number' || value === undefined)
266
+ return value;
267
+ if (typeof value === 'bigint' && Number.isSafeInteger(Number(value)))
268
+ return Number(value);
269
+ throw new Error(`${file} ${fn} returned something other than a number`);
270
+ }
@@ -1,3 +1,4 @@
1
1
  export * from './contract.js';
2
2
  export * from './seqlock.js';
3
3
  export * from './sandbox-guest.js';
4
+ export * from './wasm.js';
@@ -1,9 +1,10 @@
1
1
  /*
2
2
  * `@gameslate/sdk/plugin`: what a plugin's code builds against. The contract (GamePlugin,
3
3
  * GameMemory, AssetExtractor, PluginModule), pure helpers, and the sandbox's guest side
4
- * (`exposeToHost`, `exposeAssetsToHost`). No Node APIs: plugin bundles run in the core's QuickJS
5
- * sandbox.
4
+ * (`exposeToHost`, `exposeAssetsToHost`, `wasmModule`). No Node APIs: plugin bundles run in the
5
+ * core's QuickJS sandbox.
6
6
  */
7
7
  export * from './contract.js';
8
8
  export * from './seqlock.js';
9
9
  export * from './sandbox-guest.js';
10
+ export * from './wasm.js';
@@ -99,6 +99,7 @@ function inputFiles(host, json) {
99
99
  return files.map(f => ({
100
100
  name: f.name,
101
101
  size: f.size,
102
+ handle: f.handle,
102
103
  read: (offset, length) => new Uint8Array(host.inputRead(f.handle, offset, length)),
103
104
  }));
104
105
  }
@@ -0,0 +1,17 @@
1
+ import type { SandboxWasmHostApi } from '../index.js';
2
+ declare global {
3
+ var __gsWasm: SandboxWasmHostApi | undefined;
4
+ }
5
+ export interface WasmModule {
6
+ /** calls an export with numbers (i32, f32, f64; i64 results come back as numbers) */
7
+ call(fn: string, ...args: number[]): number | undefined;
8
+ /** a copy of `length` bytes of the module's memory from `ptr` */
9
+ read(ptr: number, length: number): Uint8Array;
10
+ /** copies `bytes` into the module's memory at `ptr` */
11
+ write(ptr: number, bytes: Uint8Array): void;
12
+ /** the module's memory size now, in bytes */
13
+ memoryBytes(): number;
14
+ }
15
+ /** The module the manifest lists as `file` (`palette.wasm`), as `gameslate-plugin build` copied
16
+ * it from the plugin's `wasm/` folder. */
17
+ export declare function wasmModule(file: string): WasmModule;
@@ -0,0 +1,17 @@
1
+ /** The module the manifest lists as `file` (`palette.wasm`), as `gameslate-plugin build` copied
2
+ * it from the plugin's `wasm/` folder. */
3
+ export function wasmModule(file) {
4
+ const host = () => {
5
+ const bridge = globalThis.__gsWasm;
6
+ if (!bridge)
7
+ throw new Error('the core gave no WebAssembly capability');
8
+ return bridge;
9
+ };
10
+ return {
11
+ call: (fn, ...args) => host().call(file, fn, ...args),
12
+ read: (ptr, length) => new Uint8Array(host().read(file, ptr, length)),
13
+ /* an exact-size copy, so only these bytes cross */
14
+ write: (ptr, bytes) => host().write(file, ptr, bytes.slice().buffer),
15
+ memoryBytes: () => host().memoryBytes(file),
16
+ };
17
+ }
@@ -53,6 +53,23 @@ export declare const GameBuildSchema: z.ZodObject<{
53
53
  name: string;
54
54
  }>;
55
55
  export type GameBuild = z.infer<typeof GameBuildSchema>;
56
+ /** How many WebAssembly modules one plugin may bundle (each gets its own capped memory). */
57
+ export declare const MAX_WASM_MODULES = 4;
58
+ /**
59
+ * A WebAssembly module the plugin bundles ("Closing the sandbox" item 3): its code calls the
60
+ * module's exports through `wasmModule(file)` and the core runs it with no imports but the
61
+ * sandbox's allow-list (src/host/wasm-host.ts).
62
+ */
63
+ export declare const WasmFileSchema: z.ZodObject<{
64
+ file: z.ZodString;
65
+ sha256: z.ZodString;
66
+ }, "strict", z.ZodTypeAny, {
67
+ file: string;
68
+ sha256: string;
69
+ }, {
70
+ file: string;
71
+ sha256: string;
72
+ }>;
56
73
  /** major.minor.patch, the only form `compareVersions` orders. */
57
74
  export declare const PluginVersionSchema: z.ZodString;
58
75
  /** The release zip a published manifest names: its URL (absolute, or relative to the URL the
@@ -97,6 +114,23 @@ export declare const PluginManifestSchema: z.ZodEffects<z.ZodObject<{
97
114
  file: string;
98
115
  sha256: string;
99
116
  }>>;
117
+ /** WebAssembly modules the live and asset code may call, pinned like the code files */
118
+ wasm: z.ZodOptional<z.ZodEffects<z.ZodArray<z.ZodObject<{
119
+ file: z.ZodString;
120
+ sha256: z.ZodString;
121
+ }, "strict", z.ZodTypeAny, {
122
+ file: string;
123
+ sha256: string;
124
+ }, {
125
+ file: string;
126
+ sha256: string;
127
+ }>, "many">, {
128
+ file: string;
129
+ sha256: string;
130
+ }[], {
131
+ file: string;
132
+ sha256: string;
133
+ }[]>>;
100
134
  games: z.ZodArray<z.ZodObject<{
101
135
  id: z.ZodString;
102
136
  title: z.ZodString;
@@ -241,6 +275,10 @@ export declare const PluginManifestSchema: z.ZodEffects<z.ZodObject<{
241
275
  file: string;
242
276
  sha256: string;
243
277
  } | undefined;
278
+ wasm?: {
279
+ file: string;
280
+ sha256: string;
281
+ }[] | undefined;
244
282
  bundle?: {
245
283
  url: string;
246
284
  sha256: string;
@@ -278,6 +316,10 @@ export declare const PluginManifestSchema: z.ZodEffects<z.ZodObject<{
278
316
  sha256: string;
279
317
  } | undefined;
280
318
  testedWith?: string[] | undefined;
319
+ wasm?: {
320
+ file: string;
321
+ sha256: string;
322
+ }[] | undefined;
281
323
  bundle?: {
282
324
  url: string;
283
325
  sha256: string;
@@ -315,6 +357,10 @@ export declare const PluginManifestSchema: z.ZodEffects<z.ZodObject<{
315
357
  file: string;
316
358
  sha256: string;
317
359
  } | undefined;
360
+ wasm?: {
361
+ file: string;
362
+ sha256: string;
363
+ }[] | undefined;
318
364
  bundle?: {
319
365
  url: string;
320
366
  sha256: string;
@@ -352,6 +398,10 @@ export declare const PluginManifestSchema: z.ZodEffects<z.ZodObject<{
352
398
  sha256: string;
353
399
  } | undefined;
354
400
  testedWith?: string[] | undefined;
401
+ wasm?: {
402
+ file: string;
403
+ sha256: string;
404
+ }[] | undefined;
355
405
  bundle?: {
356
406
  url: string;
357
407
  sha256: string;
@@ -123,6 +123,19 @@ const CodeFile = z.object({
123
123
  file: FileName,
124
124
  sha256: Sha256,
125
125
  });
126
+ /** How many WebAssembly modules one plugin may bundle (each gets its own capped memory). */
127
+ export const MAX_WASM_MODULES = 4;
128
+ /**
129
+ * A WebAssembly module the plugin bundles ("Closing the sandbox" item 3): its code calls the
130
+ * module's exports through `wasmModule(file)` and the core runs it with no imports but the
131
+ * sandbox's allow-list (src/host/wasm-host.ts).
132
+ */
133
+ export const WasmFileSchema = z
134
+ .object({
135
+ file: FileName.regex(/\.wasm$/, 'a WebAssembly module is a .wasm file'),
136
+ sha256: Sha256,
137
+ })
138
+ .strict();
126
139
  /** major.minor.patch, the only form `compareVersions` orders. */
127
140
  export const PluginVersionSchema = z
128
141
  .string()
@@ -145,6 +158,12 @@ export const PluginManifestSchema = z
145
158
  code: CodeFile,
146
159
  /** asset extractors, run in the core's sandbox by extraction jobs */
147
160
  assets: CodeFile.optional(),
161
+ /** WebAssembly modules the live and asset code may call, pinned like the code files */
162
+ wasm: z
163
+ .array(WasmFileSchema)
164
+ .max(MAX_WASM_MODULES)
165
+ .refine(ws => new Set(ws.map(w => w.file)).size === ws.length, 'each WebAssembly file is listed once')
166
+ .optional(),
148
167
  games: z
149
168
  .array(z
150
169
  .object({
@@ -1523,3 +1523,15 @@ export interface SandboxAssetsHostApi {
1523
1523
  /** hands the core a block of output bytes; the index outputs refer to it by */
1524
1524
  emitBinary(data: ArrayBuffer): number;
1525
1525
  }
1526
+ /** The core's bridge to the plugin's own WebAssembly modules, on `globalThis.__gsWasm` (in both
1527
+ * sandboxes, when the manifest lists modules). Modules are named by their file name. */
1528
+ export interface SandboxWasmHostApi {
1529
+ /** calls an export with numbers; its number result, or undefined for none */
1530
+ call(file: string, fn: string, ...args: number[]): number | undefined;
1531
+ /** a copy of `length` bytes of the module's memory from `ptr` */
1532
+ read(file: string, ptr: number, length: number): ArrayBuffer;
1533
+ /** copies `data` into the module's memory at `ptr` */
1534
+ write(file: string, ptr: number, data: ArrayBuffer): void;
1535
+ /** the module's memory size now, in bytes */
1536
+ memoryBytes(file: string): number;
1537
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gameslate/sdk",
3
- "version": "0.3.21",
3
+ "version": "0.3.22",
4
4
  "description": "Build plugins for GameSlate, the second-screen companion for PC games: the plugin contract, game-state and catalogue schemas, and the plugin builder.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -118,6 +118,14 @@ every player confirm the update. The core (and `validate`) refuses live code tha
118
118
  the manifest doesn't list. A manifest without `builds` still loads, with a permission naming only
119
119
  the game; declare them anyway, since that leniency is for releases built before 0.3.21.
120
120
 
121
+ Read each name from the build itself, never from memory. An N64 ROM's name is its header's own
122
+ title (bytes `0x20`-`0x33`, trimmed), which often differs from the box: `STARFOX64`,
123
+ `CASTLEVANIA2`, `Silicon Valley`. For a revision you have no ROM of (one the decomp builds but
124
+ nobody has dumped here), use the decomp's own name for that ROM and say so in the commit. And
125
+ `validate` checks only one way (every build the code matches is listed): add a test that the
126
+ manifest lists no build that no source matches, since a stray build still asks every player
127
+ (gameslate-n64's `plugin/manifest.test.ts`).
128
+
121
129
  **Memory is read only from games launched through GameSlate.** The core reads a process only
122
130
  when it descends from a `gameslate run --` launch wrapper that is connected to the daemon
123
131
  (Steam launch options `~/.local/bin/gameslate run -- %command%`, or `n64-gameslate` for
@@ -347,6 +355,50 @@ Every image of a game uses one format. In the sandbox:
347
355
  - **Data licensing:** ship the extractor, never its output. Textures, models and renders are
348
356
  built on the player's machine and never committed.
349
357
 
358
+ ### WebAssembly for hot loops (sdk 0.3.22)
359
+
360
+ QuickJS interprets: a tight pixel or decompression loop runs 20–150× slower than in V8 (the
361
+ core's palette-to-RGBA demonstration: 1330 ms against 10 ms for 16 M pixels). When a build is
362
+ slow, move the loop into a WebAssembly module the plugin bundles:
363
+
364
+ - **Build it in the plugin repo, with a toolchain the repo owns,** into `plugin/wasm/<name>.wasm`
365
+ (a `yarn build:wasm` script, run before `yarn build`). Commit the source; git-ignore
366
+ `plugin/wasm/` and have CI and the release build it, so the shipped binary is the one the
367
+ source makes. The folder holds built modules only: anything else fails the build. `gameslate-plugin build` copies every `wasm/*.wasm`
368
+ beside `live.js`, refuses one that isn't valid WebAssembly, and lists each in the manifest's
369
+ `wasm` with its sha256. Up to 4 modules, 8 MB each.
370
+ - **Imports: `env.memory` and the sandbox's capabilities only.** The core refuses a module that
371
+ imports anything else (WASI, `env.abort`, a global or a table) or defines its own memory. Link
372
+ so the memory is imported:
373
+ - Rust: `--target wasm32-unknown-unknown`, `-C link-arg=--import-memory`, no `std` I/O; import
374
+ capabilities in an `extern "C"` block under `#[link(wasm_import_module = "gameslate")]`
375
+ (`fn input_read(handle: i32, offset: i64, length: i32, ptr: i32);`).
376
+ - C (clang): `--target=wasm32 -nostdlib -Wl,--no-entry -Wl,--export-dynamic
377
+ -Wl,--import-memory`; declare `__attribute__((import_module("gameslate"),
378
+ import_name("input_read")))`.
379
+ - AssemblyScript: `--importMemory --runtime stub --use abort=` (its default `env.abort` import
380
+ is refused); `@external("gameslate", "input_read") declare function input_read(...)`.
381
+ - **Capabilities:** asset code's modules may import `gameslate.input_read(handle: i32, offset:
382
+ i64, length: i32, ptr: i32)`, which reads an input range (64 MB at most) straight into the
383
+ module's memory; the handle is `InputFile.handle`. Live code's modules import nothing.
384
+ - **Memory:** the core creates it with a maximum of 1 GB (asset code) or 16 MB (live code), or
385
+ the module's own smaller maximum. `memory.grow` past it returns -1. Declare a starting size
386
+ (`--initial-memory`) big enough for your buffers, or grow it yourself.
387
+ - **Calling it:** `wasmModule('<name>.wasm')` from `@gameslate/sdk/plugin` gives `call(fn,
388
+ ...numbers)`, `write(ptr, bytes)`, `read(ptr, length)` (at most 64 MB, 16 MB in live code) and
389
+ `memoryBytes()`. Only numbers cross
390
+ (i32/f32/f64 arguments; an i64 result comes back as a number). Each call costs about 0.5 ms (a
391
+ watchdog guards it), so call once per buffer or per asset, never per pixel. Big inputs: let
392
+ the module read them with `input_read` instead of `write`-ing them through the interpreter.
393
+ - **Budget:** a call shares the guest call's time budget; a module still running at the deadline
394
+ is stopped mid-loop and the sandbox switches off (the asset fails, the next gets a fresh one).
395
+ - **Licence:** the module's source is code like any other: port only MIT/BSD/CC0 code into it
396
+ (see "Read the decomp's licence" under Pitfalls). Compilers drop the `/*! Derived from … */`
397
+ header, so the notice that ships is the repo's `THIRD_PARTY_NOTICES.md` (copied into every
398
+ build): list the ported source and every crate or C library linked into the module there
399
+ (`cargo about` can generate it). A game's own native library (a proprietary
400
+ decompressor DLL) can't be loaded this way.
401
+
350
402
  ### Registry data: what the plugin commits
351
403
 
352
404
  A plugin carries its games' committed map data in `plugin/registry/games/<gameId>/` (sdk 0.3.17):
@@ -7,8 +7,8 @@ jobs:
7
7
  check:
8
8
  runs-on: ubuntu-latest
9
9
  steps:
10
- - uses: actions/checkout@v4
11
- - uses: actions/setup-node@v4
10
+ - uses: actions/checkout@v7
11
+ - uses: actions/setup-node@v7
12
12
  with:
13
13
  node-version: 22
14
14
  - run: corepack enable
@@ -16,8 +16,8 @@ jobs:
16
16
  release:
17
17
  runs-on: ubuntu-latest
18
18
  steps:
19
- - uses: actions/checkout@v4
20
- - uses: actions/setup-node@v4
19
+ - uses: actions/checkout@v7
20
+ - uses: actions/setup-node@v7
21
21
  with:
22
22
  node-version: 22
23
23
  - run: corepack enable