@peer2peer/cli 0.1.2 → 0.1.4

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
@@ -28,8 +28,10 @@ import { receiving } from "./inbound.js";
28
28
  import * as rotation from "./rotation.js";
29
29
  import * as sessions from "./sessions.js";
30
30
  import * as projects from "./projects.js";
31
+ import * as keystore from "./keystore.js";
31
32
  import { isDid } from "@peer2peer/core/v3";
32
33
  import * as ixLocal from "./ix-local.js";
34
+ import * as sandbox from "./sandbox.js";
33
35
  import * as history from "./history.js";
34
36
  import { confirmOnTty } from "./tty-confirm.js";
35
37
  import * as social from "./social.js";
@@ -65,6 +67,92 @@ export function wideningOf(cmd) {
65
67
  }
66
68
  return undefined;
67
69
  }
70
+ /**
71
+ * Commands that touch the person's identity key, their identity document, or their own setup (or
72
+ * narrow who reaches them): run only by the person, through the same gate as widening (their
73
+ * front end's token, or their "yes" typed on their own terminal; never from inside an agent's
74
+ * session). The CLI decides by the command it parsed and its agent detection (environment and
75
+ * process ancestry), not by the command line's words: a name built at run time, or a script the
76
+ * agent wrote and runs in its own process tree, is refused like the plain command. It is not a
77
+ * boundary against an agent that runs as the same user and means to get past it: a process started
78
+ * outside the agent's tree that fakes a terminal can answer the "yes", and the key files can be
79
+ * read directly. That boundary is the OS sandbox's read and write deny on P2P_HOME
80
+ * (docs/security/threat-model.md). Internal maintenance (`p2p watch`
81
+ * renewing the document and certificates, the retry of unpublished relays on connect) calls the
82
+ * App directly, never these commands, and is not gated.
83
+ */
84
+ const PERSON_ONLY = new Map([
85
+ ["backup show", "shows your identity key (its backup phrase)"],
86
+ ["backup restore", "replaces this device's identity key"],
87
+ ["identity rotate", "moves your identity to a new key"],
88
+ ["identity republish", "publishes your identity document"],
89
+ ["identity dispute", "decides which identity a friend of yours is"],
90
+ ["devices revoke", "changes the devices your identity lists"],
91
+ ["relays add", "changes the relays your identity lists"],
92
+ ["relays remove", "changes the relays your identity lists"],
93
+ ["trust remove", "changes who you trust"],
94
+ ["invites revoke", "changes your invites"],
95
+ ["remove", "changes your friendships and circles"],
96
+ ["unfriend", "changes your friendships"],
97
+ ["circle propose", "changes a circle's members"],
98
+ ["circle transfer", "changes who owns a circle"],
99
+ ["circle hold", "changes how your circle takes changes"],
100
+ ["extensions disable", "changes which extensions run with your identity"],
101
+ ["ix import", "writes into your Ix graph"],
102
+ ["ix resolve", "runs your Ix for a peer's reference"],
103
+ ["ix config", "changes how your Ix footprints name files"],
104
+ ["receipts", "changes whether you send delivery receipts"],
105
+ ["profile set", "publishes a new version of your identity document"],
106
+ ["proof add", "publishes a new version of your identity document"],
107
+ ["block", "changes who reaches you"],
108
+ ["petname", "changes the names you know people by"],
109
+ ["circle leave", "changes your circles"],
110
+ ["held decline", "decides a held request for you"],
111
+ ["keys backend", "moves your identity and device keys"],
112
+ ]);
113
+ /** `identity rotate` options that do something beyond making or showing the plan. */
114
+ const ROTATE_ACTS = ["resume", "cancel", "exclude", "keep", "invite", "keepKeyholders", "backupFile", "contest", "resend", "yes", "branch"];
115
+ /**
116
+ * The person-only command `cmd` is ({what, why}), or undefined. Reads stay open: a bare
117
+ * `receipts`, `circle hold <cid>` and `ix config`, and a bare `identity rotate --plan` (it makes
118
+ * or shows the plan: the new fingerprint and which devices follow; nothing is published or
119
+ * revealed, and accepting it is gated).
120
+ */
121
+ export function personOnlyOf(cmd) {
122
+ const path = [];
123
+ for (let c = cmd; c && c.parent; c = c.parent)
124
+ path.unshift(c.name());
125
+ const p = path.join(" ");
126
+ const why = PERSON_ONLY.get(p);
127
+ if (why === undefined)
128
+ return undefined;
129
+ const args = cmd.args ?? [];
130
+ switch (p) {
131
+ case "receipts":
132
+ return args.length > 0 ? { what: args[0] === "on" || args[0] === "off" ? `receipts ${args[0]}` : "receipts", why } : undefined;
133
+ case "circle hold":
134
+ return args.length > 1 ? { what: args[1] === "on" || args[1] === "off" ? `circle hold <cid> ${args[1]}` : "circle hold", why } : undefined;
135
+ case "ix config":
136
+ return args.length > 0 ? { what: "ix config", why } : undefined;
137
+ // A bare `keys backend` only says where the keys are.
138
+ case "keys backend":
139
+ return args.length > 0 ? { what: `keys backend ${args[0] === "file" || args[0] === "keychain" ? args[0] : "<backend>"}`, why } : undefined;
140
+ // Restore runs only on a fresh home and needs the phrase itself, typed or piped: that is the
141
+ // person's proof outside an agent's session (a fresh home has no person token yet, and a
142
+ // headless restore must keep working). Inside an agent's session it is refused, as `link join`.
143
+ case "backup restore":
144
+ return { what: p, why, agentOnly: true };
145
+ case "identity rotate": {
146
+ const o = cmd.opts();
147
+ const acts = ROTATE_ACTS.filter((k) => o[k] !== undefined && o[k] !== false && !(Array.isArray(o[k]) && o[k].length === 0));
148
+ if (o.plan && acts.length === 0)
149
+ return undefined;
150
+ return { what: o.cancel ? "identity rotate --cancel" : o.plan ? "identity rotate --plan" : "identity rotate", why };
151
+ }
152
+ default:
153
+ return { what: p, why };
154
+ }
155
+ }
68
156
  const posInt = (name) => (v) => {
69
157
  const n = Number(v);
70
158
  if (!Number.isSafeInteger(n) || n < 0)
@@ -107,6 +195,10 @@ export function buildProgram(deps) {
107
195
  const app = baseMakeApp(env, i, o);
108
196
  app.extensions ??= extensions;
109
197
  app.front = deps.front === true;
198
+ if (app.front && deps.frontToken !== undefined) {
199
+ app.frontToken = deps.frontToken;
200
+ app.frontFresh = deps.frontFresh === true;
201
+ }
110
202
  app.confirmTty = confirmTty;
111
203
  return app;
112
204
  };
@@ -124,6 +216,9 @@ export function buildProgram(deps) {
124
216
  const app = makeApp(deps.env, io, opts.readOnly ? { readOnly: true } : undefined);
125
217
  let stop = () => { };
126
218
  try {
219
+ if (deps.personTokenLinked) {
220
+ 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`);
221
+ }
127
222
  if (deps.personTokenStale) {
128
223
  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
224
  }
@@ -131,10 +226,23 @@ export function buildProgram(deps) {
131
226
  // read-only command, which must leave the home exactly as it found it).
132
227
  if (typeof app.home === "string" && !opts.readOnly)
133
228
  await rotation.recoverInterruptedFollow(app.home).catch(() => false);
229
+ // The token was checked when the command started; the home may have changed since (an
230
+ // interrupted follow finished just now, or files swapped in by something else). Checked again
231
+ // as the home is now, before any gate: a home that had no identity then and has one now keeps
232
+ // no token. The keys the command loads are checked against it too (App.load).
233
+ if (app.front && app.frontToken !== undefined) {
234
+ const still = projects.personTokenOk({ P2P_PERSON_TOKEN: app.frontToken }, app.home);
235
+ if (!still || (app.frontFresh && projects.identityHere(app.home)))
236
+ app.front = false;
237
+ }
134
238
  // An agent can't widen who reaches this user, however it runs p2p (projects.ts).
135
239
  const widening = wideningOf(cmd);
136
240
  if (widening)
137
241
  await projects.assertPersonForWidening(app, widening, confirmTty, undefined, { noTokenBeforeIdentity: widening === "link join" });
242
+ // Nor touch the identity key, the identity document or the person's own setup (PERSON_ONLY).
243
+ const personOnly = personOnlyOf(cmd);
244
+ if (personOnly && !(personOnly.agentOnly && projects.personHereStrict(app)))
245
+ await projects.assertPersonForWidening(app, personOnly.what, confirmTty, personOnly.why);
138
246
  if (opts.requireIdentity !== false)
139
247
  await app.load(true);
140
248
  // The person token the person's front ends pass back (projects.ts), made once, in the CLI's own folder.
@@ -226,6 +334,16 @@ export function buildProgram(deps) {
226
334
  const a = (await io.prompt(`${q} [y/N] `)).trim().toLowerCase();
227
335
  return a === "y" || a === "yes";
228
336
  };
337
+ /** A question whose answer defaults to Yes (Enter): only ever for what tightens, such as the sandbox offer. */
338
+ /**
339
+ * The sandbox offer (sandbox.ts): every installed agent whose sandbox doesn't deny P2P_HOME and
340
+ * that the person hasn't said no for, each asked on its own with exactly what would be written.
341
+ * The caller has checked that the person is here (sandbox.assertPersonOutsideAgents) and can be asked.
342
+ */
343
+ const offerSandbox = async (env, home, reoffer = false) => {
344
+ const plans = sandbox.offerablePlans(env).filter((f) => reoffer || !sandbox.declinedHere(env, f.front));
345
+ return (await askEachAgent(io, env, home, plans, { from: "setup" })).lines;
346
+ };
229
347
  /** The command whose options `o` are (commander passes the same object it keeps). */
230
348
  const cmdOf = (o) => ({ opts: () => o });
231
349
  // ── pickers (prompt/): only with io.select, never with --json or --yes ──
@@ -415,11 +533,17 @@ export function buildProgram(deps) {
415
533
  .option("--print-backup", "Print the backup phrase (in --json, as backup.phrase)")
416
534
  .option("--no-backup", "Don't save or print the backup phrase now")
417
535
  .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")
536
+ .option("--sandbox", "Offer again to deny P2P_HOME to your agents' sandboxes (Claude Code, Codex) after an earlier no")
418
537
  .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)")
419
538
  .option("--json", "JSON output")
420
539
  .action(run(async (app, o) => {
421
540
  let mode = o.backupFile !== undefined ? "file" : o.printBackup ? "print" : o.backup === false ? "none" : undefined;
422
541
  const existed = await app.load(false);
542
+ // On a home that already holds an identity, setup's backup options reveal the existing key's
543
+ // phrase (`backup show`'s gate): the person's only. A new identity's own phrase is not.
544
+ if (existed && (o.printBackup || o.backupFile !== undefined)) {
545
+ await projects.assertPersonForWidening(app, o.printBackup ? "setup --print-backup" : "setup --backup-file", confirmTty, PERSON_ONLY.get("backup show"));
546
+ }
423
547
  const p2p = identity.p2pCommand();
424
548
  // Asked only once an identity exists here (its key was just made): never before.
425
549
  const askBackup = async () => {
@@ -527,11 +651,87 @@ export function buildProgram(deps) {
527
651
  lines.push(" ix not installing Ix. You won't be asked again; `p2p setup --ix` offers it again");
528
652
  }
529
653
  }
654
+ // The agents' sandboxes keep them out of P2P_HOME (sandbox.ts): offered once to the person at a
655
+ // terminal (default Yes), showing exactly what is written. Never with --json, in CI, without a
656
+ // terminal, from a front end, or inside an agent's session; a "no" is remembered.
657
+ const sandboxHere = (() => {
658
+ try {
659
+ sandbox.assertPersonOutsideAgents(app, "setup");
660
+ return true;
661
+ }
662
+ catch {
663
+ return false;
664
+ }
665
+ })();
666
+ if (!o.json && Boolean(io.prompt || io.select) && !ixLocal.ciEnv(app.env) && sandboxHere) {
667
+ io.out(lines.join("\n"));
668
+ lines.length = 0;
669
+ lines.push(...(await offerSandbox(app.env, app.home, o.sandbox === true)));
670
+ }
530
671
  lines.push("", "Invite someone: p2p invite <their name> Join with a code: p2p join <code>");
531
672
  return { json: r, human: lines.join("\n") };
532
673
  },
533
674
  // review L1: never cut short half-way through creating an identity (each step is still bounded).
534
675
  { requireIdentity: false, noDeadline: true }));
676
+ const sb = program
677
+ .command("sandbox")
678
+ .description("Whether your agents' sandboxes (Claude Code, Codex) keep them out of P2P_HOME; `sandbox enable` adds the deny to their config")
679
+ .option("--json", "JSON output")
680
+ .action(run(async (app) => {
681
+ const r = sandbox.sandboxReport(app.env);
682
+ return { json: r, human: sandbox.sandboxHuman(r, projects.personHere(app)) };
683
+ }, { requireIdentity: false, readOnly: true }));
684
+ sb.command("enable")
685
+ .description("Add the deny on P2P_HOME to your Claude Code settings and Codex config.toml (shows the changes and asks first; backs each file up)")
686
+ .option("--claude", "Only Claude Code (~/.claude/settings.json, or $CLAUDE_CONFIG_DIR), even if it isn't set up yet")
687
+ .option("--codex", "Only Codex (config.toml in CODEX_HOME, else ~/.codex), even if it isn't set up yet")
688
+ .option("--yes", "Don't ask (in your own terminal or a script of yours; never inside an agent's session)")
689
+ .option("--json", "JSON output (needs --yes)")
690
+ .action(run(async (app, o) => {
691
+ sandbox.assertPersonOutsideAgents(app, "sandbox enable");
692
+ const only = o.claude || o.codex ? [...(o.claude ? ["claude"] : []), ...(o.codex ? ["codex"] : [])] : undefined;
693
+ const planOpts = o.codexBase ? { codexBase: o.codexBase === "workspace" ? ":workspace" : ":read-only" } : {};
694
+ const fronts = (only ?? ["claude", "codex"]).map((f) => sandbox.planFront(f, app.env, planOpts)).filter((f) => only !== undefined || f.present);
695
+ const name = (f) => (f.front === "claude" ? "Claude Code" : "Codex");
696
+ const lines = [];
697
+ if (fronts.length === 0) {
698
+ lines.push(`Neither Claude Code (${sandbox.claudeSettingsPath(app.env)}) nor Codex (${sandbox.codexConfigPath(app.env)}) is set up here: nothing to change. --claude or --codex writes the config anyway.`);
699
+ }
700
+ for (const f of fronts) {
701
+ if (f.plan.kind === "already")
702
+ lines.push(`${name(f)}: already denies P2P_HOME (${f.path})`);
703
+ else if (f.plan.kind === "unavailable")
704
+ lines.push(`${name(f)}: ${f.status.detail}`);
705
+ else if (f.plan.kind === "manual")
706
+ lines.push(`${name(f)}: not changed: ${f.plan.reason}.${f.plan.snippet ? ` Add this to ${f.path} yourself:\n\n${f.plan.snippet}\n` : ""}`);
707
+ }
708
+ const edits = fronts.filter((f) => f.plan.kind === "edit");
709
+ let written = [];
710
+ if (edits.length > 0) {
711
+ // Windows has no process-tree check (agent detection fails open there): the person's answer at a terminal is required.
712
+ if (o.yes && process.platform === "win32")
713
+ throw new CliError("usage", "nothing was changed: on Windows, run `p2p sandbox enable` at your terminal without --yes and answer the question");
714
+ if (!o.yes && (o.json || !(io.prompt || io.select))) {
715
+ throw new CliError("usage", "nothing was changed: run `p2p sandbox enable` at your terminal to see the changes and be asked, or add --yes");
716
+ }
717
+ const res = await askEachAgent(io, app.env, app.home, edits, { yes: o.yes === true, from: "enable" });
718
+ written = res.written;
719
+ lines.push(...res.lines);
720
+ }
721
+ return {
722
+ json: { written, fronts: fronts.map((f) => ({ front: f.front, path: f.path, plan: f.plan.kind, ...(f.plan.kind === "manual" ? { reason: f.plan.reason } : {}) })) },
723
+ human: lines.join("\n"),
724
+ };
725
+ }, { requireIdentity: false, noDeadline: true }));
726
+ sb.commands.find((c) => c.name() === "enable")?.addOption(new Option("--codex-base <base>", "When your Codex config sets no sandbox: what the new profile extends (read-only, the default, or workspace)").choices(["read-only", "workspace"]));
727
+ sb.command("notice")
728
+ .description("For a front end: the one-time notice for its person when its agent's sandbox doesn't deny P2P_HOME")
729
+ .option("--front <name>", "claude or codex", "claude")
730
+ .option("--json", "JSON output")
731
+ .action(run(async (app, o) => {
732
+ const notice = await sandbox.sandboxNotice(app, o.front === "codex" ? "codex" : "claude").catch(() => undefined);
733
+ return { json: notice ? { notice } : {}, human: notice ?? "" };
734
+ }, { requireIdentity: false }));
535
735
  program
536
736
  .command("whoami")
537
737
  .description("Your address, fingerprint, devices, relays and document expiry")
@@ -540,6 +740,44 @@ export function buildProgram(deps) {
540
740
  const r = await ops.whoami(app);
541
741
  return { json: r, human: fmt.formatWhoami(r) };
542
742
  }));
743
+ const keys = program.command("keys").description("Where this device's secret keys are kept: files in P2P_HOME (the default) or the OS keychain");
744
+ keys
745
+ .command("backend [backend]")
746
+ .description("Show where this device's keys are kept; `keychain` moves them into the OS keychain, `file` back into P2P_HOME (only you, never an agent)")
747
+ .option("--json", "JSON output")
748
+ .addHelpText("after", [
749
+ "",
750
+ "keychain: the macOS Keychain, the Windows Credential Manager, or the Secret Service keyring (libsecret's",
751
+ "secret-tool) on Linux. The keys are stored, read back and compared before keys.json loses them; a move that",
752
+ "was interrupted finishes when run again. If the keychain can't be read later (locked, its tool missing),",
753
+ "commands that need the keys stop with an error: p2p never makes new keys in their place.",
754
+ ].join("\n"))
755
+ .action(run(async (app, backend) => {
756
+ if (backend !== undefined && backend !== "keychain" && backend !== "file")
757
+ throw new CliError("usage", "p2p keys backend [keychain|file]");
758
+ const say = (s) => {
759
+ const where = s.keys === "keychain" ? `${s.keychain.label} (item ${s.item?.service}, account ${s.item?.account})` : s.keys === "file" ? `${app.home}/cli/keys.json (0600)` : "nowhere yet (no identity here)";
760
+ const lines = [`Keys: ${where}${s.keys !== "none" ? (s.readable ? ", readable" : ", NOT readable") : ""}.`, `New keys go to: ${s.configured === "keychain" ? s.keychain.label : "files in P2P_HOME"}.`];
761
+ if (s.problem)
762
+ lines.push(`Problem: ${s.problem}`);
763
+ if (s.configured === "file")
764
+ lines.push(s.keychain.available ? `To keep them in ${s.keychain.label}: \`p2p keys backend keychain\`.` : `${s.keychain.label} isn't available here: ${s.keychain.why}.`);
765
+ return lines.join("\n");
766
+ };
767
+ if (backend === undefined) {
768
+ const s = keystore.keyStoreStatus(app.home);
769
+ return { json: s, human: say(s) };
770
+ }
771
+ const r = backend === "keychain" ? await keystore.moveKeysToKeychain(app.state.keyStore) : await keystore.moveKeysToFiles(app.state.keyStore);
772
+ for (const w of r.warnings)
773
+ app.warn(w);
774
+ const s = keystore.keyStoreStatus(app.home);
775
+ const head = r.moved ? `Moved this device's keys to ${r.where}.` : `Keys are kept in ${r.where}.`;
776
+ const note = backend === "keychain"
777
+ ? "\nNote: an agent sandbox that denies P2P_HOME doesn't cover the keychain. Anything running as you (an agent too) can ask it for the keys, and can delete or overwrite the item: on a key holder that can destroy the only copy of your identity key, and only your backup phrase brings it back. Have it saved first (`p2p backup show`). See docs/security/threat-model.md, \"Keys in the OS keychain\"."
778
+ : "";
779
+ return { json: { ...r, status: s }, human: `${head}\n${say(s)}${note}` };
780
+ }, { requireIdentity: false }));
543
781
  const backup = program.command("backup").description("The 24-word backup phrase of your identity key (§2.7)");
