@nexart/codemode-sdk 1.8.4 → 1.10.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.
Files changed (38) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +120 -1
  3. package/dist/cjs/browser.cjs +1 -1
  4. package/dist/cjs/browser.js +1 -1
  5. package/dist/cjs/core.cjs +406 -1
  6. package/dist/cjs/core.js +397 -2
  7. package/dist/cjs/node.cjs +1 -1
  8. package/dist/cjs/node.js +1 -1
  9. package/dist/esm/browser.cjs +1 -1
  10. package/dist/esm/browser.js +1 -1
  11. package/dist/esm/core.cjs +406 -1
  12. package/dist/esm/core.js +397 -2
  13. package/dist/esm/node.cjs +1 -1
  14. package/dist/esm/node.js +1 -1
  15. package/dist/types/sdk/codemode/attestation.d.ts +24 -0
  16. package/dist/types/sdk/codemode/attestation.d.ts.map +1 -0
  17. package/dist/types/sdk/codemode/canonicalJson.d.ts +16 -0
  18. package/dist/types/sdk/codemode/canonicalJson.d.ts.map +1 -0
  19. package/dist/types/sdk/codemode/cerProtocol.d.ts +40 -0
  20. package/dist/types/sdk/codemode/cerProtocol.d.ts.map +1 -0
  21. package/dist/types/sdk/codemode/core-index.d.ts +9 -1
  22. package/dist/types/sdk/codemode/core-index.d.ts.map +1 -1
  23. package/dist/types/sdk/codemode/entry/browser.d.ts +1 -1
  24. package/dist/types/sdk/codemode/entry/browser.d.ts.map +1 -1
  25. package/dist/types/sdk/codemode/nodeReceipt.d.ts +65 -0
  26. package/dist/types/sdk/codemode/nodeReceipt.d.ts.map +1 -0
  27. package/dist/types/sdk/codemode/runtime.d.ts +1 -1
  28. package/dist/types/sdk/codemode/runtime.d.ts.map +1 -1
  29. package/dist/types/sdk/codemode/types.d.ts +96 -0
  30. package/dist/types/sdk/codemode/types.d.ts.map +1 -1
  31. package/dist/types/sdk/codemode/verifyDetailed.d.ts +25 -0
  32. package/dist/types/sdk/codemode/verifyDetailed.d.ts.map +1 -0
  33. package/dist/types/sdk/codemode/version.d.ts +2 -2
  34. package/dist/types/sdk/codemode/version.d.ts.map +1 -1
  35. package/examples/sketch-minimal.js +27 -0
  36. package/examples/sketch-vars.js +59 -0
  37. package/examples/sketch.js +24 -0
  38. package/package.json +8 -2
package/CHANGELOG.md CHANGED
@@ -4,6 +4,64 @@ All notable changes to @nexart/codemode-sdk will be documented in this file.
4
4
 
5
5
  ---
6
6
 
