micro509 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/CHANGELOG.md +88 -1
  2. package/dist/crypto/crypto.d.ts +11 -2
  3. package/dist/crypto/crypto.js +30 -17
  4. package/dist/crypto/crypto.js.map +1 -1
  5. package/dist/crypto.d.ts +2 -2
  6. package/dist/der/der.js.map +1 -1
  7. package/dist/index.d.ts +6 -5
  8. package/dist/internal/asn1/asn1.js +10 -2
  9. package/dist/internal/asn1/asn1.js.map +1 -1
  10. package/dist/internal/asn1/ber.js.map +1 -1
  11. package/dist/internal/asn1/decode-refusal.js.map +1 -1
  12. package/dist/internal/asn1/der.js.map +1 -1
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  15. package/dist/internal/crypto/ecdsa.js.map +1 -1
  16. package/dist/internal/crypto/hash.js.map +1 -1
  17. package/dist/internal/crypto/pbes2.js.map +1 -1
  18. package/dist/internal/crypto/prime-ec.js.map +1 -1
  19. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  20. package/dist/internal/crypto/sig-verify.d.ts +40 -0
  21. package/dist/internal/crypto/sig-verify.js +152 -65
  22. package/dist/internal/crypto/sig-verify.js.map +1 -1
  23. package/dist/internal/crypto/signing.js.map +1 -1
  24. package/dist/internal/jose/base64url.js.map +1 -1
  25. package/dist/internal/jose/json-data.js.map +1 -1
  26. package/dist/internal/jose/strict-json.js.map +1 -1
  27. package/dist/internal/shared/base64.js.map +1 -1
  28. package/dist/internal/shared/dn.js.map +1 -1
  29. package/dist/internal/shared/idna.js.map +1 -1
  30. package/dist/internal/shared/ip.js.map +1 -1
  31. package/dist/internal/shared/mailbox.js.map +1 -1
  32. package/dist/internal/shared/punycode.js.map +1 -1
  33. package/dist/internal/shared/uri-host.js.map +1 -1
  34. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  35. package/dist/internal/verify/policy-engine.js.map +1 -1
  36. package/dist/internal/verify/spki-distrust.js.map +1 -1
  37. package/dist/internal/verify/verify-path.js +222 -116
  38. package/dist/internal/verify/verify-path.js.map +1 -1
  39. package/dist/internal/x509/directory-name.js.map +1 -1
  40. package/dist/internal/x509/extension-bits.js.map +1 -1
  41. package/dist/internal/x509/extension-errors.js.map +1 -1
  42. package/dist/internal/x509/extension-registry.js.map +1 -1
  43. package/dist/internal/x509/general-name-profile.js.map +1 -1
  44. package/dist/internal/x509/general-name.js.map +1 -1
  45. package/dist/internal/x509/name-fields.js.map +1 -1
  46. package/dist/internal/x509/or-address.js.map +1 -1
  47. package/dist/jose/base64url.js.map +1 -1
  48. package/dist/jose/errors.js.map +1 -1
  49. package/dist/jose/jwe.js.map +1 -1
  50. package/dist/jose/jwks.js.map +1 -1
  51. package/dist/jose/jws.js.map +1 -1
  52. package/dist/jose/jwt.js.map +1 -1
  53. package/dist/jose/remote-jwks.js.map +1 -1
  54. package/dist/kdf/argon2-arithmetic.js.map +1 -1
  55. package/dist/kdf/argon2-core.js.map +1 -1
  56. package/dist/kdf/argon2-memory.js.map +1 -1
  57. package/dist/kdf/argon2-portable.js.map +1 -1
  58. package/dist/kdf/argon2.js.map +1 -1
  59. package/dist/keys/keys.js.map +1 -1
  60. package/dist/pem/pem.js.map +1 -1
  61. package/dist/pkcs/pfx.js.map +1 -1
  62. package/dist/pkcs/pkcs12-mac.js +1 -1
  63. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  64. package/dist/pkcs/pkcs7.d.ts +10 -0
  65. package/dist/pkcs/pkcs7.js +106 -88
  66. package/dist/pkcs/pkcs7.js.map +1 -1
  67. package/dist/result/result.js.map +1 -1
  68. package/dist/revocation/chain.d.ts +67 -13
  69. package/dist/revocation/chain.js +429 -301
  70. package/dist/revocation/chain.js.map +1 -1
  71. package/dist/revocation/crl.d.ts +65 -11
  72. package/dist/revocation/crl.js +492 -202
  73. package/dist/revocation/crl.js.map +1 -1
  74. package/dist/revocation/ocsp.d.ts +79 -24
  75. package/dist/revocation/ocsp.js +417 -231
  76. package/dist/revocation/ocsp.js.map +1 -1
  77. package/dist/revocation/revocation.d.ts +68 -13
  78. package/dist/revocation/revocation.js +194 -73
  79. package/dist/revocation/revocation.js.map +1 -1
  80. package/dist/revocation.d.ts +4 -4
  81. package/dist/ssh/ssh.js.map +1 -1
  82. package/dist/ssh/wire.js.map +1 -1
  83. package/dist/verify/identity.d.ts +2 -2
  84. package/dist/verify/identity.js +2 -2
  85. package/dist/verify/identity.js.map +1 -1
  86. package/dist/verify/verify.d.ts +84 -32
  87. package/dist/verify/verify.js +221 -171
  88. package/dist/verify/verify.js.map +1 -1
  89. package/dist/verify.d.ts +3 -2
  90. package/dist/x509/certificate.js.map +1 -1
  91. package/dist/x509/csr.js.map +1 -1
  92. package/dist/x509/extensions.js.map +1 -1
  93. package/dist/x509/fingerprint.js.map +1 -1
  94. package/dist/x509/name-text.js.map +1 -1
  95. package/dist/x509/name.js.map +1 -1
  96. package/dist/x509/parse.d.ts +6 -2
  97. package/dist/x509/parse.js +121 -121
  98. package/dist/x509/parse.js.map +1 -1
  99. package/package.json +11 -11
