@peer2peer/cli 0.1.3 → 0.1.5

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/rotation.js CHANGED
@@ -55,10 +55,12 @@
55
55
  // circle (§3.3); this hands over only what the old key still controls.
56
56
  import { copyFile, lstat, mkdir, readFile, rename, rm, stat, writeFile, chmod } from "node:fs/promises";
57
57
  import { join } from "node:path";
58
- import { addIdentityVersion, applyCircleBundle, b64uEncode, backupPhraseFromSeed, capsToRevokeOnUnfriend, createCircleTransferAccept, createDeviceCert, createIdentityDoc, createMembershipStatement, createProof, createRotation, createUnfriendV3, decodeTyped, displayAddress, displayFingerprint, dnsProofRecord, encodeLinkCode, generateDeviceKeysV3, generateIdentityKey, IdentityChain, INVITE_MAX_TTL_SEC, blockUser, createCap, jwsHash, LINK_TTL_SEC, linkId, liveFriendshipsV3, loadCircle, mergePrevTip, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
58
+ import { addIdentityVersion, applyCircleBundle, b64uEncode, backupPhraseFromSeed, capsToRevokeOnUnfriend, createCircleTransferAccept, createDeviceCert, createIdentityDoc, createMembershipStatement, createProof, createRotation, createUnfriendV3, decodeTyped, displayAddress, displayFingerprint, dnsProofRecord, encodeLinkCode, generateDeviceKeysV3, generateIdentityKey, IdentityChain, INVITE_MAX_TTL_SEC, isCanonicalRelayUrl, isDid, blockUser, createCap, jwsHash, LINK_TTL_SEC, linkId, liveFriendshipsV3, loadCircle, mergePrevTip, newLinkSecret, nextMembershipN, P2PError, parseLinkCode, recordOwnLeave, rotationConflicts, rotationKey, sanitizePeerText, sealLinkResponse, selectLinkRequest, storeOfferedCircle, TYP3, unfriendApplies, verifyDeviceCertV3, verifyMembershipStatement, verifyRotation, verifyRotationSignatures, verifyUnfriendV3, } from "@peer2peer/core/v3";
59
59
  import { FileDocBackend } from "@peer2peer/core/v3/node";
60
60
  import { App, certDid, defaultLabel, newKeysDoc } from "./app.js";
61
61
  import { CliError } from "./errors.js";
62
+ import { rotationLockOf, withRotationLock } from "./rotation-lock.js";
63
+ import { branchLine } from "./format.js";
62
64
  import { fetchTips, linkGet, linkPut, publishOver, relayCode, RelayConnection, sleep } from "./relay-client.js";
63
65
  import { deliverCircle, memberCaps, ownerPublish, signOwnJoin } from "./circle-ops.js";
64
66
  import { accept, dropHeld, getHeld, hold, mintInvite, withHeldId } from "./social.js";
@@ -67,6 +69,22 @@ import { linkJoin } from "./identity.js";
67
69
  import { renewPersonToken } from "./projects.js";
68
70
  import { makeEvent, receiving } from "./inbound.js";
69
71
  const STEPS = ["created", "published", "devices", "social", "final", "done"];
72
+ /** Printable ASCII only, one to 2048 characters (a single anchored class: linear, no backtracking). */
73
+ const PRINTABLE_ASCII = /^[\x21-\x7e]{1,2048}$/;
74
+ /**
75
+ * #91: a branch summary for the plan and the `branch_ambiguous` error. Its relay URLs and device ids come from
76
+ * versions whoever holds the identity key may have signed. Core's parser only lets canonical relay URLs (§5.1:
77
+ * WHATWG-serialised, so percent-encoded, no userinfo, query or fragment) and device ids (`d_` + base32) into a
78
+ * verified version; they are checked again here before they are printed, and anything else is left out.
79
+ */
80
+ export function branchSummary(hash, ver, by, relays) {
81
+ return {
82
+ hash,
83
+ ver,
84
+ by: [...new Set(by.filter((d) => isDid(d)))],
85
+ relays: relays.filter((r) => typeof r === "string" && PRINTABLE_ASCII.test(r) && isCanonicalRelayUrl(r)),
86
+ };
87
+ }
70
88
  const rotationDir = (home) => join(home, "rotation");
71
89
  const newHomeOf = (home) => join(rotationDir(home), "new");
72
90
  const followHomeOf = (home) => join(rotationDir(home), "follow");
@@ -184,10 +202,10 @@ function certLabel(cert) {
184
202
  return "";
185
203
  }
186
204
  }
