@peer2peer/cli 0.1.2 → 0.1.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.
@@ -0,0 +1,188 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // One `p2p identity rotate` run per home at a time (#91 review, #99).
4
+ import { randomBytes, createHash } from "node:crypto";
5
+ import { constants } from "node:fs";
6
+ import { open, readdir, rm, writeFile } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { CliError } from "./errors.js";
9
+ import { processStartMs } from "./procstart.js";
10
+ /** #91 review: where a running rotation step records who it is (one run per home at a time). */
11
+ export const rotationLockOf = (home) => join(home, "rotation.lock");
12
+ /** Start times compare to the second (ps), with room for clock rounding (as running.ts and inbound.ts). */
13
+ const START_SLACK_MS = 2500;
14
+ /** A lock this build writes is well under this; anything larger isn't read. */
15
+ const MAX_LOCK_BYTES = 4096;
16
+ /** An empty lock (a run that died between creating and writing it) older than this is stale. */
17
+ const EMPTY_STALE_MS = 60_000;
18
+ const MARKER_RE = /^rotation\.lock\.[0-9a-f]{32}\.takeover$/;
19
+ /**
20
+ * Reads the lock file without following a symbolic link or blocking on a FIFO (#99 review, as sandbox.ts
21
+ * readConfigFile): only a regular file of at most MAX_LOCK_BYTES. Anything else refuses, naming the file.
22
+ */
23
+ async function readLock(file) {
24
+ let fh;
25
+ try {
26
+ fh = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
27
+ }
28
+ catch (e) {
29
+ if (e.code === "ENOENT")
30
+ return { kind: "gone" };
31
+ throw lockError(file, `${file} couldn't be read (${e.code ?? e.message})`);
32
+ }
33
+ try {
34
+ const st = await fh.stat();
35
+ if (!st.isFile())
36
+ throw lockError(file, `${file} isn't a regular file`);
37
+ if (st.size > MAX_LOCK_BYTES)
38
+ throw lockError(file, `${file} is larger than a rotation lock`);
39
+ const buf = Buffer.alloc(MAX_LOCK_BYTES + 1);
40
+ let n = 0;
41
+ for (;;) {
42
+ const { bytesRead } = await fh.read(buf, n, buf.length - n, null);
43
+ if (bytesRead === 0)
44
+ break;
45
+ n += bytesRead;
46
+ if (n > MAX_LOCK_BYTES)
47
+ throw lockError(file, `${file} is larger than a rotation lock`);
48
+ }
49
+ return { kind: "read", raw: buf.subarray(0, n).toString("utf8"), mtimeMs: st.mtimeMs };
50
+ }
51
+ finally {
52
+ await fh.close();
53
+ }
54
+ }
55
+ function parseLock(raw) {
56
+ const t = raw.trim();
57
+ // A lock from an older build: just the pid.
58
+ if (/^[0-9]{1,10}$/.test(t)) {
59
+ const pid = Number.parseInt(t, 10);
60
+ return pid > 0 ? { pid } : undefined;
61
+ }
62
+ try {
63
+ const o = JSON.parse(t);
64
+ if (!o || typeof o !== "object" || typeof o.pid !== "number" || !Number.isSafeInteger(o.pid) || o.pid <= 0)
65
+ return undefined;
66
+ return { pid: o.pid, ...(typeof o.started === "number" && Number.isFinite(o.started) ? { started: o.started } : {}) };
67
+ }
68
+ catch {
69
+ return undefined;
70
+ }
71
+ }
72
+ function running(pid) {
73
+ try {
74
+ process.kill(pid, 0);
75
+ return true;
76
+ }
77
+ catch (e) {
78
+ return e.code === "EPERM";
79
+ }
80
+ }
81
+ /**
82
+ * Whether the run that wrote `rec` may still be running. A process with its pid must exist; when the lock records
83
+ * the process's start time and the OS tells the current one, they must match (#99: a pid reused by another process
84
+ * doesn't hold the lock forever). When the start time can't be told, it counts as running (fail closed: the error
85
+ * names the lock file, to delete when nothing is rotating).
86
+ */
87
+ function lockLive(rec) {
88
+ if (!running(rec.pid))
89
+ return false;
90
+ if (rec.started === undefined)
91
+ return true;
92
+ const now = processStartMs(rec.pid);
93
+ return now === undefined || Math.abs(now - rec.started) < START_SLACK_MS;
94
+ }
95
+ const deleteHint = (file) => `If nothing is rotating here (a run was killed, or its process id is in use again), delete ${file}`;
96
+ function lockError(file, why) {
97
+ return new CliError("rotation_in_progress", `${why}, so \`p2p identity rotate\` can't tell whether another run is in progress. ${deleteHint(file)}`);
98
+ }
99
+ const lockBusy = (file) => new CliError("rotation_in_progress", `another \`p2p identity rotate\` run is in progress for this identity: wait for it to finish, then try again. ${deleteHint(file)}`);
100
+ /** How a takeover marker is named: after the stale lock's content, which nothing but its (gone) run would remove. */
101
+ const markerOf = (file, raw) => `${file}.${createHash("sha256").update(raw).digest("hex").slice(0, 32)}.takeover`;
102
+ /** Exclusive create: true when this call created `file`, false when it already existed. */
103
+ async function createExclusive(file, content) {
104
+ try {
105
+ await writeFile(file, content, { mode: 0o600, flag: "wx" });
106
+ return true;
107
+ }
108
+ catch (e) {
109
+ if (e.code === "EEXIST")
110
+ return false;
111
+ throw e;
112
+ }
113
+ }
114
+ /**
115
+ * Leftover takeover markers (a run that died during a takeover) once we hold the lock. Safe: a marker only lets its
116
+ * creator remove a lock with the content it is named after, and the lock now holds ours, which no marker names
117
+ * (we run).
118
+ */
119
+ async function sweepMarkers(home) {
120
+ const names = await readdir(home).catch(() => []);
121
+ await Promise.all(names.filter((n) => MARKER_RE.test(n)).map((n) => rm(join(home, n), { force: true }).catch(() => undefined)));
122
+ }
123
+ /**
124
+ * Runs `fn` holding the rotation lock of `home`, so a second run (`--resume --contest` while the first is in
125
+ * followers(), or `--plan --exclude X` while a `--resume --yes` run saves) can't have its state overwritten by the
126
+ * other's saves.
127
+ *
128
+ * The lock is created with O_EXCL and records the run (LockRecord). A lock left by a run that no longer runs
129
+ * (lockLive), or an empty one older than EMPTY_STALE_MS, is taken over, exclusively (#99): the run first creates,
130
+ * with O_EXCL, a takeover marker named after the stale lock's exact content. Only the run that creates it removes the
131
+ * lock, and only while the lock still holds that content; nothing else removes a lock with that content (its own run
132
+ * is gone). Then it takes the lock with O_EXCL like any other run. So two runs taking over the same stale lock leave
133
+ * exactly one owner: the other's marker fails, or (created after the first removed its marker, which is after the
134
+ * first took the lock) it finds the first's live lock and refuses. A fresh run racing a takeover gets the lock or
135
+ * doesn't, by O_EXCL. Every refusal names the lock file.
136
+ */
137
+ export async function withRotationLock(home, fn) {
138
+ const file = rotationLockOf(home);
139
+ const started = processStartMs(process.pid) ?? Math.round(Date.now() - process.uptime() * 1000);
140
+ const mine = `${JSON.stringify({ pid: process.pid, started, run: randomBytes(16).toString("hex"), at: Date.now() })}\n`;
141
+ if (!(await createExclusive(file, mine))) {
142
+ const cur = await readLock(file);
143
+ if (cur.kind === "gone") {
144
+ // Gone in the meantime (its run finished): take it like any other run.
145
+ if (!(await createExclusive(file, mine)))
146
+ throw lockBusy(file);
147
+ }
148
+ else {
149
+ const { raw } = cur;
150
+ if (raw.trim() === "") {
151
+ // A run that died between creating and writing it, or one writing it right now.
152
+ if (Date.now() - cur.mtimeMs < EMPTY_STALE_MS)
153
+ throw lockBusy(file);
154
+ }
155
+ else {
156
+ const rec = parseLock(raw);
157
+ if (!rec)
158
+ throw lockError(file, `${file} doesn't hold a rotation lock this build can read`);
159
+ if (lockLive(rec))
160
+ throw lockBusy(file);
161
+ }
162
+ const marker = markerOf(file, raw);
163
+ if (!(await createExclusive(marker, mine))) {
164
+ throw new CliError("rotation_in_progress", `another \`p2p identity rotate\` run is taking over a stale rotation lock: try again. ${deleteHint(file)}`);
165
+ }
166
+ try {
167
+ const now = await readLock(file);
168
+ if (now.kind === "read" && now.raw === raw)
169
+ await rm(file, { force: true });
170
+ if (!(await createExclusive(file, mine)))
171
+ throw lockBusy(file);
172
+ }
173
+ finally {
174
+ await rm(marker, { force: true }).catch(() => undefined);
175
+ }
176
+ }
177
+ }
178
+ await sweepMarkers(home);
179
+ try {
180
+ return await fn();
181
+ }
182
+ finally {
183
+ // Only our own lock is removed.
184
+ const now = await readLock(file).catch(() => undefined);
185
+ if (now?.kind === "read" && now.raw === mine)
186
+ await rm(file, { force: true }).catch(() => undefined);
187
+ }
188
+ }
@@ -1,5 +1,6 @@
1
1
  import { type RotationStatement, type VerifiedRotation } from "@peer2peer/core/v3";
