@blamejs/core 0.7.18 → 0.7.19

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 (167) hide show
  1. package/CHANGELOG.md +425 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +315 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +316 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/health.js +392 -392
  86. package/lib/middleware/index.js +82 -79
  87. package/lib/middleware/rate-limit.js +358 -358
  88. package/lib/middleware/request-id.js +61 -61
  89. package/lib/middleware/request-log.js +168 -168
  90. package/lib/middleware/require-auth.js +104 -104
  91. package/lib/middleware/security-headers.js +116 -116
  92. package/lib/middleware/sse.js +166 -166
  93. package/lib/migrations.js +383 -383
  94. package/lib/mtls-ca.js +518 -518
  95. package/lib/mtls-engine-default.js +481 -481
  96. package/lib/network-dns.js +632 -632
  97. package/lib/network-heartbeat.js +290 -290
  98. package/lib/network-nts.js +574 -574
  99. package/lib/network-proxy.js +265 -265
  100. package/lib/network-tls.js +328 -328
  101. package/lib/network.js +233 -233
  102. package/lib/notify.js +612 -612
  103. package/lib/ntp-check.js +229 -229
  104. package/lib/numeric-bounds.js +111 -111
  105. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  106. package/lib/object-store/azure-blob.js +488 -488
  107. package/lib/object-store/gcs-bucket-ops.js +351 -351
  108. package/lib/object-store/gcs.js +519 -519
  109. package/lib/object-store/http-put.js +153 -153
  110. package/lib/object-store/index.js +197 -197
  111. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  112. package/lib/object-store/sigv4.js +903 -903
  113. package/lib/observability.js +151 -151
  114. package/lib/otel-export.js +269 -269
  115. package/lib/pagination.js +464 -464
  116. package/lib/parsers/index.js +80 -80
  117. package/lib/parsers/safe-env.js +642 -642
  118. package/lib/parsers/safe-ini.js +292 -292
  119. package/lib/parsers/safe-toml.js +784 -784
  120. package/lib/parsers/safe-xml.js +390 -390
  121. package/lib/parsers/safe-yaml.js +1015 -1015
  122. package/lib/permissions.js +708 -708
  123. package/lib/pqc-agent.js +87 -87
  124. package/lib/pqc-gate.js +279 -279
  125. package/lib/protobuf-encoder.js +190 -190
  126. package/lib/protocol-dispatcher.js +161 -161
  127. package/lib/pubsub-redis.js +167 -167
  128. package/lib/pubsub.js +429 -429
  129. package/lib/queue-local.js +476 -476
  130. package/lib/queue-redis.js +745 -745
  131. package/lib/queue-sqs.js +319 -319
  132. package/lib/queue.js +695 -695
  133. package/lib/redis-client.js +519 -519
  134. package/lib/request-helpers.js +340 -340
  135. package/lib/restore-bundle.js +237 -237
  136. package/lib/restore-rollback.js +259 -259
  137. package/lib/restore.js +409 -409
  138. package/lib/retry.js +376 -376
  139. package/lib/router.js +748 -748
  140. package/lib/safe-async.js +735 -735
  141. package/lib/safe-buffer.js +237 -237
  142. package/lib/safe-json.js +541 -541
  143. package/lib/safe-schema.js +1266 -1266
  144. package/lib/safe-url.js +159 -159
  145. package/lib/scheduler.js +706 -706
  146. package/lib/security-assert.js +373 -373
  147. package/lib/seeders.js +618 -618
  148. package/lib/session.js +535 -478
  149. package/lib/slug.js +269 -269
  150. package/lib/ssrf-guard.js +401 -401
  151. package/lib/storage.js +471 -471
  152. package/lib/subject.js +281 -281
  153. package/lib/template.js +791 -791
  154. package/lib/testing.js +798 -798
  155. package/lib/time.js +310 -310
  156. package/lib/totp.js +302 -302
  157. package/lib/tracing.js +494 -494
  158. package/lib/uuid.js +132 -132
  159. package/lib/validate-opts.js +340 -340
  160. package/lib/vault/index.js +308 -308
  161. package/lib/vault/rotate.js +784 -784
  162. package/lib/vault/wrap.js +296 -296
  163. package/lib/vendor/noble-ciphers.cjs +9 -9
  164. package/lib/webhook.js +595 -595
  165. package/lib/websocket.js +1048 -1048
  166. package/package.json +77 -77
  167. package/sbom.cyclonedx.json +7 -7