187
- /** Our own identity's chain, verified (or undefined); pending heads never narrow our own view (#65 review M1). */
205
+ /** Our own identity's chain, verified (or undefined); pending heads (and #92 left-out versions) never narrow our own view (#65 review M1). */
188
206
  async function ownChain(app) {
189
207
  const stored = await app.store.getIdentity(app.userId);
190
- return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [] }) : undefined;
208
+ return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [], leftOut: [] }) : undefined;
191
209
  }
192
210
  /**
193
211
  * The newest version of our identity that is not a rotation's final one:
@@ -232,8 +250,11 @@ async function ownBranchFork(app) {
232
250
  * hash (whoever holds the identity key can pick those). A candidate is plausible when every version on
233
251
  * it since the fork point (the versions not behind every plain tip) is in this device's publish log or
234
252
  * was published `by` this device or a device that a version in its publish log lists. One candidate, or
235
- * exactly one plausible: that one. Otherwise the user chooses (`choice`, `--branch <hash>`), shown each
236
- * branch's publishers and relays. Undefined when our identity isn't forked that way.
253
+ * exactly one plausible: that one (#91: with the other candidates as `others`, warned about and shown in
254
+ * the plan: the owner's branch counts as implausible when a version on it comes from an owner device the
255
+ * publish log never lists, so a stolen device's branch could be the only plausible one). Otherwise the
256
+ * user chooses (`choice`, `--branch <hash>`), shown each branch's publishers and relays. Undefined when
257
+ * our identity isn't forked that way.
237
258
  */
238
259
  async function ownBranchTip(app, choice) {
239
260
  const fork = await ownBranchFork(app);
@@ -247,23 +268,31 @@ async function ownBranchTip(app, choice) {
247
268
  const chosen = candidates.find((t) => t.hash === choice);
248
269
  if (!chosen)
249
270
  throw new CliError("usage", `--branch ${choice}: not a branch of your identity that lists this device (${candidates.map((t) => t.hash).join(", ")})`);
250
- return chosen;
271
+ return { tip: chosen, others: [] };
251
272
  }
252
273
  if (candidates.length === 1)
253
- return candidates[0];
274
+ return { tip: candidates[0], others: [] };
254
275
  const log = new Set((await app.store.getPublishLog()).published);
276
+ // #91: every device any version in the publish log lists, including ones a later version revoked. That only
277
+ // ever makes more branches plausible, so it fails safe: more ambiguity (the user chooses), never a silent pick.
255
278
  const trusted = new Set([app.did, ...[...log].flatMap((h) => chain.get(h)?.devices ?? [])]);
256
279
  const behind = plain.map((t) => new Set(chain.ancestors(t.hash).map((v) => v.hash)));
257
280
  const common = new Set([...behind[0]].filter((h) => behind.every((set) => set.has(h))));
258
281
  const since = (t) => chain.ancestors(t.hash).filter((v) => !common.has(v.hash));
259
282
  const plausible = candidates.filter((t) => since(t).every((v) => log.has(v.hash) || trusted.has(v.by)));
283
+ const branches = candidates.map((t) => branchSummary(t.hash, t.ver, since(t).map((v) => v.by), t.relays));
260
284
  if (plausible.length === 1)
261
- return plausible[0];
262
- const branches = candidates.map((t) => ({ hash: t.hash, ver: t.ver, by: [...new Set(since(t).map((v) => v.by))], relays: [...t.relays] }));
285
+ return { tip: plausible[0], others: branches.filter((b) => b.hash !== plausible[0].hash) };
263
286
  throw new CliError("branch_ambiguous", `your identity is forked by a version that leaves this device out, and more than one branch still lists it: ${branches
264
- .map((x) => `${x.hash} (ver ${x.ver}, published by ${x.by.join(", ")}; relays ${x.relays.join(", ")})`)
287
+ .map(branchLine)
265
288
  .join("; ")}. Someone else holds your identity key. Check which branch is yours, then run \`p2p identity rotate --plan --branch <hash>\``, { branches });
266
289
  }
