@peer2peer/cli 0.1.1 → 0.1.2

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";
@@ -123,6 +124,9 @@ export function buildProgram(deps) {
123
124
  const app = makeApp(deps.env, io, opts.readOnly ? { readOnly: true } : undefined);
124
125
  let stop = () => { };
125
126
  try {
127
+ if (deps.personTokenStale) {
128
+ 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)`);
129
+ }
126
130
  // §2.8 (L4): a follow that died mid-swap finishes before anything reads this home (not for a
127
131
  // read-only command, which must leave the home exactly as it found it).
128
132
  if (typeof app.home === "string" && !opts.readOnly)
@@ -130,7 +134,7 @@ export function buildProgram(deps) {
130
134
  // An agent can't widen who reaches this user, however it runs p2p (projects.ts).
131
135
  const widening = wideningOf(cmd);
132
136
  if (widening)
133
- await projects.assertPersonForWidening(app, widening, confirmTty);
137
+ await projects.assertPersonForWidening(app, widening, confirmTty, undefined, { noTokenBeforeIdentity: widening === "link join" });
134
138
  if (opts.requireIdentity !== false)
135
139
  await app.load(true);
136
140
  // The person token the person's front ends pass back (projects.ts), made once, in the CLI's own folder.
@@ -188,7 +192,7 @@ export function buildProgram(deps) {
188
192
  deps.io.out(pretty.safePretty(out.pretty(deps.io.pretty)));
189
193
  else if (out.human)
190
194
  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).
195
+ // Ix is optional: new installs are offered it; an existing one hears it once, at a terminal, from the person (ix-local.ts).
192
196
  if (!json && !opts.readOnly && app.keys && deps.io.prompt && projects.personHere(app) && cmd.name() !== "setup") {
193
197
  const n = await ixLocal.ixNotice(app).catch(() => undefined);
194
198
  if (n)
@@ -254,6 +258,115 @@ export function buildProgram(deps) {
254
258
  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
259
  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
260
  const heldChoices = async (app) => (await ops.listHeld(app)).map((h) => ({ value: h.id, label: `${h.address}: ${h.summary}`, detail: h.type }));
261
+ /** What `p2p join` says it did (setup's invite path says the same). */
262
+ const joinLines = (r) => {
263
+ 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)" : ""}.`];
264
+ for (const c of r.circles) {
265
+ if (c.status === "joined" || c.status === "already")
266
+ 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)" : ""}.`);
267
+ else if (c.status === "pending")
268
+ lines.push(`${r.friend.address} adds you to "${c.name}" when their client next runs; your next p2p command finishes the join.`);
269
+ else if (c.status === "held")
270
+ 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.`);
271
+ else
272
+ lines.push(`"${c.name}" couldn't be confirmed with a second member (§3.3): \`p2p held approve ${c.held}\` to join anyway.`);
273
+ }
274
+ return lines;
275
+ };
276
+ // ── setup's questions (a person at a terminal only: io.prompt) ──
277
+ /** One of `letters`, asked at most three times; then nothing is done. */
278
+ const askLetter = async (q, letters) => {
279
+ for (let i = 0; i < 3; i++) {
280
+ const a = (await io.prompt(q)).trim().toLowerCase();
281
+ if (letters.includes(a))
282
+ return a;
283
+ io.err(`Type ${letters.slice(0, -1).join(", ")} or ${letters[letters.length - 1]}.`);
284
+ }
285
+ throw new CliError("cancelled", "cancelled: nothing was done (run `p2p setup` again)");
286
+ };
287
+ const askNonEmpty = async (q, what) => {
288
+ for (let i = 0; i < 3; i++) {
289
+ const a = (await io.prompt(q)).trim();
290
+ if (a !== "")
291
+ return a;
292
+ io.err(`Type ${what}, or press Ctrl-C to stop.`);
293
+ }
294
+ throw new CliError("cancelled", "cancelled: nothing was done (run `p2p setup` again)");
295
+ };
296
+ /** How a person with no identity here is joining (setup): before any key is made. */
297
+ const askJoinPath = async (p2p) => {
298
+ io.out([
299
+ "How are you joining Peer2Peer?",
300
+ " [l] I already use Peer2Peer on another device: link this device to it",
301
+ " [i] I have an invite link or code from someone",
302
+ " [n] Start a new identity (my first device)",
303
+ `(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.)`,
304
+ ].join("\n"));
305
+ const a = await askLetter("Choose l, i or n: ", ["l", "i", "n"]);
306
+ return a === "l" ? "link" : a === "i" ? "invite" : "new";
307
+ };
308
+ /** The group's relay for a new identity (no default relay: bring your own), as a canonical wss:// URL. */
309
+ const askRelay = async () => {
310
+ io.out("\nPeer2Peer has no default relay: each group runs its own. Ask whoever runs yours for its address (wss://…).");
311
+ for (let i = 0; i < 3; i++) {
312
+ let a = (await io.prompt("Relay URL (wss://…): ")).trim();
313
+ // A bare host means wss:// (the only scheme a relay URL has); any other scheme is refused.
314
+ if (a !== "" && !/^[a-z][a-z0-9+.-]*:\/\//i.test(a))
315
+ a = `wss://${a}`;
316
+ if (!/^wss:\/\//i.test(a)) {
317
+ io.err(a === "" ? "Type the relay's address (wss://…)." : "A relay URL starts with wss:// (ws://, http:// and https:// aren't relay URLs).");
318
+ continue;
319
+ }
320
+ try {
321
+ return normalizeRelays([a])[0];
322
+ }
323
+ catch (e) {
324
+ io.err(e instanceof CliError ? String(e.message) : `${a} is not a relay URL`);
325
+ }
326
+ }
327
+ throw new CliError("cancelled", "cancelled: nothing was done (run `p2p setup --relay wss://…` again)");
328
+ };
329
+ const isLinkCode = (s) => /^p2p-link:/i.test(s.trim());
330
+ const looksLikeInvite = (s) => {
331
+ try {
332
+ parseShortCode(s, { allowPrivate: true });
333
+ return true;
334
+ }
335
+ catch {
336
+ return false;
337
+ }
338
+ };
339
+ /**
340
+ * The person's yes, on their own terminal, to the identity a link code makes this device part of
341
+ * (`link join` and setup's link path): nothing is kept before it.
342
+ */
343
+ 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.`);
344
+ /** setup, "I already use Peer2Peer on another device": `p2p link join`, inline. No identity is made here, so no backup is asked. */
345
+ const setupByLink = async (app, p2p, o) => {
346
+ await projects.assertPersonForWidening(app, "link join", confirmTty, undefined, { noTokenBeforeIdentity: true });
347
+ io.out([
348
+ "",
349
+ "Link this device to the identity you already have:",
350
+ " 1. On your other device run: p2p link start",
351
+ " (Windows PowerShell: p2p.cmd link start; in Claude Code: /peers link start)",
352
+ " 2. It shows a one-time link code (p2p-link:…). Type it here.",
353
+ "Only type a code shown on YOUR OWN other device. A code from anyone else makes this device theirs.",
354
+ ...(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.)`] : []),
355
+ ].join("\n"));
356
+ const code = await askNonEmpty("Link code: ", "the link code");
357
+ // An invite pasted here (someone else's): it is joined as an invite, with its own confirmation.
358
+ if (!isLinkCode(code) && looksLikeInvite(code)) {
359
+ 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).");
360
+ return { invite: code };
361
+ }
362
+ const j = await ops.linkJoin(app, code, { ...(o.allowPrivateRelay ? { allowPrivateRelay: true } : {}) });
363
+ io.out(`Compare code: ${j.compareCode}\nCheck the other device shows the same code, and confirm there. Waiting…`);
364
+ const r = await j.wait(confirmLinkIdentity(p2p));
365
+ return {
366
+ json: { linked: r },
367
+ 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"),
368
+ };
369
+ };
257
370
  // ── identity ──────────────────────────────────────────────────────────────
