micro509 0.18.0 → 0.19.1
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.
- package/CHANGELOG.md +109 -1
- package/dist/crypto/crypto.d.ts +11 -2
- package/dist/crypto/crypto.js +30 -17
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +2 -2
- package/dist/der/der.js.map +1 -1
- package/dist/index.d.ts +7 -6
- package/dist/internal/asn1/asn1.js +10 -2
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js.map +1 -1
- package/dist/internal/asn1/decode-refusal.js.map +1 -1
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js +64 -64
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.js +3 -3
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/prime-ec.js.map +1 -1
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +40 -0
- package/dist/internal/crypto/sig-verify.js +152 -65
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/jose/base64url.js.map +1 -1
- package/dist/internal/jose/json-data.js.map +1 -1
- package/dist/internal/jose/strict-json.js.map +1 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna-tables.js +3 -3
- package/dist/internal/shared/idna.js.map +1 -1
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js.map +1 -1
- package/dist/internal/shared/punycode.js +1 -1
- package/dist/internal/shared/punycode.js.map +1 -1
- package/dist/internal/shared/uri-host.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js.map +1 -1
- package/dist/internal/verify/verify-path.js +222 -116
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js.map +1 -1
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js.map +1 -1
- package/dist/jose/base64url.js.map +1 -1
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.js.map +1 -1
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.js.map +1 -1
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/kdf/argon2-arithmetic.js.map +1 -1
- package/dist/kdf/argon2-core.js.map +1 -1
- package/dist/kdf/argon2-memory.js.map +1 -1
- package/dist/kdf/argon2-portable.js +1 -1
- package/dist/kdf/argon2-portable.js.map +1 -1
- package/dist/kdf/argon2.js +2 -2
- package/dist/kdf/argon2.js.map +1 -1
- package/dist/keys/keys.d.ts +7 -2
- package/dist/keys/keys.js +10 -6
- package/dist/keys/keys.js.map +1 -1
- package/dist/pem/pem.d.ts +20 -7
- package/dist/pem/pem.js +24 -20
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +2 -2
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.js +3 -3
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +10 -0
- package/dist/pkcs/pkcs7.js +106 -88
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/result/result.js.map +1 -1
- package/dist/revocation/chain.d.ts +67 -13
- package/dist/revocation/chain.js +429 -301
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +65 -11
- package/dist/revocation/crl.js +472 -182
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +79 -24
- package/dist/revocation/ocsp.js +417 -231
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +68 -13
- package/dist/revocation/revocation.js +194 -73
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +4 -4
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.js.map +1 -1
- package/dist/verify/identity.d.ts +2 -2
- package/dist/verify/identity.js +2 -2
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/verify.d.ts +84 -32
- package/dist/verify/verify.js +221 -175
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +3 -2
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.js +1 -1
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.js +1 -1
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +6 -2
- package/dist/x509/parse.js +121 -121
- package/dist/x509/parse.js.map +1 -1
- package/package.json +16 -16
package/dist/pem/pem.d.ts
CHANGED
|
@@ -33,6 +33,16 @@ export interface CategorizedPemBlocks {
|
|
|
33
33
|
export declare function pemEncode(label: string, der: Uint8Array): string;
|
|
34
34
|
/** Machine-readable failure reason for the PEM decoders. */
|
|
35
35
|
export type PemErrorCode = "malformed";
|
|
36
|
+
/** Controls how much of the input a PEM decoder consumes. */
|
|
37
|
+
export interface PemDecodeOptions {
|
|
38
|
+
/**
|
|
39
|
+
* Require the entire input to be one PEM block of the requested label.
|
|
40
|
+
* The BEGIN and END lines must be exact, and the body must contain only
|
|
41
|
+
* nonempty base64 lines. Each line break may be LF or CRLF, with at most
|
|
42
|
+
* one optional line break after END. Defaults to false.
|
|
43
|
+
*/
|
|
44
|
+
readonly wholeInput?: boolean;
|
|
45
|
+
}
|
|
36
46
|
/** Structured failure payload for PEM decoding. */
|
|
37
47
|
export interface PemFailure extends Micro509Error<PemErrorCode> {
|
|
38
48
|
/** Always `false` for failures. */
|
|
@@ -55,13 +65,15 @@ export type CategorizePemBlocksResult = {
|
|
|
55
65
|
} | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;
|
|
56
66
|
/**
|
|
57
67
|
* Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the
|
|
58
|
-
* DER content from a PEM string.
|
|
59
|
-
* Throws if the
|
|
68
|
+
* DER content from a PEM string. By default, text ahead of the `BEGIN` line
|
|
69
|
+
* is ignored. Throws if the input fails the selected policy or the
|
|
70
|
+
* `BEGIN`/`END` markers don't match `label`.
|
|
60
71
|
*
|
|
61
72
|
* @param label Expected PEM type label.
|
|
62
73
|
* @param pem PEM-encoded text (may contain `\r`).
|
|
74
|
+
* @param options Set `wholeInput` to require one block with exact boundaries.
|
|
63
75
|
*/
|
|
64
|
-
export declare function pemDecodeOrThrow(label: string, pem: string): Uint8Array;
|
|
76
|
+
export declare function pemDecodeOrThrow(label: string, pem: string, options?: PemDecodeOptions): Uint8Array;
|
|
65
77
|
/**
|
|
66
78
|
* Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns
|
|
67
79
|
* them as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files
|
|
@@ -76,13 +88,14 @@ export declare function splitPemBlocksOrThrow(input: string): readonly PemBlock[
|
|
|
76
88
|
export declare function categorizePemBlocksOrThrow(input: string | readonly PemBlock[]): CategorizedPemBlocks;
|
|
77
89
|
/**
|
|
78
90
|
* Extracts and base64-decodes the DER content from a PEM string.
|
|
79
|
-
* Text ahead of the `BEGIN` line is ignored.
|
|
91
|
+
* Text ahead of the `BEGIN` line is ignored by default. Set
|
|
92
|
+
* {@linkcode PemDecodeOptions.wholeInput} to require one complete block.
|
|
80
93
|
*
|
|
81
94
|
* Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`
|
|
82
|
-
* markers don't match `label
|
|
83
|
-
* throwing form use {@linkcode pemDecodeOrThrow}.
|
|
95
|
+
* markers don't match `label`, the input fails the selected policy, or the
|
|
96
|
+
* body is not valid base64. For the throwing form use {@linkcode pemDecodeOrThrow}.
|
|
84
97
|
*/
|
|
85
|
-
export declare function pemDecode(label: string, pem: string): PemDecodeResult;
|
|
98
|
+
export declare function pemDecode(label: string, pem: string, options?: PemDecodeOptions): PemDecodeResult;
|
|
86
99
|
/**
|
|
87
100
|
* Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them
|
|
88
101
|
* as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files and
|
package/dist/pem/pem.js
CHANGED
|
@@ -22,25 +22,29 @@ function pemEncode(e, n) {
|
|
|
22
22
|
}
|
|
23
23
|
/**
|
|
24
24
|
* Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the
|
|
25
|
-
* DER content from a PEM string.
|
|
26
|
-
* Throws if the
|
|
25
|
+
* DER content from a PEM string. By default, text ahead of the `BEGIN` line
|
|
26
|
+
* is ignored. Throws if the input fails the selected policy or the
|
|
27
|
+
* `BEGIN`/`END` markers don't match `label`.
|
|
27
28
|
*
|
|
28
29
|
* @param label Expected PEM type label.
|
|
29
30
|
* @param pem PEM-encoded text (may contain `\r`).
|
|
31
|
+
* @param options Set `wholeInput` to require one block with exact boundaries.
|
|
30
32
|
*/
|
|
31
|
-
function pemDecodeOrThrow(t, n) {
|
|
32
|
-
let i = trimPemDocument(n.replace(/\r\n?/g, "\n")).split("\n")
|
|
33
|
-
|
|
33
|
+
function pemDecodeOrThrow(t, n, i) {
|
|
34
|
+
let o = i?.wholeInput === !0, s = (o ? n.replace(/\r\n/g, "\n") : trimPemDocument(n.replace(/\r\n?/g, "\n"))).split("\n");
|
|
35
|
+
o && s.at(-1) === "" && s.pop();
|
|
36
|
+
let c = o ? 0 : findPreEncapsulationBoundary(s);
|
|
37
|
+
(c === void 0 || parsePemBoundaryLine(s[c] ?? "", "BEGIN", o) !== t || parsePemBoundaryLine(s.at(-1) ?? "", "END", o) !== t || s.length - c < 3) && a("malformed", `Invalid PEM for ${t}`, {
|
|
34
38
|
stage: "pem",
|
|
35
39
|
reason: "invalid_armor"
|
|
36
40
|
});
|
|
37
|
-
let
|
|
38
|
-
|
|
41
|
+
let l = s.slice(c + 1, -1), u = o ? l : normalizePemBodyLines(l);
|
|
42
|
+
u.every((e) => /^[A-Za-z0-9+/=]+$/.test(e)) || a("malformed", `Invalid PEM for ${t}`, {
|
|
39
43
|
stage: "base64",
|
|
40
44
|
reason: "invalid_base64"
|
|
41
45
|
});
|
|
42
46
|
try {
|
|
43
|
-
return e(
|
|
47
|
+
return e(u.join(""));
|
|
44
48
|
} catch (e) {
|
|
45
49
|
r(e), a("malformed", `Invalid PEM for ${t}`, {
|
|
46
50
|
stage: "base64",
|
|
@@ -119,14 +123,13 @@ function categorizePemBlocksOrThrow(e) {
|
|
|
119
123
|
};
|
|
120
124
|
}
|
|
121
125
|
function normalizePemBodyLines(e) {
|
|
122
|
-
|
|
123
|
-
return t.length === 0 ? [""] : t.every((e) => /^[A-Za-z0-9+/=]+$/.test(e)) ? t : void 0;
|
|
126
|
+
return e.map((e) => e.replace(/[ \t]/g, "")).filter((e) => e !== "");
|
|
124
127
|
}
|
|
125
|
-
function parsePemBoundaryLine(e, t) {
|
|
126
|
-
let
|
|
127
|
-
if (!
|
|
128
|
-
let
|
|
129
|
-
return isPemLabel(
|
|
128
|
+
function parsePemBoundaryLine(e, t, n = !1) {
|
|
129
|
+
let r = `-----${t} `, i = n ? e : trimLwsp(e);
|
|
130
|
+
if (!i.startsWith(r) || !i.endsWith("-----")) return;
|
|
131
|
+
let a = i.slice(r.length, -5);
|
|
132
|
+
return isPemLabel(a) ? a : void 0;
|
|
130
133
|
}
|
|
131
134
|
/** RFC 7468 §2: data before the encapsulation boundaries is permitted. */
|
|
132
135
|
function findPreEncapsulationBoundary(e) {
|
|
@@ -204,14 +207,15 @@ function isPemLabel(e) {
|
|
|
204
207
|
}
|
|
205
208
|
/**
|
|
206
209
|
* Extracts and base64-decodes the DER content from a PEM string.
|
|
207
|
-
* Text ahead of the `BEGIN` line is ignored.
|
|
210
|
+
* Text ahead of the `BEGIN` line is ignored by default. Set
|
|
211
|
+
* {@linkcode PemDecodeOptions.wholeInput} to require one complete block.
|
|
208
212
|
*
|
|
209
213
|
* Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`
|
|
210
|
-
* markers don't match `label
|
|
211
|
-
* throwing form use {@linkcode pemDecodeOrThrow}.
|
|
214
|
+
* markers don't match `label`, the input fails the selected policy, or the
|
|
215
|
+
* body is not valid base64. For the throwing form use {@linkcode pemDecodeOrThrow}.
|
|
212
216
|
*/
|
|
213
|
-
function pemDecode(e, t) {
|
|
214
|
-
return toPemResult(() => pemDecodeOrThrow(e, t), "Invalid PEM");
|
|
217
|
+
function pemDecode(e, t, n) {
|
|
218
|
+
return toPemResult(() => pemDecodeOrThrow(e, t, n), "Invalid PEM");
|
|
215
219
|
}
|
|
216
220
|
/**
|
|
217
221
|
* Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them
|
package/dist/pem/pem.js.map
CHANGED
|
@@ -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,K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qB;AAClF;;AAGA,SAAS,YACR,GACA,GAG8D;CAC9D,IAAI;EACH,OAAO+B,EAAcC,EAAU,CAAC;CACjC,SAASlC,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","options","wholeInput","lines","begin","bodyLines","base64Lines","line","error","input","block","normalized","blocks","openBlock","lineStart","newline","lineEnd","nextLineStart","beginLine","beginLabel","endLabel","end","certificates","certificateRequests","privateKeys","publicKeys","others","kind","prefix","boundary","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/** Controls how much of the input a PEM decoder consumes. */\nexport interface PemDecodeOptions {\n\t/**\n\t * Require the entire input to be one PEM block of the requested label.\n\t * The BEGIN and END lines must be exact, and the body must contain only\n\t * nonempty base64 lines. Each line break may be LF or CRLF, with at most\n\t * one optional line break after END. Defaults to false.\n\t */\n\treadonly wholeInput?: boolean;\n}\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. By default, text ahead of the `BEGIN` line\n * is ignored. Throws if the input fails the selected policy or the\n * `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 * @param options Set `wholeInput` to require one block with exact boundaries.\n */\nexport function pemDecodeOrThrow(\n\tlabel: string,\n\tpem: string,\n\toptions?: PemDecodeOptions,\n): Uint8Array {\n\tconst wholeInput = options?.wholeInput === true;\n\tconst normalized = wholeInput\n\t\t? pem.replace(/\\r\\n/g, '\\n')\n\t\t: trimPemDocument(pem.replace(/\\r\\n?/g, '\\n'));\n\tconst lines = normalized.split('\\n');\n\tif (wholeInput && lines.at(-1) === '') lines.pop();\n\tconst begin = wholeInput ? 0 : findPreEncapsulationBoundary(lines);\n\tif (\n\t\tbegin === undefined ||\n\t\tparsePemBoundaryLine(lines[begin] ?? '', 'BEGIN', wholeInput) !== label ||\n\t\tparsePemBoundaryLine(lines.at(-1) ?? '', 'END', wholeInput) !== 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 = lines.slice(begin + 1, -1);\n\tconst base64Lines = wholeInput ? bodyLines : normalizePemBodyLines(bodyLines);\n\tif (!base64Lines.every((line) => /^[A-Za-z0-9+/=]+$/.test(line))) {\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(base64Lines.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[] {\n\treturn lines.map((line) => line.replace(/[ \\t]/g, '')).filter((line) => line !== '');\n}\n\nfunction parsePemBoundaryLine(\n\tline: string,\n\tkind: 'BEGIN' | 'END',\n\twholeInput = false,\n): string | undefined {\n\tconst prefix = `-----${kind} `;\n\tconst boundary = wholeInput ? line : trimLwsp(line);\n\tif (!boundary.startsWith(prefix) || !boundary.endsWith('-----')) {\n\t\treturn undefined;\n\t}\n\tconst label = boundary.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 by default. Set\n * {@linkcode PemDecodeOptions.wholeInput} to require one complete block.\n *\n * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`\n * markers don't match `label`, the input fails the selected policy, or the\n * body is not valid base64. For the throwing form use {@linkcode pemDecodeOrThrow}.\n */\nexport function pemDecode(label: string, pem: string, options?: PemDecodeOptions): PemDecodeResult {\n\treturn toPemResult(() => pemDecodeOrThrow(label, pem, options), '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;;;;;;;AAQ1B,SAAgB,UAAUC,GAAeC,GAAyB;CACjE,IAAI,CAAC,WAAWD,CAAK,GACpB,MAAU,MAAM,mBAAmB;CAIpC,OAAO,cAAcA,EAAM,UAFdN,EAAaO,CACT,CAAC,CAAC,MAAM,UAAU,KAAK,CAAC,EAAA,CACC,KAAK,IAAI,EAAE,aAAaD,EAAM;AACzE;;;;;;;;;;;AA+CA,SAAgB,iBACfA,GACAE,GACAC,GACa;CACb,IAAMC,IAAaD,GAAS,eAAe,IAIrCE,KAHaD,IAChBF,EAAI,QAAQ,SAAS,IAAI,IACzB,gBAAgBA,EAAI,QAAQ,UAAU,IAAI,CAAC,EAAA,CACrB,MAAM,IAAI;CAC/BE,KAAcC,EAAM,GAAG,EAAE,MAAM,MAAIA,EAAM,IAAI;CACjD,IAAMC,IAAQF,IAAa,IAAI,6BAA6BC,CAAK;CACjE,CACCC,MAAU,KAAA,KACV,qBAAqBD,EAAMC,MAAU,IAAI,SAASF,CAAU,MAAMJ,KAClE,qBAAqBK,EAAM,GAAG,EAAE,KAAK,IAAI,OAAOD,CAAU,MAAMJ,KAChEK,EAAM,SAASC,IAAQ,MAEvBR,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ACR6B,GACAC,GAG8D;CAC9D,IAAI;EACH,OAAO5C,EAAc2C,EAAU,CAAC;CACjC,SAAS9B,GAAO;EAEf,OADAd,EAAmBc,CAAK,GACjBf,EAAc,aAAae,aAAiB,QAAQA,EAAM,UAAU+B,CAAe;CAC3F;AACD"}
|
package/dist/pem.d.ts
CHANGED
|
@@ -4,5 +4,5 @@
|
|
|
4
4
|
*
|
|
5
5
|
* @module micro509/pem
|
|
6
6
|
*/
|
|
7
|
-
import { CategorizePemBlocksResult, CategorizedPemBlocks, PemBlock, PemDecodeResult, PemErrorCode, PemFailure, SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow } from "./pem/pem.js";
|
|
8
|
-
export { type CategorizePemBlocksResult, type CategorizedPemBlocks, type PemBlock, type PemDecodeResult, type PemErrorCode, type PemFailure, type SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow };
|
|
7
|
+
import { CategorizePemBlocksResult, CategorizedPemBlocks, PemBlock, PemDecodeOptions, PemDecodeResult, PemErrorCode, PemFailure, SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow } from "./pem/pem.js";
|
|
8
|
+
export { type CategorizePemBlocksResult, type CategorizedPemBlocks, type PemBlock, type PemDecodeOptions, type PemDecodeResult, type PemErrorCode, type PemFailure, type SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow };
|
package/dist/pkcs/pfx.js.map
CHANGED
|
@@ -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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6SA,eAAsB,UAAU,GAAiD;CAChF,IAAMA,IAAgC,CAAC,GACjCC,IAA+B,CAAC;CACtC,KAAK,IAAMC,KAAeC,EAAM,gBAAgB,CAAC,GAAG;EAGnD,IAAIC;EACJ,IAAI;GACH,IAAiB,qBAAqBF,EAAY,WAAW;EAC9D,QAAQ;GACP,OAAO,mBACN,uBACA,qEACD;EACD;EACA,EAAgB,KAAK,qBAAqBE,GAAgBF,EAAY,UAAU,CAAC;CAClF;CACA,KAAK,IAAMG,KAAcF,EAAM,eAAe,CAAC,GAC9C,EAAe,KACd,oBAAoB,MAAM,oBAAoBE,EAAW,UAAU,GAAGA,EAAW,UAAU,CAC5F;CAED,IAAMC,IAA6B,CAAC;CAIpC,IAHIN,EAAgB,SAAS,KAC5BM,EAAa,KAAK,sBAAsBC,EAASP,CAAe,CAAC,CAAC,GAE/DC,EAAe,SAAS,GAAG;EAC9B,IAAMO,IAAeD,EAASN,CAAc;EAC5C,EAAa,KACZE,EAAM,eAAe,KAAA,IAClB,sBAAsBK,CAAY,IAClC,MAAM,+BAA+BA,GAAcL,EAAM,UAAU,CACvE;CACD;CACA,IAAMM,IAAoBF,EAASD,CAAY,GACzCI,IACLP,EAAM,QAAQ,KAAA,IAAY,KAAA,IAAY,MAAMQ,EAAoBF,GAAmBN,EAAM,GAAG,GACvFS,IAAML,EAAS;E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AAQ,SAAS,WAAW,KAAKa,MAAU,KAAA,GAC9C,MAAU,MAAM,0DAA0D;CAE3E,OAAOA;AACR;;AAGA,SAAS,mBAAmB,GAAyB;CACpD,IAAMb,IAAUC,EAAYpF,CAAG;CAC/B,IAAImF,EAAQ,QAAQ,IACnB,MAAU,MAAM,kCAAkC;CAEnD,IAAMtB,IAAeoC,EAAa,IAAMd,EAAQ,KAAK;CACrD,IAAItB,EAAa,SAAS,KAAKA,EAAa,SAAS,KACpD,MAAU,MAAM,4CAA4C;CAE7D,OAAOA;AACR"}
|
|
1
|
+
{"version":3,"file":"pfx.js","names":["decodeIntegerNumber","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,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D,IAAsBpG,EAAoBmG,CAAoB,GAC9D/B,IAAcgC,EAAoB,IAClCC,IAAYD,EAAoB,IAChCE,IAAmBF,EAAoB;CAC7C,IACChC,MAAgB,KAAA,KAChBiC,MAAc,KAAA,KACdC,MAAqB,KAAA,KACrBF,EAAoB,WAAW,GAE/B,MAAU,MAAM,gCAAgC;CAGjD,OADArG,EAAoBiE,GAAQI,GAAa,CAAI,GACtClD,EACNhB,EAAoB8D,GAAQqC,CAAS,GACrCpG,EAAiB+D,GAAQsC,GAAkB,KAAM,CAAI,GACrDJ,GACAnD,CACD;AACD;;AAGA,SAAS,0BAA0BiB,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"}
|
package/dist/pkcs/pkcs12-mac.js
CHANGED
|
@@ -52,7 +52,7 @@ async function createPkcs12MacData(e, t) {
|
|
|
52
52
|
}
|
|
53
53
|
async function createPbmac1MacData(e, t) {
|
|
54
54
|
let n = t.iterations ?? 1e5;
|
|
55
|
-
(!Number.isInteger(n) || n < 1 || n >
|
|
55
|
+
(!Number.isInteger(n) || n < 1 || n > 0xffffffff) && throwPkcs12MacError("invalid_iterations", `PBMAC1 iterations must be an integer from 1 to ${_}, got ${n}`);
|
|
56
56
|
let i = t.salt ?? S().getRandomValues(/* @__PURE__ */ new Uint8Array(16)), a = {
|
|
57
57
|
salt: i,
|
|
58
58
|
iterations: n,
|
|
@@ -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,
|
|
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");
|
|
@@ -211,7 +211,7 @@ function parsePbkdf2Parameters(t) {
|
|
|
211
211
|
if (o === void 0) throw Error("PBKDF2-params in PBMAC1 must include keyLength");
|
|
212
212
|
c === void 0 && throwMacDataError("unsupported_mac_algorithm", "PBKDF2 prf is absent and defaults to HMAC-SHA-1, which PBMAC1 verification does not accept");
|
|
213
213
|
let l = parseHmacAlgorithm(readAlgorithmIdentifier(n, c, "PBKDF2 prf"), "PBKDF2 prf"), u = e(i.value, "PBKDF2 iterationCount");
|
|
214
|
-
if (u.type === "unsafe" || u.value >
|
|
214
|
+
if (u.type === "unsafe" || u.value > 0xffffffff) throw Error(`PBKDF2 iterationCount must be at most ${_}`);
|
|
215
215
|
if (u.value === 0) throw Error("PBKDF2 iterationCount must be at least 1");
|
|
216
216
|
return {
|
|
217
217
|
salt: new Uint8Array(r.value),
|