290
+ /** #91: the warning when provenance picked our own branch among others that still list this device. */
291
+ function otherBranchesWarning(tip, others) {
292
+ return `your identity is forked, and the plan builds on the branch ${tip} as yours (its versions come from your devices); other branches still list this device: ${others
293
+ .map(branchLine)
294
+ .join("; ")}. If ${tip} isn't yours, drop this plan (\`p2p identity rotate --cancel\`) and choose with \`p2p identity rotate --plan --branch <hash>\``;
295
+ }
267
296
  /**
268
297
  * #75: the name and relays our final version takes when built from our own branch: those of the newest
269
298
  * version on it this device published, with the relays this device is configured with, never the tip's
@@ -412,6 +441,8 @@ function planOf(st) {
412
441
  friendsOptIn: optIn,
413
442
  contest: !!st.contest,
414
443
  ...(st.backupFile ? { backup: { file: st.backupFile } } : {}),
444
+ ...(st.ownBranch ? { branch: st.ownBranch.tip } : {}),
445
+ ...(st.ownBranch?.others?.length ? { otherBranches: st.ownBranch.others } : {}),
415
446
  };
416
447
  }
417
448
  async function planWithAddress(app, st) {
@@ -483,6 +514,9 @@ async function loadOrRecover(app, prior, opts) {
483
514
  * fingerprint, the devices that would follow, and what moves.
484
515
  */
