@fangorn-network/sdk 2026.7.12 → 2026.7.14

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 (72) hide show
  1. package/README.md +104 -69
  2. package/lib/cli/cli.js +26 -19
  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 +105 -21
  17. package/lib/engine/car.d.ts +10 -0
  18. package/lib/engine/car.js +37 -0
  19. package/lib/engine/graph.d.ts +70 -0
  20. package/lib/engine/graph.js +73 -0
  21. package/lib/engine/index.d.ts +109 -70
  22. package/lib/engine/index.js +296 -226
  23. package/lib/engine/test-helpers.d.ts +43 -0
  24. package/lib/engine/test-helpers.js +69 -0
  25. package/lib/fangorn.d.ts +28 -25
  26. package/lib/fangorn.js +118 -83
  27. package/lib/harness/index.d.ts +4 -3
  28. package/lib/harness/index.js +9 -3
  29. package/lib/index.d.ts +3 -3
  30. package/lib/index.js +2 -2
  31. package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/_polyval.js +1 -1
  32. package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/aes.js +1 -1
  33. package/lib/node_modules/{.pnpm/@noble_ciphers@1.3.0/node_modules/@noble → @noble}/ciphers/esm/utils.js +1 -1
  34. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/curve.js +1 -1
  35. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/edwards.js +1 -1
  36. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/modular.js +1 -1
  37. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/abstract/montgomery.js +1 -1
  38. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/ed25519.js +1 -1
  39. package/lib/node_modules/{.pnpm/@noble_curves@1.9.7/node_modules/@noble → @noble}/curves/esm/utils.js +1 -1
  40. package/lib/providers/storage/car.js +2 -1
  41. package/lib/providers/storage/pinata.d.ts +16 -9
  42. package/lib/providers/storage/pinata.js +34 -25
  43. package/lib/providers/storage/types.d.ts +18 -8
  44. package/lib/{roles/repo → repo}/index.d.ts +1 -1
  45. package/lib/{roles/repo → repo}/index.js +1 -1
  46. package/lib/test/testbed.d.ts +9 -7
  47. package/lib/test/testbed.js +3 -2
  48. package/package.json +3 -9
  49. package/lib/ crypto/constants.d.ts +0 -4
  50. package/lib/ crypto/constants.js +0 -5
  51. package/lib/ crypto/merkle.d.ts +0 -10
  52. package/lib/ crypto/merkle.js +0 -34
  53. package/lib/ crypto/utils.d.ts +0 -1
  54. package/lib/ crypto/utils.js +0 -1
  55. package/lib/builders/a2aCardBuilder.d.ts +0 -28
  56. package/lib/builders/a2aCardBuilder.js +0 -105
  57. package/lib/engine/blockstore.d.ts +0 -24
  58. package/lib/engine/blockstore.js +0 -85
  59. package/lib/roles/index.d.ts +0 -1
  60. package/lib/roles/index.js +0 -1
  61. package/lib/test/car_smoke.d.ts +0 -1
  62. package/lib/test/car_smoke.js +0 -81
  63. package/lib/test/cleanup-embeddings-testdata.d.ts +0 -1
  64. package/lib/test/cleanup-embeddings-testdata.js +0 -75
  65. package/lib/test/index.d.ts +0 -10
  66. package/lib/test/index.js +0 -27
  67. package/lib/test/setup-embeddings-testdata.d.ts +0 -11
  68. package/lib/test/setup-embeddings-testdata.js +0 -155
  69. package/lib/utils/index.d.ts +0 -11
  70. package/lib/utils/index.js +0 -29
  71. package/lib/utils/manifest.d.ts +0 -23
  72. package/lib/utils/manifest.js +0 -77