@@ -1 +1 @@
1
- {"version":3,"file":"pem.js","names":["PEM_LABEL_PATTERN","label","base64Encode","der","lines","pem","begin","throwMicro509Error","bodyLines","base64Decode","error","rethrowIfInvariant","input","block","normalized","blocks","openBlock","lineStart","newline","lineEnd","nextLineStart","line","beginLine","beginLabel","endLabel","end","certificates","certificateRequests","privateKeys","publicKeys","others","nonEmptyLines","prefix","kind","withoutSurroundingWsp","index","RFC822_FIELD_NAME","character","value","headers","foldedName","delimiter","headerName","successResult","operation","failureResult","fallbackMessage"],"sources":["../../src/pem/pem.ts"],"sourcesContent":["/**\n * PEM helpers used across the public API.\n *\n * Encodes, decodes, splits, and categorizes PEM blocks as defined by\n * RFC 7468.\n *\n * @module\n */\n\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport {\n\tfailureResult,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n} from '#micro509/result/result';\n\n/** A single decoded PEM block with its label, decoded DER bytes, and original PEM text. */\nexport interface PemBlock {\n\t/** RFC 7468 label between the `BEGIN` / `END` markers (e.g. `\"CERTIFICATE\"`). */\n\treadonly label: string;\n\t/** Decoded DER content of this block. */\n\treadonly bytes: Uint8Array;\n\t/** The original PEM text including `BEGIN`/`END` lines. */\n\treadonly pem: string;\n}\n\n/**\n * PEM blocks grouped by their label into well-known PKI categories.\n * Blocks that don't match any known label land in {@linkcode others}.\n */\nexport interface CategorizedPemBlocks {\n\t/** Blocks with label `CERTIFICATE`. */\n\treadonly certificates: readonly PemBlock[];\n\t/** Blocks with label `CERTIFICATE REQUEST`. */\n\treadonly certificateRequests: readonly PemBlock[];\n\t/** Blocks with label `PRIVATE KEY`, `RSA PRIVATE KEY`, or `EC PRIVATE KEY`. */\n\treadonly privateKeys: readonly PemBlock[];\n\t/** Blocks with label `PUBLIC KEY`. */\n\treadonly publicKeys: readonly PemBlock[];\n\t/** Blocks whose label doesn't match any of the above categories. */\n\treadonly others: readonly PemBlock[];\n}\n\n// RFC 7468 §3 label ABNF: labelchar = %x21-2C / %x2E-7E, joined by an optional\n// single \"-\" or SP; an empty label is legal.\nconst PEM_LABEL_PATTERN = /^(?:[!-,.-~](?:[- ]?[!-,.-~])*)?$/;\n\n/**\n * Wraps DER bytes in a PEM envelope with 64-character base64 lines.\n *\n * @param label PEM type label (e.g. `\"CERTIFICATE\"`, `\"PRIVATE KEY\"`).\n * @param der Raw DER-encoded content.\n */\nexport function pemEncode(label: string, der: Uint8Array): string {\n\tif (!isPemLabel(label)) {\n\t\tthrow new Error('Invalid PEM label');\n\t}\n\tconst body = base64Encode(der);\n\tconst lines = body.match(/.{1,64}/g) ?? [];\n\treturn `-----BEGIN ${label}-----\\n${lines.join('\\n')}\\n-----END ${label}-----\\n`;\n}\n\n/** Machine-readable failure reason for the PEM decoders. */\nexport type PemErrorCode = 'malformed';\n\n/** Structured failure payload for PEM decoding. */\nexport interface PemFailure extends Micro509Error<PemErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode pemDecode}. */\nexport type PemDecodeResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode splitPemBlocks}. */\nexport type SplitPemBlocksResult =\n\t| { readonly ok: true; readonly value: readonly PemBlock[] }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode categorizePemBlocks}. */\nexport type CategorizePemBlocksResult =\n\t| { readonly ok: true; readonly value: CategorizedPemBlocks }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/**\n * Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the\n * DER content from a PEM string. Text ahead of the `BEGIN` line is ignored.\n * Throws if the `BEGIN`/`END` markers don't match `label`.\n *\n * @param label Expected PEM type label.\n * @param pem PEM-encoded text (may contain `\\r`).\n */\nexport function pemDecodeOrThrow(label: string, pem: string): Uint8Array {\n\tconst normalized = trimPemDocument(pem.replace(/\\r\\n?/g, '\\n'));\n\tconst lines = normalized.split('\\n');\n\tconst begin = findPreEncapsulationBoundary(lines);\n\tif (\n\t\tbegin === undefined ||\n\t\tparsePemBoundaryLine(lines[begin] ?? '', 'BEGIN') !== label ||\n\t\tparsePemBoundaryLine(lines[lines.length - 1] ?? '', 'END') !== label ||\n\t\tlines.length - begin < 3\n\t) {\n\t\tthrowMicro509Error('malformed', `Invalid PEM for ${label}`, {\n\t\t\tstage: 'pem',\n\t\t\treason: 'invalid_armor',\n\t\t} as const);\n\t}\n\tconst bodyLines = normalizePemBodyLines(lines.slice(begin + 1, -1));\n\tif (bodyLines === undefined) {\n\t\tthrowMicro509Error('malformed', `Invalid PEM for ${label}`, {\n\t\t\tstage: 'base64',\n\t\t\treason: 'invalid_base64',\n\t\t} as const);\n\t}\n\ttry {\n\t\treturn base64Decode(bodyLines.join(''));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tthrowMicro509Error('malformed', `Invalid PEM for ${label}`, {\n\t\t\tstage: 'base64',\n\t\t\treason: 'invalid_base64',\n\t\t} as const);\n\t}\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns\n * them as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files\n * and ignores non-PEM text between blocks.\n */\nexport function splitPemBlocksOrThrow(input: string): readonly PemBlock[] {\n\treturn splitPemTextBlocksOrThrow(input).map((block) => ({\n\t\t...block,\n\t\tbytes: pemDecodeOrThrow(block.label, block.pem),\n\t}));\n}\n\n/** @internal A bounded-by-input PEM block before decoding its body. */\nexport interface PemTextBlock {\n\treadonly label: string;\n\treadonly pem: string;\n}\n\n/** @internal Shares the ordinary boundary scanner, retaining legacy encrypted bodies verbatim. */\nexport function splitPemTextBlocksOrThrow(input: string): readonly PemTextBlock[] {\n\tconst normalized = input.replace(/^\\uFEFF/, '').replace(/\\r\\n?/g, '\\n');\n\tconst blocks: PemTextBlock[] = [];\n\tlet openBlock: { readonly label: string; readonly start: number } | undefined;\n\tlet lineStart = 0;\n\twhile (lineStart < normalized.length) {\n\t\tconst newline = normalized.indexOf('\\n', lineStart);\n\t\tconst lineEnd = newline === -1 ? normalized.length : newline;\n\t\tconst nextLineStart = newline === -1 ? normalized.length : newline + 1;\n\t\tconst line = normalized.slice(lineStart, lineEnd);\n\t\tconst beginLine = line.replace(/^[ \\t]+/, '');\n\t\tconst beginLabel = parsePemBoundaryLine(line, 'BEGIN');\n\t\tconst endLabel = parsePemBoundaryLine(line, 'END');\n\n\t\tif (beginLabel !== undefined) {\n\t\t\tif (openBlock !== undefined) {\n\t\t\t\tthrow new Error('Malformed PEM block');\n\t\t\t}\n\t\t\topenBlock = { label: beginLabel, start: lineStart + line.length - beginLine.length };\n\t\t} else if (endLabel !== undefined) {\n\t\t\tblocks.push(closePemBlock(normalized, openBlock, endLabel, nextLineStart));\n\t\t\topenBlock = undefined;\n\t\t} else if (looksLikePemBoundary(line)) {\n\t\t\tthrow new Error('Malformed PEM block');\n\t\t}\n\n\t\tif (newline === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tlineStart = nextLineStart;\n\t}\n\tif (openBlock !== undefined) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\treturn blocks;\n}\n\nfunction closePemBlock(\n\tinput: string,\n\topenBlock: { readonly label: string; readonly start: number } | undefined,\n\tendLabel: string,\n\tend: number,\n): PemTextBlock {\n\tif (openBlock === undefined || openBlock.label !== endLabel) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\tconst pem = input.slice(openBlock.start, end);\n\treturn {\n\t\tlabel: openBlock.label,\n\t\tpem,\n\t};\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n */\nexport function categorizePemBlocksOrThrow(\n\tinput: string | readonly PemBlock[],\n): CategorizedPemBlocks {\n\tconst blocks = typeof input === 'string' ? splitPemBlocksOrThrow(input) : input;\n\tconst certificates: PemBlock[] = [];\n\tconst certificateRequests: PemBlock[] = [];\n\tconst privateKeys: PemBlock[] = [];\n\tconst publicKeys: PemBlock[] = [];\n\tconst others: PemBlock[] = [];\n\n\tfor (const block of blocks) {\n\t\tswitch (block.label) {\n\t\t\tcase 'CERTIFICATE':\n\t\t\t\tcertificates.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'CERTIFICATE REQUEST':\n\t\t\t\tcertificateRequests.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PRIVATE KEY':\n\t\t\tcase 'RSA PRIVATE KEY':\n\t\t\tcase 'EC PRIVATE KEY':\n\t\t\t\tprivateKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PUBLIC KEY':\n\t\t\t\tpublicKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tothers.push(block);\n\t\t}\n\t}\n\n\treturn { certificates, certificateRequests, privateKeys, publicKeys, others };\n}\n\nfunction normalizePemBodyLines(lines: readonly string[]): readonly string[] | undefined {\n\tconst normalizedLines = lines.map((line) => line.replace(/[ \\t]/g, ''));\n\tconst nonEmptyLines = normalizedLines.filter((line) => line !== '');\n\tif (nonEmptyLines.length === 0) {\n\t\treturn [''];\n\t}\n\treturn nonEmptyLines.every((line) => /^[A-Za-z0-9+/=]+$/.test(line)) ? nonEmptyLines : undefined;\n}\n\nfunction parsePemBoundaryLine(line: string, kind: 'BEGIN' | 'END'): string | undefined {\n\tconst prefix = `-----${kind} `;\n\tconst withoutSurroundingWsp = trimLwsp(line);\n\tif (!withoutSurroundingWsp.startsWith(prefix) || !withoutSurroundingWsp.endsWith('-----')) {\n\t\treturn undefined;\n\t}\n\tconst label = withoutSurroundingWsp.slice(prefix.length, -5);\n\treturn isPemLabel(label) ? label : undefined;\n}\n\n/** RFC 7468 §2: data before the encapsulation boundaries is permitted. */\nfunction findPreEncapsulationBoundary(lines: readonly string[]): number | undefined {\n\tfor (const [index, line] of lines.entries()) {\n\t\tif (parsePemBoundaryLine(line, 'BEGIN') !== undefined) {\n\t\t\treturn index;\n\t\t}\n\t\tif (looksLikePemBoundary(line)) {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction looksLikePemBoundary(line: string): boolean {\n\treturn /^[ \\t]*-{5,}(?:BEGIN|END)/.test(line);\n}\n\n/** RFC 822 §3.2: `field-name = 1*<any CHAR, excluding CTLs, SPACE, and \":\">`. */\nconst RFC822_FIELD_NAME = /^[\\x21-\\x39\\x3b-\\x7e]+$/;\n\n/** RFC 822 §3.3: `LWSP-char = SPACE / HTAB`. */\nfunction isLwspChar(character: string): boolean {\n\treturn character === ' ' || character === '\\t';\n}\n\n/**\n * Strips the whitespace surrounding a PEM document: `LWSP-char`s and the line\n * terminators that separate the boundary lines from the body.\n *\n * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode\n * `Zs`, making those characters acceptable at a document edge while\n * {@linkcode parsePemBoundaryLine} rejects them everywhere else.\n */\nfunction trimPemDocument(value: string): string {\n\treturn value.replace(/^[ \\t\\n]+|[ \\t\\n]+$/g, '');\n}\n\n/**\n * @internal Strips surrounding RFC 822 §3.3 `LWSP-char`s.\n *\n * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode `Zs`,\n * none of which the grammar admits.\n */\nexport function trimLwsp(value: string): string {\n\treturn value.replace(/^[ \\t]+|[ \\t]+$/g, '');\n}\n\n/** A PEM block carrying RFC 1421 §4.6 encapsulated headers ahead of its body. */\nexport interface TraditionalPemBlock {\n\t/** PEM type label between the `BEGIN` / `END` markers. */\n\treadonly label: string;\n\t/** Encapsulated headers (e.g. `Proc-Type`, `DEK-Info`), unfolded. */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n}\n\n/**\n * @internal Parses a PEM block with RFC 1421 §4.6 encapsulated headers.\n *\n * RFC 7468 §2 forbids headers, so this path exists only for the legacy\n * OpenSSL-style encrypted PKCS#1 and SEC1 blocks that predate it.\n */\nexport function parseTraditionalPemOrThrow(pem: string): TraditionalPemBlock {\n\tconst normalized = trimPemDocument(pem.replace(/\\r\\n?/g, '\\n'));\n\tconst lines = normalized.split('\\n');\n\tconst label = parsePemBoundaryLine(lines[0] ?? '', 'BEGIN');\n\tif (label === undefined || lines.length < 2) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tif (parsePemBoundaryLine(lines[lines.length - 1] ?? '', 'END') !== label) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\tlet foldedName: string | undefined;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (foldedName !== undefined && isLwspChar(line.charAt(0))) {\n\t\t\theaders.set(foldedName, `${headers.get(foldedName) ?? ''}${line}`);\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst delimiter = line.indexOf(':');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (!RFC822_FIELD_NAME.test(headerName)) {\n\t\t\tthrow new Error(`Invalid PEM header name: ${headerName}`);\n\t\t}\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 1).replace(/^[ \\t]+/, ''));\n\t\tfoldedName = headerName;\n\t\tindex += 1;\n\t}\n\treturn { label, headers, base64Body: lines.slice(index, lines.length - 1).join('') };\n}\n\nfunction isPemLabel(label: string): boolean {\n\treturn PEM_LABEL_PATTERN.exec(label)?.[0] === label;\n}\n\n/**\n * Extracts and base64-decodes the DER content from a PEM string.\n * Text ahead of the `BEGIN` line is ignored.\n *\n * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`\n * markers don't match `label` or the body is not valid base64. For the\n * throwing form use {@linkcode pemDecodeOrThrow}.\n */\nexport function pemDecode(label: string, pem: string): PemDecodeResult {\n\treturn toPemResult(() => pemDecodeOrThrow(label, pem), 'Invalid PEM');\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them\n * as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files and\n * ignores non-PEM text between blocks.\n *\n * Returns a typed failure (`code: 'malformed'`) on stray or truncated PEM\n * markers. For the throwing form use {@linkcode splitPemBlocksOrThrow}.\n */\nexport function splitPemBlocks(input: string): SplitPemBlocksResult {\n\treturn toPemResult(() => splitPemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n *\n * Returns a typed failure (`code: 'malformed'`) when raw text contains stray\n * or truncated PEM markers. For the throwing form use\n * {@linkcode categorizePemBlocksOrThrow}.\n */\nexport function categorizePemBlocks(\n\tinput: string | readonly PemBlock[],\n): CategorizePemBlocksResult {\n\treturn toPemResult(() => categorizePemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/** Shared Result wrapper around the throwing PEM cores. */\nfunction toPemResult<TValue>(\n\toperation: () => TValue,\n\tfallbackMessage: string,\n):\n\t| { readonly ok: true; readonly value: TValue }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure> {\n\ttry {\n\t\treturn successResult(operation());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : fallbackMessage);\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA+CA,MAAMA,IAAoB;;;;;;;AAQ1B,SAAgB,UAAU,GAAe,GAAyB;CACjE,IAAI,CAAC,WAAWC,CAAK,GACpB,MAAU,MAAM,mBAAmB;CAIpC,OAAO,cAAcA,EAAM,UAFdC,EAAaC,CACT,CAAC,CAAC,MAAM,UAAU,KAAK,CAAC,EAAA,CACC,KAAK,IAAI,EAAE,aAAaF,EAAM;AACzE;;;;;;;;;AAkCA,SAAgB,iBAAiB,GAAe,GAAyB;CAExE,IAAMG,IADa,gBAAgBC,EAAI,QAAQ,UAAU,IAAI,CACtC,CAAC,CAAC,MAAM,IAAI,GAC7BC,IAAQ,6BAA6BF,CAAK;CAChD,CACCE,MAAU,KAAA,KACV,qBAAqBF,EAAME,MAAU,IAAI,OAAO,MAAML,KACtD,qBAAqBG,EAAMA,EAAM,SAAS,MAAM,IAAI,KAAK,MAAMH,KAC/DG,EAAM,SAASE,IAAQ,MAEvBC,EAAmB,aAAa,mBAAmBN,KAAS;EAC3D,OAAO;EACP,QAAQ;CACT,CA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C,GAAO;EAEf,OADAC,EAAmBD,CAAK,GACjBmC,EAAc,aAAanC,aAAiB,QAAQA,EAAM,UAAUoC,CAAe;CAC3F;AACD"}
1
+ {"version":3,"file":"pem.js","names":["base64Decode","base64Encode","failureResult","rethrowIfInvariant","successResult","throwMicro509Error","PEM_LABEL_PATTERN","label","der","pem","lines","begin","bodyLines","error","input","block","normalized","blocks","openBlock","lineStart","newline","lineEnd","nextLineStart","line","beginLine","beginLabel","endLabel","end","certificates","certificateRequests","privateKeys","publicKeys","others","nonEmptyLines","kind","prefix","withoutSurroundingWsp","index","RFC822_FIELD_NAME","character","value","headers","foldedName","delimiter","headerName","operation","fallbackMessage"],"sources":["../../src/pem/pem.ts"],"sourcesContent":["/**\n * PEM helpers used across the public API.\n *\n * Encodes, decodes, splits, and categorizes PEM blocks as defined by\n * RFC 7468.\n *\n * @module\n */\n\nimport { base64Decode, base64Encode } from '#micro509/internal/shared/base64';\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport {\n\tfailureResult,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n} from '#micro509/result/result';\n\n/** A single decoded PEM block with its label, decoded DER bytes, and original PEM text. */\nexport interface PemBlock {\n\t/** RFC 7468 label between the `BEGIN` / `END` markers (e.g. `\"CERTIFICATE\"`). */\n\treadonly label: string;\n\t/** Decoded DER content of this block. */\n\treadonly bytes: Uint8Array;\n\t/** The original PEM text including `BEGIN`/`END` lines. */\n\treadonly pem: string;\n}\n\n/**\n * PEM blocks grouped by their label into well-known PKI categories.\n * Blocks that don't match any known label land in {@linkcode others}.\n */\nexport interface CategorizedPemBlocks {\n\t/** Blocks with label `CERTIFICATE`. */\n\treadonly certificates: readonly PemBlock[];\n\t/** Blocks with label `CERTIFICATE REQUEST`. */\n\treadonly certificateRequests: readonly PemBlock[];\n\t/** Blocks with label `PRIVATE KEY`, `RSA PRIVATE KEY`, or `EC PRIVATE KEY`. */\n\treadonly privateKeys: readonly PemBlock[];\n\t/** Blocks with label `PUBLIC KEY`. */\n\treadonly publicKeys: readonly PemBlock[];\n\t/** Blocks whose label doesn't match any of the above categories. */\n\treadonly others: readonly PemBlock[];\n}\n\n// RFC 7468 §3 label ABNF: labelchar = %x21-2C / %x2E-7E, joined by an optional\n// single \"-\" or SP; an empty label is legal.\nconst PEM_LABEL_PATTERN = /^(?:[!-,.-~](?:[- ]?[!-,.-~])*)?$/;\n\n/**\n * Wraps DER bytes in a PEM envelope with 64-character base64 lines.\n *\n * @param label PEM type label (e.g. `\"CERTIFICATE\"`, `\"PRIVATE KEY\"`).\n * @param der Raw DER-encoded content.\n */\nexport function pemEncode(label: string, der: Uint8Array): string {\n\tif (!isPemLabel(label)) {\n\t\tthrow new Error('Invalid PEM label');\n\t}\n\tconst body = base64Encode(der);\n\tconst lines = body.match(/.{1,64}/g) ?? [];\n\treturn `-----BEGIN ${label}-----\\n${lines.join('\\n')}\\n-----END ${label}-----\\n`;\n}\n\n/** Machine-readable failure reason for the PEM decoders. */\nexport type PemErrorCode = 'malformed';\n\n/** Structured failure payload for PEM decoding. */\nexport interface PemFailure extends Micro509Error<PemErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode pemDecode}. */\nexport type PemDecodeResult =\n\t| { readonly ok: true; readonly value: Uint8Array }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode splitPemBlocks}. */\nexport type SplitPemBlocksResult =\n\t| { readonly ok: true; readonly value: readonly PemBlock[] }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/** Success-or-failure result from {@linkcode categorizePemBlocks}. */\nexport type CategorizePemBlocksResult =\n\t| { readonly ok: true; readonly value: CategorizedPemBlocks }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;\n\n/**\n * Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the\n * DER content from a PEM string. Text ahead of the `BEGIN` line is ignored.\n * Throws if the `BEGIN`/`END` markers don't match `label`.\n *\n * @param label Expected PEM type label.\n * @param pem PEM-encoded text (may contain `\\r`).\n */\nexport function pemDecodeOrThrow(label: string, pem: string): Uint8Array {\n\tconst normalized = trimPemDocument(pem.replace(/\\r\\n?/g, '\\n'));\n\tconst lines = normalized.split('\\n');\n\tconst begin = findPreEncapsulationBoundary(lines);\n\tif (\n\t\tbegin === undefined ||\n\t\tparsePemBoundaryLine(lines[begin] ?? '', 'BEGIN') !== label ||\n\t\tparsePemBoundaryLine(lines[lines.length - 1] ?? '', 'END') !== label ||\n\t\tlines.length - begin < 3\n\t) {\n\t\tthrowMicro509Error('malformed', `Invalid PEM for ${label}`, {\n\t\t\tstage: 'pem',\n\t\t\treason: 'invalid_armor',\n\t\t} as const);\n\t}\n\tconst bodyLines = normalizePemBodyLines(lines.slice(begin + 1, -1));\n\tif (bodyLines === undefined) {\n\t\tthrowMicro509Error('malformed', `Invalid PEM for ${label}`, {\n\t\t\tstage: 'base64',\n\t\t\treason: 'invalid_base64',\n\t\t} as const);\n\t}\n\ttry {\n\t\treturn base64Decode(bodyLines.join(''));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tthrowMicro509Error('malformed', `Invalid PEM for ${label}`, {\n\t\t\tstage: 'base64',\n\t\t\treason: 'invalid_base64',\n\t\t} as const);\n\t}\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns\n * them as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files\n * and ignores non-PEM text between blocks.\n */\nexport function splitPemBlocksOrThrow(input: string): readonly PemBlock[] {\n\treturn splitPemTextBlocksOrThrow(input).map((block) => ({\n\t\t...block,\n\t\tbytes: pemDecodeOrThrow(block.label, block.pem),\n\t}));\n}\n\n/** @internal A bounded-by-input PEM block before decoding its body. */\nexport interface PemTextBlock {\n\treadonly label: string;\n\treadonly pem: string;\n}\n\n/** @internal Shares the ordinary boundary scanner, retaining legacy encrypted bodies verbatim. */\nexport function splitPemTextBlocksOrThrow(input: string): readonly PemTextBlock[] {\n\tconst normalized = input.replace(/^\\uFEFF/, '').replace(/\\r\\n?/g, '\\n');\n\tconst blocks: PemTextBlock[] = [];\n\tlet openBlock: { readonly label: string; readonly start: number } | undefined;\n\tlet lineStart = 0;\n\twhile (lineStart < normalized.length) {\n\t\tconst newline = normalized.indexOf('\\n', lineStart);\n\t\tconst lineEnd = newline === -1 ? normalized.length : newline;\n\t\tconst nextLineStart = newline === -1 ? normalized.length : newline + 1;\n\t\tconst line = normalized.slice(lineStart, lineEnd);\n\t\tconst beginLine = line.replace(/^[ \\t]+/, '');\n\t\tconst beginLabel = parsePemBoundaryLine(line, 'BEGIN');\n\t\tconst endLabel = parsePemBoundaryLine(line, 'END');\n\n\t\tif (beginLabel !== undefined) {\n\t\t\tif (openBlock !== undefined) {\n\t\t\t\tthrow new Error('Malformed PEM block');\n\t\t\t}\n\t\t\topenBlock = { label: beginLabel, start: lineStart + line.length - beginLine.length };\n\t\t} else if (endLabel !== undefined) {\n\t\t\tblocks.push(closePemBlock(normalized, openBlock, endLabel, nextLineStart));\n\t\t\topenBlock = undefined;\n\t\t} else if (looksLikePemBoundary(line)) {\n\t\t\tthrow new Error('Malformed PEM block');\n\t\t}\n\n\t\tif (newline === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tlineStart = nextLineStart;\n\t}\n\tif (openBlock !== undefined) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\treturn blocks;\n}\n\nfunction closePemBlock(\n\tinput: string,\n\topenBlock: { readonly label: string; readonly start: number } | undefined,\n\tendLabel: string,\n\tend: number,\n): PemTextBlock {\n\tif (openBlock === undefined || openBlock.label !== endLabel) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\tconst pem = input.slice(openBlock.start, end);\n\treturn {\n\t\tlabel: openBlock.label,\n\t\tpem,\n\t};\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n */\nexport function categorizePemBlocksOrThrow(\n\tinput: string | readonly PemBlock[],\n): CategorizedPemBlocks {\n\tconst blocks = typeof input === 'string' ? splitPemBlocksOrThrow(input) : input;\n\tconst certificates: PemBlock[] = [];\n\tconst certificateRequests: PemBlock[] = [];\n\tconst privateKeys: PemBlock[] = [];\n\tconst publicKeys: PemBlock[] = [];\n\tconst others: PemBlock[] = [];\n\n\tfor (const block of blocks) {\n\t\tswitch (block.label) {\n\t\t\tcase 'CERTIFICATE':\n\t\t\t\tcertificates.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'CERTIFICATE REQUEST':\n\t\t\t\tcertificateRequests.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PRIVATE KEY':\n\t\t\tcase 'RSA PRIVATE KEY':\n\t\t\tcase 'EC PRIVATE KEY':\n\t\t\t\tprivateKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tcase 'PUBLIC KEY':\n\t\t\t\tpublicKeys.push(block);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tothers.push(block);\n\t\t}\n\t}\n\n\treturn { certificates, certificateRequests, privateKeys, publicKeys, others };\n}\n\nfunction normalizePemBodyLines(lines: readonly string[]): readonly string[] | undefined {\n\tconst normalizedLines = lines.map((line) => line.replace(/[ \\t]/g, ''));\n\tconst nonEmptyLines = normalizedLines.filter((line) => line !== '');\n\tif (nonEmptyLines.length === 0) {\n\t\treturn [''];\n\t}\n\treturn nonEmptyLines.every((line) => /^[A-Za-z0-9+/=]+$/.test(line)) ? nonEmptyLines : undefined;\n}\n\nfunction parsePemBoundaryLine(line: string, kind: 'BEGIN' | 'END'): string | undefined {\n\tconst prefix = `-----${kind} `;\n\tconst withoutSurroundingWsp = trimLwsp(line);\n\tif (!withoutSurroundingWsp.startsWith(prefix) || !withoutSurroundingWsp.endsWith('-----')) {\n\t\treturn undefined;\n\t}\n\tconst label = withoutSurroundingWsp.slice(prefix.length, -5);\n\treturn isPemLabel(label) ? label : undefined;\n}\n\n/** RFC 7468 §2: data before the encapsulation boundaries is permitted. */\nfunction findPreEncapsulationBoundary(lines: readonly string[]): number | undefined {\n\tfor (const [index, line] of lines.entries()) {\n\t\tif (parsePemBoundaryLine(line, 'BEGIN') !== undefined) {\n\t\t\treturn index;\n\t\t}\n\t\tif (looksLikePemBoundary(line)) {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nfunction looksLikePemBoundary(line: string): boolean {\n\treturn /^[ \\t]*-{5,}(?:BEGIN|END)/.test(line);\n}\n\n/** RFC 822 §3.2: `field-name = 1*<any CHAR, excluding CTLs, SPACE, and \":\">`. */\nconst RFC822_FIELD_NAME = /^[\\x21-\\x39\\x3b-\\x7e]+$/;\n\n/** RFC 822 §3.3: `LWSP-char = SPACE / HTAB`. */\nfunction isLwspChar(character: string): boolean {\n\treturn character === ' ' || character === '\\t';\n}\n\n/**\n * Strips the whitespace surrounding a PEM document: `LWSP-char`s and the line\n * terminators that separate the boundary lines from the body.\n *\n * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode\n * `Zs`, making those characters acceptable at a document edge while\n * {@linkcode parsePemBoundaryLine} rejects them everywhere else.\n */\nfunction trimPemDocument(value: string): string {\n\treturn value.replace(/^[ \\t\\n]+|[ \\t\\n]+$/g, '');\n}\n\n/**\n * @internal Strips surrounding RFC 822 §3.3 `LWSP-char`s.\n *\n * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode `Zs`,\n * none of which the grammar admits.\n */\nexport function trimLwsp(value: string): string {\n\treturn value.replace(/^[ \\t]+|[ \\t]+$/g, '');\n}\n\n/** A PEM block carrying RFC 1421 §4.6 encapsulated headers ahead of its body. */\nexport interface TraditionalPemBlock {\n\t/** PEM type label between the `BEGIN` / `END` markers. */\n\treadonly label: string;\n\t/** Encapsulated headers (e.g. `Proc-Type`, `DEK-Info`), unfolded. */\n\treadonly headers: ReadonlyMap<string, string>;\n\t/** Base64-encoded payload after the headers. */\n\treadonly base64Body: string;\n}\n\n/**\n * @internal Parses a PEM block with RFC 1421 §4.6 encapsulated headers.\n *\n * RFC 7468 §2 forbids headers, so this path exists only for the legacy\n * OpenSSL-style encrypted PKCS#1 and SEC1 blocks that predate it.\n */\nexport function parseTraditionalPemOrThrow(pem: string): TraditionalPemBlock {\n\tconst normalized = trimPemDocument(pem.replace(/\\r\\n?/g, '\\n'));\n\tconst lines = normalized.split('\\n');\n\tconst label = parsePemBoundaryLine(lines[0] ?? '', 'BEGIN');\n\tif (label === undefined || lines.length < 2) {\n\t\tthrow new Error('Invalid PEM block');\n\t}\n\tif (parsePemBoundaryLine(lines[lines.length - 1] ?? '', 'END') !== label) {\n\t\tthrow new Error('PEM boundaries do not match');\n\t}\n\tconst headers = new Map<string, string>();\n\tlet index = 1;\n\tlet foldedName: string | undefined;\n\twhile (index < lines.length - 1) {\n\t\tconst line = lines[index];\n\t\tif (line === undefined) {\n\t\t\tbreak;\n\t\t}\n\t\tif (line.length === 0) {\n\t\t\tindex += 1;\n\t\t\tbreak;\n\t\t}\n\t\tif (foldedName !== undefined && isLwspChar(line.charAt(0))) {\n\t\t\theaders.set(foldedName, `${headers.get(foldedName) ?? ''}${line}`);\n\t\t\tindex += 1;\n\t\t\tcontinue;\n\t\t}\n\t\tconst delimiter = line.indexOf(':');\n\t\tif (delimiter === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst headerName = line.slice(0, delimiter);\n\t\tif (!RFC822_FIELD_NAME.test(headerName)) {\n\t\t\tthrow new Error(`Invalid PEM header name: ${headerName}`);\n\t\t}\n\t\tif (headers.has(headerName)) {\n\t\t\tthrow new Error(`Duplicate PEM header: ${headerName}`);\n\t\t}\n\t\theaders.set(headerName, line.slice(delimiter + 1).replace(/^[ \\t]+/, ''));\n\t\tfoldedName = headerName;\n\t\tindex += 1;\n\t}\n\treturn { label, headers, base64Body: lines.slice(index, lines.length - 1).join('') };\n}\n\nfunction isPemLabel(label: string): boolean {\n\treturn PEM_LABEL_PATTERN.exec(label)?.[0] === label;\n}\n\n/**\n * Extracts and base64-decodes the DER content from a PEM string.\n * Text ahead of the `BEGIN` line is ignored.\n *\n * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`\n * markers don't match `label` or the body is not valid base64. For the\n * throwing form use {@linkcode pemDecodeOrThrow}.\n */\nexport function pemDecode(label: string, pem: string): PemDecodeResult {\n\treturn toPemResult(() => pemDecodeOrThrow(label, pem), 'Invalid PEM');\n}\n\n/**\n * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them\n * as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files and\n * ignores non-PEM text between blocks.\n *\n * Returns a typed failure (`code: 'malformed'`) on stray or truncated PEM\n * markers. For the throwing form use {@linkcode splitPemBlocksOrThrow}.\n */\nexport function splitPemBlocks(input: string): SplitPemBlocksResult {\n\treturn toPemResult(() => splitPemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/**\n * Groups PEM blocks by label into well-known PKI categories\n * (certificates, CSRs, private keys, public keys, and everything else).\n * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.\n *\n * Returns a typed failure (`code: 'malformed'`) when raw text contains stray\n * or truncated PEM markers. For the throwing form use\n * {@linkcode categorizePemBlocksOrThrow}.\n */\nexport function categorizePemBlocks(\n\tinput: string | readonly PemBlock[],\n): CategorizePemBlocksResult {\n\treturn toPemResult(() => categorizePemBlocksOrThrow(input), 'Malformed PEM block');\n}\n\n/** Shared Result wrapper around the throwing PEM cores. */\nfunction toPemResult<TValue>(\n\toperation: () => TValue,\n\tfallbackMessage: string,\n):\n\t| { readonly ok: true; readonly value: TValue }\n\t| ErrorResult<PemErrorCode, Record<never, never>, PemFailure> {\n\ttry {\n\t\treturn successResult(operation());\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn failureResult('malformed', error instanceof Error ? error.message : fallbackMessage);\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA+CA,MAAMM,IAAoB;;;;;;;AA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AW,EAAE,CAAC,GACxED,IAAaE,GACbP,KAAS;CACV;CACA,OAAO;EAAE9B;EAAOkC;EAAS,YAAY/B,EAAM,MAAM2B,GAAO3B,EAAM,SAAS,CAAC,CAAC,CAAC,KAAK,EAAE;CAAE;AACpF;AAEA,SAAS,WAAWH,GAAwB;CAC3C,OAAOD,EAAkB,KAAKC,CAAK,CAAC,GAAG,OAAOA;AAC/C;;;;;;;;;AAUA,SAAgB,UAAUA,GAAeE,GAA8B;CACtE,OAAO,kBAAkB,iBAAiBF,GAAOE,CAAG,GAAG,aAAa;AACrE;;;;;;;;;AAUA,SAAgB,eAAeK,GAAqC;CACnE,OAAO,kBAAkB,sBAAsBA,CAAK,GAAG,qBAAqB;AAC7E;;;;;;;;;;AAWA,SAAgB,oBACfA,GAC4B;CAC5B,OAAO,kBAAkB,2BAA2BA,CAAK,GAAG,qBAAqB;AAClF;;AAGA,SAAS,YACR+B,GACAC,GAG8D;CAC9D,IAAI;EACH,OAAO1C,EAAcyC,EAAU,CAAC;CACjC,SAAShC,GAAO;EAEf,OADAV,EAAmBU,CAAK,GACjBX,EAAc,aAAaW,aAAiB,QAAQA,EAAM,UAAUiC,CAAe;CAC3F;AACD"}
@@ -1 +1 @@
1
- {"version":3,"file":"pfx.js","names":["certificateBags","privateKeyBags","certificate","input","certificateDer","privateKey","contentInfos","sequence","safeContents","authenticatedSafe","macData","createPkcs12MacData","der","integerFromNumber","pemEncode","base64Encode","failureResult","code","message","options","createKdfBudget","topLevel","berSequenceChildren","readBerRoot","version","authSafe","decodeIntegerNumber","berPrimitiveContent","authenticatedSafeOctets","macElement","macResult","berToDefiniteLength","bags","contentInfo","safeContentsResult","budget","bag","error","refusal","decodeRefusalOf","DECODE_REFUSAL_CODES","bytes","blocks","splitPemBlocksOrThrow","pem","block","source","oid","OIDS","content","children","contentType","decodeObjectIdentifier","DECODE_LIMIT_CODES","data","encryptedData","decrypted","rethrowIfInvariant","isWrongPasswordError","isKdfIterationLimitError","root","certBag","objectIdentifier","explicitContext","octetString","attributes","pkcs8Der","encryption","encryptPbes2","tlv","out","setOf","throwMicro509Error","friendlyName","bmpString","bagId","bagValue","attributeSet","bagOid","value","certBagChildren","certType","certValue","parseCertificateDerOrThrow","berEncoding","readRootElement","entries","localKeyId","attribute","parts","values","attrOid","rawValues","toHex","firstValue","element","readElement","exportPkcs8Der","candidate","parsePkcs12MacData","macDataDer","encryptedContentInfo","contentInfoChildren","algorithm","encryptedContent","decryptPbes2","berStringContent","password","child","decodeString"],"sources":["../../src/pkcs/pfx.ts"],"sourcesContent":["/**\n * PKCS#12/PFX container creation and parsing.\n *\n * Builds and decodes PFX archives containing certificate bags, private-key bags,\n * optional PBES2 encryption, and PKCS#12 MAC integrity verification.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport type { BerElement } from '#micro509/internal/asn1/ber';\nimport {\n\tberEncoding,\n\tberPrimitiveContent,\n\tberSequenceChildren,\n\tberStringContent,\n\tberToDefiniteLength,\n\treadBerRoot,\n} from '#micro509/internal/asn1/ber';\nimport {\n\tDECODE_LIMIT_CODES,\n\tDECODE_REFUSAL_CODES,\n\tdecodeRefusalOf,\n} from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tbmpString,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { KdfBudget, KdfLimitOptions } from '#micro509/internal/crypto/pbes2';\nimport {\n\tcreateKdfBudget,\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisKdfIterationLimitError,\n\tisWrongPasswordError,\n} from '#micro509/internal/crypto/pbes2';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { EncryptedPkcs8Options } from '#micro509/keys/keys';\nimport { exportPkcs8Der } from '#micro509/keys/keys';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem';\nimport type { ParsedPkcs12MacData, Pkcs12MacOptions } from '#micro509/pkcs/pkcs12-mac';\nimport { createPkcs12MacData, parsePkcs12MacData } from '#micro509/pkcs/pkcs12-mac';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, throwMicro509Error } from '#micro509/result/result';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow } from '#micro509/x509/parse';\n\nexport type * from '#micro509/pkcs/pkcs12-mac';\n\n/** PEM string or DER bytes for a certificate to include in a PFX bag. */\nexport type PfxCertificateSource = string | Uint8Array | ParsedCertificate;\n/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */\nexport type PfxPrivateKeySource = CryptoKey | Uint8Array;\n\n/** Optional metadata attached to a certificate or key bag inside a PFX. */\nexport interface PfxBagAttributesInput {\n\t/**\n\t * Human-readable label stored as a BMPString attribute of 1 to 255 characters\n\t * (RFC 2985 §5.5.1), none of them a surrogate, U+FFFE or U+FFFF.\n\t */\n\treadonly friendlyName?: string;\n\t/** Opaque identifier linking a certificate bag to its corresponding key bag. */\n\treadonly localKeyId?: Uint8Array;\n}\n\n/** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxCertificateBagInput {\n\t/** Certificate as PEM text or DER bytes. */\n\treadonly certificate: PfxCertificateSource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxPrivateKeyBagInput {\n\t/** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */\n\treadonly privateKey: PfxPrivateKeySource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** Input for {@linkcode createPfx}. */\nexport interface CreatePfxInput {\n\t/** Certificates to include as certBag entries. */\n\treadonly certificates?: readonly PfxCertificateBagInput[];\n\t/** Private keys to include as keyBag entries. */\n\treadonly privateKeys?: readonly PfxPrivateKeyBagInput[];\n\t/** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */\n\treadonly encryption?: PfxEncryptionOptions;\n\t/** PKCS#12 MAC integrity settings: the RFC 7292 MAC or RFC 9879 PBMAC1. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode EncryptedPkcs8Options}. */\nexport type PfxEncryptionOptions = EncryptedPkcs8Options;\n\nexport type { KdfLimitOptions } from '#micro509/internal/crypto/pbes2';\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions extends KdfLimitOptions {\n\t/** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */\n\treadonly password?: string;\n\t/** Separate password for MAC verification. Falls back to `password` when omitted. */\n\treadonly macPassword?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */\nexport interface PfxMaterial {\n\t/** Raw DER-encoded PFX bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PFX (`-----BEGIN PKCS12-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */\nexport interface ParsedPfxAttribute {\n\t/** Dotted-decimal OID identifying this attribute type. */\n\treadonly oid: string;\n\t/**\n\t * Hex of each received attribute value, re-encoded with definite lengths.\n\t * Universal constructed strings are joined into primitive strings. SET OF\n\t * order and implicitly tagged constructed strings stay as received.\n\t */\n\treadonly valuesHex: readonly string[];\n}\n\n/** Decoded bag attributes for a single SafeBag inside a PFX. */\nexport interface ParsedPfxBagAttributes {\n\t/** All raw attributes as OID + hex-encoded values. */\n\treadonly entries: readonly ParsedPfxAttribute[];\n\t/** Decoded BMPString friendly-name attribute, if present. */\n\treadonly friendlyName?: string;\n\t/** Hex-encoded localKeyId attribute, if present. */\n\treadonly localKeyId?: string;\n}\n\n/**\n * Discriminated union of SafeBag types decoded from a PFX container.\n *\n * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.\n */\nexport type ParsedPfxBag =\n\t| {\n\t\t\t/** Bag contains an X.509 certificate. */\n\t\t\treadonly kind: 'certificate';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Parsed certificate from the certBag. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** Bag contains a PKCS#8 private key. */\n\t\t\treadonly kind: 'privateKey';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER-encoded PKCS#8 PrivateKeyInfo. */\n\t\t\treadonly pkcs8Der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Bag type not recognized by this library. */\n\t\t\treadonly kind: 'unknown';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/**\n\t\t\t * The received bag value, re-encoded with definite lengths. Universal\n\t\t\t * constructed strings are joined into primitive strings. SET OF order and\n\t\t\t * implicitly tagged constructed strings stay as received.\n\t\t\t */\n\t\t\treadonly valueDer: Uint8Array;\n\t };\n\n/** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport interface ParsedPfx {\n\t/** All SafeBags in the PFX, including unknown types. */\n\treadonly bags: readonly ParsedPfxBag[];\n\t/** Convenience: only the parsed certificates extracted from certBag entries. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries. */\n\treadonly privateKeys: readonly Uint8Array[];\n\t/** MAC verification metadata, present when the PFX includes a MacData block. */\n\treadonly macData?: ParsedPkcs12MacData;\n}\n\n// Result types for PFX parsing\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode =\n\t| DecodeFailureCode\n\t| 'invalid_password'\n\t| 'password_required'\n\t| 'kdf_iterations_exceeded'\n\t| 'password_not_bmp_string'\n\t| 'password_not_utf8'\n\t| 'unsupported_mac_algorithm'\n\t| 'weak_mac_key_length';\n\n/** Error payload for a failed PFX parse. */\nexport interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport type ParsePfxResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded PFX container. */\n\t\t\treadonly value: ParsedPfx;\n\t }\n\t| ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\n// Result types for PFX creation\n\n/**\n * Caller-correctable failure code from {@linkcode createPfx}.\n *\n * The only parse boundary in creation is the certificate source: it is\n * normalized from untrusted PEM/DER. Private keys are either a WebCrypto\n * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through\n * unvalidated, so there is no distinct `invalid_private_key` failure to model.\n */\nexport type CreatePfxErrorCode = 'invalid_certificate';\n\n/** Bag attribute input that {@linkcode createPfx} refuses by throwing a `ResultError`. */\nexport type PfxEncoderErrorCode = 'invalid_friendly_name';\n\n/** Error payload for a failed PFX creation. */\nexport interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPfx}. */\nexport type CreatePfxResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the PFX container. */\n\t\t\treadonly value: PfxMaterial;\n\t }\n\t| ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;\n\n// createPfx\n\n/**\n * Builds a PKCS#12/PFX archive containing certificates and/or private keys.\n *\n * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.\n * When `mac` is provided, a PKCS#12 MAC integrity block is appended.\n *\n * Returns a {@linkcode CreatePfxResult}: the container material on success, or a\n * typed `invalid_certificate` failure when a certificate source is not a single\n * PEM/DER certificate.\n *\n * When `mac` is provided, `mac.type` selects the RFC 7292 MAC (the default) or\n * RFC 9879 PBMAC1.\n *\n * @throws {ResultError} with a {@linkcode CreatePkcs12MacDataErrorCode} when `mac.iterations`\n * is out of range or `mac.password` cannot be encoded for the selected MAC, and with\n * {@linkcode PfxEncoderErrorCode} `invalid_friendly_name` when a bag `friendlyName` is not a\n * BMPString of 1 to 255 characters.\n *\n * @example\n * ```ts\n * import { createPfx, unwrap } from 'micro509';\n *\n * const result = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * if (result.ok) {\n * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64\n * }\n * // or, when inputs are already validated: const pfx = unwrap(result);\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<CreatePfxResult> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\t// normalizeCertificate parses untrusted PEM/DER and throws on malformed\n\t\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\t\tlet certificateDer: Uint8Array;\n\t\ttry {\n\t\t\tcertificateDer = normalizeCertificate(certificate.certificate);\n\t\t} catch {\n\t\t\treturn pfxCreationFailure(\n\t\t\t\t'invalid_certificate',\n\t\t\t\t'Each PFX certificate source must be a single PEM or DER certificate',\n\t\t\t);\n\t\t}\n\t\tcertificateBags.push(createCertificateBag(certificateDer, certificate.attributes));\n\t}\n\tfor (const privateKey of input.privateKeys ?? []) {\n\t\tprivateKeyBags.push(\n\t\t\tcreatePrivateKeyBag(await normalizePrivateKey(privateKey.privateKey), privateKey.attributes),\n\t\t);\n\t}\n\tconst contentInfos: Uint8Array[] = [];\n\tif (certificateBags.length > 0) {\n\t\tcontentInfos.push(createDataContentInfo(sequence(certificateBags)));\n\t}\n\tif (privateKeyBags.length > 0) {\n\t\tconst safeContents = sequence(privateKeyBags);\n\t\tcontentInfos.push(\n\t\t\tinput.encryption === undefined\n\t\t\t\t? createDataContentInfo(safeContents)\n\t\t\t\t: await createEncryptedDataContentInfo(safeContents, input.encryption),\n\t\t);\n\t}\n\tconst authenticatedSafe = sequence(contentInfos);\n\tconst macData =\n\t\tinput.mac === undefined ? undefined : await createPkcs12MacData(authenticatedSafe, input.mac);\n\tconst der = sequence([\n\t\tintegerFromNumber(3),\n\t\tcreateDataContentInfo(authenticatedSafe),\n\t\t...(macData === undefined ? [] : [macData.der]),\n\t]);\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tder,\n\t\t\tpem: pemEncode('PKCS12', der),\n\t\t\tbase64: base64Encode(der),\n\t\t},\n\t};\n}\n\n/** Shorthand for constructing a PFX creation failure result. */\nfunction pfxCreationFailure(\n\tcode: CreatePfxErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n// parsePfxDer / parsePfxPem — Result-returning\n\n/**\n * Decodes a BER- or DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * The PFX, AuthenticatedSafe and SafeContents layers accept BER: indefinite and\n * non-minimal lengths and constructed OCTET STRINGs. The MAC is verified over the\n * AuthenticatedSafe octets as received. Certificates and private keys inside the\n * bags must be DER.\n *\n * Returns a result union — check `ok` before accessing `value`.\n * Encrypted containers require `options.password`. MAC verification uses\n * `options.macPassword` (falls back to `options.password`).\n *\n * @example\n * ```ts\n * import { parsePfxDer } from 'micro509';\n *\n * const result = await parsePfxDer(pfxBytes, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.certificates.length);\n * }\n * ```\n */\nexport async function parsePfxDer(\n\tder: Uint8Array,\n\toptions?: ParsePfxOptions,\n): Promise<ParsePfxResult> {\n\treturn await parsePfxDerWithBudget(der, options, createKdfBudget(options));\n}\n\nasync function parsePfxDerWithBudget(\n\tder: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n\tbudget: KdfBudget,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = berSequenceChildren(readBerRoot(der));\n\t\tif (topLevel.length < 2 || topLevel.length > 3) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tconst version = topLevel[0];\n\t\tconst authSafe = topLevel[1];\n\t\tif (version === undefined || authSafe === undefined) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(berPrimitiveContent(der, version, 0x02)) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authenticatedSafeOctets = extractContentInfoData(der, authSafe);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\tconst macResult = await verifyPfxMacData(\n\t\t\t\tberToDefiniteLength(der, macElement),\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\toptions,\n\t\t\t);\n\t\t\tif (macResult.error !== undefined) {\n\t\t\t\treturn macResult.error;\n\t\t\t}\n\t\t\tmacData = macResult.macData;\n\t\t}\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of berSequenceChildren(readBerRoot(authenticatedSafeOctets))) {\n\t\t\tconst safeContentsResult = await extractSafeContents(\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\tcontentInfo,\n\t\t\t\toptions,\n\t\t\t\tbudget,\n\t\t\t);\n\t\t\tif (safeContentsResult.error !== undefined) {\n\t\t\t\treturn safeContentsResult.error;\n\t\t\t}\n\t\t\tconst safeContents = safeContentsResult.data;\n\t\t\tfor (const bag of berSequenceChildren(safeContentsResult.root)) {\n\t\t\t\tbags.push(parseSafeBag(safeContents, bag));\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tbags,\n\t\t\t\tcertificates: bags.flatMap((bag) => (bag.kind === 'certificate' ? [bag.certificate] : [])),\n\t\t\t\tprivateKeys: bags.flatMap((bag) => (bag.kind === 'privateKey' ? [bag.pkcs8Der] : [])),\n\t\t\t\t...(macData === undefined ? {} : { macData }),\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? pfxFailure('malformed', 'Malformed PFX structure')\n\t\t\t: pfxFailure(refusal.code, refusal.message);\n\t}\n}\n\n/**\n * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.\n *\n * Delegates to {@linkcode parsePfxDer} after PEM decoding.\n *\n * @example\n * ```ts\n * import { parsePfxPem } from 'micro509';\n *\n * const result = await parsePfxPem(pfxPemString, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.privateKeys.length);\n * }\n * ```\n */\nexport async function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\tconst budget = createKdfBudget(options);\n\tlet bytes: Uint8Array;\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS12');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t\t}\n\t\tbytes = block.bytes;\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n\treturn await parsePfxDerWithBudget(bytes, options, budget);\n}\n\n// Private: PFX helpers\n\n/** Shorthand for constructing a PFX parse failure result. */\nfunction pfxFailure(\n\tcode: ParsePfxErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Unwraps a `data` ContentInfo to its inner OCTET STRING payload. */\nfunction extractContentInfoData(source: Uint8Array, contentInfo: BerElement): Uint8Array {\n\tconst { oid, content } = readContentInfo(source, contentInfo);\n\tif (oid !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(source, content);\n}\n\nfunction readContentInfo(\n\tsource: Uint8Array,\n\tcontentInfo: BerElement,\n): { readonly oid: string; readonly content: BerElement } {\n\tconst children = berSequenceChildren(contentInfo);\n\tconst contentType = children[0];\n\tconst content = children[1];\n\tif (contentType === undefined || content === undefined || children.length !== 2) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\treturn {\n\t\toid: decodeObjectIdentifier(berPrimitiveContent(source, contentType, 0x06)),\n\t\tcontent,\n\t};\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tsource: Uint8Array,\n\tcontentInfo: BerElement,\n\toptions: ParsePfxOptions | undefined,\n\tbudget: KdfBudget,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly root: BerElement;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly root?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tlet oid: string;\n\tlet content: BerElement;\n\ttry {\n\t\t({ oid, content } = readContentInfo(source, contentInfo));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\terror:\n\t\t\t\trefusal === undefined\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed ContentInfo')\n\t\t\t\t\t: pfxFailure(refusal.code, refusal.message),\n\t\t};\n\t}\n\tif (oid === OIDS.pkcs7Data) {\n\t\tconst data = extractContextOctetString(source, content);\n\t\treturn { data, root: readBerRoot(data) };\n\t}\n\tif (oid !== OIDS.pkcs7EncryptedData) {\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Unsupported PFX ContentInfo type'),\n\t\t};\n\t}\n\tif (options?.password === undefined) {\n\t\treturn {\n\t\t\terror: pfxFailure('password_required', 'Password required for encrypted PFX content'),\n\t\t};\n\t}\n\tconst encryptedData = extractContextChild(content);\n\tlet decrypted: Uint8Array;\n\ttry {\n\t\tdecrypted = await decryptEncryptedData(source, encryptedData, options.password, budget);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t\t};\n\t\t}\n\t\tif (isKdfIterationLimitError(error)) {\n\t\t\treturn { error: pfxFailure('kdf_iterations_exceeded', error.message) };\n\t\t}\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\terror:\n\t\t\t\trefusal === undefined\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed PFX encrypted content')\n\t\t\t\t\t: pfxFailure(refusal.code, refusal.message),\n\t\t};\n\t}\n\ttry {\n\t\tconst root = readBerRoot(decrypted);\n\t\tberSequenceChildren(root);\n\t\treturn { data: decrypted, root };\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal !== undefined) {\n\t\t\treturn { error: pfxFailure(refusal.code, refusal.message) };\n\t\t}\n\t\t// AES-CBC padding is unauthenticated: a wrong key passes the padding\n\t\t// check ~1/256 of the time and \"decrypts\" to random bytes that are not\n\t\t// a SafeContents SEQUENCE — a wrong password, not malformed input.\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n}\n\n/** Encodes a certBag SafeBag wrapping a DER certificate with optional attributes. */\nfunction createCertificateBag(\n\tcertificateDer: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\tconst certBag = sequence([\n\t\tobjectIdentifier(OIDS.x509CertificateBagType),\n\t\texplicitContext(0, octetString(certificateDer)),\n\t]);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12CertBag),\n\t\texplicitContext(0, certBag),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Encodes a keyBag SafeBag wrapping PKCS#8 DER with optional attributes. */\nfunction createPrivateKeyBag(\n\tpkcs8Der: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12KeyBag),\n\t\texplicitContext(0, pkcs8Der),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Wraps raw bytes in a `pkcs7-data` ContentInfo SEQUENCE. */\nfunction createDataContentInfo(data: Uint8Array): Uint8Array {\n\treturn sequence([objectIdentifier(OIDS.pkcs7Data), explicitContext(0, octetString(data))]);\n}\n\n/** PBES2-encrypts data and wraps it in a `pkcs7-encryptedData` ContentInfo. */\nasync function createEncryptedDataContentInfo(\n\tdata: Uint8Array,\n\toptions: PfxEncryptionOptions,\n): Promise<Uint8Array> {\n\tconst encryption = await encryptPbes2(data, options);\n\tconst encryptedData = sequence([\n\t\tintegerFromNumber(0),\n\t\tsequence([\n\t\t\tobjectIdentifier(OIDS.pkcs7Data),\n\t\t\tencryption.algorithmIdentifierDer,\n\t\t\ttlv(0x80, encryption.encryptedData),\n\t\t]),\n\t]);\n\treturn sequence([objectIdentifier(OIDS.pkcs7EncryptedData), explicitContext(0, encryptedData)]);\n}\n\n/** DER-encodes optional friendlyName / localKeyId into a SET OF SEQUENCE. */\nfunction encodeBagAttributes(attributes: PfxBagAttributesInput | undefined): readonly Uint8Array[] {\n\tif (attributes === undefined) {\n\t\treturn [];\n\t}\n\tconst out: Uint8Array[] = [];\n\tif (attributes.friendlyName !== undefined) {\n\t\tout.push(\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(OIDS.friendlyName),\n\t\t\t\tsetOf([encodeFriendlyName(attributes.friendlyName)]),\n\t\t\t]),\n\t\t);\n\t}\n\tif (attributes.localKeyId !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.localKeyId), setOf([octetString(attributes.localKeyId)])]),\n\t\t);\n\t}\n\treturn out.length === 0 ? [] : [setOf(out)];\n}\n\n/** RFC 2985 §5.5.1: `pkcs-9-ub-friendlyName`. */\nconst MAX_FRIENDLY_NAME_LENGTH = 255;\n\nfunction encodeFriendlyName(friendlyName: string): Uint8Array {\n\tconst refuse = (): never =>\n\t\tthrowMicro509Error<PfxEncoderErrorCode>(\n\t\t\t'invalid_friendly_name',\n\t\t\t'friendlyName must be a BMPString of 1 to 255 characters, none of them a surrogate, U+FFFE or U+FFFF',\n\t\t);\n\tif (friendlyName.length === 0 || friendlyName.length > MAX_FRIENDLY_NAME_LENGTH) {\n\t\treturn refuse();\n\t}\n\ttry {\n\t\treturn bmpString(friendlyName);\n\t} catch {\n\t\treturn refuse();\n\t}\n}\n\n/** Decodes a single SafeBag into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(source: Uint8Array, bag: BerElement): ParsedPfxBag {\n\tconst children = berSequenceChildren(bag);\n\tconst bagId = children[0];\n\tconst bagValue = children[1];\n\tconst attributeSet = children[2];\n\tif (bagId === undefined || bagValue === undefined || children.length > 3) {\n\t\tthrow new Error('Malformed SafeBag');\n\t}\n\tconst bagOid = decodeObjectIdentifier(berPrimitiveContent(source, bagId, 0x06));\n\tconst attributes = parseBagAttributes(source, attributeSet);\n\tconst value = extractContextChild(bagValue);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBagChildren = berSequenceChildren(value);\n\t\tconst certType = certBagChildren[0];\n\t\tconst certValue = certBagChildren[1];\n\t\tif (\n\t\t\tcertType === undefined ||\n\t\t\tcertValue === undefined ||\n\t\t\tcertBagChildren.length !== 2 ||\n\t\t\tdecodeObjectIdentifier(berPrimitiveContent(source, certType, 0x06)) !==\n\t\t\t\tOIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(extractContextOctetString(source, certValue)),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8Der = berEncoding(source, value);\n\t\treadRootElement(pkcs8Der);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der,\n\t\t};\n\t}\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: berToDefiniteLength(source, value),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: BerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tif (attributeSet.tag !== 0x31) {\n\t\tthrow new Error('Malformed PFX bag attributes');\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of attributeSet.children) {\n\t\tconst parts = berSequenceChildren(attribute);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed PFX bag attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(berPrimitiveContent(source, oid, 0x06));\n\t\tconst rawValues = values.children.map((value) => berToDefiniteLength(source, value));\n\t\tentries.push({\n\t\t\toid: attrOid,\n\t\t\tvaluesHex: rawValues.map((value) => toHex(value)),\n\t\t});\n\t\tif (attrOid === OIDS.friendlyName) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (friendlyName !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed friendlyName attribute');\n\t\t\t}\n\t\t\tfriendlyName = decodeFriendlyName(firstValue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.localKeyId) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (localKeyId !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed localKeyId attribute');\n\t\t\t}\n\t\t\tlocalKeyId = decodeLocalKeyId(firstValue);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\t...(friendlyName === undefined ? {} : { friendlyName }),\n\t\t...(localKeyId === undefined ? {} : { localKeyId }),\n\t};\n}\n\nfunction decodeLocalKeyId(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('localKeyId must use OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nfunction normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\treturn source instanceof CryptoKey\n\t\t? exportPkcs8Der(source)\n\t\t: Promise.resolve(new Uint8Array(source));\n}\n\n/** Extracts DER bytes from a PEM string, or passes raw DER through. */\nfunction normalizeCertificate(source: PfxCertificateSource): Uint8Array {\n\tif (typeof source === 'string') {\n\t\tconst block = splitPemBlocksOrThrow(source).find(\n\t\t\t(candidate) => candidate.label === 'CERTIFICATE',\n\t\t);\n\t\tif (block === undefined) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn new Uint8Array(block.bytes);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn new Uint8Array(source);\n\t}\n\treturn new Uint8Array(source.der);\n}\n\n/** Parses the MacData block and verifies it against the AuthenticatedSafe when a password is given. */\nasync function verifyPfxMacData(\n\tmacDataDer: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| { readonly macData: ParsedPkcs12MacData; readonly error?: undefined }\n\t| {\n\t\t\treadonly macData?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst macResult = await parsePkcs12MacData(\n\t\tmacDataDer,\n\t\tauthenticatedSafe,\n\t\toptions?.macPassword ?? options?.password,\n\t\toptions,\n\t);\n\tif (!macResult.ok) {\n\t\treturn {\n\t\t\terror:\n\t\t\t\tmacResult.code === 'malformed'\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed PFX MacData')\n\t\t\t\t\t: pfxFailure(macResult.code, macResult.message),\n\t\t};\n\t}\n\tif (macResult.value.verification === 'invalid') {\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content'),\n\t\t};\n\t}\n\treturn { macData: macResult.value };\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nfunction decryptEncryptedData(\n\tsource: Uint8Array,\n\tencryptedData: BerElement,\n\tpassword: string,\n\tbudget: KdfBudget,\n): Promise<Uint8Array> {\n\tconst topLevel = berSequenceChildren(encryptedData);\n\tconst version = topLevel[0];\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || version === undefined || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tif (decodeIntegerNumber(berPrimitiveContent(source, version, 0x02)) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoChildren = berSequenceChildren(encryptedContentInfo);\n\tconst contentType = contentInfoChildren[0];\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\tcontentType === undefined ||\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tberPrimitiveContent(source, contentType, 0x06);\n\treturn decryptPbes2(\n\t\tberToDefiniteLength(source, algorithm),\n\t\tberStringContent(source, encryptedContent, 0x80, 0x04),\n\t\tpassword,\n\t\tbudget,\n\t);\n}\n\n/** Reads the OCTET STRING inside a `[0] EXPLICIT` wrapper. */\nfunction extractContextOctetString(source: Uint8Array, element: BerElement): Uint8Array {\n\treturn berStringContent(source, extractContextChild(element), 0x04);\n}\n\n/** Reads the single child element inside a `[0] EXPLICIT` wrapper. */\nfunction extractContextChild(element: BerElement): BerElement {\n\tif (element.tag !== 0xa0) {\n\t\tthrow new Error('Expected [0] EXPLICIT value');\n\t}\n\tconst child = element.children[0];\n\tif (element.children.length !== 1 || child === undefined) {\n\t\tthrow new Error('Expected context-specific wrapper with exactly one value');\n\t}\n\treturn child;\n}\n\n/** RFC 2985 §5.5.1: a friendlyName value is a BMPString of SIZE (1..255). */\nfunction decodeFriendlyName(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('friendlyName must be a BMPString');\n\t}\n\tconst friendlyName = decodeString(0x1e, element.value);\n\tif (friendlyName.length < 1 || friendlyName.length > MAX_FRIENDLY_NAME_LENGTH) {\n\t\tthrow new Error('friendlyName must hold 1 to 255 characters');\n\t}\n\treturn friendlyName;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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ntegerNumber","decodeObjectIdentifier","decodeString","toHex","berEncoding","berPrimitiveContent","berSequenceChildren","berStringContent","berToDefiniteLength","readBerRoot","DECODE_LIMIT_CODES","decodeRefusalOf","bmpString","explicitContext","integerFromNumber","objectIdentifier","octetString","readElement","readRootElement","sequence","setOf","tlv","OIDS","createKdfBudget","decryptPbes2","encryptPbes2","isKdfIterationLimitError","isWrongPasswordError","base64Encode","exportPkcs8Der","pemEncode","splitPemBlocksOrThrow","createPkcs12MacData","parsePkcs12MacData","DECODE_REFUSAL_CODES","failureResult","rethrowIfInvariant","throwMicro509Error","parseCertificateDerOrThrow","input","certificateBags","privateKeyBags","certificate","certificateDer","privateKey","contentInfos","safeContents","authenticatedSafe","macData","der","code","message","options","budget","topLevel","version","authSafe","authenticatedSafeOctets","macElement","macResult","bags","contentInfo","safeContentsResult","bag","error","refusal","pem","bytes","blocks","block","source","oid","content","children","contentType","data","encryptedData","decrypted","root","attributes","certBag","pkcs8Der","encryption","out","friendlyName","bagId","bagValue","attributeSet","bagOid","value","certBagChildren","certType","certValue","entries","localKeyId","attribute","parts","values","attrOid","rawValues","firstValue","element","candidate","macDataDer","password","encryptedContentInfo","contentInfoChildren","algorithm","encryptedContent","child"],"sources":["../../src/pkcs/pfx.ts"],"sourcesContent":["/**\n * PKCS#12/PFX container creation and parsing.\n *\n * Builds and decodes PFX archives containing certificate bags, private-key bags,\n * optional PBES2 encryption, and PKCS#12 MAC integrity verification.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerNumber,\n\tdecodeObjectIdentifier,\n\tdecodeString,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport type { BerElement } from '#micro509/internal/asn1/ber';\nimport {\n\tberEncoding,\n\tberPrimitiveContent,\n\tberSequenceChildren,\n\tberStringContent,\n\tberToDefiniteLength,\n\treadBerRoot,\n} from '#micro509/internal/asn1/ber';\nimport {\n\tDECODE_LIMIT_CODES,\n\tDECODE_REFUSAL_CODES,\n\tdecodeRefusalOf,\n} from '#micro509/internal/asn1/decode-refusal';\nimport {\n\tbmpString,\n\texplicitContext,\n\tintegerFromNumber,\n\tobjectIdentifier,\n\toctetString,\n\treadElement,\n\treadRootElement,\n\tsequence,\n\tsetOf,\n\ttlv,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport type { KdfBudget, KdfLimitOptions } from '#micro509/internal/crypto/pbes2';\nimport {\n\tcreateKdfBudget,\n\tdecryptPbes2,\n\tencryptPbes2,\n\tisKdfIterationLimitError,\n\tisWrongPasswordError,\n} from '#micro509/internal/crypto/pbes2';\nimport { base64Encode } from '#micro509/internal/shared/base64';\nimport type { EncryptedPkcs8Options } from '#micro509/keys/keys';\nimport { exportPkcs8Der } from '#micro509/keys/keys';\nimport { pemEncode, splitPemBlocksOrThrow } from '#micro509/pem/pem';\nimport type { ParsedPkcs12MacData, Pkcs12MacOptions } from '#micro509/pkcs/pkcs12-mac';\nimport { createPkcs12MacData, parsePkcs12MacData } from '#micro509/pkcs/pkcs12-mac';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult, rethrowIfInvariant, throwMicro509Error } from '#micro509/result/result';\nimport type { ParsedCertificate } from '#micro509/x509/parse';\nimport { parseCertificateDerOrThrow } from '#micro509/x509/parse';\n\nexport type * from '#micro509/pkcs/pkcs12-mac';\n\n/** PEM string or DER bytes for a certificate to include in a PFX bag. */\nexport type PfxCertificateSource = string | Uint8Array | ParsedCertificate;\n/** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */\nexport type PfxPrivateKeySource = CryptoKey | Uint8Array;\n\n/** Optional metadata attached to a certificate or key bag inside a PFX. */\nexport interface PfxBagAttributesInput {\n\t/**\n\t * Human-readable label stored as a BMPString attribute of 1 to 255 characters\n\t * (RFC 2985 §5.5.1), none of them a surrogate, U+FFFE or U+FFFF.\n\t */\n\treadonly friendlyName?: string;\n\t/** Opaque identifier linking a certificate bag to its corresponding key bag. */\n\treadonly localKeyId?: Uint8Array;\n}\n\n/** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxCertificateBagInput {\n\t/** Certificate as PEM text or DER bytes. */\n\treadonly certificate: PfxCertificateSource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */\nexport interface PfxPrivateKeyBagInput {\n\t/** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */\n\treadonly privateKey: PfxPrivateKeySource;\n\t/** Optional bag-level attributes (friendly name, local key ID). */\n\treadonly attributes?: PfxBagAttributesInput;\n}\n\n/** Input for {@linkcode createPfx}. */\nexport interface CreatePfxInput {\n\t/** Certificates to include as certBag entries. */\n\treadonly certificates?: readonly PfxCertificateBagInput[];\n\t/** Private keys to include as keyBag entries. */\n\treadonly privateKeys?: readonly PfxPrivateKeyBagInput[];\n\t/** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */\n\treadonly encryption?: PfxEncryptionOptions;\n\t/** PKCS#12 MAC integrity settings: the RFC 7292 MAC or RFC 9879 PBMAC1. Omit to skip MAC generation. */\n\treadonly mac?: Pkcs12MacOptions;\n}\n\n/** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode EncryptedPkcs8Options}. */\nexport type PfxEncryptionOptions = EncryptedPkcs8Options;\n\nexport type { KdfLimitOptions } from '#micro509/internal/crypto/pbes2';\n\n/** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport interface ParsePfxOptions extends KdfLimitOptions {\n\t/** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */\n\treadonly password?: string;\n\t/** Separate password for MAC verification. Falls back to `password` when omitted. */\n\treadonly macPassword?: string;\n}\n\n/** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */\nexport interface PfxMaterial {\n\t/** Raw DER-encoded PFX bytes. */\n\treadonly der: Uint8Array;\n\t/** PEM-armored PFX (`-----BEGIN PKCS12-----`). */\n\treadonly pem: string;\n\t/** Base64-encoded DER (no PEM armor). */\n\treadonly base64: string;\n}\n\n/** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */\nexport interface ParsedPfxAttribute {\n\t/** Dotted-decimal OID identifying this attribute type. */\n\treadonly oid: string;\n\t/**\n\t * Hex of each received attribute value, re-encoded with definite lengths.\n\t * Universal constructed strings are joined into primitive strings. SET OF\n\t * order and implicitly tagged constructed strings stay as received.\n\t */\n\treadonly valuesHex: readonly string[];\n}\n\n/** Decoded bag attributes for a single SafeBag inside a PFX. */\nexport interface ParsedPfxBagAttributes {\n\t/** All raw attributes as OID + hex-encoded values. */\n\treadonly entries: readonly ParsedPfxAttribute[];\n\t/** Decoded BMPString friendly-name attribute, if present. */\n\treadonly friendlyName?: string;\n\t/** Hex-encoded localKeyId attribute, if present. */\n\treadonly localKeyId?: string;\n}\n\n/**\n * Discriminated union of SafeBag types decoded from a PFX container.\n *\n * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.\n */\nexport type ParsedPfxBag =\n\t| {\n\t\t\t/** Bag contains an X.509 certificate. */\n\t\t\treadonly kind: 'certificate';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Parsed certificate from the certBag. */\n\t\t\treadonly certificate: ParsedCertificate;\n\t }\n\t| {\n\t\t\t/** Bag contains a PKCS#8 private key. */\n\t\t\treadonly kind: 'privateKey';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/** Raw DER-encoded PKCS#8 PrivateKeyInfo. */\n\t\t\treadonly pkcs8Der: Uint8Array;\n\t }\n\t| {\n\t\t\t/** Bag type not recognized by this library. */\n\t\t\treadonly kind: 'unknown';\n\t\t\t/** Dotted-decimal OID of the bag type. */\n\t\t\treadonly bagId: string;\n\t\t\t/** Decoded bag-level attributes. */\n\t\t\treadonly attributes: ParsedPfxBagAttributes;\n\t\t\t/**\n\t\t\t * The received bag value, re-encoded with definite lengths. Universal\n\t\t\t * constructed strings are joined into primitive strings. SET OF order and\n\t\t\t * implicitly tagged constructed strings stay as received.\n\t\t\t */\n\t\t\treadonly valueDer: Uint8Array;\n\t };\n\n/** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport interface ParsedPfx {\n\t/** All SafeBags in the PFX, including unknown types. */\n\treadonly bags: readonly ParsedPfxBag[];\n\t/** Convenience: only the parsed certificates extracted from certBag entries. */\n\treadonly certificates: readonly ParsedCertificate[];\n\t/** Convenience: raw PKCS#8 DER of each private key extracted from keyBag entries. */\n\treadonly privateKeys: readonly Uint8Array[];\n\t/** MAC verification metadata, present when the PFX includes a MacData block. */\n\treadonly macData?: ParsedPkcs12MacData;\n}\n\n// Result types for PFX parsing\n\n/** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */\nexport type ParsePfxErrorCode =\n\t| DecodeFailureCode\n\t| 'invalid_password'\n\t| 'password_required'\n\t| 'kdf_iterations_exceeded'\n\t| 'password_not_bmp_string'\n\t| 'password_not_utf8'\n\t| 'unsupported_mac_algorithm'\n\t| 'weak_mac_key_length';\n\n/** Error payload for a failed PFX parse. */\nexport interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */\nexport type ParsePfxResult =\n\t| {\n\t\t\t/** Parse succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** Decoded PFX container. */\n\t\t\treadonly value: ParsedPfx;\n\t }\n\t| ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\n// Result types for PFX creation\n\n/**\n * Caller-correctable failure code from {@linkcode createPfx}.\n *\n * The only parse boundary in creation is the certificate source: it is\n * normalized from untrusted PEM/DER. Private keys are either a WebCrypto\n * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through\n * unvalidated, so there is no distinct `invalid_private_key` failure to model.\n */\nexport type CreatePfxErrorCode = 'invalid_certificate';\n\n/** Bag attribute input that {@linkcode createPfx} refuses by throwing a `ResultError`. */\nexport type PfxEncoderErrorCode = 'invalid_friendly_name';\n\n/** Error payload for a failed PFX creation. */\nexport interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode createPfx}. */\nexport type CreatePfxResult =\n\t| {\n\t\t\t/** Creation succeeded. */\n\t\t\treadonly ok: true;\n\t\t\t/** DER, PEM, and base64 forms of the PFX container. */\n\t\t\treadonly value: PfxMaterial;\n\t }\n\t| ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure>;\n\n// createPfx\n\n/**\n * Builds a PKCS#12/PFX archive containing certificates and/or private keys.\n *\n * When `encryption` is provided, the key-bag ContentInfo is PBES2-encrypted.\n * When `mac` is provided, a PKCS#12 MAC integrity block is appended.\n *\n * Returns a {@linkcode CreatePfxResult}: the container material on success, or a\n * typed `invalid_certificate` failure when a certificate source is not a single\n * PEM/DER certificate.\n *\n * When `mac` is provided, `mac.type` selects the RFC 7292 MAC (the default) or\n * RFC 9879 PBMAC1.\n *\n * @throws {ResultError} with a {@linkcode CreatePkcs12MacDataErrorCode} when `mac.iterations`\n * is out of range or `mac.password` cannot be encoded for the selected MAC, and with\n * {@linkcode PfxEncoderErrorCode} `invalid_friendly_name` when a bag `friendlyName` is not a\n * BMPString of 1 to 255 characters.\n *\n * @example\n * ```ts\n * import { createPfx, unwrap } from 'micro509';\n *\n * const result = await createPfx({\n * certificates: [{ certificate: certPem }],\n * privateKeys: [{ privateKey: keyPair.privateKey }],\n * encryption: { password: 's3cret' },\n * mac: { password: 's3cret' },\n * });\n * if (result.ok) {\n * const pfx = result.value; // pfx.der, pfx.pem, pfx.base64\n * }\n * // or, when inputs are already validated: const pfx = unwrap(result);\n * ```\n */\nexport async function createPfx(input: CreatePfxInput): Promise<CreatePfxResult> {\n\tconst certificateBags: Uint8Array[] = [];\n\tconst privateKeyBags: Uint8Array[] = [];\n\tfor (const certificate of input.certificates ?? []) {\n\t\t// normalizeCertificate parses untrusted PEM/DER and throws on malformed\n\t\t// input — a caller-correctable trust boundary, so map it to a typed failure.\n\t\tlet certificateDer: Uint8Array;\n\t\ttry {\n\t\t\tcertificateDer = normalizeCertificate(certificate.certificate);\n\t\t} catch {\n\t\t\treturn pfxCreationFailure(\n\t\t\t\t'invalid_certificate',\n\t\t\t\t'Each PFX certificate source must be a single PEM or DER certificate',\n\t\t\t);\n\t\t}\n\t\tcertificateBags.push(createCertificateBag(certificateDer, certificate.attributes));\n\t}\n\tfor (const privateKey of input.privateKeys ?? []) {\n\t\tprivateKeyBags.push(\n\t\t\tcreatePrivateKeyBag(await normalizePrivateKey(privateKey.privateKey), privateKey.attributes),\n\t\t);\n\t}\n\tconst contentInfos: Uint8Array[] = [];\n\tif (certificateBags.length > 0) {\n\t\tcontentInfos.push(createDataContentInfo(sequence(certificateBags)));\n\t}\n\tif (privateKeyBags.length > 0) {\n\t\tconst safeContents = sequence(privateKeyBags);\n\t\tcontentInfos.push(\n\t\t\tinput.encryption === undefined\n\t\t\t\t? createDataContentInfo(safeContents)\n\t\t\t\t: await createEncryptedDataContentInfo(safeContents, input.encryption),\n\t\t);\n\t}\n\tconst authenticatedSafe = sequence(contentInfos);\n\tconst macData =\n\t\tinput.mac === undefined ? undefined : await createPkcs12MacData(authenticatedSafe, input.mac);\n\tconst der = sequence([\n\t\tintegerFromNumber(3),\n\t\tcreateDataContentInfo(authenticatedSafe),\n\t\t...(macData === undefined ? [] : [macData.der]),\n\t]);\n\treturn {\n\t\tok: true,\n\t\tvalue: {\n\t\t\tder,\n\t\t\tpem: pemEncode('PKCS12', der),\n\t\t\tbase64: base64Encode(der),\n\t\t},\n\t};\n}\n\n/** Shorthand for constructing a PFX creation failure result. */\nfunction pfxCreationFailure(\n\tcode: CreatePfxErrorCode,\n\tmessage: string,\n): ErrorResult<CreatePfxErrorCode, Record<never, never>, CreatePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n// parsePfxDer / parsePfxPem — Result-returning\n\n/**\n * Decodes a BER- or DER-encoded PKCS#12/PFX container into its constituent bags.\n *\n * The PFX, AuthenticatedSafe and SafeContents layers accept BER: indefinite and\n * non-minimal lengths and constructed OCTET STRINGs. The MAC is verified over the\n * AuthenticatedSafe octets as received. Certificates and private keys inside the\n * bags must be DER.\n *\n * Returns a result union — check `ok` before accessing `value`.\n * Encrypted containers require `options.password`. MAC verification uses\n * `options.macPassword` (falls back to `options.password`).\n *\n * @example\n * ```ts\n * import { parsePfxDer } from 'micro509';\n *\n * const result = await parsePfxDer(pfxBytes, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.certificates.length);\n * }\n * ```\n */\nexport async function parsePfxDer(\n\tder: Uint8Array,\n\toptions?: ParsePfxOptions,\n): Promise<ParsePfxResult> {\n\treturn await parsePfxDerWithBudget(der, options, createKdfBudget(options));\n}\n\nasync function parsePfxDerWithBudget(\n\tder: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n\tbudget: KdfBudget,\n): Promise<ParsePfxResult> {\n\ttry {\n\t\tconst topLevel = berSequenceChildren(readBerRoot(der));\n\t\tif (topLevel.length < 2 || topLevel.length > 3) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tconst version = topLevel[0];\n\t\tconst authSafe = topLevel[1];\n\t\tif (version === undefined || authSafe === undefined) {\n\t\t\treturn pfxFailure('malformed', 'Malformed PFX structure');\n\t\t}\n\t\tif (decodeIntegerNumber(berPrimitiveContent(der, version, 0x02)) !== 3) {\n\t\t\treturn pfxFailure('malformed', 'Unsupported PFX version');\n\t\t}\n\t\tconst authenticatedSafeOctets = extractContentInfoData(der, authSafe);\n\t\tconst macElement = topLevel[2];\n\t\tlet macData: ParsedPkcs12MacData | undefined;\n\t\tif (macElement !== undefined) {\n\t\t\tconst macResult = await verifyPfxMacData(\n\t\t\t\tberToDefiniteLength(der, macElement),\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\toptions,\n\t\t\t);\n\t\t\tif (macResult.error !== undefined) {\n\t\t\t\treturn macResult.error;\n\t\t\t}\n\t\t\tmacData = macResult.macData;\n\t\t}\n\t\tconst bags: ParsedPfxBag[] = [];\n\t\tfor (const contentInfo of berSequenceChildren(readBerRoot(authenticatedSafeOctets))) {\n\t\t\tconst safeContentsResult = await extractSafeContents(\n\t\t\t\tauthenticatedSafeOctets,\n\t\t\t\tcontentInfo,\n\t\t\t\toptions,\n\t\t\t\tbudget,\n\t\t\t);\n\t\t\tif (safeContentsResult.error !== undefined) {\n\t\t\t\treturn safeContentsResult.error;\n\t\t\t}\n\t\t\tconst safeContents = safeContentsResult.data;\n\t\t\tfor (const bag of berSequenceChildren(safeContentsResult.root)) {\n\t\t\t\tbags.push(parseSafeBag(safeContents, bag));\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tok: true,\n\t\t\tvalue: {\n\t\t\t\tbags,\n\t\t\t\tcertificates: bags.flatMap((bag) => (bag.kind === 'certificate' ? [bag.certificate] : [])),\n\t\t\t\tprivateKeys: bags.flatMap((bag) => (bag.kind === 'privateKey' ? [bag.pkcs8Der] : [])),\n\t\t\t\t...(macData === undefined ? {} : { macData }),\n\t\t\t},\n\t\t};\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_REFUSAL_CODES);\n\t\treturn refusal === undefined\n\t\t\t? pfxFailure('malformed', 'Malformed PFX structure')\n\t\t\t: pfxFailure(refusal.code, refusal.message);\n\t}\n}\n\n/**\n * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.\n *\n * Delegates to {@linkcode parsePfxDer} after PEM decoding.\n *\n * @example\n * ```ts\n * import { parsePfxPem } from 'micro509';\n *\n * const result = await parsePfxPem(pfxPemString, { password: 's3cret' });\n * if (result.ok) {\n * console.log(result.value.privateKeys.length);\n * }\n * ```\n */\nexport async function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult> {\n\tconst budget = createKdfBudget(options);\n\tlet bytes: Uint8Array;\n\ttry {\n\t\tconst blocks = splitPemBlocksOrThrow(pem).filter((block) => block.label === 'PKCS12');\n\t\tconst block = blocks[0];\n\t\tif (block === undefined || blocks.length !== 1) {\n\t\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t\t}\n\t\tbytes = block.bytes;\n\t} catch {\n\t\treturn pfxFailure('malformed', 'Expected exactly one PKCS12 PEM block');\n\t}\n\treturn await parsePfxDerWithBudget(bytes, options, budget);\n}\n\n// Private: PFX helpers\n\n/** Shorthand for constructing a PFX parse failure result. */\nfunction pfxFailure(\n\tcode: ParsePfxErrorCode,\n\tmessage: string,\n): ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure> {\n\treturn failureResult(code, message);\n}\n\n/** Unwraps a `data` ContentInfo to its inner OCTET STRING payload. */\nfunction extractContentInfoData(source: Uint8Array, contentInfo: BerElement): Uint8Array {\n\tconst { oid, content } = readContentInfo(source, contentInfo);\n\tif (oid !== OIDS.pkcs7Data) {\n\t\tthrow new Error('Only passwordless data ContentInfo is supported');\n\t}\n\treturn extractContextOctetString(source, content);\n}\n\nfunction readContentInfo(\n\tsource: Uint8Array,\n\tcontentInfo: BerElement,\n): { readonly oid: string; readonly content: BerElement } {\n\tconst children = berSequenceChildren(contentInfo);\n\tconst contentType = children[0];\n\tconst content = children[1];\n\tif (contentType === undefined || content === undefined || children.length !== 2) {\n\t\tthrow new Error('Malformed ContentInfo');\n\t}\n\treturn {\n\t\toid: decodeObjectIdentifier(berPrimitiveContent(source, contentType, 0x06)),\n\t\tcontent,\n\t};\n}\n\n/** Extracts SafeContents bytes from a ContentInfo, decrypting if EncryptedData. */\nasync function extractSafeContents(\n\tsource: Uint8Array,\n\tcontentInfo: BerElement,\n\toptions: ParsePfxOptions | undefined,\n\tbudget: KdfBudget,\n): Promise<\n\t| {\n\t\t\treadonly data: Uint8Array;\n\t\t\treadonly root: BerElement;\n\t\t\treadonly error?: undefined;\n\t }\n\t| {\n\t\t\treadonly data?: undefined;\n\t\t\treadonly root?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tlet oid: string;\n\tlet content: BerElement;\n\ttry {\n\t\t({ oid, content } = readContentInfo(source, contentInfo));\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\terror:\n\t\t\t\trefusal === undefined\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed ContentInfo')\n\t\t\t\t\t: pfxFailure(refusal.code, refusal.message),\n\t\t};\n\t}\n\tif (oid === OIDS.pkcs7Data) {\n\t\tconst data = extractContextOctetString(source, content);\n\t\treturn { data, root: readBerRoot(data) };\n\t}\n\tif (oid !== OIDS.pkcs7EncryptedData) {\n\t\treturn {\n\t\t\terror: pfxFailure('malformed', 'Unsupported PFX ContentInfo type'),\n\t\t};\n\t}\n\tif (options?.password === undefined) {\n\t\treturn {\n\t\t\terror: pfxFailure('password_required', 'Password required for encrypted PFX content'),\n\t\t};\n\t}\n\tconst encryptedData = extractContextChild(content);\n\tlet decrypted: Uint8Array;\n\ttry {\n\t\tdecrypted = await decryptEncryptedData(source, encryptedData, options.password, budget);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isWrongPasswordError(error)) {\n\t\t\treturn {\n\t\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t\t};\n\t\t}\n\t\tif (isKdfIterationLimitError(error)) {\n\t\t\treturn { error: pfxFailure('kdf_iterations_exceeded', error.message) };\n\t\t}\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\treturn {\n\t\t\terror:\n\t\t\t\trefusal === undefined\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed PFX encrypted content')\n\t\t\t\t\t: pfxFailure(refusal.code, refusal.message),\n\t\t};\n\t}\n\ttry {\n\t\tconst root = readBerRoot(decrypted);\n\t\tberSequenceChildren(root);\n\t\treturn { data: decrypted, root };\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tconst refusal = decodeRefusalOf(error, DECODE_LIMIT_CODES);\n\t\tif (refusal !== undefined) {\n\t\t\treturn { error: pfxFailure(refusal.code, refusal.message) };\n\t\t}\n\t\t// AES-CBC padding is unauthenticated: a wrong key passes the padding\n\t\t// check ~1/256 of the time and \"decrypts\" to random bytes that are not\n\t\t// a SafeContents SEQUENCE — a wrong password, not malformed input.\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX password or encrypted content'),\n\t\t};\n\t}\n}\n\n/** Encodes a certBag SafeBag wrapping a DER certificate with optional attributes. */\nfunction createCertificateBag(\n\tcertificateDer: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\tconst certBag = sequence([\n\t\tobjectIdentifier(OIDS.x509CertificateBagType),\n\t\texplicitContext(0, octetString(certificateDer)),\n\t]);\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12CertBag),\n\t\texplicitContext(0, certBag),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Encodes a keyBag SafeBag wrapping PKCS#8 DER with optional attributes. */\nfunction createPrivateKeyBag(\n\tpkcs8Der: Uint8Array,\n\tattributes: PfxBagAttributesInput | undefined,\n): Uint8Array {\n\treturn sequence([\n\t\tobjectIdentifier(OIDS.pkcs12KeyBag),\n\t\texplicitContext(0, pkcs8Der),\n\t\t...encodeBagAttributes(attributes),\n\t]);\n}\n\n/** Wraps raw bytes in a `pkcs7-data` ContentInfo SEQUENCE. */\nfunction createDataContentInfo(data: Uint8Array): Uint8Array {\n\treturn sequence([objectIdentifier(OIDS.pkcs7Data), explicitContext(0, octetString(data))]);\n}\n\n/** PBES2-encrypts data and wraps it in a `pkcs7-encryptedData` ContentInfo. */\nasync function createEncryptedDataContentInfo(\n\tdata: Uint8Array,\n\toptions: PfxEncryptionOptions,\n): Promise<Uint8Array> {\n\tconst encryption = await encryptPbes2(data, options);\n\tconst encryptedData = sequence([\n\t\tintegerFromNumber(0),\n\t\tsequence([\n\t\t\tobjectIdentifier(OIDS.pkcs7Data),\n\t\t\tencryption.algorithmIdentifierDer,\n\t\t\ttlv(0x80, encryption.encryptedData),\n\t\t]),\n\t]);\n\treturn sequence([objectIdentifier(OIDS.pkcs7EncryptedData), explicitContext(0, encryptedData)]);\n}\n\n/** DER-encodes optional friendlyName / localKeyId into a SET OF SEQUENCE. */\nfunction encodeBagAttributes(attributes: PfxBagAttributesInput | undefined): readonly Uint8Array[] {\n\tif (attributes === undefined) {\n\t\treturn [];\n\t}\n\tconst out: Uint8Array[] = [];\n\tif (attributes.friendlyName !== undefined) {\n\t\tout.push(\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(OIDS.friendlyName),\n\t\t\t\tsetOf([encodeFriendlyName(attributes.friendlyName)]),\n\t\t\t]),\n\t\t);\n\t}\n\tif (attributes.localKeyId !== undefined) {\n\t\tout.push(\n\t\t\tsequence([objectIdentifier(OIDS.localKeyId), setOf([octetString(attributes.localKeyId)])]),\n\t\t);\n\t}\n\treturn out.length === 0 ? [] : [setOf(out)];\n}\n\n/** RFC 2985 §5.5.1: `pkcs-9-ub-friendlyName`. */\nconst MAX_FRIENDLY_NAME_LENGTH = 255;\n\nfunction encodeFriendlyName(friendlyName: string): Uint8Array {\n\tconst refuse = (): never =>\n\t\tthrowMicro509Error<PfxEncoderErrorCode>(\n\t\t\t'invalid_friendly_name',\n\t\t\t'friendlyName must be a BMPString of 1 to 255 characters, none of them a surrogate, U+FFFE or U+FFFF',\n\t\t);\n\tif (friendlyName.length === 0 || friendlyName.length > MAX_FRIENDLY_NAME_LENGTH) {\n\t\treturn refuse();\n\t}\n\ttry {\n\t\treturn bmpString(friendlyName);\n\t} catch {\n\t\treturn refuse();\n\t}\n}\n\n/** Decodes a single SafeBag into a {@linkcode ParsedPfxBag} discriminated union. */\nfunction parseSafeBag(source: Uint8Array, bag: BerElement): ParsedPfxBag {\n\tconst children = berSequenceChildren(bag);\n\tconst bagId = children[0];\n\tconst bagValue = children[1];\n\tconst attributeSet = children[2];\n\tif (bagId === undefined || bagValue === undefined || children.length > 3) {\n\t\tthrow new Error('Malformed SafeBag');\n\t}\n\tconst bagOid = decodeObjectIdentifier(berPrimitiveContent(source, bagId, 0x06));\n\tconst attributes = parseBagAttributes(source, attributeSet);\n\tconst value = extractContextChild(bagValue);\n\tif (bagOid === OIDS.pkcs12CertBag) {\n\t\tconst certBagChildren = berSequenceChildren(value);\n\t\tconst certType = certBagChildren[0];\n\t\tconst certValue = certBagChildren[1];\n\t\tif (\n\t\t\tcertType === undefined ||\n\t\t\tcertValue === undefined ||\n\t\t\tcertBagChildren.length !== 2 ||\n\t\t\tdecodeObjectIdentifier(berPrimitiveContent(source, certType, 0x06)) !==\n\t\t\t\tOIDS.x509CertificateBagType\n\t\t) {\n\t\t\tthrow new Error('Malformed certBag');\n\t\t}\n\t\treturn {\n\t\t\tkind: 'certificate',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tcertificate: parseCertificateDerOrThrow(extractContextOctetString(source, certValue)),\n\t\t};\n\t}\n\tif (bagOid === OIDS.pkcs12KeyBag) {\n\t\tconst pkcs8Der = berEncoding(source, value);\n\t\treadRootElement(pkcs8Der);\n\t\treturn {\n\t\t\tkind: 'privateKey',\n\t\t\tbagId: bagOid,\n\t\t\tattributes,\n\t\t\tpkcs8Der,\n\t\t};\n\t}\n\treturn {\n\t\tkind: 'unknown',\n\t\tbagId: bagOid,\n\t\tattributes,\n\t\tvalueDer: berToDefiniteLength(source, value),\n\t};\n}\n\n/** Decodes the SET OF attributes attached to a SafeBag. */\nfunction parseBagAttributes(\n\tsource: Uint8Array,\n\tattributeSet: BerElement | undefined,\n): ParsedPfxBagAttributes {\n\tif (attributeSet === undefined) {\n\t\treturn { entries: [] };\n\t}\n\tif (attributeSet.tag !== 0x31) {\n\t\tthrow new Error('Malformed PFX bag attributes');\n\t}\n\tconst entries: ParsedPfxAttribute[] = [];\n\tlet friendlyName: string | undefined;\n\tlet localKeyId: string | undefined;\n\tfor (const attribute of attributeSet.children) {\n\t\tconst parts = berSequenceChildren(attribute);\n\t\tconst oid = parts[0];\n\t\tconst values = parts[1];\n\t\tif (oid === undefined || values === undefined || parts.length !== 2 || values.tag !== 0x31) {\n\t\t\tthrow new Error('Malformed PFX bag attribute');\n\t\t}\n\t\tconst attrOid = decodeObjectIdentifier(berPrimitiveContent(source, oid, 0x06));\n\t\tconst rawValues = values.children.map((value) => berToDefiniteLength(source, value));\n\t\tentries.push({\n\t\t\toid: attrOid,\n\t\t\tvaluesHex: rawValues.map((value) => toHex(value)),\n\t\t});\n\t\tif (attrOid === OIDS.friendlyName) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (friendlyName !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed friendlyName attribute');\n\t\t\t}\n\t\t\tfriendlyName = decodeFriendlyName(firstValue);\n\t\t\tcontinue;\n\t\t}\n\t\tif (attrOid === OIDS.localKeyId) {\n\t\t\tconst firstValue = rawValues[0];\n\t\t\tif (localKeyId !== undefined || rawValues.length !== 1 || firstValue === undefined) {\n\t\t\t\tthrow new Error('Malformed localKeyId attribute');\n\t\t\t}\n\t\t\tlocalKeyId = decodeLocalKeyId(firstValue);\n\t\t}\n\t}\n\treturn {\n\t\tentries,\n\t\t...(friendlyName === undefined ? {} : { friendlyName }),\n\t\t...(localKeyId === undefined ? {} : { localKeyId }),\n\t};\n}\n\nfunction decodeLocalKeyId(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x04) {\n\t\tthrow new Error('localKeyId must use OCTET STRING');\n\t}\n\treturn toHex(element.value);\n}\n\n/** Exports a `CryptoKey` to PKCS#8 DER, or passes raw bytes through. */\nfunction normalizePrivateKey(source: PfxPrivateKeySource): Promise<Uint8Array> {\n\treturn source instanceof CryptoKey\n\t\t? exportPkcs8Der(source)\n\t\t: Promise.resolve(new Uint8Array(source));\n}\n\n/** Extracts DER bytes from a PEM string, or passes raw DER through. */\nfunction normalizeCertificate(source: PfxCertificateSource): Uint8Array {\n\tif (typeof source === 'string') {\n\t\tconst block = splitPemBlocksOrThrow(source).find(\n\t\t\t(candidate) => candidate.label === 'CERTIFICATE',\n\t\t);\n\t\tif (block === undefined) {\n\t\t\tthrow new Error('Certificate PEM required');\n\t\t}\n\t\treturn new Uint8Array(block.bytes);\n\t}\n\tif (source instanceof Uint8Array) {\n\t\treturn new Uint8Array(source);\n\t}\n\treturn new Uint8Array(source.der);\n}\n\n/** Parses the MacData block and verifies it against the AuthenticatedSafe when a password is given. */\nasync function verifyPfxMacData(\n\tmacDataDer: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\toptions: ParsePfxOptions | undefined,\n): Promise<\n\t| { readonly macData: ParsedPkcs12MacData; readonly error?: undefined }\n\t| {\n\t\t\treadonly macData?: undefined;\n\t\t\treadonly error: ErrorResult<ParsePfxErrorCode, Record<never, never>, ParsePfxFailure>;\n\t }\n> {\n\tconst macResult = await parsePkcs12MacData(\n\t\tmacDataDer,\n\t\tauthenticatedSafe,\n\t\toptions?.macPassword ?? options?.password,\n\t\toptions,\n\t);\n\tif (!macResult.ok) {\n\t\treturn {\n\t\t\terror:\n\t\t\t\tmacResult.code === 'malformed'\n\t\t\t\t\t? pfxFailure('malformed', 'Malformed PFX MacData')\n\t\t\t\t\t: pfxFailure(macResult.code, macResult.message),\n\t\t};\n\t}\n\tif (macResult.value.verification === 'invalid') {\n\t\treturn {\n\t\t\terror: pfxFailure('invalid_password', 'Invalid PFX MAC password or corrupted content'),\n\t\t};\n\t}\n\treturn { macData: macResult.value };\n}\n\n/** Decrypts a PKCS#7 EncryptedData structure using PBES2 with the given password. */\nfunction decryptEncryptedData(\n\tsource: Uint8Array,\n\tencryptedData: BerElement,\n\tpassword: string,\n\tbudget: KdfBudget,\n): Promise<Uint8Array> {\n\tconst topLevel = berSequenceChildren(encryptedData);\n\tconst version = topLevel[0];\n\tconst encryptedContentInfo = topLevel[1];\n\tif (topLevel.length !== 2 || version === undefined || encryptedContentInfo === undefined) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tif (decodeIntegerNumber(berPrimitiveContent(source, version, 0x02)) !== 0) {\n\t\tthrow new Error('Malformed EncryptedData');\n\t}\n\tconst contentInfoChildren = berSequenceChildren(encryptedContentInfo);\n\tconst contentType = contentInfoChildren[0];\n\tconst algorithm = contentInfoChildren[1];\n\tconst encryptedContent = contentInfoChildren[2];\n\tif (\n\t\tcontentType === undefined ||\n\t\talgorithm === undefined ||\n\t\tencryptedContent === undefined ||\n\t\tcontentInfoChildren.length !== 3\n\t) {\n\t\tthrow new Error('Malformed EncryptedContentInfo');\n\t}\n\tberPrimitiveContent(source, contentType, 0x06);\n\treturn decryptPbes2(\n\t\tberToDefiniteLength(source, algorithm),\n\t\tberStringContent(source, encryptedContent, 0x80, 0x04),\n\t\tpassword,\n\t\tbudget,\n\t);\n}\n\n/** Reads the OCTET STRING inside a `[0] EXPLICIT` wrapper. */\nfunction extractContextOctetString(source: Uint8Array, element: BerElement): Uint8Array {\n\treturn berStringContent(source, extractContextChild(element), 0x04);\n}\n\n/** Reads the single child element inside a `[0] EXPLICIT` wrapper. */\nfunction extractContextChild(element: BerElement): BerElement {\n\tif (element.tag !== 0xa0) {\n\t\tthrow new Error('Expected [0] EXPLICIT value');\n\t}\n\tconst child = element.children[0];\n\tif (element.children.length !== 1 || child === undefined) {\n\t\tthrow new Error('Expected context-specific wrapper with exactly one value');\n\t}\n\treturn child;\n}\n\n/** RFC 2985 §5.5.1: a friendlyName value is a BMPString of SIZE (1..255). */\nfunction decodeFriendlyName(der: Uint8Array): string {\n\tconst element = readElement(der);\n\tif (element.tag !== 0x1e) {\n\t\tthrow new Error('friendlyName must be a BMPString');\n\t}\n\tconst friendlyName = decodeString(0x1e, element.value);\n\tif (friendlyName.length < 1 || friendlyName.length > MAX_FRIENDLY_NAME_LENGTH) {\n\t\tthrow new Error('friendlyName must hold 1 to 255 characters');\n\t}\n\treturn friendlyName;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6SA,eAAsB,UAAUuC,GAAiD;CAChF,IAAMC,IAAgC,CAAC,GACjCC,IAA+B,CAAC;CACtC,KAAK,IAAMC,KAAeH,EAAM,gBAAgB,CAAC,GAAG;EAGnD,IAAII;EACJ,IAAI;GACHA,IAAiB,qBAAqBD,EAAY,WAAW;EAC9D,QAAQ;GACP,OAAO,mBACN,uBACA,qEACD;EACD;EACAF,EAAgB,KAAK,qBAAqBG,GAAgBD,EAAY,UAAU,CAAC;CAClF;CACA,KAAK,IAAME,KAAcL,EAAM,eAAe,CAAC,GAC9CE,EAAe,KACd,oBAAoB,MAAM,oBAAoBG,EAAW,UAAU,GAAGA,EAAW,UAAU,CAC5F;CAED,IAAMC,IAA6B,CAAC;CAIpC,IAHIL,EAAgB,SAAS,KAC5BK,EAAa,KAAK,sBAAsB1B,EAASqB,CAAe,CAAC,CAAC,GAE/DC,EAAe,SAAS,GAAG;EAC9B,IAAMK,IAAe3B,EAASsB,CAAc;EAC5CI,EAAa,KACZN,EAAM,eAAe,KAAA,IAClB,sBAAsBO,CAAY,IAClC,MAAM,+BAA+BA,GAAcP,EAAM,UAAU,CACvE;CACD;CACA,IAAMQ,IAAoB5B,EAAS0B,CAAY,GACzCG,IACLT,EAAM,QAAQ,KAAA,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B,GAAoB+B,GAAiC;CACvF,OAAO9F,EAAiB+D,GAAQ,oBAAoB+B,CAAO,GAAG,CAAI;AACnE;;AAGA,SAAS,oBAAoBA,GAAiC;CAC7D,IAAIA,EAAQ,QAAQ,KACnB,MAAU,MAAM,6BAA6B;CAE9C,IAAMQ,IAAQR,EAAQ,SAAS;CAC/B,IAAIA,EAAQ,SAAS,WAAW,KAAKQ,MAAU,KAAA,GAC9C,MAAU,MAAM,0DAA0D;CAE3E,OAAOA;AACR;;AAGA,SAAS,mBAAmB5D,GAAyB;CACpD,IAAMoD,IAAUpF,EAAYgC,CAAG;CAC/B,IAAIoD,EAAQ,QAAQ,IACnB,MAAU,MAAM,kCAAkC;CAEnD,IAAMjB,IAAelF,EAAa,IAAMmG,EAAQ,KAAK;CACrD,IAAIjB,EAAa,SAAS,KAAKA,EAAa,SAAS,KACpD,MAAU,MAAM,4CAA4C;CAE7D,OAAOA;AACR"}
@@ -165,7 +165,7 @@ async function parsePkcs12MacData(e, t, n, r) {
165
165
  function decodeMacIterations(t, n, r, i) {
166
166
  let a = e(t, i);
167
167
  if (a.type === "safe") return a.value;
168
- throw r !== void 0 && v(n, Infinity), Error(`${i} too large for safe number (${t.length} bytes)`);
168
+ throw r !== void 0 && v(n, 1e400), Error(`${i} too large for safe number (${t.length} bytes)`);
169
169
  }
170
170
  async function verifyPbmac1MacData(e, t, n, i, a, o) {
171
171
  if (t === void 0) throw Error("PBMAC1 parameters must be present");
@@ -1 +1 @@
1
- {"version":3,"file":"pkcs12-mac.js","names":["_exhaustive","code","message","options","authenticatedSafe","iterations","salt","getCrypto","mac","sequence","objectIdentifier","OIDS","nullValue","octetString","integerFromNumber","describeHashAlgorithm","toHex","WEBCRYPTO_MAX_PBKDF2_ITERATIONS","parameters","hmacWithSha256","algorithm","THROWN_MAC_DATA_ERROR_CODES","pkcs12Budget","createKdfBudget","DEFAULT_MAX_PKCS12_MAC_ITERATIONS","pbkdf2Budget","DEFAULT_MAX_KDF_ITERATIONS","top","readSequenceChildren","der","digestInfo","digestInfoDer","digestInfoChildren","digest","algorithmDer","algorithmChildren","algorithmOid","digestAlgorithmOid","decodeObjectIdentifier","password","parsedIterations","unchecked","expected","successResult","error","rethrowIfInvariant","isKdfIterationLimitError","failureResult","isResultError","candidate","decodeFailureResult","DECODE_LIMIT_CODES","magnitude","decodeIntegerMagnitude","content","label","chargeKdfBudget","budget","parametersElement","paramsDer","children","kdfElement","macElement","kdf","messageAuthScheme","iterationCount","optional","keyLengthElement","rest","prfElement","prf","element","source","oid","name","derivePbkdf2Bytes","index","next","key","toArrayBuffer","keyBytes","D","id","passwordBytes","I","concatBytes","blocks","length","output","A","round","B","offset","bytes","out","size","carry","block","sum","addend","left","right","result"],"sources":["../../src/pkcs/pkcs12-mac.ts"],"sourcesContent":["/**\n * PKCS#12 MAC data creation and verification.\n *\n * Computes and verifies the password-based integrity check of a PFX: the\n * RFC 7292 HMAC-SHA-256 MAC keyed by the PKCS#12 key-derivation scheme, and\n * PBMAC1 (RFC 9879) keyed by PBKDF2.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerMagnitude,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, decodeFailureResult } from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names';\nimport type { KdfBudget, KdfLimitOptions, Pbkdf2Hash } from '#micro509/internal/crypto/pbes2';\nimport {\n\tchargeKdfBudget,\n\tcreateKdfBudget,\n\tDEFAULT_MAX_KDF_ITERATIONS,\n\tDEFAULT_MAX_PKCS12_MAC_ITERATIONS,\n\tderivePbkdf2Bytes,\n\tisKdfIterationLimitError,\n\tWEBCRYPTO_MAX_PBKDF2_ITERATIONS,\n} from '#micro509/internal/crypto/pbes2';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport {\n\tfailureResult,\n\tisResultError,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n} from '#micro509/result/result';\n\n/** Machine-readable reason {@linkcode createPkcs12MacData} rejected its construction input. */\nexport type CreatePkcs12MacDataErrorCode =\n\t| 'password_not_bmp_string'\n\t| 'password_not_utf8'\n\t| 'invalid_iterations';\n\nfunction throwPkcs12MacError(code: CreatePkcs12MacDataErrorCode, message: string): never {\n\tthrowMicro509Error(code, message);\n}\n\n/**\n * Input for {@linkcode createPkcs12MacData}. `type` selects the MAC: `'pkcs12-kdf'` (the\n * default) is the RFC 7292 HMAC-SHA-256 MAC keyed by the PKCS#12 KDF, and `'pbmac1'` is\n * RFC 9879 PBMAC1 with PBKDF2-HMAC-SHA-256, a 32-octet key and HMAC-SHA-256.\n */\nexport type Pkcs12MacOptions =\n\t| {\n\t\t\t/** RFC 7292 Appendix B key derivation with HMAC-SHA-256. */\n\t\t\treadonly type?: 'pkcs12-kdf';\n\t\t\t/**\n\t\t\t * Password used to derive the HMAC key via the PKCS#12 KDF. Every character must be a\n\t\t\t * BMPString character, so UTF-16 surrogates, U+FFFE and U+FFFF are rejected.\n\t\t\t */\n\t\t\treadonly password: string;\n\t\t\t/** PKCS#12 KDF iteration count, a positive safe integer. Default: `2048`. */\n\t\t\treadonly iterations?: number;\n\t\t\t/** Random salt. Default: 16 cryptographically random bytes. */\n\t\t\treadonly salt?: Uint8Array;\n\t }\n\t| {\n\t\t\t/** RFC 9879 PBMAC1. */\n\t\t\treadonly type: 'pbmac1';\n\t\t\t/**\n\t\t\t * Password fed to PBKDF2 as UTF-8 without a NULL terminator. Unpaired UTF-16\n\t\t\t * surrogates are rejected.\n\t\t\t */\n\t\t\treadonly password: string;\n\t\t\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */\n\t\t\treadonly iterations?: number;\n\t\t\t/** PBKDF2 salt, also written to the ignored MacData macSalt. Default: 16 random bytes. */\n\t\t\treadonly salt?: Uint8Array;\n\t };\n\n/**\n * Decoded PKCS#12 MacData block returned by {@linkcode parsePkcs12MacData}. `type` names the\n * MAC: `'pkcs12-kdf'` for the RFC 7292 MAC and `'pbmac1'` for RFC 9879 PBMAC1.\n */\nexport type ParsedPkcs12MacData =\n\t| {\n\t\t\t/** RFC 7292 MAC keyed by the PKCS#12 KDF. */\n\t\t\treadonly type: 'pkcs12-kdf';\n\t\t\t/** OID of the digest algorithm (always SHA-256). */\n\t\t\treadonly digestAlgorithmOid: string;\n\t\t\t/** Human-readable digest algorithm name (`\"SHA-256\"`). */\n\t\t\treadonly digestAlgorithmName: string;\n\t\t\t/** Hex-encoded MAC digest value. */\n\t\t\treadonly digestHex: string;\n\t\t\t/** Hex-encoded MacData macSalt. */\n\t\t\treadonly saltHex: string;\n\t\t\t/** MacData iterations, the PKCS#12 KDF iteration count. */\n\t\t\treadonly iterations: number;\n\t\t\t/**\n\t\t\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t\t\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t\t\t */\n\t\t\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n\t }\n\t| {\n\t\t\t/** RFC 9879 PBMAC1 keyed by PBKDF2. */\n\t\t\treadonly type: 'pbmac1';\n\t\t\t/** The id-PBMAC1 OID. */\n\t\t\treadonly digestAlgorithmOid: string;\n\t\t\t/** Always `\"PBMAC1\"`. */\n\t\t\treadonly digestAlgorithmName: string;\n\t\t\t/** Hex-encoded MAC value. */\n\t\t\treadonly digestHex: string;\n\t\t\t/** Hex-encoded PBKDF2 salt. MacData macSalt is ignored. */\n\t\t\treadonly saltHex: string;\n\t\t\t/** PBKDF2 iteration count. MacData iterations is ignored. */\n\t\t\treadonly iterations: number;\n\t\t\t/** PBKDF2 keyLength in octets. */\n\t\t\treadonly keyLength: number;\n\t\t\t/** PBKDF2 pseudorandom function. */\n\t\t\treadonly prf: 'HMAC-SHA-256' | 'HMAC-SHA-384' | 'HMAC-SHA-512';\n\t\t\t/** PBMAC1 message authentication scheme. */\n\t\t\treadonly messageAuthScheme: 'HMAC-SHA-256' | 'HMAC-SHA-384' | 'HMAC-SHA-512';\n\t\t\t/**\n\t\t\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t\t\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t\t\t */\n\t\t\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n\t };\n\ntype ParsedPbmac1MacData = Extract<ParsedPkcs12MacData, { readonly type: 'pbmac1' }>;\ntype Pbmac1Hmac = ParsedPbmac1MacData['prf'];\n\nconst PBMAC1_MAX_KEY_LENGTH = 64;\nconst PBMAC1_MIN_KEY_LENGTH = 20;\n\n/**\n * Computes a PKCS#12 MAC over the AuthenticatedSafe and returns the DER-encoded MacData\n * block alongside its parsed representation.\n *\n * @throws {ResultError} with code `invalid_iterations` when `iterations` is out of range,\n * `password_not_bmp_string` when a `'pkcs12-kdf'` password contains a UTF-16 surrogate, U+FFFE\n * or U+FFFF, and `password_not_utf8` when a `'pbmac1'` password contains an unpaired UTF-16\n * surrogate.\n */\nexport async function createPkcs12MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Pkcs12MacOptions,\n): Promise<{\n\t/** DER-encoded MacData SEQUENCE. */\n\treadonly der: Uint8Array;\n\t/** Structured representation of the MAC parameters and digest. */\n\treadonly parsed: ParsedPkcs12MacData;\n}> {\n\tif (options.type === 'pbmac1') {\n\t\treturn await createPbmac1MacData(authenticatedSafe, options);\n\t}\n\tconst iterations = options.iterations ?? 2048;\n\tif (!Number.isSafeInteger(iterations) || iterations <= 0) {\n\t\tthrowPkcs12MacError(\n\t\t\t'invalid_iterations',\n\t\t\t`MacData iterations must be a positive safe integer, got ${iterations}`,\n\t\t);\n\t}\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst mac = await computePkcs12Mac(authenticatedSafe, options.password, salt, iterations);\n\tconst der = sequence([\n\t\tsequence([sequence([objectIdentifier(OIDS.sha256), nullValue()]), octetString(mac)]),\n\t\toctetString(salt),\n\t\t...(iterations === 1 ? [] : [integerFromNumber(iterations)]),\n\t]);\n\treturn {\n\t\tder,\n\t\tparsed: {\n\t\t\ttype: 'pkcs12-kdf',\n\t\t\tdigestAlgorithmOid: OIDS.sha256,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(OIDS.sha256),\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\nasync function createPbmac1MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Extract<Pkcs12MacOptions, { readonly type: 'pbmac1' }>,\n): Promise<{ readonly der: Uint8Array; readonly parsed: ParsedPkcs12MacData }> {\n\tconst iterations = options.iterations ?? 100_000;\n\tif (\n\t\t!Number.isInteger(iterations) ||\n\t\titerations < 1 ||\n\t\titerations > WEBCRYPTO_MAX_PBKDF2_ITERATIONS\n\t) {\n\t\tthrowPkcs12MacError(\n\t\t\t'invalid_iterations',\n\t\t\t`PBMAC1 iterations must be an integer from 1 to ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterations}`,\n\t\t);\n\t}\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst parameters: Pbmac1Parameters = {\n\t\tsalt,\n\t\titerations,\n\t\tkeyLength: 32,\n\t\tprf: 'HMAC-SHA-256',\n\t\tmessageAuthScheme: 'HMAC-SHA-256',\n\t};\n\tconst mac = await computePbmac1(authenticatedSafe, options.password, parameters);\n\tconst hmacWithSha256 = sequence([objectIdentifier(OIDS.hmacWithSHA256), nullValue()]);\n\tconst algorithm = sequence([\n\t\tobjectIdentifier(OIDS.pbmac1),\n\t\tsequence([\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(OIDS.pbkdf2),\n\t\t\t\tsequence([\n\t\t\t\t\toctetString(salt),\n\t\t\t\t\tintegerFromNumber(iterations),\n\t\t\t\t\tintegerFromNumber(parameters.keyLength),\n\t\t\t\t\thmacWithSha256,\n\t\t\t\t]),\n\t\t\t]),\n\t\t\thmacWithSha256,\n\t\t]),\n\t]);\n\treturn {\n\t\tder: sequence([sequence([algorithm, octetString(mac)]), octetString(salt)]),\n\t\tparsed: {\n\t\t\ttype: 'pbmac1',\n\t\t\tdigestAlgorithmOid: OIDS.pbmac1,\n\t\t\tdigestAlgorithmName: 'PBMAC1',\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tkeyLength: parameters.keyLength,\n\t\t\tprf: parameters.prf,\n\t\t\tmessageAuthScheme: parameters.messageAuthScheme,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\n/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataErrorCode =\n\t| Exclude<DecodeFailureCode, 'unsupported'>\n\t| 'kdf_iterations_exceeded'\n\t| 'password_not_bmp_string'\n\t| 'password_not_utf8'\n\t| 'unsupported_mac_algorithm'\n\t| 'weak_mac_key_length';\n\ntype ThrownMacDataErrorCode = Exclude<\n\tParsePkcs12MacDataErrorCode,\n\tDecodeFailureCode | 'kdf_iterations_exceeded'\n>;\n\nconst THROWN_MAC_DATA_ERROR_CODES = [\n\t'password_not_bmp_string',\n\t'password_not_utf8',\n\t'unsupported_mac_algorithm',\n\t'weak_mac_key_length',\n] as const satisfies readonly ThrownMacDataErrorCode[];\n\nfunction throwMacDataError(\n\tcode: 'unsupported_mac_algorithm' | 'weak_mac_key_length',\n\tmessage: string,\n): never {\n\tthrowMicro509Error(code, message);\n}\n\n/** Options for {@linkcode parsePkcs12MacData} and {@linkcode parsePkcs12MacDataOrThrow}. */\nexport type ParsePkcs12MacDataOptions = KdfLimitOptions;\n\n/** Structured failure payload for MacData parsing. */\nexport interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataResult =\n\t| { readonly ok: true; readonly value: ParsedPkcs12MacData }\n\t| ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;\n\n/**\n * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is\n * provided, verifies the MAC and reports the outcome in `verification`, and\n * throws before deriving when the iteration count exceeds\n * `options.maxKdfIterations` or {@linkcode Number.MAX_SAFE_INTEGER}. The\n * default limit is `100_000` for the PKCS#12 KDF and `2_000_000` for the\n * PBKDF2 behind PBMAC1. Without `password` no key is derived, so\n * `options.maxKdfIterations` is not applied and `verification` is\n * `'unchecked'`. Throws a {@linkcode ResultError} carrying a\n * {@linkcode ParsePkcs12MacDataErrorCode} for an unsupported MAC, a PBMAC1 key\n * length below 20 octets, or a password the MAC cannot encode.\n */\nexport async function parsePkcs12MacDataOrThrow(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n\toptions?: ParsePkcs12MacDataOptions,\n): Promise<ParsedPkcs12MacData> {\n\tconst pkcs12Budget = createKdfBudget(options, DEFAULT_MAX_PKCS12_MAC_ITERATIONS);\n\tconst pbkdf2Budget = createKdfBudget(options, DEFAULT_MAX_KDF_ITERATIONS);\n\tconst top = readSequenceChildren(der);\n\tconst digestInfo = top[0];\n\tconst salt = top[1];\n\tconst iterations = top[2];\n\tif (\n\t\t(top.length !== 2 && top.length !== 3) ||\n\t\tdigestInfo === undefined ||\n\t\tsalt === undefined ||\n\t\tsalt.tag !== 0x04 ||\n\t\t(iterations !== undefined && iterations.tag !== 0x02)\n\t) {\n\t\tthrow new Error('Malformed MacData');\n\t}\n\tconst digestInfoDer = der.slice(digestInfo.start - digestInfo.headerLength, digestInfo.end);\n\tconst digestInfoChildren = readSequenceChildren(digestInfoDer);\n\tconst algorithm = digestInfoChildren[0];\n\tconst digest = digestInfoChildren[1];\n\tif (\n\t\tdigestInfoChildren.length !== 2 ||\n\t\talgorithm === undefined ||\n\t\tdigest === undefined ||\n\t\tdigest.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed DigestInfo');\n\t}\n\tconst algorithmDer = digestInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\t(algorithmChildren.length !== 1 && algorithmChildren.length !== 2)\n\t) {\n\t\tthrow new Error('MacData algorithm missing');\n\t}\n\tconst digestAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (digestAlgorithmOid === OIDS.pbmac1) {\n\t\treturn await verifyPbmac1MacData(\n\t\t\talgorithmDer,\n\t\t\talgorithmChildren[1],\n\t\t\tdigest.value,\n\t\t\tauthenticatedSafe,\n\t\t\tpassword,\n\t\t\tpbkdf2Budget,\n\t\t);\n\t}\n\tif (digestAlgorithmOid !== OIDS.sha256) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t`Only SHA-256 PKCS#12 MAC and PBMAC1 are supported, got ${describeHashAlgorithm(digestAlgorithmOid)}`,\n\t\t);\n\t}\n\tconst parsedIterations =\n\t\titerations === undefined\n\t\t\t? 1\n\t\t\t: decodeMacIterations(iterations.value, pkcs12Budget, password, 'MacData iterations');\n\tif (parsedIterations === 0) {\n\t\tthrow new Error('MacData iterations must be a positive safe integer');\n\t}\n\tconst unchecked = {\n\t\ttype: 'pkcs12-kdf',\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tdigestHex: toHex(digest.value),\n\t\tsaltHex: toHex(salt.value),\n\t\titerations: parsedIterations,\n\t\tverification: 'unchecked',\n\t} as const;\n\tif (password === undefined) {\n\t\treturn unchecked;\n\t}\n\tchargeKdfBudget(pkcs12Budget, parsedIterations);\n\tconst expected = await computePkcs12Mac(\n\t\tauthenticatedSafe,\n\t\tpassword,\n\t\tsalt.value,\n\t\tparsedIterations,\n\t);\n\treturn {\n\t\t...unchecked,\n\t\tverification: equalBytes(expected, digest.value) ? 'valid' : 'invalid',\n\t};\n}\n\n/**\n * Decodes a DER-encoded MacData block. When `password` is provided, verifies\n * the MAC and reports the outcome in `verification`.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input, an\n * iteration count below 1, or a PBMAC1 iteration count above 4294967295,\n * `'unsupported_mac_algorithm'` for a MAC other than\n * the RFC 7292 SHA-256 MAC or a PBMAC1 variant this implementation does not\n * handle, `'weak_mac_key_length'` for a PBMAC1 key length below 20 octets,\n * `'password_not_bmp_string'` when an RFC 7292 password contains a UTF-16\n * surrogate, U+FFFE or U+FFFF, and `'password_not_utf8'` when a PBMAC1 password contains an\n * unpaired UTF-16 surrogate. With a `password`, returns\n * `code: 'kdf_iterations_exceeded'` when the iteration count exceeds\n * `options.maxKdfIterations`, or an RFC 7292 MAC count exceeds\n * {@linkcode Number.MAX_SAFE_INTEGER}. Without a `password` no key is derived:\n * `options.maxKdfIterations` is not applied, an RFC 7292 MAC count above\n * {@linkcode Number.MAX_SAFE_INTEGER} is `'malformed'`, and `verification` is\n * `'unchecked'`. For the throwing form use {@linkcode parsePkcs12MacDataOrThrow}.\n */\nexport async function parsePkcs12MacData(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n\toptions?: ParsePkcs12MacDataOptions,\n): Promise<ParsePkcs12MacDataResult> {\n\ttry {\n\t\treturn successResult(\n\t\t\tawait parsePkcs12MacDataOrThrow(der, authenticatedSafe, password, options),\n\t\t);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isKdfIterationLimitError(error)) {\n\t\t\treturn failureResult('kdf_iterations_exceeded', error.message);\n\t\t}\n\t\tif (isResultError(error)) {\n\t\t\tconst code = THROWN_MAC_DATA_ERROR_CODES.find((candidate) => candidate === error.code);\n\t\t\tif (code !== undefined) {\n\t\t\t\treturn failureResult(code, error.error.message);\n\t\t\t}\n\t\t}\n\t\treturn decodeFailureResult(error, DECODE_LIMIT_CODES, 'Malformed MacData');\n\t}\n}\n\nfunction decodeMacIterations(\n\tcontent: Uint8Array,\n\tbudget: KdfBudget,\n\tpassword: string | undefined,\n\tlabel: string,\n): number {\n\tconst magnitude = decodeIntegerMagnitude(content, label);\n\tif (magnitude.type === 'safe') {\n\t\treturn magnitude.value;\n\t}\n\tif (password !== undefined) {\n\t\tchargeKdfBudget(budget, Number.POSITIVE_INFINITY);\n\t}\n\tthrow new Error(`${label} too large for safe number (${content.length} bytes)`);\n}\n\ninterface Pbmac1Parameters {\n\treadonly salt: Uint8Array;\n\treadonly iterations: number;\n\treadonly keyLength: number;\n\treadonly prf: Pbmac1Hmac;\n\treadonly messageAuthScheme: Pbmac1Hmac;\n}\n\ninterface AlgorithmIdentifierFields {\n\treadonly oid: string;\n\treadonly parameters: DerElement | undefined;\n\treadonly der: Uint8Array;\n}\n\nasync function verifyPbmac1MacData(\n\talgorithmDer: Uint8Array,\n\tparametersElement: DerElement | undefined,\n\tdigest: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string | undefined,\n\tbudget: KdfBudget,\n): Promise<ParsedPbmac1MacData> {\n\tif (parametersElement === undefined) {\n\t\tthrow new Error('PBMAC1 parameters must be present');\n\t}\n\tconst parameters = parsePbmac1Parameters(algorithmDer, parametersElement);\n\tconst unchecked = {\n\t\ttype: 'pbmac1',\n\t\tdigestAlgorithmOid: OIDS.pbmac1,\n\t\tdigestAlgorithmName: 'PBMAC1',\n\t\tdigestHex: toHex(digest),\n\t\tsaltHex: toHex(parameters.salt),\n\t\titerations: parameters.iterations,\n\t\tkeyLength: parameters.keyLength,\n\t\tprf: parameters.prf,\n\t\tmessageAuthScheme: parameters.messageAuthScheme,\n\t\tverification: 'unchecked',\n\t} as const;\n\tif (password === undefined) {\n\t\treturn unchecked;\n\t}\n\tchargeKdfBudget(budget, parameters.iterations);\n\tconst expected = await computePbmac1(authenticatedSafe, password, parameters);\n\treturn { ...unchecked, verification: equalBytes(expected, digest) ? 'valid' : 'invalid' };\n}\n\nfunction parsePbmac1Parameters(\n\talgorithmDer: Uint8Array,\n\tparametersElement: DerElement,\n): Pbmac1Parameters {\n\tif (parametersElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBMAC1-params');\n\t}\n\tconst paramsDer = algorithmDer.slice(\n\t\tparametersElement.start - parametersElement.headerLength,\n\t\tparametersElement.end,\n\t);\n\tconst children = readSequenceChildren(paramsDer);\n\tconst kdfElement = children[0];\n\tconst macElement = children[1];\n\tif (children.length !== 2 || kdfElement === undefined || macElement === undefined) {\n\t\tthrow new Error('Malformed PBMAC1-params');\n\t}\n\tconst kdf = readAlgorithmIdentifier(paramsDer, kdfElement, 'PBMAC1 keyDerivationFunc');\n\tif (kdf.oid !== OIDS.pbkdf2) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t`Unsupported PBMAC1 key derivation function ${kdf.oid}`,\n\t\t);\n\t}\n\tconst messageAuthScheme = parseHmacAlgorithm(\n\t\treadAlgorithmIdentifier(paramsDer, macElement, 'PBMAC1 messageAuthScheme'),\n\t\t'PBMAC1 messageAuthScheme',\n\t);\n\treturn { ...parsePbkdf2Parameters(kdf), messageAuthScheme };\n}\n\nfunction parsePbkdf2Parameters(\n\tkdf: AlgorithmIdentifierFields,\n): Omit<Pbmac1Parameters, 'messageAuthScheme'> {\n\tif (kdf.parameters === undefined || kdf.parameters.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2-params');\n\t}\n\tconst der = kdf.der.slice(kdf.parameters.start - kdf.parameters.headerLength, kdf.parameters.end);\n\tconst [salt, iterationCount, ...optional] = readSequenceChildren(der);\n\tif (salt === undefined || iterationCount === undefined || iterationCount.tag !== 0x02) {\n\t\tthrow new Error('Malformed PBKDF2-params');\n\t}\n\tif (salt.tag === 0x30) {\n\t\tthrowMacDataError('unsupported_mac_algorithm', 'PBKDF2 otherSource salt is not supported');\n\t}\n\tif (salt.tag !== 0x04) {\n\t\tthrow new Error('Malformed PBKDF2 salt');\n\t}\n\tconst keyLengthElement = optional[0]?.tag === 0x02 ? optional[0] : undefined;\n\tconst rest = keyLengthElement === undefined ? optional : optional.slice(1);\n\tconst prfElement = rest[0];\n\tif (rest.length > 1 || (prfElement !== undefined && prfElement.tag !== 0x30)) {\n\t\tthrow new Error('Malformed PBKDF2-params');\n\t}\n\tif (keyLengthElement === undefined) {\n\t\tthrow new Error('PBKDF2-params in PBMAC1 must include keyLength');\n\t}\n\tif (prfElement === undefined) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t'PBKDF2 prf is absent and defaults to HMAC-SHA-1, which PBMAC1 verification does not accept',\n\t\t);\n\t}\n\tconst prf = parseHmacAlgorithm(\n\t\treadAlgorithmIdentifier(der, prfElement, 'PBKDF2 prf'),\n\t\t'PBKDF2 prf',\n\t);\n\tconst iterations = decodeIntegerMagnitude(iterationCount.value, 'PBKDF2 iterationCount');\n\tif (iterations.type === 'unsafe' || iterations.value > WEBCRYPTO_MAX_PBKDF2_ITERATIONS) {\n\t\tthrow new Error(`PBKDF2 iterationCount must be at most ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}`);\n\t}\n\tif (iterations.value === 0) {\n\t\tthrow new Error('PBKDF2 iterationCount must be at least 1');\n\t}\n\treturn {\n\t\tsalt: new Uint8Array(salt.value),\n\t\titerations: iterations.value,\n\t\tkeyLength: decodePbmac1KeyLength(keyLengthElement.value),\n\t\tprf,\n\t};\n}\n\nfunction decodePbmac1KeyLength(content: Uint8Array): number {\n\tconst magnitude = decodeIntegerMagnitude(content, 'PBKDF2 keyLength');\n\tif (magnitude.type === 'unsafe' || magnitude.value > PBMAC1_MAX_KEY_LENGTH) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t`PBKDF2 keyLength above ${PBMAC1_MAX_KEY_LENGTH} octets is not supported`,\n\t\t);\n\t}\n\tif (magnitude.value === 0) {\n\t\tthrow new Error('PBKDF2 keyLength must be at least 1');\n\t}\n\tif (magnitude.value < PBMAC1_MIN_KEY_LENGTH) {\n\t\tthrowMacDataError(\n\t\t\t'weak_mac_key_length',\n\t\t\t`PBKDF2 keyLength ${magnitude.value} is below ${PBMAC1_MIN_KEY_LENGTH} octets`,\n\t\t);\n\t}\n\treturn magnitude.value;\n}\n\nfunction readAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: DerElement,\n\tlabel: string,\n): AlgorithmIdentifierFields {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`Malformed ${label}`);\n\t}\n\tconst der = source.slice(element.start - element.headerLength, element.end);\n\tconst children = readSequenceChildren(der);\n\tconst oid = children[0];\n\tif (oid === undefined || oid.tag !== 0x06 || children.length > 2) {\n\t\tthrow new Error(`Malformed ${label}`);\n\t}\n\treturn { oid: decodeObjectIdentifier(oid.value), parameters: children[1], der };\n}\n\nfunction parseHmacAlgorithm(algorithm: AlgorithmIdentifierFields, label: string): Pbmac1Hmac {\n\tif (\n\t\talgorithm.parameters !== undefined &&\n\t\t(algorithm.parameters.tag !== 0x05 || algorithm.parameters.length !== 0)\n\t) {\n\t\tthrow new Error(`${label} parameters must be NULL`);\n\t}\n\tswitch (algorithm.oid) {\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'HMAC-SHA-256';\n\t\tcase OIDS.hmacWithSHA384:\n\t\t\treturn 'HMAC-SHA-384';\n\t\tcase OIDS.hmacWithSHA512:\n\t\t\treturn 'HMAC-SHA-512';\n\t}\n\treturn throwMacDataError('unsupported_mac_algorithm', `Unsupported ${label} ${algorithm.oid}`);\n}\n\nfunction hmacHash(name: Pbmac1Hmac): Pbkdf2Hash {\n\tswitch (name) {\n\t\tcase 'HMAC-SHA-256':\n\t\t\treturn 'SHA-256';\n\t\tcase 'HMAC-SHA-384':\n\t\t\treturn 'SHA-384';\n\t\tcase 'HMAC-SHA-512':\n\t\t\treturn 'SHA-512';\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled PBMAC1 HMAC: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nasync function computePbmac1(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tparameters: Pbmac1Parameters,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePbkdf2Bytes(\n\t\tencodePbmac1Password(password),\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\thmacHash(parameters.prf),\n\t\tparameters.keyLength,\n\t);\n\treturn await hmac(authenticatedSafe, keyBytes, hmacHash(parameters.messageAuthScheme));\n}\n\nfunction encodePbmac1Password(password: string): Uint8Array {\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = password.charCodeAt(index + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (code >= 0xd800 && code <= 0xdfff) {\n\t\t\tthrowPkcs12MacError(\n\t\t\t\t'password_not_utf8',\n\t\t\t\t`PBMAC1 password has no UTF-8 encoding: unpaired UTF-16 surrogate 0x${code.toString(16)} at index ${index}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn new TextEncoder().encode(password);\n}\n\n/** Derives an HMAC-SHA-256 key via the PKCS#12 KDF and signs the AuthenticatedSafe. */\nasync function computePkcs12Mac(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePkcs12Key(password, salt, iterations, 3, 32);\n\treturn await hmac(authenticatedSafe, keyBytes, 'SHA-256');\n}\n\nasync function hmac(\n\tmessage: Uint8Array,\n\tkeyBytes: Uint8Array,\n\thash: Pbkdf2Hash,\n): Promise<Uint8Array> {\n\tconst key = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'HMAC', hash },\n\t\tfalse,\n\t\t['sign'],\n\t);\n\treturn new Uint8Array(await getCrypto().subtle.sign('HMAC', key, toArrayBuffer(message)));\n}\n\n/**\n * PKCS#12 key derivation with SHA-256 (RFC 7292 Appendix B). `id` selects the purpose:\n * 1 for key material, 2 for an IV, 3 for a MAC key.\n *\n * @throws {ResultError} with code `password_not_bmp_string` when the password contains a\n * UTF-16 surrogate, U+FFFE or U+FFFF.\n */\nexport async function derivePkcs12Key(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tid: 1 | 2 | 3,\n\tlength: number,\n): Promise<Uint8Array> {\n\tconst u = 32;\n\tconst v = 64;\n\tconst D = new Uint8Array(v).fill(id);\n\tconst passwordBytes = encodePkcs12Password(password);\n\tconst I = concatBytes([repeatToMultiple(salt, v), repeatToMultiple(passwordBytes, v)]);\n\tconst blocks = Math.ceil(length / u);\n\tconst output = new Uint8Array(blocks * u);\n\tfor (let index = 0; index < blocks; index += 1) {\n\t\tlet A = await digestSha256(concatBytes([D, I]));\n\t\tfor (let round = 1; round < iterations; round += 1) {\n\t\t\tA = await digestSha256(A);\n\t\t}\n\t\toutput.set(A, index * u);\n\t\tif (index + 1 === blocks) {\n\t\t\tbreak;\n\t\t}\n\t\tconst B = repeatToLength(A, v);\n\t\tfor (let offset = 0; offset < I.length; offset += v) {\n\t\t\taddBlockInPlace(I.subarray(offset, offset + v), B);\n\t\t}\n\t}\n\treturn output.slice(0, length);\n}\n\n/** SHA-256 hash via WebCrypto. */\nasync function digestSha256(bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(bytes)));\n}\n\n/** Encodes a password as a null-terminated BMPString, two big-endian bytes per character (RFC 7292 B.1). */\nfunction encodePkcs12Password(password: string): Uint8Array {\n\tconst out = new Uint8Array((password.length + 1) * 2);\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tif (code >= 0xd800 && code <= 0xdfff) {\n\t\t\tthrowPkcs12MacError(\n\t\t\t\t'password_not_bmp_string',\n\t\t\t\t`PKCS#12 password is not a BMPString: UTF-16 surrogate 0x${code.toString(16)} at index ${index}`,\n\t\t\t);\n\t\t}\n\t\tif (code >= 0xfffe) {\n\t\t\tthrowPkcs12MacError(\n\t\t\t\t'password_not_bmp_string',\n\t\t\t\t`PKCS#12 password is not a BMPString: U+${code.toString(16).toUpperCase()} at index ${index}`,\n\t\t\t);\n\t\t}\n\t\tout[index * 2] = code >> 8;\n\t\tout[index * 2 + 1] = code & 0xff;\n\t}\n\treturn out;\n}\n\n/** Repeats `bytes` to the nearest multiple of `size`. */\nfunction repeatToMultiple(bytes: Uint8Array, size: number): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn new Uint8Array();\n\t}\n\treturn repeatToLength(bytes, size * Math.ceil(bytes.length / size));\n}\n\n/** Cyclically repeats `bytes` to fill exactly `length` bytes. */\nfunction repeatToLength(bytes: Uint8Array, length: number): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tout[index] = bytes[index % bytes.length] ?? 0;\n\t}\n\treturn out;\n}\n\n/** Big-endian add-with-carry of `addend` into `block`, modifying `block` in place. */\nfunction addBlockInPlace(block: Uint8Array, addend: Uint8Array): void {\n\tlet carry = 1;\n\tfor (let index = block.length - 1; index >= 0; index -= 1) {\n\t\tconst sum = (block[index] ?? 0) + (addend[index] ?? 0) + carry;\n\t\tblock[index] = sum & 0xff;\n\t\tcarry = sum >> 8;\n\t}\n}\n\n/** Constant-time byte comparison to avoid timing side-channels in MAC checks. */\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tlet result = 0;\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tresult |= (left[index] ?? 0) ^ (right[index] ?? 0);\n\t}\n\treturn result === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuDA,SAAS,oBAAoB,GAAoC,GAAwB;CACxF,EAAmBC,GAAMC,CAAO;AACjC;;;;;;;;;;AAoGA,eAAsB,oBACrB,GACA,GAME;CACF,IAAIC,EAAQ,SAAS,UACpB,OAAO,MAAM,oBAAoBC,GAAmBD,CAAO;CAE5D,IAAME,IAAaF,EAAQ,cAAc;CACzC,CAAI,CAAC,OAAO,cAAcE,CAAU,KAAKA,KAAc,MACtD,oBACC,sBACA,2DAA2DA,GAC5D;CAED,IAAMC,IAAOH,EAAQ,QAAQI,EAAU,CAAC,CAAC,gCAAgB,IAAI,WAAW,EAAE,CAAC,GACrEC,IAAM,MAAM,iBAAiBJ,GAAmBD,EAAQ,UAAUG,GAAMD,CAAU;CAMxF,OAAO;EACN,KANWI,EAAS;GACpBA,EAAS,CAACA,EAAS,CAACC,EAAiBC,EAAK,MAAM,GAAGC,EAAU,CAAC,CAAC,GAAGC,EAAYL,CAAG,CAAC,CAAC;GACnFK,EAAYP,CAAI;GAChB,GAAID,MAAe,IAAI,CAAC,IAAI,CAACS,EAAkBT,CAAU,CAAC;EAC3D,CAEG;EACF,QAAQ;GACP,MAAM;GACN,oBAAoBM,EAAK;GACzB,qBAAqBI,EAAsBJ,EAAK,MAAM;GACtD,WAAWK,EAAMR,CAAG;GACpB,SAASQ,EAAMV,CAAI;GACnB;GACA,cAAc;EACf;CACD;AACD;AAEA,eAAe,oBACd,GACA,GAC8E;CAC9E,IAAMD,IAAaF,EAAQ,cAAc;CACzC,CACC,CAAC,OAAO,UAAUE,CAAU,KAC5BA,IAAa,KACbA,IAAA,eAEA,oBACC,sBACA,kDA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AAGA,SAAS,gBAAgB,GAAmB,GAA0B;CACrE,IAAIE,IAAQ;CACZ,KAAK,IAAIpB,IAAQqB,EAAM,SAAS,GAAGrB,KAAS,GAAG,KAAY;EAC1D,IAAMsB,KAAOD,EAAMrB,MAAU,MAAMuB,EAAOvB,MAAU,KAAKoB;EAEzD,AADA,EAAMpB,KAASsB,IAAM,KACrB,IAAQA,KAAO;CAChB;AACD;;AAGA,SAAS,WAAW,GAAkB,GAA4B;CACjE,IAAIE,EAAK,WAAWC,EAAM,QACzB,OAAO;CAER,IAAIC,IAAS;CACb,KAAK,IAAI1B,IAAQ,GAAGA,IAAQwB,EAAK,QAAQ,KAAS,GACjD,MAAWA,EAAKxB,MAAU,MAAMyB,EAAMzB,MAAU;CAEjD,OAAO0B,MAAW;AACnB"}
1
+ {"version":3,"file":"pkcs12-mac.js","names":["_exhaustive","decodeIntegerMagnitude","decodeObjectIdentifier","toArrayBuffer","toHex","DECODE_LIMIT_CODES","decodeFailureResult","concatBytes","integerFromNumber","nullValue","objectIdentifier","octetString","readSequenceChildren","sequence","OIDS","describeHashAlgorithm","DEFAULT_MAX_KDF_ITERATIONS","DEFAULT_MAX_PKCS12_MAC_ITERATIONS","WEBCRYPTO_MAX_PBKDF2_ITERATIONS","chargeKdfBudget","createKdfBudget","derivePbkdf2Bytes","isKdfIterationLimitError","getCrypto","failureResult","isResultError","rethrowIfInvariant","successResult","throwMicro509Error","code","message","authenticatedSafe","options","iterations","salt","mac","parameters","hmacWithSha256","algorithm","THROWN_MAC_DATA_ERROR_CODES","der","password","pkcs12Budget","pbkdf2Budget","top","digestInfo","digestInfoDer","digestInfoChildren","digest","algorithmDer","algorithmChildren","algorithmOid","digestAlgorithmOid","parsedIterations","unchecked","expected","error","candidate","content","budget","label","magnitude","parametersElement","paramsDer","children","kdfElement","macElement","kdf","messageAuthScheme","iterationCount","optional","keyLengthElement","rest","prfElement","prf","source","element","oid","name","index","next","keyBytes","hash","key","id","length","D","passwordBytes","I","blocks","output","A","round","B","offset","bytes","out","size","block","addend","carry","sum","left","right","result"],"sources":["../../src/pkcs/pkcs12-mac.ts"],"sourcesContent":["/**\n * PKCS#12 MAC data creation and verification.\n *\n * Computes and verifies the password-based integrity check of a PFX: the\n * RFC 7292 HMAC-SHA-256 MAC keyed by the PKCS#12 key-derivation scheme, and\n * PBMAC1 (RFC 9879) keyed by PBKDF2.\n *\n * @module\n */\n\nimport {\n\tdecodeIntegerMagnitude,\n\tdecodeObjectIdentifier,\n\ttoArrayBuffer,\n\ttoHex,\n} from '#micro509/internal/asn1/asn1';\nimport { DECODE_LIMIT_CODES, decodeFailureResult } from '#micro509/internal/asn1/decode-refusal';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport {\n\tconcatBytes,\n\tintegerFromNumber,\n\tnullValue,\n\tobjectIdentifier,\n\toctetString,\n\treadSequenceChildren,\n\tsequence,\n} from '#micro509/internal/asn1/der';\nimport { OIDS } from '#micro509/internal/asn1/oids';\nimport { describeHashAlgorithm } from '#micro509/internal/crypto/algorithm-names';\nimport type { KdfBudget, KdfLimitOptions, Pbkdf2Hash } from '#micro509/internal/crypto/pbes2';\nimport {\n\tchargeKdfBudget,\n\tcreateKdfBudget,\n\tDEFAULT_MAX_KDF_ITERATIONS,\n\tDEFAULT_MAX_PKCS12_MAC_ITERATIONS,\n\tderivePbkdf2Bytes,\n\tisKdfIterationLimitError,\n\tWEBCRYPTO_MAX_PBKDF2_ITERATIONS,\n} from '#micro509/internal/crypto/pbes2';\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport type { DecodeFailureCode, ErrorResult, Micro509Error } from '#micro509/result/result';\nimport {\n\tfailureResult,\n\tisResultError,\n\trethrowIfInvariant,\n\tsuccessResult,\n\tthrowMicro509Error,\n} from '#micro509/result/result';\n\n/** Machine-readable reason {@linkcode createPkcs12MacData} rejected its construction input. */\nexport type CreatePkcs12MacDataErrorCode =\n\t| 'password_not_bmp_string'\n\t| 'password_not_utf8'\n\t| 'invalid_iterations';\n\nfunction throwPkcs12MacError(code: CreatePkcs12MacDataErrorCode, message: string): never {\n\tthrowMicro509Error(code, message);\n}\n\n/**\n * Input for {@linkcode createPkcs12MacData}. `type` selects the MAC: `'pkcs12-kdf'` (the\n * default) is the RFC 7292 HMAC-SHA-256 MAC keyed by the PKCS#12 KDF, and `'pbmac1'` is\n * RFC 9879 PBMAC1 with PBKDF2-HMAC-SHA-256, a 32-octet key and HMAC-SHA-256.\n */\nexport type Pkcs12MacOptions =\n\t| {\n\t\t\t/** RFC 7292 Appendix B key derivation with HMAC-SHA-256. */\n\t\t\treadonly type?: 'pkcs12-kdf';\n\t\t\t/**\n\t\t\t * Password used to derive the HMAC key via the PKCS#12 KDF. Every character must be a\n\t\t\t * BMPString character, so UTF-16 surrogates, U+FFFE and U+FFFF are rejected.\n\t\t\t */\n\t\t\treadonly password: string;\n\t\t\t/** PKCS#12 KDF iteration count, a positive safe integer. Default: `2048`. */\n\t\t\treadonly iterations?: number;\n\t\t\t/** Random salt. Default: 16 cryptographically random bytes. */\n\t\t\treadonly salt?: Uint8Array;\n\t }\n\t| {\n\t\t\t/** RFC 9879 PBMAC1. */\n\t\t\treadonly type: 'pbmac1';\n\t\t\t/**\n\t\t\t * Password fed to PBKDF2 as UTF-8 without a NULL terminator. Unpaired UTF-16\n\t\t\t * surrogates are rejected.\n\t\t\t */\n\t\t\treadonly password: string;\n\t\t\t/** PBKDF2 iteration count, an integer from 1 to 4294967295. Default: `100_000`. */\n\t\t\treadonly iterations?: number;\n\t\t\t/** PBKDF2 salt, also written to the ignored MacData macSalt. Default: 16 random bytes. */\n\t\t\treadonly salt?: Uint8Array;\n\t };\n\n/**\n * Decoded PKCS#12 MacData block returned by {@linkcode parsePkcs12MacData}. `type` names the\n * MAC: `'pkcs12-kdf'` for the RFC 7292 MAC and `'pbmac1'` for RFC 9879 PBMAC1.\n */\nexport type ParsedPkcs12MacData =\n\t| {\n\t\t\t/** RFC 7292 MAC keyed by the PKCS#12 KDF. */\n\t\t\treadonly type: 'pkcs12-kdf';\n\t\t\t/** OID of the digest algorithm (always SHA-256). */\n\t\t\treadonly digestAlgorithmOid: string;\n\t\t\t/** Human-readable digest algorithm name (`\"SHA-256\"`). */\n\t\t\treadonly digestAlgorithmName: string;\n\t\t\t/** Hex-encoded MAC digest value. */\n\t\t\treadonly digestHex: string;\n\t\t\t/** Hex-encoded MacData macSalt. */\n\t\t\treadonly saltHex: string;\n\t\t\t/** MacData iterations, the PKCS#12 KDF iteration count. */\n\t\t\treadonly iterations: number;\n\t\t\t/**\n\t\t\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t\t\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t\t\t */\n\t\t\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n\t }\n\t| {\n\t\t\t/** RFC 9879 PBMAC1 keyed by PBKDF2. */\n\t\t\treadonly type: 'pbmac1';\n\t\t\t/** The id-PBMAC1 OID. */\n\t\t\treadonly digestAlgorithmOid: string;\n\t\t\t/** Always `\"PBMAC1\"`. */\n\t\t\treadonly digestAlgorithmName: string;\n\t\t\t/** Hex-encoded MAC value. */\n\t\t\treadonly digestHex: string;\n\t\t\t/** Hex-encoded PBKDF2 salt. MacData macSalt is ignored. */\n\t\t\treadonly saltHex: string;\n\t\t\t/** PBKDF2 iteration count. MacData iterations is ignored. */\n\t\t\treadonly iterations: number;\n\t\t\t/** PBKDF2 keyLength in octets. */\n\t\t\treadonly keyLength: number;\n\t\t\t/** PBKDF2 pseudorandom function. */\n\t\t\treadonly prf: 'HMAC-SHA-256' | 'HMAC-SHA-384' | 'HMAC-SHA-512';\n\t\t\t/** PBMAC1 message authentication scheme. */\n\t\t\treadonly messageAuthScheme: 'HMAC-SHA-256' | 'HMAC-SHA-384' | 'HMAC-SHA-512';\n\t\t\t/**\n\t\t\t * MAC verification outcome: `'unchecked'` when no password was supplied\n\t\t\t * during parsing, otherwise `'valid'` or `'invalid'`.\n\t\t\t */\n\t\t\treadonly verification: 'valid' | 'invalid' | 'unchecked';\n\t };\n\ntype ParsedPbmac1MacData = Extract<ParsedPkcs12MacData, { readonly type: 'pbmac1' }>;\ntype Pbmac1Hmac = ParsedPbmac1MacData['prf'];\n\nconst PBMAC1_MAX_KEY_LENGTH = 64;\nconst PBMAC1_MIN_KEY_LENGTH = 20;\n\n/**\n * Computes a PKCS#12 MAC over the AuthenticatedSafe and returns the DER-encoded MacData\n * block alongside its parsed representation.\n *\n * @throws {ResultError} with code `invalid_iterations` when `iterations` is out of range,\n * `password_not_bmp_string` when a `'pkcs12-kdf'` password contains a UTF-16 surrogate, U+FFFE\n * or U+FFFF, and `password_not_utf8` when a `'pbmac1'` password contains an unpaired UTF-16\n * surrogate.\n */\nexport async function createPkcs12MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Pkcs12MacOptions,\n): Promise<{\n\t/** DER-encoded MacData SEQUENCE. */\n\treadonly der: Uint8Array;\n\t/** Structured representation of the MAC parameters and digest. */\n\treadonly parsed: ParsedPkcs12MacData;\n}> {\n\tif (options.type === 'pbmac1') {\n\t\treturn await createPbmac1MacData(authenticatedSafe, options);\n\t}\n\tconst iterations = options.iterations ?? 2048;\n\tif (!Number.isSafeInteger(iterations) || iterations <= 0) {\n\t\tthrowPkcs12MacError(\n\t\t\t'invalid_iterations',\n\t\t\t`MacData iterations must be a positive safe integer, got ${iterations}`,\n\t\t);\n\t}\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst mac = await computePkcs12Mac(authenticatedSafe, options.password, salt, iterations);\n\tconst der = sequence([\n\t\tsequence([sequence([objectIdentifier(OIDS.sha256), nullValue()]), octetString(mac)]),\n\t\toctetString(salt),\n\t\t...(iterations === 1 ? [] : [integerFromNumber(iterations)]),\n\t]);\n\treturn {\n\t\tder,\n\t\tparsed: {\n\t\t\ttype: 'pkcs12-kdf',\n\t\t\tdigestAlgorithmOid: OIDS.sha256,\n\t\t\tdigestAlgorithmName: describeHashAlgorithm(OIDS.sha256),\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\nasync function createPbmac1MacData(\n\tauthenticatedSafe: Uint8Array,\n\toptions: Extract<Pkcs12MacOptions, { readonly type: 'pbmac1' }>,\n): Promise<{ readonly der: Uint8Array; readonly parsed: ParsedPkcs12MacData }> {\n\tconst iterations = options.iterations ?? 100_000;\n\tif (\n\t\t!Number.isInteger(iterations) ||\n\t\titerations < 1 ||\n\t\titerations > WEBCRYPTO_MAX_PBKDF2_ITERATIONS\n\t) {\n\t\tthrowPkcs12MacError(\n\t\t\t'invalid_iterations',\n\t\t\t`PBMAC1 iterations must be an integer from 1 to ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}, got ${iterations}`,\n\t\t);\n\t}\n\tconst salt = options.salt ?? getCrypto().getRandomValues(new Uint8Array(16));\n\tconst parameters: Pbmac1Parameters = {\n\t\tsalt,\n\t\titerations,\n\t\tkeyLength: 32,\n\t\tprf: 'HMAC-SHA-256',\n\t\tmessageAuthScheme: 'HMAC-SHA-256',\n\t};\n\tconst mac = await computePbmac1(authenticatedSafe, options.password, parameters);\n\tconst hmacWithSha256 = sequence([objectIdentifier(OIDS.hmacWithSHA256), nullValue()]);\n\tconst algorithm = sequence([\n\t\tobjectIdentifier(OIDS.pbmac1),\n\t\tsequence([\n\t\t\tsequence([\n\t\t\t\tobjectIdentifier(OIDS.pbkdf2),\n\t\t\t\tsequence([\n\t\t\t\t\toctetString(salt),\n\t\t\t\t\tintegerFromNumber(iterations),\n\t\t\t\t\tintegerFromNumber(parameters.keyLength),\n\t\t\t\t\thmacWithSha256,\n\t\t\t\t]),\n\t\t\t]),\n\t\t\thmacWithSha256,\n\t\t]),\n\t]);\n\treturn {\n\t\tder: sequence([sequence([algorithm, octetString(mac)]), octetString(salt)]),\n\t\tparsed: {\n\t\t\ttype: 'pbmac1',\n\t\t\tdigestAlgorithmOid: OIDS.pbmac1,\n\t\t\tdigestAlgorithmName: 'PBMAC1',\n\t\t\tdigestHex: toHex(mac),\n\t\t\tsaltHex: toHex(salt),\n\t\t\titerations,\n\t\t\tkeyLength: parameters.keyLength,\n\t\t\tprf: parameters.prf,\n\t\t\tmessageAuthScheme: parameters.messageAuthScheme,\n\t\t\tverification: 'valid',\n\t\t},\n\t};\n}\n\n/** Machine-readable failure reason for {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataErrorCode =\n\t| Exclude<DecodeFailureCode, 'unsupported'>\n\t| 'kdf_iterations_exceeded'\n\t| 'password_not_bmp_string'\n\t| 'password_not_utf8'\n\t| 'unsupported_mac_algorithm'\n\t| 'weak_mac_key_length';\n\ntype ThrownMacDataErrorCode = Exclude<\n\tParsePkcs12MacDataErrorCode,\n\tDecodeFailureCode | 'kdf_iterations_exceeded'\n>;\n\nconst THROWN_MAC_DATA_ERROR_CODES = [\n\t'password_not_bmp_string',\n\t'password_not_utf8',\n\t'unsupported_mac_algorithm',\n\t'weak_mac_key_length',\n] as const satisfies readonly ThrownMacDataErrorCode[];\n\nfunction throwMacDataError(\n\tcode: 'unsupported_mac_algorithm' | 'weak_mac_key_length',\n\tmessage: string,\n): never {\n\tthrowMicro509Error(code, message);\n}\n\n/** Options for {@linkcode parsePkcs12MacData} and {@linkcode parsePkcs12MacDataOrThrow}. */\nexport type ParsePkcs12MacDataOptions = KdfLimitOptions;\n\n/** Structured failure payload for MacData parsing. */\nexport interface ParsePkcs12MacDataFailure extends Micro509Error<ParsePkcs12MacDataErrorCode> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** Success-or-failure result from {@linkcode parsePkcs12MacData}. */\nexport type ParsePkcs12MacDataResult =\n\t| { readonly ok: true; readonly value: ParsedPkcs12MacData }\n\t| ErrorResult<ParsePkcs12MacDataErrorCode, Record<never, never>, ParsePkcs12MacDataFailure>;\n\n/**\n * Throwing core for {@linkcode parsePkcs12MacData}. When `password` is\n * provided, verifies the MAC and reports the outcome in `verification`, and\n * throws before deriving when the iteration count exceeds\n * `options.maxKdfIterations` or {@linkcode Number.MAX_SAFE_INTEGER}. The\n * default limit is `100_000` for the PKCS#12 KDF and `2_000_000` for the\n * PBKDF2 behind PBMAC1. Without `password` no key is derived, so\n * `options.maxKdfIterations` is not applied and `verification` is\n * `'unchecked'`. Throws a {@linkcode ResultError} carrying a\n * {@linkcode ParsePkcs12MacDataErrorCode} for an unsupported MAC, a PBMAC1 key\n * length below 20 octets, or a password the MAC cannot encode.\n */\nexport async function parsePkcs12MacDataOrThrow(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n\toptions?: ParsePkcs12MacDataOptions,\n): Promise<ParsedPkcs12MacData> {\n\tconst pkcs12Budget = createKdfBudget(options, DEFAULT_MAX_PKCS12_MAC_ITERATIONS);\n\tconst pbkdf2Budget = createKdfBudget(options, DEFAULT_MAX_KDF_ITERATIONS);\n\tconst top = readSequenceChildren(der);\n\tconst digestInfo = top[0];\n\tconst salt = top[1];\n\tconst iterations = top[2];\n\tif (\n\t\t(top.length !== 2 && top.length !== 3) ||\n\t\tdigestInfo === undefined ||\n\t\tsalt === undefined ||\n\t\tsalt.tag !== 0x04 ||\n\t\t(iterations !== undefined && iterations.tag !== 0x02)\n\t) {\n\t\tthrow new Error('Malformed MacData');\n\t}\n\tconst digestInfoDer = der.slice(digestInfo.start - digestInfo.headerLength, digestInfo.end);\n\tconst digestInfoChildren = readSequenceChildren(digestInfoDer);\n\tconst algorithm = digestInfoChildren[0];\n\tconst digest = digestInfoChildren[1];\n\tif (\n\t\tdigestInfoChildren.length !== 2 ||\n\t\talgorithm === undefined ||\n\t\tdigest === undefined ||\n\t\tdigest.tag !== 0x04\n\t) {\n\t\tthrow new Error('Malformed DigestInfo');\n\t}\n\tconst algorithmDer = digestInfoDer.slice(algorithm.start - algorithm.headerLength, algorithm.end);\n\tconst algorithmChildren = readSequenceChildren(algorithmDer);\n\tconst algorithmOid = algorithmChildren[0];\n\tif (\n\t\talgorithmOid === undefined ||\n\t\t(algorithmChildren.length !== 1 && algorithmChildren.length !== 2)\n\t) {\n\t\tthrow new Error('MacData algorithm missing');\n\t}\n\tconst digestAlgorithmOid = decodeObjectIdentifier(algorithmOid.value);\n\tif (digestAlgorithmOid === OIDS.pbmac1) {\n\t\treturn await verifyPbmac1MacData(\n\t\t\talgorithmDer,\n\t\t\talgorithmChildren[1],\n\t\t\tdigest.value,\n\t\t\tauthenticatedSafe,\n\t\t\tpassword,\n\t\t\tpbkdf2Budget,\n\t\t);\n\t}\n\tif (digestAlgorithmOid !== OIDS.sha256) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t`Only SHA-256 PKCS#12 MAC and PBMAC1 are supported, got ${describeHashAlgorithm(digestAlgorithmOid)}`,\n\t\t);\n\t}\n\tconst parsedIterations =\n\t\titerations === undefined\n\t\t\t? 1\n\t\t\t: decodeMacIterations(iterations.value, pkcs12Budget, password, 'MacData iterations');\n\tif (parsedIterations === 0) {\n\t\tthrow new Error('MacData iterations must be a positive safe integer');\n\t}\n\tconst unchecked = {\n\t\ttype: 'pkcs12-kdf',\n\t\tdigestAlgorithmOid,\n\t\tdigestAlgorithmName: describeHashAlgorithm(digestAlgorithmOid),\n\t\tdigestHex: toHex(digest.value),\n\t\tsaltHex: toHex(salt.value),\n\t\titerations: parsedIterations,\n\t\tverification: 'unchecked',\n\t} as const;\n\tif (password === undefined) {\n\t\treturn unchecked;\n\t}\n\tchargeKdfBudget(pkcs12Budget, parsedIterations);\n\tconst expected = await computePkcs12Mac(\n\t\tauthenticatedSafe,\n\t\tpassword,\n\t\tsalt.value,\n\t\tparsedIterations,\n\t);\n\treturn {\n\t\t...unchecked,\n\t\tverification: equalBytes(expected, digest.value) ? 'valid' : 'invalid',\n\t};\n}\n\n/**\n * Decodes a DER-encoded MacData block. When `password` is provided, verifies\n * the MAC and reports the outcome in `verification`.\n *\n * Returns a typed failure (`code: 'malformed'`) on malformed input, an\n * iteration count below 1, or a PBMAC1 iteration count above 4294967295,\n * `'unsupported_mac_algorithm'` for a MAC other than\n * the RFC 7292 SHA-256 MAC or a PBMAC1 variant this implementation does not\n * handle, `'weak_mac_key_length'` for a PBMAC1 key length below 20 octets,\n * `'password_not_bmp_string'` when an RFC 7292 password contains a UTF-16\n * surrogate, U+FFFE or U+FFFF, and `'password_not_utf8'` when a PBMAC1 password contains an\n * unpaired UTF-16 surrogate. With a `password`, returns\n * `code: 'kdf_iterations_exceeded'` when the iteration count exceeds\n * `options.maxKdfIterations`, or an RFC 7292 MAC count exceeds\n * {@linkcode Number.MAX_SAFE_INTEGER}. Without a `password` no key is derived:\n * `options.maxKdfIterations` is not applied, an RFC 7292 MAC count above\n * {@linkcode Number.MAX_SAFE_INTEGER} is `'malformed'`, and `verification` is\n * `'unchecked'`. For the throwing form use {@linkcode parsePkcs12MacDataOrThrow}.\n */\nexport async function parsePkcs12MacData(\n\tder: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword?: string,\n\toptions?: ParsePkcs12MacDataOptions,\n): Promise<ParsePkcs12MacDataResult> {\n\ttry {\n\t\treturn successResult(\n\t\t\tawait parsePkcs12MacDataOrThrow(der, authenticatedSafe, password, options),\n\t\t);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\tif (isKdfIterationLimitError(error)) {\n\t\t\treturn failureResult('kdf_iterations_exceeded', error.message);\n\t\t}\n\t\tif (isResultError(error)) {\n\t\t\tconst code = THROWN_MAC_DATA_ERROR_CODES.find((candidate) => candidate === error.code);\n\t\t\tif (code !== undefined) {\n\t\t\t\treturn failureResult(code, error.error.message);\n\t\t\t}\n\t\t}\n\t\treturn decodeFailureResult(error, DECODE_LIMIT_CODES, 'Malformed MacData');\n\t}\n}\n\nfunction decodeMacIterations(\n\tcontent: Uint8Array,\n\tbudget: KdfBudget,\n\tpassword: string | undefined,\n\tlabel: string,\n): number {\n\tconst magnitude = decodeIntegerMagnitude(content, label);\n\tif (magnitude.type === 'safe') {\n\t\treturn magnitude.value;\n\t}\n\tif (password !== undefined) {\n\t\tchargeKdfBudget(budget, Number.POSITIVE_INFINITY);\n\t}\n\tthrow new Error(`${label} too large for safe number (${content.length} bytes)`);\n}\n\ninterface Pbmac1Parameters {\n\treadonly salt: Uint8Array;\n\treadonly iterations: number;\n\treadonly keyLength: number;\n\treadonly prf: Pbmac1Hmac;\n\treadonly messageAuthScheme: Pbmac1Hmac;\n}\n\ninterface AlgorithmIdentifierFields {\n\treadonly oid: string;\n\treadonly parameters: DerElement | undefined;\n\treadonly der: Uint8Array;\n}\n\nasync function verifyPbmac1MacData(\n\talgorithmDer: Uint8Array,\n\tparametersElement: DerElement | undefined,\n\tdigest: Uint8Array,\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string | undefined,\n\tbudget: KdfBudget,\n): Promise<ParsedPbmac1MacData> {\n\tif (parametersElement === undefined) {\n\t\tthrow new Error('PBMAC1 parameters must be present');\n\t}\n\tconst parameters = parsePbmac1Parameters(algorithmDer, parametersElement);\n\tconst unchecked = {\n\t\ttype: 'pbmac1',\n\t\tdigestAlgorithmOid: OIDS.pbmac1,\n\t\tdigestAlgorithmName: 'PBMAC1',\n\t\tdigestHex: toHex(digest),\n\t\tsaltHex: toHex(parameters.salt),\n\t\titerations: parameters.iterations,\n\t\tkeyLength: parameters.keyLength,\n\t\tprf: parameters.prf,\n\t\tmessageAuthScheme: parameters.messageAuthScheme,\n\t\tverification: 'unchecked',\n\t} as const;\n\tif (password === undefined) {\n\t\treturn unchecked;\n\t}\n\tchargeKdfBudget(budget, parameters.iterations);\n\tconst expected = await computePbmac1(authenticatedSafe, password, parameters);\n\treturn { ...unchecked, verification: equalBytes(expected, digest) ? 'valid' : 'invalid' };\n}\n\nfunction parsePbmac1Parameters(\n\talgorithmDer: Uint8Array,\n\tparametersElement: DerElement,\n): Pbmac1Parameters {\n\tif (parametersElement.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBMAC1-params');\n\t}\n\tconst paramsDer = algorithmDer.slice(\n\t\tparametersElement.start - parametersElement.headerLength,\n\t\tparametersElement.end,\n\t);\n\tconst children = readSequenceChildren(paramsDer);\n\tconst kdfElement = children[0];\n\tconst macElement = children[1];\n\tif (children.length !== 2 || kdfElement === undefined || macElement === undefined) {\n\t\tthrow new Error('Malformed PBMAC1-params');\n\t}\n\tconst kdf = readAlgorithmIdentifier(paramsDer, kdfElement, 'PBMAC1 keyDerivationFunc');\n\tif (kdf.oid !== OIDS.pbkdf2) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t`Unsupported PBMAC1 key derivation function ${kdf.oid}`,\n\t\t);\n\t}\n\tconst messageAuthScheme = parseHmacAlgorithm(\n\t\treadAlgorithmIdentifier(paramsDer, macElement, 'PBMAC1 messageAuthScheme'),\n\t\t'PBMAC1 messageAuthScheme',\n\t);\n\treturn { ...parsePbkdf2Parameters(kdf), messageAuthScheme };\n}\n\nfunction parsePbkdf2Parameters(\n\tkdf: AlgorithmIdentifierFields,\n): Omit<Pbmac1Parameters, 'messageAuthScheme'> {\n\tif (kdf.parameters === undefined || kdf.parameters.tag !== 0x30) {\n\t\tthrow new Error('Malformed PBKDF2-params');\n\t}\n\tconst der = kdf.der.slice(kdf.parameters.start - kdf.parameters.headerLength, kdf.parameters.end);\n\tconst [salt, iterationCount, ...optional] = readSequenceChildren(der);\n\tif (salt === undefined || iterationCount === undefined || iterationCount.tag !== 0x02) {\n\t\tthrow new Error('Malformed PBKDF2-params');\n\t}\n\tif (salt.tag === 0x30) {\n\t\tthrowMacDataError('unsupported_mac_algorithm', 'PBKDF2 otherSource salt is not supported');\n\t}\n\tif (salt.tag !== 0x04) {\n\t\tthrow new Error('Malformed PBKDF2 salt');\n\t}\n\tconst keyLengthElement = optional[0]?.tag === 0x02 ? optional[0] : undefined;\n\tconst rest = keyLengthElement === undefined ? optional : optional.slice(1);\n\tconst prfElement = rest[0];\n\tif (rest.length > 1 || (prfElement !== undefined && prfElement.tag !== 0x30)) {\n\t\tthrow new Error('Malformed PBKDF2-params');\n\t}\n\tif (keyLengthElement === undefined) {\n\t\tthrow new Error('PBKDF2-params in PBMAC1 must include keyLength');\n\t}\n\tif (prfElement === undefined) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t'PBKDF2 prf is absent and defaults to HMAC-SHA-1, which PBMAC1 verification does not accept',\n\t\t);\n\t}\n\tconst prf = parseHmacAlgorithm(\n\t\treadAlgorithmIdentifier(der, prfElement, 'PBKDF2 prf'),\n\t\t'PBKDF2 prf',\n\t);\n\tconst iterations = decodeIntegerMagnitude(iterationCount.value, 'PBKDF2 iterationCount');\n\tif (iterations.type === 'unsafe' || iterations.value > WEBCRYPTO_MAX_PBKDF2_ITERATIONS) {\n\t\tthrow new Error(`PBKDF2 iterationCount must be at most ${WEBCRYPTO_MAX_PBKDF2_ITERATIONS}`);\n\t}\n\tif (iterations.value === 0) {\n\t\tthrow new Error('PBKDF2 iterationCount must be at least 1');\n\t}\n\treturn {\n\t\tsalt: new Uint8Array(salt.value),\n\t\titerations: iterations.value,\n\t\tkeyLength: decodePbmac1KeyLength(keyLengthElement.value),\n\t\tprf,\n\t};\n}\n\nfunction decodePbmac1KeyLength(content: Uint8Array): number {\n\tconst magnitude = decodeIntegerMagnitude(content, 'PBKDF2 keyLength');\n\tif (magnitude.type === 'unsafe' || magnitude.value > PBMAC1_MAX_KEY_LENGTH) {\n\t\tthrowMacDataError(\n\t\t\t'unsupported_mac_algorithm',\n\t\t\t`PBKDF2 keyLength above ${PBMAC1_MAX_KEY_LENGTH} octets is not supported`,\n\t\t);\n\t}\n\tif (magnitude.value === 0) {\n\t\tthrow new Error('PBKDF2 keyLength must be at least 1');\n\t}\n\tif (magnitude.value < PBMAC1_MIN_KEY_LENGTH) {\n\t\tthrowMacDataError(\n\t\t\t'weak_mac_key_length',\n\t\t\t`PBKDF2 keyLength ${magnitude.value} is below ${PBMAC1_MIN_KEY_LENGTH} octets`,\n\t\t);\n\t}\n\treturn magnitude.value;\n}\n\nfunction readAlgorithmIdentifier(\n\tsource: Uint8Array,\n\telement: DerElement,\n\tlabel: string,\n): AlgorithmIdentifierFields {\n\tif (element.tag !== 0x30) {\n\t\tthrow new Error(`Malformed ${label}`);\n\t}\n\tconst der = source.slice(element.start - element.headerLength, element.end);\n\tconst children = readSequenceChildren(der);\n\tconst oid = children[0];\n\tif (oid === undefined || oid.tag !== 0x06 || children.length > 2) {\n\t\tthrow new Error(`Malformed ${label}`);\n\t}\n\treturn { oid: decodeObjectIdentifier(oid.value), parameters: children[1], der };\n}\n\nfunction parseHmacAlgorithm(algorithm: AlgorithmIdentifierFields, label: string): Pbmac1Hmac {\n\tif (\n\t\talgorithm.parameters !== undefined &&\n\t\t(algorithm.parameters.tag !== 0x05 || algorithm.parameters.length !== 0)\n\t) {\n\t\tthrow new Error(`${label} parameters must be NULL`);\n\t}\n\tswitch (algorithm.oid) {\n\t\tcase OIDS.hmacWithSHA256:\n\t\t\treturn 'HMAC-SHA-256';\n\t\tcase OIDS.hmacWithSHA384:\n\t\t\treturn 'HMAC-SHA-384';\n\t\tcase OIDS.hmacWithSHA512:\n\t\t\treturn 'HMAC-SHA-512';\n\t}\n\treturn throwMacDataError('unsupported_mac_algorithm', `Unsupported ${label} ${algorithm.oid}`);\n}\n\nfunction hmacHash(name: Pbmac1Hmac): Pbkdf2Hash {\n\tswitch (name) {\n\t\tcase 'HMAC-SHA-256':\n\t\t\treturn 'SHA-256';\n\t\tcase 'HMAC-SHA-384':\n\t\t\treturn 'SHA-384';\n\t\tcase 'HMAC-SHA-512':\n\t\t\treturn 'SHA-512';\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = name;\n\t\t\tthrow new Error(`Unhandled PBMAC1 HMAC: ${String(_exhaustive)}`);\n\t\t}\n\t}\n}\n\nasync function computePbmac1(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tparameters: Pbmac1Parameters,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePbkdf2Bytes(\n\t\tencodePbmac1Password(password),\n\t\tparameters.salt,\n\t\tparameters.iterations,\n\t\thmacHash(parameters.prf),\n\t\tparameters.keyLength,\n\t);\n\treturn await hmac(authenticatedSafe, keyBytes, hmacHash(parameters.messageAuthScheme));\n}\n\nfunction encodePbmac1Password(password: string): Uint8Array {\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tif (code >= 0xd800 && code <= 0xdbff) {\n\t\t\tconst next = password.charCodeAt(index + 1);\n\t\t\tif (next >= 0xdc00 && next <= 0xdfff) {\n\t\t\t\tindex += 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (code >= 0xd800 && code <= 0xdfff) {\n\t\t\tthrowPkcs12MacError(\n\t\t\t\t'password_not_utf8',\n\t\t\t\t`PBMAC1 password has no UTF-8 encoding: unpaired UTF-16 surrogate 0x${code.toString(16)} at index ${index}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn new TextEncoder().encode(password);\n}\n\n/** Derives an HMAC-SHA-256 key via the PKCS#12 KDF and signs the AuthenticatedSafe. */\nasync function computePkcs12Mac(\n\tauthenticatedSafe: Uint8Array,\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n): Promise<Uint8Array> {\n\tconst keyBytes = await derivePkcs12Key(password, salt, iterations, 3, 32);\n\treturn await hmac(authenticatedSafe, keyBytes, 'SHA-256');\n}\n\nasync function hmac(\n\tmessage: Uint8Array,\n\tkeyBytes: Uint8Array,\n\thash: Pbkdf2Hash,\n): Promise<Uint8Array> {\n\tconst key = await getCrypto().subtle.importKey(\n\t\t'raw',\n\t\ttoArrayBuffer(keyBytes),\n\t\t{ name: 'HMAC', hash },\n\t\tfalse,\n\t\t['sign'],\n\t);\n\treturn new Uint8Array(await getCrypto().subtle.sign('HMAC', key, toArrayBuffer(message)));\n}\n\n/**\n * PKCS#12 key derivation with SHA-256 (RFC 7292 Appendix B). `id` selects the purpose:\n * 1 for key material, 2 for an IV, 3 for a MAC key.\n *\n * @throws {ResultError} with code `password_not_bmp_string` when the password contains a\n * UTF-16 surrogate, U+FFFE or U+FFFF.\n */\nexport async function derivePkcs12Key(\n\tpassword: string,\n\tsalt: Uint8Array,\n\titerations: number,\n\tid: 1 | 2 | 3,\n\tlength: number,\n): Promise<Uint8Array> {\n\tconst u = 32;\n\tconst v = 64;\n\tconst D = new Uint8Array(v).fill(id);\n\tconst passwordBytes = encodePkcs12Password(password);\n\tconst I = concatBytes([repeatToMultiple(salt, v), repeatToMultiple(passwordBytes, v)]);\n\tconst blocks = Math.ceil(length / u);\n\tconst output = new Uint8Array(blocks * u);\n\tfor (let index = 0; index < blocks; index += 1) {\n\t\tlet A = await digestSha256(concatBytes([D, I]));\n\t\tfor (let round = 1; round < iterations; round += 1) {\n\t\t\tA = await digestSha256(A);\n\t\t}\n\t\toutput.set(A, index * u);\n\t\tif (index + 1 === blocks) {\n\t\t\tbreak;\n\t\t}\n\t\tconst B = repeatToLength(A, v);\n\t\tfor (let offset = 0; offset < I.length; offset += v) {\n\t\t\taddBlockInPlace(I.subarray(offset, offset + v), B);\n\t\t}\n\t}\n\treturn output.slice(0, length);\n}\n\n/** SHA-256 hash via WebCrypto. */\nasync function digestSha256(bytes: Uint8Array): Promise<Uint8Array> {\n\treturn new Uint8Array(await getCrypto().subtle.digest('SHA-256', toArrayBuffer(bytes)));\n}\n\n/** Encodes a password as a null-terminated BMPString, two big-endian bytes per character (RFC 7292 B.1). */\nfunction encodePkcs12Password(password: string): Uint8Array {\n\tconst out = new Uint8Array((password.length + 1) * 2);\n\tfor (let index = 0; index < password.length; index += 1) {\n\t\tconst code = password.charCodeAt(index);\n\t\tif (code >= 0xd800 && code <= 0xdfff) {\n\t\t\tthrowPkcs12MacError(\n\t\t\t\t'password_not_bmp_string',\n\t\t\t\t`PKCS#12 password is not a BMPString: UTF-16 surrogate 0x${code.toString(16)} at index ${index}`,\n\t\t\t);\n\t\t}\n\t\tif (code >= 0xfffe) {\n\t\t\tthrowPkcs12MacError(\n\t\t\t\t'password_not_bmp_string',\n\t\t\t\t`PKCS#12 password is not a BMPString: U+${code.toString(16).toUpperCase()} at index ${index}`,\n\t\t\t);\n\t\t}\n\t\tout[index * 2] = code >> 8;\n\t\tout[index * 2 + 1] = code & 0xff;\n\t}\n\treturn out;\n}\n\n/** Repeats `bytes` to the nearest multiple of `size`. */\nfunction repeatToMultiple(bytes: Uint8Array, size: number): Uint8Array {\n\tif (bytes.length === 0) {\n\t\treturn new Uint8Array();\n\t}\n\treturn repeatToLength(bytes, size * Math.ceil(bytes.length / size));\n}\n\n/** Cyclically repeats `bytes` to fill exactly `length` bytes. */\nfunction repeatToLength(bytes: Uint8Array, length: number): Uint8Array {\n\tconst out = new Uint8Array(length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tout[index] = bytes[index % bytes.length] ?? 0;\n\t}\n\treturn out;\n}\n\n/** Big-endian add-with-carry of `addend` into `block`, modifying `block` in place. */\nfunction addBlockInPlace(block: Uint8Array, addend: Uint8Array): void {\n\tlet carry = 1;\n\tfor (let index = block.length - 1; index >= 0; index -= 1) {\n\t\tconst sum = (block[index] ?? 0) + (addend[index] ?? 0) + carry;\n\t\tblock[index] = sum & 0xff;\n\t\tcarry = sum >> 8;\n\t}\n}\n\n/** Constant-time byte comparison to avoid timing side-channels in MAC checks. */\nfunction equalBytes(left: Uint8Array, right: Uint8Array): boolean {\n\tif (left.length !== right.length) {\n\t\treturn false;\n\t}\n\tlet result = 0;\n\tfor (let index = 0; index < left.length; index += 1) {\n\t\tresult |= (left[index] ?? 0) ^ (right[index] ?? 0);\n\t}\n\treturn result === 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuDA,SAAS,oBAAoB6B,GAAoCC,GAAwB;CACxFF,EAAmBC,GAAMC,CAAO;AACjC;;;;;;;;;;AAoGA,eAAsB,oBACrBC,GACAC,GAME;CACF,IAAIA,EAAQ,SAAS,UACpB,OAAO,MAAM,oBAAoBD,GA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GAA4B;CACjE,IAAID,EAAK,WAAWC,EAAM,QACzB,OAAO;CAER,IAAIC,IAAS;CACb,KAAK,IAAIzB,IAAQ,GAAGA,IAAQuB,EAAK,QAAQvB,KAAS,GACjDyB,MAAWF,EAAKvB,MAAU,MAAMwB,EAAMxB,MAAU;CAEjD,OAAOyB,MAAW;AACnB"}
@@ -1,3 +1,4 @@
1
+ import { SignatureVerifiers } from "../internal/crypto/sig-verify.js";
1
2
  import { DecodeFailureCode, DecodeRefusalCode, ErrorResult, Micro509Error } from "../result/result.js";
2
3
  import { SignatureProfileInput } from "../internal/crypto/signing.js";
3
4
  import { ParsedCertificate, ParsedName } from "../x509/parse.js";
@@ -182,6 +183,15 @@ export interface VerifyPkcs7SignedDataOptions {
182
183
  * Required to verify a detached signature; ignored when the SignedData embeds its own content.
183
184
  */
184
185
  readonly content?: Uint8Array;
186
+ /**
187
+ * Caller verifiers for signature algorithms micro509 does not verify through
188
+ * WebCrypto, keyed by dotted-decimal signature algorithm OID. One runs only
189
+ * where a SignerInfo signature would otherwise use unsupported algorithm
190
+ * parameters, with the parameters in the signer certificate. A key that
191
+ * micro509 verifies natively, a key that is no OID, or a value that is no
192
+ * function fails with `invalid_options`.
193
+ */
194
+ readonly signatureVerifiers?: SignatureVerifiers;
185
195
  }
186
196
  /** A SignerInfo paired with the certificate that verified its signature. */
187
197
  export interface VerifiedPkcs7Signer {