@opendatalabs/vana-sdk 3.16.0 → 3.18.0
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 +107 -0
- package/dist/direct/personal-server-read.cjs +20 -1
- package/dist/direct/personal-server-read.cjs.map +1 -1
- package/dist/direct/personal-server-read.js +23 -1
- package/dist/direct/personal-server-read.js.map +1 -1
- package/dist/errors.cjs +121 -2
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +190 -0
- package/dist/errors.js +106 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.browser.d.ts +5 -1
- package/dist/index.browser.js +1449 -58
- package/dist/index.browser.js.map +4 -4
- package/dist/index.node.cjs +1501 -59
- package/dist/index.node.cjs.map +4 -4
- package/dist/index.node.d.ts +5 -1
- package/dist/index.node.js +1449 -58
- package/dist/index.node.js.map +4 -4
- package/dist/protocol/data-point-deletion.cjs +220 -0
- package/dist/protocol/data-point-deletion.cjs.map +1 -0
- package/dist/protocol/data-point-deletion.d.ts +180 -0
- package/dist/protocol/data-point-deletion.js +193 -0
- package/dist/protocol/data-point-deletion.js.map +1 -0
- package/dist/protocol/data-point-deletion.test.d.ts +1 -0
- package/dist/protocol/gateway.cjs +145 -32
- package/dist/protocol/gateway.cjs.map +1 -1
- package/dist/protocol/gateway.d.ts +42 -3
- package/dist/protocol/gateway.js +156 -32
- package/dist/protocol/gateway.js.map +1 -1
- package/dist/protocol/lineage.cjs +287 -0
- package/dist/protocol/lineage.cjs.map +1 -0
- package/dist/protocol/lineage.d.ts +228 -0
- package/dist/protocol/lineage.js +258 -0
- package/dist/protocol/lineage.js.map +1 -0
- package/dist/protocol/lineage.test.d.ts +1 -0
- package/dist/protocol/personal-server-data.cjs +20 -1
- package/dist/protocol/personal-server-data.cjs.map +1 -1
- package/dist/protocol/personal-server-data.js +23 -1
- package/dist/protocol/personal-server-data.js.map +1 -1
- package/dist/protocol/personal-server-error-body.cjs +57 -0
- package/dist/protocol/personal-server-error-body.cjs.map +1 -0
- package/dist/protocol/personal-server-error-body.d.ts +18 -0
- package/dist/protocol/personal-server-error-body.js +32 -0
- package/dist/protocol/personal-server-error-body.js.map +1 -0
- package/dist/protocol/personal-server-write.cjs +623 -0
- package/dist/protocol/personal-server-write.cjs.map +1 -0
- package/dist/protocol/personal-server-write.d.ts +284 -0
- package/dist/protocol/personal-server-write.js +601 -0
- package/dist/protocol/personal-server-write.js.map +1 -0
- package/dist/protocol/personal-server-write.test.d.ts +1 -0
- package/dist/protocol/write-signer.cjs +67 -0
- package/dist/protocol/write-signer.cjs.map +1 -0
- package/dist/protocol/write-signer.d.ts +59 -0
- package/dist/protocol/write-signer.js +43 -0
- package/dist/protocol/write-signer.js.map +1 -0
- package/dist/protocol/write-signer.test.d.ts +1 -0
- package/dist/storage/index.cjs.map +1 -1
- package/dist/storage/index.d.ts +1 -1
- package/dist/storage/index.js.map +1 -1
- package/dist/storage/providers/vana-storage.cjs +66 -0
- package/dist/storage/providers/vana-storage.cjs.map +1 -1
- package/dist/storage/providers/vana-storage.d.ts +26 -0
- package/dist/storage/providers/vana-storage.js +66 -0
- package/dist/storage/providers/vana-storage.js.map +1 -1
- package/dist/tests/mock-personal-server.d.ts +127 -0
- package/dist/utils/response-body.cjs +46 -0
- package/dist/utils/response-body.cjs.map +1 -0
- package/dist/utils/response-body.d.ts +26 -0
- package/dist/utils/response-body.js +20 -0
- package/dist/utils/response-body.js.map +1 -0
- package/dist/utils/response-body.test.d.ts +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/protocol/personal-server-write.ts"],"sourcesContent":["/**\n * Builder-side client for the Personal Server Write API.\n *\n * @remarks\n * A builder holding a write-grant (a grant whose scope entries carry the\n * `write:` prefix, see {@link formatScopeEntry}) writes into a user's Personal\n * Server in two steps:\n *\n * 1. {@link openWriteSession}: `POST /v1/write/session` with a Web3Signed\n * handshake that carries the grant id as a signed claim. The Personal\n * Server verifies the builder key against the grant and mints a\n * short-lived bearer token bound to `{ builder, grantId }`.\n * 2. {@link writeData}: `POST /v1/data/:scope` with that bearer plus an\n * `X-Vana-Write-Signature` proof, a second Web3Signed signature over the\n * representation the Personal Server will store, again carrying the grant\n * id as a signed claim. The Personal Server stores the proof with the\n * record under the reserved `$writtenBy` key so anyone holding the record\n * can verify who wrote it.\n *\n * What the proof covers: a JSON write signs the request body, which must be\n * the compact `JSON.stringify` form (the server rejects anything else with\n * `WRITE_BODY_NOT_CANONICAL`); a binary write signs the `$binary` record the\n * server stores for the bytes and their representation headers\n * ({@link binaryWriteSignedBytes}), not the raw bytes. Every proof is\n * single-use: a retry after a lost response signs a fresh proof.\n *\n * Derivatives name their sources through `lineage` (see\n * {@link deriveDataPointId}): for a JSON write the ids are the top-level\n * `lineage` field of the body (inside the signed bytes); for a binary write\n * they are the `lineage` field of the `X-Vana-Metadata` JSON (inside the\n * signed `$binary` record). The server validates them and mirrors them under\n * the reserved `$lineage` key. Callers never send `$writtenBy` or `$lineage`.\n *\n * @category Protocol\n */\n\nimport { sha256 } from \"@noble/hashes/sha2\";\nimport { bytesToHex, isAddress, type Address, type Hex } from \"viem\";\nimport { z } from \"zod\";\nimport { buildWeb3SignedHeader } from \"../auth/web3-signed-builder\";\nimport {\n type PersonalServerWriteError,\n WriteConflictError,\n WriteForbiddenError,\n WriteLineageError,\n WriteRejectedError,\n WriteRequestError,\n WriteSessionError,\n WriteSessionExpiredError,\n WriteTransportError,\n WriteUnauthorizedError,\n} from \"../errors\";\nimport { toBase64 } from \"../utils/encoding\";\nimport { IngestResponseSchema, type IngestResponse } from \"./data-file\";\nimport {\n assertDerivedScopeNaming,\n deriveDataPointId,\n isDataPointId,\n} from \"./lineage\";\nimport {\n isRecord,\n readPersonalServerErrorBody,\n} from \"./personal-server-error-body\";\nimport { scopeMatchesPattern } from \"./scopes\";\nimport {\n resolveWriteSigner,\n type ResolveWriteSignerOptions,\n type WriteSigner,\n type WriteSignerSource,\n} from \"./write-signer\";\n\n/** Path of the write-session handshake. */\nexport const WRITE_SESSION_PATH = \"/v1/write/session\";\n/** Header carrying the builder's per-write payload proof. */\nexport const WRITE_SIGNATURE_HEADER = \"X-Vana-Write-Signature\";\n/** Header carrying caller metadata (and `lineage`) for a binary write. */\nexport const WRITE_METADATA_HEADER = \"X-Vana-Metadata\";\n/** Field the lineage source ids travel in (body for JSON, metadata for binary). */\nexport const LINEAGE_FIELD = \"lineage\";\n/** The most sources one record may cite. */\nexport const MAX_LINEAGE_SOURCES = 256;\n/** Header carrying the filename of a binary write (printable ASCII names). */\nexport const WRITE_FILENAME_HEADER = \"X-Filename\";\n/**\n * Header carrying a filename the `X-Filename` header cannot: the Personal\n * Server percent-decodes `filename*=UTF-8''...` (RFC 5987).\n */\nexport const WRITE_CONTENT_DISPOSITION_HEADER = \"Content-Disposition\";\n/** Reserved record key the Personal Server stamps builder attribution into. */\nexport const WRITER_ATTRIBUTION_KEY = \"$writtenBy\";\n/** Reserved record key the Personal Server stamps lineage sources into. */\nexport const LINEAGE_KEY = \"$lineage\";\n/** Record keys a builder must never send. */\nexport const RESERVED_WRITE_KEYS: readonly string[] = [\n WRITER_ATTRIBUTION_KEY,\n LINEAGE_KEY,\n];\n\n/**\n * Transport-level retry knobs shared by {@link openWriteSession} and\n * {@link writeData}.\n *\n * @remarks\n * Applies only when `fetch` **throws** (connection reset, DNS, a relay drop).\n * Every attempt signs a fresh proof, because the Personal Server consumes a\n * proof the moment it accepts it. A received HTTP response is never retried:\n * a 4xx/5xx is surfaced as a typed error.\n */\nexport interface WriteTransportRetryOptions {\n /** Total attempts including the first (default 3). `1` disables retries. */\n attempts?: number;\n /** Delay before the first retry (ms); doubles per retry (default 1_000). */\n initialDelayMs?: number;\n}\n\n/** An open write session: the bearer token plus what it was minted for. */\nexport interface WriteSession {\n /** Personal Server origin, without a trailing slash. */\n personalServerUrl: string;\n /** Web3Signed audience every proof under this session is addressed to. */\n audience: string;\n /** The write-grant the session is bound to. */\n grantId: string;\n /** The bearer token (`vana_write_...`). */\n accessToken: string;\n /** Unix milliseconds after which the token is no longer accepted. */\n expiresAt: number;\n /** Write patterns (prefix stripped) the session may write into. */\n writeScopes: readonly string[];\n /** The builder key the session was opened with; signs every write proof. */\n signer: WriteSigner;\n}\n\nexport interface OpenWriteSessionParams extends ResolveWriteSignerOptions {\n /** Personal Server origin, e.g. `https://ps.example.com`. */\n personalServerUrl: string;\n /** Builder key: a viem `LocalAccount`, `WalletClient`, or `{ signMessage }`. */\n signer: WriteSignerSource;\n /** The write-grant issued to the builder. */\n grantId: string;\n /** Web3Signed audience; defaults to `personalServerUrl`. */\n audience?: string;\n /** `fetch` to use; defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Extra request headers. */\n headers?: HeadersInit;\n retry?: WriteTransportRetryOptions;\n}\n\n/** A lineage source: a data point id, or the pair it is derived from. */\nexport type LineageSource = Hex | { ownerAddress: Address; scope: string };\n\n/** Bytes to store as an unstructured (binary) record. */\nexport interface WriteBinaryPayload {\n bytes: Uint8Array;\n /** Media type, e.g. `application/pdf`. Parameters are dropped when stored. */\n contentType: string;\n /**\n * Stored with the record. Sent as `X-Filename` when it is printable ASCII,\n * otherwise as `Content-Disposition: attachment; filename*=UTF-8''...`,\n * which the Personal Server decodes back to the same string. Must not have\n * leading or trailing whitespace (HTTP would strip it and the signed\n * representation would no longer match).\n */\n filename?: string;\n}\n\ninterface WriteDataBaseParams {\n session: WriteSession;\n /**\n * The scope to write into; must match one of the session's write patterns.\n * A derived scope must not share its first dot-segment with any source's\n * scope (the server rejects it with `LINEAGE_SCOPE_UNDER_SOURCE_PREFIX`):\n * put derivatives in the app's own namespace.\n */\n scope: string;\n /**\n * The data points this record was derived from: ids\n * ({@link deriveDataPointId}) or `{ ownerAddress, scope }` pairs the SDK\n * derives the id from. Distinct, at most {@link MAX_LINEAGE_SOURCES}, all\n * belonging to the same owner as the target scope, never the record's own\n * id. Sent lowercased as the record's `lineage` field, inside the signed\n * bytes. `[]` is an explicit root statement and is sent; absent or `null`\n * makes no statement. Pairs also let the SDK apply the naming rule\n * ({@link assertDerivedScopeNaming}) before anything is signed.\n */\n lineage?: readonly LineageSource[] | null;\n /** `fetch` to use; defaults to `globalThis.fetch`. */\n fetch?: typeof fetch;\n /** Extra request headers. */\n headers?: HeadersInit;\n retry?: WriteTransportRetryOptions;\n}\n\n/**\n * A JSON write: `data` is stored as the record (plus `lineage` when given).\n * Anything else to store goes inside `data`; `lineage` and reserved keys are\n * not accepted in it.\n */\nexport interface WriteJsonDataParams extends WriteDataBaseParams {\n data: Record<string, unknown>;\n binary?: never;\n metadata?: never;\n}\n\n/** A binary write: the bytes are stored as a `$binary` record. */\nexport interface WriteBinaryDataParams extends WriteDataBaseParams {\n binary: WriteBinaryPayload;\n data?: never;\n /**\n * Caller metadata stored with the record (`X-Vana-Metadata`, part of the\n * signed `$binary` record). Must not contain `lineage` (use the option) or\n * a reserved key.\n */\n metadata?: Record<string, unknown>;\n}\n\nexport type WriteDataParams = WriteJsonDataParams | WriteBinaryDataParams;\n\nconst WriteDataResultSchema = IngestResponseSchema.extend({\n // Present when the write carried lineage: the validated, lowercased ids.\n lineage: z.object({ sources: z.array(z.string()) }).optional(),\n});\n\n/** The Personal Server's ingest answer, plus the accepted lineage if any. */\nexport type WriteDataResult = IngestResponse & {\n lineage?: { sources: Hex[] };\n};\n\nconst WriteSessionResponseSchema = z.object({\n access_token: z.string().min(1),\n token_type: z.string(),\n expires_in: z.number().nonnegative(),\n scope: z.string(),\n});\n\nfunction normalizeBaseUrl(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\nfunction resolveFetch(fetchFn: typeof fetch | undefined): typeof fetch {\n const resolved = fetchFn ?? globalThis.fetch;\n if (resolved === undefined) {\n throw new WriteRequestError(\"No fetch implementation available\");\n }\n return resolved;\n}\n\nfunction dataPath(scope: string): string {\n return `/v1/data/${encodeURIComponent(scope)}`;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\nfunction finiteOr(value: number | undefined, fallback: number): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * The Personal Server consumes every proof it accepts, and a Web3Signed\n * payload is fully determined by `{ aud, method, uri, bodyHash, grantId, iat,\n * exp }`, so two proofs for the same request signed within one second would\n * be byte-identical and the second rejected as a replay. Remember the\n * highest `iat` issued per request identity in this process and bump past\n * it when a second proof for the same identity falls inside the same second.\n *\n * A mark is kept for as long as the server can still remember the proof it\n * guards (its lifetime plus the verifier's clock skew), so a proof is never\n * re-issued while it could still be rejected as a replay: not by a burst,\n * and not by a wall clock stepping backwards (an identical request after a\n * step back waits for the clock instead of reusing the mark). Marks are\n * bucketed by their `iat` second, so pruning (once per second) only touches\n * the buckets that fell out of the retention window: the work per proof is\n * amortised constant and the map is bounded by the distinct requests signed\n * in the window.\n */\nconst issuedProofIats = new Map<string, number>();\n/** `iat` second -> identities whose current mark is that second. */\nconst issuedProofBuckets = new Map<number, Set<string>>();\nlet issuedProofIatsPrunedAtSec = 0;\n/** `buildWeb3SignedHeader`'s default `exp - iat`. */\nconst WEB3_SIGNED_PROOF_LIFETIME_SECONDS = 300;\n/** The verifier's tolerated clock skew (`verifyWeb3Signed`). */\nconst WEB3_SIGNED_CLOCK_SKEW_SECONDS = 60;\nconst PROOF_IAT_RETENTION_SECONDS =\n WEB3_SIGNED_PROOF_LIFETIME_SECONDS + WEB3_SIGNED_CLOCK_SKEW_SECONDS;\n/**\n * How far ahead of the clock a bumped `iat` may run when the proof is sent.\n * The verifier tolerates 60 s of skew. A burst of identical requests that\n * would need to run further ahead waits for the clock instead, so a proof is\n * never repeated; sustained identical requests are throttled to one per\n * second after a burst of this many.\n */\nconst PROOF_IAT_MAX_AHEAD_SECONDS = 30;\n\nfunction pruneIssuedProofIats(nowSec: number): void {\n if (issuedProofIatsPrunedAtSec === nowSec) return;\n issuedProofIatsPrunedAtSec = nowSec;\n const cutoff = nowSec - PROOF_IAT_RETENTION_SECONDS;\n // There is at most one bucket per second in the window, so this walk is\n // bounded by the window length, not by the number of marks.\n for (const [sec, keys] of issuedProofBuckets) {\n if (sec >= cutoff) continue;\n for (const key of keys) issuedProofIats.delete(key);\n issuedProofBuckets.delete(sec);\n }\n}\n\nfunction setIssuedProofIat(key: string, iat: number, previous?: number): void {\n if (previous !== undefined) {\n const bucket = issuedProofBuckets.get(previous);\n bucket?.delete(key);\n if (bucket?.size === 0) issuedProofBuckets.delete(previous);\n }\n issuedProofIats.set(key, iat);\n let bucket = issuedProofBuckets.get(iat);\n if (bucket === undefined) {\n bucket = new Set();\n issuedProofBuckets.set(iat, bucket);\n }\n bucket.add(key);\n}\n\n/**\n * Reserve the next `iat` for a request identity. The reservation is made\n * synchronously so concurrent callers never share a value; the returned\n * promise only waits when the reserved `iat` is further ahead of the clock\n * than {@link PROOF_IAT_MAX_AHEAD_SECONDS}.\n */\nfunction nextProofIat(proofKey: string): Promise<number> {\n const nowSec = Math.floor(Date.now() / 1000);\n pruneIssuedProofIats(nowSec);\n const last = issuedProofIats.get(proofKey);\n const iat = last === undefined ? nowSec : Math.max(nowSec, last + 1);\n setIssuedProofIat(proofKey, iat, last);\n const waitSec = iat - nowSec - PROOF_IAT_MAX_AHEAD_SECONDS;\n if (waitSec <= 0) return Promise.resolve(iat);\n return sleep(waitSec * 1000).then(() => iat);\n}\n\nfunction proofKeyFor(parts: {\n aud: string;\n method: string;\n uri: string;\n grantId: string;\n signedBytes?: Uint8Array;\n}): string {\n // A digest, so a retained mark costs a fixed amount of memory whatever the\n // request looked like.\n return bytesToHex(\n sha256(\n new TextEncoder().encode(\n JSON.stringify([\n parts.aud,\n parts.method,\n parts.uri,\n parts.grantId,\n parts.signedBytes ? bytesToHex(sha256(parts.signedBytes)) : \"\",\n ]),\n ),\n ),\n );\n}\n\n/**\n * Send a request, re-signing it on every attempt. Only a thrown `fetch` is\n * retried; the proof builder and any received response are never retried.\n */\nasync function sendWithFreshProof(\n label: string,\n fetchFn: typeof fetch,\n options: WriteTransportRetryOptions | undefined,\n proofKey: string,\n build: (iat: number) => Promise<{ url: string; init: RequestInit }>,\n): Promise<Response> {\n const attempts = Math.max(1, Math.floor(finiteOr(options?.attempts, 3)));\n let delayMs = Math.max(0, finiteOr(options?.initialDelayMs, 1_000));\n let lastError: unknown;\n for (let attempt = 0; attempt < attempts; attempt++) {\n const { url, init } = await build(await nextProofIat(proofKey));\n try {\n return await fetchFn(url, init);\n } catch (err) {\n lastError = err;\n }\n if (attempt < attempts - 1) {\n await sleep(delayMs);\n delayMs *= 2;\n }\n }\n throw new WriteTransportError(\n `${label} failed after ${attempts} attempt(s): ${errorMessage(lastError)}`,\n attempts,\n lastError,\n );\n}\n\n/**\n * Open a write session against a Personal Server.\n *\n * @remarks\n * Sends `POST /v1/write/session` with a Web3Signed `Authorization` header\n * whose signed claims carry `grantId`. The handshake proof is single-use on\n * the server; a transport retry signs a new one.\n *\n * @returns The session to pass to {@link writeData}.\n * @throws {WriteSessionError} When the Personal Server refuses the handshake\n * (`errorCode` names why: `UNREGISTERED_BUILDER`, `GRANT_REQUIRED`,\n * `GRANT_REVOKED`, `SCOPE_MISMATCH` for a grant without write entries,\n * `INVALID_SIGNATURE` when the key is not the grantee,\n * `GRANT_OWNER_MISMATCH`, ...).\n * @throws {WriteTransportError} When `fetch` threw on every attempt.\n * @throws {WriteRequestError} When the signer is unusable.\n */\nexport async function openWriteSession(\n params: OpenWriteSessionParams,\n): Promise<WriteSession> {\n const fetchFn = resolveFetch(params.fetch);\n const personalServerUrl = normalizeBaseUrl(params.personalServerUrl);\n const audience = params.audience ?? personalServerUrl;\n const signer = resolveWriteSigner(params.signer, { account: params.account });\n\n const response = await sendWithFreshProof(\n \"Write session handshake\",\n fetchFn,\n params.retry,\n proofKeyFor({\n aud: audience,\n method: \"POST\",\n uri: WRITE_SESSION_PATH,\n grantId: params.grantId,\n }),\n async (iat) => {\n const headers = new Headers(params.headers);\n headers.set(\n \"Authorization\",\n await buildWeb3SignedHeader({\n signMessage: signer.signMessage,\n aud: audience,\n method: \"POST\",\n uri: WRITE_SESSION_PATH,\n grantId: params.grantId,\n iat,\n }),\n );\n return {\n url: `${personalServerUrl}${WRITE_SESSION_PATH}`,\n init: { method: \"POST\", headers },\n };\n },\n );\n // Read the clock before parsing so `expiresAt` never overstates the\n // remaining lifetime.\n const mintedAt = Date.now();\n\n if (!response.ok) {\n const { errorCode, message, details } =\n await readPersonalServerErrorBody(response);\n throw new WriteSessionError(\n message ??\n `Write session handshake failed: ${response.status} ${response.statusText}`,\n response.status,\n errorCode,\n details,\n );\n }\n\n let body: unknown;\n try {\n body = await response.json();\n } catch (err) {\n throw new WriteSessionError(\n \"Write session response is not JSON\",\n response.status,\n null,\n { cause: errorMessage(err) },\n );\n }\n const parsed = WriteSessionResponseSchema.safeParse(body);\n if (!parsed.success) {\n throw new WriteSessionError(\n \"Write session response is not a session\",\n response.status,\n null,\n { issues: parsed.error.issues },\n );\n }\n if (parsed.data.token_type.toLowerCase() !== \"bearer\") {\n throw new WriteSessionError(\n `Write session token type is not Bearer: ${parsed.data.token_type}`,\n response.status,\n );\n }\n\n return {\n personalServerUrl,\n audience,\n grantId: params.grantId,\n accessToken: parsed.data.access_token,\n expiresAt: mintedAt + parsed.data.expires_in * 1000,\n writeScopes: parsed.data.scope.split(\" \").filter((s) => s.length > 0),\n signer,\n };\n}\n\n/** Every field {@link writeData} relies on, checked before any is used. */\nfunction isWriteSession(value: unknown): value is WriteSession {\n if (!isRecord(value)) return false;\n const signer: unknown = value.signer;\n return (\n typeof value.personalServerUrl === \"string\" &&\n typeof value.audience === \"string\" &&\n typeof value.grantId === \"string\" &&\n typeof value.accessToken === \"string\" &&\n value.accessToken.length > 0 &&\n typeof value.expiresAt === \"number\" &&\n Number.isFinite(value.expiresAt) &&\n Array.isArray(value.writeScopes) &&\n value.writeScopes.every((scope) => typeof scope === \"string\") &&\n isRecord(signer) &&\n typeof signer.signMessage === \"function\"\n );\n}\n\n/** `true` when one of the session's write patterns covers `scope`. */\nexport function sessionCoversScope(\n session: Pick<WriteSession, \"writeScopes\">,\n scope: string,\n): boolean {\n if (\n !isRecord(session) ||\n !Array.isArray(session.writeScopes) ||\n !session.writeScopes.every((pattern) => typeof pattern === \"string\")\n ) {\n throw new WriteRequestError(\"session must come from openWriteSession\");\n }\n return session.writeScopes.some((pattern) =>\n scopeMatchesPattern(scope, pattern),\n );\n}\n\n/**\n * The media type the Personal Server stores for a binary write: the\n * `Content-Type` minus its parameters, `application/octet-stream` when blank.\n */\nexport function normalizeBinaryMimeType(contentType: string | null): string {\n if (!contentType) return \"application/octet-stream\";\n return contentType.split(\";\")[0].trim() || \"application/octet-stream\";\n}\n\n/**\n * How the Personal Server reads an `X-Vana-Metadata` header: JSON when it\n * parses, the raw string otherwise, `undefined` when absent or blank.\n */\nexport function parseWriteMetadataHeader(value: string | null): unknown {\n if (value === null) return undefined;\n const trimmed = value.trim();\n if (trimmed === \"\") return undefined;\n try {\n return JSON.parse(trimmed);\n } catch {\n return value;\n }\n}\n\n/**\n * Encode a metadata object for the `X-Vana-Metadata` header. Non-ASCII\n * characters are `\\uXXXX`-escaped so the value is header-safe everywhere;\n * it parses back to the same object.\n */\nexport function encodeWriteMetadataHeader(\n metadata: Record<string, unknown>,\n): string {\n let json: string;\n try {\n json = JSON.stringify(metadata);\n } catch (err) {\n throw new WriteRequestError(\n `metadata is not JSON-serialisable: ${errorMessage(err)}`,\n );\n }\n if (typeof json !== \"string\") {\n throw new WriteRequestError(\"metadata must serialise to JSON\");\n }\n return json.replace(\n /[\\u007f-\\uffff]/g,\n (c) => `\\\\u${c.charCodeAt(0).toString(16).padStart(4, \"0\")}`,\n );\n}\n\nexport interface BinaryWriteSignedBytesInput {\n /** The raw body bytes the write sends. */\n bytes: Uint8Array;\n /** The `Content-Type` header the write sends (parameters are ignored). */\n contentType: string;\n /** The `X-Filename` header value the write sends, if any. */\n filename?: string;\n /** The exact `X-Vana-Metadata` header value the write sends, if any. */\n metadataHeader?: string;\n}\n\n/**\n * The bytes a builder signs for a binary write: the compact JSON of the\n * `$binary` record the Personal Server stores for these headers and bytes\n * (`personal-server-ts` `binaryWriteSignedBytes`, mirrored field for field).\n *\n * @returns UTF-8 bytes of the stored record's compact JSON.\n */\nexport function binaryWriteSignedBytes(\n input: BinaryWriteSignedBytesInput,\n): Uint8Array {\n const metadata = parseWriteMetadataHeader(input.metadataHeader ?? null);\n const record: Record<string, unknown> = {\n $binary: true,\n mimeType: normalizeBinaryMimeType(input.contentType),\n ...(input.filename ? { filename: input.filename } : {}),\n sizeBytes: input.bytes.length,\n contentHash: bytesToHex(sha256(input.bytes)),\n encoding: \"base64\",\n content: toBase64(input.bytes),\n ...(metadata !== undefined ? { metadata } : {}),\n };\n return new TextEncoder().encode(JSON.stringify(record));\n}\n\nconst PRINTABLE_ASCII = /^[\\x20-\\x7e]*$/;\n\n/**\n * Carry a filename the way the Personal Server reads it back verbatim:\n * `X-Filename` for printable ASCII, RFC 5987 `filename*` otherwise (a raw\n * non-ASCII header value is rejected by `fetch` or mangled in transit).\n */\nfunction setFilenameHeader(headers: Headers, filename: string): void {\n if (PRINTABLE_ASCII.test(filename)) {\n headers.set(WRITE_FILENAME_HEADER, filename);\n return;\n }\n headers.set(\n WRITE_CONTENT_DISPOSITION_HEADER,\n `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,\n );\n}\n\nfunction assertNoReservedKeys(\n value: Record<string, unknown>,\n where: string,\n): void {\n for (const key of RESERVED_WRITE_KEYS) {\n if (Object.prototype.hasOwnProperty.call(value, key)) {\n throw new WriteRequestError(\n `${where} must not contain the reserved ${key} key; the Personal Server stamps it`,\n { key },\n );\n }\n }\n}\n\nfunction isLineagePair(\n value: unknown,\n): value is { ownerAddress: Address; scope: string } {\n return (\n isRecord(value) &&\n typeof value.ownerAddress === \"string\" &&\n typeof value.scope === \"string\"\n );\n}\n\n/**\n * Validate and lowercase the sources the way the Personal Server will\n * (distinct, at most {@link MAX_LINEAGE_SOURCES}, never the record's own id)\n * and apply the naming rule to every source given as a pair. `[]` is kept:\n * it is an explicit root statement.\n */\nfunction normalizeLineage(lineage: unknown, derivedScope: string): Hex[] {\n if (!Array.isArray(lineage)) {\n throw new WriteRequestError(\"lineage must be an array of data point ids\");\n }\n if (lineage.length > MAX_LINEAGE_SOURCES) {\n throw new WriteRequestError(\n `lineage lists ${lineage.length} sources; the maximum is ${MAX_LINEAGE_SOURCES}`,\n { max: MAX_LINEAGE_SOURCES, count: lineage.length },\n );\n }\n const seen = new Set<string>();\n const sources: Hex[] = [];\n const sourceScopes: string[] = [];\n const ownIds = new Set<string>();\n for (const entry of lineage as unknown[]) {\n let id: Hex;\n if (isLineagePair(entry)) {\n if (!isAddress(entry.ownerAddress, { strict: false })) {\n throw new WriteRequestError(\n \"lineage source ownerAddress must be an EVM address\",\n { ownerAddress: entry.ownerAddress },\n );\n }\n if (entry.scope.length === 0) {\n throw new WriteRequestError(\"lineage source scope is required\");\n }\n id = deriveDataPointId(entry.ownerAddress, entry.scope);\n sourceScopes.push(entry.scope);\n ownIds.add(deriveDataPointId(entry.ownerAddress, derivedScope));\n } else if (isDataPointId(entry)) {\n id = entry;\n } else {\n throw new WriteRequestError(\n \"lineage entries must be 32-byte hex data point ids or { ownerAddress, scope } pairs\",\n { entry },\n );\n }\n const normalized = id.toLowerCase() as Hex;\n if (seen.has(normalized)) {\n throw new WriteRequestError(\"lineage must not repeat a data point id\", {\n dataPointId: normalized,\n });\n }\n seen.add(normalized);\n sources.push(normalized);\n }\n for (const own of ownIds) {\n if (seen.has(own)) {\n throw new WriteRequestError(\n \"lineage must not cite the record's own data point\",\n { dataPointId: own, scope: derivedScope },\n );\n }\n }\n assertDerivedScopeNaming(derivedScope, sourceScopes);\n return sources;\n}\n\nfunction assertNoLineageField(\n value: Record<string, unknown>,\n where: string,\n): void {\n if (Object.prototype.hasOwnProperty.call(value, LINEAGE_FIELD)) {\n throw new WriteRequestError(\n `${where}.${LINEAGE_FIELD} is reserved; pass sources through the lineage option`,\n );\n }\n}\n\n/** The `X-Vana-Metadata` header for a binary write, or `undefined`. */\nfunction buildMetadataHeader(\n metadata: Record<string, unknown> | undefined,\n sources: Hex[] | undefined,\n): string | undefined {\n if (metadata !== undefined) {\n if (!isRecord(metadata)) {\n throw new WriteRequestError(\"metadata must be a plain object\");\n }\n assertNoReservedKeys(metadata, \"metadata\");\n assertNoLineageField(metadata, \"metadata\");\n }\n if (metadata === undefined && sources === undefined) return undefined;\n return encodeWriteMetadataHeader({\n ...(metadata ?? {}),\n ...(sources !== undefined ? { [LINEAGE_FIELD]: sources } : {}),\n });\n}\n\ninterface PreparedWrite {\n body: Uint8Array;\n /** What the proof's `bodyHash` commits to. */\n signedBytes: Uint8Array;\n contentType: string;\n filename?: string;\n metadataHeader?: string;\n}\n\nfunction prepareWrite(params: WriteDataParams): PreparedWrite {\n if (params.binary !== undefined && params.data !== undefined) {\n throw new WriteRequestError(\"Pass either data or binary, not both\");\n }\n // Absent or null lineage makes no statement: send nothing. Anything else\n // (`[]` included: an explicit root) is validated before it is touched,\n // since callers may be untyped.\n const rawLineage: unknown = params.lineage;\n const sources =\n rawLineage === undefined || rawLineage === null\n ? undefined\n : normalizeLineage(rawLineage, params.scope);\n\n if (params.binary !== undefined) {\n const { bytes, contentType, filename } = params.binary;\n if (!(bytes instanceof Uint8Array)) {\n throw new WriteRequestError(\"binary.bytes must be a Uint8Array\");\n }\n if (typeof contentType !== \"string\" || contentType.trim() === \"\") {\n throw new WriteRequestError(\"binary.contentType is required\");\n }\n if (filename !== undefined) {\n if (typeof filename !== \"string\") {\n throw new WriteRequestError(\"binary.filename must be a string\");\n }\n if (filename !== filename.trim()) {\n throw new WriteRequestError(\n \"binary.filename must not have leading or trailing whitespace\",\n );\n }\n }\n const metadataHeader = buildMetadataHeader(params.metadata, sources);\n return {\n body: bytes,\n signedBytes: binaryWriteSignedBytes({\n bytes,\n contentType,\n filename,\n metadataHeader,\n }),\n contentType,\n filename,\n metadataHeader,\n };\n }\n\n if (params.data === undefined) {\n throw new WriteRequestError(\"Pass data (a JSON object) or binary\");\n }\n if (!isRecord(params.data)) {\n throw new WriteRequestError(\"data must be a plain JSON object\");\n }\n if (params.metadata !== undefined) {\n throw new WriteRequestError(\n \"metadata applies to binary writes; put fields to store inside data\",\n );\n }\n assertNoReservedKeys(params.data, \"data\");\n assertNoLineageField(params.data, \"data\");\n const record =\n sources === undefined\n ? params.data\n : { ...params.data, [LINEAGE_FIELD]: sources };\n let text: string;\n try {\n // Compact JSON is the contract: the server re-serialises the parsed\n // record and requires it to match the signed bytes.\n text = JSON.stringify(record);\n } catch (err) {\n throw new WriteRequestError(\n `data is not JSON-serialisable: ${errorMessage(err)}`,\n );\n }\n if (typeof text !== \"string\" || !text.startsWith(\"{\")) {\n throw new WriteRequestError(\"data must serialise to a JSON object\");\n }\n const body = new TextEncoder().encode(text);\n return {\n body,\n signedBytes: body,\n contentType: \"application/json\",\n };\n}\n\nasync function writeErrorFromResponse(\n response: Response,\n): Promise<PersonalServerWriteError> {\n const { errorCode, message, details } =\n await readPersonalServerErrorBody(response);\n const text =\n message ??\n `Personal Server write failed: ${response.status} ${response.statusText}`;\n // Lineage rejections span 400 / 422 / 502; the code is the discriminator.\n if (response.status === 422 || errorCode?.startsWith(\"LINEAGE_\")) {\n return new WriteLineageError(text, response.status, errorCode, details);\n }\n switch (response.status) {\n case 401:\n return new WriteUnauthorizedError(text, errorCode, details);\n case 403:\n return new WriteForbiddenError(text, errorCode, details);\n case 409:\n return new WriteConflictError(text, errorCode, details);\n default:\n return new WriteRejectedError(text, response.status, errorCode, details);\n }\n}\n\n/**\n * Write one record into a scope under an open write session.\n *\n * @remarks\n * Sends `POST /v1/data/:scope` with `Authorization: Bearer <session token>`\n * and `X-Vana-Write-Signature`, a Web3Signed proof over the stored\n * representation carrying the session's `grantId` as a signed claim. JSON\n * writes send `data` as compact JSON with `Content-Type: application/json`;\n * binary writes send the bytes with their `Content-Type`, `X-Filename`, and\n * sign {@link binaryWriteSignedBytes}. `lineage` is the record's top-level\n * `lineage` field for JSON and the `lineage` field of `X-Vana-Metadata` for\n * binary, so the proof covers it either way.\n *\n * @returns The ingest answer (`scope`, `collectedAt`, `status`, and\n * `lineage.sources` when the write carried lineage).\n * @throws {WriteRequestError} Before sending: no payload, a reserved key, a\n * malformed lineage id, or non-object data.\n * @throws {WriteSessionExpiredError} Before sending: the session token has\n * passed its lifetime.\n * @throws {WriteUnauthorizedError} 401 (proof or session rejected).\n * @throws {WriteForbiddenError} 403 (grant no longer authorises the write).\n * @throws {WriteConflictError} 409.\n * @throws {WriteLineageError} Any `LINEAGE_*` rejection: 422\n * `LINEAGE_SOURCE_UNKNOWN` (`details.unknown`), 400 `LINEAGE_INVALID` /\n * `LINEAGE_SCOPE_UNDER_SOURCE_PREFIX`, 502 `LINEAGE_SOURCE_LOOKUP_FAILED`.\n * @throws {WriteRejectedError} Any other non-2xx.\n * @throws {WriteTransportError} `fetch` threw on every attempt.\n */\nexport async function writeData(\n params: WriteDataParams,\n): Promise<WriteDataResult> {\n const { session } = params;\n if (!isWriteSession(session)) {\n throw new WriteRequestError(\"session must come from openWriteSession\");\n }\n const fetchFn = resolveFetch(params.fetch);\n if (typeof params.scope !== \"string\" || params.scope.length === 0) {\n throw new WriteRequestError(\"scope is required\");\n }\n const prepared = prepareWrite(params);\n if (Date.now() >= session.expiresAt) {\n throw new WriteSessionExpiredError(\n \"Write session has expired; open a new session\",\n { grantId: session.grantId, expiresAt: session.expiresAt },\n );\n }\n\n const path = dataPath(params.scope);\n const response = await sendWithFreshProof(\n `Write to ${params.scope}`,\n fetchFn,\n params.retry,\n proofKeyFor({\n aud: session.audience,\n method: \"POST\",\n uri: path,\n grantId: session.grantId,\n signedBytes: prepared.signedBytes,\n }),\n async (iat) => {\n const headers = new Headers(params.headers);\n headers.set(\"Content-Type\", prepared.contentType);\n headers.set(\"Authorization\", `Bearer ${session.accessToken}`);\n if (prepared.filename) {\n setFilenameHeader(headers, prepared.filename);\n }\n if (prepared.metadataHeader !== undefined) {\n headers.set(WRITE_METADATA_HEADER, prepared.metadataHeader);\n }\n headers.set(\n WRITE_SIGNATURE_HEADER,\n await buildWeb3SignedHeader({\n signMessage: session.signer.signMessage,\n aud: session.audience,\n method: \"POST\",\n uri: path,\n body: prepared.signedBytes,\n grantId: session.grantId,\n iat,\n }),\n );\n return {\n url: `${session.personalServerUrl}${path}`,\n init: {\n method: \"POST\",\n headers,\n body: prepared.body as unknown as BodyInit,\n },\n };\n },\n );\n\n if (!response.ok) {\n throw await writeErrorFromResponse(response);\n }\n let body: unknown;\n try {\n body = await response.json();\n } catch (err) {\n throw new WriteRejectedError(\n \"Personal Server write response is not JSON\",\n response.status,\n null,\n { cause: errorMessage(err) },\n );\n }\n const parsed = WriteDataResultSchema.safeParse(body);\n if (!parsed.success) {\n throw new WriteRejectedError(\n \"Personal Server write response is not an ingest result\",\n response.status,\n null,\n { issues: parsed.error.issues },\n );\n }\n return parsed.data as WriteDataResult;\n}\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\nexport type WritePersonalServerDataParams = Omit<\n OpenWriteSessionParams,\n \"fetch\" | \"headers\" | \"retry\"\n> &\n DistributiveOmit<WriteDataParams, \"session\">;\n\n/** {@link writePersonalServerData}'s answer: the ingest result plus the session it opened. */\nexport interface WritePersonalServerDataResult extends WriteDataResult {\n /** Reuse for further writes until `expiresAt`. */\n session: WriteSession;\n}\n\n/**\n * Open a write session and write one record in a single call.\n *\n * @remarks\n * Equivalent to {@link openWriteSession} followed by {@link writeData}. The\n * session is returned so further writes can reuse it; opening one per write\n * is correct but costs an extra signature and round-trip each time.\n *\n * @throws Everything {@link openWriteSession} and {@link writeData} throw.\n */\nexport async function writePersonalServerData(\n params: WritePersonalServerDataParams,\n): Promise<WritePersonalServerDataResult> {\n const session = await openWriteSession({\n personalServerUrl: params.personalServerUrl,\n signer: params.signer,\n grantId: params.grantId,\n account: params.account,\n audience: params.audience,\n fetch: params.fetch,\n headers: params.headers,\n retry: params.retry,\n });\n const writeParams = { ...params, session } as WriteDataParams;\n const result = await writeData(writeParams);\n return { ...result, session };\n}\n"],"mappings":"AAoCA,SAAS,cAAc;AACvB,SAAS,YAAY,iBAAyC;AAC9D,SAAS,SAAS;AAClB,SAAS,6BAA6B;AACtC;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB;AACzB,SAAS,4BAAiD;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,OAIK;AAGA,MAAM,qBAAqB;AAE3B,MAAM,yBAAyB;AAE/B,MAAM,wBAAwB;AAE9B,MAAM,gBAAgB;AAEtB,MAAM,sBAAsB;AAE5B,MAAM,wBAAwB;AAK9B,MAAM,mCAAmC;AAEzC,MAAM,yBAAyB;AAE/B,MAAM,cAAc;AAEpB,MAAM,sBAAyC;AAAA,EACpD;AAAA,EACA;AACF;AA2HA,MAAM,wBAAwB,qBAAqB,OAAO;AAAA;AAAA,EAExD,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,EAAE,SAAS;AAC/D,CAAC;AAOD,MAAM,6BAA6B,EAAE,OAAO;AAAA,EAC1C,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC9B,YAAY,EAAE,OAAO;AAAA,EACrB,YAAY,EAAE,OAAO,EAAE,YAAY;AAAA,EACnC,OAAO,EAAE,OAAO;AAClB,CAAC;AAED,SAAS,iBAAiB,KAAqB;AAC7C,SAAO,IAAI,QAAQ,QAAQ,EAAE;AAC/B;AAEA,SAAS,aAAa,SAAiD;AACrE,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+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var write_signer_exports = {};
|
|
20
|
+
__export(write_signer_exports, {
|
|
21
|
+
resolveWriteSigner: () => resolveWriteSigner
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(write_signer_exports);
|
|
24
|
+
var import_errors = require("../errors");
|
|
25
|
+
function isRecord(value) {
|
|
26
|
+
return value !== null && typeof value === "object";
|
|
27
|
+
}
|
|
28
|
+
function isViemWriteAccount(source) {
|
|
29
|
+
return isRecord(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
|
|
30
|
+
}
|
|
31
|
+
function isViemWriteWalletClient(source) {
|
|
32
|
+
return isRecord(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
|
|
33
|
+
}
|
|
34
|
+
function accountAddress(account) {
|
|
35
|
+
return typeof account === "string" ? account : account.address;
|
|
36
|
+
}
|
|
37
|
+
function resolveWriteSigner(source, options = {}) {
|
|
38
|
+
if (isViemWriteWalletClient(source)) {
|
|
39
|
+
const account = options.account ?? source.account;
|
|
40
|
+
if (account === void 0) {
|
|
41
|
+
throw new import_errors.WriteRequestError(
|
|
42
|
+
"Viem wallet client requires an account option or account property"
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
return {
|
|
46
|
+
address: accountAddress(account),
|
|
47
|
+
signMessage: (message) => source.signMessage({ account, message })
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
if (isViemWriteAccount(source)) {
|
|
51
|
+
return {
|
|
52
|
+
address: source.address,
|
|
53
|
+
signMessage: (message) => source.signMessage({ message })
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (!isRecord(source) || typeof source.signMessage !== "function") {
|
|
57
|
+
throw new import_errors.WriteRequestError(
|
|
58
|
+
"signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
return source;
|
|
62
|
+
}
|
|
63
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
64
|
+
0 && (module.exports = {
|
|
65
|
+
resolveWriteSigner
|
|
66
|
+
});
|
|
67
|
+
//# sourceMappingURL=write-signer.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/protocol/write-signer.ts"],"sourcesContent":["/**\n * Builder key abstraction shared by the Write API and lineage reads.\n *\n * @remarks\n * Everything the Personal Server asks a builder to sign is an EIP-191\n * `personal_sign` over a Web3Signed payload, so one `signMessage` callback is\n * the whole contract. {@link resolveWriteSigner} accepts the shapes a builder\n * already has: a viem `LocalAccount` (backend, `privateKeyToAccount`), a viem\n * `WalletClient` (browser wallet), or a bare `{ signMessage }` object.\n *\n * @category Protocol\n */\n\nimport type { Account, Address, Hex } from \"viem\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\nimport { WriteRequestError } from \"../errors\";\n\n/** The signer the Write API drives: an EIP-191 signature over a string. */\nexport interface WriteSigner {\n /** The builder address, when known. Used for messages only. */\n address?: Address;\n /** EIP-191 (`personal_sign`) over the Web3Signed payload string. */\n signMessage: Web3SignedSignFn;\n}\n\n/** The subset of a viem `LocalAccount` the Write API uses. */\nexport interface ViemWriteAccount {\n address: Address;\n type: \"local\";\n signMessage(args: { message: string }): Promise<Hex>;\n}\n\n/** The subset of a viem `WalletClient` the Write API uses. */\nexport interface ViemWriteWalletClient {\n type?: string;\n transport?: unknown;\n account?: Account | undefined;\n signMessage(args: {\n account: Account | Address;\n message: string;\n }): Promise<Hex>;\n}\n\n/** Any signer {@link resolveWriteSigner} understands. */\nexport type WriteSignerSource =\n | WriteSigner\n | ViemWriteAccount\n | ViemWriteWalletClient;\n\nexport interface ResolveWriteSignerOptions {\n /**\n * Account to sign with when the viem wallet client has no hoisted account\n * (browser wallets). Ignored for other signer shapes.\n */\n account?: Account | Address;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\";\n}\n\nfunction isViemWriteAccount(source: unknown): source is ViemWriteAccount {\n return (\n isRecord(source) &&\n source.type === \"local\" &&\n typeof source.address === \"string\" &&\n typeof source.signMessage === \"function\"\n );\n}\n\n/**\n * A viem client: `createWalletClient` stamps `type: \"walletClient\"`, and every\n * viem client carries a `transport`. Either marker is enough; a bare\n * `{ signMessage }` signer has neither, and a local account has\n * `type: \"local\"`.\n */\nfunction isViemWriteWalletClient(\n source: unknown,\n): source is ViemWriteWalletClient {\n return (\n isRecord(source) &&\n typeof source.signMessage === \"function\" &&\n source.type !== \"local\" &&\n (source.type === \"walletClient\" || \"transport\" in source)\n );\n}\n\nfunction accountAddress(account: Account | Address): Address {\n return typeof account === \"string\" ? account : account.address;\n}\n\n/**\n * Normalise a builder key into a {@link WriteSigner}.\n *\n * @param source - A viem `LocalAccount`, a viem `WalletClient`, or a\n * `{ signMessage }` object (returned as-is).\n * @param options - `account` for a wallet client without a hoisted account.\n * @returns A signer whose `signMessage` produces EIP-191 signatures.\n * @throws {WriteRequestError} When a wallet client has no account to sign\n * with, or the source exposes no `signMessage` function.\n */\nexport function resolveWriteSigner(\n source: WriteSignerSource,\n options: ResolveWriteSignerOptions = {},\n): WriteSigner {\n if (isViemWriteWalletClient(source)) {\n const account = options.account ?? source.account;\n if (account === undefined) {\n throw new WriteRequestError(\n \"Viem wallet client requires an account option or account property\",\n );\n }\n return {\n address: accountAddress(account),\n signMessage: (message) => source.signMessage({ account, message }),\n };\n }\n if (isViemWriteAccount(source)) {\n return {\n address: source.address,\n signMessage: (message) => source.signMessage({ message }),\n };\n }\n if (!isRecord(source) || typeof source.signMessage !== \"function\") {\n throw new WriteRequestError(\n \"signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object\",\n );\n }\n return source as WriteSigner;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,oBAAkC;AA0ClC,SAAS,SAAS,OAAkD;AAClE,SAAO,UAAU,QAAQ,OAAO,UAAU;AAC5C;AAEA,SAAS,mBAAmB,QAA6C;AACvE,SACE,SAAS,MAAM,KACf,OAAO,SAAS,WAChB,OAAO,OAAO,YAAY,YAC1B,OAAO,OAAO,gBAAgB;AAElC;AAQA,SAAS,wBACP,QACiC;AACjC,SACE,SAAS,MAAM,KACf,OAAO,OAAO,gBAAgB,cAC9B,OAAO,SAAS,YACf,OAAO,SAAS,kBAAkB,eAAe;AAEtD;AAEA,SAAS,eAAe,SAAqC;AAC3D,SAAO,OAAO,YAAY,WAAW,UAAU,QAAQ;AACzD;AAYO,SAAS,mBACd,QACA,UAAqC,CAAC,GACzB;AACb,MAAI,wBAAwB,MAAM,GAAG;AACnC,UAAM,UAAU,QAAQ,WAAW,OAAO;AAC1C,QAAI,YAAY,QAAW;AACzB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,MACL,SAAS,eAAe,OAAO;AAAA,MAC/B,aAAa,CAAC,YAAY,OAAO,YAAY,EAAE,SAAS,QAAQ,CAAC;AAAA,IACnE;AAAA,EACF;AACA,MAAI,mBAAmB,MAAM,GAAG;AAC9B,WAAO;AAAA,MACL,SAAS,OAAO;AAAA,MAChB,aAAa,CAAC,YAAY,OAAO,YAAY,EAAE,QAAQ,CAAC;AAAA,IAC1D;AAAA,EACF;AACA,MAAI,CAAC,SAAS,MAAM,KAAK,OAAO,OAAO,gBAAgB,YAAY;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Builder key abstraction shared by the Write API and lineage reads.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Everything the Personal Server asks a builder to sign is an EIP-191
|
|
6
|
+
* `personal_sign` over a Web3Signed payload, so one `signMessage` callback is
|
|
7
|
+
* the whole contract. {@link resolveWriteSigner} accepts the shapes a builder
|
|
8
|
+
* already has: a viem `LocalAccount` (backend, `privateKeyToAccount`), a viem
|
|
9
|
+
* `WalletClient` (browser wallet), or a bare `{ signMessage }` object.
|
|
10
|
+
*
|
|
11
|
+
* @category Protocol
|
|
12
|
+
*/
|
|
13
|
+
import type { Account, Address, Hex } from "viem";
|
|
14
|
+
import type { Web3SignedSignFn } from "../auth/web3-signed-builder.js";
|
|
15
|
+
/** The signer the Write API drives: an EIP-191 signature over a string. */
|
|
16
|
+
export interface WriteSigner {
|
|
17
|
+
/** The builder address, when known. Used for messages only. */
|
|
18
|
+
address?: Address;
|
|
19
|
+
/** EIP-191 (`personal_sign`) over the Web3Signed payload string. */
|
|
20
|
+
signMessage: Web3SignedSignFn;
|
|
21
|
+
}
|
|
22
|
+
/** The subset of a viem `LocalAccount` the Write API uses. */
|
|
23
|
+
export interface ViemWriteAccount {
|
|
24
|
+
address: Address;
|
|
25
|
+
type: "local";
|
|
26
|
+
signMessage(args: {
|
|
27
|
+
message: string;
|
|
28
|
+
}): Promise<Hex>;
|
|
29
|
+
}
|
|
30
|
+
/** The subset of a viem `WalletClient` the Write API uses. */
|
|
31
|
+
export interface ViemWriteWalletClient {
|
|
32
|
+
type?: string;
|
|
33
|
+
transport?: unknown;
|
|
34
|
+
account?: Account | undefined;
|
|
35
|
+
signMessage(args: {
|
|
36
|
+
account: Account | Address;
|
|
37
|
+
message: string;
|
|
38
|
+
}): Promise<Hex>;
|
|
39
|
+
}
|
|
40
|
+
/** Any signer {@link resolveWriteSigner} understands. */
|
|
41
|
+
export type WriteSignerSource = WriteSigner | ViemWriteAccount | ViemWriteWalletClient;
|
|
42
|
+
export interface ResolveWriteSignerOptions {
|
|
43
|
+
/**
|
|
44
|
+
* Account to sign with when the viem wallet client has no hoisted account
|
|
45
|
+
* (browser wallets). Ignored for other signer shapes.
|
|
46
|
+
*/
|
|
47
|
+
account?: Account | Address;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Normalise a builder key into a {@link WriteSigner}.
|
|
51
|
+
*
|
|
52
|
+
* @param source - A viem `LocalAccount`, a viem `WalletClient`, or a
|
|
53
|
+
* `{ signMessage }` object (returned as-is).
|
|
54
|
+
* @param options - `account` for a wallet client without a hoisted account.
|
|
55
|
+
* @returns A signer whose `signMessage` produces EIP-191 signatures.
|
|
56
|
+
* @throws {WriteRequestError} When a wallet client has no account to sign
|
|
57
|
+
* with, or the source exposes no `signMessage` function.
|
|
58
|
+
*/
|
|
59
|
+
export declare function resolveWriteSigner(source: WriteSignerSource, options?: ResolveWriteSignerOptions): WriteSigner;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { WriteRequestError } from "../errors.js";
|
|
2
|
+
function isRecord(value) {
|
|
3
|
+
return value !== null && typeof value === "object";
|
|
4
|
+
}
|
|
5
|
+
function isViemWriteAccount(source) {
|
|
6
|
+
return isRecord(source) && source.type === "local" && typeof source.address === "string" && typeof source.signMessage === "function";
|
|
7
|
+
}
|
|
8
|
+
function isViemWriteWalletClient(source) {
|
|
9
|
+
return isRecord(source) && typeof source.signMessage === "function" && source.type !== "local" && (source.type === "walletClient" || "transport" in source);
|
|
10
|
+
}
|
|
11
|
+
function accountAddress(account) {
|
|
12
|
+
return typeof account === "string" ? account : account.address;
|
|
13
|
+
}
|
|
14
|
+
function resolveWriteSigner(source, options = {}) {
|
|
15
|
+
if (isViemWriteWalletClient(source)) {
|
|
16
|
+
const account = options.account ?? source.account;
|
|
17
|
+
if (account === void 0) {
|
|
18
|
+
throw new WriteRequestError(
|
|
19
|
+
"Viem wallet client requires an account option or account property"
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
address: accountAddress(account),
|
|
24
|
+
signMessage: (message) => source.signMessage({ account, message })
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
if (isViemWriteAccount(source)) {
|
|
28
|
+
return {
|
|
29
|
+
address: source.address,
|
|
30
|
+
signMessage: (message) => source.signMessage({ message })
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
if (!isRecord(source) || typeof source.signMessage !== "function") {
|
|
34
|
+
throw new WriteRequestError(
|
|
35
|
+
"signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object"
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
return source;
|
|
39
|
+
}
|
|
40
|
+
export {
|
|
41
|
+
resolveWriteSigner
|
|
42
|
+
};
|
|
43
|
+
//# sourceMappingURL=write-signer.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/protocol/write-signer.ts"],"sourcesContent":["/**\n * Builder key abstraction shared by the Write API and lineage reads.\n *\n * @remarks\n * Everything the Personal Server asks a builder to sign is an EIP-191\n * `personal_sign` over a Web3Signed payload, so one `signMessage` callback is\n * the whole contract. {@link resolveWriteSigner} accepts the shapes a builder\n * already has: a viem `LocalAccount` (backend, `privateKeyToAccount`), a viem\n * `WalletClient` (browser wallet), or a bare `{ signMessage }` object.\n *\n * @category Protocol\n */\n\nimport type { Account, Address, Hex } from \"viem\";\nimport type { Web3SignedSignFn } from \"../auth/web3-signed-builder\";\nimport { WriteRequestError } from \"../errors\";\n\n/** The signer the Write API drives: an EIP-191 signature over a string. */\nexport interface WriteSigner {\n /** The builder address, when known. Used for messages only. */\n address?: Address;\n /** EIP-191 (`personal_sign`) over the Web3Signed payload string. */\n signMessage: Web3SignedSignFn;\n}\n\n/** The subset of a viem `LocalAccount` the Write API uses. */\nexport interface ViemWriteAccount {\n address: Address;\n type: \"local\";\n signMessage(args: { message: string }): Promise<Hex>;\n}\n\n/** The subset of a viem `WalletClient` the Write API uses. */\nexport interface ViemWriteWalletClient {\n type?: string;\n transport?: unknown;\n account?: Account | undefined;\n signMessage(args: {\n account: Account | Address;\n message: string;\n }): Promise<Hex>;\n}\n\n/** Any signer {@link resolveWriteSigner} understands. */\nexport type WriteSignerSource =\n | WriteSigner\n | ViemWriteAccount\n | ViemWriteWalletClient;\n\nexport interface ResolveWriteSignerOptions {\n /**\n * Account to sign with when the viem wallet client has no hoisted account\n * (browser wallets). Ignored for other signer shapes.\n */\n account?: Account | Address;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\";\n}\n\nfunction isViemWriteAccount(source: unknown): source is ViemWriteAccount {\n return (\n isRecord(source) &&\n source.type === \"local\" &&\n typeof source.address === \"string\" &&\n typeof source.signMessage === \"function\"\n );\n}\n\n/**\n * A viem client: `createWalletClient` stamps `type: \"walletClient\"`, and every\n * viem client carries a `transport`. Either marker is enough; a bare\n * `{ signMessage }` signer has neither, and a local account has\n * `type: \"local\"`.\n */\nfunction isViemWriteWalletClient(\n source: unknown,\n): source is ViemWriteWalletClient {\n return (\n isRecord(source) &&\n typeof source.signMessage === \"function\" &&\n source.type !== \"local\" &&\n (source.type === \"walletClient\" || \"transport\" in source)\n );\n}\n\nfunction accountAddress(account: Account | Address): Address {\n return typeof account === \"string\" ? account : account.address;\n}\n\n/**\n * Normalise a builder key into a {@link WriteSigner}.\n *\n * @param source - A viem `LocalAccount`, a viem `WalletClient`, or a\n * `{ signMessage }` object (returned as-is).\n * @param options - `account` for a wallet client without a hoisted account.\n * @returns A signer whose `signMessage` produces EIP-191 signatures.\n * @throws {WriteRequestError} When a wallet client has no account to sign\n * with, or the source exposes no `signMessage` function.\n */\nexport function resolveWriteSigner(\n source: WriteSignerSource,\n options: ResolveWriteSignerOptions = {},\n): WriteSigner {\n if (isViemWriteWalletClient(source)) {\n const account = options.account ?? source.account;\n if (account === undefined) {\n throw new WriteRequestError(\n \"Viem wallet client requires an account option or account property\",\n );\n }\n return {\n address: accountAddress(account),\n signMessage: (message) => source.signMessage({ account, message }),\n };\n }\n if (isViemWriteAccount(source)) {\n return {\n address: source.address,\n signMessage: (message) => source.signMessage({ message }),\n };\n }\n if (!isRecord(source) || typeof source.signMessage !== \"function\") {\n throw new WriteRequestError(\n \"signer must be a viem LocalAccount, a viem WalletClient, or a { signMessage } object\",\n );\n }\n return source as WriteSigner;\n}\n"],"mappings":"AAeA,SAAS,yBAAyB;AA0ClC,SAAS,SAAS,OAAkD;AAClE,SAAO,UAAU,QAAQ,OAAO,UAAU;AAC5C;AAEA,SAAS,mBAAmB,QAA6C;AACvE,SACE,SAAS,MAAM,KACf,OAAO,SAAS,WAChB,OAAO,OAAO,YAAY,YAC1B,OAAO,OAAO,gBAAgB;AAElC;AAQA,SAAS,wBACP,QACiC;AACjC,SACE,SAAS,MAAM,KACf,OAAO,OAAO,gBAAgB,cAC9B,OAAO,SAAS,YACf,OAAO,SAAS,kBAAkB,eAAe;AAEtD;AAEA,SAAS,eAAe,SAAqC;AAC3D,SAAO,OAAO,YAAY,WAAW,UAAU,QAAQ;AACzD;AAYO,SAAS,mBACd,QACA,UAAqC,CAAC,GACzB;AACb,MAAI,wBAAwB,MAAM,GAAG;AACnC,UAAM,UAAU,QAAQ,WAAW,OAAO;AAC1C,QAAI,YAAY,QAAW;AACzB,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,MACL,SAAS,eAAe,OAAO;AAAA,MAC/B,aAAa,CAAC,YAAY,OAAO,YAAY,EAAE,SAAS,QAAQ,CAAC;AAAA,IACnE;AAAA,EACF;AACA,MAAI,mBAAmB,MAAM,GAAG;AAC9B,WAAO;AAAA,MACL,SAAS,OAAO;AAAA,MAChB,aAAa,CAAC,YAAY,OAAO,YAAY,EAAE,QAAQ,CAAC;AAAA,IAC1D;AAAA,EACF;AACA,MAAI,CAAC,SAAS,MAAM,KAAK,OAAO,OAAO,gBAAgB,YAAY;AACjE,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/storage/index.ts"],"sourcesContent":["/**\n * Storage API for Vana SDK\n *\n * Provides unified interface for different storage providers\n * to upload, download, and manage user data files.\n *\n * ## Storage Provider Decision Tree\n *\n * Choose your storage provider based on your needs:\n *\n * **Default backend hosted by ODL?**\n * - ✅ Use `VanaStorage` - storage.vana.org with Web3Signed auth.\n *\n * **Need full CRUD operations and metadata?**\n * - ✅ Use `PinataStorage` - Managed IPFS with listing, deletion, and rich metadata\n *\n * **Want to use your own IPFS infrastructure?**\n * - ✅ Use `IpfsStorage.forInfura()` - Connect to Infura IPFS service\n * - ✅ Use `IpfsStorage.forLocalNode()` - Connect to local IPFS node\n * - ✅ Use `new IpfsStorage()` - Connect to any IPFS-compatible service\n *\n * **Want flexible callback-based storage?**\n * - ✅ Use `CallbackStorage` - Implement storage via custom callbacks (HTTP, WebSocket, etc.)\n *\n * **Need Google Drive integration?**\n * - ✅ Use `GoogleDriveStorage` - Direct Google Drive API with folder management\n *\n * @example\n * ```typescript\n * // Managed IPFS with full features\n * const pinata = new PinataStorage({ jwt: \"your-jwt\" });\n *\n * // Standard IPFS with Infura\n * const ipfs = IpfsStorage.forInfura({ projectId: \"...\", projectSecret: \"...\" });\n *\n * // Callback-based storage (flexible)\n * const storage = new CallbackStorage({\n * async upload(blob, filename) {\n * // Your custom upload logic\n * const response = await fetch('/api/upload', { method: 'POST', body: blob });\n * const data = await response.json();\n * return { url: data.url, size: blob.size, contentType: blob.type };\n * },\n * async download(identifier) {\n * // Your custom download logic\n * const response = await fetch(`/api/download/${identifier}`);\n * return response.blob();\n * }\n * });\n * ```\n */\n\n// Re-export storage types from types module to avoid circular dependencies\nexport type {\n StorageProvider,\n StorageUploadResult,\n StorageFile,\n StorageListOptions,\n StorageProviderConfig,\n} from \"../types/storage\";\n\nexport { StorageError } from \"../types/storage\";\n\n// Export default Vana storage factory\nexport { createVanaStorageProvider } from \"./default\";\nexport type { VanaStorageProviderOptions } from \"./default\";\n\n// Export storage providers\nexport { R2Storage } from \"./providers/r2\";\nexport type { R2Config } from \"./providers/r2\";\nexport { VanaStorage } from \"./providers/vana-storage\";\nexport type {\n VanaStorageConfig,\n VanaStorageSigner,\n} from \"./providers/vana-storage\";\nexport type { ProtocolNetwork } from \"../protocol/networks\";\nexport { GoogleDriveStorage } from \"./providers/google-drive\";\nexport { DropboxStorage } from \"./providers/dropbox\";\nexport { IpfsStorage } from \"./providers/ipfs\";\nexport { PinataStorage } from \"./providers/pinata\";\nexport { CallbackStorage } from \"./providers/callback-storage\";\n\n// Export storage manager\nexport { StorageManager } from \"./manager\";\n\n// Export storage callback types\nexport type {\n StorageCallbacks,\n StorageDownloadOptions,\n StorageListResult,\n} from \"../types/config\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6DA,qBAA6B;AAG7B,qBAA0C;AAI1C,gBAA0B;AAE1B,0BAA4B;
|
|
1
|
+
{"version":3,"sources":["../../src/storage/index.ts"],"sourcesContent":["/**\n * Storage API for Vana SDK\n *\n * Provides unified interface for different storage providers\n * to upload, download, and manage user data files.\n *\n * ## Storage Provider Decision Tree\n *\n * Choose your storage provider based on your needs:\n *\n * **Default backend hosted by ODL?**\n * - ✅ Use `VanaStorage` - storage.vana.org with Web3Signed auth.\n *\n * **Need full CRUD operations and metadata?**\n * - ✅ Use `PinataStorage` - Managed IPFS with listing, deletion, and rich metadata\n *\n * **Want to use your own IPFS infrastructure?**\n * - ✅ Use `IpfsStorage.forInfura()` - Connect to Infura IPFS service\n * - ✅ Use `IpfsStorage.forLocalNode()` - Connect to local IPFS node\n * - ✅ Use `new IpfsStorage()` - Connect to any IPFS-compatible service\n *\n * **Want flexible callback-based storage?**\n * - ✅ Use `CallbackStorage` - Implement storage via custom callbacks (HTTP, WebSocket, etc.)\n *\n * **Need Google Drive integration?**\n * - ✅ Use `GoogleDriveStorage` - Direct Google Drive API with folder management\n *\n * @example\n * ```typescript\n * // Managed IPFS with full features\n * const pinata = new PinataStorage({ jwt: \"your-jwt\" });\n *\n * // Standard IPFS with Infura\n * const ipfs = IpfsStorage.forInfura({ projectId: \"...\", projectSecret: \"...\" });\n *\n * // Callback-based storage (flexible)\n * const storage = new CallbackStorage({\n * async upload(blob, filename) {\n * // Your custom upload logic\n * const response = await fetch('/api/upload', { method: 'POST', body: blob });\n * const data = await response.json();\n * return { url: data.url, size: blob.size, contentType: blob.type };\n * },\n * async download(identifier) {\n * // Your custom download logic\n * const response = await fetch(`/api/download/${identifier}`);\n * return response.blob();\n * }\n * });\n * ```\n */\n\n// Re-export storage types from types module to avoid circular dependencies\nexport type {\n StorageProvider,\n StorageUploadResult,\n StorageFile,\n StorageListOptions,\n StorageProviderConfig,\n} from \"../types/storage\";\n\nexport { StorageError } from \"../types/storage\";\n\n// Export default Vana storage factory\nexport { createVanaStorageProvider } from \"./default\";\nexport type { VanaStorageProviderOptions } from \"./default\";\n\n// Export storage providers\nexport { R2Storage } from \"./providers/r2\";\nexport type { R2Config } from \"./providers/r2\";\nexport { VanaStorage } from \"./providers/vana-storage\";\nexport type {\n VanaStorageConfig,\n VanaStorageSigner,\n VanaStorageScopeDeleteResult,\n} from \"./providers/vana-storage\";\nexport type { ProtocolNetwork } from \"../protocol/networks\";\nexport { GoogleDriveStorage } from \"./providers/google-drive\";\nexport { DropboxStorage } from \"./providers/dropbox\";\nexport { IpfsStorage } from \"./providers/ipfs\";\nexport { PinataStorage } from \"./providers/pinata\";\nexport { CallbackStorage } from \"./providers/callback-storage\";\n\n// Export storage manager\nexport { StorageManager } from \"./manager\";\n\n// Export storage callback types\nexport type {\n StorageCallbacks,\n StorageDownloadOptions,\n StorageListResult,\n} from \"../types/config\";\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6DA,qBAA6B;AAG7B,qBAA0C;AAI1C,gBAA0B;AAE1B,0BAA4B;AAO5B,0BAAmC;AACnC,qBAA+B;AAC/B,kBAA4B;AAC5B,oBAA8B;AAC9B,8BAAgC;AAGhC,qBAA+B;","names":[]}
|
package/dist/storage/index.d.ts
CHANGED
|
@@ -56,7 +56,7 @@ export type { VanaStorageProviderOptions } from "./default.js";
|
|
|
56
56
|
export { R2Storage } from "./providers/r2.js";
|
|
57
57
|
export type { R2Config } from "./providers/r2.js";
|
|
58
58
|
export { VanaStorage } from "./providers/vana-storage.js";
|
|
59
|
-
export type { VanaStorageConfig, VanaStorageSigner, } from "./providers/vana-storage.js";
|
|
59
|
+
export type { VanaStorageConfig, VanaStorageSigner, VanaStorageScopeDeleteResult, } from "./providers/vana-storage.js";
|
|
60
60
|
export type { ProtocolNetwork } from "../protocol/networks.js";
|
|
61
61
|
export { GoogleDriveStorage } from "./providers/google-drive.js";
|
|
62
62
|
export { DropboxStorage } from "./providers/dropbox.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/storage/index.ts"],"sourcesContent":["/**\n * Storage API for Vana SDK\n *\n * Provides unified interface for different storage providers\n * to upload, download, and manage user data files.\n *\n * ## Storage Provider Decision Tree\n *\n * Choose your storage provider based on your needs:\n *\n * **Default backend hosted by ODL?**\n * - ✅ Use `VanaStorage` - storage.vana.org with Web3Signed auth.\n *\n * **Need full CRUD operations and metadata?**\n * - ✅ Use `PinataStorage` - Managed IPFS with listing, deletion, and rich metadata\n *\n * **Want to use your own IPFS infrastructure?**\n * - ✅ Use `IpfsStorage.forInfura()` - Connect to Infura IPFS service\n * - ✅ Use `IpfsStorage.forLocalNode()` - Connect to local IPFS node\n * - ✅ Use `new IpfsStorage()` - Connect to any IPFS-compatible service\n *\n * **Want flexible callback-based storage?**\n * - ✅ Use `CallbackStorage` - Implement storage via custom callbacks (HTTP, WebSocket, etc.)\n *\n * **Need Google Drive integration?**\n * - ✅ Use `GoogleDriveStorage` - Direct Google Drive API with folder management\n *\n * @example\n * ```typescript\n * // Managed IPFS with full features\n * const pinata = new PinataStorage({ jwt: \"your-jwt\" });\n *\n * // Standard IPFS with Infura\n * const ipfs = IpfsStorage.forInfura({ projectId: \"...\", projectSecret: \"...\" });\n *\n * // Callback-based storage (flexible)\n * const storage = new CallbackStorage({\n * async upload(blob, filename) {\n * // Your custom upload logic\n * const response = await fetch('/api/upload', { method: 'POST', body: blob });\n * const data = await response.json();\n * return { url: data.url, size: blob.size, contentType: blob.type };\n * },\n * async download(identifier) {\n * // Your custom download logic\n * const response = await fetch(`/api/download/${identifier}`);\n * return response.blob();\n * }\n * });\n * ```\n */\n\n// Re-export storage types from types module to avoid circular dependencies\nexport type {\n StorageProvider,\n StorageUploadResult,\n StorageFile,\n StorageListOptions,\n StorageProviderConfig,\n} from \"../types/storage\";\n\nexport { StorageError } from \"../types/storage\";\n\n// Export default Vana storage factory\nexport { createVanaStorageProvider } from \"./default\";\nexport type { VanaStorageProviderOptions } from \"./default\";\n\n// Export storage providers\nexport { R2Storage } from \"./providers/r2\";\nexport type { R2Config } from \"./providers/r2\";\nexport { VanaStorage } from \"./providers/vana-storage\";\nexport type {\n VanaStorageConfig,\n VanaStorageSigner,\n} from \"./providers/vana-storage\";\nexport type { ProtocolNetwork } from \"../protocol/networks\";\nexport { GoogleDriveStorage } from \"./providers/google-drive\";\nexport { DropboxStorage } from \"./providers/dropbox\";\nexport { IpfsStorage } from \"./providers/ipfs\";\nexport { PinataStorage } from \"./providers/pinata\";\nexport { CallbackStorage } from \"./providers/callback-storage\";\n\n// Export storage manager\nexport { StorageManager } from \"./manager\";\n\n// Export storage callback types\nexport type {\n StorageCallbacks,\n StorageDownloadOptions,\n StorageListResult,\n} from \"../types/config\";\n"],"mappings":"AA6DA,SAAS,oBAAoB;AAG7B,SAAS,iCAAiC;AAI1C,SAAS,iBAAiB;AAE1B,SAAS,mBAAmB;
|
|
1
|
+
{"version":3,"sources":["../../src/storage/index.ts"],"sourcesContent":["/**\n * Storage API for Vana SDK\n *\n * Provides unified interface for different storage providers\n * to upload, download, and manage user data files.\n *\n * ## Storage Provider Decision Tree\n *\n * Choose your storage provider based on your needs:\n *\n * **Default backend hosted by ODL?**\n * - ✅ Use `VanaStorage` - storage.vana.org with Web3Signed auth.\n *\n * **Need full CRUD operations and metadata?**\n * - ✅ Use `PinataStorage` - Managed IPFS with listing, deletion, and rich metadata\n *\n * **Want to use your own IPFS infrastructure?**\n * - ✅ Use `IpfsStorage.forInfura()` - Connect to Infura IPFS service\n * - ✅ Use `IpfsStorage.forLocalNode()` - Connect to local IPFS node\n * - ✅ Use `new IpfsStorage()` - Connect to any IPFS-compatible service\n *\n * **Want flexible callback-based storage?**\n * - ✅ Use `CallbackStorage` - Implement storage via custom callbacks (HTTP, WebSocket, etc.)\n *\n * **Need Google Drive integration?**\n * - ✅ Use `GoogleDriveStorage` - Direct Google Drive API with folder management\n *\n * @example\n * ```typescript\n * // Managed IPFS with full features\n * const pinata = new PinataStorage({ jwt: \"your-jwt\" });\n *\n * // Standard IPFS with Infura\n * const ipfs = IpfsStorage.forInfura({ projectId: \"...\", projectSecret: \"...\" });\n *\n * // Callback-based storage (flexible)\n * const storage = new CallbackStorage({\n * async upload(blob, filename) {\n * // Your custom upload logic\n * const response = await fetch('/api/upload', { method: 'POST', body: blob });\n * const data = await response.json();\n * return { url: data.url, size: blob.size, contentType: blob.type };\n * },\n * async download(identifier) {\n * // Your custom download logic\n * const response = await fetch(`/api/download/${identifier}`);\n * return response.blob();\n * }\n * });\n * ```\n */\n\n// Re-export storage types from types module to avoid circular dependencies\nexport type {\n StorageProvider,\n StorageUploadResult,\n StorageFile,\n StorageListOptions,\n StorageProviderConfig,\n} from \"../types/storage\";\n\nexport { StorageError } from \"../types/storage\";\n\n// Export default Vana storage factory\nexport { createVanaStorageProvider } from \"./default\";\nexport type { VanaStorageProviderOptions } from \"./default\";\n\n// Export storage providers\nexport { R2Storage } from \"./providers/r2\";\nexport type { R2Config } from \"./providers/r2\";\nexport { VanaStorage } from \"./providers/vana-storage\";\nexport type {\n VanaStorageConfig,\n VanaStorageSigner,\n VanaStorageScopeDeleteResult,\n} from \"./providers/vana-storage\";\nexport type { ProtocolNetwork } from \"../protocol/networks\";\nexport { GoogleDriveStorage } from \"./providers/google-drive\";\nexport { DropboxStorage } from \"./providers/dropbox\";\nexport { IpfsStorage } from \"./providers/ipfs\";\nexport { PinataStorage } from \"./providers/pinata\";\nexport { CallbackStorage } from \"./providers/callback-storage\";\n\n// Export storage manager\nexport { StorageManager } from \"./manager\";\n\n// Export storage callback types\nexport type {\n StorageCallbacks,\n StorageDownloadOptions,\n StorageListResult,\n} from \"../types/config\";\n"],"mappings":"AA6DA,SAAS,oBAAoB;AAG7B,SAAS,iCAAiC;AAI1C,SAAS,iBAAiB;AAE1B,SAAS,mBAAmB;AAO5B,SAAS,0BAA0B;AACnC,SAAS,sBAAsB;AAC/B,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAGhC,SAAS,sBAAsB;","names":[]}
|
|
@@ -24,6 +24,7 @@ module.exports = __toCommonJS(vana_storage_exports);
|
|
|
24
24
|
var import__ = require("../index");
|
|
25
25
|
var import_web3_signed_builder = require("../../auth/web3-signed-builder");
|
|
26
26
|
var import_networks = require("../../protocol/networks");
|
|
27
|
+
var import_response_body = require("../../utils/response-body");
|
|
27
28
|
const DEFAULT_ENDPOINT = "https://storage.vana.org";
|
|
28
29
|
const LEGACY_BLOB_PATH_PREFIX = "/v1/blobs";
|
|
29
30
|
const DEFAULT_TOKEN_TTL_SECONDS = 300;
|
|
@@ -194,6 +195,65 @@ class VanaStorage {
|
|
|
194
195
|
}
|
|
195
196
|
return true;
|
|
196
197
|
}
|
|
198
|
+
/**
|
|
199
|
+
* Delete every version's blob under `(owner, scope)` --
|
|
200
|
+
* `DELETE {prefix}/{owner}/{scope}` on vana-storage, signed with the same
|
|
201
|
+
* Web3Signed header as uploads (aud = endpoint origin, empty bodyHash).
|
|
202
|
+
* The worker accepts the owner's own signature or a personal server the
|
|
203
|
+
* owner registered with the gateway.
|
|
204
|
+
*
|
|
205
|
+
* @param ownerAddress - Must equal the provider's configured owner; a
|
|
206
|
+
* mismatch throws before anything is signed so this wallet can never be
|
|
207
|
+
* induced to sign a delete for another namespace.
|
|
208
|
+
* @param scope - The scope segment, e.g. `"instagram.profile"`.
|
|
209
|
+
*/
|
|
210
|
+
async deleteScope(ownerAddress, scope) {
|
|
211
|
+
if (ownerAddress.toLowerCase() !== this.ownerAddress) {
|
|
212
|
+
throw new import__.StorageError(
|
|
213
|
+
`deleteScope owner '${ownerAddress}' does not match the configured owner '${this.ownerAddress}'`,
|
|
214
|
+
"INVALID_OWNER",
|
|
215
|
+
"vana-storage"
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
if (scope.length === 0 || scope.includes("/") || isTraversalSegment(scope)) {
|
|
219
|
+
throw new import__.StorageError(
|
|
220
|
+
`scope must be a single non-empty path segment, got '${scope}'`,
|
|
221
|
+
"INVALID_SCOPE",
|
|
222
|
+
"vana-storage"
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
const path = `${this.blobPathPrefix}/${this.ownerAddress}/${encodeURIComponent(scope)}`;
|
|
226
|
+
const header = await this.signRequest("DELETE", path);
|
|
227
|
+
let response;
|
|
228
|
+
try {
|
|
229
|
+
response = await this.fetchImpl(`${this.endpoint}${path}`, {
|
|
230
|
+
method: "DELETE",
|
|
231
|
+
headers: { authorization: header }
|
|
232
|
+
});
|
|
233
|
+
} catch (cause) {
|
|
234
|
+
throw new import__.StorageError(
|
|
235
|
+
`vana-storage scope delete network error: ${describe(cause)}`,
|
|
236
|
+
"DELETE_ERROR",
|
|
237
|
+
"vana-storage",
|
|
238
|
+
{ cause: cause instanceof Error ? cause : void 0 }
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
if (!response.ok) {
|
|
242
|
+
const responseText = await safeText(response);
|
|
243
|
+
throw new import__.StorageError(
|
|
244
|
+
`vana-storage scope delete failed: ${response.status} ${response.statusText} - ${responseText}`,
|
|
245
|
+
"DELETE_FAILED",
|
|
246
|
+
"vana-storage"
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
const body = await (0, import_response_body.readJsonObject)(response);
|
|
250
|
+
return {
|
|
251
|
+
deleted: typeof body["deleted"] === "boolean" ? body["deleted"] : true,
|
|
252
|
+
scope: typeof body["scope"] === "string" ? body["scope"] : scope,
|
|
253
|
+
count: nonNegativeInteger(body["count"]) ?? 0,
|
|
254
|
+
totalBytes: nonNegativeInteger(body["totalBytes"]) ?? 0
|
|
255
|
+
};
|
|
256
|
+
}
|
|
197
257
|
getConfig() {
|
|
198
258
|
return {
|
|
199
259
|
name: "vana-storage",
|
|
@@ -322,6 +382,12 @@ function encodeRelativePath(filename) {
|
|
|
322
382
|
}
|
|
323
383
|
return parts.map((p) => encodeURIComponent(p)).join("/");
|
|
324
384
|
}
|
|
385
|
+
function isTraversalSegment(segment) {
|
|
386
|
+
return segment === "." || segment === "..";
|
|
387
|
+
}
|
|
388
|
+
function nonNegativeInteger(value) {
|
|
389
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
|
|
390
|
+
}
|
|
325
391
|
function describe(value) {
|
|
326
392
|
if (value instanceof Error) return value.message;
|
|
327
393
|
return String(value);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/storage/providers/vana-storage.ts"],"sourcesContent":["import {\n StorageError,\n type StorageProvider,\n type StorageUploadResult,\n type StorageFile,\n type StorageListOptions,\n type StorageProviderConfig,\n} from \"../index\";\nimport {\n buildWeb3SignedHeader,\n type Web3SignedSignFn,\n} from \"../../auth/web3-signed-builder\";\nimport {\n getProtocolNetworkChainId,\n isProtocolNetwork,\n type ProtocolNetwork,\n} from \"../../protocol/networks\";\n\nconst DEFAULT_ENDPOINT = \"https://storage.vana.org\";\nconst LEGACY_BLOB_PATH_PREFIX = \"/v1/blobs\";\nconst DEFAULT_TOKEN_TTL_SECONDS = 300;\nconst MAX_UPLOAD_ATTEMPTS = 4;\nconst MAX_RATE_LIMIT_DELAY_MS = 30_000;\n\n/**\n * Wallet-style signer used by {@link VanaStorage} to authenticate every\n * request. For Personal Server flows this can be a registered server wallet\n * signing requests for the owner's storage namespace.\n *\n * @category Storage\n */\nexport interface VanaStorageSigner {\n /** EIP-191 address (`0x...`). */\n address: `0x${string}`;\n /** EIP-191 personal_sign callback (e.g. viem `account.signMessage`). */\n signMessage: Web3SignedSignFn;\n}\n\n/**\n * Configuration for {@link VanaStorage}.\n *\n * @category Storage\n */\nexport interface VanaStorageConfig {\n /**\n * Base URL of the vana-storage Worker. Defaults to `https://storage.vana.org`.\n *\n * This selects the storage endpoint and is independent of {@link network} /\n * {@link chainId}.\n */\n endpoint?: string;\n /**\n * Named Vana protocol network that scopes blob paths. Prefer this for known\n * Vana networks because it keeps callers on the SDK's typed network registry.\n *\n * When set, uploads use chain-scoped routes derived from the network's chain\n * ID (`/v1/chains/1480/...` for mainnet, `/v1/chains/14800/...` for Moksha).\n */\n network?: ProtocolNetwork;\n /**\n * Explicit numeric chain ID for custom or future networks not yet represented\n * by {@link ProtocolNetwork}.\n *\n * When set, uploads use chain-scoped routes\n * (`/v1/chains/{chainId}/blobs/...`) so data for different chains under the\n * same owner/scope/timestamp never collides. Reads and deletes must use the\n * same chain-scoped namespace; legacy blobs should be migrated or re-collected\n * rather than read through an ambiguous fallback. When omitted, the provider\n * preserves the legacy `/v1/blobs/...` routes and behavior.\n *\n * `chainId` and {@link network} are mutually consistent ways to select the\n * namespace. If both are provided, they must resolve to the same chain ID.\n * `endpoint` remains orthogonal: it picks the storage host, not the protocol\n * namespace.\n */\n chainId?: number;\n /**\n * Wallet signer used to authenticate writes and reads.\n */\n signer: VanaStorageSigner;\n /**\n * Owner namespace under which blobs are stored. Defaults to the signer address.\n */\n ownerAddress?: `0x${string}`;\n /**\n * Optional `fetch` implementation. Defaults to the global `fetch`.\n * Useful for tests and for environments that need a custom HTTP client.\n */\n fetchImpl?: typeof fetch;\n}\n\ninterface VanaStorageUploadResponse {\n key: string;\n url: string;\n etag: string;\n size: number;\n}\n\n/**\n * Storage provider that talks to the vana-storage Worker\n * (`https://storage.vana.org` by default). All requests are authenticated\n * with Web3Signed headers signed by the configured wallet.\n *\n * @remarks\n * Filenames passed to {@link VanaStorage.upload} must be of the form\n * `\"{scope}/{collectedAt}\"` (e.g. `\"instagram.profile/2026-05-08T20:00:00.000Z\"`).\n * The owner address is prepended automatically to produce the canonical\n * blob path `/v1/blobs/{owner}/{scope}/{collectedAt}`.\n *\n * When {@link VanaStorageConfig.network} or {@link VanaStorageConfig.chainId}\n * is set, paths are chain-scoped as\n * `/v1/chains/{chainId}/blobs/{owner}/{scope}/{collectedAt}` so different chains\n * never collide on the same host. The Web3Signed audience remains the endpoint\n * origin regardless of network.\n *\n * @category Storage\n *\n * @example\n * ```typescript\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import { VanaStorage } from \"@opendatalabs/vana-sdk/node\";\n *\n * const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);\n * const storage = new VanaStorage({\n * signer: {\n * address: account.address,\n * signMessage: (msg) => account.signMessage({ message: msg }),\n * },\n * });\n *\n * const result = await storage.upload(\n * new Blob([ciphertext]),\n * \"instagram.profile/2026-05-08T20:00:00.000Z\",\n * );\n * ```\n */\nexport class VanaStorage implements StorageProvider {\n private readonly endpoint: string;\n private readonly network?: ProtocolNetwork;\n private readonly chainId?: number;\n private readonly blobPathPrefix: string;\n private readonly signer: VanaStorageSigner;\n private readonly ownerAddress: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: VanaStorageConfig) {\n if (!config?.signer?.address || !config?.signer?.signMessage) {\n throw new StorageError(\n \"VanaStorage requires a signer with address and signMessage\",\n \"MISSING_SIGNER\",\n \"vana-storage\",\n );\n }\n this.endpoint = (config.endpoint ?? DEFAULT_ENDPOINT).replace(/\\/+$/, \"\");\n const resolved = resolveStorageNamespace(config);\n this.network = resolved.network;\n this.chainId = resolved.chainId;\n this.blobPathPrefix =\n this.chainId !== undefined\n ? `/v1/chains/${this.chainId}/blobs`\n : LEGACY_BLOB_PATH_PREFIX;\n this.signer = config.signer;\n this.ownerAddress = (\n config.ownerAddress ?? config.signer.address\n ).toLowerCase();\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);\n }\n\n /**\n * Upload an encrypted blob to vana-storage.\n *\n * @param file - The blob to upload.\n * @param filename - Required relative key in the form `\"{scope}/{collectedAt}\"`.\n * The owner address is prepended automatically.\n */\n async upload(file: Blob, filename?: string): Promise<StorageUploadResult> {\n if (!filename) {\n throw new StorageError(\n \"VanaStorage.upload requires a filename of the form '{scope}/{collectedAt}'\",\n \"MISSING_FILENAME\",\n \"vana-storage\",\n );\n }\n\n const subpath = encodeRelativePath(filename);\n const path = `${this.blobPathPrefix}/${this.ownerAddress}/${subpath}`;\n const body = new Uint8Array(await file.arrayBuffer());\n const contentType =\n file.type !== \"\" ? file.type : \"application/octet-stream\";\n\n const header = await this.signRequest(\"PUT\", path, body);\n\n let response: Response | null = null;\n let responseText = \"\";\n for (let attempt = 1; attempt <= MAX_UPLOAD_ATTEMPTS; attempt++) {\n try {\n response = await this.fetchImpl(`${this.endpoint}${path}`, {\n method: \"PUT\",\n headers: {\n authorization: header,\n \"content-type\": contentType,\n },\n body,\n });\n } catch (cause) {\n throw new StorageError(\n `vana-storage upload network error: ${describe(cause)}`,\n \"UPLOAD_ERROR\",\n \"vana-storage\",\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (response.ok) {\n break;\n }\n\n responseText = await safeText(response);\n if (response.status === 429 && attempt < MAX_UPLOAD_ATTEMPTS) {\n const delayMs = retryDelayMs(response, responseText);\n if (delayMs > 0) {\n await sleep(delayMs);\n }\n continue;\n }\n\n throw new StorageError(\n `vana-storage upload failed: ${response.status} ${response.statusText} - ${responseText}`,\n \"UPLOAD_FAILED\",\n \"vana-storage\",\n );\n }\n\n if (!response?.ok) {\n throw new StorageError(\n `vana-storage upload failed after ${MAX_UPLOAD_ATTEMPTS} attempts - ${responseText}`,\n \"UPLOAD_FAILED\",\n \"vana-storage\",\n );\n }\n\n const result = (await response.json()) as VanaStorageUploadResponse;\n return {\n url: result.url,\n size: result.size,\n contentType,\n metadata: { key: result.key, etag: result.etag },\n };\n }\n\n /**\n * Download a blob by URL. The URL must point at a path under this\n * provider's endpoint.\n */\n async download(url: string): Promise<Blob> {\n const path = this.pathFromUrl(url);\n const header = await this.signRequest(\"GET\", path);\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}${path}`, {\n method: \"GET\",\n headers: { authorization: header },\n });\n } catch (cause) {\n throw new StorageError(\n `vana-storage download network error: ${describe(cause)}`,\n \"DOWNLOAD_ERROR\",\n \"vana-storage\",\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (!response.ok) {\n throw new StorageError(\n `vana-storage download failed: ${response.status} ${response.statusText}`,\n \"DOWNLOAD_FAILED\",\n \"vana-storage\",\n );\n }\n\n return await response.blob();\n }\n\n /**\n * Listing is not supported by vana-storage — file discovery is handled by\n * the Gateway DataRegistry, not the storage layer.\n */\n async list(_options?: StorageListOptions): Promise<StorageFile[]> {\n throw new StorageError(\n \"list is not supported by vana-storage; query the Gateway DataRegistry instead\",\n \"NOT_IMPLEMENTED\",\n \"vana-storage\",\n );\n }\n\n async delete(url: string): Promise<boolean> {\n const path = this.pathFromUrl(url);\n const header = await this.signRequest(\"DELETE\", path);\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}${path}`, {\n method: \"DELETE\",\n headers: { authorization: header },\n });\n } catch (cause) {\n throw new StorageError(\n `vana-storage delete network error: ${describe(cause)}`,\n \"DELETE_ERROR\",\n \"vana-storage\",\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (response.status === 404) return false;\n if (!response.ok) {\n throw new StorageError(\n `vana-storage delete failed: ${response.status} ${response.statusText}`,\n \"DELETE_FAILED\",\n \"vana-storage\",\n );\n }\n return true;\n }\n\n getConfig(): StorageProviderConfig {\n return {\n name: \"vana-storage\",\n type: \"vana-storage\",\n requiresAuth: true,\n features: {\n upload: true,\n download: true,\n list: false,\n delete: true,\n },\n };\n }\n\n private async signRequest(\n method: \"GET\" | \"PUT\" | \"DELETE\",\n path: string,\n body?: Uint8Array,\n ): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n return buildWeb3SignedHeader({\n signMessage: this.signer.signMessage,\n aud: this.endpoint,\n method,\n uri: path,\n iat: now,\n exp: now + DEFAULT_TOKEN_TTL_SECONDS,\n ...(body !== undefined && body.length > 0 && { body }),\n });\n }\n\n private pathFromUrl(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new StorageError(\n `Invalid URL: ${url}`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n const expectedHost = new URL(this.endpoint).host;\n if (parsed.host !== expectedHost) {\n throw new StorageError(\n `URL host '${parsed.host}' does not match storage endpoint '${expectedHost}'`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n // Restrict to a blob path for this owner so a caller cannot induce this\n // wallet to sign arbitrary same-host paths.\n const route = parseBlobPath(parsed.pathname);\n if (!route || route.owner.toLowerCase() !== this.ownerAddress) {\n throw new StorageError(\n `URL path '${parsed.pathname}' must be ${this.blobPathPrefix}/${this.ownerAddress}/{scope}/{collectedAt}`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n // A provider must only sign requests for its configured namespace. Chain\n // mode is strict: old legacy blobs should be migrated or re-collected\n // rather than read through a second ambiguous path.\n if (route.chainId !== this.chainId) {\n throw new StorageError(\n `URL chainId '${route.chainId ?? \"legacy\"}' does not match provider namespace '${this.namespaceDescription()}'`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n return parsed.pathname;\n }\n\n private namespaceDescription(): string {\n if (this.network !== undefined) {\n return `${this.network} (${this.chainId})`;\n }\n return this.chainId === undefined ? \"legacy\" : String(this.chainId);\n }\n}\n\ninterface ParsedBlobRoute {\n chainId?: number;\n owner: string;\n scope: string;\n collectedAt: string;\n}\n\nfunction isValidChainId(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0;\n}\n\nfunction resolveStorageNamespace(\n config: Pick<VanaStorageConfig, \"network\" | \"chainId\">,\n): {\n chainId?: number;\n network?: ProtocolNetwork;\n} {\n if (config.network !== undefined && !isProtocolNetwork(config.network)) {\n throw new StorageError(\n `Unsupported vana-storage network '${String(config.network)}'`,\n \"INVALID_NETWORK\",\n \"vana-storage\",\n );\n }\n\n if (config.chainId !== undefined && !isValidChainId(config.chainId)) {\n throw new StorageError(\n `Unsupported vana-storage chainId '${String(config.chainId)}'`,\n \"INVALID_CHAIN_ID\",\n \"vana-storage\",\n );\n }\n\n if (config.network === undefined) {\n return { chainId: config.chainId };\n }\n\n const networkChainId = getProtocolNetworkChainId(config.network);\n if (config.chainId !== undefined && config.chainId !== networkChainId) {\n throw new StorageError(\n `vana-storage network '${config.network}' resolves to chainId '${networkChainId}', not '${config.chainId}'`,\n \"INVALID_CHAIN_ID\",\n \"vana-storage\",\n );\n }\n\n return { chainId: networkChainId, network: config.network };\n}\n\n/**\n * Parse a storage blob pathname into structured route info, or `null` when the\n * path is neither the legacy nor the chain-scoped blob shape. Traversal\n * segments (`.` / `..`) are rejected as invalid.\n */\nfunction parseBlobPath(pathname: string): ParsedBlobRoute | null {\n const segments = pathname.split(\"/\").filter((s) => s.length > 0);\n const isTraversal = (s: string): boolean => s === \".\" || s === \"..\";\n\n // Legacy: /v1/blobs/{owner}/{scope}/{collectedAt}\n if (\n segments.length === 5 &&\n segments[0] === \"v1\" &&\n segments[1] === \"blobs\"\n ) {\n const [, , owner, scope, collectedAt] = segments as [\n string,\n string,\n string,\n string,\n string,\n ];\n if (isTraversal(scope) || isTraversal(collectedAt)) return null;\n return { owner, scope, collectedAt };\n }\n\n // Chain-scoped: /v1/chains/{chainId}/blobs/{owner}/{scope}/{collectedAt}\n if (\n segments.length === 7 &&\n segments[0] === \"v1\" &&\n segments[1] === \"chains\" &&\n segments[3] === \"blobs\"\n ) {\n const [, , chainIdSegment, , owner, scope, collectedAt] = segments as [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n ];\n if (!/^[0-9]+$/.test(chainIdSegment)) return null;\n const chainId = Number(chainIdSegment);\n if (!isValidChainId(chainId)) return null;\n if (isTraversal(scope) || isTraversal(collectedAt)) return null;\n return { chainId, owner, scope, collectedAt };\n }\n\n return null;\n}\n\nfunction encodeRelativePath(filename: string): string {\n const parts = filename.split(\"/\");\n if (\n parts.length !== 2 ||\n parts.some((p) => p.length === 0 || p === \".\" || p === \"..\")\n ) {\n throw new StorageError(\n `filename must be exactly '{scope}/{collectedAt}' with non-empty segments, got '${filename}'`,\n \"INVALID_FILENAME\",\n \"vana-storage\",\n );\n }\n return parts.map((p) => encodeURIComponent(p)).join(\"/\");\n}\n\nfunction describe(value: unknown): string {\n if (value instanceof Error) return value.message;\n return String(value);\n}\n\nfunction retryDelayMs(response: Response, responseText: string): number {\n const headerDelayMs = parseRetryAfterHeaderMs(\n response.headers.get(\"retry-after\"),\n );\n if (headerDelayMs !== null) {\n return clampRateLimitDelay(headerDelayMs);\n }\n\n return clampRateLimitDelay(parseRetryAfterBodyMs(responseText) ?? 0);\n}\n\nfunction parseRetryAfterHeaderMs(value: string | null): number | null {\n if (!value) return null;\n\n const seconds = Number(value);\n if (Number.isFinite(seconds)) {\n return seconds * 1000;\n }\n\n const dateMs = Date.parse(value);\n if (Number.isFinite(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n\n return null;\n}\n\nfunction parseRetryAfterBodyMs(responseText: string): number | null {\n if (!responseText) return null;\n\n try {\n const parsed = JSON.parse(responseText) as { retryAfter?: unknown };\n const seconds = Number(parsed.retryAfter);\n return Number.isFinite(seconds) ? seconds * 1000 : null;\n } catch {\n return null;\n }\n}\n\nfunction clampRateLimitDelay(delayMs: number): number {\n return Math.min(Math.max(0, delayMs), MAX_RATE_LIMIT_DELAY_MS);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function safeText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAOO;AACP,iCAGO;AACP,sBAIO;AAEP,MAAM,mBAAmB;AACzB,MAAM,0BAA0B;AAChC,MAAM,4BAA4B;AAClC,MAAM,sBAAsB;AAC5B,MAAM,0BAA0B;AAkHzB,MAAM,YAAuC;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA2B;AACrC,QAAI,CAAC,QAAQ,QAAQ,WAAW,CAAC,QAAQ,QAAQ,aAAa;AAC5D,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AACA,SAAK,YAAY,OAAO,YAAY,kBAAkB,QAAQ,QAAQ,EAAE;AACxE,UAAM,WAAW,wBAAwB,MAAM;AAC/C,SAAK,UAAU,SAAS;AACxB,SAAK,UAAU,SAAS;AACxB,SAAK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;AACtC,UAAM,UAAU,OAAO,OAAO,UAAU;AACxC,WAAO,OAAO,SAAS,OAAO,IAAI,UAAU,MAAO;AAAA,EACrD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,oBAAoB,SAAyB;AACpD,SAAO,KAAK,IAAI,KAAK,IAAI,GAAG,OAAO,GAAG,uBAAuB;AAC/D;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,eAAe,SAAS,UAAqC;AAC3D,MAAI;AACF,WAAO,MAAM,SAAS,KAAK;AAAA,EAC7B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../../src/storage/providers/vana-storage.ts"],"sourcesContent":["import {\n StorageError,\n type StorageProvider,\n type StorageUploadResult,\n type StorageFile,\n type StorageListOptions,\n type StorageProviderConfig,\n} from \"../index\";\nimport {\n buildWeb3SignedHeader,\n type Web3SignedSignFn,\n} from \"../../auth/web3-signed-builder\";\nimport {\n getProtocolNetworkChainId,\n isProtocolNetwork,\n type ProtocolNetwork,\n} from \"../../protocol/networks\";\nimport { readJsonObject } from \"../../utils/response-body\";\n\nconst DEFAULT_ENDPOINT = \"https://storage.vana.org\";\nconst LEGACY_BLOB_PATH_PREFIX = \"/v1/blobs\";\nconst DEFAULT_TOKEN_TTL_SECONDS = 300;\nconst MAX_UPLOAD_ATTEMPTS = 4;\nconst MAX_RATE_LIMIT_DELAY_MS = 30_000;\n\n/**\n * Wallet-style signer used by {@link VanaStorage} to authenticate every\n * request. For Personal Server flows this can be a registered server wallet\n * signing requests for the owner's storage namespace.\n *\n * @category Storage\n */\nexport interface VanaStorageSigner {\n /** EIP-191 address (`0x...`). */\n address: `0x${string}`;\n /** EIP-191 personal_sign callback (e.g. viem `account.signMessage`). */\n signMessage: Web3SignedSignFn;\n}\n\n/**\n * Configuration for {@link VanaStorage}.\n *\n * @category Storage\n */\nexport interface VanaStorageConfig {\n /**\n * Base URL of the vana-storage Worker. Defaults to `https://storage.vana.org`.\n *\n * This selects the storage endpoint and is independent of {@link network} /\n * {@link chainId}.\n */\n endpoint?: string;\n /**\n * Named Vana protocol network that scopes blob paths. Prefer this for known\n * Vana networks because it keeps callers on the SDK's typed network registry.\n *\n * When set, uploads use chain-scoped routes derived from the network's chain\n * ID (`/v1/chains/1480/...` for mainnet, `/v1/chains/14800/...` for Moksha).\n */\n network?: ProtocolNetwork;\n /**\n * Explicit numeric chain ID for custom or future networks not yet represented\n * by {@link ProtocolNetwork}.\n *\n * When set, uploads use chain-scoped routes\n * (`/v1/chains/{chainId}/blobs/...`) so data for different chains under the\n * same owner/scope/timestamp never collides. Reads and deletes must use the\n * same chain-scoped namespace; legacy blobs should be migrated or re-collected\n * rather than read through an ambiguous fallback. When omitted, the provider\n * preserves the legacy `/v1/blobs/...` routes and behavior.\n *\n * `chainId` and {@link network} are mutually consistent ways to select the\n * namespace. If both are provided, they must resolve to the same chain ID.\n * `endpoint` remains orthogonal: it picks the storage host, not the protocol\n * namespace.\n */\n chainId?: number;\n /**\n * Wallet signer used to authenticate writes and reads.\n */\n signer: VanaStorageSigner;\n /**\n * Owner namespace under which blobs are stored. Defaults to the signer address.\n */\n ownerAddress?: `0x${string}`;\n /**\n * Optional `fetch` implementation. Defaults to the global `fetch`.\n * Useful for tests and for environments that need a custom HTTP client.\n */\n fetchImpl?: typeof fetch;\n}\n\ninterface VanaStorageUploadResponse {\n key: string;\n url: string;\n etag: string;\n size: number;\n}\n\n/**\n * Response of {@link VanaStorage.deleteScope} -- the worker's\n * `DELETE /:owner/:scope` body. `count` is the number of blobs removed (0 is\n * a success: nothing was stored under that scope).\n *\n * @category Storage\n */\nexport interface VanaStorageScopeDeleteResult {\n deleted: boolean;\n scope: string;\n count: number;\n totalBytes: number;\n}\n\n/**\n * Storage provider that talks to the vana-storage Worker\n * (`https://storage.vana.org` by default). All requests are authenticated\n * with Web3Signed headers signed by the configured wallet.\n *\n * @remarks\n * Filenames passed to {@link VanaStorage.upload} must be of the form\n * `\"{scope}/{collectedAt}\"` (e.g. `\"instagram.profile/2026-05-08T20:00:00.000Z\"`).\n * The owner address is prepended automatically to produce the canonical\n * blob path `/v1/blobs/{owner}/{scope}/{collectedAt}`.\n *\n * When {@link VanaStorageConfig.network} or {@link VanaStorageConfig.chainId}\n * is set, paths are chain-scoped as\n * `/v1/chains/{chainId}/blobs/{owner}/{scope}/{collectedAt}` so different chains\n * never collide on the same host. The Web3Signed audience remains the endpoint\n * origin regardless of network.\n *\n * @category Storage\n *\n * @example\n * ```typescript\n * import { privateKeyToAccount } from \"viem/accounts\";\n * import { VanaStorage } from \"@opendatalabs/vana-sdk/node\";\n *\n * const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);\n * const storage = new VanaStorage({\n * signer: {\n * address: account.address,\n * signMessage: (msg) => account.signMessage({ message: msg }),\n * },\n * });\n *\n * const result = await storage.upload(\n * new Blob([ciphertext]),\n * \"instagram.profile/2026-05-08T20:00:00.000Z\",\n * );\n * ```\n */\nexport class VanaStorage implements StorageProvider {\n private readonly endpoint: string;\n private readonly network?: ProtocolNetwork;\n private readonly chainId?: number;\n private readonly blobPathPrefix: string;\n private readonly signer: VanaStorageSigner;\n private readonly ownerAddress: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(config: VanaStorageConfig) {\n if (!config?.signer?.address || !config?.signer?.signMessage) {\n throw new StorageError(\n \"VanaStorage requires a signer with address and signMessage\",\n \"MISSING_SIGNER\",\n \"vana-storage\",\n );\n }\n this.endpoint = (config.endpoint ?? DEFAULT_ENDPOINT).replace(/\\/+$/, \"\");\n const resolved = resolveStorageNamespace(config);\n this.network = resolved.network;\n this.chainId = resolved.chainId;\n this.blobPathPrefix =\n this.chainId !== undefined\n ? `/v1/chains/${this.chainId}/blobs`\n : LEGACY_BLOB_PATH_PREFIX;\n this.signer = config.signer;\n this.ownerAddress = (\n config.ownerAddress ?? config.signer.address\n ).toLowerCase();\n this.fetchImpl = config.fetchImpl ?? globalThis.fetch.bind(globalThis);\n }\n\n /**\n * Upload an encrypted blob to vana-storage.\n *\n * @param file - The blob to upload.\n * @param filename - Required relative key in the form `\"{scope}/{collectedAt}\"`.\n * The owner address is prepended automatically.\n */\n async upload(file: Blob, filename?: string): Promise<StorageUploadResult> {\n if (!filename) {\n throw new StorageError(\n \"VanaStorage.upload requires a filename of the form '{scope}/{collectedAt}'\",\n \"MISSING_FILENAME\",\n \"vana-storage\",\n );\n }\n\n const subpath = encodeRelativePath(filename);\n const path = `${this.blobPathPrefix}/${this.ownerAddress}/${subpath}`;\n const body = new Uint8Array(await file.arrayBuffer());\n const contentType =\n file.type !== \"\" ? file.type : \"application/octet-stream\";\n\n const header = await this.signRequest(\"PUT\", path, body);\n\n let response: Response | null = null;\n let responseText = \"\";\n for (let attempt = 1; attempt <= MAX_UPLOAD_ATTEMPTS; attempt++) {\n try {\n response = await this.fetchImpl(`${this.endpoint}${path}`, {\n method: \"PUT\",\n headers: {\n authorization: header,\n \"content-type\": contentType,\n },\n body,\n });\n } catch (cause) {\n throw new StorageError(\n `vana-storage upload network error: ${describe(cause)}`,\n \"UPLOAD_ERROR\",\n \"vana-storage\",\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (response.ok) {\n break;\n }\n\n responseText = await safeText(response);\n if (response.status === 429 && attempt < MAX_UPLOAD_ATTEMPTS) {\n const delayMs = retryDelayMs(response, responseText);\n if (delayMs > 0) {\n await sleep(delayMs);\n }\n continue;\n }\n\n throw new StorageError(\n `vana-storage upload failed: ${response.status} ${response.statusText} - ${responseText}`,\n \"UPLOAD_FAILED\",\n \"vana-storage\",\n );\n }\n\n if (!response?.ok) {\n throw new StorageError(\n `vana-storage upload failed after ${MAX_UPLOAD_ATTEMPTS} attempts - ${responseText}`,\n \"UPLOAD_FAILED\",\n \"vana-storage\",\n );\n }\n\n const result = (await response.json()) as VanaStorageUploadResponse;\n return {\n url: result.url,\n size: result.size,\n contentType,\n metadata: { key: result.key, etag: result.etag },\n };\n }\n\n /**\n * Download a blob by URL. The URL must point at a path under this\n * provider's endpoint.\n */\n async download(url: string): Promise<Blob> {\n const path = this.pathFromUrl(url);\n const header = await this.signRequest(\"GET\", path);\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}${path}`, {\n method: \"GET\",\n headers: { authorization: header },\n });\n } catch (cause) {\n throw new StorageError(\n `vana-storage download network error: ${describe(cause)}`,\n \"DOWNLOAD_ERROR\",\n \"vana-storage\",\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (!response.ok) {\n throw new StorageError(\n `vana-storage download failed: ${response.status} ${response.statusText}`,\n \"DOWNLOAD_FAILED\",\n \"vana-storage\",\n );\n }\n\n return await response.blob();\n }\n\n /**\n * Listing is not supported by vana-storage — file discovery is handled by\n * the Gateway DataRegistry, not the storage layer.\n */\n async list(_options?: StorageListOptions): Promise<StorageFile[]> {\n throw new StorageError(\n \"list is not supported by vana-storage; query the Gateway DataRegistry instead\",\n \"NOT_IMPLEMENTED\",\n \"vana-storage\",\n );\n }\n\n async delete(url: string): Promise<boolean> {\n const path = this.pathFromUrl(url);\n const header = await this.signRequest(\"DELETE\", path);\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}${path}`, {\n method: \"DELETE\",\n headers: { authorization: header },\n });\n } catch (cause) {\n throw new StorageError(\n `vana-storage delete network error: ${describe(cause)}`,\n \"DELETE_ERROR\",\n \"vana-storage\",\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (response.status === 404) return false;\n if (!response.ok) {\n throw new StorageError(\n `vana-storage delete failed: ${response.status} ${response.statusText}`,\n \"DELETE_FAILED\",\n \"vana-storage\",\n );\n }\n return true;\n }\n\n /**\n * Delete every version's blob under `(owner, scope)` --\n * `DELETE {prefix}/{owner}/{scope}` on vana-storage, signed with the same\n * Web3Signed header as uploads (aud = endpoint origin, empty bodyHash).\n * The worker accepts the owner's own signature or a personal server the\n * owner registered with the gateway.\n *\n * @param ownerAddress - Must equal the provider's configured owner; a\n * mismatch throws before anything is signed so this wallet can never be\n * induced to sign a delete for another namespace.\n * @param scope - The scope segment, e.g. `\"instagram.profile\"`.\n */\n async deleteScope(\n ownerAddress: `0x${string}`,\n scope: string,\n ): Promise<VanaStorageScopeDeleteResult> {\n if (ownerAddress.toLowerCase() !== this.ownerAddress) {\n throw new StorageError(\n `deleteScope owner '${ownerAddress}' does not match the configured owner '${this.ownerAddress}'`,\n \"INVALID_OWNER\",\n \"vana-storage\",\n );\n }\n if (\n scope.length === 0 ||\n scope.includes(\"/\") ||\n isTraversalSegment(scope)\n ) {\n throw new StorageError(\n `scope must be a single non-empty path segment, got '${scope}'`,\n \"INVALID_SCOPE\",\n \"vana-storage\",\n );\n }\n\n const path = `${this.blobPathPrefix}/${this.ownerAddress}/${encodeURIComponent(scope)}`;\n const header = await this.signRequest(\"DELETE\", path);\n\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}${path}`, {\n method: \"DELETE\",\n headers: { authorization: header },\n });\n } catch (cause) {\n throw new StorageError(\n `vana-storage scope delete network error: ${describe(cause)}`,\n \"DELETE_ERROR\",\n \"vana-storage\",\n { cause: cause instanceof Error ? cause : undefined },\n );\n }\n\n if (!response.ok) {\n const responseText = await safeText(response);\n throw new StorageError(\n `vana-storage scope delete failed: ${response.status} ${response.statusText} - ${responseText}`,\n \"DELETE_FAILED\",\n \"vana-storage\",\n );\n }\n\n // A 2xx is the success signal; the body is informational. Tolerate an\n // empty 204, a non-JSON body, or a JSON `null`/array, and only trust\n // fields that carry the documented type.\n const body = await readJsonObject(response);\n return {\n deleted: typeof body[\"deleted\"] === \"boolean\" ? body[\"deleted\"] : true,\n scope: typeof body[\"scope\"] === \"string\" ? body[\"scope\"] : scope,\n count: nonNegativeInteger(body[\"count\"]) ?? 0,\n totalBytes: nonNegativeInteger(body[\"totalBytes\"]) ?? 0,\n };\n }\n\n getConfig(): StorageProviderConfig {\n return {\n name: \"vana-storage\",\n type: \"vana-storage\",\n requiresAuth: true,\n features: {\n upload: true,\n download: true,\n list: false,\n delete: true,\n },\n };\n }\n\n private async signRequest(\n method: \"GET\" | \"PUT\" | \"DELETE\",\n path: string,\n body?: Uint8Array,\n ): Promise<string> {\n const now = Math.floor(Date.now() / 1000);\n return buildWeb3SignedHeader({\n signMessage: this.signer.signMessage,\n aud: this.endpoint,\n method,\n uri: path,\n iat: now,\n exp: now + DEFAULT_TOKEN_TTL_SECONDS,\n ...(body !== undefined && body.length > 0 && { body }),\n });\n }\n\n private pathFromUrl(url: string): string {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new StorageError(\n `Invalid URL: ${url}`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n const expectedHost = new URL(this.endpoint).host;\n if (parsed.host !== expectedHost) {\n throw new StorageError(\n `URL host '${parsed.host}' does not match storage endpoint '${expectedHost}'`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n // Restrict to a blob path for this owner so a caller cannot induce this\n // wallet to sign arbitrary same-host paths.\n const route = parseBlobPath(parsed.pathname);\n if (!route || route.owner.toLowerCase() !== this.ownerAddress) {\n throw new StorageError(\n `URL path '${parsed.pathname}' must be ${this.blobPathPrefix}/${this.ownerAddress}/{scope}/{collectedAt}`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n // A provider must only sign requests for its configured namespace. Chain\n // mode is strict: old legacy blobs should be migrated or re-collected\n // rather than read through a second ambiguous path.\n if (route.chainId !== this.chainId) {\n throw new StorageError(\n `URL chainId '${route.chainId ?? \"legacy\"}' does not match provider namespace '${this.namespaceDescription()}'`,\n \"INVALID_URL\",\n \"vana-storage\",\n );\n }\n return parsed.pathname;\n }\n\n private namespaceDescription(): string {\n if (this.network !== undefined) {\n return `${this.network} (${this.chainId})`;\n }\n return this.chainId === undefined ? \"legacy\" : String(this.chainId);\n }\n}\n\ninterface ParsedBlobRoute {\n chainId?: number;\n owner: string;\n scope: string;\n collectedAt: string;\n}\n\nfunction isValidChainId(value: unknown): value is number {\n return typeof value === \"number\" && Number.isInteger(value) && value > 0;\n}\n\nfunction resolveStorageNamespace(\n config: Pick<VanaStorageConfig, \"network\" | \"chainId\">,\n): {\n chainId?: number;\n network?: ProtocolNetwork;\n} {\n if (config.network !== undefined && !isProtocolNetwork(config.network)) {\n throw new StorageError(\n `Unsupported vana-storage network '${String(config.network)}'`,\n \"INVALID_NETWORK\",\n \"vana-storage\",\n );\n }\n\n if (config.chainId !== undefined && !isValidChainId(config.chainId)) {\n throw new StorageError(\n `Unsupported vana-storage chainId '${String(config.chainId)}'`,\n \"INVALID_CHAIN_ID\",\n \"vana-storage\",\n );\n }\n\n if (config.network === undefined) {\n return { chainId: config.chainId };\n }\n\n const networkChainId = getProtocolNetworkChainId(config.network);\n if (config.chainId !== undefined && config.chainId !== networkChainId) {\n throw new StorageError(\n `vana-storage network '${config.network}' resolves to chainId '${networkChainId}', not '${config.chainId}'`,\n \"INVALID_CHAIN_ID\",\n \"vana-storage\",\n );\n }\n\n return { chainId: networkChainId, network: config.network };\n}\n\n/**\n * Parse a storage blob pathname into structured route info, or `null` when the\n * path is neither the legacy nor the chain-scoped blob shape. Traversal\n * segments (`.` / `..`) are rejected as invalid.\n */\nfunction parseBlobPath(pathname: string): ParsedBlobRoute | null {\n const segments = pathname.split(\"/\").filter((s) => s.length > 0);\n const isTraversal = (s: string): boolean => s === \".\" || s === \"..\";\n\n // Legacy: /v1/blobs/{owner}/{scope}/{collectedAt}\n if (\n segments.length === 5 &&\n segments[0] === \"v1\" &&\n segments[1] === \"blobs\"\n ) {\n const [, , owner, scope, collectedAt] = segments as [\n string,\n string,\n string,\n string,\n string,\n ];\n if (isTraversal(scope) || isTraversal(collectedAt)) return null;\n return { owner, scope, collectedAt };\n }\n\n // Chain-scoped: /v1/chains/{chainId}/blobs/{owner}/{scope}/{collectedAt}\n if (\n segments.length === 7 &&\n segments[0] === \"v1\" &&\n segments[1] === \"chains\" &&\n segments[3] === \"blobs\"\n ) {\n const [, , chainIdSegment, , owner, scope, collectedAt] = segments as [\n string,\n string,\n string,\n string,\n string,\n string,\n string,\n ];\n if (!/^[0-9]+$/.test(chainIdSegment)) return null;\n const chainId = Number(chainIdSegment);\n if (!isValidChainId(chainId)) return null;\n if (isTraversal(scope) || isTraversal(collectedAt)) return null;\n return { chainId, owner, scope, collectedAt };\n }\n\n return null;\n}\n\nfunction encodeRelativePath(filename: string): string {\n const parts = filename.split(\"/\");\n if (\n parts.length !== 2 ||\n parts.some((p) => p.length === 0 || p === \".\" || p === \"..\")\n ) {\n throw new StorageError(\n `filename must be exactly '{scope}/{collectedAt}' with non-empty segments, got '${filename}'`,\n \"INVALID_FILENAME\",\n \"vana-storage\",\n );\n }\n return parts.map((p) => encodeURIComponent(p)).join(\"/\");\n}\n\nfunction isTraversalSegment(segment: string): boolean {\n return segment === \".\" || segment === \"..\";\n}\n\nfunction nonNegativeInteger(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0\n ? value\n : undefined;\n}\n\nfunction describe(value: unknown): string {\n if (value instanceof Error) return value.message;\n return String(value);\n}\n\nfunction retryDelayMs(response: Response, responseText: string): number {\n const headerDelayMs = parseRetryAfterHeaderMs(\n response.headers.get(\"retry-after\"),\n );\n if (headerDelayMs !== null) {\n return clampRateLimitDelay(headerDelayMs);\n }\n\n return clampRateLimitDelay(parseRetryAfterBodyMs(responseText) ?? 0);\n}\n\nfunction parseRetryAfterHeaderMs(value: string | null): number | null {\n if (!value) return null;\n\n const seconds = Number(value);\n if (Number.isFinite(seconds)) {\n return seconds * 1000;\n }\n\n const dateMs = Date.parse(value);\n if (Number.isFinite(dateMs)) {\n return Math.max(0, dateMs - Date.now());\n }\n\n return null;\n}\n\nfunction parseRetryAfterBodyMs(responseText: string): number | null {\n if (!responseText) return null;\n\n try {\n const parsed = JSON.parse(responseText) as { retryAfter?: unknown };\n const seconds = Number(parsed.retryAfter);\n return Number.isFinite(seconds) ? seconds * 1000 : null;\n } catch {\n return null;\n }\n}\n\nfunction clampRateLimitDelay(delayMs: number): number {\n return Math.min(Math.max(0, delayMs), MAX_RATE_LIMIT_DELAY_MS);\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function safeText(response: Response): Promise<string> {\n try {\n return await response.text();\n } catch {\n return \"\";\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,eAOO;AACP,iCAGO;AACP,sBAIO;AACP,2BAA+B;AAE/B,MAAM,mBAAmB;AACzB,MAAM,0BAA0B;AAChC,MAAM,4BAA4B;AAClC,MAAM,sBAAsB;AAC5B,MAAM,0BAA0B;AAgIzB,MAAM,YAAuC;AAAA,EACjC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA2B;AACrC,QAAI,CAAC,QAAQ,QAAQ,WAAW,CAAC,QAAQ,QAAQ,aAAa;AAC5D,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,IACF;AACA,SAAK,YAAY,OAAO,YAAY,kBAAkB,QAAQ,QAAQ,EAAE;AACxE,UAAM,WAAW,wBAAwB,MAAM;AAC/C,SAAK,UAAU,SAAS;AACxB,SAAK,UAAU,SAAS;AACxB,SAAK,iBACH,KAAK,YAAY,SACb,cAAc,KAAK,OAAO,WAC1B;AACN,SAAK,SAAS,OAAO;AACrB,SAAK,gBACH,OAAO,gBAAgB,OAAO,OAAO,SACrC,YAAY;AACd,SAAK,YAAY,OAAO,aAAa,WAAW,MAAM,KAAK,UAAU;AAAA,EACvE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAO,MAAY,UAAiD;AACxE,QAAI,CAAC,UAAU;AACb,YAAM,IAAI;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,MACF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