micro509 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/CHANGELOG.md +2064 -0
  2. package/README.md +111 -183
  3. package/dist/crypto/crypto.d.ts +104 -0
  4. package/dist/crypto/crypto.js +105 -0
  5. package/dist/crypto/crypto.js.map +1 -0
  6. package/dist/crypto.d.ts +4 -0
  7. package/dist/crypto.js +1 -0
  8. package/dist/der/der.d.ts +41 -33
  9. package/dist/der/der.js +26 -24
  10. package/dist/der/der.js.map +1 -1
  11. package/dist/index.d.ts +18 -14
  12. package/dist/index.js +19 -17
  13. package/dist/internal/asn1/asn1.d.ts +3 -6
  14. package/dist/internal/asn1/asn1.js +355 -44
  15. package/dist/internal/asn1/asn1.js.map +1 -1
  16. package/dist/internal/asn1/ber.js +146 -0
  17. package/dist/internal/asn1/ber.js.map +1 -0
  18. package/dist/internal/asn1/decode-refusal.js +29 -0
  19. package/dist/internal/asn1/decode-refusal.js.map +1 -0
  20. package/dist/internal/asn1/der.d.ts +42 -43
  21. package/dist/internal/asn1/der.js +148 -56
  22. package/dist/internal/asn1/der.js.map +1 -1
  23. package/dist/internal/asn1/oids.js +90 -54
  24. package/dist/internal/asn1/oids.js.map +1 -1
  25. package/dist/internal/asn1/oids2.js +1 -2
  26. package/dist/internal/asn1/oids2.js.map +1 -1
  27. package/dist/internal/crypto/algorithm-names.js +5 -2
  28. package/dist/internal/crypto/algorithm-names.js.map +1 -1
  29. package/dist/internal/crypto/ecdsa.js +13 -8
  30. package/dist/internal/crypto/ecdsa.js.map +1 -1
  31. package/dist/internal/crypto/hash.js +1 -2
  32. package/dist/internal/crypto/hash.js.map +1 -1
  33. package/dist/internal/crypto/pbes2.d.ts +51 -0
  34. package/dist/internal/crypto/pbes2.js +86 -34
  35. package/dist/internal/crypto/pbes2.js.map +1 -1
  36. package/dist/internal/crypto/rsa-pss.js +48 -44
  37. package/dist/internal/crypto/rsa-pss.js.map +1 -1
  38. package/dist/internal/crypto/sig-verify.d.ts +28 -0
  39. package/dist/internal/crypto/sig-verify.js +111 -62
  40. package/dist/internal/crypto/sig-verify.js.map +1 -1
  41. package/dist/internal/crypto/signing.d.ts +1 -4
  42. package/dist/internal/crypto/signing.js +28 -29
  43. package/dist/internal/crypto/signing.js.map +1 -1
  44. package/dist/internal/crypto/webcrypto.js +1 -2
  45. package/dist/internal/crypto/webcrypto.js.map +1 -1
  46. package/dist/internal/shared/base64.js +8 -3
  47. package/dist/internal/shared/base64.js.map +1 -1
  48. package/dist/internal/shared/dn.d.ts +13 -0
  49. package/dist/internal/shared/dn.js +101 -48
  50. package/dist/internal/shared/dn.js.map +1 -1
  51. package/dist/internal/shared/idna-tables.js +7217 -0
  52. package/dist/internal/shared/idna-tables.js.map +1 -0
  53. package/dist/internal/shared/idna.js +296 -0
  54. package/dist/internal/shared/idna.js.map +1 -0
  55. package/dist/internal/shared/ip.d.ts +66 -0
  56. package/dist/internal/shared/ip.js +19 -3
  57. package/dist/internal/shared/ip.js.map +1 -1
  58. package/dist/internal/shared/mailbox.js +26 -0
  59. package/dist/internal/shared/mailbox.js.map +1 -0
  60. package/dist/internal/shared/punycode.js +101 -0
  61. package/dist/internal/shared/punycode.js.map +1 -0
  62. package/dist/internal/shared/rfc3454-tables.js +1 -2
  63. package/dist/internal/shared/rfc3454-tables.js.map +1 -1
  64. package/dist/internal/shared/rfc4518-tables.js +119 -0
  65. package/dist/internal/shared/rfc4518-tables.js.map +1 -0
  66. package/dist/internal/shared/uri-host.js +102 -0
  67. package/dist/internal/shared/uri-host.js.map +1 -0
  68. package/dist/internal/verify/name-constraints-engine.js +246 -131
  69. package/dist/internal/verify/name-constraints-engine.js.map +1 -1
  70. package/dist/internal/verify/policy-engine.js +6 -21
  71. package/dist/internal/verify/policy-engine.js.map +1 -1
  72. package/dist/internal/verify/verify-path.d.ts +4 -0
  73. package/dist/internal/verify/verify-path.js +264 -128
  74. package/dist/internal/verify/verify-path.js.map +1 -1
  75. package/dist/internal/x509/directory-name.js +23 -0
  76. package/dist/internal/x509/directory-name.js.map +1 -0
  77. package/dist/internal/x509/extension-bits.js +15 -13
  78. package/dist/internal/x509/extension-bits.js.map +1 -1
  79. package/dist/internal/x509/extension-errors.d.ts +3 -0
  80. package/dist/internal/x509/extension-errors.js +19 -0
  81. package/dist/internal/x509/extension-errors.js.map +1 -0
  82. package/dist/internal/x509/extension-registry.js +157 -81
  83. package/dist/internal/x509/extension-registry.js.map +1 -1
  84. package/dist/internal/x509/general-name-profile.js +129 -0
  85. package/dist/internal/x509/general-name-profile.js.map +1 -0
  86. package/dist/internal/x509/general-name-tags.js +27 -0
  87. package/dist/internal/x509/general-name-tags.js.map +1 -0
  88. package/dist/internal/x509/general-name.js +183 -0
  89. package/dist/internal/x509/general-name.js.map +1 -0
  90. package/dist/internal/x509/name-fields.js +21 -12
  91. package/dist/internal/x509/name-fields.js.map +1 -1
  92. package/dist/internal/x509/or-address.js +217 -0
  93. package/dist/internal/x509/or-address.js.map +1 -0
  94. package/dist/keys/keys.d.ts +124 -95
  95. package/dist/keys/keys.js +362 -214
  96. package/dist/keys/keys.js.map +1 -1
  97. package/dist/keys.d.ts +3 -2
  98. package/dist/keys.js +3 -2
  99. package/dist/pem/pem.d.ts +17 -19
  100. package/dist/pem/pem.js +122 -41
  101. package/dist/pem/pem.js.map +1 -1
  102. package/dist/pem.js +1 -2
  103. package/dist/pkcs/pfx.d.ts +57 -32
  104. package/dist/pkcs/pfx.js +209 -173
  105. package/dist/pkcs/pfx.js.map +1 -1
  106. package/dist/pkcs/pkcs12-mac.d.ts +104 -27
  107. package/dist/pkcs/pkcs12-mac.js +266 -79
  108. package/dist/pkcs/pkcs12-mac.js.map +1 -1
  109. package/dist/pkcs/pkcs7.d.ts +123 -53
  110. package/dist/pkcs/pkcs7.js +314 -238
  111. package/dist/pkcs/pkcs7.js.map +1 -1
  112. package/dist/pkcs.d.ts +5 -4
  113. package/dist/result/result.d.ts +43 -28
  114. package/dist/result/result.js +27 -14
  115. package/dist/result/result.js.map +1 -1
  116. package/dist/result.d.ts +2 -2
  117. package/dist/result.js +1 -2
  118. package/dist/revocation/chain.d.ts +101 -23
  119. package/dist/revocation/chain.js +456 -206
  120. package/dist/revocation/chain.js.map +1 -1
  121. package/dist/revocation/crl.d.ts +140 -65
  122. package/dist/revocation/crl.js +691 -391
  123. package/dist/revocation/crl.js.map +1 -1
  124. package/dist/revocation/ocsp.d.ts +145 -69
  125. package/dist/revocation/ocsp.js +347 -297
  126. package/dist/revocation/ocsp.js.map +1 -1
  127. package/dist/revocation/revocation.d.ts +48 -36
  128. package/dist/revocation/revocation.js +112 -63
  129. package/dist/revocation/revocation.js.map +1 -1
  130. package/dist/revocation.d.ts +5 -5
  131. package/dist/revocation.js +5 -5
  132. package/dist/verify/identity.d.ts +18 -20
  133. package/dist/verify/identity.js +120 -90
  134. package/dist/verify/identity.js.map +1 -1
  135. package/dist/verify/name-constraints.d.ts +1 -4
  136. package/dist/verify/policy.d.ts +15 -8
  137. package/dist/verify/verify.d.ts +86 -46
  138. package/dist/verify/verify.js +309 -143
  139. package/dist/verify/verify.js.map +1 -1
  140. package/dist/verify.d.ts +3 -2
  141. package/dist/verify.js +4 -3
  142. package/dist/x509/certificate.d.ts +50 -28
  143. package/dist/x509/certificate.js +69 -36
  144. package/dist/x509/certificate.js.map +1 -1
  145. package/dist/x509/csr.d.ts +9 -8
  146. package/dist/x509/csr.js +10 -11
  147. package/dist/x509/csr.js.map +1 -1
  148. package/dist/x509/extensions.d.ts +207 -82
  149. package/dist/x509/extensions.js +561 -128
  150. package/dist/x509/extensions.js.map +1 -1
  151. package/dist/x509/fingerprint.d.ts +4 -7
  152. package/dist/x509/fingerprint.js +1 -2
  153. package/dist/x509/fingerprint.js.map +1 -1
  154. package/dist/x509/name-text.d.ts +7 -9
  155. package/dist/x509/name-text.js +20 -4
  156. package/dist/x509/name-text.js.map +1 -1
  157. package/dist/x509/name.d.ts +15 -14
  158. package/dist/x509/name.js +23 -19
  159. package/dist/x509/name.js.map +1 -1
  160. package/dist/x509/parse.d.ts +165 -64
  161. package/dist/x509/parse.js +444 -459
  162. package/dist/x509/parse.js.map +1 -1
  163. package/dist/x509.d.ts +8 -5
  164. package/dist/x509.js +10 -8
  165. package/package.json +90 -65
