@peer2peer/cli 0.1.1 → 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/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,11 +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";
36
42
  import { enabledNamespaces } from "./extensions.js";
37
- import { extIxInstalled, ixBinary, IX_INSTALL_URL, ixMemorySupport, ixVersion, runIx } from "./ix-local.js";
43
+ import { extIxInstalled, ixBinary, ixDeclined, IX_INSTALL_URL, ixInstallLine, ixMemorySupport, ixVersion, runIx } from "./ix-local.js";
44
+ import { personHere } from "./projects.js";
38
45
  import { graphMemoryReport } from "./graph-memory.js";
39
46
  import { graphMemoryEnabled } from "./config.js";
40
- import { describeGraphTarget, listProjects, localGraphEndpoint, projectOf, projectsDoc, projectGraphTarget, sessionWorkdir } from "./projects.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
+ ];
41
67
  /**
42
68
  * Clock skew. Signed objects (device certificates, documents, caps, invites, statements) are
43
69
  * refused when their `iat` is more than DEFAULT_SKEW_SEC (300 s) ahead of the verifier's clock,
@@ -500,8 +526,19 @@ async function deviceChecks(c, app, o, ms, reports) {
500
526
  if (dropped > 0) {
501
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");
502
528
  }
503
- await ixChecks(c, app, ms);
529
+ const ix = await ixChecks(c, app, ms);
504
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
+ };
505
542
  }
506
543
  // ---------------------------------------------------------------------------
507
544
  // Ix (epic #41): the local CLI, its backend, this checkout's map, and each project's graph target
@@ -519,8 +556,12 @@ export async function ixChecks(c, app, ms) {
519
556
  const target = { endpoint: local };
520
557
  const bin = ixBinary(app.env);
521
558
  const on = enabledNamespaces(app.env, app.file).enabled.includes("ix");
559
+ let memory;
522
560
  if (!bin) {
523
- c.add("ix", "unknown", "Ix", "the Ix CLI isn't installed (Peer2Peer works without it; peers' Ix items show as plain text)", `install Ix (${IX_INSTALL_URL}), then \`p2p extensions enable ix\``);
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\``);
524
565
  }
525
566
  else {
526
567
  const v = (await bounded(ixVersion(bin, app.env, target, ms), ms + 500)).value;
@@ -532,8 +573,7 @@ export async function ixChecks(c, app, ms) {
532
573
  c.add("ix-extension", "ok", "Ix extension", "enabled: sessions can share Ix context");
533
574
  else
534
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`");
535
- if (on)
536
- await graphMemoryChecks(c, app, bin, target, ms);
576
+ memory = on ? await graphMemoryChecks(c, app, bin, target, ms) : { on: false, detail: "off: the Ix extension isn't enabled" };
537
577
  // Never followed elsewhere: a loopback listener that redirects is not the local backend.
538
578
  const h = await httpProbe(`${local}/v1/health`, ms, { noRedirect: true });
539
579
  if (h.ok && h.status !== undefined && h.status < 500)
@@ -567,12 +607,17 @@ export async function ixChecks(c, app, ms) {
567
607
  for (const p of all)
568
608
  if (!rows.some((r) => r.id === p.id))
569
609
  rows.push({ id: p.id, name: p.name });
610
+ const graphs = [];
570
611
  for (const r of rows.slice(0, MAX_GRAPH_ROWS)) {
571
612
  const t = projectGraphTarget(app, r, doc);
572
- c.add(`graph:${r.id}`, "ok", `graph of project ${peer(r.name)}${r.id === here.id ? " (here)" : ""}`, `${describeGraphTarget(t)}${t.kind === "local" ? `: ${t.why}` : ""}`);
573
- }
574
- if (rows.length > MAX_GRAPH_ROWS)
575
- c.add("graph:more", "ok", "graphs of other projects", `${rows.length - MAX_GRAPH_ROWS} more not listed (run \`p2p project show\` in each)`);
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 };
576
621
  }
577
622
  /**
578
623
  * Graph memory (graph-memory.ts): whether this Ix has the OSS `ix note` (local) or Ix Pro's (cloud,
@@ -582,7 +627,7 @@ export async function ixChecks(c, app, ms) {
582
627
  async function graphMemoryChecks(c, app, bin, target, ms) {
583
628
  if (!graphMemoryEnabled(app.env, app.home)) {
584
629
  c.add("ix-memory", "ok", "Ix graph memory", 'off ("ixMemory": false in config.json, or P2P_IX_MEMORY=0)');
585
- return;
630
+ return { on: false, detail: 'off ("ixMemory": false in config.json, or P2P_IX_MEMORY=0)' };
586
631
  }
587
632
  const support = (await bounded(ixMemorySupport(bin, app.env, target, ms), ms + 500)).value;
588
633
  const doc = (await bounded(graphMemoryReport(app), ms)).value;
@@ -609,6 +654,22 @@ async function graphMemoryChecks(c, app, bin, target, ms) {
609
654
  }
610
655
  if (app.file.ixTrustRootListener === true)
611
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})` };
612
673
  }
613
674
  // ---------------------------------------------------------------------------
614
675
  // About another user
@@ -852,8 +913,8 @@ export async function doctor(app, o) {
852
913
  }
853
914
  const reports = await probeRelays(app, app.relays, ms, true, app.userId);
854
915
  if (scope === "device") {
855
- await deviceChecks(c, app, o, ms, reports);
856
- 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 };
857
918
  }
858
919
  // About a user: who they are first (a userId needn't be known yet).
859
920
  const input = o.user.trim();
@@ -867,8 +928,8 @@ export async function doctor(app, o) {
867
928
  return { scope, version: o.version, user: { input }, checks: c.list, summary: summarize(c.list) };
868
929
  }
869
930
  if (userId === app.userId) {
870
- await deviceChecks(c, app, o, ms, reports);
871
- 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 };
872
933
  }
873
934
  // This device first, in one line (its details are `p2p doctor` with no user).
874
935
  const dev = new Checks();
@@ -916,7 +977,23 @@ async function versionChecks(c, app, userId) {
916
977
  }
917
978
  return { devices, unavailable };
918
979
  }
919
- /** 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. */
920
997
  export function formatDoctor(r) {
921
998
  const head = r.scope === "user" && r.user ? `p2p doctor: can you see ${r.user.address ?? r.user.input}?` : "p2p doctor: this device";
922
999
  const lines = [head, ""];
@@ -925,6 +1002,8 @@ export function formatDoctor(r) {
925
1002
  if (x.fix)
926
1003
  lines.push(` ${x.status === "unknown" ? "to tell" : "fix"}: ${x.fix}`);
927
1004
  }
1005
+ if (r.dataFlow)
1006
+ lines.push("", ...formatDataFlow(r.dataFlow));
928
1007
  lines.push("", `${r.summary.ok} ✓ ${r.summary.fail} ✗ ${r.summary.unknown} ?`);
929
1008
  return lines.join("\n");
930
1009
  }
