@fangorn-network/sdk 2026.7.14 → 2026.7.27

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,4 +1,5 @@
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
4
  import { FangornEngine, MetagraphRegistry, assertValidNamespace } from "./engine/index.js";
4
5
  import { DataRegistryClient } from "./contracts/data-registry/index.js";
@@ -8,31 +9,37 @@ import { CID } from "multiformats/cid";
8
9
 
9
10
  //#region src/fangorn.ts
10
11
  const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
11
- function isPinataConfig(s) {
12
- return "pinata" in s;
12
+ /** Build a signer for the access worker's ownership handshake from a wallet. */
13
+ function walletSigner(walletClient) {
14
+ const account = walletClient.account;
15
+ if (!account) throw new Error("Signed-url storage requires a wallet account to sign the access worker's challenge.");
16
+ return {
17
+ address: account.address,
18
+ signMessage: (message) => walletClient.signMessage({
19
+ account,
20
+ message
21
+ })
22
+ };
13
23
  }
14
- function resolveStorage(storage) {
24
+ function resolveStorage(storage, walletClient, config) {
15
25
  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)}`);
26
+ if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
27
+ if ("signedUrl" in storage) return new SignedUrlBackend(storage.signedUrl.workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway);
28
+ throw new Error(`Invalid storage config: must be { pinata: … } or { signedUrl: … }, got ${JSON.stringify(storage)}`);
18
29
  }
19
30
  var Fangorn = class Fangorn {
20
31
  ctx;
21
32
  _engine = null;
22
- _metagraph = null;
33
+ _metagraph = new MetagraphRegistry();
23
34
  constructor(ctx) {
24
35
  this.ctx = ctx;
25
36
  }
26
37
  get engine() {
27
38
  if (!this.ctx.metadataStorage) throw new Error("fangorn.engine requires storage configurations. Pass { pinata: { ... } } to Fangorn.create()");
28
- if (!this._engine) {
29
- this._metagraph = new MetagraphRegistry();
30
- this._engine = new FangornEngine(this.ctx.metadataStorage, this._metagraph, this.ctx.dataRegistry);
31
- }
39
+ this._engine ??= new FangornEngine(this.ctx.metadataStorage, this._metagraph, this.ctx.dataRegistry);
32
40
  return this._engine;
33
41
  }
34
42
  get metagraph() {
35
- if (!this._metagraph) throw new Error("MetagraphRegistry has not been initialized. Ensure the client is connected.");
36
43
  return this._metagraph;
37
44
  }
38
45
  static create(options) {
@@ -43,7 +50,7 @@ var Fangorn = class Fangorn {
43
50
  chain: resolvedConfig.chain,
44
51
  transport: http(resolvedConfig.rpcUrl)
45
52
  });
46
- const metadataStorage = resolveStorage(options.storage);
53
+ const metadataStorage = resolveStorage(options.storage, walletClient, resolvedConfig);
47
54
  const domain = options.domain ?? new URL(resolvedConfig.rpcUrl).hostname;
48
55
  const publicClient = createPublicClient({ transport: http(resolvedConfig.rpcUrl) });
49
56
  return new Fangorn({
@@ -329,9 +336,18 @@ var Fangorn = class Fangorn {
329
336
  return this.ctx.dataRegistry;
330
337
  }
331
338
  getStorage() {
332
- if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } to Fangorn.create()");
339
+ if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
333
340
  return this.ctx.metadataStorage;
334
341
  }
342
+ /**
343
+ * Swap the storage backend at runtime — e.g. move from access-worker signed
344
+ * URLs to your own Pinata JWT (or back). Rebuilds the engine on next use so it
345
+ * picks up the new backend.
346
+ */
347
+ setStorage(storage) {
348
+ this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config);
349
+ this._engine = null;
350
+ }
335
351
  getWalletClient() {
336
352
  return this.ctx.walletClient;
337
353
  }
package/lib/index.d.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
2
+ import { AccessRequest, AccessSigner, DecryptHandleParams, EncryptAndUploadParams, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
3
+ import { FangornContext, FangornCreateOptions, StorageConfig } from "./types/index.js";
2
4
  import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
3
5
  import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
4
6
  import { PinataBackend } from "./providers/storage/pinata.js";
5
- import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.js";
6
- export { AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, Fangorn, FangornConfig, FileFacade, NamespaceChange, PinataBackend, ProcessorResult, SubscribeOptions, SupportedNetworks, Vertex, buildAssetGraph, buildMarkdownGraph, deserialize, extractMarkdownLinks, retrieveByCid, serialize };
7
+ import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
8
+ import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
9
+ export { AccessRequest, AccessSigner, AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, DEFAULT_SIGNED_URL_WORKER, DecryptHandleParams, Edge, EncryptAndUploadParams, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, MAX_UPLOAD_ATTEMPTS, NamespaceChange, PinataBackend, ProcessorResult, SignedUrlBackend, SignedUrlSigner, StorageConfig, SubscribeOptions, SupportedNetworks, Vertex, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf, withUploadRetry };
package/lib/index.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import { FangornConfig, SupportedNetworks } from "./config.js";
2
- import { deserialize, retrieveByCid, serialize } from "./providers/storage/utils.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";
4
5
  import { Fangorn } from "./fangorn.js";
5
6
  import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
7
+ 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";
6
8
 
7
- export { Fangorn, FangornConfig, PinataBackend, SupportedNetworks, buildAssetGraph, buildMarkdownGraph, deserialize, extractMarkdownLinks, retrieveByCid, serialize };
9
+ export { DEFAULT_SIGNED_URL_WORKER, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf, withUploadRetry };
@@ -1,6 +1,6 @@
1
1
  import { serialize } from "./utils.js";
2
- import * as UnixFS from "@ipld/unixfs";
3
2
  import { CarWriter } from "@ipld/car";
3
+ import * as UnixFS from "@ipld/unixfs";
4
4
 
5
5
  //#region src/providers/storage/car.ts
6
6
  const enc = new TextEncoder();
@@ -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,30 +1,14 @@
1
- import { retrieveByCid, serialize } from "./utils.js";
2
- import { packCar } from "./car.js";
1
+ import { retrieveByCid, serialize, withUploadRetry } from "./utils.js";
2
+ import { packCar } from "../../engine/car.js";
3
3
  import { keccak256, stringToBytes } from "viem";
4
4
  import { CID } from "multiformats/cid";
5
+ import { encode } from "multiformats/block";
5
6
  import { PinataSDK } from "pinata";
6
7
  import * as dagCbor from "@ipld/dag-cbor";
8
+ import { sha256 } from "multiformats/hashes/sha2";
7
9
 
8
10
  //#region src/providers/storage/pinata.ts
9
11
  const RAW_CODE = 85;
10
- const MAX_UPLOAD_ATTEMPTS = Math.max(1, Number(process.env.PINATA_UPLOAD_RETRIES ?? 6));
11
- function isTransientUpload(err) {
12
- const e = err;
13
- const s = typeof e.statusCode === "number" ? e.statusCode : 0;
14
- if (s === 408 || s === 425 || s === 429 || s >= 500) return true;
15
- const m = `${e.code ?? ""} ${e.message ?? ""}`;
16
- 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);
17
- }
18
- async function withUploadRetry(label, fn) {
19
- for (let attempt = 1;; attempt++) try {
20
- return await fn();
21
- } catch (err) {
22
- if (attempt >= MAX_UPLOAD_ATTEMPTS || !isTransientUpload(err)) throw err;
23
- const delay = Math.min(3e4, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500);
24
- console.warn(` [pinata] upload "${label}" failed (attempt ${attempt.toString()}/${MAX_UPLOAD_ATTEMPTS.toString()}), retrying in ${(delay / 1e3).toFixed(1)}s: ${err.message}`);
25
- await new Promise((r) => setTimeout(r, delay));
26
- }
27
- }
28
12
  var PinataBackend = class {
29
13
  pinata;
30
14
  gateway;
@@ -66,9 +50,26 @@ var PinataBackend = class {
66
50
  */
67
51
  async putMany(items) {
68
52
  if (items.length === 0) return {};
69
- const { bytes, uriByName } = await packCar(items);
53
+ const blocks = [];
54
+ const uriByName = {};
55
+ for (const item of items) {
56
+ const block = await encode({
57
+ value: item.data,
58
+ codec: dagCbor,
59
+ hasher: sha256
60
+ });
61
+ blocks.push(block);
62
+ uriByName[item.name] = `ipfs://${block.cid.toString()}`;
63
+ }
64
+ const rootBlock = await encode({
65
+ value: uriByName,
66
+ codec: dagCbor,
67
+ hasher: sha256
68
+ });
69
+ blocks.push(rootBlock);
70
+ const bytes = await packCar(rootBlock.cid, blocks);
70
71
  await withUploadRetry(`car[${items.length.toString()}f/${(bytes.length / 1e6).toFixed(1)}MB]`, async () => {
71
- const file = new File([bytes], "data.car", { type: "application/vnd.ipld.car" });
72
+ const file = new File([bytes.buffer], "data.car", { type: "application/vnd.ipld.car" });
72
73
  await this.pinata.upload.public.file(file).car();
73
74
  });