@@ -0,0 +1,47 @@
1
+ //#region src/contracts/settlement-registry/abi.d.ts
2
+ /**
3
+ * The Settlement Registry: the on-chain rail that gates who can read a
4
+ * settlement-priced resource. A consumer settles (pays) for a `resourceId`
5
+ * out of band; the access worker (and anyone else) then reads `isSettled` to
6
+ * decide whether to release the bytes.
7
+ *
8
+ * This is the exact ABI the deployed access worker calls
9
+ * (`webworker/src/index.ts`), kept in lock-step so the SDK and worker agree on
10
+ * the settlement check. Read-only here: the pay/settle write path is a separate
11
+ * payment rail (x402 / ERC-3009 USDC) and is out of band for the SDK.
12
+ */
13
+ declare const SETTLEMENT_REGISTRY_ABI: readonly [{
14
+ readonly inputs: readonly [{
15
+ readonly internalType: "address";
16
+ readonly name: "stealth_address";
17
+ readonly type: "address";
18
+ }, {
19
+ readonly internalType: "bytes32";
20
+ readonly name: "resource_id";
21
+ readonly type: "bytes32";
22
+ }];
23
+ readonly name: "isSettled";
24
+ readonly outputs: readonly [{
25
+ readonly internalType: "bool";
26
+ readonly name: "";
27
+ readonly type: "bool";
28
+ }];
29
+ readonly stateMutability: "view";
30
+ readonly type: "function";
31
+ }, {
32
+ readonly inputs: readonly [{
33
+ readonly internalType: "bytes32";
34
+ readonly name: "resource_id";
35
+ readonly type: "bytes32";
36
+ }];
37
+ readonly name: "getPrice";
38
+ readonly outputs: readonly [{
39
+ readonly internalType: "uint256";
40
+ readonly name: "";
41
+ readonly type: "uint256";
42
+ }];
43
+ readonly stateMutability: "view";
44
+ readonly type: "function";
45
+ }];
46
+ //#endregion
47
+ export { SETTLEMENT_REGISTRY_ABI };
@@ -0,0 +1,48 @@
1
+ //#region src/contracts/settlement-registry/abi.ts
2
+ /**
3
+ * The Settlement Registry: the on-chain rail that gates who can read a
4
+ * settlement-priced resource. A consumer settles (pays) for a `resourceId`
5
+ * out of band; the access worker (and anyone else) then reads `isSettled` to
6
+ * decide whether to release the bytes.
7
+ *
8
+ * This is the exact ABI the deployed access worker calls
9
+ * (`webworker/src/index.ts`), kept in lock-step so the SDK and worker agree on
10
+ * the settlement check. Read-only here: the pay/settle write path is a separate
11
+ * payment rail (x402 / ERC-3009 USDC) and is out of band for the SDK.
12
+ */
13
+ const SETTLEMENT_REGISTRY_ABI = [{
14
+ inputs: [{
15
+ internalType: "address",
16
+ name: "stealth_address",
17
+ type: "address"
18
+ }, {
19
+ internalType: "bytes32",
20
+ name: "resource_id",
21
+ type: "bytes32"
22
+ }],
23
+ name: "isSettled",
24
+ outputs: [{
25
+ internalType: "bool",
26
+ name: "",
27
+ type: "bool"
28
+ }],
29
+ stateMutability: "view",
30
+ type: "function"
31
+ }, {
32
+ inputs: [{
33
+ internalType: "bytes32",
34
+ name: "resource_id",
35
+ type: "bytes32"
36
+ }],
37
+ name: "getPrice",
38
+ outputs: [{
39
+ internalType: "uint256",
40
+ name: "",
41
+ type: "uint256"
42
+ }],
43
+ stateMutability: "view",
44
+ type: "function"
45
+ }];
46
+
47
+ //#endregion
48
+ export { SETTLEMENT_REGISTRY_ABI };
@@ -0,0 +1,25 @@
1
+ import { Address, Hex, PublicClient } from "viem";
2
+
3
+ //#region src/contracts/settlement-registry/index.d.ts
4
+
5
+ /**
6
+ * Read-only client for the Settlement Registry — the settlement rail behind
7
+ * gated reads. A resource is identified by its `resourceId` (bytes32, the same
8
+ * value produced by `resourceId(owner, schemaId, name)` in utils/manifest and
9
+ * bound into a sealed field's HKDF key).
10
+ *
11
+ * `getPrice(resourceId) === 0` means the resource is free (the worker lets any
12
+ * signed request through); a non-zero price means the caller must have settled.
13
+ * The pay/settle write path is a separate payment rail and is not modeled here.
14
+ */
15
+ declare class SettlementRegistryClient {
16
+ private contractAddress;
17
+ private publicClient;
18
+ constructor(contractAddress: Address, publicClient: PublicClient);
19
+ /** True if `stealthAddress` has settled for `resourceId`. */
20
+ isSettled(stealthAddress: Address, resourceId: Hex): Promise<boolean>;
21
+ /** Price of `resourceId` in the settlement token's smallest unit; 0 = free. */
22
+ getPrice(resourceId: Hex): Promise<bigint>;
23
+ }
24
+ //#endregion
25
+ export { SettlementRegistryClient };
@@ -0,0 +1,40 @@
1
+ import { SETTLEMENT_REGISTRY_ABI } from "./abi.js";
2
+
3
+ //#region src/contracts/settlement-registry/index.ts
4
+ /**
5
+ * Read-only client for the Settlement Registry — the settlement rail behind
6
+ * gated reads. A resource is identified by its `resourceId` (bytes32, the same
7
+ * value produced by `resourceId(owner, schemaId, name)` in utils/manifest and
8
+ * bound into a sealed field's HKDF key).
9
+ *
10
+ * `getPrice(resourceId) === 0` means the resource is free (the worker lets any
11
+ * signed request through); a non-zero price means the caller must have settled.
12
+ * The pay/settle write path is a separate payment rail and is not modeled here.
13
+ */
14
+ var SettlementRegistryClient = class {
15
+ constructor(contractAddress, publicClient) {
16
+ this.contractAddress = contractAddress;
17
+ this.publicClient = publicClient;
18
+ }
19
+ /** True if `stealthAddress` has settled for `resourceId`. */
20
+ async isSettled(stealthAddress, resourceId) {
21
+ return this.publicClient.readContract({
22
+ address: this.contractAddress,
23
+ abi: SETTLEMENT_REGISTRY_ABI,
24
+ functionName: "isSettled",
25
+ args: [stealthAddress, resourceId]
26
+ });
27
+ }
28
+ /** Price of `resourceId` in the settlement token's smallest unit; 0 = free. */
29
+ async getPrice(resourceId) {
30
+ return this.publicClient.readContract({
31
+ address: this.contractAddress,
32
+ abi: SETTLEMENT_REGISTRY_ABI,
33
+ functionName: "getPrice",
34
+ args: [resourceId]
35
+ });
36
+ }
37
+ };
38
+
39
+ //#endregion
40
+ export { SettlementRegistryClient };
@@ -1,5 +1,3 @@
1
- import { AesEncryptedData } from "./types.js";
2
-
3
1
  //#region src/crypto/aes.d.ts
