node-opcua-pki 6.22.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/bin/install_prerequisite.ts +1 -1
  2. package/bin/pki.ts +1 -1
  3. package/dist/bin/install_prerequisite.d.ts +2 -0
  4. package/dist/bin/install_prerequisite.js +6 -0
  5. package/dist/bin/install_prerequisite.js.map +1 -0
  6. package/dist/bin/pki.d.ts +2 -0
  7. package/dist/bin/pki.js +4 -0
  8. package/dist/bin/pki.js.map +1 -0
  9. package/dist/lib/ca/backends/native_ca_backend.d.ts +49 -0
  10. package/dist/lib/ca/backends/native_ca_backend.js +365 -0
  11. package/dist/lib/ca/backends/native_ca_backend.js.map +1 -0
  12. package/dist/lib/ca/backends/openssl_ca_backend.d.ts +47 -0
  13. package/dist/lib/ca/backends/openssl_ca_backend.js +398 -0
  14. package/dist/lib/ca/backends/openssl_ca_backend.js.map +1 -0
  15. package/dist/lib/ca/certificate_authority.d.ts +62 -0
  16. package/dist/lib/ca/certificate_authority.js +91 -0
  17. package/dist/lib/ca/certificate_authority.js.map +1 -0
  18. package/dist/lib/ca/core/ca_backend.d.ts +89 -0
  19. package/dist/lib/ca/core/ca_backend.js +24 -0
  20. package/dist/lib/ca/core/ca_backend.js.map +1 -0
  21. package/dist/lib/ca/core/ca_database.d.ts +91 -0
  22. package/dist/lib/ca/core/ca_database.js +267 -0
  23. package/dist/lib/ca/core/ca_database.js.map +1 -0
  24. package/dist/{core-BwqSJPHc.d.mts → lib/ca/core/certificate_authority_core.d.ts} +45 -394
  25. package/dist/lib/ca/core/certificate_authority_core.js +1300 -0
  26. package/dist/lib/ca/core/certificate_authority_core.js.map +1 -0
  27. package/dist/lib/ca/core/index.d.ts +17 -0
  28. package/dist/lib/ca/core/index.js +25 -0
  29. package/dist/lib/ca/core/index.js.map +1 -0
  30. package/dist/lib/ca/crypto_create_CA.d.ts +1 -0
  31. package/dist/lib/ca/crypto_create_CA.js +821 -0
  32. package/dist/lib/ca/crypto_create_CA.js.map +1 -0
  33. package/dist/lib/ca/index.d.ts +1 -0
  34. package/dist/lib/ca/index.js +2 -0
  35. package/dist/lib/ca/index.js.map +1 -0
  36. package/dist/lib/ca/templates/ca_config_template.cnf.d.ts +2 -0
  37. package/dist/lib/ca/templates/ca_config_template.cnf.js +170 -0
  38. package/dist/lib/ca/templates/ca_config_template.cnf.js.map +1 -0
  39. package/dist/lib/core.d.ts +33 -0
  40. package/dist/lib/core.js +56 -0
  41. package/dist/lib/core.js.map +1 -0
  42. package/dist/lib/index.d.ts +11 -0
  43. package/dist/lib/index.js +37 -0
  44. package/dist/lib/index.js.map +1 -0
  45. package/dist/lib/misc/applicationurn.d.ts +1 -0
  46. package/dist/lib/misc/applicationurn.js +40 -0
  47. package/dist/lib/misc/applicationurn.js.map +1 -0
  48. package/dist/lib/misc/hostname.d.ts +8 -0
  49. package/dist/lib/misc/hostname.js +82 -0
  50. package/dist/lib/misc/hostname.js.map +1 -0
  51. package/dist/lib/misc/subject.d.ts +2 -0
  52. package/dist/lib/misc/subject.js +2 -0
  53. package/dist/lib/misc/subject.js.map +1 -0
  54. package/dist/{index.d.ts → lib/pki/certificate_manager.d.ts} +24 -246
  55. package/dist/lib/pki/certificate_manager.js +2302 -0
  56. package/dist/lib/pki/certificate_manager.js.map +1 -0
  57. package/dist/lib/pki/templates/simple_config_template.cnf.d.ts +2 -0
  58. package/dist/lib/pki/templates/simple_config_template.cnf.js +74 -0
  59. package/dist/lib/pki/templates/simple_config_template.cnf.js.map +1 -0
  60. package/dist/lib/pki/toolbox_pfx.d.ts +127 -0
  61. package/dist/lib/pki/toolbox_pfx.js +248 -0
  62. package/dist/lib/pki/toolbox_pfx.js.map +1 -0
  63. package/dist/lib/toolbox/common.d.ts +150 -0
  64. package/dist/lib/toolbox/common.js +82 -0
  65. package/dist/lib/toolbox/common.js.map +1 -0
  66. package/dist/lib/toolbox/common2.d.ts +25 -0
  67. package/dist/lib/toolbox/common2.js +97 -0
  68. package/dist/lib/toolbox/common2.js.map +1 -0
  69. package/dist/lib/toolbox/config.d.ts +5 -0
  70. package/dist/lib/toolbox/config.js +28 -0
  71. package/dist/lib/toolbox/config.js.map +1 -0
  72. package/dist/lib/toolbox/debug.d.ts +5 -0
  73. package/dist/lib/toolbox/debug.js +35 -0
  74. package/dist/lib/toolbox/debug.js.map +1 -0
  75. package/dist/lib/toolbox/display.d.ts +4 -0
  76. package/dist/lib/toolbox/display.js +56 -0
  77. package/dist/lib/toolbox/display.js.map +1 -0
  78. package/dist/lib/toolbox/index.d.ts +5 -0
  79. package/dist/lib/toolbox/index.js +28 -0
  80. package/dist/lib/toolbox/index.js.map +1 -0
  81. package/dist/lib/toolbox/with_openssl/_create_random_file.d.ts +4 -0
  82. package/dist/lib/toolbox/with_openssl/_create_random_file.js +50 -0
  83. package/dist/lib/toolbox/with_openssl/_create_random_file.js.map +1 -0
  84. package/dist/lib/toolbox/with_openssl/_env.d.ts +58 -0
  85. package/dist/lib/toolbox/with_openssl/_env.js +126 -0
  86. package/dist/lib/toolbox/with_openssl/_env.js.map +1 -0
  87. package/dist/lib/toolbox/with_openssl/create_certificate_signing_request.d.ts +5 -0
  88. package/dist/lib/toolbox/with_openssl/create_certificate_signing_request.js +72 -0
  89. package/dist/lib/toolbox/with_openssl/create_certificate_signing_request.js.map +1 -0
  90. package/dist/lib/toolbox/with_openssl/create_private_key.d.ts +5 -0
  91. package/dist/lib/toolbox/with_openssl/create_private_key.js +92 -0
  92. package/dist/lib/toolbox/with_openssl/create_private_key.js.map +1 -0
  93. package/dist/lib/toolbox/with_openssl/create_self_signed_certificate.d.ts +5 -0
  94. package/dist/lib/toolbox/with_openssl/create_self_signed_certificate.js +135 -0
  95. package/dist/lib/toolbox/with_openssl/create_self_signed_certificate.js.map +1 -0
  96. package/dist/lib/toolbox/with_openssl/execute_openssl.d.ts +67 -0
  97. package/dist/lib/toolbox/with_openssl/execute_openssl.js +246 -0
  98. package/dist/lib/toolbox/with_openssl/execute_openssl.js.map +1 -0
  99. package/dist/lib/toolbox/with_openssl/index.d.ts +5 -0
  100. package/dist/lib/toolbox/with_openssl/index.js +30 -0
  101. package/dist/lib/toolbox/with_openssl/index.js.map +1 -0
  102. package/dist/lib/toolbox/with_openssl/install_prerequisite.d.ts +7 -0
  103. package/dist/lib/toolbox/with_openssl/install_prerequisite.js +358 -0
  104. package/dist/lib/toolbox/with_openssl/install_prerequisite.js.map +1 -0
  105. package/dist/lib/toolbox/with_openssl/toolbox.d.ts +53 -0
  106. package/dist/lib/toolbox/with_openssl/toolbox.js +190 -0
  107. package/dist/lib/toolbox/with_openssl/toolbox.js.map +1 -0
  108. package/dist/lib/toolbox/without_openssl/create_certificate_signing_request.d.ts +5 -0
  109. package/dist/lib/toolbox/without_openssl/create_certificate_signing_request.js +69 -0
  110. package/dist/lib/toolbox/without_openssl/create_certificate_signing_request.js.map +1 -0
  111. package/dist/lib/toolbox/without_openssl/create_self_signed_certificate.d.ts +3 -0
  112. package/dist/lib/toolbox/without_openssl/create_self_signed_certificate.js +78 -0
  113. package/dist/lib/toolbox/without_openssl/create_self_signed_certificate.js.map +1 -0
  114. package/dist/lib/toolbox/without_openssl/index.d.ts +2 -0
  115. package/dist/lib/toolbox/without_openssl/index.js +25 -0
  116. package/dist/lib/toolbox/without_openssl/index.js.map +1 -0
  117. package/package.json +11 -30
  118. package/dist/bin/install_prerequisite.mjs +0 -18
  119. package/dist/bin/install_prerequisite.mjs.map +0 -1
  120. package/dist/bin/pki.mjs +0 -5895
  121. package/dist/bin/pki.mjs.map +0 -1
  122. package/dist/chunk-EQ4DGI4M.mjs +0 -1917
  123. package/dist/chunk-EQ4DGI4M.mjs.map +0 -1
  124. package/dist/chunk-GCHH54PS.mjs +0 -30
  125. package/dist/chunk-GCHH54PS.mjs.map +0 -1
  126. package/dist/core-BwqSJPHc.d.ts +0 -1041
  127. package/dist/core.d.mts +0 -2
  128. package/dist/core.d.ts +0 -2
  129. package/dist/core.js +0 -1902
  130. package/dist/core.js.map +0 -1
  131. package/dist/core.mjs +0 -21
  132. package/dist/core.mjs.map +0 -1
  133. package/dist/index.d.mts +0 -1001
  134. package/dist/index.js +0 -4968
  135. package/dist/index.js.map +0 -1
  136. package/dist/index.mjs +0 -3106
  137. package/dist/index.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../lib/misc/applicationurn.ts","../../lib/misc/hostname.ts","../../lib/toolbox/common.ts","../../lib/toolbox/config.ts","../../lib/toolbox/debug.ts","../../lib/toolbox/common2.ts","../../lib/toolbox/display.ts","../../lib/toolbox/without_openssl/create_certificate_signing_request.ts","../../lib/toolbox/without_openssl/create_self_signed_certificate.ts","../../lib/toolbox/without_openssl/index.ts","../../lib/pki/templates/simple_config_template.cnf.ts","../../lib/pki/certificate_manager.ts","../../lib/toolbox/index.ts","../../lib/toolbox/with_openssl/_env.ts","../../lib/misc/subject.ts","../../lib/toolbox/with_openssl/install_prerequisite.ts","../../lib/toolbox/with_openssl/execute_openssl.ts","../../lib/toolbox/with_openssl/toolbox.ts","../../lib/toolbox/with_openssl/create_certificate_signing_request.ts","../../lib/toolbox/with_openssl/index.ts","../../lib/ca/core/ca_database.ts","../../lib/ca/backends/native_ca_backend.ts","../../lib/ca/backends/openssl_ca_backend.ts","../../lib/ca/templates/ca_config_template.cnf.ts","../../lib/ca/core/certificate_authority_core.ts","../../lib/ca/certificate_authority.ts","../../lib/ca/crypto_create_CA.ts","../../bin/pki.ts"],"sourcesContent":["// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport assert from \"node:assert\";\nimport { createHash } from \"node:crypto\";\n\nexport function makeApplicationUrn(hostname: string, suffix: string): string {\n // beware : Openssl doesn't support urn with length greater than 64 !!\n // sometimes hostname length could be too long ...\n // application urn length must not exceed 64 car. to comply with openssl\n // see cryptoCA\n let hostnameHash = hostname;\n if (hostnameHash.length + 7 + suffix.length >= 64) {\n // we need to reduce the applicationUrn side => let's take\n // a portion of the hostname hash.\n hostnameHash = createHash(\"md5\").update(hostname).digest(\"hex\").substring(0, 16);\n }\n\n const applicationUrn = `urn:${hostnameHash}:${suffix}`;\n assert(applicationUrn.length <= 64);\n return applicationUrn;\n}\n","/**\n * @module node-opcua-hostname\n */\nimport dns from \"node:dns\";\nimport os from \"node:os\";\nimport { promisify } from \"node:util\";\n\nfunction trim(str: string, length?: number): string {\n if (!length) {\n return str;\n }\n return str.substring(0, Math.min(str.length, length));\n}\n\nfunction fqdn(callback: (err: Error | null, fqdn?: string) => void) {\n const uqdn = os.hostname();\n\n dns.lookup(uqdn, { hints: dns.ADDRCONFIG }, (err1: Error | null, ip: string) => {\n if (err1) {\n return callback(err1);\n }\n\n dns.lookupService(ip, 0, (err2: Error | null, _fqdn: string) => {\n if (err2) {\n return callback(err2);\n }\n _fqdn = _fqdn.replace(\".localdomain\", \"\");\n callback(null, _fqdn);\n });\n });\n}\n\nlet _fullyQualifiedDomainNameInCache: string | undefined;\n\n/**\n * extract FullyQualifiedDomainName of this computer\n */\nexport async function extractFullyQualifiedDomainName(): Promise<string> {\n if (_fullyQualifiedDomainNameInCache) {\n return _fullyQualifiedDomainNameInCache;\n }\n if (process.platform === \"win32\") {\n // http://serverfault.com/a/73643/251863\n const env = process.env;\n _fullyQualifiedDomainNameInCache =\n env.COMPUTERNAME + (env.USERDNSDOMAIN && env.USERDNSDOMAIN?.length > 0 ? `.${env.USERDNSDOMAIN as string}` : \"\");\n } else {\n try {\n _fullyQualifiedDomainNameInCache = await promisify(fqdn)();\n if (_fullyQualifiedDomainNameInCache === \"localhost\") {\n throw new Error(\"localhost not expected\");\n }\n if (/sethostname/.test(_fullyQualifiedDomainNameInCache as string)) {\n throw new Error(\"Detecting fqdn on windows !!!\");\n }\n } catch (_err) {\n // fall back to old method\n _fullyQualifiedDomainNameInCache = os.hostname();\n }\n }\n return _fullyQualifiedDomainNameInCache as string;\n}\n\nexport async function prepareFQDN() {\n _fullyQualifiedDomainNameInCache = await extractFullyQualifiedDomainName();\n}\n\nexport function getFullyQualifiedDomainName(optional_max_length?: number) {\n if (!_fullyQualifiedDomainNameInCache) {\n throw new Error(\"FullyQualifiedDomainName computation is not completed yet\");\n }\n return _fullyQualifiedDomainNameInCache ? trim(_fullyQualifiedDomainNameInCache, optional_max_length) : \"%FQDN%\";\n}\n\nexport function getHostname() {\n return os.hostname();\n}\n\nexport function resolveFullyQualifiedDomainName(str: string): string {\n if (!_fullyQualifiedDomainNameInCache) {\n throw new Error(\"FullyQualifiedDomainName computation is not completed yet\");\n }\n str = str.replace(\"%FQDN%\", _fullyQualifiedDomainNameInCache);\n str = str.replace(\"{FQDN}\", _fullyQualifiedDomainNameInCache);\n str = str.replace(\"{hostname}\", getHostname());\n return str;\n}\n// note : under windows ... echo %COMPUTERNAME%.%USERDNSDOMAIN%\nprepareFQDN();\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport assert from \"node:assert\";\n\n/** RSA key size in bits. */\nexport type KeySize = 1024 | 2048 | 3072 | 4096;\n/** Hex-encoded SHA-1 certificate thumbprint. */\nexport type Thumbprint = string;\n/** A filesystem path to a file. */\nexport type Filename = string;\n/** Status of a certificate in the trust store. */\nexport type CertificateStatus = \"unknown\" | \"trusted\" | \"rejected\";\n\nimport type { CaSigner, CertificatePurpose, PrivateKey } from \"node-opcua-crypto\";\nimport type { SubjectOptions } from \"../misc/subject\";\n\n/**\n * @deprecated Use {@link KeySize} instead.\n */\nexport type KeyLength = 1024 | 2048 | 3072 | 4096;\n\nexport function quote(str?: string): string {\n return `\"${str || \"\"}\"`;\n}\n\n/**\n * Subject Alternative Name (SAN) parameters for certificate\n * generation.\n */\nexport interface ProcessAltNamesParam {\n /** DNS host names to include in the SAN extension. */\n dns?: string[];\n /** IP addresses to include in the SAN extension. */\n ip?: string[];\n /** OPC UA application URI for the SAN extension. */\n applicationUri?: string;\n}\n\n/**\n * Options for creating a Certificate Signing Request (CSR).\n */\nexport interface CreateCertificateSigningRequestOptions extends ProcessAltNamesParam {\n /** X.500 subject for the certificate. */\n subject?: SubjectOptions | string;\n}\n\n/**\n * Extended CSR options that include filesystem paths and\n * certificate purpose — used internally by the OpenSSL toolbox.\n */\nexport interface CreateCertificateSigningRequestWithConfigOptions extends CreateCertificateSigningRequestOptions {\n /** Root directory of the PKI store. */\n rootDir: Filename;\n /** Path to the OpenSSL configuration file. */\n configFile: Filename;\n /**\n * The private key: a filesystem path to a PEM file (unencrypted;\n * the historical behavior), an already-resolved in-memory\n * {@link PrivateKey}, or an opaque {@link CaSigner} (HSM/KMS-held key;\n * only the openssl-free toolbox supports it — openssl needs a key file)\n * — see {@link CreateSelfSignCertificateWithConfigParam.privateKey}.\n */\n privateKey: Filename | PrivateKey | CaSigner;\n /** Intended purpose of the certificate. */\n purpose: CertificatePurpose;\n}\n\n/**\n * Narrows the `privateKey` union of the toolbox options: a {@link CaSigner}\n * is the only member that carries a `sign` method — a path is a string and\n * a {@link PrivateKey} envelope has only `hidden`.\n */\nexport function isOpaqueSigner(privateKey: Filename | PrivateKey | CaSigner): privateKey is CaSigner {\n return typeof privateKey !== \"string\" && typeof (privateKey as CaSigner).sign === \"function\";\n}\n\n/**\n * Validity period parameters for certificate generation.\n */\nexport interface StartDateEndDateParam {\n /** Certificate \"Not Before\" date. Defaults to now. */\n startDate?: Date;\n /** Certificate \"Not After\" date (computed from validity). */\n endDate?: Date;\n /** Number of days the certificate is valid. @defaultValue 365 */\n validity?: number;\n /**\n * Certificate validity in milliseconds.\n *\n * When provided, takes precedence over {@link validity} and enables\n * sub-day validity (X.509 supports second precision per RFC 5280\n * §4.1.2.5; OpenSSL is invoked with `-startdate`/`-enddate` already).\n *\n * Typical use is short-lived certificates for demos or for renewal\n * cycle testing. Existing day-based callers are unaffected.\n */\n validityMs?: number;\n}\n\n/**\n * Parameters for creating a self-signed certificate.\n */\nexport interface CreateSelfSignCertificateParam extends ProcessAltNamesParam, StartDateEndDateParam {\n /** X.500 subject for the certificate. */\n subject?: SubjectOptions | string;\n}\n\n/**\n * Extended self-signed certificate options that include\n * filesystem paths and purpose — used internally.\n */\nexport interface CreateSelfSignCertificateWithConfigParam extends CreateSelfSignCertificateParam {\n /** Root directory of the PKI store. */\n rootDir: Filename;\n /** Path to the OpenSSL configuration file. */\n configFile: Filename;\n /**\n * The private key: a filesystem path to a PEM file (unencrypted;\n * the historical behavior), an already-resolved in-memory\n * {@link PrivateKey} — used when the key is passphrase-protected on\n * disk, so the decrypted key material is never written back out in\n * cleartext — or an opaque {@link CaSigner} (HSM/KMS-held key; only\n * the openssl-free toolbox supports it — openssl needs a key file).\n */\n privateKey: Filename | PrivateKey | CaSigner;\n /** Intended purpose of the certificate. */\n purpose: CertificatePurpose;\n}\n\n/**\n * A passphrase, or a function resolving one — called lazily, and at most\n * once per `CertificateManager` / `CertificateAuthority` instance (the\n * result is cached in memory). Never logged.\n */\nexport type PrivateKeyPassphrase = string | (() => Promise<string>);\n\n/**\n * Sources a {@link PrivateKey} from somewhere other than the local\n * filesystem (an HSM, a KMS, ...). When configured on `CertificateManager`,\n * it overrides disk entirely — the on-disk `own/private/private_key.pem` is\n * neither generated nor read. `CertificateAuthority` does not support a\n * provider (its signing paths are openssl reading a key file); it does\n * support `privateKeyPassphrase`.\n */\nexport interface PrivateKeyProvider {\n getPrivateKey(): Promise<PrivateKey>;\n}\n\n/** Resolve a {@link PrivateKeyPassphrase}, if configured. */\nexport async function resolvePrivateKeyPassphrase(passphrase: PrivateKeyPassphrase | undefined): Promise<string | undefined> {\n if (passphrase === undefined) {\n return undefined;\n }\n return typeof passphrase === \"function\" ? await passphrase() : passphrase;\n}\n\n/**\n * General-purpose parameters passed to CA operations such as\n * {@link CertificateAuthority.signCertificateRequest} and\n * {@link CertificateAuthority.revokeCertificate}.\n */\nexport interface Params extends ProcessAltNamesParam, StartDateEndDateParam {\n /** X.500 subject for the certificate. */\n subject?: SubjectOptions | string;\n\n /** Path to the private key file. */\n privateKey?: string;\n /** Path to the OpenSSL configuration file. */\n configFile?: string;\n /** Root directory of the PKI store. */\n rootDir?: string;\n\n /** Output filename for the generated certificate. */\n outputFile?: string;\n /** CRL revocation reason (e.g. `\"keyCompromise\"`). */\n reason?: string;\n}\n\nexport function adjustDate(params: StartDateEndDateParam) {\n assert(params instanceof Object);\n params.startDate = params.startDate || new Date();\n assert(params.startDate instanceof Date);\n\n // Precedence: validityMs > validity (days) > default 365 days.\n // When validityMs is set, compute endDate via millisecond arithmetic\n // (sub-day capable). Otherwise preserve the legacy calendar-day\n // arithmetic via setDate() so day-based callers remain\n // bit-for-bit identical (including DST boundary handling).\n if (params.validityMs !== undefined) {\n if (params.validityMs <= 0) {\n throw new RangeError(`validityMs must be > 0 (got ${params.validityMs})`);\n }\n params.endDate = new Date(params.startDate.getTime() + params.validityMs);\n // Keep params.validity in sync as the ceil-rounded day count, so\n // downstream code paths that read params.validity (e.g. logging,\n // OpenSSL command echo) still see a sensible value.\n params.validity = Math.ceil(params.validityMs / 86_400_000);\n } else {\n params.validity = params.validity || 365; // one year\n params.endDate = new Date(params.startDate.getTime());\n params.endDate.setDate(params.startDate.getDate() + params.validity);\n }\n\n // params.endDate = x509Date(endDate);\n // params.startDate = x509Date(startDate);\n\n assert(params.endDate instanceof Date);\n assert(params.startDate instanceof Date);\n\n // // istanbul ignore next\n // if (!g_config.silent) {\n // warningLog(\" start Date \", params.startDate.toUTCString(), x509Date(params.startDate));\n // warningLog(\" end Date \", params.endDate.toUTCString(), x509Date(params.endDate));\n // }\n}\n\nexport function adjustApplicationUri(params: Params) {\n const applicationUri = params.applicationUri || \"\";\n if (applicationUri.length > 200) {\n throw new Error(`Openssl doesn't support urn with length greater than 200${applicationUri}`);\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nexport const g_config = {\n opensslVersion: \"unset\",\n silent: process.env.VERBOSE ? !process.env.VERBOSE : true,\n force: false\n};\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nexport const doDebug = process.env.NODEOPCUAPKIDEBUG || false;\nexport const displayError = true;\nexport const displayDebug = !!process.env.NODEOPCUAPKIDEBUG || false;\nexport function debugLog(...args: unknown[]) {\n // istanbul ignore next\n if (displayDebug) {\n console.log.apply(null, args);\n }\n}\nexport function warningLog(...args: unknown[]) {\n console.log.apply(null, args);\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport assert from \"node:assert\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport chalk from \"chalk\";\n\nimport { g_config } from \"./config\";\n\nimport { debugLog, warningLog } from \"./debug\";\n\nexport function certificateFileExist(certificateFile: string): boolean {\n // istanbul ignore next\n if (fs.existsSync(certificateFile) && !g_config.force) {\n warningLog(\n chalk.yellow(\" certificate \") + chalk.cyan(certificateFile) + chalk.yellow(\" already exists => do not overwrite\")\n );\n return false;\n }\n return true;\n}\n\nexport function mkdirRecursiveSync(folder: string): void {\n if (!fs.existsSync(folder)) {\n // istanbul ignore next\n debugLog(chalk.white(\" .. constructing \"), folder);\n fs.mkdirSync(folder, { recursive: true });\n }\n}\n\n/**\n * Restrict a file or directory to owner-only access (mode 0600/0700).\n *\n * fs.chmod only toggles the read-only attribute on Windows and cannot express\n * POSIX-style owner-only permissions, so this is a no-op there rather than a\n * false sense of protection. Errors are logged, not thrown: a read-only mount\n * or an unexpected ownership mismatch should not prevent the server from\n * starting.\n */\nexport function restrictPrivateFilePermissions(target: string, mode: 0o600 | 0o700): void {\n // istanbul ignore if\n if (process.platform === \"win32\") {\n return;\n }\n try {\n fs.chmodSync(target, mode);\n } catch (err) {\n // istanbul ignore next\n warningLog(chalk.yellow(\" could not restrict permissions on \"), target, (err as Error).message);\n }\n}\n\n/**\n * Create (or repair) a directory intended to hold private key material,\n * restricted to owner-only access. Safe to call on an existing directory\n * to repair permissions left by an earlier, less restrictive version.\n */\nexport function ensurePrivateDirectory(dir: string): void {\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n restrictPrivateFilePermissions(dir, 0o700);\n}\n\n/**\n * `true` if the PEM file at `filename` holds a passphrase-encrypted PKCS#8\n * key (`-----BEGIN ENCRYPTED PRIVATE KEY-----`). Header check only; it does\n * not validate or decrypt the key. Throws if the file cannot be read.\n */\nexport function isEncryptedPrivateKeyFile(filename: string): boolean {\n return fs.readFileSync(filename, \"utf-8\").includes(\"-----BEGIN ENCRYPTED PRIVATE KEY-----\");\n}\n\nexport function makePath(folderName: string, filename?: string): string {\n let s: string;\n if (filename) {\n s = path.join(path.normalize(folderName), filename);\n } else {\n assert(folderName);\n s = folderName;\n }\n s = s.replace(/\\\\/g, \"/\");\n return s;\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport chalk from \"chalk\";\nimport { g_config } from \"./config\";\nimport { warningLog } from \"./debug\";\n\n// istanbul ignore next\nexport function displayChapter(str: string) {\n const l = \" \";\n warningLog(`${chalk.bgWhite(l)} `);\n str = ` ${str}${l}`.substring(0, l.length);\n warningLog(chalk.bgWhite.cyan(str));\n warningLog(`${chalk.bgWhite(l)} `);\n}\n\nexport function displayTitle(str: string) {\n // istanbul ignore next\n if (!g_config.silent) {\n warningLog(\"\");\n warningLog(chalk.yellowBright(str));\n warningLog(chalk.yellow(new Array(str.length + 1).join(\"=\")), \"\\n\");\n }\n}\n\nexport function displaySubtitle(str: string) {\n // istanbul ignore next\n if (!g_config.silent) {\n warningLog(\"\");\n warningLog(` ${chalk.yellowBright(str)}`);\n warningLog(` ${chalk.white(new Array(str.length + 1).join(\"-\"))}`, \"\\n\");\n }\n}\nexport function display(str: string) {\n // istanbul ignore next\n if (!g_config.silent) {\n warningLog(` ${str}`);\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2022-2026 Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport assert from \"node:assert\";\nimport fs from \"node:fs\";\nimport { coercePrivateKeyPem, createCertificateSigningRequest, pemToPrivateKey, Subject } from \"node-opcua-crypto\";\nimport { type CreateCertificateSigningRequestWithConfigOptions, isOpaqueSigner } from \"../common\";\nimport { display, displaySubtitle } from \"../display\";\n\n/**\n * create a certificate signing request\n */\nexport async function createCertificateSigningRequestAsync(\n certificateSigningRequestFilename: string,\n params: CreateCertificateSigningRequestWithConfigOptions\n): Promise<void> {\n assert(params);\n assert(params.rootDir);\n assert(params.configFile);\n assert(params.privateKey);\n if (typeof params.privateKey === \"string\") {\n assert(fs.existsSync(params.privateKey), `Private key must exist${params.privateKey}`);\n }\n\n // assert(fs.existsSync(params.configFile), \"config file must exist \" + params.configFile);\n assert(fs.existsSync(params.rootDir), \"RootDir key must exist\");\n assert(typeof certificateSigningRequestFilename === \"string\");\n\n const subject = params.subject ? new Subject(params.subject).toString() : undefined;\n displaySubtitle(\"- Creating a Certificate Signing Request with subtile\");\n\n // an opaque signer is handed to the CSR primitive as-is: the\n // proof-of-possession signature and the embedded public key both come\n // from the signer, and there is no PEM to coerce\n const privateKey = isOpaqueSigner(params.privateKey)\n ? params.privateKey\n : await pemToPrivateKey(\n typeof params.privateKey === \"string\"\n ? await fs.promises.readFile(params.privateKey, \"utf-8\")\n : coercePrivateKeyPem(params.privateKey)\n );\n\n const { csr } = await createCertificateSigningRequest({\n privateKey,\n dns: params.dns,\n ip: params.ip,\n subject,\n applicationUri: params.applicationUri,\n purpose: params.purpose\n });\n await fs.promises.writeFile(certificateSigningRequestFilename, csr, \"utf-8\");\n\n display(\n `- privateKey ${\n typeof params.privateKey === \"string\"\n ? params.privateKey\n : isOpaqueSigner(params.privateKey)\n ? \"<opaque-signer>\"\n : \"<in-memory>\"\n }`\n );\n display(`- certificateSigningRequestFilename ${certificateSigningRequestFilename}`);\n\n // to verify that the CSR is correct:\n // openssl req -in ./tmp/without_openssl.csr -noout -verify\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2022-2026 Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport assert from \"node:assert\";\nimport fs from \"node:fs\";\n\nimport {\n CertificatePurpose,\n coercePrivateKeyPem,\n createSelfSignedCertificate as createSelfSignedCertificate1,\n pemToPrivateKey,\n Subject\n} from \"node-opcua-crypto\";\nimport { adjustDate, type CreateSelfSignCertificateWithConfigParam, isOpaqueSigner } from \"../common\";\nimport { displayTitle } from \"../display\";\n\nexport async function createSelfSignedCertificateAsync(\n certificate: string,\n params: CreateSelfSignCertificateWithConfigParam\n): Promise<void> {\n params.purpose = params.purpose || CertificatePurpose.ForApplication;\n assert(params.purpose, \"Please provide a Certificate Purpose\");\n /**\n * note: due to a limitation of openssl ,\n * it is not possible to control the startDate of the certificate validity\n * to achieve this the certificateAuthority tool shall be used.\n */\n assert(fs.existsSync(params.configFile));\n assert(fs.existsSync(params.rootDir));\n if (typeof params.privateKey === \"string\") {\n assert(fs.existsSync(params.privateKey));\n }\n if (!params.subject) {\n throw Error(\"Missing subject\");\n }\n\n assert(typeof params.applicationUri === \"string\");\n assert(Array.isArray(params.dns));\n\n // xx no key size in self-signed assert(params.keySize == 2048 || params.keySize == 4096);\n\n // processAltNames(params);\n adjustDate(params);\n assert(Object.prototype.hasOwnProperty.call(params, \"validity\"));\n\n let subject: Subject | string = new Subject(params.subject);\n subject = subject.toString();\n\n // xx const certificateRequestFilename = certificate + \".csr\";\n const purpose = params.purpose;\n\n displayTitle(\"Generate a certificate request\");\n\n // an opaque signer is handed to the primitive as-is: the public half\n // comes from getPublicKey() and signing routes through the signer\n // (node-opcua-crypto >= 5.10.1); there is no PEM to coerce\n const privateKey = isOpaqueSigner(params.privateKey)\n ? params.privateKey\n : await pemToPrivateKey(\n typeof params.privateKey === \"string\"\n ? await fs.promises.readFile(params.privateKey, \"utf-8\")\n : coercePrivateKeyPem(params.privateKey)\n );\n\n const { cert } = await createSelfSignedCertificate1({\n privateKey,\n notBefore: params.startDate,\n notAfter: params.endDate,\n validity: params.validity,\n dns: params.dns,\n ip: params.ip,\n subject,\n applicationUri: params.applicationUri,\n purpose\n });\n await fs.promises.writeFile(certificate, cert, \"utf-8\");\n}\n\nexport async function createSelfSignedCertificate(\n certificate: string,\n params: CreateSelfSignCertificateWithConfigParam\n): Promise<void> {\n await createSelfSignedCertificateAsync(certificate, params);\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nexport * from \"./create_certificate_signing_request\";\nexport * from \"./create_self_signed_certificate\";\n","const config =\n \"##################################################################################################\\n\" +\n \"## SIMPLE OPENSSL CONFIG FILE FOR SELF-SIGNED CERTIFICATE GENERATION\\n\" +\n \"################################################################################################################\\n\" +\n \"\\n\" +\n \"distinguished_name = req_distinguished_name\\n\" +\n \"default_md = sha1\\n\" +\n \"\\n\" +\n \"default_md = sha256 # The default digest algorithm\\n\" +\n \"\\n\" +\n \"[ v3_ca ]\\n\" +\n \"subjectKeyIdentifier = hash\\n\" +\n \"authorityKeyIdentifier = keyid:always,issuer:always\\n\" +\n \"\\n\" +\n \"# authorityKeyIdentifier = keyid\\n\" +\n \"basicConstraints = CA:TRUE\\n\" +\n \"keyUsage = critical, cRLSign, keyCertSign\\n\" +\n 'nsComment = \"Self-signed Certificate for CA generated by Node-OPCUA Certificate utility\"\\n' +\n \"#nsCertType = sslCA, emailCA\\n\" +\n \"#subjectAltName = email:copy\\n\" +\n \"#issuerAltName = issuer:copy\\n\" +\n \"#obj = DER:02:03\\n\" +\n \"# crlDistributionPoints = @crl_info\\n\" +\n \"# [ crl_info ]\\n\" +\n \"# URI.0 = http://localhost:8900/crl.pem\\n\" +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n \"\\n\" +\n \"[ req ]\\n\" +\n \"days = 390\\n\" +\n \"req_extensions = v3_req\\n\" +\n \"x509_extensions = v3_ca\\n\" +\n \"\\n\" +\n \"[v3_req]\\n\" +\n \"basicConstraints = CA:false\\n\" +\n \"keyUsage = critical, nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment\\n\" +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n \"\\n\" +\n \"[ v3_ca_signed]\\n\" +\n \"subjectKeyIdentifier = hash\\n\" +\n \"authorityKeyIdentifier = keyid,issuer\\n\" +\n \"basicConstraints = critical, CA:FALSE\\n\" +\n \"keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment\\n\" +\n \"extendedKeyUsage = clientAuth,serverAuth \\n\" +\n 'nsComment = \"certificate generated by Node-OPCUA Certificate utility and signed by a CA\"\\n' +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n \"[ v3_selfsigned]\\n\" +\n \"subjectKeyIdentifier = hash\\n\" +\n \"authorityKeyIdentifier = keyid,issuer\\n\" +\n \"basicConstraints = critical, CA:FALSE\\n\" +\n \"keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment\\n\" +\n \"extendedKeyUsage = clientAuth,serverAuth \\n\" +\n 'nsComment = \"Self-signed certificate generated by Node-OPCUA Certificate utility\"\\n' +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n \"[ req_distinguished_name ]\\n\" +\n \"countryName = Country Name (2 letter code)\\n\" +\n \"countryName_default = FR\\n\" +\n \"countryName_min = 2\\n\" +\n \"countryName_max = 2\\n\" +\n \"# stateOrProvinceName = State or Province Name (full name)\\n\" +\n \"# stateOrProvinceName_default = Ile de France\\n\" +\n \"# localityName = Locality Name (city, district)\\n\" +\n \"# localityName_default = Paris\\n\" +\n \"organizationName = Organization Name (company)\\n\" +\n \"organizationName_default = NodeOPCUA\\n\" +\n \"# organizationalUnitName = Organizational Unit Name (department, division)\\n\" +\n \"# organizationalUnitName_default = R&D\\n\" +\n \"commonName = Common Name (hostname, FQDN, IP, or your name)\\n\" +\n \"commonName_max = 256\\n\" +\n \"commonName_default = NodeOPCUA\\n\" +\n \"# emailAddress = Email Address\\n\" +\n \"# emailAddress_max = 40\\n\" +\n \"# emailAddress_default = node-opcua (at) node-opcua (dot) com\\n\" +\n \"subjectAltName = $ENV::ALTNAME\";\n\nexport default config;\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki — CertificateManager\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n// This project is licensed under the terms of the MIT license.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport { EventEmitter } from \"node:events\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { drainPendingLocks, withLock } from \"@ster5/global-mutex\";\nimport chalk from \"chalk\";\nimport chokidar, { type FSWatcher as ChokidarFSWatcher } from \"chokidar\";\nimport {\n type CaSigner,\n type Certificate,\n type CertificateInternals,\n type CertificateRevocationList,\n type CertificateRevocationListInfo,\n caSignerFromKeyOperations,\n type DER,\n exploreCertificate,\n exploreCertificateInfo,\n exploreCertificateRevocationList,\n generatePrivateKeyFile,\n type IKeyOperations,\n keyOperationsFromPrivateKey,\n type LocalKeyOperations,\n makeSHA1Thumbprint,\n type PrivateKey,\n PrivateKeyUnavailableError,\n readCertificateChain,\n readCertificateChainAsync,\n readCertificateRevocationList,\n readPrivateKey,\n split_der,\n toPem,\n verifyCertificateSignature,\n writePrivateKeyFile\n} from \"node-opcua-crypto\";\n\nimport type { SubjectOptions } from \"../misc/subject\";\nimport type {\n CertificateStatus,\n CreateSelfSignCertificateParam,\n CreateSelfSignCertificateWithConfigParam,\n Filename,\n KeySize,\n PrivateKeyPassphrase,\n PrivateKeyProvider,\n Thumbprint\n} from \"../toolbox/common\";\nimport { resolvePrivateKeyPassphrase } from \"../toolbox/common\";\nimport {\n ensurePrivateDirectory,\n isEncryptedPrivateKeyFile,\n makePath,\n mkdirRecursiveSync,\n restrictPrivateFilePermissions\n} from \"../toolbox/common2\";\nimport { debugLog, warningLog } from \"../toolbox/debug\";\nimport { createCertificateSigningRequestAsync, createSelfSignedCertificate } from \"../toolbox/without_openssl\";\n\nimport _simple_config_template from \"./templates/simple_config_template.cnf\";\n\n/**\n *\n * a minimalist config file for openssl that allows\n * self-signed certificate to be generated.\n *\n */\nconst configurationFileSimpleTemplate: string = _simple_config_template;\nconst fsWriteFile = fs.promises.writeFile;\n\ninterface Entry {\n certificate: Certificate;\n filename: string;\n /** Lazily cached result of `exploreCertificate(certificate)`. */\n info?: CertificateInternals;\n}\n\n/** Return the cached `info` or compute and cache it. */\nfunction getOrComputeInfo(entry: Entry): CertificateInternals {\n if (!entry.info) {\n entry.info = exploreCertificate(entry.certificate);\n }\n return entry.info;\n}\n\ninterface CRLEntry {\n crlInfo: CertificateRevocationListInfo;\n filename: string;\n}\ninterface CRLData {\n serialNumbers: { [key: string]: Date };\n crls: CRLEntry[];\n}\ninterface Thumbs {\n trusted: Map<string, Entry>;\n rejected: Map<string, Entry>;\n issuers: {\n certs: Map<string, Entry>;\n };\n /** key = subjectFingerPrint of issuer certificate */\n crl: Map<string, CRLData>;\n /** key = subjectFingerPrint of issuer certificate */\n issuersCrl: Map<string, CRLData>;\n}\n\n/**\n * Identifies which PKI sub-store a certificate event originated from.\n */\nexport type CertificateStore = \"trusted\" | \"rejected\" | \"issuersCerts\";\n\n/**\n * Identifies which PKI sub-store a CRL event originated from.\n */\nexport type CrlStore = \"crl\" | \"issuersCrl\";\n\n/**\n * Events emitted by {@link CertificateManager} when the\n * file-system watchers detect certificate or CRL changes.\n */\nexport interface CertificateManagerEvents {\n /** A certificate file was added to a store. */\n certificateAdded: (event: { store: CertificateStore; certificate: Certificate; fingerprint: string; filename: string }) => void;\n /** A certificate file was removed from a store. */\n certificateRemoved: (event: { store: CertificateStore; fingerprint: string; filename: string }) => void;\n /** A certificate file was modified in a store. */\n certificateChange: (event: {\n store: CertificateStore;\n certificate: Certificate;\n fingerprint: string;\n filename: string;\n }) => void;\n /** A CRL file was added. */\n crlAdded: (event: { store: CrlStore; filename: string }) => void;\n /** A CRL file was removed. */\n crlRemoved: (event: { store: CrlStore; filename: string }) => void;\n}\n\n/**\n * Options controlling certificate validation in\n * {@link CertificateManager.addTrustedCertificateFromChain}.\n *\n * By default all checks are **strict** (secure). Set individual\n * flags to `true` only in test/development environments.\n */\nexport interface AddCertificateValidationOptions {\n /**\n * Accept certificates whose validity period has expired\n * or is not yet active.\n * @defaultValue false\n */\n acceptExpiredCertificate?: boolean;\n\n /**\n * Accept certificates that have been revoked by their\n * issuer's CRL. When `false` (the default), a revoked\n * certificate is rejected with `BadCertificateRevoked`.\n * @defaultValue false\n */\n acceptRevokedCertificate?: boolean;\n\n /**\n * Do not fail when a CRL is missing for an issuer in the\n * chain. When `false` (the default), a missing CRL causes\n * `BadCertificateRevocationUnknown`.\n * @defaultValue false\n */\n ignoreMissingRevocationList?: boolean;\n\n /**\n * Maximum depth of the certificate chain (leaf + issuers).\n * The leaf certificate counts as depth 1.\n * @defaultValue 5\n */\n maxChainLength?: number;\n}\n\n/**\n * Options for creating a {@link CertificateManager}.\n */\nexport interface CertificateManagerOptions {\n /**\n * RSA key size for generated private keys.\n * @defaultValue 2048\n */\n keySize?: KeySize;\n /** Filesystem path where the PKI directory structure is stored. */\n location: string;\n\n /**\n * Validation options applied by\n * {@link CertificateManager.addTrustedCertificateFromChain}.\n *\n * Defaults are secure — all checks enabled.\n */\n addCertificateValidationOptions?: AddCertificateValidationOptions;\n\n /**\n * When `true`, the CertificateManager will **not** start\n * chokidar file-system watchers on the PKI folders.\n *\n * The initial file-system scan still runs so the in-memory\n * indexes are populated, but live change detection is\n * disabled. This is useful in test / CI environments where\n * many CertificateManager instances are created in parallel\n * and the accumulated `fs.watch` handles exhaust the libuv\n * thread-pool, causing event-loop starvation.\n *\n * @defaultValue false\n */\n disableFileWatchers?: boolean;\n\n /**\n * Encrypt the private key at rest with this passphrase (opt-in,\n * default off). When set:\n * - a freshly generated key is written as encrypted PKCS#8;\n * - an existing *plaintext* key is re-encrypted in place by\n * {@link CertificateManager.initialize} (atomic rename, same as\n * {@link CertificateManager.reencryptPrivateKey}), so enabling the\n * option on an existing install never leaves the key in cleartext;\n * - an existing encrypted key requires the same passphrase — a\n * mismatch, or an encrypted key with no passphrase configured, fails\n * `initialize()` closed with `PrivateKeyPassphraseRequiredError`.\n *\n * A function is called at most once per `CertificateManager` instance\n * (the decrypted key is cached in memory for the instance's lifetime,\n * see {@link CertificateManager.getPrivateKey}). Never logged.\n *\n * Existing consumers that read `own/private/private_key.pem` directly\n * (e.g. node-opcua's `OPCUAServer`, or `createPFX` without its\n * `privateKeyPassphrase` option) still expect a plaintext key — do not\n * enable this unless every reader of that file goes through\n * {@link CertificateManager.getPrivateKey} or is given the passphrase.\n */\n privateKeyPassphrase?: PrivateKeyPassphrase;\n\n /**\n * Source the private key from somewhere other than\n * `own/private/private_key.pem` (an HSM, a KMS, ...). When set, it\n * overrides disk entirely for every operation that needs the private\n * key — the on-disk file is not read, and `privateKeyPassphrase` is\n * ignored.\n */\n privateKeyProvider?: PrivateKeyProvider;\n\n /**\n * Use a private key this manager can never read: an opaque\n * {@link IKeyOperations} provider (HSM, KMS, TPM, OS keystore, ...).\n *\n * The distinction with `privateKeyProvider` matters: a\n * `privateKeyProvider` *sources raw key material* from elsewhere and\n * hands it back; `keyOperations` never reveals the key — only sign and\n * decrypt operations on it. Prefer `keyOperations` whenever the key\n * does not need to be exportable.\n *\n * When set:\n * - {@link CertificateManager.getPrivateKey} and\n * {@link CertificateManager.reencryptPrivateKey} throw\n * `PrivateKeyUnavailableError` — there is no key material to return\n * or rewrite, and no on-disk key is generated or expected;\n * - {@link CertificateManager.getKeyOperations} returns this object;\n * - `initialize()` fails closed if the provider cannot answer\n * `getKeyMetadata()` (unreachable HSM, misconfiguration);\n * - mutually exclusive with `privateKeyProvider` and\n * `privateKeyPassphrase` — both describe key *material*, which an\n * opaque configuration does not have.\n */\n keyOperations?: IKeyOperations;\n}\n\n/**\n * Parameters for {@link createSelfSignedCertificate}.\n * All fields from {@link CreateSelfSignCertificateParam} are required.\n */\nexport interface CreateSelfSignCertificateParam1 extends CreateSelfSignCertificateParam {\n /**\n * Output path for the certificate.\n * @defaultValue `\"own/certs/self_signed_certificate.pem\"`\n */\n outputFile?: Filename;\n /** X.500 subject for the certificate. */\n subject: SubjectOptions | string;\n /** OPC UA application URI for the SAN extension. */\n applicationUri: string;\n /** DNS host names to include in the SAN extension. */\n dns: string[];\n /** Certificate \"Not Before\" date. */\n startDate: Date;\n /** Number of days the certificate is valid. */\n validity: number;\n}\n\n/**\n * Options to fine-tune certificate verification behaviour.\n * Passed to {@link CertificateManager.verifyCertificate}.\n *\n * Without any options, `verifyCertificate` is **strict**: only\n * certificates that are explicitly present in the trusted store\n * will return {@link VerificationStatus.Good}. Unknown or\n * rejected certificates return\n * {@link VerificationStatus.BadCertificateUntrusted} even when\n * their issuer chain is valid.\n *\n * Set {@link acceptCertificateWithValidIssuerChain} to `true`\n * to accept certificates whose issuer chain validates against\n * a trusted CA — even if the leaf certificate itself is not\n * in the trusted store.\n */\nexport interface VerifyCertificateOptions {\n /** Accept certificates whose \"Not After\" date has passed. */\n acceptOutdatedCertificate?: boolean;\n /** Accept issuer certificates whose \"Not After\" date has passed. */\n acceptOutDatedIssuerCertificate?: boolean;\n /** Do not fail when a CRL is missing for an issuer. */\n ignoreMissingRevocationList?: boolean;\n /** Accept certificates whose \"Not Before\" date is in the future. */\n acceptPendingCertificate?: boolean;\n /**\n * Accept a certificate that is not in the trusted store when\n * its issuer (CA) certificate is trusted, the signature is\n * valid, and the certificate does not appear in the CRL.\n *\n * When `false` (the default), only certificates explicitly\n * placed in the trusted store are accepted — this is the\n * same behaviour as {@link CertificateManager.isCertificateTrusted}.\n *\n * @defaultValue false\n */\n acceptCertificateWithValidIssuerChain?: boolean;\n}\n\n/**\n * OPC UA certificate verification status codes.\n *\n * These mirror the OPC UA `StatusCode` values for certificate\n * validation results.\n */\nexport enum VerificationStatus {\n /** The certificate provided as a parameter is not valid. */\n BadCertificateInvalid = \"BadCertificateInvalid\",\n /** An error occurred verifying security. */\n BadSecurityChecksFailed = \"BadSecurityChecksFailed\",\n /** The certificate does not meet the requirements of the security policy. */\n BadCertificatePolicyCheckFailed = \"BadCertificatePolicyCheckFailed\",\n /** The certificate has expired or is not yet valid. */\n BadCertificateTimeInvalid = \"BadCertificateTimeInvalid\",\n /** An issuer certificate has expired or is not yet valid. */\n BadCertificateIssuerTimeInvalid = \"BadCertificateIssuerTimeInvalid\",\n /** The HostName used to connect to a server does not match a HostName in the certificate. */\n BadCertificateHostNameInvalid = \"BadCertificateHostNameInvalid\",\n /** The URI specified in the ApplicationDescription does not match the URI in the certificate. */\n BadCertificateUriInvalid = \"BadCertificateUriInvalid\",\n /** The certificate may not be used for the requested operation. */\n BadCertificateUseNotAllowed = \"BadCertificateUseNotAllowed\",\n /** The issuer certificate may not be used for the requested operation. */\n BadCertificateIssuerUseNotAllowed = \"BadCertificateIssuerUseNotAllowed\",\n /** The certificate is not trusted. */\n BadCertificateUntrusted = \"BadCertificateUntrusted\",\n /** It was not possible to determine if the certificate has been revoked. */\n BadCertificateRevocationUnknown = \"BadCertificateRevocationUnknown\",\n /** It was not possible to determine if the issuer certificate has been revoked. */\n BadCertificateIssuerRevocationUnknown = \"BadCertificateIssuerRevocationUnknown\",\n /** The certificate has been revoked. */\n BadCertificateRevoked = \"BadCertificateRevoked\",\n /** The issuer certificate has been revoked. */\n BadCertificateIssuerRevoked = \"BadCertificateIssuerRevoked\",\n /** The certificate chain is incomplete. */\n BadCertificateChainIncomplete = \"BadCertificateChainIncomplete\",\n\n /** Validation OK. */\n Good = \"Good\"\n}\n\nexport function coerceCertificateChain(certificate: Certificate | Certificate[]): Certificate[] {\n if (Array.isArray(certificate)) {\n if (certificate.length === 0) return [];\n return certificate.reduce((acc, cert) => {\n return acc.concat(split_der(cert));\n }, [] as Certificate[]);\n }\n return split_der(certificate);\n}\n\nexport function makeFingerprint(certificate: Certificate | Certificate[] | CertificateRevocationList): string {\n // When the buffer contains a certificate chain (multiple\n // concatenated DER structures), the thumbprint must be\n // computed on the leaf certificate only (first element).\n const chain = coerceCertificateChain(certificate as Certificate | Certificate[]);\n return makeSHA1Thumbprint(chain[0]).toString(\"hex\");\n}\nfunction short(stringToShorten: string) {\n return stringToShorten.substring(0, 10);\n}\n// biome-ignore lint/suspicious/noControlCharactersInRegex: we need to filter control characters\nconst forbiddenChars = /[\\x00-\\x1F<>:\"/\\\\|?*]/g;\n\nfunction buildIdealCertificateName(certificate: Certificate | Certificate[]): string {\n const chain = coerceCertificateChain(certificate as Certificate | Certificate[]);\n const fingerprint = makeFingerprint(chain);\n try {\n const commonName = exploreCertificate(chain[0]).tbsCertificate.subject.commonName || \"\";\n // commonName may contain invalid characters for a filename such as / or \\ or :\n // that we need to replace with a valid character.\n // replace / or \\ or : with _\n const sanitizedCommonName = commonName.replace(forbiddenChars, \"_\");\n return `${sanitizedCommonName}[${fingerprint}]`;\n } catch (_err) {\n // make be certificate is incorrect !\n return `invalid_certificate_[${fingerprint}]`;\n }\n}\nfunction findMatchingIssuerKey(entries: Entry[], wantedIssuerKey: string): Entry[] {\n return entries.filter((entry) => {\n const info = getOrComputeInfo(entry);\n return info.tbsCertificate.extensions && info.tbsCertificate.extensions.subjectKeyIdentifier === wantedIssuerKey;\n });\n}\n\nfunction isSelfSigned2(info: CertificateInternals): boolean {\n return (\n info.tbsCertificate.extensions?.subjectKeyIdentifier ===\n info.tbsCertificate.extensions?.authorityKeyIdentifier?.keyIdentifier\n );\n}\n\nfunction isSelfSigned3(certificate: Buffer): boolean {\n const info = exploreCertificate(certificate);\n return isSelfSigned2(info);\n}\n\nfunction _isIssuerInfo(info: CertificateInternals): boolean {\n const basicConstraints = info.tbsCertificate.extensions?.basicConstraints;\n if (basicConstraints?.cA) {\n return true;\n }\n const keyUsage = info.tbsCertificate.extensions?.keyUsage;\n if (keyUsage?.keyCertSign) {\n return true;\n }\n return false;\n}\n\n/**\n * Check if the provided certificate acts as an issuer (CA)\n * @param certificate - the DER-encoded certificate\n * @returns true if the certificate has CA basicConstraints or keyCertSign keyUsage\n */\nexport function isIssuer(certificate: Certificate): boolean {\n try {\n const info = exploreCertificate(certificate);\n return _isIssuerInfo(info);\n } catch (_err) {\n return false;\n }\n}\n\n/**\n * Check if the provided certificate acts as an intermediate issuer.\n * An intermediate issuer is a CA certificate that is not a root CA (not self-signed).\n * @param certificate - the DER-encoded certificate\n * @returns true if the certificate is a CA and is not self-signed\n */\nexport function isIntermediateIssuer(certificate: Certificate): boolean {\n try {\n const info = exploreCertificate(certificate);\n if (!_isIssuerInfo(info)) {\n return false;\n }\n // A root CA is self-signed. If it's not self-signed, it's an intermediate CA.\n return !isSelfSigned2(info);\n } catch (_err) {\n return false;\n }\n}\n\n/**\n * Check if the provided certificate acts as a root issuer.\n * A root issuer is a CA certificate that is self-signed.\n * @param certificate - the DER-encoded certificate\n * @returns true if the certificate is a CA and is self-signed\n */\nexport function isRootIssuer(certificate: Certificate): boolean {\n try {\n const info = exploreCertificate(certificate);\n if (!_isIssuerInfo(info)) {\n return false;\n }\n // A root CA is securely self-signed\n return isSelfSigned2(info);\n } catch (_err) {\n return false;\n }\n}\n\n/**\n * Find the issuer certificate for a given certificate within\n * a provided certificate chain.\n *\n * @param certificate - the DER-encoded certificate whose issuer to find\n * @param chain - candidate issuer certificates to search\n * @returns the matching issuer certificate, or `null` if not found\n */\nexport function findIssuerCertificateInChain(certificate: Certificate | Certificate[], chain: Certificate[]): Certificate | null {\n const coercedCertificate = coerceCertificateChain(certificate);\n const firstCertificate = coercedCertificate[0];\n if (!firstCertificate) {\n return null;\n }\n const certInfo = exploreCertificate(firstCertificate);\n\n // istanbul ignore next\n if (isSelfSigned2(certInfo)) {\n // the certificate is self signed so is it's own issuer.\n return firstCertificate;\n }\n const wantedIssuerKey = certInfo.tbsCertificate.extensions?.authorityKeyIdentifier?.keyIdentifier;\n\n // istanbul ignore next\n if (!wantedIssuerKey) {\n // Certificate has no extension 3 ! the certificate might have been generated by an old system\n debugLog(\"Certificate has no extension 3\");\n return null;\n }\n const coercedChain = coerceCertificateChain(chain);\n const potentialIssuers = coercedChain.filter((c) => {\n const info = exploreCertificate(c);\n return info.tbsCertificate.extensions && info.tbsCertificate.extensions.subjectKeyIdentifier === wantedIssuerKey;\n });\n\n if (potentialIssuers.length === 1) {\n return potentialIssuers[0];\n }\n if (potentialIssuers.length > 1) {\n debugLog(\"findIssuerCertificateInChain: certificate is not self-signed but has several issuers\");\n return potentialIssuers[0];\n }\n return null;\n}\n\n/**\n * Lifecycle state of a {@link CertificateManager} instance.\n */\nexport enum CertificateManagerState {\n Uninitialized = 0,\n Initializing = 1,\n Initialized = 2,\n Disposing = 3,\n Disposed = 4\n}\n/**\n * Manages a GDS-compliant PKI directory structure for an OPC UA\n * application.\n *\n * The PKI store layout follows the OPC UA specification:\n *\n * ```\n * <location>/\n * ├── own/\n * │ ├── certs/ Own certificate(s)\n * │ └── private/ Own private key\n * ├── trusted/\n * │ ├── certs/ Trusted peer certificates\n * │ └── crl/ CRLs for trusted certs\n * ├── rejected/ Untrusted / rejected certificates\n * └── issuers/\n * ├── certs/ CA (issuer) certificates\n * └── crl/ CRLs for issuer certificates\n * ```\n *\n * File-system watchers keep the in-memory indexes in sync with\n * on-disk changes. Call {@link dispose} when the instance is no\n * longer needed to release watchers and allow the process to\n * exit cleanly.\n *\n * ## Environment Variables\n *\n * - **`OPCUA_PKI_USE_POLLING`** — set to `\"true\"` to use\n * polling-based file watching instead of native OS events.\n * Useful for NFS, CIFS, Docker volumes, or other remote /\n * virtual file systems where native events are unreliable.\n *\n * - **`OPCUA_PKI_POLLING_INTERVAL`** — polling interval in\n * milliseconds (only effective when polling is enabled).\n * Clamped to the range [100, 600 000]. Defaults to\n * {@link folderPollingInterval} (5 000 ms).\n *\n * @example\n * ```ts\n * const cm = new CertificateManager({ location: \"/var/pki\" });\n * await cm.initialize();\n * const status = await cm.verifyCertificate(cert);\n * await cm.dispose();\n * ```\n */\n\n// ── Chain completion result types ─────────────────────────────\n\n/**\n * Status codes returned by {@link CertificateManager.completeCertificateChain}.\n */\nexport enum ChainCompletionStatus {\n /** The chain already reached a self-signed root — no action was needed. */\n AlreadyComplete = \"AlreadyComplete\",\n\n /** One or more issuer certificates were successfully appended. */\n ChainCompleted = \"ChainCompleted\",\n\n /** The issuer for the last certificate in the chain could not be found\n * in the issuers or trusted stores. The chain is still partial. */\n IssuerNotFound = \"IssuerNotFound\",\n\n /** The input chain was empty. */\n EmptyChain = \"EmptyChain\",\n\n /** Chain completion was stopped because the maximum depth was reached. */\n MaxDepthReached = \"MaxDepthReached\"\n}\n\n/**\n * Result of {@link CertificateManager.completeCertificateChain}.\n */\nexport interface ChainCompletionResult {\n /** The (possibly completed) certificate chain, leaf first. */\n chain: Certificate[];\n\n /** Status code indicating whether completion succeeded and why/why not. */\n status: ChainCompletionStatus;\n\n /** Human-readable diagnostic message. */\n message: string;\n}\n\n// ── CertificateManager ───────────────────────────────────────\n\nexport class CertificateManager extends EventEmitter {\n // ── Global instance registry ─────────────────────────────────\n // Tracks all initialized CertificateManager instances so their\n // file watchers can be closed automatically on process exit,\n // even if the consumer forgets to call dispose().\n static #activeInstances = new Set<CertificateManager>();\n static #cleanupInstalled = false;\n static #exitHandler: (() => void) | undefined;\n\n /**\n * Install a best-effort `exit` hook that closes any watcher\n * still open when the process terminates.\n *\n * **This library never terminates the host process.** No\n * SIGINT/SIGTERM handler is installed: deciding how (and\n * whether) to shut down on a signal is the application's\n * responsibility, and a listener registered here would both\n * pre-empt the application's own graceful shutdown and\n * silently suppress Node's default signal behaviour.\n *\n * Nothing here is load-bearing for process exit. The native\n * `fs.watch` handles are `unref()`'d when the watchers are\n * created (see `#readCertificates`), so an undisposed\n * CertificateManager never keeps the event loop alive. This\n * hook is only tidiness on the way out.\n *\n * `exit` rather than `beforeExit`: `beforeExit` fires when\n * the loop merely drains and the loop can subsequently be\n * resurrected, which would leave a still-in-use instance\n * marked Disposed. `exit` is terminal, synchronous-only and\n * cannot alter the exit code.\n */\n static #installExitCleanup(): void {\n if (CertificateManager.#cleanupInstalled) return;\n CertificateManager.#cleanupInstalled = true;\n\n const closeDanglingWatchers = () => {\n for (const cm of CertificateManager.#activeInstances) {\n for (const w of cm.#watchers) {\n try {\n w.close();\n } catch {\n /* best-effort */\n }\n }\n cm.#watchers.splice(0);\n cm.state = CertificateManagerState.Disposed;\n }\n CertificateManager.#activeInstances.clear();\n };\n\n CertificateManager.#exitHandler = closeDanglingWatchers;\n process.on(\"exit\", closeDanglingWatchers);\n }\n\n /**\n * Remove the `exit` hook once the last instance is disposed,\n * so a library that is initialized and disposed repeatedly\n * does not accumulate process listeners. A later\n * `initialize()` re-arms it.\n */\n static #uninstallExitCleanupIfIdle(): void {\n if (CertificateManager.#activeInstances.size > 0) return;\n if (CertificateManager.#exitHandler) {\n process.removeListener(\"exit\", CertificateManager.#exitHandler);\n CertificateManager.#exitHandler = undefined;\n }\n CertificateManager.#cleanupInstalled = false;\n }\n\n /**\n * Dispose **all** active CertificateManager instances,\n * closing their file watchers and freeing resources.\n *\n * This is mainly useful in test tear-down to ensure the\n * Node.js process can exit cleanly.\n */\n public static async disposeAll(): Promise<void> {\n const instances = [...CertificateManager.#activeInstances];\n await Promise.all(instances.map((cm) => CertificateManager.prototype.dispose.call(cm)));\n }\n\n /**\n * Assert that all CertificateManager instances have been\n * properly disposed. Throws an Error listing the locations\n * of any leaked instances.\n *\n * Intended for use in test `afterAll()` / `afterEach()`\n * hooks to catch missing `dispose()` calls early.\n *\n * @example\n * ```ts\n * after(() => {\n * CertificateManager.checkAllDisposed();\n * });\n * ```\n */\n public static checkAllDisposed(): void {\n if (CertificateManager.#activeInstances.size === 0) return;\n const locations = [...CertificateManager.#activeInstances].map((cm) => cm.rootDir);\n throw new Error(\n `${CertificateManager.#activeInstances.size} CertificateManager instance(s) not disposed:\\n - ${locations.join(\"\\n - \")}`\n );\n }\n // ─────────────────────────────────────────────────────────────\n\n /**\n * When `true` (the default), any certificate that is not\n * already in the trusted or rejected store is automatically\n * written to the rejected folder the first time it is seen.\n */\n public untrustUnknownCertificate = true;\n /** Current lifecycle state of this instance. */\n public state: CertificateManagerState = CertificateManagerState.Uninitialized;\n /** @deprecated Use {@link folderPollingInterval} instead (typo fix). */\n public folderPoolingInterval = 5000;\n\n /** Interval in milliseconds for file-system polling (when enabled). */\n public get folderPollingInterval(): number {\n return this.folderPoolingInterval;\n }\n public set folderPollingInterval(value: number) {\n this.folderPoolingInterval = value;\n }\n\n /** RSA key size used when generating the private key. */\n public readonly keySize: KeySize;\n readonly #location: string;\n readonly #watchers: fs.FSWatcher[] = [];\n readonly #pendingUnrefs: Set<() => void> = new Set();\n #readCertificatesCalled = false;\n readonly #filenameToHash = new Map<string, string>();\n #initializingPromise?: Promise<void>;\n readonly #addCertValidation: Required<AddCertificateValidationOptions>;\n readonly #disableFileWatchers: boolean;\n readonly #privateKeyPassphrase?: PrivateKeyPassphrase;\n readonly #privateKeyProvider?: PrivateKeyProvider;\n readonly #keyOperations?: IKeyOperations;\n /** The stable lazy wrap handed out by {@link getKeyOperations} for non-opaque configurations. */\n #lazyLocalKeyOperations?: IKeyOperations;\n /**\n * The on-disk key, decrypted once and kept for the instance's lifetime,\n * so the passphrase (or its resolver function) is consulted at most\n * once. Cleared by `dispose()`. Not used when a provider is configured:\n * the provider is the authority on the current key.\n */\n #cachedPrivateKey?: PrivateKey;\n\n readonly #thumbs: Thumbs = {\n rejected: new Map(),\n trusted: new Map(),\n issuers: {\n certs: new Map()\n },\n crl: new Map(),\n issuersCrl: new Map()\n };\n\n /**\n * Create a new CertificateManager.\n *\n * The constructor creates the root directory if it does not\n * exist but does **not** initialise the PKI store — call\n * {@link initialize} before using any other method.\n *\n * @param options - configuration options\n */\n constructor(options: CertificateManagerOptions) {\n super();\n options.keySize = options.keySize || 2048;\n if (!options.location) {\n throw new Error(\"CertificateManager: missing 'location' option\");\n }\n\n this.#location = makePath(options.location, \"\");\n this.keySize = options.keySize;\n\n const v = options.addCertificateValidationOptions ?? {};\n this.#addCertValidation = {\n acceptExpiredCertificate: v.acceptExpiredCertificate ?? false,\n acceptRevokedCertificate: v.acceptRevokedCertificate ?? false,\n ignoreMissingRevocationList: v.ignoreMissingRevocationList ?? false,\n maxChainLength: v.maxChainLength ?? 5\n };\n\n this.#disableFileWatchers = options.disableFileWatchers ?? process.env.OPCUA_PKI_DISABLE_FILE_WATCHERS === \"true\";\n this.#privateKeyPassphrase = options.privateKeyPassphrase;\n this.#privateKeyProvider = options.privateKeyProvider;\n this.#keyOperations = options.keyOperations;\n if (this.#keyOperations && this.#privateKeyProvider) {\n throw new Error(\n \"CertificateManager: 'keyOperations' and 'privateKeyProvider' are mutually exclusive:\" +\n \" one hides the key, the other sources its material\"\n );\n }\n if (this.#keyOperations && this.#privateKeyPassphrase) {\n throw new Error(\n \"CertificateManager: 'privateKeyPassphrase' is meaningless with 'keyOperations':\" +\n \" there is no key material for a passphrase to protect\"\n );\n }\n\n mkdirRecursiveSync(options.location);\n\n if (!fs.existsSync(this.#location)) {\n throw new Error(`CertificateManager cannot access location ${this.#location}`);\n }\n }\n\n /** Path to the OpenSSL configuration file. */\n get configFile() {\n return path.join(this.rootDir, \"own/openssl.cnf\");\n }\n\n /** Root directory of the PKI store. */\n get rootDir() {\n return this.#location;\n }\n\n /**\n * Path to the private key file (`own/private/private_key.pem`).\n *\n * Kept for backward compatibility with code that reads the key\n * directly from disk. When a passphrase or a `privateKeyProvider` is\n * configured, prefer {@link getPrivateKey} instead — this getter still\n * returns the on-disk path even if a provider is configured (there may\n * be no meaningful file in that case).\n */\n get privateKey() {\n return path.join(this.rootDir, \"own/private/private_key.pem\");\n }\n\n /**\n * Resolve the private key: from `privateKeyProvider` if configured,\n * otherwise from disk (decrypting with `privateKeyPassphrase` if the\n * key is encrypted). Fails closed — throws\n * `PrivateKeyPassphraseRequiredError` — if the on-disk key is encrypted\n * and no passphrase is configured, or if the wrong passphrase is\n * configured.\n *\n * The on-disk key is read and decrypted once and then cached for the\n * lifetime of this instance, so a `privateKeyPassphrase` function is\n * called at most once (concurrent first calls share the same read). A\n * failed read is not cached, so a caller can fix the passphrase and\n * retry. A `privateKeyProvider` is consulted on every call: it is the\n * authority on what the current key is.\n */\n public async getPrivateKey(): Promise<PrivateKey> {\n if (this.#keyOperations) {\n throw new PrivateKeyUnavailableError(\n \"CertificateManager.getPrivateKey is not available when keyOperations is configured:\" +\n \" the private key is held by the key-operations provider (HSM/KMS) and cannot be read\" +\n \" — use getKeyOperations() instead\"\n );\n }\n if (this.#privateKeyProvider) {\n return await this.#privateKeyProvider.getPrivateKey();\n }\n if (this.#cachedPrivateKey) {\n return this.#cachedPrivateKey;\n }\n if (!this.#privateKeyPromise) {\n this.#privateKeyPromise = (async () => {\n const passphrase = await resolvePrivateKeyPassphrase(this.#privateKeyPassphrase);\n return readPrivateKey(this.privateKey, passphrase);\n })().then(\n (key) => {\n this.#cachedPrivateKey = key;\n return key;\n },\n (err) => {\n this.#privateKeyPromise = undefined; // not cached: allow a retry\n throw err;\n }\n );\n }\n return await this.#privateKeyPromise;\n }\n /** In-flight first read of the on-disk key, so concurrent callers share one passphrase resolution. */\n #privateKeyPromise?: Promise<PrivateKey>;\n\n /**\n * True when this manager's key is opaque — configured through\n * `keyOperations`, held by an HSM/KMS, never obtainable as material.\n * When true, {@link getPrivateKey} throws `PrivateKeyUnavailableError`\n * and {@link getKeyOperations} is the only way to use the key.\n */\n public isPrivateKeyOpaque(): boolean {\n return !!this.#keyOperations;\n }\n\n /**\n * The key as an opaque {@link IKeyOperations} — the recommended way to\n * *use* the private key regardless of where it lives.\n *\n * Returns the configured `keyOperations` object when the key is opaque.\n * Otherwise returns a stable lazy wrap over {@link getPrivateKey}: its\n * methods resolve the key on first use (disk read, passphrase,\n * `privateKeyProvider` — all async), so the wrap offers no synchronous\n * fast path; callers that need one resolve the key themselves and build\n * a `LocalKeyOperations` over it. The wrap follows key rotation: a\n * `privateKeyProvider` that starts returning a different key gets a\n * fresh underlying `LocalKeyOperations`.\n */\n public getKeyOperations(): IKeyOperations {\n if (this.#keyOperations) {\n return this.#keyOperations;\n }\n if (!this.#lazyLocalKeyOperations) {\n let cached: { key: PrivateKey; ops: LocalKeyOperations } | undefined;\n const resolve = async (): Promise<LocalKeyOperations> => {\n const key = await this.getPrivateKey();\n // keyed by identity: the disk path always returns the cached envelope,\n // while a provider that rotates the key yields a fresh wrap\n if (!cached || cached.key !== key) {\n cached = { key, ops: keyOperationsFromPrivateKey(key) };\n }\n return cached.ops;\n };\n this.#lazyLocalKeyOperations = {\n sign: async (data, params) => (await resolve()).sign(data, params),\n decryptBlock: async (block, params) => (await resolve()).decryptBlock(block, params),\n getKeyMetadata: async () => (await resolve()).getKeyMetadata(),\n getPublicKey: async () => (await resolve()).getPublicKey()\n };\n }\n return this.#lazyLocalKeyOperations;\n }\n\n /**\n * Fail closed at `initialize()` time, not on the first certificate\n * operation, if the key cannot actually be used: wrong/missing\n * passphrase on an encrypted key, a broken `privateKeyProvider`, or an\n * unreachable `keyOperations` provider (probed via `getKeyMetadata`).\n */\n async #probePrivateKey(): Promise<void> {\n if (this.#keyOperations) {\n await this.#keyOperations.getKeyMetadata();\n return;\n }\n await this.getPrivateKey();\n }\n\n /**\n * The key to hand to a certificate-issuance primitive: the raw\n * {@link PrivateKey} for a local configuration, or a {@link CaSigner}\n * adapted from `keyOperations` when the key is opaque — which requires\n * the provider to implement `getPublicKey` (the adapter says so if not).\n */\n async #resolveSigningKey(): Promise<PrivateKey | CaSigner> {\n if (this.#keyOperations) {\n return caSignerFromKeyOperations(this.#keyOperations);\n }\n return await this.getPrivateKey();\n }\n\n /**\n * Enable, disable, or rotate the passphrase protecting the on-disk\n * private key: decrypt with `oldPassphrase` (omit if the key is\n * currently unencrypted), then write back encrypted with\n * `newPassphrase` (omit to leave it unencrypted). The write goes to a\n * temporary file in the same directory and is atomically renamed into\n * place, so a crash mid-rotation cannot leave a partially-written key;\n * the temporary file is removed if anything fails, so a rotation *to*\n * plaintext can never leave a stray cleartext copy behind. Runs under\n * the same lock as `initialize()`.\n *\n * This only rewrites the on-disk file — it does not update this\n * instance's own `privateKeyPassphrase` (set at construction), and it\n * drops this instance's cached key so that disk stays the source of\n * truth. Construct a new `CertificateManager` with the new passphrase to\n * continue using it afterward.\n *\n * Not supported when a `privateKeyProvider` is configured (there is no\n * disk file for this method to rewrite).\n */\n public async reencryptPrivateKey(oldPassphrase?: PrivateKeyPassphrase, newPassphrase?: PrivateKeyPassphrase): Promise<void> {\n if (this.#keyOperations) {\n throw new PrivateKeyUnavailableError(\n \"reencryptPrivateKey: not supported when keyOperations is configured — there is no key material to rewrite\"\n );\n }\n if (this.#privateKeyProvider) {\n throw new Error(\"reencryptPrivateKey: not supported when a privateKeyProvider is configured\");\n }\n const oldPass = await resolvePrivateKeyPassphrase(oldPassphrase);\n const newPass = await resolvePrivateKeyPassphrase(newPassphrase);\n await this.withLock2(async () => {\n const privateKey = readPrivateKey(this.privateKey, oldPass);\n await this.#rewritePrivateKeyFile(privateKey, newPass);\n });\n this.#cachedPrivateKey = undefined;\n this.#privateKeyPromise = undefined;\n }\n\n /**\n * Atomically replace the on-disk private key with `privateKey`, written\n * as PKCS#8 (encrypted with `passphrase` if given). Temp file next to the\n * target, `0600`, renamed into place; the temp file is unlinked on any\n * failure so no partial or cleartext copy can be left behind.\n * Caller must hold the lock.\n */\n async #rewritePrivateKeyFile(privateKey: PrivateKey, passphrase: string | undefined): Promise<void> {\n const tmpFilename = `${this.privateKey}.${process.pid}-${Date.now()}.tmp`;\n try {\n await writePrivateKeyFile(tmpFilename, privateKey, { passphrase });\n await fs.promises.rename(tmpFilename, this.privateKey);\n } finally {\n await fs.promises.rm(tmpFilename, { force: true });\n }\n }\n\n /** Path to the OpenSSL random seed file. */\n get randomFile() {\n return path.join(this.rootDir, \"./random.rnd\");\n }\n\n /**\n * Move a certificate to the rejected store.\n * If the certificate was previously trusted, it will be removed from the trusted folder.\n * @param certificateOrChain - the DER-encoded certificate or certificate chain\n */\n public async rejectCertificate(certificateOrChain: Certificate | Certificate[]): Promise<void> {\n await this.#moveCertificate(certificateOrChain, \"rejected\");\n }\n\n /**\n * Move a certificate to the trusted store.\n * If the certificate was previously rejected, it will be removed from the rejected folder.\n * @param certificateOrChain - the DER-encoded certificate or certificate chain\n */\n public async trustCertificate(certificateOrChain: Certificate | Certificate[]): Promise<void> {\n await this.#moveCertificate(certificateOrChain, \"trusted\");\n }\n\n /**\n * Check whether the trusted certificate store is empty.\n *\n * This inspects the in-memory index, which is kept in\n * sync with the `trusted/certs/` folder by file-system\n * watchers after {@link initialize} has been called.\n */\n public isTrustListEmpty(): boolean {\n return this.#thumbs.trusted.size === 0;\n }\n\n /**\n * Return the number of certificates currently in the\n * trusted store.\n */\n public getTrustedCertificateCount(): number {\n return this.#thumbs.trusted.size;\n }\n\n /** Path to the rejected certificates folder. */\n public get rejectedFolder(): string {\n return path.join(this.rootDir, \"rejected\");\n }\n /** Path to the trusted certificates folder. */\n public get trustedFolder(): string {\n return path.join(this.rootDir, \"trusted/certs\");\n }\n /** Path to the trusted CRL folder. */\n public get crlFolder(): string {\n return path.join(this.rootDir, \"trusted/crl\");\n }\n /** Path to the issuer (CA) certificates folder. */\n public get issuersCertFolder(): string {\n return path.join(this.rootDir, \"issuers/certs\");\n }\n /** Path to the issuer CRL folder. */\n public get issuersCrlFolder(): string {\n return path.join(this.rootDir, \"issuers/crl\");\n }\n /** Path to the own certificate folder. */\n public get ownCertFolder(): string {\n return path.join(this.rootDir, \"own/certs\");\n }\n public get ownPrivateFolder(): string {\n return path.join(this.rootDir, \"own/private\");\n }\n\n /**\n * Check if a certificate is in the trusted store.\n * If the certificate is unknown and `untrustUnknownCertificate` is set,\n * it will be written to the rejected folder.\n * @param certificate - the DER-encoded certificate\n * @returns `\"Good\"` if trusted, `\"BadCertificateUntrusted\"` if rejected/unknown,\n * or `\"BadCertificateInvalid\"` if the certificate cannot be parsed.\n */\n public async isCertificateTrusted(\n certificateOrCertificateChain: Certificate | Certificate[]\n ): Promise<\"Good\" | \"BadCertificateUntrusted\" | \"BadCertificateInvalid\"> {\n try {\n const chain = coerceCertificateChain(certificateOrCertificateChain);\n const leafCertificate = chain[0];\n if (chain.length < 1) {\n return \"BadCertificateInvalid\";\n }\n let fingerprint: Thumbprint;\n try {\n fingerprint = makeFingerprint(chain[0]) as Thumbprint;\n } catch (_err) {\n return \"BadCertificateInvalid\";\n }\n\n if (this.#thumbs.trusted.has(fingerprint)) {\n return \"Good\";\n }\n\n if (!this.#thumbs.rejected.has(fingerprint)) {\n if (!this.untrustUnknownCertificate) {\n return \"Good\";\n }\n // Verify structure before writing — don't persist invalid data\n try {\n exploreCertificateInfo(chain[0]);\n } catch (_err) {\n return \"BadCertificateInvalid\";\n }\n\n const filename = path.join(this.rejectedFolder, `${buildIdealCertificateName(leafCertificate)}.pem`);\n debugLog(\"certificate has never been seen before and is now rejected (untrusted) \", filename);\n\n await fsWriteFile(filename, toPem(chain, \"CERTIFICATE\"));\n this.#thumbs.rejected.set(fingerprint, { certificate: leafCertificate, filename });\n }\n return \"BadCertificateUntrusted\";\n } catch (_err) {\n return \"BadCertificateInvalid\";\n }\n }\n async #innerVerifyCertificateAsync(\n certificateOrChain: Certificate | Certificate[],\n _isIssuer: boolean,\n level: number,\n options: VerifyCertificateOptions\n ): Promise<VerificationStatus> {\n if (level >= 5) {\n // maximum level of certificate in chain reached !\n return VerificationStatus.BadSecurityChecksFailed;\n }\n const chain = coerceCertificateChain(certificateOrChain);\n debugLog(\"NB CERTIFICATE IN CHAIN = \", chain.length);\n const info = exploreCertificate(chain[0]);\n\n let hasValidIssuer = false;\n let hasTrustedIssuer = false;\n // check if certificate is attached to a issuer\n const hasIssuerKey = info.tbsCertificate.extensions?.authorityKeyIdentifier?.keyIdentifier;\n debugLog(\"Certificate as an Issuer Key\", hasIssuerKey);\n\n if (hasIssuerKey) {\n const isSelfSigned = isSelfSigned2(info);\n\n debugLog(\"Is the Certificate self-signed ?\", isSelfSigned);\n if (!isSelfSigned) {\n debugLog(\n \"Is issuer found in the list of know issuers ?\",\n \"\\n subjectKeyIdentifier = \",\n info.tbsCertificate.extensions?.subjectKeyIdentifier,\n \"\\n authorityKeyIdentifier = \",\n info.tbsCertificate.extensions?.authorityKeyIdentifier?.keyIdentifier\n );\n let issuerCertificate = await this.findIssuerCertificate(chain[0]);\n if (!issuerCertificate) {\n // the issuer has not been found in the list of trusted certificate\n // may be the issuer certificate is in the chain itself ?\n issuerCertificate = findIssuerCertificateInChain(chain[0], chain);\n if (!issuerCertificate) {\n debugLog(\n \" the issuer has not been found in the chain itself nor in the issuer.cert list => the chain is incomplete!\"\n );\n return VerificationStatus.BadCertificateChainIncomplete;\n }\n debugLog(\" the issuer certificate has been found in the chain itself ! the chain is complete !\");\n } else {\n debugLog(\" the issuer certificate has been found in the issuer.cert folder !\");\n }\n const issuerStatus = await this.#innerVerifyCertificateAsync(issuerCertificate, true, level + 1, options);\n if (issuerStatus === VerificationStatus.BadCertificateRevocationUnknown) {\n // the issuer must have a CRL available .... !\n return VerificationStatus.BadCertificateIssuerRevocationUnknown;\n }\n if (issuerStatus === VerificationStatus.BadCertificateIssuerRevocationUnknown) {\n // the issuer must have a CRL available .... !\n return VerificationStatus.BadCertificateIssuerRevocationUnknown;\n }\n if (issuerStatus === VerificationStatus.BadCertificateTimeInvalid) {\n if (!options?.acceptOutDatedIssuerCertificate) {\n // the issuer must have valid dates ....\n return VerificationStatus.BadCertificateIssuerTimeInvalid;\n }\n }\n if (issuerStatus === VerificationStatus.BadCertificateUntrusted) {\n debugLog(\"warning issuerStatus = \", issuerStatus.toString(), \"the issuer certificate is not trusted\");\n // return VerificationStatus.BadSecurityChecksFailed;\n }\n\n if (issuerStatus !== VerificationStatus.Good && issuerStatus !== VerificationStatus.BadCertificateUntrusted) {\n // if the issuer has other issue => let's drop!\n return VerificationStatus.BadSecurityChecksFailed;\n }\n // verify that certificate was signed by issuer\n const isCertificateSignatureOK = verifyCertificateSignature(chain[0], issuerCertificate);\n if (!isCertificateSignatureOK) {\n debugLog(\" the certificate was not signed by the issuer as it claim to be ! Danger\");\n return VerificationStatus.BadSecurityChecksFailed;\n }\n hasValidIssuer = true;\n\n // let detected if our certificate is in the revocation list\n let revokedStatus = await this.isCertificateRevoked(chain, issuerCertificate);\n if (revokedStatus === VerificationStatus.BadCertificateRevocationUnknown) {\n if (options?.ignoreMissingRevocationList) {\n // continue as if the certificate was not revoked\n revokedStatus = VerificationStatus.Good;\n }\n }\n if (revokedStatus !== VerificationStatus.Good) {\n // certificate is revoked !!!\n debugLog(\"revokedStatus\", revokedStatus);\n return revokedStatus;\n }\n\n // let check if the issuer is explicitly trusted\n const issuerTrustedStatus = await this.#checkRejectedOrTrusted(issuerCertificate);\n debugLog(\"issuerTrustedStatus\", issuerTrustedStatus);\n\n if (issuerTrustedStatus === \"unknown\") {\n hasTrustedIssuer = false;\n } else if (issuerTrustedStatus === \"trusted\") {\n hasTrustedIssuer = true;\n } else if (issuerTrustedStatus === \"rejected\") {\n // we should never get there: this should have been detected before !!!\n return VerificationStatus.BadSecurityChecksFailed;\n }\n } else {\n // verify that certificate was signed by issuer (self in this case)\n const isCertificateSignatureOK = verifyCertificateSignature(chain[0], chain[0]);\n if (!isCertificateSignatureOK) {\n debugLog(\"Self-signed Certificate signature is not valid\");\n return VerificationStatus.BadSecurityChecksFailed;\n }\n const revokedStatus = await this.isCertificateRevoked(chain);\n debugLog(\"revokedStatus of self signed certificate:\", revokedStatus);\n }\n }\n\n const status = await this.#checkRejectedOrTrusted(chain[0]);\n if (status === \"rejected\") {\n if (!(options.acceptCertificateWithValidIssuerChain && hasValidIssuer && hasTrustedIssuer)) {\n return VerificationStatus.BadCertificateUntrusted;\n }\n }\n // Has SoftwareCertificate passed its issue date and has it not expired ?\n // check dates\n //\n // exploreCertificate rather than exploreCertificateInfo: only the two\n // dates are wanted, and exploreCertificateInfo additionally insists on\n // an RSA-sized public key. It threw on an EC certificate, which the\n // caller then saw as BadCertificateInvalid - a verdict about the key\n // type, reported as if the certificate were malformed. An issuer\n // parsed the same way, purely to be written to the debug log, made\n // that fatal for any chain with an EC issuer in it.\n const { validity } = exploreCertificate(chain[0]).tbsCertificate;\n const now = new Date();\n\n let isTimeInvalid = false;\n // check that certificate is active\n if (validity.notBefore.getTime() > now.getTime()) {\n // certificate is not active yet\n debugLog(\n `${chalk.red(\"certificate is invalid : certificate is not active yet !\")} not before date =${validity.notBefore}`\n );\n if (!options.acceptPendingCertificate) {\n isTimeInvalid = true;\n }\n }\n\n // check that certificate has not expired\n if (validity.notAfter.getTime() <= now.getTime()) {\n // certificate is obsolete\n debugLog(`${chalk.red(\"certificate is invalid : certificate has expired !\")} not after date =${validity.notAfter}`);\n if (!options.acceptOutdatedCertificate) {\n isTimeInvalid = true;\n }\n }\n if (status === \"trusted\") {\n return isTimeInvalid ? VerificationStatus.BadCertificateTimeInvalid : VerificationStatus.Good;\n }\n // status should be \"unknown\" or \"rejected\" (bypassed) at this point\n if (hasIssuerKey) {\n if (!hasTrustedIssuer) {\n return VerificationStatus.BadCertificateUntrusted;\n }\n if (!hasValidIssuer) {\n return VerificationStatus.BadCertificateUntrusted;\n }\n if (!options.acceptCertificateWithValidIssuerChain) {\n // strict mode: the leaf cert is not in the trusted store\n return VerificationStatus.BadCertificateUntrusted;\n }\n return isTimeInvalid ? VerificationStatus.BadCertificateTimeInvalid : VerificationStatus.Good;\n } else {\n return VerificationStatus.BadCertificateUntrusted;\n }\n }\n\n /**\n * Internal verification hook called by {@link verifyCertificate}.\n *\n * Subclasses can override this to inject additional validation\n * logic (e.g. application-level policy checks) while still\n * delegating to the default chain/CRL/trust verification.\n *\n * @param certificate - the DER-encoded certificate to verify\n * @param options - verification options forwarded from the\n * public API\n * @returns the verification status code\n */\n protected async verifyCertificateAsync(\n certificate: Certificate | Certificate[],\n options: VerifyCertificateOptions\n ): Promise<VerificationStatus> {\n const chain = coerceCertificateChain(certificate);\n for (const element of chain) {\n try {\n // exploreCertificate throws if the DER element is not a\n // valid X.509 certificate (e.g. it is a CRL or some other\n // ASN.1 structure), which is the only question being asked\n // here. exploreCertificateInfo used to stand in for it, but\n // it also insists on an RSA-sized public key, so every chain\n // containing an EC certificate was reported invalid on\n // structural grounds it never actually failed.\n exploreCertificate(element);\n } catch (_err) {\n return VerificationStatus.BadCertificateInvalid;\n }\n }\n const status1 = await this.#innerVerifyCertificateAsync(chain, false, 0, options);\n return status1;\n }\n\n /**\n * Verify a certificate against the PKI trust store.\n *\n * This performs a full validation including trust status,\n * issuer chain, CRL revocation checks, and time validity.\n *\n * @param certificate - the DER-encoded certificate to verify\n * @param options - optional flags to relax validation rules\n * @returns the verification status code\n */\n public async verifyCertificate(\n certificate: Certificate | Certificate[],\n options?: VerifyCertificateOptions\n ): Promise<VerificationStatus> {\n // Is the signature on the SoftwareCertificate valid .?\n if (!certificate) {\n // missing certificate\n return VerificationStatus.BadSecurityChecksFailed;\n }\n try {\n const status = await this.verifyCertificateAsync(certificate, options || {});\n return status;\n } catch (error) {\n warningLog(`verifyCertificate error: ${(error as Error).message}`);\n return VerificationStatus.BadCertificateInvalid;\n }\n }\n\n /**\n * Initialize the PKI directory structure, generate the\n * private key (if missing), and start file-system watchers.\n *\n * This method is idempotent — subsequent calls are no-ops.\n * It must be called before any certificate operations.\n */\n public async initialize(): Promise<void> {\n if (this.state !== CertificateManagerState.Uninitialized) {\n return;\n }\n this.state = CertificateManagerState.Initializing;\n this.#initializingPromise = this.#initialize();\n try {\n await this.#initializingPromise;\n } catch (err) {\n // Fail closed but not stuck: a failed initialize() (typically a\n // wrong or missing private-key passphrase) must leave the\n // instance re-initializable, not parked in Initializing where a\n // retry would silently no-op with empty trust indexes.\n this.#initializingPromise = undefined;\n this.state = CertificateManagerState.Uninitialized;\n throw err;\n }\n this.#initializingPromise = undefined;\n this.state = CertificateManagerState.Initialized;\n\n // Register for automatic cleanup on process exit\n CertificateManager.#activeInstances.add(this);\n CertificateManager.#installExitCleanup();\n }\n\n async #initialize(): Promise<void> {\n const pkiDir = this.#location;\n mkdirRecursiveSync(pkiDir);\n mkdirRecursiveSync(path.join(pkiDir, \"own\"));\n mkdirRecursiveSync(path.join(pkiDir, \"own/certs\"));\n ensurePrivateDirectory(path.join(pkiDir, \"own/private\"));\n mkdirRecursiveSync(path.join(pkiDir, \"rejected\"));\n mkdirRecursiveSync(path.join(pkiDir, \"trusted\"));\n mkdirRecursiveSync(path.join(pkiDir, \"trusted/certs\"));\n mkdirRecursiveSync(path.join(pkiDir, \"trusted/crl\"));\n\n mkdirRecursiveSync(path.join(pkiDir, \"issuers\"));\n mkdirRecursiveSync(path.join(pkiDir, \"issuers/certs\")); // contains Trusted CA certificates\n mkdirRecursiveSync(path.join(pkiDir, \"issuers/crl\")); // contains CRL of revoked CA certificates\n\n // when a privateKeyProvider or keyOperations is configured it overrides disk\n // entirely, so there is no on-disk key to generate, encrypt, or check for existence\n const ownsDiskKey = !this.#privateKeyProvider && !this.#keyOperations;\n const needsKeyGeneration = ownsDiskKey && !fs.existsSync(this.privateKey);\n // Secure by default: a passphrase configured on an install whose key\n // is still plaintext means \"protect this key\", not \"ignore me\". Node's\n // createPrivateKey would silently accept the plaintext key with any\n // passphrase, so detect it here and encrypt in place.\n const needsKeyEncryption =\n ownsDiskKey &&\n !needsKeyGeneration &&\n this.#privateKeyPassphrase !== undefined &&\n !isEncryptedPrivateKeyFile(this.privateKey);\n\n if (!fs.existsSync(this.configFile) || needsKeyGeneration || needsKeyEncryption) {\n return await this.withLock2(async () => {\n if (this.state === CertificateManagerState.Disposing || this.state === CertificateManagerState.Disposed) {\n return;\n }\n\n if (!fs.existsSync(this.configFile)) {\n fs.writeFileSync(this.configFile, configurationFileSimpleTemplate);\n }\n // note : openssl 1.1.1 has a bug that causes a failure if\n // random file cannot be found. (should be fixed in 1.1.1.a)\n // if this issue become important we may have to consider checking that rndFile exists and recreate\n // it if not . this could be achieved with the command :\n // \"openssl rand -writerand ${this.randomFile}\"\n //\n // cf: https://github.com/node-opcua/node-opcua/issues/554\n\n if (ownsDiskKey && !fs.existsSync(this.privateKey)) {\n debugLog(\"generating private key ...\");\n // setEnv(\"RANDFILE\", this.randomFile);\n const passphrase = await resolvePrivateKeyPassphrase(this.#privateKeyPassphrase);\n await generatePrivateKeyFile(this.privateKey, this.keySize, { passphrase });\n // seed the cache from the passphrase we already resolved,\n // so a passphrase function is not called a second time below\n this.#cachedPrivateKey = readPrivateKey(this.privateKey, passphrase);\n } else if (ownsDiskKey && this.#privateKeyPassphrase !== undefined && !isEncryptedPrivateKeyFile(this.privateKey)) {\n // (re-checked under the lock: another instance may have done it first)\n warningLog(\"initialize: private key is plaintext but a passphrase is configured; encrypting it in place\");\n const passphrase = await resolvePrivateKeyPassphrase(this.#privateKeyPassphrase);\n const plaintextKey = readPrivateKey(this.privateKey);\n await this.#rewritePrivateKeyFile(plaintextKey, passphrase);\n this.#cachedPrivateKey = plaintextKey;\n }\n if (ownsDiskKey) {\n // repair permissions on installs created before this hardening,\n // and confirm them on a freshly generated key\n restrictPrivateFilePermissions(this.privateKey, 0o600);\n }\n await this.#probePrivateKey();\n await this.#readCertificates();\n });\n } else {\n if (ownsDiskKey) {\n restrictPrivateFilePermissions(this.privateKey, 0o600);\n }\n await this.#probePrivateKey();\n await this.#readCertificates();\n }\n }\n\n /**\n * Dispose of the CertificateManager, releasing file watchers\n * and other resources. The instance should not be used after\n * calling this method.\n */\n public async dispose(): Promise<void> {\n if (this.state === CertificateManagerState.Disposing) {\n throw new Error(\"Already disposing\");\n }\n\n if (this.state === CertificateManagerState.Uninitialized) {\n this.state = CertificateManagerState.Disposed;\n return;\n }\n\n // Wait for initialization to complete before disposing\n if (this.state === CertificateManagerState.Initializing) {\n if (this.#initializingPromise) {\n await this.#initializingPromise;\n }\n }\n\n try {\n this.state = CertificateManagerState.Disposing;\n // Wait for any in-flight withLock operations (e.g.\n // fire-and-forget trustCertificate calls) to complete\n // so their setInterval timers are properly cleared.\n await drainPendingLocks();\n // Ensure all fs.watch handles are unref'd even if\n // chokidar hasn't reached \"ready\" yet.\n for (const unreff of this.#pendingUnrefs) {\n unreff();\n }\n this.#pendingUnrefs.clear();\n await Promise.all(this.#watchers.map((w) => w.close()));\n this.#watchers.forEach((w) => {\n w.removeAllListeners();\n });\n this.#watchers.splice(0);\n } finally {\n this.state = CertificateManagerState.Disposed;\n this.#cachedPrivateKey = undefined;\n this.#privateKeyPromise = undefined;\n CertificateManager.#activeInstances.delete(this);\n CertificateManager.#uninstallExitCleanupIfIdle();\n }\n }\n\n /**\n * Force a full re-scan of all PKI folders, rebuilding\n * the in-memory `_thumbs` index from scratch.\n *\n * Call this after external processes have modified the\n * PKI folders (e.g. via `writeTrustList` or CLI tools)\n * to ensure the CertificateManager sees the latest\n * state without waiting for file-system events.\n */\n public async reloadCertificates(): Promise<void> {\n // Close existing watchers\n await Promise.all(this.#watchers.map((w) => w.close()));\n for (const w of this.#watchers) {\n w.removeAllListeners();\n }\n this.#watchers.splice(0);\n\n // Clear in-memory indexes\n this.#thumbs.rejected.clear();\n this.#thumbs.trusted.clear();\n this.#thumbs.issuers.certs.clear();\n this.#thumbs.crl.clear();\n this.#thumbs.issuersCrl.clear();\n this.#filenameToHash.clear();\n\n // Re-scan all folders\n this.#readCertificatesCalled = false;\n await this.#readCertificates();\n }\n\n protected async withLock2<T>(action: () => Promise<T>): Promise<T> {\n const lockFileName = path.join(this.rootDir, \"mutex\");\n return withLock<T>({ fileToLock: lockFileName }, async () => {\n return await action();\n });\n }\n /**\n * Create a self-signed certificate for this PKI's private key.\n *\n * The certificate is written to `params.outputFile` or\n * `own/certs/self_signed_certificate.pem` by default.\n *\n * @param params - certificate parameters (subject, SANs,\n * validity, etc.)\n */\n public async createSelfSignedCertificate(params: CreateSelfSignCertificateParam1): Promise<void> {\n if (typeof params.applicationUri !== \"string\") {\n throw new Error(\"createSelfSignedCertificate: expecting applicationUri to be a string\");\n }\n if (!this.#privateKeyProvider && !this.#keyOperations && !fs.existsSync(this.privateKey)) {\n throw new Error(`Cannot find private key ${this.privateKey}`);\n }\n let certificateFilename = path.join(this.rootDir, \"own/certs/self_signed_certificate.pem\");\n certificateFilename = params.outputFile || certificateFilename;\n\n // a copy, not an in-place mutation: the caller's object must never\n // end up holding the resolved private key material\n const _params: CreateSelfSignCertificateWithConfigParam = {\n ...(params as unknown as CreateSelfSignCertificateWithConfigParam),\n rootDir: this.rootDir,\n configFile: this.configFile,\n privateKey: await this.#resolveSigningKey(),\n subject: params.subject || \"CN=FIXME\"\n };\n await this.withLock2(async () => {\n await createSelfSignedCertificate(certificateFilename, _params);\n });\n }\n\n /**\n * Create a Certificate Signing Request (CSR) using this\n * PKI's private key and configuration.\n *\n * The CSR file is written to `own/certs/` with a timestamped\n * filename.\n *\n * @param params - CSR parameters (subject, SANs)\n * @returns the filesystem path to the generated CSR file\n */\n public async createCertificateRequest(params: CreateSelfSignCertificateParam): Promise<Filename> {\n if (!params) {\n throw new Error(\"params is required\");\n }\n if (Object.prototype.hasOwnProperty.call(params, \"rootDir\")) {\n throw new Error(\"rootDir should not be specified \");\n }\n // a copy, not an in-place mutation: the caller's object must never\n // end up holding the resolved private key material\n const _params: CreateSelfSignCertificateWithConfigParam = {\n ...(params as CreateSelfSignCertificateWithConfigParam),\n rootDir: path.resolve(this.rootDir),\n configFile: path.resolve(this.configFile),\n privateKey: await this.#resolveSigningKey()\n };\n\n return await this.withLock2<string>(async () => {\n // compose a file name for the request\n const now = new Date();\n const today = `${now.toISOString().slice(0, 10)}_${now.getTime()}`;\n const certificateSigningRequestFilename = path.join(this.rootDir, \"own/certs\", `certificate_${today}.csr`);\n await createCertificateSigningRequestAsync(certificateSigningRequestFilename, _params);\n return certificateSigningRequestFilename;\n });\n }\n\n /**\n * Add a CA (issuer) certificate to the issuers store.\n * If the certificate is already present, this is a no-op.\n * @param certificate - the DER-encoded CA certificate\n * @param validate - if `true`, verify the certificate before adding\n * @param addInTrustList - if `true`, also add to the trusted store\n * @returns `VerificationStatus.Good` on success\n */\n public async addIssuer(certificate: DER, validate = false, addInTrustList = false): Promise<VerificationStatus> {\n if (validate) {\n const status = await this.verifyCertificate(certificate);\n if (status !== VerificationStatus.Good && status !== VerificationStatus.BadCertificateUntrusted) {\n return status;\n }\n }\n const pemCertificate = toPem(certificate, \"CERTIFICATE\");\n const fingerprint = makeFingerprint(certificate);\n if (this.#thumbs.issuers.certs.has(fingerprint)) {\n // already in .. simply ignore\n return VerificationStatus.Good;\n }\n // write certificate\n const filename = path.join(this.issuersCertFolder, `issuer_${buildIdealCertificateName(certificate)}.pem`);\n await fs.promises.writeFile(filename, pemCertificate, \"ascii\");\n\n // first time seen, let's save it.\n this.#thumbs.issuers.certs.set(fingerprint, { certificate, filename });\n\n if (addInTrustList) {\n // add certificate in the trust list as well\n await this.trustCertificate(certificate);\n }\n\n return VerificationStatus.Good;\n }\n\n /**\n * Add multiple CA (issuer) certificates to the issuers store.\n * @param certificates - the DER-encoded CA certificates\n * @param validate - if `true`, verify each certificate before adding\n * @param addInTrustList - if `true`, also add each certificate to the trusted store\n * @returns `VerificationStatus.Good` on success\n */\n public async addIssuers(certificates: Certificate[], validate = false, addInTrustList = false): Promise<VerificationStatus> {\n for (const certificate of certificates) {\n // check that certificate is a issuer certificate\n if (!isIssuer(certificate)) {\n warningLog(`Certificate ${makeFingerprint(certificate)} is not a issuer certificate`);\n continue;\n }\n await this.addIssuer(certificate, validate, addInTrustList);\n }\n return VerificationStatus.Good;\n }\n\n /**\n * Add a CRL to the certificate manager.\n * @param crl - the CRL to add\n * @param target - \"issuers\" (default) writes to issuers/crl, \"trusted\" writes to trusted/crl\n */\n public async addRevocationList(\n crl: CertificateRevocationList,\n target: \"issuers\" | \"trusted\" = \"issuers\"\n ): Promise<VerificationStatus> {\n return await this.withLock2<VerificationStatus>(async () => {\n try {\n const index = target === \"trusted\" ? this.#thumbs.crl : this.#thumbs.issuersCrl;\n const folder = target === \"trusted\" ? this.crlFolder : this.issuersCrlFolder;\n\n const crlInfo = exploreCertificateRevocationList(crl);\n const key = crlInfo.tbsCertList.issuerFingerprint;\n if (!index.has(key)) {\n index.set(key, { crls: [], serialNumbers: {} });\n }\n const pemCertificate = toPem(crl, \"X509 CRL\");\n // Use the issuer fingerprint for the filename — NOT buildIdealCertificateName()\n // which expects a certificate, not a CRL. Passing a CRL causes\n // exploreCertificate() to throw, producing \"invalid_certificate_\" names.\n const sanitizedKey = key.replace(/:/g, \"\");\n const filename = path.join(folder, `crl_[${sanitizedKey}].pem`);\n await fs.promises.writeFile(filename, pemCertificate, \"ascii\");\n\n await this.#onCrlFileAdded(index, filename);\n\n await this.#waitAndCheckCRLProcessingStatus();\n\n return VerificationStatus.Good;\n } catch (err) {\n debugLog(err);\n return VerificationStatus.BadSecurityChecksFailed;\n }\n });\n }\n\n /**\n * Remove all CRL files from the specified folder(s) and clear the\n * corresponding in-memory index.\n * @param target - \"issuers\" clears issuers/crl, \"trusted\" clears\n * trusted/crl, \"all\" clears both.\n */\n public async clearRevocationLists(target: \"issuers\" | \"trusted\" | \"all\"): Promise<void> {\n const clearFolder = async (folder: string, index: Map<string, CRLData>) => {\n try {\n const files = await fs.promises.readdir(folder);\n for (const file of files) {\n const ext = path.extname(file).toLowerCase();\n if (ext === \".crl\" || ext === \".pem\" || ext === \".der\") {\n await fs.promises.unlink(path.join(folder, file));\n }\n }\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n index.clear();\n };\n\n if (target === \"issuers\" || target === \"all\") {\n await clearFolder(this.issuersCrlFolder, this.#thumbs.issuersCrl);\n }\n if (target === \"trusted\" || target === \"all\") {\n await clearFolder(this.crlFolder, this.#thumbs.crl);\n }\n }\n\n /**\n * Check whether an issuer certificate with the given thumbprint\n * is already registered.\n * @param thumbprint - hex-encoded SHA-1 thumbprint (lowercase)\n */\n public async hasIssuer(thumbprint: string): Promise<boolean> {\n await this.#readCertificates();\n const normalized = thumbprint.toLowerCase();\n return this.#thumbs.issuers.certs.has(normalized);\n }\n\n /**\n * Remove a trusted certificate identified by its SHA-1 thumbprint.\n * Deletes the file on disk and removes the entry from the\n * in-memory index.\n * @param thumbprint - hex-encoded SHA-1 thumbprint (lowercase)\n * @returns the removed certificate buffer, or `null` if not found\n */\n public async removeTrustedCertificate(thumbprint: string): Promise<Certificate | null> {\n await this.#readCertificates();\n const normalized = thumbprint.toLowerCase();\n const entry = this.#thumbs.trusted.get(normalized);\n if (!entry) {\n return null;\n }\n try {\n await fs.promises.unlink(entry.filename);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n this.#thumbs.trusted.delete(normalized);\n return entry.certificate;\n }\n\n /**\n * Remove an issuer certificate identified by its SHA-1 thumbprint.\n * Deletes the file on disk and removes the entry from the\n * in-memory index.\n * @param thumbprint - hex-encoded SHA-1 thumbprint (lowercase)\n * @returns the removed certificate buffer, or `null` if not found\n */\n public async removeIssuer(thumbprint: string): Promise<Certificate | null> {\n await this.#readCertificates();\n const normalized = thumbprint.toLowerCase();\n const entry = this.#thumbs.issuers.certs.get(normalized);\n if (!entry) {\n return null;\n }\n try {\n await fs.promises.unlink(entry.filename);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n this.#thumbs.issuers.certs.delete(normalized);\n return entry.certificate;\n }\n\n /**\n * Remove all CRL files that were issued by the given CA certificate\n * from the specified folder (or both).\n * @param issuerCertificate - the CA certificate whose CRLs to remove\n * @param target - \"issuers\", \"trusted\", or \"all\" (default \"all\")\n */\n public async removeRevocationListsForIssuer(\n issuerCertificate: Certificate,\n target: \"issuers\" | \"trusted\" | \"all\" = \"all\"\n ): Promise<void> {\n const issuerInfo = exploreCertificate(issuerCertificate);\n const issuerFingerprint = issuerInfo.tbsCertificate.subjectFingerPrint;\n\n const processIndex = async (index: Map<string, CRLData>) => {\n const crlData = index.get(issuerFingerprint);\n if (!crlData) return;\n for (const crlEntry of crlData.crls) {\n try {\n await fs.promises.unlink(crlEntry.filename);\n } catch (err: unknown) {\n if ((err as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw err;\n }\n }\n }\n index.delete(issuerFingerprint);\n };\n\n if (target === \"issuers\" || target === \"all\") {\n await processIndex(this.#thumbs.issuersCrl);\n }\n if (target === \"trusted\" || target === \"all\") {\n await processIndex(this.#thumbs.crl);\n }\n }\n\n /**\n * Validate a certificate (optionally with its chain) and add\n * the leaf certificate to the trusted store.\n *\n * Performs OPC UA Part 4, Table 100 validation:\n *\n * 1. **Certificate Structure** — parse the DER encoding.\n * 2. **Build Certificate Chain** — walk from the leaf to a\n * self-signed root CA, using the provided chain and the\n * issuers store.\n * 3. **Signature** — verify each certificate's signature\n * against its issuer.\n * 4. **Issuer Presence** — every issuer in the chain must\n * already be registered in the issuers store (per GDS\n * 7.8.2.6).\n * 5. **Validity Period** — each certificate must be within\n * its validity window (overridable via\n * {@link AddCertificateValidationOptions.acceptExpiredCertificate}).\n * 6. **Revocation Check** — each certificate is checked\n * against its issuer's CRL (overridable via\n * {@link AddCertificateValidationOptions.acceptRevokedCertificate}\n * and {@link AddCertificateValidationOptions.ignoreMissingRevocationList}).\n *\n * Only the leaf certificate is added to the trusted store.\n *\n * @param certificateChain - DER-encoded certificate or chain\n * @returns `VerificationStatus.Good` on success, or an error\n * status indicating why the certificate was rejected.\n */\n public async addTrustedCertificateFromChain(certificateChain: Certificate | Certificate[]): Promise<VerificationStatus> {\n // Top-level guard: never let an unexpected error escape.\n // Every code path returns a VerificationStatus; unexpected\n // throws (corrupt buffers, crypto failures, etc.) are\n // caught here and mapped to BadCertificateInvalid.\n try {\n return await this.#addTrustedCertificateFromChainImpl(certificateChain);\n } catch (_err) {\n warningLog(\"addTrustedCertificateFromChain: unexpected error\", _err);\n return VerificationStatus.BadCertificateInvalid;\n }\n }\n\n async #addTrustedCertificateFromChainImpl(certificateChain: Certificate | Certificate[]): Promise<VerificationStatus> {\n let certificates: Certificate[];\n try {\n certificates = coerceCertificateChain(certificateChain);\n } catch (_err) {\n return VerificationStatus.BadCertificateInvalid;\n }\n if (certificates.length === 0) {\n return VerificationStatus.BadCertificateInvalid;\n }\n const leafCertificate = certificates[0];\n const opts = this.#addCertValidation;\n\n // ── Step 1: Certificate Structure ────────────────────────\n let leafInfo: CertificateInternals;\n try {\n leafInfo = exploreCertificate(leafCertificate);\n } catch (_err) {\n return VerificationStatus.BadCertificateInvalid;\n }\n\n // Re-scan the issuers folder to pick up certificates\n // added directly to disk (e.g. by GDS push or external\n // tooling) that the file-system watcher may not have\n // delivered yet.\n await this.#scanCertFolder(this.issuersCertFolder, this.#thumbs.issuers.certs);\n\n // ── Step 2–6: Walk the chain from leaf to root ───────────\n // depth counts the number of certificates validated in the\n // chain. maxChainLength=1 → only self-signed certs;\n // maxChainLength=2 → leaf + root CA; etc.\n let currentCert = leafCertificate;\n let currentInfo = leafInfo;\n let depth = 0;\n\n while (true) {\n depth++;\n if (depth > opts.maxChainLength) {\n // Chain depth exceeded before reaching root\n return VerificationStatus.BadSecurityChecksFailed;\n }\n\n // ── Step 5: Validity Period ──────────────────────────\n if (!opts.acceptExpiredCertificate) {\n // currentInfo is kept in lockstep with currentCert, so the\n // dates are already parsed. Re-reading them through\n // exploreCertificateInfo cost a second parse and rejected any\n // EC certificate outright, since that helper also insists on\n // an RSA-sized public key.\n const { validity } = currentInfo.tbsCertificate;\n const now = new Date();\n if (validity.notBefore.getTime() > now.getTime()) {\n return VerificationStatus.BadCertificateTimeInvalid;\n }\n if (validity.notAfter.getTime() <= now.getTime()) {\n return depth === 1\n ? VerificationStatus.BadCertificateTimeInvalid\n : VerificationStatus.BadCertificateIssuerTimeInvalid;\n }\n }\n\n // ── Self-signed certificate ──────────────────────────\n if (isSelfSigned2(currentInfo)) {\n // Step 3: Verify self-signature\n try {\n if (!verifyCertificateSignature(currentCert, currentCert)) {\n return VerificationStatus.BadCertificateInvalid;\n }\n } catch (_err) {\n return VerificationStatus.BadCertificateInvalid;\n }\n // Self-signed certificates don't need revocation\n // or issuer checks — we're at the root.\n break;\n }\n\n // ── Step 2: Find issuer ──────────────────────────────\n // First try findIssuerCertificate (checks issuers store\n // and trusted store), then fall back to the chain.\n let issuerCert = await this.findIssuerCertificate(currentCert);\n if (!issuerCert) {\n // The issuer is not in the issuers store — try\n // the explicitly provided chain.\n issuerCert = findIssuerCertificateInChain(currentCert, certificates);\n if (!issuerCert || issuerCert === currentCert) {\n return VerificationStatus.BadCertificateChainIncomplete;\n }\n }\n\n // ── Step 3: Signature verification ───────────────────\n try {\n if (!verifyCertificateSignature(currentCert, issuerCert)) {\n return VerificationStatus.BadCertificateInvalid;\n }\n } catch (_err) {\n return VerificationStatus.BadCertificateInvalid;\n }\n\n // ── Step 4: Issuer must be in the issuers store ──────\n // Per GDS 7.8.2.6: \"This Method will return a\n // validation error if the Certificate is issued by a CA\n // and the Certificate for the issuer is not in the\n // TrustList\"\n const issuerThumbprint = makeFingerprint(issuerCert);\n if (!(await this.hasIssuer(issuerThumbprint))) {\n return VerificationStatus.BadCertificateChainIncomplete;\n }\n\n // ── Step 6: Revocation check ─────────────────────────\n const revokedStatus = await this.isCertificateRevoked(currentCert, issuerCert);\n if (revokedStatus === VerificationStatus.BadCertificateRevoked) {\n if (!opts.acceptRevokedCertificate) {\n return VerificationStatus.BadCertificateRevoked;\n }\n } else if (revokedStatus === VerificationStatus.BadCertificateRevocationUnknown) {\n if (!opts.ignoreMissingRevocationList) {\n return VerificationStatus.BadCertificateRevocationUnknown;\n }\n }\n\n // Move up the chain\n currentCert = issuerCert;\n try {\n currentInfo = exploreCertificate(currentCert);\n } catch (_err) {\n return VerificationStatus.BadCertificateInvalid;\n }\n }\n\n // All checks passed — trust the leaf certificate.\n // Pass the full chain so the PEM on disk preserves\n // intermediate CA certificates (chain-on-disk,\n // leaf-only-in-memory principle).\n await this.trustCertificate(certificates);\n return VerificationStatus.Good;\n }\n\n /**\n * Check whether an issuer certificate is still needed by any\n * certificate in the trusted store.\n *\n * This is used before removing an issuer to ensure that\n * doing so would not break the chain of any trusted\n * certificate.\n *\n * @param issuerCertificate - the CA certificate to check\n * @returns `true` if at least one trusted certificate was\n * signed by this issuer.\n */\n public async isIssuerInUseByTrustedCertificate(issuerCertificate: Certificate): Promise<boolean> {\n await this.#readCertificates();\n for (const entry of this.#thumbs.trusted.values()) {\n if (!entry.certificate) continue;\n try {\n if (verifyCertificateSignature(entry.certificate, issuerCertificate)) {\n return true;\n }\n } catch (_err) {\n // Skip certificates that can't be verified\n }\n }\n return false;\n }\n\n /**\n * find the issuer certificate among the trusted issuer certificates.\n *\n * The findIssuerCertificate method is an asynchronous method that attempts to find\n * the issuer certificate for a given certificate from the list of issuer certificate declared in the PKI\n *\n * - If the certificate is self-signed, it returns the certificate itself.\n *\n * - If the certificate has no extension 3, it is assumed to be generated by an old system, and a null value is returned.\n *\n * - the method checks both issuer and trusted certificates and returns the appropriate issuercertificate,\n * if found. If multiple matching certificates are found, a warning is logged to the console.\n *\n */\n public async findIssuerCertificate(certificate: Certificate | Certificate[]): Promise<Certificate | null> {\n const firstCertificate = coerceCertificateChain(certificate)[0];\n const certInfo = exploreCertificate(firstCertificate);\n\n if (isSelfSigned2(certInfo)) {\n // the certificate is self signed so is it's own issuer.\n return firstCertificate;\n }\n\n const wantedIssuerKey = certInfo.tbsCertificate.extensions?.authorityKeyIdentifier?.keyIdentifier;\n\n if (!wantedIssuerKey) {\n // Certificate has no extension 3 ! the certificate might have been generated by an old system\n debugLog(\"Certificate has no extension 3\");\n return null;\n }\n\n const issuerCertificates = [...this.#thumbs.issuers.certs.values()];\n\n const selectedIssuerCertificates = findMatchingIssuerKey(issuerCertificates, wantedIssuerKey);\n\n if (selectedIssuerCertificates.length > 0) {\n if (selectedIssuerCertificates.length > 1) {\n warningLog(\"Warning more than one issuer certificate exists with subjectKeyIdentifier \", wantedIssuerKey);\n }\n return selectedIssuerCertificates[0].certificate || null;\n }\n // check also in trusted list\n const trustedCertificates = [...this.#thumbs.trusted.values()];\n const selectedTrustedCertificates = findMatchingIssuerKey(trustedCertificates, wantedIssuerKey);\n\n if (selectedTrustedCertificates.length > 1) {\n warningLog(\n \"Warning more than one certificate exists with subjectKeyIdentifier in trusted certificate list \",\n wantedIssuerKey,\n selectedTrustedCertificates.length\n );\n }\n return selectedTrustedCertificates.length > 0 ? selectedTrustedCertificates[0].certificate : null;\n }\n\n /**\n * Outcome status for {@link CertificateManager.completeCertificateChain}.\n */\n public static readonly ChainCompletionStatus = ChainCompletionStatus;\n\n /**\n * Complete a certificate chain by walking the issuer store.\n *\n * Starting from the last certificate in the provided chain, this method\n * repeatedly calls {@link findIssuerCertificate} to locate the parent\n * certificate until it reaches a self-signed root or can no longer find\n * an issuer.\n *\n * @param chain - the (potentially partial) certificate chain, leaf first\n * @param maxDepth - maximum number of issuers to append (default: 10)\n * @returns a {@link ChainCompletionResult} containing the (possibly completed)\n * chain, a status code, and an optional diagnostic message.\n */\n public async completeCertificateChain(chain: Certificate[], maxDepth = 10): Promise<ChainCompletionResult> {\n if (chain.length === 0) {\n return {\n chain,\n status: ChainCompletionStatus.EmptyChain,\n message: \"Input chain is empty — nothing to complete.\"\n };\n }\n\n // Re-scan the issuers folder to ensure we have the latest\n await this.#scanCertFolder(this.issuersCertFolder, this.#thumbs.issuers.certs);\n\n const result = [...chain];\n let depth = 0;\n\n while (depth < maxDepth) {\n const lastCert = result[result.length - 1];\n const lastInfo = exploreCertificate(lastCert);\n\n // Stop if the last certificate is self-signed (root)\n if (isSelfSigned2(lastInfo)) {\n const wasExtended = result.length > chain.length;\n return {\n chain: result,\n status: wasExtended ? ChainCompletionStatus.ChainCompleted : ChainCompletionStatus.AlreadyComplete,\n message: wasExtended\n ? `Chain completed: ${result.length - chain.length} issuer(s) appended, ending at self-signed root \"${lastInfo.tbsCertificate.subject.commonName}\".`\n : `Chain is already complete (self-signed root \"${lastInfo.tbsCertificate.subject.commonName}\").`\n };\n }\n\n const issuerCert = await this.findIssuerCertificate(lastCert);\n if (!issuerCert) {\n // Cannot find the issuer — chain remains partial\n const cn = lastInfo.tbsCertificate.subject.commonName ?? \"?\";\n const akid = lastInfo.tbsCertificate.extensions?.authorityKeyIdentifier?.keyIdentifier ?? \"?\";\n const msg =\n `Cannot find issuer for \"${cn}\" ` +\n `(authorityKeyIdentifier: ${akid}). ` +\n `Ensure the CA certificate is present in the issuers/certs folder.`;\n warningLog(`completeCertificateChain: ${msg}`);\n return {\n chain: result,\n status: ChainCompletionStatus.IssuerNotFound,\n message: msg\n };\n }\n\n // Avoid loops: don't add the certificate if it's already in the chain\n const issuerFingerprint = makeFingerprint(issuerCert);\n const alreadyInChain = result.some((c) => makeFingerprint(c) === issuerFingerprint);\n if (alreadyInChain) {\n return {\n chain: result,\n status: ChainCompletionStatus.AlreadyComplete,\n message: `Chain ends at root \"${exploreCertificate(issuerCert).tbsCertificate.subject.commonName}\" (already present in chain).`\n };\n }\n\n result.push(issuerCert);\n depth++;\n }\n\n // maxDepth exceeded\n return {\n chain: result,\n status: ChainCompletionStatus.MaxDepthReached,\n message: `Chain completion stopped after ${maxDepth} iterations — possible circular chain or very deep hierarchy.`\n };\n }\n\n /**\n *\n * check if the certificate explicitly appear in the trust list, the reject list or none.\n * In case of being in the reject and trusted list at the same time is consider: rejected.\n * @internal\n * @private\n */\n async #checkRejectedOrTrusted(certificate: Certificate | Certificate[]): Promise<CertificateStatus> {\n const firstCertificate = coerceCertificateChain(certificate)[0];\n const fingerprint = makeFingerprint(firstCertificate);\n\n debugLog(\"#checkRejectedOrTrusted fingerprint \", short(fingerprint));\n\n await this.#readCertificates();\n\n if (this.#thumbs.rejected.has(fingerprint)) {\n return \"rejected\";\n }\n if (this.#thumbs.trusted.has(fingerprint)) {\n return \"trusted\";\n }\n return \"unknown\";\n }\n\n async #moveCertificate(certificateOrChain: Certificate | Certificate[], newStatus: CertificateStatus) {\n await this.withLock2(async () => {\n const chain = coerceCertificateChain(certificateOrChain);\n const certificate = chain[0]; // leaf — used for indexing\n const fingerprint = makeFingerprint(certificate);\n\n let status = await this.#checkRejectedOrTrusted(certificate);\n if (status === \"unknown\") {\n // # unknown means rejected — write full chain to disk\n const pem = toPem(chain, \"CERTIFICATE\");\n const filename = path.join(this.rejectedFolder, `${buildIdealCertificateName(certificate)}.pem`);\n await fs.promises.writeFile(filename, pem);\n this.#thumbs.rejected.set(fingerprint, { certificate, filename });\n status = \"rejected\";\n }\n\n debugLog(\"#moveCertificate\", fingerprint.substring(0, 10), \"from\", status, \"to\", newStatus);\n\n if (status !== \"rejected\" && status !== \"trusted\") {\n throw new Error(`#moveCertificate: unexpected status '${status}' for certificate ${fingerprint.substring(0, 10)}`);\n }\n\n if (status !== newStatus) {\n const indexSrc = status === \"rejected\" ? this.#thumbs.rejected : this.#thumbs.trusted;\n const srcEntry = indexSrc.get(fingerprint);\n\n if (!srcEntry) {\n debugLog(\" cannot find certificate \", fingerprint.substring(0, 10), \" in\", status);\n throw new Error(`#moveCertificate: certificate ${fingerprint.substring(0, 10)} not found in ${status} index`);\n }\n const destFolder = newStatus === \"trusted\" ? this.trustedFolder : this.rejectedFolder;\n const certificateDest = path.join(destFolder, path.basename(srcEntry.filename));\n\n debugLog(\"#moveCertificate\", fingerprint.substring(0, 10), \"old name\", srcEntry.filename);\n debugLog(\"#moveCertificate\", fingerprint.substring(0, 10), \"new name\", certificateDest);\n await fs.promises.rename(srcEntry.filename, certificateDest);\n indexSrc.delete(fingerprint);\n const indexDest = newStatus === \"trusted\" ? this.#thumbs.trusted : this.#thumbs.rejected;\n indexDest.set(fingerprint, { certificate, filename: certificateDest });\n }\n });\n }\n #findAssociatedCRLs(issuerCertificate: Certificate): CRLData | null {\n const issuerCertificateInfo = exploreCertificate(issuerCertificate);\n const key = issuerCertificateInfo.tbsCertificate.subjectFingerPrint;\n return this.#thumbs.issuersCrl.get(key) ?? this.#thumbs.crl.get(key) ?? null;\n }\n\n /**\n * Check whether a certificate has been revoked by its issuer's CRL.\n *\n * - Self-signed certificates are never considered revoked.\n * - If no `issuerCertificate` is provided, the method attempts\n * to find it via {@link findIssuerCertificate}.\n *\n * @param certificate - the DER-encoded certificate to check\n * @param issuerCertificate - optional issuer certificate; looked\n * up automatically when omitted\n * @returns `Good` if not revoked, `BadCertificateRevoked` if the\n * serial number appears in a CRL,\n * `BadCertificateRevocationUnknown` if no CRL is available,\n * or `BadCertificateChainIncomplete` if the issuer cannot be\n * found.\n */\n public async isCertificateRevoked(\n certificate: Certificate | Certificate[],\n issuerCertificate?: Certificate | null\n ): Promise<VerificationStatus> {\n const chain = coerceCertificateChain(certificate);\n const firstCertificate = chain[0];\n if (isSelfSigned3(firstCertificate)) {\n return VerificationStatus.Good;\n }\n\n if (!issuerCertificate) {\n issuerCertificate = await this.findIssuerCertificate(firstCertificate);\n }\n if (!issuerCertificate) {\n issuerCertificate = findIssuerCertificateInChain(firstCertificate, chain);\n }\n if (!issuerCertificate) {\n return VerificationStatus.BadCertificateChainIncomplete;\n }\n const crls = this.#findAssociatedCRLs(issuerCertificate);\n\n if (!crls) {\n return VerificationStatus.BadCertificateRevocationUnknown;\n }\n const certInfo = exploreCertificate(firstCertificate);\n const serialNumber =\n certInfo.tbsCertificate.serialNumber || certInfo.tbsCertificate.extensions?.authorityKeyIdentifier?.serial || \"\";\n\n const key = certInfo.tbsCertificate.extensions?.authorityKeyIdentifier?.authorityCertIssuerFingerPrint || \"<unknown>\";\n const crl2 = this.#thumbs.crl.get(key) ?? null;\n\n if (crls.serialNumbers[serialNumber] || crl2?.serialNumbers[serialNumber]) {\n return VerificationStatus.BadCertificateRevoked;\n }\n return VerificationStatus.Good;\n }\n\n #pendingCrlToProcess = 0;\n #onCrlProcessWaiters: (() => void)[] = [];\n #queue: { index: Map<string, CRLData>; filename: string }[] = [];\n #onCrlFileAdded(index: Map<string, CRLData>, filename: string) {\n this.#queue.push({ index, filename });\n this.#pendingCrlToProcess += 1;\n if (this.#pendingCrlToProcess === 1) {\n this.#processNextCrl();\n }\n }\n async #processNextCrl() {\n try {\n const nextCRL = this.#queue.shift();\n if (!nextCRL) return;\n const { index, filename } = nextCRL;\n const crl = await readCertificateRevocationList(filename);\n const crlInfo = exploreCertificateRevocationList(crl);\n debugLog(chalk.cyan(\"add CRL in folder \"), filename);\n const fingerprint = crlInfo.tbsCertList.issuerFingerprint;\n if (!index.has(fingerprint)) {\n index.set(fingerprint, { crls: [], serialNumbers: {} });\n }\n const data = index.get(fingerprint) || { crls: [], serialNumbers: {} };\n data.crls.push({ crlInfo, filename });\n\n // now inject serial numbers\n for (const revokedCertificate of crlInfo.tbsCertList.revokedCertificates) {\n const serialNumber = revokedCertificate.userCertificate;\n if (!data.serialNumbers[serialNumber]) {\n data.serialNumbers[serialNumber] = revokedCertificate.revocationDate;\n }\n }\n debugLog(chalk.cyan(\"CRL\"), fingerprint, \"serial numbers = \", Object.keys(data.serialNumbers));\n } catch (err) {\n debugLog(\"CRL filename error =\");\n debugLog(err);\n }\n this.#pendingCrlToProcess -= 1;\n if (this.#pendingCrlToProcess === 0) {\n for (const waiter of this.#onCrlProcessWaiters) {\n waiter();\n }\n this.#onCrlProcessWaiters.length = 0;\n } else {\n this.#processNextCrl();\n }\n }\n async #readCertificates(): Promise<void> {\n if (this.#readCertificatesCalled) {\n return;\n }\n this.#readCertificatesCalled = true;\n\n // Chokidar configuration choices:\n //\n // usePolling: false (default)\n // Use native OS file-system events (inotify on Linux,\n // FSEvents on macOS, ReadDirectoryChangesW on Windows)\n // for near-real-time detection of cert/CRL additions\n // and removals. This is significantly faster than\n // polling (milliseconds vs seconds).\n //\n // Set OPCUA_PKI_USE_POLLING=true to revert to polling\n // for environments where native events are unreliable\n // (NFS, CIFS, Docker volumes, or other remote/virtual\n // file systems).\n //\n // persistent: false\n // Watchers do NOT keep the Node.js event loop alive.\n // This prevents the process from hanging if the\n // CertificateManager is not properly disposed. The\n // trade-off is that watchers stop receiving events if\n // there are no other active handles — acceptable since\n // CertificateManager always runs alongside a server.\n //\n // awaitWriteFinish: not set\n // Certificate and CRL files are small (typically < 5 KB)\n // and written atomically (fs.writeFile). No need to\n // wait for write stabilization, which would add a 2s+\n // delay before the in-memory index is updated.\n //\n const usePolling = process.env.OPCUA_PKI_USE_POLLING === \"true\";\n const envInterval = process.env.OPCUA_PKI_POLLING_INTERVAL\n ? parseInt(process.env.OPCUA_PKI_POLLING_INTERVAL, 10)\n : undefined;\n const pollingInterval = Math.min(10 * 60 * 1000, Math.max(100, envInterval ?? this.folderPollingInterval));\n // depth: 0\n // PKI store folders are flat — certificates and CRLs sit\n // directly in them. Without an explicit depth chokidar\n // recurses without bound (handler.js: `oDepth == null`)\n // and descends into any subdirectory that appears, which\n // routes through NodeFsHandler._handleRead ->\n // FSWatcher._throttle. That schedules *ref'd* 1s timers;\n // a directory churning under the watcher can spin\n // thousands of them and keep the event loop alive\n // indefinitely, so an undisposed CertificateManager stops\n // the process from exiting. Note this is a timer problem,\n // not a handle problem: the fs.watch handles themselves\n // come back correctly unref'd. Flat watching keeps\n // _handleRead off subdirectories entirely.\n //\n const chokidarOptions = {\n usePolling,\n ...(usePolling ? { interval: pollingInterval } : {}),\n depth: 0,\n persistent: false\n };\n\n // Workaround for two problems with persistent:false:\n //\n // 1. Chokidar does forward persistent:false into fs.watch\n // (handler.js, createFsWatchInstance) and on current\n // Node the resulting handles do come back unref'd —\n // but that was not enough in practice on Windows when\n // 0fbe111 was written, where undisposed instances\n // pinned the loop open. The explicit .unref() is kept\n // as the guarantee rather than trusting the platform.\n //\n // 2. Chokidar does not register an 'error' handler on\n // fs.watch when persistent:false (handler.js l.160-168).\n // On Windows + Node < 22, the native handle fires EPERM\n // when the watched directory is removed, which becomes\n // an uncaught exception that crashes the process.\n //\n // We install a single shared fs.watch() interception BEFORE\n // creating all 5 watchers. Every captured handle gets both\n // an error handler (fix #2) and is later .unref()'d (fix #1).\n //\n // The interception stays active until ALL watchers have\n // emitted \"ready\" — chokidar creates fs.watch handles\n // asynchronously during directory scanning, so we must keep\n // the interception alive until that completes.\n const allCapturedHandles: fs.FSWatcher[] = [];\n const origWatch = fs.watch;\n let watcherReadyCount = 0;\n const totalWatchers = 5;\n\n fs.watch = ((...args: Parameters<typeof fs.watch>) => {\n const handle = origWatch.apply(fs, args);\n handle.setMaxListeners(handle.getMaxListeners() + 1);\n handle.on(\"error\", () => {\n /* swallow – watched directory was removed */\n });\n allCapturedHandles.push(handle);\n return handle;\n }) as typeof fs.watch;\n\n const createUnreffedWatcher = (folder: string) => {\n const startIdx = allCapturedHandles.length;\n const w = chokidar.watch(folder, chokidarOptions);\n const unreffAll = () => {\n // Unref only handles created for THIS watcher\n for (let i = startIdx; i < allCapturedHandles.length; i++) {\n allCapturedHandles[i].unref();\n }\n // Restore fs.watch once ALL watchers are ready\n watcherReadyCount++;\n if (watcherReadyCount >= totalWatchers) {\n fs.watch = origWatch;\n }\n };\n return { w, capturedHandles: allCapturedHandles.slice(startIdx), unreffAll };\n };\n\n // ── Phase 1: Async scan ─────────────────────────────────\n // Populate the in-memory indexes by reading existing\n // files. Uses async readdir/stat to yield the event loop\n // between files. All 5 folders are scanned in parallel.\n await Promise.all([\n this.#scanCertFolder(this.trustedFolder, this.#thumbs.trusted),\n this.#scanCertFolder(this.issuersCertFolder, this.#thumbs.issuers.certs),\n this.#scanCertFolder(this.rejectedFolder, this.#thumbs.rejected),\n this.#scanCrlFolder(this.crlFolder, this.#thumbs.crl),\n this.#scanCrlFolder(this.issuersCrlFolder, this.#thumbs.issuersCrl)\n ]);\n\n // ── Phase 2: Deferred file watchers ─────────────────────\n // Start chokidar watchers in the background. We do NOT\n // await \"ready\" so initialize() returns immediately after\n // the sync scan. Chokidar will re-discover existing files\n // (harmless Map overwrites) then watch for live changes.\n //\n // When disableFileWatchers is set, skip the watcher setup\n // entirely. The in-memory indexes are already populated\n // from the scan above. Also restore fs.watch immediately\n // since no watchers will be created.\n if (this.#disableFileWatchers) {\n fs.watch = origWatch;\n } else {\n this.#startWatcher(this.trustedFolder, this.#thumbs.trusted, createUnreffedWatcher, \"trusted\");\n this.#startWatcher(this.issuersCertFolder, this.#thumbs.issuers.certs, createUnreffedWatcher, \"issuersCerts\");\n this.#startWatcher(this.rejectedFolder, this.#thumbs.rejected, createUnreffedWatcher, \"rejected\");\n this.#startCrlWatcher(this.crlFolder, this.#thumbs.crl, createUnreffedWatcher, \"crl\");\n this.#startCrlWatcher(this.issuersCrlFolder, this.#thumbs.issuersCrl, createUnreffedWatcher, \"issuersCrl\");\n }\n }\n\n /**\n * Scan a certificate folder and populate the in-memory index.\n * Uses async readdir/stat to yield the event loop between\n * file reads, preventing main-loop stalls with large folders.\n */\n async #scanCertFolder(folder: string, index: Map<string, Entry>): Promise<void> {\n if (!fs.existsSync(folder)) return;\n const files = await fs.promises.readdir(folder);\n for (const file of files) {\n const filename = path.join(folder, file);\n try {\n const stat = await fs.promises.stat(filename);\n if (!stat.isFile()) continue;\n const certs = await readCertificateChainAsync(filename);\n if (certs.length === 0) continue;\n const certificate = certs[0];\n\n // Legacy migration: if the file contained multiple\n // certs (e.g. from old buggy toPem that wrapped a\n // concatenated DER in a single PEM block), re-write\n // with proper multi-block PEM and auto-register any\n // intermediate CA certs in the issuers store.\n // Best-effort: if the filesystem is read-only the\n // migration is skipped — the leaf is still indexed.\n if (certs.length > 1) {\n try {\n await fs.promises.writeFile(filename, toPem(certs, \"CERTIFICATE\"), \"ascii\");\n } catch (writeErr) {\n debugLog(`scanCertFolder: could not rewrite legacy PEM ${filename} (read-only fs?)`, writeErr);\n }\n for (let i = 1; i < certs.length; i++) {\n if (isIssuer(certs[i])) {\n try {\n await this.addIssuer(certs[i]);\n } catch (issuerErr) {\n debugLog(`scanCertFolder: could not auto-register issuer from ${filename}`, issuerErr);\n }\n }\n }\n }\n\n const info = exploreCertificate(certificate);\n const fingerprint = makeFingerprint(certificate);\n index.set(fingerprint, { certificate, filename, info });\n this.#filenameToHash.set(filename, fingerprint);\n } catch (err) {\n debugLog(`scanCertFolder: skipping ${filename}`, err);\n }\n }\n }\n\n /**\n * Scan a CRL folder and populate the in-memory CRL index.\n */\n async #scanCrlFolder(folder: string, index: Map<string, CRLData>): Promise<void> {\n if (!fs.existsSync(folder)) return;\n const files = await fs.promises.readdir(folder);\n for (const file of files) {\n const filename = path.join(folder, file);\n try {\n const stat = await fs.promises.stat(filename);\n if (!stat.isFile()) continue;\n this.#onCrlFileAdded(index, filename);\n } catch (err) {\n debugLog(`scanCrlFolder: skipping ${filename}`, err);\n }\n }\n await this.#waitAndCheckCRLProcessingStatus();\n }\n\n /**\n * Start a chokidar watcher for a CRL folder.\n * Non-blocking — does NOT await \"ready\".\n */\n #startCrlWatcher(\n folder: string,\n index: Map<string, CRLData>,\n createUnreffedWatcher: (folder: string) => { w: ChokidarFSWatcher; unreffAll: () => void },\n store: CrlStore\n ): void {\n const { w, unreffAll } = createUnreffedWatcher(folder);\n w.on(\"error\", (err: unknown) => {\n debugLog(`chokidar CRL watcher error on ${folder}:`, err);\n });\n let ready = false;\n\n w.on(\"unlink\", (filename: string) => {\n for (const [key, data] of index.entries()) {\n data.crls = data.crls.filter((c) => c.filename !== filename);\n if (data.crls.length === 0) {\n index.delete(key);\n }\n }\n if (ready) {\n this.emit(\"crlRemoved\", { store, filename });\n }\n });\n w.on(\"add\", (filename: string) => {\n if (ready) {\n this.#onCrlFileAdded(index, filename);\n this.emit(\"crlAdded\", { store, filename });\n }\n });\n w.on(\"change\", (changedPath: string) => {\n debugLog(\"change in folder \", folder, changedPath);\n });\n this.#watchers.push(w as unknown as fs.FSWatcher);\n this.#pendingUnrefs.add(unreffAll);\n w.on(\"ready\", () => {\n ready = true;\n this.#pendingUnrefs.delete(unreffAll);\n unreffAll();\n });\n }\n\n /**\n * Start a chokidar watcher for a certificate folder.\n * Non-blocking — does NOT await \"ready\".\n */\n #startWatcher(\n folder: string,\n index: Map<string, Entry>,\n createUnreffedWatcher: (folder: string) => { w: ChokidarFSWatcher; unreffAll: () => void },\n store: CertificateStore\n ): void {\n const { w, unreffAll } = createUnreffedWatcher(folder);\n w.on(\"error\", (err: unknown) => {\n debugLog(`chokidar cert watcher error on ${folder}:`, err);\n });\n let ready = false;\n w.on(\"unlink\", (filename: string) => {\n debugLog(chalk.cyan(`unlink in folder ${folder}`), filename);\n const h = this.#filenameToHash.get(filename);\n if (h && index.has(h)) {\n index.delete(h);\n this.emit(\"certificateRemoved\", { store, fingerprint: h, filename });\n }\n });\n w.on(\"add\", (filename: string) => {\n debugLog(chalk.cyan(`add in folder ${folder}`), filename);\n try {\n const certificate = readCertificateChain(filename)[0];\n const info = exploreCertificate(certificate);\n const fingerprint = makeFingerprint(certificate);\n\n const isNew = !index.has(fingerprint);\n index.set(fingerprint, { certificate, filename, info });\n this.#filenameToHash.set(filename, fingerprint);\n\n debugLog(\n chalk.magenta(\"CERT\"),\n info.tbsCertificate.subjectFingerPrint,\n info.tbsCertificate.serialNumber,\n info.tbsCertificate.extensions?.authorityKeyIdentifier?.authorityCertIssuerFingerPrint\n );\n if (ready || isNew) {\n this.emit(\"certificateAdded\", { store, certificate, fingerprint, filename });\n }\n } catch (err) {\n debugLog(`Walk files in folder ${folder} with file ${filename}`);\n debugLog(err);\n }\n });\n w.on(\"change\", (changedPath: string) => {\n debugLog(chalk.cyan(`change in folder ${folder}`), changedPath);\n try {\n const certificate = readCertificateChain(changedPath)[0];\n const newFingerprint = makeFingerprint(certificate);\n const oldHash = this.#filenameToHash.get(changedPath);\n if (oldHash && oldHash !== newFingerprint) {\n index.delete(oldHash);\n }\n index.set(newFingerprint, { certificate, filename: changedPath, info: exploreCertificate(certificate) });\n this.#filenameToHash.set(changedPath, newFingerprint);\n this.emit(\"certificateChange\", { store, certificate, fingerprint: newFingerprint, filename: changedPath });\n } catch (err) {\n debugLog(`change event: failed to re-read ${changedPath}`, err);\n }\n });\n this.#watchers.push(w as unknown as fs.FSWatcher);\n this.#pendingUnrefs.add(unreffAll);\n w.on(\"ready\", () => {\n ready = true;\n this.#pendingUnrefs.delete(unreffAll);\n unreffAll();\n debugLog(\"ready\");\n debugLog([...index.keys()].map((k) => k.substring(0, 10)));\n });\n }\n\n // make sure that all crls have been processed.\n async #waitAndCheckCRLProcessingStatus(): Promise<void> {\n return new Promise((resolve, _reject) => {\n if (this.#pendingCrlToProcess === 0) {\n setImmediate(resolve);\n return;\n }\n this.#onCrlProcessWaiters.push(resolve);\n });\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nexport * from \"./common\";\nexport * from \"./common2\";\nexport * from \"./config\";\nexport * from \"./debug\";\nexport * from \"./display\";\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport type { ProcessAltNamesParam } from \"../common\";\nimport { g_config } from \"../config\";\nimport { warningLog } from \"../debug\";\n\n/**\n * Environment variables passed through to every openssl child process,\n * beyond whatever a specific call explicitly needs (e.g. a passphrase via\n * `ExecuteOptions.env`).\n *\n * This app's own config-templating (ALTNAME, CDP_URL, AIA_VALUE — see\n * `generateStaticConfig`) substitutes values directly into the config file\n * content; it never relies on the openssl child actually seeing those as\n * real OS environment variables. Only `OPENSSL_CONF` and `RANDFILE` are\n * genuinely required at the OS level, alongside whatever the shell, the\n * dynamic loader, and the openssl binary themselves need to start up on\n * each platform.\n *\n * Rather than handing the child the full parent process environment —\n * which, in a hosting application, may hold unrelated secrets (API keys,\n * database credentials, tokens) that have no business being visible to a\n * spawned openssl process — only this curated, minimal set is passed\n * through. The same set is used to *discover* the openssl binary\n * (`install_prerequisite`) and to *run* it, so a binary that is found is\n * also one that can start.\n */\nexport const SAFE_ENV_PASSTHROUGH: ReadonlySet<string> = new Set([\n // POSIX/Windows shell and process essentials\n \"path\",\n \"home\",\n \"userprofile\",\n \"temp\",\n \"tmp\",\n \"tmpdir\",\n \"systemroot\",\n \"windir\",\n \"comspec\",\n \"pathext\",\n \"appdata\",\n \"localappdata\",\n // dynamic loader: a custom-built or relocated openssl (e.g. under /opt,\n // or Homebrew on macOS) may need these to find its own libcrypto/libssl\n \"ld_library_path\",\n \"dyld_library_path\",\n \"dyld_fallback_library_path\",\n // locale, so openssl's textual output stays parseable\n \"lang\",\n \"lc_all\",\n \"lc_ctype\",\n // openssl configuration this app, or the host OS/user, may rely on\n \"openssl_conf\",\n \"randfile\",\n \"openssl_modules\",\n \"openssl_engines\",\n \"ssl_cert_file\",\n \"ssl_cert_dir\"\n]);\n\n/**\n * Build the environment for an openssl child process: the allowlisted\n * subset of `process.env` (see {@link SAFE_ENV_PASSTHROUGH}), overlaid with\n * `extra` (per-invocation values such as a passphrase for `-passin env:`).\n * Never writes to `process.env`.\n */\nexport function buildChildEnv(extra?: NodeJS.ProcessEnv): NodeJS.ProcessEnv {\n const env: NodeJS.ProcessEnv = {};\n for (const key of Object.keys(process.env)) {\n if (SAFE_ENV_PASSTHROUGH.has(key.toLowerCase())) {\n env[key] = process.env[key];\n }\n }\n return { ...env, ...extra };\n}\n\n/**\n * A copy of `options` safe to hand to a logger: the values of any\n * per-invocation `env` are replaced by their variable names, so a passphrase\n * passed for `-passin env:NAME` can never end up in debug output.\n */\nexport function redactEnvForLog<T extends { env?: NodeJS.ProcessEnv }>(options: T): Omit<T, \"env\"> & { env?: string[] } {\n const { env, ...rest } = options;\n return env ? { ...rest, env: Object.keys(env) } : rest;\n}\n\nexport const exportedEnvVars: Record<string, string> = {};\n\nexport function setEnv(varName: string, value: string): void {\n // istanbul ignore next\n if (!g_config.silent) {\n warningLog(` set ${varName}=${value}`);\n }\n exportedEnvVars[varName] = value;\n\n if ([\"OPENSSL_CONF\"].indexOf(varName) >= 0) {\n process.env[varName] = value;\n }\n if ([\"RANDFILE\"].indexOf(varName) >= 0) {\n process.env[varName] = value;\n }\n}\n\nexport function hasEnv(varName: string): boolean {\n return Object.prototype.hasOwnProperty.call(exportedEnvVars, varName);\n}\nexport function getEnv(varName: string): string {\n return exportedEnvVars[varName];\n}\n\nexport function unsetEnv(varName: string): void {\n delete exportedEnvVars[varName];\n}\n\nexport function getEnvironmentVarNames(): { key: string; pattern: string }[] {\n return Object.keys(exportedEnvVars).map((varName: string) => {\n return { key: varName, pattern: `\\\\$ENV\\\\:\\\\:${varName}` };\n });\n}\n\n/**\n * Build the openssl `subjectAltName` value string (`URI:..., DNS:..., IP:...`)\n * from SAN parameters. The single implementation of this format — used both\n * by {@link processAltNames} (which publishes it to the shared env registry)\n * and by callers that pass it as an explicit per-render override — so a\n * format fix cannot land in one copy only.\n */\nexport function buildSubjectAltNameString(params: ProcessAltNamesParam): string {\n return [\n `URI:${params.applicationUri}`,\n ...(params.dns ?? []).map((d: string) => `DNS:${d}`),\n ...(params.ip ?? []).map((d: string) => `IP:${d}`)\n ].join(\", \");\n}\n\nexport function processAltNames(params: ProcessAltNamesParam) {\n params.dns = params.dns || [];\n params.ip = params.ip || [];\n setEnv(\"ALTNAME\", buildSubjectAltNameString(params));\n}\n","export type { SubjectOptions } from \"node-opcua-crypto\";\nexport { Subject } from \"node-opcua-crypto\";\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport child_process from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\n\nimport byline from \"byline\";\nimport chalk from \"chalk\";\nimport yauzl from \"yauzl\";\n\nimport { warningLog } from \"../debug\";\nimport { buildChildEnv } from \"./_env\";\n\nconst doDebug = process.env.NODEOPCUAPKIDEBUG || false;\n\ninterface ExecuteResult {\n exitCode: number;\n output: string;\n}\n\n/**\n * Run `file` with `args` directly (no shell), same as execute_openssl's\n * `execute()`: the same curated environment (a binary discovered with the\n * full parent env but run with a reduced one could otherwise be found here\n * and then fail to load its libraries later), and /dev/null stdin.\n * Resolves with the exit code rather than rejecting on a non-zero exit;\n * rejects only when the process cannot be spawned at all.\n */\nasync function execute(file: string, args: string[], cwd?: string): Promise<ExecuteResult> {\n let output = \"\";\n\n return await new Promise<ExecuteResult>((resolve, reject) => {\n const child = child_process.spawn(file, args, {\n cwd,\n windowsHide: true,\n env: buildChildEnv(),\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n child.on(\"error\", (err: Error) => reject(err));\n child.on(\"close\", (code: number | null) => resolve({ exitCode: code ?? 1, output }));\n\n const stream1 = byline(child.stdout as Readable);\n stream1.on(\"data\", (line: string) => {\n output += `${line}\\n`;\n // istanbul ignore next\n if (doDebug) {\n process.stdout.write(` stdout ${chalk.yellow(line)}\\n`);\n }\n });\n });\n}\n\nfunction is_expected_openssl_version(strVersion: string): boolean {\n return !!strVersion.match(/OpenSSL \\d/);\n}\n\nasync function getopensslExecPath(): Promise<string> {\n let result1: ExecuteResult | undefined;\n try {\n result1 = await execute(\"which\", [\"openssl\"]);\n } catch (err) {\n warningLog(\"warning: \", (err as Error).message);\n throw new Error(\"Cannot find openssl\");\n }\n\n const exitCode = result1?.exitCode;\n const output = result1?.output;\n\n if (exitCode !== 0) {\n warningLog(chalk.yellow(\" it seems that \") + chalk.cyan(\"openssl\") + chalk.yellow(\" is not installed on your computer \"));\n warningLog(chalk.yellow(\"Please install it before running this programs\"));\n throw new Error(\"Cannot find openssl\");\n }\n const opensslExecPath = output.replace(/\\n\\r/g, \"\").trim();\n return opensslExecPath;\n}\nexport async function check_system_openssl_version(): Promise<string> {\n const opensslExecPath = await getopensslExecPath();\n\n // istanbul ignore next\n if (doDebug) {\n warningLog(` OpenSSL found in : ${chalk.yellow(opensslExecPath)}`);\n }\n // ------------------------ now verify that openssl version is the correct one\n const result = await execute(opensslExecPath, [\"version\"]);\n\n const exitCode = result?.exitCode;\n const output = result?.output;\n\n const version = output.trim();\n\n const versionOK = exitCode === 0 && is_expected_openssl_version(version);\n if (!versionOK) {\n let message =\n chalk.whiteBright(\"Warning !!!!!!!!!!!! \") +\n \"\\nyour version of openssl is \" +\n version +\n \". It doesn't match the expected version\";\n\n if (process.platform === \"darwin\") {\n message +=\n chalk.cyan(\"\\nplease refer to :\") +\n chalk.yellow(\" https://github.com/node-opcua/node-opcua/\" + \"wiki/installing-node-opcua-or-node-red-on-MacOS\");\n }\n\n console.log(message);\n }\n return output;\n}\n\nasync function install_and_check_win32_openssl_version(): Promise<string> {\n const downloadFolder = path.join(os.tmpdir(), \".\");\n\n function get_openssl_folder_win32(): string {\n if (process.env.LOCALAPPDATA) {\n const userProgramFolder = path.join(process.env.LOCALAPPDATA, \"Programs\");\n if (fs.existsSync(userProgramFolder)) {\n return path.join(userProgramFolder, \"openssl\");\n }\n }\n return path.join(process.cwd(), \"openssl\");\n }\n\n function get_openssl_exec_path_win32(): string {\n const opensslFolder = get_openssl_folder_win32();\n return path.join(opensslFolder, \"openssl.exe\");\n }\n\n async function check_openssl_win32(): Promise<{ opensslOk?: boolean; version?: string }> {\n const opensslExecPath = get_openssl_exec_path_win32();\n\n const exists = fs.existsSync(opensslExecPath);\n if (!exists) {\n warningLog(\"checking presence of \", opensslExecPath);\n warningLog(chalk.red(\" cannot find file \") + opensslExecPath);\n return {\n opensslOk: false,\n version: `cannot find file ${opensslExecPath}`\n };\n } else {\n const cwd = \".\";\n\n const { exitCode, output } = await execute(opensslExecPath, [\"version\"], cwd);\n const version = output.trim();\n // istanbul ignore next\n\n if (doDebug) {\n warningLog(\" Version = \", version);\n }\n return {\n opensslOk: exitCode === 0 && is_expected_openssl_version(version),\n version\n };\n }\n }\n\n /**\n * Try to find a system-installed openssl on Windows via `where`.\n * Returns the path if found and version is acceptable, otherwise undefined.\n */\n async function find_system_openssl_win32(): Promise<string | undefined> {\n try {\n const result = await execute(\"where\", [\"openssl\"]);\n if (result.exitCode !== 0) {\n return undefined;\n }\n // `where` may return multiple lines; take the first one\n const opensslPath = result.output.split(/\\r?\\n/)[0].trim();\n if (!opensslPath || !fs.existsSync(opensslPath)) {\n return undefined;\n }\n // verify version\n const versionResult = await execute(opensslPath, [\"version\"]);\n const version = versionResult.output.trim();\n if (versionResult.exitCode === 0 && is_expected_openssl_version(version)) {\n warningLog(\n chalk.green(\"Using system OpenSSL: \") + chalk.cyan(version) + chalk.green(\" at \") + chalk.cyan(opensslPath)\n );\n return opensslPath;\n }\n warningLog(chalk.yellow(\"System OpenSSL found but version not accepted: \") + version);\n return undefined;\n } catch (_err) {\n return undefined;\n }\n }\n\n /**\n * detect whether windows OS is a 64 bits or 32 bits\n * http://ss64.com/nt/syntax-64bit.html\n * http://blogs.msdn.com/b/david.wang/archive/2006/03/26/howto-detect-process-bitness.aspx\n * @return {number}\n */\n function win32or64(): 32 | 64 {\n if (process.env.PROCESSOR_ARCHITECTURE === \"x86\" && process.env.PROCESSOR_ARCHITEW6432) {\n return 64;\n }\n\n if (process.env.PROCESSOR_ARCHITECTURE === \"AMD64\") {\n return 64;\n }\n\n // check if we are running node x32 on a x64 arch\n if (process.env.CURRENT_CPU === \"x64\") {\n return 64;\n }\n return 32;\n }\n\n async function download_openssl(): Promise<{ downloadedFile: string }> {\n const url =\n win32or64() === 64\n ? \"https://github.com/node-opcua/node-opcua-pki/releases/download/2.14.2/openssl-1.0.2u-x64_86-win64.zip\"\n : \"https://github.com/node-opcua/node-opcua-pki/releases/download/2.14.2/openssl-1.0.2u-i386-win32.zip\";\n // the zip file\n const outputFilename = path.join(downloadFolder, path.basename(url));\n\n warningLog(`downloading ${chalk.yellow(url)} to ${outputFilename}`);\n\n if (fs.existsSync(outputFilename)) {\n return { downloadedFile: outputFilename };\n }\n\n const response = await fetch(url, { redirect: \"follow\" });\n if (!response.ok || !response.body) {\n throw new Error(`Failed to download OpenSSL from ${url}: ${response.status} ${response.statusText}`);\n }\n\n const contentLength = parseInt(response.headers.get(\"content-length\") || \"0\", 10);\n let downloaded = 0;\n let lastPercent = -1;\n\n const fileStream = fs.createWriteStream(outputFilename);\n\n // Use pipeline for proper backpressure and cleanup\n const body = response.body as unknown as Readable;\n body.on(\"data\", (chunk: Buffer) => {\n downloaded += chunk.length;\n if (contentLength > 0) {\n const percent = Math.floor((downloaded / contentLength) * 100);\n if (percent !== lastPercent && percent % 10 === 0) {\n lastPercent = percent;\n warningLog(` download progress: ${percent}%`);\n }\n }\n });\n\n await pipeline(body, fileStream);\n\n // Verify the downloaded file exists and has content\n const stat = fs.statSync(outputFilename);\n if (stat.size === 0) {\n fs.unlinkSync(outputFilename);\n throw new Error(`Downloaded file is empty: ${outputFilename}`);\n }\n\n warningLog(chalk.green(\"Download complete: \") + `${stat.size} bytes`);\n return { downloadedFile: outputFilename };\n }\n\n async function unzip_openssl(zipFilename: string) {\n const opensslFolder = get_openssl_folder_win32();\n\n const zipFile = await new Promise<yauzl.ZipFile>((resolve, reject) => {\n yauzl.open(zipFilename, { lazyEntries: true }, (err?: Error | null, zipfile?: yauzl.ZipFile) => {\n if (err) {\n reject(err);\n } else {\n if (!zipfile) {\n reject(new Error(\"zipfile is null\"));\n } else {\n resolve(zipfile);\n }\n }\n });\n });\n\n zipFile.readEntry();\n\n await new Promise<void>((resolve, reject) => {\n zipFile.on(\"end\", (err?: Error) => {\n setImmediate(() => {\n // istanbul ignore next\n if (doDebug) {\n warningLog(\"unzip done\");\n }\n if (err) {\n reject(err);\n } else {\n resolve();\n }\n });\n });\n\n zipFile.on(\"entry\", (entry: yauzl.Entry) => {\n zipFile.openReadStream(entry, (err?: Error | null, readStream?: Readable) => {\n if (err) {\n return reject(err);\n }\n\n const file = path.join(opensslFolder, entry.fileName);\n\n // istanbul ignore next\n if (doDebug) {\n warningLog(\" unzipping :\", file);\n }\n\n const writeStream = fs.createWriteStream(file, \"binary\");\n // ensure parent directory exists\n readStream?.pipe(writeStream);\n\n writeStream.on(\"close\", () => {\n zipFile.readEntry();\n });\n });\n });\n });\n }\n\n // 1. Try system-installed OpenSSL first (e.g. on CI runners)\n const systemOpenssl = await find_system_openssl_win32();\n if (systemOpenssl) {\n return systemOpenssl;\n }\n\n // 2. Check bundled OpenSSL at the expected local path\n const opensslFolder = get_openssl_folder_win32();\n const opensslExecPath = get_openssl_exec_path_win32();\n\n if (!fs.existsSync(opensslFolder)) {\n // istanbul ignore next\n if (doDebug) {\n warningLog(\"creating openssl_folder\", opensslFolder);\n }\n fs.mkdirSync(opensslFolder);\n }\n\n const { opensslOk, version: _version } = await check_openssl_win32();\n\n if (!opensslOk) {\n // 3. Download as last resort\n warningLog(chalk.yellow(\"openssl seems to be missing and need to be installed\"));\n const { downloadedFile } = await download_openssl();\n\n // istanbul ignore next\n if (doDebug) {\n warningLog(\"deflating \", chalk.yellow(downloadedFile));\n }\n await unzip_openssl(downloadedFile);\n\n const opensslExists = !!fs.existsSync(opensslExecPath);\n\n // istanbul ignore next\n if (doDebug) {\n warningLog(\"verifying \", opensslExists, opensslExists ? chalk.green(\"OK \") : chalk.red(\" Error\"), opensslExecPath);\n }\n\n const _opensslExecPath2 = await check_openssl_win32();\n return opensslExecPath;\n } else {\n // istanbul ignore next\n if (doDebug) {\n warningLog(chalk.green(\"openssl is already installed and have the expected version.\"));\n }\n return opensslExecPath;\n }\n}\n\n/**\n *\n * return path to the openssl executable\n */\nexport async function install_prerequisite(): Promise<string> {\n // istanbul ignore else\n if (process.platform !== \"win32\") {\n return await check_system_openssl_version();\n } else {\n return await install_and_check_win32_openssl_version();\n }\n}\n\nexport async function get_openssl_exec_path(): Promise<string> {\n if (process.platform === \"win32\") {\n const opensslExecPath = await install_prerequisite();\n if (!fs.existsSync(opensslExecPath)) {\n throw new Error(`internal error cannot find ${opensslExecPath}`);\n }\n return opensslExecPath;\n } else {\n return \"openssl\";\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport assert from \"node:assert\";\nimport child_process from \"node:child_process\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport byline from \"byline\";\nimport chalk from \"chalk\";\nimport { makePath } from \"../common2\";\nimport { g_config } from \"../config\";\nimport { debugLog, displayError, doDebug, warningLog } from \"../debug\";\nimport { buildChildEnv, redactEnvForLog, setEnv } from \"./_env\";\nimport { get_openssl_exec_path } from \"./install_prerequisite\";\n\nlet opensslPath: string | undefined; // not initialized\n\nconst n = makePath;\n\n/**\n * Arguments for one openssl invocation, one array element per argv entry,\n * e.g. `[\"x509\", \"-in\", certificateFile, \"-noout\"]`. Values are handed to\n * the openssl process as-is: no shell is involved, so no quoting or escaping\n * is needed and no value can be interpreted as a shell metacharacter.\n */\nexport type OpensslArgs = readonly string[];\n\nexport interface ExecuteOptions {\n cwd?: string;\n hideErrorMessage?: boolean;\n /**\n * Extra environment variables for this invocation only. Merged with a\n * curated, minimal passthrough of the current process environment (see\n * `SAFE_ENV_PASSTHROUGH` in `_env.ts`) for the spawned child — never the\n * full parent environment, and never written to `process.env`, so\n * concurrent invocations cannot see or clobber each other's values and\n * unrelated secrets sitting in the host application's environment are\n * never handed to the openssl child.\n *\n * Use this together with openssl's `-passin env:NAME` / `-passout\n * env:NAME` syntax to pass a secret without ever placing it in argv: an\n * argv value is visible to other processes via the process list. See\n * {@link passinArg} / {@link passoutArg}.\n */\n env?: NodeJS.ProcessEnv;\n}\n\n// Fixed names for the per-invocation environment variables used to pass\n// passphrases to openssl via `-passin env:NAME` / `-passout env:NAME`\n// instead of placing them in argv (see ExecuteOptions.env for why). Safe to\n// reuse across concurrent calls: each call passes its own `env` object to a\n// distinct child process — nothing here touches process.env, so there is no\n// shared mutable state to race on.\nconst PASSIN_ENV_VAR = \"NODE_OPCUA_PKI_OPENSSL_PASSIN\";\nconst PASSOUT_ENV_VAR = \"NODE_OPCUA_PKI_OPENSSL_PASSOUT\";\n\n/** openssl argv entries plus the env they need; merge `env` into `ExecuteOptions.env`. */\nexport interface OpensslPassArg {\n args: string[];\n env: NodeJS.ProcessEnv;\n}\n\n/**\n * `-passin env:...` for a source passphrase (an input key or PFX bundle).\n *\n * Always emit this — with `\"\"` when there is no passphrase — for any command\n * that reads a private key which *might* be encrypted: without a `-passin`,\n * openssl prompts on the controlling terminal for an encrypted key. An empty\n * `-passin` on a plaintext key is a no-op; on an encrypted key it fails fast\n * with `bad decrypt` instead.\n */\nexport function passinArg(passphrase = \"\"): OpensslPassArg {\n return { args: [\"-passin\", `env:${PASSIN_ENV_VAR}`], env: { [PASSIN_ENV_VAR]: passphrase } };\n}\n\n/** `-passout env:...` for an output passphrase (a PFX bundle being written). */\nexport function passoutArg(passphrase = \"\"): OpensslPassArg {\n return { args: [\"-passout\", `env:${PASSOUT_ENV_VAR}`], env: { [PASSOUT_ENV_VAR]: passphrase } };\n}\n\n/** For logs and error messages only: a shell-like rendering of an argv. Never re-parsed. */\nfunction renderForDisplay(file: string, args: OpensslArgs): string {\n return [file, ...args].map((a) => (a === \"\" || /[\\s\"'`$\\\\]/.test(a) ? JSON.stringify(a) : a)).join(\" \");\n}\n\n/**\n * Run `file` with `args` directly (no shell): each element of `args` reaches\n * the child as one argv entry, so a value can never be reinterpreted as a\n * shell metacharacter, a redirection, or a second command. stdin is\n * `/dev/null`: OpenSSL's app UI opens the console before honouring\n * `-passin` and calls tcgetattr on stdin when there is no controlling TTY;\n * a socket (Node's default child stdin) yields ENOTTY on Linux but\n * EOPNOTSUPP on macOS, which OpenSSL rejects and the key load fails even\n * with the right passphrase; /dev/null yields ENOTTY everywhere. It also\n * removes any way for openssl to block reading a password from stdin.\n */\nexport async function execute(file: string, args: OpensslArgs, options: ExecuteOptions): Promise<string> {\n const from = new Error();\n\n options.cwd = options.cwd || process.cwd();\n\n // istanbul ignore next\n if (!g_config.silent) {\n warningLog(chalk.cyan(\" CWD \"), options.cwd);\n }\n\n const outputs: string[] = [];\n const errorOutputs: string[] = [];\n const display = renderForDisplay(file, args);\n\n return await new Promise((resolve, reject) => {\n const child = child_process.spawn(file, [...args], {\n cwd: options.cwd,\n windowsHide: true,\n env: buildChildEnv(options.env),\n stdio: [\"ignore\", \"pipe\", \"pipe\"]\n });\n\n const fail = (message: string) => {\n // istanbul ignore next\n // The banner duplicates what the rejection already carries, and\n // this is the one place in this module that ignored the library's\n // own (default-on) silence. Callers that let the error propagate\n // still get the full command and stderr from the Error itself;\n // set VERBOSE to see it as it happens.\n if (!options.hideErrorMessage && !g_config.silent) {\n const fence = \"###########################################\";\n console.error(chalk.bgWhiteBright.redBright(`${fence} OPENSSL ERROR ${fence}`));\n console.error(chalk.bgWhiteBright.redBright(`CWD = ${options.cwd}`));\n console.error(chalk.bgWhiteBright.redBright(message));\n console.error(chalk.bgWhiteBright.redBright(`${fence} OPENSSL ERROR ${fence}`));\n\n console.error(from.stack);\n }\n reject(new Error(message));\n };\n\n child.on(\"error\", (err: Error) => fail(`Command failed: ${display}\\n${err.message}`));\n child.on(\"close\", (code: number | null, signal: NodeJS.Signals | null) => {\n if (code === 0) {\n resolve(outputs.join(\"\"));\n return;\n }\n const why = signal ? `signal ${signal}` : `exit code ${code}`;\n fail(`Command failed: ${display}\\n${errorOutputs.join(\"\")}(${why})`);\n });\n\n if (child.stdout) {\n const stream2 = byline(child.stdout);\n stream2.on(\"data\", (line: string) => {\n outputs.push(`${line}\\n`);\n });\n if (!g_config.silent) {\n stream2.on(\"data\", (line: string) => {\n line = line.toString();\n if (doDebug) {\n process.stdout.write(`${chalk.white(\" stdout \") + chalk.whiteBright(line)}\\n`);\n }\n });\n }\n }\n\n if (child.stderr) {\n const stream1 = byline(child.stderr);\n stream1.on(\"data\", (line: string) => {\n line = line.toString();\n errorOutputs.push(`${line}\\n`);\n // istanbul ignore next\n if (!g_config.silent && displayError) {\n process.stdout.write(`${chalk.white(\" stderr \") + chalk.red(line)}\\n`);\n }\n });\n }\n });\n}\n\nexport async function find_openssl(): Promise<string> {\n return await get_openssl_exec_path();\n}\n\nexport async function ensure_openssl_installed(): Promise<void> {\n if (!opensslPath) {\n opensslPath = await find_openssl();\n const outputs = await execute_openssl([\"version\"], { cwd: \".\" });\n g_config.opensslVersion = outputs.trim();\n if (doDebug) {\n warningLog(\"OpenSSL version : \", g_config.opensslVersion);\n }\n }\n}\n\nexport async function executeOpensslAsync(args: OpensslArgs, options: ExecuteOpenSSLOptions): Promise<string> {\n return await execute_openssl(args, options);\n}\n\nexport async function execute_openssl_no_failure(args: OpensslArgs, options: ExecuteOpenSSLOptions) {\n options = options || {};\n options.hideErrorMessage = true;\n try {\n return await execute_openssl(args, options);\n } catch (err) {\n debugLog(\" (ignored error = ERROR : )\", (err as Error).message);\n }\n}\n\nfunction getTempFolder(): string {\n return os.tmpdir();\n}\n\nexport interface ExecuteOpenSSLOptions extends ExecuteOptions {\n openssl_conf?: string;\n}\n\n/**\n * Run `openssl` with `args` (see {@link OpensslArgs}): no shell, one argv\n * entry per element, curated environment, /dev/null stdin.\n */\nexport async function execute_openssl(args: OpensslArgs, options: ExecuteOpenSSLOptions): Promise<string> {\n // never log `options` as-is: `options.env` may carry a passphrase\n debugLog(\"execute_openssl\", args, redactEnvForLog(options));\n const empty_config_file = n(getTempFolder(), \"empty_config.cnf\");\n if (!fs.existsSync(empty_config_file)) {\n await fs.promises.writeFile(empty_config_file, \"# empty config file\");\n }\n\n options = options || {};\n options.openssl_conf = options.openssl_conf || empty_config_file; // \"!! OPEN SLL CONF NOT DEFINED BAD FILE !!\";\n assert(options.openssl_conf);\n setEnv(\"OPENSSL_CONF\", options.openssl_conf);\n\n // istanbul ignore next\n if (!g_config.silent) {\n warningLog(chalk.cyan(\" OPENSSL_CONF\"), process.env.OPENSSL_CONF);\n warningLog(chalk.cyan(\" RANDFILE \"), process.env.RANDFILE);\n warningLog(chalk.cyan(\" CMD \"), chalk.cyanBright(renderForDisplay(\"openssl\", args)));\n }\n await ensure_openssl_installed();\n return await execute(opensslPath as string, args, options);\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport assert from \"node:assert\";\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport type { Filename } from \"../common\";\nimport { makePath } from \"../common2\";\nimport { g_config } from \"../config\";\nimport { getEnv, getEnvironmentVarNames, hasEnv } from \"./_env\";\nimport { type ExecuteOptions, execute_openssl, passinArg } from \"./execute_openssl\";\n\nfunction openssl_require2DigitYearInDate() {\n // istanbul ignore next\n if (!g_config.opensslVersion) {\n throw new Error(\n \"openssl_require2DigitYearInDate : openssl version is not known:\" + \" please call ensure_openssl_installed()\"\n );\n }\n return g_config.opensslVersion.match(/OpenSSL 0\\.9/);\n}\n\ng_config.opensslVersion = \"\";\n\nlet _counter = 0;\n\n/**\n * Strip Mustache-style conditional blocks from an OpenSSL config template.\n *\n * {{#KEY}}...{{/KEY}}\n *\n * The block content is **kept** (markers removed) iff `KEY` resolves to a\n * non-empty value — from `envOverrides` if it names the key, otherwise from\n * the global registry (see {@link exportedEnvVars}) — and stripped\n * (including the markers and the trailing newline) otherwise.\n *\n * Used to drive opt-in extensions like CRL Distribution Points and\n * Authority Information Access: the same template serves the\n * extension-set case (URL configured) and the extension-omitted case\n * (no URL configured).\n */\nfunction stripConditionalBlocks(template: string, envOverrides?: Readonly<Record<string, string>>): string {\n return template.replace(/\\{\\{#([A-Z_][A-Z0-9_]*)\\}\\}([\\s\\S]*?)\\{\\{\\/\\1\\}\\}\\r?\\n?/g, (_match, key: string, content: string) => {\n const keep =\n envOverrides && Object.prototype.hasOwnProperty.call(envOverrides, key)\n ? envOverrides[key] !== \"\"\n : hasEnv(key) && getEnv(key) !== \"\";\n return keep ? content : \"\";\n });\n}\n\n/**\n * Render an OpenSSL config template (`$ENV::NAME` substitution, `{{#NAME}}`\n * conditional blocks) to a temporary file and return its path.\n *\n * `envOverrides`, when given, is consulted before the global env registry\n * for every key it names — the substituted value never depends on whatever\n * `setEnv()` calls other, possibly-concurrent code made before or after this\n * call. Pass it for any value the caller has already computed locally (as\n * every `CertificateAuthority` operation now does for `ALTNAME` /\n * `CDP_URL` / `AIA_VALUE`); omit it, as every other caller does, to keep\n * reading the shared registry exactly as before.\n */\nexport function generateStaticConfig(\n configPath: string,\n options?: ExecuteOptions,\n envOverrides?: Readonly<Record<string, string>>\n) {\n const prePath = options?.cwd || \"\";\n\n const originalFilename = !path.isAbsolute(configPath) ? path.join(prePath, configPath) : configPath;\n let staticConfig = fs.readFileSync(originalFilename, { encoding: \"utf8\" });\n // Strip conditional blocks first so unset placeholders never reach\n // the env-var substitution pass below.\n staticConfig = stripConditionalBlocks(staticConfig, envOverrides);\n // Substituted values go through the function form of String.replace: the\n // string form interprets `$`-sequences (`$&`, `$$`, \"$`\", `$'`) in the\n // VALUE as replacement patterns, so a subject CN or CDP/OCSP URL\n // containing `$&` would re-insert the `$ENV::NAME` literal into the\n // rendered config and every openssl call on it would fail with\n // \"variable has no value\".\n for (const envVar of getEnvironmentVarNames()) {\n if (envOverrides && Object.prototype.hasOwnProperty.call(envOverrides, envVar.key)) {\n continue; // overridden below\n }\n staticConfig = staticConfig.replace(new RegExp(envVar.pattern, \"gi\"), () => getEnv(envVar.key));\n }\n if (envOverrides) {\n for (const [key, value] of Object.entries(envOverrides)) {\n staticConfig = staticConfig.replace(new RegExp(`\\\\$ENV\\\\:\\\\:${key}`, \"gi\"), () => value);\n }\n }\n const staticConfigPath = `${configPath}.${process.pid}-${_counter++}.tmp`;\n const temporaryConfigPath = !path.isAbsolute(configPath) ? path.join(prePath, staticConfigPath) : staticConfigPath;\n fs.writeFileSync(temporaryConfigPath, staticConfig);\n if (options?.cwd) {\n return path.relative(options.cwd, temporaryConfigPath);\n } else {\n return temporaryConfigPath;\n }\n}\n\n/**\n * Remove a rendered temp config produced by {@link generateStaticConfig}.\n * `configFile` is whatever that function returned (relative to\n * `options.cwd` when a cwd was given, absolute otherwise). Every caller of\n * `generateStaticConfig` is expected to pair it with this in a `finally`,\n * or the `<name>.<pid>-<n>.tmp` files accumulate next to the real config\n * forever.\n */\nexport async function cleanupStaticConfig(configFile: string, options?: ExecuteOptions): Promise<void> {\n await fs.promises.rm(path.resolve(options?.cwd ?? \"\", configFile), { force: true });\n}\n\nconst n = makePath;\n\n/**\n * calculate the public key from private key\n * openssl rsa -pubout -in private_key.pem -passin env:...\n *\n * `-passin` is always emitted (empty for a plaintext key) so an encrypted\n * key without a passphrase fails fast instead of hanging on a TTY prompt.\n *\n * @method getPublicKeyFromPrivateKey\n * @param privateKeyFilename: the existing file with the private key\n * @param publicKeyFilename: the file where to store the public key\n * @param passphrase: decrypts `privateKeyFilename` if it is an encrypted PKCS#8 key\n */\nexport async function getPublicKeyFromPrivateKey(\n privateKeyFilename: string,\n publicKeyFilename: string,\n passphrase?: string\n): Promise<void> {\n assert(fs.existsSync(privateKeyFilename));\n const passin = passinArg(passphrase);\n await execute_openssl([\"rsa\", \"-pubout\", \"-in\", n(privateKeyFilename), \"-out\", n(publicKeyFilename), ...passin.args], {\n env: passin.env\n });\n}\n\n/**\n * extract public key from a certificate\n * openssl x509 -pubkey -in certificate.pem -nottext\n *\n * @method getPublicKeyFromCertificate\n * @param certificateFilename\n * @param publicKeyFilename\n */\nexport async function getPublicKeyFromCertificate(certificateFilename: string, publicKeyFilename: string) {\n assert(fs.existsSync(certificateFilename));\n // no shell, so no `>` redirection: capture stdout and write it ourselves\n const output = await execute_openssl([\"x509\", \"-pubkey\", \"-in\", n(certificateFilename)], {});\n await fs.promises.writeFile(publicKeyFilename, output);\n}\nexport function x509Date(date?: Date): string {\n date = date || new Date();\n const Y = date.getUTCFullYear();\n const M = date.getUTCMonth() + 1;\n const D = date.getUTCDate();\n const h = date.getUTCHours();\n const m = date.getUTCMinutes();\n const s = date.getUTCSeconds();\n\n function w(s: string | number, l: number): string {\n return `${s}`.padStart(l, \"0\");\n }\n\n if (openssl_require2DigitYearInDate()) {\n // for example: on MacOS , where openssl 0.98 is installed by default\n return `${w(Y, 2) + w(M, 2) + w(D, 2) + w(h, 2) + w(m, 2) + w(s, 2)}Z`;\n } else {\n // for instance when openssl version is greater than 1.0.0\n return `${w(Y, 4) + w(M, 2) + w(D, 2) + w(h, 2) + w(m, 2) + w(s, 2)}Z`;\n }\n}\n\n/**\n * @param certificate - the certificate file in PEM format, file must exist\n */\nexport async function dumpCertificate(certificate: Filename): Promise<string> {\n assert(fs.existsSync(certificate));\n return await execute_openssl([\"x509\", \"-in\", n(certificate), \"-text\", \"-noout\"], {});\n}\n\nexport async function toDer(certificatePem: string): Promise<string> {\n assert(fs.existsSync(certificatePem));\n const certificateDer = certificatePem.replace(\".pem\", \".der\");\n return await execute_openssl([\"x509\", \"-outform\", \"der\", \"-in\", certificatePem, \"-out\", certificateDer], {});\n}\n\nexport async function fingerprint(certificatePem: string): Promise<string> {\n // openssl x509 -in my_certificate.pem -hash -dates -noout -fingerprint\n assert(fs.existsSync(certificatePem));\n return await execute_openssl([\"x509\", \"-fingerprint\", \"-noout\", \"-in\", certificatePem], {});\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport assert from \"node:assert\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\n\nimport { Subject } from \"../../misc/subject\";\nimport type { CreateCertificateSigningRequestWithConfigOptions } from \"../common\";\nimport { makePath } from \"../common2\";\nimport { displaySubtitle } from \"../display\";\nimport { processAltNames } from \"./_env\";\nimport { execute_openssl } from \"./execute_openssl\";\nimport { cleanupStaticConfig, generateStaticConfig } from \"./toolbox\";\n\nconst n = makePath;\n\n/**\n * create a certificate signing request\n */\nexport async function createCertificateSigningRequestWithOpenSSL(\n certificateSigningRequestFilename: string,\n params: CreateCertificateSigningRequestWithConfigOptions\n): Promise<void> {\n assert(params);\n assert(params.rootDir);\n assert(params.configFile);\n assert(params.privateKey);\n assert(typeof params.privateKey === \"string\");\n assert(fs.existsSync(params.configFile), `config file must exist ${params.configFile}`);\n assert(fs.existsSync(params.privateKey), `Private key must exist${params.privateKey}`);\n assert(fs.existsSync(params.rootDir), \"RootDir key must exist\");\n assert(typeof certificateSigningRequestFilename === \"string\");\n\n // note : this openssl command requires a config file\n processAltNames(params);\n const configFile = generateStaticConfig(params.configFile, { cwd: params.rootDir });\n try {\n const options = { cwd: params.rootDir, openssl_conf: path.relative(params.rootDir, configFile) };\n\n const subject = params.subject ? new Subject(params.subject).toString() : undefined;\n\n displaySubtitle(\"- Creating a Certificate Signing Request with openssl\");\n await execute_openssl(\n [\n \"req\",\n \"-new\",\n \"-sha256\",\n \"-batch\",\n \"-text\",\n \"-config\",\n n(configFile),\n \"-key\",\n n(params.privateKey),\n ...(subject ? [\"-subj\", subject] : []),\n \"-out\",\n n(certificateSigningRequestFilename)\n ],\n options\n );\n } finally {\n await cleanupStaticConfig(configFile, { cwd: params.rootDir });\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport exp from \"node:constants\";\n\nconst _exp = exp;\n\nexport * from \"./_env\";\nexport * from \"./create_certificate_signing_request\";\nexport * from \"./execute_openssl\";\nexport * from \"./install_prerequisite\";\nexport * from \"./toolbox\";\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { convertPEMtoDER, readCertificatePEM } from \"node-opcua-crypto\";\n\n/**\n * A record from the OpenSSL CA certificate database (`index.txt`).\n */\nexport interface IssuedCertificateRecord {\n /** Hex-encoded serial number (e.g. `\"1000\"`). */\n serial: string;\n /** Certificate status. */\n status: \"valid\" | \"revoked\" | \"expired\";\n /** X.500 subject string (slash-delimited). */\n subject: string;\n /** Certificate expiry date as ISO-8601 string. */\n expiryDate: string;\n /**\n * Revocation date as ISO-8601 string.\n * Only present when `status === \"revoked\"`.\n */\n revocationDate?: string;\n /**\n * CRL revocation reason (e.g. `\"keyCompromise\"`), as stored after the\n * comma in the revocation-date field. Only present when\n * `status === \"revoked\"` and a reason was recorded.\n */\n reason?: string;\n}\n\n/**\n * Parse an OpenSSL date string (`YYMMDDHHmmssZ`) into an ISO-8601 string.\n */\nfunction parseOpenSSLDate(dateStr: string): string {\n // Revocation dates may have a reason suffix: \"YYMMDDHHmmssZ,reason\"\n // Strip anything after the first comma.\n const raw = dateStr?.split(\",\")[0] ?? \"\";\n if (raw.length < 12) return \"\";\n // OpenSSL uses 2-digit year; 70+ is 19xx, <70 is 20xx\n const yy = parseInt(raw.substring(0, 2), 10);\n const year = yy >= 70 ? 1900 + yy : 2000 + yy;\n const month = raw.substring(2, 4);\n const day = raw.substring(4, 6);\n const hour = raw.substring(6, 8);\n const min = raw.substring(8, 10);\n const sec = raw.substring(10, 12);\n return `${year}-${month}-${day}T${hour}:${min}:${sec}Z`;\n}\n\n/** The inverse of {@link parseOpenSSLDate}: format a `Date` as `YYMMDDHHmmssZ` (UTC). */\nfunction formatOpenSSLDate(date: Date): string {\n const yy = String(date.getUTCFullYear() % 100).padStart(2, \"0\");\n const mm = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n const dd = String(date.getUTCDate()).padStart(2, \"0\");\n const hh = String(date.getUTCHours()).padStart(2, \"0\");\n const mi = String(date.getUTCMinutes()).padStart(2, \"0\");\n const ss = String(date.getUTCSeconds()).padStart(2, \"0\");\n return `${yy}${mm}${dd}${hh}${mi}${ss}Z`;\n}\n\n/** Extract the reason suffix (after the first comma) from a revocation-date field, if any. */\nfunction parseRevocationReason(dateStr: string): string | undefined {\n const parts = dateStr?.split(\",\");\n return parts && parts.length > 1 ? parts[1] : undefined;\n}\n\n/** Pad a hex string to an even number of digits, matching OpenSSL's `serial`/`crlnumber` file convention. */\nfunction evenLengthHex(value: bigint): string {\n const hex = value.toString(16).toUpperCase();\n return hex.length % 2 === 0 ? hex : `0${hex}`;\n}\n\n/**\n * Escape every control character (and backslash) as `\\xHH`, the way\n * OpenSSL's `X509_NAME_oneline` does before writing a subject to\n * `index.txt`. `index.txt` is a tab/newline-delimited table: a subject\n * (which comes verbatim from the requester's CSR, so is attacker\n * controlled) containing a raw `\\n` or `\\t` would otherwise inject a\n * forged row — e.g. an `R` entry naming a victim's serial, which the next\n * CRL regeneration would then faithfully publish as revoked.\n */\nfunction escapeIndexField(value: string): string {\n // biome-ignore lint/suspicious/noControlCharactersInRegex: escaping control characters is the point\n return value.replace(/[\\x00-\\x1f\\x7f\\\\]/g, (c) => `\\\\x${c.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`);\n}\n\n/** A hex serial handed to a writer must be exactly that — never something that could carry a field or row separator. */\nfunction assertHexSerial(serial: string): string {\n if (!/^[0-9A-Fa-f]+$/.test(serial)) {\n throw new Error(`Invalid certificate serial number: ${JSON.stringify(serial)}`);\n }\n return serial.toUpperCase();\n}\n\n/**\n * Read and write access to a CA's OpenSSL-format certificate database\n * (`index.txt`, `serial`, `crlnumber`, `certs/<SERIAL>.pem`).\n *\n * This is the format `openssl ca` itself writes and reads; every mutating\n * method here (`nextSerial`, `nextCrlNumber`, `appendIssued`, `markRevoked`,\n * `storeCertificate`) exists so a native (non-openssl) signing backend can\n * write the exact same on-disk format `openssl ca` does, so an install can\n * move between backends and external `openssl` tooling keeps working on the\n * same directory. Callers are responsible for serializing access — every\n * mutating call must happen under the owning CA's directory lock\n * (`CertificateAuthority._withCaDirectoryLock`), the same guarantee\n * `OpenSslCaBackend` gets from the lock around each `openssl ca` /\n * `openssl x509 -CAserial` invocation.\n */\nexport class CaDatabase {\n readonly #rootDir: string;\n\n constructor(rootDir: string) {\n this.#rootDir = rootDir;\n }\n\n /** Path to the OpenSSL certificate database file (`index.txt`). */\n public get indexFile(): string {\n return path.join(this.#rootDir, \"index.txt\");\n }\n\n /**\n * Parse the OpenSSL `index.txt` certificate database.\n *\n * Each line has tab-separated fields:\n * ```\n * status expiry [revocationDate] serial unknown subject\n * ```\n *\n * - status: `V` (valid), `R` (revoked), `E` (expired)\n * - expiry: `YYMMDDHHmmssZ`\n * - revocationDate: present only for revoked certs\n * - serial: hex string\n * - unknown: always `\"unknown\"`\n * - subject: X.500 slash-delimited string\n */\n public readIndex(): IssuedCertificateRecord[] {\n const indexPath = this.indexFile;\n if (!fs.existsSync(indexPath)) {\n return [];\n }\n\n const content = fs.readFileSync(indexPath, \"utf-8\");\n const lines = content.split(\"\\n\").filter((l) => l.trim().length > 0);\n const records: IssuedCertificateRecord[] = [];\n\n for (const line of lines) {\n const fields = line.split(\"\\t\");\n if (fields.length < 4) continue;\n\n const statusChar = fields[0];\n const expiryStr = fields[1];\n\n let serial: string;\n let subject: string;\n let revocationDate: string | undefined;\n\n if (statusChar === \"R\") {\n // Revoked: status expiry revocationDate serial unknown subject\n revocationDate = fields[2];\n serial = fields[3];\n subject = fields.length >= 6 ? fields[5] : \"\";\n } else {\n // Valid/Expired: status expiry (empty) serial unknown subject\n serial = fields[3];\n subject = fields.length >= 6 ? fields[5] : \"\";\n }\n\n let status: \"valid\" | \"revoked\" | \"expired\";\n switch (statusChar) {\n case \"V\":\n status = \"valid\";\n break;\n case \"R\":\n status = \"revoked\";\n break;\n case \"E\":\n status = \"expired\";\n break;\n default:\n continue; // skip unknown status\n }\n\n records.push({\n serial,\n status,\n subject,\n expiryDate: parseOpenSSLDate(expiryStr),\n revocationDate: revocationDate ? parseOpenSSLDate(revocationDate) : undefined,\n reason: revocationDate ? parseRevocationReason(revocationDate) : undefined\n });\n }\n\n return records;\n }\n\n /** Look up one record by serial number (case-insensitive). */\n public findBySerial(serial: string): IssuedCertificateRecord | undefined {\n const upper = serial.toUpperCase();\n return this.readIndex().find((r) => r.serial.toUpperCase() === upper);\n }\n\n /**\n * Read a specific issued certificate by serial number.\n *\n * OpenSSL stores signed certificates in the `certs/` directory using\n * the naming convention `<SERIAL>.pem`.\n *\n * @param serial - hex-encoded serial number (e.g. `\"1000\"`)\n * @returns the DER buffer, or `undefined` if not found\n */\n public getCertificateBySerial(serial: string): Buffer | undefined {\n const upper = serial.toUpperCase();\n const certFile = path.join(this.#rootDir, \"certs\", `${upper}.pem`);\n if (!fs.existsSync(certFile)) {\n return undefined;\n }\n const pem = readCertificatePEM(certFile);\n return convertPEMtoDER(pem);\n }\n\n /**\n * Read-increment-write a hex counter file (`serial`/`crlnumber`),\n * returning the value to hand out — matching `openssl ca`'s own\n * behavior: the file holds the *next* value to assign, and is bumped\n * to the following one immediately after being read. A `.old` backup\n * of the pre-bump content is kept, as `openssl` itself does.\n */\n #nextHexCounter(fileName: string): string {\n const counterFile = path.join(this.#rootDir, fileName);\n const current = BigInt(`0x${fs.readFileSync(counterFile, \"utf-8\").trim()}`);\n fs.copyFileSync(counterFile, `${counterFile}.old`);\n fs.writeFileSync(counterFile, evenLengthHex(current + 1n));\n return evenLengthHex(current);\n }\n\n /** Hand out the next certificate serial number, bumping the `serial` file. */\n public nextSerial(): string {\n return this.#nextHexCounter(\"serial\");\n }\n\n /** Hand out the next CRL number, bumping the `crlnumber` file. */\n public nextCrlNumber(): string {\n return this.#nextHexCounter(\"crlnumber\");\n }\n\n /** Append a newly-issued certificate's `V` (valid) row to `index.txt`. */\n public appendIssued(record: { serial: string; expiryDate: Date; subject: string }): void {\n const serial = assertHexSerial(record.serial);\n const subject = escapeIndexField(record.subject);\n const line = `V\\t${formatOpenSSLDate(record.expiryDate)}\\t\\t${serial}\\tunknown\\t${subject}\\n`;\n fs.appendFileSync(this.indexFile, line);\n }\n\n /**\n * Rewrite a certificate's `index.txt` row from `V` to `R` (revoked).\n * Throws if the serial is not found, or is already revoked — the same\n * \"already revoked\" case `openssl ca -revoke` itself rejects.\n */\n public markRevoked(serial: string, revocationDate: Date, reason: string): void {\n const upper = assertHexSerial(serial);\n if (!/^[A-Za-z]+$/.test(reason)) {\n throw new Error(`Invalid CRL reason: ${JSON.stringify(reason)}`);\n }\n const lines = fs\n .readFileSync(this.indexFile, \"utf-8\")\n .split(\"\\n\")\n .filter((l) => l.trim().length > 0);\n\n let found = false;\n const rewritten = lines.map((line) => {\n const fields = line.split(\"\\t\");\n if (fields.length < 4 || fields[3]?.toUpperCase() !== upper) {\n return line;\n }\n if (fields[0] === \"R\") {\n throw new Error(`Certificate ${upper} is already revoked`);\n }\n found = true;\n const subject = fields.length >= 6 ? fields[5] : \"\";\n return `R\\t${fields[1]}\\t${formatOpenSSLDate(revocationDate)},${reason}\\t${upper}\\tunknown\\t${subject}`;\n });\n\n if (!found) {\n throw new Error(`Certificate ${upper} not found in the certificate database`);\n }\n fs.writeFileSync(this.indexFile, `${rewritten.join(\"\\n\")}\\n`);\n }\n\n /** Store a signed certificate's PEM under `certs/<SERIAL>.pem`, as `openssl ca` does. */\n public storeCertificate(serial: string, pem: string): void {\n const certFile = path.join(this.#rootDir, \"certs\", `${assertHexSerial(serial)}.pem`);\n fs.writeFileSync(certFile, pem);\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n type CaSignAlgorithm,\n type CaSigner,\n CertificatePurpose,\n createCertificateFromCsr,\n createCertificateSigningRequest,\n createCrl,\n isCaSigner,\n privateKeyToCryptoKey,\n readPrivateKey,\n Subject,\n x509\n} from \"node-opcua-crypto\";\nimport { displaySubtitle, displayTitle, type Params, type ProcessAltNamesParam } from \"../../toolbox\";\nimport type { CaBackend } from \"../core/ca_backend\";\nimport { CaDatabase } from \"../core/ca_database\";\nimport type { CertificateAuthorityCore } from \"../core/certificate_authority_core\";\n\n/** The CA-certificate lifetime the openssl backend hard-codes (`x509 -req -days 3650`). */\nconst CA_CERT_VALIDITY_DAYS = 3650;\n\nconst RSA_SHA256: CaSignAlgorithm = { name: \"RSASSA-PKCS1-v1_5\", hash: { name: \"SHA-256\" } };\n\n/** A signer declares its own algorithm; a raw key is always the RSA/SHA-256 this CA generates. */\nfunction signingAlgorithmOf(key: CryptoKey | CaSigner): CaSignAlgorithm {\n return isCaSigner(key) ? key.algorithm : RSA_SHA256;\n}\n\nfunction daysFromNow(notBefore: Date, days: number): Date {\n return new Date(notBefore.getTime() + days * 24 * 60 * 60 * 1000);\n}\n\n/**\n * The SAN every CA certificate carries. RFC 5280 does not require one on a\n * CA certificate, but the OPC UA profile does, and validators (UaExpert,\n * the compliance tools) reject a CA without it - so mirror what the\n * openssl backend puts in `[v3_ca]`: `URI:urn:<commonName>`.\n */\nfunction caSanUri(ca: CertificateAuthorityCore): string {\n return `urn:${ca.subject.commonName || \"NodeOPCUA-CA\"}`;\n}\n\n/**\n * The subject alternative names a CSR asked for, in the shape the signing\n * primitive wants. `openssl ca` does not copy SANs across from the CSR\n * (openssl/openssl#10458), which is why the caller has to re-derive them;\n * peculiar decodes IP addresses to dotted form for us.\n */\nfunction sanFromCsr(csrPem: string): { dns: string[]; ip: string[]; applicationUri?: string } {\n const request = new x509.Pkcs10CertificateRequest(csrPem);\n const extension = request.getExtension(\"2.5.29.17\") as x509.SubjectAlternativeNameExtension | null;\n const dns: string[] = [];\n const ip: string[] = [];\n let applicationUri: string | undefined;\n for (const name of extension?.names.toJSON() ?? []) {\n if (name.type === \"dns\") {\n dns.push(name.value);\n } else if (name.type === \"ip\") {\n ip.push(name.value);\n } else if (name.type === \"url\" && applicationUri === undefined) {\n applicationUri = name.value;\n }\n }\n return { dns, ip, applicationUri };\n}\n\n/**\n * Maps this codebase's CRL revocation reason strings (see\n * `CertificateAuthority.revokeCertificate`'s `crlReasons` list) to\n * `@peculiar/x509`'s `X509CrlReason` enum keys — same reasons, but\n * `X509CrlReason.cACompromise` is lowercase-first where this codebase's\n * `\"CACompromise\"` is not.\n */\nconst REASON_TO_X509_CRL_REASON: Record<string, x509.X509CrlReason> = {\n unspecified: x509.X509CrlReason.unspecified,\n keyCompromise: x509.X509CrlReason.keyCompromise,\n CACompromise: x509.X509CrlReason.cACompromise,\n affiliationChanged: x509.X509CrlReason.affiliationChanged,\n superseded: x509.X509CrlReason.superseded,\n cessationOfOperation: x509.X509CrlReason.cessationOfOperation,\n certificateHold: x509.X509CrlReason.certificateHold,\n removeFromCRL: x509.X509CrlReason.removeFromCRL\n};\n\n/**\n * Builds OpenSSL's slash-delimited one-line subject (`\"/CN=Leaf/O=Acme\"`)\n * from the certificate's parsed subject attributes — NOT by re-splitting\n * `Name.toString()`. The subject comes verbatim from the requester's CSR,\n * so it is attacker-controlled; the string form escapes `,` (which a\n * `split(\",\")` would then mangle) and, because its control-character\n * `replace()` has no `g` flag, escapes only the FIRST `\\n`/`\\t` per value,\n * letting later ones through raw — which would let a crafted CN inject a\n * forged row into the tab/newline-delimited `index.txt`. Working from\n * `toJSON()` sidesteps that entirely; {@link CaDatabase} additionally\n * escapes every control character it writes, as `X509_NAME_oneline` does.\n */\nfunction toOpenSslSubjectString(subjectName: x509.Name): string {\n const parts: string[] = [];\n for (const rdn of subjectName.toJSON()) {\n for (const [type, values] of Object.entries(rdn)) {\n for (const value of values) {\n parts.push(`${type}=${value}`);\n }\n }\n }\n return `/${parts.join(\"/\")}`;\n}\n\n/**\n * A native (pure-JS, no `openssl` child process) {@link CaBackend}: it\n * bootstraps a CA, signs end-entity and subordinate-CA requests, revokes,\n * and builds CRLs entirely through `node-opcua-crypto`'s signing\n * primitives and {@link CaDatabase}'s write path, so the resulting\n * `index.txt`/`serial`/`crlnumber`/`certs/` are the same on-disk format\n * `openssl ca` produces and an install can move between backends.\n *\n * The signing key reaches every operation through\n * `CertificateAuthority._getSigningKey()`, which yields either the on-disk\n * key or an external `CaSigner`. Nothing below can tell the difference,\n * which is the point: a CA whose key lives in an HSM never has a\n * `private/cakey.pem` and never needs one.\n *\n * Two deliberate differences from the openssl backend, both improvements:\n * a subordinate CA's certificate is recorded in the issuer's `index.txt`\n * (`openssl x509 -CAserial` bumps the serial file but records nothing),\n * and a subordinate's SAN is taken from its own CSR rather than being\n * stamped with the issuer's.\n */\nexport class NativeCaBackend implements CaBackend {\n /** Nothing to check: this backend spawns no process and needs no tool on PATH. */\n /** Signing goes through `ca._getSigningKey()`, which may be an external signer. */\n public readonly supportsExternalSigner = true;\n\n public async preflight(): Promise<void> {\n // intentionally empty\n }\n\n /**\n * Write a CSR for the CA's own key, the `[v3_ca_req]` equivalent. The\n * key comes from the CA rather than from `privateKeyFile`: on a\n * signer-backed CA that file does not exist.\n */\n public async generateCaCsr(\n ca: CertificateAuthorityCore,\n _caRootDir: string,\n _privateKeyFile: string,\n csrFile: string\n ): Promise<void> {\n displayTitle(\"Generate a certificate request for the CA key\");\n const signingKey = await ca._getSigningKey();\n const { csr } = await createCertificateSigningRequest({\n privateKey: signingKey,\n subject: ca.subject.toString(),\n applicationUri: caSanUri(ca),\n purpose: CertificatePurpose.ForCertificateAuthority\n });\n await fs.promises.writeFile(csrFile, csr);\n }\n\n public async bootstrap(ca: CertificateAuthorityCore): Promise<void> {\n const caRootDir = path.resolve(ca.rootDir);\n const csrFile = path.join(caRootDir, \"private/cakey.csr\");\n await this.generateCaCsr(ca, caRootDir, path.join(caRootDir, \"private/cakey.pem\"), csrFile);\n\n const issuerCA = ca._issuerCA;\n if (issuerCA) {\n displayTitle(\"Generate CA Certificate (signed by issuer CA)\");\n // The issuer's serial file and database are mutated here, so the\n // issuer's own lock is required - the caller only holds this\n // (subordinate) CA's. Subordinate -> issuer is the only cross-CA\n // lock edge in this codebase and it is never reversed, so it\n // cannot deadlock; the exception is two CAs sharing one rootDir,\n // where the lock is already held and re-acquiring the\n // non-reentrant file lock would deadlock against itself.\n const signWithIssuer = () => this.signSubordinateCsr(issuerCA, csrFile, ca.caCertificate, CA_CERT_VALIDITY_DAYS);\n if (path.resolve(issuerCA.rootDir) === caRootDir) {\n await signWithIssuer();\n } else {\n await issuerCA._withCaDirectoryLock(signWithIssuer);\n }\n } else {\n displayTitle(\"Generate CA Certificate (self-signed)\");\n const csrPem = await fs.promises.readFile(csrFile, \"utf-8\");\n const signingKey = await ca._getSigningKey();\n const request = new x509.Pkcs10CertificateRequest(csrPem);\n const notBefore = new Date();\n const { cert } = await createCertificateFromCsr({\n csr: csrPem,\n // the CSR's own parsed subject, so issuer and subject are\n // byte-identical on a self-signed root: re-encoding a string\n // form could differ and break chain building\n issuerName: request.subjectName,\n issuerPublicKey: request.publicKey,\n signingKey,\n signingAlgorithm: signingAlgorithmOf(signingKey),\n notBefore,\n notAfter: daysFromNow(notBefore, CA_CERT_VALIDITY_DAYS),\n purpose: CertificatePurpose.ForCertificateAuthority,\n applicationUri: caSanUri(ca),\n revocation: {\n crlDistributionUrl: ca.crlDistributionUrl,\n ocspResponderUrl: ca.ocspResponderUrl,\n caIssuersUrl: ca.caIssuersUrl\n }\n });\n await fs.promises.writeFile(ca.caCertificate, cert);\n }\n\n displaySubtitle(\"generate initial CRL (Certificate Revocation List)\");\n await this.#regenerateCrlLocked(ca, new CaDatabase(ca.rootDir));\n displayTitle(\"Create Certificate Authority (CA) ---> DONE\");\n }\n\n /** Sign a subordinate CA's request with this CA's key, the `[v3_ca]` equivalent. */\n public async signSubordinateCsr(\n ca: CertificateAuthorityCore,\n csrFile: string,\n certFile: string,\n validityDays: number\n ): Promise<void> {\n const { signingKey, signingAlgorithm, issuerPublicKey, issuerName } = await this.#issuerContext(ca);\n const csrPem = await fs.promises.readFile(csrFile, \"utf-8\");\n const db = new CaDatabase(ca.rootDir);\n const serialNumber = db.nextSerial();\n const notBefore = new Date();\n const notAfter = daysFromNow(notBefore, validityDays);\n\n const { cert } = await createCertificateFromCsr({\n csr: csrPem,\n issuerName,\n issuerPublicKey,\n signingKey,\n signingAlgorithm,\n serialNumber,\n notBefore,\n notAfter,\n purpose: CertificatePurpose.ForCertificateAuthority,\n // the subordinate's own SAN, not the issuer's\n ...sanFromCsr(csrPem),\n revocation: {\n crlDistributionUrl: ca.crlDistributionUrl,\n ocspResponderUrl: ca.ocspResponderUrl,\n caIssuersUrl: ca.caIssuersUrl\n }\n });\n\n await fs.promises.writeFile(certFile, cert);\n this.#record(db, serialNumber, cert, notAfter);\n }\n\n /**\n * Self-sign a certificate with a caller-supplied key file and record it\n * in this CA's database: the native equivalent of `openssl req -new`\n * followed by `openssl ca -selfsign`, which likewise applies the\n * end-entity profile and updates `index.txt`.\n */\n public async createSelfSignedCertificate(\n ca: CertificateAuthorityCore,\n certificateFile: string,\n privateKeyFile: string,\n params: Params\n ): Promise<void> {\n displaySubtitle(\"- the certificate signing request\");\n const key = await privateKeyToCryptoKey(readPrivateKey(privateKeyFile, await ca._privateKeyPassphrase()));\n const { csr } = await createCertificateSigningRequest({\n privateKey: key,\n subject: params.subject ? new Subject(params.subject).toString() : ca.subject.toString(),\n dns: params.dns,\n ip: params.ip,\n applicationUri: params.applicationUri,\n purpose: CertificatePurpose.ForApplication\n });\n\n displaySubtitle(\"- creating the self-signed certificate\");\n const request = new x509.Pkcs10CertificateRequest(csr);\n const db = new CaDatabase(ca.rootDir);\n const serialNumber = db.nextSerial();\n const notBefore = params.startDate ?? new Date();\n const notAfter = params.endDate ?? daysFromNow(notBefore, params.validity ?? 365);\n\n const { cert } = await createCertificateFromCsr({\n csr,\n issuerName: request.subjectName,\n issuerPublicKey: request.publicKey,\n signingKey: key,\n signingAlgorithm: RSA_SHA256,\n serialNumber,\n notBefore,\n notAfter,\n purpose: CertificatePurpose.ForApplication,\n ...sanFromCsr(csr)\n });\n\n await fs.promises.writeFile(certificateFile, cert);\n this.#record(db, serialNumber, cert, notAfter);\n }\n\n /** `certs/<SERIAL>.pem` plus the `V` row, exactly as `openssl ca` writes them. */\n #record(db: CaDatabase, serialNumber: string, certPem: string, notAfter: Date): void {\n db.storeCertificate(serialNumber, certPem);\n db.appendIssued({\n serial: serialNumber,\n expiryDate: notAfter,\n subject: toOpenSslSubjectString(new x509.X509Certificate(certPem).subjectName)\n });\n }\n\n /**\n * The CA's signing key and issuer identity, resolved fresh on every\n * call and never cached across operations. The identity is read back\n * from the CA certificate on disk so that the issuer field of anything\n * this CA signs is byte-identical to that certificate's subject.\n */\n async #issuerContext(ca: CertificateAuthorityCore): Promise<{\n signingKey: CryptoKey | CaSigner;\n signingAlgorithm: CaSignAlgorithm;\n issuerPublicKey: x509.PublicKey;\n issuerName: x509.Name;\n }> {\n const signingKey = await ca._getSigningKey();\n const caCertPem = await fs.promises.readFile(ca.caCertificate, \"utf-8\");\n const caCert = new x509.X509Certificate(caCertPem);\n return {\n signingKey,\n signingAlgorithm: signingAlgorithmOf(signingKey),\n issuerPublicKey: caCert.publicKey,\n issuerName: caCert.subjectName\n };\n }\n\n public async signEndEntityCsr(\n ca: CertificateAuthorityCore,\n certificate: string,\n csr: string,\n params: Params,\n sanOverride: Required<ProcessAltNamesParam>\n ): Promise<void> {\n const { signingKey, signingAlgorithm, issuerPublicKey, issuerName } = await this.#issuerContext(ca);\n const db = new CaDatabase(ca.rootDir);\n const serialNumber = db.nextSerial();\n const csrPem = await fs.promises.readFile(csr, \"utf-8\");\n\n const notBefore = params.startDate ?? new Date();\n const notAfter = params.endDate ?? new Date(notBefore.getTime() + (params.validity ?? 365) * 24 * 60 * 60 * 1000);\n\n const { cert } = await createCertificateFromCsr({\n csr: csrPem,\n issuerName,\n issuerPublicKey,\n signingKey,\n signingAlgorithm,\n serialNumber,\n notBefore,\n notAfter,\n purpose: CertificatePurpose.ForApplication,\n dns: sanOverride.dns,\n ip: sanOverride.ip,\n applicationUri: sanOverride.applicationUri,\n revocation: {\n crlDistributionUrl: ca.crlDistributionUrl,\n ocspResponderUrl: ca.ocspResponderUrl,\n caIssuersUrl: ca.caIssuersUrl\n }\n });\n\n await fs.promises.writeFile(certificate, cert);\n this.#record(db, serialNumber, cert, notAfter);\n }\n\n async #regenerateCrlLocked(ca: CertificateAuthorityCore, db: CaDatabase): Promise<void> {\n const { signingKey, signingAlgorithm, issuerPublicKey, issuerName } = await this.#issuerContext(ca);\n const crlNumber = db.nextCrlNumber();\n const entries = db\n .readIndex()\n .filter((r) => r.status === \"revoked\")\n .map((r) => ({\n serialNumber: r.serial,\n revocationDate: r.revocationDate ? new Date(r.revocationDate) : new Date(),\n reason: r.reason ? REASON_TO_X509_CRL_REASON[r.reason] : undefined\n }));\n\n const { crl } = await createCrl({\n issuerName,\n issuerPublicKey,\n signingKey,\n signingAlgorithm,\n crlNumber: BigInt(`0x${crlNumber}`),\n entries\n });\n\n await fs.promises.writeFile(ca.revocationList, crl);\n const der = new x509.X509Crl(crl).rawData;\n await fs.promises.writeFile(ca.revocationListDER, Buffer.from(der));\n }\n\n public async regenerateCrl(ca: CertificateAuthorityCore): Promise<void> {\n const db = new CaDatabase(ca.rootDir);\n await this.#regenerateCrlLocked(ca, db);\n }\n\n public async revoke(ca: CertificateAuthorityCore, certificate: string, reason: string): Promise<void> {\n const certPem = await fs.promises.readFile(certificate, \"utf-8\");\n const cert = new x509.X509Certificate(certPem);\n const db = new CaDatabase(ca.rootDir);\n db.markRevoked(cert.serialNumber, new Date(), reason);\n await this.#regenerateCrlLocked(ca, db);\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport { Subject } from \"node-opcua-crypto\";\nimport { displaySubtitle, displayTitle, makePath, type Params, type ProcessAltNamesParam } from \"../../toolbox\";\nimport {\n buildSubjectAltNameString,\n cleanupStaticConfig,\n ensure_openssl_installed,\n execute_openssl,\n execute_openssl_no_failure,\n generateStaticConfig,\n type OpensslPassArg,\n passinArg,\n setEnv,\n x509Date\n} from \"../../toolbox/with_openssl\";\nimport type { CaBackend } from \"../core/ca_backend\";\nimport type { CertificateAuthorityCore } from \"../core/certificate_authority_core\";\n\nconst n = makePath;\n\n/** The ALTNAME openssl embeds as `subjectAltName` on the CA's own certificate/CSR — see `[v3_ca]` / `[v3_ca_req]`. */\nfunction caAltName(ca: CertificateAuthorityCore): string {\n // OPC UA validators (UaExpert, compliance tools) require every\n // certificate — including the root/intermediate CA — to carry a\n // SubjectAltName extension. RFC 5280 does not strictly mandate it\n // on CA certificates but the OPC UA Profile does. Build a stable\n // URI SAN derived from the CA CommonName so the resulting CA cert\n // passes the spec check.\n return `URI:urn:${ca.subject.commonName || \"NodeOPCUA-CA\"}`;\n}\n\n/**\n * Every render of `conf/caconfig.cnf` needs `ALTNAME` / `CDP_URL` /\n * `AIA_VALUE` resolved, **even for an `openssl` subcommand that only reads\n * a different section** (`ca -gencrl` only needs `[crl_ext]`, `ca -revoke`\n * only needs `[ca]`): openssl's config loader (`NCONF_load`) expands every\n * `$ENV::NAME` reference in the file line by line as it parses it, not\n * lazily per queried section, and every section in this template — not\n * just the two gated behind `{{#CDP_URL}}` / `{{#AIA_VALUE}}` — references\n * `$ENV::ALTNAME` unconditionally. Leaving any of the three unresolved\n * makes openssl fall through to its own native `$ENV::` resolution (a real\n * OS environment variable, which is never set) and fail with \"variable has\n * no value\".\n *\n * Passed explicitly rather than relying on whatever `setEnv()` last wrote\n * to the shared registry (see {@link generateStaticConfig}'s\n * `envOverrides`) — empty string means \"omit the extension\" for the two\n * gated keys (the template's `{{#KEY}}` block strips itself on an empty\n * value), never \"fall back to the registry\".\n *\n * Exported as the single implementation of the CDP/AIA value format:\n * `CertificateAuthority._wireRevocationEnvVars` (the legacy registry shim)\n * delegates here so the format cannot drift between the two mechanisms.\n */\nexport function caConfigEnvOverrides(ca: CertificateAuthorityCore, altName: string = caAltName(ca)): Record<string, string> {\n const aiaLegs: string[] = [];\n if (ca.ocspResponderUrl) {\n aiaLegs.push(`OCSP;URI:${ca.ocspResponderUrl}`);\n }\n if (ca.caIssuersUrl) {\n aiaLegs.push(`caIssuers;URI:${ca.caIssuersUrl}`);\n }\n return {\n ALTNAME: altName,\n CDP_URL: ca.crlDistributionUrl ?? \"\",\n AIA_VALUE: aiaLegs.join(\",\")\n };\n}\n\n/**\n * The default {@link CaBackend}: shells out to the `openssl` CLI, exactly as\n * `CertificateAuthority` always has — this is a pure code move (plus a lock\n * around every database-mutating operation, temp-config cleanup, and\n * explicit `envOverrides` on every config render) with no change in the\n * openssl commands issued or the files produced.\n */\nexport class OpenSslCaBackend implements CaBackend {\n /** This backend is the `openssl` executable, so it has to be there. */\n /**\n * `-passin env:` argv and env for an openssl call that has to load this\n * CA's key. Built here rather than on the CA: the passphrase is the\n * CA's business, but expressing it as an openssl argument is this\n * backend's, and the core has no reason to know the flag exists.\n */\n async #passin(ca: CertificateAuthorityCore): Promise<OpensslPassArg> {\n return passinArg(await ca._privateKeyPassphrase());\n }\n\n /** The openssl CLI loads its key from a file, so it cannot call out to an HSM. */\n public readonly supportsExternalSigner = false;\n\n public async preflight(): Promise<void> {\n await ensure_openssl_installed();\n }\n\n /**\n * Render `conf/caconfig.cnf` once with explicit overrides, run `fn`\n * with the rendered path, and always remove the temp file. Structural\n * guarantee that (a) every render carries the three required env\n * values and (b) no rendered `<name>.<pid>-<n>.tmp` file is ever left\n * behind — each was previously a per-method discipline.\n */\n async #withConfig<T>(\n ca: CertificateAuthorityCore,\n altName: string,\n fn: (configFile: string, options: { cwd: string }) => Promise<T>\n ): Promise<T> {\n const caRootDir = path.resolve(ca.rootDir);\n const options = { cwd: caRootDir };\n const configFile = generateStaticConfig(\"conf/caconfig.cnf\", options, caConfigEnvOverrides(ca, altName));\n try {\n return await fn(configFile, options);\n } finally {\n await cleanupStaticConfig(configFile, options);\n }\n }\n\n async #generateCaCsrWith(\n ca: CertificateAuthorityCore,\n configFile: string,\n options: { cwd: string },\n privateKeyFile: string,\n csrFile: string\n ): Promise<void> {\n const passin = await this.#passin(ca);\n displayTitle(\"Generate a certificate request for the CA key\");\n await execute_openssl(\n [\n \"req\",\n \"-new\",\n \"-sha256\",\n \"-extensions\",\n \"v3_ca_req\",\n \"-config\",\n n(configFile),\n \"-key\",\n n(privateKeyFile),\n \"-out\",\n n(csrFile),\n \"-subj\",\n ca.subject.toString(),\n ...passin.args\n ],\n { ...options, env: passin.env }\n );\n }\n\n /**\n * `openssl ca -gencrl` signs the CRL with the CA key it finds through the\n * config file (`private_key = $dir/private/cakey.pem`), so it needs the\n * CA passphrase like every other `openssl ca` invocation.\n */\n async #regenerateCrlWith(ca: CertificateAuthorityCore, configFile: string, options: { cwd: string }): Promise<void> {\n const passin = await this.#passin(ca);\n // produce a CRL in PEM format\n displaySubtitle(\"regenerate CRL (Certificate Revocation List)\");\n await execute_openssl([\"ca\", \"-gencrl\", \"-config\", n(configFile), \"-out\", \"crl/revocation_list.crl\", ...passin.args], {\n ...options,\n env: passin.env\n });\n await execute_openssl(\n [\"crl\", \"-in\", \"crl/revocation_list.crl\", \"-out\", \"crl/revocation_list.der\", \"-outform\", \"der\"],\n options\n );\n\n displaySubtitle(\"Display (Certificate Revocation List)\");\n await execute_openssl([\"crl\", \"-in\", n(ca.revocationList), \"-text\", \"-noout\"], options);\n }\n\n public async generateCaCsr(\n ca: CertificateAuthorityCore,\n _caRootDir: string,\n privateKeyFile: string,\n csrFile: string\n ): Promise<void> {\n await this.#withConfig(ca, caAltName(ca), (configFile, options) =>\n this.#generateCaCsrWith(ca, configFile, options, privateKeyFile, csrFile)\n );\n }\n\n public async bootstrap(ca: CertificateAuthorityCore): Promise<void> {\n const caRootDir = path.resolve(ca.rootDir);\n const privateKeyFilename = path.join(caRootDir, \"private/cakey.pem\");\n const csrFilename = path.join(caRootDir, \"private/cakey.csr\");\n\n // one render serves the CSR, the CA-certificate signature, and the\n // initial CRL (the overrides are identical for all three)\n await this.#withConfig(ca, caAltName(ca), async (configFile, options) => {\n await this.#generateCaCsrWith(ca, configFile, options, privateKeyFilename, csrFilename);\n\n const issuerCA = ca._issuerCA;\n if (issuerCA) {\n // Subordinate (intermediate) CA — signed by the parent CA\n displayTitle(\"Generate CA Certificate (signed by issuer CA)\");\n const issuerCert = path.resolve(issuerCA.caCertificate);\n const issuerKey = path.resolve(issuerCA.rootDir, \"private/cakey.pem\");\n const issuerSerial = path.resolve(issuerCA.rootDir, \"serial\");\n // the -CAkey is the *issuer's* key: its passphrase, not this CA's\n const issuerPassin = await this.#passin(issuerCA);\n const signWithIssuer = async () => {\n await execute_openssl(\n [\n \"x509\",\n \"-sha256\",\n \"-req\",\n \"-days\",\n \"3650\",\n \"-extensions\",\n \"v3_ca\",\n \"-extfile\",\n n(configFile),\n \"-in\",\n \"private/cakey.csr\",\n \"-CA\",\n n(issuerCert),\n \"-CAkey\",\n n(issuerKey),\n \"-CAserial\",\n n(issuerSerial),\n \"-out\",\n \"public/cacert.pem\",\n ...issuerPassin.args\n ],\n { ...options, env: issuerPassin.env }\n );\n };\n // `-CAserial` read-increment-writes the ISSUER's serial file,\n // so this must hold the issuer's directory lock, not just the\n // subordinate's (which the caller already holds). The only\n // cross-CA lock ordering in the codebase is subordinate ->\n // issuer, so this cannot deadlock — unless both CAs share one\n // rootDir (a degenerate configuration), where the lock is\n // already held and re-acquiring the non-reentrant file lock\n // would self-deadlock: skip it there.\n if (path.resolve(issuerCA.rootDir) === caRootDir) {\n await signWithIssuer();\n } else {\n await issuerCA._withCaDirectoryLock(signWithIssuer);\n }\n } else {\n // Root CA — self-signed\n displayTitle(\"Generate CA Certificate (self-signed)\");\n const passin = await this.#passin(ca);\n await execute_openssl(\n [\n \"x509\",\n \"-sha256\",\n \"-req\",\n \"-days\",\n \"3650\",\n \"-extensions\",\n \"v3_ca\",\n \"-extfile\",\n n(configFile),\n \"-in\",\n \"private/cakey.csr\",\n \"-signkey\",\n n(privateKeyFilename),\n \"-out\",\n \"public/cacert.pem\",\n ...passin.args\n ],\n { ...options, env: passin.env }\n );\n }\n\n displaySubtitle(\"generate initial CRL (Certificate Revocation List)\");\n await this.#regenerateCrlWith(ca, configFile, options);\n });\n displayTitle(\"Create Certificate Authority (CA) ---> DONE\");\n }\n\n public async regenerateCrl(ca: CertificateAuthorityCore): Promise<void> {\n await this.#withConfig(ca, caAltName(ca), (configFile, options) => this.#regenerateCrlWith(ca, configFile, options));\n }\n\n public async signSubordinateCsr(\n ca: CertificateAuthorityCore,\n csrFile: string,\n certFile: string,\n validityDays: number\n ): Promise<void> {\n // `[v3_ca]`'s subjectAltName should describe the *subordinate* being\n // certified, not `ca` (the issuer doing the signing) — but nothing\n // here parses `csrFile`'s own subject, so this reuses the issuer's\n // identity as a well-formed placeholder. This is a pre-existing gap,\n // not a regression: the original code left this value to whatever a\n // prior, unrelated operation had last set in the shared env\n // registry (an accidental \"URI:undefined\" or a stale value from a\n // different CA entirely), so this is deterministic where the\n // original was not, even though neither describes the subordinate.\n await this.#withConfig(ca, caAltName(ca), async (configFile, options) => {\n const caRootDir = options.cwd;\n const passin = await this.#passin(ca);\n await execute_openssl(\n [\n \"x509\",\n \"-sha256\",\n \"-req\",\n \"-days\",\n String(validityDays),\n \"-extensions\",\n \"v3_ca\",\n \"-extfile\",\n n(configFile),\n \"-in\",\n n(csrFile),\n \"-CA\",\n n(ca.caCertificate),\n \"-CAkey\",\n n(path.join(caRootDir, \"private/cakey.pem\")),\n \"-CAserial\",\n n(path.join(caRootDir, \"serial\")),\n \"-out\",\n n(certFile),\n ...passin.args\n ],\n { ...options, env: passin.env }\n );\n });\n }\n\n public async signEndEntityCsr(\n ca: CertificateAuthorityCore,\n certificate: string,\n csr: string,\n params1: Params,\n sanOverride: Required<ProcessAltNamesParam>\n ): Promise<void> {\n await this.#withConfig(ca, buildSubjectAltNameString(sanOverride), async (configFile, options) => {\n displaySubtitle(\"- then we ask the authority to sign the certificate signing request\");\n const passin = await this.#passin(ca);\n await execute_openssl(\n [\n \"ca\",\n \"-config\",\n configFile,\n \"-startdate\",\n x509Date(params1.startDate),\n \"-enddate\",\n x509Date(params1.endDate),\n \"-batch\",\n \"-out\",\n n(certificate),\n \"-in\",\n n(csr),\n ...passin.args\n ],\n { ...options, env: passin.env }\n );\n\n displaySubtitle(\"- dump the certificate for a check\");\n await execute_openssl([\"x509\", \"-in\", n(certificate), \"-dates\", \"-fingerprint\", \"-purpose\", \"-noout\"], options);\n });\n }\n\n public async revoke(ca: CertificateAuthorityCore, certificate: string, reason: string): Promise<void> {\n // one render serves the revocation and the CRL regeneration\n // openssl writes its entropy file here; the native backend has no such notion\n setEnv(\"RANDFILE\", path.join(ca.rootDir, \"random.rnd\"));\n await this.#withConfig(ca, caAltName(ca), async (configFile, options) => {\n displaySubtitle(\"Revoke certificate\");\n const passin = await this.#passin(ca);\n await execute_openssl_no_failure(\n [\"ca\", \"-verbose\", \"-config\", n(configFile), \"-revoke\", certificate, \"-crl_reason\", reason, ...passin.args],\n { ...options, env: passin.env }\n );\n\n // regenerate CRL (Certificate Revocation List)\n await this.#regenerateCrlWith(ca, configFile, options);\n\n displaySubtitle(\"Verify that certificate is revoked\");\n await execute_openssl_no_failure(\n [\n \"verify\",\n \"-verbose\",\n \"-CRLfile\",\n n(ca.revocationList),\n \"-CAfile\",\n n(ca.caCertificate),\n \"-crl_check\",\n n(certificate)\n ],\n options\n );\n\n // produce CRL in DER format\n displaySubtitle(\"Produce CRL in DER form \");\n await execute_openssl(\n [\"crl\", \"-in\", n(ca.revocationList), \"-out\", \"crl/revocation_list.der\", \"-outform\", \"der\"],\n options\n );\n // produce CRL in PEM format with text\n displaySubtitle(\"Produce CRL in PEM form \");\n await execute_openssl(\n [\"crl\", \"-in\", n(ca.revocationList), \"-out\", \"crl/revocation_list.pem\", \"-outform\", \"pem\", \"-text\"],\n options\n );\n });\n }\n\n public async createSelfSignedCertificate(\n ca: CertificateAuthorityCore,\n certificateFile: string,\n privateKeyFile: string,\n params: Params\n ): Promise<void> {\n // Explicit overrides like every other method: `$ENV::ALTNAME` in the\n // rendered config comes from THIS call's params, never from whatever\n // the shared env registry happened to hold — the registry-based\n // render made a concurrent operation's SANs (or an empty ALTNAME\n // from a concurrent revoke) leak into this certificate. CDP/AIA now\n // deterministically follow this CA's configured URLs as well.\n const envOverrides = caConfigEnvOverrides(ca, buildSubjectAltNameString(params));\n const configFile = generateStaticConfig(ca.configFile, { cwd: ca.rootDir }, envOverrides);\n const options = {\n cwd: ca.rootDir,\n openssl_conf: makePath(configFile)\n };\n\n try {\n const subject = params.subject ? new Subject(params.subject).toString() : \"\";\n const subjectOptions = subject && subject.length > 1 ? [\"-subj\", subject] : [];\n const csrFile = `${certificateFile}_csr`;\n\n // `req -new -key` reads (and, for an encrypted key, must decrypt)\n // privateKeyFile too: without -passin it hangs indefinitely\n // waiting on a passphrase prompt that never comes, even with\n // stdin redirected to /dev/null — unlike e.g. `pkcs12`/`rsa\n // -pubout`, which fail fast instead. Reproduced directly against\n // OpenSSL 3.5.4. Empty passin is a no-op against a plaintext key.\n const passin = await this.#passin(ca);\n\n displaySubtitle(\"- the certificate signing request\");\n await execute_openssl(\n [\n \"req\",\n \"-new\",\n \"-sha256\",\n ...subjectOptions,\n \"-batch\",\n \"-key\",\n n(privateKeyFile),\n \"-out\",\n n(csrFile),\n ...passin.args\n ],\n { ...options, env: passin.env }\n );\n\n displaySubtitle(\"- creating the self-signed certificate\");\n await execute_openssl(\n [\n \"ca\",\n \"-selfsign\",\n \"-keyfile\",\n n(privateKeyFile),\n \"-startdate\",\n x509Date(params.startDate),\n \"-enddate\",\n x509Date(params.endDate),\n \"-batch\",\n \"-out\",\n n(certificateFile),\n \"-in\",\n n(csrFile),\n ...passin.args\n ],\n { ...options, env: passin.env }\n );\n\n displaySubtitle(\"- dump the certificate for a check\");\n await execute_openssl([\"x509\", \"-in\", n(certificateFile), \"-dates\", \"-fingerprint\", \"-purpose\", \"-noout\"], {});\n\n displaySubtitle(\"- verify self-signed certificate\");\n await execute_openssl_no_failure([\"verify\", \"-verbose\", \"-CAfile\", n(certificateFile), n(certificateFile)], options);\n\n await fs.promises.unlink(csrFile);\n } finally {\n await cleanupStaticConfig(configFile, { cwd: ca.rootDir });\n }\n }\n}\n","const config =\n \"#.........DO NOT MODIFY BY HAND .........................\\n\" +\n \"[ ca ]\\n\" +\n \"default_ca = CA_default\\n\" +\n \"[ CA_default ]\\n\" +\n 'dir = \"%%ROOT_FOLDER%%\" # the main CA folder (quoted: see renderCaConfig)\\n' +\n \"certs = $dir/certs # where to store certificates\\n\" +\n \"new_certs_dir = $dir/certs #\\n\" +\n \"database = $dir/index.txt # the certificate database\\n\" +\n \"serial = $dir/serial # the serial number counter\\n\" +\n \"certificate = $dir/public/cacert.pem # The root CA certificate\\n\" +\n \"private_key = $dir/private/cakey.pem # the CA private key\\n\" +\n \"x509_extensions = usr_cert #\\n\" +\n \"default_days = 3650 # default validity : 10 years\\n\" +\n \"\\n\" +\n \"# default_md = sha1\\n\" +\n \"\\n\" +\n \"default_md = sha256 # The default digest algorithm\\n\" +\n \"\\n\" +\n \"preserve = no\\n\" +\n \"policy = policy_match\\n\" +\n \"# randfile = $dir/random.rnd\\n\" +\n \"# default_startdate = YYMMDDHHMMSSZ\\n\" +\n \"# default_enddate = YYMMDDHHMMSSZ\\n\" +\n \"crl_dir = $dir/crl\\n\" +\n \"crl_extensions = crl_ext\\n\" +\n \"crl = $dir/crl/revocation_list.crl # the Revocation list\\n\" +\n \"crlnumber = $dir/crlnumber # CRL number file\\n\" +\n \"default_crl_days = 30\\n\" +\n \"default_crl_hours = 24\\n\" +\n \"#msie_hack\\n\" +\n \"\\n\" +\n \"[ policy_match ]\\n\" +\n \"countryName = optional\\n\" +\n \"stateOrProvinceName = optional\\n\" +\n \"localityName = optional\\n\" +\n \"organizationName = optional\\n\" +\n \"organizationalUnitName = optional\\n\" +\n \"commonName = optional\\n\" +\n \"emailAddress = optional\\n\" +\n \"\\n\" +\n \"[ req ]\\n\" +\n \"default_bits = 4096 # Size of keys\\n\" +\n \"default_keyfile = key.pem # name of generated keys\\n\" +\n \"distinguished_name = req_distinguished_name\\n\" +\n \"attributes = req_attributes\\n\" +\n \"x509_extensions = v3_ca\\n\" +\n \"#input_password\\n\" +\n \"#output_password\\n\" +\n \"string_mask = nombstr # permitted characters\\n\" +\n \"req_extensions = v3_req\\n\" +\n \"\\n\" +\n \"[ req_distinguished_name ]\\n\" +\n \"\\n\" +\n \"#0 countryName = Country Name (2 letter code)\\n\" +\n \"# countryName_default = FR\\n\" +\n \"# countryName_min = 2\\n\" +\n \"# countryName_max = 2\\n\" +\n \"# stateOrProvinceName = State or Province Name (full name)\\n\" +\n \"# stateOrProvinceName_default = Ile de France\\n\" +\n \"# localityName = Locality Name (city, district)\\n\" +\n \"# localityName_default = Paris\\n\" +\n \"organizationName = Organization Name (company)\\n\" +\n \"organizationName_default = NodeOPCUA\\n\" +\n \"# organizationalUnitName = Organizational Unit Name (department, division)\\n\" +\n \"# organizationalUnitName_default = R&D\\n\" +\n \"commonName = Common Name (hostname, FQDN, IP, or your name)\\n\" +\n \"commonName_max = 256\\n\" +\n \"commonName_default = NodeOPCUA\\n\" +\n \"# emailAddress = Email Address\\n\" +\n \"# emailAddress_max = 40\\n\" +\n \"# emailAddress_default = node-opcua (at) node-opcua (dot) com\\n\" +\n \"\\n\" +\n \"[ req_attributes ]\\n\" +\n \"#challengePassword = A challenge password\\n\" +\n \"#challengePassword_min = 4\\n\" +\n \"#challengePassword_max = 20\\n\" +\n \"#unstructuredName = An optional company name\\n\" +\n \"[ usr_cert ]\\n\" +\n \"basicConstraints = critical, CA:FALSE\\n\" +\n \"subjectKeyIdentifier = hash\\n\" +\n \"authorityKeyIdentifier = keyid,issuer:always\\n\" +\n \"#authorityKeyIdentifier = keyid\\n\" +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n \"# issuerAltName = issuer:copy\\n\" +\n \"nsComment = ''OpenSSL Generated Certificate''\\n\" +\n \"#nsCertType = client, email, objsign for ''everything including object signing''\\n\" +\n \"#nsCaRevocationUrl = http://www.domain.dom/ca-crl.pem\\n\" +\n \"#nsBaseUrl =\\n\" +\n \"#nsRenewalUrl =\\n\" +\n \"#nsCaPolicyUrl =\\n\" +\n \"#nsSslServerName =\\n\" +\n \"keyUsage = critical, digitalSignature, nonRepudiation,\" +\n \" keyEncipherment, dataEncipherment, keyAgreement\\n\" +\n \"extendedKeyUsage = critical,serverAuth ,clientAuth\\n\" +\n // Opt-in CRL Distribution Points and Authority Information Access.\n // Emitted only when CertificateAuthority.setCrlDistributionUrl /\n // setOcspResponderUrl / setCaIssuersUrl have been called — the\n // conditional blocks are stripped by generateStaticConfig() when\n // the matching env var is unset. See US-202.\n \"{{#CDP_URL}}crlDistributionPoints = URI:$ENV::CDP_URL\\n{{/CDP_URL}}\" +\n \"{{#AIA_VALUE}}authorityInfoAccess = $ENV::AIA_VALUE\\n{{/AIA_VALUE}}\" +\n \"\\n\" +\n \"[ v3_req ]\\n\" +\n \"basicConstraints = critical, CA:FALSE\\n\" +\n \"keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, keyAgreement\\n\" +\n \"extendedKeyUsage = critical,serverAuth ,clientAuth\\n\" +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n 'nsComment = \"CA Generated by Node-OPCUA Certificate utility using openssl\"\\n' +\n \"[ v3_ca_req ]\\n\" +\n // -----------------------------------------------------------------------\n // v3_ca_req is used ONLY during the CSR step (`openssl req -new\n // -extensions v3_ca_req`). At that stage no issuer certificate\n // exists yet (we are bootstrapping the root CA), so we must NOT\n // include `authorityKeyIdentifier` here.\n //\n // OpenSSL 3.5.x (Alpine) rejects *any* authorityKeyIdentifier\n // value during CSR generation — even plain `keyid` — because\n // v3_akid.c unconditionally looks for an issuer certificate:\n //\n // v3_akid.c:156: no issuer certificate\n //\n // The authorityKeyIdentifier is properly added during the\n // self-signing step (`openssl x509 -req -extensions v3_ca`)\n // where the issuer key is available.\n //\n // Tested with:\n // - OpenSSL 3.0.x (Ubuntu) — works\n // - OpenSSL 3.4.1 (Windows) — works\n // - OpenSSL 3.5.5 (Alpine) — works (only with this fix)\n //\n // References:\n // - https://github.com/openssl/openssl/issues/21519\n // - OpenSSL man x509v3_config(5) – authorityKeyIdentifier\n // -----------------------------------------------------------------------\n \"subjectKeyIdentifier = hash\\n\" +\n \"basicConstraints = CA:TRUE\\n\" +\n \"keyUsage = critical, cRLSign, keyCertSign\\n\" +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n 'nsComment = \"CA CSR generated by Node-OPCUA Certificate utility using openssl\"\\n' +\n \"[ v3_ca ]\\n\" +\n \"subjectKeyIdentifier = hash\\n\" +\n \"authorityKeyIdentifier = keyid:always,issuer:always\\n\" +\n \"basicConstraints = CA:TRUE\\n\" +\n \"keyUsage = critical, cRLSign, keyCertSign\\n\" +\n // OPC UA validators (UaExpert, ANSI compliance tools) flag a missing\n // SubjectAltName on the CA cert. Pull it from the ALTNAME env var\n // populated by construct_CertificateAuthority.\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n 'nsComment = \"CA Certificate generated by Node-OPCUA Certificate utility using openssl\"\\n' +\n \"#nsCertType = sslCA, emailCA\\n\" +\n \"#issuerAltName = issuer:copy\\n\" +\n \"#obj = DER:02:03\\n\" +\n // Opt-in CDP / AIA on the CA cert itself (US-202). Previously a\n // hardcoded http://localhost:8900/crl.pem was emitted unconditionally\n // — which produced broken certs in any deployment outside dev.\n \"{{#CDP_URL}}crlDistributionPoints = URI:$ENV::CDP_URL\\n{{/CDP_URL}}\" +\n \"{{#AIA_VALUE}}authorityInfoAccess = $ENV::AIA_VALUE\\n{{/AIA_VALUE}}\" +\n \"[ v3_selfsigned]\\n\" +\n \"basicConstraints = critical, CA:FALSE\\n\" +\n \"keyUsage = nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, keyAgreement\\n\" +\n \"extendedKeyUsage = critical,serverAuth ,clientAuth\\n\" +\n 'nsComment = \"Self-signed certificate, generated by NodeOPCUA\"\\n' +\n \"subjectAltName = $ENV::ALTNAME\\n\" +\n \"\\n\" +\n \"[ crl_ext ]\\n\" +\n \"#issuerAltName = issuer:copy\\n\" +\n \"authorityKeyIdentifier = keyid:always,issuer:always\\n\" +\n \"#authorityInfoAccess = @issuer_info\";\n\nexport default config;\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\nimport assert from \"node:assert\";\nimport fs from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { withLock } from \"@ster5/global-mutex\";\nimport chalk from \"chalk\";\nimport {\n type CaSigner,\n CertificatePurpose,\n certificateMatchesPrivateKey,\n convertPEMtoDER,\n createCertificateSigningRequest,\n createPfx,\n exploreCertificate,\n exploreCertificateSigningRequest,\n generatePrivateKeyFile,\n type PrivateKey,\n privateKeyToCryptoKey,\n readCertificatePEM,\n readCertificateSigningRequest,\n readPrivateKey,\n Subject,\n type SubjectOptions,\n toPem,\n verifyCertificateSignature,\n writePrivateKeyFile,\n x509\n} from \"node-opcua-crypto\";\nimport {\n adjustApplicationUri,\n adjustDate,\n certificateFileExist,\n debugLog,\n displaySubtitle,\n displayTitle,\n ensurePrivateDirectory,\n type Filename,\n isEncryptedPrivateKeyFile,\n type KeySize,\n makePath,\n mkdirRecursiveSync,\n type Params,\n type PrivateKeyPassphrase,\n type ProcessAltNamesParam,\n resolvePrivateKeyPassphrase,\n restrictPrivateFilePermissions,\n warningLog\n} from \"../../toolbox\";\nimport type { CaBackend } from \"./ca_backend\";\nimport { CaDatabase, type IssuedCertificateRecord } from \"./ca_database\";\n\n/** Default X.500 subject used when no custom subject is provided. */\nexport const defaultSubject = \"/C=FR/ST=IDF/L=Paris/O=Local NODE-OPCUA Certificate Authority/CN=NodeOPCUA-CA\";\n\nimport _ca_config_template from \"../templates/ca_config_template.cnf\";\n\nexport const configurationFileTemplate: string = _ca_config_template;\n\n/**\n * Escape a value for use inside a double-quoted openssl config value.\n *\n * openssl's config parser (crypto/conf/conf_def.c) treats an unquoted value\n * specially: `$var` / `${var}` / `$(var)` are expanded, and `'`, `\"` and the\n * backtick are all quote characters (a backtick pair is silently removed).\n * Inside a double-quoted value none of that applies: characters are copied\n * verbatim except a backslash, which escapes the next character. So a path\n * containing `$`, backticks, `#` or spaces is safe once double-quoted with\n * `\\` and `\"` escaped.\n */\nexport function escapeOpensslConfDoubleQuoted(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Render the CA openssl configuration for `caRootDir`. The root folder is\n * emitted forward-slashed (openssl accepts that on every platform) and\n * double-quoted, so a CA `location` containing characters that openssl's\n * config syntax would otherwise interpret (`$`, backticks, `#`, quotes) is\n * taken literally.\n */\nexport function renderCaConfig(caRootDir: string): string {\n return configurationFileTemplate.replace(/%%ROOT_FOLDER%%/, escapeOpensslConfDoubleQuoted(makePath(caRootDir)));\n}\n\nconst config = {\n certificateDir: \"INVALID\",\n forceCA: false,\n pkiDir: \"INVALID\"\n};\n\n/**\n * Upper bound on how long a CA operation waits for `.ca.lock` before\n * throwing. CA operations themselves complete in seconds; a dead holder's\n * lock goes stale and is taken over after ~2 minutes, so 5 minutes covers\n * every legitimate wait with margin while still turning a stuck holder\n * into a loud error instead of a silent fleet-wide hang.\n */\nconst CA_LOCK_MAX_WAIT_MS = 5 * 60_000;\n\n/**\n * How long a waiter sleeps between attempts at the CA directory lock.\n * The lock library's default backoff doubles without an upper bound, so a\n * queue of contending operations ends up sleeping through 1s, 2s, 4s, 8s,\n * 16s ... while the lock is in fact free again after milliseconds: eight\n * queued signings measured over two minutes. Capping the interval keeps a\n * freed lock from going unnoticed; `CA_LOCK_MAX_WAIT_MS` still bounds the\n * total wait.\n */\nconst CA_LOCK_RETRY = { minTimeout: 20, maxTimeout: 250 };\n\n// convert 'c07b9179' to \"192.123.145.121\"\nfunction octetStringToIpAddress(a: string) {\n return (\n parseInt(a.substring(0, 2), 16).toString() +\n \".\" +\n parseInt(a.substring(2, 4), 16).toString() +\n \".\" +\n parseInt(a.substring(4, 6), 16).toString() +\n \".\" +\n parseInt(a.substring(6, 8), 16).toString()\n );\n}\nassert(octetStringToIpAddress(\"c07b9179\") === \"192.123.145.121\");\n\n/**\n * Result of {@link CertificateAuthority.initializeCSR}.\n *\n * - `\"ready\"` — the CA certificate already exists and is valid.\n * - `\"pending\"` — key + CSR exist but no cert; waiting for external signing.\n * - `\"created\"` — a fresh key + CSR were just generated.\n * - `\"expired\"` — the CA certificate has expired (or will expire within\n * the configured threshold). A new CSR has been generated for renewal\n * while preserving the existing private key.\n */\nexport type InitializeCSRResult =\n | { status: \"ready\" }\n | { status: \"pending\"; csrPath: string }\n | { status: \"created\"; csrPath: string }\n | { status: \"expired\"; csrPath: string; expiryDate: Date };\n\n/**\n * Result of {@link CertificateAuthority.installCACertificate}.\n *\n * - `\"success\"` — the certificate was installed and CRL generated.\n * - `\"error\"` — the certificate was rejected (see `reason`).\n */\nexport type InstallCACertificateResult = { status: \"success\" } | { status: \"error\"; reason: string; message: string };\n\n/**\n * Options for creating a {@link CertificateAuthority}.\n */\nexport interface CertificateAuthorityCoreOptions {\n /** RSA key size for the CA private key. */\n keySize: KeySize;\n /** Filesystem path where the CA directory structure is stored. */\n location: string;\n /**\n * X.500 subject for the CA certificate.\n * Accepts a slash-delimited string (e.g. `\"/CN=My CA/O=Acme\"`) or\n * a structured {@link SubjectOptions} object.\n *\n * @defaultValue {@link defaultSubject}\n */\n subject?: string | SubjectOptions;\n /**\n * Parent CA that will sign this CA's certificate.\n * If omitted, the CA is self-signed (root CA).\n * The parent CA must be initialized before this CA.\n */\n issuerCA?: CertificateAuthorityCore;\n /**\n * Public URL (http/https) where the CRL produced by this CA is\n * reachable. When set, every issued certificate carries an\n * X.509v3 `crlDistributionPoints` extension pointing at this URL.\n *\n * Leave undefined to omit the extension entirely (opt-in — see\n * US-202). Validated synchronously at construction / setter call.\n */\n crlDistributionUrl?: string;\n /**\n * Public URL of the OCSP responder. When set, every issued cert\n * carries an `authorityInfoAccess` extension with an `OCSP` leg\n * pointing at this URL. Leave undefined to omit (US-202).\n */\n ocspResponderUrl?: string;\n /**\n * Public URL where the issuer's certificate can be fetched.\n * When set, the `authorityInfoAccess` extension on every issued\n * cert carries a `caIssuers` leg pointing at this URL (chain\n * repair). Leave undefined to omit (US-202).\n */\n caIssuersUrl?: string;\n /**\n * Encrypt the CA private key (`private/cakey.pem`) at rest with this\n * passphrase (opt-in, default off). When set:\n * - a freshly generated CA key is written as encrypted PKCS#8;\n * - an existing *plaintext* CA key is encrypted in place by\n * {@link CertificateAuthority.initialize} / `initializeCSR()`;\n * - every `openssl` invocation that loads the CA key (CSR, self-sign,\n * sign, revoke, CRL generation) receives it via `-passin env:`, never\n * in argv; a missing or wrong passphrase fails `initialize()` closed.\n *\n * A function is called at most once per instance; the resolved\n * passphrase is kept in memory for the instance's lifetime because the\n * CA hands it to each openssl child. Never logged.\n *\n * A subordinate CA (`issuerCA` set) uses the *issuer's* passphrase for\n * the issuer's key: construct the parent with its own option.\n */\n privateKeyPassphrase?: PrivateKeyPassphrase;\n /**\n * Who actually signs, and writes the certificate database. Supplying it\n * is the whole point of this class: nothing here names a concrete\n * backend, so a program that only ever uses the native one never\n * references - and never has to ship - the openssl one.\n *\n * {@link CertificateAuthority} is the batteries-included subclass that\n * picks a backend for you from a `\"openssl\" | \"native\"` option.\n */\n backend: CaBackend;\n /**\n * Sign with an external key that never leaves its holder - an HSM or a\n * cloud KMS - instead of `private/cakey.pem`. The signer exposes only\n * `getPublicKey()` and `sign(tbs)`; this class builds the to-be-signed\n * bytes locally and asks the signer for the signature.\n *\n * Setting this implies `backend: \"native\"` (the openssl CLI can only\n * load a key from a file, so it cannot honour a signer); combining it\n * with an explicit `backend: \"openssl\"` is a constructor error. No\n * `private/cakey.pem` is generated, and the key-file operations that\n * cannot apply - {@link CertificateAuthority.getPrivateKey} and\n * {@link CertificateAuthority.reencryptPrivateKey} - throw.\n */\n signer?: CaSigner;\n}\n\n/**\n * An OpenSSL-based Certificate Authority (CA) that can create,\n * sign, and revoke X.509 certificates.\n *\n * The CA maintains a standard OpenSSL directory layout under\n * {@link CertificateAuthority.rootDir | rootDir}:\n *\n * ```\n * <location>/\n * ├── conf/ OpenSSL configuration\n * ├── private/ CA private key (cakey.pem)\n * ├── public/ CA certificate (cacert.pem)\n * ├── certs/ Signed certificates\n * ├── crl/ Revocation lists\n * ├── serial Next serial number\n * ├── crlnumber Next CRL number\n * └── index.txt Certificate database\n * ```\n *\n * @example\n * ```ts\n * const ca = new CertificateAuthority({\n * keySize: 2048,\n * location: \"/var/pki/CA\"\n * });\n * await ca.initialize();\n * ```\n */\n\n// ---------------------------------------------------------------\n// Certificate database types (US-057)\n// ---------------------------------------------------------------\n\nexport type { IssuedCertificateRecord };\n\n/**\n * Options for {@link CertificateAuthority.signCertificateRequestFromDER}.\n *\n * All fields are optional. When provided, they override the\n * corresponding values from the CSR.\n */\nexport interface SignCertificateOptions {\n /** Certificate validity in days (default: 365). */\n validity?: number;\n /**\n * Certificate validity in milliseconds.\n *\n * When provided, takes precedence over {@link validity} and enables\n * sub-day validity (e.g. 10-minute certificates for renewal demos).\n */\n validityMs?: number;\n /** Override the certificate start date. */\n startDate?: Date;\n /** Override DNS SANs. */\n dns?: string[];\n /** Override IP SANs. */\n ip?: string[];\n /** Override the application URI SAN. */\n applicationUri?: string;\n /** Override the X.500 subject. */\n subject?: SubjectOptions | string;\n}\n\n/**\n * Capabilities advertised by a PKI backend (or by this\n * {@link CertificateAuthority}) so consumers can clamp requested\n * validity to the limits the backend can actually honor.\n *\n * Useful for the GDS Pull / Push management flows, where the CA may\n * be supplied by an external service (step-ca, EJBCA, …) with its\n * own minimum / maximum / granularity constraints.\n *\n * @see CertificateAuthority.getCapabilities\n */\nexport interface PkiBackendCapabilities {\n /** Smallest validity this backend can issue, in milliseconds. */\n minValidityMs: number;\n /** Largest validity this backend will issue, in milliseconds. */\n maxValidityMs: number;\n /**\n * Validity is rounded up to the nearest multiple of this many\n * milliseconds. For `node-opcua-pki`'s OpenSSL-based CA this is\n * 1 000 ms (one second — the X.509 floor per RFC 5280 §4.1.2.5).\n */\n validityGranularityMs: number;\n /**\n * Native unit the backend works in. Diagnostic only — callers\n * always pass `validityMs` (US-208 / US-210).\n */\n nativeUnit: \"second\" | \"minute\" | \"hour\" | \"day\";\n}\n\n/**\n * Options for {@link CertificateAuthority.generateKeyPairAndSignDER}.\n */\nexport interface GenerateKeyPairAndSignOptions {\n /** OPC UA application URI (required). */\n applicationUri: string;\n /** X.500 subject for the certificate (e.g. \"CN=MyApp\"). */\n subject?: SubjectOptions | string;\n /** DNS host names for the SAN extension. */\n dns?: string[];\n /** IP addresses for the SAN extension. */\n ip?: string[];\n /** Certificate validity in days (default: 365). */\n validity?: number;\n /**\n * Certificate validity in milliseconds.\n *\n * When provided, takes precedence over {@link validity} and enables\n * sub-day validity (e.g. 10-minute certificates for renewal demos).\n */\n validityMs?: number;\n /** Certificate start date (default: now). */\n startDate?: Date;\n /** RSA key size in bits (default: 2048). */\n keySize?: KeySize;\n}\n\n/**\n * Options for {@link CertificateAuthority.generateKeyPairAndSignPFX}.\n *\n * Extends the DER options with an optional `passphrase` to protect\n * the PFX bundle.\n */\nexport interface GenerateKeyPairAndSignPFXOptions extends GenerateKeyPairAndSignOptions {\n /**\n * Passphrase to protect the PFX file.\n * If omitted, the PFX is created without a password.\n */\n passphrase?: string;\n}\n\n/**\n * Synchronously validate a revocation-related URL (CDP / OCSP /\n * caIssuers) before it is stored on a {@link CertificateAuthority}.\n *\n * Rules:\n * - `undefined` is a valid input — the matching extension is omitted.\n * - Empty string throws (almost always a config bug — pass `undefined`).\n * - Must parse via `new URL(s)`.\n * - Protocol must be `http:` or `https:`.\n * - Must include a non-trivial path (not `\"\"` or `\"/\"`).\n * - Loopback hostname produces a warning but does not throw — useful\n * for tests and local dev where pki-server and relying party share\n * a host.\n *\n * @see US-202\n */\nfunction validateRevocationUrl(url: string | undefined, fieldName: string): string | undefined {\n if (url === undefined) {\n return undefined;\n }\n if (url === \"\") {\n throw new Error(`${fieldName} must not be empty — pass undefined to disable the extension`);\n }\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new Error(`${fieldName} is not a valid URL: ${url}`);\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n throw new Error(`${fieldName} must use http: or https: (got ${parsed.protocol} in ${url})`);\n }\n if (!parsed.pathname || parsed.pathname === \"/\") {\n throw new Error(`${fieldName} must include a path component (got ${url})`);\n }\n const isLoopback = parsed.hostname === \"localhost\" || parsed.hostname === \"::1\" || parsed.hostname.startsWith(\"127.\");\n if (isLoopback) {\n console.warn(\n `[node-opcua-pki] ${fieldName} points at loopback (${url}) — ` +\n \"certificates issued with this URL will be unreachable from any other host.\"\n );\n }\n return url;\n}\n\nexport class CertificateAuthorityCore {\n /** RSA key size used when generating the CA private key. */\n public readonly keySize: KeySize;\n /** Root filesystem path of the CA directory structure. */\n public readonly location: string;\n /** X.500 subject of the CA certificate. */\n public readonly subject: Subject;\n\n /** @internal Parent CA (undefined for root CAs). */\n readonly _issuerCA?: CertificateAuthorityCore;\n\n /** @internal Configured CDP / AIA URLs (US-202). */\n private _crlDistributionUrl?: string;\n private _ocspResponderUrl?: string;\n private _caIssuersUrl?: string;\n\n readonly #privateKeyPassphrase?: PrivateKeyPassphrase;\n /** resolved once (see `privateKeyPassphrase`); `#passphraseResolved` distinguishes \"none\" from \"not yet\" */\n #resolvedPassphrase?: string;\n #passphraseResolved = false;\n\n /** Signing backend: `openssl` shells out to the CLI, `native` signs in-process. */\n readonly #backend: CaBackend;\n /** External signing key (HSM/KMS), when one was supplied instead of a key file. */\n readonly #signer?: CaSigner;\n /** Read access to `index.txt` / `certs/<SERIAL>.pem`. */\n readonly #db: CaDatabase;\n\n constructor(options: CertificateAuthorityCoreOptions) {\n assert(Object.prototype.hasOwnProperty.call(options, \"location\"));\n assert(Object.prototype.hasOwnProperty.call(options, \"keySize\"));\n this.location = options.location;\n this.keySize = options.keySize || 2048;\n this.subject = new Subject(options.subject || defaultSubject);\n this._issuerCA = options.issuerCA;\n this.#privateKeyPassphrase = options.privateKeyPassphrase;\n this.#signer = options.signer;\n if (options.signer) {\n // Refuse a signer nothing can use here, where the message can say\n // what is wrong with it, rather than letting it surface as a\n // normalize-algorithm error thrown from inside WebCrypto once the\n // CA directory already exists. The type system says as much for\n // TypeScript callers, but a signer is exactly the sort of object\n // that arrives from untyped glue around a KMS SDK.\n const algorithm = options.signer.algorithm;\n if (algorithm.name !== \"RSASSA-PKCS1-v1_5\" && algorithm.name !== \"ECDSA\") {\n throw new Error(\n `CertificateAuthority: signer algorithm ${(algorithm as { name: string }).name} is not supported - ` +\n \"use RSASSA-PKCS1-v1_5 or ECDSA.\"\n );\n }\n if (algorithm.name === \"ECDSA\" && !algorithm.namedCurve) {\n throw new Error(\n \"CertificateAuthority: an ECDSA signer must declare its namedCurve (P-256, P-384 or P-521) - \" +\n \"importing the signer's public key needs the curve, and an SPKI import cannot infer it.\"\n );\n }\n }\n if (options.signer && !options.backend.supportsExternalSigner) {\n // asked of the backend rather than hardcoded here, so this class\n // keeps working for backends it has never heard of\n throw new Error(\n \"CertificateAuthority: this backend cannot sign with an external signer - \" +\n \"it loads its key from a file. Use a backend that supports one, such as NativeCaBackend.\"\n );\n }\n this.#backend = options.backend;\n this.#db = new CaDatabase(this.location);\n if (options.crlDistributionUrl !== undefined) {\n this.setCrlDistributionUrl(options.crlDistributionUrl);\n }\n if (options.ocspResponderUrl !== undefined) {\n this.setOcspResponderUrl(options.ocspResponderUrl);\n }\n if (options.caIssuersUrl !== undefined) {\n this.setCaIssuersUrl(options.caIssuersUrl);\n }\n }\n\n /**\n * Public URL where the CRL produced by this CA is reachable, or\n * `undefined` if no CDP extension should be emitted on issued certs.\n */\n public get crlDistributionUrl(): string | undefined {\n return this._crlDistributionUrl;\n }\n\n /**\n * Public URL of the OCSP responder, or `undefined` if no AIA OCSP\n * leg should be emitted on issued certs.\n */\n public get ocspResponderUrl(): string | undefined {\n return this._ocspResponderUrl;\n }\n\n /**\n * Public URL where the issuer's certificate can be fetched, or\n * `undefined` if no AIA caIssuers leg should be emitted.\n */\n public get caIssuersUrl(): string | undefined {\n return this._caIssuersUrl;\n }\n\n /**\n * Configure the URL embedded as `crlDistributionPoints` in every\n * subsequently-issued certificate. Pass `undefined` to disable\n * the extension entirely. Validated synchronously — throws on\n * empty string, non-http(s) protocol, missing path. Warns (does\n * not throw) when the URL points at loopback.\n *\n * @see US-202\n */\n public setCrlDistributionUrl(url: string | undefined): void {\n this._crlDistributionUrl = validateRevocationUrl(url, \"crlDistributionUrl\");\n }\n\n /**\n * Configure the OCSP responder URL embedded as the `OCSP` leg of\n * the `authorityInfoAccess` extension on every subsequently-issued\n * certificate. Pass `undefined` to disable.\n *\n * @see US-202\n */\n public setOcspResponderUrl(url: string | undefined): void {\n this._ocspResponderUrl = validateRevocationUrl(url, \"ocspResponderUrl\");\n }\n\n /**\n * Configure the caIssuers URL embedded as the `caIssuers` leg of\n * the `authorityInfoAccess` extension on every subsequently-issued\n * certificate. Pass `undefined` to disable.\n *\n * @see US-202\n */\n public setCaIssuersUrl(url: string | undefined): void {\n this._caIssuersUrl = validateRevocationUrl(url, \"caIssuersUrl\");\n }\n\n /** Absolute path to the CA root directory (alias for {@link location}). */\n public get rootDir() {\n return this.location;\n }\n\n /** Path to the OpenSSL configuration file (`conf/caconfig.cnf`). */\n public get configFile() {\n return path.normalize(path.join(this.rootDir, \"./conf/caconfig.cnf\"));\n }\n\n /** Path to the CA private key (`private/cakey.pem`); may be passphrase-encrypted, see {@link getPrivateKey}. */\n public get privateKey() {\n return path.join(path.resolve(this.rootDir), \"private/cakey.pem\");\n }\n\n /**\n * The CA private key, decrypted with the configured `privateKeyPassphrase`\n * if it is encrypted. Fails closed (`PrivateKeyPassphraseRequiredError`)\n * on an encrypted key with no or the wrong passphrase.\n */\n public async getPrivateKey(): Promise<PrivateKey> {\n this.#assertKeyIsOnDisk(\"getPrivateKey\");\n return readPrivateKey(this.privateKey, await this._privateKeyPassphrase());\n }\n\n /**\n * True when this CA signs with an external {@link CaSigner} (HSM/KMS)\n * rather than with `private/cakey.pem`. There is then no private key\n * file on disk, and never was one.\n */\n public get hasExternalSigner(): boolean {\n return this.#signer !== undefined;\n }\n\n /**\n * Does `cert` certify the key this CA signs with? With the key on disk\n * that is a private-key match; with a signer there is no private key to\n * match, so compare the certified public key against the signer's own -\n * the same question, asked the only way an HSM allows.\n */\n async #certificateMatchesOurKey(certPem: string, certDer: Buffer): Promise<boolean> {\n if (this.#signer) {\n const ours = Buffer.from(await this.#signer.getPublicKey());\n const certified = Buffer.from(new x509.X509Certificate(certPem).publicKey.rawData);\n return ours.equals(certified);\n }\n return certificateMatchesPrivateKey(certDer, await this.getPrivateKey());\n }\n\n /** Reject the key-file-only operations up front, rather than failing on a missing file later. */\n #assertKeyIsOnDisk(what: string): void {\n if (this.#signer) {\n throw new Error(\n `CertificateAuthority.${what} is not available on a signer-backed CA: ` +\n \"the private key lives in the signer (HSM/KMS) and is never written to disk.\"\n );\n }\n }\n\n /**\n * @internal The key every signing operation goes through. An injected\n * {@link CaSigner} is returned as-is; otherwise the on-disk key is read\n * (and decrypted) and handed over as a plain `CryptoKey`. Both are\n * accepted by the `node-opcua-crypto` signing primitives, so callers\n * never branch on which one they got.\n */\n public async _getSigningKey(): Promise<CryptoKey | CaSigner> {\n if (this.#signer) {\n return this.#signer;\n }\n return privateKeyToCryptoKey(await this.getPrivateKey());\n }\n\n /**\n * Enable, disable, or rotate the passphrase protecting `private/cakey.pem`\n * (temp file + atomic rename, temp file removed on failure). Only\n * rewrites the file: construct a new `CertificateAuthority` with the new\n * passphrase to continue using it.\n */\n public async reencryptPrivateKey(oldPassphrase?: PrivateKeyPassphrase, newPassphrase?: PrivateKeyPassphrase): Promise<void> {\n this.#assertKeyIsOnDisk(\"reencryptPrivateKey\");\n const oldPass = await resolvePrivateKeyPassphrase(oldPassphrase);\n const newPass = await resolvePrivateKeyPassphrase(newPassphrase);\n const key = readPrivateKey(this.privateKey, oldPass);\n await this.#rewritePrivateKeyFile(key, newPass);\n }\n\n async #rewritePrivateKeyFile(privateKey: PrivateKey, passphrase: string | undefined): Promise<void> {\n const tmpFilename = `${this.privateKey}.${process.pid}-${Date.now()}.tmp`;\n try {\n await writePrivateKeyFile(tmpFilename, privateKey, { passphrase });\n await fs.promises.rename(tmpFilename, this.privateKey);\n } finally {\n await fs.promises.rm(tmpFilename, { force: true });\n }\n }\n\n /** @internal resolve the configured passphrase, at most once per instance */\n public async _privateKeyPassphrase(): Promise<string | undefined> {\n if (!this.#passphraseResolved) {\n this.#resolvedPassphrase = await resolvePrivateKeyPassphrase(this.#privateKeyPassphrase);\n this.#passphraseResolved = true;\n }\n return this.#resolvedPassphrase;\n }\n\n /**\n * @internal On an existing key: encrypt it in place if a passphrase is\n * configured and it is still plaintext (secure by default: the option\n * means \"protect this key\", not \"ignore me\"), then read it back so a\n * wrong or missing passphrase fails initialize() closed rather than the\n * first signing operation.\n */\n public async _ensurePrivateKeyProtection(): Promise<void> {\n if (this.#signer || !fs.existsSync(this.privateKey)) {\n return;\n }\n if (this.#privateKeyPassphrase !== undefined && !isEncryptedPrivateKeyFile(this.privateKey)) {\n warningLog(\"CertificateAuthority: private key is plaintext but a passphrase is configured; encrypting it in place\");\n const plaintextKey = readPrivateKey(this.privateKey);\n await this.#rewritePrivateKeyFile(plaintextKey, await this._privateKeyPassphrase());\n }\n await this.getPrivateKey();\n }\n\n /**\n * Acquire a file-based lock on this CA's directory for the duration of\n * `action` — serializes every operation that mutates the certificate\n * database (`index.txt`, `serial`, `crlnumber`, `certs/`,\n * `crl/revocation_list.*`) or the CA's own key/certificate, so\n * concurrent calls on one `CertificateAuthority` (or two instances\n * pointed at the same directory, in this or another process) cannot\n * interleave. Mirrors `CertificateManager.withLock2`.\n *\n * Only ever call this from a top-level public operation — nested calls\n * on the same instance would deadlock, since the underlying file lock\n * is not reentrant.\n *\n * The wait is bounded: a waiter gives up (throws) after\n * `CA_LOCK_MAX_WAIT_MS`. Without a bound, a holder whose openssl child\n * hangs would block every CA operation in every process forever and\n * silently — the lock library's keepalive keeps refreshing the lock\n * file's mtime as long as the holder process is alive, so stale-lock\n * recovery never fires for a live-but-stuck holder. A dead holder's\n * lock goes stale (default 2 minutes) and is taken over well within\n * this bound.\n */\n async #withCaLock<T>(action: () => Promise<T>): Promise<T> {\n const lockFileName = path.join(this.rootDir, \".ca.lock\");\n return withLock<T>(\n {\n fileToLock: lockFileName,\n retries: { forever: true, maxRetryTime: CA_LOCK_MAX_WAIT_MS, ...CA_LOCK_RETRY }\n },\n action\n );\n }\n\n /**\n * @internal Run `action` under this CA's directory lock. For the one\n * legitimate cross-instance use: a subordinate CA's bootstrap signs its\n * certificate with `openssl x509 -CAserial`, which read-increment-writes\n * THIS issuer's `serial` file, and must therefore hold this issuer's\n * lock (ordering is always subordinate -> issuer, so no cycle).\n */\n public async _withCaDirectoryLock<T>(action: () => Promise<T>): Promise<T> {\n return this.#withCaLock(action);\n }\n\n /** Path to the CA certificate in PEM format (`public/cacert.pem`). */\n public get caCertificate() {\n // the Certificate Authority Certificate\n return makePath(this.rootDir, \"./public/cacert.pem\");\n }\n\n /**\n * Path to the issuer certificate chain (`public/issuer_chain.pem`).\n *\n * This file is created by {@link installCACertificate} when the\n * provided cert file contains additional issuer certificates\n * (e.g. intermediate + root). It is appended to signed certs\n * by {@link constructCertificateChain} to produce a full chain\n * per OPC UA Part 6 §6.2.6.\n */\n public get issuerCertificateChain() {\n return makePath(this.rootDir, \"./public/issuer_chain.pem\");\n }\n\n /**\n * Path to the current Certificate Revocation List in DER format.\n * (`crl/revocation_list.der`)\n */\n public get revocationListDER() {\n return makePath(this.rootDir, \"./crl/revocation_list.der\");\n }\n\n /**\n * Path to the current Certificate Revocation List in PEM format.\n * (`crl/revocation_list.crl`)\n */\n public get revocationList() {\n return makePath(this.rootDir, \"./crl/revocation_list.crl\");\n }\n\n /**\n * Path to the concatenated CA certificate + CRL file.\n * Used by OpenSSL for CRL-based verification.\n */\n public get caCertificateWithCrl() {\n return makePath(this.rootDir, \"./public/cacertificate_with_crl.pem\");\n }\n\n // ---------------------------------------------------------------\n // Buffer-based accessors (US-059)\n // ---------------------------------------------------------------\n\n /**\n * Return the CA certificate as a DER-encoded buffer.\n *\n * @throws if the CA certificate file does not exist\n * (call {@link initialize} first).\n */\n public getCACertificateDER(): Buffer {\n const pem = readCertificatePEM(this.caCertificate);\n return convertPEMtoDER(pem);\n }\n\n /**\n * Return the CA certificate as a PEM-encoded string.\n *\n * @throws if the CA certificate file does not exist\n * (call {@link initialize} first).\n */\n public getCACertificatePEM(): string {\n const raw = readCertificatePEM(this.caCertificate);\n // OpenSSL CA cert files may include a human-readable text\n // dump before the PEM block — strip it.\n const beginMarker = \"-----BEGIN CERTIFICATE-----\";\n const idx = raw.indexOf(beginMarker);\n if (idx > 0) {\n return raw.substring(idx);\n }\n return raw;\n }\n\n /**\n * Return the current Certificate Revocation List as a\n * DER-encoded buffer.\n *\n * Returns an empty buffer if no CRL has been generated yet.\n */\n public getCRLDER(): Buffer {\n const crlPath = this.revocationListDER;\n if (!fs.existsSync(crlPath)) {\n return Buffer.alloc(0);\n }\n return fs.readFileSync(crlPath);\n }\n\n /**\n * Return the current Certificate Revocation List as a\n * PEM-encoded string.\n *\n * Returns an empty string if no CRL has been generated yet.\n */\n public getCRLPEM(): string {\n const crlPath = this.revocationList;\n if (!fs.existsSync(crlPath)) {\n return \"\";\n }\n const raw = fs.readFileSync(crlPath, \"utf-8\");\n // OpenSSL CRL files may include a human-readable text\n // dump before the PEM block — strip it.\n const beginMarker = \"-----BEGIN X509 CRL-----\";\n const idx = raw.indexOf(beginMarker);\n if (idx > 0) {\n return raw.substring(idx);\n }\n return raw;\n }\n\n // ---------------------------------------------------------------\n // Certificate database API (US-057)\n // ---------------------------------------------------------------\n\n /**\n * Return a list of all issued certificates recorded in the\n * OpenSSL `index.txt` database.\n *\n * Each entry includes the serial number, subject, status,\n * expiry date, and (for revoked certs) the revocation date.\n */\n public getIssuedCertificates(): IssuedCertificateRecord[] {\n return this.#db.readIndex();\n }\n\n /**\n * Return the total number of certificates recorded in\n * `index.txt`.\n */\n public getIssuedCertificateCount(): number {\n return this.#db.readIndex().length;\n }\n\n /**\n * Return the status of a certificate by its serial number.\n *\n * @param serial - hex-encoded serial number (e.g. `\"1000\"`)\n * @returns `\"valid\"`, `\"revoked\"`, `\"expired\"`, or\n * `undefined` if not found\n */\n public getCertificateStatus(serial: string): \"valid\" | \"revoked\" | \"expired\" | undefined {\n return this.#db.findBySerial(serial)?.status;\n }\n\n /**\n * Read a specific issued certificate by serial number and\n * return its content as a DER-encoded buffer.\n *\n * OpenSSL stores signed certificates in the `certs/`\n * directory using the naming convention `<SERIAL>.pem`.\n *\n * @param serial - hex-encoded serial number (e.g. `\"1000\"`)\n * @returns the DER buffer, or `undefined` if not found\n */\n public getCertificateBySerial(serial: string): Buffer | undefined {\n return this.#db.getCertificateBySerial(serial);\n }\n\n /**\n * Path to the OpenSSL certificate database file.\n */\n public get indexFile(): string {\n return this.#db.indexFile;\n }\n\n // ---------------------------------------------------------------\n // Buffer-based CA operations (US-058)\n // ---------------------------------------------------------------\n\n /**\n * Sign a DER-encoded Certificate Signing Request and return\n * the signed certificate as a DER buffer.\n *\n * This method handles temp-file creation and cleanup\n * internally so that callers can work with in-memory\n * buffers only.\n *\n * The CA can override fields from the CSR by passing\n * `options.dns`, `options.ip`, `options.applicationUri`,\n * `options.startDate`, or `options.subject`.\n *\n * @param csrDer - the CSR as a DER-encoded buffer\n * @param options - signing options and CA overrides\n * @returns the signed certificate as a DER-encoded buffer\n */\n public async signCertificateRequestFromDER(csrDer: Buffer, options?: SignCertificateOptions): Promise<Buffer> {\n const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), \"pki-sign-\"));\n\n try {\n const csrFile = path.join(tmpDir, \"request.csr\");\n const certFile = path.join(tmpDir, \"certificate.pem\");\n\n // Write CSR as PEM\n const csrPem = toPem(csrDer, \"CERTIFICATE REQUEST\");\n await fs.promises.writeFile(csrFile, csrPem, \"utf-8\");\n\n // Build signing parameters — CA overrides take precedence.\n // validityMs (sub-day capable) overrides validity (days) when\n // both are provided; adjustDate() handles precedence.\n const signingParams: Params = {};\n if (options?.validityMs !== undefined) signingParams.validityMs = options.validityMs;\n else signingParams.validity = options?.validity ?? 365;\n if (options?.startDate) signingParams.startDate = options.startDate;\n if (options?.dns) signingParams.dns = options.dns;\n if (options?.ip) signingParams.ip = options.ip;\n if (options?.applicationUri) signingParams.applicationUri = options.applicationUri;\n if (options?.subject) signingParams.subject = options.subject;\n\n // Delegate to the existing file-based method\n await this.signCertificateRequest(certFile, csrFile, signingParams);\n\n // Read the signed certificate and convert to DER\n const certPem = readCertificatePEM(certFile);\n return convertPEMtoDER(certPem);\n } finally {\n await fs.promises.rm(tmpDir, {\n recursive: true,\n force: true\n });\n }\n }\n\n /**\n * Advertise the validity limits this CA can honor.\n *\n * Consumers (notably the GDS server in [`cert_auth.ts`](https://github.com/sterfive/node-opcua-gds))\n * clamp a requested validity against these bounds before calling\n * {@link signCertificateRequestFromDER}, so a misconfigured\n * `defaultCertValidity` cannot ask the CA for something it cannot\n * produce.\n *\n * Defaults match the OpenSSL-backed implementation:\n * - `minValidityMs = 60_000` (1 minute) — practical floor; the\n * X.509 spec floor is 1 second but very short certs are rarely\n * useful and pathological for any real deployment.\n * - `maxValidityMs = 10 * 365 * 86_400_000` (≈ 10 years) — long\n * enough for root CAs.\n * - `validityGranularityMs = 1_000` (1 second) — RFC 5280 §4.1.2.5\n * floor on `notBefore` / `notAfter`.\n * - `nativeUnit = \"second\"` — what `x509Date()` actually encodes.\n *\n * @see US-208 — the consumer-side capability story.\n */\n public getCapabilities(): PkiBackendCapabilities {\n return {\n minValidityMs: 60_000,\n maxValidityMs: 10 * 365 * 86_400_000,\n validityGranularityMs: 1_000,\n nativeUnit: \"second\"\n };\n }\n\n /**\n * Generate a new RSA key pair, create an internal CSR, sign it\n * with this CA, and return both the certificate and private key\n * as DER-encoded buffers.\n *\n * The private key is **never stored** by the CA — it exists only\n * in a temporary directory that is cleaned up after the operation.\n *\n * This is used by `StartNewKeyPairRequest` (OPC UA Part 12) for\n * constrained devices that cannot generate their own keys.\n *\n * @param options - key generation and certificate parameters\n * @returns `{ certificateDer, privateKey }` — certificate as DER,\n * private key as a branded `PrivateKey` buffer\n */\n /**\n * An ephemeral key and a CSR for it, written into `tmpDir`. Both\n * `generateKeyPairAndSign*` methods need exactly this, and neither\n * needs a subprocess for it: the key comes from node's crypto and the\n * request is built and self-signed in process, so no `openssl.cnf` has\n * to be rendered either.\n */\n async #createEphemeralKeyAndCsr(\n tmpDir: string,\n keySize: KeySize,\n options: { applicationUri: string; subject?: SubjectOptions | string; dns?: string[]; ip?: string[] }\n ): Promise<{ privateKeyFile: string; csrFile: string }> {\n const privateKeyFile = path.join(tmpDir, \"private_key.pem\");\n await generatePrivateKeyFile(privateKeyFile, keySize);\n\n const { csr } = await createCertificateSigningRequest({\n privateKey: await privateKeyToCryptoKey(readPrivateKey(privateKeyFile)),\n subject: options.subject ? new Subject(options.subject).toString() : undefined,\n applicationUri: options.applicationUri,\n dns: options.dns ?? [],\n ip: options.ip ?? [],\n purpose: CertificatePurpose.ForApplication\n });\n const csrFile = path.join(tmpDir, \"request.csr\");\n await fs.promises.writeFile(csrFile, csr);\n return { privateKeyFile, csrFile };\n }\n\n public async generateKeyPairAndSignDER(options: GenerateKeyPairAndSignOptions): Promise<{\n certificateDer: Buffer;\n privateKey: PrivateKey;\n }> {\n const keySize = options.keySize ?? 2048;\n const startDate = options.startDate ?? new Date();\n const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), \"pki-keygen-\"));\n\n try {\n // 1. Ephemeral key + CSR, both in process\n const { privateKeyFile, csrFile } = await this.#createEphemeralKeyAndCsr(tmpDir, keySize, options);\n\n // 4. Sign the CSR with this CA — validityMs takes precedence\n // over validity when both are provided (adjustDate handles it).\n const certFile = path.join(tmpDir, \"certificate.pem\");\n const signingParams: Params = {\n applicationUri: options.applicationUri,\n dns: options.dns,\n ip: options.ip,\n startDate\n };\n if (options.validityMs !== undefined) signingParams.validityMs = options.validityMs;\n else signingParams.validity = options.validity ?? 365;\n await this.signCertificateRequest(certFile, csrFile, signingParams);\n\n // 5. Read results\n const certPem = readCertificatePEM(certFile);\n const certificateDer = convertPEMtoDER(certPem);\n const privateKey = readPrivateKey(privateKeyFile);\n\n return { certificateDer, privateKey };\n } finally {\n // 6. Securely clean up — private key is never persisted\n await fs.promises.rm(tmpDir, {\n recursive: true,\n force: true\n });\n }\n }\n\n /**\n * Generate a new RSA key pair, create an internal CSR, sign it\n * with this CA, and return the result as a PKCS#12 (PFX)\n * buffer bundling the certificate, private key, and CA chain.\n *\n * The private key is **never stored** by the CA — it exists only\n * in a temporary directory that is cleaned up after the operation.\n *\n * @param options - key generation, certificate, and PFX options\n * @returns the PFX as a `Buffer`\n */\n public async generateKeyPairAndSignPFX(options: GenerateKeyPairAndSignPFXOptions): Promise<Buffer> {\n const keySize = options.keySize ?? 2048;\n const startDate = options.startDate ?? new Date();\n const passphrase = options.passphrase ?? \"\";\n const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), \"pki-keygen-pfx-\"));\n\n try {\n // 1. Ephemeral key + CSR, both in process\n const { privateKeyFile, csrFile } = await this.#createEphemeralKeyAndCsr(tmpDir, keySize, options);\n\n // 4. Sign the CSR with this CA — validityMs takes precedence\n // over validity when both are provided (adjustDate handles it).\n const certFile = path.join(tmpDir, \"certificate.pem\");\n const signingParams: Params = {\n applicationUri: options.applicationUri,\n dns: options.dns,\n ip: options.ip,\n startDate\n };\n if (options.validityMs !== undefined) signingParams.validityMs = options.validityMs;\n else signingParams.validity = options.validity ?? 365;\n await this.signCertificateRequest(certFile, csrFile, signingParams);\n\n // 5. Bundle into PFX. signCertificateRequest leaves the chain in\n // certFile, so the leading block is the certificate and the rest\n // is already this CA's own - no need to read it back separately.\n const blocks = (await fs.promises.readFile(certFile, \"utf-8\")).match(\n /-----BEGIN CERTIFICATE-----[\\s\\S]*?-----END CERTIFICATE-----/g\n );\n if (!blocks || blocks.length === 0) {\n throw new Error(`generateKeyPairAndSignPFX: no certificate was produced in ${certFile}`);\n }\n return await createPfx({\n certificate: convertPEMtoDER(blocks[0]),\n certificateChain: blocks.slice(1).map(convertPEMtoDER),\n privateKey: readPrivateKey(privateKeyFile),\n password: passphrase\n });\n } finally {\n // 7. Securely clean up — private key is never persisted\n await fs.promises.rm(tmpDir, {\n recursive: true,\n force: true\n });\n }\n }\n\n /**\n * Revoke a DER-encoded certificate and regenerate the CRL.\n *\n * Extracts the serial number from the certificate, then\n * uses the stored cert file at `certs/<serial>.pem` for\n * revocation — avoiding temp-file PEM format mismatches.\n *\n * @param certDer - the certificate as a DER-encoded buffer\n * @param reason - CRL reason code\n * (default: `\"keyCompromise\"`)\n * @throws if the certificate's serial is not found in the CA\n */\n public async revokeCertificateDER(certDer: Buffer, reason?: string): Promise<void> {\n // 1. Extract serial from the DER certificate\n const info = exploreCertificate(certDer);\n // exploreCertificate returns serial as \"10:00\" (colon-hex)\n // openssl stores cert files as \"1000.pem\" (plain hex upper)\n const serial = info.tbsCertificate.serialNumber.replace(/:/g, \"\").toUpperCase();\n\n // 2. Use the cert file that openssl ca already stored\n const storedCertFile = path.join(this.rootDir, \"certs\", `${serial}.pem`);\n if (!fs.existsSync(storedCertFile)) {\n throw new Error(`Cannot revoke: no stored certificate found for serial ${serial} at ${storedCertFile}`);\n }\n\n // 3. Delegate to the existing file-based method\n await this.revokeCertificate(storedCertFile, {\n reason: reason ?? \"keyCompromise\"\n });\n }\n\n /**\n * Initialize the CA directory structure, generate the CA\n * private key and self-signed certificate if they do not\n * already exist.\n */\n public async initialize(): Promise<void> {\n // the lock file lives inside rootDir, so rootDir must exist before\n // #withCaLock can even acquire it — on a brand-new CA it doesn't yet\n mkdirRecursiveSync(path.resolve(this.rootDir));\n await this.#withCaLock(() => this.#bootstrap());\n }\n\n /**\n * @internal Shared (backend-agnostic) part of `initialize()`: directory\n * layout, default database files, the \"already initialized\" / \"partial\n * init\" checks, and the openssl config file — then delegates CSR\n * generation, CA-certificate signing, and the initial CRL to\n * {@link CaBackend.bootstrap}. Must be called under {@link #withCaLock}.\n */\n async #bootstrap(): Promise<void> {\n const caRootDir = path.resolve(this.rootDir);\n\n mkdirRecursiveSync(caRootDir);\n ensurePrivateDirectory(path.join(caRootDir, \"private\"));\n mkdirRecursiveSync(path.join(caRootDir, \"public\"));\n mkdirRecursiveSync(path.join(caRootDir, \"certs\"));\n mkdirRecursiveSync(path.join(caRootDir, \"crl\"));\n mkdirRecursiveSync(path.join(caRootDir, \"conf\"));\n\n const serial = path.join(caRootDir, \"serial\");\n if (!fs.existsSync(serial)) {\n await fs.promises.writeFile(serial, \"1000\");\n }\n const crlNumber = path.join(caRootDir, \"crlnumber\");\n if (!fs.existsSync(crlNumber)) {\n await fs.promises.writeFile(crlNumber, \"1000\");\n }\n const indexFile = path.join(caRootDir, \"index.txt\");\n if (!fs.existsSync(indexFile)) {\n await fs.promises.writeFile(indexFile, \"\");\n }\n\n // A signer-backed CA has no key file and never will: the key is held\n // by the HSM/KMS, so it always \"exists\" and is never generated here.\n const signerBacked = this.hasExternalSigner;\n const caKeyExists = signerBacked || fs.existsSync(path.join(caRootDir, \"private/cakey.pem\"));\n const caCertExists = fs.existsSync(path.join(caRootDir, \"public/cacert.pem\"));\n if (caKeyExists && caCertExists && !config.forceCA) {\n // CA is fully initialized => do not overwrite\n if (!signerBacked) {\n // repair permissions on installs created before this hardening\n restrictPrivateFilePermissions(path.join(caRootDir, \"private/cakey.pem\"), 0o600);\n // encrypt a plaintext key in place if a passphrase is configured, and\n // fail closed now if the key cannot be read with the configured one\n await this._ensurePrivateKeyProtection();\n }\n debugLog(\"CA private key and certificate already exist ... skipping\");\n return;\n }\n if (!signerBacked && caKeyExists && !caCertExists) {\n // Partial init: key exists but certificate does not.\n // This can happen when a previous CA creation failed\n // (e.g. OpenSSL 3.5 authorityKeyIdentifier error).\n // Remove the stale key so the CA is rebuilt from scratch.\n debugLog(\"CA private key exists but cacert.pem is missing — rebuilding CA\");\n fs.unlinkSync(path.join(caRootDir, \"private/cakey.pem\"));\n // Also remove the stale CSR if present\n const staleCsr = path.join(caRootDir, \"private/cakey.csr\");\n if (fs.existsSync(staleCsr)) {\n fs.unlinkSync(staleCsr);\n }\n }\n\n displayTitle(\"Create Certificate Authority (CA)\");\n\n const indexFileAttr = path.join(caRootDir, \"index.txt.attr\");\n if (!fs.existsSync(indexFileAttr)) {\n await fs.promises.writeFile(indexFileAttr, \"unique_subject = no\");\n }\n\n const caConfigFile = this.configFile;\n await fs.promises.writeFile(caConfigFile, renderCaConfig(caRootDir));\n\n if (!signerBacked) {\n const privateKeyFilename = path.join(caRootDir, \"private/cakey.pem\");\n\n displayTitle(`Generate the CA private Key - ${this.keySize}`);\n // The first step is to create your RSA Private Key.\n // This key is a 1025,2048,3072 or 2038 bit RSA key which is encrypted using\n // Triple-DES and stored in a PEM format so that it is readable as ASCII text.\n await generatePrivateKeyFile(privateKeyFilename, this.keySize, { passphrase: await this._privateKeyPassphrase() });\n restrictPrivateFilePermissions(privateKeyFilename, 0o600);\n }\n\n // Once the private key is generated a Certificate Signing Request can be generated.\n // The CSR is then used in one of two ways. Ideally, the CSR will be sent to a Certificate Authority, such as\n // Thawte or Verisign who will verify the identity of the requestor and issue a signed certificate.\n // The second option is to self-sign the CSR, which will be demonstrated in the next section\n await this.#backend.bootstrap(this);\n }\n\n /**\n * Initialize the CA directory structure and generate the\n * private key + CSR **without signing**.\n *\n * Use this when the CA certificate will be signed by an\n * external (third-party) root CA. After receiving the signed\n * certificate, call {@link installCACertificate} to complete\n * the setup.\n *\n * **Idempotent / restart-safe:**\n * - If the CA certificate exists and is valid → `{ status: \"ready\" }`\n * - If the CA certificate has expired → `{ status: \"expired\", csrPath, expiryDate }`\n * (a new CSR is generated, preserving the existing private key)\n * - If key + CSR exist but no cert (restart before install) →\n * `{ status: \"pending\", csrPath }` without regenerating\n * - Otherwise → generates key + CSR → `{ status: \"created\", csrPath }`\n *\n * @returns an {@link InitializeCSRResult} describing the CA state\n */\n public async initializeCSR(): Promise<InitializeCSRResult> {\n const caRootDir = path.resolve(this.rootDir);\n\n // the lock file lives inside rootDir, so rootDir must exist before\n // #withCaLock can even acquire it — on a brand-new CA it doesn't yet\n mkdirRecursiveSync(caRootDir);\n // Everything below mutates the CA directory (key generation guarded\n // only by an existsSync check, default database files, the openssl\n // config, the CSR) and must run under the same lock initialize()\n // uses, or two concurrent initializeCSR() calls can both pass the\n // key-existence check and overwrite each other's key after one of\n // them has already derived a CSR from it.\n return this.#withCaLock(() => this.#initializeCSRLocked(caRootDir));\n }\n\n async #initializeCSRLocked(caRootDir: string): Promise<InitializeCSRResult> {\n // Ensure directory structure always exists\n for (const dir of [\"public\", \"certs\", \"crl\", \"conf\"]) {\n mkdirRecursiveSync(path.join(caRootDir, dir));\n }\n ensurePrivateDirectory(path.join(caRootDir, \"private\"));\n\n const caCertFile = this.caCertificate;\n const privateKeyFile = path.join(caRootDir, \"private/cakey.pem\");\n const csrFile = path.join(caRootDir, \"private/cakey.csr\");\n\n // a signer-backed CA holds its key externally: it is always\n // \"available\" and there is no file to generate, protect or permission\n const keyAvailable = this.hasExternalSigner || fs.existsSync(privateKeyFile);\n\n // repair permissions on installs created before this hardening,\n // encrypt in place if a passphrase is configured, fail closed if unreadable\n if (!this.hasExternalSigner && fs.existsSync(privateKeyFile)) {\n restrictPrivateFilePermissions(privateKeyFile, 0o600);\n await this._ensurePrivateKeyProtection();\n }\n\n // ── Case 1: cert already exists ──\n if (fs.existsSync(caCertFile)) {\n // Check if the certificate has expired\n const certDer = convertPEMtoDER(readCertificatePEM(caCertFile));\n const certInfo = exploreCertificate(certDer);\n const notAfter = certInfo.tbsCertificate.validity.notAfter;\n if (notAfter.getTime() < Date.now()) {\n // Certificate has expired — regenerate CSR for renewal\n debugLog(\"CA certificate has expired — generating renewal CSR\");\n await this._generateCSR(caRootDir, privateKeyFile, csrFile);\n return { status: \"expired\", csrPath: csrFile, expiryDate: notAfter };\n }\n debugLog(\"CA certificate already exists and is valid — ready\");\n return { status: \"ready\" };\n }\n\n // ── Case 2: key + CSR exist but no cert → pending state ──\n // (restart between initializeCSR and installCACertificate)\n if (keyAvailable && fs.existsSync(csrFile)) {\n debugLog(\"CA key + CSR already exist — pending external signing\");\n return { status: \"pending\", csrPath: csrFile };\n }\n\n // ── Case 3: fresh setup — generate key + CSR ──\n // Create default files (serial, crlnumber, index.txt)\n const serial = path.join(caRootDir, \"serial\");\n if (!fs.existsSync(serial)) {\n await fs.promises.writeFile(serial, \"1000\");\n }\n const crlNumber = path.join(caRootDir, \"crlnumber\");\n if (!fs.existsSync(crlNumber)) {\n await fs.promises.writeFile(crlNumber, \"1000\");\n }\n const indexFile = path.join(caRootDir, \"index.txt\");\n if (!fs.existsSync(indexFile)) {\n await fs.promises.writeFile(indexFile, \"\");\n }\n const indexFileAttr = path.join(caRootDir, \"index.txt.attr\");\n if (!fs.existsSync(indexFileAttr)) {\n await fs.promises.writeFile(indexFileAttr, \"unique_subject = no\");\n }\n\n // Write OpenSSL config\n const caConfigFile = this.configFile;\n await fs.promises.writeFile(caConfigFile, renderCaConfig(caRootDir));\n\n // Generate private key\n if (!keyAvailable) {\n await generatePrivateKeyFile(privateKeyFile, this.keySize, { passphrase: await this._privateKeyPassphrase() });\n restrictPrivateFilePermissions(privateKeyFile, 0o600);\n }\n\n // Generate CSR\n await this._generateCSR(caRootDir, privateKeyFile, csrFile);\n return { status: \"created\", csrPath: csrFile };\n }\n\n /**\n * Check whether the CA certificate needs renewal and, if so,\n * generate a new CSR for re-signing by the external root CA.\n *\n * Use this while the CA is running to detect upcoming expiry\n * **before** it actually expires. The existing private key is\n * preserved so previously issued certs remain valid.\n *\n * @param thresholdDays - number of days before expiry at which\n * to trigger renewal (default: 30)\n * @returns an {@link InitializeCSRResult} — `\"expired\"` if\n * renewal is needed, `\"ready\"` if the cert is still valid\n */\n public async renewCSR(thresholdDays = 30): Promise<InitializeCSRResult> {\n const caRootDir = path.resolve(this.rootDir);\n const caCertFile = this.caCertificate;\n const privateKeyFile = path.join(caRootDir, \"private/cakey.pem\");\n const csrFile = path.join(caRootDir, \"private/cakey.csr\");\n\n if (!fs.existsSync(caCertFile)) {\n // No cert at all — delegate to initializeCSR\n return this.initializeCSR();\n }\n\n const certDer = convertPEMtoDER(readCertificatePEM(caCertFile));\n const certInfo = exploreCertificate(certDer);\n const notAfter = certInfo.tbsCertificate.validity.notAfter;\n\n const thresholdMs = thresholdDays * 24 * 60 * 60 * 1000;\n if (notAfter.getTime() - Date.now() < thresholdMs) {\n debugLog(`CA certificate expires within ${thresholdDays} days — generating renewal CSR`);\n await this.#withCaLock(() => this._generateCSR(caRootDir, privateKeyFile, csrFile));\n return { status: \"expired\", csrPath: csrFile, expiryDate: notAfter };\n }\n\n return { status: \"ready\" };\n }\n\n /**\n * Generate a CSR using the existing private key.\n * Must be called under {@link #withCaLock} — the lock is taken by the\n * public callers (`initializeCSR`, `renewCSR`), not here, so that\n * `initializeCSR` can hold one lock across key generation AND CSR\n * generation without the non-reentrant file lock deadlocking.\n * @internal\n */\n private async _generateCSR(caRootDir: string, privateKeyFile: string, csrFile: string): Promise<void> {\n await this.#backend.generateCaCsr(this, caRootDir, privateKeyFile, csrFile);\n }\n\n /**\n * Install an externally-signed CA certificate and generate\n * the initial CRL.\n *\n * Call this after {@link initializeCSR} once the external\n * root CA has signed the CSR.\n *\n * **Safety checks:**\n * - Verifies that the certificate's public key matches the\n * CA private key before installing.\n *\n * @param signedCertFile - path to the PEM-encoded signed\n * CA certificate (issued by the external root CA)\n * @returns an {@link InstallCACertificateResult} with\n * `status: \"success\"` or `status: \"error\"` and a `reason`\n */\n public async installCACertificate(signedCertFile: string): Promise<InstallCACertificateResult> {\n return this.#withCaLock(async () => {\n const caCertFile = this.caCertificate;\n\n // Read the full content once — may contain a chain\n const fullPem = await fs.promises.readFile(signedCertFile, \"utf8\");\n\n // Split PEM blocks: first cert → cacert.pem, rest → issuer_chain.pem\n const pemBlocks = fullPem.match(/-----BEGIN CERTIFICATE-----[\\s\\S]*?-----END CERTIFICATE-----/g);\n if (!pemBlocks || pemBlocks.length === 0) {\n return {\n status: \"error\",\n reason: \"no_certificate_found\",\n message: \"The provided file does not contain any PEM-encoded certificate.\"\n };\n }\n\n // Verify the first certificate really belongs to this CA's key\n const certDer = convertPEMtoDER(pemBlocks[0]);\n if (!(await this.#certificateMatchesOurKey(pemBlocks[0], certDer))) {\n return {\n status: \"error\",\n reason: \"certificate_key_mismatch\",\n message:\n \"The provided certificate does not match the CA \" +\n \"private key. Ensure the certificate was signed \" +\n \"from the CSR generated by initializeCSR().\"\n };\n }\n\n // Write the first cert (the CA cert itself)\n await fs.promises.writeFile(caCertFile, `${pemBlocks[0]}\\n`);\n\n // Write any additional issuer certs to the chain file\n const issuerChainFile = this.issuerCertificateChain;\n if (pemBlocks.length > 1) {\n const issuerPem = `${pemBlocks.slice(1).join(\"\\n\")}\\n`;\n await fs.promises.writeFile(issuerChainFile, issuerPem);\n debugLog(`Stored ${pemBlocks.length - 1} issuer certificate(s) in issuer_chain.pem`);\n } else {\n // No issuer chain — remove stale file if present\n if (fs.existsSync(issuerChainFile)) {\n await fs.promises.unlink(issuerChainFile);\n }\n }\n\n // Generate initial CRL\n await this.#backend.regenerateCrl(this);\n\n return { status: \"success\" };\n });\n }\n\n /**\n * Sign a CSR with CA extensions (`v3_ca`), producing a\n * subordinate CA certificate.\n *\n * Unlike {@link signCertificateRequest} which signs with\n * end-entity extensions (SANs, etc.), this method signs\n * with `basicConstraints = CA:TRUE` and `keyUsage =\n * keyCertSign, cRLSign`.\n *\n * @param certFile - output path for the signed CA cert (PEM)\n * @param csrFile - path to the subordinate CA's CSR\n * @param params - signing parameters\n */\n public async signCACertificateRequest(certFile: string, csrFile: string, params: { validity?: number }): Promise<void> {\n await this.#withCaLock(async () => {\n const validity = params.validity ?? 3650;\n\n await this.#backend.signSubordinateCsr(this, csrFile, certFile, validity);\n\n // Append this CA's cert chain to the output so the caller\n // receives a complete chain file ready for installCACertificate.\n // Chain format: [signedSubordinateCert, thisCA, thisCA's issuers...]\n await this.constructCertificateChain(certFile);\n });\n }\n\n /**\n * Rebuild the combined CA certificate + CRL file.\n *\n * This concatenates the CA certificate with the current\n * revocation list so that OpenSSL can verify certificates\n * with CRL checking enabled.\n */\n public async constructCACertificateWithCRL(): Promise<void> {\n const cacertWithCRL = this.caCertificateWithCrl;\n\n // note : in order to check if the certificate is revoked,\n // you need to specify -crl_check and have both the CA cert and the (applicable) CRL in your trust store.\n // There are two ways to do that:\n // 1. concatenate cacert.pem and crl.pem into one file and use that for -CAfile.\n // 2. use some linked\n // ( from http://security.stackexchange.com/a/58305/59982)\n\n if (fs.existsSync(this.revocationList)) {\n await fs.promises.writeFile(\n cacertWithCRL,\n fs.readFileSync(this.caCertificate, \"utf8\") + fs.readFileSync(this.revocationList, \"utf8\")\n );\n } else {\n // there is no revocation list yet\n await fs.promises.writeFile(cacertWithCRL, fs.readFileSync(this.caCertificate));\n }\n }\n\n /**\n * Append the CA certificate to a signed certificate file,\n * creating a PEM certificate chain.\n *\n * @param certificate - path to the certificate file to extend\n */\n public async constructCertificateChain(certificate: Filename): Promise<void> {\n assert(fs.existsSync(certificate));\n assert(fs.existsSync(this.caCertificate));\n\n debugLog(chalk.yellow(\" certificate file :\"), chalk.cyan(certificate));\n\n // Build chain: cert + this CA cert + issuer chain (if available)\n let chain = await fs.promises.readFile(certificate, \"utf8\");\n chain += await fs.promises.readFile(this.caCertificate, \"utf8\");\n\n // Append the issuer certificate chain (e.g. root CA cert)\n // to produce a complete chain per OPC UA Part 6 §6.2.6\n if (fs.existsSync(this.issuerCertificateChain)) {\n chain += await fs.promises.readFile(this.issuerCertificateChain, \"utf8\");\n }\n\n await fs.promises.writeFile(certificate, chain);\n }\n\n /**\n * Create a self-signed certificate using OpenSSL.\n *\n * @param certificateFile - output path for the signed certificate\n * @param privateKey - path to the private key file\n * @param params - certificate parameters (subject, validity, SANs)\n */\n public async createSelfSignedCertificate(certificateFile: Filename, privateKey: Filename, params: Params): Promise<void> {\n assert(typeof privateKey === \"string\");\n assert(fs.existsSync(privateKey));\n\n if (!certificateFileExist(certificateFile)) {\n return;\n }\n\n adjustDate(params);\n adjustApplicationUri(params);\n params.dns = params.dns || [];\n params.ip = params.ip || [];\n\n await this.#withCaLock(async () => {\n await this.#backend.createSelfSignedCertificate(this, certificateFile, privateKey, params);\n });\n }\n\n /**\n * Regenerate `crl/revocation_list.{crl,der}` from the current database\n * state, without changing any certificate's status. Normally\n * unnecessary — `revokeCertificate` already regenerates the CRL as\n * part of revoking — but useful to force a refresh (e.g. after\n * switching a CA's `backend` between `\"openssl\"` and `\"native\"`).\n */\n public async regenerateCrl(): Promise<void> {\n await this.#withCaLock(async () => {\n await this.#backend.regenerateCrl(this);\n });\n }\n\n /**\n * Revoke a certificate and regenerate the CRL.\n *\n * @param certificate - path to the certificate file to revoke\n * @param params - revocation parameters\n * @param params.reason - CRL reason code\n * (default `\"keyCompromise\"`)\n */\n public async revokeCertificate(certificate: Filename, params: Params): Promise<void> {\n const crlReasons = [\n \"unspecified\",\n \"keyCompromise\",\n \"CACompromise\",\n \"affiliationChanged\",\n \"superseded\",\n \"cessationOfOperation\",\n \"certificateHold\",\n \"removeFromCRL\"\n ];\n\n const reason = params.reason || \"keyCompromise\";\n assert(crlReasons.indexOf(reason) >= 0);\n\n displayTitle(`Revoking certificate ${certificate}`);\n\n await this.#withCaLock(async () => {\n await this.#backend.revoke(this, certificate, reason);\n });\n }\n\n /**\n * Sign a Certificate Signing Request (CSR) with this CA.\n *\n * The signed certificate is written to `certificate`, and the\n * CA certificate chain plus CRL are appended to form a\n * complete certificate chain.\n *\n * @param certificate - output path for the signed certificate\n * @param certificateSigningRequestFilename - path to the CSR\n * @param params1 - signing parameters (validity, dates, SANs)\n * @returns the path to the signed certificate\n */\n public async signCertificateRequest(\n certificate: Filename,\n certificateSigningRequestFilename: Filename,\n params1: Params\n ): Promise<Filename> {\n // ask the backend, do not assume: a native CA needs no openssl at all\n await this.#backend.preflight();\n assert(fs.existsSync(certificateSigningRequestFilename));\n if (!certificateFileExist(certificate)) {\n return \"\";\n }\n adjustDate(params1);\n adjustApplicationUri(params1);\n\n // note :\n // subjectAltName is not copied across\n // see https://github.com/openssl/openssl/issues/10458\n const csr = await readCertificateSigningRequest(certificateSigningRequestFilename);\n const csrInfo = exploreCertificateSigningRequest(csr);\n\n const applicationUri = csrInfo.extensionRequest.subjectAltName.uniformResourceIdentifier\n ? csrInfo.extensionRequest.subjectAltName.uniformResourceIdentifier[0]\n : undefined;\n if (typeof applicationUri !== \"string\") {\n throw new Error(\"Cannot find applicationUri in CSR\");\n }\n\n const dns = csrInfo.extensionRequest.subjectAltName.dNSName || [];\n let ip = csrInfo.extensionRequest.subjectAltName.iPAddress || [];\n ip = ip.map(octetStringToIpAddress);\n\n const sanOverride: Required<ProcessAltNamesParam> = { applicationUri, dns, ip };\n\n return this.#withCaLock(async () => {\n await this.#backend.signEndEntityCsr(this, certificate, certificateSigningRequestFilename, params1, sanOverride);\n\n displaySubtitle(\"- construct CA certificate with CRL\");\n await this.constructCACertificateWithCRL();\n\n // construct certificate chain\n // concatenate certificate with CA Certificate and revocation list\n displaySubtitle(\"- construct certificate chain\");\n await this.constructCertificateChain(certificate);\n // todo\n displaySubtitle(\"- verify certificate against the root CA\");\n await this.verifyCertificate(certificate);\n\n return certificate;\n });\n }\n\n /**\n * Check that `certificate` really was signed by this CA, and throw if it\n * was not.\n *\n * This used to do nothing: `openssl verify` crashes on Windows, so the\n * check was left as a placeholder. It no longer needs a subprocess -\n * `verifyCertificateSignature` does it in pure JS, the same way\n * {@link CertificateManager} already validates a chain - so the check\n * that `signCertificateRequest` always claimed to perform now actually\n * happens on every issuance, whichever backend did the signing.\n *\n * Only the leading certificate is examined: the file may be a chain,\n * and the rest of it is this CA's own certificate and its issuers.\n *\n * @param certificate - path to the certificate (or chain) to verify\n */\n public async verifyCertificate(certificate: Filename): Promise<void> {\n const pem = await fs.promises.readFile(certificate, \"utf-8\");\n const blocks = pem.match(/-----BEGIN CERTIFICATE-----[\\s\\S]*?-----END CERTIFICATE-----/g);\n if (!blocks || blocks.length === 0) {\n throw new Error(`verifyCertificate: ${certificate} contains no PEM-encoded certificate`);\n }\n const caCertificateDer = convertPEMtoDER(readCertificatePEM(this.caCertificate));\n if (!verifyCertificateSignature(convertPEMtoDER(blocks[0]), caCertificateDer)) {\n throw new Error(\n `verifyCertificate: ${certificate} was not signed by this certificate authority (${this.caCertificate})`\n );\n }\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua-pki\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n\nimport { type OpensslPassArg, passinArg, setEnv, unsetEnv } from \"../toolbox/with_openssl\";\nimport { NativeCaBackend } from \"./backends/native_ca_backend\";\nimport { caConfigEnvOverrides, OpenSslCaBackend } from \"./backends/openssl_ca_backend\";\nimport { CertificateAuthorityCore, type CertificateAuthorityCoreOptions } from \"./core/certificate_authority_core\";\n\n// Everything the CA exposes lives in the core module; re-exported here so\n// that `import { ... } from \"./ca/certificate_authority\"` keeps resolving\n// exactly as it did before the split.\nexport * from \"./core/certificate_authority_core\";\n\n/**\n * Options for {@link CertificateAuthority}: the core's, except that the\n * backend is named rather than supplied.\n */\nexport interface CertificateAuthorityOptions extends Omit<CertificateAuthorityCoreOptions, \"backend\"> {\n /**\n * Signing backend to use.\n *\n * - `\"openssl\"` (default): shells out to the `openssl` CLI, as this\n * class always has.\n * - `\"native\"`: signs in pure JS via `node-opcua-crypto`, writing the\n * same on-disk database format, and needs no `openssl` executable.\n *\n * Setting `signer` implies `\"native\"`, since the openssl CLI can only\n * load a key from a file.\n *\n * To supply a backend instance directly - including one of your own -\n * use {@link CertificateAuthorityCore}, which is also the class to\n * build against when you do not want the openssl backend in your\n * bundle at all.\n */\n backend?: \"openssl\" | \"native\";\n}\n\n/**\n * A Certificate Authority with a backend chosen for you.\n *\n * This is {@link CertificateAuthorityCore} plus the convenience that made\n * it the historical API: name a backend, or name nothing and get openssl.\n * Because it resolves the name, it necessarily references both backends,\n * which is why the core exists separately - a program that never imports\n * this class never pulls the openssl backend into its bundle.\n */\nexport class CertificateAuthority extends CertificateAuthorityCore {\n constructor(options: CertificateAuthorityOptions) {\n if (options.signer && options.backend === \"openssl\") {\n throw new Error(\n \"CertificateAuthority: backend 'openssl' cannot be combined with 'signer' - \" +\n \"the openssl CLI loads its key from a file and cannot call an external signer. \" +\n \"Drop the backend option (a signer implies 'native') or drop the signer.\"\n );\n }\n const backend = options.signer || options.backend === \"native\" ? new NativeCaBackend() : new OpenSslCaBackend();\n super({ ...options, backend });\n }\n\n /**\n * @internal `-passin env:` argv + env for an openssl call that loads\n * this CA's key (always emitted, empty when none).\n *\n * The openssl backend builds its own now; this remains so that external\n * code calling it keeps working, and lives here rather than on the core\n * because the flag means nothing to a backend that spawns nothing.\n */\n public async _opensslPassin(): Promise<OpensslPassArg> {\n return passinArg(await this._privateKeyPassphrase());\n }\n\n /**\n * @internal\n * Legacy shim: publish the `CDP_URL` / `AIA_VALUE` config substitution\n * values to the shared env registry, or unset them so the matching\n * `{{#KEY}}...{{/KEY}}` blocks are stripped. Nothing in this package\n * reads the registry any more - every openssl config render receives\n * these values explicitly, from the same {@link caConfigEnvOverrides}\n * builder this delegates to, so the two cannot drift - kept only for\n * external code that renders openssl config templates against the\n * registry directly.\n *\n * It lives on this class rather than the core because it is meaningful\n * only to the openssl backend.\n */\n public _wireRevocationEnvVars(): void {\n const overrides = caConfigEnvOverrides(this);\n if (overrides.CDP_URL) {\n setEnv(\"CDP_URL\", overrides.CDP_URL);\n } else {\n unsetEnv(\"CDP_URL\");\n }\n if (overrides.AIA_VALUE) {\n setEnv(\"AIA_VALUE\", overrides.AIA_VALUE);\n } else {\n unsetEnv(\"AIA_VALUE\");\n }\n }\n}\n","// ---------------------------------------------------------------------------------------------------------------------\n// node-opcua\n// ---------------------------------------------------------------------------------------------------------------------\n// Copyright (c) 2014-2026 - Etienne Rossignon - etienne.rossignon (at) gadz.org\n// Copyright (c) 2022-2026 - Sterfive.com\n// ---------------------------------------------------------------------------------------------------------------------\n//\n// This project is licensed under the terms of the MIT license.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n// permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n// Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n// ---------------------------------------------------------------------------------------------------------------------\n// Error.stackTraceLimit = Infinity;\n\nimport assert from \"node:assert\";\nimport fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport chalk from \"chalk\";\nimport { CertificatePurpose, generatePrivateKeyFile, Subject, type SubjectOptions } from \"node-opcua-crypto\";\n\nimport { makeApplicationUrn } from \"../misc/applicationurn\";\nimport { extractFullyQualifiedDomainName, getFullyQualifiedDomainName } from \"../misc/hostname\";\nimport { CertificateManager, type CreateSelfSignCertificateParam1 } from \"../pki/certificate_manager\";\nimport {\n type CreateCertificateSigningRequestWithConfigOptions,\n debugLog,\n displayChapter,\n displaySubtitle,\n displayTitle,\n type Filename,\n g_config,\n type KeySize,\n makePath,\n mkdirRecursiveSync,\n warningLog\n} from \"../toolbox\";\nimport {\n createCertificateSigningRequestWithOpenSSL,\n dumpCertificate,\n ensure_openssl_installed,\n fingerprint,\n getPublicKeyFromPrivateKey,\n setEnv,\n toDer\n} from \"../toolbox/with_openssl\";\nimport { CertificateAuthority, defaultSubject } from \"./certificate_authority\";\n\nconst epilog = \"Copyright (c) sterfive - node-opcua - 2017-2026\";\n\n// ------------------------------------------------- some useful dates\nfunction get_offset_date(date: Date, nbDays: number): Date {\n const d = new Date(date.getTime());\n d.setDate(d.getDate() + nbDays);\n return d;\n}\n\nconst today = new Date();\nconst yesterday = get_offset_date(today, -1);\nconst two_years_ago = get_offset_date(today, -2 * 365);\nconst next_year = get_offset_date(today, 365);\n\ninterface LocalConfig {\n CAFolder?: string;\n PKIFolder?: string;\n\n keySize?: KeySize;\n\n subject?: SubjectOptions | string;\n\n certificateDir?: Filename;\n\n privateKey?: Filename;\n\n applicationUri?: string;\n\n outputFile?: string;\n\n altNames?: string[];\n dns?: string[];\n ip?: string[];\n\n startDate?: Date;\n validity?: number;\n}\n\nlet gLocalConfig: LocalConfig = {};\n\nlet g_certificateAuthority: CertificateAuthority; // the Certificate Authority\n\n/***\n *\n *\n * prerequisites :\n * g_config.CAFolder : the folder of the CA\n */\nasync function construct_CertificateAuthority(subject: string) {\n // verify that g_config file has been loaded\n assert(typeof gLocalConfig.CAFolder === \"string\", \"expecting a CAFolder in config\");\n assert(typeof gLocalConfig.keySize === \"number\", \"expecting a keySize in config\");\n\n if (!g_certificateAuthority) {\n g_certificateAuthority = new CertificateAuthority({\n keySize: gLocalConfig.keySize,\n location: gLocalConfig.CAFolder,\n subject\n });\n await g_certificateAuthority.initialize();\n }\n}\n\nlet certificateManager: CertificateManager; // the Certificate Manager\n/***\n *\n *\n * prerequisites :\n * g_config.PKIFolder : the folder of the PKI\n */\nasync function construct_CertificateManager() {\n assert(typeof gLocalConfig.PKIFolder === \"string\", \"expecting a PKIFolder in config\");\n\n if (!certificateManager) {\n certificateManager = new CertificateManager({\n keySize: gLocalConfig.keySize,\n location: gLocalConfig.PKIFolder\n });\n await certificateManager.initialize();\n }\n}\n\nfunction _displayConfig(config: { [key: string]: { toString: () => string } }) {\n function w(str: string, l: number): string {\n return `${str} `.substring(0, l);\n }\n\n warningLog(chalk.yellow(\" configuration = \"));\n\n for (const [key, value] of Object.entries(config)) {\n warningLog(` ${chalk.yellow(w(key, 30))} : ${chalk.cyan(value.toString())}`);\n }\n}\n\nfunction default_template_content(): string {\n // istanbul ignore next\n if ((process as unknown as { pkg?: { entrypoint: string } }).pkg?.entrypoint) {\n // we are using PKG compiled package !\n\n // warningLog(\"___filename\", __filename);\n // warningLog(\"__dirname\", __dirname);\n // warningLog(\"process.pkg.entrypoint\", (process as unknown as IReadConfigurationOpts).pkg.entrypoint);\n const a = fs.readFileSync(path.join(__dirname, \"../../bin/pki_config.example.js\"), \"utf8\");\n return a;\n }\n function find_default_config_template() {\n const rootFolder = find_module_root_folder();\n\n // Note: we use a hardcoded config filename here because after tsup bundling,\n // __filename points to the bundle file (e.g., \"index.mjs\") rather than the\n // original source file, making dynamic name construction unreliable.\n const configName = \"pki_config.example.js\";\n\n let default_config_template = path.join(rootFolder, \"bin\", configName);\n\n if (!fs.existsSync(default_config_template)) {\n default_config_template = path.join(__dirname, \"..\", configName);\n\n if (!fs.existsSync(default_config_template)) {\n default_config_template = path.join(__dirname, `../bin/${configName}`);\n }\n }\n return default_config_template;\n }\n const default_config_template = find_default_config_template();\n assert(fs.existsSync(default_config_template));\n const default_config_template_content = fs.readFileSync(default_config_template, \"utf8\");\n return default_config_template_content;\n}\n\n/**\n *\n */\nfunction find_module_root_folder() {\n let rootFolder = path.join(__dirname);\n\n for (let i = 0; i < 4; i++) {\n if (fs.existsSync(path.join(rootFolder, \"package.json\"))) {\n return rootFolder;\n }\n rootFolder = path.join(rootFolder, \"..\");\n }\n\n assert(fs.existsSync(path.join(rootFolder, \"package.json\")), \"root folder must have a package.json file\");\n return rootFolder;\n}\n\ninterface IReadConfigurationOpts {\n root: string;\n silent?: boolean;\n subject?: string;\n CAFolder?: string;\n PKIFolder?: string;\n privateKey?: string;\n applicationUri?: string;\n output?: string;\n altNames?: string;\n dns?: string;\n ip?: string;\n keySize?: KeySize;\n validity?: number;\n}\n\nasync function readConfiguration(argv: IReadConfigurationOpts) {\n if (argv.silent) {\n g_config.silent = true;\n } else {\n g_config.silent = false;\n }\n\n const fqdn = await extractFullyQualifiedDomainName();\n const hostname = os.hostname();\n let certificateDir: string;\n\n function performSubstitution(str: string): string {\n str = str.replace(\"{CWD}\", process.cwd());\n if (certificateDir) {\n str = str.replace(\"{root}\", certificateDir);\n }\n if (gLocalConfig?.PKIFolder) {\n str = str.replace(\"{PKIFolder}\", gLocalConfig.PKIFolder);\n }\n str = str.replace(\"{hostname}\", hostname);\n str = str.replace(\"%FQDN%\", fqdn);\n return str;\n }\n\n function prepare(file: Filename): Filename {\n const tmp = path.resolve(performSubstitution(file));\n return makePath(tmp);\n }\n\n // ------------------------------------------------------------------------------------------------------------\n certificateDir = argv.root;\n assert(typeof certificateDir === \"string\");\n\n certificateDir = prepare(certificateDir);\n mkdirRecursiveSync(certificateDir);\n assert(fs.existsSync(certificateDir));\n\n // ------------------------------------------------------------------------------------------------------------\n const default_config = path.join(certificateDir, \"config.js\");\n\n if (!fs.existsSync(default_config)) {\n // copy\n debugLog(chalk.yellow(\" Creating default g_config file \"), chalk.cyan(default_config));\n const default_config_template_content = default_template_content();\n fs.writeFileSync(default_config, default_config_template_content);\n } else {\n debugLog(chalk.yellow(\" using g_config file \"), chalk.cyan(default_config));\n }\n if (!fs.existsSync(default_config)) {\n debugLog(chalk.redBright(\" cannot find config file \", default_config));\n }\n\n // see http://stackoverflow.com/questions/94445/using-openssl-what-does-unable-to-write-random-state-mean\n // set random file to be random.rnd in the same folder as the g_config file\n const defaultRandomFile = path.join(path.dirname(default_config), \"random.rnd\");\n setEnv(\"RANDFILE\", defaultRandomFile);\n\n const _require = createRequire(__filename);\n gLocalConfig = _require(default_config);\n\n gLocalConfig.subject = new Subject(gLocalConfig.subject || \"\");\n\n // if subject is provided on the command line , it has hight priority\n if (argv.subject) {\n gLocalConfig.subject = new Subject(argv.subject);\n }\n\n // istanbul ignore next\n if (!gLocalConfig.subject.commonName) {\n throw new Error(\"subject must have a Common Name\");\n }\n\n gLocalConfig.certificateDir = certificateDir;\n\n // ------------------------------------------------------------------------------------------------------------\n let CAFolder = argv.CAFolder || path.join(certificateDir, \"CA\");\n CAFolder = prepare(CAFolder);\n gLocalConfig.CAFolder = CAFolder;\n\n // ------------------------------------------------------------------------------------------------------------\n gLocalConfig.PKIFolder = path.join(gLocalConfig.certificateDir, \"PKI\");\n if (argv.PKIFolder) {\n gLocalConfig.PKIFolder = prepare(argv.PKIFolder);\n }\n gLocalConfig.PKIFolder = prepare(gLocalConfig.PKIFolder);\n if (argv.privateKey) {\n gLocalConfig.privateKey = prepare(argv.privateKey);\n }\n\n if (argv.applicationUri) {\n gLocalConfig.applicationUri = performSubstitution(argv.applicationUri);\n }\n\n if (argv.output) {\n gLocalConfig.outputFile = argv.output;\n }\n\n gLocalConfig.altNames = [];\n if (argv.altNames) {\n gLocalConfig.altNames = argv.altNames.split(\";\");\n }\n gLocalConfig.dns = [getFullyQualifiedDomainName()];\n if (argv.dns) {\n gLocalConfig.dns = argv.dns.split(\",\").map(performSubstitution);\n }\n gLocalConfig.ip = [];\n if (argv.ip) {\n gLocalConfig.ip = argv.ip.split(\",\");\n }\n if (argv.keySize) {\n const v = argv.keySize;\n if (v !== 1024 && v !== 2048 && v !== 3072 && v !== 4096) {\n throw new Error(`invalid keysize specified ${v} should be 1024,2048,3072 or 4096`);\n }\n gLocalConfig.keySize = argv.keySize;\n }\n\n if (argv.validity) {\n gLocalConfig.validity = argv.validity;\n }\n // xx displayConfig(g_config);\n // ------------------------------------------------------------------------------------------------------------\n}\n\nasync function createDefaultCertificate(\n base_name: string,\n prefix: string,\n key_length: KeySize,\n applicationUri: string,\n dev: boolean\n) {\n // possible key length in bits\n assert(key_length === 1024 || key_length === 2048 || key_length === 3072 || key_length === 4096);\n\n const private_key_file = makePath(base_name, `${prefix}key_${key_length}.pem`);\n const public_key_file = makePath(base_name, `${prefix}public_key_${key_length}.pub`);\n const certificate_file = makePath(base_name, `${prefix}cert_${key_length}.pem`);\n const certificate_file_outofdate = makePath(base_name, `${prefix}cert_${key_length}_outofdate.pem`);\n const certificate_file_not_active_yet = makePath(base_name, `${prefix}cert_${key_length}_not_active_yet.pem`);\n const certificate_revoked = makePath(base_name, `${prefix}cert_${key_length}_revoked.pem`);\n const self_signed_certificate_file = makePath(base_name, `${prefix}selfsigned_cert_${key_length}.pem`);\n\n const fqdn = getFullyQualifiedDomainName();\n const hostname = os.hostname();\n const dns: string[] = [\n // for conformance reason, localhost shall not be present in the DNS field of COP\n // ***FORBIDEN** \"localhost\",\n getFullyQualifiedDomainName()\n ];\n if (hostname !== fqdn) {\n dns.push(hostname);\n }\n\n const ip: string[] = [];\n\n async function createCertificateIfNotExist(\n certificate: Filename,\n private_key: Filename,\n applicationUri: string,\n startDate: Date,\n validity: number\n ): Promise<string> {\n // istanbul ignore next\n if (fs.existsSync(certificate)) {\n warningLog(chalk.yellow(\" certificate\"), chalk.cyan(certificate), chalk.yellow(\" already exists => skipping\"));\n return \"\";\n } else {\n return await createCertificate(certificate, private_key, applicationUri, startDate, validity);\n }\n }\n\n async function createCertificate(\n certificate: Filename,\n privateKey: Filename,\n applicationUri: string,\n startDate: Date,\n validity: number\n ): Promise<string> {\n const certificateSigningRequestFile = `${certificate}.csr`;\n\n const configFile = makePath(base_name, \"../certificates/PKI/own/openssl.cnf\");\n\n const dns = [os.hostname()];\n const ip = [\"127.0.0.1\"];\n\n const params: CreateCertificateSigningRequestWithConfigOptions = {\n applicationUri,\n privateKey,\n rootDir: \".\",\n configFile,\n dns,\n ip,\n purpose: CertificatePurpose.ForApplication\n };\n\n // create CSR\n await createCertificateSigningRequestWithOpenSSL(certificateSigningRequestFile, params);\n\n return await g_certificateAuthority.signCertificateRequest(certificate, certificateSigningRequestFile, {\n applicationUri,\n dns,\n ip,\n startDate,\n validity\n });\n }\n\n async function createSelfSignedCertificate(\n certificate: Filename,\n private_key: Filename,\n applicationUri: string,\n startDate: Date,\n validity: number\n ) {\n await g_certificateAuthority.createSelfSignedCertificate(certificate, private_key, {\n applicationUri,\n dns,\n ip,\n startDate,\n validity\n });\n }\n\n async function revoke_certificate(certificate: Filename) {\n await g_certificateAuthority.revokeCertificate(certificate, {});\n }\n\n async function createPrivateKeyIfNotExist(privateKey: Filename, keyLength: KeySize) {\n if (fs.existsSync(privateKey)) {\n warningLog(chalk.yellow(\" privateKey\"), chalk.cyan(privateKey), chalk.yellow(\" already exists => skipping\"));\n return;\n } else {\n await generatePrivateKeyFile(privateKey, keyLength);\n }\n }\n\n displaySubtitle(` create private key :${private_key_file}`);\n\n await createPrivateKeyIfNotExist(private_key_file, key_length);\n displaySubtitle(` extract public key ${public_key_file} from private key `);\n await getPublicKeyFromPrivateKey(private_key_file, public_key_file);\n displaySubtitle(` create Certificate ${certificate_file}`);\n\n await createCertificateIfNotExist(certificate_file, private_key_file, applicationUri, yesterday, 365);\n\n displaySubtitle(` create self signed Certificate ${self_signed_certificate_file}`);\n\n if (fs.existsSync(self_signed_certificate_file)) {\n // self_signed certificate already exists\n return;\n }\n await createSelfSignedCertificate(self_signed_certificate_file, private_key_file, applicationUri, yesterday, 365);\n\n if (dev) {\n await createCertificateIfNotExist(certificate_file_outofdate, private_key_file, applicationUri, two_years_ago, 365);\n\n await createCertificateIfNotExist(certificate_file_not_active_yet, private_key_file, applicationUri, next_year, 365);\n\n if (!fs.existsSync(certificate_revoked)) {\n // self_signed certificate already exists\n const certificate = await createCertificateIfNotExist(\n certificate_revoked,\n private_key_file,\n `${applicationUri}Revoked`, // make sure we used a uniq URI here\n yesterday,\n 365\n );\n warningLog(\" certificate to revoke => \", certificate);\n // must be awaited: `openssl ca -revoke` / `-gencrl` rewrite index.txt\n // (index.txt.new -> rename), and a concurrent `openssl ca` signing the\n // next key size's certificate can open index.txt in the window where\n // it does not exist (\"Problem with index file ... no such file\")\n await revoke_certificate(certificate_revoked);\n }\n }\n}\n\nasync function wrap(func: () => Promise<void>) {\n try {\n await func();\n } catch (err) {\n console.log((err as Error).message);\n }\n}\n\nasync function create_default_certificates(dev: boolean) {\n assert(gLocalConfig);\n const base_name = gLocalConfig.certificateDir || \"\";\n assert(fs.existsSync(base_name));\n\n let clientURN: string;\n let serverURN: string;\n let discoveryServerURN: string;\n await wrap(async () => {\n await extractFullyQualifiedDomainName();\n const hostname = os.hostname();\n const fqdn = getFullyQualifiedDomainName();\n warningLog(chalk.yellow(\" hostname = \"), chalk.cyan(hostname));\n warningLog(chalk.yellow(\" fqdn = \"), chalk.cyan(fqdn));\n clientURN = makeApplicationUrn(hostname, \"NodeOPCUA-Client\");\n serverURN = makeApplicationUrn(hostname, \"NodeOPCUA-Server\");\n discoveryServerURN = makeApplicationUrn(hostname, \"NodeOPCUA-DiscoveryServer\");\n\n displayTitle(\"Create Application Certificate for Server & its private key\");\n await createDefaultCertificate(base_name, \"client_\", 1024, clientURN, dev);\n await createDefaultCertificate(base_name, \"client_\", 2048, clientURN, dev);\n await createDefaultCertificate(base_name, \"client_\", 3072, clientURN, dev);\n await createDefaultCertificate(base_name, \"client_\", 4096, clientURN, dev);\n\n displayTitle(\"Create Application Certificate for Client & its private key\");\n await createDefaultCertificate(base_name, \"server_\", 1024, serverURN, dev);\n await createDefaultCertificate(base_name, \"server_\", 2048, serverURN, dev);\n await createDefaultCertificate(base_name, \"server_\", 3072, serverURN, dev);\n await createDefaultCertificate(base_name, \"server_\", 4096, serverURN, dev);\n\n displayTitle(\"Create Application Certificate for DiscoveryServer & its private key\");\n await createDefaultCertificate(base_name, \"discoveryServer_\", 1024, discoveryServerURN, dev);\n await createDefaultCertificate(base_name, \"discoveryServer_\", 2048, discoveryServerURN, dev);\n await createDefaultCertificate(base_name, \"discoveryServer_\", 3072, discoveryServerURN, dev);\n await createDefaultCertificate(base_name, \"discoveryServer_\", 4096, discoveryServerURN, dev);\n });\n}\n\nasync function createDefaultCertificates(dev: boolean) {\n await construct_CertificateAuthority(\"\");\n await construct_CertificateManager();\n await create_default_certificates(dev);\n}\n\nimport commandLineArgs from \"command-line-args\";\nimport commandLineUsage from \"command-line-usage\";\n\nconst commonOptions = [\n {\n name: \"root\",\n alias: \"r\",\n type: String,\n defaultValue: \"{CWD}/certificates\",\n description: \"the location of the Certificate folder\"\n },\n {\n name: \"CAFolder\",\n alias: \"c\",\n type: String,\n defaultValue: \"{root}/CA\",\n description: \"the location of the Certificate Authority folder\"\n },\n { name: \"PKIFolder\", type: String, defaultValue: \"{root}/PKI\", description: \"the location of the Public Key Infrastructure\" },\n { name: \"silent\", type: Boolean, defaultValue: false, description: \"minimize output\" },\n {\n name: \"privateKey\",\n alias: \"p\",\n type: String,\n defaultValue: \"{PKIFolder}/own/private_key.pem\",\n description: \"the private key to use to generate certificate\"\n },\n {\n name: \"keySize\",\n alias: \"k\",\n type: Number,\n defaultValue: 2048,\n description: \"the private key size in bits (1024|2048|3072|4096)\"\n },\n { name: \"help\", alias: \"h\", type: Boolean, description: \"display this help\" }\n];\n\nfunction getOptions(names: string[]) {\n return commonOptions.filter((o) => names.includes(o.name) || o.name === \"help\" || o.name === \"silent\");\n}\n\nfunction showHelp(command: string, description: string, options: Record<string, unknown>[], usage?: string) {\n const sections = [\n {\n header: `Command: ${command}`,\n content: description\n },\n {\n header: \"Usage\",\n content: usage || `$0 ${command} [options]`\n },\n {\n header: \"Options\",\n optionList: options\n }\n ];\n console.log(commandLineUsage(sections));\n}\n\nexport async function main(argumentsList: string | string[]) {\n const mainDefinitions = [{ name: \"command\", defaultOption: true }];\n let mainOptions: commandLineArgs.CommandLineOptions;\n try {\n mainOptions = commandLineArgs(mainDefinitions, { argv: argumentsList as string[], stopAtFirstUnknown: true });\n } catch (err) {\n console.log((err as Error).message);\n return;\n }\n\n const argv = mainOptions._unknown || [];\n const command = mainOptions.command;\n\n if (!command || command === \"help\") {\n console.log(\n commandLineUsage([\n {\n header: \"node-opcua-pki\",\n content: `PKI management for node-opcua\\n\\n${epilog}`\n },\n {\n header: \"Commands\",\n content: [\n { name: \"demo\", summary: \"create default certificate for node-opcua demos\" },\n { name: \"createCA\", summary: \"create a Certificate Authority\" },\n { name: \"createPKI\", summary: \"create a Public Key Infrastructure\" },\n { name: \"certificate\", summary: \"create a new certificate\" },\n { name: \"revoke <certificateFile>\", summary: \"revoke a existing certificate\" },\n { name: \"csr\", summary: \"create a certificate signing request\" },\n { name: \"sign\", summary: \"validate a certificate signing request and generate a certificate\" },\n { name: \"dump <certificateFile>\", summary: \"display a certificate\" },\n { name: \"toder <pemCertificate>\", summary: \"convert a certificate to a DER format with finger print\" },\n { name: \"fingerprint <certificateFile>\", summary: \"print the certificate fingerprint\" },\n { name: \"version\", summary: \"display the version number\" }\n ]\n }\n ])\n );\n return;\n }\n\n if (command === \"version\") {\n const rootFolder = find_module_root_folder();\n const pkg = JSON.parse(fs.readFileSync(path.join(rootFolder, \"package.json\"), \"utf-8\"));\n console.log(pkg.version);\n return;\n }\n\n if (command === \"demo\") {\n const optionsDef = [\n ...getOptions([\"root\", \"silent\"]),\n { name: \"dev\", type: Boolean, description: \"create all sort of fancy certificates for dev testing purposes\" },\n { name: \"clean\", type: Boolean, description: \"Purge existing directory [use with care!]\" }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help)\n return showHelp(\n \"demo\",\n \"create default certificate for node-opcua demos\",\n optionsDef,\n \"$0 demo [--dev] [--silent] [--clean]\"\n );\n\n await wrap(async () => {\n await ensure_openssl_installed();\n displayChapter(\"Create Demo certificates\");\n displayTitle(\"reading configuration\");\n await readConfiguration(local_argv as unknown as IReadConfigurationOpts);\n if (local_argv.clean) {\n displayTitle(\"Cleaning old certificates\");\n assert(gLocalConfig);\n const certificateDir = gLocalConfig.certificateDir || \"\";\n const files = await fs.promises.readdir(certificateDir);\n for (const file of files) {\n if (file.includes(\".pem\") || file.includes(\".pub\")) {\n await fs.promises.unlink(path.join(certificateDir, file));\n }\n }\n mkdirRecursiveSync(certificateDir);\n }\n displayTitle(\"create certificates\");\n await createDefaultCertificates(local_argv.dev);\n displayChapter(\"Demo certificates CREATED\");\n });\n return;\n }\n\n if (command === \"createCA\") {\n const optionsDef = [\n ...getOptions([\"root\", \"CAFolder\", \"keySize\", \"silent\"]),\n { name: \"subject\", type: String, defaultValue: defaultSubject, description: \"the CA certificate subject\" }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help) return showHelp(\"createCA\", \"create a Certificate Authority\", optionsDef);\n\n await wrap(async () => {\n await ensure_openssl_installed();\n await readConfiguration(local_argv as unknown as IReadConfigurationOpts);\n await construct_CertificateAuthority(local_argv.subject);\n });\n return;\n }\n\n if (command === \"createPKI\") {\n const optionsDef = getOptions([\"root\", \"PKIFolder\", \"keySize\", \"silent\"]);\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help) return showHelp(\"createPKI\", \"create a Public Key Infrastructure\", optionsDef);\n\n await wrap(async () => {\n await readConfiguration(local_argv as unknown as IReadConfigurationOpts);\n await construct_CertificateManager();\n });\n return;\n }\n\n if (command === \"certificate\") {\n const optionsDef = [\n ...getOptions([\"root\", \"CAFolder\", \"PKIFolder\", \"privateKey\", \"silent\"]),\n {\n name: \"applicationUri\",\n alias: \"a\",\n type: String,\n defaultValue: \"urn:{hostname}:Node-OPCUA-Server\",\n description: \"the application URI\"\n },\n {\n name: \"output\",\n alias: \"o\",\n type: String,\n defaultValue: \"my_certificate.pem\",\n description: \"the name of the generated certificate =>\"\n },\n {\n name: \"selfSigned\",\n alias: \"s\",\n type: Boolean,\n defaultValue: false,\n description: \"if true, certificate will be self-signed\"\n },\n { name: \"validity\", alias: \"v\", type: Number, description: \"the certificate validity in days\" },\n {\n name: \"dns\",\n type: String,\n defaultValue: \"{hostname}\",\n description: \"the list of valid domain name (comma separated)\"\n },\n { name: \"ip\", type: String, defaultValue: \"\", description: \"the list of valid IPs (comma separated)\" },\n {\n name: \"subject\",\n type: String,\n defaultValue: \"\",\n description: \"the certificate subject ( for instance C=FR/ST=Centre/L=Orleans/O=SomeOrganization/CN=Hello )\"\n }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help || !local_argv.applicationUri || !local_argv.output)\n return showHelp(\"certificate\", \"create a new certificate\", optionsDef);\n\n async function command_certificate(local_argv: IReadConfigurationOpts) {\n const selfSigned = !!(local_argv as unknown as { selfSigned?: boolean }).selfSigned;\n if (!selfSigned) {\n await command_full_certificate(local_argv);\n } else {\n await command_selfsigned_certificate(local_argv);\n }\n }\n\n async function command_selfsigned_certificate(local_argv: IReadConfigurationOpts) {\n const _fqdn = await extractFullyQualifiedDomainName();\n await readConfiguration(local_argv);\n await construct_CertificateManager();\n\n displaySubtitle(` create self signed Certificate ${gLocalConfig.outputFile}`);\n let subject =\n local_argv.subject && local_argv.subject.length > 1 ? new Subject(local_argv.subject) : gLocalConfig.subject || \"\";\n\n subject = JSON.parse(JSON.stringify(subject));\n\n const params: CreateSelfSignCertificateParam1 = {\n applicationUri: gLocalConfig.applicationUri || \"\",\n dns: gLocalConfig.dns || [],\n ip: gLocalConfig.ip || [],\n outputFile: gLocalConfig.outputFile || \"self_signed_certificate.pem\",\n startDate: gLocalConfig.startDate || new Date(),\n subject,\n validity: gLocalConfig.validity || 365\n };\n\n await certificateManager.createSelfSignedCertificate(params);\n }\n\n async function command_full_certificate(local_argv: IReadConfigurationOpts) {\n await readConfiguration(local_argv);\n await construct_CertificateManager();\n await construct_CertificateAuthority(\"\");\n assert(fs.existsSync(gLocalConfig.CAFolder || \"\"), \" CA folder must exist\");\n gLocalConfig.privateKey = undefined; // use PKI private key\n // create a Certificate Request from the certificate Manager\n\n gLocalConfig.subject = local_argv.subject && local_argv.subject.length > 1 ? local_argv.subject : gLocalConfig.subject;\n\n const csr_file = await certificateManager.createCertificateRequest(\n gLocalConfig as Parameters<typeof certificateManager.createCertificateRequest>[0]\n );\n if (!csr_file) {\n return;\n }\n warningLog(\" csr_file = \", csr_file);\n const certificate = csr_file.replace(\".csr\", \".pem\");\n\n if (fs.existsSync(certificate)) {\n throw new Error(` File ${certificate} already exist`);\n }\n await g_certificateAuthority.signCertificateRequest(\n certificate,\n csr_file,\n gLocalConfig as Parameters<typeof g_certificateAuthority.signCertificateRequest>[2]\n );\n\n assert(typeof gLocalConfig.outputFile === \"string\");\n fs.writeFileSync(gLocalConfig.outputFile || \"\", fs.readFileSync(certificate, \"ascii\"));\n }\n\n await wrap(async () => await command_certificate(local_argv as unknown as IReadConfigurationOpts));\n return;\n }\n\n if (command === \"revoke\") {\n const optionsDef = [{ name: \"certificateFile\", type: String, defaultOption: true }, ...getOptions([\"root\", \"CAFolder\"])];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help || !local_argv.certificateFile)\n return showHelp(\n \"revoke <certificateFile>\",\n \"revoke a existing certificate\",\n optionsDef,\n \"$0 revoke my_certificate.pem\"\n );\n\n async function revoke_certificate(certificate: Filename) {\n await g_certificateAuthority.revokeCertificate(certificate, {});\n }\n\n await wrap(async () => {\n const certificate = path.resolve(local_argv.certificateFile);\n warningLog(chalk.yellow(\" Certificate to revoke : \"), chalk.cyan(certificate));\n if (!fs.existsSync(certificate)) {\n throw new Error(`cannot find certificate to revoke ${certificate}`);\n }\n await readConfiguration(local_argv as unknown as IReadConfigurationOpts);\n await construct_CertificateAuthority(\"\");\n await revoke_certificate(certificate);\n warningLog(\"done ... \");\n warningLog(\" crl = \", g_certificateAuthority.revocationList);\n warningLog(\"\\nyou should now publish the new Certificate Revocation List\");\n });\n return;\n }\n\n if (command === \"csr\") {\n const optionsDef = [\n ...getOptions([\"root\", \"PKIFolder\", \"privateKey\", \"silent\"]),\n {\n name: \"applicationUri\",\n alias: \"a\",\n type: String,\n defaultValue: \"urn:{hostname}:Node-OPCUA-Server\",\n description: \"the application URI\"\n },\n {\n name: \"output\",\n alias: \"o\",\n type: String,\n defaultValue: \"my_certificate_signing_request.csr\",\n description: \"the name of the generated signing_request\"\n },\n {\n name: \"dns\",\n type: String,\n defaultValue: \"{hostname}\",\n description: \"the list of valid domain name (comma separated)\"\n },\n { name: \"ip\", type: String, defaultValue: \"\", description: \"the list of valid IPs (comma separated)\" },\n {\n name: \"subject\",\n type: String,\n defaultValue: \"/CN=Certificate\",\n description: \"the certificate subject ( for instance /C=FR/ST=Centre/L=Orleans/O=SomeOrganization/CN=Hello )\"\n }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help) return showHelp(\"csr\", \"create a certificate signing request\", optionsDef);\n\n await wrap(async () => {\n await readConfiguration(local_argv as unknown as IReadConfigurationOpts);\n if (!fs.existsSync(gLocalConfig.PKIFolder || \"\")) {\n warningLog(\"PKI folder must exist\");\n }\n await construct_CertificateManager();\n if (!gLocalConfig.outputFile || fs.existsSync(gLocalConfig.outputFile)) {\n throw new Error(` File ${gLocalConfig.outputFile} already exist`);\n }\n gLocalConfig.privateKey = undefined; // use PKI private key\n // create a Certificate Request from the certificate Manager\n\n gLocalConfig.subject = local_argv.subject && local_argv.subject.length > 1 ? local_argv.subject : gLocalConfig.subject;\n\n const internal_csr_file = await certificateManager.createCertificateRequest(\n gLocalConfig as Parameters<typeof certificateManager.createCertificateRequest>[0]\n );\n if (!internal_csr_file) {\n return;\n }\n if (!gLocalConfig.outputFile) {\n warningLog(\"please specify a output file\");\n return;\n }\n const csr = await fs.promises.readFile(internal_csr_file, \"utf-8\");\n fs.writeFileSync(gLocalConfig.outputFile || \"\", csr, \"utf-8\");\n\n warningLog(\"Subject = \", gLocalConfig.subject);\n warningLog(\"applicationUri = \", gLocalConfig.applicationUri);\n warningLog(\"altNames = \", gLocalConfig.altNames);\n warningLog(\"dns = \", gLocalConfig.dns);\n warningLog(\"ip = \", gLocalConfig.ip);\n\n warningLog(\"CSR file = \", gLocalConfig.outputFile);\n });\n return;\n }\n\n if (command === \"sign\") {\n const optionsDef = [\n ...getOptions([\"root\", \"CAFolder\", \"silent\"]),\n { name: \"csr\", alias: \"i\", type: String, defaultValue: \"my_certificate_signing_request.csr\", description: \"the csr\" },\n {\n name: \"output\",\n alias: \"o\",\n type: String,\n defaultValue: \"my_certificate.pem\",\n description: \"the name of the generated certificate\"\n },\n { name: \"validity\", alias: \"v\", type: Number, defaultValue: 365, description: \"the certificate validity in days\" }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help || !local_argv.csr || !local_argv.output)\n return showHelp(\"sign\", \"validate a certificate signing request and generate a certificate\", optionsDef);\n\n await wrap(async () => {\n await readConfiguration(local_argv as unknown as IReadConfigurationOpts);\n if (!fs.existsSync(gLocalConfig.CAFolder || \"\")) {\n throw new Error(`CA folder must exist:${gLocalConfig.CAFolder}`);\n }\n await construct_CertificateAuthority(\"\");\n const csr_file: string = path.resolve((local_argv as unknown as { csr?: string }).csr || \"\");\n if (!fs.existsSync(csr_file)) {\n throw new Error(`Certificate signing request doesn't exist: ${csr_file}`);\n }\n const certificate = path.resolve(local_argv.output || csr_file.replace(\".csr\", \".pem\"));\n if (fs.existsSync(certificate)) {\n throw new Error(` File ${certificate} already exist`);\n }\n\n await g_certificateAuthority.signCertificateRequest(\n certificate,\n csr_file,\n gLocalConfig as Parameters<typeof g_certificateAuthority.signCertificateRequest>[2]\n );\n\n assert(typeof gLocalConfig.outputFile === \"string\");\n fs.writeFileSync(gLocalConfig.outputFile || \"\", fs.readFileSync(certificate, \"ascii\"));\n });\n return;\n }\n\n if (command === \"dump\") {\n const optionsDef = [\n { name: \"certificateFile\", type: String, defaultOption: true },\n { name: \"help\", alias: \"h\", type: Boolean }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help || !local_argv.certificateFile)\n return showHelp(\"dump <certificateFile>\", \"display a certificate\", optionsDef);\n\n await wrap(async () => {\n const data = await dumpCertificate(local_argv.certificateFile);\n warningLog(data);\n });\n return;\n }\n\n if (command === \"toder\") {\n const optionsDef = [\n { name: \"pemCertificate\", type: String, defaultOption: true },\n { name: \"help\", alias: \"h\", type: Boolean }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help || !local_argv.pemCertificate)\n return showHelp(\"toder <pemCertificate>\", \"convert a certificate to a DER format with finger print\", optionsDef);\n\n await wrap(async () => {\n await toDer(local_argv.pemCertificate);\n });\n return;\n }\n\n if (command === \"fingerprint\") {\n const optionsDef = [\n { name: \"certificateFile\", type: String, defaultOption: true },\n { name: \"help\", alias: \"h\", type: Boolean }\n ];\n const local_argv = commandLineArgs(optionsDef, { argv });\n if (local_argv.help || !local_argv.certificateFile)\n return showHelp(\"fingerprint <certificateFile>\", \"print the certificate fingerprint\", optionsDef);\n\n await wrap(async () => {\n const certificate = local_argv.certificateFile;\n const data = await fingerprint(certificate);\n if (!data) return;\n const s = data.split(\"=\")[1].split(\":\").join(\"\").trim();\n warningLog(s);\n });\n return;\n }\n\n console.log(`Unknown command: ${command}`);\n}\n","#!/usr/bin/env node\nimport { main as pki_main } from \"../lib/ca/crypto_create_CA\";\n\npki_main(process.argv.splice(2));\n"],"mappings":";;;;;;;;;;AAsBA,OAAO,YAAY;AACnB,SAAS,kBAAkB;AAEpB,SAAS,mBAAmB,UAAkB,QAAwB;AAKzE,MAAI,eAAe;AACnB,MAAI,aAAa,SAAS,IAAI,OAAO,UAAU,IAAI;AAG/C,mBAAe,WAAW,KAAK,EAAE,OAAO,QAAQ,EAAE,OAAO,KAAK,EAAE,UAAU,GAAG,EAAE;AAAA,EACnF;AAEA,QAAM,iBAAiB,OAAO,YAAY,IAAI,MAAM;AACpD,SAAO,eAAe,UAAU,EAAE;AAClC,SAAO;AACX;AAxCA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGA,OAAO,SAAS;AAChB,OAAO,QAAQ;AACf,SAAS,iBAAiB;AAE1B,SAAS,KAAK,KAAa,QAAyB;AAChD,MAAI,CAAC,QAAQ;AACT,WAAO;AAAA,EACX;AACA,SAAO,IAAI,UAAU,GAAG,KAAK,IAAI,IAAI,QAAQ,MAAM,CAAC;AACxD;AAEA,SAAS,KAAK,UAAsD;AAChE,QAAM,OAAO,GAAG,SAAS;AAEzB,MAAI,OAAO,MAAM,EAAE,OAAO,IAAI,WAAW,GAAG,CAAC,MAAoB,OAAe;AAC5E,QAAI,MAAM;AACN,aAAO,SAAS,IAAI;AAAA,IACxB;AAEA,QAAI,cAAc,IAAI,GAAG,CAAC,MAAoB,UAA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AAO;AAAA,QACP,MAAM;AAAA,QACN,cAAc;AAAA,QACd,aAAa;AAAA,MACjB;AAAA,MACA,EAAE,MAAM,QAAQ,OAAO,KAAK,MAAM,SAAS,aAAa,oBAAoB;AAAA,IAChF;AAAA;AAAA;;;AC1kBA;AAAA;AAAA;AACA;AAEA,SAAS,QAAQ,KAAK,OAAO,CAAC,CAAC;AAAA;AAAA;","names":["assert","assert","chalk","assert","fs","assert","fs","coercePrivateKeyPem","pemToPrivateKey","Subject","fs","path","chalk","fingerprint","ChainCompletionStatus","today","Subject","fs","os","path","chalk","doDebug","opensslFolder","opensslExecPath","opensslPath","assert","child_process","fs","os","byline","chalk","execute","display","assert","fs","path","n","s","init_toolbox","assert","fs","path","Subject","n","init_create_certificate_signing_request","init_toolbox","init_create_certificate_signing_request","init_toolbox","fs","path","fs","path","CertificatePurpose","createCertificateSigningRequest","readPrivateKey","Subject","dns","fs","path","Subject","n","config","assert","fs","os","path","withLock","chalk","CertificatePurpose","convertPEMtoDER","createCertificateSigningRequest","exploreCertificate","generatePrivateKeyFile","privateKeyToCryptoKey","readCertificatePEM","readPrivateKey","Subject","toPem","verifyCertificateSignature","writePrivateKeyFile","x509","config","dns","assert","fs","os","path","chalk","CertificatePurpose","generatePrivateKeyFile","Subject","default_config_template","fqdn","dns","applicationUri","ip","createSelfSignedCertificate","local_argv"]}