node-opcua-server 2.70.1 → 2.71.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 (53) hide show
  1. package/dist/base_server.d.ts +110 -110
  2. package/dist/base_server.js +473 -473
  3. package/dist/factory.d.ts +12 -12
  4. package/dist/factory.js +23 -23
  5. package/dist/history_server_capabilities.d.ts +35 -35
  6. package/dist/history_server_capabilities.js +43 -43
  7. package/dist/i_channel_data.d.ts +13 -13
  8. package/dist/i_channel_data.js +2 -2
  9. package/dist/i_register_server_manager.d.ts +16 -16
  10. package/dist/i_register_server_manager.js +2 -2
  11. package/dist/i_server_side_publish_engine.d.ts +36 -36
  12. package/dist/i_server_side_publish_engine.js +49 -49
  13. package/dist/i_socket_data.d.ts +11 -11
  14. package/dist/i_socket_data.js +2 -2
  15. package/dist/index.d.ts +15 -15
  16. package/dist/index.js +31 -31
  17. package/dist/monitored_item.d.ts +177 -177
  18. package/dist/monitored_item.js +998 -998
  19. package/dist/node_sampler.d.ts +3 -3
  20. package/dist/node_sampler.js +75 -75
  21. package/dist/opcua_server.d.ts +647 -647
  22. package/dist/opcua_server.js +2385 -2385
  23. package/dist/queue.d.ts +11 -11
  24. package/dist/queue.js +71 -71
  25. package/dist/register_server_manager.d.ts +96 -96
  26. package/dist/register_server_manager.js +584 -584
  27. package/dist/register_server_manager_hidden.d.ts +17 -17
  28. package/dist/register_server_manager_hidden.js +27 -27
  29. package/dist/register_server_manager_mdns_only.d.ts +22 -22
  30. package/dist/register_server_manager_mdns_only.js +55 -55
  31. package/dist/server_capabilities.d.ts +61 -61
  32. package/dist/server_capabilities.js +108 -108
  33. package/dist/server_end_point.d.ts +183 -183
  34. package/dist/server_end_point.js +816 -816
  35. package/dist/server_engine.d.ts +316 -316
  36. package/dist/server_engine.js +1688 -1688
  37. package/dist/server_publish_engine.d.ts +112 -112
  38. package/dist/server_publish_engine.js +530 -530
  39. package/dist/server_publish_engine_for_orphan_subscriptions.d.ts +16 -16
  40. package/dist/server_publish_engine_for_orphan_subscriptions.js +49 -49
  41. package/dist/server_session.d.ts +181 -181
  42. package/dist/server_session.js +738 -738
  43. package/dist/server_subscription.d.ts +395 -395
  44. package/dist/server_subscription.js +1316 -1316
  45. package/dist/sessions_compatible_for_transfer.d.ts +2 -2
  46. package/dist/sessions_compatible_for_transfer.js +36 -36
  47. package/dist/user_manager.d.ts +32 -32
  48. package/dist/user_manager.js +74 -74
  49. package/dist/user_manager_ua.d.ts +3 -3
  50. package/dist/user_manager_ua.js +39 -39
  51. package/dist/validate_filter.d.ts +5 -5
  52. package/dist/validate_filter.js +60 -60
  53. package/package.json +46 -46
