@peer2peer/cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.0/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.
3
+ `@peer2peer/cli` is the standalone `p2p` command for [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.2/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
- It is core software: it never imports Ix or Kartr (`node scripts/check-boundaries.mjs`).
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.0/docs/run-a-relay.md)), or use one your community runs. No relay is built in yet. Tell `p2p` about it once:
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.2/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
@@ -15,7 +15,7 @@ export P2P_DEFAULT_RELAYS=wss://relay.example.org/v3 # 1–5, comma separated
15
15
  **Ann:**
16
16
 
17
17
  ```sh
18
- p2p setup # makes your key (name: your OS user); offers to save the backup phrase
18
+ p2p setup # asks how you're joining (link a device you already use, an invite, or new); new: your relay, your key, the backup phrase
19
19
  p2p invite ben # prints a one-time code: relay.example.org/K7QM-3XPD-9TWA-HF2N-6RJC
20
20
  ```
21
21
 
@@ -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.0/docs/concepts.md#projects-project-boundaries).
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.2/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`):
@@ -53,13 +53,13 @@ Every command takes `--json`. With it, a command prints exactly one JSON object
53
53
 
54
54
  **On a terminal** (stdin and stdout both a TTY, no `--json`, `--yes`, `--no-input` or `CI`, and not inside an agent's tool call), a command missing an argument it could take from a list asks for it with a picker: arrow keys or j/k move, space selects, enter confirms, typing filters, Esc or Ctrl-C cancels (exit 1, nothing done). `invite` with no `--circle` picks the circles and the expiry; `join` asks Join/Cancel; `circle default|invite|leave|members`, `held approve|decline`, `remove`, `unfriend`, `block`, `unblock`, `invites revoke`, `send` (recipient, then text) and `trust add|remove` pick what's missing (`trust add` still takes the fingerprint typed). Output on a terminal is laid out (tables, colour for state, relative times; `NO_COLOR`, `FORCE_COLOR` and `TERM=dumb` are respected), and `p2p` alone shows a home screen. Piped or redirected, every command prints and exits exactly as before. `--no-input` (anywhere on the line) turns off pickers and questions on a terminal too.
55
55
 
56
- On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded) to show their health; piped, they don't. `send` without `--from-session` sends from the `tui` session, shares that session with the recipient when it isn't yet ("shared session tui with <name>", so the message can land there and replies reach `p2p tui`; undone if the send fails; never with `--from-session` or off a terminal, and an agent's `p2p send` without `--from-session` is refused by the guards; a send from `p2p tui` does the same), and says so ("sent from session tui; replies show in `p2p tui`"). `trust add` lists names (or petnames) only: you type the fingerprint as the person gave it to you. A signal (SIGINT, SIGTERM, SIGHUP) during a picker restores the terminal, then ends the process as the signal would.
56
+ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded) to show their health; piped, they don't. `send` without `--from-session` sends from the `tui` session, shares that session with the recipient when it isn't yet ("shared session tui with <name>", so the message can land there and replies reach `p2p tui`; undone if the send fails before anything went out and the roster is still the one the share wrote; never with `--from-session` or off a terminal, and an agent's `p2p send` without `--from-session` is refused by the guards; a send from `p2p tui` does the same), and says so ("sent from session tui; replies show in `p2p tui`"). `trust add` lists names (or petnames) only: you type the fingerprint as the person gave it to you. A signal (SIGINT, SIGTERM, SIGHUP) during a picker restores the terminal, then ends the process as the signal would.
57
57
 
58
58
  **Agents:** the pickers stay off inside Claude Code's and Codex's tool calls (`CLAUDECODE`, `CODEX_THREAD_ID`, `CODEX_SESSION_ID`). That check knows only those two: any other agent or automation that runs `p2p` in a terminal should pass `--no-input` or set `CI=1`.
59
59
 
60
60
  | Command | What it does |
61
61
  |---|---|
62
- | `setup [--name n] [--relay url]… [--backup-file [path] \| --print-backup \| --no-backup]` | 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`. |
62
+ | `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. |
63
63
  | `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. |
64
64
  | `whoami` | Shows your address and grouped fingerprint, devices, relays and document expiry. |
65
65
  | `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`. |
@@ -84,12 +84,15 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
84
84
  | `circle join <link> [--wait s] [--yes] [--allow-private-relay]` | Bootstraps the full chain and confirms it with the owner and one other member before joining (§3.3). A link naming a relay on a private address needs the same opt-in as `accept`. |
85
85
  | `circle leave`, `ls`, `members <cid>`, `propose <cid> add\|remove\|promote\|demote\|rename …`, `transfer <cid> <user>` (`--accept` to consent), `policy <cid> invite\|open`, `default <cid>\|--none` | The rest of circle management. |
