@fangorn-network/sdk 2026.10.28 → 2026.11.3
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.
- package/README.md +37 -653
- package/lib/cli/cli.js +46 -357
- package/lib/cli/index.d.ts +1 -4
- package/lib/cli/index.js +2 -20
- package/lib/cli/sell.d.ts +28 -0
- package/lib/cli/sell.js +95 -0
- package/lib/config.d.ts +163 -226
- package/lib/config.js +8 -35
- package/lib/contracts/data-registry/abi.d.ts +206 -6
- package/lib/contracts/data-registry/abi.js +415 -186
- package/lib/contracts/data-registry/index.d.ts +126 -2
- package/lib/contracts/data-registry/index.js +174 -1
- package/lib/contracts/index.d.ts +4 -7
- package/lib/contracts/index.js +4 -7
- package/lib/contracts/logs.d.ts +1 -1
- package/lib/contracts/logs.js +1 -1
- package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +288 -637
- package/lib/contracts/settlement-registry/abi.js +947 -0
- package/lib/contracts/settlement-registry/index.d.ts +141 -0
- package/lib/contracts/settlement-registry/index.js +209 -0
- package/lib/crypto/aes.d.ts +2 -2
- package/lib/crypto/aes.js +4 -4
- package/lib/crypto/encryption.d.ts +8 -109
- package/lib/crypto/encryption.js +16 -114
- package/lib/crypto/paid.d.ts +104 -0
- package/lib/crypto/paid.js +147 -0
- package/lib/engine/index.d.ts +23 -12
- package/lib/engine/index.js +68 -29
- package/lib/engine/records.d.ts +4 -7
- package/lib/engine/records.js +6 -6
- package/lib/engine/test-helpers.d.ts +2 -3
- package/lib/engine/test-helpers.js +7 -5
- package/lib/erc8004.js +7 -10
- package/lib/fangorn.d.ts +65 -96
- package/lib/fangorn.js +110 -168
- package/lib/feed.d.ts +7 -8
- package/lib/feed.js +7 -8
- package/lib/index.d.ts +10 -13
- package/lib/index.js +10 -13
- package/lib/providers/storage/signed-url.d.ts +2 -10
- package/lib/providers/storage/signed-url.js +5 -15
- package/lib/providers/storage/types.d.ts +1 -1
- package/lib/providers/storage/utils.js +5 -3
- package/lib/test/key-server.d.ts +12 -0
- package/lib/test/key-server.js +30 -0
- package/lib/test/mem-registry.d.ts +14 -19
- package/lib/test/mem-registry.js +44 -37
- package/lib/test/sdk-suite.d.ts +1 -4
- package/lib/test/sdk-suite.js +16 -87
- package/lib/test/testbed.d.ts +35 -45
- package/lib/test/testbed.js +29 -56
- package/lib/types/index.d.ts +6 -11
- package/package.json +2 -5
- package/lib/contracts/app-registry/abi.d.ts +0 -1306
- package/lib/contracts/app-registry/abi.js +0 -1493
- package/lib/contracts/app-registry/index.d.ts +0 -200
- package/lib/contracts/app-registry/index.js +0 -325
- package/lib/contracts/membership-registry/abi.js +0 -1333
- package/lib/contracts/membership-registry/index.d.ts +0 -79
- package/lib/contracts/membership-registry/index.js +0 -104
- package/lib/contracts/types.d.ts +0 -8
- package/lib/contracts/types.js +0 -10
- package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
- package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
- package/lib/harness/index.d.ts +0 -58
- package/lib/harness/index.js +0 -73
- package/lib/registry.d.ts +0 -118
- package/lib/registry.js +0 -184
package/lib/crypto/encryption.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
|
|
2
2
|
import { getRandomValues } from "./rand.js";
|
|
3
|
-
import {
|
|
4
|
-
import { x25519 } from "@noble/curves/ed25519";
|
|
3
|
+
import { hexToBytes } from "viem";
|
|
5
4
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
|
+
import { x25519 } from "@noble/curves/ed25519";
|
|
6
6
|
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
7
7
|
|
|
8
8
|
//#region src/crypto/encryption.ts
|
|
9
|
+
/** A field only its owner can open: sealSelf under the owner's own secret. */
|
|
9
10
|
const GADGET_SELF_HKDF_V1 = "self-hkdf-v1";
|
|
10
|
-
const GADGET_WORKER_USDC_V1 = "worker-usdc-v1";
|
|
11
11
|
/** Length of an X25519 public key, in bytes. */
|
|
12
12
|
const X25519_PUBKEY_LENGTH = 32;
|
|
13
13
|
const utf8 = (s) => new TextEncoder().encode(s);
|
|
14
|
-
function concat(...parts) {
|
|
14
|
+
function concat$1(...parts) {
|
|
15
15
|
const total = parts.reduce((n, p) => n + p.length, 0);
|
|
16
16
|
const out = new Uint8Array(total);
|
|
17
17
|
let off = 0;
|
|
@@ -22,38 +22,31 @@ function concat(...parts) {
|
|
|
22
22
|
return out;
|
|
23
23
|
}
|
|
24
24
|
const hkdfSha256 = (ikm, salt, info, length) => hkdf(sha256, ikm, salt, info, length);
|
|
25
|
-
const
|
|
26
|
-
const sealInfo = (resourceId) => concat(hexToBytes(resourceId), utf8(":sealed"));
|
|
25
|
+
const sealInfo = (resourceId) => concat$1(hexToBytes(resourceId), utf8(":sealed"));
|
|
27
26
|
/**
|
|
28
|
-
*
|
|
29
|
-
* to the resourceId.
|
|
27
|
+
* Ephemeral-static ECDH to the recipient's static key, keyed to the resourceId.
|
|
30
28
|
*
|
|
31
29
|
* ciphertext = ephemeralPub(32) || nonce(12) || aes-256-gcm-ct
|
|
32
30
|
*
|
|
33
|
-
* Only the holder of the secret matching `
|
|
31
|
+
* Only the holder of the secret matching `recipientPubkey` can derive the same AES
|
|
34
32
|
* key, and only with the matching `resourceId`.
|
|
35
33
|
*/
|
|
36
|
-
function seal(plaintext,
|
|
34
|
+
function seal(plaintext, recipientPubkey, resourceId) {
|
|
37
35
|
const ephSec = x25519.utils.randomSecretKey();
|
|
38
36
|
const ephPub = x25519.getPublicKey(ephSec);
|
|
39
|
-
const aesKey = hkdfSha256(x25519.getSharedSecret(ephSec,
|
|
37
|
+
const aesKey = hkdfSha256(x25519.getSharedSecret(ephSec, recipientPubkey), void 0, sealInfo(resourceId), 32);
|
|
40
38
|
const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
|
|
41
|
-
return concat(ephPub, nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
|
|
39
|
+
return concat$1(ephPub, nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
|
|
42
40
|
}
|
|
43
|
-
/**
|
|
44
|
-
|
|
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.
|
|
48
|
-
*/
|
|
49
|
-
function unseal(ciphertext, workerSecret, resourceId) {
|
|
41
|
+
/** Inverse of {@link seal}, with the recipient's secret and the same resourceId. */
|
|
42
|
+
function unseal(ciphertext, recipientSecret, resourceId) {
|
|
50
43
|
const ephPub = ciphertext.slice(0, X25519_PUBKEY_LENGTH);
|
|
51
44
|
const nonce = ciphertext.slice(X25519_PUBKEY_LENGTH, X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
|
|
52
45
|
const aesCt = ciphertext.slice(X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
|
|
53
|
-
return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(
|
|
46
|
+
return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(recipientSecret, ephPub), void 0, sealInfo(resourceId), 32), aesCt, nonce);
|
|
54
47
|
}
|
|
55
48
|
/**
|
|
56
|
-
*
|
|
49
|
+
* Derive the AES key straight from the owner's own 32-byte
|
|
57
50
|
* secret, bound to the resourceId. No ECDH, no recipient — only a party holding
|
|
58
51
|
* `ownSecret` can re-derive the key.
|
|
59
52
|
*
|
|
@@ -62,7 +55,7 @@ function unseal(ciphertext, workerSecret, resourceId) {
|
|
|
62
55
|
function sealSelf(plaintext, ownSecret, resourceId) {
|
|
63
56
|
const aesKey = hkdfSha256(ownSecret, void 0, sealInfo(resourceId), 32);
|
|
64
57
|
const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
|
|
65
|
-
return concat(nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
|
|
58
|
+
return concat$1(nonce, aesGcmEncrypt(aesKey, plaintext, nonce));
|
|
66
59
|
}
|
|
67
60
|
/** Inverse of {@link sealSelf}. */
|
|
68
61
|
function unsealSelf(ciphertext, ownSecret, resourceId) {
|
|
@@ -70,97 +63,6 @@ function unsealSelf(ciphertext, ownSecret, resourceId) {
|
|
|
70
63
|
const aesCt = ciphertext.slice(GCM_NONCE_LENGTH);
|
|
71
64
|
return aesGcmDecrypt(hkdfSha256(ownSecret, void 0, sealInfo(resourceId), 32), aesCt, nonce);
|
|
72
65
|
}
|
|
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.
|
|
77
|
-
*/
|
|
78
|
-
async function encryptAndUpload(params) {
|
|
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);
|
|
81
|
-
const uploadRes = await fetch(`${storage.workerUrl}/upload`, {
|
|
82
|
-
method: "POST",
|
|
83
|
-
headers: {
|
|
84
|
-
Authorization: `Bearer ${storage.authToken}`,
|
|
85
|
-
"Content-Type": storage.contentType
|
|
86
|
-
},
|
|
87
|
-
body: ciphertext
|
|
88
|
-
});
|
|
89
|
-
if (!uploadRes.ok) throw new Error(`upload failed: ${uploadRes.status.toString()}`);
|
|
90
|
-
const { objectKey } = await uploadRes.json();
|
|
91
|
-
return {
|
|
92
|
-
"@type": "handle",
|
|
93
|
-
objectKey,
|
|
94
|
-
workerUrl: storage.workerUrl,
|
|
95
|
-
encryption: {
|
|
96
|
-
gadget: params.gadget,
|
|
97
|
-
resourceId,
|
|
98
|
-
ciphertextHash: sha256Hex(ciphertext),
|
|
99
|
-
...params.gadget === GADGET_WORKER_USDC_V1 ? { workerPubkey: bytesToHex(params.workerPubkey) } : {}
|
|
100
|
-
}
|
|
101
|
-
};
|
|
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
|
-
}
|
|
164
66
|
|
|
165
67
|
//#endregion
|
|
166
|
-
export { GADGET_SELF_HKDF_V1,
|
|
68
|
+
export { GADGET_SELF_HKDF_V1, X25519_PUBKEY_LENGTH, seal, sealSelf, unseal, unsealSelf };
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { MetadataStorage } from "../providers/storage/types.js";
|
|
2
|
+
import { AccessSigner } from "./encryption.js";
|
|
3
|
+
import { Address, Hex } from "viem";
|
|
4
|
+
|
|
5
|
+
//#region src/crypto/paid.d.ts
|
|
6
|
+
declare const GADGET_FIELD_V1 = "field-v1";
|
|
7
|
+
/** What a repo key is sealed under. `repo` is `repoId(name)`. */
|
|
8
|
+
interface PaidScope {
|
|
9
|
+
chainId: number;
|
|
10
|
+
registry: Address;
|
|
11
|
+
publisher: Address;
|
|
12
|
+
repo: Hex;
|
|
13
|
+
generation: bigint;
|
|
14
|
+
}
|
|
15
|
+
/** The repo key, sealed to a key server. Public: it goes in the repo as a record. */
|
|
16
|
+
interface Deposit {
|
|
17
|
+
"@type": "deposit";
|
|
18
|
+
gadget: typeof GADGET_FIELD_V1;
|
|
19
|
+
chainId: number;
|
|
20
|
+
registry: Address;
|
|
21
|
+
publisher: Address;
|
|
22
|
+
repo: Hex;
|
|
23
|
+
generation: string;
|
|
24
|
+
keyServer: string;
|
|
25
|
+
sealed: Hex;
|
|
26
|
+
}
|
|
27
|
+
/** A paid field's value in a record payload. */
|
|
28
|
+
interface FieldHandle {
|
|
29
|
+
"@type": "handle";
|
|
30
|
+
gadget: typeof GADGET_FIELD_V1;
|
|
31
|
+
generation: string;
|
|
32
|
+
cid: string;
|
|
33
|
+
}
|
|
34
|
+
/** What a buyer posts to a key server's `/access`. */
|
|
35
|
+
interface AccessRequest {
|
|
36
|
+
publisher: Address;
|
|
37
|
+
repo: Hex;
|
|
38
|
+
generation: string;
|
|
39
|
+
/** `recordKey(id)`, or `WHOLE_REPO` for the repo key */
|
|
40
|
+
key: Hex;
|
|
41
|
+
/** A throwaway X25519 public key; the reply is sealed to it. */
|
|
42
|
+
readerKey: Hex;
|
|
43
|
+
/** The deposit's `sealed`. */
|
|
44
|
+
sealed: Hex;
|
|
45
|
+
timestamp: number;
|
|
46
|
+
signature: Hex;
|
|
47
|
+
}
|
|
48
|
+
declare const statement: (s: PaidScope) => Hex;
|
|
49
|
+
/**
|
|
50
|
+
* A random repo key. The publisher doesn't keep it: to seal more records later,
|
|
51
|
+
* it asks the key server for it (`requestKey` with `WHOLE_REPO`), like a buyer
|
|
52
|
+
* of the whole repo.
|
|
53
|
+
*/
|
|
54
|
+
declare const newRepoKey: () => Uint8Array;
|
|
55
|
+
declare const deriveRecordKey: (kRepo: Uint8Array, stmt: Hex, key: Hex) => Uint8Array;
|
|
56
|
+
/** `nonce(12) || AES-256-GCM(kRecord, plaintext, aad = stmt || key || field)` */
|
|
57
|
+
declare function encryptField(kRecord: Uint8Array, plaintext: Uint8Array, stmt: Hex, key: Hex, field: string): Uint8Array;
|
|
58
|
+
declare function decryptField(kRecord: Uint8Array, ciphertext: Uint8Array, stmt: Hex, key: Hex, field: string): Uint8Array;
|
|
59
|
+
declare function makeDeposit(p: {
|
|
60
|
+
kRepo: Uint8Array;
|
|
61
|
+
keyServerPubkey: Uint8Array;
|
|
62
|
+
keyServer: string;
|
|
63
|
+
scope: PaidScope;
|
|
64
|
+
}): Deposit;
|
|
65
|
+
/** Encrypt one field, upload the ciphertext, and return the handle that replaces the value. */
|
|
66
|
+
declare function sealField(p: {
|
|
67
|
+
plaintext: Uint8Array;
|
|
68
|
+
kRepo: Uint8Array;
|
|
69
|
+
scope: PaidScope;
|
|
70
|
+
/** `recordKey(id)` */
|
|
71
|
+
key: Hex;
|
|
72
|
+
field: string;
|
|
73
|
+
storage: Pick<MetadataStorage, "putFile">;
|
|
74
|
+
}): Promise<FieldHandle>;
|
|
75
|
+
/** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
|
|
76
|
+
declare const accessMessage: (stmt: Hex, key: Hex, readerKey: Hex, timestamp: number) => Hex;
|
|
77
|
+
declare function buildAccessRequest(p: {
|
|
78
|
+
signer: AccessSigner;
|
|
79
|
+
deposit: Deposit;
|
|
80
|
+
key: Hex;
|
|
81
|
+
readerKey: Hex;
|
|
82
|
+
/** unix seconds; defaults to now */
|
|
83
|
+
timestamp?: number;
|
|
84
|
+
}): Promise<AccessRequest>;
|
|
85
|
+
/** Ask the deposit's key server for `key`'s key: the record key, or the repo key for `WHOLE_REPO`. */
|
|
86
|
+
declare function requestKey(p: {
|
|
87
|
+
deposit: Deposit;
|
|
88
|
+
key: Hex;
|
|
89
|
+
signer: AccessSigner;
|
|
90
|
+
fetch?: typeof globalThis.fetch;
|
|
91
|
+
}): Promise<Uint8Array>;
|
|
92
|
+
/** Get the record's key, fetch the field's ciphertext and decrypt it. */
|
|
93
|
+
declare function openField(p: {
|
|
94
|
+
handle: FieldHandle;
|
|
95
|
+
deposit: Deposit;
|
|
96
|
+
/** `recordKey(id)` */
|
|
97
|
+
key: Hex;
|
|
98
|
+
field: string;
|
|
99
|
+
signer: AccessSigner;
|
|
100
|
+
storage: Pick<MetadataStorage, "getFile">;
|
|
101
|
+
fetch?: typeof globalThis.fetch;
|
|
102
|
+
}): Promise<Uint8Array>;
|
|
103
|
+
//#endregion
|
|
104
|
+
export { AccessRequest, Deposit, FieldHandle, GADGET_FIELD_V1, PaidScope, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement };
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
|
|
2
|
+
import { getRandomValues } from "./rand.js";
|
|
3
|
+
import { seal, unseal } from "./encryption.js";
|
|
4
|
+
import { bytesToHex, concat, encodeAbiParameters, hexToBytes, keccak256, toHex } from "viem";
|
|
5
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
6
|
+
import { x25519 } from "@noble/curves/ed25519";
|
|
7
|
+
import { hkdf } from "@noble/hashes/hkdf.js";
|
|
8
|
+
|
|
9
|
+
//#region src/crypto/paid.ts
|
|
10
|
+
const GADGET_FIELD_V1 = "field-v1";
|
|
11
|
+
const hkdf32 = (ikm, info) => hkdf(sha256, ikm, void 0, typeof info === "string" ? hexToBytes(info) : info, 32);
|
|
12
|
+
const statement = (s) => keccak256(encodeAbiParameters([
|
|
13
|
+
{ type: "string" },
|
|
14
|
+
{ type: "uint256" },
|
|
15
|
+
{ type: "address" },
|
|
16
|
+
{ type: "address" },
|
|
17
|
+
{ type: "bytes32" },
|
|
18
|
+
{ type: "uint64" }
|
|
19
|
+
], [
|
|
20
|
+
"fangorn:pay:v1",
|
|
21
|
+
BigInt(s.chainId),
|
|
22
|
+
s.registry,
|
|
23
|
+
s.publisher,
|
|
24
|
+
s.repo,
|
|
25
|
+
s.generation
|
|
26
|
+
]));
|
|
27
|
+
const scopeOf = (d) => ({
|
|
28
|
+
chainId: d.chainId,
|
|
29
|
+
registry: d.registry,
|
|
30
|
+
publisher: d.publisher,
|
|
31
|
+
repo: d.repo,
|
|
32
|
+
generation: BigInt(d.generation)
|
|
33
|
+
});
|
|
34
|
+
/**
|
|
35
|
+
* A random repo key. The publisher doesn't keep it: to seal more records later,
|
|
36
|
+
* it asks the key server for it (`requestKey` with `WHOLE_REPO`), like a buyer
|
|
37
|
+
* of the whole repo.
|
|
38
|
+
*/
|
|
39
|
+
const newRepoKey = () => getRandomValues(new Uint8Array(32));
|
|
40
|
+
const deriveRecordKey = (kRepo, stmt, key) => hkdf32(kRepo, concat([
|
|
41
|
+
stmt,
|
|
42
|
+
key,
|
|
43
|
+
toHex("fangorn:record-key")
|
|
44
|
+
]));
|
|
45
|
+
const fieldAad = (stmt, key, field) => hexToBytes(concat([
|
|
46
|
+
stmt,
|
|
47
|
+
key,
|
|
48
|
+
toHex(field)
|
|
49
|
+
]));
|
|
50
|
+
/** `nonce(12) || AES-256-GCM(kRecord, plaintext, aad = stmt || key || field)` */
|
|
51
|
+
function encryptField(kRecord, plaintext, stmt, key, field) {
|
|
52
|
+
const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
|
|
53
|
+
const ct = aesGcmEncrypt(kRecord, plaintext, nonce, fieldAad(stmt, key, field));
|
|
54
|
+
const out = new Uint8Array(nonce.length + ct.length);
|
|
55
|
+
out.set(nonce);
|
|
56
|
+
out.set(ct, nonce.length);
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
function decryptField(kRecord, ciphertext, stmt, key, field) {
|
|
60
|
+
return aesGcmDecrypt(kRecord, ciphertext.slice(GCM_NONCE_LENGTH), ciphertext.slice(0, GCM_NONCE_LENGTH), fieldAad(stmt, key, field));
|
|
61
|
+
}
|
|
62
|
+
function makeDeposit(p) {
|
|
63
|
+
const { scope } = p;
|
|
64
|
+
return {
|
|
65
|
+
"@type": "deposit",
|
|
66
|
+
gadget: GADGET_FIELD_V1,
|
|
67
|
+
chainId: scope.chainId,
|
|
68
|
+
registry: scope.registry,
|
|
69
|
+
publisher: scope.publisher,
|
|
70
|
+
repo: scope.repo,
|
|
71
|
+
generation: scope.generation.toString(),
|
|
72
|
+
keyServer: p.keyServer,
|
|
73
|
+
sealed: bytesToHex(seal(p.kRepo, p.keyServerPubkey, statement(scope)))
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
/** Encrypt one field, upload the ciphertext, and return the handle that replaces the value. */
|
|
77
|
+
async function sealField(p) {
|
|
78
|
+
const stmt = statement(p.scope);
|
|
79
|
+
const ct = encryptField(deriveRecordKey(p.kRepo, stmt, p.key), p.plaintext, stmt, p.key, p.field);
|
|
80
|
+
return {
|
|
81
|
+
"@type": "handle",
|
|
82
|
+
gadget: GADGET_FIELD_V1,
|
|
83
|
+
generation: p.scope.generation.toString(),
|
|
84
|
+
cid: await p.storage.putFile(ct, `${p.key}.${p.field}`)
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
|
|
88
|
+
const accessMessage = (stmt, key, readerKey, timestamp) => keccak256(encodeAbiParameters([
|
|
89
|
+
{ type: "string" },
|
|
90
|
+
{ type: "bytes32" },
|
|
91
|
+
{ type: "bytes32" },
|
|
92
|
+
{ type: "bytes32" },
|
|
93
|
+
{ type: "uint64" }
|
|
94
|
+
], [
|
|
95
|
+
"fangorn:access:v1",
|
|
96
|
+
stmt,
|
|
97
|
+
key,
|
|
98
|
+
readerKey,
|
|
99
|
+
BigInt(timestamp)
|
|
100
|
+
]));
|
|
101
|
+
async function buildAccessRequest(p) {
|
|
102
|
+
const { deposit, key, readerKey } = p;
|
|
103
|
+
const timestamp = p.timestamp ?? Math.floor(Date.now() / 1e3);
|
|
104
|
+
const raw = accessMessage(statement(scopeOf(deposit)), key, readerKey, timestamp);
|
|
105
|
+
return {
|
|
106
|
+
publisher: deposit.publisher,
|
|
107
|
+
repo: deposit.repo,
|
|
108
|
+
generation: deposit.generation,
|
|
109
|
+
key,
|
|
110
|
+
readerKey,
|
|
111
|
+
sealed: deposit.sealed,
|
|
112
|
+
timestamp,
|
|
113
|
+
signature: await p.signer.signMessage({ message: { raw } })
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** Ask the deposit's key server for `key`'s key: the record key, or the repo key for `WHOLE_REPO`. */
|
|
117
|
+
async function requestKey(p) {
|
|
118
|
+
const secret = x25519.utils.randomSecretKey();
|
|
119
|
+
const req = await buildAccessRequest({
|
|
120
|
+
signer: p.signer,
|
|
121
|
+
deposit: p.deposit,
|
|
122
|
+
key: p.key,
|
|
123
|
+
readerKey: bytesToHex(x25519.getPublicKey(secret))
|
|
124
|
+
});
|
|
125
|
+
const res = await (p.fetch ?? fetch)(`${p.deposit.keyServer}/access`, {
|
|
126
|
+
method: "POST",
|
|
127
|
+
headers: { "Content-Type": "application/json" },
|
|
128
|
+
body: JSON.stringify(req)
|
|
129
|
+
});
|
|
130
|
+
if (!res.ok) throw new Error(`key server refused: ${res.status.toString()} ${await res.text()}`);
|
|
131
|
+
const { sealed } = await res.json();
|
|
132
|
+
return unseal(hexToBytes(sealed), secret, statement(scopeOf(p.deposit)));
|
|
133
|
+
}
|
|
134
|
+
/** Get the record's key, fetch the field's ciphertext and decrypt it. */
|
|
135
|
+
async function openField(p) {
|
|
136
|
+
if (p.handle.generation !== p.deposit.generation) throw new Error("the handle and the deposit are for different generations");
|
|
137
|
+
const [kRecord, ct] = await Promise.all([requestKey({
|
|
138
|
+
deposit: p.deposit,
|
|
139
|
+
key: p.key,
|
|
140
|
+
signer: p.signer,
|
|
141
|
+
fetch: p.fetch
|
|
142
|
+
}), p.storage.getFile(p.handle.cid)]);
|
|
143
|
+
return decryptField(kRecord, ct, statement(scopeOf(p.deposit)), p.key, p.field);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
//#endregion
|
|
147
|
+
export { GADGET_FIELD_V1, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement };
|
package/lib/engine/index.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
1
|
+
import { CommitUpdate, Registry } from "../contracts/data-registry/index.js";
|
|
2
|
+
import "../contracts/index.js";
|
|
3
3
|
import { MetadataStorage } from "../providers/storage/types.js";
|
|
4
|
+
import { CommitBlock, Ref } from "./records.js";
|
|
4
5
|
import { Address, Hash, Hex } from "viem";
|
|
5
6
|
import { CID } from "multiformats/cid";
|
|
6
7
|
|
|
@@ -20,7 +21,7 @@ interface StoredRecord {
|
|
|
20
21
|
type: RecordType;
|
|
21
22
|
payload: Record<string, unknown>;
|
|
22
23
|
}
|
|
23
|
-
/** A decoded commit, γ = (e, parent, root) plus its repo name
|
|
24
|
+
/** A decoded commit, γ = (e, parent, root) plus its repo name and CAR (see CommitBlock). */
|
|
24
25
|
type CommitObject = CommitBlock;
|
|
25
26
|
interface RepoContents {
|
|
26
27
|
records: StoredRecord[];
|
|
@@ -44,11 +45,22 @@ declare const MAX_REPO_NAME_LENGTH = 256;
|
|
|
44
45
|
* The root of the graph, committed to IPFS, as hex
|
|
45
46
|
*/
|
|
46
47
|
declare function rootHexFromCid(commitCid: CID): Hex;
|
|
48
|
+
/** The update that settles `commit`. */
|
|
49
|
+
declare function commitUpdate(commit: CommitBlock): CommitUpdate;
|
|
50
|
+
/** The head the registry computes for `u`. */
|
|
51
|
+
declare function commitHead(u: CommitUpdate): Promise<Hex>;
|
|
52
|
+
/** A commit's update, signed by its publisher for anyone to submit. */
|
|
53
|
+
interface SignedUpdate {
|
|
54
|
+
publisher: Address;
|
|
55
|
+
update: CommitUpdate;
|
|
56
|
+
signature: Hex;
|
|
57
|
+
}
|
|
58
|
+
/** The CID a storage backend returned for a file, with or without an `ipfs://` prefix. */
|
|
59
|
+
declare function fileCid(uri: string): CID;
|
|
47
60
|
/** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
|
|
48
61
|
declare function assertValidRepoName(repo: RepoName): void;
|
|
49
62
|
/** One line of a commit's diff against its parent. */
|
|
50
63
|
interface CommitDiff {
|
|
51
|
-
message: string;
|
|
52
64
|
parent: string | null;
|
|
53
65
|
epoch: number;
|
|
54
66
|
repo: string;
|
|
@@ -69,7 +81,6 @@ interface CreateCommitOptions {
|
|
|
69
81
|
records: RecordInput[];
|
|
70
82
|
/** Ids of records to remove. Applied before `records`. */
|
|
71
83
|
deletes?: string[];
|
|
72
|
-
message: string;
|
|
73
84
|
/**
|
|
74
85
|
* When true, the staged records REPLACE the repo's previous contents
|
|
75
86
|
* (a snapshot commit — anything omitted is removed). Default: puts and
|
|
@@ -120,7 +131,7 @@ declare class FangornEngine {
|
|
|
120
131
|
resolveHeadCommit(publisher: Address, repo: RepoName): Promise<CID | null>;
|
|
121
132
|
/**
|
|
122
133
|
* Which repo a commit belongs to. Events carry only `keccak256(name)`, so
|
|
123
|
-
* this is how
|
|
134
|
+
* this is how a subscriber to every repo recovers the name.
|
|
124
135
|
*/
|
|
125
136
|
repoOf(rootHex: Hex): Promise<RepoName>;
|
|
126
137
|
/** The record state a commit holds. */
|
|
@@ -144,16 +155,16 @@ declare class FangornEngine {
|
|
|
144
155
|
* Settle a local commit as the on-chain head of one repo — the `update` of
|
|
145
156
|
* WHITEPAPER_1 §3.2. The commit and its CAR are already durable in storage
|
|
146
157
|
* (createCommit uploads them), so this is just the compare-and-swap.
|
|
147
|
-
*
|
|
148
|
-
* The commit's parent must BE the current head, not merely an ancestor of
|
|
149
|
-
* it: then the parent chain and the registry's log are one history
|
|
150
|
-
* (Theorem 3). Today's contract only checks the old root, so the parent is
|
|
151
|
-
* checked here.
|
|
152
158
|
*/
|
|
153
159
|
pushCommit(publisher: Address, repo: RepoName, commitCid: CID): Promise<{
|
|
154
160
|
txHash: Hash;
|
|
155
161
|
onChainTip: CID;
|
|
156
162
|
}>;
|
|
163
|
+
/** `pushCommit`, signed by this registry's wallet for anyone to submit with `relayCommit`. */
|
|
164
|
+
signCommit(publisher: Address, repo: RepoName, commitCid: CID): Promise<SignedUpdate>;
|
|
165
|
+
relayCommit(s: SignedUpdate): Promise<Hash>;
|
|
166
|
+
/** The update for `commitCid`, once it is one the registry will take as the next head. */
|
|
167
|
+
settleable(publisher: Address, repo: RepoName, commitCid: CID): Promise<CommitUpdate>;
|
|
157
168
|
/** Walk the parent chain from `tip` toward the root, newest first. */
|
|
158
169
|
walkParents(tip: CID, max?: number): AsyncGenerator<{
|
|
159
170
|
cid: CID;
|
|
@@ -192,4 +203,4 @@ declare class FangornEngine {
|
|
|
192
203
|
readRecord(publisher: Address, repo: RepoName, id: string): Promise<StoredRecord | null>;
|
|
193
204
|
}
|
|
194
205
|
//#endregion
|
|
195
|
-
export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, StoredRecord, assertValidRepoName, rootHexFromCid };
|
|
206
|
+
export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, SignedUpdate, StoredRecord, assertValidRepoName, commitHead, commitUpdate, fileCid, rootHexFromCid };
|