74
75
  return uriByName;
@@ -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 };
@@ -1,6 +1,9 @@
1
+ import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./signed-url.js";
1
2
  import { PinataBackend } from "./pinata.js";
3
+ import { CID } from "multiformats/cid";
2
4
 
3
5
  //#region src/providers/storage/utils.ts
6
+ const RAW_CODE = 85;
4
7
  const REVIVERS = [(_key, value) => {
5
8
  if (value !== null && typeof value === "object" && "__type" in value && "data" in value && value.__type === "Uint8Array") return new Uint8Array(Buffer.from(value.data, "base64"));
6
9
  return value;
@@ -24,6 +27,57 @@ function deserialize(text) {
24
27
  return value;
25
28
  });
26
29
  }
30
+ const MAX_UPLOAD_ATTEMPTS = Math.max(1, Number(process.env.PINATA_UPLOAD_RETRIES ?? 6));
31
+ function isTransientUpload(err) {
32
+ const e = err;
33
+ const s = typeof e.statusCode === "number" ? e.statusCode : 0;
34
+ if (s === 408 || s === 425 || s === 429 || s >= 500) return true;
35
+ const m = `${e.code ?? ""} ${e.message ?? ""}`;
36
+ 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);
37
+ }
38
+ async function withUploadRetry(label, fn) {
39
+ for (let attempt = 1;; attempt++) try {
40
+ return await fn();
41
+ } catch (err) {
42
+ if (attempt >= MAX_UPLOAD_ATTEMPTS || !isTransientUpload(err)) throw err;
43
+ const delay = Math.min(3e4, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500);
44
+ console.warn(` [upload] "${label}" failed (attempt ${attempt.toString()}/${MAX_UPLOAD_ATTEMPTS.toString()}), retrying in ${(delay / 1e3).toFixed(1)}s: ${err.message}`);
45
+ await new Promise((r) => setTimeout(r, delay));
46
+ }
47
+ }
48
+ /**
49
+ * Fetch the exact raw bytes for a CID from a public IPFS gateway (no decoding),
50
+ * retrying to ride out gateway replication lag right after an upload. Blocks
51
+ * written via putBlock() are addressed by their raw-codec (0x55) sibling, so a
52
+ * dag-cbor ("bafyrei…") CID is translated before fetching — the same handling
53
+ * PinataBackend.fetchRaw does, but over a public gateway with no JWT.
54
+ */
55
+ async function fetchRawByCid(cid, gateway = "https://ipfs.io", { retries = 5, timeoutMs = 16e3 } = {}) {
56
+ let fetchCid = cid.replace(/^ipfs:\/\//, "");
57
+ if (fetchCid.startsWith("bafyrei")) try {
58
+ fetchCid = CID.createV1(RAW_CODE, CID.parse(fetchCid).multihash).toString();
59
+ } catch {}
60
+ const base = (gateway || "https://ipfs.io").replace(/\/$/, "");
61
+ const url = `${/^https?:\/\//.test(base) ? base : `https://${base}`}/ipfs/${fetchCid}`;
62
+ let lastError;
63
+ for (let attempt = 0; attempt < retries; attempt++) {
64
+ const controller = new AbortController();
65
+ const timeout = setTimeout(() => {
66
+ controller.abort();
67
+ }, timeoutMs);
68
+ try {
69
+ const res = await fetch(url, { signal: controller.signal });
70
+ if (!res.ok) throw new Error(`HTTP ${res.status.toString()} ${res.statusText}`);
71
+ return new Uint8Array(await res.arrayBuffer());
72
+ } catch (err) {
73
+ lastError = err;
74
+ if (attempt < retries - 1) await new Promise((r) => setTimeout(r, 1e3));
75
+ } finally {
76
+ clearTimeout(timeout);
77
+ }
78
+ }
79
+ throw new Error(`Failed to retrieve ${cid} from ${url} after ${retries.toString()} attempts: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
80
+ }
27
81
  /**
28
82
  * Fetch any content by CID from a public IPFS gateway.
29
83
  * No auth required — all Fangorn content is public; privacy is cryptographic.
@@ -48,4 +102,4 @@ async function retrieveByCid(cid, gateway = "https://ipfs.io", timeoutSecond = 1
48
102
  }
49
103
 
50
104
  //#endregion
51
- export { PinataBackend, deserialize, retrieveByCid, serialize };
105
+ export { DEFAULT_SIGNED_URL_WORKER, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry };
@@ -16,6 +16,11 @@ type StorageConfig = {
16
16
  jwt: string;
17
17
  gateway: string;
18
18
  };
19
+ } | {
20
+ signedUrl: {
21
+ workerUrl?: string;
22
+ gateway?: string;
23
+ };
19
24
  };
20
25
  interface FangornCreateOptions {
21
26
  storage?: StorageConfig;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fangorn-network/sdk",
3
- "version": "2026.07.14",
3
+ "version": "2026.07.27",
4
4
  "description": "Git for knowledge graphs",
5
5
  "repository": {
6
6
  "type": "git",
@@ -61,6 +61,8 @@
61
61
  "@ipld/car": "^5.4.6",
62
62
  "@ipld/dag-cbor": "^10.0.1",
63
63
  "@ipld/unixfs": "^3.0.0",
64
+ "@noble/ciphers": "^1.3.0",
65
+ "@noble/curves": "^1.9.7",
64
66
  "@noble/hashes": "^2.2.0",
65
67
  "@noir-lang/noir_js": "1.0.0-beta.22",
66
68
  "@semaphore-protocol/group": "^4.14.2",