space-data-module-sdk 0.10.4 → 0.12.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.
@@ -3,6 +3,7 @@ import {
3
3
  createSingleFileBundle,
4
4
  getWasmCustomSections,
5
5
  parseSingleFileBundle,
6
+ rewriteProtectedEnvelopeTrailer,
6
7
  } from "./wasm.js";
7
8
  import { SDS_MANIFEST_SECTION_NAME } from "./constants.js";
8
9
  import {
@@ -23,11 +24,51 @@ import { ModuleBundleEntryRole } from "spacedatastandards.org/lib/js/MBL/main.js
23
24
 
24
25
  export const MODULE_SIGNATURE_ALGORITHM = "ed25519";
25
26
  export const MODULE_SIGNATURE_ENTRY_ROLE = "signature";
26
- export const LEGACY_MODULE_SIGNATURE_HASH_ALGORITHM =
27
+ // The `signedHashAlgorithm` of the publication form: REQUIRED and fixed, the
28
+ // exact string the node's publication signer writes next to its
29
+ // statementDomain (sdn-server/internal/modulesign). The wire string is the
30
+ // node's and does not change; the statementDomain, not this label, says what
31
+ // the signature covers.
32
+ //
33
+ // A signature entry with NO statementDomain is one of the two forms removed in
34
+ // 0.11.0 and is refused by name: `legacy_module_signature` (the bare module
35
+ // digest, labelled with this string or with none) or `legacy_bundle_signature`
36
+ // (the whole-bundle digest, BUNDLE_SIGNATURE_HASH_ALGORITHM).
37
+ export const PUBLICATION_SIGNED_HASH_ALGORITHM =
27
38
  "sha256-canonical-module-hash";
39
+ // The SDK's public TEST signer (keyId sdm-dev-test-2026), whose private half is
40
+ // committed in test/support/dev-module-signing-keypair.json and therefore
41
+ // public. A signature by this key shows only that the file was not damaged by
42
+ // accident: anyone can sign anything with it. verifyModuleArtifact reports it
43
+ // as testSigner by the verified KEY (the keyId in the entry is not signed and
44
+ // says nothing).
45
+ export const SDK_TEST_SIGNER_PUBLIC_KEY_HEX =
46
+ "cf4625795484d8efe18860141cfdeaaaed7bbee9209488405b6ddeac7543fe78";
47
+
48
+ export function isSdkTestSigner(publicKeyHex) {
49
+ return (
50
+ String(publicKeyHex ?? "").trim().toLowerCase() ===
51
+ SDK_TEST_SIGNER_PUBLIC_KEY_HEX
52
+ );
53
+ }
54
+
28
55
  export const BUNDLE_SIGNATURE_HASH_ALGORITHM =
29
56
  "sha256-sdn-module-bundle-v1";
30
57
 
58
+ /**
59
+ * The one signature form, `signatureScope: "publication"`: Ed25519 over
60
+ * `"SDN-MODULE-PUBLICATION-V1" || 0x00 || sha256(portable)`, an entry with the
61
+ * same fields and values as the node's signing endpoint writes. "module" (the bare canonical
62
+ * module digest) and "bundle" (the whole-bundle digest) were removed in 0.11.0
63
+ * and are refused by name.
64
+ */
65
+ export const MODULE_SIGNATURE_SCOPES = Object.freeze(["publication"]);
66
+ export const DEFAULT_MODULE_SIGNATURE_SCOPE = "publication";
67
+ const REMOVED_SIGNATURE_SCOPES = Object.freeze({
68
+ module: "a signature over the bare canonical module digest, no statement domain",
69
+ bundle: "a signature over the whole-bundle digest, no statement domain",
70
+ });
71
+
31
72
  export class ModuleSignatureError extends Error {
32
73
  constructor(code, message) {
33
74
  super(message);
@@ -41,7 +82,8 @@ function bytesToHex(bytes) {
41
82
  }
42
83
 
43
84
  function hexToBytes(hex) {
44
- const normalized = String(hex ?? "").trim().toLowerCase();
85
+ // Trimmed as Go's strings.TrimSpace trims, as the node trims these fields.
86
+ const normalized = trimGoWhitespace(hex).toLowerCase();
45
87
  if (!/^[0-9a-f]*$/.test(normalized) || normalized.length % 2 !== 0) {
46
88
  throw new ModuleSignatureError(
47
89
  "invalid_hex",
@@ -55,26 +97,62 @@ function hexToBytes(hex) {
55
97
  return out;
56
98
  }
57
99
 
100
+ // A trusted key is exactly 64 hex characters (a 32-byte Ed25519 public key)
101
+ // after trim and lowercase. Anything else that is not empty is REFUSED by
102
+ // name: a key the operator named and the SDK silently dropped would leave a
103
+ // policy that trusts nothing it was told to, or none at all (fail open).
104
+ // The list itself is undefined, null (no keys), an array or a comma-separated
105
+ // string; any other value (a Set, an object, a number) is refused by name too,
106
+ // never read as an empty list.
58
107
  function normalizeTrustedPublicKeys(trustedPublicKeys) {
59
- const list = Array.isArray(trustedPublicKeys)
60
- ? trustedPublicKeys
61
- : typeof trustedPublicKeys === "string"
62
- ? trustedPublicKeys.split(",")
63
- : [];
64
- return list
65
- .map((key) => String(key ?? "").trim().toLowerCase())
66
- .filter((key) => key.length === 64);
108
+ if (trustedPublicKeys === undefined || trustedPublicKeys === null) {
109
+ return [];
110
+ }
111
+ let list;
112
+ if (Array.isArray(trustedPublicKeys)) {
113
+ list = trustedPublicKeys;
114
+ } else if (typeof trustedPublicKeys === "string") {
115
+ list = trustedPublicKeys.split(",");
116
+ } else {
117
+ const kind =
118
+ typeof trustedPublicKeys === "object"
119
+ ? Object.prototype.toString.call(trustedPublicKeys).slice(8, -1)
120
+ : typeof trustedPublicKeys;
121
+ throw new ModuleSignatureError(
122
+ "invalid_trusted_key",
123
+ `trusted signer keys must be an array of hex strings or a comma-separated string; got ${kind}`,
124
+ );
125
+ }
126
+ const keys = [];
127
+ for (const entry of list) {
128
+ const key = String(entry ?? "").trim().toLowerCase();
129
+ if (key === "") continue;
130
+ if (!/^[0-9a-f]{64}$/.test(key)) {
131
+ throw new ModuleSignatureError(
132
+ "invalid_trusted_key",
133
+ `a trusted signer key must be exactly 64 hex characters (a 32-byte Ed25519 public key, no 0x prefix); got ${key.length} characters`,
134
+ );
135
+ }
136
+ keys.push(key);
137
+ }
138
+ return keys;
67
139
  }
68
140
 
141
+ // The entry judged is the one the node judges (publication_signature.go,
142
+ // findModuleSignatureEntry): the first whose role is SIGNATURE, or whose
143
+ // entryId or sectionName, Go-trimmed and lowercased, is "signature" or
144
+ // "sds.signature".
69
145
  function findSignatureEntry(bundle) {
146
+ const folded = (value) =>
147
+ typeof value === "string" ? trimGoWhitespace(value).toLowerCase() : value;
70
148
  for (const entry of bundle?.entries ?? []) {
71
149
  const role =
72
150
  typeof entry.role === "string" ? entry.role.toLowerCase() : entry.role;
73
151
  if (
74
152
  role === MODULE_SIGNATURE_ENTRY_ROLE ||
75
153
  role === ModuleBundleEntryRole.SIGNATURE ||
76
- entry.entryId === "signature" ||
77
- entry.sectionName === "sds.signature"
154
+ folded(entry.entryId) === "signature" ||
155
+ folded(entry.sectionName) === "sds.signature"
78
156
  ) {
79
157
  return entry;
80
158
  }
@@ -130,6 +208,21 @@ function decodeSignaturePayload(entry) {
130
208
  );
131
209
  }
132
210
  }
211
+ // Every known key is a string, as the node's struct reads it (Go's
212
+ // json.Unmarshal refuses an array, a number, an object or a boolean for a
213
+ // string field). keyId may also be null: OrbPro's envelope signer and this
214
+ // SDK write keyId null when there is none. Without this check, String()
215
+ // turned a one-element array into its string and admitted what the node
216
+ // refuses.
217
+ for (const key of SIGNATURE_PAYLOAD_KEYS) {
218
+ if (!Object.hasOwn(parsed, key)) continue;
219
+ const value = parsed[key];
220
+ if (typeof value === "string" || (key === "keyId" && value === null)) continue;
221
+ throw new ModuleSignatureError(
222
+ "invalid_signature_payload",
223
+ `module signature entry payload's "${key}" is ${value === null ? "null" : Array.isArray(value) ? "an array" : typeof value}; it must be a string${key === "keyId" ? " or null" : ""}`,
224
+ );
225
+ }
133
226
  return parsed;
134
227
  }
135
228
 
@@ -153,199 +246,136 @@ async function bestEffortCanonicalModuleHashHex(payloadBytes) {
153
246
  }
154
247
  }
155
248
 
156
- const bundleStatementTextEncoder = new TextEncoder();
157
-
158
- function compareUtf8Keys(left, right) {
159
- const leftBytes = bundleStatementTextEncoder.encode(left);
160
- const rightBytes = bundleStatementTextEncoder.encode(right);
161
- const length = Math.min(leftBytes.length, rightBytes.length);
162
- for (let index = 0; index < length; index += 1) {
163
- if (leftBytes[index] !== rightBytes[index]) {
164
- return leftBytes[index] - rightBytes[index];
165
- }
249
+ function resolveSignatureScope(signatureScope) {
250
+ if (signatureScope === undefined) {
251
+ return DEFAULT_MODULE_SIGNATURE_SCOPE;
166
252
  }
167
- return leftBytes.length - rightBytes.length;
168
- }
169
-
170
- function normalizeBundleStatementValue(value) {
171
- if (value === undefined) {
172
- return undefined;
173
- }
174
- if (value === null || typeof value !== "object") {
175
- return value;
176
- }
177
- if (Array.isArray(value)) {
178
- return value.map((item) => {
179
- const normalized = normalizeBundleStatementValue(item);
180
- return normalized === undefined ? null : normalized;
181
- });
182
- }
183
- return Object.fromEntries(
184
- Object.entries(value)
185
- .filter(([, nestedValue]) => nestedValue !== undefined)
186
- .sort(([left], [right]) => compareUtf8Keys(left, right))
187
- .map(([key, nestedValue]) => [
188
- key,
189
- normalizeBundleStatementValue(nestedValue),
190
- ]),
191
- );
253
+ if (Object.hasOwn(REMOVED_SIGNATURE_SCOPES, signatureScope)) {
254
+ throw new ModuleSignatureError(
255
+ "legacy_signature_scope",
256
+ `signatureScope ${JSON.stringify(signatureScope)} (${REMOVED_SIGNATURE_SCOPES[signatureScope]}) was removed in space-data-module-sdk 0.11.0; the one form is signatureScope "publication"`,
257
+ );
258
+ }
259
+ if (!MODULE_SIGNATURE_SCOPES.includes(signatureScope)) {
260
+ throw new ModuleSignatureError(
261
+ "invalid_signature_scope",
262
+ `signatureScope must be one of ${MODULE_SIGNATURE_SCOPES.map((scope) => JSON.stringify(scope)).join(", ")}`,
263
+ );
264
+ }
265
+ return signatureScope;
192
266
  }
193
267
 
194
- function canonicalBundleStatementBytes(statement) {
195
- // Go's encoding/json orders map keys by their UTF-8 bytes and escapes these
196
- // five code points by default. Match that host-side representation exactly
197
- // so a bundle digest is independent of JavaScript's locale configuration.
198
- const json = JSON.stringify(normalizeBundleStatementValue(statement)).replace(
199
- /[<>&\u2028\u2029]/g,
200
- (character) =>
201
- `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`,
268
+ /**
269
+ * The publication signature entry over `portable` (the bytes before the
270
+ * trailer), with the same fields and values as the node's SignatureEntry
271
+ * (sdn-server/internal/modulesign/modulesign.go, Sign). Not the same bytes:
272
+ * the bundle writer sorts the keys and this writes keyId null when there is
273
+ * none, where the node writes its struct's field order and keyId ""; both
274
+ * verify on both sides.
275
+ */
276
+ async function publicationSignatureEntry(seed, portable, keyId) {
277
+ const publicKey = await ed25519PublicKey(seed);
278
+ const contentHashBytes = await sha256Bytes(new Uint8Array(portable));
279
+ const signedHashHex = bytesToHex(contentHashBytes);
280
+ const signatureBytes = await ed25519Sign(
281
+ buildSignatureStatement(DOMAIN_MODULE_PUBLICATION_V1, contentHashBytes),
282
+ seed,
202
283
  );
203
- return bundleStatementTextEncoder.encode(json);
204
- }
205
-
206
- function normalizedBundleEntryForSignature(entry) {
207
- const payload = new Uint8Array(entry.payload ?? []);
208
284
  return {
209
- entryId: entry.entryId ?? null,
210
- role: Number(entry.role ?? ModuleBundleEntryRole.AUXILIARY),
211
- sectionName: entry.sectionName ?? null,
212
- typeRef: entry.typeRef ?? null,
213
- payloadEncoding: Number(entry.payloadEncoding ?? 0),
214
- mediaType: entry.mediaType ?? null,
215
- flags: Number(entry.flags ?? 0),
216
- sha256Hex: bytesToHex(new Uint8Array(entry.sha256 ?? [])),
217
- payloadLength: payload.length,
218
- description: entry.description ?? null,
285
+ contentHashBytes,
286
+ signedHashHex,
287
+ signature: {
288
+ algorithm: MODULE_SIGNATURE_ALGORITHM,
289
+ keyId: keyId ?? null,
290
+ publicKeyHex: bytesToHex(new Uint8Array(publicKey)),
291
+ signatureHex: bytesToHex(new Uint8Array(signatureBytes)),
292
+ signedHashAlgorithm: PUBLICATION_SIGNED_HASH_ALGORITHM,
293
+ signedHashHex,
294
+ statementDomain: DOMAIN_MODULE_PUBLICATION_V1,
295
+ },
219
296
  };
220
297
  }
221
298
 
222
299
  /**
223
- * Compute the v1 whole-bundle signing digest. Every non-signature entry's
224
- * payload hash is recomputed before the canonical statement is hashed; an
225
- * attacker cannot make a modified payload self-consistent merely by changing
226
- * its MBL sha256 field. Bundle metadata and the portable module hash are bound
227
- * by the same statement.
300
+ * An artifact whose trailer carries an ENC record: the payload is ciphertext
301
+ * and is NEVER parsed. The signature is taken over the bytes as stored (the
302
+ * ciphertext), the same statement as for a plaintext module; the trailer is
303
+ * written again with the new signature entry, every other bundle entry, and
304
+ * the ENC and PNM records as they were. The engine's envelope signer
305
+ * (OrbPro `scripts/signProtectedEnvelope.mjs`) writes the same entry.
306
+ *
307
+ * What this signature binds is the ciphertext only: not the ENC record (its
308
+ * cipher suite, key context or recipient), not the plaintext. A host that
309
+ * decrypts checks the plaintext's own signature after decrypting.
228
310
  */
229
- export async function computeModuleBundleSignatureHash(bundle, options = {}) {
230
- if (!bundle || typeof bundle !== "object") {
231
- throw new ModuleSignatureError(
232
- "invalid_bundle",
233
- "module bundle is missing or malformed",
234
- );
235
- }
236
- const entries = (bundle.entries ?? []).filter(
237
- (entry) => !findSignatureEntry({ entries: [entry] }),
238
- );
239
- const seen = new Set();
240
- for (const entry of entries) {
241
- const entryId = String(entry.entryId ?? "");
242
- if (!entryId) {
243
- throw new ModuleSignatureError(
244
- "invalid_bundle",
245
- "module bundle contains an entry without an entryId",
246
- );
247
- }
248
- if (seen.has(entryId)) {
249
- throw new ModuleSignatureError(
250
- "invalid_bundle",
251
- `module bundle contains duplicate entryId ${JSON.stringify(entryId)}`,
252
- );
253
- }
254
- seen.add(entryId);
255
- const payloadHash = await sha256Bytes(new Uint8Array(entry.payload ?? []));
256
- if (!equalBytes(payloadHash, entry.sha256)) {
257
- throw new ModuleSignatureError(
258
- "hash_mismatch",
259
- `module bundle entry ${JSON.stringify(entryId)} payload hash does not match its recorded sha256`,
260
- );
261
- }
262
- }
263
-
264
- const recordedModuleHash = new Uint8Array(bundle.canonicalModuleHash ?? []);
265
- if (recordedModuleHash.length !== 32) {
266
- throw new ModuleSignatureError(
267
- "invalid_bundle",
268
- "module bundle canonicalModuleHash must be 32 bytes",
269
- );
270
- }
271
- if (options.wasmBytes) {
272
- const canonical = await computeCanonicalModuleHash(options.wasmBytes, {
273
- customSectionPrefix:
274
- bundle.canonicalization?.strippedCustomSectionPrefix,
275
- });
276
- if (!equalBytes(canonical.hashBytes, recordedModuleHash)) {
277
- throw new ModuleSignatureError(
278
- "hash_mismatch",
279
- "module canonical hash does not match the bundle's recorded hash",
280
- );
281
- }
282
- }
283
-
284
- const manifestEntry = entries.find(
285
- (entry) =>
286
- entry.entryId === "manifest" ||
287
- entry.role === ModuleBundleEntryRole.MANIFEST,
288
- );
289
- const recordedManifestHash = new Uint8Array(bundle.manifestHash ?? []);
290
- if (manifestEntry) {
291
- const manifestHash = await sha256Bytes(
292
- new Uint8Array(manifestEntry.payload ?? []),
293
- );
294
- if (!equalBytes(manifestHash, recordedManifestHash)) {
295
- throw new ModuleSignatureError(
296
- "hash_mismatch",
297
- "module manifest payload hash does not match the bundle's manifestHash",
298
- );
299
- }
300
- } else if (recordedManifestHash.length !== 0) {
311
+ async function signEncryptedArtifact(protectedArtifact, seed, options, signatureScope) {
312
+ const portable = new Uint8Array(protectedArtifact.payloadBytes);
313
+ const keptEntries = (protectedArtifact.mbl?.entries ?? [])
314
+ .filter((entry) => !findSignatureEntry({ entries: [entry] }))
315
+ .map((entry) => ({ ...entry, payload: new Uint8Array(entry.payload ?? []) }));
316
+ const { signature, signedHashHex, contentHashBytes } =
317
+ await publicationSignatureEntry(seed, portable, options.keyId);
318
+ const wasmBytes = await rewriteProtectedEnvelopeTrailer({
319
+ publicationRecords: protectedArtifact,
320
+ entries: keptEntries,
321
+ signature,
322
+ contentHash: contentHashBytes,
323
+ });
324
+ const written = extractPublicationRecordCollection(wasmBytes);
325
+ if (!written?.enc || !equalBytes(written.payloadBytes, portable)) {
301
326
  throw new ModuleSignatureError(
302
327
  "hash_mismatch",
303
- "module bundle records a manifestHash but contains no manifest entry",
328
+ "writing the signature changed the encrypted payload; nothing signed",
304
329
  );
305
330
  }
306
-
307
- const statement = {
308
- version: 1,
309
- bundleVersion: Number(bundle.bundleVersion ?? 1),
310
- moduleFormat: bundle.moduleFormat ?? null,
311
- canonicalization: {
312
- version: Number(bundle.canonicalization?.version ?? 1),
313
- strippedCustomSectionPrefix:
314
- bundle.canonicalization?.strippedCustomSectionPrefix ?? null,
315
- bundleSectionName:
316
- bundle.canonicalization?.bundleSectionName ?? null,
317
- hashAlgorithm: bundle.canonicalization?.hashAlgorithm ?? null,
318
- },
319
- canonicalModuleHashHex: bytesToHex(recordedModuleHash),
320
- manifestHashHex: bytesToHex(recordedManifestHash),
321
- manifestExportSymbol: bundle.manifestExportSymbol ?? null,
322
- manifestSizeSymbol: bundle.manifestSizeSymbol ?? null,
323
- entries: entries
324
- .map(normalizedBundleEntryForSignature)
325
- .sort((left, right) => compareUtf8Keys(left.entryId, right.entryId)),
326
- };
327
- const hashBytes = await sha256Bytes(canonicalBundleStatementBytes(statement));
328
331
  return {
329
- statement,
330
- hashBytes,
331
- hashHex: bytesToHex(hashBytes),
332
+ wasmBytes,
333
+ signature,
334
+ // The bundle's recorded value, as it stands in the trailer: the
335
+ // plaintext's canonical hash when the old trailer carried one, else the
336
+ // ciphertext's content hash. The ciphertext itself is never parsed.
337
+ canonicalModuleHashHex: bytesToHex(
338
+ new Uint8Array(written.mbl?.canonicalModuleHash ?? []),
339
+ ),
340
+ signedHashHex,
341
+ signatureScope,
332
342
  };
333
343
  }
334
344
 
335
345
  /**
336
- * Sign a module artifact's canonical wasm hash with an Ed25519 key and embed
337
- * the detached signature in the artifact's MBL bundle (sds.signature entry).
346
+ * Sign a module artifact with an Ed25519 key and embed the detached signature
347
+ * in the artifact's MBL bundle (sds.signature entry).
348
+ *
349
+ * One form, `signatureScope: "publication"` (the default and the only value):
350
+ * an entry with the same fields and values as the one the node's signing
351
+ * endpoint writes (`sdn-server/internal/modulesign`); the key order and an
352
+ * absent keyId (null here, "" there) differ, and both verify. The
353
+ * signature covers the bytes before the trailer; the trailer's entries (the
354
+ * manifest copy included) are not covered.
355
+ *
356
+ * What is hashed is what the OUTPUT holds before its trailer. For a raw
357
+ * module (no trailer yet) that is the module with its `sds.*` custom sections
358
+ * removed (they move into the trailer), so a raw build that still carries
359
+ * `sds.manifest` is signed correctly in one pass. For a file that already has
360
+ * a trailer, the bytes before it are signed as they stand and kept unchanged
361
+ * (a node-signed file keeps its `sds.manifest` section there): signing again
362
+ * never changes the loadable wasm. For an artifact whose trailer carries an
363
+ * ENC record, the payload is ciphertext: it is hashed as stored and never
364
+ * parsed.
338
365
  *
339
366
  * Existing bundle entries, the manifest, and any ENC/PNM publication records
340
- * in the REC trailer are preserved. Any previous signature entry is replaced.
367
+ * in the REC trailer are preserved. Any previous signature entry is replaced,
368
+ * whatever its form: a previous signature is never verified or kept here.
341
369
  *
342
370
  * @param {Uint8Array|ArrayBuffer} bytes - module artifact (raw wasm or single-file bundle)
343
371
  * @param {Object} options
344
372
  * @param {string} options.privateKeySeedHex - 32-byte Ed25519 seed, hex
345
373
  * @param {string} [options.keyId] - identifier recorded alongside the signature
346
- * @returns {Promise<{wasmBytes: Uint8Array, signature: Object, canonicalModuleHashHex: string}>}
374
+ * @param {"publication"} [options.signatureScope]
375
+ * @returns {Promise<{wasmBytes: Uint8Array, signature: Object, canonicalModuleHashHex: string, signedHashHex: string, signatureScope: string}>}
347
376
  */
348
377
  export async function signModuleArtifact(bytes, options = {}) {
378
+ const signatureScope = resolveSignatureScope(options.signatureScope);
349
379
  const seed = hexToBytes(options.privateKeySeedHex);
350
380
  if (seed.length !== 32) {
351
381
  throw new ModuleSignatureError(
@@ -354,8 +384,10 @@ export async function signModuleArtifact(bytes, options = {}) {
354
384
  );
355
385
  }
356
386
  const protectedArtifact = extractPublicationRecordCollection(bytes);
387
+ if (protectedArtifact?.enc) {
388
+ return signEncryptedArtifact(protectedArtifact, seed, options, signatureScope);
389
+ }
357
390
  const payloadBytes = protectedArtifact?.payloadBytes ?? bytes;
358
- const canonical = await computeCanonicalModuleHash(payloadBytes);
359
391
 
360
392
  let manifestBytes;
361
393
  let preservedEntries = [];
@@ -387,43 +419,37 @@ export async function signModuleArtifact(bytes, options = {}) {
387
419
  )[0];
388
420
  }
389
421
 
390
- let signedHashBytes = canonical.hashBytes;
391
- let signedHashHex = canonical.hashHex;
392
- let signedHashAlgorithm = LEGACY_MODULE_SIGNATURE_HASH_ALGORITHM;
393
- if (options.signatureScope === "bundle") {
394
- const unsigned = await createSingleFileBundle({
395
- wasmBytes: bytes,
396
- ...(manifestBytes ? { manifestBytes } : {}),
397
- entries: preservedEntries,
398
- });
399
- const parsedUnsigned = await parseSingleFileBundle(unsigned.wasmBytes);
400
- const bundleHash = await computeModuleBundleSignatureHash(
401
- parsedUnsigned.bundle,
402
- { wasmBytes: parsedUnsigned.wasmBytes },
403
- );
404
- signedHashBytes = bundleHash.hashBytes;
405
- signedHashHex = bundleHash.hashHex;
406
- signedHashAlgorithm = BUNDLE_SIGNATURE_HASH_ALGORITHM;
407
- } else if (
408
- options.signatureScope !== undefined &&
409
- options.signatureScope !== "module"
410
- ) {
422
+ // The bundle as it will be written, without its signature: the preimage is
423
+ // the bytes before the trailer, which the signature entry does not change.
424
+ const unsigned = await createSingleFileBundle({
425
+ wasmBytes: bytes,
426
+ ...(manifestBytes ? { manifestBytes } : {}),
427
+ entries: preservedEntries,
428
+ });
429
+ const unsignedPortable = extractPublicationRecordCollection(
430
+ unsigned.wasmBytes,
431
+ )?.payloadBytes;
432
+ if (!unsignedPortable) {
411
433
  throw new ModuleSignatureError(
412
- "invalid_signature_scope",
413
- 'signatureScope must be either "module" or "bundle"',
434
+ "invalid_bundle",
435
+ "the unsigned bundle has no publication trailer",
414
436
  );
415
437
  }
416
438
 
417
- const publicKey = await ed25519PublicKey(seed);
418
- const signatureBytes = await ed25519Sign(signedHashBytes, seed);
419
- const signature = {
420
- algorithm: MODULE_SIGNATURE_ALGORITHM,
421
- keyId: options.keyId ?? null,
422
- publicKeyHex: bytesToHex(new Uint8Array(publicKey)),
423
- signatureHex: bytesToHex(new Uint8Array(signatureBytes)),
424
- signedHashHex,
425
- signedHashAlgorithm,
426
- };
439
+ // A file that already has a trailer (signed before, by this SDK or by the
440
+ // node) is signed over the bytes before that trailer AS THEY STAND, and they
441
+ // are kept unchanged: signing again never changes the loadable wasm. A
442
+ // node-signed file keeps its sds.manifest section in those bytes; the bundle
443
+ // writer would strip it (only the trailer it writes is used, below).
444
+ const keptPortable = protectedArtifact
445
+ ? new Uint8Array(protectedArtifact.payloadBytes)
446
+ : null;
447
+
448
+ const { signature, signedHashHex } = await publicationSignatureEntry(
449
+ seed,
450
+ keptPortable ?? unsignedPortable,
451
+ options.keyId,
452
+ );
427
453
 
428
454
  const rebuilt = await createSingleFileBundle({
429
455
  wasmBytes: bytes,
@@ -431,21 +457,47 @@ export async function signModuleArtifact(bytes, options = {}) {
431
457
  signature,
432
458
  entries: preservedEntries,
433
459
  });
460
+ const signedPortable = extractPublicationRecordCollection(
461
+ rebuilt.wasmBytes,
462
+ )?.payloadBytes;
463
+ if (!equalBytes(signedPortable, unsignedPortable)) {
464
+ throw new ModuleSignatureError(
465
+ "hash_mismatch",
466
+ "writing the signature changed the bytes before the trailer; nothing signed",
467
+ );
468
+ }
469
+ let wasmBytes = new Uint8Array(rebuilt.wasmBytes);
470
+ if (keptPortable) {
471
+ // The trailer is self-contained (its footer records only its own length):
472
+ // the one just written goes after the bytes as they stood.
473
+ const trailer = wasmBytes.subarray(signedPortable.length);
474
+ wasmBytes = new Uint8Array(keptPortable.length + trailer.length);
475
+ wasmBytes.set(keptPortable, 0);
476
+ wasmBytes.set(trailer, keptPortable.length);
477
+ const written = extractPublicationRecordCollection(wasmBytes);
478
+ if (!written?.mbl || written.enc || !equalBytes(written.payloadBytes, keptPortable)) {
479
+ throw new ModuleSignatureError(
480
+ "hash_mismatch",
481
+ "writing the signature changed the bytes before the trailer; nothing signed",
482
+ );
483
+ }
484
+ }
434
485
  return {
435
- wasmBytes: rebuilt.wasmBytes,
486
+ wasmBytes,
436
487
  signature,
437
488
  canonicalModuleHashHex: rebuilt.canonicalModuleHashHex,
438
489
  signedHashHex,
490
+ signatureScope,
439
491
  };
440
492
  }
441
493
 
442
494
  /**
443
495
  * Verify a module artifact's embedded Ed25519 signature before loading.
444
496
  *
445
- * TWO SIGNED FORMS, and the artifact chooses — not the caller, not a policy:
497
+ * ONE SIGNED FORM, the publication form:
446
498
  *
447
- * - `statementDomain` PRESENT — the NODE-SIGNED form issued by the node's
448
- * content-bound signing endpoint. The signature covers the domain-separated
499
+ * - `statementDomain` PRESENT — written by the node's content-bound signing
500
+ * endpoint and by `signModuleArtifact`. The signature covers the domain-separated
449
501
  * statement `domain || 0x00 || sha256(portable)` (see ./sigdomain.js), where
450
502
  * `portable` is the trailer-stripped payload — the exact bytes the runtime
451
503
  * instantiates and the node's capability policy identifies by content hash.
@@ -454,27 +506,37 @@ export async function signModuleArtifact(bytes, options = {}) {
454
506
  * update-manifest domain, say) is REFUSED, which is what stops a signature
455
507
  * minted for a signed update from being stapled into a module trailer.
456
508
  *
457
- * - `statementDomain` ABSENT — the legacy SDK-signed form: a signature over
458
- * the bare canonical module (or bundle) digest. Verification is byte-identical
459
- * to what it has always been, so every artifact already published keeps
460
- * verifying.
509
+ * A signature WITHOUT a statement domain is one of the two forms removed in
510
+ * 0.11.0 and is REFUSED by name before the signer is asked about (it is a
511
+ * property of the artifact): `legacy_bundle_signature` when it declares the
512
+ * whole-bundle hash algorithm, `legacy_module_signature` for the bare module
513
+ * digest. Such an artifact must be signed again. The node still admits both;
514
+ * the parity test names the vectors where the verdicts differ.
461
515
  *
462
- * THIS MIRRORS THE NODE EXACTLY, deliberately and to the reason code, because
463
- * the same artifact is verified by the Go loaders
464
- * (`sdn-server/internal/modulert/publication_signature.go` and its kubo twin)
465
- * and by this function in the browser and under Node/WasmEdge. An artifact that
466
- * verifies on the node and is refused here is a cross-runtime defect, not a
467
- * platform difference — so the checks below run in the node's ORDER (what the
468
- * signature covers is resolved before who signed it) and the shared vector file
516
+ * This verifier is also deliberately STRICTER than the node's on the
517
+ * publication form's own fields. It REQUIRES `signedHashHex` (equal to sha256
518
+ * of the bytes before the trailer) and `signedHashAlgorithm` (the fixed label);
519
+ * a null, empty or absent value is refused here (`invalid_signature_payload`
520
+ * for null, `missing_signed_hash`, `unsupported_hash_algorithm`), while the
521
+ * node admits an empty or null `signedHashHex` and consults
522
+ * `signedHashAlgorithm` only to recognize the whole-bundle label, so it admits
523
+ * an empty, null or other value there. A null `statementDomain` sends the node
524
+ * down its path without a domain (the removed form), which this verifier
525
+ * refuses. A null `keyId` is admitted on both sides.
526
+ *
527
+ * Apart from those differences, the checks follow the node
528
+ * (`sdn-server/internal/modulert/publication_signature.go` and its kubo twin),
529
+ * which verifies the same artifact as this function does in the browser and
530
+ * under Node/WasmEdge: they run in the node's ORDER (what the signature covers
531
+ * is resolved before who signed it), and the shared vector file
469
532
  * `test/support/statement-domain-vectors.json` pins both sides against the same
470
533
  * bytes and the same refusal reasons.
471
534
  *
472
- * Note the deliberate omissions on the node-signed path: `signedHashAlgorithm`
473
- * is not consulted and the bundle's recorded `canonicalModuleHash` is not
474
- * gated on, because the node consults neither. The domain itself defines the
475
- * hash basis (portable-payload SHA-256), and that basis binds the entire
476
- * instantiated payload — a strictly stronger commitment than the canonical
477
- * hash, which strips `sds.*` custom sections before hashing.
535
+ * The bundle's recorded `canonicalModuleHash` is not gated on, because the
536
+ * node does not gate on it. The domain itself defines the hash basis
537
+ * (portable-payload SHA-256), and that basis binds the entire instantiated
538
+ * payload — a strictly stronger commitment than the canonical hash, which
539
+ * strips `sds.*` custom sections before hashing.
478
540
  *
479
541
  * A present-but-invalid signature always throws. A missing signature throws
480
542
  * only when `requireSignature` is true.
@@ -487,6 +549,9 @@ export async function signModuleArtifact(bytes, options = {}) {
487
549
  */
488
550
  export async function verifyModuleArtifact(bytes, options = {}) {
489
551
  const requireSignature = options.requireSignature === true;
552
+ // First, before the artifact is looked at: a malformed trusted key is the
553
+ // caller's error (invalid_trusted_key) whatever the file holds.
554
+ const trusted = normalizeTrustedPublicKeys(options.trustedPublicKeys);
490
555
  const protectedArtifact = extractPublicationRecordCollection(bytes);
491
556
  const signatureEntry = protectedArtifact?.mbl
492
557
  ? findSignatureEntry(protectedArtifact.mbl)
@@ -525,7 +590,7 @@ export async function verifyModuleArtifact(bytes, options = {}) {
525
590
  "module signature must not be all zeroes",
526
591
  );
527
592
  }
528
- const publicKeyHex = String(payload.publicKeyHex ?? "").trim().toLowerCase();
593
+ const publicKeyHex = trimGoWhitespace(payload.publicKeyHex).toLowerCase();
529
594
  const publicKeyBytes = hexToBytes(publicKeyHex);
530
595
  if (publicKeyBytes.length !== 32) {
531
596
  throw new ModuleSignatureError(
@@ -534,7 +599,6 @@ export async function verifyModuleArtifact(bytes, options = {}) {
534
599
  );
535
600
  }
536
601
 
537
- const trusted = normalizeTrustedPublicKeys(options.trustedPublicKeys);
538
602
  // resolvedStatementDomain is carried onto the thrown error so a refusal
539
603
  // reports the same (reason, domain) pair the node's ModuleSignatureStatus
540
604
  // does — including for untrusted_signer, where the domain was already
@@ -601,6 +665,30 @@ export async function verifyModuleArtifact(bytes, options = {}) {
601
665
  throw error;
602
666
  }
603
667
 
668
+ // The entry names what it covers. signedHashHex is REQUIRED and equal to
669
+ // sha256(portable) (a different one is hash_mismatch, above); the node's
670
+ // signer always writes it, and sdn-js already requires it. The hash
671
+ // algorithm label is REQUIRED and is the node's fixed string.
672
+ if (declaredHashHex === "") {
673
+ const error = new ModuleSignatureError(
674
+ "missing_signed_hash",
675
+ `module signature declares no signedHashHex; the publication form records sha256 of the bytes before the trailer (${contentHashHex}), sign the module again`,
676
+ );
677
+ error.statementDomain = DOMAIN_MODULE_PUBLICATION_V1;
678
+ throw error;
679
+ }
680
+ if (
681
+ trimGoWhitespace(payload.signedHashAlgorithm) !==
682
+ PUBLICATION_SIGNED_HASH_ALGORITHM
683
+ ) {
684
+ const error = new ModuleSignatureError(
685
+ "unsupported_hash_algorithm",
686
+ `module signature declares signedHashAlgorithm ${JSON.stringify(payload.signedHashAlgorithm ?? "")}; the publication form records ${JSON.stringify(PUBLICATION_SIGNED_HASH_ALGORITHM)}`,
687
+ );
688
+ error.statementDomain = DOMAIN_MODULE_PUBLICATION_V1;
689
+ throw error;
690
+ }
691
+
604
692
  const statementBytes = buildSignatureStatement(
605
693
  DOMAIN_MODULE_PUBLICATION_V1,
606
694
  contentHashBytes,
@@ -627,6 +715,7 @@ export async function verifyModuleArtifact(bytes, options = {}) {
627
715
  signed: true,
628
716
  keyId: payload.keyId ?? null,
629
717
  publicKeyHex,
718
+ testSigner: isSdkTestSigner(publicKeyHex),
630
719
  statementDomain: DOMAIN_MODULE_PUBLICATION_V1,
631
720
  contentHashHex,
632
721
  // Reported for continuity with the legacy result shape (the CLI prints
@@ -639,80 +728,31 @@ export async function verifyModuleArtifact(bytes, options = {}) {
639
728
  };
640
729
  }
641
730
 
642
- // ---- legacy form: bare canonical module (or bundle) digest ---------------
643
- const canonical = await computeCanonicalModuleHash(protectedArtifact.payloadBytes);
644
- const recordedHash = new Uint8Array(
645
- protectedArtifact.mbl.canonicalModuleHash ?? [],
646
- );
731
+ // ---- no statement domain: a removed form, refused by name -----------------
732
+ // Before the signer is asked about: the form is a property of the artifact.
647
733
  if (
648
- recordedHash.length !== canonical.hashBytes.length ||
649
- !recordedHash.every((byte, i) => byte === canonical.hashBytes[i])
650
- ) {
651
- throw new ModuleSignatureError(
652
- "hash_mismatch",
653
- "module canonical hash does not match the bundle's recorded hash",
654
- );
655
- }
656
-
657
- let signedHashBytes = canonical.hashBytes;
658
- let signedHashHex = canonical.hashHex;
659
- let signatureScope = "module";
660
- const signedHashAlgorithm = String(payload.signedHashAlgorithm ?? "");
661
- if (signedHashAlgorithm === BUNDLE_SIGNATURE_HASH_ALGORITHM) {
662
- const parsed = await parseSingleFileBundle(bytes);
663
- const bundleHash = await computeModuleBundleSignatureHash(parsed.bundle, {
664
- wasmBytes: parsed.wasmBytes,
665
- });
666
- signedHashBytes = bundleHash.hashBytes;
667
- signedHashHex = bundleHash.hashHex;
668
- signatureScope = "bundle";
669
- } else if (
670
- signedHashAlgorithm !== LEGACY_MODULE_SIGNATURE_HASH_ALGORITHM
734
+ trimGoWhitespace(payload.signedHashAlgorithm) ===
735
+ BUNDLE_SIGNATURE_HASH_ALGORITHM
671
736
  ) {
672
737
  throw new ModuleSignatureError(
673
- "unsupported_hash_algorithm",
674
- `unsupported module signature hash algorithm: ${signedHashAlgorithm}`,
738
+ "legacy_bundle_signature",
739
+ `module signature has no statementDomain and covers the whole-bundle digest (signedHashAlgorithm ${JSON.stringify(BUNDLE_SIGNATURE_HASH_ALGORITHM)}); space-data-module-sdk 0.11.0 refuses this form, sign the module again`,
675
740
  );
676
741
  }
742
+ const declaredAlgorithm = trimGoWhitespace(payload.signedHashAlgorithm);
677
743
  if (
678
- String(payload.signedHashHex ?? "").toLowerCase() !== signedHashHex
744
+ declaredAlgorithm !== "" &&
745
+ declaredAlgorithm !== PUBLICATION_SIGNED_HASH_ALGORITHM
679
746
  ) {
680
747
  throw new ModuleSignatureError(
681
- "hash_mismatch",
682
- "module or bundle hash does not match the signed digest",
748
+ "unsupported_hash_algorithm",
749
+ `unsupported module signature hash algorithm: ${payload.signedHashAlgorithm}`,
683
750
  );
684
751
  }
685
-
686
- // Trust is asked LAST here too, for the same reason as above and so the two
687
- // forms cannot report different reasons for the same defect.
688
- requireTrustedSigner();
689
-
690
- const valid = await ed25519Verify(
691
- signedHashBytes,
692
- signatureBytes,
693
- publicKeyBytes,
752
+ throw new ModuleSignatureError(
753
+ "legacy_module_signature",
754
+ `module signature has no statementDomain and covers the bare canonical module digest (signedHashAlgorithm ${JSON.stringify(payload.signedHashAlgorithm ?? "")}); space-data-module-sdk 0.11.0 refuses this form, sign the module again`,
694
755
  );
695
- if (!valid) {
696
- throw new ModuleSignatureError(
697
- "invalid_signature",
698
- "module signature verification failed",
699
- );
700
- }
701
- return {
702
- verified: true,
703
- signed: true,
704
- keyId: payload.keyId ?? null,
705
- publicKeyHex,
706
- // Null, not absent: the legacy form is a POSITIVE statement that this
707
- // artifact predates domain separation, which a caller may want to log.
708
- statementDomain: null,
709
- contentHashHex: bytesToHex(
710
- await sha256Bytes(new Uint8Array(protectedArtifact.payloadBytes)),
711
- ),
712
- canonicalModuleHashHex: canonical.hashHex,
713
- signatureScope,
714
- signedHashHex,
715
- };
716
756
  }
717
757
 
718
758
  function readEnv(name) {
@@ -735,27 +775,68 @@ function readEnv(name) {
735
775
  *
736
776
  * Returns null when no policy is configured (loading proceeds unverified,
737
777
  * preserving existing behavior).
778
+ *
779
+ * NAMING A TRUSTED KEY REQUIRES A SIGNATURE. The publication form does not
780
+ * cover its own trailer, so stripping the trailer (or only its signature
781
+ * entry) leaves a file that would otherwise load as "unsigned" under a policy
782
+ * that trusts key X. A policy, environment or global that names any trusted
783
+ * key therefore always sets requireSignature, whatever it says about it.
784
+ *
785
+ * A MALFORMED KEY IS REFUSED, never dropped: any non-empty entry that is not
786
+ * exactly 64 hex characters after trim and lowercase (a `0x` prefix, a
787
+ * 63-character typo, a non-hex character) throws
788
+ * `ModuleSignatureError("invalid_trusted_key")`, so a typo can never turn the
789
+ * check off. A list that is not undefined, null, an array or a string (a Set,
790
+ * an object, a number) throws `invalid_trusted_key` as well. In the object
791
+ * form, a `trustedPublicKeys` that was given (a non-empty array, a non-blank
792
+ * string) but yields no key (for example `[process.env.KEY]` with KEY unset)
793
+ * throws `invalid_trusted_key`; an explicit empty array names no key and adds
794
+ * no requirement. An environment variable that yields no key (unset, empty,
795
+ * blanks or commas only) does not hide the global list.
796
+ *
797
+ * `verifySignature: true` uses the environment's or the global's trust. The
798
+ * caller asked for verification, so it always requires a signature: with no
799
+ * trust configured there, nothing is trusted and every load is refused by
800
+ * name (`missing_signature` or `untrusted_signer`), never let through.
738
801
  */
739
802
  export function resolveModuleSignaturePolicy(options = {}) {
740
803
  if (options.verifySignature === false) {
741
804
  return null;
742
805
  }
743
806
  if (options.verifySignature && typeof options.verifySignature === "object") {
807
+ const given = options.verifySignature.trustedPublicKeys;
808
+ const trustedPublicKeys = normalizeTrustedPublicKeys(given);
809
+ const named =
810
+ (Array.isArray(given) && given.length > 0) ||
811
+ (typeof given === "string" && given.trim() !== "");
812
+ if (named && trustedPublicKeys.length === 0) {
813
+ // For example [process.env.KEY] with KEY unset: the caller named keys,
814
+ // and not one of them is a key. Refused, never read as "no keys".
815
+ throw new ModuleSignatureError(
816
+ "invalid_trusted_key",
817
+ "trustedPublicKeys was given but holds no key (every entry is empty)",
818
+ );
819
+ }
744
820
  return {
745
- trustedPublicKeys: normalizeTrustedPublicKeys(
746
- options.verifySignature.trustedPublicKeys,
747
- ),
748
- requireSignature: options.verifySignature.requireSignature === true,
821
+ trustedPublicKeys,
822
+ requireSignature:
823
+ options.verifySignature.requireSignature === true ||
824
+ trustedPublicKeys.length > 0,
749
825
  };
750
826
  }
751
827
  const envTrusted = readEnv("SDM_TRUSTED_MODULE_SIGNERS");
752
828
  const envRequire = readEnv("SDM_REQUIRE_MODULE_SIGNATURE");
753
829
  const globalTrusted = globalThis.__SDM_TRUSTED_MODULE_SIGNERS__;
754
830
  const globalRequire = globalThis.__SDM_REQUIRE_MODULE_SIGNATURE__;
755
- const trustedPublicKeys = normalizeTrustedPublicKeys(
756
- envTrusted ?? globalTrusted,
757
- );
831
+ // The environment's list is read first; the global is used when the
832
+ // environment yields no key (unset, empty, blanks or commas only), so a
833
+ // variable that names nothing never hides the global list.
834
+ const envKeys = normalizeTrustedPublicKeys(envTrusted);
835
+ const trustedPublicKeys =
836
+ envKeys.length > 0 ? envKeys : normalizeTrustedPublicKeys(globalTrusted);
758
837
  const requireSignature =
838
+ options.verifySignature === true ||
839
+ trustedPublicKeys.length > 0 ||
759
840
  envRequire === "1" ||
760
841
  envRequire === "true" ||
761
842
  globalRequire === true ||