@peer2peer/cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/config.d.ts CHANGED
@@ -15,7 +15,59 @@ export interface FileConfig {
15
15
  };
16
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
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
+ * The person said no to Ix when `p2p setup` recommended it (ix-local.ts): not asked again, and no
37
+ * agent hint. `p2p setup --ix` offers it again. Ix is optional; Peer2Peer never installs it.
38
+ */
39
+ ixDeclined?: boolean;
40
+ /**
41
+ * Messages from your own agent sessions skip the hold in a session that approves its own tool calls
42
+ * (`p2p own-agents deliver`, person only). Off by default: they are held like a peer's. No variable
43
+ * overrides it, so nothing an agent sets in its environment turns it on.
44
+ */
45
+ ownAgentsDeliver?: boolean;
46
+ /**
47
+ * Narrower (`p2p own-agents deliver --devices <did…|all-other>`, person only): messages from your own
48
+ * sessions on these other devices skip the hold, while this device's agent sessions stay held. Another
49
+ * device can't say whether you typed a message (that needs the wire field of RFC #48), so this trusts
50
+ * every session there.
51
+ */
52
+ ownDevicesDeliver?: string[] | "all-other";
18
53
  }
54
+ /**
55
+ * Whether `p2p watch` writes this device's sessions' context into the local Ix graph (graph-memory.ts):
56
+ * on by default (it needs the Ix extension and an Ix with the OSS `ix note`). `"ixMemory": false` in
57
+ * config.json turns it off, and so does P2P_IX_MEMORY=0 (or `false`). The environment can only turn it
58
+ * off: it never overrides the person's `false`.
59
+ */
60
+ export declare function graphMemoryEnabled(env: Env, home: string): boolean;
61
+ /** Whether your own agent sessions' messages skip the hold (FileConfig.ownAgentsDeliver). */
62
+ export declare function ownAgentsDeliver(home: string): boolean;
63
+ /** The other devices whose sessions skip the hold (FileConfig.ownDevicesDeliver): none, a list, or every other one. */
64
+ export declare function ownDevicesDeliver(home: string): string[] | "all-other";
65
+ /**
66
+ * Whether a message from one of your own agent sessions on device `did` skips the hold now (read at
67
+ * delivery time, never stamped on an event): `own-agents deliver`, or `--devices` naming that device
68
+ * (another device than this one).
69
+ */
70
+ export declare function ownAgentsDeliverFrom(home: string, did: string, thisDevice: string): boolean;
19
71
  /**
20
72
  * Whether this device puts its caps and client version in the identity document (`dinfo`).
21
73
  * Off by default in this release: pre-release clients from before protocol 3.1 refuse
package/dist/config.js CHANGED
@@ -22,6 +22,57 @@ import { join } from "node:path";
22
22
  import { fileURLToPath } from "node:url";
23
23
  import { canonicalRelayUrl, MAX_RELAYS, relayHttpsBase } from "@peer2peer/core/v3";
24
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
+ }
25
76
  /**
26
77
  * Whether this device puts its caps and client version in the identity document (`dinfo`).
27
78
  * Off by default in this release: pre-release clients from before protocol 3.1 refuse
package/dist/doctor.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { App } from "./app.js";
2
2
  import { type PeerDevice } from "./features.js";
3
+ import { type GraphMemoryDoc } from "./graph-memory.js";
4
+ import { type GraphTarget } from "./projects.js";
3
5
  export type CheckStatus = "ok" | "fail" | "unknown";
4
6
  export interface Check {
5
7
  id: string;
@@ -30,6 +32,61 @@ export interface DoctorResult {
30
32
  theyLack: string[];
31
33
  weLack: string[];
32
34
  };
35
+ /** This device: where each kind of data goes ("Where your data goes"). */
36
+ dataFlow?: DataFlow;
37
+ }
38
+ /** The threat model, which lists everything a relay sees. */
39
+ export declare const THREAT_MODEL_DOC = "docs/security/threat-model.md";
40
+ /** What is encrypted and what isn't, on one page. */
41
+ export declare const ENCRYPTION_DOC = "docs/security/encryption.md";
42
+ /**
43
+ * Some of what a relay sees besides an envelope's ciphertext (the threat model, "What each party can
44
+ * see", has the full list): never read as complete.
45
+ */
46
+ export declare const RELAY_METADATA: readonly string[];
47
+ /**
48
+ * Where each kind of data goes, as `p2p doctor` says it for this device. Facts, not checks: the
49
+ * graph targets come from projects.ts (graphTarget's rule, the same as `p2p project show`).
50
+ */
51
+ export interface DataFlow {
52
+ /** Messages, statuses, receipts, rosters and Ix items shared with peers: end-to-end encrypted envelopes. */
53
+ wire: {
54
+ encryption: "end-to-end";
55
+ relaysSee: "ciphertext and metadata"; /** Some of it, not all: `doc` has the full list. */
56
+ metadata: readonly string[];
57
+ doc: string;
58
+ };
59
+ /** Message history (history.ts): never leaves this device; sealed at rest, with its key beside it. */
60
+ history: {
61
+ where: "this device only";
62
+ recording: boolean;
63
+ encryptedAtRest: true;
64
+ keyBesideIt: true;
65
+ eventLogPlaintextDays: number;
66
+ };
67
+ /**
68
+ * Graph memory (graph-memory.ts): on only with Ix, the Ix extension, and an Ix with a local `ix note`.
69
+ * `on` is "unknown" when the doctor couldn't tell (`ix --help` didn't answer in time): `p2p watch`
70
+ * may still be writing, and `detail` says what it wrote and queued so far.
71
+ */
72
+ graphMemory: {
73
+ on: boolean | "unknown";
74
+ detail: string;
75
+ };
76
+ /** Each project's graph target (the project here first), at most MAX_GRAPH_ROWS of them. */
77
+ graphs: {
78
+ id: string;
79
+ name: string;
80
+ here: boolean;
81
+ target: GraphTarget;
82
+ line: string;
83
+ plaintext: string;
84
+ }[];
85
+ /** Projects not listed past MAX_GRAPH_ROWS. */
86
+ graphsNotListed: number;
87
+ /** Whether any listed project's target is a shared (cloud) graph. None today: every target is local. */
88
+ anyShared: boolean;
89
+ doc: string;
33
90
  }
