@bom-pi/core 0.2.2 → 0.2.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bom-pi/core",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Core pairing machinery for Bom Pi: ceremonies, transports, durable stores",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -331,13 +331,15 @@ async function syncDirectory(directory: string): Promise<void> {
331
331
  }
332
332
  }
333
333
 
334
- /** A lease names its holder: `pid:uuid`. A dead (or malformed) pid is a crash leftover. */
334
+ /** A lease names its holder: `pid:uuid`. A lease without a parsable holder was abandoned
335
+ * mid-creation: the writer died before finishing its own identity, so it never returned from
336
+ * the acquire and never guarded a single mutation (every mutation re-validates the lease
337
+ * inode first). Such leases are crash leftovers, not locks — reclaim them. */
335
338
  function leaseStale(content: string): boolean {
336
339
  const separator = content.indexOf(":");
337
340
 
338
341
  if (separator <= 0) {
339
- // A pre-PID lease cannot be proven abandoned; it stays explicit recovery.
340
- return false;
342
+ return true;
341
343
  }
342
344
 
343
345
  const pid = Number.parseInt(content.slice(0, separator), 10);
@@ -371,10 +373,7 @@ async function acquireLock(directory: string, lockPath: string): Promise<LockLea
371
373
  return acquireLock(directory, lockPath);
372
374
  }
373
375
 
374
- fail(
375
- "writer lock exists; explicit recovery required (a pre-PID lease from a crashed " +
376
- "writer cannot be self-reclaimed: verify no daemon runs, then remove the lock)",
377
- );
376
+ fail("writer lock exists; a live writer holds this store (explicit recovery required)");
378
377
  }
379
378
 
380
379
  throw error;
@@ -2,7 +2,7 @@
2
2
  * It also hosts the owner's M4 relay activation record: a durable off-by-default switch with the
3
3
  * same single-writer, atomic, fail-closed discipline as the pairing record itself. */
4
4
  import { randomUUID } from "node:crypto";
5
- import { lstat, mkdir, open, readFile, unlink, type FileHandle } from "node:fs/promises";
5
+ import { lstat, mkdir, open, readFile, rm, unlink, type FileHandle } from "node:fs/promises";
6
6
  import { assertWindowsPrivatePath, durableRename } from "./windows-native.ts";
7
7
  import { join } from "node:path";
8
8
 
@@ -111,21 +111,68 @@ async function syncDirectory(directory: string): Promise<void> {
111
111
  }
112
112
  }
113
113
 
