node-opcua-pki 6.8.2 → 6.10.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.
package/dist/index.d.mts CHANGED
@@ -148,6 +148,25 @@ interface CertificateAuthorityOptions {
148
148
  * await ca.initialize();
149
149
  * ```
150
150
  */
151
+ /**
152
+ * A record from the OpenSSL CA certificate database
153
+ * (`index.txt`).
154
+ */
155
+ interface IssuedCertificateRecord {
156
+ /** Hex-encoded serial number (e.g. `"1000"`). */
157
+ serial: string;
158
+ /** Certificate status. */
159
+ status: "valid" | "revoked" | "expired";
160
+ /** X.500 subject string (slash-delimited). */
161
+ subject: string;
162
+ /** Certificate expiry date as ISO-8601 string. */
163
+ expiryDate: string;
164
+ /**
165
+ * Revocation date as ISO-8601 string.
166
+ * Only present when `status === "revoked"`.
167
+ */
168
+ revocationDate?: string;
169
+ }
151
170
  declare class CertificateAuthority {
152
171
  /** RSA key size used when generating the CA private key. */
153
172
  readonly keySize: KeySize;
@@ -177,6 +196,116 @@ declare class CertificateAuthority {
177
196
  * Used by OpenSSL for CRL-based verification.
178
197
  */
179
198
  get caCertificateWithCrl(): string;
199
+ /**
200
+ * Return the CA certificate as a DER-encoded buffer.
201
+ *
202
+ * @throws if the CA certificate file does not exist
203
+ * (call {@link initialize} first).
204
+ */
205
+ getCACertificateDER(): Buffer;
206
+ /**
207
+ * Return the CA certificate as a PEM-encoded string.
208
+ *
209
+ * @throws if the CA certificate file does not exist
210
+ * (call {@link initialize} first).
211
+ */
212
+ getCACertificatePEM(): string;
213
+ /**
214
+ * Return the current Certificate Revocation List as a
215
+ * DER-encoded buffer.
216
+ *
217
+ * Returns an empty buffer if no CRL has been generated yet.
218
+ */
219
+ getCRLDER(): Buffer;
220
+ /**
221
+ * Return the current Certificate Revocation List as a
222
+ * PEM-encoded string.
223
+ *
224
+ * Returns an empty string if no CRL has been generated yet.
225
+ */
226
+ getCRLPEM(): string;
227
+ /**
228
+ * Return a list of all issued certificates recorded in the
229
+ * OpenSSL `index.txt` database.
230
+ *
231
+ * Each entry includes the serial number, subject, status,
232
+ * expiry date, and (for revoked certs) the revocation date.
233
+ */
234
+ getIssuedCertificates(): IssuedCertificateRecord[];
235
+ /**
236
+ * Return the total number of certificates recorded in
237
+ * `index.txt`.
238
+ */
239
+ getIssuedCertificateCount(): number;
240
+ /**
241
+ * Return the status of a certificate by its serial number.
242
+ *
243
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
244
+ * @returns `"valid"`, `"revoked"`, `"expired"`, or
245
+ * `undefined` if not found
246
+ */
247
+ getCertificateStatus(serial: string): "valid" | "revoked" | "expired" | undefined;
248
+ /**
249
+ * Read a specific issued certificate by serial number and
250
+ * return its content as a DER-encoded buffer.
251
+ *
252
+ * OpenSSL stores signed certificates in the `certs/`
253
+ * directory using the naming convention `<SERIAL>.pem`.
254
+ *
255
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
256
+ * @returns the DER buffer, or `undefined` if not found
257
+ */
258
+ getCertificateBySerial(serial: string): Buffer | undefined;
259
+ /**
260
+ * Path to the OpenSSL certificate database file.
261
+ */
262
+ get indexFile(): string;
263
+ /**
264
+ * Parse the OpenSSL `index.txt` certificate database.
265
+ *
266
+ * Each line has tab-separated fields:
267
+ * ```
268
+ * status expiry [revocationDate] serial unknown subject
269
+ * ```
270
+ *
271
+ * - status: `V` (valid), `R` (revoked), `E` (expired)
272
+ * - expiry: `YYMMDDHHmmssZ`
273
+ * - revocationDate: present only for revoked certs
274
+ * - serial: hex string
275
+ * - unknown: always `"unknown"`
276
+ * - subject: X.500 slash-delimited string
277
+ */
278
+ private _parseIndexTxt;
279
+ /**
280
+ * Sign a DER-encoded Certificate Signing Request and return
281
+ * the signed certificate as a DER buffer.
282
+ *
283
+ * This method handles temp-file creation and cleanup
284
+ * internally so that callers can work with in-memory
285
+ * buffers only.
286
+ *
287
+ * @param csrDer - the CSR as a DER-encoded buffer
288
+ * @param options - signing options
289
+ * @param options.validity - certificate validity in days
290
+ * (default: 365)
291
+ * @returns the signed certificate as a DER-encoded buffer
292
+ */
293
+ signCertificateRequestFromDER(csrDer: Buffer, options?: {
294
+ validity?: number;
295
+ }): Promise<Buffer>;
296
+ /**
297
+ * Revoke a DER-encoded certificate and regenerate the CRL.
298
+ *
299
+ * Extracts the serial number from the certificate, then
300
+ * uses the stored cert file at `certs/<serial>.pem` for
301
+ * revocation — avoiding temp-file PEM format mismatches.
302
+ *
303
+ * @param certDer - the certificate as a DER-encoded buffer
304
+ * @param reason - CRL reason code
305
+ * (default: `"keyCompromise"`)
306
+ * @throws if the certificate's serial is not found in the CA
307
+ */
308
+ revokeCertificateDER(certDer: Buffer, reason?: string): Promise<void>;
180
309
  /**
181
310
  * Initialize the CA directory structure, generate the CA
182
311
  * private key and self-signed certificate if they do not
package/dist/index.d.ts CHANGED
@@ -148,6 +148,25 @@ interface CertificateAuthorityOptions {
148
148
  * await ca.initialize();
149
149
  * ```
150
150
  */
151
+ /**
152
+ * A record from the OpenSSL CA certificate database
153
+ * (`index.txt`).
154
+ */
155
+ interface IssuedCertificateRecord {
156
+ /** Hex-encoded serial number (e.g. `"1000"`). */
157
+ serial: string;
158
+ /** Certificate status. */
159
+ status: "valid" | "revoked" | "expired";
160
+ /** X.500 subject string (slash-delimited). */
161
+ subject: string;
162
+ /** Certificate expiry date as ISO-8601 string. */
163
+ expiryDate: string;
164
+ /**
165
+ * Revocation date as ISO-8601 string.
166
+ * Only present when `status === "revoked"`.
167
+ */
168
+ revocationDate?: string;
169
+ }
151
170
  declare class CertificateAuthority {
152
171
  /** RSA key size used when generating the CA private key. */
153
172
  readonly keySize: KeySize;
@@ -177,6 +196,116 @@ declare class CertificateAuthority {
177
196
  * Used by OpenSSL for CRL-based verification.
178
197
  */
179
198
  get caCertificateWithCrl(): string;
199
+ /**
200
+ * Return the CA certificate as a DER-encoded buffer.
201
+ *
202
+ * @throws if the CA certificate file does not exist
203
+ * (call {@link initialize} first).
204
+ */
205
+ getCACertificateDER(): Buffer;
206
+ /**
207
+ * Return the CA certificate as a PEM-encoded string.
208
+ *
209
+ * @throws if the CA certificate file does not exist
210
+ * (call {@link initialize} first).
211
+ */
212
+ getCACertificatePEM(): string;
213
+ /**
214
+ * Return the current Certificate Revocation List as a
215
+ * DER-encoded buffer.
216
+ *
217
+ * Returns an empty buffer if no CRL has been generated yet.
218
+ */
219
+ getCRLDER(): Buffer;
220
+ /**
221
+ * Return the current Certificate Revocation List as a
222
+ * PEM-encoded string.
223
+ *
224
+ * Returns an empty string if no CRL has been generated yet.
225
+ */
226
+ getCRLPEM(): string;
227
+ /**
228
+ * Return a list of all issued certificates recorded in the
229
+ * OpenSSL `index.txt` database.
230
+ *
231
+ * Each entry includes the serial number, subject, status,
232
+ * expiry date, and (for revoked certs) the revocation date.
233
+ */
234
+ getIssuedCertificates(): IssuedCertificateRecord[];
235
+ /**
236
+ * Return the total number of certificates recorded in
237
+ * `index.txt`.
238
+ */
239
+ getIssuedCertificateCount(): number;
240
+ /**
241
+ * Return the status of a certificate by its serial number.
242
+ *
243
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
244
+ * @returns `"valid"`, `"revoked"`, `"expired"`, or
245
+ * `undefined` if not found
246
+ */
247
+ getCertificateStatus(serial: string): "valid" | "revoked" | "expired" | undefined;
248
+ /**
249
+ * Read a specific issued certificate by serial number and
250
+ * return its content as a DER-encoded buffer.
251
+ *
252
+ * OpenSSL stores signed certificates in the `certs/`
253
+ * directory using the naming convention `<SERIAL>.pem`.
254
+ *
255
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
256
+ * @returns the DER buffer, or `undefined` if not found
257
+ */
258
+ getCertificateBySerial(serial: string): Buffer | undefined;
259
+ /**
260
+ * Path to the OpenSSL certificate database file.
261
+ */
262
+ get indexFile(): string;
263
+ /**
264
+ * Parse the OpenSSL `index.txt` certificate database.
265
+ *
266
+ * Each line has tab-separated fields:
267
+ * ```
268
+ * status expiry [revocationDate] serial unknown subject
269
+ * ```
270
+ *
271
+ * - status: `V` (valid), `R` (revoked), `E` (expired)
272
+ * - expiry: `YYMMDDHHmmssZ`
273
+ * - revocationDate: present only for revoked certs
274
+ * - serial: hex string
275
+ * - unknown: always `"unknown"`
276
+ * - subject: X.500 slash-delimited string
277
+ */
278
+ private _parseIndexTxt;
279
+ /**
280
+ * Sign a DER-encoded Certificate Signing Request and return
281
+ * the signed certificate as a DER buffer.
282
+ *
283
+ * This method handles temp-file creation and cleanup
284
+ * internally so that callers can work with in-memory
285
+ * buffers only.
286
+ *
287
+ * @param csrDer - the CSR as a DER-encoded buffer
288
+ * @param options - signing options
289
+ * @param options.validity - certificate validity in days
290
+ * (default: 365)
291
+ * @returns the signed certificate as a DER-encoded buffer
292
+ */
293
+ signCertificateRequestFromDER(csrDer: Buffer, options?: {
294
+ validity?: number;
295
+ }): Promise<Buffer>;
296
+ /**
297
+ * Revoke a DER-encoded certificate and regenerate the CRL.
298
+ *
299
+ * Extracts the serial number from the certificate, then
300
+ * uses the stored cert file at `certs/<serial>.pem` for
301
+ * revocation — avoiding temp-file PEM format mismatches.
302
+ *
303
+ * @param certDer - the certificate as a DER-encoded buffer
304
+ * @param reason - CRL reason code
305
+ * (default: `"keyCompromise"`)
306
+ * @throws if the certificate's serial is not found in the CA
307
+ */
308
+ revokeCertificateDER(certDer: Buffer, reason?: string): Promise<void>;
180
309
  /**
181
310
  * Initialize the CA directory structure, generate the CA
182
311
  * private key and self-signed certificate if they do not
package/dist/index.js CHANGED
@@ -53,6 +53,7 @@ module.exports = __toCommonJS(lib_exports);
53
53
  // packages/node-opcua-pki/lib/ca/certificate_authority.ts
54
54
  var import_node_assert6 = __toESM(require("assert"));
55
55
  var import_node_fs6 = __toESM(require("fs"));
56
+ var import_node_os3 = __toESM(require("os"));
56
57
  var import_node_path5 = __toESM(require("path"));
57
58
  var import_chalk5 = __toESM(require("chalk"));
58
59
  var import_node_opcua_crypto2 = require("node-opcua-crypto");
@@ -754,8 +755,7 @@ subjectAltName = $ENV::ALTNAME
754
755
  nsComment = "CA Generated by Node-OPCUA Certificate utility using openssl"
755
756
  [ v3_ca ]
756
757
  subjectKeyIdentifier = hash
757
- authorityKeyIdentifier = keyid:always,issuer:always
758
- # authorityKeyIdentifier = keyid
758
+ authorityKeyIdentifier = keyid
759
759
  basicConstraints = CA:TRUE
760
760
  keyUsage = critical, cRLSign, keyCertSign
761
761
  nsComment = "CA Certificate generated by Node-OPCUA Certificate utility using openssl"
@@ -866,6 +866,18 @@ async function regenerateCrl(revocationList, configOption, options) {
866
866
  displaySubtitle("Display (Certificate Revocation List)");
867
867
  await execute_openssl(`crl -in ${q(n2(revocationList))} -text -noout`, options);
868
868
  }
869
+ function parseOpenSSLDate(dateStr) {
870
+ const raw = dateStr?.split(",")[0] ?? "";
871
+ if (raw.length < 12) return "";
872
+ const yy = parseInt(raw.substring(0, 2), 10);
873
+ const year = yy >= 70 ? 1900 + yy : 2e3 + yy;
874
+ const month = raw.substring(2, 4);
875
+ const day = raw.substring(4, 6);
876
+ const hour = raw.substring(6, 8);
877
+ const min = raw.substring(8, 10);
878
+ const sec = raw.substring(10, 12);
879
+ return `${year}-${month}-${day}T${hour}:${min}:${sec}Z`;
880
+ }
869
881
  var CertificateAuthority = class {
870
882
  /** RSA key size used when generating the CA private key. */
871
883
  keySize;
@@ -913,6 +925,244 @@ var CertificateAuthority = class {
913
925
  get caCertificateWithCrl() {
914
926
  return makePath(this.rootDir, "./public/cacertificate_with_crl.pem");
915
927
  }
928
+ // ---------------------------------------------------------------
929
+ // Buffer-based accessors (US-059)
930
+ // ---------------------------------------------------------------
931
+ /**
932
+ * Return the CA certificate as a DER-encoded buffer.
933
+ *
934
+ * @throws if the CA certificate file does not exist
935
+ * (call {@link initialize} first).
936
+ */
937
+ getCACertificateDER() {
938
+ const pem = (0, import_node_opcua_crypto2.readCertificatePEM)(this.caCertificate);
939
+ return (0, import_node_opcua_crypto2.convertPEMtoDER)(pem);
940
+ }
941
+ /**
942
+ * Return the CA certificate as a PEM-encoded string.
943
+ *
944
+ * @throws if the CA certificate file does not exist
945
+ * (call {@link initialize} first).
946
+ */
947
+ getCACertificatePEM() {
948
+ const raw = (0, import_node_opcua_crypto2.readCertificatePEM)(this.caCertificate);
949
+ const beginMarker = "-----BEGIN CERTIFICATE-----";
950
+ const idx = raw.indexOf(beginMarker);
951
+ if (idx > 0) {
952
+ return raw.substring(idx);
953
+ }
954
+ return raw;
955
+ }
956
+ /**
957
+ * Return the current Certificate Revocation List as a
958
+ * DER-encoded buffer.
959
+ *
960
+ * Returns an empty buffer if no CRL has been generated yet.
961
+ */
962
+ getCRLDER() {
963
+ const crlPath = this.revocationListDER;
964
+ if (!import_node_fs6.default.existsSync(crlPath)) {
965
+ return Buffer.alloc(0);
966
+ }
967
+ return import_node_fs6.default.readFileSync(crlPath);
968
+ }
969
+ /**
970
+ * Return the current Certificate Revocation List as a
971
+ * PEM-encoded string.
972
+ *
973
+ * Returns an empty string if no CRL has been generated yet.
974
+ */
975
+ getCRLPEM() {
976
+ const crlPath = this.revocationList;
977
+ if (!import_node_fs6.default.existsSync(crlPath)) {
978
+ return "";
979
+ }
980
+ const raw = import_node_fs6.default.readFileSync(crlPath, "utf-8");
981
+ const beginMarker = "-----BEGIN X509 CRL-----";
982
+ const idx = raw.indexOf(beginMarker);
983
+ if (idx > 0) {
984
+ return raw.substring(idx);
985
+ }
986
+ return raw;
987
+ }
988
+ // ---------------------------------------------------------------
989
+ // Certificate database API (US-057)
990
+ // ---------------------------------------------------------------
991
+ /**
992
+ * Return a list of all issued certificates recorded in the
993
+ * OpenSSL `index.txt` database.
994
+ *
995
+ * Each entry includes the serial number, subject, status,
996
+ * expiry date, and (for revoked certs) the revocation date.
997
+ */
998
+ getIssuedCertificates() {
999
+ return this._parseIndexTxt();
1000
+ }
1001
+ /**
1002
+ * Return the total number of certificates recorded in
1003
+ * `index.txt`.
1004
+ */
1005
+ getIssuedCertificateCount() {
1006
+ return this._parseIndexTxt().length;
1007
+ }
1008
+ /**
1009
+ * Return the status of a certificate by its serial number.
1010
+ *
1011
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
1012
+ * @returns `"valid"`, `"revoked"`, `"expired"`, or
1013
+ * `undefined` if not found
1014
+ */
1015
+ getCertificateStatus(serial) {
1016
+ const upper = serial.toUpperCase();
1017
+ const record = this._parseIndexTxt().find((r) => r.serial.toUpperCase() === upper);
1018
+ return record?.status;
1019
+ }
1020
+ /**
1021
+ * Read a specific issued certificate by serial number and
1022
+ * return its content as a DER-encoded buffer.
1023
+ *
1024
+ * OpenSSL stores signed certificates in the `certs/`
1025
+ * directory using the naming convention `<SERIAL>.pem`.
1026
+ *
1027
+ * @param serial - hex-encoded serial number (e.g. `"1000"`)
1028
+ * @returns the DER buffer, or `undefined` if not found
1029
+ */
1030
+ getCertificateBySerial(serial) {
1031
+ const upper = serial.toUpperCase();
1032
+ const certFile = import_node_path5.default.join(this.rootDir, "certs", `${upper}.pem`);
1033
+ if (!import_node_fs6.default.existsSync(certFile)) {
1034
+ return void 0;
1035
+ }
1036
+ const pem = (0, import_node_opcua_crypto2.readCertificatePEM)(certFile);
1037
+ return (0, import_node_opcua_crypto2.convertPEMtoDER)(pem);
1038
+ }
1039
+ /**
1040
+ * Path to the OpenSSL certificate database file.
1041
+ */
1042
+ get indexFile() {
1043
+ return import_node_path5.default.join(this.rootDir, "index.txt");
1044
+ }
1045
+ /**
1046
+ * Parse the OpenSSL `index.txt` certificate database.
1047
+ *
1048
+ * Each line has tab-separated fields:
1049
+ * ```
1050
+ * status expiry [revocationDate] serial unknown subject
1051
+ * ```
1052
+ *
1053
+ * - status: `V` (valid), `R` (revoked), `E` (expired)
1054
+ * - expiry: `YYMMDDHHmmssZ`
1055
+ * - revocationDate: present only for revoked certs
1056
+ * - serial: hex string
1057
+ * - unknown: always `"unknown"`
1058
+ * - subject: X.500 slash-delimited string
1059
+ */
1060
+ _parseIndexTxt() {
1061
+ const indexPath = this.indexFile;
1062
+ if (!import_node_fs6.default.existsSync(indexPath)) {
1063
+ return [];
1064
+ }
1065
+ const content = import_node_fs6.default.readFileSync(indexPath, "utf-8");
1066
+ const lines = content.split("\n").filter((l) => l.trim().length > 0);
1067
+ const records = [];
1068
+ for (const line of lines) {
1069
+ const fields = line.split(" ");
1070
+ if (fields.length < 4) continue;
1071
+ const statusChar = fields[0];
1072
+ const expiryStr = fields[1];
1073
+ let serial;
1074
+ let subject;
1075
+ let revocationDate;
1076
+ if (statusChar === "R") {
1077
+ revocationDate = fields[2];
1078
+ serial = fields[3];
1079
+ subject = fields.length >= 6 ? fields[5] : "";
1080
+ } else {
1081
+ serial = fields[3];
1082
+ subject = fields.length >= 6 ? fields[5] : "";
1083
+ }
1084
+ let status;
1085
+ switch (statusChar) {
1086
+ case "V":
1087
+ status = "valid";
1088
+ break;
1089
+ case "R":
1090
+ status = "revoked";
1091
+ break;
1092
+ case "E":
1093
+ status = "expired";
1094
+ break;
1095
+ default:
1096
+ continue;
1097
+ }
1098
+ records.push({
1099
+ serial,
1100
+ status,
1101
+ subject,
1102
+ expiryDate: parseOpenSSLDate(expiryStr),
1103
+ revocationDate: revocationDate ? parseOpenSSLDate(revocationDate) : void 0
1104
+ });
1105
+ }
1106
+ return records;
1107
+ }
1108
+ // ---------------------------------------------------------------
1109
+ // Buffer-based CA operations (US-058)
1110
+ // ---------------------------------------------------------------
1111
+ /**
1112
+ * Sign a DER-encoded Certificate Signing Request and return
1113
+ * the signed certificate as a DER buffer.
1114
+ *
1115
+ * This method handles temp-file creation and cleanup
1116
+ * internally so that callers can work with in-memory
1117
+ * buffers only.
1118
+ *
1119
+ * @param csrDer - the CSR as a DER-encoded buffer
1120
+ * @param options - signing options
1121
+ * @param options.validity - certificate validity in days
1122
+ * (default: 365)
1123
+ * @returns the signed certificate as a DER-encoded buffer
1124
+ */
1125
+ async signCertificateRequestFromDER(csrDer, options) {
1126
+ const validity = options?.validity ?? 365;
1127
+ const tmpDir = await import_node_fs6.default.promises.mkdtemp(import_node_path5.default.join(import_node_os3.default.tmpdir(), "pki-sign-"));
1128
+ try {
1129
+ const csrFile = import_node_path5.default.join(tmpDir, "request.csr");
1130
+ const certFile = import_node_path5.default.join(tmpDir, "certificate.pem");
1131
+ const csrPem = (0, import_node_opcua_crypto2.toPem)(csrDer, "CERTIFICATE REQUEST");
1132
+ await import_node_fs6.default.promises.writeFile(csrFile, csrPem, "utf-8");
1133
+ await this.signCertificateRequest(certFile, csrFile, { validity });
1134
+ const certPem = (0, import_node_opcua_crypto2.readCertificatePEM)(certFile);
1135
+ return (0, import_node_opcua_crypto2.convertPEMtoDER)(certPem);
1136
+ } finally {
1137
+ await import_node_fs6.default.promises.rm(tmpDir, {
1138
+ recursive: true,
1139
+ force: true
1140
+ });
1141
+ }
1142
+ }
1143
+ /**
1144
+ * Revoke a DER-encoded certificate and regenerate the CRL.
1145
+ *
1146
+ * Extracts the serial number from the certificate, then
1147
+ * uses the stored cert file at `certs/<serial>.pem` for
1148
+ * revocation — avoiding temp-file PEM format mismatches.
1149
+ *
1150
+ * @param certDer - the certificate as a DER-encoded buffer
1151
+ * @param reason - CRL reason code
1152
+ * (default: `"keyCompromise"`)
1153
+ * @throws if the certificate's serial is not found in the CA
1154
+ */
1155
+ async revokeCertificateDER(certDer, reason) {
1156
+ const info = (0, import_node_opcua_crypto2.exploreCertificate)(certDer);
1157
+ const serial = info.tbsCertificate.serialNumber.replace(/:/g, "").toUpperCase();
1158
+ const storedCertFile = import_node_path5.default.join(this.rootDir, "certs", `${serial}.pem`);
1159
+ if (!import_node_fs6.default.existsSync(storedCertFile)) {
1160
+ throw new Error(`Cannot revoke: no stored certificate found for serial ${serial} at ${storedCertFile}`);
1161
+ }
1162
+ await this.revokeCertificate(storedCertFile, {
1163
+ reason: reason ?? "keyCompromise"
1164
+ });
1165
+ }
916
1166
  /**
917
1167
  * Initialize the CA directory structure, generate the CA
918
1168
  * private key and self-signed certificate if they do not