@peer2peer/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +366 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +363 -0
  6. package/dist/app.js +1177 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +611 -0
  12. package/dist/cli.js +1650 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +112 -0
  16. package/dist/config.js +243 -0
  17. package/dist/doctor.d.ts +99 -0
  18. package/dist/doctor.js +817 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +32 -0
  22. package/dist/ext-host.js +259 -0
  23. package/dist/extensions.d.ts +386 -0
  24. package/dist/extensions.js +395 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/identity.d.ts +236 -0
  30. package/dist/identity.js +751 -0
  31. package/dist/inbound.d.ts +32 -0
  32. package/dist/inbound.js +258 -0
  33. package/dist/index.d.ts +8 -0
  34. package/dist/index.js +14 -0
  35. package/dist/join-answers.d.ts +49 -0
  36. package/dist/join-answers.js +149 -0
  37. package/dist/outbox.d.ts +109 -0
  38. package/dist/outbox.js +337 -0
  39. package/dist/pretty.d.ts +100 -0
  40. package/dist/pretty.js +256 -0
  41. package/dist/procstart.d.ts +1 -0
  42. package/dist/procstart.js +66 -0
  43. package/dist/progress.d.ts +30 -0
  44. package/dist/progress.js +78 -0
  45. package/dist/projects.d.ts +240 -0
  46. package/dist/projects.js +699 -0
  47. package/dist/prompt/picker.d.ts +64 -0
  48. package/dist/prompt/picker.js +152 -0
  49. package/dist/prompt/tty.d.ts +29 -0
  50. package/dist/prompt/tty.js +122 -0
  51. package/dist/readonly.d.ts +20 -0
  52. package/dist/readonly.js +50 -0
  53. package/dist/receipts.d.ts +99 -0
  54. package/dist/receipts.js +180 -0
  55. package/dist/relay-client.d.ts +277 -0
  56. package/dist/relay-client.js +873 -0
  57. package/dist/relay-info.d.ts +24 -0
  58. package/dist/relay-info.js +53 -0
  59. package/dist/rotation.d.ts +402 -0
  60. package/dist/rotation.js +2054 -0
  61. package/dist/running.d.ts +5 -0
  62. package/dist/running.js +74 -0
  63. package/dist/sessions.d.ts +340 -0
  64. package/dist/sessions.js +1152 -0
  65. package/dist/shortcode.d.ts +149 -0
  66. package/dist/shortcode.js +465 -0
  67. package/dist/social.d.ts +139 -0
  68. package/dist/social.js +485 -0
  69. package/dist/state.d.ts +483 -0
  70. package/dist/state.js +217 -0
  71. package/dist/stdin.d.ts +17 -0
  72. package/dist/stdin.js +46 -0
  73. package/dist/sync.d.ts +77 -0
  74. package/dist/sync.js +375 -0
  75. package/dist/transient.d.ts +1 -0
  76. package/dist/transient.js +28 -0
  77. package/dist/trust.d.ts +37 -0
  78. package/dist/trust.js +134 -0
  79. package/dist/tty-confirm.d.ts +2 -0
  80. package/dist/tty-confirm.js +53 -0
  81. package/dist/tui/command.d.ts +20 -0
  82. package/dist/tui/command.js +70 -0
  83. package/dist/tui/frame.d.ts +43 -0
  84. package/dist/tui/frame.js +111 -0
  85. package/dist/tui/model.d.ts +215 -0
  86. package/dist/tui/model.js +255 -0
  87. package/dist/tui/sanitize.d.ts +13 -0
  88. package/dist/tui/sanitize.js +151 -0
  89. package/dist/tui/terminal.d.ts +88 -0
  90. package/dist/tui/terminal.js +354 -0
  91. package/dist/tui/tui.d.ts +71 -0
  92. package/dist/tui/tui.js +571 -0
  93. package/dist/tui/view.d.ts +4 -0
  94. package/dist/tui/view.js +356 -0
  95. package/dist/unknown-kinds.d.ts +12 -0
  96. package/dist/unknown-kinds.js +66 -0
  97. package/dist/version.d.ts +1 -0
  98. package/dist/version.js +5 -0
  99. package/dist/want-pow.d.ts +12 -0
  100. package/dist/want-pow.js +46 -0
  101. package/dist/watch.d.ts +35 -0
  102. package/dist/watch.js +325 -0
  103. package/dist/xstate.d.ts +125 -0
  104. package/dist/xstate.js +422 -0
  105. package/package.json +60 -4
