/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { ClientInteraction } from "#action/client/ClientInteraction.js"; import { ClientRead } from "#action/client/ClientRead.js"; import { WriteResult } from "#action/index.js"; import { Invoke } from "#action/request/Invoke.js"; import { Read } from "#action/request/Read.js"; import { Write } from "#action/request/Write.js"; import { ResultStatus } from "#action/response/ResultStatus.js"; import { BleDisconnectedError } from "#ble/Ble.js"; import { Certificate } from "#certificate/kinds/Certificate.js"; import { PeerMessageMissingError, PeerUnresponsiveError } from "#peer/PeerCommunicationError.js"; import { OperationalDataset } from "#thread/OperationalDataset.js"; import { asError, Bytes, CanceledError, causedBy, ChannelType, Diagnostic, Duration, EcdsaSignature, ImplementationError, Instant, Logger, Millis, Minutes, NoResponseTimeoutError, PublicKey, repackErrorAs, Seconds, Time, Timer, Timespan, Timestamp, UnexpectedDataError, } from "@matter/general"; import { ClusterId, ClusterType, EndpointNumber, FabricIndex, Global, NodeId, Status, StatusResponseError, VendorId, } from "@matter/types"; import { BasicInformation } from "@matter/types/clusters/basic-information"; import { Descriptor } from "@matter/types/clusters/descriptor"; import { GeneralCommissioning } from "@matter/types/clusters/general-commissioning"; import { NetworkCommissioning } from "@matter/types/clusters/network-commissioning"; import { OperationalCredentials } from "@matter/types/clusters/operational-credentials"; import { OtaSoftwareUpdateRequestor } from "@matter/types/clusters/ota-software-update-requestor"; import { TimeSynchronization } from "@matter/types/clusters/time-synchronization"; import { CertificateAuthority } from "../certificate/CertificateAuthority.js"; import { AttestationFinding, DeviceAttestationCheck, DeviceAttestationError, DeviceAttestationValidator, } from "../certificate/DeviceAttestationValidator.js"; import { Dac } from "../certificate/kinds/AttestationCertificates.js"; import { TlvCertSigningRequest } from "../common/OperationalCredentialsTypes.js"; import { DclCertificateService } from "../dcl/DclCertificateService.js"; import { Fabric } from "../fabric/Fabric.js"; import { CommissioningError } from "./CommissioningError.js"; import { PeerAddress } from "./PeerAddress.js"; const logger = Logger.get("ControllerCommissioner"); export interface OtaProviderLocation { nodeId: NodeId; endpoint: EndpointNumber; } /** * User specific options for the Commissioning process */ export type ControllerCommissioningFlowOptions = { /** * The regulatory location (indoor or outdoor) where the device is used. */ regulatoryLocation: GeneralCommissioning.RegulatoryLocationType; /** * The country where the device is used. */ regulatoryCountryCode: string; /** * The vendor ID we present as a commissioner. */ adminVendorId?: VendorId; /** * Required credentials if the device is to connect to a wifi network provide the credentials here. */ wifiNetwork?: { wifiSsid: string; wifiCredentials: string; }; /** * If the device should connect to a thread network. */ threadNetwork?: { networkName?: string; operationalDataset: string; }; /** The Location of the OTA provider for this fabric set on the commissioned devices if OTA is supported */ otaUpdateProviderLocation?: OtaProviderLocation; /** * Attestation validation settings. Injected by ControllerCommissioner — the only user-facing * part is `onFailure` which is forwarded from CommissioningClient options. */ attestation: { /** Attestation challenge key from the PASE session, used to verify attestation and CSR signatures. */ challengeKey: Bytes; /** DclCertificateService for PAA trust store and revocation checks. Looked up from environment. */ dclCertificateService?: DclCertificateService; /** * Controls behavior when attestation produces findings. * - `false`: reject on any finding * - `true`: always accept with info logging * - callback: receives `AttestationFinding[]` and decides the outcome; may * - return `true` to proceed * - return `false` to reject with the underlying error * - return a `string` to reject with a new {@link CommissioningError} whose message is * that string and whose `cause` is the underlying error * - throw any error to reject by rethrowing that error verbatim (no wrapping) * - `undefined`: accept with warning logging (backward compatibility) * * The callback receives either: * - A single error-level finding for hard failures (invalid chain, bad signature, revoked * certificate, untrusted PAA, DCL service unavailable). The commissioner must decide * whether to proceed despite the failure. * - One or more warning/info-level findings after successful validation (e.g. provisional * CD, test CD, skipped CD signer verification, no revocation data, test-cert-only PAA). * These are informational and the commissioner can inspect them for detailed decisions. * * TODO: Make required in next breaking version and remove undefined backward-compatible accept */ onFailure?: DeviceAttestationValidator.OnAttestationFailure; }; }; type AttestationDecision = { proceed: true } | { proceed: false; reason?: string }; /** Types representation of a general commissioning response. */ type CommissioningSuccessFailureResponse = { errorCode: number; debugText?: string; }; /** Result code of a single commissioning step. */ enum CommissioningStepResultCode { Success, Failure, Skipped, Stop, } /** * Result of a single commissioning step * Breadcrump value is stored for each step for transparency */ type CommissioningStepResult = { code: CommissioningStepResultCode; breadcrumb: number; }; /** * Definition of one commissioning step * All steps are for execution sorted by stepNumber and subStepNumber */ type CommissioningStep = { /** Step Number according to the specs */ stepNumber: number; /** Order of actions within a step */ subStepNumber: number; /** Name of the action or step */ name: string; /** Logic function to execute */ stepLogic: () => Promise; /** Optional flag to indicate that the failsafe timer should be rearmed in any case before this step. */ reArmFailsafe?: boolean; }; /** Data that are collected initially or through the commissioning process and can be used also by other steps. */ type CollectedCommissioningData = { basicCommissioningInfo?: GeneralCommissioning.BasicCommissioningInfo; productName?: string; networkFeatures?: { endpointId: EndpointNumber; value: ClusterType.FeaturesOf; }[]; networkStatus?: { endpointId: EndpointNumber; value: NetworkCommissioning.NetworkInfo[]; }[]; otaRequestorList?: EndpointNumber[]; rootPartsList?: EndpointNumber[]; rootServerList?: ClusterId[]; vendorId?: VendorId; productId?: number; supportsConcurrentConnection?: boolean; successfullyConnectedToNetwork?: boolean; fabricIndex?: FabricIndex; }; /** The number of fabrics that can be commissioned is already reached. */ export class MaximumCommissionedFabricsReachedError extends CommissioningError {} /** The commissioning process could not be finished within the maximum allowed commissioning timeframe. */ export class CommissioningTimeoutError extends CommissioningError {} /** Error that throws when the device is already commissioned to this fabric. */ export class DeviceAlreadyCommissionedToThisFabricError extends CommissioningError {} /** Error that throws when the device is already commissioned to another fabric with the same label. */ export class FabricLabelConflictError extends CommissioningError {} /** Error that throws when the device has no connected network and no credentials for Wifi or Thread network were configured. */ export class WifiOrThreadNetworkCredentialsNotConfiguredError extends CommissioningError {} /** Error that throws when the setup for the provided Wifi network failed. */ export class WifiNetworkSetupFailedError extends CommissioningError {} /** Error that throws when the setup for the provided Thread network failed. */ export class ThreadNetworkSetupFailedError extends CommissioningError {} /** Error that throws when the NodeId is already used in the fabric. */ export class NodeIdConflictError extends CommissioningError {} /** Error that throws when the device could not be connected using the operational discovery and no session could be created. */ export class OperativeConnectionFailedError extends CommissioningError {} /** Error that throws when Commissioning fails but a process can be continued. */ class RecoverableCommissioningError extends CommissioningError {} /** Error that throws when a supplied Thread network name contradicts the name inside the operational dataset. */ export class ThreadNetworkNameMismatchError extends CommissioningError {} /** * Resolve the Thread network name to commission with. * * Derives the name from the operational dataset when the caller omitted it, and verifies a caller-supplied name against * the dataset — declining on mismatch so an ambiguous credential set cannot silently commission the wrong network. A * dataset that cannot be decoded is left to the device to reject; the supplied name is kept as-is. */ export function resolveThreadNetworkName(threadNetwork: { networkName?: string; operationalDataset: string; }): string | undefined { let datasetName: string | undefined; try { datasetName = OperationalDataset.decode(threadNetwork.operationalDataset).networkName; } catch (error) { logger.warn( `Could not decode Thread operational dataset to derive/verify its network name: ${asError(error).message}`, ); return threadNetwork.networkName || undefined; } const { networkName } = threadNetwork; if (!networkName) { return datasetName; } if (datasetName !== undefined && datasetName !== networkName) { throw new ThreadNetworkNameMismatchError( `Thread network name "${networkName}" does not match the name "${datasetName}" in the supplied operational dataset`, ); } return networkName; } const DEFAULT_FAILSAFE_TIME = Minutes.one; /** When we execute longer actions like network connections or reconnection, we need to keep the BTP session alive */ const BTP_IDLE_ALIVE_INTERVAL = Seconds(25); /** Expected maximum time for CASE session establishment over the operational network. */ const CASE_RECONNECT_TIMEOUT = Minutes(5); /** Failsafe left after the wait for a response ends. */ const FAILSAFE_PROCESSING_MARGIN = Seconds(10); /** Most MRP send time counted into the wait for a response when sizing the failsafe. */ const FAILSAFE_MAX_SEND_TIME = Seconds(10); /** Devices may report very low scan/connect timeouts that are not enough in practice */ const MIN_NETWORK_SCAN_TIMEOUT_SECONDS = 60; const MIN_NETWORK_CONNECT_TIMEOUT_SECONDS = 60; const RootEndpointNumber = EndpointNumber(0); /** * Class to abstract the Device commission flow in a step wise way as defined in Specs. The specs are not 100% */ export class ControllerCommissioningFlow { protected interaction: ClientInteraction; protected readonly ca: CertificateAuthority; protected readonly fabric: Fabric; protected readonly transitionToCase: ( peerAddress: PeerAddress, supportsConcurrentConnections: boolean, ) => Promise; protected readonly commissioningOptions: ControllerCommissioningFlowOptions; protected readonly commissioningSteps = new Array(); protected readonly commissioningStepResults = new Map(); #commissioningStartedTime: Timestamp | undefined; #commissioningExpiryTime: Timestamp | undefined; #currentFailSafeEndTime: Timestamp | undefined; #dacPublicKey?: ReturnType; protected lastBreadcrumb = 1; protected collectedCommissioningData: CollectedCommissioningData = {}; #defaultFailSafeTime = DEFAULT_FAILSAFE_TIME; #armFailsafeInterval?: Timer; constructor( /** ClientInteraction for the initiated PASE session */ interaction: ClientInteraction, /** CertificateAuthority of the controller. */ ca: CertificateAuthority, /** Fabric of the controller. */ fabric: Fabric, /** Commissioning options for the commissioning process. */ commissioningOptions: ControllerCommissioningFlowOptions, /** Callback that establishes CASE connection or handles final commissioning */ transitionToCase: ( peerAddress: PeerAddress, supportsConcurrentConnections: boolean, ) => Promise, ) { this.interaction = interaction; this.ca = ca; this.fabric = fabric; this.transitionToCase = transitionToCase; this.commissioningOptions = commissioningOptions; logger.debug(`Commissioning options: ${Diagnostic.json(commissioningOptions)}`); this.#initializeCommissioningSteps(); } async [Symbol.asyncDispose]() { await this.interaction.close(); } /** * Fabric index assigned to our identity by the peer device, captured from the AddNoc response. Defined * after `executeCommissioning()` resolves successfully. */ get fabricIndexOnPeer(): FabricIndex | undefined { return this.collectedCommissioningData.fabricIndex; } /** * Execute the commissioning process in the defined order. The steps are sorted before execution based on the step * number and sub step number. * If >50% of the failsafe time has passed, the failsafe timer is re-armed (50% of 60s default are 30s and each * action is allowed to take 30s at minimum based on specs). */ async executeCommissioning() { this.#sortSteps(); let failSafeTimerReArmedAfterPreviousStep = false; for (const step of this.commissioningSteps) { logger.info(`Executing commissioning step ${step.stepNumber}.${step.subStepNumber}: ${step.name}`); try { if ( step.reArmFailsafe && !failSafeTimerReArmedAfterPreviousStep && !this.#armFailsafeInterval?.isRunning ) { logger.debug(`Re-Arming failsafe timer before executing step`); await this.#reArmFailsafeBetweenSteps(); } failSafeTimerReArmedAfterPreviousStep = false; const result = await step.stepLogic(); this.#setCommissioningStepResult(step, result); if (this.#currentFailSafeEndTime !== undefined) { if (this.#commissioningExpiryTime !== undefined && Time.nowMs > this.#commissioningExpiryTime) { logger.error( `Commissioning step ${step.stepNumber}.${step.subStepNumber}: ${step.name} succeeded, but commissioning took too long in general!`, ); const maxTimeS = this.collectedCommissioningData.basicCommissioningInfo?.maxCumulativeFailsafeSeconds; throw new CommissioningTimeoutError( `Commissioning time exceeds the maximum timeframe${maxTimeS ? ` of ${maxTimeS}s` : ""}`, ); } /** * Commissioner SHALL re-arm the Fail-safe timer on the Commissionee to the desired commissioning * timeout within 60 seconds of the completion of a PASE session establishment, using the ArmFailSafe * command (see Section 11.10.7.2, “ArmFailSafe Command”) */ const timeLeft = Timespan(Time.nowMs, this.#currentFailSafeEndTime).duration; if (timeLeft < this.#defaultFailSafeTime / 2) { logger.info( `After Commissioning step ${step.stepNumber}.${step.subStepNumber}: ${ step.name } succeeded, ${Duration.format(timeLeft)} left for failsafe timer, re-arming failsafe`, ); failSafeTimerReArmedAfterPreviousStep = await this.#reArmFailsafeBetweenSteps(); } } if (result.code === CommissioningStepResultCode.Stop) { break; } } catch (e) { const error = asError(e); if (error instanceof RecoverableCommissioningError) { logger.warn( `Commissioning step ${step.stepNumber}.${step.subStepNumber}: ${step.name} failed with recoverable error:`, Diagnostic.errorMessage(error), Diagnostic.weak("(continuing commissioning)"), ); } else if (causedBy(error, CommissioningError, StatusResponseError)) { logger.error( `Commissioning step ${step.stepNumber}.${step.subStepNumber}: ${step.name} failed with error:`, Diagnostic.errorMessage(error), Diagnostic.weak("(terminating commissioning)"), ); // TODO In concurrent connection commissioning flow, the failure of any of the steps 2 through 10 // SHALL result in the Commissioner and Commissionee returning to step 2 (device discovery and // commissioning channel establishment) and repeating each step. The failure of any of the steps // 11 through 15 in concurrent connection commissioning flow SHALL result in the Commissioner and // Commissionee returning to step 11 (configuration of operational network information). In the // case of failure of any of the steps 11 through 15 in concurrent connection commissioning flow, // the Commissioner and Commissionee SHALL reuse the existing PASE-derived encryption keys over // the commissioning channel and all steps up to and including step 10 are considered to have // been successfully completed. // Commissioners that need to restart from step 2 MAY immediately expire the fail-safe by invoking // the ArmFailSafe command with an ExpiryLengthSeconds field set to 0. Otherwise, Commissioners // will need to wait until the current fail-safe timer has expired for the Commissionee to begin // accepting PASE again. await this.#resetFailsafeTimer(); StatusResponseError.accept(error); // Convert error throw repackErrorAs(error, CommissioningError); } else { throw error; } } } } /** * Convenience method to get a number of attributes in a read and return exactly these values in the order as * defined in the request */ async #readConcreteAttributeValues(request: ClientRead) { const attributeMap = new Map(); if (request.attributeRequests === undefined) { throw new ImplementationError("Can only handle Attribute reads"); } for (const { endpointId, clusterId, attributeId } of request.attributeRequests) { if (endpointId === undefined || clusterId === undefined) { continue; } attributeMap.set(`${endpointId}-${clusterId}-${attributeId}`, undefined); } for await (const data of this.interaction.read(request)) { for await (const entry of data) { if (entry.kind !== "attr-value") { continue; } const { path: { endpointId, clusterId, attributeId }, value, } = entry; const key = `${endpointId}-${clusterId}-${attributeId}`; if (!attributeMap.has(key)) { continue; } attributeMap.set(key, value); } } return [...attributeMap.values()]; } // TODO improve response typing async #invokeCommand( request: Invoke.ConcreteCommandRequest, options: Omit = {}, ) { for await (const data of this.interaction.invoke( Invoke({ commands: [request], ...options, }), )) { for (const entry of data) { // We send only one command, so we only get one response back switch (entry.kind) { case "cmd-status": if (entry.status !== Status.Success) { throw ResultStatus.errorOf(entry); } return; case "cmd-response": return entry.data; } } } } /** * Initialize commissioning steps and add them in the default order as defined by * @see {@link MatterSpecification.v161.Core} § 5.5 */ #initializeCommissioningSteps() { this.commissioningSteps.push({ stepNumber: 0, // Preparation subStepNumber: 1, name: "GetInitialData", stepLogic: () => this.#getInitialData(), }); // Step 1: is outside of this class and requires to have relevant information needed by next steps // Step 2: is about discovery which is already done before this starts here // TODO Step 3-5: Commissioner handles/prepares for T&C Ack, if supported // Step 6: is the PASE session establishment which is done before this starts here this.commissioningSteps.push({ stepNumber: 7, subStepNumber: 1, name: "GeneralCommissioning.ArmFailsafe", stepLogic: () => this.#armFailsafe(), }); this.commissioningSteps.push({ stepNumber: 8, subStepNumber: 1, name: "GeneralCommissioning.ConfigureRegulatoryInformation", stepLogic: () => this.#configureRegulatoryInformation(), }); this.commissioningSteps.push({ stepNumber: 8, subStepNumber: 2, name: "TimeSynchronization.SynchronizeTime", stepLogic: () => this.#synchronizeTime(), }); // TODO Step 9: If device and Controller supports T&C Feature then User consent is handled this.commissioningSteps.push({ stepNumber: 10, subStepNumber: 1, name: "OperationalCredentials.DeviceAttestation", stepLogic: () => this.#deviceAttestation(), }); this.commissioningSteps.push({ stepNumber: 11, // includes 11-13 subStepNumber: 1, name: "OperationalCredentials.Certificates", stepLogic: () => this.#certificates(), }); // TODO Step 14: TimeSynchronization.SetTrustedTimeSource if supported this.commissioningSteps.push({ stepNumber: 15, subStepNumber: 1, name: "AccessControl", stepLogic: () => this.#configureAccessControlLists(), }); // Care about Network commissioning only when we are on BLE, because else we are already on IP network if (this.interaction.channelType === ChannelType.BLE) { this.commissioningSteps.push({ stepNumber: 16, subStepNumber: 1, name: "NetworkCommissioning.Validate", stepLogic: () => this.#validateNetwork(), }); if (this.commissioningOptions.wifiNetwork !== undefined) { this.commissioningSteps.push({ stepNumber: 16, // includes step 17 subStepNumber: 2, name: "NetworkCommissioning.Wifi", reArmFailsafe: true, stepLogic: () => this.#configureNetworkWifi(), }); } if (this.commissioningOptions.threadNetwork !== undefined) { this.commissioningSteps.push({ stepNumber: 16, // includes step 17 subStepNumber: 3, name: "NetworkCommissioning.Thread", reArmFailsafe: true, stepLogic: () => this.#configureNetworkThread(), }); } } else { logger.info( `Skipping NetworkCommissioning steps because the device is already on IP network (${this.interaction.channelType})`, ); } this.commissioningSteps.push({ stepNumber: 18, // includes step 19 (CASE connection) subStepNumber: 1, name: "Reconnect", stepLogic: () => this.#reconnectWithDevice(), }); this.commissioningSteps.push({ stepNumber: 20, subStepNumber: 1, name: "GeneralCommissioning.Complete", stepLogic: () => this.#completeCommissioning(), }); this.commissioningSteps.push({ stepNumber: 98, // Should be allowed in Step 13, but Tasmota is not supporting this subStepNumber: 1, name: "OperationalCredentials.UpdateFabricLabel", stepLogic: () => this.#updateFabricLabel(), }); if (this.commissioningOptions.otaUpdateProviderLocation !== undefined) { this.commissioningSteps.push({ stepNumber: 99, subStepNumber: 1, name: "AdditionalLogic.AddDefaultOtaProvider", stepLogic: () => this.#addDefaultOtaProvider(), }); } } #sortSteps() { this.commissioningSteps.sort((a, b) => { if (a.stepNumber !== b.stepNumber) return a.stepNumber - b.stepNumber; return a.subStepNumber - b.subStepNumber; }); } #setCommissioningStepResult(step: CommissioningStep, result: CommissioningStepResult) { this.commissioningStepResults.set(`${step.stepNumber}-${step.subStepNumber}`, result); } getCommissioningStepResult(stepNumber: number, subStepNumber: number) { return this.commissioningStepResults.get(`${stepNumber}-${subStepNumber}`); } /** Helper method to check for errorCode/debugTest responses and throw error on failure */ #ensureOperationalCredentialsSuccess( context: string, { statusCode, debugText, fabricIndex }: OperationalCredentials.NocResponse, ) { logger.debug( `Commissioning step ${context} returned ${OperationalCredentials.NodeOperationalCertStatus[statusCode]} (${statusCode})${debugText ? `, ${debugText}` : ""}${ fabricIndex !== undefined ? `, fabricIndex: ${fabricIndex}` : "" }`, ); if (statusCode === OperationalCredentials.NodeOperationalCertStatus.Ok) return; if (context === "addNoc") { // Let's return a bit more convenient error in this case if (statusCode === OperationalCredentials.NodeOperationalCertStatus.FabricConflict) { throw new DeviceAlreadyCommissionedToThisFabricError( `Commission error: This device is already commissioned into this fabric. You cannot commission it again.`, ); } else if (statusCode === OperationalCredentials.NodeOperationalCertStatus.TableFull) { throw new MaximumCommissionedFabricsReachedError( `Commission error: This device reached the maximum number of fabrics it can be part of. Please remove a fabric before trying to add another one.`, ); } } else if ( context === "updateFabricLabel" && statusCode === OperationalCredentials.NodeOperationalCertStatus.LabelConflict ) { throw new FabricLabelConflictError( `Cannot set fabric label to "${this.fabric.label}" because another fabric on this device already uses this name. Please adjust fabric labels to be unique.`, ); } throw new CommissioningError( `Commission error for "${context}": ${OperationalCredentials.NodeOperationalCertStatus[statusCode]} (${statusCode})${debugText ? `, ${debugText}` : ""}${ fabricIndex !== undefined ? `, fabricIndex: ${fabricIndex}` : "" }`, ); } /** Helper method to check for errorCode/debugTest responses and throw error on failure */ #ensureGeneralCommissioningSuccess(context: string, { errorCode, debugText }: CommissioningSuccessFailureResponse) { logger.debug(`Commissioning step ${context} returned ${errorCode}${debugText ? `, ${debugText}` : ""}`); if (errorCode === GeneralCommissioning.CommissioningError.Ok) return; throw new CommissioningError( `Commission error for "${context}": ${GeneralCommissioning.CommissioningError[errorCode]} (${errorCode})${debugText ? `, ${debugText}` : ""}`, ); } /** * Initial Step to receive some common data used by other steps */ async #getInitialData() { const [ supportedFabrics, commissionedFabrics, rootPartsList, rootServerList, vendorId, productId, productName, supportsConcurrentConnection, ] = await this.#readConcreteAttributeValues( Read( Read.Attribute({ endpoint: RootEndpointNumber, cluster: OperationalCredentials, attributes: ["supportedFabrics", "commissionedFabrics"], }), Read.Attribute({ endpoint: RootEndpointNumber, cluster: Descriptor, attributes: ["partsList", "serverList"], }), Read.Attribute({ endpoint: RootEndpointNumber, cluster: BasicInformation, attributes: ["vendorId", "productId", "productName"], }), Read.Attribute({ endpoint: RootEndpointNumber, cluster: GeneralCommissioning, attributes: ["supportsConcurrentConnection"], }), ), ); if (commissionedFabrics >= supportedFabrics) { throw new MaximumCommissionedFabricsReachedError( `Commissioned fabrics (${commissionedFabrics}) exceed supported fabrics (${supportedFabrics}). Please remove some fabrics before commissioning.`, ); } this.collectedCommissioningData.rootPartsList = rootPartsList; this.collectedCommissioningData.rootServerList = rootServerList; this.collectedCommissioningData.vendorId = vendorId; this.collectedCommissioningData.productId = productId; this.collectedCommissioningData.productName = productName; this.collectedCommissioningData.supportsConcurrentConnection = supportsConcurrentConnection; const networkData = this.interaction.read( Read( Read.Attribute({ cluster: NetworkCommissioning, attributes: ["featureMap", "networks"], }), Read.Attribute({ cluster: OtaSoftwareUpdateRequestor, attributes: ["defaultOtaProviders"], }), ), ); const networkFeatures = new Array<{ endpointId: EndpointNumber; value: ClusterType.FeaturesOf; }>(); const networkStatus = new Array<{ endpointId: EndpointNumber; value: NetworkCommissioning.NetworkInfo[]; }>(); const otaRequestors = new Array(); for await (const data of networkData) { for await (const entry of data) { if (entry.kind !== "attr-value") { continue; } const { path: { endpointId, attributeId }, value, } = entry; switch (attributeId) { case Global.attributes.featureMap.id: networkFeatures.push({ endpointId, value: value as ClusterType.FeaturesOf, }); break; case NetworkCommissioning.attributes.networks.id: networkStatus.push({ endpointId, value: value as NetworkCommissioning.NetworkInfo[], }); break; case OtaSoftwareUpdateRequestor.attributes.defaultOtaProviders.id: otaRequestors.push(endpointId); break; } } } this.collectedCommissioningData.networkFeatures = networkFeatures; this.collectedCommissioningData.networkStatus = networkStatus; this.collectedCommissioningData.otaRequestorList = otaRequestors; return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } /** * Re-arm the failsafe between commissioning steps. Skipped once the commissioning session is closed, for example * after the device left BLE for its operational network; the Reconnect step then continues over CASE. * * @returns true when the failsafe was re-armed */ async #reArmFailsafeBetweenSteps() { if (this.interaction.session?.isClosed) { logger.debug("Skipping armFailSafe between steps: session is closed"); return false; } await this.#armFailsafe(); return true; } /** * Step 7 * Commissioner SHALL re-arm the Fail-safe timer on the Commissionee to the desired commissioning * timeout within 60 seconds of the completion of a PASE session establishment, using the * ArmFailSafe command (see Section 11.10.7.2, “ArmFailSafe Command”). A Commissioner MAY * collect device information including guidance on the fail-safe value from the Commissionee by * reading BasicCommissioningInfo attribute (see Section 11.10.6.2, “BasicCommissioningInfo * Attribute”) before invoking the ArmFailSafe command. */ async #armFailsafe(time?: Duration) { if (this.collectedCommissioningData.basicCommissioningInfo === undefined) { const [basicCommissioningInfo] = await this.#readConcreteAttributeValues( Read( Read.Attribute({ endpoint: RootEndpointNumber, cluster: GeneralCommissioning, attributes: ["basicCommissioningInfo"], }), ), ); this.collectedCommissioningData.basicCommissioningInfo = basicCommissioningInfo; this.#defaultFailSafeTime = Seconds(basicCommissioningInfo.failSafeExpiryLengthSeconds); this.#commissioningStartedTime = Time.nowMs; this.#commissioningExpiryTime = Timestamp( this.#commissioningStartedTime + Seconds(basicCommissioningInfo.maxCumulativeFailsafeSeconds), ); } // armFailSafe.expiryLengthSeconds must not exceed the device's mandatory (uint16) maximum cumulative failsafe. const { basicCommissioningInfo } = this.collectedCommissioningData; const maxExpiry = basicCommissioningInfo ? Seconds(basicCommissioningInfo.maxCumulativeFailsafeSeconds) : this.#defaultFailSafeTime; const expiryLength = Duration.min(time ?? this.#defaultFailSafeTime, maxExpiry); this.#ensureGeneralCommissioningSuccess( "armFailSafe", await this.#invokeCommand({ endpoint: RootEndpointNumber, cluster: GeneralCommissioning, command: "armFailSafe", fields: { breadcrumb: this.lastBreadcrumb, expiryLengthSeconds: Seconds.of(expiryLength), }, }), ); this.#currentFailSafeEndTime = Timestamp(Time.nowMs + expiryLength); return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } get #failSafeTimeLeft() { if (this.#currentFailSafeEndTime === undefined) { return Instant; } return Duration.max(Timespan(Time.nowMs, this.#currentFailSafeEndTime).duration, 0); } async #ensureFailsafeTimerFor(maxProcessingTime: Duration) { // The failsafe must outlive our wait for the response. The MRP worst case of an idle ICD peer would arm the // device's maximum, which a failed commissioning leaves the device locked in, so send time counts only up to // FAILSAFE_MAX_SEND_TIME. const responseWait = Duration.min( this.interaction.maximumPeerResponseTime(maxProcessingTime, true), Millis(maxProcessingTime + FAILSAFE_MAX_SEND_TIME), ); const minFailsafeTime = Millis(responseWait + FAILSAFE_PROCESSING_MARGIN); if (this.interaction.channelType === ChannelType.BLE) { this.#armFailsafeInterval?.stop(); this.#armFailsafeInterval = Time.getPeriodicTimer( "Re-Arm Failsafe during longer interactions", BTP_IDLE_ALIVE_INTERVAL, () => { // Session gone (e.g. BLE dropped after connectNetwork) — pointless to re-arm, // and the send attempt would block until it finds out the hard way. if (this.interaction.session?.isClosed) { logger.debug("Skipping periodic armFailSafe: session is closed"); this.#armFailsafeInterval?.stop(); this.#armFailsafeInterval = undefined; return; } const now = Time.nowMs; if (this.#commissioningExpiryTime !== undefined && now < this.#commissioningExpiryTime) { logger.debug( `Re-Arm Failsafe Timer during longer actions with device. Time left: ${Duration.format(Timespan(now, this.#commissioningExpiryTime).duration)}`, ); this.#armFailsafe(Duration.max(this.#defaultFailSafeTime, this.#failSafeTimeLeft)).catch( error => { logger.warn("Error while re-arming failsafe during reconnect", error); this.#armFailsafeInterval?.stop(); this.#armFailsafeInterval = undefined; }, ); } else { // Stop as soon as we are over the maximum commissioning time this.#armFailsafeInterval?.stop(); this.#armFailsafeInterval = undefined; } }, ).start(); } // When not on BLE, we just ensure the Failsafe timer is armed long enough const timeLeft = this.#failSafeTimeLeft; if (timeLeft < minFailsafeTime) { logger.debug( `Failsafe timer has only ${Duration.format(timeLeft)} left, re-arming for at least ${Duration.format(minFailsafeTime)}`, ); await this.#armFailsafe(Duration.max(minFailsafeTime, this.#defaultFailSafeTime)); } else { logger.debug(`Failsafe timer is already set for at least ${Duration.format(timeLeft)}`); } } /** * On BLE the device may drop the commissioning channel when `connectNetwork` is sent, so the * failsafe must cover both the connect time and the subsequent CASE reconnection. We arm * pessimistically whenever BLE is in play — not just when the device has declared * `supportsConcurrentConnection=false` — because some devices report concurrent support but * behave non-concurrent in practice. Once BLE is gone we cannot extend the failsafe, and if * it expires on the device before CASE reconnect lands, the device rolls back addNOC. * * On IP transports, BLE drop is not a concern and the declared flag can be trusted. */ #connectNetworkFailsafeTime(connectMaxTimeSeconds: number): Duration { const pessimistic = this.interaction.channelType === ChannelType.BLE || this.collectedCommissioningData.supportsConcurrentConnection === false; if (pessimistic) { return Duration.max( Millis(Seconds(connectMaxTimeSeconds) + CASE_RECONNECT_TIMEOUT), this.#defaultFailSafeTime, ); } return Seconds(connectMaxTimeSeconds); } /** * Recognise transport-level failures on the commissioning channel that indicate the device has * stopped responding — typically because it moved to the operational network. Some devices drop * the channel the moment their operational network is configured (on `addOrUpdate*Network` or the * follow-up networks read), others only on `connectNetwork`. * * Device-returned `NetworkingStatus != Success` is NOT a transport error; those are real * spec-level failures (bad credentials, unknown network, etc.) and must surface normally. * * Bare `AbortedError` is deliberately excluded: a user-initiated cancel or shutdown abort must * propagate cleanly, not be swallowed as a "non-concurrent signal". Transport aborts surface * with a more specific cause ({@link PeerUnresponsiveError}, e.g. `PeerAckMissingError` from MRP timeouts, * {@link BleDisconnectedError} from BLE loss) that `causedBy` already matches. */ #isCommissioningChannelDrop(error: unknown) { return causedBy( error, BleDisconnectedError, // also matches BleChannelClosedError subclass PeerUnresponsiveError, NoResponseTimeoutError, ); } /** * Respond to a commissioning-channel drop by treating the device as non-concurrent: stop the * periodic failsafe re-arm timer (BLE is gone anyway) and flip the flag so `#reconnectWithDevice` * takes the non-concurrent path straight to operational discovery. */ #handleCommissioningChannelDrop(error: unknown) { logger.warn( "Commissioning channel dropped while configuring the operational network — assuming device is non-concurrent, proceeding to CASE", Diagnostic.errorMessage(asError(error)), ); this.collectedCommissioningData.supportsConcurrentConnection = false; this.#armFailsafeInterval?.stop(); this.#armFailsafeInterval = undefined; } /** * Run a network-configuration interaction that may cause the device to leave the commissioning * channel and classify the outcome. * * - `transportFailure: true` means the channel dropped (BLE/MRP gone); the flag has already been * flipped by {@link #handleCommissioningChannelDrop} and the caller should return * {@link CommissioningStepResultCode.Success} so the flow falls through into the non-concurrent * CASE reconnect path. * - `transportFailure: false` carries the action's result for the caller to validate. * * Non-transport errors (real spec failures) propagate unchanged. */ async #withCommissioningChannelDropFallback( action: () => Promise, ): Promise<{ transportFailure: true } | { transportFailure: false; value: T }> { try { return { transportFailure: false, value: await action() }; } catch (error) { if (!this.#isCommissioningChannelDrop(error)) throw error; this.#handleCommissioningChannelDrop(error); return { transportFailure: true }; } } /** * Issue `NetworkCommissioning.connectNetwork` for the given network and classify the outcome. * * - `transportFailure: true` means the channel dropped mid-connect; the caller returns Success to * fall through into the non-concurrent CASE reconnect path. * - `transportFailure: false` carries the device's actual response and is the caller's job to * validate ({@link NetworkCommissioning.NetworkCommissioningStatus}, debug text, etc). * * Shared between the WiFi and Thread paths so the try/catch + ensureFailsafe dance lives in * one place and both media stay in lockstep. */ async #invokeConnectNetwork( networkId: Uint8Array, connectMaxTimeSeconds: number, ): Promise<{ transportFailure: true } | { transportFailure: false; networkingStatus: number; debugText?: string }> { await this.#ensureFailsafeTimerFor(this.#connectNetworkFailsafeTime(connectMaxTimeSeconds)); const result = await this.#withCommissioningChannelDropFallback(() => this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: NetworkCommissioning, command: "connectNetwork", fields: { networkId, breadcrumb: this.lastBreadcrumb++, }, }, { expectedProcessingTime: Seconds(connectMaxTimeSeconds), }, ), ); if (result.transportFailure) { return { transportFailure: true }; } const { networkingStatus, debugText } = result.value; return { transportFailure: false, networkingStatus, debugText }; } async #resetFailsafeTimer() { if (this.#currentFailSafeEndTime === undefined) return; try { await this.#invokeCommand({ endpoint: RootEndpointNumber, cluster: GeneralCommissioning, command: "armFailSafe", fields: { breadcrumb: this.lastBreadcrumb, expiryLengthSeconds: 0, }, }); this.#currentFailSafeEndTime = undefined; // No failsafe active anymore } catch (error) { logger.error(`Error while resetting failsafe timer`, error); } } /** * Step 8 - 1 * Commissioner SHALL configure regulatory information if the Commissionee has at least one instance of * the Network Commissioning cluster on any endpoint with either the WI (i.e. Wi-Fi) or TH (i.e. Thread) * feature flags set in its FeatureMap, Commissioner SHALL configure regulatory information in the * Commissionee using the SetRegulatoryConfig command. */ async #configureRegulatoryInformation() { if (this.collectedCommissioningData.networkFeatures === undefined) { throw new CommissioningError( "Initial information collection failed. No network features collected. This should never happen.", ); } // Read the infos for all Network Commissioning clusters const hasRadioNetwork = this.collectedCommissioningData.networkFeatures.some( ({ value: { wiFiNetworkInterface, threadNetworkInterface } }) => wiFiNetworkInterface || threadNetworkInterface, ); if (hasRadioNetwork) { let [locationCapability] = await this.#readConcreteAttributeValues( Read( Read.Attribute({ endpoint: RootEndpointNumber, cluster: GeneralCommissioning, attributes: ["locationCapability"], }), ), ); if (locationCapability === GeneralCommissioning.RegulatoryLocationType.IndoorOutdoor) { locationCapability = this.commissioningOptions.regulatoryLocation; } else { logger.debug( `Device does not support a configurable regulatory location type. Location is set to "${ locationCapability === GeneralCommissioning.RegulatoryLocationType.Indoor ? "Indoor" : "Outdoor" }"`, ); } let countryCode = this.commissioningOptions.regulatoryCountryCode; const regulatoryResult = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: GeneralCommissioning, command: "setRegulatoryConfig", fields: { breadcrumb: this.lastBreadcrumb++, newRegulatoryConfig: locationCapability, countryCode, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); if ( regulatoryResult.errorCode === GeneralCommissioning.CommissioningError.ValueOutsideRange && countryCode !== "XX" ) { logger.debug( `Device does not support a configurable country code. Use "XX" instead of "${countryCode}"`, ); countryCode = "XX"; this.#ensureGeneralCommissioningSuccess( "setRegulatoryConfig", await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: GeneralCommissioning, command: "setRegulatoryConfig", fields: { breadcrumb: this.lastBreadcrumb, newRegulatoryConfig: locationCapability, countryCode, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ), ); } else { this.#ensureGeneralCommissioningSuccess("setRegulatoryConfig", regulatoryResult); } return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } /** * Step 8 - 2 * Commissioner SHOULD configure UTC time, timezone, and DST offset, if the Commissionee supports the * time synchronization cluster. * ▪ The Commissioner SHOULD configure UTC time using the SetUTCTime command. * ▪ The Commissioner SHOULD set the time zone using the SetTimeZone command, if the TimeZone Feature is supported. * ▪ The Commissioner SHOULD set the DST offsets using the SetDSTOffset command if the TimeZone Feature is supported, and the SetTimeZoneResponse from the Commissionee had the DSTOffsetsRequired field set to True. * ▪ The Commissioner SHOULD set a Default NTP server using the SetDefaultNTP command if the NTPClient Feature is supported and the DefaultNTP attribute is null. If the current value is non-null, Commissioners MAY opt to overwrite the current value. */ async #synchronizeTime() { if ( this.collectedCommissioningData.rootServerList !== undefined && this.collectedCommissioningData.rootServerList.find(clusterId => clusterId === TimeSynchronization.id) ) { logger.debug("TimeSynchronization cluster is supported"); // TODO: implement } return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } /** * Step 10 * Commissioner SHALL establish the authenticity of the Commissionee as a certified Matter device * (see Section 6.2.3, “Device Attestation Procedure”). */ async #deviceAttestation() { const { certificate: deviceAttestation } = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: OperationalCredentials, command: "certificateChainRequest", fields: { certificateType: OperationalCredentials.CertificateChainType.DacCertificate, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); const { certificate: productAttestation } = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: OperationalCredentials, command: "certificateChainRequest", fields: { certificateType: OperationalCredentials.CertificateChainType.PaiCertificate, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); const attestationNonce = this.fabric.crypto.randomBytes(32); const { attestationElements, attestationSignature } = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: OperationalCredentials, command: "attestationRequest", fields: { attestationNonce, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); const { attestation } = this.commissioningOptions; let findings: AttestationFinding[]; let baseError: Error | undefined; let dacPublicKey: ReturnType | undefined; try { const result = await DeviceAttestationValidator.validate( { crypto: this.fabric.crypto, dclCertificateService: attestation.dclCertificateService, attestationChallenge: attestation.challengeKey, }, { dac: deviceAttestation, pai: productAttestation, attestationElements, attestationSignature, attestationNonce, vendorId: this.collectedCommissioningData.vendorId!, productId: this.collectedCommissioningData.productId!, }, ); findings = result.findings; dacPublicKey = result.dacPublicKey; } catch (error) { // A cancellation (e.g. shutdown/close while the DCL service is consulted) must propagate // cleanly rather than be downgraded to an attestation finding. if (causedBy(error, CanceledError)) { throw error; } baseError = asError(error); if (error instanceof DeviceAttestationError) { findings = [{ level: "error", type: error.failure, message: error.message }]; } else { // Unexpected validation error (e.g. an unrecoverably corrupt trust-store certificate). // Surface it as an error finding so the onFailure policy can still judge it, instead of // hard-aborting commissioning outside the findings mechanism. findings = [ { level: "error", type: DeviceAttestationCheck.ValidationError, message: baseError.message }, ]; } } if (findings.length > 0) { const decision = await this.#resolveAttestationFindings(findings); if (!decision.proceed) { baseError ??= new CommissioningError( `Device attestation produced ${findings.length} finding(s) and was rejected by policy`, ); if (decision.reason !== undefined) { throw new CommissioningError(decision.reason, { cause: baseError }); } throw baseError; } logger.info(`Device attestation successfully verified with ${findings.length} accepted finding(s)`); } else { logger.info("Device attestation successfully verified"); } if (dacPublicKey === undefined) { // Attestation failed but policy accepted it, so the key the validator would have returned is missing try { dacPublicKey = PublicKey(Dac.fromAsn1(deviceAttestation).cert.ellipticCurvePublicKey); } catch (cause) { throw new CommissioningError( "Device attestation was accepted but the DAC cannot be parsed, so the CSR signature cannot be verified", { cause }, ); } } this.#dacPublicKey = dacPublicKey; return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } /** Resolve attestation findings according to the configured policy. */ async #resolveAttestationFindings(findings: AttestationFinding[]): Promise { const policy = this.commissioningOptions.attestation.onFailure; if (typeof policy === "function") { // Throws from the callback propagate to the caller unchanged. const result = await policy(findings); if (result === true) return { proceed: true }; if (typeof result === "string") return { proceed: false, reason: result }; return { proceed: false }; } for (const f of findings) { switch (policy) { case undefined: // TODO: Remove backward-compatible accept in next breaking version logger.warn("Attestation finding accepted for backward compatibility:", f.type, f.message); break; case true: logger.info("Attestation finding accepted by policy:", f.type, f.message); break; case false: logger.info("Attestation finding, rejecting:", f.type, f.message); break; } } return { proceed: policy !== false }; } // TODO consider Distributed Compliance Ledger Info about Commissioning Flow /** * Step 11-13 * 11: Following the Device Attestation Procedure yielding a decision to proceed with commissioning, the Commissioner * SHALL request operational CSR from Commissionee using the CSRRequest command (see Section 11.17.6.5, * “CSRRequest Command”). The CSRRequest command will cause the generation of a new operational key pair at the * Commissionee. * 12: Commissioner SHALL generate or otherwise obtain an Operational Certificate containing Operational ID after * receiving the CSRResponse command from the Commissionee (see Section 11.17.6.5, “CSRRequest Command”), using * implementation-specific means. * 13: Commissioner SHALL install operational credentials (see Figure 40, “Node Operational Credentials * flow”) on the Commissionee using the AddTrustedRootCertificate and AddNOC commands, * and SHALL use the UpdateFabricLabel command to set a string that the user can recognize and * relate to this Commissioner/Administrator. * The AdminVendorId field of the AddNOC command SHALL be set to a value for which the Vendor Schema in * DCL contains the name and other information of the Commissioner’s manufacturer. */ async #certificates() { const { nocsrElements, attestationSignature: csrSignature } = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: OperationalCredentials, command: "csrRequest", fields: { csrNonce: this.fabric.crypto.randomBytes(32) }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); if (nocsrElements.byteLength === 0 || csrSignature.byteLength === 0) { throw new UnexpectedDataError("Invalid response from device"); } // Verify CSR attestation signature using DAC public key (extracted in step 10) if (this.#dacPublicKey !== undefined) { try { await this.fabric.crypto.verifyEcdsa( this.#dacPublicKey, Bytes.concat(nocsrElements, this.commissioningOptions.attestation!.challengeKey), new EcdsaSignature(csrSignature), ); } catch { throw new CommissioningError("CSR signature verification failed against DAC public key"); } } const { certSigningRequest } = TlvCertSigningRequest.decode(nocsrElements); const operationalPublicKey = await Certificate.getPublicKeyFromCsr(this.ca.crypto, certSigningRequest); await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: OperationalCredentials, command: "addTrustedRootCertificate", fields: { rootCaCertificate: this.ca.rootCert, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); const peerOperationalCert = await this.ca.generateNoc( operationalPublicKey, this.fabric.fabricId, this.interaction.address.nodeId, ); const addNocResponse = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: OperationalCredentials, command: "addNoc", fields: { nocValue: peerOperationalCert, icacValue: this.ca.icacCert ?? new Uint8Array(0), ipkValue: this.fabric.identityProtectionKey, adminVendorId: this.fabric.rootVendorId, caseAdminSubject: this.fabric.rootNodeId, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); this.#ensureOperationalCredentialsSuccess("addNoc", addNocResponse); const { fabricIndex } = addNocResponse; this.collectedCommissioningData.fabricIndex = fabricIndex; return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } /** * Step 13-2 (we do as 99 at the end because) * The Administrator having established a CASE session with the Commissionee over the operational network in the * previous steps SHALL invoke the CommissioningComplete command (see Section 11.10.7.6, * “CommissioningComplete Command”). A success response after invocation of the CommissioningComplete command ends * the commissioning process. */ async #updateFabricLabel() { const { fabricIndex } = this.collectedCommissioningData; if (fabricIndex === undefined) { logger.error("No fabric index available after addNoc. This should never happen."); return { code: CommissioningStepResultCode.Failure, breadcrumb: this.lastBreadcrumb, }; } try { this.#ensureOperationalCredentialsSuccess( "updateFabricLabel", await this.#invokeCommand({ endpoint: RootEndpointNumber, cluster: OperationalCredentials, command: "updateFabricLabel", fields: { label: this.fabric.label, }, }), ); } catch (error) { throw repackErrorAs(error, RecoverableCommissioningError); } return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } /** * Step 15 * Commissioner MAY configure the Access Control List (see Access Control Cluster) on the Commissionee in any way * it sees fit, if the singular entry added by the AddNOC command in the previous step granting Administer * privilege over CASE authentication type for the Node ID provided with the command is not sufficient to express * its desired access control policies. */ async #configureAccessControlLists() { // Standard entry is enough in our case return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } /** * Step 16-17 * 16: If the Commissionee both supports it and requires it, the Commissioner SHALL configure the operational network * at the Commissionee using commands such as AddOrUpdateWiFiNetwork (see Section 11.9.7.3, “AddOrUpdateWiFiNetwork * Command”) and AddOrUpdateThreadNetwork (see Section 11.9.7.4, “AddOrUpdateThreadNetwork Command”). * A Commissionee requires network commissioning if it is not already on the desired operational network. * A Commissionee supports network commissioning if it has any NetworkCommissioning cluster instances. * A Commissioner MAY learn about the networks visible to the Commissionee using ScanNetworks command * (see Section 11.9.7.1, “ScanNetworks Command”). * 17: The Commissioner SHALL trigger the Commissionee to connect to the operational network using ConnectNetwork * command (see Section 11.9.7.8, “ConnectNetwork Command”) unless the Commissionee is already on the desired * operational network. */ async #validateNetwork() { if ( this.collectedCommissioningData.networkFeatures === undefined || this.collectedCommissioningData.networkStatus === undefined ) { throw new CommissioningError( "Initial information collection failed. No network features or status collected. This should never happen.", ); } if ( (this.commissioningOptions.wifiNetwork === undefined || !this.commissioningOptions.wifiNetwork.wifiSsid || !this.commissioningOptions.wifiNetwork.wifiCredentials) && (this.commissioningOptions.threadNetwork === undefined || !this.commissioningOptions.threadNetwork.operationalDataset) ) { // Check if we have no networkCommissioning cluster or an Ethernet one const anyEthernetInterface = this.collectedCommissioningData.networkFeatures.length === 0 || this.collectedCommissioningData.networkFeatures.some( ({ value: { ethernetNetworkInterface } }) => ethernetNetworkInterface === true, ); const anyInterfaceConnected = this.collectedCommissioningData.networkStatus.length === 0 || this.collectedCommissioningData.networkStatus.some(({ value }) => value.some(({ connected }) => connected), ); if (!anyEthernetInterface && !anyInterfaceConnected) { throw new WifiOrThreadNetworkCredentialsNotConfiguredError( "No Wi-Fi/Thread network credentials are configured for commissioning and no Ethernet interface is available on the device and no interface already connected.", ); } } return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } async #configureNetworkWifi() { if (this.commissioningOptions.wifiNetwork === undefined) { logger.debug("WiFi network is not configured"); return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } if ( this.collectedCommissioningData.networkFeatures !== undefined && this.collectedCommissioningData.networkStatus !== undefined ) { const rootNetworkFeatures = this.collectedCommissioningData.networkFeatures.find( ({ endpointId }) => endpointId === 0, )?.value; const rootNetworkStatus = this.collectedCommissioningData.networkStatus.find( ({ endpointId }) => endpointId === 0, )?.value; logger.debug( `Root Networks found: ${Diagnostic.json(rootNetworkFeatures)} - ${Diagnostic.json(rootNetworkStatus)}`, ); if (rootNetworkFeatures?.wiFiNetworkInterface !== true) { logger.debug("Commissionee does not support any WiFi network interface"); return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } if (rootNetworkStatus !== undefined && rootNetworkStatus.length > 0 && rootNetworkStatus[0].connected) { logger.debug("Commissionee is already connected to the WiFi network"); this.collectedCommissioningData.successfullyConnectedToNetwork = true; return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } } logger.debug("Configuring WiFi network ..."); const ssid = Bytes.fromString(this.commissioningOptions.wifiNetwork.wifiSsid); const credentials = Bytes.fromString(this.commissioningOptions.wifiNetwork.wifiCredentials); const [rawScanMaxTimeSeconds, rawConnectMaxTimeSeconds] = await this.#readConcreteAttributeValues( Read( Read.Attribute({ endpoint: RootEndpointNumber, cluster: NetworkCommissioning, attributes: ["scanMaxTimeSeconds", "connectMaxTimeSeconds"], }), ), ); // Enforce minimum 60s for scan/connect timeouts regardless of what the device reports const scanMaxTimeSeconds = Math.max(rawScanMaxTimeSeconds ?? 0, MIN_NETWORK_SCAN_TIMEOUT_SECONDS); const connectMaxTimeSeconds = Math.max(rawConnectMaxTimeSeconds ?? 0, MIN_NETWORK_CONNECT_TIMEOUT_SECONDS); // Only Scan when the device supports concurrent connections let wifiScanFailureHint: string | undefined; if (this.collectedCommissioningData.supportsConcurrentConnection !== false) { const scan = await this.#scanNetworks( { ssid, breadcrumb: this.lastBreadcrumb++ }, Seconds(scanMaxTimeSeconds), ); if (typeof scan === "string") { wifiScanFailureHint = `scan failed: ${scan}`; logger.warn( `WiFi network scan for "${this.commissioningOptions.wifiNetwork.wifiSsid}" failed: ${scan} - attempting connection anyway`, ); } else if (scan.networkingStatus !== NetworkCommissioning.NetworkCommissioningStatus.Success) { const { networkingStatus, debugText } = scan; wifiScanFailureHint = `scan failed: status=${NetworkCommissioning.NetworkCommissioningStatus[networkingStatus]} (${networkingStatus})${debugText ? `, ${debugText}` : ""}`; logger.warn( `WiFi network scan for "${this.commissioningOptions.wifiNetwork.wifiSsid}" returned status ${NetworkCommissioning.NetworkCommissioningStatus[networkingStatus]} (${networkingStatus})${debugText ? `: ${debugText}` : ""} - attempting connection anyway`, ); } else if (scan.wiFiScanResults === undefined || scan.wiFiScanResults.length === 0) { wifiScanFailureHint = `network not found in scan results`; logger.warn( `WiFi network "${this.commissioningOptions.wifiNetwork.wifiSsid}" not found in scan results - attempting connection anyway`, ); } } // The device may drop the (BLE) commissioning channel the moment its network is configured, // before connectNetwork — and once it is gone the failsafe can no longer be re-armed. Arm the // full connect + CASE reconnect window up front so an early drop still leaves time to reconnect. await this.#ensureFailsafeTimerFor(this.#connectNetworkFailsafeTime(connectMaxTimeSeconds)); const wifiNetwork = this.commissioningOptions.wifiNetwork; const addResult = await this.#withCommissioningChannelDropFallback(async () => { const { networkingStatus: addNetworkingStatus, debugText: addDebugText, networkIndex, } = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: NetworkCommissioning, command: "addOrUpdateWiFiNetwork", fields: { ssid, credentials, breadcrumb: this.lastBreadcrumb++, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); if (addNetworkingStatus !== NetworkCommissioning.NetworkCommissioningStatus.Success) { throw new WifiNetworkSetupFailedError( `Commissionee failed to add WiFi network "${wifiNetwork.wifiSsid}"${addDebugText ? `: ${addDebugText}` : ""}${wifiScanFailureHint !== undefined ? ` (${wifiScanFailureHint} - verify network name and availability)` : ""}`, ); } if (networkIndex === undefined) { throw new WifiNetworkSetupFailedError(`Commissionee did not return network index`); } logger.debug(`Commissionee added WiFi network ${wifiNetwork.wifiSsid} with network index ${networkIndex}`); const [updatedNetworks] = await this.#readConcreteAttributeValues( Read( Read.Attribute({ endpoint: RootEndpointNumber, cluster: NetworkCommissioning, attributes: ["networks"], }), ), ); if (updatedNetworks[networkIndex] === undefined) { throw new WifiNetworkSetupFailedError(`Commissionee did not return network with index ${networkIndex}`); } return updatedNetworks[networkIndex]; }); if (addResult.transportFailure) { return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } const { networkId, connected } = addResult.value; if (connected) { this.collectedCommissioningData.successfullyConnectedToNetwork = true; logger.debug( `Commissionee is already connected to WiFi network ${wifiNetwork.wifiSsid} (networkId ${Bytes.toHex(networkId)})`, ); return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } const connectResult = await this.#invokeConnectNetwork(networkId, connectMaxTimeSeconds); if (connectResult.transportFailure) { return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } if (connectResult.networkingStatus !== NetworkCommissioning.NetworkCommissioningStatus.Success) { throw new WifiNetworkSetupFailedError( `Commissionee failed to connect to WiFi network "${this.commissioningOptions.wifiNetwork.wifiSsid}"${connectResult.debugText ? `: ${connectResult.debugText}` : ""}${wifiScanFailureHint !== undefined ? ` (${wifiScanFailureHint} - verify network name and availability)` : ""}`, ); } this.collectedCommissioningData.successfullyConnectedToNetwork = true; logger.debug( `Commissionee successfully connected to WiFi network ${ this.commissioningOptions.wifiNetwork.wifiSsid } (networkId ${Bytes.toHex(networkId)})`, ); return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } async #configureNetworkThread() { if (this.collectedCommissioningData.successfullyConnectedToNetwork) { logger.info("Node is already connected to a network. Skipping Thread configuration."); return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } if (this.commissioningOptions.threadNetwork === undefined) { logger.debug("Thread network is not configured"); return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } if ( this.collectedCommissioningData.networkFeatures !== undefined && this.collectedCommissioningData.networkStatus !== undefined ) { const rootNetworkFeatures = this.collectedCommissioningData.networkFeatures.find( ({ endpointId }) => endpointId === 0, )?.value; const rootNetworkStatus = this.collectedCommissioningData.networkStatus.find( ({ endpointId }) => endpointId === 0, )?.value; logger.debug( `Root Networks found: ${Diagnostic.json(rootNetworkFeatures)} - ${Diagnostic.json(rootNetworkStatus)}`, ); if (rootNetworkFeatures?.threadNetworkInterface !== true) { logger.debug("Commissionee does not support any Thread network interface"); return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } if (rootNetworkStatus !== undefined && rootNetworkStatus.length > 0 && rootNetworkStatus[0].connected) { logger.debug("Commissionee is already connected to the Thread network"); return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } } const networkName = resolveThreadNetworkName(this.commissioningOptions.threadNetwork); logger.debug("Configuring Thread network ..."); const [rawScanMaxTimeSeconds, rawConnectMaxTimeSeconds] = await this.#readConcreteAttributeValues( Read( Read.Attribute({ endpoint: RootEndpointNumber, cluster: NetworkCommissioning, attributes: ["scanMaxTimeSeconds", "connectMaxTimeSeconds"], }), ), ); // Enforce minimum 60s for scan/connect timeouts regardless of what the device reports const scanMaxTimeSeconds = Math.max(rawScanMaxTimeSeconds ?? 0, MIN_NETWORK_SCAN_TIMEOUT_SECONDS); const connectMaxTimeSeconds = Math.max(rawConnectMaxTimeSeconds ?? 0, MIN_NETWORK_CONNECT_TIMEOUT_SECONDS); let threadScanFailureHint: string | undefined; if (!networkName) { logger.info("Thread network name is not configured. Skip scanning for it."); } else if (this.collectedCommissioningData.supportsConcurrentConnection !== false) { // Only Scan when the device supports concurrent connections const scan = await this.#scanNetworks({ breadcrumb: this.lastBreadcrumb++ }, Seconds(scanMaxTimeSeconds)); if (typeof scan === "string") { threadScanFailureHint = `scan failed: ${scan}`; logger.warn(`Thread network scan failed: ${scan} - attempting connection anyway`); } else if (scan.networkingStatus !== NetworkCommissioning.NetworkCommissioningStatus.Success) { const { networkingStatus, debugText } = scan; threadScanFailureHint = `scan failed: status=${NetworkCommissioning.NetworkCommissioningStatus[networkingStatus]} (${networkingStatus})${debugText ? `, ${debugText}` : ""}`; logger.warn( `Thread network scan returned status ${NetworkCommissioning.NetworkCommissioningStatus[networkingStatus]} (${networkingStatus})${debugText ? `: ${debugText}` : ""} - attempting connection anyway`, ); } else if (scan.threadScanResults === undefined || scan.threadScanResults.length === 0) { threadScanFailureHint = `no Thread networks found in scan results`; logger.warn( `Thread network scan returned no results for "${networkName}" - attempting connection anyway`, ); } else { const wantedNetworkFound = scan.threadScanResults.find( ({ networkName: scanned }) => scanned === networkName, ); if (wantedNetworkFound === undefined) { threadScanFailureHint = `network "${networkName}" not found in scan results`; logger.warn( `Thread network "${networkName}" not found in scan results: ${Diagnostic.json(scan.threadScanResults)} - attempting connection anyway`, ); } else { logger.debug( `Commissionee found wanted Thread network ${networkName}: ${Diagnostic.json(wantedNetworkFound)}`, ); } } } // The device may drop the (BLE) commissioning channel the moment its network is configured, // before connectNetwork — and once it is gone the failsafe can no longer be re-armed. Arm the // full connect + CASE reconnect window up front so an early drop still leaves time to reconnect. await this.#ensureFailsafeTimerFor(this.#connectNetworkFailsafeTime(connectMaxTimeSeconds)); const threadNetwork = this.commissioningOptions.threadNetwork; const addResult = await this.#withCommissioningChannelDropFallback(async () => { const { networkingStatus: addNetworkingStatus, debugText: addDebugText, networkIndex, } = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: NetworkCommissioning, command: "addOrUpdateThreadNetwork", fields: { operationalDataset: Bytes.fromHex(threadNetwork.operationalDataset), breadcrumb: this.lastBreadcrumb++, }, }, { useExtendedFailSafeMessageResponseTimeout: true, }, ); if (addNetworkingStatus !== NetworkCommissioning.NetworkCommissioningStatus.Success) { throw new ThreadNetworkSetupFailedError( `Commissionee failed to add Thread network: status=${NetworkCommissioning.NetworkCommissioningStatus[addNetworkingStatus]} (${addNetworkingStatus})${addDebugText ? `, ${addDebugText}` : ""}${threadScanFailureHint !== undefined ? ` (${threadScanFailureHint} - verify network name and availability)` : ""}`, ); } if (networkIndex === undefined) { throw new ThreadNetworkSetupFailedError(`Commissionee did not return network index`); } logger.debug( `Commissionee added Thread network ${networkName ?? "via operational dataset"} with network index ${networkIndex}`, ); const [updatedNetworks] = await this.#readConcreteAttributeValues( Read( Read.Attribute({ endpoint: RootEndpointNumber, cluster: NetworkCommissioning, attributes: ["networks"], }), ), ); if (updatedNetworks[networkIndex] === undefined) { throw new ThreadNetworkSetupFailedError( `Commissionee did not return network with index ${networkIndex}`, ); } return updatedNetworks[networkIndex]; }); if (addResult.transportFailure) { return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } const { networkId, connected } = addResult.value; if (connected) { logger.debug( `Commissionee is already connected to Thread network ${ threadNetwork.networkName ?? "via operational dataset" } (networkId ${Bytes.toHex(networkId)})`, ); return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } const connectResult = await this.#invokeConnectNetwork(networkId, connectMaxTimeSeconds); if (connectResult.transportFailure) { return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } const { networkingStatus, debugText } = connectResult; if (networkingStatus !== NetworkCommissioning.NetworkCommissioningStatus.Success) { throw new ThreadNetworkSetupFailedError( `Commissionee failed to connect to Thread network: status=${NetworkCommissioning.NetworkCommissioningStatus[networkingStatus]} (${networkingStatus})${debugText ? `, ${debugText}` : ""}${threadScanFailureHint !== undefined ? ` (${threadScanFailureHint} - verify network name and availability)` : ""}`, ); } logger.debug( `Commissionee successfully connected to Thread network ${ this.commissioningOptions.threadNetwork.networkName ?? "via operational dataset" } (networkId ${Bytes.toHex(networkId)})`, ); return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } /** * Invokes ScanNetworks on the root endpoint. The scan result only feeds diagnostic hints into later network setup * errors, so as with the CHIP SDK commissioner a failed scan does not abort commissioning: the device rejecting the * command with an Interaction Model status, answering without a ScanNetworksResponse, or not answering in time. * Any other failure is rethrown. * * @returns the ScanNetworksResponse, or a description of why there is none */ async #scanNetworks( fields: NetworkCommissioning.ScanNetworksRequest, scanTime: Duration, ): Promise { await this.#ensureFailsafeTimerFor(scanTime); let response: NetworkCommissioning.ScanNetworksResponse | undefined; try { response = await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: NetworkCommissioning, command: "scanNetworks", fields }, { expectedProcessingTime: scanTime }, ); } catch (error) { if (error instanceof StatusResponseError) { return error.message; } const missingResponse = PeerMessageMissingError.of(error); if (missingResponse !== undefined) { return missingResponse.message; } throw error; } return response ?? "no ScanNetworksResponse received"; } /** * Step 18-19 * 18: Finalization of the Commissioning process begins. An Administrator configured in the ACL of the Commissionee * by the Commissioner SHALL use Operational Discovery to discover the Commissionee. This Administrator MAY be * the Commissioner itself, or another Node to which the Commissioner has delegated the task. * 19: The Administrator SHALL open a CASE (see Section 4.14.2, “Certificate Authenticated Session Establishment * (CASE)”) session with the Commissionee over the operational network. */ async #reconnectWithDevice() { const isConcurrentFlow = this.collectedCommissioningData.supportsConcurrentConnection !== false; logger.debug(`Reconnecting with device with ${isConcurrentFlow ? "concurrent" : "non-concurrent"} flow ...`); // Reconnection with discovery could take longer than the default failsafe time, so we need to // re-arm the failsafe when we are in a concurrent commissioning flow also in parallel to // the operative reconnection. // For non-concurrent flow the BLE connection already dropped when connectNetwork was sent // (step 16/17), so we cannot re-arm here — the failsafe was armed for long enough before // that step. For concurrent flow the BLE session is still alive, so try to extend it. if (isConcurrentFlow) { try { await this.#ensureFailsafeTimerFor(CASE_RECONNECT_TIMEOUT); } catch (error) { // Ignore errors on PASE actions, either way CASE success/failure decides the outcome, not this re-arm. logger.info("Failed to re-arm failsafe before operational reconnect, proceeding anyway", error); } } else { this.#armFailsafeInterval?.stop(); } let transitionResult: ClientInteraction | undefined; try { transitionResult = await this.transitionToCase( this.interaction.address, // Assume concurrent connections are supported if not know (which should not be the case when we came here) isConcurrentFlow, ); } catch (cause) { throw new OperativeConnectionFailedError("Operative reconnection with device failed", { cause }); } finally { this.#armFailsafeInterval?.stop(); } if (transitionResult === undefined) { logger.debug("CASE commissioning handled externally, terminating commissioning flow"); return { code: CommissioningStepResultCode.Stop, breadcrumb: this.lastBreadcrumb, }; } await this.interaction.close(); this.interaction = transitionResult; logger.debug("Successfully reconnected with device ..."); return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } /** * Step 20 * The Administrator having established a CASE session with the Commissionee over the operational network in the * previous steps SHALL invoke the CommissioningComplete command (see Section 11.10.7.6, * “CommissioningComplete Command”). A success response after invocation of the CommissioningComplete command ends * the commissioning process. */ async #completeCommissioning() { this.#ensureGeneralCommissioningSuccess( "commissioningComplete", await this.#invokeCommand( { endpoint: RootEndpointNumber, cluster: GeneralCommissioning, command: "commissioningComplete", }, { useExtendedFailSafeMessageResponseTimeout: true, }, ), ); this.#currentFailSafeEndTime = undefined; // gets deactivated when successful return { code: CommissioningStepResultCode.Success, breadcrumb: this.lastBreadcrumb, }; } async #addDefaultOtaProvider() { if (this.commissioningOptions.otaUpdateProviderLocation === undefined) { return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } if (!this.collectedCommissioningData?.otaRequestorList?.length) { logger.debug("No OTA Requestor found, skipping adding default OTA provider"); return { code: CommissioningStepResultCode.Skipped, breadcrumb: this.lastBreadcrumb, }; } const { nodeId: providerNodeId, endpoint } = this.commissioningOptions.otaUpdateProviderLocation; let success = false; for (const requestorEndpoint of this.collectedCommissioningData.otaRequestorList) { try { // Fabric scoped attribute, so we just overwrite our value const writeResult = await this.interaction.write( Write( Write.Attribute({ endpoint: requestorEndpoint, cluster: OtaSoftwareUpdateRequestor, attributes: ["defaultOtaProviders"], value: [ { providerNodeId, endpoint, fabricIndex: this.fabric.fabricIndex, }, ], }), ), ); WriteResult.assertSuccess(writeResult); success = true; logger.debug(`Added default OTA provider on endpoint ${endpoint}`); } catch (error) { // Ok to just log, we will check again also in the SoftwareUpdateManager logger.info("Could not set default OTA provider", error); } } return { code: success ? CommissioningStepResultCode.Success : CommissioningStepResultCode.Failure, breadcrumb: this.lastBreadcrumb, }; } close() { this.#armFailsafeInterval?.stop(); } }