@peer2peer/cli 0.1.2 → 0.1.3
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 +8 -6
- package/dist/ancestry.d.ts +42 -2
- package/dist/ancestry.js +215 -32
- package/dist/app.d.ts +44 -2
- package/dist/app.js +116 -15
- package/dist/cli.d.ts +30 -3
- package/dist/cli.js +133 -8
- package/dist/doctor.js +29 -1
- package/dist/format.d.ts +2 -0
- package/dist/format.js +5 -1
- package/dist/identity.d.ts +6 -2
- package/dist/identity.js +34 -19
- package/dist/pretty.js +2 -1
- package/dist/projects.d.ts +58 -12
- package/dist/projects.js +220 -48
- package/dist/rotation.d.ts +20 -1
- package/dist/rotation.js +280 -14
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/watch.js +43 -13
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# p2p: the Peer2Peer CLI
|
|
2
2
|
|
|
3
|
-
`@peer2peer/cli` is the standalone `p2p` command for [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
3
|
+
`@peer2peer/cli` is the standalone `p2p` command for [Peer2Peer v3](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.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.
|
|
4
4
|
|
|
5
5
|
It is core software: it never imports Ix or an extension (`node scripts/check-boundaries.mjs`).
|
|
6
6
|
|
|
7
7
|
## Two friends in two minutes
|
|
8
8
|
|
|
9
|
-
You need a relay. Run your own (`npx @peer2peer/relay`, see [run-a-relay.md](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
9
|
+
You need a relay. Run your own (`npx @peer2peer/relay`, see [run-a-relay.md](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.3/docs/run-a-relay.md)), or use one your community runs. No relay is built in yet. Tell `p2p` about it once:
|
|
10
10
|
|
|
11
11
|
```sh
|
|
12
12
|
export P2P_DEFAULT_RELAYS=wss://relay.example.org/v3 # 1–5, comma separated
|
|
@@ -29,7 +29,7 @@ p2p join relay.example.org/K7QM-3XPD-9TWA-HF2N-6RJC # you and ann@k7f2-qx9a-3m
|
|
|
29
29
|
|
|
30
30
|
If Ann has a default circle (`p2p circle default <cid>`) that she owns or administers, the code joins Ben to it as well, and it becomes his default circle. Ann's client adds him the next time it runs (at once, when a `watch` is running), and tells her `ben@… joined via your code K7QM… ("ben")`. If that isn't who she meant, `p2p remove <userId>` undoes it. The code works once and lives 7 days at most. The long-link form (`p2p invite --link` / `p2p accept <link>`) still works.
|
|
31
31
|
|
|
32
|
-
**Share a project and talk.** A session is shared with nobody until you share the project it works in (a git repository, or a folder): see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.
|
|
32
|
+
**Share a project and talk.** A session is shared with nobody until you share the project it works in (a git repository, or a folder): see [projects](https://github.com/ix-infrastructure/Peer2Peer/blob/v0.1.3/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`):
|
|
@@ -57,6 +57,8 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
|
|
|
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
|
+
**Person-only commands:** the commands that widen who reaches you, and the ones that touch your identity key, your identity document or your own setup, run only for you: with your front end's token (`P2P_PERSON_TOKEN`, from `<home>/cli/person.key`; on a home with an identity it is derived from the device key, so a `person.key` written by anything else never verifies), or after you type `yes` on your own terminal; never from inside an agent's session, and never when p2p can't read its process tree to tell (fail closed). Beyond the widening ones: `backup show|restore` (`backup restore` runs only on a fresh home and needs the phrase itself, so outside an agent's session the phrase is the proof and nothing more is asked; inside one it is refused), `setup --print-backup|--backup-file` on a home that already holds an identity, `identity rotate` (all but a bare `--plan`), `identity republish`, `identity dispute`, `devices revoke`, `relays add|remove`, `profile set`, `proof add`, `trust remove`, `invites revoke`, `remove`, `unfriend`, `block`, `petname`, `circle propose`, `circle transfer`, `circle leave`, `circle hold <cid> on|off`, `held decline`, `extensions disable`, `receipts on|off`, `ix import`, `ix resolve` and `ix config <setting>` (ext-ix's). Reads stay open (`invites` cuts its live codes inside an agent's session without the token), and `watch`'s automatic renewal of your document and certificates isn't a command and keeps running. This is defence in depth, not a boundary: an agent running as you can start a process outside its own tree that fakes a terminal, or read your key files. Sandbox your agents, denying them `P2P_HOME` (docs/security/threat-model.md).
|
|
61
|
+
|
|
60
62
|
| Command | What it does |
|
|
61
63
|
|---|---|
|
|
62
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. |
|
|
@@ -73,7 +75,7 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
|
|
|
73
75
|
| `proof add github <handle> [--gist id]` / `proof add dns <domain>` / `proof verify <user>` | §2.6 proofs. `add` prints exactly what to publish. |
|
|
74
76
|
| `invite [label] [--circle cid]… [--no-circle] [--to user] [--ttl-days N] [--relay url] [--web]` | A one-time short code (protocol P4), printed with its web link (`https://ix-infra.com/p2p/invite#<relay>/<CODE>`, the same code; `--web` prints only the link). It friends whoever redeems it and joins them to each `--circle` (up to 5, each one you own or administer, none open; otherwise no code is made) or, by default, to your default circle (when you own or administer it). The label is local only; it is shown when the code is redeemed. `--to` binds the code to one recipient. `--ttl-days` is 1–7 (default 7). |
|
|
75
77
|
| `join <code\|link> [--wait s] [--preview] [--confirmed] [--yes] [--name n] [--allow-private-relay]` | Redeems a code or its web link: friends, plus each circle under §3.3. It first shows who the code is from and every circle it joins, and asks once; `--preview` shows that and stops, `--confirmed` says you saw it, `--yes` says yes for scripts (and joins even when no second member could confirm it). Only a verified, invite-only circle the inviter runs is joined on the yes, and only if the circle that arrives is the one shown; anything else waits as a circle invite to approve on its own. The first circle becomes your default only when you have none (never an open one); running sessions stay as they are. A code whose relay is, or resolves to, a loopback, link-local or private address is refused unless you pass `--allow-private-relay` (or set `P2P_ALLOW_PRIVATE_RELAY=1`), for your own relay on your network. With no identity yet, it creates one first, on your default relays. With no default relays, the code's relay is your only one: it warns (`relayWarning` in `--json`), and you should add another with `p2p relays add`. |
|
|
76
|
-
| `relays` / `relays add <url>` / `relays remove <url
|
|
78
|
+
| `relays` / `relays add <url>` / `relays remove <url>...` | The relays your identity document lists (1–5). `remove` takes one or more. Adding or removing publishes the next document version to the old and new relays, sends each friend a fresh friend cap on the new list, and re-signs your circle joins with a fresh co-member cap (`capsReissued`, `rejoined` in `--json`). |
|
|
77
79
|
| `invites` / `invites revoke <code>` | Your codes: `open`, `taken` (the relay gave it out, nobody joined yet), `evicted` (the relay dropped it to make room: make a new one), `redeemed` (by whom), `expired` or `revoked`. Revoking deletes the code at the relay, revokes its cap, and refuses its accept even from someone who took it before. |
|
|
78
80
|
| `remove <user>` | Undoes a redemption: unfriends them and takes them out of the circles your codes added them to. |
|
|
79
81
|
| `invite --link [--to user] [--uses N]` / `accept <link> [--allow-private-relay]` | The long-link form (§3.1). The invite carries your document and a contact-only cap. A link naming a relay on a loopback, link-local or private address is refused unless `--allow-private-relay` (or `P2P_ALLOW_PRIVATE_RELAY=1`). |
|
|
@@ -91,7 +93,7 @@ On a terminal, `p2p` alone and `p2p relays` connect to your own relays (bounded)
|
|
|
91
93
|
| `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. |
|
|
92
94
|
| `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. |
|
|
93
95
|
| `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.
|
|
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 |
|
|
95
97
|
| `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. |
|
|
96
98
|
| `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). |
|
|
97
99
|
| `watch --session <sid> --jsonl` | One JSON line per accepted event. Stays connected and reconnects silently. |
|
|
@@ -329,7 +331,7 @@ Without a user, it checks this device:
|
|
|
329
331
|
- 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);
|
|
330
332
|
- 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`).
|
|
331
333
|
|
|
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.
|
|
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`.
|
|
333
335
|
|
|
334
336
|
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`.
|
|
335
337
|
|
package/dist/ancestry.d.ts
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
|
+
export type Ancestry = "agent" | "none" | "unknown";
|
|
2
|
+
/**
|
|
3
|
+
* Thrown by a reader for a process that is not this user's (another user's, or hidden by /proc's
|
|
4
|
+
* `hidepid`): the end of this user's own process tree, so the walk answers "none". An agent's
|
|
5
|
+
* session runs as the person, so its processes are always this user's and always readable.
|
|
6
|
+
*/
|
|
7
|
+
export declare class OtherUsersProcess extends Error {
|
|
8
|
+
readonly hidden: boolean;
|
|
9
|
+
/** Not visible at all (/proc's `hidepid`): it may also have just exited, so the walk checks that it didn't. */
|
|
10
|
+
constructor(hidden?: boolean);
|
|
11
|
+
}
|
|
1
12
|
/** An executable that is Claude Code or Codex, by its basename (argv0) only: never a word elsewhere on a command line. */
|
|
2
13
|
export declare function isAgentProcess(executable: string): boolean;
|
|
3
14
|
/**
|
|
@@ -6,8 +17,37 @@ export declare function isAgentProcess(executable: string): boolean;
|
|
|
6
17
|
* `@openai/codex`. A path, never a word elsewhere on the line.
|
|
7
18
|
*/
|
|
8
19
|
export declare function isAgentScript(args: string): boolean;
|
|
20
|
+
/** One process as the walk sees it: its parent, its executable, and (asked only for a script host) its command line. */
|
|
21
|
+
export interface ProcInfo {
|
|
22
|
+
ppid: number;
|
|
23
|
+
comm: string;
|
|
24
|
+
args: () => string;
|
|
25
|
+
}
|
|
26
|
+
/** The system's `ps`, by absolute path (never PATH), or undefined. */
|
|
27
|
+
export declare const PS_PATHS: readonly string[];
|
|
28
|
+
/**
|
|
29
|
+
* Walks parent processes from `start`, comparing each one's executable by basename (and a script
|
|
30
|
+
* host's script path). "agent" on a match; "none" once the walk reaches the root (pid 1 or 0);
|
|
31
|
+
* "unknown" when a process can't be read or the walk runs past 64 steps.
|
|
32
|
+
*/
|
|
33
|
+
export declare function walkAncestry(start: number, read: (pid: number) => ProcInfo, self?: number): Ancestry;
|
|
34
|
+
/**
|
|
35
|
+
* Linux: whether this process's user namespace is the initial one: /proc/self/uid_map is exactly
|
|
36
|
+
* one line "0 0 4294967295". In any other (an unprivileged sandbox, a rootless container) /proc
|
|
37
|
+
* entries can be bind-mounted to say anything, so the walk can't be trusted: "unknown".
|
|
38
|
+
*/
|
|
39
|
+
export declare function initialUserNamespace(uidMap: string): boolean;
|
|
9
40
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
41
|
+
* Linux: whether this process runs in a nested PID namespace (a container, `bwrap --unshare-pid`):
|
|
42
|
+
* /proc/self/status lists more than one pid in `NSpid`. The walk there ends at the namespace's own
|
|
43
|
+
* pid 1, before any agent outside it could be seen, so the answer is "unknown", never "none".
|
|
12
44
|
*/
|
|
45
|
+
export declare function nestedPidNamespace(status: string): boolean;
|
|
46
|
+
/** This process's ancestry, read once. Windows: "none" (the token and the terminal confirmation still apply). */
|
|
47
|
+
export declare function ancestry(): Ancestry;
|
|
48
|
+
/** Why the ancestry is "unknown" (for the refusal), or "". */
|
|
49
|
+
export declare function ancestryWhy(): string;
|
|
50
|
+
/** Whether a Claude Code or Codex process is an ancestor of this one. */
|
|
13
51
|
export declare function agentAncestor(): boolean;
|
|
52
|
+
/** Whether this process's ancestry couldn't be read (the person-only gates then fail closed). */
|
|
53
|
+
export declare function ancestryUnknown(): boolean;
|
package/dist/ancestry.js
CHANGED
|
@@ -4,8 +4,28 @@
|
|
|
4
4
|
// environment variables can be scrubbed by the agent, the process tree only hidden by detaching
|
|
5
5
|
// (`setsid`, a daemon), which the /dev/tty confirmation covers (tty-confirm.ts). Its own module so
|
|
6
6
|
// the test suites can replace it (vitest setup) without any hook in the shipped CLI.
|
|
7
|
+
//
|
|
8
|
+
// The tree is read from /proc on Linux and with the system's own `ps` by absolute path elsewhere,
|
|
9
|
+
// never through PATH (a `ps` an agent put first on PATH could answer "no agent"). When it can't be
|
|
10
|
+
// read, the answer is "unknown", and the person-only gates treat unknown as an agent's session
|
|
11
|
+
// (projects.ts assertPersonForWidening): fail closed. The person's token still works there.
|
|
7
12
|
import { execFileSync } from "node:child_process";
|
|
13
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
8
14
|
let cached;
|
|
15
|
+
let why = "";
|
|
16
|
+
/**
|
|
17
|
+
* Thrown by a reader for a process that is not this user's (another user's, or hidden by /proc's
|
|
18
|
+
* `hidepid`): the end of this user's own process tree, so the walk answers "none". An agent's
|
|
19
|
+
* session runs as the person, so its processes are always this user's and always readable.
|
|
20
|
+
*/
|
|
21
|
+
export class OtherUsersProcess extends Error {
|
|
22
|
+
hidden;
|
|
23
|
+
/** Not visible at all (/proc's `hidepid`): it may also have just exited, so the walk checks that it didn't. */
|
|
24
|
+
constructor(hidden = false) {
|
|
25
|
+
super(hidden ? "hidden process" : "another user's process");
|
|
26
|
+
this.hidden = hidden;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
9
29
|
/** An executable that is Claude Code or Codex, by its basename (argv0) only: never a word elsewhere on a command line. */
|
|
10
30
|
export function isAgentProcess(executable) {
|
|
11
31
|
const base = (executable.trim().split(/[\\/]/).pop() ?? "").toLowerCase();
|
|
@@ -16,15 +36,6 @@ function isScriptHost(comm) {
|
|
|
16
36
|
const base = (comm.trim().split(/[\\/]/).pop() ?? "").toLowerCase();
|
|
17
37
|
return base === "node" || base === "nodejs" || base === "bun" || base === "node.exe";
|
|
18
38
|
}
|
|
19
|
-
/** The command line of `pid` (`ps -o args=`), or "". */
|
|
20
|
-
function argsOf(pid) {
|
|
21
|
-
try {
|
|
22
|
-
return execFileSync("ps", ["-o", "args=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] }).trim();
|
|
23
|
-
}
|
|
24
|
-
catch {
|
|
25
|
-
return "";
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
39
|
/**
|
|
29
40
|
* Whether a script host's command line runs Claude Code's or Codex's npm package: its script (the
|
|
30
41
|
* first argument after the runtime and its options) lies inside `@anthropic-ai/claude-code` or
|
|
@@ -36,36 +47,208 @@ export function isAgentScript(args) {
|
|
|
36
47
|
const p = script.replace(/\\/g, "/");
|
|
37
48
|
return p.includes("/@anthropic-ai/claude-code/") || p.includes("/@openai/codex/");
|
|
38
49
|
}
|
|
50
|
+
/** The system's `ps`, by absolute path (never PATH), or undefined. */
|
|
51
|
+
export const PS_PATHS = ["/bin/ps", "/usr/bin/ps"];
|
|
52
|
+
function systemPs() {
|
|
53
|
+
return PS_PATHS.find((p) => existsSync(p));
|
|
54
|
+
}
|
|
55
|
+
/** Whether /proc hides other users' processes (`hidepid` among its mount options). */
|
|
56
|
+
function procHidesOthers() {
|
|
57
|
+
try {
|
|
58
|
+
return readFileSync("/proc/mounts", "utf8")
|
|
59
|
+
.split("\n")
|
|
60
|
+
.some((l) => {
|
|
61
|
+
const f = l.split(" ");
|
|
62
|
+
return f[1] === "/proc" && (f[3] ?? "").split(",").some((o) => o.startsWith("hidepid=") && o !== "hidepid=0" && o !== "hidepid=off");
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Reads one process from /proc (Linux). Throws when it can't; OtherUsersProcess past the end of this user's tree. */
|
|
70
|
+
function procRead(pid) {
|
|
71
|
+
let stat;
|
|
72
|
+
try {
|
|
73
|
+
stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
const code = e.code;
|
|
77
|
+
if (code === "EACCES" || code === "EPERM" || code === "ENOENT") {
|
|
78
|
+
// Another user's process (visible but unreadable), or one /proc hides because it isn't ours.
|
|
79
|
+
try {
|
|
80
|
+
if (statSync(`/proc/${pid}`).uid !== process.getuid?.())
|
|
81
|
+
throw new OtherUsersProcess();
|
|
82
|
+
}
|
|
83
|
+
catch (s) {
|
|
84
|
+
if (s instanceof OtherUsersProcess)
|
|
85
|
+
throw s;
|
|
86
|
+
if (s.code === "ENOENT" && procHidesOthers())
|
|
87
|
+
throw new OtherUsersProcess(true);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
throw e;
|
|
91
|
+
}
|
|
92
|
+
// "<pid> (<comm>) <state> <ppid> …": comm may hold spaces and parentheses, so read after the last ")".
|
|
93
|
+
const close = stat.lastIndexOf(")");
|
|
94
|
+
if (close < 0)
|
|
95
|
+
throw new Error("unreadable stat");
|
|
96
|
+
const ppid = Number(stat.slice(close + 2).split(" ")[1]);
|
|
97
|
+
if (!Number.isSafeInteger(ppid))
|
|
98
|
+
throw new Error("unreadable stat");
|
|
99
|
+
// The executable's name, as `ps -o comm=` gives it on Linux.
|
|
100
|
+
const comm = stat.slice(stat.indexOf("(") + 1, close);
|
|
101
|
+
return {
|
|
102
|
+
ppid,
|
|
103
|
+
comm,
|
|
104
|
+
args: () => {
|
|
105
|
+
try {
|
|
106
|
+
return readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").join(" ").trim();
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return "";
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Reads one process with the system's `ps`. Throws when it can't. */
|
|
115
|
+
function psRead(ps, pid) {
|
|
116
|
+
const line = execFileSync(ps, ["-o", "ppid=,comm=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], env: { LC_ALL: "C" } }).trim();
|
|
117
|
+
const sp = line.search(/\s/);
|
|
118
|
+
if (sp < 0)
|
|
119
|
+
throw new Error("unreadable ps line");
|
|
120
|
+
const ppid = Number(line.slice(0, sp));
|
|
121
|
+
if (!Number.isSafeInteger(ppid))
|
|
122
|
+
throw new Error("unreadable ps line");
|
|
123
|
+
return {
|
|
124
|
+
ppid,
|
|
125
|
+
comm: line.slice(sp + 1),
|
|
126
|
+
args: () => {
|
|
127
|
+
try {
|
|
128
|
+
return execFileSync(ps, ["-o", "args=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], env: { LC_ALL: "C" } }).trim();
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return "";
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
};
|
|
135
|
+
}
|
|
39
136
|
/**
|
|
40
|
-
* Walks parent
|
|
41
|
-
*
|
|
137
|
+
* Walks parent processes from `start`, comparing each one's executable by basename (and a script
|
|
138
|
+
* host's script path). "agent" on a match; "none" once the walk reaches the root (pid 1 or 0);
|
|
139
|
+
* "unknown" when a process can't be read or the walk runs past 64 steps.
|
|
42
140
|
*/
|
|
43
|
-
export function
|
|
141
|
+
export function walkAncestry(start, read, self = process.pid) {
|
|
142
|
+
let pid = start;
|
|
143
|
+
let child = self;
|
|
144
|
+
for (let i = 0; i < 64; i++) {
|
|
145
|
+
if (pid <= 1)
|
|
146
|
+
return "none";
|
|
147
|
+
let p;
|
|
148
|
+
try {
|
|
149
|
+
p = read(pid);
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
if (e instanceof OtherUsersProcess) {
|
|
153
|
+
if (!e.hidden)
|
|
154
|
+
return "none";
|
|
155
|
+
// Hidden, or gone: a parent that exited mid-walk is no end of the tree. Its child (ours,
|
|
156
|
+
// readable) still naming it as parent means it is there, only hidden: another user's.
|
|
157
|
+
let still;
|
|
158
|
+
try {
|
|
159
|
+
still = read(child).ppid === pid;
|
|
160
|
+
}
|
|
161
|
+
catch {
|
|
162
|
+
still = false;
|
|
163
|
+
}
|
|
164
|
+
if (still)
|
|
165
|
+
return "none";
|
|
166
|
+
why = "a process in it exited while it was read: run the command again";
|
|
167
|
+
return "unknown";
|
|
168
|
+
}
|
|
169
|
+
why = e.code === "ETIMEDOUT" || /timed? ?out/i.test(String(e.message)) ? "reading it timed out: run the command again" : "a process in it couldn't be read: run the command again";
|
|
170
|
+
return "unknown";
|
|
171
|
+
}
|
|
172
|
+
if (isAgentProcess(p.comm) || (isScriptHost(p.comm) && isAgentScript(p.args())))
|
|
173
|
+
return "agent";
|
|
174
|
+
if (p.ppid === pid) {
|
|
175
|
+
why = "it loops";
|
|
176
|
+
return "unknown";
|
|
177
|
+
}
|
|
178
|
+
child = pid;
|
|
179
|
+
pid = p.ppid;
|
|
180
|
+
}
|
|
181
|
+
why = "it is deeper than 64 processes";
|
|
182
|
+
return "unknown";
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Linux: whether this process's user namespace is the initial one: /proc/self/uid_map is exactly
|
|
186
|
+
* one line "0 0 4294967295". In any other (an unprivileged sandbox, a rootless container) /proc
|
|
187
|
+
* entries can be bind-mounted to say anything, so the walk can't be trusted: "unknown".
|
|
188
|
+
*/
|
|
189
|
+
export function initialUserNamespace(uidMap) {
|
|
190
|
+
const lines = uidMap.split("\n").map((l) => l.trim().split(/\s+/).join(" ")).filter((l) => l !== "");
|
|
191
|
+
return lines.length === 1 && lines[0] === "0 0 4294967295";
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Linux: whether this process runs in a nested PID namespace (a container, `bwrap --unshare-pid`):
|
|
195
|
+
* /proc/self/status lists more than one pid in `NSpid`. The walk there ends at the namespace's own
|
|
196
|
+
* pid 1, before any agent outside it could be seen, so the answer is "unknown", never "none".
|
|
197
|
+
*/
|
|
198
|
+
export function nestedPidNamespace(status) {
|
|
199
|
+
const line = status.split("\n").find((l) => l.startsWith("NSpid:"));
|
|
200
|
+
return line !== undefined && line.slice(6).trim().split(/\s+/).filter(Boolean).length > 1;
|
|
201
|
+
}
|
|
202
|
+
/** This process's ancestry, read once. Windows: "none" (the token and the terminal confirmation still apply). */
|
|
203
|
+
export function ancestry() {
|
|
44
204
|
if (cached !== undefined)
|
|
45
205
|
return cached;
|
|
46
|
-
|
|
206
|
+
// Windows: no process-tree check at all (fails open there: the agents' variables, the person
|
|
207
|
+
// token and the terminal confirmation still apply).
|
|
47
208
|
if (process.platform === "win32")
|
|
48
|
-
return cached;
|
|
49
|
-
|
|
50
|
-
let
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
209
|
+
return (cached = "none");
|
|
210
|
+
if (process.platform === "linux" && existsSync("/proc/self/stat")) {
|
|
211
|
+
let status = "";
|
|
212
|
+
try {
|
|
213
|
+
status = readFileSync("/proc/self/status", "utf8");
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
// read below
|
|
217
|
+
}
|
|
218
|
+
let uidMap = "";
|
|
219
|
+
try {
|
|
220
|
+
uidMap = readFileSync("/proc/self/uid_map", "utf8");
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
// checked below
|
|
224
|
+
}
|
|
225
|
+
if (!initialUserNamespace(uidMap)) {
|
|
226
|
+
why = "it runs in a user namespace (a sandbox or rootless container), where the process tree can't be trusted: pass your person token there";
|
|
227
|
+
return (cached = "unknown");
|
|
65
228
|
}
|
|
229
|
+
if (nestedPidNamespace(status)) {
|
|
230
|
+
why = "it runs in a container or sandbox with its own process namespace, where an agent outside can't be seen: pass your person token there";
|
|
231
|
+
return (cached = "unknown");
|
|
232
|
+
}
|
|
233
|
+
return (cached = walkAncestry(process.ppid, procRead));
|
|
66
234
|
}
|
|
67
|
-
|
|
68
|
-
|
|
235
|
+
const ps = systemPs();
|
|
236
|
+
if (!ps) {
|
|
237
|
+
why = "there is no system ps (/bin/ps or /usr/bin/ps)";
|
|
238
|
+
return (cached = "unknown");
|
|
69
239
|
}
|
|
240
|
+
cached = walkAncestry(process.ppid, (pid) => psRead(ps, pid));
|
|
70
241
|
return cached;
|
|
71
242
|
}
|
|
243
|
+
/** Why the ancestry is "unknown" (for the refusal), or "". */
|
|
244
|
+
export function ancestryWhy() {
|
|
245
|
+
return ancestry() === "unknown" ? why : "";
|
|
246
|
+
}
|
|
247
|
+
/** Whether a Claude Code or Codex process is an ancestor of this one. */
|
|
248
|
+
export function agentAncestor() {
|
|
249
|
+
return ancestry() === "agent";
|
|
250
|
+
}
|
|
251
|
+
/** Whether this process's ancestry couldn't be read (the person-only gates then fail closed). */
|
|
252
|
+
export function ancestryUnknown() {
|
|
253
|
+
return ancestry() === "unknown";
|
|
254
|
+
}
|
package/dist/app.d.ts
CHANGED
|
@@ -85,6 +85,16 @@ export interface Delivery {
|
|
|
85
85
|
export declare class App {
|
|
86
86
|
/** The person's front end vouched for this command (P2P_PERSON_TOKEN, checked once and removed: projects.ts). */
|
|
87
87
|
front: boolean;
|
|
88
|
+
/**
|
|
89
|
+
* The token `front` rests on, kept in memory (never in the environment), so the keys this command
|
|
90
|
+
* loads are checked against it (load): a home whose files change after the start never lends the
|
|
91
|
+
* token to other keys. Undefined for an embedder that vouches without one.
|
|
92
|
+
*/
|
|
93
|
+
frontToken?: string;
|
|
94
|
+
/** The home held no identity when the token was checked (a front end's first run). */
|
|
95
|
+
frontFresh: boolean;
|
|
96
|
+
/** This command made, restored or swapped in the identity it holds (init, link join, restore, a rotation's swap). */
|
|
97
|
+
identityMadeHere: boolean;
|
|
88
98
|
/** The person's "yes" on their controlling terminal (tty-confirm.ts); cli.ts may stand another in (tests). */
|
|
89
99
|
confirmTty: (question: string) => Promise<boolean>;
|
|
90
100
|
readonly env: Env;
|
|
@@ -144,6 +154,13 @@ export declare class App {
|
|
|
144
154
|
constructor(opts: AppOptions);
|
|
145
155
|
/** Loads this device's keys. With `require`, a missing identity is an error. */
|
|
146
156
|
load(require?: boolean): Promise<boolean>;
|
|
157
|
+
/**
|
|
158
|
+
* The person token this command was given must be the one these keys derive (projects.ts
|
|
159
|
+
* personTokenMatchesKeys), unless this command made the identity itself. A home that had no
|
|
160
|
+
* identity when the token was checked, and has one now that this command didn't make, never
|
|
161
|
+
* keeps it. Otherwise the command stops: the home changed under it.
|
|
162
|
+
*/
|
|
163
|
+
private checkFrontKeys;
|
|
147
164
|
setKeys(keys: KeysDoc, self: SelfDoc): void;
|
|
148
165
|
get userId(): string;
|
|
149
166
|
get did(): string;
|
|
@@ -208,6 +225,12 @@ export declare class App {
|
|
|
208
225
|
* Network I/O for core's refreshIdentity (§5.6), per relay so core can cap
|
|
209
226
|
* each relay's answer on its own: `tips` and the `chain` walk
|
|
210
227
|
* (`/v3/identity/<id>/chain?to=&n=`) on every listed relay (at most 5).
|
|
228
|
+
*
|
|
229
|
+
* #78: a relay that couldn't be reached (an error or a timeout) is left out of the answer, and when none
|
|
230
|
+
* of the relays asked answered the call fails, so core counts it as a relay that didn't answer (core asks
|
|
231
|
+
* one relay per call), never as one that answered "nothing": its silence doesn't make up a majority that
|
|
232
|
+
* clears pending heads or counts as fresh, and a relay is never named as forging over a gap the silent
|
|
233
|
+
* one wasn't really asked about.
|
|
211
234
|
*/
|
|
212
235
|
fetcher(): IdentityFetcher;
|
|
213
236
|
/**
|
|
@@ -255,11 +278,30 @@ export declare class App {
|
|
|
255
278
|
* none), never one whose genuine gap the walk merely didn't reach. And the confirmed head must not be
|
|
256
279
|
* below any version the full refresh left unconnected, unless every relay that sent that version is set
|
|
257
280
|
* aside: a lagging kept relay can't "confirm" a stale head while another relay serves a newer version.
|
|
258
|
-
* (
|
|
259
|
-
* version shows it in this refresh.)
|
|
281
|
+
* (A newer version an earlier refresh stored as a pending head, from a relay silent now: ownPendingGuard.)
|
|
260
282
|
* Returns the view, or undefined when this doesn't apply (the caller then refuses as before).
|
|
261
283
|
*/
|
|
262
284
|
private ownStrictFallback;
|
|
285
|
+
/**
|
|
286
|
+
* #78: a strict refresh of our own identity skips relays that don't answer, so a lagging relay could
|
|
287
|
+
* "confirm" a stale head while the up-to-date one times out. This device may already hold the newer
|
|
288
|
+
* version, as a pending head an earlier, incomplete refresh recorded with the relays that sent it. Refuses
|
|
289
|
+
* when a pending head above the confirmed head was sent by a relay that:
|
|
290
|
+
* - is still listed and isn't set aside by this edit (`setAside.relays`: the relays it removes), so
|
|
291
|
+
* `p2p relays remove` always gets past a relay that holds the owner up. A pending head another relay
|
|
292
|
+
* sent too still holds the edit up while that one is silent (#78 re-review: removing a relay that
|
|
293
|
+
* replayed an honest relay's version, and now withholds it, mustn't fork against it); silent relays
|
|
294
|
+
* that hold each other up are removed together (`relays remove` takes several);
|
|
295
|
+
* - wasn't named as serving versions that don't connect (a forged chain's, core's unconnectedRelays);
|
|
296
|
+
* - didn't answer this refresh: a relay that answered gave its current tips, so what it still serves is
|
|
297
|
+
* already in this refresh (connected, or the refresh failed or was cut short), and what it no longer
|
|
298
|
+
* serves doesn't hold the owner up.
|
|
299
|
+
* So one relay can hold an edit up only while it stays silent, and only with a version signed with the
|
|
300
|
+
* identity key above the head the other relays confirm (a genuine newer version, which building below would
|
|
301
|
+
* fork, or a thief's); removing that relay always goes ahead. A pending head stored without its senders
|
|
302
|
+
* (older builds), expired, or not a valid version of this identity never holds an edit up.
|
|
303
|
+
*/
|
|
304
|
+
private ownPendingGuard;
|
|
263
305
|
/** Relays a (bundled, unverified) identity document lists: only a hint for where to refresh from. */
|
|
264
306
|
static relaysOf(docJws: string | undefined): string[];
|
|
265
307
|
/** The view of `userId`, refreshed from the relays its document lists (or `hint`, then ours, when unknown). */
|