@@ -0,0 +1,751 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // The identity commands (docs/protocol.md §2): init, whoami, devices and
4
+ // revocation, device linking, the backup phrase, profiles and proofs.
5
+ import { chmod, readFile, rm, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+ import { resolveTxt } from "node:dns/promises";
8
+ import { addIdentityVersion, b64uEncode, backupPhraseFromSeed, canonicalProofLoc, createCap, createDeviceCert, createIdentityDoc, createLinkRequest, createMembershipStatement, createProof, daysPastExp, decodeTyped, displayAddress, displayFingerprint, displayProfile, dnsProofRecord, encodeLinkCode, generateDeviceKeysV3, generateIdentityKey, identityFreshness, identityKeyFromBackupPhrase, isValidName, jumpIdentity, liveFriendshipsV3, jwsHash, LINK_TTL_SEC, linkCompareCode, linkId, loadCircle, MAX_DEVICES, MAX_RELAYS, newLinkSecret, nowSec, nextMembershipN, openLinkResponse, P2PError, parseLinkCode, PROFILE_AVATAR_DATA_MAX, sanitizePeerText, sealLinkResponse, selectLinkRequest, TYP3, verifiedProofs, verifyDeviceCertV3, verifyMembershipStatement, verifyProofSignature, } from "@peer2peer/core/v3";
9
+ import { capPeek, certDid, defaultLabel, defaultName, joinCapOf, newKeysDoc } from "./app.js";
10
+ import { defaultRelays, normalizeRelays } from "./config.js";
11
+ import { CliError } from "./errors.js";
12
+ import { fetchTips, linkGet, linkPut, openLinkConnection, relayCode, sleep } from "./relay-client.js";
13
+ import { exportAll, sendSync, verifiedIssuedCap } from "./sync.js";
14
+ import { receiving } from "./inbound.js";
15
+ import { recordJoin, resignJoin } from "./circle-ops.js";
16
+ export async function init(app, opts) {
17
+ if (await app.load(false))
18
+ throw new CliError("already_initialized", `${app.home} already holds an identity (${app.userId})`);
19
+ const relays = opts.relays && opts.relays.length > 0 ? normalizeRelays(opts.relays) : defaultRelays(app.env, app.file);
20
+ if (relays.length === 0) {
21
+ throw new CliError("no_relays", `no relays configured: pass --relay wss://… (1–5), or set P2P_DEFAULT_RELAYS, or "defaultRelays" in ${app.home}/config.json`);
22
+ }
23
+ const name = opts.name ?? defaultName();
24
+ if (!isValidName(name))
25
+ throw new CliError("usage", "--name must match [a-z0-9._-]{1,32}");
26
+ const ik = generateIdentityKey();
27
+ const device = generateDeviceKeysV3(ik.userId);
28
+ const cert = createDeviceCert(ik, { signingPublicKey: device.signingPublicKey, agreementPublicKey: device.agreementPublicKey, label: defaultLabel() });
29
+ const doc = createIdentityDoc(ik, { ver: 1, prev: null, name, relays, devices: [device.did], keyholders: [device.did], by: device.did, certs: [cert] });
30
+ const keys = newKeysDoc(ik.userId, device, cert, ik);
31
+ const self = { name, relays, createdAt: Date.now() };
32
+ await app.state.put("keys", keys);
33
+ await app.state.put("self", self);
34
+ app.setKeys(keys, self);
35
+ await addIdentityVersion(app.store, doc);
36
+ await app.store.putDeviceCert({ userId: ik.userId, did: device.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
37
+ await app.store.recordPublished({ hash: jwsHash(doc), devices: [device.did], relays });
38
+ // Not before the first document is on the relays (refreshDeviceInfo builds on the relays' head).
39
+ app.deviceInfoDeferred = true;
40
+ await app.connect({ allowNone: true });
41
+ const r = await app.publishDoc(doc, relays);
42
+ app.deviceInfoDeferred = false;
43
+ if (r.ok.length > 0)
44
+ await app.refreshDeviceInfo().catch(() => undefined);
45
+ return { userId: ik.userId, address: displayAddress(ik.userId, name), fingerprint: displayFingerprint(ik.userId), did: device.did, relays, published: r.ok, failed: r.failed };
46
+ }
47
+ export const BACKUP_FILE_NAME = "backup-phrase.txt";
48
+ export async function setup(app, opts) {
49
+ let created = false;
50
+ let pub;
51
+ if (!(await app.load(false))) {
52
+ const r = await init(app, { name: opts.name, relays: opts.relays });
53
+ created = true;
54
+ pub = { published: r.published, failed: r.failed };
55
+ }
56
+ const v = await app.ownView();
57
+ const out = {
58
+ userId: app.userId,
59
+ address: displayAddress(app.userId, v.head.name),
60
+ fingerprint: displayFingerprint(app.userId),
61
+ did: app.did,
62
+ relays: v.head.relays,
63
+ created,
64
+ ...(pub ?? {}),
65
+ };
66
+ if (opts.backup === "file") {
67
+ const path = opts.backupFile ?? join(app.home, BACKUP_FILE_NAME);
68
+ const { phrase } = await backupShow(app);
69
+ try {
70
+ // Never overwrite: an existing file may be the only copy of another phrase.
71
+ await writeFile(path, `${phrase}\n`, { mode: 0o600, flag: "wx" });
72
+ }
73
+ catch (e) {
74
+ if (e.code === "EEXIST")
75
+ throw new CliError("exists", `${path} already exists: not overwriting it (pass --backup-file <path>)`, { ...out });
76
+ throw e;
77
+ }
78
+ await chmod(path, 0o600);
79
+ out.backup = { file: path };
80
+ }
81
+ else if (opts.backup === "print") {
82
+ out.backup = { phrase: (await backupShow(app)).phrase };
83
+ }
84
+ return out;
85
+ }
86
+ // ---------------------------------------------------------------------------
87
+ // relays (the list in your identity document, §5.8)
88
+ export async function relaysList(app) {
89
+ return { relays: [...(await app.ownView()).head.relays] };
90
+ }
91
+ async function changeRelays(app, f) {
92
+ app.requireKeyholder("Changing your relays");
93
+ await app.connectAndDrain();
94
+ const pub = await app.publishNext((p) => {
95
+ p.relays = f(p.relays);
96
+ });
97
+ const re = await reissueForRelays(app);
98
+ return { relays: [...(await app.ownView()).head.relays], ver: pub.ver, published: pub.ok, failed: pub.failed, ...re };
99
+ }
100
+ /**
101
+ * review L5: caps name the relays they admit at. After the relay list changes,
102
+ * friends get a fresh friend cap on the new list and our circle joins are
103
+ * re-signed with a fresh co-member cap, so nobody is left holding caps only
104
+ * for relays we dropped. Old caps aren't revoked: a friend who hasn't picked
105
+ * up the new one still reaches the relays both name.
106
+ */
107
+ export async function reissueForRelays(app) {
108
+ const cur = new Set(app.relays);
109
+ const sameRelays = (rs) => rs.length === cur.size && rs.every((r) => cur.has(r));
110
+ const live = new Set((await liveFriendshipsV3(app.store, app.signerCtx())).map((x) => (x.inviter === app.userId ? x.invitee : x.inviter)));
111
+ const now = nowSec();
112
+ const stale = new Set();
113
+ const current = new Set();
114
+ for (const c of await app.store.listCapsIssued()) {
115
+ const facts = verifiedIssuedCap(app, c.jws);
116
+ if (!facts || facts.iss !== app.userId || facts.sub === "*" || facts.sub === app.userId || facts.kinds[0] !== "*" || facts.exp <= now)
117
+ continue;
118
+ if (!live.has(facts.sub))
119
+ continue;
120
+ (sameRelays(facts.relays) ? current : stale).add(facts.sub);
121
+ }
122
+ let capsReissued = 0;
123
+ const issued = [];
124
+ for (const sub of stale) {
125
+ if (current.has(sub))
126
+ continue;
127
+ const cap = createCap(app.device, app.keys.cert, { purpose: "friend", sub, relays: app.relays });
128
+ issued.push(await app.recordIssued(cap));
129
+ try {
130
+ const d = await app.deliver(sub, "contact", { own: app.userId, sid: "~contact" }, { text: cap });
131
+ if (d.relays.length > 0)
132
+ capsReissued++;
133
+ }
134
+ catch (e) {
135
+ app.warn(`couldn't send ${await app.addressOf(sub)} your new relays: ${e.message}`);
136
+ }
137
+ }
138
+ const rejoined = [];
139
+ for (const rec of await app.store.listCircles()) {
140
+ const mine = rec.statements[app.userId];
141
+ if (!rec.joinedByMe || mine?.op !== "join")
142
+ continue;
143
+ const cap = joinCapOf(mine.jws);
144
+ const p = cap ? capPeek(cap) : undefined;
145
+ if (p && sameRelays(p.relays))
146
+ continue;
147
+ if (await resignJoin(app, rec.cid))
148
+ rejoined.push(rec.cid);
149
+ }
150
+ if (issued.length > 0)
151
+ await sendSync(app, { capsIssued: issued });
152
+ return { capsReissued, rejoined };
153
+ }
154
+ /** Adds a relay to your identity document (the next version, published to old and new relays). */
155
+ export async function relaysAdd(app, url) {
156
+ const r = normalizeRelays([url])[0];
157
+ const cur = (await app.ownView()).head.relays;
158
+ if (cur.includes(r))
159
+ return { relays: [...cur], ver: (await app.ownView()).head.ver, published: [], failed: [], capsReissued: 0, rejoined: [] };
160
+ if (cur.length >= MAX_RELAYS)
161
+ throw new CliError("bad_relay", `at most ${MAX_RELAYS} relays: remove one first`);
162
+ return changeRelays(app, (list) => [...list.filter((x) => x !== r), r]);
163
+ }
164
+ /** Removes a relay (at least one must stay). The removed relay gets the new version too, so it stops admitting removed state. */
165
+ export async function relaysRemove(app, url) {
166
+ const r = normalizeRelays([url])[0];
167
+ const cur = (await app.ownView()).head.relays;
168
+ if (!cur.includes(r))
169
+ throw new CliError("not_found", `${r} is not one of your relays`);
170
+ if (cur.length === 1)
171
+ throw new CliError("usage", "that is your only relay: add another first");
172
+ // Caps naming the dropped relay, captured before the re-issue adds new ones.
173
+ const old = (await app.store.listCapsIssued()).filter((c) => c.iss === app.userId && c.relays.includes(r));
174
+ const out = await changeRelays(app, (list) => list.filter((x) => x !== r));
175
+ // review L2: revoke them at the dropped relay only (our devices are still in its allowlist). Other
176
+ // relays keep honouring them, so friends who haven't picked up the new caps stay covered.
177
+ // Best effort: the relay may be down.
178
+ let revokedAtRemoved = 0;
179
+ const pool = app.pool ?? (await app.connect({ allowNone: true }));
180
+ for (const c of old) {
181
+ if ((await pool.revoke(c.capid, [r]).catch(() => [])).length > 0)
182
+ revokedAtRemoved++;
183
+ }
184
+ if (revokedAtRemoved < old.length)
185
+ app.warn(`couldn't revoke ${old.length - revokedAtRemoved} of your old caps at ${r}; they expire on their own`);
186
+ return { ...out, revokedAtRemoved };
187
+ }
188
+ export async function devices(app) {
189
+ const v = await app.ownView();
190
+ const rows = [];
191
+ for (const d of v.devices) {
192
+ const c = v.head.certs?.find((x) => certDid(x) === d) ?? (d === app.did ? app.keys.cert : undefined);
193
+ let label = "";
194
+ let certExp;
195
+ if (c) {
196
+ const p = decodeTyped(c, TYP3.device).payload;
197
+ label = sanitizePeerText(p.label, 64);
198
+ certExp = typeof p.exp === "number" ? p.exp : undefined;
199
+ }
200
+ rows.push({ did: d, label, keyholder: v.keyholders.includes(d), thisDevice: d === app.did, ...(certExp ? { certExp } : {}) });
201
+ }
202
+ return rows;
203
+ }
204
+ export async function whoami(app) {
205
+ const v = await app.ownView();
206
+ const warnings = [];
207
+ const f = identityFreshness(v.head.exp);
208
+ if (f !== "fresh")
209
+ warnings.push(`your identity document expired ${daysPastExp(v.head.exp)} days ago: run any command on a key-holding device to re-publish`);
210
+ if (app.isKeyholder && v.keyholders.length < 2 && !app.self?.backupShown) {
211
+ warnings.push("only this device holds your identity key and you haven't saved a backup: run `p2p backup show`, or link a second key holder (`p2p link start --keyholder`)");
212
+ }
213
+ if (app.self?.unpublished?.length)
214
+ warnings.push(`your document isn't on ${app.self.unpublished.join(", ")} yet`);
215
+ return {
216
+ userId: app.userId,
217
+ name: v.head.name,
218
+ address: displayAddress(app.userId, v.head.name),
219
+ fingerprint: displayFingerprint(app.userId),
220
+ did: app.did,
221
+ keyholder: app.isKeyholder,
222
+ devices: await devices(app),
223
+ relays: v.head.relays,
224
+ doc: { ver: v.head.ver, exp: v.head.exp, freshness: f, daysPastExp: daysPastExp(v.head.exp), forked: v.forked, historyGap: v.historyGap },
225
+ profile: displayProfile(v.head.profile),
226
+ proofs: v.head.proofs?.length ?? 0,
227
+ ...(app.self?.defaultCircle ? { defaultCircle: app.self.defaultCircle } : {}),
228
+ warnings,
229
+ };
230
+ }
231
+ /**
232
+ * Revokes a device (§2.5): the next document version without it. Caps that
233
+ * device signed stop working at relays (§5.3 L1), so they are revoked and
234
+ * re-issued from this device, and membership statements it signed are
235
+ * re-signed (§3.3 N4).
236
+ */
237
+ export async function revokeDevice(app, did) {
238
+ app.requireKeyholder("Revoking a device");
239
+ if (did === app.did)
240
+ throw new CliError("usage", "a device can't revoke itself; revoke it from another key-holding device");
241
+ await app.connectAndDrain();
242
+ // Another key holder may have linked devices since: build on the relays' head (also review H2).
243
+ await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true });
244
+ const v = await app.ownView();
245
+ if (!v.devices.includes(did))
246
+ throw new CliError("not_found", `${did} is not one of your devices`);
247
+ const wasKeyholder = v.keyholders.includes(did);
248
+ const pub = await app.publishNext((p) => {
249
+ p.devices = p.devices.filter((d) => d !== did);
250
+ p.keyholders = p.keyholders.filter((d) => d !== did);
251
+ p.certs = (p.certs ?? []).filter((c) => certDid(c) !== did);
252
+ });
253
+ // Caps the revoked device signed.
254
+ const signedBy = (jws) => {
255
+ try {
256
+ const cert = decodeTyped(jws, TYP3.cap).payload.cert;
257
+ return typeof cert === "string" && certDid(cert) === did;
258
+ }
259
+ catch {
260
+ return false;
261
+ }
262
+ };
263
+ const old = await app.store.takeCapsIssued((c) => signedBy(c.jws));
264
+ await app.revokeCaps(old);
265
+ let reissued = 0;
266
+ // review M5: what a cap grants comes from its signed JWS, never the stored record's fields,
267
+ // and replacements go only to live friends.
268
+ const live = new Set((await liveFriendshipsV3(app.store, app.signerCtx())).map((f) => (f.inviter === app.userId ? f.invitee : f.inviter)));
269
+ const subs = new Set();
270
+ for (const c of old) {
271
+ const facts = verifiedIssuedCap(app, c.jws);
272
+ if (!facts || facts.iss !== app.userId || facts.sub === "*" || facts.sub === app.userId || facts.kinds[0] !== "*")
273
+ continue;
274
+ if (!live.has(facts.sub) || subs.has(facts.sub))
275
+ continue;
276
+ subs.add(facts.sub);
277
+ const cap = createCap(app.device, app.keys.cert, { purpose: "friend", sub: facts.sub, relays: app.relays });
278
+ await app.recordIssued(cap);
279
+ try {
280
+ const d = await app.deliver(facts.sub, "contact", { own: app.userId, sid: "~contact" }, { text: cap });
281
+ if (d.relays.length > 0)
282
+ reissued++;
283
+ }
284
+ catch {
285
+ // they'll need a fresh invite
286
+ }
287
+ }
288
+ // Membership statements the revoked device signed: re-sign with n+1 and a fresh cap.
289
+ const rejoined = [];
290
+ for (const rec of await app.store.listCircles()) {
291
+ const mine = rec.statements[app.userId];
292
+ if (!mine || mine.op !== "join")
293
+ continue;
294
+ const kid = JSON.parse(Buffer.from(mine.jws.split(".")[0], "base64url").toString()).kid;
295
+ if (kid !== did)
296
+ continue;
297
+ const c = await loadCircle(app.store, rec.cid);
298
+ if (!c)
299
+ continue;
300
+ const cap = createCap(app.device, app.keys.cert, { purpose: "join", relays: app.relays });
301
+ const jws = createMembershipStatement(app.signer(), { cid: rec.cid, n: nextMembershipN(rec.myN), op: "join", at: c.chain.head.hash, cap });
302
+ const s = await verifyMembershipStatement(jws, app.signerCtx());
303
+ await recordJoin(app, s);
304
+ await app.recordIssued(cap);
305
+ for (const m of c.chain.head.members) {
306
+ if (m === app.userId)
307
+ continue;
308
+ await app.deliver(m, "circle", { own: app.userId, sid: "~circle" }, { circles: [], joins: [jws], ops: [] }).catch(() => undefined);
309
+ }
310
+ rejoined.push(rec.cid);
311
+ }
312
+ const warnings = wasKeyholder ? [lostKeyholderWarning(1)] : [];
313
+ for (const w of warnings)
314
+ app.warn(w);
315
+ return { revoked: did, ver: pub.ver, capsReissued: reissued, rejoined, warnings };
316
+ }
317
+ export async function linkStart(app, opts = {}) {
318
+ const ik = app.requireKeyholder("Linking a device");
319
+ const v = await app.ownView();
320
+ if (v.devices.length >= MAX_DEVICES)
321
+ throw new CliError("too_many_devices", `an identity lists at most ${MAX_DEVICES} devices: revoke one first`);
322
+ const relay = opts.relay ? normalizeRelays([opts.relay])[0] : app.relays[0];
323
+ const s = newLinkSecret();
324
+ const lid = linkId(s);
325
+ const pool = await app.connect();
326
+ const conn = await pool.ensure(relay);
327
+ const opened = await conn.request({ t: "link-open", lid });
328
+ if (opened.t !== "ok")
329
+ throw new CliError("link_failed", `${relay} refused to open a link mailbox (${relayCode(opened.code ?? opened.t)})`);
330
+ const expiresAt = Date.now() + LINK_TTL_SEC * 1000;
331
+ let cancelled = false;
332
+ return {
333
+ code: encodeLinkCode(s, relay),
334
+ relay,
335
+ expiresAt,
336
+ cancel: () => {
337
+ cancelled = true;
338
+ },
339
+ wait: async (confirm) => {
340
+ let req;
341
+ for (;;) {
342
+ if (cancelled)
343
+ throw new CliError("cancelled", "link cancelled");
344
+ if (Date.now() >= expiresAt)
345
+ throw new CliError("link_expired", "the link code expired (10 minutes): start again");
346
+ const entries = await linkGet(conn, lid, "req");
347
+ if (entries === undefined)
348
+ throw new CliError("link_expired", "the link mailbox is gone: start again");
349
+ try {
350
+ req = selectLinkRequest(s, entries);
351
+ }
352
+ catch (e) {
353
+ if (e instanceof P2PError && e.reason === "link-multiple-requests") {
354
+ throw new CliError("link_aborted", "more than one device answered this code: someone else saw it. Link aborted; start again on a private screen");
355
+ }
356
+ throw e;
357
+ }
358
+ if (req)
359
+ break;
360
+ await sleep(app.tun.linkPollMs);
361
+ }
362
+ const ok = await confirm({ label: req.displayLabel, compareCode: req.compareCode, did: req.did });
363
+ if (!ok)
364
+ throw new CliError("link_declined", "the compare codes didn't match or you declined: nothing was linked");
365
+ const cert = createDeviceCert(ik, { signingPublicKey: req.signingPublicKey, agreementPublicKey: req.agreementPublicKey, ...(req.displayLabel ? { label: req.displayLabel } : {}) });
366
+ const pub = await app.publishNext((p) => {
367
+ p.devices = [...p.devices, req.did];
368
+ if (opts.keyholder)
369
+ p.keyholders = [...p.keyholders, req.did];
370
+ p.certs = [...(p.certs ?? []), cert];
371
+ });
372
+ await app.store.putDeviceCert({ userId: app.userId, did: req.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
373
+ const frame = sealLinkResponse(s, req, { cert, doc: pub.doc, ...(opts.keyholder ? { ik: b64uEncode(ik.secretKey) } : {}) }, app.device);
374
+ await linkPut(conn, lid, "resp", JSON.stringify(frame));
375
+ // Everything else the new device needs travels by sync.
376
+ await sendSync(app, await exportAll(app), [req.did]);
377
+ return { did: req.did, label: req.displayLabel, keyholder: !!opts.keyholder, ver: pub.ver };
378
+ },
379
+ };
380
+ }
381
+ export async function linkJoin(app, code, opts = {}) {
382
+ if (await app.load(false))
383
+ throw new CliError("already_initialized", `${app.home} already holds an identity (${app.userId})`);
384
+ let parsed;
385
+ try {
386
+ parsed = parseLinkCode(code);
387
+ }
388
+ catch {
389
+ throw new CliError("usage", "that is not a link code (p2p-link:…@relay)");
390
+ }
391
+ const { secret, relay } = parsed;
392
+ const device = generateDeviceKeysV3("p2p:pending");
393
+ const x = generateDeviceKeysV3("p2p:pending");
394
+ const label = (opts.label ?? defaultLabel()).slice(0, 64);
395
+ const req = createLinkRequest(secret, device, x.agreementPublicKey, label);
396
+ const lid = linkId(secret);
397
+ const conn = await openLinkConnection(relay, app.transport, app.tun.connectTimeoutMs, app.progress);
398
+ try {
399
+ await linkPut(conn, lid, "req", JSON.stringify(req));
400
+ }
401
+ catch (e) {
402
+ conn.close();
403
+ throw e;
404
+ }
405
+ return {
406
+ compareCode: linkCompareCode(secret, device.did),
407
+ did: device.did,
408
+ wait: async () => {
409
+ const deadline = Date.now() + Math.min(LINK_TTL_SEC * 1000, opts.maxWaitMs ?? Infinity);
410
+ let frame;
411
+ try {
412
+ for (;;) {
413
+ if (Date.now() >= deadline)
414
+ throw new CliError("link_expired", "no answer from the other device within 10 minutes");
415
+ const entries = await linkGet(conn, lid, "resp");
416
+ if (entries === undefined)
417
+ throw new CliError("link_expired", "the link mailbox is gone (expired or declined)");
418
+ if (entries.length > 0) {
419
+ frame = entries[0];
420
+ break;
421
+ }
422
+ await sleep(app.tun.linkPollMs);
423
+ }
424
+ }
425
+ finally {
426
+ conn.close();
427
+ }
428
+ const opened = openLinkResponse(secret, device, x.agreementSecretKey, JSON.parse(frame));
429
+ const userId = opened.doc.iss;
430
+ const keys = newKeysDoc(userId, { ...device, userId }, opened.cert.jws, opened.ik);
431
+ const self = { name: opened.doc.name, relays: opened.doc.relays, createdAt: Date.now() };
432
+ await app.state.put("keys", keys);
433
+ await app.state.put("self", self);
434
+ app.setKeys(keys, self);
435
+ await app.refreshIdentity(userId, opened.doc.relays, { force: true });
436
+ // The bundle came sealed from our own key holder under the link secret: when the relays
437
+ // can't be reached yet, start our own chain from the document it carried.
438
+ if (!(await app.view(userId))?.devices.includes(device.did))
439
+ await jumpIdentity(app.store, opened.doc.jws);
440
+ await app.store.putDeviceCert({ userId, did: device.did, exp: opened.cert.exp, jws: opened.cert.jws });
441
+ receiving(app);
442
+ await app.connectAndDrain();
443
+ return { userId, address: displayAddress(userId, opened.doc.name), did: device.did, keyholder: !!opened.ik };
444
+ },
445
+ };
446
+ }
447
+ // ---------------------------------------------------------------------------
448
+ // Backup (§2.7)
449
+ export async function backupShow(app) {
450
+ const ik = app.requireKeyholder("Showing the backup phrase");
451
+ const phrase = backupPhraseFromSeed(ik.secretKey);
452
+ await app.updateSelf((s) => ({ ...s, backupShown: true }));
453
+ return { phrase, words: 24 };
454
+ }
455
+ /**
456
+ * Restores the identity key on a fresh home: a new key-holding device and
457
+ * the next document version, which by default lists only this device (§2.7:
458
+ * normally revoking devices that were lost). Friendships and circles are not
459
+ * in the phrase: friends' certificates of the old devices stop verifying.
460
+ *
461
+ * review M4: "the relays hold no document" and "the relays couldn't be read"
462
+ * are different. Starting a new chain at version 1 needs `newChain`, and
463
+ * only when at least one relay answered and none holds a document.
464
+ */
465
+ export async function backupRestore(app, phrase, opts) {
466
+ if (await app.load(false))
467
+ throw new CliError("already_initialized", `${app.home} already holds an identity (${app.userId})`);
468
+ try {
469
+ return await restoreInto(app, phrase, opts);
470
+ }
471
+ catch (e) {
472
+ await app.close().catch(() => { });
473
+ // review L1: once a publish may have been stored (accepted, or sent with no answer), a relay may
474
+ // hold the restored version, and wiping would strand the only keys of the device it lists.
475
+ if (app.publishMaybeStored) {
476
+ const why = e instanceof Error ? e.message : String(e);
477
+ throw new CliError("restore_interrupted", `${why}. A relay may already hold the restored document, so this device's state in ${app.home} was kept: run \`p2p identity republish\` to finish, or move ${app.home} aside and run \`p2p backup restore\` again (that revokes this half-restored device)`, { home: app.home, cause: e instanceof CliError ? e.code : "error" });
478
+ }
479
+ // review N-H1: nothing is committed unless a relay took the new version. The home was fresh
480
+ // (checked above), and no relay can hold the new version (every publish was refused outright or
481
+ // never reached a relay), so its state directories go; config.json stays.
482
+ await rm(join(app.home, "cli"), { recursive: true, force: true });
483
+ await rm(join(app.home, "v3"), { recursive: true, force: true });
484
+ throw e;
485
+ }
486
+ }
487
+ async function restoreInto(app, phrase, opts) {
488
+ let ik;
489
+ try {
490
+ ik = identityKeyFromBackupPhrase(phrase);
491
+ }
492
+ catch (e) {
493
+ throw new CliError("bad_phrase", e.message);
494
+ }
495
+ const relays = opts.relays && opts.relays.length > 0 ? normalizeRelays(opts.relays) : defaultRelays(app.env, app.file);
496
+ if (relays.length === 0)
497
+ throw new CliError("no_relays", "pass --relay with one of the relays your identity uses (or set P2P_DEFAULT_RELAYS)");
498
+ // Which relays answered, and with what.
499
+ let reachable = 0;
500
+ let found = 0;
501
+ for (const r of relays) {
502
+ try {
503
+ found += (await fetchTips(app.transport(r), ik.userId, app.tun.connectTimeoutMs, app.progress)).length;
504
+ reachable++;
505
+ }
506
+ catch {
507
+ // unreachable or erroring relay
508
+ }
509
+ }
510
+ if (reachable === 0)
511
+ throw new CliError("unreachable", "none of those relays could be read: try again when one is reachable (nothing was changed)");
512
+ if (found === 0 && !opts.newChain) {
513
+ throw new CliError("no_document", "no relay you named holds a document for this identity. Name the relays your identity uses (--relay), or pass --new-chain to start a new history at version 1");
514
+ }
515
+ const device = generateDeviceKeysV3(ik.userId);
516
+ const cert = createDeviceCert(ik, { signingPublicKey: device.signingPublicKey, agreementPublicKey: device.agreementPublicKey, label: defaultLabel() });
517
+ const keys = newKeysDoc(ik.userId, device, cert, ik);
518
+ const self = { name: opts.name ?? defaultName(), relays, createdAt: Date.now(), backupShown: true };
519
+ app.setKeys(keys, self);
520
+ // The relays hold a document that doesn't list this device yet: publish over a restricted connection.
521
+ app.allowRestricted = true;
522
+ const warnings = [];
523
+ if (found === 0) {
524
+ const name = opts.name ?? defaultName();
525
+ const doc = createIdentityDoc(ik, { ver: 1, prev: null, name, relays, devices: [device.did], keyholders: [device.did], by: device.did, certs: [cert] });
526
+ await app.state.put("keys", keys);
527
+ await app.state.put("self", { ...self, name });
528
+ app.setKeys(keys, { ...self, name });
529
+ await app.store.putDeviceCert({ userId: ik.userId, did: device.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
530
+ await addIdentityVersion(app.store, doc);
531
+ await app.connect({ allowNone: true });
532
+ const r = await app.publishDoc(doc, relays);
533
+ if (r.ok.length === 0)
534
+ throw new CliError("not_published", `no relay accepted the new identity document (${r.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")}); nothing was restored`);
535
+ warnings.push("started a new identity history at version 1 (--new-chain)");
536
+ for (const w of warnings)
537
+ app.warn(w);
538
+ if (r.failed.length > 0)
539
+ warnings.push(`RESTORE INCOMPLETE: ${r.failed.length} relays didn't take the new document (${r.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")})`);
540
+ for (const w of warnings.slice(1))
541
+ app.warn(w);
542
+ return { userId: ik.userId, address: displayAddress(ik.userId, name), did: device.did, ver: 1, revoked: [], warnings, merged: 0, failed: r.failed };
543
+ }
544
+ // Strict: the head must be confirmed on the relays before building on it.
545
+ const existing = await app.refreshIdentity(ik.userId, relays, { force: true, strict: true });
546
+ if (!existing)
547
+ throw new CliError("refresh_failed", "couldn't fit the relays' identity document");
548
+ await app.state.put("keys", keys);
549
+ await app.store.putDeviceCert({ userId: ik.userId, did: device.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
550
+ await app.state.put("self", { ...self, name: existing.head.name, relays: existing.head.relays });
551
+ app.setKeys(keys, { ...self, name: existing.head.name, relays: existing.head.relays });
552
+ const revoked = opts.keepDevices ? [] : existing.devices;
553
+ await app.connect({ allowNone: true });
554
+ const pub = await app.publishNext((p) => {
555
+ if (!opts.keepDevices) {
556
+ p.devices = [];
557
+ p.keyholders = [];
558
+ p.certs = [];
559
+ }
560
+ if (p.devices.length >= MAX_DEVICES)
561
+ throw new CliError("too_many_devices", "your identity already lists 10 devices: restore without --keep-devices");
562
+ p.devices = [...p.devices, device.did];
563
+ p.keyholders = [...p.keyholders, device.did];
564
+ if (opts.name)
565
+ p.name = opts.name;
566
+ }, { restoring: true });
567
+ if (pub.ok.length === 0) {
568
+ throw new CliError("not_published", `no relay accepted the restored identity document (${pub.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")}); nothing was restored`);
569
+ }
570
+ const lostKeyholders = revoked.filter((d) => existing.keyholders.includes(d));
571
+ if (lostKeyholders.length > 0)
572
+ warnings.push(lostKeyholderWarning(lostKeyholders.length));
573
+ // R3-M2: a relay that refused keeps serving the old document (which doesn't list this device).
574
+ if (pub.failed.length > 0) {
575
+ warnings.push(`RESTORE INCOMPLETE: ${pub.failed.length} of your relays didn't take the new document (${pub.failed.map((f) => `${f.relay}: ${f.code}`).join(", ")}). Until they do, they still list your old devices and refuse this one; run \`p2p identity republish\` once they're reachable (it's also retried on every connect)`);
576
+ }
577
+ for (const w of warnings)
578
+ app.warn(w);
579
+ return { userId: ik.userId, address: displayAddress(ik.userId, opts.name ?? existing.head.name), did: device.did, ver: pub.ver, revoked, warnings, merged: pub.merged, failed: pub.failed };
580
+ }
581
+ /** review H2/L5: revoking a key holder doesn't take the identity key back. */
582
+ export function lostKeyholderWarning(n) {
583
+ return `${n === 1 ? "a revoked device was a key holder: it" : `${n} revoked devices were key holders: they`} still hold your identity key and could publish new versions, and occupy the relays' restricted connection slots for your identity. Only identity rotation neutralises a lost key holder: run \`p2p identity rotate\` (§2.8) from a key holder you still have`;
584
+ }
585
+ // ---------------------------------------------------------------------------
586
+ // Profile (draft 3 additions P1)
587
+ const MAGIC = [
588
+ ["png", [0x89, 0x50, 0x4e, 0x47]],
589
+ ["jpeg", [0xff, 0xd8, 0xff]],
590
+ ["gif", [0x47, 0x49, 0x46, 0x38]],
591
+ ];
592
+ /** An avatar value: an https URL or data: URI as given, or an image file made into a data: URI (≤ 4 KiB). */
593
+ export async function avatarValue(input, read = (p) => readFile(p)) {
594
+ if (/^https:\/\//i.test(input) || input.startsWith("data:"))
595
+ return input;
596
+ let bytes;
597
+ try {
598
+ bytes = await read(input);
599
+ }
600
+ catch {
601
+ throw new CliError("usage", `--avatar ${input} is not an https URL, a data: URI or a readable image file`);
602
+ }
603
+ let mime = MAGIC.find(([, m]) => m.every((b, i) => bytes[i] === b))?.[0];
604
+ if (!mime && bytes.length > 12 && Buffer.from(bytes.slice(0, 4)).toString() === "RIFF" && Buffer.from(bytes.slice(8, 12)).toString() === "WEBP")
605
+ mime = "webp";
606
+ if (!mime)
607
+ throw new CliError("usage", "--avatar must be a PNG, JPEG, WebP or GIF image (SVG is not allowed)");
608
+ const uri = `data:image/${mime};base64,${Buffer.from(bytes).toString("base64")}`;
609
+ if (uri.length > PROFILE_AVATAR_DATA_MAX) {
610
+ throw new CliError("avatar_too_large", `the avatar is ${uri.length} bytes as a data: URI; the cap is ${PROFILE_AVATAR_DATA_MAX} (4 KiB): use a smaller image or an https URL`);
611
+ }
612
+ return uri;
613
+ }
614
+ export async function profileSet(app, opts) {
615
+ const avatar = opts.avatar !== undefined && opts.avatar !== "" ? await avatarValue(opts.avatar) : opts.avatar;
616
+ await app.connect({ allowNone: true });
617
+ let pub;
618
+ try {
619
+ pub = await app.publishNext((p) => {
620
+ const cur = opts.clear ? {} : { ...(p.profile ?? {}) };
621
+ if (opts.bio !== undefined) {
622
+ if (opts.bio === "")
623
+ delete cur.bio;
624
+ else
625
+ cur.bio = opts.bio;
626
+ }
627
+ if (avatar !== undefined) {
628
+ if (avatar === "")
629
+ delete cur.avatar;
630
+ else
631
+ cur.avatar = avatar;
632
+ }
633
+ if (opts.links !== undefined) {
634
+ if (opts.links.length === 0)
635
+ delete cur.links;
636
+ else
637
+ cur.links = opts.links;
638
+ }
639
+ if (Object.keys(cur).length === 0)
640
+ delete p.profile;
641
+ else
642
+ p.profile = cur;
643
+ });
644
+ }
645
+ catch (e) {
646
+ if (e instanceof P2PError && e.reason === "malformed")
647
+ throw new CliError("bad_profile", e.message);
648
+ throw e;
649
+ }
650
+ const v = await app.ownView();
651
+ return { profile: displayProfile(v.head.profile), ver: pub.ver };
652
+ }
653
+ export async function profileShow(app, who) {
654
+ const u = who ? await app.resolveUser(who) : app.userId;
655
+ const v = u === app.userId ? await app.ownView() : await app.viewFor(u);
656
+ if (!v)
657
+ throw new CliError("unknown_user", `no identity document for ${u}`);
658
+ return { userId: u, address: await app.addressOf(u), profile: displayProfile(v.head.profile) };
659
+ }
660
+ export async function proofAdd(app, kind, claimRaw, opts) {
661
+ const ik = app.requireKeyholder("Signing a proof");
662
+ const claim = claimRaw.trim().toLowerCase();
663
+ if (kind === "github") {
664
+ if (!opts.gist) {
665
+ return {
666
+ kind,
667
+ claim,
668
+ pending: true,
669
+ publish: `1. Create a public gist as ${claim} at https://gist.github.com (any file name, e.g. p2p-proof.md; any content for now).\n2. Run: p2p proof add github ${claim} --gist <gist id>\n3. Replace the gist's content with the proof that command prints.`,
670
+ };
671
+ }
672
+ let loc;
673
+ try {
674
+ loc = canonicalProofLoc("github", claim, opts.gist);
675
+ }
676
+ catch (e) {
677
+ throw new CliError("usage", e.message);
678
+ }
679
+ const proof = createProof(ik, { kind: "github", claim, loc });
680
+ const pub = await addProof(app, proof, "github", claim);
681
+ return { kind, claim, loc, proof, ver: pub, publish: `Put this exact text in your gist ${loc}:\n${proof}` };
682
+ }
683
+ if (kind === "dns") {
684
+ let loc;
685
+ try {
686
+ loc = canonicalProofLoc("dns", claim);
687
+ }
688
+ catch (e) {
689
+ throw new CliError("usage", e.message);
690
+ }
691
+ const proof = createProof(ik, { kind: "dns", claim, loc });
692
+ const pub = await addProof(app, proof, "dns", claim);
693
+ return { kind, claim, loc, proof, ver: pub, publish: `Add this DNS TXT record:\n ${loc} TXT "${dnsProofRecord(app.userId)}"` };
694
+ }
695
+ throw new CliError("usage", "proof kinds are github and dns");
696
+ }
697
+ async function addProof(app, proof, kind, claim) {
698
+ await app.connect({ allowNone: true });
699
+ const same = (j) => {
700
+ try {
701
+ const p = decodeTyped(j, TYP3.proof).payload;
702
+ return p.kind === kind && p.claim === claim;
703
+ }
704
+ catch {
705
+ return false;
706
+ }
707
+ };
708
+ const pub = await app.publishNext((p) => {
709
+ p.proofs = [...(p.proofs ?? []).filter((j) => !same(j)), proof];
710
+ });
711
+ return pub.ver;
712
+ }
713
+ /** Fetchers for the built-in kinds: the GitHub gist API and DNS TXT. */
714
+ export function defaultProofFetchers() {
715
+ return {
716
+ github: async (loc) => {
717
+ const id = loc.split("/").at(-1);
718
+ const res = await fetch(`https://api.github.com/gists/${encodeURIComponent(id)}`, { headers: { accept: "application/vnd.github+json", "user-agent": "peer2peer-cli" } });
719
+ if (!res.ok)
720
+ return undefined;
721
+ const g = (await res.json());
722
+ if (!g.owner?.login)
723
+ return undefined;
724
+ return { owner: g.owner.login, files: Object.values(g.files ?? {}).map((f) => f.content ?? "") };
725
+ },
726
+ dnsTxt: async (name) => (await resolveTxt(name)).map((r) => r.join("")),
727
+ };
728
+ }
729
+ export async function proofVerify(app, who, fetchers = defaultProofFetchers()) {
730
+ const u = await app.resolveUser(who);
731
+ const v = u === app.userId ? await app.ownView() : await app.viewFor(u);
732
+ if (!v)
733
+ throw new CliError("unknown_user", `no identity document for ${who}`);
734
+ const ok = await verifiedProofs(v.head, fetchers);
735
+ const out = [];
736
+ for (const j of v.head.proofs ?? []) {
737
+ const hit = ok.find((p) => p.jws === j);
738
+ if (hit) {
739
+ out.push({ kind: hit.kind, claim: sanitizePeerText(hit.claim, 64), loc: hit.loc, verified: true, display: hit.display });
740
+ continue;
741
+ }
742
+ try {
743
+ const p = verifyProofSignature(j, v.head);
744
+ out.push({ kind: p.kind, claim: sanitizePeerText(p.claim, 64), loc: p.loc, verified: false, error: "the counterpart doesn't hold this proof (or couldn't be fetched)" });
745
+ }
746
+ catch (e) {
747
+ out.push({ kind: "?", claim: "?", loc: "", verified: false, error: e.message });
748
+ }
749
+ }
750
+ return { userId: u, address: await app.addressOf(u), proofs: out };
751
+ }