7
+ ## [1.9.0] — 2026-02-25
8
+
9
+ ### Added — Attestation Parity (Reason Codes + Signed Receipt Verification)
10
+
11
+ **Feature Release — Additive only. No existing APIs changed.**
12
+
13
+ Brings the Code Mode SDK attestation layer to parity with `@nexart/ai-execution` v0.5.0.
14
+
15
+ #### New Types (`types.ts`)
16
+ - `CodeVerifyCode` — stable string-valued reason code enum (12 codes)
17
+ - `CodeVerificationResult` — `{ ok, code, details? }` returned by all verification functions
18
+ - `NodeReceiptVerifyResult` — alias of `CodeVerificationResult` for receipt-specific call sites
19
+ - `NodeKeysDocument` — shape of `/.well-known/nexart-node.json`
20
+ - `SignedAttestationReceipt` — payload signed by the attestation node
21
+ - `CodeAttestationReceipt` — normalised receipt extracted from any bundle layout
22
+
23
+ #### New Module — `nodeReceipt.ts`
24
+ - `verifyNodeReceiptSignature({ receipt, signatureB64Url, key })` — offline Ed25519 verification (browser + Node, @noble/ed25519)
25
+ - `fetchNodeKeys(nodeUrl)` — fetch `NodeKeysDocument` from attestation node
26
+ - `selectNodeKey(doc, kid?)` — select key by explicit kid → activeKid → first
27
+ - `verifyBundleAttestation(bundle, { nodeUrl, kid? })` — full offline attestation check with certificateHash cross-check (receipt-swap prevention), all three bundle layouts supported
28
+
29
+ #### New Module — `attestation.ts`
30
+ - `getAttestationReceipt(bundle)` — normalised receipt or null; recognises Layout A (top-level), Layout B (nested envelope), Layout C (legacy flat fields)
31
+ - `hasAttestation(bundle)` — boolean shorthand
32
+
33
+ #### New Module — `canonicalJson.ts`
34
+ - `toCanonicalJson(value)` — deterministic sorted-key JSON serialisation used for signing/verifying receipt bytes
35
+
36
+ #### New Dependencies
37
+ - `@noble/ed25519` ^3.0.0 (browser-compatible Ed25519) — declared in `dependencies` (installed per-package, no hoisting required)
38
+ - `@noble/hashes` ^1.7.0 (sha512 for noble ed25519) — same
39
+ - `@types/node` ^20.0.0 (dev) — added to `devDependencies` so `Buffer`/`process`/`require` resolve correctly under TypeScript strict mode; prevents "works only when hoisted" failures
40
+
41
+ #### TypeScript Config
42
+ - `"types": ["node"]` added to both `tsconfig.json` and `tsconfig.types.json` `compilerOptions`
43
+ - `nodeReceipt.ts`, `attestation.ts`, `canonicalJson.ts` added explicitly to both `files` arrays
44
+
45
+ #### Tests
46
+ - `tests/attestation.test.ts` — 25 tests covering all code paths, error cases, and all three bundle layouts; `npm run test:attestation`
47
+
48
+ #### Fixtures
49
+ - `fixtures/attestation/keys-v1.json`
50
+ - `fixtures/attestation/receipt-v1.json`
51
+ - `fixtures/attestation/receipt-v1.sig`
52
+ - `fixtures/attestation/receipt-v1.pub`
53
+
54
+ #### Docs
55
+ - README: new Attestation & Verification section with reason codes, `verifyBundleAttestation` usage, node keys endpoint, and receipt extraction helpers
56
+
57
+ #### Unchanged
58
+ - No protocol changes (v1.2.0)
59
+ - No changes to existing hashing or canonicalisation semantics
60
+ - All existing `executeCodeMode`, `createRuntime`, `validateSnapshot` APIs unchanged
61
+ - All existing smoke tests and execution boundary tests pass
62
+
63
+ ---
64
+
7
65
  ## [1.8.4] — 2026-01-25
8
66
 
9
67
  ### Fixed — Node ESM Compatibility
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @nexart/codemode-sdk
2
2
 
3
- **Version: 1.8.4 (Protocol v1.2.0)**
3
+ **Version: 1.9.0 (Protocol v1.2.0)**
4
4
 
5
5
  A deterministic execution runtime for reproducible, verifiable computation.
6
6
 
@@ -33,6 +33,43 @@ A deterministic execution runtime for reproducible, verifiable computation.
33
33
 
34
34
  ---
35
35
 
36
+ ## Quickstart: CLI Examples
37
+
38
+ The SDK includes ready-to-run example sketches. Use the `@nexart/cli` to render them via the canonical renderer.
39
+
40
+ ### Setup
41
+
42
+ ```bash
43
+ # Set up authentication for remote rendering
44
+ export NEXART_RENDERER_ENDPOINT=https://nexart-canonical-renderer-production.up.railway.app
45
+ export NEXART_API_KEY=nx_live_your_key_here
46
+ ```
47
+
48
+ ### Run Examples
49
+
50
+ ```bash
51
+ # Run the main example sketch
52
+ npx @nexart/cli run ./examples/sketch.js --seed 12345 --include-code --out ./out.png
53
+
54
+ # Verify the output is deterministic
55
+ npx @nexart/cli verify ./out.snapshot.json
56
+ # Output: [nexart] Result: PASS
57
+ ```
58
+
59
+ ### Example Sketches
60
+
61
+ | File | Description |
62
+ |------|-------------|
63
+ | `examples/sketch.js` | Main example — VAR controls + random palette, protocol-safe |
64
+ | `examples/sketch-minimal.js` | Simple shapes, no randomness — identical every run |
65
+ | `examples/sketch-vars.js` | Uses VAR + random() — demonstrates determinism |
66
+
67
+ ### Canonical Size
68
+
69
+ The canonical renderer enforces a fixed canvas size of **1950x2400**. Do not pass custom `--width` or `--height` to the canonical endpoint — the size is enforced server-side for consistent, verifiable output.
70
+
71
+ ---
72
+
36
73
  ## What This SDK Does
37
74
 
38
75
  This SDK provides a **deterministic runtime layer** for executing code that must produce identical output given identical inputs — across environments, over time, and under verification.
@@ -434,6 +471,88 @@ The following are rejected with `[Code Mode Protocol Error]`:
434
471
 
435
472
  ---
436
473
 