544
782
  backup
545
783
  .command("show")
@@ -593,8 +831,8 @@ export function buildProgram(deps) {
593
831
  }));
594
832
  for (const verb of ["add", "remove"]) {
595
833
  relays
596
- .command(`${verb} <url>`)
597
- .description(verb === "add" ? "Add a relay (1-5 in all)" : "Remove a relay (one must stay)")
834
+ .command(verb === "add" ? "add <url>" : "remove <url...>")
835
+ .description(verb === "add" ? "Add a relay (1-5 in all)" : "Remove one or more relays, in one new version (one must stay)")
598
836
  .option("--json", "JSON output")
599
837
  .action(run(async (app, url) => {
600
838
  const r = verb === "add" ? await ops.relaysAdd(app, url) : await ops.relaysRemove(app, url);
@@ -625,6 +863,7 @@ export function buildProgram(deps) {
625
863
  .option("--keep-keyholders", "Devices that held the old identity key also get the new one (default: they follow as ordinary devices)")
626
864
  .option("--wait <seconds>", "How long to wait for your other devices to follow (default 600, the link code's life)", posInt("--wait"))
627
865
  .option("--backup-file [path]", "Save the new key's 24-word backup phrase to a 0600 file (default <home>/backup-phrase-<fingerprint>.txt)")
866
+ .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)")
628
867
  .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")
629
868
  .option("--resend", "After a rotation: send the new identity's invite again to the friends it didn't reach (throttled)")
630
869
  .option("-y, --yes", "Accept the plan without asking (scripts)")
@@ -661,7 +900,7 @@ export function buildProgram(deps) {
661
900
  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)` : ""}.`,
662
901
  };
663
902
  }
664
- const opts = { resume: o.resume, exclude: o.exclude, keep: o.keep, invite: o.invite, keepKeyholders: o.keepKeyholders, contest: o.contest, ...backup };
903
+ const opts = { resume: o.resume, exclude: o.exclude, keep: o.keep, invite: o.invite, keepKeyholders: o.keepKeyholders, branch: o.branch, contest: o.contest, ...backup };
665
904
  if (o.plan) {
666
905
  const plan = await ops.rotatePlan(app, opts);
667
906
  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.` };
@@ -961,8 +1200,13 @@ export function buildProgram(deps) {
961
1200
  .description("Your invite codes and what became of them; `invites revoke <code>` cancels one")
962
1201
  .option("--json", "JSON output")
963
1202
  .action(run(async (app) => {
964
- const r = await ops.listCodes(app);
965
- return { json: { invites: r }, human: fmt.formatCodes(r), pretty: (p) => pretty.prettyCodes(r, p) };
1203
+ const all = await ops.listCodes(app);
1204
+ // A live code (open, or taken and not yet joined) lets whoever holds it in: inside an agent's
1205
+ // session (or where that can't be told) without the person's token, it is cut as a redeemed
1206
+ // one is, in the JSON too. The status stays readable.
1207
+ const redacted = !projects.personHereStrict(app);
1208
+ const r = redacted ? all.map((c) => ({ ...c, code: fmt.shortCode(c.code), ...(c.status === "open" || c.status === "taken" ? { redacted: true } : {}) })) : all;
1209
+ return { json: { invites: r, ...(redacted ? { redacted: true } : {}) }, human: fmt.formatCodes(r), pretty: (p) => pretty.prettyCodes(r, p) };
966
1210
  }));
967
1211
  invites
968
1212
  .command("revoke [code]")
@@ -1805,6 +2049,54 @@ export function buildProgram(deps) {
1805
2049
  codexCommands(program, deps, io);
1806
2050
  return program;
1807
2051
  }
2052
+ /**
2053
+ * Asks about each agent's sandbox edit on its own (sandbox.ts frontPreview: what changes, how to
2054
+ * undo it, and exactly what is written), default Yes; `yes` skips the questions. A no is remembered
2055
+ * for that agent. A file that changed after it was shown isn't written (sandbox.applyPlans).
2056
+ */
2057
+ async function askEachAgent(io, env, home, plans, o) {
2058
+ const lines = [];
2059
+ const written = [];
2060
+ const pre = o.from === "setup" ? " sandbox " : "";
2061
+ for (const f of plans) {
2062
+ if (f.plan.kind !== "edit")
2063
+ continue;
2064
+ if (!o.yes)
2065
+ io.out(`\n${sandbox.frontPreview(f, home, sandbox.userHomeOf(env))}`);
2066
+ const yes = o.yes === true || (await askDefaultYes(io, sandbox.frontQuestion(f)));
2067
+ if (!yes) {
2068
+ sandbox.setSandboxDeclined(home, f.front, true);
2069
+ lines.push(`${pre}${sandbox.AGENT_NAME[f.front]}: not changed. ${o.from === "enable" ? "`p2p setup` won't offer it again" : "You won't be asked again"}; \`p2p sandbox enable\` adds it any time`);
2070
+ continue;
2071
+ }
2072
+ try {
2073
+ for (const w of sandbox.applyPlans([f])) {
2074
+ written.push(w);
2075
+ lines.push(`${pre}Wrote ${w.path}${w.backup ? ` (backup: ${w.backup})` : ""}`);
2076
+ }
2077
+ }
2078
+ catch (e) {
2079
+ lines.push(`${pre}${sandbox.AGENT_NAME[f.front]}: not changed: ${e instanceof Error ? e.message : String(e)}`);
2080
+ continue;
2081
+ }
2082
+ if (sandbox.declinedHere(env, f.front))
2083
+ sandbox.setSandboxDeclined(home, f.front, false);
2084
+ lines.push(f.front === "codex" ? `${pre}Codex reads config.toml when it starts: restart open Codex sessions.` : `${pre}Claude Code applies settings changes to open sessions at their next command.`);
2085
+ }
2086
+ return { lines, written };
2087
+ }
2088
+ /** A question whose answer defaults to Yes (Enter): only ever for what tightens, such as the sandbox offer. */
2089
+ async function askDefaultYes(io, q) {
2090
+ if (io.select) {
2091
+ const lines = q.split("\n");
2092
+ const r = await io.select({ intro: lines.slice(0, -1), message: lines[lines.length - 1] || "Continue?", choices: [{ value: "yes", label: "Yes" }, { value: "no", label: "No" }], initial: "yes" });
2093
+ return r?.[0] === "yes";
2094
+ }
2095
+ if (!io.prompt)
2096
+ return false;
2097
+ const a = (await io.prompt(`${q} [Y/n] `)).trim().toLowerCase();
2098
+ return a === "" || a === "y" || a === "yes";
2099
+ }
1808
2100
  /** The running `p2p` script (the bundled p2p.mjs, or dist/bin.js), for Codex to start. */
