space-data-module-sdk 0.10.4 → 0.11.0

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,579 @@
1
+ // The manifest a module's SIGNED CODE carries, and the rule that binds the
2
+ // trailer's copy to it.
3
+ //
4
+ // The one signature form (SDN-MODULE-PUBLICATION-V1) covers the bytes before
5
+ // the `$REC` trailer. The SDK's bundle writer moves the `sds.manifest` custom
6
+ // section out of the wasm and into the trailer's MBL `manifest` entry, so in a
7
+ // signed file that copy is NOT covered by the signature. The code carries its
8
+ // own copy: the manifest the export `plugin_get_manifest_flatbuffer` returns
9
+ // (with `plugin_get_manifest_flatbuffer_size`), which lives in the module's
10
+ // data and is covered. A reader that needs a module's manifest takes it from
11
+ // the code, and an artifact whose trailer copy is not byte for byte the code's
12
+ // copy is refused by name.
13
+ //
14
+ // Browser-safe: no Node imports.
15
+
16
+ import {
17
+ DEFAULT_MANIFEST_EXPORT_SYMBOL,
18
+ DEFAULT_MANIFEST_SIZE_SYMBOL,
19
+ SDS_MANIFEST_SECTION_NAME,
20
+ } from "./constants.js";
21
+ import { ModuleSignatureError } from "./signing.js";
22
+ import {
23
+ decodeUnsignedLeb128,
24
+ getWasmCustomSections,
25
+ parseWasmModuleSections,
26
+ } from "./wasm.js";
27
+ import { extractPublicationRecordCollection } from "../transport/records.js";
28
+
29
+ const textDecoder = new TextDecoder();
30
+
31
+ function asBytes(value) {
32
+ if (value instanceof Uint8Array) return value;
33
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
34
+ if (ArrayBuffer.isView(value)) {
35
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
36
+ }
37
+ return new Uint8Array(value ?? []);
38
+ }
39
+
40
+ function equalBytes(a, b) {
41
+ if (a.length !== b.length) return false;
42
+ for (let i = 0; i < a.length; i += 1) {
43
+ if (a[i] !== b[i]) return false;
44
+ }
45
+ return true;
46
+ }
47
+
48
+ /**
49
+ * The trailer's (unsigned) manifest entry, or null. Reported, never trusted.
50
+ * @param {Uint8Array|ArrayBuffer} artifactBytes
51
+ * @returns {Uint8Array|null}
52
+ */
53
+ export function readTrailerManifestBytes(artifactBytes) {
54
+ const publication = extractPublicationRecordCollection(asBytes(artifactBytes));
55
+ for (const entry of publication?.mbl?.entries ?? []) {
56
+ if (
57
+ entry?.entryId === "manifest" ||
58
+ entry?.sectionName === SDS_MANIFEST_SECTION_NAME
59
+ ) {
60
+ return asBytes(entry.payload).slice();
61
+ }
62
+ }
63
+ return null;
64
+ }
65
+
66
+ /**
67
+ * The manifest a running instance returns from its manifest exports, or null
68
+ * when it has none.
69
+ * @param {WebAssembly.Instance} instance
70
+ * @param {WebAssembly.Memory} [memory] the instance's memory, when imported
71
+ * @returns {Uint8Array|null}
72
+ */
73
+ export function readInstanceManifestBytes(instance, memory) {
74
+ const exports = instance?.exports ?? {};
75
+ const getBytes = exports[DEFAULT_MANIFEST_EXPORT_SYMBOL];
76
+ const getSize = exports[DEFAULT_MANIFEST_SIZE_SYMBOL];
77
+ if (typeof getBytes !== "function" || typeof getSize !== "function") {
78
+ return null;
79
+ }
80
+ const mem =
81
+ exports.memory instanceof WebAssembly.Memory ? exports.memory : memory;
82
+ if (!(mem instanceof WebAssembly.Memory)) return null;
83
+ const ptr = Number(getBytes()) >>> 0;
84
+ const size = Number(getSize()) >>> 0;
85
+ if (!ptr || !size || ptr + size > mem.buffer.byteLength) return null;
86
+ return new Uint8Array(mem.buffer, ptr, size).slice();
87
+ }
88
+
89
+ // ---- a minimal instantiation of the signed code, to ask it for its manifest --
90
+ //
91
+ // Every import is a stand-in: a function that throws if called, and a memory,
92
+ // table or global of the declared shape. Nothing the module does here reaches
93
+ // a host. The manifest exports return a pointer into the module's own data,
94
+ // which instantiation (including the start function that copies passive data
95
+ // segments into memory) has already written.
96
+
97
+ const VALUE_TYPES = {
98
+ 0x7f: ["i32", 0],
99
+ 0x7e: ["i64", 0n],
100
+ 0x7d: ["f32", 0],
101
+ 0x7c: ["f64", 0],
102
+ 0x70: ["anyfunc", null],
103
+ 0x6f: ["externref", null],
104
+ };
105
+
106
+ function readName(bytes, offset) {
107
+ const length = decodeUnsignedLeb128(bytes, offset);
108
+ const start = length.nextOffset;
109
+ const end = start + length.value;
110
+ return { value: textDecoder.decode(bytes.subarray(start, end)), nextOffset: end };
111
+ }
112
+
113
+ function readLimits(bytes, offset) {
114
+ const flags = bytes[offset];
115
+ let cursor = offset + 1;
116
+ if (flags & 0x04) {
117
+ throw new Error("64-bit memory limits are not read here");
118
+ }
119
+ const initial = decodeUnsignedLeb128(bytes, cursor);
120
+ cursor = initial.nextOffset;
121
+ let maximum;
122
+ if (flags & 0x01) {
123
+ const max = decodeUnsignedLeb128(bytes, cursor);
124
+ maximum = max.value;
125
+ cursor = max.nextOffset;
126
+ }
127
+ return {
128
+ initial: initial.value,
129
+ maximum,
130
+ shared: Boolean(flags & 0x02),
131
+ nextOffset: cursor,
132
+ };
133
+ }
134
+
135
+ function stubImports(portableBytes) {
136
+ const parsed = parseWasmModuleSections(portableBytes);
137
+ const imports = {};
138
+ let importedMemory = null;
139
+ const trap = (moduleName, fieldName) => () => {
140
+ throw new Error(
141
+ `manifest read: import ${moduleName}.${fieldName} is not available while reading the code's manifest`,
142
+ );
143
+ };
144
+ for (const section of parsed.sections) {
145
+ if (section.id !== 2) continue;
146
+ const bytes = parsed.bytes.subarray(section.payloadStart, section.payloadEnd);
147
+ const count = decodeUnsignedLeb128(bytes, 0);
148
+ let cursor = count.nextOffset;
149
+ for (let index = 0; index < count.value; index += 1) {
150
+ const moduleName = readName(bytes, cursor);
151
+ const fieldName = readName(bytes, moduleName.nextOffset);
152
+ cursor = fieldName.nextOffset;
153
+ const kind = bytes[cursor++];
154
+ const target = (imports[moduleName.value] ??= {});
155
+ if (kind === 0x00) {
156
+ cursor = decodeUnsignedLeb128(bytes, cursor).nextOffset;
157
+ target[fieldName.value] = trap(moduleName.value, fieldName.value);
158
+ } else if (kind === 0x01) {
159
+ const refType = bytes[cursor++];
160
+ const limits = readLimits(bytes, cursor);
161
+ cursor = limits.nextOffset;
162
+ target[fieldName.value] = new WebAssembly.Table({
163
+ element: refType === 0x70 ? "anyfunc" : "externref",
164
+ initial: limits.initial,
165
+ ...(limits.maximum !== undefined ? { maximum: limits.maximum } : {}),
166
+ });
167
+ } else if (kind === 0x02) {
168
+ const limits = readLimits(bytes, cursor);
169
+ cursor = limits.nextOffset;
170
+ const memory = new WebAssembly.Memory({
171
+ initial: limits.initial,
172
+ ...(limits.maximum !== undefined ? { maximum: limits.maximum } : {}),
173
+ ...(limits.shared ? { shared: true } : {}),
174
+ });
175
+ importedMemory ??= memory;
176
+ target[fieldName.value] = memory;
177
+ } else if (kind === 0x03) {
178
+ const valueType = VALUE_TYPES[bytes[cursor++]];
179
+ const mutable = bytes[cursor++] === 0x01;
180
+ if (!valueType) throw new Error("unknown global import type");
181
+ target[fieldName.value] = new WebAssembly.Global(
182
+ { value: valueType[0], mutable },
183
+ valueType[1],
184
+ );
185
+ } else {
186
+ throw new Error(`import kind ${kind} is not read here`);
187
+ }
188
+ }
189
+ }
190
+ return { imports, importedMemory };
191
+ }
192
+
193
+ // ---- the manifest exports answered WITHOUT running the code ----------------
194
+ //
195
+ // An SDK-built module's two manifest exports are constants: each body is
196
+ // `i32.const N; end` (no locals). Their answer is then read from the module's
197
+ // data image: the active data segments at their constant offsets, and the
198
+ // passive segments that the start function copies with the linker's
199
+ // `i32.const dst; i32.const 0; i32.const len; memory.init seg 0` sequence (a
200
+ // shared-memory build's `__wasm_init_memory`). Nothing is instantiated, no
201
+ // memory is allocated beyond the answer, no start function runs.
202
+
203
+ const STATIC_MANIFEST_MAX_BYTES = 16 * 1024 * 1024;
204
+
205
+ function decodeSignedLeb128I32(bytes, offset) {
206
+ let result = 0;
207
+ let shift = 0;
208
+ let cursor = offset;
209
+ let byte;
210
+ do {
211
+ if (cursor >= bytes.length || shift > 35) return null;
212
+ byte = bytes[cursor++];
213
+ result |= (byte & 0x7f) << shift;
214
+ shift += 7;
215
+ } while (byte & 0x80);
216
+ if (shift < 32 && byte & 0x40) result |= -1 << shift;
217
+ return { value: result | 0, nextOffset: cursor };
218
+ }
219
+
220
+ function skipLimits(bytes, cursor) {
221
+ const flags = bytes[cursor++];
222
+ cursor = decodeUnsignedLeb128(bytes, cursor).nextOffset;
223
+ if (flags & 0x01) cursor = decodeUnsignedLeb128(bytes, cursor).nextOffset;
224
+ return cursor;
225
+ }
226
+
227
+ function sectionVector(parsed, id) {
228
+ const section = parsed.sections.find((entry) => entry.id === id);
229
+ if (!section) return null;
230
+ return parsed.bytes.subarray(section.payloadStart, section.payloadEnd);
231
+ }
232
+
233
+ function countImportedFunctions(bytes) {
234
+ if (!bytes) return 0;
235
+ const count = decodeUnsignedLeb128(bytes, 0);
236
+ let cursor = count.nextOffset;
237
+ let functions = 0;
238
+ for (let index = 0; index < count.value; index += 1) {
239
+ cursor = readName(bytes, readName(bytes, cursor).nextOffset).nextOffset;
240
+ const kind = bytes[cursor++];
241
+ if (kind === 0x00) {
242
+ functions += 1;
243
+ cursor = decodeUnsignedLeb128(bytes, cursor).nextOffset;
244
+ } else if (kind === 0x01) {
245
+ cursor = skipLimits(bytes, cursor + 1);
246
+ } else if (kind === 0x02) {
247
+ cursor = skipLimits(bytes, cursor);
248
+ } else if (kind === 0x03) {
249
+ cursor += 2;
250
+ } else if (kind === 0x04) {
251
+ cursor = decodeUnsignedLeb128(bytes, cursor + 1).nextOffset;
252
+ } else {
253
+ throw new Error(`import kind ${kind} is not read here`);
254
+ }
255
+ }
256
+ return functions;
257
+ }
258
+
259
+ function exportedIndex(bytes, name, wantedKind) {
260
+ if (!bytes) return null;
261
+ const count = decodeUnsignedLeb128(bytes, 0);
262
+ let cursor = count.nextOffset;
263
+ for (let index = 0; index < count.value; index += 1) {
264
+ const exportName = readName(bytes, cursor);
265
+ const kind = bytes[exportName.nextOffset];
266
+ const target = decodeUnsignedLeb128(bytes, exportName.nextOffset + 1);
267
+ cursor = target.nextOffset;
268
+ if (exportName.value === name) return kind === wantedKind ? target.value : null;
269
+ }
270
+ return null;
271
+ }
272
+
273
+ const exportedFunctionIndex = (bytes, name) => exportedIndex(bytes, name, 0x00);
274
+
275
+ function functionBody(codeBytes, definedIndex) {
276
+ if (!codeBytes || definedIndex < 0) return null;
277
+ const count = decodeUnsignedLeb128(codeBytes, 0);
278
+ if (definedIndex >= count.value) return null;
279
+ let cursor = count.nextOffset;
280
+ for (let index = 0; index < count.value; index += 1) {
281
+ const size = decodeUnsignedLeb128(codeBytes, cursor);
282
+ const end = size.nextOffset + size.value;
283
+ if (end > codeBytes.length) return null;
284
+ if (index === definedIndex) return codeBytes.subarray(size.nextOffset, end);
285
+ cursor = end;
286
+ }
287
+ return null;
288
+ }
289
+
290
+ // A body that is exactly `(no locals) i32.const N end`: its unsigned value.
291
+ function constantI32Body(body) {
292
+ if (!body || body.length < 3 || body[0] !== 0x00 || body[1] !== 0x41) return null;
293
+ const value = decodeSignedLeb128I32(body, 2);
294
+ if (!value || value.nextOffset !== body.length - 1 || body[value.nextOffset] !== 0x0b) {
295
+ return null;
296
+ }
297
+ return value.value >>> 0;
298
+ }
299
+
300
+ function constantI32Expression(bytes, cursor) {
301
+ if (bytes[cursor] !== 0x41) return null;
302
+ const value = decodeSignedLeb128I32(bytes, cursor + 1);
303
+ if (!value || bytes[value.nextOffset] !== 0x0b) return null;
304
+ return { value: value.value >>> 0, nextOffset: value.nextOffset + 1 };
305
+ }
306
+
307
+ // Each data segment with its constant placement (null when it has none).
308
+ function dataSegments(bytes) {
309
+ if (!bytes) return [];
310
+ const count = decodeUnsignedLeb128(bytes, 0);
311
+ let cursor = count.nextOffset;
312
+ const segments = [];
313
+ for (let index = 0; index < count.value; index += 1) {
314
+ const flags = decodeUnsignedLeb128(bytes, cursor);
315
+ cursor = flags.nextOffset;
316
+ let offset = null;
317
+ let passive = false;
318
+ let memory = 0;
319
+ if (flags.value === 1) {
320
+ passive = true;
321
+ } else if (flags.value === 0 || flags.value === 2) {
322
+ if (flags.value === 2) {
323
+ const memoryIndex = decodeUnsignedLeb128(bytes, cursor);
324
+ memory = memoryIndex.value;
325
+ cursor = memoryIndex.nextOffset;
326
+ }
327
+ const expression = constantI32Expression(bytes, cursor);
328
+ if (!expression) return null;
329
+ offset = expression.value;
330
+ cursor = expression.nextOffset;
331
+ } else {
332
+ return null;
333
+ }
334
+ const size = decodeUnsignedLeb128(bytes, cursor);
335
+ const start = size.nextOffset;
336
+ const end = start + size.value;
337
+ if (end > bytes.length) return null;
338
+ segments.push({ offset, passive, memory, bytes: bytes.subarray(start, end) });
339
+ cursor = end;
340
+ }
341
+ return segments;
342
+ }
343
+
344
+ // The start function's linker sequences (a shared-memory build's
345
+ // `__wasm_init_memory`, after Binaryen's memory packing):
346
+ // `i32.const dst; i32.const 0; i32.const len; memory.init seg 0` places a
347
+ // passive segment, and
348
+ // `i32.const dst; i32.const 0; i32.const len; memory.fill 0` writes the
349
+ // zero runs the packing took out of the segments.
350
+ // Only copies into `memory` (the memory the manifest is read from) count.
351
+ // Returns the zero-filled ranges.
352
+ function placePassiveSegments(startBody, segments, memory) {
353
+ const zeroRanges = [];
354
+ if (!startBody) return zeroRanges;
355
+ for (let cursor = 0; cursor < startBody.length; cursor += 1) {
356
+ if (startBody[cursor] !== 0x41) continue;
357
+ const dst = decodeSignedLeb128I32(startBody, cursor + 1);
358
+ if (!dst || startBody[dst.nextOffset] !== 0x41) continue;
359
+ const second = decodeSignedLeb128I32(startBody, dst.nextOffset + 1);
360
+ if (!second || second.value !== 0 || startBody[second.nextOffset] !== 0x41) continue;
361
+ const len = decodeSignedLeb128I32(startBody, second.nextOffset + 1);
362
+ if (!len || startBody[len.nextOffset] !== 0xfc) continue;
363
+ const op = startBody[len.nextOffset + 1];
364
+ if (op === 0x0b) {
365
+ if (decodeUnsignedLeb128(startBody, len.nextOffset + 2).value === memory) {
366
+ zeroRanges.push({ offset: dst.value >>> 0, length: len.value >>> 0 });
367
+ }
368
+ continue;
369
+ }
370
+ if (op !== 0x08) continue;
371
+ const segment = decodeUnsignedLeb128(startBody, len.nextOffset + 2);
372
+ if (decodeUnsignedLeb128(startBody, segment.nextOffset).value !== memory) continue;
373
+ const target = segments[segment.value];
374
+ if (
375
+ target?.passive &&
376
+ target.offset === null &&
377
+ len.value >>> 0 === target.bytes.length
378
+ ) {
379
+ target.offset = dst.value >>> 0;
380
+ }
381
+ }
382
+ return zeroRanges;
383
+ }
384
+
385
+ /**
386
+ * The manifest the code's two manifest exports would return, worked out from
387
+ * the bytes alone, or a reason why it cannot be. Never instantiates.
388
+ * @param {Uint8Array} portable - the bytes before the trailer
389
+ * @returns {{bytes: Uint8Array}|{bytes: null, reason: string, exportsManifest: boolean}}
390
+ */
391
+ export function readStaticManifestBytes(portable) {
392
+ const parsed = parseWasmModuleSections(portable);
393
+ const exportsBytes = sectionVector(parsed, 7);
394
+ const getIndex = exportedFunctionIndex(exportsBytes, DEFAULT_MANIFEST_EXPORT_SYMBOL);
395
+ const sizeIndex = exportedFunctionIndex(exportsBytes, DEFAULT_MANIFEST_SIZE_SYMBOL);
396
+ if (getIndex === null || sizeIndex === null) {
397
+ return { bytes: null, reason: "the code exports no manifest", exportsManifest: false };
398
+ }
399
+ const notStatic = (why) => ({
400
+ bytes: null,
401
+ reason: `the code's manifest exports cannot be answered from its bytes alone (${why})`,
402
+ exportsManifest: true,
403
+ });
404
+ const importedFunctions = countImportedFunctions(sectionVector(parsed, 2));
405
+ const code = sectionVector(parsed, 10);
406
+ const ptr = constantI32Body(functionBody(code, getIndex - importedFunctions));
407
+ const size = constantI32Body(functionBody(code, sizeIndex - importedFunctions));
408
+ if (ptr === null || size === null) return notStatic("an export body is not a constant");
409
+ if (!ptr || !size) return notStatic("an export returns zero");
410
+ if (size > STATIC_MANIFEST_MAX_BYTES) return notStatic(`a ${size}-byte manifest`);
411
+ const segments = dataSegments(sectionVector(parsed, 11));
412
+ if (!segments) return notStatic("a data segment has no constant placement");
413
+ // The memory the exports' pointer is read from: the exported `memory`
414
+ // (readInstanceManifestBytes reads that one), else memory 0.
415
+ const memory = exportedIndex(exportsBytes, "memory", 0x02) ?? 0;
416
+ const start = sectionVector(parsed, 8);
417
+ let zeroRanges = [];
418
+ if (start) {
419
+ const startIndex = decodeUnsignedLeb128(start, 0).value;
420
+ zeroRanges = placePassiveSegments(
421
+ functionBody(code, startIndex - importedFunctions),
422
+ segments,
423
+ memory,
424
+ );
425
+ }
426
+ const out = new Uint8Array(size);
427
+ const covered = new Uint8Array(size);
428
+ const end = ptr + size;
429
+ const cover = (offset, length, source) => {
430
+ const from = Math.max(ptr, offset);
431
+ const to = Math.min(end, offset + length);
432
+ if (from >= to) return;
433
+ if (source) out.set(source.subarray(from - offset, to - offset), from - ptr);
434
+ covered.fill(1, from - ptr, to - ptr);
435
+ };
436
+ for (const range of zeroRanges) cover(range.offset, range.length, null);
437
+ for (const segment of segments) {
438
+ // A passive segment has a placement only when the start function copies
439
+ // it into this memory; an active one counts only in this memory.
440
+ if (segment.offset !== null && (segment.passive || segment.memory === memory)) {
441
+ cover(segment.offset, segment.bytes.length, segment.bytes);
442
+ }
443
+ }
444
+ // Without a start function nothing runs before the exports are called, and
445
+ // a fresh memory is zero wherever no segment is placed. With one, every
446
+ // byte of the answer must come from a placed segment or a zero fill it
447
+ // recognizably does: no guess about memory that only running it would write.
448
+ if (start && !covered.every((byte) => byte === 1)) {
449
+ return notStatic("the manifest is not wholly in the data the start function places");
450
+ }
451
+ return { bytes: out };
452
+ }
453
+
454
+ /**
455
+ * The manifest the SIGNED code carries: an `sds.manifest` custom section left
456
+ * in the bytes before the trailer, else what the code's manifest exports
457
+ * return. Never the trailer.
458
+ *
459
+ * The exports are asked of the caller's running instance when one is given;
460
+ * else they are answered from the bytes alone when their bodies are
461
+ * constants (readStaticManifestBytes; the SDK's builds are); else the code
462
+ * is instantiated with stand-in imports ONLY when the caller says its
463
+ * signature was already verified under a policy that requires one
464
+ * (`verifiedSignature: true`). Code nobody verified is never run here: a
465
+ * start function that loops, or a declared memory of 4 GiB, would hang or
466
+ * load the caller's process. Such code is reported as not asked.
467
+ *
468
+ * @param {Uint8Array|ArrayBuffer} artifactBytes - a signed artifact or raw wasm
469
+ * @param {{instance?: WebAssembly.Instance, memory?: WebAssembly.Memory, verifiedSignature?: boolean}} [options]
470
+ * a caller that already runs these bytes passes its instance, which is asked
471
+ * instead; `verifiedSignature: true` allows a stand-in instantiation
472
+ * @returns {Promise<{bytes: Uint8Array, source: "custom-section"|"manifest-export"|"static-exports"}|{bytes: null, source: null, reason: string, notRun?: boolean}>}
473
+ */
474
+ export async function readSignedCodeManifest(artifactBytes, options = {}) {
475
+ const input = asBytes(artifactBytes);
476
+ const publication = extractPublicationRecordCollection(input);
477
+ const portable = publication?.payloadBytes
478
+ ? asBytes(publication.payloadBytes)
479
+ : input;
480
+ let sections = [];
481
+ try {
482
+ sections = getWasmCustomSections(portable, SDS_MANIFEST_SECTION_NAME);
483
+ } catch (error) {
484
+ return { bytes: null, source: null, reason: `not a wasm module: ${error?.message ?? error}` };
485
+ }
486
+ if (sections.length > 0) {
487
+ return { bytes: asBytes(sections[0]).slice(), source: "custom-section" };
488
+ }
489
+ if (options.instance) {
490
+ const bytes = readInstanceManifestBytes(options.instance, options.memory);
491
+ if (bytes) return { bytes, source: "manifest-export" };
492
+ return { bytes: null, source: null, reason: "the code exports no manifest" };
493
+ }
494
+ let staticRead;
495
+ try {
496
+ staticRead = readStaticManifestBytes(portable);
497
+ } catch (error) {
498
+ staticRead = {
499
+ bytes: null,
500
+ reason: `the code's manifest exports cannot be answered from its bytes alone (${error?.message ?? error})`,
501
+ exportsManifest: true,
502
+ };
503
+ }
504
+ if (staticRead.bytes) return { bytes: staticRead.bytes, source: "static-exports" };
505
+ if (!staticRead.exportsManifest) {
506
+ return { bytes: null, source: null, reason: staticRead.reason };
507
+ }
508
+ if (options.verifiedSignature !== true) {
509
+ return {
510
+ bytes: null,
511
+ source: null,
512
+ notRun: true,
513
+ reason: `${staticRead.reason}; the code was not run to ask it, because its signature was not verified under a policy that requires one`,
514
+ };
515
+ }
516
+ try {
517
+ const { imports, importedMemory } = stubImports(portable);
518
+ const { instance } = await WebAssembly.instantiate(portable.slice(), imports);
519
+ const bytes = readInstanceManifestBytes(instance, importedMemory);
520
+ if (bytes) return { bytes, source: "manifest-export" };
521
+ return { bytes: null, source: null, reason: "the code exports no manifest" };
522
+ } catch (error) {
523
+ return {
524
+ bytes: null,
525
+ source: null,
526
+ reason: `the code could not be asked for its manifest: ${error?.message ?? error}`,
527
+ };
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Bind the trailer's manifest copy to the code's. Returns the code's manifest
533
+ * bytes (null when the code carries none and the trailer carries none).
534
+ *
535
+ * Refused by name:
536
+ * - `trailer_manifest_mismatch`: the trailer's copy is not byte for byte the
537
+ * code's copy (the trailer was changed after signing, or never matched).
538
+ * - `trailer_manifest_unbound`: the trailer carries a manifest and the code
539
+ * carries none (or could not be read), so nothing signed vouches for it.
540
+ * `error.codeNotRun` is true when the code does export a manifest that
541
+ * only running it would give, and it was not run because its signature
542
+ * was not verified (`verifiedSignature` not set).
543
+ *
544
+ * A module with no manifest in its code and none in its trailer returns null:
545
+ * it declares nothing, and each reader treats that as it treats an absent
546
+ * manifest (the flow host refuses a flow without one; the WasmEdge gate then
547
+ * judges by the caller's manifest alone).
548
+ *
549
+ * @param {Uint8Array|ArrayBuffer} artifactBytes
550
+ * @param {{instance?: WebAssembly.Instance, memory?: WebAssembly.Memory, verifiedSignature?: boolean}} [options]
551
+ * as for readSignedCodeManifest
552
+ * @returns {Promise<Uint8Array|null>}
553
+ */
554
+ export async function readBoundManifestBytes(artifactBytes, options = {}) {
555
+ const trailer = readTrailerManifestBytes(artifactBytes);
556
+ const { bytes: code, reason, notRun } = await readSignedCodeManifest(
557
+ artifactBytes,
558
+ options,
559
+ );
560
+ if (trailer && !code) {
561
+ const error = new ModuleSignatureError(
562
+ "trailer_manifest_unbound",
563
+ notRun
564
+ ? `the artifact's trailer carries a manifest, and its signed code could not be asked for its own (${reason}); the trailer is not covered by the signature, so its manifest is refused`
565
+ : `the artifact's trailer carries a manifest, but its signed code carries none to bind it to (${reason}); the trailer is not covered by the signature, so its manifest is refused`,
566
+ );
567
+ // True when the code does export a manifest that only running it would
568
+ // give: the code was not run, because its signature was not verified.
569
+ error.codeNotRun = notRun === true;
570
+ throw error;
571
+ }
572
+ if (trailer && !equalBytes(trailer, code)) {
573
+ throw new ModuleSignatureError(
574
+ "trailer_manifest_mismatch",
575
+ `the artifact's trailer manifest (${trailer.length} bytes) is not the manifest its signed code carries (${code.length} bytes); the trailer is not covered by the signature and was changed after signing`,
576
+ );
577
+ }
578
+ return code;
579
+ }
@@ -3,6 +3,7 @@ export * from "./codec.js";
3
3
  export * from "./wasm.js";
4
4
  export * from "./artifactBytes.js";
5
5
  export * from "./signing.js";
6
+ export * from "./codeManifest.js";
6
7
  // Re-exported under explicit names rather than `export *`: sigdomain's own
7
8
  // names (`statement`, `domains`, `describe`, `registered`) are deliberately
8
9
  // terse for callers that import the module directly, and far too generic to