@peer2peer/cli 0.0.0-stage → 0.1.1

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.
Files changed (111) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +370 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +368 -0
  6. package/dist/app.js +1181 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +660 -0
  12. package/dist/cli.js +1787 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +159 -0
  16. package/dist/config.js +294 -0
  17. package/dist/doctor.d.ts +113 -0
  18. package/dist/doctor.js +930 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +38 -0
  22. package/dist/ext-host.js +293 -0
  23. package/dist/extensions.d.ts +487 -0
  24. package/dist/extensions.js +406 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/graph-memory.d.ts +107 -0
  30. package/dist/graph-memory.js +393 -0
  31. package/dist/history.d.ts +155 -0
  32. package/dist/history.js +697 -0
  33. package/dist/identity.d.ts +239 -0
  34. package/dist/identity.js +759 -0
  35. package/dist/inbound.d.ts +32 -0
  36. package/dist/inbound.js +261 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +14 -0
  39. package/dist/ix-local.d.ts +76 -0
  40. package/dist/ix-local.js +203 -0
  41. package/dist/join-answers.d.ts +49 -0
  42. package/dist/join-answers.js +149 -0
  43. package/dist/outbox.d.ts +109 -0
  44. package/dist/outbox.js +337 -0
  45. package/dist/pretty.d.ts +100 -0
  46. package/dist/pretty.js +256 -0
  47. package/dist/procstart.d.ts +1 -0
  48. package/dist/procstart.js +66 -0
  49. package/dist/progress.d.ts +30 -0
  50. package/dist/progress.js +78 -0
  51. package/dist/projects.d.ts +491 -0
  52. package/dist/projects.js +1383 -0
  53. package/dist/prompt/picker.d.ts +64 -0
  54. package/dist/prompt/picker.js +152 -0
  55. package/dist/prompt/tty.d.ts +29 -0
  56. package/dist/prompt/tty.js +122 -0
  57. package/dist/readonly.d.ts +20 -0
  58. package/dist/readonly.js +50 -0
  59. package/dist/receipts.d.ts +99 -0
  60. package/dist/receipts.js +182 -0
  61. package/dist/relay-client.d.ts +277 -0
  62. package/dist/relay-client.js +873 -0
  63. package/dist/relay-info.d.ts +24 -0
  64. package/dist/relay-info.js +53 -0
  65. package/dist/rotation.d.ts +402 -0
  66. package/dist/rotation.js +2054 -0
  67. package/dist/running.d.ts +5 -0
  68. package/dist/running.js +74 -0
  69. package/dist/sessions.d.ts +355 -0
  70. package/dist/sessions.js +1247 -0
  71. package/dist/shortcode.d.ts +149 -0
  72. package/dist/shortcode.js +465 -0
  73. package/dist/social.d.ts +139 -0
  74. package/dist/social.js +485 -0
  75. package/dist/state.d.ts +509 -0
  76. package/dist/state.js +220 -0
  77. package/dist/stdin.d.ts +17 -0
  78. package/dist/stdin.js +46 -0
  79. package/dist/sync.d.ts +77 -0
  80. package/dist/sync.js +375 -0
  81. package/dist/transient.d.ts +1 -0
  82. package/dist/transient.js +28 -0
  83. package/dist/trust.d.ts +37 -0
  84. package/dist/trust.js +134 -0
  85. package/dist/tty-confirm.d.ts +2 -0
  86. package/dist/tty-confirm.js +53 -0
  87. package/dist/tui/command.d.ts +20 -0
  88. package/dist/tui/command.js +70 -0
  89. package/dist/tui/frame.d.ts +43 -0
  90. package/dist/tui/frame.js +111 -0
  91. package/dist/tui/model.d.ts +221 -0
  92. package/dist/tui/model.js +259 -0
  93. package/dist/tui/sanitize.d.ts +13 -0
  94. package/dist/tui/sanitize.js +151 -0
  95. package/dist/tui/terminal.d.ts +88 -0
  96. package/dist/tui/terminal.js +354 -0
  97. package/dist/tui/tui.d.ts +78 -0
  98. package/dist/tui/tui.js +612 -0
  99. package/dist/tui/view.d.ts +4 -0
  100. package/dist/tui/view.js +358 -0
  101. package/dist/unknown-kinds.d.ts +12 -0
  102. package/dist/unknown-kinds.js +66 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +5 -0
  105. package/dist/want-pow.d.ts +12 -0
  106. package/dist/want-pow.js +46 -0
  107. package/dist/watch.d.ts +35 -0
  108. package/dist/watch.js +331 -0
  109. package/dist/xstate.d.ts +125 -0
  110. package/dist/xstate.js +422 -0
  111. package/package.json +60 -4