2
2
  import { App } from "./app.js";
3
+ import { rotationLockOf } from "./rotation-lock.js";
3
4
  import type { HeldItem } from "./state.js";
4
5
  import { type EventFrom, type NewEvent } from "./inbound.js";
5
6
  export type RotationStep = "created" | "published" | "devices" | "social" | "final" | "done";
@@ -31,6 +32,19 @@ export interface RotationState {
31
32
  accepted?: boolean;
32
33
  /** Contesting a rotation this device didn't publish (§2.8: a conflict, so neither applies). */
33
34
  contest?: boolean;
35
+ /**
36
+ * #75: begun on this device's own branch of a fork that a version leaving this device out made
37
+ * (ownBranchTip): that tip, and the name and relays the final version takes (ownBranchFinalFields).
38
+ * The view's allowlist then leaves this device out, so, as contesting, its stored friendships count
39
+ * without verifying now. `others` (#91): the other branches that still list this device, when provenance
40
+ * picked this one among them (shown in the plan, so a wrong pick isn't silent).
41
+ */
42
+ ownBranch?: {
43
+ tip: string;
44
+ name: string;
45
+ relays: string[];
46
+ others?: BranchSummary[];
47
+ };
34
48
  keepKeyholders: boolean;
35
49
  devices: Record<string, RotationDeviceRec>;
36
50
  /** Excluded devices revoked on the old identity before any link code went out. */
@@ -68,7 +82,26 @@ export interface RotationState {
68
82
  /** Where the old home went, once this home is the new identity's. */
69
83
  archive?: string;
70
84
  }
85
+ /** #75, #91: a branch of our forked identity as shown to the user: its tip, who published it since the fork, its relays. */
86
+ export interface BranchSummary {
87
+ hash: string;
88
+ ver: number;
89
+ by: string[];
90
+ relays: string[];
91
+ }
92
+ /**
93
+ * #91: a branch summary for the plan and the `branch_ambiguous` error. Its relay URLs and device ids come from
94
+ * versions whoever holds the identity key may have signed. Core's parser only lets canonical relay URLs (§5.1:
95
+ * WHATWG-serialised, so percent-encoded, no userinfo, query or fragment) and device ids (`d_` + base32) into a
96
+ * verified version; they are checked again here before they are printed, and anything else is left out.
97
+ */
98
+ export declare function branchSummary(hash: string, ver: number, by: readonly string[], relays: readonly string[]): BranchSummary;
71
99
  export declare function readRotationState(home: string): Promise<RotationState | undefined>;
100
+ /**
101
+ * After a swap: the home must now hold the identity the link joined. Anything else (files changed
102
+ * under the swap) keeps no person token and stops the command.
103
+ */
104
+ export declare function assertAdopted(app: App, userId: string): void;
72
105
  /**
73
106
  * Makes `src` (a home holding the new identity) this home's identity, after
74
107
  * the old identity's work here has stopped (moveHomes).
@@ -104,6 +137,8 @@ export interface RotateOptions {
104
137
  backupFileDefault?: boolean;
105
138
  /** A key holder contests a rotation it didn't publish: a competing one, so neither applies. */
106
139
  contest?: boolean;
140
+ /** #75: which branch is this device's own, when ownBranchTip can't tell (its jwsHash). */
141
+ branch?: string;
107
142
  /** Tests: stop after this step, as an interruption would. */
108
143
  stopAfter?: RotationStep;
109
144
  }
