@peer2peer/cli 0.1.1 → 0.1.3

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.
@@ -31,6 +31,17 @@ export interface RotationState {
31
31
  accepted?: boolean;
32
32
  /** Contesting a rotation this device didn't publish (§2.8: a conflict, so neither applies). */
33
33
  contest?: boolean;
34
+ /**
35
+ * #75: begun on this device's own branch of a fork that a version leaving this device out made
36
+ * (ownBranchTip): that tip, and the name and relays the final version takes (ownBranchFinalFields).
37
+ * The view's allowlist then leaves this device out, so, as contesting, its stored friendships count
38
+ * without verifying now.
39
+ */
40
+ ownBranch?: {
41
+ tip: string;
42
+ name: string;
43
+ relays: string[];
44
+ };
34
45
  keepKeyholders: boolean;
35
46
  devices: Record<string, RotationDeviceRec>;
36
47
  /** Excluded devices revoked on the old identity before any link code went out. */
@@ -69,6 +80,11 @@ export interface RotationState {
69
80
  archive?: string;
70
81
  }
71
82
  export declare function readRotationState(home: string): Promise<RotationState | undefined>;
83
+ /**
84
+ * After a swap: the home must now hold the identity the link joined. Anything else (files changed
85
+ * under the swap) keeps no person token and stops the command.
86
+ */
87
+ export declare function assertAdopted(app: App, userId: string): void;
72
88
  /**
73
89
  * Makes `src` (a home holding the new identity) this home's identity, after
74
90
  * the old identity's work here has stopped (moveHomes).
@@ -104,6 +120,8 @@ export interface RotateOptions {
104
120
  backupFileDefault?: boolean;
105
121
  /** A key holder contests a rotation it didn't publish: a competing one, so neither applies. */
106
122
  contest?: boolean;
123
+ /** #75: which branch is this device's own, when ownBranchTip can't tell (its jwsHash). */
124
+ branch?: string;
107
125
  /** Tests: stop after this step, as an interruption would. */
108
126
  stopAfter?: RotationStep;
109
127
  }