1809
2101
  function selfScript(deps) {
1810
2102
  const p = deps.scriptPath ?? process.argv[1] ?? "";
@@ -1847,6 +2139,23 @@ function codexCommands(program, deps, io) {
1847
2139
  try {
1848
2140
  const script = selfScript(deps);
1849
2141
  out(Boolean(o.json), codex.installCommand({ env: deps.env, node: deps.nodeCommand ?? process.execPath, script, ...(o.codexHome ? { codexHome: resolve(o.codexHome) } : {}), write: o.write, remove: o.remove }));
2142
+ // Then the sandbox offer for Codex (sandbox.ts), once, to the person at a terminal (default Yes).
2143
+ if (o.write && !o.remove && !o.json && (io.prompt || io.select) && !ixLocal.ciEnv(deps.env)) {
2144
+ const env = o.codexHome ? { ...deps.env, CODEX_HOME: resolve(o.codexHome) } : deps.env;
2145
+ let here = true;
2146
+ try {
2147
+ sandbox.assertPersonOutsideAgents({ env }, "codex install --write");
2148
+ }
2149
+ catch {
2150
+ here = false;
2151
+ }
2152
+ const plans = here && !sandbox.declinedHere(env, "codex") ? sandbox.offerablePlans(env, ["codex"]) : [];
2153
+ if (plans.length > 0) {
2154
+ const r = await askEachAgent(io, env, resolveHome(env), plans, { from: "codex install" });
2155
+ for (const l of r.lines)
2156
+ io.out(l.trim());
2157
+ }
2158
+ }
1850
2159
  }
1851
2160
  catch (e) {
1852
2161
  fail(Boolean(o.json), e);
@@ -1959,14 +2268,29 @@ export async function main(argvIn, deps) {
1959
2268
  {
1960
2269
  // A copy without it (an embedder's object is left as it was); the process's own environment loses it too.
1961
2270
  const env = { ...deps.env };
1962
- const given = (env.P2P_PERSON_TOKEN ?? "").trim() !== "";
1963
- const front = deps.front === true || projects.takePersonToken(env, resolveHome(env));
2271
+ const token = (env.P2P_PERSON_TOKEN ?? "").trim();
2272
+ const given = token !== "";
2273
+ const home = resolveHome(env);
2274
+ const byToken = projects.takePersonToken(env, home);
2275
+ const front = deps.front === true || byToken;
2276
+ const linked = given && !front && !projects.homeFilesOwn(home);
2277
+ if (given && !front && !linked)
2278
+ projects.healPersonToken(home);
1964
2279
  if (deps.env === process.env)
1965
2280
  delete process.env.P2P_PERSON_TOKEN;
1966
2281
  // A token that isn't this home's is refused outright, never quietly taken as "not the person": the
1967
2282
  // person.key it was read from was replaced when an identity was created or restored here
1968
2283
  // (projects.ts renewPersonToken), and the front end that passed it reads the file again.
1969
- deps = { ...deps, front, env, ...(given && !front ? { personTokenStale: true } : {}) };
2284
+ deps = {
2285
+ ...deps,
2286
+ front,
2287
+ env,
2288
+ ...(byToken && deps.front !== true ? { frontToken: token, frontFresh: !projects.identityHere(home) } : {}),
2289
+ // A token that couldn't be checked because the keys it derives from are in a keychain that can't
2290
+ // be read now (keystore.ts) isn't stale: the command runs without it, and one that needs the keys
2291
+ // stops with the keychain's own error (`p2p doctor` still diagnoses).
2292
+ ...(linked ? { personTokenLinked: true } : given && !front && !keystore.keysUnreadable(home) ? { personTokenStale: true } : {}),
2293
+ };
1970
2294
  }
1971
2295
  // `--no-input` anywhere before `--`: no pickers, no questions (as a script would run).
1972
2296
  const end = argvIn.indexOf("--");
package/dist/config.d.ts CHANGED
@@ -37,6 +37,11 @@ export interface FileConfig {
37
37
  * agent hint. `p2p setup --ix` offers it again. Ix is optional; Peer2Peer never installs it.
38
38
  */
39
39
  ixDeclined?: boolean;
40
+ /**
41
+ * The agents the person said no for when `p2p setup` (or `p2p codex install --write`) offered to deny
42
+ * P2P_HOME to their sandboxes (sandbox.ts; `true`: both): not offered again. `p2p sandbox enable` asks again.
43
+ */
44
+ sandboxDeclined?: boolean | ("claude" | "codex")[];
40
45
  /**
41
46
  * Messages from your own agent sessions skip the hold in a session that approves its own tool calls
42
47
  * (`p2p own-agents deliver`, person only). Off by default: they are held like a peer's. No variable
package/dist/doctor.d.ts CHANGED
@@ -155,6 +155,13 @@ export declare function clockVerdict(skews: readonly {
155
155
  }[]): Check;
156
156
  /** "Where your data goes" for this device (no probes: what the code does, and this device's settings). */
157
157
  export declare function dataFlowOf(app: Pick<App, "env" | "home">, ix: Pick<DataFlow, "graphMemory" | "graphs" | "graphsNotListed">): DataFlow;
158
+ /**
159
+ * One line per installed front end: does its agent's sandbox deny its commands read and write
160
+ * access to P2P_HOME? That is the boundary the CLI's own gates rest on (an agent running as you can
161
+ * otherwise read the key files). Read from the person's config files; nothing is written, and
162
+ * nothing of their contents is shown.
163
+ */
164
+ export declare function sandboxChecks(c: Checks, app: App): void;
158
165
  /**
159
166
  * The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
160
167
  * whether the project here is mapped, and the graph target of the project here and of each project