/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { InteractionSession } from "#action/Interactable.js"; import { CommandInvokeHandler, CommandTypeProtocol, EndpointProtocol, NodeProtocol } from "#action/protocols.js"; import { Invoke } from "#action/request/Invoke.js"; import { InvokeResult } from "#action/response/InvokeResult.js"; import { AccessControl, hasRemoteActor } from "#action/server/AccessControl.js"; import { DataResponse, FallbackLimits } from "#action/server/DataResponse.js"; import { Diagnostic, InternalError, Logger } from "@matter/general"; import { AccessLevel, CommandModel, DataModelPath, ElementTag, FabricIndex as FabricIndexField } from "@matter/model"; import { CommandPath, EndpointNumber, FabricIndex, Status, StatusResponse, StatusResponseError, TlvSchema, TlvStream, ValidationError, } from "@matter/types"; import { Subject } from "./Subject.js"; const logger = Logger.get("CommandInvokeResponse"); /** * Implements invoking of commands for matter "invoke" interactions. * * TODO - profile; ensure nested functions are properly JITed and/or inlined */ export class CommandInvokeResponse< SessionT extends InteractionSession = InteractionSession, > extends DataResponse { #fabricIndex: FabricIndex; // The initial "chunk" may be a list of errors. As producers execute it is a set of records associated with the // most recently touched endpoint. When the endpoint changes the previous chunk emits #chunk?: InvokeResult.Data[]; // Each input CommandDataIB that does not have an error installs a producer. Producers run after validation and // generate actual command data #invokers?: Array<(this: CommandInvokeResponse) => AsyncIterable>; // The following state updates as data producers execute. This serves both to convey state between functions and as // a cache between producers that touch the same endpoint and/or cluster #currentEndpoint?: EndpointProtocol; // Collected only when the request asks for the endpoints it dispatches to #dispatchEndpoints?: Set; #registeredPaths = new Set(); #registeredCommandRefs = new Set(); // Count how many command status (on error) and command invokes (success) we have emitted #statusCount = 0; #successCount = 0; #errorCount = 0; constructor(node: NodeProtocol, session: SessionT) { super(node, session); this.#fabricIndex = session.fabric ?? FabricIndex.NO_FABRIC; } async *process({ invokeRequests, beforeDispatch }: T): InvokeResult { using _invoking = this.join("invoking"); const multipleInvokes = invokeRequests.length > 1; if (beforeDispatch !== undefined) { this.#dispatchEndpoints = new Set(); } // Register paths for (const command of invokeRequests) { const { commandPath: path, commandFields, commandRef } = command; if (path.endpointId === undefined || path.clusterId === undefined || path.commandId === undefined) { if (multipleInvokes) { throw new StatusResponseError( "Wildcard path must not be used with multiple invokes", Status.InvalidAction, ); } this.#processWildcard(path, commandRef, commandFields); } else { if (Subject.isGroup(this.session.subject)) { // Group command cannot be concrete paths throw new StatusResponseError("Group commands cannot be concrete paths", Status.InvalidAction); } if (multipleInvokes && commandRef === undefined) { throw new StatusResponseError( "The CommandRef field must be specified for all commands in a batch invoke", Status.InvalidAction, ); } this.#processConcrete(path as InvokeResult.ConcreteCommandPath, commandRef, commandFields); } } if (this.#dispatchEndpoints !== undefined) { beforeDispatch?.(this.#dispatchEndpoints); } if (this.#invokers) { for (const invoker of this.#invokers) { for await (const chunk of invoker.apply(this)) { yield chunk; } } } // We emit chunks lazily when the endpoint changes so there may be one remaining chunk. There may also be a // chunk with errors even if there are no data producers if (this.#chunk !== undefined) { yield this.#chunk; } } get counts() { return { status: this.#statusCount, success: this.#successCount, existent: this.#successCount + this.#errorCount, }; } /** * Process a wildcard path and invoke commands on all endpoints that match the path. */ #processWildcard(path: CommandPath, commandRef: number | undefined, commandFields: TlvStream | undefined) { const { clusterId, endpointId, commandId } = path; // Formally, according to spec, we should check for node mismatch here but commandPath do not have a nodeId const isGroupPath = Subject.isGroup(this.session.subject); if (isGroupPath && endpointId !== undefined) { throw new StatusResponseError("Illegal command invoke with group ID and endpoint ID", Status.InvalidAction); } if (clusterId === undefined || commandId === undefined) { throw new StatusResponseError( "Wildcard path write must specify a clusterId and commandId", Status.InvalidAction, ); } let groupEndpoints: EndpointNumber[] | undefined; if (isGroupPath) { if (this.session.subject.endpoints.length) { groupEndpoints = this.session.subject.endpoints; } else { // No endpoints mapped to this group, so we cannot invoke anything logger.debug(`No endpoints mapped to group ${this.session.subject.id}, skipping wildcard invoke`); return; } } if (this.#dispatchEndpoints !== undefined) { for (const endpoint of this.#wildcardEndpoints(groupEndpoints)) { if (this.#wildcardTargetOf(endpoint, path) !== undefined) { this.#dispatchEndpoints.add(endpoint.id); } } } // If we are here, then endpointId must be wildcard aka undefined this.#addInvoker(async function* invokeWildcardEndpoints(this: CommandInvokeResponse) { for (const endpoint of this.#wildcardEndpoints(groupEndpoints)) { yield* this.#processEndpointForWildcard(endpoint, path, commandRef, commandFields); } }); } /** * The endpoints a wildcard path covers: all of them, or those of the group it was sent to. */ *#wildcardEndpoints(groupEndpoints: EndpointNumber[] | undefined) { for (const endpoint of this.node) { if (groupEndpoints === undefined || groupEndpoints.includes(endpoint.id)) { yield endpoint; } } } /** * Invoke a command specified by a concrete path */ #processConcrete( path: InvokeResult.ConcreteCommandPath, commandRef: number | undefined, commandFields: TlvStream | undefined, ) { const { endpointId, clusterId, commandId } = path; const pathKey = `${endpointId}-${clusterId}-${commandId}`; if (this.#registeredPaths.has(pathKey)) { throw new StatusResponseError( `Duplicate concrete command path ${this.node.inspectPath(path)} on batch invoke`, Status.InvalidAction, ); } this.#registeredPaths.add(pathKey); if (commandRef !== undefined) { if (this.#registeredCommandRefs.has(commandRef)) { throw new StatusResponseError( `Duplicate commandRef ${commandRef} on batch invoke`, Status.InvalidAction, ); } this.#registeredCommandRefs.add(commandRef); } // Formally, according to spec, we should check for node mismatch here but commandPath do not have a nodeId // Resolve path elements const endpoint = this.node[endpointId]; const cluster = endpoint?.[clusterId]; const command = cluster?.type.commands[commandId]; let limits; if (command === undefined) { // We still need to authorize the user for access even though this path doesn't resolve. Spec is not // explicit on what privilege level we should require as normally that information comes from the resolved // command. So attempt to resolve via the active model const modelAttr = this.node.matter .member(path.clusterId, [ElementTag.Cluster]) ?.member(path.commandId, [ElementTag.Command]); if (modelAttr) { // OK cluster doesn't exist at that location, but we do understand semantically, so use limits from the // model limits = AccessControl(modelAttr as CommandModel).limits; } else { // We've got no idea. This effectively falls back to "view" privilege limits = FallbackLimits; } } else { limits = command.limits; } // Order prescribed by core spec 8.8.3.2: an Operate-privilege pass gates element-existence disclosure, // existence checks follow, then the actual-privilege pass gates the invoke. // We need some fallback location if cluster is not defined const location: AccessControl.Location = { ...(cluster?.location ?? { path: DataModelPath.none, endpoint: endpointId, cluster: clusterId, }), owningFabric: this.session.fabric, }; let access: { session: AccessControl.RemoteActorSession; location: AccessControl.Location } | undefined; if (hasRemoteActor(this.session)) { access = { session: this.session, location }; const denial = this.#authorize(access.session, AccessLevel.Operate, location); if (denial !== undefined) { return this.#addStatus(path, commandRef, denial); } } if (endpoint === undefined) { return this.#addStatus(path, commandRef, Status.UnsupportedEndpoint); } if (cluster === undefined) { return this.#addStatus(path, commandRef, Status.UnsupportedCluster); } if (command === undefined || !cluster.type.commands[command.id]) { return this.#addStatus(path, commandRef, Status.UnsupportedCommand); } if (access !== undefined) { const denial = this.#authorize(access.session, limits.writeLevel, access.location); if (denial !== undefined) { this.#errorCount++; return this.#addStatus(path, commandRef, denial); } } if (hasRemoteActor(this.session)) { if (limits.largeMessage && !this.session.largeMessage) { this.#errorCount++; return this.#addStatus(path, commandRef, Status.InvalidTransportType); } if (limits.fabricScoped && !this.session.fabric) { this.#errorCount++; return this.#addStatus(path, commandRef, Status.UnsupportedAccess); } if (limits.timed && !this.session.timed) { this.#errorCount++; return this.#addStatus(path, commandRef, Status.NeedsTimedInteraction); } } this.#dispatchEndpoints?.add(endpointId); // This path contributes an command value this.#addInvoker(async function* invokeConcretePath() { // Update internal state for target endpoint if (this.#currentEndpoint !== endpoint) { if (this.#chunk) { yield this.#chunk; this.#chunk = undefined; } this.#currentEndpoint = endpoint; } await this.#invokeCommand( command, path, commandRef, commandFields, cluster.commands[command.id], cluster.skipCommandValidation, ); }); } /** * Starts new chunk or adds to current chunk all values from {@link endpoint} selected by {@link path}. * * Emits previous chunk if it exists and was not for this endpoint. This means that our chunk size is one endpoint * worth of data, except for the initial error chunk if there are path errors. ** * TODO - skip endpoints for which subject is unauthorized as optimization */ async *#processEndpointForWildcard( endpoint: EndpointProtocol, path: CommandPath, commandRef: number | undefined, commandFields: TlvStream | undefined, ) { if (this.#currentEndpoint !== endpoint) { if (this.#chunk) { yield this.#chunk; this.#chunk = undefined; } this.#currentEndpoint = endpoint; } const target = this.#wildcardTargetOf(endpoint, path); if (target === undefined) { return; } const { cluster, command } = target; await this.#invokeCommand( command, { ...path, endpointId: endpoint.id, }, commandRef, commandFields, cluster.commands[command.id], cluster.skipCommandValidation, ); } /** * The cluster and command a wildcard {@link path} dispatches to on {@link endpoint}, or undefined if the endpoint * lacks them or the session may not invoke the command there. */ #wildcardTargetOf(endpoint: EndpointProtocol, { clusterId, commandId }: CommandPath) { if (clusterId === undefined || commandId === undefined) { return; } const cluster = endpoint[clusterId]; const command = cluster?.type.commands[commandId]; if (cluster === undefined || command === undefined) { return; } if (hasRemoteActor(this.session)) { const { limits } = command; if (this.session.authorityAt(limits.writeLevel, cluster.location) !== AccessControl.Authority.Granted) { return; } if (limits.largeMessage && !this.session.largeMessage) { return; } if (limits.fabricScoped && !this.session.fabric) { return; } if (limits.timed && !this.session.timed) { return; } } return { cluster, command }; } /** * Add a function that invokes commands and produces data. These functions are run after validation of input paths. */ #addInvoker(producer: (this: CommandInvokeResponse) => AsyncIterable) { if (this.#invokers) { this.#invokers.push(producer); } else { this.#invokers = [producer]; } } /** * Validate access at {@link level}. Returns undefined if granted; otherwise the status to report. */ #authorize(session: AccessControl.RemoteActorSession, level: AccessLevel, location: AccessControl.Location) { const permission = session.authorityAt(level, location); switch (permission) { case AccessControl.Authority.Granted: return undefined; case AccessControl.Authority.Unauthorized: return Status.UnsupportedAccess; case AccessControl.Authority.Restricted: return Status.AccessRestricted; default: throw new InternalError(`Unsupported authorization state ${permission}`); } } #addResponse(chunk: InvokeResult.Data) { if (this.#chunk) { this.#chunk.push(chunk); } else { this.#chunk = [chunk]; } } /** * Add a status value. */ #addStatus( path: InvokeResult.ConcreteCommandPath, commandRef: number | undefined, status: Status, clusterStatus?: number, ) { // Spec 1.6 §7.10.7: when a cluster-specific status is present the outer IM status SHALL be SUCCESS or FAILURE. if (clusterStatus !== undefined && status !== Status.Success) { status = Status.Failure; } if (status !== Status.Success) { logger.info( () => `Invoke error ${this.node.inspectPath(path)}: Status=${Status[status]}(${status}), ClusterStatus=${clusterStatus}`, ); } const response: InvokeResult.CommandStatus = { kind: "cmd-status", path, status, clusterStatus, commandRef, }; if (status !== Status.Success) { this.#statusCount++; } this.#addResponse(response); } async #invokeCommand( command: CommandTypeProtocol, path: InvokeResult.ConcreteCommandPath, commandRef: number | undefined, commandFields: TlvStream | undefined, invoker: CommandInvokeHandler, skipValidation?: boolean, ) { try { const { requestTlv, responseTlv } = command; const request = this.#decodeWithSchema(requestTlv, commandFields); if (!skipValidation) { requestTlv.validate(request); } const response = await invoker(request, this.session); // A response the schema cannot represent must roll back with its command rather than leave state // committed behind a failure status const encodedResponse = responseTlv.encodeTlv(response); await this.session.transaction?.commit(); this.#successCount++; if (encodedResponse.length === 0) { this.#addStatus(path, commandRef, Status.Success); } else { this.#addResponse({ kind: "cmd-response", path: { ...path, commandId: command.responseId, }, data: encodedResponse, commandRef, }); } } catch (error) { // Spec 1.6 §8.8.3.2.1: Invoke Execution yields only a CommandStatusIB or a CommandDataIB, so this command // owes a status even if handling the error itself fails let status = Status.Failure; let clusterStatus: number | undefined; try { await this.session.transaction?.rollback(); const sre = StatusResponseError.of(error); if (sre === undefined) { logger.error(`Unhandled error invoking command ${this.node.inspectPath(path)}:`, error); } else { status = sre.code; clusterStatus = sre.clusterCode; const errorLogText = `Error ${Diagnostic.hex(status)}${ clusterStatus !== undefined ? `/${Diagnostic.hex(clusterStatus)}` : "" } while invoking command: ${sre.message}`; if (sre instanceof ValidationError) { logger.info( `Validation-${errorLogText}${sre.fieldName !== undefined ? ` in field ${sre.fieldName}` : ""}`, ); if (status === Status.InvalidAction) { status = Status.InvalidCommand; } } else { logger.info(errorLogText); } } } catch (secondary) { logger.error("Secondary error handling invoke failure:", secondary); } this.#errorCount++; this.#addStatus(path, commandRef, status, clusterStatus); } } #decodeWithSchema(tlv: TlvSchema, value: TlvStream | undefined) { if (value === undefined) { return undefined; // The validation will fail if the schema expected data } let decoded; try { decoded = tlv.decodeTlv(value); } catch (error) { // A payload that does not match the command's schema is a fault in the request, not in this node StatusResponseError.reject(error); throw new StatusResponse.InvalidCommandError( `Command payload does not match the command schema: ${error instanceof Error ? error.message : error}`, ); } return tlv.injectField( decoded, FabricIndexField.id, this.#fabricIndex, () => true, // We always inject the current fabricIndex for invokes ); } }