@peer2peer/cli 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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/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.5/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.3/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.5/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.3/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.5/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,9 @@ 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
+ | `version [--json]` | CLI version, protocol minor, advertised capabilities and Node.js version. Works offline without an identity. `--version` still prints only the package version. |
65
+ | `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. |
66
+ | `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
67
  | `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
68
  | `whoami` | Shows your address and grouped fingerprint, devices, relays and document expiry. |
67
69
  | `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 +95,7 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
93
95
  | `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
96
  | `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
97
  | `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.3/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 |
98
+ | `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.5/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
99
  | `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
100
  | `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
101
  | `watch --session <sid> --jsonl` | One JSON line per accepted event. Stays connected and reconnects silently. |
@@ -158,7 +160,7 @@ The cursor (`<home>/cursors/<sid>.cursor`) advances only after a line reaches st
158
160
  | `P2P_DEVICE_INFO` / `deviceInfo` in config.json | Off by default. On, a key-holding device keeps its caps and version in your identity document (`dinfo`), on relays that list `identity.lenient`. Clients from before protocol 3.1 refuse a document with it, so it stays off until the previous two releases are 3.1 (docs/compatibility.md, step 2). |
159
161
  | `P2P_DRAIN_QUIET_MS`, `P2P_DRAIN_MAX_MS`, `P2P_DOC_REFRESH_SEC`, `P2P_LINK_POLL_MS` | Timing knobs, mostly for tests. |
160
162
 
