micro509 0.17.0 → 0.18.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 (137) hide show
  1. package/CHANGELOG.md +123 -6
  2. package/README.md +3 -0
  3. package/dist/crypto/crypto.d.ts +2 -3
  4. package/dist/crypto.d.ts +6 -0
  5. package/dist/der/der.d.ts +14 -4
  6. package/dist/der/der.js +19 -19
  7. package/dist/der.d.ts +26 -2
  8. package/dist/der.js +4 -4
  9. package/dist/index.d.ts +82 -15
  10. package/dist/index.js +19 -19
  11. package/dist/internal/asn1/asn1.d.ts +1 -2
  12. package/dist/internal/asn1/der.d.ts +1 -2
  13. package/dist/internal/asn1/oids.js +71 -353
  14. package/dist/internal/asn1/oids.js.map +1 -1
  15. package/dist/internal/asn1/oids.json.js +357 -0
  16. package/dist/internal/asn1/oids.json.js.map +1 -0
  17. package/dist/internal/crypto/algorithm-names.js +1 -1
  18. package/dist/internal/crypto/pbes2.d.ts +1 -2
  19. package/dist/internal/crypto/pbes2.js +70 -70
  20. package/dist/internal/crypto/prime-ec.js +37 -0
  21. package/dist/internal/crypto/prime-ec.js.map +1 -0
  22. package/dist/internal/crypto/rsa-pss.js +50 -50
  23. package/dist/internal/crypto/sig-verify.d.ts +1 -2
  24. package/dist/internal/crypto/sig-verify.js +60 -60
  25. package/dist/internal/crypto/signing.d.ts +1 -2
  26. package/dist/internal/crypto/signing.js +26 -26
  27. package/dist/internal/jose/json-data.js +108 -0
  28. package/dist/internal/jose/json-data.js.map +1 -0
  29. package/dist/internal/jose/strict-json.d.ts +1 -2
  30. package/dist/internal/shared/dn.d.ts +1 -2
  31. package/dist/internal/shared/dn.js +1 -1
  32. package/dist/internal/shared/ip.d.ts +1 -2
  33. package/dist/internal/verify/name-constraints-engine.js +64 -64
  34. package/dist/internal/verify/policy-engine.js +1 -1
  35. package/dist/internal/verify/verify-path.d.ts +1 -2
  36. package/dist/internal/verify/verify-path.js +19 -19
  37. package/dist/internal/x509/directory-name.js +10 -10
  38. package/dist/internal/x509/extension-errors.d.ts +1 -2
  39. package/dist/internal/x509/extension-registry.js +18 -18
  40. package/dist/internal/x509/general-name-profile.js +9 -9
  41. package/dist/internal/x509/general-name.js +32 -32
  42. package/dist/internal/x509/name-fields.js +1 -1
  43. package/dist/jose/base64url.d.ts +4 -0
  44. package/dist/jose/base64url.js +14 -0
  45. package/dist/jose/base64url.js.map +1 -0
  46. package/dist/jose/errors.d.ts +9 -3
  47. package/dist/jose/errors.js.map +1 -1
  48. package/dist/jose/jwe.d.ts +64 -0
  49. package/dist/jose/jwe.js +188 -0
  50. package/dist/jose/jwe.js.map +1 -0
  51. package/dist/jose/jwks.d.ts +38 -10
  52. package/dist/jose/jwks.js +156 -96
  53. package/dist/jose/jwks.js.map +1 -1
  54. package/dist/jose/jws.d.ts +8 -6
  55. package/dist/jose/jws.js +216 -170
  56. package/dist/jose/jws.js.map +1 -1
  57. package/dist/jose/jwt.d.ts +8 -2
  58. package/dist/jose/jwt.js +98 -98
  59. package/dist/jose/remote-jwks.d.ts +1 -2
  60. package/dist/jose/remote-jwks.js +106 -108
  61. package/dist/jose/remote-jwks.js.map +1 -1
  62. package/dist/jose.d.ts +15 -4
  63. package/dist/jose.js +7 -5
  64. package/dist/kdf/argon2-arithmetic.js +15 -0
  65. package/dist/kdf/argon2-arithmetic.js.map +1 -0
  66. package/dist/kdf/argon2-core.js +486 -0
  67. package/dist/kdf/argon2-core.js.map +1 -0
  68. package/dist/kdf/argon2-memory.js +20 -0
  69. package/dist/kdf/argon2-memory.js.map +1 -0
  70. package/dist/kdf/argon2-portable.js +18 -0
  71. package/dist/kdf/argon2-portable.js.map +1 -0
  72. package/dist/kdf/argon2.d.ts +22 -11
  73. package/dist/kdf/argon2.js +32 -13
  74. package/dist/kdf/argon2.js.map +1 -1
  75. package/dist/kdf.d.ts +6 -0
  76. package/dist/keys/keys.d.ts +31 -6
  77. package/dist/keys/keys.js +315 -233
  78. package/dist/keys/keys.js.map +1 -1
  79. package/dist/keys.d.ts +11 -2
  80. package/dist/keys.js +2 -2
  81. package/dist/pem/pem.d.ts +1 -2
  82. package/dist/pem/pem.js +40 -25
  83. package/dist/pem/pem.js.map +1 -1
  84. package/dist/pem.d.ts +6 -0
  85. package/dist/pkcs/pfx.d.ts +2 -3
  86. package/dist/pkcs/pfx.js +142 -142
  87. package/dist/pkcs/pkcs12-mac.d.ts +1 -2
  88. package/dist/pkcs/pkcs12-mac.js +122 -122
  89. package/dist/pkcs/pkcs7.d.ts +14 -3
  90. package/dist/pkcs/pkcs7.js +268 -248
  91. package/dist/pkcs/pkcs7.js.map +1 -1
  92. package/dist/pkcs.d.ts +10 -1
  93. package/dist/pkcs.js +4 -4
  94. package/dist/result/result.d.ts +1 -2
  95. package/dist/result.d.ts +6 -0
  96. package/dist/revocation/chain.d.ts +2 -3
  97. package/dist/revocation/chain.js +52 -52
  98. package/dist/revocation/crl.d.ts +2 -3
  99. package/dist/revocation/crl.js +319 -319
  100. package/dist/revocation/crl.js.map +1 -1
  101. package/dist/revocation/ocsp.d.ts +2 -3
  102. package/dist/revocation/ocsp.js +395 -395
  103. package/dist/revocation/revocation.d.ts +2 -3
  104. package/dist/revocation/revocation.js +22 -22
  105. package/dist/revocation.d.ts +12 -3
  106. package/dist/revocation.js +4 -4
  107. package/dist/ssh/ssh.d.ts +2 -3
  108. package/dist/ssh/ssh.js +165 -170
  109. package/dist/ssh/ssh.js.map +1 -1
  110. package/dist/ssh/wire.d.ts +1 -2
  111. package/dist/ssh/wire.js +10 -10
  112. package/dist/ssh.d.ts +8 -0
  113. package/dist/verify/identity.d.ts +1 -2
  114. package/dist/verify/identity.js +31 -31
  115. package/dist/verify/name-constraints.d.ts +9 -2
  116. package/dist/verify/policy.d.ts +9 -2
  117. package/dist/verify/verify.d.ts +3 -4
  118. package/dist/verify/verify.js +121 -121
  119. package/dist/verify.d.ts +9 -0
  120. package/dist/x509/certificate.d.ts +4 -5
  121. package/dist/x509/certificate.js +40 -40
  122. package/dist/x509/csr.d.ts +3 -4
  123. package/dist/x509/csr.js +15 -15
  124. package/dist/x509/extensions.d.ts +1 -2
  125. package/dist/x509/extensions.js +165 -165
  126. package/dist/x509/extensions.js.map +1 -1
  127. package/dist/x509/fingerprint.d.ts +1 -2
  128. package/dist/x509/name-text.d.ts +1 -2
  129. package/dist/x509/name.d.ts +1 -2
  130. package/dist/x509/name.js +15 -15
  131. package/dist/x509/parse.d.ts +3 -4
  132. package/dist/x509/parse.js +423 -423
  133. package/dist/x509.d.ts +17 -4
  134. package/dist/x509.js +8 -8
  135. package/package.json +27 -34
  136. package/dist/internal/asn1/oids2.js +0 -75
  137. package/dist/internal/asn1/oids2.js.map +0 -1