258
371
  program
259
372
  .command("init")
@@ -295,23 +408,90 @@ export function buildProgram(deps) {
295
408
  }, { requireIdentity: false }));
296
409
  program
297
410
  .command("setup")
298
- .description("Get started: create your identity with sensible defaults (safe to run again)")
411
+ .description("Get started: link this device to your identity, join with an invite, or create a new identity (safe to run again)")
299
412
  .option("--name <name>", "Your display name (default: your OS user name)")
300
413
  .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
414
  .option("--backup-file [path]", "Save the 24-word backup phrase to a 0600 file (default <home>/backup-phrase.txt)")
302
415
  .option("--print-backup", "Print the backup phrase (in --json, as backup.phrase)")
303
416
  .option("--no-backup", "Don't save or print the backup phrase now")
417
+ .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")
418
+ .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
419
  .option("--json", "JSON output")
305
420
  .action(run(async (app, o) => {
306
421
  let mode = o.backupFile !== undefined ? "file" : o.printBackup ? "print" : o.backup === false ? "none" : undefined;
307
422
  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)");
423
+ const p2p = identity.p2pCommand();
424
+ // Asked only once an identity exists here (its key was just made): never before.
425
+ const askBackup = async () => {
426
+ 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
427
  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(", ")}`];
428
+ return a === "p" ? "print" : a === "s" ? "none" : "file";
429
+ };
430
+ // A person at a terminal with no identity here says how they're joining first, before any key
431
+ // is made: someone who already has an identity links this device to it instead of making a
432
+ // second one. Never with --json, in CI, without a terminal, or inside an agent's session.
433
+ const asking = !existed && !o.json && Boolean(io.prompt) && !ixLocal.ciEnv(app.env) && projects.personHere(app);
434
+ let how = asking ? await askJoinPath(p2p) : "new";
435
+ let inviteCode;
436
+ if (how === "link") {
437
+ const ignored = [
438
+ ...(o.name !== undefined ? ["--name"] : []),
439
+ ...(o.relay && o.relay.length > 0 ? ["--relay"] : []),
440
+ ...(o.backupFile !== undefined ? ["--backup-file"] : []),
441
+ ...(o.printBackup ? ["--print-backup"] : []),
442
+ ];
443
+ const l = await setupByLink(app, p2p, { allowPrivateRelay: o.allowPrivateRelay, ignored });
444
+ if (!("invite" in l))
445
+ return l;
446
+ how = "invite";
447
+ inviteCode = l.invite;
448
+ }
449
+ let createdHere = false;
450
+ if (how === "invite") {
451
+ await projects.assertPersonForWidening(app, "join", confirmTty, undefined, { noTokenBeforeIdentity: true });
452
+ if (inviteCode === undefined)
453
+ io.out("\nPaste the invite link (https://…/p2p/invite#…) or the code you were sent. It carries the relays your inviter uses.");
454
+ const code = inviteCode ?? (await askNonEmpty("Invite link or code: ", "an invite link or code"));
455
+ if (isLinkCode(code)) {
456
+ 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`);
457
+ }
458
+ const j = await ops.joinCode(app, code, {
459
+ name: o.name,
460
+ ...(o.allowPrivateRelay ? { allowPrivateRelay: true } : {}),
461
+ confirm: (q) => confirmPrompt(q, false, ["Join", "Cancel"]),
462
+ create: async (a, x) => {
463
+ const c = await ops.init(a, x);
464
+ receiving(a);
465
+ createdHere = true;
466
+ io.out(`Created ${c.address}`);
467
+ io.err(`Only this device holds your identity key: save a backup with \`${p2p} backup show\` (setup asks next).`);
468
+ return { userId: c.userId, address: c.address, relays: c.relays };
469
+ },
470
+ });
471
+ io.out(joinLines(j).join("\n"));
472
+ if (createdHere && mode === undefined)
473
+ mode = await askBackup();
474
+ }
475
+ let relays = o.relay;
476
+ // There is no default relay (bring your own): a new identity starts on the group's relay.
477
+ if (how === "new" && asking && !(relays && relays.length > 0) && defaultRelays(app.env, app.file).length === 0)
478
+ relays = [await askRelay()];
479
+ const chooseBackup = how === "new" && mode === undefined && !o.json && io.prompt
480
+ ? async (c) => {
481
+ createdHere = true;
482
+ io.out(`Created ${c.address}`);
483
+ return askBackup();
484
+ }
485
+ : undefined;
486
+ const r = await ops.setup(app, {
487
+ name: o.name,
488
+ relays,
489
+ backup: mode,
490
+ ...(typeof o.backupFile === "string" ? { backupFile: o.backupFile } : {}),
491
+ ...(o.ix ? { ix: true } : {}),
492
+ ...(chooseBackup ? { chooseBackup } : {}),
493
+ });
494
+ const lines = [...(createdHere ? [`Your identity: ${r.address}`] : [r.created ? `Created ${r.address}` : `Already set up: ${r.address}`]), ` relays ${r.relays.join(", ")}`];
315
495
  if (r.backup?.file) {
316
496
  lines.push(` backup saved to ${r.backup.file}`);
317
497
  // review L4: the default file sits next to the key it backs up.
@@ -319,14 +499,34 @@ export function buildProgram(deps) {
319
499
  }
320
500
  if (r.backup?.phrase)
321
501
  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`.");
502
+ // Whenever this device is the only key holder and the phrase was never shown (not only just
503
+ // after creating it: a setup cut short at the question, or a join that failed after creating).
504
+ if (r.backupNeeded)
505
+ 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\`.`);
506
+ // Ix is optional and recommended: offered to the person at a terminal (default No), never
507
+ // installed. Never with --json, in CI, without a terminal, or inside an agent's session.
508
+ 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
509
  if (r.ix?.enabledNow)
