opcjs-client 0.1.34-alpha → 0.1.35-alpha

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sessions/sessionInvalidError.ts","../src/services/serviceBase.ts","../src/services/sessionService.ts","../src/issuerConfiguration.ts","../src/sessions/session.ts","../src/sessions/sessionHandler.ts","../src/securityConfiguration.ts","../src/services/attributeServiceAttributes.ts","../src/services/attributeService.ts","../src/readValueResult.ts","../src/subscriptionHandlerEntry.ts","../src/subscriptionHandler.ts","../src/services/subscriptionService.ts","../src/services/monitoredItemService.ts","../src/services/methodService.ts","../src/callMethodResult.ts","../src/services/browseService.ts","../src/browseNodeResult.ts","../src/client.ts","../src/configurationClient.ts","../src/userIdentity.ts"],"names":["StatusCodeToString","StatusCode","StatusCodeToStringNumber","RequestHeader","ExtensionObject","getLogger","ApplicationDescription","LocalizedText","ApplicationTypeEnum","CreateSessionRequest","CreateSessionResponse","SignatureData","ActivateSessionRequest","CloseSessionRequest","UserTokenTypeEnum","NodeId","TimestampsToReturnEnum","ReadValueId","QualifiedName","ReadRequest","SubscriptionAcknowledgement","ExpandedNodeId","CreateSubscriptionRequest","PublishRequest","MonitoringParameters","MonitoredItemCreateRequest","MonitoringModeEnum","CreateMonitoredItemsRequest","CallRequest","ViewDescription","BrowseRequest","BrowseNextRequest","initLoggerProvider","WebSocketFascade","WebSocketReadableStream","WebSocketWritableStream","SecureChannelContext","TcpMessageInjector","TcpConnectionHandler","TcpMessageDecoupler","SecureChannelMessageEncoder","SecureChannelTypeDecoder","SecureChannelMessageDecoder","SecureChannelTypeEncoder","SecureChannelChunkWriter","SecureChannelChunkReader","SecureChannelFacade","CallMethodRequest","Variant","BrowseDescription","BrowseDirectionEnum","BrowseResultMaskEnum","Configuration","LoggerFactory","Encoder","BinaryWriter","registerEncoders","Decoder","BinaryReader","registerTypeDecoders","registerBinaryDecoders","AnonymousIdentityToken","UserNameI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AmB,aAAA,EAAiF;AAC9G,IAAA,MAAM,YAAA,GAAe,IAAI,aAAA,EAAa;AACtC,IAAA,MAAM,WAAA,GAAc,IAAIiD,6BAAAA,EAAoB;AAC5C,IAAA,WAAA,CAAY,SAAA,GAAY,IAAI,WAAA,EAAY,CAAE,OAAO,EAAE,CAAA;AACnD,IAAA,YAAA,CAAa,iBAAA,GAAoB,WAAA;AACjC,IAAA,YAAA,CAAa,YAAYjD,2BAAAA,CAAkB,WAAA;AAC3C,IAAA,YAAA,CAAa,mBAAA,GAAsB,aAAA;AACnC,IAAA,OAAO,YAAA;AAAA,EACX;AAAA,EAEO,oBAAA,GAA0C;AAC7C,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EAChB;AAAA,EAEO,YAAA,GAAkC;AACrC,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EAChB;AAAA,EAEO,sBAAA,GAA+E;AAClF,IAAA,IAAG,CAAC,KAAK,mBAAA,EAAoB;AACzB,MAAA,MAAM,IAAI,MAAM,kCAAkC,CAAA;AAAA,IACtD;AAEA,IAAA,OAAO,IAAA,CAAK,mBAAA;AAAA,EAChB;AACJ","file":"index.cjs","sourcesContent":["import { StatusCodeToString } from 'opcjs-base'\n\n/**\n * Thrown when the server signals that the current Session is no longer valid.\n *\n * Callers that want to react to a dropped session (e.g. by creating a new one\n * and retrying the operation) should catch this specific error type instead of\n * the generic `Error` class.\n *\n * Relevant OPC UA status codes:\n * - `BadSessionIdInvalid` (0x80250000) – session no longer exists on the server\n * - `BadSessionClosed` (0x80260000) – session was closed explicitly\n */\nexport class SessionInvalidError extends Error {\n readonly statusCode: number\n\n constructor(statusCode: number) {\n super(`Session is no longer valid: ${StatusCodeToString(statusCode)} (0x${statusCode.toString(16).toUpperCase()})`)\n this.name = 'SessionInvalidError'\n this.statusCode = statusCode\n }\n}\n","import { ExtensionObject, ISecureChannel, NodeId, RequestHeader, StatusCode, StatusCodeToString, StatusCodeToStringNumber } from 'opcjs-base'\n\nimport { SessionInvalidError } from '../sessions/sessionInvalidError.js'\n\nexport abstract class ServiceBase {\n\n /**\n * Validates the `serviceResult` value from a response header.\n *\n * Throws `SessionInvalidError` for session-related status codes so callers\n * can detect a dropped session and act accordingly (e.g. reconnect).\n * Throws a generic `Error` for all other non-Good codes.\n *\n * @param result - The `serviceResult` value from the response header.\n * @param context - Short description used in the error message (e.g. \"ReadRequest\").\n */\n protected checkServiceResult(result: number | undefined, context: string): void {\n if (result === undefined || result === StatusCode.Good) return\n\n if (result === StatusCode.BadSessionIdInvalid || result === StatusCode.BadSessionClosed) {\n throw new SessionInvalidError(result)\n }\n\n throw new Error(`${context} failed: ${StatusCodeToString(result)} (${StatusCodeToStringNumber(result)})`)\n }\n\n protected createRequestHeader(): RequestHeader {\n const requestHeader = new RequestHeader();\n requestHeader.authenticationToken = this.authToken;\n requestHeader.timestamp = new Date();\n requestHeader.requestHandle = 0; // will be set by secure channel\n requestHeader.returnDiagnostics = 0;\n requestHeader.auditEntryId = '';\n requestHeader.timeoutHint = 60000;\n requestHeader.additionalHeader = ExtensionObject.newEmpty();\n\n return requestHeader;\n }\n \n constructor(private authToken: NodeId, protected secureChannel: ISecureChannel){}\n}","import {\n ActivateSessionRequest, ActivateSessionResponse, ApplicationDescription, ApplicationTypeEnum,\n CloseSessionRequest, CloseSessionResponse,\n Configuration, CreateSessionRequest, CreateSessionResponse, EndpointDescription, ExtensionObject,\n getLogger,\n ISecureChannel, LocalizedText, NodeId, SignatureData, SignedSoftwareCertificate, StatusCode,\n StatusCodeToString, UserIdentityToken,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\nexport class SessionService extends ServiceBase {\n private logger = getLogger(\"services.SessionService\");\n\n /**\n * Creates a new session on the server (OPC UA Part 4, Section 5.7.2).\n * @returns The session ID, authentication token, and selected server endpoint.\n */\n async createSession(): Promise<{ sessionId: number, authToken: NodeId, endpoint: EndpointDescription }> {\n this.logger.debug(\"Creating session...\");\n\n const clientDescription = new ApplicationDescription();\n clientDescription.applicationUri = this.configuration.applicationUri;\n clientDescription.productUri = this.configuration.productUri;\n clientDescription.applicationName = new LocalizedText(undefined, this.configuration.productName);\n clientDescription.applicationType = ApplicationTypeEnum.Client;\n clientDescription.gatewayServerUri = '';\n clientDescription.discoveryProfileUri = '';\n clientDescription.discoveryUrls = new Array<string>();\n\n const request = new CreateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientDescription = clientDescription;\n request.serverUri = '';\n request.endpointUrl = this.secureChannel.getEndpointUrl();\n request.sessionName = '';\n request.clientNonce = null;\n request.clientCertificate = null;\n request.requestedSessionTimeout = 60000;\n request.maxResponseMessageSize = 0;\n\n\n // todo: verify endpoints\n // todo: check application uri in server certificate\n\n this.logger.debug(\"Sending CreateSessionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request);\n if (!response || !(response instanceof CreateSessionResponse)) {\n throw new Error(\"Invalid response type for CreateSessionRequest\");\n }\n\n const castedResponse = response as CreateSessionResponse;\n if (!castedResponse || !castedResponse.sessionId || !castedResponse.authenticationToken) {\n throw new Error(\"CreateSessionResponse missing SessionId or AuthenticationToken\");\n }\n\n const serviceResult = castedResponse.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSessionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n // The URL the client actually used to connect. Prepend the OPC UA scheme\n // prefix so it is parseable by the standard URL constructor.\n const clientConnectionUrl = new URL('opc.' + this.secureChannel.getEndpointUrl())\n const securityMode = this.secureChannel.getSecurityMode()\n const securityPolicyUri = this.secureChannel.getSecurityPolicy()\n\n // OPC UA Part 4, Section 5.4.4.2: Clients should be prepared to replace\n // the HostName and port returned in the EndpointDescription with the\n // HostName or IP address and port they used to call GetEndpoints. This\n // handles NAT/load-balancer scenarios where the server advertises internal\n // addresses that are unreachable by the client.\n const normalizeEndpointUrl = (serverEndpointUrl: string): URL => {\n const url = new URL(serverEndpointUrl)\n url.hostname = clientConnectionUrl.hostname\n url.port = clientConnectionUrl.port\n return url\n }\n\n // Match on protocol and path only; host and port are normalized away so\n // that internally-addressed endpoints are still found.\n const serverEndpoint = castedResponse?.serverEndpoints?.find(currentEndpoint => {\n const normalized = normalizeEndpointUrl(currentEndpoint.endpointUrl as string)\n return normalized.protocol === clientConnectionUrl.protocol\n && normalized.pathname === clientConnectionUrl.pathname\n && currentEndpoint.securityMode === securityMode\n && currentEndpoint.securityPolicyUri === securityPolicyUri\n })\n\n if (!serverEndpoint) {\n throw new Error(`Server endpoint ${clientConnectionUrl.toString()} not found in CreateSessionResponse`)\n }\n\n // Replace the server-reported host and port with the client's actual\n // connection address so downstream code uses the correct URL.\n serverEndpoint.endpointUrl = normalizeEndpointUrl(serverEndpoint.endpointUrl as string).toString()\n\n // NOTE: per OPC UA Part 4, Section 5.4.4.2 the client shall still verify\n // the HostName it used to open the SecureChannel against the HostName list\n // in the Server Certificate. This is deferred until certificate-based\n // security (non-None SecurityPolicy) is implemented.\n\n this.logger.debug(\"Session created with id:\", castedResponse.sessionId.identifier);\n return {\n sessionId: castedResponse.sessionId.identifier as number,\n authToken: castedResponse.authenticationToken,\n endpoint: serverEndpoint\n };\n }\n\n /**\n * Activates an existing session using the supplied identity token (OPC UA Part 4, Section 5.7.3).\n * @param identityToken - User identity token (anonymous, username/password, certificate, or issued token).\n */\n async activateSession(identityToken: UserIdentityToken): Promise<void> {\n const signatureData = new SignatureData();\n signatureData.algorithm = this.secureChannel.getSecurityPolicy();\n signatureData.signature = new Uint8Array(0);\n\n const request = new ActivateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientSignature = signatureData;\n request.clientSoftwareCertificates = new Array<SignedSoftwareCertificate>();\n request.localeIds = ['en-US'];\n request.userIdentityToken = ExtensionObject.newBinary(identityToken);\n request.userTokenSignature = signatureData;\n\n this.logger.debug(\"Sending ActivateSessionRequest...\");\n const activateResponse = await this.secureChannel.issueServiceRequest(request) as ActivateSessionResponse;\n\n const activateResult = activateResponse?.responseHeader?.serviceResult;\n if (activateResult !== undefined && activateResult !== StatusCode.Good) {\n throw new Error(`ActivateSessionRequest failed: ${StatusCodeToString(activateResult)}`);\n }\n\n this.logger.debug(\"Session activated.\");\n }\n\n /**\n * Closes the current session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * associated with this Session, freeing their resources immediately.\n * Pass false to keep Subscriptions alive for transfer to another Session.\n */\n async closeSession(deleteSubscriptions: boolean): Promise<void> {\n this.logger.debug('Sending CloseSessionRequest...')\n\n const request = new CloseSessionRequest()\n request.requestHeader = this.createRequestHeader()\n request.deleteSubscriptions = deleteSubscriptions\n\n const response = await this.secureChannel.issueServiceRequest(request) as CloseSessionResponse\n\n const result = response?.responseHeader?.serviceResult\n if (result !== undefined && result !== StatusCode.Good) {\n throw new Error(`CloseSession failed: ${StatusCodeToString(result)}`)\n }\n\n this.logger.debug('Session closed.')\n }\n\n recreate(authToken: NodeId): SessionService {\n return new SessionService(authToken, this.secureChannel, this.configuration)\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel, private configuration: Configuration) {\n super(authToken, secureChannel)\n }\n}","interface IssuerEndpointUrl {\n 'ua.resourceId': string;\n 'ua.authorityUrl': string;\n 'ua.authorityProfileUri': string;\n 'ua.tokenEndpoint': string;\n 'ua.authorizationEndpoint': string;\n 'ua.requestTypes': string[];\n 'ua.scopes': string[];\n}\n\nexport class IssuerConfiguration{\n public static newFrom(issuerEndpointUrl: IssuerEndpointUrl): IssuerConfiguration {\n return new IssuerConfiguration(\n issuerEndpointUrl['ua.resourceId'],\n issuerEndpointUrl['ua.authorityUrl'],\n issuerEndpointUrl['ua.authorityProfileUri'],\n issuerEndpointUrl['ua.tokenEndpoint'],\n issuerEndpointUrl['ua.authorizationEndpoint'],\n issuerEndpointUrl['ua.requestTypes'],\n issuerEndpointUrl['ua.scopes']\n );\n }\n \n constructor(\n public resourceId: string,\n public authorityUrl: string,\n public authorityProfileUri: string,\n public tokenEndpoint: string,\n public authorizationEndpoint: string,\n public requestTypes: string[],\n public scopes: string[]\n ){\n \n }\n}","import { EndpointDescription, IssuedIdentityToken, NodeId, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"../issuerConfiguration\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\n\nexport class Session {\n async activateSession(identity: UserIdentity): Promise<void> {\n const token = identity.getUserIdentityToken();\n const tokenType = identity.getTokenType();\n const tokenPolicy = this.endpoint.userIdentityTokens?.find(t => t.tokenType === tokenType);\n if (!tokenPolicy) {\n throw new Error(`UserIdentityToken of type ${tokenType} not supported by server`);\n }\n token.policyId = tokenPolicy.policyId;\n\n if (tokenType === UserTokenTypeEnum.IssuedToken) {\n if (!tokenPolicy.issuerEndpointUrl) {\n throw new Error(\"IssuerEndpointUrl not defined for IssuedToken\");\n }\n const issuerEndpointUrl = JSON.parse(tokenPolicy.issuerEndpointUrl)\n const issuerConfig = IssuerConfiguration.newFrom(issuerEndpointUrl);\n\n const issuerLoginCallback = identity.getIssuerLoginCallback();\n const tokenData = await issuerLoginCallback(issuerConfig);\n\n const issuerToken = token as IssuedIdentityToken;\n issuerToken.tokenData = new TextEncoder().encode(tokenData.json);\n }\n\n await this.sessionServices.activateSession(token);\n }\n\n getAuthToken(): NodeId {\n return this.authToken;\n }\n\n getSessionId(): number {\n return this.sessionId;\n }\n\n getEndpoint(): EndpointDescription {\n return this.endpoint;\n }\n\n /**\n * Closes the session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * tied to this Session. Defaults to true.\n */\n async close(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n constructor(\n public sessionId: number,\n private authToken: NodeId,\n private endpoint: EndpointDescription,\n private sessionServices: SessionService) { }\n}","import { ConfigurationClient } from \"../configurationClient\";\nimport { EndpointDescription, ISecureChannel, NodeId, UserTokenTypeEnum, getLogger } from \"opcjs-base\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\nimport { Session } from \"./session\";\n\nexport class SessionHandler {\n private sessionServices: SessionService;\n private logger = getLogger(\"sessions.SessionHandler\");\n\n async createNewSession(identity:UserIdentity) : Promise<Session>{\n const ret = await this.sessionServices.createSession();\n this.sessionServices = this.sessionServices.recreate(ret.authToken)\n\n const session = new Session(ret.sessionId, ret.authToken, ret.endpoint, this.sessionServices);\n\n // Enforce user-token type restrictions from the client security configuration\n // before activating; the endpoint is now known from CreateSession.\n this.validateUserTokenPolicy(identity, ret.endpoint)\n\n await session.activateSession(identity);\n return session;\n }\n\n /**\n * Attempts to reactivate an existing OPC UA session on the current (new) SecureChannel\n * without calling CreateSession first (OPC UA Part 4, Section 5.7.3).\n *\n * This is the preferred recovery path when the SecureChannel drops but the server-side\n * session has not yet timed out: only a new channel is needed, not a new session.\n *\n * @returns The reactivated Session if ActivateSession succeeded, or `null` if the server\n * rejected the request (e.g. the session had already expired).\n */\n async tryActivateExistingSession(\n existingAuthToken: NodeId,\n existingSessionId: number,\n existingEndpoint: EndpointDescription,\n identity: UserIdentity,\n ): Promise<Session | null> {\n // Build a SessionService bound to the existing auth token so the RequestHeader\n // carries it and the server can correlate the ActivateSession to the right session.\n const serviceForExistingSession = this.sessionServices.recreate(existingAuthToken)\n try {\n const session = new Session(existingSessionId, existingAuthToken, existingEndpoint, serviceForExistingSession)\n await session.activateSession(identity)\n return session\n } catch (err) {\n this.logger.debug('ActivateSession for existing session failed:', err)\n return null\n }\n }\n\n /**\n * Closes the active session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - Forwarded to CloseSessionRequest. Defaults to true.\n */\n async closeSession(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n /**\n * Validates the requested user-identity token type against:\n * 1. The `allowedUserTokenTypes` from the client security configuration — the\n * client has explicitly restricted which token types it will use.\n * 2. The token policies advertised by the server endpoint — verifies that the\n * server actually supports at least one of the allowed types.\n *\n * Throws with a descriptive message if either check fails.\n */\n private validateUserTokenPolicy(identity: UserIdentity, endpoint: EndpointDescription): void {\n const allowedTypes = this.configuration.securityConfiguration?.allowedUserTokenTypes\n if (!allowedTypes) return // no restriction configured\n\n const requestedType = identity.getTokenType()\n\n // 1. Client-side restriction: the chosen identity must be an allowed type.\n if (!allowedTypes.includes(requestedType)) {\n throw new Error(\n `User token type '${UserTokenTypeEnum[requestedType]}' is not permitted by the ` +\n `client security configuration. Allowed types: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n\n // 2. Server-side availability: at least one allowed type must be offered.\n const serverTypes = endpoint.userIdentityTokens?.map(p => p.tokenType) ?? []\n const intersection = allowedTypes.filter(t => serverTypes.includes(t))\n if (intersection.length === 0) {\n throw new Error(\n `Server endpoint does not offer any user token type from the allowed list: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}. ` +\n `Server offers: ${serverTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n }\n\n constructor(secureChannel:ISecureChannel, private configuration: ConfigurationClient) {\n this.sessionServices = new SessionService(NodeId.newTwoByte(0), secureChannel, configuration);\n }\n}","import type { MessageSecurityModeEnum, UserTokenTypeEnum } from 'opcjs-base'\n\n/** URI for the SecurityPolicy None profile. */\nexport const SECURITY_POLICY_NONE_URI = 'http://opcfoundation.org/UA/SecurityPolicy#None'\n\n/**\n * How the client should handle a server certificate it cannot verify.\n *\n * - `'reject'` — abort the connection (secure default when `trustedCAs` is configured).\n * - `'trust'` — accept any certificate without verification (development convenience;\n * **insecure in production**).\n *\n * @note Enforcement is deferred until certificate-based security policies are\n * implemented. The value is stored and will be honoured when that support lands.\n */\nexport type UnknownCertificatePolicy = 'reject' | 'trust'\n\n/**\n * OPC UA client security configuration (OPC UA Part 2, Security Administration CU).\n *\n * Restricts which security options the client will accept when connecting to or\n * negotiating with a server. All fields are optional; omitting a field applies\n * the permissive default so that existing callers need no changes.\n *\n * @example\n * ```ts\n * const config = ConfigurationClient.getSimple('MyApp', 'MyCompany')\n * config.securityConfiguration = {\n * allowedUserTokenTypes: [UserTokenTypeEnum.UserName],\n * allowSecurityPolicyNone: false, // require an encrypted channel\n * }\n * ```\n */\nexport type SecurityConfiguration = {\n /**\n * User-identity-token types the client is willing to accept.\n *\n * When set, `connect()` will throw if:\n * - The supplied `UserIdentity`'s token type is not in this list, OR\n * - The server endpoint does not offer any type from this list.\n *\n * Default: all token types are accepted (no restriction).\n */\n allowedUserTokenTypes?: UserTokenTypeEnum[]\n\n /**\n * Allow connecting when the negotiated SecurityPolicy is `None` (unencrypted,\n * unsigned channel).\n *\n * Set to `false` to require a secure channel — `connect()` will throw rather\n * than establish a cleartext connection.\n *\n * Currently the only supported security policy is `None`. Setting this to `false`\n * will therefore cause `connect()` to always throw until non-None policies are\n * added to this client implementation.\n *\n * Default: `true` (SecurityPolicy None is permitted).\n */\n allowSecurityPolicyNone?: boolean\n\n /**\n * Required `MessageSecurityMode` for the secure channel.\n *\n * When set, `connect()` verifies that the channel's negotiated mode matches\n * this value and throws otherwise.\n *\n * Currently only `MessageSecurityModeEnum.None` is supported.\n *\n * Default: no requirement (any mode is accepted).\n */\n messageSecurityMode?: MessageSecurityModeEnum\n\n /**\n * DER-encoded X.509 trusted CA certificates used to verify the server's\n * application instance certificate.\n *\n * @note Reserved for future use. Certificate verification is not yet implemented.\n * Providing this field has no effect until non-None security policies land.\n */\n trustedCAs?: Uint8Array[]\n\n /**\n * How to handle a server certificate that cannot be verified against `trustedCAs`.\n *\n * - `'reject'` — refuse the connection (default when `trustedCAs` is provided).\n * - `'trust'` — accept any certificate (development only; insecure in production).\n *\n * @note Reserved for future use. Has no effect until certificate verification is\n * implemented alongside non-None security policies.\n */\n unknownCertificatePolicy?: UnknownCertificatePolicy\n}\n","// according to https://reference.opcfoundation.org/Core/Part6/v105/docs/A.1\n// see also: https://reference.opcfoundation.org/Core/Part4/v105/docs/7.24.1#Table154\n\nexport const AttrIdNodeId = 1\nexport const AttrIdNodeClass = 2\nexport const AttrIdBrowseName = 3\nexport const AttrIdDisplayName = 4\nexport const AttrIdDescription = 5\nexport const AttrIdWriteMask = 6\nexport const AttrIdUserWriteMask = 7\nexport const AttrIdIsAbstract = 8\nexport const AttrIdSymmetric = 9\nexport const AttrIdInverseName = 10\nexport const AttrIdContainsNoLoops = 11\nexport const AttrIdEventNotifier = 12\nexport const AttrIdValue = 13\nexport const AttrIdDataType = 14\nexport const AttrIdValueRank = 15\nexport const AttrIdArrayDimensions = 16\nexport const AttrIdAccessLevel = 17\nexport const AttrIdUserAccessLevel = 18\nexport const AttrIdMinimumSamplingInterval = 19\nexport const AttrIdHistorizing = 20\nexport const AttrIdExecutable = 21\nexport const AttrIdUserExecutable = 22\nexport const AttrIdDataTypeDefinition = 23\nexport const AttrIdRolePermissions = 24\nexport const AttrIdUserRolePermissions = 25\nexport const AttrIdAccessRestrictions = 26\nexport const AttrIdAccessLevelEx = 27\n","import {\n getLogger, ISecureChannel, NodeId, QualifiedName, ReadRequest, ReadResponse, ReadValueId,\n StatusCode, TimestampsToReturnEnum,\n} from 'opcjs-base'\n\nimport { AttrIdValue } from './attributeServiceAttributes.js'\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.10.2\nexport class AttributeService extends ServiceBase {\n private logger = getLogger(\"services.AttributeService\");\n\n /**\n * Reads the Value attribute of one or more Nodes (OPC UA Part 4, Section 5.10.2).\n * @param nodeIds - NodeIds of the Nodes to read.\n * @param maxAge - Maximum age of the cached value in milliseconds the server may return. 0 = always current value.\n * @param timestampsToReturn - Which timestamps to include in results. Default: Source.\n * @returns Array of results containing value and raw status code number, one per requested NodeId.\n */\n async ReadValue(\n nodeIds: NodeId[],\n maxAge: number = 0,\n timestampsToReturn: TimestampsToReturnEnum = TimestampsToReturnEnum.Source,\n ): Promise<{ statusCode: number, value: unknown }[]> {\n const readValueIds = nodeIds.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n return readValueId;\n });\n\n const request = new ReadRequest();\n request.requestHeader = this.createRequestHeader();\n request.maxAge = maxAge;\n request.timestampsToReturn = timestampsToReturn;\n request.nodesToRead = readValueIds;\n\n this.logger.debug(\"Sending ReadRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as ReadResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'ReadRequest')\n\n const results = new Array<{ statusCode: number, value: unknown }>();\n for (const dataValue of response.results ?? []) {\n results.push({\n statusCode: dataValue.statusCode ?? StatusCode.Good,\n value: dataValue.value as unknown,\n });\n }\n return results;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","export class ReadValueResult {\n constructor(public value: unknown, public statusCode: number) {}\n}","import { NodeId } from \"opcjs-base\";\n\nexport class SubscriptionHandlerEntry{\n constructor(\n public subscriptionId:number,\n public handle: number, \n public id:NodeId, \n public callback: (data: { id: NodeId, value: unknown }[]) => void\n ){}\n}","import {\n DataChangeNotification,\n ExpandedNodeId,\n getLogger,\n NodeId,\n StatusChangeNotification,\n SubscriptionAcknowledgement,\n} from 'opcjs-base'\n\nimport { MonitoredItemService } from './services/monitoredItemService'\nimport { SubscriptionService } from './services/subscriptionService'\nimport { SubscriptionHandlerEntry } from './subscriptionHandlerEntry'\n\n// OPC UA Part 4, §5.14 — Subscriptions and Monitored Items\n\n/** Node type IDs for notification payloads (OPC UA Part 4, §7.21) */\nconst NODE_ID_DATA_CHANGE_NOTIFICATION = 811\nconst NODE_ID_STATUS_CHANGE_NOTIFICATION = 818\n\nexport class SubscriptionHandler {\n private logger = getLogger('SubscriptionHandler')\n private entries = new Array<SubscriptionHandlerEntry>()\n private nextHandle = 0\n private isRunning = false\n\n /** Returns true when at least one subscription is active and the publish loop is running. */\n hasActiveSubscription(): boolean {\n return this.isRunning && this.entries.length > 0\n }\n\n async subscribe(ids: NodeId[], callback: (data: { id: NodeId; value: unknown }[]) => void) {\n if (this.entries.length > 0) {\n throw new Error('Subscribing more than once is not implemented')\n }\n\n const subscriptionId = await this.subscriptionService.createSubscription()\n const items = []\n for (const id of ids) {\n const entry = new SubscriptionHandlerEntry(subscriptionId, this.nextHandle++, id, callback)\n this.entries.push(entry)\n items.push({ id, handle: entry.handle })\n }\n await this.monitoredItemService.createMonitoredItems(subscriptionId, items)\n\n // Start the publish loop with no pending acknowledgements.\n this.isRunning = true\n void this.publishLoop([])\n }\n\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n private async publishLoop(pendingAcknowledgements: SubscriptionAcknowledgement[]): Promise<void> {\n if (!this.isRunning) return\n\n let response\n try {\n response = await this.subscriptionService.publish(pendingAcknowledgements)\n } catch (err) {\n this.logger.error(`Publish failed, stopping publish loop: ${err}`)\n this.isRunning = false\n return\n }\n\n const { subscriptionId, availableSequenceNumbers, moreNotifications, notificationMessage } = response\n const notificationDatas = notificationMessage?.notificationData ?? []\n const seqNumber = notificationMessage?.sequenceNumber\n\n // Build acknowledgements for the next publish request.\n // Per spec: only acknowledge sequence numbers that are in availableSequenceNumbers\n // and only for real notification messages (not keep-alive, which have empty notificationData).\n const nextAcknowledgements: SubscriptionAcknowledgement[] = []\n const isKeepAlive = notificationDatas.length === 0\n\n if (!isKeepAlive && seqNumber !== undefined) {\n // Acknowledge only if the server still lists this sequence number as available.\n const isAvailable = !availableSequenceNumbers || availableSequenceNumbers.includes(seqNumber)\n if (isAvailable) {\n const ack = new SubscriptionAcknowledgement()\n ack.subscriptionId = subscriptionId\n ack.sequenceNumber = seqNumber\n nextAcknowledgements.push(ack)\n }\n }\n\n // Dispatch notifications to registered callbacks.\n for (const notificationData of notificationDatas) {\n const decodedData = notificationData.data\n const rawTypeId = notificationData.typeId\n const typeNodeId = rawTypeId instanceof ExpandedNodeId ? rawTypeId.nodeId : rawTypeId\n\n if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_DATA_CHANGE_NOTIFICATION) {\n const dataChangeNotification = decodedData as DataChangeNotification\n for (const item of dataChangeNotification.monitoredItems) {\n const entry = this.entries.find(e => e.handle === item.clientHandle)\n entry?.callback([{ id: entry.id, value: item.value.value?.value }])\n }\n } else if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_STATUS_CHANGE_NOTIFICATION) {\n // The server notifies us the subscription state has changed (e.g. expired, closed).\n const statusChange = decodedData as StatusChangeNotification\n this.logger.warn(\n `Subscription ${subscriptionId} status changed: 0x${statusChange.status?.toString(16).toUpperCase()}`,\n )\n this.isRunning = false\n return\n } else {\n this.logger.warn(\n `Notification data type ${typeNodeId.namespace}:${typeNodeId.identifier} is not supported.`,\n )\n }\n }\n\n // Per spec: if moreNotifications is true the server has more queued data — re-publish immediately\n // without delay so the server's queue drains before its lifetime counter expires.\n // Otherwise, schedule the next publish after a short yield to avoid a tight synchronous loop.\n if (moreNotifications) {\n void this.publishLoop(nextAcknowledgements)\n } else {\n setTimeout(() => void this.publishLoop(nextAcknowledgements), 0)\n }\n }\n\n constructor(\n private subscriptionService: SubscriptionService,\n private monitoredItemService: MonitoredItemService,\n ) {}\n}","import {\n CreateSubscriptionRequest, CreateSubscriptionResponse, getLogger, ISecureChannel, NodeId,\n PublishRequest, PublishResponse, StatusCode, StatusCodeToString, SubscriptionAcknowledgement,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\n/** Options for creating a subscription. All fields are optional; server will revise requested values. */\nexport interface CreateSubscriptionOptions {\n /** Requested publishing interval in milliseconds. Default: 2000. */\n requestedPublishingInterval?: number;\n /** Requested lifetime count (number of publishing intervals before subscription times out). Default: 360000. */\n requestedLifetimeCount?: number;\n /** Requested max keep-alive count. Default: 60000. */\n requestedMaxKeepAliveCount?: number;\n /** Maximum number of notifications per publish response. 0 = no limit. Default: 200. */\n maxNotificationsPerPublish?: number;\n /** Subscription priority relative to other subscriptions. Default: 1. */\n priority?: number;\n}\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14\nexport class SubscriptionService extends ServiceBase {\n private logger = getLogger(\"services.SubscriptionService\");\n\n /**\n * Creates a new subscription on the server (OPC UA Part 4, Section 5.14.2).\n * @param options - Optional subscription parameters; server revises all values.\n * @returns The server-assigned subscription ID.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.2\n async createSubscription(options?: CreateSubscriptionOptions): Promise<number> {\n const request = new CreateSubscriptionRequest();\n request.requestHeader = this.createRequestHeader();\n request.requestedPublishingInterval = options?.requestedPublishingInterval ?? 2000;\n request.requestedLifetimeCount = options?.requestedLifetimeCount ?? 360000;\n request.requestedMaxKeepAliveCount = options?.requestedMaxKeepAliveCount ?? 60000;\n request.maxNotificationsPerPublish = options?.maxNotificationsPerPublish ?? 200;\n request.publishingEnabled = true;\n request.priority = options?.priority ?? 1;\n\n this.logger.debug(\"Sending CreateSubscriptionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateSubscriptionResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSubscriptionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(`Subscription created with id: ${response.subscriptionId}`);\n return response.subscriptionId;\n }\n\n /**\n * Sends a publish request to receive notifications from active subscriptions (OPC UA Part 4, Section 5.14.5).\n * @param acknowledgements - Sequence numbers to acknowledge from previous publish responses.\n * @returns The publish response containing notification data.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n async publish(acknowledgements: SubscriptionAcknowledgement[]): Promise<PublishResponse> {\n const request = new PublishRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionAcknowledgements = acknowledgements;\n\n this.logger.debug(\"Sending PublishRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as PublishResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`PublishRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(\"Received PublishResponse.\");\n return response;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import {\n CreateMonitoredItemsRequest, CreateMonitoredItemsResponse,\n ExtensionObject, getLogger, ISecureChannel, MonitoredItemCreateRequest, MonitoringModeEnum,\n MonitoringParameters, NodeId, QualifiedName, ReadValueId, StatusCode, StatusCodeToString,\n TimestampsToReturnEnum,\n} from \"opcjs-base\";\nimport { AttrIdValue } from \"./attributeServiceAttributes\";\nimport { ServiceBase } from \"./serviceBase\";\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.13.2\nexport class MonitoredItemService extends ServiceBase {\n private logger = getLogger(\"services.MonitoredItemService\");\n\n /**\n * Creates monitored items within a subscription (OPC UA Part 4, Section 5.13.2).\n * @param subscriptionId - ID of the subscription to add monitored items to.\n * @param ids - Array of NodeIds and client handles identifying the items to monitor.\n * @param samplingInterval - Requested sampling interval in milliseconds. -1 = use subscription publishing interval.\n * @param queueSize - Requested queue size for each monitored item.\n */\n async createMonitoredItems(\n subscriptionId: number,\n ids: { id: NodeId, handle: number }[],\n samplingInterval: number = 1000,\n queueSize: number = 100,\n ): Promise<void> {\n const items = ids.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni.id;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n\n const monitoringParameters = new MonitoringParameters();\n monitoringParameters.clientHandle = ni.handle;\n monitoringParameters.samplingInterval = samplingInterval;\n monitoringParameters.filter = ExtensionObject.newEmpty();\n monitoringParameters.queueSize = queueSize;\n monitoringParameters.discardOldest = true;\n\n const monitoredItemCreateRequest = new MonitoredItemCreateRequest();\n monitoredItemCreateRequest.itemToMonitor = readValueId;\n monitoredItemCreateRequest.monitoringMode = MonitoringModeEnum.Reporting;\n monitoredItemCreateRequest.requestedParameters = monitoringParameters;\n return monitoredItemCreateRequest;\n });\n\n const request = new CreateMonitoredItemsRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionId = subscriptionId;\n request.timestampsToReturn = TimestampsToReturnEnum.Source;\n request.itemsToCreate = items;\n\n this.logger.debug(\"Sending CreateMonitoredItemsRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateMonitoredItemsResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateMonitoredItemsRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n for (const result of response.results ?? []) {\n if (result.statusCode !== undefined && result.statusCode !== StatusCode.Good) {\n this.logger.warn(`Failed to create monitored item: ${StatusCodeToString(result.statusCode)}`);\n }\n }\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import { CallMethodRequest, CallRequest, CallResponse, getLogger, ISecureChannel, NodeId, StatusCode } from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.11.2\nexport class MethodService extends ServiceBase {\n private logger = getLogger(\"services.MethodService\");\n\n /**\n * Calls one or more methods on the server (OPC UA Part 4, Section 5.11.2).\n * @param methodsToCall - Array of CallMethodRequest describing each method to invoke.\n * @returns Array of results containing output argument values and raw status code number, one per requested method.\n */\n async call(methodsToCall: CallMethodRequest[]): Promise<{ statusCode: number, value: unknown[] }[]> {\n const request = new CallRequest();\n request.requestHeader = this.createRequestHeader();\n request.methodsToCall = methodsToCall;\n\n this.logger.debug(\"Sending CallRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CallResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'CallRequest')\n\n return response.results.map(result => ({\n statusCode: result.statusCode ?? StatusCode.Good,\n value: result.outputArguments.map(arg => arg.value),\n }));\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","export class CallMethodResult {\n constructor(public values: unknown[], public statusCode: number) {}\n}","import {\n BrowseDescription, BrowseNextRequest, BrowseNextResponse,\n BrowseRequest, BrowseResponse, BrowseResult,\n getLogger, ISecureChannel, NodeId, UaByteString, ViewDescription,\n} from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.9\nexport class BrowseService extends ServiceBase {\n private logger = getLogger(\"services.BrowseService\");\n\n /**\n * Browses one or more Nodes and returns their References (OPC UA Part 4, Section 5.9.2).\n * @param nodesToBrowse - Array of BrowseDescriptions specifying nodes and filter criteria.\n * @returns Array of BrowseResult, one per requested node.\n */\n async browse(nodesToBrowse: BrowseDescription[]): Promise<BrowseResult[]> {\n const view = new ViewDescription();\n view.viewId = NodeId.newNumeric(0, 0);\n view.timestamp = new Date(-11644473600000); // OPC UA MinDateTime (ticks=0)\n view.viewVersion = 0;\n\n const request = new BrowseRequest();\n request.requestHeader = this.createRequestHeader();\n request.view = view;\n request.requestedMaxReferencesPerNode = 0;\n request.nodesToBrowse = nodesToBrowse;\n\n this.logger.debug(\"Sending BrowseRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseRequest')\n\n return response.results ?? []\n }\n\n /**\n * Continues a Browse operation using continuation points (OPC UA Part 4, Section 5.9.3).\n * @param continuationPoints - Continuation points returned by a prior Browse or BrowseNext call.\n * @param releaseContinuationPoints - If true, releases the continuation points without returning results.\n * @returns Array of BrowseResult, one per continuation point.\n */\n async browseNext(\n continuationPoints: UaByteString[],\n releaseContinuationPoints: boolean,\n ): Promise<BrowseResult[]> {\n const request = new BrowseNextRequest();\n request.requestHeader = this.createRequestHeader();\n request.releaseContinuationPoints = releaseContinuationPoints;\n request.continuationPoints = continuationPoints;\n\n this.logger.debug(\"Sending BrowseNextRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseNextResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseNextRequest')\n\n return response.results ?? []\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","import {\n ExpandedNodeId, LocalizedText, NodeClassEnum,\n NodeId, QualifiedName\n} from \"opcjs-base\";\n\nexport class BrowseNodeResult {\n constructor(\n public referenceTypeId: NodeId,\n public isForward: boolean,\n public nodeId: ExpandedNodeId,\n public browseName: QualifiedName,\n public displayName: LocalizedText,\n public nodeClass: NodeClassEnum,\n public typeDefinition: ExpandedNodeId,\n ) {}\n}\n","import {\n NodeId,\n ISecureChannel,\n TcpConnectionHandler,\n SecureChannelFacade,\n SecureChannelContext,\n SecureChannelMessageEncoder,\n SecureChannelTypeDecoder,\n SecureChannelMessageDecoder,\n SecureChannelTypeEncoder,\n initLoggerProvider,\n TcpMessageInjector,\n TcpMessageDecoupler,\n getLogger,\n WebSocketFascade,\n WebSocketReadableStream,\n WebSocketWritableStream,\n SecureChannelChunkReader,\n SecureChannelChunkWriter,\n CallMethodRequest,\n Variant,\n BrowseDescription,\n BrowseDirectionEnum,\n BrowseResultMaskEnum,\n ReferenceDescription,\n ILogger,\n} from 'opcjs-base'\n\nimport { SessionHandler } from './sessions/sessionHandler.js'\nimport { Session } from './sessions/session.js'\nimport { SessionInvalidError } from './sessions/sessionInvalidError.js'\nimport { SECURITY_POLICY_NONE_URI } from './securityConfiguration.js'\nimport { AttributeService } from './services/attributeService.js'\nimport { ReadValueResult } from './readValueResult.js'\nimport { SubscriptionHandler } from './subscriptionHandler.js'\nimport { SubscriptionService } from './services/subscriptionService.js'\nimport { MonitoredItemService } from './services/monitoredItemService.js'\nimport { UserIdentity } from './userIdentity.js'\nimport { ConfigurationClient } from './configurationClient.js'\nimport { MethodService } from './services/methodService.js'\nimport { CallMethodResult } from './callMethodResult.js'\nimport { BrowseService } from './services/browseService.js'\nimport { BrowseNodeResult } from './browseNodeResult.js'\nimport { CallMethodArgument } from './callMethodArgument.js'\n\n/** NodeId of Server_ServerStatus (ns=0, i=2256) — a cheap server-side read used for session keep-alive. */\nconst SERVER_STATUS_NODE_ID = NodeId.newNumeric(0, 2256)\n/**\n * How often to read the server when no subscription is active (ms).\n * Must be shorter than the server's revisedSessionTimeout (default: 60 000 ms).\n */\nconst KEEP_ALIVE_INTERVAL_MS = 25_000\n\nexport class Client {\n private endpointUrl: string\n private attributeService?: AttributeService\n private methodService?: MethodService\n private browseService?: BrowseService\n private session?: Session\n private subscriptionHandler?: SubscriptionHandler\n private logger: ILogger\n // Stored after connect() so that refreshSession() and disconnect() can use them.\n private secureChannel?: ISecureChannel\n private secureChannelFacade?: SecureChannelFacade\n private ws?: WebSocketFascade\n private sessionHandler?: SessionHandler\n private keepAliveTimer?: ReturnType<typeof setInterval>\n\n getSession(): Session {\n if (!this.session) {\n throw new Error('No session available')\n }\n return this.session\n }\n\n /**\n * (Re-)initialises all session-scoped services from the current `this.session`.\n * Called both after the initial `connect()` and after a session refresh.\n */\n private initServices(): void {\n const authToken = this.session!.getAuthToken()\n const sc = this.secureChannel!\n this.attributeService = new AttributeService(authToken, sc)\n this.methodService = new MethodService(authToken, sc)\n this.browseService = new BrowseService(authToken, sc)\n this.subscriptionHandler = new SubscriptionHandler(\n new SubscriptionService(authToken, sc),\n new MonitoredItemService(authToken, sc),\n )\n }\n\n /**\n * Executes `fn` and, if it throws a `SessionInvalidError`, creates a fresh\n * session and retries the operation exactly once.\n *\n * This covers the reactive case: a service call reveals that the server has\n * already dropped the session (e.g. due to timeout). The new session is\n * established transparently before re-running the original operation.\n *\n * For any other error (e.g. transport-level failures when the SecureChannel\n * drops), this method attempts to reconnect the channel and reactivate the\n * existing session first — falling back to a brand-new session only when\n * reactivation fails — before retrying the operation once.\n */\n private async withSessionRefresh<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof SessionInvalidError) {\n this.logger.info(`Session invalid (${err.statusCode.toString(16)}), refreshing session...`)\n this.session = await this.sessionHandler!.createNewSession(this.identity)\n this.initServices()\n this.logger.info('Session refreshed, retrying operation.')\n\n // Retry once with the new session. If it fails again the error propagates.\n return await fn()\n }\n\n // Possibly a channel drop: attempt reconnect + ActivateSession on existing session\n // before giving up and creating a brand-new session (OPC UA Part 4 Session Auto Reconnect).\n this.logger.info('Service call failed, attempting channel reconnect and session reactivation...')\n try {\n await this.reconnectAndReactivate()\n this.initServices()\n this.logger.info('Reconnected successfully, retrying operation.')\n } catch (reconnectErr) {\n // Reconnect itself failed; surface the original error so the caller\n // gets a meaningful diagnostic (the reconnect error is logged separately).\n this.logger.warn('Channel reconnect failed:', reconnectErr)\n throw err\n }\n\n // Retry once after a successful reconnect. If it fails again the error propagates.\n return await fn()\n }\n }\n\n /**\n * Starts a periodic keep-alive timer that reads Server_ServerStatus when no subscription is\n * active. OPC UA Part 4, Section 5.7.1 requires clients to keep the session alive; when no\n * subscription Publish loop is running this is the only mechanism that does so.\n */\n private startKeepAlive(): void {\n this.keepAliveTimer = setInterval(() => {\n if (this.subscriptionHandler?.hasActiveSubscription()) {\n // The subscription publish loop is already keeping the session alive.\n return\n }\n if (this.attributeService) {\n void this.attributeService.ReadValue([SERVER_STATUS_NODE_ID]).catch((err) => {\n this.logger.warn('Keep-alive read failed:', err)\n })\n }\n }, KEEP_ALIVE_INTERVAL_MS)\n }\n\n private stopKeepAlive(): void {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n }\n\n async connect(): Promise<void> {\n const { ws, sc } = await this.openTransportAndChannel()\n\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n\n this.logger.debug('Creating session...')\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.debug('Session created.')\n\n this.logger.debug('Initializing services...')\n this.initServices()\n this.startKeepAlive()\n }\n\n /**\n * Builds the full WebSocket → TCP → SecureChannel pipeline and returns the\n * two objects needed to drive it: the raw WebSocket facade (for teardown)\n * and the SecureChannelFacade (for service requests/session management).\n *\n * Extracted from `connect()` so it can be reused by `reconnectAndReactivate()`.\n */\n private async openTransportAndChannel(): Promise<{ ws: WebSocketFascade; sc: SecureChannelFacade }> {\n const wsOptions = { endpoint: this.endpointUrl }\n const ws = new WebSocketFascade(wsOptions);\n const webSocketReadableStream = new WebSocketReadableStream(ws, 1000);\n const webSocketWritableStream = new WebSocketWritableStream(ws);\n\n const scContext = new SecureChannelContext(this.endpointUrl);\n const tcpMessageInjector = new TcpMessageInjector();\n const tcpConnectionHandler = new TcpConnectionHandler(tcpMessageInjector, scContext);\n const tcpMessageDecoupler = new TcpMessageDecoupler(tcpConnectionHandler.onTcpMessage.bind(tcpConnectionHandler));\n const scMessageEncoder = new SecureChannelMessageEncoder(scContext);\n const scTypeDecoder = new SecureChannelTypeDecoder(\n this.configuration.decoder,\n );\n const scMessageDecoder = new SecureChannelMessageDecoder(scContext);\n const scTypeEncoder = new SecureChannelTypeEncoder(\n this.configuration.encoder,\n );\n const scChunkWriter = new SecureChannelChunkWriter(scContext);\n const scChunkReader = new SecureChannelChunkReader(scContext);\n\n webSocketReadableStream.pipeTo(tcpMessageDecoupler.writable);\n tcpMessageDecoupler.readable.pipeTo(scMessageDecoder.writable);\n scMessageDecoder.readable.pipeTo(scChunkReader.writable);\n scChunkReader.readable.pipeTo(scTypeDecoder.writable);\n\n scTypeEncoder.readable.pipeTo(scChunkWriter.writable);\n scChunkWriter.readable.pipeTo(scMessageEncoder.writable);\n scMessageEncoder.readable.pipeTo(tcpMessageInjector.writable);\n tcpMessageInjector.readable.pipeTo(webSocketWritableStream);\n\n const sc = new SecureChannelFacade(scContext, scTypeDecoder, scTypeEncoder);\n\n let connected = false;\n while (!connected) {\n this.logger.debug(`Connecting to OPC UA server at ${this.endpointUrl}...`);\n await ws.connect();\n this.logger.debug(\"WebSocket connection established, now establishing TCP connection...\");\n connected = await tcpConnectionHandler.connect(this.endpointUrl);\n\n if (!connected) {\n this.logger.info(\"Connection failed, retrying in 2 seconds...\");\n await new Promise((resolve) => setTimeout(resolve, 2000));\n }\n }\n this.logger.info(\"Connected to OPC UA server.\");\n\n this.logger.debug(\"Opening secure channel...\");\n await sc.openSecureChannel();\n this.logger.debug(\"Secure channel established.\");\n\n // Enforce any channel-level security requirements before proceeding.\n this.enforceChannelSecurityConfig(sc);\n\n return { ws, sc };\n }\n\n /**\n * Validates the negotiated channel's security policy and mode against the\n * client's `SecurityConfiguration` (OPC UA Part 2, Security Administration).\n *\n * Throws if:\n * - `allowSecurityPolicyNone` is `false` and the channel uses SecurityPolicy None.\n * - `messageSecurityMode` is set and does not match the channel's actual mode.\n */\n private enforceChannelSecurityConfig(sc: SecureChannelFacade): void {\n const config = this.configuration.securityConfiguration\n if (!config) return\n\n const negotiatedPolicy = sc.getSecurityPolicy()\n const negotiatedMode = sc.getSecurityMode()\n\n if (config.allowSecurityPolicyNone === false && negotiatedPolicy === SECURITY_POLICY_NONE_URI) {\n throw new Error(\n 'Connection refused: SecurityPolicy None is disabled by the client security configuration. ' +\n 'Only SecurityPolicy None is currently supported by this client implementation.',\n )\n }\n\n if (config.messageSecurityMode !== undefined && config.messageSecurityMode !== negotiatedMode) {\n throw new Error(\n `Connection refused: negotiated MessageSecurityMode ${negotiatedMode} does not match ` +\n `the required mode ${config.messageSecurityMode} from the security configuration.`,\n )\n }\n }\n\n /**\n * Tears down the current (dead) channel and establishes a fresh one, then\n * attempts to recover the existing OPC UA session via ActivateSession before\n * falling back to a full CreateSession + ActivateSession.\n *\n * OPC UA Part 4, Section 5.7.1 / Session Client Auto Reconnect conformance unit:\n * When the SecureChannel drops but the server-side session has not yet timed\n * out, the client SHOULD reuse the existing session by calling ActivateSession\n * on the new channel. Only if that fails should the client create a new session.\n */\n private async reconnectAndReactivate(): Promise<void> {\n this.logger.info('Tearing down dead channel before reconnect...')\n\n // Close the old channel and WebSocket (best effort — they may already be dead).\n try { this.secureChannelFacade?.close() } catch { /* already dead */ }\n try { this.ws?.close() } catch { /* already dead */ }\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n this.ws = undefined\n\n const { ws, sc } = await this.openTransportAndChannel()\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n\n // Attempt to reactivate the existing session on the new channel.\n if (this.session) {\n const reactivated = await this.sessionHandler.tryActivateExistingSession(\n this.session.getAuthToken(),\n this.session.getSessionId(),\n this.session.getEndpoint(),\n this.identity,\n )\n if (reactivated !== null) {\n this.session = reactivated\n this.logger.info('Existing session successfully reactivated on new channel.')\n return\n }\n this.logger.info('ActivateSession for existing session failed; creating a fresh session...')\n }\n\n // Fall back: full CreateSession + ActivateSession.\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.info('Fresh session established on new channel.')\n }\n\n /**\n * Gracefully disconnects from the OPC UA server.\n *\n * Sequence per OPC UA Part 4, Section 5.7.4:\n * 1. CloseSession (deleteSubscriptions=true) so the server frees all resources.\n * 2. Close the SecureChannel, which cancels the pending token-renewal timer.\n * 3. Close the WebSocket transport.\n *\n * CloseSession errors are swallowed so transport teardown always completes even\n * when the session has already expired on the server side.\n */\n async disconnect(): Promise<void> {\n this.logger.info('Disconnecting from OPC UA server...')\n this.stopKeepAlive()\n\n if (this.session && this.sessionHandler) {\n try {\n await this.sessionHandler.closeSession(true)\n } catch (err) {\n // Session may already be gone on the server; log and continue teardown.\n this.logger.warn('CloseSession failed (continuing teardown):', err)\n }\n this.session = undefined\n }\n\n this.secureChannelFacade?.close()\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n\n this.ws?.close()\n this.ws = undefined\n\n this.logger.info('Disconnected.')\n }\n\n async read(ids: NodeId[]): Promise<ReadValueResult[]> {\n return this.withSessionRefresh(async () => {\n const result = await this.attributeService?.ReadValue(ids)\n return result?.map(r => new ReadValueResult(r.value, r.statusCode)) ?? []\n })\n }\n\n /**\n * Method for calling a single method on the server.\n * @param objectId - NodeId of the Object that owns the method.\n * @param methodId - NodeId of the Method to invoke.\n * @param inputArguments - Input argument Variants (default: empty).\n * @returns The CallMethodResult for the invoked method.\n */\n async callMethod(\n objectId: NodeId,\n methodId: NodeId,\n inputArguments: CallMethodArgument[] = []\n ): Promise<CallMethodResult> {\n return this.withSessionRefresh(async () => {\n const request = new CallMethodRequest()\n request.objectId = objectId\n request.methodId = methodId\n request.inputArguments = inputArguments.map(arg => Variant.newFrom(arg))\n\n const responses = await this.methodService!.call([request])\n const response = responses[0]\n return new CallMethodResult(response.value, response.statusCode)\n })\n }\n\n async browse(\n nodeId: NodeId,\n recursive: boolean = false,\n ): Promise<BrowseNodeResult[]> {\n return this.withSessionRefresh(() => {\n const visited = new Set<string>()\n return this.browseRecursive(nodeId, recursive, visited)\n })\n }\n\n private async browseRecursive(\n nodeId: NodeId,\n recursive: boolean,\n visited: Set<string>,\n ): Promise<BrowseNodeResult[]> {\n const nodeKey = `${nodeId.namespace}:${nodeId.identifier}`;\n if (visited.has(nodeKey)) {\n return [];\n }\n visited.add(nodeKey);\n\n const description = new BrowseDescription();\n description.nodeId = nodeId;\n description.browseDirection = BrowseDirectionEnum.Forward;\n description.referenceTypeId = NodeId.newNumeric(0, 33); // HierarchicalReferences\n description.includeSubtypes = true;\n description.nodeClassMask = 0; // all node classes\n description.resultMask = BrowseResultMaskEnum.All;\n\n const browseResults = await this.browseService!.browse([description]);\n const browseResult = browseResults[0];\n const allReferences = [...(browseResult.references ?? [])];\n\n let continuationPoint = browseResult.continuationPoint;\n while (continuationPoint && continuationPoint.byteLength > 0) {\n const nextResults = await this.browseService!\n .browseNext([continuationPoint], false);\n const nextResult = nextResults[0];\n allReferences.push(...(nextResult.references ?? []));\n continuationPoint = nextResult.continuationPoint;\n }\n\n const results = allReferences.map((ref: ReferenceDescription) =>\n new BrowseNodeResult(\n ref.referenceTypeId,\n ref.isForward,\n ref.nodeId,\n ref.browseName,\n ref.displayName,\n ref.nodeClass,\n ref.typeDefinition,\n )\n );\n\n if (recursive) {\n for (const ref of allReferences) {\n const childNodeId = NodeId.newNumeric(\n ref.nodeId.nodeId.namespace,\n ref.nodeId.nodeId.identifier as number,\n );\n const childResults = await this.browseRecursive(\n childNodeId, true, visited,\n );\n results.push(...childResults);\n }\n }\n\n return results;\n }\n\n async subscribe(\n ids: NodeId[],\n callback: (data: { id: NodeId; value: unknown }[]) => void,\n ) {\n this.subscriptionHandler?.subscribe(ids, callback);\n }\n\n constructor(\n endpointUrl: string,\n private configuration: ConfigurationClient,\n private identity: UserIdentity,\n ) {\n this.endpointUrl = endpointUrl;\n initLoggerProvider(configuration.loggerFactory);\n this.logger = getLogger(\"Client\");\n }\n}\n","import {\n BinaryReader,\n BinaryWriter,\n Configuration,\n Decoder,\n Encoder,\n ILoggerFactory,\n LoggerFactory,\n registerBinaryDecoders,\n registerEncoders,\n registerTypeDecoders\n} from \"opcjs-base\";\n\nimport type { SecurityConfiguration } from './securityConfiguration.js'\n\nexport class ConfigurationClient extends Configuration {\n /**\n * Optional security restrictions applied during `Client.connect()`.\n * When not set, permissive defaults are used (SecurityPolicy None allowed,\n * all user-token types accepted).\n *\n * @see SecurityConfiguration\n */\n public securityConfiguration?: SecurityConfiguration\n public static getSimple(\n name: string,\n company: string,\n loggerFactory?: ILoggerFactory,\n ): ConfigurationClient {\n\n if (!loggerFactory) {\n loggerFactory = new LoggerFactory({\n defaultLevel: 'DEBUG', //todo: use enum\n categoryLevels: {\n \"transport.*\": \"TRACE\",\n \"secureChannel.*\": \"TRACE\",\n },\n });\n }\n const applicationUri = `urn:${company}:${name}`;\n const productUri = `urn:${company}:${name}:product`;\n\n const encoder = new Encoder();\n encoder.registerWriterFactory(\"binary\", () => {\n return new BinaryWriter();\n });\n registerEncoders(encoder);\n\n const decoder = new Decoder();\n decoder.registerReaderFactory(\"binary\", (data: unknown) => {\n return new BinaryReader(data as Uint8Array);\n });\n registerTypeDecoders(decoder);\n registerBinaryDecoders(decoder);\n\n return new ConfigurationClient(\n name,\n applicationUri,\n name,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n\n constructor(\n applicationName: string,\n applicationUri: string,\n productName: string,\n productUri: string,\n encoder: Encoder,\n decoder: Decoder,\n loggerFactory: ILoggerFactory,\n ) {\n super(\n applicationName,\n applicationUri,\n productName,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n}\n","import { IssuedIdentityToken, UserIdentityToken, UserNameIdentityToken, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"./issuerConfiguration\";\nimport { IssuerToken } from \"./issuerToken\";\nimport { AnonymousIdentityToken } from \"opcjs-base\";\n\nexport class UserIdentity {\n private userIdentityToken?: UserIdentityToken;\n private tokenType = UserTokenTypeEnum.Anonymous;\n private issuerLoginCallback: ((config:IssuerConfiguration)=>Promise<IssuerToken>) | undefined = undefined;\n\n public static newAnonymous(): UserIdentity {\n const userIdentity = new UserIdentity();\n userIdentity.userIdentityToken = new AnonymousIdentityToken();\n userIdentity.userIdentityToken.policyId = \"anonymous\";\n userIdentity.tokenType = UserTokenTypeEnum.Anonymous;\n return userIdentity;\n }\n \n public static newWithUserName(userName: string, password: string): UserIdentity {\n const userIdentity = new UserIdentity();\n const nameToken = new UserNameIdentityToken();\n nameToken.userName = userName;\n nameToken.password = new TextEncoder().encode(password);\n\n userIdentity.userIdentityToken = nameToken;\n userIdentity.tokenType = UserTokenTypeEnum.UserName;\n return userIdentity;\n }\n\n public static newWithIssuerToken(loginCallback: (config:IssuerConfiguration)=>Promise<IssuerToken>): UserIdentity {\n const userIdentity = new UserIdentity();\n const issuedToken = new IssuedIdentityToken();\n issuedToken.tokenData = new TextEncoder().encode(\"\"); // token data will be filled by the login callback \n userIdentity.userIdentityToken = issuedToken;\n userIdentity.tokenType = UserTokenTypeEnum.IssuedToken;\n userIdentity.issuerLoginCallback = loginCallback;\n return userIdentity;\n }\n\n public getUserIdentityToken(): UserIdentityToken {\n return this.userIdentityToken as UserIdentityToken;\n }\n\n public getTokenType(): UserTokenTypeEnum {\n return this.tokenType;\n }\n\n public getIssuerLoginCallback(): ((config:IssuerConfiguration)=>Promise<IssuerToken>) {\n if(!this.issuerLoginCallback){\n throw new Error(\"No issuer login callback defined\");\n }\n \n return this.issuerLoginCallback;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/sessions/sessionInvalidError.ts","../src/services/serviceBase.ts","../src/services/sessionService.ts","../src/issuerConfiguration.ts","../src/sessions/session.ts","../src/sessions/sessionHandler.ts","../src/securityConfiguration.ts","../src/services/attributeServiceAttributes.ts","../src/services/attributeService.ts","../src/readValueResult.ts","../src/subscriptionHandlerEntry.ts","../src/subscriptionHandler.ts","../src/services/subscriptionService.ts","../src/services/monitoredItemService.ts","../src/services/methodService.ts","../src/callMethodResult.ts","../src/services/browseService.ts","../src/browseNodeResult.ts","../src/client.ts","../src/configurationClient.ts","../src/userIdentity.ts"],"names":["StatusCodeToString","StatusCode","StatusCodeToStringNumber","RequestHeader","ExtensionObject","getLogger","ApplicationDescription","LocalizedText","ApplicationTypeEnum","CreateSessionRequest","CreateSessionResponse","SignatureData","ActivateSessionRequest","CloseSessionRequest","UserTokenTypeEnum","NodeId","TimestampsToReturnEnum","ReadValueId","QualifiedName","ReadRequest","SubscriptionAcknowledgement","ExpandedNodeId","CreateSubscriptionRequest","PublishRequest","MonitoringParameters","MonitoredItemCreateRequest","MonitoringModeEnum","CreateMonitoredItemsRequest","CallRequest","ViewDescription","BrowseRequest","BrowseNextRequest","initLoggerProvider","WebSocketFascade","WebSocketReadableStream","WebSocketWritableStream","SecureChannelContext","TcpMessageInjector","TcpConnectionHandler","TcpMessageDecoupler","SecureChannelMessageEncoder","SecureChannelTypeDecoder","SecureChannelMessageDecoder","SecureChannelTypeEncoder","SecureChannelChunkWriter","SecureChannelChunkReader","SecureChannelFacade","CallMethodRequest","Variant","BrowseDescription","BrowseDirectionEnum","BrowseResultMaskEnum","Configuration","LoggerFactory","Encoder","BinaryWriter","registerEncoders","Decoder","BinaryReader","registerTypeDecoders","registerBinaryDecoders","AnonymousIdentityToken","UserNameIdentityToken","IssuedIdentityToken"],"mappings":";;;;;AAaO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EACpC,UAAA;AAAA,EAET,YAAY,UAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,CAAA,4BAAA,EAA+BA,4BAAA,CAAmB,UAAU,CAAC,CAAA,IAAA,EAAO,UAAA,CAAW,QAAA,CAAS,EAAE,CAAA,CAAE,WAAA,EAAa,CAAA,CAAA,CAAG,CAAA;AAClH,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAAA,EACpB;AACF;;;ACjBO,IAAe,cAAf,MAA2B;AAAA,EAmC9B,WAAA,CAAoB,WAA6B,aAAA,EAA8B;AAA3D,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAA6B,IAAA,IAAA,CAAA,aAAA,GAAA,aAAA;AAAA,EAA+B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAvBtE,kBAAA,CAAmB,QAA4B,OAAA,EAAuB;AAC5E,IAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAWC,oBAAA,CAAW,IAAA,EAAM;AAExD,IAAA,IAAI,MAAA,KAAWA,oBAAA,CAAW,mBAAA,IAAuB,MAAA,KAAWA,qBAAW,gBAAA,EAAkB;AACrF,MAAA,MAAM,IAAI,oBAAoB,MAAM,CAAA;AAAA,IACxC;AAEA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA,SAAA,EAAYD,4BAAAA,CAAmB,MAAM,CAAC,CAAA,EAAA,EAAKE,kCA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AA,EAAY,CAAE,OAAO,QAAQ,CAAA;AAEtD,IAAA,YAAA,CAAa,iBAAA,GAAoB,SAAA;AACjC,IAAA,YAAA,CAAa,YAAYhD,2BAAAA,CAAkB,QAAA;AAC3C,IAAA,OAAO,YAAA;AAAA,EACX;AAAA,EAEA,OAAc,mBAAmB,aAAA,EAAiF;AAC9G,IAAA,MAAM,YAAA,GAAe,IAAI,aAAA,EAAa;AACtC,IAAA,MAAM,WAAA,GAAc,IAAIiD,6BAAAA,EAAoB;AAC5C,IAAA,WAAA,CAAY,SAAA,GAAY,IAAI,WAAA,EAAY,CAAE,OAAO,EAAE,CAAA;AACnD,IAAA,YAAA,CAAa,iBAAA,GAAoB,WAAA;AACjC,IAAA,YAAA,CAAa,YAAYjD,2BAAAA,CAAkB,WAAA;AAC3C,IAAA,YAAA,CAAa,mBAAA,GAAsB,aAAA;AACnC,IAAA,OAAO,YAAA;AAAA,EACX;AAAA,EAEO,oBAAA,GAA0C;AAC7C,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EAChB;AAAA,EAEO,YAAA,GAAkC;AACrC,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EAChB;AAAA,EAEO,sBAAA,GAA+E;AAClF,IAAA,IAAG,CAAC,KAAK,mBAAA,EAAoB;AACzB,MAAA,MAAM,IAAI,MAAM,kCAAkC,CAAA;AAAA,IACtD;AAEA,IAAA,OAAO,IAAA,CAAK,mBAAA;AAAA,EAChB;AACJ","file":"index.cjs","sourcesContent":["import { StatusCodeToString } from 'opcjs-base'\n\n/**\n * Thrown when the server signals that the current Session is no longer valid.\n *\n * Callers that want to react to a dropped session (e.g. by creating a new one\n * and retrying the operation) should catch this specific error type instead of\n * the generic `Error` class.\n *\n * Relevant OPC UA status codes:\n * - `BadSessionIdInvalid` (0x80250000) – session no longer exists on the server\n * - `BadSessionClosed` (0x80260000) – session was closed explicitly\n */\nexport class SessionInvalidError extends Error {\n readonly statusCode: number\n\n constructor(statusCode: number) {\n super(`Session is no longer valid: ${StatusCodeToString(statusCode)} (0x${statusCode.toString(16).toUpperCase()})`)\n this.name = 'SessionInvalidError'\n this.statusCode = statusCode\n }\n}\n","import { ExtensionObject, ISecureChannel, NodeId, RequestHeader, StatusCode, StatusCodeToString, StatusCodeToStringNumber } from 'opcjs-base'\n\nimport { SessionInvalidError } from '../sessions/sessionInvalidError.js'\n\nexport abstract class ServiceBase {\n\n /**\n * Validates the `serviceResult` value from a response header.\n *\n * Throws `SessionInvalidError` for session-related status codes so callers\n * can detect a dropped session and act accordingly (e.g. reconnect).\n * Throws a generic `Error` for all other non-Good codes.\n *\n * @param result - The `serviceResult` value from the response header.\n * @param context - Short description used in the error message (e.g. \"ReadRequest\").\n */\n protected checkServiceResult(result: number | undefined, context: string): void {\n if (result === undefined || result === StatusCode.Good) return\n\n if (result === StatusCode.BadSessionIdInvalid || result === StatusCode.BadSessionClosed) {\n throw new SessionInvalidError(result)\n }\n\n throw new Error(`${context} failed: ${StatusCodeToString(result)} (${StatusCodeToStringNumber(result)})`)\n }\n\n protected createRequestHeader(): RequestHeader {\n const requestHeader = new RequestHeader();\n requestHeader.authenticationToken = this.authToken;\n requestHeader.timestamp = new Date();\n requestHeader.requestHandle = 0; // will be set by secure channel\n requestHeader.returnDiagnostics = 0;\n requestHeader.auditEntryId = '';\n requestHeader.timeoutHint = 60000;\n requestHeader.additionalHeader = ExtensionObject.newEmpty();\n\n return requestHeader;\n }\n \n constructor(private authToken: NodeId, protected secureChannel: ISecureChannel){}\n}","import {\n ActivateSessionRequest, ActivateSessionResponse, ApplicationDescription, ApplicationTypeEnum,\n CloseSessionRequest, CloseSessionResponse,\n Configuration, CreateSessionRequest, CreateSessionResponse, EndpointDescription, ExtensionObject,\n getLogger,\n ISecureChannel, LocalizedText, NodeId, SignatureData, SignedSoftwareCertificate, StatusCode,\n StatusCodeToString, UserIdentityToken,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\nexport class SessionService extends ServiceBase {\n private logger = getLogger(\"services.SessionService\");\n\n /**\n * Creates a new session on the server (OPC UA Part 4, Section 5.7.2).\n * @returns The session ID, authentication token, and selected server endpoint.\n */\n async createSession(): Promise<{ sessionId: number, authToken: NodeId, endpoint: EndpointDescription }> {\n this.logger.debug(\"Creating session...\");\n\n const clientDescription = new ApplicationDescription();\n clientDescription.applicationUri = this.configuration.applicationUri;\n clientDescription.productUri = this.configuration.productUri;\n clientDescription.applicationName = new LocalizedText(undefined, this.configuration.productName);\n clientDescription.applicationType = ApplicationTypeEnum.Client;\n clientDescription.gatewayServerUri = '';\n clientDescription.discoveryProfileUri = '';\n clientDescription.discoveryUrls = new Array<string>();\n\n const request = new CreateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientDescription = clientDescription;\n request.serverUri = '';\n request.endpointUrl = this.secureChannel.getEndpointUrl();\n request.sessionName = '';\n request.clientNonce = null;\n request.clientCertificate = null;\n request.requestedSessionTimeout = 60000;\n request.maxResponseMessageSize = 0;\n\n\n // todo: verify endpoints\n // todo: check application uri in server certificate\n\n this.logger.debug(\"Sending CreateSessionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request);\n if (!response || !(response instanceof CreateSessionResponse)) {\n throw new Error(\"Invalid response type for CreateSessionRequest\");\n }\n\n const castedResponse = response as CreateSessionResponse;\n if (!castedResponse || !castedResponse.sessionId || !castedResponse.authenticationToken) {\n throw new Error(\"CreateSessionResponse missing SessionId or AuthenticationToken\");\n }\n\n const serviceResult = castedResponse.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSessionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n // The URL the client actually used to connect. Prepend the OPC UA scheme\n // prefix so it is parseable by the standard URL constructor.\n const clientConnectionUrl = new URL('opc.' + this.secureChannel.getEndpointUrl())\n const securityMode = this.secureChannel.getSecurityMode()\n const securityPolicyUri = this.secureChannel.getSecurityPolicy()\n\n // OPC UA Part 4, Section 5.4.4.2: Clients should be prepared to replace\n // the HostName and port returned in the EndpointDescription with the\n // HostName or IP address and port they used to call GetEndpoints. This\n // handles NAT/load-balancer scenarios where the server advertises internal\n // addresses that are unreachable by the client.\n const normalizeEndpointUrl = (serverEndpointUrl: string): URL => {\n const url = new URL(serverEndpointUrl)\n url.hostname = clientConnectionUrl.hostname\n url.port = clientConnectionUrl.port\n return url\n }\n\n // Match on protocol and path only; host and port are normalized away so\n // that internally-addressed endpoints are still found.\n const serverEndpoint = castedResponse?.serverEndpoints?.find(currentEndpoint => {\n const normalized = normalizeEndpointUrl(currentEndpoint.endpointUrl as string)\n return normalized.protocol === clientConnectionUrl.protocol\n && normalized.pathname === clientConnectionUrl.pathname\n && currentEndpoint.securityMode === securityMode\n && currentEndpoint.securityPolicyUri === securityPolicyUri\n })\n\n if (!serverEndpoint) {\n throw new Error(`Server endpoint ${clientConnectionUrl.toString()} not found in CreateSessionResponse`)\n }\n\n // Replace the server-reported host and port with the client's actual\n // connection address so downstream code uses the correct URL.\n serverEndpoint.endpointUrl = normalizeEndpointUrl(serverEndpoint.endpointUrl as string).toString()\n\n // NOTE: per OPC UA Part 4, Section 5.4.4.2 the client shall still verify\n // the HostName it used to open the SecureChannel against the HostName list\n // in the Server Certificate. This is deferred until certificate-based\n // security (non-None SecurityPolicy) is implemented.\n\n this.logger.debug(\"Session created with id:\", castedResponse.sessionId.identifier);\n return {\n sessionId: castedResponse.sessionId.identifier as number,\n authToken: castedResponse.authenticationToken,\n endpoint: serverEndpoint\n };\n }\n\n /**\n * Activates an existing session using the supplied identity token (OPC UA Part 4, Section 5.7.3).\n * @param identityToken - User identity token (anonymous, username/password, certificate, or issued token).\n */\n async activateSession(identityToken: UserIdentityToken): Promise<void> {\n const signatureData = new SignatureData();\n signatureData.algorithm = this.secureChannel.getSecurityPolicy();\n signatureData.signature = new Uint8Array(0);\n\n const request = new ActivateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientSignature = signatureData;\n request.clientSoftwareCertificates = new Array<SignedSoftwareCertificate>();\n request.localeIds = ['en-US'];\n request.userIdentityToken = ExtensionObject.newBinary(identityToken);\n request.userTokenSignature = signatureData;\n\n this.logger.debug(\"Sending ActivateSessionRequest...\");\n const activateResponse = await this.secureChannel.issueServiceRequest(request) as ActivateSessionResponse;\n\n const activateResult = activateResponse?.responseHeader?.serviceResult;\n if (activateResult !== undefined && activateResult !== StatusCode.Good) {\n throw new Error(`ActivateSessionRequest failed: ${StatusCodeToString(activateResult)}`);\n }\n\n this.logger.debug(\"Session activated.\");\n }\n\n /**\n * Closes the current session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * associated with this Session, freeing their resources immediately.\n * Pass false to keep Subscriptions alive for transfer to another Session.\n */\n async closeSession(deleteSubscriptions: boolean): Promise<void> {\n this.logger.debug('Sending CloseSessionRequest...')\n\n const request = new CloseSessionRequest()\n request.requestHeader = this.createRequestHeader()\n request.deleteSubscriptions = deleteSubscriptions\n\n const response = await this.secureChannel.issueServiceRequest(request) as CloseSessionResponse\n\n const result = response?.responseHeader?.serviceResult\n if (result !== undefined && result !== StatusCode.Good) {\n throw new Error(`CloseSession failed: ${StatusCodeToString(result)}`)\n }\n\n this.logger.debug('Session closed.')\n }\n\n recreate(authToken: NodeId): SessionService {\n return new SessionService(authToken, this.secureChannel, this.configuration)\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel, private configuration: Configuration) {\n super(authToken, secureChannel)\n }\n}","interface IssuerEndpointUrl {\n 'ua.resourceId': string;\n 'ua.authorityUrl': string;\n 'ua.authorityProfileUri': string;\n 'ua.tokenEndpoint': string;\n 'ua.authorizationEndpoint': string;\n 'ua.requestTypes': string[];\n 'ua.scopes': string[];\n}\n\nexport class IssuerConfiguration{\n public static newFrom(issuerEndpointUrl: IssuerEndpointUrl): IssuerConfiguration {\n return new IssuerConfiguration(\n issuerEndpointUrl['ua.resourceId'],\n issuerEndpointUrl['ua.authorityUrl'],\n issuerEndpointUrl['ua.authorityProfileUri'],\n issuerEndpointUrl['ua.tokenEndpoint'],\n issuerEndpointUrl['ua.authorizationEndpoint'],\n issuerEndpointUrl['ua.requestTypes'],\n issuerEndpointUrl['ua.scopes']\n );\n }\n \n constructor(\n public resourceId: string,\n public authorityUrl: string,\n public authorityProfileUri: string,\n public tokenEndpoint: string,\n public authorizationEndpoint: string,\n public requestTypes: string[],\n public scopes: string[]\n ){\n \n }\n}","import { EndpointDescription, IssuedIdentityToken, NodeId, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"../issuerConfiguration\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\n\nexport class Session {\n async activateSession(identity: UserIdentity): Promise<void> {\n const token = identity.getUserIdentityToken();\n const tokenType = identity.getTokenType();\n const tokenPolicy = this.endpoint.userIdentityTokens?.find(t => t.tokenType === tokenType);\n if (!tokenPolicy) {\n throw new Error(`UserIdentityToken of type ${tokenType} not supported by server`);\n }\n token.policyId = tokenPolicy.policyId;\n\n if (tokenType === UserTokenTypeEnum.IssuedToken) {\n if (!tokenPolicy.issuerEndpointUrl) {\n throw new Error(\"IssuerEndpointUrl not defined for IssuedToken\");\n }\n const issuerEndpointUrl = JSON.parse(tokenPolicy.issuerEndpointUrl)\n const issuerConfig = IssuerConfiguration.newFrom(issuerEndpointUrl);\n\n const issuerLoginCallback = identity.getIssuerLoginCallback();\n const tokenData = await issuerLoginCallback(issuerConfig);\n\n const issuerToken = token as IssuedIdentityToken;\n issuerToken.tokenData = new TextEncoder().encode(tokenData.json);\n }\n\n await this.sessionServices.activateSession(token);\n }\n\n getAuthToken(): NodeId {\n return this.authToken;\n }\n\n getSessionId(): number {\n return this.sessionId;\n }\n\n getEndpoint(): EndpointDescription {\n return this.endpoint;\n }\n\n /**\n * Closes the session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * tied to this Session. Defaults to true.\n */\n async close(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n constructor(\n public sessionId: number,\n private authToken: NodeId,\n private endpoint: EndpointDescription,\n private sessionServices: SessionService) { }\n}","import { ConfigurationClient } from \"../configurationClient\";\nimport { EndpointDescription, ISecureChannel, NodeId, UserTokenTypeEnum, getLogger } from \"opcjs-base\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\nimport { Session } from \"./session\";\n\nexport class SessionHandler {\n private sessionServices: SessionService;\n private logger = getLogger(\"sessions.SessionHandler\");\n\n async createNewSession(identity:UserIdentity) : Promise<Session>{\n const ret = await this.sessionServices.createSession();\n this.sessionServices = this.sessionServices.recreate(ret.authToken)\n\n const session = new Session(ret.sessionId, ret.authToken, ret.endpoint, this.sessionServices);\n\n // Enforce user-token type restrictions from the client security configuration\n // before activating; the endpoint is now known from CreateSession.\n this.validateUserTokenPolicy(identity, ret.endpoint)\n\n await session.activateSession(identity);\n return session;\n }\n\n /**\n * Attempts to reactivate an existing OPC UA session on the current (new) SecureChannel\n * without calling CreateSession first (OPC UA Part 4, Section 5.7.3).\n *\n * This is the preferred recovery path when the SecureChannel drops but the server-side\n * session has not yet timed out: only a new channel is needed, not a new session.\n *\n * @returns The reactivated Session if ActivateSession succeeded, or `null` if the server\n * rejected the request (e.g. the session had already expired).\n */\n async tryActivateExistingSession(\n existingAuthToken: NodeId,\n existingSessionId: number,\n existingEndpoint: EndpointDescription,\n identity: UserIdentity,\n ): Promise<Session | null> {\n // Build a SessionService bound to the existing auth token so the RequestHeader\n // carries it and the server can correlate the ActivateSession to the right session.\n const serviceForExistingSession = this.sessionServices.recreate(existingAuthToken)\n try {\n const session = new Session(existingSessionId, existingAuthToken, existingEndpoint, serviceForExistingSession)\n await session.activateSession(identity)\n return session\n } catch (err) {\n this.logger.debug('ActivateSession for existing session failed:', err)\n return null\n }\n }\n\n /**\n * Closes the active session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - Forwarded to CloseSessionRequest. Defaults to true.\n */\n async closeSession(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n /**\n * Validates the requested user-identity token type against:\n * 1. The `allowedUserTokenTypes` from the client security configuration — the\n * client has explicitly restricted which token types it will use.\n * 2. The token policies advertised by the server endpoint — verifies that the\n * server actually supports at least one of the allowed types.\n *\n * Throws with a descriptive message if either check fails.\n */\n private validateUserTokenPolicy(identity: UserIdentity, endpoint: EndpointDescription): void {\n const allowedTypes = this.configuration.securityConfiguration?.allowedUserTokenTypes\n if (!allowedTypes) return // no restriction configured\n\n const requestedType = identity.getTokenType()\n\n // 1. Client-side restriction: the chosen identity must be an allowed type.\n if (!allowedTypes.includes(requestedType)) {\n throw new Error(\n `User token type '${UserTokenTypeEnum[requestedType]}' is not permitted by the ` +\n `client security configuration. Allowed types: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n\n // 2. Server-side availability: at least one allowed type must be offered.\n const serverTypes = endpoint.userIdentityTokens?.map(p => p.tokenType) ?? []\n const intersection = allowedTypes.filter(t => serverTypes.includes(t))\n if (intersection.length === 0) {\n throw new Error(\n `Server endpoint does not offer any user token type from the allowed list: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}. ` +\n `Server offers: ${serverTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n }\n\n constructor(secureChannel:ISecureChannel, private configuration: ConfigurationClient) {\n this.sessionServices = new SessionService(NodeId.newTwoByte(0), secureChannel, configuration);\n }\n}","import type { MessageSecurityModeEnum, UserTokenTypeEnum } from 'opcjs-base'\n\n/** URI for the SecurityPolicy None profile. */\nexport const SECURITY_POLICY_NONE_URI = 'http://opcfoundation.org/UA/SecurityPolicy#None'\n\n/**\n * How the client should handle a server certificate it cannot verify.\n *\n * - `'reject'` — abort the connection (secure default when `trustedCAs` is configured).\n * - `'trust'` — accept any certificate without verification (development convenience;\n * **insecure in production**).\n *\n * @note Enforcement is deferred until certificate-based security policies are\n * implemented. The value is stored and will be honoured when that support lands.\n */\nexport type UnknownCertificatePolicy = 'reject' | 'trust'\n\n/**\n * OPC UA client security configuration (OPC UA Part 2, Security Administration CU).\n *\n * Restricts which security options the client will accept when connecting to or\n * negotiating with a server. All fields are optional; omitting a field applies\n * the permissive default so that existing callers need no changes.\n *\n * @example\n * ```ts\n * const config = ConfigurationClient.getSimple('MyApp', 'MyCompany')\n * config.securityConfiguration = {\n * allowedUserTokenTypes: [UserTokenTypeEnum.UserName],\n * allowSecurityPolicyNone: false, // require an encrypted channel\n * }\n * ```\n */\nexport type SecurityConfiguration = {\n /**\n * User-identity-token types the client is willing to accept.\n *\n * When set, `connect()` will throw if:\n * - The supplied `UserIdentity`'s token type is not in this list, OR\n * - The server endpoint does not offer any type from this list.\n *\n * Default: all token types are accepted (no restriction).\n */\n allowedUserTokenTypes?: UserTokenTypeEnum[]\n\n /**\n * Allow connecting when the negotiated SecurityPolicy is `None` (unencrypted,\n * unsigned channel).\n *\n * Set to `false` to require a secure channel — `connect()` will throw rather\n * than establish a cleartext connection.\n *\n * Currently the only supported security policy is `None`. Setting this to `false`\n * will therefore cause `connect()` to always throw until non-None policies are\n * added to this client implementation.\n *\n * Default: `true` (SecurityPolicy None is permitted).\n */\n allowSecurityPolicyNone?: boolean\n\n /**\n * Required `MessageSecurityMode` for the secure channel.\n *\n * When set, `connect()` verifies that the channel's negotiated mode matches\n * this value and throws otherwise.\n *\n * Currently only `MessageSecurityModeEnum.None` is supported.\n *\n * Default: no requirement (any mode is accepted).\n */\n messageSecurityMode?: MessageSecurityModeEnum\n\n /**\n * DER-encoded X.509 trusted CA certificates used to verify the server's\n * application instance certificate.\n *\n * @note Reserved for future use. Certificate verification is not yet implemented.\n * Providing this field has no effect until non-None security policies land.\n */\n trustedCAs?: Uint8Array[]\n\n /**\n * How to handle a server certificate that cannot be verified against `trustedCAs`.\n *\n * - `'reject'` — refuse the connection (default when `trustedCAs` is provided).\n * - `'trust'` — accept any certificate (development only; insecure in production).\n *\n * @note Reserved for future use. Has no effect until certificate verification is\n * implemented alongside non-None security policies.\n */\n unknownCertificatePolicy?: UnknownCertificatePolicy\n}\n","// according to https://reference.opcfoundation.org/Core/Part6/v105/docs/A.1\n// see also: https://reference.opcfoundation.org/Core/Part4/v105/docs/7.24.1#Table154\n\nexport const AttrIdNodeId = 1\nexport const AttrIdNodeClass = 2\nexport const AttrIdBrowseName = 3\nexport const AttrIdDisplayName = 4\nexport const AttrIdDescription = 5\nexport const AttrIdWriteMask = 6\nexport const AttrIdUserWriteMask = 7\nexport const AttrIdIsAbstract = 8\nexport const AttrIdSymmetric = 9\nexport const AttrIdInverseName = 10\nexport const AttrIdContainsNoLoops = 11\nexport const AttrIdEventNotifier = 12\nexport const AttrIdValue = 13\nexport const AttrIdDataType = 14\nexport const AttrIdValueRank = 15\nexport const AttrIdArrayDimensions = 16\nexport const AttrIdAccessLevel = 17\nexport const AttrIdUserAccessLevel = 18\nexport const AttrIdMinimumSamplingInterval = 19\nexport const AttrIdHistorizing = 20\nexport const AttrIdExecutable = 21\nexport const AttrIdUserExecutable = 22\nexport const AttrIdDataTypeDefinition = 23\nexport const AttrIdRolePermissions = 24\nexport const AttrIdUserRolePermissions = 25\nexport const AttrIdAccessRestrictions = 26\nexport const AttrIdAccessLevelEx = 27\n","import {\n getLogger, ISecureChannel, NodeId, QualifiedName, ReadRequest, ReadResponse, ReadValueId,\n StatusCode, TimestampsToReturnEnum,\n} from 'opcjs-base'\n\nimport { AttrIdValue } from './attributeServiceAttributes.js'\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.10.2\nexport class AttributeService extends ServiceBase {\n private logger = getLogger(\"services.AttributeService\");\n\n /**\n * Reads the Value attribute of one or more Nodes (OPC UA Part 4, Section 5.10.2).\n * @param nodeIds - NodeIds of the Nodes to read.\n * @param maxAge - Maximum age of the cached value in milliseconds the server may return. 0 = always current value.\n * @param timestampsToReturn - Which timestamps to include in results. Default: Source.\n * @returns Array of results containing value and raw status code number, one per requested NodeId.\n */\n async ReadValue(\n nodeIds: NodeId[],\n maxAge: number = 0,\n timestampsToReturn: TimestampsToReturnEnum = TimestampsToReturnEnum.Source,\n ): Promise<{ statusCode: number, value: unknown }[]> {\n const readValueIds = nodeIds.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n return readValueId;\n });\n\n const request = new ReadRequest();\n request.requestHeader = this.createRequestHeader();\n request.maxAge = maxAge;\n request.timestampsToReturn = timestampsToReturn;\n request.nodesToRead = readValueIds;\n\n this.logger.debug(\"Sending ReadRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as ReadResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'ReadRequest')\n\n const results = new Array<{ statusCode: number, value: unknown }>();\n for (const dataValue of response.results ?? []) {\n results.push({\n statusCode: dataValue.statusCode ?? StatusCode.Good,\n value: dataValue.value as unknown,\n });\n }\n return results;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","export class ReadValueResult {\n constructor(public value: unknown, public statusCode: number) {}\n}","import { NodeId } from \"opcjs-base\";\n\nexport class SubscriptionHandlerEntry{\n constructor(\n public subscriptionId:number,\n public handle: number, \n public id:NodeId, \n public callback: (data: { id: NodeId, value: unknown }[]) => void\n ){}\n}","import {\n DataChangeNotification,\n ExpandedNodeId,\n getLogger,\n NodeId,\n StatusChangeNotification,\n SubscriptionAcknowledgement,\n} from 'opcjs-base'\n\nimport { MonitoredItemService } from './services/monitoredItemService'\nimport { SubscriptionService } from './services/subscriptionService'\nimport { SubscriptionHandlerEntry } from './subscriptionHandlerEntry'\n\n// OPC UA Part 4, §5.14 — Subscriptions and Monitored Items\n\n/** Node type IDs for notification payloads (OPC UA Part 4, §7.21) */\nconst NODE_ID_DATA_CHANGE_NOTIFICATION = 811\nconst NODE_ID_STATUS_CHANGE_NOTIFICATION = 818\n\nexport class SubscriptionHandler {\n private logger = getLogger('SubscriptionHandler')\n private entries = new Array<SubscriptionHandlerEntry>()\n private nextHandle = 0\n private isRunning = false\n\n /** Returns true when at least one subscription is active and the publish loop is running. */\n hasActiveSubscription(): boolean {\n return this.isRunning && this.entries.length > 0\n }\n\n async subscribe(ids: NodeId[], callback: (data: { id: NodeId; value: unknown }[]) => void) {\n if (this.entries.length > 0) {\n throw new Error('Subscribing more than once is not implemented')\n }\n\n const subscriptionId = await this.subscriptionService.createSubscription()\n const items = []\n for (const id of ids) {\n const entry = new SubscriptionHandlerEntry(subscriptionId, this.nextHandle++, id, callback)\n this.entries.push(entry)\n items.push({ id, handle: entry.handle })\n }\n await this.monitoredItemService.createMonitoredItems(subscriptionId, items)\n\n // Start the publish loop with no pending acknowledgements.\n this.isRunning = true\n void this.publishLoop([])\n }\n\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n private async publishLoop(pendingAcknowledgements: SubscriptionAcknowledgement[]): Promise<void> {\n if (!this.isRunning) return\n\n let response\n try {\n response = await this.subscriptionService.publish(pendingAcknowledgements)\n } catch (err) {\n this.logger.error(`Publish failed, stopping publish loop: ${err}`)\n this.isRunning = false\n return\n }\n\n const { subscriptionId, availableSequenceNumbers, moreNotifications, notificationMessage } = response\n const notificationDatas = notificationMessage?.notificationData ?? []\n const seqNumber = notificationMessage?.sequenceNumber\n\n // Build acknowledgements for the next publish request.\n // Per spec: only acknowledge sequence numbers that are in availableSequenceNumbers\n // and only for real notification messages (not keep-alive, which have empty notificationData).\n const nextAcknowledgements: SubscriptionAcknowledgement[] = []\n const isKeepAlive = notificationDatas.length === 0\n\n if (!isKeepAlive && seqNumber !== undefined) {\n // Acknowledge only if the server still lists this sequence number as available.\n const isAvailable = !availableSequenceNumbers || availableSequenceNumbers.includes(seqNumber)\n if (isAvailable) {\n const ack = new SubscriptionAcknowledgement()\n ack.subscriptionId = subscriptionId\n ack.sequenceNumber = seqNumber\n nextAcknowledgements.push(ack)\n }\n }\n\n // Dispatch notifications to registered callbacks.\n for (const notificationData of notificationDatas) {\n const decodedData = notificationData.data\n const rawTypeId = notificationData.typeId\n const typeNodeId = rawTypeId instanceof ExpandedNodeId ? rawTypeId.nodeId : rawTypeId\n\n if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_DATA_CHANGE_NOTIFICATION) {\n const dataChangeNotification = decodedData as DataChangeNotification\n for (const item of dataChangeNotification.monitoredItems) {\n const entry = this.entries.find(e => e.handle === item.clientHandle)\n entry?.callback([{ id: entry.id, value: item.value.value?.value }])\n }\n } else if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_STATUS_CHANGE_NOTIFICATION) {\n // The server notifies us the subscription state has changed (e.g. expired, closed).\n const statusChange = decodedData as StatusChangeNotification\n this.logger.warn(\n `Subscription ${subscriptionId} status changed: 0x${statusChange.status?.toString(16).toUpperCase()}`,\n )\n this.isRunning = false\n return\n } else {\n this.logger.warn(\n `Notification data type ${typeNodeId.namespace}:${typeNodeId.identifier} is not supported.`,\n )\n }\n }\n\n // Per spec: if moreNotifications is true the server has more queued data — re-publish immediately\n // without delay so the server's queue drains before its lifetime counter expires.\n // Otherwise, schedule the next publish after a short yield to avoid a tight synchronous loop.\n if (moreNotifications) {\n void this.publishLoop(nextAcknowledgements)\n } else {\n setTimeout(() => void this.publishLoop(nextAcknowledgements), 0)\n }\n }\n\n constructor(\n private subscriptionService: SubscriptionService,\n private monitoredItemService: MonitoredItemService,\n ) {}\n}","import {\n CreateSubscriptionRequest, CreateSubscriptionResponse, getLogger, ISecureChannel, NodeId,\n PublishRequest, PublishResponse, StatusCode, StatusCodeToString, SubscriptionAcknowledgement,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\n/** Options for creating a subscription. All fields are optional; server will revise requested values. */\nexport interface CreateSubscriptionOptions {\n /** Requested publishing interval in milliseconds. Default: 2000. */\n requestedPublishingInterval?: number;\n /** Requested lifetime count (number of publishing intervals before subscription times out). Default: 360000. */\n requestedLifetimeCount?: number;\n /** Requested max keep-alive count. Default: 60000. */\n requestedMaxKeepAliveCount?: number;\n /** Maximum number of notifications per publish response. 0 = no limit. Default: 200. */\n maxNotificationsPerPublish?: number;\n /** Subscription priority relative to other subscriptions. Default: 1. */\n priority?: number;\n}\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14\nexport class SubscriptionService extends ServiceBase {\n private logger = getLogger(\"services.SubscriptionService\");\n\n /**\n * Creates a new subscription on the server (OPC UA Part 4, Section 5.14.2).\n * @param options - Optional subscription parameters; server revises all values.\n * @returns The server-assigned subscription ID.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.2\n async createSubscription(options?: CreateSubscriptionOptions): Promise<number> {\n const request = new CreateSubscriptionRequest();\n request.requestHeader = this.createRequestHeader();\n request.requestedPublishingInterval = options?.requestedPublishingInterval ?? 2000;\n request.requestedLifetimeCount = options?.requestedLifetimeCount ?? 360000;\n request.requestedMaxKeepAliveCount = options?.requestedMaxKeepAliveCount ?? 60000;\n request.maxNotificationsPerPublish = options?.maxNotificationsPerPublish ?? 200;\n request.publishingEnabled = true;\n request.priority = options?.priority ?? 1;\n\n this.logger.debug(\"Sending CreateSubscriptionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateSubscriptionResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSubscriptionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(`Subscription created with id: ${response.subscriptionId}`);\n return response.subscriptionId;\n }\n\n /**\n * Sends a publish request to receive notifications from active subscriptions (OPC UA Part 4, Section 5.14.5).\n * @param acknowledgements - Sequence numbers to acknowledge from previous publish responses.\n * @returns The publish response containing notification data.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n async publish(acknowledgements: SubscriptionAcknowledgement[]): Promise<PublishResponse> {\n const request = new PublishRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionAcknowledgements = acknowledgements;\n\n this.logger.debug(\"Sending PublishRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as PublishResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`PublishRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(\"Received PublishResponse.\");\n return response;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import {\n CreateMonitoredItemsRequest, CreateMonitoredItemsResponse,\n ExtensionObject, getLogger, ISecureChannel, MonitoredItemCreateRequest, MonitoringModeEnum,\n MonitoringParameters, NodeId, QualifiedName, ReadValueId, StatusCode, StatusCodeToString,\n TimestampsToReturnEnum,\n} from \"opcjs-base\";\nimport { AttrIdValue } from \"./attributeServiceAttributes\";\nimport { ServiceBase } from \"./serviceBase\";\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.13.2\nexport class MonitoredItemService extends ServiceBase {\n private logger = getLogger(\"services.MonitoredItemService\");\n\n /**\n * Creates monitored items within a subscription (OPC UA Part 4, Section 5.13.2).\n * @param subscriptionId - ID of the subscription to add monitored items to.\n * @param ids - Array of NodeIds and client handles identifying the items to monitor.\n * @param samplingInterval - Requested sampling interval in milliseconds. -1 = use subscription publishing interval.\n * @param queueSize - Requested queue size for each monitored item.\n */\n async createMonitoredItems(\n subscriptionId: number,\n ids: { id: NodeId, handle: number }[],\n samplingInterval: number = 1000,\n queueSize: number = 100,\n ): Promise<void> {\n const items = ids.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni.id;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n\n const monitoringParameters = new MonitoringParameters();\n monitoringParameters.clientHandle = ni.handle;\n monitoringParameters.samplingInterval = samplingInterval;\n monitoringParameters.filter = ExtensionObject.newEmpty();\n monitoringParameters.queueSize = queueSize;\n monitoringParameters.discardOldest = true;\n\n const monitoredItemCreateRequest = new MonitoredItemCreateRequest();\n monitoredItemCreateRequest.itemToMonitor = readValueId;\n monitoredItemCreateRequest.monitoringMode = MonitoringModeEnum.Reporting;\n monitoredItemCreateRequest.requestedParameters = monitoringParameters;\n return monitoredItemCreateRequest;\n });\n\n const request = new CreateMonitoredItemsRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionId = subscriptionId;\n request.timestampsToReturn = TimestampsToReturnEnum.Source;\n request.itemsToCreate = items;\n\n this.logger.debug(\"Sending CreateMonitoredItemsRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateMonitoredItemsResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateMonitoredItemsRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n for (const result of response.results ?? []) {\n if (result.statusCode !== undefined && result.statusCode !== StatusCode.Good) {\n this.logger.warn(`Failed to create monitored item: ${StatusCodeToString(result.statusCode)}`);\n }\n }\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import { CallMethodRequest, CallRequest, CallResponse, getLogger, ISecureChannel, NodeId, StatusCode } from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.11.2\nexport class MethodService extends ServiceBase {\n private logger = getLogger(\"services.MethodService\");\n\n /**\n * Calls one or more methods on the server (OPC UA Part 4, Section 5.11.2).\n * @param methodsToCall - Array of CallMethodRequest describing each method to invoke.\n * @returns Array of results containing output argument values and raw status code number, one per requested method.\n */\n async call(methodsToCall: CallMethodRequest[]): Promise<{ statusCode: number, value: unknown[] }[]> {\n const request = new CallRequest();\n request.requestHeader = this.createRequestHeader();\n request.methodsToCall = methodsToCall;\n\n this.logger.debug(\"Sending CallRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CallResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'CallRequest')\n\n return response.results.map(result => ({\n statusCode: result.statusCode ?? StatusCode.Good,\n value: result.outputArguments.map(arg => arg.value),\n }));\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","export class CallMethodResult {\n constructor(public values: unknown[], public statusCode: number) {}\n}","import {\n BrowseDescription, BrowseNextRequest, BrowseNextResponse,\n BrowseRequest, BrowseResponse, BrowseResult,\n getLogger, ISecureChannel, NodeId, UaByteString, ViewDescription,\n} from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.9\nexport class BrowseService extends ServiceBase {\n private logger = getLogger(\"services.BrowseService\");\n\n /**\n * Browses one or more Nodes and returns their References (OPC UA Part 4, Section 5.9.2).\n * @param nodesToBrowse - Array of BrowseDescriptions specifying nodes and filter criteria.\n * @returns Array of BrowseResult, one per requested node.\n */\n async browse(nodesToBrowse: BrowseDescription[]): Promise<BrowseResult[]> {\n const view = new ViewDescription();\n view.viewId = NodeId.newNumeric(0, 0);\n view.timestamp = new Date(-11644473600000); // OPC UA MinDateTime (ticks=0)\n view.viewVersion = 0;\n\n const request = new BrowseRequest();\n request.requestHeader = this.createRequestHeader();\n request.view = view;\n request.requestedMaxReferencesPerNode = 0;\n request.nodesToBrowse = nodesToBrowse;\n\n this.logger.debug(\"Sending BrowseRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseRequest')\n\n return response.results ?? []\n }\n\n /**\n * Continues a Browse operation using continuation points (OPC UA Part 4, Section 5.9.3).\n * @param continuationPoints - Continuation points returned by a prior Browse or BrowseNext call.\n * @param releaseContinuationPoints - If true, releases the continuation points without returning results.\n * @returns Array of BrowseResult, one per continuation point.\n */\n async browseNext(\n continuationPoints: UaByteString[],\n releaseContinuationPoints: boolean,\n ): Promise<BrowseResult[]> {\n const request = new BrowseNextRequest();\n request.requestHeader = this.createRequestHeader();\n request.releaseContinuationPoints = releaseContinuationPoints;\n request.continuationPoints = continuationPoints;\n\n this.logger.debug(\"Sending BrowseNextRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseNextResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseNextRequest')\n\n return response.results ?? []\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","import {\n ExpandedNodeId, LocalizedText, NodeClassEnum,\n NodeId, QualifiedName\n} from \"opcjs-base\";\n\nexport class BrowseNodeResult {\n constructor(\n public referenceTypeId: NodeId,\n public isForward: boolean,\n public nodeId: ExpandedNodeId,\n public browseName: QualifiedName,\n public displayName: LocalizedText,\n public nodeClass: NodeClassEnum,\n public typeDefinition: ExpandedNodeId,\n ) {}\n}\n","import {\n NodeId,\n ISecureChannel,\n TcpConnectionHandler,\n SecureChannelFacade,\n SecureChannelContext,\n SecureChannelMessageEncoder,\n SecureChannelTypeDecoder,\n SecureChannelMessageDecoder,\n SecureChannelTypeEncoder,\n initLoggerProvider,\n TcpMessageInjector,\n TcpMessageDecoupler,\n getLogger,\n WebSocketFascade,\n WebSocketReadableStream,\n WebSocketWritableStream,\n SecureChannelChunkReader,\n SecureChannelChunkWriter,\n CallMethodRequest,\n Variant,\n BrowseDescription,\n BrowseDirectionEnum,\n BrowseResultMaskEnum,\n ReferenceDescription,\n ILogger,\n} from 'opcjs-base'\n\nimport { SessionHandler } from './sessions/sessionHandler.js'\nimport { Session } from './sessions/session.js'\nimport { SessionInvalidError } from './sessions/sessionInvalidError.js'\nimport { SECURITY_POLICY_NONE_URI } from './securityConfiguration.js'\nimport { AttributeService } from './services/attributeService.js'\nimport { ReadValueResult } from './readValueResult.js'\nimport { SubscriptionHandler } from './subscriptionHandler.js'\nimport { SubscriptionService } from './services/subscriptionService.js'\nimport { MonitoredItemService } from './services/monitoredItemService.js'\nimport { UserIdentity } from './userIdentity.js'\nimport { ConfigurationClient } from './configurationClient.js'\nimport { MethodService } from './services/methodService.js'\nimport { CallMethodResult } from './callMethodResult.js'\nimport { BrowseService } from './services/browseService.js'\nimport { BrowseNodeResult } from './browseNodeResult.js'\nimport { CallMethodArgument } from './callMethodArgument.js'\n\n/** NodeId of Server_ServerStatus (ns=0, i=2256) — a cheap server-side read used for session keep-alive. */\nconst SERVER_STATUS_NODE_ID = NodeId.newNumeric(0, 2256)\n/**\n * How often to read the server when no subscription is active (ms).\n * Must be shorter than the server's revisedSessionTimeout (default: 60 000 ms).\n */\nconst KEEP_ALIVE_INTERVAL_MS = 25_000\n\nexport class Client {\n private endpointUrl: string\n private attributeService?: AttributeService\n private methodService?: MethodService\n private browseService?: BrowseService\n private session?: Session\n private subscriptionHandler?: SubscriptionHandler\n private logger: ILogger\n // Stored after connect() so that refreshSession() and disconnect() can use them.\n private secureChannel?: ISecureChannel\n private secureChannelFacade?: SecureChannelFacade\n private ws?: WebSocketFascade\n private sessionHandler?: SessionHandler\n private keepAliveTimer?: ReturnType<typeof setInterval>\n\n getSession(): Session {\n if (!this.session) {\n throw new Error('No session available')\n }\n return this.session\n }\n\n /**\n * (Re-)initialises all session-scoped services from the current `this.session`.\n * Called both after the initial `connect()` and after a session refresh.\n */\n private initServices(): void {\n const authToken = this.session!.getAuthToken()\n const sc = this.secureChannel!\n this.attributeService = new AttributeService(authToken, sc)\n this.methodService = new MethodService(authToken, sc)\n this.browseService = new BrowseService(authToken, sc)\n this.subscriptionHandler = new SubscriptionHandler(\n new SubscriptionService(authToken, sc),\n new MonitoredItemService(authToken, sc),\n )\n }\n\n /**\n * Executes `fn` and, if it throws a `SessionInvalidError`, creates a fresh\n * session and retries the operation exactly once.\n *\n * This covers the reactive case: a service call reveals that the server has\n * already dropped the session (e.g. due to timeout). The new session is\n * established transparently before re-running the original operation.\n *\n * For any other error (e.g. transport-level failures when the SecureChannel\n * drops), this method attempts to reconnect the channel and reactivate the\n * existing session first — falling back to a brand-new session only when\n * reactivation fails — before retrying the operation once.\n */\n private async withSessionRefresh<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof SessionInvalidError) {\n this.logger.info(`Session invalid (${err.statusCode.toString(16)}), refreshing session...`)\n this.session = await this.sessionHandler!.createNewSession(this.identity)\n this.initServices()\n this.logger.info('Session refreshed, retrying operation.')\n\n // Retry once with the new session. If it fails again the error propagates.\n return await fn()\n }\n\n // Possibly a channel drop: attempt reconnect + ActivateSession on existing session\n // before giving up and creating a brand-new session (OPC UA Part 4 Session Auto Reconnect).\n this.logger.info('Service call failed, attempting channel reconnect and session reactivation...')\n try {\n await this.reconnectAndReactivate()\n this.initServices()\n this.logger.info('Reconnected successfully, retrying operation.')\n } catch (reconnectErr) {\n // Reconnect itself failed; surface the original error so the caller\n // gets a meaningful diagnostic (the reconnect error is logged separately).\n this.logger.warn('Channel reconnect failed:', reconnectErr)\n throw err\n }\n\n // Retry once after a successful reconnect. If it fails again the error propagates.\n return await fn()\n }\n }\n\n /**\n * Starts a periodic keep-alive timer that reads Server_ServerStatus when no subscription is\n * active. OPC UA Part 4, Section 5.7.1 requires clients to keep the session alive; when no\n * subscription Publish loop is running this is the only mechanism that does so.\n */\n private startKeepAlive(): void {\n this.keepAliveTimer = setInterval(() => {\n if (this.subscriptionHandler?.hasActiveSubscription()) {\n // The subscription publish loop is already keeping the session alive.\n return\n }\n if (this.attributeService) {\n void this.attributeService.ReadValue([SERVER_STATUS_NODE_ID]).catch((err) => {\n this.logger.warn('Keep-alive read failed:', err)\n })\n }\n }, KEEP_ALIVE_INTERVAL_MS)\n }\n\n private stopKeepAlive(): void {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n }\n\n async connect(): Promise<void> {\n const { ws, sc } = await this.openTransportAndChannel()\n\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n\n this.logger.debug('Creating session...')\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.debug('Session created.')\n\n this.logger.debug('Initializing services...')\n this.initServices()\n this.startKeepAlive()\n }\n\n /**\n * Builds the full WebSocket → TCP → SecureChannel pipeline and returns the\n * two objects needed to drive it: the raw WebSocket facade (for teardown)\n * and the SecureChannelFacade (for service requests/session management).\n *\n * Extracted from `connect()` so it can be reused by `reconnectAndReactivate()`.\n */\n private async openTransportAndChannel(): Promise<{ ws: WebSocketFascade; sc: SecureChannelFacade }> {\n const wsOptions = { endpoint: this.endpointUrl }\n const ws = new WebSocketFascade(wsOptions);\n const webSocketReadableStream = new WebSocketReadableStream(ws, 1000);\n const webSocketWritableStream = new WebSocketWritableStream(ws);\n\n const scContext = new SecureChannelContext(this.endpointUrl);\n const tcpMessageInjector = new TcpMessageInjector();\n const tcpConnectionHandler = new TcpConnectionHandler(tcpMessageInjector, scContext);\n const tcpMessageDecoupler = new TcpMessageDecoupler(tcpConnectionHandler.onTcpMessage.bind(tcpConnectionHandler));\n const scMessageEncoder = new SecureChannelMessageEncoder(scContext);\n const scTypeDecoder = new SecureChannelTypeDecoder(\n this.configuration.decoder,\n );\n const scMessageDecoder = new SecureChannelMessageDecoder(scContext);\n const scTypeEncoder = new SecureChannelTypeEncoder(\n this.configuration.encoder,\n );\n const scChunkWriter = new SecureChannelChunkWriter(scContext);\n const scChunkReader = new SecureChannelChunkReader(scContext);\n\n webSocketReadableStream.pipeTo(tcpMessageDecoupler.writable);\n tcpMessageDecoupler.readable.pipeTo(scMessageDecoder.writable);\n scMessageDecoder.readable.pipeTo(scChunkReader.writable);\n scChunkReader.readable.pipeTo(scTypeDecoder.writable);\n\n scTypeEncoder.readable.pipeTo(scChunkWriter.writable);\n scChunkWriter.readable.pipeTo(scMessageEncoder.writable);\n scMessageEncoder.readable.pipeTo(tcpMessageInjector.writable);\n tcpMessageInjector.readable.pipeTo(webSocketWritableStream);\n\n const sc = new SecureChannelFacade(scContext, scTypeDecoder, scTypeEncoder);\n\n let connected = false;\n while (!connected) {\n this.logger.debug(`Connecting to OPC UA server at ${this.endpointUrl}...`);\n await ws.connect();\n this.logger.debug(\"WebSocket connection established, now establishing TCP connection...\");\n connected = await tcpConnectionHandler.connect(this.endpointUrl);\n\n if (!connected) {\n this.logger.info(\"Connection failed, retrying in 2 seconds...\");\n await new Promise((resolve) => setTimeout(resolve, 2000));\n }\n }\n this.logger.info(\"Connected to OPC UA server.\");\n\n this.logger.debug(\"Opening secure channel...\");\n await sc.openSecureChannel();\n this.logger.debug(\"Secure channel established.\");\n\n // Enforce any channel-level security requirements before proceeding.\n this.enforceChannelSecurityConfig(sc);\n\n return { ws, sc };\n }\n\n /**\n * Validates the negotiated channel's security policy and mode against the\n * client's `SecurityConfiguration` (OPC UA Part 2, Security Administration).\n *\n * Throws if:\n * - `allowSecurityPolicyNone` is `false` and the channel uses SecurityPolicy None.\n * - `messageSecurityMode` is set and does not match the channel's actual mode.\n */\n private enforceChannelSecurityConfig(sc: SecureChannelFacade): void {\n const config = this.configuration.securityConfiguration\n if (!config) return\n\n const negotiatedPolicy = sc.getSecurityPolicy()\n const negotiatedMode = sc.getSecurityMode()\n\n if (config.allowSecurityPolicyNone === false && negotiatedPolicy === SECURITY_POLICY_NONE_URI) {\n throw new Error(\n 'Connection refused: SecurityPolicy None is disabled by the client security configuration. ' +\n 'Only SecurityPolicy None is currently supported by this client implementation.',\n )\n }\n\n if (config.messageSecurityMode !== undefined && config.messageSecurityMode !== negotiatedMode) {\n throw new Error(\n `Connection refused: negotiated MessageSecurityMode ${negotiatedMode} does not match ` +\n `the required mode ${config.messageSecurityMode} from the security configuration.`,\n )\n }\n }\n\n /**\n * Tears down the current (dead) channel and establishes a fresh one, then\n * attempts to recover the existing OPC UA session via ActivateSession before\n * falling back to a full CreateSession + ActivateSession.\n *\n * OPC UA Part 4, Section 5.7.1 / Session Client Auto Reconnect conformance unit:\n * When the SecureChannel drops but the server-side session has not yet timed\n * out, the client SHOULD reuse the existing session by calling ActivateSession\n * on the new channel. Only if that fails should the client create a new session.\n */\n private async reconnectAndReactivate(): Promise<void> {\n this.logger.info('Tearing down dead channel before reconnect...')\n\n // Close the old channel and WebSocket (best effort — they may already be dead).\n try { this.secureChannelFacade?.close() } catch { /* already dead */ }\n try { this.ws?.close() } catch { /* already dead */ }\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n this.ws = undefined\n\n const { ws, sc } = await this.openTransportAndChannel()\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n\n // Attempt to reactivate the existing session on the new channel.\n if (this.session) {\n const reactivated = await this.sessionHandler.tryActivateExistingSession(\n this.session.getAuthToken(),\n this.session.getSessionId(),\n this.session.getEndpoint(),\n this.identity,\n )\n if (reactivated !== null) {\n this.session = reactivated\n this.logger.info('Existing session successfully reactivated on new channel.')\n return\n }\n this.logger.info('ActivateSession for existing session failed; creating a fresh session...')\n }\n\n // Fall back: full CreateSession + ActivateSession.\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.info('Fresh session established on new channel.')\n }\n\n /**\n * Gracefully disconnects from the OPC UA server.\n *\n * Sequence per OPC UA Part 4, Section 5.7.4:\n * 1. CloseSession (deleteSubscriptions=true) so the server frees all resources.\n * 2. Close the SecureChannel, which cancels the pending token-renewal timer.\n * 3. Close the WebSocket transport.\n *\n * CloseSession errors are swallowed so transport teardown always completes even\n * when the session has already expired on the server side.\n */\n async disconnect(): Promise<void> {\n this.logger.info('Disconnecting from OPC UA server...')\n this.stopKeepAlive()\n\n if (this.session && this.sessionHandler) {\n try {\n await this.sessionHandler.closeSession(true)\n } catch (err) {\n // Session may already be gone on the server; log and continue teardown.\n this.logger.warn('CloseSession failed (continuing teardown):', err)\n }\n this.session = undefined\n }\n\n this.secureChannelFacade?.close()\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n\n this.ws?.close()\n this.ws = undefined\n\n this.logger.info('Disconnected.')\n }\n\n async read(ids: NodeId[]): Promise<ReadValueResult[]> {\n return this.withSessionRefresh(async () => {\n const result = await this.attributeService?.ReadValue(ids)\n return result?.map(r => new ReadValueResult(r.value, r.statusCode)) ?? []\n })\n }\n\n /**\n * Method for calling a single method on the server.\n * @param objectId - NodeId of the Object that owns the method.\n * @param methodId - NodeId of the Method to invoke.\n * @param inputArguments - Input argument Variants (default: empty).\n * @returns The CallMethodResult for the invoked method.\n */\n async callMethod(\n objectId: NodeId,\n methodId: NodeId,\n inputArguments: CallMethodArgument[] = []\n ): Promise<CallMethodResult> {\n return this.withSessionRefresh(async () => {\n const request = new CallMethodRequest()\n request.objectId = objectId\n request.methodId = methodId\n request.inputArguments = inputArguments.map(arg => Variant.newFrom(arg as Parameters<typeof Variant.newFrom>[0]))\n\n const responses = await this.methodService!.call([request])\n const response = responses[0]\n return new CallMethodResult(response.value, response.statusCode)\n })\n }\n\n async browse(\n nodeId: NodeId,\n recursive: boolean = false,\n ): Promise<BrowseNodeResult[]> {\n return this.withSessionRefresh(() => {\n const visited = new Set<string>()\n return this.browseRecursive(nodeId, recursive, visited)\n })\n }\n\n private async browseRecursive(\n nodeId: NodeId,\n recursive: boolean,\n visited: Set<string>,\n ): Promise<BrowseNodeResult[]> {\n const nodeKey = `${nodeId.namespace}:${nodeId.identifier}`;\n if (visited.has(nodeKey)) {\n return [];\n }\n visited.add(nodeKey);\n\n const description = new BrowseDescription();\n description.nodeId = nodeId;\n description.browseDirection = BrowseDirectionEnum.Forward;\n description.referenceTypeId = NodeId.newNumeric(0, 33); // HierarchicalReferences\n description.includeSubtypes = true;\n description.nodeClassMask = 0; // all node classes\n description.resultMask = BrowseResultMaskEnum.All;\n\n const browseResults = await this.browseService!.browse([description]);\n const browseResult = browseResults[0];\n const allReferences = [...(browseResult.references ?? [])];\n\n let continuationPoint = browseResult.continuationPoint;\n while (continuationPoint && continuationPoint.byteLength > 0) {\n const nextResults = await this.browseService!\n .browseNext([continuationPoint], false);\n const nextResult = nextResults[0];\n allReferences.push(...(nextResult.references ?? []));\n continuationPoint = nextResult.continuationPoint;\n }\n\n const results = allReferences.map((ref: ReferenceDescription) =>\n new BrowseNodeResult(\n ref.referenceTypeId,\n ref.isForward,\n ref.nodeId,\n ref.browseName,\n ref.displayName,\n ref.nodeClass,\n ref.typeDefinition,\n )\n );\n\n if (recursive) {\n for (const ref of allReferences) {\n const childNodeId = NodeId.newNumeric(\n ref.nodeId.nodeId.namespace,\n ref.nodeId.nodeId.identifier as number,\n );\n const childResults = await this.browseRecursive(\n childNodeId, true, visited,\n );\n results.push(...childResults);\n }\n }\n\n return results;\n }\n\n async subscribe(\n ids: NodeId[],\n callback: (data: { id: NodeId; value: unknown }[]) => void,\n ) {\n this.subscriptionHandler?.subscribe(ids, callback);\n }\n\n constructor(\n endpointUrl: string,\n private configuration: ConfigurationClient,\n private identity: UserIdentity,\n ) {\n this.endpointUrl = endpointUrl;\n initLoggerProvider(configuration.loggerFactory);\n this.logger = getLogger(\"Client\");\n }\n}\n","import {\n BinaryReader,\n BinaryWriter,\n Configuration,\n Decoder,\n Encoder,\n ILoggerFactory,\n LoggerFactory,\n registerBinaryDecoders,\n registerEncoders,\n registerTypeDecoders\n} from \"opcjs-base\";\n\nimport type { SecurityConfiguration } from './securityConfiguration.js'\n\nexport class ConfigurationClient extends Configuration {\n /**\n * Optional security restrictions applied during `Client.connect()`.\n * When not set, permissive defaults are used (SecurityPolicy None allowed,\n * all user-token types accepted).\n *\n * @see SecurityConfiguration\n */\n public securityConfiguration?: SecurityConfiguration\n public static getSimple(\n name: string,\n company: string,\n loggerFactory?: ILoggerFactory,\n ): ConfigurationClient {\n\n if (!loggerFactory) {\n loggerFactory = new LoggerFactory({\n defaultLevel: 'DEBUG', //todo: use enum\n categoryLevels: {\n \"transport.*\": \"TRACE\",\n \"secureChannel.*\": \"TRACE\",\n },\n });\n }\n const applicationUri = `urn:${company}:${name}`;\n const productUri = `urn:${company}:${name}:product`;\n\n const encoder = new Encoder();\n encoder.registerWriterFactory(\"binary\", () => {\n return new BinaryWriter();\n });\n registerEncoders(encoder);\n\n const decoder = new Decoder();\n decoder.registerReaderFactory(\"binary\", (data: unknown) => {\n return new BinaryReader(data as Uint8Array);\n });\n registerTypeDecoders(decoder);\n registerBinaryDecoders(decoder);\n\n return new ConfigurationClient(\n name,\n applicationUri,\n name,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n\n constructor(\n applicationName: string,\n applicationUri: string,\n productName: string,\n productUri: string,\n encoder: Encoder,\n decoder: Decoder,\n loggerFactory: ILoggerFactory,\n ) {\n super(\n applicationName,\n applicationUri,\n productName,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n}\n","import { IssuedIdentityToken, UserIdentityToken, UserNameIdentityToken, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"./issuerConfiguration\";\nimport { IssuerToken } from \"./issuerToken\";\nimport { AnonymousIdentityToken } from \"opcjs-base\";\n\nexport class UserIdentity {\n private userIdentityToken?: UserIdentityToken;\n private tokenType = UserTokenTypeEnum.Anonymous;\n private issuerLoginCallback: ((config:IssuerConfiguration)=>Promise<IssuerToken>) | undefined = undefined;\n\n public static newAnonymous(): UserIdentity {\n const userIdentity = new UserIdentity();\n userIdentity.userIdentityToken = new AnonymousIdentityToken();\n userIdentity.userIdentityToken.policyId = \"anonymous\";\n userIdentity.tokenType = UserTokenTypeEnum.Anonymous;\n return userIdentity;\n }\n \n public static newWithUserName(userName: string, password: string): UserIdentity {\n const userIdentity = new UserIdentity();\n const nameToken = new UserNameIdentityToken();\n nameToken.userName = userName;\n nameToken.password = new TextEncoder().encode(password);\n\n userIdentity.userIdentityToken = nameToken;\n userIdentity.tokenType = UserTokenTypeEnum.UserName;\n return userIdentity;\n }\n\n public static newWithIssuerToken(loginCallback: (config:IssuerConfiguration)=>Promise<IssuerToken>): UserIdentity {\n const userIdentity = new UserIdentity();\n const issuedToken = new IssuedIdentityToken();\n issuedToken.tokenData = new TextEncoder().encode(\"\"); // token data will be filled by the login callback \n userIdentity.userIdentityToken = issuedToken;\n userIdentity.tokenType = UserTokenTypeEnum.IssuedToken;\n userIdentity.issuerLoginCallback = loginCallback;\n return userIdentity;\n }\n\n public getUserIdentityToken(): UserIdentityToken {\n return this.userIdentityToken as UserIdentityToken;\n }\n\n public getTokenType(): UserTokenTypeEnum {\n return this.tokenType;\n }\n\n public getIssuerLoginCallback(): ((config:IssuerConfiguration)=>Promise<IssuerToken>) {\n if(!this.issuerLoginCallback){\n throw new Error(\"No issuer login callback defined\");\n }\n \n return this.issuerLoginCallback;\n }\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { ISecureChannel, RequestHeader, NodeId, EndpointDescription, UserIdentityToken, Configuration, UserTokenTypeEnum, MessageSecurityModeEnum, ILoggerFactory, Encoder, Decoder, ExpandedNodeId, QualifiedName, LocalizedText, NodeClassEnum, UaPrimitive, XmlElement, ExtensionObject, DataValue, DiagnosticInfo, Variant } from 'opcjs-base';
1
+ import { ISecureChannel, RequestHeader, NodeId, EndpointDescription, UserIdentityToken, Configuration, UserTokenTypeEnum, MessageSecurityModeEnum, ILoggerFactory, Encoder, Decoder, ExpandedNodeId, QualifiedName, LocalizedText, NodeClassEnum, UaPrimitive, XmlElement, ExtensionObject, DataValue, DiagnosticInfo } from 'opcjs-base';
2
2
 
3
3
  declare abstract class ServiceBase {
4
4
  private authToken;
@@ -223,7 +223,23 @@ declare class BrowseNodeResult {
223
223
  constructor(referenceTypeId: NodeId, isForward: boolean, nodeId: ExpandedNodeId, browseName: QualifiedName, displayName: LocalizedText, nodeClass: NodeClassEnum, typeDefinition: ExpandedNodeId);
224
224
  }
225
225
 
226
- type CallMethodArgument = UaPrimitive | NodeId | ExpandedNodeId | QualifiedName | LocalizedText | XmlElement | ExtensionObject | DataValue | DiagnosticInfo | Variant;
226
+ /**
227
+ * A single (scalar) value that may be passed as a method argument.
228
+ * `Variant` is intentionally excluded — callers work with concrete OPC UA types;
229
+ * the conversion to `Variant` is done internally by `callMethod`.
230
+ */
231
+ type ScalarCallMethodArgument = UaPrimitive | NodeId | ExpandedNodeId | QualifiedName | LocalizedText | XmlElement | ExtensionObject | DataValue | DiagnosticInfo;
232
+ /**
233
+ * A value (or homogeneous array of values) that may be passed as a method argument
234
+ * to {@link Client.callMethod}.
235
+ *
236
+ * Pass a plain array to create an array-rank Variant input argument, e.g.:
237
+ * ```ts
238
+ * client.callMethod(objId, methodId, [[uaDouble(1.0), uaDouble(2.0)]])
239
+ * ```
240
+ * Arrays must be homogeneous — all elements must be of the same OPC UA type.
241
+ */
242
+ type CallMethodArgument = ScalarCallMethodArgument | ScalarCallMethodArgument[];
227
243
 
228
244
  declare class Client {
229
245
  private configuration;
@@ -342,4 +358,4 @@ declare class SessionInvalidError extends Error {
342
358
  constructor(statusCode: number);
343
359
  }
344
360
 
345
- export { BrowseNodeResult, type CallMethodArgument, CallMethodResult, Client, ConfigurationClient, SECURITY_POLICY_NONE_URI, type SecurityConfiguration, SessionInvalidError, type UnknownCertificatePolicy, UserIdentity };
361
+ export { BrowseNodeResult, type CallMethodArgument, CallMethodResult, Client, ConfigurationClient, SECURITY_POLICY_NONE_URI, type ScalarCallMethodArgument, type SecurityConfiguration, SessionInvalidError, type UnknownCertificatePolicy, UserIdentity };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { ISecureChannel, RequestHeader, NodeId, EndpointDescription, UserIdentityToken, Configuration, UserTokenTypeEnum, MessageSecurityModeEnum, ILoggerFactory, Encoder, Decoder, ExpandedNodeId, QualifiedName, LocalizedText, NodeClassEnum, UaPrimitive, XmlElement, ExtensionObject, DataValue, DiagnosticInfo, Variant } from 'opcjs-base';
1
+ import { ISecureChannel, RequestHeader, NodeId, EndpointDescription, UserIdentityToken, Configuration, UserTokenTypeEnum, MessageSecurityModeEnum, ILoggerFactory, Encoder, Decoder, ExpandedNodeId, QualifiedName, LocalizedText, NodeClassEnum, UaPrimitive, XmlElement, ExtensionObject, DataValue, DiagnosticInfo } from 'opcjs-base';
2
2
 
3
3
  declare abstract class ServiceBase {
4
4
  private authToken;
@@ -223,7 +223,23 @@ declare class BrowseNodeResult {
223
223
  constructor(referenceTypeId: NodeId, isForward: boolean, nodeId: ExpandedNodeId, browseName: QualifiedName, displayName: LocalizedText, nodeClass: NodeClassEnum, typeDefinition: ExpandedNodeId);
224
224
  }
225
225
 
226
- type CallMethodArgument = UaPrimitive | NodeId | ExpandedNodeId | QualifiedName | LocalizedText | XmlElement | ExtensionObject | DataValue | DiagnosticInfo | Variant;
226
+ /**
227
+ * A single (scalar) value that may be passed as a method argument.
228
+ * `Variant` is intentionally excluded — callers work with concrete OPC UA types;
229
+ * the conversion to `Variant` is done internally by `callMethod`.
230
+ */
231
+ type ScalarCallMethodArgument = UaPrimitive | NodeId | ExpandedNodeId | QualifiedName | LocalizedText | XmlElement | ExtensionObject | DataValue | DiagnosticInfo;
232
+ /**
233
+ * A value (or homogeneous array of values) that may be passed as a method argument
234
+ * to {@link Client.callMethod}.
235
+ *
236
+ * Pass a plain array to create an array-rank Variant input argument, e.g.:
237
+ * ```ts
238
+ * client.callMethod(objId, methodId, [[uaDouble(1.0), uaDouble(2.0)]])
239
+ * ```
240
+ * Arrays must be homogeneous — all elements must be of the same OPC UA type.
241
+ */
242
+ type CallMethodArgument = ScalarCallMethodArgument | ScalarCallMethodArgument[];
227
243
 
228
244
  declare class Client {
229
245
  private configuration;
@@ -342,4 +358,4 @@ declare class SessionInvalidError extends Error {
342
358
  constructor(statusCode: number);
343
359
  }
344
360
 
345
- export { BrowseNodeResult, type CallMethodArgument, CallMethodResult, Client, ConfigurationClient, SECURITY_POLICY_NONE_URI, type SecurityConfiguration, SessionInvalidError, type UnknownCertificatePolicy, UserIdentity };
361
+ export { BrowseNodeResult, type CallMethodArgument, CallMethodResult, Client, ConfigurationClient, SECURITY_POLICY_NONE_URI, type ScalarCallMethodArgument, type SecurityConfiguration, SessionInvalidError, type UnknownCertificatePolicy, UserIdentity };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sessions/sessionInvalidError.ts","../src/services/serviceBase.ts","../src/services/sessionService.ts","../src/issuerConfiguration.ts","../src/sessions/session.ts","../src/sessions/sessionHandler.ts","../src/securityConfiguration.ts","../src/services/attributeServiceAttributes.ts","../src/services/attributeService.ts","../src/readValueResult.ts","../src/subscriptionHandlerEntry.ts","../src/subscriptionHandler.ts","../src/services/subscriptionService.ts","../src/services/monitoredItemService.ts","../src/services/methodService.ts","../src/callMethodResult.ts","../src/services/browseService.ts","../src/browseNodeResult.ts","../src/client.ts","../src/configurationClient.ts","../src/userIdentity.ts"],"names":["StatusCodeToString","StatusCode","ExtensionObject","NodeId","getLogger","UserTokenTypeEnum","ReadValueId","QualifiedName","TimestampsToReturnEnum","CallMethodRequest","BrowseDescription","Configuration","IssuedIdentityToken"],"mappings":";;;AAaO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EACpC,UAAA;AAAA,EAET,YAAY,UAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,CAAA,4BAAA,EAA+B,kBAAA,CAAmB,UAAU,CAAC,CAAA,IAAA,EAAO,UAAA,CAAW,QAAA,CAAS,EAAE,CAAA,CAAE,WAAA,EAAa,CAAA,CAAA,CAAG,CAAA;AAClH,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAAA,EACpB;AACF;;;ACjBO,IAAe,cAAf,MAA2B;AAAA,EAmC9B,WAAA,CAAoB,WAA6B,aAAA,EAA8B;AAA3D,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAA6B,IAAA,IAAA,CAAA,aA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B;AACJ","file":"index.js","sourcesContent":["import { StatusCodeToString } from 'opcjs-base'\n\n/**\n * Thrown when the server signals that the current Session is no longer valid.\n *\n * Callers that want to react to a dropped session (e.g. by creating a new one\n * and retrying the operation) should catch this specific error type instead of\n * the generic `Error` class.\n *\n * Relevant OPC UA status codes:\n * - `BadSessionIdInvalid` (0x80250000) – session no longer exists on the server\n * - `BadSessionClosed` (0x80260000) – session was closed explicitly\n */\nexport class SessionInvalidError extends Error {\n readonly statusCode: number\n\n constructor(statusCode: number) {\n super(`Session is no longer valid: ${StatusCodeToString(statusCode)} (0x${statusCode.toString(16).toUpperCase()})`)\n this.name = 'SessionInvalidError'\n this.statusCode = statusCode\n }\n}\n","import { ExtensionObject, ISecureChannel, NodeId, RequestHeader, StatusCode, StatusCodeToString, StatusCodeToStringNumber } from 'opcjs-base'\n\nimport { SessionInvalidError } from '../sessions/sessionInvalidError.js'\n\nexport abstract class ServiceBase {\n\n /**\n * Validates the `serviceResult` value from a response header.\n *\n * Throws `SessionInvalidError` for session-related status codes so callers\n * can detect a dropped session and act accordingly (e.g. reconnect).\n * Throws a generic `Error` for all other non-Good codes.\n *\n * @param result - The `serviceResult` value from the response header.\n * @param context - Short description used in the error message (e.g. \"ReadRequest\").\n */\n protected checkServiceResult(result: number | undefined, context: string): void {\n if (result === undefined || result === StatusCode.Good) return\n\n if (result === StatusCode.BadSessionIdInvalid || result === StatusCode.BadSessionClosed) {\n throw new SessionInvalidError(result)\n }\n\n throw new Error(`${context} failed: ${StatusCodeToString(result)} (${StatusCodeToStringNumber(result)})`)\n }\n\n protected createRequestHeader(): RequestHeader {\n const requestHeader = new RequestHeader();\n requestHeader.authenticationToken = this.authToken;\n requestHeader.timestamp = new Date();\n requestHeader.requestHandle = 0; // will be set by secure channel\n requestHeader.returnDiagnostics = 0;\n requestHeader.auditEntryId = '';\n requestHeader.timeoutHint = 60000;\n requestHeader.additionalHeader = ExtensionObject.newEmpty();\n\n return requestHeader;\n }\n \n constructor(private authToken: NodeId, protected secureChannel: ISecureChannel){}\n}","import {\n ActivateSessionRequest, ActivateSessionResponse, ApplicationDescription, ApplicationTypeEnum,\n CloseSessionRequest, CloseSessionResponse,\n Configuration, CreateSessionRequest, CreateSessionResponse, EndpointDescription, ExtensionObject,\n getLogger,\n ISecureChannel, LocalizedText, NodeId, SignatureData, SignedSoftwareCertificate, StatusCode,\n StatusCodeToString, UserIdentityToken,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\nexport class SessionService extends ServiceBase {\n private logger = getLogger(\"services.SessionService\");\n\n /**\n * Creates a new session on the server (OPC UA Part 4, Section 5.7.2).\n * @returns The session ID, authentication token, and selected server endpoint.\n */\n async createSession(): Promise<{ sessionId: number, authToken: NodeId, endpoint: EndpointDescription }> {\n this.logger.debug(\"Creating session...\");\n\n const clientDescription = new ApplicationDescription();\n clientDescription.applicationUri = this.configuration.applicationUri;\n clientDescription.productUri = this.configuration.productUri;\n clientDescription.applicationName = new LocalizedText(undefined, this.configuration.productName);\n clientDescription.applicationType = ApplicationTypeEnum.Client;\n clientDescription.gatewayServerUri = '';\n clientDescription.discoveryProfileUri = '';\n clientDescription.discoveryUrls = new Array<string>();\n\n const request = new CreateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientDescription = clientDescription;\n request.serverUri = '';\n request.endpointUrl = this.secureChannel.getEndpointUrl();\n request.sessionName = '';\n request.clientNonce = null;\n request.clientCertificate = null;\n request.requestedSessionTimeout = 60000;\n request.maxResponseMessageSize = 0;\n\n\n // todo: verify endpoints\n // todo: check application uri in server certificate\n\n this.logger.debug(\"Sending CreateSessionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request);\n if (!response || !(response instanceof CreateSessionResponse)) {\n throw new Error(\"Invalid response type for CreateSessionRequest\");\n }\n\n const castedResponse = response as CreateSessionResponse;\n if (!castedResponse || !castedResponse.sessionId || !castedResponse.authenticationToken) {\n throw new Error(\"CreateSessionResponse missing SessionId or AuthenticationToken\");\n }\n\n const serviceResult = castedResponse.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSessionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n // The URL the client actually used to connect. Prepend the OPC UA scheme\n // prefix so it is parseable by the standard URL constructor.\n const clientConnectionUrl = new URL('opc.' + this.secureChannel.getEndpointUrl())\n const securityMode = this.secureChannel.getSecurityMode()\n const securityPolicyUri = this.secureChannel.getSecurityPolicy()\n\n // OPC UA Part 4, Section 5.4.4.2: Clients should be prepared to replace\n // the HostName and port returned in the EndpointDescription with the\n // HostName or IP address and port they used to call GetEndpoints. This\n // handles NAT/load-balancer scenarios where the server advertises internal\n // addresses that are unreachable by the client.\n const normalizeEndpointUrl = (serverEndpointUrl: string): URL => {\n const url = new URL(serverEndpointUrl)\n url.hostname = clientConnectionUrl.hostname\n url.port = clientConnectionUrl.port\n return url\n }\n\n // Match on protocol and path only; host and port are normalized away so\n // that internally-addressed endpoints are still found.\n const serverEndpoint = castedResponse?.serverEndpoints?.find(currentEndpoint => {\n const normalized = normalizeEndpointUrl(currentEndpoint.endpointUrl as string)\n return normalized.protocol === clientConnectionUrl.protocol\n && normalized.pathname === clientConnectionUrl.pathname\n && currentEndpoint.securityMode === securityMode\n && currentEndpoint.securityPolicyUri === securityPolicyUri\n })\n\n if (!serverEndpoint) {\n throw new Error(`Server endpoint ${clientConnectionUrl.toString()} not found in CreateSessionResponse`)\n }\n\n // Replace the server-reported host and port with the client's actual\n // connection address so downstream code uses the correct URL.\n serverEndpoint.endpointUrl = normalizeEndpointUrl(serverEndpoint.endpointUrl as string).toString()\n\n // NOTE: per OPC UA Part 4, Section 5.4.4.2 the client shall still verify\n // the HostName it used to open the SecureChannel against the HostName list\n // in the Server Certificate. This is deferred until certificate-based\n // security (non-None SecurityPolicy) is implemented.\n\n this.logger.debug(\"Session created with id:\", castedResponse.sessionId.identifier);\n return {\n sessionId: castedResponse.sessionId.identifier as number,\n authToken: castedResponse.authenticationToken,\n endpoint: serverEndpoint\n };\n }\n\n /**\n * Activates an existing session using the supplied identity token (OPC UA Part 4, Section 5.7.3).\n * @param identityToken - User identity token (anonymous, username/password, certificate, or issued token).\n */\n async activateSession(identityToken: UserIdentityToken): Promise<void> {\n const signatureData = new SignatureData();\n signatureData.algorithm = this.secureChannel.getSecurityPolicy();\n signatureData.signature = new Uint8Array(0);\n\n const request = new ActivateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientSignature = signatureData;\n request.clientSoftwareCertificates = new Array<SignedSoftwareCertificate>();\n request.localeIds = ['en-US'];\n request.userIdentityToken = ExtensionObject.newBinary(identityToken);\n request.userTokenSignature = signatureData;\n\n this.logger.debug(\"Sending ActivateSessionRequest...\");\n const activateResponse = await this.secureChannel.issueServiceRequest(request) as ActivateSessionResponse;\n\n const activateResult = activateResponse?.responseHeader?.serviceResult;\n if (activateResult !== undefined && activateResult !== StatusCode.Good) {\n throw new Error(`ActivateSessionRequest failed: ${StatusCodeToString(activateResult)}`);\n }\n\n this.logger.debug(\"Session activated.\");\n }\n\n /**\n * Closes the current session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * associated with this Session, freeing their resources immediately.\n * Pass false to keep Subscriptions alive for transfer to another Session.\n */\n async closeSession(deleteSubscriptions: boolean): Promise<void> {\n this.logger.debug('Sending CloseSessionRequest...')\n\n const request = new CloseSessionRequest()\n request.requestHeader = this.createRequestHeader()\n request.deleteSubscriptions = deleteSubscriptions\n\n const response = await this.secureChannel.issueServiceRequest(request) as CloseSessionResponse\n\n const result = response?.responseHeader?.serviceResult\n if (result !== undefined && result !== StatusCode.Good) {\n throw new Error(`CloseSession failed: ${StatusCodeToString(result)}`)\n }\n\n this.logger.debug('Session closed.')\n }\n\n recreate(authToken: NodeId): SessionService {\n return new SessionService(authToken, this.secureChannel, this.configuration)\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel, private configuration: Configuration) {\n super(authToken, secureChannel)\n }\n}","interface IssuerEndpointUrl {\n 'ua.resourceId': string;\n 'ua.authorityUrl': string;\n 'ua.authorityProfileUri': string;\n 'ua.tokenEndpoint': string;\n 'ua.authorizationEndpoint': string;\n 'ua.requestTypes': string[];\n 'ua.scopes': string[];\n}\n\nexport class IssuerConfiguration{\n public static newFrom(issuerEndpointUrl: IssuerEndpointUrl): IssuerConfiguration {\n return new IssuerConfiguration(\n issuerEndpointUrl['ua.resourceId'],\n issuerEndpointUrl['ua.authorityUrl'],\n issuerEndpointUrl['ua.authorityProfileUri'],\n issuerEndpointUrl['ua.tokenEndpoint'],\n issuerEndpointUrl['ua.authorizationEndpoint'],\n issuerEndpointUrl['ua.requestTypes'],\n issuerEndpointUrl['ua.scopes']\n );\n }\n \n constructor(\n public resourceId: string,\n public authorityUrl: string,\n public authorityProfileUri: string,\n public tokenEndpoint: string,\n public authorizationEndpoint: string,\n public requestTypes: string[],\n public scopes: string[]\n ){\n \n }\n}","import { EndpointDescription, IssuedIdentityToken, NodeId, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"../issuerConfiguration\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\n\nexport class Session {\n async activateSession(identity: UserIdentity): Promise<void> {\n const token = identity.getUserIdentityToken();\n const tokenType = identity.getTokenType();\n const tokenPolicy = this.endpoint.userIdentityTokens?.find(t => t.tokenType === tokenType);\n if (!tokenPolicy) {\n throw new Error(`UserIdentityToken of type ${tokenType} not supported by server`);\n }\n token.policyId = tokenPolicy.policyId;\n\n if (tokenType === UserTokenTypeEnum.IssuedToken) {\n if (!tokenPolicy.issuerEndpointUrl) {\n throw new Error(\"IssuerEndpointUrl not defined for IssuedToken\");\n }\n const issuerEndpointUrl = JSON.parse(tokenPolicy.issuerEndpointUrl)\n const issuerConfig = IssuerConfiguration.newFrom(issuerEndpointUrl);\n\n const issuerLoginCallback = identity.getIssuerLoginCallback();\n const tokenData = await issuerLoginCallback(issuerConfig);\n\n const issuerToken = token as IssuedIdentityToken;\n issuerToken.tokenData = new TextEncoder().encode(tokenData.json);\n }\n\n await this.sessionServices.activateSession(token);\n }\n\n getAuthToken(): NodeId {\n return this.authToken;\n }\n\n getSessionId(): number {\n return this.sessionId;\n }\n\n getEndpoint(): EndpointDescription {\n return this.endpoint;\n }\n\n /**\n * Closes the session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * tied to this Session. Defaults to true.\n */\n async close(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n constructor(\n public sessionId: number,\n private authToken: NodeId,\n private endpoint: EndpointDescription,\n private sessionServices: SessionService) { }\n}","import { ConfigurationClient } from \"../configurationClient\";\nimport { EndpointDescription, ISecureChannel, NodeId, UserTokenTypeEnum, getLogger } from \"opcjs-base\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\nimport { Session } from \"./session\";\n\nexport class SessionHandler {\n private sessionServices: SessionService;\n private logger = getLogger(\"sessions.SessionHandler\");\n\n async createNewSession(identity:UserIdentity) : Promise<Session>{\n const ret = await this.sessionServices.createSession();\n this.sessionServices = this.sessionServices.recreate(ret.authToken)\n\n const session = new Session(ret.sessionId, ret.authToken, ret.endpoint, this.sessionServices);\n\n // Enforce user-token type restrictions from the client security configuration\n // before activating; the endpoint is now known from CreateSession.\n this.validateUserTokenPolicy(identity, ret.endpoint)\n\n await session.activateSession(identity);\n return session;\n }\n\n /**\n * Attempts to reactivate an existing OPC UA session on the current (new) SecureChannel\n * without calling CreateSession first (OPC UA Part 4, Section 5.7.3).\n *\n * This is the preferred recovery path when the SecureChannel drops but the server-side\n * session has not yet timed out: only a new channel is needed, not a new session.\n *\n * @returns The reactivated Session if ActivateSession succeeded, or `null` if the server\n * rejected the request (e.g. the session had already expired).\n */\n async tryActivateExistingSession(\n existingAuthToken: NodeId,\n existingSessionId: number,\n existingEndpoint: EndpointDescription,\n identity: UserIdentity,\n ): Promise<Session | null> {\n // Build a SessionService bound to the existing auth token so the RequestHeader\n // carries it and the server can correlate the ActivateSession to the right session.\n const serviceForExistingSession = this.sessionServices.recreate(existingAuthToken)\n try {\n const session = new Session(existingSessionId, existingAuthToken, existingEndpoint, serviceForExistingSession)\n await session.activateSession(identity)\n return session\n } catch (err) {\n this.logger.debug('ActivateSession for existing session failed:', err)\n return null\n }\n }\n\n /**\n * Closes the active session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - Forwarded to CloseSessionRequest. Defaults to true.\n */\n async closeSession(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n /**\n * Validates the requested user-identity token type against:\n * 1. The `allowedUserTokenTypes` from the client security configuration — the\n * client has explicitly restricted which token types it will use.\n * 2. The token policies advertised by the server endpoint — verifies that the\n * server actually supports at least one of the allowed types.\n *\n * Throws with a descriptive message if either check fails.\n */\n private validateUserTokenPolicy(identity: UserIdentity, endpoint: EndpointDescription): void {\n const allowedTypes = this.configuration.securityConfiguration?.allowedUserTokenTypes\n if (!allowedTypes) return // no restriction configured\n\n const requestedType = identity.getTokenType()\n\n // 1. Client-side restriction: the chosen identity must be an allowed type.\n if (!allowedTypes.includes(requestedType)) {\n throw new Error(\n `User token type '${UserTokenTypeEnum[requestedType]}' is not permitted by the ` +\n `client security configuration. Allowed types: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n\n // 2. Server-side availability: at least one allowed type must be offered.\n const serverTypes = endpoint.userIdentityTokens?.map(p => p.tokenType) ?? []\n const intersection = allowedTypes.filter(t => serverTypes.includes(t))\n if (intersection.length === 0) {\n throw new Error(\n `Server endpoint does not offer any user token type from the allowed list: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}. ` +\n `Server offers: ${serverTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n }\n\n constructor(secureChannel:ISecureChannel, private configuration: ConfigurationClient) {\n this.sessionServices = new SessionService(NodeId.newTwoByte(0), secureChannel, configuration);\n }\n}","import type { MessageSecurityModeEnum, UserTokenTypeEnum } from 'opcjs-base'\n\n/** URI for the SecurityPolicy None profile. */\nexport const SECURITY_POLICY_NONE_URI = 'http://opcfoundation.org/UA/SecurityPolicy#None'\n\n/**\n * How the client should handle a server certificate it cannot verify.\n *\n * - `'reject'` — abort the connection (secure default when `trustedCAs` is configured).\n * - `'trust'` — accept any certificate without verification (development convenience;\n * **insecure in production**).\n *\n * @note Enforcement is deferred until certificate-based security policies are\n * implemented. The value is stored and will be honoured when that support lands.\n */\nexport type UnknownCertificatePolicy = 'reject' | 'trust'\n\n/**\n * OPC UA client security configuration (OPC UA Part 2, Security Administration CU).\n *\n * Restricts which security options the client will accept when connecting to or\n * negotiating with a server. All fields are optional; omitting a field applies\n * the permissive default so that existing callers need no changes.\n *\n * @example\n * ```ts\n * const config = ConfigurationClient.getSimple('MyApp', 'MyCompany')\n * config.securityConfiguration = {\n * allowedUserTokenTypes: [UserTokenTypeEnum.UserName],\n * allowSecurityPolicyNone: false, // require an encrypted channel\n * }\n * ```\n */\nexport type SecurityConfiguration = {\n /**\n * User-identity-token types the client is willing to accept.\n *\n * When set, `connect()` will throw if:\n * - The supplied `UserIdentity`'s token type is not in this list, OR\n * - The server endpoint does not offer any type from this list.\n *\n * Default: all token types are accepted (no restriction).\n */\n allowedUserTokenTypes?: UserTokenTypeEnum[]\n\n /**\n * Allow connecting when the negotiated SecurityPolicy is `None` (unencrypted,\n * unsigned channel).\n *\n * Set to `false` to require a secure channel — `connect()` will throw rather\n * than establish a cleartext connection.\n *\n * Currently the only supported security policy is `None`. Setting this to `false`\n * will therefore cause `connect()` to always throw until non-None policies are\n * added to this client implementation.\n *\n * Default: `true` (SecurityPolicy None is permitted).\n */\n allowSecurityPolicyNone?: boolean\n\n /**\n * Required `MessageSecurityMode` for the secure channel.\n *\n * When set, `connect()` verifies that the channel's negotiated mode matches\n * this value and throws otherwise.\n *\n * Currently only `MessageSecurityModeEnum.None` is supported.\n *\n * Default: no requirement (any mode is accepted).\n */\n messageSecurityMode?: MessageSecurityModeEnum\n\n /**\n * DER-encoded X.509 trusted CA certificates used to verify the server's\n * application instance certificate.\n *\n * @note Reserved for future use. Certificate verification is not yet implemented.\n * Providing this field has no effect until non-None security policies land.\n */\n trustedCAs?: Uint8Array[]\n\n /**\n * How to handle a server certificate that cannot be verified against `trustedCAs`.\n *\n * - `'reject'` — refuse the connection (default when `trustedCAs` is provided).\n * - `'trust'` — accept any certificate (development only; insecure in production).\n *\n * @note Reserved for future use. Has no effect until certificate verification is\n * implemented alongside non-None security policies.\n */\n unknownCertificatePolicy?: UnknownCertificatePolicy\n}\n","// according to https://reference.opcfoundation.org/Core/Part6/v105/docs/A.1\n// see also: https://reference.opcfoundation.org/Core/Part4/v105/docs/7.24.1#Table154\n\nexport const AttrIdNodeId = 1\nexport const AttrIdNodeClass = 2\nexport const AttrIdBrowseName = 3\nexport const AttrIdDisplayName = 4\nexport const AttrIdDescription = 5\nexport const AttrIdWriteMask = 6\nexport const AttrIdUserWriteMask = 7\nexport const AttrIdIsAbstract = 8\nexport const AttrIdSymmetric = 9\nexport const AttrIdInverseName = 10\nexport const AttrIdContainsNoLoops = 11\nexport const AttrIdEventNotifier = 12\nexport const AttrIdValue = 13\nexport const AttrIdDataType = 14\nexport const AttrIdValueRank = 15\nexport const AttrIdArrayDimensions = 16\nexport const AttrIdAccessLevel = 17\nexport const AttrIdUserAccessLevel = 18\nexport const AttrIdMinimumSamplingInterval = 19\nexport const AttrIdHistorizing = 20\nexport const AttrIdExecutable = 21\nexport const AttrIdUserExecutable = 22\nexport const AttrIdDataTypeDefinition = 23\nexport const AttrIdRolePermissions = 24\nexport const AttrIdUserRolePermissions = 25\nexport const AttrIdAccessRestrictions = 26\nexport const AttrIdAccessLevelEx = 27\n","import {\n getLogger, ISecureChannel, NodeId, QualifiedName, ReadRequest, ReadResponse, ReadValueId,\n StatusCode, TimestampsToReturnEnum,\n} from 'opcjs-base'\n\nimport { AttrIdValue } from './attributeServiceAttributes.js'\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.10.2\nexport class AttributeService extends ServiceBase {\n private logger = getLogger(\"services.AttributeService\");\n\n /**\n * Reads the Value attribute of one or more Nodes (OPC UA Part 4, Section 5.10.2).\n * @param nodeIds - NodeIds of the Nodes to read.\n * @param maxAge - Maximum age of the cached value in milliseconds the server may return. 0 = always current value.\n * @param timestampsToReturn - Which timestamps to include in results. Default: Source.\n * @returns Array of results containing value and raw status code number, one per requested NodeId.\n */\n async ReadValue(\n nodeIds: NodeId[],\n maxAge: number = 0,\n timestampsToReturn: TimestampsToReturnEnum = TimestampsToReturnEnum.Source,\n ): Promise<{ statusCode: number, value: unknown }[]> {\n const readValueIds = nodeIds.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n return readValueId;\n });\n\n const request = new ReadRequest();\n request.requestHeader = this.createRequestHeader();\n request.maxAge = maxAge;\n request.timestampsToReturn = timestampsToReturn;\n request.nodesToRead = readValueIds;\n\n this.logger.debug(\"Sending ReadRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as ReadResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'ReadRequest')\n\n const results = new Array<{ statusCode: number, value: unknown }>();\n for (const dataValue of response.results ?? []) {\n results.push({\n statusCode: dataValue.statusCode ?? StatusCode.Good,\n value: dataValue.value as unknown,\n });\n }\n return results;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","export class ReadValueResult {\n constructor(public value: unknown, public statusCode: number) {}\n}","import { NodeId } from \"opcjs-base\";\n\nexport class SubscriptionHandlerEntry{\n constructor(\n public subscriptionId:number,\n public handle: number, \n public id:NodeId, \n public callback: (data: { id: NodeId, value: unknown }[]) => void\n ){}\n}","import {\n DataChangeNotification,\n ExpandedNodeId,\n getLogger,\n NodeId,\n StatusChangeNotification,\n SubscriptionAcknowledgement,\n} from 'opcjs-base'\n\nimport { MonitoredItemService } from './services/monitoredItemService'\nimport { SubscriptionService } from './services/subscriptionService'\nimport { SubscriptionHandlerEntry } from './subscriptionHandlerEntry'\n\n// OPC UA Part 4, §5.14 — Subscriptions and Monitored Items\n\n/** Node type IDs for notification payloads (OPC UA Part 4, §7.21) */\nconst NODE_ID_DATA_CHANGE_NOTIFICATION = 811\nconst NODE_ID_STATUS_CHANGE_NOTIFICATION = 818\n\nexport class SubscriptionHandler {\n private logger = getLogger('SubscriptionHandler')\n private entries = new Array<SubscriptionHandlerEntry>()\n private nextHandle = 0\n private isRunning = false\n\n /** Returns true when at least one subscription is active and the publish loop is running. */\n hasActiveSubscription(): boolean {\n return this.isRunning && this.entries.length > 0\n }\n\n async subscribe(ids: NodeId[], callback: (data: { id: NodeId; value: unknown }[]) => void) {\n if (this.entries.length > 0) {\n throw new Error('Subscribing more than once is not implemented')\n }\n\n const subscriptionId = await this.subscriptionService.createSubscription()\n const items = []\n for (const id of ids) {\n const entry = new SubscriptionHandlerEntry(subscriptionId, this.nextHandle++, id, callback)\n this.entries.push(entry)\n items.push({ id, handle: entry.handle })\n }\n await this.monitoredItemService.createMonitoredItems(subscriptionId, items)\n\n // Start the publish loop with no pending acknowledgements.\n this.isRunning = true\n void this.publishLoop([])\n }\n\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n private async publishLoop(pendingAcknowledgements: SubscriptionAcknowledgement[]): Promise<void> {\n if (!this.isRunning) return\n\n let response\n try {\n response = await this.subscriptionService.publish(pendingAcknowledgements)\n } catch (err) {\n this.logger.error(`Publish failed, stopping publish loop: ${err}`)\n this.isRunning = false\n return\n }\n\n const { subscriptionId, availableSequenceNumbers, moreNotifications, notificationMessage } = response\n const notificationDatas = notificationMessage?.notificationData ?? []\n const seqNumber = notificationMessage?.sequenceNumber\n\n // Build acknowledgements for the next publish request.\n // Per spec: only acknowledge sequence numbers that are in availableSequenceNumbers\n // and only for real notification messages (not keep-alive, which have empty notificationData).\n const nextAcknowledgements: SubscriptionAcknowledgement[] = []\n const isKeepAlive = notificationDatas.length === 0\n\n if (!isKeepAlive && seqNumber !== undefined) {\n // Acknowledge only if the server still lists this sequence number as available.\n const isAvailable = !availableSequenceNumbers || availableSequenceNumbers.includes(seqNumber)\n if (isAvailable) {\n const ack = new SubscriptionAcknowledgement()\n ack.subscriptionId = subscriptionId\n ack.sequenceNumber = seqNumber\n nextAcknowledgements.push(ack)\n }\n }\n\n // Dispatch notifications to registered callbacks.\n for (const notificationData of notificationDatas) {\n const decodedData = notificationData.data\n const rawTypeId = notificationData.typeId\n const typeNodeId = rawTypeId instanceof ExpandedNodeId ? rawTypeId.nodeId : rawTypeId\n\n if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_DATA_CHANGE_NOTIFICATION) {\n const dataChangeNotification = decodedData as DataChangeNotification\n for (const item of dataChangeNotification.monitoredItems) {\n const entry = this.entries.find(e => e.handle === item.clientHandle)\n entry?.callback([{ id: entry.id, value: item.value.value?.value }])\n }\n } else if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_STATUS_CHANGE_NOTIFICATION) {\n // The server notifies us the subscription state has changed (e.g. expired, closed).\n const statusChange = decodedData as StatusChangeNotification\n this.logger.warn(\n `Subscription ${subscriptionId} status changed: 0x${statusChange.status?.toString(16).toUpperCase()}`,\n )\n this.isRunning = false\n return\n } else {\n this.logger.warn(\n `Notification data type ${typeNodeId.namespace}:${typeNodeId.identifier} is not supported.`,\n )\n }\n }\n\n // Per spec: if moreNotifications is true the server has more queued data — re-publish immediately\n // without delay so the server's queue drains before its lifetime counter expires.\n // Otherwise, schedule the next publish after a short yield to avoid a tight synchronous loop.\n if (moreNotifications) {\n void this.publishLoop(nextAcknowledgements)\n } else {\n setTimeout(() => void this.publishLoop(nextAcknowledgements), 0)\n }\n }\n\n constructor(\n private subscriptionService: SubscriptionService,\n private monitoredItemService: MonitoredItemService,\n ) {}\n}","import {\n CreateSubscriptionRequest, CreateSubscriptionResponse, getLogger, ISecureChannel, NodeId,\n PublishRequest, PublishResponse, StatusCode, StatusCodeToString, SubscriptionAcknowledgement,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\n/** Options for creating a subscription. All fields are optional; server will revise requested values. */\nexport interface CreateSubscriptionOptions {\n /** Requested publishing interval in milliseconds. Default: 2000. */\n requestedPublishingInterval?: number;\n /** Requested lifetime count (number of publishing intervals before subscription times out). Default: 360000. */\n requestedLifetimeCount?: number;\n /** Requested max keep-alive count. Default: 60000. */\n requestedMaxKeepAliveCount?: number;\n /** Maximum number of notifications per publish response. 0 = no limit. Default: 200. */\n maxNotificationsPerPublish?: number;\n /** Subscription priority relative to other subscriptions. Default: 1. */\n priority?: number;\n}\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14\nexport class SubscriptionService extends ServiceBase {\n private logger = getLogger(\"services.SubscriptionService\");\n\n /**\n * Creates a new subscription on the server (OPC UA Part 4, Section 5.14.2).\n * @param options - Optional subscription parameters; server revises all values.\n * @returns The server-assigned subscription ID.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.2\n async createSubscription(options?: CreateSubscriptionOptions): Promise<number> {\n const request = new CreateSubscriptionRequest();\n request.requestHeader = this.createRequestHeader();\n request.requestedPublishingInterval = options?.requestedPublishingInterval ?? 2000;\n request.requestedLifetimeCount = options?.requestedLifetimeCount ?? 360000;\n request.requestedMaxKeepAliveCount = options?.requestedMaxKeepAliveCount ?? 60000;\n request.maxNotificationsPerPublish = options?.maxNotificationsPerPublish ?? 200;\n request.publishingEnabled = true;\n request.priority = options?.priority ?? 1;\n\n this.logger.debug(\"Sending CreateSubscriptionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateSubscriptionResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSubscriptionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(`Subscription created with id: ${response.subscriptionId}`);\n return response.subscriptionId;\n }\n\n /**\n * Sends a publish request to receive notifications from active subscriptions (OPC UA Part 4, Section 5.14.5).\n * @param acknowledgements - Sequence numbers to acknowledge from previous publish responses.\n * @returns The publish response containing notification data.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n async publish(acknowledgements: SubscriptionAcknowledgement[]): Promise<PublishResponse> {\n const request = new PublishRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionAcknowledgements = acknowledgements;\n\n this.logger.debug(\"Sending PublishRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as PublishResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`PublishRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(\"Received PublishResponse.\");\n return response;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import {\n CreateMonitoredItemsRequest, CreateMonitoredItemsResponse,\n ExtensionObject, getLogger, ISecureChannel, MonitoredItemCreateRequest, MonitoringModeEnum,\n MonitoringParameters, NodeId, QualifiedName, ReadValueId, StatusCode, StatusCodeToString,\n TimestampsToReturnEnum,\n} from \"opcjs-base\";\nimport { AttrIdValue } from \"./attributeServiceAttributes\";\nimport { ServiceBase } from \"./serviceBase\";\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.13.2\nexport class MonitoredItemService extends ServiceBase {\n private logger = getLogger(\"services.MonitoredItemService\");\n\n /**\n * Creates monitored items within a subscription (OPC UA Part 4, Section 5.13.2).\n * @param subscriptionId - ID of the subscription to add monitored items to.\n * @param ids - Array of NodeIds and client handles identifying the items to monitor.\n * @param samplingInterval - Requested sampling interval in milliseconds. -1 = use subscription publishing interval.\n * @param queueSize - Requested queue size for each monitored item.\n */\n async createMonitoredItems(\n subscriptionId: number,\n ids: { id: NodeId, handle: number }[],\n samplingInterval: number = 1000,\n queueSize: number = 100,\n ): Promise<void> {\n const items = ids.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni.id;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n\n const monitoringParameters = new MonitoringParameters();\n monitoringParameters.clientHandle = ni.handle;\n monitoringParameters.samplingInterval = samplingInterval;\n monitoringParameters.filter = ExtensionObject.newEmpty();\n monitoringParameters.queueSize = queueSize;\n monitoringParameters.discardOldest = true;\n\n const monitoredItemCreateRequest = new MonitoredItemCreateRequest();\n monitoredItemCreateRequest.itemToMonitor = readValueId;\n monitoredItemCreateRequest.monitoringMode = MonitoringModeEnum.Reporting;\n monitoredItemCreateRequest.requestedParameters = monitoringParameters;\n return monitoredItemCreateRequest;\n });\n\n const request = new CreateMonitoredItemsRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionId = subscriptionId;\n request.timestampsToReturn = TimestampsToReturnEnum.Source;\n request.itemsToCreate = items;\n\n this.logger.debug(\"Sending CreateMonitoredItemsRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateMonitoredItemsResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateMonitoredItemsRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n for (const result of response.results ?? []) {\n if (result.statusCode !== undefined && result.statusCode !== StatusCode.Good) {\n this.logger.warn(`Failed to create monitored item: ${StatusCodeToString(result.statusCode)}`);\n }\n }\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import { CallMethodRequest, CallRequest, CallResponse, getLogger, ISecureChannel, NodeId, StatusCode } from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.11.2\nexport class MethodService extends ServiceBase {\n private logger = getLogger(\"services.MethodService\");\n\n /**\n * Calls one or more methods on the server (OPC UA Part 4, Section 5.11.2).\n * @param methodsToCall - Array of CallMethodRequest describing each method to invoke.\n * @returns Array of results containing output argument values and raw status code number, one per requested method.\n */\n async call(methodsToCall: CallMethodRequest[]): Promise<{ statusCode: number, value: unknown[] }[]> {\n const request = new CallRequest();\n request.requestHeader = this.createRequestHeader();\n request.methodsToCall = methodsToCall;\n\n this.logger.debug(\"Sending CallRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CallResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'CallRequest')\n\n return response.results.map(result => ({\n statusCode: result.statusCode ?? StatusCode.Good,\n value: result.outputArguments.map(arg => arg.value),\n }));\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","export class CallMethodResult {\n constructor(public values: unknown[], public statusCode: number) {}\n}","import {\n BrowseDescription, BrowseNextRequest, BrowseNextResponse,\n BrowseRequest, BrowseResponse, BrowseResult,\n getLogger, ISecureChannel, NodeId, UaByteString, ViewDescription,\n} from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.9\nexport class BrowseService extends ServiceBase {\n private logger = getLogger(\"services.BrowseService\");\n\n /**\n * Browses one or more Nodes and returns their References (OPC UA Part 4, Section 5.9.2).\n * @param nodesToBrowse - Array of BrowseDescriptions specifying nodes and filter criteria.\n * @returns Array of BrowseResult, one per requested node.\n */\n async browse(nodesToBrowse: BrowseDescription[]): Promise<BrowseResult[]> {\n const view = new ViewDescription();\n view.viewId = NodeId.newNumeric(0, 0);\n view.timestamp = new Date(-11644473600000); // OPC UA MinDateTime (ticks=0)\n view.viewVersion = 0;\n\n const request = new BrowseRequest();\n request.requestHeader = this.createRequestHeader();\n request.view = view;\n request.requestedMaxReferencesPerNode = 0;\n request.nodesToBrowse = nodesToBrowse;\n\n this.logger.debug(\"Sending BrowseRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseRequest')\n\n return response.results ?? []\n }\n\n /**\n * Continues a Browse operation using continuation points (OPC UA Part 4, Section 5.9.3).\n * @param continuationPoints - Continuation points returned by a prior Browse or BrowseNext call.\n * @param releaseContinuationPoints - If true, releases the continuation points without returning results.\n * @returns Array of BrowseResult, one per continuation point.\n */\n async browseNext(\n continuationPoints: UaByteString[],\n releaseContinuationPoints: boolean,\n ): Promise<BrowseResult[]> {\n const request = new BrowseNextRequest();\n request.requestHeader = this.createRequestHeader();\n request.releaseContinuationPoints = releaseContinuationPoints;\n request.continuationPoints = continuationPoints;\n\n this.logger.debug(\"Sending BrowseNextRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseNextResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseNextRequest')\n\n return response.results ?? []\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","import {\n ExpandedNodeId, LocalizedText, NodeClassEnum,\n NodeId, QualifiedName\n} from \"opcjs-base\";\n\nexport class BrowseNodeResult {\n constructor(\n public referenceTypeId: NodeId,\n public isForward: boolean,\n public nodeId: ExpandedNodeId,\n public browseName: QualifiedName,\n public displayName: LocalizedText,\n public nodeClass: NodeClassEnum,\n public typeDefinition: ExpandedNodeId,\n ) {}\n}\n","import {\n NodeId,\n ISecureChannel,\n TcpConnectionHandler,\n SecureChannelFacade,\n SecureChannelContext,\n SecureChannelMessageEncoder,\n SecureChannelTypeDecoder,\n SecureChannelMessageDecoder,\n SecureChannelTypeEncoder,\n initLoggerProvider,\n TcpMessageInjector,\n TcpMessageDecoupler,\n getLogger,\n WebSocketFascade,\n WebSocketReadableStream,\n WebSocketWritableStream,\n SecureChannelChunkReader,\n SecureChannelChunkWriter,\n CallMethodRequest,\n Variant,\n BrowseDescription,\n BrowseDirectionEnum,\n BrowseResultMaskEnum,\n ReferenceDescription,\n ILogger,\n} from 'opcjs-base'\n\nimport { SessionHandler } from './sessions/sessionHandler.js'\nimport { Session } from './sessions/session.js'\nimport { SessionInvalidError } from './sessions/sessionInvalidError.js'\nimport { SECURITY_POLICY_NONE_URI } from './securityConfiguration.js'\nimport { AttributeService } from './services/attributeService.js'\nimport { ReadValueResult } from './readValueResult.js'\nimport { SubscriptionHandler } from './subscriptionHandler.js'\nimport { SubscriptionService } from './services/subscriptionService.js'\nimport { MonitoredItemService } from './services/monitoredItemService.js'\nimport { UserIdentity } from './userIdentity.js'\nimport { ConfigurationClient } from './configurationClient.js'\nimport { MethodService } from './services/methodService.js'\nimport { CallMethodResult } from './callMethodResult.js'\nimport { BrowseService } from './services/browseService.js'\nimport { BrowseNodeResult } from './browseNodeResult.js'\nimport { CallMethodArgument } from './callMethodArgument.js'\n\n/** NodeId of Server_ServerStatus (ns=0, i=2256) — a cheap server-side read used for session keep-alive. */\nconst SERVER_STATUS_NODE_ID = NodeId.newNumeric(0, 2256)\n/**\n * How often to read the server when no subscription is active (ms).\n * Must be shorter than the server's revisedSessionTimeout (default: 60 000 ms).\n */\nconst KEEP_ALIVE_INTERVAL_MS = 25_000\n\nexport class Client {\n private endpointUrl: string\n private attributeService?: AttributeService\n private methodService?: MethodService\n private browseService?: BrowseService\n private session?: Session\n private subscriptionHandler?: SubscriptionHandler\n private logger: ILogger\n // Stored after connect() so that refreshSession() and disconnect() can use them.\n private secureChannel?: ISecureChannel\n private secureChannelFacade?: SecureChannelFacade\n private ws?: WebSocketFascade\n private sessionHandler?: SessionHandler\n private keepAliveTimer?: ReturnType<typeof setInterval>\n\n getSession(): Session {\n if (!this.session) {\n throw new Error('No session available')\n }\n return this.session\n }\n\n /**\n * (Re-)initialises all session-scoped services from the current `this.session`.\n * Called both after the initial `connect()` and after a session refresh.\n */\n private initServices(): void {\n const authToken = this.session!.getAuthToken()\n const sc = this.secureChannel!\n this.attributeService = new AttributeService(authToken, sc)\n this.methodService = new MethodService(authToken, sc)\n this.browseService = new BrowseService(authToken, sc)\n this.subscriptionHandler = new SubscriptionHandler(\n new SubscriptionService(authToken, sc),\n new MonitoredItemService(authToken, sc),\n )\n }\n\n /**\n * Executes `fn` and, if it throws a `SessionInvalidError`, creates a fresh\n * session and retries the operation exactly once.\n *\n * This covers the reactive case: a service call reveals that the server has\n * already dropped the session (e.g. due to timeout). The new session is\n * established transparently before re-running the original operation.\n *\n * For any other error (e.g. transport-level failures when the SecureChannel\n * drops), this method attempts to reconnect the channel and reactivate the\n * existing session first — falling back to a brand-new session only when\n * reactivation fails — before retrying the operation once.\n */\n private async withSessionRefresh<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof SessionInvalidError) {\n this.logger.info(`Session invalid (${err.statusCode.toString(16)}), refreshing session...`)\n this.session = await this.sessionHandler!.createNewSession(this.identity)\n this.initServices()\n this.logger.info('Session refreshed, retrying operation.')\n\n // Retry once with the new session. If it fails again the error propagates.\n return await fn()\n }\n\n // Possibly a channel drop: attempt reconnect + ActivateSession on existing session\n // before giving up and creating a brand-new session (OPC UA Part 4 Session Auto Reconnect).\n this.logger.info('Service call failed, attempting channel reconnect and session reactivation...')\n try {\n await this.reconnectAndReactivate()\n this.initServices()\n this.logger.info('Reconnected successfully, retrying operation.')\n } catch (reconnectErr) {\n // Reconnect itself failed; surface the original error so the caller\n // gets a meaningful diagnostic (the reconnect error is logged separately).\n this.logger.warn('Channel reconnect failed:', reconnectErr)\n throw err\n }\n\n // Retry once after a successful reconnect. If it fails again the error propagates.\n return await fn()\n }\n }\n\n /**\n * Starts a periodic keep-alive timer that reads Server_ServerStatus when no subscription is\n * active. OPC UA Part 4, Section 5.7.1 requires clients to keep the session alive; when no\n * subscription Publish loop is running this is the only mechanism that does so.\n */\n private startKeepAlive(): void {\n this.keepAliveTimer = setInterval(() => {\n if (this.subscriptionHandler?.hasActiveSubscription()) {\n // The subscription publish loop is already keeping the session alive.\n return\n }\n if (this.attributeService) {\n void this.attributeService.ReadValue([SERVER_STATUS_NODE_ID]).catch((err) => {\n this.logger.warn('Keep-alive read failed:', err)\n })\n }\n }, KEEP_ALIVE_INTERVAL_MS)\n }\n\n private stopKeepAlive(): void {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n }\n\n async connect(): Promise<void> {\n const { ws, sc } = await this.openTransportAndChannel()\n\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n\n this.logger.debug('Creating session...')\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.debug('Session created.')\n\n this.logger.debug('Initializing services...')\n this.initServices()\n this.startKeepAlive()\n }\n\n /**\n * Builds the full WebSocket → TCP → SecureChannel pipeline and returns the\n * two objects needed to drive it: the raw WebSocket facade (for teardown)\n * and the SecureChannelFacade (for service requests/session management).\n *\n * Extracted from `connect()` so it can be reused by `reconnectAndReactivate()`.\n */\n private async openTransportAndChannel(): Promise<{ ws: WebSocketFascade; sc: SecureChannelFacade }> {\n const wsOptions = { endpoint: this.endpointUrl }\n const ws = new WebSocketFascade(wsOptions);\n const webSocketReadableStream = new WebSocketReadableStream(ws, 1000);\n const webSocketWritableStream = new WebSocketWritableStream(ws);\n\n const scContext = new SecureChannelContext(this.endpointUrl);\n const tcpMessageInjector = new TcpMessageInjector();\n const tcpConnectionHandler = new TcpConnectionHandler(tcpMessageInjector, scContext);\n const tcpMessageDecoupler = new TcpMessageDecoupler(tcpConnectionHandler.onTcpMessage.bind(tcpConnectionHandler));\n const scMessageEncoder = new SecureChannelMessageEncoder(scContext);\n const scTypeDecoder = new SecureChannelTypeDecoder(\n this.configuration.decoder,\n );\n const scMessageDecoder = new SecureChannelMessageDecoder(scContext);\n const scTypeEncoder = new SecureChannelTypeEncoder(\n this.configuration.encoder,\n );\n const scChunkWriter = new SecureChannelChunkWriter(scContext);\n const scChunkReader = new SecureChannelChunkReader(scContext);\n\n webSocketReadableStream.pipeTo(tcpMessageDecoupler.writable);\n tcpMessageDecoupler.readable.pipeTo(scMessageDecoder.writable);\n scMessageDecoder.readable.pipeTo(scChunkReader.writable);\n scChunkReader.readable.pipeTo(scTypeDecoder.writable);\n\n scTypeEncoder.readable.pipeTo(scChunkWriter.writable);\n scChunkWriter.readable.pipeTo(scMessageEncoder.writable);\n scMessageEncoder.readable.pipeTo(tcpMessageInjector.writable);\n tcpMessageInjector.readable.pipeTo(webSocketWritableStream);\n\n const sc = new SecureChannelFacade(scContext, scTypeDecoder, scTypeEncoder);\n\n let connected = false;\n while (!connected) {\n this.logger.debug(`Connecting to OPC UA server at ${this.endpointUrl}...`);\n await ws.connect();\n this.logger.debug(\"WebSocket connection established, now establishing TCP connection...\");\n connected = await tcpConnectionHandler.connect(this.endpointUrl);\n\n if (!connected) {\n this.logger.info(\"Connection failed, retrying in 2 seconds...\");\n await new Promise((resolve) => setTimeout(resolve, 2000));\n }\n }\n this.logger.info(\"Connected to OPC UA server.\");\n\n this.logger.debug(\"Opening secure channel...\");\n await sc.openSecureChannel();\n this.logger.debug(\"Secure channel established.\");\n\n // Enforce any channel-level security requirements before proceeding.\n this.enforceChannelSecurityConfig(sc);\n\n return { ws, sc };\n }\n\n /**\n * Validates the negotiated channel's security policy and mode against the\n * client's `SecurityConfiguration` (OPC UA Part 2, Security Administration).\n *\n * Throws if:\n * - `allowSecurityPolicyNone` is `false` and the channel uses SecurityPolicy None.\n * - `messageSecurityMode` is set and does not match the channel's actual mode.\n */\n private enforceChannelSecurityConfig(sc: SecureChannelFacade): void {\n const config = this.configuration.securityConfiguration\n if (!config) return\n\n const negotiatedPolicy = sc.getSecurityPolicy()\n const negotiatedMode = sc.getSecurityMode()\n\n if (config.allowSecurityPolicyNone === false && negotiatedPolicy === SECURITY_POLICY_NONE_URI) {\n throw new Error(\n 'Connection refused: SecurityPolicy None is disabled by the client security configuration. ' +\n 'Only SecurityPolicy None is currently supported by this client implementation.',\n )\n }\n\n if (config.messageSecurityMode !== undefined && config.messageSecurityMode !== negotiatedMode) {\n throw new Error(\n `Connection refused: negotiated MessageSecurityMode ${negotiatedMode} does not match ` +\n `the required mode ${config.messageSecurityMode} from the security configuration.`,\n )\n }\n }\n\n /**\n * Tears down the current (dead) channel and establishes a fresh one, then\n * attempts to recover the existing OPC UA session via ActivateSession before\n * falling back to a full CreateSession + ActivateSession.\n *\n * OPC UA Part 4, Section 5.7.1 / Session Client Auto Reconnect conformance unit:\n * When the SecureChannel drops but the server-side session has not yet timed\n * out, the client SHOULD reuse the existing session by calling ActivateSession\n * on the new channel. Only if that fails should the client create a new session.\n */\n private async reconnectAndReactivate(): Promise<void> {\n this.logger.info('Tearing down dead channel before reconnect...')\n\n // Close the old channel and WebSocket (best effort — they may already be dead).\n try { this.secureChannelFacade?.close() } catch { /* already dead */ }\n try { this.ws?.close() } catch { /* already dead */ }\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n this.ws = undefined\n\n const { ws, sc } = await this.openTransportAndChannel()\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n\n // Attempt to reactivate the existing session on the new channel.\n if (this.session) {\n const reactivated = await this.sessionHandler.tryActivateExistingSession(\n this.session.getAuthToken(),\n this.session.getSessionId(),\n this.session.getEndpoint(),\n this.identity,\n )\n if (reactivated !== null) {\n this.session = reactivated\n this.logger.info('Existing session successfully reactivated on new channel.')\n return\n }\n this.logger.info('ActivateSession for existing session failed; creating a fresh session...')\n }\n\n // Fall back: full CreateSession + ActivateSession.\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.info('Fresh session established on new channel.')\n }\n\n /**\n * Gracefully disconnects from the OPC UA server.\n *\n * Sequence per OPC UA Part 4, Section 5.7.4:\n * 1. CloseSession (deleteSubscriptions=true) so the server frees all resources.\n * 2. Close the SecureChannel, which cancels the pending token-renewal timer.\n * 3. Close the WebSocket transport.\n *\n * CloseSession errors are swallowed so transport teardown always completes even\n * when the session has already expired on the server side.\n */\n async disconnect(): Promise<void> {\n this.logger.info('Disconnecting from OPC UA server...')\n this.stopKeepAlive()\n\n if (this.session && this.sessionHandler) {\n try {\n await this.sessionHandler.closeSession(true)\n } catch (err) {\n // Session may already be gone on the server; log and continue teardown.\n this.logger.warn('CloseSession failed (continuing teardown):', err)\n }\n this.session = undefined\n }\n\n this.secureChannelFacade?.close()\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n\n this.ws?.close()\n this.ws = undefined\n\n this.logger.info('Disconnected.')\n }\n\n async read(ids: NodeId[]): Promise<ReadValueResult[]> {\n return this.withSessionRefresh(async () => {\n const result = await this.attributeService?.ReadValue(ids)\n return result?.map(r => new ReadValueResult(r.value, r.statusCode)) ?? []\n })\n }\n\n /**\n * Method for calling a single method on the server.\n * @param objectId - NodeId of the Object that owns the method.\n * @param methodId - NodeId of the Method to invoke.\n * @param inputArguments - Input argument Variants (default: empty).\n * @returns The CallMethodResult for the invoked method.\n */\n async callMethod(\n objectId: NodeId,\n methodId: NodeId,\n inputArguments: CallMethodArgument[] = []\n ): Promise<CallMethodResult> {\n return this.withSessionRefresh(async () => {\n const request = new CallMethodRequest()\n request.objectId = objectId\n request.methodId = methodId\n request.inputArguments = inputArguments.map(arg => Variant.newFrom(arg))\n\n const responses = await this.methodService!.call([request])\n const response = responses[0]\n return new CallMethodResult(response.value, response.statusCode)\n })\n }\n\n async browse(\n nodeId: NodeId,\n recursive: boolean = false,\n ): Promise<BrowseNodeResult[]> {\n return this.withSessionRefresh(() => {\n const visited = new Set<string>()\n return this.browseRecursive(nodeId, recursive, visited)\n })\n }\n\n private async browseRecursive(\n nodeId: NodeId,\n recursive: boolean,\n visited: Set<string>,\n ): Promise<BrowseNodeResult[]> {\n const nodeKey = `${nodeId.namespace}:${nodeId.identifier}`;\n if (visited.has(nodeKey)) {\n return [];\n }\n visited.add(nodeKey);\n\n const description = new BrowseDescription();\n description.nodeId = nodeId;\n description.browseDirection = BrowseDirectionEnum.Forward;\n description.referenceTypeId = NodeId.newNumeric(0, 33); // HierarchicalReferences\n description.includeSubtypes = true;\n description.nodeClassMask = 0; // all node classes\n description.resultMask = BrowseResultMaskEnum.All;\n\n const browseResults = await this.browseService!.browse([description]);\n const browseResult = browseResults[0];\n const allReferences = [...(browseResult.references ?? [])];\n\n let continuationPoint = browseResult.continuationPoint;\n while (continuationPoint && continuationPoint.byteLength > 0) {\n const nextResults = await this.browseService!\n .browseNext([continuationPoint], false);\n const nextResult = nextResults[0];\n allReferences.push(...(nextResult.references ?? []));\n continuationPoint = nextResult.continuationPoint;\n }\n\n const results = allReferences.map((ref: ReferenceDescription) =>\n new BrowseNodeResult(\n ref.referenceTypeId,\n ref.isForward,\n ref.nodeId,\n ref.browseName,\n ref.displayName,\n ref.nodeClass,\n ref.typeDefinition,\n )\n );\n\n if (recursive) {\n for (const ref of allReferences) {\n const childNodeId = NodeId.newNumeric(\n ref.nodeId.nodeId.namespace,\n ref.nodeId.nodeId.identifier as number,\n );\n const childResults = await this.browseRecursive(\n childNodeId, true, visited,\n );\n results.push(...childResults);\n }\n }\n\n return results;\n }\n\n async subscribe(\n ids: NodeId[],\n callback: (data: { id: NodeId; value: unknown }[]) => void,\n ) {\n this.subscriptionHandler?.subscribe(ids, callback);\n }\n\n constructor(\n endpointUrl: string,\n private configuration: ConfigurationClient,\n private identity: UserIdentity,\n ) {\n this.endpointUrl = endpointUrl;\n initLoggerProvider(configuration.loggerFactory);\n this.logger = getLogger(\"Client\");\n }\n}\n","import {\n BinaryReader,\n BinaryWriter,\n Configuration,\n Decoder,\n Encoder,\n ILoggerFactory,\n LoggerFactory,\n registerBinaryDecoders,\n registerEncoders,\n registerTypeDecoders\n} from \"opcjs-base\";\n\nimport type { SecurityConfiguration } from './securityConfiguration.js'\n\nexport class ConfigurationClient extends Configuration {\n /**\n * Optional security restrictions applied during `Client.connect()`.\n * When not set, permissive defaults are used (SecurityPolicy None allowed,\n * all user-token types accepted).\n *\n * @see SecurityConfiguration\n */\n public securityConfiguration?: SecurityConfiguration\n public static getSimple(\n name: string,\n company: string,\n loggerFactory?: ILoggerFactory,\n ): ConfigurationClient {\n\n if (!loggerFactory) {\n loggerFactory = new LoggerFactory({\n defaultLevel: 'DEBUG', //todo: use enum\n categoryLevels: {\n \"transport.*\": \"TRACE\",\n \"secureChannel.*\": \"TRACE\",\n },\n });\n }\n const applicationUri = `urn:${company}:${name}`;\n const productUri = `urn:${company}:${name}:product`;\n\n const encoder = new Encoder();\n encoder.registerWriterFactory(\"binary\", () => {\n return new BinaryWriter();\n });\n registerEncoders(encoder);\n\n const decoder = new Decoder();\n decoder.registerReaderFactory(\"binary\", (data: unknown) => {\n return new BinaryReader(data as Uint8Array);\n });\n registerTypeDecoders(decoder);\n registerBinaryDecoders(decoder);\n\n return new ConfigurationClient(\n name,\n applicationUri,\n name,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n\n constructor(\n applicationName: string,\n applicationUri: string,\n productName: string,\n productUri: string,\n encoder: Encoder,\n decoder: Decoder,\n loggerFactory: ILoggerFactory,\n ) {\n super(\n applicationName,\n applicationUri,\n productName,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n}\n","import { IssuedIdentityToken, UserIdentityToken, UserNameIdentityToken, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"./issuerConfiguration\";\nimport { IssuerToken } from \"./issuerToken\";\nimport { AnonymousIdentityToken } from \"opcjs-base\";\n\nexport class UserIdentity {\n private userIdentityToken?: UserIdentityToken;\n private tokenType = UserTokenTypeEnum.Anonymous;\n private issuerLoginCallback: ((config:IssuerConfiguration)=>Promise<IssuerToken>) | undefined = undefined;\n\n public static newAnonymous(): UserIdentity {\n const userIdentity = new UserIdentity();\n userIdentity.userIdentityToken = new AnonymousIdentityToken();\n userIdentity.userIdentityToken.policyId = \"anonymous\";\n userIdentity.tokenType = UserTokenTypeEnum.Anonymous;\n return userIdentity;\n }\n \n public static newWithUserName(userName: string, password: string): UserIdentity {\n const userIdentity = new UserIdentity();\n const nameToken = new UserNameIdentityToken();\n nameToken.userName = userName;\n nameToken.password = new TextEncoder().encode(password);\n\n userIdentity.userIdentityToken = nameToken;\n userIdentity.tokenType = UserTokenTypeEnum.UserName;\n return userIdentity;\n }\n\n public static newWithIssuerToken(loginCallback: (config:IssuerConfiguration)=>Promise<IssuerToken>): UserIdentity {\n const userIdentity = new UserIdentity();\n const issuedToken = new IssuedIdentityToken();\n issuedToken.tokenData = new TextEncoder().encode(\"\"); // token data will be filled by the login callback \n userIdentity.userIdentityToken = issuedToken;\n userIdentity.tokenType = UserTokenTypeEnum.IssuedToken;\n userIdentity.issuerLoginCallback = loginCallback;\n return userIdentity;\n }\n\n public getUserIdentityToken(): UserIdentityToken {\n return this.userIdentityToken as UserIdentityToken;\n }\n\n public getTokenType(): UserTokenTypeEnum {\n return this.tokenType;\n }\n\n public getIssuerLoginCallback(): ((config:IssuerConfiguration)=>Promise<IssuerToken>) {\n if(!this.issuerLoginCallback){\n throw new Error(\"No issuer login callback defined\");\n }\n \n return this.issuerLoginCallback;\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/sessions/sessionInvalidError.ts","../src/services/serviceBase.ts","../src/services/sessionService.ts","../src/issuerConfiguration.ts","../src/sessions/session.ts","../src/sessions/sessionHandler.ts","../src/securityConfiguration.ts","../src/services/attributeServiceAttributes.ts","../src/services/attributeService.ts","../src/readValueResult.ts","../src/subscriptionHandlerEntry.ts","../src/subscriptionHandler.ts","../src/services/subscriptionService.ts","../src/services/monitoredItemService.ts","../src/services/methodService.ts","../src/callMethodResult.ts","../src/services/browseService.ts","../src/browseNodeResult.ts","../src/client.ts","../src/configurationClient.ts","../src/userIdentity.ts"],"names":["StatusCodeToString","StatusCode","ExtensionObject","NodeId","getLogger","UserTokenTypeEnum","ReadValueId","QualifiedName","TimestampsToReturnEnum","CallMethodRequest","BrowseDescription","Configuration","IssuedIdentityToken"],"mappings":";;;AAaO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EACpC,UAAA;AAAA,EAET,YAAY,UAAA,EAAoB;AAC9B,IAAA,KAAA,CAAM,CAAA,4BAAA,EAA+B,kBAAA,CAAmB,UAAU,CAAC,CAAA,IAAA,EAAO,UAAA,CAAW,QAAA,CAAS,EAAE,CAAA,CAAE,WAAA,EAAa,CAAA,CAAA,CAAG,CAAA;AAClH,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AACZ,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAAA,EACpB;AACF;;;ACjBO,IAAe,cAAf,MAA2B;AAAA,EAmC9B,WAAA,CAAoB,WAA6B,aAAA,EAA8B;AAA3D,IAAA,IAAA,CAAA,SAAA,GAAA,SAAA;AAA6B,IAAA,IAAA,CAAA,aAAA,GAAA,aAAA;AAAA,EAA+B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAvBtE,kBAAA,CAAmB,QAA4B,OAAA,EAAuB;AAC5E,IAAA,IAAI,MAAA,KAAW,MAAA,IAAa,MAAA,KAAW,UAAA,CAAW,IAAA,EAAM;AAExD,IAAA,IAAI,MAAA,KAAW,UAAA,CAAW,mBAAA,IAAuB,MAAA,KAAW,WAAW,gBAAA,EAAkB;AACrF,MAAA,MAAM,IAAI,oBAAoB,MAAM,CAAA;AAAA,IACxC;AAEA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA,SAAA,EAAYA,kBAAAA,CAAmB,MAAM,CAAC,CAAA,EAAA,EAAK,wBAAA,CAAyB,MAAM,CAAC,CAAA,CAAA,CAAG,CAAA;AAAA,EAC5G;AAAA,EAEU,mBAAA,GAAqC;AAC3C,IAAA,MAA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A,EAAa;AACtC,IAAA,MAAM,WAAA,GAAc,IAAIO,mBAAAA,EAAoB;AAC5C,IAAA,WAAA,CAAY,SAAA,GAAY,IAAI,WAAA,EAAY,CAAE,OAAO,EAAE,CAAA;AACnD,IAAA,YAAA,CAAa,iBAAA,GAAoB,WAAA;AACjC,IAAA,YAAA,CAAa,YAAYP,iBAAAA,CAAkB,WAAA;AAC3C,IAAA,YAAA,CAAa,mBAAA,GAAsB,aAAA;AACnC,IAAA,OAAO,YAAA;AAAA,EACX;AAAA,EAEO,oBAAA,GAA0C;AAC7C,IAAA,OAAO,IAAA,CAAK,iBAAA;AAAA,EAChB;AAAA,EAEO,YAAA,GAAkC;AACrC,IAAA,OAAO,IAAA,CAAK,SAAA;AAAA,EAChB;AAAA,EAEO,sBAAA,GAA+E;AAClF,IAAA,IAAG,CAAC,KAAK,mBAAA,EAAoB;AACzB,MAAA,MAAM,IAAI,MAAM,kCAAkC,CAAA;AAAA,IACtD;AAEA,IAAA,OAAO,IAAA,CAAK,mBAAA;AAAA,EAChB;AACJ","file":"index.js","sourcesContent":["import { StatusCodeToString } from 'opcjs-base'\n\n/**\n * Thrown when the server signals that the current Session is no longer valid.\n *\n * Callers that want to react to a dropped session (e.g. by creating a new one\n * and retrying the operation) should catch this specific error type instead of\n * the generic `Error` class.\n *\n * Relevant OPC UA status codes:\n * - `BadSessionIdInvalid` (0x80250000) – session no longer exists on the server\n * - `BadSessionClosed` (0x80260000) – session was closed explicitly\n */\nexport class SessionInvalidError extends Error {\n readonly statusCode: number\n\n constructor(statusCode: number) {\n super(`Session is no longer valid: ${StatusCodeToString(statusCode)} (0x${statusCode.toString(16).toUpperCase()})`)\n this.name = 'SessionInvalidError'\n this.statusCode = statusCode\n }\n}\n","import { ExtensionObject, ISecureChannel, NodeId, RequestHeader, StatusCode, StatusCodeToString, StatusCodeToStringNumber } from 'opcjs-base'\n\nimport { SessionInvalidError } from '../sessions/sessionInvalidError.js'\n\nexport abstract class ServiceBase {\n\n /**\n * Validates the `serviceResult` value from a response header.\n *\n * Throws `SessionInvalidError` for session-related status codes so callers\n * can detect a dropped session and act accordingly (e.g. reconnect).\n * Throws a generic `Error` for all other non-Good codes.\n *\n * @param result - The `serviceResult` value from the response header.\n * @param context - Short description used in the error message (e.g. \"ReadRequest\").\n */\n protected checkServiceResult(result: number | undefined, context: string): void {\n if (result === undefined || result === StatusCode.Good) return\n\n if (result === StatusCode.BadSessionIdInvalid || result === StatusCode.BadSessionClosed) {\n throw new SessionInvalidError(result)\n }\n\n throw new Error(`${context} failed: ${StatusCodeToString(result)} (${StatusCodeToStringNumber(result)})`)\n }\n\n protected createRequestHeader(): RequestHeader {\n const requestHeader = new RequestHeader();\n requestHeader.authenticationToken = this.authToken;\n requestHeader.timestamp = new Date();\n requestHeader.requestHandle = 0; // will be set by secure channel\n requestHeader.returnDiagnostics = 0;\n requestHeader.auditEntryId = '';\n requestHeader.timeoutHint = 60000;\n requestHeader.additionalHeader = ExtensionObject.newEmpty();\n\n return requestHeader;\n }\n \n constructor(private authToken: NodeId, protected secureChannel: ISecureChannel){}\n}","import {\n ActivateSessionRequest, ActivateSessionResponse, ApplicationDescription, ApplicationTypeEnum,\n CloseSessionRequest, CloseSessionResponse,\n Configuration, CreateSessionRequest, CreateSessionResponse, EndpointDescription, ExtensionObject,\n getLogger,\n ISecureChannel, LocalizedText, NodeId, SignatureData, SignedSoftwareCertificate, StatusCode,\n StatusCodeToString, UserIdentityToken,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\nexport class SessionService extends ServiceBase {\n private logger = getLogger(\"services.SessionService\");\n\n /**\n * Creates a new session on the server (OPC UA Part 4, Section 5.7.2).\n * @returns The session ID, authentication token, and selected server endpoint.\n */\n async createSession(): Promise<{ sessionId: number, authToken: NodeId, endpoint: EndpointDescription }> {\n this.logger.debug(\"Creating session...\");\n\n const clientDescription = new ApplicationDescription();\n clientDescription.applicationUri = this.configuration.applicationUri;\n clientDescription.productUri = this.configuration.productUri;\n clientDescription.applicationName = new LocalizedText(undefined, this.configuration.productName);\n clientDescription.applicationType = ApplicationTypeEnum.Client;\n clientDescription.gatewayServerUri = '';\n clientDescription.discoveryProfileUri = '';\n clientDescription.discoveryUrls = new Array<string>();\n\n const request = new CreateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientDescription = clientDescription;\n request.serverUri = '';\n request.endpointUrl = this.secureChannel.getEndpointUrl();\n request.sessionName = '';\n request.clientNonce = null;\n request.clientCertificate = null;\n request.requestedSessionTimeout = 60000;\n request.maxResponseMessageSize = 0;\n\n\n // todo: verify endpoints\n // todo: check application uri in server certificate\n\n this.logger.debug(\"Sending CreateSessionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request);\n if (!response || !(response instanceof CreateSessionResponse)) {\n throw new Error(\"Invalid response type for CreateSessionRequest\");\n }\n\n const castedResponse = response as CreateSessionResponse;\n if (!castedResponse || !castedResponse.sessionId || !castedResponse.authenticationToken) {\n throw new Error(\"CreateSessionResponse missing SessionId or AuthenticationToken\");\n }\n\n const serviceResult = castedResponse.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSessionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n // The URL the client actually used to connect. Prepend the OPC UA scheme\n // prefix so it is parseable by the standard URL constructor.\n const clientConnectionUrl = new URL('opc.' + this.secureChannel.getEndpointUrl())\n const securityMode = this.secureChannel.getSecurityMode()\n const securityPolicyUri = this.secureChannel.getSecurityPolicy()\n\n // OPC UA Part 4, Section 5.4.4.2: Clients should be prepared to replace\n // the HostName and port returned in the EndpointDescription with the\n // HostName or IP address and port they used to call GetEndpoints. This\n // handles NAT/load-balancer scenarios where the server advertises internal\n // addresses that are unreachable by the client.\n const normalizeEndpointUrl = (serverEndpointUrl: string): URL => {\n const url = new URL(serverEndpointUrl)\n url.hostname = clientConnectionUrl.hostname\n url.port = clientConnectionUrl.port\n return url\n }\n\n // Match on protocol and path only; host and port are normalized away so\n // that internally-addressed endpoints are still found.\n const serverEndpoint = castedResponse?.serverEndpoints?.find(currentEndpoint => {\n const normalized = normalizeEndpointUrl(currentEndpoint.endpointUrl as string)\n return normalized.protocol === clientConnectionUrl.protocol\n && normalized.pathname === clientConnectionUrl.pathname\n && currentEndpoint.securityMode === securityMode\n && currentEndpoint.securityPolicyUri === securityPolicyUri\n })\n\n if (!serverEndpoint) {\n throw new Error(`Server endpoint ${clientConnectionUrl.toString()} not found in CreateSessionResponse`)\n }\n\n // Replace the server-reported host and port with the client's actual\n // connection address so downstream code uses the correct URL.\n serverEndpoint.endpointUrl = normalizeEndpointUrl(serverEndpoint.endpointUrl as string).toString()\n\n // NOTE: per OPC UA Part 4, Section 5.4.4.2 the client shall still verify\n // the HostName it used to open the SecureChannel against the HostName list\n // in the Server Certificate. This is deferred until certificate-based\n // security (non-None SecurityPolicy) is implemented.\n\n this.logger.debug(\"Session created with id:\", castedResponse.sessionId.identifier);\n return {\n sessionId: castedResponse.sessionId.identifier as number,\n authToken: castedResponse.authenticationToken,\n endpoint: serverEndpoint\n };\n }\n\n /**\n * Activates an existing session using the supplied identity token (OPC UA Part 4, Section 5.7.3).\n * @param identityToken - User identity token (anonymous, username/password, certificate, or issued token).\n */\n async activateSession(identityToken: UserIdentityToken): Promise<void> {\n const signatureData = new SignatureData();\n signatureData.algorithm = this.secureChannel.getSecurityPolicy();\n signatureData.signature = new Uint8Array(0);\n\n const request = new ActivateSessionRequest();\n request.requestHeader = this.createRequestHeader();\n request.clientSignature = signatureData;\n request.clientSoftwareCertificates = new Array<SignedSoftwareCertificate>();\n request.localeIds = ['en-US'];\n request.userIdentityToken = ExtensionObject.newBinary(identityToken);\n request.userTokenSignature = signatureData;\n\n this.logger.debug(\"Sending ActivateSessionRequest...\");\n const activateResponse = await this.secureChannel.issueServiceRequest(request) as ActivateSessionResponse;\n\n const activateResult = activateResponse?.responseHeader?.serviceResult;\n if (activateResult !== undefined && activateResult !== StatusCode.Good) {\n throw new Error(`ActivateSessionRequest failed: ${StatusCodeToString(activateResult)}`);\n }\n\n this.logger.debug(\"Session activated.\");\n }\n\n /**\n * Closes the current session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * associated with this Session, freeing their resources immediately.\n * Pass false to keep Subscriptions alive for transfer to another Session.\n */\n async closeSession(deleteSubscriptions: boolean): Promise<void> {\n this.logger.debug('Sending CloseSessionRequest...')\n\n const request = new CloseSessionRequest()\n request.requestHeader = this.createRequestHeader()\n request.deleteSubscriptions = deleteSubscriptions\n\n const response = await this.secureChannel.issueServiceRequest(request) as CloseSessionResponse\n\n const result = response?.responseHeader?.serviceResult\n if (result !== undefined && result !== StatusCode.Good) {\n throw new Error(`CloseSession failed: ${StatusCodeToString(result)}`)\n }\n\n this.logger.debug('Session closed.')\n }\n\n recreate(authToken: NodeId): SessionService {\n return new SessionService(authToken, this.secureChannel, this.configuration)\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel, private configuration: Configuration) {\n super(authToken, secureChannel)\n }\n}","interface IssuerEndpointUrl {\n 'ua.resourceId': string;\n 'ua.authorityUrl': string;\n 'ua.authorityProfileUri': string;\n 'ua.tokenEndpoint': string;\n 'ua.authorizationEndpoint': string;\n 'ua.requestTypes': string[];\n 'ua.scopes': string[];\n}\n\nexport class IssuerConfiguration{\n public static newFrom(issuerEndpointUrl: IssuerEndpointUrl): IssuerConfiguration {\n return new IssuerConfiguration(\n issuerEndpointUrl['ua.resourceId'],\n issuerEndpointUrl['ua.authorityUrl'],\n issuerEndpointUrl['ua.authorityProfileUri'],\n issuerEndpointUrl['ua.tokenEndpoint'],\n issuerEndpointUrl['ua.authorizationEndpoint'],\n issuerEndpointUrl['ua.requestTypes'],\n issuerEndpointUrl['ua.scopes']\n );\n }\n \n constructor(\n public resourceId: string,\n public authorityUrl: string,\n public authorityProfileUri: string,\n public tokenEndpoint: string,\n public authorizationEndpoint: string,\n public requestTypes: string[],\n public scopes: string[]\n ){\n \n }\n}","import { EndpointDescription, IssuedIdentityToken, NodeId, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"../issuerConfiguration\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\n\nexport class Session {\n async activateSession(identity: UserIdentity): Promise<void> {\n const token = identity.getUserIdentityToken();\n const tokenType = identity.getTokenType();\n const tokenPolicy = this.endpoint.userIdentityTokens?.find(t => t.tokenType === tokenType);\n if (!tokenPolicy) {\n throw new Error(`UserIdentityToken of type ${tokenType} not supported by server`);\n }\n token.policyId = tokenPolicy.policyId;\n\n if (tokenType === UserTokenTypeEnum.IssuedToken) {\n if (!tokenPolicy.issuerEndpointUrl) {\n throw new Error(\"IssuerEndpointUrl not defined for IssuedToken\");\n }\n const issuerEndpointUrl = JSON.parse(tokenPolicy.issuerEndpointUrl)\n const issuerConfig = IssuerConfiguration.newFrom(issuerEndpointUrl);\n\n const issuerLoginCallback = identity.getIssuerLoginCallback();\n const tokenData = await issuerLoginCallback(issuerConfig);\n\n const issuerToken = token as IssuedIdentityToken;\n issuerToken.tokenData = new TextEncoder().encode(tokenData.json);\n }\n\n await this.sessionServices.activateSession(token);\n }\n\n getAuthToken(): NodeId {\n return this.authToken;\n }\n\n getSessionId(): number {\n return this.sessionId;\n }\n\n getEndpoint(): EndpointDescription {\n return this.endpoint;\n }\n\n /**\n * Closes the session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - When true the server deletes all Subscriptions\n * tied to this Session. Defaults to true.\n */\n async close(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n constructor(\n public sessionId: number,\n private authToken: NodeId,\n private endpoint: EndpointDescription,\n private sessionServices: SessionService) { }\n}","import { ConfigurationClient } from \"../configurationClient\";\nimport { EndpointDescription, ISecureChannel, NodeId, UserTokenTypeEnum, getLogger } from \"opcjs-base\";\nimport { SessionService } from \"../services/sessionService\";\nimport { UserIdentity } from \"../userIdentity\";\nimport { Session } from \"./session\";\n\nexport class SessionHandler {\n private sessionServices: SessionService;\n private logger = getLogger(\"sessions.SessionHandler\");\n\n async createNewSession(identity:UserIdentity) : Promise<Session>{\n const ret = await this.sessionServices.createSession();\n this.sessionServices = this.sessionServices.recreate(ret.authToken)\n\n const session = new Session(ret.sessionId, ret.authToken, ret.endpoint, this.sessionServices);\n\n // Enforce user-token type restrictions from the client security configuration\n // before activating; the endpoint is now known from CreateSession.\n this.validateUserTokenPolicy(identity, ret.endpoint)\n\n await session.activateSession(identity);\n return session;\n }\n\n /**\n * Attempts to reactivate an existing OPC UA session on the current (new) SecureChannel\n * without calling CreateSession first (OPC UA Part 4, Section 5.7.3).\n *\n * This is the preferred recovery path when the SecureChannel drops but the server-side\n * session has not yet timed out: only a new channel is needed, not a new session.\n *\n * @returns The reactivated Session if ActivateSession succeeded, or `null` if the server\n * rejected the request (e.g. the session had already expired).\n */\n async tryActivateExistingSession(\n existingAuthToken: NodeId,\n existingSessionId: number,\n existingEndpoint: EndpointDescription,\n identity: UserIdentity,\n ): Promise<Session | null> {\n // Build a SessionService bound to the existing auth token so the RequestHeader\n // carries it and the server can correlate the ActivateSession to the right session.\n const serviceForExistingSession = this.sessionServices.recreate(existingAuthToken)\n try {\n const session = new Session(existingSessionId, existingAuthToken, existingEndpoint, serviceForExistingSession)\n await session.activateSession(identity)\n return session\n } catch (err) {\n this.logger.debug('ActivateSession for existing session failed:', err)\n return null\n }\n }\n\n /**\n * Closes the active session on the server (OPC UA Part 4, Section 5.7.4).\n * @param deleteSubscriptions - Forwarded to CloseSessionRequest. Defaults to true.\n */\n async closeSession(deleteSubscriptions = true): Promise<void> {\n await this.sessionServices.closeSession(deleteSubscriptions)\n }\n\n /**\n * Validates the requested user-identity token type against:\n * 1. The `allowedUserTokenTypes` from the client security configuration — the\n * client has explicitly restricted which token types it will use.\n * 2. The token policies advertised by the server endpoint — verifies that the\n * server actually supports at least one of the allowed types.\n *\n * Throws with a descriptive message if either check fails.\n */\n private validateUserTokenPolicy(identity: UserIdentity, endpoint: EndpointDescription): void {\n const allowedTypes = this.configuration.securityConfiguration?.allowedUserTokenTypes\n if (!allowedTypes) return // no restriction configured\n\n const requestedType = identity.getTokenType()\n\n // 1. Client-side restriction: the chosen identity must be an allowed type.\n if (!allowedTypes.includes(requestedType)) {\n throw new Error(\n `User token type '${UserTokenTypeEnum[requestedType]}' is not permitted by the ` +\n `client security configuration. Allowed types: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n\n // 2. Server-side availability: at least one allowed type must be offered.\n const serverTypes = endpoint.userIdentityTokens?.map(p => p.tokenType) ?? []\n const intersection = allowedTypes.filter(t => serverTypes.includes(t))\n if (intersection.length === 0) {\n throw new Error(\n `Server endpoint does not offer any user token type from the allowed list: ` +\n `${allowedTypes.map(t => UserTokenTypeEnum[t]).join(', ')}. ` +\n `Server offers: ${serverTypes.map(t => UserTokenTypeEnum[t]).join(', ')}.`,\n )\n }\n }\n\n constructor(secureChannel:ISecureChannel, private configuration: ConfigurationClient) {\n this.sessionServices = new SessionService(NodeId.newTwoByte(0), secureChannel, configuration);\n }\n}","import type { MessageSecurityModeEnum, UserTokenTypeEnum } from 'opcjs-base'\n\n/** URI for the SecurityPolicy None profile. */\nexport const SECURITY_POLICY_NONE_URI = 'http://opcfoundation.org/UA/SecurityPolicy#None'\n\n/**\n * How the client should handle a server certificate it cannot verify.\n *\n * - `'reject'` — abort the connection (secure default when `trustedCAs` is configured).\n * - `'trust'` — accept any certificate without verification (development convenience;\n * **insecure in production**).\n *\n * @note Enforcement is deferred until certificate-based security policies are\n * implemented. The value is stored and will be honoured when that support lands.\n */\nexport type UnknownCertificatePolicy = 'reject' | 'trust'\n\n/**\n * OPC UA client security configuration (OPC UA Part 2, Security Administration CU).\n *\n * Restricts which security options the client will accept when connecting to or\n * negotiating with a server. All fields are optional; omitting a field applies\n * the permissive default so that existing callers need no changes.\n *\n * @example\n * ```ts\n * const config = ConfigurationClient.getSimple('MyApp', 'MyCompany')\n * config.securityConfiguration = {\n * allowedUserTokenTypes: [UserTokenTypeEnum.UserName],\n * allowSecurityPolicyNone: false, // require an encrypted channel\n * }\n * ```\n */\nexport type SecurityConfiguration = {\n /**\n * User-identity-token types the client is willing to accept.\n *\n * When set, `connect()` will throw if:\n * - The supplied `UserIdentity`'s token type is not in this list, OR\n * - The server endpoint does not offer any type from this list.\n *\n * Default: all token types are accepted (no restriction).\n */\n allowedUserTokenTypes?: UserTokenTypeEnum[]\n\n /**\n * Allow connecting when the negotiated SecurityPolicy is `None` (unencrypted,\n * unsigned channel).\n *\n * Set to `false` to require a secure channel — `connect()` will throw rather\n * than establish a cleartext connection.\n *\n * Currently the only supported security policy is `None`. Setting this to `false`\n * will therefore cause `connect()` to always throw until non-None policies are\n * added to this client implementation.\n *\n * Default: `true` (SecurityPolicy None is permitted).\n */\n allowSecurityPolicyNone?: boolean\n\n /**\n * Required `MessageSecurityMode` for the secure channel.\n *\n * When set, `connect()` verifies that the channel's negotiated mode matches\n * this value and throws otherwise.\n *\n * Currently only `MessageSecurityModeEnum.None` is supported.\n *\n * Default: no requirement (any mode is accepted).\n */\n messageSecurityMode?: MessageSecurityModeEnum\n\n /**\n * DER-encoded X.509 trusted CA certificates used to verify the server's\n * application instance certificate.\n *\n * @note Reserved for future use. Certificate verification is not yet implemented.\n * Providing this field has no effect until non-None security policies land.\n */\n trustedCAs?: Uint8Array[]\n\n /**\n * How to handle a server certificate that cannot be verified against `trustedCAs`.\n *\n * - `'reject'` — refuse the connection (default when `trustedCAs` is provided).\n * - `'trust'` — accept any certificate (development only; insecure in production).\n *\n * @note Reserved for future use. Has no effect until certificate verification is\n * implemented alongside non-None security policies.\n */\n unknownCertificatePolicy?: UnknownCertificatePolicy\n}\n","// according to https://reference.opcfoundation.org/Core/Part6/v105/docs/A.1\n// see also: https://reference.opcfoundation.org/Core/Part4/v105/docs/7.24.1#Table154\n\nexport const AttrIdNodeId = 1\nexport const AttrIdNodeClass = 2\nexport const AttrIdBrowseName = 3\nexport const AttrIdDisplayName = 4\nexport const AttrIdDescription = 5\nexport const AttrIdWriteMask = 6\nexport const AttrIdUserWriteMask = 7\nexport const AttrIdIsAbstract = 8\nexport const AttrIdSymmetric = 9\nexport const AttrIdInverseName = 10\nexport const AttrIdContainsNoLoops = 11\nexport const AttrIdEventNotifier = 12\nexport const AttrIdValue = 13\nexport const AttrIdDataType = 14\nexport const AttrIdValueRank = 15\nexport const AttrIdArrayDimensions = 16\nexport const AttrIdAccessLevel = 17\nexport const AttrIdUserAccessLevel = 18\nexport const AttrIdMinimumSamplingInterval = 19\nexport const AttrIdHistorizing = 20\nexport const AttrIdExecutable = 21\nexport const AttrIdUserExecutable = 22\nexport const AttrIdDataTypeDefinition = 23\nexport const AttrIdRolePermissions = 24\nexport const AttrIdUserRolePermissions = 25\nexport const AttrIdAccessRestrictions = 26\nexport const AttrIdAccessLevelEx = 27\n","import {\n getLogger, ISecureChannel, NodeId, QualifiedName, ReadRequest, ReadResponse, ReadValueId,\n StatusCode, TimestampsToReturnEnum,\n} from 'opcjs-base'\n\nimport { AttrIdValue } from './attributeServiceAttributes.js'\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.10.2\nexport class AttributeService extends ServiceBase {\n private logger = getLogger(\"services.AttributeService\");\n\n /**\n * Reads the Value attribute of one or more Nodes (OPC UA Part 4, Section 5.10.2).\n * @param nodeIds - NodeIds of the Nodes to read.\n * @param maxAge - Maximum age of the cached value in milliseconds the server may return. 0 = always current value.\n * @param timestampsToReturn - Which timestamps to include in results. Default: Source.\n * @returns Array of results containing value and raw status code number, one per requested NodeId.\n */\n async ReadValue(\n nodeIds: NodeId[],\n maxAge: number = 0,\n timestampsToReturn: TimestampsToReturnEnum = TimestampsToReturnEnum.Source,\n ): Promise<{ statusCode: number, value: unknown }[]> {\n const readValueIds = nodeIds.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n return readValueId;\n });\n\n const request = new ReadRequest();\n request.requestHeader = this.createRequestHeader();\n request.maxAge = maxAge;\n request.timestampsToReturn = timestampsToReturn;\n request.nodesToRead = readValueIds;\n\n this.logger.debug(\"Sending ReadRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as ReadResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'ReadRequest')\n\n const results = new Array<{ statusCode: number, value: unknown }>();\n for (const dataValue of response.results ?? []) {\n results.push({\n statusCode: dataValue.statusCode ?? StatusCode.Good,\n value: dataValue.value as unknown,\n });\n }\n return results;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","export class ReadValueResult {\n constructor(public value: unknown, public statusCode: number) {}\n}","import { NodeId } from \"opcjs-base\";\n\nexport class SubscriptionHandlerEntry{\n constructor(\n public subscriptionId:number,\n public handle: number, \n public id:NodeId, \n public callback: (data: { id: NodeId, value: unknown }[]) => void\n ){}\n}","import {\n DataChangeNotification,\n ExpandedNodeId,\n getLogger,\n NodeId,\n StatusChangeNotification,\n SubscriptionAcknowledgement,\n} from 'opcjs-base'\n\nimport { MonitoredItemService } from './services/monitoredItemService'\nimport { SubscriptionService } from './services/subscriptionService'\nimport { SubscriptionHandlerEntry } from './subscriptionHandlerEntry'\n\n// OPC UA Part 4, §5.14 — Subscriptions and Monitored Items\n\n/** Node type IDs for notification payloads (OPC UA Part 4, §7.21) */\nconst NODE_ID_DATA_CHANGE_NOTIFICATION = 811\nconst NODE_ID_STATUS_CHANGE_NOTIFICATION = 818\n\nexport class SubscriptionHandler {\n private logger = getLogger('SubscriptionHandler')\n private entries = new Array<SubscriptionHandlerEntry>()\n private nextHandle = 0\n private isRunning = false\n\n /** Returns true when at least one subscription is active and the publish loop is running. */\n hasActiveSubscription(): boolean {\n return this.isRunning && this.entries.length > 0\n }\n\n async subscribe(ids: NodeId[], callback: (data: { id: NodeId; value: unknown }[]) => void) {\n if (this.entries.length > 0) {\n throw new Error('Subscribing more than once is not implemented')\n }\n\n const subscriptionId = await this.subscriptionService.createSubscription()\n const items = []\n for (const id of ids) {\n const entry = new SubscriptionHandlerEntry(subscriptionId, this.nextHandle++, id, callback)\n this.entries.push(entry)\n items.push({ id, handle: entry.handle })\n }\n await this.monitoredItemService.createMonitoredItems(subscriptionId, items)\n\n // Start the publish loop with no pending acknowledgements.\n this.isRunning = true\n void this.publishLoop([])\n }\n\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n private async publishLoop(pendingAcknowledgements: SubscriptionAcknowledgement[]): Promise<void> {\n if (!this.isRunning) return\n\n let response\n try {\n response = await this.subscriptionService.publish(pendingAcknowledgements)\n } catch (err) {\n this.logger.error(`Publish failed, stopping publish loop: ${err}`)\n this.isRunning = false\n return\n }\n\n const { subscriptionId, availableSequenceNumbers, moreNotifications, notificationMessage } = response\n const notificationDatas = notificationMessage?.notificationData ?? []\n const seqNumber = notificationMessage?.sequenceNumber\n\n // Build acknowledgements for the next publish request.\n // Per spec: only acknowledge sequence numbers that are in availableSequenceNumbers\n // and only for real notification messages (not keep-alive, which have empty notificationData).\n const nextAcknowledgements: SubscriptionAcknowledgement[] = []\n const isKeepAlive = notificationDatas.length === 0\n\n if (!isKeepAlive && seqNumber !== undefined) {\n // Acknowledge only if the server still lists this sequence number as available.\n const isAvailable = !availableSequenceNumbers || availableSequenceNumbers.includes(seqNumber)\n if (isAvailable) {\n const ack = new SubscriptionAcknowledgement()\n ack.subscriptionId = subscriptionId\n ack.sequenceNumber = seqNumber\n nextAcknowledgements.push(ack)\n }\n }\n\n // Dispatch notifications to registered callbacks.\n for (const notificationData of notificationDatas) {\n const decodedData = notificationData.data\n const rawTypeId = notificationData.typeId\n const typeNodeId = rawTypeId instanceof ExpandedNodeId ? rawTypeId.nodeId : rawTypeId\n\n if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_DATA_CHANGE_NOTIFICATION) {\n const dataChangeNotification = decodedData as DataChangeNotification\n for (const item of dataChangeNotification.monitoredItems) {\n const entry = this.entries.find(e => e.handle === item.clientHandle)\n entry?.callback([{ id: entry.id, value: item.value.value?.value }])\n }\n } else if (typeNodeId.namespace === 0 && typeNodeId.identifier === NODE_ID_STATUS_CHANGE_NOTIFICATION) {\n // The server notifies us the subscription state has changed (e.g. expired, closed).\n const statusChange = decodedData as StatusChangeNotification\n this.logger.warn(\n `Subscription ${subscriptionId} status changed: 0x${statusChange.status?.toString(16).toUpperCase()}`,\n )\n this.isRunning = false\n return\n } else {\n this.logger.warn(\n `Notification data type ${typeNodeId.namespace}:${typeNodeId.identifier} is not supported.`,\n )\n }\n }\n\n // Per spec: if moreNotifications is true the server has more queued data — re-publish immediately\n // without delay so the server's queue drains before its lifetime counter expires.\n // Otherwise, schedule the next publish after a short yield to avoid a tight synchronous loop.\n if (moreNotifications) {\n void this.publishLoop(nextAcknowledgements)\n } else {\n setTimeout(() => void this.publishLoop(nextAcknowledgements), 0)\n }\n }\n\n constructor(\n private subscriptionService: SubscriptionService,\n private monitoredItemService: MonitoredItemService,\n ) {}\n}","import {\n CreateSubscriptionRequest, CreateSubscriptionResponse, getLogger, ISecureChannel, NodeId,\n PublishRequest, PublishResponse, StatusCode, StatusCodeToString, SubscriptionAcknowledgement,\n} from \"opcjs-base\";\nimport { ServiceBase } from \"./serviceBase\";\n\n/** Options for creating a subscription. All fields are optional; server will revise requested values. */\nexport interface CreateSubscriptionOptions {\n /** Requested publishing interval in milliseconds. Default: 2000. */\n requestedPublishingInterval?: number;\n /** Requested lifetime count (number of publishing intervals before subscription times out). Default: 360000. */\n requestedLifetimeCount?: number;\n /** Requested max keep-alive count. Default: 60000. */\n requestedMaxKeepAliveCount?: number;\n /** Maximum number of notifications per publish response. 0 = no limit. Default: 200. */\n maxNotificationsPerPublish?: number;\n /** Subscription priority relative to other subscriptions. Default: 1. */\n priority?: number;\n}\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14\nexport class SubscriptionService extends ServiceBase {\n private logger = getLogger(\"services.SubscriptionService\");\n\n /**\n * Creates a new subscription on the server (OPC UA Part 4, Section 5.14.2).\n * @param options - Optional subscription parameters; server revises all values.\n * @returns The server-assigned subscription ID.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.2\n async createSubscription(options?: CreateSubscriptionOptions): Promise<number> {\n const request = new CreateSubscriptionRequest();\n request.requestHeader = this.createRequestHeader();\n request.requestedPublishingInterval = options?.requestedPublishingInterval ?? 2000;\n request.requestedLifetimeCount = options?.requestedLifetimeCount ?? 360000;\n request.requestedMaxKeepAliveCount = options?.requestedMaxKeepAliveCount ?? 60000;\n request.maxNotificationsPerPublish = options?.maxNotificationsPerPublish ?? 200;\n request.publishingEnabled = true;\n request.priority = options?.priority ?? 1;\n\n this.logger.debug(\"Sending CreateSubscriptionRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateSubscriptionResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateSubscriptionRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(`Subscription created with id: ${response.subscriptionId}`);\n return response.subscriptionId;\n }\n\n /**\n * Sends a publish request to receive notifications from active subscriptions (OPC UA Part 4, Section 5.14.5).\n * @param acknowledgements - Sequence numbers to acknowledge from previous publish responses.\n * @returns The publish response containing notification data.\n */\n // https://reference.opcfoundation.org/Core/Part4/v105/docs/5.14.5\n async publish(acknowledgements: SubscriptionAcknowledgement[]): Promise<PublishResponse> {\n const request = new PublishRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionAcknowledgements = acknowledgements;\n\n this.logger.debug(\"Sending PublishRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as PublishResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`PublishRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n this.logger.debug(\"Received PublishResponse.\");\n return response;\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import {\n CreateMonitoredItemsRequest, CreateMonitoredItemsResponse,\n ExtensionObject, getLogger, ISecureChannel, MonitoredItemCreateRequest, MonitoringModeEnum,\n MonitoringParameters, NodeId, QualifiedName, ReadValueId, StatusCode, StatusCodeToString,\n TimestampsToReturnEnum,\n} from \"opcjs-base\";\nimport { AttrIdValue } from \"./attributeServiceAttributes\";\nimport { ServiceBase } from \"./serviceBase\";\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.13.2\nexport class MonitoredItemService extends ServiceBase {\n private logger = getLogger(\"services.MonitoredItemService\");\n\n /**\n * Creates monitored items within a subscription (OPC UA Part 4, Section 5.13.2).\n * @param subscriptionId - ID of the subscription to add monitored items to.\n * @param ids - Array of NodeIds and client handles identifying the items to monitor.\n * @param samplingInterval - Requested sampling interval in milliseconds. -1 = use subscription publishing interval.\n * @param queueSize - Requested queue size for each monitored item.\n */\n async createMonitoredItems(\n subscriptionId: number,\n ids: { id: NodeId, handle: number }[],\n samplingInterval: number = 1000,\n queueSize: number = 100,\n ): Promise<void> {\n const items = ids.map(ni => {\n const readValueId = new ReadValueId();\n readValueId.nodeId = ni.id;\n readValueId.attributeId = AttrIdValue;\n readValueId.indexRange = '';\n readValueId.dataEncoding = new QualifiedName(0, ''); // empty per OPC UA Part 4 §7.28 — no longer used\n\n const monitoringParameters = new MonitoringParameters();\n monitoringParameters.clientHandle = ni.handle;\n monitoringParameters.samplingInterval = samplingInterval;\n monitoringParameters.filter = ExtensionObject.newEmpty();\n monitoringParameters.queueSize = queueSize;\n monitoringParameters.discardOldest = true;\n\n const monitoredItemCreateRequest = new MonitoredItemCreateRequest();\n monitoredItemCreateRequest.itemToMonitor = readValueId;\n monitoredItemCreateRequest.monitoringMode = MonitoringModeEnum.Reporting;\n monitoredItemCreateRequest.requestedParameters = monitoringParameters;\n return monitoredItemCreateRequest;\n });\n\n const request = new CreateMonitoredItemsRequest();\n request.requestHeader = this.createRequestHeader();\n request.subscriptionId = subscriptionId;\n request.timestampsToReturn = TimestampsToReturnEnum.Source;\n request.itemsToCreate = items;\n\n this.logger.debug(\"Sending CreateMonitoredItemsRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CreateMonitoredItemsResponse;\n\n const serviceResult = response.responseHeader?.serviceResult;\n if (serviceResult !== undefined && serviceResult !== StatusCode.Good) {\n throw new Error(`CreateMonitoredItemsRequest failed: ${StatusCodeToString(serviceResult)}`);\n }\n\n for (const result of response.results ?? []) {\n if (result.statusCode !== undefined && result.statusCode !== StatusCode.Good) {\n this.logger.warn(`Failed to create monitored item: ${StatusCodeToString(result.statusCode)}`);\n }\n }\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}","import { CallMethodRequest, CallRequest, CallResponse, getLogger, ISecureChannel, NodeId, StatusCode } from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.11.2\nexport class MethodService extends ServiceBase {\n private logger = getLogger(\"services.MethodService\");\n\n /**\n * Calls one or more methods on the server (OPC UA Part 4, Section 5.11.2).\n * @param methodsToCall - Array of CallMethodRequest describing each method to invoke.\n * @returns Array of results containing output argument values and raw status code number, one per requested method.\n */\n async call(methodsToCall: CallMethodRequest[]): Promise<{ statusCode: number, value: unknown[] }[]> {\n const request = new CallRequest();\n request.requestHeader = this.createRequestHeader();\n request.methodsToCall = methodsToCall;\n\n this.logger.debug(\"Sending CallRequest...\");\n const response = await this.secureChannel.issueServiceRequest(request) as CallResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'CallRequest')\n\n return response.results.map(result => ({\n statusCode: result.statusCode ?? StatusCode.Good,\n value: result.outputArguments.map(arg => arg.value),\n }));\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","export class CallMethodResult {\n constructor(public values: unknown[], public statusCode: number) {}\n}","import {\n BrowseDescription, BrowseNextRequest, BrowseNextResponse,\n BrowseRequest, BrowseResponse, BrowseResult,\n getLogger, ISecureChannel, NodeId, UaByteString, ViewDescription,\n} from 'opcjs-base'\n\nimport { ServiceBase } from './serviceBase.js'\n\n// https://reference.opcfoundation.org/Core/Part4/v105/docs/5.9\nexport class BrowseService extends ServiceBase {\n private logger = getLogger(\"services.BrowseService\");\n\n /**\n * Browses one or more Nodes and returns their References (OPC UA Part 4, Section 5.9.2).\n * @param nodesToBrowse - Array of BrowseDescriptions specifying nodes and filter criteria.\n * @returns Array of BrowseResult, one per requested node.\n */\n async browse(nodesToBrowse: BrowseDescription[]): Promise<BrowseResult[]> {\n const view = new ViewDescription();\n view.viewId = NodeId.newNumeric(0, 0);\n view.timestamp = new Date(-11644473600000); // OPC UA MinDateTime (ticks=0)\n view.viewVersion = 0;\n\n const request = new BrowseRequest();\n request.requestHeader = this.createRequestHeader();\n request.view = view;\n request.requestedMaxReferencesPerNode = 0;\n request.nodesToBrowse = nodesToBrowse;\n\n this.logger.debug(\"Sending BrowseRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseRequest')\n\n return response.results ?? []\n }\n\n /**\n * Continues a Browse operation using continuation points (OPC UA Part 4, Section 5.9.3).\n * @param continuationPoints - Continuation points returned by a prior Browse or BrowseNext call.\n * @param releaseContinuationPoints - If true, releases the continuation points without returning results.\n * @returns Array of BrowseResult, one per continuation point.\n */\n async browseNext(\n continuationPoints: UaByteString[],\n releaseContinuationPoints: boolean,\n ): Promise<BrowseResult[]> {\n const request = new BrowseNextRequest();\n request.requestHeader = this.createRequestHeader();\n request.releaseContinuationPoints = releaseContinuationPoints;\n request.continuationPoints = continuationPoints;\n\n this.logger.debug(\"Sending BrowseNextRequest...\");\n const response = await this.secureChannel\n .issueServiceRequest(request) as BrowseNextResponse;\n\n this.checkServiceResult(response.responseHeader?.serviceResult, 'BrowseNextRequest')\n\n return response.results ?? []\n }\n\n constructor(authToken: NodeId, secureChannel: ISecureChannel) {\n super(authToken, secureChannel);\n }\n}\n","import {\n ExpandedNodeId, LocalizedText, NodeClassEnum,\n NodeId, QualifiedName\n} from \"opcjs-base\";\n\nexport class BrowseNodeResult {\n constructor(\n public referenceTypeId: NodeId,\n public isForward: boolean,\n public nodeId: ExpandedNodeId,\n public browseName: QualifiedName,\n public displayName: LocalizedText,\n public nodeClass: NodeClassEnum,\n public typeDefinition: ExpandedNodeId,\n ) {}\n}\n","import {\n NodeId,\n ISecureChannel,\n TcpConnectionHandler,\n SecureChannelFacade,\n SecureChannelContext,\n SecureChannelMessageEncoder,\n SecureChannelTypeDecoder,\n SecureChannelMessageDecoder,\n SecureChannelTypeEncoder,\n initLoggerProvider,\n TcpMessageInjector,\n TcpMessageDecoupler,\n getLogger,\n WebSocketFascade,\n WebSocketReadableStream,\n WebSocketWritableStream,\n SecureChannelChunkReader,\n SecureChannelChunkWriter,\n CallMethodRequest,\n Variant,\n BrowseDescription,\n BrowseDirectionEnum,\n BrowseResultMaskEnum,\n ReferenceDescription,\n ILogger,\n} from 'opcjs-base'\n\nimport { SessionHandler } from './sessions/sessionHandler.js'\nimport { Session } from './sessions/session.js'\nimport { SessionInvalidError } from './sessions/sessionInvalidError.js'\nimport { SECURITY_POLICY_NONE_URI } from './securityConfiguration.js'\nimport { AttributeService } from './services/attributeService.js'\nimport { ReadValueResult } from './readValueResult.js'\nimport { SubscriptionHandler } from './subscriptionHandler.js'\nimport { SubscriptionService } from './services/subscriptionService.js'\nimport { MonitoredItemService } from './services/monitoredItemService.js'\nimport { UserIdentity } from './userIdentity.js'\nimport { ConfigurationClient } from './configurationClient.js'\nimport { MethodService } from './services/methodService.js'\nimport { CallMethodResult } from './callMethodResult.js'\nimport { BrowseService } from './services/browseService.js'\nimport { BrowseNodeResult } from './browseNodeResult.js'\nimport { CallMethodArgument } from './callMethodArgument.js'\n\n/** NodeId of Server_ServerStatus (ns=0, i=2256) — a cheap server-side read used for session keep-alive. */\nconst SERVER_STATUS_NODE_ID = NodeId.newNumeric(0, 2256)\n/**\n * How often to read the server when no subscription is active (ms).\n * Must be shorter than the server's revisedSessionTimeout (default: 60 000 ms).\n */\nconst KEEP_ALIVE_INTERVAL_MS = 25_000\n\nexport class Client {\n private endpointUrl: string\n private attributeService?: AttributeService\n private methodService?: MethodService\n private browseService?: BrowseService\n private session?: Session\n private subscriptionHandler?: SubscriptionHandler\n private logger: ILogger\n // Stored after connect() so that refreshSession() and disconnect() can use them.\n private secureChannel?: ISecureChannel\n private secureChannelFacade?: SecureChannelFacade\n private ws?: WebSocketFascade\n private sessionHandler?: SessionHandler\n private keepAliveTimer?: ReturnType<typeof setInterval>\n\n getSession(): Session {\n if (!this.session) {\n throw new Error('No session available')\n }\n return this.session\n }\n\n /**\n * (Re-)initialises all session-scoped services from the current `this.session`.\n * Called both after the initial `connect()` and after a session refresh.\n */\n private initServices(): void {\n const authToken = this.session!.getAuthToken()\n const sc = this.secureChannel!\n this.attributeService = new AttributeService(authToken, sc)\n this.methodService = new MethodService(authToken, sc)\n this.browseService = new BrowseService(authToken, sc)\n this.subscriptionHandler = new SubscriptionHandler(\n new SubscriptionService(authToken, sc),\n new MonitoredItemService(authToken, sc),\n )\n }\n\n /**\n * Executes `fn` and, if it throws a `SessionInvalidError`, creates a fresh\n * session and retries the operation exactly once.\n *\n * This covers the reactive case: a service call reveals that the server has\n * already dropped the session (e.g. due to timeout). The new session is\n * established transparently before re-running the original operation.\n *\n * For any other error (e.g. transport-level failures when the SecureChannel\n * drops), this method attempts to reconnect the channel and reactivate the\n * existing session first — falling back to a brand-new session only when\n * reactivation fails — before retrying the operation once.\n */\n private async withSessionRefresh<T>(fn: () => Promise<T>): Promise<T> {\n try {\n return await fn()\n } catch (err) {\n if (err instanceof SessionInvalidError) {\n this.logger.info(`Session invalid (${err.statusCode.toString(16)}), refreshing session...`)\n this.session = await this.sessionHandler!.createNewSession(this.identity)\n this.initServices()\n this.logger.info('Session refreshed, retrying operation.')\n\n // Retry once with the new session. If it fails again the error propagates.\n return await fn()\n }\n\n // Possibly a channel drop: attempt reconnect + ActivateSession on existing session\n // before giving up and creating a brand-new session (OPC UA Part 4 Session Auto Reconnect).\n this.logger.info('Service call failed, attempting channel reconnect and session reactivation...')\n try {\n await this.reconnectAndReactivate()\n this.initServices()\n this.logger.info('Reconnected successfully, retrying operation.')\n } catch (reconnectErr) {\n // Reconnect itself failed; surface the original error so the caller\n // gets a meaningful diagnostic (the reconnect error is logged separately).\n this.logger.warn('Channel reconnect failed:', reconnectErr)\n throw err\n }\n\n // Retry once after a successful reconnect. If it fails again the error propagates.\n return await fn()\n }\n }\n\n /**\n * Starts a periodic keep-alive timer that reads Server_ServerStatus when no subscription is\n * active. OPC UA Part 4, Section 5.7.1 requires clients to keep the session alive; when no\n * subscription Publish loop is running this is the only mechanism that does so.\n */\n private startKeepAlive(): void {\n this.keepAliveTimer = setInterval(() => {\n if (this.subscriptionHandler?.hasActiveSubscription()) {\n // The subscription publish loop is already keeping the session alive.\n return\n }\n if (this.attributeService) {\n void this.attributeService.ReadValue([SERVER_STATUS_NODE_ID]).catch((err) => {\n this.logger.warn('Keep-alive read failed:', err)\n })\n }\n }, KEEP_ALIVE_INTERVAL_MS)\n }\n\n private stopKeepAlive(): void {\n clearInterval(this.keepAliveTimer)\n this.keepAliveTimer = undefined\n }\n\n async connect(): Promise<void> {\n const { ws, sc } = await this.openTransportAndChannel()\n\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n\n this.logger.debug('Creating session...')\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.debug('Session created.')\n\n this.logger.debug('Initializing services...')\n this.initServices()\n this.startKeepAlive()\n }\n\n /**\n * Builds the full WebSocket → TCP → SecureChannel pipeline and returns the\n * two objects needed to drive it: the raw WebSocket facade (for teardown)\n * and the SecureChannelFacade (for service requests/session management).\n *\n * Extracted from `connect()` so it can be reused by `reconnectAndReactivate()`.\n */\n private async openTransportAndChannel(): Promise<{ ws: WebSocketFascade; sc: SecureChannelFacade }> {\n const wsOptions = { endpoint: this.endpointUrl }\n const ws = new WebSocketFascade(wsOptions);\n const webSocketReadableStream = new WebSocketReadableStream(ws, 1000);\n const webSocketWritableStream = new WebSocketWritableStream(ws);\n\n const scContext = new SecureChannelContext(this.endpointUrl);\n const tcpMessageInjector = new TcpMessageInjector();\n const tcpConnectionHandler = new TcpConnectionHandler(tcpMessageInjector, scContext);\n const tcpMessageDecoupler = new TcpMessageDecoupler(tcpConnectionHandler.onTcpMessage.bind(tcpConnectionHandler));\n const scMessageEncoder = new SecureChannelMessageEncoder(scContext);\n const scTypeDecoder = new SecureChannelTypeDecoder(\n this.configuration.decoder,\n );\n const scMessageDecoder = new SecureChannelMessageDecoder(scContext);\n const scTypeEncoder = new SecureChannelTypeEncoder(\n this.configuration.encoder,\n );\n const scChunkWriter = new SecureChannelChunkWriter(scContext);\n const scChunkReader = new SecureChannelChunkReader(scContext);\n\n webSocketReadableStream.pipeTo(tcpMessageDecoupler.writable);\n tcpMessageDecoupler.readable.pipeTo(scMessageDecoder.writable);\n scMessageDecoder.readable.pipeTo(scChunkReader.writable);\n scChunkReader.readable.pipeTo(scTypeDecoder.writable);\n\n scTypeEncoder.readable.pipeTo(scChunkWriter.writable);\n scChunkWriter.readable.pipeTo(scMessageEncoder.writable);\n scMessageEncoder.readable.pipeTo(tcpMessageInjector.writable);\n tcpMessageInjector.readable.pipeTo(webSocketWritableStream);\n\n const sc = new SecureChannelFacade(scContext, scTypeDecoder, scTypeEncoder);\n\n let connected = false;\n while (!connected) {\n this.logger.debug(`Connecting to OPC UA server at ${this.endpointUrl}...`);\n await ws.connect();\n this.logger.debug(\"WebSocket connection established, now establishing TCP connection...\");\n connected = await tcpConnectionHandler.connect(this.endpointUrl);\n\n if (!connected) {\n this.logger.info(\"Connection failed, retrying in 2 seconds...\");\n await new Promise((resolve) => setTimeout(resolve, 2000));\n }\n }\n this.logger.info(\"Connected to OPC UA server.\");\n\n this.logger.debug(\"Opening secure channel...\");\n await sc.openSecureChannel();\n this.logger.debug(\"Secure channel established.\");\n\n // Enforce any channel-level security requirements before proceeding.\n this.enforceChannelSecurityConfig(sc);\n\n return { ws, sc };\n }\n\n /**\n * Validates the negotiated channel's security policy and mode against the\n * client's `SecurityConfiguration` (OPC UA Part 2, Security Administration).\n *\n * Throws if:\n * - `allowSecurityPolicyNone` is `false` and the channel uses SecurityPolicy None.\n * - `messageSecurityMode` is set and does not match the channel's actual mode.\n */\n private enforceChannelSecurityConfig(sc: SecureChannelFacade): void {\n const config = this.configuration.securityConfiguration\n if (!config) return\n\n const negotiatedPolicy = sc.getSecurityPolicy()\n const negotiatedMode = sc.getSecurityMode()\n\n if (config.allowSecurityPolicyNone === false && negotiatedPolicy === SECURITY_POLICY_NONE_URI) {\n throw new Error(\n 'Connection refused: SecurityPolicy None is disabled by the client security configuration. ' +\n 'Only SecurityPolicy None is currently supported by this client implementation.',\n )\n }\n\n if (config.messageSecurityMode !== undefined && config.messageSecurityMode !== negotiatedMode) {\n throw new Error(\n `Connection refused: negotiated MessageSecurityMode ${negotiatedMode} does not match ` +\n `the required mode ${config.messageSecurityMode} from the security configuration.`,\n )\n }\n }\n\n /**\n * Tears down the current (dead) channel and establishes a fresh one, then\n * attempts to recover the existing OPC UA session via ActivateSession before\n * falling back to a full CreateSession + ActivateSession.\n *\n * OPC UA Part 4, Section 5.7.1 / Session Client Auto Reconnect conformance unit:\n * When the SecureChannel drops but the server-side session has not yet timed\n * out, the client SHOULD reuse the existing session by calling ActivateSession\n * on the new channel. Only if that fails should the client create a new session.\n */\n private async reconnectAndReactivate(): Promise<void> {\n this.logger.info('Tearing down dead channel before reconnect...')\n\n // Close the old channel and WebSocket (best effort — they may already be dead).\n try { this.secureChannelFacade?.close() } catch { /* already dead */ }\n try { this.ws?.close() } catch { /* already dead */ }\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n this.ws = undefined\n\n const { ws, sc } = await this.openTransportAndChannel()\n this.secureChannel = sc\n this.secureChannelFacade = sc\n this.ws = ws\n this.sessionHandler = new SessionHandler(sc, this.configuration)\n\n // Attempt to reactivate the existing session on the new channel.\n if (this.session) {\n const reactivated = await this.sessionHandler.tryActivateExistingSession(\n this.session.getAuthToken(),\n this.session.getSessionId(),\n this.session.getEndpoint(),\n this.identity,\n )\n if (reactivated !== null) {\n this.session = reactivated\n this.logger.info('Existing session successfully reactivated on new channel.')\n return\n }\n this.logger.info('ActivateSession for existing session failed; creating a fresh session...')\n }\n\n // Fall back: full CreateSession + ActivateSession.\n this.session = await this.sessionHandler.createNewSession(this.identity)\n this.logger.info('Fresh session established on new channel.')\n }\n\n /**\n * Gracefully disconnects from the OPC UA server.\n *\n * Sequence per OPC UA Part 4, Section 5.7.4:\n * 1. CloseSession (deleteSubscriptions=true) so the server frees all resources.\n * 2. Close the SecureChannel, which cancels the pending token-renewal timer.\n * 3. Close the WebSocket transport.\n *\n * CloseSession errors are swallowed so transport teardown always completes even\n * when the session has already expired on the server side.\n */\n async disconnect(): Promise<void> {\n this.logger.info('Disconnecting from OPC UA server...')\n this.stopKeepAlive()\n\n if (this.session && this.sessionHandler) {\n try {\n await this.sessionHandler.closeSession(true)\n } catch (err) {\n // Session may already be gone on the server; log and continue teardown.\n this.logger.warn('CloseSession failed (continuing teardown):', err)\n }\n this.session = undefined\n }\n\n this.secureChannelFacade?.close()\n this.secureChannelFacade = undefined\n this.secureChannel = undefined\n\n this.ws?.close()\n this.ws = undefined\n\n this.logger.info('Disconnected.')\n }\n\n async read(ids: NodeId[]): Promise<ReadValueResult[]> {\n return this.withSessionRefresh(async () => {\n const result = await this.attributeService?.ReadValue(ids)\n return result?.map(r => new ReadValueResult(r.value, r.statusCode)) ?? []\n })\n }\n\n /**\n * Method for calling a single method on the server.\n * @param objectId - NodeId of the Object that owns the method.\n * @param methodId - NodeId of the Method to invoke.\n * @param inputArguments - Input argument Variants (default: empty).\n * @returns The CallMethodResult for the invoked method.\n */\n async callMethod(\n objectId: NodeId,\n methodId: NodeId,\n inputArguments: CallMethodArgument[] = []\n ): Promise<CallMethodResult> {\n return this.withSessionRefresh(async () => {\n const request = new CallMethodRequest()\n request.objectId = objectId\n request.methodId = methodId\n request.inputArguments = inputArguments.map(arg => Variant.newFrom(arg as Parameters<typeof Variant.newFrom>[0]))\n\n const responses = await this.methodService!.call([request])\n const response = responses[0]\n return new CallMethodResult(response.value, response.statusCode)\n })\n }\n\n async browse(\n nodeId: NodeId,\n recursive: boolean = false,\n ): Promise<BrowseNodeResult[]> {\n return this.withSessionRefresh(() => {\n const visited = new Set<string>()\n return this.browseRecursive(nodeId, recursive, visited)\n })\n }\n\n private async browseRecursive(\n nodeId: NodeId,\n recursive: boolean,\n visited: Set<string>,\n ): Promise<BrowseNodeResult[]> {\n const nodeKey = `${nodeId.namespace}:${nodeId.identifier}`;\n if (visited.has(nodeKey)) {\n return [];\n }\n visited.add(nodeKey);\n\n const description = new BrowseDescription();\n description.nodeId = nodeId;\n description.browseDirection = BrowseDirectionEnum.Forward;\n description.referenceTypeId = NodeId.newNumeric(0, 33); // HierarchicalReferences\n description.includeSubtypes = true;\n description.nodeClassMask = 0; // all node classes\n description.resultMask = BrowseResultMaskEnum.All;\n\n const browseResults = await this.browseService!.browse([description]);\n const browseResult = browseResults[0];\n const allReferences = [...(browseResult.references ?? [])];\n\n let continuationPoint = browseResult.continuationPoint;\n while (continuationPoint && continuationPoint.byteLength > 0) {\n const nextResults = await this.browseService!\n .browseNext([continuationPoint], false);\n const nextResult = nextResults[0];\n allReferences.push(...(nextResult.references ?? []));\n continuationPoint = nextResult.continuationPoint;\n }\n\n const results = allReferences.map((ref: ReferenceDescription) =>\n new BrowseNodeResult(\n ref.referenceTypeId,\n ref.isForward,\n ref.nodeId,\n ref.browseName,\n ref.displayName,\n ref.nodeClass,\n ref.typeDefinition,\n )\n );\n\n if (recursive) {\n for (const ref of allReferences) {\n const childNodeId = NodeId.newNumeric(\n ref.nodeId.nodeId.namespace,\n ref.nodeId.nodeId.identifier as number,\n );\n const childResults = await this.browseRecursive(\n childNodeId, true, visited,\n );\n results.push(...childResults);\n }\n }\n\n return results;\n }\n\n async subscribe(\n ids: NodeId[],\n callback: (data: { id: NodeId; value: unknown }[]) => void,\n ) {\n this.subscriptionHandler?.subscribe(ids, callback);\n }\n\n constructor(\n endpointUrl: string,\n private configuration: ConfigurationClient,\n private identity: UserIdentity,\n ) {\n this.endpointUrl = endpointUrl;\n initLoggerProvider(configuration.loggerFactory);\n this.logger = getLogger(\"Client\");\n }\n}\n","import {\n BinaryReader,\n BinaryWriter,\n Configuration,\n Decoder,\n Encoder,\n ILoggerFactory,\n LoggerFactory,\n registerBinaryDecoders,\n registerEncoders,\n registerTypeDecoders\n} from \"opcjs-base\";\n\nimport type { SecurityConfiguration } from './securityConfiguration.js'\n\nexport class ConfigurationClient extends Configuration {\n /**\n * Optional security restrictions applied during `Client.connect()`.\n * When not set, permissive defaults are used (SecurityPolicy None allowed,\n * all user-token types accepted).\n *\n * @see SecurityConfiguration\n */\n public securityConfiguration?: SecurityConfiguration\n public static getSimple(\n name: string,\n company: string,\n loggerFactory?: ILoggerFactory,\n ): ConfigurationClient {\n\n if (!loggerFactory) {\n loggerFactory = new LoggerFactory({\n defaultLevel: 'DEBUG', //todo: use enum\n categoryLevels: {\n \"transport.*\": \"TRACE\",\n \"secureChannel.*\": \"TRACE\",\n },\n });\n }\n const applicationUri = `urn:${company}:${name}`;\n const productUri = `urn:${company}:${name}:product`;\n\n const encoder = new Encoder();\n encoder.registerWriterFactory(\"binary\", () => {\n return new BinaryWriter();\n });\n registerEncoders(encoder);\n\n const decoder = new Decoder();\n decoder.registerReaderFactory(\"binary\", (data: unknown) => {\n return new BinaryReader(data as Uint8Array);\n });\n registerTypeDecoders(decoder);\n registerBinaryDecoders(decoder);\n\n return new ConfigurationClient(\n name,\n applicationUri,\n name,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n\n constructor(\n applicationName: string,\n applicationUri: string,\n productName: string,\n productUri: string,\n encoder: Encoder,\n decoder: Decoder,\n loggerFactory: ILoggerFactory,\n ) {\n super(\n applicationName,\n applicationUri,\n productName,\n productUri,\n encoder,\n decoder,\n loggerFactory,\n );\n }\n}\n","import { IssuedIdentityToken, UserIdentityToken, UserNameIdentityToken, UserTokenTypeEnum } from \"opcjs-base\";\nimport { IssuerConfiguration } from \"./issuerConfiguration\";\nimport { IssuerToken } from \"./issuerToken\";\nimport { AnonymousIdentityToken } from \"opcjs-base\";\n\nexport class UserIdentity {\n private userIdentityToken?: UserIdentityToken;\n private tokenType = UserTokenTypeEnum.Anonymous;\n private issuerLoginCallback: ((config:IssuerConfiguration)=>Promise<IssuerToken>) | undefined = undefined;\n\n public static newAnonymous(): UserIdentity {\n const userIdentity = new UserIdentity();\n userIdentity.userIdentityToken = new AnonymousIdentityToken();\n userIdentity.userIdentityToken.policyId = \"anonymous\";\n userIdentity.tokenType = UserTokenTypeEnum.Anonymous;\n return userIdentity;\n }\n \n public static newWithUserName(userName: string, password: string): UserIdentity {\n const userIdentity = new UserIdentity();\n const nameToken = new UserNameIdentityToken();\n nameToken.userName = userName;\n nameToken.password = new TextEncoder().encode(password);\n\n userIdentity.userIdentityToken = nameToken;\n userIdentity.tokenType = UserTokenTypeEnum.UserName;\n return userIdentity;\n }\n\n public static newWithIssuerToken(loginCallback: (config:IssuerConfiguration)=>Promise<IssuerToken>): UserIdentity {\n const userIdentity = new UserIdentity();\n const issuedToken = new IssuedIdentityToken();\n issuedToken.tokenData = new TextEncoder().encode(\"\"); // token data will be filled by the login callback \n userIdentity.userIdentityToken = issuedToken;\n userIdentity.tokenType = UserTokenTypeEnum.IssuedToken;\n userIdentity.issuerLoginCallback = loginCallback;\n return userIdentity;\n }\n\n public getUserIdentityToken(): UserIdentityToken {\n return this.userIdentityToken as UserIdentityToken;\n }\n\n public getTokenType(): UserTokenTypeEnum {\n return this.tokenType;\n }\n\n public getIssuerLoginCallback(): ((config:IssuerConfiguration)=>Promise<IssuerToken>) {\n if(!this.issuerLoginCallback){\n throw new Error(\"No issuer login callback defined\");\n }\n \n return this.issuerLoginCallback;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opcjs-client",
3
- "version": "0.1.34-alpha",
3
+ "version": "0.1.35-alpha",
4
4
  "description": "A client for OPC UA communication.",
5
5
  "repository": {
6
6
  "type": "git",