@@ -12,7 +12,7 @@ function uintInRange(e, t, n) {
12
12
  return Number.isSafeInteger(e) && e >= t && e <= n;
13
13
  }
14
14
  function validate(e, t) {
15
- if (e.algorithm !== "argon2id" && e.algorithm !== "argon2d") return failure("unsupported", "Unsupported Argon2 variant");
15
+ if (e.algorithm !== "argon2id" && e.algorithm !== "argon2d" && e.algorithm !== "argon2i") return failure("unsupported", "Unsupported Argon2 variant");
16
16
  if (e.version !== 16 && e.version !== 19) return failure("unsupported", "Unsupported Argon2 version");
17
17
  if (!uintInRange(e.parallelism, 1, 16777215) || !uintInRange(e.memoryKiB, 8 * e.parallelism, 4294967295) || !uintInRange(e.passes, 1, 4294967295) || !uintInRange(e.outputBytes, 4, 4294967295)) return failure("invalid_parameters", "Invalid Argon2 numeric parameters");
18
18
  let n = [
@@ -82,16 +82,25 @@ async function nativeArgon2(e) {
82
82
  case "argon2d":
83
83
  n = "Argon2d";
84
84
  break;
85
+ case "argon2i":
86
+ n = "Argon2i";
87
+ break;
85
88
  default: return failure("unsupported", "Unsupported Argon2 variant");
86
89
  }
87
90
  try {
88
- let r = await Reflect.apply(t.importKey, t, [
89
- "raw-secret",
90
- e.password,
91
- n,
92
- !1,
93
- ["deriveBits"]
94
- ]);
91
+ let r;
92
+ try {
93
+ r = await Reflect.apply(t.importKey, t, [
94
+ "raw-secret",
95
+ e.password,
96
+ n,
97
+ !1,
98
+ ["deriveBits"]
99
+ ]);
100
+ } catch (e) {
101
+ if (e instanceof TypeError) return failure("unsupported", "This runtime does not support the raw-secret key format");
102
+ throw e;
103
+ }
95
104
  if (typeof CryptoKey > "u" || !(r instanceof CryptoKey)) return failure("derivation_failed", "Native Argon2 returned an invalid key");
96
105
  let i = {
97
106
  name: n,
@@ -116,18 +125,28 @@ async function nativeArgon2(e) {
116
125
  return e instanceof Error && e.name === "NotSupportedError" ? failure("unsupported", "This runtime does not support native Argon2") : failure("derivation_failed", "Native Argon2 derivation failed");
117
126
  }
118
127
  }
128
+ async function builtinArgon2(e, t) {
129
+ if (t !== "portable") {
130
+ let n = await nativeArgon2(e);
131
+ if (t === "native" || n.ok || n.error.code !== "unsupported") return n;
132
+ }
133
+ let { portableArgon2: n } = await import("./argon2-portable.js");
134
+ return n(e);
135
+ }
119
136
  /**
120
137
  * Derives raw Argon2 bytes after validating parameters and resource ceilings.
121
138
  *
122
- * The default native WebCrypto adapter implements version 0x13. Runtime support
123
- * is detected by the import/derive operations, without an extra trial derivation.
124
- * Supply an explicit backend for other environments or version 0x10. There is
125
- * no fallback between variants, versions, or implementations.
139
+ * Native WebCrypto is preferred for version 0x13. An unsupported request uses
140
+ * the TypeScript implementation for the exact variant and version, including
141
+ * 0x10. Other native failures are returned without retrying. Explicit
142
+ * backends never fall back. No algorithm, version, or parameter is substituted.
126
143
  *
127
144
  * Caller buffers are copied synchronously before the first await and never
128
145
  * modified. Owned temporary arrays are zeroed on completion. Native key storage
129
146
  * and runtime copies cannot be explicitly erased by JavaScript. The returned
130
147
  * output is caller-owned. Calls cannot cancel native work once dispatched.
148
+ * TypeScript work yields while filling memory blocks. Its private memory matrix
149
+ * is erased on completion or failure.
131
150
  * Limits apply per call, not to concurrent invocations.
132
151
  */
133
152
  async function deriveArgon2(e, t = {}) {
@@ -142,7 +161,7 @@ async function deriveArgon2(e, t = {}) {
142
161
  if (r !== void 0) return r;
143
162
  let i = copyInput(n);
144
163
  try {
145
- let e = await (t.backend ?? nativeArgon2)(i);
164
+ let e = typeof t.backend == "function" ? await t.backend(i) : await builtinArgon2(i, t.backend);
146
165
  if (!e.ok) {
147
166
  let t = e.error.code;
148
167
  return failure(t === "unsupported" || t === "limit_exceeded" || t === "invalid_parameters" ? t : "derivation_failed", "Argon2 backend could not derive the requested key");
@@ -1 +1 @@
1
- {"version":3,"file":"argon2.js","names":["value","min","max","input","inputs","bytes","bounds","limits","sum","maximum","actual","secret","associatedData","subtle","name","key","params","output","error","snapshot","invalid","options","owned","result","code"],"sources":["../../src/kdf/argon2.ts"],"sourcesContent":["/**\n * Argon2 adapter and resource-policy boundary. The default backend uses native\n * WebCrypto, with no algorithm fallback or portable implementation bundled.\n *\n * @module\n */\n\nimport type { Micro509Error, Result } from '#micro509/result/result';\n\n/** Argon2id for new uses, or Argon2d for compatibility with existing formats. */\nexport type Argon2Algorithm = 'argon2id' | 'argon2d';\n\n/** Argon2 versions used by KDBX. The native backend supports only 0x13. */\nexport type Argon2Version = 0x10 | 0x13;\n\n/** Exact derivation inputs. Password encoding and format preprocessing belong to the caller. */\nexport interface Argon2Input {\n\t/** Select Argon2id for new applications. */\n\treadonly algorithm: Argon2Algorithm;\n\t/** Exact version. No version substitution is performed. */\n\treadonly version: Argon2Version;\n\t/** Password or format-preprocessed input bytes. */\n\treadonly password: Uint8Array;\n\t/** Salt bytes. The native backend requires at least eight bytes. */\n\treadonly salt: Uint8Array;\n\t/** Total memory in kibibytes, at least eight times parallelism. */\n\treadonly memoryKiB: number;\n\t/** Number of full passes through memory. */\n\treadonly passes: number;\n\t/** Number of lanes. */\n\treadonly parallelism: number;\n\t/** Requested output length in bytes, at least four. */\n\treadonly outputBytes: number;\n\t/** Optional secret input, separate from the password. */\n\treadonly secret?: Uint8Array;\n\t/** Optional associated data included in the derivation. */\n\treadonly associatedData?: Uint8Array;\n}\n\n/** Per-invocation ceilings, checked before copying inputs or calling the backend. */\nexport interface Argon2Limits {\n\t/** Memory ceiling in KiB. Default: 262144 (256 MiB). */\n\treadonly maxMemoryKiB?: number;\n\t/** Pass ceiling. Default: 16. */\n\treadonly maxPasses?: number;\n\t/** Lane ceiling. Default: 16. */\n\treadonly maxParallelism?: number;\n\t/** Output-byte ceiling. Default: 1024. */\n\treadonly maxOutputBytes?: number;\n\t/** Sum of password, salt, secret, and associated-data lengths. Default: 1048576. */\n\treadonly maxInputBytes?: number;\n}\n\n/** Stable failures without password, salt, or backend exception content. */\nexport type Argon2ErrorCode =\n\t| 'invalid_parameters'\n\t| 'limit_exceeded'\n\t| 'unsupported'\n\t| 'derivation_failed';\n\n/** Derived bytes or a typed error. Successful output belongs to the caller. */\nexport type Argon2Result = Result<Uint8Array, Micro509Error<Argon2ErrorCode>>;\n\n/**\n * Trusted, explicitly supplied implementation for the exact requested algorithm\n * and version. Called only after parameter and resource checks. Input arrays are\n * private copies, wiped when the promise settles. A backend that transfers an input\n * buffer must erase it in the receiving worker. Transfer ownership of output\n * bytes to the caller: the wrapper copies and wipes that array before returning.\n * Report unsupported requests explicitly, without fallback. Execution behavior\n * and cancellation of a custom backend are its provider's responsibility.\n */\nexport type Argon2Backend = (input: Argon2Input) => Promise<Argon2Result>;\n\n/** Resource policy and optional external implementation for {@linkcode deriveArgon2}. */\nexport interface Argon2Options {\n\t/** Per-call ceilings. Applications must separately bound concurrent calls. */\n\treadonly limits?: Argon2Limits;\n\t/** Explicit trusted backend. Omit to use native WebCrypto version 0x13. */\n\treadonly backend?: Argon2Backend;\n}\n\nfunction failure(code: Argon2ErrorCode, message: string): Argon2Result {\n\treturn { ok: false, error: { code, message } };\n}\n\nfunction uintInRange(value: number, min: number, max: number): boolean {\n\treturn Number.isSafeInteger(value) && value >= min && value <= max;\n}\n\nfunction validate(input: Argon2Input, limits: Argon2Limits): Argon2Result | undefined {\n\tif (input.algorithm !== 'argon2id' && input.algorithm !== 'argon2d') {\n\t\treturn failure('unsupported', 'Unsupported Argon2 variant');\n\t}\n\tif (input.version !== 0x10 && input.version !== 0x13) {\n\t\treturn failure('unsupported', 'Unsupported Argon2 version');\n\t}\n\t// RFC 9106 section 3.1. Memory is passed exactly, including values not\n\t// divisible by 4*p: rounding the input would change the initial hash.\n\tif (\n\t\t!uintInRange(input.parallelism, 1, 0xffffff) ||\n\t\t!uintInRange(input.memoryKiB, 8 * input.parallelism, 0xffffffff) ||\n\t\t!uintInRange(input.passes, 1, 0xffffffff) ||\n\t\t!uintInRange(input.outputBytes, 4, 0xffffffff)\n\t) {\n\t\treturn failure('invalid_parameters', 'Invalid Argon2 numeric parameters');\n\t}\n\tconst inputs = [input.password, input.salt, input.secret, input.associatedData];\n\tif (\n\t\t!(input.password instanceof Uint8Array) ||\n\t\t!(input.salt instanceof Uint8Array) ||\n\t\tinputs.some((bytes) => bytes !== undefined && !(bytes instanceof Uint8Array))\n\t) {\n\t\treturn failure('invalid_parameters', 'Argon2 inputs must be Uint8Array values');\n\t}\n\ttry {\n\t\t// A detached or out-of-bounds view reports zero length. Validate its\n\t\t// backing store before copying any of the caller's secret material.\n\t\tfor (const bytes of inputs) {\n\t\t\tif (bytes !== undefined) Uint8Array.prototype.values.call(bytes);\n\t\t}\n\t} catch {\n\t\treturn failure('invalid_parameters', 'Argon2 input buffer is unavailable');\n\t}\n\tconst bounds = [\n\t\t[input.memoryKiB, limits.maxMemoryKiB ?? 262144],\n\t\t[input.passes, limits.maxPasses ?? 16],\n\t\t[input.parallelism, limits.maxParallelism ?? 16],\n\t\t[input.outputBytes, limits.maxOutputBytes ?? 1024],\n\t\t[\n\t\t\tinputs.reduce((sum, bytes) => sum + (bytes?.byteLength ?? 0), 0),\n\t\t\tlimits.maxInputBytes ?? 1048576,\n\t\t],\n\t] as const;\n\tif (bounds.some(([, maximum]) => !uintInRange(maximum, 1, 0xffffffff))) {\n\t\treturn failure('invalid_parameters', 'Argon2 resource limits must be positive uint32 values');\n\t}\n\tif (bounds.some(([actual, maximum]) => actual > maximum)) {\n\t\treturn failure('limit_exceeded', 'Argon2 request exceeds resource limits');\n\t}\n\treturn undefined;\n}\n\nfunction snapshotInput(input: Argon2Input): Argon2Input {\n\t// Read declared properties once, including inherited and non-enumerable ones.\n\t// Byte arrays remain references until validation has enforced resource bounds.\n\tconst {\n\t\talgorithm,\n\t\tversion,\n\t\tpassword,\n\t\tsalt,\n\t\tmemoryKiB,\n\t\tpasses,\n\t\tparallelism,\n\t\toutputBytes,\n\t\tsecret,\n\t\tassociatedData,\n\t} = input;\n\treturn {\n\t\talgorithm,\n\t\tversion,\n\t\tpassword,\n\t\tsalt,\n\t\tmemoryKiB,\n\t\tpasses,\n\t\tparallelism,\n\t\toutputBytes,\n\t\t...(secret === undefined ? {} : { secret }),\n\t\t...(associatedData === undefined ? {} : { associatedData }),\n\t};\n}\n\nfunction copyInput(input: Argon2Input): Argon2Input {\n\treturn {\n\t\talgorithm: input.algorithm,\n\t\tversion: input.version,\n\t\tmemoryKiB: input.memoryKiB,\n\t\tpasses: input.passes,\n\t\tparallelism: input.parallelism,\n\t\toutputBytes: input.outputBytes,\n\t\tpassword: new Uint8Array(input.password),\n\t\tsalt: new Uint8Array(input.salt),\n\t\t...(input.secret === undefined ? {} : { secret: new Uint8Array(input.secret) }),\n\t\t...(input.associatedData === undefined\n\t\t\t? {}\n\t\t\t: { associatedData: new Uint8Array(input.associatedData) }),\n\t};\n}\n\nfunction eraseAccessible(bytes: Uint8Array | undefined): void {\n\t// Transfer detaches the sender's view. Its bytes can only be erased by the\n\t// receiving worker, and cleanup must still proceed through the other inputs.\n\tif (bytes !== undefined && bytes.byteLength > 0) Uint8Array.prototype.fill.call(bytes, 0);\n}\n\nasync function nativeArgon2(input: Argon2Input): Promise<Argon2Result> {\n\tif (input.version !== 0x13) {\n\t\treturn failure('unsupported', 'Native Argon2 supports version 0x13 only');\n\t}\n\tif (input.salt.byteLength < 8) {\n\t\treturn failure('unsupported', 'Native Argon2 requires a salt of at least eight bytes');\n\t}\n\tif (input.outputBytes > Math.floor(0xffffffff / 8)) {\n\t\treturn failure('unsupported', 'Requested output exceeds the native WebCrypto bit-length range');\n\t}\n\tif (typeof globalThis.crypto?.subtle === 'undefined') {\n\t\treturn failure('unsupported', 'Native WebCrypto is unavailable');\n\t}\n\tconst subtle = globalThis.crypto.subtle;\n\tlet name: 'Argon2id' | 'Argon2d';\n\tswitch (input.algorithm) {\n\t\tcase 'argon2id':\n\t\t\tname = 'Argon2id';\n\t\t\tbreak;\n\t\tcase 'argon2d':\n\t\t\tname = 'Argon2d';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn failure('unsupported', 'Unsupported Argon2 variant');\n\t}\n\ttry {\n\t\t// raw-secret is a runtime WebCrypto extension not present in every DOM\n\t\t// declaration. The result is narrowed rather than asserted or globally\n\t\t// augmenting consumers' SubtleCrypto definitions.\n\t\tconst key: unknown = await Reflect.apply(subtle.importKey, subtle, [\n\t\t\t'raw-secret',\n\t\t\tinput.password,\n\t\t\tname,\n\t\t\tfalse,\n\t\t\t['deriveBits'],\n\t\t]);\n\t\tif (typeof CryptoKey === 'undefined' || !(key instanceof CryptoKey)) {\n\t\t\treturn failure('derivation_failed', 'Native Argon2 returned an invalid key');\n\t\t}\n\t\tconst params = {\n\t\t\tname,\n\t\t\tversion: input.version,\n\t\t\tmemory: input.memoryKiB,\n\t\t\tpasses: input.passes,\n\t\t\tparallelism: input.parallelism,\n\t\t\tnonce: new Uint8Array(input.salt),\n\t\t\t...(input.secret === undefined ? {} : { secretValue: new Uint8Array(input.secret) }),\n\t\t\t...(input.associatedData === undefined\n\t\t\t\t? {}\n\t\t\t\t: { associatedData: new Uint8Array(input.associatedData) }),\n\t\t};\n\t\ttry {\n\t\t\tconst output = await subtle.deriveBits(params, key, input.outputBytes * 8);\n\t\t\treturn { ok: true, value: new Uint8Array(output) };\n\t\t} finally {\n\t\t\tparams.nonce.fill(0);\n\t\t\tparams.secretValue?.fill(0);\n\t\t\tparams.associatedData?.fill(0);\n\t\t}\n\t} catch (error) {\n\t\treturn error instanceof Error && error.name === 'NotSupportedError'\n\t\t\t? failure('unsupported', 'This runtime does not support native Argon2')\n\t\t\t: failure('derivation_failed', 'Native Argon2 derivation failed');\n\t}\n}\n\n/**\n * Derives raw Argon2 bytes after validating parameters and resource ceilings.\n *\n * The default native WebCrypto adapter implements version 0x13. Runtime support\n * is detected by the import/derive operations, without an extra trial derivation.\n * Supply an explicit backend for other environments or version 0x10. There is\n * no fallback between variants, versions, or implementations.\n *\n * Caller buffers are copied synchronously before the first await and never\n * modified. Owned temporary arrays are zeroed on completion. Native key storage\n * and runtime copies cannot be explicitly erased by JavaScript. The returned\n * output is caller-owned. Calls cannot cancel native work once dispatched.\n * Limits apply per call, not to concurrent invocations.\n */\nexport async function deriveArgon2(\n\tinput: Argon2Input,\n\toptions: Argon2Options = {},\n): Promise<Argon2Result> {\n\tif (input === null || typeof input !== 'object') {\n\t\treturn failure('invalid_parameters', 'Argon2 input must be an object');\n\t}\n\tlet snapshot: Argon2Input;\n\ttry {\n\t\tsnapshot = snapshotInput(input);\n\t} catch {\n\t\treturn failure('invalid_parameters', 'Argon2 input properties could not be read');\n\t}\n\tconst invalid = validate(snapshot, options.limits ?? {});\n\tif (invalid !== undefined) return invalid;\n\tconst owned = copyInput(snapshot);\n\ttry {\n\t\tconst result = await (options.backend ?? nativeArgon2)(owned);\n\t\tif (!result.ok) {\n\t\t\t// A custom provider's diagnostic may contain secrets. Return only the\n\t\t\t// recognized code and a fixed message at this public boundary.\n\t\t\tconst code = result.error.code;\n\t\t\treturn failure(\n\t\t\t\tcode === 'unsupported' || code === 'limit_exceeded' || code === 'invalid_parameters'\n\t\t\t\t\t? code\n\t\t\t\t\t: 'derivation_failed',\n\t\t\t\t'Argon2 backend could not derive the requested key',\n\t\t\t);\n\t\t}\n\t\tif (!(result.value instanceof Uint8Array)) {\n\t\t\treturn failure('derivation_failed', 'Argon2 backend returned invalid output');\n\t\t}\n\t\ttry {\n\t\t\treturn result.value.byteLength === owned.outputBytes\n\t\t\t\t? { ok: true, value: new Uint8Array(result.value) }\n\t\t\t\t: failure('derivation_failed', 'Argon2 backend returned an incorrect output length');\n\t\t} finally {\n\t\t\teraseAccessible(result.value);\n\t\t}\n\t} catch {\n\t\treturn failure('derivation_failed', 'Argon2 backend failed');\n\t} finally {\n\t\teraseAccessible(owned.password);\n\t\teraseAccessible(owned.salt);\n\t\teraseAccessible(owned.secret);\n\t\teraseAccessible(owned.associatedData);\n\t}\n}\n"],"mappings":";AAkFA,SAAS,QAAQ,GAAuB,GAA+B;CACtE,OAAO;EAAE,IAAI;EAAO,OAAO;GAAE;GAAM;EAAQ;CAAE;AAC9C;AAEA,SAAS,YAAY,GAAe,GAAa,GAAsB;CACtE,OAAO,OAAO,cAAcA,CAAK,KAAKA,KAASC,KAAOD,KAASE;AAChE;AAEA,SAAS,SAAS,GAAoB,GAAgD;CACrF,IAAIC,EAAM,cAAc,cAAcA,EAAM,cAAc,WACzD,OAAO,QAAQ,eAAe,4BAA4B;CAE3D,IAAIA,EAAM,YAAY,MAAQA,EAAM,YAAY,IAC/C,OAAO,QAAQ,eAAe,4BAA4B;CAI3D,IACC,CAAC,YAAYA,EAAM,aAAa,GAAG,QAAQ,KAC3C,CAAC,YAAYA,EAAM,WAAW,IAAIA,EAAM,aAAa,UAAU,KAC/D,CAAC,YAAYA,EAAM,QAAQ,GAAG,UAAU,KACxC,CAAC,YAAYA,EAAM,aAAa,GAAG,UAAU,GAE7C,OAAO,QAAQ,sBAAsB,mCAAmC;CAEzE,IAAMC,IAAS;EAACD,EAAM;EAAUA,EAAM;EAAMA,EAAM;EAAQA,EAAM;CAAc;CAC9E,IACC,EAAEA,EAAM,oBAAoB,eAC5B,EAAEA,EAAM,gBAAgB,eACxBC,EAAO,MAAM,MAAUC,MAAU,KAAA,KAAa,EAAEA,aAAiB,WAAW,GAE5E,OAAO,QAAQ,sBAAsB,yCAAyC;CAE/E,IAAI;EAGH,KAAK,IAAMA,KAASD,GACnB,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QAAQ,qBAAqB,uBAAuB;CAC5D,UAAU;EAIT,AAHA,gBAAgBD,EAAM,QAAQ,GAC9B,gBAAgBA,EAAM,IAAI,GAC1B,gBAAgBA,EAAM,MAAM,GAC5B,gBAAgBA,EAAM,cAAc;CACrC;AACD"}
1
+ {"version":3,"file":"argon2.js","names":["value","min","max","input","inputs","bytes","bounds","limits","sum","maximum","actual","secret","associatedData","subtle","name","key","error","params","output","backend","result","portableArgon2","snapshot","invalid","options","owned","code"],"sources":["../../src/kdf/argon2.ts"],"sourcesContent":["/**\n * Argon2 derivation and resource-policy boundary. The default backend prefers\n * native WebCrypto and uses the TypeScript implementation when unsupported.\n *\n * @module\n */\n\nimport type { Micro509Error, Result } from '#micro509/result/result';\n\n/** RFC 9106 Argon2 variants. Use Argon2id for new password-based applications. */\nexport type Argon2Algorithm = 'argon2d' | 'argon2i' | 'argon2id';\n\n/** Argon2 versions used by KDBX. The native backend supports only 0x13. */\nexport type Argon2Version = 0x10 | 0x13;\n\n/** Exact derivation inputs. Password encoding and format preprocessing belong to the caller. */\nexport interface Argon2Input {\n\t/** Select Argon2id for new applications. */\n\treadonly algorithm: Argon2Algorithm;\n\t/** Exact version. No version substitution is performed. */\n\treadonly version: Argon2Version;\n\t/** Password or format-preprocessed input bytes. */\n\treadonly password: Uint8Array;\n\t/** Salt bytes. RFC 9106 recommends 16 bytes; the native backend requires at least eight. */\n\treadonly salt: Uint8Array;\n\t/** Total memory in kibibytes, at least eight times parallelism. */\n\treadonly memoryKiB: number;\n\t/** Number of full passes through memory. */\n\treadonly passes: number;\n\t/** Number of lanes. */\n\treadonly parallelism: number;\n\t/** Requested output length in bytes, at least four. */\n\treadonly outputBytes: number;\n\t/** Optional secret input, separate from the password. */\n\treadonly secret?: Uint8Array;\n\t/** Optional associated data included in the derivation. */\n\treadonly associatedData?: Uint8Array;\n}\n\n/** Per-invocation ceilings, checked before copying inputs or calling the backend. */\nexport interface Argon2Limits {\n\t/** Memory ceiling in KiB. Default: 262144 (256 MiB). */\n\treadonly maxMemoryKiB?: number;\n\t/** Pass ceiling. Default: 16. */\n\treadonly maxPasses?: number;\n\t/** Lane ceiling. Default: 16. */\n\treadonly maxParallelism?: number;\n\t/** Output-byte ceiling. Default: 1024. */\n\treadonly maxOutputBytes?: number;\n\t/** Sum of password, salt, secret, and associated-data lengths. Default: 1048576. */\n\treadonly maxInputBytes?: number;\n}\n\n/** Stable failures without password, salt, or backend exception content. */\nexport type Argon2ErrorCode =\n\t| 'invalid_parameters'\n\t| 'limit_exceeded'\n\t| 'unsupported'\n\t| 'derivation_failed';\n\n/** Derived bytes or a typed error. Successful output belongs to the caller. */\nexport type Argon2Result = Result<Uint8Array, Micro509Error<Argon2ErrorCode>>;\n\n/**\n * Trusted, explicitly supplied implementation for the exact requested algorithm\n * and version. Called only after parameter and resource checks. Input arrays are\n * private copies, wiped when the promise settles. A backend that transfers an input\n * buffer must erase it in the receiving worker. Transfer ownership of output\n * bytes to the caller: the wrapper copies and wipes that array before returning.\n * Report unsupported requests explicitly, without fallback. Execution behavior\n * and cancellation of a custom backend are its provider's responsibility.\n */\nexport type Argon2Backend = (input: Argon2Input) => Promise<Argon2Result>;\n\n/** Resource policy and optional external implementation for {@linkcode deriveArgon2}. */\nexport interface Argon2Options {\n\t/** Per-call ceilings. Applications must separately bound concurrent calls. */\n\treadonly limits?: Argon2Limits;\n\t/**\n\t * Omit to prefer native WebCrypto, then the TypeScript implementation on `unsupported` only.\n\t * Select `native` or `portable` to require that implementation, or supply a\n\t * trusted callback. Explicit selections never fall back to another backend.\n\t */\n\treadonly backend?: Argon2Backend | 'native' | 'portable';\n}\n\nfunction failure(code: Argon2ErrorCode, message: string): Argon2Result {\n\treturn { ok: false, error: { code, message } };\n}\n\nfunction uintInRange(value: number, min: number, max: number): boolean {\n\treturn Number.isSafeInteger(value) && value >= min && value <= max;\n}\n\nfunction validate(input: Argon2Input, limits: Argon2Limits): Argon2Result | undefined {\n\tif (\n\t\tinput.algorithm !== 'argon2id' &&\n\t\tinput.algorithm !== 'argon2d' &&\n\t\tinput.algorithm !== 'argon2i'\n\t) {\n\t\treturn failure('unsupported', 'Unsupported Argon2 variant');\n\t}\n\tif (input.version !== 0x10 && input.version !== 0x13) {\n\t\treturn failure('unsupported', 'Unsupported Argon2 version');\n\t}\n\t// RFC 9106 section 3.1. Memory is passed exactly, including values not\n\t// divisible by 4*p: rounding the input would change the initial hash.\n\tif (\n\t\t!uintInRange(input.parallelism, 1, 0xffffff) ||\n\t\t!uintInRange(input.memoryKiB, 8 * input.parallelism, 0xffffffff) ||\n\t\t!uintInRange(input.passes, 1, 0xffffffff) ||\n\t\t!uintInRange(input.outputBytes, 4, 0xffffffff)\n\t) {\n\t\treturn failure('invalid_parameters', 'Invalid Argon2 numeric parameters');\n\t}\n\tconst inputs = [input.password, input.salt, input.secret, input.associatedData];\n\tif (\n\t\t!(input.password instanceof Uint8Array) ||\n\t\t!(input.salt instanceof Uint8Array) ||\n\t\tinputs.some((bytes) => bytes !== undefined && !(bytes instanceof Uint8Array))\n\t) {\n\t\treturn failure('invalid_parameters', 'Argon2 inputs must be Uint8Array values');\n\t}\n\ttry {\n\t\t// A detached or out-of-bounds view reports zero length. Validate its\n\t\t// backing store before copying any of the caller's secret material.\n\t\tfor (const bytes of inputs) {\n\t\t\tif (bytes !== undefined) Uint8Array.prototype.values.call(bytes);\n\t\t}\n\t} catch {\n\t\treturn failure('invalid_parameters', 'Argon2 input buffer is unavailable');\n\t}\n\tconst bounds = [\n\t\t[input.memoryKiB, limits.maxMemoryKiB ?? 262144],\n\t\t[input.passes, limits.maxPasses ?? 16],\n\t\t[input.parallelism, limits.maxParallelism ?? 16],\n\t\t[input.outputBytes, limits.maxOutputBytes ?? 1024],\n\t\t[\n\t\t\tinputs.reduce((sum, bytes) => sum + (bytes?.byteLength ?? 0), 0),\n\t\t\tlimits.maxInputBytes ?? 1048576,\n\t\t],\n\t] as const;\n\tif (bounds.some(([, maximum]) => !uintInRange(maximum, 1, 0xffffffff))) {\n\t\treturn failure('invalid_parameters', 'Argon2 resource limits must be positive uint32 values');\n\t}\n\tif (bounds.some(([actual, maximum]) => actual > maximum)) {\n\t\treturn failure('limit_exceeded', 'Argon2 request exceeds resource limits');\n\t}\n\treturn undefined;\n}\n\nfunction snapshotInput(input: Argon2Input): Argon2Input {\n\t// Read declared properties once, including inherited and non-enumerable ones.\n\t// Byte arrays remain references until validation has enforced resource bounds.\n\tconst {\n\t\talgorithm,\n\t\tversion,\n\t\tpassword,\n\t\tsalt,\n\t\tmemoryKiB,\n\t\tpasses,\n\t\tparallelism,\n\t\toutputBytes,\n\t\tsecret,\n\t\tassociatedData,\n\t} = input;\n\treturn {\n\t\talgorithm,\n\t\tversion,\n\t\tpassword,\n\t\tsalt,\n\t\tmemoryKiB,\n\t\tpasses,\n\t\tparallelism,\n\t\toutputBytes,\n\t\t...(secret === undefined ? {} : { secret }),\n\t\t...(associatedData === undefined ? {} : { associatedData }),\n\t};\n}\n\nfunction copyInput(input: Argon2Input): Argon2Input {\n\treturn {\n\t\talgorithm: input.algorithm,\n\t\tversion: input.version,\n\t\tmemoryKiB: input.memoryKiB,\n\t\tpasses: input.passes,\n\t\tparallelism: input.parallelism,\n\t\toutputBytes: input.outputBytes,\n\t\tpassword: new Uint8Array(input.password),\n\t\tsalt: new Uint8Array(input.salt),\n\t\t...(input.secret === undefined ? {} : { secret: new Uint8Array(input.secret) }),\n\t\t...(input.associatedData === undefined\n\t\t\t? {}\n\t\t\t: { associatedData: new Uint8Array(input.associatedData) }),\n\t};\n}\n\nfunction eraseAccessible(bytes: Uint8Array | undefined): void {\n\t// Transfer detaches the sender's view. Its bytes can only be erased by the\n\t// receiving worker, and cleanup must still proceed through the other inputs.\n\tif (bytes !== undefined && bytes.byteLength > 0) Uint8Array.prototype.fill.call(bytes, 0);\n}\n\nasync function nativeArgon2(input: Argon2Input): Promise<Argon2Result> {\n\tif (input.version !== 0x13) {\n\t\treturn failure('unsupported', 'Native Argon2 supports version 0x13 only');\n\t}\n\tif (input.salt.byteLength < 8) {\n\t\treturn failure('unsupported', 'Native Argon2 requires a salt of at least eight bytes');\n\t}\n\tif (input.outputBytes > Math.floor(0xffffffff / 8)) {\n\t\treturn failure('unsupported', 'Requested output exceeds the native WebCrypto bit-length range');\n\t}\n\tif (typeof globalThis.crypto?.subtle === 'undefined') {\n\t\treturn failure('unsupported', 'Native WebCrypto is unavailable');\n\t}\n\tconst subtle = globalThis.crypto.subtle;\n\tlet name: 'Argon2d' | 'Argon2i' | 'Argon2id';\n\tswitch (input.algorithm) {\n\t\tcase 'argon2id':\n\t\t\tname = 'Argon2id';\n\t\t\tbreak;\n\t\tcase 'argon2d':\n\t\t\tname = 'Argon2d';\n\t\t\tbreak;\n\t\tcase 'argon2i':\n\t\t\tname = 'Argon2i';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\treturn failure('unsupported', 'Unsupported Argon2 variant');\n\t}\n\ttry {\n\t\t// raw-secret is a runtime WebCrypto extension not present in every DOM\n\t\t// declaration. The result is narrowed rather than asserted or globally\n\t\t// augmenting consumers' SubtleCrypto definitions.\n\t\tlet key: unknown;\n\t\ttry {\n\t\t\tkey = await Reflect.apply(subtle.importKey, subtle, [\n\t\t\t\t'raw-secret',\n\t\t\t\tinput.password,\n\t\t\t\tname,\n\t\t\t\tfalse,\n\t\t\t\t['deriveBits'],\n\t\t\t]);\n\t\t} catch (error) {\n\t\t\t// Older WebCrypto KeyFormat enums reject raw-secret with TypeError.\n\t\t\t// Keep this classification local to import; deriveBits failures stay failures.\n\t\t\tif (error instanceof TypeError) {\n\t\t\t\treturn failure('unsupported', 'This runtime does not support the raw-secret key format');\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t\tif (typeof CryptoKey === 'undefined' || !(key instanceof CryptoKey)) {\n\t\t\treturn failure('derivation_failed', 'Native Argon2 returned an invalid key');\n\t\t}\n\t\tconst params = {\n\t\t\tname,\n\t\t\tversion: input.version,\n\t\t\tmemory: input.memoryKiB,\n\t\t\tpasses: input.passes,\n\t\t\tparallelism: input.parallelism,\n\t\t\tnonce: new Uint8Array(input.salt),\n\t\t\t...(input.secret === undefined ? {} : { secretValue: new Uint8Array(input.secret) }),\n\t\t\t...(input.associatedData === undefined\n\t\t\t\t? {}\n\t\t\t\t: { associatedData: new Uint8Array(input.associatedData) }),\n\t\t};\n\t\ttry {\n\t\t\tconst output = await subtle.deriveBits(params, key, input.outputBytes * 8);\n\t\t\treturn { ok: true, value: new Uint8Array(output) };\n\t\t} finally {\n\t\t\tparams.nonce.fill(0);\n\t\t\tparams.secretValue?.fill(0);\n\t\t\tparams.associatedData?.fill(0);\n\t\t}\n\t} catch (error) {\n\t\treturn error instanceof Error && error.name === 'NotSupportedError'\n\t\t\t? failure('unsupported', 'This runtime does not support native Argon2')\n\t\t\t: failure('derivation_failed', 'Native Argon2 derivation failed');\n\t}\n}\n\nasync function builtinArgon2(\n\tinput: Argon2Input,\n\tbackend: 'native' | 'portable' | undefined,\n): Promise<Argon2Result> {\n\tif (backend !== 'portable') {\n\t\tconst result = await nativeArgon2(input);\n\t\tif (backend === 'native' || result.ok || result.error.code !== 'unsupported') return result;\n\t}\n\tconst { portableArgon2 } = await import('#micro509/kdf/argon2-portable');\n\treturn portableArgon2(input);\n}\n\n/**\n * Derives raw Argon2 bytes after validating parameters and resource ceilings.\n *\n * Native WebCrypto is preferred for version 0x13. An unsupported request uses\n * the TypeScript implementation for the exact variant and version, including\n * 0x10. Other native failures are returned without retrying. Explicit\n * backends never fall back. No algorithm, version, or parameter is substituted.\n *\n * Caller buffers are copied synchronously before the first await and never\n * modified. Owned temporary arrays are zeroed on completion. Native key storage\n * and runtime copies cannot be explicitly erased by JavaScript. The returned\n * output is caller-owned. Calls cannot cancel native work once dispatched.\n * TypeScript work yields while filling memory blocks. Its private memory matrix\n * is erased on completion or failure.\n * Limits apply per call, not to concurrent invocations.\n */\nexport async function deriveArgon2(\n\tinput: Argon2Input,\n\toptions: Argon2Options = {},\n): Promise<Argon2Result> {\n\tif (input === null || typeof input !== 'object') {\n\t\treturn failure('invalid_parameters', 'Argon2 input must be an object');\n\t}\n\tlet snapshot: Argon2Input;\n\ttry {\n\t\tsnapshot = snapshotInput(input);\n\t} catch {\n\t\treturn failure('invalid_parameters', 'Argon2 input properties could not be read');\n\t}\n\tconst invalid = validate(snapshot, options.limits ?? {});\n\tif (invalid !== undefined) return invalid;\n\tconst owned = copyInput(snapshot);\n\ttry {\n\t\tconst result =\n\t\t\ttypeof options.backend === 'function'\n\t\t\t\t? await options.backend(owned)\n\t\t\t\t: await builtinArgon2(owned, options.backend);\n\t\tif (!result.ok) {\n\t\t\t// A custom provider's diagnostic may contain secrets. Return only the\n\t\t\t// recognized code and a fixed message at this public boundary.\n\t\t\tconst code = result.error.code;\n\t\t\treturn failure(\n\t\t\t\tcode === 'unsupported' || code === 'limit_exceeded' || code === 'invalid_parameters'\n\t\t\t\t\t? code\n\t\t\t\t\t: 'derivation_failed',\n\t\t\t\t'Argon2 backend could not derive the requested key',\n\t\t\t);\n\t\t}\n\t\tif (!(result.value instanceof Uint8Array)) {\n\t\t\treturn failure('derivation_failed', 'Argon2 backend returned invalid output');\n\t\t}\n\t\ttry {\n\t\t\treturn result.value.byteLength === owned.outputBytes\n\t\t\t\t? { ok: true, value: new Uint8Array(result.value) }\n\t\t\t\t: failure('derivation_failed', 'Argon2 backend returned an incorrect output length');\n\t\t} finally {\n\t\t\teraseAccessible(result.value);\n\t\t}\n\t} catch {\n\t\treturn failure('derivation_failed', 'Argon2 backend failed');\n\t} finally {\n\t\teraseAccessible(owned.password);\n\t\teraseAccessible(owned.salt);\n\t\teraseAccessible(owned.secret);\n\t\teraseAccessible(owned.associatedData);\n\t}\n}\n"],"mappings":";AAsFA,SAAS,QAAQ,GAAuB,GAA+B;CACtE,OAAO;EAAE,IAAI;EAAO,OAAO;GAAE;GAAM;EAAQ;CAAE;AAC9C;AAEA,SAAS,YAAY,GAAe,GAAa,GAAsB;CACtE,OAAO,OAAO,cAAcA,CAAK,KA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T,AAHA,gBAAgBK,EAAM,QAAQ,GAC9B,gBAAgBA,EAAM,IAAI,GAC1B,gBAAgBA,EAAM,MAAM,GAC5B,gBAAgBA,EAAM,cAAc;CACrC;AACD"}
package/dist/kdf.d.ts CHANGED
@@ -1,2 +1,8 @@
1
+ /**
2
+ * Optional byte-oriented Argon2 key derivation with explicit resource limits.
3
+ * Import this entrypoint directly. Certificate APIs do not load it.
4
+ *
5
+ * @module micro509/kdf
6
+ */
1
7
  import { Argon2Algorithm, Argon2Backend, Argon2ErrorCode, Argon2Input, Argon2Limits, Argon2Options, Argon2Result, Argon2Version, deriveArgon2 } from "./kdf/argon2.js";
2
8
  export { type Argon2Algorithm, type Argon2Backend, type Argon2ErrorCode, type Argon2Input, type Argon2Limits, type Argon2Options, type Argon2Result, type Argon2Version, deriveArgon2 };
@@ -121,8 +121,21 @@ export interface LegacyPemEncryptionOptions {
121
121
  * or DER nested deeper than 64 levels.
122
122
  */
123
123
  export type ImportKeyErrorCode = Exclude<DecodeFailureCode, "unsupported">;
124
+ /** Stage at which an ordinary key import refused input. */
125
+ export type ImportKeyStage = "container" | "pem" | "base64" | "asn1" | "algorithm" | "backend";
126
+ /** Stable diagnostic independent of human-readable messages and native backend errors. */
127
+ export type ImportKeyReason = "unsupported_container" | "multiple_blocks" | "encrypted_key" | "invalid_armor" | "invalid_base64" | "invalid_asn1" | "decode_limit" | "unsupported_algorithm" | "algorithm_mismatch" | "public_key_mismatch" | "backend_rejected";
128
+ /** Safe structured context: names only, never input bytes, passwords or backend prose. */
129
+ export interface ImportKeyErrorDetails {
130
+ /** Stage that refused the input. */
131
+ readonly stage: ImportKeyStage;
132
+ /** Stable refusal reason within the stage. */
133
+ readonly reason: ImportKeyReason;
134
+ /** Container selected by the importer, when known. */
135
+ readonly container?: "pkcs8" | "pkcs1" | "sec1" | "spki" | "jwk";
136
+ }
124
137
  /** Structured failure payload for key import. */
125
- export interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {
138
+ export interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode, ImportKeyErrorDetails> {
126
139
  /** Always `false` for failures. */
127
140
  readonly ok: false;
128
141
  }
@@ -130,14 +143,14 @@ export interface ImportKeyFailure extends Micro509Error<ImportKeyErrorCode> {
130
143
  * Success-or-failure result returned by the public `import*` key functions.
131
144
  *
132
145
  * On failure, `code` is `'malformed'` for structurally invalid input,
133
- * algorithm mismatches, and wrong-password decryption failures alike (see the
134
- * throwing `*OrThrow` variants for raw error messages), and `'limit_exceeded'`
146
+ * algorithm mismatches and backend refusal. `details` provides a stable stage/reason
147
+ * through the Result and `*OrThrow`/`unwrap` forms, without backend messages. `'limit_exceeded'` is
135
148
  * for an implementation limit.
136
149
  */
137
150
  export type ImportKeyResult<T> = {
138
151
  readonly ok: true;
139
152
  readonly value: T;
140
- } | ErrorResult<ImportKeyErrorCode, Record<never, never>, ImportKeyFailure>;
153
+ } | ErrorResult<ImportKeyErrorCode, ImportKeyErrorDetails, ImportKeyFailure>;
141
154
  /**
142
155
  * Machine-readable failure reason for the `importEncrypted*` key functions.
143
156
  *
@@ -469,6 +482,19 @@ export declare function importSpkiPemOrThrow(pem: string, algorithm?: PublicKeyI
469
482
  * @see `importSpkiPemOrThrow` for the throwing variant
470
483
  */
471
484
  export declare function importSpkiPem(pem: string, algorithm?: PublicKeyImportInput): Promise<ImportKeyResult<CryptoKey>>;
485
+ /**
486
+ * Imports exactly one unencrypted private-key PEM block by its label: PKCS#8 `PRIVATE KEY`,
487
+ * PKCS#1 `RSA PRIVATE KEY`, or SEC1 `EC PRIVATE KEY`. Bundles (including a certificate plus key)
488
+ * are refused rather than selecting an arbitrary block. Non-PEM surrounding text follows the
489
+ * shared PEM scanner's behavior. Encrypted PKCS#8 and traditional encrypted PEM require the
490
+ * explicit password-taking import functions. No format guessing or decryption is attempted.
491
+ *
492
+ * Without `algorithm`, existing inference applies (RSA defaults to PKCS#1v1.5/SHA-256).
493
+ * An explicit descriptor additionally asserts key family/curve and selects RSA padding/hash.
494
+ */
495
+ export declare function importPrivateKeyPemOrThrow(pem: string, algorithm?: PrivateKeyImportInput): Promise<CryptoKey>;
496
+ /** Result-returning counterpart of {@linkcode importPrivateKeyPemOrThrow}. */
497
+ export declare function importPrivateKeyPem(pem: string, algorithm?: PrivateKeyImportInput): Promise<ImportKeyResult<CryptoKey>>;
472
498
  /**
473
499
  * Import a public key from base64-encoded SubjectPublicKeyInfo (no PEM headers).
474
500
  *
@@ -834,5 +860,4 @@ export declare function decryptRsaOaepOrThrow(privateKey: CryptoKey, ciphertext:
834
860
  * @see `decryptRsaOaepOrThrow` for the throwing variant
835
861
  */
836
862
  export declare function decryptRsaOaep(privateKey: CryptoKey, ciphertext: Uint8Array, options?: RsaOaepOptions): Promise<DecryptRsaOaepResult>;
837
- export { type KdfLimitOptions, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Parameters, type Pbes2Prf, parsePbes2AlgorithmIdentifier };
838
- //# sourceMappingURL=keys.d.ts.map
863
+ export { type KdfLimitOptions, type Pbes2EncryptionOptions, type Pbes2EncryptionScheme, type Pbes2Parameters, type Pbes2Prf, parsePbes2AlgorithmIdentifier };