161
- **Keys.** Device keys, and the identity key on key holders, are kept in a 0600 file in `<home>/cli`. An OS keychain backend is not wired up yet.
163
+ **Keys.** By default, device keys and the identity key on key holders are kept in a 0600 file in `<home>/cli`. Run `p2p keys backend keychain` in your own terminal to move them into the OS keychain, or `p2p keys backend file` to move them back. Save your backup phrase first; see the [OS keychain guide](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.5/docs/keychain.md) and [threat model](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.5/docs/security/threat-model.md#keys-in-the-os-keychain).
162
164
 
163
165
  **Forks.** When two key holders publish at once, your document forks (§2.5). The next version this CLI publishes first merges the tips, pairwise for three or more, with the intersection of devices and key holders, `by` this device or else the lowest common key holder. It then re-adds any device a merge dropped that wasn't revoked, so a device linked during a fork isn't lost. It re-adds a device only when this device holds each branch's history back to their common ancestor; otherwise it warns you to link that device again rather than guess. A merge's `by` is nominal (a common key holder): the device that wrote it records it as its own, and a merge adds nothing, so no device's "versions I didn't publish" check alerts on it. If the branches share no key holder, it refuses and recommends rotation.
164
166
 
@@ -331,7 +333,7 @@ Without a user, it checks this device:
331
333
  - 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
334
  - 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
335
 
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.3/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`.
336
+ 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.5/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
337
 
336
338
  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
339
 
package/dist/app.d.ts CHANGED
@@ -82,6 +82,8 @@ export interface Delivery {
82
82
  codes: string[];
83
83
  }[];
84
84
  }
85
+ /** At most this many other caps ride along with a send target (relay-client.ts SendTarget.fallback). */
86
+ export declare const MAX_FALLBACK_CAPS = 3;
85
87
  export declare class App {
86
88
  /** The person's front end vouched for this command (P2P_PERSON_TOKEN, checked once and removed: projects.ts). */
87
89
  front: boolean;
@@ -248,12 +250,32 @@ export declare class App {
248
250
  strict?: boolean;
249
251
  setAside?: SetAside;
250
252
  }): Promise<IdentityView | undefined>;
253
+ /**
254
+ * #79, #92 follow-up: the relays core held a refresh of our own identity back for (`by`, they sent a head that
255
+ * would leave out the versions `left`), counted like the relays core names as serving versions that don't connect
256
+ * (a rotation sets them aside, the hint names them) only when one of `left` is our own current tip: a tip of our
257
+ * stored chain (never an old version a relay replays: that is an ancestor of what we hold, or not held at all)
258
+ * that our devices published (the publish log) and that the head held back for (`head`) revoked no device of (#99),
259
+ * 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
260
+ * published (another owner device whose versions haven't reached this device's log yet, the provenance rule of
261
+ * ownBranchTip in rotation.ts). That provenance alone never counts against a head that still lists this device: the
262
+ * devices a logged version lists include ones the owner revoked since, and a version such a device signed, held
263
+ * here, must not get the relays serving the owner's revocation set aside. Otherwise none: a relay replaying an old
264
+ * version (history pruned past what the relays keep) can't get an honest relay set aside, and a relay that really
265
+ * holds the owner up can still be removed (`p2p relays remove`).
266
+ */
267
+ private ownHeldBack;
251
268
  /**
252
269
  * For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
253
270
  * core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
254
271
  * so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
272
+ * #99 review: `heldBy`, the relays core held the refresh back for, are named too when they weren't counted
273
+ * (ownHeldBack refused, as when their head drops a device this device's current version lists), with what to do:
274
+ * nothing else names them.
255
275
  */
256
276
  private unconnectedHint;
277
+ /** #99 review: the relays a refresh of our own identity was held back for, not set aside (ownHeldBack refused). */
278
+ private heldBackHint;
257
279
  /**
258
280
  * #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
259
281
  * identity edit that removes relays (`setAside.relays`: the ones it removes), or a rotation step
@@ -388,6 +410,12 @@ export declare class App {
388
410
  selfCap(): string;
389
411
  /** Caps we hold that let us reach `to` with `kind`, by relay (best first). */
390
412
  capsFor(to: string, kind: string, extra?: readonly string[]): Promise<Map<string, string>>;
413
+ /**
414
+ * Every cap we hold that lets us reach `to` with `kind`, by relay, best first. The best one can be
415
+ * dead at the relay while a later one works: a friend cap revoked by a block (an unblock issues no
416
+ * new one) next to a co-member's join cap, and the order between them is only their expiry (#127).
417
+ */
418
+ capChoicesFor(to: string, kind: string, extra?: readonly string[]): Promise<Map<string, string[]>>;
391
419
  /** Records a cap this device issued, so it can be revoked later (§5.3). */
392
420
  recordIssued(capJws: string): Promise<StoredCapV3>;
393
421
  /** Sends `revoke` for each cap to every relay it names. */
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";
@@ -41,6 +42,10 @@ export const CLOSE_GRACE_MS = 3000;
41
42
  const FETCHED_SLACK_MS = 5000;
42
43
  export const REPUBLISH_DOC_WITHIN_SEC = 7 * 86_400;
43
44
  const CAP_PRIORITY = (c) => (c.kinds[0] === "*" ? 0 : 1);
45
+ /** At most this many other caps ride along with a send target (relay-client.ts SendTarget.fallback). */
46
+ export const MAX_FALLBACK_CAPS = 3;
47
+ /** Send targets as stored and reported (the outbox, `unsent`): each relay's best cap, without the fallbacks. */
48
+ const firstCaps = (targets) => targets.map((t) => ({ relay: t.relay, ...(t.cap !== undefined ? { cap: t.cap } : {}) }));
44
49
  export class App {
45
50
  /** The person's front end vouched for this command (P2P_PERSON_TOKEN, checked once and removed: projects.ts). */
46
51
  front = false;
@@ -136,6 +141,13 @@ export class App {
136
141
  }
137
142
  this.checkFrontKeys(keys);
138
143
  this.setKeys(keys, self);
144
+ // A home that chose the OS keychain whose keys are still in keys.json (an interrupted move, or a
145
+ // rotation that swapped in a new identity's files): moved now (keystore.ts). Never on a read-only run.
146
+ if (!this.readOnly) {
147
+ const w = await finishPendingMove(this.state.keyStore);
148
+ if (w)
149
+ this.warn(w);
150
+ }
139
151
  return true;
140
152
  }
141
153
  /**
@@ -506,11 +518,12 @@ export class App {
506
518
  // Strict callers (publishing our own next version) must not build on a head they couldn't confirm.
507
519
  if (opts.strict) {
508
520
  // #79: relays core held the refresh back for count like the ones it names (see the incomplete case below).
509
- const unconnected = [...new Set([...unconnectedRelaysOf(e), ...(own ? heldBackByOf(e) : [])])];
521
+ const heldBy = own ? heldBackByOf(e) : [];
522
+ const unconnected = [...new Set([...unconnectedRelaysOf(e), ...(own ? await this.ownHeldBack(heldBy, heldBackForOf(e), heldBackHeadOf(e)) : [])])];
510
523
  const versions = unconnectedVersionsOf(e);
511
524
  const fb = e.reason === "chain-broken" ? await this.ownStrictFallback(userId, list, unconnected, versions, opts.setAside, refreshFrom) : undefined;
512
525
  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)}`);
526
+ 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
527
  v = fb;
515
528
  named = unconnected;
516
529
  }
@@ -530,11 +543,13 @@ export class App {
530
543
  }
531
544
  // #79: relays core held the refresh back for (they sent a version of our identity that doesn't connect to
532
545
  // 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
