import { CarReader } from '@ipld/car' import { asyncIterableReader, createDecoder } from '@ipld/car/decoder' import { Applog, CidString, IpnsString, isEncryptedApplog, sortApplogsByTs } from '@wovin/core/applog' import { decodePubFromCar, streamReaderToIterable, tryParseCID } from '@wovin/core/ipfs' import { ThreadInMemory } from '@wovin/core/thread' import { Logger } from 'besonders-logger' import { CID } from 'multiformats/cid' import { ProxyConfig, stripUrlOfTrailingSlash } from './utils.ts' const { WARN, LOG, DEBUG, VERBOSE, ERROR } = Logger.setup(Logger.INFO) // eslint-disable-line no-unused-vars export class IPNSNeverPublishedError extends Error { constructor(ipns: string) { super(`IPNS key has never been published: ${ipns}`) this.name = 'IPNSNeverPublishedError' } } export class IPNSResolutionError extends Error { constructor(ipns: string, cause: unknown) { super(`Failed to resolve IPNS ${ipns}: ${cause}`) this.name = 'IPNSResolutionError' this.cause = cause } } export async function retrieveThread( proxyConfig: /*Pick<*/ ProxyConfig, // ? which one when /*, 'baseUrl' | 'gatewayBaseUrl'>*/ pubID: IpnsString | CidString | null, { readOnly = true, pinnedCID }: { readOnly?: boolean; pinnedCID?: CidString } = {}, ) { // TODO: refactor to be DRY (e.g. double in nftstorage/w3s) let { cid: parsedPubID, errors, isIpns } = tryParseCID(pubID) if (!parsedPubID) throw ERROR(`Failed to parse pubID`, pubID, errors) DEBUG(`[retrieveThread] parsedPubID`, parsedPubID) let cid: CID if (pinnedCID) { DEBUG(`[retrieveThread] using pinnedCID`) if (!isIpns) WARN(`pubID isn't IPNS, but pinnedCID different:`, { pubID, pinnedCID }) // semantically ambivalent cid = CID.parse(pinnedCID) } else if (!isIpns) { DEBUG(`[retrieveThread] pubID is not IPNS - using as CID`) cid = parsedPubID // TODO: check for dag-json ? } else { if (!pubID) throw ERROR(`[retrieveThread] neither pubID nor pinnedCID provided`) if (!proxyConfig.nameBaseUrl) throw ERROR(`[retrieveThread] IPNS, but no nameBaseUrl`) try { cid = await resolveIPNS(proxyConfig, pubID as IpnsString) DEBUG(`Resolved pub to CID`, cid.toString()) } catch (err) { // Re-throw custom IPNS errors to preserve error types for proper error handling if (err instanceof IPNSNeverPublishedError || err instanceof IPNSResolutionError) { throw err } throw ERROR(`Failed to resolve IPNS ${pubID}:`, err) } } const car = await retrieveCar(proxyConfig.gatewayBaseUrl, cid) const { applogs: maybeEncrypted } = await decodePubFromCar(car) const encrypted = maybeEncrypted.filter(log => isEncryptedApplog(log)) if (encrypted.length) WARN(`Found ${encrypted.length} encrypted logs - skipping`) // TODO: decryption const applogs = maybeEncrypted.filter(log => !(log instanceof Uint8Array)) as Applog[] sortApplogsByTs(applogs) const thread = ThreadInMemory.fromArray( applogs, `preview${pubID && pubID !== cid.toString() ? '-' + pubID : ''}@${cid.toString()}`, readOnly, ) return { cid, thread, encryptedCount: encrypted.length } // return thread } export async function resolveIPNS( proxyConfig: Pick, // ? which one when name: IpnsString, ): Promise { const baseUrl = stripUrlOfTrailingSlash(proxyConfig.nameBaseUrl) let response: Response try { response = await fetch(`${baseUrl}/name/${name}`) // TODO: ucan-proxy? or GW? } catch (err) { throw new IPNSResolutionError(name, err) } // Check if the IPNS key has never been published (404) or doesn't exist if (!response.ok) { if (response.status === 404) { throw new IPNSNeverPublishedError(name) } throw new IPNSResolutionError(name, `HTTP ${response.status}: ${response.statusText}`) } let result: any try { result = await response.json() } catch (err) { throw new IPNSResolutionError(name, `Invalid JSON response: ${err}`) } // Check if result.value exists if (!result.value) { // No value typically means never published throw new IPNSNeverPublishedError(name) } if (!result.value.startsWith('/ipfs/')) { WARN("IPNS value is not '/ipfs/..':", result) } try { return CID.parse(result.value.replace('/ipfs/', '')) } catch (err) { throw new IPNSResolutionError(name, `Invalid CID in IPNS value: ${err}`) } } /** * Best-effort resolve an IPNS name via one or more w3name-compatible HTTP services * (`GET /name/` → `{value:"/ipfs/"}`), independent of any connector * or UCAN auth and independent of the public IPFS DHT. * * This is the graceful-transition fallback for names published to w3name * (e.g. `https://name.web3.storage`) that haven't propagated to the public DHT, so * public gateways can't resolve them. Unlike {@link resolveIPNS} it returns `null` * instead of throwing, and races a list of bases — suitable as a last-resort step in * a larger resolution chain. Resolvers may be passed with or without a trailing `/name/`. * * @param ipns - The IPNS name (k51... string) * @param bases - w3name service base URLs (e.g. `["https://name.web3.storage"]`) * @returns The resolved CID, or null if no service could resolve the name */ export async function resolveIPNSViaW3Name(ipns: string, bases: string[]): Promise { if (!ipns.startsWith('k51')) return null // only IPNS libp2p-key names if (!bases?.length) return null for (const rawBase of bases) { try { const base = new URL(rawBase.endsWith('/') ? rawBase : rawBase + '/') // w3name convention is `/name/`; default the path in when the // resolver is given as a bare origin so callers can pass just the URL. if (base.pathname === '/') base.pathname = '/name/' const url = new URL(ipns, base).toString() DEBUG(`[resolveIPNSViaW3Name] GET ${url}`) const response = await fetch(url) if (!response.ok) { DEBUG(`[resolveIPNSViaW3Name] ${rawBase} returned ${response.status}`) continue } const result = await response.json() as { value?: string } const value = result?.value if (typeof value === 'string' && value.startsWith('/ipfs/')) { const cid = CID.parse(value.replace('/ipfs/', '')) DEBUG(`[resolveIPNSViaW3Name] resolved via ${rawBase}:`, cid.toString()) return cid } WARN(`[resolveIPNSViaW3Name] ${rawBase} returned 200 but no usable value`, result) } catch (err) { WARN(`[resolveIPNSViaW3Name] ${rawBase} failed:`, err) } } return null } export async function retrieveCar(gatewayBaseUrl: string, cid: CID): Promise { gatewayBaseUrl = stripUrlOfTrailingSlash(gatewayBaseUrl) DEBUG('Retrieving:', cid.toString(), 'from', gatewayBaseUrl) const url = `${gatewayBaseUrl}/ipfs/${cid}?format=car&dag-scope=all` // TODO: or via ucan-proxy? const response = await fetch(url) // TODO: refactor to be DRY (e.g. nftstorage/w3s) let result: Error | AsyncIterable if (!response?.ok || !response?.body) { result = ERROR(`[retrieveCar] unexpected response ${response?.statusText}`, { url }) WARN(`Gateway failed:`, url, result) } // The data is an AsyncIterable, convert it to an AsyncIterable for the CarReader result = streamReaderToIterable(response!.body.getReader()) if (result instanceof Error) throw result // return a CarReader from the CAR data return await CarReader.fromIterable(result) // return (await readCarAsFarAsICan(result)).car }