{"version":3,"file":"index.cjs","sources":["../src/util.ts","../src/Digest.ts","../src/signers/ES256KSigner.ts","../src/signers/SimpleSigner.ts","../src/signers/EllipticSigner.ts","../src/signers/EdDSASigner.ts","../src/signers/NaclSigner.ts","../src/signers/ES256Signer.ts","../src/SignerAlgorithm.ts","../src/blockchains/bip122.ts","../src/blockchains/cosmos.ts","../src/blockchains/index.ts","../src/VerifierAlgorithm.ts","../src/Errors.ts","../src/ConditionalAlgorithm.ts","../src/JWT.ts","../src/encryption/JWE.ts","../src/encryption/xc20pDir.ts","../src/encryption/X25519-ECDH-ES.ts","../src/encryption/X25519-ECDH-1PU.ts","../src/encryption/ECDH.ts","../src/encryption/createEncrypter.ts","../src/encryption/xc20pEncryption.ts"],"sourcesContent":["import { concat, fromString, toString } from 'uint8arrays'\nimport { x25519 } from '@noble/curves/ed25519'\nimport type { EphemeralKeyPair } from './encryption/types.js'\nimport { varint } from 'multiformats'\nimport { BaseName, decode, encode } from 'multibase'\nimport type { VerificationMethod } from 'did-resolver'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\n\nconst u8a = { toString, fromString, concat }\n\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport interface EcdsaSignature {\n  r: string\n  s: string\n  recoveryParam?: number\n}\n\n/**\n * @deprecated Signers will be expected to return base64url `string` signatures.\n */\nexport type ECDSASignature = {\n  compact: Uint8Array\n  recovery?: number\n}\n\nexport type JsonWebKey = {\n  crv: string\n  kty: string\n  x?: string\n  y?: string\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [key: string]: any\n}\n\nexport function bytesToBase64url(b: Uint8Array): string {\n  return u8a.toString(b, 'base64url')\n}\n\nexport function base64ToBytes(s: string): Uint8Array {\n  const inputBase64Url = s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '')\n  return u8a.fromString(inputBase64Url, 'base64url')\n}\n\nexport function bytesToBase64(b: Uint8Array): string {\n  return u8a.toString(b, 'base64pad')\n}\n\nexport function base58ToBytes(s: string): Uint8Array {\n  return u8a.fromString(s, 'base58btc')\n}\n\nexport function bytesToBase58(b: Uint8Array): string {\n  return u8a.toString(b, 'base58btc')\n}\n\nexport type KNOWN_JWA = 'ES256' | 'ES256K' | 'ES256K-R' | 'Ed25519' | 'EdDSA'\n\nexport type KNOWN_VERIFICATION_METHOD =\n  | 'JsonWebKey2020'\n  | 'Multikey'\n  | 'Secp256k1SignatureVerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n  | 'Secp256k1VerificationKey2018' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n  | 'EcdsaSecp256k1VerificationKey2019' // ES256K / ES256K-R\n  | 'EcdsaPublicKeySecp256k1' // deprecated in favor of EcdsaSecp256k1VerificationKey2019\n  | 'EcdsaSecp256k1RecoveryMethod2020' // ES256K-R (ES256K also supported with 1 less bit of security)\n  | 'EcdsaSecp256r1VerificationKey2019' // ES256 / P-256\n  | 'Ed25519VerificationKey2018'\n  | 'Ed25519VerificationKey2020'\n  | 'ED25519SignatureVerification' // deprecated\n  | 'ConditionalProof2022'\n  | 'X25519KeyAgreementKey2019' // deprecated\n  | 'X25519KeyAgreementKey2020'\n\nexport type KNOWN_KEY_TYPE = 'Secp256k1' | 'Ed25519' | 'X25519' | 'Bls12381G1' | 'Bls12381G2' | 'P-256'\n\nexport type PublicKeyTypes = Record<KNOWN_JWA, KNOWN_VERIFICATION_METHOD[]>\n\nexport const SUPPORTED_PUBLIC_KEY_TYPES: PublicKeyTypes = {\n  ES256: ['JsonWebKey2020', 'Multikey', 'EcdsaSecp256r1VerificationKey2019'],\n  ES256K: [\n    'EcdsaSecp256k1VerificationKey2019',\n    /**\n     * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n     */\n    'EcdsaSecp256k1RecoveryMethod2020',\n    /**\n     * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n     *   not an ethereumAddress\n     */\n    'Secp256k1VerificationKey2018',\n    /**\n     * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n     *   not an ethereumAddress\n     */\n    'Secp256k1SignatureVerificationKey2018',\n    /**\n     * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n     *   not an ethereumAddress\n     */\n    'EcdsaPublicKeySecp256k1',\n    /**\n     *  TODO - support R1 key as well\n     *   'ConditionalProof2022',\n     */\n    'JsonWebKey2020',\n    'Multikey',\n  ],\n  'ES256K-R': [\n    'EcdsaSecp256k1VerificationKey2019',\n    /**\n     * Equivalent to EcdsaSecp256k1VerificationKey2019 when key is an ethereumAddress\n     */\n    'EcdsaSecp256k1RecoveryMethod2020',\n    /**\n     * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n     *   not an ethereumAddress\n     */\n    'Secp256k1VerificationKey2018',\n    /**\n     * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n     *   not an ethereumAddress\n     */\n    'Secp256k1SignatureVerificationKey2018',\n    /**\n     * @deprecated, supported for backward compatibility. Equivalent to EcdsaSecp256k1VerificationKey2019 when key is\n     *   not an ethereumAddress\n     */\n    'EcdsaPublicKeySecp256k1',\n    'ConditionalProof2022',\n    'JsonWebKey2020',\n    'Multikey',\n  ],\n  Ed25519: [\n    'ED25519SignatureVerification',\n    'Ed25519VerificationKey2018',\n    'Ed25519VerificationKey2020',\n    'JsonWebKey2020',\n    'Multikey',\n  ],\n  EdDSA: [\n    'ED25519SignatureVerification',\n    'Ed25519VerificationKey2018',\n    'Ed25519VerificationKey2020',\n    'JsonWebKey2020',\n    'Multikey',\n  ],\n}\n\nexport const VM_TO_KEY_TYPE: Record<KNOWN_VERIFICATION_METHOD, KNOWN_KEY_TYPE | undefined> = {\n  Secp256k1SignatureVerificationKey2018: 'Secp256k1',\n  Secp256k1VerificationKey2018: 'Secp256k1',\n  EcdsaSecp256k1VerificationKey2019: 'Secp256k1',\n  EcdsaPublicKeySecp256k1: 'Secp256k1',\n  EcdsaSecp256k1RecoveryMethod2020: 'Secp256k1',\n  EcdsaSecp256r1VerificationKey2019: 'P-256',\n  Ed25519VerificationKey2018: 'Ed25519',\n  Ed25519VerificationKey2020: 'Ed25519',\n  ED25519SignatureVerification: 'Ed25519',\n  X25519KeyAgreementKey2019: 'X25519',\n  X25519KeyAgreementKey2020: 'X25519',\n  ConditionalProof2022: undefined,\n  JsonWebKey2020: undefined, // key type must be specified in the JWK\n  Multikey: undefined, // key type must be extracted from the multicodec\n}\n\nexport type KNOWN_CODECS =\n  | 'ed25519-pub'\n  | 'x25519-pub'\n  | 'secp256k1-pub'\n  | 'bls12_381-g1-pub'\n  | 'bls12_381-g2-pub'\n  | 'p256-pub'\n\n// this is from the multicodec table https://github.com/multiformats/multicodec/blob/master/table.csv\nexport const supportedCodecs: Record<KNOWN_CODECS, number> = {\n  'ed25519-pub': 0xed,\n  'x25519-pub': 0xec,\n  'secp256k1-pub': 0xe7,\n  'bls12_381-g1-pub': 0xea,\n  'bls12_381-g2-pub': 0xeb,\n  'p256-pub': 0x1200,\n}\n\nexport const CODEC_TO_KEY_TYPE: Record<KNOWN_CODECS, KNOWN_KEY_TYPE> = {\n  'bls12_381-g1-pub': 'Bls12381G1',\n  'bls12_381-g2-pub': 'Bls12381G2',\n  'ed25519-pub': 'Ed25519',\n  'p256-pub': 'P-256',\n  'secp256k1-pub': 'Secp256k1',\n  'x25519-pub': 'X25519',\n}\n\n/**\n * Extracts the raw byte representation of a public key from a VerificationMethod along with an inferred key type\n * @param pk a VerificationMethod entry from a DIDDocument\n * @return an object containing the `keyBytes` of the public key and an inferred `keyType`\n */\nexport function extractPublicKeyBytes(pk: VerificationMethod): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n  if (pk.publicKeyBase58) {\n    return {\n      keyBytes: base58ToBytes(pk.publicKeyBase58),\n      keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n    }\n  } else if (pk.publicKeyBase64) {\n    return {\n      keyBytes: base64ToBytes(pk.publicKeyBase64),\n      keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD],\n    }\n  } else if (pk.publicKeyHex) {\n    return { keyBytes: hexToBytes(pk.publicKeyHex), keyType: VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n  } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'secp256k1' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n    return {\n      keyBytes: secp256k1.ProjectivePoint.fromAffine({\n        x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n        y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n      }).toRawBytes(false),\n      keyType: 'Secp256k1',\n    }\n  } else if (pk.publicKeyJwk && pk.publicKeyJwk.crv === 'P-256' && pk.publicKeyJwk.x && pk.publicKeyJwk.y) {\n    return {\n      keyBytes: p256.ProjectivePoint.fromAffine({\n        x: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.x)),\n        y: bytesToBigInt(base64ToBytes(pk.publicKeyJwk.y)),\n      }).toRawBytes(false),\n      keyType: 'P-256',\n    }\n  } else if (\n    pk.publicKeyJwk &&\n    pk.publicKeyJwk.kty === 'OKP' &&\n    ['Ed25519', 'X25519'].includes(pk.publicKeyJwk.crv ?? '') &&\n    pk.publicKeyJwk.x\n  ) {\n    return { keyBytes: base64ToBytes(pk.publicKeyJwk.x), keyType: pk.publicKeyJwk.crv as KNOWN_KEY_TYPE }\n  } else if (pk.publicKeyMultibase) {\n    const { keyBytes, keyType } = multibaseToBytes(pk.publicKeyMultibase)\n    return { keyBytes, keyType: keyType ?? VM_TO_KEY_TYPE[pk.type as KNOWN_VERIFICATION_METHOD] }\n  }\n  return { keyBytes: new Uint8Array() }\n}\n\n/**\n * Encodes the given byte array to a multibase string (defaulting to base58btc).\n * If a codec is provided, the corresponding multicodec prefix will be added.\n *\n * @param b - the Uint8Array to be encoded\n * @param base - the base to use for encoding (defaults to base58btc)\n * @param codec - the codec to use for encoding (defaults to no codec)\n *\n * @returns the multibase encoded string\n *\n * @public\n */\nexport function bytesToMultibase(\n  b: Uint8Array,\n  base: BaseName = 'base58btc',\n  codec?: keyof typeof supportedCodecs | number\n): string {\n  if (!codec) {\n    return u8a.toString(encode(base, b), 'utf-8')\n  } else {\n    const codecCode = typeof codec === 'string' ? supportedCodecs[codec] : codec\n    const prefixLength = varint.encodingLength(codecCode)\n    const multicodecEncoding = new Uint8Array(prefixLength + b.length)\n    varint.encodeTo(codecCode, multicodecEncoding) // set prefix\n    multicodecEncoding.set(b, prefixLength) // add the original bytes\n    return u8a.toString(encode(base, multicodecEncoding), 'utf-8')\n  }\n}\n\n/**\n * Converts a multibase string to the Uint8Array it represents.\n * This method will assume the byte array that is multibase encoded is a multicodec and will attempt to decode it.\n *\n * @param s - the string to be converted\n *\n * @throws if the string is not formatted correctly.\n *\n * @public\n */\nexport function multibaseToBytes(s: string): { keyBytes: Uint8Array; keyType?: KNOWN_KEY_TYPE } {\n  const bytes = decode(s)\n\n  // look for known key lengths first\n  // Ed25519/X25519, secp256k1/P256 compressed or not, BLS12-381 G1/G2 compressed\n  if ([32, 33, 48, 64, 65, 96].includes(bytes.length)) {\n    return { keyBytes: bytes }\n  }\n\n  // then assume multicodec, otherwise return the bytes\n  try {\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    const [codec, length] = varint.decode(bytes)\n    const possibleCodec: string | undefined =\n      Object.entries(supportedCodecs).filter(([, code]) => code === codec)?.[0][0] ?? ''\n    return { keyBytes: bytes.slice(length), keyType: CODEC_TO_KEY_TYPE[possibleCodec as KNOWN_CODECS] }\n  } catch (e) {\n    // not a multicodec, return the bytes\n    return { keyBytes: bytes }\n  }\n}\n\nexport function hexToBytes(s: string, minLength?: number): Uint8Array {\n  let input = s.startsWith('0x') ? s.substring(2) : s\n\n  if (input.length % 2 !== 0) {\n    input = `0${input}`\n  }\n\n  if (minLength) {\n    const paddedLength = Math.max(input.length, minLength * 2)\n    input = input.padStart(paddedLength, '00')\n  }\n\n  return u8a.fromString(input.toLowerCase(), 'base16')\n}\n\nexport function encodeBase64url(s: string): string {\n  return bytesToBase64url(u8a.fromString(s))\n}\n\nexport function decodeBase64url(s: string): string {\n  return u8a.toString(base64ToBytes(s))\n}\n\nexport function bytesToHex(b: Uint8Array): string {\n  return u8a.toString(b, 'base16')\n}\n\nexport function bytesToBigInt(b: Uint8Array): bigint {\n  return BigInt(`0x` + u8a.toString(b, 'base16'))\n}\n\nexport function bigintToBytes(n: bigint, minLength?: number): Uint8Array {\n  return hexToBytes(n.toString(16), minLength)\n}\n\nexport function stringToBytes(s: string): Uint8Array {\n  return u8a.fromString(s, 'utf-8')\n}\n\nexport function toJose({ r, s, recoveryParam }: EcdsaSignature, recoverable?: boolean): string {\n  const jose = new Uint8Array(recoverable ? 65 : 64)\n  jose.set(u8a.fromString(r, 'base16'), 0)\n  jose.set(u8a.fromString(s, 'base16'), 32)\n  if (recoverable) {\n    if (typeof recoveryParam === 'undefined') {\n      throw new Error('Signer did not return a recoveryParam')\n    }\n    jose[64] = <number>recoveryParam\n  }\n  return bytesToBase64url(jose)\n}\n\nexport function fromJose(signature: string): { r: string; s: string; recoveryParam?: number } {\n  const signatureBytes: Uint8Array = base64ToBytes(signature)\n  if (signatureBytes.length < 64 || signatureBytes.length > 65) {\n    throw new TypeError(`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`)\n  }\n  const r = bytesToHex(signatureBytes.slice(0, 32))\n  const s = bytesToHex(signatureBytes.slice(32, 64))\n  const recoveryParam = signatureBytes.length === 65 ? signatureBytes[64] : undefined\n  return { r, s, recoveryParam }\n}\n\nexport function toSealed(ciphertext: string, tag?: string): Uint8Array {\n  return u8a.concat([base64ToBytes(ciphertext), tag ? base64ToBytes(tag) : new Uint8Array(0)])\n}\n\nexport function leftpad(data: string, size = 64): string {\n  if (data.length === size) return data\n  return '0'.repeat(size - data.length) + data\n}\n\n/**\n * Generate random x25519 key pair.\n */\nexport function generateKeyPair(): { secretKey: Uint8Array; publicKey: Uint8Array } {\n  const secretKey = x25519.utils.randomPrivateKey()\n  const publicKey = x25519.getPublicKey(secretKey)\n  return {\n    secretKey: secretKey,\n    publicKey: publicKey,\n  }\n}\n\n/**\n * Generate private-public x25519 key pair from `seed`.\n */\nexport function generateKeyPairFromSeed(seed: Uint8Array): { secretKey: Uint8Array; publicKey: Uint8Array } {\n  if (seed.length !== 32) {\n    throw new Error(`x25519: seed must be ${32} bytes`)\n  }\n  return {\n    publicKey: x25519.getPublicKey(seed),\n    secretKey: seed,\n  }\n}\n\nexport function genX25519EphemeralKeyPair(): EphemeralKeyPair {\n  const epk = generateKeyPair()\n  return {\n    publicKeyJWK: { kty: 'OKP', crv: 'X25519', x: bytesToBase64url(epk.publicKey) },\n    secretKey: epk.secretKey,\n  }\n}\n\n/**\n * Checks if a variable is defined and not null.\n * After this check, typescript sees the variable as defined.\n *\n * @param arg - The input to be verified\n *\n * @returns true if the input variable is defined.\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n  return arg !== null && typeof arg !== 'undefined'\n}\n","import { sha256 as sha256Hash } from '@noble/hashes/sha256'\nexport { ripemd160 } from '@noble/hashes/ripemd160'\nimport { keccak_256 } from '@noble/hashes/sha3'\nimport { fromString, toString, concat } from 'uint8arrays'\n\nexport function sha256(payload: string | Uint8Array): Uint8Array {\n  const data = typeof payload === 'string' ? fromString(payload) : payload\n  return sha256Hash(data)\n}\n\nexport const keccak = keccak_256\n\nexport function toEthereumAddress(hexPublicKey: string): string {\n  const hashInput = fromString(hexPublicKey.slice(2), 'base16')\n  return `0x${toString(keccak(hashInput).slice(-20), 'base16')}`\n}\n\nfunction writeUint32BE(value: number, array = new Uint8Array(4)): Uint8Array {\n  const encoded = fromString(value.toString(), 'base10')\n  array.set(encoded, 4 - encoded.length)\n  return array\n}\n\nconst lengthAndInput = (input: Uint8Array): Uint8Array => concat([writeUint32BE(input.length), input])\n\n// This implementation of concatKDF was inspired by these two implementations:\n// https://github.com/digitalbazaar/minimal-cipher/blob/master/algorithms/ecdhkdf.js\n// https://github.com/panva/jose/blob/master/lib/jwa/ecdh/derive.js\nexport function concatKDF(\n  secret: Uint8Array,\n  keyLen: number,\n  alg: string,\n  producerInfo?: Uint8Array,\n  consumerInfo?: Uint8Array\n): Uint8Array {\n  if (keyLen !== 256) throw new Error(`Unsupported key length: ${keyLen}`)\n  const value = concat([\n    lengthAndInput(fromString(alg)),\n    lengthAndInput(typeof producerInfo === 'undefined' ? new Uint8Array(0) : producerInfo), // apu\n    lengthAndInput(typeof consumerInfo === 'undefined' ? new Uint8Array(0) : consumerInfo), // apv\n    writeUint32BE(keyLen),\n  ])\n\n  // since our key lenght is 256 we only have to do one round\n  const roundNumber = 1\n  return sha256(concat([writeUint32BE(roundNumber), secret, value]))\n}\n","import { leftpad, toJose } from '../util.js'\nimport { Signer } from '../JWT.js'\nimport { sha256 } from '../Digest.js'\nimport { secp256k1 } from '@noble/curves/secp256k1'\n\n/**\n *  Creates a configured signer function for signing data using the ES256K (secp256k1 + sha256) algorithm.\n *\n *  The signing function itself takes the data as a `Uint8Array` or `string` and returns a `base64Url`-encoded signature\n *\n *  @example\n *  ```typescript\n *  const sign: Signer = ES256KSigner(process.env.PRIVATE_KEY)\n *  const signature: string = await sign(data)\n *  ```\n *\n *  @param    {String}    privateKey   a private key as `Uint8Array`\n *  @param    {Boolean}   recoverable  an optional flag to add the recovery param to the generated signatures\n *  @return   {Function}               a configured signer function `(data: string | Uint8Array): Promise<string>`\n */\nexport function ES256KSigner(privateKey: Uint8Array, recoverable = false): Signer {\n  const privateKeyBytes: Uint8Array = privateKey\n  if (privateKeyBytes.length !== 32) {\n    throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKeyBytes.length}`)\n  }\n\n  return async (data: string | Uint8Array): Promise<string> => {\n    const signature = secp256k1.sign(sha256(data), privateKeyBytes)\n    return toJose(\n      {\n        r: leftpad(signature.r.toString(16)),\n        s: leftpad(signature.s.toString(16)),\n        recoveryParam: signature.recovery,\n      },\n      recoverable\n    )\n  }\n}\n","import { fromJose, hexToBytes } from '../util.js'\nimport type { Signer } from '../JWT.js'\nimport { ES256KSigner } from './ES256KSigner.js'\n\n/**\n * @deprecated Please use ES256KSigner\n *  The SimpleSigner returns a configured function for signing data.\n *\n *  @example\n *  const signer = SimpleSigner(process.env.PRIVATE_KEY)\n *  signer(data, (err, signature) => {\n *    ...\n *  })\n *\n *  @param    {String}         hexPrivateKey    a hex encoded private key\n *  @return   {Function}                     a configured signer function\n */\nfunction SimpleSigner(hexPrivateKey: string): Signer {\n  const signer = ES256KSigner(hexToBytes(hexPrivateKey), true)\n  return async (data) => {\n    const signature = (await signer(data)) as string\n    return fromJose(signature)\n  }\n}\n\nexport default SimpleSigner\n","import type { Signer } from '../JWT.js'\nimport { hexToBytes } from '../util.js'\nimport { ES256KSigner } from './ES256KSigner.js'\n\n/**\n * @deprecated Please use ES256KSigner\n *  The EllipticSigner returns a configured function for signing data.\n *\n *  @example\n *  ```typescript\n *  const signer = EllipticSigner(process.env.PRIVATE_KEY)\n *  signer(data).then( (signature: string) => {\n *    ...\n *  })\n *  ```\n *\n *  @param    {String}         hexPrivateKey    a hex encoded private key\n *  @return   {Function}                        a configured signer function\n */\nfunction EllipticSigner(hexPrivateKey: string): Signer {\n  return ES256KSigner(hexToBytes(hexPrivateKey))\n}\n\nexport default EllipticSigner\n","import { ed25519 } from '@noble/curves/ed25519'\nimport type { Signer } from '../JWT.js'\nimport { bytesToBase64url, stringToBytes } from '../util.js'\n\n/**\n *  Creates a configured signer function for signing data using the EdDSA (Ed25519) algorithm.\n *\n *  The private key is expected to be a `Uint8Array` of 32 bytes, but for compatibility 64 bytes are also acceptable.\n * Users of `@stablelib/ed25519` or `tweetnacl` will be able to use the 64 byte secret keys that library generates.\n * These libraries precompute the public key and append it as the last 32 bytes of the secretKey, to speed up later\n * signing operations.\n *\n *  The signing function itself takes the data as a `Uint8Array` or utf8 `string` and returns a `base64Url`-encoded\n * signature\n *\n *  @example\n *  ```typescript\n *  const sign: Signer = EdDSASigner(process.env.PRIVATE_KEY)\n *  const signature: string = await sign(data)\n *  ```\n *\n *  @param    {String}    secretKey   a 32 or 64 byte secret key as `Uint8Array`\n *  @return   {Function}              a configured signer function `(data: string | Uint8Array): Promise<string>`\n */\nexport function EdDSASigner(secretKey: Uint8Array): Signer {\n  const privateKeyBytes: Uint8Array = secretKey\n  if (![32, 64].includes(privateKeyBytes.length)) {\n    throw new Error(`bad_key: Invalid private key format. Expecting 32 or 64 bytes, but got ${privateKeyBytes.length}`)\n  }\n  return async (data: string | Uint8Array): Promise<string> => {\n    const dataBytes: Uint8Array = typeof data === 'string' ? stringToBytes(data) : data\n    const signature = ed25519.sign(dataBytes, privateKeyBytes.slice(0, 32))\n    return bytesToBase64url(signature)\n  }\n}\n","import { EdDSASigner as EdDSASigner } from './EdDSASigner.js'\nimport type { Signer } from '../JWT.js'\nimport { base64ToBytes } from '../util.js'\n\n/**\n * @deprecated Please use EdDSASigner\n *\n *  The NaclSigner returns a configured function for signing data using the Ed25519 algorithm.\n *\n *  The signing function itself takes the data as a `string` or `Uint8Array` parameter and returns a\n *   `base64Url`-encoded signature.\n *\n *  @example\n *  const signer = NaclSigner(process.env.PRIVATE_KEY)\n *  const data: string = '...'\n *  signer(data).then( (signature: string) => {\n *    ...\n *  })\n *\n *  @param    {String}   base64PrivateKey    a 64 byte base64 encoded private key\n *  @return   {Function}                     a configured signer function\n */\n\nfunction NaclSigner(base64PrivateKey: string): Signer {\n  return EdDSASigner(base64ToBytes(base64PrivateKey))\n}\n\nexport default NaclSigner\n","import { leftpad, toJose } from '../util.js'\nimport { Signer } from '../JWT.js'\nimport { sha256 } from '../Digest.js'\nimport { p256 } from '@noble/curves/p256'\n\n/**\n *  Creates a configured signer function for signing data using the ES256 (secp256r1 + sha256) algorithm.\n *\n *  The signing function itself takes the data as a `Uint8Array` or `string` and returns a `base64Url`-encoded signature\n *\n *  @example\n *  ```typescript\n *  const sign: Signer = ES256Signer(process.env.PRIVATE_KEY)\n *  const signature: string = await sign(data)\n *  ```\n *\n *  @param    {String}    privateKey   a private key as `Uint8Array`\n *  @return   {Function}               a configured signer function `(data: string | Uint8Array): Promise<string>`\n */\nexport function ES256Signer(privateKey: Uint8Array): Signer {\n  if (privateKey.length !== 32) {\n    throw new Error(`bad_key: Invalid private key format. Expecting 32 bytes, but got ${privateKey.length}`)\n  }\n  return async (data: string | Uint8Array): Promise<string> => {\n    const signature = p256.sign(sha256(data), privateKey)\n    return toJose({\n      r: leftpad(signature.r.toString(16)),\n      s: leftpad(signature.s.toString(16)),\n    })\n  }\n}\n","import type { Signer, SignerAlgorithm } from './JWT.js'\nimport { type EcdsaSignature, fromJose, toJose } from './util.js'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction instanceOfEcdsaSignature(object: any): object is EcdsaSignature {\n  return typeof object === 'object' && 'r' in object && 's' in object\n}\n\nexport function ES256SignerAlg(): SignerAlgorithm {\n  return async function sign(payload: string, signer: Signer): Promise<string> {\n    const signature: EcdsaSignature | string = await signer(payload)\n    if (instanceOfEcdsaSignature(signature)) {\n      return toJose(signature)\n    } else {\n      return signature\n    }\n  }\n}\n\nexport function ES256KSignerAlg(recoverable?: boolean): SignerAlgorithm {\n  return async function sign(payload: string, signer: Signer): Promise<string> {\n    const signature: EcdsaSignature | string = await signer(payload)\n    if (instanceOfEcdsaSignature(signature)) {\n      return toJose(signature, recoverable)\n    } else {\n      if (recoverable && typeof fromJose(signature).recoveryParam === 'undefined') {\n        throw new Error(`not_supported: ES256K-R not supported when signer doesn't provide a recovery param`)\n      }\n      return signature\n    }\n  }\n}\n\nexport function Ed25519SignerAlg(): SignerAlgorithm {\n  return async function sign(payload: string, signer: Signer): Promise<string> {\n    const signature: EcdsaSignature | string = await signer(payload)\n    if (!instanceOfEcdsaSignature(signature)) {\n      return signature\n    } else {\n      throw new Error('invalid_config: expected a signer function that returns a string instead of signature object')\n    }\n  }\n}\n\ninterface SignerAlgorithms {\n  [alg: string]: SignerAlgorithm\n}\n\nconst algorithms: SignerAlgorithms = {\n  ES256: ES256SignerAlg(),\n  ES256K: ES256KSignerAlg(),\n  // This is a non-standard algorithm but retained for backwards compatibility\n  // see https://github.com/decentralized-identity/did-jwt/issues/146\n  'ES256K-R': ES256KSignerAlg(true),\n  // This is actually incorrect but retained for backwards compatibility\n  // see https://github.com/decentralized-identity/did-jwt/issues/130\n  Ed25519: Ed25519SignerAlg(),\n  EdDSA: Ed25519SignerAlg(),\n}\n\nfunction SignerAlg(alg: string): SignerAlgorithm {\n  const impl: SignerAlgorithm = algorithms[alg]\n  if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n  return impl\n}\n\nexport default SignerAlg\n","import { base58ToBytes, bytesToBase58, bytesToHex, hexToBytes } from '../util.js'\nimport { ripemd160, sha256 } from '../Digest.js'\n\nexport function publicKeyToAddress(publicKey: string, otherAddress: string): string {\n  // Use the same version/prefix byte as the given address.\n  const version = bytesToHex(base58ToBytes(otherAddress).slice(0, 1))\n  const publicKeyBuffer = hexToBytes(publicKey)\n  const publicKeyHash = ripemd160(sha256(publicKeyBuffer))\n  const step1 = version + bytesToHex(publicKeyHash)\n  const step2 = sha256(hexToBytes(step1))\n  const step3 = sha256(step2)\n  const checksum = bytesToHex(step3).substring(0, 8)\n  const step4 = step1 + checksum\n  return bytesToBase58(hexToBytes(step4))\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport { bech32 } from '@scure/base'\nimport { sha256, ripemd160 } from '../Digest.js'\n\nexport function publicKeyToAddress(publicKey: string, prefix: string): string {\n  const publicKeyBuffer = secp256k1.ProjectivePoint.fromHex(publicKey).toRawBytes()\n  const hash = ripemd160(sha256(publicKeyBuffer))\n  const words = bech32.toWords(hash)\n  return bech32.encode(prefix, words).replace(prefix, '')\n}\n","import { publicKeyToAddress as bip122 } from './bip122.js'\nimport { publicKeyToAddress as cosmos } from './cosmos.js'\nimport { toEthereumAddress } from '../Digest.js'\n\nexport function verifyBlockchainAccountId(publicKey: string, blockchainAccountId: string | undefined): boolean {\n  if (blockchainAccountId) {\n    const chain = blockchainAccountId.split(':')\n    switch (chain[0]) {\n      case 'bip122':\n        chain[chain.length - 1] = bip122(publicKey, chain[chain.length - 1])\n        break\n      case 'cosmos':\n        chain[chain.length - 1] = cosmos(publicKey, chain[1])\n        break\n      case 'eip155':\n        chain[chain.length - 1] = toEthereumAddress(publicKey)\n        break\n      default:\n        return false\n    }\n    return chain.join(':').toLowerCase() === blockchainAccountId.toLowerCase()\n  }\n  return false\n}\n","import { sha256, toEthereumAddress } from './Digest.js'\nimport type { VerificationMethod } from 'did-resolver'\nimport {\n  base64ToBytes,\n  bytesToHex,\n  EcdsaSignature,\n  ECDSASignature,\n  extractPublicKeyBytes,\n  KNOWN_JWA,\n  stringToBytes,\n} from './util.js'\nimport { verifyBlockchainAccountId } from './blockchains/index.js'\nimport { secp256k1 } from '@noble/curves/secp256k1'\nimport { p256 } from '@noble/curves/p256'\nimport { ed25519 } from '@noble/curves/ed25519'\n\n// converts a JOSE signature to it's components\nexport function toSignatureObject(signature: string, recoverable = false): EcdsaSignature {\n  const rawSig: Uint8Array = base64ToBytes(signature)\n  if (rawSig.length !== (recoverable ? 65 : 64)) {\n    throw new Error('wrong signature length')\n  }\n  const r: string = bytesToHex(rawSig.slice(0, 32))\n  const s: string = bytesToHex(rawSig.slice(32, 64))\n  const sigObj: EcdsaSignature = { r, s }\n  if (recoverable) {\n    sigObj.recoveryParam = rawSig[64]\n  }\n  return sigObj\n}\n\nexport function toSignatureObject2(signature: string, recoverable = false): ECDSASignature {\n  const bytes = base64ToBytes(signature)\n  if (bytes.length !== (recoverable ? 65 : 64)) {\n    throw new Error('wrong signature length')\n  }\n  return {\n    compact: bytes.slice(0, 64),\n    recovery: bytes[64],\n  }\n}\n\nexport function verifyES256(data: string, signature: string, authenticators: VerificationMethod[]): VerificationMethod {\n  const hash = sha256(data)\n  const sig = p256.Signature.fromCompact(toSignatureObject2(signature).compact)\n  const fullPublicKeys = authenticators.filter((a: VerificationMethod) => !a.ethereumAddress && !a.blockchainAccountId)\n\n  const signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n    try {\n      const { keyBytes } = extractPublicKeyBytes(pk)\n      return p256.verify(sig, hash, keyBytes)\n    } catch (err) {\n      return false\n    }\n  })\n\n  if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n  return signer\n}\n\nexport function verifyES256K(\n  data: string,\n  signature: string,\n  authenticators: VerificationMethod[]\n): VerificationMethod {\n  const hash = sha256(data)\n  const signatureNormalized = secp256k1.Signature.fromCompact(base64ToBytes(signature)).normalizeS()\n  const fullPublicKeys = authenticators.filter((a: VerificationMethod) => {\n    return !a.ethereumAddress && !a.blockchainAccountId\n  })\n  const blockchainAddressKeys = authenticators.filter((a: VerificationMethod) => {\n    return a.ethereumAddress || a.blockchainAccountId\n  })\n\n  let signer: VerificationMethod | undefined = fullPublicKeys.find((pk: VerificationMethod) => {\n    try {\n      const { keyBytes } = extractPublicKeyBytes(pk)\n      return secp256k1.verify(signatureNormalized, hash, keyBytes)\n    } catch (err) {\n      return false\n    }\n  })\n\n  if (!signer && blockchainAddressKeys.length > 0) {\n    signer = verifyRecoverableES256K(data, signature, blockchainAddressKeys)\n  }\n\n  if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n  return signer\n}\n\nexport function verifyRecoverableES256K(\n  data: string,\n  signature: string,\n  authenticators: VerificationMethod[]\n): VerificationMethod {\n  const signatures: ECDSASignature[] = []\n  if (signature.length > 86) {\n    signatures.push(toSignatureObject2(signature, true))\n  } else {\n    const so = toSignatureObject2(signature, false)\n    signatures.push({ ...so, recovery: 0 })\n    signatures.push({ ...so, recovery: 1 })\n  }\n  const hash = sha256(data)\n\n  const checkSignatureAgainstSigner = (sigObj: ECDSASignature): VerificationMethod | undefined => {\n    const signature = secp256k1.Signature.fromCompact(sigObj.compact).addRecoveryBit(sigObj.recovery || 0)\n    const recoveredPublicKey = signature.recoverPublicKey(hash)\n    const recoveredAddress = toEthereumAddress(recoveredPublicKey.toHex(false)).toLowerCase()\n    const recoveredPublicKeyHex = recoveredPublicKey.toHex(false)\n    const recoveredCompressedPublicKeyHex = recoveredPublicKey.toHex(true)\n\n    return authenticators.find((a: VerificationMethod) => {\n      const { keyBytes } = extractPublicKeyBytes(a)\n      const keyHex = bytesToHex(keyBytes)\n      return (\n        keyHex === recoveredPublicKeyHex ||\n        keyHex === recoveredCompressedPublicKeyHex ||\n        a.ethereumAddress?.toLowerCase() === recoveredAddress ||\n        a.blockchainAccountId?.split('@eip155')?.[0].toLowerCase() === recoveredAddress || // CAIP-2\n        verifyBlockchainAccountId(recoveredPublicKeyHex, a.blockchainAccountId) // CAIP-10\n      )\n    })\n  }\n\n  // Find first verification method\n  for (const signature of signatures) {\n    const verificationMethod = checkSignatureAgainstSigner(signature)\n    if (verificationMethod) return verificationMethod\n  }\n  // If no one found matching\n  throw new Error('invalid_signature: Signature invalid for JWT')\n}\n\nexport function verifyEd25519(\n  data: string,\n  signature: string,\n  authenticators: VerificationMethod[]\n): VerificationMethod {\n  const clear = stringToBytes(data)\n  const signatureBytes = base64ToBytes(signature)\n  const signer = authenticators.find((a: VerificationMethod) => {\n    const { keyBytes, keyType } = extractPublicKeyBytes(a)\n    if (keyType === 'Ed25519') {\n      return ed25519.verify(signatureBytes, clear, keyBytes)\n    } else {\n      return false\n    }\n  })\n  if (!signer) throw new Error('invalid_signature: Signature invalid for JWT')\n  return signer\n}\n\ntype Verifier = (data: string, signature: string, authenticators: VerificationMethod[]) => VerificationMethod\n\ntype Algorithms = Record<KNOWN_JWA, Verifier>\n\nconst algorithms: Algorithms = {\n  ES256: verifyES256,\n  ES256K: verifyES256K,\n  // This is a non-standard algorithm but retained for backwards compatibility\n  // see https://github.com/decentralized-identity/did-jwt/issues/146\n  'ES256K-R': verifyRecoverableES256K,\n  // This is actually incorrect but retained for backwards compatibility\n  // see https://github.com/decentralized-identity/did-jwt/issues/130\n  Ed25519: verifyEd25519,\n  EdDSA: verifyEd25519,\n}\n\nfunction VerifierAlgorithm(alg: string): Verifier {\n  const impl: Verifier = algorithms[alg as KNOWN_JWA]\n  if (!impl) throw new Error(`not_supported: Unsupported algorithm ${alg}`)\n  return impl\n}\n\nVerifierAlgorithm.toSignatureObject = toSignatureObject\n\nexport default VerifierAlgorithm\n","/**\n * Error prefixes used for known verification failure cases.\n *\n * For compatibility, these error prefixes match the existing error messages, but will be adjusted in a future major\n * version update to match the scenarios better.\n *\n * @beta\n */\nexport const JWT_ERROR = {\n  /**\n   * Thrown when a JWT payload schema is unexpected or when validity period does not match\n   */\n  INVALID_JWT: 'invalid_jwt',\n  /**\n   * Thrown when the verifier audience does not match the one set in the JWT payload\n   */\n  INVALID_AUDIENCE: 'invalid_config',\n  /**\n   * Thrown when none of the public keys of the issuer match the signature of the JWT.\n   *\n   * This is equivalent to `NO_SUITABLE_KEYS` when the `proofPurpose` is NOT specified.\n   */\n  INVALID_SIGNATURE: 'invalid_signature',\n  /**\n   * Thrown when the DID document of the issuer does not have any keys that match the signature for the given\n   * `proofPurpose`.\n   *\n   * This is equivalent to `invalid_signature`, when a `proofPurpose` is specified.\n   */\n  NO_SUITABLE_KEYS: 'no_suitable_keys',\n  /**\n   * Thrown when the `alg` of the JWT or the encoding of the key is not supported\n   */\n  NOT_SUPPORTED: 'not_supported',\n  /**\n   * Thrown when the DID resolver is unable to resolve the issuer DID.\n   */\n  RESOLVER_ERROR: 'resolver_error',\n}\n","import type { VerificationMethod } from 'did-resolver'\nimport { JWT_ERROR } from './Errors.js'\nimport { type JWTDecoded, type JWTVerifyOptions, resolveAuthenticator, verifyJWT, verifyJWTDecoded } from './JWT.js'\n\nexport const CONDITIONAL_PROOF_2022 = 'ConditionalProof2022'\n\nexport async function verifyProof(\n  jwt: string,\n  { header, payload, signature, data }: JWTDecoded,\n  authenticator: VerificationMethod,\n  options: JWTVerifyOptions\n): Promise<VerificationMethod> {\n  if (authenticator.type === CONDITIONAL_PROOF_2022) {\n    return verifyConditionalProof(jwt, { payload, header, signature, data }, authenticator, options)\n  } else {\n    return verifyJWTDecoded({ header, payload, data, signature }, [authenticator])\n  }\n}\n\nexport async function verifyConditionalProof(\n  jwt: string,\n  { header, payload, signature, data }: JWTDecoded,\n  authenticator: VerificationMethod,\n  options: JWTVerifyOptions\n): Promise<VerificationMethod> {\n  // Validate the condition according to its condition property\n  if (authenticator.conditionWeightedThreshold) {\n    return verifyConditionWeightedThreshold(jwt, { header, payload, data, signature }, authenticator, options)\n  } else if (authenticator.conditionDelegated) {\n    return verifyConditionDelegated(jwt, { header, payload, data, signature }, authenticator, options)\n  }\n  // TODO other conditions\n\n  throw new Error(\n    `${JWT_ERROR.INVALID_JWT}: conditional proof type did not find condition for authenticator ${authenticator.id}.`\n  )\n}\n\nasync function verifyConditionWeightedThreshold(\n  jwt: string,\n  { header, payload, data, signature }: JWTDecoded,\n  authenticator: VerificationMethod,\n  options: JWTVerifyOptions\n): Promise<VerificationMethod> {\n  if (!authenticator.conditionWeightedThreshold || !authenticator.threshold) {\n    throw new Error('Expected conditionWeightedThreshold and threshold')\n  }\n\n  const issuers: string[] = []\n  const threshold = authenticator.threshold\n  let weightCount = 0\n\n  for (const weightedCondition of authenticator.conditionWeightedThreshold) {\n    const currentCondition = weightedCondition.condition\n    let foundSigner: VerificationMethod | undefined\n\n    try {\n      if (currentCondition.type === CONDITIONAL_PROOF_2022) {\n        if (!options.didAuthenticator) {\n          throw new Error('Expected didAuthenticator')\n        }\n\n        const newOptions: JWTVerifyOptions = {\n          ...options,\n          didAuthenticator: {\n            didResolutionResult: options.didAuthenticator?.didResolutionResult,\n            authenticators: [currentCondition],\n            issuer: currentCondition.id,\n          },\n        }\n        const { verified } = await verifyJWT(jwt, newOptions)\n        if (verified) {\n          foundSigner = currentCondition\n        }\n      } else {\n        foundSigner = await verifyJWTDecoded({ header, payload, data, signature }, currentCondition)\n      }\n    } catch (e) {\n      if (!(e as Error).message.startsWith(JWT_ERROR.INVALID_SIGNATURE)) throw e\n    }\n\n    if (foundSigner && !issuers.includes(foundSigner.id)) {\n      issuers.push(foundSigner.id)\n      weightCount += weightedCondition.weight\n\n      if (weightCount >= threshold) {\n        return authenticator\n      }\n    }\n  }\n  throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: condition for authenticator ${authenticator.id} is not met.`)\n}\n\nasync function verifyConditionDelegated(\n  jwt: string,\n  { header, payload, data, signature }: JWTDecoded,\n  authenticator: VerificationMethod,\n  options: JWTVerifyOptions\n): Promise<VerificationMethod> {\n  if (!authenticator.conditionDelegated) {\n    throw new Error('Expected conditionDelegated')\n  }\n  if (!options.resolver) {\n    throw new Error('Expected resolver')\n  }\n\n  let foundSigner: VerificationMethod | undefined\n\n  const issuer = authenticator.conditionDelegated\n  const didAuthenticator = await resolveAuthenticator(options.resolver, header.alg, issuer, options.proofPurpose)\n  const didResolutionResult = didAuthenticator.didResolutionResult\n\n  if (!didResolutionResult?.didDocument) {\n    throw new Error(`${JWT_ERROR.RESOLVER_ERROR}: Could not resolve delegated DID ${issuer}.`)\n  }\n\n  const delegatedAuthenticator = didAuthenticator.authenticators.find((authenticator) => authenticator.id === issuer)\n  if (!delegatedAuthenticator) {\n    throw new Error(\n      `${JWT_ERROR.NO_SUITABLE_KEYS}: Could not find delegated authenticator ${issuer} in it's DID Document`\n    )\n  }\n\n  if (delegatedAuthenticator.type === CONDITIONAL_PROOF_2022) {\n    const { verified } = await verifyJWT(jwt, {\n      ...options,\n      ...{\n        didAuthenticator: {\n          didResolutionResult,\n          authenticators: [delegatedAuthenticator],\n          issuer: delegatedAuthenticator.id,\n        },\n      },\n    })\n    if (verified) {\n      foundSigner = delegatedAuthenticator\n    }\n  } else {\n    try {\n      foundSigner = verifyJWTDecoded({ header, payload, data, signature }, delegatedAuthenticator)\n    } catch (e) {\n      if (!(e as Error).message.startsWith('invalid_signature:')) throw e\n    }\n  }\n\n  if (foundSigner) {\n    return authenticator\n  }\n\n  throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: condition for authenticator ${authenticator.id} is not met.`)\n}\n","import canonicalizeData from 'canonicalize'\nimport { DIDDocument, DIDResolutionResult, parse, ParsedDID, Resolvable, VerificationMethod } from 'did-resolver'\nimport SignerAlg from './SignerAlgorithm.js'\nimport { decodeBase64url, EcdsaSignature, encodeBase64url, KNOWN_JWA, SUPPORTED_PUBLIC_KEY_TYPES } from './util.js'\nimport VerifierAlgorithm from './VerifierAlgorithm.js'\nimport { JWT_ERROR } from './Errors.js'\nimport { verifyProof } from './ConditionalAlgorithm.js'\n\nexport type Signer = (data: string | Uint8Array) => Promise<EcdsaSignature | string>\nexport type SignerAlgorithm = (payload: string, signer: Signer) => Promise<string>\n\nexport type ProofPurposeTypes =\n  | 'assertionMethod'\n  | 'authentication'\n  // | 'keyAgreement' // keyAgreement VerificationMethod should not be used for signing\n  | 'capabilityDelegation'\n  | 'capabilityInvocation'\n\nexport interface JWTOptions {\n  issuer: string\n  signer: Signer\n  /**\n   * @deprecated Please use `header.alg` to specify the JWT algorithm.\n   */\n  alg?: string\n  expiresIn?: number\n  canonicalize?: boolean\n}\n\nexport interface JWTVerifyOptions {\n  /** @deprecated Please use `proofPurpose: 'authentication' instead` */\n  auth?: boolean\n  audience?: string\n  callbackUrl?: string\n  resolver?: Resolvable\n  skewTime?: number\n  /** See https://www.w3.org/TR/did-spec-registries/#verification-relationships */\n  proofPurpose?: ProofPurposeTypes\n  policies?: JWTVerifyPolicies\n  didAuthenticator?: DIDAuthenticator\n}\n\n/**\n * Overrides the different types of checks performed on the JWT besides the signature check\n */\nexport interface JWTVerifyPolicies {\n  // overrides the timestamp against which the validity interval is checked\n  now?: number\n  // when set to false, the timestamp checks ignore the Not Before(`nbf`) property\n  nbf?: boolean\n  // when set to false, the timestamp checks ignore the Issued At(`iat`) property\n  iat?: boolean\n  // when set to false, the timestamp checks ignore the Expires At(`exp`) property\n  exp?: boolean\n  // when set to false, the JWT audience check is skipped\n  aud?: boolean\n}\n\nexport interface JWSCreationOptions {\n  canonicalize?: boolean\n}\n\nexport interface DIDAuthenticator {\n  authenticators: VerificationMethod[]\n  issuer: string\n  didResolutionResult: DIDResolutionResult\n}\n\nexport interface JWTHeader {\n  typ: 'JWT'\n  alg: string\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [x: string]: any\n}\n\nexport interface JWTPayload {\n  iss?: string\n  sub?: string\n  aud?: string | string[]\n  iat?: number\n  nbf?: number\n  exp?: number\n  rexp?: number\n\n  // eslint-disable-next-line @typescript-eslint/no-explicit-any\n  [x: string]: any\n}\n\nexport interface JWTDecoded {\n  header: JWTHeader\n  payload: JWTPayload\n  signature: string\n  data: string\n}\n\nexport interface JWSDecoded {\n  header: JWTHeader\n  payload: string\n  signature: string\n  data: string\n}\n\n/**\n * Result object returned by {@link verifyJWT}\n */\nexport interface JWTVerified {\n  /**\n   * Set to true for a JWT that passes all the required checks minus any verification overrides.\n   */\n  verified: true\n\n  /**\n   * The decoded JWT payload\n   */\n  payload: Partial<JWTPayload>\n\n  /**\n   * The result of resolving the issuer DID\n   */\n  didResolutionResult: DIDResolutionResult\n\n  /**\n   * the issuer DID\n   */\n  issuer: string\n\n  /**\n   * The public key of the issuer that matches the JWT signature\n   */\n  signer: VerificationMethod\n\n  /**\n   * The original JWT that was verified\n   */\n  jwt: string\n\n  /**\n   * Any overrides that were used during verification\n   */\n  policies?: JWTVerifyPolicies\n}\n\nexport const SELF_ISSUED_V2 = 'https://self-issued.me/v2'\nexport const SELF_ISSUED_V2_VC_INTEROP = 'https://self-issued.me/v2/openid-vc' // https://identity.foundation/jwt-vc-presentation-profile/#id-token-validation\nexport const SELF_ISSUED_V0_1 = 'https://self-issued.me'\n\ntype LegacyVerificationMethod = { publicKey?: string }\n\nconst defaultAlg: KNOWN_JWA = 'ES256K'\nconst DID_JSON = 'application/did+json'\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction encodeSection(data: any, shouldCanonicalize = false): string {\n  if (shouldCanonicalize) {\n    return encodeBase64url(<string>canonicalizeData(data))\n  } else {\n    return encodeBase64url(JSON.stringify(data))\n  }\n}\n\nexport const NBF_SKEW = 300\n\nfunction decodeJWS(jws: string): JWSDecoded {\n  const parts = jws.match(/^([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)\\.([a-zA-Z0-9_-]+)$/)\n  if (parts) {\n    return {\n      header: JSON.parse(decodeBase64url(parts[1])),\n      payload: parts[2],\n      signature: parts[3],\n      data: `${parts[1]}.${parts[2]}`,\n    }\n  }\n  throw new Error('invalid_argument: Incorrect format JWS')\n}\n\n/**\n *  Decodes a JWT and returns an object representing the payload\n *\n *  @example\n *  decodeJWT('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJpYXQiOjE1...')\n *\n *  @param    {String}            jwt                a JSON Web Token to verify\n * @param    {Object}            [recurse]          whether to recurse into the payload to decode any nested JWTs\n *  @return   {Object}                               a JS object representing the decoded JWT\n */\nexport function decodeJWT(jwt: string, recurse = true): JWTDecoded {\n  if (!jwt) throw new Error('invalid_argument: no JWT passed into decodeJWT')\n  try {\n    const jws = decodeJWS(jwt)\n    const decodedJwt: JWTDecoded = Object.assign(jws, { payload: JSON.parse(decodeBase64url(jws.payload)) })\n    const iss = decodedJwt.payload.iss\n\n    if (decodedJwt.header.cty === 'JWT' && recurse) {\n      const innerDecodedJwt = decodeJWT(decodedJwt.payload.jwt)\n\n      if (innerDecodedJwt.payload.iss !== iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n      return innerDecodedJwt\n    }\n    return decodedJwt\n  } catch (e) {\n    throw new Error(`invalid_argument: ${JWT_ERROR.INVALID_JWT}: ${e}`)\n  }\n}\n\n/**\n *  Creates a signed JWS given a payload, a signer, and an optional header.\n *\n *  @example\n *  const signer = ES256KSigner(process.env.PRIVATE_KEY)\n *  const jws = await createJWS({ my: 'payload' }, signer)\n *\n *  @param    {Object}            payload           payload object\n *  @param    {Signer}            signer            a signer, see `ES256KSigner or `EdDSASigner`\n *  @param    {Object}            header            optional object to specify or customize the JWS header\n *  @param    {Object}            options           can be used to trigger automatic canonicalization of header and\n *                                                    payload properties\n *  @return   {Promise<string>}                     a Promise which resolves to a JWS string or rejects with an error\n */\nexport async function createJWS(\n  payload: string | Partial<JWTPayload>,\n  signer: Signer,\n  header: Partial<JWTHeader> = {},\n  options: JWSCreationOptions = {}\n): Promise<string> {\n  if (!header.alg) header.alg = defaultAlg\n  const encodedPayload = typeof payload === 'string' ? payload : encodeSection(payload, options.canonicalize)\n  const signingInput: string = [encodeSection(header, options.canonicalize), encodedPayload].join('.')\n\n  const jwtSigner: SignerAlgorithm = SignerAlg(header.alg)\n  const signature: string = await jwtSigner(signingInput, signer)\n\n  // JWS Compact Serialization\n  // https://www.rfc-editor.org/rfc/rfc7515#section-7.1\n  return [signingInput, signature].join('.')\n}\n\n/**\n *  Creates a signed JWT given an address which becomes the issuer, a signer, and a payload for which the signature is\n * over.\n *\n *  @example\n *  const signer = ES256KSigner(process.env.PRIVATE_KEY)\n *  createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n *      ...\n *  })\n *\n *  @param    {Object}            payload               payload object\n *  @param    {Object}            [options]             an unsigned credential object\n *  @param    {String}            options.issuer        The DID of the issuer (signer) of JWT\n *  @param    {String}            options.alg           [DEPRECATED] The JWT signing algorithm to use. Supports:\n *   [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n *  @param    {Signer}            options.signer        a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n *  @param    {boolean}           options.canonicalize  optional flag to canonicalize header and payload before signing\n *  @param    {Object}            header                optional object to specify or customize the JWT header\n *  @return   {Promise<Object, Error>}                  a promise which resolves with a signed JSON Web Token or\n *   rejects with an error\n */\nexport async function createJWT(\n  payload: Partial<JWTPayload>,\n  { issuer, signer, alg, expiresIn, canonicalize }: JWTOptions,\n  header: Partial<JWTHeader> = {}\n): Promise<string> {\n  if (!signer) throw new Error('missing_signer: No Signer functionality has been configured')\n  if (!issuer) throw new Error('missing_issuer: No issuing DID has been configured')\n  if (!header.typ) header.typ = 'JWT'\n  if (!header.alg) header.alg = alg\n  const timestamps: Partial<JWTPayload> = {\n    iat: Math.floor(Date.now() / 1000),\n    exp: undefined,\n  }\n  if (expiresIn) {\n    if (typeof expiresIn === 'number') {\n      timestamps.exp = <number>(payload.nbf || timestamps.iat) + Math.floor(expiresIn)\n    } else {\n      throw new Error('invalid_argument: JWT expiresIn is not a number')\n    }\n  }\n  const fullPayload = { ...timestamps, ...payload, iss: issuer }\n  return createJWS(fullPayload, signer, header, { canonicalize })\n}\n\n/**\n *  Creates a multi-signature signed JWT given multiple issuers and their corresponding signers, and a payload for\n * which the signature is over.\n *\n *  @example\n *  const signer = ES256KSigner(process.env.PRIVATE_KEY)\n *  createJWT({address: '5A8bRWU3F7j3REx3vkJ...', signer}, {key1: 'value', key2: ..., ... }).then(jwt => {\n *      ...\n *  })\n *\n *  @param    {Object}            payload               payload object\n *  @param    {Object}            [options]             an unsigned credential object\n *  @param    {boolean}           options.expiresIn     optional flag to denote the expiration time\n *  @param    {boolean}           options.canonicalize  optional flag to canonicalize header and payload before signing\n *  @param    {Object[]}          issuers               array of the issuers, their signers and algorithms\n *  @param    {string}            issuers[].issuer      The DID of the issuer (signer) of JWT\n *  @param    {Signer}            issuers[].signer      a `Signer` function, Please see `ES256KSigner` or `EdDSASigner`\n *  @param    {String}            issuers[].alg         [DEPRECATED] The JWT signing algorithm to use. Supports:\n *   [ES256K, ES256K-R, Ed25519, EdDSA], Defaults to: ES256K. Please use `header.alg` to specify the algorithm\n *  @return   {Promise<Object, Error>}                  a promise which resolves with a signed JSON Web Token or\n *   rejects with an error\n */\nexport async function createMultisignatureJWT(\n  payload: Partial<JWTPayload>,\n  { expiresIn, canonicalize }: Partial<JWTOptions>,\n  issuers: { issuer: string; signer: Signer; alg: string }[]\n): Promise<string> {\n  if (issuers.length === 0) throw new Error('invalid_argument: must provide one or more issuers')\n\n  let payloadResult: Partial<JWTPayload> = payload\n\n  let jwt = ''\n  for (let i = 0; i < issuers.length; i++) {\n    const issuer = issuers[i]\n\n    const header: Partial<JWTHeader> = {\n      typ: 'JWT',\n      alg: issuer.alg,\n    }\n\n    // Create nested JWT\n    // See Point 5 of https://www.rfc-editor.org/rfc/rfc7519#section-7.1\n    // After the first JWT is created (the first JWS), the next JWT is created by inputting the previous JWT as the\n    // payload\n    if (i !== 0) {\n      header.cty = 'JWT'\n    }\n\n    jwt = await createJWT(payloadResult, { ...issuer, canonicalize, expiresIn }, header)\n\n    payloadResult = { jwt }\n  }\n  return jwt\n}\n\nexport function verifyJWTDecoded(\n  { header, payload, data, signature }: JWTDecoded,\n  pubKeys: VerificationMethod | VerificationMethod[]\n): VerificationMethod {\n  if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n\n  const iss = payload.iss\n  let recurse = true\n  do {\n    if (iss !== payload.iss) throw new Error(`${JWT_ERROR.INVALID_JWT}: multiple issuers`)\n\n    try {\n      const result = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n\n      return result\n    } catch (e) {\n      if (!(e as Error).message.startsWith(JWT_ERROR.INVALID_SIGNATURE)) throw e\n    }\n\n    // TODO probably best to create copy objects than replace reference objects\n    if (header.cty !== 'JWT') {\n      recurse = false\n    } else {\n      ;({ payload, header, signature, data } = decodeJWT(payload.jwt, false))\n    }\n  } while (recurse)\n\n  throw new Error(`${JWT_ERROR.INVALID_SIGNATURE}: no matching public key found`)\n}\n\nexport function verifyJWSDecoded(\n  { header, data, signature }: JWSDecoded,\n  pubKeys: VerificationMethod | VerificationMethod[]\n): VerificationMethod {\n  if (!Array.isArray(pubKeys)) pubKeys = [pubKeys]\n  const signer: VerificationMethod = VerifierAlgorithm(header.alg)(data, signature, pubKeys)\n  return signer\n}\n\n/**\n *  Verifies given JWS. If the JWS is valid, returns the public key that was\n *  used to sign the JWS, or throws an `Error` if none of the `pubKeys` match.\n *\n *  @example\n *  const pubKey = verifyJWS('eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....', { publicKeyHex: '0x12341...' })\n *\n *  @param    {String}                          jws         A JWS string to verify\n *  @param    {Array<VerificationMethod> | VerificationMethod}    pubKeys     The public keys used to verify the JWS\n *  @return   {VerificationMethod}                       The public key used to sign the JWS\n */\nexport function verifyJWS(jws: string, pubKeys: VerificationMethod | VerificationMethod[]): VerificationMethod {\n  const jwsDecoded: JWSDecoded = decodeJWS(jws)\n  return verifyJWSDecoded(jwsDecoded, pubKeys)\n}\n\n/**\n *  Verifies given JWT. If the JWT is valid, the promise returns an object including the JWT, the payload of the JWT,\n *  and the DID document of the issuer of the JWT.\n *\n *  @example\n *  ```ts\n *  verifyJWT(\n *      'did:uport:eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NksifQ.eyJyZXF1Z....',\n *      {audience: '5A8bRWU3F7j3REx3vkJ...', callbackUrl: 'https://...'}\n *    ).then(obj => {\n *        const did = obj.did // DID of signer\n *        const payload = obj.payload\n *        const doc = obj.didResolutionResult.didDocument // DID Document of issuer\n *        const jwt = obj.jwt\n *        const signerKeyId = obj.signer.id // ID of key in DID document that signed JWT\n *        ...\n *    })\n *  ```\n *\n *  @param    {String}            jwt                a JSON Web Token to verify\n *  @param    {Object}            [options]           an unsigned credential object\n *  @param    {Boolean}           options.auth        Require signer to be listed in the authentication section of the\n *   DID document (for Authentication purposes)\n *  @param    {String}            options.audience    DID of the recipient of the JWT\n *  @param    {String}            options.callbackUrl callback url in JWT\n *  @return   {Promise<Object, Error>}               a promise which resolves with a response object or rejects with an\n *   error\n */\nexport async function verifyJWT(\n  jwt: string,\n  options: JWTVerifyOptions = {\n    resolver: undefined,\n    auth: undefined,\n    audience: undefined,\n    callbackUrl: undefined,\n    skewTime: undefined,\n    proofPurpose: undefined,\n    policies: {},\n    didAuthenticator: undefined,\n  }\n): Promise<JWTVerified> {\n  if (!options.resolver) throw new Error('missing_resolver: No DID resolver has been configured')\n  const { payload, header, signature, data }: JWTDecoded = decodeJWT(jwt, false)\n  const proofPurpose: ProofPurposeTypes | undefined = Object.prototype.hasOwnProperty.call(options, 'auth')\n    ? options.auth\n      ? 'authentication'\n      : undefined\n    : options.proofPurpose\n\n  let didUrl: string | undefined\n\n  if (!payload.iss && !payload.client_id) {\n    throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT iss or client_id are required`)\n  }\n\n  if (options.didAuthenticator) {\n    didUrl = options.didAuthenticator.issuer\n  } else if (payload.iss === SELF_ISSUED_V2 || payload.iss === SELF_ISSUED_V2_VC_INTEROP) {\n    if (!payload.sub) {\n      throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT sub is required`)\n    }\n    if (typeof payload.sub_jwk === 'undefined') {\n      didUrl = payload.sub\n    } else {\n      didUrl = (header.kid || '').split('#')[0]\n    }\n  } else if (payload.iss === SELF_ISSUED_V0_1) {\n    if (!payload.did) {\n      throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT did is required`)\n    }\n    didUrl = payload.did\n  } else if (!payload.iss && payload.scope === 'openid' && payload.redirect_uri) {\n    // SIOP Request payload\n    // https://identity.foundation/jwt-vc-presentation-profile/#self-issued-op-request-object\n    if (!payload.client_id) {\n      throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT client_id is required`)\n    }\n    didUrl = payload.client_id\n  } else {\n    didUrl = payload.iss\n  }\n\n  if (!didUrl) {\n    throw new Error(`${JWT_ERROR.INVALID_JWT}: No DID has been found in the JWT`)\n  }\n\n  let authenticators: VerificationMethod[]\n  let issuer: string\n  let didResolutionResult: DIDResolutionResult\n  if (options.didAuthenticator) {\n    ;({ didResolutionResult, authenticators, issuer } = options.didAuthenticator)\n  } else {\n    ;({ didResolutionResult, authenticators, issuer } = await resolveAuthenticator(\n      options.resolver,\n      header.alg,\n      didUrl,\n      proofPurpose\n    ))\n    // Add to options object for recursive reference\n    options.didAuthenticator = { didResolutionResult, authenticators, issuer }\n  }\n\n  const { did } = parse(didUrl) as ParsedDID\n\n  let signer: VerificationMethod | null = null\n\n  if (did !== didUrl) {\n    const authenticator = authenticators.find((auth) => auth.id === didUrl)\n    if (!authenticator) {\n      throw new Error(`${JWT_ERROR.INVALID_JWT}: No authenticator found for did URL ${didUrl}`)\n    }\n\n    signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n  } else {\n    let i = 0\n    while (!signer && i < authenticators.length) {\n      const authenticator = authenticators[i]\n      try {\n        signer = await verifyProof(jwt, { payload, header, signature, data }, authenticator, options)\n      } catch (e) {\n        if (!(e as Error).message.includes(JWT_ERROR.INVALID_SIGNATURE) || i === authenticators.length - 1) throw e\n      }\n\n      i++\n    }\n  }\n\n  if (signer) {\n    const now: number = typeof options.policies?.now === 'number' ? options.policies.now : Math.floor(Date.now() / 1000)\n    const skewTime = typeof options.skewTime !== 'undefined' && options.skewTime >= 0 ? options.skewTime : NBF_SKEW\n\n    const nowSkewed = now + skewTime\n    if (options.policies?.nbf !== false && payload.nbf) {\n      if (payload.nbf > nowSkewed) {\n        throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid before nbf: ${payload.nbf}`)\n      }\n    } else if (options.policies?.iat !== false && payload.iat && payload.iat > nowSkewed) {\n      throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT not valid yet (issued in the future) iat: ${payload.iat}`)\n    }\n    if (options.policies?.exp !== false && payload.exp && payload.exp <= now - skewTime) {\n      throw new Error(`${JWT_ERROR.INVALID_JWT}: JWT has expired: exp: ${payload.exp} < now: ${now}`)\n    }\n    if (options.policies?.aud !== false && payload.aud) {\n      if (!options.audience && !options.callbackUrl) {\n        throw new Error(\n          `${JWT_ERROR.INVALID_AUDIENCE}: JWT audience is required but your app address has not been configured`\n        )\n      }\n      const audArray = Array.isArray(payload.aud) ? payload.aud : [payload.aud]\n      const matchedAudience = audArray.find((item) => options.audience === item || options.callbackUrl === item)\n\n      if (typeof matchedAudience === 'undefined') {\n        throw new Error(`${JWT_ERROR.INVALID_AUDIENCE}: JWT audience does not match your DID or callback url`)\n      }\n    }\n\n    return { verified: true, payload, didResolutionResult, issuer, signer, jwt, policies: options.policies }\n  }\n  throw new Error(\n    `${JWT_ERROR.INVALID_SIGNATURE}: JWT not valid. issuer DID document does not contain a verificationMethod that matches the signature.`\n  )\n}\n\n/**\n * Resolves relevant public keys or other authenticating material used to verify signature from the DID document of\n * provided DID\n *\n *  @example\n *  ```ts\n *  resolveAuthenticator(resolver, 'ES256K', 'did:uport:2nQtiQG6Cgm1GYTBaaKAgr76uY7iSexUkqX').then(obj => {\n *      const payload = obj.payload\n *      const profile = obj.profile\n *      const jwt = obj.jwt\n *      // ...\n *  })\n *  ```\n *\n *  @param resolver - {Resolvable} a DID resolver function that can obtain the `DIDDocument` for the `issuer`\n *  @param alg - {String} a JWT algorithm\n *  @param issuer - {String} a Decentralized Identifier (DID) to lookup\n *  @param proofPurpose - {ProofPurposeTypes} *Optional* Use the verificationMethod linked in that section of the\n *   issuer DID document\n *  @return {Promise<DIDAuthenticator>} a promise which resolves with an object containing an array of authenticators\n *   or rejects with an error if none exist\n */\nexport async function resolveAuthenticator(\n  resolver: Resolvable,\n  alg: string,\n  issuer: string,\n  proofPurpose?: ProofPurposeTypes\n): Promise<DIDAuthenticator> {\n  const types: string[] = SUPPORTED_PUBLIC_KEY_TYPES[alg as KNOWN_JWA]\n  if (!types || types.length === 0) {\n    throw new Error(`${JWT_ERROR.NOT_SUPPORTED}: No supported signature types for algorithm ${alg}`)\n  }\n  let didResult: DIDResolutionResult\n\n  const result = (await resolver.resolve(issuer, { accept: DID_JSON })) as unknown\n  // support legacy resolvers that do not produce DIDResolutionResult\n  if (Object.getOwnPropertyNames(result).indexOf('didDocument') === -1) {\n    didResult = {\n      didDocument: result as DIDDocument,\n      didDocumentMetadata: {},\n      didResolutionMetadata: { contentType: DID_JSON },\n    }\n  } else {\n    didResult = result as DIDResolutionResult\n  }\n\n  if (didResult.didResolutionMetadata?.error || didResult.didDocument == null) {\n    const { error, message } = didResult.didResolutionMetadata\n    throw new Error(\n      `${JWT_ERROR.RESOLVER_ERROR}: Unable to resolve DID document for ${issuer}: ${error}, ${message || ''}`\n    )\n  }\n\n  const getPublicKeyById = (verificationMethods: VerificationMethod[], pubid?: string): VerificationMethod | null => {\n    const filtered = verificationMethods.filter(({ id }) => pubid === id)\n    return filtered.length > 0 ? filtered[0] : null\n  }\n\n  let publicKeysToCheck: VerificationMethod[] = [\n    ...(didResult?.didDocument?.verificationMethod || []),\n    ...(didResult?.didDocument?.publicKey || []),\n  ]\n  if (typeof proofPurpose === 'string') {\n    // support legacy DID Documents that do not list assertionMethod\n    if (\n      proofPurpose.startsWith('assertion') &&\n      !Object.getOwnPropertyNames(didResult?.didDocument).includes('assertionMethod')\n    ) {\n      didResult.didDocument = { ...(<DIDDocument>didResult.didDocument) }\n      didResult.didDocument.assertionMethod = [...publicKeysToCheck.map((pk) => pk.id)]\n    }\n\n    publicKeysToCheck = (didResult.didDocument[proofPurpose] || [])\n      .map((verificationMethod) => {\n        if (typeof verificationMethod === 'string') {\n          return getPublicKeyById(publicKeysToCheck, verificationMethod)\n        } else if (typeof (<LegacyVerificationMethod>verificationMethod).publicKey === 'string') {\n          // this is a legacy format\n          return getPublicKeyById(publicKeysToCheck, (<LegacyVerificationMethod>verificationMethod).publicKey)\n        } else {\n          return <VerificationMethod>verificationMethod\n        }\n      })\n      .filter((key) => key != null) as VerificationMethod[]\n  }\n\n  const authenticators: VerificationMethod[] = publicKeysToCheck.filter(({ type }) =>\n    types.find((supported) => supported === type)\n  )\n\n  if (typeof proofPurpose === 'string' && (!authenticators || authenticators.length === 0)) {\n    throw new Error(\n      `${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys suitable for ${alg} with ${proofPurpose} purpose`\n    )\n  }\n  if (!authenticators || authenticators.length === 0) {\n    throw new Error(`${JWT_ERROR.NO_SUITABLE_KEYS}: DID document for ${issuer} does not have public keys for ${alg}`)\n  }\n  return { authenticators, issuer, didResolutionResult: didResult }\n}\n","import { base64ToBytes, bytesToBase64url, decodeBase64url, stringToBytes, toSealed } from '../util.js'\nimport type { Decrypter, Encrypter, EncryptionResult, EphemeralKeyPair, JWE, ProtectedHeader } from './types.js'\n\nfunction validateJWE(jwe: JWE) {\n  if (!(jwe.protected && jwe.iv && jwe.ciphertext && jwe.tag)) {\n    throw new Error('bad_jwe: missing properties')\n  }\n  if (jwe.recipients) {\n    jwe.recipients.map((rec) => {\n      if (!(rec.header && rec.encrypted_key)) {\n        throw new Error('bad_jwe: malformed recipients')\n      }\n    })\n  }\n}\n\nfunction encodeJWE({ ciphertext, tag, iv, protectedHeader, recipient }: EncryptionResult, aad?: Uint8Array): JWE {\n  const jwe: JWE = {\n    protected: <string>protectedHeader,\n    iv: bytesToBase64url(iv ?? new Uint8Array(0)),\n    ciphertext: bytesToBase64url(ciphertext),\n    tag: bytesToBase64url(tag ?? new Uint8Array(0)),\n  }\n  if (aad) jwe.aad = bytesToBase64url(aad)\n  if (recipient) jwe.recipients = [recipient]\n  return jwe\n}\n\nexport async function createJWE(\n  cleartext: Uint8Array,\n  encrypters: Encrypter[],\n  protectedHeader: ProtectedHeader = {},\n  aad?: Uint8Array,\n  useSingleEphemeralKey = false\n): Promise<JWE> {\n  if (encrypters[0].alg === 'dir') {\n    if (encrypters.length > 1) throw new Error('not_supported: Can only do \"dir\" encryption to one key.')\n    const encryptionResult = await encrypters[0].encrypt(cleartext, protectedHeader, aad)\n    return encodeJWE(encryptionResult, aad)\n  } else {\n    const tmpEnc = encrypters[0].enc\n    if (!encrypters.reduce((acc, encrypter) => acc && encrypter.enc === tmpEnc, true)) {\n      throw new Error('invalid_argument: Incompatible encrypters passed')\n    }\n    let cek: Uint8Array | undefined\n    let jwe: JWE | undefined\n    let epk: EphemeralKeyPair | undefined\n    if (useSingleEphemeralKey) {\n      epk = encrypters[0].genEpk?.()\n      const alg = encrypters[0].alg\n      protectedHeader = { ...protectedHeader, alg, epk: epk?.publicKeyJWK }\n    }\n\n    for (const encrypter of encrypters) {\n      if (!cek) {\n        const encryptionResult = await encrypter.encrypt(cleartext, protectedHeader, aad, epk)\n        cek = encryptionResult.cek\n        jwe = encodeJWE(encryptionResult, aad)\n      } else {\n        const recipient = await encrypter.encryptCek?.(cek, epk)\n        if (recipient) {\n          jwe?.recipients?.push(recipient)\n        }\n      }\n    }\n    return <JWE>jwe\n  }\n}\n\nexport async function decryptJWE(jwe: JWE, decrypter: Decrypter): Promise<Uint8Array> {\n  validateJWE(jwe)\n  const protHeader = JSON.parse(decodeBase64url(jwe.protected))\n  if (protHeader.enc !== decrypter.enc)\n    throw new Error(`not_supported: Decrypter does not supported: '${protHeader.enc}'`)\n  const sealed = toSealed(jwe.ciphertext, jwe.tag)\n  const aad = stringToBytes(jwe.aad ? `${jwe.protected}.${jwe.aad}` : jwe.protected)\n  let cleartext = null\n  if (protHeader.alg === 'dir' && decrypter.alg === 'dir') {\n    cleartext = await decrypter.decrypt(sealed, base64ToBytes(jwe.iv), aad)\n  } else if (!jwe.recipients || jwe.recipients.length === 0) {\n    throw new Error('bad_jwe: missing recipients')\n  } else {\n    for (let i = 0; !cleartext && i < jwe.recipients.length; i++) {\n      const recipient = jwe.recipients[i]\n      Object.assign(recipient.header, protHeader)\n      if (recipient.header.alg === decrypter.alg) {\n        cleartext = await decrypter.decrypt(sealed, base64ToBytes(jwe.iv), aad, recipient)\n      }\n    }\n  }\n  if (cleartext === null) throw new Error('failure: Failed to decrypt')\n  return cleartext\n}\n","import type { Decrypter, Encrypter, EncryptionResult, ProtectedHeader } from './types.js'\nimport { bytesToBase64url, encodeBase64url, stringToBytes } from '../util.js'\nimport { xchacha20poly1305 } from '@noble/ciphers/chacha'\nimport { randomBytes } from '@noble/hashes/utils'\n\nexport function xc20pEncrypter(key: Uint8Array): (cleartext: Uint8Array, aad?: Uint8Array) => EncryptionResult {\n  return (cleartext: Uint8Array, aad?: Uint8Array) => {\n    const iv = randomBytes(24)\n    const cipher = xchacha20poly1305(key, iv, aad)\n    const sealed = cipher.encrypt(cleartext)\n    return {\n      ciphertext: sealed.subarray(0, sealed.length - 16),\n      tag: sealed.subarray(sealed.length - 16),\n      iv,\n    }\n  }\n}\n\nexport function xc20pDirEncrypter(key: Uint8Array): Encrypter {\n  const xc20pEncrypt = xc20pEncrypter(key)\n  const enc = 'XC20P'\n  const alg = 'dir'\n\n  async function encrypt(\n    cleartext: Uint8Array,\n    protectedHeader: ProtectedHeader = {},\n    aad?: Uint8Array\n  ): Promise<EncryptionResult> {\n    const protHeader = encodeBase64url(JSON.stringify(Object.assign({ alg }, protectedHeader, { enc })))\n    const encodedAad = stringToBytes(aad ? `${protHeader}.${bytesToBase64url(aad)}` : protHeader)\n    return {\n      ...xc20pEncrypt(cleartext, encodedAad),\n      protectedHeader: protHeader,\n    }\n  }\n\n  return { alg, enc, encrypt }\n}\n\nexport function xc20pDirDecrypter(key: Uint8Array): Decrypter {\n  async function decrypt(sealed: Uint8Array, iv: Uint8Array, aad?: Uint8Array): Promise<Uint8Array | null> {\n    try {\n      return xchacha20poly1305(key, iv, aad).decrypt(sealed)\n    } catch (error) {\n      return null\n    }\n  }\n\n  return { alg: 'dir', enc: 'XC20P', decrypt }\n}\n","import type { ECDH, EphemeralKeyPair, Recipient } from './types.js'\nimport { base64ToBytes, bytesToBase64url, generateKeyPair, generateKeyPairFromSeed } from '../util.js'\nimport { concatKDF } from '../Digest.js'\nimport { x25519 } from '@noble/curves/ed25519'\n\nexport async function computeX25519EcdhEsKek(recipient: Recipient, receiverSecret: Uint8Array | ECDH, alg: string) {\n  const crv = 'X25519'\n  const keyLen = 256\n  const header = recipient.header\n  if (header.epk?.crv !== crv || typeof header.epk.x == 'undefined') return null\n  const publicKey = base64ToBytes(header.epk.x)\n  let sharedSecret\n  if (receiverSecret instanceof Uint8Array) {\n    sharedSecret = x25519.getSharedSecret(receiverSecret, publicKey)\n  } else {\n    sharedSecret = await receiverSecret(publicKey)\n  }\n\n  // Key Encryption Key\n  let producerInfo: Uint8Array | undefined = undefined\n  let consumerInfo: Uint8Array | undefined = undefined\n  if (recipient.header.apu) producerInfo = base64ToBytes(recipient.header.apu)\n  if (recipient.header.apv) consumerInfo = base64ToBytes(recipient.header.apv)\n  return concatKDF(sharedSecret, keyLen, alg, producerInfo, consumerInfo)\n}\n\nexport async function createX25519EcdhEsKek(\n  recipientPublicKey: Uint8Array,\n  senderSecret: Uint8Array | ECDH | undefined, // unused\n  alg: string,\n  apu: string | undefined, // unused\n  apv: string | undefined,\n  ephemeralKeyPair: EphemeralKeyPair | undefined\n) {\n  const crv = 'X25519'\n  const keyLen = 256\n  const ephemeral = ephemeralKeyPair ? generateKeyPairFromSeed(ephemeralKeyPair.secretKey) : generateKeyPair()\n  const epk = { kty: 'OKP', crv, x: bytesToBase64url(ephemeral.publicKey) }\n  const sharedSecret = x25519.getSharedSecret(ephemeral.secretKey, recipientPublicKey)\n  // Key Encryption Key\n  const consumerInfo = base64ToBytes(apv ?? '')\n  const kek = concatKDF(sharedSecret, keyLen, alg, undefined, consumerInfo)\n  return { epk, kek }\n}\n","import type { ECDH, EphemeralKeyPair, Recipient } from './types.js'\nimport { base64ToBytes, bytesToBase64url, generateKeyPair, generateKeyPairFromSeed } from '../util.js'\nimport { concatKDF } from '../Digest.js'\nimport { x25519 } from '@noble/curves/ed25519'\nexport async function computeX25519Ecdh1PUv3Kek(\n  recipient: Recipient,\n  recipientSecret: Uint8Array | ECDH,\n  senderPublicKey: Uint8Array,\n  alg: string\n) {\n  const crv = 'X25519'\n  const keyLen = 256\n  const header = recipient.header\n  if (header.epk?.crv !== crv || typeof header.epk.x == 'undefined') return null\n  // ECDH-1PU requires additional shared secret between\n  // static key of sender and static key of recipient\n  const publicKey = base64ToBytes(header.epk.x)\n  let zE: Uint8Array\n  let zS: Uint8Array\n\n  if (recipientSecret instanceof Uint8Array) {\n    zE = x25519.getSharedSecret(recipientSecret, publicKey)\n    zS = x25519.getSharedSecret(recipientSecret, senderPublicKey)\n  } else {\n    zE = await recipientSecret(publicKey)\n    zS = await recipientSecret(senderPublicKey)\n  }\n\n  const sharedSecret = new Uint8Array(zE.length + zS.length)\n  sharedSecret.set(zE)\n  sharedSecret.set(zS, zE.length)\n\n  // Key Encryption Key\n  let producerInfo\n  let consumerInfo\n  if (recipient.header.apu) producerInfo = base64ToBytes(recipient.header.apu)\n  if (recipient.header.apv) consumerInfo = base64ToBytes(recipient.header.apv)\n\n  return concatKDF(sharedSecret, keyLen, alg, producerInfo, consumerInfo)\n}\n\nexport async function createX25519Ecdh1PUv3Kek(\n  recipientPublicKey: Uint8Array,\n  senderSecret: Uint8Array | ECDH,\n  alg: string, // must be provided as this is the key agreement alg + the key wrapper alg, Example: 'ECDH-ES+A256KW'\n  apu: string | undefined,\n  apv: string | undefined,\n  ephemeralKeyPair: EphemeralKeyPair | undefined\n) {\n  const crv = 'X25519'\n  const keyLen = 256\n  const ephemeral = ephemeralKeyPair ? generateKeyPairFromSeed(ephemeralKeyPair.secretKey) : generateKeyPair()\n  const epk = { kty: 'OKP', crv, x: bytesToBase64url(ephemeral.publicKey) }\n  const zE = x25519.getSharedSecret(ephemeral.secretKey, recipientPublicKey)\n\n  // ECDH-1PU requires additional shared secret between\n  // static key of sender and static key of recipient\n  let zS\n  if (senderSecret instanceof Uint8Array) {\n    zS = x25519.getSharedSecret(senderSecret, recipientPublicKey)\n  } else {\n    zS = await senderSecret(recipientPublicKey)\n  }\n\n  const sharedSecret = new Uint8Array(zE.length + zS.length)\n  sharedSecret.set(zE)\n  sharedSecret.set(zS, zE.length)\n\n  let partyUInfo: Uint8Array = new Uint8Array(0)\n  let partyVInfo: Uint8Array = new Uint8Array(0)\n  if (apu) partyUInfo = base64ToBytes(apu)\n  if (apv) partyVInfo = base64ToBytes(apv)\n\n  // Key Encryption Key\n  const kek = concatKDF(sharedSecret, keyLen, alg, partyUInfo, partyVInfo)\n  return { epk, kek }\n}\n","import { x25519 } from '@noble/curves/ed25519'\nimport type { ECDH } from './types.js'\n\n/**\n * Wraps an X25519 secret key into an ECDH method that can be used to compute a shared secret with a public key.\n * @param mySecretKey A `Uint8Array` of length 32 representing the bytes of my secret key\n * @returns an `ECDH` method with the signature `(theirPublicKey: Uint8Array) => Promise<Uint8Array>`\n *\n * @throws 'invalid_argument:...' if the secret key size is wrong\n */\nexport function createX25519ECDH(mySecretKey: Uint8Array): ECDH {\n  if (mySecretKey.length !== 32) {\n    throw new Error('invalid_argument: incorrect secret key length for X25519')\n  }\n  return async (theirPublicKey: Uint8Array): Promise<Uint8Array> => {\n    if (theirPublicKey.length !== 32) {\n      throw new Error('invalid_argument: incorrect publicKey key length for X25519')\n    }\n    return x25519.getSharedSecret(mySecretKey, theirPublicKey)\n  }\n}\n","import type {\n  AuthEncryptParams,\n  ContentEncrypter,\n  ECDH,\n  Encrypter,\n  EncryptionResult,\n  EphemeralKeyPair,\n  KekCreator,\n  KeyWrapper,\n  ProtectedHeader,\n  Recipient,\n} from './types.js'\nimport { bytesToBase64url, genX25519EphemeralKeyPair } from '../util.js'\nimport { randomBytes } from '@noble/hashes/utils'\n\nexport function createFullEncrypter(\n  recipientPublicKey: Uint8Array,\n  senderSecret: Uint8Array | ECDH | undefined,\n  options: Partial<AuthEncryptParams> = {},\n  kekCreator: KekCreator,\n  keyWrapper: KeyWrapper,\n  contentEncrypter: ContentEncrypter\n): Encrypter {\n  async function encryptCek(cek: Uint8Array, ephemeralKeyPair?: EphemeralKeyPair): Promise<Recipient> {\n    const { epk, kek } = await kekCreator.createKek(\n      recipientPublicKey,\n      senderSecret,\n      `${kekCreator.alg}+${keyWrapper.alg}`,\n      options.apu,\n      options.apv,\n      ephemeralKeyPair\n    )\n    const res = await keyWrapper.from(kek).wrap(cek)\n    const recipient: Recipient = {\n      encrypted_key: bytesToBase64url(res.ciphertext),\n      header: {},\n    }\n    if (res.iv) recipient.header.iv = bytesToBase64url(res.iv)\n    if (res.tag) recipient.header.tag = bytesToBase64url(res.tag)\n    if (options.kid) recipient.header.kid = options.kid\n    if (options.apu) recipient.header.apu = options.apu\n    if (options.apv) recipient.header.apv = options.apv\n    if (!ephemeralKeyPair) {\n      recipient.header.alg = `${kekCreator.alg}+${keyWrapper.alg}`\n      recipient.header.epk = epk\n    }\n\n    return recipient\n  }\n\n  async function encrypt(\n    cleartext: Uint8Array,\n    protectedHeader: ProtectedHeader = {},\n    aad?: Uint8Array,\n    ephemeralKeyPair?: EphemeralKeyPair\n  ): Promise<EncryptionResult> {\n    // we won't want alg to be set to dir from xc20pDirEncrypter\n    Object.assign(protectedHeader, { alg: undefined })\n    // Content Encryption Key\n    const cek = randomBytes(32)\n    const recipient: Recipient = await encryptCek(cek, ephemeralKeyPair)\n    // getting an ephemeral key means the epk is set only once per all recipients\n    if (ephemeralKeyPair) {\n      protectedHeader.alg = `${kekCreator.alg}+${keyWrapper.alg}`\n      protectedHeader.epk = ephemeralKeyPair.publicKeyJWK\n    }\n    return {\n      ...(await contentEncrypter.from(cek).encrypt(cleartext, protectedHeader, aad)),\n      recipient,\n      cek,\n    }\n  }\n\n  return { alg: keyWrapper.alg, enc: contentEncrypter.enc, encrypt, encryptCek, genEpk: genX25519EphemeralKeyPair }\n}\n","import type { Resolvable, VerificationMethod } from 'did-resolver'\nimport type {\n  AnonEncryptParams,\n  AuthEncryptParams,\n  Decrypter,\n  ECDH,\n  Encrypter,\n  KeyWrapper,\n  ProtectedHeader,\n  Recipient,\n  WrappingResult,\n} from './types.js'\nimport { base64ToBytes, extractPublicKeyBytes, isDefined, toSealed } from '../util.js'\nimport { xc20pDirDecrypter, xc20pDirEncrypter, xc20pEncrypter } from './xc20pDir.js'\nimport { computeX25519Ecdh1PUv3Kek, createX25519Ecdh1PUv3Kek } from './X25519-ECDH-1PU.js'\nimport { computeX25519EcdhEsKek, createX25519EcdhEsKek } from './X25519-ECDH-ES.js'\nimport { createFullEncrypter } from './createEncrypter.js'\n\n/**\n * @deprecated Use\n *   {@link xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2 | xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2() } instead\n */\nexport function createAuthEncrypter(\n  recipientPublicKey: Uint8Array,\n  senderSecret: Uint8Array | ECDH,\n  options: Partial<AuthEncryptParams> = {}\n): Encrypter {\n  return xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(recipientPublicKey, senderSecret, options)\n}\n\n/**\n * @deprecated Use {@link xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2 | xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2() }\n *   instead\n */\nexport function createAnonEncrypter(publicKey: Uint8Array, options: Partial<AnonEncryptParams> = {}): Encrypter {\n  return xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2(publicKey, options)\n}\n\n/**\n * @deprecated Use\n *   {@link xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2 | xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2() } instead\n */\nexport function createAuthDecrypter(recipientSecret: Uint8Array | ECDH, senderPublicKey: Uint8Array): Decrypter {\n  return xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(recipientSecret, senderPublicKey)\n}\n\n/**\n * @deprecated Use {@link xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2 | xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2() }\n *   instead\n */\nexport function createAnonDecrypter(recipientSecret: Uint8Array | ECDH): Decrypter {\n  return xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2(recipientSecret)\n}\n\nexport function validateHeader(header?: ProtectedHeader): Required<Pick<ProtectedHeader, 'epk' | 'iv' | 'tag'>> {\n  if (!(header && header.epk && header.iv && header.tag)) {\n    throw new Error('bad_jwe: malformed header')\n  }\n  return header as Required<Pick<ProtectedHeader, 'epk' | 'iv' | 'tag'>>\n}\n\nexport const xc20pKeyWrapper: KeyWrapper = {\n  from: (wrappingKey: Uint8Array) => {\n    const wrap = async (cek: Uint8Array): Promise<WrappingResult> => {\n      return xc20pEncrypter(wrappingKey)(cek)\n    }\n    return { wrap }\n  },\n\n  alg: 'XC20PKW',\n}\n\n/**\n * @deprecated Use {@link xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2 | xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2() }\n *   instead\n */\nexport function x25519Encrypter(publicKey: Uint8Array, kid?: string, apv?: string): Encrypter {\n  return xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2(publicKey, { kid, apv })\n}\n\n/**\n * Recommended encrypter for anonymous encryption (i.e. no sender authentication).\n * Uses {@link https://tools.ietf.org/html/draft-amringer-jose-chacha-02 | ECDH-ES+XC20PKW v2}.\n *\n * @param recipientPublicKey - the byte array representing the recipient public key\n * @param options - {@link AnonEncryptParams} used to specify the recipient key ID (`kid`)\n *\n * @returns an {@link Encrypter} instance usable with {@link createJWE}\n *\n * NOTE: ECDH-ES+XC20PKW is a proposed draft in IETF and not a standard yet and\n * is subject to change as new revisions or until the official CFRG specification is released.\n */\nexport function xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2(\n  recipientPublicKey: Uint8Array,\n  options: Partial<AnonEncryptParams> = {}\n): Encrypter {\n  return createFullEncrypter(\n    recipientPublicKey,\n    undefined,\n    options,\n    { createKek: createX25519EcdhEsKek, alg: 'ECDH-ES' },\n    xc20pKeyWrapper,\n    { from: (cek: Uint8Array) => xc20pDirEncrypter(cek), enc: 'XC20P' }\n  )\n}\n\n/**\n *  Recommended encrypter for authenticated encryption (i.e. sender authentication and requires\n *  sender private key to encrypt the data).\n *  Uses {@link https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03 | ECDH-1PU v3 } and\n *  {@link https://tools.ietf.org/html/draft-amringer-jose-chacha-02 | XC20PKW v2 }.\n *\n *  @param recipientPublicKey - the byte array representing the recipient public key\n *  @param senderSecret - either a Uint8Array representing the sender secret key or\n *    an ECDH function that wraps the key and can promise a shared secret given a public key\n *  @param options - {@link AuthEncryptParams} used to specify extra header parameters\n *\n *  @returns an {@link Encrypter} instance usable with {@link createJWE}\n *\n *  NOTE: ECDH-1PU and XC20PKW are proposed drafts in IETF and not a standard yet and\n *  are subject to change as new revisions or until the official CFRG specification are released.\n *\n * Implements ECDH-1PU+XC20PKW with XChaCha20Poly1305 based on the following specs:\n *   - {@link https://tools.ietf.org/html/draft-amringer-jose-chacha-02 | XC20PKW}\n *   - {@link https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03 | ECDH-1PU}\n */\nexport function xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2(\n  recipientPublicKey: Uint8Array,\n  senderSecret: Uint8Array | ECDH,\n  options: Partial<AuthEncryptParams> = {}\n): Encrypter {\n  return createFullEncrypter(\n    recipientPublicKey,\n    senderSecret,\n    options,\n    { createKek: createX25519Ecdh1PUv3Kek, alg: 'ECDH-1PU' },\n    xc20pKeyWrapper,\n    { from: (cek: Uint8Array) => xc20pDirEncrypter(cek), enc: 'XC20P' }\n  )\n}\n\nexport async function resolveX25519Encrypters(dids: string[], resolver: Resolvable): Promise<Encrypter[]> {\n  const encryptersForDID = async (did: string, resolved: string[] = []): Promise<Encrypter[]> => {\n    const { didResolutionMetadata, didDocument } = await resolver.resolve(did)\n    resolved.push(did)\n    if (didResolutionMetadata?.error || didDocument == null) {\n      throw new Error(\n        `resolver_error: Could not resolve ${did}: ${didResolutionMetadata.error}, ${didResolutionMetadata.message}`\n      )\n    }\n    let controllerEncrypters: Encrypter[] = []\n    if (!didDocument.controller && !didDocument.keyAgreement) {\n      throw new Error(`no_suitable_keys: Could not find x25519 key for ${did}`)\n    }\n    if (didDocument.controller) {\n      let controllers = Array.isArray(didDocument.controller) ? didDocument.controller : [didDocument.controller]\n      controllers = controllers.filter((c) => !resolved.includes(c))\n      const encrypterPromises = controllers.map((did) =>\n        encryptersForDID(did, resolved).catch(() => {\n          return []\n        })\n      )\n      const encrypterArrays = await Promise.all(encrypterPromises)\n      controllerEncrypters = ([] as Encrypter[]).concat(...encrypterArrays)\n    }\n    const agreementKeys: VerificationMethod[] = didDocument.keyAgreement\n      ?.map((key) => {\n        if (typeof key === 'string') {\n          return [...(didDocument.publicKey || []), ...(didDocument.verificationMethod || [])].find(\n            (pk) => pk.id === key\n          )\n        }\n        return key\n      })\n      ?.filter((key) => typeof key !== 'undefined') as VerificationMethod[]\n    const pks =\n      agreementKeys?.filter((key) =>\n        ['X25519KeyAgreementKey2019', 'X25519KeyAgreementKey2020', 'JsonWebKey2020', 'Multikey'].includes(key.type)\n      ) ?? []\n    if (!pks.length && !controllerEncrypters.length)\n      throw new Error(`no_suitable_keys: Could not find X25519 key for ${did}`)\n    return pks\n      .map((pk) => {\n        const { keyBytes, keyType } = extractPublicKeyBytes(pk)\n        if (keyType === 'X25519') {\n          return x25519Encrypter(keyBytes, pk.id)\n        } else {\n          return null\n        }\n      })\n      .filter(isDefined)\n      .concat(...controllerEncrypters)\n  }\n\n  const encrypterPromises = dids.map((did) => encryptersForDID(did))\n  const encrypterArrays = await Promise.all(encrypterPromises)\n  return ([] as Encrypter[]).concat(...encrypterArrays)\n}\n\n/**\n * @deprecated Use {@link xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2 | xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2() }\n *   instead\n */\nexport function x25519Decrypter(receiverSecret: Uint8Array | ECDH): Decrypter {\n  return xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2(receiverSecret)\n}\n\n/**\n * Recommended decrypter for anonymous encryption (i.e. no sender authentication).\n * Uses {@link https://tools.ietf.org/html/draft-amringer-jose-chacha-02 | ECDH-ES+XC20PKW v2 }.\n *\n * @param recipientSecret - either a Uint8Array representing the recipient secret key or\n *   an ECDH function that wraps the key and can promise a shared secret given a public key\n *\n * @returns a {@link Decrypter} instance usable with {@link decryptJWE}\n *\n * NOTE: ECDH-ES+XC20PKW is a proposed draft in IETF and not a standard yet and\n * is subject to change as new revisions or until the official CFRG specification is released.\n *\n * @beta\n */\nexport function xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2(recipientSecret: Uint8Array | ECDH): Decrypter {\n  const alg = 'ECDH-ES+XC20PKW'\n  const enc = 'XC20P'\n\n  async function decrypt(\n    sealed: Uint8Array,\n    iv: Uint8Array,\n    aad?: Uint8Array,\n    recipient?: Recipient\n  ): Promise<Uint8Array | null> {\n    recipient = <Recipient>recipient\n    const header = validateHeader(recipient.header)\n\n    const kek = await computeX25519EcdhEsKek(recipient, recipientSecret, alg)\n    if (!kek) return null\n    // Content Encryption Key\n    const sealedCek = toSealed(recipient.encrypted_key, header.tag)\n    const cek = await xc20pDirDecrypter(kek).decrypt(sealedCek, base64ToBytes(header.iv))\n    if (cek === null) return null\n\n    return xc20pDirDecrypter(cek).decrypt(sealed, iv, aad)\n  }\n\n  return { alg, enc, decrypt }\n}\n\n/**\n * Recommended decrypter for authenticated encryption (i.e. sender authentication and requires\n * sender public key to decrypt the data).\n * Uses {@link https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03 | ECDH-1PU v3 } and\n * {@link https://tools.ietf.org/html/draft-amringer-jose-chacha-02 | XC20PKW v2 }.\n *\n * @param recipientSecret - either a Uint8Array representing the recipient secret key or\n *   an ECDH function that wraps the key and can promise a shared secret given a public key\n * @param senderPublicKey - the byte array representing the sender public key\n *\n * @returns a {@link Decrypter} instance usable with {@link decryptJWE}\n *\n * NOTE: ECDH-1PU and XC20PKW are proposed drafts in IETF and not a standard yet and\n * are subject to change as new revisions or until the official CFRG specification are released.\n *\n * @beta\n *\n * Implements ECDH-1PU+XC20PKW with XChaCha20Poly1305 based on the following specs:\n *   - {@link https://tools.ietf.org/html/draft-amringer-jose-chacha-02 | XC20PKW}\n *   - {@link https://tools.ietf.org/html/draft-madden-jose-ecdh-1pu-03 | ECDH-1PU}\n */\nexport function xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2(\n  recipientSecret: Uint8Array | ECDH,\n  senderPublicKey: Uint8Array\n): Decrypter {\n  const alg = 'ECDH-1PU+XC20PKW'\n  const enc = 'XC20P'\n\n  async function decrypt(\n    sealed: Uint8Array,\n    iv: Uint8Array,\n    aad?: Uint8Array,\n    recipient?: Recipient\n  ): Promise<Uint8Array | null> {\n    recipient = <Recipient>recipient\n    const header = validateHeader(recipient.header)\n    const kek = await computeX25519Ecdh1PUv3Kek(recipient, recipientSecret, senderPublicKey, alg)\n    if (!kek) return null\n    // Content Encryption Key\n    const sealedCek = toSealed(recipient.encrypted_key, header.tag)\n    const cek = await xc20pDirDecrypter(kek).decrypt(sealedCek, base64ToBytes(header.iv))\n    if (cek === null) return null\n\n    return xc20pDirDecrypter(cek).decrypt(sealed, iv, aad)\n  }\n\n  return { alg, enc, decrypt }\n}\n"],"names":["u8a","toString","fromString","concat","bytesToBase64url","b","base64ToBytes","s","inputBase64Url","replace","base58ToBytes","bytesToBase58","SUPPORTED_PUBLIC_KEY_TYPES","ES256","ES256K","Ed25519","EdDSA","VM_TO_KEY_TYPE","Secp256k1SignatureVerificationKey2018","Secp256k1VerificationKey2018","EcdsaSecp256k1VerificationKey2019","EcdsaPublicKeySecp256k1","EcdsaSecp256k1RecoveryMethod2020","EcdsaSecp256r1VerificationKey2019","Ed25519VerificationKey2018","Ed25519VerificationKey2020","ED25519SignatureVerification","X25519KeyAgreementKey2019","X25519KeyAgreementKey2020","ConditionalProof2022","undefined","JsonWebKey2020","Multikey","supportedCodecs","CODEC_TO_KEY_TYPE","extractPublicKeyBytes","pk","publicKeyBase58","keyBytes","keyType","type","publicKeyBase64","publicKeyHex","hexToBytes","publicKeyJwk","crv","x","y","secp256k1","ProjectivePoint","fromAffine","bytesToBigInt","toRawBytes","p256","kty","includes","publicKeyMultibase","multibaseToBytes","Uint8Array","bytesToMultibase","base","codec","encode","codecCode","prefixLength","varint","encodingLength","multicodecEncoding","length","encodeTo","set","bytes","decode","possibleCodec","Object","entries","filter","code","slice","e","minLength","input","startsWith","substring","paddedLength","Math","max","padStart","toLowerCase","encodeBase64url","decodeBase64url","bytesToHex","BigInt","stringToBytes","toJose","r","recoveryParam","recoverable","jose","Error","fromJose","signature","signatureBytes","TypeError","toSealed","ciphertext","tag","leftpad","data","size","repeat","generateKeyPair","secretKey","x25519","utils","randomPrivateKey","publicKey","getPublicKey","generateKeyPairFromSeed","seed","genX25519EphemeralKeyPair","epk","publicKeyJWK","isDefined","arg","sha256","payload","sha256Hash","keccak","keccak_256","toEthereumAddress","hexPublicKey","hashInput","writeUint32BE","value","array","encoded","lengthAndInput","concatKDF","secret","keyLen","alg","producerInfo","consumerInfo","roundNumber","ES256KSigner","privateKey","privateKeyBytes","sign","recovery","SimpleSigner","hexPrivateKey","signer","EllipticSigner","EdDSASigner","dataBytes","ed25519","NaclSigner","base64PrivateKey","ES256Signer","instanceOfEcdsaSignature","object","ES256SignerAlg","ES256KSignerAlg","Ed25519SignerAlg","algorithms","SignerAlg","impl","publicKeyToAddress","otherAddress","version","publicKeyBuffer","publicKeyHash","ripemd160","step1","step2","step3","checksum","step4","prefix","fromHex","hash","words","bech32","toWords","verifyBlockchainAccountId","blockchainAccountId","chain","split","bip122","cosmos","join","toSignatureObject","rawSig","sigObj","toSignatureObject2","compact","verifyES256","authenticators","sig","Signature","fromCompact","fullPublicKeys","a","ethereumAddress","find","verify","err","verifyES256K","signatureNormalized","normalizeS","blockchainAddressKeys","verifyRecoverableES256K","signatures","push","so","checkSignatureAgainstSigner","addRecoveryBit","recoveredPublicKey","recoverPublicKey","recoveredAddress","toHex","recoveredPublicKeyHex","recoveredCompressedPublicKeyHex","keyHex","verificationMethod","verifyEd25519","clear","VerifierAlgorithm","JWT_ERROR","INVALID_JWT","INVALID_AUDIENCE","INVALID_SIGNATURE","NO_SUITABLE_KEYS","NOT_SUPPORTED","RESOLVER_ERROR","verifyConditionDelegated","jwt","header","authenticator","options","conditionDelegated","resolver","foundSigner","issuer","resolveAuthenticator","proofPurpose","didAuthenticator","id","didResolutionResult","didDocument","delegatedAuthenticator","CONDITIONAL_PROOF_2022","verifyJWT","verified","verifyJWTDecoded","message","then","observer","pact","prototype","onFulfilled","result","state","callback","_settle","verifyConditionWeightedThreshold","conditionWeightedThreshold","threshold","issuers","weightCount","weightedCondition","weight","currentCondition","condition","newOptions","verifyConditionalProof","verifyProof","v","onRejected","body","i","reject","update","bind","_resumeAfterUpdate","shouldContinue","_resumeAfterBody","types","didResult","resolve","accept","DID_JSON","getOwnPropertyNames","indexOf","didDocumentMetadata","didResolutionMetadata","contentType","error","getPublicKeyById","verificationMethods","pubid","filtered","publicKeysToCheck","assertionMethod","map","key","supported","auth","audience","callbackUrl","skewTime","policies","now","floor","Date","NBF_SKEW","nowSkewed","nbf","iat","exp","aud","audArray","Array","isArray","matchedAudience","item","did","parse","didUrl","decodeJWT","hasOwnProperty","call","iss","client_id","SELF_ISSUED_V2","SELF_ISSUED_V2_VC_INTEROP","sub","sub_jwk","kid","SELF_ISSUED_V0_1","scope","redirect_uri","createMultisignatureJWT","expiresIn","canonicalize","payloadResult","typ","cty","createJWT","timestamps","fullPayload","createJWS","defaultAlg","encodedPayload","encodeSection","signingInput","jwtSigner","shouldCanonicalize","canonicalizeData","JSON","stringify","decodeJWS","jws","parts","match","recurse","decodedJwt","assign","innerDecodedJwt","pubKeys","verifyJWSDecoded","verifyJWS","jwsDecoded","_this","thenable","validateJWE","jwe","protected","iv","recipients","rec","encrypted_key","encodeJWE","protectedHeader","recipient","aad","decryptJWE","decrypter","cleartext","protHeader","enc","sealed","decrypt","createJWE","encrypters","useSingleEphemeralKey","encrypt","encryptionResult","tmpEnc","reduce","acc","encrypter","cek","genEpk","encryptCek","xc20pEncrypter","randomBytes","cipher","xchacha20poly1305","subarray","xc20pDirEncrypter","encodedAad","xc20pEncrypt","xc20pDirDecrypter","createX25519EcdhEsKek","recipientPublicKey","senderSecret","apu","apv","ephemeralKeyPair","ephemeral","sharedSecret","getSharedSecret","kek","computeX25519EcdhEsKek","receiverSecret","createX25519Ecdh1PUv3Kek","zE","zS","partyUInfo","partyVInfo","computeX25519Ecdh1PUv3Kek","recipientSecret","senderPublicKey","createX25519ECDH","mySecretKey","theirPublicKey","createFullEncrypter","kekCreator","keyWrapper","contentEncrypter","from","createKek","wrap","res","resolveX25519Encrypters","dids","encryptersForDID","resolved","agreementKeys","keyAgreement","pks","controllerEncrypters","x25519Encrypter","controller","controllers","c","encrypterPromises","catch","Promise","all","encrypterArrays","createAuthEncrypter","xc20pAuthEncrypterEcdh1PuV3x25519WithXc20PkwV2","createAnonEncrypter","xc20pAnonEncrypterEcdhESx25519WithXc20PkwV2","createAuthDecrypter","xc20pAuthDecrypterEcdh1PuV3x25519WithXc20PkwV2","createAnonDecrypter","xc20pAnonDecrypterEcdhESx25519WithXc20PkwV2","validateHeader","xc20pKeyWrapper","wrappingKey","x25519Decrypter","sealedCek"],"mappings":";;;;;;;;;;;;;;;;;;;AASA,MAAMA,GAAG,GAAG;YAAEC,oBAAF;cAAYC,sBAAZ;UAAwBC;AAAxB,CAAZ;SA4BgBC,iBAAiBC;EAC/B,OAAOL,GAAG,CAACC,QAAJ,CAAaI,CAAb,EAAgB,WAAhB,CAAP;AACD;SAEeC,cAAcC;EAC5B,MAAMC,cAAc,GAAGD,CAAC,CAACE,OAAF,CAAU,KAAV,EAAiB,GAAjB,EAAsBA,OAAtB,CAA8B,KAA9B,EAAqC,GAArC,EAA0CA,OAA1C,CAAkD,IAAlD,EAAwD,EAAxD,CAAvB;EACA,OAAOT,GAAG,CAACE,UAAJ,CAAeM,cAAf,EAA+B,WAA/B,CAAP;AACD;SAMeE,cAAcH;EAC5B,OAAOP,GAAG,CAACE,UAAJ,CAAeK,CAAf,EAAkB,WAAlB,CAAP;AACD;SAEeI,cAAcN;EAC5B,OAAOL,GAAG,CAACC,QAAJ,CAAaI,CAAb,EAAgB,WAAhB,CAAP;AACD;AAwBM,MAAMO,0BAA0B,GAAmB;EACxDC,KAAK,EAAE,CAAC,gBAAD,EAAmB,UA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