{"version":3,"sources":["../src/recovery/attestationDefaults.ts","../src/recovery/nitro/cbor.ts","../src/recovery/nitro/der.ts","../src/recovery/nitro/attestation.ts","../src/recovery/enclaveChannel.ts","../src/recovery/SocialRecoveryClient.ts","../src/signer/prfSalt.ts","../src/chains/stellar/PasskeyPrf.ts"],"names":["value","bytesEqual","plaintext","result","sha256"],"mappings":";;;;AAqBO,IAAM,mCAAA,GAAyD;AAAA,EACpE,IAAA,EAAM;AAAA,IACJ,kGAAA;AAAA,IACA;AAAA;AAEJ;;;ACoBO,SAAS,WAAW,KAAA,EAA2C;AACpE,EAAA,MAAM,MAAA,GAAiB,EAAE,KAAA,EAAO,MAAA,EAAQ,CAAA,EAAE;AAC1C,EAAA,MAAM,KAAA,GAAQ,WAAW,MAAM,CAAA;AAC/B,EAAA,IAAI,MAAA,CAAO,MAAA,KAAW,KAAA,CAAM,MAAA,EAAQ;AAClC,IAAA,MAAM,IAAI,MAAM,2CAA2C,CAAA;AAAA,EAC7D;AACA,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,WAAW,MAAA,EAAwC;AAC1D,EAAA,MAAM,OAAA,GAAU,UAAU,MAAM,CAAA;AAChC,EAAA,MAAM,QAAQ,OAAA,IAAW,CAAA;AACzB,EAAA,MAAM,OAAO,OAAA,GAAU,EAAA;AAEvB,EAAA,IAAI,SAAS,EAAA,EAAI;AAGf,IAAA,IAAI,KAAA,KAAU,CAAA,EAAG,OAAO,mBAAA,CAAoB,MAAM,CAAA;AAClD,IAAA,IAAI,KAAA,KAAU,CAAA,EAAG,OAAO,qBAAA,CAAsB,MAAM,CAAA;AACpD,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mCAAA,EAAsC,KAAK,CAAA,iBAAA,CAAmB,CAAA;AAAA,EAChF;AACA,EAAA,IAAI,OAAO,EAAA,EAAI,MAAM,IAAI,KAAA,CAAM,CAAA,sCAAA,EAAyC,IAAI,CAAA,CAAE,CAAA;AAG9E,EAAA,IAAI,UAAU,CAAA,EAA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AAA;AACjD,EAAA,IAAI,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA,EAAG,OAAO,IAAA;AAC/B,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,WAAW,MAAA,EAA4B;AAC9C,EAAA,MAAM,KAAA,GAAQ,IAAI,WAAA,EAAY,CAAE,OAAO,MAAM,CAAA;AAC7C,EAAA,OAAO,KAAA,CAAM,MAAA,IAAU,EAAA,GAAK,KAAA,GAAQC,OAAO,KAAK,CAAA;AAClD;AAEA,SAAS,IAAI,KAAA,EAAiC;AAC5C,EAAA,OAAO,MAAM,KAAA,EAAM;AACrB","file":"chunk-T2ZMQHFD.mjs","sourcesContent":["import type { AttestationPolicy } from \"./SocialRecoveryClient\";\n\n/**\n * The Nitro enclave image Cavos runs for hardware-isolated recovery.\n *\n * These values answer one question: *which enclave am I willing to talk to?*\n * They ship here, in a versioned package you install and can audit, rather than\n * arriving from the recovery API — an API that told the client which\n * measurement to trust could simply name its own, and the attestation would\n * prove nothing. The attestation itself is signed by AWS, so authenticity is\n * already anchored outside Cavos; this policy only fixes the workload's\n * identity.\n *\n * `pcr0` is the SHA-384 measurement of the enclave image file, as reported by\n * `nitro-cli build-enclave`. It accepts a list so a rollout can overlap:\n * publish the new measurement alongside the one still deployed, ship the\n * release, then redeploy. Apps on either version keep working through the\n * transition. Order is newest first.\n *\n * Override via `socialRecoveryAttestation` when you run your own enclave.\n */\nexport const DEFAULT_SOCIAL_RECOVERY_ATTESTATION: AttestationPolicy = {\n  pcr0: [\n    \"f388b0bf627bdad34968ebab083688b999da2aaa369a65323a3085725de0fc79d7cf0fab6527d57e06b4b10950a150f9\",\n    \"5ec163560006f105b5448c2db77ecf5ec442e00abd475f65349d6d93e837279652708770c50b3aa2e8676f553f572825\",\n  ],\n};\n","/**\n * The minimal CBOR (RFC 8949) subset needed to read a Nitro attestation\n * document, plus the one encoder case needed to rebuild a COSE `Sig_structure`.\n *\n * This is deliberately not a general CBOR library. Attestation documents are\n * adversarial input — a browser verifying one must reject anything it does not\n * fully understand rather than guess. So non-canonical integer widths, chunked\n * strings, and trailing bytes are all hard errors, and the decoder is small\n * enough to audit in one sitting.\n *\n * Indefinite-length maps and arrays ARE accepted, because the Nitro Security\n * Module genuinely emits them: a real attestation document's payload opens with\n * `0xBF`, an indefinite-length map. That makes the document non-canonical, so\n * nothing here may re-encode a decoded value and compare bytes. Signature\n * verification therefore runs over the original payload bytes as received —\n * never over a re-serialisation. Indefinite-length *strings* remain rejected;\n * the NSM does not emit them and chunked strings are a classic source of\n * parser-differential bugs.\n */\n\nexport type CborValue =\n  | number\n  | bigint\n  | Uint8Array\n  | string\n  | CborValue[]\n  | Map<CborValue, CborValue>\n  | boolean\n  | null;\n\n/** A CBOR tag (major type 6) and the value it wraps. */\nexport interface CborTagged {\n  tag: number;\n  value: CborValue;\n}\n\ninterface Cursor {\n  readonly bytes: Uint8Array;\n  offset: number;\n}\n\n/**\n * Decode exactly one CBOR item from `bytes`. Trailing bytes are rejected: an\n * attestation document that decodes but leaves data behind is malformed, and\n * silently ignoring the remainder is how parser-differential bugs start.\n */\nexport function decodeCbor(bytes: Uint8Array): CborValue | CborTagged {\n  const cursor: Cursor = { bytes, offset: 0 };\n  const value = decodeItem(cursor);\n  if (cursor.offset !== bytes.length) {\n    throw new Error(\"cbor: trailing bytes after top-level item\");\n  }\n  return value;\n}\n\nfunction decodeItem(cursor: Cursor): CborValue | CborTagged {\n  const initial = readUint8(cursor);\n  const major = initial >> 5;\n  const info = initial & 0x1f;\n\n  if (info === 31) {\n    // Only maps (5) and arrays (4) may be indefinite-length here. A bare break\n    // code (major 7) outside a container, or a chunked string, is malformed.\n    if (major === 5) return decodeIndefiniteMap(cursor);\n    if (major === 4) return decodeIndefiniteArray(cursor);\n    throw new Error(`cbor: indefinite-length major type ${major} is not supported`);\n  }\n  if (info > 27) throw new Error(`cbor: reserved additional information ${info}`);\n\n  // Major type 7 encodes simple values, not a length.\n  if (major === 7) {\n    if (info === 20) return false;\n    if (info === 21) return true;\n    if (info === 22) return null;\n    throw new Error(`cbor: unsupported simple value ${info}`);\n  }\n\n  const argument = readArgument(cursor, info);\n\n  switch (major) {\n    case 0:\n      return toNumberIfSafe(argument);\n    case 1:\n      return toNumberIfSafe(-1n - argument);\n    case 2:\n      return readBytes(cursor, lengthOf(argument));\n    case 3:\n      return new TextDecoder(\"utf-8\", { fatal: true }).decode(\n        readBytes(cursor, lengthOf(argument)),\n      );\n    case 4: {\n      const count = lengthOf(argument);\n      const items: CborValue[] = [];\n      for (let index = 0; index < count; index += 1) {\n        items.push(decodeItem(cursor) as CborValue);\n      }\n      return items;\n    }\n    case 5: {\n      const count = lengthOf(argument);\n      const entries = new Map<CborValue, CborValue>();\n      for (let index = 0; index < count; index += 1) {\n        const key = decodeItem(cursor) as CborValue;\n        const value = decodeItem(cursor) as CborValue;\n        // Duplicate keys make the document's meaning ambiguous; a verifier and\n        // a signer could disagree about which one counts.\n        if (entries.has(key)) throw new Error(\"cbor: duplicate map key\");\n        entries.set(key, value);\n      }\n      return entries;\n    }\n    case 6:\n      return { tag: lengthOf(argument), value: decodeItem(cursor) as CborValue };\n    default:\n      throw new Error(`cbor: unsupported major type ${major}`);\n  }\n}\n\n/** The CBOR \"break\" code that terminates an indefinite-length container. */\nconst BREAK = 0xff;\n\nfunction atBreak(cursor: Cursor): boolean {\n  if (cursor.offset >= cursor.bytes.length) throw new Error(\"cbor: unterminated indefinite item\");\n  return cursor.bytes[cursor.offset] === BREAK;\n}\n\nfunction decodeIndefiniteArray(cursor: Cursor): CborValue {\n  const items: CborValue[] = [];\n  while (!atBreak(cursor)) items.push(decodeItem(cursor) as CborValue);\n  cursor.offset += 1; // consume the break\n  return items;\n}\n\nfunction decodeIndefiniteMap(cursor: Cursor): CborValue {\n  const entries = new Map<CborValue, CborValue>();\n  while (!atBreak(cursor)) {\n    const key = decodeItem(cursor) as CborValue;\n    if (atBreak(cursor)) throw new Error(\"cbor: map key without a value\");\n    const value = decodeItem(cursor) as CborValue;\n    if (entries.has(key)) throw new Error(\"cbor: duplicate map key\");\n    entries.set(key, value);\n  }\n  cursor.offset += 1; // consume the break\n  return entries;\n}\n\n/**\n * Read the argument that follows the initial byte. Widths are checked for\n * canonical (shortest-form) encoding: a value that fits in fewer bytes than it\n * was given is rejected, so the same document cannot be re-encoded two ways.\n */\nfunction readArgument(cursor: Cursor, info: number): bigint {\n  if (info < 24) return BigInt(info);\n  if (info === 24) {\n    const value = BigInt(readUint8(cursor));\n    if (value < 24n) throw new Error(\"cbor: non-canonical 1-byte argument\");\n    return value;\n  }\n  const width = info === 25 ? 2 : info === 26 ? 4 : 8;\n  const bytes = readBytes(cursor, width);\n  let value = 0n;\n  for (const byte of bytes) value = (value << 8n) | BigInt(byte);\n  const minimum = width === 2 ? 0x100n : width === 4 ? 0x10000n : 0x100000000n;\n  if (value < minimum) throw new Error(`cbor: non-canonical ${width}-byte argument`);\n  return value;\n}\n\nfunction lengthOf(argument: bigint): number {\n  if (argument > BigInt(Number.MAX_SAFE_INTEGER)) {\n    throw new Error(\"cbor: length exceeds supported range\");\n  }\n  return Number(argument);\n}\n\nfunction toNumberIfSafe(value: bigint): number | bigint {\n  return value >= BigInt(Number.MIN_SAFE_INTEGER) && value <= BigInt(Number.MAX_SAFE_INTEGER)\n    ? Number(value)\n    : value;\n}\n\nfunction readUint8(cursor: Cursor): number {\n  if (cursor.offset >= cursor.bytes.length) throw new Error(\"cbor: unexpected end of input\");\n  return cursor.bytes[cursor.offset++];\n}\n\nfunction readBytes(cursor: Cursor, length: number): Uint8Array {\n  if (cursor.offset + length > cursor.bytes.length) {\n    throw new Error(\"cbor: unexpected end of input\");\n  }\n  const slice = cursor.bytes.subarray(cursor.offset, cursor.offset + length);\n  cursor.offset += length;\n  return slice;\n}\n\n/**\n * Encode the COSE `Sig_structure` array that ES384 signatures are computed\n * over: `[\"Signature1\", protected, external_aad, payload]`. This is the only\n * value the kit ever encodes, so the encoder covers just text strings, byte\n * strings, and a fixed-size array.\n */\nexport function encodeSigStructure(\n  protectedHeader: Uint8Array,\n  externalAad: Uint8Array,\n  payload: Uint8Array,\n): Uint8Array {\n  return concatBytes([\n    Uint8Array.from([0x84]), // array(4)\n    encodeTextString(\"Signature1\"),\n    encodeByteString(protectedHeader),\n    encodeByteString(externalAad),\n    encodeByteString(payload),\n  ]);\n}\n\nfunction encodeTextString(value: string): Uint8Array {\n  const bytes = new TextEncoder().encode(value);\n  return concatBytes([encodeHead(3, bytes.length), bytes]);\n}\n\nfunction encodeByteString(value: Uint8Array): Uint8Array {\n  return concatBytes([encodeHead(2, value.length), value]);\n}\n\nfunction encodeHead(major: number, length: number): Uint8Array {\n  const prefix = major << 5;\n  if (length < 24) return Uint8Array.from([prefix | length]);\n  if (length < 0x100) return Uint8Array.from([prefix | 24, length]);\n  if (length < 0x10000) return Uint8Array.from([prefix | 25, length >> 8, length & 0xff]);\n  return Uint8Array.from([\n    prefix | 26,\n    (length >>> 24) & 0xff,\n    (length >>> 16) & 0xff,\n    (length >>> 8) & 0xff,\n    length & 0xff,\n  ]);\n}\n\nfunction concatBytes(parts: Uint8Array[]): Uint8Array {\n  const total = parts.reduce((sum, part) => sum + part.length, 0);\n  const out = new Uint8Array(total);\n  let offset = 0;\n  for (const part of parts) {\n    out.set(part, offset);\n    offset += part.length;\n  }\n  return out;\n}\n","/**\n * The minimal DER / X.509 reader needed to validate a Nitro attestation\n * certificate chain in a browser.\n *\n * WebCrypto can verify an ECDSA signature but cannot parse a certificate, and\n * pulling a full X.509 stack into the SDK for four fields is not a trade worth\n * making. This reads only what chain validation actually needs: the signed\n * region, the public key, the validity window, and the CA flag.\n *\n * Everything here treats its input as hostile. Lengths are bounds-checked,\n * non-canonical DER is rejected, and any structure that does not match the\n * expected shape is an error rather than a default.\n */\n\nconst TAG_BOOLEAN = 0x01;\nconst TAG_INTEGER = 0x02;\nconst TAG_BIT_STRING = 0x03;\nconst TAG_OCTET_STRING = 0x04;\nconst TAG_OID = 0x06;\nconst TAG_SEQUENCE = 0x30;\nconst TAG_UTC_TIME = 0x17;\nconst TAG_GENERALIZED_TIME = 0x18;\nconst TAG_CONTEXT_3 = 0xa3;\n\n/** OID 1.2.840.10045.4.3.3 — ecdsa-with-SHA384, the only algorithm Nitro uses. */\nconst OID_ECDSA_WITH_SHA384 = \"1.2.840.10045.4.3.3\";\n/** OID 2.5.29.19 — basicConstraints. */\nconst OID_BASIC_CONSTRAINTS = \"2.5.29.19\";\n\nexport interface DerElement {\n  tag: number;\n  /** The full element including tag and length bytes. */\n  full: Uint8Array;\n  /** The element's contents, excluding tag and length bytes. */\n  content: Uint8Array;\n  /** Offset immediately after this element in the parent buffer. */\n  end: number;\n}\n\nexport interface ParsedCertificate {\n  /** The exact DER bytes the signature is computed over. */\n  tbs: Uint8Array;\n  /** SubjectPublicKeyInfo, in the form WebCrypto's `spki` import expects. */\n  subjectPublicKeyInfo: Uint8Array;\n  /** Raw `r ‖ s`, converted from the DER-encoded ECDSA signature. */\n  signature: Uint8Array;\n  issuer: Uint8Array;\n  subject: Uint8Array;\n  notBefore: Date;\n  notAfter: Date;\n  isCertificateAuthority: boolean;\n}\n\n/** Read the DER element that starts at `offset`. */\nexport function readElement(bytes: Uint8Array, offset: number): DerElement {\n  if (offset + 2 > bytes.length) throw new Error(\"der: truncated element header\");\n  const tag = bytes[offset];\n  // Multi-byte tags would mean a structure this reader does not expect.\n  if ((tag & 0x1f) === 0x1f) throw new Error(\"der: multi-byte tags are not supported\");\n\n  const lengthByte = bytes[offset + 1];\n  let length: number;\n  let headerLength: number;\n\n  if (lengthByte < 0x80) {\n    length = lengthByte;\n    headerLength = 2;\n  } else {\n    const lengthBytes = lengthByte & 0x7f;\n    if (lengthBytes === 0) throw new Error(\"der: indefinite lengths are not valid in DER\");\n    if (lengthBytes > 4) throw new Error(\"der: length exceeds supported range\");\n    if (offset + 2 + lengthBytes > bytes.length) throw new Error(\"der: truncated length\");\n    length = 0;\n    for (let index = 0; index < lengthBytes; index += 1) {\n      length = (length << 8) | bytes[offset + 2 + index];\n    }\n    // DER requires the shortest possible length encoding.\n    if (length < 0x80) throw new Error(\"der: non-canonical length encoding\");\n    headerLength = 2 + lengthBytes;\n  }\n\n  const contentStart = offset + headerLength;\n  const end = contentStart + length;\n  if (end > bytes.length) throw new Error(\"der: element overruns buffer\");\n\n  return {\n    tag,\n    full: bytes.subarray(offset, end),\n    content: bytes.subarray(contentStart, end),\n    end,\n  };\n}\n\nfunction expect(bytes: Uint8Array, offset: number, tag: number, label: string): DerElement {\n  const element = readElement(bytes, offset);\n  if (element.tag !== tag) {\n    throw new Error(`der: expected ${label} (tag 0x${tag.toString(16)}), got 0x${element.tag.toString(16)}`);\n  }\n  return element;\n}\n\n/**\n * Parse an X.509 certificate far enough to validate a chain.\n *\n * The signature algorithm is checked here rather than by the caller: a chain\n * whose certificates are signed with something other than ECDSA-SHA384 is not a\n * Nitro chain, and finding that out early keeps the verifier's contract narrow.\n */\nexport function parseCertificate(der: Uint8Array): ParsedCertificate {\n  const certificate = expect(der, 0, TAG_SEQUENCE, \"Certificate\");\n  if (certificate.end !== der.length) throw new Error(\"der: trailing bytes after certificate\");\n\n  const body = certificate.content;\n  const tbs = expect(body, 0, TAG_SEQUENCE, \"TBSCertificate\");\n  const signatureAlgorithm = expect(body, tbs.end, TAG_SEQUENCE, \"signatureAlgorithm\");\n  const signatureValue = expect(body, signatureAlgorithm.end, TAG_BIT_STRING, \"signatureValue\");\n  if (signatureValue.end !== body.length) {\n    throw new Error(\"der: trailing bytes after signatureValue\");\n  }\n\n  const algorithmOid = readObjectIdentifier(\n    expect(signatureAlgorithm.content, 0, TAG_OID, \"algorithm OID\"),\n  );\n  if (algorithmOid !== OID_ECDSA_WITH_SHA384) {\n    throw new Error(`der: unexpected certificate signature algorithm ${algorithmOid}`);\n  }\n\n  // A BIT STRING's first content byte counts unused trailing bits; for a\n  // signature it must be zero.\n  if (signatureValue.content.length < 1 || signatureValue.content[0] !== 0) {\n    throw new Error(\"der: malformed signature BIT STRING\");\n  }\n\n  const fields = readTbsFields(tbs.content);\n\n  return {\n    tbs: tbs.full,\n    subjectPublicKeyInfo: fields.subjectPublicKeyInfo,\n    signature: derEcdsaSignatureToRaw(signatureValue.content.subarray(1), 48),\n    issuer: fields.issuer,\n    subject: fields.subject,\n    notBefore: fields.notBefore,\n    notAfter: fields.notAfter,\n    isCertificateAuthority: fields.isCertificateAuthority,\n  };\n}\n\nfunction readTbsFields(tbs: Uint8Array): {\n  issuer: Uint8Array;\n  subject: Uint8Array;\n  notBefore: Date;\n  notAfter: Date;\n  subjectPublicKeyInfo: Uint8Array;\n  isCertificateAuthority: boolean;\n} {\n  let offset = 0;\n\n  // version [0] EXPLICIT, optional and defaulting to v1.\n  const first = readElement(tbs, offset);\n  if (first.tag === 0xa0) offset = first.end;\n\n  const serialNumber = expect(tbs, offset, TAG_INTEGER, \"serialNumber\");\n  const innerAlgorithm = expect(tbs, serialNumber.end, TAG_SEQUENCE, \"signature\");\n  const issuer = expect(tbs, innerAlgorithm.end, TAG_SEQUENCE, \"issuer\");\n  const validity = expect(tbs, issuer.end, TAG_SEQUENCE, \"validity\");\n  const subject = expect(tbs, validity.end, TAG_SEQUENCE, \"subject\");\n  const subjectPublicKeyInfo = expect(tbs, subject.end, TAG_SEQUENCE, \"subjectPublicKeyInfo\");\n\n  const notBeforeElement = readElement(validity.content, 0);\n  const notAfterElement = readElement(validity.content, notBeforeElement.end);\n\n  return {\n    issuer: issuer.full,\n    subject: subject.full,\n    notBefore: readTime(notBeforeElement),\n    notAfter: readTime(notAfterElement),\n    subjectPublicKeyInfo: subjectPublicKeyInfo.full,\n    isCertificateAuthority: readCaFlag(tbs, subjectPublicKeyInfo.end),\n  };\n}\n\n/**\n * Read the basicConstraints CA flag, if the certificate carries one.\n *\n * Absent basicConstraints means \"not a CA\" (RFC 5280), which is the safe\n * default: a chain that omits it for an issuing certificate should fail.\n */\nfunction readCaFlag(tbs: Uint8Array, offset: number): boolean {\n  let cursor = offset;\n  while (cursor < tbs.length) {\n    const element = readElement(tbs, cursor);\n    cursor = element.end;\n    if (element.tag !== TAG_CONTEXT_3) continue;\n\n    const extensions = expect(element.content, 0, TAG_SEQUENCE, \"Extensions\");\n    let extensionOffset = 0;\n    while (extensionOffset < extensions.content.length) {\n      const extension = expect(extensions.content, extensionOffset, TAG_SEQUENCE, \"Extension\");\n      extensionOffset = extension.end;\n\n      const oidElement = expect(extension.content, 0, TAG_OID, \"extnID\");\n      if (readObjectIdentifier(oidElement) !== OID_BASIC_CONSTRAINTS) continue;\n\n      // `critical` is optional and defaults to FALSE, so the OCTET STRING may\n      // be either the second or the third field.\n      let next = readElement(extension.content, oidElement.end);\n      if (next.tag === TAG_BOOLEAN) next = readElement(extension.content, next.end);\n      if (next.tag !== TAG_OCTET_STRING) throw new Error(\"der: malformed basicConstraints\");\n\n      const constraints = expect(next.content, 0, TAG_SEQUENCE, \"BasicConstraints\");\n      if (constraints.content.length === 0) return false;\n      const caFlag = readElement(constraints.content, 0);\n      if (caFlag.tag !== TAG_BOOLEAN) return false;\n      return caFlag.content.length === 1 && caFlag.content[0] !== 0;\n    }\n  }\n  return false;\n}\n\nfunction readTime(element: DerElement): Date {\n  const text = new TextDecoder(\"utf-8\", { fatal: true }).decode(element.content);\n\n  if (element.tag === TAG_UTC_TIME) {\n    // YYMMDDHHMMSSZ — RFC 5280 pivots the two-digit year at 50.\n    const match = /^(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text);\n    if (!match) throw new Error(\"der: malformed UTCTime\");\n    const twoDigitYear = Number(match[1]);\n    const year = twoDigitYear >= 50 ? 1900 + twoDigitYear : 2000 + twoDigitYear;\n    return utc(year, match.slice(2).map(Number) as [number, number, number, number, number]);\n  }\n\n  if (element.tag === TAG_GENERALIZED_TIME) {\n    // YYYYMMDDHHMMSSZ\n    const match = /^(\\d{4})(\\d{2})(\\d{2})(\\d{2})(\\d{2})(\\d{2})Z$/.exec(text);\n    if (!match) throw new Error(\"der: malformed GeneralizedTime\");\n    return utc(\n      Number(match[1]),\n      match.slice(2).map(Number) as [number, number, number, number, number],\n    );\n  }\n\n  throw new Error(`der: unexpected time tag 0x${element.tag.toString(16)}`);\n}\n\nfunction utc(\n  year: number,\n  [month, day, hour, minute, second]: [number, number, number, number, number],\n): Date {\n  return new Date(Date.UTC(year, month - 1, day, hour, minute, second));\n}\n\nfunction readObjectIdentifier(element: DerElement): string {\n  const content = element.content;\n  if (content.length === 0) throw new Error(\"der: empty OID\");\n\n  const parts: number[] = [Math.floor(content[0] / 40), content[0] % 40];\n  let value = 0;\n  for (let index = 1; index < content.length; index += 1) {\n    const byte = content[index];\n    value = value * 128 + (byte & 0x7f);\n    if ((byte & 0x80) === 0) {\n      parts.push(value);\n      value = 0;\n    }\n  }\n  return parts.join(\".\");\n}\n\n/**\n * Convert a DER `SEQUENCE { r INTEGER, s INTEGER }` signature into the fixed\n * `r ‖ s` form WebCrypto expects. DER integers are signed and minimally\n * encoded, so they carry a leading zero when the high bit is set and drop\n * leading zero bytes otherwise; both are normalised to `size` bytes here.\n */\nexport function derEcdsaSignatureToRaw(der: Uint8Array, size: number): Uint8Array {\n  const sequence = expect(der, 0, TAG_SEQUENCE, \"ECDSA-Sig-Value\");\n  if (sequence.end !== der.length) throw new Error(\"der: trailing bytes after signature\");\n\n  const r = expect(sequence.content, 0, TAG_INTEGER, \"r\");\n  const s = expect(sequence.content, r.end, TAG_INTEGER, \"s\");\n  if (s.end !== sequence.content.length) throw new Error(\"der: unexpected signature fields\");\n\n  const out = new Uint8Array(size * 2);\n  out.set(normaliseInteger(r.content, size), 0);\n  out.set(normaliseInteger(s.content, size), size);\n  return out;\n}\n\nfunction normaliseInteger(bytes: Uint8Array, size: number): Uint8Array {\n  let start = 0;\n  while (start < bytes.length - 1 && bytes[start] === 0) start += 1;\n  const trimmed = bytes.subarray(start);\n  if (trimmed.length > size) throw new Error(\"der: signature integer is too large\");\n  const out = new Uint8Array(size);\n  out.set(trimmed, size - trimmed.length);\n  return out;\n}\n","/**\n * Verification of AWS Nitro Enclaves attestation documents.\n *\n * This answers one question for the browser: *is the key I am about to encrypt\n * my Google credential to actually held by the enclave image Cavos published?*\n * Nothing else in the recovery flow is load-bearing for confidentiality — the\n * control plane and the enclave's parent instance only ever relay ciphertext —\n * so this file is the security boundary and is written to be read closely.\n *\n * The trust anchor is the AWS Nitro root certificate, pinned below as bytes. It\n * ships in this package rather than arriving from the recovery API for the same\n * reason the workload measurements do: an API that told the client which root\n * to trust could name its own, and the attestation would prove nothing.\n *\n * Document format: RFC 8949 CBOR, signed as a COSE_Sign1 structure with ES384.\n * See https://docs.aws.amazon.com/enclaves/latest/user/verify-root.html\n */\n\nimport { decodeCbor, encodeSigStructure, type CborValue } from \"./cbor\";\nimport { parseCertificate, type ParsedCertificate } from \"./der\";\n\n/**\n * The AWS Nitro Attestation PKI root, DER-encoded.\n *\n * Verified against the fingerprint AWS publishes:\n *   64:1A:03:21:A3:E2:44:EF:E4:56:46:31:95:D6:06:31:\n *   7E:D7:CD:CC:3C:17:56:E0:98:93:F3:C6:8F:79:BB:5B\n * Valid until 2049-10-28. `npm run verify:nitro-root` re-checks this constant\n * against the published certificate.\n */\nconst NITRO_ROOT_CERTIFICATE_B64 =\n  \"MIICETCCAZagAwIBAgIRAPkxdWgbkK/hHUbMtOTn+FYwCgYIKoZIzj0EAwMwSTELMAkGA1UEBhMC\" +\n  \"VVMxDzANBgNVBAoMBkFtYXpvbjEMMAoGA1UECwwDQVdTMRswGQYDVQQDDBJhd3Mubml0cm8tZW5j\" +\n  \"bGF2ZXMwHhcNMTkxMDI4MTMyODA1WhcNNDkxMDI4MTQyODA1WjBJMQswCQYDVQQGEwJVUzEPMA0G\" +\n  \"A1UECgwGQW1hem9uMQwwCgYDVQQLDANBV1MxGzAZBgNVBAMMEmF3cy5uaXRyby1lbmNsYXZlczB2\" +\n  \"MBAGByqGSM49AgEGBSuBBAAiA2IABPwCVOumCMHzaHDimtqQvkY4MpJzbolL//Zy2YlES1BR5TSk\" +\n  \"sfbb48C8WBoyt7F2Bw7eEtaaP+ohG2bnUs990d0JX28TcPQXCEPZ3BABIeTPYwEoCWZEh8l5YoQw\" +\n  \"TcU/9KNCMEAwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUkCW1DdkFR+eWw5b6cp3PmanfS5Yw\" +\n  \"DgYDVR0PAQH/BAQDAgGGMAoGCCqGSM49BAMDA2kAMGYCMQCjfy+Rocm9Xue4YnwWmNJVA44fA0P5\" +\n  \"W2OpYow9OYCVRaEevL8uO1XYru5xtMPWrfMCMQCi85sWBbJwKKXdS6BptQFuZbT73o/gBh1qUxl/\" +\n  \"nNr12UO8Yfwr6wPLb+6NIwLz3/Y=\";\n\n/** COSE algorithm identifier for ECDSA w/ SHA-384. */\nconst COSE_ALG_ES384 = -35;\n/** COSE header label for the signing algorithm. */\nconst COSE_HEADER_ALG = 1;\n/** CBOR tag identifying a COSE_Sign1 structure. */\nconst COSE_SIGN1_TAG = 18;\n/** P-384 signatures are two 48-byte scalars. */\nconst P384_COORDINATE_BYTES = 48;\n\n/**\n * How stale an attestation document may be. Documents are produced per session,\n * and the enclave answers in milliseconds, so a wide window buys nothing but\n * replay surface. Five minutes tolerates ordinary clock skew.\n */\nconst MAX_DOCUMENT_AGE_MS = 5 * 60_000;\n\n/**\n * Which enclave the SDK is willing to talk to.\n *\n * `pcr0` accepts a list so an image rollout can overlap: publish the new\n * measurement alongside the one still deployed, ship the release, then\n * redeploy. Apps on either version keep working through the transition.\n * Order is newest first.\n */\nexport interface NitroAttestationPolicy {\n  /** Accepted PCR0 values (hex, no `0x`) — the measurement of the enclave image. */\n  pcr0: string | string[];\n}\n\nexport interface NitroAttestationDocument {\n  moduleId: string;\n  timestamp: Date;\n  pcrs: Map<number, Uint8Array>;\n  /** The enclave's ephemeral channel key, as published in the document. */\n  publicKey?: Uint8Array;\n  userData?: Uint8Array;\n  nonce?: Uint8Array;\n}\n\n/**\n * Verify a Nitro attestation document and return its contents.\n *\n * Throws on any failure. Callers must treat a thrown error as \"do not send this\n * enclave anything\" — there is no partial success, and no field of the returned\n * document is meaningful unless the whole verification passed.\n *\n * `now` is injectable so tests can pin a moment inside a captured document's\n * validity window; production callers should leave it unset.\n */\nexport async function verifyNitroAttestation(\n  document: Uint8Array,\n  policy: NitroAttestationPolicy,\n  options: { now?: Date } = {},\n): Promise<NitroAttestationDocument> {\n  const now = options.now ?? new Date();\n\n  const { protectedHeader, payload, signature } = readCoseSign1(document);\n  assertEs384(protectedHeader);\n\n  const attestation = readAttestationDocument(payload);\n\n  // Order matters below. The certificate chain establishes that AWS vouches for\n  // the signing key; only then is it worth checking what the document says.\n  const leaf = await verifyCertificateChain(attestation.certificate, attestation.cabundle, now);\n\n  const signedRegion = encodeSigStructure(protectedHeader, new Uint8Array(0), payload);\n  const signingKey = await importP384PublicKey(leaf.subjectPublicKeyInfo);\n  const signatureIsValid = await crypto.subtle.verify(\n    { name: \"ECDSA\", hash: \"SHA-384\" },\n    signingKey,\n    signature as unknown as BufferSource,\n    signedRegion as unknown as BufferSource,\n  );\n  if (!signatureIsValid) {\n    throw new Error(\"kit/nitro: attestation signature is invalid\");\n  }\n\n  const age = now.getTime() - attestation.timestamp.getTime();\n  if (age > MAX_DOCUMENT_AGE_MS) {\n    throw new Error(\"kit/nitro: attestation document is stale\");\n  }\n  // A document dated in the future is either clock skew or a replay attempt\n  // against a rolled-back clock. Allow the same tolerance in both directions.\n  if (age < -MAX_DOCUMENT_AGE_MS) {\n    throw new Error(\"kit/nitro: attestation document is dated in the future\");\n  }\n\n  const pcr0 = attestation.pcrs.get(0);\n  if (!pcr0 || !isAcceptedMeasurement(toHex(pcr0), policy.pcr0)) {\n    throw new Error(\"kit/nitro: enclave image measurement is not accepted\");\n  }\n\n  return attestation;\n}\n\n/**\n * Whether an attested PCR0 is one this build accepts.\n *\n * An empty accepted list matches nothing: a policy that cannot be satisfied\n * must fail closed rather than wave everything past.\n */\nexport function isAcceptedMeasurement(\n  attested: string | undefined | null,\n  expected: string | string[],\n): boolean {\n  if (!attested) return false;\n  const accepted = (Array.isArray(expected) ? expected : [expected]).map(normaliseHex);\n  return accepted.length > 0 && accepted.includes(normaliseHex(attested));\n}\n\nfunction normaliseHex(value: string): string {\n  return value.replace(/^0x/i, \"\").toLowerCase();\n}\n\ninterface CoseSign1 {\n  protectedHeader: Uint8Array;\n  payload: Uint8Array;\n  signature: Uint8Array;\n}\n\nfunction readCoseSign1(document: Uint8Array): CoseSign1 {\n  let decoded = decodeCbor(document);\n\n  // The structure may be tagged or untagged depending on the producer; the NSM\n  // emits it tagged. Accept either, but reject any other tag.\n  if (typeof decoded === \"object\" && decoded !== null && \"tag\" in decoded) {\n    if (decoded.tag !== COSE_SIGN1_TAG) {\n      throw new Error(`kit/nitro: unexpected CBOR tag ${decoded.tag}`);\n    }\n    decoded = decoded.value;\n  }\n\n  if (!Array.isArray(decoded) || decoded.length !== 4) {\n    throw new Error(\"kit/nitro: attestation is not a COSE_Sign1 structure\");\n  }\n\n  const [protectedHeader, , payload, signature] = decoded;\n  if (\n    !(protectedHeader instanceof Uint8Array) ||\n    !(payload instanceof Uint8Array) ||\n    !(signature instanceof Uint8Array)\n  ) {\n    throw new Error(\"kit/nitro: malformed COSE_Sign1 fields\");\n  }\n  if (signature.length !== P384_COORDINATE_BYTES * 2) {\n    throw new Error(\"kit/nitro: unexpected signature length\");\n  }\n\n  return { protectedHeader, payload, signature };\n}\n\n/**\n * Require that the signature really is ES384.\n *\n * Reading the algorithm from the protected header and then trusting it would be\n * pointless — the header is attacker-supplied. It is pinned to one value so a\n * document cannot ask to be verified under a weaker algorithm.\n */\nfunction assertEs384(protectedHeader: Uint8Array): void {\n  const header = decodeCbor(protectedHeader);\n  if (!(header instanceof Map)) {\n    throw new Error(\"kit/nitro: malformed COSE protected header\");\n  }\n  if (header.get(COSE_HEADER_ALG) !== COSE_ALG_ES384) {\n    throw new Error(\"kit/nitro: attestation is not signed with ES384\");\n  }\n}\n\ninterface RawAttestation extends NitroAttestationDocument {\n  certificate: Uint8Array;\n  cabundle: Uint8Array[];\n}\n\nfunction readAttestationDocument(payload: Uint8Array): RawAttestation {\n  const document = decodeCbor(payload);\n  if (!(document instanceof Map)) {\n    throw new Error(\"kit/nitro: attestation payload is not a map\");\n  }\n\n  const moduleId = requireString(document, \"module_id\");\n  const digest = requireString(document, \"digest\");\n  // The PCR values are SHA-384 digests; any other digest function would mean\n  // the measurements are not comparable to the ones this build pins.\n  if (digest !== \"SHA384\") {\n    throw new Error(`kit/nitro: unexpected PCR digest ${digest}`);\n  }\n\n  const timestampValue = document.get(\"timestamp\");\n  if (typeof timestampValue !== \"number\" && typeof timestampValue !== \"bigint\") {\n    throw new Error(\"kit/nitro: attestation timestamp is missing\");\n  }\n\n  const pcrsValue = document.get(\"pcrs\");\n  if (!(pcrsValue instanceof Map)) throw new Error(\"kit/nitro: attestation PCRs are missing\");\n  const pcrs = new Map<number, Uint8Array>();\n  for (const [index, value] of pcrsValue) {\n    if (typeof index !== \"number\" || !(value instanceof Uint8Array)) {\n      throw new Error(\"kit/nitro: malformed PCR entry\");\n    }\n    pcrs.set(index, value);\n  }\n\n  const certificate = document.get(\"certificate\");\n  if (!(certificate instanceof Uint8Array)) {\n    throw new Error(\"kit/nitro: attestation certificate is missing\");\n  }\n\n  const cabundleValue = document.get(\"cabundle\");\n  if (!Array.isArray(cabundleValue) || cabundleValue.length === 0) {\n    throw new Error(\"kit/nitro: attestation CA bundle is missing\");\n  }\n  const cabundle = cabundleValue.map((entry) => {\n    if (!(entry instanceof Uint8Array)) throw new Error(\"kit/nitro: malformed CA bundle entry\");\n    return entry;\n  });\n\n  return {\n    moduleId,\n    timestamp: new Date(Number(timestampValue)),\n    pcrs,\n    certificate,\n    cabundle,\n    publicKey: optionalBytes(document, \"public_key\"),\n    userData: optionalBytes(document, \"user_data\"),\n    nonce: optionalBytes(document, \"nonce\"),\n  };\n}\n\nfunction requireString(document: Map<CborValue, CborValue>, key: string): string {\n  const value = document.get(key);\n  if (typeof value !== \"string\" || value.length === 0) {\n    throw new Error(`kit/nitro: attestation ${key} is missing`);\n  }\n  return value;\n}\n\nfunction optionalBytes(\n  document: Map<CborValue, CborValue>,\n  key: string,\n): Uint8Array | undefined {\n  const value = document.get(key);\n  if (value === undefined || value === null) return undefined;\n  if (!(value instanceof Uint8Array)) throw new Error(`kit/nitro: malformed ${key}`);\n  // The NSM encodes \"absent\" as a zero-length string in some SDK versions.\n  return value.length === 0 ? undefined : value;\n}\n\n/**\n * Validate the certificate path from the document's signing certificate up to\n * the pinned AWS root.\n *\n * AWS emits `cabundle` root-first (`[ROOT, INTERM_1, …, INTERM_N]`), so the\n * path runs in the opposite order. The bundle's own root is deliberately\n * discarded and replaced with the pinned one: trusting the root that arrived\n * alongside the document would make the whole chain self-signed by the\n * attacker.\n */\nasync function verifyCertificateChain(\n  leafDer: Uint8Array,\n  cabundle: Uint8Array[],\n  now: Date,\n): Promise<ParsedCertificate> {\n  const root = parseCertificate(base64ToBytes(NITRO_ROOT_CERTIFICATE_B64));\n\n  // [leaf, INTERM_N, …, INTERM_1] — the bundle's index 0 (its root) is dropped.\n  const path = [leafDer, ...cabundle.slice(1).reverse()].map(parseCertificate);\n  const leaf = path[0];\n\n  // Each certificate is verified against the one above it, ending at the root.\n  const issuers = [...path.slice(1), root];\n\n  for (let index = 0; index < path.length; index += 1) {\n    const subject = path[index];\n    const issuer = issuers[index];\n\n    if (now < subject.notBefore || now > subject.notAfter) {\n      throw new Error(\"kit/nitro: a certificate in the chain is outside its validity window\");\n    }\n    if (!bytesEqual(subject.issuer, issuer.subject)) {\n      throw new Error(\"kit/nitro: certificate chain is not contiguous\");\n    }\n    // Every certificate that signs another must be a CA. Without this, a leaf\n    // certificate could be used to mint an apparently valid chain.\n    if (!issuer.isCertificateAuthority) {\n      throw new Error(\"kit/nitro: a non-CA certificate is used as an issuer\");\n    }\n\n    const issuerKey = await importP384PublicKey(issuer.subjectPublicKeyInfo);\n    const valid = await crypto.subtle.verify(\n      { name: \"ECDSA\", hash: \"SHA-384\" },\n      issuerKey,\n      subject.signature as unknown as BufferSource,\n      subject.tbs as unknown as BufferSource,\n    );\n    if (!valid) throw new Error(\"kit/nitro: certificate chain signature is invalid\");\n  }\n\n  if (now < root.notBefore || now > root.notAfter) {\n    throw new Error(\"kit/nitro: the pinned Nitro root certificate is expired\");\n  }\n\n  return leaf;\n}\n\nfunction importP384PublicKey(spki: Uint8Array): Promise<CryptoKey> {\n  return crypto.subtle.importKey(\n    \"spki\",\n    spki as unknown as BufferSource,\n    { name: \"ECDSA\", namedCurve: \"P-384\" },\n    false,\n    [\"verify\"],\n  );\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false;\n  let difference = 0;\n  for (let index = 0; index < a.length; index += 1) difference |= a[index] ^ b[index];\n  return difference === 0;\n}\n\nfunction toHex(bytes: Uint8Array): string {\n  let out = \"\";\n  for (const byte of bytes) out += byte.toString(16).padStart(2, \"0\");\n  return out;\n}\n\nfunction base64ToBytes(value: string): Uint8Array {\n  const binary = atob(value);\n  return Uint8Array.from(binary, (character) => character.charCodeAt(0));\n}\n","import {\n  base64UrlToBytes,\n  bytesToBase64Url,\n  bytesToUtf8,\n  utf8ToBytes,\n} from \"../crypto/encoding\";\nimport { verifyNitroAttestation, type NitroAttestationPolicy } from \"./nitro/attestation\";\n\n/**\n * Verify the enclave's attestation and return the channel key **from inside\n * it**.\n *\n * This is the security boundary of the whole flow. The key is deliberately\n * read out of the signed document rather than from the JSON field beside it:\n * that way there is nothing to cross-check, because a relay that substituted\n * a key it controls would have to produce an AWS-signed document containing\n * it. `user_data` binds the document to this session, so a document minted\n * for one session cannot be replayed as the answer to another.\n */\nexport async function verifiedChannelKey(\n  sessionId: string,\n  attestationDocumentB64: string | undefined,\n  policy: NitroAttestationPolicy,\n): Promise<Uint8Array> {\n  if (!attestationDocumentB64) {\n    throw new Error(\"kit/social-recovery: the session carried no attestation\");\n  }\n  const attestation = await verifyNitroAttestation(base64UrlToBytes(attestationDocumentB64), policy);\n\n  if (!attestation.publicKey) {\n    throw new Error(\"kit/social-recovery: the attestation carried no channel key\");\n  }\n  const expectedBinding = new Uint8Array(\n    await crypto.subtle.digest(\"SHA-256\", utf8ToBytes(sessionId) as unknown as BufferSource),\n  );\n  if (!attestation.userData || !bytesEqual(attestation.userData, expectedBinding)) {\n    throw new Error(\"kit/social-recovery: the attestation is not bound to this session\");\n  }\n  return attestation.publicKey;\n}\n\n/**\n * Encrypt a job to the attested key, hand it to `send`, and return the\n * enclave's answer opened from its sealed copy.\n *\n * Only the sealed copy is used. Any plain `result` beside it is for the control\n * plane to persist; everything on the way back here could rewrite it, and the\n * sealed copy opens only under a key this client shares with the attested\n * enclave.\n */\nexport async function runEnclaveJob<T>(\n  sessionId: string,\n  channelKey: Uint8Array,\n  job: unknown,\n  send: (encrypted: {\n    client_public_key_b64: string;\n    nonce_b64: string;\n    ciphertext_b64: string;\n  }) => Promise<any>,\n): Promise<T> {\n  const { encrypted, openResult } = await encryptForEnclave<T>(\n    sessionId,\n    channelKey,\n    utf8ToBytes(JSON.stringify(job)),\n  );\n  const response = await send(encrypted);\n  const sealed = response?.sealed_result;\n  if (typeof sealed?.nonce_b64 !== \"string\" || typeof sealed?.ciphertext_b64 !== \"string\") {\n    throw new Error(\"kit/social-recovery: the enclave's answer was not authenticated\");\n  }\n  return openResult(sealed);\n}\n\nexport async function encryptForEnclave<T = unknown>(\n  sessionId: string,\n  enclavePublicRaw: Uint8Array,\n  plaintext: Uint8Array,\n): Promise<{\n  encrypted: { client_public_key_b64: string; nonce_b64: string; ciphertext_b64: string };\n  /** Open the enclave's sealed answer to this job. */\n  openResult(sealed: { nonce_b64: string; ciphertext_b64: string }): Promise<T>;\n}> {\n  const enclavePublic = await crypto.subtle.importKey(\n    \"raw\",\n    enclavePublicRaw as unknown as BufferSource,\n    { name: \"ECDH\", namedCurve: \"P-256\" },\n    false,\n    [],\n  );\n  const client = await crypto.subtle.generateKey(\n    { name: \"ECDH\", namedCurve: \"P-256\" },\n    false,\n    [\"deriveBits\"],\n  );\n  const shared = await crypto.subtle.deriveBits(\n    { name: \"ECDH\", public: enclavePublic },\n    client.privateKey,\n    256,\n  );\n  const hkdfKey = await crypto.subtle.importKey(\"raw\", shared, \"HKDF\", false, [\"deriveKey\"]);\n  // One exchange, two keys: the request and the answer are sealed under\n  // different `info` so neither direction can be replayed as the other\n  // (RFC 9180 §9.8).\n  const channelKey = (info: string, usage: KeyUsage) =>\n    crypto.subtle.deriveKey(\n      {\n        name: \"HKDF\",\n        hash: \"SHA-256\",\n        salt: utf8ToBytes(sessionId) as unknown as BufferSource,\n        info: utf8ToBytes(info) as unknown as BufferSource,\n      },\n      hkdfKey,\n      { name: \"AES-GCM\", length: 256 },\n      false,\n      [usage],\n    );\n  const aes = await channelKey(\"cavos-confidential-channel-v1\", \"encrypt\");\n  const responseKey = await channelKey(\"cavos-confidential-channel-v1/response\", \"decrypt\");\n  const nonce = crypto.getRandomValues(new Uint8Array(12));\n  const ciphertext = await crypto.subtle.encrypt(\n    {\n      name: \"AES-GCM\",\n      iv: nonce as unknown as BufferSource,\n      additionalData: utf8ToBytes(sessionId) as unknown as BufferSource,\n    },\n    aes,\n    plaintext as unknown as BufferSource,\n  );\n  const clientPublic = new Uint8Array(\n    await crypto.subtle.exportKey(\"raw\", client.publicKey),\n  );\n  return {\n    encrypted: {\n      client_public_key_b64: bytesToBase64Url(clientPublic),\n      nonce_b64: bytesToBase64Url(nonce),\n      ciphertext_b64: bytesToBase64Url(new Uint8Array(ciphertext)),\n    },\n    async openResult(sealed) {\n      let plaintext: ArrayBuffer;\n      try {\n        plaintext = await crypto.subtle.decrypt(\n          {\n            name: \"AES-GCM\",\n            iv: base64UrlToBytes(sealed.nonce_b64) as unknown as BufferSource,\n            additionalData: utf8ToBytes(sessionId) as unknown as BufferSource,\n          },\n          responseKey,\n          base64UrlToBytes(sealed.ciphertext_b64) as unknown as BufferSource,\n        );\n      } catch {\n        throw new Error(\"kit/social-recovery: the enclave's answer failed authentication\");\n      }\n      return JSON.parse(bytesToUtf8(new Uint8Array(plaintext))) as T;\n    },\n  };\n}\n\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n  if (a.length !== b.length) return false;\n  let difference = 0;\n  for (let index = 0; index < a.length; index += 1) difference |= a[index] ^ b[index];\n  return difference === 0;\n}\n","import { bytesToBase64Url } from \"../crypto/encoding\";\nimport type { SocialRecoveryCredential } from \"./SocialRecoveryCredential\";\nimport type { NitroAttestationPolicy } from \"./nitro/attestation\";\nimport { runEnclaveJob, verifiedChannelKey } from \"./enclaveChannel\";\n\nexport type SocialRecoveryProvider = \"google\" | \"apple\" | \"email\";\nexport type SocialRecoveryAction = \"enroll\" | \"recover\";\n\n/**\n * Which enclave this build will talk to. See `attestationDefaults.ts`.\n */\nexport type AttestationPolicy = NitroAttestationPolicy;\n\nexport interface SocialRecoveryClientOptions {\n  baseUrl: string;\n  appId: string;\n  environment?: \"development\" | \"production\";\n  /**\n   * Values pinned by the developer from the Cavos environment configuration.\n   * They must not be learned from the same control plane being attested.\n   */\n  attestation: AttestationPolicy;\n}\n\nexport interface ProviderPolicy {\n  app_id: string;\n  environment_id: string;\n  provider: SocialRecoveryProvider;\n  issuer: string;\n  audience: string;\n  jwks_uri: string;\n}\n\nexport type ChainAuthorization =\n  | {\n      chain: \"starknet\";\n      chain_id_hex: string;\n      account_hex: string;\n      new_x_hex: string;\n      new_y_hex: string;\n      recovery_nonce: string;\n      expires_at: number;\n    }\n  | {\n      chain: \"solana\";\n      account_b58_bytes_b64: string;\n      new_pubkey_b64: string;\n      /** Decimal u64 string; JavaScript numbers cannot represent every nonce. */\n      recovery_nonce: string;\n      expires_at: number;\n    };\n\nexport interface SocialRecoveryResult {\n  result: \"enrolled\" | \"recovered\" | \"confirmed\";\n  [key: string]: unknown;\n}\n\n/**\n * A started session. The enclave is already running, so this arrives ready and\n * attested in the same response — there is no `starting` state to wait out.\n */\ninterface StartedSession {\n  session_id: string;\n  provider: SocialRecoveryProvider;\n  policy: ProviderPolicy;\n  ephemeral_public_key_b64?: string;\n  attestation_document_b64?: string;\n  /**\n   * The wallet's existing record: always present for a recovery, and present\n   * for an enrolment when the wallet already has one.\n   */\n  sealed_record_b64?: string;\n}\n\n/**\n * Talks to the Cavos recovery enclave.\n *\n * The OIDC credential is encrypted in-browser to a P-256 key held only by an\n * AWS Nitro Enclave whose measurement this build pins. The Cavos API and the\n * enclave's parent instance relay ciphertext and are not trusted with any of it.\n *\n * Two round trips, both synchronous: start a session, then run the job. The\n * previous Confidential Space transport had to prewarm a VM before login and\n * then poll two endpoints for up to two minutes while it booted.\n */\nexport class SocialRecoveryClient {\n  constructor(private readonly opts: SocialRecoveryClientOptions) {}\n\n  async lookupDekEnrollment(params: {\n    provider: SocialRecoveryCredential[\"provider\"];\n    subject: string;\n    /** Proves the caller is `subject`; the answer names that person's wallet. */\n    idToken: string;\n  }): Promise<{ wallet_address: string } | null> {\n    const query = new URLSearchParams({\n      app_id: this.opts.appId,\n      provider: params.provider,\n      subject: params.subject,\n    });\n    if (this.opts.environment) query.set(\"environment\", this.opts.environment);\n    let row: { enrolled?: unknown; wallet_address?: unknown } | null = null;\n    const url = new URL(\"/api/recovery/social/enrollment\", this.opts.baseUrl);\n    url.search = query.toString();\n    try {\n      const response = await fetch(url, {\n        headers: { Accept: \"application/json\", Authorization: `Bearer ${params.idToken}` },\n      });\n      if (!response.ok) return null;\n      row = await response.json();\n    } catch {\n      return null;\n    }\n    if (!row?.enrolled || typeof row.wallet_address !== \"string\" || !row.wallet_address) {\n      return null;\n    }\n    return { wallet_address: row.wallet_address };\n  }\n\n  async enroll(params: {\n    walletAddress: string;\n    credential: SocialRecoveryCredential;\n    dek?: Uint8Array;\n  }): Promise<{ sessionId: string; result: SocialRecoveryResult }> {\n    const session = await this.start(\n      params.walletAddress,\n      \"enroll\",\n      params.credential,\n      Boolean(params.dek),\n    );\n    const channelKey = await verifiedChannelKey(\n      session.session_id,\n      session.attestation_document_b64,\n      this.opts.attestation,\n    );\n    if (session.sealed_record_b64) {\n      // The wallet already has a record. What it holds is the enclave's to say,\n      // not the control plane's: a resumed Starknet enrolment installs this\n      // public key on-chain for good, and \"already protected\" is only true if\n      // the record really is this identity's and seals this device's DEK.\n      const result = await this.runJob(session.session_id, channelKey, {\n        action: \"confirm\",\n        credential: jobCredential(params.credential),\n        sealed_record_b64: session.sealed_record_b64,\n        ...(params.dek ? { stellar_dek_b64: bytesToBase64Url(params.dek) } : {}),\n      });\n      return { sessionId: session.session_id, result };\n    }\n    const result = await this.runJob(session.session_id, channelKey, {\n      action: \"enroll\",\n      credential: jobCredential(params.credential),\n      policy: session.policy,\n      ...(params.dek ? { stellar_dek_b64: bytesToBase64Url(params.dek) } : {}),\n    });\n    return { sessionId: session.session_id, result };\n  }\n\n  async recover(params: {\n    walletAddress: string;\n    credential: SocialRecoveryCredential;\n    authorizations?: ChainAuthorization[];\n    recipientPublicSec1?: Uint8Array;\n  }): Promise<{ sessionId: string; result: SocialRecoveryResult }> {\n    const session = await this.start(\n      params.walletAddress,\n      \"recover\",\n      params.credential,\n    );\n    if (!session.sealed_record_b64) {\n      throw new Error(\"kit/social-recovery: enrollment record is missing\");\n    }\n\n    const channelKey = await verifiedChannelKey(\n      session.session_id,\n      session.attestation_document_b64,\n      this.opts.attestation,\n    );\n    const result = await this.runJob(session.session_id, channelKey, {\n      action: \"recover\",\n      credential: jobCredential(params.credential),\n      sealed_record_b64: session.sealed_record_b64,\n      authorizations: params.authorizations ?? [],\n      ...(params.recipientPublicSec1\n        ? { stellar_recipient_pubkey_b64: bytesToBase64Url(params.recipientPublicSec1) }\n        : {}),\n    });\n    return { sessionId: session.session_id, result };\n  }\n\n  async confirmEnrollment(sessionId: string, txHash: string): Promise<void> {\n    await this.fetchJson(`/api/recovery/social/sessions/${sessionId}/confirm`, {\n      method: \"POST\",\n      body: JSON.stringify({ tx_hash: txHash }),\n    });\n  }\n\n  private start(\n    walletAddress: string,\n    action: SocialRecoveryAction,\n    credential: SocialRecoveryCredential,\n    dekEnroll = false,\n  ): Promise<StartedSession> {\n    return this.fetchJson(\"/api/recovery/social/sessions\", {\n      method: \"POST\",\n      body: JSON.stringify({\n        app_id: this.opts.appId,\n        ...(this.opts.environment ? { environment: this.opts.environment } : {}),\n        wallet_address: walletAddress,\n        action,\n        // An app may offer every provider, so the one this credential came from\n        // decides the policy. Control planes predating that ignore the field and\n        // fall back to the environment's single configured provider.\n        provider: credential.provider,\n        auth_challenge: credential.tokenFingerprint,\n        ...(dekEnroll ? { dek_enroll: true } : {}),\n      }),\n    });\n  }\n\n  private async runJob(\n    sessionId: string,\n    channelKey: Uint8Array,\n    job: unknown,\n  ): Promise<SocialRecoveryResult> {\n    return runEnclaveJob<SocialRecoveryResult>(sessionId, channelKey, job, (encrypted) =>\n      this.fetchJson(`/api/recovery/social/sessions/${sessionId}/job`, {\n        method: \"POST\",\n        body: JSON.stringify(encrypted),\n      }),\n    );\n  }\n\n  private async fetchJson(path: string, init?: RequestInit): Promise<any> {\n    const response = await fetch(new URL(path, this.opts.baseUrl), {\n      ...init,\n      headers: { \"Content-Type\": \"application/json\", ...(init?.headers ?? {}) },\n    });\n    if (!response.ok) {\n      const body = await response.text().catch(() => \"\");\n      throw new Error(`kit/social-recovery: ${path} -> ${response.status} ${body}`);\n    }\n    return response.json();\n  }\n}\n\n/**\n * The credential as the enclave reads it.\n *\n * `provider` is the credential's own, read from the token's `iss`, not one the\n * server echoed back: the enclave refuses a job whose credential provider\n * differs from its policy before it checks anything else.\n */\nfunction jobCredential(credential: SocialRecoveryCredential) {\n  return {\n    provider: credential.provider,\n    id_token: credential.idToken,\n    token_fingerprint: credential.tokenFingerprint,\n    ...(credential.noncePreimage ? { nonce_preimage: credential.noncePreimage } : {}),\n  };\n}\n","import { sha256 } from \"@noble/hashes/sha256\";\n\n/**\n * Fixed PRF input salt — scopes the derived secret to the classic-G DEK factor.\n *\n * Stable forever: changing it changes every existing user's passkey secret.\n * Shared so the credential that registers as an on-chain approver and the one\n * that unwraps the Stellar DEK can be the same passkey — they were two separate\n * `credentials.create()` calls, which is two prompts and, worse, two passkeys in\n * the user's account for one wallet.\n */\nexport const PRF_SALT = sha256(new TextEncoder().encode(\"cavos-stellar-prf-v1\"));\n","import { sha256 } from \"@noble/hashes/sha256\";\nimport type { PasskeyEnrollParams, PasskeyPrfProvider } from \"../../signer/PasskeyProvider\";\nimport { PRF_SALT } from \"../../signer/prfSalt\";\n\n/**\n * WebAuthn **PRF** factor for the classic-G envelope.\n *\n * Unlike the Soroban passkey path (which needs an on-chain-verifiable *assertion\n * signature*), the classic-G account only needs a stable 32-byte secret to wrap\n * the DEK — exactly what the WebAuthn PRF extension provides: for a given\n * credential + input salt the authenticator returns the same 32 bytes on every\n * device the passkey syncs to (iCloud Keychain / Google Password Manager), and\n * that secret is derived inside the authenticator and never derivable by Cavos or\n * OAuth. That makes it the ideal synced anchor to approve a new device or recover.\n *\n * `getSecret()` returns the raw PRF output; callers pass it to\n * `derivePasskeyKEK` (via `CavosStellar.enrollPasskey` /\n * `approveThisDeviceWithPasskey`). Keeping this class free of any DEK/KEK logic\n * lets the account class stay runtime-agnostic and unit-testable.\n */\n\nexport interface PasskeyPrfOptions {\n  /** Relying-Party id (usually the eTLD+1). Defaults to `window.location.hostname`. */\n  rpId?: string;\n  /** Human-readable RP name shown in the OS passkey UI. */\n  rpName?: string;\n}\n\nexport type PasskeyPrfEnrollParams = PasskeyEnrollParams;\n\n\n\nexport class PasskeyPrf implements PasskeyPrfProvider {\n  private readonly rpId: string;\n  private readonly rpName: string;\n\n  constructor(opts: PasskeyPrfOptions = {}) {\n    if (typeof window === \"undefined\" || !navigator.credentials) {\n      throw new Error(\"kit/passkey-prf: WebAuthn is only available in a browser\");\n    }\n    this.rpId = opts.rpId ?? window.location.hostname;\n    this.rpName = opts.rpName ?? this.rpId;\n    if (isIpAddress(this.rpId)) {\n      throw new Error(\n        `kit/passkey-prf: passkeys can't use an IP address as the domain (\"${this.rpId}\"). ` +\n          \"Use http://localhost, a real HTTPS domain, or a tunnel — or pass an explicit `rpId`.\",\n      );\n    }\n  }\n\n  /** True if this platform advertises a usable passkey (platform authenticator). */\n  static async isSupported(): Promise<boolean> {\n    if (typeof window === \"undefined\" || !window.PublicKeyCredential) return false;\n    try {\n      return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Create a new synced, discoverable passkey with the PRF extension enabled, then\n   * immediately read its PRF secret. Returns the credential id and the 32-byte\n   * secret so the caller can enroll the passkey factor in one step. Some\n   * authenticators don't return PRF results on create — in that case `secret` is\n   * undefined and the caller should follow up with `getSecret()`.\n   */\n  async enroll(params: PasskeyPrfEnrollParams): Promise<{ credentialId: Uint8Array; secret?: Uint8Array }> {\n    const cred = (await navigator.credentials.create({\n      publicKey: {\n        challenge: buf(crypto.getRandomValues(new Uint8Array(32))),\n        rp: { id: this.rpId, name: this.rpName },\n        user: {\n          id: buf(userHandle(params.userId)),\n          name: params.userName,\n          displayName: params.displayName ?? params.userName,\n        },\n        pubKeyCredParams: [{ type: \"public-key\", alg: -7 }], // ES256 (P-256)\n        authenticatorSelection: {\n          residentKey: \"required\",\n          requireResidentKey: true,\n          userVerification: \"required\",\n        },\n        attestation: \"none\",\n        extensions: { prf: { eval: { first: buf(PRF_SALT) } } } as AuthenticationExtensionsClientInputs,\n      },\n    })) as PublicKeyCredential | null;\n    if (!cred) throw new Error(\"kit/passkey-prf: enrollment cancelled\");\n    return { credentialId: new Uint8Array(cred.rawId), secret: readPrf(cred) };\n  }\n\n  /**\n   * Get the passkey's 32-byte PRF secret. Uses discoverable credentials (no\n   * `allowCredentials`), so it works from a brand-new browser — the OS shows the\n   * synced passkey picker. Throws if the authenticator doesn't support PRF.\n   */\n  async getSecret(credentialId?: Uint8Array): Promise<Uint8Array> {\n    const cred = (await navigator.credentials.get({\n      publicKey: {\n        challenge: buf(crypto.getRandomValues(new Uint8Array(32))),\n        rpId: this.rpId,\n        // Pinned to one credential when the caller knows which: enrolment has\n        // just created the passkey, and letting the picker offer a different\n        // one would derive a secret that unwraps nothing.\n        allowCredentials: credentialId\n          ? [{ type: \"public-key\" as const, id: buf(credentialId) }]\n          : [],\n        userVerification: \"required\",\n        extensions: { prf: { eval: { first: buf(PRF_SALT) } } } as AuthenticationExtensionsClientInputs,\n      },\n    })) as PublicKeyCredential | null;\n    if (!cred) throw new Error(\"kit/passkey-prf: assertion cancelled\");\n    const secret = readPrf(cred);\n    if (!secret) {\n      throw new Error(\n        \"kit/passkey-prf: this authenticator did not return a PRF result — PRF is unsupported here\",\n      );\n    }\n    return secret;\n  }\n}\n\n/** Read the 32-byte PRF `first` result from a credential's extension results. */\nfunction readPrf(cred: PublicKeyCredential): Uint8Array | undefined {\n  const results = (cred.getClientExtensionResults() as { prf?: { results?: { first?: ArrayBuffer } } }).prf\n    ?.results?.first;\n  return results ? new Uint8Array(results) : undefined;\n}\n\nfunction isIpAddress(host: string): boolean {\n  if (/^\\d{1,3}(\\.\\d{1,3}){3}$/.test(host)) return true;\n  if (host.includes(\":\")) return true;\n  return false;\n}\n\nfunction userHandle(userId: string): Uint8Array {\n  const bytes = new TextEncoder().encode(userId);\n  return bytes.length <= 64 ? bytes : sha256(bytes);\n}\n\nfunction buf(bytes: Uint8Array): BufferSource {\n  return bytes.slice() as unknown as BufferSource;\n}\n"]}