@peer2peer/cli 0.1.3 → 0.1.5

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/outbox.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type App } from "./app.js";
2
+ import type { SendTarget } from "./relay-client.js";
2
3
  export declare const OUTBOX_TTL_MS: number;
3
4
  export declare const OUTBOX_PER_RECIPIENT = 10;
4
5
  export declare const OUTBOX_MAX = 200;
@@ -102,8 +103,5 @@ export type RoundViews = Map<string, Promise<{
102
103
  * ones it was sealed for, each with a cap of this moment.
103
104
  */
104
105
  export declare function stillAllowed(app: App, item: OutboxItem, views?: RoundViews): Promise<{
105
- targets: {
106
- relay: string;
107
- cap?: string;
108
- }[];
106
+ targets: SendTarget[];
109
107
  } | "refused" | "later">;
package/dist/outbox.js CHANGED
@@ -32,7 +32,7 @@
32
32
  // while this device's own relays answered are expired early: their relays answer but refuse.
33
33
  import { createHash } from "node:crypto";
34
34
  import { CircleChain, decodeEnvelopeV3, liveFriendshipsV3, REPLAY_WINDOW } from "@peer2peer/core/v3";
35
- import { orderRelays } from "./app.js";
35
+ import { MAX_FALLBACK_CAPS, orderRelays } from "./app.js";
36
36
  import { CliError } from "./errors.js";
37
37
  import { makeEvent } from "./inbound.js";
38
38
  import { sessKey } from "./state.js";
@@ -330,8 +330,17 @@ export async function stillAllowed(app, item, views = new Map()) {
330
330
  return "refused";
331
331
  relays = orderRelays(own.head.relays, own.relays).slice(0, 3);
332
332
  }
333
- const caps = await app.capsFor(to, item.kind);
333
+ // Every cap of this moment, each relay's best first and the others as fallbacks: a queued copy
334
+ // whose best cap was revoked meanwhile (a block and an unblock) still goes on a live one (#127).
335
+ const caps = await app.capChoicesFor(to, item.kind);
334
336
  const candidates = [...new Set([...relays, ...item.targets.map((t) => t.relay)])];
335
- const targets = candidates.filter((r) => caps.has(r)).slice(0, 3).map((r) => ({ relay: r, cap: caps.get(r) }));
337
+ const targets = candidates
338
+ .filter((r) => (caps.get(r)?.length ?? 0) > 0)
339
+ .slice(0, 3)
340
+ .map((r) => {
341
+ const [cap, ...rest] = caps.get(r);
342
+ const fallback = rest.slice(0, MAX_FALLBACK_CAPS);
343
+ return { relay: r, cap, ...(fallback.length > 0 ? { fallback } : {}) };
344
+ });
336
345
  return targets.length > 0 ? { targets } : "refused";
337
346
  }
package/dist/procstart.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // claim from another local process is found (rare), so a spawn is fine. Undefined when the
6
6
  // platform can't say cheaply: the caller then keeps going by the pid alone.
7
7
  import { execFileSync } from "node:child_process";
8
- import { readFileSync } from "node:fs";
8
+ import { existsSync, readFileSync } from "node:fs";
9
9
  let bootMs;
10
10
  function linuxStartMs(pid) {
11
11
  // Field 22 of /proc/<pid>/stat: start time in clock ticks after boot (USER_HZ, 100 on Linux).
@@ -22,9 +22,17 @@ function linuxStartMs(pid) {
22
22
  }
23
23
  return bootMs + (ticks / 100) * 1000;
24
24
  }
25
+ /** ps by absolute path (#99 review): never whatever `ps` comes first on PATH. */
26
+ const PS = ["/bin/ps", "/usr/bin/ps"].find((p) => existsSync(p));
25
27
  function psStartMs(pid) {
26
- const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], env: { LC_ALL: "C", PATH: process.env.PATH ?? "" } }).trim();
27
- const t = Date.parse(out);
28
+ if (!PS)
29
+ return undefined;
30
+ // TZ=UTC, and read back as UTC (#99 review): lstart prints local time without a zone, so a time zone change
31
+ // between two processes (automatic time zone, travel) would otherwise move every answer by hours.
32
+ const out = execFileSync(PS, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], env: { LC_ALL: "C", TZ: "UTC" } }).trim();
33
+ if (!out)
34
+ return undefined;
35
+ const t = Date.parse(`${out} GMT`);
28
36
  return Number.isFinite(t) ? t : undefined;
29
37
  }
30
38
  /**
package/dist/projects.js CHANGED
@@ -27,6 +27,7 @@ import { homedir, tmpdir } from "node:os";
27
27
  import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
28
28
  import { circlePolicy, liveFriendshipsV3, loadCircle, sanitizePeerText, standsLookup } from "@peer2peer/core/v3";
29
29
  import { CliError } from "./errors.js";
30
+ import { signingSeedSync } from "./keystore.js";
30
31
  /** The person's own terminal session (`p2p tui`, `p2p send` with no --from-session). */
31
32
  export const PERSON_SESSION = "tui";
32
33
  /** The committed file a repository may carry to ask for privacy (it can never widen anything). */
