@fangorn-network/sdk 2026.7.13 → 2026.7.24

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 (61) hide show
  1. package/README.md +23 -2
  2. package/lib/cli/cli.js +18 -11
  3. package/lib/cli/index.d.ts +13 -13
  4. package/lib/config.d.ts +93 -92
  5. package/lib/contracts/data-registry/abi.d.ts +207 -35
  6. package/lib/contracts/data-registry/index.js +4 -4
  7. package/lib/contracts/index.d.ts +3 -1
  8. package/lib/contracts/index.js +3 -1
  9. package/lib/contracts/settlement-registry/abi.d.ts +47 -0
  10. package/lib/contracts/settlement-registry/abi.js +48 -0
  11. package/lib/contracts/settlement-registry/index.d.ts +25 -0
  12. package/lib/contracts/settlement-registry/index.js +40 -0
  13. package/lib/crypto/aes.d.ts +1 -8
  14. package/lib/crypto/aes.js +2 -34
  15. package/lib/crypto/encryption.d.ts +112 -26
  16. package/lib/crypto/encryption.js +106 -22
  17. package/lib/engine/index.js +6 -3
  18. package/lib/fangorn.d.ts +4 -4
  19. package/lib/fangorn.js +20 -18
  20. package/lib/harness/index.d.ts +4 -3
  21. package/lib/harness/index.js +9 -3
  22. package/lib/index.d.ts +3 -3
  23. package/lib/index.js +3 -3
  24. package/lib/providers/storage/car.js +3 -2
  25. package/lib/providers/storage/pinata.js +27 -7
  26. package/lib/{roles/repo → repo}/index.d.ts +1 -1
  27. package/lib/{roles/repo → repo}/index.js +1 -1
  28. package/lib/test/testbed.d.ts +2 -2
  29. package/lib/test/testbed.js +1 -1
  30. package/package.json +4 -2
  31. package/lib/ crypto/constants.d.ts +0 -4
  32. package/lib/ crypto/constants.js +0 -5
  33. package/lib/ crypto/merkle.d.ts +0 -10
  34. package/lib/ crypto/merkle.js +0 -34
  35. package/lib/ crypto/utils.d.ts +0 -1
  36. package/lib/ crypto/utils.js +0 -1
  37. package/lib/builders/a2aCardBuilder.d.ts +0 -28
  38. package/lib/builders/a2aCardBuilder.js +0 -105
  39. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/_polyval.js +0 -218
  40. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js +0 -261
  41. package/lib/node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/utils.js +0 -156
  42. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/curve.js +0 -299
  43. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/edwards.js +0 -532
  44. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/modular.js +0 -344
  45. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/abstract/montgomery.js +0 -137
  46. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js +0 -262
  47. package/lib/node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/utils.js +0 -150
  48. package/lib/roles/index.d.ts +0 -1
  49. package/lib/roles/index.js +0 -1
  50. package/lib/test/car_smoke.d.ts +0 -1
  51. package/lib/test/car_smoke.js +0 -81
  52. package/lib/test/cleanup-embeddings-testdata.d.ts +0 -1
  53. package/lib/test/cleanup-embeddings-testdata.js +0 -75
  54. package/lib/test/index.d.ts +0 -10
  55. package/lib/test/index.js +0 -27
  56. package/lib/test/setup-embeddings-testdata.d.ts +0 -11
  57. package/lib/test/setup-embeddings-testdata.js +0 -155
  58. package/lib/utils/index.d.ts +0 -11
  59. package/lib/utils/index.js +0 -29
  60. package/lib/utils/manifest.d.ts +0 -23
  61. package/lib/utils/manifest.js +0 -77
@@ -1,53 +1,139 @@
1
1
  import { Hex } from "viem";
2
2
 
3
3
  //#region src/crypto/encryption.d.ts
