@peer2peer/cli 0.0.0-stage → 0.1.1

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.
Files changed (111) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +370 -2
  3. package/dist/ancestry.d.ts +13 -0
  4. package/dist/ancestry.js +71 -0
  5. package/dist/app.d.ts +368 -0
  6. package/dist/app.js +1181 -0
  7. package/dist/bin.d.ts +2 -0
  8. package/dist/bin.js +56 -0
  9. package/dist/circle-ops.d.ts +402 -0
  10. package/dist/circle-ops.js +1725 -0
  11. package/dist/cli.d.ts +660 -0
  12. package/dist/cli.js +1787 -0
  13. package/dist/codes.d.ts +231 -0
  14. package/dist/codes.js +998 -0
  15. package/dist/config.d.ts +159 -0
  16. package/dist/config.js +294 -0
  17. package/dist/doctor.d.ts +113 -0
  18. package/dist/doctor.js +930 -0
  19. package/dist/errors.d.ts +8 -0
  20. package/dist/errors.js +29 -0
  21. package/dist/ext-host.d.ts +38 -0
  22. package/dist/ext-host.js +293 -0
  23. package/dist/extensions.d.ts +487 -0
  24. package/dist/extensions.js +406 -0
  25. package/dist/features.d.ts +91 -0
  26. package/dist/features.js +164 -0
  27. package/dist/format.d.ts +57 -0
  28. package/dist/format.js +248 -0
  29. package/dist/graph-memory.d.ts +107 -0
  30. package/dist/graph-memory.js +393 -0
  31. package/dist/history.d.ts +155 -0
  32. package/dist/history.js +697 -0
  33. package/dist/identity.d.ts +239 -0
  34. package/dist/identity.js +759 -0
  35. package/dist/inbound.d.ts +32 -0
  36. package/dist/inbound.js +261 -0
  37. package/dist/index.d.ts +8 -0
  38. package/dist/index.js +14 -0
  39. package/dist/ix-local.d.ts +76 -0
  40. package/dist/ix-local.js +203 -0
  41. package/dist/join-answers.d.ts +49 -0
  42. package/dist/join-answers.js +149 -0
  43. package/dist/outbox.d.ts +109 -0
  44. package/dist/outbox.js +337 -0
  45. package/dist/pretty.d.ts +100 -0
  46. package/dist/pretty.js +256 -0
  47. package/dist/procstart.d.ts +1 -0
  48. package/dist/procstart.js +66 -0
  49. package/dist/progress.d.ts +30 -0
  50. package/dist/progress.js +78 -0
  51. package/dist/projects.d.ts +491 -0
  52. package/dist/projects.js +1383 -0
  53. package/dist/prompt/picker.d.ts +64 -0
  54. package/dist/prompt/picker.js +152 -0
  55. package/dist/prompt/tty.d.ts +29 -0
  56. package/dist/prompt/tty.js +122 -0
  57. package/dist/readonly.d.ts +20 -0
  58. package/dist/readonly.js +50 -0
  59. package/dist/receipts.d.ts +99 -0
  60. package/dist/receipts.js +182 -0
  61. package/dist/relay-client.d.ts +277 -0
  62. package/dist/relay-client.js +873 -0
  63. package/dist/relay-info.d.ts +24 -0
  64. package/dist/relay-info.js +53 -0
  65. package/dist/rotation.d.ts +402 -0
  66. package/dist/rotation.js +2054 -0
  67. package/dist/running.d.ts +5 -0
  68. package/dist/running.js +74 -0
  69. package/dist/sessions.d.ts +355 -0
  70. package/dist/sessions.js +1247 -0
  71. package/dist/shortcode.d.ts +149 -0
  72. package/dist/shortcode.js +465 -0
  73. package/dist/social.d.ts +139 -0
  74. package/dist/social.js +485 -0
  75. package/dist/state.d.ts +509 -0
  76. package/dist/state.js +220 -0
  77. package/dist/stdin.d.ts +17 -0
  78. package/dist/stdin.js +46 -0
  79. package/dist/sync.d.ts +77 -0
  80. package/dist/sync.js +375 -0
  81. package/dist/transient.d.ts +1 -0
  82. package/dist/transient.js +28 -0
  83. package/dist/trust.d.ts +37 -0
  84. package/dist/trust.js +134 -0
  85. package/dist/tty-confirm.d.ts +2 -0
  86. package/dist/tty-confirm.js +53 -0
  87. package/dist/tui/command.d.ts +20 -0
  88. package/dist/tui/command.js +70 -0
  89. package/dist/tui/frame.d.ts +43 -0
  90. package/dist/tui/frame.js +111 -0
  91. package/dist/tui/model.d.ts +221 -0
  92. package/dist/tui/model.js +259 -0
  93. package/dist/tui/sanitize.d.ts +13 -0
  94. package/dist/tui/sanitize.js +151 -0
  95. package/dist/tui/terminal.d.ts +88 -0
  96. package/dist/tui/terminal.js +354 -0
  97. package/dist/tui/tui.d.ts +78 -0
  98. package/dist/tui/tui.js +612 -0
  99. package/dist/tui/view.d.ts +4 -0
  100. package/dist/tui/view.js +358 -0
  101. package/dist/unknown-kinds.d.ts +12 -0
  102. package/dist/unknown-kinds.js +66 -0
  103. package/dist/version.d.ts +1 -0
  104. package/dist/version.js +5 -0
  105. package/dist/want-pow.d.ts +12 -0
  106. package/dist/want-pow.js +46 -0
  107. package/dist/watch.d.ts +35 -0
  108. package/dist/watch.js +331 -0
  109. package/dist/xstate.d.ts +125 -0
  110. package/dist/xstate.js +422 -0
  111. package/package.json +60 -4
