/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { MessagePrivacy } from "#codec/MessagePrivacy.js"; import { GroupKeySet, KeySets, OperationalKeySet } from "#groups/KeySets.js"; import { MessagingState } from "#groups/MessagingState.js"; import { BasicMap, Bytes, Crypto, hex, InternalError, MatterFlowError, StorageContext } from "@matter/general"; import { FabricId, GlobalFabricId, GroupId, MATTER_EPOCH_OFFSET_US } from "@matter/types"; import { GroupMulticastPolicy, Groups } from "./Groups.js"; export const GROUP_SECURITY_INFO = Bytes.fromString("GroupKey v1.0"); export const IPK_DEFAULT_EPOCH_START_TIME = MATTER_EPOCH_OFFSET_US; /** * Class that contains an operational view on the Group Keys for a fabric */ export class FabricGroups { readonly #crypto: Crypto; readonly #globalId: GlobalFabricId; #groups: Groups; #messagingState: MessagingState; /** Operationally enhanced variants of the group key sets based on their ID. */ #keySets = new KeySets(); constructor(fabric: FabricGroups.FabricIdentity, storage?: StorageContext) { this.#crypto = fabric.crypto; this.#globalId = fabric.globalId; this.#groups = new Groups(fabric.fabricId, this.#keySets); this.#messagingState = new MessagingState(); // KeySet with ID 0 is always the Fabric IPK, so we initialize from there because this is not stored // in Key Management Cluster this.#keySets.add({ groupKeySetId: 0, epochKey0: fabric.identityProtectionKey, operationalEpochKey0: fabric.operationalIdentityProtectionKey, epochStartTime0: IPK_DEFAULT_EPOCH_START_TIME, // with the Year 2000-offset that's basically 0 and always ok, but only for the IPK key groupSessionId0: null, epochKey1: null, operationalEpochKey1: null, epochStartTime1: null, groupSessionId1: null, epochKey2: null, operationalEpochKey2: null, epochStartTime2: null, groupSessionId2: null, groupKeySecurityPolicy: 0, // GroupKeyManagement.GroupKeySecurityPolicy.TrustFirst, the other option is provisional }); if (storage !== undefined) { this.storage = storage; } } set storage(storage: StorageContext) { this.#messagingState.storage = storage; } /** Operative lookup of the group key sets by their id. */ get keySets(): KeySets { return this.#keySets; } get messaging(): MessagingState { return this.#messagingState; } /** Operative lookup of the group key set id and the key by a group session Id. */ get sessions() { return this.#keySets.sessions; } get groupKeyIdMap(): BasicMap { return this.#groups.idMap; } set groupKeyIdMap(map: Map) { this.#groups.idMap = map; } get endpoints() { return this.#groups.endpointMap; } get multicastPolicy() { return this.#groups.multicastPolicy; } /** Whether any group of this fabric currently maps to the given key set. */ isKeySetMapped(keySetId: number) { return this.#groups.isKeySetMapped(keySetId); } currentKeyForGroup(groupId: GroupId) { return this.#groups.currentKeyForId(groupId); } subjectForGroup(id: GroupId, operationalKey: Bytes) { return this.#groups.subjectForGroup(id, operationalKey); } multicastAddressFor(groupId: GroupId): string { return this.#groups.multicastAddress(groupId); } /** Sets the multicast address policy for a specific group (Groupcast cluster, Matter 1.6). */ setGroupMulticastPolicy(groupId: GroupId, policy: GroupMulticastPolicy) { this.#groups.setGroupMulticastPolicy(groupId, policy); } /** Removes the multicast address policy for a specific group. */ removeGroupMulticastPolicy(groupId: GroupId) { this.#groups.removeGroupMulticastPolicy(groupId); } /* TODO for Controller to generate new epochs addGroupEpoch(groupKeySetId: number, startTimeMs = Time.nowMs) { // TODO for Controller to generate new epochs const epochKey = Crypto.getRandomData(CRYPTO_SYMMETRIC_KEY_LENGTH); const operationalEpochKey = Crypto.hkdf(epochKey, this.#fabric.operationalId, GROUP_SECURITY_INFO); const epochStartTime = startTimeMs * 1000; logger.debug(`addGroupEpoch: epochStartTime=${epochStartTime}`, operationalEpochKey); // TODO extend in structure and such } */ /** * Sets new group key set data and pre-calculates all operative data like session ids and operational keys. * Overwriting the existing one if it exists. */ async setFromGroupKeySet(groupKeySet: GroupKeySet) { const { epochKey0, epochKey1, epochKey2 } = groupKeySet; const previousEntry = this.#keySets.get("groupKeySetId", groupKeySet.groupKeySetId); if (epochKey0 === null) { throw new MatterFlowError("EpochKey0 must be set"); // checked before, but to make typing happy } // Lets pre-calculate the operational keys const globalId = Bytes.fromHex(hex.fixed(this.#globalId, 16)); const operationalEpochKey0 = await this.#crypto.createHkdfKey(epochKey0, globalId, GROUP_SECURITY_INFO); const operationalEpochKey1 = epochKey1 !== null ? await this.#crypto.createHkdfKey(epochKey1, globalId, GROUP_SECURITY_INFO) : null; const operationalEpochKey2 = epochKey2 !== null ? await this.#crypto.createHkdfKey(epochKey2, globalId, GROUP_SECURITY_INFO) : null; const operationalPrivacyKey0 = Bytes.of(await MessagePrivacy.deriveKey(this.#crypto, operationalEpochKey0)); const operationalPrivacyKey1 = operationalEpochKey1 !== null ? Bytes.of(await MessagePrivacy.deriveKey(this.#crypto, operationalEpochKey1)) : null; const operationalPrivacyKey2 = operationalEpochKey2 !== null ? Bytes.of(await MessagePrivacy.deriveKey(this.#crypto, operationalEpochKey2)) : null; this.#keySets.add({ ...groupKeySet, operationalEpochKey0, operationalPrivacyKey0, groupSessionId0: await this.#keySets.sessionIdFromKey(this.#crypto, operationalEpochKey0), operationalEpochKey1, operationalPrivacyKey1, groupSessionId1: operationalEpochKey1 !== null ? await this.#keySets.sessionIdFromKey(this.#crypto, operationalEpochKey1) : null, operationalEpochKey2, operationalPrivacyKey2, groupSessionId2: operationalEpochKey2 !== null ? await this.#keySets.sessionIdFromKey(this.#crypto, operationalEpochKey2) : null, }); // An in-place rewrite that changes epoch keys drops the previous operational keys; forget their reception state // (unless still referenced) so a later key set reusing a dropped epoch key re-synchronizes on its first message. if (previousEntry !== undefined) { this.#forgetUnreferencedReceptionState(previousEntry); } } /** Removes a group key set by its id. */ removeGroupKeySet(groupKeySetId: number) { if (groupKeySetId === 0) { throw new InternalError("Cannot remove the group key set 0."); } const removedEntry = this.#keySets.get("groupKeySetId", groupKeySetId); const deleted = this.#keySets.delete("groupKeySetId", groupKeySetId); if (removedEntry !== undefined) { this.#forgetUnreferencedReceptionState(removedEntry); } return deleted; } /** * Forget the group message replay-protection state for a departing key set's operational keys, unless a remaining * key set still derives the same key — duplicate epoch keys share one reception window, so it must survive until the * last referencing key set is gone. */ #forgetUnreferencedReceptionState(formerEntry: OperationalKeySet) { const stillReferenced = new Set(); for (const keySet of this.#keySets) { for (const key of [keySet.operationalEpochKey0, keySet.operationalEpochKey1, keySet.operationalEpochKey2]) { if (key !== null) { stillReferenced.add(Bytes.toHex(key)); } } } for (const key of [ formerEntry.operationalEpochKey0, formerEntry.operationalEpochKey1, formerEntry.operationalEpochKey2, ]) { if (key !== null && !stillReferenced.has(Bytes.toHex(key))) { this.#messagingState.forgetReceptionState(key); } } } } export namespace FabricGroups { /** The fabric values group key derivation and multicast addressing depend on. */ export interface FabricIdentity { crypto: Crypto; fabricId: FabricId; globalId: GlobalFabricId; identityProtectionKey: Bytes; operationalIdentityProtectionKey: Bytes; } }