- const unconnected = [...new Set([...(v.unconnectedRelays ?? []), ...(own ? (v.heldBackBy ?? []) : [])])];
546
+ // don't connect: a rotation sets them aside, any other edit refuses and names them. Only when what they left
547
+ // out is a version our own devices published (ownHeldBack).
548
+ const heldBy = own ? (v.heldBackBy ?? []) : [];
549
+ const unconnected = [...new Set([...(v.unconnectedRelays ?? []), ...(own ? await this.ownHeldBack(heldBy, v.heldBackFor ?? [], v.heldBackHead) : [])])];
535
550
  const fb = await this.ownStrictFallback(userId, list, unconnected, v.unconnectedVersions ?? [], opts.setAside, refreshFrom);
536
551
  if (!fb)
537
- throw new CliError("refresh_failed", `refreshing the identity document was cut short; try again${this.unconnectedHint(unconnected, v.unconnectedVersions ?? [], userId)}`);
552
+ throw new CliError("refresh_failed", `refreshing the identity document was cut short; try again${this.unconnectedHint(unconnected, v.unconnectedVersions ?? [], userId, heldBy)}`);
538
553
  named = unconnected;
539
554
  v = fb;
540
555
  }
@@ -549,22 +564,76 @@ export class App {
549
564
  await this.state.update("fetched", (cur = {}) => ({ next: { ...cur, [userId]: Math.max(cur[userId] ?? 0, now) }, result: undefined }));
550
565
  return v;
551
566
  }
567
+ /**
568
+ * #79, #92 follow-up: the relays core held a refresh of our own identity back for (`by`, they sent a head that
569
+ * would leave out the versions `left`), counted like the relays core names as serving versions that don't connect
570
+ * (a rotation sets them aside, the hint names them) only when one of `left` is our own current tip: a tip of our
571
+ * stored chain (never an old version a relay replays: that is an ancestor of what we hold, or not held at all)
572
+ * that our devices published (the publish log) and that the head held back for (`head`) revoked no device of (#99),
573
+ * 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
574
+ * published (another owner device whose versions haven't reached this device's log yet, the provenance rule of
575
+ * ownBranchTip in rotation.ts). That provenance alone never counts against a head that still lists this device: the
576
+ * devices a logged version lists include ones the owner revoked since, and a version such a device signed, held
577
+ * here, must not get the relays serving the owner's revocation set aside. Otherwise none: a relay replaying an old
578
+ * version (history pruned past what the relays keep) can't get an honest relay set aside, and a relay that really
579
+ * holds the owner up can still be removed (`p2p relays remove`).
580
+ */
581
+ async ownHeldBack(by, left, head) {
582
+ if (by.length === 0 || left.length === 0 || !this.keys)
583
+ return [];
584
+ const stored = await this.store.getIdentity(this.keys.userId);
585
+ if (!stored || stored.versions.length === 0)
586
+ return [];
587
+ const chain = IdentityChain.fromStored({ ...stored, pendingHeads: [], leftOut: [] });
588
+ const tips = new Set(chain.tips().map((t) => t.hash));
589
+ const published = new Set((await this.store.getPublishLog()).published);
590
+ // Unknown (an older core): as if it listed this device, so provenance alone never counts.
591
+ const headLeavesMeOut = head !== undefined && !head.keyholders.includes(this.did);
592
+ const trusted = headLeavesMeOut ? new Set([this.did, ...[...published].flatMap((h) => chain.get(h)?.devices ?? [])]) : new Set();
593
+ // #99: our own published tip V counts against a head that still lists this device only when that head lists
594
+ // every device V lists. A head that dropped one may be the owner's revocation, reached from another device while
595
+ // this one was offline longer than the relays keep the history between them: a relay still serving V must not get
596
+ // the relays serving that revocation set aside (the rotation would plan from V's stale device list). That case
597
+ // can't be told apart from a thief's head that keeps this device and drops another device V lists: whoever holds
598
+ // the key chooses what its head lists, so it can make this rule refuse. Refusing is the fail-closed choice (no
599
+ // relay is set aside on evidence the head's signer picks); the error then names the relays the refresh was held
600
+ // back for and says how to remove one (unconnectedHint's `heldBy`). An unknown head (an older core) revoked
601
+ // something, for all we know.
602
+ const revokedNone = (v) => head?.devices !== undefined && v.devices.every((d) => head.devices.includes(d));
603
+ const own = left.some((h) => {
604
+ const v = tips.has(h) ? chain.get(h) : undefined;
605
+ return v !== undefined && ((published.has(h) && (headLeavesMeOut || revokedNone(v))) || trusted.has(v.by));
606
+ });
607
+ return own ? [...by] : [];
608
+ }
552
609
  /**
553
610
  * For a strict refresh of our own identity that failed: what to do. The key-compromise wording only for relays
554
611
  * core named (#67 review F1): each sent a version whose missing parent every relay was asked for and none had,
555
612
  * so nothing a device of ours published would be there. Otherwise only which relays sent the newer versions.
613
+ * #99 review: `heldBy`, the relays core held the refresh back for, are named too when they weren't counted
614
+ * (ownHeldBack refused, as when their head drops a device this device's current version lists), with what to do:
615
+ * nothing else names them.
556
616
  */