34
91
  export interface DoctorOptions {
35
92
  /** The CLI's own version (cli.ts VERSION). */
@@ -64,6 +121,7 @@ export interface HttpProbe {
64
121
  /** One bounded GET (the relay's document API), with its latency and the server's Date header. */
65
122
  export declare function httpProbe(url: string, timeoutMs: number, opts?: {
66
123
  maxBody?: number;
124
+ noRedirect?: boolean;
67
125
  }): Promise<HttpProbe>;
68
126
  export interface WsProbe {
69
127
  /** Dial + hello (+ auth) took this long. */
@@ -83,6 +141,10 @@ export declare function modVersions(root: string): Promise<{
83
141
  plugin?: string;
84
142
  bundled?: string;
85
143
  }>;
144
+ declare class Checks {
145
+ readonly list: Check[];
146
+ add(id: string, status: CheckStatus, title: string, detail: string, fix?: string): Check;
147
+ }
86
148
  /**
87
149
  * The clock check from each relay's skew (seconds, + when this device is ahead): ✓ under
88
150
  * SKEW_OK_SEC, ? (a warning) up to the protocol's limit (SKEW_FAIL_SEC, 300 s), ✗ only past it.
@@ -91,9 +153,30 @@ export declare function clockVerdict(skews: readonly {
91
153
  relay: string;
92
154
  sec: number;
93
155
  }[]): Check;
156
+ /** "Where your data goes" for this device (no probes: what the code does, and this device's settings). */
157
+ export declare function dataFlowOf(app: Pick<App, "env" | "home">, ix: Pick<DataFlow, "graphMemory" | "graphs" | "graphsNotListed">): DataFlow;
158
+ /**
159
+ * The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
160
+ * whether the project here is mapped, and the graph target of the project here and of each project
161
+ * with a policy ("local only" today). Without Ix nothing is a failure: Peer2Peer works without it.
162
+ * `ix` runs as ext-ix runs it (ix-local.ts): absolute path, allowlisted environment, the local
163
+ * endpoint pinned, read-only commands, bounded.
164
+ */
165
+ export declare function ixChecks(c: Checks, app: App, ms: number): Promise<Pick<DataFlow, "graphMemory" | "graphs" | "graphsNotListed">>;
166
+ /**
167
+ * Graph memory's state for "Where your data goes", from what Ix answered (`support`: undefined when it
168
+ * didn't in time) and what `p2p watch` recorded. Not knowing is "unknown", never "off": the watch
169
+ * asks Ix itself and may be writing.
170
+ */
171
+ export declare function graphMemoryState(support: "oss" | "pro" | "none" | undefined, doc: Pick<GraphMemoryDoc, "written" | "queue"> | undefined, endpoint: string): DataFlow["graphMemory"];
94
172
  export declare function summarize(checks: readonly Check[]): DoctorResult["summary"];
95
173
  /** The doctor's per-step bound: P2P_DOCTOR_TIMEOUT_MS (default 5 s), never more than the connect timeout. */
96
174
  export declare function doctorTimeoutMs(app: App, override?: number): number;
97
175
  export declare function doctor(app: App, o: DoctorOptions): Promise<DoctorResult>;
98
- /** Human output: one line per check (✓ ✗ ?), with its fix indented below. */
176
+ /** The heading of the data-flow section (pretty.ts styles it). */
177
+ export declare const DATA_FLOW_HEADING = "Where your data goes";
178
+ /** "Where your data goes", in plain words: one line per kind of data, then one per project's graph. */
179
+ export declare function formatDataFlow(d: DataFlow): string[];
180
+ /** Human output: one line per check (✓ ✗ ?), with its fix indented below, then where data goes. */
99
181
  export declare function formatDoctor(r: DoctorResult): string;
182
+ export {};
package/dist/doctor.js CHANGED
@@ -21,6 +21,11 @@
21
21
  // bounded (P2P_DOCTOR_TIMEOUT_MS, default 5 s, never more than the connect
22
22
  // timeout), and so is every local step, so the command can't hang. Nothing
23
23
  // secret is ever in the output: no keys, caps, invite or link codes, envelopes.
24
+ //
25
+ // For this device it ends with "Where your data goes" (dataFlow): what travels end-to-end
26
+ // encrypted and what a relay still sees, where message history is kept, and per project the graph
27
+ // target (projects.ts graphTarget's rule, as `p2p project show` prints it) and that Ix keeps what it
28
+ // gets in plaintext.
24
29
  import { readdirSync, statSync } from "node:fs";
25
30
  import { readFile, stat } from "node:fs/promises";
26
31
  import { dirname, join } from "node:path";
@@ -33,6 +38,32 @@ import { defaultRelays } from "./config.js";
33
38
  import { CliError } from "./errors.js";
34
39
  import { readCapped, RelayConnection } from "./relay-client.js";
35
40
  import { rosterAudience, sessionRef } from "./sessions.js";
41
+ import { EVENT_RETENTION_MS } from "./state.js";
42
+ import { enabledNamespaces } from "./extensions.js";
43
+ import { extIxInstalled, ixBinary, ixDeclined, IX_INSTALL_URL, ixInstallLine, ixMemorySupport, ixVersion, runIx } from "./ix-local.js";
44
+ import { personHere } from "./projects.js";
45
+ import { graphMemoryReport } from "./graph-memory.js";
46
+ import { graphMemoryEnabled } from "./config.js";
47
+ import { historySettings } from "./history.js";
48
+ import { graphPlaintextNote, graphTargetLine, listProjects, localGraphEndpoint, projectOf, projectsDoc, projectGraphTarget, sessionWorkdir } from "./projects.js";
49
+ /** The threat model, which lists everything a relay sees. */
50
+ export const THREAT_MODEL_DOC = "docs/security/threat-model.md";
51
+ /** What is encrypted and what isn't, on one page. */
52
+ export const ENCRYPTION_DOC = "docs/security/encryption.md";
53
+ /**
54
+ * Some of what a relay sees besides an envelope's ciphertext (the threat model, "What each party can
55
+ * see", has the full list): never read as complete.
56
+ */
57
+ export const RELAY_METADATA = [
58
+ "who may reach whom (capabilities)",
59
+ "which mailboxes send to which",
60
+ "sizes",
61
+ "timing",
62
+ "each envelope's kind and session id",
63
+ "IP addresses",
64
+ "your public identity document",
65
+ "on a members-only relay that admits a circle's members, that circle's signed chain (its name, owner, admins and members)",
66
+ ];
36
67
  /**
37
68
  * Clock skew. Signed objects (device certificates, documents, caps, invites, statements) are
38
69
  * refused when their `iat` is more than DEFAULT_SKEW_SEC (300 s) ahead of the verifier's clock,
@@ -95,7 +126,7 @@ export async function httpProbe(url, timeoutMs, opts = {}) {
95
126
  t.unref?.();
96
127
  const t0 = Date.now();
97
128
  try {
98
- const res = await fetch(url, { signal: ctl.signal, headers: { accept: "application/json" } });
129
+ const res = await fetch(url, { signal: ctl.signal, headers: { accept: "application/json" }, ...(opts.noRedirect ? { redirect: "error" } : {}) });
99
130
  const t1 = Date.now();
100
131
  const date = res.headers.get("date");
101
132
  const serverMs = date ? Date.parse(date) : NaN;
@@ -495,7 +526,150 @@ async function deviceChecks(c, app, o, ms, reports) {
495
526
  if (dropped > 0) {
496
527
  c.add("inbound", "unknown", "incoming envelopes", `${dropped} couldn't be applied and ${dropped === 1 ? "was" : "were"} dropped after failing for good (or every attempt)`, "if messages from someone seem missing, ask them to send again; P2P_DEBUG=1 on `p2p ls` shows why one fails");
497
528
  }
529
+ const ix = await ixChecks(c, app, ms);
498
530
  await versionCheck(c, app, o, ms);
531
+ return dataFlowOf(app, ix);
532
+ }
533
+ /** "Where your data goes" for this device (no probes: what the code does, and this device's settings). */
534
+ export function dataFlowOf(app, ix) {
535
+ return {
536
+ wire: { encryption: "end-to-end", relaysSee: "ciphertext and metadata", metadata: RELAY_METADATA, doc: THREAT_MODEL_DOC },
537
+ history: { where: "this device only", recording: historySettings(app).enabled, encryptedAtRest: true, keyBesideIt: true, eventLogPlaintextDays: Math.round(EVENT_RETENTION_MS / 86_400_000) },
538
+ ...ix,
539
+ anyShared: ix.graphs.some((g) => g.target.kind === "shared"),
540
+ doc: ENCRYPTION_DOC,
541
+ };
542
+ }
543
+ // ---------------------------------------------------------------------------
544
+ // Ix (epic #41): the local CLI, its backend, this checkout's map, and each project's graph target
545
+ /** At most this many projects' graph targets are listed. */
546
+ const MAX_GRAPH_ROWS = 10;
547
+ /**
548
+ * The Ix section: the binary and its version, the local backend (reachable at the local endpoint),
549
+ * whether the project here is mapped, and the graph target of the project here and of each project
550
+ * with a policy ("local only" today). Without Ix nothing is a failure: Peer2Peer works without it.
551
+ * `ix` runs as ext-ix runs it (ix-local.ts): absolute path, allowlisted environment, the local
552
+ * endpoint pinned, read-only commands, bounded.
553
+ */
554
+ export async function ixChecks(c, app, ms) {
555
+ const local = localGraphEndpoint(app.env, app.file);
556
+ const target = { endpoint: local };
557
+ const bin = ixBinary(app.env);
558
+ const on = enabledNamespaces(app.env, app.file).enabled.includes("ix");
559
+ let memory;
560
+ if (!bin) {
561
+ memory = { on: false, detail: "off: Ix isn't installed" };
562
+ c.add("ix", "unknown", "Ix", `the Ix CLI isn't installed: it is optional (Peer2Peer works without it; peers' Ix items show as plain text)${ixDeclined(app.file) ? ", and you said no to it at setup" : ""}`, personHere(app)
563
+ ? `optional and recommended; Peer2Peer never installs it. To add it, run \`${ixInstallLine()}\` yourself (${IX_INSTALL_URL}), then \`p2p setup --ix\``
564
+ : `optional and recommended; installing it is your user's decision, never yours: ask your user whether they want it; they run \`${ixInstallLine()}\` in their own terminal, then \`p2p setup --ix\``);
565
+ }
566
+ else {
567
+ const v = (await bounded(ixVersion(bin, app.env, target, ms), ms + 500)).value;
568
+ if (v)
569
+ c.add("ix", "ok", "Ix", `ix ${v} (${bin})`);
570
+ else
571
+ c.add("ix", "unknown", "Ix", `${bin} didn't answer \`ix --version\` in time`, "run `ix --version` in a terminal");
572
+ if (on)
573
+ c.add("ix-extension", "ok", "Ix extension", "enabled: sessions can share Ix context");
574
+ else
575
+ c.add("ix-extension", "unknown", "Ix extension", "not enabled", extIxInstalled(app.env) ? "`p2p extensions enable ix`" : "`npm i -g @peer2peer/ext-ix`, then `p2p extensions enable ix`");
576
+ memory = on ? await graphMemoryChecks(c, app, bin, target, ms) : { on: false, detail: "off: the Ix extension isn't enabled" };
577
+ // Never followed elsewhere: a loopback listener that redirects is not the local backend.
578
+ const h = await httpProbe(`${local}/v1/health`, ms, { noRedirect: true });
579
+ if (h.ok && h.status !== undefined && h.status < 500)
580
+ c.add("ix-backend", "ok", "Ix backend", `reachable at ${local} (${h.ms} ms)`);
581
+ else
582
+ c.add("ix-backend", "fail", "Ix backend", `nothing answers at ${local}${h.error ? `: ${h.error}` : h.status ? ` (HTTP ${h.status})` : ""}`, "start it with `ix docker start` (or set `ixEndpoint` in config.json to your local backend)");
583
+ const here = projectOf(sessionWorkdir(app.env));
584
+ if (here.kind === "git" && h.ok) {
585
+ const st = (await bounded(runIx(bin, ["status", "--format", "json", "--root", here.root], { env: app.env, target, cwd: here.root, timeoutMs: ms }), ms + 500)).value;
586
+ let mapped;
587
+ try {
588
+ const j = st && st.code === 0 ? JSON.parse(st.stdout) : undefined;
589
+ mapped = j ? j.graphCompleted === true : undefined;
590
+ }
591
+ catch {
592
+ mapped = undefined;
593
+ }
594
+ if (mapped === true)
595
+ c.add("ix-workspace", "ok", "Ix workspace", `${here.name} is mapped`);
596
+ else if (mapped === false)
597
+ c.add("ix-workspace", "unknown", "Ix workspace", `${here.name} isn't mapped yet`, `run \`ix map\` in ${here.root}`);
598
+ else
599
+ c.add("ix-workspace", "unknown", "Ix workspace", `couldn't tell whether ${here.name} is mapped`, "run `ix status` in it");
600
+ }
601
+ }
602
+ // Graph targets: the project here first, then each project with a policy.
603
+ const doc = (await bounded(projectsDoc(app), ms)).value ?? { v: 1, projects: {} };
604
+ const here = projectOf(sessionWorkdir(app.env));
605
+ const rows = [{ id: here.id, name: here.name, ...(here.repoPrivate ? { repoPrivate: true } : {}) }];
606
+ const all = (await bounded(listProjects(app), ms)).value ?? [];
607
+ for (const p of all)
608
+ if (!rows.some((r) => r.id === p.id))
609
+ rows.push({ id: p.id, name: p.name });
610
+ const graphs = [];
611
+ for (const r of rows.slice(0, MAX_GRAPH_ROWS)) {
612
+ const t = projectGraphTarget(app, r, doc);
613
+ const line = graphTargetLine(t);
614
+ graphs.push({ id: r.id, name: peer(r.name), here: r.id === here.id, target: t, line, plaintext: graphPlaintextNote(t) });
615
+ c.add(`graph:${r.id}`, "ok", `graph of project ${peer(r.name)}${r.id === here.id ? " (here)" : ""}`, line);
616
+ }
617
+ const more = Math.max(0, rows.length - MAX_GRAPH_ROWS);
618
+ if (more > 0)
619
+ c.add("graph:more", "ok", "graphs of other projects", `${more} more not listed (run \`p2p project show\` in each)`);
620
+ return { graphMemory: memory, graphs, graphsNotListed: more };
621
+ }
622
+ /**
623
+ * Graph memory (graph-memory.ts): whether this Ix has the OSS `ix note` (local) or Ix Pro's (cloud,
624
+ * so memory stays off), and what `p2p watch` wrote, queued and dropped. Never a failure: Peer2Peer
625
+ * works without it.
626
+ */
627
+ async function graphMemoryChecks(c, app, bin, target, ms) {
628
+ if (!graphMemoryEnabled(app.env, app.home)) {
629
+ c.add("ix-memory", "ok", "Ix graph memory", 'off ("ixMemory": false in config.json, or P2P_IX_MEMORY=0)');
630
+ return { on: false, detail: 'off ("ixMemory": false in config.json, or P2P_IX_MEMORY=0)' };
631
+ }
632
+ const support = (await bounded(ixMemorySupport(bin, app.env, target, ms), ms + 500)).value;
633
+ const doc = (await bounded(graphMemoryReport(app), ms)).value;
634
+ const counts = doc ? `${doc.written} written, ${doc.queue.length} queued` : "nothing written yet";
635
+ const dropped = doc ? Object.entries(doc.dropped).filter(([, n]) => n > 0) : [];
636
+ if (support === "oss")
637
+ c.add("ix-memory", "ok", "Ix graph memory", `on: sessions' records, statuses and edited files go to the local graph only (${target.endpoint}); ${counts}`);
638
+ else if (support === "pro")
639
+ c.add("ix-memory", "unknown", "Ix graph memory", "off: Ix Pro is installed, and its `ix note` writes to your cloud org; Peer2Peer keeps graph writes local", "use an Ix without Pro for local notes (or leave it off)");
640
+ else if (support === "none")
641
+ c.add("ix-memory", "unknown", "Ix graph memory", "off: this Ix has no local `ix note` (it came after Ix 0.13.0)", "upgrade Ix (`ix upgrade`)");
642
+ else
643
+ c.add("ix-memory", "unknown", "Ix graph memory", `couldn't tell whether this Ix has a local \`ix note\`; ${counts}`, "run `ix --help` in a terminal");
644
+ if (dropped.length > 0) {
645
+ const total = dropped.reduce((a, [, n]) => a + n, 0);
646
+ c.add("ix-memory-dropped", "unknown", "Ix graph memory dropped", `${total} item${total === 1 ? "" : "s"} not written (${dropped.map(([r, n]) => `${peer(r)}: ${n}`).join(", ")})`, "best effort: each reason is counted; the queue holds 64 items");
647
+ }
648
+ if (doc?.unavailable && support === "oss") {
649
+ // Who holds the local endpoint's port wasn't this user (ext-ix listener.ts): say what to do.
650
+ const fix = doc.unavailable.reason === "ix_listener"
651
+ ? `start your Ix backend (\`ix docker start\`); if another user's process holds the port, use a port of yours (\`ixEndpoint\` in config.json). On Linux, Docker's port proxy runs as root: if this machine's Docker is only yours, set "ixTrustRootListener": true in config.json (by hand)`
652
+ : undefined;
653
+ c.add("ix-memory-last", "unknown", "Ix graph memory", `last stopped: ${peer(doc.unavailable.message, 300)}`, fix);
654
+ }
655
+ if (app.file.ixTrustRootListener === true)
656
+ c.add("ix-memory-root", "ok", "Ix graph memory", 'a root-owned listener on the local port counts as yours ("ixTrustRootListener": true in config.json)');
657
+ return graphMemoryState(support, doc, target.endpoint);
658
+ }
659
+ /**
660
+ * Graph memory's state for "Where your data goes", from what Ix answered (`support`: undefined when it
661
+ * didn't in time) and what `p2p watch` recorded. Not knowing is "unknown", never "off": the watch
662
+ * asks Ix itself and may be writing.
663
+ */
664
+ export function graphMemoryState(support, doc, endpoint) {
665
+ if (support === "oss")
666
+ return { on: true, detail: `on: your sessions in shared projects are recorded in the local graph only (${endpoint})` };
667
+ if (support === "pro")
668
+ return { on: false, detail: "off: Ix Pro is installed (its `ix note` writes to the cloud), so nothing is written" };
669
+ if (support === "none")
670
+ return { on: false, detail: "off: this Ix has no local `ix note`" };
671
+ const counts = doc ? `${doc.written} written, ${doc.queue.length} queued` : "nothing written yet";
672
+ return { on: "unknown", detail: `unknown: couldn't tell whether this Ix has a local \`ix note\`; ${counts} (to the local graph only, ${endpoint})` };
499
673
  }
500
674
  // ---------------------------------------------------------------------------
501
675
  // About another user
@@ -739,8 +913,8 @@ export async function doctor(app, o) {
739
913
  }
740
914
  const reports = await probeRelays(app, app.relays, ms, true, app.userId);
741
915
  if (scope === "device") {
742
- await deviceChecks(c, app, o, ms, reports);
743
- return { scope, version: o.version, checks: c.list, summary: summarize(c.list) };
916
+ const dataFlow = await deviceChecks(c, app, o, ms, reports);
917
+ return { scope, version: o.version, checks: c.list, summary: summarize(c.list), dataFlow };
744
918
  }
745
919
  // About a user: who they are first (a userId needn't be known yet).
746
920
  const input = o.user.trim();
@@ -754,8 +928,8 @@ export async function doctor(app, o) {
754
928
  return { scope, version: o.version, user: { input }, checks: c.list, summary: summarize(c.list) };
755
929
  }
756
930
  if (userId === app.userId) {
757
- await deviceChecks(c, app, o, ms, reports);
758
- return { scope: "device", version: o.version, user: { input, userId, address: await app.addressOf(userId) }, checks: c.list, summary: summarize(c.list) };
931
+ const dataFlow = await deviceChecks(c, app, o, ms, reports);
932
+ return { scope: "device", version: o.version, user: { input, userId, address: await app.addressOf(userId) }, checks: c.list, summary: summarize(c.list), dataFlow };
759
933
  }
760
934
  // This device first, in one line (its details are `p2p doctor` with no user).
761
935
  const dev = new Checks();
@@ -803,7 +977,23 @@ async function versionChecks(c, app, userId) {
803
977
  }
804
978
  return { devices, unavailable };
805
979
  }
806
- /** Human output: one line per check (✓ ✗ ?), with its fix indented below. */
980
+ /** The heading of the data-flow section (pretty.ts styles it). */
981
+ export const DATA_FLOW_HEADING = "Where your data goes";
982
+ /** "Where your data goes", in plain words: one line per kind of data, then one per project's graph. */
983
+ export function formatDataFlow(d) {
984
+ const lines = [`${DATA_FLOW_HEADING} (${d.doc})`];
985
+ lines.push(` messages, statuses, receipts: end-to-end encrypted; relays can't read their content, but see metadata, including ${d.wire.metadata.join(", ")} (all of it: ${d.wire.doc})`);
986
+ lines.push(` message history: ${d.history.recording ? "on this device only" : "not recording (history.enabled is false, or P2P_HISTORY=0); what was kept stays on this device only"}, encrypted at rest, but its key sits beside it in P2P_HOME; the event log keeps up to ${d.history.eventLogPlaintextDays} days of recent messages in the clear`);
987
+ lines.push(` graph memory: ${d.graphMemory.detail}`);
988
+ for (const g of d.graphs)
989
+ lines.push(` graph of project ${g.name}${g.here ? " (here)" : ""}: ${g.line} (${g.plaintext})`);
990
+ if (d.graphsNotListed > 0)
991
+ lines.push(` ${d.graphsNotListed} more project${d.graphsNotListed === 1 ? "" : "s"} not listed: run \`p2p project show\` in each`);
992
+ if (!d.anyShared)
993
+ lines.push(` cloud graph: none; no ${d.graphsNotListed > 0 ? "listed " : ""}project writes to one (a shared team graph is planned: opt-in per circle, and its operator can read what it holds)`);
994
+ return lines;
995
+ }
996
+ /** Human output: one line per check (✓ ✗ ?), with its fix indented below, then where data goes. */
807
997
  export function formatDoctor(r) {
808
998
  const head = r.scope === "user" && r.user ? `p2p doctor: can you see ${r.user.address ?? r.user.input}?` : "p2p doctor: this device";
809
999
  const lines = [head, ""];
@@ -812,6 +1002,8 @@ export function formatDoctor(r) {
812
1002
  if (x.fix)
813
1003
  lines.push(` ${x.status === "unknown" ? "to tell" : "fix"}: ${x.fix}`);
814
1004
  }
1005
+ if (r.dataFlow)
1006
+ lines.push("", ...formatDataFlow(r.dataFlow));
815
1007
  lines.push("", `${r.summary.ok} ✓ ${r.summary.fail} ✗ ${r.summary.unknown} ?`);
816
1008
  return lines.join("\n");
817
1009
  }
@@ -3,6 +3,12 @@ import type { App, Io } from "./app.js";
3
3
  import { type ExtContext, type ExtensionRegistry, type P2PExtension } from "./extensions.js";
4
4
  export declare const IX_INSTALL_HINT = "https://github.com/ix-infrastructure/Ix";
5
5
  export declare function extContext(app: App, ext: P2PExtension, io: Io, json: boolean, confirm: (q: string, yes?: boolean) => Promise<boolean>): ExtContext;
6
+ /**
7
+ * ExtContext.mayShareSessionContext: context recorded for `ofSid` may go out from `fromSid` only when
8
+ * they're the same session, or both ceilings are shared, everyone `fromSid` reaches is also reached
9
+ * by `ofSid`, and their graph targets are the same. Fails closed: anything private, unbound or unknown is no.
10
+ */
11
+ export declare function mayShareSessionContext(app: App, ofSid: string, fromSid: string): Promise<boolean>;
6
12
  /** ExtContext.kv: <home>/ext/<ns>.json, written atomically, 0600. */
7
13
  export declare const MAX_EXT_STORE_BYTES: number;
8
14
  /**
package/dist/ext-host.js CHANGED
@@ -12,7 +12,8 @@ import { join } from "node:path";
12
12
  import { displayStatus, sanitizePeerText } from "@peer2peer/core/v3";
13
13
  import { CliError } from "./errors.js";
14
14
  import { enabledNamespaces, extensionPackageName, kindNamespace, KNOWN_EXTENSIONS, setExtensionEnabled, } from "./extensions.js";
15
- import { sessionWorkdir } from "./projects.js";
15
+ import { ixAdvice } from "./ix-local.js";
16
+ import { ceilingAudience, graphPinnedEnv, graphTarget, localGraphEndpoint, PERSON_SESSION, sessionCeiling, sessionDirs, sessionWorkdir } from "./projects.js";
16
17
  import { listPeers, sendExtension, sessionAudience, sessionRef } from "./sessions.js";
17
18
  import { sessKey } from "./state.js";
18
19
  import { declaredState, expiresAt, keptCopy, liveStates, publishExtensionState } from "./xstate.js";
@@ -46,9 +47,18 @@ function toExtEvent(e) {
46
47
  };
47
48
  }
48
49
  export function extContext(app, ext, io, json, confirm) {
50
+ // Pinned to the local graph: no IX_* cloud setting of the caller's reaches an extension's `ix` (projects.ts).
51
+ const pinned = graphPinnedEnv(app.env, { kind: "local", endpoint: localGraphEndpoint(app.env, app.file), why: "" });
49
52
  return {
50
- env: app.env,
53
+ env: pinned,
51
54
  cwd: extWorkdir(app.env),
55
+ graphTarget: async (o = {}) => {
56
+ const { dirs, over } = sessionDirs(app.env);
57
+ const paths = Array.isArray(o.paths) ? [...o.paths] : [];
58
+ const t = await graphTarget(app, { ...(typeof o.sid === "string" && o.sid !== "" ? { sid: o.sid } : {}), dirs, paths, over });
59
+ // From config.json only (the person's file), never the environment.
60
+ return t.kind === "local" && app.file.ixTrustRootListener === true ? { ...t, trustRootListener: true } : t;
61
+ },
52
62
  io: { err: (s) => io.err(s), ...(io.readStdin ? { readStdin: io.readStdin } : {}) },
53
63
  json,
54
64
  interactive: !json && io.prompt !== undefined,
@@ -116,6 +126,7 @@ export function extContext(app, ext, io, json, confirm) {
116
126
  });
117
127
  },
118
128
  audience: (sid) => sessionAudience(app, sid),
129
+ mayShareSessionContext: (ofSid, fromSid) => mayShareSessionContext(app, ofSid, fromSid),
119
130
  localMac: (data) => localMac(app, ext.ns, data),
120
131
  ownStatus: async (sid) => {
121
132
  const rec = (await app.state.get("peers"))?.[sessKey(app.userId, sid)];
@@ -127,6 +138,30 @@ export function extContext(app, ext, io, json, confirm) {
127
138
  },
128
139
  };
129
140
  }
141
+ /**
142
+ * ExtContext.mayShareSessionContext: context recorded for `ofSid` may go out from `fromSid` only when
143
+ * they're the same session, or both ceilings are shared, everyone `fromSid` reaches is also reached
144
+ * by `ofSid`, and their graph targets are the same. Fails closed: anything private, unbound or unknown is no.
145
+ */
146
+ export async function mayShareSessionContext(app, ofSid, fromSid) {
147
+ if (typeof ofSid !== "string" || typeof fromSid !== "string" || ofSid === "" || fromSid === "")
148
+ return false;
149
+ if (ofSid === fromSid)
150
+ return true;
151
+ if (ofSid === PERSON_SESSION || fromSid === PERSON_SESSION)
152
+ return false;
153
+ const [of, from] = await Promise.all([sessionCeiling(app, ofSid), sessionCeiling(app, fromSid)]);
154
+ if (of.kind !== "shared" || from.kind !== "shared")
155
+ return false;
156
+ const [ofAud, fromAud] = await Promise.all([ceilingAudience(app, of), ceilingAudience(app, from)]);
157
+ if (!ofAud || !fromAud)
158
+ return false;
159
+ for (const u of fromAud)
160
+ if (!ofAud.has(u))
161
+ return false;
162
+ const [a, b] = await Promise.all([graphTarget(app, { sid: ofSid }), graphTarget(app, { sid: fromSid })]);
163
+ return a.kind === b.kind && a.endpoint === b.endpoint && (a.kind !== "shared" || (b.kind === "shared" && a.circle === b.circle));
164
+ }
130
165
  /** ExtContext.kv: <home>/ext/<ns>.json, written atomically, 0600. */
131
166
  export const MAX_EXT_STORE_BYTES = 64 * 1024;
132
167
  function extStore(home, ns) {
@@ -232,12 +267,15 @@ export function registerExtensionCommands(program, reg, deps) {
232
267
  const loaded = reg.list().map((l) => ({ ns: l.ext.ns, name: l.ext.name, version: l.ext.version, from: l.from, commands: (l.ext.commands ?? []).map((c) => c.name) }));
233
268
  const { enabled, ignored } = enabledNamespaces(app.env, app.file);
234
269
  const missing = KNOWN_EXTENSIONS.filter((ns) => !reg.get(ns)).map(extensionPackageName);
270
+ // Ix is optional and recommended (never installed for the person): front ends read this to
271
+ // tell their agent it may suggest Ix once, and never install it itself.
272
+ const ix = ixAdvice(app.env, app.file);
235
273
  const human = [
236
274
  ...(loaded.length ? loaded.map((l) => `${l.name} ${l.version} (x:${l.ns}.*): ${l.from}`) : ["no extensions loaded"]),
237
275
  `enabled: ${enabled.length ? enabled.join(", ") : "none"}${app.env.P2P_EXTENSIONS !== undefined ? " (from P2P_EXTENSIONS)" : ""}`,
238
276
  ...(ignored.length ? [`ignored (not registered): ${ignored.join(", ")}`] : []),
239
277
  ].join("\n");
240
- return { json: { extensions: loaded, enabled, missing, ...(ignored.length ? { ignored } : {}) }, human };
278
+ return { json: { extensions: loaded, enabled, missing, ...(ignored.length ? { ignored } : {}), ix }, human };
241
279
  }, { requireIdentity: false }));
242
280
  for (const on of [true, false]) {
243
281
  group