4
- /** A TEE-sealed field handle: where the ciphertext lives and how to verify/decrypt it. */
4
+ declare const GADGET_SELF_HKDF_V1 = "self-hkdf-v1";
5
+ declare const GADGET_WORKER_USDC_V1 = "worker-usdc-v1";
6
+ type Gadget = typeof GADGET_SELF_HKDF_V1 | typeof GADGET_WORKER_USDC_V1;
7
+ /**
8
+ * A sealed-field handle: where the ciphertext lives and how to verify/open it.
9
+ * This is what gets embedded in a vertex `payload[field]` in place of the
10
+ * plaintext value — the engine treats it as an opaque object.
11
+ */
5
12
  interface HandleFieldInput {
6
13
  "@type": "handle";
7
- uri: string;
14
+ /** R2 object key. Signed over in the /access request; resolve via {@link decryptHandle}. */
15
+ objectKey: string;
16
+ /**
17
+ * Access-worker endpoint. NOTE: this is the *access* worker, distinct from
18
+ * the Pinata-presign upload worker in the CLI config — do not conflate them.
19
+ */
8
20
  workerUrl: string;
9
21
  encryption: {
10
- gadget: string;
22
+ gadget: Gadget;
23
+ /**
24
+ * 32-byte resource id the ciphertext is bound to. Doubles as the HKDF
25
+ * binding and the Settlement Registry key (`isSettled`/`getPrice`).
26
+ */
27
+ resourceId: Hex;
11
28
  ciphertextHash: Hex;
12
- teePubkey: Hex;
29
+ /** Present only for worker-usdc-v1: the worker's static X25519 pubkey. */
30
+ workerPubkey?: Hex;
13
31
  };
14
32
  }
15
33
  /** Length of an X25519 public key, in bytes. */
16
34
  declare const X25519_PUBKEY_LENGTH = 32;
17
35
  declare const sha256Hex: (bytes: Uint8Array) => Hex;
18
36
  /**
19
- * Ephemeral-static ECDH to the TEE's static key, keyed to the resourceId.
37
+ * worker-usdc-v1 seal: ephemeral-static ECDH to the worker's static key, keyed
38
+ * to the resourceId.
20
39
  *
21
40
  * ciphertext = ephemeralPub(32) || nonce(12) || aes-256-gcm-ct
22
41
  *
23
- * Only the holder of the secret matching `teePubkey` can derive the same AES
42
+ * Only the holder of the secret matching `workerPubkey` can derive the same AES
24
43
  * key, and only with the matching `resourceId`.
25
44
  */
26
- declare function seal(plaintext: Uint8Array, teePubkey: Uint8Array, resourceId: Hex): Uint8Array;
45
+ declare function seal(plaintext: Uint8Array, workerPubkey: Uint8Array, resourceId: Hex): Uint8Array;
46
+ /**
47
+ * Inverse of {@link seal}. Recovers the plaintext given the worker's static
48
+ * secret and the same resourceId. This is the operation the access worker
49
+ * performs after the settlement gate passes; exposed here for parity testing
50
+ * and local tooling.
51
+ */
52
+ declare function unseal(ciphertext: Uint8Array, workerSecret: Uint8Array, resourceId: Hex): Uint8Array;
27
53
  /**
28
- * Inverse of {@link seal}. Recovers the plaintext given the TEE's static secret
29
- * and the same resourceId. This is the operation the real TEE performs after the
30
- * settlement gate passes; exposed here for parity testing and local tooling.
54
+ * self-hkdf-v1 seal: derive the AES key straight from the owner's own 32-byte
55
+ * secret, bound to the resourceId. No ECDH, no recipient — only a party holding
56
+ * `ownSecret` can re-derive the key.
57
+ *
58
+ * ciphertext = nonce(12) || aes-256-gcm-ct
31
59
  */
32
- declare function unseal(ciphertext: Uint8Array, teeSecret: Uint8Array, resourceId: Hex): Uint8Array;
33
- interface EncryptAndUploadParams {
60
+ declare function sealSelf(plaintext: Uint8Array, ownSecret: Uint8Array, resourceId: Hex): Uint8Array;
61
+ /** Inverse of {@link sealSelf}. */
62
+ declare function unsealSelf(ciphertext: Uint8Array, ownSecret: Uint8Array, resourceId: Hex): Uint8Array;
63
+ interface StorageTarget {
64
+ /** Access-worker upload endpoint (NOT the Pinata-presign worker). */
65
+ workerUrl: string;
66
+ /** Bearer token the worker requires for uploads. */
67
+ authToken: string;
68
+ contentType: string;
69
+ }
70
+ type EncryptAndUploadParams = {
71
+ gadget: typeof GADGET_SELF_HKDF_V1;
34
72
  plaintext: Uint8Array;
35
- /** 32-byte resource identifier the ciphertext is bound to (HKDF info + settlement key). */
36
73
  resourceId: Hex;
37
- storage: {
38
- workerUrl: string;
39
- authToken: string;
40
- contentType: string;
41
- };
42
- /** TEE's static X25519 public key (32 bytes). */
43
- teePubkey: Uint8Array;
44
- gadget?: string;
45
- }
74
+ storage: StorageTarget;
75
+ /** The owner's own 32-byte secret. */
76
+ ownSecret: Uint8Array;
77
+ } | {
78
+ gadget: typeof GADGET_WORKER_USDC_V1;
79
+ plaintext: Uint8Array;
80
+ resourceId: Hex;
81
+ storage: StorageTarget;
82
+ /** The access worker's static X25519 public key (32 bytes). */
83
+ workerPubkey: Uint8Array;
84
+ };
46
85
  /**
47
- * Seal `plaintext` to the TEE, upload the opaque ciphertext to the storage
48
- * worker, and return the manifest handle describing where to fetch it and how
49
- * to verify/decrypt it.
86
+ * Seal `plaintext` under the chosen gadget, upload the opaque ciphertext to the
87
+ * access worker (which writes it to R2), and return the handle describing where
88
+ * to fetch it and how to open it.
50
89
  */
