/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { FabricManager } from "#fabric/FabricManager.js"; import { ExchangeManager } from "#protocol/ExchangeManager.js"; import { NodeSession } from "#session/NodeSession.js"; import { SessionManager } from "#session/SessionManager.js"; import { AsyncObservable, Environment, Environmental, Logger, MatterFlowError } from "@matter/general"; import { GeneralStatusCode, SECURE_CHANNEL_PROTOCOL_ID, SecureChannelStatusCode, SecureMessageType, Status, StatusResponseError, } from "@matter/types"; import { Message } from "../codec/MessageCodec.js"; import { MessageExchange } from "../protocol/MessageExchange.js"; import { ProtocolHandler } from "../protocol/ProtocolHandler.js"; import { CaseServer } from "../session/case/CaseServer.js"; import { MaximumPasePairingErrorsReachedError, PaseServer } from "../session/pase/PaseServer.js"; import { SecureChannelMessenger } from "./SecureChannelMessenger.js"; import { SecureChannelStatusMessage } from "./SecureChannelStatusMessageSchema.js"; const logger = Logger.get("SecureChannelProtocol"); export class StatusReportOnlySecureChannelProtocol implements ProtocolHandler { readonly id = SECURE_CHANNEL_PROTOCOL_ID; // We need to check the message details to decide if ok or not, so we take them all readonly requiresSecureSession = undefined; async onNewExchange(exchange: MessageExchange, message: Message) { const messageType = message.payloadHeader.messageType; switch (messageType) { case SecureMessageType.StatusReport: await this.handleInitialStatusReport(exchange, message); break; default: // We silently ignore incoming Standalone Ack messages that we do not expect here if (messageType !== SecureMessageType.StandaloneAck) { throw new StatusResponseError( `Unexpected initial message on secure channel protocol: ${messageType.toString(16)}`, Status.InvalidAction, ); } } } async handleInitialStatusReport(exchange: MessageExchange, message: Message) { const { payloadHeader: { messageType }, payload, } = message; if (messageType !== SecureMessageType.StatusReport) { throw new MatterFlowError( `Unexpected message type on secure channel protocol, expected StatusReport: ${messageType.toString( 16, )}`, ); } const { generalStatus, protocolStatus } = SecureChannelStatusMessage.decode(payload); // Only CloseSession is expected as an initial StatusReport; anything else is a stray peer retransmit. if (generalStatus !== GeneralStatusCode.Success || protocolStatus !== SecureChannelStatusCode.CloseSession) { logger.debug( exchange.via, `Ignoring unexpected initial StatusReport (general: ${generalStatus}, protocol: ${protocolStatus})`, ); await exchange.close(); return; } const { session } = exchange; NodeSession.assert(session); logger.debug(exchange.via, "Closed by peer"); await session.handlePeerClose(exchange); } async close() { // Nothing to do } } export class SecureChannelProtocol extends StatusReportOnlySecureChannelProtocol { #paseCommissioner: PaseServer | undefined; readonly #caseCommissioner: CaseServer; readonly #fabrics: FabricManager; readonly #tooManyPaseErrors = AsyncObservable<[]>(); constructor(sessions: SessionManager, fabrics: FabricManager) { super(); this.#fabrics = fabrics; this.#caseCommissioner = new CaseServer(sessions, fabrics); } static [Environmental.create](env: Environment) { const instance = new SecureChannelProtocol(env.get(SessionManager), env.get(FabricManager)); env.get(ExchangeManager).addProtocolHandler(instance); env.set(SecureChannelProtocol, instance); return instance; } /** * Emitted when the active PASE session hits the maximum error threshold. */ get tooManyPaseErrors() { return this.#tooManyPaseErrors; } setPaseCommissioner(paseServer: PaseServer) { this.#paseCommissioner = paseServer; } async removePaseCommissioner() { await this.#paseCommissioner?.close(); this.#paseCommissioner = undefined; } override async onNewExchange(exchange: MessageExchange, message: Message) { const messageType = message.payloadHeader.messageType; switch (messageType) { case SecureMessageType.PbkdfParamRequest: if (this.#paseCommissioner === undefined) { // Cleaner to return an error (ok for chip-tool as it seems)? // Formally we should not respond at all which leads to retries and such const messenger = new SecureChannelMessenger(exchange); await messenger.sendError(SecureChannelStatusCode.InvalidParam); await messenger.close(); // also closes exchange return; } try { await this.#paseCommissioner.onNewExchange(exchange); } catch (error) { MaximumPasePairingErrorsReachedError.accept(error); await this.#tooManyPaseErrors.emit(); } break; case SecureMessageType.Sigma1: await this.#caseCommissioner.onNewExchange(exchange); break; case SecureMessageType.IcdCheckInMessage: await this.#handleIcdCheckIn(exchange, message); break; default: await super.onNewExchange(exchange, message); } } /** * Silently processes an ICD Check-In message: trial-decrypts against every fabric that has active ICD state, * invokes the matching peer handler, then closes the exchange. The handler itself never sends a response; * conformant Check-Ins are unreliable (R=0) so no acknowledgement is generated either. * * @see {@link MatterSpecification.v161.Core} § 4.22 (Check-In Protocol), § 9.15.1.3.3 */ async #handleIcdCheckIn(exchange: MessageExchange, message: Message) { try { for (const fabric of this.#fabrics) { if (!fabric.icdActive) { continue; } // processCheckIn classifies its own expected cases (wrong-key/malformed decode and handler errors are // handled internally), so anything thrown here is unexpected and must surface rather than be swallowed. if (await fabric.icd.processCheckIn(message.payload)) { return; } } logger.debug("Ignoring ICD check-in matching no registered peer"); } finally { await exchange.close(); } } }