/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { ClientInteraction } from "#action/client/ClientInteraction.js"; import { BleChannel, BleChannelClosedError } from "#ble/Ble.js"; import { CertificateAuthority } from "#certificate/CertificateAuthority.js"; import { DeviceAttestationValidator } from "#certificate/DeviceAttestationValidator.js"; import { CommissionableDevice, DiscoveryData, DiscoveryDataDiagnostics, ScannerSet } from "#common/Scanner.js"; import { Fabric } from "#fabric/Fabric.js"; import { CommissioningConnection } from "#peer/CommissioningConnection.js"; import { CommissioningError, PairRetransmissionLimitReachedError } from "#peer/CommissioningError.js"; import { ControllerCommissioningFlow, ControllerCommissioningFlowOptions, NodeIdConflictError, } from "#peer/ControllerCommissioningFlow.js"; import { ExchangeManager } from "#protocol/ExchangeManager.js"; import { DedicatedChannelExchangeProvider } from "#protocol/ExchangeProvider.js"; import { ChannelStatusResponseError } from "#securechannel/SecureChannelMessenger.js"; import { NodeSession } from "#session/NodeSession.js"; import { PaseClient } from "#session/pase/PaseClient.js"; import { SessionManager } from "#session/SessionManager.js"; import { SessionParameters } from "#session/SessionParameters.js"; import { Abort, asError, Bytes, causedBy, Channel, ChannelType, ClassExtends, Duration, Environment, Environmental, ImplementationError, isIPv6, Logger, MaybePromise, Millis, NoResponseTimeoutError, Seconds, ServerAddress, ServerAddressSet, TransportSet, } from "@matter/general"; import { FabricIndex, NodeId, SECURE_CHANNEL_PROTOCOL_ID, SecureChannelStatusCode } from "@matter/types"; import { GeneralCommissioning } from "@matter/types/clusters/general-commissioning"; import { DclCertificateService } from "../dcl/DclCertificateService.js"; import { PeerAddress } from "./PeerAddress.js"; import { CommissioningTransitionError, PeerCommunicationError } from "./PeerCommunicationError.js"; import { PeerSet } from "./PeerSet.js"; import { PeerTimingParameters } from "./PeerTimingParameters.js"; const logger = Logger.get("ControllerCommissioner"); /** * General commissioning options. */ export interface CommissioningOptions extends Partial { /** Controls behavior when device attestation produces findings. */ onAttestationFailure?: DeviceAttestationValidator.OnAttestationFailure; /** The fabric into which to commission. */ fabric: Fabric; /** The node ID to assign (the commissioner assigns a random node ID if omitted) */ nodeId?: NodeId; /** Passcode to use for commissioning. */ passcode: number; /** * Commissioning completion callback * * This optional callback allows the caller to complete commissioning once PASE commissioning completes. If it does * not throw, the commissioner considers commissioning complete. `sessionParameters` are those the device reported * over PASE; whoever establishes the operational CASE session should use them. */ finalizeCommissioning?: ( peerAddress: PeerAddress, discoveryData?: DiscoveryData, sessionParameters?: Partial, ) => MaybePromise; /** * Commissioning Flow Implementation as class that extends the official implementation to use for commissioning. * Defaults to the matter.js default implementation {@link ControllerCommissioningFlow}. */ commissioningFlowImpl?: ClassExtends; /** * Timing overrides for the step-18 CASE reconnect. * * After commissioning completes, the commissioner establishes the first operational CASE session. The device is * known to be freshly online at this point, so tighter timing is appropriate. Any fields provided here are merged * on top of the global {@link PeerSet.timing} for that single connection only. */ caseConnectionTiming?: Partial; /** * Wall-clock budget for the step-18 CASE reconnect, across every candidate address and retry. * * Defaults to {@link DEFAULT_CASE_CONNECTION_TIMEOUT}. Lower it to bound commissioning to a single handshake * attempt, so a handshake the device fails is a commissioning failure rather than something a retry can recover. * * On an IP transport, raising it past the failsafe armed for this step (`ControllerCommissioningFlow` allows up to * 5 minutes for the reconnect, clamped by the device's own `MaxCumulativeFailsafeSeconds`) has the device roll * `addNOC` back mid-connect, so a longer budget cannot succeed. The concurrent BLE flow keeps re-arming instead. * * Expiry fails commissioning, which deletes the peer and so aborts the connection it was still attempting. The * rejection therefore reports a budget that ran out, not what the device answered. No effect where * {@link finalizeCommissioning} owns the operational step instead. */ caseConnectionTimeout?: Duration; } /** * 4m15s allows two ~2-minute server-side retry windows to complete before we abort. */ export const DEFAULT_CASE_CONNECTION_TIMEOUT = Seconds(255); /** * {@link DiscoveryData} of a device to commission. A non-empty `deviceIdentifier` marks the addresses as those of one * discovered device instance, so a wrong passcode on one of them stops the attempts on the others. */ export type CommissioningDiscoveryData = DiscoveryData & { deviceIdentifier?: string }; /** * Configuration for commissioning a previously discovered node. */ export interface LocatedNodeCommissioningOptions extends CommissioningOptions { /** * Addresses of the one node to commission. They are tried one after the other, ordered by * {@link ServerAddressSet.compareDesirability} (see {@link CommissioningConnection}). */ addresses: ServerAddress[]; /** Discovery metadata of the device. */ discoveryData?: CommissioningDiscoveryData; /** * Overall wall-clock budget for PASE establishment across all candidate addresses. * Defaults to 30 seconds. */ timeout?: Duration; /** * Abort signal for cancellation. When fired during PASE establishment, cancels the attempt. * In parallel commissioning scenarios this is used to cancel other candidates once one wins. */ abort?: AbortSignal; /** * Called immediately after PASE is established, before the main commissioning flow begins. * * Returns the {@link NodeId} to assign this device, reserved at win-time so the operational identity is * claimed only once a candidate has won the PASE race. Returns `undefined` to abort — the PASE session is * closed and commissioning is skipped. * * This is the hook used by {@link CommissioningDiscovery} for multi-candidate parallel flows: the first * candidate to establish PASE claims and returns its node ID (and signals the others via {@link abort} to * stop). Any candidate that establishes PASE after another has already won returns `undefined` here and * cleans up. In the single-device located-node path this callback is unnecessary; provide {@link nodeId} * (or leave it undefined for an automatically assigned ID) instead. */ claimNodeIdAfterPase?: () => MaybePromise; } /** * Options for establishing a PASE session with a device whose address(es) are already known. * * Use this when you have at least one address for the device (from a prior discovery, a QR code, or a * pre-configured address). For pure mDNS/BLE discovery without known addresses, use {@link PaseDiscovery}. */ export interface EstablishPaseOptions { /** * One or more addresses at which the device may be reached. They are tried one after the other, ordered by * {@link ServerAddressSet.compareDesirability} (see {@link CommissioningConnection}). */ addresses: ServerAddress[]; /** Discovery metadata of the device. */ discoveryData?: CommissioningDiscoveryData; /** PASE passcode for the device. */ passcode: number; /** Overall timeout for PASE establishment across all addresses. Defaults to 30 seconds. */ timeout?: Duration; /** External abort signal that, when fired, cancels all in-flight PASE attempts. */ abort?: AbortSignal; /** * Atomic gate for parallel PASE racing. * * Called immediately after PASE is established (before any further work). Return `true` to claim this * PASE session as the winner. Return `false` if another candidate already won — this session is closed * cleanly without proceeding. * * When omitted, the first successful PASE session is always accepted. */ continueAfterPase?: () => boolean; } /** Result returned by {@link ControllerCommissioner.establishPase}. */ export interface EstablishPaseResult { paseSession: NodeSession; discoveryData?: DiscoveryData; } /** * Interfaces {@link ControllerCommissioner} with other components. */ export interface ControllerCommissionerContext { peers: PeerSet; transports: TransportSet; sessions: SessionManager; exchanges: ExchangeManager; ca: CertificateAuthority; environment: Environment; } /** * Commissions other nodes onto a fabric. */ export class ControllerCommissioner { #context: ControllerCommissionerContext; #paseClient: PaseClient; constructor(context: ControllerCommissionerContext) { this.#context = context; this.#paseClient = new PaseClient(context.sessions); } static [Environmental.create](env: Environment) { const instance = new ControllerCommissioner({ peers: env.get(PeerSet), transports: env.get(TransportSet), sessions: env.get(SessionManager), exchanges: env.get(ExchangeManager), ca: env.get(CertificateAuthority), environment: env, }); env.set(ControllerCommissioner, instance); return instance; } /** * Commission a previously discovered node. */ async commission(options: LocatedNodeCommissioningOptions): Promise { const { passcode, addresses, discoveryData, fabric, nodeId, abort, claimNodeIdAfterPase, timeout = Seconds(30), } = options; this.#assertRequestedNodeIdAvailable(fabric, nodeId); this.#validateCommissioningOptions(options); const addressCandidates = this.#addressesToCandidates(addresses, discoveryData); const { session } = await this.#establishPaseFromCandidates({ devices: addressCandidates, timeout, passcode, retryFailureAsPeerCommunication: "Could not connect to device", abort, // This method ends the PASE session on every path suppressPeerLoss: true, }); try { // Claim the operational identity only after PASE; undefined means another candidate already won the race let assignedNodeId = nodeId; if (claimNodeIdAfterPase !== undefined) { assignedNodeId = await claimNodeIdAfterPase(); if (assignedNodeId === undefined) { throw new CommissioningError( "Commissioning cancelled: another device was already successfully connected", ); } } const result = await this.#commissionConnectedNode( session, { ...options, nodeId: assignedNodeId }, discoveryData, ); await this.#closePaseSession( session, new CommissioningTransitionError("Commissioning over PASE completed"), ); return result; } catch (error) { await this.#closePaseSession(session, asError(error)); throw error; } } /** * Ends the PASE session without masking the error that ended commissioning. */ async #closePaseSession(session: NodeSession, cause: Error) { try { await session.initiateForceClose({ cause }); } catch (error) { logger.warn("Error closing PASE session", error); } } /** * A commissioned device closes its commissioning window, but a scanner may still hold the advertisement that * opened it, and a later discovery by short discriminator matches many devices. */ #forgetCommissionedDevice(addresses: ServerAddress[], discoveryData?: DiscoveryData) { const environment = this.#context.environment; if (!environment.has(ScannerSet)) { return; } const identity = discoveryData?.D !== undefined && discoveryData.VP !== undefined ? { D: discoveryData.D, VP: discoveryData.VP } : undefined; for (const scanner of environment.get(ScannerSet)) { try { scanner.forgetCommissionedDevice?.(addresses, identity); } catch (error) { // The device is commissioned either way, so a scanner's bookkeeping must not fail the commissioning logger.warn(`Error forgetting commissioned device in ${scanner.type} scanner:`, error); } } } /** * Establishes a PASE session with a known device without running a commissioning flow. * * The addresses are tried one after the other, most desirable first (see {@link EstablishPaseOptions.addresses}). * The first to complete PASE wins; the rest are cancelled via an abort signal. A wrong passcode * (`PasscodeMismatchError`) stops the remaining addresses when they belong to one discovered device (see * {@link EstablishPaseOptions.discoveryData}); otherwise it fails only the address it occurred on. */ async establishPase(options: EstablishPaseOptions): Promise { const { addresses, discoveryData, passcode, timeout = Seconds(30), abort, continueAfterPase } = options; const candidates = this.#addressesToCandidates(addresses, discoveryData); const { session } = await this.#establishPaseFromCandidates({ devices: candidates, timeout, passcode, retryFailureAsPeerCommunication: "Could not connect to device", abort, }); // Check with the caller whether to proceed with this session. In parallel PASE scenarios this callback // atomically determines the winner: the first call returns true; any subsequent call returns false and // we clean up this session cleanly. if (continueAfterPase !== undefined && !continueAfterPase()) { await session.initiateForceClose({ cause: new CommissioningError("PASE established but another candidate already won"), }); throw new CommissioningError("PASE cancelled: another candidate was already selected"); } return { paseSession: session, discoveryData }; } async #establishPaseFromCandidates(options: { devices: CommissionableDevice[]; timeout: Duration; passcode: number; retryFailureAsPeerCommunication?: string; abort?: AbortSignal; suppressPeerLoss?: boolean; }) { try { return await CommissioningConnection({ devices: options.devices, timeout: options.timeout, externalAbort: options.abort, establishSession: (address, device, { signal, onPbkdfParamResponse }) => this.#establishEphemeralNodeSession( address, options.passcode, device, signal, options.suppressPeerLoss, onPbkdfParamResponse, ), }); } catch (error) { if ( options.retryFailureAsPeerCommunication !== undefined && causedBy(error, PairRetransmissionLimitReachedError) ) { throw new PeerCommunicationError(options.retryFailureAsPeerCommunication); } throw error; } } /** A wrong passcode throws {@link PasscodeMismatchError}. */ async #establishEphemeralNodeSession( address: ServerAddress, passcode: number, device?: DiscoveryData, signal?: AbortSignal, suppressPeerLoss?: boolean, onPbkdfParamResponse?: () => void, ): Promise { let paseChannel: Channel; if (device !== undefined) { logger.info(`Establish PASE to device`, DiscoveryDataDiagnostics(device)); } if (ServerAddress.isIp(address)) { // PASE always uses UDP — even if address was discovered with TCP type const { ip } = address; const isIpv6Address = isIPv6(ip); const paseInterface = this.#context.transports.interfaceFor( ChannelType.UDP, isIpv6Address ? "::" : "0.0.0.0", ); if (paseInterface === undefined) { throw new PairRetransmissionLimitReachedError( `IPv${isIpv6Address ? "6" : "4"} interface not initialized. Cannot use ${ip} for commissioning.`, ); } paseChannel = await Abort.attempt(signal, paseInterface.openChannel(address)); } else if (ServerAddress.isBle(address)) { const ble = this.#context.transports.interfaceFor(ChannelType.BLE); if (!ble) { throw new PairRetransmissionLimitReachedError( `BLE interface not initialized. Cannot use ${address.peripheralAddress} for commissioning.`, ); } paseChannel = await Abort.attempt(signal, ble.openChannel(address, { abort: signal })); } else { throw new ImplementationError(`Unsupported address type for Matter PASE commissioning`); } // Do PASE pairing const unsecuredSession = this.#context.sessions.createUnsecuredSession({ channel: paseChannel, // Use the session parameters from MDNS announcements when available and rest is assumed to be fallbacks sessionParameters: { idleInterval: Millis(device?.SII), activeInterval: Millis(device?.SAI), activeThreshold: Millis(device?.SAT), }, isInitiator: true, }); const paseExchange = this.#context.exchanges.initiateExchangeForSession( unsecuredSession, SECURE_CHANNEL_PROTOCOL_ID, ); try { const caseSession = await this.#paseClient.pair( this.#context.sessions.sessionParameters, paseExchange, paseChannel, passcode, { abort: signal, suppressPeerLoss, onPbkdfParamResponse }, ); await unsecuredSession.detachChannel()?.release(); return caseSession; } catch (e) { // Close the exchange and rethrow if (causedBy(e, ChannelStatusResponseError)) { throw new NoResponseTimeoutError( `Establishing PASE channel failed with channel status response error ${asError(e).message}`, ); } throw e; } finally { await unsecuredSession.initiateForceClose({ cause: new CommissioningTransitionError("PASE session has transitioned to CASE"), }); } } /** Validate if a Peer Address is already known and commissioned */ #assertPeerAddress(address: PeerAddress) { if (this.#context.peers.has(address)) { throw new NodeIdConflictError(`Node ID ${address.nodeId} is already commissioned and can not be reused`); } } #assertRequestedNodeIdAvailable(fabric: Fabric, nodeId?: NodeId) { if (nodeId !== undefined) { this.#assertPeerAddress(fabric.addressOf(nodeId)); } } #validateCommissioningOptions(options: CommissioningOptions) { // Nothing else bounds the post-PASE flow, and the device's failsafe expires regardless, so an unbounded budget // could only wait for a commissioning the device has already rolled back. const { caseConnectionTimeout } = options; if (caseConnectionTimeout !== undefined && !Number.isFinite(caseConnectionTimeout)) { throw new ImplementationError( `caseConnectionTimeout must be finite, not ${Duration.format(caseConnectionTimeout)}`, ); } if (options.threadNetwork !== undefined) { const { operationalDataset } = options.threadNetwork; if (operationalDataset.length === 0) { throw new CommissioningError("Thread operational dataset must not be empty"); } if (operationalDataset.length % 2 !== 0) { throw new CommissioningError("Thread operational dataset must have an even number of hex characters"); } if (!/^[0-9a-fA-F]+$/.test(operationalDataset)) { throw new CommissioningError( "Thread operational dataset must only contain valid hexadecimal characters", ); } } if (options.wifiNetwork !== undefined) { const { wifiSsid } = options.wifiNetwork; if (wifiSsid.length === 0) { throw new CommissioningError("Wi-Fi SSID must not be empty"); } } } /** * Maps addresses to synthetic {@link CommissionableDevice} candidates, ordered by * {@link ServerAddressSet.compareDesirability}; equally ranked addresses keep the given order. * * Addresses of one discovered device instance form one candidate, so a wrong passcode on one address stops the * others. Otherwise each distinct address becomes its own candidate: an address may be stale and reach a * different device, whose passcode check must not cancel the attempts on the others. */ #addressesToCandidates( addresses: ServerAddress[], discoveryData?: CommissioningDiscoveryData, ): CommissionableDevice[] { const distinct = new Map(addresses.map(address => [ServerAddress.urlFor(address), address])); const sorted = [...distinct.values()].sort(ServerAddressSet.compareDesirability); const deviceIdentifier = discoveryData?.deviceIdentifier; if (deviceIdentifier !== undefined && deviceIdentifier !== "") { return [{ ...discoveryData, addresses: sorted, deviceIdentifier, D: discoveryData?.D ?? 0, CM: 1 }]; } return sorted.map((address, index) => ({ ...(discoveryData ?? {}), addresses: [address], deviceIdentifier: `known-address-${index}-${ServerAddress.urlFor(address)}`, D: discoveryData?.D ?? 0, CM: 1, })); } /** Finds an unused random Node-ID to use for commissioning if not already provided. */ #determineAddress(fabric: Fabric, nodeId?: NodeId) { while (true) { const address = fabric.addressOf(nodeId ?? NodeId.randomOperationalNodeId(fabric.crypto)); try { this.#assertPeerAddress(address); } catch (error) { if (error instanceof CommissioningError && nodeId !== undefined) { throw error; } continue; } return address; } } /** * Method to commission a device with a PASE secure channel. It returns the NodeId of the commissioned device on * success. */ async #commissionConnectedNode( ephemeralSession: NodeSession, options: LocatedNodeCommissioningOptions, discoveryData?: DiscoveryData, ): Promise { const { fabric, finalizeCommissioning: performCaseCommissioning, commissioningFlowImpl = ControllerCommissioningFlow, caseConnectionTiming, caseConnectionTimeout = DEFAULT_CASE_CONNECTION_TIMEOUT, } = options; const commissioningOptions = { ...options, regulatoryLocation: options.regulatoryLocation ?? GeneralCommissioning.RegulatoryLocationType.Outdoor, regulatoryCountryCode: options.regulatoryCountryCode ?? "XX", }; // TODO Depending on the Error type during commissioning we can do a retry ... /* Whenever the Fail-Safe timer is armed, Commissioners and Administrators SHALL NOT consider any cluster operation to have timed-out before waiting at least 30 seconds for a valid response from the cluster server. Some commands and attributes with complex side-effects MAY require longer and have specific timing requirements stated in their respective cluster specification. 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. In non-concurrent connection commissioning flow, the failure of any of the steps 2 through 15 SHALL result in the Commissioner and Commissionee returning to step 2 (device discovery and commissioning channel establishment) and repeating each step. 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. In both concurrent connection commissioning flow and non-concurrent connection commissioning flow, the Commissionee SHALL exit Commissioning Mode after 20 failed attempts. */ const address = this.#determineAddress(fabric, commissioningOptions.nodeId); logger.info(`Start commissioning of node ${address.toString()} into fabric ${fabric.fabricId}`); const exchangeProvider = new DedicatedChannelExchangeProvider(this.#context.exchanges, ephemeralSession); // BLE-only: BTP MRP retrans blocks pending invokes for ~45s when a non-concurrent device // drops BLE after connectNetwork. Force-close on BLE-lost so the awaited invoke rejects // immediately and the commissioning flow can flip to the non-concurrent CASE path. if (!ephemeralSession.isClosed) { const paseChannel = ephemeralSession.channel.transportChannel; if (paseChannel instanceof BleChannel) { paseChannel.closed.once(() => { ephemeralSession .initiateForceClose({ cause: new BleChannelClosedError(`BLE transport closed on ${ephemeralSession.via}`), }) .catch(error => logger.warn("Error while force-closing PASE session on BLE close", error)); }); } } await using commissioner = new commissioningFlowImpl( new ClientInteraction({ environment: this.#context.environment, exchangeProvider, address, }), this.#context.ca, fabric, { ...commissioningOptions, attestation: { challengeKey: ephemeralSession.attestationChallengeKey, dclCertificateService: this.#context.environment.has(DclCertificateService) ? this.#context.environment.get(DclCertificateService) : undefined, onFailure: options.onAttestationFailure, }, }, async (address, supportsConcurrentConnections) => { if (!supportsConcurrentConnections) { /* In non-concurrent connection commissioning flow the commissioning channel SHALL terminate after successful step 12 (trigger joining of operational network at Commissionee). */ // We've reconnected using CASE so close the ephemeral node ID session await this.#closePaseSession( ephemeralSession, new CommissioningTransitionError( "Commissioning session closed because node has now joined fabric", ), ); } if (performCaseCommissioning !== undefined) { await performCaseCommissioning(address, discoveryData, ephemeralSession.reportedParameters); return; } const peer = this.#context.peers.for(address); peer.descriptor.discoveryData = discoveryData; // PASE already negotiated the device's session parameters; seed them so the initial operational CASE // transport decision (e.g. the TCP spec-version gate) has the device's spec version available. peer.descriptor.reportedSessionParameters = ephemeralSession.reportedParameters; await peer.connect({ connectionTimeout: caseConnectionTimeout, timing: caseConnectionTiming, handleError: error => { const csre = ChannelStatusResponseError.of(error); if (csre?.protocolStatusCode === SecureChannelStatusCode.NoSharedTrustRoots) { // During commissioning the device may not yet recognize the fabric; retry quickly logger.warn("Peer reports no shared trust roots during commissioning, retrying quickly"); return Seconds(15); } }, }); return new ClientInteraction({ environment: this.#context.environment, exchangeProvider: peer.exchangeProvider, address, }); }, ); let fabricIndexOnPeer: FabricIndex | undefined; try { await commissioner.executeCommissioning(); // The device's commissioning window is closed now, whatever fails after this point this.#forgetCommissionedDevice(options.addresses, discoveryData); const captured = commissioner.fabricIndexOnPeer; // Treat the spec-invalid NO_FABRIC (0) as "unknown" so callers don't have to filter it again. fabricIndexOnPeer = captured === FabricIndex.NO_FABRIC ? undefined : captured; } catch (error) { // We might have added data for an operational address that we need to cleanup await this.#context.peers.get(address)?.delete(); throw error; } finally { commissioner.close(); } return { address, fabricIndexOnPeer }; } } /** Result of a successful commissioning operation. */ export interface CommissionResult { /** Controller-side {@link PeerAddress} (interned). */ address: PeerAddress; /** Fabric index the peer assigned to our identity, from the AddNoc response. */ fabricIndexOnPeer?: FabricIndex; }