325
510
  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
511
  else if (r.ix?.enabled)
327
512
  lines.push(" ix the Ix extension is on (graph: local only)");
328
- else if (r.ix?.hint)
513
+ else if (r.ix?.hint && !offerIx)
329
514
  lines.push(` ix ${r.ix.hint}`);
515
+ if (offerIx) {
516
+ io.out(lines.join("\n"));
517
+ lines.length = 0;
518
+ const yes = await confirmPrompt(["", ...ixLocal.IX_PITCH, "Install Ix?"].join("\n"));
519
+ if (yes) {
520
+ if (ixLocal.ixDeclined(app.file))
521
+ ixLocal.setIxDeclined(app.home, false);
522
+ // Printed, never run: installing is the person's own action, in their own terminal.
523
+ 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.`);
524
+ }
525
+ else {
526
+ ixLocal.setIxDeclined(app.home, true);
527
+ lines.push(" ix not installing Ix. You won't be asked again; `p2p setup --ix` offers it again");
528
+ }
529
+ }
330
530
  lines.push("", "Invite someone: p2p invite <their name> Join with a code: p2p join <code>");
331
531
  return { json: r, human: lines.join("\n") };
332
532
  },
@@ -544,14 +744,36 @@ export function buildProgram(deps) {
544
744
  .description("On the new device: join with the code the other device shows")
545
745
  .option("--label <label>", "A name for this device")
546
746
  .option("--rotated", "This device's identity was rotated while it was offline: re-link it to the new identity (§2.8)")
747
+ .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")
748
+ .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
749
  .option("--json", "JSON output")
548
750
  .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 });
751
+ if (o.rotated) {
752
+ const j = await ops.relinkRotated(app, code, { label: o.label });
753
+ if (o.json)
754
+ io.err(JSON.stringify({ compareCode: j.compareCode, did: j.did }));
755
+ else
756
+ io.out(`Compare code: ${j.compareCode}\nCheck the other device shows the same code, and confirm there. Waiting…`);
757
+ const r = await j.wait();
758
+ return { json: r, human: `This device is now ${r.address} (${r.did})${r.keyholder ? ", a key holder" : ""}.` };
759
+ }
760
+ const j = await ops.linkJoin(app, code, { label: o.label, ...(o.allowPrivateRelay ? { allowPrivateRelay: true } : {}) });
550
761
  if (o.json)
551
762
  io.err(JSON.stringify({ compareCode: j.compareCode, did: j.did }));
552
763
  else
553
764
  io.out(`Compare code: ${j.compareCode}\nCheck the other device shows the same code, and confirm there. Waiting…`);
554
- const r = await j.wait();
765
+ // Which identity this device becomes is the person's to confirm (a code from someone else
766
+ // makes it theirs): on their own terminal, or the fingerprint a script expects.
767
+ const expect = o.expectFingerprint?.trim().toLowerCase();
768
+ const r = await j.wait(expect !== undefined
769
+ ? async (who) => {
770
+ const ok = who.fingerprint.toLowerCase() === expect;
771
+ // At a terminal, the identity is still said (on stderr; nothing is asked: scripts stay non-interactive).
772
+ if (deps.io.prompt)
773
+ 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.`);
774
+ return ok;
775
+ }
776
+ : confirmLinkIdentity(identity.p2pCommand()));
555
777
  return { json: r, human: `This device is now ${r.address} (${r.did})${r.keyholder ? ", a key holder" : ""}.` };