51
90
  declare function encryptAndUpload(params: EncryptAndUploadParams): Promise<HandleFieldInput>;
91
+ /** Anything that can personal_sign a raw 32-byte hash (viem LocalAccount / WalletClient). */
92
+ interface AccessSigner {
93
+ signMessage(args: {
94
+ message: {
95
+ raw: Hex;
96
+ };
97
+ }): Promise<Hex>;
98
+ }
99
+ interface AccessRequest {
100
+ nullifier: Hex;
101
+ resourceId: Hex;
102
+ objectKey: string;
103
+ timestamp: number;
104
+ signature: Hex;
105
+ }
106
+ /**
107
+ * The message the worker recovers the stealth address from — must match
108
+ * `buildMessageHash` in the worker byte-for-byte:
109
+ * keccak256(abi.encodePacked(uint256 nullifier, bytes32 resourceId, string objectKey, uint64 timestamp))
110
+ */
111
+ declare function accessMessageHash(nullifier: Hex, resourceId: Hex, objectKey: string, timestamp: number): Hex;
112
+ /** Sign the packed message so the worker can recover the settling stealth address. */
113
+ declare function buildAccessRequest(params: {
114
+ signer: AccessSigner;
115
+ nullifier: Hex;
116
+ resourceId: Hex;
117
+ objectKey: string;
118
+ /** Unix seconds; defaults to now. Must be inside the worker's TIMESTAMP_WINDOW. */
119
+ timestamp?: number;
120
+ }): Promise<AccessRequest>;
121
+ interface DecryptHandleParams {
122
+ handle: HandleFieldInput;
123
+ /** Signs the /access request; its address is what the worker checks settlement for. */
124
+ signer: AccessSigner;
125
+ /** Per-read nullifier (replay/anonymity); passed through to the worker. */
126
+ nullifier: Hex;
127
+ /** self-hkdf-v1 only: the same 32-byte secret used to seal. */
128
+ ownSecret?: Uint8Array;
129
+ }
130
+ /**
131
+ * Resolve a {@link HandleFieldInput} back to plaintext via the worker's
132
+ * settlement-gated `POST /access`.
133
+ *
134
+ * self-hkdf-v1 bytes come back sealed → verify hash → unseal with ownSecret.
135
+ * worker-usdc-v1 the worker already unsealed → bytes are plaintext.
136
+ */
137
+ declare function decryptHandle(params: DecryptHandleParams): Promise<Uint8Array>;
52
138
  //#endregion
53
- export { EncryptAndUploadParams, HandleFieldInput, X25519_PUBKEY_LENGTH, encryptAndUpload, seal, sha256Hex, unseal };
139
+ export { AccessRequest, AccessSigner, DecryptHandleParams, EncryptAndUploadParams, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf };
@@ -1,11 +1,13 @@
1
- import { getRandomValues } from "./rand.js";
2
1
  import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
3
- import { x25519 } from "../node_modules/.pnpm/@noble_curves@1.9.7/node_modules/@noble/curves/esm/ed25519.js";
4
- import { bytesToHex, hexToBytes } from "viem";
2
+ import { getRandomValues } from "./rand.js";
3
+ import { bytesToHex, encodePacked, hexToBytes, keccak256 } from "viem";
4
+ import { x25519 } from "@noble/curves/ed25519";
5
5
  import { sha256 } from "@noble/hashes/sha2.js";