86
86
  | `ls [--all]` (JSON: `peers[]` with `rule`/`viewerRule` (how you're authorised), `senderRule`, `circle`; and `relays: {listed, connected, failed: [{url, reason}]}`) | Live sessions of friends, circle-mates and your other devices, with the sanitized summary and files. A session is live for 150 s after the `ts` of its last status. |
87
- | `send --from-session <sid> --to <user>[/<sid>\|" [ref]"] [--notify-when-idle] [--stdin] [--project-dir d]… [text…\|-]` | Refused (`not_shared`) to anyone outside the session's projects' audience (see `project`). Text comes from the arguments, or from stdin with `--stdin` or a single `-` (stdin is also read when there's no text and no `--notify-when-idle`). A pure `--notify-when-idle` subscription never waits on stdin. The output says how many relays the message was delivered via. A session that isn't live but was seen within the last 24 hours still gets it: the relays hold it until that session reconnects (`queued: true, state: "offline", lastSeen`); with no ref and several such sessions the send is `ambiguous`. When no relay can be reached, the sealed message waits in this device's outbox and `watch` sends it later (`queued: true, state: "outbox"`); either way it expires after 7 days. Any other "via 0" is an error. "Delivered" means a relay has it: when the target session is live and its status advertises `receipts.v1` the message asks for delivery receipts (`receipts: "requested"`, `receiptId`), which come back to the sending session's `watch` as `p2p.receipt` lines (`outcome`: `shown`, `held`, `declined`, `expired` or `ended`); otherwise `receipts: "unsupported"` (an older client, or one with receipts off). |
88
- | `receipt <event> --from-session <sid> --outcome shown\|held\|declined\|expired\|ended` | For the front end that shows messages: what became of a `p2p.message` that carried `receipt: true`. The CLI decides whether a receipt goes out (§4.3 "Delivery receipts"): receipts on, the session not private, each outcome once and nothing after a final one, an ended session's copy only ever as `ended`, at most 30 a minute to one user, a fair share past 120 a minute in all, and never more than 240. `{sent, outcome?, reason?}`, never an error for "nothing to send". |
87
+ | `send --from-session <sid> --to <user>[/<sid>\|" [ref]"] [--notify-when-idle] [--stdin] [--project-dir d]… [text…\|-]` | Refused (`not_shared`) to anyone outside the session's projects' audience (see `project`). Another session of yours on this device is reached only when named (`<you> [ref]` or `<you>/<sid>`; a bare `--to <you>` never picks one here), through your relay sealed to this device, under the same rules as your other devices; the sending session itself is refused (`self_send`). This device records which session sent it, and whether you did from your own terminal, so the receiving session can name the sender and hold an agent session's message where it would hold a peer's (nothing about it goes on the wire). Text comes from the arguments, or from stdin with `--stdin` or a single `-` (stdin is also read when there's no text and no `--notify-when-idle`). A pure `--notify-when-idle` subscription never waits on stdin. The output says how many relays the message was delivered via. A session that isn't live but was seen within the last 24 hours still gets it: the relays hold it until that session reconnects (`queued: true, state: "offline", lastSeen`); with no ref and several such sessions the send is `ambiguous`. When no relay can be reached, the sealed message waits in this device's outbox and `watch` sends it later (`queued: true, state: "outbox"`); either way it expires after 7 days. Any other "via 0" is an error. "Delivered" means a relay has it: when the target session is live and its status advertises `receipts.v1` the message asks for delivery receipts (`receipts: "requested"`, `receiptId`), which come back to the sending session's `watch` as `p2p.receipt` lines (`outcome`: `shown`, `held`, `declined`, `expired` or `ended`); otherwise `receipts: "unsupported"` (an older client, or one with receipts off). |
88
+ | `own-agents [hold\|deliver [--devices <did…\|all-other>]\|check <did>]` | Whether your own agent sessions' messages skip the hold in a session that approves its own tool calls. `hold` by default (it clears both settings); `deliver` lets every one through, `deliver --devices` only those from the named other devices (or all of them), never this device's. Both are yours alone (refused inside an agent's session). `check <did>` is for front ends, at delivery time: `{did, deliver}`. |
89
+ | `receipt <event> --from-session <sid> --outcome shown\|held\|declined\|expired\|ended` | For the front end that shows messages: what became of a `p2p.message` that carried `receipt: true`. Only the session's front end (its token) runs it, or, outside an agent's session, a caller for a session no front end registered (`refused` otherwise). The CLI decides whether a receipt goes out (§4.3 "Delivery receipts"): receipts on, the session not private, each outcome once and nothing after a final one, an ended session's copy only ever as `ended`, at most 30 a minute to one user, a fair share past 120 a minute in all, and never more than 240. `{sent, outcome?, reason?}`, never an error for "nothing to send". |
89
90
  | `trust ls`, `trust add\|remove <user\|circle:<cid\|name>>`, `trust check <userId>` | Who may message a session that approves its own tool calls without the hold (front ends such as the Claude mod read it). Users by full userId or `name@fingerprint` (resolved by fingerprint; a bare name is refused), circles by id or name, stored in config.json (`trust`, 0600). A trusted circle covers its standing members as its verified state has them when checked, which is anyone its owner or admins add: someone removed from it, or this user leaving it, ends their trust. An open circle can't be trusted (`open_circle`), and a trusted circle that turns open trusts nobody until it is invite-only again. Changes are made under the state lock, so concurrent `trust` and `receipts` changes never lose one. A blocked user is never trusted. `trust ls --json` lists `users`, `circles` (with their current `members`) and everyone `trusted` now. |
91
+ | `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. |
90
92
  | `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. |
91
- | `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 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`. |
92
- | `project share [<circle>…] [--person u]… [--add] [--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.0/docs/concepts.md#projects-project-boundaries)). `share` with nothing named: a picker on a terminal, else your default circle. A committed `.p2p-private` makes a repository private; nothing in a repository can share it |
93
+ | `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`. |
94
+ | `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.2/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 |
95
+ | `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. |
93
96
  | `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). |
94
97
  | `watch --session <sid> --jsonl` | One JSON line per accepted event. Stays connected and reconnects silently. |
95
98
  | `doctor [<user>]` | Explains, in plain words, why sessions are or aren't visible. See [Doctor](#doctor). |
@@ -117,7 +120,7 @@ Every line has `kind`, `id`, `at` (ms) and a verified `from: {userId, did, addre
117
120
  ### Short-code JSON
118
121
 
119
122
  ```
120
- p2p setup --json {userId, address, fingerprint, did, relays, created, published?, failed?, backup?: {file} | {phrase}}
123
+ p2p setup --json {userId, address, fingerprint, did, relays, created, published?, failed?, backup?: {file} | {phrase}, ix?: {found, enabled, enabledNow?, hint?}}
121
124
  (backup.phrase only with --print-backup; no backup key when nothing was saved or printed)
122
125
  p2p invite --json {code: "<relay>/K7QM-3XPD-9TWA-HF2N-6RJC", line, relay, label, to: {userId,address}|null,
123
126
  circle: {cid,name}|null, circles, web, expiresAt (unix s), uses: 1, lid, (lid: the relay lookup id, not secret; the same lid is on p2p.joined)
@@ -212,7 +215,7 @@ Then this home becomes the new identity's; the old one is archived in `<home>/ro
212
215
 
213
216
  That is why loading is opt-in (`src/extensions.ts`):
214
217
 
215
- - **Which:** only the namespaces registered in docs/protocol.md §8.3 (`ix`, `kartr`), and only those you enabled: `p2p extensions enable ix` (writes `extensions: ["ix"]` to `<home>/config.json`; `p2p extensions disable ix` undoes it), or `P2P_EXTENSIONS=ix` set in your own shell for one environment (`none` turns all off; it overrides config.json; `config` defers to config.json, which is what the Claude mod passes so that only config.json opt-in counts for the `p2p` it runs). Anything else in the list is ignored with a warning. Nothing enabled, nothing loaded, even when a package is installed.
218
+ - **Which:** only the namespaces registered in docs/protocol.md §8.3 (such as `ix`), and only those you enabled: `p2p extensions enable ix` (writes `extensions: ["ix"]` to `<home>/config.json`; `p2p extensions disable ix` undoes it), or `P2P_EXTENSIONS=ix` set in your own shell for one environment (`none` turns all off; it overrides config.json; `config` defers to config.json, which is what the Claude mod passes so that only config.json opt-in counts for the `p2p` it runs). Anything else in the list is ignored with a warning. Nothing enabled, nothing loaded, even when a package is installed.
216
219
  - **Where:** only explicit `node_modules` directories: each `P2P_EXTENSION_PATH` entry (a directory or its `node_modules`), then the CLI's own sibling `node_modules` when the CLI is installed as a package (a global `npm i -g @peer2peer/cli @peer2peer/ext-ix` puts both there). There is no walk-up through parent directories, no `NODE_PATH` and no global folders; the package's entry file must lie inside the package.
217
220
  - **Announced:** the first time an extension loads from a new location, `p2p` says so on stderr, with the resolved file (`<home>/extension-locations.json` remembers it).
218
221
  - **How:** the resolved file is loaded with a dynamic `import()` of its URL. That loader is the one computed import `check-boundaries` allows in core (with the committed bundle that inlines it); static and literal-dynamic imports of `@peer2peer/ext-*` stay forbidden, and no core `package.json` may list one.
@@ -274,7 +277,7 @@ These are the places where the spec left room. They are listed so other clients
274
277
  |---|---|
275
278
  | **1 People** | Friends and circle-mates with a live (●) or offline (○) dot, their sessions with label, `[ref]`, state, the one-line status, repo and branch, edited files, and each session's subagents nested under it. `m` (or Enter) messages the person or session; `d` runs the doctor for them. |
276
279
  | **2 Held** | First contacts, circle invites and join requests (`p2p held`), and messages your Codex sessions hold (`p2p codex held`). `a` accepts or delivers and `x` declines, each after a confirm (a Codex release asks for the code its window shows instead). `t` is *Always deliver from …* for a held message: it shows the sender's fingerprint, and you type its first four characters to confirm (a `y` or a paste doesn't count). The message is released first, and the trust (`p2p trust add`) is saved only once that went through. Messages the Claude Code mod holds live in Claude Code (its `/peers` panel), where the CLI can't see them: the screen says so instead of listing them. |
277
- | **3 Messages** | Recent messages received and sent: delivery receipts as they come back (`shown`, `held`, `declined`, `expired`, `ended`), and messages waiting at the relays for an offline session or in this device's outbox, with when the session was last seen. Enter opens a message; `r` replies. The TUI sends no receipts: its session is private (no status, no roster), so senders don't ask it for any, and a `shown` would only tell them that it exists and when you read it. At most the 100 newest messages are kept in memory. |
280
+ | **3 Messages** | Recent messages received and sent: delivery receipts as they come back (`shown`, `held`, `declined`, `expired`, `ended`), and messages waiting at the relays for an offline session or in this device's outbox, with when the session was last seen. Enter opens a message; `r` replies; `h` switches between every session's messages and your inbox only (messages to you, and this window's). Older ones, and what your agent sessions sent, come from the message history (`p2p history`), 30 days by default. The TUI sends no receipts: its session is private (no status, no roster), so senders don't ask it for any, and a `shown` would only tell them that it exists and when you read it. At most the 100 newest messages are kept in memory. |
278
281
  | **4 Send** | Pick a session or a person, type, Enter: the same path as `p2p send`, from the TUI's own session (`tui`, or `--session`). Replies come back to it live. |
279
282
  | **5 Health** | Each relay up or down, with what its `/.well-known/p2p-relay.json` says (open or members-only, software, proof-of-work), and the doctor's checks (identity, document expiry, clock, sharing). `r` runs the doctor again. |
280
283
 
@@ -323,11 +326,14 @@ Without a user, it checks this device:
323
326
  - the clock against the relays' (things signed more than 5 minutes off are refused);
324
327
  - the default circle and whether you stand in it (with none, new sessions are private);
325
328
  - which live sessions are shared, and with whom; when this device last posted a status (the mod does every 60 s) and when a `watch` last moved its cursor. Where nothing local says, it answers `?`;
329
+ - 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);
326
330
  - 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`).
327
331
 
332
+ 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.2/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`.
333
+
328
334
  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`.
329
335
 
330
- It's read-only: it publishes nothing, sends nothing, never acks what's queued, and leaves `P2P_HOME` byte-for-byte as it found it. What it refreshes (a friend's document, say) lands in an in-memory overlay that is gone when it exits, so a step that times out and finishes late can't write either. It loads no extension (loading one runs its code and records where it came from). Its bounds, with T = `P2P_DOCTOR_TIMEOUT_MS` (default 5000, never more than `P2P_CONNECT_TIMEOUT_MS`): each relay probe takes at most 2T (the whole connect, then one round trip; relays are probed in parallel, beside one HTTP request of at most T), the friend's document refresh at most 2T, and each local step at most T. It contacts at most 5 of a peer's relays, whatever their (possibly forked) document lists, and keeps no answer body from them. The usual command deadline (`P2P_COMMAND_TIMEOUT_SEC`, 60 s) caps the whole run, so an unreachable relay costs seconds, not a hang. The output never holds keys, capabilities, certificates, invite or link codes, or envelopes. In `--json`, `checks[]` has `{id, status: "ok"|"fail"|"unknown", title, detail, fix?}` and `summary` counts them; the exit code is 0 whatever the checks say. In Claude Code, `/peers doctor [user]` runs it.
336
+ It's read-only: it publishes nothing, sends nothing, never acks what's queued, and leaves `P2P_HOME` byte-for-byte as it found it. What it refreshes (a friend's document, say) lands in an in-memory overlay that is gone when it exits, so a step that times out and finishes late can't write either. It loads no extension (loading one runs its code and records where it came from). Its bounds, with T = `P2P_DOCTOR_TIMEOUT_MS` (default 5000, never more than `P2P_CONNECT_TIMEOUT_MS`): each relay probe takes at most 2T (the whole connect, then one round trip; relays are probed in parallel, beside one HTTP request of at most T), the friend's document refresh at most 2T, and each local step at most T. It contacts at most 5 of a peer's relays, whatever their (possibly forked) document lists, and keeps no answer body from them. The usual command deadline (`P2P_COMMAND_TIMEOUT_SEC`, 60 s) caps the whole run, so an unreachable relay costs seconds, not a hang. The output never holds keys, capabilities, certificates, invite or link codes, or envelopes. In `--json`, `checks[]` has `{id, status: "ok"|"fail"|"unknown", title, detail, fix?}`, `summary` counts them, and `dataFlow` (this device only) is the section above; the exit code is 0 whatever the checks say. In Claude Code, `/peers doctor [user]` runs it.
331
337
 
332
338
  ## Windows
333
339
 
package/dist/app.d.ts CHANGED
@@ -6,6 +6,15 @@ import type { Pretty } from "./pretty.js";
6
6
  import { CliState, type KeysDoc, type SelfDoc } from "./state.js";
7
7
  import { type Progress } from "./progress.js";
8
8
  import type { ExtensionRegistry } from "./extensions.js";
9
+ /**
10
+ * #67: relays a strict refresh of our own identity may leave out when it can't confirm the head over all of
11
+ * them (App.ownStrictFallback): the ones an edit removes, and (rotation) the ones that sent versions it
12
+ * couldn't connect.
13
+ */
14
+ export interface SetAside {
15
+ relays?: readonly string[];
16
+ unconnected?: boolean;
17
+ }
9
18
  export interface Io {
10
19
  /** Human output (stdout). */
11
20
  out(s: string): void;
@@ -187,7 +196,13 @@ export declare class App {
187
196
  /** Connects and handles everything queued for this device. */
188
197
  connectAndDrain(): Promise<RelayPool>;
189
198
  close(): Promise<void>;
199
+ /**
200
+ * Our own identity's view. Pending heads (core #35) never narrow it: they are for trusting others'
201
+ * devices, and a version only the identity key signed must not stop this device from editing or
202
+ * rotating the identity (#65 review M1).
203
+ */
190
204
  ownView(): Promise<IdentityView>;
205
+ /** The stored view of `userId`; our own identity's never narrowed by pending heads (#65 re-review N1, see ownView). */
191
206
  view(userId: string): Promise<IdentityView | undefined>;
192
207
  /**
193
208
  * Network I/O for core's refreshIdentity (§5.6), per relay so core can cap
@@ -200,12 +215,51 @@ export declare class App {
200
215
  * gap filling, automatic jumps only over unanchored history). This is the
201
216
  * only way an identity enters the store: bundled documents never do.
202
217
  * Failures leave the held view (or none) and are reported as a warning.
218
+ *
219
+ * `setAside` (#67, strict refreshes of our own identity only): relays to leave out when the refresh over
220
+ * all of them can't confirm the head. See ownStrictFallback.
203
221
  */
204
222
  refreshIdentity(userId: string, relays: readonly string[], opts?: {
205
223
  force?: boolean;
206
224
  quiet?: boolean;
207
225
  strict?: boolean;
226
+ setAside?: SetAside;
208
227
  }): Promise<IdentityView | undefined>;
228
+ /**
229
+ * For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
230
+ * core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
231
+ * so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
232
+ */
233
+ private unconnectedHint;
234
+ /**
235
+ * #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
236
+ * identity edit that removes relays (`setAside.relays`: the ones it removes), or a rotation step
237
+ * (`setAside.unconnected`: the relays that sent versions the refresh couldn't connect), it is retried over
238
+ * the other listed relays, and the caller goes ahead only if that refresh is complete.
239
+ *
240
+ * Why this is safe:
241
+ * - The strict refresh is there so we don't fork our own chain by building on a stale head (review H2):
242
+ * a newer version another of our key holders published went to every relay the document lists. The
243
+ * relays kept must still give a complete refresh, so a newer version any of them serves is still found,
244
+ * connected and built on (or, far behind, the refresh is incomplete and the edit refused: trying again
245
+ * goes on where the walk stopped). Leaving a relay out is what the strict refresh already allows when
246
+ * that relay doesn't answer.
247
+ * - Which relays are left out is the user's choice (the ones the edit removes) or each relay's own
248
+ * evidence (it sent identity-key-signed versions that don't connect): one relay can't get another left
249
+ * out. Any other edit still refuses while such a relay is listed, and names it (fork and compromise
250
+ * detection stay: the user is told someone else may hold the key).
251
+ * - What is published is still head.ver + 1 on the head the kept relays confirmed: a relay left out can't
252
+ * make it lower, or make it fork from anything but what those relays serve.
253
+ * - Nothing is left out when no relay would be left; the kept relays' refresh must reach one of them.
254
+ * - #67 review F1: core names a relay only for versions on a dead gap (asked of every relay, held by
255
+ * none), never one whose genuine gap the walk merely didn't reach. And the confirmed head must not be
256
+ * below any version the full refresh left unconnected, unless every relay that sent that version is set
257
+ * aside: a lagging kept relay can't "confirm" a stale head while another relay serves a newer version.
258
+ * (Pending heads stored by earlier refreshes can't be traced to a relay; a relay still serving a newer
259
+ * version shows it in this refresh.)
260
+ * Returns the view, or undefined when this doesn't apply (the caller then refuses as before).
261
+ */
262
+ private ownStrictFallback;
209
263
  /** Relays a (bundled, unverified) identity document lists: only a hint for where to refresh from. */
210
264
  static relaysOf(docJws: string | undefined): string[];
211
265
  /** The view of `userId`, refreshed from the relays its document lists (or `hint`, then ours, when unknown). */
@@ -261,6 +315,8 @@ export declare class App {
261
315
  restoring?: boolean;
262
316
  /** §2.8 step 6: the old identity's final version: no devices, no key holders, carrying the statement (P3). */
263
317
  rotation?: RotationStatement;
318
+ /** #67: relays this edit removes (see ownStrictFallback). */
319
+ removing?: readonly string[];
264
320
  }): Promise<{
265
321
  doc: string;
266
322
  ver: number;
@@ -307,7 +363,34 @@ export declare class App {
307
363
  extraCaps?: readonly string[];
308
364
  hint?: readonly string[];
309
365
  onlyDevices?: readonly string[];
366
+ /** Called with each copy's device and seq once they are known, before any copy goes out. */
367
+ beforeSend?: (copies: {
368
+ did: string;
369
+ seq: number;
370
+ }[]) => Promise<void>;
310
371
  }): Promise<Delivery>;
372
+ /**
373
+ * Seals `plaintext` for `to` exactly as deliver does (the same devices, a fresh seq each, the same
374
+ * relays and caps) and sends nothing: copies for the outbox to send later (outbox.ts).
375
+ */
376
+ seal(to: string, kind: EnvelopeKindV3, session: {
377
+ own: string;
378
+ sid: string;
379
+ }, plaintext: object, opts?: {
380
+ onlyDevices?: readonly string[];
381
+ beforeSend?: (copies: {
382
+ did: string;
383
+ seq: number;
384
+ }[]) => Promise<void>;
385
+ }): Promise<{
386
+ did: string;
387
+ env: string;
388
+ targets: {
389
+ relay: string;
390
+ cap?: string;
391
+ }[];
392
+ }[]>;
393
+ private sealCopies;
311
394
  /** Delivers to our other devices, when there are any (sync, §4.3). */
312
395
  syncOwn(body: Record<string, unknown>): Promise<Delivery | undefined>;
313
396
  }
package/dist/app.js CHANGED
@@ -12,7 +12,7 @@
12
12
  import { personTokenOk } from "./projects.js";
13
13
  import { confirmOnTty } from "./tty-confirm.js";
14
14
  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, IdentityChain, identityKeyFromSeed, isUserId, isValidName, nowSec, P2PError, peekIdentityDoc, canonicalRelayUrl, sealEnvelopeV3, storeCertResolver, storeSignerContext, TYP3, verifyDeviceCertV3, verifyRotationSignatures, } from "@peer2peer/core/v3";
15
+ import { addIdentityVersion, b64uDecode, b64uEncode, capAllowsKind, CircleChain, createCap, createDeviceCert, createIdentityDoc, decodeTyped, deviceKeysV3FromSecrets, displayAddress, displayFingerprint, getIdentityView, MAX_DEVICES, mergeFields, mergePrevTip, scheduledWriter, refreshIdentity as coreRefreshIdentity, unconnectedRelaysOf, unconnectedVersionsOf, IdentityChain, identityKeyFromSeed, isUserId, isValidName, nowSec, P2PError, peekIdentityDoc, canonicalRelayUrl, sealEnvelopeV3, storeCertResolver, storeSignerContext, TYP3, verifyDeviceCertV3, verifyRotationSignatures, } from "@peer2peer/core/v3";
16
16
  import { FileDocBackend, FileTrustStoreV3 } from "@peer2peer/core/v3/node";
17
17
  import { OverlayDocBackend, ReadOnlyTrustStoreV3 } from "./readonly.js";
18
18
  import { basename, join } from "node:path";
@@ -397,15 +397,21 @@ export class App {
397
397
  }
398
398
  // -------------------------------------------------------------------------
399
399
  // Identity documents (§2.5, §5.6)
400
+ /**
401
+ * Our own identity's view. Pending heads (core #35) never narrow it: they are for trusting others'
402
+ * devices, and a version only the identity key signed must not stop this device from editing or
403
+ * rotating the identity (#65 review M1).
404
+ */
400
405
  ownView() {
401
- return getIdentityView(this.store, this.userId).then((v) => {
406
+ return getIdentityView(this.store, this.userId, { ignorePending: true }).then((v) => {
402
407
  if (!v)
403
408
  throw new CliError("no_identity", "this device holds no identity document for its user");
404
409
  return v;
405
410
  });
406
411
  }
412
+ /** The stored view of `userId`; our own identity's never narrowed by pending heads (#65 re-review N1, see ownView). */
407
413
  async view(userId) {
408
- return getIdentityView(this.store, userId);
414
+ return getIdentityView(this.store, userId, userId === this.keys?.userId ? { ignorePending: true } : {});
409
415
  }
410
416
  /**
411
417
  * Network I/O for core's refreshIdentity (§5.6), per relay so core can cap
@@ -429,6 +435,9 @@ export class App {
429
435
  * gap filling, automatic jumps only over unanchored history). This is the
430
436
  * only way an identity enters the store: bundled documents never do.
431
437
  * Failures leave the held view (or none) and are reported as a warning.
438
+ *
439
+ * `setAside` (#67, strict refreshes of our own identity only): relays to leave out when the refresh over
440
+ * all of them can't confirm the head. See ownStrictFallback.
432
441
  */
433
442
  async refreshIdentity(userId, relays, opts = {}) {
434
443
  const fetched = (await this.state.get("fetched"))?.[userId];
@@ -442,36 +451,123 @@ export class App {
442
451
  throw new CliError("refresh_failed", `no relays to refresh ${userId} from`);
443
452
  return held;
444
453
  }
454
+ const refreshFrom = (rs) => step(this.progress, `refreshing ${userId}'s identity document from ${rs.join(", ")}`, () => coreRefreshIdentity(this.store, userId, this.fetcher(), { relays: rs }));
455
+ let v;
445
456
  try {
446
- const v = await step(this.progress, `refreshing ${userId}'s identity document from ${list.join(", ")}`, () => coreRefreshIdentity(this.store, userId, this.fetcher(), { relays: list }));
447
- if (v.incomplete) {
448
- if (opts.strict)
449
- throw new CliError("refresh_failed", "refreshing the identity document was cut short; try again");
457
+ v = await refreshFrom(list);
458
+ }
459
+ catch (e) {
460
+ if (!(e instanceof P2PError))
461
+ throw e;
462
+ // Strict callers (publishing our own next version) must not build on a head they couldn't confirm.
463
+ if (opts.strict) {
464
+ const unconnected = unconnectedRelaysOf(e);
465
+ const versions = unconnectedVersionsOf(e);
466
+ const own = e.reason === "chain-broken" ? await this.ownStrictFallback(userId, list, unconnected, versions, opts.setAside, refreshFrom) : undefined;
467
+ if (!own)
468
+ 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)}`);
469
+ v = own;
470
+ }
471
+ else {
472
+ if (e.reason === "chain-broken" && held && !opts.quiet) {
473
+ this.warn(`${await this.addressOf(userId)}'s newest identity document doesn't connect to the history held here (§2.5 history gap); keeping the held one`);
474
+ }
475
+ return held;
476
+ }
477
+ }
478
+ if (v.incomplete) {
479
+ if (!opts.strict) {
450
480
  // Cut short by core's work bound: the head may be stale. Not refreshed; don't act on it as fresh.
451
481
  if (!opts.quiet)
452
482
  this.warn(`refreshing ${await this.addressOf(userId)}'s identity document was cut short; using what was held before (try again)`);
453
483
  return held;
454
484
  }
455
- // Recorded moments ago by another p2p process of this home (a watch and a command refresh
456
- // the same people in a burst): no write. Only ever leaves the time a little older, so the
457
- // next refresh comes no later.
458
- const now = Date.now();
459
- const last = (await this.state.get("fetched"))?.[userId];
460
- if (last === undefined || last < now - FETCHED_SLACK_MS)
461
- await this.state.update("fetched", (cur = {}) => ({ next: { ...cur, [userId]: Math.max(cur[userId] ?? 0, now) }, result: undefined }));
462
- return v;
485
+ const own = await this.ownStrictFallback(userId, list, v.unconnectedRelays ?? [], v.unconnectedVersions ?? [], opts.setAside, refreshFrom);
486
+ if (!own)
487
+ throw new CliError("refresh_failed", `refreshing the identity document was cut short; try again${this.unconnectedHint(v.unconnectedRelays ?? [], v.unconnectedVersions ?? [], userId)}`);
488
+ v = own;
489
+ }
490
+ // Recorded moments ago by another p2p process of this home (a watch and a command refresh
491
+ // the same people in a burst): no write. Only ever leaves the time a little older, so the
492
+ // next refresh comes no later.
493
+ const now = Date.now();
494
+ const last = (await this.state.get("fetched"))?.[userId];
495
+ if (last === undefined || last < now - FETCHED_SLACK_MS)
496
+ await this.state.update("fetched", (cur = {}) => ({ next: { ...cur, [userId]: Math.max(cur[userId] ?? 0, now) }, result: undefined }));
497
+ return v;
498
+ }
499
+ /**
500
+ * For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
501
+ * core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
502
+ * so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
503
+ */
504
+ unconnectedHint(unconnected, versions, userId) {
505
+ if (userId !== this.keys?.userId)
506
+ return "";
507
+ if (unconnected.length > 0) {
508
+ const one = unconnected.length === 1;
509
+ return `. ${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\`)`;
510
+ }
511
+ const from = [...new Set(versions.flatMap((x) => x.relays))];
512
+ if (from.length === 0)
513
+ return "";
514
+ return `. 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>\`)`;
515
+ }
516
+ /**
517
+ * #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
518
+ * identity edit that removes relays (`setAside.relays`: the ones it removes), or a rotation step
519
+ * (`setAside.unconnected`: the relays that sent versions the refresh couldn't connect), it is retried over
520
+ * the other listed relays, and the caller goes ahead only if that refresh is complete.
521
+ *
522
+ * Why this is safe:
523
+ * - The strict refresh is there so we don't fork our own chain by building on a stale head (review H2):
524
+ * a newer version another of our key holders published went to every relay the document lists. The
525
+ * relays kept must still give a complete refresh, so a newer version any of them serves is still found,
526
+ * connected and built on (or, far behind, the refresh is incomplete and the edit refused: trying again
527
+ * goes on where the walk stopped). Leaving a relay out is what the strict refresh already allows when
528
+ * that relay doesn't answer.
529
+ * - Which relays are left out is the user's choice (the ones the edit removes) or each relay's own
530
+ * evidence (it sent identity-key-signed versions that don't connect): one relay can't get another left
531
+ * out. Any other edit still refuses while such a relay is listed, and names it (fork and compromise
532
+ * detection stay: the user is told someone else may hold the key).
533
+ * - What is published is still head.ver + 1 on the head the kept relays confirmed: a relay left out can't
534
+ * make it lower, or make it fork from anything but what those relays serve.
535
+ * - Nothing is left out when no relay would be left; the kept relays' refresh must reach one of them.
536
+ * - #67 review F1: core names a relay only for versions on a dead gap (asked of every relay, held by
537
+ * none), never one whose genuine gap the walk merely didn't reach. And the confirmed head must not be
538
+ * below any version the full refresh left unconnected, unless every relay that sent that version is set
539
+ * aside: a lagging kept relay can't "confirm" a stale head while another relay serves a newer version.
540
+ * (Pending heads stored by earlier refreshes can't be traced to a relay; a relay still serving a newer
541
+ * version shows it in this refresh.)
542
+ * Returns the view, or undefined when this doesn't apply (the caller then refuses as before).
543
+ */
544
+ async ownStrictFallback(userId, list, unconnected, versions, setAside, refreshFrom) {
545
+ if (!setAside || userId !== this.keys?.userId)
546
+ return undefined;
547
+ const aside = new Set([...(setAside.relays ?? []), ...(setAside.unconnected ? unconnected : [])].filter((r) => list.includes(r)));
548
+ const rest = list.filter((r) => !aside.has(r));
549
+ if (aside.size === 0 || rest.length === 0)
550
+ return undefined;
551
+ let v;
552
+ try {
553
+ v = await refreshFrom(rest);
463
554
  }
464
555
  catch (e) {
465
- if (!(e instanceof P2PError))
466
- throw e;
467
- // Strict callers (publishing our own next version) must not build on a head they couldn't confirm.
468
- if (opts.strict)
469
- throw new CliError("refresh_failed", `couldn't confirm the current identity document on the relays (${e.reason}): not publishing on a possibly stale head`);
470
- if (e.reason === "chain-broken" && held && !opts.quiet) {
471
- this.warn(`${await this.addressOf(userId)}'s newest identity document doesn't connect to the history held here (§2.5 history gap); keeping the held one`);
472
- }
473
- return held;
556
+ if (e instanceof P2PError)
557
+ return undefined;
558
+ throw e;
559
+ }
560
+ if (v.incomplete)
561
+ return undefined;
562
+ if (versions.some((x) => x.ver > v.head.ver && (x.relays.length === 0 || x.relays.some((r) => !aside.has(r)))))
563
+ return undefined;
564
+ // §2.5 compromise detection: say so, whatever the user goes on to do (only for relays core named, F1).
565
+ const forged = unconnected.filter((r) => aside.has(r));
566
+ if (forged.length > 0) {
567
+ const one = forged.length === 1;
568
+ this.warn(`${forged.join(", ")} ${one ? "serves" : "serve"} versions of your identity, signed with your identity key, that don't connect to the history your other relays confirm (left out of this check). If no device of yours published them, someone else holds your identity key: rotate your identity (\`p2p identity rotate\`)`);
474
569
  }
570
+ return v;
475
571
  }
476
572
  /** Relays a (bundled, unverified) identity document lists: only a hint for where to refresh from. */
477
573
  static relaysOf(docJws) {
@@ -522,6 +618,7 @@ export class App {
522
618
  /** Signer resolution for core verifiers, finding unknown identities on the relays (once per process). */
523
619
  signerCtx(hint = []) {
524
620
  return storeSignerContext(this.store, {
621
+ own: this.keys?.userId,
525
622
  resolveIdentity: (u) => this.discover(u, hint),
526
623
  });
527
624
  }
@@ -649,7 +746,10 @@ export class App {
649
746
  const ik = this.requireKeyholder("Publishing the identity document");
650
747
  // §2.5: build on the newest head the relays hold, or not at all (review H2: a stale key holder
651
748
  // republishing blind could fork the identity).
652
- await this.refreshIdentity(this.userId, this.relays, { force: true, strict: true });
749
+ // #67: an edit that removes relays, or the rotation's final version, may leave out a listed relay
750
+ // serving versions that don't connect (a thief's, signed with the identity key): see ownStrictFallback.
751
+ const setAside = opts.rotation ? { unconnected: true } : opts.removing?.length ? { relays: opts.removing } : undefined;
752
+ await this.refreshIdentity(this.userId, this.relays, { force: true, strict: true, ...(setAside ? { setAside } : {}) });
653
753
  let view = await this.ownView();
654
754
  // What the tips list before any merge: a merge keeps only the intersection (§2.5), so devices
655
755
  // only one branch listed are re-added below unless they were revoked (review N-H1).
@@ -692,7 +792,7 @@ export class App {
692
792
  const stored = await this.store.getIdentity(this.userId);
693
793
  // Only devices a merge dropped come back: never one revoked along the head's ancestry, nor one
694
794
  // core denies after a history jump.
695
- const plan = stored && merges.length > 0 ? planReadd(IdentityChain.fromStored(stored), preTips, unionDevices, view.devices, head.hash, stored.denied ?? []) : { readd: [], skipped: [] };
795
+ const plan = stored && merges.length > 0 ? planReadd(IdentityChain.fromStored({ ...stored, pendingHeads: [] }), preTips, unionDevices, view.devices, head.hash, stored.denied ?? []) : { readd: [], skipped: [] };
696
796
  for (const d of plan.skipped)
697
797
  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)`);
698
798
  const readd = plan.readd;
@@ -945,14 +1045,38 @@ export class App {
945
1045
  */
946
1046
  async deliver(to, kind, session, plaintext, opts = {}) {
947
1047
  const pool = this.pool ?? (await this.connect());
1048
+ const { targets, outgoing, errors, sealed } = await this.sealCopies(to, kind, session, plaintext, opts);
1049
+ const sentVia = new Set();
1050
+ const results = await Promise.all(outgoing.map(({ d, env }) => pool.sendEnvelope(env, to, d, kind, targets)));
1051
+ const unsent = [];
1052
+ for (const [i, res] of results.entries()) {
1053
+ for (const r of res.sent)
1054
+ sentVia.add(r);
1055
+ for (const e of res.errors)
1056
+ errors.push({ did: outgoing[i].d, relay: e.relay, code: e.code, ...(e.written ? { written: true } : {}) });
1057
+ if (res.sent.length === 0)
1058
+ unsent.push({ did: outgoing[i].d, env: outgoing[i].env, targets, codes: res.errors.map((e) => e.code) });
1059
+ }
1060
+ return { userId: to, devices: sealed, relays: [...sentVia], ...(errors.length > 0 ? { errors } : {}), ...(unsent.length > 0 ? { unsent } : {}) };
1061
+ }
1062
+ /**
1063
+ * Seals `plaintext` for `to` exactly as deliver does (the same devices, a fresh seq each, the same
1064
+ * relays and caps) and sends nothing: copies for the outbox to send later (outbox.ts).
1065
+ */
1066
+ async seal(to, kind, session, plaintext, opts = {}) {
1067
+ const { targets, outgoing } = await this.sealCopies(to, kind, session, plaintext, opts);
1068
+ return outgoing.map(({ d, env }) => ({ did: d, env, targets }));
1069
+ }
1070
+ async sealCopies(to, kind, session, plaintext, opts) {
948
1071
  const view = to === this.userId ? await this.ownView() : await this.viewFor(to, { refresh: opts.refresh, hint: opts.hint });
949
1072
  if (!view)
950
1073
  throw new CliError("unknown_user", `no identity document for ${to}: can't find their devices or relays`);
951
- const devices = view.devices.filter((d) => !(to === this.userId && d === this.did) && (!opts.onlyDevices || opts.onlyDevices.includes(d)));
1074
+ // This device only when named in onlyDevices (a message to another session of ours here, or a
1075
+ // receipt for one): sealed to itself and sent through a relay like any other copy.
1076
+ const devices = view.devices.filter((d) => (to !== this.userId || d !== this.did || opts.onlyDevices?.includes(d) === true) && (!opts.onlyDevices || opts.onlyDevices.includes(d)));
952
1077
  const relays = orderRelays(view.head.relays, view.relays).slice(0, 3);
953
1078
  const caps = await this.capsFor(to, kind, opts.extraCaps);
954
1079
  const resolveCert = storeCertResolver(this.store);
955
- const sentVia = new Set();
956
1080
  const errors = [];
957
1081
  // Certificates first (each verified, as before), then one seq block for every copy, then the
958
1082
  // copies go out together: one round trip for all of the recipient's devices, not one each.
@@ -971,6 +1095,8 @@ export class App {
971
1095
  }
972
1096
  }
973
1097
  const seqs = ready.length > 0 ? await this.state.nextSeqs(session.own, session.sid, ready.length) : [];
1098
+ if (opts.beforeSend && ready.length > 0)
1099
+ await opts.beforeSend(ready.map((r, i) => ({ did: r.d, seq: seqs[i] })));
974
1100
  const targets = relays.map((r) => ({ relay: r, cap: caps.get(r) })).filter((t) => t.cap !== undefined || kind === "contact");
975
1101
  const outgoing = [];
976
1102
  for (const [i, { d, kpk }] of ready.entries()) {
@@ -994,18 +1120,7 @@ export class App {
994
1120
  else
995
1121
  outgoing.push({ d, env });
996
1122
  }
997
- const sealed = ready.length;
998
- const results = await Promise.all(outgoing.map(({ d, env }) => pool.sendEnvelope(env, to, d, kind, targets)));
999
- const unsent = [];
1000
- for (const [i, res] of results.entries()) {
1001
- for (const r of res.sent)
1002
- sentVia.add(r);
1003
- for (const e of res.errors)
1004
- errors.push({ did: outgoing[i].d, relay: e.relay, code: e.code, ...(e.written ? { written: true } : {}) });
1005
- if (res.sent.length === 0)
1006
- unsent.push({ did: outgoing[i].d, env: outgoing[i].env, targets, codes: res.errors.map((e) => e.code) });
1007
- }
1008
- return { userId: to, devices: sealed, relays: [...sentVia], ...(errors.length > 0 ? { errors } : {}), ...(unsent.length > 0 ? { unsent } : {}) };
1123
+ return { targets, outgoing, errors, sealed: ready.length };
1009
1124
  }
1010
1125
  /** Delivers to our other devices, when there are any (sync, §4.3). */
1011
1126
  async syncOwn(body) {