556
778
  },
557
779
  // Linking waits up to 10 minutes for the other device, by design.
@@ -732,18 +954,7 @@ export function buildProgram(deps) {
732
954
  return { userId: c.userId, address: c.address, relays: c.relays };
733
955
  },
734
956
  });
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") };
957
+ return { json: r, human: joinLines(r).join("\n") };
747
958
  }, { requireIdentity: false, waitDefault: 15 }));
748
959
  const invites = program
749
960
  .command("invites")
@@ -1399,7 +1610,7 @@ export function buildProgram(deps) {
1399
1610
  for (const p of v.people)
1400
1611
  lines.push(` ${p.address}`);
1401
1612
  if (v.graph)
1402
- lines.push(` graph: ${projects.describeGraphTarget(v.graph)}${v.graph.kind === "local" && v.graph.why ? `: ${v.graph.why}` : ""}`);
1613
+ lines.push(` graph: ${projects.graphTargetLine(v.graph)}`, ` (${projects.graphPlaintextNote(v.graph)})`);
1403
1614
  return lines.join("\n");
1404
1615
  };
1405
1616
  project
@@ -1748,10 +1959,14 @@ export async function main(argvIn, deps) {
1748
1959
  {
1749
1960
  // A copy without it (an embedder's object is left as it was); the process's own environment loses it too.
1750
1961
  const env = { ...deps.env };
1962
+ const given = (env.P2P_PERSON_TOKEN ?? "").trim() !== "";
1751
1963
  const front = deps.front === true || projects.takePersonToken(env, resolveHome(env));
1752
1964
  if (deps.env === process.env)
1753
1965
  delete process.env.P2P_PERSON_TOKEN;
1754
- deps = { ...deps, front, env };
1966
+ // A token that isn't this home's is refused outright, never quietly taken as "not the person": the
1967
+ // person.key it was read from was replaced when an identity was created or restored here
1968
+ // (projects.ts renewPersonToken), and the front end that passed it reads the file again.
1969
+ deps = { ...deps, front, env, ...(given && !front ? { personTokenStale: true } : {}) };
1755
1970
  }
1756
1971
  // `--no-input` anywhere before `--`: no pickers, no questions (as a script would run).
1757
1972
  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
package/dist/doctor.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { App } from "./app.js";
2
2
  import { type PeerDevice } from "./features.js";
3
+ import { type GraphMemoryDoc } from "./graph-memory.js";
4
+ import { type GraphTarget } from "./projects.js";
3
5
  export type CheckStatus = "ok" | "fail" | "unknown";
4
6
  export interface Check {
5
7
  id: string;
@@ -30,6 +32,61 @@ export interface DoctorResult {
30
32
  theyLack: string[];
31
33
  weLack: string[];
32
34
  };
35
+ /** This device: where each kind of data goes ("Where your data goes"). */
36
+ dataFlow?: DataFlow;
37
+ }
38
+ /** The threat model, which lists everything a relay sees. */
39
+ export declare const THREAT_MODEL_DOC = "docs/security/threat-model.md";
40
+ /** What is encrypted and what isn't, on one page. */
41
+ export declare const ENCRYPTION_DOC = "docs/security/encryption.md";
42
+ /**
43
+ * Some of what a relay sees besides an envelope's ciphertext (the threat model, "What each party can
44
+ * see", has the full list): never read as complete.
45
+ */
46
+ export declare const RELAY_METADATA: readonly string[];
47
+ /**
48
+ * Where each kind of data goes, as `p2p doctor` says it for this device. Facts, not checks: the
49
+ * graph targets come from projects.ts (graphTarget's rule, the same as `p2p project show`).
50
+ */
51
+ export interface DataFlow {
52
+ /** Messages, statuses, receipts, rosters and Ix items shared with peers: end-to-end encrypted envelopes. */
53
+ wire: {
54
+ encryption: "end-to-end";
55
+ relaysSee: "ciphertext and metadata"; /** Some of it, not all: `doc` has the full list. */
56
+ metadata: readonly string[];
57
+ doc: string;
58
+ };
59
+ /** Message history (history.ts): never leaves this device; sealed at rest, with its key beside it. */
60
+ history: {
61
+ where: "this device only";
62
+ recording: boolean;
63
+ encryptedAtRest: true;
64
+ keyBesideIt: true;
65
+ eventLogPlaintextDays: number;
66
+ };
67
+ /**
68
+ * Graph memory (graph-memory.ts): on only with Ix, the Ix extension, and an Ix with a local `ix note`.
69
+ * `on` is "unknown" when the doctor couldn't tell (`ix --help` didn't answer in time): `p2p watch`
70
+ * may still be writing, and `detail` says what it wrote and queued so far.
71
+ */
72
+ graphMemory: {
73
+ on: boolean | "unknown";
74
+ detail: string;
75
+ };
76
+ /** Each project's graph target (the project here first), at most MAX_GRAPH_ROWS of them. */
77
+ graphs: {
78
+ id: string;
79
+ name: string;
80
+ here: boolean;
81
+ target: GraphTarget;
82
+ line: string;
83
+ plaintext: string;
84
+ }[];
85
+ /** Projects not listed past MAX_GRAPH_ROWS. */
86
+ graphsNotListed: number;
87
+ /** Whether any listed project's target is a shared (cloud) graph. None today: every target is local. */
88
+ anyShared: boolean;
89
+ doc: string;
33
90
  }
34
91
  export interface DoctorOptions {
35
92
  /** The CLI's own version (cli.ts VERSION). */
@@ -96,6 +153,8 @@ export declare function clockVerdict(skews: readonly {
96
153
  relay: string;
97
154
  sec: number;
98
155
  }[]): Check;
156
+ /** "Where your data goes" for this device (no probes: what the code does, and this device's settings). */
157
+ export declare function dataFlowOf(app: Pick<App, "env" | "home">, ix: Pick<DataFlow, "graphMemory" | "graphs" | "graphsNotListed">): DataFlow;
99
158
  /**
100
159
  * The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
101
160
  * whether the project here is mapped, and the graph target of the project here and of each project
@@ -103,11 +162,21 @@ export declare function clockVerdict(skews: readonly {
103
162
  * `ix` runs as ext-ix runs it (ix-local.ts): absolute path, allowlisted environment, the local
104
163
  * endpoint pinned, read-only commands, bounded.
105
164
  */
106
- export declare function ixChecks(c: Checks, app: App, ms: number): Promise<void>;
165
+ export declare function ixChecks(c: Checks, app: App, ms: number): Promise<Pick<DataFlow, "graphMemory" | "graphs" | "graphsNotListed">>;
166
+ /**
167
+ * Graph memory's state for "Where your data goes", from what Ix answered (`support`: undefined when it
168
+ * didn't in time) and what `p2p watch` recorded. Not knowing is "unknown", never "off": the watch
169
+ * asks Ix itself and may be writing.
170
+ */
171
+ export declare function graphMemoryState(support: "oss" | "pro" | "none" | undefined, doc: Pick<GraphMemoryDoc, "written" | "queue"> | undefined, endpoint: string): DataFlow["graphMemory"];
107
172
  export declare function summarize(checks: readonly Check[]): DoctorResult["summary"];
108
173
  /** The doctor's per-step bound: P2P_DOCTOR_TIMEOUT_MS (default 5 s), never more than the connect timeout. */
109
174
  export declare function doctorTimeoutMs(app: App, override?: number): number;
110
175
  export declare function doctor(app: App, o: DoctorOptions): Promise<DoctorResult>;
111
- /** Human output: one line per check (✓ ✗ ?), with its fix indented below. */
176
+ /** The heading of the data-flow section (pretty.ts styles it). */
177
+ export declare const DATA_FLOW_HEADING = "Where your data goes";
178
+ /** "Where your data goes", in plain words: one line per kind of data, then one per project's graph. */
179
+ export declare function formatDataFlow(d: DataFlow): string[];
180
+ /** Human output: one line per check (✓ ✗ ?), with its fix indented below, then where data goes. */
112
181
  export declare function formatDoctor(r: DoctorResult): string;
113
182
  export {};