@@ -0,0 +1,159 @@
1
+ export type Env = Record<string, string | undefined>;
2
+ export interface FileConfig {
3
+ defaultRelays?: string[];
4
+ /** Enabled extension namespaces (`p2p extensions enable ix`); see extensions.ts. */
5
+ extensions?: string[];
6
+ transport?: Record<string, string>;
7
+ /** Send `caps` in statuses (§4.3 "Status caps"); on by default since P1, `false` opts out. P2P_STATUS_CAPS wins. */
8
+ statusCaps?: boolean;
9
+ /** Send delivery receipts (§4.3 "Delivery receipts"); on by default, `false` turns them off. P2P_RECEIPTS wins. */
10
+ receipts?: boolean;
11
+ /** Who this user trusts to drive a session that approves its own tool calls (trust.ts): full userIds and circle ids. */
12
+ trust?: {
13
+ users?: string[];
14
+ circles?: string[];
15
+ };
16
+ /** Publish this device's caps and version in the identity document (`dinfo`); off until step 2 (docs/compatibility.md). P2P_DEVICE_INFO wins. */
17
+ deviceInfo?: boolean;
18
+ /** The local Ix backend (projects.ts localGraphEndpoint): honoured only as a loopback URL. Default http://localhost:8090. */
19
+ ixEndpoint?: string;
20
+ /**
21
+ * Trust a root-owned listener on the local Ix endpoint's port (ext-ix listener.ts): Docker's port
22
+ * proxy on Linux runs as root whoever started the container, so on a machine whose Docker others
23
+ * use too it may be a teammate's backend. Off by default; only this file turns it on (hand-edited:
24
+ * no command writes it, and no environment variable overrides it).
25
+ */
26
+ ixTrustRootListener?: boolean;
27
+ /** Message history (history.ts): on by default, kept `retentionDays` (30) and at most `maxBytes` (8 MiB). P2P_HISTORY=0 turns recording off. */
28
+ history?: {
29
+ enabled?: boolean;
30
+ retentionDays?: number;
31
+ maxBytes?: number;
32
+ };
33
+ /** Graph memory (graph-memory.ts): this device's sessions' context into the local Ix graph; on by default with the Ix extension, `false` turns it off. P2P_IX_MEMORY=0 turns it off too. */
34
+ ixMemory?: boolean;
35
+ /**
36
+ * Messages from your own agent sessions skip the hold in a session that approves its own tool calls
37
+ * (`p2p own-agents deliver`, person only). Off by default: they are held like a peer's. No variable
38
+ * overrides it, so nothing an agent sets in its environment turns it on.
39
+ */
40
+ ownAgentsDeliver?: boolean;
41
+ /**
42
+ * Narrower (`p2p own-agents deliver --devices <did…|all-other>`, person only): messages from your own
43
+ * sessions on these other devices skip the hold, while this device's agent sessions stay held. Another
44
+ * device can't say whether you typed a message (that needs the wire field of RFC #48), so this trusts
45
+ * every session there.
46
+ */
47
+ ownDevicesDeliver?: string[] | "all-other";
48
+ }
49
+ /**
50
+ * Whether `p2p watch` writes this device's sessions' context into the local Ix graph (graph-memory.ts):
51
+ * on by default (it needs the Ix extension and an Ix with the OSS `ix note`). `"ixMemory": false` in
52
+ * config.json turns it off, and so does P2P_IX_MEMORY=0 (or `false`). The environment can only turn it
53
+ * off: it never overrides the person's `false`.
54
+ */
55
+ export declare function graphMemoryEnabled(env: Env, home: string): boolean;
56
+ /** Whether your own agent sessions' messages skip the hold (FileConfig.ownAgentsDeliver). */
57
+ export declare function ownAgentsDeliver(home: string): boolean;
58
+ /** The other devices whose sessions skip the hold (FileConfig.ownDevicesDeliver): none, a list, or every other one. */
59
+ export declare function ownDevicesDeliver(home: string): string[] | "all-other";
60
+ /**
61
+ * Whether a message from one of your own agent sessions on device `did` skips the hold now (read at
62
+ * delivery time, never stamped on an event): `own-agents deliver`, or `--devices` naming that device
63
+ * (another device than this one).
64
+ */
65
+ export declare function ownAgentsDeliverFrom(home: string, did: string, thisDevice: string): boolean;
66
+ /**
67
+ * Whether this device puts its caps and client version in the identity document (`dinfo`).
68
+ * Off by default in this release: pre-release clients from before protocol 3.1 refuse
69
+ * an identity document with a field they don't know, so the user would become unreachable to them.
70
+ * Step 2 (once the two previous releases are 3.1) turns it on. `P2P_DEVICE_INFO` (`1`/`true`,
71
+ * `0`/`false`) wins over `"deviceInfo": true` in config.json. Even on, it is published only to
72
+ * relays that list `identity.lenient` (relay-info.ts).
73
+ */
74
+ export declare function deviceInfoEnabled(env: Env, home: string): boolean;
75
+ /**
76
+ * Whether this user sends delivery receipts, and advertises `receipts.v1` (§4.3): on by default.
77
+ * `P2P_RECEIPTS` (`1`/`true` on, `0`/`false` off) wins over `"receipts": false` in config.json.
78
+ * Off, no receipt goes out and no status advertises the cap, so senders see what an older client
79
+ * looks like ("no receipt yet"): turning them off is not itself revealed.
80
+ */
81
+ export declare function receiptsEnabled(env: Env, home: string): boolean;
82
+ /**
83
+ * Whether statuses carry `caps` (two-step rollout, §4.3, step 2): on by
84
+ * default. `P2P_STATUS_CAPS` (`1`/`true` on, `0`/`false` off) wins over
85
+ * `"statusCaps": false` in config.json, the opt-out for a user whose peers
86
+ * still run a client older than the amendment (it rejects a status carrying
87
+ * `caps`). A broken config.json counts as the default (the command reports
88
+ * it elsewhere).
89
+ */
90
+ export declare function statusCapsEnabled(env: Env, home: string): boolean;
91
+ export declare function resolveHome(env: Env): string;
92
+ export declare function readFileConfig(home: string): FileConfig;
93
+ /** `p2p receipts on|off`: sets `receipts` in <home>/config.json (atomically, 0600). */
94
+ export declare function setReceiptsEnabled(home: string, on: boolean): void;
95
+ /**
96
+ * Read-modify-write of one top-level field of <home>/config.json under the state lock, so two
97
+ * commands changing it at once (`p2p receipts`, `p2p trust`) never lose an update (pre-release review N3).
98
+ * `fn` gets the field as stored and returns its next value and a result.
99
+ */
100
+ export declare function updateFileConfigField<R>(app: {
101
+ home: string;
102
+ state: {
103
+ withLock<T>(fn: () => Promise<T>): Promise<T>;
104
+ };
105
+ }, key: string, fn: (cur: unknown) => {
106
+ next: unknown;
107
+ result: R;
108
+ }): Promise<R>;
109
+ /** Sets one top-level field of <home>/config.json, keeping the rest (atomically, 0600). Callers hold the state lock. */
110
+ export declare function setFileConfigField(home: string, key: string, value: unknown): void;
111
+ /** Canonicalises, de-duplicates and bounds a relay list (1–5, §5.8). */
112
+ export declare function normalizeRelays(list: readonly string[]): string[];
113
+ /** `defaultRelays` from the `defaults.json` beside the CLI (or `P2P_DEFAULTS_FILE`); [] when there is none. */
114
+ export declare function shippedDefaultRelays(env: Env): string[];
115
+ /** The relays a new identity uses when `--relay` is not given. */
116
+ export declare function defaultRelays(env: Env, file: FileConfig): string[];
117
+ export interface Transport {
118
+ /** What the WebSocket dials. */
119
+ ws: string;
120
+ /** The document API base (§5.6): `<http>/identity/<userId>`. */
121
+ http: string;
122
+ }
123
+ export type TransportResolver = (canonical: string) => Transport;
124
+ export declare function transportResolver(env: Env, file: FileConfig): TransportResolver;
125
+ /** Tunables, mostly so tests run fast. */
126
+ export interface Tunables {
127
+ /** How long a short command listens for queued envelopes after connecting. */
128
+ drainQuietMs: number;
129
+ drainMaxMs: number;
130
+ /** Re-fetch a contact's identity document when the copy is older than this. */
131
+ docRefreshSec: number;
132
+ /** Link mailbox polling. */
133
+ linkPollMs: number;
134
+ /** Per-relay connect timeout: each of dial, hello and auth (and an HTTP document fetch). */
135
+ connectTimeoutMs: number;
136
+ /** Per relay request (send, identity, invite-*, …). */
137
+ requestTimeoutMs: number;
138
+ /** A whole short command (not `watch`; `--wait` adds to it; 0 = none). */
139
+ commandTimeoutSec: number;
140
+ /** How long a failed identity lookup is remembered before trying again. */
141
+ discoverRetrySec: number;
142
+ /** A relay refusing this device triggers at most one own-document refresh per this long. */
143
+ refusedRefreshSec: number;
144
+ /** A relay that refused a publish outright is retried automatically at most this often. */
145
+ refusedPublishRetrySec: number;
146
+ /** Bytes of circle history this client sends, per rolling hour, in answer to non-members' `want`s. */
147
+ strangerAnswerBytesPerHour: number;
148
+ /** Bytes of circle history sent per rolling hour to non-members whose want names no version they were offered. */
149
+ unlinkedAnswerBytesPerHour: number;
150
+ /** How long each device after the first in answering order waits before answering a want nobody answered. */
151
+ wantFallbackSec: number;
152
+ /** Bytes of one circle's history sent per rolling hour to all its members together. */
153
+ memberAnswerBytesPerCirclePerHour: number;
154
+ /** Bytes of circle history this client sends one asker (member or not) per rolling hour. */
155
+ answerBytesPerAskerPerHour: number;
156
+ /** Tests only: a smaller cap on a code's sealed bundle than the relay's (never a larger one). */
157
+ inviteBlobMax?: number;
158
+ }
159
+ export declare function tunables(env: Env): Tunables;
package/dist/config.js ADDED
@@ -0,0 +1,294 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Where the CLI keeps its state, which relays a new identity uses, and how a
4
+ // canonical relay URL is actually reached.
5
+ //
6
+ // - Home: `P2P_HOME`, else `~/.p2p`. The v3 trust store lives in
7
+ // `<home>/v3` (FileTrustStoreV3), the CLI's own documents in `<home>/cli`,
8
+ // both 0700 with 0600 files written atomically under a cross-process lock.
9
+ // - Default relays: none are hardcoded. `P2P_DEFAULT_RELAYS` (comma or
10
+ // space separated) wins over `defaultRelays` in `<home>/config.json`,
11
+ // which wins over `defaultRelays` in a `defaults.json` shipped next to the
12
+ // CLI (the bundled single-file build; `P2P_DEFAULTS_FILE` names another).
13
+ // - Transport overrides: a canonical relay URL (always `wss://…`, §5.1) is
14
+ // dialled at itself, and its document API at `https://<host>/<path>`.
15
+ // `P2P_RELAY_TRANSPORT` (JSON) or `transport` in config.json can map a
16
+ // canonical URL to another dial URL, e.g. a local relay without TLS:
17
+ // `{"wss://relay.test/v3": "ws://127.0.0.1:8080/v3"}`. It is a hosts file
18
+ // for relays: the hello check still compares against the canonical URL.
19
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
20
+ import { homedir } from "node:os";
21
+ import { join } from "node:path";
22
+ import { fileURLToPath } from "node:url";
23
+ import { canonicalRelayUrl, MAX_RELAYS, relayHttpsBase } from "@peer2peer/core/v3";
24
+ import { CliError } from "./errors.js";
25
+ /**
26
+ * Whether `p2p watch` writes this device's sessions' context into the local Ix graph (graph-memory.ts):
27
+ * on by default (it needs the Ix extension and an Ix with the OSS `ix note`). `"ixMemory": false` in
28
+ * config.json turns it off, and so does P2P_IX_MEMORY=0 (or `false`). The environment can only turn it
29
+ * off: it never overrides the person's `false`.
30
+ */
31
+ export function graphMemoryEnabled(env, home) {
32
+ const v = env.P2P_IX_MEMORY?.trim().toLowerCase();
33
+ if (v === "0" || v === "false")
34
+ return false;
35
+ try {
36
+ return readFileConfig(home).ixMemory !== false;
37
+ }
38
+ catch {
39
+ return true;
40
+ }
41
+ }
42
+ /** Whether your own agent sessions' messages skip the hold (FileConfig.ownAgentsDeliver). */
43
+ export function ownAgentsDeliver(home) {
44
+ try {
45
+ return readFileConfig(home).ownAgentsDeliver === true;
46
+ }
47
+ catch {
48
+ return false;
49
+ }
50
+ }
51
+ /** The other devices whose sessions skip the hold (FileConfig.ownDevicesDeliver): none, a list, or every other one. */
52
+ export function ownDevicesDeliver(home) {
53
+ try {
54
+ const v = readFileConfig(home).ownDevicesDeliver;
55
+ if (v === "all-other")
56
+ return v;
57
+ return Array.isArray(v) ? v.filter((d) => typeof d === "string") : [];
58
+ }
59
+ catch {
60
+ return [];
61
+ }
62
+ }
63
+ /**
64
+ * Whether a message from one of your own agent sessions on device `did` skips the hold now (read at
65
+ * delivery time, never stamped on an event): `own-agents deliver`, or `--devices` naming that device
66
+ * (another device than this one).
67
+ */
68
+ export function ownAgentsDeliverFrom(home, did, thisDevice) {
69
+ if (ownAgentsDeliver(home))
70
+ return true;
71
+ if (did === thisDevice)
72
+ return false;
73
+ const devices = ownDevicesDeliver(home);
74
+ return devices === "all-other" || devices.includes(did);
75
+ }
76
+ /**
77
+ * Whether this device puts its caps and client version in the identity document (`dinfo`).
78
+ * Off by default in this release: pre-release clients from before protocol 3.1 refuse
79
+ * an identity document with a field they don't know, so the user would become unreachable to them.
80
+ * Step 2 (once the two previous releases are 3.1) turns it on. `P2P_DEVICE_INFO` (`1`/`true`,
81
+ * `0`/`false`) wins over `"deviceInfo": true` in config.json. Even on, it is published only to
82
+ * relays that list `identity.lenient` (relay-info.ts).
83
+ */
84
+ export function deviceInfoEnabled(env, home) {
85
+ const v = env.P2P_DEVICE_INFO?.trim().toLowerCase();
86
+ if (v === "1" || v === "true")
87
+ return true;
88
+ if (v === "0" || v === "false")
89
+ return false;
90
+ try {
91
+ return readFileConfig(home).deviceInfo === true;
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ }
97
+ /**
98
+ * Whether this user sends delivery receipts, and advertises `receipts.v1` (§4.3): on by default.
99
+ * `P2P_RECEIPTS` (`1`/`true` on, `0`/`false` off) wins over `"receipts": false` in config.json.
100
+ * Off, no receipt goes out and no status advertises the cap, so senders see what an older client
101
+ * looks like ("no receipt yet"): turning them off is not itself revealed.
102
+ */
103
+ export function receiptsEnabled(env, home) {
104
+ const v = env.P2P_RECEIPTS?.trim().toLowerCase();
105
+ if (v === "1" || v === "true")
106
+ return true;
107
+ if (v === "0" || v === "false")
108
+ return false;
109
+ try {
110
+ return readFileConfig(home).receipts !== false;
111
+ }
112
+ catch {
113
+ return true;
114
+ }
115
+ }
116
+ /**
117
+ * Whether statuses carry `caps` (two-step rollout, §4.3, step 2): on by
118
+ * default. `P2P_STATUS_CAPS` (`1`/`true` on, `0`/`false` off) wins over
119
+ * `"statusCaps": false` in config.json, the opt-out for a user whose peers
120
+ * still run a client older than the amendment (it rejects a status carrying
121
+ * `caps`). A broken config.json counts as the default (the command reports
122
+ * it elsewhere).
123
+ */
124
+ export function statusCapsEnabled(env, home) {
125
+ const v = env.P2P_STATUS_CAPS?.trim().toLowerCase();
126
+ if (v === "1" || v === "true")
127
+ return true;
128
+ if (v === "0" || v === "false")
129
+ return false;
130
+ try {
131
+ return readFileConfig(home).statusCaps !== false;
132
+ }
133
+ catch {
134
+ return true;
135
+ }
136
+ }
137
+ export function resolveHome(env) {
138
+ const h = env.P2P_HOME?.trim();
139
+ return h ? h : join(homedir(), ".p2p");
140
+ }
141
+ export function readFileConfig(home) {
142
+ let raw;
143
+ try {
144
+ raw = readFileSync(join(home, "config.json"), "utf8");
145
+ }
146
+ catch {
147
+ return {};
148
+ }
149
+ let v;
150
+ try {
151
+ v = JSON.parse(raw);
152
+ }
153
+ catch {
154
+ throw new CliError("config", `${join(home, "config.json")} is not valid JSON`);
155
+ }
156
+ if (typeof v !== "object" || v === null || Array.isArray(v))
157
+ throw new CliError("config", "config.json must hold a JSON object");
158
+ return v;
159
+ }
160
+ /** `p2p receipts on|off`: sets `receipts` in <home>/config.json (atomically, 0600). */
161
+ export function setReceiptsEnabled(home, on) {
162
+ setFileConfigField(home, "receipts", on);
163
+ }
164
+ /**
165
+ * Read-modify-write of one top-level field of <home>/config.json under the state lock, so two
166
+ * commands changing it at once (`p2p receipts`, `p2p trust`) never lose an update (pre-release review N3).
167
+ * `fn` gets the field as stored and returns its next value and a result.
168
+ */
169
+ export async function updateFileConfigField(app, key, fn) {
170
+ return app.state.withLock(async () => {
171
+ const r = fn(readFileConfig(app.home)[key]);
172
+ setFileConfigField(app.home, key, r.next);
173
+ return r.result;
174
+ });
175
+ }
176
+ /** Sets one top-level field of <home>/config.json, keeping the rest (atomically, 0600). Callers hold the state lock. */
177
+ export function setFileConfigField(home, key, value) {
178
+ const p = join(home, "config.json");
179
+ const cfg = readFileConfig(home);
180
+ mkdirSync(home, { recursive: true, mode: 0o700 });
181
+ const tmp = `${p}.${process.pid}.tmp`;
182
+ writeFileSync(tmp, JSON.stringify({ ...cfg, [key]: value }, null, 2) + "\n", { mode: 0o600 });
183
+ renameSync(tmp, p);
184
+ }
185
+ /** Canonicalises, de-duplicates and bounds a relay list (1–5, §5.8). */
186
+ export function normalizeRelays(list) {
187
+ const out = [];
188
+ for (const r of list) {
189
+ let c;
190
+ try {
191
+ c = canonicalRelayUrl(r.trim());
192
+ }
193
+ catch (e) {
194
+ throw new CliError("bad_relay", `${r} is not a relay URL: ${e.message}`);
195
+ }
196
+ if (!out.includes(c))
197
+ out.push(c);
198
+ }
199
+ if (out.length > MAX_RELAYS)
200
+ throw new CliError("bad_relay", `at most ${MAX_RELAYS} relays (got ${out.length})`);
201
+ return out;
202
+ }
203
+ /** `defaultRelays` from the `defaults.json` beside the CLI (or `P2P_DEFAULTS_FILE`); [] when there is none. */
204
+ export function shippedDefaultRelays(env) {
205
+ let path;
206
+ try {
207
+ path = env.P2P_DEFAULTS_FILE?.trim() || fileURLToPath(new URL("./defaults.json", import.meta.url));
208
+ }
209
+ catch {
210
+ return [];
211
+ }
212
+ let raw;
213
+ try {
214
+ raw = readFileSync(path, "utf8");
215
+ }
216
+ catch {
217
+ return [];
218
+ }
219
+ try {
220
+ const v = JSON.parse(raw);
221
+ if (v.defaultRelays === undefined)
222
+ return [];
223
+ if (!Array.isArray(v.defaultRelays) || v.defaultRelays.some((x) => typeof x !== "string"))
224
+ throw new Error("defaultRelays must be a list of relay URLs");
225
+ return v.defaultRelays;
226
+ }
227
+ catch (e) {
228
+ throw new CliError("config", `${path}: ${e.message}`);
229
+ }
230
+ }
231
+ /** The relays a new identity uses when `--relay` is not given. */
232
+ export function defaultRelays(env, file) {
233
+ const fromEnv = env.P2P_DEFAULT_RELAYS?.split(/[\s,]+/).filter((s) => s !== "");
234
+ const list = fromEnv && fromEnv.length > 0 ? fromEnv : file.defaultRelays && file.defaultRelays.length > 0 ? file.defaultRelays : shippedDefaultRelays(env);
235
+ return normalizeRelays(list);
236
+ }
237
+ function httpFor(ws) {
238
+ return ws.replace(/^wss:/, "https:").replace(/^ws:/, "http:");
239
+ }
240
+ export function transportResolver(env, file) {
241
+ let map = { ...(file.transport ?? {}) };
242
+ if (env.P2P_RELAY_TRANSPORT) {
243
+ try {
244
+ const v = JSON.parse(env.P2P_RELAY_TRANSPORT);
245
+ if (typeof v !== "object" || v === null || Array.isArray(v))
246
+ throw new Error("not an object");
247
+ map = { ...map, ...v };
248
+ }
249
+ catch (e) {
250
+ throw new CliError("config", `P2P_RELAY_TRANSPORT must be a JSON object: ${e.message}`);
251
+ }
252
+ }
253
+ const canon = {};
254
+ for (const [k, v] of Object.entries(map)) {
255
+ if (typeof v !== "string" || !/^wss?:\/\//.test(v))
256
+ throw new CliError("config", `transport for ${k} must be a ws:// or wss:// URL`);
257
+ canon[canonicalRelayUrl(k)] = v.replace(/\/+$/, "");
258
+ }
259
+ return (relay) => {
260
+ const c = canonicalRelayUrl(relay);
261
+ const over = canon[c];
262
+ if (over)
263
+ return { ws: over, http: httpFor(over) };
264
+ return { ws: c, http: relayHttpsBase(c) };
265
+ };
266
+ }
267
+ export function tunables(env) {
268
+ const n = (k, d) => {
269
+ const v = env[k];
270
+ if (v === undefined || v.trim() === "")
271
+ return d;
272
+ const x = Number(v);
273
+ return Number.isFinite(x) && x >= 0 ? x : d;
274
+ };
275
+ return {
276
+ drainQuietMs: n("P2P_DRAIN_QUIET_MS", 400),
277
+ drainMaxMs: n("P2P_DRAIN_MAX_MS", 5000),
278
+ docRefreshSec: n("P2P_DOC_REFRESH_SEC", 60),
279
+ linkPollMs: n("P2P_LINK_POLL_MS", 2000),
280
+ connectTimeoutMs: n("P2P_CONNECT_TIMEOUT_MS", 10_000),
281
+ requestTimeoutMs: n("P2P_REQUEST_TIMEOUT_MS", 15_000),
282
+ commandTimeoutSec: n("P2P_COMMAND_TIMEOUT_SEC", 60),
283
+ discoverRetrySec: n("P2P_DISCOVER_RETRY_SEC", 60),
284
+ refusedRefreshSec: n("P2P_REFUSED_REFRESH_SEC", 60),
285
+ refusedPublishRetrySec: n("P2P_REFUSED_PUBLISH_RETRY_SEC", 3600),
286
+ strangerAnswerBytesPerHour: n("P2P_STRANGER_ANSWER_BYTES_PER_HOUR", 8 * 1024 * 1024),
287
+ unlinkedAnswerBytesPerHour: n("P2P_UNLINKED_ANSWER_BYTES_PER_HOUR", 1024 * 1024),
288
+ wantFallbackSec: n("P2P_WANT_FALLBACK_SEC", 120),
289
+ memberAnswerBytesPerCirclePerHour: n("P2P_MEMBER_ANSWER_BYTES_PER_CIRCLE_PER_HOUR", 16 * 1024 * 1024),
290
+ answerBytesPerAskerPerHour: n("P2P_ANSWER_BYTES_PER_ASKER_PER_HOUR", 4 * 1024 * 1024),
291
+ // Tests only (the "bundle too big" case): it can only lower the cap (codes.ts takes the smaller of the two).
292
+ ...(env.P2P_INVITE_BLOB_MAX ? { inviteBlobMax: n("P2P_INVITE_BLOB_MAX", 32 * 1024) } : {}),
293
+ };
294
+ }
@@ -0,0 +1,113 @@
1
+ import { App } from "./app.js";
2
+ import { type PeerDevice } from "./features.js";
3
+ export type CheckStatus = "ok" | "fail" | "unknown";
4
+ export interface Check {
5
+ id: string;
6
+ status: CheckStatus;
7
+ title: string;
8
+ detail: string;
9
+ /** One line: what to do (✗), or what would tell (?). */
10
+ fix?: string;
11
+ }
12
+ export interface DoctorResult {
13
+ scope: "device" | "user";
14
+ version: string;
15
+ user?: {
16
+ input: string;
17
+ userId?: string;
18
+ address?: string;
19
+ };
20
+ checks: Check[];
21
+ summary: {
22
+ ok: number;
23
+ fail: number;
24
+ unknown: number;
25
+ };
26
+ /** About a user: each of their devices with its client version and caps (docs/compatibility.md). */
27
+ devices?: PeerDevice[];
28
+ /** About a user: the known features one of you has and the other lacks. */
29
+ unavailable?: {
30
+ theyLack: string[];
31
+ weLack: string[];
32
+ };
33
+ }
34
+ export interface DoctorOptions {
35
+ /** The CLI's own version (cli.ts VERSION). */
36
+ version: string;
37
+ user?: string;
38
+ /** Overrides P2P_DOCTOR_TIMEOUT_MS (tests). */
39
+ timeoutMs?: number;
40
+ /** The mod's folder, when known (P2P_MOD_ROOT; else the folder around a bundled p2p.mjs). */
41
+ modRoot?: string;
42
+ }
43
+ /**
44
+ * Clock skew. Signed objects (device certificates, documents, caps, invites, statements) are
45
+ * refused when their `iat` is more than DEFAULT_SKEW_SEC (300 s) ahead of the verifier's clock,
46
+ * in core and at relays (relay auth too). Envelope `ts` alone tolerates 10 minutes
47
+ * (REPLAY_FUTURE_SKEW_MS), so 300 s is the real limit. Under SKEW_OK_SEC is fine (the Date
48
+ * header has 1 s resolution, plus half a round trip); up to the limit still works, so it is a
49
+ * warning; only past it does anything break.
50
+ */
51
+ export declare const SKEW_OK_SEC = 30;
52
+ export declare const SKEW_FAIL_SEC = 300;
53
+ export interface HttpProbe {
54
+ ok: boolean;
55
+ status?: number;
56
+ ms: number;
57
+ /** The server's clock (ms) from its Date header, and our midpoint of the request. */
58
+ serverMs?: number;
59
+ localMs?: number;
60
+ body?: Record<string, unknown>;
61
+ error?: string;
62
+ code?: "unreachable" | "timeout" | "network";
63
+ }
64
+ /** One bounded GET (the relay's document API), with its latency and the server's Date header. */
65
+ export declare function httpProbe(url: string, timeoutMs: number, opts?: {
66
+ maxBody?: number;
67
+ noRedirect?: boolean;
68
+ }): Promise<HttpProbe>;
69
+ export interface WsProbe {
70
+ /** Dial + hello (+ auth) took this long. */
71
+ connectMs?: number;
72
+ /** An authenticated round trip. */
73
+ rttMs?: number;
74
+ authed: boolean;
75
+ restricted: boolean;
76
+ /** Envelopes the relay pushed while we were connected (queued for this device; not acked). */
77
+ queued: number;
78
+ error?: string;
79
+ code?: string;
80
+ }
81
+ /** Dials one relay as this device (or anonymously), checks hello and auth, and makes one authenticated round trip. */
82
+ export declare function wsProbe(app: App, relay: string, timeoutMs: number, auth: boolean): Promise<WsProbe>;
83
+ export declare function modVersions(root: string): Promise<{
84
+ plugin?: string;
85
+ bundled?: string;
86
+ }>;
87
+ declare class Checks {
88
+ readonly list: Check[];
89
+ add(id: string, status: CheckStatus, title: string, detail: string, fix?: string): Check;
90
+ }
91
+ /**
92
+ * The clock check from each relay's skew (seconds, + when this device is ahead): ✓ under
93
+ * SKEW_OK_SEC, ? (a warning) up to the protocol's limit (SKEW_FAIL_SEC, 300 s), ✗ only past it.
94
+ */
95
+ export declare function clockVerdict(skews: readonly {
96
+ relay: string;
97
+ sec: number;
98
+ }[]): Check;
99
+ /**
100
+ * The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
101
+ * whether the project here is mapped, and the graph target of the project here and of each project
102
+ * with a policy ("local only" today). Without Ix nothing is a failure: Peer2Peer works without it.
103
+ * `ix` runs as ext-ix runs it (ix-local.ts): absolute path, allowlisted environment, the local
104
+ * endpoint pinned, read-only commands, bounded.
105
+ */
106
+ export declare function ixChecks(c: Checks, app: App, ms: number): Promise<void>;
107
+ export declare function summarize(checks: readonly Check[]): DoctorResult["summary"];
108
+ /** The doctor's per-step bound: P2P_DOCTOR_TIMEOUT_MS (default 5 s), never more than the connect timeout. */
109
+ export declare function doctorTimeoutMs(app: App, override?: number): number;
110
+ export declare function doctor(app: App, o: DoctorOptions): Promise<DoctorResult>;
111
+ /** Human output: one line per check (✓ ✗ ?), with its fix indented below. */
112
+ export declare function formatDoctor(r: DoctorResult): string;
113
+ export {};