@peer2peer/cli 0.1.3 → 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.
- package/README.md +7 -6
- package/dist/app.d.ts +20 -0
- package/dist/app.js +77 -12
- package/dist/cli.d.ts +4 -4
- package/dist/cli.js +200 -1
- package/dist/config.d.ts +5 -0
- package/dist/doctor.d.ts +7 -0
- package/dist/doctor.js +73 -2
- package/dist/format.d.ts +3 -1
- package/dist/format.js +12 -0
- package/dist/identity.js +2 -0
- package/dist/keystore.d.ts +223 -0
- package/dist/keystore.js +1021 -0
- package/dist/procstart.js +11 -3
- package/dist/projects.js +4 -8
- package/dist/rotation-lock.d.ts +17 -0
- package/dist/rotation-lock.js +188 -0
- package/dist/rotation.d.ts +27 -1
- package/dist/rotation.js +141 -15
- package/dist/sandbox.d.ts +195 -0
- package/dist/sandbox.js +763 -0
- package/dist/state.d.ts +8 -0
- package/dist/state.js +12 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -3
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
|
-
|
|
27
|
-
|
|
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
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
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) {
|
|
@@ -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
|
+
}
|
package/dist/rotation.d.ts
CHANGED
|
@@ -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;
|
package/dist/rotation.js
CHANGED
|
@@ -55,10 +55,12 @@
|
|
|
55
55
|
// circle (§3.3); this hands over only what the old key still controls.
|
|
56
56
|
import { copyFile, lstat, mkdir, readFile, rename, rm, stat, writeFile, chmod } from "node:fs/promises";
|
|
57
57
|
import { join } from "node:path";
|
|
58
|
-
import { addIdentityVersion, applyCircleBundle, b64uEncode, backupPhraseFromSeed, capsToRevokeOnUnfriend, createCircleTransferAccept, createDeviceCert, createIdentityDoc, createMembershipStatement, createProof, createRotation, createUnfriendV3, decodeTyped, displayAddress, displayFingerprint, dnsProofRecord, encodeLinkCode, generateDeviceKeysV3, generateIdentityKey, IdentityChain, INVITE_MAX_TTL_SEC, blockUser, createCap, jwsHash, LINK_TTL_SEC, linkId, liveFriendshipsV3, loadCircle, mergePrevTip, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
|
|
58
|
+
import { addIdentityVersion, applyCircleBundle, b64uEncode, backupPhraseFromSeed, capsToRevokeOnUnfriend, createCircleTransferAccept, createDeviceCert, createIdentityDoc, createMembershipStatement, createProof, createRotation, createUnfriendV3, decodeTyped, displayAddress, displayFingerprint, dnsProofRecord, encodeLinkCode, generateDeviceKeysV3, generateIdentityKey, IdentityChain, INVITE_MAX_TTL_SEC, isCanonicalRelayUrl, isDid, blockUser, createCap, jwsHash, LINK_TTL_SEC, linkId, liveFriendshipsV3, loadCircle, mergePrevTip, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sanitizePeerText, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
|
|
59
59
|
import { FileDocBackend } from "@peer2peer/core/v3/node";
|
|
60
60
|
import { App, certDid, defaultLabel, newKeysDoc } from "./app.js";
|
|
61
61
|
import { CliError } from "./errors.js";
|
|
62
|
+
import { rotationLockOf, withRotationLock } from "./rotation-lock.js";
|
|
63
|
+
import { branchLine } from "./format.js";
|
|
62
64
|
import { fetchTips, linkGet, linkPut, publishOver, relayCode, RelayConnection, sleep } from "./relay-client.js";
|
|
63
65
|
import { deliverCircle, memberCaps, ownerPublish, signOwnJoin } from "./circle-ops.js";
|
|
64
66
|
import { accept, dropHeld, getHeld, hold, mintInvite, withHeldId } from "./social.js";
|
|
@@ -67,6 +69,22 @@ import { linkJoin } from "./identity.js";
|
|
|
67
69
|
import { renewPersonToken } from "./projects.js";
|
|
68
70
|
import { makeEvent, receiving } from "./inbound.js";
|
|
69
71
|
const STEPS = ["created", "published", "devices", "social", "final", "done"];
|
|
72
|
+
/** Printable ASCII only, one to 2048 characters (a single anchored class: linear, no backtracking). */
|
|
73
|
+
const PRINTABLE_ASCII = /^[\x21-\x7e]{1,2048}$/;
|
|
74
|
+
/**
|
|
75
|
+
* #91: a branch summary for the plan and the `branch_ambiguous` error. Its relay URLs and device ids come from
|
|
76
|
+
* versions whoever holds the identity key may have signed. Core's parser only lets canonical relay URLs (§5.1:
|
|
77
|
+
* WHATWG-serialised, so percent-encoded, no userinfo, query or fragment) and device ids (`d_` + base32) into a
|
|
78
|
+
* verified version; they are checked again here before they are printed, and anything else is left out.
|
|
79
|
+
*/
|
|
80
|
+
export function branchSummary(hash, ver, by, relays) {
|
|
81
|
+
return {
|
|
82
|
+
hash,
|
|
83
|
+
ver,
|
|
84
|
+
by: [...new Set(by.filter((d) => isDid(d)))],
|
|
85
|
+
relays: relays.filter((r) => typeof r === "string" && PRINTABLE_ASCII.test(r) && isCanonicalRelayUrl(r)),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
70
88
|
const rotationDir = (home) => join(home, "rotation");
|
|
71
89
|
const newHomeOf = (home) => join(rotationDir(home), "new");
|
|
72
90
|
const followHomeOf = (home) => join(rotationDir(home), "follow");
|
|
@@ -184,10 +202,10 @@ function certLabel(cert) {
|
|
|
184
202
|
return "";
|
|
185
203
|
}
|
|
186
204
|
}
|
|
187
|
-
/** Our own identity's chain, verified (or undefined); pending heads never narrow our own view (#65 review M1). */
|
|
205
|
+
/** Our own identity's chain, verified (or undefined); pending heads (and #92 left-out versions) never narrow our own view (#65 review M1). */
|
|
188
206
|
async function ownChain(app) {
|
|
189
207
|
const stored = await app.store.getIdentity(app.userId);
|
|
190
|
-
return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [] }) : undefined;
|
|
208
|
+
return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [], leftOut: [] }) : undefined;
|
|
191
209
|
}
|
|
192
210
|
/**
|
|
193
211
|
* The newest version of our identity that is not a rotation's final one:
|
|
@@ -232,8 +250,11 @@ async function ownBranchFork(app) {
|
|
|
232
250
|
* hash (whoever holds the identity key can pick those). A candidate is plausible when every version on
|
|
233
251
|
* it since the fork point (the versions not behind every plain tip) is in this device's publish log or
|
|
234
252
|
* was published `by` this device or a device that a version in its publish log lists. One candidate, or
|
|
235
|
-
* exactly one plausible: that one
|
|
236
|
-
*
|
|
253
|
+
* exactly one plausible: that one (#91: with the other candidates as `others`, warned about and shown in
|
|
254
|
+
* the plan: the owner's branch counts as implausible when a version on it comes from an owner device the
|
|
255
|
+
* publish log never lists, so a stolen device's branch could be the only plausible one). Otherwise the
|
|
256
|
+
* user chooses (`choice`, `--branch <hash>`), shown each branch's publishers and relays. Undefined when
|
|
257
|
+
* our identity isn't forked that way.
|
|
237
258
|
*/
|
|
238
259
|
async function ownBranchTip(app, choice) {
|
|
239
260
|
const fork = await ownBranchFork(app);
|
|
@@ -247,23 +268,31 @@ async function ownBranchTip(app, choice) {
|
|
|
247
268
|
const chosen = candidates.find((t) => t.hash === choice);
|
|
248
269
|
if (!chosen)
|
|
249
270
|
throw new CliError("usage", `--branch ${choice}: not a branch of your identity that lists this device (${candidates.map((t) => t.hash).join(", ")})`);
|
|
250
|
-
return chosen;
|
|
271
|
+
return { tip: chosen, others: [] };
|
|
251
272
|
}
|
|
252
273
|
if (candidates.length === 1)
|
|
253
|
-
return candidates[0];
|
|
274
|
+
return { tip: candidates[0], others: [] };
|
|
254
275
|
const log = new Set((await app.store.getPublishLog()).published);
|
|
276
|
+
// #91: every device any version in the publish log lists, including ones a later version revoked. That only
|
|
277
|
+
// ever makes more branches plausible, so it fails safe: more ambiguity (the user chooses), never a silent pick.
|
|
255
278
|
const trusted = new Set([app.did, ...[...log].flatMap((h) => chain.get(h)?.devices ?? [])]);
|
|
256
279
|
const behind = plain.map((t) => new Set(chain.ancestors(t.hash).map((v) => v.hash)));
|
|
257
280
|
const common = new Set([...behind[0]].filter((h) => behind.every((set) => set.has(h))));
|
|
258
281
|
const since = (t) => chain.ancestors(t.hash).filter((v) => !common.has(v.hash));
|
|
259
282
|
const plausible = candidates.filter((t) => since(t).every((v) => log.has(v.hash) || trusted.has(v.by)));
|
|
283
|
+
const branches = candidates.map((t) => branchSummary(t.hash, t.ver, since(t).map((v) => v.by), t.relays));
|
|
260
284
|
if (plausible.length === 1)
|
|
261
|
-
return plausible[0];
|
|
262
|
-
const branches = candidates.map((t) => ({ hash: t.hash, ver: t.ver, by: [...new Set(since(t).map((v) => v.by))], relays: [...t.relays] }));
|
|
285
|
+
return { tip: plausible[0], others: branches.filter((b) => b.hash !== plausible[0].hash) };
|
|
263
286
|
throw new CliError("branch_ambiguous", `your identity is forked by a version that leaves this device out, and more than one branch still lists it: ${branches
|
|
264
|
-
.map(
|
|
287
|
+
.map(branchLine)
|
|
265
288
|
.join("; ")}. Someone else holds your identity key. Check which branch is yours, then run \`p2p identity rotate --plan --branch <hash>\``, { branches });
|
|
266
289
|
}
|
|
290
|
+
/** #91: the warning when provenance picked our own branch among others that still list this device. */
|
|
291
|
+
function otherBranchesWarning(tip, others) {
|
|
292
|
+
return `your identity is forked, and the plan builds on the branch ${tip} as yours (its versions come from your devices); other branches still list this device: ${others
|
|
293
|
+
.map(branchLine)
|
|
294
|
+
.join("; ")}. If ${tip} isn't yours, drop this plan (\`p2p identity rotate --cancel\`) and choose with \`p2p identity rotate --plan --branch <hash>\``;
|
|
295
|
+
}
|
|
267
296
|
/**
|
|
268
297
|
* #75: the name and relays our final version takes when built from our own branch: those of the newest
|
|
269
298
|
* version on it this device published, with the relays this device is configured with, never the tip's
|
|
@@ -412,6 +441,8 @@ function planOf(st) {
|
|
|
412
441
|
friendsOptIn: optIn,
|
|
413
442
|
contest: !!st.contest,
|
|
414
443
|
...(st.backupFile ? { backup: { file: st.backupFile } } : {}),
|
|
444
|
+
...(st.ownBranch ? { branch: st.ownBranch.tip } : {}),
|
|
445
|
+
...(st.ownBranch?.others?.length ? { otherBranches: st.ownBranch.others } : {}),
|
|
415
446
|
};
|
|
416
447
|
}
|
|
417
448
|
async function planWithAddress(app, st) {
|
|
@@ -483,6 +514,9 @@ async function loadOrRecover(app, prior, opts) {
|
|
|
483
514
|
* fingerprint, the devices that would follow, and what moves.
|
|
484
515
|
*/
|
|
485
516
|
export async function rotatePlan(app, opts = {}) {
|
|
517
|
+
return withRotationLock(app.home, () => rotatePlanLocked(app, opts));
|
|
518
|
+
}
|
|
519
|
+
async function rotatePlanLocked(app, opts) {
|
|
486
520
|
const prior = await readRotationState(app.home);
|
|
487
521
|
const recovered = await loadOrRecover(app, prior, opts);
|
|
488
522
|
if (recovered)
|
|
@@ -490,6 +524,8 @@ export async function rotatePlan(app, opts = {}) {
|
|
|
490
524
|
if (prior && prior.step !== "done" && prior.step !== "created") {
|
|
491
525
|
throw new CliError("rotation_in_progress", `a rotation to ${prior.to} is under way: finish it with \`p2p identity rotate --resume\``);
|
|
492
526
|
}
|
|
527
|
+
if (prior && prior.step === "created")
|
|
528
|
+
assertSameBranch(prior, opts);
|
|
493
529
|
const st = prior && prior.step === "created" ? prior : await begin(app, opts);
|
|
494
530
|
if (st === prior)
|
|
495
531
|
applyExcludes(st, opts.exclude, opts.keep);
|
|
@@ -497,8 +533,26 @@ export async function rotatePlan(app, opts = {}) {
|
|
|
497
533
|
await saveState(app.home, st);
|
|
498
534
|
return planWithAddress(app, st);
|
|
499
535
|
}
|
|
536
|
+
/**
|
|
537
|
+
* #91: a plan not yet accepted is reused by `--plan` and `--resume`, so a `--branch` naming another branch than the
|
|
538
|
+
* plan's own would be ignored: refused instead (drop the plan first).
|
|
539
|
+
*/
|
|
540
|
+
function assertSameBranch(st, opts) {
|
|
541
|
+
if (opts.branch === undefined || opts.branch === st.ownBranch?.tip)
|
|
542
|
+
return;
|
|
543
|
+
if (st.step !== "created" || st.accepted) {
|
|
544
|
+
throw new CliError("usage", `--branch ${opts.branch}: the rotation under way here ${st.ownBranch ? `builds on the branch ${st.ownBranch.tip}` : "isn't built on a branch of a forked identity"}, and can't change now`);
|
|
545
|
+
}
|
|
546
|
+
const how = `drop it first (\`p2p identity rotate --cancel\`), then \`p2p identity rotate --plan --branch ${opts.branch}\``;
|
|
547
|
+
throw new CliError("usage", st.ownBranch
|
|
548
|
+
? `--branch ${opts.branch}: the rotation plan here builds on the branch ${st.ownBranch.tip}. To choose another, ${how}`
|
|
549
|
+
: `--branch ${opts.branch}: the rotation plan here isn't built on a branch of a forked identity. To choose one, ${how}`);
|
|
550
|
+
}
|
|
500
551
|
/** `p2p identity rotate --cancel`: drops a rotation whose plan wasn't accepted (nothing was published). */
|
|
501
552
|
export async function rotateCancel(app) {
|
|
553
|
+
return withRotationLock(app.home, () => rotateCancelLocked(app));
|
|
554
|
+
}
|
|
555
|
+
async function rotateCancelLocked(app) {
|
|
502
556
|
const st = await readRotationState(app.home);
|
|
503
557
|
if (!st || st.step === "done")
|
|
504
558
|
return { cancelled: false };
|
|
@@ -509,7 +563,15 @@ export async function rotateCancel(app) {
|
|
|
509
563
|
app.warn(`the backup phrase of the key that wasn't used is still in ${st.backupFile}: delete it`);
|
|
510
564
|
return { cancelled: true, to: st.to };
|
|
511
565
|
}
|
|
566
|
+
export { rotationLockOf };
|
|
567
|
+
/**
|
|
568
|
+
* One `p2p identity rotate` run per home at a time (#91 review): `--plan`, `--cancel` and `--resend` too (#99), so a
|
|
569
|
+
* `--plan --exclude X` racing a `--resume --yes` run can't lose the exclusion. See withRotationLock.
|
|
570
|
+
*/
|
|
512
571
|
export async function rotate(app, opts = {}) {
|
|
572
|
+
return withRotationLock(app.home, () => rotateLocked(app, opts));
|
|
573
|
+
}
|
|
574
|
+
async function rotateLocked(app, opts) {
|
|
513
575
|
const prior = await readRotationState(app.home);
|
|
514
576
|
const recovered = await loadOrRecover(app, prior, opts);
|
|
515
577
|
if (recovered)
|
|
@@ -521,6 +583,11 @@ export async function rotate(app, opts = {}) {
|
|
|
521
583
|
if (!prior || prior.step === "done")
|
|
522
584
|
throw new CliError("no_rotation", "there is no rotation in progress here to resume");
|
|
523
585
|
st = prior;
|
|
586
|
+
assertSameBranch(st, opts);
|
|
587
|
+
// #91: `--resume --contest`: a rotation of this identity this device didn't publish came out while this one was
|
|
588
|
+
// under way (publishFinal points here): this one goes on as a competing one, so friends see a conflict.
|
|
589
|
+
if (opts.contest && !st.contest)
|
|
590
|
+
await contestOnResume(app, st, opts);
|
|
524
591
|
}
|
|
525
592
|
else {
|
|
526
593
|
if (prior && prior.step !== "done")
|
|
@@ -659,14 +726,17 @@ async function begin(app, opts) {
|
|
|
659
726
|
throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
|
|
660
727
|
}
|
|
661
728
|
// #75: forked by a version that leaves this device out, the plan lists from this device's own branch.
|
|
662
|
-
const
|
|
729
|
+
const picked = view.rotations.length > 0 ? undefined : await ownBranchTip(app, opts.branch);
|
|
730
|
+
const own = picked?.tip;
|
|
663
731
|
if (!opts.contest && !(own ?? view).keyholders.includes(app.did)) {
|
|
664
732
|
throw new CliError("device_revoked", "this device is no longer a listed key holder of your identity");
|
|
665
733
|
}
|
|
666
734
|
let ownBranch;
|
|
667
|
-
if (own) {
|
|
735
|
+
if (picked && own) {
|
|
668
736
|
const f = ownBranchFinalFields(app, (await ownChain(app)), own, new Set((await app.store.getPublishLog()).published));
|
|
669
|
-
ownBranch = { tip: own.hash, name: f.name, relays: f.relays };
|
|
737
|
+
ownBranch = { tip: own.hash, name: f.name, relays: f.relays, ...(picked.others.length > 0 ? { others: picked.others } : {}) };
|
|
738
|
+
if (picked.others.length > 0)
|
|
739
|
+
app.warn(otherBranchesWarning(own.hash, picked.others));
|
|
670
740
|
if (f.extra.length > 0)
|
|
671
741
|
app.warn(`your own branch lists relays no version this device published added (${f.extra.join(", ")}): your old identity's final version leaves them out`);
|
|
672
742
|
}
|
|
@@ -1138,8 +1208,21 @@ async function publishFinal(app, st) {
|
|
|
1138
1208
|
const mine = chain.allTips().find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
|
|
1139
1209
|
// #75: a fork made by a version that leaves this device out can't go through publishNext (its merge
|
|
1140
1210
|
// would leave this device unlisted, so it couldn't publish): see ownBranchTip and finalOnOwnBranch.
|
|
1141
|
-
if (st.ownBranch && !contesting)
|
|
1142
|
-
|
|
1211
|
+
if (st.ownBranch && !contesting) {
|
|
1212
|
+
try {
|
|
1213
|
+
return await publishOwnBranchFinal(app, ik, st, st.ownBranch, mine);
|
|
1214
|
+
}
|
|
1215
|
+
catch (e) {
|
|
1216
|
+
// #91: a rotation someone else published meanwhile (the refresh just brought it in) makes the relays refuse
|
|
1217
|
+
// ours however often it is rebuilt: say so, and point to the contest, never to another --resume.
|
|
1218
|
+
if (!(e instanceof CliError))
|
|
1219
|
+
throw e;
|
|
1220
|
+
const foreign = await foreignRotations(app);
|
|
1221
|
+
if (foreign.length === 0)
|
|
1222
|
+
throw e;
|
|
1223
|
+
throw await rotatedMeanwhile(app, foreign, e);
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1143
1226
|
if (mine) {
|
|
1144
1227
|
// Published by an interrupted run: make sure the relays have it.
|
|
1145
1228
|
const r = await app.publishDoc(mine.jws, mine.relays);
|
|
@@ -1168,6 +1251,46 @@ async function publishFinal(app, st) {
|
|
|
1168
1251
|
}
|
|
1169
1252
|
return { ver: base.ver + 1, ...r };
|
|
1170
1253
|
}
|
|
1254
|
+
/**
|
|
1255
|
+
* #91: `--resume --contest`. A plan not yet accepted was made without the contest's drops (begin: the device that
|
|
1256
|
+
* signed the contested rotation, and every other key holder): refused, the user drops it and makes a contest's plan.
|
|
1257
|
+
* Past acceptance, those devices are dropped if no link code went out yet (unless kept, `--keep`); after that,
|
|
1258
|
+
* the ones that follow (or were sent a code) are named, so the user can revoke them on the new identity.
|
|
1259
|
+
*/
|
|
1260
|
+
async function contestOnResume(app, st, opts) {
|
|
1261
|
+
const foreign = await foreignRotations(app);
|
|
1262
|
+
if (foreign.length === 0)
|
|
1263
|
+
throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
|
|
1264
|
+
if (st.step === "created" && !st.accepted) {
|
|
1265
|
+
throw new CliError("usage", "this rotation plan was made before the rotation you want to contest, without dropping the devices that could have published it: drop it (`p2p identity rotate --cancel`), then contest with `p2p identity rotate --contest`");
|
|
1266
|
+
}
|
|
1267
|
+
const chain = await ownChain(app);
|
|
1268
|
+
const signers = new Set(foreign.map((f) => chain?.get(f.hash)?.by).filter((d) => d !== undefined && d !== app.did));
|
|
1269
|
+
const whyOf = (did, d) => signers.has(did) ? "signed the rotation you are contesting" : d.keyholder ? "holds your identity key, so it could have published the rotation you are contesting" : undefined;
|
|
1270
|
+
const suspects = Object.entries(st.devices).filter(([did, d]) => d.status !== "excluded" && d.status !== "aborted" && whyOf(did, d) !== undefined);
|
|
1271
|
+
const named = [];
|
|
1272
|
+
for (const [did, d] of suspects) {
|
|
1273
|
+
if (!after(st, "devices") && d.status === "pending" && !(opts.keep ?? []).includes(did)) {
|
|
1274
|
+
d.status = "excluded";
|
|
1275
|
+
d.why = whyOf(did, d);
|
|
1276
|
+
}
|
|
1277
|
+
else {
|
|
1278
|
+
named.push(`${did}${d.label ? ` (${sanitizePeerText(d.label, 64)})` : ""}${d.newDid ? `, now ${d.newDid}` : ""}: ${whyOf(did, d)}`);
|
|
1279
|
+
}
|
|
1280
|
+
}
|
|
1281
|
+
st.contest = true;
|
|
1282
|
+
await saveState(app.home, st);
|
|
1283
|
+
if (named.length > 0) {
|
|
1284
|
+
app.warn(`these devices of yours follow this rotation (or were sent its link code) and could have published the rotation you are contesting: ${named.join("; ")}. If one is lost or stolen, revoke it on your new identity (\`p2p devices revoke <did>\`)`);
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
/** #91: the error when a rotation this device didn't publish is out and the relays refuse our own final version. */
|
|
1288
|
+
async function rotatedMeanwhile(app, foreign, cause) {
|
|
1289
|
+
const to = [...new Set(foreign.map((f) => f.rotation.to))];
|
|
1290
|
+
const chain = await ownChain(app);
|
|
1291
|
+
const by = [...new Set(foreign.map((f) => chain?.get(f.hash)?.by).filter((d) => d !== undefined && isDid(d)))];
|
|
1292
|
+
return new CliError("identity_rotated", `no relay took your old identity's final version (${cause.message}): this identity was already rotated to ${to.join(" and ")}${by.length > 0 ? ` (signed by your device ${by.join(" and ")})` : ""}, and this device didn't publish that. If you didn't start it, someone holds your identity key: contest it with \`p2p identity rotate --resume --contest\` (your friends then see a conflict and apply neither)`, { to, by });
|
|
1293
|
+
}
|
|
1171
1294
|
/**
|
|
1172
1295
|
* #75: publishes the final version built from our own branch (finalOnOwnBranch), or the one an
|
|
1173
1296
|
* interrupted run built (`pinned`). A final version no relay took because the tips moved since (the
|
|
@@ -1428,6 +1551,9 @@ export const RESEND_PER_HOUR = 50;
|
|
|
1428
1551
|
* of what a relay advertises, in a rolling hour).
|
|
1429
1552
|
*/
|
|
1430
1553
|
export async function rotateResend(app) {
|
|
1554
|
+
return withRotationLock(app.home, () => rotateResendLocked(app));
|
|
1555
|
+
}
|
|
1556
|
+
async function rotateResendLocked(app) {
|
|
1431
1557
|
await app.load(true);
|
|
1432
1558
|
const st = await readRotationState(app.home);
|
|
1433
1559
|
if (!st || st.step !== "done" || app.userId !== st.to)
|