@peer2peer/cli 0.1.2 → 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.
- package/README.md +8 -6
- package/dist/ancestry.d.ts +42 -2
- package/dist/ancestry.js +215 -32
- package/dist/app.d.ts +44 -2
- package/dist/app.js +116 -15
- package/dist/cli.d.ts +30 -3
- package/dist/cli.js +133 -8
- package/dist/doctor.js +29 -1
- package/dist/format.d.ts +2 -0
- package/dist/format.js +5 -1
- package/dist/identity.d.ts +6 -2
- package/dist/identity.js +34 -19
- package/dist/pretty.js +2 -1
- package/dist/projects.d.ts +58 -12
- package/dist/projects.js +220 -48
- package/dist/rotation.d.ts +20 -1
- package/dist/rotation.js +280 -14
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/watch.js +43 -13
- package/package.json +3 -3
package/dist/rotation.js
CHANGED
|
@@ -53,13 +53,13 @@
|
|
|
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";
|
|
@@ -85,6 +85,15 @@ async function dropState(home) {
|
|
|
85
85
|
await rm(newHomeOf(home), { recursive: true, force: true });
|
|
86
86
|
}
|
|
87
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
|
+
}
|
|
88
97
|
async function exists(p) {
|
|
89
98
|
try {
|
|
90
99
|
await stat(p);
|
|
@@ -107,6 +116,11 @@ async function appAt(app, home) {
|
|
|
107
116
|
* `<home>/rotated/<tag>/`, `src`'s take their place.
|
|
108
117
|
*/
|
|
109
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
|
+
}
|
|
110
124
|
const archive = join(home, "rotated", tag);
|
|
111
125
|
await mkdir(archive, { recursive: true, mode: 0o700 });
|
|
112
126
|
const srcHasState = await exists(join(src, "cli"));
|
|
@@ -124,11 +138,23 @@ async function moveHomes(home, src, tag) {
|
|
|
124
138
|
await rm(join(archive, d, ".lock"), { force: true });
|
|
125
139
|
return archive;
|
|
126
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
|
+
}
|
|
127
151
|
/**
|
|
128
152
|
* Makes `src` (a home holding the new identity) this home's identity, after
|
|
129
153
|
* the old identity's work here has stopped (moveHomes).
|
|
130
154
|
*/
|
|
131
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;
|
|
132
158
|
// Nothing of the old identity may still be writing: an envelope handled mid-swap would take its
|
|
133
159
|
// lock into the archive (or write the old identity's state into the new home).
|
|
134
160
|
await app.close();
|
|
@@ -183,6 +209,100 @@ async function preRotationHead(app) {
|
|
|
183
209
|
}
|
|
184
210
|
return undefined;
|
|
185
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
|
+
}
|
|
186
306
|
/** Rotations our identity's held tips carry that this device didn't publish (its publish log). */
|
|
187
307
|
async function foreignRotations(app) {
|
|
188
308
|
const chain = await ownChain(app);
|
|
@@ -250,14 +370,15 @@ export async function alertForeignRotations(app) {
|
|
|
250
370
|
* friendship whose our-side signature comes from this device or a device
|
|
251
371
|
* that stays in the plan counts (a thief's device can plant friendships with
|
|
252
372
|
* accomplices); rotating normally it must also verify now, while a contest
|
|
253
|
-
*
|
|
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
|
|
254
375
|
* is shown in the plan, invited only when the user opts in.
|
|
255
376
|
*/
|
|
256
377
|
export function friendVerdict(st, peer) {
|
|
257
378
|
const entries = st.friendSigners?.[peer] ?? [];
|
|
258
379
|
// A follower that aborted (another device answered its code) is no more trusted than a dropped one.
|
|
259
380
|
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)))
|
|
381
|
+
if (entries.some((e) => trusted(e.did) && (st.contest || st.ownBranch || e.live)))
|
|
261
382
|
return { invite: true };
|
|
262
383
|
const dropped = entries.map((e) => st.devices[e.did]).find((d) => d?.status === "excluded");
|
|
263
384
|
const why = entries.some((e) => trusted(e.did))
|
|
@@ -506,11 +627,23 @@ async function begin(app, opts) {
|
|
|
506
627
|
await app.refreshIdentity(app.userId, app.relays, { force: true, quiet: true });
|
|
507
628
|
}
|
|
508
629
|
else {
|
|
509
|
-
await app.connectAndDrain()
|
|
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
|
+
});
|
|
510
642
|
// Build on the relays' head: a stale view could miss a competing rotation or a new device. #67: a listed
|
|
511
643
|
// relay serving versions that don't connect (a thief's, signed with the old identity key) is left out
|
|
512
644
|
// when the others confirm the head (App.ownStrictFallback): rotation is the remedy for exactly that.
|
|
513
645
|
await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true, setAside: { unconnected: true } });
|
|
646
|
+
await dropUnheldOwnMerges(app);
|
|
514
647
|
}
|
|
515
648
|
const view = await app.ownView();
|
|
516
649
|
const foreign = await foreignRotations(app);
|
|
@@ -525,15 +658,24 @@ async function begin(app, opts) {
|
|
|
525
658
|
if (foreign.length === 0 && !alerted)
|
|
526
659
|
throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
|
|
527
660
|
}
|
|
528
|
-
|
|
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)) {
|
|
529
664
|
throw new CliError("device_revoked", "this device is no longer a listed key holder of your identity");
|
|
530
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
|
+
}
|
|
531
673
|
// 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;
|
|
674
|
+
const base = view.rotations.length > 0 ? await preRotationHead(app) : (own ?? view.head);
|
|
533
675
|
if (!base)
|
|
534
676
|
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;
|
|
677
|
+
const baseDevices = view.rotations.length > 0 || own ? base.devices : view.devices;
|
|
678
|
+
const baseKeyholders = view.rotations.length > 0 || own ? base.keyholders : view.keyholders;
|
|
537
679
|
const exclude = [...new Set(opts.exclude ?? [])];
|
|
538
680
|
for (const d of exclude)
|
|
539
681
|
if (!baseDevices.includes(d) || d === app.did)
|
|
@@ -591,8 +733,9 @@ async function begin(app, opts) {
|
|
|
591
733
|
const self = { name: base.name, relays: [...base.relays], createdAt: Date.now() };
|
|
592
734
|
// The new identity's home gets its own person token (projects.ts renewPersonToken), before its keys;
|
|
593
735
|
// front ends read it again.
|
|
594
|
-
|
|
595
|
-
|
|
736
|
+
const nkeys = newKeysDoc(newIk.userId, device, cert, newIk);
|
|
737
|
+
renewPersonToken(home, nkeys.spk);
|
|
738
|
+
await napp.state.put("keys", nkeys);
|
|
596
739
|
await napp.state.put("self", self);
|
|
597
740
|
await napp.load(true);
|
|
598
741
|
await addIdentityVersion(napp.store, doc);
|
|
@@ -608,6 +751,7 @@ async function begin(app, opts) {
|
|
|
608
751
|
step: "created",
|
|
609
752
|
accepted: false,
|
|
610
753
|
...(opts.contest ? { contest: true } : {}),
|
|
754
|
+
...(ownBranch ? { ownBranch } : {}),
|
|
611
755
|
keepKeyholders: !!opts.keepKeyholders,
|
|
612
756
|
devices: Object.fromEntries(others.map((d) => {
|
|
613
757
|
const t = trust.get(d);
|
|
@@ -757,7 +901,12 @@ async function revokeExcluded(app, st) {
|
|
|
757
901
|
return;
|
|
758
902
|
const view = await app.ownView();
|
|
759
903
|
const listed = excluded.filter((d) => view.devices.includes(d));
|
|
760
|
-
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) {
|
|
761
910
|
try {
|
|
762
911
|
await app.publishNext((p) => {
|
|
763
912
|
p.devices = p.devices.filter((d) => !listed.includes(d));
|
|
@@ -973,6 +1122,8 @@ async function social(app, napp, st, newIk) {
|
|
|
973
1122
|
* out, this one is its sibling: a fork that carries two rotations, which
|
|
974
1123
|
* friends see as a conflict. Contesting, a relay that already refuses this
|
|
975
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).
|
|
976
1127
|
*/
|
|
977
1128
|
async function publishFinal(app, st) {
|
|
978
1129
|
const ik = app.requireKeyholder("Publishing your old identity's final version");
|
|
@@ -985,6 +1136,10 @@ async function publishFinal(app, st) {
|
|
|
985
1136
|
throw new CliError("no_identity", "this device holds no identity document for its user");
|
|
986
1137
|
const tips = chain.tips();
|
|
987
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);
|
|
988
1143
|
if (mine) {
|
|
989
1144
|
// Published by an interrupted run: make sure the relays have it.
|
|
990
1145
|
const r = await app.publishDoc(mine.jws, mine.relays);
|
|
@@ -1004,7 +1159,8 @@ async function publishFinal(app, st) {
|
|
|
1004
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 });
|
|
1005
1160
|
await addIdentityVersion(app.store, doc);
|
|
1006
1161
|
await app.store.recordPublished({ hash: jwsHash(doc) });
|
|
1007
|
-
const
|
|
1162
|
+
const targets = [...new Set([...base.relays, ...app.relays])];
|
|
1163
|
+
const r = await app.publishDoc(doc, targets);
|
|
1008
1164
|
if (r.ok.length === 0) {
|
|
1009
1165
|
if (!contesting)
|
|
1010
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\``);
|
|
@@ -1012,6 +1168,109 @@ async function publishFinal(app, st) {
|
|
|
1012
1168
|
}
|
|
1013
1169
|
return { ver: base.ver + 1, ...r };
|
|
1014
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
|
+
}
|
|
1015
1274
|
/** Copies a circle's chain and statements from `src`'s store into `dst`'s (verified on the way in). */
|
|
1016
1275
|
async function syncCircle(dst, src, cid) {
|
|
1017
1276
|
const exp = await exportCircle(src, cid);
|
|
@@ -1967,6 +2226,7 @@ export async function followHeld(app, idOrItem) {
|
|
|
1967
2226
|
await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: r.to, tag }), { mode: 0o600 });
|
|
1968
2227
|
await adoptHome(app, tmp, tag);
|
|
1969
2228
|
await reload(app);
|
|
2229
|
+
assertAdopted(app, res.userId);
|
|
1970
2230
|
app.io.err(`this device moved with your identity: it is now ${res.address} (${res.did})`);
|
|
1971
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 })]);
|
|
1972
2232
|
return { ...res, from: old };
|
|
@@ -2001,6 +2261,11 @@ export async function recoverInterruptedFollow(home) {
|
|
|
2001
2261
|
catch {
|
|
2002
2262
|
return false;
|
|
2003
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
|
+
}
|
|
2004
2269
|
if (!(await exists(join(tmp, "cli"))) && (await exists(join(home, "cli")))) {
|
|
2005
2270
|
// The new identity is already in place (the swap finished but the marker stayed).
|
|
2006
2271
|
await rm(tmp, { recursive: true, force: true });
|
|
@@ -2056,6 +2321,7 @@ export async function relinkRotated(app, code, opts = {}) {
|
|
|
2056
2321
|
await writeFile(join(tmp, "linked.json"), JSON.stringify({ to: res.userId, tag }), { mode: 0o600 });
|
|
2057
2322
|
await adoptHome(app, tmp, tag);
|
|
2058
2323
|
await reload(app);
|
|
2324
|
+
assertAdopted(app, res.userId);
|
|
2059
2325
|
return { ...res, from: old };
|
|
2060
2326
|
},
|
|
2061
2327
|
};
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.1.
|
|
1
|
+
export declare const VERSION = "0.1.3";
|
package/dist/version.js
CHANGED
package/dist/watch.js
CHANGED
|
@@ -22,7 +22,7 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
|
22
22
|
import { join } from "node:path";
|
|
23
23
|
import { certExpiresWithin, mayRepublish, nowSec } from "@peer2peer/core/v3";
|
|
24
24
|
import { CLOSE_GRACE_MS, REPUBLISH_DOC_WITHIN_SEC } from "./app.js";
|
|
25
|
-
import { receiving } from "./inbound.js";
|
|
25
|
+
import { makeEvent, receiving } from "./inbound.js";
|
|
26
26
|
import { answerDeferredWants, renewOpenJoinCaps } from "./circle-ops.js";
|
|
27
27
|
import { checkSid, expireSubs } from "./sessions.js";
|
|
28
28
|
import { CliError } from "./errors.js";
|
|
@@ -293,6 +293,43 @@ export async function refreshContacts(app) {
|
|
|
293
293
|
await retryRotationJoins(app).catch(() => []);
|
|
294
294
|
await app.adoptCertFromDoc();
|
|
295
295
|
}
|
|
296
|
+
/** Whether the head's document or one of its device certificates is due for renewal. */
|
|
297
|
+
function renewalDue(head, now) {
|
|
298
|
+
const certSoon = (head.certs ?? []).some((c) => {
|
|
299
|
+
try {
|
|
300
|
+
const exp = JSON.parse(Buffer.from(c.split(".")[1], "base64url").toString()).exp;
|
|
301
|
+
return certExpiresWithin({ exp }, 30 * 86_400, now);
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
return false;
|
|
305
|
+
}
|
|
306
|
+
});
|
|
307
|
+
return certSoon || head.exp - now <= REPUBLISH_DOC_WITHIN_SEC;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* #78 review: the strict refresh before a renewal was refused because a relay that doesn't answer sent a newer
|
|
311
|
+
* version of our identity earlier (App.ownPendingGuard). Never silent: a warning on every run, and once the
|
|
312
|
+
* renewal is due, a `p2p.alert` (`what: "renewal-held"`) for the mod's status line, raised again each day
|
|
313
|
+
* left, so it escalates as the document nears expiry instead of letting it lapse unnoticed.
|
|
314
|
+
*/
|
|
315
|
+
async function renewalHeld(app, e) {
|
|
316
|
+
const heldBy = e.extra.heldBy.filter((r) => typeof r === "string");
|
|
317
|
+
const v = await app.ownView();
|
|
318
|
+
const now = nowSec();
|
|
319
|
+
const daysLeft = Math.max(0, Math.floor((v.head.exp - now) / 86_400));
|
|
320
|
+
const fix = `try again when ${heldBy.length === 1 ? "it answers" : "they answer"}, or remove ${heldBy.length === 1 ? "it" : "them"} (\`p2p relays remove ${heldBy.join(" ")}\`) if gone for good or no device of yours published that version; \`p2p doctor\` shows the details`;
|
|
321
|
+
app.warn(`can't renew your identity document (expires in ${daysLeft} days): ${heldBy.join(", ")} didn't answer and earlier sent a newer version of it; ${fix}`);
|
|
322
|
+
if (!renewalDue(v.head, now))
|
|
323
|
+
return;
|
|
324
|
+
await app.state.addEvents([
|
|
325
|
+
makeEvent(`renewal-held|${v.head.hash}|${daysLeft}`, "p2p.alert", Date.now(), {
|
|
326
|
+
from: { userId: app.userId, did: app.did, address: await app.addressOf(app.userId), self: true },
|
|
327
|
+
what: "renewal-held",
|
|
328
|
+
daysLeft,
|
|
329
|
+
heldBy,
|
|
330
|
+
}),
|
|
331
|
+
]);
|
|
332
|
+
}
|
|
296
333
|
/** Key holders keep the document and certificates fresh (§2.3 renewal, §2.5 re-publish, single writer). */
|
|
297
334
|
export async function maintain(app) {
|
|
298
335
|
if (!app.isKeyholder) {
|
|
@@ -304,25 +341,18 @@ export async function maintain(app) {
|
|
|
304
341
|
await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true });
|
|
305
342
|
}
|
|
306
343
|
catch (e) {
|
|
307
|
-
if (e instanceof CliError)
|
|
344
|
+
if (e instanceof CliError) {
|
|
345
|
+
if (Array.isArray(e.extra.heldBy))
|
|
346
|
+
await renewalHeld(app, e).catch(() => undefined);
|
|
308
347
|
return;
|
|
348
|
+
}
|
|
309
349
|
throw e;
|
|
310
350
|
}
|
|
311
351
|
const v = await app.ownView();
|
|
312
352
|
if (!v.devices.includes(app.did) || !v.keyholders.includes(app.did))
|
|
313
353
|
return;
|
|
314
354
|
const now = nowSec();
|
|
315
|
-
|
|
316
|
-
try {
|
|
317
|
-
const exp = JSON.parse(Buffer.from(c.split(".")[1], "base64url").toString()).exp;
|
|
318
|
-
return certExpiresWithin({ exp }, 30 * 86_400, now);
|
|
319
|
-
}
|
|
320
|
-
catch {
|
|
321
|
-
return false;
|
|
322
|
-
}
|
|
323
|
-
});
|
|
324
|
-
const docSoon = v.head.exp - now <= REPUBLISH_DOC_WITHIN_SEC;
|
|
325
|
-
if ((docSoon || certSoon) && mayRepublish(app.did, v.head, now)) {
|
|
355
|
+
if (renewalDue(v.head, now) && mayRepublish(app.did, v.head, now)) {
|
|
326
356
|
await app.publishNext(() => { }).catch((e) => {
|
|
327
357
|
if (!(e instanceof CliError))
|
|
328
358
|
throw e;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@peer2peer/cli",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"description": "The standalone Peer2Peer v3 CLI (`p2p`): an account-free identity, friends, circles, end-to-end encrypted session messaging and status over open relays",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"peer2peer",
|
|
@@ -53,8 +53,8 @@
|
|
|
53
53
|
"registry": "https://registry.npmjs.org/"
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
|
-
"@peer2peer/codex-bridge": "0.1.
|
|
57
|
-
"@peer2peer/core": "0.1.
|
|
56
|
+
"@peer2peer/codex-bridge": "0.1.3",
|
|
57
|
+
"@peer2peer/core": "0.1.3",
|
|
58
58
|
"commander": "15.0.0",
|
|
59
59
|
"uqr": "0.1.3",
|
|
60
60
|
"ws": "8.22.0"
|