@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.
package/dist/cli.js CHANGED
@@ -12,7 +12,7 @@ import { resolve } from "node:path";
12
12
  import * as codex from "@peer2peer/codex-bridge";
13
13
  import { Command, CommanderError, Option } from "commander";
14
14
  import { App } from "./app.js";
15
- import { ownAgentsDeliver, ownAgentsDeliverFrom, ownDevicesDeliver, readFileConfig, resolveHome, updateFileConfigField } from "./config.js";
15
+ import { defaultRelays, normalizeRelays, ownAgentsDeliver, ownAgentsDeliverFrom, ownDevicesDeliver, readFileConfig, resolveHome, updateFileConfigField } from "./config.js";
16
16
  import { receiptsSetting, sendReceipt } from "./receipts.js";
17
17
  import * as trustOps from "./trust.js";
18
18
  import { CliError, toErrorJson } from "./errors.js";
@@ -22,6 +22,7 @@ import * as circles from "./circle-ops.js";
22
22
  import { registerExtensionCommands } from "./ext-host.js";
23
23
  import { ExtensionRegistry, loadExtensions } from "./extensions.js";
24
24
  import * as codes from "./codes.js";
25
+ import { parseShortCode } from "./shortcode.js";
25
26
  import * as identity from "./identity.js";
26
27
  import { receiving } from "./inbound.js";
27
28
  import * as rotation from "./rotation.js";
@@ -64,6 +65,88 @@ export function wideningOf(cmd) {
64
65
  }
65
66
  return undefined;
66
67
  }