@@ -147,6 +182,10 @@ export interface RotationPlan {
147
182
  backup?: {
148
183
  file: string;
149
184
  };
185
+ /** #75: the branch of a forked identity the plan builds on (its tip's jwsHash), when it is forked that way. */
186
+ branch?: string;
187
+ /** #91: the other branches that still list this device, when provenance picked `branch` among them. */
188
+ otherBranches?: BranchSummary[];
150
189
  }
151
190
  export interface RotateResult {
152
191
  from: string;
@@ -200,7 +239,8 @@ export interface RotateResult {
200
239
  * friendship whose our-side signature comes from this device or a device
201
240
  * that stays in the plan counts (a thief's device can plant friendships with
202
241
  * accomplices); rotating normally it must also verify now, while a contest
203
- * also takes stored ones the other rotation left unverifiable. Anything else
242
+ * (or a rotation from this device's own branch of a fork, #75) also takes
243
+ * stored ones that don't verify now. Anything else
204
244
  * is shown in the plan, invited only when the user opts in.
205
245
  */
206
246
  export declare function friendVerdict(st: RotationState, peer: string): {
@@ -218,6 +258,11 @@ export declare function rotateCancel(app: App): Promise<{
218
258
  cancelled: boolean;
219
259
  to?: string;
220
260
  }>;
261
+ export { rotationLockOf };
262
+ /**
263
+ * One `p2p identity rotate` run per home at a time (#91 review): `--plan`, `--cancel` and `--resend` too (#99), so a
264
+ * `--plan --exclude X` racing a `--resume --yes` run can't lose the exclusion. See withRotationLock.
265
+ */
221
266
  export declare function rotate(app: App, opts?: RotateOptions): Promise<RotateResult>;
222
267
  /** A device counts as seen lately when it sent this device something, or got a certificate, in the last 30 days. */
223
268
  export declare const DEVICE_SEEN_WINDOW_SEC: number;