557
- unconnectedHint(unconnected, versions, userId) {
617
+ unconnectedHint(unconnected, versions, userId, heldBy = []) {
558
618
  if (userId !== this.keys?.userId)
559
619
  return "";
620
+ const held = [...new Set(heldBy)].filter((r) => !unconnected.includes(r));
621
+ const heldHint = held.length === 0 ? "" : this.heldBackHint(held);
560
622
  if (unconnected.length > 0) {
561
623
  const one = unconnected.length === 1;
562
- 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\`)`;
624
+ 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
625
  }
564
- const from = [...new Set(versions.flatMap((x) => x.relays))];
626
+ const from = [...new Set(versions.flatMap((x) => x.relays))].filter((r) => !held.includes(r));
565
627
  if (from.length === 0)
566
- return "";
567
- 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>\`)`;
628
+ return heldHint;
629
+ 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>\`)`;
630
+ }
631
+ /** #99 review: the relays a refresh of our own identity was held back for, not set aside (ownHeldBack refused). */
632
+ heldBackHint(held) {
633
+ const one = held.length === 1;
634
+ 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. ` +
635
+ `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. ` +
636
+ `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
637
  }
569
638
  /**
570
639
  * #67: a strict refresh of our OWN identity couldn't confirm the head over every listed relay. Before an
@@ -887,7 +956,7 @@ export class App {
887
956
  const stored = await this.store.getIdentity(this.userId);
888
957
  // Only devices a merge dropped come back: never one revoked along the head's ancestry, nor one
889
958
  // 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: [] };
959
+ const plan = stored && merges.length > 0 ? planReadd(IdentityChain.fromStored({ ...stored, pendingHeads: [], leftOut: [] }), preTips, unionDevices, view.devices, head.hash, stored.denied ?? []) : { readd: [], skipped: [] };
891
960
  for (const d of plan.skipped)
892
961
  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
962
  const readd = plan.readd;
@@ -1084,6 +1153,14 @@ export class App {
1084
1153
  }
1085
1154
  /** Caps we hold that let us reach `to` with `kind`, by relay (best first). */
1086
1155
  async capsFor(to, kind, extra = []) {
1156
+ return new Map([...(await this.capChoicesFor(to, kind, extra))].map(([r, caps]) => [r, caps[0]]));
1157
+ }
1158
+ /**
1159
+ * Every cap we hold that lets us reach `to` with `kind`, by relay, best first. The best one can be
1160
+ * dead at the relay while a later one works: a friend cap revoked by a block (an unblock issues no
1161
+ * new one) next to a co-member's join cap, and the order between them is only their expiry (#127).
1162
+ */
1163
+ async capChoicesFor(to, kind, extra = []) {
1087
1164
  const now = nowSec();
1088
1165
  const cands = [];
1089
1166
  if (to === this.userId) {
@@ -1112,12 +1189,20 @@ export class App {
1112
1189
  cands.push({ jws: j, relays: p.relays, kinds: p.kinds, exp: p.exp });
1113
1190
  }
1114
1191
  const usable = cands.filter((c) => c.exp > now + 60 && capAllowsKind(c.kinds, kind)).sort((a, b) => CAP_PRIORITY(a) - CAP_PRIORITY(b) || b.exp - a.exp);
1192
+ // One entry per cap id: the same cap held twice (say, as held and as a join cap) is no fallback.
1115
1193
  const out = new Map();
1116
- for (const c of usable)
1117
- for (const r of c.relays)
1118
- if (!out.has(r))
1119
- out.set(r, c.jws);
1120
- return out;
1194
+ for (const c of usable) {
1195
+ const id = capPeek(c.jws)?.capid ?? c.jws;
1196
+ for (const r of c.relays) {
1197
+ const e = out.get(r) ?? { jws: [], ids: new Set() };
1198
+ if (e.ids.has(id))
1199
+ continue;
1200
+ e.ids.add(id);
1201
+ e.jws.push(c.jws);
1202
+ out.set(r, e);
1203
+ }
1204
+ }
1205
+ return new Map([...out].map(([r, e]) => [r, e.jws]));
1121
1206
  }
1122
1207
  /** Records a cap this device issued, so it can be revoked later (§5.3). */
1123
1208
  async recordIssued(capJws) {
@@ -1156,7 +1241,7 @@ export class App {
1156
1241
  for (const e of res.errors)
1157
1242
  errors.push({ did: outgoing[i].d, relay: e.relay, code: e.code, ...(e.written ? { written: true } : {}) });
1158
1243
  if (res.sent.length === 0)
1159
- unsent.push({ did: outgoing[i].d, env: outgoing[i].env, targets, codes: res.errors.map((e) => e.code) });
1244
+ unsent.push({ did: outgoing[i].d, env: outgoing[i].env, targets: firstCaps(targets), codes: res.errors.map((e) => e.code) });
1160
1245
  }
1161
1246
  return { userId: to, devices: sealed, relays: [...sentVia], ...(errors.length > 0 ? { errors } : {}), ...(unsent.length > 0 ? { unsent } : {}) };
1162
1247
  }
@@ -1166,7 +1251,7 @@ export class App {
1166
1251
  */
1167
1252
  async seal(to, kind, session, plaintext, opts = {}) {
1168
1253
  const { targets, outgoing } = await this.sealCopies(to, kind, session, plaintext, opts);
1169
- return outgoing.map(({ d, env }) => ({ did: d, env, targets }));
1254
+ return outgoing.map(({ d, env }) => ({ did: d, env, targets: firstCaps(targets) }));
1170
1255
  }
1171
1256
  async sealCopies(to, kind, session, plaintext, opts) {
1172
1257
  const view = to === this.userId ? await this.ownView() : await this.viewFor(to, { refresh: opts.refresh, hint: opts.hint });
@@ -1176,7 +1261,7 @@ export class App {
1176
1261
  // receipt for one): sealed to itself and sent through a relay like any other copy.
1177
1262
  const devices = view.devices.filter((d) => (to !== this.userId || d !== this.did || opts.onlyDevices?.includes(d) === true) && (!opts.onlyDevices || opts.onlyDevices.includes(d)));
1178
1263
  const relays = orderRelays(view.head.relays, view.relays).slice(0, 3);
1179
- const caps = await this.capsFor(to, kind, opts.extraCaps);
1264
+ const caps = await this.capChoicesFor(to, kind, opts.extraCaps);
1180
1265
  const resolveCert = storeCertResolver(this.store);
1181
1266
  const errors = [];
1182
1267
  // Certificates first (each verified, as before), then one seq block for every copy, then the
@@ -1198,7 +1283,13 @@ export class App {
1198
1283
  const seqs = ready.length > 0 ? await this.state.nextSeqs(session.own, session.sid, ready.length) : [];
1199
1284
  if (opts.beforeSend && ready.length > 0)
1200
1285
  await opts.beforeSend(ready.map((r, i) => ({ did: r.d, seq: seqs[i] })));
1201
- const targets = relays.map((r) => ({ relay: r, cap: caps.get(r) })).filter((t) => t.cap !== undefined || kind === "contact");
1286
+ const targets = relays
1287
+ .map((r) => {
1288
+ const [cap, ...rest] = caps.get(r) ?? [];
1289
+ const fallback = rest.slice(0, MAX_FALLBACK_CAPS);
1290
+ return { relay: r, cap, ...(fallback.length > 0 ? { fallback } : {}) };
1291
+ })
1292
+ .filter((t) => t.cap !== undefined || kind === "contact");
1202
1293
  const outgoing = [];
1203
1294
  for (const [i, { d, kpk }] of ready.entries()) {
1204
1295
  const env = sealEnvelopeV3({
@@ -730,7 +730,8 @@ export async function joinCircle(app, input, opts = {}) {
730
730
  if (exp)
731
731
  await sendSync(app, { circles: [exp] });
732
732
  if (!delivered.some((d) => d.relays.length > 0) && targets.length > 0) {
733
- throw new CliError("undelivered", "joined locally, but the join was delivered via 0 relays: the owner doesn't know yet", { cid });
733
+ const codes = [...new Set(delivered.flatMap((d) => (d.errors ?? []).map((e) => e.code)))];
734
+ throw new CliError("undelivered", `joined locally, but the join was delivered via 0 relays${codes.length ? ` (${codes.join(", ")})` : ""}: the owner doesn't know yet`, { cid });
734
735
  }
735
736
  return {
736
737
  ...base,
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;