import { resolveIPNSSequence, type IPNSPublishTarget } from '@wovin/core/ipns' import { type StorageConnector } from '@wovin/core/pubsub' import type { BlockStoreish } from '@wovin/core/ipfs' import { Logger } from 'besonders-logger' import { EdDSASigner } from 'iso-signatures/signers/eddsa.js' import type { ISigner } from 'iso-signatures/types' import { CID } from 'multiformats' import { resolveIPNS, retrieveCar, retrieveThread } from './retrieve.ts' import { storeCar } from './store.ts' import { carMirrorPush, carMirrorPull, type BlockStoreForPull, type CarMirrorProgress, type DagLinkCache } from './car-mirror.ts' import { publishIPNS } from './publish.ts' import { createStoreDelegation, getServiceDID } from './delegation.ts' import { SignedDelegation, StorageCommand, UcanCommand } from './types.ts' import { ClassFields, ParametersExceptFirst } from './utils.ts' const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO) // eslint-disable-line no-unused-vars export * from './retrieve.ts' export * from './store.ts' export * from './publish.ts' export * from './delegation.ts' export * from './types.ts' export type { BlockStoreForPull, CarMirrorProgress, DagLinkCache } from './car-mirror.ts' export { createDagLinkCache } from './car-mirror.ts' /** * Storage connector using UCAN delegation spec for authorization. * * Authorization flow: * 1. init() creates a parent delegation from issuerKey to a temporary key * 2. storeCar() creates a request delegation from tmpKey to service, with parent as proof * 3. The delegation chain is sent in HTTP headers for server validation */ export class UcanStoreProxyConnector implements StorageConnector { /** * Initialize a new connector with parent delegations. * * Creates delegations from the issuer key to a temporary key for all storage commands. * The temporary key is used to create request-specific delegations. */ static async init( { url, issuerKey, delegations, ...restConfig }: Partial>> & { url: string issuerKey: ISigner delegations?: SignedDelegation[] }, ) { const serviceDID = getServiceDID(url) const tmpKey = await EdDSASigner.generate() LOG(`Init UcanStoreProxyConnector:`, { url, serviceDID, issuerDID: issuerKey.did, tmpKeyDID: tmpKey.did, }) // Use provided delegations if available, otherwise generate them let parentDelegations: SignedDelegation[] = delegations ?? [] if (!delegations) { // Create parent delegations from issuer to tmpKey for each command const commands: UcanCommand[] = ['/storage/read', '/storage/store', '/storage/pin', '/ipns/publish'] for (const cmd of commands) { const delegation = await createStoreDelegation({ issuer: issuerKey.did, audience: tmpKey.did, subject: serviceDID, command: cmd, expiration: Infinity, signer: issuerKey, }) parentDelegations.push(delegation) DEBUG(`Created parent delegation`, { cmd, cid: delegation.cid.toString() }) } } return Object.assign( new UcanStoreProxyConnector(url, issuerKey, tmpKey, parentDelegations), restConfig, ) } /** Per-attempt timeout for storeCar (ms). Defaults to the package default (10 min floor). */ storeTimeoutMs?: number /** Number of storeCar retries AFTER the initial attempt (default 2 => 3 attempts total). */ storeRetries?: number /** Delay between storeCar retry attempts (ms). Default: 500. */ storeRetryDelayMs?: number constructor( public baseUrl: string, private issuerKey: ISigner, private tmpKey: ISigner, private delegations: SignedDelegation[] = [], public gatewayBaseUrl: string = baseUrl, public nameBaseUrl: string = baseUrl, ) { } get isSetup() { return true } get isValid() { return true // TODO test ucan validity (expiration, etc.) } /** * Store a CAR file with UCAN authorization. * * Creates a request delegation from tmpKey to service with the store command, * using the parent delegation as proof of authority. */ async storeCar(car: Blob, signal?: AbortSignal) { const serviceDID = getServiceDID(this.baseUrl) // Find the parent delegation for storage/store const parentDelegation = this.delegations.find(d => d.payload.cmd === '/storage/store') if (!parentDelegation) { throw ERROR(`No parent delegation found for /storage/store`) } DEBUG(`[storeCar] Creating request delegation:`, { issuer: this.tmpKey.did, audience: serviceDID, subject: serviceDID, parentIss: parentDelegation.payload.iss, parentAud: parentDelegation.payload.aud, parentSub: parentDelegation.payload.sub, }) // Create request delegation: tmpKey -> service, with parent as proof const requestDelegation = await createStoreDelegation({ issuer: this.tmpKey.did, audience: serviceDID, subject: serviceDID, command: '/storage/store', expiration: Infinity, proofs: [parentDelegation], signer: this.tmpKey, }) return storeCar(this.baseUrl, car, requestDelegation, signal, { timeoutMs: this.storeTimeoutMs, retries: this.storeRetries, retryDelayMs: this.storeRetryDelayMs, }) } /** * Push a DAG to the server using car-mirror protocol. * * Lazily walks the DAG from the blockStore, using bloom filters * to skip blocks the server already has. */ async pushDag( rootCid: CID, blockStore: BlockStoreish, opts: { signal?: AbortSignal onProgress?: (progress: CarMirrorProgress) => void /** * Root CID of the last snapshot this server is known to already have (e.g. the * previous successful push's rootCid for this thread) — NOT this push's own * rootCid. Lets the sender skip that subtree instead of re-walking the whole DAG. * Safe to omit or pass a stale/wrong value — the server self-corrects in round 2 * at the cost of one extra round-trip. See CarMirrorOptions.prevBoundary. */ prevBoundary?: CID } = {}, ): Promise { const { signal, onProgress, prevBoundary } = opts const serviceDID = getServiceDID(this.baseUrl) // Find the parent delegation for storage/store const parentDelegation = this.delegations.find(d => d.payload.cmd === '/storage/store') if (!parentDelegation) { throw ERROR(`No parent delegation found for /storage/store`) } // Create request delegation: tmpKey -> service, with parent as proof const requestDelegation = await createStoreDelegation({ issuer: this.tmpKey.did, audience: serviceDID, subject: serviceDID, command: '/storage/store', expiration: Infinity, proofs: [parentDelegation], signer: this.tmpKey, }) return carMirrorPush(this.baseUrl, rootCid, blockStore, { delegation: requestDelegation, signal, onProgress, prevBoundary, }) } /** * Pull a DAG from the server using car-mirror protocol. * * Incrementally fetches only blocks the local store doesn't have, * verifying and storing them directly into the provided blockStore. */ async pullDag( rootCid: CID, blockStore: BlockStoreForPull, opts: { signal?: AbortSignal onProgress?: (progress: CarMirrorProgress) => void /** * Root CID of the last snapshot already fully present locally (e.g. the * subscription's lastCID) — stops the local want-discovery walk at the * boundary instead of re-walking the whole history. Safe to omit or pass * a stale value. See CarMirrorOptions.prevBoundary. */ prevBoundary?: CID /** Cross-call local-store-walk memoization. See CarMirrorOptions.dagLinkCache. */ dagLinkCache?: DagLinkCache } = {}, ): Promise { const { signal, onProgress, prevBoundary, dagLinkCache } = opts const serviceDID = getServiceDID(this.baseUrl) // Find the parent delegation for storage/read const parentDelegation = this.delegations.find(d => d.payload.cmd === '/storage/read') if (!parentDelegation) { throw ERROR(`No parent delegation found for /storage/read`) } // Create request delegation: tmpKey -> service, with parent as proof const requestDelegation = await createStoreDelegation({ issuer: this.tmpKey.did, audience: serviceDID, subject: serviceDID, command: '/storage/read', expiration: Infinity, proofs: [parentDelegation], signer: this.tmpKey, }) return carMirrorPull(this.baseUrl, rootCid, blockStore, { delegation: requestDelegation, signal, onProgress, prevBoundary, dagLinkCache, }) } async retrieveCar(cid: CID) { if (!this.gatewayBaseUrl) throw new Error(`gatewayBaseUrl required for retrieveCar`) return retrieveCar(this.gatewayBaseUrl, cid) } async retrieveThread( ...args: ParametersExceptFirst ) { if (!this.gatewayBaseUrl) throw new Error(`gatewayBaseUrl required for retrieveThread`) return retrieveThread(this, ...args) } async resolveIPNS( ...args: ParametersExceptFirst ) { if (!this.nameBaseUrl) throw new Error(`nameBaseUrl required for resolveIPNS (connector baseUrl=${this.baseUrl})`) return resolveIPNS(this, ...args) } /** * Publish an IPNS record with UCAN authorization. * * Creates a request delegation from tmpKey to service with the ipns/publish command, * using the parent delegation as proof of authority. */ async publishIPNS(ipnsKey: string, recordBase64: string) { // Always publish to baseUrl (the Kubo-backed storage proxy). // nameBaseUrl is used only for resolving, not publishing. const nameUrl = this.baseUrl const serviceDID = getServiceDID(nameUrl) // Find the parent delegation for ipns/publish const parentDelegation = this.delegations.find(d => d.payload.cmd === '/ipns/publish') if (!parentDelegation) { throw ERROR(`No parent delegation found for /ipns/publish`) } DEBUG(`[publishIPNS] Creating request delegation:`, { issuer: this.tmpKey.did, audience: serviceDID, subject: serviceDID, parentIss: parentDelegation.payload.iss, parentAud: parentDelegation.payload.aud, parentSub: parentDelegation.payload.sub, }) // Create request delegation: tmpKey -> service, with parent as proof const requestDelegation = await createStoreDelegation({ issuer: this.tmpKey.did, audience: serviceDID, subject: serviceDID, command: '/ipns/publish', expiration: Infinity, proofs: [parentDelegation], signer: this.tmpKey, }) return publishIPNS(nameUrl, ipnsKey, recordBase64, requestDelegation) } /** * Return an IPNSPublishTarget adapter for use with publishIPNSRecord(). * * The adapter publishes IPNS records to `baseUrl` (the Kubo-backed storage * proxy) via UCAN delegation and resolves the current sequence number from * the server at `baseUrl`. Sequence resolution uses a GET to * `${baseUrl}/name/${ipnsName}`, parsing the raw record's sequence field. * If the server returns a 404 or no record, `null` is returned and the * caller (e.g. `publishIPNSRecord`) starts from sequence 0n. * * Because resolution is server-truth, this target alone provides monotonic * sequences across restarts and devices. Core's sequence-coherence retry * (in `publishIPNSRecord`) handles any race conditions by bumping and * retrying on conflict. */ asIPNSTarget(): IPNSPublishTarget { return { name: `ucan-proxy:${this.baseUrl}`, publish: async (ipnsName: string, recordBytes: Uint8Array) => { const recordBase64 = btoa(String.fromCharCode(...recordBytes)) await this.publishIPNS(ipnsName, recordBase64) }, resolveSequence: async (ipnsName: string): Promise => { try { return await resolveIPNSSequence(this.baseUrl, ipnsName) } catch (err) { console.warn(`[asIPNSTarget] resolveSequence failed for ${ipnsName}:`, err) return null } }, } } } /** * Publish a snapshot CID to IPNS via a UcanStoreProxyConnector. * * This is the standard way to publish a snapshot root CID after storing its * CAR blob. It signs the IPNS record with the given key and publishes it * to the connector's base URL (the Kubo-backed storage proxy). Sequence * numbers are resolved server-side so the connector target alone provides * monotonicity across devices; core's coherence retry handles any races. * * Previously each app duplicated this logic (localStorage sequence tracking, * zt.ax target assembly, etc.). This shared helper replaces all of them. * * @param cid - The root CID of the snapshot to publish. * @param ipnsKey - The raw Ed25519 private key bytes for IPNS signing. * @param connector - The storage connector (publishes to its `baseUrl`). * @returns The signed IPNS record, including the sequence used. */ export async function publishSnapshotToIpns( cid: CID, ipnsKey: Uint8Array, connector: UcanStoreProxyConnector, ): Promise { const { publishIPNSRecord } = await import('@wovin/core/ipns') const targets = [connector.asIPNSTarget()] return publishIPNSRecord(ipnsKey, cid, targets) }