import { Logger } from 'besonders-logger' 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 /** * Publish an IPNS record 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 name server * @param ipnsKey - IPNS key to publish under * @param recordBase64 - Base64-encoded IPNS record * @param delegation - Signed delegation authorizing the publish operation */ export async function publishIPNS( baseUrl: string, ipnsKey: string, recordBase64: string, delegation: SignedDelegation, ): Promise { baseUrl = stripUrlOfTrailingSlash(baseUrl) 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}/name/${ipnsKey}`, { method: 'POST', headers: { 'Authorization': `Bearer ${base64Delegation}`, 'Accept': 'application/json', 'Content-Type': 'text/plain', 'ucans': allTokens.join(', '), }, body: recordBase64, mode: 'cors', }) } catch (err) { ERROR('Failed to publish IPNS to ucan proxy:', err) throw err } const result = await response.json() if (!response.ok) throw ERROR(`[publishIPNS] failed:`, result?.error || result || response, { result, response }) DEBUG('[publishIPNS] result', { response, result }) }