@zwave-js/cc 15.25.3 → 15.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src_gen/cc/Security2CC.ts"],
4
- "sourcesContent": ["import { CommandClasses, EncapsulationFlags, type GetNode, type GetValueDB, MPANState, type MaybeNotKnown, type MessageOrCCLogEntry, MessagePriority, type MessageRecord, type MulticastDestination, NODE_ID_BROADCAST, NODE_ID_BROADCAST_LR, type NodeId, type S2SecurityClass, SPANState, type SPANTableEntry, SecurityClass, type SecurityManager2, type SecurityManagers, type SupportsCC, TransmitOptions, type WithAddress, ZWaveError, ZWaveErrorCodes, decryptAES128CCM, encodeBitMask, encodeCCList, encryptAES128CCM, getCCName, highResTimestamp, isLongRangeNodeId, isTransmissionError, isZWaveError, logDict, logList, logText, parseBitMask, parseCCList, securityClassIsS2, securityClassOrder, validatePayload, } from \"@zwave-js/core\";\nimport { Bytes, type BytesView, buffer2hex, getEnumMemberName, pick, } from \"@zwave-js/shared\";\nimport { wait } from \"alcalzone-shared/async\";\nimport { isArray } from \"alcalzone-shared/typeguards\";\nimport { CCAPI } from \"../lib/API.js\";\nimport { type CCRaw, type CCResponseRole, CommandClass, type InterviewContext, } from \"../lib/CommandClass.js\";\nimport { API, CCCommand, commandClass, expectedCCResponse, implementedVersion, } from \"../lib/CommandClassDecorators.js\";\nimport { MGRPExtension, MOSExtension, MPANExtension, SPANExtension, Security2Extension, ValidateS2ExtensionResult, validateS2Extension, } from \"../lib/Security2/Extension.js\";\nimport { ECDHProfiles, KEXFailType, KEXSchemes, } from \"../lib/Security2/shared.js\";\nimport { Security2Command } from \"../lib/_Types.js\";\nimport type { CCEncodingContext, CCParsingContext } from \"../lib/traits.js\";\nimport { CRC16CC } from \"./CRC16CC.js\";\nimport { MultiChannelCC } from \"./MultiChannelCC.js\";\nimport { SecurityCC } from \"./SecurityCC.js\";\nimport { TransportServiceCC } from \"./TransportServiceCC.js\";\nfunction securityClassToBitMask(key: SecurityClass): Bytes {\n return encodeBitMask([key], SecurityClass.S0_Legacy, SecurityClass.S2_Unauthenticated);\n}\nfunction bitMaskToSecurityClass(buffer: BytesView, offset: number): SecurityClass {\n const keys = parseBitMask(buffer.subarray(offset, offset + 1), SecurityClass.S2_Unauthenticated);\n validatePayload(keys.length === 1);\n return keys[0];\n}\nconst SECURITY_S2_AUTH_TAG_LENGTH = 8;\nfunction getAuthenticationData(sendingNodeId: number, destination: number, homeId: number, commandLength: number, unencryptedPayload: BytesView): BytesView {\n const nodeIdSize = isLongRangeNodeId(sendingNodeId) || isLongRangeNodeId(destination)\n ? 2\n : 1;\n const ret = new Bytes(2 * nodeIdSize + 6 + unencryptedPayload.length);\n let offset = 0;\n ret.writeUIntBE(sendingNodeId, offset, nodeIdSize);\n offset += nodeIdSize;\n ret.writeUIntBE(destination, offset, nodeIdSize);\n offset += nodeIdSize;\n ret.writeUInt32BE(homeId, offset);\n offset += 4;\n ret.writeUInt16BE(commandLength, offset);\n offset += 2;\n // This includes the sequence number and all unencrypted extensions\n ret.set(unencryptedPayload, offset);\n return ret;\n}\nfunction getSecurityManager(ownNodeId: number, securityManagers: SecurityManagers, otherNodeId: MulticastDestination | number): SecurityManager2 | undefined {\n const longRange = isLongRangeNodeId(ownNodeId)\n || isLongRangeNodeId(isArray(otherNodeId) ? otherNodeId[0] : otherNodeId);\n return longRange\n ? securityManagers.securityManagerLR\n : securityManagers.securityManager2;\n}\n/** Validates that a sequence number is not a duplicate and updates the SPAN table if it is accepted. Returns the previous sequence number if there is one. */\nfunction validateSequenceNumber(securityManager: SecurityManager2, sourceNodeId: number, sequenceNumber: number): number | undefined {\n validatePayload.withReason(`Duplicate command (sequence number ${sequenceNumber})`)(!securityManager.isDuplicateSinglecast(sourceNodeId, sequenceNumber));\n // Not a duplicate, store it\n return securityManager.storeSequenceNumber(sourceNodeId, sequenceNumber);\n}\nconst MAX_DECRYPT_ATTEMPTS_SINGLECAST = 5;\nconst MAX_DECRYPT_ATTEMPTS_MULTICAST = 5;\nconst MAX_DECRYPT_ATTEMPTS_SC_FOLLOWUP = 1;\n// @publicAPI\nexport interface DecryptionResult {\n plaintext: BytesView;\n authOK: boolean;\n key?: BytesView;\n iv?: BytesView;\n securityClass: SecurityClass | undefined;\n}\nfunction assertSecurityRX(ctx: CCParsingContext): SecurityManager2 {\n if (!ctx.ownNodeId) {\n throw new ZWaveError(`Secure commands (S2) can only be decoded when the controller's node id is known!`, ZWaveErrorCodes.Driver_NotReady);\n }\n const ret = getSecurityManager(ctx.ownNodeId, ctx, ctx.sourceNodeId);\n if (!ret) {\n throw new ZWaveError(`Secure commands (S2) can only be decoded when the security manager is set up!`, ZWaveErrorCodes.Driver_NoSecurity);\n }\n return ret;\n}\nfunction assertSecurityTX(ctx: CCEncodingContext, destination: MulticastDestination | number): SecurityManager2 {\n if (!ctx.ownNodeId) {\n throw new ZWaveError(`Secure commands (S2) can only be sent when the controller's node id is known!`, ZWaveErrorCodes.Driver_NotReady);\n }\n const ret = getSecurityManager(ctx.ownNodeId, ctx, destination);\n if (!ret) {\n throw new ZWaveError(`Secure commands (S2) can only be sent when the security manager is set up!`, ZWaveErrorCodes.Driver_NoSecurity);\n }\n return ret;\n}\nasync function decryptSinglecast(ctx: CCParsingContext, securityManager: SecurityManager2, sendingNodeId: number, curSequenceNumber: number, prevSequenceNumber: number, ciphertext: BytesView, authData: BytesView, authTag: BytesView, spanState: SPANTableEntry & {\n type: SPANState.SPAN | SPANState.LocalEI;\n}, extensions: Security2Extension[]): Promise<DecryptionResult> {\n const decryptWithNonce = async (nonce: BytesView) => {\n const { keyCCM: key } = securityManager.getKeysForNode(sendingNodeId);\n const iv = nonce;\n const ret = await decryptAES128CCM(ciphertext, key, iv, authData, authTag);\n return {\n key,\n iv,\n ...ret,\n };\n };\n const getNonceAndDecrypt = async () => {\n const iv = await securityManager.nextNonce(sendingNodeId);\n return decryptWithNonce(iv);\n };\n if (spanState.type === SPANState.SPAN) {\n // There SHOULD be a shared SPAN between both parties. But experience has shown that both could have\n // sent a command at roughly the same time, using the same SPAN for encryption.\n // To avoid a nasty desync and both nodes trying to resync at the same time, causing message loss,\n // we accept commands encrypted with the previous SPAN under very specific circumstances:\n if (\n // The previous SPAN is still known, i.e. the node didn't send another command that was successfully decrypted\n !!spanState.currentSPAN\n // it is still valid\n && spanState.currentSPAN.expires > highResTimestamp()\n // The received command is exactly the next, expected one\n && prevSequenceNumber != undefined\n && curSequenceNumber === ((prevSequenceNumber + 1) & 0xff)\n // And in case of a mock-based test, do this only on the controller\n && !ctx.__internalIsMockNode) {\n const nonce = spanState.currentSPAN.nonce;\n spanState.currentSPAN = undefined;\n // If we could decrypt this way, we're done...\n const result = await decryptWithNonce(nonce);\n if (result.authOK) {\n return {\n ...result,\n securityClass: spanState.securityClass,\n };\n }\n // ...otherwise, we need to try the normal way\n }\n else {\n // forgetting the current SPAN shouldn't be necessary but better be safe than sorry\n spanState.currentSPAN = undefined;\n }\n // This can only happen if the security class is known\n return {\n ...(await getNonceAndDecrypt()),\n securityClass: spanState.securityClass,\n };\n }\n else if (spanState.type === SPANState.LocalEI) {\n // We've sent the other our receiver's EI and received its sender's EI,\n // meaning we can now establish an SPAN\n const senderEI = getSenderEI(extensions);\n if (!senderEI)\n failNoSPAN();\n const receiverEI = spanState.receiverEI;\n // How we do this depends on whether we know the security class of the other node\n const isBootstrappingNode = securityManager.tempKeys.has(sendingNodeId);\n if (isBootstrappingNode) {\n // We're currently bootstrapping the node, it might be using a temporary key\n await securityManager.initializeTempSPAN(sendingNodeId, senderEI, receiverEI);\n const ret = await getNonceAndDecrypt();\n // Decryption with the temporary key worked\n if (ret.authOK) {\n return {\n ...ret,\n securityClass: SecurityClass.Temporary,\n };\n }\n // Reset the SPAN state and try with the recently granted security class\n securityManager.setSPANState(sendingNodeId, spanState);\n }\n // When ending up here, one of two situations has occured:\n // a) We've taken over an existing network and do not know the node's security class\n // b) We know the security class, but we're about to establish a new SPAN. This may happen at a lower\n // security class than the one the node normally uses, e.g. when we're being queried for securely\n // supported CCs.\n // In both cases, we should simply try decoding with multiple security classes, starting from the highest one.\n // If this fails, we restore the previous (partial) SPAN state.\n // Try all security classes where we do not definitely know that it was not granted\n // While bootstrapping a node, we consider the key that is being exchanged (including S0) to be the highest. No need to look at others\n const possibleSecurityClasses = isBootstrappingNode\n ? [ctx.getHighestSecurityClass(sendingNodeId)!]\n : securityClassOrder.filter((s) => ctx.hasSecurityClass(sendingNodeId, s)\n !== false);\n for (const secClass of possibleSecurityClasses) {\n // Skip security classes we don't have keys for\n if (!securityManager.hasKeysForSecurityClass(secClass)) {\n continue;\n }\n // Initialize an SPAN with that security class\n await securityManager.initializeSPAN(sendingNodeId, secClass, senderEI, receiverEI);\n const ret = await getNonceAndDecrypt();\n // It worked, return the result\n if (ret.authOK) {\n // Also if we weren't sure before, we now know that the security class is granted\n if (ctx.hasSecurityClass(sendingNodeId, secClass)\n === undefined) {\n ctx.setSecurityClass(sendingNodeId, secClass, true);\n }\n return {\n ...ret,\n securityClass: secClass,\n };\n }\n else {\n // Reset the SPAN state and try with the next security class\n securityManager.setSPANState(sendingNodeId, spanState);\n }\n }\n }\n // Nothing worked, fail the decryption\n return {\n plaintext: new Uint8Array(),\n authOK: false,\n securityClass: undefined,\n };\n}\nasync function decryptMulticast(sendingNodeId: number, securityManager: SecurityManager2, groupId: number, ciphertext: BytesView, authData: BytesView, authTag: BytesView): Promise<DecryptionResult> {\n const iv = await securityManager.nextPeerMPAN(sendingNodeId, groupId);\n const { keyCCM: key } = securityManager.getKeysForNode(sendingNodeId);\n return {\n key,\n iv,\n ...(await decryptAES128CCM(ciphertext, key, iv, authData, authTag)),\n // The security class is irrelevant when decrypting multicast commands\n securityClass: undefined,\n };\n}\nfunction parseExtensions(buffer: BytesView, wasEncrypted: boolean): {\n extensions: Security2Extension[];\n mustDiscardCommand: boolean;\n bytesRead: number;\n} {\n const extensions: Security2Extension[] = [];\n let mustDiscardCommand = false;\n let offset = 0;\n parsing: while (true) {\n if (buffer.length < offset + 2) {\n // An S2 extension was expected, but the buffer is too short\n mustDiscardCommand = true;\n break parsing;\n }\n // The length field could be too large, which would cause part of the actual ciphertext\n // to be ignored. Try to avoid this for known extensions by checking the actual and expected length.\n const { actual: actualLength, expected: expectedLength } = Security2Extension\n .getExtensionLength(buffer.subarray(offset));\n // Parse the extension using the expected length if possible\n const extensionLength = expectedLength ?? actualLength;\n if (extensionLength < 2) {\n // An S2 extension was expected, but the length is too short\n mustDiscardCommand = true;\n break parsing;\n }\n else if (extensionLength\n > buffer.length\n - offset\n - (wasEncrypted\n ? 0\n : SECURITY_S2_AUTH_TAG_LENGTH)) {\n // The supposed length is longer than the space the extensions may occupy\n mustDiscardCommand = true;\n break parsing;\n }\n const extensionData = buffer.subarray(offset, offset + extensionLength);\n offset += extensionLength;\n const ext = Security2Extension.parse(extensionData);\n switch (validateS2Extension(ext, wasEncrypted)) {\n case ValidateS2ExtensionResult.OK:\n if (expectedLength != undefined\n && actualLength !== expectedLength) {\n // The extension length field does not match, ignore the extension\n }\n else {\n extensions.push(ext);\n }\n break;\n case ValidateS2ExtensionResult.DiscardExtension:\n // Do nothing\n break;\n case ValidateS2ExtensionResult.DiscardCommand:\n mustDiscardCommand = true;\n break;\n }\n // Check if that was the last extension\n if (!ext.moreToFollow)\n break parsing;\n }\n return {\n extensions,\n mustDiscardCommand,\n bytesRead: offset,\n };\n}\nfunction getDestinationIDTX(this: Security2CC & {\n extensions: Security2Extension[];\n}): number {\n if (this.isSinglecast())\n return this.nodeId;\n const ret = getMulticastGroupId(this.extensions);\n if (ret == undefined) {\n throw new ZWaveError(\"Multicast Security S2 encapsulation requires the MGRP extension\", ZWaveErrorCodes.Security2CC_MissingExtension);\n }\n return ret;\n}\nfunction getDestinationIDRX(ctx: CCParsingContext, extensions: Security2Extension[]): number {\n if (ctx.frameType === \"singlecast\") {\n return ctx.ownNodeId;\n }\n const ret = getMulticastGroupId(extensions);\n if (ret == undefined) {\n throw new ZWaveError(\"Multicast Security S2 encapsulation requires the MGRP extension\", ZWaveErrorCodes.Security2CC_MissingExtension);\n }\n return ret;\n}\nfunction getMulticastGroupId(extensions: Security2Extension[]): number | undefined {\n const mgrpExtension = extensions.find((e) => e instanceof MGRPExtension);\n return mgrpExtension?.groupId;\n}\n/** Returns the Sender's Entropy Input if this command contains an SPAN extension */\nfunction getSenderEI(extensions: Security2Extension[]): BytesView | undefined {\n const spanExtension = extensions.find((e) => e instanceof SPANExtension);\n return spanExtension?.senderEI;\n}\n// Encapsulation CCs are used internally and too frequently that we\n// want to pay the cost of validating each call\n/* eslint-disable @zwave-js/ccapi-validate-args */\n@API(CommandClasses[\"Security 2\"])\nexport class Security2CCAPI extends CCAPI {\n public supportsCommand(_cmd: Security2Command): MaybeNotKnown<boolean> {\n // All commands are mandatory\n return true;\n }\n /**\n * Sends a nonce to the node, either in response to a NonceGet request or a message that failed to decrypt. The message is sent without any retransmission etc.\n * The return value indicates whether a nonce was successfully sent\n */\n public async sendNonce(): Promise<boolean> {\n this.assertSupportsCommand(Security2Command, Security2Command.NonceReport);\n this.assertPhysicalEndpoint(this.endpoint);\n const securityManager = getSecurityManager(this.host.ownNodeId, this.host, this.endpoint.nodeId);\n if (!securityManager) {\n throw new ZWaveError(`Nonces can only be sent if secure communication is set up!`, ZWaveErrorCodes.Driver_NoSecurity);\n }\n const receiverEI = await securityManager.generateNonce(this.endpoint.nodeId);\n const cc = new Security2CCNonceReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n SOS: true,\n MOS: false,\n receiverEI,\n });\n try {\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Seems we need these options or some nodes won't accept the nonce\n transmitOptions: TransmitOptions.ACK\n | TransmitOptions.AutoRoute,\n // Only try sending a nonce once\n maxSendAttempts: 1,\n // Nonce requests must be handled immediately\n priority: MessagePriority.Immediate,\n // We don't want failures causing us to treat the node as asleep or dead\n changeNodeStatusOnMissingACK: false,\n // And we need to react to\n });\n }\n catch (e) {\n if (isTransmissionError(e)) {\n // The nonce could not be sent, invalidate it\n securityManager.deleteNonce(this.endpoint.nodeId);\n return false;\n }\n else {\n // Pass other errors through\n throw e;\n }\n }\n return true;\n }\n /** Notifies the target node that the MPAN state is out of sync */\n public async sendMOS(): Promise<boolean> {\n this.assertSupportsCommand(Security2Command, Security2Command.NonceReport);\n this.assertPhysicalEndpoint(this.endpoint);\n const cc = new Security2CCNonceReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n SOS: false,\n MOS: true,\n });\n try {\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Seems we need these options or some nodes won't accept the nonce\n transmitOptions: TransmitOptions.ACK\n | TransmitOptions.AutoRoute,\n // Only try sending a nonce once\n maxSendAttempts: 1,\n // Nonce requests must be handled immediately\n priority: MessagePriority.Immediate,\n // We don't want failures causing us to treat the node as asleep or dead\n changeNodeStatusOnMissingACK: false,\n });\n }\n catch (e) {\n if (isTransmissionError(e)) {\n return false;\n }\n else {\n // Pass other errors through\n throw e;\n }\n }\n return true;\n }\n /** Sends the given MPAN to the node */\n public async sendMPAN(groupId: number, innerMPANState: BytesView): Promise<boolean> {\n this.assertSupportsCommand(Security2Command, Security2Command.MessageEncapsulation);\n this.assertPhysicalEndpoint(this.endpoint);\n const cc = new Security2CCMessageEncapsulation({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n extensions: [\n new MPANExtension({\n groupId,\n innerMPANState,\n }),\n ],\n });\n try {\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Seems we need these options or some nodes won't accept the nonce\n transmitOptions: TransmitOptions.ACK\n | TransmitOptions.AutoRoute,\n // Only try sending a nonce once\n maxSendAttempts: 1,\n // Nonce requests must be handled immediately\n priority: MessagePriority.Immediate,\n // We don't want failures causing us to treat the node as asleep or dead\n changeNodeStatusOnMissingACK: false,\n });\n }\n catch (e) {\n if (isTransmissionError(e)) {\n return false;\n }\n else {\n // Pass other errors through\n throw e;\n }\n }\n return true;\n }\n /**\n * Queries the securely supported commands for the current security class\n * @param securityClass Can be used to overwrite the security class to use. If this doesn't match the current one, new nonces will need to be exchanged.\n */\n public async getSupportedCommands(securityClass: SecurityClass.S2_AccessControl | SecurityClass.S2_Authenticated | SecurityClass.S2_Unauthenticated): Promise<MaybeNotKnown<CommandClasses[]>> {\n this.assertSupportsCommand(Security2Command, Security2Command.CommandsSupportedGet);\n let cc: CommandClass = new Security2CCCommandsSupportedGet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n });\n // Security2CCCommandsSupportedGet is special because we cannot reply on the applHost to do the automatic\n // encapsulation because it would use a different security class. Therefore the entire possible stack\n // of encapsulation needs to be done here\n if (MultiChannelCC.requiresEncapsulation(cc)) {\n const multiChannelCCVersion = this.host.getSupportedCCVersion(CommandClasses[\"Multi Channel\"], this.endpoint.nodeId as number);\n cc = multiChannelCCVersion === 1\n ? MultiChannelCC.encapsulateV1(cc)\n : MultiChannelCC.encapsulate(cc);\n }\n cc = Security2CC.encapsulate(cc, this.host.ownNodeId, this.host, { securityClass });\n const response = await this.host.sendCommand<Security2CCCommandsSupportedReport>(cc, {\n ...this.commandOptions,\n autoEncapsulate: false,\n });\n return response?.supportedCCs;\n }\n public async reportSupportedCommands(supportedCCs: CommandClasses[]): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.CommandsSupportedReport);\n const cc = new Security2CCCommandsSupportedReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n supportedCCs,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n // oxlint-disable-next-line typescript/explicit-module-boundary-types\n public async getKeyExchangeParameters() {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXGet);\n const cc = new Security2CCKEXGet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n });\n const response = await this.host.sendCommand<Security2CCKEXReport>(cc, this.commandOptions);\n if (response) {\n return pick(response, [\n \"requestCSA\",\n \"echo\",\n \"supportedKEXSchemes\",\n \"supportedECDHProfiles\",\n \"requestedKeys\",\n \"_reserved\",\n ]);\n }\n }\n /** Requests the given keys from an including node */\n public async requestKeys(params: Omit<Security2CCKEXReportOptions, \"echo\">): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXReport);\n const cc = new Security2CCKEXReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: false,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n /** Grants the joining node the given keys */\n public async grantKeys(params: Omit<Security2CCKEXSetOptions, \"echo\">): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXSet);\n const cc = new Security2CCKEXSet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: false,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n /** Confirms the keys that were requested by a node */\n public async confirmRequestedKeys(params: Omit<Security2CCKEXReportOptions, \"echo\">): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXReport);\n const cc = new Security2CCKEXReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: true,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n /** Confirms the keys that were granted by the including node */\n public async confirmGrantedKeys(params: Omit<Security2CCKEXSetOptions, \"echo\">): Promise<Security2CCKEXReport | Security2CCKEXFail | undefined> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXSet);\n const cc = new Security2CCKEXSet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: true,\n });\n return this.host.sendCommand(cc, this.commandOptions);\n }\n /** Notifies the other node that the ongoing key exchange was aborted */\n public async abortKeyExchange(failType: KEXFailType): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXFail);\n const cc = new Security2CCKEXFail({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n failType,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async sendPublicKey(publicKey: BytesView, includingNode: boolean = true): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.PublicKeyReport);\n const cc = new Security2CCPublicKeyReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n includingNode,\n publicKey,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async requestNetworkKey(securityClass: SecurityClass): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.NetworkKeyGet);\n const cc = new Security2CCNetworkKeyGet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n requestedKey: securityClass,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async sendNetworkKey(securityClass: SecurityClass, networkKey: BytesView): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.NetworkKeyReport);\n const cc = new Security2CCNetworkKeyReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n grantedKey: securityClass,\n networkKey,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async verifyNetworkKey(): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.NetworkKeyVerify);\n const cc = new Security2CCNetworkKeyVerify({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async confirmKeyVerification(): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.TransferEnd);\n const cc = new Security2CCTransferEnd({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n keyVerified: true,\n keyRequestComplete: false,\n });\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Don't wait for an ACK from the node\n transmitOptions: TransmitOptions.DEFAULT & ~TransmitOptions.ACK,\n });\n }\n public async endKeyExchange(): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.TransferEnd);\n const cc = new Security2CCTransferEnd({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n keyVerified: false,\n keyRequestComplete: true,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n}\n@commandClass(CommandClasses[\"Security 2\"])\n@implementedVersion(1)\nexport class Security2CC extends CommandClass {\n declare ccCommand: Security2Command;\n public async interview(ctx: InterviewContext): Promise<void> {\n const securityManager = getSecurityManager(ctx.ownNodeId, ctx, this.nodeId);\n const node = this.getNode(ctx)!;\n const endpoint = this.getEndpoint(ctx)!;\n const api = CCAPI.create(CommandClasses[\"Security 2\"], ctx, endpoint).withOptions({\n priority: MessagePriority.NodeQuery,\n tag: \"interview\",\n });\n // Only on the highest security class the response includes the supported commands\n const secClass = node.getHighestSecurityClass();\n let hasReceivedSecureCommands = false;\n let possibleSecurityClasses: S2SecurityClass[];\n if (securityClassIsS2(secClass)) {\n // The highest security class is known to be S2, only query that one\n possibleSecurityClasses = [secClass];\n }\n else if (endpoint.index === 0) {\n // If the highest security class isn't known, query all possible security classes\n // but only on the root device\n possibleSecurityClasses = [\n SecurityClass.S2_Unauthenticated,\n SecurityClass.S2_Authenticated,\n SecurityClass.S2_AccessControl,\n ];\n }\n else {\n // For endpoint interviews, the security class MUST be known\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Cannot query securely supported commands for endpoint because the node's security class isn't known...`,\n level: \"error\",\n });\n return;\n }\n for (const secClass of possibleSecurityClasses) {\n // We might not know all assigned security classes yet, so we work our way up from low to high and try to request the supported commands.\n // This way, each command is encrypted with the security class we're currently testing.\n // If the node does not respond, it wasn't assigned the security class.\n // If it responds with a non-empty list, we know this is the highest class it supports.\n // If the list is empty, the security class is still supported.\n // If we already know the class is not supported, skip it\n if (node.hasSecurityClass(secClass) === false)\n continue;\n // If no key is configured for this security class, skip it\n if (!securityManager?.hasKeysForSecurityClass(secClass)) {\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Cannot query securely supported commands (${getEnumMemberName(SecurityClass, secClass)}) - network key is not configured...`,\n level: \"warn\",\n });\n continue;\n }\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)})...`,\n direction: \"outbound\",\n });\n // Query the supported commands but avoid remembering the wrong security class in case of a failure\n let supportedCCs: CommandClasses[] | undefined;\n // Try up to 3 times on the root device. We REALLY don't want a spurious timeout or collision to cause us to discard a known good security class\n const MAX_ATTEMPTS = this.endpointIndex === 0 ? 3 : 1;\n for (let attempts = 1; attempts <= MAX_ATTEMPTS; attempts++) {\n try {\n supportedCCs = await api.getSupportedCommands(secClass);\n }\n catch (e) {\n if (isZWaveError(e)\n && e.code === ZWaveErrorCodes.Security2CC_CannotDecode) {\n // Either we were using a non-granted security class,\n // or querying with the known highest security class had an issue\n supportedCCs = undefined;\n }\n else {\n throw e;\n }\n }\n if (supportedCCs == undefined\n && possibleSecurityClasses.length === 1) {\n if (attempts < MAX_ATTEMPTS) {\n // We definitely know the highest security class\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)}), attempt ${attempts}/${MAX_ATTEMPTS} failed. Retrying in 500ms...`,\n level: \"warn\",\n });\n await wait(500);\n continue;\n }\n else if (endpoint.index > 0) {\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)}) failed. Assuming the endpoint supports all its mandatory CCs securely...`,\n level: \"warn\",\n });\n // Just mark all endpoint CCs as secure. Without this we would attempt\n // unencrypted communication with the endpoint, which will likely fail.\n for (const [ccId] of endpoint.getCCs()) {\n endpoint.addCC(ccId, { secure: true });\n }\n break;\n }\n else {\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)}) failed. Let's hope for the best...`,\n level: \"warn\",\n });\n break;\n }\n }\n else {\n // In any other case, we can stop trying\n break;\n }\n }\n if (supportedCCs == undefined) {\n if (endpoint.index === 0\n && possibleSecurityClasses.length > 1) {\n // No supported commands found, mark the security class as not granted\n // unless we were sure about the security class\n node.setSecurityClass(secClass, false);\n ctx.logNode(node.id, {\n message: `The node was NOT granted the security class ${getEnumMemberName(SecurityClass, secClass)}`,\n direction: \"inbound\",\n });\n }\n continue;\n }\n if (endpoint.index === 0 && possibleSecurityClasses.length > 1) {\n // Mark the security class as granted unless we were sure about the security class\n node.setSecurityClass(secClass, true);\n ctx.logNode(node.id, {\n message: `The node was granted the security class ${getEnumMemberName(SecurityClass, secClass)}`,\n direction: \"inbound\",\n });\n }\n if (!hasReceivedSecureCommands && supportedCCs.length > 0) {\n hasReceivedSecureCommands = true;\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: logText([\n `received secure commands (${getEnumMemberName(SecurityClass, secClass)})`,\n \"supported CCs:\",\n ], {\n nested: logList(supportedCCs.map((cc) => getCCName(cc))),\n }),\n direction: \"inbound\",\n });\n // Remember which commands are supported securely\n for (const cc of supportedCCs) {\n // Basic CC has special rules for when it is considered supported\n // Therefore we mark all other CCs as supported, but not Basic CC,\n // for which support is determined later.\n if (cc === CommandClasses.Basic) {\n endpoint.addCC(cc, { secure: true });\n }\n else {\n endpoint.addCC(cc, {\n isSupported: true,\n secure: true,\n });\n }\n }\n }\n }\n // Remember that the interview is complete\n this.setInterviewComplete(ctx, true);\n }\n /** Tests if a command should be sent secure and thus requires encapsulation */\n public static requiresEncapsulation(cc: CommandClass): boolean {\n // No security flag -> no encapsulation\n if (!(cc.encapsulationFlags & EncapsulationFlags.Security)) {\n return false;\n }\n // S0, CRC16, Transport Service -> no S2 encapsulation\n if (cc instanceof SecurityCC\n || cc instanceof CRC16CC\n || cc instanceof TransportServiceCC) {\n return false;\n }\n // S2: check command\n if (cc instanceof Security2CC) {\n // These S2 commands need additional encapsulation\n switch (cc.ccCommand) {\n case Security2Command.CommandsSupportedGet:\n case Security2Command.CommandsSupportedReport:\n case Security2Command.NetworkKeyGet:\n case Security2Command.NetworkKeyReport:\n case Security2Command.NetworkKeyVerify:\n case Security2Command.TransferEnd:\n return true;\n case Security2Command.KEXSet:\n case Security2Command.KEXReport:\n // KEXSet/Report need to be encrypted for the confirmation only\n return (cc as Security2CCKEXSet | Security2CCKEXReport)\n .echo;\n case Security2Command.KEXFail: {\n switch ((cc as Security2CCKEXFail).failType) {\n case KEXFailType.Decrypt:\n case KEXFailType.WrongSecurityLevel:\n case KEXFailType.KeyNotGranted:\n case KEXFailType.NoVerify:\n return true;\n default:\n return false;\n }\n }\n }\n return false;\n }\n // Everything else needs to be encapsulated if the CC is secure\n return true;\n }\n /** Encapsulates a command that should be sent encrypted */\n public static encapsulate(cc: CommandClass, ownNodeId: number, securityManagers: SecurityManagers, options?: {\n securityClass?: SecurityClass;\n multicastOutOfSync?: boolean;\n multicastGroupId?: number;\n verifyDelivery?: boolean;\n }): Security2CCMessageEncapsulation {\n // Determine which extensions must be used on the command\n const extensions: Security2Extension[] = [];\n if (options?.multicastOutOfSync) {\n extensions.push(new MOSExtension());\n }\n if (options?.multicastGroupId != undefined) {\n extensions.push(new MGRPExtension({ groupId: options.multicastGroupId }));\n }\n // Make sure that S2 multicast uses broadcasts. While the specs mention that both multicast and broadcast\n // are possible, it has been found that devices treat multicasts like singlecast followups and respond incorrectly.\n let nodeId: number;\n if (cc.isMulticast()) {\n if (cc.nodeId.some((nodeId) => isLongRangeNodeId(nodeId))) {\n nodeId = NODE_ID_BROADCAST_LR;\n }\n else {\n nodeId = NODE_ID_BROADCAST;\n }\n }\n else {\n nodeId = cc.nodeId as number;\n }\n const ret = new Security2CCMessageEncapsulation({\n nodeId,\n encapsulated: cc,\n securityClass: options?.securityClass,\n extensions,\n verifyDelivery: options?.verifyDelivery,\n });\n // Copy the encapsulation flags from the encapsulated command\n // but omit Security, since we're doing that right now\n ret.encapsulationFlags = cc.encapsulationFlags\n & ~EncapsulationFlags.Security;\n return ret;\n }\n}\nfunction failNoSPAN(): never {\n validatePayload.fail(ZWaveErrorCodes.Security2CC_NoSPAN);\n}\nfunction failNoMPAN(): never {\n validatePayload.fail(ZWaveErrorCodes.Security2CC_NoMPAN);\n}\n// @publicAPI\nexport type MulticastContext = {\n isMulticast: true;\n groupId: number;\n} | {\n isMulticast: false;\n groupId?: number;\n};\n// @publicAPI\nexport interface Security2CCMessageEncapsulationOptions {\n sequenceNumber?: number;\n /** Can be used to override the default security class for the command */\n securityClass?: SecurityClass;\n extensions?: Security2Extension[];\n encapsulated?: CommandClass;\n verifyDelivery?: boolean;\n}\n// An S2 encapsulated command may result in a NonceReport to be sent by the node if it couldn't decrypt the message\nfunction getCCResponseForMessageEncapsulation(ctx: GetNode<NodeId & SupportsCC>, sent: Security2CCMessageEncapsulation) {\n if (sent.encapsulated?.expectsCCResponse(ctx)) {\n const ret = [\n Security2CCMessageEncapsulation as any,\n Security2CCNonceReport as any,\n ];\n if (sent.encapsulated instanceof Security2CCKEXSet\n || sent.encapsulated instanceof Security2CCKEXReport\n || sent.encapsulated instanceof Security2CCNetworkKeyGet\n || sent.encapsulated instanceof Security2CCNetworkKeyReport\n || sent.encapsulated instanceof Security2CCNetworkKeyVerify) {\n ret.push(Security2CCKEXFail as any);\n }\n return ret;\n }\n}\nfunction testCCResponseForMessageEncapsulation(sent: Security2CCMessageEncapsulation, received: Security2CCMessageEncapsulation | Security2CCNonceReport | Security2CCKEXFail) {\n if (received instanceof Security2CCMessageEncapsulation) {\n return \"checkEncapsulated\";\n }\n else if (received instanceof Security2CCKEXFail) {\n return true;\n }\n else {\n return received.SOS && !!received.receiverEI;\n }\n}\n@CCCommand(Security2Command.MessageEncapsulation)\n@expectedCCResponse(getCCResponseForMessageEncapsulation, testCCResponseForMessageEncapsulation)\nexport class Security2CCMessageEncapsulation extends Security2CC {\n public constructor(options: WithAddress<Security2CCMessageEncapsulationOptions>) {\n super(options);\n if (!options.encapsulated && !options.extensions?.length) {\n throw new ZWaveError(\"Security S2 encapsulation requires an encapsulated CC and/or extensions\", ZWaveErrorCodes.Argument_Invalid);\n }\n this.sequenceNumber = options.sequenceNumber;\n this.securityClass = options.securityClass;\n if (options.encapsulated) {\n this.encapsulated = options.encapsulated;\n options.encapsulated.encapsulatingCC = this as any;\n }\n this.verifyDelivery = options.verifyDelivery !== false;\n this.extensions = options.extensions ?? [];\n if (typeof this.nodeId !== \"number\"\n && !this.extensions.some((e) => e instanceof MGRPExtension)) {\n throw new ZWaveError(\"Multicast Security S2 encapsulation requires the MGRP extension\", ZWaveErrorCodes.Security2CC_MissingExtension);\n }\n }\n public static async from(raw: CCRaw, ctx: CCParsingContext): Promise<Security2CCMessageEncapsulation> {\n const securityManager = assertSecurityRX(ctx);\n validatePayload(raw.payload.length >= 2);\n // Check the sequence number to avoid duplicates\n const sequenceNumber: number | undefined = raw.payload[0];\n // Ensure the node has a security class\n validatePayload.withReason(\"No security class granted\")(ctx.getHighestSecurityClass(ctx.sourceNodeId) !== SecurityClass.None);\n const hasExtensions = !!(raw.payload[1] & 0b1);\n const hasEncryptedExtensions = !!(raw.payload[1] & 0b10);\n let offset = 2;\n const extensions: Security2Extension[] = [];\n let mustDiscardCommand = false;\n if (hasExtensions) {\n const parseResult = parseExtensions(raw.payload.subarray(offset), false);\n extensions.push(...parseResult.extensions);\n offset += parseResult.bytesRead;\n mustDiscardCommand = parseResult.mustDiscardCommand;\n }\n const mcctx = ((): MulticastContext => {\n const multicastGroupId = getMulticastGroupId(extensions);\n if (ctx.frameType === \"multicast\" || ctx.frameType === \"broadcast\") {\n if (multicastGroupId == undefined) {\n validatePayload.fail(\"Multicast frames without MGRP extension\");\n }\n return {\n isMulticast: true,\n groupId: multicastGroupId,\n };\n }\n else {\n return { isMulticast: false, groupId: multicastGroupId };\n }\n })();\n // If a command is to be discarded before decryption,\n // we still need to increment the SPAN or MPAN state\n if (mustDiscardCommand) {\n if (mcctx.isMulticast) {\n await securityManager.nextPeerMPAN(ctx.sourceNodeId, mcctx.groupId);\n }\n else {\n await securityManager.nextNonce(ctx.sourceNodeId);\n }\n validatePayload.fail(\"Invalid S2 extension\");\n }\n let prevSequenceNumber: number | undefined;\n let mpanState: ReturnType<SecurityManager2[\"getPeerMPAN\"]> | undefined;\n if (mcctx.isMulticast) {\n mpanState = securityManager.getPeerMPAN(ctx.sourceNodeId, mcctx.groupId);\n }\n else {\n // Don't accept duplicate Singlecast commands\n prevSequenceNumber = validateSequenceNumber(securityManager, ctx.sourceNodeId, sequenceNumber);\n // When a node receives a singlecast message after a multicast group was marked out of sync,\n // it must forget about the group.\n if (mcctx.groupId == undefined) {\n securityManager.resetOutOfSyncMPANs(ctx.sourceNodeId);\n }\n }\n const unencryptedPayload = raw.payload.subarray(0, offset);\n const ciphertext = raw.payload.subarray(offset, -SECURITY_S2_AUTH_TAG_LENGTH);\n const authTag = raw.payload.subarray(-SECURITY_S2_AUTH_TAG_LENGTH);\n const messageLength = 2 /* CommandClass.computeEncapsulationOverhead() */\n + raw.payload.length;\n const authData = getAuthenticationData(ctx.sourceNodeId, getDestinationIDRX(ctx, extensions), ctx.homeId, messageLength, unencryptedPayload);\n let decrypt: () => Promise<DecryptionResult>;\n if (mcctx.isMulticast) {\n // For incoming multicast commands, make sure we have an MPAN\n if (mpanState?.type !== MPANState.MPAN) {\n // If we don't, mark the MPAN as out of sync, so we can respond accordingly on the singlecast followup\n securityManager.storePeerMPAN(ctx.sourceNodeId, mcctx.groupId, { type: MPANState.OutOfSync });\n failNoMPAN();\n }\n decrypt = () => decryptMulticast(ctx.sourceNodeId, securityManager, mcctx.groupId, ciphertext, authData, authTag);\n }\n else {\n // Decrypt payload and verify integrity\n const spanState = securityManager.getSPANState(ctx.sourceNodeId);\n // If we are not able to establish an SPAN yet, fail the decryption\n if (spanState.type === SPANState.None) {\n failNoSPAN();\n }\n else if (spanState.type === SPANState.RemoteEI) {\n // TODO: The specs are not clear how to handle this case\n // For now, do the same as if we didn't have any EI\n failNoSPAN();\n }\n decrypt = () => decryptSinglecast(ctx, securityManager, ctx.sourceNodeId, sequenceNumber, prevSequenceNumber!, ciphertext, authData, authTag, spanState, extensions);\n }\n let plaintext: BytesView | undefined;\n let authOK = false;\n let key: BytesView | undefined;\n let iv: BytesView | undefined;\n let decryptionSecurityClass: SecurityClass | undefined;\n // If the Receiver is unable to authenticate the singlecast message with the current SPAN,\n // the Receiver SHOULD try decrypting the message with one or more of the following SPAN values,\n // stopping when decryption is successful or the maximum number of iterations is reached.\n // If the Receiver is unable to decrypt the S2 MC frame with the current MPAN, the Receiver MAY try\n // decrypting the frame with one or more of the subsequent MPAN values, stopping when decryption is\n // successful or the maximum number of iterations is reached.\n const decryptAttempts = mcctx.isMulticast\n ? MAX_DECRYPT_ATTEMPTS_MULTICAST\n : mcctx.groupId != undefined\n ? MAX_DECRYPT_ATTEMPTS_SC_FOLLOWUP\n : MAX_DECRYPT_ATTEMPTS_SINGLECAST;\n for (let i = 0; i < decryptAttempts; i++) {\n ({\n plaintext,\n authOK,\n key,\n iv,\n securityClass: decryptionSecurityClass,\n } = await decrypt());\n if (authOK && !!plaintext)\n break;\n // No need to try further SPANs if we just got the sender's EI\n if (!!getSenderEI(extensions))\n break;\n }\n // If authentication fails, do so with an error code that instructs the\n // applHost to tell the node we have no nonce\n if (!authOK || !plaintext) {\n if (mcctx.isMulticast) {\n // Mark the MPAN as out of sync\n securityManager.storePeerMPAN(ctx.sourceNodeId, mcctx.groupId, { type: MPANState.OutOfSync });\n validatePayload.fail(ZWaveErrorCodes.Security2CC_CannotDecodeMulticast);\n }\n else {\n validatePayload.fail(ZWaveErrorCodes.Security2CC_CannotDecode);\n }\n }\n else if (!mcctx.isMulticast && mcctx.groupId != undefined) {\n // After reception of a singlecast followup, the MPAN state must be increased\n securityManager.tryIncrementPeerMPAN(ctx.sourceNodeId, mcctx.groupId);\n }\n // Remember which security class was used to decrypt this message, so we can discard it later\n const securityClass: SecurityClass | undefined = decryptionSecurityClass;\n offset = 0;\n if (hasEncryptedExtensions) {\n const parseResult = parseExtensions(plaintext, true);\n extensions.push(...parseResult.extensions);\n offset += parseResult.bytesRead;\n mustDiscardCommand = parseResult.mustDiscardCommand;\n }\n // Before we can continue, check if the command must be discarded\n if (mustDiscardCommand) {\n validatePayload.fail(\"Invalid extension\");\n }\n // The MPAN and MGRP extensions must not be sent together\n const mpanExtension = extensions.find((e) => e instanceof MPANExtension);\n if (mcctx.groupId != undefined && mpanExtension) {\n validatePayload.fail(\"Invalid combination of extensions\");\n }\n // If the MPAN extension was received, store the MPAN\n if (!mcctx.isMulticast) {\n const mpanExtension = extensions.find((e) => e instanceof MPANExtension);\n if (mpanExtension) {\n securityManager.storePeerMPAN(ctx.sourceNodeId, mpanExtension.groupId, {\n type: MPANState.MPAN,\n currentMPAN: mpanExtension.innerMPANState,\n });\n }\n }\n // Not every S2 message includes an encapsulated CC\n const decryptedCCBytes = plaintext.subarray(offset);\n let encapsulated: CommandClass | undefined;\n if (decryptedCCBytes.length > 0) {\n // make sure this contains a complete CC command that's worth splitting\n validatePayload(decryptedCCBytes.length >= 2);\n // and deserialize the CC\n encapsulated = await CommandClass.parse(decryptedCCBytes, ctx);\n }\n const ret = new Security2CCMessageEncapsulation({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n securityClass,\n extensions,\n encapsulated,\n });\n // Remember for debugging purposes\n ret.key = key;\n ret.iv = iv;\n ret.authData = authData;\n ret.authTag = authTag;\n ret.plaintext = decryptedCCBytes;\n return ret;\n }\n public readonly securityClass?: SecurityClass;\n // Only used for testing/debugging purposes\n private key?: BytesView;\n private iv?: BytesView;\n private authData?: BytesView;\n private authTag?: BytesView;\n private ciphertext?: BytesView;\n private plaintext?: BytesView;\n public readonly verifyDelivery: boolean = true;\n public sequenceNumber: number | undefined;\n private ensureSequenceNumber(securityManager: SecurityManager2): asserts this is this & {\n sequenceNumber: number;\n } {\n if (this.sequenceNumber == undefined) {\n if (this.isSinglecast()) {\n this.sequenceNumber = securityManager.nextSequenceNumber(this.nodeId);\n }\n else {\n const groupId = getDestinationIDTX.call(this);\n this.sequenceNumber = securityManager\n .nextMulticastSequenceNumber(groupId);\n }\n }\n }\n public encapsulated?: CommandClass;\n public extensions: Security2Extension[];\n public override prepareRetransmission(): void {\n super.prepareRetransmission();\n this.sequenceNumber = undefined;\n }\n public hasMOSExtension(): boolean {\n return this.extensions.some((e) => e instanceof MOSExtension);\n }\n /** Returns the Sender's Entropy Input if this command contains an SPAN extension */\n public getSenderEI(): BytesView | undefined {\n return getSenderEI(this.extensions);\n }\n /** Returns the multicast group ID if this command contains an MGRP extension */\n public getMulticastGroupId(): number | undefined {\n return getMulticastGroupId(this.extensions);\n }\n private async maybeAddSPANExtension(ctx: CCEncodingContext, securityManager: SecurityManager2): Promise<void> {\n if (!this.isSinglecast())\n return;\n const receiverNodeId: number = this.nodeId;\n const spanState = securityManager.getSPANState(receiverNodeId);\n if (spanState.type === SPANState.None\n || spanState.type === SPANState.LocalEI) {\n // Can't do anything here if we don't have the receiver's EI\n throw new ZWaveError(`Security S2 CC requires the receiver's nonce to be sent!`, ZWaveErrorCodes.Security2CC_NoSPAN);\n }\n else if (spanState.type === SPANState.RemoteEI) {\n // We have the receiver's EI, generate our input and send it over\n // With both, we can create an SPAN\n const senderEI = await securityManager.generateNonce(undefined);\n const receiverEI = spanState.receiverEI;\n // While bootstrapping a node, prefer the temporary key, unless the\n // specific command specifies a security class\n if (this.securityClass == undefined\n && securityManager.tempKeys.has(receiverNodeId)) {\n await securityManager.initializeTempSPAN(receiverNodeId, senderEI, receiverEI);\n }\n else {\n const securityClass = this.securityClass\n ?? ctx.getHighestSecurityClass(receiverNodeId);\n if (securityClass == undefined) {\n throw new ZWaveError(\"No security class defined for this command!\", ZWaveErrorCodes.Security2CC_NoSPAN);\n }\n await securityManager.initializeSPAN(receiverNodeId, securityClass, senderEI, receiverEI);\n }\n // Add or update the SPAN extension\n let spanExtension = this.extensions.find((e) => e instanceof SPANExtension);\n if (spanExtension) {\n spanExtension.senderEI = senderEI;\n }\n else {\n spanExtension = new SPANExtension({ senderEI });\n this.extensions.push(spanExtension);\n }\n }\n }\n public async serialize(ctx: CCEncodingContext): Promise<Bytes> {\n const securityManager = assertSecurityTX(ctx, this.nodeId);\n this.ensureSequenceNumber(securityManager);\n // Include Sender EI in the command if we only have the receiver's EI\n await this.maybeAddSPANExtension(ctx, securityManager);\n const unencryptedExtensions = this.extensions.filter((e) => !e.isEncrypted());\n const encryptedExtensions = this.extensions.filter((e) => e.isEncrypted());\n const unencryptedPayload = Bytes.concat([\n [\n this.sequenceNumber,\n (encryptedExtensions.length > 0 ? 0b10 : 0)\n | (unencryptedExtensions.length > 0 ? 1 : 0),\n ],\n ...unencryptedExtensions.map((e, index) => e.serialize(index < unencryptedExtensions.length - 1)),\n ]);\n const serializedCC = (await this.encapsulated?.serialize(ctx))\n ?? new Bytes();\n const plaintextPayload = Bytes.concat([\n ...encryptedExtensions.map((e, index) => e.serialize(index < encryptedExtensions.length - 1)),\n serializedCC,\n ]);\n // Generate the authentication data for CCM encryption\n const destinationTag = getDestinationIDTX.call(this as Security2CCMessageEncapsulation);\n const messageLength = this.computeEncapsulationOverhead()\n + serializedCC.length;\n const authData = getAuthenticationData(ctx.ownNodeId, destinationTag, ctx.homeId, messageLength, unencryptedPayload);\n let key: BytesView;\n let iv: BytesView;\n if (this.isSinglecast()) {\n // Singlecast:\n // Generate a nonce for encryption, and remember it to attempt decryption\n // of potential in-flight messages from the target node.\n iv = await securityManager.nextNonce(this.nodeId, true);\n const { keyCCM } = \n // Prefer the overridden security class if it was given\n this.securityClass != undefined\n ? securityManager.getKeysForSecurityClass(this.securityClass)\n : securityManager.getKeysForNode(this.nodeId);\n key = keyCCM;\n }\n else {\n // Multicast:\n const keyAndIV = await securityManager.getMulticastKeyAndIV(destinationTag);\n key = keyAndIV.key;\n iv = keyAndIV.iv;\n }\n const { ciphertext: ciphertextPayload, authTag } = await encryptAES128CCM(plaintextPayload, key, iv, authData, SECURITY_S2_AUTH_TAG_LENGTH);\n // Remember key and IV for debugging purposes\n this.key = key;\n this.iv = iv;\n this.authData = authData;\n this.authTag = authTag;\n this.ciphertext = ciphertextPayload;\n this.payload = Bytes.concat([\n unencryptedPayload,\n ciphertextPayload,\n authTag,\n ]);\n return super.serialize(ctx);\n }\n protected computeEncapsulationOverhead(): number {\n // Security S2 adds:\n // * 1 byte sequence number\n // * 1 byte control\n // * N bytes extensions\n // * SECURITY_S2_AUTH_TAG_LENGTH bytes auth tag\n const extensionBytes = this.extensions\n .map((e) => e.computeLength())\n .reduce((a, b) => a + b, 0);\n return (super.computeEncapsulationOverhead()\n + 2\n + SECURITY_S2_AUTH_TAG_LENGTH\n + extensionBytes);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n const message: MessageRecord = {\n \"sequence number\": this.sequenceNumber ?? \"(not set)\",\n };\n // Log the used keys in integration tests\n if (process.env.NODE_ENV === \"test\"\n || process.env.NODE_ENV === \"development\") {\n if (this.key) {\n message.key = buffer2hex(this.key);\n }\n if (this.iv) {\n message.IV = buffer2hex(this.iv);\n }\n if (this.ciphertext) {\n message.ciphertext = buffer2hex(this.ciphertext);\n }\n else if (this.plaintext) {\n message.plaintext = buffer2hex(this.plaintext);\n }\n if (this.authData) {\n message[\"auth data\"] = buffer2hex(this.authData);\n }\n if (this.authTag) {\n message[\"auth tag\"] = buffer2hex(this.authTag);\n }\n }\n if (this.securityClass != undefined) {\n message[\"security class\"] = getEnumMemberName(SecurityClass, this.securityClass);\n }\n return {\n ...super.toLogEntry(ctx),\n message: logDict(message, this.extensions.map((e) => e.toLogEntry())),\n };\n }\n}\n// @publicAPI\nexport type Security2CCNonceReportOptions = {\n sequenceNumber?: number;\n} & ({\n MOS: boolean;\n SOS: true;\n receiverEI: BytesView;\n} | {\n MOS: true;\n SOS: false;\n receiverEI?: undefined;\n});\n@CCCommand(Security2Command.NonceReport)\nexport class Security2CCNonceReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCNonceReportOptions>) {\n super(options);\n this.SOS = options.SOS;\n this.MOS = options.MOS;\n this.sequenceNumber = options.sequenceNumber;\n if (options.SOS)\n this.receiverEI = options.receiverEI;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNonceReport {\n // Make sure that we can send/receive secure commands\n const securityManager = assertSecurityRX(ctx);\n validatePayload(raw.payload.length >= 2);\n const sequenceNumber = raw.payload[0];\n // Don't accept duplicate commands\n validateSequenceNumber(securityManager, ctx.sourceNodeId, sequenceNumber);\n const MOS = !!(raw.payload[1] & 0b10);\n const SOS = !!(raw.payload[1] & 0b1);\n if (SOS) {\n // If the SOS flag is set, the REI field MUST be included in the command\n validatePayload(raw.payload.length >= 18);\n const receiverEI = raw.payload.subarray(2, 18);\n // In that case we also need to store it, so the next sent command\n // can use it for encryption\n securityManager.storeRemoteEI(ctx.sourceNodeId, receiverEI);\n return new this({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n MOS,\n SOS,\n receiverEI,\n });\n }\n else if (MOS) {\n return new this({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n MOS,\n SOS: false,\n });\n }\n else {\n validatePayload.fail(\"Either MOS or SOS must be set\");\n }\n }\n public sequenceNumber: number | undefined;\n private ensureSequenceNumber(securityManager: SecurityManager2): asserts this is this & {\n sequenceNumber: number;\n } {\n if (this.sequenceNumber == undefined) {\n this.sequenceNumber = securityManager.nextSequenceNumber(this.nodeId as number);\n }\n }\n public readonly SOS: boolean;\n public readonly MOS: boolean;\n public readonly receiverEI?: BytesView;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n const securityManager = assertSecurityTX(ctx, this.nodeId);\n this.ensureSequenceNumber(securityManager);\n this.payload = Bytes.from([\n this.sequenceNumber,\n (this.MOS ? 0b10 : 0) + (this.SOS ? 0b1 : 0),\n ]);\n if (this.SOS) {\n this.payload = Bytes.concat([this.payload, this.receiverEI!]);\n }\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n const message: MessageRecord = {\n \"sequence number\": this.sequenceNumber ?? \"(not set)\",\n SOS: this.SOS,\n MOS: this.MOS,\n };\n if (this.receiverEI) {\n message[\"receiver entropy\"] = buffer2hex(this.receiverEI);\n }\n return {\n ...super.toLogEntry(ctx),\n message,\n };\n }\n}\n// @publicAPI\nexport interface Security2CCNonceGetOptions {\n sequenceNumber?: number;\n}\n@CCCommand(Security2Command.NonceGet)\n@expectedCCResponse(Security2CCNonceReport)\nexport class Security2CCNonceGet extends Security2CC {\n // TODO: A node sending this command MUST accept a delay up to <Previous Round-trip-time to peer node> +\n // 250 ms before receiving the Security 2 Nonce Report Command.\n public constructor(options: WithAddress<Security2CCNonceGetOptions>) {\n super(options);\n this.sequenceNumber = options.sequenceNumber;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNonceGet {\n const securityManager = assertSecurityRX(ctx);\n validatePayload(raw.payload.length >= 1);\n const sequenceNumber = raw.payload[0];\n // Don't accept duplicate commands\n validateSequenceNumber(securityManager, ctx.sourceNodeId, sequenceNumber);\n return new this({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n });\n }\n public sequenceNumber: number | undefined;\n private ensureSequenceNumber(securityManager: SecurityManager2): asserts this is this & {\n sequenceNumber: number;\n } {\n if (this.sequenceNumber == undefined) {\n this.sequenceNumber = securityManager.nextSequenceNumber(this.nodeId as number);\n }\n }\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n const securityManager = assertSecurityTX(ctx, this.nodeId);\n this.ensureSequenceNumber(securityManager);\n this.payload = Bytes.from([this.sequenceNumber]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"sequence number\": this.sequenceNumber ?? \"(not set)\",\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCKEXReportOptions {\n requestCSA: boolean;\n echo: boolean;\n _reserved?: number;\n supportedKEXSchemes: KEXSchemes[];\n supportedECDHProfiles: ECDHProfiles[];\n requestedKeys: SecurityClass[];\n}\n@CCCommand(Security2Command.KEXReport)\nexport class Security2CCKEXReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCKEXReportOptions>) {\n super(options);\n this.requestCSA = options.requestCSA;\n this.echo = options.echo;\n this._reserved = options._reserved ?? 0;\n this.supportedKEXSchemes = options.supportedKEXSchemes;\n this.supportedECDHProfiles = options.supportedECDHProfiles;\n this.requestedKeys = options.requestedKeys;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCKEXReport {\n validatePayload(raw.payload.length >= 4);\n const requestCSA = !!(raw.payload[0] & 0b10);\n const echo = !!(raw.payload[0] & 0b1);\n // Remember the reserved bits for the echo\n const _reserved = raw.payload[0] & 252;\n // The bit mask starts at 0, but bit 0 is not used\n const supportedKEXSchemes: KEXSchemes[] = parseBitMask(raw.payload.subarray(1, 2), 0).filter((s) => s !== 0);\n const supportedECDHProfiles: ECDHProfiles[] = parseBitMask(raw.payload.subarray(2, 3), ECDHProfiles.Curve25519);\n const requestedKeys: SecurityClass[] = parseBitMask(raw.payload.subarray(3, 4), SecurityClass.S2_Unauthenticated);\n return new this({\n nodeId: ctx.sourceNodeId,\n requestCSA,\n echo,\n _reserved,\n supportedKEXSchemes,\n supportedECDHProfiles,\n requestedKeys,\n });\n }\n public readonly _reserved: number;\n public readonly requestCSA: boolean;\n public readonly echo: boolean;\n public readonly supportedKEXSchemes: readonly KEXSchemes[];\n public readonly supportedECDHProfiles: readonly ECDHProfiles[];\n public readonly requestedKeys: readonly SecurityClass[];\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n [\n this._reserved\n + (this.requestCSA ? 0b10 : 0)\n + (this.echo ? 0b1 : 0),\n ],\n // The bit mask starts at 0, but bit 0 is not used\n encodeBitMask(this.supportedKEXSchemes, 7, 0),\n encodeBitMask(this.supportedECDHProfiles, 7, ECDHProfiles.Curve25519),\n encodeBitMask(this.requestedKeys, SecurityClass.S0_Legacy, SecurityClass.S2_Unauthenticated),\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n echo: this.echo,\n \"supported schemes\": logList(this.supportedKEXSchemes.map((s) => getEnumMemberName(KEXSchemes, s))),\n \"supported ECDH profiles\": logList(this.supportedECDHProfiles.map((s) => getEnumMemberName(ECDHProfiles, s))),\n \"CSA requested\": this.requestCSA,\n \"requested security classes\": logList(this.requestedKeys.map((s) => getEnumMemberName(SecurityClass, s))),\n },\n };\n }\n}\n@CCCommand(Security2Command.KEXGet)\n@expectedCCResponse(Security2CCKEXReport)\nexport class Security2CCKEXGet extends Security2CC {\n}\n// @publicAPI\nexport interface Security2CCKEXSetOptions {\n permitCSA: boolean;\n echo: boolean;\n _reserved?: number;\n selectedKEXScheme: KEXSchemes;\n selectedECDHProfile: ECDHProfiles;\n grantedKeys: SecurityClass[];\n}\nfunction getExpectedResponseForKEXSet(ctx: GetNode<NodeId & SupportsCC>, sent: Security2CCKEXSet) {\n if (sent.echo) {\n return [Security2CCKEXReport, Security2CCKEXFail];\n }\n else {\n return undefined;\n }\n}\nfunction testExpectedResponseForKEXSet(sent: Security2CCKEXSet, received: any): CCResponseRole {\n if (sent.echo) {\n if (received instanceof Security2CCKEXReport) {\n return received.echo;\n }\n else if (received instanceof Security2CCKEXFail) {\n return true;\n }\n }\n return false;\n}\n@CCCommand(Security2Command.KEXSet)\n@expectedCCResponse(getExpectedResponseForKEXSet, testExpectedResponseForKEXSet)\nexport class Security2CCKEXSet extends Security2CC {\n public constructor(options: WithAddress<Security2CCKEXSetOptions>) {\n super(options);\n this.permitCSA = options.permitCSA;\n this.echo = options.echo;\n this._reserved = options._reserved ?? 0;\n this.selectedKEXScheme = options.selectedKEXScheme;\n this.selectedECDHProfile = options.selectedECDHProfile;\n this.grantedKeys = options.grantedKeys;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCKEXSet {\n validatePayload(raw.payload.length >= 4);\n const _reserved = raw.payload[0] & 252;\n const permitCSA = !!(raw.payload[0] & 0b10);\n const echo = !!(raw.payload[0] & 0b1);\n // The bit mask starts at 0, but bit 0 is not used\n const selectedKEXSchemes = parseBitMask(raw.payload.subarray(1, 2), 0).filter((s) => s !== 0);\n validatePayload(selectedKEXSchemes.length === 1);\n const selectedKEXScheme: KEXSchemes = selectedKEXSchemes[0];\n const selectedECDHProfiles = parseBitMask(raw.payload.subarray(2, 3), ECDHProfiles.Curve25519);\n validatePayload(selectedECDHProfiles.length === 1);\n const selectedECDHProfile: ECDHProfiles = selectedECDHProfiles[0];\n const grantedKeys: SecurityClass[] = parseBitMask(raw.payload.subarray(3, 4), SecurityClass.S2_Unauthenticated);\n return new this({\n nodeId: ctx.sourceNodeId,\n _reserved,\n permitCSA,\n echo,\n selectedKEXScheme,\n selectedECDHProfile,\n grantedKeys,\n });\n }\n public readonly _reserved: number;\n public permitCSA: boolean;\n public echo: boolean;\n public selectedKEXScheme: KEXSchemes;\n public selectedECDHProfile: ECDHProfiles;\n public grantedKeys: SecurityClass[];\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n [\n this._reserved\n + (this.permitCSA ? 0b10 : 0)\n + (this.echo ? 0b1 : 0),\n ],\n // The bit mask starts at 0, but bit 0 is not used\n encodeBitMask([this.selectedKEXScheme], 7, 0),\n encodeBitMask([this.selectedECDHProfile], 7, ECDHProfiles.Curve25519),\n encodeBitMask(this.grantedKeys, SecurityClass.S0_Legacy, SecurityClass.S2_Unauthenticated),\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n echo: this.echo,\n \"selected scheme\": getEnumMemberName(KEXSchemes, this.selectedKEXScheme),\n \"selected ECDH profile\": getEnumMemberName(ECDHProfiles, this.selectedECDHProfile),\n \"CSA permitted\": this.permitCSA,\n \"granted security classes\": logList(this.grantedKeys.map((s) => getEnumMemberName(SecurityClass, s))),\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCKEXFailOptions {\n failType: KEXFailType;\n}\n@CCCommand(Security2Command.KEXFail)\nexport class Security2CCKEXFail extends Security2CC {\n public constructor(options: WithAddress<Security2CCKEXFailOptions>) {\n super(options);\n this.failType = options.failType;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCKEXFail {\n validatePayload(raw.payload.length >= 1);\n const failType: KEXFailType = raw.payload[0];\n return new this({\n nodeId: ctx.sourceNodeId,\n failType,\n });\n }\n public failType: KEXFailType;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.from([this.failType]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: { reason: getEnumMemberName(KEXFailType, this.failType) },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCPublicKeyReportOptions {\n includingNode: boolean;\n publicKey: BytesView;\n}\n@CCCommand(Security2Command.PublicKeyReport)\nexport class Security2CCPublicKeyReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCPublicKeyReportOptions>) {\n super(options);\n this.includingNode = options.includingNode;\n this.publicKey = options.publicKey;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCPublicKeyReport {\n validatePayload(raw.payload.length >= 17);\n const includingNode = !!(raw.payload[0] & 0b1);\n const publicKey: BytesView = raw.payload.subarray(1);\n return new this({\n nodeId: ctx.sourceNodeId,\n includingNode,\n publicKey,\n });\n }\n public includingNode: boolean;\n public publicKey: BytesView;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n [this.includingNode ? 1 : 0],\n this.publicKey,\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"is including node\": this.includingNode,\n \"public key\": buffer2hex(this.publicKey),\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCNetworkKeyReportOptions {\n grantedKey: SecurityClass;\n networkKey: BytesView;\n}\n@CCCommand(Security2Command.NetworkKeyReport)\nexport class Security2CCNetworkKeyReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCNetworkKeyReportOptions>) {\n super(options);\n this.grantedKey = options.grantedKey;\n this.networkKey = options.networkKey;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNetworkKeyReport {\n validatePayload(raw.payload.length >= 17);\n const grantedKey: SecurityClass = bitMaskToSecurityClass(raw.payload, 0);\n const networkKey = raw.payload.subarray(1, 17);\n return new this({\n nodeId: ctx.sourceNodeId,\n grantedKey,\n networkKey,\n });\n }\n public grantedKey: SecurityClass;\n public networkKey: BytesView;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n securityClassToBitMask(this.grantedKey),\n this.networkKey,\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"security class\": getEnumMemberName(SecurityClass, this.grantedKey),\n // This shouldn't be logged, so users can safely post their logs online\n // \"network key\": buffer2hex(this.networkKey),\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCNetworkKeyGetOptions {\n requestedKey: SecurityClass;\n}\n@CCCommand(Security2Command.NetworkKeyGet)\n// Don't expect a response - we need to distinguish between Report and Fail\n// FIXME: maybe use the dynamic @expectedCCResponse instead?\nexport class Security2CCNetworkKeyGet extends Security2CC {\n public constructor(options: WithAddress<Security2CCNetworkKeyGetOptions>) {\n super(options);\n this.requestedKey = options.requestedKey;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNetworkKeyGet {\n validatePayload(raw.payload.length >= 1);\n const requestedKey: SecurityClass = bitMaskToSecurityClass(raw.payload, 0);\n return new this({\n nodeId: ctx.sourceNodeId,\n requestedKey,\n });\n }\n public requestedKey: SecurityClass;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = securityClassToBitMask(this.requestedKey);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"security class\": getEnumMemberName(SecurityClass, this.requestedKey),\n },\n };\n }\n}\n@CCCommand(Security2Command.NetworkKeyVerify)\nexport class Security2CCNetworkKeyVerify extends Security2CC {\n}\n// @publicAPI\nexport interface Security2CCTransferEndOptions {\n keyVerified: boolean;\n keyRequestComplete: boolean;\n}\n@CCCommand(Security2Command.TransferEnd)\nexport class Security2CCTransferEnd extends Security2CC {\n public constructor(options: WithAddress<Security2CCTransferEndOptions>) {\n super(options);\n this.keyVerified = options.keyVerified;\n this.keyRequestComplete = options.keyRequestComplete;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCTransferEnd {\n validatePayload(raw.payload.length >= 1);\n const keyVerified = !!(raw.payload[0] & 0b10);\n const keyRequestComplete = !!(raw.payload[0] & 0b1);\n return new this({\n nodeId: ctx.sourceNodeId,\n keyVerified,\n keyRequestComplete,\n });\n }\n public keyVerified: boolean;\n public keyRequestComplete: boolean;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.from([\n (this.keyVerified ? 0b10 : 0) + (this.keyRequestComplete ? 0b1 : 0),\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"key verified\": this.keyVerified,\n \"request complete\": this.keyRequestComplete,\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCCommandsSupportedReportOptions {\n supportedCCs: CommandClasses[];\n}\n@CCCommand(Security2Command.CommandsSupportedReport)\nexport class Security2CCCommandsSupportedReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCCommandsSupportedReportOptions>) {\n super(options);\n this.supportedCCs = options.supportedCCs;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCCommandsSupportedReport {\n const CCs = parseCCList(raw.payload);\n // SDS13783: A sending node MAY terminate the list of supported command classes with the\n // COMMAND_CLASS_MARK command class identifier.\n // A receiving node MUST stop parsing the list of supported command classes if it detects the\n // COMMAND_CLASS_MARK command class identifier in the Security 2 Commands Supported Report\n const supportedCCs = CCs.supportedCCs;\n return new this({\n nodeId: ctx.sourceNodeId,\n supportedCCs,\n });\n }\n public readonly supportedCCs: CommandClasses[];\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = encodeCCList(this.supportedCCs, []);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"supported CCs\": logList(this.supportedCCs.map((cc) => getCCName(cc))),\n },\n };\n }\n}\n@CCCommand(Security2Command.CommandsSupportedGet)\n@expectedCCResponse(Security2CCCommandsSupportedReport)\nexport class Security2CCCommandsSupportedGet extends Security2CC {\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kBAAwsB;AACxsB,oBAA4E;AAC5E,mBAAqB;AACrB,wBAAwB;AACxB,iBAAsB;AACtB,0BAAsF;AACtF,oCAAsF;AACtF,uBAA+I;AAC/I,IAAAA,iBAAuD;AACvD,mBAAiC;AAEjC,qBAAwB;AACxB,4BAA+B;AAC/B,wBAA2B;AAC3B,gCAAmC;AACnC,SAAS,uBAAuB,KAAkB;AAC9C,aAAO,2BAAc,CAAC,GAAG,GAAG,0BAAc,WAAW,0BAAc,kBAAkB;AACzF;AAFS;AAGT,SAAS,uBAAuB,QAAmB,QAAc;AAC7D,QAAM,WAAO,0BAAa,OAAO,SAAS,QAAQ,SAAS,CAAC,GAAG,0BAAc,kBAAkB;AAC/F,mCAAgB,KAAK,WAAW,CAAC;AACjC,SAAO,KAAK,CAAC;AACjB;AAJS;AAKT,MAAM,8BAA8B;AACpC,SAAS,sBAAsB,eAAuB,aAAqB,QAAgB,eAAuB,oBAA6B;AAC3I,QAAM,iBAAa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zB,aAAO,IAAI,KAAK;QACZ,QAAQ,IAAI;QACZ;OACH;IACL;IACgB;IACT,UAAU,KAAsB;AACnC,WAAK,cAAU,0BAAa,KAAK,cAAc,CAAA,CAAE;AACjD,aAAO,MAAM,UAAU,GAAG;IAC9B;IACO,WAAW,KAAgB;AAC9B,aAAO;QACH,GAAG,MAAM,WAAW,GAAG;QACvB,SAAS;UACL,qBAAiB,qBAAQ,KAAK,aAAa,IAAI,CAAC,WAAO,uBAAU,EAAE,CAAC,CAAC;;;IAGjF;;;;IAIS,mCAA+B,MAAA;8BAF3C,yCAAU,8BAAiB,oBAAoB,OAC/C,kDAAmB,kCAAkC,CAAC;;;;oBACF;uDAAA,YAAW;WAAA;;;;;;;;AAAhE,qCAAA,MAAA,mBAAA,EAAA,OAAA,WAAA,GAAA,kBAAA,EAAA,MAAA,SAAA,MAAA,WAAA,MAAA,UAAA,UAAA,GAAA,MAAA,uBAAA;;;AAAa,0CAAA,YAAA,uBAAA;;;;;",
4
+ "sourcesContent": ["import { CommandClasses, EncapsulationFlags, type GetNode, type GetValueDB, MPANState, type MaybeNotKnown, type MessageOrCCLogEntry, MessagePriority, type MessageRecord, type MulticastDestination, NODE_ID_BROADCAST, NODE_ID_BROADCAST_LR, type NodeId, type S2SecurityClass, SPANState, type SPANTableEntry, SecurityClass, type SecurityManager2, type SecurityManagers, type SupportsCC, TransmitOptions, type WithAddress, ZWaveError, ZWaveErrorCodes, decryptAES128CCM, encodeBitMask, encodeCCList, encryptAES128CCM, getCCName, highResTimestamp, isLongRangeNodeId, isTransmissionError, isZWaveError, logDict, logList, logText, parseBitMask, parseCCList, securityClassIsS2, securityClassOrder, validatePayload, } from \"@zwave-js/core\";\nimport { Bytes, type BytesView, buffer2hex, getEnumMemberName, getenv, pick, } from \"@zwave-js/shared\";\nimport { wait } from \"alcalzone-shared/async\";\nimport { isArray } from \"alcalzone-shared/typeguards\";\nimport { CCAPI } from \"../lib/API.js\";\nimport { type CCRaw, type CCResponseRole, CommandClass, type InterviewContext, } from \"../lib/CommandClass.js\";\nimport { API, CCCommand, commandClass, expectedCCResponse, implementedVersion, } from \"../lib/CommandClassDecorators.js\";\nimport { MGRPExtension, MOSExtension, MPANExtension, SPANExtension, Security2Extension, ValidateS2ExtensionResult, validateS2Extension, } from \"../lib/Security2/Extension.js\";\nimport { ECDHProfiles, KEXFailType, KEXSchemes, } from \"../lib/Security2/shared.js\";\nimport { Security2Command } from \"../lib/_Types.js\";\nimport type { CCEncodingContext, CCParsingContext } from \"../lib/traits.js\";\nimport { CRC16CC } from \"./CRC16CC.js\";\nimport { MultiChannelCC } from \"./MultiChannelCC.js\";\nimport { SecurityCC } from \"./SecurityCC.js\";\nimport { TransportServiceCC } from \"./TransportServiceCC.js\";\nfunction securityClassToBitMask(key: SecurityClass): Bytes {\n return encodeBitMask([key], SecurityClass.S0_Legacy, SecurityClass.S2_Unauthenticated);\n}\nfunction bitMaskToSecurityClass(buffer: BytesView, offset: number): SecurityClass {\n const keys = parseBitMask(buffer.subarray(offset, offset + 1), SecurityClass.S2_Unauthenticated);\n validatePayload(keys.length === 1);\n return keys[0];\n}\nconst SECURITY_S2_AUTH_TAG_LENGTH = 8;\nfunction getAuthenticationData(sendingNodeId: number, destination: number, homeId: number, commandLength: number, unencryptedPayload: BytesView): BytesView {\n const nodeIdSize = isLongRangeNodeId(sendingNodeId) || isLongRangeNodeId(destination)\n ? 2\n : 1;\n const ret = new Bytes(2 * nodeIdSize + 6 + unencryptedPayload.length);\n let offset = 0;\n ret.writeUIntBE(sendingNodeId, offset, nodeIdSize);\n offset += nodeIdSize;\n ret.writeUIntBE(destination, offset, nodeIdSize);\n offset += nodeIdSize;\n ret.writeUInt32BE(homeId, offset);\n offset += 4;\n ret.writeUInt16BE(commandLength, offset);\n offset += 2;\n // This includes the sequence number and all unencrypted extensions\n ret.set(unencryptedPayload, offset);\n return ret;\n}\nfunction getSecurityManager(ownNodeId: number, securityManagers: SecurityManagers, otherNodeId: MulticastDestination | number): SecurityManager2 | undefined {\n const longRange = isLongRangeNodeId(ownNodeId)\n || isLongRangeNodeId(isArray(otherNodeId) ? otherNodeId[0] : otherNodeId);\n return longRange\n ? securityManagers.securityManagerLR\n : securityManagers.securityManager2;\n}\n/** Validates that a sequence number is not a duplicate and updates the SPAN table if it is accepted. Returns the previous sequence number if there is one. */\nfunction validateSequenceNumber(securityManager: SecurityManager2, sourceNodeId: number, sequenceNumber: number): number | undefined {\n validatePayload.withReason(`Duplicate command (sequence number ${sequenceNumber})`)(!securityManager.isDuplicateSinglecast(sourceNodeId, sequenceNumber));\n // Not a duplicate, store it\n return securityManager.storeSequenceNumber(sourceNodeId, sequenceNumber);\n}\nconst MAX_DECRYPT_ATTEMPTS_SINGLECAST = 5;\nconst MAX_DECRYPT_ATTEMPTS_MULTICAST = 5;\nconst MAX_DECRYPT_ATTEMPTS_SC_FOLLOWUP = 1;\n// @publicAPI\nexport interface DecryptionResult {\n plaintext: BytesView;\n authOK: boolean;\n key?: BytesView;\n iv?: BytesView;\n securityClass: SecurityClass | undefined;\n}\nfunction assertSecurityRX(ctx: CCParsingContext): SecurityManager2 {\n if (!ctx.ownNodeId) {\n throw new ZWaveError(`Secure commands (S2) can only be decoded when the controller's node id is known!`, ZWaveErrorCodes.Driver_NotReady);\n }\n const ret = getSecurityManager(ctx.ownNodeId, ctx, ctx.sourceNodeId);\n if (!ret) {\n throw new ZWaveError(`Secure commands (S2) can only be decoded when the security manager is set up!`, ZWaveErrorCodes.Driver_NoSecurity);\n }\n return ret;\n}\nfunction assertSecurityTX(ctx: CCEncodingContext, destination: MulticastDestination | number): SecurityManager2 {\n if (!ctx.ownNodeId) {\n throw new ZWaveError(`Secure commands (S2) can only be sent when the controller's node id is known!`, ZWaveErrorCodes.Driver_NotReady);\n }\n const ret = getSecurityManager(ctx.ownNodeId, ctx, destination);\n if (!ret) {\n throw new ZWaveError(`Secure commands (S2) can only be sent when the security manager is set up!`, ZWaveErrorCodes.Driver_NoSecurity);\n }\n return ret;\n}\nasync function decryptSinglecast(ctx: CCParsingContext, securityManager: SecurityManager2, sendingNodeId: number, curSequenceNumber: number, prevSequenceNumber: number, ciphertext: BytesView, authData: BytesView, authTag: BytesView, spanState: SPANTableEntry & {\n type: SPANState.SPAN | SPANState.LocalEI;\n}, extensions: Security2Extension[]): Promise<DecryptionResult> {\n const decryptWithNonce = async (nonce: BytesView) => {\n const { keyCCM: key } = securityManager.getKeysForNode(sendingNodeId);\n const iv = nonce;\n const ret = await decryptAES128CCM(ciphertext, key, iv, authData, authTag);\n return {\n key,\n iv,\n ...ret,\n };\n };\n const getNonceAndDecrypt = async () => {\n const iv = await securityManager.nextNonce(sendingNodeId);\n return decryptWithNonce(iv);\n };\n if (spanState.type === SPANState.SPAN) {\n // There SHOULD be a shared SPAN between both parties. But experience has shown that both could have\n // sent a command at roughly the same time, using the same SPAN for encryption.\n // To avoid a nasty desync and both nodes trying to resync at the same time, causing message loss,\n // we accept commands encrypted with the previous SPAN under very specific circumstances:\n if (\n // The previous SPAN is still known, i.e. the node didn't send another command that was successfully decrypted\n !!spanState.currentSPAN\n // it is still valid\n && spanState.currentSPAN.expires > highResTimestamp()\n // The received command is exactly the next, expected one\n && prevSequenceNumber != undefined\n && curSequenceNumber === ((prevSequenceNumber + 1) & 0xff)\n // And in case of a mock-based test, do this only on the controller\n && !ctx.__internalIsMockNode) {\n const nonce = spanState.currentSPAN.nonce;\n spanState.currentSPAN = undefined;\n // If we could decrypt this way, we're done...\n const result = await decryptWithNonce(nonce);\n if (result.authOK) {\n return {\n ...result,\n securityClass: spanState.securityClass,\n };\n }\n // ...otherwise, we need to try the normal way\n }\n else {\n // forgetting the current SPAN shouldn't be necessary but better be safe than sorry\n spanState.currentSPAN = undefined;\n }\n // This can only happen if the security class is known\n return {\n ...(await getNonceAndDecrypt()),\n securityClass: spanState.securityClass,\n };\n }\n else if (spanState.type === SPANState.LocalEI) {\n // We've sent the other our receiver's EI and received its sender's EI,\n // meaning we can now establish an SPAN\n const senderEI = getSenderEI(extensions);\n if (!senderEI)\n failNoSPAN();\n const receiverEI = spanState.receiverEI;\n // How we do this depends on whether we know the security class of the other node\n const isBootstrappingNode = securityManager.tempKeys.has(sendingNodeId);\n if (isBootstrappingNode) {\n // We're currently bootstrapping the node, it might be using a temporary key\n await securityManager.initializeTempSPAN(sendingNodeId, senderEI, receiverEI);\n const ret = await getNonceAndDecrypt();\n // Decryption with the temporary key worked\n if (ret.authOK) {\n return {\n ...ret,\n securityClass: SecurityClass.Temporary,\n };\n }\n // Reset the SPAN state and try with the recently granted security class\n securityManager.setSPANState(sendingNodeId, spanState);\n }\n // When ending up here, one of two situations has occured:\n // a) We've taken over an existing network and do not know the node's security class\n // b) We know the security class, but we're about to establish a new SPAN. This may happen at a lower\n // security class than the one the node normally uses, e.g. when we're being queried for securely\n // supported CCs.\n // In both cases, we should simply try decoding with multiple security classes, starting from the highest one.\n // If this fails, we restore the previous (partial) SPAN state.\n // Try all security classes where we do not definitely know that it was not granted\n // While bootstrapping a node, we consider the key that is being exchanged (including S0) to be the highest. No need to look at others\n const possibleSecurityClasses = isBootstrappingNode\n ? [ctx.getHighestSecurityClass(sendingNodeId)!]\n : securityClassOrder.filter((s) => ctx.hasSecurityClass(sendingNodeId, s)\n !== false);\n for (const secClass of possibleSecurityClasses) {\n // Skip security classes we don't have keys for\n if (!securityManager.hasKeysForSecurityClass(secClass)) {\n continue;\n }\n // Initialize an SPAN with that security class\n await securityManager.initializeSPAN(sendingNodeId, secClass, senderEI, receiverEI);\n const ret = await getNonceAndDecrypt();\n // It worked, return the result\n if (ret.authOK) {\n // Also if we weren't sure before, we now know that the security class is granted\n if (ctx.hasSecurityClass(sendingNodeId, secClass)\n === undefined) {\n ctx.setSecurityClass(sendingNodeId, secClass, true);\n }\n return {\n ...ret,\n securityClass: secClass,\n };\n }\n else {\n // Reset the SPAN state and try with the next security class\n securityManager.setSPANState(sendingNodeId, spanState);\n }\n }\n }\n // Nothing worked, fail the decryption\n return {\n plaintext: new Uint8Array(),\n authOK: false,\n securityClass: undefined,\n };\n}\nasync function decryptMulticast(sendingNodeId: number, securityManager: SecurityManager2, groupId: number, ciphertext: BytesView, authData: BytesView, authTag: BytesView): Promise<DecryptionResult> {\n const iv = await securityManager.nextPeerMPAN(sendingNodeId, groupId);\n const { keyCCM: key } = securityManager.getKeysForNode(sendingNodeId);\n return {\n key,\n iv,\n ...(await decryptAES128CCM(ciphertext, key, iv, authData, authTag)),\n // The security class is irrelevant when decrypting multicast commands\n securityClass: undefined,\n };\n}\nfunction parseExtensions(buffer: BytesView, wasEncrypted: boolean): {\n extensions: Security2Extension[];\n mustDiscardCommand: boolean;\n bytesRead: number;\n} {\n const extensions: Security2Extension[] = [];\n let mustDiscardCommand = false;\n let offset = 0;\n parsing: while (true) {\n if (buffer.length < offset + 2) {\n // An S2 extension was expected, but the buffer is too short\n mustDiscardCommand = true;\n break parsing;\n }\n // The length field could be too large, which would cause part of the actual ciphertext\n // to be ignored. Try to avoid this for known extensions by checking the actual and expected length.\n const { actual: actualLength, expected: expectedLength } = Security2Extension\n .getExtensionLength(buffer.subarray(offset));\n // Parse the extension using the expected length if possible\n const extensionLength = expectedLength ?? actualLength;\n if (extensionLength < 2) {\n // An S2 extension was expected, but the length is too short\n mustDiscardCommand = true;\n break parsing;\n }\n else if (extensionLength\n > buffer.length\n - offset\n - (wasEncrypted\n ? 0\n : SECURITY_S2_AUTH_TAG_LENGTH)) {\n // The supposed length is longer than the space the extensions may occupy\n mustDiscardCommand = true;\n break parsing;\n }\n const extensionData = buffer.subarray(offset, offset + extensionLength);\n offset += extensionLength;\n const ext = Security2Extension.parse(extensionData);\n switch (validateS2Extension(ext, wasEncrypted)) {\n case ValidateS2ExtensionResult.OK:\n if (expectedLength != undefined\n && actualLength !== expectedLength) {\n // The extension length field does not match, ignore the extension\n }\n else {\n extensions.push(ext);\n }\n break;\n case ValidateS2ExtensionResult.DiscardExtension:\n // Do nothing\n break;\n case ValidateS2ExtensionResult.DiscardCommand:\n mustDiscardCommand = true;\n break;\n }\n // Check if that was the last extension\n if (!ext.moreToFollow)\n break parsing;\n }\n return {\n extensions,\n mustDiscardCommand,\n bytesRead: offset,\n };\n}\nfunction getDestinationIDTX(this: Security2CC & {\n extensions: Security2Extension[];\n}): number {\n if (this.isSinglecast())\n return this.nodeId;\n const ret = getMulticastGroupId(this.extensions);\n if (ret == undefined) {\n throw new ZWaveError(\"Multicast Security S2 encapsulation requires the MGRP extension\", ZWaveErrorCodes.Security2CC_MissingExtension);\n }\n return ret;\n}\nfunction getDestinationIDRX(ctx: CCParsingContext, extensions: Security2Extension[]): number {\n if (ctx.frameType === \"singlecast\") {\n return ctx.ownNodeId;\n }\n const ret = getMulticastGroupId(extensions);\n if (ret == undefined) {\n throw new ZWaveError(\"Multicast Security S2 encapsulation requires the MGRP extension\", ZWaveErrorCodes.Security2CC_MissingExtension);\n }\n return ret;\n}\nfunction getMulticastGroupId(extensions: Security2Extension[]): number | undefined {\n const mgrpExtension = extensions.find((e) => e instanceof MGRPExtension);\n return mgrpExtension?.groupId;\n}\n/** Returns the Sender's Entropy Input if this command contains an SPAN extension */\nfunction getSenderEI(extensions: Security2Extension[]): BytesView | undefined {\n const spanExtension = extensions.find((e) => e instanceof SPANExtension);\n return spanExtension?.senderEI;\n}\n// Encapsulation CCs are used internally and too frequently that we\n// want to pay the cost of validating each call\n/* eslint-disable @zwave-js/ccapi-validate-args */\n@API(CommandClasses[\"Security 2\"])\nexport class Security2CCAPI extends CCAPI {\n public supportsCommand(_cmd: Security2Command): MaybeNotKnown<boolean> {\n // All commands are mandatory\n return true;\n }\n /**\n * Sends a nonce to the node, either in response to a NonceGet request or a message that failed to decrypt. The message is sent without any retransmission etc.\n * The return value indicates whether a nonce was successfully sent\n */\n public async sendNonce(): Promise<boolean> {\n this.assertSupportsCommand(Security2Command, Security2Command.NonceReport);\n this.assertPhysicalEndpoint(this.endpoint);\n const securityManager = getSecurityManager(this.host.ownNodeId, this.host, this.endpoint.nodeId);\n if (!securityManager) {\n throw new ZWaveError(`Nonces can only be sent if secure communication is set up!`, ZWaveErrorCodes.Driver_NoSecurity);\n }\n const receiverEI = await securityManager.generateNonce(this.endpoint.nodeId);\n const cc = new Security2CCNonceReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n SOS: true,\n MOS: false,\n receiverEI,\n });\n try {\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Seems we need these options or some nodes won't accept the nonce\n transmitOptions: TransmitOptions.ACK\n | TransmitOptions.AutoRoute,\n // Only try sending a nonce once\n maxSendAttempts: 1,\n // Nonce requests must be handled immediately\n priority: MessagePriority.Immediate,\n // We don't want failures causing us to treat the node as asleep or dead\n changeNodeStatusOnMissingACK: false,\n // And we need to react to\n });\n }\n catch (e) {\n if (isTransmissionError(e)) {\n // The nonce could not be sent, invalidate it\n securityManager.deleteNonce(this.endpoint.nodeId);\n return false;\n }\n else {\n // Pass other errors through\n throw e;\n }\n }\n return true;\n }\n /** Notifies the target node that the MPAN state is out of sync */\n public async sendMOS(): Promise<boolean> {\n this.assertSupportsCommand(Security2Command, Security2Command.NonceReport);\n this.assertPhysicalEndpoint(this.endpoint);\n const cc = new Security2CCNonceReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n SOS: false,\n MOS: true,\n });\n try {\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Seems we need these options or some nodes won't accept the nonce\n transmitOptions: TransmitOptions.ACK\n | TransmitOptions.AutoRoute,\n // Only try sending a nonce once\n maxSendAttempts: 1,\n // Nonce requests must be handled immediately\n priority: MessagePriority.Immediate,\n // We don't want failures causing us to treat the node as asleep or dead\n changeNodeStatusOnMissingACK: false,\n });\n }\n catch (e) {\n if (isTransmissionError(e)) {\n return false;\n }\n else {\n // Pass other errors through\n throw e;\n }\n }\n return true;\n }\n /** Sends the given MPAN to the node */\n public async sendMPAN(groupId: number, innerMPANState: BytesView): Promise<boolean> {\n this.assertSupportsCommand(Security2Command, Security2Command.MessageEncapsulation);\n this.assertPhysicalEndpoint(this.endpoint);\n const cc = new Security2CCMessageEncapsulation({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n extensions: [\n new MPANExtension({\n groupId,\n innerMPANState,\n }),\n ],\n });\n try {\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Seems we need these options or some nodes won't accept the nonce\n transmitOptions: TransmitOptions.ACK\n | TransmitOptions.AutoRoute,\n // Only try sending a nonce once\n maxSendAttempts: 1,\n // Nonce requests must be handled immediately\n priority: MessagePriority.Immediate,\n // We don't want failures causing us to treat the node as asleep or dead\n changeNodeStatusOnMissingACK: false,\n });\n }\n catch (e) {\n if (isTransmissionError(e)) {\n return false;\n }\n else {\n // Pass other errors through\n throw e;\n }\n }\n return true;\n }\n /**\n * Queries the securely supported commands for the current security class\n * @param securityClass Can be used to overwrite the security class to use. If this doesn't match the current one, new nonces will need to be exchanged.\n */\n public async getSupportedCommands(securityClass: SecurityClass.S2_AccessControl | SecurityClass.S2_Authenticated | SecurityClass.S2_Unauthenticated): Promise<MaybeNotKnown<CommandClasses[]>> {\n this.assertSupportsCommand(Security2Command, Security2Command.CommandsSupportedGet);\n let cc: CommandClass = new Security2CCCommandsSupportedGet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n });\n // Security2CCCommandsSupportedGet is special because we cannot reply on the applHost to do the automatic\n // encapsulation because it would use a different security class. Therefore the entire possible stack\n // of encapsulation needs to be done here\n if (MultiChannelCC.requiresEncapsulation(cc)) {\n const multiChannelCCVersion = this.host.getSupportedCCVersion(CommandClasses[\"Multi Channel\"], this.endpoint.nodeId as number);\n cc = multiChannelCCVersion === 1\n ? MultiChannelCC.encapsulateV1(cc)\n : MultiChannelCC.encapsulate(cc);\n }\n cc = Security2CC.encapsulate(cc, this.host.ownNodeId, this.host, { securityClass });\n const response = await this.host.sendCommand<Security2CCCommandsSupportedReport>(cc, {\n ...this.commandOptions,\n autoEncapsulate: false,\n });\n return response?.supportedCCs;\n }\n public async reportSupportedCommands(supportedCCs: CommandClasses[]): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.CommandsSupportedReport);\n const cc = new Security2CCCommandsSupportedReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n supportedCCs,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n // oxlint-disable-next-line typescript/explicit-module-boundary-types\n public async getKeyExchangeParameters() {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXGet);\n const cc = new Security2CCKEXGet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n });\n const response = await this.host.sendCommand<Security2CCKEXReport>(cc, this.commandOptions);\n if (response) {\n return pick(response, [\n \"requestCSA\",\n \"echo\",\n \"supportedKEXSchemes\",\n \"supportedECDHProfiles\",\n \"requestedKeys\",\n \"_reserved\",\n ]);\n }\n }\n /** Requests the given keys from an including node */\n public async requestKeys(params: Omit<Security2CCKEXReportOptions, \"echo\">): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXReport);\n const cc = new Security2CCKEXReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: false,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n /** Grants the joining node the given keys */\n public async grantKeys(params: Omit<Security2CCKEXSetOptions, \"echo\">): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXSet);\n const cc = new Security2CCKEXSet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: false,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n /** Confirms the keys that were requested by a node */\n public async confirmRequestedKeys(params: Omit<Security2CCKEXReportOptions, \"echo\">): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXReport);\n const cc = new Security2CCKEXReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: true,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n /** Confirms the keys that were granted by the including node */\n public async confirmGrantedKeys(params: Omit<Security2CCKEXSetOptions, \"echo\">): Promise<Security2CCKEXReport | Security2CCKEXFail | undefined> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXSet);\n const cc = new Security2CCKEXSet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n ...params,\n echo: true,\n });\n return this.host.sendCommand(cc, this.commandOptions);\n }\n /** Notifies the other node that the ongoing key exchange was aborted */\n public async abortKeyExchange(failType: KEXFailType): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.KEXFail);\n const cc = new Security2CCKEXFail({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n failType,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async sendPublicKey(publicKey: BytesView, includingNode: boolean = true): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.PublicKeyReport);\n const cc = new Security2CCPublicKeyReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n includingNode,\n publicKey,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async requestNetworkKey(securityClass: SecurityClass): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.NetworkKeyGet);\n const cc = new Security2CCNetworkKeyGet({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n requestedKey: securityClass,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async sendNetworkKey(securityClass: SecurityClass, networkKey: BytesView): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.NetworkKeyReport);\n const cc = new Security2CCNetworkKeyReport({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n grantedKey: securityClass,\n networkKey,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async verifyNetworkKey(): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.NetworkKeyVerify);\n const cc = new Security2CCNetworkKeyVerify({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n public async confirmKeyVerification(): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.TransferEnd);\n const cc = new Security2CCTransferEnd({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n keyVerified: true,\n keyRequestComplete: false,\n });\n await this.host.sendCommand(cc, {\n ...this.commandOptions,\n // Don't wait for an ACK from the node\n transmitOptions: TransmitOptions.DEFAULT & ~TransmitOptions.ACK,\n });\n }\n public async endKeyExchange(): Promise<void> {\n this.assertSupportsCommand(Security2Command, Security2Command.TransferEnd);\n const cc = new Security2CCTransferEnd({\n nodeId: this.endpoint.nodeId,\n endpointIndex: this.endpoint.index,\n keyVerified: false,\n keyRequestComplete: true,\n });\n await this.host.sendCommand(cc, this.commandOptions);\n }\n}\n@commandClass(CommandClasses[\"Security 2\"])\n@implementedVersion(1)\nexport class Security2CC extends CommandClass {\n declare ccCommand: Security2Command;\n public async interview(ctx: InterviewContext): Promise<void> {\n const securityManager = getSecurityManager(ctx.ownNodeId, ctx, this.nodeId);\n const node = this.getNode(ctx)!;\n const endpoint = this.getEndpoint(ctx)!;\n const api = CCAPI.create(CommandClasses[\"Security 2\"], ctx, endpoint).withOptions({\n priority: MessagePriority.NodeQuery,\n tag: \"interview\",\n });\n // Only on the highest security class the response includes the supported commands\n const secClass = node.getHighestSecurityClass();\n let hasReceivedSecureCommands = false;\n let possibleSecurityClasses: S2SecurityClass[];\n if (securityClassIsS2(secClass)) {\n // The highest security class is known to be S2, only query that one\n possibleSecurityClasses = [secClass];\n }\n else if (endpoint.index === 0) {\n // If the highest security class isn't known, query all possible security classes\n // but only on the root device\n possibleSecurityClasses = [\n SecurityClass.S2_Unauthenticated,\n SecurityClass.S2_Authenticated,\n SecurityClass.S2_AccessControl,\n ];\n }\n else {\n // For endpoint interviews, the security class MUST be known\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Cannot query securely supported commands for endpoint because the node's security class isn't known...`,\n level: \"error\",\n });\n return;\n }\n for (const secClass of possibleSecurityClasses) {\n // We might not know all assigned security classes yet, so we work our way up from low to high and try to request the supported commands.\n // This way, each command is encrypted with the security class we're currently testing.\n // If the node does not respond, it wasn't assigned the security class.\n // If it responds with a non-empty list, we know this is the highest class it supports.\n // If the list is empty, the security class is still supported.\n // If we already know the class is not supported, skip it\n if (node.hasSecurityClass(secClass) === false)\n continue;\n // If no key is configured for this security class, skip it\n if (!securityManager?.hasKeysForSecurityClass(secClass)) {\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Cannot query securely supported commands (${getEnumMemberName(SecurityClass, secClass)}) - network key is not configured...`,\n level: \"warn\",\n });\n continue;\n }\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)})...`,\n direction: \"outbound\",\n });\n // Query the supported commands but avoid remembering the wrong security class in case of a failure\n let supportedCCs: CommandClasses[] | undefined;\n // Try up to 3 times on the root device. We REALLY don't want a spurious timeout or collision to cause us to discard a known good security class\n const MAX_ATTEMPTS = this.endpointIndex === 0 ? 3 : 1;\n for (let attempts = 1; attempts <= MAX_ATTEMPTS; attempts++) {\n try {\n supportedCCs = await api.getSupportedCommands(secClass);\n }\n catch (e) {\n if (isZWaveError(e)\n && e.code === ZWaveErrorCodes.Security2CC_CannotDecode) {\n // Either we were using a non-granted security class,\n // or querying with the known highest security class had an issue\n supportedCCs = undefined;\n }\n else {\n throw e;\n }\n }\n if (supportedCCs == undefined\n && possibleSecurityClasses.length === 1) {\n if (attempts < MAX_ATTEMPTS) {\n // We definitely know the highest security class\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)}), attempt ${attempts}/${MAX_ATTEMPTS} failed. Retrying in 500ms...`,\n level: \"warn\",\n });\n await wait(500);\n continue;\n }\n else if (endpoint.index > 0) {\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)}) failed. Assuming the endpoint supports all its mandatory CCs securely...`,\n level: \"warn\",\n });\n // Just mark all endpoint CCs as secure. Without this we would attempt\n // unencrypted communication with the endpoint, which will likely fail.\n for (const [ccId] of endpoint.getCCs()) {\n endpoint.addCC(ccId, { secure: true });\n }\n break;\n }\n else {\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: `Querying securely supported commands (${getEnumMemberName(SecurityClass, secClass)}) failed. Let's hope for the best...`,\n level: \"warn\",\n });\n break;\n }\n }\n else {\n // In any other case, we can stop trying\n break;\n }\n }\n if (supportedCCs == undefined) {\n if (endpoint.index === 0\n && possibleSecurityClasses.length > 1) {\n // No supported commands found, mark the security class as not granted\n // unless we were sure about the security class\n node.setSecurityClass(secClass, false);\n ctx.logNode(node.id, {\n message: `The node was NOT granted the security class ${getEnumMemberName(SecurityClass, secClass)}`,\n direction: \"inbound\",\n });\n }\n continue;\n }\n if (endpoint.index === 0 && possibleSecurityClasses.length > 1) {\n // Mark the security class as granted unless we were sure about the security class\n node.setSecurityClass(secClass, true);\n ctx.logNode(node.id, {\n message: `The node was granted the security class ${getEnumMemberName(SecurityClass, secClass)}`,\n direction: \"inbound\",\n });\n }\n if (!hasReceivedSecureCommands && supportedCCs.length > 0) {\n hasReceivedSecureCommands = true;\n ctx.logNode(node.id, {\n endpoint: endpoint.index,\n message: logText([\n `received secure commands (${getEnumMemberName(SecurityClass, secClass)})`,\n \"supported CCs:\",\n ], {\n nested: logList(supportedCCs.map((cc) => getCCName(cc))),\n }),\n direction: \"inbound\",\n });\n // Remember which commands are supported securely\n for (const cc of supportedCCs) {\n // Basic CC has special rules for when it is considered supported\n // Therefore we mark all other CCs as supported, but not Basic CC,\n // for which support is determined later.\n if (cc === CommandClasses.Basic) {\n endpoint.addCC(cc, { secure: true });\n }\n else {\n endpoint.addCC(cc, {\n isSupported: true,\n secure: true,\n });\n }\n }\n }\n }\n // Remember that the interview is complete\n this.setInterviewComplete(ctx, true);\n }\n /** Tests if a command should be sent secure and thus requires encapsulation */\n public static requiresEncapsulation(cc: CommandClass): boolean {\n // No security flag -> no encapsulation\n if (!(cc.encapsulationFlags & EncapsulationFlags.Security)) {\n return false;\n }\n // S0, CRC16, Transport Service -> no S2 encapsulation\n if (cc instanceof SecurityCC\n || cc instanceof CRC16CC\n || cc instanceof TransportServiceCC) {\n return false;\n }\n // S2: check command\n if (cc instanceof Security2CC) {\n // These S2 commands need additional encapsulation\n switch (cc.ccCommand) {\n case Security2Command.CommandsSupportedGet:\n case Security2Command.CommandsSupportedReport:\n case Security2Command.NetworkKeyGet:\n case Security2Command.NetworkKeyReport:\n case Security2Command.NetworkKeyVerify:\n case Security2Command.TransferEnd:\n return true;\n case Security2Command.KEXSet:\n case Security2Command.KEXReport:\n // KEXSet/Report need to be encrypted for the confirmation only\n return (cc as Security2CCKEXSet | Security2CCKEXReport)\n .echo;\n case Security2Command.KEXFail: {\n switch ((cc as Security2CCKEXFail).failType) {\n case KEXFailType.Decrypt:\n case KEXFailType.WrongSecurityLevel:\n case KEXFailType.KeyNotGranted:\n case KEXFailType.NoVerify:\n return true;\n default:\n return false;\n }\n }\n }\n return false;\n }\n // Everything else needs to be encapsulated if the CC is secure\n return true;\n }\n /** Encapsulates a command that should be sent encrypted */\n public static encapsulate(cc: CommandClass, ownNodeId: number, securityManagers: SecurityManagers, options?: {\n securityClass?: SecurityClass;\n multicastOutOfSync?: boolean;\n multicastGroupId?: number;\n verifyDelivery?: boolean;\n }): Security2CCMessageEncapsulation {\n // Determine which extensions must be used on the command\n const extensions: Security2Extension[] = [];\n if (options?.multicastOutOfSync) {\n extensions.push(new MOSExtension());\n }\n if (options?.multicastGroupId != undefined) {\n extensions.push(new MGRPExtension({ groupId: options.multicastGroupId }));\n }\n // Make sure that S2 multicast uses broadcasts. While the specs mention that both multicast and broadcast\n // are possible, it has been found that devices treat multicasts like singlecast followups and respond incorrectly.\n let nodeId: number;\n if (cc.isMulticast()) {\n if (cc.nodeId.some((nodeId) => isLongRangeNodeId(nodeId))) {\n nodeId = NODE_ID_BROADCAST_LR;\n }\n else {\n nodeId = NODE_ID_BROADCAST;\n }\n }\n else {\n nodeId = cc.nodeId as number;\n }\n const ret = new Security2CCMessageEncapsulation({\n nodeId,\n encapsulated: cc,\n securityClass: options?.securityClass,\n extensions,\n verifyDelivery: options?.verifyDelivery,\n });\n // Copy the encapsulation flags from the encapsulated command\n // but omit Security, since we're doing that right now\n ret.encapsulationFlags = cc.encapsulationFlags\n & ~EncapsulationFlags.Security;\n return ret;\n }\n}\nfunction failNoSPAN(): never {\n validatePayload.fail(ZWaveErrorCodes.Security2CC_NoSPAN);\n}\nfunction failNoMPAN(): never {\n validatePayload.fail(ZWaveErrorCodes.Security2CC_NoMPAN);\n}\n// @publicAPI\nexport type MulticastContext = {\n isMulticast: true;\n groupId: number;\n} | {\n isMulticast: false;\n groupId?: number;\n};\n// @publicAPI\nexport interface Security2CCMessageEncapsulationOptions {\n sequenceNumber?: number;\n /** Can be used to override the default security class for the command */\n securityClass?: SecurityClass;\n extensions?: Security2Extension[];\n encapsulated?: CommandClass;\n verifyDelivery?: boolean;\n}\n// An S2 encapsulated command may result in a NonceReport to be sent by the node if it couldn't decrypt the message\nfunction getCCResponseForMessageEncapsulation(ctx: GetNode<NodeId & SupportsCC>, sent: Security2CCMessageEncapsulation) {\n if (sent.encapsulated?.expectsCCResponse(ctx)) {\n const ret = [\n Security2CCMessageEncapsulation as any,\n Security2CCNonceReport as any,\n ];\n if (sent.encapsulated instanceof Security2CCKEXSet\n || sent.encapsulated instanceof Security2CCKEXReport\n || sent.encapsulated instanceof Security2CCNetworkKeyGet\n || sent.encapsulated instanceof Security2CCNetworkKeyReport\n || sent.encapsulated instanceof Security2CCNetworkKeyVerify) {\n ret.push(Security2CCKEXFail as any);\n }\n return ret;\n }\n}\nfunction testCCResponseForMessageEncapsulation(sent: Security2CCMessageEncapsulation, received: Security2CCMessageEncapsulation | Security2CCNonceReport | Security2CCKEXFail) {\n if (received instanceof Security2CCMessageEncapsulation) {\n return \"checkEncapsulated\";\n }\n else if (received instanceof Security2CCKEXFail) {\n return true;\n }\n else {\n return received.SOS && !!received.receiverEI;\n }\n}\n@CCCommand(Security2Command.MessageEncapsulation)\n@expectedCCResponse(getCCResponseForMessageEncapsulation, testCCResponseForMessageEncapsulation)\nexport class Security2CCMessageEncapsulation extends Security2CC {\n public constructor(options: WithAddress<Security2CCMessageEncapsulationOptions>) {\n super(options);\n if (!options.encapsulated && !options.extensions?.length) {\n throw new ZWaveError(\"Security S2 encapsulation requires an encapsulated CC and/or extensions\", ZWaveErrorCodes.Argument_Invalid);\n }\n this.sequenceNumber = options.sequenceNumber;\n this.securityClass = options.securityClass;\n if (options.encapsulated) {\n this.encapsulated = options.encapsulated;\n options.encapsulated.encapsulatingCC = this as any;\n }\n this.verifyDelivery = options.verifyDelivery !== false;\n this.extensions = options.extensions ?? [];\n if (typeof this.nodeId !== \"number\"\n && !this.extensions.some((e) => e instanceof MGRPExtension)) {\n throw new ZWaveError(\"Multicast Security S2 encapsulation requires the MGRP extension\", ZWaveErrorCodes.Security2CC_MissingExtension);\n }\n }\n public static async from(raw: CCRaw, ctx: CCParsingContext): Promise<Security2CCMessageEncapsulation> {\n const securityManager = assertSecurityRX(ctx);\n validatePayload(raw.payload.length >= 2);\n // Check the sequence number to avoid duplicates\n const sequenceNumber: number | undefined = raw.payload[0];\n // Ensure the node has a security class\n validatePayload.withReason(\"No security class granted\")(ctx.getHighestSecurityClass(ctx.sourceNodeId) !== SecurityClass.None);\n const hasExtensions = !!(raw.payload[1] & 0b1);\n const hasEncryptedExtensions = !!(raw.payload[1] & 0b10);\n let offset = 2;\n const extensions: Security2Extension[] = [];\n let mustDiscardCommand = false;\n if (hasExtensions) {\n const parseResult = parseExtensions(raw.payload.subarray(offset), false);\n extensions.push(...parseResult.extensions);\n offset += parseResult.bytesRead;\n mustDiscardCommand = parseResult.mustDiscardCommand;\n }\n const mcctx = ((): MulticastContext => {\n const multicastGroupId = getMulticastGroupId(extensions);\n if (ctx.frameType === \"multicast\" || ctx.frameType === \"broadcast\") {\n if (multicastGroupId == undefined) {\n validatePayload.fail(\"Multicast frames without MGRP extension\");\n }\n return {\n isMulticast: true,\n groupId: multicastGroupId,\n };\n }\n else {\n return { isMulticast: false, groupId: multicastGroupId };\n }\n })();\n // If a command is to be discarded before decryption,\n // we still need to increment the SPAN or MPAN state\n if (mustDiscardCommand) {\n if (mcctx.isMulticast) {\n await securityManager.nextPeerMPAN(ctx.sourceNodeId, mcctx.groupId);\n }\n else {\n await securityManager.nextNonce(ctx.sourceNodeId);\n }\n validatePayload.fail(\"Invalid S2 extension\");\n }\n let prevSequenceNumber: number | undefined;\n let mpanState: ReturnType<SecurityManager2[\"getPeerMPAN\"]> | undefined;\n if (mcctx.isMulticast) {\n mpanState = securityManager.getPeerMPAN(ctx.sourceNodeId, mcctx.groupId);\n }\n else {\n // Don't accept duplicate Singlecast commands\n prevSequenceNumber = validateSequenceNumber(securityManager, ctx.sourceNodeId, sequenceNumber);\n // When a node receives a singlecast message after a multicast group was marked out of sync,\n // it must forget about the group.\n if (mcctx.groupId == undefined) {\n securityManager.resetOutOfSyncMPANs(ctx.sourceNodeId);\n }\n }\n const unencryptedPayload = raw.payload.subarray(0, offset);\n const ciphertext = raw.payload.subarray(offset, -SECURITY_S2_AUTH_TAG_LENGTH);\n const authTag = raw.payload.subarray(-SECURITY_S2_AUTH_TAG_LENGTH);\n const messageLength = 2 /* CommandClass.computeEncapsulationOverhead() */\n + raw.payload.length;\n const authData = getAuthenticationData(ctx.sourceNodeId, getDestinationIDRX(ctx, extensions), ctx.homeId, messageLength, unencryptedPayload);\n let decrypt: () => Promise<DecryptionResult>;\n if (mcctx.isMulticast) {\n // For incoming multicast commands, make sure we have an MPAN\n if (mpanState?.type !== MPANState.MPAN) {\n // If we don't, mark the MPAN as out of sync, so we can respond accordingly on the singlecast followup\n securityManager.storePeerMPAN(ctx.sourceNodeId, mcctx.groupId, { type: MPANState.OutOfSync });\n failNoMPAN();\n }\n decrypt = () => decryptMulticast(ctx.sourceNodeId, securityManager, mcctx.groupId, ciphertext, authData, authTag);\n }\n else {\n // Decrypt payload and verify integrity\n const spanState = securityManager.getSPANState(ctx.sourceNodeId);\n // If we are not able to establish an SPAN yet, fail the decryption\n if (spanState.type === SPANState.None) {\n failNoSPAN();\n }\n else if (spanState.type === SPANState.RemoteEI) {\n // TODO: The specs are not clear how to handle this case\n // For now, do the same as if we didn't have any EI\n failNoSPAN();\n }\n decrypt = () => decryptSinglecast(ctx, securityManager, ctx.sourceNodeId, sequenceNumber, prevSequenceNumber!, ciphertext, authData, authTag, spanState, extensions);\n }\n let plaintext: BytesView | undefined;\n let authOK = false;\n let key: BytesView | undefined;\n let iv: BytesView | undefined;\n let decryptionSecurityClass: SecurityClass | undefined;\n // If the Receiver is unable to authenticate the singlecast message with the current SPAN,\n // the Receiver SHOULD try decrypting the message with one or more of the following SPAN values,\n // stopping when decryption is successful or the maximum number of iterations is reached.\n // If the Receiver is unable to decrypt the S2 MC frame with the current MPAN, the Receiver MAY try\n // decrypting the frame with one or more of the subsequent MPAN values, stopping when decryption is\n // successful or the maximum number of iterations is reached.\n const decryptAttempts = mcctx.isMulticast\n ? MAX_DECRYPT_ATTEMPTS_MULTICAST\n : mcctx.groupId != undefined\n ? MAX_DECRYPT_ATTEMPTS_SC_FOLLOWUP\n : MAX_DECRYPT_ATTEMPTS_SINGLECAST;\n for (let i = 0; i < decryptAttempts; i++) {\n ({\n plaintext,\n authOK,\n key,\n iv,\n securityClass: decryptionSecurityClass,\n } = await decrypt());\n if (authOK && !!plaintext)\n break;\n // No need to try further SPANs if we just got the sender's EI\n if (!!getSenderEI(extensions))\n break;\n }\n // If authentication fails, do so with an error code that instructs the\n // applHost to tell the node we have no nonce\n if (!authOK || !plaintext) {\n if (mcctx.isMulticast) {\n // Mark the MPAN as out of sync\n securityManager.storePeerMPAN(ctx.sourceNodeId, mcctx.groupId, { type: MPANState.OutOfSync });\n validatePayload.fail(ZWaveErrorCodes.Security2CC_CannotDecodeMulticast);\n }\n else {\n validatePayload.fail(ZWaveErrorCodes.Security2CC_CannotDecode);\n }\n }\n else if (!mcctx.isMulticast && mcctx.groupId != undefined) {\n // After reception of a singlecast followup, the MPAN state must be increased\n securityManager.tryIncrementPeerMPAN(ctx.sourceNodeId, mcctx.groupId);\n }\n // Remember which security class was used to decrypt this message, so we can discard it later\n const securityClass: SecurityClass | undefined = decryptionSecurityClass;\n offset = 0;\n if (hasEncryptedExtensions) {\n const parseResult = parseExtensions(plaintext, true);\n extensions.push(...parseResult.extensions);\n offset += parseResult.bytesRead;\n mustDiscardCommand = parseResult.mustDiscardCommand;\n }\n // Before we can continue, check if the command must be discarded\n if (mustDiscardCommand) {\n validatePayload.fail(\"Invalid extension\");\n }\n // The MPAN and MGRP extensions must not be sent together\n const mpanExtension = extensions.find((e) => e instanceof MPANExtension);\n if (mcctx.groupId != undefined && mpanExtension) {\n validatePayload.fail(\"Invalid combination of extensions\");\n }\n // If the MPAN extension was received, store the MPAN\n if (!mcctx.isMulticast) {\n const mpanExtension = extensions.find((e) => e instanceof MPANExtension);\n if (mpanExtension) {\n securityManager.storePeerMPAN(ctx.sourceNodeId, mpanExtension.groupId, {\n type: MPANState.MPAN,\n currentMPAN: mpanExtension.innerMPANState,\n });\n }\n }\n // Not every S2 message includes an encapsulated CC\n const decryptedCCBytes = plaintext.subarray(offset);\n let encapsulated: CommandClass | undefined;\n if (decryptedCCBytes.length > 0) {\n // make sure this contains a complete CC command that's worth splitting\n validatePayload(decryptedCCBytes.length >= 2);\n // and deserialize the CC\n encapsulated = await CommandClass.parse(decryptedCCBytes, ctx);\n }\n const ret = new Security2CCMessageEncapsulation({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n securityClass,\n extensions,\n encapsulated,\n });\n // Remember for debugging purposes\n ret.key = key;\n ret.iv = iv;\n ret.authData = authData;\n ret.authTag = authTag;\n ret.plaintext = decryptedCCBytes;\n return ret;\n }\n public readonly securityClass?: SecurityClass;\n // Only used for testing/debugging purposes\n private key?: BytesView;\n private iv?: BytesView;\n private authData?: BytesView;\n private authTag?: BytesView;\n private ciphertext?: BytesView;\n private plaintext?: BytesView;\n public readonly verifyDelivery: boolean = true;\n public sequenceNumber: number | undefined;\n private ensureSequenceNumber(securityManager: SecurityManager2): asserts this is this & {\n sequenceNumber: number;\n } {\n if (this.sequenceNumber == undefined) {\n if (this.isSinglecast()) {\n this.sequenceNumber = securityManager.nextSequenceNumber(this.nodeId);\n }\n else {\n const groupId = getDestinationIDTX.call(this);\n this.sequenceNumber = securityManager\n .nextMulticastSequenceNumber(groupId);\n }\n }\n }\n public encapsulated?: CommandClass;\n public extensions: Security2Extension[];\n public override prepareRetransmission(): void {\n super.prepareRetransmission();\n this.sequenceNumber = undefined;\n }\n public hasMOSExtension(): boolean {\n return this.extensions.some((e) => e instanceof MOSExtension);\n }\n /** Returns the Sender's Entropy Input if this command contains an SPAN extension */\n public getSenderEI(): BytesView | undefined {\n return getSenderEI(this.extensions);\n }\n /** Returns the multicast group ID if this command contains an MGRP extension */\n public getMulticastGroupId(): number | undefined {\n return getMulticastGroupId(this.extensions);\n }\n private async maybeAddSPANExtension(ctx: CCEncodingContext, securityManager: SecurityManager2): Promise<void> {\n if (!this.isSinglecast())\n return;\n const receiverNodeId: number = this.nodeId;\n const spanState = securityManager.getSPANState(receiverNodeId);\n if (spanState.type === SPANState.None\n || spanState.type === SPANState.LocalEI) {\n // Can't do anything here if we don't have the receiver's EI\n throw new ZWaveError(`Security S2 CC requires the receiver's nonce to be sent!`, ZWaveErrorCodes.Security2CC_NoSPAN);\n }\n else if (spanState.type === SPANState.RemoteEI) {\n // We have the receiver's EI, generate our input and send it over\n // With both, we can create an SPAN\n const senderEI = await securityManager.generateNonce(undefined);\n const receiverEI = spanState.receiverEI;\n // While bootstrapping a node, prefer the temporary key, unless the\n // specific command specifies a security class\n if (this.securityClass == undefined\n && securityManager.tempKeys.has(receiverNodeId)) {\n await securityManager.initializeTempSPAN(receiverNodeId, senderEI, receiverEI);\n }\n else {\n const securityClass = this.securityClass\n ?? ctx.getHighestSecurityClass(receiverNodeId);\n if (securityClass == undefined) {\n throw new ZWaveError(\"No security class defined for this command!\", ZWaveErrorCodes.Security2CC_NoSPAN);\n }\n await securityManager.initializeSPAN(receiverNodeId, securityClass, senderEI, receiverEI);\n }\n // Add or update the SPAN extension\n let spanExtension = this.extensions.find((e) => e instanceof SPANExtension);\n if (spanExtension) {\n spanExtension.senderEI = senderEI;\n }\n else {\n spanExtension = new SPANExtension({ senderEI });\n this.extensions.push(spanExtension);\n }\n }\n }\n public async serialize(ctx: CCEncodingContext): Promise<Bytes> {\n const securityManager = assertSecurityTX(ctx, this.nodeId);\n this.ensureSequenceNumber(securityManager);\n // Include Sender EI in the command if we only have the receiver's EI\n await this.maybeAddSPANExtension(ctx, securityManager);\n const unencryptedExtensions = this.extensions.filter((e) => !e.isEncrypted());\n const encryptedExtensions = this.extensions.filter((e) => e.isEncrypted());\n const unencryptedPayload = Bytes.concat([\n [\n this.sequenceNumber,\n (encryptedExtensions.length > 0 ? 0b10 : 0)\n | (unencryptedExtensions.length > 0 ? 1 : 0),\n ],\n ...unencryptedExtensions.map((e, index) => e.serialize(index < unencryptedExtensions.length - 1)),\n ]);\n const serializedCC = (await this.encapsulated?.serialize(ctx))\n ?? new Bytes();\n const plaintextPayload = Bytes.concat([\n ...encryptedExtensions.map((e, index) => e.serialize(index < encryptedExtensions.length - 1)),\n serializedCC,\n ]);\n // Generate the authentication data for CCM encryption\n const destinationTag = getDestinationIDTX.call(this as Security2CCMessageEncapsulation);\n const messageLength = this.computeEncapsulationOverhead()\n + serializedCC.length;\n const authData = getAuthenticationData(ctx.ownNodeId, destinationTag, ctx.homeId, messageLength, unencryptedPayload);\n let key: BytesView;\n let iv: BytesView;\n if (this.isSinglecast()) {\n // Singlecast:\n // Generate a nonce for encryption, and remember it to attempt decryption\n // of potential in-flight messages from the target node.\n iv = await securityManager.nextNonce(this.nodeId, true);\n const { keyCCM } = \n // Prefer the overridden security class if it was given\n this.securityClass != undefined\n ? securityManager.getKeysForSecurityClass(this.securityClass)\n : securityManager.getKeysForNode(this.nodeId);\n key = keyCCM;\n }\n else {\n // Multicast:\n const keyAndIV = await securityManager.getMulticastKeyAndIV(destinationTag);\n key = keyAndIV.key;\n iv = keyAndIV.iv;\n }\n const { ciphertext: ciphertextPayload, authTag } = await encryptAES128CCM(plaintextPayload, key, iv, authData, SECURITY_S2_AUTH_TAG_LENGTH);\n // Remember key and IV for debugging purposes\n this.key = key;\n this.iv = iv;\n this.authData = authData;\n this.authTag = authTag;\n this.ciphertext = ciphertextPayload;\n this.payload = Bytes.concat([\n unencryptedPayload,\n ciphertextPayload,\n authTag,\n ]);\n return super.serialize(ctx);\n }\n protected computeEncapsulationOverhead(): number {\n // Security S2 adds:\n // * 1 byte sequence number\n // * 1 byte control\n // * N bytes extensions\n // * SECURITY_S2_AUTH_TAG_LENGTH bytes auth tag\n const extensionBytes = this.extensions\n .map((e) => e.computeLength())\n .reduce((a, b) => a + b, 0);\n return (super.computeEncapsulationOverhead()\n + 2\n + SECURITY_S2_AUTH_TAG_LENGTH\n + extensionBytes);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n const message: MessageRecord = {\n \"sequence number\": this.sequenceNumber ?? \"(not set)\",\n };\n // Log the used keys in integration tests\n if (getenv(\"NODE_ENV\") === \"test\"\n || getenv(\"NODE_ENV\") === \"development\") {\n if (this.key) {\n message.key = buffer2hex(this.key);\n }\n if (this.iv) {\n message.IV = buffer2hex(this.iv);\n }\n if (this.ciphertext) {\n message.ciphertext = buffer2hex(this.ciphertext);\n }\n else if (this.plaintext) {\n message.plaintext = buffer2hex(this.plaintext);\n }\n if (this.authData) {\n message[\"auth data\"] = buffer2hex(this.authData);\n }\n if (this.authTag) {\n message[\"auth tag\"] = buffer2hex(this.authTag);\n }\n }\n if (this.securityClass != undefined) {\n message[\"security class\"] = getEnumMemberName(SecurityClass, this.securityClass);\n }\n return {\n ...super.toLogEntry(ctx),\n message: logDict(message, this.extensions.map((e) => e.toLogEntry())),\n };\n }\n}\n// @publicAPI\nexport type Security2CCNonceReportOptions = {\n sequenceNumber?: number;\n} & ({\n MOS: boolean;\n SOS: true;\n receiverEI: BytesView;\n} | {\n MOS: true;\n SOS: false;\n receiverEI?: undefined;\n});\n@CCCommand(Security2Command.NonceReport)\nexport class Security2CCNonceReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCNonceReportOptions>) {\n super(options);\n this.SOS = options.SOS;\n this.MOS = options.MOS;\n this.sequenceNumber = options.sequenceNumber;\n if (options.SOS)\n this.receiverEI = options.receiverEI;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNonceReport {\n // Make sure that we can send/receive secure commands\n const securityManager = assertSecurityRX(ctx);\n validatePayload(raw.payload.length >= 2);\n const sequenceNumber = raw.payload[0];\n // Don't accept duplicate commands\n validateSequenceNumber(securityManager, ctx.sourceNodeId, sequenceNumber);\n const MOS = !!(raw.payload[1] & 0b10);\n const SOS = !!(raw.payload[1] & 0b1);\n if (SOS) {\n // If the SOS flag is set, the REI field MUST be included in the command\n validatePayload(raw.payload.length >= 18);\n const receiverEI = raw.payload.subarray(2, 18);\n // In that case we also need to store it, so the next sent command\n // can use it for encryption\n securityManager.storeRemoteEI(ctx.sourceNodeId, receiverEI);\n return new this({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n MOS,\n SOS,\n receiverEI,\n });\n }\n else if (MOS) {\n return new this({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n MOS,\n SOS: false,\n });\n }\n else {\n validatePayload.fail(\"Either MOS or SOS must be set\");\n }\n }\n public sequenceNumber: number | undefined;\n private ensureSequenceNumber(securityManager: SecurityManager2): asserts this is this & {\n sequenceNumber: number;\n } {\n if (this.sequenceNumber == undefined) {\n this.sequenceNumber = securityManager.nextSequenceNumber(this.nodeId as number);\n }\n }\n public readonly SOS: boolean;\n public readonly MOS: boolean;\n public readonly receiverEI?: BytesView;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n const securityManager = assertSecurityTX(ctx, this.nodeId);\n this.ensureSequenceNumber(securityManager);\n this.payload = Bytes.from([\n this.sequenceNumber,\n (this.MOS ? 0b10 : 0) + (this.SOS ? 0b1 : 0),\n ]);\n if (this.SOS) {\n this.payload = Bytes.concat([this.payload, this.receiverEI!]);\n }\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n const message: MessageRecord = {\n \"sequence number\": this.sequenceNumber ?? \"(not set)\",\n SOS: this.SOS,\n MOS: this.MOS,\n };\n if (this.receiverEI) {\n message[\"receiver entropy\"] = buffer2hex(this.receiverEI);\n }\n return {\n ...super.toLogEntry(ctx),\n message,\n };\n }\n}\n// @publicAPI\nexport interface Security2CCNonceGetOptions {\n sequenceNumber?: number;\n}\n@CCCommand(Security2Command.NonceGet)\n@expectedCCResponse(Security2CCNonceReport)\nexport class Security2CCNonceGet extends Security2CC {\n // TODO: A node sending this command MUST accept a delay up to <Previous Round-trip-time to peer node> +\n // 250 ms before receiving the Security 2 Nonce Report Command.\n public constructor(options: WithAddress<Security2CCNonceGetOptions>) {\n super(options);\n this.sequenceNumber = options.sequenceNumber;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNonceGet {\n const securityManager = assertSecurityRX(ctx);\n validatePayload(raw.payload.length >= 1);\n const sequenceNumber = raw.payload[0];\n // Don't accept duplicate commands\n validateSequenceNumber(securityManager, ctx.sourceNodeId, sequenceNumber);\n return new this({\n nodeId: ctx.sourceNodeId,\n sequenceNumber,\n });\n }\n public sequenceNumber: number | undefined;\n private ensureSequenceNumber(securityManager: SecurityManager2): asserts this is this & {\n sequenceNumber: number;\n } {\n if (this.sequenceNumber == undefined) {\n this.sequenceNumber = securityManager.nextSequenceNumber(this.nodeId as number);\n }\n }\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n const securityManager = assertSecurityTX(ctx, this.nodeId);\n this.ensureSequenceNumber(securityManager);\n this.payload = Bytes.from([this.sequenceNumber]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"sequence number\": this.sequenceNumber ?? \"(not set)\",\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCKEXReportOptions {\n requestCSA: boolean;\n echo: boolean;\n _reserved?: number;\n supportedKEXSchemes: KEXSchemes[];\n supportedECDHProfiles: ECDHProfiles[];\n requestedKeys: SecurityClass[];\n}\n@CCCommand(Security2Command.KEXReport)\nexport class Security2CCKEXReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCKEXReportOptions>) {\n super(options);\n this.requestCSA = options.requestCSA;\n this.echo = options.echo;\n this._reserved = options._reserved ?? 0;\n this.supportedKEXSchemes = options.supportedKEXSchemes;\n this.supportedECDHProfiles = options.supportedECDHProfiles;\n this.requestedKeys = options.requestedKeys;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCKEXReport {\n validatePayload(raw.payload.length >= 4);\n const requestCSA = !!(raw.payload[0] & 0b10);\n const echo = !!(raw.payload[0] & 0b1);\n // Remember the reserved bits for the echo\n const _reserved = raw.payload[0] & 252;\n // The bit mask starts at 0, but bit 0 is not used\n const supportedKEXSchemes: KEXSchemes[] = parseBitMask(raw.payload.subarray(1, 2), 0).filter((s) => s !== 0);\n const supportedECDHProfiles: ECDHProfiles[] = parseBitMask(raw.payload.subarray(2, 3), ECDHProfiles.Curve25519);\n const requestedKeys: SecurityClass[] = parseBitMask(raw.payload.subarray(3, 4), SecurityClass.S2_Unauthenticated);\n return new this({\n nodeId: ctx.sourceNodeId,\n requestCSA,\n echo,\n _reserved,\n supportedKEXSchemes,\n supportedECDHProfiles,\n requestedKeys,\n });\n }\n public readonly _reserved: number;\n public readonly requestCSA: boolean;\n public readonly echo: boolean;\n public readonly supportedKEXSchemes: readonly KEXSchemes[];\n public readonly supportedECDHProfiles: readonly ECDHProfiles[];\n public readonly requestedKeys: readonly SecurityClass[];\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n [\n this._reserved\n + (this.requestCSA ? 0b10 : 0)\n + (this.echo ? 0b1 : 0),\n ],\n // The bit mask starts at 0, but bit 0 is not used\n encodeBitMask(this.supportedKEXSchemes, 7, 0),\n encodeBitMask(this.supportedECDHProfiles, 7, ECDHProfiles.Curve25519),\n encodeBitMask(this.requestedKeys, SecurityClass.S0_Legacy, SecurityClass.S2_Unauthenticated),\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n echo: this.echo,\n \"supported schemes\": logList(this.supportedKEXSchemes.map((s) => getEnumMemberName(KEXSchemes, s))),\n \"supported ECDH profiles\": logList(this.supportedECDHProfiles.map((s) => getEnumMemberName(ECDHProfiles, s))),\n \"CSA requested\": this.requestCSA,\n \"requested security classes\": logList(this.requestedKeys.map((s) => getEnumMemberName(SecurityClass, s))),\n },\n };\n }\n}\n@CCCommand(Security2Command.KEXGet)\n@expectedCCResponse(Security2CCKEXReport)\nexport class Security2CCKEXGet extends Security2CC {\n}\n// @publicAPI\nexport interface Security2CCKEXSetOptions {\n permitCSA: boolean;\n echo: boolean;\n _reserved?: number;\n selectedKEXScheme: KEXSchemes;\n selectedECDHProfile: ECDHProfiles;\n grantedKeys: SecurityClass[];\n}\nfunction getExpectedResponseForKEXSet(ctx: GetNode<NodeId & SupportsCC>, sent: Security2CCKEXSet) {\n if (sent.echo) {\n return [Security2CCKEXReport, Security2CCKEXFail];\n }\n else {\n return undefined;\n }\n}\nfunction testExpectedResponseForKEXSet(sent: Security2CCKEXSet, received: any): CCResponseRole {\n if (sent.echo) {\n if (received instanceof Security2CCKEXReport) {\n return received.echo;\n }\n else if (received instanceof Security2CCKEXFail) {\n return true;\n }\n }\n return false;\n}\n@CCCommand(Security2Command.KEXSet)\n@expectedCCResponse(getExpectedResponseForKEXSet, testExpectedResponseForKEXSet)\nexport class Security2CCKEXSet extends Security2CC {\n public constructor(options: WithAddress<Security2CCKEXSetOptions>) {\n super(options);\n this.permitCSA = options.permitCSA;\n this.echo = options.echo;\n this._reserved = options._reserved ?? 0;\n this.selectedKEXScheme = options.selectedKEXScheme;\n this.selectedECDHProfile = options.selectedECDHProfile;\n this.grantedKeys = options.grantedKeys;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCKEXSet {\n validatePayload(raw.payload.length >= 4);\n const _reserved = raw.payload[0] & 252;\n const permitCSA = !!(raw.payload[0] & 0b10);\n const echo = !!(raw.payload[0] & 0b1);\n // The bit mask starts at 0, but bit 0 is not used\n const selectedKEXSchemes = parseBitMask(raw.payload.subarray(1, 2), 0).filter((s) => s !== 0);\n validatePayload(selectedKEXSchemes.length === 1);\n const selectedKEXScheme: KEXSchemes = selectedKEXSchemes[0];\n const selectedECDHProfiles = parseBitMask(raw.payload.subarray(2, 3), ECDHProfiles.Curve25519);\n validatePayload(selectedECDHProfiles.length === 1);\n const selectedECDHProfile: ECDHProfiles = selectedECDHProfiles[0];\n const grantedKeys: SecurityClass[] = parseBitMask(raw.payload.subarray(3, 4), SecurityClass.S2_Unauthenticated);\n return new this({\n nodeId: ctx.sourceNodeId,\n _reserved,\n permitCSA,\n echo,\n selectedKEXScheme,\n selectedECDHProfile,\n grantedKeys,\n });\n }\n public readonly _reserved: number;\n public permitCSA: boolean;\n public echo: boolean;\n public selectedKEXScheme: KEXSchemes;\n public selectedECDHProfile: ECDHProfiles;\n public grantedKeys: SecurityClass[];\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n [\n this._reserved\n + (this.permitCSA ? 0b10 : 0)\n + (this.echo ? 0b1 : 0),\n ],\n // The bit mask starts at 0, but bit 0 is not used\n encodeBitMask([this.selectedKEXScheme], 7, 0),\n encodeBitMask([this.selectedECDHProfile], 7, ECDHProfiles.Curve25519),\n encodeBitMask(this.grantedKeys, SecurityClass.S0_Legacy, SecurityClass.S2_Unauthenticated),\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n echo: this.echo,\n \"selected scheme\": getEnumMemberName(KEXSchemes, this.selectedKEXScheme),\n \"selected ECDH profile\": getEnumMemberName(ECDHProfiles, this.selectedECDHProfile),\n \"CSA permitted\": this.permitCSA,\n \"granted security classes\": logList(this.grantedKeys.map((s) => getEnumMemberName(SecurityClass, s))),\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCKEXFailOptions {\n failType: KEXFailType;\n}\n@CCCommand(Security2Command.KEXFail)\nexport class Security2CCKEXFail extends Security2CC {\n public constructor(options: WithAddress<Security2CCKEXFailOptions>) {\n super(options);\n this.failType = options.failType;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCKEXFail {\n validatePayload(raw.payload.length >= 1);\n const failType: KEXFailType = raw.payload[0];\n return new this({\n nodeId: ctx.sourceNodeId,\n failType,\n });\n }\n public failType: KEXFailType;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.from([this.failType]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: { reason: getEnumMemberName(KEXFailType, this.failType) },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCPublicKeyReportOptions {\n includingNode: boolean;\n publicKey: BytesView;\n}\n@CCCommand(Security2Command.PublicKeyReport)\nexport class Security2CCPublicKeyReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCPublicKeyReportOptions>) {\n super(options);\n this.includingNode = options.includingNode;\n this.publicKey = options.publicKey;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCPublicKeyReport {\n validatePayload(raw.payload.length >= 17);\n const includingNode = !!(raw.payload[0] & 0b1);\n const publicKey: BytesView = raw.payload.subarray(1);\n return new this({\n nodeId: ctx.sourceNodeId,\n includingNode,\n publicKey,\n });\n }\n public includingNode: boolean;\n public publicKey: BytesView;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n [this.includingNode ? 1 : 0],\n this.publicKey,\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"is including node\": this.includingNode,\n \"public key\": buffer2hex(this.publicKey),\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCNetworkKeyReportOptions {\n grantedKey: SecurityClass;\n networkKey: BytesView;\n}\n@CCCommand(Security2Command.NetworkKeyReport)\nexport class Security2CCNetworkKeyReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCNetworkKeyReportOptions>) {\n super(options);\n this.grantedKey = options.grantedKey;\n this.networkKey = options.networkKey;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNetworkKeyReport {\n validatePayload(raw.payload.length >= 17);\n const grantedKey: SecurityClass = bitMaskToSecurityClass(raw.payload, 0);\n const networkKey = raw.payload.subarray(1, 17);\n return new this({\n nodeId: ctx.sourceNodeId,\n grantedKey,\n networkKey,\n });\n }\n public grantedKey: SecurityClass;\n public networkKey: BytesView;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.concat([\n securityClassToBitMask(this.grantedKey),\n this.networkKey,\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"security class\": getEnumMemberName(SecurityClass, this.grantedKey),\n // This shouldn't be logged, so users can safely post their logs online\n // \"network key\": buffer2hex(this.networkKey),\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCNetworkKeyGetOptions {\n requestedKey: SecurityClass;\n}\n@CCCommand(Security2Command.NetworkKeyGet)\n// Don't expect a response - we need to distinguish between Report and Fail\n// FIXME: maybe use the dynamic @expectedCCResponse instead?\nexport class Security2CCNetworkKeyGet extends Security2CC {\n public constructor(options: WithAddress<Security2CCNetworkKeyGetOptions>) {\n super(options);\n this.requestedKey = options.requestedKey;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCNetworkKeyGet {\n validatePayload(raw.payload.length >= 1);\n const requestedKey: SecurityClass = bitMaskToSecurityClass(raw.payload, 0);\n return new this({\n nodeId: ctx.sourceNodeId,\n requestedKey,\n });\n }\n public requestedKey: SecurityClass;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = securityClassToBitMask(this.requestedKey);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"security class\": getEnumMemberName(SecurityClass, this.requestedKey),\n },\n };\n }\n}\n@CCCommand(Security2Command.NetworkKeyVerify)\nexport class Security2CCNetworkKeyVerify extends Security2CC {\n}\n// @publicAPI\nexport interface Security2CCTransferEndOptions {\n keyVerified: boolean;\n keyRequestComplete: boolean;\n}\n@CCCommand(Security2Command.TransferEnd)\nexport class Security2CCTransferEnd extends Security2CC {\n public constructor(options: WithAddress<Security2CCTransferEndOptions>) {\n super(options);\n this.keyVerified = options.keyVerified;\n this.keyRequestComplete = options.keyRequestComplete;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCTransferEnd {\n validatePayload(raw.payload.length >= 1);\n const keyVerified = !!(raw.payload[0] & 0b10);\n const keyRequestComplete = !!(raw.payload[0] & 0b1);\n return new this({\n nodeId: ctx.sourceNodeId,\n keyVerified,\n keyRequestComplete,\n });\n }\n public keyVerified: boolean;\n public keyRequestComplete: boolean;\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = Bytes.from([\n (this.keyVerified ? 0b10 : 0) + (this.keyRequestComplete ? 0b1 : 0),\n ]);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"key verified\": this.keyVerified,\n \"request complete\": this.keyRequestComplete,\n },\n };\n }\n}\n// @publicAPI\nexport interface Security2CCCommandsSupportedReportOptions {\n supportedCCs: CommandClasses[];\n}\n@CCCommand(Security2Command.CommandsSupportedReport)\nexport class Security2CCCommandsSupportedReport extends Security2CC {\n public constructor(options: WithAddress<Security2CCCommandsSupportedReportOptions>) {\n super(options);\n this.supportedCCs = options.supportedCCs;\n }\n public static from(raw: CCRaw, ctx: CCParsingContext): Security2CCCommandsSupportedReport {\n const CCs = parseCCList(raw.payload);\n // SDS13783: A sending node MAY terminate the list of supported command classes with the\n // COMMAND_CLASS_MARK command class identifier.\n // A receiving node MUST stop parsing the list of supported command classes if it detects the\n // COMMAND_CLASS_MARK command class identifier in the Security 2 Commands Supported Report\n const supportedCCs = CCs.supportedCCs;\n return new this({\n nodeId: ctx.sourceNodeId,\n supportedCCs,\n });\n }\n public readonly supportedCCs: CommandClasses[];\n public serialize(ctx: CCEncodingContext): Promise<Bytes> {\n this.payload = encodeCCList(this.supportedCCs, []);\n return super.serialize(ctx);\n }\n public toLogEntry(ctx?: GetValueDB): MessageOrCCLogEntry {\n return {\n ...super.toLogEntry(ctx),\n message: {\n \"supported CCs\": logList(this.supportedCCs.map((cc) => getCCName(cc))),\n },\n };\n }\n}\n@CCCommand(Security2Command.CommandsSupportedGet)\n@expectedCCResponse(Security2CCCommandsSupportedReport)\nexport class Security2CCCommandsSupportedGet extends Security2CC {\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,kBAAwsB;AACxsB,oBAAoF;AACpF,mBAAqB;AACrB,wBAAwB;AACxB,iBAAsB;AACtB,0BAAsF;AACtF,oCAAsF;AACtF,uBAA+I;AAC/I,IAAAA,iBAAuD;AACvD,mBAAiC;AAEjC,qBAAwB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AK;;;IAGrC;;;;IAOS,sCAAkC,MAAA;8BAD9C,yCAAU,8BAAiB,uBAAuB,CAAC;;;;oBACI;0DAAA,YAAW;WAAA;;;;;;;;AAAnE,qCAAA,MAAA,mBAAA,EAAA,OAAA,WAAA,GAAA,kBAAA,EAAA,MAAA,SAAA,MAAA,WAAA,MAAA,UAAA,UAAA,GAAA,MAAA,uBAAA;;;AAAa,0CAAA,YAAA,uBAAA;;IACT,YAAmB,SAA+D;AAC9E,YAAM,OAAO;AACb,WAAK,eAAe,QAAQ;IAChC;IACO,OAAO,KAAK,KAAY,KAAqB;AAChD,YAAM,UAAM,yBAAY,IAAI,OAAO;AAKnC,YAAM,eAAe,IAAI;AACzB,aAAO,IAAI,KAAK;QACZ,QAAQ,IAAI;QACZ;OACH;IACL;IACgB;IACT,UAAU,KAAsB;AACnC,WAAK,cAAU,0BAAa,KAAK,cAAc,CAAA,CAAE;AACjD,aAAO,MAAM,UAAU,GAAG;IAC9B;IACO,WAAW,KAAgB;AAC9B,aAAO;QACH,GAAG,MAAM,WAAW,GAAG;QACvB,SAAS;UACL,qBAAiB,qBAAQ,KAAK,aAAa,IAAI,CAAC,WAAO,uBAAU,EAAE,CAAC,CAAC;;;IAGjF;;;;IAIS,mCAA+B,MAAA;8BAF3C,yCAAU,8BAAiB,oBAAoB,OAC/C,kDAAmB,kCAAkC,CAAC;;;;oBACF;uDAAA,YAAW;WAAA;;;;;;;;AAAhE,qCAAA,MAAA,mBAAA,EAAA,OAAA,WAAA,GAAA,kBAAA,EAAA,MAAA,SAAA,MAAA,WAAA,MAAA,UAAA,UAAA,GAAA,MAAA,uBAAA;;;AAAa,0CAAA,YAAA,uBAAA;;;;;",
6
6
  "names": ["import_shared", "secClass", "Security2CC", "nodeId", "mpanExtension", "Security2CCMessageEncapsulation"]
7
7
  }
@@ -638,7 +638,7 @@ let SecurityCCCommandEncapsulation = (() => {
638
638
  }
639
639
  }
640
640
  }
641
- if (process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development") {
641
+ if ((0, import_shared.getenv)("NODE_ENV") === "test" || (0, import_shared.getenv)("NODE_ENV") === "development") {
642
642
  if (this.iv) {
643
643
  message.IV = (0, import_shared.buffer2hex)(this.iv);
644
644
  }