/** * UCAN Delegation creation and serialization * * Implements delegation spec format (cmd/sub/pol) instead of capability-style (att/can/with). * @see https://github.com/ucan-wg/delegation */ import { CID } from 'multiformats' import { Delegation } from 'iso-ucan/delegation' import type { ISigner } from 'iso-signatures/types' import { Logger } from 'besonders-logger' import { CreateDelegationOptions, DelegationPayload, SignedDelegation, UcanCommand, } from './types.ts' const { DEBUG } = Logger.setup(Logger.INFO) /** * Convert a hex string to Uint8Array. */ function hexToBytes(hex: string): Uint8Array { const bytes = new Uint8Array(hex.length / 2) for (let i = 0; i < hex.length; i += 2) { bytes[i / 2] = parseInt(hex.substr(i, 2), 16) } return bytes } /** * Normalize a command path to always have a leading slash and no trailing slash. */ export function normalizeCommand(cmd: string): UcanCommand { let normalized = cmd if (!normalized.startsWith('/')) { normalized = '/' + normalized } if (normalized.endsWith('/') && normalized.length > 1) { normalized = normalized.slice(0, -1) } return normalized as UcanCommand } /** * Serialize a delegation payload to DAG-CBOR and sign it using iso-ucan. * * @returns SignedDelegation with bytes, CID, and metadata */ export async function serializeDelegation( payload: DelegationPayload, signer: ISigner, proofs: SignedDelegation[] = [] ): Promise { // Convert nonce string to Uint8Array const nonceBytes = hexToBytes(payload.nonce) // Create delegation using iso-ucan const delegation = await Delegation.create({ iss: signer, aud: payload.aud, sub: payload.sub, cmd: payload.cmd, pol: [], exp: payload.exp === Infinity ? null : payload.exp, nbf: payload.nbf, nonce: nonceBytes, }) DEBUG('[serializeDelegation] Created delegation', { iss: payload.iss, aud: payload.aud, sub: payload.sub, cmd: payload.cmd, cid: delegation.cid.toString(), }) return { bytes: delegation.bytes, cid: delegation.cid as unknown as CID, payload, proofs, } } /** * Create and serialize a storage delegation in one step. */ export async function createStoreDelegation( opts: CreateDelegationOptions & { signer: ISigner } ): Promise { const payload: DelegationPayload = { iss: opts.issuer, aud: opts.audience, sub: opts.subject, cmd: normalizeCommand(opts.command), pol: [], // Empty policy array for phase 1 exp: opts.expiration, nonce: opts.nonce ?? generateNonce(), // REQUIRED per delegation spec } if (opts.notBefore !== undefined) { payload.nbf = opts.notBefore } return serializeDelegation(payload, opts.signer, opts.proofs) } /** * Generate a random nonce (12 bytes = 24 hex chars). * Required by delegation spec for replay protection. */ function generateNonce(): string { const bytes = new Uint8Array(12) crypto.getRandomValues(bytes) return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('') } /** * Encode a SignedDelegation to base64 for use in HTTP headers. */ export function delegationToBase64(delegation: SignedDelegation): string { return btoa(String.fromCharCode(...delegation.bytes)) } /** * Get the service DID from a URL (did:web format). */ export function getServiceDID(url: string | URL): `did:web:${string}` { const urlObj = typeof url === 'string' ? new URL(url) : url return `did:web:${encodeURIComponent(urlObj.host)}` as const }