@@ -1,2386 +1,2386 @@
1
- "use strict";
2
- /**
3
- * @module node-opcua-server
4
- */
5
- // tslint:disable:no-console
6
- // tslint:disable:max-line-length
7
- // tslint:disable:unified-signatures
8
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
- return new (P || (P = Promise))(function (resolve, reject) {
11
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
- step((generator = generator.apply(thisArg, _arguments || [])).next());
15
- });
16
- };
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.OPCUAServer = exports.RegisterServerMethod = exports.filterDiagnosticInfo = void 0;
19
- const crypto = require("crypto");
20
- const util_1 = require("util");
21
- const async = require("async");
22
- const chalk = require("chalk");
23
- const node_opcua_hostname_1 = require("node-opcua-hostname");
24
- const node_opcua_assert_1 = require("node-opcua-assert");
25
- const utils = require("node-opcua-utils");
26
- const node_opcua_address_space_1 = require("node-opcua-address-space");
27
- const node_opcua_certificate_manager_1 = require("node-opcua-certificate-manager");
28
- const node_opcua_common_1 = require("node-opcua-common");
29
- const node_opcua_crypto_1 = require("node-opcua-crypto");
30
- const node_opcua_data_model_1 = require("node-opcua-data-model");
31
- const node_opcua_data_value_1 = require("node-opcua-data-value");
32
- const node_opcua_debug_1 = require("node-opcua-debug");
33
- const node_opcua_object_registry_1 = require("node-opcua-object-registry");
34
- const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
35
- const node_opcua_service_browse_1 = require("node-opcua-service-browse");
36
- const node_opcua_service_call_1 = require("node-opcua-service-call");
37
- const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
38
- const node_opcua_service_history_1 = require("node-opcua-service-history");
39
- const node_opcua_service_node_management_1 = require("node-opcua-service-node-management");
40
- const node_opcua_service_query_1 = require("node-opcua-service-query");
41
- const node_opcua_service_read_1 = require("node-opcua-service-read");
42
- const node_opcua_service_register_node_1 = require("node-opcua-service-register-node");
43
- const node_opcua_service_session_1 = require("node-opcua-service-session");
44
- const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
45
- const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
46
- const node_opcua_service_write_1 = require("node-opcua-service-write");
47
- const node_opcua_status_code_1 = require("node-opcua-status-code");
48
- const node_opcua_types_1 = require("node-opcua-types");
49
- const node_opcua_variant_1 = require("node-opcua-variant");
50
- const node_opcua_variant_2 = require("node-opcua-variant");
51
- const node_opcua_utils_1 = require("node-opcua-utils");
52
- const base_server_1 = require("./base_server");
53
- const factory_1 = require("./factory");
54
- const monitored_item_1 = require("./monitored_item");
55
- const register_server_manager_1 = require("./register_server_manager");
56
- const register_server_manager_hidden_1 = require("./register_server_manager_hidden");
57
- const register_server_manager_mdns_only_1 = require("./register_server_manager_mdns_only");
58
- const server_end_point_1 = require("./server_end_point");
59
- const server_engine_1 = require("./server_engine");
60
- const user_manager_1 = require("./user_manager");
61
- const user_manager_ua_1 = require("./user_manager_ua");
62
- function isSubscriptionIdInvalid(subscriptionId) {
63
- return subscriptionId < 0 || subscriptionId >= 0xffffffff;
64
- }
65
- // tslint:disable-next-line:no-var-requires
66
- const thenify = require("thenify");
67
- // tslint:disable-next-line:no-var-requires
68
- const package_info = require("../package.json");
69
- const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
70
- const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
71
- const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
72
- const default_maxAllowedSessionNumber = 10;
73
- const default_maxConnectionsPerEndpoint = 10;
74
- function g_sendError(channel, message, ResponseClass, statusCode) {
75
- const response = new ResponseClass({
76
- responseHeader: { serviceResult: statusCode }
77
- });
78
- return channel.send_response("MSG", response, message);
79
- }
80
- const default_build_info = {
81
- manufacturerName: "NodeOPCUA : MIT Licence ( see http://node-opcua.github.io/)",
82
- productName: "NodeOPCUA-Server",
83
- productUri: null,
84
- softwareVersion: package_info.version,
85
- buildNumber: "0",
86
- buildDate: new Date(2020, 1, 1)
87
- // xx buildDate: fs.statSync(package_json_file).mtime
88
- };
89
- const minSessionTimeout = 100; // 100 milliseconds
90
- const defaultSessionTimeout = 1000 * 30; // 30 seconds
91
- const maxSessionTimeout = 1000 * 60 * 50; // 50 minutes
92
- function _adjust_session_timeout(sessionTimeout) {
93
- let revisedSessionTimeout = sessionTimeout || defaultSessionTimeout;
94
- revisedSessionTimeout = Math.min(revisedSessionTimeout, maxSessionTimeout);
95
- revisedSessionTimeout = Math.max(revisedSessionTimeout, minSessionTimeout);
96
- return revisedSessionTimeout;
97
- }
98
- function channel_has_session(channel, session) {
99
- if (session.channel === channel) {
100
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(channel.sessionTokens, session.authenticationToken.toString()));
101
- return true;
102
- }
103
- return false;
104
- }
105
- function moveSessionToChannel(session, channel) {
106
- debugLog("moveSessionToChannel sessionId", session.nodeId, " channelId=", channel.channelId);
107
- if (session.publishEngine) {
108
- session.publishEngine.cancelPendingPublishRequestBeforeChannelChange();
109
- }
110
- session._detach_channel();
111
- session._attach_channel(channel);
112
- (0, node_opcua_assert_1.assert)(session.channel.channelId === channel.channelId);
113
- }
114
- function _attempt_to_close_some_old_unactivated_session(server) {
115
- return __awaiter(this, void 0, void 0, function* () {
116
- const session = server.engine.getOldestUnactivatedSession();
117
- if (session) {
118
- yield server.engine.closeSession(session.authenticationToken, false, "Forcing");
119
- }
120
- });
121
- }
122
- function getRequiredEndpointInfo(endpoint) {
123
- (0, node_opcua_assert_1.assert)(endpoint instanceof node_opcua_types_1.EndpointDescription);
124
- // It is recommended that Servers only include the server.applicationUri, endpointUrl, securityMode,
125
- // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all
126
- // other parameters set to null. Only the recommended parameters shall be verified by
127
- // the client.
128
- const e = new node_opcua_types_1.EndpointDescription({
129
- endpointUrl: endpoint.endpointUrl,
130
- securityLevel: endpoint.securityLevel,
131
- securityMode: endpoint.securityMode,
132
- securityPolicyUri: endpoint.securityPolicyUri,
133
- server: {
134
- applicationUri: endpoint.server.applicationUri,
135
- applicationType: endpoint.server.applicationType,
136
- applicationName: endpoint.server.applicationName
137
- // ... to be continued after verifying what fields are actually needed
138
- },
139
- transportProfileUri: endpoint.transportProfileUri,
140
- userIdentityTokens: endpoint.userIdentityTokens
141
- });
142
- // reduce even further by explicitly setting unwanted members to null
143
- e.server.productUri = null;
144
- e.server.applicationName = null;
145
- // xx e.server.applicationType = null as any;
146
- e.server.gatewayServerUri = null;
147
- e.server.discoveryProfileUri = null;
148
- e.server.discoveryUrls = null;
149
- e.serverCertificate = null;
150
- return e;
151
- }
152
- // serverUri String This value is only specified if the EndpointDescription has a gatewayServerUri.
153
- // This value is the applicationUri from the EndpointDescription which is the applicationUri for the
154
- // underlying Server. The type EndpointDescription is defined in 7.10.
155
- function _serverEndpointsForCreateSessionResponse(server, endpointUrl, serverUri) {
156
- serverUri = null; // unused then
157
- // The Server shall return a set of EndpointDescriptions available for the serverUri specified in the request.
158
- // It is recommended that Servers only include the endpointUrl, securityMode,
159
- // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all other parameters
160
- // set to null. Only the recommended parameters shall be verified by the client.
161
- return server
162
- ._get_endpoints(endpointUrl)
163
- .filter((e) => !e.restricted) // remove restricted endpoints
164
- .filter((e) => (0, node_opcua_utils_1.matchUri)(e.endpointUrl, endpointUrl))
165
- .map(getRequiredEndpointInfo);
166
- }
167
- function adjustSecurityPolicy(channel, userTokenPolicy_securityPolicyUri) {
168
- // check that userIdentityToken
169
- let securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(userTokenPolicy_securityPolicyUri);
170
- // if the security policy is not specified we use the session security policy
171
- if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.Invalid) {
172
- securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(channel.clientSecurityHeader.securityPolicyUri);
173
- (0, node_opcua_assert_1.assert)(securityPolicy !== node_opcua_secure_channel_1.SecurityPolicy.Invalid);
174
- }
175
- return securityPolicy;
176
- }
177
- function findUserTokenByPolicy(endpoint_description, userTokenType, policyId) {
178
- (0, node_opcua_assert_1.assert)(endpoint_description instanceof node_opcua_types_1.EndpointDescription);
179
- const r = endpoint_description.userIdentityTokens.filter((userIdentity) => userIdentity.tokenType === userTokenType && (!policyId || userIdentity.policyId === policyId));
180
- return r.length === 0 ? null : r[0];
181
- }
182
- function findUserTokenPolicy(endpoint_description, userTokenType) {
183
- (0, node_opcua_assert_1.assert)(endpoint_description instanceof node_opcua_types_1.EndpointDescription);
184
- const r = endpoint_description.userIdentityTokens.filter((userIdentity) => {
185
- (0, node_opcua_assert_1.assert)(userIdentity.tokenType !== undefined);
186
- return userIdentity.tokenType === userTokenType;
187
- });
188
- return r.length === 0 ? null : r[0];
189
- }
190
- function createAnonymousIdentityToken(endpoint_desc) {
191
- (0, node_opcua_assert_1.assert)(endpoint_desc instanceof node_opcua_types_1.EndpointDescription);
192
- const userTokenPolicy = findUserTokenPolicy(endpoint_desc, node_opcua_service_endpoints_1.UserTokenType.Anonymous);
193
- if (!userTokenPolicy) {
194
- throw new Error("Cannot find ANONYMOUS user token policy in end point description");
195
- }
196
- return new node_opcua_service_session_1.AnonymousIdentityToken({ policyId: userTokenPolicy.policyId });
197
- }
198
- function sameIdentityToken(token1, token2) {
199
- if (token1 instanceof node_opcua_service_session_1.UserNameIdentityToken) {
200
- if (!(token2 instanceof node_opcua_service_session_1.UserNameIdentityToken)) {
201
- return false;
202
- }
203
- if (token1.userName !== token2.userName) {
204
- return false;
205
- }
206
- if (token1.password.toString("hex") !== token2.password.toString("hex")) {
207
- return false;
208
- }
209
- }
210
- else if (token1 instanceof node_opcua_service_session_1.AnonymousIdentityToken) {
211
- if (!(token2 instanceof node_opcua_service_session_1.AnonymousIdentityToken)) {
212
- return false;
213
- }
214
- if (token1.policyId !== token2.policyId) {
215
- return false;
216
- }
217
- return true;
218
- }
219
- (0, node_opcua_assert_1.assert)(false, " Not implemented yet");
220
- return false;
221
- }
222
- function getTokenType(userIdentityToken) {
223
- if (userIdentityToken instanceof node_opcua_service_session_1.AnonymousIdentityToken) {
224
- return node_opcua_service_endpoints_1.UserTokenType.Anonymous;
225
- }
226
- else if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
227
- return node_opcua_service_endpoints_1.UserTokenType.UserName;
228
- }
229
- else if (userIdentityToken instanceof node_opcua_types_1.IssuedIdentityToken) {
230
- return node_opcua_service_endpoints_1.UserTokenType.IssuedToken;
231
- }
232
- else if (userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken) {
233
- return node_opcua_service_endpoints_1.UserTokenType.Certificate;
234
- }
235
- return node_opcua_service_endpoints_1.UserTokenType.Invalid;
236
- }
237
- function thumbprint(certificate) {
238
- return certificate ? certificate.toString("base64") : "";
239
- }
240
- /*=== private
241
- *
242
- * perform the read operation on a given node for a monitored item.
243
- * this method DOES NOT apply to Variable Values attribute
244
- *
245
- * @param self
246
- * @param oldValue
247
- * @param node
248
- * @param itemToMonitor
249
- * @private
250
- */
251
- function monitoredItem_read_and_record_value(self, context, oldValue, node, itemToMonitor, callback) {
252
- (0, node_opcua_assert_1.assert)(self instanceof monitored_item_1.MonitoredItem);
253
- (0, node_opcua_assert_1.assert)(oldValue instanceof node_opcua_data_value_1.DataValue);
254
- (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
255
- const dataValue = node.readAttribute(context, itemToMonitor.attributeId, itemToMonitor.indexRange, itemToMonitor.dataEncoding);
256
- callback(null, dataValue);
257
- }
258
- /*== private
259
- * @method monitoredItem_read_and_record_value_async
260
- * this method applies to Variable Values attribute
261
- * @param self
262
- * @param oldValue
263
- * @param node
264
- * @param itemToMonitor
265
- * @private
266
- */
267
- function monitoredItem_read_and_record_value_async(self, context, oldValue, node, itemToMonitor, callback) {
268
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
269
- (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
270
- (0, node_opcua_assert_1.assert)(self instanceof monitored_item_1.MonitoredItem);
271
- (0, node_opcua_assert_1.assert)(oldValue instanceof node_opcua_data_value_1.DataValue);
272
- // do it asynchronously ( this is only valid for value attributes )
273
- (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
274
- node.readValueAsync(context, (err, dataValue) => {
275
- callback(err, dataValue);
276
- });
277
- }
278
- function build_scanning_node_function(context, addressSpace, monitoredItem, itemToMonitor) {
279
- (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
280
- (0, node_opcua_assert_1.assert)(itemToMonitor instanceof node_opcua_service_read_1.ReadValueId);
281
- const node = addressSpace.findNode(itemToMonitor.nodeId);
282
- /* istanbul ignore next */
283
- if (!node) {
284
- errorLog(" INVALID NODE ID , ", itemToMonitor.nodeId.toString());
285
- (0, node_opcua_debug_1.dump)(itemToMonitor);
286
- return (oldData, callback) => {
287
- callback(null, new node_opcua_data_value_1.DataValue({
288
- statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown,
289
- value: { dataType: node_opcua_variant_1.DataType.Null, value: 0 }
290
- }));
291
- };
292
- }
293
- ///// !!monitoredItem.setNode(node);
294
- if (itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value) {
295
- const monitoredItem_read_and_record_value_func = itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value && typeof node.readValueAsync === "function"
296
- ? monitoredItem_read_and_record_value_async
297
- : monitoredItem_read_and_record_value;
298
- return function func(oldDataValue, callback) {
299
- (0, node_opcua_assert_1.assert)(this instanceof monitored_item_1.MonitoredItem);
300
- (0, node_opcua_assert_1.assert)(oldDataValue instanceof node_opcua_data_value_1.DataValue);
301
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
302
- monitoredItem_read_and_record_value_func(this, context, oldDataValue, node, itemToMonitor, callback);
303
- };
304
- }
305
- else {
306
- // Attributes, other than the Value Attribute, are only monitored for a change in value.
307
- // The filter is not used for these Attributes. Any change in value for these Attributes
308
- // causes a Notification to be generated.
309
- // only record value when it has changed
310
- return function func(oldDataValue, callback) {
311
- (0, node_opcua_assert_1.assert)(this instanceof monitored_item_1.MonitoredItem);
312
- (0, node_opcua_assert_1.assert)(oldDataValue instanceof node_opcua_data_value_1.DataValue);
313
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
314
- const newDataValue = node.readAttribute(null, itemToMonitor.attributeId);
315
- callback(null, newDataValue);
316
- };
317
- }
318
- }
319
- function prepareMonitoredItem(context, addressSpace, monitoredItem) {
320
- const itemToMonitor = monitoredItem.itemToMonitor;
321
- const readNodeFunc = build_scanning_node_function(context, addressSpace, monitoredItem, itemToMonitor);
322
- monitoredItem.samplingFunc = readNodeFunc;
323
- }
324
- function isMonitoringModeValid(monitoringMode) {
325
- (0, node_opcua_assert_1.assert)(node_opcua_types_1.MonitoringMode.Invalid !== undefined);
326
- return monitoringMode !== node_opcua_types_1.MonitoringMode.Invalid && monitoringMode <= node_opcua_types_1.MonitoringMode.Reporting;
327
- }
328
- function _installRegisterServerManager(self) {
329
- (0, node_opcua_assert_1.assert)(self instanceof OPCUAServer);
330
- (0, node_opcua_assert_1.assert)(!self.registerServerManager);
331
- /* istanbul ignore next */
332
- if (!self.registerServerMethod) {
333
- throw new Error("Internal Error");
334
- }
335
- switch (self.registerServerMethod) {
336
- case RegisterServerMethod.HIDDEN:
337
- self.registerServerManager = new register_server_manager_hidden_1.RegisterServerManagerHidden({
338
- server: self
339
- });
340
- break;
341
- case RegisterServerMethod.MDNS:
342
- self.registerServerManager = new register_server_manager_mdns_only_1.RegisterServerManagerMDNSONLY({
343
- server: self
344
- });
345
- break;
346
- case RegisterServerMethod.LDS:
347
- self.registerServerManager = new register_server_manager_1.RegisterServerManager({
348
- discoveryServerEndpointUrl: self.discoveryServerEndpointUrl,
349
- server: self
350
- });
351
- break;
352
- /* istanbul ignore next */
353
- default:
354
- throw new Error("Invalid switch");
355
- }
356
- self.registerServerManager.on("serverRegistrationPending", () => {
357
- /**
358
- * emitted when the server is trying to registered the LDS
359
- * but when the connection to the lds has failed
360
- * serverRegistrationPending is sent when the backoff signal of the
361
- * connection process is raised
362
- * @event serverRegistrationPending
363
- */
364
- debugLog("serverRegistrationPending");
365
- self.emit("serverRegistrationPending");
366
- });
367
- self.registerServerManager.on("serverRegistered", () => {
368
- /**
369
- * emitted when the server is successfully registered to the LDS
370
- * @event serverRegistered
371
- */
372
- debugLog("serverRegistered");
373
- self.emit("serverRegistered");
374
- });
375
- self.registerServerManager.on("serverRegistrationRenewed", () => {
376
- /**
377
- * emitted when the server has successfully renewed its registration to the LDS
378
- * @event serverRegistrationRenewed
379
- */
380
- debugLog("serverRegistrationRenewed");
381
- self.emit("serverRegistrationRenewed");
382
- });
383
- self.registerServerManager.on("serverUnregistered", () => {
384
- debugLog("serverUnregistered");
385
- /**
386
- * emitted when the server is successfully unregistered to the LDS
387
- * ( for instance during shutdown)
388
- * @event serverUnregistered
389
- */
390
- self.emit("serverUnregistered");
391
- });
392
- }
393
- function validate_applicationUri(channel, request) {
394
- var _a, _b;
395
- const applicationUri = request.clientDescription.applicationUri;
396
- const clientCertificate = request.clientCertificate;
397
- // if session is insecure there is no need to check certificate information
398
- if (channel.securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
399
- return true; // assume correct
400
- }
401
- if (!clientCertificate || clientCertificate.length === 0) {
402
- return true; // can't check
403
- }
404
- const e = (0, node_opcua_crypto_1.exploreCertificate)(clientCertificate);
405
- const uniformResourceIdentifier = (_b = (_a = e.tbsCertificate.extensions.subjectAltName) === null || _a === void 0 ? void 0 : _a.uniformResourceIdentifier) !== null && _b !== void 0 ? _b : null;
406
- const applicationUriFromCert = uniformResourceIdentifier && uniformResourceIdentifier.length > 0 ? uniformResourceIdentifier[0] : null;
407
- /* istanbul ignore next */
408
- if (applicationUriFromCert !== applicationUri) {
409
- errorLog("BadCertificateUriInvalid!");
410
- errorLog("applicationUri = ", applicationUri);
411
- errorLog("applicationUriFromCert = ", applicationUriFromCert);
412
- }
413
- return applicationUriFromCert === applicationUri;
414
- }
415
- function validate_security_endpoint(server, request, channel) {
416
- debugLog("validate_security_endpoint = ", request.endpointUrl);
417
- let endpoints = server._get_endpoints(request.endpointUrl);
418
- // endpointUrl String The network address that the Client used to access the Session Endpoint.
419
- // The HostName portion of the URL should be one of the HostNames for the application that are
420
- // specified in the Server’s ApplicationInstanceCertificate (see 7.2). The Server shall raise an
421
- // AuditUrlMismatchEventType event if the URL does not match the Server’s HostNames.
422
- // AuditUrlMismatchEventType event type is defined in Part 5.
423
- // The Server uses this information for diagnostics and to determine the set of
424
- // EndpointDescriptions to return in the response.
425
- // ToDo: check endpointUrl validity and emit an AuditUrlMismatchEventType event if not
426
- if (endpoints.length === 0) {
427
- // we have a UrlMismatch here
428
- const ua_server = server.engine.addressSpace.rootFolder.objects.server;
429
- ua_server.raiseEvent("AuditUrlMismatchEventType", {
430
- endpointUrl: { dataType: node_opcua_variant_1.DataType.String, value: request.endpointUrl }
431
- });
432
- debugLog("Cannot find endpoint in available endpoints with endpointUri", request.endpointUrl);
433
- if (OPCUAServer.requestExactEndpointUrl) {
434
- return { errCode: node_opcua_status_code_1.StatusCodes.BadServiceUnsupported };
435
- }
436
- else {
437
- endpoints = server._get_endpoints(null);
438
- }
439
- }
440
- // ignore restricted endpoints
441
- endpoints = endpoints.filter((e) => !e.restricted);
442
- const endpoints_matching_security_mode = endpoints.filter((e) => {
443
- return e.securityMode === channel.securityMode;
444
- });
445
- if (endpoints_matching_security_mode.length === 0) {
446
- return { errCode: node_opcua_status_code_1.StatusCodes.BadSecurityModeRejected };
447
- }
448
- const endpoints_matching_security_policy = endpoints_matching_security_mode.filter((e) => {
449
- return e.securityPolicyUri === channel.securityHeader.securityPolicyUri;
450
- });
451
- if (endpoints_matching_security_policy.length === 0) {
452
- return { errCode: node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected };
453
- }
454
- if (endpoints_matching_security_policy.length !== 1) {
455
- debugLog("endpoints_matching_security_policy= ", endpoints_matching_security_policy.length);
456
- }
457
- return { errCode: node_opcua_status_code_1.StatusCodes.Good, endpoint: endpoints_matching_security_policy[0] };
458
- }
459
- function filterDiagnosticInfo(returnDiagnostics, response) {
460
- if (node_opcua_data_model_1.RESPONSE_DIAGNOSTICS_MASK_ALL & returnDiagnostics) {
461
- response.responseHeader.serviceDiagnostics = (0, node_opcua_data_model_1.filterDiagnosticServiceLevel)(returnDiagnostics, response.responseHeader.serviceDiagnostics);
462
- if (response.diagnosticInfos && response.diagnosticInfos.length > 0) {
463
- response.diagnosticInfos = response.diagnosticInfos.map((d) => (0, node_opcua_data_model_1.filterDiagnosticOperationLevel)(returnDiagnostics, d));
464
- }
465
- else {
466
- response.diagnosticInfos = [];
467
- }
468
- if (response.results) {
469
- for (const entry of response.results) {
470
- if (entry.inputArgumentDiagnosticInfos && entry.inputArgumentDiagnosticInfos.length > 0) {
471
- entry.inputArgumentDiagnosticInfos = entry.inputArgumentDiagnosticInfos.map((d) => (0, node_opcua_data_model_1.filterDiagnosticOperationLevel)(returnDiagnostics, d));
472
- }
473
- else {
474
- entry.inputArgumentDiagnosticInfos = [];
475
- }
476
- }
477
- }
478
- }
479
- }
480
- exports.filterDiagnosticInfo = filterDiagnosticInfo;
481
- var RegisterServerMethod;
482
- (function (RegisterServerMethod) {
483
- RegisterServerMethod[RegisterServerMethod["HIDDEN"] = 1] = "HIDDEN";
484
- RegisterServerMethod[RegisterServerMethod["MDNS"] = 2] = "MDNS";
485
- RegisterServerMethod[RegisterServerMethod["LDS"] = 3] = "LDS"; // the server registers itself to the LDS or LDS-ME (Local Discovery Server)
486
- })(RegisterServerMethod = exports.RegisterServerMethod || (exports.RegisterServerMethod = {}));
487
- const g_requestExactEndpointUrl = !!process.env.NODEOPCUA_SERVER_REQUEST_EXACT_ENDPOINT_URL;
488
- /**
489
- *
490
- */
491
- class OPCUAServer extends base_server_1.OPCUABaseServer {
492
- constructor(options) {
493
- super(options);
494
- /**
495
- * false if anonymous connection are not allowed
496
- */
497
- this.allowAnonymous = false;
498
- this.allowAnonymous = false;
499
- options = options || {};
500
- this.options = options;
501
- /**
502
- * @property maxAllowedSessionNumber
503
- */
504
- this.maxAllowedSessionNumber = options.maxAllowedSessionNumber || default_maxAllowedSessionNumber;
505
- /**
506
- * @property maxConnectionsPerEndpoint
507
- */
508
- this.maxConnectionsPerEndpoint = options.maxConnectionsPerEndpoint || default_maxConnectionsPerEndpoint;
509
- // build Info
510
- const buildInfo = Object.assign(Object.assign({}, default_build_info), options.buildInfo);
511
- // repair product name
512
- buildInfo.productUri = buildInfo.productUri || this.serverInfo.productUri;
513
- this.serverInfo.productUri = this.serverInfo.productUri || buildInfo.productUri;
514
- this.userManager = (0, user_manager_1.makeUserManager)(options.userManager);
515
- options.allowAnonymous = options.allowAnonymous === undefined ? true : !!options.allowAnonymous;
516
- /**
517
- * @property allowAnonymous
518
- */
519
- this.allowAnonymous = options.allowAnonymous;
520
- this.discoveryServerEndpointUrl = options.discoveryServerEndpointUrl || "opc.tcp://%FQDN%:4840";
521
- (0, node_opcua_assert_1.assert)(typeof this.discoveryServerEndpointUrl === "string");
522
- this.serverInfo.applicationType = node_opcua_service_endpoints_1.ApplicationType.Server;
523
- this.capabilitiesForMDNS = options.capabilitiesForMDNS || ["NA"];
524
- this.registerServerMethod = options.registerServerMethod || RegisterServerMethod.HIDDEN;
525
- _installRegisterServerManager(this);
526
- if (!options.userCertificateManager) {
527
- this.userCertificateManager = (0, node_opcua_certificate_manager_1.getDefaultCertificateManager)("UserPKI");
528
- }
529
- else {
530
- this.userCertificateManager = options.userCertificateManager;
531
- }
532
- // note: we need to delay initialization of endpoint as certain resources
533
- // such as %FQDN% might not be ready yet at this stage
534
- this._delayInit = () => __awaiter(this, void 0, void 0, function* () {
535
- /* istanbul ignore next */
536
- if (!options) {
537
- throw new Error("Internal Error");
538
- }
539
- // to check => this.serverInfo.applicationName = this.serverInfo.productName || buildInfo.productName;
540
- // note: applicationUri is handled in a special way
541
- this.engine = new server_engine_1.ServerEngine({
542
- applicationUri: () => this.serverInfo.applicationUri,
543
- buildInfo,
544
- isAuditing: options.isAuditing,
545
- serverCapabilities: options.serverCapabilities
546
- });
547
- this.objectFactory = new factory_1.Factory(this.engine);
548
- const endpointDefinitions = options.alternateEndpoints || [];
549
- const hostname = (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
550
- endpointDefinitions.push({
551
- port: options.port || 26543,
552
- allowAnonymous: options.allowAnonymous,
553
- alternateHostname: options.alternateHostname,
554
- disableDiscovery: options.disableDiscovery,
555
- hostname: options.hostname || hostname,
556
- securityModes: options.securityModes,
557
- securityPolicies: options.securityPolicies
558
- });
559
- // todo should self.serverInfo.productUri match self.engine.buildInfo.productUri ?
560
- for (const endpointOptions of endpointDefinitions) {
561
- const endPoint = this.createEndpointDescriptions(options, endpointOptions);
562
- this.endpoints.push(endPoint);
563
- endPoint.on("message", (message, channel) => {
564
- this.on_request(message, channel);
565
- });
566
- endPoint.on("error", (err) => {
567
- errorLog("OPCUAServer endpoint error", err);
568
- // set serverState to ServerState.Failed;
569
- this.engine.setServerState(node_opcua_common_1.ServerState.Failed);
570
- this.shutdown(() => {
571
- /* empty */
572
- });
573
- });
574
- }
575
- });
576
- }
577
- /**
578
- * total number of bytes written by the server since startup
579
- */
580
- get bytesWritten() {
581
- return this.endpoints.reduce((accumulated, endpoint) => {
582
- return accumulated + endpoint.bytesWritten;
583
- }, 0);
584
- }
585
- /**
586
- * total number of bytes read by the server since startup
587
- */
588
- get bytesRead() {
589
- return this.endpoints.reduce((accumulated, endpoint) => {
590
- return accumulated + endpoint.bytesRead;
591
- }, 0);
592
- }
593
- /**
594
- * Number of transactions processed by the server since startup
595
- */
596
- get transactionsCount() {
597
- return this.endpoints.reduce((accumulated, endpoint) => {
598
- return accumulated + endpoint.transactionsCount;
599
- }, 0);
600
- }
601
- /**
602
- * The server build info
603
- */
604
- get buildInfo() {
605
- return this.engine.buildInfo;
606
- }
607
- /**
608
- * the number of connected channel on all existing end points
609
- */
610
- get currentChannelCount() {
611
- // TODO : move to base
612
- return this.endpoints.reduce((currentValue, endPoint) => {
613
- return currentValue + endPoint.currentChannelCount;
614
- }, 0);
615
- }
616
- /**
617
- * The number of active subscriptions from all sessions
618
- */
619
- get currentSubscriptionCount() {
620
- return this.engine ? this.engine.currentSubscriptionCount : 0;
621
- }
622
- /**
623
- * the number of session activation requests that have been rejected
624
- */
625
- get rejectedSessionCount() {
626
- return this.engine ? this.engine.rejectedSessionCount : 0;
627
- }
628
- /**
629
- * the number of request that have been rejected
630
- */
631
- get rejectedRequestsCount() {
632
- return this.engine ? this.engine.rejectedRequestsCount : 0;
633
- }
634
- /**
635
- * the number of sessions that have been aborted
636
- */
637
- get sessionAbortCount() {
638
- return this.engine ? this.engine.sessionAbortCount : 0;
639
- }
640
- /**
641
- * the publishing interval count
642
- */
643
- get publishingIntervalCount() {
644
- return this.engine ? this.engine.publishingIntervalCount : 0;
645
- }
646
- /**
647
- * the number of sessions currently active
648
- */
649
- get currentSessionCount() {
650
- return this.engine ? this.engine.currentSessionCount : 0;
651
- }
652
- /**
653
- * true if the server has been initialized
654
- *
655
- */
656
- get initialized() {
657
- return this.engine && this.engine.addressSpace !== null;
658
- }
659
- /**
660
- * is the server auditing ?
661
- */
662
- get isAuditing() {
663
- return this.engine ? this.engine.isAuditing : false;
664
- }
665
- initialize(...args) {
666
- const done = args[0];
667
- (0, node_opcua_assert_1.assert)(!this.initialized, "server is already initialized"); // already initialized ?
668
- this._preInitTask.push(() => __awaiter(this, void 0, void 0, function* () {
669
- /* istanbul ignore else */
670
- if (this._delayInit) {
671
- yield this._delayInit();
672
- this._delayInit = undefined;
673
- }
674
- }));
675
- this.performPreInitialization()
676
- .then(() => {
677
- OPCUAServer.registry.register(this);
678
- this.engine.initialize(this.options, () => {
679
- (0, user_manager_ua_1.bindRoleSet)(this.userManager, this.engine.addressSpace);
680
- setImmediate(() => {
681
- this.emit("post_initialize");
682
- done();
683
- });
684
- });
685
- })
686
- .catch((err) => {
687
- done(err);
688
- });
689
- }
690
- start(...args) {
691
- const done = args[0];
692
- const tasks = [];
693
- tasks.push((0, util_1.callbackify)(node_opcua_hostname_1.extractFullyQualifiedDomainName));
694
- if (!this.initialized) {
695
- tasks.push((callback) => {
696
- this.initialize(callback);
697
- });
698
- }
699
- tasks.push((callback) => {
700
- super.start((err) => {
701
- if (err) {
702
- this.shutdown((/*err2*/ err2) => {
703
- callback(err);
704
- });
705
- }
706
- else {
707
- // we start the registration process asynchronously
708
- // as we want to make server immediately available
709
- this.registerServerManager.start(() => {
710
- /* empty */
711
- });
712
- setImmediate(callback);
713
- }
714
- });
715
- });
716
- async.series(tasks, done);
717
- }
718
- shutdown(...args) {
719
- const timeout = args.length === 1 ? OPCUAServer.defaultShutdownTimeout : args[0];
720
- const callback = (args.length === 1 ? args[0] : args[1]);
721
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
722
- debugLog("OPCUAServer#shutdown (timeout = ", timeout, ")");
723
- /* istanbul ignore next */
724
- if (!this.engine) {
725
- return callback();
726
- }
727
- (0, node_opcua_assert_1.assert)(this.engine);
728
- if (!this.engine.isStarted()) {
729
- // server may have been shot down already , or may have fail to start !!
730
- const err = new Error("OPCUAServer#shutdown failure ! server doesn't seems to be started yet");
731
- return callback(err);
732
- }
733
- this.userCertificateManager.dispose();
734
- this.engine.setServerState(node_opcua_common_1.ServerState.Shutdown);
735
- const shutdownTime = new Date(Date.now() + timeout);
736
- this.engine.setShutdownTime(shutdownTime);
737
- debugLog("OPCUAServer is now unregistering itself from the discovery server " + this.buildInfo);
738
- this.registerServerManager.stop((err) => {
739
- debugLog("OPCUAServer unregistered from discovery server", err);
740
- setTimeout(() => __awaiter(this, void 0, void 0, function* () {
741
- yield this.engine.shutdown();
742
- debugLog("OPCUAServer#shutdown: started");
743
- base_server_1.OPCUABaseServer.prototype.shutdown.call(this, (err1) => {
744
- debugLog("OPCUAServer#shutdown: completed");
745
- this.dispose();
746
- callback(err1);
747
- });
748
- }), timeout);
749
- });
750
- }
751
- dispose() {
752
- for (const endpoint of this.endpoints) {
753
- endpoint.dispose();
754
- }
755
- this.endpoints = [];
756
- this.removeAllListeners();
757
- if (this.registerServerManager) {
758
- this.registerServerManager.dispose();
759
- this.registerServerManager = undefined;
760
- }
761
- OPCUAServer.registry.unregister(this);
762
- /* istanbul ignore next */
763
- if (this.engine) {
764
- this.engine.dispose();
765
- }
766
- }
767
- raiseEvent(eventType, options) {
768
- /* istanbul ignore next */
769
- if (!this.engine.addressSpace) {
770
- errorLog("addressSpace missing");
771
- return;
772
- }
773
- const server = this.engine.addressSpace.findNode("Server");
774
- /* istanbul ignore next */
775
- if (!server) {
776
- // xx throw new Error("OPCUAServer#raiseEvent : cannot find Server object");
777
- return;
778
- }
779
- let eventTypeNode = eventType;
780
- if (typeof eventType === "string") {
781
- eventTypeNode = this.engine.addressSpace.findEventType(eventType);
782
- if (eventTypeNode) {
783
- return server.raiseEvent(eventTypeNode, options);
784
- }
785
- else {
786
- console.warn(" cannot find event type ", eventType);
787
- }
788
- }
789
- else {
790
- return server.raiseEvent(eventTypeNode, options);
791
- }
792
- }
793
- /**
794
- * create and register a new session
795
- * @internal
796
- */
797
- createSession(options) {
798
- /* istanbul ignore next */
799
- if (!this.engine) {
800
- throw new Error("Internal Error");
801
- }
802
- return this.engine.createSession(options);
803
- }
804
- /**
805
- * retrieve a session by authentication token
806
- * @internal
807
- */
808
- getSession(authenticationToken, activeOnly) {
809
- return this.engine ? this.engine.getSession(authenticationToken, activeOnly) : null;
810
- }
811
- /**
812
- *
813
- * @param channel
814
- * @param clientCertificate
815
- * @param clientNonce
816
- * @internal
817
- */
818
- computeServerSignature(channel, clientCertificate, clientNonce) {
819
- return (0, node_opcua_secure_channel_1.computeSignature)(clientCertificate, clientNonce, this.getPrivateKey(), channel.messageBuilder.securityPolicy);
820
- }
821
- /**
822
- *
823
- * @param session
824
- * @param channel
825
- * @param clientSignature
826
- * @internal
827
- */
828
- verifyClientSignature(session, channel, clientSignature) {
829
- const clientCertificate = channel.receiverCertificate;
830
- const securityPolicy = channel.messageBuilder.securityPolicy;
831
- const serverCertificate = this.getCertificate();
832
- const result = (0, node_opcua_secure_channel_1.verifySignature)(serverCertificate, session.nonce, clientSignature, clientCertificate, securityPolicy);
833
- return result;
834
- }
835
- isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback) {
836
- (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken);
837
- const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
838
- if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
839
- return callback(null, node_opcua_status_code_1.StatusCodes.Good);
840
- }
841
- const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
842
- /* istanbul ignore next */
843
- if (!cryptoFactory) {
844
- return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
845
- }
846
- /* istanbul ignore next */
847
- if (userIdentityToken.encryptionAlgorithm !== cryptoFactory.asymmetricEncryptionAlgorithm) {
848
- errorLog("invalid encryptionAlgorithm");
849
- errorLog("userTokenPolicy", userTokenPolicy.toString());
850
- errorLog("userTokenPolicy", userIdentityToken.toString());
851
- return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
852
- }
853
- const userName = userIdentityToken.userName;
854
- const password = userIdentityToken.password;
855
- if (!userName || !password) {
856
- return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
857
- }
858
- return callback(null, node_opcua_status_code_1.StatusCodes.Good);
859
- }
860
- isValidX509IdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback) {
861
- (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken);
862
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
863
- const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
864
- const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
865
- /* istanbul ignore next */
866
- if (!cryptoFactory) {
867
- return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
868
- }
869
- if (!userTokenSignature || !userTokenSignature.signature) {
870
- return callback(null, node_opcua_status_code_1.StatusCodes.BadUserSignatureInvalid);
871
- }
872
- if (userIdentityToken.policyId !== userTokenPolicy.policyId) {
873
- errorLog("invalid encryptionAlgorithm");
874
- errorLog("userTokenPolicy", userTokenPolicy.toString());
875
- errorLog("userTokenPolicy", userIdentityToken.toString());
876
- return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
877
- }
878
- const certificate = userIdentityToken.certificateData; /* as Certificate*/
879
- const nonce = session.nonce;
880
- const serverCertificate = this.getCertificate();
881
- (0, node_opcua_assert_1.assert)(serverCertificate instanceof Buffer);
882
- (0, node_opcua_assert_1.assert)(certificate instanceof Buffer, "expecting certificate to be a Buffer");
883
- (0, node_opcua_assert_1.assert)(nonce instanceof Buffer, "expecting nonce to be a Buffer");
884
- (0, node_opcua_assert_1.assert)(userTokenSignature.signature instanceof Buffer, "expecting userTokenSignature to be a Buffer");
885
- // verify proof of possession by checking certificate signature & server nonce correctness
886
- if (!(0, node_opcua_secure_channel_1.verifySignature)(serverCertificate, nonce, userTokenSignature, certificate, securityPolicy)) {
887
- return callback(null, node_opcua_status_code_1.StatusCodes.BadUserSignatureInvalid);
888
- }
889
- // verify if certificate is Valid
890
- this.userCertificateManager.checkCertificate(certificate, (err, certificateStatus) => {
891
- /* istanbul ignore next */
892
- if (err) {
893
- return callback(err);
894
- }
895
- if (node_opcua_status_code_1.StatusCodes.BadCertificateUntrusted === certificateStatus ||
896
- node_opcua_status_code_1.StatusCodes.BadCertificateTimeInvalid === certificateStatus ||
897
- node_opcua_status_code_1.StatusCodes.BadCertificateIssuerTimeInvalid === certificateStatus ||
898
- node_opcua_status_code_1.StatusCodes.BadCertificateIssuerUseNotAllowed === certificateStatus ||
899
- node_opcua_status_code_1.StatusCodes.BadCertificateIssuerRevocationUnknown === certificateStatus ||
900
- node_opcua_status_code_1.StatusCodes.BadCertificateRevocationUnknown === certificateStatus ||
901
- node_opcua_status_code_1.StatusCodes.BadCertificateRevoked === certificateStatus ||
902
- node_opcua_status_code_1.StatusCodes.BadCertificateUseNotAllowed === certificateStatus ||
903
- node_opcua_status_code_1.StatusCodes.BadSecurityChecksFailed === certificateStatus ||
904
- node_opcua_status_code_1.StatusCodes.Good !== certificateStatus) {
905
- debugLog("isValidX509IdentityToken => certificateStatus = ", certificateStatus === null || certificateStatus === void 0 ? void 0 : certificateStatus.toString());
906
- return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenRejected);
907
- }
908
- if (node_opcua_status_code_1.StatusCodes.Good !== certificateStatus) {
909
- (0, node_opcua_assert_1.assert)(certificateStatus instanceof node_opcua_status_code_1.StatusCode);
910
- return callback(null, certificateStatus);
911
- // return callback(null, StatusCodes.BadIdentityTokenInvalid);
912
- }
913
- // verify if certificate is truster or rejected
914
- // todo: StatusCodes.BadCertificateUntrusted
915
- // store untrusted certificate to rejected folder
916
- // todo:
917
- return callback(null, node_opcua_status_code_1.StatusCodes.Good);
918
- });
919
- }
920
- /**
921
- * @internal
922
- */
923
- userNameIdentityTokenAuthenticateUser(channel, session, userTokenPolicy, userIdentityToken, callback) {
924
- (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken);
925
- // assert(this.isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken));
926
- const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
927
- const userName = userIdentityToken.userName;
928
- let password = userIdentityToken.password;
929
- // decrypt password if necessary
930
- if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
931
- // not good, password was sent in clear text ...
932
- password = password.toString();
933
- }
934
- else {
935
- const serverPrivateKey = this.getPrivateKey();
936
- const serverNonce = session.nonce;
937
- (0, node_opcua_assert_1.assert)(serverNonce instanceof Buffer);
938
- const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
939
- /* istanbul ignore next */
940
- if (!cryptoFactory) {
941
- return callback(new Error(" Unsupported security Policy"));
942
- }
943
- const buff = cryptoFactory.asymmetricDecrypt(password, serverPrivateKey);
944
- // server certificate may be invalid and asymmetricDecrypt may fail
945
- if (!buff || buff.length < 4) {
946
- async.setImmediate(() => callback(null, false));
947
- return;
948
- }
949
- const length = buff.readUInt32LE(0) - serverNonce.length;
950
- password = buff.slice(4, 4 + length).toString("utf-8");
951
- }
952
- this.userManager
953
- .isValidUser(session, userName, password)
954
- .then((isValid) => callback(null, isValid))
955
- .catch((err) => callback(err));
956
- }
957
- /**
958
- * @internal
959
- */
960
- isValidUserIdentityToken(channel, session, userIdentityToken, userTokenSignature, endpointDescription, callback) {
961
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
962
- /* istanbul ignore next */
963
- if (!userIdentityToken) {
964
- throw new Error("Invalid token");
965
- }
966
- const userTokenType = getTokenType(userIdentityToken);
967
- const userTokenPolicy = findUserTokenByPolicy(endpointDescription, userTokenType, userIdentityToken.policyId);
968
- if (!userTokenPolicy) {
969
- // cannot find token with this policyId
970
- return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
971
- }
972
- //
973
- if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
974
- return this.isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback);
975
- }
976
- if (userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken) {
977
- return this.isValidX509IdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback);
978
- }
979
- return callback(null, node_opcua_status_code_1.StatusCodes.Good);
980
- }
981
- /**
982
- *
983
- * @internal
984
- * @param channel
985
- * @param session
986
- * @param userIdentityToken
987
- * @param callback
988
- * @returns {*}
989
- */
990
- isUserAuthorized(channel, session, userIdentityToken, callback) {
991
- (0, node_opcua_assert_1.assert)(userIdentityToken);
992
- (0, node_opcua_assert_1.assert)(typeof callback === "function");
993
- const userTokenType = getTokenType(userIdentityToken);
994
- const userTokenPolicy = findUserTokenByPolicy(session.getEndpointDescription(), userTokenType, userIdentityToken.policyId);
995
- /** istanbul ignore next */
996
- if (!userTokenPolicy) {
997
- return callback(null, false);
998
- }
999
- // find if a userToken exists
1000
- if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
1001
- return this.userNameIdentityTokenAuthenticateUser(channel, session, userTokenPolicy, userIdentityToken, callback);
1002
- }
1003
- async.setImmediate(callback.bind(null, null, true));
1004
- }
1005
- makeServerNonce() {
1006
- return crypto.randomBytes(32);
1007
- }
1008
- // session services
1009
- // eslint-disable-next-line max-statements
1010
- _on_CreateSessionRequest(message, channel) {
1011
- return __awaiter(this, void 0, void 0, function* () {
1012
- const request = message.request;
1013
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.CreateSessionRequest);
1014
- function rejectConnection(server, statusCode) {
1015
- server.engine.incrementSecurityRejectedSessionCount();
1016
- const response1 = new node_opcua_service_session_1.CreateSessionResponse({
1017
- responseHeader: { serviceResult: statusCode }
1018
- });
1019
- channel.send_response("MSG", response1, message);
1020
- // and close !
1021
- }
1022
- // From OPCUA V1.03 Part 4 5.6.2 CreateSession
1023
- // A Server application should limit the number of Sessions. To protect against misbehaving Clients and denial
1024
- // of service attacks, the Server shall close the oldest Session that is not activated before reaching the
1025
- // maximum number of supported Sessions
1026
- if (this.currentSessionCount >= this.maxAllowedSessionNumber) {
1027
- yield _attempt_to_close_some_old_unactivated_session(this);
1028
- }
1029
- // check if session count hasn't reach the maximum allowed sessions
1030
- if (this.currentSessionCount >= this.maxAllowedSessionNumber) {
1031
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadTooManySessions);
1032
- }
1033
- // Release 1.03 OPC Unified Architecture, Part 4 page 24 - CreateSession Parameters
1034
- // client should prove a sessionName
1035
- // Session name is a Human readable string that identifies the Session. The Server makes this name and the
1036
- // sessionId visible in its AddressSpace for diagnostic purposes. The Client should provide a name that is
1037
- // unique for the instance of the Client.
1038
- // If this parameter is not specified the Server shall assign a value.
1039
- if (utils.isNullOrUndefined(request.sessionName)) {
1040
- // see also #198
1041
- // let's the server assign a sessionName for this lazy client.
1042
- debugLog("assigning OPCUAServer.fallbackSessionName because client's sessionName is null ", OPCUAServer.fallbackSessionName);
1043
- request.sessionName = OPCUAServer.fallbackSessionName;
1044
- }
1045
- // Duration Requested maximum number of milliseconds that a Session should remain open without activity.
1046
- // If the Client fails to issue a Service request within this interval, then the Server shall automatically
1047
- // terminate the Client Session.
1048
- const revisedSessionTimeout = _adjust_session_timeout(request.requestedSessionTimeout);
1049
- // Release 1.02 page 27 OPC Unified Architecture, Part 4: CreateSession.clientNonce
1050
- // A random number that should never be used in any other request. This number shall have a minimum length of 32
1051
- // bytes. Profiles may increase the required length. The Server shall use this value to prove possession of
1052
- // its application instance Certificate in the response.
1053
- if (!request.clientNonce || request.clientNonce.length < 32) {
1054
- if (channel.securityMode !== node_opcua_secure_channel_1.MessageSecurityMode.None) {
1055
- errorLog(chalk.red("SERVER with secure connection: Missing or invalid client Nonce "), request.clientNonce && request.clientNonce.toString("hex"));
1056
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadNonceInvalid);
1057
- }
1058
- }
1059
- if ((0, node_opcua_secure_channel_1.nonceAlreadyBeenUsed)(request.clientNonce)) {
1060
- errorLog(chalk.red("SERVER with secure connection: None has already been used"), request.clientNonce && request.clientNonce.toString("hex"));
1061
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadNonceInvalid);
1062
- }
1063
- // check application spoofing
1064
- // check if applicationUri in createSessionRequest matches applicationUri in client Certificate
1065
- if (!validate_applicationUri(channel, request)) {
1066
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadCertificateUriInvalid);
1067
- }
1068
- const { errCode, endpoint } = validate_security_endpoint(this, request, channel);
1069
- if (errCode !== node_opcua_status_code_1.StatusCodes.Good) {
1070
- return rejectConnection(this, errCode);
1071
- }
1072
- // see Release 1.02 27 OPC Unified Architecture, Part 4
1073
- const session = this.createSession({
1074
- clientDescription: request.clientDescription,
1075
- sessionTimeout: revisedSessionTimeout
1076
- });
1077
- session.endpoint = endpoint;
1078
- (0, node_opcua_assert_1.assert)(session);
1079
- (0, node_opcua_assert_1.assert)(session.sessionTimeout === revisedSessionTimeout);
1080
- session.clientDescription = request.clientDescription;
1081
- session.sessionName = request.sessionName || "<unknown session name>";
1082
- // Depending upon on the SecurityPolicy and the SecurityMode of the SecureChannel, the exchange of
1083
- // ApplicationInstanceCertificates and Nonces may be optional and the signatures may be empty. See
1084
- // Part 7 for the definition of SecurityPolicies and the handling of these parameters
1085
- // serverNonce:
1086
- // A random number that should never be used in any other request.
1087
- // This number shall have a minimum length of 32 bytes.
1088
- // The Client shall use this value to prove possession of its application instance
1089
- // Certificate in the ActivateSession request.
1090
- // This value may also be used to prove possession of the userIdentityToken it
1091
- // specified in the ActivateSession request.
1092
- //
1093
- // ( this serverNonce will only be used up to the _on_ActivateSessionRequest
1094
- // where a new nonce will be created)
1095
- session.nonce = this.makeServerNonce();
1096
- session.channelId = channel.channelId;
1097
- session._attach_channel(channel);
1098
- const serverCertificateChain = this.getCertificateChain();
1099
- const hasEncryption = true;
1100
- // If the securityPolicyUri is None and none of the UserTokenPolicies requires encryption
1101
- if (session.channel.securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
1102
- // ToDo: Check that none of our insecure endpoint has a a UserTokenPolicy that require encryption
1103
- // and set hasEncryption = false under this condition
1104
- }
1105
- const response = new node_opcua_service_session_1.CreateSessionResponse({
1106
- // A identifier which uniquely identifies the session.
1107
- sessionId: session.nodeId,
1108
- // A unique identifier assigned by the Server to the Session.
1109
- // The token used to authenticate the client in subsequent requests.
1110
- authenticationToken: session.authenticationToken,
1111
- revisedSessionTimeout,
1112
- serverNonce: session.nonce,
1113
- // serverCertificate: type ApplicationServerCertificate
1114
- // The application instance Certificate issued to the Server.
1115
- // A Server shall prove possession by using the private key to sign the Nonce provided
1116
- // by the Client in the request. The Client shall verify that this Certificate is the same as
1117
- // the one it used to create the SecureChannel.
1118
- // The ApplicationInstanceCertificate type is defined in OpCUA 1.03 part 4 - $7.2 page 108
1119
- // If the securityPolicyUri is None and none of the UserTokenPolicies requires
1120
- // encryption, the Server shall not send an ApplicationInstanceCertificate and the Client
1121
- // shall ignore the ApplicationInstanceCertificate.
1122
- serverCertificate: hasEncryption ? serverCertificateChain : undefined,
1123
- // The endpoints provided by the server.
1124
- // The Server shall return a set of EndpointDescriptions available for the serverUri
1125
- // specified in the request.[...]
1126
- // The Client shall verify this list with the list from a Discovery Endpoint if it used a Discovery
1127
- // Endpoint to fetch the EndpointDescriptions.
1128
- // It is recommended that Servers only include the endpointUrl, securityMode,
1129
- // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all
1130
- // other parameters set to null. Only the recommended parameters shall be verified by
1131
- // the client.
1132
- serverEndpoints: _serverEndpointsForCreateSessionResponse(this, session.endpoint.endpointUrl, request.serverUri),
1133
- // This parameter is deprecated and the array shall be empty.
1134
- serverSoftwareCertificates: null,
1135
- // This is a signature generated with the private key associated with the
1136
- // serverCertificate. This parameter is calculated by appending the clientNonce to the
1137
- // clientCertificate and signing the resulting sequence of bytes.
1138
- // The SignatureAlgorithm shall be the AsymmetricSignatureAlgorithm specified in the
1139
- // SecurityPolicy for the Endpoint.
1140
- // The SignatureData type is defined in 7.30.
1141
- serverSignature: this.computeServerSignature(channel, request.clientCertificate, request.clientNonce),
1142
- // The maximum message size accepted by the server
1143
- // The Client Communication Stack should return a Bad_RequestTooLarge error to the
1144
- // application if a request message exceeds this limit.
1145
- // The value zero indicates that this parameter is not used.
1146
- maxRequestMessageSize: 0x4000000
1147
- });
1148
- this.emit("create_session", session);
1149
- session.on("session_closed", (session1, deleteSubscriptions, reason) => {
1150
- (0, node_opcua_assert_1.assert)(typeof reason === "string");
1151
- if (this.isAuditing) {
1152
- (0, node_opcua_assert_1.assert)(reason === "Timeout" || reason === "Terminated" || reason === "CloseSession" || reason === "Forcing");
1153
- const sourceName = "Session/" + reason;
1154
- this.raiseEvent("AuditSessionEventType", {
1155
- /* part 5 - 6.4.3 AuditEventType */
1156
- actionTimeStamp: { dataType: "DateTime", value: new Date() },
1157
- status: { dataType: "Boolean", value: true },
1158
- serverId: { dataType: "String", value: "" },
1159
- // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1160
- clientAuditEntryId: { dataType: "String", value: "" },
1161
- // The ClientUserId identifies the user of the client requesting an action. The ClientUserId can be
1162
- // obtained from the UserIdentityToken passed in the ActivateSession call.
1163
- clientUserId: { dataType: "String", value: "" },
1164
- sourceName: { dataType: "String", value: sourceName },
1165
- /* part 5 - 6.4.7 AuditSessionEventType */
1166
- sessionId: { dataType: "NodeId", value: session1.nodeId }
1167
- });
1168
- }
1169
- this.emit("session_closed", session1, deleteSubscriptions);
1170
- });
1171
- if (this.isAuditing) {
1172
- // ------------------------------------------------------------------------------------------------------
1173
- this.raiseEvent("AuditCreateSessionEventType", {
1174
- /* part 5 - 6.4.3 AuditEventType */
1175
- actionTimeStamp: { dataType: "DateTime", value: new Date() },
1176
- status: { dataType: "Boolean", value: true },
1177
- serverId: { dataType: "String", value: "" },
1178
- // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1179
- clientAuditEntryId: { dataType: "String", value: "" },
1180
- // The ClientUserId identifies the user of the client requesting an action. The ClientUserId can be
1181
- // obtained from the UserIdentityToken passed in the ActivateSession call.
1182
- clientUserId: { dataType: "String", value: "" },
1183
- sourceName: { dataType: "String", value: "Session/CreateSession" },
1184
- /* part 5 - 6.4.7 AuditSessionEventType */
1185
- sessionId: { dataType: "NodeId", value: session.nodeId },
1186
- /* part 5 - 6.4.8 AuditCreateSessionEventType */
1187
- // SecureChannelId shall uniquely identify the SecureChannel. The application shall use the same
1188
- // identifier in all AuditEvents related to the Session Service Set (AuditCreateSessionEventType,
1189
- // AuditActivateSessionEventType and their subtypes) and the SecureChannel Service Set
1190
- // (AuditChannelEventType and its subtypes
1191
- secureChannelId: { dataType: "String", value: session.channel.channelId.toString() },
1192
- // Duration
1193
- revisedSessionTimeout: { dataType: "Duration", value: session.sessionTimeout },
1194
- // clientCertificate
1195
- clientCertificate: { dataType: "ByteString", value: session.channel.clientCertificate },
1196
- // clientCertificateThumbprint
1197
- clientCertificateThumbprint: {
1198
- dataType: "String",
1199
- value: thumbprint(session.channel.clientCertificate)
1200
- }
1201
- });
1202
- }
1203
- // -----------------------------------------------------------------------------------------------------------
1204
- (0, node_opcua_assert_1.assert)(response.authenticationToken);
1205
- channel.send_response("MSG", response, message);
1206
- });
1207
- }
1208
- // TODO : implement this:
1209
- //
1210
- // When the ActivateSession Service is called for the first time then the Server shall reject the request
1211
- // if the SecureChannel is not same as the one associated with the CreateSession request.
1212
- // Subsequent calls to ActivateSession may be associated with different SecureChannels. If this is the
1213
- // case then the Server shall verify that the Certificate the Client used to create the new
1214
- // SecureChannel is the same as the Certificate used to create the original SecureChannel. In addition,
1215
- // the Server shall verify that the Client supplied a UserIdentityToken that is identical to the token
1216
- // currently associated with the Session. Once the Server accepts the new SecureChannel it shall
1217
- // reject requests sent via the old SecureChannel.
1218
- /**
1219
- *
1220
- * @method _on_ActivateSessionRequest
1221
- * @private
1222
- *
1223
- *
1224
- */
1225
- _on_ActivateSessionRequest(message, channel) {
1226
- const request = message.request;
1227
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.ActivateSessionRequest);
1228
- // get session from authenticationToken
1229
- const authenticationToken = request.requestHeader.authenticationToken;
1230
- const session = this.getSession(authenticationToken);
1231
- function rejectConnection(server, statusCode) {
1232
- if (statusCode === node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid) {
1233
- server.engine.incrementRejectedSessionCount();
1234
- }
1235
- else {
1236
- server.engine.incrementRejectedSessionCount();
1237
- server.engine.incrementSecurityRejectedSessionCount();
1238
- }
1239
- const response1 = new node_opcua_service_session_1.ActivateSessionResponse({ responseHeader: { serviceResult: statusCode } });
1240
- channel.send_response("MSG", response1, message);
1241
- // and close !
1242
- }
1243
- let response;
1244
- /* istanbul ignore next */
1245
- if (!session) {
1246
- // this may happen when the server has been restarted and a client tries to reconnect, thinking
1247
- // that the previous session may still be active
1248
- debugLog(chalk.yellow.bold(" Bad Session in _on_ActivateSessionRequest"), authenticationToken.toString());
1249
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1250
- }
1251
- // tslint:disable-next-line: no-unused-expression
1252
- session.keepAlive ? session.keepAlive() : void 0;
1253
- // OpcUA 1.02 part 3 $5.6.3.1 ActiveSession Set page 29
1254
- // When the ActivateSession Service is called f or the first time then the Server shall reject the request
1255
- // if the SecureChannel is not same as the one associated with the CreateSession request.
1256
- if (session.status === "new") {
1257
- // xx if (channel.session_nonce !== session.nonce) {
1258
- if (!channel_has_session(channel, session)) {
1259
- // it looks like session activation is being using a channel that is not the
1260
- // one that have been used to create the session
1261
- errorLog(" channel.sessionTokens === " + Object.keys(channel.sessionTokens).join(" "));
1262
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionNotActivated);
1263
- }
1264
- }
1265
- // OpcUA 1.02 part 3 $5.6.3.1 ActiveSession Set page 29
1266
- // ... Subsequent calls to ActivateSession may be associated with different SecureChannels. If this is the
1267
- // case then the Server shall verify that the Certificate the Client used to create the new
1268
- // SecureChannel is the same as the Certificate used to create the original SecureChannel.
1269
- if (session.status === "active") {
1270
- if (session.channel.channelId !== channel.channelId) {
1271
- warningLog(" Session ", session.sessionName, " is being transferred from channel", chalk.cyan(session.channel.channelId.toString()), " to channel ", chalk.cyan(channel.channelId.toString()));
1272
- // session is being reassigned to a new Channel,
1273
- // we shall verify that the certificate used to create the Session is the same as the current
1274
- // channel certificate.
1275
- const old_channel_cert_thumbprint = thumbprint(session.channel.clientCertificate);
1276
- const new_channel_cert_thumbprint = thumbprint(channel.clientCertificate);
1277
- if (old_channel_cert_thumbprint !== new_channel_cert_thumbprint) {
1278
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadNoValidCertificates); // not sure about this code !
1279
- }
1280
- // ... In addition the Server shall verify that the Client supplied a UserIdentityToken that is
1281
- // identical to the token currently associated with the Session reassign session to new channel.
1282
- if (!sameIdentityToken(session.userIdentityToken, request.userIdentityToken)) {
1283
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadIdentityChangeNotSupported); // not sure about this code !
1284
- }
1285
- }
1286
- moveSessionToChannel(session, channel);
1287
- }
1288
- else if (session.status === "screwed") {
1289
- // session has been used before being activated => this should be detected and session should be dismissed.
1290
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1291
- }
1292
- else if (session.status === "closed") {
1293
- warningLog(chalk.yellow.bold(" Bad Session Closed in _on_ActivateSessionRequest"), authenticationToken.toString());
1294
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1295
- }
1296
- // verify clientSignature provided by the client
1297
- if (!this.verifyClientSignature(session, channel, request.clientSignature)) {
1298
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadApplicationSignatureInvalid);
1299
- }
1300
- // userIdentityToken may be missing , assume anonymous access then
1301
- request.userIdentityToken = request.userIdentityToken || createAnonymousIdentityToken(session.endpoint);
1302
- // check request.userIdentityToken is correct ( expected type and correctly formed)
1303
- this.isValidUserIdentityToken(channel, session, request.userIdentityToken, request.userTokenSignature, session.endpoint, (err, statusCode) => {
1304
- if (statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1305
- /* istanbul ignore next */
1306
- if (!(statusCode && statusCode instanceof node_opcua_status_code_1.StatusCode)) {
1307
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadCertificateInvalid);
1308
- }
1309
- return rejectConnection(this, statusCode);
1310
- }
1311
- session.userIdentityToken = request.userIdentityToken;
1312
- // check if user access is granted
1313
- this.isUserAuthorized(channel, session, request.userIdentityToken, (err1, authorized) => {
1314
- /* istanbul ignore next */
1315
- if (err1) {
1316
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadInternalError);
1317
- }
1318
- if (!authorized) {
1319
- return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadUserAccessDenied);
1320
- }
1321
- else {
1322
- // extract : OPC UA part 4 - 5.6.3
1323
- // Once used, a serverNonce cannot be used again. For that reason, the Server returns a new
1324
- // serverNonce each time the ActivateSession Service is called.
1325
- session.nonce = this.makeServerNonce();
1326
- session.status = "active";
1327
- response = new node_opcua_service_session_1.ActivateSessionResponse({ serverNonce: session.nonce });
1328
- channel.send_response("MSG", response, message);
1329
- const userIdentityTokenPasswordRemoved = (userIdentityToken) => {
1330
- const a = userIdentityToken.clone();
1331
- // remove password
1332
- a.password = "*************";
1333
- return a;
1334
- };
1335
- // send OPCUA Event Notification
1336
- // see part 5 : 6.4.3 AuditEventType
1337
- // 6.4.7 AuditSessionEventType
1338
- // 6.4.10 AuditActivateSessionEventType
1339
- (0, node_opcua_assert_1.assert)(session.nodeId); // sessionId
1340
- // xx assert(session.channel.clientCertificate instanceof Buffer);
1341
- (0, node_opcua_assert_1.assert)(session.sessionTimeout > 0);
1342
- if (this.isAuditing) {
1343
- this.raiseEvent("AuditActivateSessionEventType", {
1344
- /* part 5 - 6.4.3 AuditEventType */
1345
- actionTimeStamp: { dataType: "DateTime", value: new Date() },
1346
- status: { dataType: "Boolean", value: true },
1347
- serverId: { dataType: "String", value: "" },
1348
- // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1349
- clientAuditEntryId: { dataType: "String", value: "" },
1350
- // The ClientUserId identifies the user of the client requesting an action.
1351
- // The ClientUserId can be obtained from the UserIdentityToken passed in the
1352
- // ActivateSession call.
1353
- clientUserId: { dataType: "String", value: "cc" },
1354
- sourceName: { dataType: "String", value: "Session/ActivateSession" },
1355
- /* part 5 - 6.4.7 AuditSessionEventType */
1356
- sessionId: { dataType: "NodeId", value: session.nodeId },
1357
- /* part 5 - 6.4.10 AuditActivateSessionEventType */
1358
- clientSoftwareCertificates: {
1359
- arrayType: node_opcua_variant_2.VariantArrayType.Array,
1360
- dataType: "ExtensionObject" /* SignedSoftwareCertificate */,
1361
- value: []
1362
- },
1363
- // UserIdentityToken reflects the userIdentityToken parameter of the ActivateSession
1364
- // Service call.
1365
- // For Username/Password tokens the password should NOT be included.
1366
- userIdentityToken: {
1367
- dataType: "ExtensionObject" /* UserIdentityToken */,
1368
- value: userIdentityTokenPasswordRemoved(session.userIdentityToken)
1369
- },
1370
- // SecureChannelId shall uniquely identify the SecureChannel. The application shall
1371
- // use the same identifier in all AuditEvents related to the Session Service Set
1372
- // (AuditCreateSessionEventType, AuditActivateSessionEventType and their subtypes) and
1373
- // the SecureChannel Service Set (AuditChannelEventType and its subtypes).
1374
- secureChannelId: { dataType: "String", value: session.channel.channelId.toString() }
1375
- });
1376
- }
1377
- this.emit("session_activated", session, userIdentityTokenPasswordRemoved);
1378
- }
1379
- });
1380
- });
1381
- }
1382
- prepare(message, channel) {
1383
- const request = message.request;
1384
- // --- check that session is correct
1385
- const authenticationToken = request.requestHeader.authenticationToken;
1386
- const session = this.getSession(authenticationToken, /*activeOnly*/ true);
1387
- if (!session) {
1388
- message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid;
1389
- return;
1390
- }
1391
- message.session = session;
1392
- // --- check that provided session matches session attached to channel
1393
- if (channel.channelId !== session.channelId) {
1394
- if (!(request instanceof node_opcua_service_session_1.ActivateSessionRequest)) {
1395
- errorLog(chalk.red.bgWhite("ERROR: channel.channelId !== session.channelId on processing request " + request.constructor.name), channel.channelId, session.channelId);
1396
- }
1397
- message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSecureChannelIdInvalid;
1398
- }
1399
- else if (channel_has_session(channel, session)) {
1400
- message.session_statusCode = node_opcua_status_code_1.StatusCodes.Good;
1401
- }
1402
- else {
1403
- // session ma y have been moved to a different channel
1404
- message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSecureChannelIdInvalid;
1405
- }
1406
- }
1407
- /**
1408
- * ensure that action is performed on a valid session object,
1409
- * @method _apply_on_SessionObject
1410
- * @param ResponseClass the constructor of the response Class
1411
- * @param message
1412
- * @param channel
1413
- * @param actionToPerform
1414
- * @param actionToPerform.session {ServerSession}
1415
- * @param actionToPerform.sendResponse
1416
- * @param actionToPerform.sendResponse.response
1417
- * @param actionToPerform.sendError
1418
- * @param actionToPerform.sendError.statusCode
1419
- * @param actionToPerform.sendError.diagnostics
1420
- *
1421
- * @private
1422
- */
1423
- _apply_on_SessionObject(ResponseClass, message, channel, actionToPerform) {
1424
- return __awaiter(this, void 0, void 0, function* () {
1425
- (0, node_opcua_assert_1.assert)(typeof actionToPerform === "function");
1426
- function sendResponse(response1) {
1427
- try {
1428
- (0, node_opcua_assert_1.assert)(response1 instanceof ResponseClass);
1429
- if (message.session) {
1430
- const counterName = ResponseClass.name.replace("Response", "");
1431
- message.session.incrementRequestTotalCounter(counterName);
1432
- }
1433
- return channel.send_response("MSG", response1, message);
1434
- }
1435
- catch (err) {
1436
- // istanbul ignore next
1437
- if (err instanceof Error) {
1438
- // istanbul ignore next
1439
- errorLog("Internal error in issuing response\nplease contact support@sterfive.com", message.request.toString(), "\n", response1.toString());
1440
- }
1441
- // istanbul ignore next
1442
- throw err;
1443
- }
1444
- }
1445
- function sendError(statusCode) {
1446
- if (message.session) {
1447
- message.session.incrementRequestErrorCounter(ResponseClass.name.replace("Response", ""));
1448
- }
1449
- return g_sendError(channel, message, ResponseClass, statusCode);
1450
- }
1451
- let response;
1452
- /* istanbul ignore next */
1453
- if (!message.session || message.session_statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1454
- const errMessage = "INVALID SESSION !! ";
1455
- response = new ResponseClass({ responseHeader: { serviceResult: message.session_statusCode } });
1456
- debugLog(chalk.red.bold(errMessage), chalk.yellow(message.session_statusCode.toString()), response.constructor.name);
1457
- return sendResponse(response);
1458
- }
1459
- (0, node_opcua_assert_1.assert)(message.session_statusCode === node_opcua_status_code_1.StatusCodes.Good);
1460
- // OPC UA Specification 1.02 part 4 page 26
1461
- // When a Session is terminated, all outstanding requests on the Session are aborted and
1462
- // Bad_SessionClosed StatusCodes are returned to the Client. In addition, the Server deletes the entry
1463
- // for the Client from its SessionDiagnostics Array Variable and notifies any other Clients who were
1464
- // subscribed to this entry.
1465
- if (message.session.status === "closed") {
1466
- // note : use StatusCodes.BadSessionClosed , for pending message for this session
1467
- return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1468
- }
1469
- if (message.session.status === "new") {
1470
- // mark session as being screwed ! so it cannot be activated anymore
1471
- message.session.status = "screwed";
1472
- return sendError(node_opcua_status_code_1.StatusCodes.BadSessionNotActivated);
1473
- }
1474
- if (message.session.status !== "active") {
1475
- // mark session as being screwed ! so it cannot be activated anymore
1476
- message.session.status = "screwed";
1477
- // note : use StatusCodes.BadSessionClosed , for pending message for this session
1478
- return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1479
- }
1480
- // lets also reset the session watchdog so it doesn't
1481
- // (Sessions are terminated by the Server automatically if the Client fails to issue a Service
1482
- // request on the Session within the timeout period negotiated by the Server in the
1483
- // CreateSession Service response. )
1484
- if (message.session.keepAlive) {
1485
- (0, node_opcua_assert_1.assert)(typeof message.session.keepAlive === "function");
1486
- message.session.keepAlive();
1487
- }
1488
- message.session.incrementTotalRequestCount();
1489
- yield actionToPerform(message.session, sendResponse, sendError);
1490
- });
1491
- }
1492
- _apply_on_Subscription(ResponseClass, message, channel, actionToPerform) {
1493
- return __awaiter(this, void 0, void 0, function* () {
1494
- (0, node_opcua_assert_1.assert)(typeof actionToPerform === "function");
1495
- const request = message.request;
1496
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "subscriptionId"));
1497
- this._apply_on_SessionObject(ResponseClass, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1498
- const subscription = session.getSubscription(request.subscriptionId);
1499
- if (!subscription) {
1500
- return sendError(node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid);
1501
- }
1502
- subscription.resetLifeTimeAndKeepAliveCounters();
1503
- yield actionToPerform(session, subscription, sendResponse, sendError);
1504
- }));
1505
- });
1506
- }
1507
- _apply_on_SubscriptionIds(ResponseClass, message, channel, actionToPerform) {
1508
- (0, node_opcua_assert_1.assert)(typeof actionToPerform === "function");
1509
- const request = message.request;
1510
- (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "subscriptionIds"));
1511
- this._apply_on_SessionObject(ResponseClass, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1512
- const subscriptionIds = request.subscriptionIds;
1513
- if (!request.subscriptionIds || request.subscriptionIds.length === 0) {
1514
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1515
- }
1516
- // if (request.subscriptionIds.length > OPCUAServer.MAX_SUBSCRIPTION) {
1517
- // return sendError(StatusCodes.BadTooManyOperations);
1518
- // }
1519
- const results = subscriptionIds.map((subscriptionId) => actionToPerform(session, subscriptionId));
1520
- // resolve potential pending promises ....
1521
- for (let i = 0; i < results.length; i++) {
1522
- if (results[i].then) {
1523
- results[i] = yield results[i];
1524
- }
1525
- }
1526
- const response = new ResponseClass({
1527
- responseHeader: {
1528
- serviceResult: request.subscriptionIds.length > OPCUAServer.MAX_SUBSCRIPTION
1529
- ? node_opcua_status_code_1.StatusCodes.BadTooManyOperations
1530
- : node_opcua_status_code_1.StatusCodes.Good
1531
- },
1532
- results
1533
- });
1534
- sendResponse(response);
1535
- }));
1536
- }
1537
- _apply_on_Subscriptions(ResponseClass, message, channel, actionToPerform) {
1538
- this._apply_on_SubscriptionIds(ResponseClass, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () {
1539
- /* istanbul ignore next */
1540
- if (isSubscriptionIdInvalid(subscriptionId)) {
1541
- return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
1542
- }
1543
- const subscription = session.getSubscription(subscriptionId);
1544
- if (!subscription) {
1545
- return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
1546
- }
1547
- return actionToPerform(session, subscription);
1548
- }));
1549
- }
1550
- _closeSession(authenticationToken, deleteSubscriptions, reason) {
1551
- return __awaiter(this, void 0, void 0, function* () {
1552
- if (deleteSubscriptions && this.options.onDeleteMonitoredItem) {
1553
- const session = this.getSession(authenticationToken);
1554
- if (session) {
1555
- const subscriptions = session.publishEngine.subscriptions;
1556
- for (const subscription of subscriptions) {
1557
- yield subscription.applyOnMonitoredItem(this.options.onDeleteMonitoredItem.bind(null, subscription));
1558
- }
1559
- }
1560
- }
1561
- yield this.engine.closeSession(authenticationToken, deleteSubscriptions, reason);
1562
- });
1563
- }
1564
- /**
1565
- * @method _on_CloseSessionRequest
1566
- * @param message
1567
- * @param channel
1568
- * @private
1569
- */
1570
- _on_CloseSessionRequest(message, channel) {
1571
- const request = message.request;
1572
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.CloseSessionRequest);
1573
- let response;
1574
- message.session_statusCode = node_opcua_status_code_1.StatusCodes.Good;
1575
- function sendError(statusCode) {
1576
- return g_sendError(channel, message, node_opcua_service_session_1.CloseSessionResponse, statusCode);
1577
- }
1578
- function sendResponse(response1) {
1579
- channel.send_response("MSG", response1, message);
1580
- }
1581
- // do not use _apply_on_SessionObject
1582
- // this._apply_on_SessionObject(CloseSessionResponse, message, channel, function (session) {
1583
- // });
1584
- const session = message.session;
1585
- if (!session) {
1586
- return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1587
- }
1588
- // session has been created but not activated !
1589
- const wasNotActivated = session.status === "new";
1590
- (() => __awaiter(this, void 0, void 0, function* () {
1591
- yield this._closeSession(request.requestHeader.authenticationToken, request.deleteSubscriptions, "CloseSession");
1592
- // if (false && wasNotActivated) {
1593
- // return sendError(StatusCodes.BadSessionNotActivated);
1594
- // }
1595
- response = new node_opcua_service_session_1.CloseSessionResponse({});
1596
- sendResponse(response);
1597
- }))();
1598
- }
1599
- // browse services
1600
- /**
1601
- * @method _on_BrowseRequest
1602
- * @param message
1603
- * @param channel
1604
- * @private
1605
- */
1606
- _on_BrowseRequest(message, channel) {
1607
- const request = message.request;
1608
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_browse_1.BrowseRequest);
1609
- const diagnostic = {};
1610
- this._apply_on_SessionObject(node_opcua_service_browse_1.BrowseResponse, message, channel, (session, sendResponse, sendError) => {
1611
- let response;
1612
- // test view
1613
- if (request.view && !request.view.viewId.isEmpty()) {
1614
- let theView = this.engine.addressSpace.findNode(request.view.viewId);
1615
- if (theView && theView.nodeClass !== node_opcua_data_model_1.NodeClass.View) {
1616
- // Error: theView is not a View
1617
- diagnostic.localizedText = { text: "Expecting a view here" };
1618
- theView = null;
1619
- }
1620
- if (!theView) {
1621
- return sendError(node_opcua_status_code_1.StatusCodes.BadViewIdUnknown);
1622
- }
1623
- }
1624
- if (!request.nodesToBrowse || request.nodesToBrowse.length === 0) {
1625
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1626
- }
1627
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerBrowse > 0) {
1628
- if (request.nodesToBrowse.length > this.engine.serverCapabilities.operationLimits.maxNodesPerBrowse) {
1629
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1630
- }
1631
- }
1632
- // limit results to requestedMaxReferencesPerNode further so it never exceed a too big number
1633
- const requestedMaxReferencesPerNode = Math.min(9876, request.requestedMaxReferencesPerNode);
1634
- (0, node_opcua_assert_1.assert)(request.nodesToBrowse[0].schema.name === "BrowseDescription");
1635
- const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1636
- const f = (0, util_1.callbackify)(this.engine.browseWithAutomaticExpansion).bind(this.engine);
1637
- f(request.nodesToBrowse, context, (err, results) => {
1638
- // istanbul ignore next
1639
- if (!results) {
1640
- throw new Error("internal error : " + (err === null || err === void 0 ? void 0 : err.message));
1641
- }
1642
- (0, node_opcua_assert_1.assert)(results[0].schema.name === "BrowseResult");
1643
- // handle continuation point and requestedMaxReferencesPerNode
1644
- const maxBrowseContinuationPoints = this.engine.serverCapabilities.maxBrowseContinuationPoints;
1645
- results = results.map((result) => {
1646
- (0, node_opcua_assert_1.assert)(!result.continuationPoint);
1647
- // istanbul ignore next
1648
- if (!session.continuationPointManager) {
1649
- return new node_opcua_types_1.BrowseResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNoContinuationPoints });
1650
- }
1651
- if (session.continuationPointManager.hasReachedMaximum(maxBrowseContinuationPoints)) {
1652
- return new node_opcua_types_1.BrowseResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNoContinuationPoints });
1653
- }
1654
- const truncatedResult = session.continuationPointManager.registerReferences(requestedMaxReferencesPerNode, result.references || [], { continuationPoint: null });
1655
- let { statusCode } = truncatedResult;
1656
- const { continuationPoint, values } = truncatedResult;
1657
- statusCode = result.statusCode;
1658
- return new node_opcua_types_1.BrowseResult({
1659
- statusCode,
1660
- continuationPoint,
1661
- references: values
1662
- });
1663
- });
1664
- response = new node_opcua_service_browse_1.BrowseResponse({
1665
- diagnosticInfos: undefined,
1666
- results
1667
- });
1668
- sendResponse(response);
1669
- });
1670
- });
1671
- }
1672
- /**
1673
- * @method _on_BrowseNextRequest
1674
- * @param message
1675
- * @param channel
1676
- * @private
1677
- */
1678
- _on_BrowseNextRequest(message, channel) {
1679
- const request = message.request;
1680
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_browse_1.BrowseNextRequest);
1681
- this._apply_on_SessionObject(node_opcua_service_browse_1.BrowseNextResponse, message, channel, (session, sendResponse, sendError) => {
1682
- if (!request.continuationPoints || request.continuationPoints.length === 0) {
1683
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1684
- }
1685
- const results = request.continuationPoints
1686
- .map((continuationPoint, index) => session.continuationPointManager.getNextReferences(0, {
1687
- continuationPoint,
1688
- index,
1689
- releaseContinuationPoints: request.releaseContinuationPoints
1690
- }))
1691
- .map((r) => ({
1692
- continuationPoint: r.continuationPoint,
1693
- references: r.values,
1694
- statusCode: r.statusCode
1695
- }));
1696
- const response = new node_opcua_service_browse_1.BrowseNextResponse({
1697
- diagnosticInfos: undefined,
1698
- results
1699
- });
1700
- sendResponse(response);
1701
- });
1702
- }
1703
- // read services
1704
- _on_ReadRequest(message, channel) {
1705
- const request = message.request;
1706
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_read_1.ReadRequest);
1707
- this._apply_on_SessionObject(node_opcua_service_read_1.ReadResponse, message, channel, (session, sendResponse, sendError) => {
1708
- const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1709
- let response;
1710
- let results = [];
1711
- const timestampsToReturn = request.timestampsToReturn;
1712
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1713
- return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1714
- }
1715
- if (request.maxAge < 0) {
1716
- return sendError(node_opcua_status_code_1.StatusCodes.BadMaxAgeInvalid);
1717
- }
1718
- request.nodesToRead = request.nodesToRead || [];
1719
- if (!request.nodesToRead || request.nodesToRead.length <= 0) {
1720
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1721
- }
1722
- (0, node_opcua_assert_1.assert)(request.nodesToRead[0].schema.name === "ReadValueId");
1723
- // limit size of nodesToRead array to maxNodesPerRead
1724
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerRead > 0) {
1725
- if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRead) {
1726
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1727
- }
1728
- }
1729
- // proceed with registered nodes alias resolution
1730
- for (const nodeToRead of request.nodesToRead) {
1731
- nodeToRead.nodeId = session.resolveRegisteredNode(nodeToRead.nodeId);
1732
- }
1733
- // ask for a refresh of asynchronous variables
1734
- this.engine.refreshValues(request.nodesToRead, request.maxAge, (err) => {
1735
- (0, node_opcua_assert_1.assert)(!err, " error not handled here , fix me");
1736
- results = this.engine.read(context, request);
1737
- (0, node_opcua_assert_1.assert)(results[0].schema.name === "DataValue");
1738
- (0, node_opcua_assert_1.assert)(results.length === request.nodesToRead.length);
1739
- response = new node_opcua_service_read_1.ReadResponse({
1740
- diagnosticInfos: undefined,
1741
- results: undefined
1742
- });
1743
- // set it here for performance
1744
- response.results = results;
1745
- (0, node_opcua_assert_1.assert)(response.diagnosticInfos.length === 0);
1746
- sendResponse(response);
1747
- });
1748
- });
1749
- }
1750
- // read services
1751
- _on_HistoryReadRequest(message, channel) {
1752
- const request = message.request;
1753
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_history_1.HistoryReadRequest);
1754
- this._apply_on_SessionObject(node_opcua_service_history_1.HistoryReadResponse, message, channel, (session, sendResponse, sendError) => {
1755
- let response;
1756
- const timestampsToReturn = request.timestampsToReturn;
1757
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1758
- return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1759
- }
1760
- request.nodesToRead = request.nodesToRead || [];
1761
- if (!request.nodesToRead || request.nodesToRead.length <= 0) {
1762
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1763
- }
1764
- (0, node_opcua_assert_1.assert)(request.nodesToRead[0].schema.name === "HistoryReadValueId");
1765
- // limit size of nodesToRead array to maxNodesPerRead
1766
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerRead > 0) {
1767
- if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRead) {
1768
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1769
- }
1770
- }
1771
- // todo : handle
1772
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadData > 0) {
1773
- if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadData) {
1774
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1775
- }
1776
- }
1777
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadEvents > 0) {
1778
- if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadEvents) {
1779
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1780
- }
1781
- }
1782
- const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1783
- // ask for a refresh of asynchronous variables
1784
- this.engine.refreshValues(request.nodesToRead, 0, (err) => {
1785
- (0, node_opcua_assert_1.assert)(!err, " error not handled here , fix me"); // TODO
1786
- this.engine.historyRead(context, request, (err1, results) => {
1787
- if (err1) {
1788
- return sendError(node_opcua_status_code_1.StatusCodes.BadHistoryOperationInvalid);
1789
- }
1790
- if (!results) {
1791
- return sendError(node_opcua_status_code_1.StatusCodes.BadHistoryOperationInvalid);
1792
- }
1793
- (0, node_opcua_assert_1.assert)(results[0].schema.name === "HistoryReadResult");
1794
- (0, node_opcua_assert_1.assert)(results.length === request.nodesToRead.length);
1795
- response = new node_opcua_service_history_1.HistoryReadResponse({
1796
- diagnosticInfos: undefined,
1797
- results
1798
- });
1799
- (0, node_opcua_assert_1.assert)(response.diagnosticInfos.length === 0);
1800
- sendResponse(response);
1801
- });
1802
- });
1803
- });
1804
- }
1805
- /*
1806
- // write services
1807
- // OPCUA Specification 1.02 Part 3 : 5.10.4 Write
1808
- // This Service is used to write values to one or more Attributes of one or more Nodes. For constructed
1809
- // Attribute values whose elements are indexed, such as an array, this Service allows Clients to write
1810
- // the entire set of indexed values as a composite, to write individual elements or to write ranges of
1811
- // elements of the composite.
1812
- // The values are written to the data source, such as a device, and the Service does not return until it writes
1813
- // the values or determines that the value cannot be written. In certain cases, the Server will successfully
1814
- // to an intermediate system or Server, and will not know if the data source was updated properly. In these cases,
1815
- // the Server should report a success code that indicates that the write was not verified.
1816
- // In the cases where the Server is able to verify that it has successfully written to the data source,
1817
- // it reports an unconditional success.
1818
- */
1819
- _on_WriteRequest(message, channel) {
1820
- const request = message.request;
1821
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_write_1.WriteRequest);
1822
- (0, node_opcua_assert_1.assert)(!request.nodesToWrite || Array.isArray(request.nodesToWrite));
1823
- this._apply_on_SessionObject(node_opcua_service_write_1.WriteResponse, message, channel, (session, sendResponse, sendError) => {
1824
- let response;
1825
- if (!request.nodesToWrite || request.nodesToWrite.length === 0) {
1826
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1827
- }
1828
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerWrite > 0) {
1829
- if (request.nodesToWrite.length > this.engine.serverCapabilities.operationLimits.maxNodesPerWrite) {
1830
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1831
- }
1832
- }
1833
- // proceed with registered nodes alias resolution
1834
- for (const nodeToWrite of request.nodesToWrite) {
1835
- nodeToWrite.nodeId = session.resolveRegisteredNode(nodeToWrite.nodeId);
1836
- }
1837
- const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1838
- (0, node_opcua_assert_1.assert)(request.nodesToWrite[0].schema.name === "WriteValue");
1839
- this.engine.write(context, request.nodesToWrite, (err, results) => {
1840
- if (err) {
1841
- errorLog(err);
1842
- return sendError(node_opcua_status_code_1.StatusCodes.BadInternalError);
1843
- }
1844
- (0, node_opcua_assert_1.assert)(Array.isArray(results));
1845
- (0, node_opcua_assert_1.assert)(results.length === request.nodesToWrite.length);
1846
- response = new node_opcua_service_write_1.WriteResponse({
1847
- diagnosticInfos: undefined,
1848
- results
1849
- });
1850
- sendResponse(response);
1851
- });
1852
- });
1853
- }
1854
- // subscription services
1855
- _on_CreateSubscriptionRequest(message, channel) {
1856
- const engine = this.engine;
1857
- const addressSpace = engine.addressSpace;
1858
- const request = message.request;
1859
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.CreateSubscriptionRequest);
1860
- this._apply_on_SessionObject(node_opcua_service_subscription_1.CreateSubscriptionResponse, message, channel, (session, sendResponse, sendError) => {
1861
- const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1862
- if (session.currentSubscriptionCount >= OPCUAServer.MAX_SUBSCRIPTION) {
1863
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManySubscriptions);
1864
- }
1865
- const subscription = session.createSubscription(request);
1866
- subscription.on("monitoredItem", (monitoredItem) => {
1867
- prepareMonitoredItem(context, addressSpace, monitoredItem);
1868
- });
1869
- const response = new node_opcua_service_subscription_1.CreateSubscriptionResponse({
1870
- revisedLifetimeCount: subscription.lifeTimeCount,
1871
- revisedMaxKeepAliveCount: subscription.maxKeepAliveCount,
1872
- revisedPublishingInterval: subscription.publishingInterval,
1873
- subscriptionId: subscription.id
1874
- });
1875
- sendResponse(response);
1876
- });
1877
- }
1878
- _on_DeleteSubscriptionsRequest(message, channel) {
1879
- const request = message.request;
1880
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.DeleteSubscriptionsRequest);
1881
- this._apply_on_SubscriptionIds(node_opcua_service_subscription_1.DeleteSubscriptionsResponse, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () {
1882
- let subscription = this.engine.findOrphanSubscription(subscriptionId);
1883
- // istanbul ignore next
1884
- if (subscription) {
1885
- warningLog("Deleting an orphan subscription", subscriptionId);
1886
- yield this._beforeDeleteSubscription(subscription);
1887
- return this.engine.deleteOrphanSubscription(subscription);
1888
- }
1889
- subscription = session.getSubscription(subscriptionId);
1890
- if (subscription) {
1891
- yield this._beforeDeleteSubscription(subscription);
1892
- }
1893
- return session.deleteSubscription(subscriptionId);
1894
- }));
1895
- }
1896
- _on_TransferSubscriptionsRequest(message, channel) {
1897
- //
1898
- // sendInitialValue Boolean
1899
- // A Boolean parameter with the following values:
1900
- // TRUE the first Publish response(s) after the TransferSubscriptions call shall
1901
- // contain the current values of all Monitored Items in the Subscription where
1902
- // the Monitoring Mode is set to Reporting.
1903
- // FALSE the first Publish response after the TransferSubscriptions call shall contain only the value
1904
- // changes since the last Publish response was sent.
1905
- // This parameter only applies to MonitoredItems used for monitoring Attribute changes.
1906
- //
1907
- const engine = this.engine;
1908
- const request = message.request;
1909
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.TransferSubscriptionsRequest);
1910
- this._apply_on_SubscriptionIds(node_opcua_service_subscription_1.TransferSubscriptionsResponse, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () { return yield engine.transferSubscription(session, subscriptionId, request.sendInitialValues); }));
1911
- }
1912
- _on_CreateMonitoredItemsRequest(message, channel) {
1913
- const engine = this.engine;
1914
- const addressSpace = engine.addressSpace;
1915
- const request = message.request;
1916
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.CreateMonitoredItemsRequest);
1917
- this._apply_on_Subscription(node_opcua_service_subscription_1.CreateMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1918
- const timestampsToReturn = request.timestampsToReturn;
1919
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1920
- return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1921
- }
1922
- if (!request.itemsToCreate || request.itemsToCreate.length === 0) {
1923
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1924
- }
1925
- if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
1926
- if (request.itemsToCreate.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
1927
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1928
- }
1929
- }
1930
- const options = this.options;
1931
- let results = [];
1932
- if (options.onCreateMonitoredItem) {
1933
- const resultsPromise = request.itemsToCreate.map((monitoredItemCreateRequest) => __awaiter(this, void 0, void 0, function* () {
1934
- const { monitoredItem, createResult } = subscription.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
1935
- if (monitoredItem) {
1936
- yield options.onCreateMonitoredItem(subscription, monitoredItem);
1937
- subscription.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
1938
- }
1939
- return createResult;
1940
- }));
1941
- results = yield Promise.all(resultsPromise);
1942
- }
1943
- else {
1944
- results = request.itemsToCreate.map((monitoredItemCreateRequest) => {
1945
- const { monitoredItem, createResult } = subscription.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
1946
- if (monitoredItem) {
1947
- subscription.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
1948
- }
1949
- return createResult;
1950
- });
1951
- }
1952
- const response = new node_opcua_service_subscription_1.CreateMonitoredItemsResponse({
1953
- responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.Good },
1954
- results
1955
- // ,diagnosticInfos: []
1956
- });
1957
- sendResponse(response);
1958
- }));
1959
- }
1960
- _on_ModifySubscriptionRequest(message, channel) {
1961
- const request = message.request;
1962
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.ModifySubscriptionRequest);
1963
- this._apply_on_Subscription(node_opcua_service_subscription_1.ModifySubscriptionResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1964
- subscription.modify(request);
1965
- const response = new node_opcua_service_subscription_1.ModifySubscriptionResponse({
1966
- revisedLifetimeCount: subscription.lifeTimeCount,
1967
- revisedMaxKeepAliveCount: subscription.maxKeepAliveCount,
1968
- revisedPublishingInterval: subscription.publishingInterval
1969
- });
1970
- sendResponse(response);
1971
- }));
1972
- }
1973
- _on_ModifyMonitoredItemsRequest(message, channel) {
1974
- const request = message.request;
1975
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.ModifyMonitoredItemsRequest);
1976
- this._apply_on_Subscription(node_opcua_service_subscription_1.ModifyMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1977
- const timestampsToReturn = request.timestampsToReturn;
1978
- if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1979
- return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1980
- }
1981
- if (!request.itemsToModify || request.itemsToModify.length === 0) {
1982
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1983
- }
1984
- /* istanbul ignore next */
1985
- if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
1986
- if (request.itemsToModify.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
1987
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1988
- }
1989
- }
1990
- const itemsToModify = request.itemsToModify; // MonitoredItemModifyRequest
1991
- function modifyMonitoredItem(item) {
1992
- const monitoredItemId = item.monitoredItemId;
1993
- const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
1994
- if (!monitoredItem) {
1995
- return new node_opcua_service_subscription_1.MonitoredItemModifyResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid });
1996
- }
1997
- // adjust samplingInterval if === -1
1998
- if (item.requestedParameters.samplingInterval === -1) {
1999
- item.requestedParameters.samplingInterval = subscription.publishingInterval;
2000
- }
2001
- return monitoredItem.modify(timestampsToReturn, item.requestedParameters);
2002
- }
2003
- const results = itemsToModify.map(modifyMonitoredItem);
2004
- const response = new node_opcua_service_subscription_1.ModifyMonitoredItemsResponse({
2005
- results
2006
- });
2007
- sendResponse(response);
2008
- }));
2009
- }
2010
- _on_PublishRequest(message, channel) {
2011
- const request = message.request;
2012
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.PublishRequest);
2013
- this._apply_on_SessionObject(node_opcua_service_subscription_1.PublishResponse, message, channel, (session, sendResponse, sendError) => {
2014
- (0, node_opcua_assert_1.assert)(session);
2015
- (0, node_opcua_assert_1.assert)(session.publishEngine); // server.publishEngine doesn't exists, OPCUAServer has probably shut down already
2016
- session.publishEngine._on_PublishRequest(request, (request1, response) => {
2017
- sendResponse(response);
2018
- });
2019
- });
2020
- }
2021
- _on_SetPublishingModeRequest(message, channel) {
2022
- const request = message.request;
2023
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetPublishingModeRequest);
2024
- const publishingEnabled = request.publishingEnabled;
2025
- this._apply_on_Subscriptions(node_opcua_service_subscription_1.SetPublishingModeResponse, message, channel, (session, subscription) => __awaiter(this, void 0, void 0, function* () {
2026
- return subscription.setPublishingMode(publishingEnabled);
2027
- }));
2028
- }
2029
- _on_DeleteMonitoredItemsRequest(message, channel) {
2030
- const request = message.request;
2031
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.DeleteMonitoredItemsRequest);
2032
- this._apply_on_Subscription(node_opcua_service_subscription_1.DeleteMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2033
- /* istanbul ignore next */
2034
- if (!request.monitoredItemIds || request.monitoredItemIds.length === 0) {
2035
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2036
- }
2037
- /* istanbul ignore next */
2038
- if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2039
- if (request.monitoredItemIds.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2040
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2041
- }
2042
- }
2043
- const resultsPromises = request.monitoredItemIds.map((monitoredItemId) => __awaiter(this, void 0, void 0, function* () {
2044
- if (this.options.onDeleteMonitoredItem) {
2045
- const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
2046
- if (monitoredItem) {
2047
- yield this.options.onDeleteMonitoredItem(subscription, monitoredItem);
2048
- }
2049
- }
2050
- return subscription.removeMonitoredItem(monitoredItemId);
2051
- }));
2052
- try {
2053
- const results = yield Promise.all(resultsPromises);
2054
- const response = new node_opcua_service_subscription_1.DeleteMonitoredItemsResponse({
2055
- diagnosticInfos: undefined,
2056
- results
2057
- });
2058
- sendResponse(response);
2059
- }
2060
- catch (err) {
2061
- console.log(err);
2062
- return sendError(node_opcua_status_code_1.StatusCodes.BadInternalError);
2063
- }
2064
- }));
2065
- }
2066
- _on_SetTriggeringRequest(message, channel) {
2067
- const request = message.request;
2068
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetTriggeringRequest);
2069
- this._apply_on_Subscription(node_opcua_service_subscription_1.SetTriggeringResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2070
- /* */
2071
- const { triggeringItemId, linksToAdd, linksToRemove } = request;
2072
- /**
2073
- * The MaxMonitoredItemsPerCall Property indicates
2074
- * [...]
2075
- * • the maximum size of the sum of the linksToAdd and linksToRemove arrays when a
2076
- * Client calls the SetTriggering Service.
2077
- *
2078
- */
2079
- const maxElements = (linksToAdd ? linksToAdd.length : 0) + (linksToRemove ? linksToRemove.length : 0);
2080
- if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2081
- if (maxElements > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2082
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2083
- }
2084
- }
2085
- const { addResults, removeResults, statusCode } = subscription.setTriggering(triggeringItemId, linksToAdd, linksToRemove);
2086
- const response = new node_opcua_service_subscription_1.SetTriggeringResponse({
2087
- responseHeader: { serviceResult: statusCode },
2088
- addResults,
2089
- removeResults,
2090
- addDiagnosticInfos: null,
2091
- removeDiagnosticInfos: null
2092
- });
2093
- sendResponse(response);
2094
- }));
2095
- }
2096
- _beforeDeleteSubscription(subscription) {
2097
- return __awaiter(this, void 0, void 0, function* () {
2098
- if (!this.options.onDeleteMonitoredItem) {
2099
- return;
2100
- }
2101
- yield subscription.applyOnMonitoredItem(this.options.onDeleteMonitoredItem.bind(null, subscription));
2102
- });
2103
- }
2104
- _on_RepublishRequest(message, channel) {
2105
- const request = message.request;
2106
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.RepublishRequest);
2107
- this._apply_on_Subscription(node_opcua_service_subscription_1.RepublishResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2108
- // update diagnostic counter
2109
- subscription.subscriptionDiagnostics.republishRequestCount += 1;
2110
- subscription.subscriptionDiagnostics.republishMessageRequestCount += 1;
2111
- const retransmitSequenceNumber = request.retransmitSequenceNumber;
2112
- const notificationMessage = subscription.getMessageForSequenceNumber(retransmitSequenceNumber);
2113
- if (!notificationMessage) {
2114
- return sendError(node_opcua_status_code_1.StatusCodes.BadMessageNotAvailable);
2115
- }
2116
- const response = new node_opcua_service_subscription_1.RepublishResponse({
2117
- notificationMessage,
2118
- responseHeader: {
2119
- serviceResult: node_opcua_status_code_1.StatusCodes.Good
2120
- }
2121
- });
2122
- // update diagnostic counter
2123
- subscription.subscriptionDiagnostics.republishMessageCount += 1;
2124
- sendResponse(response);
2125
- }));
2126
- }
2127
- // Bad_NothingToDo
2128
- // Bad_TooManyOperations
2129
- // Bad_SubscriptionIdInvalid
2130
- // Bad_MonitoringModeInvalid
2131
- _on_SetMonitoringModeRequest(message, channel) {
2132
- const request = message.request;
2133
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetMonitoringModeRequest);
2134
- this._apply_on_Subscription(node_opcua_service_subscription_1.SetMonitoringModeResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2135
- /* istanbul ignore next */
2136
- if (!request.monitoredItemIds || request.monitoredItemIds.length === 0) {
2137
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2138
- }
2139
- /* istanbul ignore next */
2140
- if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2141
- if (request.monitoredItemIds.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2142
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2143
- }
2144
- }
2145
- const monitoringMode = request.monitoringMode;
2146
- if (!isMonitoringModeValid(monitoringMode)) {
2147
- return sendError(node_opcua_status_code_1.StatusCodes.BadMonitoringModeInvalid);
2148
- }
2149
- const results = request.monitoredItemIds.map((monitoredItemId) => {
2150
- const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
2151
- if (!monitoredItem) {
2152
- return node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid;
2153
- }
2154
- monitoredItem.setMonitoringMode(monitoringMode);
2155
- return node_opcua_status_code_1.StatusCodes.Good;
2156
- });
2157
- const response = new node_opcua_service_subscription_1.SetMonitoringModeResponse({
2158
- results
2159
- });
2160
- sendResponse(response);
2161
- }));
2162
- }
2163
- // _on_TranslateBrowsePathsToNodeIds service
2164
- _on_TranslateBrowsePathsToNodeIdsRequest(message, channel) {
2165
- const request = message.request;
2166
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsRequest);
2167
- this._apply_on_SessionObject(node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2168
- if (!request.browsePaths || request.browsePaths.length === 0) {
2169
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2170
- }
2171
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerTranslateBrowsePathsToNodeIds > 0) {
2172
- if (request.browsePaths.length >
2173
- this.engine.serverCapabilities.operationLimits.maxNodesPerTranslateBrowsePathsToNodeIds) {
2174
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2175
- }
2176
- }
2177
- const browsePathsResults = request.browsePaths.map((browsePath) => this.engine.browsePath(browsePath));
2178
- const response = new node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse({
2179
- diagnosticInfos: null,
2180
- results: browsePathsResults
2181
- });
2182
- sendResponse(response);
2183
- }));
2184
- }
2185
- // Call Service Result Codes
2186
- // Symbolic Id Description
2187
- // Bad_NothingToDo See Table 165 for the description of this result code.
2188
- // Bad_TooManyOperations See Table 165 for the description of this result code.
2189
- //
2190
- _on_CallRequest(message, channel) {
2191
- const request = message.request;
2192
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_call_1.CallRequest);
2193
- this._apply_on_SessionObject(node_opcua_service_call_1.CallResponse, message, channel, (session, sendResponse, sendError) => {
2194
- let response;
2195
- if (!request.methodsToCall || request.methodsToCall.length === 0) {
2196
- return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2197
- }
2198
- // the MaxNodesPerMethodCall Property indicates the maximum size of the methodsToCall array when
2199
- // a Client calls the Call Service.
2200
- let maxNodesPerMethodCall = this.engine.serverCapabilities.operationLimits.maxNodesPerMethodCall;
2201
- maxNodesPerMethodCall = maxNodesPerMethodCall <= 0 ? 1000 : maxNodesPerMethodCall;
2202
- if (request.methodsToCall.length > maxNodesPerMethodCall) {
2203
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2204
- }
2205
- /* jshint validthis: true */
2206
- const addressSpace = this.engine.addressSpace;
2207
- const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
2208
- async.map(request.methodsToCall, node_opcua_address_space_1.callMethodHelper.bind(null, context, addressSpace), (err, results) => {
2209
- /* istanbul ignore next */
2210
- if (err) {
2211
- errorLog("ERROR in method Call !! ", err);
2212
- }
2213
- (0, node_opcua_assert_1.assert)(Array.isArray(results));
2214
- response = new node_opcua_service_call_1.CallResponse({
2215
- results: results
2216
- });
2217
- filterDiagnosticInfo(request.requestHeader.returnDiagnostics, response);
2218
- sendResponse(response);
2219
- });
2220
- });
2221
- }
2222
- _on_RegisterNodesRequest(message, channel) {
2223
- const request = message.request;
2224
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_register_node_1.RegisterNodesRequest);
2225
- this._apply_on_SessionObject(node_opcua_service_register_node_1.RegisterNodesResponse, message, channel, (session, sendResponse, sendError) => {
2226
- let response;
2227
- if (!request.nodesToRegister || request.nodesToRegister.length === 0) {
2228
- response = new node_opcua_service_register_node_1.RegisterNodesResponse({ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.BadNothingToDo } });
2229
- return sendResponse(response);
2230
- }
2231
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes > 0) {
2232
- if (request.nodesToRegister.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes) {
2233
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2234
- }
2235
- }
2236
- // A list of NodeIds which the Client shall use for subsequent access operations. The
2237
- // size and order of this list matches the size and order of the nodesToRegister
2238
- // request parameter.
2239
- // The Server may return the NodeId from the request or a new (an alias) NodeId. It
2240
- // is recommended that the Server return a numeric NodeIds for aliasing.
2241
- // In case no optimization is supported for a Node, the Server shall return the
2242
- // NodeId from the request.
2243
- const registeredNodeIds = request.nodesToRegister.map((nodeId) => session.registerNode(nodeId));
2244
- response = new node_opcua_service_register_node_1.RegisterNodesResponse({
2245
- registeredNodeIds
2246
- });
2247
- sendResponse(response);
2248
- });
2249
- }
2250
- _on_UnregisterNodesRequest(message, channel) {
2251
- const request = message.request;
2252
- (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_register_node_1.UnregisterNodesRequest);
2253
- this._apply_on_SessionObject(node_opcua_service_register_node_1.UnregisterNodesResponse, message, channel, (session, sendResponse, sendError) => {
2254
- let response;
2255
- request.nodesToUnregister = request.nodesToUnregister || [];
2256
- if (!request.nodesToUnregister || request.nodesToUnregister.length === 0) {
2257
- response = new node_opcua_service_register_node_1.UnregisterNodesResponse({ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.BadNothingToDo } });
2258
- return sendResponse(response);
2259
- }
2260
- if (this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes > 0) {
2261
- if (request.nodesToUnregister.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes) {
2262
- return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2263
- }
2264
- }
2265
- request.nodesToUnregister.map((nodeId) => session.unRegisterNode(nodeId));
2266
- response = new node_opcua_service_register_node_1.UnregisterNodesResponse({});
2267
- sendResponse(response);
2268
- });
2269
- }
2270
- /* istanbul ignore next */
2271
- _on_Cancel(message, channel) {
2272
- return g_sendError(channel, message, node_opcua_types_1.CancelResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2273
- }
2274
- // NodeManagement Service Set Overview
2275
- // This Service Set defines Services to add and delete AddressSpace Nodes and References between them. All added
2276
- // Nodes continue to exist in the AddressSpace even if the Client that created them disconnects from the Server.
2277
- //
2278
- /* istanbul ignore next */
2279
- _on_AddNodes(message, channel) {
2280
- return g_sendError(channel, message, node_opcua_service_node_management_1.AddNodesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2281
- }
2282
- /* istanbul ignore next */
2283
- _on_AddReferences(message, channel) {
2284
- return g_sendError(channel, message, node_opcua_service_node_management_1.AddReferencesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2285
- }
2286
- /* istanbul ignore next */
2287
- _on_DeleteNodes(message, channel) {
2288
- return g_sendError(channel, message, node_opcua_service_node_management_1.DeleteNodesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2289
- }
2290
- /* istanbul ignore next */
2291
- _on_DeleteReferences(message, channel) {
2292
- return g_sendError(channel, message, node_opcua_service_node_management_1.DeleteReferencesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2293
- }
2294
- // Query Service
2295
- /* istanbul ignore next */
2296
- _on_QueryFirst(message, channel) {
2297
- return g_sendError(channel, message, node_opcua_service_query_1.QueryFirstResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2298
- }
2299
- /* istanbul ignore next */
2300
- _on_QueryNext(message, channel) {
2301
- return g_sendError(channel, message, node_opcua_service_query_1.QueryNextResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2302
- }
2303
- /* istanbul ignore next */
2304
- _on_HistoryUpdate(message, channel) {
2305
- return g_sendError(channel, message, node_opcua_service_history_1.HistoryUpdateResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2306
- }
2307
- createEndpoint(port1, serverOptions) {
2308
- // add the tcp/ip endpoint with no security
2309
- const endPoint = new server_end_point_1.OPCUAServerEndPoint({
2310
- port: port1,
2311
- certificateManager: this.serverCertificateManager,
2312
- certificateChain: this.getCertificateChain(),
2313
- privateKey: this.getPrivateKey(),
2314
- defaultSecureTokenLifetime: serverOptions.defaultSecureTokenLifetime || 600000,
2315
- timeout: serverOptions.timeout || 3 * 60 * 1000,
2316
- maxConnections: this.maxConnectionsPerEndpoint,
2317
- objectFactory: this.objectFactory,
2318
- serverInfo: this.serverInfo
2319
- });
2320
- return endPoint;
2321
- }
2322
- createEndpointDescriptions(serverOption, endpointOptions) {
2323
- /* istanbul ignore next */
2324
- if (!endpointOptions) {
2325
- throw new Error("internal error");
2326
- }
2327
- const hostname = (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
2328
- endpointOptions.hostname = endpointOptions.hostname || hostname;
2329
- endpointOptions.port = endpointOptions.port || 26543;
2330
- /* istanbul ignore next */
2331
- if (!Object.prototype.hasOwnProperty.call(endpointOptions, "port") ||
2332
- !isFinite(endpointOptions.port) ||
2333
- typeof endpointOptions.port !== "number") {
2334
- throw new Error("expecting a valid port (number)");
2335
- }
2336
- const port = Number(endpointOptions.port || 0);
2337
- const endPoint = this.createEndpoint(port, serverOption);
2338
- endpointOptions.alternateHostname = endpointOptions.alternateHostname || [];
2339
- const alternateHostname = endpointOptions.alternateHostname instanceof Array
2340
- ? endpointOptions.alternateHostname
2341
- : [endpointOptions.alternateHostname];
2342
- const allowAnonymous = endpointOptions.allowAnonymous === undefined ? true : !!endpointOptions.allowAnonymous;
2343
- endPoint.addStandardEndpointDescriptions({
2344
- allowAnonymous,
2345
- securityModes: endpointOptions.securityModes,
2346
- securityPolicies: endpointOptions.securityPolicies,
2347
- hostname: endpointOptions.hostname,
2348
- alternateHostname,
2349
- disableDiscovery: !!endpointOptions.disableDiscovery,
2350
- // xx hostname,
2351
- resourcePath: serverOption.resourcePath || ""
2352
- });
2353
- return endPoint;
2354
- }
2355
- initializeCM() {
2356
- const _super = Object.create(null, {
2357
- initializeCM: { get: () => super.initializeCM }
2358
- });
2359
- return __awaiter(this, void 0, void 0, function* () {
2360
- yield _super.initializeCM.call(this);
2361
- yield this.userCertificateManager.initialize();
2362
- });
2363
- }
2364
- }
2365
- exports.OPCUAServer = OPCUAServer;
2366
- OPCUAServer.defaultShutdownTimeout = 100; // 250 ms
2367
- /**
2368
- * if requestExactEndpointUrl is set to true the server will only accept createSession that have a endpointUrl that strictly matches
2369
- * one of the provided endpoint.
2370
- * This mean that if the server expose a endpoint with url such as opc.tcp://MYHOSTNAME:1234, client will not be able to reach the server
2371
- * with the ip address of the server.
2372
- * requestExactEndpointUrl = true => emulates the Prosys Server behavior
2373
- * requestExactEndpointUrl = false => emulates the Unified Automation behavior.
2374
- */
2375
- OPCUAServer.requestExactEndpointUrl = g_requestExactEndpointUrl;
2376
- OPCUAServer.registry = new node_opcua_object_registry_1.ObjectRegistry();
2377
- OPCUAServer.fallbackSessionName = "Client didn't provide a meaningful sessionName ...";
2378
- /**
2379
- * the maximum number of subscription that can be created per server
2380
- */
2381
- OPCUAServer.MAX_SUBSCRIPTION = 50;
2382
- const opts = { multiArgs: false };
2383
- OPCUAServer.prototype.start = thenify.withCallback(OPCUAServer.prototype.start, opts);
2384
- OPCUAServer.prototype.initialize = thenify.withCallback(OPCUAServer.prototype.initialize, opts);
2385
- OPCUAServer.prototype.shutdown = thenify.withCallback(OPCUAServer.prototype.shutdown, opts);
1
+ "use strict";
2
+ /**
3
+ * @module node-opcua-server
4
+ */
5
+ // tslint:disable:no-console
6
+ // tslint:disable:max-line-length
7
+ // tslint:disable:unified-signatures
8
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
9
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
10
+ return new (P || (P = Promise))(function (resolve, reject) {
11
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
12
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
13
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
14
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
15
+ });
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.OPCUAServer = exports.RegisterServerMethod = exports.filterDiagnosticInfo = void 0;
19
+ const crypto = require("crypto");
20
+ const util_1 = require("util");
21
+ const async = require("async");
22
+ const chalk = require("chalk");
23
+ const node_opcua_hostname_1 = require("node-opcua-hostname");
24
+ const node_opcua_assert_1 = require("node-opcua-assert");
25
+ const utils = require("node-opcua-utils");
26
+ const node_opcua_address_space_1 = require("node-opcua-address-space");
27
+ const node_opcua_certificate_manager_1 = require("node-opcua-certificate-manager");
28
+ const node_opcua_common_1 = require("node-opcua-common");
29
+ const node_opcua_crypto_1 = require("node-opcua-crypto");
30
+ const node_opcua_data_model_1 = require("node-opcua-data-model");
31
+ const node_opcua_data_value_1 = require("node-opcua-data-value");
32
+ const node_opcua_debug_1 = require("node-opcua-debug");
33
+ const node_opcua_object_registry_1 = require("node-opcua-object-registry");
34
+ const node_opcua_secure_channel_1 = require("node-opcua-secure-channel");
35
+ const node_opcua_service_browse_1 = require("node-opcua-service-browse");
36
+ const node_opcua_service_call_1 = require("node-opcua-service-call");
37
+ const node_opcua_service_endpoints_1 = require("node-opcua-service-endpoints");
38
+ const node_opcua_service_history_1 = require("node-opcua-service-history");
39
+ const node_opcua_service_node_management_1 = require("node-opcua-service-node-management");
40
+ const node_opcua_service_query_1 = require("node-opcua-service-query");
41
+ const node_opcua_service_read_1 = require("node-opcua-service-read");
42
+ const node_opcua_service_register_node_1 = require("node-opcua-service-register-node");
43
+ const node_opcua_service_session_1 = require("node-opcua-service-session");
44
+ const node_opcua_service_subscription_1 = require("node-opcua-service-subscription");
45
+ const node_opcua_service_translate_browse_path_1 = require("node-opcua-service-translate-browse-path");
46
+ const node_opcua_service_write_1 = require("node-opcua-service-write");
47
+ const node_opcua_status_code_1 = require("node-opcua-status-code");
48
+ const node_opcua_types_1 = require("node-opcua-types");
49
+ const node_opcua_variant_1 = require("node-opcua-variant");
50
+ const node_opcua_variant_2 = require("node-opcua-variant");
51
+ const node_opcua_utils_1 = require("node-opcua-utils");
52
+ const base_server_1 = require("./base_server");
53
+ const factory_1 = require("./factory");
54
+ const monitored_item_1 = require("./monitored_item");
55
+ const register_server_manager_1 = require("./register_server_manager");
56
+ const register_server_manager_hidden_1 = require("./register_server_manager_hidden");
57
+ const register_server_manager_mdns_only_1 = require("./register_server_manager_mdns_only");
58
+ const server_end_point_1 = require("./server_end_point");
59
+ const server_engine_1 = require("./server_engine");
60
+ const user_manager_1 = require("./user_manager");
61
+ const user_manager_ua_1 = require("./user_manager_ua");
62
+ function isSubscriptionIdInvalid(subscriptionId) {
63
+ return subscriptionId < 0 || subscriptionId >= 0xffffffff;
64
+ }
65
+ // tslint:disable-next-line:no-var-requires
66
+ const thenify = require("thenify");
67
+ // tslint:disable-next-line:no-var-requires
68
+ const package_info = require("../package.json");
69
+ const debugLog = (0, node_opcua_debug_1.make_debugLog)(__filename);
70
+ const errorLog = (0, node_opcua_debug_1.make_errorLog)(__filename);
71
+ const warningLog = (0, node_opcua_debug_1.make_warningLog)(__filename);
72
+ const default_maxAllowedSessionNumber = 10;
73
+ const default_maxConnectionsPerEndpoint = 10;
74
+ function g_sendError(channel, message, ResponseClass, statusCode) {
75
+ const response = new ResponseClass({
76
+ responseHeader: { serviceResult: statusCode }
77
+ });
78
+ return channel.send_response("MSG", response, message);
79
+ }
80
+ const default_build_info = {
81
+ manufacturerName: "NodeOPCUA : MIT Licence ( see http://node-opcua.github.io/)",
82
+ productName: "NodeOPCUA-Server",
83
+ productUri: null,
84
+ softwareVersion: package_info.version,
85
+ buildNumber: "0",
86
+ buildDate: new Date(2020, 1, 1)
87
+ // xx buildDate: fs.statSync(package_json_file).mtime
88
+ };
89
+ const minSessionTimeout = 100; // 100 milliseconds
90
+ const defaultSessionTimeout = 1000 * 30; // 30 seconds
91
+ const maxSessionTimeout = 1000 * 60 * 50; // 50 minutes
92
+ function _adjust_session_timeout(sessionTimeout) {
93
+ let revisedSessionTimeout = sessionTimeout || defaultSessionTimeout;
94
+ revisedSessionTimeout = Math.min(revisedSessionTimeout, maxSessionTimeout);
95
+ revisedSessionTimeout = Math.max(revisedSessionTimeout, minSessionTimeout);
96
+ return revisedSessionTimeout;
97
+ }
98
+ function channel_has_session(channel, session) {
99
+ if (session.channel === channel) {
100
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(channel.sessionTokens, session.authenticationToken.toString()));
101
+ return true;
102
+ }
103
+ return false;
104
+ }
105
+ function moveSessionToChannel(session, channel) {
106
+ debugLog("moveSessionToChannel sessionId", session.nodeId, " channelId=", channel.channelId);
107
+ if (session.publishEngine) {
108
+ session.publishEngine.cancelPendingPublishRequestBeforeChannelChange();
109
+ }
110
+ session._detach_channel();
111
+ session._attach_channel(channel);
112
+ (0, node_opcua_assert_1.assert)(session.channel.channelId === channel.channelId);
113
+ }
114
+ function _attempt_to_close_some_old_unactivated_session(server) {
115
+ return __awaiter(this, void 0, void 0, function* () {
116
+ const session = server.engine.getOldestUnactivatedSession();
117
+ if (session) {
118
+ yield server.engine.closeSession(session.authenticationToken, false, "Forcing");
119
+ }
120
+ });
121
+ }
122
+ function getRequiredEndpointInfo(endpoint) {
123
+ (0, node_opcua_assert_1.assert)(endpoint instanceof node_opcua_types_1.EndpointDescription);
124
+ // It is recommended that Servers only include the server.applicationUri, endpointUrl, securityMode,
125
+ // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all
126
+ // other parameters set to null. Only the recommended parameters shall be verified by
127
+ // the client.
128
+ const e = new node_opcua_types_1.EndpointDescription({
129
+ endpointUrl: endpoint.endpointUrl,
130
+ securityLevel: endpoint.securityLevel,
131
+ securityMode: endpoint.securityMode,
132
+ securityPolicyUri: endpoint.securityPolicyUri,
133
+ server: {
134
+ applicationUri: endpoint.server.applicationUri,
135
+ applicationType: endpoint.server.applicationType,
136
+ applicationName: endpoint.server.applicationName
137
+ // ... to be continued after verifying what fields are actually needed
138
+ },
139
+ transportProfileUri: endpoint.transportProfileUri,
140
+ userIdentityTokens: endpoint.userIdentityTokens
141
+ });
142
+ // reduce even further by explicitly setting unwanted members to null
143
+ e.server.productUri = null;
144
+ e.server.applicationName = null;
145
+ // xx e.server.applicationType = null as any;
146
+ e.server.gatewayServerUri = null;
147
+ e.server.discoveryProfileUri = null;
148
+ e.server.discoveryUrls = null;
149
+ e.serverCertificate = null;
150
+ return e;
151
+ }
152
+ // serverUri String This value is only specified if the EndpointDescription has a gatewayServerUri.
153
+ // This value is the applicationUri from the EndpointDescription which is the applicationUri for the
154
+ // underlying Server. The type EndpointDescription is defined in 7.10.
155
+ function _serverEndpointsForCreateSessionResponse(server, endpointUrl, serverUri) {
156
+ serverUri = null; // unused then
157
+ // The Server shall return a set of EndpointDescriptions available for the serverUri specified in the request.
158
+ // It is recommended that Servers only include the endpointUrl, securityMode,
159
+ // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all other parameters
160
+ // set to null. Only the recommended parameters shall be verified by the client.
161
+ return server
162
+ ._get_endpoints(endpointUrl)
163
+ .filter((e) => !e.restricted) // remove restricted endpoints
164
+ .filter((e) => (0, node_opcua_utils_1.matchUri)(e.endpointUrl, endpointUrl))
165
+ .map(getRequiredEndpointInfo);
166
+ }
167
+ function adjustSecurityPolicy(channel, userTokenPolicy_securityPolicyUri) {
168
+ // check that userIdentityToken
169
+ let securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(userTokenPolicy_securityPolicyUri);
170
+ // if the security policy is not specified we use the session security policy
171
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.Invalid) {
172
+ securityPolicy = (0, node_opcua_secure_channel_1.fromURI)(channel.clientSecurityHeader.securityPolicyUri);
173
+ (0, node_opcua_assert_1.assert)(securityPolicy !== node_opcua_secure_channel_1.SecurityPolicy.Invalid);
174
+ }
175
+ return securityPolicy;
176
+ }
177
+ function findUserTokenByPolicy(endpoint_description, userTokenType, policyId) {
178
+ (0, node_opcua_assert_1.assert)(endpoint_description instanceof node_opcua_types_1.EndpointDescription);
179
+ const r = endpoint_description.userIdentityTokens.filter((userIdentity) => userIdentity.tokenType === userTokenType && (!policyId || userIdentity.policyId === policyId));
180
+ return r.length === 0 ? null : r[0];
181
+ }
182
+ function findUserTokenPolicy(endpoint_description, userTokenType) {
183
+ (0, node_opcua_assert_1.assert)(endpoint_description instanceof node_opcua_types_1.EndpointDescription);
184
+ const r = endpoint_description.userIdentityTokens.filter((userIdentity) => {
185
+ (0, node_opcua_assert_1.assert)(userIdentity.tokenType !== undefined);
186
+ return userIdentity.tokenType === userTokenType;
187
+ });
188
+ return r.length === 0 ? null : r[0];
189
+ }
190
+ function createAnonymousIdentityToken(endpoint_desc) {
191
+ (0, node_opcua_assert_1.assert)(endpoint_desc instanceof node_opcua_types_1.EndpointDescription);
192
+ const userTokenPolicy = findUserTokenPolicy(endpoint_desc, node_opcua_service_endpoints_1.UserTokenType.Anonymous);
193
+ if (!userTokenPolicy) {
194
+ throw new Error("Cannot find ANONYMOUS user token policy in end point description");
195
+ }
196
+ return new node_opcua_service_session_1.AnonymousIdentityToken({ policyId: userTokenPolicy.policyId });
197
+ }
198
+ function sameIdentityToken(token1, token2) {
199
+ if (token1 instanceof node_opcua_service_session_1.UserNameIdentityToken) {
200
+ if (!(token2 instanceof node_opcua_service_session_1.UserNameIdentityToken)) {
201
+ return false;
202
+ }
203
+ if (token1.userName !== token2.userName) {
204
+ return false;
205
+ }
206
+ if (token1.password.toString("hex") !== token2.password.toString("hex")) {
207
+ return false;
208
+ }
209
+ }
210
+ else if (token1 instanceof node_opcua_service_session_1.AnonymousIdentityToken) {
211
+ if (!(token2 instanceof node_opcua_service_session_1.AnonymousIdentityToken)) {
212
+ return false;
213
+ }
214
+ if (token1.policyId !== token2.policyId) {
215
+ return false;
216
+ }
217
+ return true;
218
+ }
219
+ (0, node_opcua_assert_1.assert)(false, " Not implemented yet");
220
+ return false;
221
+ }
222
+ function getTokenType(userIdentityToken) {
223
+ if (userIdentityToken instanceof node_opcua_service_session_1.AnonymousIdentityToken) {
224
+ return node_opcua_service_endpoints_1.UserTokenType.Anonymous;
225
+ }
226
+ else if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
227
+ return node_opcua_service_endpoints_1.UserTokenType.UserName;
228
+ }
229
+ else if (userIdentityToken instanceof node_opcua_types_1.IssuedIdentityToken) {
230
+ return node_opcua_service_endpoints_1.UserTokenType.IssuedToken;
231
+ }
232
+ else if (userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken) {
233
+ return node_opcua_service_endpoints_1.UserTokenType.Certificate;
234
+ }
235
+ return node_opcua_service_endpoints_1.UserTokenType.Invalid;
236
+ }
237
+ function thumbprint(certificate) {
238
+ return certificate ? certificate.toString("base64") : "";
239
+ }
240
+ /*=== private
241
+ *
242
+ * perform the read operation on a given node for a monitored item.
243
+ * this method DOES NOT apply to Variable Values attribute
244
+ *
245
+ * @param self
246
+ * @param oldValue
247
+ * @param node
248
+ * @param itemToMonitor
249
+ * @private
250
+ */
251
+ function monitoredItem_read_and_record_value(self, context, oldValue, node, itemToMonitor, callback) {
252
+ (0, node_opcua_assert_1.assert)(self instanceof monitored_item_1.MonitoredItem);
253
+ (0, node_opcua_assert_1.assert)(oldValue instanceof node_opcua_data_value_1.DataValue);
254
+ (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
255
+ const dataValue = node.readAttribute(context, itemToMonitor.attributeId, itemToMonitor.indexRange, itemToMonitor.dataEncoding);
256
+ callback(null, dataValue);
257
+ }
258
+ /*== private
259
+ * @method monitoredItem_read_and_record_value_async
260
+ * this method applies to Variable Values attribute
261
+ * @param self
262
+ * @param oldValue
263
+ * @param node
264
+ * @param itemToMonitor
265
+ * @private
266
+ */
267
+ function monitoredItem_read_and_record_value_async(self, context, oldValue, node, itemToMonitor, callback) {
268
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
269
+ (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
270
+ (0, node_opcua_assert_1.assert)(self instanceof monitored_item_1.MonitoredItem);
271
+ (0, node_opcua_assert_1.assert)(oldValue instanceof node_opcua_data_value_1.DataValue);
272
+ // do it asynchronously ( this is only valid for value attributes )
273
+ (0, node_opcua_assert_1.assert)(itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value);
274
+ node.readValueAsync(context, (err, dataValue) => {
275
+ callback(err, dataValue);
276
+ });
277
+ }
278
+ function build_scanning_node_function(context, addressSpace, monitoredItem, itemToMonitor) {
279
+ (0, node_opcua_assert_1.assert)(context instanceof node_opcua_address_space_1.SessionContext);
280
+ (0, node_opcua_assert_1.assert)(itemToMonitor instanceof node_opcua_service_read_1.ReadValueId);
281
+ const node = addressSpace.findNode(itemToMonitor.nodeId);
282
+ /* istanbul ignore next */
283
+ if (!node) {
284
+ errorLog(" INVALID NODE ID , ", itemToMonitor.nodeId.toString());
285
+ (0, node_opcua_debug_1.dump)(itemToMonitor);
286
+ return (oldData, callback) => {
287
+ callback(null, new node_opcua_data_value_1.DataValue({
288
+ statusCode: node_opcua_status_code_1.StatusCodes.BadNodeIdUnknown,
289
+ value: { dataType: node_opcua_variant_1.DataType.Null, value: 0 }
290
+ }));
291
+ };
292
+ }
293
+ ///// !!monitoredItem.setNode(node);
294
+ if (itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value) {
295
+ const monitoredItem_read_and_record_value_func = itemToMonitor.attributeId === node_opcua_data_model_1.AttributeIds.Value && typeof node.readValueAsync === "function"
296
+ ? monitoredItem_read_and_record_value_async
297
+ : monitoredItem_read_and_record_value;
298
+ return function func(oldDataValue, callback) {
299
+ (0, node_opcua_assert_1.assert)(this instanceof monitored_item_1.MonitoredItem);
300
+ (0, node_opcua_assert_1.assert)(oldDataValue instanceof node_opcua_data_value_1.DataValue);
301
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
302
+ monitoredItem_read_and_record_value_func(this, context, oldDataValue, node, itemToMonitor, callback);
303
+ };
304
+ }
305
+ else {
306
+ // Attributes, other than the Value Attribute, are only monitored for a change in value.
307
+ // The filter is not used for these Attributes. Any change in value for these Attributes
308
+ // causes a Notification to be generated.
309
+ // only record value when it has changed
310
+ return function func(oldDataValue, callback) {
311
+ (0, node_opcua_assert_1.assert)(this instanceof monitored_item_1.MonitoredItem);
312
+ (0, node_opcua_assert_1.assert)(oldDataValue instanceof node_opcua_data_value_1.DataValue);
313
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
314
+ const newDataValue = node.readAttribute(null, itemToMonitor.attributeId);
315
+ callback(null, newDataValue);
316
+ };
317
+ }
318
+ }
319
+ function prepareMonitoredItem(context, addressSpace, monitoredItem) {
320
+ const itemToMonitor = monitoredItem.itemToMonitor;
321
+ const readNodeFunc = build_scanning_node_function(context, addressSpace, monitoredItem, itemToMonitor);
322
+ monitoredItem.samplingFunc = readNodeFunc;
323
+ }
324
+ function isMonitoringModeValid(monitoringMode) {
325
+ (0, node_opcua_assert_1.assert)(node_opcua_types_1.MonitoringMode.Invalid !== undefined);
326
+ return monitoringMode !== node_opcua_types_1.MonitoringMode.Invalid && monitoringMode <= node_opcua_types_1.MonitoringMode.Reporting;
327
+ }
328
+ function _installRegisterServerManager(self) {
329
+ (0, node_opcua_assert_1.assert)(self instanceof OPCUAServer);
330
+ (0, node_opcua_assert_1.assert)(!self.registerServerManager);
331
+ /* istanbul ignore next */
332
+ if (!self.registerServerMethod) {
333
+ throw new Error("Internal Error");
334
+ }
335
+ switch (self.registerServerMethod) {
336
+ case RegisterServerMethod.HIDDEN:
337
+ self.registerServerManager = new register_server_manager_hidden_1.RegisterServerManagerHidden({
338
+ server: self
339
+ });
340
+ break;
341
+ case RegisterServerMethod.MDNS:
342
+ self.registerServerManager = new register_server_manager_mdns_only_1.RegisterServerManagerMDNSONLY({
343
+ server: self
344
+ });
345
+ break;
346
+ case RegisterServerMethod.LDS:
347
+ self.registerServerManager = new register_server_manager_1.RegisterServerManager({
348
+ discoveryServerEndpointUrl: self.discoveryServerEndpointUrl,
349
+ server: self
350
+ });
351
+ break;
352
+ /* istanbul ignore next */
353
+ default:
354
+ throw new Error("Invalid switch");
355
+ }
356
+ self.registerServerManager.on("serverRegistrationPending", () => {
357
+ /**
358
+ * emitted when the server is trying to registered the LDS
359
+ * but when the connection to the lds has failed
360
+ * serverRegistrationPending is sent when the backoff signal of the
361
+ * connection process is raised
362
+ * @event serverRegistrationPending
363
+ */
364
+ debugLog("serverRegistrationPending");
365
+ self.emit("serverRegistrationPending");
366
+ });
367
+ self.registerServerManager.on("serverRegistered", () => {
368
+ /**
369
+ * emitted when the server is successfully registered to the LDS
370
+ * @event serverRegistered
371
+ */
372
+ debugLog("serverRegistered");
373
+ self.emit("serverRegistered");
374
+ });
375
+ self.registerServerManager.on("serverRegistrationRenewed", () => {
376
+ /**
377
+ * emitted when the server has successfully renewed its registration to the LDS
378
+ * @event serverRegistrationRenewed
379
+ */
380
+ debugLog("serverRegistrationRenewed");
381
+ self.emit("serverRegistrationRenewed");
382
+ });
383
+ self.registerServerManager.on("serverUnregistered", () => {
384
+ debugLog("serverUnregistered");
385
+ /**
386
+ * emitted when the server is successfully unregistered to the LDS
387
+ * ( for instance during shutdown)
388
+ * @event serverUnregistered
389
+ */
390
+ self.emit("serverUnregistered");
391
+ });
392
+ }
393
+ function validate_applicationUri(channel, request) {
394
+ var _a, _b;
395
+ const applicationUri = request.clientDescription.applicationUri;
396
+ const clientCertificate = request.clientCertificate;
397
+ // if session is insecure there is no need to check certificate information
398
+ if (channel.securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
399
+ return true; // assume correct
400
+ }
401
+ if (!clientCertificate || clientCertificate.length === 0) {
402
+ return true; // can't check
403
+ }
404
+ const e = (0, node_opcua_crypto_1.exploreCertificate)(clientCertificate);
405
+ const uniformResourceIdentifier = (_b = (_a = e.tbsCertificate.extensions.subjectAltName) === null || _a === void 0 ? void 0 : _a.uniformResourceIdentifier) !== null && _b !== void 0 ? _b : null;
406
+ const applicationUriFromCert = uniformResourceIdentifier && uniformResourceIdentifier.length > 0 ? uniformResourceIdentifier[0] : null;
407
+ /* istanbul ignore next */
408
+ if (applicationUriFromCert !== applicationUri) {
409
+ errorLog("BadCertificateUriInvalid!");
410
+ errorLog("applicationUri = ", applicationUri);
411
+ errorLog("applicationUriFromCert = ", applicationUriFromCert);
412
+ }
413
+ return applicationUriFromCert === applicationUri;
414
+ }
415
+ function validate_security_endpoint(server, request, channel) {
416
+ debugLog("validate_security_endpoint = ", request.endpointUrl);
417
+ let endpoints = server._get_endpoints(request.endpointUrl);
418
+ // endpointUrl String The network address that the Client used to access the Session Endpoint.
419
+ // The HostName portion of the URL should be one of the HostNames for the application that are
420
+ // specified in the Server’s ApplicationInstanceCertificate (see 7.2). The Server shall raise an
421
+ // AuditUrlMismatchEventType event if the URL does not match the Server’s HostNames.
422
+ // AuditUrlMismatchEventType event type is defined in Part 5.
423
+ // The Server uses this information for diagnostics and to determine the set of
424
+ // EndpointDescriptions to return in the response.
425
+ // ToDo: check endpointUrl validity and emit an AuditUrlMismatchEventType event if not
426
+ if (endpoints.length === 0) {
427
+ // we have a UrlMismatch here
428
+ const ua_server = server.engine.addressSpace.rootFolder.objects.server;
429
+ ua_server.raiseEvent("AuditUrlMismatchEventType", {
430
+ endpointUrl: { dataType: node_opcua_variant_1.DataType.String, value: request.endpointUrl }
431
+ });
432
+ debugLog("Cannot find endpoint in available endpoints with endpointUri", request.endpointUrl);
433
+ if (OPCUAServer.requestExactEndpointUrl) {
434
+ return { errCode: node_opcua_status_code_1.StatusCodes.BadServiceUnsupported };
435
+ }
436
+ else {
437
+ endpoints = server._get_endpoints(null);
438
+ }
439
+ }
440
+ // ignore restricted endpoints
441
+ endpoints = endpoints.filter((e) => !e.restricted);
442
+ const endpoints_matching_security_mode = endpoints.filter((e) => {
443
+ return e.securityMode === channel.securityMode;
444
+ });
445
+ if (endpoints_matching_security_mode.length === 0) {
446
+ return { errCode: node_opcua_status_code_1.StatusCodes.BadSecurityModeRejected };
447
+ }
448
+ const endpoints_matching_security_policy = endpoints_matching_security_mode.filter((e) => {
449
+ return e.securityPolicyUri === channel.securityHeader.securityPolicyUri;
450
+ });
451
+ if (endpoints_matching_security_policy.length === 0) {
452
+ return { errCode: node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected };
453
+ }
454
+ if (endpoints_matching_security_policy.length !== 1) {
455
+ debugLog("endpoints_matching_security_policy= ", endpoints_matching_security_policy.length);
456
+ }
457
+ return { errCode: node_opcua_status_code_1.StatusCodes.Good, endpoint: endpoints_matching_security_policy[0] };
458
+ }
459
+ function filterDiagnosticInfo(returnDiagnostics, response) {
460
+ if (node_opcua_data_model_1.RESPONSE_DIAGNOSTICS_MASK_ALL & returnDiagnostics) {
461
+ response.responseHeader.serviceDiagnostics = (0, node_opcua_data_model_1.filterDiagnosticServiceLevel)(returnDiagnostics, response.responseHeader.serviceDiagnostics);
462
+ if (response.diagnosticInfos && response.diagnosticInfos.length > 0) {
463
+ response.diagnosticInfos = response.diagnosticInfos.map((d) => (0, node_opcua_data_model_1.filterDiagnosticOperationLevel)(returnDiagnostics, d));
464
+ }
465
+ else {
466
+ response.diagnosticInfos = [];
467
+ }
468
+ if (response.results) {
469
+ for (const entry of response.results) {
470
+ if (entry.inputArgumentDiagnosticInfos && entry.inputArgumentDiagnosticInfos.length > 0) {
471
+ entry.inputArgumentDiagnosticInfos = entry.inputArgumentDiagnosticInfos.map((d) => (0, node_opcua_data_model_1.filterDiagnosticOperationLevel)(returnDiagnostics, d));
472
+ }
473
+ else {
474
+ entry.inputArgumentDiagnosticInfos = [];
475
+ }
476
+ }
477
+ }
478
+ }
479
+ }
480
+ exports.filterDiagnosticInfo = filterDiagnosticInfo;
481
+ var RegisterServerMethod;
482
+ (function (RegisterServerMethod) {
483
+ RegisterServerMethod[RegisterServerMethod["HIDDEN"] = 1] = "HIDDEN";
484
+ RegisterServerMethod[RegisterServerMethod["MDNS"] = 2] = "MDNS";
485
+ RegisterServerMethod[RegisterServerMethod["LDS"] = 3] = "LDS"; // the server registers itself to the LDS or LDS-ME (Local Discovery Server)
486
+ })(RegisterServerMethod = exports.RegisterServerMethod || (exports.RegisterServerMethod = {}));
487
+ const g_requestExactEndpointUrl = !!process.env.NODEOPCUA_SERVER_REQUEST_EXACT_ENDPOINT_URL;
488
+ /**
489
+ *
490
+ */
491
+ class OPCUAServer extends base_server_1.OPCUABaseServer {
492
+ constructor(options) {
493
+ super(options);
494
+ /**
495
+ * false if anonymous connection are not allowed
496
+ */
497
+ this.allowAnonymous = false;
498
+ this.allowAnonymous = false;
499
+ options = options || {};
500
+ this.options = options;
501
+ /**
502
+ * @property maxAllowedSessionNumber
503
+ */
504
+ this.maxAllowedSessionNumber = options.maxAllowedSessionNumber || default_maxAllowedSessionNumber;
505
+ /**
506
+ * @property maxConnectionsPerEndpoint
507
+ */
508
+ this.maxConnectionsPerEndpoint = options.maxConnectionsPerEndpoint || default_maxConnectionsPerEndpoint;
509
+ // build Info
510
+ const buildInfo = Object.assign(Object.assign({}, default_build_info), options.buildInfo);
511
+ // repair product name
512
+ buildInfo.productUri = buildInfo.productUri || this.serverInfo.productUri;
513
+ this.serverInfo.productUri = this.serverInfo.productUri || buildInfo.productUri;
514
+ this.userManager = (0, user_manager_1.makeUserManager)(options.userManager);
515
+ options.allowAnonymous = options.allowAnonymous === undefined ? true : !!options.allowAnonymous;
516
+ /**
517
+ * @property allowAnonymous
518
+ */
519
+ this.allowAnonymous = options.allowAnonymous;
520
+ this.discoveryServerEndpointUrl = options.discoveryServerEndpointUrl || "opc.tcp://%FQDN%:4840";
521
+ (0, node_opcua_assert_1.assert)(typeof this.discoveryServerEndpointUrl === "string");
522
+ this.serverInfo.applicationType = node_opcua_service_endpoints_1.ApplicationType.Server;
523
+ this.capabilitiesForMDNS = options.capabilitiesForMDNS || ["NA"];
524
+ this.registerServerMethod = options.registerServerMethod || RegisterServerMethod.HIDDEN;
525
+ _installRegisterServerManager(this);
526
+ if (!options.userCertificateManager) {
527
+ this.userCertificateManager = (0, node_opcua_certificate_manager_1.getDefaultCertificateManager)("UserPKI");
528
+ }
529
+ else {
530
+ this.userCertificateManager = options.userCertificateManager;
531
+ }
532
+ // note: we need to delay initialization of endpoint as certain resources
533
+ // such as %FQDN% might not be ready yet at this stage
534
+ this._delayInit = () => __awaiter(this, void 0, void 0, function* () {
535
+ /* istanbul ignore next */
536
+ if (!options) {
537
+ throw new Error("Internal Error");
538
+ }
539
+ // to check => this.serverInfo.applicationName = this.serverInfo.productName || buildInfo.productName;
540
+ // note: applicationUri is handled in a special way
541
+ this.engine = new server_engine_1.ServerEngine({
542
+ applicationUri: () => this.serverInfo.applicationUri,
543
+ buildInfo,
544
+ isAuditing: options.isAuditing,
545
+ serverCapabilities: options.serverCapabilities
546
+ });
547
+ this.objectFactory = new factory_1.Factory(this.engine);
548
+ const endpointDefinitions = options.alternateEndpoints || [];
549
+ const hostname = (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
550
+ endpointDefinitions.push({
551
+ port: options.port || 26543,
552
+ allowAnonymous: options.allowAnonymous,
553
+ alternateHostname: options.alternateHostname,
554
+ disableDiscovery: options.disableDiscovery,
555
+ hostname: options.hostname || hostname,
556
+ securityModes: options.securityModes,
557
+ securityPolicies: options.securityPolicies
558
+ });
559
+ // todo should self.serverInfo.productUri match self.engine.buildInfo.productUri ?
560
+ for (const endpointOptions of endpointDefinitions) {
561
+ const endPoint = this.createEndpointDescriptions(options, endpointOptions);
562
+ this.endpoints.push(endPoint);
563
+ endPoint.on("message", (message, channel) => {
564
+ this.on_request(message, channel);
565
+ });
566
+ endPoint.on("error", (err) => {
567
+ errorLog("OPCUAServer endpoint error", err);
568
+ // set serverState to ServerState.Failed;
569
+ this.engine.setServerState(node_opcua_common_1.ServerState.Failed);
570
+ this.shutdown(() => {
571
+ /* empty */
572
+ });
573
+ });
574
+ }
575
+ });
576
+ }
577
+ /**
578
+ * total number of bytes written by the server since startup
579
+ */
580
+ get bytesWritten() {
581
+ return this.endpoints.reduce((accumulated, endpoint) => {
582
+ return accumulated + endpoint.bytesWritten;
583
+ }, 0);
584
+ }
585
+ /**
586
+ * total number of bytes read by the server since startup
587
+ */
588
+ get bytesRead() {
589
+ return this.endpoints.reduce((accumulated, endpoint) => {
590
+ return accumulated + endpoint.bytesRead;
591
+ }, 0);
592
+ }
593
+ /**
594
+ * Number of transactions processed by the server since startup
595
+ */
596
+ get transactionsCount() {
597
+ return this.endpoints.reduce((accumulated, endpoint) => {
598
+ return accumulated + endpoint.transactionsCount;
599
+ }, 0);
600
+ }
601
+ /**
602
+ * The server build info
603
+ */
604
+ get buildInfo() {
605
+ return this.engine.buildInfo;
606
+ }
607
+ /**
608
+ * the number of connected channel on all existing end points
609
+ */
610
+ get currentChannelCount() {
611
+ // TODO : move to base
612
+ return this.endpoints.reduce((currentValue, endPoint) => {
613
+ return currentValue + endPoint.currentChannelCount;
614
+ }, 0);
615
+ }
616
+ /**
617
+ * The number of active subscriptions from all sessions
618
+ */
619
+ get currentSubscriptionCount() {
620
+ return this.engine ? this.engine.currentSubscriptionCount : 0;
621
+ }
622
+ /**
623
+ * the number of session activation requests that have been rejected
624
+ */
625
+ get rejectedSessionCount() {
626
+ return this.engine ? this.engine.rejectedSessionCount : 0;
627
+ }
628
+ /**
629
+ * the number of request that have been rejected
630
+ */
631
+ get rejectedRequestsCount() {
632
+ return this.engine ? this.engine.rejectedRequestsCount : 0;
633
+ }
634
+ /**
635
+ * the number of sessions that have been aborted
636
+ */
637
+ get sessionAbortCount() {
638
+ return this.engine ? this.engine.sessionAbortCount : 0;
639
+ }
640
+ /**
641
+ * the publishing interval count
642
+ */
643
+ get publishingIntervalCount() {
644
+ return this.engine ? this.engine.publishingIntervalCount : 0;
645
+ }
646
+ /**
647
+ * the number of sessions currently active
648
+ */
649
+ get currentSessionCount() {
650
+ return this.engine ? this.engine.currentSessionCount : 0;
651
+ }
652
+ /**
653
+ * true if the server has been initialized
654
+ *
655
+ */
656
+ get initialized() {
657
+ return this.engine && this.engine.addressSpace !== null;
658
+ }
659
+ /**
660
+ * is the server auditing ?
661
+ */
662
+ get isAuditing() {
663
+ return this.engine ? this.engine.isAuditing : false;
664
+ }
665
+ initialize(...args) {
666
+ const done = args[0];
667
+ (0, node_opcua_assert_1.assert)(!this.initialized, "server is already initialized"); // already initialized ?
668
+ this._preInitTask.push(() => __awaiter(this, void 0, void 0, function* () {
669
+ /* istanbul ignore else */
670
+ if (this._delayInit) {
671
+ yield this._delayInit();
672
+ this._delayInit = undefined;
673
+ }
674
+ }));
675
+ this.performPreInitialization()
676
+ .then(() => {
677
+ OPCUAServer.registry.register(this);
678
+ this.engine.initialize(this.options, () => {
679
+ (0, user_manager_ua_1.bindRoleSet)(this.userManager, this.engine.addressSpace);
680
+ setImmediate(() => {
681
+ this.emit("post_initialize");
682
+ done();
683
+ });
684
+ });
685
+ })
686
+ .catch((err) => {
687
+ done(err);
688
+ });
689
+ }
690
+ start(...args) {
691
+ const done = args[0];
692
+ const tasks = [];
693
+ tasks.push((0, util_1.callbackify)(node_opcua_hostname_1.extractFullyQualifiedDomainName));
694
+ if (!this.initialized) {
695
+ tasks.push((callback) => {
696
+ this.initialize(callback);
697
+ });
698
+ }
699
+ tasks.push((callback) => {
700
+ super.start((err) => {
701
+ if (err) {
702
+ this.shutdown((/*err2*/ err2) => {
703
+ callback(err);
704
+ });
705
+ }
706
+ else {
707
+ // we start the registration process asynchronously
708
+ // as we want to make server immediately available
709
+ this.registerServerManager.start(() => {
710
+ /* empty */
711
+ });
712
+ setImmediate(callback);
713
+ }
714
+ });
715
+ });
716
+ async.series(tasks, done);
717
+ }
718
+ shutdown(...args) {
719
+ const timeout = args.length === 1 ? OPCUAServer.defaultShutdownTimeout : args[0];
720
+ const callback = (args.length === 1 ? args[0] : args[1]);
721
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
722
+ debugLog("OPCUAServer#shutdown (timeout = ", timeout, ")");
723
+ /* istanbul ignore next */
724
+ if (!this.engine) {
725
+ return callback();
726
+ }
727
+ (0, node_opcua_assert_1.assert)(this.engine);
728
+ if (!this.engine.isStarted()) {
729
+ // server may have been shot down already , or may have fail to start !!
730
+ const err = new Error("OPCUAServer#shutdown failure ! server doesn't seems to be started yet");
731
+ return callback(err);
732
+ }
733
+ this.userCertificateManager.dispose();
734
+ this.engine.setServerState(node_opcua_common_1.ServerState.Shutdown);
735
+ const shutdownTime = new Date(Date.now() + timeout);
736
+ this.engine.setShutdownTime(shutdownTime);
737
+ debugLog("OPCUAServer is now unregistering itself from the discovery server " + this.buildInfo);
738
+ this.registerServerManager.stop((err) => {
739
+ debugLog("OPCUAServer unregistered from discovery server", err);
740
+ setTimeout(() => __awaiter(this, void 0, void 0, function* () {
741
+ yield this.engine.shutdown();
742
+ debugLog("OPCUAServer#shutdown: started");
743
+ base_server_1.OPCUABaseServer.prototype.shutdown.call(this, (err1) => {
744
+ debugLog("OPCUAServer#shutdown: completed");
745
+ this.dispose();
746
+ callback(err1);
747
+ });
748
+ }), timeout);
749
+ });
750
+ }
751
+ dispose() {
752
+ for (const endpoint of this.endpoints) {
753
+ endpoint.dispose();
754
+ }
755
+ this.endpoints = [];
756
+ this.removeAllListeners();
757
+ if (this.registerServerManager) {
758
+ this.registerServerManager.dispose();
759
+ this.registerServerManager = undefined;
760
+ }
761
+ OPCUAServer.registry.unregister(this);
762
+ /* istanbul ignore next */
763
+ if (this.engine) {
764
+ this.engine.dispose();
765
+ }
766
+ }
767
+ raiseEvent(eventType, options) {
768
+ /* istanbul ignore next */
769
+ if (!this.engine.addressSpace) {
770
+ errorLog("addressSpace missing");
771
+ return;
772
+ }
773
+ const server = this.engine.addressSpace.findNode("Server");
774
+ /* istanbul ignore next */
775
+ if (!server) {
776
+ // xx throw new Error("OPCUAServer#raiseEvent : cannot find Server object");
777
+ return;
778
+ }
779
+ let eventTypeNode = eventType;
780
+ if (typeof eventType === "string") {
781
+ eventTypeNode = this.engine.addressSpace.findEventType(eventType);
782
+ if (eventTypeNode) {
783
+ return server.raiseEvent(eventTypeNode, options);
784
+ }
785
+ else {
786
+ console.warn(" cannot find event type ", eventType);
787
+ }
788
+ }
789
+ else {
790
+ return server.raiseEvent(eventTypeNode, options);
791
+ }
792
+ }
793
+ /**
794
+ * create and register a new session
795
+ * @internal
796
+ */
797
+ createSession(options) {
798
+ /* istanbul ignore next */
799
+ if (!this.engine) {
800
+ throw new Error("Internal Error");
801
+ }
802
+ return this.engine.createSession(options);
803
+ }
804
+ /**
805
+ * retrieve a session by authentication token
806
+ * @internal
807
+ */
808
+ getSession(authenticationToken, activeOnly) {
809
+ return this.engine ? this.engine.getSession(authenticationToken, activeOnly) : null;
810
+ }
811
+ /**
812
+ *
813
+ * @param channel
814
+ * @param clientCertificate
815
+ * @param clientNonce
816
+ * @internal
817
+ */
818
+ computeServerSignature(channel, clientCertificate, clientNonce) {
819
+ return (0, node_opcua_secure_channel_1.computeSignature)(clientCertificate, clientNonce, this.getPrivateKey(), channel.messageBuilder.securityPolicy);
820
+ }
821
+ /**
822
+ *
823
+ * @param session
824
+ * @param channel
825
+ * @param clientSignature
826
+ * @internal
827
+ */
828
+ verifyClientSignature(session, channel, clientSignature) {
829
+ const clientCertificate = channel.receiverCertificate;
830
+ const securityPolicy = channel.messageBuilder.securityPolicy;
831
+ const serverCertificate = this.getCertificate();
832
+ const result = (0, node_opcua_secure_channel_1.verifySignature)(serverCertificate, session.nonce, clientSignature, clientCertificate, securityPolicy);
833
+ return result;
834
+ }
835
+ isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback) {
836
+ (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken);
837
+ const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
838
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
839
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
840
+ }
841
+ const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
842
+ /* istanbul ignore next */
843
+ if (!cryptoFactory) {
844
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
845
+ }
846
+ /* istanbul ignore next */
847
+ if (userIdentityToken.encryptionAlgorithm !== cryptoFactory.asymmetricEncryptionAlgorithm) {
848
+ errorLog("invalid encryptionAlgorithm");
849
+ errorLog("userTokenPolicy", userTokenPolicy.toString());
850
+ errorLog("userTokenPolicy", userIdentityToken.toString());
851
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
852
+ }
853
+ const userName = userIdentityToken.userName;
854
+ const password = userIdentityToken.password;
855
+ if (!userName || !password) {
856
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
857
+ }
858
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
859
+ }
860
+ isValidX509IdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback) {
861
+ (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken);
862
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
863
+ const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
864
+ const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
865
+ /* istanbul ignore next */
866
+ if (!cryptoFactory) {
867
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
868
+ }
869
+ if (!userTokenSignature || !userTokenSignature.signature) {
870
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadUserSignatureInvalid);
871
+ }
872
+ if (userIdentityToken.policyId !== userTokenPolicy.policyId) {
873
+ errorLog("invalid encryptionAlgorithm");
874
+ errorLog("userTokenPolicy", userTokenPolicy.toString());
875
+ errorLog("userTokenPolicy", userIdentityToken.toString());
876
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadSecurityPolicyRejected);
877
+ }
878
+ const certificate = userIdentityToken.certificateData; /* as Certificate*/
879
+ const nonce = session.nonce;
880
+ const serverCertificate = this.getCertificate();
881
+ (0, node_opcua_assert_1.assert)(serverCertificate instanceof Buffer);
882
+ (0, node_opcua_assert_1.assert)(certificate instanceof Buffer, "expecting certificate to be a Buffer");
883
+ (0, node_opcua_assert_1.assert)(nonce instanceof Buffer, "expecting nonce to be a Buffer");
884
+ (0, node_opcua_assert_1.assert)(userTokenSignature.signature instanceof Buffer, "expecting userTokenSignature to be a Buffer");
885
+ // verify proof of possession by checking certificate signature & server nonce correctness
886
+ if (!(0, node_opcua_secure_channel_1.verifySignature)(serverCertificate, nonce, userTokenSignature, certificate, securityPolicy)) {
887
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadUserSignatureInvalid);
888
+ }
889
+ // verify if certificate is Valid
890
+ this.userCertificateManager.checkCertificate(certificate, (err, certificateStatus) => {
891
+ /* istanbul ignore next */
892
+ if (err) {
893
+ return callback(err);
894
+ }
895
+ if (node_opcua_status_code_1.StatusCodes.BadCertificateUntrusted === certificateStatus ||
896
+ node_opcua_status_code_1.StatusCodes.BadCertificateTimeInvalid === certificateStatus ||
897
+ node_opcua_status_code_1.StatusCodes.BadCertificateIssuerTimeInvalid === certificateStatus ||
898
+ node_opcua_status_code_1.StatusCodes.BadCertificateIssuerUseNotAllowed === certificateStatus ||
899
+ node_opcua_status_code_1.StatusCodes.BadCertificateIssuerRevocationUnknown === certificateStatus ||
900
+ node_opcua_status_code_1.StatusCodes.BadCertificateRevocationUnknown === certificateStatus ||
901
+ node_opcua_status_code_1.StatusCodes.BadCertificateRevoked === certificateStatus ||
902
+ node_opcua_status_code_1.StatusCodes.BadCertificateUseNotAllowed === certificateStatus ||
903
+ node_opcua_status_code_1.StatusCodes.BadSecurityChecksFailed === certificateStatus ||
904
+ node_opcua_status_code_1.StatusCodes.Good !== certificateStatus) {
905
+ debugLog("isValidX509IdentityToken => certificateStatus = ", certificateStatus === null || certificateStatus === void 0 ? void 0 : certificateStatus.toString());
906
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenRejected);
907
+ }
908
+ if (node_opcua_status_code_1.StatusCodes.Good !== certificateStatus) {
909
+ (0, node_opcua_assert_1.assert)(certificateStatus instanceof node_opcua_status_code_1.StatusCode);
910
+ return callback(null, certificateStatus);
911
+ // return callback(null, StatusCodes.BadIdentityTokenInvalid);
912
+ }
913
+ // verify if certificate is truster or rejected
914
+ // todo: StatusCodes.BadCertificateUntrusted
915
+ // store untrusted certificate to rejected folder
916
+ // todo:
917
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
918
+ });
919
+ }
920
+ /**
921
+ * @internal
922
+ */
923
+ userNameIdentityTokenAuthenticateUser(channel, session, userTokenPolicy, userIdentityToken, callback) {
924
+ (0, node_opcua_assert_1.assert)(userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken);
925
+ // assert(this.isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken));
926
+ const securityPolicy = adjustSecurityPolicy(channel, userTokenPolicy.securityPolicyUri);
927
+ const userName = userIdentityToken.userName;
928
+ let password = userIdentityToken.password;
929
+ // decrypt password if necessary
930
+ if (securityPolicy === node_opcua_secure_channel_1.SecurityPolicy.None) {
931
+ // not good, password was sent in clear text ...
932
+ password = password.toString();
933
+ }
934
+ else {
935
+ const serverPrivateKey = this.getPrivateKey();
936
+ const serverNonce = session.nonce;
937
+ (0, node_opcua_assert_1.assert)(serverNonce instanceof Buffer);
938
+ const cryptoFactory = (0, node_opcua_secure_channel_1.getCryptoFactory)(securityPolicy);
939
+ /* istanbul ignore next */
940
+ if (!cryptoFactory) {
941
+ return callback(new Error(" Unsupported security Policy"));
942
+ }
943
+ const buff = cryptoFactory.asymmetricDecrypt(password, serverPrivateKey);
944
+ // server certificate may be invalid and asymmetricDecrypt may fail
945
+ if (!buff || buff.length < 4) {
946
+ async.setImmediate(() => callback(null, false));
947
+ return;
948
+ }
949
+ const length = buff.readUInt32LE(0) - serverNonce.length;
950
+ password = buff.slice(4, 4 + length).toString("utf-8");
951
+ }
952
+ this.userManager
953
+ .isValidUser(session, userName, password)
954
+ .then((isValid) => callback(null, isValid))
955
+ .catch((err) => callback(err));
956
+ }
957
+ /**
958
+ * @internal
959
+ */
960
+ isValidUserIdentityToken(channel, session, userIdentityToken, userTokenSignature, endpointDescription, callback) {
961
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
962
+ /* istanbul ignore next */
963
+ if (!userIdentityToken) {
964
+ throw new Error("Invalid token");
965
+ }
966
+ const userTokenType = getTokenType(userIdentityToken);
967
+ const userTokenPolicy = findUserTokenByPolicy(endpointDescription, userTokenType, userIdentityToken.policyId);
968
+ if (!userTokenPolicy) {
969
+ // cannot find token with this policyId
970
+ return callback(null, node_opcua_status_code_1.StatusCodes.BadIdentityTokenInvalid);
971
+ }
972
+ //
973
+ if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
974
+ return this.isValidUserNameIdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback);
975
+ }
976
+ if (userIdentityToken instanceof node_opcua_service_session_1.X509IdentityToken) {
977
+ return this.isValidX509IdentityToken(channel, session, userTokenPolicy, userIdentityToken, userTokenSignature, callback);
978
+ }
979
+ return callback(null, node_opcua_status_code_1.StatusCodes.Good);
980
+ }
981
+ /**
982
+ *
983
+ * @internal
984
+ * @param channel
985
+ * @param session
986
+ * @param userIdentityToken
987
+ * @param callback
988
+ * @returns {*}
989
+ */
990
+ isUserAuthorized(channel, session, userIdentityToken, callback) {
991
+ (0, node_opcua_assert_1.assert)(userIdentityToken);
992
+ (0, node_opcua_assert_1.assert)(typeof callback === "function");
993
+ const userTokenType = getTokenType(userIdentityToken);
994
+ const userTokenPolicy = findUserTokenByPolicy(session.getEndpointDescription(), userTokenType, userIdentityToken.policyId);
995
+ /** istanbul ignore next */
996
+ if (!userTokenPolicy) {
997
+ return callback(null, false);
998
+ }
999
+ // find if a userToken exists
1000
+ if (userIdentityToken instanceof node_opcua_service_session_1.UserNameIdentityToken) {
1001
+ return this.userNameIdentityTokenAuthenticateUser(channel, session, userTokenPolicy, userIdentityToken, callback);
1002
+ }
1003
+ async.setImmediate(callback.bind(null, null, true));
1004
+ }
1005
+ makeServerNonce() {
1006
+ return crypto.randomBytes(32);
1007
+ }
1008
+ // session services
1009
+ // eslint-disable-next-line max-statements
1010
+ _on_CreateSessionRequest(message, channel) {
1011
+ return __awaiter(this, void 0, void 0, function* () {
1012
+ const request = message.request;
1013
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.CreateSessionRequest);
1014
+ function rejectConnection(server, statusCode) {
1015
+ server.engine.incrementSecurityRejectedSessionCount();
1016
+ const response1 = new node_opcua_service_session_1.CreateSessionResponse({
1017
+ responseHeader: { serviceResult: statusCode }
1018
+ });
1019
+ channel.send_response("MSG", response1, message);
1020
+ // and close !
1021
+ }
1022
+ // From OPCUA V1.03 Part 4 5.6.2 CreateSession
1023
+ // A Server application should limit the number of Sessions. To protect against misbehaving Clients and denial
1024
+ // of service attacks, the Server shall close the oldest Session that is not activated before reaching the
1025
+ // maximum number of supported Sessions
1026
+ if (this.currentSessionCount >= this.maxAllowedSessionNumber) {
1027
+ yield _attempt_to_close_some_old_unactivated_session(this);
1028
+ }
1029
+ // check if session count hasn't reach the maximum allowed sessions
1030
+ if (this.currentSessionCount >= this.maxAllowedSessionNumber) {
1031
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadTooManySessions);
1032
+ }
1033
+ // Release 1.03 OPC Unified Architecture, Part 4 page 24 - CreateSession Parameters
1034
+ // client should prove a sessionName
1035
+ // Session name is a Human readable string that identifies the Session. The Server makes this name and the
1036
+ // sessionId visible in its AddressSpace for diagnostic purposes. The Client should provide a name that is
1037
+ // unique for the instance of the Client.
1038
+ // If this parameter is not specified the Server shall assign a value.
1039
+ if (utils.isNullOrUndefined(request.sessionName)) {
1040
+ // see also #198
1041
+ // let's the server assign a sessionName for this lazy client.
1042
+ debugLog("assigning OPCUAServer.fallbackSessionName because client's sessionName is null ", OPCUAServer.fallbackSessionName);
1043
+ request.sessionName = OPCUAServer.fallbackSessionName;
1044
+ }
1045
+ // Duration Requested maximum number of milliseconds that a Session should remain open without activity.
1046
+ // If the Client fails to issue a Service request within this interval, then the Server shall automatically
1047
+ // terminate the Client Session.
1048
+ const revisedSessionTimeout = _adjust_session_timeout(request.requestedSessionTimeout);
1049
+ // Release 1.02 page 27 OPC Unified Architecture, Part 4: CreateSession.clientNonce
1050
+ // A random number that should never be used in any other request. This number shall have a minimum length of 32
1051
+ // bytes. Profiles may increase the required length. The Server shall use this value to prove possession of
1052
+ // its application instance Certificate in the response.
1053
+ if (!request.clientNonce || request.clientNonce.length < 32) {
1054
+ if (channel.securityMode !== node_opcua_secure_channel_1.MessageSecurityMode.None) {
1055
+ errorLog(chalk.red("SERVER with secure connection: Missing or invalid client Nonce "), request.clientNonce && request.clientNonce.toString("hex"));
1056
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadNonceInvalid);
1057
+ }
1058
+ }
1059
+ if ((0, node_opcua_secure_channel_1.nonceAlreadyBeenUsed)(request.clientNonce)) {
1060
+ errorLog(chalk.red("SERVER with secure connection: None has already been used"), request.clientNonce && request.clientNonce.toString("hex"));
1061
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadNonceInvalid);
1062
+ }
1063
+ // check application spoofing
1064
+ // check if applicationUri in createSessionRequest matches applicationUri in client Certificate
1065
+ if (!validate_applicationUri(channel, request)) {
1066
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadCertificateUriInvalid);
1067
+ }
1068
+ const { errCode, endpoint } = validate_security_endpoint(this, request, channel);
1069
+ if (errCode !== node_opcua_status_code_1.StatusCodes.Good) {
1070
+ return rejectConnection(this, errCode);
1071
+ }
1072
+ // see Release 1.02 27 OPC Unified Architecture, Part 4
1073
+ const session = this.createSession({
1074
+ clientDescription: request.clientDescription,
1075
+ sessionTimeout: revisedSessionTimeout
1076
+ });
1077
+ session.endpoint = endpoint;
1078
+ (0, node_opcua_assert_1.assert)(session);
1079
+ (0, node_opcua_assert_1.assert)(session.sessionTimeout === revisedSessionTimeout);
1080
+ session.clientDescription = request.clientDescription;
1081
+ session.sessionName = request.sessionName || "<unknown session name>";
1082
+ // Depending upon on the SecurityPolicy and the SecurityMode of the SecureChannel, the exchange of
1083
+ // ApplicationInstanceCertificates and Nonces may be optional and the signatures may be empty. See
1084
+ // Part 7 for the definition of SecurityPolicies and the handling of these parameters
1085
+ // serverNonce:
1086
+ // A random number that should never be used in any other request.
1087
+ // This number shall have a minimum length of 32 bytes.
1088
+ // The Client shall use this value to prove possession of its application instance
1089
+ // Certificate in the ActivateSession request.
1090
+ // This value may also be used to prove possession of the userIdentityToken it
1091
+ // specified in the ActivateSession request.
1092
+ //
1093
+ // ( this serverNonce will only be used up to the _on_ActivateSessionRequest
1094
+ // where a new nonce will be created)
1095
+ session.nonce = this.makeServerNonce();
1096
+ session.channelId = channel.channelId;
1097
+ session._attach_channel(channel);
1098
+ const serverCertificateChain = this.getCertificateChain();
1099
+ const hasEncryption = true;
1100
+ // If the securityPolicyUri is None and none of the UserTokenPolicies requires encryption
1101
+ if (session.channel.securityMode === node_opcua_secure_channel_1.MessageSecurityMode.None) {
1102
+ // ToDo: Check that none of our insecure endpoint has a a UserTokenPolicy that require encryption
1103
+ // and set hasEncryption = false under this condition
1104
+ }
1105
+ const response = new node_opcua_service_session_1.CreateSessionResponse({
1106
+ // A identifier which uniquely identifies the session.
1107
+ sessionId: session.nodeId,
1108
+ // A unique identifier assigned by the Server to the Session.
1109
+ // The token used to authenticate the client in subsequent requests.
1110
+ authenticationToken: session.authenticationToken,
1111
+ revisedSessionTimeout,
1112
+ serverNonce: session.nonce,
1113
+ // serverCertificate: type ApplicationServerCertificate
1114
+ // The application instance Certificate issued to the Server.
1115
+ // A Server shall prove possession by using the private key to sign the Nonce provided
1116
+ // by the Client in the request. The Client shall verify that this Certificate is the same as
1117
+ // the one it used to create the SecureChannel.
1118
+ // The ApplicationInstanceCertificate type is defined in OpCUA 1.03 part 4 - $7.2 page 108
1119
+ // If the securityPolicyUri is None and none of the UserTokenPolicies requires
1120
+ // encryption, the Server shall not send an ApplicationInstanceCertificate and the Client
1121
+ // shall ignore the ApplicationInstanceCertificate.
1122
+ serverCertificate: hasEncryption ? serverCertificateChain : undefined,
1123
+ // The endpoints provided by the server.
1124
+ // The Server shall return a set of EndpointDescriptions available for the serverUri
1125
+ // specified in the request.[...]
1126
+ // The Client shall verify this list with the list from a Discovery Endpoint if it used a Discovery
1127
+ // Endpoint to fetch the EndpointDescriptions.
1128
+ // It is recommended that Servers only include the endpointUrl, securityMode,
1129
+ // securityPolicyUri, userIdentityTokens, transportProfileUri and securityLevel with all
1130
+ // other parameters set to null. Only the recommended parameters shall be verified by
1131
+ // the client.
1132
+ serverEndpoints: _serverEndpointsForCreateSessionResponse(this, session.endpoint.endpointUrl, request.serverUri),
1133
+ // This parameter is deprecated and the array shall be empty.
1134
+ serverSoftwareCertificates: null,
1135
+ // This is a signature generated with the private key associated with the
1136
+ // serverCertificate. This parameter is calculated by appending the clientNonce to the
1137
+ // clientCertificate and signing the resulting sequence of bytes.
1138
+ // The SignatureAlgorithm shall be the AsymmetricSignatureAlgorithm specified in the
1139
+ // SecurityPolicy for the Endpoint.
1140
+ // The SignatureData type is defined in 7.30.
1141
+ serverSignature: this.computeServerSignature(channel, request.clientCertificate, request.clientNonce),
1142
+ // The maximum message size accepted by the server
1143
+ // The Client Communication Stack should return a Bad_RequestTooLarge error to the
1144
+ // application if a request message exceeds this limit.
1145
+ // The value zero indicates that this parameter is not used.
1146
+ maxRequestMessageSize: 0x4000000
1147
+ });
1148
+ this.emit("create_session", session);
1149
+ session.on("session_closed", (session1, deleteSubscriptions, reason) => {
1150
+ (0, node_opcua_assert_1.assert)(typeof reason === "string");
1151
+ if (this.isAuditing) {
1152
+ (0, node_opcua_assert_1.assert)(reason === "Timeout" || reason === "Terminated" || reason === "CloseSession" || reason === "Forcing");
1153
+ const sourceName = "Session/" + reason;
1154
+ this.raiseEvent("AuditSessionEventType", {
1155
+ /* part 5 - 6.4.3 AuditEventType */
1156
+ actionTimeStamp: { dataType: "DateTime", value: new Date() },
1157
+ status: { dataType: "Boolean", value: true },
1158
+ serverId: { dataType: "String", value: "" },
1159
+ // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1160
+ clientAuditEntryId: { dataType: "String", value: "" },
1161
+ // The ClientUserId identifies the user of the client requesting an action. The ClientUserId can be
1162
+ // obtained from the UserIdentityToken passed in the ActivateSession call.
1163
+ clientUserId: { dataType: "String", value: "" },
1164
+ sourceName: { dataType: "String", value: sourceName },
1165
+ /* part 5 - 6.4.7 AuditSessionEventType */
1166
+ sessionId: { dataType: "NodeId", value: session1.nodeId }
1167
+ });
1168
+ }
1169
+ this.emit("session_closed", session1, deleteSubscriptions);
1170
+ });
1171
+ if (this.isAuditing) {
1172
+ // ------------------------------------------------------------------------------------------------------
1173
+ this.raiseEvent("AuditCreateSessionEventType", {
1174
+ /* part 5 - 6.4.3 AuditEventType */
1175
+ actionTimeStamp: { dataType: "DateTime", value: new Date() },
1176
+ status: { dataType: "Boolean", value: true },
1177
+ serverId: { dataType: "String", value: "" },
1178
+ // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1179
+ clientAuditEntryId: { dataType: "String", value: "" },
1180
+ // The ClientUserId identifies the user of the client requesting an action. The ClientUserId can be
1181
+ // obtained from the UserIdentityToken passed in the ActivateSession call.
1182
+ clientUserId: { dataType: "String", value: "" },
1183
+ sourceName: { dataType: "String", value: "Session/CreateSession" },
1184
+ /* part 5 - 6.4.7 AuditSessionEventType */
1185
+ sessionId: { dataType: "NodeId", value: session.nodeId },
1186
+ /* part 5 - 6.4.8 AuditCreateSessionEventType */
1187
+ // SecureChannelId shall uniquely identify the SecureChannel. The application shall use the same
1188
+ // identifier in all AuditEvents related to the Session Service Set (AuditCreateSessionEventType,
1189
+ // AuditActivateSessionEventType and their subtypes) and the SecureChannel Service Set
1190
+ // (AuditChannelEventType and its subtypes
1191
+ secureChannelId: { dataType: "String", value: session.channel.channelId.toString() },
1192
+ // Duration
1193
+ revisedSessionTimeout: { dataType: "Duration", value: session.sessionTimeout },
1194
+ // clientCertificate
1195
+ clientCertificate: { dataType: "ByteString", value: session.channel.clientCertificate },
1196
+ // clientCertificateThumbprint
1197
+ clientCertificateThumbprint: {
1198
+ dataType: "String",
1199
+ value: thumbprint(session.channel.clientCertificate)
1200
+ }
1201
+ });
1202
+ }
1203
+ // -----------------------------------------------------------------------------------------------------------
1204
+ (0, node_opcua_assert_1.assert)(response.authenticationToken);
1205
+ channel.send_response("MSG", response, message);
1206
+ });
1207
+ }
1208
+ // TODO : implement this:
1209
+ //
1210
+ // When the ActivateSession Service is called for the first time then the Server shall reject the request
1211
+ // if the SecureChannel is not same as the one associated with the CreateSession request.
1212
+ // Subsequent calls to ActivateSession may be associated with different SecureChannels. If this is the
1213
+ // case then the Server shall verify that the Certificate the Client used to create the new
1214
+ // SecureChannel is the same as the Certificate used to create the original SecureChannel. In addition,
1215
+ // the Server shall verify that the Client supplied a UserIdentityToken that is identical to the token
1216
+ // currently associated with the Session. Once the Server accepts the new SecureChannel it shall
1217
+ // reject requests sent via the old SecureChannel.
1218
+ /**
1219
+ *
1220
+ * @method _on_ActivateSessionRequest
1221
+ * @private
1222
+ *
1223
+ *
1224
+ */
1225
+ _on_ActivateSessionRequest(message, channel) {
1226
+ const request = message.request;
1227
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.ActivateSessionRequest);
1228
+ // get session from authenticationToken
1229
+ const authenticationToken = request.requestHeader.authenticationToken;
1230
+ const session = this.getSession(authenticationToken);
1231
+ function rejectConnection(server, statusCode) {
1232
+ if (statusCode === node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid) {
1233
+ server.engine.incrementRejectedSessionCount();
1234
+ }
1235
+ else {
1236
+ server.engine.incrementRejectedSessionCount();
1237
+ server.engine.incrementSecurityRejectedSessionCount();
1238
+ }
1239
+ const response1 = new node_opcua_service_session_1.ActivateSessionResponse({ responseHeader: { serviceResult: statusCode } });
1240
+ channel.send_response("MSG", response1, message);
1241
+ // and close !
1242
+ }
1243
+ let response;
1244
+ /* istanbul ignore next */
1245
+ if (!session) {
1246
+ // this may happen when the server has been restarted and a client tries to reconnect, thinking
1247
+ // that the previous session may still be active
1248
+ debugLog(chalk.yellow.bold(" Bad Session in _on_ActivateSessionRequest"), authenticationToken.toString());
1249
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1250
+ }
1251
+ // tslint:disable-next-line: no-unused-expression
1252
+ session.keepAlive ? session.keepAlive() : void 0;
1253
+ // OpcUA 1.02 part 3 $5.6.3.1 ActiveSession Set page 29
1254
+ // When the ActivateSession Service is called f or the first time then the Server shall reject the request
1255
+ // if the SecureChannel is not same as the one associated with the CreateSession request.
1256
+ if (session.status === "new") {
1257
+ // xx if (channel.session_nonce !== session.nonce) {
1258
+ if (!channel_has_session(channel, session)) {
1259
+ // it looks like session activation is being using a channel that is not the
1260
+ // one that have been used to create the session
1261
+ errorLog(" channel.sessionTokens === " + Object.keys(channel.sessionTokens).join(" "));
1262
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionNotActivated);
1263
+ }
1264
+ }
1265
+ // OpcUA 1.02 part 3 $5.6.3.1 ActiveSession Set page 29
1266
+ // ... Subsequent calls to ActivateSession may be associated with different SecureChannels. If this is the
1267
+ // case then the Server shall verify that the Certificate the Client used to create the new
1268
+ // SecureChannel is the same as the Certificate used to create the original SecureChannel.
1269
+ if (session.status === "active") {
1270
+ if (session.channel.channelId !== channel.channelId) {
1271
+ warningLog(" Session ", session.sessionName, " is being transferred from channel", chalk.cyan(session.channel.channelId.toString()), " to channel ", chalk.cyan(channel.channelId.toString()));
1272
+ // session is being reassigned to a new Channel,
1273
+ // we shall verify that the certificate used to create the Session is the same as the current
1274
+ // channel certificate.
1275
+ const old_channel_cert_thumbprint = thumbprint(session.channel.clientCertificate);
1276
+ const new_channel_cert_thumbprint = thumbprint(channel.clientCertificate);
1277
+ if (old_channel_cert_thumbprint !== new_channel_cert_thumbprint) {
1278
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadNoValidCertificates); // not sure about this code !
1279
+ }
1280
+ // ... In addition the Server shall verify that the Client supplied a UserIdentityToken that is
1281
+ // identical to the token currently associated with the Session reassign session to new channel.
1282
+ if (!sameIdentityToken(session.userIdentityToken, request.userIdentityToken)) {
1283
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadIdentityChangeNotSupported); // not sure about this code !
1284
+ }
1285
+ }
1286
+ moveSessionToChannel(session, channel);
1287
+ }
1288
+ else if (session.status === "screwed") {
1289
+ // session has been used before being activated => this should be detected and session should be dismissed.
1290
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1291
+ }
1292
+ else if (session.status === "closed") {
1293
+ warningLog(chalk.yellow.bold(" Bad Session Closed in _on_ActivateSessionRequest"), authenticationToken.toString());
1294
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadSessionClosed);
1295
+ }
1296
+ // verify clientSignature provided by the client
1297
+ if (!this.verifyClientSignature(session, channel, request.clientSignature)) {
1298
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadApplicationSignatureInvalid);
1299
+ }
1300
+ // userIdentityToken may be missing , assume anonymous access then
1301
+ request.userIdentityToken = request.userIdentityToken || createAnonymousIdentityToken(session.endpoint);
1302
+ // check request.userIdentityToken is correct ( expected type and correctly formed)
1303
+ this.isValidUserIdentityToken(channel, session, request.userIdentityToken, request.userTokenSignature, session.endpoint, (err, statusCode) => {
1304
+ if (statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1305
+ /* istanbul ignore next */
1306
+ if (!(statusCode && statusCode instanceof node_opcua_status_code_1.StatusCode)) {
1307
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadCertificateInvalid);
1308
+ }
1309
+ return rejectConnection(this, statusCode);
1310
+ }
1311
+ session.userIdentityToken = request.userIdentityToken;
1312
+ // check if user access is granted
1313
+ this.isUserAuthorized(channel, session, request.userIdentityToken, (err1, authorized) => {
1314
+ /* istanbul ignore next */
1315
+ if (err1) {
1316
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadInternalError);
1317
+ }
1318
+ if (!authorized) {
1319
+ return rejectConnection(this, node_opcua_status_code_1.StatusCodes.BadUserAccessDenied);
1320
+ }
1321
+ else {
1322
+ // extract : OPC UA part 4 - 5.6.3
1323
+ // Once used, a serverNonce cannot be used again. For that reason, the Server returns a new
1324
+ // serverNonce each time the ActivateSession Service is called.
1325
+ session.nonce = this.makeServerNonce();
1326
+ session.status = "active";
1327
+ response = new node_opcua_service_session_1.ActivateSessionResponse({ serverNonce: session.nonce });
1328
+ channel.send_response("MSG", response, message);
1329
+ const userIdentityTokenPasswordRemoved = (userIdentityToken) => {
1330
+ const a = userIdentityToken.clone();
1331
+ // remove password
1332
+ a.password = "*************";
1333
+ return a;
1334
+ };
1335
+ // send OPCUA Event Notification
1336
+ // see part 5 : 6.4.3 AuditEventType
1337
+ // 6.4.7 AuditSessionEventType
1338
+ // 6.4.10 AuditActivateSessionEventType
1339
+ (0, node_opcua_assert_1.assert)(session.nodeId); // sessionId
1340
+ // xx assert(session.channel.clientCertificate instanceof Buffer);
1341
+ (0, node_opcua_assert_1.assert)(session.sessionTimeout > 0);
1342
+ if (this.isAuditing) {
1343
+ this.raiseEvent("AuditActivateSessionEventType", {
1344
+ /* part 5 - 6.4.3 AuditEventType */
1345
+ actionTimeStamp: { dataType: "DateTime", value: new Date() },
1346
+ status: { dataType: "Boolean", value: true },
1347
+ serverId: { dataType: "String", value: "" },
1348
+ // ClientAuditEntryId contains the human-readable AuditEntryId defined in Part 3.
1349
+ clientAuditEntryId: { dataType: "String", value: "" },
1350
+ // The ClientUserId identifies the user of the client requesting an action.
1351
+ // The ClientUserId can be obtained from the UserIdentityToken passed in the
1352
+ // ActivateSession call.
1353
+ clientUserId: { dataType: "String", value: "cc" },
1354
+ sourceName: { dataType: "String", value: "Session/ActivateSession" },
1355
+ /* part 5 - 6.4.7 AuditSessionEventType */
1356
+ sessionId: { dataType: "NodeId", value: session.nodeId },
1357
+ /* part 5 - 6.4.10 AuditActivateSessionEventType */
1358
+ clientSoftwareCertificates: {
1359
+ arrayType: node_opcua_variant_2.VariantArrayType.Array,
1360
+ dataType: "ExtensionObject" /* SignedSoftwareCertificate */,
1361
+ value: []
1362
+ },
1363
+ // UserIdentityToken reflects the userIdentityToken parameter of the ActivateSession
1364
+ // Service call.
1365
+ // For Username/Password tokens the password should NOT be included.
1366
+ userIdentityToken: {
1367
+ dataType: "ExtensionObject" /* UserIdentityToken */,
1368
+ value: userIdentityTokenPasswordRemoved(session.userIdentityToken)
1369
+ },
1370
+ // SecureChannelId shall uniquely identify the SecureChannel. The application shall
1371
+ // use the same identifier in all AuditEvents related to the Session Service Set
1372
+ // (AuditCreateSessionEventType, AuditActivateSessionEventType and their subtypes) and
1373
+ // the SecureChannel Service Set (AuditChannelEventType and its subtypes).
1374
+ secureChannelId: { dataType: "String", value: session.channel.channelId.toString() }
1375
+ });
1376
+ }
1377
+ this.emit("session_activated", session, userIdentityTokenPasswordRemoved);
1378
+ }
1379
+ });
1380
+ });
1381
+ }
1382
+ prepare(message, channel) {
1383
+ const request = message.request;
1384
+ // --- check that session is correct
1385
+ const authenticationToken = request.requestHeader.authenticationToken;
1386
+ const session = this.getSession(authenticationToken, /*activeOnly*/ true);
1387
+ if (!session) {
1388
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid;
1389
+ return;
1390
+ }
1391
+ message.session = session;
1392
+ // --- check that provided session matches session attached to channel
1393
+ if (channel.channelId !== session.channelId) {
1394
+ if (!(request instanceof node_opcua_service_session_1.ActivateSessionRequest)) {
1395
+ errorLog(chalk.red.bgWhite("ERROR: channel.channelId !== session.channelId on processing request " + request.constructor.name), channel.channelId, session.channelId);
1396
+ }
1397
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSecureChannelIdInvalid;
1398
+ }
1399
+ else if (channel_has_session(channel, session)) {
1400
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.Good;
1401
+ }
1402
+ else {
1403
+ // session ma y have been moved to a different channel
1404
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.BadSecureChannelIdInvalid;
1405
+ }
1406
+ }
1407
+ /**
1408
+ * ensure that action is performed on a valid session object,
1409
+ * @method _apply_on_SessionObject
1410
+ * @param ResponseClass the constructor of the response Class
1411
+ * @param message
1412
+ * @param channel
1413
+ * @param actionToPerform
1414
+ * @param actionToPerform.session {ServerSession}
1415
+ * @param actionToPerform.sendResponse
1416
+ * @param actionToPerform.sendResponse.response
1417
+ * @param actionToPerform.sendError
1418
+ * @param actionToPerform.sendError.statusCode
1419
+ * @param actionToPerform.sendError.diagnostics
1420
+ *
1421
+ * @private
1422
+ */
1423
+ _apply_on_SessionObject(ResponseClass, message, channel, actionToPerform) {
1424
+ return __awaiter(this, void 0, void 0, function* () {
1425
+ (0, node_opcua_assert_1.assert)(typeof actionToPerform === "function");
1426
+ function sendResponse(response1) {
1427
+ try {
1428
+ (0, node_opcua_assert_1.assert)(response1 instanceof ResponseClass);
1429
+ if (message.session) {
1430
+ const counterName = ResponseClass.name.replace("Response", "");
1431
+ message.session.incrementRequestTotalCounter(counterName);
1432
+ }
1433
+ return channel.send_response("MSG", response1, message);
1434
+ }
1435
+ catch (err) {
1436
+ // istanbul ignore next
1437
+ if (err instanceof Error) {
1438
+ // istanbul ignore next
1439
+ errorLog("Internal error in issuing response\nplease contact support@sterfive.com", message.request.toString(), "\n", response1.toString());
1440
+ }
1441
+ // istanbul ignore next
1442
+ throw err;
1443
+ }
1444
+ }
1445
+ function sendError(statusCode) {
1446
+ if (message.session) {
1447
+ message.session.incrementRequestErrorCounter(ResponseClass.name.replace("Response", ""));
1448
+ }
1449
+ return g_sendError(channel, message, ResponseClass, statusCode);
1450
+ }
1451
+ let response;
1452
+ /* istanbul ignore next */
1453
+ if (!message.session || message.session_statusCode !== node_opcua_status_code_1.StatusCodes.Good) {
1454
+ const errMessage = "INVALID SESSION !! ";
1455
+ response = new ResponseClass({ responseHeader: { serviceResult: message.session_statusCode } });
1456
+ debugLog(chalk.red.bold(errMessage), chalk.yellow(message.session_statusCode.toString()), response.constructor.name);
1457
+ return sendResponse(response);
1458
+ }
1459
+ (0, node_opcua_assert_1.assert)(message.session_statusCode === node_opcua_status_code_1.StatusCodes.Good);
1460
+ // OPC UA Specification 1.02 part 4 page 26
1461
+ // When a Session is terminated, all outstanding requests on the Session are aborted and
1462
+ // Bad_SessionClosed StatusCodes are returned to the Client. In addition, the Server deletes the entry
1463
+ // for the Client from its SessionDiagnostics Array Variable and notifies any other Clients who were
1464
+ // subscribed to this entry.
1465
+ if (message.session.status === "closed") {
1466
+ // note : use StatusCodes.BadSessionClosed , for pending message for this session
1467
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1468
+ }
1469
+ if (message.session.status === "new") {
1470
+ // mark session as being screwed ! so it cannot be activated anymore
1471
+ message.session.status = "screwed";
1472
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionNotActivated);
1473
+ }
1474
+ if (message.session.status !== "active") {
1475
+ // mark session as being screwed ! so it cannot be activated anymore
1476
+ message.session.status = "screwed";
1477
+ // note : use StatusCodes.BadSessionClosed , for pending message for this session
1478
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1479
+ }
1480
+ // lets also reset the session watchdog so it doesn't
1481
+ // (Sessions are terminated by the Server automatically if the Client fails to issue a Service
1482
+ // request on the Session within the timeout period negotiated by the Server in the
1483
+ // CreateSession Service response. )
1484
+ if (message.session.keepAlive) {
1485
+ (0, node_opcua_assert_1.assert)(typeof message.session.keepAlive === "function");
1486
+ message.session.keepAlive();
1487
+ }
1488
+ message.session.incrementTotalRequestCount();
1489
+ yield actionToPerform(message.session, sendResponse, sendError);
1490
+ });
1491
+ }
1492
+ _apply_on_Subscription(ResponseClass, message, channel, actionToPerform) {
1493
+ return __awaiter(this, void 0, void 0, function* () {
1494
+ (0, node_opcua_assert_1.assert)(typeof actionToPerform === "function");
1495
+ const request = message.request;
1496
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "subscriptionId"));
1497
+ this._apply_on_SessionObject(ResponseClass, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1498
+ const subscription = session.getSubscription(request.subscriptionId);
1499
+ if (!subscription) {
1500
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid);
1501
+ }
1502
+ subscription.resetLifeTimeAndKeepAliveCounters();
1503
+ yield actionToPerform(session, subscription, sendResponse, sendError);
1504
+ }));
1505
+ });
1506
+ }
1507
+ _apply_on_SubscriptionIds(ResponseClass, message, channel, actionToPerform) {
1508
+ (0, node_opcua_assert_1.assert)(typeof actionToPerform === "function");
1509
+ const request = message.request;
1510
+ (0, node_opcua_assert_1.assert)(Object.prototype.hasOwnProperty.call(request, "subscriptionIds"));
1511
+ this._apply_on_SessionObject(ResponseClass, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1512
+ const subscriptionIds = request.subscriptionIds;
1513
+ if (!request.subscriptionIds || request.subscriptionIds.length === 0) {
1514
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1515
+ }
1516
+ // if (request.subscriptionIds.length > OPCUAServer.MAX_SUBSCRIPTION) {
1517
+ // return sendError(StatusCodes.BadTooManyOperations);
1518
+ // }
1519
+ const results = subscriptionIds.map((subscriptionId) => actionToPerform(session, subscriptionId));
1520
+ // resolve potential pending promises ....
1521
+ for (let i = 0; i < results.length; i++) {
1522
+ if (results[i].then) {
1523
+ results[i] = yield results[i];
1524
+ }
1525
+ }
1526
+ const response = new ResponseClass({
1527
+ responseHeader: {
1528
+ serviceResult: request.subscriptionIds.length > OPCUAServer.MAX_SUBSCRIPTION
1529
+ ? node_opcua_status_code_1.StatusCodes.BadTooManyOperations
1530
+ : node_opcua_status_code_1.StatusCodes.Good
1531
+ },
1532
+ results
1533
+ });
1534
+ sendResponse(response);
1535
+ }));
1536
+ }
1537
+ _apply_on_Subscriptions(ResponseClass, message, channel, actionToPerform) {
1538
+ this._apply_on_SubscriptionIds(ResponseClass, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () {
1539
+ /* istanbul ignore next */
1540
+ if (isSubscriptionIdInvalid(subscriptionId)) {
1541
+ return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
1542
+ }
1543
+ const subscription = session.getSubscription(subscriptionId);
1544
+ if (!subscription) {
1545
+ return node_opcua_status_code_1.StatusCodes.BadSubscriptionIdInvalid;
1546
+ }
1547
+ return actionToPerform(session, subscription);
1548
+ }));
1549
+ }
1550
+ _closeSession(authenticationToken, deleteSubscriptions, reason) {
1551
+ return __awaiter(this, void 0, void 0, function* () {
1552
+ if (deleteSubscriptions && this.options.onDeleteMonitoredItem) {
1553
+ const session = this.getSession(authenticationToken);
1554
+ if (session) {
1555
+ const subscriptions = session.publishEngine.subscriptions;
1556
+ for (const subscription of subscriptions) {
1557
+ yield subscription.applyOnMonitoredItem(this.options.onDeleteMonitoredItem.bind(null, subscription));
1558
+ }
1559
+ }
1560
+ }
1561
+ yield this.engine.closeSession(authenticationToken, deleteSubscriptions, reason);
1562
+ });
1563
+ }
1564
+ /**
1565
+ * @method _on_CloseSessionRequest
1566
+ * @param message
1567
+ * @param channel
1568
+ * @private
1569
+ */
1570
+ _on_CloseSessionRequest(message, channel) {
1571
+ const request = message.request;
1572
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_session_1.CloseSessionRequest);
1573
+ let response;
1574
+ message.session_statusCode = node_opcua_status_code_1.StatusCodes.Good;
1575
+ function sendError(statusCode) {
1576
+ return g_sendError(channel, message, node_opcua_service_session_1.CloseSessionResponse, statusCode);
1577
+ }
1578
+ function sendResponse(response1) {
1579
+ channel.send_response("MSG", response1, message);
1580
+ }
1581
+ // do not use _apply_on_SessionObject
1582
+ // this._apply_on_SessionObject(CloseSessionResponse, message, channel, function (session) {
1583
+ // });
1584
+ const session = message.session;
1585
+ if (!session) {
1586
+ return sendError(node_opcua_status_code_1.StatusCodes.BadSessionIdInvalid);
1587
+ }
1588
+ // session has been created but not activated !
1589
+ const wasNotActivated = session.status === "new";
1590
+ (() => __awaiter(this, void 0, void 0, function* () {
1591
+ yield this._closeSession(request.requestHeader.authenticationToken, request.deleteSubscriptions, "CloseSession");
1592
+ // if (false && wasNotActivated) {
1593
+ // return sendError(StatusCodes.BadSessionNotActivated);
1594
+ // }
1595
+ response = new node_opcua_service_session_1.CloseSessionResponse({});
1596
+ sendResponse(response);
1597
+ }))();
1598
+ }
1599
+ // browse services
1600
+ /**
1601
+ * @method _on_BrowseRequest
1602
+ * @param message
1603
+ * @param channel
1604
+ * @private
1605
+ */
1606
+ _on_BrowseRequest(message, channel) {
1607
+ const request = message.request;
1608
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_browse_1.BrowseRequest);
1609
+ const diagnostic = {};
1610
+ this._apply_on_SessionObject(node_opcua_service_browse_1.BrowseResponse, message, channel, (session, sendResponse, sendError) => {
1611
+ let response;
1612
+ // test view
1613
+ if (request.view && !request.view.viewId.isEmpty()) {
1614
+ let theView = this.engine.addressSpace.findNode(request.view.viewId);
1615
+ if (theView && theView.nodeClass !== node_opcua_data_model_1.NodeClass.View) {
1616
+ // Error: theView is not a View
1617
+ diagnostic.localizedText = { text: "Expecting a view here" };
1618
+ theView = null;
1619
+ }
1620
+ if (!theView) {
1621
+ return sendError(node_opcua_status_code_1.StatusCodes.BadViewIdUnknown);
1622
+ }
1623
+ }
1624
+ if (!request.nodesToBrowse || request.nodesToBrowse.length === 0) {
1625
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1626
+ }
1627
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerBrowse > 0) {
1628
+ if (request.nodesToBrowse.length > this.engine.serverCapabilities.operationLimits.maxNodesPerBrowse) {
1629
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1630
+ }
1631
+ }
1632
+ // limit results to requestedMaxReferencesPerNode further so it never exceed a too big number
1633
+ const requestedMaxReferencesPerNode = Math.min(9876, request.requestedMaxReferencesPerNode);
1634
+ (0, node_opcua_assert_1.assert)(request.nodesToBrowse[0].schema.name === "BrowseDescription");
1635
+ const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1636
+ const f = (0, util_1.callbackify)(this.engine.browseWithAutomaticExpansion).bind(this.engine);
1637
+ f(request.nodesToBrowse, context, (err, results) => {
1638
+ // istanbul ignore next
1639
+ if (!results) {
1640
+ throw new Error("internal error : " + (err === null || err === void 0 ? void 0 : err.message));
1641
+ }
1642
+ (0, node_opcua_assert_1.assert)(results[0].schema.name === "BrowseResult");
1643
+ // handle continuation point and requestedMaxReferencesPerNode
1644
+ const maxBrowseContinuationPoints = this.engine.serverCapabilities.maxBrowseContinuationPoints;
1645
+ results = results.map((result) => {
1646
+ (0, node_opcua_assert_1.assert)(!result.continuationPoint);
1647
+ // istanbul ignore next
1648
+ if (!session.continuationPointManager) {
1649
+ return new node_opcua_types_1.BrowseResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNoContinuationPoints });
1650
+ }
1651
+ if (session.continuationPointManager.hasReachedMaximum(maxBrowseContinuationPoints)) {
1652
+ return new node_opcua_types_1.BrowseResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadNoContinuationPoints });
1653
+ }
1654
+ const truncatedResult = session.continuationPointManager.registerReferences(requestedMaxReferencesPerNode, result.references || [], { continuationPoint: null });
1655
+ let { statusCode } = truncatedResult;
1656
+ const { continuationPoint, values } = truncatedResult;
1657
+ statusCode = result.statusCode;
1658
+ return new node_opcua_types_1.BrowseResult({
1659
+ statusCode,
1660
+ continuationPoint,
1661
+ references: values
1662
+ });
1663
+ });
1664
+ response = new node_opcua_service_browse_1.BrowseResponse({
1665
+ diagnosticInfos: undefined,
1666
+ results
1667
+ });
1668
+ sendResponse(response);
1669
+ });
1670
+ });
1671
+ }
1672
+ /**
1673
+ * @method _on_BrowseNextRequest
1674
+ * @param message
1675
+ * @param channel
1676
+ * @private
1677
+ */
1678
+ _on_BrowseNextRequest(message, channel) {
1679
+ const request = message.request;
1680
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_browse_1.BrowseNextRequest);
1681
+ this._apply_on_SessionObject(node_opcua_service_browse_1.BrowseNextResponse, message, channel, (session, sendResponse, sendError) => {
1682
+ if (!request.continuationPoints || request.continuationPoints.length === 0) {
1683
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1684
+ }
1685
+ const results = request.continuationPoints
1686
+ .map((continuationPoint, index) => session.continuationPointManager.getNextReferences(0, {
1687
+ continuationPoint,
1688
+ index,
1689
+ releaseContinuationPoints: request.releaseContinuationPoints
1690
+ }))
1691
+ .map((r) => ({
1692
+ continuationPoint: r.continuationPoint,
1693
+ references: r.values,
1694
+ statusCode: r.statusCode
1695
+ }));
1696
+ const response = new node_opcua_service_browse_1.BrowseNextResponse({
1697
+ diagnosticInfos: undefined,
1698
+ results
1699
+ });
1700
+ sendResponse(response);
1701
+ });
1702
+ }
1703
+ // read services
1704
+ _on_ReadRequest(message, channel) {
1705
+ const request = message.request;
1706
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_read_1.ReadRequest);
1707
+ this._apply_on_SessionObject(node_opcua_service_read_1.ReadResponse, message, channel, (session, sendResponse, sendError) => {
1708
+ const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1709
+ let response;
1710
+ let results = [];
1711
+ const timestampsToReturn = request.timestampsToReturn;
1712
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1713
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1714
+ }
1715
+ if (request.maxAge < 0) {
1716
+ return sendError(node_opcua_status_code_1.StatusCodes.BadMaxAgeInvalid);
1717
+ }
1718
+ request.nodesToRead = request.nodesToRead || [];
1719
+ if (!request.nodesToRead || request.nodesToRead.length <= 0) {
1720
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1721
+ }
1722
+ (0, node_opcua_assert_1.assert)(request.nodesToRead[0].schema.name === "ReadValueId");
1723
+ // limit size of nodesToRead array to maxNodesPerRead
1724
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerRead > 0) {
1725
+ if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRead) {
1726
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1727
+ }
1728
+ }
1729
+ // proceed with registered nodes alias resolution
1730
+ for (const nodeToRead of request.nodesToRead) {
1731
+ nodeToRead.nodeId = session.resolveRegisteredNode(nodeToRead.nodeId);
1732
+ }
1733
+ // ask for a refresh of asynchronous variables
1734
+ this.engine.refreshValues(request.nodesToRead, request.maxAge, (err) => {
1735
+ (0, node_opcua_assert_1.assert)(!err, " error not handled here , fix me");
1736
+ results = this.engine.read(context, request);
1737
+ (0, node_opcua_assert_1.assert)(results[0].schema.name === "DataValue");
1738
+ (0, node_opcua_assert_1.assert)(results.length === request.nodesToRead.length);
1739
+ response = new node_opcua_service_read_1.ReadResponse({
1740
+ diagnosticInfos: undefined,
1741
+ results: undefined
1742
+ });
1743
+ // set it here for performance
1744
+ response.results = results;
1745
+ (0, node_opcua_assert_1.assert)(response.diagnosticInfos.length === 0);
1746
+ sendResponse(response);
1747
+ });
1748
+ });
1749
+ }
1750
+ // read services
1751
+ _on_HistoryReadRequest(message, channel) {
1752
+ const request = message.request;
1753
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_history_1.HistoryReadRequest);
1754
+ this._apply_on_SessionObject(node_opcua_service_history_1.HistoryReadResponse, message, channel, (session, sendResponse, sendError) => {
1755
+ let response;
1756
+ const timestampsToReturn = request.timestampsToReturn;
1757
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1758
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1759
+ }
1760
+ request.nodesToRead = request.nodesToRead || [];
1761
+ if (!request.nodesToRead || request.nodesToRead.length <= 0) {
1762
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1763
+ }
1764
+ (0, node_opcua_assert_1.assert)(request.nodesToRead[0].schema.name === "HistoryReadValueId");
1765
+ // limit size of nodesToRead array to maxNodesPerRead
1766
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerRead > 0) {
1767
+ if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRead) {
1768
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1769
+ }
1770
+ }
1771
+ // todo : handle
1772
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadData > 0) {
1773
+ if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadData) {
1774
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1775
+ }
1776
+ }
1777
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadEvents > 0) {
1778
+ if (request.nodesToRead.length > this.engine.serverCapabilities.operationLimits.maxNodesPerHistoryReadEvents) {
1779
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1780
+ }
1781
+ }
1782
+ const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1783
+ // ask for a refresh of asynchronous variables
1784
+ this.engine.refreshValues(request.nodesToRead, 0, (err) => {
1785
+ (0, node_opcua_assert_1.assert)(!err, " error not handled here , fix me"); // TODO
1786
+ this.engine.historyRead(context, request, (err1, results) => {
1787
+ if (err1) {
1788
+ return sendError(node_opcua_status_code_1.StatusCodes.BadHistoryOperationInvalid);
1789
+ }
1790
+ if (!results) {
1791
+ return sendError(node_opcua_status_code_1.StatusCodes.BadHistoryOperationInvalid);
1792
+ }
1793
+ (0, node_opcua_assert_1.assert)(results[0].schema.name === "HistoryReadResult");
1794
+ (0, node_opcua_assert_1.assert)(results.length === request.nodesToRead.length);
1795
+ response = new node_opcua_service_history_1.HistoryReadResponse({
1796
+ diagnosticInfos: undefined,
1797
+ results
1798
+ });
1799
+ (0, node_opcua_assert_1.assert)(response.diagnosticInfos.length === 0);
1800
+ sendResponse(response);
1801
+ });
1802
+ });
1803
+ });
1804
+ }
1805
+ /*
1806
+ // write services
1807
+ // OPCUA Specification 1.02 Part 3 : 5.10.4 Write
1808
+ // This Service is used to write values to one or more Attributes of one or more Nodes. For constructed
1809
+ // Attribute values whose elements are indexed, such as an array, this Service allows Clients to write
1810
+ // the entire set of indexed values as a composite, to write individual elements or to write ranges of
1811
+ // elements of the composite.
1812
+ // The values are written to the data source, such as a device, and the Service does not return until it writes
1813
+ // the values or determines that the value cannot be written. In certain cases, the Server will successfully
1814
+ // to an intermediate system or Server, and will not know if the data source was updated properly. In these cases,
1815
+ // the Server should report a success code that indicates that the write was not verified.
1816
+ // In the cases where the Server is able to verify that it has successfully written to the data source,
1817
+ // it reports an unconditional success.
1818
+ */
1819
+ _on_WriteRequest(message, channel) {
1820
+ const request = message.request;
1821
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_write_1.WriteRequest);
1822
+ (0, node_opcua_assert_1.assert)(!request.nodesToWrite || Array.isArray(request.nodesToWrite));
1823
+ this._apply_on_SessionObject(node_opcua_service_write_1.WriteResponse, message, channel, (session, sendResponse, sendError) => {
1824
+ let response;
1825
+ if (!request.nodesToWrite || request.nodesToWrite.length === 0) {
1826
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1827
+ }
1828
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerWrite > 0) {
1829
+ if (request.nodesToWrite.length > this.engine.serverCapabilities.operationLimits.maxNodesPerWrite) {
1830
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1831
+ }
1832
+ }
1833
+ // proceed with registered nodes alias resolution
1834
+ for (const nodeToWrite of request.nodesToWrite) {
1835
+ nodeToWrite.nodeId = session.resolveRegisteredNode(nodeToWrite.nodeId);
1836
+ }
1837
+ const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1838
+ (0, node_opcua_assert_1.assert)(request.nodesToWrite[0].schema.name === "WriteValue");
1839
+ this.engine.write(context, request.nodesToWrite, (err, results) => {
1840
+ if (err) {
1841
+ errorLog(err);
1842
+ return sendError(node_opcua_status_code_1.StatusCodes.BadInternalError);
1843
+ }
1844
+ (0, node_opcua_assert_1.assert)(Array.isArray(results));
1845
+ (0, node_opcua_assert_1.assert)(results.length === request.nodesToWrite.length);
1846
+ response = new node_opcua_service_write_1.WriteResponse({
1847
+ diagnosticInfos: undefined,
1848
+ results
1849
+ });
1850
+ sendResponse(response);
1851
+ });
1852
+ });
1853
+ }
1854
+ // subscription services
1855
+ _on_CreateSubscriptionRequest(message, channel) {
1856
+ const engine = this.engine;
1857
+ const addressSpace = engine.addressSpace;
1858
+ const request = message.request;
1859
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.CreateSubscriptionRequest);
1860
+ this._apply_on_SessionObject(node_opcua_service_subscription_1.CreateSubscriptionResponse, message, channel, (session, sendResponse, sendError) => {
1861
+ const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
1862
+ if (session.currentSubscriptionCount >= OPCUAServer.MAX_SUBSCRIPTION) {
1863
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManySubscriptions);
1864
+ }
1865
+ const subscription = session.createSubscription(request);
1866
+ subscription.on("monitoredItem", (monitoredItem) => {
1867
+ prepareMonitoredItem(context, addressSpace, monitoredItem);
1868
+ });
1869
+ const response = new node_opcua_service_subscription_1.CreateSubscriptionResponse({
1870
+ revisedLifetimeCount: subscription.lifeTimeCount,
1871
+ revisedMaxKeepAliveCount: subscription.maxKeepAliveCount,
1872
+ revisedPublishingInterval: subscription.publishingInterval,
1873
+ subscriptionId: subscription.id
1874
+ });
1875
+ sendResponse(response);
1876
+ });
1877
+ }
1878
+ _on_DeleteSubscriptionsRequest(message, channel) {
1879
+ const request = message.request;
1880
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.DeleteSubscriptionsRequest);
1881
+ this._apply_on_SubscriptionIds(node_opcua_service_subscription_1.DeleteSubscriptionsResponse, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () {
1882
+ let subscription = this.engine.findOrphanSubscription(subscriptionId);
1883
+ // istanbul ignore next
1884
+ if (subscription) {
1885
+ warningLog("Deleting an orphan subscription", subscriptionId);
1886
+ yield this._beforeDeleteSubscription(subscription);
1887
+ return this.engine.deleteOrphanSubscription(subscription);
1888
+ }
1889
+ subscription = session.getSubscription(subscriptionId);
1890
+ if (subscription) {
1891
+ yield this._beforeDeleteSubscription(subscription);
1892
+ }
1893
+ return session.deleteSubscription(subscriptionId);
1894
+ }));
1895
+ }
1896
+ _on_TransferSubscriptionsRequest(message, channel) {
1897
+ //
1898
+ // sendInitialValue Boolean
1899
+ // A Boolean parameter with the following values:
1900
+ // TRUE the first Publish response(s) after the TransferSubscriptions call shall
1901
+ // contain the current values of all Monitored Items in the Subscription where
1902
+ // the Monitoring Mode is set to Reporting.
1903
+ // FALSE the first Publish response after the TransferSubscriptions call shall contain only the value
1904
+ // changes since the last Publish response was sent.
1905
+ // This parameter only applies to MonitoredItems used for monitoring Attribute changes.
1906
+ //
1907
+ const engine = this.engine;
1908
+ const request = message.request;
1909
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.TransferSubscriptionsRequest);
1910
+ this._apply_on_SubscriptionIds(node_opcua_service_subscription_1.TransferSubscriptionsResponse, message, channel, (session, subscriptionId) => __awaiter(this, void 0, void 0, function* () { return yield engine.transferSubscription(session, subscriptionId, request.sendInitialValues); }));
1911
+ }
1912
+ _on_CreateMonitoredItemsRequest(message, channel) {
1913
+ const engine = this.engine;
1914
+ const addressSpace = engine.addressSpace;
1915
+ const request = message.request;
1916
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.CreateMonitoredItemsRequest);
1917
+ this._apply_on_Subscription(node_opcua_service_subscription_1.CreateMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1918
+ const timestampsToReturn = request.timestampsToReturn;
1919
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1920
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1921
+ }
1922
+ if (!request.itemsToCreate || request.itemsToCreate.length === 0) {
1923
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1924
+ }
1925
+ if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
1926
+ if (request.itemsToCreate.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
1927
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1928
+ }
1929
+ }
1930
+ const options = this.options;
1931
+ let results = [];
1932
+ if (options.onCreateMonitoredItem) {
1933
+ const resultsPromise = request.itemsToCreate.map((monitoredItemCreateRequest) => __awaiter(this, void 0, void 0, function* () {
1934
+ const { monitoredItem, createResult } = subscription.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
1935
+ if (monitoredItem) {
1936
+ yield options.onCreateMonitoredItem(subscription, monitoredItem);
1937
+ subscription.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
1938
+ }
1939
+ return createResult;
1940
+ }));
1941
+ results = yield Promise.all(resultsPromise);
1942
+ }
1943
+ else {
1944
+ results = request.itemsToCreate.map((monitoredItemCreateRequest) => {
1945
+ const { monitoredItem, createResult } = subscription.preCreateMonitoredItem(addressSpace, timestampsToReturn, monitoredItemCreateRequest);
1946
+ if (monitoredItem) {
1947
+ subscription.postCreateMonitoredItem(monitoredItem, monitoredItemCreateRequest, createResult);
1948
+ }
1949
+ return createResult;
1950
+ });
1951
+ }
1952
+ const response = new node_opcua_service_subscription_1.CreateMonitoredItemsResponse({
1953
+ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.Good },
1954
+ results
1955
+ // ,diagnosticInfos: []
1956
+ });
1957
+ sendResponse(response);
1958
+ }));
1959
+ }
1960
+ _on_ModifySubscriptionRequest(message, channel) {
1961
+ const request = message.request;
1962
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.ModifySubscriptionRequest);
1963
+ this._apply_on_Subscription(node_opcua_service_subscription_1.ModifySubscriptionResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1964
+ subscription.modify(request);
1965
+ const response = new node_opcua_service_subscription_1.ModifySubscriptionResponse({
1966
+ revisedLifetimeCount: subscription.lifeTimeCount,
1967
+ revisedMaxKeepAliveCount: subscription.maxKeepAliveCount,
1968
+ revisedPublishingInterval: subscription.publishingInterval
1969
+ });
1970
+ sendResponse(response);
1971
+ }));
1972
+ }
1973
+ _on_ModifyMonitoredItemsRequest(message, channel) {
1974
+ const request = message.request;
1975
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.ModifyMonitoredItemsRequest);
1976
+ this._apply_on_Subscription(node_opcua_service_subscription_1.ModifyMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
1977
+ const timestampsToReturn = request.timestampsToReturn;
1978
+ if (timestampsToReturn === node_opcua_service_read_1.TimestampsToReturn.Invalid) {
1979
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTimestampsToReturnInvalid);
1980
+ }
1981
+ if (!request.itemsToModify || request.itemsToModify.length === 0) {
1982
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
1983
+ }
1984
+ /* istanbul ignore next */
1985
+ if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
1986
+ if (request.itemsToModify.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
1987
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
1988
+ }
1989
+ }
1990
+ const itemsToModify = request.itemsToModify; // MonitoredItemModifyRequest
1991
+ function modifyMonitoredItem(item) {
1992
+ const monitoredItemId = item.monitoredItemId;
1993
+ const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
1994
+ if (!monitoredItem) {
1995
+ return new node_opcua_service_subscription_1.MonitoredItemModifyResult({ statusCode: node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid });
1996
+ }
1997
+ // adjust samplingInterval if === -1
1998
+ if (item.requestedParameters.samplingInterval === -1) {
1999
+ item.requestedParameters.samplingInterval = subscription.publishingInterval;
2000
+ }
2001
+ return monitoredItem.modify(timestampsToReturn, item.requestedParameters);
2002
+ }
2003
+ const results = itemsToModify.map(modifyMonitoredItem);
2004
+ const response = new node_opcua_service_subscription_1.ModifyMonitoredItemsResponse({
2005
+ results
2006
+ });
2007
+ sendResponse(response);
2008
+ }));
2009
+ }
2010
+ _on_PublishRequest(message, channel) {
2011
+ const request = message.request;
2012
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.PublishRequest);
2013
+ this._apply_on_SessionObject(node_opcua_service_subscription_1.PublishResponse, message, channel, (session, sendResponse, sendError) => {
2014
+ (0, node_opcua_assert_1.assert)(session);
2015
+ (0, node_opcua_assert_1.assert)(session.publishEngine); // server.publishEngine doesn't exists, OPCUAServer has probably shut down already
2016
+ session.publishEngine._on_PublishRequest(request, (request1, response) => {
2017
+ sendResponse(response);
2018
+ });
2019
+ });
2020
+ }
2021
+ _on_SetPublishingModeRequest(message, channel) {
2022
+ const request = message.request;
2023
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetPublishingModeRequest);
2024
+ const publishingEnabled = request.publishingEnabled;
2025
+ this._apply_on_Subscriptions(node_opcua_service_subscription_1.SetPublishingModeResponse, message, channel, (session, subscription) => __awaiter(this, void 0, void 0, function* () {
2026
+ return subscription.setPublishingMode(publishingEnabled);
2027
+ }));
2028
+ }
2029
+ _on_DeleteMonitoredItemsRequest(message, channel) {
2030
+ const request = message.request;
2031
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.DeleteMonitoredItemsRequest);
2032
+ this._apply_on_Subscription(node_opcua_service_subscription_1.DeleteMonitoredItemsResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2033
+ /* istanbul ignore next */
2034
+ if (!request.monitoredItemIds || request.monitoredItemIds.length === 0) {
2035
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2036
+ }
2037
+ /* istanbul ignore next */
2038
+ if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2039
+ if (request.monitoredItemIds.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2040
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2041
+ }
2042
+ }
2043
+ const resultsPromises = request.monitoredItemIds.map((monitoredItemId) => __awaiter(this, void 0, void 0, function* () {
2044
+ if (this.options.onDeleteMonitoredItem) {
2045
+ const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
2046
+ if (monitoredItem) {
2047
+ yield this.options.onDeleteMonitoredItem(subscription, monitoredItem);
2048
+ }
2049
+ }
2050
+ return subscription.removeMonitoredItem(monitoredItemId);
2051
+ }));
2052
+ try {
2053
+ const results = yield Promise.all(resultsPromises);
2054
+ const response = new node_opcua_service_subscription_1.DeleteMonitoredItemsResponse({
2055
+ diagnosticInfos: undefined,
2056
+ results
2057
+ });
2058
+ sendResponse(response);
2059
+ }
2060
+ catch (err) {
2061
+ console.log(err);
2062
+ return sendError(node_opcua_status_code_1.StatusCodes.BadInternalError);
2063
+ }
2064
+ }));
2065
+ }
2066
+ _on_SetTriggeringRequest(message, channel) {
2067
+ const request = message.request;
2068
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetTriggeringRequest);
2069
+ this._apply_on_Subscription(node_opcua_service_subscription_1.SetTriggeringResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2070
+ /* */
2071
+ const { triggeringItemId, linksToAdd, linksToRemove } = request;
2072
+ /**
2073
+ * The MaxMonitoredItemsPerCall Property indicates
2074
+ * [...]
2075
+ * • the maximum size of the sum of the linksToAdd and linksToRemove arrays when a
2076
+ * Client calls the SetTriggering Service.
2077
+ *
2078
+ */
2079
+ const maxElements = (linksToAdd ? linksToAdd.length : 0) + (linksToRemove ? linksToRemove.length : 0);
2080
+ if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2081
+ if (maxElements > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2082
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2083
+ }
2084
+ }
2085
+ const { addResults, removeResults, statusCode } = subscription.setTriggering(triggeringItemId, linksToAdd, linksToRemove);
2086
+ const response = new node_opcua_service_subscription_1.SetTriggeringResponse({
2087
+ responseHeader: { serviceResult: statusCode },
2088
+ addResults,
2089
+ removeResults,
2090
+ addDiagnosticInfos: null,
2091
+ removeDiagnosticInfos: null
2092
+ });
2093
+ sendResponse(response);
2094
+ }));
2095
+ }
2096
+ _beforeDeleteSubscription(subscription) {
2097
+ return __awaiter(this, void 0, void 0, function* () {
2098
+ if (!this.options.onDeleteMonitoredItem) {
2099
+ return;
2100
+ }
2101
+ yield subscription.applyOnMonitoredItem(this.options.onDeleteMonitoredItem.bind(null, subscription));
2102
+ });
2103
+ }
2104
+ _on_RepublishRequest(message, channel) {
2105
+ const request = message.request;
2106
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.RepublishRequest);
2107
+ this._apply_on_Subscription(node_opcua_service_subscription_1.RepublishResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2108
+ // update diagnostic counter
2109
+ subscription.subscriptionDiagnostics.republishRequestCount += 1;
2110
+ subscription.subscriptionDiagnostics.republishMessageRequestCount += 1;
2111
+ const retransmitSequenceNumber = request.retransmitSequenceNumber;
2112
+ const notificationMessage = subscription.getMessageForSequenceNumber(retransmitSequenceNumber);
2113
+ if (!notificationMessage) {
2114
+ return sendError(node_opcua_status_code_1.StatusCodes.BadMessageNotAvailable);
2115
+ }
2116
+ const response = new node_opcua_service_subscription_1.RepublishResponse({
2117
+ notificationMessage,
2118
+ responseHeader: {
2119
+ serviceResult: node_opcua_status_code_1.StatusCodes.Good
2120
+ }
2121
+ });
2122
+ // update diagnostic counter
2123
+ subscription.subscriptionDiagnostics.republishMessageCount += 1;
2124
+ sendResponse(response);
2125
+ }));
2126
+ }
2127
+ // Bad_NothingToDo
2128
+ // Bad_TooManyOperations
2129
+ // Bad_SubscriptionIdInvalid
2130
+ // Bad_MonitoringModeInvalid
2131
+ _on_SetMonitoringModeRequest(message, channel) {
2132
+ const request = message.request;
2133
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_subscription_1.SetMonitoringModeRequest);
2134
+ this._apply_on_Subscription(node_opcua_service_subscription_1.SetMonitoringModeResponse, message, channel, (session, subscription, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2135
+ /* istanbul ignore next */
2136
+ if (!request.monitoredItemIds || request.monitoredItemIds.length === 0) {
2137
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2138
+ }
2139
+ /* istanbul ignore next */
2140
+ if (this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall > 0) {
2141
+ if (request.monitoredItemIds.length > this.engine.serverCapabilities.operationLimits.maxMonitoredItemsPerCall) {
2142
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2143
+ }
2144
+ }
2145
+ const monitoringMode = request.monitoringMode;
2146
+ if (!isMonitoringModeValid(monitoringMode)) {
2147
+ return sendError(node_opcua_status_code_1.StatusCodes.BadMonitoringModeInvalid);
2148
+ }
2149
+ const results = request.monitoredItemIds.map((monitoredItemId) => {
2150
+ const monitoredItem = subscription.getMonitoredItem(monitoredItemId);
2151
+ if (!monitoredItem) {
2152
+ return node_opcua_status_code_1.StatusCodes.BadMonitoredItemIdInvalid;
2153
+ }
2154
+ monitoredItem.setMonitoringMode(monitoringMode);
2155
+ return node_opcua_status_code_1.StatusCodes.Good;
2156
+ });
2157
+ const response = new node_opcua_service_subscription_1.SetMonitoringModeResponse({
2158
+ results
2159
+ });
2160
+ sendResponse(response);
2161
+ }));
2162
+ }
2163
+ // _on_TranslateBrowsePathsToNodeIds service
2164
+ _on_TranslateBrowsePathsToNodeIdsRequest(message, channel) {
2165
+ const request = message.request;
2166
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsRequest);
2167
+ this._apply_on_SessionObject(node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse, message, channel, (session, sendResponse, sendError) => __awaiter(this, void 0, void 0, function* () {
2168
+ if (!request.browsePaths || request.browsePaths.length === 0) {
2169
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2170
+ }
2171
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerTranslateBrowsePathsToNodeIds > 0) {
2172
+ if (request.browsePaths.length >
2173
+ this.engine.serverCapabilities.operationLimits.maxNodesPerTranslateBrowsePathsToNodeIds) {
2174
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2175
+ }
2176
+ }
2177
+ const browsePathsResults = request.browsePaths.map((browsePath) => this.engine.browsePath(browsePath));
2178
+ const response = new node_opcua_service_translate_browse_path_1.TranslateBrowsePathsToNodeIdsResponse({
2179
+ diagnosticInfos: null,
2180
+ results: browsePathsResults
2181
+ });
2182
+ sendResponse(response);
2183
+ }));
2184
+ }
2185
+ // Call Service Result Codes
2186
+ // Symbolic Id Description
2187
+ // Bad_NothingToDo See Table 165 for the description of this result code.
2188
+ // Bad_TooManyOperations See Table 165 for the description of this result code.
2189
+ //
2190
+ _on_CallRequest(message, channel) {
2191
+ const request = message.request;
2192
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_call_1.CallRequest);
2193
+ this._apply_on_SessionObject(node_opcua_service_call_1.CallResponse, message, channel, (session, sendResponse, sendError) => {
2194
+ let response;
2195
+ if (!request.methodsToCall || request.methodsToCall.length === 0) {
2196
+ return sendError(node_opcua_status_code_1.StatusCodes.BadNothingToDo);
2197
+ }
2198
+ // the MaxNodesPerMethodCall Property indicates the maximum size of the methodsToCall array when
2199
+ // a Client calls the Call Service.
2200
+ let maxNodesPerMethodCall = this.engine.serverCapabilities.operationLimits.maxNodesPerMethodCall;
2201
+ maxNodesPerMethodCall = maxNodesPerMethodCall <= 0 ? 1000 : maxNodesPerMethodCall;
2202
+ if (request.methodsToCall.length > maxNodesPerMethodCall) {
2203
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2204
+ }
2205
+ /* jshint validthis: true */
2206
+ const addressSpace = this.engine.addressSpace;
2207
+ const context = new node_opcua_address_space_1.SessionContext({ session, server: this });
2208
+ async.map(request.methodsToCall, node_opcua_address_space_1.callMethodHelper.bind(null, context, addressSpace), (err, results) => {
2209
+ /* istanbul ignore next */
2210
+ if (err) {
2211
+ errorLog("ERROR in method Call !! ", err);
2212
+ }
2213
+ (0, node_opcua_assert_1.assert)(Array.isArray(results));
2214
+ response = new node_opcua_service_call_1.CallResponse({
2215
+ results: results
2216
+ });
2217
+ filterDiagnosticInfo(request.requestHeader.returnDiagnostics, response);
2218
+ sendResponse(response);
2219
+ });
2220
+ });
2221
+ }
2222
+ _on_RegisterNodesRequest(message, channel) {
2223
+ const request = message.request;
2224
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_register_node_1.RegisterNodesRequest);
2225
+ this._apply_on_SessionObject(node_opcua_service_register_node_1.RegisterNodesResponse, message, channel, (session, sendResponse, sendError) => {
2226
+ let response;
2227
+ if (!request.nodesToRegister || request.nodesToRegister.length === 0) {
2228
+ response = new node_opcua_service_register_node_1.RegisterNodesResponse({ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.BadNothingToDo } });
2229
+ return sendResponse(response);
2230
+ }
2231
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes > 0) {
2232
+ if (request.nodesToRegister.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes) {
2233
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2234
+ }
2235
+ }
2236
+ // A list of NodeIds which the Client shall use for subsequent access operations. The
2237
+ // size and order of this list matches the size and order of the nodesToRegister
2238
+ // request parameter.
2239
+ // The Server may return the NodeId from the request or a new (an alias) NodeId. It
2240
+ // is recommended that the Server return a numeric NodeIds for aliasing.
2241
+ // In case no optimization is supported for a Node, the Server shall return the
2242
+ // NodeId from the request.
2243
+ const registeredNodeIds = request.nodesToRegister.map((nodeId) => session.registerNode(nodeId));
2244
+ response = new node_opcua_service_register_node_1.RegisterNodesResponse({
2245
+ registeredNodeIds
2246
+ });
2247
+ sendResponse(response);
2248
+ });
2249
+ }
2250
+ _on_UnregisterNodesRequest(message, channel) {
2251
+ const request = message.request;
2252
+ (0, node_opcua_assert_1.assert)(request instanceof node_opcua_service_register_node_1.UnregisterNodesRequest);
2253
+ this._apply_on_SessionObject(node_opcua_service_register_node_1.UnregisterNodesResponse, message, channel, (session, sendResponse, sendError) => {
2254
+ let response;
2255
+ request.nodesToUnregister = request.nodesToUnregister || [];
2256
+ if (!request.nodesToUnregister || request.nodesToUnregister.length === 0) {
2257
+ response = new node_opcua_service_register_node_1.UnregisterNodesResponse({ responseHeader: { serviceResult: node_opcua_status_code_1.StatusCodes.BadNothingToDo } });
2258
+ return sendResponse(response);
2259
+ }
2260
+ if (this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes > 0) {
2261
+ if (request.nodesToUnregister.length > this.engine.serverCapabilities.operationLimits.maxNodesPerRegisterNodes) {
2262
+ return sendError(node_opcua_status_code_1.StatusCodes.BadTooManyOperations);
2263
+ }
2264
+ }
2265
+ request.nodesToUnregister.map((nodeId) => session.unRegisterNode(nodeId));
2266
+ response = new node_opcua_service_register_node_1.UnregisterNodesResponse({});
2267
+ sendResponse(response);
2268
+ });
2269
+ }
2270
+ /* istanbul ignore next */
2271
+ _on_Cancel(message, channel) {
2272
+ return g_sendError(channel, message, node_opcua_types_1.CancelResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2273
+ }
2274
+ // NodeManagement Service Set Overview
2275
+ // This Service Set defines Services to add and delete AddressSpace Nodes and References between them. All added
2276
+ // Nodes continue to exist in the AddressSpace even if the Client that created them disconnects from the Server.
2277
+ //
2278
+ /* istanbul ignore next */
2279
+ _on_AddNodes(message, channel) {
2280
+ return g_sendError(channel, message, node_opcua_service_node_management_1.AddNodesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2281
+ }
2282
+ /* istanbul ignore next */
2283
+ _on_AddReferences(message, channel) {
2284
+ return g_sendError(channel, message, node_opcua_service_node_management_1.AddReferencesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2285
+ }
2286
+ /* istanbul ignore next */
2287
+ _on_DeleteNodes(message, channel) {
2288
+ return g_sendError(channel, message, node_opcua_service_node_management_1.DeleteNodesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2289
+ }
2290
+ /* istanbul ignore next */
2291
+ _on_DeleteReferences(message, channel) {
2292
+ return g_sendError(channel, message, node_opcua_service_node_management_1.DeleteReferencesResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2293
+ }
2294
+ // Query Service
2295
+ /* istanbul ignore next */
2296
+ _on_QueryFirst(message, channel) {
2297
+ return g_sendError(channel, message, node_opcua_service_query_1.QueryFirstResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2298
+ }
2299
+ /* istanbul ignore next */
2300
+ _on_QueryNext(message, channel) {
2301
+ return g_sendError(channel, message, node_opcua_service_query_1.QueryNextResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2302
+ }
2303
+ /* istanbul ignore next */
2304
+ _on_HistoryUpdate(message, channel) {
2305
+ return g_sendError(channel, message, node_opcua_service_history_1.HistoryUpdateResponse, node_opcua_status_code_1.StatusCodes.BadServiceUnsupported);
2306
+ }
2307
+ createEndpoint(port1, serverOptions) {
2308
+ // add the tcp/ip endpoint with no security
2309
+ const endPoint = new server_end_point_1.OPCUAServerEndPoint({
2310
+ port: port1,
2311
+ certificateManager: this.serverCertificateManager,
2312
+ certificateChain: this.getCertificateChain(),
2313
+ privateKey: this.getPrivateKey(),
2314
+ defaultSecureTokenLifetime: serverOptions.defaultSecureTokenLifetime || 600000,
2315
+ timeout: serverOptions.timeout || 3 * 60 * 1000,
2316
+ maxConnections: this.maxConnectionsPerEndpoint,
2317
+ objectFactory: this.objectFactory,
2318
+ serverInfo: this.serverInfo
2319
+ });
2320
+ return endPoint;
2321
+ }
2322
+ createEndpointDescriptions(serverOption, endpointOptions) {
2323
+ /* istanbul ignore next */
2324
+ if (!endpointOptions) {
2325
+ throw new Error("internal error");
2326
+ }
2327
+ const hostname = (0, node_opcua_hostname_1.getFullyQualifiedDomainName)();
2328
+ endpointOptions.hostname = endpointOptions.hostname || hostname;
2329
+ endpointOptions.port = endpointOptions.port || 26543;
2330
+ /* istanbul ignore next */
2331
+ if (!Object.prototype.hasOwnProperty.call(endpointOptions, "port") ||
2332
+ !isFinite(endpointOptions.port) ||
2333
+ typeof endpointOptions.port !== "number") {
2334
+ throw new Error("expecting a valid port (number)");
2335
+ }
2336
+ const port = Number(endpointOptions.port || 0);
2337
+ const endPoint = this.createEndpoint(port, serverOption);
2338
+ endpointOptions.alternateHostname = endpointOptions.alternateHostname || [];
2339
+ const alternateHostname = endpointOptions.alternateHostname instanceof Array
2340
+ ? endpointOptions.alternateHostname
2341
+ : [endpointOptions.alternateHostname];
2342
+ const allowAnonymous = endpointOptions.allowAnonymous === undefined ? true : !!endpointOptions.allowAnonymous;
2343
+ endPoint.addStandardEndpointDescriptions({
2344
+ allowAnonymous,
2345
+ securityModes: endpointOptions.securityModes,
2346
+ securityPolicies: endpointOptions.securityPolicies,
2347
+ hostname: endpointOptions.hostname,
2348
+ alternateHostname,
2349
+ disableDiscovery: !!endpointOptions.disableDiscovery,
2350
+ // xx hostname,
2351
+ resourcePath: serverOption.resourcePath || ""
2352
+ });
2353
+ return endPoint;
2354
+ }
2355
+ initializeCM() {
2356
+ const _super = Object.create(null, {
2357
+ initializeCM: { get: () => super.initializeCM }
2358
+ });
2359
+ return __awaiter(this, void 0, void 0, function* () {
2360
+ yield _super.initializeCM.call(this);
2361
+ yield this.userCertificateManager.initialize();
2362
+ });
2363
+ }
2364
+ }
2365
+ exports.OPCUAServer = OPCUAServer;
2366
+ OPCUAServer.defaultShutdownTimeout = 100; // 250 ms
2367
+ /**
2368
+ * if requestExactEndpointUrl is set to true the server will only accept createSession that have a endpointUrl that strictly matches
2369
+ * one of the provided endpoint.
2370
+ * This mean that if the server expose a endpoint with url such as opc.tcp://MYHOSTNAME:1234, client will not be able to reach the server
2371
+ * with the ip address of the server.
2372
+ * requestExactEndpointUrl = true => emulates the Prosys Server behavior
2373
+ * requestExactEndpointUrl = false => emulates the Unified Automation behavior.
2374
+ */
2375
+ OPCUAServer.requestExactEndpointUrl = g_requestExactEndpointUrl;
2376
+ OPCUAServer.registry = new node_opcua_object_registry_1.ObjectRegistry();
2377
+ OPCUAServer.fallbackSessionName = "Client didn't provide a meaningful sessionName ...";
2378
+ /**
2379
+ * the maximum number of subscription that can be created per server
2380
+ */
2381
+ OPCUAServer.MAX_SUBSCRIPTION = 50;
2382
+ const opts = { multiArgs: false };
2383
+ OPCUAServer.prototype.start = thenify.withCallback(OPCUAServer.prototype.start, opts);
2384
+ OPCUAServer.prototype.initialize = thenify.withCallback(OPCUAServer.prototype.initialize, opts);
2385
+ OPCUAServer.prototype.shutdown = thenify.withCallback(OPCUAServer.prototype.shutdown, opts);
2386
2386
  //# sourceMappingURL=opcua_server.js.map