import { Logger } from 'besonders-logger' import { CID } from 'multiformats' import { SignedDelegation } from './types.ts' import { delegationToBase64 } from './delegation.ts' import { stripUrlOfTrailingSlash } from './utils.ts' const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO) // eslint-disable-line no-unused-vars export class DagIncompleteError extends Error { rootCID: string reason: string constructor(rootCID: string, reason: string) { super(`DAG incomplete for ${rootCID}: ${reason}`) this.name = 'DagIncompleteError' this.rootCID = rootCID this.reason = reason } } /** * Store a CAR file using UCAN delegation authentication. * * Uses the delegation spec format (cmd/sub/pol) for authorization. * The delegation and its proof chain are sent via HTTP headers: * - Authorization: Bearer * - ucans: * * @param baseUrl - Base URL of the storage server * @param car - CAR file blob to upload * @param delegation - Signed delegation authorizing the store operation * @returns CID of the stored content */ export async function storeCar(baseUrl: string, car: Blob, delegation: SignedDelegation, signal?: AbortSignal): Promise { baseUrl = stripUrlOfTrailingSlash(baseUrl) const sizeMB = (car.size / 1_048_576).toFixed(1) const timeoutMs = signal ? undefined : Math.max(300_000, car.size / 1000) LOG(`[storeCar] Uploading CAR: ${sizeMB} MB${timeoutMs ? `, timeout: ${(timeoutMs / 1000).toFixed(0)}s` : ', external signal'}`) let response: Response try { // Convert delegation to base64 for Authorization header const base64Delegation = delegationToBase64(delegation) // Collect all delegations (request + proofs) for ucans header const allTokens = [base64Delegation] for (const proof of delegation.proofs) { allTokens.push(delegationToBase64(proof)) } response = await fetch(`${baseUrl}/upload`, { method: 'PUT', headers: { 'Authorization': `Bearer ${base64Delegation}`, 'Accept': 'application/json', 'Content-Type': `application/car`, 'ucans': allTokens.join(', '), }, body: car, mode: 'cors', signal: signal ?? AbortSignal.timeout(timeoutMs!), }) } catch (err) { ERROR('Failed to upload to ucan proxy:', err) if ((err as any).message?.includes('net::ERR_CERT_AUTHORITY_INVALID')) { // certificate authority error } else { // something else went wrong } throw err } // Docs: https://nft.storage/api-docs/#operations-NFT_Storage-upload const result = await response.json() if (!response.ok) { const dagMsg = result?.reason ?? result?.error if (response.status === 422 && typeof dagMsg === 'string' && dagMsg.startsWith('DAG incomplete for ')) { throw new DagIncompleteError(dagMsg.match(/DAG incomplete for ([^:]+)/)?.[1] ?? '', dagMsg) } throw ERROR(`[storeCar] failed:`, result?.error || result || response, { result, response }) } DEBUG('[storeCar] result', { response, result }) // Server returns {Roots: [{Cid: {"/": "..."}, PinErrorMsg: ""}, ...]} const roots = result.Roots ?? (result.Root ? [result.Root] : []) // support both new (Roots array) and legacy (Root object) format if (!roots.length || !roots[0]?.Cid) throw ERROR(`[storeCar] unexpected response shape — no root CID:`, { result }) if (roots.length > 1) WARN(`[storeCar] CAR has ${roots.length} roots, returning first only`) for (const root of roots) { const pinErr = root.PinErrorMsg if (pinErr) WARN(`Pin error for ${root.Cid?.['/']}: ${pinErr}`, { result }) } const err = result.Type === 'error' ? result.Message : null if (err) WARN(`Pin error:`, err, { result }) return CID.parse(roots[0].Cid['/']) // docs: https://docs.ipfs.tech/reference/kubo/rpc/#api-v0-dag-import }