indigo-matter-bridge 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/node.js ADDED
@@ -0,0 +1,946 @@
1
+ /**
2
+ * The Matter side of the bridge: a ServerNode with an Aggregator at endpoint 1
3
+ * and one bridged child endpoint per exported Indigo device.
4
+ *
5
+ * The child set is entirely protocol-driven (§3.1-§3.3) and lives in
6
+ * {@link EndpointRegistry}; a node that has never been attached to serves an
7
+ * empty aggregator. Endpoint *numbers* are persisted by matter.js against
8
+ * `Endpoint.id`, so a device that comes back with the same id comes back with
9
+ * the same number — presence in the running set is not what preserves identity.
10
+ *
11
+ * All matter.js coupling lives here, in `endpoints.ts`/`registry.ts` and in
12
+ * main.ts — ADR-0006's binding constraint keeps it out of the Indigo plugin
13
+ * entirely, and this module keeps it out of the protocol layer so the protocol
14
+ * is testable on its own.
15
+ */
16
+ import { join } from "node:path";
17
+ import { Endpoint, Environment, ServerNode, VendorId, version as matterJsVersion } from "@matter/main";
18
+ import { BasicInformationServer } from "@matter/main/behaviors/basic-information";
19
+ import { AggregatorEndpoint } from "@matter/main/endpoints/aggregator";
20
+ import { Crypto } from "@matter/main";
21
+ import { DeviceCommissioner, FabricManager, PaseClient, PaseServer, SessionManager } from "@matter/main/protocol";
22
+ import { CommissioningFlowType, FabricIndex, ManualPairingCodeCodec, QrPairingCodeCodec, } from "@matter/main/types";
23
+ import { ENDPOINT_MAP_FILE, EndpointMapStore, refuseReasonFor } from "./endpoint-map.js";
24
+ import { uniqueIdFor } from "./endpoints.js";
25
+ import { describeError, describeErrorWithStack, endpointMapInvalidDetails, ErrorCode, ProtocolError, RefuseReason, } from "./protocol.js";
26
+ import { EndpointRegistry } from "./registry.js";
27
+ import { clearCommissioned, identityFileProblem, markCommissioned, nodeUniqueIdFor, readIdentity, serialNumberFor, } from "./storage.js";
28
+ import { CommissioningWindow } from "./window.js";
29
+ /** Test vendor id. Uncertified by design — see ADR-0006 "Attestation cuts both ways". */
30
+ export const VENDOR_ID = 0xfff1;
31
+ export const PRODUCT_ID = 0x8000;
32
+ export const VENDOR_NAME = "simons-plugins";
33
+ export const PRODUCT_NAME = "Indigo Matter Bridge";
34
+ /** A bridge has no hardware. Constant rather than invented, but present rather
35
+ * than absent: ecosystems render the attribute, and an absent one reads blank. */
36
+ export const HARDWARE_VERSION = 1;
37
+ export const HARDWARE_VERSION_STRING = "1";
38
+ /** PRD §5.3: no hard cap, but past this many exports the log says so. */
39
+ export const ENDPOINT_COUNT_WARNING = 100;
40
+ /** §4.3 `warnings` key for identity-file writes. Stable, so it replaces itself. */
41
+ const WARN_IDENTITY_WRITE = "identity-write";
42
+ /** PBKDF iteration count for enhanced-window verifiers. Spec floor is 1000. */
43
+ const PBKDF_ITERATIONS = 1000;
44
+ const PBKDF_SALT_BYTES = 32;
45
+ export { matterJsVersion };
46
+ export class BridgeNode {
47
+ config;
48
+ bridgeVersion;
49
+ log;
50
+ #server;
51
+ #registry;
52
+ #command;
53
+ #driftListener;
54
+ #fabricsListener;
55
+ #commissionedListener;
56
+ #decommissionedListener;
57
+ /** Last observed fabric count — what turns a change into a §5 transition. */
58
+ #fabricCount = 0;
59
+ #window;
60
+ #endpointMap;
61
+ /** The identity, rebound by {@link markCommissioned}/{@link clearCommissioned}. */
62
+ #identity;
63
+ /** Why we are refusing everything but the §1.1 recovery trio, if we are. */
64
+ #refusal;
65
+ /** The drift the last {@link checkDrift} found; what §4.3 reports. */
66
+ #drift = [];
67
+ /**
68
+ * §4.3 `warnings` this object owns — the identity-file ones. The endpoint
69
+ * map keeps its own and {@link getStatus} merges them, so each warning is
70
+ * cleared by whatever succeeded rather than by a central bookkeeper that
71
+ * would have to know when that happened.
72
+ */
73
+ #warnings = new Map();
74
+ /**
75
+ * @param initialRefusal a refuse-to-start reason decided before the node was
76
+ * built — today only `main.ts`'s unusable-`identity.json` check, which has
77
+ * to happen before the identity is loaded (and therefore before this
78
+ * object can exist) because loading it is what would overwrite it.
79
+ */
80
+ constructor(config, identity, bridgeVersion, log = console.log, initialRefusal) {
81
+ this.config = config;
82
+ this.bridgeVersion = bridgeVersion;
83
+ this.log = log;
84
+ this.#identity = identity;
85
+ this.#refusal = initialRefusal;
86
+ this.#endpointMap = new EndpointMapStore(config.storagePath, message => this.log(message));
87
+ this.#window = new CommissioningWindow({
88
+ log: message => this.log(message),
89
+ onExpire: () => this.endMatterCommissioning(),
90
+ });
91
+ }
92
+ /** The identity in force — rebound whenever its commissioning witness moves. */
93
+ get identity() {
94
+ return this.#identity;
95
+ }
96
+ /** Matter wants an integer software version; derive it from the npm semver. */
97
+ get softwareVersion() {
98
+ const [major = 0, minor = 0, patch = 0] = this.bridgeVersion.split(".").map(part => Number.parseInt(part, 10));
99
+ return (major || 0) * 10000 + (minor || 0) * 100 + (patch || 0);
100
+ }
101
+ /**
102
+ * The identity every bridged child publishes on its Bridged Device Basic
103
+ * Information. Derived here, from the same constants and the same
104
+ * `softwareVersion` the root node uses, so the two can never drift.
105
+ */
106
+ get bridgedIdentity() {
107
+ return {
108
+ vendorName: VENDOR_NAME,
109
+ vendorId: VENDOR_ID,
110
+ productName: PRODUCT_NAME,
111
+ hardwareVersion: HARDWARE_VERSION,
112
+ hardwareVersionString: HARDWARE_VERSION_STRING,
113
+ softwareVersion: this.softwareVersion,
114
+ softwareVersionString: this.bridgeVersion,
115
+ };
116
+ }
117
+ /**
118
+ * Build the node and bring it online. The aggregator is added first so it
119
+ * takes endpoint 1; bridged children land at 2 and up, in the order the
120
+ * first `attach` creates them (and thereafter at whatever number matter.js
121
+ * has persisted against their id).
122
+ */
123
+ async start() {
124
+ const environment = Environment.default;
125
+ // matter.js resolves all of these lazily through its VariableService,
126
+ // so setting them before `ServerNode.create` is what keeps storage out
127
+ // of ~/.matter and pins mDNS when asked.
128
+ environment.vars.set("storage.path", this.config.storagePath);
129
+ if (this.config.mdnsInterface !== undefined) {
130
+ environment.vars.set("mdns.networkInterface", this.config.mdnsInterface);
131
+ }
132
+ // We own SIGTERM/SIGINT outright. matter.js's ProcessManager installs its
133
+ // own interrupt handlers when the runtime starts, and being registered
134
+ // first they run first — tearing the ServerNode down concurrently with
135
+ // main.ts's ordered shutdown. `runtime.signals` is the documented opt-out
136
+ // (`ProcessManager.hasSignalSupport` reads it).
137
+ environment.vars.set("runtime.signals", false);
138
+ const server = await ServerNode.create({
139
+ id: "indigo-matter-bridge",
140
+ environment,
141
+ network: { port: this.config.matterPort },
142
+ commissioning: {
143
+ passcode: this.identity.passcode,
144
+ discriminator: this.identity.discriminator,
145
+ },
146
+ productDescription: {
147
+ name: PRODUCT_NAME,
148
+ deviceType: AggregatorEndpoint.deviceType,
149
+ },
150
+ basicInformation: {
151
+ vendorName: VENDOR_NAME,
152
+ vendorId: VendorId(VENDOR_ID),
153
+ productName: PRODUCT_NAME,
154
+ productId: PRODUCT_ID,
155
+ serialNumber: serialNumberFor(this.identity),
156
+ uniqueId: nodeUniqueIdFor(this.identity),
157
+ hardwareVersion: HARDWARE_VERSION,
158
+ hardwareVersionString: HARDWARE_VERSION_STRING,
159
+ softwareVersion: this.softwareVersion,
160
+ softwareVersionString: this.bridgeVersion,
161
+ },
162
+ });
163
+ this.#server = server;
164
+ const aggregator = new Endpoint(AggregatorEndpoint, { id: "aggregator" });
165
+ await server.add(aggregator);
166
+ this.#registry = new EndpointRegistry({
167
+ aggregator,
168
+ // Deliberately the SAME values the root node's BasicInformation
169
+ // carries above: an ecosystem that shows the bridge's manufacturer
170
+ // and firmware alongside a child's should not be shown two answers.
171
+ bridgeIdentity: this.bridgedIdentity,
172
+ log: message => this.log(message),
173
+ emit: data => this.#command?.(data),
174
+ onConfigurationChange: () => this.bumpConfigurationVersion(),
175
+ });
176
+ server.events.commissioning.fabricsChanged.on((fabricIndex, action) => {
177
+ // A throw here propagates straight into matter.js's observable, and
178
+ // `fabrics()` reads server state that is legitimately gone once
179
+ // close() is under way. Log-only, never rethrow.
180
+ try {
181
+ this.log(`Fabric ${action}: index ${fabricIndex} (${this.fabrics().length} total)`);
182
+ this.noteCommissioningWitness();
183
+ this.noteFabrics(String(action));
184
+ }
185
+ catch (error) {
186
+ try {
187
+ this.log(`Fabric ${action}: index ${fabricIndex} (count unavailable: ${describeError(error)})`);
188
+ }
189
+ catch {
190
+ // The logger itself failed; there is nowhere left to report.
191
+ }
192
+ }
193
+ });
194
+ // Before the stack goes online, so the answer is available the moment a
195
+ // client can ask — and so the log reads in the order things happened.
196
+ this.#endpointMap.load();
197
+ await server.start();
198
+ // The §5 transition baseline. Taken before the identity assertion so a
199
+ // fabric that arrives during it is a transition rather than the start.
200
+ this.#fabricCount = this.fabrics().length;
201
+ this.assertEndpointIdentity();
202
+ this.log(`Matter node online on port ${this.config.matterPort}, storage ${this.config.storagePath}`);
203
+ this.logPairing();
204
+ }
205
+ /**
206
+ * The PRD §7 refuse-to-start decision, taken once the stack is up and the
207
+ * fabric table is readable.
208
+ *
209
+ * Three conditions, and the asymmetry between them is the whole design.
210
+ * Endpoint numbers only matter to somebody who is *paired*: on a bridge
211
+ * nothing has ever commissioned, a missing or unreadable map costs nothing,
212
+ * so a fresh install must never be blocked by one. Once a fabric exists,
213
+ * both directions of the loss are fatal to identity and neither may be
214
+ * papered over —
215
+ *
216
+ * * fabrics but no usable map: the numbers being served cannot be checked
217
+ * against anything, so a silent re-record would bless whatever matter.js
218
+ * happens to be handing out this boot;
219
+ * * the commissioning witness but no fabrics (PRD §7's "storage missing but
220
+ * previously commissioned"): matter.js's storage has gone, which means its
221
+ * own `Endpoint.id → number` allocation went with it, and every accessory
222
+ * is about to be re-created in every ecosystem the user paired.
223
+ *
224
+ * Refusing is *not* a process exit. The Matter stack stays up so `get_pairing`
225
+ * still answers and the user can see the state, but `attach` is refused, so
226
+ * no endpoint is ever created — which is what actually prevents the
227
+ * duplication. §3.11 is the way out, and it is explicit because it is a
228
+ * decision only the user can take.
229
+ */
230
+ assertEndpointIdentity() {
231
+ if (this.#refusal !== undefined) {
232
+ this.refuse(this.#refusal);
233
+ return;
234
+ }
235
+ const commissioned = this.server.lifecycle.isCommissioned;
236
+ const reason = refuseReasonFor({
237
+ commissioned,
238
+ mapProblem: this.#endpointMap.problem,
239
+ commissionedAt: this.identity.commissionedAt,
240
+ });
241
+ if (reason === undefined) {
242
+ if (commissioned && !this.#endpointMap.present) {
243
+ this.bootstrapEndpointMap();
244
+ }
245
+ this.noteCommissioningWitness();
246
+ return;
247
+ }
248
+ if (reason === RefuseReason.fabricStorageLost) {
249
+ this.log(`Identity records commissioning at ${this.identity.commissionedAt}, but the ` +
250
+ "Matter stack reports no fabrics");
251
+ }
252
+ this.refuse(reason);
253
+ }
254
+ /**
255
+ * A commissioned bridge with no `endpoint-map.json` at all: adopt the
256
+ * numbers matter.js has already been persisting, and serve.
257
+ *
258
+ * This is the upgrade path, and it is the common case rather than an edge
259
+ * one — **every** bridge commissioned before E5 shipped has fabrics,
260
+ * endpoints and no map, because the file did not exist. The first cut of E5
261
+ * refused there, which would have stopped serving every already-paired
262
+ * accessory the moment the node was updated.
263
+ *
264
+ * Seeding is legitimate precisely because our map does not allocate
265
+ * anything: matter.js keys the real numbers on `Endpoint.id` in its own
266
+ * store, this file is the independent witness, and writing down numbers
267
+ * that are already true is not blessing anything — the number a
268
+ * not-yet-created endpoint will get is already determined. That is the
269
+ * difference from a **rebuild**, which discards a baseline that disagreed.
270
+ *
271
+ * The baseline starts empty and is filled by the first attach's `check`
272
+ * from the live set. Those live numbers ARE matter.js's persisted ones —
273
+ * it restores each `Endpoint.id`'s number from its own store as the
274
+ * endpoint is created — so the witness this records is the pre-upgrade
275
+ * truth, not a fresh allocation.
276
+ *
277
+ * An earlier cut read matter.js's store directly here, to also cover
278
+ * endpoints it knows about but this attach does not export. It was deleted
279
+ * after verification against a real pre-E5 storage directory: the chain
280
+ * (`root`→`parts`→`aggregator`→`parts`, `contexts()`) enumerates only
281
+ * subcontexts already materialised in memory, and at bootstrap time none
282
+ * are, so it returned an empty list while reporting that it had adopted
283
+ * numbers — a false success in a migration path. The numbers live in flat
284
+ * on-disk keys whose layout is matter.js-internal. Not worth re-deriving:
285
+ * a not-yet-exported endpoint's number is decided by `Endpoint.id`
286
+ * whenever it IS created, so an entry for it buys nothing.
287
+ */
288
+ bootstrapEndpointMap() {
289
+ const source = "the first reconcile records the live set, which is matter.js's own persisted numbers";
290
+ this.log("MIGRATION: this bridge is commissioned but has no endpoint-number map — one is being " +
291
+ `created now rather than refused. Nothing is renumbered: matter.js owns the numbers ` +
292
+ `and this file only witnesses them (${source}).`);
293
+ // The line above is written before the answer is known, because it
294
+ // explains what is being attempted — but it must not be left standing
295
+ // as the last word when the attempt failed. A migration that never
296
+ // reached disk has not happened: `present` is still false at the next
297
+ // start, which bootstraps again, and saying otherwise would have the
298
+ // log claiming a baseline that no restart can find.
299
+ if (!this.#endpointMap.seed([], source)) {
300
+ this.log("MIGRATION NOT RECORDED: the endpoint-map baseline could not be written, so no " +
301
+ "baseline exists yet — the next start will bootstrap again. Drift cannot be " +
302
+ "detected until it lands.");
303
+ }
304
+ }
305
+ refuse(reason) {
306
+ this.#refusal = reason;
307
+ // The remedy is not the same for every reason, and printing the map one
308
+ // for all of them sent the identity case somewhere that cannot help:
309
+ // `rebuildEndpointMap` explicitly THROWS for `identityUnreadable` (see
310
+ // §3.11), so a user following that sentence would run the one command
311
+ // guaranteed to refuse them, and still be no closer to the file that
312
+ // actually needs restoring.
313
+ const remedy = reason === RefuseReason.identityUnreadable
314
+ ? "Nothing will be exported until the quarantined identity.json.unreadable-<stamp> is " +
315
+ "restored or repaired as identity.json and the bridge restarted; rebuilding the " +
316
+ "endpoint map CANNOT fix this."
317
+ : "Nothing will be exported until the endpoint map is rebuilt (BRIDGE_PROTOCOL §3.11), " +
318
+ "which WILL duplicate accessories in already-paired ecosystems.";
319
+ this.log(`REFUSING to serve endpoints — ${reason}. ${remedy}`);
320
+ }
321
+ /** §1.1 — the reason we are refusing, or `undefined` while serving. */
322
+ endpointMapRefusal() {
323
+ return this.#refusal;
324
+ }
325
+ /**
326
+ * Stamp `commissionedAt` the first time a fabric is seen.
327
+ *
328
+ * Written on the *observation* rather than on the commissioning command,
329
+ * because the thing being witnessed is "endpoint numbers now matter to
330
+ * somebody", and that is true of a fabric restored from a backup exactly as
331
+ * it is of one just paired.
332
+ */
333
+ noteCommissioningWitness() {
334
+ if (this.identity.commissionedAt !== undefined || this.fabrics().length === 0) {
335
+ return;
336
+ }
337
+ this.applyWitness(WARN_IDENTITY_WRITE, markCommissioned(this.config.storagePath, this.identity, message => this.log(message)));
338
+ }
339
+ /**
340
+ * Adopt a {@link WitnessWrite}'s identity and record (or clear) its warning.
341
+ *
342
+ * The whole point of B1: these writes used to return only the identity, so
343
+ * a caller could not tell a witness that reached disk from one that did not
344
+ * — and both `factory_reset` and the drift baseline report success in a
345
+ * voice that assumes it did.
346
+ */
347
+ applyWitness(key, write) {
348
+ this.#identity = write.identity;
349
+ if (write.persisted) {
350
+ this.#warnings.delete(key);
351
+ }
352
+ else {
353
+ this.#warnings.set(key, write.problem ?? "identity.json could not be written");
354
+ }
355
+ return write.persisted;
356
+ }
357
+ /**
358
+ * §5 `fabrics_changed` / `commissioned` / `decommissioned`.
359
+ *
360
+ * One place, because the three are one fact seen at three grains and
361
+ * deriving them separately is how they drift apart. `change` is `undefined`
362
+ * for the callers that only want the transition re-checked — §3.9's last
363
+ * leave and §3.10's erase both move the count without necessarily producing
364
+ * an observable we saw.
365
+ *
366
+ * Never throws: it is called from inside matter.js's own observable and
367
+ * from teardown paths where `fabrics()` legitimately fails.
368
+ */
369
+ noteFabrics(change) {
370
+ let fabrics;
371
+ try {
372
+ fabrics = this.fabrics();
373
+ }
374
+ catch (error) {
375
+ // One `catch` used to swallow three separate things, and the worst
376
+ // of them was silent and delayed: `commissionedAt` is cleared from
377
+ // here (via noteLastFabricGone), so a read that fails on the way
378
+ // out of a deliberate last-fabric unpair strands the witness — and
379
+ // the NEXT start refuses to serve anything, blaming lost fabric
380
+ // storage for something the user did on purpose. The §5 events go
381
+ // with it, so an ecosystem pairing or unpairing lands in the plugin
382
+ // as nothing at all. Log-only: this runs inside matter.js's own
383
+ // observable and on teardown paths where the read legitimately
384
+ // fails, and a throw there takes the stack down with it.
385
+ try {
386
+ this.log(`Fabric list unavailable (${describeError(error)}); no fabrics_changed / ` +
387
+ "commissioned / decommissioned event will be raised for this change, and if " +
388
+ "this was the last fabric leaving, the commissioning witness has NOT been " +
389
+ "cleared — the next start would then refuse to serve endpoints, reporting " +
390
+ "lost fabric storage.");
391
+ }
392
+ catch {
393
+ // The logger itself failed; there is nowhere left to report.
394
+ }
395
+ return;
396
+ }
397
+ if (change !== undefined) {
398
+ this.#fabricsListener?.(fabrics, change);
399
+ }
400
+ const was = this.#fabricCount;
401
+ this.#fabricCount = fabrics.length;
402
+ if (was === 0 && fabrics.length > 0) {
403
+ this.#commissionedListener?.();
404
+ }
405
+ else if (was > 0 && fabrics.length === 0) {
406
+ this.noteLastFabricGone();
407
+ this.#decommissionedListener?.();
408
+ }
409
+ }
410
+ /**
411
+ * The fabric set has just emptied — which means matter.js has already
412
+ * factory-reset itself, whoever caused it.
413
+ *
414
+ * `CommissioningServer` watches `commissioned` and calls `doFactoryReset()`
415
+ * → `erase()` when the last fabric leaves. Our commissioning witness knows
416
+ * nothing about that, so leaving it set makes the very NEXT start see
417
+ * "witness says paired, stack says no fabrics" — the `fabricStorageLost`
418
+ * signature — and refuse to serve anything, telling the user their Matter
419
+ * storage was lost when in fact they deliberately unpaired their last
420
+ * ecosystem.
421
+ *
422
+ * Deliberately here rather than in {@link removeFabric}: §3.9 is only one of
423
+ * the ways to get here. An ecosystem that removes *us* from its side does it
424
+ * too, and that route never touches our command handler at all.
425
+ */
426
+ noteLastFabricGone() {
427
+ if (this.identity.commissionedAt === undefined) {
428
+ return;
429
+ }
430
+ this.log("The last fabric has gone — matter.js factory-resets itself when the fabric set empties, " +
431
+ "so the commissioning witness is being cleared to match. Without this the next start " +
432
+ "would refuse to serve endpoints, blaming lost storage for a deliberate unpairing.");
433
+ this.applyWitness(WARN_IDENTITY_WRITE, clearCommissioned(this.config.storagePath, this.identity, message => this.log(message)));
434
+ this.#drift = [];
435
+ }
436
+ /** Print the pairing codes the way an operator (and the plugin log) needs them. */
437
+ logPairing() {
438
+ const pairing = this.getPairing();
439
+ if (pairing.commissioned && !pairing.windowOpen) {
440
+ this.log(`Commissioned into ${pairing.fabrics.length} fabric(s); no commissioning window open`);
441
+ return;
442
+ }
443
+ this.log(`Manual pairing code: ${pairing.manualPairingCode}`);
444
+ this.log(`QR pairing code: ${pairing.qrPairingCode}`);
445
+ }
446
+ get server() {
447
+ if (this.#server === undefined) {
448
+ throw new ProtocolError(ErrorCode.internal, "Matter node not started");
449
+ }
450
+ return this.#server;
451
+ }
452
+ fabrics() {
453
+ const fabrics = this.server.state.commissioning.fabrics;
454
+ return Object.values(fabrics).map(fabric => ({
455
+ fabricIndex: Number(fabric.fabricIndex),
456
+ label: fabric.label,
457
+ vendorId: Number(fabric.rootVendorId),
458
+ }));
459
+ }
460
+ get registry() {
461
+ if (this.#registry === undefined) {
462
+ throw new ProtocolError(ErrorCode.internal, "Matter node not started");
463
+ }
464
+ return this.#registry;
465
+ }
466
+ getStatus() {
467
+ const endpoints = this.#registry?.summaries() ?? [];
468
+ return {
469
+ commissioned: this.server.lifecycle.isCommissioned,
470
+ fabrics: this.fabrics(),
471
+ endpointCount: endpoints.length,
472
+ endpoints,
473
+ // Whatever the last check found. NOT recomputed here: `get_status`
474
+ // is the plugin's watchdog tick, and a detector that ran per tick
475
+ // would re-emit `drift_detected` every 15s for one unchanged fault.
476
+ drift: [...this.#drift],
477
+ driftChecked: this.#endpointMap.checked,
478
+ warnings: [...this.#warnings.values(), ...this.#endpointMap.warnings],
479
+ };
480
+ }
481
+ /**
482
+ * Compare the live endpoint numbers against the persisted map (PRD §4.3).
483
+ *
484
+ * Run at the end of every operation that can create an endpoint, which is
485
+ * where a number can first be wrong. Report-only by contract: a mismatch
486
+ * populates `StatusReport.drift`, emits §5 `drift_detected` and changes
487
+ * nothing — the map keeps its baseline so the fault keeps being reported
488
+ * rather than being blessed into the truth on the next pass.
489
+ */
490
+ checkDrift() {
491
+ const live = (this.#registry?.summaries() ?? []).map(summary => ({
492
+ uniqueId: uniqueIdFor(summary.indigoDeviceId),
493
+ endpointNumber: summary.endpointNumber,
494
+ }));
495
+ const drift = this.#endpointMap.check(live);
496
+ this.#drift = drift;
497
+ if (drift.length === 0) {
498
+ return;
499
+ }
500
+ this.log(`ENDPOINT-NUMBER DRIFT: ${drift
501
+ .map(entry => `${entry.uniqueId} expected ${entry.expected}, got ${entry.actual}`)
502
+ .join("; ")}. Exported accessories may have swapped identities in paired ` +
503
+ "ecosystems; this is never repaired automatically.");
504
+ this.#driftListener?.(drift);
505
+ }
506
+ /** §3.1 — reconcile the live endpoint set, then answer with the new status. */
507
+ async reconcile(endpoints, replaceAll) {
508
+ try {
509
+ await this.registry.reconcile(endpoints, replaceAll);
510
+ }
511
+ finally {
512
+ // In a `finally` because a part-applied reconcile (registry.ts is
513
+ // explicit that there is no transaction across several `add`s) has
514
+ // still created endpoints, and those are exactly the numbers worth
515
+ // checking. Skipping the check on the failure path would leave the
516
+ // one case where drift is most likely un-looked-at.
517
+ this.checkDrift();
518
+ }
519
+ if (this.registry.size > ENDPOINT_COUNT_WARNING) {
520
+ this.log(`${this.registry.size} exported endpoints exceeds the ${ENDPOINT_COUNT_WARNING} advisory limit; ` +
521
+ "ecosystem per-home accessory caps will bite before memory does");
522
+ }
523
+ return this.getStatus();
524
+ }
525
+ /** §3.2 */
526
+ async upsertEndpoint(spec) {
527
+ try {
528
+ return await this.registry.upsert(spec);
529
+ }
530
+ finally {
531
+ this.checkDrift();
532
+ }
533
+ }
534
+ /**
535
+ * §3.3
536
+ *
537
+ * The drift check runs here too, even though a removal creates nothing.
538
+ * matter.js re-allocates while endpoints come and go, and a removal is one
539
+ * of the moments a *surviving* endpoint's number could differ from what the
540
+ * map says — leaving the one operation that reshapes the live set as the
541
+ * only one that never looked would have made that invisible until the next
542
+ * upsert happened to notice.
543
+ */
544
+ async removeEndpoint(indigoDeviceId) {
545
+ try {
546
+ return await this.registry.remove(indigoDeviceId);
547
+ }
548
+ finally {
549
+ this.checkDrift();
550
+ }
551
+ }
552
+ /** §3.4 */
553
+ async setState(indigoDeviceId, states) {
554
+ await this.registry.setState(indigoDeviceId, states);
555
+ }
556
+ /** §3.5 */
557
+ async setReachable(indigoDeviceId, reachable) {
558
+ await this.registry.setReachable(indigoDeviceId, reachable);
559
+ }
560
+ /**
561
+ * PRD §5.3 / Matter 1.5: a changed bridged-node set is a configuration
562
+ * change of the bridge. Bumping the root's `ConfigurationVersion` also
563
+ * covers the children — matter.js's own
564
+ * `BridgedDeviceBasicInformationServer.increaseConfigurationVersion`
565
+ * increments the root as well, so doing it once per batch is both cheaper
566
+ * and truer to "one logical change, one increment".
567
+ */
568
+ async bumpConfigurationVersion() {
569
+ const server = this.#server;
570
+ if (server === undefined) {
571
+ return;
572
+ }
573
+ await server.act(agent => agent.get(BasicInformationServer).increaseConfigurationVersion());
574
+ }
575
+ /** §5: the sink for `window_closed`, wired up by the protocol server. */
576
+ onWindowClosed(listener) {
577
+ this.#window.onClosed(listener);
578
+ }
579
+ /** §5: the sink for `command`. One listener, last registration wins. */
580
+ onCommand(listener) {
581
+ this.#command = listener;
582
+ }
583
+ /** §5: the sink for `drift_detected`. */
584
+ onDriftDetected(listener) {
585
+ this.#driftListener = listener;
586
+ }
587
+ /** §5: the sink for `fabrics_changed`. */
588
+ onFabricsChanged(listener) {
589
+ this.#fabricsListener = listener;
590
+ }
591
+ /** §5: the sink for `commissioned`. */
592
+ onCommissioned(listener) {
593
+ this.#commissionedListener = listener;
594
+ }
595
+ /** §5: the sink for `decommissioned`. */
596
+ onDecommissioned(listener) {
597
+ this.#decommissionedListener = listener;
598
+ }
599
+ /**
600
+ * §3.9 — drop one ecosystem's fabric.
601
+ *
602
+ * Driven through `FabricManager` rather than the `OperationalCredentials`
603
+ * cluster command for the same reason §3.8 avoids `AdministratorCommissioning`:
604
+ * `OperationalCredentialsServer.removeFabric` opens with `assertRemoteActor`,
605
+ * so it cannot be invoked from an offline agent at all.
606
+ *
607
+ * An index with no fabric behind it succeeds — but it succeeds as
608
+ * `{removed: false}`, and that distinction is the whole reason this returns
609
+ * anything. The plugin picks an index out of a `get_pairing` readout that is
610
+ * by definition a moment old, and the way it goes stale is the ecosystem
611
+ * unpairing itself, so "it is already gone" is the request being granted,
612
+ * not refused. Answering `{}` for both made the plugin tell the user "that
613
+ * ecosystem has been unpaired, every accessory has been removed" over a
614
+ * no-op — and, because the early return also skipped {@link noteFabrics},
615
+ * no `fabrics_changed` followed and the ghost row stayed in the plugin's
616
+ * cached list (which is what its picker is built from) forever. Both halves
617
+ * are fixed here: the outcome is reported, and the fabric set is
618
+ * re-published either way so a stale cache is corrected by the very request
619
+ * that tripped over it.
620
+ *
621
+ * **Removing the LAST fabric is a factory reset that we did not perform.**
622
+ * matter.js's `CommissioningServer` watches `commissioned` and, when the
623
+ * final fabric leaves, calls `doFactoryReset()` → `erase()` on its own. Our
624
+ * commissioning witness knows nothing about that, so leaving it set made
625
+ * the very next start see "witness says paired, no fabrics" — the
626
+ * `fabricStorageLost` signature — and refuse to serve anything, telling the
627
+ * user their Matter storage had been lost when in fact they had just
628
+ * unpaired their last ecosystem on purpose. {@link noteLastFabricGone}
629
+ * handles it, from {@link noteFabrics}, so the route where an ecosystem
630
+ * unpairs *us* is covered too.
631
+ */
632
+ async removeFabric(fabricIndex) {
633
+ const fabrics = this.server.env.get(FabricManager);
634
+ const fabric = fabrics.maybeFor(FabricIndex(fabricIndex));
635
+ if (fabric === undefined) {
636
+ this.log(`No fabric at index ${fabricIndex}; nothing to remove`);
637
+ // Re-publish the set the caller's index came from. Nothing changed
638
+ // HERE, but the asker demonstrably holds a list that says otherwise,
639
+ // and this is the only moment we know that. `"unchanged"` names the
640
+ // §5 `change` for what it is rather than borrowing an action word.
641
+ this.noteFabrics("unchanged");
642
+ return { removed: false, remaining: this.fabricCountOrNull() };
643
+ }
644
+ // `leave` rather than `delete`: it flushes subscriptions and emits the
645
+ // leave event first, which is how a controller learns it was removed
646
+ // instead of simply losing the node.
647
+ await fabric.leave();
648
+ // Inside a try: the leave has already happened and succeeded, and a
649
+ // read of server state that a self-reset is concurrently rebuilding
650
+ // must not turn a completed removal into a failed command.
651
+ let remaining;
652
+ try {
653
+ remaining = this.fabrics().length;
654
+ this.log(`Removed fabric ${fabricIndex} (${remaining} remaining)`);
655
+ }
656
+ catch (error) {
657
+ remaining = null;
658
+ this.log(`Removed fabric ${fabricIndex}; the remaining fabric count is unavailable ` +
659
+ `(${describeError(error)})`);
660
+ }
661
+ // Re-checked rather than assumed: `fabric.leave()` does not necessarily
662
+ // produce a `fabricsChanged` observation we saw, and the empty-set case
663
+ // is the one that matters (see noteLastFabricGone). Runs on the
664
+ // count-unavailable path too — it is precisely the last-fabric leave
665
+ // that makes the count unreadable, and that is the case whose witness
666
+ // must be cleared.
667
+ this.noteFabrics();
668
+ return { removed: true, remaining };
669
+ }
670
+ /** The fabric count, or `null` if server state cannot be read right now. */
671
+ fabricCountOrNull() {
672
+ try {
673
+ return this.fabrics().length;
674
+ }
675
+ catch {
676
+ return null;
677
+ }
678
+ }
679
+ /**
680
+ * §3.10 — wipe commissioning credentials and start advertising fresh.
681
+ *
682
+ * `ServerNode.erase()` is matter.js 0.17.8's factory reset: it takes the node
683
+ * offline, clears sessions, fabrics, events and the node's storage, then
684
+ * brings it back up if it was up — so re-advertising is not something we
685
+ * have to arrange.
686
+ *
687
+ * The endpoint map is **preserved by default**, which is the whole reason it
688
+ * lives outside the storage context `erase()` wipes: a user who resets to
689
+ * re-pair the same ecosystems should not have their accessory identities
690
+ * scrambled as a side effect. `preserveEndpointNumbers: false` is the
691
+ * explicit "the map itself is what is corrupt" path (PRD §7).
692
+ *
693
+ * The commissioning witness is cleared either way. Leaving it set would make
694
+ * the very next start refuse: witness says paired, `erase()` says no
695
+ * fabrics, which is exactly the fabric-storage-lost signature — and it would
696
+ * be the reset doing it to itself.
697
+ *
698
+ * The live endpoints are deliberately left alone. They are still the set the
699
+ * plugin asked for; what changed is who is allowed to see them.
700
+ */
701
+ async factoryReset(preserveEndpointNumbers) {
702
+ this.#window.clear();
703
+ this.log(`Factory reset: wiping commissioning credentials (endpoint numbers ` +
704
+ `${preserveEndpointNumbers ? "preserved" : "DISCARDED"})`);
705
+ await this.server.erase();
706
+ this.applyWitness(WARN_IDENTITY_WRITE, clearCommissioned(this.config.storagePath, this.identity, message => this.log(message)));
707
+ if (!preserveEndpointNumbers && !this.#endpointMap.discard()) {
708
+ // The in-memory map is empty either way, so the node behaves as
709
+ // asked — but the file the user asked to be rid of is still there,
710
+ // and the next start would load it as a baseline for numbers that
711
+ // no longer mean anything. `discard()` has always reported this;
712
+ // nobody was reading it, under a "Factory reset complete" line that
713
+ // said the opposite.
714
+ this.log(`The endpoint map file survived the reset — ${join(this.config.storagePath, ENDPOINT_MAP_FILE)} ` +
715
+ "could not be deleted, so the next start will load it as a baseline. Delete it by hand.");
716
+ }
717
+ this.#drift = [];
718
+ // A reset node is un-commissioned, so nothing it could have refused for
719
+ // is still true. Belt and braces rather than the main path: §1.1 keeps
720
+ // `factory_reset` OUT of the recovery commands (see RECOVERY_COMMANDS —
721
+ // §3.11 is the non-destructive exit and it already covers every refusal
722
+ // state), so a reset cannot normally be reached while refusing. It can
723
+ // still be reached in the other order — a refusal raised by a check
724
+ // between the erase and here — and leaving one set would be an outage
725
+ // with no remaining cause.
726
+ this.#refusal = undefined;
727
+ this.noteFabrics();
728
+ // §3.10 promises the witness is gone. A write can report success and
729
+ // still not be what the next start reads, and the failure mode is
730
+ // specific and nasty: a `commissionedAt` that survived an erase is the
731
+ // exact `fabricStorageLost` signature, so the next boot refuses to
732
+ // serve anything and blames lost storage for the reset the user asked
733
+ // for. Verified by reading it back rather than asserted.
734
+ //
735
+ // `readIdentity` alone cannot do the verifying: it answers `undefined`
736
+ // both for "the file is gone, so the witness certainly is" and for "the
737
+ // file is there and I cannot parse it", and reading the second as the
738
+ // first reports a verification that never happened over the one file
739
+ // that might still be carrying the marker.
740
+ const unverifiable = identityFileProblem(this.config.storagePath);
741
+ const onDisk = readIdentity(this.config.storagePath);
742
+ if (unverifiable !== undefined) {
743
+ const message = "Factory reset could NOT verify that the commissioning marker is gone, because " +
744
+ `${unverifiable}. If that file still carries "commissionedAt", the next start will ` +
745
+ "refuse to serve endpoints and report lost fabric storage — check it by hand.";
746
+ this.log(message);
747
+ this.#warnings.set(WARN_IDENTITY_WRITE, message);
748
+ }
749
+ else if (onDisk?.commissionedAt !== undefined) {
750
+ const message = "Factory reset could NOT clear the commissioning marker in identity.json — the next " +
751
+ "start will refuse to serve endpoints, reporting lost fabric storage. Delete " +
752
+ `"commissionedAt" from ${this.config.storagePath}/identity.json by hand.`;
753
+ this.log(message);
754
+ this.#warnings.set(WARN_IDENTITY_WRITE, message);
755
+ }
756
+ // What preservation actually bought, checked rather than claimed.
757
+ // `erase()` wipes matter.js's OWN allocation, so a preserved map is a
758
+ // baseline for numbers that are about to be handed out afresh — it
759
+ // preserves the ability to NOTICE, not the numbers (see §3.10). Running
760
+ // the detector here is what turns that into a statement in the log
761
+ // instead of a surprise on the next attach.
762
+ if (preserveEndpointNumbers) {
763
+ this.checkDrift();
764
+ this.log(this.#drift.length === 0
765
+ ? "Endpoint-number map preserved; no drift against the live endpoints yet — note " +
766
+ "that matter.js's own allocation was wiped by the reset, so drift is expected " +
767
+ "as endpoints are re-created and is what the preserved map exists to report"
768
+ : `Endpoint-number map preserved and ${this.#drift.length} endpoint(s) already ` +
769
+ "differ from it — that is the reset's own renumbering, reported exactly as " +
770
+ "designed; rebuild the map (§3.11) to accept it");
771
+ }
772
+ this.log("Factory reset complete; advertising for commissioning again");
773
+ this.logPairing();
774
+ }
775
+ /**
776
+ * §3.11 — adopt the live endpoint numbers as the new persisted map.
777
+ *
778
+ * The way out of the refuse-to-start state, and the only operation that
779
+ * discards a baseline. It renumbers nothing: by the time a user is asked to
780
+ * confirm this, whatever duplication a lost map implies has already happened
781
+ * in the ecosystems. What the rebuild changes is that the node stops
782
+ * refusing and starts telling the truth about the numbers that now exist.
783
+ *
784
+ * When the refusal was `fabricStorageLost` the witness is cleared too —
785
+ * confirming the rebuild is the user accepting that those pairings are gone,
786
+ * and leaving the witness set would refuse again on the next start for a
787
+ * loss they have already acknowledged.
788
+ */
789
+ async rebuildEndpointMap() {
790
+ // §3.11 is the way out of a MAP problem and nothing else. An unusable
791
+ // `identity.json` is a different loss with a different remedy (restore
792
+ // the file), and clearing the refusal for it would put a bridge serving
793
+ // endpoints under a `SerialNumber` nobody has ever seen — which is the
794
+ // exact harm the refusal exists to prevent.
795
+ if (this.#refusal === RefuseReason.identityUnreadable) {
796
+ throw new ProtocolError(ErrorCode.endpointMapInvalid, endpointMapInvalidDetails(`${RefuseReason.identityUnreadable}, and rebuilding the endpoint map cannot fix ` +
797
+ "that — the unusable file was moved aside as identity.json.unreadable-<stamp>; " +
798
+ "restore or repair it and restart the bridge"));
799
+ }
800
+ const live = (this.#registry?.summaries() ?? []).map(summary => ({
801
+ uniqueId: uniqueIdFor(summary.indigoDeviceId),
802
+ endpointNumber: summary.endpointNumber,
803
+ }));
804
+ if (!this.#endpointMap.rebuild(live)) {
805
+ // The refusal deliberately stays. Answering with a StatusReport here
806
+ // told the user "serving normally again" over a map that never
807
+ // reached the disk, so the next start would refuse for the same
808
+ // reason and the rebuild they confirmed would have to be confirmed
809
+ // again — after they had been told it worked.
810
+ throw new ProtocolError(ErrorCode.internal, "the rebuilt endpoint map could not be written, so nothing has changed — free some " +
811
+ `space in ${this.config.storagePath} and try again`);
812
+ }
813
+ this.#drift = [];
814
+ this.#refusal = undefined;
815
+ if (!this.server.lifecycle.isCommissioned) {
816
+ this.applyWitness(WARN_IDENTITY_WRITE, clearCommissioned(this.config.storagePath, this.identity, message => this.log(message)));
817
+ }
818
+ this.log(live.length === 0
819
+ ? "Endpoint map rebuilt from 0 live endpoints — the node was refusing, and §1.1 " +
820
+ "excludes attach from the recovery commands, so there were none to read. The " +
821
+ "baseline is now empty and the reconcile that follows records the real numbers; " +
822
+ "serving normally again"
823
+ : `Endpoint map rebuilt from ${live.length} live endpoint(s); serving normally again`);
824
+ return this.getStatus();
825
+ }
826
+ getPairing() {
827
+ const commissioned = this.server.lifecycle.isCommissioned;
828
+ const window = this.#window.current;
829
+ if (window !== undefined) {
830
+ return {
831
+ commissioned,
832
+ windowOpen: true,
833
+ windowExpiresAt: window.expiresAt.toISOString(),
834
+ manualPairingCode: window.manualPairingCode,
835
+ qrPairingCode: window.qrPairingCode,
836
+ fabrics: this.fabrics(),
837
+ };
838
+ }
839
+ if (!commissioned) {
840
+ // The never-commissioned initial state: the basic window is open and
841
+ // its codes are the persisted originals (§3.7).
842
+ const codes = this.server.state.commissioning.pairingCodes;
843
+ return {
844
+ commissioned: false,
845
+ windowOpen: true,
846
+ windowExpiresAt: null,
847
+ manualPairingCode: codes.manualPairingCode,
848
+ qrPairingCode: codes.qrPairingCode,
849
+ fabrics: this.fabrics(),
850
+ };
851
+ }
852
+ return {
853
+ commissioned: true,
854
+ windowOpen: false,
855
+ windowExpiresAt: null,
856
+ manualPairingCode: null,
857
+ qrPairingCode: null,
858
+ fabrics: this.fabrics(),
859
+ };
860
+ }
861
+ /**
862
+ * Open an enhanced commissioning window so a further ecosystem can pair.
863
+ * The passcode is ephemeral: matter.js holds only the PAKE verifier, so we
864
+ * derive and keep the display codes ourselves for the window's lifetime.
865
+ *
866
+ * This drives `DeviceCommissioner` rather than the `AdministratorCommissioning`
867
+ * cluster command, because in matter.js 0.17.8 that command asserts a remote
868
+ * authenticated session (it records the requesting fabric in
869
+ * `adminFabricIndex`) and therefore cannot be invoked from an offline agent.
870
+ * The consequence is that the cluster's `windowStatus`/`adminFabricIndex`
871
+ * attributes do not reflect a locally-opened window — a conformance gap for
872
+ * E7 to close, not something the pairing flow depends on.
873
+ */
874
+ async openCommissioningWindow(durationSeconds) {
875
+ // Before anything Matter-side: `allowEnhancedCommissioning` swaps the PASE
876
+ // commissioner and only then throws on a double-open, which would kill the
877
+ // code the user is already holding. See CommissioningWindow.assertClosed.
878
+ this.#window.assertClosed();
879
+ const server = this.server;
880
+ let discriminator;
881
+ let passcode;
882
+ try {
883
+ const crypto = server.env.get(Crypto);
884
+ passcode = PaseClient.generateRandomPasscode(crypto);
885
+ discriminator = PaseClient.generateRandomDiscriminator(crypto);
886
+ const salt = crypto.randomBytes(PBKDF_SALT_BYTES);
887
+ const verifier = await PaseClient.generatePakePasscodeVerifier(crypto, passcode, {
888
+ iterations: PBKDF_ITERATIONS,
889
+ salt,
890
+ });
891
+ const paseServer = PaseServer.fromVerificationValue(server.env.get(SessionManager), verifier, {
892
+ iterations: PBKDF_ITERATIONS,
893
+ salt,
894
+ });
895
+ await server.env.get(DeviceCommissioner).allowEnhancedCommissioning(discriminator, paseServer, () => {
896
+ this.#window.noteEnded();
897
+ });
898
+ }
899
+ catch (error) {
900
+ this.log(`Failed to open commissioning window: ${describeErrorWithStack(error)}`);
901
+ throw new ProtocolError(ErrorCode.commissioningWindowFailed, describeError(error));
902
+ }
903
+ const manualPairingCode = ManualPairingCodeCodec.encode({ discriminator, passcode });
904
+ const qrPairingCode = QrPairingCodeCodec.encode([
905
+ {
906
+ version: 0,
907
+ vendorId: VENDOR_ID,
908
+ productId: PRODUCT_ID,
909
+ flowType: CommissioningFlowType.Standard,
910
+ discriminator,
911
+ passcode,
912
+ discoveryCapabilities: 0b100, // on IP network
913
+ },
914
+ ]);
915
+ // DeviceCommissioner *does* build a STANDARD_COMMISSIONING_TIMEOUT timer
916
+ // in `#enterCommissioningMode`, but never calls `.start()` on it — a
917
+ // matter.js 0.17.8 bug — so nothing on the Matter side would ever close
918
+ // this window. Ours is the only timer. If upstream fixes that, the two
919
+ // race, which is why we cap durationSeconds at Matter's own 900s maximum:
920
+ // whichever fires first, the outcome is the same.
921
+ const expiresAt = this.#window.open(durationSeconds, manualPairingCode, qrPairingCode);
922
+ return { manualPairingCode, qrPairingCode, windowExpiresAt: expiresAt.toISOString() };
923
+ }
924
+ /** End the Matter-side window after ours expired. Never throws. */
925
+ endMatterCommissioning() {
926
+ const server = this.#server;
927
+ if (server === undefined) {
928
+ return;
929
+ }
930
+ void server.env
931
+ .get(DeviceCommissioner)
932
+ .endCommissioning()
933
+ .catch((error) => this.log(`Failed to end commissioning: ${describeError(error)}`));
934
+ }
935
+ async close() {
936
+ this.#window.clear();
937
+ const server = this.#server;
938
+ this.#server = undefined;
939
+ this.#registry?.close();
940
+ this.#registry = undefined;
941
+ if (server !== undefined) {
942
+ await server.close();
943
+ }
944
+ }
945
+ }
946
+ //# sourceMappingURL=node.js.map