474
+ ## Attestation & Verification (v1.9.0)
475
+
476
+ ### Verification Reason Codes
477
+
478
+ Every verification function returns a `CodeVerificationResult` with a stable, machine-readable `code`:
479
+
480
+ ```typescript
481
+ import { CodeVerifyCode } from '@nexart/codemode-sdk';
482
+
483
+ // Stable string codes — safe to switch on, persist to storage, or compare:
484
+ // CodeVerifyCode.OK
485
+ // CodeVerifyCode.CERTIFICATE_HASH_MISMATCH
486
+ // CodeVerifyCode.SNAPSHOT_HASH_MISMATCH
487
+ // CodeVerifyCode.RENDER_HASH_MISMATCH
488
+ // CodeVerifyCode.INVALID_SHA256_FORMAT
489
+ // CodeVerifyCode.CANONICALIZATION_ERROR
490
+ // CodeVerifyCode.SCHEMA_ERROR
491
+ // CodeVerifyCode.NODE_RECEIPT_MISSING
492
+ // CodeVerifyCode.NODE_RECEIPT_KEY_NOT_FOUND
493
+ // CodeVerifyCode.NODE_RECEIPT_INVALID_SIGNATURE
494
+ // CodeVerifyCode.NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED
495
+ // CodeVerifyCode.UNKNOWN_ERROR
496
+ ```
497
+
498
+ ### Signed Node Receipt Verification (offline)
499
+
500
+ Verify that a Code Mode snapshot bundle was attested by an authorised NexArt attestation node — entirely offline, browser and Node.js compatible:
501
+
502
+ ```typescript
503
+ import { verifyBundleAttestation } from '@nexart/codemode-sdk';
504
+
505
+ const res = await verifyBundleAttestation(bundle, { nodeUrl: 'https://node.nexart.dev' });
506
+ console.log(res.ok, res.code);
507
+ // true "OK"
508
+ // false "CERTIFICATE_HASH_MISMATCH" (receipt doesn't match bundle)
509
+ // false "NODE_RECEIPT_INVALID_SIGNATURE" (tampered receipt)
510
+ ```
511
+
512
+ `verifyBundleAttestation` performs these steps automatically:
513
+ 1. Extracts the signed receipt and signature from the bundle (top-level or nested layout).
514
+ 2. Cross-checks `receipt.certificateHash === bundle.certificateHash` to prevent receipt-swapping attacks.
515
+ 3. Fetches the node's public keys from `/.well-known/nexart-node.json`.
516
+ 4. Selects the appropriate key (by `kid`, `activeKid`, or first available).
517
+ 5. Verifies the Ed25519 signature over the canonical JSON bytes of the receipt.
518
+
519
+ ### Node Keys Endpoint
520
+
521
+ Public keys are discovered automatically from:
522
+
523
+ ```
524
+ GET {nodeUrl}/.well-known/nexart-node.json
525
+ ```
526
+
527
+ You can also fetch or inspect keys directly:
528
+
529
+ ```typescript
530
+ import { fetchNodeKeys, selectNodeKey } from '@nexart/codemode-sdk';
531
+
532
+ const doc = await fetchNodeKeys('https://node.nexart.dev');
533
+ const { key } = selectNodeKey(doc, 'kid-optional');
534
+ ```
535
+
536
+ ### Receipt Extraction Helpers
537
+
538
+ Inspect bundles without performing full verification:
539
+
540
+ ```typescript
541
+ import { getAttestationReceipt, hasAttestation } from '@nexart/codemode-sdk';
542
+
543
+ if (hasAttestation(bundle)) {
544
+ const receipt = getAttestationReceipt(bundle);
545
+ console.log(receipt?.attestationId, receipt?.nodeId);
546
+ }
547
+ ```
548
+
549
+ Both helpers recognise:
550
+ - **Layout A** — `bundle.receipt` + `bundle.signature` (signed envelope)
551
+ - **Layout B** — `bundle.attestation.receipt` + `bundle.attestation.signature` (nested envelope)
552
+ - **Layout C** — legacy flat fields (`bundle.attestationId`, `bundle.nodeRuntimeHash`, …)
553
+
554
+ ---
555
+
437
556
  ## Examples
438
557
 