@@ -1,481 +1,481 @@
1
- "use strict";
2
- /**
3
- * mtls-engine-default — pure-JS X.509 engine wired into b.mtlsCa.
4
- *
5
- * Implements the engine contract documented at the top of lib/mtls-ca.js:
6
- * generateCa({ generation }) -> { caCertPem, caKeyPem }
7
- * signClientCert({ cn, validityDays,
8
- * caCertPem, caKeyPem }) -> { cert, key, ca, issuedAt, expiresAt }
9
- * packageP12({ cn, password, validityDays,
10
- * caCertPem, caKeyPem }) -> { p12, certPem, issuedAt, expiresAt }
11
- *
12
- * Backed by lib/vendor/pki.cjs (vendored @peculiar/x509 + pkijs +
13
- * reflect-metadata + ASN.1 schema chain). node:crypto.webcrypto is bound
14
- * inside the bundle entry; nothing here calls openssl CLI.
15
- *
16
- * Algorithm envelope:
17
- * CA + leaf signatures: ECDSA P-384 + SHA-384
18
- * PKCS#12 key bag : PBES2 + AES-256-CBC + PBKDF2-HMAC-SHA-512, 2,000,000 iter
19
- * PKCS#12 cert bag : same as key bag
20
- * PKCS#12 outer MAC : HMAC-SHA-512 + PBKDF2, 2,000,000 iter
21
- *
22
- * The X.509 ecosystem doesn't yet accept SLH-DSA / ML-DSA on shipping
23
- * client certs, so the cert sigs stay classical ECDSA-P384 — matching
24
- * the framework's hybrid KEM posture rather than its standalone PQ
25
- * signing posture. Swap atomically when browsers + OS cert stores can
26
- * verify a PQ algorithm; bump CA_GENERATION on the same release so
27
- * b.mtlsCa.status reports legacy correctly.
28
- */
29
-
30
- var nodeCrypto = require("node:crypto");
31
-
32
- var pki = require("./vendor/pki.cjs");
33
-
34
- var C = require("./constants");
35
- var crypto = require("./crypto");
36
- var nb = require("./numeric-bounds");
37
- var { FrameworkError } = require("./framework-error");
38
-
39
- var x509 = pki.x509;
40
- var pkijs = pki.pkijs;
41
- var webcrypto = pki.crypto;
42
-
43
- class MtlsEngineError extends FrameworkError {
44
- constructor(code, message) {
45
- super(message, code);
46
- this.name = "MtlsEngineError";
47
- this.permanent = true;
48
- this.isMtlsEngineError = true;
49
- }
50
- }
51
-
52
- var CA_KEY_USAGES = ["sign", "verify"];
53
-
54
- // Algorithm priority — each entry probed at first use; the first one
55
- // the vendored x509 library AND webcrypto can both honour wins.
56
- // Ordered highest-PQC-posture first so the engine self-upgrades the
57
- // moment the vendor bundle gains PQ-sig X.509 support.
58
- //
59
- // keyAlg: passed to webcrypto.subtle.generateKey + import
60
- // sigAlg: passed to x509.X509CertificateGenerator.create
61
- // label : surfaced via b.mtlsCa.status() so operators can audit
62
- // which algorithm the in-flight CA generation is using
63
- var ALG_CANDIDATES = [
64
- // Pure-PQC stateless hash-based — matches lib/audit-sign's posture.
65
- // FIPS 205 (SPHINCS+ family). Awaiting node:tls + browser cert-store
66
- // verification support; currently issuance-only on most stacks.
67
- {
68
- label: "SLH-DSA-SHAKE-256f",
69
- keyAlg: { name: "SLH-DSA-SHAKE-256f" },
70
- sigAlg: { name: "SLH-DSA-SHAKE-256f" },
71
- posture: "pqc-pure",
72
- },
73
- {
74
- label: "SLH-DSA-SHAKE-128f",
75
- keyAlg: { name: "SLH-DSA-SHAKE-128f" },
76
- sigAlg: { name: "SLH-DSA-SHAKE-128f" },
77
- posture: "pqc-pure",
78
- },
79
- // Pure-PQC lattice — FIPS 204 (Dilithium family). Smaller than SLH-DSA,
80
- // accepted by the same emerging cert-store deployments.
81
- {
82
- label: "ML-DSA-87",
83
- keyAlg: { name: "ML-DSA-87" },
84
- sigAlg: { name: "ML-DSA-87" },
85
- posture: "pqc-pure",
86
- },
87
- {
88
- label: "ML-DSA-65",
89
- keyAlg: { name: "ML-DSA-65" },
90
- sigAlg: { name: "ML-DSA-65" },
91
- posture: "pqc-pure",
92
- },
93
- // Documented bridge — used until cert ecosystems verify the above.
94
- // The framework's hybrid KEM posture (X25519MLKEM768) covers handshake
95
- // KEX; these certs sign with ECDSA P-384 + SHA-384.
96
- {
97
- label: "ECDSA-P384-SHA384",
98
- keyAlg: { name: "ECDSA", namedCurve: "P-384" },
99
- sigAlg: { name: "ECDSA", hash: "SHA-384" },
100
- posture: "classical",
101
- },
102
- ];
103
-
104
- // First-call probe cache. Re-runs after engine reload (test reset path).
105
- var _selectedAlg = null;
106
-
107
- async function _probeCandidate(c) {
108
- try {
109
- var pair = await webcrypto.subtle.generateKey(c.keyAlg, true, CA_KEY_USAGES);
110
- if (!pair || !pair.publicKey) return false;
111
- // Also confirm the x509 generator accepts the sigAlg by issuing a
112
- // throwaway self-signed cert. Some keyAlgs work in webcrypto but
113
- // aren't yet wired through @peculiar/x509's encoder — without this
114
- // round-trip we'd select an algorithm we can't actually mint certs
115
- // with and hit a confusing failure on first issuance.
116
- await x509.X509CertificateGenerator.create({
117
- serialNumber: "01",
118
- subject: "CN=probe",
119
- issuer: "CN=probe",
120
- notBefore: new Date(),
121
- notAfter: new Date(Date.now() + C.TIME.seconds(1)),
122
- signingAlgorithm: c.sigAlg,
123
- publicKey: pair.publicKey,
124
- signingKey: pair.privateKey,
125
- });
126
- return true;
127
- } catch (_e) {
128
- return false;
129
- }
130
- }
131
-
132
- async function _selectAlgorithm() {
133
- if (_selectedAlg) return _selectedAlg;
134
- for (var i = 0; i < ALG_CANDIDATES.length; i++) {
135
- var c = ALG_CANDIDATES[i];
136
- var ok = await _probeCandidate(c);
137
- if (ok) { _selectedAlg = c; return c; }
138
- }
139
- // Should never happen — ECDSA-P384-SHA384 is universal.
140
- throw new MtlsEngineError("mtls-engine/no-algorithm",
141
- "no candidate algorithm passed the webcrypto + x509 probe");
142
- }
143
-
144
- // Backwards-compat shape for callers that read these directly. Resolved
145
- // lazily so the algorithm choice is the first-probe result.
146
- var CA_KEY_ALG = null;
147
- var CA_SIG_ALG = null;
148
-
149
- // AES-256 key length expressed in bits — webcrypto's contract for the
150
- // `length` field of AES-CBC. Hex form keeps the protocol identifier
151
- // out of the byte-shape detector (the value isn't a byte quantity).
152
- var P12_CONTENT_ENC = { name: "AES-CBC", length: 0x100 };
153
- var P12_KDF_HASH = "SHA-512";
154
- var P12_MAC_HASH = "SHA-512";
155
- // PKCS#12 PBKDF2 iteration count — protocol-fixed cost parameter, not
156
- // a byte quantity. Hex form per the same rationale as P12_CONTENT_ENC.length.
157
- var P12_ITER = 0x1E8480;
158
-
159
- var CA_VALIDITY_DAYS = 10 * 365; // 10y CA lifetime
160
- var LEAF_DEFAULT_DAYS = 365;
161
- var DEFAULT_CA_NAME = "blamejs CA";
162
- var BAG_ID_KEY = "1.2.840.113549.1.12.10.1.2"; // pkcs-12-pkcs-8ShroudedKeyBag
163
- var BAG_ID_CERT = "1.2.840.113549.1.12.10.1.3"; // pkcs-12-certBag
164
- var EKU_CLIENT_AUTH_OID = "1.3.6.1.5.5.7.3.2";
165
- var EKU_SERVER_AUTH_OID = "1.3.6.1.5.5.7.3.1";
166
-
167
- function _pemBlock(label, der) {
168
- var b64 = Buffer.from(der).toString("base64");
169
- return "-----BEGIN " + label + "-----\n" + b64.match(/.{1,64}/g).join("\n") + "\n-----END " + label + "-----\n";
170
- }
171
-
172
- async function _exportKeyPairToPem(keyPair) {
173
- var pkcs8 = await webcrypto.subtle.exportKey("pkcs8", keyPair.privateKey);
174
- var spki = await webcrypto.subtle.exportKey("spki", keyPair.publicKey);
175
- return {
176
- privatePem: _pemBlock("PRIVATE KEY", pkcs8),
177
- publicPem: _pemBlock("PUBLIC KEY", spki),
178
- };
179
- }
180
-
181
- // Import a PEM private key regardless of its on-disk encoding.
182
- // Existing keys may be SEC1, PKCS#1, or PKCS#8 — Node's createPrivateKey
183
- // normalises all three; webcrypto.importKey then reads the PKCS#8 DER.
184
- async function _importPemPrivateKey(pem, alg, usages, extractable) {
185
- var keyObj = nodeCrypto.createPrivateKey(pem);
186
- var pkcs8 = keyObj.export({ format: "der", type: "pkcs8" });
187
- return webcrypto.subtle.importKey("pkcs8", pkcs8, alg, !!extractable, usages);
188
- }
189
-
190
- function _parseCertPem(pem) {
191
- return new x509.X509Certificate(pem);
192
- }
193
-
194
- function _normaliseCn(cn) {
195
- var s = String(cn || "").replace(/[^a-zA-Z0-9_.-]/g, "").slice(0, 63);
196
- if (!s) {
197
- throw new MtlsEngineError("mtls-engine/bad-cn",
198
- "cn must contain at least one [A-Za-z0-9._-] character (post-sanitisation)");
199
- }
200
- return s;
201
- }
202
-
203
- async function generateCa(opts) {
204
- opts = opts || {};
205
- var generation = (typeof opts.generation === "number" && opts.generation >= 1)
206
- ? Math.floor(opts.generation) : 1;
207
- var caName = opts.name || DEFAULT_CA_NAME;
208
-
209
- var alg = await _selectAlgorithm();
210
- CA_KEY_ALG = alg.keyAlg; CA_SIG_ALG = alg.sigAlg;
211
- var keys = await webcrypto.subtle.generateKey(CA_KEY_ALG, true, CA_KEY_USAGES);
212
- var now = new Date();
213
- var ca = await x509.X509CertificateGenerator.createSelfSigned({
214
- serialNumber: crypto.generateToken(C.BYTES.bytes(16)),
215
- name: "CN=" + caName + ",OU=CAv" + generation,
216
- notBefore: now,
217
- notAfter: new Date(now.getTime() + C.TIME.days(CA_VALIDITY_DAYS)),
218
- signingAlgorithm: CA_SIG_ALG,
219
- keys: keys,
220
- extensions: [
221
- new x509.BasicConstraintsExtension(true, 0, true),
222
- new x509.KeyUsagesExtension(
223
- x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign,
224
- true
225
- ),
226
- ],
227
- });
228
- var pem = await _exportKeyPairToPem(keys);
229
- return { caCertPem: ca.toString("pem"), caKeyPem: pem.privatePem };
230
- }
231
-
232
- async function signClientCert(opts) {
233
- opts = opts || {};
234
- if (typeof opts.cn !== "string" || !opts.caCertPem || !opts.caKeyPem) {
235
- throw new MtlsEngineError("mtls-engine/missing-arg",
236
- "signClientCert requires { cn, caCertPem, caKeyPem }");
237
- }
238
- nb.requirePositiveFiniteIntIfPresent(opts.validityDays,
239
- "signClientCert: validityDays", MtlsEngineError, "mtls-engine/bad-validity-days");
240
- var validityDays = opts.validityDays !== undefined
241
- ? opts.validityDays : LEAF_DEFAULT_DAYS;
242
- var cn = _normaliseCn(opts.cn);
243
-
244
- // Extended Key Usage: defaults to clientAuth (the historical behaviour).
245
- // Operators issuing server certs for inbound mTLS reverse-proxy fronts
246
- // pass `usage: "server"` (sets serverAuth EKU), or `usage: "both"`
247
- // (clientAuth + serverAuth — dual-purpose certs for service-to-service
248
- // mTLS where the same workload is both initiator and acceptor).
249
- var usage = opts.usage || "client";
250
- var ekuOids = [];
251
- if (usage === "client" || usage === "both") ekuOids.push(EKU_CLIENT_AUTH_OID);
252
- if (usage === "server" || usage === "both") ekuOids.push(EKU_SERVER_AUTH_OID);
253
- if (ekuOids.length === 0) {
254
- throw new MtlsEngineError("mtls-engine/bad-usage",
255
- "signClientCert: opts.usage must be 'client' | 'server' | 'both', got " +
256
- JSON.stringify(opts.usage));
257
- }
258
-
259
- // Subject Alternative Names — required for serverAuth (modern TLS
260
- // clients only honor SANs, not CN). Accept opts.sans as an array of
261
- // strings (DNS names by default; "DNS:foo" / "IP:1.2.3.4" forms also).
262
- var sanExt = null;
263
- if (Array.isArray(opts.sans) && opts.sans.length > 0) {
264
- var sanEntries = opts.sans.map(function (s) {
265
- var str = String(s);
266
- if (/^DNS:/i.test(str)) return { type: "dns", value: str.slice(4) };
267
- if (/^IP:/i.test(str)) return { type: "ip", value: str.slice(3) };
268
- // Bare entries default to DNS — matches operator expectation
269
- return { type: "dns", value: str };
270
- });
271
- sanExt = new x509.SubjectAlternativeNameExtension(sanEntries);
272
- } else if (usage === "server" || usage === "both") {
273
- // serverAuth without a SAN is unverifiable by modern TLS clients.
274
- // Auto-add the CN as a DNS SAN so the most common case "just works".
275
- sanExt = new x509.SubjectAlternativeNameExtension([{ type: "dns", value: cn }]);
276
- }
277
-
278
- var alg = await _selectAlgorithm();
279
- CA_KEY_ALG = alg.keyAlg; CA_SIG_ALG = alg.sigAlg;
280
- var caKey = await _importPemPrivateKey(opts.caKeyPem, CA_KEY_ALG, ["sign"]);
281
- var caCert = _parseCertPem(opts.caCertPem);
282
- var clientKeys = await webcrypto.subtle.generateKey(CA_KEY_ALG, true, CA_KEY_USAGES);
283
-
284
- var now = new Date();
285
- var notAfter = new Date(now.getTime() + C.TIME.days(validityDays));
286
- var extensions = [
287
- new x509.BasicConstraintsExtension(false, undefined, true),
288
- new x509.KeyUsagesExtension(
289
- x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment,
290
- true
291
- ),
292
- new x509.ExtendedKeyUsageExtension(ekuOids, true),
293
- ];
294
- if (sanExt) extensions.push(sanExt);
295
-
296
- var clientCert = await x509.X509CertificateGenerator.create({
297
- serialNumber: crypto.generateToken(C.BYTES.bytes(16)),
298
- subject: "CN=" + cn,
299
- issuer: caCert.subject,
300
- notBefore: now,
301
- notAfter: notAfter,
302
- signingAlgorithm: CA_SIG_ALG,
303
- publicKey: clientKeys.publicKey,
304
- signingKey: caKey,
305
- extensions: extensions,
306
- });
307
- var pem = await _exportKeyPairToPem(clientKeys);
308
- return {
309
- cert: clientCert.toString("pem"),
310
- key: pem.privatePem,
311
- ca: opts.caCertPem,
312
- issuedAt: now.toISOString(),
313
- expiresAt: notAfter.toISOString(),
314
- usage: usage,
315
- };
316
- }
317
-
318
- async function packageP12(opts) {
319
- opts = opts || {};
320
- if (typeof opts.password !== "string" || opts.password.length < 1) {
321
- throw new MtlsEngineError("mtls-engine/no-password",
322
- "packageP12 requires opts.password (non-empty string)");
323
- }
324
- var leaf = await signClientCert(opts);
325
-
326
- // Re-import the leaf key as extractable so we can re-export PKCS#8 DER
327
- // for the shrouded key bag.
328
- var leafKey = await _importPemPrivateKey(leaf.key, CA_KEY_ALG, ["sign"], true);
329
- var leafPkcs8 = await webcrypto.subtle.exportKey("pkcs8", leafKey);
330
- var privateKeyInfo = pkijs.PrivateKeyInfo.fromBER(leafPkcs8);
331
-
332
- var leafX509 = _parseCertPem(leaf.cert);
333
- var caX509 = _parseCertPem(leaf.ca);
334
- var leafPkijsCert = pkijs.Certificate.fromBER(leafX509.rawData);
335
- var caPkijsCert = pkijs.Certificate.fromBER(caX509.rawData);
336
-
337
- var passwordBuf = Buffer.from(opts.password, "utf8");
338
-
339
- var pfx = new pkijs.PFX({
340
- parsedValue: {
341
- integrityMode: 0, // PasswordMode (outer HMAC-PBKDF2)
342
- authenticatedSafe: new pkijs.AuthenticatedSafe({
343
- parsedValue: {
344
- safeContents: [
345
- {
346
- privacyMode: 1, // PasswordPrivacyMode (PBES2)
347
- value: new pkijs.SafeContents({
348
- safeBags: [
349
- new pkijs.SafeBag({
350
- bagId: BAG_ID_KEY,
351
- bagValue: new pkijs.PKCS8ShroudedKeyBag({ parsedValue: privateKeyInfo }),
352
- }),
353
- ],
354
- }),
355
- },
356
- {
357
- privacyMode: 1,
358
- value: new pkijs.SafeContents({
359
- safeBags: [
360
- new pkijs.SafeBag({
361
- bagId: BAG_ID_CERT,
362
- bagValue: new pkijs.CertBag({ parsedValue: leafPkijsCert }),
363
- }),
364
- new pkijs.SafeBag({
365
- bagId: BAG_ID_CERT,
366
- bagValue: new pkijs.CertBag({ parsedValue: caPkijsCert }),
367
- }),
368
- ],
369
- }),
370
- },
371
- ],
372
- },
373
- }),
374
- },
375
- });
376
-
377
- // Inner protection on the shrouded-key bag itself.
378
- await pfx.parsedValue.authenticatedSafe.parsedValue.safeContents[0]
379
- .value.safeBags[0].bagValue.makeInternalValues({
380
- password: passwordBuf,
381
- contentEncryptionAlgorithm: P12_CONTENT_ENC,
382
- hmacHashAlgorithm: P12_KDF_HASH,
383
- iterationCount: P12_ITER,
384
- });
385
-
386
- // Encrypt each SafeContents envelope.
387
- await pfx.parsedValue.authenticatedSafe.makeInternalValues({
388
- safeContents: [
389
- { password: passwordBuf, contentEncryptionAlgorithm: P12_CONTENT_ENC, hmacHashAlgorithm: P12_KDF_HASH, iterationCount: P12_ITER },
390
- { password: passwordBuf, contentEncryptionAlgorithm: P12_CONTENT_ENC, hmacHashAlgorithm: P12_KDF_HASH, iterationCount: P12_ITER },
391
- ],
392
- });
393
-
394
- // Outer integrity MAC.
395
- await pfx.makeInternalValues({
396
- password: passwordBuf,
397
- iterations: P12_ITER,
398
- pbkdf2HashAlgorithm: P12_KDF_HASH,
399
- hmacHashAlgorithm: P12_MAC_HASH,
400
- });
401
-
402
- return {
403
- p12: Buffer.from(pfx.toSchema().toBER(false)),
404
- certPem: leaf.cert,
405
- issuedAt: leaf.issuedAt,
406
- expiresAt: leaf.expiresAt,
407
- };
408
- }
409
-
410
- function algorithmEnvelope() {
411
- return {
412
- cert: {
413
- keyAlg: CA_KEY_ALG,
414
- sigAlg: CA_SIG_ALG,
415
- label: _selectedAlg && _selectedAlg.label,
416
- posture: _selectedAlg && _selectedAlg.posture,
417
- // Operators querying status() before any cert has been issued
418
- // get the candidate priority list — the engine probes lazily so
419
- // the chosen algorithm isn't known until first use.
420
- priority: ALG_CANDIDATES.map(function (c) {
421
- return { label: c.label, posture: c.posture };
422
- }),
423
- },
424
- p12: {
425
- contentEncryption: P12_CONTENT_ENC,
426
- kdfHash: P12_KDF_HASH,
427
- macHash: P12_MAC_HASH,
428
- iterationCount: P12_ITER,
429
- },
430
- caValidityDays: CA_VALIDITY_DAYS,
431
- leafDefaultDays: LEAF_DEFAULT_DAYS,
432
- };
433
- }
434
-
435
- // Generate a signed X.509 CRL (RFC 5280) covering every revoked
436
- // serial number. The vendored peculiar/x509 library exposes
437
- // X509CrlGenerator.create which builds the TBSCertList, populates
438
- // the entries, and signs with the CA private key — same signature
439
- // algorithm the CA itself was issued under (auto-detected via
440
- // _selectAlgorithm + cached on first issuance).
441
- async function generateCrl(opts) {
442
- opts = opts || {};
443
- if (!opts.caCertPem || !opts.caKeyPem) {
444
- throw new MtlsEngineError("mtls-engine/missing-arg",
445
- "generateCrl requires { caCertPem, caKeyPem, revocations, thisUpdate, nextUpdate }");
446
- }
447
- var revocations = Array.isArray(opts.revocations) ? opts.revocations : [];
448
- var alg = await _selectAlgorithm();
449
- CA_KEY_ALG = alg.keyAlg; CA_SIG_ALG = alg.sigAlg;
450
-
451
- var caKey = await _importPemPrivateKey(opts.caKeyPem, CA_KEY_ALG, ["sign"]);
452
- var caCert = _parseCertPem(opts.caCertPem);
453
-
454
- // X509CrlEntry expects { serialNumber: hex, revocationDate, reason }.
455
- var entries = revocations.map(function (r) {
456
- return {
457
- serialNumber: r.serialNumber,
458
- revocationDate: new Date(r.revokedAt || Date.now()),
459
- reason: (typeof r.reasonCode === "number") ? r.reasonCode : 0,
460
- };
461
- });
462
-
463
- var crl = await x509.X509CrlGenerator.create({
464
- issuer: caCert.subject,
465
- thisUpdate: opts.thisUpdate || new Date(),
466
- nextUpdate: opts.nextUpdate,
467
- entries: entries,
468
- signingAlgorithm: CA_SIG_ALG,
469
- signingKey: caKey,
470
- });
471
- return crl.toString("pem");
472
- }
473
-
474
- module.exports = {
475
- generateCa: generateCa,
476
- signClientCert: signClientCert,
477
- packageP12: packageP12,
478
- generateCrl: generateCrl,
479
- algorithmEnvelope: algorithmEnvelope,
480
- MtlsEngineError: MtlsEngineError,
481
- };
1
+ "use strict";
2
+ /**
3
+ * mtls-engine-default — pure-JS X.509 engine wired into b.mtlsCa.
4
+ *
5
+ * Implements the engine contract documented at the top of lib/mtls-ca.js:
6
+ * generateCa({ generation }) -> { caCertPem, caKeyPem }
7
+ * signClientCert({ cn, validityDays,
8
+ * caCertPem, caKeyPem }) -> { cert, key, ca, issuedAt, expiresAt }
9
+ * packageP12({ cn, password, validityDays,
10
+ * caCertPem, caKeyPem }) -> { p12, certPem, issuedAt, expiresAt }
11
+ *
12
+ * Backed by lib/vendor/pki.cjs (vendored @peculiar/x509 + pkijs +
13
+ * reflect-metadata + ASN.1 schema chain). node:crypto.webcrypto is bound
14
+ * inside the bundle entry; nothing here calls openssl CLI.
15
+ *
16
+ * Algorithm envelope:
17
+ * CA + leaf signatures: ECDSA P-384 + SHA-384
18
+ * PKCS#12 key bag : PBES2 + AES-256-CBC + PBKDF2-HMAC-SHA-512, 2,000,000 iter
19
+ * PKCS#12 cert bag : same as key bag
20
+ * PKCS#12 outer MAC : HMAC-SHA-512 + PBKDF2, 2,000,000 iter
21
+ *
22
+ * The X.509 ecosystem doesn't yet accept SLH-DSA / ML-DSA on shipping
23
+ * client certs, so the cert sigs stay classical ECDSA-P384 — matching
24
+ * the framework's hybrid KEM posture rather than its standalone PQ
25
+ * signing posture. Swap atomically when browsers + OS cert stores can
26
+ * verify a PQ algorithm; bump CA_GENERATION on the same release so
27
+ * b.mtlsCa.status reports legacy correctly.
28
+ */
29
+
30
+ var nodeCrypto = require("node:crypto");
31
+
32
+ var pki = require("./vendor/pki.cjs");
33
+
34
+ var C = require("./constants");
35
+ var crypto = require("./crypto");
36
+ var nb = require("./numeric-bounds");
37
+ var { FrameworkError } = require("./framework-error");
38
+
39
+ var x509 = pki.x509;
40
+ var pkijs = pki.pkijs;
41
+ var webcrypto = pki.crypto;
42
+
43
+ class MtlsEngineError extends FrameworkError {
44
+ constructor(code, message) {
45
+ super(message, code);
46
+ this.name = "MtlsEngineError";
47
+ this.permanent = true;
48
+ this.isMtlsEngineError = true;
49
+ }
50
+ }
51
+
52
+ var CA_KEY_USAGES = ["sign", "verify"];
53
+
54
+ // Algorithm priority — each entry probed at first use; the first one
55
+ // the vendored x509 library AND webcrypto can both honour wins.
56
+ // Ordered highest-PQC-posture first so the engine self-upgrades the
57
+ // moment the vendor bundle gains PQ-sig X.509 support.
58
+ //
59
+ // keyAlg: passed to webcrypto.subtle.generateKey + import
60
+ // sigAlg: passed to x509.X509CertificateGenerator.create
61
+ // label : surfaced via b.mtlsCa.status() so operators can audit
62
+ // which algorithm the in-flight CA generation is using
63
+ var ALG_CANDIDATES = [
64
+ // Pure-PQC stateless hash-based — matches lib/audit-sign's posture.
65
+ // FIPS 205 (SPHINCS+ family). Awaiting node:tls + browser cert-store
66
+ // verification support; currently issuance-only on most stacks.
67
+ {
68
+ label: "SLH-DSA-SHAKE-256f",
69
+ keyAlg: { name: "SLH-DSA-SHAKE-256f" },
70
+ sigAlg: { name: "SLH-DSA-SHAKE-256f" },
71
+ posture: "pqc-pure",
72
+ },
73
+ {
74
+ label: "SLH-DSA-SHAKE-128f",
75
+ keyAlg: { name: "SLH-DSA-SHAKE-128f" },
76
+ sigAlg: { name: "SLH-DSA-SHAKE-128f" },
77
+ posture: "pqc-pure",
78
+ },
79
+ // Pure-PQC lattice — FIPS 204 (Dilithium family). Smaller than SLH-DSA,
80
+ // accepted by the same emerging cert-store deployments.
81
+ {
82
+ label: "ML-DSA-87",
83
+ keyAlg: { name: "ML-DSA-87" },
84
+ sigAlg: { name: "ML-DSA-87" },
85
+ posture: "pqc-pure",
86
+ },
87
+ {
88
+ label: "ML-DSA-65",
89
+ keyAlg: { name: "ML-DSA-65" },
90
+ sigAlg: { name: "ML-DSA-65" },
91
+ posture: "pqc-pure",
92
+ },
93
+ // Documented bridge — used until cert ecosystems verify the above.
94
+ // The framework's hybrid KEM posture (X25519MLKEM768) covers handshake
95
+ // KEX; these certs sign with ECDSA P-384 + SHA-384.
96
+ {
97
+ label: "ECDSA-P384-SHA384",
98
+ keyAlg: { name: "ECDSA", namedCurve: "P-384" },
99
+ sigAlg: { name: "ECDSA", hash: "SHA-384" },
100
+ posture: "classical",
101
+ },
102
+ ];
103
+
104
+ // First-call probe cache. Re-runs after engine reload (test reset path).
105
+ var _selectedAlg = null;
106
+
107
+ async function _probeCandidate(c) {
108
+ try {
109
+ var pair = await webcrypto.subtle.generateKey(c.keyAlg, true, CA_KEY_USAGES);
110
+ if (!pair || !pair.publicKey) return false;
111
+ // Also confirm the x509 generator accepts the sigAlg by issuing a
112
+ // throwaway self-signed cert. Some keyAlgs work in webcrypto but
113
+ // aren't yet wired through @peculiar/x509's encoder — without this
114
+ // round-trip we'd select an algorithm we can't actually mint certs
115
+ // with and hit a confusing failure on first issuance.
116
+ await x509.X509CertificateGenerator.create({
117
+ serialNumber: "01",
118
+ subject: "CN=probe",
119
+ issuer: "CN=probe",
120
+ notBefore: new Date(),
121
+ notAfter: new Date(Date.now() + C.TIME.seconds(1)),
122
+ signingAlgorithm: c.sigAlg,
123
+ publicKey: pair.publicKey,
124
+ signingKey: pair.privateKey,
125
+ });
126
+ return true;
127
+ } catch (_e) {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ async function _selectAlgorithm() {
133
+ if (_selectedAlg) return _selectedAlg;
134
+ for (var i = 0; i < ALG_CANDIDATES.length; i++) {
135
+ var c = ALG_CANDIDATES[i];
136
+ var ok = await _probeCandidate(c);
137
+ if (ok) { _selectedAlg = c; return c; }
138
+ }
139
+ // Should never happen — ECDSA-P384-SHA384 is universal.
140
+ throw new MtlsEngineError("mtls-engine/no-algorithm",
141
+ "no candidate algorithm passed the webcrypto + x509 probe");
142
+ }
143
+
144
+ // Backwards-compat shape for callers that read these directly. Resolved
145
+ // lazily so the algorithm choice is the first-probe result.
146
+ var CA_KEY_ALG = null;
147
+ var CA_SIG_ALG = null;
148
+
149
+ // AES-256 key length expressed in bits — webcrypto's contract for the
150
+ // `length` field of AES-CBC. Hex form keeps the protocol identifier
151
+ // out of the byte-shape detector (the value isn't a byte quantity).
152
+ var P12_CONTENT_ENC = { name: "AES-CBC", length: 0x100 };
153
+ var P12_KDF_HASH = "SHA-512";
154
+ var P12_MAC_HASH = "SHA-512";
155
+ // PKCS#12 PBKDF2 iteration count — protocol-fixed cost parameter, not
156
+ // a byte quantity. Hex form per the same rationale as P12_CONTENT_ENC.length.
157
+ var P12_ITER = 0x1E8480;
158
+
159
+ var CA_VALIDITY_DAYS = 10 * 365; // 10y CA lifetime
160
+ var LEAF_DEFAULT_DAYS = 365;
161
+ var DEFAULT_CA_NAME = "blamejs CA";
162
+ var BAG_ID_KEY = "1.2.840.113549.1.12.10.1.2"; // pkcs-12-pkcs-8ShroudedKeyBag
163
+ var BAG_ID_CERT = "1.2.840.113549.1.12.10.1.3"; // pkcs-12-certBag
164
+ var EKU_CLIENT_AUTH_OID = "1.3.6.1.5.5.7.3.2";
165
+ var EKU_SERVER_AUTH_OID = "1.3.6.1.5.5.7.3.1";
166
+
167
+ function _pemBlock(label, der) {
168
+ var b64 = Buffer.from(der).toString("base64");
169
+ return "-----BEGIN " + label + "-----\n" + b64.match(/.{1,64}/g).join("\n") + "\n-----END " + label + "-----\n";
170
+ }
171
+
172
+ async function _exportKeyPairToPem(keyPair) {
173
+ var pkcs8 = await webcrypto.subtle.exportKey("pkcs8", keyPair.privateKey);
174
+ var spki = await webcrypto.subtle.exportKey("spki", keyPair.publicKey);
175
+ return {
176
+ privatePem: _pemBlock("PRIVATE KEY", pkcs8),
177
+ publicPem: _pemBlock("PUBLIC KEY", spki),
178
+ };
179
+ }
180
+
181
+ // Import a PEM private key regardless of its on-disk encoding.
182
+ // Existing keys may be SEC1, PKCS#1, or PKCS#8 — Node's createPrivateKey
183
+ // normalises all three; webcrypto.importKey then reads the PKCS#8 DER.
184
+ async function _importPemPrivateKey(pem, alg, usages, extractable) {
185
+ var keyObj = nodeCrypto.createPrivateKey(pem);
186
+ var pkcs8 = keyObj.export({ format: "der", type: "pkcs8" });
187
+ return webcrypto.subtle.importKey("pkcs8", pkcs8, alg, !!extractable, usages);
188
+ }
189
+
190
+ function _parseCertPem(pem) {
191
+ return new x509.X509Certificate(pem);
192
+ }
193
+
194
+ function _normaliseCn(cn) {
195
+ var s = String(cn || "").replace(/[^a-zA-Z0-9_.-]/g, "").slice(0, 63);
196
+ if (!s) {
197
+ throw new MtlsEngineError("mtls-engine/bad-cn",
198
+ "cn must contain at least one [A-Za-z0-9._-] character (post-sanitisation)");
199
+ }
200
+ return s;
201
+ }
202
+
203
+ async function generateCa(opts) {
204
+ opts = opts || {};
205
+ var generation = (typeof opts.generation === "number" && opts.generation >= 1)
206
+ ? Math.floor(opts.generation) : 1;
207
+ var caName = opts.name || DEFAULT_CA_NAME;
208
+
209
+ var alg = await _selectAlgorithm();
210
+ CA_KEY_ALG = alg.keyAlg; CA_SIG_ALG = alg.sigAlg;
211
+ var keys = await webcrypto.subtle.generateKey(CA_KEY_ALG, true, CA_KEY_USAGES);
212
+ var now = new Date();
213
+ var ca = await x509.X509CertificateGenerator.createSelfSigned({
214
+ serialNumber: crypto.generateToken(C.BYTES.bytes(16)),
215
+ name: "CN=" + caName + ",OU=CAv" + generation,
216
+ notBefore: now,
217
+ notAfter: new Date(now.getTime() + C.TIME.days(CA_VALIDITY_DAYS)),
218
+ signingAlgorithm: CA_SIG_ALG,
219
+ keys: keys,
220
+ extensions: [
221
+ new x509.BasicConstraintsExtension(true, 0, true),
222
+ new x509.KeyUsagesExtension(
223
+ x509.KeyUsageFlags.keyCertSign | x509.KeyUsageFlags.cRLSign,
224
+ true
225
+ ),
226
+ ],
227
+ });
228
+ var pem = await _exportKeyPairToPem(keys);
229
+ return { caCertPem: ca.toString("pem"), caKeyPem: pem.privatePem };
230
+ }
231
+
232
+ async function signClientCert(opts) {
233
+ opts = opts || {};
234
+ if (typeof opts.cn !== "string" || !opts.caCertPem || !opts.caKeyPem) {
235
+ throw new MtlsEngineError("mtls-engine/missing-arg",
236
+ "signClientCert requires { cn, caCertPem, caKeyPem }");
237
+ }
238
+ nb.requirePositiveFiniteIntIfPresent(opts.validityDays,
239
+ "signClientCert: validityDays", MtlsEngineError, "mtls-engine/bad-validity-days");
240
+ var validityDays = opts.validityDays !== undefined
241
+ ? opts.validityDays : LEAF_DEFAULT_DAYS;
242
+ var cn = _normaliseCn(opts.cn);
243
+
244
+ // Extended Key Usage: defaults to clientAuth (the historical behaviour).
245
+ // Operators issuing server certs for inbound mTLS reverse-proxy fronts
246
+ // pass `usage: "server"` (sets serverAuth EKU), or `usage: "both"`
247
+ // (clientAuth + serverAuth — dual-purpose certs for service-to-service
248
+ // mTLS where the same workload is both initiator and acceptor).
249
+ var usage = opts.usage || "client";
250
+ var ekuOids = [];
251
+ if (usage === "client" || usage === "both") ekuOids.push(EKU_CLIENT_AUTH_OID);
252
+ if (usage === "server" || usage === "both") ekuOids.push(EKU_SERVER_AUTH_OID);
253
+ if (ekuOids.length === 0) {
254
+ throw new MtlsEngineError("mtls-engine/bad-usage",
255
+ "signClientCert: opts.usage must be 'client' | 'server' | 'both', got " +
256
+ JSON.stringify(opts.usage));
257
+ }
258
+
259
+ // Subject Alternative Names — required for serverAuth (modern TLS
260
+ // clients only honor SANs, not CN). Accept opts.sans as an array of
261
+ // strings (DNS names by default; "DNS:foo" / "IP:1.2.3.4" forms also).
262
+ var sanExt = null;
263
+ if (Array.isArray(opts.sans) && opts.sans.length > 0) {
264
+ var sanEntries = opts.sans.map(function (s) {
265
+ var str = String(s);
266
+ if (/^DNS:/i.test(str)) return { type: "dns", value: str.slice(4) };
267
+ if (/^IP:/i.test(str)) return { type: "ip", value: str.slice(3) };
268
+ // Bare entries default to DNS — matches operator expectation
269
+ return { type: "dns", value: str };
270
+ });
271
+ sanExt = new x509.SubjectAlternativeNameExtension(sanEntries);
272
+ } else if (usage === "server" || usage === "both") {
273
+ // serverAuth without a SAN is unverifiable by modern TLS clients.
274
+ // Auto-add the CN as a DNS SAN so the most common case "just works".
275
+ sanExt = new x509.SubjectAlternativeNameExtension([{ type: "dns", value: cn }]);
276
+ }
277
+
278
+ var alg = await _selectAlgorithm();
279
+ CA_KEY_ALG = alg.keyAlg; CA_SIG_ALG = alg.sigAlg;
280
+ var caKey = await _importPemPrivateKey(opts.caKeyPem, CA_KEY_ALG, ["sign"]);
281
+ var caCert = _parseCertPem(opts.caCertPem);
282
+ var clientKeys = await webcrypto.subtle.generateKey(CA_KEY_ALG, true, CA_KEY_USAGES);
283
+
284
+ var now = new Date();
285
+ var notAfter = new Date(now.getTime() + C.TIME.days(validityDays));
286
+ var extensions = [
287
+ new x509.BasicConstraintsExtension(false, undefined, true),
288
+ new x509.KeyUsagesExtension(
289
+ x509.KeyUsageFlags.digitalSignature | x509.KeyUsageFlags.keyEncipherment,
290
+ true
291
+ ),
292
+ new x509.ExtendedKeyUsageExtension(ekuOids, true),
293
+ ];
294
+ if (sanExt) extensions.push(sanExt);
295
+
296
+ var clientCert = await x509.X509CertificateGenerator.create({
297
+ serialNumber: crypto.generateToken(C.BYTES.bytes(16)),
298
+ subject: "CN=" + cn,
299
+ issuer: caCert.subject,
300
+ notBefore: now,
301
+ notAfter: notAfter,
302
+ signingAlgorithm: CA_SIG_ALG,
303
+ publicKey: clientKeys.publicKey,
304
+ signingKey: caKey,
305
+ extensions: extensions,
306
+ });
307
+ var pem = await _exportKeyPairToPem(clientKeys);
308
+ return {
309
+ cert: clientCert.toString("pem"),
310
+ key: pem.privatePem,
311
+ ca: opts.caCertPem,
312
+ issuedAt: now.toISOString(),
313
+ expiresAt: notAfter.toISOString(),
314
+ usage: usage,
315
+ };
316
+ }
317
+
318
+ async function packageP12(opts) {
319
+ opts = opts || {};
320
+ if (typeof opts.password !== "string" || opts.password.length < 1) {
321
+ throw new MtlsEngineError("mtls-engine/no-password",
322
+ "packageP12 requires opts.password (non-empty string)");
323
+ }
324
+ var leaf = await signClientCert(opts);
325
+
326
+ // Re-import the leaf key as extractable so we can re-export PKCS#8 DER
327
+ // for the shrouded key bag.
328
+ var leafKey = await _importPemPrivateKey(leaf.key, CA_KEY_ALG, ["sign"], true);
329
+ var leafPkcs8 = await webcrypto.subtle.exportKey("pkcs8", leafKey);
330
+ var privateKeyInfo = pkijs.PrivateKeyInfo.fromBER(leafPkcs8);
331
+
332
+ var leafX509 = _parseCertPem(leaf.cert);
333
+ var caX509 = _parseCertPem(leaf.ca);
334
+ var leafPkijsCert = pkijs.Certificate.fromBER(leafX509.rawData);
335
+ var caPkijsCert = pkijs.Certificate.fromBER(caX509.rawData);
336
+
337
+ var passwordBuf = Buffer.from(opts.password, "utf8");
338
+
339
+ var pfx = new pkijs.PFX({
340
+ parsedValue: {
341
+ integrityMode: 0, // PasswordMode (outer HMAC-PBKDF2)
342
+ authenticatedSafe: new pkijs.AuthenticatedSafe({
343
+ parsedValue: {
344
+ safeContents: [
345
+ {
346
+ privacyMode: 1, // PasswordPrivacyMode (PBES2)
347
+ value: new pkijs.SafeContents({
348
+ safeBags: [
349
+ new pkijs.SafeBag({
350
+ bagId: BAG_ID_KEY,
351
+ bagValue: new pkijs.PKCS8ShroudedKeyBag({ parsedValue: privateKeyInfo }),
352
+ }),
353
+ ],
354
+ }),
355
+ },
356
+ {
357
+ privacyMode: 1,
358
+ value: new pkijs.SafeContents({
359
+ safeBags: [
360
+ new pkijs.SafeBag({
361
+ bagId: BAG_ID_CERT,
362
+ bagValue: new pkijs.CertBag({ parsedValue: leafPkijsCert }),
363
+ }),
364
+ new pkijs.SafeBag({
365
+ bagId: BAG_ID_CERT,
366
+ bagValue: new pkijs.CertBag({ parsedValue: caPkijsCert }),
367
+ }),
368
+ ],
369
+ }),
370
+ },
371
+ ],
372
+ },
373
+ }),
374
+ },
375
+ });
376
+
377
+ // Inner protection on the shrouded-key bag itself.
378
+ await pfx.parsedValue.authenticatedSafe.parsedValue.safeContents[0]
379
+ .value.safeBags[0].bagValue.makeInternalValues({
380
+ password: passwordBuf,
381
+ contentEncryptionAlgorithm: P12_CONTENT_ENC,
382
+ hmacHashAlgorithm: P12_KDF_HASH,
383
+ iterationCount: P12_ITER,
384
+ });
385
+
386
+ // Encrypt each SafeContents envelope.
387
+ await pfx.parsedValue.authenticatedSafe.makeInternalValues({
388
+ safeContents: [
389
+ { password: passwordBuf, contentEncryptionAlgorithm: P12_CONTENT_ENC, hmacHashAlgorithm: P12_KDF_HASH, iterationCount: P12_ITER },
390
+ { password: passwordBuf, contentEncryptionAlgorithm: P12_CONTENT_ENC, hmacHashAlgorithm: P12_KDF_HASH, iterationCount: P12_ITER },
391
+ ],
392
+ });
393
+
394
+ // Outer integrity MAC.
395
+ await pfx.makeInternalValues({
396
+ password: passwordBuf,
397
+ iterations: P12_ITER,
398
+ pbkdf2HashAlgorithm: P12_KDF_HASH,
399
+ hmacHashAlgorithm: P12_MAC_HASH,
400
+ });
401
+
402
+ return {
403
+ p12: Buffer.from(pfx.toSchema().toBER(false)),
404
+ certPem: leaf.cert,
405
+ issuedAt: leaf.issuedAt,
406
+ expiresAt: leaf.expiresAt,
407
+ };
408
+ }
409
+
410
+ function algorithmEnvelope() {
411
+ return {
412
+ cert: {
413
+ keyAlg: CA_KEY_ALG,
414
+ sigAlg: CA_SIG_ALG,
415
+ label: _selectedAlg && _selectedAlg.label,
416
+ posture: _selectedAlg && _selectedAlg.posture,
417
+ // Operators querying status() before any cert has been issued
418
+ // get the candidate priority list — the engine probes lazily so
419
+ // the chosen algorithm isn't known until first use.
420
+ priority: ALG_CANDIDATES.map(function (c) {
421
+ return { label: c.label, posture: c.posture };
422
+ }),
423
+ },
424
+ p12: {
425
+ contentEncryption: P12_CONTENT_ENC,
426
+ kdfHash: P12_KDF_HASH,
427
+ macHash: P12_MAC_HASH,
428
+ iterationCount: P12_ITER,
429
+ },
430
+ caValidityDays: CA_VALIDITY_DAYS,
431
+ leafDefaultDays: LEAF_DEFAULT_DAYS,
432
+ };
433
+ }
434
+
435
+ // Generate a signed X.509 CRL (RFC 5280) covering every revoked
436
+ // serial number. The vendored peculiar/x509 library exposes
437
+ // X509CrlGenerator.create which builds the TBSCertList, populates
438
+ // the entries, and signs with the CA private key — same signature
439
+ // algorithm the CA itself was issued under (auto-detected via
440
+ // _selectAlgorithm + cached on first issuance).
441
+ async function generateCrl(opts) {
442
+ opts = opts || {};
443
+ if (!opts.caCertPem || !opts.caKeyPem) {
444
+ throw new MtlsEngineError("mtls-engine/missing-arg",
445
+ "generateCrl requires { caCertPem, caKeyPem, revocations, thisUpdate, nextUpdate }");
446
+ }
447
+ var revocations = Array.isArray(opts.revocations) ? opts.revocations : [];
448
+ var alg = await _selectAlgorithm();
449
+ CA_KEY_ALG = alg.keyAlg; CA_SIG_ALG = alg.sigAlg;
450
+
451
+ var caKey = await _importPemPrivateKey(opts.caKeyPem, CA_KEY_ALG, ["sign"]);
452
+ var caCert = _parseCertPem(opts.caCertPem);
453
+
454
+ // X509CrlEntry expects { serialNumber: hex, revocationDate, reason }.
455
+ var entries = revocations.map(function (r) {
456
+ return {
457
+ serialNumber: r.serialNumber,
458
+ revocationDate: new Date(r.revokedAt || Date.now()),
459
+ reason: (typeof r.reasonCode === "number") ? r.reasonCode : 0,
460
+ };
461
+ });
462
+
463
+ var crl = await x509.X509CrlGenerator.create({
464
+ issuer: caCert.subject,
465
+ thisUpdate: opts.thisUpdate || new Date(),
466
+ nextUpdate: opts.nextUpdate,
467
+ entries: entries,
468
+ signingAlgorithm: CA_SIG_ALG,
469
+ signingKey: caKey,
470
+ });
471
+ return crl.toString("pem");
472
+ }
473
+
474
+ module.exports = {
475
+ generateCa: generateCa,
476
+ signClientCert: signClientCert,
477
+ packageP12: packageP12,
478
+ generateCrl: generateCrl,
479
+ algorithmEnvelope: algorithmEnvelope,
480
+ MtlsEngineError: MtlsEngineError,
481
+ };