114
+ /** The pid of a live lease holder, or null for a lease that is malformed, legacy (pre-pid
115
+ * build) or names a provably dead holder. Such leases never guarded a completed mutation —
116
+ * every mutation requires a finished lease and re-validates the lease inode first (assertLock),
117
+ * and the app's single-instance lock rules out a second live daemon on one data directory — so
118
+ * they are crash leftovers and get reclaimed instead of blocking the next boot. */
119
+ function liveLeaseHolderPid(content: string): number | null {
120
+ const trimmed = content.trim();
121
+
122
+ if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed)) {
123
+ return null; // legacy bare-uuid build: the lease cannot name a live holder
124
+ }
125
+
126
+ const separator = trimmed.indexOf(":");
127
+ const pid = Number.parseInt(separator > 0 ? trimmed.slice(0, separator) : "", 10);
128
+
129
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
130
+ return null; // the writer died before finishing its own identity
131
+ }
132
+
133
+ try {
134
+ process.kill(pid, 0);
135
+
136
+ return pid;
137
+ } catch (error) {
138
+ // EPERM names a live process under another user; anything else is dead or invalid.
139
+ return (error as NodeJS.ErrnoException).code === "EPERM" ? pid : null;
140
+ }
141
+ }
142
+
114
143
  async function acquireLock(directory: string, lockFile: string): Promise<LockLease> {
144
+ const path = join(directory, lockFile);
115
145
  let handle: FileHandle;
116
146
 
117
147
  try {
118
- handle = await open(join(directory, lockFile), "wx", 0o600);
148
+ handle = await open(path, "wx", 0o600);
119
149
  } catch (error) {
120
- if ((error as NodeJS.ErrnoException).code === "EEXIST") {
121
- fail("writer lock exists; explicit recovery required");
150
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
151
+ throw error;
122
152
  }
123
153
 
124
- throw error;
154
+ // An EEXIST lease nobody live holds is a crash leftover: reclaim it once, fail-closed.
155
+ const existing = await readFile(path, "utf8").catch(() => "");
156
+ const holder = liveLeaseHolderPid(existing);
157
+
158
+ if (holder !== null) {
159
+ fail(
160
+ `writer lock exists; a live writer (pid ${holder}) holds this store ` +
161
+ "(stop it, or verify and recover explicitly)",
162
+ );
163
+ }
164
+
165
+ await rm(path, { force: true });
166
+
167
+ try {
168
+ handle = await open(path, "wx", 0o600);
169
+ } catch (race) {
170
+ fail("writer lock exists; a live writer holds this store (explicit recovery required)");
171
+ }
125
172
  }
126
173
 
127
174
  try {
128
- const identity = randomUUID();
175
+ const identity = `${process.pid}:${randomUUID()}`;
129
176
 
130
177
  await handle.writeFile(identity);
131
178
  await handle.sync();
@@ -296,6 +343,89 @@ export class RelaySwitchStore {
296
343
  }
297
344
  }
298
345
 
346
+ /** Boot-time open that heals a crashed initializer's leftovers automatically: a lease
347
+ * nobody finished writing (reclaimed by acquireLock), or a relay record that never came
348
+ * to exist. A valid record — OFF or ON — is adopted untouched. A record that exists but
349
+ * is unusable is moved aside as evidence and reset to OFF, which is exactly what the
350
+ * fail-closed read already reported while it sat there. Owner anomalies and live writers
351
+ * still refuse: healing never crosses a security check, and never arms anything. */
352
+ static async openHealing(
353
+ directory: string,
354
+ log?: (line: string) => void,
355
+ ): Promise<RelaySwitchStore> {
356
+ await mkdir(directory, { mode: 0o700, recursive: true });
357
+ await checkDirectory(directory);
358
+
359
+ const lock = await acquireLock(directory, RELAY_LOCK);
360
+
361
+ try {
362
+ const file = join(directory, RELAY_FILE);
363
+ const stat = await lstat(file).catch((error: NodeJS.ErrnoException) => {
364
+ if (error.code === "ENOENT") {
365
+ return null;
366
+ }
367
+
368
+ throw error;
369
+ });
370
+
371
+ let record: RelaySwitchSnapshot | null = null;
372
+
373
+ if (stat !== null) {
374
+ const regular = stat.isFile();
375
+ const privateFile =
376
+ regular && (process.platform === "win32" || (stat.mode & 0o777) === 0o600);
377
+ const owned = process.getuid === undefined || stat.uid === process.getuid();
378
+
379
+ if (!owned) {
380
+ // Parity with open(): a re-owned record is never adopted — and never healed.
381
+ fail("relay switch record must be owned by the current user");
382
+ }
383
+
384
+ if (regular && privateFile) {
385
+ try {
386
+ await assertWindowsPrivatePath(file, "file");
387
+ record = parseRelaySwitch(await readFile(file, "utf8"));
388
+ } catch (error) {
389
+ if (!/corrupt/.test(String((error as Error)?.message ?? ""))) {
390
+ // Read or platform-security anomalies need eyes, not healing.
391
+ throw error;
392
+ }
393
+
394
+ record = null;
395
+ }
396
+ }
397
+ }
398
+
399
+ if (record !== null) {
400
+ return new RelaySwitchStore(directory, record, lock);
401
+ }
402
+
403
+ const store = new RelaySwitchStore(
404
+ directory,
405
+ { version: 1, relay: { enabled: false } },
406
+ lock,
407
+ );
408
+
409
+ if (stat !== null) {
410
+ await durableRename(file, join(directory, "relay-switch.corrupt.json"));
411
+ log?.(
412
+ "relay switch: prior record unusable; moved aside to " +
413
+ "relay-switch.corrupt.json and reset to OFF",
414
+ );
415
+ } else {
416
+ log?.("relay switch: no prior record (crashed initializer); created OFF");
417
+ }
418
+
419
+ await store.persist(store.record);
420
+
421
+ return store;
422
+ } catch (error) {
423
+ await releaseLock(directory, RELAY_LOCK, lock);
424
+
425
+ throw error;
426
+ }
427
+ }
428
+
299
429
  /** Release only this instance's lock; parity with PairingStorage.close. */
300
430
  async close(): Promise<void> {
301
431
  if (this.writing) {