@peer2peer/cli 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/rotation.js CHANGED
@@ -53,13 +53,15 @@
53
53
  // (`p2p identity rotate --contest`), which makes that conflict;
54
54
  // - rotation can't recover a compromised owner's circles: those need a new
55
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";
56
+ import { copyFile, lstat, mkdir, readFile, rename, rm, stat, writeFile, chmod } from "node:fs/promises";
57
57
  import { join } from "node:path";
58
- import { addIdentityVersion, applyCircleBundle, b64uEncode, backupPhraseFromSeed, capsToRevokeOnUnfriend, createCircleTransferAccept, createDeviceCert, createIdentityDoc, createMembershipStatement, createProof, createRotation, createUnfriendV3, decodeTyped, displayAddress, displayFingerprint, dnsProofRecord, encodeLinkCode, generateDeviceKeysV3, generateIdentityKey, IdentityChain, INVITE_MAX_TTL_SEC, blockUser, createCap, jwsHash, LINK_TTL_SEC, linkId, liveFriendshipsV3, loadCircle, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
58
+ import { addIdentityVersion, applyCircleBundle, b64uEncode, backupPhraseFromSeed, capsToRevokeOnUnfriend, createCircleTransferAccept, createDeviceCert, createIdentityDoc, createMembershipStatement, createProof, createRotation, createUnfriendV3, decodeTyped, displayAddress, displayFingerprint, dnsProofRecord, encodeLinkCode, generateDeviceKeysV3, generateIdentityKey, IdentityChain, INVITE_MAX_TTL_SEC, isCanonicalRelayUrl, isDid, blockUser, createCap, jwsHash, LINK_TTL_SEC, linkId, liveFriendshipsV3, loadCircle, mergePrevTip, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sanitizePeerText, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
59
59
  import { FileDocBackend } from "@peer2peer/core/v3/node";
60
60
  import { App, certDid, defaultLabel, newKeysDoc } from "./app.js";
61
61
  import { CliError } from "./errors.js";
62
- import { linkGet, linkPut, relayCode, sleep } from "./relay-client.js";
62
+ import { rotationLockOf, withRotationLock } from "./rotation-lock.js";
63
+ import { branchLine } from "./format.js";
64
+ import { fetchTips, linkGet, linkPut, publishOver, relayCode, RelayConnection, sleep } from "./relay-client.js";
63
65
  import { deliverCircle, memberCaps, ownerPublish, signOwnJoin } from "./circle-ops.js";
64
66
  import { accept, dropHeld, getHeld, hold, mintInvite, withHeldId } from "./social.js";
65
67
  import { exportAll, exportCircle, mergeRemovals, sendSync } from "./sync.js";
@@ -67,6 +69,22 @@ import { linkJoin } from "./identity.js";
67
69
  import { renewPersonToken } from "./projects.js";
68
70
  import { makeEvent, receiving } from "./inbound.js";
69
71
  const STEPS = ["created", "published", "devices", "social", "final", "done"];
72
+ /** Printable ASCII only, one to 2048 characters (a single anchored class: linear, no backtracking). */
73
+ const PRINTABLE_ASCII = /^[\x21-\x7e]{1,2048}$/;
74
+ /**
75
+ * #91: a branch summary for the plan and the `branch_ambiguous` error. Its relay URLs and device ids come from
76
+ * versions whoever holds the identity key may have signed. Core's parser only lets canonical relay URLs (§5.1:
77
+ * WHATWG-serialised, so percent-encoded, no userinfo, query or fragment) and device ids (`d_` + base32) into a
78
+ * verified version; they are checked again here before they are printed, and anything else is left out.
79
+ */
80
+ export function branchSummary(hash, ver, by, relays) {
81
+ return {
82
+ hash,
83
+ ver,
84
+ by: [...new Set(by.filter((d) => isDid(d)))],
85
+ relays: relays.filter((r) => typeof r === "string" && PRINTABLE_ASCII.test(r) && isCanonicalRelayUrl(r)),
86
+ };
87
+ }
70
88
  const rotationDir = (home) => join(home, "rotation");
71
89
  const newHomeOf = (home) => join(rotationDir(home), "new");
72
90
  const followHomeOf = (home) => join(rotationDir(home), "follow");
@@ -85,6 +103,15 @@ async function dropState(home) {
85
103
  await rm(newHomeOf(home), { recursive: true, force: true });
86
104
  }
87
105
  const after = (s, step) => STEPS.indexOf(s.step) >= STEPS.indexOf(step);
106
+ /** Whether `p` is a symbolic link (a missing path isn't). */
107
+ async function isLink(p) {
108
+ try {
109
+ return (await lstat(p)).isSymbolicLink();
110
+ }
111
+ catch {
112
+ return false;
113
+ }
114
+ }
88
115
  async function exists(p) {
89
116
  try {
90
117
  await stat(p);
@@ -107,6 +134,11 @@ async function appAt(app, home) {
107
134
  * `<home>/rotated/<tag>/`, `src`'s take their place.
108
135
  */
109
136
  async function moveHomes(home, src, tag) {
137
+ // Only folders a follow or rotation made: a link (to another home's state) is never moved into this one.
138
+ for (const p of [src, join(src, "cli"), join(src, "v3"), join(src, "cursors")]) {
139
+ if (await isLink(p))
140
+ throw new CliError("refused", `${p} is a symbolic link: nothing was moved into ${home}`);
141
+ }
110
142
  const archive = join(home, "rotated", tag);
111
143
  await mkdir(archive, { recursive: true, mode: 0o700 });
112
144
  const srcHasState = await exists(join(src, "cli"));
@@ -124,11 +156,23 @@ async function moveHomes(home, src, tag) {
124
156
  await rm(join(archive, d, ".lock"), { force: true });
125
157
  return archive;
126
158
  }
159
+ /**
160
+ * After a swap: the home must now hold the identity the link joined. Anything else (files changed
161
+ * under the swap) keeps no person token and stops the command.
162
+ */
163
+ export function assertAdopted(app, userId) {
164
+ if (app.userId === userId)
165
+ return;
166
+ app.front = false;
167
+ throw new CliError("wrong_identity", `after the move this home holds ${app.userId}, not ${userId}: it stopped here`);
168
+ }
127
169
  /**
128
170
  * Makes `src` (a home holding the new identity) this home's identity, after
129
171
  * the old identity's work here has stopped (moveHomes).
130
172
  */
131
173
  export async function adoptHome(app, src, tag) {
174
+ // The identity swapped in is this command's own (the person's token was for the one it replaces).
175
+ app.identityMadeHere = true;
132
176
  // Nothing of the old identity may still be writing: an envelope handled mid-swap would take its
133
177
  // lock into the archive (or write the old identity's state into the new home).
134
178
  await app.close();
@@ -158,10 +202,10 @@ function certLabel(cert) {
158
202
  return "";
159
203
  }
160
204
  }
161
- /** Our own identity's chain, verified (or undefined); pending heads never narrow our own view (#65 review M1). */
205
+ /** Our own identity's chain, verified (or undefined); pending heads (and #92 left-out versions) never narrow our own view (#65 review M1). */
162
206
  async function ownChain(app) {
163
207
  const stored = await app.store.getIdentity(app.userId);
164
- return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [] }) : undefined;
208
+ return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [], leftOut: [] }) : undefined;
165
209
  }
166
210
  /**
167
211
  * The newest version of our identity that is not a rotation's final one:
@@ -183,6 +227,111 @@ async function preRotationHead(app) {
183
227
  }
184
228
  return undefined;
185
229
  }
230
+ /**
231
+ * #75: our identity forked by a version that connects to our history but leaves this device out. A
232
+ * merge keeps only the intersection, so it would leave this device unlisted (it couldn't publish), and
233
+ * the relays already refuse it. Returns the plain tips (no rotation) and the candidates for this
234
+ * device's own branch: those that list it as a key holder. Undefined when our identity isn't forked
235
+ * that way: one plain tip, a fork that lists this device on every branch (publishNext merges it), or
236
+ * one that lists it on none (this device can't publish, and can't take this path either).
237
+ */
238
+ async function ownBranchFork(app) {
239
+ const chain = await ownChain(app);
240
+ if (!chain)
241
+ return undefined;
242
+ const plain = chain.tips().filter((t) => t.rotation === undefined);
243
+ const candidates = plain.filter((t) => t.devices.includes(app.did) && t.keyholders.includes(app.did));
244
+ if (plain.length < 2 || candidates.length === 0 || candidates.length === plain.length)
245
+ return undefined;
246
+ return { chain, plain, candidates };
247
+ }
248
+ /**
249
+ * #75: which candidate (ownBranchFork) is this device's own branch, by provenance, never by `ver` or
250
+ * hash (whoever holds the identity key can pick those). A candidate is plausible when every version on
251
+ * it since the fork point (the versions not behind every plain tip) is in this device's publish log or
252
+ * was published `by` this device or a device that a version in its publish log lists. One candidate, or
253
+ * exactly one plausible: that one (#91: with the other candidates as `others`, warned about and shown in
254
+ * the plan: the owner's branch counts as implausible when a version on it comes from an owner device the
255
+ * publish log never lists, so a stolen device's branch could be the only plausible one). Otherwise the
256
+ * user chooses (`choice`, `--branch <hash>`), shown each branch's publishers and relays. Undefined when
257
+ * our identity isn't forked that way.
258
+ */
259
+ async function ownBranchTip(app, choice) {
260
+ const fork = await ownBranchFork(app);
261
+ if (!fork) {
262
+ if (choice !== undefined)
263
+ throw new CliError("usage", "--branch: your identity isn't forked by a version that leaves this device out");
264
+ return undefined;
265
+ }
266
+ const { chain, plain, candidates } = fork;
267
+ if (choice !== undefined) {
268
+ const chosen = candidates.find((t) => t.hash === choice);
269
+ if (!chosen)
270
+ throw new CliError("usage", `--branch ${choice}: not a branch of your identity that lists this device (${candidates.map((t) => t.hash).join(", ")})`);
271
+ return { tip: chosen, others: [] };
272
+ }
273
+ if (candidates.length === 1)
274
+ return { tip: candidates[0], others: [] };
275
+ const log = new Set((await app.store.getPublishLog()).published);
276
+ // #91: every device any version in the publish log lists, including ones a later version revoked. That only
277
+ // ever makes more branches plausible, so it fails safe: more ambiguity (the user chooses), never a silent pick.
278
+ const trusted = new Set([app.did, ...[...log].flatMap((h) => chain.get(h)?.devices ?? [])]);
279
+ const behind = plain.map((t) => new Set(chain.ancestors(t.hash).map((v) => v.hash)));
280
+ const common = new Set([...behind[0]].filter((h) => behind.every((set) => set.has(h))));
281
+ const since = (t) => chain.ancestors(t.hash).filter((v) => !common.has(v.hash));
282
+ const plausible = candidates.filter((t) => since(t).every((v) => log.has(v.hash) || trusted.has(v.by)));
283
+ const branches = candidates.map((t) => branchSummary(t.hash, t.ver, since(t).map((v) => v.by), t.relays));
284
+ if (plausible.length === 1)
285
+ return { tip: plausible[0], others: branches.filter((b) => b.hash !== plausible[0].hash) };
286
+ throw new CliError("branch_ambiguous", `your identity is forked by a version that leaves this device out, and more than one branch still lists it: ${branches
287
+ .map(branchLine)
288
+ .join("; ")}. Someone else holds your identity key. Check which branch is yours, then run \`p2p identity rotate --plan --branch <hash>\``, { branches });
289
+ }
290
+ /** #91: the warning when provenance picked our own branch among others that still list this device. */
291
+ function otherBranchesWarning(tip, others) {
292
+ return `your identity is forked, and the plan builds on the branch ${tip} as yours (its versions come from your devices); other branches still list this device: ${others
293
+ .map(branchLine)
294
+ .join("; ")}. If ${tip} isn't yours, drop this plan (\`p2p identity rotate --cancel\`) and choose with \`p2p identity rotate --plan --branch <hash>\``;
295
+ }
296
+ /**
297
+ * #75: the name and relays our final version takes when built from our own branch: those of the newest
298
+ * version on it this device published, with the relays this device is configured with, never the tip's
299
+ * (newer versions on a branch can come from whoever holds the identity key, and could name relays that
300
+ * never serve the final version to friends). `extra`: relays the tip lists beyond those.
301
+ */
302
+ function ownBranchFinalFields(app, chain, tip, log) {
303
+ const mine = chain
304
+ .ancestors(tip.hash)
305
+ .filter((v) => log.has(v.hash))
306
+ .pop();
307
+ const relays = [...new Set([...(mine?.relays ?? []), ...app.relays])];
308
+ return { name: mine?.name ?? app.self?.name ?? tip.name, relays, extra: tip.relays.filter((r) => !relays.includes(r)) };
309
+ }
310
+ /**
311
+ * #75, upgrades from 0.1.2: a failed edit there kept its merge (publishNext) without publishing it. A
312
+ * plain tip this device made that leaves it out hides our own branch, so a merge tip in our publish log
313
+ * that leaves this device out and that no relay serves is dropped from the store.
314
+ */
315
+ async function dropUnheldOwnMerges(app) {
316
+ const chain = await ownChain(app);
317
+ if (!chain)
318
+ return;
319
+ const log = new Set((await app.store.getPublishLog()).published);
320
+ const stale = chain.tips().filter((t) => t.merge !== undefined && t.rotation === undefined && log.has(t.hash) && !t.devices.includes(app.did));
321
+ if (stale.length === 0)
322
+ return;
323
+ const view = await app.ownView();
324
+ const answers = await Promise.all(view.relays.slice(0, 5).map((r) => fetchTips(app.transport(r), app.userId, app.tun.connectTimeoutMs, app.progress).catch(() => [])));
325
+ const held = new Set(answers.flatMap((tips) => tips.map((j) => jwsHash(j))));
326
+ await dropVersions(app, stale.filter((t) => !held.has(t.hash)).map((t) => t.hash));
327
+ }
328
+ /** Removes versions of our own identity from the store (never published, or no relay took them). */
329
+ async function dropVersions(app, hashes) {
330
+ if (hashes.length === 0)
331
+ return;
332
+ const drop = new Set(hashes);
333
+ await app.store.updateIdentity(app.userId, (cur) => (cur ? { next: { ...cur, versions: cur.versions.filter((v) => !drop.has(jwsHash(v))) }, result: undefined } : { result: undefined }));
334
+ }
186
335
  /** Rotations our identity's held tips carry that this device didn't publish (its publish log). */
187
336
  async function foreignRotations(app) {
188
337
  const chain = await ownChain(app);
@@ -250,14 +399,15 @@ export async function alertForeignRotations(app) {
250
399
  * friendship whose our-side signature comes from this device or a device
251
400
  * that stays in the plan counts (a thief's device can plant friendships with
252
401
  * accomplices); rotating normally it must also verify now, while a contest
253
- * also takes stored ones the other rotation left unverifiable. Anything else
402
+ * (or a rotation from this device's own branch of a fork, #75) also takes
403
+ * stored ones that don't verify now. Anything else
254
404
  * is shown in the plan, invited only when the user opts in.
255
405
  */
256
406
  export function friendVerdict(st, peer) {
257
407
  const entries = st.friendSigners?.[peer] ?? [];
258
408
  // A follower that aborted (another device answered its code) is no more trusted than a dropped one.
259
409
  const trusted = (did) => did === st.selfDid || (st.devices[did] !== undefined && st.devices[did].status !== "excluded" && st.devices[did].status !== "aborted");
260
- if (entries.some((e) => trusted(e.did) && (st.contest || e.live)))
410
+ if (entries.some((e) => trusted(e.did) && (st.contest || st.ownBranch || e.live)))
261
411
  return { invite: true };
262
412
  const dropped = entries.map((e) => st.devices[e.did]).find((d) => d?.status === "excluded");
263
413
  const why = entries.some((e) => trusted(e.did))
@@ -291,6 +441,8 @@ function planOf(st) {
291
441
  friendsOptIn: optIn,
292
442
  contest: !!st.contest,
293
443
  ...(st.backupFile ? { backup: { file: st.backupFile } } : {}),
444
+ ...(st.ownBranch ? { branch: st.ownBranch.tip } : {}),
445
+ ...(st.ownBranch?.others?.length ? { otherBranches: st.ownBranch.others } : {}),
294
446
  };
295
447
  }
296
448
  async function planWithAddress(app, st) {
@@ -362,6 +514,9 @@ async function loadOrRecover(app, prior, opts) {
362
514
  * fingerprint, the devices that would follow, and what moves.
363
515
  */
364
516
  export async function rotatePlan(app, opts = {}) {
517
+ return withRotationLock(app.home, () => rotatePlanLocked(app, opts));
518
+ }
519
+ async function rotatePlanLocked(app, opts) {
365
520
  const prior = await readRotationState(app.home);
366
521
  const recovered = await loadOrRecover(app, prior, opts);
367
522
  if (recovered)
@@ -369,6 +524,8 @@ export async function rotatePlan(app, opts = {}) {
369
524
  if (prior && prior.step !== "done" && prior.step !== "created") {
370
525
  throw new CliError("rotation_in_progress", `a rotation to ${prior.to} is under way: finish it with \`p2p identity rotate --resume\``);
371
526
  }
527
+ if (prior && prior.step === "created")
528
+ assertSameBranch(prior, opts);
372
529
  const st = prior && prior.step === "created" ? prior : await begin(app, opts);
373
530
  if (st === prior)
374
531
  applyExcludes(st, opts.exclude, opts.keep);
@@ -376,8 +533,26 @@ export async function rotatePlan(app, opts = {}) {
376
533
  await saveState(app.home, st);
377
534
  return planWithAddress(app, st);
378
535
  }
536
+ /**
537
+ * #91: a plan not yet accepted is reused by `--plan` and `--resume`, so a `--branch` naming another branch than the
538
+ * plan's own would be ignored: refused instead (drop the plan first).
539
+ */
540
+ function assertSameBranch(st, opts) {
541
+ if (opts.branch === undefined || opts.branch === st.ownBranch?.tip)
542
+ return;
543
+ if (st.step !== "created" || st.accepted) {
544
+ throw new CliError("usage", `--branch ${opts.branch}: the rotation under way here ${st.ownBranch ? `builds on the branch ${st.ownBranch.tip}` : "isn't built on a branch of a forked identity"}, and can't change now`);
545
+ }
546
+ const how = `drop it first (\`p2p identity rotate --cancel\`), then \`p2p identity rotate --plan --branch ${opts.branch}\``;
547
+ throw new CliError("usage", st.ownBranch
548
+ ? `--branch ${opts.branch}: the rotation plan here builds on the branch ${st.ownBranch.tip}. To choose another, ${how}`
549
+ : `--branch ${opts.branch}: the rotation plan here isn't built on a branch of a forked identity. To choose one, ${how}`);
550
+ }
379
551
  /** `p2p identity rotate --cancel`: drops a rotation whose plan wasn't accepted (nothing was published). */
380
552
  export async function rotateCancel(app) {
553
+ return withRotationLock(app.home, () => rotateCancelLocked(app));
554
+ }
555
+ async function rotateCancelLocked(app) {
381
556
  const st = await readRotationState(app.home);
382
557
  if (!st || st.step === "done")
383
558
  return { cancelled: false };
@@ -388,7 +563,15 @@ export async function rotateCancel(app) {
388
563
  app.warn(`the backup phrase of the key that wasn't used is still in ${st.backupFile}: delete it`);
389
564
  return { cancelled: true, to: st.to };
390
565
  }
566
+ export { rotationLockOf };
567
+ /**
568
+ * One `p2p identity rotate` run per home at a time (#91 review): `--plan`, `--cancel` and `--resend` too (#99), so a
569
+ * `--plan --exclude X` racing a `--resume --yes` run can't lose the exclusion. See withRotationLock.
570
+ */
391
571
  export async function rotate(app, opts = {}) {
572
+ return withRotationLock(app.home, () => rotateLocked(app, opts));
573
+ }
574
+ async function rotateLocked(app, opts) {
392
575
  const prior = await readRotationState(app.home);
393
576
  const recovered = await loadOrRecover(app, prior, opts);
394
577
  if (recovered)
@@ -400,6 +583,11 @@ export async function rotate(app, opts = {}) {
400
583
  if (!prior || prior.step === "done")
401
584
  throw new CliError("no_rotation", "there is no rotation in progress here to resume");
402
585
  st = prior;
586
+ assertSameBranch(st, opts);
587
+ // #91: `--resume --contest`: a rotation of this identity this device didn't publish came out while this one was
588
+ // under way (publishFinal points here): this one goes on as a competing one, so friends see a conflict.
589
+ if (opts.contest && !st.contest)
590
+ await contestOnResume(app, st, opts);
403
591
  }
404
592
  else {
405
593
  if (prior && prior.step !== "done")
@@ -506,11 +694,23 @@ async function begin(app, opts) {
506
694
  await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
507
695
  }
508
696
  else {
509
- await app.connectAndDrain();
697
+ await app.connectAndDrain().catch(async (e) => {
698
+ // #75: a key holder's version that connects to our history but leaves this device out makes the
699
+ // relays refuse it. Rotation is the remedy, built on this device's own branch (ownBranchTip).
700
+ if (!(e instanceof CliError) || e.code !== "device_revoked")
701
+ throw e;
702
+ await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
703
+ await dropUnheldOwnMerges(app);
704
+ if (!(await ownBranchFork(app))) {
705
+ throw new CliError("device_revoked", "the relays refuse this device, and no branch of your identity that leaves another device of yours out lists it as a key holder: it can't rotate (it may have been revoked)");
706
+ }
707
+ app.io.err(`p2p: ${e.message}`);
708
+ });
510
709
  // Build on the relays' head: a stale view could miss a competing rotation or a new device. #67: a listed
511
710
  // relay serving versions that don't connect (a thief's, signed with the old identity key) is left out
512
711
  // when the others confirm the head (App.ownStrictFallback): rotation is the remedy for exactly that.
513
712
  await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true, setAside: { unconnected: true } });
713
+ await dropUnheldOwnMerges(app);
514
714
  }
515
715
  const view = await app.ownView();
516
716
  const foreign = await foreignRotations(app);
@@ -525,15 +725,27 @@ async function begin(app, opts) {
525
725
  if (foreign.length === 0 && !alerted)
526
726
  throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
527
727
  }
528
- else if (!view.keyholders.includes(app.did)) {
728
+ // #75: forked by a version that leaves this device out, the plan lists from this device's own branch.
729
+ const picked = view.rotations.length > 0 ? undefined : await ownBranchTip(app, opts.branch);
730
+ const own = picked?.tip;
731
+ if (!opts.contest && !(own ?? view).keyholders.includes(app.did)) {
529
732
  throw new CliError("device_revoked", "this device is no longer a listed key holder of your identity");
530
733
  }
734
+ let ownBranch;
735
+ if (picked && own) {
736
+ const f = ownBranchFinalFields(app, (await ownChain(app)), own, new Set((await app.store.getPublishLog()).published));
737
+ ownBranch = { tip: own.hash, name: f.name, relays: f.relays, ...(picked.others.length > 0 ? { others: picked.others } : {}) };
738
+ if (picked.others.length > 0)
739
+ app.warn(otherBranchesWarning(own.hash, picked.others));
740
+ if (f.extra.length > 0)
741
+ app.warn(`your own branch lists relays no version this device published added (${f.extra.join(", ")}): your old identity's final version leaves them out`);
742
+ }
531
743
  // What the plan lists from: the head, or (contesting) the version the other rotation replaced.
532
- const base = view.rotations.length > 0 ? await preRotationHead(app) : view.head;
744
+ const base = view.rotations.length > 0 ? await preRotationHead(app) : (own ?? view.head);
533
745
  if (!base)
534
746
  throw new CliError("refresh_failed", "couldn't find your identity's last version before the rotation");
535
- const baseDevices = view.rotations.length > 0 ? base.devices : view.devices;
536
- const baseKeyholders = view.rotations.length > 0 ? base.keyholders : view.keyholders;
747
+ const baseDevices = view.rotations.length > 0 || own ? base.devices : view.devices;
748
+ const baseKeyholders = view.rotations.length > 0 || own ? base.keyholders : view.keyholders;
537
749
  const exclude = [...new Set(opts.exclude ?? [])];
538
750
  for (const d of exclude)
539
751
  if (!baseDevices.includes(d) || d === app.did)
@@ -591,8 +803,9 @@ async function begin(app, opts) {
591
803
  const self = { name: base.name, relays: [...base.relays], createdAt: Date.now() };
592
804
  // The new identity's home gets its own person token (projects.ts renewPersonToken), before its keys;
593
805
  // front ends read it again.
594
- renewPersonToken(home);
595
- await napp.state.put("keys", newKeysDoc(newIk.userId, device, cert, newIk));
806
+ const nkeys = newKeysDoc(newIk.userId, device, cert, newIk);
807
+ renewPersonToken(home, nkeys.spk);
808
+ await napp.state.put("keys", nkeys);
596
809
  await napp.state.put("self", self);
597
810
  await napp.load(true);
598
811
  await addIdentityVersion(napp.store, doc);
@@ -608,6 +821,7 @@ async function begin(app, opts) {
608
821
  step: "created",
609
822
  accepted: false,
610
823
  ...(opts.contest ? { contest: true } : {}),
824
+ ...(ownBranch ? { ownBranch } : {}),
611
825
  keepKeyholders: !!opts.keepKeyholders,
612
826
  devices: Object.fromEntries(others.map((d) => {
613
827
  const t = trust.get(d);
@@ -757,7 +971,12 @@ async function revokeExcluded(app, st) {
757
971
  return;
758
972
  const view = await app.ownView();
759
973
  const listed = excluded.filter((d) => view.devices.includes(d));
760
- if (listed.length > 0 && view.rotations.length === 0) {
974
+ if (listed.length > 0 && view.rotations.length === 0 && st.ownBranch) {
975
+ // #75: an edit would merge in the branch that leaves this device out, and can't be published. The
976
+ // devices only our branch lists are refused by the relays already; the final version revokes the rest.
977
+ app.warn(`couldn't revoke ${listed.join(", ")} on your old identity before the rotation (it is forked by a version that leaves this device out); the old identity's final version revokes every device`);
978
+ }
979
+ else if (listed.length > 0 && view.rotations.length === 0) {
761
980
  try {
762
981
  await app.publishNext((p) => {
763
982
  p.devices = p.devices.filter((d) => !listed.includes(d));
@@ -973,6 +1192,8 @@ async function social(app, napp, st, newIk) {
973
1192
  * out, this one is its sibling: a fork that carries two rotations, which
974
1193
  * friends see as a conflict. Contesting, a relay that already refuses this
975
1194
  * device is tolerated (the friends' conflict comes from the invites anyway).
1195
+ * When a version that connects to our history leaves this device out (#75),
1196
+ * it is built from this device's own branch (finalOnOwnBranch).
976
1197
  */
977
1198
  async function publishFinal(app, st) {
978
1199
  const ik = app.requireKeyholder("Publishing your old identity's final version");
@@ -985,6 +1206,23 @@ async function publishFinal(app, st) {
985
1206
  throw new CliError("no_identity", "this device holds no identity document for its user");
986
1207
  const tips = chain.tips();
987
1208
  const mine = chain.allTips().find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
1209
+ // #75: a fork made by a version that leaves this device out can't go through publishNext (its merge
1210
+ // would leave this device unlisted, so it couldn't publish): see ownBranchTip and finalOnOwnBranch.
1211
+ if (st.ownBranch && !contesting) {
1212
+ try {
1213
+ return await publishOwnBranchFinal(app, ik, st, st.ownBranch, mine);
1214
+ }
1215
+ catch (e) {
1216
+ // #91: a rotation someone else published meanwhile (the refresh just brought it in) makes the relays refuse
1217
+ // ours however often it is rebuilt: say so, and point to the contest, never to another --resume.
1218
+ if (!(e instanceof CliError))
1219
+ throw e;
1220
+ const foreign = await foreignRotations(app);
1221
+ if (foreign.length === 0)
1222
+ throw e;
1223
+ throw await rotatedMeanwhile(app, foreign, e);
1224
+ }
1225
+ }
988
1226
  if (mine) {
989
1227
  // Published by an interrupted run: make sure the relays have it.
990
1228
  const r = await app.publishDoc(mine.jws, mine.relays);
@@ -1004,7 +1242,8 @@ async function publishFinal(app, st) {
1004
1242
  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 });
1005
1243
  await addIdentityVersion(app.store, doc);
1006
1244
  await app.store.recordPublished({ hash: jwsHash(doc) });
1007
- const r = await app.publishDoc(doc, [...new Set([...base.relays, ...app.relays])]);
1245
+ const targets = [...new Set([...base.relays, ...app.relays])];
1246
+ const r = await app.publishDoc(doc, targets);
1008
1247
  if (r.ok.length === 0) {
1009
1248
  if (!contesting)
1010
1249
  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\``);
@@ -1012,6 +1251,149 @@ async function publishFinal(app, st) {
1012
1251
  }
1013
1252
  return { ver: base.ver + 1, ...r };
1014
1253
  }
1254
+ /**
1255
+ * #91: `--resume --contest`. A plan not yet accepted was made without the contest's drops (begin: the device that
1256
+ * signed the contested rotation, and every other key holder): refused, the user drops it and makes a contest's plan.
1257
+ * Past acceptance, those devices are dropped if no link code went out yet (unless kept, `--keep`); after that,
1258
+ * the ones that follow (or were sent a code) are named, so the user can revoke them on the new identity.
1259
+ */
1260
+ async function contestOnResume(app, st, opts) {
1261
+ const foreign = await foreignRotations(app);
1262
+ if (foreign.length === 0)
1263
+ throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
1264
+ if (st.step === "created" && !st.accepted) {
1265
+ throw new CliError("usage", "this rotation plan was made before the rotation you want to contest, without dropping the devices that could have published it: drop it (`p2p identity rotate --cancel`), then contest with `p2p identity rotate --contest`");
1266
+ }
1267
+ const chain = await ownChain(app);
1268
+ const signers = new Set(foreign.map((f) => chain?.get(f.hash)?.by).filter((d) => d !== undefined && d !== app.did));
1269
+ const whyOf = (did, d) => signers.has(did) ? "signed the rotation you are contesting" : d.keyholder ? "holds your identity key, so it could have published the rotation you are contesting" : undefined;
1270
+ const suspects = Object.entries(st.devices).filter(([did, d]) => d.status !== "excluded" && d.status !== "aborted" && whyOf(did, d) !== undefined);
1271
+ const named = [];
1272
+ for (const [did, d] of suspects) {
1273
+ if (!after(st, "devices") && d.status === "pending" && !(opts.keep ?? []).includes(did)) {
1274
+ d.status = "excluded";
1275
+ d.why = whyOf(did, d);
1276
+ }
1277
+ else {
1278
+ named.push(`${did}${d.label ? ` (${sanitizePeerText(d.label, 64)})` : ""}${d.newDid ? `, now ${d.newDid}` : ""}: ${whyOf(did, d)}`);
1279
+ }
1280
+ }
1281
+ st.contest = true;
1282
+ await saveState(app.home, st);
1283
+ if (named.length > 0) {
1284
+ app.warn(`these devices of yours follow this rotation (or were sent its link code) and could have published the rotation you are contesting: ${named.join("; ")}. If one is lost or stolen, revoke it on your new identity (\`p2p devices revoke <did>\`)`);
1285
+ }
1286
+ }
1287
+ /** #91: the error when a rotation this device didn't publish is out and the relays refuse our own final version. */
1288
+ async function rotatedMeanwhile(app, foreign, cause) {
1289
+ const to = [...new Set(foreign.map((f) => f.rotation.to))];
1290
+ const chain = await ownChain(app);
1291
+ const by = [...new Set(foreign.map((f) => chain?.get(f.hash)?.by).filter((d) => d !== undefined && isDid(d)))];
1292
+ return new CliError("identity_rotated", `no relay took your old identity's final version (${cause.message}): this identity was already rotated to ${to.join(" and ")}${by.length > 0 ? ` (signed by your device ${by.join(" and ")})` : ""}, and this device didn't publish that. If you didn't start it, someone holds your identity key: contest it with \`p2p identity rotate --resume --contest\` (your friends then see a conflict and apply neither)`, { to, by });
1293
+ }
1294
+ /**
1295
+ * #75: publishes the final version built from our own branch (finalOnOwnBranch), or the one an
1296
+ * interrupted run built (`pinned`). A final version no relay took because the tips moved since (the
1297
+ * other branch grew, so it's no longer on top of every tip) is never taken: it is discarded, with the
1298
+ * merges built for it, and built again on the tips the relays hold now.
1299
+ */
1300
+ async function publishOwnBranchFinal(app, ik, st, own, pinned) {
1301
+ const targets = [...new Set([...own.relays, ...app.relays])];
1302
+ let final = pinned ?? (await finalOnOwnBranch(app, ik, st, own));
1303
+ let r = await publishFinalDoc(app, ik, final.jws, targets);
1304
+ if (r.ok.length === 0 && r.failed.some((f) => f.code === "forbidden" || f.code === "identity-gap")) {
1305
+ await discardOwnFinal(app, final);
1306
+ await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
1307
+ final = await finalOnOwnBranch(app, ik, st, own);
1308
+ r = await publishFinalDoc(app, ik, final.jws, targets);
1309
+ }
1310
+ if (r.ok.length === 0)
1311
+ 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\``);
1312
+ return { ver: final.ver, ...r };
1313
+ }
1314
+ /** Drops a final version no relay took, and the merges finalOnOwnBranch built under it (the relays serve any they took again). */
1315
+ async function discardOwnFinal(app, final) {
1316
+ const chain = await ownChain(app);
1317
+ const log = new Set((await app.store.getPublishLog()).published);
1318
+ const drop = [final.hash];
1319
+ const stack = [final.prev, final.merge];
1320
+ while (stack.length > 0) {
1321
+ const h = stack.pop();
1322
+ const v = h ? chain?.get(h) : undefined;
1323
+ if (!v || v.merge === undefined || v.devices.length > 0 || v.keyholders.length > 0 || v.by !== app.did || !log.has(v.hash) || drop.includes(v.hash))
1324
+ continue;
1325
+ drop.push(v.hash);
1326
+ stack.push(v.prev, v.merge);
1327
+ }
1328
+ await dropVersions(app, drop);
1329
+ }
1330
+ /**
1331
+ * #75: the final version when someone holding the identity key forked our identity with a version that
1332
+ * leaves this device out (ownBranchTip). The relays then refuse this device; a restricted connection
1333
+ * (§2.7) takes only a version on top of every held tip, never a fork; and a rotation version can't be a
1334
+ * merge (P3). So the tips are merged first, listing nobody (a merge may drop any device, §2.5), and the
1335
+ * final version follows that merge. Name and relays are those begin took from our own branch
1336
+ * (ownBranchFinalFields): nothing of the other branch carries over.
1337
+ */
1338
+ async function finalOnOwnBranch(app, ik, st, own) {
1339
+ const plainTips = async () => ((await ownChain(app))?.tips() ?? []).filter((t) => t.rotation === undefined);
1340
+ let tips = await plainTips();
1341
+ for (let i = 0; tips.length > 1; i++) {
1342
+ if (i >= 64)
1343
+ throw new CliError("internal", "couldn't merge the branches of your identity document");
1344
+ const { prev, other } = mergePrevTip(tips[0], tips[1]);
1345
+ const m = createIdentityDoc(ik, { ver: Math.max(prev.ver, other.ver) + 1, prev: prev.hash, merge: other.hash, name: own.name, relays: [...own.relays], devices: [], keyholders: [], by: app.did });
1346
+ if ((await addIdentityVersion(app.store, m)).status === "gap")
1347
+ throw new CliError("internal", "the merge does not chain onto the held tips");
1348
+ await app.store.recordPublished({ hash: jwsHash(m) });
1349
+ tips = await plainTips();
1350
+ }
1351
+ const base = tips[0];
1352
+ if (!base)
1353
+ throw new CliError("refresh_failed", "couldn't find your identity's last version before the rotation");
1354
+ const doc = createIdentityDoc(ik, { ver: base.ver + 1, prev: base.hash, name: own.name, relays: [...own.relays], devices: [], keyholders: [], by: app.did, rotation: st.statement });
1355
+ const added = await addIdentityVersion(app.store, doc);
1356
+ if (added.status === "gap")
1357
+ throw new CliError("internal", "the final version does not chain onto the held tips");
1358
+ await app.store.recordPublished({ hash: jwsHash(doc) });
1359
+ return added.doc;
1360
+ }
1361
+ /**
1362
+ * Publishes our identity's final version (the versions it needs back-filled). #75: a relay that refuses
1363
+ * this device (left out of a forked identity's allowlist) gets it over a restricted connection (§2.7)
1364
+ * with a throwaway device of the old identity: certified for an hour, listed nowhere, and only able to
1365
+ * publish on top of every held tip.
1366
+ */
1367
+ async function publishFinalDoc(app, ik, doc, relays) {
1368
+ const r = await app.publishDoc(doc, relays);
1369
+ const refused = r.failed.filter((f) => f.code === "auth_failed");
1370
+ if (refused.length === 0)
1371
+ return r;
1372
+ const prev = (await ownChain(app))?.get(jwsHash(doc))?.prev;
1373
+ const history = prev ? await app.ownHistory(prev) : [];
1374
+ const keys = generateDeviceKeysV3(ik.userId);
1375
+ const cert = createDeviceCert(ik, { signingPublicKey: keys.signingPublicKey, agreementPublicKey: keys.agreementPublicKey, label: "rotation" }, { ttlSec: 3600 });
1376
+ const ok = [...r.ok];
1377
+ const failed = r.failed.filter((f) => f.code !== "auth_failed");
1378
+ for (const { relay } of refused) {
1379
+ const conn = new RelayConnection(relay, app.transport(relay), { auth: { cert, signingSecretKey: keys.signingSecretKey }, allowRestricted: true, timeoutMs: app.tun.connectTimeoutMs });
1380
+ try {
1381
+ await conn.open();
1382
+ const code = await publishOver(conn, doc, history);
1383
+ if (code === "ok")
1384
+ ok.push(relay);
1385
+ else
1386
+ failed.push({ relay, code });
1387
+ }
1388
+ catch (e) {
1389
+ failed.push({ relay, code: e.code ?? "network" });
1390
+ }
1391
+ finally {
1392
+ conn.close();
1393
+ }
1394
+ }
1395
+ return { ok, failed };
1396
+ }
1015
1397
  /** Copies a circle's chain and statements from `src`'s store into `dst`'s (verified on the way in). */
1016
1398
  async function syncCircle(dst, src, cid) {
1017
1399
  const exp = await exportCircle(src, cid);
@@ -1169,6 +1551,9 @@ export const RESEND_PER_HOUR = 50;
1169
1551
  * of what a relay advertises, in a rolling hour).
1170
1552
  */
1171
1553
  export async function rotateResend(app) {
1554
+ return withRotationLock(app.home, () => rotateResendLocked(app));
1555
+ }
1556
+ async function rotateResendLocked(app) {
1172
1557
  await app.load(true);
1173
1558
  const st = await readRotationState(app.home);
1174
1559
  if (!st || st.step !== "done" || app.userId !== st.to)
@@ -1967,6 +2352,7 @@ export async function followHeld(app, idOrItem) {
1967
2352
  await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: r.to, tag }), { mode: 0o600 });
1968
2353
  await adoptHome(app, tmp, tag);
1969
2354
  await reload(app);
2355
+ assertAdopted(app, res.userId);
1970
2356
  app.io.err(`this device moved with your identity: it is now ${res.address} (${res.did})`);
1971
2357
  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 })]);
1972
2358
  return { ...res, from: old };
@@ -2001,6 +2387,11 @@ export async function recoverInterruptedFollow(home) {
2001
2387
  catch {
2002
2388
  return false;
2003
2389
  }
2390
+ // Only the folders a follow made here: a link (to another home's state) is never moved into this one.
2391
+ for (const p of [rotationDir(home), tmp, join(tmp, "linked.json"), join(tmp, "cli"), join(tmp, "v3"), join(tmp, "cursors")]) {
2392
+ if (await isLink(p))
2393
+ return false;
2394
+ }
2004
2395
  if (!(await exists(join(tmp, "cli"))) && (await exists(join(home, "cli")))) {
2005
2396
  // The new identity is already in place (the swap finished but the marker stayed).
2006
2397
  await rm(tmp, { recursive: true, force: true });
@@ -2056,6 +2447,7 @@ export async function relinkRotated(app, code, opts = {}) {
2056
2447
  await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: res.userId, tag }), { mode: 0o600 });
2057
2448
  await adoptHome(app, tmp, tag);
2058
2449
  await reload(app);
2450
+ assertAdopted(app, res.userId);
2059
2451
  return { ...res, from: old };
2060
2452
  },
2061
2453
  };