@fangorn-network/sdk 2026.7.24 → 2026.7.28

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/lib/fangorn.js CHANGED
@@ -1,20 +1,32 @@
1
1
  import { FangornConfig } from "./config.js";
2
+ import { SignedUrlBackend } from "./providers/storage/signed-url.js";
2
3
  import { PinataBackend } from "./providers/storage/pinata.js";
3
- import { FangornEngine, MetagraphRegistry, assertValidNamespace } from "./engine/index.js";
4
- import { DataRegistryClient } from "./contracts/data-registry/index.js";
4
+ import { FangornEngine, MetagraphRegistry, assertValidNamespace, rootHexFromCid } from "./engine/index.js";
5
+ import { DataRegistryClient, subspaceId } from "./contracts/data-registry/index.js";
6
+ import "./contracts/index.js";
5
7
  import { createPublicClient, createWalletClient, http } from "viem";
6
8
  import { privateKeyToAccount } from "viem/accounts";
7
9
  import { CID } from "multiformats/cid";
8
10
 
9
11
  //#region src/fangorn.ts
10
12
  const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
11
- function isPinataConfig(s) {
12
- return "pinata" in s;
13
+ /** Build a signer for the access worker's ownership handshake from a wallet. */
14
+ function walletSigner(walletClient) {
15
+ const account = walletClient.account;
16
+ if (!account) throw new Error("Signed-url storage requires a wallet account to sign the access worker's challenge.");
17
+ return {
18
+ address: account.address,
19
+ signMessage: (message) => walletClient.signMessage({
20
+ account,
21
+ message
22
+ })
23
+ };
13
24
  }
14
- function resolveStorage(storage) {
25
+ function resolveStorage(storage, walletClient, config) {
15
26
  if (!storage) return void 0;
16
- if (isPinataConfig(storage)) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
17
- throw new Error(`Invalid storage config: must be { pinata: { jwt, gateway } }, got ${JSON.stringify(storage)}`);
27
+ if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
28
+ if ("signedUrl" in storage) return new SignedUrlBackend(storage.signedUrl.workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway);
29
+ throw new Error(`Invalid storage config: must be { pinata: … } or { signedUrl: … }, got ${JSON.stringify(storage)}`);
18
30
  }
19
31
  var Fangorn = class Fangorn {
20
32
  ctx;
@@ -39,21 +51,21 @@ var Fangorn = class Fangorn {
39
51
  chain: resolvedConfig.chain,
40
52
  transport: http(resolvedConfig.rpcUrl)
41
53
  });
42
- const metadataStorage = resolveStorage(options.storage);
54
+ const metadataStorage = resolveStorage(options.storage, walletClient, resolvedConfig);
43
55
  const domain = options.domain ?? new URL(resolvedConfig.rpcUrl).hostname;
44
56
  const publicClient = createPublicClient({ transport: http(resolvedConfig.rpcUrl) });
45
57
  return new Fangorn({
46
58
  walletClient,
47
59
  metadataStorage,
48
60
  domain,
49
- dataRegistry: new DataRegistryClient(resolvedConfig.dataRegistryContractAddress, publicClient, walletClient),
61
+ dataRegistry: new DataRegistryClient(resolvedConfig.dataRegistryContractAddress, resolvedConfig.appId, publicClient, walletClient),
50
62
  config: resolvedConfig
51
63
  });
52
64
  }
53
- async reset() {
65
+ async reset(namespace) {
54
66
  const registry = this.getDataRegistry();
55
- const currentRoot = await registry.getNamespaceHead(this.getAddress());
56
- await registry.commitStateRoot(currentRoot, ZERO_BYTES32);
67
+ const currentRoot = await registry.getNamespaceHead(this.getAddress(), namespace);
68
+ await registry.commitStateRoot(namespace, currentRoot, ZERO_BYTES32);
57
69
  }
58
70
  /**
59
71
  * Register permissive (no required fields) schemas for every tag/relation a
@@ -117,7 +129,7 @@ var Fangorn = class Fangorn {
117
129
  txHash: void 0,
118
130
  alreadyInitialized: true
119
131
  };
120
- const head = await this.engine.resolveHeadCommit(publisher);
132
+ const head = await this.engine.resolveHeadCommit(publisher, repoName);
121
133
  const { commitCid } = await this.createCommit({
122
134
  namespace: repoName,
123
135
  base: head,
@@ -125,7 +137,7 @@ var Fangorn = class Fangorn {
125
137
  edges: [],
126
138
  message: `Initialize repository workspace: ${repoName}`
127
139
  });
128
- const { txHash } = await this.engine.pushCommit(publisher, commitCid);
140
+ const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
129
141
  return {
130
142
  cid: commitCid.toString(),
131
143
  commitCid: commitCid.toString(),
@@ -138,7 +150,7 @@ var Fangorn = class Fangorn {
138
150
  */
139
151
  async upload(repoName, payload, schemaId) {
140
152
  const publisher = this.getAddress();
141
- const head = await this.engine.resolveHeadCommit(publisher);
153
+ const head = await this.engine.resolveHeadCommit(publisher, repoName);
142
154
  if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
143
155
  const { commitCid, vertexCids } = await this.createCommit({
144
156
  namespace: repoName,
@@ -151,7 +163,7 @@ var Fangorn = class Fangorn {
151
163
  edges: [],
152
164
  message: `Upload to namespace ${repoName} under schema ${schemaId}`
153
165
  });
154
- const { txHash } = await this.engine.pushCommit(publisher, commitCid);
166
+ const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
155
167
  return {
156
168
  payloadCid: vertexCids.v0,
157
169
  commitCid: commitCid.toString(),
@@ -168,7 +180,7 @@ var Fangorn = class Fangorn {
168
180
  assertValidNamespace(repoName);
169
181
  if (vertices.length === 0 && edges.length === 0) throw new Error("uploadBatch requires at least one vertex or edge");
170
182
  const publisher = this.getAddress();
171
- const head = await this.engine.resolveHeadCommit(publisher);
183
+ const head = await this.engine.resolveHeadCommit(publisher, repoName);
172
184
  if (!head) throw new Error(`Repository '${repoName}' does not exist. Call initRepo() prior to uploading.`);
173
185
  const { commitCid, vertexCids } = await this.createCommit({
174
186
  namespace: repoName,
@@ -177,7 +189,7 @@ var Fangorn = class Fangorn {
177
189
  edges,
178
190
  message: `Batch upload to namespace ${repoName}`
179
191
  });
180
- const { txHash } = await this.engine.pushCommit(publisher, commitCid);
192
+ const { txHash } = await this.engine.pushCommit(publisher, repoName, commitCid);
181
193
  return {
182
194
  commitCid: commitCid.toString(),
183
195
  txHash,
@@ -208,17 +220,59 @@ var Fangorn = class Fangorn {
208
220
  vertexCids
209
221
  };
210
222
  }
211
- /** Settle a local commit as the on-chain head (fast-forward unless `force`). */
212
- async push(commitCid, opts) {
213
- const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), CID.parse(commitCid), opts);
223
+ /**
224
+ * Build a commit on top of `owner`'s current on-chain head and return it
225
+ * together with the UNSIGNED settlement tx — the self-custodial publish path.
226
+ *
227
+ * `commit` + `push` assume the caller holds the publishing key. A relay server
228
+ * doesn't: it builds and pins the commit with a keyless service wallet, then
229
+ * hands the tx to the user's browser wallet to sign. The head only moves when
230
+ * the publisher themselves signs, so the server is never a trusted party.
231
+ *
232
+ * Nothing is on-chain when this returns. The commit and its CAR are durable in
233
+ * storage, so if the user never signs, the result is an orphaned commit — junk
234
+ * in IPFS, not a corrupted timeline.
235
+ */
236
+ async prepareCommit(opts) {
237
+ assertValidNamespace(opts.namespace);
238
+ const registry = this.getDataRegistry();
239
+ const oldRoot = await registry.getNamespaceHead(opts.owner, opts.namespace);
240
+ const { commitCid, vertexCids } = await this.createCommit({
241
+ namespace: opts.namespace,
242
+ base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
243
+ vertices: opts.vertices ?? [],
244
+ edges: opts.edges ?? [],
245
+ message: opts.message,
246
+ replace: opts.replace
247
+ });
248
+ const newRoot = rootHexFromCid(commitCid);
249
+ return {
250
+ commitCid: commitCid.toString(),
251
+ oldRoot,
252
+ newRoot,
253
+ staged: {
254
+ vertices: opts.vertices?.length ?? 0,
255
+ edges: opts.edges?.length ?? 0
256
+ },
257
+ tx: await registry.prepareCommitStateRoot(opts.owner, opts.namespace, oldRoot, newRoot),
258
+ vertexCids
259
+ };
260
+ }
261
+ /**
262
+ * Settle a local commit as the on-chain head of `namespace` (fast-forward
263
+ * unless `force`). Each namespace has its own timeline, so pushes to
264
+ * different namespaces never contend for the same compare-and-swap.
265
+ */
266
+ async push(namespace, commitCid, opts) {
267
+ const { txHash, onChainTip } = await this.engine.pushCommit(this.getAddress(), namespace, CID.parse(commitCid), opts);
214
268
  return {
215
269
  txHash,
216
270
  onChainTip: onChainTip.toString()
217
271
  };
218
272
  }
219
- /** The owner's current on-chain tip commit CID, or null if they have no commits. */
220
- async onChainTip(owner) {
221
- const cid = await this.engine.resolveHeadCommit(owner);
273
+ /** The owner's current on-chain tip for a namespace, or null if they have none. */
274
+ async onChainTip(owner, namespace) {
275
+ const cid = await this.engine.resolveHeadCommit(owner, namespace);
222
276
  return cid ? cid.toString() : null;
223
277
  }
224
278
  /** Walk commit history from `head` (newest first). */
@@ -244,14 +298,31 @@ var Fangorn = class Fangorn {
244
298
  return this.engine.listNamespace(repoName, this.getAddress());
245
299
  }
246
300
  /**
247
- * Stream namespace-scoped changes as the on-chain root advances. Optionally
248
- * replays from `fromBlock` first (resume cursor), then watches live until the
249
- * `signal` aborts. Each yielded change carries `blockNumber` — persist it to
250
- * resume exactly where you left off.
301
+ * Stream changes to one publisher's namespace. Optionally replays from
302
+ * `fromBlock` first (resume cursor), then watches live until the `signal`
303
+ * aborts. Each yielded change carries `blockNumber` — persist it to resume
304
+ * exactly where you left off.
305
+ */
306
+ subscribe(opts) {
307
+ return this.streamCommits({
308
+ publisher: opts.owner ?? this.getAddress(),
309
+ namespace: opts.namespace
310
+ }, opts);
311
+ }
312
+ /**
313
+ * Stream changes across the *whole app* — every publisher, every namespace.
314
+ * The app-level feed: one topic filter on `app_id`, no per-publisher fan-out
315
+ * and no global root to keep in sync. Narrow it with `namespace` (every
316
+ * publisher's `docs`) or `owner` (one publisher's whole app footprint).
251
317
  */
252
- async *subscribe(opts) {
253
- const owner = opts.owner ?? this.getAddress();
254
- const ns = opts.namespace;
318
+ subscribeApp(opts = {}) {
319
+ return this.streamCommits({
320
+ publisher: opts.owner,
321
+ namespace: opts.namespace
322
+ }, opts);
323
+ }
324
+ /** Shared catch-up-then-live loop behind `subscribe` and `subscribeApp`. */
325
+ async *streamCommits(filter, opts) {
255
326
  const registry = this.getDataRegistry();
256
327
  const seen = /* @__PURE__ */ new Set();
257
328
  const buffer = [];
@@ -265,7 +336,7 @@ var Fangorn = class Fangorn {
265
336
  wake = null;
266
337
  w?.();
267
338
  };
268
- const unwatch = registry.watchStateCommitted(owner, (log) => {
339
+ const unwatch = registry.watchStateCommitted(filter, (log) => {
269
340
  buffer.push(log);
270
341
  signal();
271
342
  }, (err) => {
@@ -278,10 +349,10 @@ var Fangorn = class Fangorn {
278
349
  };
279
350
  opts.signal?.addEventListener("abort", onAbort);
280
351
  try {
281
- if (opts.fromBlock !== void 0) for (const log of await registry.getStateCommittedLogs(owner, opts.fromBlock)) {
352
+ if (opts.fromBlock !== void 0) for (const log of await registry.getStateCommittedLogs(filter, opts.fromBlock)) {
282
353
  if (seen.has(log.logId)) continue;
283
354
  seen.add(log.logId);
284
- const change = await this.toNamespaceChange(log, ns, owner);
355
+ const change = await this.toNamespaceChange(log);
285
356
  if (change) yield change;
286
357
  }
287
358
  while (!subState.stopped) {
@@ -296,7 +367,7 @@ var Fangorn = class Fangorn {
296
367
  if (!log) continue;
297
368
  if (seen.has(log.logId)) continue;
298
369
  seen.add(log.logId);
299
- const change = await this.toNamespaceChange(log, ns, owner);
370
+ const change = await this.toNamespaceChange(log);
300
371
  if (change) yield change;
301
372
  }
302
373
  } finally {
@@ -304,13 +375,23 @@ var Fangorn = class Fangorn {
304
375
  opts.signal?.removeEventListener("abort", onAbort);
305
376
  }
306
377
  }
307
- /** Resolve a raw `StateCommitted` log into a namespace change, or null if the namespace slice was untouched. */
308
- async toNamespaceChange(log, namespace, owner) {
378
+ /**
379
+ * Resolve a raw `StateCommitted` log into a namespace change, or null if the
380
+ * namespace slice was untouched.
381
+ *
382
+ * The event carries `keccak256(namespace)`, never the name, so the name comes
383
+ * from the commit's own root map — and must hash back to the subspace the
384
+ * commit was published into, or the publisher settled a commit for one
385
+ * namespace against another's timeline.
386
+ */
387
+ async toNamespaceChange(log) {
388
+ const namespace = await this.engine.namespaceOf(log.newRoot);
389
+ if (subspaceId(namespace) !== log.subspaceId) throw new Error(`commit ${log.newRoot} declares namespace "${namespace}", which does not match the subspace it was committed to (${log.subspaceId})`);
309
390
  const diff = await this.engine.namespaceDiff(log.oldRoot === ZERO_BYTES32 ? null : log.oldRoot, log.newRoot, namespace);
310
391
  if (!(diff.addedVertices.length || diff.removedVertexCids.length || diff.addedEdges.length || diff.removedEdges.length)) return null;
311
392
  return {
312
393
  namespace,
313
- owner,
394
+ owner: log.publisher,
314
395
  commitCid: this.engine.commitCidFromRootHex(log.newRoot),
315
396
  oldRoot: log.oldRoot,
316
397
  newRoot: log.newRoot,
@@ -325,9 +406,18 @@ var Fangorn = class Fangorn {
325
406
  return this.ctx.dataRegistry;
326
407
  }
327
408
  getStorage() {
328
- if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } to Fangorn.create()");
409
+ if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
329
410
  return this.ctx.metadataStorage;
330
411
  }
412
+ /**
413
+ * Swap the storage backend at runtime — e.g. move from access-worker signed
414
+ * URLs to your own Pinata JWT (or back). Rebuilds the engine on next use so it
415
+ * picks up the new backend.
416
+ */
417
+ setStorage(storage) {
418
+ this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config);
419
+ this._engine = null;
420
+ }
331
421
  getWalletClient() {
332
422
  return this.ctx.walletClient;
333
423
  }
package/lib/index.d.ts CHANGED
@@ -1,7 +1,14 @@
1
- import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
1
+ import { AppConfig, FangornConfig, SupportedNetworks, appId } from "./config.js";
2
+ import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
3
+ import { CommitFilter, DataRegistryClient, PreparedTx, PublisherStatus, StateCommittedLog, namespaceKey, subspaceId } from "./contracts/data-registry/index.js";
4
+ import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
5
+ import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
6
+ import "./contracts/index.js";
2
7
  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";
8
+ import { FangornContext, FangornCreateOptions, StorageConfig } from "./types/index.js";
3
9
  import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
4
10
  import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
5
11
  import { PinataBackend } from "./providers/storage/pinata.js";
6
- import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
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 };
12
+ import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
13
+ import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
14
+ export { AccessRequest, AccessSigner, AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, CommitFilter, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, DataRegistryClient, DecryptHandleParams, Edge, EncryptAndUploadParams, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, MAX_UPLOAD_ATTEMPTS, NamespaceChange, PinataBackend, PreparedTx, ProcessorResult, PublisherStatus, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SignedUrlSigner, StateCommittedLog, StorageConfig, SubscribeOptions, SupportedNetworks, Vertex, X25519_PUBKEY_LENGTH, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, namespaceKey, retrieveByCid, seal, sealSelf, serialize, sha256Hex, subspaceId, unseal, unsealSelf, withUploadRetry };
package/lib/index.js CHANGED
@@ -1,8 +1,14 @@
1
- import { FangornConfig, SupportedNetworks } from "./config.js";
2
- import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
1
+ import { FangornConfig, SupportedNetworks, appId } from "./config.js";
2
+ import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./providers/storage/signed-url.js";
3
+ import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
3
4
  import { PinataBackend } from "./providers/storage/pinata.js";
5
+ import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
6
+ import { DataRegistryClient, PublisherStatus, namespaceKey, subspaceId } from "./contracts/data-registry/index.js";
7
+ import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
8
+ import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
9
+ import "./contracts/index.js";
4
10
  import { Fangorn } from "./fangorn.js";
5
11
  import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
6
12
  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
13
 
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 };
14
+ export { DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, DataRegistryClient, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, PublisherStatus, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, accessMessageHash, appId, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, namespaceKey, retrieveByCid, seal, sealSelf, serialize, sha256Hex, subspaceId, unseal, unsealSelf, withUploadRetry };
@@ -1,4 +1,5 @@
1
1
  import { MetadataStorage, StorageMeta } from "./types.js";
2
2
  import { PinataBackend } from "./pinata.js";
3
+ import { SignedUrlBackend, SignedUrlSigner } from "./signed-url.js";
3
4
  import { deserialize, retrieveByCid, serialize } from "./utils.js";
4
- export { type MetadataStorage, PinataBackend, type StorageMeta, deserialize, retrieveByCid, serialize };
5
+ export { type MetadataStorage, PinataBackend, SignedUrlBackend, type SignedUrlSigner, type StorageMeta, deserialize, retrieveByCid, serialize };
@@ -1,4 +1,5 @@
1
+ import { SignedUrlBackend } from "./signed-url.js";
1
2
  import { deserialize, retrieveByCid, serialize } from "./utils.js";
2
3
  import { PinataBackend } from "./pinata.js";
3
4
 
4
- export { PinataBackend, deserialize, retrieveByCid, serialize };
5
+ export { PinataBackend, SignedUrlBackend, deserialize, retrieveByCid, serialize };
@@ -1,4 +1,4 @@
1
- import { retrieveByCid, serialize } from "./utils.js";
1
+ import { retrieveByCid, serialize, withUploadRetry } from "./utils.js";
2
2
  import { packCar } from "../../engine/car.js";
3
3
  import { keccak256, stringToBytes } from "viem";
4
4
  import { CID } from "multiformats/cid";
@@ -9,24 +9,6 @@ import { sha256 } from "multiformats/hashes/sha2";
9
9
 
10
10
  //#region src/providers/storage/pinata.ts
11
11
  const RAW_CODE = 85;
12
- const MAX_UPLOAD_ATTEMPTS = Math.max(1, Number(process.env.PINATA_UPLOAD_RETRIES ?? 6));
13
- function isTransientUpload(err) {
14
- const e = err;
15
- const s = typeof e.statusCode === "number" ? e.statusCode : 0;
16
- if (s === 408 || s === 425 || s === 429 || s >= 500) return true;
17
- const m = `${e.code ?? ""} ${e.message ?? ""}`;
18
- return /HTTP_ERROR|disconnect|timed?\s?out|timeout|ECONN|ETIMEDOUT|EAI_AGAIN|socket hang up|network|fetch failed|terminated|aborted|429|408|50\d/i.test(m);
19
- }
20
- async function withUploadRetry(label, fn) {
21
- for (let attempt = 1;; attempt++) try {
22
- return await fn();
23
- } catch (err) {
24
- if (attempt >= MAX_UPLOAD_ATTEMPTS || !isTransientUpload(err)) throw err;
25
- const delay = Math.min(3e4, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500);
26
- console.warn(` [pinata] upload "${label}" failed (attempt ${attempt.toString()}/${MAX_UPLOAD_ATTEMPTS.toString()}), retrying in ${(delay / 1e3).toFixed(1)}s: ${err.message}`);
27
- await new Promise((r) => setTimeout(r, delay));
28
- }
29
- }
30
12
  var PinataBackend = class {
31
13
  pinata;
32
14
  gateway;
@@ -0,0 +1,52 @@
1
+ import { MetadataStorage, RawBlock, StorageMeta } from "./types.js";
2
+ import { Hex } from "viem";
3
+
4
+ //#region src/providers/storage/signed-url.d.ts
5
+
6
+ /**
7
+ * The hosted pinata-url-provider worker. Used when no worker URL is supplied, so
8
+ * callers can upload via signed URLs with zero configuration. Point at your own
9
+ * deployment by passing a workerUrl.
10
+ */
11
+ declare const DEFAULT_SIGNED_URL_WORKER = "https://pinata-url-provider.fangorn-0be.workers.dev";
12
+ /** Just enough of a wallet to run the worker's ownership handshake. */
13
+ interface SignedUrlSigner {
14
+ address: Hex;
15
+ /** EIP-191 personal_sign of `message` (what the worker recovers against). */
16
+ signMessage(message: string): Promise<Hex>;
17
+ }
18
+ /**
19
+ * Storage backend for users who don't bring their own Pinata JWT.
20
+ *
21
+ * Uploads go through the pinata-url-provider Worker: prove wallet ownership by
22
+ * signing the worker's challenge, and it hands back a short-lived, single-use
23
+ * Pinata presigned upload URL that we POST the file to — the JWT never leaves
24
+ * the worker. Reads need no auth: every Fangorn block is public content, so we
25
+ * fetch it straight from a public IPFS gateway by CID (privacy is cryptographic,
26
+ * not access-controlled). Each upload runs a fresh handshake because the
27
+ * presigned URL is one-time and expires in minutes.
28
+ *
29
+ * JWT-only operations (server-side metadata queries / deletes) are unavailable
30
+ * here — switch to a PinataBackend (your own JWT) if you need them.
31
+ */
32
+ declare class SignedUrlBackend implements MetadataStorage {
33
+ private readonly signer;
34
+ private readonly gateway;
35
+ private readonly workerUrl;
36
+ constructor(workerUrl: string | undefined, signer: SignedUrlSigner, gateway: string);
37
+ /** Run the worker challenge handshake → one-time presigned upload URL + network. */
38
+ private requestUploadUrl;
39
+ private workerJson;
40
+ /** Upload bytes via a fresh one-time presigned URL; returns the pinned CID. */
41
+ private uploadBytes;
42
+ put(data: unknown, meta?: StorageMeta): Promise<string>;
43
+ putFile(bytes: Uint8Array, name: string): Promise<string>;
44
+ putBlock(block: RawBlock): Promise<void>;
45
+ getFile(uri: string): Promise<Uint8Array>;
46
+ getRawBlock(uri: string): Promise<Uint8Array>;
47
+ get<T>(uri: string): Promise<T>;
48
+ putMany(): Promise<Record<string, string>>;
49
+ delete(): Promise<void>;
50
+ }
51
+ //#endregion
52
+ export { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner };
@@ -0,0 +1,119 @@
1
+ import { fetchRawByCid, serialize, withUploadRetry } from "./utils.js";
2
+
3
+ //#region src/providers/storage/signed-url.ts
4
+ /**
5
+ * The hosted pinata-url-provider worker. Used when no worker URL is supplied, so
6
+ * callers can upload via signed URLs with zero configuration. Point at your own
7
+ * deployment by passing a workerUrl.
8
+ */
9
+ const DEFAULT_SIGNED_URL_WORKER = "https://pinata-url-provider.fangorn-0be.workers.dev";
10
+ /** A human-readable reason from a worker error response, detail included. */
11
+ function workerError(r) {
12
+ const base = r.error ?? "unknown error";
13
+ return r.detail ? `${base} (${r.detail})` : base;
14
+ }
15
+ /**
16
+ * Storage backend for users who don't bring their own Pinata JWT.
17
+ *
18
+ * Uploads go through the pinata-url-provider Worker: prove wallet ownership by
19
+ * signing the worker's challenge, and it hands back a short-lived, single-use
20
+ * Pinata presigned upload URL that we POST the file to — the JWT never leaves
21
+ * the worker. Reads need no auth: every Fangorn block is public content, so we
22
+ * fetch it straight from a public IPFS gateway by CID (privacy is cryptographic,
23
+ * not access-controlled). Each upload runs a fresh handshake because the
24
+ * presigned URL is one-time and expires in minutes.
25
+ *
26
+ * JWT-only operations (server-side metadata queries / deletes) are unavailable
27
+ * here — switch to a PinataBackend (your own JWT) if you need them.
28
+ */
29
+ var SignedUrlBackend = class {
30
+ workerUrl;
31
+ constructor(workerUrl, signer, gateway) {
32
+ this.signer = signer;
33
+ this.gateway = gateway;
34
+ this.workerUrl = workerUrl?.trim() ? workerUrl : DEFAULT_SIGNED_URL_WORKER;
35
+ }
36
+ /** Run the worker challenge handshake → one-time presigned upload URL + network. */
37
+ async requestUploadUrl(size, uploadId) {
38
+ const address = this.signer.address;
39
+ const challenge = await this.workerJson({
40
+ address,
41
+ size,
42
+ uploadId
43
+ });
44
+ if (!challenge.challenge) throw new Error(`Presigned-URL worker did not issue a challenge: ${workerError(challenge)}`);
45
+ const signature = await this.signer.signMessage(challenge.challenge);
46
+ const grant = await this.workerJson({
47
+ address,
48
+ message: challenge.challenge,
49
+ signature,
50
+ size,
51
+ uploadId
52
+ });
53
+ if (!grant.ok || !grant.uploadUrl) throw new Error(`Presigned-URL worker denied an upload URL: ${workerError(grant)}`);
54
+ return {
55
+ uploadUrl: grant.uploadUrl,
56
+ network: grant.network ?? "public"
57
+ };
58
+ }
59
+ async workerJson(body) {
60
+ const res = await fetch(this.workerUrl, {
61
+ method: "POST",
62
+ headers: { "content-type": "application/json" },
63
+ body: JSON.stringify(body)
64
+ });
65
+ return await res.json().catch(() => null) ?? { error: `HTTP ${res.status.toString()}` };
66
+ }
67
+ /** Upload bytes via a fresh one-time presigned URL; returns the pinned CID. */
68
+ uploadBytes(bytes, name, type) {
69
+ const uploadId = globalThis.crypto.randomUUID();
70
+ return withUploadRetry(name, async () => {
71
+ const { uploadUrl, network } = await this.requestUploadUrl(bytes.length, uploadId);
72
+ const fd = new FormData();
73
+ fd.append("network", network);
74
+ fd.append("file", new File([bytes], name, { type }));
75
+ const res = await fetch(uploadUrl, {
76
+ method: "POST",
77
+ body: fd
78
+ });
79
+ const data = await res.json().catch(() => null);
80
+ if (!res.ok) throw Object.assign(/* @__PURE__ */ new Error(`Pinata upload failed: ${data ? JSON.stringify(data) : "(no body)"}`), { statusCode: res.status });
81
+ const cid = data?.data?.cid;
82
+ if (!cid) throw new Error(`Pinata upload returned no CID: ${JSON.stringify(data)}`);
83
+ return cid;
84
+ });
85
+ }
86
+ async put(data, meta) {
87
+ return this.uploadBytes(new TextEncoder().encode(serialize(data)), meta?.name ?? "file", "text/plain");
88
+ }
89
+ async putFile(bytes, name) {
90
+ return this.uploadBytes(bytes, name, "application/octet-stream");
91
+ }
92
+ async putBlock(block) {
93
+ await this.uploadBytes(block.bytes, block.cid.toString(), "application/octet-stream");
94
+ }
95
+ async getFile(uri) {
96
+ return fetchRawByCid(uri, this.gateway);
97
+ }
98
+ async getRawBlock(uri) {
99
+ return fetchRawByCid(uri, this.gateway);
100
+ }
101
+ async get(uri) {
102
+ const bytes = await fetchRawByCid(uri, this.gateway);
103
+ const text = new TextDecoder().decode(bytes);
104
+ try {
105
+ return JSON.parse(text);
106
+ } catch {
107
+ return text;
108
+ }
109
+ }
110
+ putMany() {
111
+ throw new Error("putMany (batched CAR upload) is not available with signed URLs — provide your own Pinata JWT.");
112
+ }
113
+ delete() {
114
+ throw new Error("delete is not available with signed URLs — provide your own Pinata JWT.");
115
+ }
116
+ };
117
+
118
+ //#endregion
119
+ export { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend };
@@ -1,12 +1,30 @@
1
1
  import { PinataBackend } from "./pinata.js";
2
+ import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./signed-url.js";
2
3
 
3
4
  //#region src/providers/storage/utils.d.ts
4
5
  declare function serialize(data: unknown): string;
5
6
  declare function deserialize(text: string): unknown;
7
+ declare const MAX_UPLOAD_ATTEMPTS: number;
8
+ declare function isTransientUpload(err: unknown): boolean;
9
+ declare function withUploadRetry<T>(label: string, fn: () => Promise<T>): Promise<T>;
10
+ /**
11
+ * Fetch the exact raw bytes for a CID from a public IPFS gateway (no decoding),
12
+ * retrying to ride out gateway replication lag right after an upload. Blocks
13
+ * written via putBlock() are addressed by their raw-codec (0x55) sibling, so a
14
+ * dag-cbor ("bafyrei…") CID is translated before fetching — the same handling
15
+ * PinataBackend.fetchRaw does, but over a public gateway with no JWT.
16
+ */
17
+ declare function fetchRawByCid(cid: string, gateway?: string, {
18
+ retries,
19
+ timeoutMs
20
+ }?: {
21
+ retries?: number | undefined;
22
+ timeoutMs?: number | undefined;
23
+ }): Promise<Uint8Array>;
6
24
  /**
7
25
  * Fetch any content by CID from a public IPFS gateway.
8
26
  * No auth required — all Fangorn content is public; privacy is cryptographic.
9
27
  */
10
28
  declare function retrieveByCid<T>(cid: string, gateway?: string, timeoutSecond?: number): Promise<T>;
11
29
  //#endregion
12
- export { PinataBackend, deserialize, retrieveByCid, serialize };
30
+ export { DEFAULT_SIGNED_URL_WORKER, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, SignedUrlSigner, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry };