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.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Persisted bridge identity.
3
+ *
4
+ * The install id, commissioning passcode and discriminator are generated once
5
+ * and kept in `identity.json` **outside** matter.js's own storage context, so a
6
+ * future factory reset (which wipes that context) cannot silently change the
7
+ * serial number a paired ecosystem remembers us by.
8
+ *
9
+ * Stdlib only — no matter.js import — so this is cheap to test.
10
+ */
11
+ /** Inclusive passcode bounds. Matter core spec §5.1.1.6. */
12
+ export declare const PASSCODE_MIN = 1;
13
+ export declare const PASSCODE_MAX = 99999998;
14
+ /**
15
+ * Trivial passcodes that must never be used. Matter core spec §5.1.7.1.
16
+ * `0` is listed there too and is outside {@link PASSCODE_MIN}, but a persisted
17
+ * file can still carry it, so it is named here rather than left to the bounds.
18
+ */
19
+ export declare const INVALID_PASSCODES: readonly number[];
20
+ /** The discriminator is 12 bits. */
21
+ export declare const DISCRIMINATOR_MAX = 4095;
22
+ export interface BridgeIdentity {
23
+ /** Stable install id; seeds `serialNumber` and `uniqueId`. */
24
+ installId: string;
25
+ /** Matter setup passcode for the initial (basic) commissioning window. */
26
+ passcode: number;
27
+ /** 12-bit commissioning discriminator. */
28
+ discriminator: number;
29
+ /**
30
+ * ISO 8601 UTC instant this bridge first observed a fabric, or absent if it
31
+ * never has (E5).
32
+ *
33
+ * The witness for PRD §7's "storage missing but previously commissioned".
34
+ * It has to live *here* rather than in matter.js's storage, because the
35
+ * whole failure it describes is matter.js's storage having vanished: a node
36
+ * whose fabrics are gone cannot tell "never paired" from "paired, then the
37
+ * fabric directory was lost" from anything inside the directory that is
38
+ * missing. Absent on identities written before E5, which reads — correctly
39
+ * — as "no evidence of commissioning", so an upgrade never refuses to start.
40
+ */
41
+ commissionedAt?: string;
42
+ }
43
+ /** True for a passcode inside the legal range and not on the trivial list. */
44
+ export declare function isValidPasscode(passcode: number): boolean;
45
+ /** A cryptographically random passcode that satisfies {@link isValidPasscode}. */
46
+ export declare function generatePasscode(): number;
47
+ /** A cryptographically random 12-bit discriminator. */
48
+ export declare function generateDiscriminator(): number;
49
+ /**
50
+ * Write JSON atomically: a temp file in the *same* directory (so the rename
51
+ * stays within one filesystem and is therefore atomic), then `rename`.
52
+ *
53
+ * A crash mid-write must never leave a half-written file behind, because a
54
+ * half-written file reads as corrupt — and for both files that go through here
55
+ * (`identity.json` and E5's `endpoint-map.json`) "corrupt" is the state that
56
+ * costs a user every accessory they have paired. Exported so the endpoint map
57
+ * is written the same way rather than by a second copy of this.
58
+ */
59
+ export declare function writeJsonAtomic(file: string, value: unknown): void;
60
+ /**
61
+ * Why the identity file that is *there* cannot be used, ignoring any
62
+ * quarantined siblings — `undefined` when it is fine **or absent**.
63
+ *
64
+ * The narrow half of {@link identityProblem}, for the one caller that must not
65
+ * confuse "there is no file" with "there is a file I cannot read": §3.10's
66
+ * factory reset reads this back to confirm the commissioning witness is gone,
67
+ * and an absent file means it certainly is.
68
+ */
69
+ export declare function identityFileProblem(storagePath: string): string | undefined;
70
+ /**
71
+ * Why this storage directory cannot hand back a usable identity, or
72
+ * `undefined` when it can (or when this is a genuine first run).
73
+ *
74
+ * This is the E5 half of {@link loadOrCreateIdentity}'s replace-it behaviour,
75
+ * split out rather than folded in so the mint path stays exactly what it was.
76
+ * The two answers must drive opposite decisions: a *missing* identity is a
77
+ * first run and minting is the only thing to do, while a *present but corrupt*
78
+ * one belongs to an install that may well be paired, and minting over it
79
+ * changes the `SerialNumber` and `UniqueID` every ecosystem remembers us by —
80
+ * silently un-pairing the lot. `main.ts` calls this first and refuses to serve
81
+ * endpoints when it answers, which is the same loud-refusal posture PRD §7
82
+ * requires of a lost endpoint map.
83
+ *
84
+ * **A quarantined sibling counts, which is what makes the refusal survive a
85
+ * restart.** The first start over an unusable file moves it to
86
+ * `identity.json.unreadable-<stamp>` and mints a replacement in memory only —
87
+ * so the *second* start finds no `identity.json` at all, and reading that as a
88
+ * first run would mint AND WRITE one, serving under a `SerialNumber` no paired
89
+ * ecosystem has ever seen, with a routine first-run log line to show for it.
90
+ * The refusal has to last until a human resolves it, and the evidence that one
91
+ * has not is the marker still lying there.
92
+ */
93
+ export declare function identityProblem(storagePath: string): string | undefined;
94
+ /**
95
+ * The outcome of moving the commissioning witness.
96
+ *
97
+ * The identity is still returned — the caller has to keep using one whatever
98
+ * happened — but `persisted` is now an answer rather than a silence. A caller
99
+ * that reports success over a witness that never reached disk is describing a
100
+ * different bridge from the one that will boot next: `factory_reset` leaving
101
+ * `commissionedAt` behind makes the very next start refuse with
102
+ * `fabricStorageLost`, blaming lost storage for the reset the user asked for.
103
+ */
104
+ export interface WitnessWrite {
105
+ identity: BridgeIdentity;
106
+ /** False when the change was made in memory only. */
107
+ persisted: boolean;
108
+ /** Why it did not reach disk, when it did not. */
109
+ problem?: string;
110
+ }
111
+ /**
112
+ * Record that this bridge has been commissioned, if it is not recorded already.
113
+ *
114
+ * Called the first time a fabric is observed. Returns the identity to keep
115
+ * using — the same object when nothing needed writing, so the caller can hold
116
+ * one reference. A write failure is reported and **not** thrown: losing the
117
+ * witness degrades a future refuse-to-start into a silent re-init, which is
118
+ * bad, but failing the commissioning that just succeeded is worse and
119
+ * immediate. It is reported to the caller as well as to the log, because the
120
+ * log in this milestone is a terminal somebody closed (§4.3 `warnings`).
121
+ */
122
+ export declare function markCommissioned(storagePath: string, identity: BridgeIdentity, log?: (message: string) => void, now?: () => Date): WitnessWrite;
123
+ /**
124
+ * Drop the commissioning witness — the §3.10 factory-reset counterpart of
125
+ * {@link markCommissioned}. Without this a reset node would start once, see no
126
+ * fabrics against a set `commissionedAt`, and refuse to serve anything on the
127
+ * grounds that its own reset had lost the fabric storage.
128
+ */
129
+ export declare function clearCommissioned(storagePath: string, identity: BridgeIdentity, log?: (message: string) => void): WitnessWrite;
130
+ /**
131
+ * `identity.json` exactly as it is on disk right now, or `undefined` when it is
132
+ * absent or unusable.
133
+ *
134
+ * The verification half of {@link clearCommissioned}: §3.10 promises the
135
+ * witness is gone, and the only way to say that truthfully is to go and look.
136
+ * A write can report success and still not be what the next start reads.
137
+ */
138
+ export declare function readIdentity(storagePath: string): BridgeIdentity | undefined;
139
+ /** Fresh random identity values. Pure — nothing is written. */
140
+ export declare function mintIdentity(): BridgeIdentity;
141
+ /**
142
+ * Move an unusable `identity.json` aside instead of writing over it (E5).
143
+ *
144
+ * This file holds the `SerialNumber` and `UniqueID` every paired ecosystem
145
+ * remembers us by. When it cannot be parsed, the *last* thing to do is replace
146
+ * it: the bytes on disk may be a truncation, a stray edit or a half-finished
147
+ * copy that a human can repair, and they are the only surviving record of an
148
+ * identity that cannot be regenerated. Renaming rather than deleting means the
149
+ * refusal that follows is recoverable; minting over it was not.
150
+ *
151
+ * Returns where it went, or `undefined` if there was nothing to move (or the
152
+ * move itself failed — which is reported, not thrown, because the node is about
153
+ * to refuse to serve endpoints either way).
154
+ */
155
+ export declare function quarantineIdentity(storagePath: string, log?: (message: string) => void, now?: () => Date): string | undefined;
156
+ /**
157
+ * Read `identity.json` from {@link storagePath}, creating it (and the directory)
158
+ * with freshly randomised values on first run.
159
+ *
160
+ * **Only ever called when there is no usable file to lose.** `main.ts` calls
161
+ * {@link identityProblem} first, and a present-but-unusable file goes down the
162
+ * {@link quarantineIdentity} + {@link mintIdentity} path instead, which writes
163
+ * nothing. The `problem !== undefined` branch below therefore survives only for
164
+ * the race where the file becomes unreadable between those two reads — a case
165
+ * where there is no original left to preserve anyway.
166
+ */
167
+ export declare function loadOrCreateIdentity(storagePath: string, log?: (message: string) => void): BridgeIdentity;
168
+ /**
169
+ * Matter `SerialNumber` is capped at 32 characters, so the UUID is used with its
170
+ * dashes stripped. Matter requires `UniqueID` and `SerialNumber` to differ, so
171
+ * the node's UniqueID takes the full value and this takes the first half.
172
+ */
173
+ export declare function serialNumberFor(identity: BridgeIdentity): string;
174
+ /** The root node's Matter `UniqueID` — distinct from {@link serialNumberFor}. */
175
+ export declare function nodeUniqueIdFor(identity: BridgeIdentity): string;
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Persisted bridge identity.
3
+ *
4
+ * The install id, commissioning passcode and discriminator are generated once
5
+ * and kept in `identity.json` **outside** matter.js's own storage context, so a
6
+ * future factory reset (which wipes that context) cannot silently change the
7
+ * serial number a paired ecosystem remembers us by.
8
+ *
9
+ * Stdlib only — no matter.js import — so this is cheap to test.
10
+ */
11
+ import { randomInt, randomUUID } from "node:crypto";
12
+ import { mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { describeError } from "./protocol.js";
15
+ /** Inclusive passcode bounds. Matter core spec §5.1.1.6. */
16
+ export const PASSCODE_MIN = 1;
17
+ export const PASSCODE_MAX = 99_999_998;
18
+ /**
19
+ * Trivial passcodes that must never be used. Matter core spec §5.1.7.1.
20
+ * `0` is listed there too and is outside {@link PASSCODE_MIN}, but a persisted
21
+ * file can still carry it, so it is named here rather than left to the bounds.
22
+ */
23
+ export const INVALID_PASSCODES = [
24
+ 0, 11111111, 22222222, 33333333, 44444444, 55555555, 66666666, 77777777, 88888888, 99999999, 12345678, 87654321,
25
+ ];
26
+ /** The discriminator is 12 bits. */
27
+ export const DISCRIMINATOR_MAX = 0xfff;
28
+ const IDENTITY_FILE = "identity.json";
29
+ /**
30
+ * What {@link quarantineIdentity} names the files it moves aside.
31
+ *
32
+ * Shared with {@link identityProblem} on purpose: the refusal is only sticky
33
+ * because it can recognise its own leavings, and two independently written
34
+ * copies of this string would drift apart in exactly the release where the
35
+ * refusal stopped firing and nobody noticed.
36
+ */
37
+ const QUARANTINE_PREFIX = `${IDENTITY_FILE}.unreadable-`;
38
+ /** True for a passcode inside the legal range and not on the trivial list. */
39
+ export function isValidPasscode(passcode) {
40
+ if (!Number.isInteger(passcode) || passcode < PASSCODE_MIN || passcode > PASSCODE_MAX) {
41
+ return false;
42
+ }
43
+ return !INVALID_PASSCODES.includes(passcode);
44
+ }
45
+ /** A cryptographically random passcode that satisfies {@link isValidPasscode}. */
46
+ export function generatePasscode() {
47
+ for (;;) {
48
+ const candidate = randomInt(PASSCODE_MIN, PASSCODE_MAX + 1);
49
+ if (isValidPasscode(candidate)) {
50
+ return candidate;
51
+ }
52
+ }
53
+ }
54
+ /** A cryptographically random 12-bit discriminator. */
55
+ export function generateDiscriminator() {
56
+ return randomInt(0, DISCRIMINATOR_MAX + 1);
57
+ }
58
+ function isUsableIdentity(value) {
59
+ if (typeof value !== "object" || value === null) {
60
+ return false;
61
+ }
62
+ const candidate = value;
63
+ return (typeof candidate.installId === "string" &&
64
+ candidate.installId.length > 0 &&
65
+ typeof candidate.passcode === "number" &&
66
+ isValidPasscode(candidate.passcode) &&
67
+ typeof candidate.discriminator === "number" &&
68
+ Number.isInteger(candidate.discriminator) &&
69
+ candidate.discriminator >= 0 &&
70
+ candidate.discriminator <= DISCRIMINATOR_MAX);
71
+ }
72
+ function isNotFound(error) {
73
+ return error?.code === "ENOENT";
74
+ }
75
+ /**
76
+ * Write JSON atomically: a temp file in the *same* directory (so the rename
77
+ * stays within one filesystem and is therefore atomic), then `rename`.
78
+ *
79
+ * A crash mid-write must never leave a half-written file behind, because a
80
+ * half-written file reads as corrupt — and for both files that go through here
81
+ * (`identity.json` and E5's `endpoint-map.json`) "corrupt" is the state that
82
+ * costs a user every accessory they have paired. Exported so the endpoint map
83
+ * is written the same way rather than by a second copy of this.
84
+ */
85
+ export function writeJsonAtomic(file, value) {
86
+ const temp = `${file}.${process.pid}.tmp`;
87
+ try {
88
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
89
+ renameSync(temp, file);
90
+ }
91
+ catch (error) {
92
+ try {
93
+ unlinkSync(temp);
94
+ }
95
+ catch {
96
+ // Best effort: the temp file may never have been created.
97
+ }
98
+ throw error;
99
+ }
100
+ }
101
+ function writeIdentity(file, identity) {
102
+ writeJsonAtomic(file, identity);
103
+ }
104
+ function inspectIdentityFile(storagePath) {
105
+ const file = join(storagePath, IDENTITY_FILE);
106
+ try {
107
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
108
+ return isUsableIdentity(parsed)
109
+ ? { kind: "usable" }
110
+ : {
111
+ kind: "unusable",
112
+ problem: `${file} is present but not a usable identity (missing or out-of-range fields)`,
113
+ };
114
+ }
115
+ catch (error) {
116
+ return isNotFound(error)
117
+ ? { kind: "absent" }
118
+ : { kind: "unusable", problem: `${file} is unreadable (${describeError(error)})` };
119
+ }
120
+ }
121
+ /**
122
+ * Why the identity file that is *there* cannot be used, ignoring any
123
+ * quarantined siblings — `undefined` when it is fine **or absent**.
124
+ *
125
+ * The narrow half of {@link identityProblem}, for the one caller that must not
126
+ * confuse "there is no file" with "there is a file I cannot read": §3.10's
127
+ * factory reset reads this back to confirm the commissioning witness is gone,
128
+ * and an absent file means it certainly is.
129
+ */
130
+ export function identityFileProblem(storagePath) {
131
+ const state = inspectIdentityFile(storagePath);
132
+ return state.kind === "unusable" ? state.problem : undefined;
133
+ }
134
+ /**
135
+ * Why this storage directory cannot hand back a usable identity, or
136
+ * `undefined` when it can (or when this is a genuine first run).
137
+ *
138
+ * This is the E5 half of {@link loadOrCreateIdentity}'s replace-it behaviour,
139
+ * split out rather than folded in so the mint path stays exactly what it was.
140
+ * The two answers must drive opposite decisions: a *missing* identity is a
141
+ * first run and minting is the only thing to do, while a *present but corrupt*
142
+ * one belongs to an install that may well be paired, and minting over it
143
+ * changes the `SerialNumber` and `UniqueID` every ecosystem remembers us by —
144
+ * silently un-pairing the lot. `main.ts` calls this first and refuses to serve
145
+ * endpoints when it answers, which is the same loud-refusal posture PRD §7
146
+ * requires of a lost endpoint map.
147
+ *
148
+ * **A quarantined sibling counts, which is what makes the refusal survive a
149
+ * restart.** The first start over an unusable file moves it to
150
+ * `identity.json.unreadable-<stamp>` and mints a replacement in memory only —
151
+ * so the *second* start finds no `identity.json` at all, and reading that as a
152
+ * first run would mint AND WRITE one, serving under a `SerialNumber` no paired
153
+ * ecosystem has ever seen, with a routine first-run log line to show for it.
154
+ * The refusal has to last until a human resolves it, and the evidence that one
155
+ * has not is the marker still lying there.
156
+ */
157
+ export function identityProblem(storagePath) {
158
+ const state = inspectIdentityFile(storagePath);
159
+ if (state.kind !== "absent") {
160
+ return state.kind === "unusable" ? state.problem : undefined;
161
+ }
162
+ return quarantinedIdentityProblem(storagePath);
163
+ }
164
+ /**
165
+ * The refusal a leftover quarantine marker carries, naming the way out.
166
+ *
167
+ * A listing we cannot take is deliberately *not* a refusal: this function is
168
+ * part of a never-throwing guard, and inventing one out of a failed `readdir`
169
+ * would block a first run over a transient permissions problem — the opposite
170
+ * of the trade the refusal is making everywhere else.
171
+ */
172
+ function quarantinedIdentityProblem(storagePath) {
173
+ let markers;
174
+ try {
175
+ markers = readdirSync(storagePath)
176
+ .filter(name => name.startsWith(QUARANTINE_PREFIX))
177
+ .sort();
178
+ }
179
+ catch {
180
+ return undefined;
181
+ }
182
+ if (markers.length === 0) {
183
+ return undefined;
184
+ }
185
+ return (`${join(storagePath, IDENTITY_FILE)} is missing, but ${markers.length === 1 ? "a" : markers.length} ` +
186
+ `quarantined identit${markers.length === 1 ? "y" : "ies"} (${markers.join(", ")}) still ` +
187
+ `sit${markers.length === 1 ? "s" : ""} beside it — an earlier start could not read the identity ` +
188
+ `and moved it aside. Restore or repair one of them as ${IDENTITY_FILE} in ${storagePath} and ` +
189
+ "restart. Deleting them all is the deliberate \"start fresh as a brand-new bridge\" choice, and " +
190
+ "it loses every pairing this bridge already has.");
191
+ }
192
+ /**
193
+ * Record that this bridge has been commissioned, if it is not recorded already.
194
+ *
195
+ * Called the first time a fabric is observed. Returns the identity to keep
196
+ * using — the same object when nothing needed writing, so the caller can hold
197
+ * one reference. A write failure is reported and **not** thrown: losing the
198
+ * witness degrades a future refuse-to-start into a silent re-init, which is
199
+ * bad, but failing the commissioning that just succeeded is worse and
200
+ * immediate. It is reported to the caller as well as to the log, because the
201
+ * log in this milestone is a terminal somebody closed (§4.3 `warnings`).
202
+ */
203
+ export function markCommissioned(storagePath, identity, log = () => { }, now = () => new Date()) {
204
+ if (identity.commissionedAt !== undefined) {
205
+ return { identity, persisted: true };
206
+ }
207
+ const updated = { ...identity, commissionedAt: now().toISOString() };
208
+ try {
209
+ writeIdentity(join(storagePath, IDENTITY_FILE), updated);
210
+ }
211
+ catch (error) {
212
+ const problem = `Could not record the commissioning marker in identity.json: ${describeError(error)}`;
213
+ log(problem);
214
+ return { identity: updated, persisted: false, problem };
215
+ }
216
+ return { identity: updated, persisted: true };
217
+ }
218
+ /**
219
+ * Drop the commissioning witness — the §3.10 factory-reset counterpart of
220
+ * {@link markCommissioned}. Without this a reset node would start once, see no
221
+ * fabrics against a set `commissionedAt`, and refuse to serve anything on the
222
+ * grounds that its own reset had lost the fabric storage.
223
+ */
224
+ export function clearCommissioned(storagePath, identity, log = () => { }) {
225
+ if (identity.commissionedAt === undefined) {
226
+ return { identity, persisted: true };
227
+ }
228
+ const { commissionedAt: _dropped, ...rest } = identity;
229
+ try {
230
+ writeIdentity(join(storagePath, IDENTITY_FILE), rest);
231
+ }
232
+ catch (error) {
233
+ const problem = `Could not clear the commissioning marker in identity.json: ${describeError(error)}`;
234
+ log(problem);
235
+ return { identity: rest, persisted: false, problem };
236
+ }
237
+ return { identity: rest, persisted: true };
238
+ }
239
+ /**
240
+ * `identity.json` exactly as it is on disk right now, or `undefined` when it is
241
+ * absent or unusable.
242
+ *
243
+ * The verification half of {@link clearCommissioned}: §3.10 promises the
244
+ * witness is gone, and the only way to say that truthfully is to go and look.
245
+ * A write can report success and still not be what the next start reads.
246
+ */
247
+ export function readIdentity(storagePath) {
248
+ try {
249
+ const parsed = JSON.parse(readFileSync(join(storagePath, IDENTITY_FILE), "utf8"));
250
+ return isUsableIdentity(parsed) ? parsed : undefined;
251
+ }
252
+ catch {
253
+ return undefined;
254
+ }
255
+ }
256
+ /** Fresh random identity values. Pure — nothing is written. */
257
+ export function mintIdentity() {
258
+ return {
259
+ installId: randomUUID(),
260
+ passcode: generatePasscode(),
261
+ discriminator: generateDiscriminator(),
262
+ };
263
+ }
264
+ /**
265
+ * Move an unusable `identity.json` aside instead of writing over it (E5).
266
+ *
267
+ * This file holds the `SerialNumber` and `UniqueID` every paired ecosystem
268
+ * remembers us by. When it cannot be parsed, the *last* thing to do is replace
269
+ * it: the bytes on disk may be a truncation, a stray edit or a half-finished
270
+ * copy that a human can repair, and they are the only surviving record of an
271
+ * identity that cannot be regenerated. Renaming rather than deleting means the
272
+ * refusal that follows is recoverable; minting over it was not.
273
+ *
274
+ * Returns where it went, or `undefined` if there was nothing to move (or the
275
+ * move itself failed — which is reported, not thrown, because the node is about
276
+ * to refuse to serve endpoints either way).
277
+ */
278
+ export function quarantineIdentity(storagePath, log = () => { }, now = () => new Date()) {
279
+ const file = join(storagePath, IDENTITY_FILE);
280
+ const stamp = now().toISOString().replace(/[:.]/g, "-");
281
+ const target = join(storagePath, `${QUARANTINE_PREFIX}${stamp}`);
282
+ try {
283
+ renameSync(file, target);
284
+ return target;
285
+ }
286
+ catch (error) {
287
+ if (!isNotFound(error)) {
288
+ log(`Could not move the unusable identity aside: ${describeError(error)}`);
289
+ }
290
+ return undefined;
291
+ }
292
+ }
293
+ /**
294
+ * Read `identity.json` from {@link storagePath}, creating it (and the directory)
295
+ * with freshly randomised values on first run.
296
+ *
297
+ * **Only ever called when there is no usable file to lose.** `main.ts` calls
298
+ * {@link identityProblem} first, and a present-but-unusable file goes down the
299
+ * {@link quarantineIdentity} + {@link mintIdentity} path instead, which writes
300
+ * nothing. The `problem !== undefined` branch below therefore survives only for
301
+ * the race where the file becomes unreadable between those two reads — a case
302
+ * where there is no original left to preserve anyway.
303
+ */
304
+ export function loadOrCreateIdentity(storagePath, log = () => { }) {
305
+ mkdirSync(storagePath, { recursive: true });
306
+ const file = join(storagePath, IDENTITY_FILE);
307
+ // `undefined` means "no file at all"; anything else is why we are replacing
308
+ // a file that does exist — the distinction E5 turns into refuse-to-start.
309
+ let problem;
310
+ try {
311
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
312
+ if (isUsableIdentity(parsed)) {
313
+ log(`Loaded bridge identity from ${file}`);
314
+ return parsed;
315
+ }
316
+ problem = "present but not a usable identity (missing or out-of-range fields)";
317
+ }
318
+ catch (error) {
319
+ problem = isNotFound(error) ? undefined : `unreadable (${describeError(error)})`;
320
+ }
321
+ if (problem === undefined) {
322
+ log(`No identity at ${file}; minting new bridge identity`);
323
+ }
324
+ else {
325
+ log(`Replacing bridge identity at ${file}: ${problem}`);
326
+ }
327
+ const identity = mintIdentity();
328
+ writeIdentity(file, identity);
329
+ return identity;
330
+ }
331
+ /**
332
+ * Matter `SerialNumber` is capped at 32 characters, so the UUID is used with its
333
+ * dashes stripped. Matter requires `UniqueID` and `SerialNumber` to differ, so
334
+ * the node's UniqueID takes the full value and this takes the first half.
335
+ */
336
+ export function serialNumberFor(identity) {
337
+ return identity.installId.replace(/-/g, "").slice(0, 16);
338
+ }
339
+ /** The root node's Matter `UniqueID` — distinct from {@link serialNumberFor}. */
340
+ export function nodeUniqueIdFor(identity) {
341
+ return identity.installId.replace(/-/g, "").slice(0, 32);
342
+ }
343
+ //# sourceMappingURL=storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACtG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAEjC,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C,4DAA4D;AAC5D,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC;AAC9B,MAAM,CAAC,MAAM,YAAY,GAAG,UAAU,CAAC;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AC;AAED,iFAAiF;AACjF,MAAM,UAAU,eAAe,CAAC,QAAwB;IACpD,OAAO,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAC7D,CAAC"}
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The enhanced-commissioning-window state machine (§3.8).
3
+ *
4
+ * Extracted from {@link BridgeNode} so the bookkeeping — double-open refusal,
5
+ * expiry, and which reason a `window_closed` event carries — is unit-testable
6
+ * without a Matter stack. Timer and clock are injected for the same reason.
7
+ */
8
+ import { type WindowClosedReason } from "./protocol.js";
9
+ /** Cancels a scheduled expiry. */
10
+ export type Cancel = () => void;
11
+ /** Schedules `callback` `ms` from now and returns its canceller. */
12
+ export type Scheduler = (callback: () => void, ms: number) => Cancel;
13
+ /** Real timers, unref'd: an open window must never keep the process alive. */
14
+ export declare const defaultScheduler: Scheduler;
15
+ export interface OpenWindow {
16
+ expiresAt: Date;
17
+ manualPairingCode: string;
18
+ qrPairingCode: string;
19
+ }
20
+ export interface CommissioningWindowOptions {
21
+ schedule?: Scheduler;
22
+ now?: () => number;
23
+ log?: (message: string) => void;
24
+ /**
25
+ * Ends the Matter-side window when our expiry timer fires first. Anything
26
+ * it throws is caught and logged — a timer callback must never rethrow.
27
+ */
28
+ onExpire?: () => void;
29
+ }
30
+ export declare class CommissioningWindow {
31
+ #private;
32
+ constructor(options?: CommissioningWindowOptions);
33
+ /** Register the `window_closed` sink (§5). Last registration wins. */
34
+ onClosed(listener: (reason: WindowClosedReason) => void): void;
35
+ get isOpen(): boolean;
36
+ /** The live window, or `undefined` when none is open. */
37
+ get current(): Readonly<OpenWindow> | undefined;
38
+ /**
39
+ * Refuse a second window *before* anything Matter-side is touched.
40
+ *
41
+ * matter.js 0.17.8's `DeviceCommissioner.allowEnhancedCommissioning` installs
42
+ * the new PASE commissioner and only then throws on the double-open, so a
43
+ * refusal that reaches the stack has already invalidated the code the user
44
+ * is holding. Guarding here keeps the open window intact.
45
+ */
46
+ assertClosed(): void;
47
+ /** Record a freshly opened window and arm its expiry. */
48
+ open(durationSeconds: number, manualPairingCode: string, qrPairingCode: string): Date;
49
+ /**
50
+ * matter.js reports its window ended. Returns `false` when we had already
51
+ * closed ours — which is what keeps expiry from announcing twice, since the
52
+ * expiry path itself calls `endCommissioning()` and that fires this back.
53
+ */
54
+ noteEnded(): boolean;
55
+ /** Shutdown: drop the window without announcing a close. */
56
+ clear(): void;
57
+ }