// plc.js — resolve a DID to its atproto verification key.
//
// This gates keyless reading: atproto-did-peer refuses to front a repo whose signed commit does
// not verify against this key, so a wrong or spoofed key means we serve nothing rather than
// serving someone else's content. Same resolver favela uses (favela-web/lib/plc.js).
import { httpClient } from './https.js'
import { decodeDidKey } from 'atproto-identity/lib/did-key.js'
export async function resolveDidVerifyKey (did, { plcUrl = 'https://plc.directory', doFetch = httpClient } = {}) {
const res = await doFetch(`${plcUrl}/${did}`)
if (!res.ok) throw new Error(`PLC ${res.status} for ${did}`)
const doc = JSON.parse(await res.text())
const vms = doc.verificationMethod || []
const vm = vms.find((m) => m.id && m.id.endsWith('#atproto')) || vms[0]
if (!vm || !vm.publicKeyMultibase) throw new Error(`no #atproto verificationMethod for ${did}`)
// .pubkey — decodeDidKey returns a descriptor, not raw bytes. Passing the descriptor makes
// verification fail in a way that looks like the peer has no records rather than like a key bug.
return decodeDidKey('did:key:' + vm.publicKeyMultibase).pubkey
}