node-opcua-server-configuration 2.75.0 → 2.76.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 (36) hide show
  1. package/dist/clientTools/index.d.ts +1 -1
  2. package/dist/clientTools/index.js +17 -17
  3. package/dist/clientTools/push_certificate_management_client.d.ts +176 -176
  4. package/dist/clientTools/push_certificate_management_client.js +463 -463
  5. package/dist/index.d.ts +10 -10
  6. package/dist/index.js +27 -27
  7. package/dist/push_certificate_manager.d.ts +141 -141
  8. package/dist/push_certificate_manager.js +2 -2
  9. package/dist/server/install_certificate_file_watcher.d.ts +5 -5
  10. package/dist/server/install_certificate_file_watcher.js +23 -23
  11. package/dist/server/install_push_certitifate_management.d.ts +19 -19
  12. package/dist/server/install_push_certitifate_management.js +213 -213
  13. package/dist/server/promote_trust_list.d.ts +6 -6
  14. package/dist/server/promote_trust_list.js +175 -175
  15. package/dist/server/push_certificate_manager_helpers.d.ts +4 -4
  16. package/dist/server/push_certificate_manager_helpers.js +410 -409
  17. package/dist/server/push_certificate_manager_helpers.js.map +1 -1
  18. package/dist/server/push_certificate_manager_server_impl.d.ts +49 -49
  19. package/dist/server/push_certificate_manager_server_impl.js +522 -522
  20. package/dist/server/roles_and_permissions.d.ts +3 -3
  21. package/dist/server/roles_and_permissions.js +40 -40
  22. package/dist/server/tools.d.ts +3 -3
  23. package/dist/server/tools.js +19 -19
  24. package/dist/server/trust_list_server.d.ts +13 -13
  25. package/dist/server/trust_list_server.js +89 -89
  26. package/dist/standard_certificate_types.d.ts +6 -6
  27. package/dist/standard_certificate_types.js +13 -13
  28. package/dist/trust_list.d.ts +79 -79
  29. package/dist/trust_list.js +2 -2
  30. package/dist/trust_list_impl.js +25 -25
  31. package/package.json +27 -27
  32. package/source/server/push_certificate_manager_helpers.ts +3 -3
  33. package/dist/server/install_CertificateAlarm.d.ts +0 -11
  34. package/dist/server/install_CertificateAlarm.js +0 -46
  35. package/dist/server/install_CertificateAlarm.js.map +0 -1
  36. package/source/server/install_CertificateAlarm.ts +0 -56