package/dist/ext-host.js CHANGED
@@ -12,6 +12,7 @@ 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 { ixAdvice } from "./ix-local.js";
15
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";
@@ -266,12 +267,15 @@ export function registerExtensionCommands(program, reg, deps) {
266
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) }));
267
268
  const { enabled, ignored } = enabledNamespaces(app.env, app.file);
268
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);
269
273
  const human = [
270
274
  ...(loaded.length ? loaded.map((l) => `${l.name} ${l.version} (x:${l.ns}.*): ${l.from}`) : ["no extensions loaded"]),
271
275
  `enabled: ${enabled.length ? enabled.join(", ") : "none"}${app.env.P2P_EXTENSIONS !== undefined ? " (from P2P_EXTENSIONS)" : ""}`,
272
276
  ...(ignored.length ? [`ignored (not registered): ${ignored.join(", ")}`] : []),
273
277
  ].join("\n");
274
- return { json: { extensions: loaded, enabled, missing, ...(ignored.length ? { ignored } : {}) }, human };
278
+ return { json: { extensions: loaded, enabled, missing, ...(ignored.length ? { ignored } : {}), ix }, human };
275
279
  }, { requireIdentity: false }));
276
280
  for (const on of [true, false]) {
277
281
  group
@@ -12,7 +12,7 @@
12
12
  // can reach (the home directory, the identity and device keys). ExtContext
13
13
  // is the API it is meant to use, not a sandbox. So loading is opt-in:
14
14
  // - Which: only namespaces registered in protocol §8.3 (KNOWN_EXTENSIONS)
15
- // that the user enabled: P2P_EXTENSIONS ("ix,kartr"; "none" = none), else
15
+ // that the user enabled: P2P_EXTENSIONS ("ix"; "none" = none), else
16
16
  // `extensions` in <home>/config.json (`p2p extensions enable ix`). Nothing
17
17
  // enabled, nothing loaded.
18
18
  // - Where: only explicit node_modules directories: each P2P_EXTENSION_PATH
@@ -44,7 +44,7 @@ import { extensionKindCap, isExtensionKind, isExtStateTtl, sanitizePeerText } fr
44
44
  /** The seam's version; an extension declares the one it was built against. */
45
45
  export const EXTENSION_API = 1;
46
46
  /** Namespaces registered in docs/protocol.md §8.3: the only ones that can be enabled. */
47
- export const KNOWN_EXTENSIONS = ["ix", "kartr"];
47
+ export const KNOWN_EXTENSIONS = ["ix"];
48
48
  /** Cap on the JSON a `receive` digest may add to an event. */
49
49
  export const MAX_RENDERED_BYTES = 16 * 1024;
50
50
  /** Cap on the validated body kept with an event (for user-initiated actions later). */
@@ -13,6 +13,13 @@ export interface InitResult {
13
13
  code: string;
14
14
  }[];
15
15
  }