4
2
  /** AES-256 key length, in bytes. */
5
3
  declare const AES_KEY_LENGTH = 32;
@@ -17,10 +15,5 @@ declare function aesGcmEncrypt(key: Uint8Array, plaintext: Uint8Array, nonce: Ui
17
15
  * {@link aesGcmEncrypt}. Throws if the tag does not verify.
18
16
  */
19
17
  declare function aesGcmDecrypt(key: Uint8Array, sealed: Uint8Array, nonce: Uint8Array): Uint8Array;
20
- declare function encryptData(data: string | Uint8Array): Promise<{
21
- encryptedData: AesEncryptedData;
22
- keyMaterial: Uint8Array<ArrayBuffer>;
23
- }>;
24
- declare function decryptData(encryptedData: AesEncryptedData, keyMaterial: Uint8Array<ArrayBuffer>): Promise<Uint8Array>;
25
18
  //#endregion
26
- export { AES_KEY_LENGTH, GCM_NONCE_LENGTH, GCM_TAG_LENGTH, aesGcmDecrypt, aesGcmEncrypt, decryptData, encryptData };
19
+ export { AES_KEY_LENGTH, GCM_NONCE_LENGTH, GCM_TAG_LENGTH, aesGcmDecrypt, aesGcmEncrypt };
package/lib/crypto/aes.js CHANGED
@@ -1,5 +1,4 @@
1
- import { gcm } from "../node_modules/.pnpm/@noble_ciphers@1.3.0/node_modules/@noble/ciphers/esm/aes.js";
2
- import { getRandomValues } from "./rand.js";
1
+ import { gcm } from "../node_modules/@noble/ciphers/esm/aes.js";
3
2
 
4
3
  //#region src/crypto/aes.ts
5
4
  /** AES-256 key length, in bytes. */
@@ -22,37 +21,6 @@ function aesGcmEncrypt(key, plaintext, nonce) {
22
21
  function aesGcmDecrypt(key, sealed, nonce) {
23
22
  return gcm(key, nonce).decrypt(sealed);
24
23
  }
25
- async function encryptData(data) {
26
- const salt = getRandomValues(new Uint8Array(16));
27
- const iv = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
28
- const keyMaterial = getRandomValues(new Uint8Array(AES_KEY_LENGTH));
29
- const sealed = aesGcmEncrypt(keyMaterial, typeof data === "string" ? new TextEncoder().encode(data) : data, iv);
30
- const ciphertext = sealed.slice(0, sealed.length - GCM_TAG_LENGTH);
31
- const authTag = sealed.slice(sealed.length - GCM_TAG_LENGTH);
32
- return {
33
- encryptedData: {
34
- ciphertext: new Uint8Array(ciphertext),
35
- iv,
36
- authTag: new Uint8Array(authTag),
37
- salt
38
- },
39
- keyMaterial
40
- };
41
- }
42
- async function decryptData(encryptedData, keyMaterial) {
43
- const ciphertext = toUint8Array(encryptedData.ciphertext);
44
- const iv = toUint8Array(encryptedData.iv);
45
- const authTag = toUint8Array(encryptedData.authTag);
46
- const sealed = new Uint8Array(ciphertext.length + authTag.length);
47
- sealed.set(ciphertext, 0);
48
- sealed.set(authTag, ciphertext.length);
49
- return aesGcmDecrypt(keyMaterial, sealed, iv);
50
- }
51
- function toUint8Array(data) {
52
- if (data instanceof Uint8Array) return data;
53
- if (Array.isArray(data)) return new Uint8Array(data);
54
- return new Uint8Array(Object.values(data));
55
- }
56
24
 
57
25
  //#endregion
58
- export { AES_KEY_LENGTH, GCM_NONCE_LENGTH, GCM_TAG_LENGTH, aesGcmDecrypt, aesGcmEncrypt, decryptData, encryptData };
26
+ export { AES_KEY_LENGTH, GCM_NONCE_LENGTH, GCM_TAG_LENGTH, aesGcmDecrypt, aesGcmEncrypt };
@@ -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;
27
46
  /**
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.
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;
53
+ /**
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
+ type 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 { x25519 } from "../node_modules/@noble/curves/esm/ed25519.js";
3
+ import { getRandomValues } from "./rand.js";
4
+ import { bytesToHex, encodePacked, hexToBytes, keccak256 } from "viem";
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: {
@@ -68,15 +90,77 @@ async function encryptAndUpload(params) {
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}`);
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 };
@@ -0,0 +1,10 @@
1
+ import { Block } from "./graph.js";
2
+ import { CID } from "multiformats/cid";
3
+
4
+ //#region src/engine/car.d.ts
5
+ /** Serialize blocks into CAR v1 bytes under a single root. */
6
+ declare function packCar(root: CID, blocks: Iterable<Block>): Promise<Uint8Array>;
7
+ /** Decode CAR bytes back into blocks. */
8
+ declare function readCar(bytes: Uint8Array): Promise<Block[]>;
9
+ //#endregion
10
+ export { packCar, readCar };
@@ -0,0 +1,37 @@
1
+ import { CID } from "multiformats/cid";
2
+ import { CarReader, CarWriter } from "@ipld/car";
3
+
4
+ //#region src/engine/car.ts
5
+ /** Serialize blocks into CAR v1 bytes under a single root. */
6
+ async function packCar(root, blocks) {
7
+ const { writer, out } = CarWriter.create([root]);
8
+ const collected = [];
9
+ const sink = (async () => {
10
+ for await (const part of out) collected.push(part);
11
+ })();
12
+ for (const block of blocks) await writer.put(block);
13
+ await writer.close();
14
+ await sink;
15
+ let total = 0;
16
+ for (const p of collected) total += p.length;
17
+ const buf = new Uint8Array(total);
18
+ let off = 0;
19
+ for (const p of collected) {
20
+ buf.set(p, off);
21
+ off += p.length;
22
+ }
23
+ return buf;
24
+ }
25
+ /** Decode CAR bytes back into blocks. */
26
+ async function readCar(bytes) {
27
+ const reader = await CarReader.fromBytes(bytes);
28
+ const blocks = [];
29
+ for await (const { cid, bytes: blockBytes } of reader.blocks()) blocks.push({
30
+ cid: CID.parse(cid.toString()),
31
+ bytes: blockBytes
32
+ });
33
+ return blocks;
34
+ }
35
+
36
+ //#endregion
37
+ export { packCar, readCar };