@peer2peer/cli 0.1.3 → 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/README.md +7 -6
- package/dist/app.d.ts +20 -0
- package/dist/app.js +77 -12
- package/dist/cli.d.ts +4 -4
- package/dist/cli.js +200 -1
- package/dist/config.d.ts +5 -0
- package/dist/doctor.d.ts +7 -0
- package/dist/doctor.js +73 -2
- package/dist/format.d.ts +3 -1
- package/dist/format.js +12 -0
- package/dist/identity.js +2 -0
- package/dist/keystore.d.ts +223 -0
- package/dist/keystore.js +1021 -0
- package/dist/procstart.js +11 -3
- package/dist/projects.js +4 -8
- package/dist/rotation-lock.d.ts +17 -0
- package/dist/rotation-lock.js +188 -0
- package/dist/rotation.d.ts +27 -1
- package/dist/rotation.js +141 -15
- package/dist/sandbox.d.ts +195 -0
- package/dist/sandbox.js +763 -0
- package/dist/state.d.ts +8 -0
- package/dist/state.js +12 -2
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# p2p: the Peer2Peer CLI
|
|
2
2
|
|
|
3
|
-
`@peer2peer/cli` is the standalone `p2p` command for [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
3
|
+
`@peer2peer/cli` is the standalone `p2p` command for [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.4/docs/protocol.md). It gives you an identity with no account, friends and circles, end-to-end encrypted messages between agent sessions, and live session status. Everything goes over open relays that anyone can run.
|
|
4
4
|
|
|
5
5
|
It is core software: it never imports Ix or an extension (`node scripts/check-boundaries.mjs`).
|
|
6
6
|
|
|
7
7
|
## Two friends in two minutes
|
|
8
8
|
|
|
9
|
-
You need a relay. Run your own (`npx @peer2peer/relay`, see [run-a-relay.md](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
9
|
+
You need a relay. Run your own (`npx @peer2peer/relay`, see [run-a-relay.md](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.4/docs/run-a-relay.md)), or use one your community runs. No relay is built in yet. Tell `p2p` about it once:
|
|
10
10
|
|
|
11
11
|
```sh
|
|
12
12
|
export P2P_DEFAULT_RELAYS=wss://relay.example.org/v3 # 1–5, comma separated
|
|
@@ -29,7 +29,7 @@ p2p join relay.example.org/K7QM-3XPD-9TWA-HF2N-6RJC # you and ann@k7f2-qx9a-3m
|
|
|
29
29
|
|
|
30
30
|
If Ann has a default circle (`p2p circle default <cid>`) that she owns or administers, the code joins Ben to it as well, and it becomes his default circle. Ann's client adds him the next time it runs (at once, when a `watch` is running), and tells her `ben@… joined via your code K7QM… ("ben")`. If that isn't who she meant, `p2p remove <userId>` undoes it. The code works once and lives 7 days at most. The long-link form (`p2p invite --link` / `p2p accept <link>`) still works.
|
|
31
31
|
|
|
32
|
-
**Share a project and talk.** A session is shared with nobody until you share the project it works in (a git repository, or a folder): see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
32
|
+
**Share a project and talk.** A session is shared with nobody until you share the project it works in (a git repository, or a folder): see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.4/docs/concepts.md#projects-project-boundaries).
|
|
33
33
|
|
|
34
34
|
```sh
|
|
35
35
|
# Ben, in his repository (and Ann, in hers: `p2p project share --person ben`):
|
|
@@ -61,7 +61,8 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
|
|
|
61
61
|
|
|
62
62
|
| Command | What it does |
|
|
63
63
|
|---|---|
|
|
64
|
-
| `setup [--name n] [--relay url]… [--backup-file [path] \| --print-backup \| --no-backup] [--ix]` | The friendly `init`: the name defaults to your OS user name, and relays come from the defaults. Interactively it offers to save the backup phrase to a 0600 file (default `<home>/backup-phrase.txt`, never overwritten) or print it. It is idempotent: on a home that already has an identity it changes nothing and reports `created: false`. **Ix is optional and recommended; Peer2Peer never installs it for you.** Without the Ix CLI, setup at your terminal says what Ix adds and asks `Install Ix? [y/N]` (default No): a yes prints the install command for you to run yourself, a no is remembered (`"ixDeclined": true` in config.json) and not asked again; `--ix` asks again. It never offers Ix with `--json`, with `CI` set, without a terminal, or inside an agent's session; `--json` reports `ix.installed`, `ix.recommended` and `ix.install` (the command) instead. With Ix and `@peer2peer/ext-ix` both installed, a new install (or `--ix`) asks you on your terminal (or takes the Claude mod's typed `/peers setup`) before enabling the `ix` extension; never from inside an agent's session. An existing install is never changed silently: it gets a one-time notice at a terminal instead. |
|
|
64
|
+
| `setup [--name n] [--relay url]… [--backup-file [path] \| --print-backup \| --no-backup] [--ix] [--sandbox]` | The friendly `init`: the name defaults to your OS user name, and relays come from the defaults. Interactively it offers to save the backup phrase to a 0600 file (default `<home>/backup-phrase.txt`, never overwritten) or print it. It is idempotent: on a home that already has an identity it changes nothing and reports `created: false`. **Ix is optional and recommended; Peer2Peer never installs it for you.** Without the Ix CLI, setup at your terminal says what Ix adds and asks `Install Ix? [y/N]` (default No): a yes prints the install command for you to run yourself, a no is remembered (`"ixDeclined": true` in config.json) and not asked again; `--ix` asks again. It never offers Ix with `--json`, with `CI` set, without a terminal, or inside an agent's session; `--json` reports `ix.installed`, `ix.recommended` and `ix.install` (the command) instead. With Ix and `@peer2peer/ext-ix` both installed, a new install (or `--ix`) asks you on your terminal (or takes the Claude mod's typed `/peers setup`) before enabling the `ix` extension; never from inside an agent's session. An existing install is never changed silently: it gets a one-time notice at a terminal instead. |
|
|
65
|
+
| `sandbox` / `sandbox enable [--claude] [--codex] [--yes] [--codex-base read-only\|workspace]` | Whether your agents' sandboxes (Claude Code, Codex) deny their commands read and write access to `P2P_HOME`, and the fix (`sandbox`, read-only; `doctor` shows the same, with the session's project settings and, on Linux, bubblewrap). `sandbox enable` adds the deny to your own config, asking about each agent on its own (what changes, how to undo it, exactly what is written; default Yes): Claude Code's user `settings.json` (`sandbox.enabled`, `autoAllowBashIfSandboxed: false` unless you set it, `allowUnsandboxedCommands: false`, `filesystem.denyRead`/`denyWrite`, and `Read`/`Edit` deny rules) and Codex's `config.toml` (a permissions profile, never broader than your current sandbox, that denies `P2P_HOME`; with no sandbox configured it extends `:read-only` unless `--codex-base workspace`). Each file is backed up beside itself (`<file>.p2p-backup-<time>`, 0600), nothing is written if it changed after it was shown, everything else is kept, and a second run changes nothing. `setup` at your terminal, and `codex install --write`, offer it once; a no is remembered per agent (`"sandboxDeclined"` in config.json) and `setup --sandbox` (or `sandbox enable`) asks again. Only you run it, in your own terminal: refused inside an agent's session, when p2p can't read its process tree, from a front end even with its token, and with `--yes` on Windows. See docs/security/threat-model.md. |
|
|
65
66
|
| `init [--name n] [--relay url]… [--yes]` | Creates the identity key and the first device (a key holder), and publishes document v1. It strongly prompts for a backup or a second key holder (§2.5). `--yes` skips the prompt but still warns. |
|
|
66
67
|
| `whoami` | Shows your address and grouped fingerprint, devices, relays and document expiry. |
|
|
67
68
|
| `backup show` / `backup restore [--relay …] [--keep-devices] [--new-chain]` | The 24-word BIP-39 phrase (§2.7). Restore reads the phrase from a prompt or stdin, never from argv. It makes this device a key holder and, by default, revokes the lost devices. It refuses when the relays can't be read; starting a new history at version 1 takes `--new-chain`, and only when a reachable relay holds no document. It back-fills a relay that's behind. If any listed relay still refuses (or is down), the restore is committed locally but exits **2** with `error: "restore_incomplete"` and the full result (`did`, `ver`, `failed`); fix it with `p2p identity republish`. |
|
|
@@ -93,7 +94,7 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
|
|
|
93
94
|
| `history [--session <sid>\|--inbox] [--peer <user>] [--circle <cid>] [--since 30m\|12h\|7d\|<date>] [--limit n] [--clear]` | Messages this device sent and received, oldest first (the newest `--limit`, default 50): message text in and out, and extension kinds as their one-line fallback (never the body). Kept only on this device, sealed with ChaCha20-Poly1305 under a key of its own (`cli/history.key`, 0600), for `history.retentionDays` (default 30) and at most `history.maxBytes` (default 8 MiB) in config.json, pruned on every write; `"enabled": false` or `P2P_HISTORY=0` keeps nothing new, and `--clear` deletes it all with its key, and the messages still in `events.json` (the event log `watch` reads). Past the cap the oldest go first, whoever sent them. A record's `at` is when it arrived here (`sentAt`: the sender's time). Writes are copy-on-write and reads take the state lock, so a crash loses at most what was being written; an older segment put back is never taken back in (the index names each with its hash and the next unused number, and keeps a copy, `history-mark.json`). A file that can't be opened is set aside (`history.bad-*`, said on stderr) at the next write, never shown; the text output caps each record at 4,000 characters. Nothing goes to a relay or a peer. With no `--session` (everything) or with `--inbox` (messages to you: session `tui`, or no session), it is the person's: their front end's token, or their `yes` typed on the controlling terminal, and refused inside an agent's session. `--session <sid>` is that session's own history: its front end reads it for a session a front end registered, and only what it recorded since that binding began, in projects the session is still bound to (a record kept with no binding is the person's only); without the token only the person at their terminal can. Message text is the sender's data: one line each, sanitized for the terminal. |
|
|
94
95
|
| `receipts [on\|off]` | Whether this user sends delivery receipts (on by default; `"receipts": false` in config.json, `P2P_RECEIPTS=0` overrides). On by default, which is a presence signal: statuses advertise `receipts.v1` to everyone who sees them, and a `shown` tells a sender when the message reached the session's model. Off, no receipt goes out and statuses stop advertising `receipts.v1`, so senders see what an older client looks like. |
|
|
95
96
|
| `status --session <sid> --state busy\|idle [--summary] [--file]… [--label] [--repo] [--branch] [--mode] [--cap]… [--agents-json <json\|->] [--project-dir d]…` | `--project-dir` (and `P2P_PROJECT_DIRS`, `P2P_WORKDIR`): folders the session works in; each binds it to that project, which only narrows who sees it (a device file such as `/dev/null` binds nothing). `--project-dirs-over[=unresolved,folders,front]` (and `P2P_PROJECT_DIRS_OVER`): the front end couldn't resolve a path, dropped folders past its cap, or lost track; the session is private, and the refusal names the cause (a bare flag or an unknown word is `front`). `P2P_SESSION_SCRATCH` (JSON `{sid, tmp, config, job}`, read only from a front end with the person token): Claude Code's own folders for this session (`<tmp>/claude-<uid>/<project>/<sid>`, `<config>/projects/<project>/<sid>`, its job folder); a path there binds no project, checked on real paths by the exact id, and a symlink there binds its target (docs/concepts.md). A private session sends no summary. Sends a `status` envelope to everyone the roster allows. Safe to run every 60 s. A status carries the CLI's own caps (`status.tolerant.v1`, `agents.v1`, `xstate.v1`, `proto.3.1`) and `--cap` adds what the calling client understands. `--agents-json` (a JSON array, `-` reads it from stdin) is the session's subagents (§4.3 "Status agents"): normalized (at most 8, each at most 10 repo-relative files, an 80-character task), sent as `agents` only to users whose live sessions all advertise `agents.v1`, and as a `(+N agents)` summary to everyone else (`delivered[].agents` says which). `P2P_STATUS_CAPS=0` (or `"statusCaps": false` in config.json) opts out, for peers on clients older than the §4.3 "Status caps" amendment: the status then carries only the original fields, and `--cap` is left out with a warning, never an error. `ls --json` rows and watch lines carry each session's `caps` and `agents`. |
|
|
96
|
-
| `project share [<circle>…] [--person u]… [--add] [--subfolders] [--dir d]`, `project private`, `project ls`, `project show` | Who sees sessions working in a project (a git repository, or a folder): private until shared (see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
97
|
+
| `project share [<circle>…] [--person u]… [--add] [--subfolders] [--dir d]`, `project private`, `project ls`, `project show` | Who sees sessions working in a project (a git repository, or a folder): private until shared (see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.4/docs/concepts.md#projects-project-boundaries)). `share` with nothing named: a picker on a terminal, else your default circle. `--subfolders` (a folder outside git): the share covers its subfolders too, never past a repository, a `.p2p-private` or a folder with its own policy. It is refused for `/`, a home folder, a temporary or a system folder, and it warns about the repositories and `.p2p-private` folders below. Without it the share is for that folder alone (`--add` keeps what the share had). A committed `.p2p-private` makes a repository private; nothing in a repository can share it |
|
|
97
98
|
| `session show <sid>` | Read only: the session's bound projects, each one's policy (a folder project lists the subfolders it covered), who the session reaches, and every reason it is private with what helps (a share, or a new session when the cause lasts until it ends: a cap, an unresolved path, a dropped front end, `.p2p-private`). Yours only: refused inside an agent's session without the front end's token, so no agent reads another session's bindings. |
|
|
98
99
|
| `session roster <sid> [--circle cid\|--private] [--add u]… [--remove u]…` | Who may see and message a session, within what its project shares (`not_shared` past it). Until changed here, a session follows its project's policy (§6), also when that changes after the session started; a running session never moves into an open circle by itself (it stays private, with a warning). |
|
|
99
100
|
| `watch --session <sid> --jsonl` | One JSON line per accepted event. Stays connected and reconnects silently. |
|
|
@@ -331,7 +332,7 @@ Without a user, it checks this device:
|
|
|
331
332
|
- Ix: the `ix` binary and its version, whether the Ix extension is enabled, the local backend (`<endpoint>/v1/health` reachable), whether the project here is mapped (`ix status`), and the **graph target** of the project here and of each project with a policy: `local only` today (see the threat model's "Graph targets"). Without Ix nothing here is a failure. `ix` runs by absolute path with an allowlisted environment and the local endpoint pinned (Ix's default, or a loopback `ixEndpoint` in config.json; never `IX_ENDPOINT`/`IX_PAT` from the environment);
|
|
332
333
|
- the CLI's version against the one the Claude mod bundles (found from `P2P_MOD_ROOT`, which the mod sets, or the plugin folder around a bundled `p2p.mjs`).
|
|
333
334
|
|
|
334
|
-
After the checks, **Where your data goes** says, for this device, what travels end-to-end encrypted (messages, statuses, receipts) and some of what a relay still sees (metadata, including who may reach whom, which mailboxes, sizes, timing, kind and session id, IPs, your identity document, and a circle's chain on a members-only relay that admits it; the threat model has all of it); that message history stays on this device, encrypted at rest with its key beside it, and that the event log keeps recent messages in the clear; whether graph memory is on; and each project's graph target (the same rule and wording as `p2p project show`), with the reminder that the local Ix backend keeps what it gets in plaintext. See [What is encrypted, what isn't](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
335
|
+
After the checks, **Where your data goes** says, for this device, what travels end-to-end encrypted (messages, statuses, receipts) and some of what a relay still sees (metadata, including who may reach whom, which mailboxes, sizes, timing, kind and session id, IPs, your identity document, and a circle's chain on a members-only relay that admits it; the threat model has all of it); that message history stays on this device, encrypted at rest with its key beside it, and that the event log keeps recent messages in the clear; whether graph memory is on; and each project's graph target (the same rule and wording as `p2p project show`), with the reminder that the local Ix backend keeps what it gets in plaintext. See [What is encrypted, what isn't](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.4/docs/security/encryption.md). In `--json` it is `dataFlow`: `wire`, `history`, `graphMemory {on: true | false | "unknown", detail}` ("unknown" when Ix didn't answer in time: `p2p watch` may still be writing), `graphs[] {id, name, here, target, line, plaintext}`, `graphsNotListed`, `anyShared` and `doc`.
|
|
335
336
|
|
|
336
337
|
With `<user>` (an address, petname, name or userId), it checks whether you can see them: friendship or the circles you both stand in; their identity document, fetched now and fresh; the relays they list and whether you share one you reach; whether you hold a capability for their relays and they hold one from you for yours (as far as this device's records tell); when anything last arrived from them; whether they're blocked, suspended (a contested key move) or held; and whether the sessions they shared include you, and are live. It then lists each of their devices with its protocol minor (and exact client version only when the device publishes one in `dinfo`) and the caps it advertises (from its identity document entry, else its latest status), and the features unavailable between you, in words, never as a failure (docs/compatibility.md); `--json` adds `devices` and `unavailable`.
|
|
337
338
|
|
package/dist/app.d.ts
CHANGED
|
@@ -248,12 +248,32 @@ export declare class App {
|
|
|
248
248
|
strict?: boolean;
|
|
249
249
|
setAside?: SetAside;
|
|
250
250
|
}): Promise<IdentityView | undefined>;
|
|
251
|
+
/**
|
|
252
|
+
* #79, #92 follow-up: the relays core held a refresh of our own identity back for (`by`, they sent a head that
|
|
253
|
+
* would leave out the versions `left`), counted like the relays core names as serving versions that don't connect
|
|
254
|
+
* (a rotation sets them aside, the hint names them) only when one of `left` is our own current tip: a tip of our
|
|
255
|
+
* stored chain (never an old version a relay replays: that is an ancestor of what we hold, or not held at all)
|
|
256
|
+
* that our devices published (the publish log) and that the head held back for (`head`) revoked no device of (#99),
|
|
257
|
+
* or, when the head held back for (`head`) leaves this device out as a key holder (a thief's head against the owner's devices, #79), that a device a version in the publish log lists
|
|
258
|
+
* published (another owner device whose versions haven't reached this device's log yet, the provenance rule of
|
|
259
|
+
* ownBranchTip in rotation.ts). That provenance alone never counts against a head that still lists this device: the
|
|
260
|
+
* devices a logged version lists include ones the owner revoked since, and a version such a device signed, held
|
|
261
|
+
* here, must not get the relays serving the owner's revocation set aside. Otherwise none: a relay replaying an old
|
|
262
|
+
* version (history pruned past what the relays keep) can't get an honest relay set aside, and a relay that really
|
|
263
|
+
* holds the owner up can still be removed (`p2p relays remove`).
|
|
264
|
+
*/
|
|
265
|
+
private ownHeldBack;
|
|
251
266
|
/**
|
|
252
267
|
* For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
|
|
253
268
|
* core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
|
|
254
269
|
* so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
|
|
270
|
+
* #99 review: `heldBy`, the relays core held the refresh back for, are named too when they weren't counted
|
|
271
|
+
* (ownHeldBack refused, as when their head drops a device this device's current version lists), with what to do:
|
|
272
|
+
* nothing else names them.
|
|
255
273
|
*/
|
|
256
274
|
private unconnectedHint;
|
|
275
|
+
/** #99 review: the relays a refresh of our own identity was held back for, not set aside (ownHeldBack refused). */
|
|
276
|
+
private heldBackHint;
|
|
257
277
|
/**
|
|
258
278
|
* #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
|
|
259
279
|
* identity edit that removes relays (`setAside.relays`: the ones it removes), or a rotation step
|
package/dist/app.js
CHANGED
|
@@ -10,9 +10,10 @@
|
|
|
10
10
|
// §5.8), finding caps, resolving addresses and petnames, and syncing state to
|
|
11
11
|
// the user's other devices.
|
|
12
12
|
import { identityHere, personTokenMatchesKeys, personTokenOk } from "./projects.js";
|
|
13
|
+
import { finishPendingMove } from "./keystore.js";
|
|
13
14
|
import { confirmOnTty } from "./tty-confirm.js";
|
|
14
15
|
import { hostname, userInfo } from "node:os";
|
|
15
|
-
import { addIdentityVersion, b64uDecode, b64uEncode, capAllowsKind, CircleChain, createCap, createDeviceCert, createIdentityDoc, decodeTyped, deviceKeysV3FromSecrets, displayAddress, displayFingerprint, getIdentityView, MAX_DEVICES, mergeFields, mergePrevTip, scheduledWriter, refreshIdentity as coreRefreshIdentity, heldBackByOf, unconnectedRelaysOf, unconnectedVersionsOf, IdentityChain, identityKeyFromSeed, isUserId, isValidName, nowSec, P2PError, peekIdentityDoc, pendingHeadSenders, canonicalRelayUrl, sealEnvelopeV3, storeCertResolver, storeSignerContext, TYP3, verifyDeviceCertV3, verifyRotationSignatures, } from "@peer2peer/core/v3";
|
|
16
|
+
import { addIdentityVersion, b64uDecode, b64uEncode, capAllowsKind, CircleChain, createCap, createDeviceCert, createIdentityDoc, decodeTyped, deviceKeysV3FromSecrets, displayAddress, displayFingerprint, getIdentityView, MAX_DEVICES, mergeFields, mergePrevTip, scheduledWriter, refreshIdentity as coreRefreshIdentity, heldBackByOf, heldBackForOf, heldBackHeadOf, unconnectedRelaysOf, unconnectedVersionsOf, IdentityChain, identityKeyFromSeed, isUserId, isValidName, nowSec, P2PError, peekIdentityDoc, pendingHeadSenders, canonicalRelayUrl, sealEnvelopeV3, storeCertResolver, storeSignerContext, TYP3, verifyDeviceCertV3, verifyRotationSignatures, } from "@peer2peer/core/v3";
|
|
16
17
|
import { FileDocBackend, FileTrustStoreV3 } from "@peer2peer/core/v3/node";
|
|
17
18
|
import { OverlayDocBackend, ReadOnlyTrustStoreV3 } from "./readonly.js";
|
|
18
19
|
import { basename, join } from "node:path";
|
|
@@ -136,6 +137,13 @@ export class App {
|
|
|
136
137
|
}
|
|
137
138
|
this.checkFrontKeys(keys);
|
|
138
139
|
this.setKeys(keys, self);
|
|
140
|
+
// A home that chose the OS keychain whose keys are still in keys.json (an interrupted move, or a
|
|
141
|
+
// rotation that swapped in a new identity's files): moved now (keystore.ts). Never on a read-only run.
|
|
142
|
+
if (!this.readOnly) {
|
|
143
|
+
const w = await finishPendingMove(this.state.keyStore);
|
|
144
|
+
if (w)
|
|
145
|
+
this.warn(w);
|
|
146
|
+
}
|
|
139
147
|
return true;
|
|
140
148
|
}
|
|
141
149
|
/**
|
|
@@ -506,11 +514,12 @@ export class App {
|
|
|
506
514
|
// Strict callers (publishing our own next version) must not build on a head they couldn't confirm.
|
|
507
515
|
if (opts.strict) {
|
|
508
516
|
// #79: relays core held the refresh back for count like the ones it names (see the incomplete case below).
|
|
509
|
-
const
|
|
517
|
+
const heldBy = own ? heldBackByOf(e) : [];
|
|
518
|
+
const unconnected = [...new Set([...unconnectedRelaysOf(e), ...(own ? await this.ownHeldBack(heldBy, heldBackForOf(e), heldBackHeadOf(e)) : [])])];
|
|
510
519
|
const versions = unconnectedVersionsOf(e);
|
|
511
520
|
const fb = e.reason === "chain-broken" ? await this.ownStrictFallback(userId, list, unconnected, versions, opts.setAside, refreshFrom) : undefined;
|
|
512
521
|
if (!fb)
|
|
513
|
-
throw new CliError("refresh_failed", `couldn't confirm the current identity document on the relays (${e.reason}): not publishing on a possibly stale head${this.unconnectedHint(unconnected, versions, userId)}`);
|
|
522
|
+
throw new CliError("refresh_failed", `couldn't confirm the current identity document on the relays (${e.reason}): not publishing on a possibly stale head${this.unconnectedHint(unconnected, versions, userId, heldBy)}`);
|
|
514
523
|
v = fb;
|
|
515
524
|
named = unconnected;
|
|
516
525
|
}
|
|
@@ -530,11 +539,13 @@ export class App {
|
|
|
530
539
|
}
|
|
531
540
|
// #79: relays core held the refresh back for (they sent a version of our identity that doesn't connect to
|
|
532
541
|
// a current one we hold and lists more than it) count like the relays it names as serving versions that
|
|
533
|
-
// don't connect: a rotation sets them aside, any other edit refuses and names them.
|
|
534
|
-
|
|
542
|
+
// don't connect: a rotation sets them aside, any other edit refuses and names them. Only when what they left
|
|
543
|
+
// out is a version our own devices published (ownHeldBack).
|
|
544
|
+
const heldBy = own ? (v.heldBackBy ?? []) : [];
|
|
545
|
+
const unconnected = [...new Set([...(v.unconnectedRelays ?? []), ...(own ? await this.ownHeldBack(heldBy, v.heldBackFor ?? [], v.heldBackHead) : [])])];
|
|
535
546
|
const fb = await this.ownStrictFallback(userId, list, unconnected, v.unconnectedVersions ?? [], opts.setAside, refreshFrom);
|
|
536
547
|
if (!fb)
|
|
537
|
-
throw new CliError("refresh_failed", `refreshing the identity document was cut short; try again${this.unconnectedHint(unconnected, v.unconnectedVersions ?? [], userId)}`);
|
|
548
|
+
throw new CliError("refresh_failed", `refreshing the identity document was cut short; try again${this.unconnectedHint(unconnected, v.unconnectedVersions ?? [], userId, heldBy)}`);
|
|
538
549
|
named = unconnected;
|
|
539
550
|
v = fb;
|
|
540
551
|
}
|
|
@@ -549,22 +560,76 @@ export class App {
|
|
|
549
560
|
await this.state.update("fetched", (cur = {}) => ({ next: { ...cur, [userId]: Math.max(cur[userId] ?? 0, now) }, result: undefined }));
|
|
550
561
|
return v;
|
|
551
562
|
}
|
|
563
|
+
/**
|
|
564
|
+
* #79, #92 follow-up: the relays core held a refresh of our own identity back for (`by`, they sent a head that
|
|
565
|
+
* would leave out the versions `left`), counted like the relays core names as serving versions that don't connect
|
|
566
|
+
* (a rotation sets them aside, the hint names them) only when one of `left` is our own current tip: a tip of our
|
|
567
|
+
* stored chain (never an old version a relay replays: that is an ancestor of what we hold, or not held at all)
|
|
568
|
+
* that our devices published (the publish log) and that the head held back for (`head`) revoked no device of (#99),
|
|
569
|
+
* or, when the head held back for (`head`) leaves this device out as a key holder (a thief's head against the owner's devices, #79), that a device a version in the publish log lists
|
|
570
|
+
* published (another owner device whose versions haven't reached this device's log yet, the provenance rule of
|
|
571
|
+
* ownBranchTip in rotation.ts). That provenance alone never counts against a head that still lists this device: the
|
|
572
|
+
* devices a logged version lists include ones the owner revoked since, and a version such a device signed, held
|
|
573
|
+
* here, must not get the relays serving the owner's revocation set aside. Otherwise none: a relay replaying an old
|
|
574
|
+
* version (history pruned past what the relays keep) can't get an honest relay set aside, and a relay that really
|
|
575
|
+
* holds the owner up can still be removed (`p2p relays remove`).
|
|
576
|
+
*/
|
|
577
|
+
async ownHeldBack(by, left, head) {
|
|
578
|
+
if (by.length === 0 || left.length === 0 || !this.keys)
|
|
579
|
+
return [];
|
|
580
|
+
const stored = await this.store.getIdentity(this.keys.userId);
|
|
581
|
+
if (!stored || stored.versions.length === 0)
|
|
582
|
+
return [];
|
|
583
|
+
const chain = IdentityChain.fromStored({ ...stored, pendingHeads: [], leftOut: [] });
|
|
584
|
+
const tips = new Set(chain.tips().map((t) => t.hash));
|
|
585
|
+
const published = new Set((await this.store.getPublishLog()).published);
|
|
586
|
+
// Unknown (an older core): as if it listed this device, so provenance alone never counts.
|
|
587
|
+
const headLeavesMeOut = head !== undefined && !head.keyholders.includes(this.did);
|
|
588
|
+
const trusted = headLeavesMeOut ? new Set([this.did, ...[...published].flatMap((h) => chain.get(h)?.devices ?? [])]) : new Set();
|
|
589
|
+
// #99: our own published tip V counts against a head that still lists this device only when that head lists
|
|
590
|
+
// every device V lists. A head that dropped one may be the owner's revocation, reached from another device while
|
|
591
|
+
// this one was offline longer than the relays keep the history between them: a relay still serving V must not get
|
|
592
|
+
// the relays serving that revocation set aside (the rotation would plan from V's stale device list). That case
|
|
593
|
+
// can't be told apart from a thief's head that keeps this device and drops another device V lists: whoever holds
|
|
594
|
+
// the key chooses what its head lists, so it can make this rule refuse. Refusing is the fail-closed choice (no
|
|
595
|
+
// relay is set aside on evidence the head's signer picks); the error then names the relays the refresh was held
|
|
596
|
+
// back for and says how to remove one (unconnectedHint's `heldBy`). An unknown head (an older core) revoked
|
|
597
|
+
// something, for all we know.
|
|
598
|
+
const revokedNone = (v) => head?.devices !== undefined && v.devices.every((d) => head.devices.includes(d));
|
|
599
|
+
const own = left.some((h) => {
|
|
600
|
+
const v = tips.has(h) ? chain.get(h) : undefined;
|
|
601
|
+
return v !== undefined && ((published.has(h) && (headLeavesMeOut || revokedNone(v))) || trusted.has(v.by));
|
|
602
|
+
});
|
|
603
|
+
return own ? [...by] : [];
|
|
604
|
+
}
|
|
552
605
|
/**
|
|
553
606
|
* For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
|
|
554
607
|
* core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
|
|
555
608
|
* so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
|
|
609
|
+
* #99 review: `heldBy`, the relays core held the refresh back for, are named too when they weren't counted
|
|
610
|
+
* (ownHeldBack refused, as when their head drops a device this device's current version lists), with what to do:
|
|
611
|
+
* nothing else names them.
|
|
556
612
|
*/
|
|
557
|
-
unconnectedHint(unconnected, versions, userId) {
|
|
613
|
+
unconnectedHint(unconnected, versions, userId, heldBy = []) {
|
|
558
614
|
if (userId !== this.keys?.userId)
|
|
559
615
|
return "";
|
|
616
|
+
const held = [...new Set(heldBy)].filter((r) => !unconnected.includes(r));
|
|
617
|
+
const heldHint = held.length === 0 ? "" : this.heldBackHint(held);
|
|
560
618
|
if (unconnected.length > 0) {
|
|
561
619
|
const one = unconnected.length === 1;
|
|
562
|
-
return
|
|
620
|
+
return `${heldHint}. ${unconnected.join(", ")} ${one ? "serves" : "serve"} versions of your identity, signed with your identity key, that don't connect to your history and that no relay holds the history of: if no device of yours published them, someone else holds your identity key. Remove ${one ? "that relay" : "those relays"} (\`p2p relays remove <url>\`) or rotate your identity (\`p2p identity rotate\`)`;
|
|
563
621
|
}
|
|
564
|
-
const from = [...new Set(versions.flatMap((x) => x.relays))];
|
|
622
|
+
const from = [...new Set(versions.flatMap((x) => x.relays))].filter((r) => !held.includes(r));
|
|
565
623
|
if (from.length === 0)
|
|
566
|
-
return
|
|
567
|
-
return
|
|
624
|
+
return heldHint;
|
|
625
|
+
return `${heldHint}. Newer versions of your identity from ${from.join(", ")} don't connect to the history this device holds yet; if one of those relays keeps serving versions no device of yours published, remove it (\`p2p relays remove <url>\`)`;
|
|
626
|
+
}
|
|
627
|
+
/** #99 review: the relays a refresh of our own identity was held back for, not set aside (ownHeldBack refused). */
|
|
628
|
+
heldBackHint(held) {
|
|
629
|
+
const one = held.length === 1;
|
|
630
|
+
return (`. ${held.join(", ")} ${one ? "serves" : "serve"} a newer version of your identity, signed with your identity key, that leaves out this device's current version and doesn't connect to it. ` +
|
|
631
|
+
`This device can't tell whether that is a change you made on another device (such as revoking a device there) or someone else holding your identity key, so ${one ? "that relay isn't" : "those relays aren't"} set aside automatically. ` +
|
|
632
|
+
`If no device of yours made that change, remove ${one ? "it" : "them"} (\`p2p relays remove <url>\`: that goes ahead on what your other relays confirm), then rotate your identity (\`p2p identity rotate\`)`);
|
|
568
633
|
}
|
|
569
634
|
/**
|
|
570
635
|
* #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
|
|
@@ -887,7 +952,7 @@ export class App {
|
|
|
887
952
|
const stored = await this.store.getIdentity(this.userId);
|
|
888
953
|
// Only devices a merge dropped come back: never one revoked along the head's ancestry, nor one
|
|
889
954
|
// core denies after a history jump.
|
|
890
|
-
const plan = stored && merges.length > 0 ? planReadd(IdentityChain.fromStored({ ...stored, pendingHeads: [] }), preTips, unionDevices, view.devices, head.hash, stored.denied ?? []) : { readd: [], skipped: [] };
|
|
955
|
+
const plan = stored && merges.length > 0 ? planReadd(IdentityChain.fromStored({ ...stored, pendingHeads: [], leftOut: [] }), preTips, unionDevices, view.devices, head.hash, stored.denied ?? []) : { readd: [], skipped: [] };
|
|
891
956
|
for (const d of plan.skipped)
|
|
892
957
|
this.warn(`device ${d} was dropped by the merge of your identity document's branches; link it again (this device's copy of the history can't prove it wasn't revoked)`);
|
|
893
958
|
const readd = plan.readd;
|
package/dist/cli.d.ts
CHANGED
|
@@ -147,6 +147,7 @@ export declare const realOps: {
|
|
|
147
147
|
MAX_GRAPH_PATHS: 64;
|
|
148
148
|
IX_CLOUD_ENV: readonly string[];
|
|
149
149
|
IX_KEEP: readonly string[];
|
|
150
|
+
branchSummary(hash: string, ver: number, by: readonly string[], relays: readonly string[]): rotation.BranchSummary;
|
|
150
151
|
readRotationState(home: string): Promise<rotation.RotationState | undefined>;
|
|
151
152
|
assertAdopted(app: App, userId: string): void;
|
|
152
153
|
adoptHome(app: App, src: string, tag: string): Promise<string>;
|
|
@@ -154,9 +155,7 @@ export declare const realOps: {
|
|
|
154
155
|
alertForeignRotations(app: App): Promise<void>;
|
|
155
156
|
friendVerdict(st: rotation.RotationState, peer: string): {
|
|
156
157
|
invite: boolean;
|
|
157
|
-
why
|
|
158
|
-
/** setup, "I already use Peer2Peer on another device": `p2p link join`, inline. No identity is made here, so no backup is asked. */
|
|
159
|
-
? /** setup, "I already use Peer2Peer on another device": `p2p link join`, inline. No identity is made here, so no backup is asked. */: string;
|
|
158
|
+
why?: string;
|
|
160
159
|
};
|
|
161
160
|
rotatePlan(app: App, opts?: rotation.RotateOptions): Promise<rotation.RotationPlan>;
|
|
162
161
|
rotateCancel(app: App): Promise<{
|
|
@@ -224,6 +223,7 @@ export declare const realOps: {
|
|
|
224
223
|
keyholder: boolean;
|
|
225
224
|
}>;
|
|
226
225
|
}>;
|
|
226
|
+
rotationLockOf: (home: string) => string;
|
|
227
227
|
DEVICE_SEEN_WINDOW_SEC: number;
|
|
228
228
|
RESEND_PER_HOUR: 50;
|
|
229
229
|
shellQuote(s: string): string;
|
|
@@ -257,7 +257,7 @@ export declare const realOps: {
|
|
|
257
257
|
}>;
|
|
258
258
|
removeUser(app: App, who: string): Promise<codes.RemoveResult>;
|
|
259
259
|
CODE_LABEL_MAX: 64;
|
|
260
|
-
codeHint: (code: string) => string;
|
|
260
|
+
codeHint: (code: string /** The token `front` rests on (main() keeps it in memory, never in the environment): re-checked against the home as the command finds it, and against the keys it loads (App.load). */) => string;
|
|
261
261
|
PLUGIN_INSTALL: string[];
|
|
262
262
|
CODEX_INSTALL_URL: "https://github.com/ix-infrastructure/Peer2Peer/blob/main/packages/codex-bridge/README.md#install";
|
|
263
263
|
CodePreviewReady: typeof codes.CodePreviewReady;
|
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";
|
|
@@ -106,6 +108,7 @@ const PERSON_ONLY = new Map([
|
|
|
106
108
|
["petname", "changes the names you know people by"],
|
|
107
109
|
["circle leave", "changes your circles"],
|
|
108
110
|
["held decline", "decides a held request for you"],
|
|
111
|
+
["keys backend", "moves your identity and device keys"],
|
|
109
112
|
]);
|
|
110
113
|
/** `identity rotate` options that do something beyond making or showing the plan. */
|
|
111
114
|
const ROTATE_ACTS = ["resume", "cancel", "exclude", "keep", "invite", "keepKeyholders", "backupFile", "contest", "resend", "yes", "branch"];
|
|
@@ -131,6 +134,9 @@ export function personOnlyOf(cmd) {
|
|
|
131
134
|
return args.length > 1 ? { what: args[1] === "on" || args[1] === "off" ? `circle hold <cid> ${args[1]}` : "circle hold", why } : undefined;
|
|
132
135
|
case "ix config":
|
|
133
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;
|
|
134
140
|
// Restore runs only on a fresh home and needs the phrase itself, typed or piped: that is the
|
|
135
141
|
// person's proof outside an agent's session (a fresh home has no person token yet, and a
|
|
136
142
|
// headless restore must keep working). Inside an agent's session it is refused, as `link join`.
|
|
@@ -328,6 +334,16 @@ export function buildProgram(deps) {
|
|
|
328
334
|
const a = (await io.prompt(`${q} [y/N] `)).trim().toLowerCase();
|
|
329
335
|
return a === "y" || a === "yes";
|
|
330
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
|
+
};
|
|
331
347
|
/** The command whose options `o` are (commander passes the same object it keeps). */
|
|
332
348
|
const cmdOf = (o) => ({ opts: () => o });
|
|
333
349
|
// ── pickers (prompt/): only with io.select, never with --json or --yes ──
|
|
@@ -517,6 +533,7 @@ export function buildProgram(deps) {
|
|
|
517
533
|
.option("--print-backup", "Print the backup phrase (in --json, as backup.phrase)")
|
|
518
534
|
.option("--no-backup", "Don't save or print the backup phrase now")
|
|
519
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")
|
|
520
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)")
|
|
521
538
|
.option("--json", "JSON output")
|
|
522
539
|
.action(run(async (app, o) => {
|
|
@@ -634,11 +651,87 @@ export function buildProgram(deps) {
|
|
|
634
651
|
lines.push(" ix not installing Ix. You won't be asked again; `p2p setup --ix` offers it again");
|
|
635
652
|
}
|
|
636
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
|
+
}
|
|
637
671
|
lines.push("", "Invite someone: p2p invite <their name> Join with a code: p2p join <code>");
|
|
638
672
|
return { json: r, human: lines.join("\n") };
|
|
639
673
|
},
|
|
640
674
|
// review L1: never cut short half-way through creating an identity (each step is still bounded).
|
|
641
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 }));
|
|
642
735
|
program
|
|
643
736
|
.command("whoami")
|
|
644
737
|
.description("Your address, fingerprint, devices, relays and document expiry")
|
|
@@ -647,6 +740,44 @@ export function buildProgram(deps) {
|
|
|
647
740
|
const r = await ops.whoami(app);
|
|
648
741
|
return { json: r, human: fmt.formatWhoami(r) };
|
|
649
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 }));
|
|
650
781
|
const backup = program.command("backup").description("The 24-word backup phrase of your identity key (§2.7)");
|
|
651
782
|
backup
|
|
652
783
|
.command("show")
|
|
@@ -1918,6 +2049,54 @@ export function buildProgram(deps) {
|
|
|
1918
2049
|
codexCommands(program, deps, io);
|
|
1919
2050
|
return program;
|
|
1920
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
|
+
}
|
|
1921
2100
|
/** The running `p2p` script (the bundled p2p.mjs, or dist/bin.js), for Codex to start. */
|
|
1922
2101
|
function selfScript(deps) {
|
|
1923
2102
|
const p = deps.scriptPath ?? process.argv[1] ?? "";
|
|
@@ -1960,6 +2139,23 @@ function codexCommands(program, deps, io) {
|
|
|
1960
2139
|
try {
|
|
1961
2140
|
const script = selfScript(deps);
|
|
1962
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
|
+
}
|
|
1963
2159
|
}
|
|
1964
2160
|
catch (e) {
|
|
1965
2161
|
fail(Boolean(o.json), e);
|
|
@@ -2090,7 +2286,10 @@ export async function main(argvIn, deps) {
|
|
|
2090
2286
|
front,
|
|
2091
2287
|
env,
|
|
2092
2288
|
...(byToken && deps.front !== true ? { frontToken: token, frontFresh: !projects.identityHere(home) } : {}),
|
|
2093
|
-
|
|
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 } : {}),
|
|
2094
2293
|
};
|
|
2095
2294
|
}
|
|
2096
2295
|
// `--no-input` anywhere before `--`: no pickers, no questions (as a script would run).
|
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
|