16
+ /** The `p2p` command as the person types it here (Windows PowerShell blocks npm's p2p.ps1 shim; p2p.cmd works everywhere on Windows). */
17
+ export declare function p2pCommand(platform?: NodeJS.Platform): string;
18
+ /**
19
+ * Why a new identity can't be made here (no relay anywhere), naming the three ways in. There is
20
+ * no default relay, by design (bring your own relay).
21
+ */
22
+ export declare function noRelaysReason(home: string, platform?: NodeJS.Platform): string;
16
23
  export declare function init(app: App, opts: {
17
24
  name?: string;
18
25
  relays?: string[];
@@ -35,15 +42,21 @@ export interface SetupResult {
35
42
  file?: string;
36
43
  phrase?: string;
37
44
  };
38
- /** Ix on by default (ix-local.ts setupIx): found, enabled, and what to do when it isn't. */
45
+ /** Ix, optional and recommended (ix-local.ts setupIx): found, enabled, recommended (with the command for the person to run), and what to do when it isn't on. Never installed for them. */
39
46
  ix?: SetupIx;
47
+ /** This device is the only key holder and the backup phrase was never shown or saved (`p2p backup show`). */
48
+ backupNeeded?: true;
40
49
  }
41
50
  export declare const BACKUP_FILE_NAME = "backup-phrase.txt";
51
+ export type BackupMode = "file" | "print" | "none";
42
52
  export declare function setup(app: App, opts: {
43
53
  name?: string;
44
54
  relays?: string[];
45
- backup?: "file" | "print" | "none";
55
+ backup?: BackupMode;
46
56
  backupFile?: string;
57
+ ix?: boolean;
58
+ /** Asked only once an identity was created here (never before its key exists), when `backup` isn't given. */
59
+ chooseBackup?: (created: InitResult) => Promise<BackupMode>;
47
60
  }): Promise<SetupResult>;
48
61
  export declare function relaysList(app: App): Promise<{
49
62
  relays: string[];
@@ -143,10 +156,22 @@ export declare function linkStart(app: App, opts?: {
143
156
  keyholder?: boolean;
144
157
  relay?: string;
145
158
  }): Promise<LinkStart>;
159
+ /** The identity a link code would make this device part of, shown before anything is kept (LinkJoin.wait). */
160
+ export interface LinkIdentity {
161
+ userId: string;
162
+ address: string;
163
+ fingerprint: string;
164
+ /** This device would get the identity key. */
165
+ keyholder: boolean;
166
+ }
146
167
  export interface LinkJoin {
147
168
  compareCode: string;
148
169
  did: string;
149
- wait(): Promise<{
170
+ /**
171
+ * Waits for the other device, then, with `confirm`, shows which identity this device would
172
+ * become and keeps nothing unless it says yes (a code from someone else makes this device theirs).
173
+ */
174
+ wait(confirm?: (who: LinkIdentity) => Promise<boolean>): Promise<{
150
175
  userId: string;
151
176
  address: string;
152
177
  did: string;
@@ -156,6 +181,7 @@ export interface LinkJoin {
156
181
  export declare function linkJoin(app: App, code: string, opts?: {
157
182
  label?: string;
158
183
  maxWaitMs?: number;
184
+ allowPrivateRelay?: boolean;
159
185
  }): Promise<LinkJoin>;
160
186
  export declare function backupShow(app: App): Promise<{
161
187
  phrase: string;
package/dist/identity.js CHANGED
@@ -9,18 +9,33 @@ import { addIdentityVersion, b64uEncode, backupPhraseFromSeed, canonicalProofLoc
9
9
  import { capPeek, certDid, defaultLabel, defaultName, joinCapOf, newKeysDoc } from "./app.js";
10
10
  import { defaultRelays, normalizeRelays } from "./config.js";
11
11
  import { CliError } from "./errors.js";
12
+ import { isOwnRelay, isPrivateRelayHost, PRIVATE_RESOLVE_MARK, privateGuardLookup, privateRelayMessage } from "./shortcode.js";
12
13
  import { fetchTips, linkGet, linkPut, openLinkConnection, relayCode, sleep } from "./relay-client.js";
13
14
  import { exportAll, sendSync, verifiedIssuedCap } from "./sync.js";
14
15
  import { receiving } from "./inbound.js";
15
16
  import { recordJoin, resignJoin } from "./circle-ops.js";
16
17
  import { setupIx } from "./ix-local.js";
18
+ import { renewPersonToken } from "./projects.js";
19
+ /** The `p2p` command as the person types it here (Windows PowerShell blocks npm's p2p.ps1 shim; p2p.cmd works everywhere on Windows). */
20
+ export function p2pCommand(platform = process.platform) {
21
+ return platform === "win32" ? "p2p.cmd" : "p2p";
22
+ }
23
+ /**
24
+ * Why a new identity can't be made here (no relay anywhere), naming the three ways in. There is
25
+ * no default relay, by design (bring your own relay).
26
+ */
27
+ export function noRelaysReason(home, platform = process.platform) {
28
+ const p = p2pCommand(platform);
29
+ return (`no relays configured. Already use Peer2Peer on another device? Run \`p2p link start\` there, then \`${p} link join <code>\` here (one identity, not a second one). ` +
30
+ `Have an invite? \`${p} join <invite link or code>\`. ` +
31
+ `Starting a new identity? Pass --relay wss://… (1–5, your group's relay), or set P2P_DEFAULT_RELAYS, or "defaultRelays" in ${home}/config.json`);
32
+ }
17
33
  export async function init(app, opts) {
18
34
  if (await app.load(false))
19
35
  throw new CliError("already_initialized", `${app.home} already holds an identity (${app.userId})`);
20
36
  const relays = opts.relays && opts.relays.length > 0 ? normalizeRelays(opts.relays) : defaultRelays(app.env, app.file);
21
- if (relays.length === 0) {
22
- throw new CliError("no_relays", `no relays configured: pass --relay wss://… (1–5), or set P2P_DEFAULT_RELAYS, or "defaultRelays" in ${app.home}/config.json`);
23
- }
37
+ if (relays.length === 0)
38
+ throw new CliError("no_relays", noRelaysReason(app.home));
24
39
  const name = opts.name ?? defaultName();
25
40
  if (!isValidName(name))
26
41
  throw new CliError("usage", "--name must match [a-z0-9._-]{1,32}");
@@ -30,6 +45,9 @@ export async function init(app, opts) {
30
45
  const doc = createIdentityDoc(ik, { ver: 1, prev: null, name, relays, devices: [device.did], keyholders: [device.did], by: device.did, certs: [cert] });
31
46
  const keys = newKeysDoc(ik.userId, device, cert, ik);
32
47
  const self = { name, relays, createdAt: Date.now() };
48
+ // A person.key from before this identity existed no longer counts (projects.ts renewPersonToken).
49
+ // Replaced before any key is written: if that fails, no identity is made here.
50
+ renewPersonToken(app.home);
33
51
  await app.state.put("keys", keys);
34
52
  await app.state.put("self", self);
35
53
  app.setKeys(keys, self);
@@ -49,10 +67,13 @@ export const BACKUP_FILE_NAME = "backup-phrase.txt";
49
67
  export async function setup(app, opts) {
50
68
  let created = false;
51
69
  let pub;
70
+ let backupMode = opts.backup;
52
71
  if (!(await app.load(false))) {
53
72
  const r = await init(app, { name: opts.name, relays: opts.relays });
54
73
  created = true;
55
74
  pub = { published: r.published, failed: r.failed };
75
+ if (backupMode === undefined && opts.chooseBackup)
76
+ backupMode = await opts.chooseBackup(r);
56
77
  }
57
78
  const v = await app.ownView();
58
79
  const out = {
@@ -65,13 +86,13 @@ export async function setup(app, opts) {
65
86
  ...(pub ?? {}),
66
87
  };
67
88
  try {
68
- out.ix = await setupIx(app, created);
89
+ out.ix = await setupIx(app, created, { reoffer: opts.ix === true });
69
90
  }
70
91
  catch (e) {
71
92
  // Never fails a setup: Ix is optional.
72
- out.ix = { found: false, enabled: false, hint: `couldn't check for Ix: ${sanitizePeerText(e.message, 200)}` };
93
+ out.ix = { found: false, installed: false, recommended: false, enabled: false, hint: `couldn't check for Ix: ${sanitizePeerText(e.message, 200)}` };
73
94
  }
74
- if (opts.backup === "file") {
95
+ if (backupMode === "file") {
75
96
  const path = opts.backupFile ?? join(app.home, BACKUP_FILE_NAME);
76
97
  const { phrase } = await backupShow(app);
77
98
  try {
@@ -86,9 +107,12 @@ export async function setup(app, opts) {
86
107
  await chmod(path, 0o600);
87
108
  out.backup = { file: path };
88
109
  }
89
- else if (opts.backup === "print") {
110
+ else if (backupMode === "print") {
90
111
  out.backup = { phrase: (await backupShow(app)).phrase };
91
112
  }
113
+ // This device is the only key holder and its phrase was never shown: losing it loses the identity.
114
+ if (!out.backup && app.isKeyholder && v.head.keyholders.length < 2 && !app.self?.backupShown)
115
+ out.backupNeeded = true;
92
116
  return out;
93
117
  }
94
118
  // ---------------------------------------------------------------------------
@@ -96,12 +120,14 @@ export async function setup(app, opts) {
96
120
  export async function relaysList(app) {
97
121
  return { relays: [...(await app.ownView()).head.relays] };
98
122
  }
99
- async function changeRelays(app, f) {
123
+ async function changeRelays(app, f, removing = []) {
100
124
  app.requireKeyholder("Changing your relays");
101
125
  await app.connectAndDrain();
102
126
  const pub = await app.publishNext((p) => {
103
127
  p.relays = f(p.relays);
104
- });
128
+ },
129
+ // #67: removing a relay must work even while it serves versions that don't connect (App.ownStrictFallback).
130
+ { removing });
105
131
  const re = await reissueForRelays(app);
106
132
  return { relays: [...(await app.ownView()).head.relays], ver: pub.ver, published: pub.ok, failed: pub.failed, ...re };
107
133
  }
@@ -179,7 +205,7 @@ export async function relaysRemove(app, url) {
179
205
  throw new CliError("usage", "that is your only relay: add another first");
180
206
  // Caps naming the dropped relay, captured before the re-issue adds new ones.
181
207
  const old = (await app.store.listCapsIssued()).filter((c) => c.iss === app.userId && c.relays.includes(r));
182
- const out = await changeRelays(app, (list) => list.filter((x) => x !== r));
208
+ const out = await changeRelays(app, (list) => list.filter((x) => x !== r), [r]);
183
209
  // review L2: revoke them at the dropped relay only (our devices are still in its allowlist). Other
184
210
  // relays keep honouring them, so friends who haven't picked up the new caps stay covered.
185
211
  // Best effort: the relay may be down.
@@ -397,12 +423,37 @@ export async function linkJoin(app, code, opts = {}) {
397
423
  throw new CliError("usage", "that is not a link code (p2p-link:…@relay)");
398
424
  }
399
425
  const { secret, relay } = parsed;
426
+ // A link code someone else gave connects to its relay before anyone confirms anything: the same
427
+ // private-address rule as an invite code's relay, unless it is one of the person's own relays
428
+ // (P2P_DEFAULT_RELAYS or config.json: no identity here yet) or they opted in.
429
+ const allowPrivate = opts.allowPrivateRelay || app.env.P2P_ALLOW_PRIVATE_RELAY === "1";
430
+ let own = [];
431
+ try {
432
+ own = defaultRelays(app.env, app.file);
433
+ }
434
+ catch {
435
+ // a broken config: no own relays
436
+ }
437
+ const guard = !allowPrivate && !isOwnRelay(relay, own);
438
+ if (guard && isPrivateRelayHost(new URL(relay).hostname)) {
439
+ throw new CliError("private_relay", privateRelayMessage("link code's relay", new URL(relay).hostname));
440
+ }
400
441
  const device = generateDeviceKeysV3("p2p:pending");
401
442
  const x = generateDeviceKeysV3("p2p:pending");
402
443
  const label = (opts.label ?? defaultLabel()).slice(0, 64);
403
444
  const req = createLinkRequest(secret, device, x.agreementPublicKey, label);
404
445
  const lid = linkId(secret);
405
- const conn = await openLinkConnection(relay, app.transport, app.tun.connectTimeoutMs, app.progress);
446
+ let conn;
447
+ try {
448
+ conn = await openLinkConnection(relay, app.transport, app.tun.connectTimeoutMs, app.progress, guard ? { lookup: privateGuardLookup() } : {});
449
+ }
450
+ catch (e) {
451
+ if (e.message?.includes(PRIVATE_RESOLVE_MARK)) {
452
+ const at = /\(([^()]+)\)\s*$/.exec(e.message)?.[1];
453
+ throw new CliError("private_relay", privateRelayMessage("link code's relay", new URL(relay).hostname, at ? { detail: `it resolves to ${at}` } : {}));
454
+ }
455
+ throw e;
456
+ }
406
457
  try {
407
458
  await linkPut(conn, lid, "req", JSON.stringify(req));
408
459
  }
@@ -413,7 +464,7 @@ export async function linkJoin(app, code, opts = {}) {
413
464
  return {
414
465
  compareCode: linkCompareCode(secret, device.did),
415
466
  did: device.did,
416
- wait: async () => {
467
+ wait: async (confirm) => {
417
468
  const deadline = Date.now() + Math.min(LINK_TTL_SEC * 1000, opts.maxWaitMs ?? Infinity);
418
469
  let frame;
419
470
  try {
@@ -435,8 +486,17 @@ export async function linkJoin(app, code, opts = {}) {
435
486
  }
436
487
  const opened = openLinkResponse(secret, device, x.agreementSecretKey, JSON.parse(frame));
437
488
  const userId = opened.doc.iss;
489
+ // Nothing is kept before the person says this is their identity: a code from someone else
490
+ // would make this device theirs.
491
+ if (confirm) {
492
+ const who = { userId, address: displayAddress(userId, opened.doc.name), fingerprint: displayFingerprint(userId), keyholder: !!opened.ik };
493
+ if (!(await confirm(who))) {
494
+ throw new CliError("link_declined", `not linked: nothing was kept on this device. The other device's identity (${who.address}) now lists a device that will never be used: if it is yours after all, remove it there with \`p2p devices revoke ${device.did}\``);
495
+ }
496
+ }
438
497
  const keys = newKeysDoc(userId, { ...device, userId }, opened.cert.jws, opened.ik);
439
498
  const self = { name: opened.doc.name, relays: opened.doc.relays, createdAt: Date.now() };
499
+ renewPersonToken(app.home);
440
500
  await app.state.put("keys", keys);
441
501
  await app.state.put("self", self);
442
502
  app.setKeys(keys, self);
@@ -531,6 +591,7 @@ async function restoreInto(app, phrase, opts) {
531
591
  if (found === 0) {
532
592
  const name = opts.name ?? defaultName();
533
593
  const doc = createIdentityDoc(ik, { ver: 1, prev: null, name, relays, devices: [device.did], keyholders: [device.did], by: device.did, certs: [cert] });
594
+ renewPersonToken(app.home);
534
595
  await app.state.put("keys", keys);
535
596
  await app.state.put("self", { ...self, name });
536
597
  app.setKeys(keys, { ...self, name });
@@ -553,6 +614,7 @@ async function restoreInto(app, phrase, opts) {
553
614
  const existing = await app.refreshIdentity(ik.userId, relays, { force: true, strict: true });
554
615
  if (!existing)
555
616
  throw new CliError("refresh_failed", "couldn't fit the relays' identity document");
617
+ renewPersonToken(app.home);
556
618
  await app.state.put("keys", keys);
557
619
  await app.store.putDeviceCert({ userId: ik.userId, did: device.did, exp: verifyDeviceCertV3(cert).exp, jws: cert });
558
620
  await app.state.put("self", { ...self, name: existing.head.name, relays: existing.head.relays });
@@ -1,8 +1,42 @@
1
1
  import type { App } from "./app.js";
2
- import type { Env } from "./config.js";
2
+ import { type Env, type FileConfig } from "./config.js";
3
3
  import { type GraphTarget } from "./projects.js";
4
4
  /** Where to get Ix (and how p2p says it): never installed for the person. */
5
5
  export declare const IX_INSTALL_URL = "https://github.com/ix-infrastructure/Ix";
6
+ /**
7
+ * The command(s) that install Ix on this platform, from the Ix README, for the person to run in their
8
+ * own terminal: Peer2Peer prints them and never runs them (it doesn't run a downloaded script). Intel
9
+ * Macs have no pre-built Ix package, so Homebrew builds it.
10
+ */
11
+ export declare function ixInstallCommands(platform?: NodeJS.Platform, arch?: string): string[];
12
+ /** The install command(s) as one line (`&&` between steps; Windows has one). */
13
+ export declare function ixInstallLine(platform?: NodeJS.Platform, arch?: string): string;
14
+ /** What Ix adds, in a few lines, said when `p2p setup` recommends it. */
15
+ export declare const IX_PITCH: string[];
16
+ /** The person said no to Ix at `p2p setup` (FileConfig.ixDeclined): not asked again until `p2p setup --ix`. */
17
+ export declare function ixDeclined(file: Pick<FileConfig, "ixDeclined">): boolean;
18
+ /** Records the person's answer to the Ix offer (config.json `ixDeclined`); only `p2p setup`, at a terminal, writes it. */
19
+ export declare function setIxDeclined(home: string, declined: boolean): void;
20
+ /** CI set (anything but empty, 0 or false): never a prompt. */
21
+ export declare function ciEnv(env: Env): boolean;
22
+ /**
23
+ * Whether p2p recommends Ix here (`p2p setup --json`, `p2p extensions --json`, and the hint the front
24
+ * ends give their agent): the Ix CLI isn't found and the person hasn't said no. `install` is the
25
+ * command for the person to run; nothing is ever installed for them.
26
+ */
27
+ export interface IxAdvice {
28
+ /** The Ix CLI was found. */
29
+ installed: boolean;
30
+ /** The person said no at `p2p setup` (`p2p setup --ix` asks again). */
31
+ declined: boolean;
32
+ /** Ix isn't installed and the person hasn't said no. */
33
+ recommended: boolean;
34
+ /** The command that installs Ix on this platform, for the person to run themselves. */
35
+ install: string;
36
+ }
37
+ export declare function ixAdvice(env: Env, file: Pick<FileConfig, "ixDeclined">, o?: {
38
+ reoffer?: boolean;
39
+ }): IxAdvice;
6
40
  /**
7
41
  * `name` resolved to an absolute path through PATH's absolute entries (the same rule as ext-ix's
8
42
  * which.ts: on Windows the current directory is searched before PATH, so a cloned repository's
@@ -41,6 +75,14 @@ export declare function extIxInstalled(env: Env): boolean;
41
75
  export interface SetupIx {
42
76
  /** The Ix CLI was found (its absolute path is local only, never sent anywhere). */
43
77
  found: boolean;
78
+ /** The same as `found` (IxAdvice's name). */
79
+ installed: boolean;
80
+ /** Ix isn't installed and the person hasn't said no: p2p recommends it (it never installs it). */
81
+ recommended: boolean;
82
+ /** The person said no to Ix at an earlier `p2p setup` (`--ix` asks again). */
83
+ declined?: true;
84
+ /** The command that installs Ix on this platform, for the person to run themselves (when it isn't installed). */
85
+ install?: string;
44
86
  /** The `ix` extension is enabled now (by this setup, or already). */
45
87
  enabled: boolean;
46
88
  /** This setup turned it on (a new install, Ix present, ext-ix installed, the person running it). */
@@ -49,19 +91,29 @@ export interface SetupIx {
49
91
  hint?: string;
50
92
  }
51
93
  /**
52
- * Ix on by default, for `p2p setup`. A new install (`created`) gets the `ix` extension enabled when
53
- * the Ix CLI and ext-ix are both there and the person agrees: their front end's token (the Claude
54
- * mod's typed `/peers setup`), or, outside any agent's session (its environment or a Claude Code or
55
- * Codex ancestor), their "yes" typed on the controlling terminal, as for every other person-only
56
- * action (projects.ts). Otherwise nothing changes: an existing install is never switched silently
57
- * (it gets the one-time notice, ixNotice), an agent never enables an extension, and
58
- * P2P_EXTENSIONS, when set, decides alone.
94
+ * What to do about Ix when it isn't installed: the person runs the command themselves; read by an
95
+ * agent (not the person), it says to ask the user instead, since installing is theirs alone.
96
+ */
97
+ export declare function ixInstallHint(line: string, person: boolean): string;
98
+ /**
99
+ * Ix for `p2p setup`: optional and recommended, never installed. Without the Ix CLI it says what to
100
+ * run (`recommended`, `install`), unless the person said no before (`--ix`, `reoffer`, asks again).
101
+ * With it, a new install (`created`; or any install, with `reoffer`) gets the `ix` extension enabled
102
+ * when ext-ix is there too and the person agrees: their front end's token (the Claude mod's typed
103
+ * `/peers setup`), or, outside any agent's session (its environment or a Claude Code or Codex
104
+ * ancestor), their "yes" typed on the controlling terminal, as for every other person-only action
105
+ * (projects.ts). Otherwise nothing changes: an existing install is never switched silently (it gets
106
+ * the one-time notice, ixNotice), an agent never enables an extension, and P2P_EXTENSIONS, when
107
+ * set, decides alone.
59
108
  */
60
- export declare function setupIx(app: App, created: boolean): Promise<SetupIx>;
109
+ export declare function setupIx(app: App, created: boolean, o?: {
110
+ reoffer?: boolean;
111
+ }): Promise<SetupIx>;
61
112
  /**
62
113
  * The one-time notice for an existing install (shown once per device, to the person at a terminal):
63
- * new installs turn the Ix extension on when Ix is present; this one wasn't changed. Undefined when
64
- * it was shown already, Ix isn't installed, or the extension is on (or P2P_EXTENSIONS decides).
114
+ * new installs offer to turn the Ix extension on when Ix is present; this one wasn't changed.
115
+ * Undefined when it was shown already, Ix isn't installed, the person said no to Ix, or the
116
+ * extension is on (or P2P_EXTENSIONS decides).
65
117
  */
66
118
  export declare function ixNotice(app: App): Promise<string | undefined>;
67
119
  /**