485
516
  export async function rotatePlan(app, opts = {}) {
517
+ return withRotationLock(app.home, () => rotatePlanLocked(app, opts));
518
+ }
519
+ async function rotatePlanLocked(app, opts) {
486
520
  const prior = await readRotationState(app.home);
487
521
  const recovered = await loadOrRecover(app, prior, opts);
488
522
  if (recovered)
@@ -490,6 +524,8 @@ export async function rotatePlan(app, opts = {}) {
490
524
  if (prior && prior.step !== "done" && prior.step !== "created") {
491
525
  throw new CliError("rotation_in_progress", `a rotation to ${prior.to} is under way: finish it with \`p2p identity rotate --resume\``);
492
526
  }
527
+ if (prior && prior.step === "created")
528
+ assertSameBranch(prior, opts);
493
529
  const st = prior && prior.step === "created" ? prior : await begin(app, opts);
494
530
  if (st === prior)
495
531
  applyExcludes(st, opts.exclude, opts.keep);
@@ -497,8 +533,26 @@ export async function rotatePlan(app, opts = {}) {
497
533
  await saveState(app.home, st);
498
534
  return planWithAddress(app, st);
499
535
  }
536
+ /**
537
+ * #91: a plan not yet accepted is reused by `--plan` and `--resume`, so a `--branch` naming another branch than the
538
+ * plan's own would be ignored: refused instead (drop the plan first).
539
+ */
540
+ function assertSameBranch(st, opts) {
541
+ if (opts.branch === undefined || opts.branch === st.ownBranch?.tip)
542
+ return;
543
+ if (st.step !== "created" || st.accepted) {
544
+ throw new CliError("usage", `--branch ${opts.branch}: the rotation under way here ${st.ownBranch ? `builds on the branch ${st.ownBranch.tip}` : "isn't built on a branch of a forked identity"}, and can't change now`);
545
+ }
546
+ const how = `drop it first (\`p2p identity rotate --cancel\`), then \`p2p identity rotate --plan --branch ${opts.branch}\``;
547
+ throw new CliError("usage", st.ownBranch
548
+ ? `--branch ${opts.branch}: the rotation plan here builds on the branch ${st.ownBranch.tip}. To choose another, ${how}`
549
+ : `--branch ${opts.branch}: the rotation plan here isn't built on a branch of a forked identity. To choose one, ${how}`);
550
+ }
500
551
  /** `p2p identity rotate --cancel`: drops a rotation whose plan wasn't accepted (nothing was published). */
501
552
  export async function rotateCancel(app) {
553
+ return withRotationLock(app.home, () => rotateCancelLocked(app));
554
+ }
555
+ async function rotateCancelLocked(app) {
502
556
  const st = await readRotationState(app.home);
503
557
  if (!st || st.step === "done")
504
558
  return { cancelled: false };
@@ -509,7 +563,15 @@ export async function rotateCancel(app) {
509
563
  app.warn(`the backup phrase of the key that wasn't used is still in ${st.backupFile}: delete it`);
510
564
  return { cancelled: true, to: st.to };
511
565
  }
566
+ export { rotationLockOf };
567
+ /**
568
+ * One `p2p identity rotate` run per home at a time (#91 review): `--plan`, `--cancel` and `--resend` too (#99), so a
569
+ * `--plan --exclude X` racing a `--resume --yes` run can't lose the exclusion. See withRotationLock.
570
+ */
512
571
  export async function rotate(app, opts = {}) {
572
+ return withRotationLock(app.home, () => rotateLocked(app, opts));
573
+ }
574
+ async function rotateLocked(app, opts) {
513
575
  const prior = await readRotationState(app.home);
514
576
  const recovered = await loadOrRecover(app, prior, opts);
515
577
  if (recovered)
@@ -521,6 +583,11 @@ export async function rotate(app, opts = {}) {
521
583
  if (!prior || prior.step === "done")
522
584
  throw new CliError("no_rotation", "there is no rotation in progress here to resume");
523
585
  st = prior;
586
+ assertSameBranch(st, opts);
587
+ // #91: `--resume --contest`: a rotation of this identity this device didn't publish came out while this one was
588
+ // under way (publishFinal points here): this one goes on as a competing one, so friends see a conflict.
589
+ if (opts.contest && !st.contest)
590
+ await contestOnResume(app, st, opts);
524
591
  }
525
592
  else {
526
593
  if (prior && prior.step !== "done")
@@ -659,14 +726,17 @@ async function begin(app, opts) {
659
726
  throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
660
727
  }
661
728
  // #75: forked by a version that leaves this device out, the plan lists from this device's own branch.
662
- const own = view.rotations.length > 0 ? undefined : await ownBranchTip(app, opts.branch);
729
+ const picked = view.rotations.length > 0 ? undefined : await ownBranchTip(app, opts.branch);
730
+ const own = picked?.tip;
663
731
  if (!opts.contest && !(own ?? view).keyholders.includes(app.did)) {
664
732
  throw new CliError("device_revoked", "this device is no longer a listed key holder of your identity");
665
733
  }
666
734
  let ownBranch;
667
- if (own) {
735
+ if (picked && own) {
668
736
  const f = ownBranchFinalFields(app, (await ownChain(app)), own, new Set((await app.store.getPublishLog()).published));
669
- ownBranch = { tip: own.hash, name: f.name, relays: f.relays };
737
+ ownBranch = { tip: own.hash, name: f.name, relays: f.relays, ...(picked.others.length > 0 ? { others: picked.others } : {}) };
738
+ if (picked.others.length > 0)
739
+ app.warn(otherBranchesWarning(own.hash, picked.others));
670
740
  if (f.extra.length > 0)
671
741
  app.warn(`your own branch lists relays no version this device published added (${f.extra.join(", ")}): your old identity's final version leaves them out`);
672
742
  }
@@ -1138,8 +1208,21 @@ async function publishFinal(app, st) {
1138
1208
  const mine = chain.allTips().find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
1139
1209
  // #75: a fork made by a version that leaves this device out can't go through publishNext (its merge
1140
1210
  // would leave this device unlisted, so it couldn't publish): see ownBranchTip and finalOnOwnBranch.
1141
- if (st.ownBranch && !contesting)
1142
- return publishOwnBranchFinal(app, ik, st, st.ownBranch, mine);
1211
+ if (st.ownBranch && !contesting) {
1212
+ try {
1213
+ return await publishOwnBranchFinal(app, ik, st, st.ownBranch, mine);
1214
+ }
1215
+ catch (e) {
1216
+ // #91: a rotation someone else published meanwhile (the refresh just brought it in) makes the relays refuse
1217
+ // ours however often it is rebuilt: say so, and point to the contest, never to another --resume.
1218
+ if (!(e instanceof CliError))
1219
+ throw e;
1220
+ const foreign = await foreignRotations(app);
1221
+ if (foreign.length === 0)
1222
+ throw e;
1223
+ throw await rotatedMeanwhile(app, foreign, e);
1224
+ }
1225
+ }
1143
1226
  if (mine) {
1144
1227
  // Published by an interrupted run: make sure the relays have it.
1145
1228
  const r = await app.publishDoc(mine.jws, mine.relays);
@@ -1168,6 +1251,46 @@ async function publishFinal(app, st) {
1168
1251
  }
1169
1252
  return { ver: base.ver + 1, ...r };
1170
1253
  }
1254
+ /**
1255
+ * #91: `--resume --contest`. A plan not yet accepted was made without the contest's drops (begin: the device that
1256
+ * signed the contested rotation, and every other key holder): refused, the user drops it and makes a contest's plan.
1257
+ * Past acceptance, those devices are dropped if no link code went out yet (unless kept, `--keep`); after that,
1258
+ * the ones that follow (or were sent a code) are named, so the user can revoke them on the new identity.
1259
+ */
1260
+ async function contestOnResume(app, st, opts) {
1261
+ const foreign = await foreignRotations(app);
1262
+ if (foreign.length === 0)
1263
+ throw new CliError("usage", "no rotation of your identity to contest: --contest answers one this device didn't publish");
1264
+ if (st.step === "created" && !st.accepted) {
1265
+ throw new CliError("usage", "this rotation plan was made before the rotation you want to contest, without dropping the devices that could have published it: drop it (`p2p identity rotate --cancel`), then contest with `p2p identity rotate --contest`");
1266
+ }
1267
+ const chain = await ownChain(app);
1268
+ const signers = new Set(foreign.map((f) => chain?.get(f.hash)?.by).filter((d) => d !== undefined && d !== app.did));
1269
+ const whyOf = (did, d) => signers.has(did) ? "signed the rotation you are contesting" : d.keyholder ? "holds your identity key, so it could have published the rotation you are contesting" : undefined;
1270
+ const suspects = Object.entries(st.devices).filter(([did, d]) => d.status !== "excluded" && d.status !== "aborted" && whyOf(did, d) !== undefined);
1271
+ const named = [];
1272
+ for (const [did, d] of suspects) {
1273
+ if (!after(st, "devices") && d.status === "pending" && !(opts.keep ?? []).includes(did)) {
1274
+ d.status = "excluded";
1275
+ d.why = whyOf(did, d);
1276
+ }
1277
+ else {
1278
+ named.push(`${did}${d.label ? ` (${sanitizePeerText(d.label, 64)})` : ""}${d.newDid ? `, now ${d.newDid}` : ""}: ${whyOf(did, d)}`);
1279
+ }
1280
+ }
1281
+ st.contest = true;
1282
+ await saveState(app.home, st);
1283
+ if (named.length > 0) {
1284
+ app.warn(`these devices of yours follow this rotation (or were sent its link code) and could have published the rotation you are contesting: ${named.join("; ")}. If one is lost or stolen, revoke it on your new identity (\`p2p devices revoke <did>\`)`);
1285
+ }
1286
+ }
1287
+ /** #91: the error when a rotation this device didn't publish is out and the relays refuse our own final version. */
1288
+ async function rotatedMeanwhile(app, foreign, cause) {
1289
+ const to = [...new Set(foreign.map((f) => f.rotation.to))];
1290
+ const chain = await ownChain(app);
1291
+ const by = [...new Set(foreign.map((f) => chain?.get(f.hash)?.by).filter((d) => d !== undefined && isDid(d)))];
1292
+ return new CliError("identity_rotated", `no relay took your old identity's final version (${cause.message}): this identity was already rotated to ${to.join(" and ")}${by.length > 0 ? ` (signed by your device ${by.join(" and ")})` : ""}, and this device didn't publish that. If you didn't start it, someone holds your identity key: contest it with \`p2p identity rotate --resume --contest\` (your friends then see a conflict and apply neither)`, { to, by });
1293
+ }
1171
1294
  /**
1172
1295
  * #75: publishes the final version built from our own branch (finalOnOwnBranch), or the one an
1173
1296
  * interrupted run built (`pinned`). A final version no relay took because the tips moved since (the
@@ -1428,6 +1551,9 @@ export const RESEND_PER_HOUR = 50;
1428
1551
  * of what a relay advertises, in a rolling hour).
1429
1552
  */
1430
1553
  export async function rotateResend(app) {
1554
+ return withRotationLock(app.home, () => rotateResendLocked(app));
1555
+ }
1556
+ async function rotateResendLocked(app) {
1431
1557
  await app.load(true);
1432
1558
  const st = await readRotationState(app.home);
1433
1559
  if (!st || st.step !== "done" || app.userId !== st.to)
@@ -0,0 +1,195 @@
1
+ import * as codex from "@peer2peer/codex-bridge";
2
+ import { type Env, type FileConfig } from "./config.js";
3
+ import type { App } from "./app.js";
4
+ /** The person's home folder, as the agents expand `~` (HOME, USERPROFILE on Windows). */
5
+ export declare function userHomeOf(env: Env): string;
6
+ /** P2P_HOME, absolute, and its real path when that differs (a symbolic link on the way). */
7
+ export declare function p2pHomePaths(env: Env): {
8
+ home: string;
9
+ real?: string;
10
+ };
11
+ /** Claude Code's user settings file: `$CLAUDE_CONFIG_DIR/settings.json`, else `~/.claude/settings.json`. */
12
+ export declare function claudeSettingsPath(env: Env): string;
13
+ /** Managed settings (what an organization deploys): read for the status only, never written. */
14
+ export declare function claudeManagedPath(platform?: NodeJS.Platform): string | undefined;
15
+ /** What Claude Code's settings should hold for P2P_HOME: the sandbox paths, and the file tools' rules. */
16
+ export declare function claudeWanted(paths: {
17
+ home: string;
18
+ real?: string;
19
+ }, userHome: string): {
20
+ sandbox: string[];
21
+ read: string[];
22
+ edit: string[];
23
+ };
24
+ export interface ClaudeSandboxStatus {
25
+ /** on: every piece is in place; off: something is missing; unknown: settings couldn't be read; unavailable: no sandbox on this platform. */
26
+ state: "on" | "off" | "unknown" | "unavailable";
27
+ detail: string;
28
+ /** What is missing (each a settings key or rule). */
29
+ missing: string[];
30
+ /** Things that weaken it. */
31
+ notes: string[];
32
+ settings: string;
33
+ }
34
+ /** The most a config file read here may hold: anything bigger is treated as unreadable. */
35
+ export declare const MAX_CONFIG_BYTES: number;
36
+ /**
37
+ * Reads a config file safely, whoever put it there (a cloned repository's `.claude` or `.codex`):
38
+ * opened non-blocking (a FIFO can't hang the read), it must be a regular file once a symbolic link
39
+ * is followed (not a FIFO, a device such as /dev/zero, or a folder), and at most MAX_CONFIG_BYTES.
40
+ * null when it doesn't exist; throws a CliError when it can't be read that way.
41
+ */
42
+ export declare function readConfigFile(path: string): string | null;
43
+ /** The folders whose `.claude` settings a session here loads: its working directory and, in a git repository, the repository root. */
44
+ export declare function projectRoots(workdir: string): string[];
45
+ /**
46
+ * Whether Claude Code's sandbox denies its commands (and its file tools) P2P_HOME: from the user,
47
+ * managed and this folder's project settings (`.claude/settings.json` and `.claude/settings.local.json`
48
+ * in the session's folder and its repository root), and, on Linux, whether bubblewrap is there.
49
+ */
50
+ export declare function claudeSandboxStatus(env: Env, o?: {
51
+ platform?: NodeJS.Platform;
52
+ managedPath?: string | null;
53
+ workdir?: string;
54
+ }): ClaudeSandboxStatus;
55
+ /** One change to settings.json, for the preview. */
56
+ export type JsonEdit = {
57
+ key: string;
58
+ value: unknown;
59
+ was?: unknown;
60
+ append?: boolean;
61
+ };
62
+ export type ClaudeSandboxPlan = {
63
+ kind: "already";
64
+ } | {
65
+ kind: "edit";
66
+ after: string;
67
+ edits: JsonEdit[];
68
+ } | {
69
+ kind: "manual";
70
+ reason: string;
71
+ };
72
+ /**
73
+ * The edit to Claude Code's user settings (`text`, null when the file doesn't exist) that denies
74
+ * P2P_HOME to its sandboxed commands and file tools, keeping every other key and the file's
75
+ * indentation. Idempotent: entries already there (or a folder above P2P_HOME) aren't added again.
76
+ */
77
+ export declare function planClaudeSandbox(text: string | null, env: Env): ClaudeSandboxPlan;
78
+ export interface FrontPlan {
79
+ front: "claude" | "codex";
80
+ /** The file the edit writes. */
81
+ path: string;
82
+ /** Whether the agent looks installed (its config folder exists). */
83
+ present: boolean;
84
+ status: {
85
+ state: string;
86
+ detail: string;
87
+ notes: string[];
88
+ };
89
+ plan: {
90
+ kind: "already";
91
+ } | {
92
+ kind: "edit";
93
+ before: string | null;
94
+ after: string;
95
+ preview: string[]; /** Codex: what the new profile extends. */
96
+ base?: string; /** Codex: the config set no sandbox, so the base was chosen. */
97
+ assumed?: true;
98
+ } | {
99
+ kind: "manual";
100
+ reason: string;
101
+ snippet?: string;
102
+ } | {
103
+ kind: "unavailable";
104
+ };
105
+ }
106
+ /** The Codex home (CODEX_HOME, else ~/.codex) and its config.toml. */
107
+ export declare function codexConfigPath(env: Env): string;
108
+ /** The deny paths for Codex's config (`~/…` under the home folder). */
109
+ export declare function codexDenyPathsOf(env: Env): string[];
110
+ /**
111
+ * Why P2P_HOME can't be denied safely, or undefined: a path with rule or glob characters (it would
112
+ * match something else, or break the rule), or the home folder itself, `/` or a folder above the home
113
+ * folder (denying it would lock the agents out of everything).
114
+ */
115
+ export declare function p2pHomeProblem(env: Env): string | undefined;
116
+ export declare function codexStatus(env: Env, o?: {
117
+ workdir?: string;
118
+ }): codex.CodexSandboxStatus & {
119
+ settings: string;
120
+ };
121
+ export interface PlanOptions {
122
+ platform?: NodeJS.Platform;
123
+ managedPath?: string | null;
124
+ workdir?: string;
125
+ /** For a Codex config that sets no sandbox at all: what the new profile extends (default :read-only). */
126
+ codexBase?: ":read-only" | ":workspace";
127
+ }
128
+ /** What `enable` would do for one front end (computed, nothing written). */
129
+ export declare function planFront(front: "claude" | "codex", env: Env, o?: PlanOptions): FrontPlan;
130
+ /** The name the person knows each front end's agent by. */
131
+ export declare const AGENT_NAME: Record<"claude" | "codex", string>;
132
+ /** What one agent's edit does, in full, then the exact lines: asked about on its own. */
133
+ export declare function frontPreview(f: FrontPlan, p2pHome: string, userHome: string): string;
134
+ /** The question for one agent. */
135
+ export declare function frontQuestion(f: FrontPlan): string;
136
+ /**
137
+ * Writes the planned edits. Each file must still hold what the preview was made from (else nothing
138
+ * is written). The backup sits next to the path as named (a symbolic link's own folder, not its
139
+ * target's), 0600, created exclusively; the new content is written atomically to the link's target,
140
+ * keeping its mode.
141
+ */
142
+ export declare function applyPlans(plans: readonly FrontPlan[], now?: Date): {
143
+ path: string;
144
+ backup?: string;
145
+ }[];
146
+ /**
147
+ * Only the person changes an agent's sandbox, at their own terminal, outside every agent's session:
148
+ * never with a front end's token (that would be an agent's front end changing its own sandbox), and
149
+ * never when the process tree can't be read (fail closed).
150
+ */
151
+ export declare function assertPersonOutsideAgents(app: {
152
+ env: Env;
153
+ front?: boolean;
154
+ }, what: string): void;
155
+ type Front = "claude" | "codex";
156
+ /** Which agents the person said no for (FileConfig.sandboxDeclined: `true` for both, as an older answer, or a list). */
157
+ export declare function sandboxDeclined(file: Pick<FileConfig, "sandboxDeclined">, front?: Front): boolean;
158
+ /** Records the person's answer for one agent. */
159
+ export declare function setSandboxDeclined(home: string, front: Front, declined: boolean): void;
160
+ /** The front ends worth offering: installed here (their config folder exists), with an edit to make. */
161
+ export declare function offerablePlans(env: Env, only?: readonly Front[], o?: PlanOptions): FrontPlan[];
162
+ /** Whether the person said no before, for `front` (any, without one); config.json unreadable counts as no answer. */
163
+ export declare function declinedHere(env: Env, front?: Front): boolean;
164
+ /** Whether a front end's config folder is here at all. */
165
+ export declare function frontPresent(front: "claude" | "codex", env: Env): boolean;
166
+ /**
167
+ * The one-time notice a front end shows its person (never its model) when its agent's sandbox
168
+ * doesn't deny P2P_HOME: the command to run in their own terminal. Undefined when the sandbox
169
+ * already does, the person said no before, it was shown already (once per device and front end),
170
+ * or the caller is neither the person's front end nor the person. An agent's shell without the token
171
+ * can't use it up; one that already reads P2P_HOME (no sandbox yet) can take the token and can.
172
+ */
173
+ export declare function sandboxNotice(app: App, front: "claude" | "codex"): Promise<string | undefined>;
174
+ export interface SandboxReport {
175
+ p2pHome: string;
176
+ /** The person said no to the offer before. */
177
+ declined: boolean;
178
+ claude: ClaudeSandboxStatus & {
179
+ present: boolean;
180
+ };
181
+ codex: codex.CodexSandboxStatus & {
182
+ settings: string;
183
+ present: boolean;
184
+ };
185
+ }
186
+ /** Both front ends' sandbox status (read-only; whoever asks). */
187
+ export declare function sandboxReport(env: Env, o?: {
188
+ platform?: NodeJS.Platform;
189
+ managedPath?: string | null;
190
+ workdir?: string;
191
+ }): SandboxReport;
192
+ /** The fix, said to the person, or to an agent (which never runs it). */
193
+ export declare function sandboxFix(person: boolean): string;
194
+ export declare function sandboxHuman(r: SandboxReport, person: boolean): string;
195
+ export {};