node-opcua-pki 6.20.0 → 6.21.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.
@@ -0,0 +1,1913 @@
1
+ // packages/node-opcua-pki/lib/toolbox/common.ts
2
+ import assert from "assert";
3
+ function quote(str) {
4
+ return `"${str || ""}"`;
5
+ }
6
+ async function resolvePrivateKeyPassphrase(passphrase) {
7
+ if (passphrase === void 0) {
8
+ return void 0;
9
+ }
10
+ return typeof passphrase === "function" ? await passphrase() : passphrase;
11
+ }
12
+ function adjustDate(params) {
13
+ assert(params instanceof Object);
14
+ params.startDate = params.startDate || /* @__PURE__ */ new Date();
15
+ assert(params.startDate instanceof Date);
16
+ if (params.validityMs !== void 0) {
17
+ if (params.validityMs <= 0) {
18
+ throw new RangeError(`validityMs must be > 0 (got ${params.validityMs})`);
19
+ }
20
+ params.endDate = new Date(params.startDate.getTime() + params.validityMs);
21
+ params.validity = Math.ceil(params.validityMs / 864e5);
22
+ } else {
23
+ params.validity = params.validity || 365;
24
+ params.endDate = new Date(params.startDate.getTime());
25
+ params.endDate.setDate(params.startDate.getDate() + params.validity);
26
+ }
27
+ assert(params.endDate instanceof Date);
28
+ assert(params.startDate instanceof Date);
29
+ }
30
+ function adjustApplicationUri(params) {
31
+ const applicationUri = params.applicationUri || "";
32
+ if (applicationUri.length > 200) {
33
+ throw new Error(`Openssl doesn't support urn with length greater than 200${applicationUri}`);
34
+ }
35
+ }
36
+
37
+ // packages/node-opcua-pki/lib/ca/core/ca_database.ts
38
+ import fs from "fs";
39
+ import path from "path";
40
+ import { convertPEMtoDER, readCertificatePEM } from "node-opcua-crypto";
41
+ function parseOpenSSLDate(dateStr) {
42
+ const raw = dateStr?.split(",")[0] ?? "";
43
+ if (raw.length < 12) return "";
44
+ const yy = parseInt(raw.substring(0, 2), 10);
45
+ const year = yy >= 70 ? 1900 + yy : 2e3 + yy;
46
+ const month = raw.substring(2, 4);
47
+ const day = raw.substring(4, 6);
48
+ const hour = raw.substring(6, 8);
49
+ const min = raw.substring(8, 10);
50
+ const sec = raw.substring(10, 12);
51
+ return `${year}-${month}-${day}T${hour}:${min}:${sec}Z`;
52
+ }
53
+ function formatOpenSSLDate(date) {
54
+ const yy = String(date.getUTCFullYear() % 100).padStart(2, "0");
55
+ const mm = String(date.getUTCMonth() + 1).padStart(2, "0");
56
+ const dd = String(date.getUTCDate()).padStart(2, "0");
57
+ const hh = String(date.getUTCHours()).padStart(2, "0");
58
+ const mi = String(date.getUTCMinutes()).padStart(2, "0");
59
+ const ss = String(date.getUTCSeconds()).padStart(2, "0");
60
+ return `${yy}${mm}${dd}${hh}${mi}${ss}Z`;
61
+ }
62
+ function parseRevocationReason(dateStr) {
63
+ const parts = dateStr?.split(",");
64
+ return parts && parts.length > 1 ? parts[1] : void 0;
65
+ }
66
+ function evenLengthHex(value) {
67
+ const hex = value.toString(16).toUpperCase();
68
+ return hex.length % 2 === 0 ? hex : `0${hex}`;
69
+ }
70
+ function escapeIndexField(value) {
71
+ return value.replace(/[\x00-\x1f\x7f\\]/g, (c) => `\\x${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, "0")}`);
72
+ }
73
+ function assertHexSerial(serial) {
74
+ if (!/^[0-9A-Fa-f]+$/.test(serial)) {
75
+ throw new Error(`Invalid certificate serial number: ${JSON.stringify(serial)}`);
76
+ }
77
+ return serial.toUpperCase();
78
+ }
79
+ var CaDatabase = class {
80
+ #rootDir;
81
+ constructor(rootDir) {
82
+ this.#rootDir = rootDir;
83
+ }
84
+ /** Path to the OpenSSL certificate database file (`index.txt`). */
85
+ get indexFile() {
86
+ return path.join(this.#rootDir, "index.txt");
87
+ }
88
+ /**
89
+ * Parse the OpenSSL `index.txt` certificate database.
90
+ *
91
+ * Each line has tab-separated fields:
92
+ * ```
93
+ * status expiry [revocationDate] serial unknown subject
94
+ * ```
95
+ *
96
+ * - status: `V` (valid), `R` (revoked), `E` (expired)
97
+ * - expiry: `YYMMDDHHmmssZ`
98
+ * - revocationDate: present only for revoked certs
99
+ * - serial: hex string
100
+ * - unknown: always `"unknown"`
101
+ * - subject: X.500 slash-delimited string
102
+ */
103
+ readIndex() {
104
+ const indexPath = this.indexFile;
105
+ if (!fs.existsSync(indexPath)) {
106
+ return [];
107
+ }
108
+ const content = fs.readFileSync(indexPath, "utf-8");
109
+ const lines = content.split("\n").filter((l) => l.trim().length > 0);
110
+ const records = [];
111
+ for (const line of lines) {
112
+ const fields = line.split(" ");
113
+ if (fields.length < 4) continue;
114
+ const statusChar = fields[0];
115
+ const expiryStr = fields[1];
116
+ let serial;
117
+ let subject;
118
+ let revocationDate;
119
+ if (statusChar === "R") {
120
+ revocationDate = fields[2];
121
+ serial = fields[3];
122
+ subject = fields.length >= 6 ? fields[5] : "";
123
+ } else {
124
+ serial = fields[3];
125
+ subject = fields.length >= 6 ? fields[5] : "";
126
+ }
127
+ let status;
128
+ switch (statusChar) {
129
+ case "V":
130
+ status = "valid";
131
+ break;
132
+ case "R":
133
+ status = "revoked";
134
+ break;
135
+ case "E":
136
+ status = "expired";
137
+ break;
138
+ default:
139
+ continue;
140
+ }
141
+ records.push({
142
+ serial,
143
+ status,
144
+ subject,
145
+ expiryDate: parseOpenSSLDate(expiryStr),
146
+ revocationDate: revocationDate ? parseOpenSSLDate(revocationDate) : void 0,
147
+ reason: revocationDate ? parseRevocationReason(revocationDate) : void 0
148
+ });
149
+ }
150
+ return records;
151
+ }
152
+ /** Look up one record by serial number (case-insensitive). */
153
+ findBySerial(serial) {
154
+ const upper = serial.toUpperCase();
155
+ return this.readIndex().find((r) => r.serial.toUpperCase() === upper);
156
+ }
157
+ /**
158
+ * Read a specific issued certificate by serial number.
159
+ *
160
+ * OpenSSL stores signed certificates in the `certs/` directory using
161
+ * the naming convention `<SERIAL>.pem`.
162
+ *
163
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
164
+ * @returns the DER buffer, or `undefined` if not found
165
+ */
166
+ getCertificateBySerial(serial) {
167
+ const upper = serial.toUpperCase();
168
+ const certFile = path.join(this.#rootDir, "certs", `${upper}.pem`);
169
+ if (!fs.existsSync(certFile)) {
170
+ return void 0;
171
+ }
172
+ const pem = readCertificatePEM(certFile);
173
+ return convertPEMtoDER(pem);
174
+ }
175
+ /**
176
+ * Read-increment-write a hex counter file (`serial`/`crlnumber`),
177
+ * returning the value to hand out — matching `openssl ca`'s own
178
+ * behavior: the file holds the *next* value to assign, and is bumped
179
+ * to the following one immediately after being read. A `.old` backup
180
+ * of the pre-bump content is kept, as `openssl` itself does.
181
+ */
182
+ #nextHexCounter(fileName) {
183
+ const counterFile = path.join(this.#rootDir, fileName);
184
+ const current = BigInt(`0x${fs.readFileSync(counterFile, "utf-8").trim()}`);
185
+ fs.copyFileSync(counterFile, `${counterFile}.old`);
186
+ fs.writeFileSync(counterFile, evenLengthHex(current + 1n));
187
+ return evenLengthHex(current);
188
+ }
189
+ /** Hand out the next certificate serial number, bumping the `serial` file. */
190
+ nextSerial() {
191
+ return this.#nextHexCounter("serial");
192
+ }
193
+ /** Hand out the next CRL number, bumping the `crlnumber` file. */
194
+ nextCrlNumber() {
195
+ return this.#nextHexCounter("crlnumber");
196
+ }
197
+ /** Append a newly-issued certificate's `V` (valid) row to `index.txt`. */
198
+ appendIssued(record) {
199
+ const serial = assertHexSerial(record.serial);
200
+ const subject = escapeIndexField(record.subject);
201
+ const line = `V ${formatOpenSSLDate(record.expiryDate)} ${serial} unknown ${subject}
202
+ `;
203
+ fs.appendFileSync(this.indexFile, line);
204
+ }
205
+ /**
206
+ * Rewrite a certificate's `index.txt` row from `V` to `R` (revoked).
207
+ * Throws if the serial is not found, or is already revoked — the same
208
+ * "already revoked" case `openssl ca -revoke` itself rejects.
209
+ */
210
+ markRevoked(serial, revocationDate, reason) {
211
+ const upper = assertHexSerial(serial);
212
+ if (!/^[A-Za-z]+$/.test(reason)) {
213
+ throw new Error(`Invalid CRL reason: ${JSON.stringify(reason)}`);
214
+ }
215
+ const lines = fs.readFileSync(this.indexFile, "utf-8").split("\n").filter((l) => l.trim().length > 0);
216
+ let found = false;
217
+ const rewritten = lines.map((line) => {
218
+ const fields = line.split(" ");
219
+ if (fields.length < 4 || fields[3]?.toUpperCase() !== upper) {
220
+ return line;
221
+ }
222
+ if (fields[0] === "R") {
223
+ throw new Error(`Certificate ${upper} is already revoked`);
224
+ }
225
+ found = true;
226
+ const subject = fields.length >= 6 ? fields[5] : "";
227
+ return `R ${fields[1]} ${formatOpenSSLDate(revocationDate)},${reason} ${upper} unknown ${subject}`;
228
+ });
229
+ if (!found) {
230
+ throw new Error(`Certificate ${upper} not found in the certificate database`);
231
+ }
232
+ fs.writeFileSync(this.indexFile, `${rewritten.join("\n")}
233
+ `);
234
+ }
235
+ /** Store a signed certificate's PEM under `certs/<SERIAL>.pem`, as `openssl ca` does. */
236
+ storeCertificate(serial, pem) {
237
+ const certFile = path.join(this.#rootDir, "certs", `${assertHexSerial(serial)}.pem`);
238
+ fs.writeFileSync(certFile, pem);
239
+ }
240
+ };
241
+
242
+ // packages/node-opcua-pki/lib/ca/backends/native_ca_backend.ts
243
+ import fs3 from "fs";
244
+ import path3 from "path";
245
+ import {
246
+ CertificatePurpose,
247
+ createCertificateFromCsr,
248
+ createCertificateSigningRequest,
249
+ createCrl,
250
+ isCaSigner,
251
+ privateKeyToCryptoKey,
252
+ readPrivateKey,
253
+ Subject,
254
+ x509
255
+ } from "node-opcua-crypto";
256
+
257
+ // packages/node-opcua-pki/lib/toolbox/common2.ts
258
+ import assert2 from "assert";
259
+ import fs2 from "fs";
260
+ import path2 from "path";
261
+ import chalk from "chalk";
262
+
263
+ // packages/node-opcua-pki/lib/toolbox/config.ts
264
+ var g_config = {
265
+ opensslVersion: "unset",
266
+ silent: process.env.VERBOSE ? !process.env.VERBOSE : true,
267
+ force: false
268
+ };
269
+
270
+ // packages/node-opcua-pki/lib/toolbox/debug.ts
271
+ var doDebug = process.env.NODEOPCUAPKIDEBUG || false;
272
+ var displayError = true;
273
+ var displayDebug = !!process.env.NODEOPCUAPKIDEBUG || false;
274
+ function debugLog(...args) {
275
+ if (displayDebug) {
276
+ console.log.apply(null, args);
277
+ }
278
+ }
279
+ function warningLog(...args) {
280
+ console.log.apply(null, args);
281
+ }
282
+
283
+ // packages/node-opcua-pki/lib/toolbox/common2.ts
284
+ function certificateFileExist(certificateFile) {
285
+ if (fs2.existsSync(certificateFile) && !g_config.force) {
286
+ warningLog(
287
+ chalk.yellow(" certificate ") + chalk.cyan(certificateFile) + chalk.yellow(" already exists => do not overwrite")
288
+ );
289
+ return false;
290
+ }
291
+ return true;
292
+ }
293
+ function mkdirRecursiveSync(folder) {
294
+ if (!fs2.existsSync(folder)) {
295
+ debugLog(chalk.white(" .. constructing "), folder);
296
+ fs2.mkdirSync(folder, { recursive: true });
297
+ }
298
+ }
299
+ function restrictPrivateFilePermissions(target, mode) {
300
+ if (process.platform === "win32") {
301
+ return;
302
+ }
303
+ try {
304
+ fs2.chmodSync(target, mode);
305
+ } catch (err) {
306
+ warningLog(chalk.yellow(" could not restrict permissions on "), target, err.message);
307
+ }
308
+ }
309
+ function ensurePrivateDirectory(dir) {
310
+ if (!fs2.existsSync(dir)) {
311
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
312
+ }
313
+ restrictPrivateFilePermissions(dir, 448);
314
+ }
315
+ function isEncryptedPrivateKeyFile(filename) {
316
+ return fs2.readFileSync(filename, "utf-8").includes("-----BEGIN ENCRYPTED PRIVATE KEY-----");
317
+ }
318
+ function makePath(folderName, filename) {
319
+ let s;
320
+ if (filename) {
321
+ s = path2.join(path2.normalize(folderName), filename);
322
+ } else {
323
+ assert2(folderName);
324
+ s = folderName;
325
+ }
326
+ s = s.replace(/\\/g, "/");
327
+ return s;
328
+ }
329
+
330
+ // packages/node-opcua-pki/lib/toolbox/display.ts
331
+ import chalk2 from "chalk";
332
+ function displayTitle(str) {
333
+ if (!g_config.silent) {
334
+ warningLog("");
335
+ warningLog(chalk2.yellowBright(str));
336
+ warningLog(chalk2.yellow(new Array(str.length + 1).join("=")), "\n");
337
+ }
338
+ }
339
+ function displaySubtitle(str) {
340
+ if (!g_config.silent) {
341
+ warningLog("");
342
+ warningLog(` ${chalk2.yellowBright(str)}`);
343
+ warningLog(` ${chalk2.white(new Array(str.length + 1).join("-"))}`, "\n");
344
+ }
345
+ }
346
+ function display(str) {
347
+ if (!g_config.silent) {
348
+ warningLog(` ${str}`);
349
+ }
350
+ }
351
+
352
+ // packages/node-opcua-pki/lib/ca/backends/native_ca_backend.ts
353
+ var CA_CERT_VALIDITY_DAYS = 3650;
354
+ var RSA_SHA256 = { name: "RSASSA-PKCS1-v1_5", hash: { name: "SHA-256" } };
355
+ function signingAlgorithmOf(key) {
356
+ return isCaSigner(key) ? key.algorithm : RSA_SHA256;
357
+ }
358
+ function daysFromNow(notBefore, days) {
359
+ return new Date(notBefore.getTime() + days * 24 * 60 * 60 * 1e3);
360
+ }
361
+ function caSanUri(ca) {
362
+ return `urn:${ca.subject.commonName || "NodeOPCUA-CA"}`;
363
+ }
364
+ function sanFromCsr(csrPem) {
365
+ const request = new x509.Pkcs10CertificateRequest(csrPem);
366
+ const extension = request.getExtension("2.5.29.17");
367
+ const dns = [];
368
+ const ip = [];
369
+ let applicationUri;
370
+ for (const name of extension?.names.toJSON() ?? []) {
371
+ if (name.type === "dns") {
372
+ dns.push(name.value);
373
+ } else if (name.type === "ip") {
374
+ ip.push(name.value);
375
+ } else if (name.type === "url" && applicationUri === void 0) {
376
+ applicationUri = name.value;
377
+ }
378
+ }
379
+ return { dns, ip, applicationUri };
380
+ }
381
+ var REASON_TO_X509_CRL_REASON = {
382
+ unspecified: x509.X509CrlReason.unspecified,
383
+ keyCompromise: x509.X509CrlReason.keyCompromise,
384
+ CACompromise: x509.X509CrlReason.cACompromise,
385
+ affiliationChanged: x509.X509CrlReason.affiliationChanged,
386
+ superseded: x509.X509CrlReason.superseded,
387
+ cessationOfOperation: x509.X509CrlReason.cessationOfOperation,
388
+ certificateHold: x509.X509CrlReason.certificateHold,
389
+ removeFromCRL: x509.X509CrlReason.removeFromCRL
390
+ };
391
+ function toOpenSslSubjectString(subjectName) {
392
+ const parts = [];
393
+ for (const rdn of subjectName.toJSON()) {
394
+ for (const [type, values] of Object.entries(rdn)) {
395
+ for (const value of values) {
396
+ parts.push(`${type}=${value}`);
397
+ }
398
+ }
399
+ }
400
+ return `/${parts.join("/")}`;
401
+ }
402
+ var NativeCaBackend = class {
403
+ /** Nothing to check: this backend spawns no process and needs no tool on PATH. */
404
+ /** Signing goes through `ca._getSigningKey()`, which may be an external signer. */
405
+ supportsExternalSigner = true;
406
+ async preflight() {
407
+ }
408
+ /**
409
+ * Write a CSR for the CA's own key, the `[v3_ca_req]` equivalent. The
410
+ * key comes from the CA rather than from `privateKeyFile`: on a
411
+ * signer-backed CA that file does not exist.
412
+ */
413
+ async generateCaCsr(ca, _caRootDir, _privateKeyFile, csrFile) {
414
+ displayTitle("Generate a certificate request for the CA key");
415
+ const signingKey = await ca._getSigningKey();
416
+ const { csr } = await createCertificateSigningRequest({
417
+ privateKey: signingKey,
418
+ subject: ca.subject.toString(),
419
+ applicationUri: caSanUri(ca),
420
+ purpose: CertificatePurpose.ForCertificateAuthority
421
+ });
422
+ await fs3.promises.writeFile(csrFile, csr);
423
+ }
424
+ async bootstrap(ca) {
425
+ const caRootDir = path3.resolve(ca.rootDir);
426
+ const csrFile = path3.join(caRootDir, "private/cakey.csr");
427
+ await this.generateCaCsr(ca, caRootDir, path3.join(caRootDir, "private/cakey.pem"), csrFile);
428
+ const issuerCA = ca._issuerCA;
429
+ if (issuerCA) {
430
+ displayTitle("Generate CA Certificate (signed by issuer CA)");
431
+ const signWithIssuer = () => this.signSubordinateCsr(issuerCA, csrFile, ca.caCertificate, CA_CERT_VALIDITY_DAYS);
432
+ if (path3.resolve(issuerCA.rootDir) === caRootDir) {
433
+ await signWithIssuer();
434
+ } else {
435
+ await issuerCA._withCaDirectoryLock(signWithIssuer);
436
+ }
437
+ } else {
438
+ displayTitle("Generate CA Certificate (self-signed)");
439
+ const csrPem = await fs3.promises.readFile(csrFile, "utf-8");
440
+ const signingKey = await ca._getSigningKey();
441
+ const request = new x509.Pkcs10CertificateRequest(csrPem);
442
+ const notBefore = /* @__PURE__ */ new Date();
443
+ const { cert } = await createCertificateFromCsr({
444
+ csr: csrPem,
445
+ // the CSR's own parsed subject, so issuer and subject are
446
+ // byte-identical on a self-signed root: re-encoding a string
447
+ // form could differ and break chain building
448
+ issuerName: request.subjectName,
449
+ issuerPublicKey: request.publicKey,
450
+ signingKey,
451
+ signingAlgorithm: signingAlgorithmOf(signingKey),
452
+ notBefore,
453
+ notAfter: daysFromNow(notBefore, CA_CERT_VALIDITY_DAYS),
454
+ purpose: CertificatePurpose.ForCertificateAuthority,
455
+ applicationUri: caSanUri(ca),
456
+ revocation: {
457
+ crlDistributionUrl: ca.crlDistributionUrl,
458
+ ocspResponderUrl: ca.ocspResponderUrl,
459
+ caIssuersUrl: ca.caIssuersUrl
460
+ }
461
+ });
462
+ await fs3.promises.writeFile(ca.caCertificate, cert);
463
+ }
464
+ displaySubtitle("generate initial CRL (Certificate Revocation List)");
465
+ await this.#regenerateCrlLocked(ca, new CaDatabase(ca.rootDir));
466
+ displayTitle("Create Certificate Authority (CA) ---> DONE");
467
+ }
468
+ /** Sign a subordinate CA's request with this CA's key, the `[v3_ca]` equivalent. */
469
+ async signSubordinateCsr(ca, csrFile, certFile, validityDays) {
470
+ const { signingKey, signingAlgorithm, issuerPublicKey, issuerName } = await this.#issuerContext(ca);
471
+ const csrPem = await fs3.promises.readFile(csrFile, "utf-8");
472
+ const db = new CaDatabase(ca.rootDir);
473
+ const serialNumber = db.nextSerial();
474
+ const notBefore = /* @__PURE__ */ new Date();
475
+ const notAfter = daysFromNow(notBefore, validityDays);
476
+ const { cert } = await createCertificateFromCsr({
477
+ csr: csrPem,
478
+ issuerName,
479
+ issuerPublicKey,
480
+ signingKey,
481
+ signingAlgorithm,
482
+ serialNumber,
483
+ notBefore,
484
+ notAfter,
485
+ purpose: CertificatePurpose.ForCertificateAuthority,
486
+ // the subordinate's own SAN, not the issuer's
487
+ ...sanFromCsr(csrPem),
488
+ revocation: {
489
+ crlDistributionUrl: ca.crlDistributionUrl,
490
+ ocspResponderUrl: ca.ocspResponderUrl,
491
+ caIssuersUrl: ca.caIssuersUrl
492
+ }
493
+ });
494
+ await fs3.promises.writeFile(certFile, cert);
495
+ this.#record(db, serialNumber, cert, notAfter);
496
+ }
497
+ /**
498
+ * Self-sign a certificate with a caller-supplied key file and record it
499
+ * in this CA's database: the native equivalent of `openssl req -new`
500
+ * followed by `openssl ca -selfsign`, which likewise applies the
501
+ * end-entity profile and updates `index.txt`.
502
+ */
503
+ async createSelfSignedCertificate(ca, certificateFile, privateKeyFile, params) {
504
+ displaySubtitle("- the certificate signing request");
505
+ const key = await privateKeyToCryptoKey(readPrivateKey(privateKeyFile, await ca._privateKeyPassphrase()));
506
+ const { csr } = await createCertificateSigningRequest({
507
+ privateKey: key,
508
+ subject: params.subject ? new Subject(params.subject).toString() : ca.subject.toString(),
509
+ dns: params.dns,
510
+ ip: params.ip,
511
+ applicationUri: params.applicationUri,
512
+ purpose: CertificatePurpose.ForApplication
513
+ });
514
+ displaySubtitle("- creating the self-signed certificate");
515
+ const request = new x509.Pkcs10CertificateRequest(csr);
516
+ const db = new CaDatabase(ca.rootDir);
517
+ const serialNumber = db.nextSerial();
518
+ const notBefore = params.startDate ?? /* @__PURE__ */ new Date();
519
+ const notAfter = params.endDate ?? daysFromNow(notBefore, params.validity ?? 365);
520
+ const { cert } = await createCertificateFromCsr({
521
+ csr,
522
+ issuerName: request.subjectName,
523
+ issuerPublicKey: request.publicKey,
524
+ signingKey: key,
525
+ signingAlgorithm: RSA_SHA256,
526
+ serialNumber,
527
+ notBefore,
528
+ notAfter,
529
+ purpose: CertificatePurpose.ForApplication,
530
+ ...sanFromCsr(csr)
531
+ });
532
+ await fs3.promises.writeFile(certificateFile, cert);
533
+ this.#record(db, serialNumber, cert, notAfter);
534
+ }
535
+ /** `certs/<SERIAL>.pem` plus the `V` row, exactly as `openssl ca` writes them. */
536
+ #record(db, serialNumber, certPem, notAfter) {
537
+ db.storeCertificate(serialNumber, certPem);
538
+ db.appendIssued({
539
+ serial: serialNumber,
540
+ expiryDate: notAfter,
541
+ subject: toOpenSslSubjectString(new x509.X509Certificate(certPem).subjectName)
542
+ });
543
+ }
544
+ /**
545
+ * The CA's signing key and issuer identity, resolved fresh on every
546
+ * call and never cached across operations. The identity is read back
547
+ * from the CA certificate on disk so that the issuer field of anything
548
+ * this CA signs is byte-identical to that certificate's subject.
549
+ */
550
+ async #issuerContext(ca) {
551
+ const signingKey = await ca._getSigningKey();
552
+ const caCertPem = await fs3.promises.readFile(ca.caCertificate, "utf-8");
553
+ const caCert = new x509.X509Certificate(caCertPem);
554
+ return {
555
+ signingKey,
556
+ signingAlgorithm: signingAlgorithmOf(signingKey),
557
+ issuerPublicKey: caCert.publicKey,
558
+ issuerName: caCert.subjectName
559
+ };
560
+ }
561
+ async signEndEntityCsr(ca, certificate, csr, params, sanOverride) {
562
+ const { signingKey, signingAlgorithm, issuerPublicKey, issuerName } = await this.#issuerContext(ca);
563
+ const db = new CaDatabase(ca.rootDir);
564
+ const serialNumber = db.nextSerial();
565
+ const csrPem = await fs3.promises.readFile(csr, "utf-8");
566
+ const notBefore = params.startDate ?? /* @__PURE__ */ new Date();
567
+ const notAfter = params.endDate ?? new Date(notBefore.getTime() + (params.validity ?? 365) * 24 * 60 * 60 * 1e3);
568
+ const { cert } = await createCertificateFromCsr({
569
+ csr: csrPem,
570
+ issuerName,
571
+ issuerPublicKey,
572
+ signingKey,
573
+ signingAlgorithm,
574
+ serialNumber,
575
+ notBefore,
576
+ notAfter,
577
+ purpose: CertificatePurpose.ForApplication,
578
+ dns: sanOverride.dns,
579
+ ip: sanOverride.ip,
580
+ applicationUri: sanOverride.applicationUri,
581
+ revocation: {
582
+ crlDistributionUrl: ca.crlDistributionUrl,
583
+ ocspResponderUrl: ca.ocspResponderUrl,
584
+ caIssuersUrl: ca.caIssuersUrl
585
+ }
586
+ });
587
+ await fs3.promises.writeFile(certificate, cert);
588
+ this.#record(db, serialNumber, cert, notAfter);
589
+ }
590
+ async #regenerateCrlLocked(ca, db) {
591
+ const { signingKey, signingAlgorithm, issuerPublicKey, issuerName } = await this.#issuerContext(ca);
592
+ const crlNumber = db.nextCrlNumber();
593
+ const entries = db.readIndex().filter((r) => r.status === "revoked").map((r) => ({
594
+ serialNumber: r.serial,
595
+ revocationDate: r.revocationDate ? new Date(r.revocationDate) : /* @__PURE__ */ new Date(),
596
+ reason: r.reason ? REASON_TO_X509_CRL_REASON[r.reason] : void 0
597
+ }));
598
+ const { crl } = await createCrl({
599
+ issuerName,
600
+ issuerPublicKey,
601
+ signingKey,
602
+ signingAlgorithm,
603
+ crlNumber: BigInt(`0x${crlNumber}`),
604
+ entries
605
+ });
606
+ await fs3.promises.writeFile(ca.revocationList, crl);
607
+ const der = new x509.X509Crl(crl).rawData;
608
+ await fs3.promises.writeFile(ca.revocationListDER, Buffer.from(der));
609
+ }
610
+ async regenerateCrl(ca) {
611
+ const db = new CaDatabase(ca.rootDir);
612
+ await this.#regenerateCrlLocked(ca, db);
613
+ }
614
+ async revoke(ca, certificate, reason) {
615
+ const certPem = await fs3.promises.readFile(certificate, "utf-8");
616
+ const cert = new x509.X509Certificate(certPem);
617
+ const db = new CaDatabase(ca.rootDir);
618
+ db.markRevoked(cert.serialNumber, /* @__PURE__ */ new Date(), reason);
619
+ await this.#regenerateCrlLocked(ca, db);
620
+ }
621
+ };
622
+
623
+ // packages/node-opcua-pki/lib/misc/subject.ts
624
+ import { Subject as Subject2 } from "node-opcua-crypto";
625
+
626
+ // packages/node-opcua-pki/lib/ca/core/certificate_authority_core.ts
627
+ import assert3 from "assert";
628
+ import fs4 from "fs";
629
+ import os from "os";
630
+ import path4 from "path";
631
+ import { withLock } from "@ster5/global-mutex";
632
+ import chalk3 from "chalk";
633
+ import {
634
+ CertificatePurpose as CertificatePurpose2,
635
+ certificateMatchesPrivateKey,
636
+ convertPEMtoDER as convertPEMtoDER2,
637
+ createCertificateSigningRequest as createCertificateSigningRequest2,
638
+ createPfx,
639
+ exploreCertificate,
640
+ exploreCertificateSigningRequest,
641
+ generatePrivateKeyFile,
642
+ privateKeyToCryptoKey as privateKeyToCryptoKey2,
643
+ readCertificatePEM as readCertificatePEM2,
644
+ readCertificateSigningRequest,
645
+ readPrivateKey as readPrivateKey2,
646
+ Subject as Subject3,
647
+ toPem,
648
+ verifyCertificateSignature,
649
+ writePrivateKeyFile,
650
+ x509 as x5092
651
+ } from "node-opcua-crypto";
652
+
653
+ // packages/node-opcua-pki/lib/ca/templates/ca_config_template.cnf.ts
654
+ var config = `#.........DO NOT MODIFY BY HAND .........................
655
+ [ ca ]
656
+ default_ca = CA_default
657
+ [ CA_default ]
658
+ dir = "%%ROOT_FOLDER%%" # the main CA folder (quoted: see renderCaConfig)
659
+ certs = $dir/certs # where to store certificates
660
+ new_certs_dir = $dir/certs #
661
+ database = $dir/index.txt # the certificate database
662
+ serial = $dir/serial # the serial number counter
663
+ certificate = $dir/public/cacert.pem # The root CA certificate
664
+ private_key = $dir/private/cakey.pem # the CA private key
665
+ x509_extensions = usr_cert #
666
+ default_days = 3650 # default validity : 10 years
667
+
668
+ # default_md = sha1
669
+
670
+ default_md = sha256 # The default digest algorithm
671
+
672
+ preserve = no
673
+ policy = policy_match
674
+ # randfile = $dir/random.rnd
675
+ # default_startdate = YYMMDDHHMMSSZ
676
+ # default_enddate = YYMMDDHHMMSSZ
677
+ crl_dir = $dir/crl
678
+ crl_extensions = crl_ext
679
+ crl = $dir/crl/revocation_list.crl # the Revocation list
680
+ crlnumber = $dir/crlnumber # CRL number file
681
+ default_crl_days = 30
682
+ default_crl_hours = 24
683
+ #msie_hack
684
+
685
+ [ policy_match ]
686
+ countryName = optional
687
+ stateOrProvinceName = optional
688
+ localityName = optional
689
+ organizationName = optional
690
+ organizationalUnitName = optional
691
+ commonName = optional
692
+ emailAddress = optional
693
+
694
+ [ req ]
695
+ default_bits = 4096 # Size of keys
696
+ default_keyfile = key.pem # name of generated keys
697
+ distinguished_name = req_distinguished_name
698
+ attributes = req_attributes
699
+ x509_extensions = v3_ca
700
+ #input_password
701
+ #output_password
702
+ string_mask = nombstr # permitted characters
703
+ req_extensions = v3_req
704
+
705
+ [ req_distinguished_name ]
706
+
707
+ #0 countryName = Country Name (2 letter code)
708
+ # countryName_default = FR
709
+ # countryName_min = 2
710
+ # countryName_max = 2
711
+ # stateOrProvinceName = State or Province Name (full name)
712
+ # stateOrProvinceName_default = Ile de France
713
+ # localityName = Locality Name (city, district)
714
+ # localityName_default = Paris
715
+ organizationName = Organization Name (company)
716
+ organizationName_default = NodeOPCUA
717
+ # organizationalUnitName = Organizational Unit Name (department, division)
718
+ # organizationalUnitName_default = R&D
719
+ commonName = Common Name (hostname, FQDN, IP, or your name)
720
+ commonName_max = 256
721
+ commonName_default = NodeOPCUA
722
+ # emailAddress = Email Address
723
+ # emailAddress_max = 40
724
+ # emailAddress_default = node-opcua (at) node-opcua (dot) com
725
+
726
+ [ req_attributes ]
727
+ #challengePassword = A challenge password
728
+ #challengePassword_min = 4
729
+ #challengePassword_max = 20
730
+ #unstructuredName = An optional company name
731
+ [ usr_cert ]
732
+ basicConstraints = critical, CA:FALSE
733
+ subjectKeyIdentifier = hash
734
+ authorityKeyIdentifier = keyid,issuer:always
735
+ #authorityKeyIdentifier = keyid
736
+ subjectAltName = $ENV::ALTNAME
737
+ # issuerAltName = issuer:copy
738
+ nsComment = ''OpenSSL Generated Certificate''
739
+ #nsCertType = client, email, objsign for ''everything including object signing''
740
+ #nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem
741
+ #nsBaseUrl =
742
+ #nsRenewalUrl =
743
+ #nsCaPolicyUrl =
744
+ #nsSslServerName =
745
+ keyUsage = critical, digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement
746
+ extendedKeyUsage = critical,serverAuth ,clientAuth
747
+ {{#CDP_URL}}crlDistributionPoints = URI:$ENV::CDP_URL
748
+ {{/CDP_URL}}{{#AIA_VALUE}}authorityInfoAccess = $ENV::AIA_VALUE
749
+ {{/AIA_VALUE}}
750
+ [ v3_req ]
751
+ basicConstraints = critical, CA:FALSE
752
+ keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, keyAgreement
753
+ extendedKeyUsage = critical,serverAuth ,clientAuth
754
+ subjectAltName = $ENV::ALTNAME
755
+ nsComment = "CA Generated by Node-OPCUA Certificate utility using openssl"
756
+ [ v3_ca_req ]
757
+ subjectKeyIdentifier = hash
758
+ basicConstraints = CA:TRUE
759
+ keyUsage = critical, cRLSign, keyCertSign
760
+ subjectAltName = $ENV::ALTNAME
761
+ nsComment = "CA CSR generated by Node-OPCUA Certificate utility using openssl"
762
+ [ v3_ca ]
763
+ subjectKeyIdentifier = hash
764
+ authorityKeyIdentifier = keyid:always,issuer:always
765
+ basicConstraints = CA:TRUE
766
+ keyUsage = critical, cRLSign, keyCertSign
767
+ subjectAltName = $ENV::ALTNAME
768
+ nsComment = "CA Certificate generated by Node-OPCUA Certificate utility using openssl"
769
+ #nsCertType = sslCA, emailCA
770
+ #issuerAltName = issuer:copy
771
+ #obj = DER:02:03
772
+ {{#CDP_URL}}crlDistributionPoints = URI:$ENV::CDP_URL
773
+ {{/CDP_URL}}{{#AIA_VALUE}}authorityInfoAccess = $ENV::AIA_VALUE
774
+ {{/AIA_VALUE}}[ v3_selfsigned]
775
+ basicConstraints = critical, CA:FALSE
776
+ keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, keyAgreement
777
+ extendedKeyUsage = critical,serverAuth ,clientAuth
778
+ nsComment = "Self-signed certificate, generated by NodeOPCUA"
779
+ subjectAltName = $ENV::ALTNAME
780
+
781
+ [ crl_ext ]
782
+ #issuerAltName = issuer:copy
783
+ authorityKeyIdentifier = keyid:always,issuer:always
784
+ #authorityInfoAccess = @issuer_info`;
785
+ var ca_config_template_cnf_default = config;
786
+
787
+ // packages/node-opcua-pki/lib/ca/core/certificate_authority_core.ts
788
+ var defaultSubject = "/C=FR/ST=IDF/L=Paris/O=Local NODE-OPCUA Certificate Authority/CN=NodeOPCUA-CA";
789
+ var configurationFileTemplate = ca_config_template_cnf_default;
790
+ function escapeOpensslConfDoubleQuoted(value) {
791
+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
792
+ }
793
+ function renderCaConfig(caRootDir) {
794
+ return configurationFileTemplate.replace(/%%ROOT_FOLDER%%/, escapeOpensslConfDoubleQuoted(makePath(caRootDir)));
795
+ }
796
+ var config2 = {
797
+ certificateDir: "INVALID",
798
+ forceCA: false,
799
+ pkiDir: "INVALID"
800
+ };
801
+ var CA_LOCK_MAX_WAIT_MS = 5 * 6e4;
802
+ var CA_LOCK_RETRY = { minTimeout: 20, maxTimeout: 250 };
803
+ function octetStringToIpAddress(a) {
804
+ return parseInt(a.substring(0, 2), 16).toString() + "." + parseInt(a.substring(2, 4), 16).toString() + "." + parseInt(a.substring(4, 6), 16).toString() + "." + parseInt(a.substring(6, 8), 16).toString();
805
+ }
806
+ assert3(octetStringToIpAddress("c07b9179") === "192.123.145.121");
807
+ function validateRevocationUrl(url, fieldName) {
808
+ if (url === void 0) {
809
+ return void 0;
810
+ }
811
+ if (url === "") {
812
+ throw new Error(`${fieldName} must not be empty \u2014 pass undefined to disable the extension`);
813
+ }
814
+ let parsed;
815
+ try {
816
+ parsed = new URL(url);
817
+ } catch {
818
+ throw new Error(`${fieldName} is not a valid URL: ${url}`);
819
+ }
820
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
821
+ throw new Error(`${fieldName} must use http: or https: (got ${parsed.protocol} in ${url})`);
822
+ }
823
+ if (!parsed.pathname || parsed.pathname === "/") {
824
+ throw new Error(`${fieldName} must include a path component (got ${url})`);
825
+ }
826
+ const isLoopback = parsed.hostname === "localhost" || parsed.hostname === "::1" || parsed.hostname.startsWith("127.");
827
+ if (isLoopback) {
828
+ console.warn(
829
+ `[node-opcua-pki] ${fieldName} points at loopback (${url}) \u2014 certificates issued with this URL will be unreachable from any other host.`
830
+ );
831
+ }
832
+ return url;
833
+ }
834
+ var CertificateAuthorityCore = class {
835
+ /** RSA key size used when generating the CA private key. */
836
+ keySize;
837
+ /** Root filesystem path of the CA directory structure. */
838
+ location;
839
+ /** X.500 subject of the CA certificate. */
840
+ subject;
841
+ /** @internal Parent CA (undefined for root CAs). */
842
+ _issuerCA;
843
+ /** @internal Configured CDP / AIA URLs (US-202). */
844
+ _crlDistributionUrl;
845
+ _ocspResponderUrl;
846
+ _caIssuersUrl;
847
+ #privateKeyPassphrase;
848
+ /** resolved once (see `privateKeyPassphrase`); `#passphraseResolved` distinguishes "none" from "not yet" */
849
+ #resolvedPassphrase;
850
+ #passphraseResolved = false;
851
+ /** Signing backend: `openssl` shells out to the CLI, `native` signs in-process. */
852
+ #backend;
853
+ /** External signing key (HSM/KMS), when one was supplied instead of a key file. */
854
+ #signer;
855
+ /** Read access to `index.txt` / `certs/<SERIAL>.pem`. */
856
+ #db;
857
+ constructor(options) {
858
+ assert3(Object.prototype.hasOwnProperty.call(options, "location"));
859
+ assert3(Object.prototype.hasOwnProperty.call(options, "keySize"));
860
+ this.location = options.location;
861
+ this.keySize = options.keySize || 2048;
862
+ this.subject = new Subject3(options.subject || defaultSubject);
863
+ this._issuerCA = options.issuerCA;
864
+ this.#privateKeyPassphrase = options.privateKeyPassphrase;
865
+ this.#signer = options.signer;
866
+ if (options.signer) {
867
+ const algorithm = options.signer.algorithm;
868
+ if (algorithm.name !== "RSASSA-PKCS1-v1_5" && algorithm.name !== "ECDSA") {
869
+ throw new Error(
870
+ `CertificateAuthority: signer algorithm ${algorithm.name} is not supported - use RSASSA-PKCS1-v1_5 or ECDSA.`
871
+ );
872
+ }
873
+ if (algorithm.name === "ECDSA" && !algorithm.namedCurve) {
874
+ throw new Error(
875
+ "CertificateAuthority: an ECDSA signer must declare its namedCurve (P-256, P-384 or P-521) - importing the signer's public key needs the curve, and an SPKI import cannot infer it."
876
+ );
877
+ }
878
+ }
879
+ if (options.signer && !options.backend.supportsExternalSigner) {
880
+ throw new Error(
881
+ "CertificateAuthority: this backend cannot sign with an external signer - it loads its key from a file. Use a backend that supports one, such as NativeCaBackend."
882
+ );
883
+ }
884
+ this.#backend = options.backend;
885
+ this.#db = new CaDatabase(this.location);
886
+ if (options.crlDistributionUrl !== void 0) {
887
+ this.setCrlDistributionUrl(options.crlDistributionUrl);
888
+ }
889
+ if (options.ocspResponderUrl !== void 0) {
890
+ this.setOcspResponderUrl(options.ocspResponderUrl);
891
+ }
892
+ if (options.caIssuersUrl !== void 0) {
893
+ this.setCaIssuersUrl(options.caIssuersUrl);
894
+ }
895
+ }
896
+ /**
897
+ * Public URL where the CRL produced by this CA is reachable, or
898
+ * `undefined` if no CDP extension should be emitted on issued certs.
899
+ */
900
+ get crlDistributionUrl() {
901
+ return this._crlDistributionUrl;
902
+ }
903
+ /**
904
+ * Public URL of the OCSP responder, or `undefined` if no AIA OCSP
905
+ * leg should be emitted on issued certs.
906
+ */
907
+ get ocspResponderUrl() {
908
+ return this._ocspResponderUrl;
909
+ }
910
+ /**
911
+ * Public URL where the issuer's certificate can be fetched, or
912
+ * `undefined` if no AIA caIssuers leg should be emitted.
913
+ */
914
+ get caIssuersUrl() {
915
+ return this._caIssuersUrl;
916
+ }
917
+ /**
918
+ * Configure the URL embedded as `crlDistributionPoints` in every
919
+ * subsequently-issued certificate. Pass `undefined` to disable
920
+ * the extension entirely. Validated synchronously — throws on
921
+ * empty string, non-http(s) protocol, missing path. Warns (does
922
+ * not throw) when the URL points at loopback.
923
+ *
924
+ * @see US-202
925
+ */
926
+ setCrlDistributionUrl(url) {
927
+ this._crlDistributionUrl = validateRevocationUrl(url, "crlDistributionUrl");
928
+ }
929
+ /**
930
+ * Configure the OCSP responder URL embedded as the `OCSP` leg of
931
+ * the `authorityInfoAccess` extension on every subsequently-issued
932
+ * certificate. Pass `undefined` to disable.
933
+ *
934
+ * @see US-202
935
+ */
936
+ setOcspResponderUrl(url) {
937
+ this._ocspResponderUrl = validateRevocationUrl(url, "ocspResponderUrl");
938
+ }
939
+ /**
940
+ * Configure the caIssuers URL embedded as the `caIssuers` leg of
941
+ * the `authorityInfoAccess` extension on every subsequently-issued
942
+ * certificate. Pass `undefined` to disable.
943
+ *
944
+ * @see US-202
945
+ */
946
+ setCaIssuersUrl(url) {
947
+ this._caIssuersUrl = validateRevocationUrl(url, "caIssuersUrl");
948
+ }
949
+ /** Absolute path to the CA root directory (alias for {@link location}). */
950
+ get rootDir() {
951
+ return this.location;
952
+ }
953
+ /** Path to the OpenSSL configuration file (`conf/caconfig.cnf`). */
954
+ get configFile() {
955
+ return path4.normalize(path4.join(this.rootDir, "./conf/caconfig.cnf"));
956
+ }
957
+ /** Path to the CA private key (`private/cakey.pem`); may be passphrase-encrypted, see {@link getPrivateKey}. */
958
+ get privateKey() {
959
+ return path4.join(path4.resolve(this.rootDir), "private/cakey.pem");
960
+ }
961
+ /**
962
+ * The CA private key, decrypted with the configured `privateKeyPassphrase`
963
+ * if it is encrypted. Fails closed (`PrivateKeyPassphraseRequiredError`)
964
+ * on an encrypted key with no or the wrong passphrase.
965
+ */
966
+ async getPrivateKey() {
967
+ this.#assertKeyIsOnDisk("getPrivateKey");
968
+ return readPrivateKey2(this.privateKey, await this._privateKeyPassphrase());
969
+ }
970
+ /**
971
+ * True when this CA signs with an external {@link CaSigner} (HSM/KMS)
972
+ * rather than with `private/cakey.pem`. There is then no private key
973
+ * file on disk, and never was one.
974
+ */
975
+ get hasExternalSigner() {
976
+ return this.#signer !== void 0;
977
+ }
978
+ /**
979
+ * Does `cert` certify the key this CA signs with? With the key on disk
980
+ * that is a private-key match; with a signer there is no private key to
981
+ * match, so compare the certified public key against the signer's own -
982
+ * the same question, asked the only way an HSM allows.
983
+ */
984
+ async #certificateMatchesOurKey(certPem, certDer) {
985
+ if (this.#signer) {
986
+ const ours = Buffer.from(await this.#signer.getPublicKey());
987
+ const certified = Buffer.from(new x5092.X509Certificate(certPem).publicKey.rawData);
988
+ return ours.equals(certified);
989
+ }
990
+ return certificateMatchesPrivateKey(certDer, await this.getPrivateKey());
991
+ }
992
+ /** Reject the key-file-only operations up front, rather than failing on a missing file later. */
993
+ #assertKeyIsOnDisk(what) {
994
+ if (this.#signer) {
995
+ throw new Error(
996
+ `CertificateAuthority.${what} is not available on a signer-backed CA: the private key lives in the signer (HSM/KMS) and is never written to disk.`
997
+ );
998
+ }
999
+ }
1000
+ /**
1001
+ * @internal The key every signing operation goes through. An injected
1002
+ * {@link CaSigner} is returned as-is; otherwise the on-disk key is read
1003
+ * (and decrypted) and handed over as a plain `CryptoKey`. Both are
1004
+ * accepted by the `node-opcua-crypto` signing primitives, so callers
1005
+ * never branch on which one they got.
1006
+ */
1007
+ async _getSigningKey() {
1008
+ if (this.#signer) {
1009
+ return this.#signer;
1010
+ }
1011
+ return privateKeyToCryptoKey2(await this.getPrivateKey());
1012
+ }
1013
+ /**
1014
+ * Enable, disable, or rotate the passphrase protecting `private/cakey.pem`
1015
+ * (temp file + atomic rename, temp file removed on failure). Only
1016
+ * rewrites the file: construct a new `CertificateAuthority` with the new
1017
+ * passphrase to continue using it.
1018
+ */
1019
+ async reencryptPrivateKey(oldPassphrase, newPassphrase) {
1020
+ this.#assertKeyIsOnDisk("reencryptPrivateKey");
1021
+ const oldPass = await resolvePrivateKeyPassphrase(oldPassphrase);
1022
+ const newPass = await resolvePrivateKeyPassphrase(newPassphrase);
1023
+ const key = readPrivateKey2(this.privateKey, oldPass);
1024
+ await this.#rewritePrivateKeyFile(key, newPass);
1025
+ }
1026
+ async #rewritePrivateKeyFile(privateKey, passphrase) {
1027
+ const tmpFilename = `${this.privateKey}.${process.pid}-${Date.now()}.tmp`;
1028
+ try {
1029
+ await writePrivateKeyFile(tmpFilename, privateKey, { passphrase });
1030
+ await fs4.promises.rename(tmpFilename, this.privateKey);
1031
+ } finally {
1032
+ await fs4.promises.rm(tmpFilename, { force: true });
1033
+ }
1034
+ }
1035
+ /** @internal resolve the configured passphrase, at most once per instance */
1036
+ async _privateKeyPassphrase() {
1037
+ if (!this.#passphraseResolved) {
1038
+ this.#resolvedPassphrase = await resolvePrivateKeyPassphrase(this.#privateKeyPassphrase);
1039
+ this.#passphraseResolved = true;
1040
+ }
1041
+ return this.#resolvedPassphrase;
1042
+ }
1043
+ /**
1044
+ * @internal On an existing key: encrypt it in place if a passphrase is
1045
+ * configured and it is still plaintext (secure by default: the option
1046
+ * means "protect this key", not "ignore me"), then read it back so a
1047
+ * wrong or missing passphrase fails initialize() closed rather than the
1048
+ * first signing operation.
1049
+ */
1050
+ async _ensurePrivateKeyProtection() {
1051
+ if (this.#signer || !fs4.existsSync(this.privateKey)) {
1052
+ return;
1053
+ }
1054
+ if (this.#privateKeyPassphrase !== void 0 && !isEncryptedPrivateKeyFile(this.privateKey)) {
1055
+ warningLog("CertificateAuthority: private key is plaintext but a passphrase is configured; encrypting it in place");
1056
+ const plaintextKey = readPrivateKey2(this.privateKey);
1057
+ await this.#rewritePrivateKeyFile(plaintextKey, await this._privateKeyPassphrase());
1058
+ }
1059
+ await this.getPrivateKey();
1060
+ }
1061
+ /**
1062
+ * Acquire a file-based lock on this CA's directory for the duration of
1063
+ * `action` — serializes every operation that mutates the certificate
1064
+ * database (`index.txt`, `serial`, `crlnumber`, `certs/`,
1065
+ * `crl/revocation_list.*`) or the CA's own key/certificate, so
1066
+ * concurrent calls on one `CertificateAuthority` (or two instances
1067
+ * pointed at the same directory, in this or another process) cannot
1068
+ * interleave. Mirrors `CertificateManager.withLock2`.
1069
+ *
1070
+ * Only ever call this from a top-level public operation — nested calls
1071
+ * on the same instance would deadlock, since the underlying file lock
1072
+ * is not reentrant.
1073
+ *
1074
+ * The wait is bounded: a waiter gives up (throws) after
1075
+ * `CA_LOCK_MAX_WAIT_MS`. Without a bound, a holder whose openssl child
1076
+ * hangs would block every CA operation in every process forever and
1077
+ * silently — the lock library's keepalive keeps refreshing the lock
1078
+ * file's mtime as long as the holder process is alive, so stale-lock
1079
+ * recovery never fires for a live-but-stuck holder. A dead holder's
1080
+ * lock goes stale (default 2 minutes) and is taken over well within
1081
+ * this bound.
1082
+ */
1083
+ async #withCaLock(action) {
1084
+ const lockFileName = path4.join(this.rootDir, ".ca.lock");
1085
+ return withLock(
1086
+ {
1087
+ fileToLock: lockFileName,
1088
+ retries: { forever: true, maxRetryTime: CA_LOCK_MAX_WAIT_MS, ...CA_LOCK_RETRY }
1089
+ },
1090
+ action
1091
+ );
1092
+ }
1093
+ /**
1094
+ * @internal Run `action` under this CA's directory lock. For the one
1095
+ * legitimate cross-instance use: a subordinate CA's bootstrap signs its
1096
+ * certificate with `openssl x509 -CAserial`, which read-increment-writes
1097
+ * THIS issuer's `serial` file, and must therefore hold this issuer's
1098
+ * lock (ordering is always subordinate -> issuer, so no cycle).
1099
+ */
1100
+ async _withCaDirectoryLock(action) {
1101
+ return this.#withCaLock(action);
1102
+ }
1103
+ /** Path to the CA certificate in PEM format (`public/cacert.pem`). */
1104
+ get caCertificate() {
1105
+ return makePath(this.rootDir, "./public/cacert.pem");
1106
+ }
1107
+ /**
1108
+ * Path to the issuer certificate chain (`public/issuer_chain.pem`).
1109
+ *
1110
+ * This file is created by {@link installCACertificate} when the
1111
+ * provided cert file contains additional issuer certificates
1112
+ * (e.g. intermediate + root). It is appended to signed certs
1113
+ * by {@link constructCertificateChain} to produce a full chain
1114
+ * per OPC UA Part 6 §6.2.6.
1115
+ */
1116
+ get issuerCertificateChain() {
1117
+ return makePath(this.rootDir, "./public/issuer_chain.pem");
1118
+ }
1119
+ /**
1120
+ * Path to the current Certificate Revocation List in DER format.
1121
+ * (`crl/revocation_list.der`)
1122
+ */
1123
+ get revocationListDER() {
1124
+ return makePath(this.rootDir, "./crl/revocation_list.der");
1125
+ }
1126
+ /**
1127
+ * Path to the current Certificate Revocation List in PEM format.
1128
+ * (`crl/revocation_list.crl`)
1129
+ */
1130
+ get revocationList() {
1131
+ return makePath(this.rootDir, "./crl/revocation_list.crl");
1132
+ }
1133
+ /**
1134
+ * Path to the concatenated CA certificate + CRL file.
1135
+ * Used by OpenSSL for CRL-based verification.
1136
+ */
1137
+ get caCertificateWithCrl() {
1138
+ return makePath(this.rootDir, "./public/cacertificate_with_crl.pem");
1139
+ }
1140
+ // ---------------------------------------------------------------
1141
+ // Buffer-based accessors (US-059)
1142
+ // ---------------------------------------------------------------
1143
+ /**
1144
+ * Return the CA certificate as a DER-encoded buffer.
1145
+ *
1146
+ * @throws if the CA certificate file does not exist
1147
+ * (call {@link initialize} first).
1148
+ */
1149
+ getCACertificateDER() {
1150
+ const pem = readCertificatePEM2(this.caCertificate);
1151
+ return convertPEMtoDER2(pem);
1152
+ }
1153
+ /**
1154
+ * Return the CA certificate as a PEM-encoded string.
1155
+ *
1156
+ * @throws if the CA certificate file does not exist
1157
+ * (call {@link initialize} first).
1158
+ */
1159
+ getCACertificatePEM() {
1160
+ const raw = readCertificatePEM2(this.caCertificate);
1161
+ const beginMarker = "-----BEGIN CERTIFICATE-----";
1162
+ const idx = raw.indexOf(beginMarker);
1163
+ if (idx > 0) {
1164
+ return raw.substring(idx);
1165
+ }
1166
+ return raw;
1167
+ }
1168
+ /**
1169
+ * Return the current Certificate Revocation List as a
1170
+ * DER-encoded buffer.
1171
+ *
1172
+ * Returns an empty buffer if no CRL has been generated yet.
1173
+ */
1174
+ getCRLDER() {
1175
+ const crlPath = this.revocationListDER;
1176
+ if (!fs4.existsSync(crlPath)) {
1177
+ return Buffer.alloc(0);
1178
+ }
1179
+ return fs4.readFileSync(crlPath);
1180
+ }
1181
+ /**
1182
+ * Return the current Certificate Revocation List as a
1183
+ * PEM-encoded string.
1184
+ *
1185
+ * Returns an empty string if no CRL has been generated yet.
1186
+ */
1187
+ getCRLPEM() {
1188
+ const crlPath = this.revocationList;
1189
+ if (!fs4.existsSync(crlPath)) {
1190
+ return "";
1191
+ }
1192
+ const raw = fs4.readFileSync(crlPath, "utf-8");
1193
+ const beginMarker = "-----BEGIN X509 CRL-----";
1194
+ const idx = raw.indexOf(beginMarker);
1195
+ if (idx > 0) {
1196
+ return raw.substring(idx);
1197
+ }
1198
+ return raw;
1199
+ }
1200
+ // ---------------------------------------------------------------
1201
+ // Certificate database API (US-057)
1202
+ // ---------------------------------------------------------------
1203
+ /**
1204
+ * Return a list of all issued certificates recorded in the
1205
+ * OpenSSL `index.txt` database.
1206
+ *
1207
+ * Each entry includes the serial number, subject, status,
1208
+ * expiry date, and (for revoked certs) the revocation date.
1209
+ */
1210
+ getIssuedCertificates() {
1211
+ return this.#db.readIndex();
1212
+ }
1213
+ /**
1214
+ * Return the total number of certificates recorded in
1215
+ * `index.txt`.
1216
+ */
1217
+ getIssuedCertificateCount() {
1218
+ return this.#db.readIndex().length;
1219
+ }
1220
+ /**
1221
+ * Return the status of a certificate by its serial number.
1222
+ *
1223
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
1224
+ * @returns `"valid"`, `"revoked"`, `"expired"`, or
1225
+ * `undefined` if not found
1226
+ */
1227
+ getCertificateStatus(serial) {
1228
+ return this.#db.findBySerial(serial)?.status;
1229
+ }
1230
+ /**
1231
+ * Read a specific issued certificate by serial number and
1232
+ * return its content as a DER-encoded buffer.
1233
+ *
1234
+ * OpenSSL stores signed certificates in the `certs/`
1235
+ * directory using the naming convention `<SERIAL>.pem`.
1236
+ *
1237
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
1238
+ * @returns the DER buffer, or `undefined` if not found
1239
+ */
1240
+ getCertificateBySerial(serial) {
1241
+ return this.#db.getCertificateBySerial(serial);
1242
+ }
1243
+ /**
1244
+ * Path to the OpenSSL certificate database file.
1245
+ */
1246
+ get indexFile() {
1247
+ return this.#db.indexFile;
1248
+ }
1249
+ // ---------------------------------------------------------------
1250
+ // Buffer-based CA operations (US-058)
1251
+ // ---------------------------------------------------------------
1252
+ /**
1253
+ * Sign a DER-encoded Certificate Signing Request and return
1254
+ * the signed certificate as a DER buffer.
1255
+ *
1256
+ * This method handles temp-file creation and cleanup
1257
+ * internally so that callers can work with in-memory
1258
+ * buffers only.
1259
+ *
1260
+ * The CA can override fields from the CSR by passing
1261
+ * `options.dns`, `options.ip`, `options.applicationUri`,
1262
+ * `options.startDate`, or `options.subject`.
1263
+ *
1264
+ * @param csrDer - the CSR as a DER-encoded buffer
1265
+ * @param options - signing options and CA overrides
1266
+ * @returns the signed certificate as a DER-encoded buffer
1267
+ */
1268
+ async signCertificateRequestFromDER(csrDer, options) {
1269
+ const tmpDir = await fs4.promises.mkdtemp(path4.join(os.tmpdir(), "pki-sign-"));
1270
+ try {
1271
+ const csrFile = path4.join(tmpDir, "request.csr");
1272
+ const certFile = path4.join(tmpDir, "certificate.pem");
1273
+ const csrPem = toPem(csrDer, "CERTIFICATE REQUEST");
1274
+ await fs4.promises.writeFile(csrFile, csrPem, "utf-8");
1275
+ const signingParams = {};
1276
+ if (options?.validityMs !== void 0) signingParams.validityMs = options.validityMs;
1277
+ else signingParams.validity = options?.validity ?? 365;
1278
+ if (options?.startDate) signingParams.startDate = options.startDate;
1279
+ if (options?.dns) signingParams.dns = options.dns;
1280
+ if (options?.ip) signingParams.ip = options.ip;
1281
+ if (options?.applicationUri) signingParams.applicationUri = options.applicationUri;
1282
+ if (options?.subject) signingParams.subject = options.subject;
1283
+ await this.signCertificateRequest(certFile, csrFile, signingParams);
1284
+ const certPem = readCertificatePEM2(certFile);
1285
+ return convertPEMtoDER2(certPem);
1286
+ } finally {
1287
+ await fs4.promises.rm(tmpDir, {
1288
+ recursive: true,
1289
+ force: true
1290
+ });
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Advertise the validity limits this CA can honor.
1295
+ *
1296
+ * Consumers (notably the GDS server in [`cert_auth.ts`](https://github.com/sterfive/node-opcua-gds))
1297
+ * clamp a requested validity against these bounds before calling
1298
+ * {@link signCertificateRequestFromDER}, so a misconfigured
1299
+ * `defaultCertValidity` cannot ask the CA for something it cannot
1300
+ * produce.
1301
+ *
1302
+ * Defaults match the OpenSSL-backed implementation:
1303
+ * - `minValidityMs = 60_000` (1 minute) — practical floor; the
1304
+ * X.509 spec floor is 1 second but very short certs are rarely
1305
+ * useful and pathological for any real deployment.
1306
+ * - `maxValidityMs = 10 * 365 * 86_400_000` (≈ 10 years) — long
1307
+ * enough for root CAs.
1308
+ * - `validityGranularityMs = 1_000` (1 second) — RFC 5280 §4.1.2.5
1309
+ * floor on `notBefore` / `notAfter`.
1310
+ * - `nativeUnit = "second"` — what `x509Date()` actually encodes.
1311
+ *
1312
+ * @see US-208 — the consumer-side capability story.
1313
+ */
1314
+ getCapabilities() {
1315
+ return {
1316
+ minValidityMs: 6e4,
1317
+ maxValidityMs: 10 * 365 * 864e5,
1318
+ validityGranularityMs: 1e3,
1319
+ nativeUnit: "second"
1320
+ };
1321
+ }
1322
+ /**
1323
+ * Generate a new RSA key pair, create an internal CSR, sign it
1324
+ * with this CA, and return both the certificate and private key
1325
+ * as DER-encoded buffers.
1326
+ *
1327
+ * The private key is **never stored** by the CA — it exists only
1328
+ * in a temporary directory that is cleaned up after the operation.
1329
+ *
1330
+ * This is used by `StartNewKeyPairRequest` (OPC UA Part 12) for
1331
+ * constrained devices that cannot generate their own keys.
1332
+ *
1333
+ * @param options - key generation and certificate parameters
1334
+ * @returns `{ certificateDer, privateKey }` — certificate as DER,
1335
+ * private key as a branded `PrivateKey` buffer
1336
+ */
1337
+ /**
1338
+ * An ephemeral key and a CSR for it, written into `tmpDir`. Both
1339
+ * `generateKeyPairAndSign*` methods need exactly this, and neither
1340
+ * needs a subprocess for it: the key comes from node's crypto and the
1341
+ * request is built and self-signed in process, so no `openssl.cnf` has
1342
+ * to be rendered either.
1343
+ */
1344
+ async #createEphemeralKeyAndCsr(tmpDir, keySize, options) {
1345
+ const privateKeyFile = path4.join(tmpDir, "private_key.pem");
1346
+ await generatePrivateKeyFile(privateKeyFile, keySize);
1347
+ const { csr } = await createCertificateSigningRequest2({
1348
+ privateKey: await privateKeyToCryptoKey2(readPrivateKey2(privateKeyFile)),
1349
+ subject: options.subject ? new Subject3(options.subject).toString() : void 0,
1350
+ applicationUri: options.applicationUri,
1351
+ dns: options.dns ?? [],
1352
+ ip: options.ip ?? [],
1353
+ purpose: CertificatePurpose2.ForApplication
1354
+ });
1355
+ const csrFile = path4.join(tmpDir, "request.csr");
1356
+ await fs4.promises.writeFile(csrFile, csr);
1357
+ return { privateKeyFile, csrFile };
1358
+ }
1359
+ async generateKeyPairAndSignDER(options) {
1360
+ const keySize = options.keySize ?? 2048;
1361
+ const startDate = options.startDate ?? /* @__PURE__ */ new Date();
1362
+ const tmpDir = await fs4.promises.mkdtemp(path4.join(os.tmpdir(), "pki-keygen-"));
1363
+ try {
1364
+ const { privateKeyFile, csrFile } = await this.#createEphemeralKeyAndCsr(tmpDir, keySize, options);
1365
+ const certFile = path4.join(tmpDir, "certificate.pem");
1366
+ const signingParams = {
1367
+ applicationUri: options.applicationUri,
1368
+ dns: options.dns,
1369
+ ip: options.ip,
1370
+ startDate
1371
+ };
1372
+ if (options.validityMs !== void 0) signingParams.validityMs = options.validityMs;
1373
+ else signingParams.validity = options.validity ?? 365;
1374
+ await this.signCertificateRequest(certFile, csrFile, signingParams);
1375
+ const certPem = readCertificatePEM2(certFile);
1376
+ const certificateDer = convertPEMtoDER2(certPem);
1377
+ const privateKey = readPrivateKey2(privateKeyFile);
1378
+ return { certificateDer, privateKey };
1379
+ } finally {
1380
+ await fs4.promises.rm(tmpDir, {
1381
+ recursive: true,
1382
+ force: true
1383
+ });
1384
+ }
1385
+ }
1386
+ /**
1387
+ * Generate a new RSA key pair, create an internal CSR, sign it
1388
+ * with this CA, and return the result as a PKCS#12 (PFX)
1389
+ * buffer bundling the certificate, private key, and CA chain.
1390
+ *
1391
+ * The private key is **never stored** by the CA — it exists only
1392
+ * in a temporary directory that is cleaned up after the operation.
1393
+ *
1394
+ * @param options - key generation, certificate, and PFX options
1395
+ * @returns the PFX as a `Buffer`
1396
+ */
1397
+ async generateKeyPairAndSignPFX(options) {
1398
+ const keySize = options.keySize ?? 2048;
1399
+ const startDate = options.startDate ?? /* @__PURE__ */ new Date();
1400
+ const passphrase = options.passphrase ?? "";
1401
+ const tmpDir = await fs4.promises.mkdtemp(path4.join(os.tmpdir(), "pki-keygen-pfx-"));
1402
+ try {
1403
+ const { privateKeyFile, csrFile } = await this.#createEphemeralKeyAndCsr(tmpDir, keySize, options);
1404
+ const certFile = path4.join(tmpDir, "certificate.pem");
1405
+ const signingParams = {
1406
+ applicationUri: options.applicationUri,
1407
+ dns: options.dns,
1408
+ ip: options.ip,
1409
+ startDate
1410
+ };
1411
+ if (options.validityMs !== void 0) signingParams.validityMs = options.validityMs;
1412
+ else signingParams.validity = options.validity ?? 365;
1413
+ await this.signCertificateRequest(certFile, csrFile, signingParams);
1414
+ const blocks = (await fs4.promises.readFile(certFile, "utf-8")).match(
1415
+ /-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g
1416
+ );
1417
+ if (!blocks || blocks.length === 0) {
1418
+ throw new Error(`generateKeyPairAndSignPFX: no certificate was produced in ${certFile}`);
1419
+ }
1420
+ return await createPfx({
1421
+ certificate: convertPEMtoDER2(blocks[0]),
1422
+ certificateChain: blocks.slice(1).map(convertPEMtoDER2),
1423
+ privateKey: readPrivateKey2(privateKeyFile),
1424
+ password: passphrase
1425
+ });
1426
+ } finally {
1427
+ await fs4.promises.rm(tmpDir, {
1428
+ recursive: true,
1429
+ force: true
1430
+ });
1431
+ }
1432
+ }
1433
+ /**
1434
+ * Revoke a DER-encoded certificate and regenerate the CRL.
1435
+ *
1436
+ * Extracts the serial number from the certificate, then
1437
+ * uses the stored cert file at `certs/<serial>.pem` for
1438
+ * revocation — avoiding temp-file PEM format mismatches.
1439
+ *
1440
+ * @param certDer - the certificate as a DER-encoded buffer
1441
+ * @param reason - CRL reason code
1442
+ * (default: `"keyCompromise"`)
1443
+ * @throws if the certificate's serial is not found in the CA
1444
+ */
1445
+ async revokeCertificateDER(certDer, reason) {
1446
+ const info = exploreCertificate(certDer);
1447
+ const serial = info.tbsCertificate.serialNumber.replace(/:/g, "").toUpperCase();
1448
+ const storedCertFile = path4.join(this.rootDir, "certs", `${serial}.pem`);
1449
+ if (!fs4.existsSync(storedCertFile)) {
1450
+ throw new Error(`Cannot revoke: no stored certificate found for serial ${serial} at ${storedCertFile}`);
1451
+ }
1452
+ await this.revokeCertificate(storedCertFile, {
1453
+ reason: reason ?? "keyCompromise"
1454
+ });
1455
+ }
1456
+ /**
1457
+ * Initialize the CA directory structure, generate the CA
1458
+ * private key and self-signed certificate if they do not
1459
+ * already exist.
1460
+ */
1461
+ async initialize() {
1462
+ mkdirRecursiveSync(path4.resolve(this.rootDir));
1463
+ await this.#withCaLock(() => this.#bootstrap());
1464
+ }
1465
+ /**
1466
+ * @internal Shared (backend-agnostic) part of `initialize()`: directory
1467
+ * layout, default database files, the "already initialized" / "partial
1468
+ * init" checks, and the openssl config file — then delegates CSR
1469
+ * generation, CA-certificate signing, and the initial CRL to
1470
+ * {@link CaBackend.bootstrap}. Must be called under {@link #withCaLock}.
1471
+ */
1472
+ async #bootstrap() {
1473
+ const caRootDir = path4.resolve(this.rootDir);
1474
+ mkdirRecursiveSync(caRootDir);
1475
+ ensurePrivateDirectory(path4.join(caRootDir, "private"));
1476
+ mkdirRecursiveSync(path4.join(caRootDir, "public"));
1477
+ mkdirRecursiveSync(path4.join(caRootDir, "certs"));
1478
+ mkdirRecursiveSync(path4.join(caRootDir, "crl"));
1479
+ mkdirRecursiveSync(path4.join(caRootDir, "conf"));
1480
+ const serial = path4.join(caRootDir, "serial");
1481
+ if (!fs4.existsSync(serial)) {
1482
+ await fs4.promises.writeFile(serial, "1000");
1483
+ }
1484
+ const crlNumber = path4.join(caRootDir, "crlnumber");
1485
+ if (!fs4.existsSync(crlNumber)) {
1486
+ await fs4.promises.writeFile(crlNumber, "1000");
1487
+ }
1488
+ const indexFile = path4.join(caRootDir, "index.txt");
1489
+ if (!fs4.existsSync(indexFile)) {
1490
+ await fs4.promises.writeFile(indexFile, "");
1491
+ }
1492
+ const signerBacked = this.hasExternalSigner;
1493
+ const caKeyExists = signerBacked || fs4.existsSync(path4.join(caRootDir, "private/cakey.pem"));
1494
+ const caCertExists = fs4.existsSync(path4.join(caRootDir, "public/cacert.pem"));
1495
+ if (caKeyExists && caCertExists && !config2.forceCA) {
1496
+ if (!signerBacked) {
1497
+ restrictPrivateFilePermissions(path4.join(caRootDir, "private/cakey.pem"), 384);
1498
+ await this._ensurePrivateKeyProtection();
1499
+ }
1500
+ debugLog("CA private key and certificate already exist ... skipping");
1501
+ return;
1502
+ }
1503
+ if (!signerBacked && caKeyExists && !caCertExists) {
1504
+ debugLog("CA private key exists but cacert.pem is missing \u2014 rebuilding CA");
1505
+ fs4.unlinkSync(path4.join(caRootDir, "private/cakey.pem"));
1506
+ const staleCsr = path4.join(caRootDir, "private/cakey.csr");
1507
+ if (fs4.existsSync(staleCsr)) {
1508
+ fs4.unlinkSync(staleCsr);
1509
+ }
1510
+ }
1511
+ displayTitle("Create Certificate Authority (CA)");
1512
+ const indexFileAttr = path4.join(caRootDir, "index.txt.attr");
1513
+ if (!fs4.existsSync(indexFileAttr)) {
1514
+ await fs4.promises.writeFile(indexFileAttr, "unique_subject = no");
1515
+ }
1516
+ const caConfigFile = this.configFile;
1517
+ await fs4.promises.writeFile(caConfigFile, renderCaConfig(caRootDir));
1518
+ if (!signerBacked) {
1519
+ const privateKeyFilename = path4.join(caRootDir, "private/cakey.pem");
1520
+ displayTitle(`Generate the CA private Key - ${this.keySize}`);
1521
+ await generatePrivateKeyFile(privateKeyFilename, this.keySize, { passphrase: await this._privateKeyPassphrase() });
1522
+ restrictPrivateFilePermissions(privateKeyFilename, 384);
1523
+ }
1524
+ await this.#backend.bootstrap(this);
1525
+ }
1526
+ /**
1527
+ * Initialize the CA directory structure and generate the
1528
+ * private key + CSR **without signing**.
1529
+ *
1530
+ * Use this when the CA certificate will be signed by an
1531
+ * external (third-party) root CA. After receiving the signed
1532
+ * certificate, call {@link installCACertificate} to complete
1533
+ * the setup.
1534
+ *
1535
+ * **Idempotent / restart-safe:**
1536
+ * - If the CA certificate exists and is valid → `{ status: "ready" }`
1537
+ * - If the CA certificate has expired → `{ status: "expired", csrPath, expiryDate }`
1538
+ * (a new CSR is generated, preserving the existing private key)
1539
+ * - If key + CSR exist but no cert (restart before install) →
1540
+ * `{ status: "pending", csrPath }` without regenerating
1541
+ * - Otherwise → generates key + CSR → `{ status: "created", csrPath }`
1542
+ *
1543
+ * @returns an {@link InitializeCSRResult} describing the CA state
1544
+ */
1545
+ async initializeCSR() {
1546
+ const caRootDir = path4.resolve(this.rootDir);
1547
+ mkdirRecursiveSync(caRootDir);
1548
+ return this.#withCaLock(() => this.#initializeCSRLocked(caRootDir));
1549
+ }
1550
+ async #initializeCSRLocked(caRootDir) {
1551
+ for (const dir of ["public", "certs", "crl", "conf"]) {
1552
+ mkdirRecursiveSync(path4.join(caRootDir, dir));
1553
+ }
1554
+ ensurePrivateDirectory(path4.join(caRootDir, "private"));
1555
+ const caCertFile = this.caCertificate;
1556
+ const privateKeyFile = path4.join(caRootDir, "private/cakey.pem");
1557
+ const csrFile = path4.join(caRootDir, "private/cakey.csr");
1558
+ const keyAvailable = this.hasExternalSigner || fs4.existsSync(privateKeyFile);
1559
+ if (!this.hasExternalSigner && fs4.existsSync(privateKeyFile)) {
1560
+ restrictPrivateFilePermissions(privateKeyFile, 384);
1561
+ await this._ensurePrivateKeyProtection();
1562
+ }
1563
+ if (fs4.existsSync(caCertFile)) {
1564
+ const certDer = convertPEMtoDER2(readCertificatePEM2(caCertFile));
1565
+ const certInfo = exploreCertificate(certDer);
1566
+ const notAfter = certInfo.tbsCertificate.validity.notAfter;
1567
+ if (notAfter.getTime() < Date.now()) {
1568
+ debugLog("CA certificate has expired \u2014 generating renewal CSR");
1569
+ await this._generateCSR(caRootDir, privateKeyFile, csrFile);
1570
+ return { status: "expired", csrPath: csrFile, expiryDate: notAfter };
1571
+ }
1572
+ debugLog("CA certificate already exists and is valid \u2014 ready");
1573
+ return { status: "ready" };
1574
+ }
1575
+ if (keyAvailable && fs4.existsSync(csrFile)) {
1576
+ debugLog("CA key + CSR already exist \u2014 pending external signing");
1577
+ return { status: "pending", csrPath: csrFile };
1578
+ }
1579
+ const serial = path4.join(caRootDir, "serial");
1580
+ if (!fs4.existsSync(serial)) {
1581
+ await fs4.promises.writeFile(serial, "1000");
1582
+ }
1583
+ const crlNumber = path4.join(caRootDir, "crlnumber");
1584
+ if (!fs4.existsSync(crlNumber)) {
1585
+ await fs4.promises.writeFile(crlNumber, "1000");
1586
+ }
1587
+ const indexFile = path4.join(caRootDir, "index.txt");
1588
+ if (!fs4.existsSync(indexFile)) {
1589
+ await fs4.promises.writeFile(indexFile, "");
1590
+ }
1591
+ const indexFileAttr = path4.join(caRootDir, "index.txt.attr");
1592
+ if (!fs4.existsSync(indexFileAttr)) {
1593
+ await fs4.promises.writeFile(indexFileAttr, "unique_subject = no");
1594
+ }
1595
+ const caConfigFile = this.configFile;
1596
+ await fs4.promises.writeFile(caConfigFile, renderCaConfig(caRootDir));
1597
+ if (!keyAvailable) {
1598
+ await generatePrivateKeyFile(privateKeyFile, this.keySize, { passphrase: await this._privateKeyPassphrase() });
1599
+ restrictPrivateFilePermissions(privateKeyFile, 384);
1600
+ }
1601
+ await this._generateCSR(caRootDir, privateKeyFile, csrFile);
1602
+ return { status: "created", csrPath: csrFile };
1603
+ }
1604
+ /**
1605
+ * Check whether the CA certificate needs renewal and, if so,
1606
+ * generate a new CSR for re-signing by the external root CA.
1607
+ *
1608
+ * Use this while the CA is running to detect upcoming expiry
1609
+ * **before** it actually expires. The existing private key is
1610
+ * preserved so previously issued certs remain valid.
1611
+ *
1612
+ * @param thresholdDays - number of days before expiry at which
1613
+ * to trigger renewal (default: 30)
1614
+ * @returns an {@link InitializeCSRResult} — `"expired"` if
1615
+ * renewal is needed, `"ready"` if the cert is still valid
1616
+ */
1617
+ async renewCSR(thresholdDays = 30) {
1618
+ const caRootDir = path4.resolve(this.rootDir);
1619
+ const caCertFile = this.caCertificate;
1620
+ const privateKeyFile = path4.join(caRootDir, "private/cakey.pem");
1621
+ const csrFile = path4.join(caRootDir, "private/cakey.csr");
1622
+ if (!fs4.existsSync(caCertFile)) {
1623
+ return this.initializeCSR();
1624
+ }
1625
+ const certDer = convertPEMtoDER2(readCertificatePEM2(caCertFile));
1626
+ const certInfo = exploreCertificate(certDer);
1627
+ const notAfter = certInfo.tbsCertificate.validity.notAfter;
1628
+ const thresholdMs = thresholdDays * 24 * 60 * 60 * 1e3;
1629
+ if (notAfter.getTime() - Date.now() < thresholdMs) {
1630
+ debugLog(`CA certificate expires within ${thresholdDays} days \u2014 generating renewal CSR`);
1631
+ await this.#withCaLock(() => this._generateCSR(caRootDir, privateKeyFile, csrFile));
1632
+ return { status: "expired", csrPath: csrFile, expiryDate: notAfter };
1633
+ }
1634
+ return { status: "ready" };
1635
+ }
1636
+ /**
1637
+ * Generate a CSR using the existing private key.
1638
+ * Must be called under {@link #withCaLock} — the lock is taken by the
1639
+ * public callers (`initializeCSR`, `renewCSR`), not here, so that
1640
+ * `initializeCSR` can hold one lock across key generation AND CSR
1641
+ * generation without the non-reentrant file lock deadlocking.
1642
+ * @internal
1643
+ */
1644
+ async _generateCSR(caRootDir, privateKeyFile, csrFile) {
1645
+ await this.#backend.generateCaCsr(this, caRootDir, privateKeyFile, csrFile);
1646
+ }
1647
+ /**
1648
+ * Install an externally-signed CA certificate and generate
1649
+ * the initial CRL.
1650
+ *
1651
+ * Call this after {@link initializeCSR} once the external
1652
+ * root CA has signed the CSR.
1653
+ *
1654
+ * **Safety checks:**
1655
+ * - Verifies that the certificate's public key matches the
1656
+ * CA private key before installing.
1657
+ *
1658
+ * @param signedCertFile - path to the PEM-encoded signed
1659
+ * CA certificate (issued by the external root CA)
1660
+ * @returns an {@link InstallCACertificateResult} with
1661
+ * `status: "success"` or `status: "error"` and a `reason`
1662
+ */
1663
+ async installCACertificate(signedCertFile) {
1664
+ return this.#withCaLock(async () => {
1665
+ const caCertFile = this.caCertificate;
1666
+ const fullPem = await fs4.promises.readFile(signedCertFile, "utf8");
1667
+ const pemBlocks = fullPem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);
1668
+ if (!pemBlocks || pemBlocks.length === 0) {
1669
+ return {
1670
+ status: "error",
1671
+ reason: "no_certificate_found",
1672
+ message: "The provided file does not contain any PEM-encoded certificate."
1673
+ };
1674
+ }
1675
+ const certDer = convertPEMtoDER2(pemBlocks[0]);
1676
+ if (!await this.#certificateMatchesOurKey(pemBlocks[0], certDer)) {
1677
+ return {
1678
+ status: "error",
1679
+ reason: "certificate_key_mismatch",
1680
+ message: "The provided certificate does not match the CA private key. Ensure the certificate was signed from the CSR generated by initializeCSR()."
1681
+ };
1682
+ }
1683
+ await fs4.promises.writeFile(caCertFile, `${pemBlocks[0]}
1684
+ `);
1685
+ const issuerChainFile = this.issuerCertificateChain;
1686
+ if (pemBlocks.length > 1) {
1687
+ const issuerPem = `${pemBlocks.slice(1).join("\n")}
1688
+ `;
1689
+ await fs4.promises.writeFile(issuerChainFile, issuerPem);
1690
+ debugLog(`Stored ${pemBlocks.length - 1} issuer certificate(s) in issuer_chain.pem`);
1691
+ } else {
1692
+ if (fs4.existsSync(issuerChainFile)) {
1693
+ await fs4.promises.unlink(issuerChainFile);
1694
+ }
1695
+ }
1696
+ await this.#backend.regenerateCrl(this);
1697
+ return { status: "success" };
1698
+ });
1699
+ }
1700
+ /**
1701
+ * Sign a CSR with CA extensions (`v3_ca`), producing a
1702
+ * subordinate CA certificate.
1703
+ *
1704
+ * Unlike {@link signCertificateRequest} which signs with
1705
+ * end-entity extensions (SANs, etc.), this method signs
1706
+ * with `basicConstraints = CA:TRUE` and `keyUsage =
1707
+ * keyCertSign, cRLSign`.
1708
+ *
1709
+ * @param certFile - output path for the signed CA cert (PEM)
1710
+ * @param csrFile - path to the subordinate CA's CSR
1711
+ * @param params - signing parameters
1712
+ */
1713
+ async signCACertificateRequest(certFile, csrFile, params) {
1714
+ await this.#withCaLock(async () => {
1715
+ const validity = params.validity ?? 3650;
1716
+ await this.#backend.signSubordinateCsr(this, csrFile, certFile, validity);
1717
+ await this.constructCertificateChain(certFile);
1718
+ });
1719
+ }
1720
+ /**
1721
+ * Rebuild the combined CA certificate + CRL file.
1722
+ *
1723
+ * This concatenates the CA certificate with the current
1724
+ * revocation list so that OpenSSL can verify certificates
1725
+ * with CRL checking enabled.
1726
+ */
1727
+ async constructCACertificateWithCRL() {
1728
+ const cacertWithCRL = this.caCertificateWithCrl;
1729
+ if (fs4.existsSync(this.revocationList)) {
1730
+ await fs4.promises.writeFile(
1731
+ cacertWithCRL,
1732
+ fs4.readFileSync(this.caCertificate, "utf8") + fs4.readFileSync(this.revocationList, "utf8")
1733
+ );
1734
+ } else {
1735
+ await fs4.promises.writeFile(cacertWithCRL, fs4.readFileSync(this.caCertificate));
1736
+ }
1737
+ }
1738
+ /**
1739
+ * Append the CA certificate to a signed certificate file,
1740
+ * creating a PEM certificate chain.
1741
+ *
1742
+ * @param certificate - path to the certificate file to extend
1743
+ */
1744
+ async constructCertificateChain(certificate) {
1745
+ assert3(fs4.existsSync(certificate));
1746
+ assert3(fs4.existsSync(this.caCertificate));
1747
+ debugLog(chalk3.yellow(" certificate file :"), chalk3.cyan(certificate));
1748
+ let chain = await fs4.promises.readFile(certificate, "utf8");
1749
+ chain += await fs4.promises.readFile(this.caCertificate, "utf8");
1750
+ if (fs4.existsSync(this.issuerCertificateChain)) {
1751
+ chain += await fs4.promises.readFile(this.issuerCertificateChain, "utf8");
1752
+ }
1753
+ await fs4.promises.writeFile(certificate, chain);
1754
+ }
1755
+ /**
1756
+ * Create a self-signed certificate using OpenSSL.
1757
+ *
1758
+ * @param certificateFile - output path for the signed certificate
1759
+ * @param privateKey - path to the private key file
1760
+ * @param params - certificate parameters (subject, validity, SANs)
1761
+ */
1762
+ async createSelfSignedCertificate(certificateFile, privateKey, params) {
1763
+ assert3(typeof privateKey === "string");
1764
+ assert3(fs4.existsSync(privateKey));
1765
+ if (!certificateFileExist(certificateFile)) {
1766
+ return;
1767
+ }
1768
+ adjustDate(params);
1769
+ adjustApplicationUri(params);
1770
+ params.dns = params.dns || [];
1771
+ params.ip = params.ip || [];
1772
+ await this.#withCaLock(async () => {
1773
+ await this.#backend.createSelfSignedCertificate(this, certificateFile, privateKey, params);
1774
+ });
1775
+ }
1776
+ /**
1777
+ * Regenerate `crl/revocation_list.{crl,der}` from the current database
1778
+ * state, without changing any certificate's status. Normally
1779
+ * unnecessary — `revokeCertificate` already regenerates the CRL as
1780
+ * part of revoking — but useful to force a refresh (e.g. after
1781
+ * switching a CA's `backend` between `"openssl"` and `"native"`).
1782
+ */
1783
+ async regenerateCrl() {
1784
+ await this.#withCaLock(async () => {
1785
+ await this.#backend.regenerateCrl(this);
1786
+ });
1787
+ }
1788
+ /**
1789
+ * Revoke a certificate and regenerate the CRL.
1790
+ *
1791
+ * @param certificate - path to the certificate file to revoke
1792
+ * @param params - revocation parameters
1793
+ * @param params.reason - CRL reason code
1794
+ * (default `"keyCompromise"`)
1795
+ */
1796
+ async revokeCertificate(certificate, params) {
1797
+ const crlReasons = [
1798
+ "unspecified",
1799
+ "keyCompromise",
1800
+ "CACompromise",
1801
+ "affiliationChanged",
1802
+ "superseded",
1803
+ "cessationOfOperation",
1804
+ "certificateHold",
1805
+ "removeFromCRL"
1806
+ ];
1807
+ const reason = params.reason || "keyCompromise";
1808
+ assert3(crlReasons.indexOf(reason) >= 0);
1809
+ displayTitle(`Revoking certificate ${certificate}`);
1810
+ await this.#withCaLock(async () => {
1811
+ await this.#backend.revoke(this, certificate, reason);
1812
+ });
1813
+ }
1814
+ /**
1815
+ * Sign a Certificate Signing Request (CSR) with this CA.
1816
+ *
1817
+ * The signed certificate is written to `certificate`, and the
1818
+ * CA certificate chain plus CRL are appended to form a
1819
+ * complete certificate chain.
1820
+ *
1821
+ * @param certificate - output path for the signed certificate
1822
+ * @param certificateSigningRequestFilename - path to the CSR
1823
+ * @param params1 - signing parameters (validity, dates, SANs)
1824
+ * @returns the path to the signed certificate
1825
+ */
1826
+ async signCertificateRequest(certificate, certificateSigningRequestFilename, params1) {
1827
+ await this.#backend.preflight();
1828
+ assert3(fs4.existsSync(certificateSigningRequestFilename));
1829
+ if (!certificateFileExist(certificate)) {
1830
+ return "";
1831
+ }
1832
+ adjustDate(params1);
1833
+ adjustApplicationUri(params1);
1834
+ const csr = await readCertificateSigningRequest(certificateSigningRequestFilename);
1835
+ const csrInfo = exploreCertificateSigningRequest(csr);
1836
+ const applicationUri = csrInfo.extensionRequest.subjectAltName.uniformResourceIdentifier ? csrInfo.extensionRequest.subjectAltName.uniformResourceIdentifier[0] : void 0;
1837
+ if (typeof applicationUri !== "string") {
1838
+ throw new Error("Cannot find applicationUri in CSR");
1839
+ }
1840
+ const dns = csrInfo.extensionRequest.subjectAltName.dNSName || [];
1841
+ let ip = csrInfo.extensionRequest.subjectAltName.iPAddress || [];
1842
+ ip = ip.map(octetStringToIpAddress);
1843
+ const sanOverride = { applicationUri, dns, ip };
1844
+ return this.#withCaLock(async () => {
1845
+ await this.#backend.signEndEntityCsr(this, certificate, certificateSigningRequestFilename, params1, sanOverride);
1846
+ displaySubtitle("- construct CA certificate with CRL");
1847
+ await this.constructCACertificateWithCRL();
1848
+ displaySubtitle("- construct certificate chain");
1849
+ await this.constructCertificateChain(certificate);
1850
+ displaySubtitle("- verify certificate against the root CA");
1851
+ await this.verifyCertificate(certificate);
1852
+ return certificate;
1853
+ });
1854
+ }
1855
+ /**
1856
+ * Check that `certificate` really was signed by this CA, and throw if it
1857
+ * was not.
1858
+ *
1859
+ * This used to do nothing: `openssl verify` crashes on Windows, so the
1860
+ * check was left as a placeholder. It no longer needs a subprocess -
1861
+ * `verifyCertificateSignature` does it in pure JS, the same way
1862
+ * {@link CertificateManager} already validates a chain - so the check
1863
+ * that `signCertificateRequest` always claimed to perform now actually
1864
+ * happens on every issuance, whichever backend did the signing.
1865
+ *
1866
+ * Only the leading certificate is examined: the file may be a chain,
1867
+ * and the rest of it is this CA's own certificate and its issuers.
1868
+ *
1869
+ * @param certificate - path to the certificate (or chain) to verify
1870
+ */
1871
+ async verifyCertificate(certificate) {
1872
+ const pem = await fs4.promises.readFile(certificate, "utf-8");
1873
+ const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g);
1874
+ if (!blocks || blocks.length === 0) {
1875
+ throw new Error(`verifyCertificate: ${certificate} contains no PEM-encoded certificate`);
1876
+ }
1877
+ const caCertificateDer = convertPEMtoDER2(readCertificatePEM2(this.caCertificate));
1878
+ if (!verifyCertificateSignature(convertPEMtoDER2(blocks[0]), caCertificateDer)) {
1879
+ throw new Error(
1880
+ `verifyCertificate: ${certificate} was not signed by this certificate authority (${this.caCertificate})`
1881
+ );
1882
+ }
1883
+ }
1884
+ };
1885
+
1886
+ export {
1887
+ quote,
1888
+ resolvePrivateKeyPassphrase,
1889
+ adjustDate,
1890
+ adjustApplicationUri,
1891
+ g_config,
1892
+ doDebug,
1893
+ displayError,
1894
+ debugLog,
1895
+ warningLog,
1896
+ mkdirRecursiveSync,
1897
+ restrictPrivateFilePermissions,
1898
+ ensurePrivateDirectory,
1899
+ isEncryptedPrivateKeyFile,
1900
+ makePath,
1901
+ displayTitle,
1902
+ displaySubtitle,
1903
+ display,
1904
+ CaDatabase,
1905
+ NativeCaBackend,
1906
+ Subject2 as Subject,
1907
+ defaultSubject,
1908
+ configurationFileTemplate,
1909
+ escapeOpensslConfDoubleQuoted,
1910
+ renderCaConfig,
1911
+ CertificateAuthorityCore
1912
+ };
1913
+ //# sourceMappingURL=chunk-2HTNH73K.mjs.map