@bom-pi/core 0.1.3 → 0.2.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.
@@ -1,10 +1,14 @@
1
- /** Offline pairing storage exercise. This module is not an authorization or restore mechanism. */
1
+ /** Offline pairing storage exercise. This module is not an authorization or restore mechanism.
2
+ * It also hosts the owner's M4 relay activation record: a durable off-by-default switch with the
3
+ * same single-writer, atomic, fail-closed discipline as the pairing record itself. */
2
4
  import { randomUUID } from "node:crypto";
3
5
  import { lstat, mkdir, open, readFile, rename, unlink, type FileHandle } from "node:fs/promises";
4
6
  import { join } from "node:path";
5
7
 
6
8
  const FILE = "pairing-storage.json";
7
9
  const LOCK = ".pairing-storage.lock";
10
+ const RELAY_FILE = "relay-switch.json";
11
+ const RELAY_LOCK = ".relay-switch.lock";
8
12
  const HEX_ID = /^[a-f0-9]{64}$/;
9
13
 
10
14
  type LockLease = { handle: FileHandle; identity: string };
@@ -94,11 +98,11 @@ async function syncDirectory(directory: string): Promise<void> {
94
98
  }
95
99
  }
96
100
 
97
- async function acquireLock(directory: string): Promise<LockLease> {
101
+ async function acquireLock(directory: string, lockFile: string): Promise<LockLease> {
98
102
  let handle: FileHandle;
99
103
 
100
104
  try {
101
- handle = await open(join(directory, LOCK), "wx", 0o600);
105
+ handle = await open(join(directory, lockFile), "wx", 0o600);
102
106
  } catch (error) {
103
107
  if ((error as NodeJS.ErrnoException).code === "EEXIST") {
104
108
  fail("writer lock exists; explicit recovery required");
@@ -123,10 +127,10 @@ async function acquireLock(directory: string): Promise<LockLease> {
123
127
  }
124
128
  }
125
129
 
126
- async function assertLock(directory: string, lock: LockLease): Promise<void> {
130
+ async function assertLock(directory: string, lockFile: string, lock: LockLease): Promise<void> {
127
131
  try {
128
132
  const owned = await lock.handle.stat();
129
- const present = await lstat(join(directory, LOCK));
133
+ const present = await lstat(join(directory, lockFile));
130
134
 
131
135
  if (
132
136
  !owned.isFile() ||
@@ -137,7 +141,7 @@ async function assertLock(directory: string, lock: LockLease): Promise<void> {
137
141
  owned.nlink !== 1 ||
138
142
  present.nlink !== 1 ||
139
143
  (process.getuid !== undefined && present.uid !== process.getuid()) ||
140
- (await readFile(join(directory, LOCK), "utf8")) !== lock.identity
144
+ (await readFile(join(directory, lockFile), "utf8")) !== lock.identity
141
145
  ) {
142
146
  fail("writer lock changed; explicit recovery required");
143
147
  }
@@ -146,16 +150,224 @@ async function assertLock(directory: string, lock: LockLease): Promise<void> {
146
150
  }
147
151
  }
148
152
 
149
- async function releaseLock(directory: string, lock: LockLease): Promise<void> {
153
+ async function releaseLock(directory: string, lockFile: string, lock: LockLease): Promise<void> {
150
154
  try {
151
- await assertLock(directory, lock);
152
- await unlink(join(directory, LOCK));
155
+ await assertLock(directory, lockFile, lock);
156
+ await unlink(join(directory, lockFile));
153
157
  await syncDirectory(directory);
154
158
  } finally {
155
159
  await lock.handle.close();
156
160
  }
157
161
  }
158
162
 
163
+ // ------------------------- M4 relay owner switch (§11/§16) -------------------------
164
+
165
+ /** The owner's explicit, durable M4 relay activation snapshot: only ever this record. There is
166
+ * deliberately no environment-variable or memory-only activation path, and the record carries no
167
+ * grant data — the GRANT switch is a separate, not-yet-implemented surface. */
168
+ export type RelaySwitchSnapshot = { version: 1; relay: { enabled: boolean } };
169
+
170
+ /** The switch-read seam relay lanes consume: a plain synchronous read of the durable record.
171
+ * Implementations must fail closed — anything other than a healthy, open record reads OFF. */
172
+ export type RelaySwitchRead = () => boolean;
173
+
174
+ function parseRelaySwitch(text: string): RelaySwitchSnapshot {
175
+ let value: unknown;
176
+
177
+ try {
178
+ value = JSON.parse(text);
179
+ } catch {
180
+ return fail("corrupt relay switch record");
181
+ }
182
+
183
+ const relay =
184
+ value !== null &&
185
+ typeof value === "object" &&
186
+ keys(value, ["version", "relay"]) &&
187
+ (value as RelaySwitchSnapshot).version === 1
188
+ ? (value as RelaySwitchSnapshot).relay
189
+ : null;
190
+
191
+ if (
192
+ relay === null ||
193
+ typeof relay !== "object" ||
194
+ !keys(relay, ["enabled"]) ||
195
+ typeof relay.enabled !== "boolean" ||
196
+ JSON.stringify(value) !== text
197
+ ) {
198
+ return fail("corrupt or unsupported relay switch record");
199
+ }
200
+
201
+ return value as RelaySwitchSnapshot;
202
+ }
203
+
204
+ /** One writer only; caller supplies an isolated directory. The switch is off-by-default, reads
205
+ * OFF when closed or uncertain, and never authorizes anything by being read. */
206
+ export class RelaySwitchStore {
207
+ private closed = false;
208
+ private writing = false;
209
+ private readonly lock: LockLease;
210
+ private readonly directory: string;
211
+ private record: RelaySwitchSnapshot;
212
+
213
+ private constructor(directory: string, record: RelaySwitchSnapshot, lock: LockLease) {
214
+ this.directory = directory;
215
+ this.record = record;
216
+ this.lock = lock;
217
+ }
218
+
219
+ static async create(directory: string): Promise<RelaySwitchStore> {
220
+ await mkdir(directory, { mode: 0o700 });
221
+ await checkDirectory(directory);
222
+
223
+ try {
224
+ await lstat(join(directory, RELAY_FILE));
225
+ fail("relay switch record already exists; cannot initialize over prior state");
226
+ } catch (error) {
227
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
228
+ throw error;
229
+ }
230
+ }
231
+
232
+ const lock = await acquireLock(directory, RELAY_LOCK);
233
+ const store = new RelaySwitchStore(
234
+ directory,
235
+ { version: 1, relay: { enabled: false } },
236
+ lock,
237
+ );
238
+
239
+ try {
240
+ await store.persist(store.record);
241
+ } catch (error) {
242
+ // Failed initialization is not safe to retry as a fresh store.
243
+ await lock.handle.close();
244
+
245
+ throw error;
246
+ }
247
+
248
+ return store;
249
+ }
250
+
251
+ static async open(directory: string): Promise<RelaySwitchStore> {
252
+ await checkDirectory(directory);
253
+ const lock = await acquireLock(directory, RELAY_LOCK);
254
+
255
+ try {
256
+ const file = join(directory, RELAY_FILE);
257
+ const stat = await lstat(file).catch(() =>
258
+ fail("missing or unreadable relay switch record"),
259
+ );
260
+
261
+ if (!stat.isFile() || (stat.mode & 0o777) !== 0o600) {
262
+ fail("relay switch record must be a private (0600) regular file");
263
+ }
264
+
265
+ // Parity with the pairing record: a re-owned record is never adopted.
266
+ if (process.getuid !== undefined && stat.uid !== process.getuid()) {
267
+ fail("relay switch record must be owned by the current user");
268
+ }
269
+
270
+ const record = parseRelaySwitch(
271
+ await readFile(file, "utf8").catch(() => fail("unreadable relay switch record")),
272
+ );
273
+
274
+ return new RelaySwitchStore(directory, record, lock);
275
+ } catch (error) {
276
+ await releaseLock(directory, RELAY_LOCK, lock);
277
+
278
+ throw error;
279
+ }
280
+ }
281
+
282
+ /** Release only this instance's lock; parity with PairingStorage.close. */
283
+ async close(): Promise<void> {
284
+ if (this.writing) {
285
+ fail("concurrent writer rejected");
286
+ }
287
+
288
+ if (this.closed) {
289
+ return;
290
+ }
291
+
292
+ this.closed = true;
293
+ await releaseLock(this.directory, RELAY_LOCK, this.lock);
294
+ }
295
+
296
+ /** The RelaySwitchRead seam: OFF unless the durable record of a healthy, open store says
297
+ * otherwise; a closed instance (clean stop or uncertain write) reads OFF again. */
298
+ enabled(): boolean {
299
+ return !this.closed && this.record.relay.enabled;
300
+ }
301
+
302
+ /** Secret-free record inspection. */
303
+ inspect(): RelaySwitchSnapshot {
304
+ return structuredClone(this.record);
305
+ }
306
+
307
+ /** Durably flips the switch: single-writer, atomic, fsync'd like every commit here. A failed
308
+ * write closes the instance — reads fail closed to OFF until an explicit restart recovery. */
309
+ async set(enabled: boolean): Promise<void> {
310
+ if (typeof enabled !== "boolean") {
311
+ fail("relay switch needs a boolean");
312
+ }
313
+
314
+ if (this.closed) {
315
+ fail("closed or uncertain relay switch store; restart recovery required");
316
+ }
317
+
318
+ if (this.writing) {
319
+ fail("concurrent writer rejected");
320
+ }
321
+
322
+ if (this.record.relay.enabled === enabled) {
323
+ return;
324
+ }
325
+
326
+ const next: RelaySwitchSnapshot = { version: 1, relay: { enabled } };
327
+
328
+ this.writing = true;
329
+
330
+ try {
331
+ await this.persist(next);
332
+ this.record = next;
333
+ } catch (error) {
334
+ // Rename may have succeeded while the directory fsync did not: never claim state.
335
+ this.closed = true;
336
+ await this.lock.handle.close();
337
+
338
+ throw error;
339
+ } finally {
340
+ this.writing = false;
341
+ }
342
+ }
343
+
344
+ private async persist(next: RelaySwitchSnapshot): Promise<void> {
345
+ const temp = join(this.directory, `.${RELAY_FILE}.${randomUUID()}.tmp`);
346
+ let handle: FileHandle | undefined;
347
+
348
+ try {
349
+ await assertLock(this.directory, RELAY_LOCK, this.lock);
350
+ handle = await open(temp, "wx", 0o600);
351
+ await handle.writeFile(JSON.stringify(next));
352
+ await handle.sync();
353
+ await handle.close();
354
+ handle = undefined;
355
+ await assertLock(this.directory, RELAY_LOCK, this.lock);
356
+ await rename(temp, join(this.directory, RELAY_FILE));
357
+ await assertLock(this.directory, RELAY_LOCK, this.lock);
358
+ await syncDirectory(this.directory);
359
+ await assertLock(this.directory, RELAY_LOCK, this.lock);
360
+ } finally {
361
+ await handle?.close();
362
+ await unlink(temp).catch((error: NodeJS.ErrnoException) => {
363
+ if (error.code !== "ENOENT") {
364
+ throw error;
365
+ }
366
+ });
367
+ }
368
+ }
369
+ }
370
+
159
371
  /** One writer only; caller supplies an isolated directory. No backup import or grant restore API. */
160
372
  export class PairingStorage {
161
373
  private closed = false;
@@ -205,7 +417,7 @@ export class PairingStorage {
205
417
  }
206
418
  }
207
419
 
208
- const lock = await acquireLock(directory);
420
+ const lock = await acquireLock(directory, LOCK);
209
421
  const store = new PairingStorage(
210
422
  directory,
211
423
  capacity,
@@ -241,7 +453,7 @@ export class PairingStorage {
241
453
  }
242
454
 
243
455
  await checkDirectory(directory);
244
- const lock = await acquireLock(directory);
456
+ const lock = await acquireLock(directory, LOCK);
245
457
 
246
458
  try {
247
459
  const file = join(directory, FILE);
@@ -273,7 +485,7 @@ export class PairingStorage {
273
485
  state.reserved.length > 0,
274
486
  );
275
487
  } catch (error) {
276
- await releaseLock(directory, lock);
488
+ await releaseLock(directory, LOCK, lock);
277
489
 
278
490
  throw error;
279
491
  }
@@ -290,7 +502,7 @@ export class PairingStorage {
290
502
  }
291
503
 
292
504
  this.closed = true;
293
- await releaseLock(this.directory, this.lock);
505
+ await releaseLock(this.directory, LOCK, this.lock);
294
506
  }
295
507
 
296
508
  /** Inspection never authorizes a restored grant. */
@@ -422,29 +634,29 @@ export class PairingStorage {
422
634
  let handle;
423
635
 
424
636
  try {
425
- await assertLock(this.directory, this.lock);
637
+ await assertLock(this.directory, LOCK, this.lock);
426
638
  await this.assertRecord(expected);
427
639
  // The 0700 directory assumes a trusted OS user. This detects accidental lock loss,
428
640
  // not malicious unlink/replacement in the small window between checks and writes.
429
- await assertLock(this.directory, this.lock);
641
+ await assertLock(this.directory, LOCK, this.lock);
430
642
  handle = await open(temp, "wx", 0o600);
431
643
  await handle.writeFile(JSON.stringify(next));
432
644
  this.fault?.("beforeFileSync");
433
- await assertLock(this.directory, this.lock);
645
+ await assertLock(this.directory, LOCK, this.lock);
434
646
  await handle.sync();
435
647
  await handle.close();
436
648
  handle = undefined;
437
649
  this.fault?.("beforeRename");
438
- await assertLock(this.directory, this.lock);
650
+ await assertLock(this.directory, LOCK, this.lock);
439
651
  await this.assertRecord(expected);
440
- await assertLock(this.directory, this.lock);
652
+ await assertLock(this.directory, LOCK, this.lock);
441
653
  await rename(temp, join(this.directory, FILE));
442
654
  this.fault?.("beforeDirSync");
443
- await assertLock(this.directory, this.lock);
655
+ await assertLock(this.directory, LOCK, this.lock);
444
656
  await syncDirectory(this.directory);
445
- await assertLock(this.directory, this.lock);
657
+ await assertLock(this.directory, LOCK, this.lock);
446
658
  await this.assertRecord(next);
447
- await assertLock(this.directory, this.lock);
659
+ await assertLock(this.directory, LOCK, this.lock);
448
660
  } finally {
449
661
  await handle?.close();
450
662
  await unlink(temp).catch((error: NodeJS.ErrnoException) => {