package/dist/pem/pem.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import { ErrorResult, Micro509Error } from "../result/result.js";
2
- //#region src/pem/pem.d.ts
3
2
  /** A single decoded PEM block with its label, decoded DER bytes, and original PEM text. */
4
- interface PemBlock {
3
+ export interface PemBlock {
5
4
  /** RFC 7468 label between the `BEGIN` / `END` markers (e.g. `"CERTIFICATE"`). */
6
5
  readonly label: string;
7
6
  /** Decoded DER content of this block. */
@@ -13,7 +12,7 @@ interface PemBlock {
13
12
  * PEM blocks grouped by their label into well-known PKI categories.
14
13
  * Blocks that don't match any known label land in {@linkcode others}.
15
14
  */
16
- interface CategorizedPemBlocks {
15
+ export interface CategorizedPemBlocks {
17
16
  /** Blocks with label `CERTIFICATE`. */
18
17
  readonly certificates: readonly PemBlock[];
19
18
  /** Blocks with label `CERTIFICATE REQUEST`. */
@@ -31,58 +30,59 @@ interface CategorizedPemBlocks {
31
30
  * @param label PEM type label (e.g. `"CERTIFICATE"`, `"PRIVATE KEY"`).
32
31
  * @param der Raw DER-encoded content.
33
32
  */
34
- declare function pemEncode(label: string, der: Uint8Array): string;
33
+ export declare function pemEncode(label: string, der: Uint8Array): string;
35
34
  /** Machine-readable failure reason for the PEM decoders. */
36
- type PemErrorCode = "malformed";
35
+ export type PemErrorCode = "malformed";
37
36
  /** Structured failure payload for PEM decoding. */
38
- interface PemFailure extends Micro509Error<PemErrorCode> {
37
+ export interface PemFailure extends Micro509Error<PemErrorCode> {
39
38
  /** Always `false` for failures. */
40
39
  readonly ok: false;
41
40
  }
42
41
  /** Success-or-failure result from {@linkcode pemDecode}. */
43
- type PemDecodeResult = {
42
+ export type PemDecodeResult = {
44
43
  readonly ok: true;
45
44
  readonly value: Uint8Array;
46
45
  } | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;
47
46
  /** Success-or-failure result from {@linkcode splitPemBlocks}. */
48
- type SplitPemBlocksResult = {
47
+ export type SplitPemBlocksResult = {
49
48
  readonly ok: true;
50
49
  readonly value: readonly PemBlock[];
51
50
  } | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;
52
51
  /** Success-or-failure result from {@linkcode categorizePemBlocks}. */
53
- type CategorizePemBlocksResult = {
52
+ export type CategorizePemBlocksResult = {
54
53
  readonly ok: true;
55
54
  readonly value: CategorizedPemBlocks;
56
55
  } | ErrorResult<PemErrorCode, Record<never, never>, PemFailure>;
57
56
  /**
58
57
  * Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the
59
- * DER content from a PEM string. Throws if the `BEGIN`/`END` markers don't
60
- * match `label`.
58
+ * DER content from a PEM string. Text ahead of the `BEGIN` line is ignored.
59
+ * Throws if the `BEGIN`/`END` markers don't match `label`.
61
60
  *
62
61
  * @param label Expected PEM type label.
63
62
  * @param pem PEM-encoded text (may contain `\r`).
64
63
  */
65
- declare function pemDecodeOrThrow(label: string, pem: string): Uint8Array;
64
+ export declare function pemDecodeOrThrow(label: string, pem: string): Uint8Array;
66
65
  /**
67
66
  * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns
68
67
  * them as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files
69
68
  * and ignores non-PEM text between blocks.
70
69
  */
71
- declare function splitPemBlocksOrThrow(input: string): readonly PemBlock[];
70
+ export declare function splitPemBlocksOrThrow(input: string): readonly PemBlock[];
72
71
  /**
73
72
  * Groups PEM blocks by label into well-known PKI categories
74
73
  * (certificates, CSRs, private keys, public keys, and everything else).
75
74
  * Accepts either raw PEM text or pre-split {@linkcode PemBlock} entries.
76
75
  */
77
- declare function categorizePemBlocksOrThrow(input: string | readonly PemBlock[]): CategorizedPemBlocks;
76
+ export declare function categorizePemBlocksOrThrow(input: string | readonly PemBlock[]): CategorizedPemBlocks;
78
77
  /**
79
78
  * Extracts and base64-decodes the DER content from a PEM string.
79
+ * Text ahead of the `BEGIN` line is ignored.
80
80
  *
81
81
  * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`
82
82
  * markers don't match `label` or the body is not valid base64. For the
83
83
  * throwing form use {@linkcode pemDecodeOrThrow}.
84
84
  */
85
- declare function pemDecode(label: string, pem: string): PemDecodeResult;
85
+ export declare function pemDecode(label: string, pem: string): PemDecodeResult;
86
86
  /**
87
87
  * Finds all `BEGIN`/`END`-delimited PEM blocks in a string and returns them
88
88
  * as parsed {@linkcode PemBlock} entries. Handles concatenated PEM files and
@@ -91,7 +91,7 @@ declare function pemDecode(label: string, pem: string): PemDecodeResult;
91
91
  * Returns a typed failure (`code: 'malformed'`) on stray or truncated PEM
92
92
  * markers. For the throwing form use {@linkcode splitPemBlocksOrThrow}.
93
93
  */
94
- declare function splitPemBlocks(input: string): SplitPemBlocksResult;
94
+ export declare function splitPemBlocks(input: string): SplitPemBlocksResult;
95
95
  /**
96
96
  * Groups PEM blocks by label into well-known PKI categories
97
97
  * (certificates, CSRs, private keys, public keys, and everything else).
@@ -101,7 +101,5 @@ declare function splitPemBlocks(input: string): SplitPemBlocksResult;
101
101
  * or truncated PEM markers. For the throwing form use
102
102
  * {@linkcode categorizePemBlocksOrThrow}.
103
103
  */
104
- declare function categorizePemBlocks(input: string | readonly PemBlock[]): CategorizePemBlocksResult;
105
- //#endregion
106
- export { CategorizePemBlocksResult, CategorizedPemBlocks, PemBlock, PemDecodeResult, PemErrorCode, PemFailure, SplitPemBlocksResult, categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow };
104
+ export declare function categorizePemBlocks(input: string | readonly PemBlock[]): CategorizePemBlocksResult;
107
105
  //# sourceMappingURL=pem.d.ts.map
package/dist/pem/pem.js CHANGED
@@ -1,6 +1,6 @@
1
- import { base64Decode as e, base64Encode as t } from "../internal/shared/base64.js";
2
- import { failureResult as n, rethrowIfInvariant as r, successResult as i } from "../result/result.js";
3
- //#region src/pem/pem.ts
1
+ import { failureResult as e, rethrowIfInvariant as t, successResult as n } from "../result/result.js";
2
+ import { base64Decode as r, base64Encode as i } from "../internal/shared/base64.js";
3
+ // src/pem/pem.ts
4
4
  /**
5
5
  * PEM helpers used across the public API.
6
6
  *
@@ -9,32 +9,34 @@ import { failureResult as n, rethrowIfInvariant as r, successResult as i } from
9
9
  *
10
10
  * @module
11
11
  */
12
+ const a = /^(?:[!-,.-~](?:[- ]?[!-,.-~])*)?$/;
12
13
  /**
13
14
  * Wraps DER bytes in a PEM envelope with 64-character base64 lines.
14
15
  *
15
16
  * @param label PEM type label (e.g. `"CERTIFICATE"`, `"PRIVATE KEY"`).
16
17
  * @param der Raw DER-encoded content.
17
18
  */
18
- function pemEncode(e, n) {
19
- return `-----BEGIN ${e}-----\n${(t(n).match(/.{1,64}/g) ?? []).join("\n")}\n-----END ${e}-----`;
19
+ function pemEncode(e, t) {
20
+ if (!isPemLabel(e)) throw Error("Invalid PEM label");
21
+ return `-----BEGIN ${e}-----\n${(i(t).match(/.{1,64}/g) ?? []).join("\n")}\n-----END ${e}-----\n`;
20
22
  }
21
23
  /**
22
24
  * Throwing core for {@linkcode pemDecode}: extracts and base64-decodes the
23
- * DER content from a PEM string. Throws if the `BEGIN`/`END` markers don't
24
- * match `label`.
25
+ * DER content from a PEM string. Text ahead of the `BEGIN` line is ignored.
26
+ * Throws if the `BEGIN`/`END` markers don't match `label`.
25
27
  *
26
28
  * @param label Expected PEM type label.
27
29
  * @param pem PEM-encoded text (may contain `\r`).
28
30
  */
29
- function pemDecodeOrThrow(t, n) {
30
- let r = n.replace(/\r/g, "").trim(), i = `-----BEGIN ${t}-----`, a = `-----END ${t}-----`, o = r.split("\n");
31
- if (o[0] !== i || o[o.length - 1] !== a || o.length < 3) throw Error(`Invalid PEM for ${t}`);
32
- let s = normalizePemBodyLines(o.slice(1, -1));
33
- if (s === void 0) throw Error(`Invalid PEM for ${t}`);
31
+ function pemDecodeOrThrow(e, t) {
32
+ let n = trimPemDocument(t.replace(/\r\n?/g, "\n")).split("\n"), i = findPreEncapsulationBoundary(n);
33
+ if (i === void 0 || parsePemBoundaryLine(n[i] ?? "", "BEGIN") !== e || parsePemBoundaryLine(n[n.length - 1] ?? "", "END") !== e || n.length - i < 3) throw Error(`Invalid PEM for ${e}`);
34
+ let a = normalizePemBodyLines(n.slice(i + 1, -1));
35
+ if (a === void 0) throw Error(`Invalid PEM for ${e}`);
34
36
  try {
35
- return e(s.join(""));
37
+ return r(a.join(""));
36
38
  } catch {
37
- throw Error(`Invalid PEM for ${t}`);
39
+ throw Error(`Invalid PEM for ${e}`);
38
40
  }
39
41
  }
40
42
  /**
@@ -43,30 +45,32 @@ function pemDecodeOrThrow(t, n) {
43
45
  * and ignores non-PEM text between blocks.
44
46
  */
45
47
  function splitPemBlocksOrThrow(e) {
46
- let t = e.replace(/\r/g, ""), n = [], r = 0, i = 0;
48
+ let t = e.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n"), n = [], r, i = 0;
47
49
  for (; i < t.length;) {
48
- let e = t.indexOf("-----BEGIN ", i);
50
+ let e = t.indexOf("\n", i), a = e === -1 ? t.length : e, o = e === -1 ? t.length : e + 1, s = t.slice(i, a), c = s.replace(/^[ \t]+/, ""), l = parsePemBoundaryLine(s, "BEGIN"), u = parsePemBoundaryLine(s, "END");
51
+ if (l !== void 0) {
52
+ if (r !== void 0) throw Error("Malformed PEM block");
53
+ r = {
54
+ label: l,
55
+ start: i + s.length - c.length
56
+ };
57
+ } else if (u !== void 0) n.push(closePemBlock(t, r, u, o)), r = void 0;
58
+ else if (looksLikePemBoundary(s)) throw Error("Malformed PEM block");
49
59
  if (e === -1) break;
50
- let a = e + 11, o = t.indexOf("-----", a);
51
- if (o === -1) break;
52
- let s = t.slice(a, o), c = o + 5;
53
- if (s.length === 0 || s.includes("-") || s.includes("\n") || t[c] !== "\n") {
54
- i = a;
55
- continue;
56
- }
57
- let l = c + 1, u = `\n-----END ${s}-----`, d = t.indexOf(u, l);
58
- if (d === -1) break;
59
- let f = d + u.length, p = t.slice(e, f);
60
- if (containsPemMarker(t.slice(r, e))) throw Error("Malformed PEM block");
61
- n.push({
62
- label: s,
63
- bytes: pemDecodeOrThrow(s, p),
64
- pem: p
65
- }), r = f, i = f;
60
+ i = o;
66
61
  }
67
- if (containsPemMarker(t.slice(r))) throw Error("Malformed PEM block");
62
+ if (r !== void 0) throw Error("Malformed PEM block");
68
63
  return n;
69
64
  }
65
+ function closePemBlock(e, t, n, r) {
66
+ if (t === void 0 || t.label !== n) throw Error("Malformed PEM block");
67
+ let i = e.slice(t.start, r);
68
+ return {
69
+ label: t.label,
70
+ bytes: pemDecodeOrThrow(t.label, i),
71
+ pem: i
72
+ };
73
+ }
70
74
  /**
71
75
  * Groups PEM blocks by label into well-known PKI categories
72
76
  * (certificates, CSRs, private keys, public keys, and everything else).
@@ -103,11 +107,89 @@ function normalizePemBodyLines(e) {
103
107
  let t = e.map((e) => e.replace(/[ \t]/g, "")).filter((e) => e !== "");
104
108
  return t.length === 0 ? [""] : t.every((e) => /^[A-Za-z0-9+/=]+$/.test(e)) ? t : void 0;
105
109
  }
106
- function containsPemMarker(e) {
107
- return e.includes("-----BEGIN ") || e.includes("-----END ");
110
+ function parsePemBoundaryLine(e, t) {
111
+ let n = `-----${t} `, r = trimLwsp(e);
112
+ if (!r.startsWith(n) || !r.endsWith("-----")) return;
113
+ let i = r.slice(n.length, -5);
114
+ return isPemLabel(i) ? i : void 0;
115
+ }
116
+ /** RFC 7468 §2: data before the encapsulation boundaries is permitted. */
117
+ function findPreEncapsulationBoundary(e) {
118
+ for (let [t, n] of e.entries()) {
119
+ if (parsePemBoundaryLine(n, "BEGIN") !== void 0) return t;
120
+ if (looksLikePemBoundary(n)) return;
121
+ }
122
+ }
123
+ function looksLikePemBoundary(e) {
124
+ return /^[ \t]*-{5,}(?:BEGIN|END)/.test(e);
125
+ }
126
+ /** RFC 822 §3.2: `field-name = 1*<any CHAR, excluding CTLs, SPACE, and ":">`. */
127
+ const o = /^[\x21-\x39\x3b-\x7e]+$/;
128
+ /** RFC 822 §3.3: `LWSP-char = SPACE / HTAB`. */
129
+ function isLwspChar(e) {
130
+ return e === " " || e === " ";
131
+ }
132
+ /**
133
+ * Strips the whitespace surrounding a PEM document: `LWSP-char`s and the line
134
+ * terminators that separate the boundary lines from the body.
135
+ *
136
+ * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode
137
+ * `Zs`, making those characters acceptable at a document edge while
138
+ * {@linkcode parsePemBoundaryLine} rejects them everywhere else.
139
+ */
140
+ function trimPemDocument(e) {
141
+ return e.replace(/^[ \t\n]+|[ \t\n]+$/g, "");
142
+ }
143
+ /**
144
+ * @internal Strips surrounding RFC 822 §3.3 `LWSP-char`s.
145
+ *
146
+ * `String.prototype.trim` would also strip VT, FF, NBSP, and every Unicode `Zs`,
147
+ * none of which the grammar admits.
148
+ */
149
+ function trimLwsp(e) {
150
+ return e.replace(/^[ \t]+|[ \t]+$/g, "");
151
+ }
152
+ /**
153
+ * @internal Parses a PEM block with RFC 1421 §4.6 encapsulated headers.
154
+ *
155
+ * RFC 7468 §2 forbids headers, so this path exists only for the legacy
156
+ * OpenSSL-style encrypted PKCS#1 and SEC1 blocks that predate it.
157
+ */
158
+ function parseTraditionalPemOrThrow(e) {
159
+ let t = trimPemDocument(e.replace(/\r\n?/g, "\n")).split("\n"), n = parsePemBoundaryLine(t[0] ?? "", "BEGIN");
160
+ if (n === void 0 || t.length < 2) throw Error("Invalid PEM block");
161
+ if (parsePemBoundaryLine(t[t.length - 1] ?? "", "END") !== n) throw Error("PEM boundaries do not match");
162
+ let r = /* @__PURE__ */ new Map(), i = 1, a;
163
+ for (; i < t.length - 1;) {
164
+ let e = t[i];
165
+ if (e === void 0) break;
166
+ if (e.length === 0) {
167
+ i += 1;
168
+ break;
169
+ }
170
+ if (a !== void 0 && isLwspChar(e.charAt(0))) {
171
+ r.set(a, `${r.get(a) ?? ""}${e}`), i += 1;
172
+ continue;
173
+ }
174
+ let n = e.indexOf(":");
175
+ if (n === -1) break;
176
+ let s = e.slice(0, n);
177
+ if (!o.test(s)) throw Error(`Invalid PEM header name: ${s}`);
178
+ if (r.has(s)) throw Error(`Duplicate PEM header: ${s}`);
179
+ r.set(s, e.slice(n + 1).replace(/^[ \t]+/, "")), a = s, i += 1;
180
+ }
181
+ return {
182
+ label: n,
183
+ headers: r,
184
+ base64Body: t.slice(i, t.length - 1).join("")
185
+ };
186
+ }
187
+ function isPemLabel(e) {
188
+ return a.exec(e)?.[0] === e;
108
189
  }
109
190
  /**
110
191
  * Extracts and base64-decodes the DER content from a PEM string.
192
+ * Text ahead of the `BEGIN` line is ignored.
111
193
  *
112
194
  * Returns a typed failure (`code: 'malformed'`) when the `BEGIN`/`END`
113
195
  * markers don't match `label` or the body is not valid base64. For the
@@ -140,14 +222,13 @@ function categorizePemBlocks(e) {
140
222
  return toPemResult(() => categorizePemBlocksOrThrow(e), "Malformed PEM block");
141
223
  }
142
224
  /** Shared Result wrapper around the throwing PEM cores. */
143
- function toPemResult(e, t) {
225
+ function toPemResult(r, i) {
144
226
  try {
145
- return i(e());
146
- } catch (e) {
147
- return r(e), n("malformed", e instanceof Error ? e.message : t);
227
+ return n(r());
228
+ } catch (n) {
229
+ return t(n), e("malformed", n instanceof Error ? n.message : i);
148
230
  }
149
231
  }
150
- //#endregion
151
- export { categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow };
232
+ export { categorizePemBlocks, categorizePemBlocksOrThrow, parseTraditionalPemOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow, trimLwsp };
152
233
 
153
234
  //# sourceMappingURL=pem.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"pem.js","names":[],"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 { failureResult, rethrowIfInvariant, successResult } 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/**\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\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/** 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. Throws if the `BEGIN`/`END` markers don't\n * 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 = pem.replace(/\\r/g, '').trim();\n\tconst begin = `-----BEGIN ${label}-----`;\n\tconst end = `-----END ${label}-----`;\n\tconst lines = normalized.split('\\n');\n\tif (lines[0] !== begin || lines[lines.length - 1] !== end || lines.length < 3) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\tconst bodyLines = normalizePemBodyLines(lines.slice(1, -1));\n\tif (bodyLines === undefined) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\ttry {\n\t\treturn base64Decode(bodyLines.join(''));\n\t} catch {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\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\tconst normalized = input.replace(/\\r/g, '');\n\tconst blocks: PemBlock[] = [];\n\tconst beginToken = '-----BEGIN ';\n\t// Linear `indexOf` scan rather than a global regex with a lazy body: a\n\t// backtracking pattern like `([\\s\\S]*?)…\\1` is polynomial on many unclosed\n\t// BEGIN markers (ReDoS). `indexOf` advances monotonically, so this stays O(n)\n\t// while preserving the original block/gap/label semantics.\n\tlet cursor = 0;\n\tlet scan = 0;\n\twhile (scan < normalized.length) {\n\t\tconst beginIdx = normalized.indexOf(beginToken, scan);\n\t\tif (beginIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst labelStart = beginIdx + beginToken.length;\n\t\tconst dashIdx = normalized.indexOf('-----', labelStart);\n\t\tif (dashIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst label = normalized.slice(labelStart, dashIdx);\n\t\tconst beginLineEnd = dashIdx + 5;\n\t\t// A well-formed begin line is `-----BEGIN <label>-----\\n` with a dash-free,\n\t\t// single-line label (RFC 7468). Anything else is not a block start; skip it\n\t\t// so it surfaces in the stray-marker checks instead of being parsed.\n\t\tif (\n\t\t\tlabel.length === 0 ||\n\t\t\tlabel.includes('-') ||\n\t\t\tlabel.includes('\\n') ||\n\t\t\tnormalized[beginLineEnd] !== '\\n'\n\t\t) {\n\t\t\tscan = labelStart;\n\t\t\tcontinue;\n\t\t}\n\t\tconst bodyStart = beginLineEnd + 1;\n\t\tconst endToken = `\\n-----END ${label}-----`;\n\t\tconst endIdx = normalized.indexOf(endToken, bodyStart);\n\t\tif (endIdx === -1) {\n\t\t\tbreak;\n\t\t}\n\t\tconst blockEnd = endIdx + endToken.length;\n\t\tconst pem = normalized.slice(beginIdx, blockEnd);\n\t\tif (containsPemMarker(normalized.slice(cursor, beginIdx))) {\n\t\t\tthrow new Error('Malformed PEM block');\n\t\t}\n\t\tblocks.push({\n\t\t\tlabel,\n\t\t\tbytes: pemDecodeOrThrow(label, pem),\n\t\t\tpem,\n\t\t});\n\t\tcursor = blockEnd;\n\t\tscan = blockEnd;\n\t}\n\tif (containsPemMarker(normalized.slice(cursor))) {\n\t\tthrow new Error('Malformed PEM block');\n\t}\n\treturn blocks;\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 containsPemMarker(value: string): boolean {\n\treturn value.includes('-----BEGIN ') || value.includes('-----END ');\n}\n\n/**\n * Extracts and base64-decodes the DER content from a PEM string.\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":";;;;;;;;;;;;;;;;;AA8CA,SAAgB,UAAU,GAAe,GAAyB;CAGjE,OAAO,cAAc,EAAM,UAFd,EAAa,CACT,CAAC,CAAC,MA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G,aAAa;AACrE;;;;;;;;;AAUA,SAAgB,eAAe,GAAqC;CACnE,OAAO,kBAAkB,sBAAsB,CAAK,GAAG,qBAAqB;AAC7E;;;;;;;;;;AAWA,SAAgB,oBACf,GAC4B;CAC5B,OAAO,kBAAkB,2BAA2B,CAAK,GAAG,qBAAqB;AAClF;;AAGA,SAAS,YACR,GACA,GAG8D;CAC9D,IAAI;EACH,OAAO,EAAc,EAAU,CAAC;CACjC,SAAS,GAAO;EAEf,OADA,EAAmB,CAAK,GACjB,EAAc,aAAa,aAAiB,QAAQ,EAAM,UAAU,CAAe;CAC3F;AACD"}
1
+ {"version":3,"file":"pem.js","names":["PEM_LABEL_PATTERN","label","base64Encode","der","lines","pem","begin","bodyLines","base64Decode","normalized","input","blocks","openBlock","lineStart","newline","lineEnd","nextLineStart","line","beginLine","beginLabel","endLabel","end","certificates","certificateRequests","privateKeys","publicKeys","others","block","nonEmptyLines","prefix","kind","withoutSurroundingWsp","index","RFC822_FIELD_NAME","character","value","headers","foldedName","delimiter","headerName","successResult","operation","error","rethrowIfInvariant","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 { failureResult, rethrowIfInvariant, successResult } 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\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\tconst bodyLines = normalizePemBodyLines(lines.slice(begin + 1, -1));\n\tif (bodyLines === undefined) {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\n\t}\n\ttry {\n\t\treturn base64Decode(bodyLines.join(''));\n\t} catch {\n\t\tthrow new Error(`Invalid PEM for ${label}`);\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\tconst normalized = input.replace(/^\\uFEFF/, '').replace(/\\r\\n?/g, '\\n');\n\tconst blocks: PemBlock[] = [];\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): PemBlock {\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\tbytes: pemDecodeOrThrow(openBlock.label, pem),\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":";;;;;;;;;;;AA0CA,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;;;;;;;;;AAkC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AAG,qBAAqB;AAClF;;AAGA,SAAS,YACR,GACA,GAG8D;CAC9D,IAAI;EACH,OAAO8B,EAAcC,EAAU,CAAC;CACjC,SAASC,GAAO;EAEf,OADAC,EAAmBD,CAAK,GACjBE,EAAc,aAAaF,aAAiB,QAAQA,EAAM,UAAUG,CAAe;CAC3F;AACD"}
package/dist/pem.js CHANGED
@@ -1,2 +1 @@
1
- import { categorizePemBlocks as e, categorizePemBlocksOrThrow as t, pemDecode as n, pemDecodeOrThrow as r, pemEncode as i, splitPemBlocks as a, splitPemBlocksOrThrow as o } from "./pem/pem.js";
2
- export { e as categorizePemBlocks, t as categorizePemBlocksOrThrow, n as pemDecode, r as pemDecodeOrThrow, i as pemEncode, a as splitPemBlocks, o as splitPemBlocksOrThrow };
1
+ export { categorizePemBlocks, categorizePemBlocksOrThrow, pemDecode, pemDecodeOrThrow, pemEncode, splitPemBlocks, splitPemBlocksOrThrow } from "./pem/pem.js";
@@ -1,55 +1,58 @@
1
- import { ErrorResult, Micro509Error } from "../result/result.js";
1
+ import { KdfLimitOptions } from "../internal/crypto/pbes2.js";
2
+ import { DecodeFailureCode, ErrorResult, Micro509Error } from "../result/result.js";
2
3
  import { EncryptedPkcs8Options } from "../keys/keys.js";
3
- import { ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow } from "./pkcs12-mac.js";
4
+ import { CreatePkcs12MacDataErrorCode, ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataOptions, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow } from "./pkcs12-mac.js";
4
5
  import { ParsedCertificate } from "../x509/parse.js";
5
- //#region src/pkcs/pfx.d.ts
6
6
  /** PEM string or DER bytes for a certificate to include in a PFX bag. */
7
- type PfxCertificateSource = string | Uint8Array | ParsedCertificate;
7
+ export type PfxCertificateSource = string | Uint8Array | ParsedCertificate;
8
8
  /** A WebCrypto private key or raw PKCS#8 DER bytes for a PFX key bag. */
9
- type PfxPrivateKeySource = CryptoKey | Uint8Array;
9
+ export type PfxPrivateKeySource = CryptoKey | Uint8Array;
10
10
  /** Optional metadata attached to a certificate or key bag inside a PFX. */
11
- interface PfxBagAttributesInput {
12
- /** Human-readable label stored as a BMPString attribute. */
11
+ export interface PfxBagAttributesInput {
12
+ /**
13
+ * Human-readable label stored as a BMPString attribute of 1 to 255 characters
14
+ * (RFC 2985 §5.5.1), none of them a surrogate, U+FFFE or U+FFFF.
15
+ */
13
16
  readonly friendlyName?: string;
14
17
  /** Opaque identifier linking a certificate bag to its corresponding key bag. */
15
18
  readonly localKeyId?: Uint8Array;
16
19
  }
17
20
  /** A certificate to embed in a PFX container. Input for {@linkcode createPfx}. */
18
- interface PfxCertificateBagInput {
21
+ export interface PfxCertificateBagInput {
19
22
  /** Certificate as PEM text or DER bytes. */
20
23
  readonly certificate: PfxCertificateSource;
21
24
  /** Optional bag-level attributes (friendly name, local key ID). */
22
25
  readonly attributes?: PfxBagAttributesInput;
23
26
  }
24
27
  /** A private key to embed in a PFX container. Input for {@linkcode createPfx}. */
25
- interface PfxPrivateKeyBagInput {
28
+ export interface PfxPrivateKeyBagInput {
26
29
  /** Private key as a WebCrypto `CryptoKey` or raw PKCS#8 DER bytes. */
27
30
  readonly privateKey: PfxPrivateKeySource;
28
31
  /** Optional bag-level attributes (friendly name, local key ID). */
29
32
  readonly attributes?: PfxBagAttributesInput;
30
33
  }
31
34
  /** Input for {@linkcode createPfx}. */
32
- interface CreatePfxInput {
35
+ export interface CreatePfxInput {
33
36
  /** Certificates to include as certBag entries. */
34
37
  readonly certificates?: readonly PfxCertificateBagInput[];
35
38
  /** Private keys to include as keyBag entries. */
36
39
  readonly privateKeys?: readonly PfxPrivateKeyBagInput[];
37
40
  /** PBES2 encryption settings for the key-bag ContentInfo. Omit for unencrypted. */
38
41
  readonly encryption?: PfxEncryptionOptions;
39
- /** PKCS#12 MAC integrity settings. Omit to skip MAC generation. */
42
+ /** PKCS#12 MAC integrity settings: the RFC 7292 MAC or RFC 9879 PBMAC1. Omit to skip MAC generation. */
40
43
  readonly mac?: Pkcs12MacOptions;
41
44
  }
42
45
  /** PBES2 encryption settings for PFX key-bag protection. Alias of {@linkcode EncryptedPkcs8Options}. */
43
- type PfxEncryptionOptions = EncryptedPkcs8Options;
46
+ export type PfxEncryptionOptions = EncryptedPkcs8Options;
44
47
  /** Options for {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */
45
- interface ParsePfxOptions {
48
+ export interface ParsePfxOptions extends KdfLimitOptions {
46
49
  /** Password used to decrypt PBES2-encrypted ContentInfo entries. Also used for MAC verification when `macPassword` is omitted. */
47
50
  readonly password?: string;
48
51
  /** Separate password for MAC verification. Falls back to `password` when omitted. */
49
52
  readonly macPassword?: string;
50
53
  }
51
54
  /** DER, PEM, and base64 encodings of a PFX container produced by {@linkcode createPfx}. */
52
- interface PfxMaterial {
55
+ export interface PfxMaterial {
53
56
  /** Raw DER-encoded PFX bytes. */
54
57
  readonly der: Uint8Array;
55
58
  /** PEM-armored PFX (`-----BEGIN PKCS12-----`). */
@@ -58,14 +61,18 @@ interface PfxMaterial {
58
61
  readonly base64: string;
59
62
  }
60
63
  /** A single PKCS#12 bag attribute as decoded by {@linkcode parsePfxDer}. */
61
- interface ParsedPfxAttribute {
64
+ export interface ParsedPfxAttribute {
62
65
  /** Dotted-decimal OID identifying this attribute type. */
63
66
  readonly oid: string;
64
- /** Hex-encoded DER of each attribute value. */
67
+ /**
68
+ * Hex of each received attribute value, re-encoded with definite lengths.
69
+ * Universal constructed strings are joined into primitive strings. SET OF
70
+ * order and implicitly tagged constructed strings stay as received.
71
+ */
65
72
  readonly valuesHex: readonly string[];
66
73
  }
67
74
  /** Decoded bag attributes for a single SafeBag inside a PFX. */
68
- interface ParsedPfxBagAttributes {
75
+ export interface ParsedPfxBagAttributes {
69
76
  /** All raw attributes as OID + hex-encoded values. */
70
77
  readonly entries: readonly ParsedPfxAttribute[];
71
78
  /** Decoded BMPString friendly-name attribute, if present. */
@@ -78,7 +85,7 @@ interface ParsedPfxBagAttributes {
78
85
  *
79
86
  * Use `kind` to narrow: `'certificate'` | `'privateKey'` | `'unknown'`.
80
87
  */
81
- type ParsedPfxBag = {
88
+ export type ParsedPfxBag = {
82
89
  /** Bag contains an X.509 certificate. */
83
90
  readonly kind: "certificate";
84
91
  /** Dotted-decimal OID of the bag type. */
@@ -103,11 +110,15 @@ type ParsedPfxBag = {
103
110
  readonly bagId: string;
104
111
  /** Decoded bag-level attributes. */
105
112
  readonly attributes: ParsedPfxBagAttributes;
106
- /** Raw DER of the unrecognized bag value. */
113
+ /**
114
+ * The received bag value, re-encoded with definite lengths. Universal
115
+ * constructed strings are joined into primitive strings. SET OF order and
116
+ * implicitly tagged constructed strings stay as received.
117
+ */
107
118
  readonly valueDer: Uint8Array;
108
119
  };
109
120
  /** Fully decoded PFX container returned by {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */
110
- interface ParsedPfx {
121
+ export interface ParsedPfx {
111
122
  /** All SafeBags in the PFX, including unknown types. */
112
123
  readonly bags: readonly ParsedPfxBag[];
113
124
  /** Convenience: only the parsed certificates extracted from certBag entries. */
@@ -118,14 +129,14 @@ interface ParsedPfx {
118
129
  readonly macData?: ParsedPkcs12MacData;
119
130
  }
120
131
  /** Error codes returned by {@linkcode parsePfxDer} and {@linkcode parsePfxPem}. */
121
- type ParsePfxErrorCode = "malformed" | "invalid_password" | "password_required";
132
+ export type ParsePfxErrorCode = DecodeFailureCode | "invalid_password" | "password_required" | "kdf_iterations_exceeded" | "password_not_bmp_string" | "password_not_utf8" | "unsupported_mac_algorithm" | "weak_mac_key_length";
122
133
  /** Error payload for a failed PFX parse. */
123
- interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {
134
+ export interface ParsePfxFailure extends Micro509Error<ParsePfxErrorCode> {
124
135
  /** Always `false` for failures. */
125
136
  readonly ok: false;
126
137
  }
127
138
  /** Success-or-failure result from {@linkcode parsePfxDer} / {@linkcode parsePfxPem}. */
128
- type ParsePfxResult = {
139
+ export type ParsePfxResult = {
129
140
  /** Parse succeeded. */
130
141
  readonly ok: true;
131
142
  /** Decoded PFX container. */
@@ -139,14 +150,16 @@ type ParsePfxResult = {
139
150
  * `CryptoKey` (platform errors stay throws) or raw PKCS#8 bytes passed through
140
151
  * unvalidated, so there is no distinct `invalid_private_key` failure to model.
141
152
  */
142
- type CreatePfxErrorCode = "invalid_certificate";
153
+ export type CreatePfxErrorCode = "invalid_certificate";
154
+ /** Bag attribute input that {@linkcode createPfx} refuses by throwing a `ResultError`. */
155
+ export type PfxEncoderErrorCode = "invalid_friendly_name";
143
156
  /** Error payload for a failed PFX creation. */
144
- interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {
157
+ export interface CreatePfxFailure extends Micro509Error<CreatePfxErrorCode> {
145
158
  /** Always `false` for failures. */
146
159
  readonly ok: false;
147
160
  }
148
161
  /** Success-or-failure result from {@linkcode createPfx}. */
149
- type CreatePfxResult = {
162
+ export type CreatePfxResult = {
150
163
  /** Creation succeeded. */
151
164
  readonly ok: true;
152
165
  /** DER, PEM, and base64 forms of the PFX container. */
@@ -162,6 +175,14 @@ type CreatePfxResult = {
162
175
  * typed `invalid_certificate` failure when a certificate source is not a single
163
176
  * PEM/DER certificate.
164
177
  *
178
+ * When `mac` is provided, `mac.type` selects the RFC 7292 MAC (the default) or
179
+ * RFC 9879 PBMAC1.
180
+ *
181
+ * @throws {ResultError} with a {@linkcode CreatePkcs12MacDataErrorCode} when `mac.iterations`
182
+ * is out of range or `mac.password` cannot be encoded for the selected MAC, and with
183
+ * {@linkcode PfxEncoderErrorCode} `invalid_friendly_name` when a bag `friendlyName` is not a
184
+ * BMPString of 1 to 255 characters.
185
+ *
165
186
  * @example
166
187
  * ```ts
167
188
  * import { createPfx, unwrap } from 'micro509';
@@ -178,9 +199,14 @@ type CreatePfxResult = {
178
199
  * // or, when inputs are already validated: const pfx = unwrap(result);
179
200
  * ```
180
201
  */
181
- declare function createPfx(input: CreatePfxInput): Promise<CreatePfxResult>;
202
+ export declare function createPfx(input: CreatePfxInput): Promise<CreatePfxResult>;
182
203
  /**
183
- * Decodes a DER-encoded PKCS#12/PFX container into its constituent bags.
204
+ * Decodes a BER- or DER-encoded PKCS#12/PFX container into its constituent bags.
205
+ *
206
+ * The PFX, AuthenticatedSafe and SafeContents layers accept BER: indefinite and
207
+ * non-minimal lengths and constructed OCTET STRINGs. The MAC is verified over the
208
+ * AuthenticatedSafe octets as received. Certificates and private keys inside the
209
+ * bags must be DER.
184
210
  *
185
211
  * Returns a result union — check `ok` before accessing `value`.
186
212
  * Encrypted containers require `options.password`. MAC verification uses
@@ -196,7 +222,7 @@ declare function createPfx(input: CreatePfxInput): Promise<CreatePfxResult>;
196
222
  * }
197
223
  * ```
198
224
  */
199
- declare function parsePfxDer(der: Uint8Array, options?: ParsePfxOptions): Promise<ParsePfxResult>;
225
+ export declare function parsePfxDer(der: Uint8Array, options?: ParsePfxOptions): Promise<ParsePfxResult>;
200
226
  /**
201
227
  * Decodes a PEM-armored PKCS#12/PFX container. Expects exactly one `PKCS12` block.
202
228
  *
@@ -212,7 +238,6 @@ declare function parsePfxDer(der: Uint8Array, options?: ParsePfxOptions): Promis
212
238
  * }
213
239
  * ```
214
240
  */
215
- declare function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult>;
216
- //#endregion
217
- export { CreatePfxErrorCode, CreatePfxFailure, CreatePfxInput, CreatePfxResult, ParsePfxErrorCode, ParsePfxFailure, ParsePfxOptions, ParsePfxResult, type ParsePkcs12MacDataErrorCode, type ParsePkcs12MacDataFailure, type ParsePkcs12MacDataResult, ParsedPfx, ParsedPfxAttribute, ParsedPfxBag, ParsedPfxBagAttributes, type ParsedPkcs12MacData, PfxBagAttributesInput, PfxCertificateBagInput, PfxCertificateSource, PfxEncryptionOptions, PfxMaterial, PfxPrivateKeyBagInput, PfxPrivateKeySource, type Pkcs12MacOptions, createPfx, type createPkcs12MacData, parsePfxDer, parsePfxPem, type parsePkcs12MacData, type parsePkcs12MacDataOrThrow };
241
+ export declare function parsePfxPem(pem: string, options?: ParsePfxOptions): Promise<ParsePfxResult>;
242
+ export type { CreatePkcs12MacDataErrorCode, KdfLimitOptions, ParsePkcs12MacDataErrorCode, ParsePkcs12MacDataFailure, ParsePkcs12MacDataOptions, ParsePkcs12MacDataResult, ParsedPkcs12MacData, Pkcs12MacOptions, createPkcs12MacData, parsePkcs12MacData, parsePkcs12MacDataOrThrow };
218
243
  //# sourceMappingURL=pfx.d.ts.map