6
6
  import { hkdf } from "@noble/hashes/hkdf.js";
7
7
 
8
8
  //#region src/crypto/encryption.ts
9
+ const GADGET_SELF_HKDF_V1 = "self-hkdf-v1";
10
+ const GADGET_WORKER_USDC_V1 = "worker-usdc-v1";
9
11
  /** Length of an X25519 public key, in bytes. */
10
12
  const X25519_PUBKEY_LENGTH = 32;
11
13
  const utf8 = (s) => new TextEncoder().encode(s);
@@ -23,39 +25,59 @@ const hkdfSha256 = (ikm, salt, info, length) => hkdf(sha256, ikm, salt, info, le
23
25
  const sha256Hex = (bytes) => bytesToHex(sha256(bytes));
24
26
  const sealInfo = (resourceId) => concat(hexToBytes(resourceId), utf8(":sealed"));
25
27
  /**
26
- * Ephemeral-static ECDH to the TEE's static key, keyed to the resourceId.
28
+ * worker-usdc-v1 seal: ephemeral-static ECDH to the worker's static key, keyed
29
+ * to the resourceId.
27
30
  *
28
31
  * ciphertext = ephemeralPub(32) || nonce(12) || aes-256-gcm-ct
29
32
  *
30
- * Only the holder of the secret matching `teePubkey` can derive the same AES
33
+ * Only the holder of the secret matching `workerPubkey` can derive the same AES
31
34
  * key, and only with the matching `resourceId`.
32
35
  */
33
- function seal(plaintext, teePubkey, resourceId) {
36
+ function seal(plaintext, workerPubkey, resourceId) {
34
37
  const ephSec = x25519.utils.randomSecretKey();
35
38
  const ephPub = x25519.getPublicKey(ephSec);
36
- const aesKey = hkdfSha256(x25519.getSharedSecret(ephSec, teePubkey), void 0, sealInfo(resourceId), 32);
39
+ const aesKey = hkdfSha256(x25519.getSharedSecret(ephSec, workerPubkey), void 0, sealInfo(resourceId), 32);
37
40
  const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
38
41
  return concat(ephPub, nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
39
42
  }
40
43
  /**
41
- * Inverse of {@link seal}. Recovers the plaintext given the TEE's static secret
42
- * and the same resourceId. This is the operation the real TEE performs after the
43
- * settlement gate passes; exposed here for parity testing and local tooling.
44
+ * Inverse of {@link seal}. Recovers the plaintext given the worker's static
45
+ * secret and the same resourceId. This is the operation the access worker
46
+ * performs after the settlement gate passes; exposed here for parity testing
47
+ * and local tooling.
44
48
  */
45
- function unseal(ciphertext, teeSecret, resourceId) {
49
+ function unseal(ciphertext, workerSecret, resourceId) {
46
50
  const ephPub = ciphertext.slice(0, X25519_PUBKEY_LENGTH);
47
51
  const nonce = ciphertext.slice(X25519_PUBKEY_LENGTH, X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
48
52
  const aesCt = ciphertext.slice(X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
49
- return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(teeSecret, ephPub), void 0, sealInfo(resourceId), 32), aesCt, nonce);
53
+ return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(workerSecret, ephPub), void 0, sealInfo(resourceId), 32), aesCt, nonce);
50
54
  }
51
55
  /**
52
- * Seal `plaintext` to the TEE, upload the opaque ciphertext to the storage
53
- * worker, and return the manifest handle describing where to fetch it and how
54
- * to verify/decrypt it.
56
+ * self-hkdf-v1 seal: derive the AES key straight from the owner's own 32-byte
57
+ * secret, bound to the resourceId. No ECDH, no recipient — only a party holding
58
+ * `ownSecret` can re-derive the key.
59
+ *
60
+ * ciphertext = nonce(12) || aes-256-gcm-ct
61
+ */
62
+ function sealSelf(plaintext, ownSecret, resourceId) {
63
+ const aesKey = hkdfSha256(ownSecret, void 0, sealInfo(resourceId), 32);
64
+ const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
65
+ return concat(nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
66
+ }
67
+ /** Inverse of {@link sealSelf}. */
68
+ function unsealSelf(ciphertext, ownSecret, resourceId) {
69
+ const nonce = ciphertext.slice(0, GCM_NONCE_LENGTH);
70
+ const aesCt = ciphertext.slice(GCM_NONCE_LENGTH);
71
+ return aesGcmDecrypt(hkdfSha256(ownSecret, void 0, sealInfo(resourceId), 32), aesCt, nonce);
72
+ }
73
+ /**
74
+ * Seal `plaintext` under the chosen gadget, upload the opaque ciphertext to the
75
+ * access worker (which writes it to R2), and return the handle describing where
76
+ * to fetch it and how to open it.
55
77
  */
56
78
  async function encryptAndUpload(params) {
57
- const { plaintext, resourceId, storage, teePubkey, gadget = "tee-aes-v1" } = params;
58
- const ciphertext = seal(plaintext, teePubkey, resourceId);
79
+ const { plaintext, resourceId, storage } = params;
80
+ const ciphertext = params.gadget === GADGET_SELF_HKDF_V1 ? sealSelf(plaintext, params.ownSecret, resourceId) : seal(plaintext, params.workerPubkey, resourceId);
59
81
  const uploadRes = await fetch(`${storage.workerUrl}/upload`, {
60
82
  method: "POST",
61
83
  headers: {
@@ -64,19 +86,81 @@ async function encryptAndUpload(params) {
64
86
  },
65
87
  body: ciphertext
66
88
  });
67
- if (!uploadRes.ok) throw new Error(`upload failed: ${uploadRes.status}`);
89
+ if (!uploadRes.ok) throw new Error(`upload failed: ${uploadRes.status.toString()}`);
68
90
  const { objectKey } = await uploadRes.json();
69
91
  return {
70
92
  "@type": "handle",
71
- uri: objectKey,
93
+ objectKey,
72
94
  workerUrl: storage.workerUrl,
73
95
  encryption: {
74
- gadget,
96
+ gadget: params.gadget,
97
+ resourceId,
75
98
  ciphertextHash: sha256Hex(ciphertext),
76
- teePubkey: bytesToHex(teePubkey)
99
+ ...params.gadget === GADGET_WORKER_USDC_V1 ? { workerPubkey: bytesToHex(params.workerPubkey) } : {}
77
100
  }
78
101
  };
79
102
  }
103
+ /**
104
+ * The message the worker recovers the stealth address from — must match
105
+ * `buildMessageHash` in the worker byte-for-byte:
106
+ * keccak256(abi.encodePacked(uint256 nullifier, bytes32 resourceId, string objectKey, uint64 timestamp))
107
+ */
108
+ function accessMessageHash(nullifier, resourceId, objectKey, timestamp) {
109
+ return keccak256(encodePacked([
110
+ "uint256",
111
+ "bytes32",
112
+ "string",
113
+ "uint64"
114
+ ], [
115
+ BigInt(nullifier),
116
+ resourceId,
117
+ objectKey,
118
+ BigInt(timestamp)
119
+ ]));
120
+ }
121
+ /** Sign the packed message so the worker can recover the settling stealth address. */
122
+ async function buildAccessRequest(params) {
123
+ const timestamp = params.timestamp ?? Math.floor(Date.now() / 1e3);
124
+ const hash = accessMessageHash(params.nullifier, params.resourceId, params.objectKey, timestamp);
125
+ const signature = await params.signer.signMessage({ message: { raw: hash } });
126
+ return {
127
+ nullifier: params.nullifier,
128
+ resourceId: params.resourceId,
129
+ objectKey: params.objectKey,
130
+ timestamp,
131
+ signature
132
+ };
133
+ }
134
+ /**
135
+ * Resolve a {@link HandleFieldInput} back to plaintext via the worker's
136
+ * settlement-gated `POST /access`.
137
+ *
138
+ * self-hkdf-v1 bytes come back sealed → verify hash → unseal with ownSecret.
139
+ * worker-usdc-v1 the worker already unsealed → bytes are plaintext.
140
+ */
141
+ async function decryptHandle(params) {
142
+ const { handle, signer, nullifier } = params;
143
+ const { gadget, resourceId, ciphertextHash } = handle.encryption;
144
+ const access = await buildAccessRequest({
145
+ signer,
146
+ nullifier,
147
+ resourceId,
148
+ objectKey: handle.objectKey
149
+ });
150
+ const res = await fetch(`${handle.workerUrl}/access`, {
151
+ method: "POST",
152
+ headers: { "Content-Type": "application/json" },
153
+ body: JSON.stringify(access)
154
+ });
155
+ if (!res.ok) throw new Error(`access failed: ${res.status.toString()}`);
156
+ const bytes = new Uint8Array(await res.arrayBuffer());
157
+ if (gadget === GADGET_SELF_HKDF_V1) {
158
+ if (!params.ownSecret) throw new Error(`${gadget} requires ownSecret to decrypt`);
159
+ if (sha256Hex(bytes) !== ciphertextHash) throw new Error("ciphertext hash mismatch");
160
+ return unsealSelf(bytes, params.ownSecret, resourceId);
161
+ }
162
+ return bytes;
163
+ }
80
164
 
81
165
  //#endregion
82
- export { X25519_PUBKEY_LENGTH, encryptAndUpload, seal, sha256Hex, unseal };
166
+ export { GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf };
@@ -1,5 +1,5 @@
1
- import { buildPages, decodeBlock, encodeBlock, readPages } from "./graph.js";
2
1
  import { packCar, readCar } from "./car.js";
2
+ import { buildPages, decodeBlock, encodeBlock, readPages } from "./graph.js";
3
3
  import { CID } from "multiformats/cid";
4
4
  import { sha256 } from "multiformats/hashes/sha2";
5
5
  import * as Digest from "multiformats/hashes/digest";
@@ -341,9 +341,12 @@ var FangornEngine = class {
341
341
  const afterV = new Set(after.vertexLinks.map(String));
342
342
  const afterE = new Set(after.edgeLinks.map(String));
343
343
  const addedVertices = [];
344
- for (const link of after.vertexLinks) if (!beforeV.has(link.toString())) addedVertices.push(await this.decodeVertex(link, newCommit));
345
344
  const addedEdges = [];
346
- for (const link of after.edgeLinks) if (!beforeE.has(link.toString())) addedEdges.push(await this.decodeEdge(link, newCommit));
345
+ if (after.vertexLinks.length > 0 || after.edgeLinks.length > 0) {
346
+ if (!newCommit) throw new Error("Missing commit context required to decode graph changes");
347
+ for (const link of after.vertexLinks) if (!beforeV.has(link.toString())) addedVertices.push(await this.decodeVertex(link, newCommit));
348
+ for (const link of after.edgeLinks) if (!beforeE.has(link.toString())) addedEdges.push(await this.decodeEdge(link, newCommit));
349
+ }
347
350
  const removedVertexCids = before.vertexLinks.map(String).filter((c) => !afterV.has(c));
348
351
  const removedEdges = [];
349
352
  if (oldCommit) {
package/lib/fangorn.d.ts CHANGED
@@ -37,7 +37,7 @@ interface SubscribeOptions {
37
37
  declare class Fangorn {
38
38
  private readonly ctx;
39
39
  private _engine;
40
- private _metagraph;
40
+ private readonly _metagraph;
41
41
  private constructor();
42
42
  get engine(): FangornEngine;
43
43
  get metagraph(): MetagraphRegistry;
@@ -70,7 +70,7 @@ declare class Fangorn {
70
70
  /**
71
71
  * Stage one vertex and settle it on-chain in a single shot.
72
72
  */
73
- upload(repoName: string, payload: any, schemaId: string): Promise<{
73
+ upload(repoName: string, payload: unknown, schemaId: string): Promise<{
74
74
  payloadCid: string;
75
75
  commitCid: string;
76
76
  txHash: `0x${string}`;
@@ -84,7 +84,7 @@ declare class Fangorn {
84
84
  uploadBatch(repoName: string, vertices: {
85
85
  id: string;
86
86
  tag: string;
87
- payload: any;
87
+ payload: unknown;
88
88
  }[], edges?: {
89
89
  rel: string;
90
90
  from: string;
@@ -105,7 +105,7 @@ declare class Fangorn {
105
105
  vertices?: {
106
106
  id: string;
107
107
  tag: string;
108
- payload: any;
108
+ payload: unknown;
109
109
  }[];
110
110
  edges?: {
111
111
  rel: string;
package/lib/fangorn.js CHANGED
@@ -19,20 +19,16 @@ function resolveStorage(storage) {
19
19
  var Fangorn = class Fangorn {
20
20
  ctx;
21
21
  _engine = null;
22
- _metagraph = null;
22
+ _metagraph = new MetagraphRegistry();
23
23
  constructor(ctx) {
24
24
  this.ctx = ctx;
25
25
  }
26
26
  get engine() {
27
27
  if (!this.ctx.metadataStorage) throw new Error("fangorn.engine requires storage configurations. Pass { pinata: { ... } } to Fangorn.create()");
28
- if (!this._engine) {
29
- this._metagraph = new MetagraphRegistry();
30
- this._engine = new FangornEngine(this.ctx.metadataStorage, this._metagraph, this.ctx.dataRegistry);
31
- }
28
+ this._engine ??= new FangornEngine(this.ctx.metadataStorage, this._metagraph, this.ctx.dataRegistry);
32
29
  return this._engine;
33
30
  }
34
31
  get metagraph() {
35
- this.engine;
36
32
  return this._metagraph;
37
33
  }
38
34
  static create(options) {
@@ -90,11 +86,14 @@ var Fangorn = class Fangorn {
90
86
  return this.engine.createCommit({
91
87
  namespace: opts.namespace,
92
88
  base: opts.base,
93
- vertices: opts.vertices.map((v) => ({
94
- id: v.id,
95
- schemaId: v.tag,
96
- payload: v.payload
97
- })),
89
+ vertices: opts.vertices.map((v) => {
90
+ const safePayload = v.payload && typeof v.payload === "object" && !Array.isArray(v.payload) ? v.payload : { value: v.payload };
91
+ return {
92
+ id: v.id,
93
+ schemaId: v.tag,
94
+ payload: safePayload
95
+ };
96
+ }),
98
97
  edges: opts.edges.map((e) => ({
99
98
  relation: e.rel,
100
99
  from: e.from,
@@ -154,7 +153,7 @@ var Fangorn = class Fangorn {
154
153
  });
155
154
  const { txHash } = await this.engine.pushCommit(publisher, commitCid);
156
155
  return {
157
- payloadCid: vertexCids["v0"],
156
+ payloadCid: vertexCids.v0,
158
157
  commitCid: commitCid.toString(),
159
158
  txHash
160
159
  };
@@ -257,8 +256,10 @@ var Fangorn = class Fangorn {
257
256
  const seen = /* @__PURE__ */ new Set();
258
257
  const buffer = [];
259
258
  let wake = null;
260
- let failure = null;
261
- let stopped = false;
259
+ const subState = {
260
+ failure: null,
261
+ stopped: false
262
+ };
262
263
  const signal = () => {
263
264
  const w = wake;
264
265
  wake = null;
@@ -268,11 +269,11 @@ var Fangorn = class Fangorn {
268
269
  buffer.push(log);
269
270
  signal();
270
271
  }, (err) => {
271
- failure = err;
272
+ subState.failure = err;
272
273
  signal();
273
274
  }, opts.pollingInterval);
274
275
  const onAbort = () => {
275
- stopped = true;
276
+ subState.stopped = true;
276
277
  signal();
277
278
  };
278
279
  opts.signal?.addEventListener("abort", onAbort);
@@ -283,8 +284,8 @@ var Fangorn = class Fangorn {
283
284
  const change = await this.toNamespaceChange(log, ns, owner);
284
285
  if (change) yield change;
285
286
  }
286
- while (!stopped) {
287
- if (failure) throw failure;
287
+ while (!subState.stopped) {
288
+ if (subState.failure) throw subState.failure;
288
289
  if (buffer.length === 0) {
289
290
  await new Promise((res) => {
290
291
  wake = res;
@@ -292,6 +293,7 @@ var Fangorn = class Fangorn {
292
293
  continue;
293
294
  }
294
295
  const log = buffer.shift();
296
+ if (!log) continue;
295
297
  if (seen.has(log.logId)) continue;
296
298
  seen.add(log.logId);
297
299
  const change = await this.toNamespaceChange(log, ns, owner);
@@ -21,7 +21,7 @@ interface ProcessorResult {
21
21
  /** The entity type/tag for the graph vertex (defaults to "asset") */
22
22
  tag?: string;
23
23
  /** Custom metadata object attached to the vertex */
24
- payload?: Record<string, any>;
24
+ payload?: Record<string, unknown>;
25
25
  /** An array of target vertex IDs that this file links to */
26
26
  links?: string[];
27
27
  }
@@ -33,7 +33,7 @@ interface BuildAssetGraphOptions {
33
33
  interface Vertex {
34
34
  id: string;
35
35
  tag: string;
36
- payload: Record<string, any>;
36
+ payload: Record<string, unknown>;
37
37
  }
38
38
  interface Edge {
39
39
  rel: string;
@@ -53,5 +53,6 @@ declare function buildAssetGraph(dir: string, options?: BuildAssetGraphOptions):
53
53
  * Utility helper to scan markdown strings for standard markdown links or wikilinks.
54
54
  */
55
55
  declare function extractMarkdownLinks(content: string): string[];
56
+ declare const buildMarkdownGraph: (dir: string) => CommitFileGraph;
56
57
  //#endregion
57
- export { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, extractMarkdownLinks };
58
+ export { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks };
@@ -16,7 +16,6 @@ function buildAssetGraph(dir, options = {}) {
16
16
  for (const f of rawFiles) {
17
17
  const ext = extname(f).toLowerCase();
18
18
  const processor = processors[ext];
19
- if (!processor) continue;
20
19
  const fromId = getId(f);
21
20
  const fullPath = join(dir, f);
22
21
  const fileFacade = {
@@ -57,11 +56,18 @@ function extractMarkdownLinks(content) {
57
56
  const links = [];
58
57
  const convertToId = (str) => basename(str, extname(str));
59
58
  for (const match of content.matchAll(LINK_REGEX)) {
60
- const rawTarget = match[1] ?? match[2];
59
+ const rawTarget = match[1];
61
60
  if (rawTarget) links.push(convertToId(rawTarget));
62
61
  }
63
62
  return links;
64
63
  }
64
+ const buildMarkdownGraph = (dir) => {
65
+ return buildAssetGraph(dir, { processors: { ".md": (file) => ({
66
+ tag: "doc",
67
+ payload: { content: file.readText() },
68
+ links: extractMarkdownLinks(file.readText())
69
+ }) } });
70
+ };
65
71
 
66
72
  //#endregion
67
- export { buildAssetGraph, extractMarkdownLinks };
73
+ export { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks };
package/lib/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
2
+ import { AccessRequest, AccessSigner, DecryptHandleParams, EncryptAndUploadParams, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
2
3
  import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
3
- import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, extractMarkdownLinks } from "./harness/index.js";
4
+ import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
4
5
  import { PinataBackend } from "./providers/storage/pinata.js";
5
6
  import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
6
- import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
7
- export { AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, Fangorn, FangornConfig, FileFacade, NamespaceChange, PinataBackend, ProcessorResult, SubscribeOptions, SupportedNetworks, Vertex, addressToBytes32Array, buildAssetGraph, computeSchemaId, deserialize, extractMarkdownLinks, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };
7
+ export { AccessRequest, AccessSigner, AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, DecryptHandleParams, Edge, EncryptAndUploadParams, Fangorn, FangornConfig, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, NamespaceChange, PinataBackend, ProcessorResult, SubscribeOptions, SupportedNetworks, Vertex, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf };
package/lib/index.js CHANGED
@@ -2,7 +2,7 @@ import { FangornConfig, SupportedNetworks } from "./config.js";
2
2
  import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
3
3
  import { PinataBackend } from "./providers/storage/pinata.js";
4
4
  import { Fangorn } from "./fangorn.js";
5
- import { buildAssetGraph, extractMarkdownLinks } from "./harness/index.js";
6
- import { addressToBytes32Array, computeSchemaId, fieldToHex, hexToBytes32Array, hexToField, stringToBytes32Array } from "./utils/index.js";
5
+ import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
6
+ import { GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
7
7
 
8
- export { Fangorn, FangornConfig, PinataBackend, SupportedNetworks, addressToBytes32Array, buildAssetGraph, computeSchemaId, deserialize, extractMarkdownLinks, fieldToHex, hexToBytes32Array, hexToField, retrieveByCid, serialize, stringToBytes32Array };
8
+ export { Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, PinataBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf };
@@ -1,12 +1,13 @@
1
1
  import { serialize } from "./utils.js";
2
- import * as UnixFS from "@ipld/unixfs";
3
2
  import { CarWriter } from "@ipld/car";
3
+ import * as UnixFS from "@ipld/unixfs";
4
4
 
5
5
  //#region src/providers/storage/car.ts
6
6
  const enc = new TextEncoder();
7
7
  /** Filenames inside the CAR's UnixFS directory; ':' is legal but we keep it tidy. */
8
8
  function sanitize(name) {
9
- return name.replace(/[/\x00]/g, "_");
9
+ const sanitizeRegex = new RegExp("[/\\x00]", "g");
10
+ return name.replace(sanitizeRegex, "_");
10
11
  }
11
12
  /**
12
13
  * Pack named payloads into a SINGLE CAR with a UnixFS directory root.