@@ -200,7 +218,8 @@ export interface RotateResult {
200
218
  * friendship whose our-side signature comes from this device or a device
201
219
  * that stays in the plan counts (a thief's device can plant friendships with
202
220
  * accomplices); rotating normally it must also verify now, while a contest
203
- * also takes stored ones the other rotation left unverifiable. Anything else
221
+ * (or a rotation from this device's own branch of a fork, #75) also takes
222
+ * stored ones that don't verify now. Anything else
204
223
  * is shown in the plan, invited only when the user opts in.
205
224
  */
206
225
  export declare function friendVerdict(st: RotationState, peer: string): {
package/dist/rotation.js CHANGED
@@ -53,17 +53,18 @@
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, blockUser, createCap, jwsHash, LINK_TTL_SEC, linkId, liveFriendshipsV3, loadCircle, mergePrevTip, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
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 { fetchTips, linkGet, linkPut, publishOver, relayCode, RelayConnection, sleep } from "./relay-client.js";
63
63
  import { deliverCircle, memberCaps, ownerPublish, signOwnJoin } from "./circle-ops.js";
64
64
  import { accept, dropHeld, getHeld, hold, mintInvite, withHeldId } from "./social.js";
65
65
  import { exportAll, exportCircle, mergeRemovals, sendSync } from "./sync.js";
66
66
  import { linkJoin } from "./identity.js";
67
+ import { renewPersonToken } from "./projects.js";
67
68
  import { makeEvent, receiving } from "./inbound.js";
68
69
  const STEPS = ["created", "published", "devices", "social", "final", "done"];
69
70
  const rotationDir = (home) => join(home, "rotation");
@@ -84,6 +85,15 @@ async function dropState(home) {
84
85
  await rm(newHomeOf(home), { recursive: true, force: true });
85
86
  }
86
87
  const after = (s, step) => STEPS.indexOf(s.step) >= STEPS.indexOf(step);
88
+ /** Whether `p` is a symbolic link (a missing path isn't). */
89
+ async function isLink(p) {
90
+ try {
91
+ return (await lstat(p)).isSymbolicLink();
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ }
87
97
  async function exists(p) {
88
98
  try {
89
99
  await stat(p);
@@ -106,6 +116,11 @@ async function appAt(app, home) {
106
116
  * `<home>/rotated/<tag>/`, `src`'s take their place.
107
117
  */
108
118
  async function moveHomes(home, src, tag) {
119
+ // Only folders a follow or rotation made: a link (to another home's state) is never moved into this one.
120
+ for (const p of [src, join(src, "cli"), join(src, "v3"), join(src, "cursors")]) {
121
+ if (await isLink(p))
122
+ throw new CliError("refused", `${p} is a symbolic link: nothing was moved into ${home}`);
123
+ }
109
124
  const archive = join(home, "rotated", tag);
110
125
  await mkdir(archive, { recursive: true, mode: 0o700 });
111
126
  const srcHasState = await exists(join(src, "cli"));
@@ -123,11 +138,23 @@ async function moveHomes(home, src, tag) {
123
138
  await rm(join(archive, d, ".lock"), { force: true });
124
139
  return archive;
125
140
  }
141
+ /**
142
+ * After a swap: the home must now hold the identity the link joined. Anything else (files changed
143
+ * under the swap) keeps no person token and stops the command.
144
+ */
145
+ export function assertAdopted(app, userId) {
146
+ if (app.userId === userId)
147
+ return;
148
+ app.front = false;
149
+ throw new CliError("wrong_identity", `after the move this home holds ${app.userId}, not ${userId}: it stopped here`);
150
+ }
126
151
  /**
127
152
  * Makes `src` (a home holding the new identity) this home's identity, after
128
153
  * the old identity's work here has stopped (moveHomes).
129
154
  */
130
155
  export async function adoptHome(app, src, tag) {
156
+ // The identity swapped in is this command's own (the person's token was for the one it replaces).
157
+ app.identityMadeHere = true;
131
158
  // Nothing of the old identity may still be writing: an envelope handled mid-swap would take its
132
159
  // lock into the archive (or write the old identity's state into the new home).
133
160
  await app.close();
@@ -157,10 +184,10 @@ function certLabel(cert) {
157
184
  return "";
158
185
  }
159
186
  }
160
- /** Our own identity's chain, verified (or undefined). */
187
+ /** Our own identity's chain, verified (or undefined); pending heads never narrow our own view (#65 review M1). */
161
188
  async function ownChain(app) {
162
189
  const stored = await app.store.getIdentity(app.userId);
163
- return stored && stored.versions.length > 0 ? IdentityChain.fromStored(stored) : undefined;
190
+ return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [] }) : undefined;
164
191
  }
165
192
  /**
166
193
  * The newest version of our identity that is not a rotation's final one:
@@ -182,6 +209,100 @@ async function preRotationHead(app) {
182
209
  }
183
210
  return undefined;
184
211
  }
212
+ /**
213
+ * #75: our identity forked by a version that connects to our history but leaves this device out. A
214
+ * merge keeps only the intersection, so it would leave this device unlisted (it couldn't publish), and
215
+ * the relays already refuse it. Returns the plain tips (no rotation) and the candidates for this
216
+ * device's own branch: those that list it as a key holder. Undefined when our identity isn't forked
217
+ * that way: one plain tip, a fork that lists this device on every branch (publishNext merges it), or
218
+ * one that lists it on none (this device can't publish, and can't take this path either).
219
+ */
220
+ async function ownBranchFork(app) {
221
+ const chain = await ownChain(app);
222
+ if (!chain)
223
+ return undefined;
224
+ const plain = chain.tips().filter((t) => t.rotation === undefined);
225
+ const candidates = plain.filter((t) => t.devices.includes(app.did) && t.keyholders.includes(app.did));
226
+ if (plain.length < 2 || candidates.length === 0 || candidates.length === plain.length)
227
+ return undefined;
228
+ return { chain, plain, candidates };
229
+ }
230
+ /**
231
+ * #75: which candidate (ownBranchFork) is this device's own branch, by provenance, never by `ver` or
232
+ * hash (whoever holds the identity key can pick those). A candidate is plausible when every version on
233
+ * it since the fork point (the versions not behind every plain tip) is in this device's publish log or
234
+ * was published `by` this device or a device that a version in its publish log lists. One candidate, or
235
+ * exactly one plausible: that one. Otherwise the user chooses (`choice`, `--branch <hash>`), shown each
236
+ * branch's publishers and relays. Undefined when our identity isn't forked that way.
237
+ */
238
+ async function ownBranchTip(app, choice) {
239
+ const fork = await ownBranchFork(app);
240
+ if (!fork) {
241
+ if (choice !== undefined)
242
+ throw new CliError("usage", "--branch: your identity isn't forked by a version that leaves this device out");
243
+ return undefined;
244
+ }
245
+ const { chain, plain, candidates } = fork;
246
+ if (choice !== undefined) {
247
+ const chosen = candidates.find((t) => t.hash === choice);
248
+ if (!chosen)
249
+ throw new CliError("usage", `--branch ${choice}: not a branch of your identity that lists this device (${candidates.map((t) => t.hash).join(", ")})`);
250
+ return chosen;
251
+ }
252
+ if (candidates.length === 1)
253
+ return candidates[0];
254
+ const log = new Set((await app.store.getPublishLog()).published);
255
+ const trusted = new Set([app.did, ...[...log].flatMap((h) => chain.get(h)?.devices ?? [])]);
256
+ const behind = plain.map((t) => new Set(chain.ancestors(t.hash).map((v) => v.hash)));
257
+ const common = new Set([...behind[0]].filter((h) => behind.every((set) => set.has(h))));
258
+ const since = (t) => chain.ancestors(t.hash).filter((v) => !common.has(v.hash));
259
+ const plausible = candidates.filter((t) => since(t).every((v) => log.has(v.hash) || trusted.has(v.by)));
260
+ if (plausible.length === 1)
261
+ return plausible[0];
262
+ const branches = candidates.map((t) => ({ hash: t.hash, ver: t.ver, by: [...new Set(since(t).map((v) => v.by))], relays: [...t.relays] }));
263
+ throw new CliError("branch_ambiguous", `your identity is forked by a version that leaves this device out, and more than one branch still lists it: ${branches
264
+ .map((x) => `${x.hash} (ver ${x.ver}, published by ${x.by.join(", ")}; relays ${x.relays.join(", ")})`)
265
+ .join("; ")}. Someone else holds your identity key. Check which branch is yours, then run \`p2p identity rotate --plan --branch <hash>\``, { branches });
266
+ }
267
+ /**
268
+ * #75: the name and relays our final version takes when built from our own branch: those of the newest
269
+ * version on it this device published, with the relays this device is configured with, never the tip's
270
+ * (newer versions on a branch can come from whoever holds the identity key, and could name relays that
271
+ * never serve the final version to friends). `extra`: relays the tip lists beyond those.
272
+ */
273
+ function ownBranchFinalFields(app, chain, tip, log) {
274
+ const mine = chain
275
+ .ancestors(tip.hash)
276
+ .filter((v) => log.has(v.hash))
277
+ .pop();
278
+ const relays = [...new Set([...(mine?.relays ?? []), ...app.relays])];
279
+ return { name: mine?.name ?? app.self?.name ?? tip.name, relays, extra: tip.relays.filter((r) => !relays.includes(r)) };
280
+ }
281
+ /**
282
+ * #75, upgrades from 0.1.2: a failed edit there kept its merge (publishNext) without publishing it. A
283
+ * plain tip this device made that leaves it out hides our own branch, so a merge tip in our publish log
284
+ * that leaves this device out and that no relay serves is dropped from the store.
285
+ */
286
+ async function dropUnheldOwnMerges(app) {
287
+ const chain = await ownChain(app);
288
+ if (!chain)
289
+ return;
290
+ const log = new Set((await app.store.getPublishLog()).published);
291
+ const stale = chain.tips().filter((t) => t.merge !== undefined && t.rotation === undefined && log.has(t.hash) && !t.devices.includes(app.did));
292
+ if (stale.length === 0)
293
+ return;
294
+ const view = await app.ownView();
295
+ const answers = await Promise.all(view.relays.slice(0, 5).map((r) => fetchTips(app.transport(r), app.userId, app.tun.connectTimeoutMs, app.progress).catch(() => [])));
296
+ const held = new Set(answers.flatMap((tips) => tips.map((j) => jwsHash(j))));
297
+ await dropVersions(app, stale.filter((t) => !held.has(t.hash)).map((t) => t.hash));
298
+ }
299
+ /** Removes versions of our own identity from the store (never published, or no relay took them). */
300
+ async function dropVersions(app, hashes) {
301
+ if (hashes.length === 0)
302
+ return;
303
+ const drop = new Set(hashes);
304
+ await app.store.updateIdentity(app.userId, (cur) => (cur ? { next: { ...cur, versions: cur.versions.filter((v) => !drop.has(jwsHash(v))) }, result: undefined } : { result: undefined }));
305
+ }
185
306
  /** Rotations our identity's held tips carry that this device didn't publish (its publish log). */
186
307
  async function foreignRotations(app) {
187
308
  const chain = await ownChain(app);
@@ -189,7 +310,8 @@ async function foreignRotations(app) {
189
310
  return [];
190
311
  const log = await app.store.getPublishLog();
191
312
  const out = [];
192
- for (const t of chain.tips()) {
313
+ // Every held tip, a stray's too (#74): a rotation on any held branch is the owner's to know about.
314
+ for (const t of chain.allTips()) {
193
315
  if (t.rotation === undefined || log.published.includes(t.hash))
194
316
  continue;
195
317
  try {
@@ -248,14 +370,15 @@ export async function alertForeignRotations(app) {
248
370
  * friendship whose our-side signature comes from this device or a device
249
371
  * that stays in the plan counts (a thief's device can plant friendships with
250
372
  * accomplices); rotating normally it must also verify now, while a contest
251
- * also takes stored ones the other rotation left unverifiable. Anything else
373
+ * (or a rotation from this device's own branch of a fork, #75) also takes
374
+ * stored ones that don't verify now. Anything else
252
375
  * is shown in the plan, invited only when the user opts in.
253
376
  */
254
377
  export function friendVerdict(st, peer) {
255
378
  const entries = st.friendSigners?.[peer] ?? [];
256
379
  // A follower that aborted (another device answered its code) is no more trusted than a dropped one.
257
380
  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)))
381
+ if (entries.some((e) => trusted(e.did) && (st.contest || st.ownBranch || e.live)))
259
382
  return { invite: true };
260
383
  const dropped = entries.map((e) => st.devices[e.did]).find((d) => d?.status === "excluded");
261
384
  const why = entries.some((e) => trusted(e.did))
@@ -504,9 +627,23 @@ async function begin(app, opts) {
504
627
  await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
505
628
  }
506
629
  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 });
630
+ await app.connectAndDrain().catch(async (e) => {
631
+ // #75: a key holder's version that connects to our history but leaves this device out makes the
632
+ // relays refuse it. Rotation is the remedy, built on this device's own branch (ownBranchTip).
633
+ if (!(e instanceof CliError) || e.code !== "device_revoked")
634
+ throw e;
635
+ await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
636
+ await dropUnheldOwnMerges(app);
637
+ if (!(await ownBranchFork(app))) {
638
+ 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)");
639
+ }
640
+ app.io.err(`p2p: ${e.message}`);
641
+ });
642
+ // Build on the relays' head: a stale view could miss a competing rotation or a new device. #67: a listed
643
+ // relay serving versions that don't connect (a thief's, signed with the old identity key) is left out
644
+ // when the others confirm the head (App.ownStrictFallback): rotation is the remedy for exactly that.
645
+ await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true, setAside: { unconnected: true } });
646
+ await dropUnheldOwnMerges(app);
510
647
  }
511
648
  const view = await app.ownView();
512
649
  const foreign = await foreignRotations(app);
@@ -521,15 +658,24 @@ async function begin(app, opts) {
521
658
  if (foreign.length === 0 && !alerted)
522
659
  throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
523
660
  }
524
- else if (!view.keyholders.includes(app.did)) {
661
+ // #75: forked by a version that leaves this device out, the plan lists from this device's own branch.
662
+ const own = view.rotations.length > 0 ? undefined : await ownBranchTip(app, opts.branch);
663
+ if (!opts.contest && !(own ?? view).keyholders.includes(app.did)) {
525
664
  throw new CliError("device_revoked", "this device is no longer a listed key holder of your identity");
526
665
  }
666
+ let ownBranch;
667
+ if (own) {
668
+ const f = ownBranchFinalFields(app, (await ownChain(app)), own, new Set((await app.store.getPublishLog()).published));
669
+ ownBranch = { tip: own.hash, name: f.name, relays: f.relays };
670
+ if (f.extra.length > 0)
671
+ app.warn(`your own branch lists relays no version this device published added (${f.extra.join(", ")}): your old identity's final version leaves them out`);
672
+ }
527
673
  // 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;
674
+ const base = view.rotations.length > 0 ? await preRotationHead(app) : (own ?? view.head);
529
675
  if (!base)
530
676
  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;
677
+ const baseDevices = view.rotations.length > 0 || own ? base.devices : view.devices;
678
+ const baseKeyholders = view.rotations.length > 0 || own ? base.keyholders : view.keyholders;
533
679
  const exclude = [...new Set(opts.exclude ?? [])];
534
680
  for (const d of exclude)
535
681
  if (!baseDevices.includes(d) || d === app.did)
@@ -585,7 +731,11 @@ async function begin(app, opts) {
585
731
  await rm(home, { recursive: true, force: true });
586
732
  const napp = await appAt(app, home);
587
733
  const self = { name: base.name, relays: [...base.relays], createdAt: Date.now() };
588
- await napp.state.put("keys", newKeysDoc(newIk.userId, device, cert, newIk));
734
+ // The new identity's home gets its own person token (projects.ts renewPersonToken), before its keys;
735
+ // front ends read it again.
736
+ const nkeys = newKeysDoc(newIk.userId, device, cert, newIk);
737
+ renewPersonToken(home, nkeys.spk);
738
+ await napp.state.put("keys", nkeys);
589
739
  await napp.state.put("self", self);
590
740
  await napp.load(true);
591
741
  await addIdentityVersion(napp.store, doc);
@@ -601,6 +751,7 @@ async function begin(app, opts) {
601
751
  step: "created",
602
752
  accepted: false,
603
753
  ...(opts.contest ? { contest: true } : {}),
754
+ ...(ownBranch ? { ownBranch } : {}),
604
755
  keepKeyholders: !!opts.keepKeyholders,
605
756
  devices: Object.fromEntries(others.map((d) => {
606
757
  const t = trust.get(d);
@@ -750,7 +901,12 @@ async function revokeExcluded(app, st) {
750
901
  return;
751
902
  const view = await app.ownView();
752
903
  const listed = excluded.filter((d) => view.devices.includes(d));
753
- if (listed.length > 0 && view.rotations.length === 0) {
904
+ if (listed.length > 0 && view.rotations.length === 0 && st.ownBranch) {
905
+ // #75: an edit would merge in the branch that leaves this device out, and can't be published. The
906
+ // devices only our branch lists are refused by the relays already; the final version revokes the rest.
907
+ 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`);
908
+ }
909
+ else if (listed.length > 0 && view.rotations.length === 0) {
754
910
  try {
755
911
  await app.publishNext((p) => {
756
912
  p.devices = p.devices.filter((d) => !listed.includes(d));
@@ -966,17 +1122,24 @@ async function social(app, napp, st, newIk) {
966
1122
  * out, this one is its sibling: a fork that carries two rotations, which
967
1123
  * friends see as a conflict. Contesting, a relay that already refuses this
968
1124
  * device is tolerated (the friends' conflict comes from the invites anyway).
1125
+ * When a version that connects to our history leaves this device out (#75),
1126
+ * it is built from this device's own branch (finalOnOwnBranch).
969
1127
  */
970
1128
  async function publishFinal(app, st) {
971
1129
  const ik = app.requireKeyholder("Publishing your old identity's final version");
972
1130
  const contesting = st.contest || (await foreignRotations(app)).length > 0;
973
1131
  await app.connect({ allowNone: true });
974
- await app.refreshIdentity(app.userId, app.relays, contesting ? { force: true, quiet: true } : { force: true, strict: true });
1132
+ // #67: as in begin, a relay serving versions that don't connect is left out when the others confirm the head.
1133
+ await app.refreshIdentity(app.userId, app.relays, contesting ? { force: true, quiet: true } : { force: true, strict: true, setAside: { unconnected: true } });
975
1134
  const chain = await ownChain(app);
976
1135
  if (!chain)
977
1136
  throw new CliError("no_identity", "this device holds no identity document for its user");
978
1137
  const tips = chain.tips();
979
- const mine = tips.find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
1138
+ const mine = chain.allTips().find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
1139
+ // #75: a fork made by a version that leaves this device out can't go through publishNext (its merge
1140
+ // would leave this device unlisted, so it couldn't publish): see ownBranchTip and finalOnOwnBranch.
1141
+ if (st.ownBranch && !contesting)
1142
+ return publishOwnBranchFinal(app, ik, st, st.ownBranch, mine);
980
1143
  if (mine) {
981
1144
  // Published by an interrupted run: make sure the relays have it.
982
1145
  const r = await app.publishDoc(mine.jws, mine.relays);
@@ -996,7 +1159,8 @@ async function publishFinal(app, st) {
996
1159
  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
1160
  await addIdentityVersion(app.store, doc);
998
1161
  await app.store.recordPublished({ hash: jwsHash(doc) });
999
- const r = await app.publishDoc(doc, [...new Set([...base.relays, ...app.relays])]);
1162
+ const targets = [...new Set([...base.relays, ...app.relays])];
1163
+ const r = await app.publishDoc(doc, targets);
1000
1164
  if (r.ok.length === 0) {
1001
1165
  if (!contesting)
1002
1166
  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\``);
@@ -1004,6 +1168,109 @@ async function publishFinal(app, st) {
1004
1168
  }
1005
1169
  return { ver: base.ver + 1, ...r };
1006
1170
  }
1171
+ /**
1172
+ * #75: publishes the final version built from our own branch (finalOnOwnBranch), or the one an
1173
+ * interrupted run built (`pinned`). A final version no relay took because the tips moved since (the
1174
+ * other branch grew, so it's no longer on top of every tip) is never taken: it is discarded, with the
1175
+ * merges built for it, and built again on the tips the relays hold now.
1176
+ */
1177
+ async function publishOwnBranchFinal(app, ik, st, own, pinned) {
1178
+ const targets = [...new Set([...own.relays, ...app.relays])];
1179
+ let final = pinned ?? (await finalOnOwnBranch(app, ik, st, own));
1180
+ let r = await publishFinalDoc(app, ik, final.jws, targets);
1181
+ if (r.ok.length === 0 && r.failed.some((f) => f.code === "forbidden" || f.code === "identity-gap")) {
1182
+ await discardOwnFinal(app, final);
1183
+ await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
1184
+ final = await finalOnOwnBranch(app, ik, st, own);
1185
+ r = await publishFinalDoc(app, ik, final.jws, targets);
1186
+ }
1187
+ if (r.ok.length === 0)
1188
+ 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\``);
1189
+ return { ver: final.ver, ...r };
1190
+ }
1191
+ /** Drops a final version no relay took, and the merges finalOnOwnBranch built under it (the relays serve any they took again). */
1192
+ async function discardOwnFinal(app, final) {
1193
+ const chain = await ownChain(app);
1194
+ const log = new Set((await app.store.getPublishLog()).published);
1195
+ const drop = [final.hash];
1196
+ const stack = [final.prev, final.merge];
1197
+ while (stack.length > 0) {
1198
+ const h = stack.pop();
1199
+ const v = h ? chain?.get(h) : undefined;
1200
+ 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))
1201
+ continue;
1202
+ drop.push(v.hash);
1203
+ stack.push(v.prev, v.merge);
1204
+ }
1205
+ await dropVersions(app, drop);
1206
+ }
1207
+ /**
1208
+ * #75: the final version when someone holding the identity key forked our identity with a version that
1209
+ * leaves this device out (ownBranchTip). The relays then refuse this device; a restricted connection
1210
+ * (§2.7) takes only a version on top of every held tip, never a fork; and a rotation version can't be a
1211
+ * merge (P3). So the tips are merged first, listing nobody (a merge may drop any device, §2.5), and the
1212
+ * final version follows that merge. Name and relays are those begin took from our own branch
1213
+ * (ownBranchFinalFields): nothing of the other branch carries over.
1214
+ */
1215
+ async function finalOnOwnBranch(app, ik, st, own) {
1216
+ const plainTips = async () => ((await ownChain(app))?.tips() ?? []).filter((t) => t.rotation === undefined);
1217
+ let tips = await plainTips();
1218
+ for (let i = 0; tips.length > 1; i++) {
1219
+ if (i >= 64)
1220
+ throw new CliError("internal", "couldn't merge the branches of your identity document");
1221
+ const { prev, other } = mergePrevTip(tips[0], tips[1]);
1222
+ 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 });
1223
+ if ((await addIdentityVersion(app.store, m)).status === "gap")
1224
+ throw new CliError("internal", "the merge does not chain onto the held tips");
1225
+ await app.store.recordPublished({ hash: jwsHash(m) });
1226
+ tips = await plainTips();
1227
+ }
1228
+ const base = tips[0];
1229
+ if (!base)
1230
+ throw new CliError("refresh_failed", "couldn't find your identity's last version before the rotation");
1231
+ 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 });
1232
+ const added = await addIdentityVersion(app.store, doc);
1233
+ if (added.status === "gap")
1234
+ throw new CliError("internal", "the final version does not chain onto the held tips");
1235
+ await app.store.recordPublished({ hash: jwsHash(doc) });
1236
+ return added.doc;
1237
+ }
1238
+ /**
1239
+ * Publishes our identity's final version (the versions it needs back-filled). #75: a relay that refuses
1240
+ * this device (left out of a forked identity's allowlist) gets it over a restricted connection (§2.7)
1241
+ * with a throwaway device of the old identity: certified for an hour, listed nowhere, and only able to
1242
+ * publish on top of every held tip.
1243
+ */
1244
+ async function publishFinalDoc(app, ik, doc, relays) {
1245
+ const r = await app.publishDoc(doc, relays);
1246
+ const refused = r.failed.filter((f) => f.code === "auth_failed");
1247
+ if (refused.length === 0)
1248
+ return r;
1249
+ const prev = (await ownChain(app))?.get(jwsHash(doc))?.prev;
1250
+ const history = prev ? await app.ownHistory(prev) : [];
1251
+ const keys = generateDeviceKeysV3(ik.userId);
1252
+ const cert = createDeviceCert(ik, { signingPublicKey: keys.signingPublicKey, agreementPublicKey: keys.agreementPublicKey, label: "rotation" }, { ttlSec: 3600 });
1253
+ const ok = [...r.ok];
1254
+ const failed = r.failed.filter((f) => f.code !== "auth_failed");
1255
+ for (const { relay } of refused) {
1256
+ const conn = new RelayConnection(relay, app.transport(relay), { auth: { cert, signingSecretKey: keys.signingSecretKey }, allowRestricted: true, timeoutMs: app.tun.connectTimeoutMs });
1257
+ try {
1258
+ await conn.open();
1259
+ const code = await publishOver(conn, doc, history);
1260
+ if (code === "ok")
1261
+ ok.push(relay);
1262
+ else
1263
+ failed.push({ relay, code });
1264
+ }
1265
+ catch (e) {
1266
+ failed.push({ relay, code: e.code ?? "network" });
1267
+ }
1268
+ finally {
1269
+ conn.close();
1270
+ }
1271
+ }
1272
+ return { ok, failed };
1273
+ }
1007
1274
  /** Copies a circle's chain and statements from `src`'s store into `dst`'s (verified on the way in). */
1008
1275
  async function syncCircle(dst, src, cid) {
1009
1276
  const exp = await exportCircle(src, cid);
@@ -1959,6 +2226,7 @@ export async function followHeld(app, idOrItem) {
1959
2226
  await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: r.to, tag }), { mode: 0o600 });
1960
2227
  await adoptHome(app, tmp, tag);
1961
2228
  await reload(app);
2229
+ assertAdopted(app, res.userId);
1962
2230
  app.io.err(`this device moved with your identity: it is now ${res.address} (${res.did})`);
1963
2231
  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
2232
  return { ...res, from: old };
@@ -1993,6 +2261,11 @@ export async function recoverInterruptedFollow(home) {
1993
2261
  catch {
1994
2262
  return false;
1995
2263
  }
2264
+ // Only the folders a follow made here: a link (to another home's state) is never moved into this one.
2265
+ for (const p of [rotationDir(home), tmp, join(tmp, "linked.json"), join(tmp, "cli"), join(tmp, "v3"), join(tmp, "cursors")]) {
2266
+ if (await isLink(p))
2267
+ return false;
2268
+ }
1996
2269
  if (!(await exists(join(tmp, "cli"))) && (await exists(join(home, "cli")))) {
1997
2270
  // The new identity is already in place (the swap finished but the marker stayed).
1998
2271
  await rm(tmp, { recursive: true, force: true });
@@ -2048,6 +2321,7 @@ export async function relinkRotated(app, code, opts = {}) {
2048
2321
  await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: res.userId, tag }), { mode: 0o600 });
2049
2322
  await adoptHome(app, tmp, tag);
2050
2323
  await reload(app);
2324
+ assertAdopted(app, res.userId);
2051
2325
  return { ...res, from: old };
2052
2326
  },
2053
2327
  };
@@ -241,6 +241,14 @@ export interface SendOpts {
241
241
  * session is theirs, never bound to a project. Set only by those two paths, never from a flag.
242
242
  */
243
243
  person?: boolean;
244
+ /**
245
+ * Set by sendMessage to whether a copy of this message may have reached a relay: true from the
246
+ * moment one is about to go out, and after delivery whether one did or was written to a relay
247
+ * whose answer never came. sendSharing undoes its share only while it is false.
248
+ */
249
+ wire?: {
250
+ maybe: boolean;
251
+ };
244
252
  }
245
253
  export interface SendResult {
246
254
  delivered: boolean;