@@ -0,0 +1,2054 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Identity key rotation (docs/protocol.md §2.8, with the P3 readings): the
4
+ // remedy for a lost or stolen key-holding device.
5
+ //
6
+ // `p2p identity rotate`, on a key-holding device, keeps friends able to
7
+ // verify at every step:
8
+ // 0. the plan: a new identity key is made (nothing is published yet) and
9
+ // the user sees its fingerprint and which devices would follow, drops
10
+ // any (a lost device must be dropped: `--exclude`), and accepts. Dropped
11
+ // devices are revoked before any link code is minted;
12
+ // 1. a new identity key and new device keys for this device (rotation
13
+ // re-keys every device, so this device gets a new did);
14
+ // 2. the two-part statement, signed by the old and the new identity key;
15
+ // 3. the new identity's version 1, listing only this device, on the same
16
+ // relays;
17
+ // 4. each other device of the old identity gets a `sync` from the old
18
+ // identity carrying the statement and a one-time link code minted by the
19
+ // new identity. It is HELD there: the device follows only when its user
20
+ // says so (`p2p identity follow <id>`), and a key-holding device never
21
+ // follows (it alerts, and can contest). A device that doesn't follow in
22
+ // time re-links by hand later (`link join --rotated`);
23
+ // 5. friends get a fresh invite from the new identity, bound to them and
24
+ // bundled with the statement (`contact` {rotation, invite}), which their
25
+ // client holds for approval; circles the old identity owns are handed
26
+ // over (add the new identity, then `transfer`, counter-signed here since
27
+ // this device holds both keys), circles it is a member of get the new
28
+ // identity's join with the statement for the owner, and the old
29
+ // identity's leave; proofs are re-signed under the new identity;
30
+ // 6. last, the old identity's final version, `devices: []`, carrying the
31
+ // statement (`rotation`, P3): relays then refuse the old dids, and
32
+ // friends refreshing every 10 minutes find it with no push. It needs a
33
+ // backup of the new key or a key-holding follower first (§2.5).
34
+ // Then this home becomes the new identity's; the old one is archived in
35
+ // `<home>/rotated/`. Every step is recorded in `<home>/rotation/` so an
36
+ // interrupted rotation resumes with `--resume`.
37
+ //
38
+ // The receiving sides live here too. Friends and circle owners act on a
39
+ // rotation only once the OLD identity's own published final version carries
40
+ // that same statement, so a statement the old identity never published can't
41
+ // split its owner from them: a friend's held "moved to a new key" (approved:
42
+ // the normal accept, then the old friendship ends locally), a circle owner's
43
+ // `rotation-join` (applied by itself only then, with nothing conflicting,
44
+ // never carrying admin rights, never past the owner's hold policy), and this
45
+ // user's own devices (held, alerting).
46
+ //
47
+ // Security notes (also in the help and README):
48
+ // - a thief who also has the old identity key can publish a competing
49
+ // rotation. Friends then see a conflict (two rotations from one old id)
50
+ // and nothing is applied; they resolve it out of band, with petnames and
51
+ // proofs, and exchange a fresh invite with the real one. A key holder
52
+ // that sees a rotation it didn't publish contests it
53
+ // (`p2p identity rotate --contest`), which makes that conflict;
54
+ // - rotation can't recover a compromised owner's circles: those need a new
55
+ // circle (§3.3); this hands over only what the old key still controls.
56
+ import { copyFile, mkdir, readFile, rename, rm, stat, writeFile, chmod } from "node:fs/promises";
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, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
59
+ import { FileDocBackend } from "@peer2peer/core/v3/node";
60
+ import { App, certDid, defaultLabel, newKeysDoc } from "./app.js";
61
+ import { CliError } from "./errors.js";
62
+ import { linkGet, linkPut, relayCode, sleep } from "./relay-client.js";
63
+ import { deliverCircle, memberCaps, ownerPublish, signOwnJoin } from "./circle-ops.js";
64
+ import { accept, dropHeld, getHeld, hold, mintInvite, withHeldId } from "./social.js";
65
+ import { exportAll, exportCircle, mergeRemovals, sendSync } from "./sync.js";
66
+ import { linkJoin } from "./identity.js";
67
+ import { makeEvent, receiving } from "./inbound.js";
68
+ const STEPS = ["created", "published", "devices", "social", "final", "done"];
69
+ const rotationDir = (home) => join(home, "rotation");
70
+ const newHomeOf = (home) => join(rotationDir(home), "new");
71
+ const followHomeOf = (home) => join(rotationDir(home), "follow");
72
+ function stateBackend(home) {
73
+ return new FileDocBackend(rotationDir(home));
74
+ }
75
+ export async function readRotationState(home) {
76
+ return (await stateBackend(home).read("state"));
77
+ }
78
+ async function saveState(home, s) {
79
+ const b = stateBackend(home);
80
+ await b.withLock(() => b.write("state", s));
81
+ }
82
+ async function dropState(home) {
83
+ await rm(join(rotationDir(home), "state.json"), { force: true });
84
+ await rm(newHomeOf(home), { recursive: true, force: true });
85
+ }
86
+ const after = (s, step) => STEPS.indexOf(s.step) >= STEPS.indexOf(step);
87
+ async function exists(p) {
88
+ try {
89
+ await stat(p);
90
+ return true;
91
+ }
92
+ catch {
93
+ return false;
94
+ }
95
+ }
96
+ /** An App on another home that reaches the relays the same way (config.json is copied). */
97
+ async function appAt(app, home) {
98
+ await mkdir(home, { recursive: true, mode: 0o700 });
99
+ if (await exists(join(app.home, "config.json")))
100
+ await copyFile(join(app.home, "config.json"), join(home, "config.json"));
101
+ return new App({ env: { ...app.env, P2P_HOME: home }, io: app.io });
102
+ }
103
+ /**
104
+ * The directory moves of a home swap, idempotent (an interrupted swap
105
+ * finishes on the next run): the old `cli`, `v3` and `cursors` go to
106
+ * `<home>/rotated/<tag>/`, `src`'s take their place.
107
+ */
108
+ async function moveHomes(home, src, tag) {
109
+ const archive = join(home, "rotated", tag);
110
+ await mkdir(archive, { recursive: true, mode: 0o700 });
111
+ const srcHasState = await exists(join(src, "cli"));
112
+ for (const d of ["cli", "v3", "cursors"]) {
113
+ if (srcHasState && (await exists(join(home, d))) && !(await exists(join(archive, d))))
114
+ await rename(join(home, d), join(archive, d));
115
+ }
116
+ for (const d of ["cli", "v3"]) {
117
+ if ((await exists(join(src, d))) && !(await exists(join(home, d))))
118
+ await rename(join(src, d), join(home, d));
119
+ }
120
+ await rm(src, { recursive: true, force: true });
121
+ // A lock something still held when its directory moved belongs to nobody now.
122
+ for (const d of ["cli", "v3"])
123
+ await rm(join(archive, d, ".lock"), { force: true });
124
+ return archive;
125
+ }
126
+ /**
127
+ * Makes `src` (a home holding the new identity) this home's identity, after
128
+ * the old identity's work here has stopped (moveHomes).
129
+ */
130
+ export async function adoptHome(app, src, tag) {
131
+ // Nothing of the old identity may still be writing: an envelope handled mid-swap would take its
132
+ // lock into the archive (or write the old identity's state into the new home).
133
+ await app.close();
134
+ const home = app.home;
135
+ // Let in-flight work of the old identity finish (a refresh after a relay refused it, say): take
136
+ // each store's lock once, so nothing holds it while the directories move.
137
+ // (Only where the directory is still there: taking a lock creates it.)
138
+ if (await exists(join(home, "cli")))
139
+ await app.state.backend.withLock(async () => { });
140
+ if (await exists(app.store.dir))
141
+ await new FileDocBackend(app.store.dir).withLock(async () => { });
142
+ return moveHomes(home, src, tag);
143
+ }
144
+ /** Re-points `app` at whatever identity its home now holds (after adoptHome). */
145
+ async function reload(app) {
146
+ await app.close();
147
+ await app.load(true);
148
+ }
149
+ function certLabel(cert) {
150
+ if (!cert)
151
+ return "";
152
+ try {
153
+ const l = decodeTyped(cert, TYP3.device).payload.label;
154
+ return typeof l === "string" ? l : "";
155
+ }
156
+ catch {
157
+ return "";
158
+ }
159
+ }
160
+ /** Our own identity's chain, verified (or undefined). */
161
+ async function ownChain(app) {
162
+ const stored = await app.store.getIdentity(app.userId);
163
+ return stored && stored.versions.length > 0 ? IdentityChain.fromStored(stored) : undefined;
164
+ }
165
+ /**
166
+ * The newest version of our identity that is not a rotation's final one:
167
+ * the head when nothing rotated it, else the version a rotation tip was
168
+ * built on (what a contest builds on, and lists the devices from).
169
+ */
170
+ async function preRotationHead(app) {
171
+ const chain = await ownChain(app);
172
+ if (!chain)
173
+ return undefined;
174
+ const tips = chain.tips();
175
+ const plain = tips.find((t) => t.rotation === undefined);
176
+ if (plain)
177
+ return plain;
178
+ for (const t of tips) {
179
+ const p = t.prev ? chain.get(t.prev) : undefined;
180
+ if (p && p.rotation === undefined)
181
+ return p;
182
+ }
183
+ return undefined;
184
+ }
185
+ /** Rotations our identity's held tips carry that this device didn't publish (its publish log). */
186
+ async function foreignRotations(app) {
187
+ const chain = await ownChain(app);
188
+ if (!chain)
189
+ return [];
190
+ const log = await app.store.getPublishLog();
191
+ const out = [];
192
+ for (const t of chain.tips()) {
193
+ if (t.rotation === undefined || log.published.includes(t.hash))
194
+ continue;
195
+ try {
196
+ const r = verifyRotationSignatures(t.rotation);
197
+ if (r.from === app.userId)
198
+ out.push({ hash: t.hash, rotation: r });
199
+ }
200
+ catch {
201
+ // not a valid statement
202
+ }
203
+ }
204
+ return out;
205
+ }
206
+ // ---------------------------------------------------------------------------
207
+ // Alerts: a rotation of our identity this device didn't publish
208
+ /**
209
+ * §2.8, compromise: a rotation of this user's identity that this device
210
+ * didn't publish (judged by its publish log) is raised loudly, once per
211
+ * statement: a stderr line, a `p2p.alert` watch event (the mod shows it on
212
+ * its status line). A key holder is told to contest it.
213
+ */
214
+ export async function raiseRotationAlert(app, r, by) {
215
+ const key = rotationKey(r.statement);
216
+ const fresh = await app.state.update("rotationAlerts", (cur = []) => (cur.includes(key) ? { result: false } : { next: [...cur, key].slice(-64), result: true }));
217
+ if (!fresh)
218
+ return false;
219
+ const label = by ? certLabel((await app.view(app.userId))?.head.certs?.find((c) => certDid(c) === by)) : "";
220
+ const fp = displayFingerprint(r.to);
221
+ const who = by ? ` by your device ${label ? `"${label}" ` : ""}(${by})` : "";
222
+ const what = app.isKeyholder
223
+ ? "If you didn't start this, someone holds your identity key: contest it now with `p2p identity rotate --contest` (your friends then see a conflict and apply neither)"
224
+ : "Follow it only if you started it yourself. If you didn't, someone holds your identity key: contest it from a key-holding device (`p2p identity rotate --contest`)";
225
+ app.io.err(`ALERT: your identity is being moved to a new key (${fp})${who}. ${what}.`);
226
+ await app.state.addEvents([
227
+ makeEvent(`rotation-alert|${key}`, "p2p.alert", Date.now(), {
228
+ from: { userId: app.userId, did: by ?? app.did, address: await app.addressOf(app.userId), self: true },
229
+ what: "rotation",
230
+ to: r.to,
231
+ fingerprint: fp,
232
+ ...(by ? { by, byLabel: label } : {}),
233
+ keyholder: app.isKeyholder,
234
+ contest: "p2p identity rotate --contest",
235
+ }),
236
+ ]);
237
+ return true;
238
+ }
239
+ /** Alerts for every rotation on our own held tips this device didn't publish (no network). */
240
+ export async function alertForeignRotations(app) {
241
+ if (!app.keys)
242
+ return;
243
+ for (const f of await foreignRotations(app))
244
+ await raiseRotationAlert(app, f.rotation);
245
+ }
246
+ /**
247
+ * pre-release re-review M1: whether `peer` gets the new identity's invite. Only a
248
+ * friendship whose our-side signature comes from this device or a device
249
+ * that stays in the plan counts (a thief's device can plant friendships with
250
+ * accomplices); rotating normally it must also verify now, while a contest
251
+ * also takes stored ones the other rotation left unverifiable. Anything else
252
+ * is shown in the plan, invited only when the user opts in.
253
+ */
254
+ export function friendVerdict(st, peer) {
255
+ const entries = st.friendSigners?.[peer] ?? [];
256
+ // A follower that aborted (another device answered its code) is no more trusted than a dropped one.
257
+ const trusted = (did) => did === st.selfDid || (st.devices[did] !== undefined && st.devices[did].status !== "excluded" && st.devices[did].status !== "aborted");
258
+ if (entries.some((e) => trusted(e.did) && (st.contest || e.live)))
259
+ return { invite: true };
260
+ const dropped = entries.map((e) => st.devices[e.did]).find((d) => d?.status === "excluded");
261
+ const why = entries.some((e) => trusted(e.did))
262
+ ? "the friendship doesn't verify now"
263
+ : dropped
264
+ ? `made by a device the plan drops (${dropped.why ?? "you dropped it"})`
265
+ : "made by a device your identity no longer lists";
266
+ return { invite: (st.inviteOptIn ?? []).includes(peer), why };
267
+ }
268
+ /** The friends the rotation invites (the plan's count is exactly these). */
269
+ function invitedFriends(st) {
270
+ return Object.keys(st.friendSigners ?? {}).filter((p) => friendVerdict(st, p).invite);
271
+ }
272
+ function planOf(st) {
273
+ const devs = Object.entries(st.devices);
274
+ const optIn = Object.keys(st.friendSigners ?? {})
275
+ .map((userId) => ({ userId, ...friendVerdict(st, userId) }))
276
+ .filter((v) => v.why !== undefined)
277
+ .map((v) => ({ userId: v.userId, why: v.why, invited: v.invite }));
278
+ return {
279
+ from: st.from,
280
+ address: st.from,
281
+ to: st.to,
282
+ newFingerprint: displayFingerprint(st.to),
283
+ follow: devs.filter(([, d]) => d.status === "pending").map(([did, d]) => ({ did, label: d.label, keyholder: d.keyholder, labelTrusted: d.labelTrusted !== false })),
284
+ excluded: devs
285
+ .filter(([, d]) => d.status === "excluded")
286
+ .map(([did, d]) => ({ did, label: d.label, keyholder: d.keyholder, labelTrusted: d.labelTrusted !== false, ...(d.why ? { why: d.why } : {}) })),
287
+ ...st.plan,
288
+ friends: invitedFriends(st).length,
289
+ friendsOptIn: optIn,
290
+ contest: !!st.contest,
291
+ ...(st.backupFile ? { backup: { file: st.backupFile } } : {}),
292
+ };
293
+ }
294
+ async function planWithAddress(app, st) {
295
+ const plan = planOf(st);
296
+ const friendsOptIn = await Promise.all(plan.friendsOptIn.map(async (f) => ({ ...f, address: await app.addressOf(f.userId) })));
297
+ return { ...plan, friendsOptIn, address: await app.addressOf(st.from) };
298
+ }
299
+ /** `--invite`: a friend the plan leaves out by default, invited anyway (the user's explicit choice). */
300
+ async function applyInvites(app, st, invite = []) {
301
+ for (const u of invite) {
302
+ const peer = await app.resolveUser(u);
303
+ if (!st.friendSigners?.[peer])
304
+ throw new CliError("usage", `--invite ${u}: not one of your friends`);
305
+ if (friendVerdict(st, peer).why === undefined)
306
+ continue;
307
+ st.inviteOptIn = [...new Set([...(st.inviteOptIn ?? []), peer])];
308
+ }
309
+ }
310
+ /** Every stored friendship no unfriend ended, by friend: the device that signed our side, and whether it verifies now. */
311
+ async function friendSigners(app) {
312
+ const blocked = new Set((await app.store.listBlocks()).map((b) => b.userId));
313
+ const live = new Set((await liveFriendshipsV3(app.store, app.signerCtx())).map((f) => f.inv));
314
+ const unfriends = await app.store.listUnfriends();
315
+ const out = {};
316
+ for (const f of await app.store.listFriendships()) {
317
+ if (unfriends.some((u) => unfriendApplies(f, u)))
318
+ continue;
319
+ const mine = f.inviter === app.userId;
320
+ const peer = mine ? f.invitee : f.inviter;
321
+ if (peer === app.userId || blocked.has(peer))
322
+ continue;
323
+ (out[peer] ??= []).push({ did: mine ? f.inviteDid : f.acceptDid, live: live.has(f.inv) });
324
+ }
325
+ return out;
326
+ }
327
+ /** Marks `exclude` as dropped in a plan not yet accepted. */
328
+ function applyExcludes(st, exclude = [], keep = []) {
329
+ for (const d of exclude) {
330
+ const rec = st.devices[d];
331
+ if (!rec)
332
+ throw new CliError("usage", `--exclude ${d}: not one of your other devices`);
333
+ if (rec.status === "pending")
334
+ rec.status = "excluded";
335
+ }
336
+ // An explicit keep of a device the plan dropped by default (or the user dropped before).
337
+ for (const d of keep) {
338
+ const rec = st.devices[d];
339
+ if (!rec)
340
+ throw new CliError("usage", `--keep ${d}: not one of your other devices`);
341
+ if (exclude.includes(d))
342
+ throw new CliError("usage", `${d} is both kept and excluded`);
343
+ if (rec.status === "excluded") {
344
+ rec.status = "pending";
345
+ delete rec.why;
346
+ }
347
+ }
348
+ }
349
+ async function loadOrRecover(app, prior, opts) {
350
+ if (app.keys || (await app.load(false)))
351
+ return undefined;
352
+ // A swap interrupted half way leaves no identity in the home itself: finish it.
353
+ if (opts.resume && prior?.step === "final")
354
+ return finish(app, prior);
355
+ throw new CliError("no_identity", "no identity here yet: run `p2p init` (or `p2p link join` / `p2p backup restore`)");
356
+ }
357
+ /**
358
+ * `p2p identity rotate --plan`: makes the new identity key (published only
359
+ * once the plan is accepted) and shows what would happen: the new
360
+ * fingerprint, the devices that would follow, and what moves.
361
+ */
362
+ export async function rotatePlan(app, opts = {}) {
363
+ const prior = await readRotationState(app.home);
364
+ const recovered = await loadOrRecover(app, prior, opts);
365
+ if (recovered)
366
+ throw new CliError("rotation_in_progress", "a rotation was just finished here");
367
+ if (prior && prior.step !== "done" && prior.step !== "created") {
368
+ throw new CliError("rotation_in_progress", `a rotation to ${prior.to} is under way: finish it with \`p2p identity rotate --resume\``);
369
+ }
370
+ const st = prior && prior.step === "created" ? prior : await begin(app, opts);
371
+ if (st === prior)
372
+ applyExcludes(st, opts.exclude, opts.keep);
373
+ await applyInvites(app, st, opts.invite);
374
+ await saveState(app.home, st);
375
+ return planWithAddress(app, st);
376
+ }
377
+ /** `p2p identity rotate --cancel`: drops a rotation whose plan wasn't accepted (nothing was published). */
378
+ export async function rotateCancel(app) {
379
+ const st = await readRotationState(app.home);
380
+ if (!st || st.step === "done")
381
+ return { cancelled: false };
382
+ if (st.step !== "created" || st.accepted)
383
+ throw new CliError("rotation_in_progress", "the rotation is already under way and can't be cancelled: finish it with `p2p identity rotate --resume`");
384
+ await dropState(app.home);
385
+ if (st.backupFile)
386
+ app.warn(`the backup phrase of the key that wasn't used is still in ${st.backupFile}: delete it`);
387
+ return { cancelled: true, to: st.to };
388
+ }
389
+ export async function rotate(app, opts = {}) {
390
+ const prior = await readRotationState(app.home);
391
+ const recovered = await loadOrRecover(app, prior, opts);
392
+ if (recovered)
393
+ return recovered;
394
+ if (!app.onEnvelope)
395
+ receiving(app);
396
+ let st;
397
+ if (opts.resume) {
398
+ if (!prior || prior.step === "done")
399
+ throw new CliError("no_rotation", "there is no rotation in progress here to resume");
400
+ st = prior;
401
+ }
402
+ else {
403
+ if (prior && prior.step !== "done")
404
+ throw new CliError("rotation_in_progress", `a rotation to ${prior.to} is in progress: finish it with \`p2p identity rotate --resume\``);
405
+ st = await begin(app, opts);
406
+ }
407
+ // The plan: the devices to drop, then the user's acceptance (never assumed).
408
+ if (st.step === "created" && !st.accepted) {
409
+ applyExcludes(st, opts.exclude, opts.keep);
410
+ await applyInvites(app, st, opts.invite);
411
+ const plan = await planWithAddress(app, st);
412
+ if (!opts.yes) {
413
+ if (!opts.confirm) {
414
+ await saveState(app.home, st);
415
+ throw new CliError("needs_confirmation", "accept the rotation plan first: review it with `p2p identity rotate --plan`, then `p2p identity rotate --resume --yes [--exclude <did>]…`, or run it in a terminal", { plan });
416
+ }
417
+ if (!(await opts.confirm(plan))) {
418
+ if (!opts.resume)
419
+ await dropState(app.home);
420
+ else
421
+ await saveState(app.home, st);
422
+ throw new CliError("cancelled", "nothing was changed");
423
+ }
424
+ }
425
+ st.accepted = true;
426
+ await saveState(app.home, st);
427
+ }
428
+ // The swap may have happened already (a crash right after it): finish it, then report.
429
+ if (st.step === "final" || (st.step === "done" && st.archive === undefined))
430
+ return finish(app, st);
431
+ app.requireKeyholder("Rotating your identity");
432
+ const napp = await appAt(app, newHomeOf(app.home));
433
+ try {
434
+ await napp.load(true);
435
+ if (napp.userId !== st.to)
436
+ throw new CliError("internal", "the new identity's keys don't match the rotation in progress");
437
+ const newIk = napp.requireKeyholder("Rotating your identity");
438
+ receiving(napp);
439
+ // A backup asked for later (L3: a resume after `needs_backup`).
440
+ if (!st.backupFile && (opts.backupFile || opts.backupFileDefault)) {
441
+ st.backupFile = await writeBackup(app, newIk, opts);
442
+ await saveState(app.home, st);
443
+ }
444
+ const stop = async (step) => {
445
+ await saveState(app.home, st);
446
+ if (opts.stopAfter === step)
447
+ throw new CliError("interrupted", `stopped after ${step} (resume with --resume)`);
448
+ };
449
+ if (!after(st, "published")) {
450
+ await publishNew(app, napp);
451
+ st.step = "published";
452
+ await stop("published");
453
+ }
454
+ if (!after(st, "devices")) {
455
+ await followers(app, napp, st, opts);
456
+ st.step = "devices";
457
+ await stop("devices");
458
+ }
459
+ if (!after(st, "social")) {
460
+ await social(app, napp, st, newIk);
461
+ st.step = "social";
462
+ await stop("social");
463
+ }
464
+ if (!after(st, "final")) {
465
+ // §2.5 liveness: the new key must not live on this one device only.
466
+ const keyholderFollower = Object.values(st.devices).some((d) => d.status === "followed" && d.keyholder && st.keepKeyholders);
467
+ if (!st.backupFile && !keyholderFollower) {
468
+ throw new CliError("needs_backup", "the new identity key would live on this device only: save its backup first (`p2p identity rotate --resume --backup-file [path]`), then the old identity's final version goes out");
469
+ }
470
+ // §2.8 step 6: last, the old identity's final version.
471
+ const pub = await publishFinal(app, st);
472
+ st.finalVer = pub.ver;
473
+ st.finalPublished = pub.ok.length > 0;
474
+ st.step = "final";
475
+ await stop("final");
476
+ }
477
+ }
478
+ finally {
479
+ await napp.close();
480
+ }
481
+ return finish(app, st);
482
+ }
483
+ async function writeBackup(app, ik, opts) {
484
+ const file = opts.backupFile ?? (opts.backupFileDefault ? join(app.home, `backup-phrase-${displayFingerprint(ik.userId).replace(/-/g, "")}.txt`) : undefined);
485
+ if (!file)
486
+ return undefined;
487
+ try {
488
+ await writeFile(file, `${backupPhraseFromSeed(ik.secretKey)}\n`, { mode: 0o600, flag: "wx" });
489
+ await chmod(file, 0o600);
490
+ }
491
+ catch (e) {
492
+ if (e.code === "EEXIST")
493
+ throw new CliError("exists", `${file} already exists: not overwriting it (pass --backup-file <path>)`);
494
+ throw e;
495
+ }
496
+ return file;
497
+ }
498
+ /** Steps 1–2 (and the plan): keys, the statement, the new identity's home with version 1 (not yet published). */
499
+ async function begin(app, opts) {
500
+ const oldIk = app.requireKeyholder("Rotating your identity");
501
+ if (opts.contest) {
502
+ // The relays may already refuse this device (the other rotation's final version is out).
503
+ await app.connectAndDrain().catch((e) => app.io.err(`p2p: ${e.message}`));
504
+ await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
505
+ }
506
+ else {
507
+ await app.connectAndDrain();
508
+ // Build on the relays' head: a stale view could miss a competing rotation or a new device.
509
+ await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true });
510
+ }
511
+ const view = await app.ownView();
512
+ const foreign = await foreignRotations(app);
513
+ if (view.rotations.length > 0 && !opts.contest) {
514
+ const to = view.rotations.map((r) => verifyRotationSignatures(r).to);
515
+ throw new CliError("identity_rotated", `this identity was already rotated to ${to.join(" and ")}${foreign.length > 0 ? ". This device didn't publish that: if you didn't start it, contest it with `p2p identity rotate --contest`" : ""}`, { to });
516
+ }
517
+ if (opts.contest) {
518
+ if (view.rotations.length > 0 && foreign.length === 0)
519
+ throw new CliError("usage", "that rotation is this device's own: there is nothing to contest");
520
+ const alerted = ((await app.state.get("rotationAlerts")) ?? []).length > 0;
521
+ if (foreign.length === 0 && !alerted)
522
+ throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
523
+ }
524
+ else if (!view.keyholders.includes(app.did)) {
525
+ throw new CliError("device_revoked", "this device is no longer a listed key holder of your identity");
526
+ }
527
+ // What the plan lists from: the head, or (contesting) the version the other rotation replaced.
528
+ const base = view.rotations.length > 0 ? await preRotationHead(app) : view.head;
529
+ if (!base)
530
+ throw new CliError("refresh_failed", "couldn't find your identity's last version before the rotation");
531
+ const baseDevices = view.rotations.length > 0 ? base.devices : view.devices;
532
+ const baseKeyholders = view.rotations.length > 0 ? base.keyholders : view.keyholders;
533
+ const exclude = [...new Set(opts.exclude ?? [])];
534
+ for (const d of exclude)
535
+ if (!baseDevices.includes(d) || d === app.did)
536
+ throw new CliError("usage", `--exclude ${d}: not one of your other devices`);
537
+ const others = baseDevices.filter((d) => d !== app.did);
538
+ const labelOf = (d) => certLabel(base.certs?.find((c) => certDid(c) === d));
539
+ const trust = await deviceTrust(app, others, base);
540
+ // pre-release re-review M4: contesting, the device that signed the other rotation's final version, and
541
+ // every other key holder (any of them could have), are dropped unless the user keeps them.
542
+ const contestWhy = new Map();
543
+ if (opts.contest) {
544
+ const chain = await ownChain(app);
545
+ for (const f of foreign) {
546
+ const by = chain?.get(f.hash)?.by;
547
+ if (by && by !== app.did)
548
+ contestWhy.set(by, "signed the rotation you are contesting");
549
+ }
550
+ for (const d of baseKeyholders)
551
+ if (d !== app.did && !contestWhy.has(d))
552
+ contestWhy.set(d, "holds your identity key, so it could have published the rotation you are contesting");
553
+ }
554
+ const whyOf = (d) => contestWhy.get(d) ?? trust.get(d).why;
555
+ const plan = { friends: 0, owned: 0, memberOf: 0 };
556
+ const signers = await friendSigners(app);
557
+ for (const r of await app.store.listCircles()) {
558
+ const c = await loadCircle(app.store, r.cid);
559
+ if (!c)
560
+ continue;
561
+ if (c.chain.head.owner === app.userId)
562
+ plan.owned++;
563
+ else if (r.joinedByMe && c.chain.head.members.includes(app.userId))
564
+ plan.memberOf++;
565
+ }
566
+ // 1. A new identity key, and new device keys for this device.
567
+ const newIk = generateIdentityKey();
568
+ const device = generateDeviceKeysV3(newIk.userId);
569
+ const label = certLabel(app.keys.cert) || defaultLabel();
570
+ const cert = createDeviceCert(newIk, { signingPublicKey: device.signingPublicKey, agreementPublicKey: device.agreementPublicKey, label });
571
+ // 2. The two-part statement, signed by both identity keys.
572
+ const statement = createRotation(oldIk, newIk);
573
+ const doc = createIdentityDoc(newIk, {
574
+ ver: 1,
575
+ prev: null,
576
+ name: base.name,
577
+ relays: [...base.relays],
578
+ devices: [device.did],
579
+ keyholders: [device.did],
580
+ by: device.did,
581
+ certs: [cert],
582
+ ...(base.profile ? { profile: { ...base.profile } } : {}),
583
+ });
584
+ const home = newHomeOf(app.home);
585
+ await rm(home, { recursive: true, force: true });
586
+ const napp = await appAt(app, home);
587
+ const self = { name: base.name, relays: [...base.relays], createdAt: Date.now() };
588
+ await napp.state.put("keys", newKeysDoc(newIk.userId, device, cert, newIk));
589
+ await napp.state.put("self", self);
590
+ await napp.load(true);
591
+ await addIdentityVersion(napp.store, doc);
592
+ await napp.store.putDeviceCert({ userId: newIk.userId, did: device.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
593
+ await napp.store.recordPublished({ hash: jwsHash(doc), devices: [device.did], relays: base.relays });
594
+ await copyKnowledge(app, napp);
595
+ const st = {
596
+ v: 1,
597
+ from: app.userId,
598
+ to: newIk.userId,
599
+ statement,
600
+ startedAt: Date.now(),
601
+ step: "created",
602
+ accepted: false,
603
+ ...(opts.contest ? { contest: true } : {}),
604
+ keepKeyholders: !!opts.keepKeyholders,
605
+ devices: Object.fromEntries(others.map((d) => {
606
+ const t = trust.get(d);
607
+ const why = whyOf(d);
608
+ // pre-release re-review N2/L1: a device this device didn't list itself, or hasn't seen lately, is dropped
609
+ // unless the user keeps it explicitly (`--keep`): a thief's device never gets a code by default.
610
+ const kept = (opts.keep ?? []).includes(d);
611
+ const dropped = exclude.includes(d) || (why !== undefined && !kept);
612
+ return [
613
+ d,
614
+ {
615
+ label: labelOf(d),
616
+ keyholder: baseKeyholders.includes(d),
617
+ status: dropped ? "excluded" : "pending",
618
+ labelTrusted: t.labelTrusted,
619
+ ...(why !== undefined && !kept && !exclude.includes(d) ? { why } : {}),
620
+ },
621
+ ];
622
+ })),
623
+ plan,
624
+ selfDid: app.did,
625
+ friendSigners: signers,
626
+ friends: {},
627
+ circles: {},
628
+ };
629
+ st.plan.friends = invitedFriends(st).length;
630
+ // The new key's backup, before anything is published: losing this device mid-rotation shouldn't lose it.
631
+ try {
632
+ const file = await writeBackup(app, newIk, opts);
633
+ if (file)
634
+ st.backupFile = file;
635
+ }
636
+ catch (e) {
637
+ await rm(home, { recursive: true, force: true });
638
+ throw e;
639
+ }
640
+ await saveState(app.home, st);
641
+ await napp.close();
642
+ return st;
643
+ }
644
+ /** A device counts as seen lately when it sent this device something, or got a certificate, in the last 30 days. */
645
+ export const DEVICE_SEEN_WINDOW_SEC = 30 * 86_400;
646
+ /**
647
+ * pre-release re-review N2 and L1: which devices the plan may let follow by default.
648
+ * Only devices listed by versions THIS device published (its publish log)
649
+ * and seen lately: anything else may be a thief's (added by a version this
650
+ * device didn't publish, or long gone) and is dropped unless kept. A label is
651
+ * trusted only when a version this device published carries that device's
652
+ * certificate.
653
+ */
654
+ async function deviceTrust(app, dids, base) {
655
+ const chain = await ownChain(app);
656
+ const log = await app.store.getPublishLog();
657
+ const own = new Map();
658
+ for (const t of chain?.tips() ?? [])
659
+ for (const v of chain.ancestors(t.hash))
660
+ if (log.published.includes(v.hash))
661
+ own.set(v.hash, v);
662
+ const listed = new Set([...own.values()].flatMap((v) => v.devices));
663
+ const ownCerts = new Set([...own.values()].flatMap((v) => v.certs ?? []));
664
+ const replay = ((await new FileDocBackend(app.store.dir).read("v3-replay")) ?? {});
665
+ const now = Math.floor(Date.now() / 1000);
666
+ const out = new Map();
667
+ for (const d of dids) {
668
+ const cert = base.certs?.find((c) => certDid(c) === d);
669
+ let certIat;
670
+ try {
671
+ certIat = cert ? Number(decodeTyped(cert, TYP3.device).payload.iat) || 0 : 0;
672
+ }
673
+ catch {
674
+ certIat = 0;
675
+ }
676
+ const lastAt = Math.max(0, ...Object.values(replay[d]?.lastAt ?? {})) / 1000;
677
+ const seen = now - Math.max(lastAt, certIat) <= DEVICE_SEEN_WINDOW_SEC;
678
+ const why = !listed.has(d) ? "added by a version you didn't publish" : !seen ? "not seen in the last 30 days" : undefined;
679
+ out.set(d, { ...(why ? { why } : {}), labelTrusted: cert !== undefined && ownCerts.has(cert) });
680
+ }
681
+ return out;
682
+ }
683
+ /**
684
+ * pre-release re-review L1: during a rotation window (a rotation under way on this
685
+ * device, our identity carrying a rotation, or one this device alerted
686
+ * about), why a friendship synced from another of our devices whose our-side
687
+ * signer is `did` isn't taken: that device is one the rotation drops, or one
688
+ * deviceTrust can't vouch for. Undefined (take it) outside a window, and for
689
+ * this device's own signature.
690
+ */
691
+ export async function untrustedImportSigner(app, did) {
692
+ if (did === app.did || !app.keys)
693
+ return undefined;
694
+ const st = await readRotationState(app.home).catch(() => undefined);
695
+ const active = st !== undefined && st.step !== "done";
696
+ if (active && st.devices[did]?.status === "excluded")
697
+ return st.devices[did].why ?? "a device you dropped from the rotation";
698
+ const rotated = ((await app.view(app.userId))?.rotations.length ?? 0) > 0 || ((await app.state.get("rotationAlerts")) ?? []).length > 0;
699
+ if (!active && !rotated)
700
+ return undefined;
701
+ const base = await preRotationHead(app);
702
+ if (!base)
703
+ return "your identity document isn't held here";
704
+ return (await deviceTrust(app, [did], base)).get(did)?.why;
705
+ }
706
+ /**
707
+ * What the new identity needs to reach the same people: every other
708
+ * identity's verified chain, the circles (as offered, not yet joined), and
709
+ * the local preferences (petnames, blocks). Friendships and caps are not
710
+ * copied: they were the old identity's, and are re-established.
711
+ */
712
+ async function copyKnowledge(app, napp) {
713
+ for (const u of await app.store.listIdentities()) {
714
+ const c = await app.store.getIdentity(u);
715
+ if (c)
716
+ await napp.store.putIdentity(c);
717
+ }
718
+ for (const [u, p] of Object.entries(await app.store.listPetnames()))
719
+ await napp.store.setPetname(u, p);
720
+ for (const b of await app.store.listBlocks())
721
+ await napp.store.addBlock(b);
722
+ for (const r of await app.store.listCircles()) {
723
+ // The removal record goes along (soak review H1): the new identity may own the circle next.
724
+ await napp.store.putCircle({ cid: r.cid, chain: r.chain, statements: r.statements, joinedByMe: false, ...(r.removed ? { removed: r.removed } : {}) });
725
+ }
726
+ }
727
+ /** Step 3: the new identity's version 1, on the same relays. */
728
+ async function publishNew(app, napp) {
729
+ const view = await napp.ownView();
730
+ await napp.connect({ allowNone: true });
731
+ const r = await napp.publishDoc(view.head.jws, view.head.relays);
732
+ if (r.ok.length === 0) {
733
+ throw new CliError("not_published", `no relay took the new identity's document (${r.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")}); run \`p2p identity rotate --resume\``);
734
+ }
735
+ // The old side verifies the new identity's statements (joins, consents) from its own store.
736
+ await addIdentityVersion(app.store, view.head.jws).catch(() => undefined);
737
+ }
738
+ /**
739
+ * Dropped devices are revoked on the old identity before any link code goes
740
+ * out (pre-release review H1): a lost device never gets a code, and the relays stop
741
+ * taking it.
742
+ */
743
+ async function revokeExcluded(app, st) {
744
+ // Only what the user dropped: a device the plan merely didn't trust (`why`) gets no code, and the
745
+ // final version revokes it with the rest; revoking it early could end friendships it signed.
746
+ const excluded = Object.entries(st.devices)
747
+ .filter(([, d]) => d.status === "excluded" && d.why === undefined)
748
+ .map(([did]) => did);
749
+ if (excluded.length === 0)
750
+ return;
751
+ const view = await app.ownView();
752
+ const listed = excluded.filter((d) => view.devices.includes(d));
753
+ if (listed.length > 0 && view.rotations.length === 0) {
754
+ try {
755
+ await app.publishNext((p) => {
756
+ p.devices = p.devices.filter((d) => !listed.includes(d));
757
+ p.keyholders = p.keyholders.filter((d) => !listed.includes(d));
758
+ p.certs = (p.certs ?? []).filter((c) => !listed.includes(certDid(c) ?? ""));
759
+ });
760
+ }
761
+ catch (e) {
762
+ if (!st.contest)
763
+ throw e;
764
+ app.warn(`couldn't revoke ${listed.join(", ")} on your old identity (${e.message})`);
765
+ }
766
+ }
767
+ st.revoked = excluded;
768
+ }
769
+ /**
770
+ * Step 4: every other device of the old identity gets a `sync` from the old
771
+ * identity with the statement and its own one-time link code, minted by the
772
+ * new identity (a link mailbox opened by this device's new did). The device
773
+ * holds it until its user follows (`p2p identity follow`); a request whose
774
+ * MAC verifies is then certified at once: the code travelled only inside an
775
+ * end-to-end encrypted sync to that one device, so it takes the place of the
776
+ * compare code. Devices that don't answer in time re-link by hand.
777
+ */
778
+ async function followers(app, napp, st, opts) {
779
+ await revokeExcluded(app, st);
780
+ await saveState(app.home, st);
781
+ const pending = Object.entries(st.devices).filter(([, d]) => d.status === "pending");
782
+ if (pending.length === 0)
783
+ return;
784
+ const pool = await napp.connect();
785
+ const relay = napp.relays[0];
786
+ const conn = await pool.ensure(relay);
787
+ const open = [];
788
+ for (const [did, d] of pending) {
789
+ const s = newLinkSecret();
790
+ const lid = linkId(s);
791
+ const opened = await conn.request({ t: "link-open", lid });
792
+ if (opened.t !== "ok") {
793
+ const code = relayCode(opened.code ?? opened.t);
794
+ // A relay caps the link codes one device holds open at once (`full`, 4 by default): the rest re-link by hand.
795
+ if (code !== "full" && code !== "rate-limited")
796
+ throw new CliError("link_failed", `${relay} refused to open a link mailbox (${code})`);
797
+ app.warn(`${relay} won't hold another link code for this device now (${code}): ${d.label || did} re-links by hand later (\`p2p link join <code> --rotated\`)`);
798
+ d.status = "offline";
799
+ continue;
800
+ }
801
+ const keyholder = d.keyholder && st.keepKeyholders;
802
+ const body = { rotation: { statement: st.statement, link: encodeLinkCode(s, relay), ...(keyholder ? { keyholder: true } : {}) } };
803
+ let reached = false;
804
+ try {
805
+ reached = (await app.deliver(app.userId, "sync", { own: app.userId, sid: "~sync" }, body, { onlyDevices: [did] })).relays.length > 0;
806
+ }
807
+ catch (e) {
808
+ app.io.err(`couldn't reach your device ${did}: ${e.message}`);
809
+ }
810
+ if (reached)
811
+ open.push({ did, s, lid, keyholder });
812
+ else
813
+ d.status = "offline";
814
+ }
815
+ await saveState(app.home, st);
816
+ const waitSec = Math.max(0, Math.min(opts.waitSec ?? LINK_TTL_SEC, LINK_TTL_SEC));
817
+ if (open.length > 0) {
818
+ app.io.err(`waiting up to ${waitSec}s for ${open.length} of your devices to follow: on each, accept the held rotation (\`p2p held\`, then \`p2p identity follow <id>\`); --wait to change`);
819
+ }
820
+ const deadline = Date.now() + waitSec * 1000;
821
+ while (open.length > 0 && Date.now() < deadline) {
822
+ for (const o of [...open]) {
823
+ const entries = await linkGet(conn, o.lid, "req");
824
+ const rec = st.devices[o.did];
825
+ if (entries === undefined) {
826
+ rec.status = "offline";
827
+ open.splice(open.indexOf(o), 1);
828
+ continue;
829
+ }
830
+ let req;
831
+ try {
832
+ req = selectLinkRequest(o.s, entries);
833
+ }
834
+ catch (e) {
835
+ if (e instanceof P2PError && e.reason === "link-multiple-requests") {
836
+ // Someone else holds this device's code: link nothing for it.
837
+ app.warn(`more than one device answered the code sent to ${o.did}: not linking it (re-link it by hand)`);
838
+ rec.status = "aborted";
839
+ open.splice(open.indexOf(o), 1);
840
+ continue;
841
+ }
842
+ throw e;
843
+ }
844
+ if (!req)
845
+ continue;
846
+ const newIk = napp.requireKeyholder("Linking a device");
847
+ const cert = createDeviceCert(newIk, { signingPublicKey: req.signingPublicKey, agreementPublicKey: req.agreementPublicKey, ...(req.displayLabel ? { label: req.displayLabel } : {}) });
848
+ const pub = await napp.publishNext((p) => {
849
+ p.devices = [...p.devices, req.did];
850
+ if (o.keyholder)
851
+ p.keyholders = [...p.keyholders, req.did];
852
+ p.certs = [...(p.certs ?? []), cert];
853
+ });
854
+ await napp.store.putDeviceCert({ userId: napp.userId, did: req.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
855
+ const frame = sealLinkResponse(o.s, req, { cert, doc: pub.doc, ...(o.keyholder ? { ik: b64uEncode(newIk.secretKey) } : {}) }, napp.device);
856
+ await linkPut(conn, o.lid, "resp", JSON.stringify(frame));
857
+ rec.status = "followed";
858
+ rec.newDid = req.did;
859
+ open.splice(open.indexOf(o), 1);
860
+ await saveState(app.home, st);
861
+ }
862
+ if (open.length > 0)
863
+ await sleep(napp.tun.linkPollMs);
864
+ }
865
+ for (const o of open)
866
+ st.devices[o.did].status = "offline";
867
+ }
868
+ /** Sends one friend the new identity's bound invite with the statement. */
869
+ async function inviteFriend(app, napp, peer, statement) {
870
+ try {
871
+ const m = await mintInvite(napp, { aud: peer, uses: 3, ttlSec: INVITE_MAX_TTL_SEC });
872
+ const hint = (await app.view(peer))?.relays ?? [];
873
+ const d = await napp.deliver(peer, "contact", { own: napp.userId, sid: "~contact" }, { rotation: statement, invite: m.jws }, { hint });
874
+ return d.relays.length > 0 ? "sent" : "failed";
875
+ }
876
+ catch (e) {
877
+ app.io.err(`couldn't send ${await app.addressOf(peer)} your new identity: ${e.message}`);
878
+ return "failed";
879
+ }
880
+ }
881
+ /** Step 5: friends, circles and proofs move to the new identity. */
882
+ async function social(app, napp, st, newIk) {
883
+ await app.connect({ allowNone: true });
884
+ await napp.connect({ allowNone: true });
885
+ // Friends: a fresh invite from the new identity, bound to the friend, with the statement as proof.
886
+ // Exactly the friends the accepted plan names (friendVerdict, pre-release re-review M1): never one a
887
+ // device the plan drops planted, unless the user opted in.
888
+ if (!st.friendSigners) {
889
+ st.friendSigners = await friendSigners(app);
890
+ st.selfDid ??= app.did;
891
+ }
892
+ const blocked = new Set((await app.store.listBlocks()).map((b) => b.userId));
893
+ for (const peer of invitedFriends(st)) {
894
+ if (blocked.has(peer) || st.friends[peer] === "sent")
895
+ continue;
896
+ st.friends[peer] = await inviteFriend(app, napp, peer, st.statement);
897
+ await saveState(app.home, st);
898
+ }
899
+ // Circles.
900
+ for (const r of await app.store.listCircles()) {
901
+ const prev = st.circles[r.cid];
902
+ if (prev && (prev.status === "done" || prev.status === "skipped"))
903
+ continue;
904
+ const c = await loadCircle(app.store, r.cid);
905
+ if (!c)
906
+ continue;
907
+ const h = c.chain.head;
908
+ const name = h.name;
909
+ // Already handed to the new identity by an interrupted run: finish the hand-over.
910
+ const role = h.owner === app.userId || h.owner === napp.userId ? "owner" : "member";
911
+ // (A failed attempt is retried even though the old identity's leave is already recorded here.)
912
+ if (role === "member" && !prev && !(r.joinedByMe && h.members.includes(app.userId)))
913
+ continue;
914
+ if (c.chain.frozen) {
915
+ st.circles[r.cid] = { name, role, status: "skipped", reason: `frozen (${c.chain.frozen.reason})` };
916
+ continue;
917
+ }
918
+ try {
919
+ if (role === "owner")
920
+ await handOver(app, napp, r.cid, newIk);
921
+ else
922
+ await rejoin(app, napp, r.cid, st.statement);
923
+ st.circles[r.cid] = { name, role, status: "done" };
924
+ }
925
+ catch (e) {
926
+ st.circles[r.cid] = { name, role, status: "failed", reason: e.message };
927
+ }
928
+ await saveState(app.home, st);
929
+ }
930
+ const def = app.self?.defaultCircle;
931
+ if (def && (await napp.store.getCircle(def))?.joinedByMe)
932
+ await napp.updateSelf((s) => ({ ...s, defaultCircle: def }));
933
+ // Proofs, re-signed by the new identity key: the counterparts must be updated by hand.
934
+ const head = await preRotationHead(app);
935
+ if (!st.proofs && head && (head.proofs?.length ?? 0) > 0) {
936
+ const proofs = [];
937
+ const notes = [];
938
+ for (const j of head.proofs ?? []) {
939
+ try {
940
+ const p = decodeTyped(j, TYP3.proof).payload;
941
+ if (p.kind !== "github" && p.kind !== "dns")
942
+ continue;
943
+ const proof = createProof(newIk, { kind: p.kind, claim: p.claim, loc: p.loc });
944
+ proofs.push(proof);
945
+ notes.push({
946
+ kind: p.kind,
947
+ claim: p.claim,
948
+ publish: p.kind === "github" ? `Replace the content of your gist ${p.loc} with:\n${proof}` : `Change the DNS TXT record ${p.loc} to "${dnsProofRecord(napp.userId)}"`,
949
+ });
950
+ }
951
+ catch {
952
+ // a proof this CLI can't re-sign (an extension kind): it stays with the old identity
953
+ }
954
+ }
955
+ if (proofs.length > 0)
956
+ await napp.publishNext((p) => (p.proofs = proofs));
957
+ st.proofs = notes;
958
+ }
959
+ // The followers learn the new identity's state (they linked before step 5).
960
+ await sendSync(napp, await exportAll(napp));
961
+ }
962
+ /**
963
+ * §2.8 step 6: the old identity's final version, `devices: []` with the
964
+ * statement. It builds on the newest version that isn't a rotation's final
965
+ * one, so when another rotation (one this device didn't publish) is already
966
+ * out, this one is its sibling: a fork that carries two rotations, which
967
+ * friends see as a conflict. Contesting, a relay that already refuses this
968
+ * device is tolerated (the friends' conflict comes from the invites anyway).
969
+ */
970
+ async function publishFinal(app, st) {
971
+ const ik = app.requireKeyholder("Publishing your old identity's final version");
972
+ const contesting = st.contest || (await foreignRotations(app)).length > 0;
973
+ await app.connect({ allowNone: true });
974
+ await app.refreshIdentity(app.userId, app.relays, contesting ? { force: true, quiet: true } : { force: true, strict: true });
975
+ const chain = await ownChain(app);
976
+ if (!chain)
977
+ throw new CliError("no_identity", "this device holds no identity document for its user");
978
+ const tips = chain.tips();
979
+ const mine = tips.find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
980
+ if (mine) {
981
+ // Published by an interrupted run: make sure the relays have it.
982
+ const r = await app.publishDoc(mine.jws, mine.relays);
983
+ return { ver: mine.ver, ...r };
984
+ }
985
+ const plain = tips.filter((t) => t.rotation === undefined);
986
+ if (plain.length > 1 && !contesting) {
987
+ // An honest fork: publishNext merges it first.
988
+ const pub = await app.publishNext(() => { }, { rotation: st.statement });
989
+ if (pub.ok.length === 0)
990
+ throw new CliError("not_published", `no relay took your old identity's final version (${pub.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")}); run \`p2p identity rotate --resume\``);
991
+ return pub;
992
+ }
993
+ const base = plain[0] ?? (await preRotationHead(app));
994
+ if (!base)
995
+ throw new CliError("refresh_failed", "couldn't find your identity's last version before the rotation");
996
+ const doc = createIdentityDoc(ik, { ver: base.ver + 1, prev: base.hash, name: base.name, relays: [...base.relays], devices: [], keyholders: [], by: app.did, rotation: st.statement });
997
+ await addIdentityVersion(app.store, doc);
998
+ await app.store.recordPublished({ hash: jwsHash(doc) });
999
+ const r = await app.publishDoc(doc, [...new Set([...base.relays, ...app.relays])]);
1000
+ if (r.ok.length === 0) {
1001
+ if (!contesting)
1002
+ throw new CliError("not_published", `no relay took your old identity's final version (${r.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")}); run \`p2p identity rotate --resume\``);
1003
+ app.warn("no relay took your competing final version (they already refuse your old devices); your friends still see the conflict from your new identity's invites");
1004
+ }
1005
+ return { ver: base.ver + 1, ...r };
1006
+ }
1007
+ /** Copies a circle's chain and statements from `src`'s store into `dst`'s (verified on the way in). */
1008
+ async function syncCircle(dst, src, cid) {
1009
+ const exp = await exportCircle(src, cid);
1010
+ if (!exp)
1011
+ return;
1012
+ if (!(await dst.store.getCircle(cid)))
1013
+ await storeOfferedCircle(dst.store, exp.versions);
1014
+ await applyCircleBundle(dst.store, { circles: exp.versions, joins: exp.statements, ops: [] }, { ...dst.signerCtx(), self: dst.userId });
1015
+ await mergeRemovals(dst, cid, exp.removed);
1016
+ }
1017
+ /**
1018
+ * A circle the old identity owns: add the new identity as a member, have it
1019
+ * join, hand ownership over (`transfer`, its consent counter-signed by the
1020
+ * new key over {cid, ver, prev}), then the old identity leaves and the new
1021
+ * owner drops it. Every version goes to the members as usual.
1022
+ */
1023
+ async function handOver(app, napp, cid, newIk) {
1024
+ const to = napp.userId;
1025
+ let c = (await loadCircle(app.store, cid));
1026
+ if (c.chain.head.owner === app.userId && !c.chain.head.members.includes(to))
1027
+ await ownerPublish(app, cid, { members: [...c.chain.head.members, to] });
1028
+ await syncCircle(napp, app, cid);
1029
+ let nc = (await loadCircle(napp.store, cid));
1030
+ if (nc.book[to]?.op !== "join")
1031
+ await signOwnJoin(napp, cid, nc.chain.head.hash);
1032
+ nc = (await loadCircle(napp.store, cid));
1033
+ await applyCircleBundle(app.store, { circles: [], joins: [nc.book[to].jws], ops: [] }, { ...app.signerCtx(), self: app.userId });
1034
+ c = (await loadCircle(app.store, cid));
1035
+ const h = c.chain.head;
1036
+ if (h.owner === app.userId) {
1037
+ const consent = createCircleTransferAccept(newIk, { cid, ver: h.ver + 1, prev: h.hash });
1038
+ await ownerPublish(app, cid, { newOwner: { userId: to, ik: b64uEncode(newIk.publicKey), transfer: consent } });
1039
+ }
1040
+ // (Contesting, the old device's leave may not verify any more: the new owner drops it regardless.)
1041
+ await leaveAsOld(app, cid).catch((e) => {
1042
+ if (!(e instanceof P2PError))
1043
+ throw e;
1044
+ });
1045
+ await syncCircle(napp, app, cid);
1046
+ nc = (await loadCircle(napp.store, cid));
1047
+ if (nc.chain.head.owner === to && nc.chain.head.members.includes(app.userId)) {
1048
+ await ownerPublish(napp, cid, { members: nc.chain.head.members.filter((m) => m !== app.userId), admins: nc.chain.head.admins.filter((m) => m !== app.userId) });
1049
+ }
1050
+ }
1051
+ /** The old identity's leave statement, recorded here (sent by the caller). */
1052
+ async function leaveAsOld(app, cid) {
1053
+ const c = (await loadCircle(app.store, cid));
1054
+ const mine = c.book[app.userId];
1055
+ if (mine?.op === "leave")
1056
+ return mine.jws;
1057
+ const jws = createMembershipStatement(app.signer(), { cid, n: nextMembershipN(c.record.myN), op: "leave" });
1058
+ await recordOwnLeave(app.store, app.userId, await verifyMembershipStatement(jws, app.signerCtx()));
1059
+ return jws;
1060
+ }
1061
+ /**
1062
+ * A circle the old identity is a member of: the new identity joins (at the
1063
+ * held head) and sends the join, the statement and the old identity's leave
1064
+ * to the owner, whose client swaps old for new once the old identity's final
1065
+ * version carries the statement; the leave also goes to every other member.
1066
+ */
1067
+ async function rejoin(app, napp, cid, statement) {
1068
+ const to = napp.userId;
1069
+ await syncCircle(napp, app, cid);
1070
+ let nc = (await loadCircle(napp.store, cid));
1071
+ if (nc.book[to]?.op !== "join")
1072
+ await signOwnJoin(napp, cid, nc.chain.head.hash);
1073
+ nc = (await loadCircle(napp.store, cid));
1074
+ const join = nc.book[to].jws;
1075
+ const c = (await loadCircle(app.store, cid));
1076
+ // Contesting, the old device may no longer be listed (the other rotation's final version), so its
1077
+ // leave can't verify: the owner's swap replaces the old identity anyway.
1078
+ const leave = await leaveAsOld(app, cid).catch((e) => {
1079
+ if (e instanceof P2PError)
1080
+ return undefined;
1081
+ throw e;
1082
+ });
1083
+ const owner = c.chain.head.owner;
1084
+ const d = await napp.deliver(owner, "circle", { own: to, sid: "~circle" }, { circles: [], joins: leave ? [join, leave] : [join], ops: [], rotation: statement }, { extraCaps: memberCaps(c, owner) });
1085
+ if (d.relays.length === 0)
1086
+ throw new CliError("undelivered", "the owner couldn't be reached");
1087
+ if (!leave)
1088
+ return;
1089
+ for (const m of c.chain.head.members) {
1090
+ if (m === app.userId || m === owner || m === to)
1091
+ continue;
1092
+ await deliverCircle(app, m, { joins: [leave] }, memberCaps(c, m)).catch(() => undefined);
1093
+ }
1094
+ }
1095
+ /** After the final version: this home becomes the new identity's. */
1096
+ async function finish(app, st) {
1097
+ if (st.step === "final") {
1098
+ st.archive = await adoptHome(app, newHomeOf(app.home), `${st.from.slice(4, 20)}-${st.startedAt}`);
1099
+ st.step = "done";
1100
+ await saveState(app.home, st);
1101
+ await reload(app);
1102
+ }
1103
+ else if (st.step === "done" && st.archive === undefined) {
1104
+ st.archive = join(app.home, "rotated");
1105
+ await saveState(app.home, st);
1106
+ }
1107
+ return rotateReport(app, st);
1108
+ }
1109
+ async function rotateReport(app, st) {
1110
+ const head = st.step === "done" ? (await app.view(st.to))?.head : undefined;
1111
+ const name = head?.name ?? "?";
1112
+ const warnings = [];
1113
+ const offline = Object.entries(st.devices).filter(([, d]) => d.status === "offline" || d.status === "aborted");
1114
+ if (offline.length > 0) {
1115
+ warnings.push(`${offline.length} of your devices didn't follow: on each, run \`p2p link join <code> --rotated\` with a code from \`p2p link start\` here`);
1116
+ }
1117
+ const failed = Object.entries(st.friends).filter(([, x]) => x === "failed");
1118
+ if (failed.length > 0)
1119
+ warnings.push(`${failed.length} friends weren't reached: \`p2p identity rotate --resend\` tries again`);
1120
+ if (!st.backupFile)
1121
+ warnings.push("your old backup phrase no longer restores this identity: save the new one (`p2p backup show`)");
1122
+ for (const w of warnings)
1123
+ app.warn(w);
1124
+ const followed = Object.entries(st.devices)
1125
+ .filter(([, d]) => d.status === "followed")
1126
+ .map(([did, d]) => ({ did, newDid: d.newDid ?? "", label: d.label }));
1127
+ return {
1128
+ from: st.from,
1129
+ to: st.to,
1130
+ address: displayAddress(st.to, name),
1131
+ fingerprint: displayFingerprint(st.to),
1132
+ did: app.userId === st.to ? app.did : "",
1133
+ step: st.step,
1134
+ ...(st.contest ? { contest: true } : {}),
1135
+ devices: {
1136
+ followed,
1137
+ offline: offline.map(([did, d]) => ({ did, label: d.label })),
1138
+ excluded: Object.entries(st.devices)
1139
+ .filter(([, d]) => d.status === "excluded")
1140
+ .map(([did, d]) => ({ did, label: d.label })),
1141
+ },
1142
+ friends: {
1143
+ invited: Object.values(st.friends).filter((x) => x === "sent").length,
1144
+ failed: failed.map(([u]) => u),
1145
+ },
1146
+ circles: Object.entries(st.circles).map(([cid, c]) => ({ cid, name: c.name, role: c.role, status: c.status, ...(c.reason ? { reason: c.reason } : {}) })),
1147
+ proofs: st.proofs ?? [],
1148
+ ...(st.finalVer !== undefined ? { finalVer: st.finalVer } : {}),
1149
+ ...(st.finalPublished !== undefined ? { finalPublished: st.finalPublished } : {}),
1150
+ ...(st.backupFile ? { backup: { file: st.backupFile } } : {}),
1151
+ ...(st.archive ? { archive: st.archive } : {}),
1152
+ warnings,
1153
+ };
1154
+ }
1155
+ /** The most invites `--resend` sends in a rolling hour: under the relays' per-sender contact limit. */
1156
+ export const RESEND_PER_HOUR = 50;
1157
+ /**
1158
+ * `p2p identity rotate --resend` (after the rotation is done): re-sends the
1159
+ * new identity's invite to the friends no invite reached, throttled under
1160
+ * the relays' per-sender limit on contacts (at most RESEND_PER_HOUR, or 80%
1161
+ * of what a relay advertises, in a rolling hour).
1162
+ */
1163
+ export async function rotateResend(app) {
1164
+ await app.load(true);
1165
+ const st = await readRotationState(app.home);
1166
+ if (!st || st.step !== "done" || app.userId !== st.to)
1167
+ throw new CliError("no_rotation", "--resend is for a finished rotation, on the device that rotated");
1168
+ if (!app.onEnvelope)
1169
+ receiving(app);
1170
+ const pool = await app.connect();
1171
+ let limit = RESEND_PER_HOUR;
1172
+ for (const r of app.relays) {
1173
+ try {
1174
+ const advertised = (await pool.ensure(r)).hello?.limits?.contactPerSenderPerHour;
1175
+ if (typeof advertised === "number" && advertised > 0)
1176
+ limit = Math.min(limit, Math.max(1, Math.floor(advertised * 0.8)));
1177
+ }
1178
+ catch {
1179
+ // unreachable: the default applies
1180
+ }
1181
+ }
1182
+ const now = Date.now();
1183
+ const recent = (st.resendAt ?? []).filter((t) => now - t < 3_600_000);
1184
+ const budget = Math.max(0, limit - recent.length);
1185
+ const todo = Object.entries(st.friends)
1186
+ .filter(([, x]) => x === "failed")
1187
+ .map(([u]) => u);
1188
+ let sent = 0;
1189
+ for (const peer of todo.slice(0, budget)) {
1190
+ st.friends[peer] = await inviteFriend(app, app, peer, st.statement);
1191
+ recent.push(Date.now());
1192
+ if (st.friends[peer] === "sent")
1193
+ sent++;
1194
+ st.resendAt = recent;
1195
+ await saveState(app.home, st);
1196
+ }
1197
+ const failed = Object.entries(st.friends)
1198
+ .filter(([, x]) => x === "failed")
1199
+ .map(([u]) => u);
1200
+ return { sent, failed, remaining: Math.max(0, todo.length - budget), throttled: todo.length > budget };
1201
+ }
1202
+ // ---------------------------------------------------------------------------
1203
+ // Rotations seen (friends' and co-members' clients)
1204
+ /** Every rotation statement this client has seen, by old userId (from contacts, bundles and documents). */
1205
+ async function recordRotation(app, r) {
1206
+ await app.state.update("rotations", (cur = {}) => {
1207
+ const list = cur[r.from] ?? [];
1208
+ if (list.some((s) => rotationKey(s) === rotationKey(r.statement)))
1209
+ return { result: undefined };
1210
+ // Bounded: at most 8 statements per old id, and the most recently seen 256 old ids.
1211
+ const { [r.from]: _prev, ...rest } = cur;
1212
+ const keys = Object.keys(rest);
1213
+ for (const k of keys.slice(0, Math.max(0, keys.length - (MAX_ROTATION_RECORDS - 1))))
1214
+ delete rest[k];
1215
+ return { next: { ...rest, [r.from]: [...list, r.statement].slice(-8) }, result: undefined };
1216
+ });
1217
+ }
1218
+ const MAX_ROTATION_RECORDS = 256;
1219
+ /** The verified rotations known for `old`: recorded ones and those its held document's tips carry. */
1220
+ export async function rotationsFor(app, old) {
1221
+ const out = new Map();
1222
+ const list = [...((await app.state.get("rotations"))?.[old] ?? []), ...((await app.view(old))?.rotations ?? [])];
1223
+ for (const s of list) {
1224
+ try {
1225
+ const v = verifyRotationSignatures(s);
1226
+ if (v.from === old)
1227
+ out.set(rotationKey(v.statement), v);
1228
+ }
1229
+ catch {
1230
+ // not a valid statement: ignored
1231
+ }
1232
+ }
1233
+ return [...out.values()];
1234
+ }
1235
+ /**
1236
+ * §2.8: more than one rotation from the same old id is a conflict
1237
+ * (rotationConflicts). Once the user settled one (`p2p identity dispute`),
1238
+ * the identities they rejected no longer count; a rotation to anyone new
1239
+ * conflicts again.
1240
+ */
1241
+ export async function rotationConflict(app, r) {
1242
+ const settled = (await app.state.get("rotationResolved"))?.[r.from];
1243
+ const all = [r, ...(await rotationsFor(app, r.from))].filter((x) => !settled || !settled.rejected.includes(x.to));
1244
+ return rotationConflicts(all).get(r.from);
1245
+ }
1246
+ async function recordApproval(app, old, a, opts = {}) {
1247
+ await app.state.update("rotationApprovals", (cur = {}) => {
1248
+ const list = (cur[old] ?? []).filter((x) => !(x.to === a.to && x.kind === a.kind && x.cid === a.cid));
1249
+ return { next: { ...cur, [old]: [...list, { ...a, at: Date.now() }].slice(-32) }, result: undefined };
1250
+ });
1251
+ // pre-release re-review M2: every device of this user learns the approval, so whichever of them sees a
1252
+ // later conflict suspends what was carried over.
1253
+ if (!opts.fromSync)
1254
+ await sendSync(app, { rotationApprovals: [{ old, ...a }] }).catch(() => 0);
1255
+ }
1256
+ /** A `rotationApprovals` sync from another of our devices: recorded here, and a conflict already known disputes now. */
1257
+ export async function importRotationApprovals(app, list) {
1258
+ if (!Array.isArray(list))
1259
+ return;
1260
+ const olds = new Set();
1261
+ for (const x of list.slice(0, 64)) {
1262
+ const a = x;
1263
+ if (!isUserIdish(a.old) || !isUserIdish(a.to) || (a.kind !== "friend" && a.kind !== "circle"))
1264
+ continue;
1265
+ if (a.cid !== undefined && typeof a.cid !== "string")
1266
+ continue;
1267
+ await recordApproval(app, a.old, { to: a.to, kind: a.kind, ...(typeof a.cid === "string" ? { cid: a.cid } : {}) }, { fromSync: true });
1268
+ olds.add(a.old);
1269
+ }
1270
+ for (const old of olds) {
1271
+ const known = await rotationsFor(app, old);
1272
+ const conflict = known.length > 0 ? await rotationConflict(app, known[0]) : undefined;
1273
+ if (conflict)
1274
+ await disputeRotation(app, old, conflict);
1275
+ }
1276
+ }
1277
+ const isUserIdish = (u) => typeof u === "string" && u.length > 0 && u.length <= 128 && /^[\x21-\x7e]+$/.test(u);
1278
+ /**
1279
+ * pre-release re-review N1: a conflict appeared for `old` after this user had
1280
+ * already carried something over through one of its rotations (a friendship
1281
+ * accepted, a member swapped into a circle it owns). Every identity it
1282
+ * carried over to is suspended at once: blocked locally (no delivery, no
1283
+ * session access, no circle standing) and the caps issued to it revoked at
1284
+ * its relays. The user is told loudly and offered a resolution: keep one of
1285
+ * the identities, or neither (`p2p identity dispute <id>`).
1286
+ *
1287
+ * Re-review M2: the block and the dispute go to the user's other devices
1288
+ * (`sync`), which suspend the same identities and hold the same dispute.
1289
+ * M3: on the owner's key-holding device, the suspended identities leave the
1290
+ * circles it owns at once (a new version without them); elsewhere the user
1291
+ * is told only a key holder can do that (it does when the sync reaches it).
1292
+ * M5: an identity the user already kept after checking out of band is not
1293
+ * suspended again by a later rotation from the same old id: that is held as
1294
+ * a new dispute.
1295
+ */
1296
+ async function disputeRotation(app, old, claimed, opts = {}) {
1297
+ // Identities the user already rejected stay out (a late sync of a dispute settled since is moot).
1298
+ const settled = (await app.state.get("rotationResolved"))?.[old];
1299
+ const candidates = claimed.filter((c) => !settled?.rejected.includes(c));
1300
+ if (candidates.length < 2)
1301
+ return;
1302
+ const approvals = ((await app.state.get("rotationApprovals"))?.[old] ?? []).filter((a) => candidates.includes(a.to));
1303
+ const kept = settled?.keep ?? undefined;
1304
+ const toSuspend = [...new Set([...approvals.map((a) => a.to), ...(opts.synced ?? []).filter((u) => candidates.includes(u))])].filter((u) => u !== kept);
1305
+ if (approvals.length === 0 && toSuspend.length === 0)
1306
+ return;
1307
+ const prior = (await app.state.get("disputes"))?.[old];
1308
+ if (prior && candidates.every((c) => prior.candidates.includes(c)) && toSuspend.every((u) => prior.suspended.some((s) => s.userId === u))) {
1309
+ await removeFromOwnedCircles(app, old, toSuspend);
1310
+ return;
1311
+ }
1312
+ const suspended = [...(prior?.suspended ?? [])];
1313
+ for (const to of toSuspend) {
1314
+ if (suspended.some((s) => s.userId === to))
1315
+ continue;
1316
+ const wasBlocked = await app.store.isBlocked(to);
1317
+ if (!wasBlocked)
1318
+ await app.revokeCaps(await blockUser(app.store, to)).catch(() => 0);
1319
+ suspended.push({ userId: to, wasBlocked });
1320
+ }
1321
+ const all = [...new Set([...(prior?.candidates ?? []), ...candidates])].sort();
1322
+ const item = withHeldId({ type: "rotation-dispute", from: old, at: Date.now(), old, candidates: all });
1323
+ if (prior)
1324
+ await dropHeld(app, (h) => h.id === prior.heldId);
1325
+ await hold(app, item);
1326
+ await app.state.update("disputes", (cur = {}) => ({
1327
+ next: { ...cur, [old]: { candidates: all, suspended, heldId: item.id, at: Date.now(), ...(prior?.removedFrom ? { removedFrom: prior.removedFrom } : {}) } },
1328
+ result: undefined,
1329
+ }));
1330
+ const ids = suspended.map((s) => s.userId);
1331
+ // (Not as `blocks`: each device records its own suspension, so a settlement unblocks only what it blocked.)
1332
+ // The statements go along: the other devices verify the conflict themselves (they never act on the claim alone).
1333
+ if (!opts.synced) {
1334
+ const statements = (await rotationsFor(app, old)).filter((r) => all.includes(r.to)).map((r) => r.statement);
1335
+ await sendSync(app, { rotationDispute: { old, candidates: all, suspended: ids, statements } }).catch(() => 0);
1336
+ }
1337
+ const approved = await Promise.all(ids.map((u) => app.addressOf(u)));
1338
+ const others = await Promise.all(all.filter((c) => !ids.includes(c)).map((u) => app.addressOf(u)));
1339
+ if (ids.length > 0) {
1340
+ app.io.err(`ALERT: your earlier approval of ${approved.join(" and ")} moving to a new key is now contested by another key${others.length ? ` (${others.join(", ")})` : ""}. ` +
1341
+ `Confirm out of band which one is really them. Until then ${approved.length === 1 ? "it is" : "they are"} suspended (no messages, no session access, no circle standing). ` +
1342
+ `Then: \`p2p identity dispute ${item.id} --keep <userId>\`, or \`--neither\``);
1343
+ }
1344
+ else {
1345
+ app.io.err(`ALERT: another move of ${await app.addressOf(old)} to a new key appeared (${others.join(", ")}) after you confirmed ${kept ? await app.addressOf(kept) : "one"} out of band. ` +
1346
+ `Nothing new is applied; the one you kept stays as it is. Check again, then: \`p2p identity dispute ${item.id} --keep <userId>\`, or \`--neither\``);
1347
+ }
1348
+ const from = { userId: old, did: "", address: await app.addressOf(old), self: false };
1349
+ const choices = await Promise.all(all.map(async (u) => ({ userId: u, address: await app.addressOf(u), approved: approvals.some((a) => a.to === u) || ids.includes(u) })));
1350
+ await app.state.addEvents([
1351
+ makeEvent(`rotation-dispute|${old}|${all.join(",")}`, "p2p.alert", Date.now(), { from, what: "rotation-dispute", old, suspended: ids, choices }),
1352
+ makeEvent(`rotation-dispute-held|${item.id}`, "p2p.held", Date.now(), { from, held: { id: item.id, type: item.type, old: { userId: old, address: from.address }, choices, conflict: true } }),
1353
+ ]);
1354
+ await removeFromOwnedCircles(app, old, ids);
1355
+ }
1356
+ /** A `rotationDispute` sync from another of our devices: the same identities suspended, the same dispute held. */
1357
+ /**
1358
+ * A `rotationDispute` sync from another of our devices (pre-release third review
1359
+ * M-A): never acted on as claimed. Its statements are verified here (each is
1360
+ * signed by the old and the new identity key) and the old identity's
1361
+ * document refreshed; only a conflict this device then verifies itself
1362
+ * counts, and only the identities in that verified conflict that the
1363
+ * sending device suspended are suspended here too (on a key holder, also
1364
+ * out of the circles it owns). A claim this device can't verify is a quiet
1365
+ * note: nothing is blocked, held or published.
1366
+ */
1367
+ export async function importRotationDispute(app, body) {
1368
+ const d = body;
1369
+ if (!isUserIdish(d.old) || !Array.isArray(d.candidates) || !Array.isArray(d.suspended))
1370
+ return;
1371
+ const old = d.old;
1372
+ const claimed = d.candidates.filter(isUserIdish).slice(0, 16);
1373
+ const suspended = d.suspended.filter(isUserIdish).slice(0, 16);
1374
+ if (claimed.length < 2)
1375
+ return;
1376
+ const unverified = async () => app.io.err(`p2p: another of your devices reported a contested move of ${await app.addressOf(old)} to a new key; this device can't verify it yet (nothing was changed)`);
1377
+ // Pre-release fourth review L-C: only about someone this device has to do with (a friend, a circle
1378
+ // member, an approval recorded here); anything else is dropped before anything is stored, so
1379
+ // junk reports can't push real records out of the bounded rotation list.
1380
+ if (!(await concernsUs(app, old)))
1381
+ return unverified();
1382
+ // The statements are verified in memory; they are stored only once the conflict verifies.
1383
+ const incoming = new Map();
1384
+ for (const s of Array.isArray(d.statements) ? d.statements.slice(0, 16) : []) {
1385
+ try {
1386
+ const r = verifyRotationSignatures(s);
1387
+ if (r.from === old)
1388
+ incoming.set(rotationKey(r.statement), r);
1389
+ }
1390
+ catch {
1391
+ // not a valid statement: ignored
1392
+ }
1393
+ }
1394
+ await app.refreshIdentity(old, [], { force: true, quiet: true }).catch(() => undefined);
1395
+ const settled = (await app.state.get("rotationResolved"))?.[old];
1396
+ const all = new Map(incoming);
1397
+ for (const r of await rotationsFor(app, old))
1398
+ all.set(rotationKey(r.statement), r);
1399
+ const conflict = rotationConflicts([...all.values()].filter((x) => !settled || !settled.rejected.includes(x.to))).get(old);
1400
+ const verified = (conflict ?? []).filter((c) => claimed.includes(c));
1401
+ if (!conflict || verified.length < 2)
1402
+ return unverified();
1403
+ for (const r of incoming.values())
1404
+ await recordRotation(app, r);
1405
+ await disputeRotation(app, old, conflict, { synced: suspended.filter((u) => verified.includes(u)) });
1406
+ }
1407
+ /** Whether `old` is someone this device has to do with: a friend (stored), a member of a circle it holds, or an approval recorded here. */
1408
+ async function concernsUs(app, old) {
1409
+ if (((await app.state.get("rotationApprovals"))?.[old] ?? []).length > 0)
1410
+ return true;
1411
+ if ((await app.store.listFriendships()).some((f) => pairOf(f, app.userId, old)))
1412
+ return true;
1413
+ for (const r of await app.store.listCircles()) {
1414
+ if ((await loadCircle(app.store, r.cid))?.chain.head.members.includes(old))
1415
+ return true;
1416
+ }
1417
+ return false;
1418
+ }
1419
+ /**
1420
+ * pre-release re-review M3: on the owner's key holder, suspended identities leave the
1421
+ * circles it owns (a version without them), recorded so a later `--keep`
1422
+ * puts the kept one back. Without the key, the user is told loudly.
1423
+ */
1424
+ async function removeFromOwnedCircles(app, old, ids) {
1425
+ if (ids.length === 0)
1426
+ return;
1427
+ const affected = [];
1428
+ for (const r of await app.store.listCircles()) {
1429
+ const c = await loadCircle(app.store, r.cid);
1430
+ if (!c || c.chain.head.owner !== app.userId || c.chain.frozen)
1431
+ continue;
1432
+ const h = c.chain.head;
1433
+ const members = ids.filter((u) => h.members.includes(u));
1434
+ if (members.length > 0)
1435
+ affected.push({ cid: r.cid, name: h.name, members, admins: members.filter((u) => h.admins.includes(u)) });
1436
+ }
1437
+ if (affected.length === 0)
1438
+ return;
1439
+ if (!app.isKeyholder) {
1440
+ app.io.err(`ALERT: ${affected.length === 1 ? "a circle" : "circles"} you own (${affected.map((a) => `"${a.name}"`).join(", ")}) still list${affected.length === 1 ? "s" : ""} the suspended ${ids.length === 1 ? "identity" : "identities"}: ` +
1441
+ `only a device that holds your identity key can take ${ids.length === 1 ? "it" : "them"} out. Your key holder does when it next runs (it was told); run \`p2p held\` there now.`);
1442
+ return;
1443
+ }
1444
+ const removed = [];
1445
+ for (const a of affected) {
1446
+ const h = (await loadCircle(app.store, a.cid)).chain.head;
1447
+ try {
1448
+ await ownerPublish(app, a.cid, { members: h.members.filter((m) => !a.members.includes(m)), admins: h.admins.filter((m) => !a.members.includes(m)) });
1449
+ for (const u of a.members)
1450
+ removed.push({ cid: a.cid, userId: u, admin: a.admins.includes(u) });
1451
+ }
1452
+ catch (e) {
1453
+ app.io.err(`ALERT: couldn't take the suspended ${ids.length === 1 ? "identity" : "identities"} out of your circle "${a.name}": ${e.message}. Run \`p2p held\` again`);
1454
+ }
1455
+ }
1456
+ if (removed.length === 0)
1457
+ return;
1458
+ await app.state.update("disputes", (cur = {}) => {
1459
+ const d = cur[old];
1460
+ if (!d)
1461
+ return { result: undefined };
1462
+ const prev = (d.removedFrom ?? []).filter((x) => !removed.some((y) => y.cid === x.cid && y.userId === x.userId));
1463
+ return { next: { ...cur, [old]: { ...d, removedFrom: [...prev, ...removed] } }, result: undefined };
1464
+ });
1465
+ }
1466
+ /**
1467
+ * `p2p identity dispute <id> --keep <userId> | --neither`: the user's
1468
+ * decision after checking out of band. The rejected identities' friendships
1469
+ * end locally, they leave the circles this owner swapped them into, and they
1470
+ * stay suspended; the kept one is restored (back into the circles it was
1471
+ * taken out of, or, when it was never carried over, its held rotation is
1472
+ * applied now) and later rotations to the rejected ones no longer count as a
1473
+ * conflict.
1474
+ *
1475
+ * pre-release re-review M2/M3: only on a key holder. The settlement changes circles
1476
+ * this user owns (which only the identity key signs) and goes to every
1477
+ * other device of the user, which take it from a key holder only; anywhere
1478
+ * else it is refused, loudly, with nothing changed.
1479
+ */
1480
+ export async function resolveDispute(app, id, choice) {
1481
+ const item = await getHeld(app, id);
1482
+ if (item.type !== "rotation-dispute" || !item.old)
1483
+ throw new CliError("usage", `${item.id} is not a contested rotation`);
1484
+ const old = item.old;
1485
+ const d = (await app.state.get("disputes"))?.[old];
1486
+ const candidates = d?.candidates ?? item.candidates ?? [];
1487
+ if (!choice.neither && !choice.keep)
1488
+ throw new CliError("usage", "choose one: --keep <userId> or --neither");
1489
+ if (!app.isKeyholder) {
1490
+ throw new CliError("needs_keyholder", `settle this on a device that holds your identity key: \`p2p identity dispute\` there changes the circles you own and tells all your devices. Nothing was changed here`);
1491
+ }
1492
+ const keep = choice.neither ? undefined : await app.resolveUser(choice.keep);
1493
+ if (keep !== undefined && !candidates.includes(keep))
1494
+ throw new CliError("usage", `${choice.keep} is not one of the identities that claim ${await app.addressOf(old)}`);
1495
+ await app.connectAndDrain().catch(() => undefined);
1496
+ const rejected = candidates.filter((c) => c !== keep);
1497
+ for (const rej of rejected) {
1498
+ if ((await app.store.listFriendships()).some((f) => pairOf(f, app.userId, rej)))
1499
+ await endFriendshipLocally(app, rej);
1500
+ // Owned circles that still list it (swapped in, not yet taken out) leave it.
1501
+ for (const r of await app.store.listCircles()) {
1502
+ const c = await loadCircle(app.store, r.cid);
1503
+ if (c && c.chain.head.owner === app.userId && !c.chain.frozen && c.chain.head.members.includes(rej)) {
1504
+ await ownerPublish(app, r.cid, { members: c.chain.head.members.filter((m) => m !== rej), admins: c.chain.head.admins.filter((m) => m !== rej) });
1505
+ }
1506
+ }
1507
+ // Their suspension stays: they are the user's own block now.
1508
+ }
1509
+ const out = { old, keep: keep ?? null, rejected };
1510
+ const unblock = await settleLocally(app, old, keep, rejected);
1511
+ if (keep !== undefined) {
1512
+ const friends = (await app.store.listFriendships()).some((f) => pairOf(f, app.userId, keep));
1513
+ if (friends && unblock) {
1514
+ // Its caps were revoked when it was suspended: a fresh friend cap.
1515
+ const cap = createCap(app.device, app.keys.cert, { purpose: "friend", sub: keep, relays: app.relays });
1516
+ await app.recordIssued(cap);
1517
+ await app.deliver(keep, "contact", { own: app.userId, sid: "~contact" }, { text: cap }).catch(() => undefined);
1518
+ }
1519
+ // Back into the circles it was taken out of when the dispute began.
1520
+ for (const r of (d?.removedFrom ?? []).filter((x) => x.userId === keep)) {
1521
+ const c = await loadCircle(app.store, r.cid);
1522
+ if (!c || c.chain.head.owner !== app.userId || c.chain.head.members.includes(keep))
1523
+ continue;
1524
+ await ownerPublish(app, r.cid, { members: [...c.chain.head.members, keep], admins: r.admin ? [...c.chain.head.admins.filter((m) => m !== keep), keep] : c.chain.head.admins }, { alsoTo: [keep] });
1525
+ }
1526
+ const held = (await app.state.get("held")) ?? [];
1527
+ const friendItem = held.find((h) => h.type === "rotation" && h.old === old && h.from === keep);
1528
+ if (friendItem && !friends)
1529
+ out.friend = (await approveRotation(app, friendItem, { force: true })).friend;
1530
+ for (const j of held.filter((h) => h.type === "rotation-join" && h.old === old && h.from === keep))
1531
+ await approveRotationJoin(app, j, { force: true });
1532
+ }
1533
+ await dropHeld(app, (h) => h.id === item.id);
1534
+ await sendSync(app, { rotationResolved: { old, keep: keep ?? null, rejected } }).catch(() => 0);
1535
+ return out;
1536
+ }
1537
+ /**
1538
+ * The settlement's local half (also applied from a key holder's sync):
1539
+ * recorded so the rejected identities no longer conflict, the kept one
1540
+ * unblocked unless the user had blocked it before, the dispute and the
1541
+ * rejected identities' held items dropped. Returns whether it unblocked.
1542
+ */
1543
+ async function settleLocally(app, old, keep, rejected, opts = {}) {
1544
+ const d = (await app.state.get("disputes"))?.[old];
1545
+ await app.state.update("rotationResolved", (cur = {}) => ({ next: { ...cur, [old]: { keep: keep ?? null, rejected, at: Date.now() } }, result: undefined }));
1546
+ const s = keep !== undefined ? d?.suspended.find((x) => x.userId === keep) : undefined;
1547
+ const unblock = !!s && !s.wasBlocked;
1548
+ if (unblock)
1549
+ await app.store.removeBlock(keep);
1550
+ await dropHeld(app, (h) => (h.type === "rotation-dispute" && h.old === old) ||
1551
+ ((h.type === "rotation" || h.type === "rotation-join") && h.old === old && (rejected.includes(h.from) || (opts.fromSync === true && h.from === keep))));
1552
+ await app.state.update("disputes", (cur = {}) => {
1553
+ const { [old]: _gone, ...rest } = cur;
1554
+ return { next: rest, result: undefined };
1555
+ });
1556
+ return unblock;
1557
+ }
1558
+ /** A `rotationResolved` sync: taken only from one of our current key holders (they alone settle, see resolveDispute). */
1559
+ export async function importRotationResolved(app, body, fromDid) {
1560
+ const r = body;
1561
+ if (!isUserIdish(r.old) || !Array.isArray(r.rejected) || (r.keep !== null && !isUserIdish(r.keep)))
1562
+ return;
1563
+ const view = await app.ownView().catch(() => undefined);
1564
+ if (!fromDid || fromDid === app.did || !view?.keyholders.includes(fromDid)) {
1565
+ app.io.err(`sync: ignored a settled dispute from ${fromDid ?? "an unknown device"}: only your key holders settle them`);
1566
+ return;
1567
+ }
1568
+ await settleLocally(app, r.old, r.keep ?? undefined, r.rejected.filter(isUserIdish).slice(0, 16), { fromSync: true });
1569
+ }
1570
+ /** Whether the old identity's own held document (its final version) carries exactly this statement. */
1571
+ export async function publishedByOld(app, r) {
1572
+ return ((await app.view(r.from))?.rotations ?? []).some((s) => rotationKey(s) === rotationKey(r.statement));
1573
+ }
1574
+ /** Records a rotation and flags the held items it now conflicts with. */
1575
+ export async function noteRotation(app, r) {
1576
+ await recordRotation(app, r);
1577
+ const conflict = await rotationConflict(app, r);
1578
+ if (conflict) {
1579
+ await disputeRotation(app, r.from, conflict);
1580
+ await app.state.update("held", (cur = []) => {
1581
+ let changed = false;
1582
+ const next = cur.map((h) => {
1583
+ if ((h.type === "rotation" || h.type === "rotation-join") && h.old === r.from && h.reason !== "conflict") {
1584
+ changed = true;
1585
+ return { ...h, reason: "conflict" };
1586
+ }
1587
+ return h;
1588
+ });
1589
+ return changed ? { next, result: undefined } : { result: undefined };
1590
+ });
1591
+ }
1592
+ return conflict !== undefined;
1593
+ }
1594
+ /** A friend's or co-member's document now carries a rotation (the 10-minute refresh, no push). */
1595
+ export async function noteDocRotations(app, userId) {
1596
+ for (const s of (await app.view(userId))?.rotations ?? []) {
1597
+ try {
1598
+ const r = verifyRotationSignatures(s);
1599
+ if (r.from === userId)
1600
+ await noteRotation(app, r);
1601
+ }
1602
+ catch {
1603
+ // ignored
1604
+ }
1605
+ }
1606
+ }
1607
+ function pairOf(f, a, b) {
1608
+ return (f.inviter === a && f.invitee === b) || (f.inviter === b && f.invitee === a);
1609
+ }
1610
+ /**
1611
+ * A friend's new identity sent its invite with the statement (`contact`
1612
+ * {rotation, invite}): held as "<friend> moved to a new key" (§2.8: carry a
1613
+ * friendship over only after asking). From someone who was never a friend
1614
+ * of the old identity, it is an ordinary invite.
1615
+ */
1616
+ export async function onRotationContact(app, env, at, from, rotation, invite) {
1617
+ const wasFriend = (await app.store.listFriendships()).some((f) => pairOf(f, app.userId, rotation.from));
1618
+ if (!wasFriend) {
1619
+ const item = withHeldId({ type: "invite", from: invite.iss, at, invite: invite.jws });
1620
+ await hold(app, item);
1621
+ return [makeEvent(env, "p2p.held", at, { from, held: { id: item.id, type: item.type, exp: invite.exp } })];
1622
+ }
1623
+ const conflict = await noteRotation(app, rotation);
1624
+ const item = withHeldId({ type: "rotation", from: rotation.to, at, invite: invite.jws, rotation: rotation.statement, old: rotation.from });
1625
+ await hold(app, conflict ? { ...item, reason: "conflict" } : item);
1626
+ return [
1627
+ makeEvent(env, "p2p.held", at, {
1628
+ from,
1629
+ held: { id: item.id, type: item.type, exp: invite.exp, old: { userId: rotation.from, address: await app.addressOf(rotation.from) }, ...(conflict ? { conflict: true } : {}) },
1630
+ }),
1631
+ ];
1632
+ }
1633
+ /** Ends every friendship with `old` on this user's side, locally (its devices are gone), and takes back our caps. */
1634
+ async function endFriendshipLocally(app, old) {
1635
+ const fs = (await app.store.listFriendships()).filter((f) => pairOf(f, app.userId, old));
1636
+ const ctx = app.signerCtx();
1637
+ const jwsList = [];
1638
+ for (const inv of new Set(fs.map((f) => f.inv))) {
1639
+ const j = createUnfriendV3(app.signer(), { peer: old, inv });
1640
+ const u = await verifyUnfriendV3(j, ctx);
1641
+ await app.store.addUnfriend({ iss: u.iss, peer: u.peer, inv: u.inv, iat: u.iat, jws: j });
1642
+ jwsList.push(j);
1643
+ }
1644
+ const caps = await capsToRevokeOnUnfriend(app.store, old);
1645
+ await app.revokeCaps(caps).catch(() => 0);
1646
+ await app.store.removeCapsHeld((c) => c.iss === old);
1647
+ if (jwsList.length > 0)
1648
+ await sendSync(app, { unfriends: jwsList });
1649
+ return jwsList.length;
1650
+ }
1651
+ /**
1652
+ * Approving a held "moved to a new key": both halves verified again, the old
1653
+ * identity's document refreshed, refused on any conflict and refused unless
1654
+ * the old identity's own final version carries this same statement (pre-release review H2: a statement it never published can't split it from its
1655
+ * friends); then the normal accept flow with the new identity, and the old
1656
+ * friendship ends locally. A petname carries over.
1657
+ */
1658
+ export async function approveRotation(app, item, opts = {}) {
1659
+ if (!item.rotation || !item.invite)
1660
+ throw new CliError("internal", "not a rotation item");
1661
+ const rot = verifyRotation(item.rotation);
1662
+ await app.connectAndDrain();
1663
+ await app.refreshIdentity(rot.from, [], { force: true, quiet: true });
1664
+ await noteDocRotations(app, rot.from);
1665
+ // `force`: the user settled a contest for this identity out of band (resolveDispute).
1666
+ const conflict = opts.force ? undefined : await rotationConflict(app, rot);
1667
+ if (conflict) {
1668
+ throw new CliError("rotation_conflict", `${await app.addressOf(rot.from)} has more than one rotation (to ${conflict.join(" and ")}): someone else holds their old key. Neither is applied: check with them out of band (petnames, proofs), decline these, and exchange a fresh invite`, { candidates: conflict });
1669
+ }
1670
+ if (!opts.force && !(await publishedByOld(app, rot))) {
1671
+ throw new CliError("not_published", `${await app.addressOf(rot.from)}'s own identity document doesn't carry this move yet (its final version isn't out): approve once it does. Until then it may not be theirs`);
1672
+ }
1673
+ let accepted;
1674
+ let failure;
1675
+ try {
1676
+ accepted = await accept(app, item.invite);
1677
+ }
1678
+ catch (e) {
1679
+ // The friendship is recorded even when the accept didn't get out yet.
1680
+ if (!(e instanceof CliError) || e.code !== "undelivered")
1681
+ throw e;
1682
+ failure = e;
1683
+ }
1684
+ await recordApproval(app, rot.from, { to: rot.to, kind: "friend" });
1685
+ const ended = await endFriendshipLocally(app, rot.from);
1686
+ const pet = await app.store.getPetname(rot.from);
1687
+ if (pet && !(await app.store.getPetname(rot.to))) {
1688
+ await app.store.setPetname(rot.to, pet);
1689
+ await sendSync(app, { petnames: { [rot.to]: pet } }).catch(() => 0);
1690
+ }
1691
+ await dropHeld(app, (h) => h.id === item.id);
1692
+ if (failure)
1693
+ throw failure;
1694
+ return { type: "rotation", from: rot.from, to: rot.to, friend: accepted.friend, delivered: accepted.delivered, endedOld: ended };
1695
+ }
1696
+ /** Whether this owner holds changes to `cid` for approval (`p2p circle hold`). */
1697
+ export async function circleHeld(app, cid) {
1698
+ return (await app.state.get("circleHold"))?.[cid] === true;
1699
+ }
1700
+ /**
1701
+ * When an owner's client may swap a rotated member in by itself (pre-release review
1702
+ * M1, L1): the old identity's published final version carries the
1703
+ * statement, no other rotation from it is known, the new identity isn't
1704
+ * blocked, the old one is a current member that wasn't removed before, and
1705
+ * the owner doesn't hold changes for approval.
1706
+ */
1707
+ async function rotationJoinVerdict(app, rot, cid) {
1708
+ const c = await loadCircle(app.store, cid);
1709
+ if (!c)
1710
+ return { apply: false, reason: "not-member" };
1711
+ const h = c.chain.head;
1712
+ if (await rotationConflict(app, rot))
1713
+ return { apply: false, reason: "conflict" };
1714
+ if (await app.store.isBlocked(rot.to))
1715
+ return { apply: false, reason: "blocked" };
1716
+ if ((c.record.removed ?? []).includes(rot.from) || (c.record.removed ?? []).includes(rot.to))
1717
+ return { apply: false, reason: "previously-removed" };
1718
+ if (!h.members.includes(rot.from))
1719
+ return { apply: false, reason: "not-member" };
1720
+ if (await circleHeld(app, cid))
1721
+ return { apply: false, reason: "held-by-policy" };
1722
+ if (!(await publishedByOld(app, rot)))
1723
+ return { apply: false, reason: "not-final-yet" };
1724
+ return { apply: true, adminHeld: h.admins.includes(rot.from) };
1725
+ }
1726
+ /** Swaps the old identity for the new as a member (never as an admin: that is held for the owner). */
1727
+ async function swapMember(app, rot, cid, withAdmin) {
1728
+ const h = (await loadCircle(app.store, cid)).chain.head;
1729
+ const members = h.members.includes(rot.from) ? h.members.map((m) => (m === rot.from ? rot.to : m)) : [...h.members.filter((m) => m !== rot.to), rot.to];
1730
+ const admins = h.admins.filter((m) => m !== rot.from && m !== rot.to);
1731
+ if (withAdmin)
1732
+ admins.push(rot.to);
1733
+ await recordApproval(app, rot.from, { to: rot.to, kind: "circle", cid });
1734
+ return ownerPublish(app, cid, { members, admins }, { alsoTo: [rot.from] });
1735
+ }
1736
+ async function holdRotationJoin(app, env, at, from, rot, cid, join, reason) {
1737
+ const c = (await loadCircle(app.store, cid));
1738
+ const item = withHeldId({ type: "rotation-join", from: rot.to, at, cid, head: c.chain.head.jws, join, rotation: rot.statement, old: rot.from, reason });
1739
+ await hold(app, item);
1740
+ return makeEvent(env, "p2p.held", at, { from, held: { id: item.id, type: item.type, cid, reason, old: { userId: rot.from, address: await app.addressOf(rot.from) }, ...(reason === "conflict" ? { conflict: true } : {}) } }, {}, `${join}|${reason}`);
1741
+ }
1742
+ /**
1743
+ * A `circle` bundle carrying `rotation` with the new identity's join. For a
1744
+ * circle this device owns (key holder): the old identity swapped for the new
1745
+ * as a member in one version only when rotationJoinVerdict allows it; an
1746
+ * admin's rights are held for the owner's approval; anything else is held as
1747
+ * `rotation-join` (re-checked when the old identity's final version shows up).
1748
+ */
1749
+ export async function onRotationJoin(app, env, at, from, statement, sender, joins) {
1750
+ const out = { events: [], handled: new Set() };
1751
+ let rot;
1752
+ try {
1753
+ rot = verifyRotation(statement);
1754
+ }
1755
+ catch {
1756
+ return out;
1757
+ }
1758
+ if (rot.to !== sender)
1759
+ return out;
1760
+ // Only for circles this device owns (a key holder) that the old identity is, or was, a member of:
1761
+ // anyone can mint a statement between two fresh keys, so nothing else is recorded.
1762
+ const relevant = [];
1763
+ for (const s of joins) {
1764
+ if (s.iss !== rot.to || s.op !== "join")
1765
+ continue;
1766
+ const c = await loadCircle(app.store, s.cid);
1767
+ if (!c || c.chain.head.owner !== app.userId || !app.isKeyholder)
1768
+ continue;
1769
+ if (!c.chain.head.members.includes(rot.from) && c.book[rot.from] === undefined)
1770
+ continue;
1771
+ relevant.push({ s, c });
1772
+ }
1773
+ if (relevant.length === 0)
1774
+ return out;
1775
+ out.old = rot.from;
1776
+ await noteRotation(app, rot);
1777
+ // The old identity's own document decides (M1): refresh it first.
1778
+ await app.refreshIdentity(rot.from, [], { force: true, quiet: true }).catch(() => undefined);
1779
+ for (const { s, c } of relevant) {
1780
+ out.handled.add(s.cid);
1781
+ if (c.chain.head.members.includes(rot.to))
1782
+ continue;
1783
+ const v = await rotationJoinVerdict(app, rot, s.cid);
1784
+ if (v.apply) {
1785
+ const pub = await swapMember(app, rot, s.cid, false);
1786
+ out.events.push(makeEvent(env, "p2p.circle", at, { from, event: "member-rotated", cid: s.cid, ver: pub.ver, old: rot.from, member: rot.to }, {}, `${s.cid}|rot`));
1787
+ if (v.adminHeld)
1788
+ out.events.push(await holdRotationJoin(app, env, at, from, rot, s.cid, s.jws, "admin"));
1789
+ continue;
1790
+ }
1791
+ out.events.push(await holdRotationJoin(app, env, at, from, rot, s.cid, s.jws, v.reason));
1792
+ }
1793
+ return out;
1794
+ }
1795
+ /**
1796
+ * Held `rotation-join`s waiting for the old identity's final version: applied
1797
+ * once it carries the statement (and nothing else stops them). Run after a
1798
+ * drain and on watch's 10-minute refresh.
1799
+ */
1800
+ export async function retryRotationJoins(app) {
1801
+ if (!app.keys || !app.isKeyholder)
1802
+ return [];
1803
+ const waiting = ((await app.state.get("held")) ?? []).filter((h) => h.type === "rotation-join" && h.reason === "not-final-yet" && h.rotation && h.cid);
1804
+ const events = [];
1805
+ for (const h of waiting) {
1806
+ let rot;
1807
+ try {
1808
+ rot = verifyRotation(h.rotation);
1809
+ }
1810
+ catch {
1811
+ continue;
1812
+ }
1813
+ await app.refreshIdentity(rot.from, [], { force: true, quiet: true }).catch(() => undefined);
1814
+ const c = await loadCircle(app.store, h.cid);
1815
+ if (!c || c.chain.head.owner !== app.userId)
1816
+ continue;
1817
+ if (c.chain.head.members.includes(rot.to)) {
1818
+ await dropHeld(app, (x) => x.id === h.id);
1819
+ continue;
1820
+ }
1821
+ const v = await rotationJoinVerdict(app, rot, h.cid);
1822
+ if (!v.apply) {
1823
+ if (v.reason !== "not-final-yet")
1824
+ await app.state.update("held", (cur = []) => ({ next: cur.map((x) => (x.id === h.id ? { ...x, reason: v.reason } : x)), result: undefined }));
1825
+ continue;
1826
+ }
1827
+ const pub = await swapMember(app, rot, h.cid, false);
1828
+ await dropHeld(app, (x) => x.id === h.id);
1829
+ const from = { userId: rot.to, did: "", address: await app.addressOf(rot.to), self: false };
1830
+ events.push(makeEvent(`rotation-join|${h.id}`, "p2p.circle", Date.now(), { from, event: "member-rotated", cid: h.cid, ver: pub.ver, old: rot.from, member: rot.to }));
1831
+ if (v.adminHeld)
1832
+ events.push(await holdRotationJoin(app, `rotation-join|${h.id}`, Date.now(), from, rot, h.cid, h.join ?? "", "admin"));
1833
+ }
1834
+ if (events.length > 0)
1835
+ await app.state.addEvents(events);
1836
+ return events;
1837
+ }
1838
+ /**
1839
+ * Owner: approves a held `rotation-join` (refused on a conflict, or before
1840
+ * the old identity's final version carries the statement): swaps old for
1841
+ * new, or adds the new identity, and, since the owner approves it here,
1842
+ * carries an admin's rights over (`admin` items do only that).
1843
+ */
1844
+ export async function approveRotationJoin(app, item, opts = {}) {
1845
+ if (!item.rotation || !item.cid)
1846
+ throw new CliError("internal", "not a rotation-join item");
1847
+ const rot = verifyRotation(item.rotation);
1848
+ await app.connectAndDrain();
1849
+ await app.refreshIdentity(rot.from, [], { force: true, quiet: true });
1850
+ await noteDocRotations(app, rot.from);
1851
+ const conflict = opts.force ? undefined : await rotationConflict(app, rot);
1852
+ if (conflict)
1853
+ throw new CliError("rotation_conflict", `more than one rotation from ${await app.addressOf(rot.from)} (to ${conflict.join(" and ")}): neither is applied; resolve it out of band`, { candidates: conflict });
1854
+ if (!opts.force && !(await publishedByOld(app, rot))) {
1855
+ throw new CliError("not_published", `${await app.addressOf(rot.from)}'s own identity document doesn't carry this move yet: approve once its final version is out`);
1856
+ }
1857
+ const c = await loadCircle(app.store, item.cid);
1858
+ if (!c)
1859
+ throw new CliError("not_found", "circle not held");
1860
+ const h = c.chain.head;
1861
+ let ver = h.ver;
1862
+ const wasAdmin = h.admins.includes(rot.from) || h.admins.includes(rot.to) || item.reason === "admin";
1863
+ if (!h.members.includes(rot.to) || (wasAdmin && !h.admins.includes(rot.to)))
1864
+ ver = (await swapMember(app, rot, item.cid, wasAdmin)).ver;
1865
+ await dropHeld(app, (x) => x.id === item.id);
1866
+ return { type: "rotation-join", cid: item.cid, old: rot.from, member: rot.to, ver, admin: wasAdmin };
1867
+ }
1868
+ // ---------------------------------------------------------------------------
1869
+ // The user's other devices: a rotation of our own identity
1870
+ /**
1871
+ * A `sync` from our own (old) identity with `{rotation: {statement, link,
1872
+ * keyholder?}}` (pre-release review H2): never followed by itself. On an ordinary
1873
+ * device it is held (with the new fingerprint and the sending device) for
1874
+ * the user to follow, or not; a key-holding device never follows, it alerts
1875
+ * and offers to contest. Only a sync from a current key holder counts, with
1876
+ * a statement from our own identity.
1877
+ */
1878
+ export async function noteOwnRotation(app, body, fromDid) {
1879
+ if (typeof body !== "object" || body === null)
1880
+ return;
1881
+ // Only a key holder can rotate (it holds the identity key): a sync from any other device of ours
1882
+ // naming a rotation is ignored, so a lost ordinary device can't move the others away.
1883
+ const own = await app.view(app.userId);
1884
+ if (!fromDid || !own?.keyholders.includes(fromDid)) {
1885
+ app.io.err("ignored a rotation sync from a device that isn't one of your key holders");
1886
+ return;
1887
+ }
1888
+ const b = body;
1889
+ let r;
1890
+ try {
1891
+ r = verifyRotation(b.statement);
1892
+ if (typeof b.link !== "string")
1893
+ return;
1894
+ parseLinkCode(b.link);
1895
+ }
1896
+ catch {
1897
+ app.io.err("ignored a rotation sync that doesn't verify");
1898
+ return;
1899
+ }
1900
+ if (r.from !== app.userId)
1901
+ return;
1902
+ await raiseRotationAlert(app, r, fromDid);
1903
+ if (app.isKeyholder)
1904
+ return;
1905
+ const deviceLabel = certLabel(own.head.certs?.find((c) => certDid(c) === fromDid));
1906
+ const item = withHeldId({ type: "rotation-follow", from: r.to, at: Date.now(), rotation: r.statement, old: r.from, device: fromDid, deviceLabel, newFingerprint: displayFingerprint(r.to) });
1907
+ // The link code is a secret: kept apart from the held item (which is listed), by its id.
1908
+ await app.state.update("follows", (cur = {}) => ({ next: { ...cur, [item.id]: { statement: r.statement, link: b.link, fromDid, at: Date.now() } }, result: undefined }));
1909
+ await hold(app, item);
1910
+ await app.state.addEvents([
1911
+ makeEvent(`rotation-follow|${item.id}`, "p2p.held", Date.now(), {
1912
+ from: { userId: r.to, did: fromDid, address: await app.addressOf(r.to), self: false },
1913
+ held: { id: item.id, type: item.type, newFingerprint: item.newFingerprint, device: fromDid, deviceLabel, old: { userId: r.from, address: await app.addressOf(r.from) } },
1914
+ }),
1915
+ ]);
1916
+ }
1917
+ let following = false;
1918
+ /**
1919
+ * `p2p identity follow <id>` (or approving the held item): the user's own
1920
+ * decision to move this device with its identity. Links to the new identity
1921
+ * with the code the key holder sent, then makes this home the new identity's
1922
+ * (the old one archived). A key-holding device never follows. If the key
1923
+ * holder isn't answering any more, re-link by hand (`link join --rotated`).
1924
+ */
1925
+ export async function followHeld(app, idOrItem) {
1926
+ await app.load(true);
1927
+ const item = typeof idOrItem === "string" ? await getHeld(app, idOrItem) : idOrItem;
1928
+ if (item.type !== "rotation-follow" || !item.rotation)
1929
+ throw new CliError("usage", `${item.id} is not a rotation of your identity`);
1930
+ if (app.isKeyholder) {
1931
+ throw new CliError("keyholder", "a key-holding device never follows a rotation: if you started it, link this device to the new identity by hand (`p2p link start` there, `p2p link join <code> --rotated` here); if you didn't, contest it (`p2p identity rotate --contest`)");
1932
+ }
1933
+ const rec = (await app.state.get("follows"))?.[item.id];
1934
+ if (!rec)
1935
+ throw new CliError("not_found", "this rotation's link code is gone: re-link by hand (`p2p link start` on the new identity, `p2p link join <code> --rotated` here)");
1936
+ const r = verifyRotationSignatures(rec.statement);
1937
+ if (r.from !== app.userId)
1938
+ throw new CliError("wrong_identity", "that rotation is another identity's");
1939
+ if (following)
1940
+ throw new CliError("busy", "already following");
1941
+ following = true;
1942
+ const tmp = followHomeOf(app.home);
1943
+ try {
1944
+ await rm(tmp, { recursive: true, force: true });
1945
+ const napp = await appAt(app, tmp);
1946
+ let res;
1947
+ try {
1948
+ const j = await linkJoin(napp, rec.link, { label: certLabel(app.keys.cert) || defaultLabel(), maxWaitMs: followWaitMs(app) });
1949
+ res = await j.wait();
1950
+ }
1951
+ finally {
1952
+ await napp.close();
1953
+ }
1954
+ if (res.userId !== r.to)
1955
+ throw new CliError("wrong_identity", `the link joined ${res.userId}, not ${r.to}`);
1956
+ const old = app.userId;
1957
+ const tag = `${old.slice(4, 20)}-${Date.now()}`;
1958
+ // L4: from here the swap is resumable (recoverInterruptedFollow), even if this process dies.
1959
+ await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: r.to, tag }), { mode: 0o600 });
1960
+ await adoptHome(app, tmp, tag);
1961
+ await reload(app);
1962
+ app.io.err(`this device moved with your identity: it is now ${res.address} (${res.did})`);
1963
+ await app.state.addEvents([makeEvent(`rotated|${old}|${r.to}`, "p2p.contact", Date.now(), { from: { userId: r.to, did: res.did, address: res.address, self: true }, what: "rotated", old })]);
1964
+ return { ...res, from: old };
1965
+ }
1966
+ catch (e) {
1967
+ if (!(await exists(join(tmp, "linked.json"))))
1968
+ await rm(tmp, { recursive: true, force: true }).catch(() => undefined);
1969
+ if (e instanceof CliError && (e.code === "wrong_identity" || e.code === "keyholder"))
1970
+ throw e;
1971
+ throw new CliError("follow_failed", `couldn't follow your identity to its new key (${e.message}): if the device that rotated has stopped waiting, re-link by hand: \`p2p link start\` on a device of the new identity, then here \`p2p link join <code> --rotated\``);
1972
+ }
1973
+ finally {
1974
+ following = false;
1975
+ }
1976
+ }
1977
+ function followWaitMs(app) {
1978
+ const v = Number(app.env.P2P_FOLLOW_WAIT_MS ?? "");
1979
+ return Number.isFinite(v) && v > 0 ? v : 60_000;
1980
+ }
1981
+ /**
1982
+ * L4: a follow that linked to the new identity but died before (or while)
1983
+ * this home was swapped finishes on the next run: `rotation/follow` then
1984
+ * holds the new identity and a `linked.json` marker. Pure file work, run
1985
+ * before the home's identity is loaded. Returns true when it finished one.
1986
+ */
1987
+ export async function recoverInterruptedFollow(home) {
1988
+ const tmp = followHomeOf(home);
1989
+ let marker;
1990
+ try {
1991
+ marker = JSON.parse(await readFile(join(tmp, "linked.json"), "utf8"));
1992
+ }
1993
+ catch {
1994
+ return false;
1995
+ }
1996
+ if (!(await exists(join(tmp, "cli"))) && (await exists(join(home, "cli")))) {
1997
+ // The new identity is already in place (the swap finished but the marker stayed).
1998
+ await rm(tmp, { recursive: true, force: true });
1999
+ return false;
2000
+ }
2001
+ await moveHomes(home, tmp, typeof marker.tag === "string" && /^[\w-]{1,80}$/.test(marker.tag) ? marker.tag : `follow-${Date.now()}`);
2002
+ return true;
2003
+ }
2004
+ /**
2005
+ * `p2p link join <code> --rotated`: a device whose identity was rotated
2006
+ * without it re-links by hand. Allowed only when this home's identity
2007
+ * carries a rotation (its final version, or a rotation our key holder
2008
+ * sent), and only into an identity a rotation names.
2009
+ */
2010
+ export async function relinkRotated(app, code, opts = {}) {
2011
+ await app.load(true);
2012
+ await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
2013
+ const targets = new Set();
2014
+ const sent = Object.values((await app.state.get("follows")) ?? {}).map((f) => f.statement);
2015
+ for (const s of [...((await app.view(app.userId))?.rotations ?? []), ...sent]) {
2016
+ try {
2017
+ const r = verifyRotationSignatures(s);
2018
+ if (r.from === app.userId)
2019
+ targets.add(r.to);
2020
+ }
2021
+ catch {
2022
+ // ignored
2023
+ }
2024
+ }
2025
+ if (targets.size === 0)
2026
+ throw new CliError("not_rotated", "this device's identity hasn't been rotated: --rotated only re-links a device whose identity moved (§2.8)");
2027
+ const tmp = followHomeOf(app.home);
2028
+ await rm(tmp, { recursive: true, force: true });
2029
+ const napp = await appAt(app, tmp);
2030
+ const j = await linkJoin(napp, code, { label: opts.label ?? (certLabel(app.keys.cert) || defaultLabel()) });
2031
+ const old = app.userId;
2032
+ return {
2033
+ compareCode: j.compareCode,
2034
+ did: j.did,
2035
+ wait: async () => {
2036
+ let res;
2037
+ try {
2038
+ res = await j.wait();
2039
+ }
2040
+ finally {
2041
+ await napp.close();
2042
+ }
2043
+ if (!targets.has(res.userId)) {
2044
+ await rm(tmp, { recursive: true, force: true });
2045
+ throw new CliError("wrong_identity", `that code links to ${res.userId}, which isn't where your identity moved (${[...targets].join(", ")})`);
2046
+ }
2047
+ const tag = `${old.slice(4, 20)}-${Date.now()}`;
2048
+ await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: res.userId, tag }), { mode: 0o600 });
2049
+ await adoptHome(app, tmp, tag);
2050
+ await reload(app);
2051
+ return { ...res, from: old };
2052
+ },
2053
+ };
2054
+ }