68
+ /**
69
+ * Commands that touch the person's identity key, their identity document, or their own setup (or
70
+ * narrow who reaches them): run only by the person, through the same gate as widening (their
71
+ * front end's token, or their "yes" typed on their own terminal; never from inside an agent's
72
+ * session). The CLI decides by the command it parsed and its agent detection (environment and
73
+ * process ancestry), not by the command line's words: a name built at run time, or a script the
74
+ * agent wrote and runs in its own process tree, is refused like the plain command. It is not a
75
+ * boundary against an agent that runs as the same user and means to get past it: a process started
76
+ * outside the agent's tree that fakes a terminal can answer the "yes", and the key files can be
77
+ * read directly. That boundary is the OS sandbox's read and write deny on P2P_HOME
78
+ * (docs/security/threat-model.md). Internal maintenance (`p2p watch`
79
+ * renewing the document and certificates, the retry of unpublished relays on connect) calls the
80
+ * App directly, never these commands, and is not gated.
81
+ */
82
+ const PERSON_ONLY = new Map([
83
+ ["backup show", "shows your identity key (its backup phrase)"],
84
+ ["backup restore", "replaces this device's identity key"],
85
+ ["identity rotate", "moves your identity to a new key"],
86
+ ["identity republish", "publishes your identity document"],
87
+ ["identity dispute", "decides which identity a friend of yours is"],
88
+ ["devices revoke", "changes the devices your identity lists"],
89
+ ["relays add", "changes the relays your identity lists"],
90
+ ["relays remove", "changes the relays your identity lists"],
91
+ ["trust remove", "changes who you trust"],
92
+ ["invites revoke", "changes your invites"],
93
+ ["remove", "changes your friendships and circles"],
94
+ ["unfriend", "changes your friendships"],
95
+ ["circle propose", "changes a circle's members"],
96
+ ["circle transfer", "changes who owns a circle"],
97
+ ["circle hold", "changes how your circle takes changes"],
98
+ ["extensions disable", "changes which extensions run with your identity"],
99
+ ["ix import", "writes into your Ix graph"],
100
+ ["ix resolve", "runs your Ix for a peer's reference"],
101
+ ["ix config", "changes how your Ix footprints name files"],
102
+ ["receipts", "changes whether you send delivery receipts"],
103
+ ["profile set", "publishes a new version of your identity document"],
104
+ ["proof add", "publishes a new version of your identity document"],
105
+ ["block", "changes who reaches you"],
106
+ ["petname", "changes the names you know people by"],
107
+ ["circle leave", "changes your circles"],
108
+ ["held decline", "decides a held request for you"],
109
+ ]);
110
+ /** `identity rotate` options that do something beyond making or showing the plan. */
111
+ const ROTATE_ACTS = ["resume", "cancel", "exclude", "keep", "invite", "keepKeyholders", "backupFile", "contest", "resend", "yes", "branch"];
112
+ /**
113
+ * The person-only command `cmd` is ({what, why}), or undefined. Reads stay open: a bare
114
+ * `receipts`, `circle hold <cid>` and `ix config`, and a bare `identity rotate --plan` (it makes
115
+ * or shows the plan: the new fingerprint and which devices follow; nothing is published or
116
+ * revealed, and accepting it is gated).
117
+ */
118
+ export function personOnlyOf(cmd) {
119
+ const path = [];
120
+ for (let c = cmd; c && c.parent; c = c.parent)
121
+ path.unshift(c.name());
122
+ const p = path.join(" ");
123
+ const why = PERSON_ONLY.get(p);
124
+ if (why === undefined)
125
+ return undefined;
126
+ const args = cmd.args ?? [];
127
+ switch (p) {
128
+ case "receipts":
129
+ return args.length > 0 ? { what: args[0] === "on" || args[0] === "off" ? `receipts ${args[0]}` : "receipts", why } : undefined;
130
+ case "circle hold":
131
+ return args.length > 1 ? { what: args[1] === "on" || args[1] === "off" ? `circle hold <cid> ${args[1]}` : "circle hold", why } : undefined;
132
+ case "ix config":
133
+ return args.length > 0 ? { what: "ix config", why } : undefined;
134
+ // Restore runs only on a fresh home and needs the phrase itself, typed or piped: that is the
135
+ // person's proof outside an agent's session (a fresh home has no person token yet, and a
136
+ // headless restore must keep working). Inside an agent's session it is refused, as `link join`.
137
+ case "backup restore":
138
+ return { what: p, why, agentOnly: true };
139
+ case "identity rotate": {
140
+ const o = cmd.opts();
141
+ const acts = ROTATE_ACTS.filter((k) => o[k] !== undefined && o[k] !== false && !(Array.isArray(o[k]) && o[k].length === 0));
142
+ if (o.plan && acts.length === 0)
143
+ return undefined;
144
+ return { what: o.cancel ? "identity rotate --cancel" : o.plan ? "identity rotate --plan" : "identity rotate", why };
145
+ }
146
+ default:
147
+ return { what: p, why };
148
+ }
149
+ }
67
150
  const posInt = (name) => (v) => {
68
151
  const n = Number(v);
69
152
  if (!Number.isSafeInteger(n) || n < 0)
@@ -106,6 +189,10 @@ export function buildProgram(deps) {
106
189
  const app = baseMakeApp(env, i, o);
107
190
  app.extensions ??= extensions;
108
191
  app.front = deps.front === true;
192
+ if (app.front && deps.frontToken !== undefined) {
193
+ app.frontToken = deps.frontToken;
194
+ app.frontFresh = deps.frontFresh === true;
195
+ }
109
196
  app.confirmTty = confirmTty;
110
197
  return app;
111
198
  };
@@ -123,14 +210,33 @@ export function buildProgram(deps) {
123
210
  const app = makeApp(deps.env, io, opts.readOnly ? { readOnly: true } : undefined);
124
211
  let stop = () => { };
125
212
  try {
213
+ if (deps.personTokenLinked) {
214
+ throw new CliError("refused", `the person token is never taken in ${app.home}: its cli folder, keys, self document, token, salt or v3 store is a symbolic link (or a hard-linked copy). A home kept by a dotfile manager or linked from elsewhere can't use the token: point P2P_HOME at the real folder. Nothing was done`);
215
+ }
216
+ if (deps.personTokenStale) {
217
+ throw new CliError("person_token_stale", `P2P_PERSON_TOKEN isn't this device's person token: ${projects.personTokenFile(app.home)} is replaced when an identity is created or restored here. Nothing was done: read that file again and run the command again. A front end does this itself (in Claude Code, reloading the Peer2Peer plugin also does it)`);
218
+ }
126
219
  // §2.8 (L4): a follow that died mid-swap finishes before anything reads this home (not for a
127
220
  // read-only command, which must leave the home exactly as it found it).
128
221
  if (typeof app.home === "string" && !opts.readOnly)
129
222
  await rotation.recoverInterruptedFollow(app.home).catch(() => false);
223
+ // The token was checked when the command started; the home may have changed since (an
224
+ // interrupted follow finished just now, or files swapped in by something else). Checked again
225
+ // as the home is now, before any gate: a home that had no identity then and has one now keeps
226
+ // no token. The keys the command loads are checked against it too (App.load).
227
+ if (app.front && app.frontToken !== undefined) {
228
+ const still = projects.personTokenOk({ P2P_PERSON_TOKEN: app.frontToken }, app.home);
229
+ if (!still || (app.frontFresh && projects.identityHere(app.home)))
230
+ app.front = false;
231
+ }
130
232
  // An agent can't widen who reaches this user, however it runs p2p (projects.ts).
131
233
  const widening = wideningOf(cmd);
132
234
  if (widening)
133
- await projects.assertPersonForWidening(app, widening, confirmTty);
235
+ await projects.assertPersonForWidening(app, widening, confirmTty, undefined, { noTokenBeforeIdentity: widening === "link join" });
236
+ // Nor touch the identity key, the identity document or the person's own setup (PERSON_ONLY).
237
+ const personOnly = personOnlyOf(cmd);
238
+ if (personOnly && !(personOnly.agentOnly && projects.personHereStrict(app)))
239
+ await projects.assertPersonForWidening(app, personOnly.what, confirmTty, personOnly.why);
134
240
  if (opts.requireIdentity !== false)
135
241
  await app.load(true);
136
242
  // The person token the person's front ends pass back (projects.ts), made once, in the CLI's own folder.
@@ -188,7 +294,7 @@ export function buildProgram(deps) {
188
294
  deps.io.out(pretty.safePretty(out.pretty(deps.io.pretty)));
189
295
  else if (out.human)
190
296
  io.out(safeTerminal(out.human));
191
- // Ix on by default for new installs; an existing one hears it once, at a terminal, from the person (ix-local.ts).
297
+ // Ix is optional: new installs are offered it; an existing one hears it once, at a terminal, from the person (ix-local.ts).
192
298
  if (!json && !opts.readOnly && app.keys && deps.io.prompt && projects.personHere(app) && cmd.name() !== "setup") {
193
299
  const n = await ixLocal.ixNotice(app).catch(() => undefined);
194
300
  if (n)
@@ -254,6 +360,115 @@ export function buildProgram(deps) {
254
360
  const friendChoices = async (app) => (await ops.friends(app)).friends.map((f) => ({ value: f.userId, label: f.address, detail: f.canMessage ? "connected" : "waiting for their cap" }));
255
361
  const circleChoices = async (app, which) => (await ops.listCircles(app)).filter(which).map((c) => ({ value: c.cid, label: c.name, detail: `${fmt.plural(c.members, "member")} · ${c.policy} · ${c.role}${c.isDefault ? " · default" : ""}` }));
256
362
  const heldChoices = async (app) => (await ops.listHeld(app)).map((h) => ({ value: h.id, label: `${h.address}: ${h.summary}`, detail: h.type }));
363
+ /** What `p2p join` says it did (setup's invite path says the same). */
364
+ const joinLines = (r) => {
365
+ const lines = [`You and ${r.friend.address} are friends${r.delivered && r.delivered.relays.length === 0 ? " (they'll know once the accept is delivered: run this again later)" : ""}.`];
366
+ for (const c of r.circles) {
367
+ if (c.status === "joined" || c.status === "already")
368
+ lines.push(`${c.status === "joined" ? "Joined" : "Already in"} "${c.name}"${c.default ? "; it is your default circle (new sessions start in it; running ones stay as they are)" : ""}.`);
369
+ else if (c.status === "pending")
370
+ lines.push(`${r.friend.address} adds you to "${c.name}" when their client next runs; your next p2p command finishes the join.`);
371
+ else if (c.status === "held")
372
+ lines.push(`Not joined "${c.name}" from this code (${c.reason}): if its invite comes, \`p2p held\` lists it for you to approve on its own.`);
373
+ else
374
+ lines.push(`"${c.name}" couldn't be confirmed with a second member (§3.3): \`p2p held approve ${c.held}\` to join anyway.`);
375
+ }
376
+ return lines;
377
+ };
378
+ // ── setup's questions (a person at a terminal only: io.prompt) ──
379
+ /** One of `letters`, asked at most three times; then nothing is done. */
380
+ const askLetter = async (q, letters) => {
381
+ for (let i = 0; i < 3; i++) {
382
+ const a = (await io.prompt(q)).trim().toLowerCase();
383
+ if (letters.includes(a))
384
+ return a;
385
+ io.err(`Type ${letters.slice(0, -1).join(", ")} or ${letters[letters.length - 1]}.`);
386
+ }
387
+ throw new CliError("cancelled", "cancelled: nothing was done (run `p2p setup` again)");
388
+ };
389
+ const askNonEmpty = async (q, what) => {
390
+ for (let i = 0; i < 3; i++) {
391
+ const a = (await io.prompt(q)).trim();
392
+ if (a !== "")
393
+ return a;
394
+ io.err(`Type ${what}, or press Ctrl-C to stop.`);
395
+ }
396
+ throw new CliError("cancelled", "cancelled: nothing was done (run `p2p setup` again)");
397
+ };
398
+ /** How a person with no identity here is joining (setup): before any key is made. */
399
+ const askJoinPath = async (p2p) => {
400
+ io.out([
401
+ "How are you joining Peer2Peer?",
402
+ " [l] I already use Peer2Peer on another device: link this device to it",
403
+ " [i] I have an invite link or code from someone",
404
+ " [n] Start a new identity (my first device)",
405
+ `(Already have an identity? Choose l: a new one here would be a second, separate identity. ${p2p} link join and ${p2p} join do the same later.)`,
406
+ ].join("\n"));
407
+ const a = await askLetter("Choose l, i or n: ", ["l", "i", "n"]);
408
+ return a === "l" ? "link" : a === "i" ? "invite" : "new";
409
+ };
410
+ /** The group's relay for a new identity (no default relay: bring your own), as a canonical wss:// URL. */
411
+ const askRelay = async () => {
412
+ io.out("\nPeer2Peer has no default relay: each group runs its own. Ask whoever runs yours for its address (wss://…).");
413
+ for (let i = 0; i < 3; i++) {
414
+ let a = (await io.prompt("Relay URL (wss://…): ")).trim();
415
+ // A bare host means wss:// (the only scheme a relay URL has); any other scheme is refused.
416
+ if (a !== "" && !/^[a-z][a-z0-9+.-]*:\/\//i.test(a))
417
+ a = `wss://${a}`;
418
+ if (!/^wss:\/\//i.test(a)) {
419
+ io.err(a === "" ? "Type the relay's address (wss://…)." : "A relay URL starts with wss:// (ws://, http:// and https:// aren't relay URLs).");
420
+ continue;
421
+ }
422
+ try {
423
+ return normalizeRelays([a])[0];
424
+ }
425
+ catch (e) {
426
+ io.err(e instanceof CliError ? String(e.message) : `${a} is not a relay URL`);
427
+ }
428
+ }
429
+ throw new CliError("cancelled", "cancelled: nothing was done (run `p2p setup --relay wss://…` again)");
430
+ };
431
+ const isLinkCode = (s) => /^p2p-link:/i.test(s.trim());
432
+ const looksLikeInvite = (s) => {
433
+ try {
434
+ parseShortCode(s, { allowPrivate: true });
435
+ return true;
436
+ }
437
+ catch {
438
+ return false;
439
+ }
440
+ };
441
+ /**
442
+ * The person's yes, on their own terminal, to the identity a link code makes this device part of
443
+ * (`link join` and setup's link path): nothing is kept before it.
444
+ */
445
+ const confirmLinkIdentity = (p2p) => (who) => confirmTty(`This device would become ${who.address} (fingerprint ${who.fingerprint})${who.keyholder ? ", a key holder" : ""}. Is this your identity? It must match \`${p2p} whoami\` on your other device: a link code from anyone else makes this device theirs.`);
446
+ /** setup, "I already use Peer2Peer on another device": `p2p link join`, inline. No identity is made here, so no backup is asked. */
447
+ const setupByLink = async (app, p2p, o) => {
448
+ await projects.assertPersonForWidening(app, "link join", confirmTty, undefined, { noTokenBeforeIdentity: true });
449
+ io.out([
450
+ "",
451
+ "Link this device to the identity you already have:",
452
+ " 1. On your other device run: p2p link start",
453
+ " (Windows PowerShell: p2p.cmd link start; in Claude Code: /peers link start)",
454
+ " 2. It shows a one-time link code (p2p-link:…). Type it here.",
455
+ "Only type a code shown on YOUR OWN other device. A code from anyone else makes this device theirs.",
456
+ ...(o.ignored.length > 0 ? [`(${o.ignored.join(", ")} ${o.ignored.length === 1 ? "is" : "are"} ignored when linking: this device takes your identity's name, relays and backup.)`] : []),
457
+ ].join("\n"));
458
+ const code = await askNonEmpty("Link code: ", "the link code");
459
+ // An invite pasted here (someone else's): it is joined as an invite, with its own confirmation.
460
+ if (!isLinkCode(code) && looksLikeInvite(code)) {
461
+ io.err("That is an invite from someone, not a link code from your own device: joining with it as an invite instead (you'll see who it's from first).");
462
+ return { invite: code };
463
+ }
464
+ const j = await ops.linkJoin(app, code, { ...(o.allowPrivateRelay ? { allowPrivateRelay: true } : {}) });
465
+ io.out(`Compare code: ${j.compareCode}\nCheck the other device shows the same code, and confirm there. Waiting…`);
466
+ const r = await j.wait(confirmLinkIdentity(p2p));
467
+ return {
468
+ json: { linked: r },
469
+ human: [`This device is now ${r.address} (${r.did})${r.keyholder ? ", a key holder" : ""}.`, "", `Check it: ${p2p} whoami Invite someone: ${p2p} invite <their name>`].join("\n"),
470
+ };
471
+ };
257
472
  // ── identity ──────────────────────────────────────────────────────────────
258
473
  program
259
474
  .command("init")
@@ -295,23 +510,95 @@ export function buildProgram(deps) {
295
510
  }, { requireIdentity: false }));
296
511
  program
297
512
  .command("setup")
298
- .description("Get started: create your identity with sensible defaults (safe to run again)")
513
+ .description("Get started: link this device to your identity, join with an invite, or create a new identity (safe to run again)")
299
514
  .option("--name <name>", "Your display name (default: your OS user name)")
300
515
  .option("--relay <url>", "A relay to use (repeat for up to 5); default: P2P_DEFAULT_RELAYS, config.json, or the relays shipped with the CLI", collect)
301
516
  .option("--backup-file [path]", "Save the 24-word backup phrase to a 0600 file (default <home>/backup-phrase.txt)")
302
517
  .option("--print-backup", "Print the backup phrase (in --json, as backup.phrase)")
303
518
  .option("--no-backup", "Don't save or print the backup phrase now")
519
+ .option("--ix", "Offer Ix again after an earlier no (optional; Peer2Peer never installs it), and with Ix installed, offer to turn on the Ix extension")
520
+ .option("--allow-private-relay", "Linking or joining: accept a code whose relay is a loopback, link-local or private address (your own relay on your network; also P2P_ALLOW_PRIVATE_RELAY=1)")
304
521
  .option("--json", "JSON output")
305
522
  .action(run(async (app, o) => {
306
523
  let mode = o.backupFile !== undefined ? "file" : o.printBackup ? "print" : o.backup === false ? "none" : undefined;
307
524
  const existed = await app.load(false);
308
- if (mode === undefined && !existed && !o.json && io.prompt) {
309
- io.out("Your identity key will live only on this device. A 24-word backup phrase restores it if the device is lost.\n [f] save it to a file only you can read (0600), on this device: copy it off later\n [p] print it now, for a password manager or paper (best)\n [s] skip for now (p2p backup show later)");
525
+ // On a home that already holds an identity, setup's backup options reveal the existing key's
526
+ // phrase (`backup show`'s gate): the person's only. A new identity's own phrase is not.
527
+ if (existed && (o.printBackup || o.backupFile !== undefined)) {
528
+ await projects.assertPersonForWidening(app, o.printBackup ? "setup --print-backup" : "setup --backup-file", confirmTty, PERSON_ONLY.get("backup show"));
529
+ }
530
+ const p2p = identity.p2pCommand();
531
+ // Asked only once an identity exists here (its key was just made): never before.
532
+ const askBackup = async () => {
533
+ io.out(`\nYour identity key lives only on this device. A 24-word backup phrase restores it if the device is lost.\n [f] save it to a file only you can read (0600), on this device: copy it off later\n [p] print it now, for a password manager or paper (best)\n [s] skip for now (${p2p} backup show later)`);
310
534
  const a = (await io.prompt("Choose f, p or s: ")).trim().toLowerCase();
311
- mode = a === "p" ? "print" : a === "s" ? "none" : "file";
312
- }
313
- const r = await ops.setup(app, { name: o.name, relays: o.relay, backup: mode, ...(typeof o.backupFile === "string" ? { backupFile: o.backupFile } : {}) });
314
- const lines = [r.created ? `Created ${r.address}` : `Already set up: ${r.address}`, ` relays ${r.relays.join(", ")}`];
535
+ return a === "p" ? "print" : a === "s" ? "none" : "file";
536
+ };
537
+ // A person at a terminal with no identity here says how they're joining first, before any key
538
+ // is made: someone who already has an identity links this device to it instead of making a
539
+ // second one. Never with --json, in CI, without a terminal, or inside an agent's session.
540
+ const asking = !existed && !o.json && Boolean(io.prompt) && !ixLocal.ciEnv(app.env) && projects.personHere(app);
541
+ let how = asking ? await askJoinPath(p2p) : "new";
542
+ let inviteCode;
543
+ if (how === "link") {
544
+ const ignored = [
545
+ ...(o.name !== undefined ? ["--name"] : []),
546
+ ...(o.relay && o.relay.length > 0 ? ["--relay"] : []),
547
+ ...(o.backupFile !== undefined ? ["--backup-file"] : []),
548
+ ...(o.printBackup ? ["--print-backup"] : []),
549
+ ];
550
+ const l = await setupByLink(app, p2p, { allowPrivateRelay: o.allowPrivateRelay, ignored });
551
+ if (!("invite" in l))
552
+ return l;
553
+ how = "invite";
554
+ inviteCode = l.invite;
555
+ }
556
+ let createdHere = false;
557
+ if (how === "invite") {
558
+ await projects.assertPersonForWidening(app, "join", confirmTty, undefined, { noTokenBeforeIdentity: true });
559
+ if (inviteCode === undefined)
560
+ io.out("\nPaste the invite link (https://…/p2p/invite#…) or the code you were sent. It carries the relays your inviter uses.");
561
+ const code = inviteCode ?? (await askNonEmpty("Invite link or code: ", "an invite link or code"));
562
+ if (isLinkCode(code)) {
563
+ throw new CliError("usage", `that is a device link code, not an invite: nothing was done. Link codes come only from your own other device, and one from anyone else makes this device theirs. If it is from your own device, run \`${p2p} setup\` again and choose l`);
564
+ }
565
+ const j = await ops.joinCode(app, code, {
566
+ name: o.name,
567
+ ...(o.allowPrivateRelay ? { allowPrivateRelay: true } : {}),
568
+ confirm: (q) => confirmPrompt(q, false, ["Join", "Cancel"]),
569
+ create: async (a, x) => {
570
+ const c = await ops.init(a, x);
571
+ receiving(a);
572
+ createdHere = true;
573
+ io.out(`Created ${c.address}`);
574
+ io.err(`Only this device holds your identity key: save a backup with \`${p2p} backup show\` (setup asks next).`);
575
+ return { userId: c.userId, address: c.address, relays: c.relays };
576
+ },
577
+ });
578
+ io.out(joinLines(j).join("\n"));
579
+ if (createdHere && mode === undefined)
580
+ mode = await askBackup();
581
+ }
582
+ let relays = o.relay;
583
+ // There is no default relay (bring your own): a new identity starts on the group's relay.
584
+ if (how === "new" && asking && !(relays && relays.length > 0) && defaultRelays(app.env, app.file).length === 0)
585
+ relays = [await askRelay()];
586
+ const chooseBackup = how === "new" && mode === undefined && !o.json && io.prompt
587
+ ? async (c) => {
588
+ createdHere = true;
589
+ io.out(`Created ${c.address}`);
590
+ return askBackup();
591
+ }
592
+ : undefined;
593
+ const r = await ops.setup(app, {
594
+ name: o.name,
595
+ relays,
596
+ backup: mode,
597
+ ...(typeof o.backupFile === "string" ? { backupFile: o.backupFile } : {}),
598
+ ...(o.ix ? { ix: true } : {}),
599
+ ...(chooseBackup ? { chooseBackup } : {}),
600
+ });
601
+ const lines = [...(createdHere ? [`Your identity: ${r.address}`] : [r.created ? `Created ${r.address}` : `Already set up: ${r.address}`]), ` relays ${r.relays.join(", ")}`];
315
602
  if (r.backup?.file) {
316
603
  lines.push(` backup saved to ${r.backup.file}`);
317
604
  // review L4: the default file sits next to the key it backs up.
@@ -319,14 +606,34 @@ export function buildProgram(deps) {
319
606
  }
320
607
  if (r.backup?.phrase)
321
608
  lines.push(`\nWrite these 24 words down and keep them offline. Anyone with them is you:\n\n${r.backup.phrase}\n`);
322
- if (r.created && !r.backup)
323
- io.err("warning: no backup yet: if you lose this device, the identity is gone. Run `p2p backup show`.");
609
+ // Whenever this device is the only key holder and the phrase was never shown (not only just
610
+ // after creating it: a setup cut short at the question, or a join that failed after creating).
611
+ if (r.backupNeeded)
612
+ io.err(`warning: no backup yet: this device is the only one holding your identity key, so if you lose it, the identity is gone. Run \`${p2p} backup show\`.`);
613
+ // Ix is optional and recommended: offered to the person at a terminal (default No), never
614
+ // installed. Never with --json, in CI, without a terminal, or inside an agent's session.
615
+ const offerIx = r.ix !== undefined && !r.ix.found && r.ix.recommended && !o.json && Boolean(io.prompt || io.select) && !ixLocal.ciEnv(app.env) && projects.personHere(app);
324
616
  if (r.ix?.enabledNow)
325
617
  lines.push(" ix Ix found: the Ix extension is on (`p2p extensions disable ix` turns it off). Ix calls stay on this machine (graph: local only)");
326
618
  else if (r.ix?.enabled)
327
619
  lines.push(" ix the Ix extension is on (graph: local only)");
328
- else if (r.ix?.hint)
620
+ else if (r.ix?.hint && !offerIx)
329
621
  lines.push(` ix ${r.ix.hint}`);
622
+ if (offerIx) {
623
+ io.out(lines.join("\n"));
624
+ lines.length = 0;
625
+ const yes = await confirmPrompt(["", ...ixLocal.IX_PITCH, "Install Ix?"].join("\n"));
626
+ if (yes) {
627
+ if (ixLocal.ixDeclined(app.file))
628
+ ixLocal.setIxDeclined(app.home, false);
629
+ // Printed, never run: installing is the person's own action, in their own terminal.
630
+ lines.push("", "Peer2Peer doesn't run installers. To install Ix, run this in your terminal:", "", ...ixLocal.ixInstallCommands().map((c) => ` ${c}`), "", `(details: ${ixLocal.IX_INSTALL_URL}). Then run \`p2p setup --ix\` to turn on the Ix extension.`);
631
+ }
632
+ else {
633
+ ixLocal.setIxDeclined(app.home, true);
634
+ lines.push(" ix not installing Ix. You won't be asked again; `p2p setup --ix` offers it again");
635
+ }
636
+ }
330
637
  lines.push("", "Invite someone: p2p invite <their name> Join with a code: p2p join <code>");
331
638
  return { json: r, human: lines.join("\n") };
332
639
  },
@@ -393,8 +700,8 @@ export function buildProgram(deps) {
393
700
  }));
394
701
  for (const verb of ["add", "remove"]) {
395
702
  relays
396
- .command(`${verb} <url>`)
397
- .description(verb === "add" ? "Add a relay (1-5 in all)" : "Remove a relay (one must stay)")
703
+ .command(verb === "add" ? "add <url>" : "remove <url...>")
704
+ .description(verb === "add" ? "Add a relay (1-5 in all)" : "Remove one or more relays, in one new version (one must stay)")
398
705
  .option("--json", "JSON output")
399
706
  .action(run(async (app, url) => {
400
707
  const r = verb === "add" ? await ops.relaysAdd(app, url) : await ops.relaysRemove(app, url);
@@ -425,6 +732,7 @@ export function buildProgram(deps) {
425
732
  .option("--keep-keyholders", "Devices that held the old identity key also get the new one (default: they follow as ordinary devices)")
426
733
  .option("--wait <seconds>", "How long to wait for your other devices to follow (default 600, the link code's life)", posInt("--wait"))
427
734
  .option("--backup-file [path]", "Save the new key's 24-word backup phrase to a 0600 file (default <home>/backup-phrase-<fingerprint>.txt)")
735
+ .option("--branch <hash>", "Your identity is forked by a version that leaves this device out and more than one branch still lists it: the one that is yours (its jwsHash, as the error lists them)")
428
736
  .option("--contest", "On a key holder: answer a rotation of your identity this device didn't publish with a competing one, so your friends see a conflict and apply neither")
429
737
  .option("--resend", "After a rotation: send the new identity's invite again to the friends it didn't reach (throttled)")
430
738
  .option("-y, --yes", "Accept the plan without asking (scripts)")
@@ -461,7 +769,7 @@ export function buildProgram(deps) {
461
769
  human: `Sent your new identity's invite to ${fmt.plural(r.sent, "friend")}${r.failed.length ? `; ${r.failed.length} still not reached` : ""}${r.throttled ? ` (${r.remaining} wait for the relays' hourly limit: run it again later)` : ""}.`,
462
770
  };
463
771
  }
464
- const opts = { resume: o.resume, exclude: o.exclude, keep: o.keep, invite: o.invite, keepKeyholders: o.keepKeyholders, contest: o.contest, ...backup };
772
+ const opts = { resume: o.resume, exclude: o.exclude, keep: o.keep, invite: o.invite, keepKeyholders: o.keepKeyholders, branch: o.branch, contest: o.contest, ...backup };
465
773
  if (o.plan) {
466
774
  const plan = await ops.rotatePlan(app, opts);
467
775
  return { json: { plan: true, ...plan }, human: `${fmt.formatRotationPlan(plan)}\nAccept it with \`p2p identity rotate --resume\` (add --exclude <did> to drop a device), or drop it with --cancel.` };
@@ -544,14 +852,36 @@ export function buildProgram(deps) {
544
852
  .description("On the new device: join with the code the other device shows")
545
853
  .option("--label <label>", "A name for this device")
546
854
  .option("--rotated", "This device's identity was rotated while it was offline: re-link it to the new identity (§2.8)")
855
+ .option("--expect-fingerprint <fingerprint>", "Proceed only if the identity is this one (for scripts; `p2p whoami` on the other device shows it); otherwise you confirm it on your terminal")
856
+ .option("--allow-private-relay", "Accept a code whose relay is a loopback, link-local or private address (your own relay on your network; also P2P_ALLOW_PRIVATE_RELAY=1)")
547
857
  .option("--json", "JSON output")
548
858
  .action(run(async (app, code, o) => {
549
- const j = o.rotated ? await ops.relinkRotated(app, code, { label: o.label }) : await ops.linkJoin(app, code, { label: o.label });
859
+ if (o.rotated) {
860
+ const j = await ops.relinkRotated(app, code, { label: o.label });
861
+ if (o.json)
862
+ io.err(JSON.stringify({ compareCode: j.compareCode, did: j.did }));
863
+ else
864
+ io.out(`Compare code: ${j.compareCode}\nCheck the other device shows the same code, and confirm there. Waiting…`);
865
+ const r = await j.wait();
866
+ return { json: r, human: `This device is now ${r.address} (${r.did})${r.keyholder ? ", a key holder" : ""}.` };
867
+ }
868
+ const j = await ops.linkJoin(app, code, { label: o.label, ...(o.allowPrivateRelay ? { allowPrivateRelay: true } : {}) });
550
869
  if (o.json)
551
870
  io.err(JSON.stringify({ compareCode: j.compareCode, did: j.did }));
552
871
  else
553
872
  io.out(`Compare code: ${j.compareCode}\nCheck the other device shows the same code, and confirm there. Waiting…`);
554
- const r = await j.wait();
873
+ // Which identity this device becomes is the person's to confirm (a code from someone else
874
+ // makes it theirs): on their own terminal, or the fingerprint a script expects.
875
+ const expect = o.expectFingerprint?.trim().toLowerCase();
876
+ const r = await j.wait(expect !== undefined
877
+ ? async (who) => {
878
+ const ok = who.fingerprint.toLowerCase() === expect;
879
+ // At a terminal, the identity is still said (on stderr; nothing is asked: scripts stay non-interactive).
880
+ if (deps.io.prompt)
881
+ io.err(`This device would become ${who.address} (fingerprint ${who.fingerprint})${who.keyholder ? ", a key holder" : ""}: ${ok ? "it matches" : "it does NOT match"} --expect-fingerprint.`);
882
+ return ok;
883
+ }
884
+ : confirmLinkIdentity(identity.p2pCommand()));
555
885
  return { json: r, human: `This device is now ${r.address} (${r.did})${r.keyholder ? ", a key holder" : ""}.` };
556
886
  },
557
887
  // Linking waits up to 10 minutes for the other device, by design.
@@ -732,26 +1062,20 @@ export function buildProgram(deps) {
732
1062
  return { userId: c.userId, address: c.address, relays: c.relays };
733
1063
  },
734
1064
  });
735
- const lines = [`You and ${r.friend.address} are friends${r.delivered && r.delivered.relays.length === 0 ? " (they'll know once the accept is delivered: run this again later)" : ""}.`];
736
- for (const c of r.circles) {
737
- if (c.status === "joined" || c.status === "already")
738
- lines.push(`${c.status === "joined" ? "Joined" : "Already in"} "${c.name}"${c.default ? "; it is your default circle (new sessions start in it; running ones stay as they are)" : ""}.`);
739
- else if (c.status === "pending")
740
- lines.push(`${r.friend.address} adds you to "${c.name}" when their client next runs; your next p2p command finishes the join.`);
741
- else if (c.status === "held")
742
- lines.push(`Not joined "${c.name}" from this code (${c.reason}): if its invite comes, \`p2p held\` lists it for you to approve on its own.`);
743
- else
744
- lines.push(`"${c.name}" couldn't be confirmed with a second member (§3.3): \`p2p held approve ${c.held}\` to join anyway.`);
745
- }
746
- return { json: r, human: lines.join("\n") };
1065
+ return { json: r, human: joinLines(r).join("\n") };
747
1066
  }, { requireIdentity: false, waitDefault: 15 }));
748
1067
  const invites = program
749
1068
  .command("invites")
750
1069
  .description("Your invite codes and what became of them; `invites revoke <code>` cancels one")
751
1070
  .option("--json", "JSON output")
752
1071
  .action(run(async (app) => {
753
- const r = await ops.listCodes(app);
754
- return { json: { invites: r }, human: fmt.formatCodes(r), pretty: (p) => pretty.prettyCodes(r, p) };
1072
+ const all = await ops.listCodes(app);
1073
+ // A live code (open, or taken and not yet joined) lets whoever holds it in: inside an agent's
1074
+ // session (or where that can't be told) without the person's token, it is cut as a redeemed
1075
+ // one is, in the JSON too. The status stays readable.
1076
+ const redacted = !projects.personHereStrict(app);
1077
+ const r = redacted ? all.map((c) => ({ ...c, code: fmt.shortCode(c.code), ...(c.status === "open" || c.status === "taken" ? { redacted: true } : {}) })) : all;
1078
+ return { json: { invites: r, ...(redacted ? { redacted: true } : {}) }, human: fmt.formatCodes(r), pretty: (p) => pretty.prettyCodes(r, p) };
755
1079
  }));
756
1080
  invites
757
1081
  .command("revoke [code]")
@@ -1399,7 +1723,7 @@ export function buildProgram(deps) {
1399
1723
  for (const p of v.people)
1400
1724
  lines.push(` ${p.address}`);
1401
1725
  if (v.graph)
1402
- lines.push(` graph: ${projects.describeGraphTarget(v.graph)}${v.graph.kind === "local" && v.graph.why ? `: ${v.graph.why}` : ""}`);
1726
+ lines.push(` graph: ${projects.graphTargetLine(v.graph)}`, ` (${projects.graphPlaintextNote(v.graph)})`);
1403
1727
  return lines.join("\n");
1404
1728
  };
1405
1729
  project
@@ -1748,10 +2072,26 @@ export async function main(argvIn, deps) {
1748
2072
  {
1749
2073
  // A copy without it (an embedder's object is left as it was); the process's own environment loses it too.
1750
2074
  const env = { ...deps.env };
1751
- const front = deps.front === true || projects.takePersonToken(env, resolveHome(env));
2075
+ const token = (env.P2P_PERSON_TOKEN ?? "").trim();
2076
+ const given = token !== "";
2077
+ const home = resolveHome(env);
2078
+ const byToken = projects.takePersonToken(env, home);
2079
+ const front = deps.front === true || byToken;
2080
+ const linked = given && !front && !projects.homeFilesOwn(home);
2081
+ if (given && !front && !linked)
2082
+ projects.healPersonToken(home);
1752
2083
  if (deps.env === process.env)
1753
2084
  delete process.env.P2P_PERSON_TOKEN;
1754
- deps = { ...deps, front, env };
2085
+ // A token that isn't this home's is refused outright, never quietly taken as "not the person": the
2086
+ // person.key it was read from was replaced when an identity was created or restored here
2087
+ // (projects.ts renewPersonToken), and the front end that passed it reads the file again.
2088
+ deps = {
2089
+ ...deps,
2090
+ front,
2091
+ env,
2092
+ ...(byToken && deps.front !== true ? { frontToken: token, frontFresh: !projects.identityHere(home) } : {}),
2093
+ ...(linked ? { personTokenLinked: true } : given && !front ? { personTokenStale: true } : {}),
2094
+ };
1755
2095
  }
1756
2096
  // `--no-input` anywhere before `--`: no pickers, no questions (as a script would run).
1757
2097
  const end = argvIn.indexOf("--");
package/dist/config.d.ts CHANGED
@@ -32,6 +32,11 @@ export interface FileConfig {
32
32
  };
33
33
  /** Graph memory (graph-memory.ts): this device's sessions' context into the local Ix graph; on by default with the Ix extension, `false` turns it off. P2P_IX_MEMORY=0 turns it off too. */
34
34
  ixMemory?: boolean;
35
+ /**
36
+ * The person said no to Ix when `p2p setup` recommended it (ix-local.ts): not asked again, and no
37
+ * agent hint. `p2p setup --ix` offers it again. Ix is optional; Peer2Peer never installs it.
38
+ */
39
+ ixDeclined?: boolean;
35
40
  /**
36
41
  * Messages from your own agent sessions skip the hold in a session that approves its own tool calls
37
42
  * (`p2p own-agents deliver`, person only). Off by default: they are held like a peer's. No variable