@@ -1,523 +1,523 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __asyncValues = (this && this.__asyncValues) || function (o) {
12
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
- var m = o[Symbol.asyncIterator], i;
14
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
- };
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.PushCertificateManagerServerImpl = exports.subjectToString = exports.moveFileWithBackup = exports.moveFile = exports.deleteFile = exports.copyFile = exports.certificateMatchesPrivateKey = void 0;
20
- /**
21
- * @module node-opcua-server-configuration-server
22
- */
23
- const events_1 = require("events");
24
- const fs = require("fs");
25
- const path = require("path");
26
- const util_1 = require("util");
27
- const rimraf = require("rimraf");
28
- const node_opcua_assert_1 = require("node-opcua-assert");
29
- const node_opcua_basic_types_1 = require("node-opcua-basic-types");
30
- const node_opcua_crypto_1 = require("node-opcua-crypto");
31
- const node_opcua_debug_1 = require("node-opcua-debug");
32
- const node_opcua_nodeid_1 = require("node-opcua-nodeid");
33
- const node_opcua_certificate_manager_1 = require("node-opcua-certificate-manager");
34
- // node 14 onward : import { readFile, writeFile, readdir } from "fs/promises";
35
- const { readFile, writeFile, readdir } = fs.promises;
36
- const debugLog = (0, node_opcua_debug_1.make_debugLog)("ServerConfiguration");
37
- const errorLog = (0, node_opcua_debug_1.make_errorLog)("ServerConfiguration");
38
- const warningLog = (0, node_opcua_debug_1.make_warningLog)("ServerConfiguration");
39
- const doDebug = (0, node_opcua_debug_1.checkDebugFlag)("ServerConfiguration");
40
- const defaultApplicationGroup = (0, node_opcua_nodeid_1.resolveNodeId)("ServerConfiguration_CertificateGroups_DefaultApplicationGroup");
41
- const defaultHttpsGroup = (0, node_opcua_nodeid_1.resolveNodeId)("ServerConfiguration_CertificateGroups_DefaultHttpsGroup");
42
- const defaultUserTokenGroup = (0, node_opcua_nodeid_1.resolveNodeId)("ServerConfiguration_CertificateGroups_DefaultUserTokenGroup");
43
- /**
44
- * check that the given certificate matches the given private key
45
- * @param certificate
46
- * @param privateKey
47
- */
48
- function certificateMatchesPrivateKeyPEM(certificate, privateKey) {
49
- const initialBuffer = Buffer.from("Lorem Ipsum");
50
- const encryptedBuffer = (0, node_opcua_crypto_1.publicEncrypt_long)(initialBuffer, certificate, 256, 11);
51
- const decryptedBuffer = (0, node_opcua_crypto_1.privateDecrypt_long)(encryptedBuffer, privateKey, 256);
52
- return initialBuffer.toString("utf-8") === decryptedBuffer.toString("utf-8");
53
- }
54
- function certificateMatchesPrivateKey(certificate, privateKey) {
55
- const certificatePEM = (0, node_opcua_crypto_1.toPem)(certificate, "CERTIFICATE");
56
- const privateKeyPEM = (0, node_opcua_crypto_1.toPem)(privateKey, "RSA PRIVATE KEY");
57
- return certificateMatchesPrivateKeyPEM(certificatePEM, privateKeyPEM);
58
- }
59
- exports.certificateMatchesPrivateKey = certificateMatchesPrivateKey;
60
- function findCertificateGroupName(certificateGroupNodeId) {
61
- if (typeof certificateGroupNodeId === "string") {
62
- return certificateGroupNodeId;
63
- }
64
- if ((0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, node_opcua_nodeid_1.NodeId.nullNodeId) || (0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, defaultApplicationGroup)) {
65
- return "DefaultApplicationGroup";
66
- }
67
- if ((0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, defaultHttpsGroup)) {
68
- return "DefaultHttpsGroup";
69
- }
70
- if ((0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, defaultUserTokenGroup)) {
71
- return "DefaultUserTokenGroup";
72
- }
73
- return "";
74
- }
75
- function copyFile(source, dest) {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- try {
78
- debugLog("copying file \n source ", source, "\n =>\n dest ", dest);
79
- const sourceExist = fs.existsSync(source);
80
- if (sourceExist) {
81
- yield fs.promises.copyFile(source, dest);
82
- }
83
- }
84
- catch (err) {
85
- errorLog(err);
86
- }
87
- });
88
- }
89
- exports.copyFile = copyFile;
90
- function deleteFile(file) {
91
- return __awaiter(this, void 0, void 0, function* () {
92
- try {
93
- const exists = yield fs.existsSync(file);
94
- if (exists) {
95
- debugLog("deleting file ", file);
96
- yield fs.promises.unlink(file);
97
- }
98
- }
99
- catch (err) {
100
- errorLog(err);
101
- }
102
- });
103
- }
104
- exports.deleteFile = deleteFile;
105
- function moveFile(source, dest) {
106
- return __awaiter(this, void 0, void 0, function* () {
107
- debugLog("moving file file \n source ", source, "\n =>\n dest ", dest);
108
- try {
109
- yield copyFile(source, dest);
110
- yield deleteFile(source);
111
- }
112
- catch (err) {
113
- errorLog(err);
114
- }
115
- });
116
- }
117
- exports.moveFile = moveFile;
118
- function moveFileWithBackup(source, dest) {
119
- return __awaiter(this, void 0, void 0, function* () {
120
- // let make a copy of the destination file
121
- debugLog("moveFileWithBackup file \n source ", source, "\n =>\n dest ", dest);
122
- yield copyFile(dest, dest + "_old");
123
- yield moveFile(source, dest);
124
- });
125
- }
126
- exports.moveFileWithBackup = moveFileWithBackup;
127
- function subjectToString(subject) {
128
- let s = "";
129
- subject.commonName && (s += `/CN=${subject.commonName}`);
130
- subject.country && (s += `/C=${subject.country}`);
131
- subject.countryName && (s += `/C=${subject.countryName}`);
132
- subject.domainComponent && (s += `/DC=${subject.domainComponent}`);
133
- subject.locality && (s += `/L=${subject.locality}`);
134
- subject.localityName && (s += `/L=${subject.localityName}`);
135
- subject.organization && (s += `/O=${subject.organization}`);
136
- subject.organizationName && (s += `/O=${subject.organizationName}`);
137
- subject.organizationUnitName && (s += `/OU=${subject.organizationUnitName}`);
138
- subject.state && (s += `/ST=${subject.state}`);
139
- subject.stateOrProvinceName && (s += `/ST=${subject.stateOrProvinceName}`);
140
- return s;
141
- }
142
- exports.subjectToString = subjectToString;
143
- let fileCounter = 0;
144
- class PushCertificateManagerServerImpl extends events_1.EventEmitter {
145
- constructor(options) {
146
- super();
147
- this._map = {};
148
- this._pendingTasks = [];
149
- this.$$actionQueue = [];
150
- this.applicationUri = options ? options.applicationUri : "";
151
- if (options) {
152
- this.applicationGroup = options.applicationGroup;
153
- this.userTokenGroup = options.userTokenGroup;
154
- this.httpsGroup = options.httpsGroup;
155
- if (this.userTokenGroup) {
156
- this._map.DefaultUserTokenGroup = this.userTokenGroup;
157
- // istanbul ignore next
158
- if (!(this.userTokenGroup instanceof node_opcua_certificate_manager_1.CertificateManager)) {
159
- errorLog("Expecting this.userTokenGroup to be instanceof CertificateManager :", this.userTokenGroup.constructor.name);
160
- throw new Error("Expecting this.userTokenGroup to be instanceof CertificateManager ");
161
- }
162
- }
163
- if (this.applicationGroup) {
164
- this._map.DefaultApplicationGroup = this.applicationGroup;
165
- (0, node_opcua_assert_1.assert)(this.applicationGroup instanceof node_opcua_certificate_manager_1.CertificateManager);
166
- }
167
- if (this.httpsGroup) {
168
- this._map.DefaultHttpsGroup = this.httpsGroup;
169
- (0, node_opcua_assert_1.assert)(this.httpsGroup instanceof node_opcua_certificate_manager_1.CertificateManager);
170
- }
171
- }
172
- }
173
- initialize() {
174
- return __awaiter(this, void 0, void 0, function* () {
175
- if (this.applicationGroup) {
176
- yield this.applicationGroup.initialize();
177
- }
178
- if (this.userTokenGroup) {
179
- yield this.userTokenGroup.initialize();
180
- }
181
- if (this.httpsGroup) {
182
- yield this.httpsGroup.initialize();
183
- }
184
- });
185
- }
186
- get supportedPrivateKeyFormats() {
187
- return ["PEM"];
188
- }
189
- getSupportedPrivateKeyFormats() {
190
- return __awaiter(this, void 0, void 0, function* () {
191
- return this.supportedPrivateKeyFormats;
192
- });
193
- }
194
- createSigningRequest(certificateGroupId, certificateTypeId, subjectName, regeneratePrivateKey, nonce) {
195
- return __awaiter(this, void 0, void 0, function* () {
196
- let certificateManager = this.getCertificateManager(certificateGroupId);
197
- if (!certificateManager) {
198
- debugLog(" cannot find group ", certificateGroupId);
199
- return {
200
- statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidArgument
201
- };
202
- }
203
- if (!subjectName) {
204
- // reuse existing subjectName
205
- const currentCertificateFilename = path.join(certificateManager.rootDir, "own/certs/certificate.pem");
206
- if (!fs.existsSync(currentCertificateFilename)) {
207
- errorLog("Cannot find existing certificate to extract subjectName", currentCertificateFilename);
208
- return {
209
- statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidState
210
- };
211
- }
212
- const certificate = (0, node_opcua_crypto_1.readCertificate)(currentCertificateFilename);
213
- const e = (0, node_opcua_crypto_1.exploreCertificate)(certificate);
214
- subjectName = subjectToString(e.tbsCertificate.subject);
215
- warningLog("reusing existing certificate subjectAltName = ", subjectName);
216
- }
217
- // todo : at this time regenerate PrivateKey is not supported
218
- if (regeneratePrivateKey) {
219
- // The Server shall create a new Private Key which it stores until the
220
- // matching signed Certificate is uploaded with the UpdateCertificate Method.
221
- // Previously created Private Keys may be discarded if UpdateCertificate was not
222
- // called before calling this method again.
223
- // Additional entropy which the caller shall provide if regeneratePrivateKey is TRUE.
224
- // It shall be at least 32 bytes long
225
- if (!nonce || nonce.length < 32) {
226
- (0, node_opcua_debug_1.make_warningLog)(" nonce should be provided when regeneratePrivateKey is set, and length shall be greater than 32 bytes");
227
- return {
228
- statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidArgument
229
- };
230
- }
231
- const location = path.join(certificateManager.rootDir, "tmp");
232
- if (fs.existsSync(location)) {
233
- yield (0, util_1.promisify)(rimraf)(path.join(location));
234
- }
235
- if (!fs.existsSync(location)) {
236
- yield fs.promises.mkdir(location);
237
- }
238
- const destCertificateManager = certificateManager;
239
- const keySize = certificateManager.keySize; // because keySize is private !
240
- certificateManager = new node_opcua_certificate_manager_1.CertificateManager({
241
- keySize,
242
- location,
243
- });
244
- debugLog("generating a new private key ...");
245
- yield certificateManager.initialize();
246
- this._tmpCertificateManager = certificateManager;
247
- this.addPendingTask(() => __awaiter(this, void 0, void 0, function* () {
248
- yield moveFileWithBackup(certificateManager.privateKey, destCertificateManager.privateKey);
249
- }));
250
- this.addPendingTask(() => __awaiter(this, void 0, void 0, function* () {
251
- yield (0, util_1.promisify)(rimraf)(path.join(location));
252
- }));
253
- }
254
- else {
255
- // The Server uses its existing Private Key
256
- }
257
- if (typeof subjectName !== "string") {
258
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadInternalError };
259
- }
260
- const options = {
261
- applicationUri: this.applicationUri,
262
- subject: subjectName
263
- };
264
- yield certificateManager.initialize();
265
- const csrFile = yield certificateManager.createCertificateRequest(options);
266
- const csrPEM = yield readFile(csrFile, "utf8");
267
- const certificateSigningRequest = (0, node_opcua_crypto_1.convertPEMtoDER)(csrPEM);
268
- this.addPendingTask(() => deleteFile(csrFile));
269
- return {
270
- certificateSigningRequest,
271
- statusCode: node_opcua_basic_types_1.StatusCodes.Good
272
- };
273
- });
274
- }
275
- getRejectedList() {
276
- return __awaiter(this, void 0, void 0, function* () {
277
- // rejectedList comes from each group
278
- function extractRejectedList(group, certificateList) {
279
- return __awaiter(this, void 0, void 0, function* () {
280
- if (!group) {
281
- return;
282
- }
283
- const rejectedFolder = path.join(group.rootDir, "rejected");
284
- const files = yield readdir(rejectedFolder);
285
- const stat = fs.promises.stat;
286
- const promises1 = [];
287
- for (const certFile of files) {
288
- // read date
289
- promises1.push(stat(path.join(rejectedFolder, certFile)));
290
- }
291
- const stats = yield Promise.all(promises1);
292
- for (let i = 0; i < stats.length; i++) {
293
- certificateList.push({
294
- filename: path.join(rejectedFolder, files[i]),
295
- stat: stats[i]
296
- });
297
- }
298
- });
299
- }
300
- const list = [];
301
- yield extractRejectedList(this.applicationGroup, list);
302
- yield extractRejectedList(this.userTokenGroup, list);
303
- yield extractRejectedList(this.httpsGroup, list);
304
- // now sort list from newer file to older file
305
- list.sort((a, b) => b.stat.mtime.getTime() - a.stat.mtime.getTime());
306
- const promises = [];
307
- for (const item of list) {
308
- promises.push(readFile(item.filename, "utf8"));
309
- }
310
- const certificatesPEM = yield Promise.all(promises);
311
- const certificates = certificatesPEM.map(node_opcua_crypto_1.convertPEMtoDER);
312
- return {
313
- certificates,
314
- statusCode: node_opcua_basic_types_1.StatusCodes.Good
315
- };
316
- });
317
- }
318
- updateCertificate(certificateGroupId, certificateTypeId, certificate, issuerCertificates, privateKeyFormat, privateKey) {
319
- return __awaiter(this, void 0, void 0, function* () {
320
- // Result Code Description
321
- // BadInvalidArgument The certificateTypeId or certificateGroupId is not valid.
322
- // BadCertificateInvalid The Certificate is invalid or the format is not supported.
323
- // BadNotSupported The PrivateKey is invalid or the format is not supported.
324
- // BadUserAccessDenied The current user does not have the rights required.
325
- // BadSecurityChecksFailed Some failure occurred verifying the integrity of the Certificate.
326
- const certificateManager = this.getCertificateManager(certificateGroupId);
327
- if (!certificateManager) {
328
- debugLog(" cannot find group ", certificateGroupId);
329
- return {
330
- statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidArgument
331
- };
332
- }
333
- function preInstallCertificate(self) {
334
- return __awaiter(this, void 0, void 0, function* () {
335
- const certFolder = path.join(certificateManager.rootDir, "own/certs");
336
- const certificateFileDER = path.join(certFolder, `_pending_certificate${fileCounter++}.der`);
337
- const certificateFilePEM = path.join(certFolder, `_pending_certificate${fileCounter++}.pem`);
338
- yield writeFile(certificateFileDER, certificate, "binary");
339
- yield writeFile(certificateFilePEM, (0, node_opcua_crypto_1.toPem)(certificate, "CERTIFICATE"));
340
- const destDER = path.join(certFolder, "certificate.der");
341
- const destPEM = path.join(certFolder, "certificate.pem");
342
- // put existing file in security by backing them up
343
- self.addPendingTask(() => moveFileWithBackup(certificateFileDER, destDER));
344
- self.addPendingTask(() => moveFileWithBackup(certificateFilePEM, destPEM));
345
- });
346
- }
347
- function preInstallPrivateKey(self) {
348
- return __awaiter(this, void 0, void 0, function* () {
349
- (0, node_opcua_assert_1.assert)(privateKeyFormat.toUpperCase() === "PEM");
350
- (0, node_opcua_assert_1.assert)(privateKey instanceof Buffer); // could be DER or PEM in a buffer ?
351
- const ownPrivateFolder = path.join(certificateManager.rootDir, "own/private");
352
- const privateKeyFilePEM = path.join(ownPrivateFolder, `_pending_private_key${fileCounter++}.pem`);
353
- const privateKeyPEM = (0, node_opcua_crypto_1.toPem)(privateKey, "RSA PRIVATE KEY");
354
- yield writeFile(privateKeyFilePEM, privateKeyPEM, "utf-8");
355
- self.addPendingTask(() => moveFileWithBackup(privateKeyFilePEM, certificateManager.privateKey));
356
- });
357
- }
358
- // OPC Unified Architecture, Part 12 42 Release 1.04:
359
- //
360
- // UpdateCertificate is used to update a Certificate for a Server.
361
- // There are the following three use cases for this Method:
362
- //
363
- // - The new Certificate was created based on a signing request created with the Method
364
- // In this case there is no privateKey provided.
365
- // - A new privateKey and Certificate was created outside the Server and both are updated
366
- // with this Method.
367
- // - A new Certificate was created and signed with the information from the old Certificate.
368
- // In this case there is no privateKey provided.
369
- // The Server shall do all normal integrity checks on the Certificate and all of the issuer
370
- // Certificates. If errors occur the BadSecurityChecksFailed error is returned.
371
- // todo : all normal integrity check on the certificate
372
- const certInfo = (0, node_opcua_crypto_1.exploreCertificate)(certificate);
373
- const now = new Date();
374
- if (certInfo.tbsCertificate.validity.notBefore.getTime() > now.getTime()) {
375
- // certificate is not yet valid
376
- debugLog("Certificate is not yet valid");
377
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
378
- }
379
- if (certInfo.tbsCertificate.validity.notAfter.getTime() < now.getTime()) {
380
- // certificate is already out of date
381
- debugLog("Certificate is already out of date");
382
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
383
- }
384
- // If the Server returns applyChangesRequired=FALSE then it is indicating that it is able to
385
- // satisfy the requirements specified for the ApplyChanges Method.
386
- debugLog(" updateCertificate ", (0, node_opcua_crypto_1.makeSHA1Thumbprint)(certificate).toString("hex"));
387
- if (!privateKeyFormat || !privateKey) {
388
- // first of all we need to find the future private key;
389
- // this one may have been created during the creation of the certficate signing request
390
- // but is not active yet
391
- const privateKeyDER = (0, node_opcua_crypto_1.readPrivateKey)(this._tmpCertificateManager ? this._tmpCertificateManager.privateKey : certificateManager.privateKey);
392
- // The Server shall report an error if the public key does not match the existing Certificate and
393
- // the privateKey was not provided.
394
- // privateKey is not provided, so check that the public key matches the existing certificate
395
- if (!certificateMatchesPrivateKey(certificate, privateKeyDER)) {
396
- // certificate doesn't match privateKey
397
- debugLog("certificate doesn't match privateKey");
398
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
399
- }
400
- // a new certificate is provided for us,
401
- // we keep our private key
402
- // we do this in two stages
403
- yield preInstallCertificate(this);
404
- return {
405
- statusCode: node_opcua_basic_types_1.StatusCodes.Good
406
- };
407
- }
408
- else if (privateKey) {
409
- // a private key has been provided by the caller !
410
- if (!privateKeyFormat) {
411
- debugLog("the privateKeyFormat must be specified " + privateKeyFormat);
412
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported };
413
- }
414
- if (privateKeyFormat !== "PEM" && privateKeyFormat !== "PFX") {
415
- debugLog(" the private key format is invalid privateKeyFormat =" + privateKeyFormat);
416
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported };
417
- }
418
- if (privateKeyFormat !== "PEM") {
419
- debugLog("in NodeOPCUA we only support PEM for the moment privateKeyFormat =" + privateKeyFormat);
420
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported };
421
- }
422
- // privateKey is provided, so check that the public key matches provided private key
423
- if (!certificateMatchesPrivateKey(certificate, privateKey)) {
424
- // certificate doesn't match privateKey
425
- debugLog("certificate doesn't match privateKey");
426
- return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
427
- }
428
- yield preInstallPrivateKey(this);
429
- yield preInstallCertificate(this);
430
- return {
431
- statusCode: node_opcua_basic_types_1.StatusCodes.Good
432
- };
433
- }
434
- else {
435
- // todo !
436
- return {
437
- statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported
438
- };
439
- }
440
- });
441
- }
442
- applyChanges() {
443
- return __awaiter(this, void 0, void 0, function* () {
444
- // ApplyChanges is used to tell the Server to apply any security changes.
445
- // This Method should only be called if a previous call to a Method that changed the
446
- // configuration returns applyChangesRequired=true.
447
- //
448
- // If the Server Certificate has changed, Secure Channels using the old Certificate will
449
- // eventually be interrupted.
450
- this.emit("CertificateAboutToChange", this.$$actionQueue);
451
- yield this.flushActionQueue();
452
- try {
453
- yield this.applyPendingTasks();
454
- }
455
- catch (err) {
456
- debugLog("err ", err);
457
- return node_opcua_basic_types_1.StatusCodes.BadInternalError;
458
- }
459
- this.emit("CertificateChanged", this.$$actionQueue);
460
- yield this.flushActionQueue();
461
- // The only leeway the Server has is with the timing.
462
- // In the best case, the Server can close the TransportConnections for the affected Endpoints and leave any
463
- // Subscriptions intact. This should appear no different than a network interruption from the
464
- // perspective of the Client. The Client should be prepared to deal with Certificate changes
465
- // during its reconnect logic. In the worst case, a full shutdown which affects all connected
466
- // Clients will be necessary. In the latter case, the Server shall advertise its intent to interrupt
467
- // connections by setting the SecondsTillShutdown and ShutdownReason Properties in the
468
- // ServerStatus Variable.
469
- // If the Secure Channel being used to call this Method will be affected by the Certificate change
470
- // then the Server shall introduce a delay long enough to allow the caller to receive a reply.
471
- return node_opcua_basic_types_1.StatusCodes.Good;
472
- });
473
- }
474
- getCertificateManager(certificateGroupId) {
475
- const groupName = findCertificateGroupName(certificateGroupId);
476
- return this._map[groupName] || null;
477
- }
478
- addPendingTask(functor) {
479
- this._pendingTasks.push(functor);
480
- }
481
- applyPendingTasks() {
482
- var e_1, _a;
483
- return __awaiter(this, void 0, void 0, function* () {
484
- debugLog("start applyPendingTasks");
485
- const promises = [];
486
- const t = this._pendingTasks.splice(0);
487
- if (false) {
488
- try {
489
- // node 10.2 and above
490
- for (var t_1 = __asyncValues(t), t_1_1; t_1_1 = yield t_1.next(), !t_1_1.done;) {
491
- const task = t_1_1.value;
492
- yield task();
493
- }
494
- }
495
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
496
- finally {
497
- try {
498
- if (t_1_1 && !t_1_1.done && (_a = t_1.return)) yield _a.call(t_1);
499
- }
500
- finally { if (e_1) throw e_1.error; }
501
- }
502
- }
503
- else {
504
- while (t.length) {
505
- const task = t.shift();
506
- yield task();
507
- }
508
- }
509
- yield Promise.all(promises);
510
- debugLog("end applyPendingTasks");
511
- });
512
- }
513
- flushActionQueue() {
514
- return __awaiter(this, void 0, void 0, function* () {
515
- while (this.$$actionQueue.length) {
516
- const first = this.$$actionQueue.pop();
517
- yield first();
518
- }
519
- });
520
- }
521
- }
522
- exports.PushCertificateManagerServerImpl = PushCertificateManagerServerImpl;
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.PushCertificateManagerServerImpl = exports.subjectToString = exports.moveFileWithBackup = exports.moveFile = exports.deleteFile = exports.copyFile = exports.certificateMatchesPrivateKey = void 0;
20
+ /**
21
+ * @module node-opcua-server-configuration-server
22
+ */
23
+ const events_1 = require("events");
24
+ const fs = require("fs");
25
+ const path = require("path");
26
+ const util_1 = require("util");
27
+ const rimraf = require("rimraf");
28
+ const node_opcua_assert_1 = require("node-opcua-assert");
29
+ const node_opcua_basic_types_1 = require("node-opcua-basic-types");
30
+ const node_opcua_crypto_1 = require("node-opcua-crypto");
31
+ const node_opcua_debug_1 = require("node-opcua-debug");
32
+ const node_opcua_nodeid_1 = require("node-opcua-nodeid");
33
+ const node_opcua_certificate_manager_1 = require("node-opcua-certificate-manager");
34
+ // node 14 onward : import { readFile, writeFile, readdir } from "fs/promises";
35
+ const { readFile, writeFile, readdir } = fs.promises;
36
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)("ServerConfiguration");
37
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)("ServerConfiguration");
38
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)("ServerConfiguration");
39
+ const doDebug = (0, node_opcua_debug_1.checkDebugFlag)("ServerConfiguration");
40
+ const defaultApplicationGroup = (0, node_opcua_nodeid_1.resolveNodeId)("ServerConfiguration_CertificateGroups_DefaultApplicationGroup");
41
+ const defaultHttpsGroup = (0, node_opcua_nodeid_1.resolveNodeId)("ServerConfiguration_CertificateGroups_DefaultHttpsGroup");
42
+ const defaultUserTokenGroup = (0, node_opcua_nodeid_1.resolveNodeId)("ServerConfiguration_CertificateGroups_DefaultUserTokenGroup");
43
+ /**
44
+ * check that the given certificate matches the given private key
45
+ * @param certificate
46
+ * @param privateKey
47
+ */
48
+ function certificateMatchesPrivateKeyPEM(certificate, privateKey) {
49
+ const initialBuffer = Buffer.from("Lorem Ipsum");
50
+ const encryptedBuffer = (0, node_opcua_crypto_1.publicEncrypt_long)(initialBuffer, certificate, 256, 11);
51
+ const decryptedBuffer = (0, node_opcua_crypto_1.privateDecrypt_long)(encryptedBuffer, privateKey, 256);
52
+ return initialBuffer.toString("utf-8") === decryptedBuffer.toString("utf-8");
53
+ }
54
+ function certificateMatchesPrivateKey(certificate, privateKey) {
55
+ const certificatePEM = (0, node_opcua_crypto_1.toPem)(certificate, "CERTIFICATE");
56
+ const privateKeyPEM = (0, node_opcua_crypto_1.toPem)(privateKey, "RSA PRIVATE KEY");
57
+ return certificateMatchesPrivateKeyPEM(certificatePEM, privateKeyPEM);
58
+ }
59
+ exports.certificateMatchesPrivateKey = certificateMatchesPrivateKey;
60
+ function findCertificateGroupName(certificateGroupNodeId) {
61
+ if (typeof certificateGroupNodeId === "string") {
62
+ return certificateGroupNodeId;
63
+ }
64
+ if ((0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, node_opcua_nodeid_1.NodeId.nullNodeId) || (0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, defaultApplicationGroup)) {
65
+ return "DefaultApplicationGroup";
66
+ }
67
+ if ((0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, defaultHttpsGroup)) {
68
+ return "DefaultHttpsGroup";
69
+ }
70
+ if ((0, node_opcua_nodeid_1.sameNodeId)(certificateGroupNodeId, defaultUserTokenGroup)) {
71
+ return "DefaultUserTokenGroup";
72
+ }
73
+ return "";
74
+ }
75
+ function copyFile(source, dest) {
76
+ return __awaiter(this, void 0, void 0, function* () {
77
+ try {
78
+ debugLog("copying file \n source ", source, "\n =>\n dest ", dest);
79
+ const sourceExist = fs.existsSync(source);
80
+ if (sourceExist) {
81
+ yield fs.promises.copyFile(source, dest);
82
+ }
83
+ }
84
+ catch (err) {
85
+ errorLog(err);
86
+ }
87
+ });
88
+ }
89
+ exports.copyFile = copyFile;
90
+ function deleteFile(file) {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ try {
93
+ const exists = yield fs.existsSync(file);
94
+ if (exists) {
95
+ debugLog("deleting file ", file);
96
+ yield fs.promises.unlink(file);
97
+ }
98
+ }
99
+ catch (err) {
100
+ errorLog(err);
101
+ }
102
+ });
103
+ }
104
+ exports.deleteFile = deleteFile;
105
+ function moveFile(source, dest) {
106
+ return __awaiter(this, void 0, void 0, function* () {
107
+ debugLog("moving file file \n source ", source, "\n =>\n dest ", dest);
108
+ try {
109
+ yield copyFile(source, dest);
110
+ yield deleteFile(source);
111
+ }
112
+ catch (err) {
113
+ errorLog(err);
114
+ }
115
+ });
116
+ }
117
+ exports.moveFile = moveFile;
118
+ function moveFileWithBackup(source, dest) {
119
+ return __awaiter(this, void 0, void 0, function* () {
120
+ // let make a copy of the destination file
121
+ debugLog("moveFileWithBackup file \n source ", source, "\n =>\n dest ", dest);
122
+ yield copyFile(dest, dest + "_old");
123
+ yield moveFile(source, dest);
124
+ });
125
+ }
126
+ exports.moveFileWithBackup = moveFileWithBackup;
127
+ function subjectToString(subject) {
128
+ let s = "";
129
+ subject.commonName && (s += `/CN=${subject.commonName}`);
130
+ subject.country && (s += `/C=${subject.country}`);
131
+ subject.countryName && (s += `/C=${subject.countryName}`);
132
+ subject.domainComponent && (s += `/DC=${subject.domainComponent}`);
133
+ subject.locality && (s += `/L=${subject.locality}`);
134
+ subject.localityName && (s += `/L=${subject.localityName}`);
135
+ subject.organization && (s += `/O=${subject.organization}`);
136
+ subject.organizationName && (s += `/O=${subject.organizationName}`);
137
+ subject.organizationUnitName && (s += `/OU=${subject.organizationUnitName}`);
138
+ subject.state && (s += `/ST=${subject.state}`);
139
+ subject.stateOrProvinceName && (s += `/ST=${subject.stateOrProvinceName}`);
140
+ return s;
141
+ }
142
+ exports.subjectToString = subjectToString;
143
+ let fileCounter = 0;
144
+ class PushCertificateManagerServerImpl extends events_1.EventEmitter {
145
+ constructor(options) {
146
+ super();
147
+ this._map = {};
148
+ this._pendingTasks = [];
149
+ this.$$actionQueue = [];
150
+ this.applicationUri = options ? options.applicationUri : "";
151
+ if (options) {
152
+ this.applicationGroup = options.applicationGroup;
153
+ this.userTokenGroup = options.userTokenGroup;
154
+ this.httpsGroup = options.httpsGroup;
155
+ if (this.userTokenGroup) {
156
+ this._map.DefaultUserTokenGroup = this.userTokenGroup;
157
+ // istanbul ignore next
158
+ if (!(this.userTokenGroup instanceof node_opcua_certificate_manager_1.CertificateManager)) {
159
+ errorLog("Expecting this.userTokenGroup to be instanceof CertificateManager :", this.userTokenGroup.constructor.name);
160
+ throw new Error("Expecting this.userTokenGroup to be instanceof CertificateManager ");
161
+ }
162
+ }
163
+ if (this.applicationGroup) {
164
+ this._map.DefaultApplicationGroup = this.applicationGroup;
165
+ (0, node_opcua_assert_1.assert)(this.applicationGroup instanceof node_opcua_certificate_manager_1.CertificateManager);
166
+ }
167
+ if (this.httpsGroup) {
168
+ this._map.DefaultHttpsGroup = this.httpsGroup;
169
+ (0, node_opcua_assert_1.assert)(this.httpsGroup instanceof node_opcua_certificate_manager_1.CertificateManager);
170
+ }
171
+ }
172
+ }
173
+ initialize() {
174
+ return __awaiter(this, void 0, void 0, function* () {
175
+ if (this.applicationGroup) {
176
+ yield this.applicationGroup.initialize();
177
+ }
178
+ if (this.userTokenGroup) {
179
+ yield this.userTokenGroup.initialize();
180
+ }
181
+ if (this.httpsGroup) {
182
+ yield this.httpsGroup.initialize();
183
+ }
184
+ });
185
+ }
186
+ get supportedPrivateKeyFormats() {
187
+ return ["PEM"];
188
+ }
189
+ getSupportedPrivateKeyFormats() {
190
+ return __awaiter(this, void 0, void 0, function* () {
191
+ return this.supportedPrivateKeyFormats;
192
+ });
193
+ }
194
+ createSigningRequest(certificateGroupId, certificateTypeId, subjectName, regeneratePrivateKey, nonce) {
195
+ return __awaiter(this, void 0, void 0, function* () {
196
+ let certificateManager = this.getCertificateManager(certificateGroupId);
197
+ if (!certificateManager) {
198
+ debugLog(" cannot find group ", certificateGroupId);
199
+ return {
200
+ statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidArgument
201
+ };
202
+ }
203
+ if (!subjectName) {
204
+ // reuse existing subjectName
205
+ const currentCertificateFilename = path.join(certificateManager.rootDir, "own/certs/certificate.pem");
206
+ if (!fs.existsSync(currentCertificateFilename)) {
207
+ errorLog("Cannot find existing certificate to extract subjectName", currentCertificateFilename);
208
+ return {
209
+ statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidState
210
+ };
211
+ }
212
+ const certificate = (0, node_opcua_crypto_1.readCertificate)(currentCertificateFilename);
213
+ const e = (0, node_opcua_crypto_1.exploreCertificate)(certificate);
214
+ subjectName = subjectToString(e.tbsCertificate.subject);
215
+ warningLog("reusing existing certificate subjectAltName = ", subjectName);
216
+ }
217
+ // todo : at this time regenerate PrivateKey is not supported
218
+ if (regeneratePrivateKey) {
219
+ // The Server shall create a new Private Key which it stores until the
220
+ // matching signed Certificate is uploaded with the UpdateCertificate Method.
221
+ // Previously created Private Keys may be discarded if UpdateCertificate was not
222
+ // called before calling this method again.
223
+ // Additional entropy which the caller shall provide if regeneratePrivateKey is TRUE.
224
+ // It shall be at least 32 bytes long
225
+ if (!nonce || nonce.length < 32) {
226
+ (0, node_opcua_debug_1.make_warningLog)(" nonce should be provided when regeneratePrivateKey is set, and length shall be greater than 32 bytes");
227
+ return {
228
+ statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidArgument
229
+ };
230
+ }
231
+ const location = path.join(certificateManager.rootDir, "tmp");
232
+ if (fs.existsSync(location)) {
233
+ yield (0, util_1.promisify)(rimraf)(path.join(location));
234
+ }
235
+ if (!fs.existsSync(location)) {
236
+ yield fs.promises.mkdir(location);
237
+ }
238
+ const destCertificateManager = certificateManager;
239
+ const keySize = certificateManager.keySize; // because keySize is private !
240
+ certificateManager = new node_opcua_certificate_manager_1.CertificateManager({
241
+ keySize,
242
+ location,
243
+ });
244
+ debugLog("generating a new private key ...");
245
+ yield certificateManager.initialize();
246
+ this._tmpCertificateManager = certificateManager;
247
+ this.addPendingTask(() => __awaiter(this, void 0, void 0, function* () {
248
+ yield moveFileWithBackup(certificateManager.privateKey, destCertificateManager.privateKey);
249
+ }));
250
+ this.addPendingTask(() => __awaiter(this, void 0, void 0, function* () {
251
+ yield (0, util_1.promisify)(rimraf)(path.join(location));
252
+ }));
253
+ }
254
+ else {
255
+ // The Server uses its existing Private Key
256
+ }
257
+ if (typeof subjectName !== "string") {
258
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadInternalError };
259
+ }
260
+ const options = {
261
+ applicationUri: this.applicationUri,
262
+ subject: subjectName
263
+ };
264
+ yield certificateManager.initialize();
265
+ const csrFile = yield certificateManager.createCertificateRequest(options);
266
+ const csrPEM = yield readFile(csrFile, "utf8");
267
+ const certificateSigningRequest = (0, node_opcua_crypto_1.convertPEMtoDER)(csrPEM);
268
+ this.addPendingTask(() => deleteFile(csrFile));
269
+ return {
270
+ certificateSigningRequest,
271
+ statusCode: node_opcua_basic_types_1.StatusCodes.Good
272
+ };
273
+ });
274
+ }
275
+ getRejectedList() {
276
+ return __awaiter(this, void 0, void 0, function* () {
277
+ // rejectedList comes from each group
278
+ function extractRejectedList(group, certificateList) {
279
+ return __awaiter(this, void 0, void 0, function* () {
280
+ if (!group) {
281
+ return;
282
+ }
283
+ const rejectedFolder = path.join(group.rootDir, "rejected");
284
+ const files = yield readdir(rejectedFolder);
285
+ const stat = fs.promises.stat;
286
+ const promises1 = [];
287
+ for (const certFile of files) {
288
+ // read date
289
+ promises1.push(stat(path.join(rejectedFolder, certFile)));
290
+ }
291
+ const stats = yield Promise.all(promises1);
292
+ for (let i = 0; i < stats.length; i++) {
293
+ certificateList.push({
294
+ filename: path.join(rejectedFolder, files[i]),
295
+ stat: stats[i]
296
+ });
297
+ }
298
+ });
299
+ }
300
+ const list = [];
301
+ yield extractRejectedList(this.applicationGroup, list);
302
+ yield extractRejectedList(this.userTokenGroup, list);
303
+ yield extractRejectedList(this.httpsGroup, list);
304
+ // now sort list from newer file to older file
305
+ list.sort((a, b) => b.stat.mtime.getTime() - a.stat.mtime.getTime());
306
+ const promises = [];
307
+ for (const item of list) {
308
+ promises.push(readFile(item.filename, "utf8"));
309
+ }
310
+ const certificatesPEM = yield Promise.all(promises);
311
+ const certificates = certificatesPEM.map(node_opcua_crypto_1.convertPEMtoDER);
312
+ return {
313
+ certificates,
314
+ statusCode: node_opcua_basic_types_1.StatusCodes.Good
315
+ };
316
+ });
317
+ }
318
+ updateCertificate(certificateGroupId, certificateTypeId, certificate, issuerCertificates, privateKeyFormat, privateKey) {
319
+ return __awaiter(this, void 0, void 0, function* () {
320
+ // Result Code Description
321
+ // BadInvalidArgument The certificateTypeId or certificateGroupId is not valid.
322
+ // BadCertificateInvalid The Certificate is invalid or the format is not supported.
323
+ // BadNotSupported The PrivateKey is invalid or the format is not supported.
324
+ // BadUserAccessDenied The current user does not have the rights required.
325
+ // BadSecurityChecksFailed Some failure occurred verifying the integrity of the Certificate.
326
+ const certificateManager = this.getCertificateManager(certificateGroupId);
327
+ if (!certificateManager) {
328
+ debugLog(" cannot find group ", certificateGroupId);
329
+ return {
330
+ statusCode: node_opcua_basic_types_1.StatusCodes.BadInvalidArgument
331
+ };
332
+ }
333
+ function preInstallCertificate(self) {
334
+ return __awaiter(this, void 0, void 0, function* () {
335
+ const certFolder = path.join(certificateManager.rootDir, "own/certs");
336
+ const certificateFileDER = path.join(certFolder, `_pending_certificate${fileCounter++}.der`);
337
+ const certificateFilePEM = path.join(certFolder, `_pending_certificate${fileCounter++}.pem`);
338
+ yield writeFile(certificateFileDER, certificate, "binary");
339
+ yield writeFile(certificateFilePEM, (0, node_opcua_crypto_1.toPem)(certificate, "CERTIFICATE"));
340
+ const destDER = path.join(certFolder, "certificate.der");
341
+ const destPEM = path.join(certFolder, "certificate.pem");
342
+ // put existing file in security by backing them up
343
+ self.addPendingTask(() => moveFileWithBackup(certificateFileDER, destDER));
344
+ self.addPendingTask(() => moveFileWithBackup(certificateFilePEM, destPEM));
345
+ });
346
+ }
347
+ function preInstallPrivateKey(self) {
348
+ return __awaiter(this, void 0, void 0, function* () {
349
+ (0, node_opcua_assert_1.assert)(privateKeyFormat.toUpperCase() === "PEM");
350
+ (0, node_opcua_assert_1.assert)(privateKey instanceof Buffer); // could be DER or PEM in a buffer ?
351
+ const ownPrivateFolder = path.join(certificateManager.rootDir, "own/private");
352
+ const privateKeyFilePEM = path.join(ownPrivateFolder, `_pending_private_key${fileCounter++}.pem`);
353
+ const privateKeyPEM = (0, node_opcua_crypto_1.toPem)(privateKey, "RSA PRIVATE KEY");
354
+ yield writeFile(privateKeyFilePEM, privateKeyPEM, "utf-8");
355
+ self.addPendingTask(() => moveFileWithBackup(privateKeyFilePEM, certificateManager.privateKey));
356
+ });
357
+ }
358
+ // OPC Unified Architecture, Part 12 42 Release 1.04:
359
+ //
360
+ // UpdateCertificate is used to update a Certificate for a Server.
361
+ // There are the following three use cases for this Method:
362
+ //
363
+ // - The new Certificate was created based on a signing request created with the Method
364
+ // In this case there is no privateKey provided.
365
+ // - A new privateKey and Certificate was created outside the Server and both are updated
366
+ // with this Method.
367
+ // - A new Certificate was created and signed with the information from the old Certificate.
368
+ // In this case there is no privateKey provided.
369
+ // The Server shall do all normal integrity checks on the Certificate and all of the issuer
370
+ // Certificates. If errors occur the BadSecurityChecksFailed error is returned.
371
+ // todo : all normal integrity check on the certificate
372
+ const certInfo = (0, node_opcua_crypto_1.exploreCertificate)(certificate);
373
+ const now = new Date();
374
+ if (certInfo.tbsCertificate.validity.notBefore.getTime() > now.getTime()) {
375
+ // certificate is not yet valid
376
+ debugLog("Certificate is not yet valid");
377
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
378
+ }
379
+ if (certInfo.tbsCertificate.validity.notAfter.getTime() < now.getTime()) {
380
+ // certificate is already out of date
381
+ debugLog("Certificate is already out of date");
382
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
383
+ }
384
+ // If the Server returns applyChangesRequired=FALSE then it is indicating that it is able to
385
+ // satisfy the requirements specified for the ApplyChanges Method.
386
+ debugLog(" updateCertificate ", (0, node_opcua_crypto_1.makeSHA1Thumbprint)(certificate).toString("hex"));
387
+ if (!privateKeyFormat || !privateKey) {
388
+ // first of all we need to find the future private key;
389
+ // this one may have been created during the creation of the certficate signing request
390
+ // but is not active yet
391
+ const privateKeyDER = (0, node_opcua_crypto_1.readPrivateKey)(this._tmpCertificateManager ? this._tmpCertificateManager.privateKey : certificateManager.privateKey);
392
+ // The Server shall report an error if the public key does not match the existing Certificate and
393
+ // the privateKey was not provided.
394
+ // privateKey is not provided, so check that the public key matches the existing certificate
395
+ if (!certificateMatchesPrivateKey(certificate, privateKeyDER)) {
396
+ // certificate doesn't match privateKey
397
+ debugLog("certificate doesn't match privateKey");
398
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
399
+ }
400
+ // a new certificate is provided for us,
401
+ // we keep our private key
402
+ // we do this in two stages
403
+ yield preInstallCertificate(this);
404
+ return {
405
+ statusCode: node_opcua_basic_types_1.StatusCodes.Good
406
+ };
407
+ }
408
+ else if (privateKey) {
409
+ // a private key has been provided by the caller !
410
+ if (!privateKeyFormat) {
411
+ debugLog("the privateKeyFormat must be specified " + privateKeyFormat);
412
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported };
413
+ }
414
+ if (privateKeyFormat !== "PEM" && privateKeyFormat !== "PFX") {
415
+ debugLog(" the private key format is invalid privateKeyFormat =" + privateKeyFormat);
416
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported };
417
+ }
418
+ if (privateKeyFormat !== "PEM") {
419
+ debugLog("in NodeOPCUA we only support PEM for the moment privateKeyFormat =" + privateKeyFormat);
420
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported };
421
+ }
422
+ // privateKey is provided, so check that the public key matches provided private key
423
+ if (!certificateMatchesPrivateKey(certificate, privateKey)) {
424
+ // certificate doesn't match privateKey
425
+ debugLog("certificate doesn't match privateKey");
426
+ return { statusCode: node_opcua_basic_types_1.StatusCodes.BadSecurityChecksFailed };
427
+ }
428
+ yield preInstallPrivateKey(this);
429
+ yield preInstallCertificate(this);
430
+ return {
431
+ statusCode: node_opcua_basic_types_1.StatusCodes.Good
432
+ };
433
+ }
434
+ else {
435
+ // todo !
436
+ return {
437
+ statusCode: node_opcua_basic_types_1.StatusCodes.BadNotSupported
438
+ };
439
+ }
440
+ });
441
+ }
442
+ applyChanges() {
443
+ return __awaiter(this, void 0, void 0, function* () {
444
+ // ApplyChanges is used to tell the Server to apply any security changes.
445
+ // This Method should only be called if a previous call to a Method that changed the
446
+ // configuration returns applyChangesRequired=true.
447
+ //
448
+ // If the Server Certificate has changed, Secure Channels using the old Certificate will
449
+ // eventually be interrupted.
450
+ this.emit("CertificateAboutToChange", this.$$actionQueue);
451
+ yield this.flushActionQueue();
452
+ try {
453
+ yield this.applyPendingTasks();
454
+ }
455
+ catch (err) {
456
+ debugLog("err ", err);
457
+ return node_opcua_basic_types_1.StatusCodes.BadInternalError;
458
+ }
459
+ this.emit("CertificateChanged", this.$$actionQueue);
460
+ yield this.flushActionQueue();
461
+ // The only leeway the Server has is with the timing.
462
+ // In the best case, the Server can close the TransportConnections for the affected Endpoints and leave any
463
+ // Subscriptions intact. This should appear no different than a network interruption from the
464
+ // perspective of the Client. The Client should be prepared to deal with Certificate changes
465
+ // during its reconnect logic. In the worst case, a full shutdown which affects all connected
466
+ // Clients will be necessary. In the latter case, the Server shall advertise its intent to interrupt
467
+ // connections by setting the SecondsTillShutdown and ShutdownReason Properties in the
468
+ // ServerStatus Variable.
469
+ // If the Secure Channel being used to call this Method will be affected by the Certificate change
470
+ // then the Server shall introduce a delay long enough to allow the caller to receive a reply.
471
+ return node_opcua_basic_types_1.StatusCodes.Good;
472
+ });
473
+ }
474
+ getCertificateManager(certificateGroupId) {
475
+ const groupName = findCertificateGroupName(certificateGroupId);
476
+ return this._map[groupName] || null;
477
+ }
478
+ addPendingTask(functor) {
479
+ this._pendingTasks.push(functor);
480
+ }
481
+ applyPendingTasks() {
482
+ var e_1, _a;
483
+ return __awaiter(this, void 0, void 0, function* () {
484
+ debugLog("start applyPendingTasks");
485
+ const promises = [];
486
+ const t = this._pendingTasks.splice(0);
487
+ if (false) {
488
+ try {
489
+ // node 10.2 and above
490
+ for (var t_1 = __asyncValues(t), t_1_1; t_1_1 = yield t_1.next(), !t_1_1.done;) {
491
+ const task = t_1_1.value;
492
+ yield task();
493
+ }
494
+ }
495
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
496
+ finally {
497
+ try {
498
+ if (t_1_1 && !t_1_1.done && (_a = t_1.return)) yield _a.call(t_1);
499
+ }
500
+ finally { if (e_1) throw e_1.error; }
501
+ }
502
+ }
503
+ else {
504
+ while (t.length) {
505
+ const task = t.shift();
506
+ yield task();
507
+ }
508
+ }
509
+ yield Promise.all(promises);
510
+ debugLog("end applyPendingTasks");
511
+ });
512
+ }
513
+ flushActionQueue() {
514
+ return __awaiter(this, void 0, void 0, function* () {
515
+ while (this.$$actionQueue.length) {
516
+ const first = this.$$actionQueue.pop();
517
+ yield first();
518
+ }
519
+ });
520
+ }
521
+ }
522
+ exports.PushCertificateManagerServerImpl = PushCertificateManagerServerImpl;
523
523
  //# sourceMappingURL=push_certificate_manager_server_impl.js.map