import type { DIDDocument, JsonWebKey } from "did-resolver"; import * as codec from "../codecs/jwk_jcs-pub.ts"; import { DID_LD_JSON, KEY_DID_METHOD_PREFIX } from "../constants.ts"; import { InvalidDidError } from "../errors/index.ts"; /** * Creates a DID document based on the raw public key bytes. * @see https://w3c-ccg.github.io/did-method-key/#create * @param pubKeyBytes - The "raw-public-key-bytes". * @param identifier - The identifier associated with the public key. * @param contentType - The content type, e.g. "application/did+ld+json" or "application/did+json" * @returns The DID document corresponding to the public key. */ export function pubKeyBytesToDidDoc( pubKeyBytes: Uint8Array, identifier: string, contentType?: string, ): DIDDocument { const did = `${KEY_DID_METHOD_PREFIX}${identifier}`; const keyId = `${did}#${identifier}`; let publicKeyJwk: JsonWebKey; try { publicKeyJwk = codec.decode(pubKeyBytes); } catch (error) { throw new InvalidDidError( error instanceof Error ? error.message : "Unknown error", ); } return { ...(contentType === DID_LD_JSON && { "@context": [ "https://www.w3.org/ns/did/v1", "https://w3id.org/security/suites/jws-2020/v1", ], }), assertionMethod: [keyId], authentication: [keyId], capabilityDelegation: [keyId], capabilityInvocation: [keyId], id: did, verificationMethod: [ { controller: did, id: keyId, publicKeyJwk, type: "JsonWebKey2020", }, ], }; }