439
558
  ```bash
@@ -1068,7 +1068,7 @@ var init_soundart_sketches = __esm({
1068
1068
  });
1069
1069
 
1070
1070
  // version.ts
1071
- var SDK_VERSION = "1.8.4";
1071
+ var SDK_VERSION = "1.10.0";
1072
1072
  var PROTOCOL_VERSION = "1.2.0";
1073
1073
  var PROTOCOL_PHASE = 3;
1074
1074
 
@@ -1065,7 +1065,7 @@ var init_soundart_sketches = __esm({
1065
1065
  });
1066
1066
 
1067
1067
  // version.ts
1068
- var SDK_VERSION = "1.8.4";
1068
+ var SDK_VERSION = "1.10.0";
1069
1069
  var PROTOCOL_VERSION = "1.2.0";
1070
1070
  var PROTOCOL_PHASE = 3;
1071
1071
 
package/dist/cjs/core.cjs CHANGED
@@ -1,8 +1,11 @@
1
1
  'use strict';
2
2
 
3
+ var ed25519 = require('@noble/ed25519');
4
+ var sha2_js = require('@noble/hashes/sha2.js');
5
+
3
6
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
4
7
  // version.ts
5
- var SDK_VERSION = "1.8.4";
8
+ var SDK_VERSION = "1.10.0";
6
9
  var PROTOCOL_VERSION = "1.2.0";
7
10
  var PROTOCOL_PHASE = 3;
8
11
 
@@ -25,6 +28,20 @@ var DEFAULT_CONFIG = {
25
28
  minDuration: 1,
26
29
  maxDuration: 4
27
30
  };
31
+ var CodeVerifyCode = {
32
+ OK: "OK",
33
+ CERTIFICATE_HASH_MISMATCH: "CERTIFICATE_HASH_MISMATCH",
34
+ SNAPSHOT_HASH_MISMATCH: "SNAPSHOT_HASH_MISMATCH",
35
+ RENDER_HASH_MISMATCH: "RENDER_HASH_MISMATCH",
36
+ INVALID_SHA256_FORMAT: "INVALID_SHA256_FORMAT",
37
+ CANONICALIZATION_ERROR: "CANONICALIZATION_ERROR",
38
+ SCHEMA_ERROR: "SCHEMA_ERROR",
39
+ NODE_RECEIPT_MISSING: "NODE_RECEIPT_MISSING",
40
+ NODE_RECEIPT_KEY_NOT_FOUND: "NODE_RECEIPT_KEY_NOT_FOUND",
41
+ NODE_RECEIPT_INVALID_SIGNATURE: "NODE_RECEIPT_INVALID_SIGNATURE",
42
+ NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED: "NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED",
43
+ UNKNOWN_ERROR: "UNKNOWN_ERROR"
44
+ };
28
45
 
29
46
  // p5-runtime.ts
30
47
  var CODE_MODE_PROTOCOL_VERSION = PROTOCOL_VERSION;
@@ -1632,6 +1649,384 @@ function createEngine(config) {
1632
1649
  };
1633
1650
  }
1634
1651
 
1652
+ // canonicalJson.ts
1653
+ function toCanonicalJson(value) {
1654
+ if (value === null) return "null";
1655
+ if (typeof value === "boolean") return value ? "true" : "false";
1656
+ if (typeof value === "number") {
1657
+ if (!isFinite(value)) throw new Error(`toCanonicalJson: non-finite number ${value}`);
1658
+ return JSON.stringify(value);
1659
+ }
1660
+ if (typeof value === "string") return JSON.stringify(value);
1661
+ if (Array.isArray(value)) {
1662
+ return "[" + value.map(toCanonicalJson).join(",") + "]";
1663
+ }
1664
+ if (typeof value === "object") {
1665
+ const obj = value;
1666
+ const keys = Object.keys(obj).sort();
1667
+ return "{" + keys.filter((k) => obj[k] !== void 0 && typeof obj[k] !== "function").map((k) => `${JSON.stringify(k)}:${toCanonicalJson(obj[k])}`).join(",") + "}";
1668
+ }
1669
+ throw new Error(`toCanonicalJson: unsupported type ${typeof value}`);
1670
+ }
1671
+
1672
+ // nodeReceipt.ts
1673
+ ed25519.hashes.sha512 = sha2_js.sha512;
1674
+ function base64urlToBytes(s) {
1675
+ const pad = s.length % 4;
1676
+ const base64 = s.replace(/-/g, "+").replace(/_/g, "/") + (pad ? "=".repeat(4 - pad) : "");
1677
+ if (typeof Buffer !== "undefined") {
1678
+ return new Uint8Array(Buffer.from(base64, "base64"));
1679
+ }
1680
+ const binary = atob(base64);
1681
+ return Uint8Array.from(binary, (c) => c.charCodeAt(0));
1682
+ }
1683
+ async function verifyNodeReceiptSignature(params) {
1684
+ try {
1685
+ const { receipt, signatureB64Url, key } = params;
1686
+ let pubKeyBytes;
1687
+ if (key.jwk) {
1688
+ if (key.jwk.kty !== "OKP" || key.jwk.crv !== "Ed25519") {
1689
+ return {
1690
+ ok: false,
1691
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED,
1692
+ details: [
1693
+ `JWK must have kty=OKP and crv=Ed25519, got kty=${key.jwk.kty} crv=${key.jwk.crv}`
1694
+ ]
1695
+ };
1696
+ }
1697
+ pubKeyBytes = base64urlToBytes(key.jwk.x);
1698
+ } else if (key.rawB64Url) {
1699
+ pubKeyBytes = base64urlToBytes(key.rawB64Url);
1700
+ } else if (key.spkiB64) {
1701
+ const spkiBytes = base64urlToBytes(key.spkiB64);
1702
+ if (spkiBytes.length < 32) {
1703
+ return {
1704
+ ok: false,
1705
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED,
1706
+ details: ["SPKI key too short to extract Ed25519 public key"]
1707
+ };
1708
+ }
1709
+ pubKeyBytes = spkiBytes.slice(spkiBytes.length - 32);
1710
+ } else {
1711
+ return {
1712
+ ok: false,
1713
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED,
1714
+ details: ["No usable key provided: supply jwk, rawB64Url, or spkiB64"]
1715
+ };
1716
+ }
1717
+ if (pubKeyBytes.length !== 32) {
1718
+ return {
1719
+ ok: false,
1720
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED,
1721
+ details: [`Ed25519 public key must be 32 bytes, got ${pubKeyBytes.length}`]
1722
+ };
1723
+ }
1724
+ const sigBytes = base64urlToBytes(signatureB64Url);
1725
+ if (sigBytes.length !== 64) {
1726
+ return {
1727
+ ok: false,
1728
+ code: CodeVerifyCode.NODE_RECEIPT_INVALID_SIGNATURE,
1729
+ details: [`Ed25519 signature must be 64 bytes, got ${sigBytes.length}`]
1730
+ };
1731
+ }
1732
+ const msgBytes = new TextEncoder().encode(toCanonicalJson(receipt));
1733
+ const isValid = await ed25519.verify(sigBytes, msgBytes, pubKeyBytes);
1734
+ if (!isValid) {
1735
+ return {
1736
+ ok: false,
1737
+ code: CodeVerifyCode.NODE_RECEIPT_INVALID_SIGNATURE,
1738
+ details: ["Ed25519 signature verification failed"]
1739
+ };
1740
+ }
1741
+ return { ok: true, code: CodeVerifyCode.OK };
1742
+ } catch (err) {
1743
+ return {
1744
+ ok: false,
1745
+ code: CodeVerifyCode.NODE_RECEIPT_INVALID_SIGNATURE,
1746
+ details: [err instanceof Error ? err.message : String(err)]
1747
+ };
1748
+ }
1749
+ }
1750
+ async function fetchNodeKeys(nodeUrl) {
1751
+ const url = `${nodeUrl.replace(/\/+$/, "")}/.well-known/nexart-node.json`;
1752
+ const response = await fetch(url);
1753
+ if (!response.ok) {
1754
+ throw new Error(`Failed to fetch node keys from ${url}: HTTP ${response.status}`);
1755
+ }
1756
+ const data = await response.json();
1757
+ if (typeof data !== "object" || data === null) {
1758
+ throw new Error("Node keys response is not an object");
1759
+ }
1760
+ const doc = data;
1761
+ if (typeof doc.nodeId !== "string" || !Array.isArray(doc.keys)) {
1762
+ throw new Error("Node keys document missing required fields (nodeId, keys)");
1763
+ }
1764
+ return data;
1765
+ }
1766
+ function selectNodeKey(doc, kid) {
1767
+ if (kid) {
1768
+ const found = doc.keys.find((k) => k.kid === kid);
1769
+ if (!found) {
1770
+ return {
1771
+ error: {
1772
+ ok: false,
1773
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_NOT_FOUND,
1774
+ details: [`Key with kid="${kid}" not found in node keys document`]
1775
+ }
1776
+ };
1777
+ }
1778
+ return { key: found };
1779
+ }
1780
+ if (doc.activeKid) {
1781
+ const found = doc.keys.find((k) => k.kid === doc.activeKid);
1782
+ if (!found) {
1783
+ return {
1784
+ error: {
1785
+ ok: false,
1786
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_NOT_FOUND,
1787
+ details: [`activeKid="${doc.activeKid}" not found in keys array`]
1788
+ }
1789
+ };
1790
+ }
1791
+ return { key: found };
1792
+ }
1793
+ if (doc.keys.length === 0) {
1794
+ return {
1795
+ error: {
1796
+ ok: false,
1797
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_NOT_FOUND,
1798
+ details: ["No keys available in node keys document"]
1799
+ }
1800
+ };
1801
+ }
1802
+ return { key: doc.keys[0] };
1803
+ }
1804
+ function extractReceiptAndSignature(bundle) {
1805
+ if (typeof bundle !== "object" || bundle === null) return null;
1806
+ const b = bundle;
1807
+ if (typeof b.receipt === "object" && b.receipt !== null && typeof b.signature === "string") {
1808
+ return {
1809
+ receipt: b.receipt,
1810
+ signatureB64Url: b.signature,
1811
+ attestorKeyId: typeof b.attestorKeyId === "string" ? b.attestorKeyId : void 0
1812
+ };
1813
+ }
1814
+ if (typeof b.attestation === "object" && b.attestation !== null) {
1815
+ const att = b.attestation;
1816
+ if (typeof att.receipt === "object" && att.receipt !== null && typeof att.signature === "string") {
1817
+ return {
1818
+ receipt: att.receipt,
1819
+ signatureB64Url: att.signature,
1820
+ attestorKeyId: typeof att.attestorKeyId === "string" ? att.attestorKeyId : void 0
1821
+ };
1822
+ }
1823
+ }
1824
+ if (typeof b.meta === "object" && b.meta !== null) {
1825
+ const meta = b.meta;
1826
+ if (typeof meta.attestation === "object" && meta.attestation !== null) {
1827
+ const att = meta.attestation;
1828
+ if (typeof att.receipt === "object" && att.receipt !== null && typeof att.signature === "string") {
1829
+ return {
1830
+ receipt: att.receipt,
1831
+ signatureB64Url: att.signature,
1832
+ attestorKeyId: typeof att.attestorKeyId === "string" ? att.attestorKeyId : void 0
1833
+ };
1834
+ }
1835
+ }
1836
+ }
1837
+ return null;
1838
+ }
1839
+ async function verifyBundleAttestation(bundle, options) {
1840
+ const extracted = extractReceiptAndSignature(bundle);
1841
+ if (!extracted) {
1842
+ return {
1843
+ ok: false,
1844
+ code: CodeVerifyCode.NODE_RECEIPT_MISSING,
1845
+ details: ["No signed receipt found in bundle (expected bundle.receipt + bundle.signature or bundle.attestation envelope)"]
1846
+ };
1847
+ }
1848
+ const nodeId = extracted.receipt.nodeId;
1849
+ const resolvedKid = options.kid ?? extracted.attestorKeyId ?? extracted.receipt.attestorKeyId;
1850
+ function ctx() {
1851
+ const lines = [];
1852
+ if (nodeId) lines.push(`nodeId: ${nodeId}`);
1853
+ if (resolvedKid) lines.push(`kid: ${resolvedKid}`);
1854
+ return lines;
1855
+ }
1856
+ if (typeof bundle.certificateHash === "string") {
1857
+ const bundleCertHash = bundle.certificateHash;
1858
+ if (extracted.receipt.certificateHash !== bundleCertHash) {
1859
+ return {
1860
+ ok: false,
1861
+ code: CodeVerifyCode.CERTIFICATE_HASH_MISMATCH,
1862
+ details: [
1863
+ "Receipt certificateHash does not match bundle certificateHash",
1864
+ `receipt.certificateHash: ${extracted.receipt.certificateHash}`,
1865
+ `bundle.certificateHash: ${bundleCertHash}`,
1866
+ ...ctx()
1867
+ ]
1868
+ };
1869
+ }
1870
+ }
1871
+ let keysDoc;
1872
+ try {
1873
+ keysDoc = await fetchNodeKeys(options.nodeUrl);
1874
+ } catch (err) {
1875
+ return {
1876
+ ok: false,
1877
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_NOT_FOUND,
1878
+ details: [...ctx(), err instanceof Error ? err.message : String(err)]
1879
+ };
1880
+ }
1881
+ const selected = selectNodeKey(keysDoc, resolvedKid);
1882
+ if (selected.error) {
1883
+ return {
1884
+ ...selected.error,
1885
+ details: [...ctx(), ...selected.error.details ?? []]
1886
+ };
1887
+ }
1888
+ const keyEntry = selected.key;
1889
+ const keyParam = {};
1890
+ if (keyEntry.publicKeyJwk) keyParam.jwk = keyEntry.publicKeyJwk;
1891
+ else if (keyEntry.publicKey) keyParam.rawB64Url = keyEntry.publicKey;
1892
+ else if (keyEntry.publicKeySpkiB64) keyParam.spkiB64 = keyEntry.publicKeySpkiB64;
1893
+ else {
1894
+ return {
1895
+ ok: false,
1896
+ code: CodeVerifyCode.NODE_RECEIPT_KEY_FORMAT_UNSUPPORTED,
1897
+ details: [
1898
+ `Key kid="${keyEntry.kid}" has no usable public key field (publicKeyJwk, publicKey, or publicKeySpkiB64)`,
1899
+ ...ctx()
1900
+ ]
1901
+ };
1902
+ }
1903
+ const sigResult = await verifyNodeReceiptSignature({
1904
+ receipt: extracted.receipt,
1905
+ signatureB64Url: extracted.signatureB64Url,
1906
+ key: keyParam
1907
+ });
1908
+ const contextLines = ctx();
1909
+ if (contextLines.length === 0) return sigResult;
1910
+ return sigResult.ok ? { ok: true, code: CodeVerifyCode.OK, details: contextLines } : { ...sigResult, details: [...contextLines, ...sigResult.details ?? []] };
1911
+ }
1912
+
1913
+ // attestation.ts
1914
+ function getAttestationReceipt(bundle) {
1915
+ if (typeof bundle !== "object" || bundle === null) return null;
1916
+ const b = bundle;
1917
+ if (typeof b.receipt === "object" && b.receipt !== null && typeof b.signature === "string") {
1918
+ const r = b.receipt;
1919
+ return {
1920
+ attestationId: r.attestationId,
1921
+ attestedAt: r.attestedAt,
1922
+ nodeId: r.nodeId,
1923
+ attestorKeyId: r.attestorKeyId,
1924
+ nodeRuntimeHash: r.nodeRuntimeHash,
1925
+ certificateHash: r.certificateHash,
1926
+ protocolVersion: r.protocolVersion,
1927
+ receipt: r,
1928
+ signature: b.signature
1929
+ };
1930
+ }
1931
+ if (typeof b.attestation === "object" && b.attestation !== null) {
1932
+ const att = b.attestation;
1933
+ if (typeof att.receipt === "object" && att.receipt !== null && typeof att.signature === "string") {
1934
+ const r = att.receipt;
1935
+ return {
1936
+ attestationId: r.attestationId,
1937
+ attestedAt: r.attestedAt,
1938
+ nodeId: r.nodeId,
1939
+ attestorKeyId: r.attestorKeyId,
1940
+ nodeRuntimeHash: r.nodeRuntimeHash,
1941
+ certificateHash: r.certificateHash,
1942
+ protocolVersion: r.protocolVersion,
1943
+ receipt: r,
1944
+ signature: att.signature
1945
+ };
1946
+ }
1947
+ }
1948
+ if (typeof b.attestationId === "string") {
1949
+ return {
1950
+ attestationId: b.attestationId,
1951
+ attestedAt: typeof b.attestedAt === "string" ? b.attestedAt : "",
1952
+ nodeId: typeof b.nodeId === "string" ? b.nodeId : void 0,
1953
+ attestorKeyId: typeof b.attestorKeyId === "string" ? b.attestorKeyId : void 0,
1954
+ nodeRuntimeHash: typeof b.nodeRuntimeHash === "string" ? b.nodeRuntimeHash : void 0,
1955
+ certificateHash: typeof b.certificateHash === "string" ? b.certificateHash : void 0,
1956
+ protocolVersion: typeof b.protocolVersion === "string" ? b.protocolVersion : void 0
1957
+ };
1958
+ }
1959
+ return null;
1960
+ }
1961
+ function hasAttestation(bundle) {
1962
+ return getAttestationReceipt(bundle) !== null;
1963
+ }
1964
+
1965
+ // cerProtocol.ts
1966
+ var ReasonCode = {
1967
+ BUNDLE_HASH_MISMATCH: "BUNDLE_HASH_MISMATCH",
1968
+ NODE_SIGNATURE_INVALID: "NODE_SIGNATURE_INVALID",
1969
+ NODE_SIGNATURE_MISSING: "NODE_SIGNATURE_MISSING",
1970
+ RECEIPT_HASH_MISMATCH: "RECEIPT_HASH_MISMATCH",
1971
+ SCHEMA_VERSION_UNSUPPORTED: "SCHEMA_VERSION_UNSUPPORTED",
1972
+ RECORD_NOT_FOUND: "RECORD_NOT_FOUND",
1973
+ BUNDLE_CORRUPTED: "BUNDLE_CORRUPTED"
1974
+ };
1975
+
1976
+ // verifyDetailed.ts
1977
+ function validateSnapshotStructure(snapshot) {
1978
+ const codes = [];
1979
+ if (!snapshot || typeof snapshot !== "object") {
1980
+ codes.push(ReasonCode.BUNDLE_CORRUPTED);
1981
+ return codes;
1982
+ }
1983
+ if (snapshot.protocol !== "nexart") {
1984
+ codes.push(ReasonCode.SCHEMA_VERSION_UNSUPPORTED);
1985
+ }
1986
+ if (!snapshot.outputHash || !snapshot.outputHash.startsWith("sha256:")) {
1987
+ codes.push(ReasonCode.BUNDLE_CORRUPTED);
1988
+ }
1989
+ if (!snapshot.codeHash || !snapshot.codeHash.startsWith("sha256:")) {
1990
+ codes.push(ReasonCode.BUNDLE_CORRUPTED);
1991
+ }
1992
+ return codes;
1993
+ }
1994
+ function verifyCodeModeSnapshotDetailed(snapshot, options = {}) {
1995
+ const verifiedAt = (/* @__PURE__ */ new Date()).toISOString();
1996
+ const verifier = "@nexart/codemode-sdk";
1997
+ if (!snapshot || typeof snapshot !== "object" || Array.isArray(snapshot)) {
1998
+ return {
1999
+ status: "FAILED",
2000
+ checks: { bundleIntegrity: "FAIL", nodeSignature: "SKIPPED", receiptConsistency: "SKIPPED" },
2001
+ reasonCodes: [ReasonCode.BUNDLE_CORRUPTED],
2002
+ certificateHash: "",
2003
+ bundleType: "codemode.snapshot.v1",
2004
+ verifiedAt,
2005
+ verifier
2006
+ };
2007
+ }
2008
+ const snap = snapshot;
2009
+ const structureReasons = validateSnapshotStructure(snap);
2010
+ const hashReasons = [];
2011
+ if (options.outputHash !== void 0 && options.outputHash !== snap.outputHash) {
2012
+ hashReasons.push(ReasonCode.BUNDLE_HASH_MISMATCH);
2013
+ }
2014
+ if (options.codeHash !== void 0 && options.codeHash !== snap.codeHash) {
2015
+ hashReasons.push(ReasonCode.BUNDLE_HASH_MISMATCH);
2016
+ }
2017
+ const reasonCodes = [.../* @__PURE__ */ new Set([...structureReasons, ...hashReasons])];
2018
+ const bundleIntegrity = reasonCodes.length === 0 ? "PASS" : "FAIL";
2019
+ return {
2020
+ status: bundleIntegrity === "PASS" ? "VERIFIED" : "FAILED",
2021
+ checks: { bundleIntegrity, nodeSignature: "SKIPPED", receiptConsistency: "SKIPPED" },
2022
+ reasonCodes,
2023
+ certificateHash: snap.outputHash ?? "",
2024
+ bundleType: "codemode.snapshot.v1",
2025
+ verifiedAt,
2026
+ verifier
2027
+ };
2028
+ }
2029
+
1635
2030
  // core-index.ts
1636
2031
  var SDK_VERSION2 = SDK_VERSION;
1637
2032
  var SDK_NAME = "@nexart/codemode-sdk";
@@ -1639,11 +2034,13 @@ var SDK_NAME = "@nexart/codemode-sdk";
1639
2034
  exports.CODE_MODE_ENFORCEMENT = CODE_MODE_ENFORCEMENT;
1640
2035
  exports.CODE_MODE_PROTOCOL_PHASE = CODE_MODE_PROTOCOL_PHASE;
1641
2036
  exports.CODE_MODE_PROTOCOL_VERSION = CODE_MODE_PROTOCOL_VERSION;
2037
+ exports.CodeVerifyCode = CodeVerifyCode;
1642
2038
  exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
1643
2039
  exports.DEFAULT_VARS = DEFAULT_VARS;
1644
2040
  exports.PROTOCOL_IDENTITY = PROTOCOL_IDENTITY;
1645
2041
  exports.PROTOCOL_PHASE = PROTOCOL_PHASE;
1646
2042
  exports.PROTOCOL_VERSION = PROTOCOL_VERSION;
2043
+ exports.ReasonCode = ReasonCode;
1647
2044
  exports.SDK_NAME = SDK_NAME;
1648
2045
  exports.SDK_VERSION = SDK_VERSION2;
1649
2046
  exports.VAR_COUNT = VAR_COUNT;
@@ -1654,7 +2051,15 @@ exports.createEngine = createEngine;
1654
2051
  exports.createP5Runtime = createP5Runtime;
1655
2052
  exports.createProtocolVAR = createProtocolVAR;
1656
2053
  exports.executeCodeMode = executeCodeMode;
2054
+ exports.fetchNodeKeys = fetchNodeKeys;
2055
+ exports.getAttestationReceipt = getAttestationReceipt;
2056
+ exports.hasAttestation = hasAttestation;
1657
2057
  exports.injectTimeVariables = injectTimeVariables;
1658
2058
  exports.runLoopMode = runLoopMode;
1659
2059
  exports.runStaticMode = runStaticMode;
2060
+ exports.selectNodeKey = selectNodeKey;
2061
+ exports.toCanonicalJson = toCanonicalJson;
1660
2062
  exports.validateCodeModeSource = validateCodeModeSource;
2063
+ exports.verifyBundleAttestation = verifyBundleAttestation;
2064
+ exports.verifyCodeModeSnapshotDetailed = verifyCodeModeSnapshotDetailed;
2065
+ exports.verifyNodeReceiptSignature = verifyNodeReceiptSignature;