@@ -1092,14 +1093,9 @@ function derivedToken(home) {
1092
1093
  const salt = readTrim(personSaltFile(home));
1093
1094
  if (!salt || !TOKEN_RE.test(salt))
1094
1095
  return undefined;
1095
- let spk;
1096
- try {
1097
- spk = JSON.parse(readFileSync(join(home, "cli", "keys.json"), "utf8")).spk;
1098
- }
1099
- catch {
1100
- return undefined;
1101
- }
1102
- return typeof spk === "string" && spk !== "" ? deriveToken(spk, salt) : undefined;
1096
+ // From keys.json, or from the OS keychain when the keys are kept there (keystore.ts).
1097
+ const spk = signingSeedSync(home);
1098
+ return spk ? deriveToken(spk, salt) : undefined;
1103
1099
  }
1104
1100
  /** Writes `text` to `f` whole: a new 0600 file made exclusively beside it, renamed over it (a planted symlink is replaced, not followed). */
1105
1101
  function writeWhole(f, text) {
@@ -86,6 +86,14 @@ export interface SendTarget {
86
86
  relay: string;
87
87
  /** The recipient's cap naming this relay; without one only `contact` goes, with PoW. */
88
88
  cap?: string;
89
+ /**
90
+ * Other caps we hold for this relay (each a different cap id), next best first. When the relay
91
+ * refuses `cap` with `undeliverable` (also what a revoked cap gets), the first of them is tried
92
+ * once, so one dead cap doesn't lose a send a live one would carry (#127). A second refusal
93
+ * means the cause isn't the cap (an unknown mailbox, a full store, a recipient not admitted),
94
+ * and every retry spends the relay's send budgets again: no further cap is tried.
95
+ */
96
+ fallback?: readonly string[];
89
97
  }
90
98
  export interface SendResult {
91
99
  /** Relays that answered `sent`. */
@@ -607,7 +607,13 @@ export class RelayPool {
607
607
  }
608
608
  // From here the frame goes onto an open connection (request refuses a closed one first).
609
609
  written = conn.isOpen;
610
- const r = await conn.request(frame);
610
+ let r = await conn.request(frame);
611
+ // A refused cap stored nothing: one other cap we hold for this relay may still work.
612
+ const next = t.fallback?.find((c) => c !== frame.cap);
613
+ if (r.t !== "sent" && relayCode(r.code ?? r.t) === "undeliverable" && next !== undefined) {
614
+ frame.cap = next;
615
+ r = await conn.request(frame);
616
+ }
611
617
  if (r.t === "sent")
612
618
  res.sent.push(t.relay);
613
619
  else
@@ -0,0 +1,17 @@
1
+ /** #91 review: where a running rotation step records who it is (one run per home at a time). */
2
+ export declare const rotationLockOf: (home: string) => string;
3
+ /**
4
+ * Runs `fn` holding the rotation lock of `home`, so a second run (`--resume --contest` while the first is in
5
+ * followers(), or `--plan --exclude X` while a `--resume --yes` run saves) can't have its state overwritten by the
6
+ * other's saves.
7
+ *
8
+ * The lock is created with O_EXCL and records the run (LockRecord). A lock left by a run that no longer runs
9
+ * (lockLive), or an empty one older than EMPTY_STALE_MS, is taken over, exclusively (#99): the run first creates,
10
+ * with O_EXCL, a takeover marker named after the stale lock's exact content. Only the run that creates it removes the
11
+ * lock, and only while the lock still holds that content; nothing else removes a lock with that content (its own run
12
+ * is gone). Then it takes the lock with O_EXCL like any other run. So two runs taking over the same stale lock leave
13
+ * exactly one owner: the other's marker fails, or (created after the first removed its marker, which is after the
14
+ * first took the lock) it finds the first's live lock and refuses. A fresh run racing a takeover gets the lock or
15
+ * doesn't, by O_EXCL. Every refusal names the lock file.
16
+ */
17
+ export declare function withRotationLock<T>(home: string, fn: () => Promise<T>): Promise<T>;
@@ -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";
@@ -35,12 +36,14 @@ export interface RotationState {
35
36
  * #75: begun on this device's own branch of a fork that a version leaving this device out made
36
37
  * (ownBranchTip): that tip, and the name and relays the final version takes (ownBranchFinalFields).
37
38
  * The view's allowlist then leaves this device out, so, as contesting, its stored friendships count
38
- * without verifying now.
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).
39
41
  */
40
42
  ownBranch?: {
41
43
  tip: string;
42
44
  name: string;
43
45
  relays: string[];
46
+ others?: BranchSummary[];
44
47
  };
45
48
  keepKeyholders: boolean;
46
49
  devices: Record<string, RotationDeviceRec>;
@@ -79,6 +82,20 @@ export interface RotationState {
79
82
  /** Where the old home went, once this home is the new identity's. */
80
83
  archive?: string;
81
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;
82
99
  export declare function readRotationState(home: string): Promise<RotationState | undefined>;
83
100
  /**
84
101
  * After a swap: the home must now hold the identity the link joined. Anything else (files changed
@@ -165,6 +182,10 @@ export interface RotationPlan {
165
182
  backup?: {
166
183
  file: string;
167
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[];
168
189
  }
169
190
  export interface RotateResult {
170
191
  from: string;
@@ -237,6 +258,11 @@ export declare function rotateCancel(app: App): Promise<{
237
258
  cancelled: boolean;
238
259
  to?: string;
239
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
+ */
240
266
  export declare function rotate(app: App, opts?: RotateOptions): Promise<RotateResult>;
241
267
  /** A device counts as seen lately when it sent this device something, or got a certificate, in the last 30 days. */
242
268
  export declare const DEVICE_SEEN_WINDOW_SEC: number;