@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,1383 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Project boundaries (docs/concepts.md "Projects", threat model "Project boundaries").
4
+ //
5
+ // - A project is a git repository, keyed by its normalised remote URL (if any) and its git
6
+ // common dir, so every worktree and subfolder of one clone is the same project. Outside git,
7
+ // the real path of the folder, or of the nearest folder above it whose share covers its
8
+ // subfolders (opt-in: `p2p project share --subfolders`), never past a repository, a
9
+ // `.p2p-private`, a folder with its own policy or a folder that is gone.
10
+ // - Its policy lives only in this user's state (`<home>/cli/projects`): shared with circles and
11
+ // named people, or private. A project with no policy is private: only this user's own devices
12
+ // see its sessions. Nothing in a repository can widen that; a committed `.p2p-private` file at
13
+ // the repository's top level can only make it private.
14
+ // - Each session is bound to every project it has worked in (its directories, the files it
15
+ // touched): sticky until the session ends. Its ceiling is the intersection of those projects'
16
+ // policies, the most restrictive, so a session that touched a private project stays private.
17
+ // - The ceiling caps the session's signed roster (sessions.ts getSession), so who sees its status,
18
+ // footprints and summary, and who may message it, follows it everywhere a roster is checked: on
19
+ // this device, on the user's other devices and at every peer, old clients included. Sends from a
20
+ // session (messages, extension kinds, offline copies) are refused to anyone outside it.
21
+ // - `p2p tui` and `p2p send` typed at a terminal with no --from-session are the person's own
22
+ // session: never bound, no ceiling.
23
+ import { agentAncestor, isAgentProcess } from "./ancestry.js";
24
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
25
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
26
+ import { homedir, tmpdir } from "node:os";
27
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
28
+ import { circlePolicy, liveFriendshipsV3, loadCircle, sanitizePeerText, standsLookup } from "@peer2peer/core/v3";
29
+ import { CliError } from "./errors.js";
30
+ /** The person's own terminal session (`p2p tui`, `p2p send` with no --from-session). */
31
+ export const PERSON_SESSION = "tui";
32
+ /** The committed file a repository may carry to ask for privacy (it can never widen anything). */
33
+ export const PRIVATE_MARKER = ".p2p-private";
34
+ /**
35
+ * The directory a session works in, as the CLI sees it: P2P_WORKDIR when it names an existing
36
+ * absolute directory (the Claude mod and the Codex bridge run p2p from elsewhere and pass the
37
+ * session's folder there), else the process's own.
38
+ */
39
+ export function sessionWorkdir(env) {
40
+ const w = env.P2P_WORKDIR?.trim();
41
+ if (w && isAbsolute(w)) {
42
+ try {
43
+ if (statSync(w).isDirectory())
44
+ return w;
45
+ }
46
+ catch {
47
+ // not there: the process's own
48
+ }
49
+ }
50
+ return process.cwd();
51
+ }
52
+ /**
53
+ * Every folder a session works in, as its front end tells the CLI: its working directory
54
+ * (sessionWorkdir) and P2P_PROJECT_DIRS (path-delimited: folders it moved to, files it touched
55
+ * elsewhere). Anyone may add to these: a binding only ever narrows who the session reaches.
56
+ */
57
+ export function sessionDirs(env) {
58
+ const extra = (env.P2P_PROJECT_DIRS ?? "").split(delimiter).filter((x) => x.trim() !== "" && isAbsolute(x.trim()));
59
+ // Past the cap (or when the front end says it dropped some): private, never "the first N".
60
+ const why = extra.length > MAX_SESSION_DIRS ? ["folders"] : [];
61
+ const said = env.P2P_PROJECT_DIRS_OVER?.trim() ?? "";
62
+ if (said !== "" && said !== "0")
63
+ why.push(...overWhys(said));
64
+ return { dirs: [sessionWorkdir(env), ...extra.slice(0, MAX_SESSION_DIRS)], over: why.length > 0, why: [...new Set(why)] };
65
+ }
66
+ const OVER_WHYS = new Set(["projects", "folders", "unresolved", "front", "constraints"]);
67
+ /** A front end's over reasons (`unresolved,folders`, an array, or `1`/`true` from an older one): an unknown word counts as `front`, never as nothing. */
68
+ export function overWhys(v) {
69
+ const words = Array.isArray(v) ? v.map(String) : typeof v === "string" ? v.split(/[\s,]+/) : v === true ? ["front"] : [];
70
+ const out = new Set();
71
+ for (const w of words.map((x) => x.trim().toLowerCase()).filter((x) => x !== ""))
72
+ out.add(OVER_WHYS.has(w) ? w : "front");
73
+ return [...out];
74
+ }
75
+ /** At most this many folders a front end passes per call; past it the session is private. */
76
+ export const MAX_SESSION_DIRS = 512;
77
+ /** At most this many projects per session; past it the session is private. */
78
+ export const MAX_SESSION_PROJECTS = 16;
79
+ /** Bindings of sessions not seen for this long are dropped. */
80
+ export const SESSION_BINDING_TTL_MS = 30 * 24 * 3600 * 1000;
81
+ /** At most this many circles and people in one project's policy. */
82
+ export const MAX_PROJECT_SHARES = 32;
83
+ /** At most this many constraints a session keeps; past it, private. */
84
+ export const MAX_SESSION_CONSTRAINTS = 16;
85
+ /** At most this many covered subfolders a bound folder project remembers; past it, every policy below it counts. */
86
+ export const MAX_UNDER = 64;
87
+ /** Causes no share can lift: the session stays private until it ends. */
88
+ const STICKY = new Set(["projects", "folders", "unresolved", "front", "constraints", "legacy-over", "repo-private", "sent-private"]);
89
+ // ---------------------------------------------------------------------------
90
+ // Project identity
91
+ const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex");
92
+ /** The real path, with the case the file system stores (realpathSync.native), else as given. */
93
+ function real(p) {
94
+ try {
95
+ return realpathSync.native(p);
96
+ }
97
+ catch {
98
+ try {
99
+ return realpathSync(p);
100
+ }
101
+ catch {
102
+ return p;
103
+ }
104
+ }
105
+ }
106
+ /** The nearest existing directory at or above `p`, as a real path. */
107
+ function existingDir(p) {
108
+ let cur = resolve(p);
109
+ for (let i = 0; i < 4096; i++) {
110
+ try {
111
+ const st = statSync(cur);
112
+ return real(st.isDirectory() ? cur : dirname(cur));
113
+ }
114
+ catch {
115
+ const up = dirname(cur);
116
+ if (up === cur)
117
+ return cur;
118
+ cur = up;
119
+ }
120
+ }
121
+ return cur;
122
+ }
123
+ /** Device and pseudo-file roots: what is under them is never a project (POSIX). */
124
+ const PSEUDO_ROOTS = ["/dev", "/proc", "/sys"];
125
+ /**
126
+ * Whether `p` is a device or pseudo file (`/dev/null`, `/dev/tty`, `/proc/self/status`), never a
127
+ * project: it exists, isn't a folder, and its real path stays under /dev (and isn't a regular
128
+ * file there, like one in /dev/shm), /proc or /sys. A path through /proc to a real file
129
+ * (`/proc/self/cwd/x`, `/proc/<pid>/root/…`) resolves out of it and binds as usual; one that
130
+ * doesn't exist binds its nearest existing parent as every path does.
131
+ */
132
+ export function pseudoPath(p) {
133
+ if (process.platform === "win32" || typeof p !== "string" || !isAbsolute(p))
134
+ return false;
135
+ // Named there, too: a link elsewhere (a repository's file that points at /dev/null) binds as its folder.
136
+ const at = resolve(p);
137
+ if (!PSEUDO_ROOTS.some((root) => at === root || at.startsWith(`${root}/`)))
138
+ return false;
139
+ let st;
140
+ try {
141
+ st = statSync(p);
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ if (st.isDirectory())
147
+ return false;
148
+ const r = real(p);
149
+ const under = (root) => r === root || r.startsWith(`${root}/`);
150
+ if (under("/dev"))
151
+ return !st.isFile();
152
+ return PSEUDO_ROOTS.slice(1).some(under);
153
+ }
154
+ /**
155
+ * Whether a path component holds a brace expansion with a choice: a `{`, then `,` or `..` with no
156
+ * brace between, then `}` (`{.git,x}`, `{a..z}`). One pass, so it stays linear on any input.
157
+ */
158
+ export function braceChoice(c) {
159
+ let open = false;
160
+ let choice = false;
161
+ for (let i = 0; i < c.length; i++) {
162
+ const ch = c[i];
163
+ if (ch === "{") {
164
+ open = true;
165
+ choice = false;
166
+ }
167
+ else if (ch === "}") {
168
+ if (open && choice)
169
+ return true;
170
+ open = false;
171
+ }
172
+ else if (open && (ch === "," || (ch === "." && c[i + 1] === ".")))
173
+ choice = true;
174
+ }
175
+ return false;
176
+ }
177
+ /**
178
+ * The folder holding the first path component that names a repository's marker (`.git`,
179
+ * PRIVATE_MARKER) or could match one (a glob or brace pattern a dotfile can match: `.g*`,
180
+ * `[.]git`, `{.git,x}`): a command naming it may remove it, so a shared folder above never
181
+ * covers that folder (projectOf). Lexical, on the path as given.
182
+ */
183
+ function namedStop(p) {
184
+ const parts = p.split(/[\\/]/);
185
+ for (let i = 1; i < parts.length; i++) {
186
+ const c = parts[i];
187
+ const glob = ((c.startsWith(".") || c.startsWith("[")) && /[*?[]/.test(c)) || braceChoice(c);
188
+ if (c === ".git" || c === PRIVATE_MARKER || glob)
189
+ return parts.slice(0, i).join(sep) || sep;
190
+ }
191
+ return undefined;
192
+ }
193
+ /** Whether `p` is `dir` or below it (real paths, this platform's separator). */
194
+ function within(p, dir) {
195
+ if (p === dir)
196
+ return true;
197
+ const d = dir.endsWith(sep) ? dir : `${dir}${sep}`;
198
+ return p.startsWith(d);
199
+ }
200
+ /** A folder project's id: its real path, hashed. */
201
+ export function dirProjectId(root) {
202
+ return `pj_${sha(`dir\n${root}`).slice(0, 24)}`;
203
+ }
204
+ /**
205
+ * A remote URL as one canonical string: scheme, credentials, port-less ssh form, trailing `.git`
206
+ * and slashes dropped, host lower-cased. `https://u:t@GitHub.com/a/b.git` and `git@github.com:a/b`
207
+ * are both `github.com/a/b`. A local path stays a path.
208
+ */
209
+ export function normalizeRemote(url) {
210
+ let u = url.trim();
211
+ if (u === "" || u.length > 2048 || /[\0\n\r]/.test(u))
212
+ return undefined;
213
+ let host;
214
+ let path;
215
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\/(.*)$/i.exec(u);
216
+ if (scheme) {
217
+ const rest = scheme[2];
218
+ if (scheme[1].toLowerCase() === "file")
219
+ return u.replace(/^file:\/\//i, "").replace(/\/+$/, "").replace(/\.git$/, "") || undefined;
220
+ const slash = rest.indexOf("/");
221
+ host = slash < 0 ? rest : rest.slice(0, slash);
222
+ path = slash < 0 ? "" : rest.slice(slash + 1);
223
+ host = host.replace(/^.*@/, "").replace(/:\d+$/, "");
224
+ }
225
+ else {
226
+ const scp = /^(?:[^@/:]+@)?([^/:]+):(.*)$/.exec(u);
227
+ if (scp && !/^[A-Za-z]:[\\/]/.test(u)) {
228
+ host = scp[1];
229
+ path = scp[2];
230
+ }
231
+ else {
232
+ u = u.replace(/\\/g, "/").replace(/\/+$/, "").replace(/\.git$/, "");
233
+ return u || undefined;
234
+ }
235
+ }
236
+ path = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").replace(/\/+$/, "");
237
+ host = host.toLowerCase();
238
+ return host ? `${host}/${path}` : undefined;
239
+ }
240
+ /** The remote URLs in a git config file's text: `origin` first, then the others in order. */
241
+ function remotesOf(config) {
242
+ const out = [];
243
+ let section;
244
+ for (const raw of config.split(/\r?\n/)) {
245
+ const line = raw.trim();
246
+ const sec = /^\[\s*remote\s+"([^"]*)"\s*\]$/.exec(line);
247
+ if (sec) {
248
+ section = sec[1];
249
+ continue;
250
+ }
251
+ if (line.startsWith("[")) {
252
+ section = undefined;
253
+ continue;
254
+ }
255
+ const kv = /^url\s*=\s*(.*)$/.exec(line);
256
+ if (section !== undefined && kv)
257
+ out.push({ name: section, url: kv[1].replace(/^"|"$/g, "") });
258
+ }
259
+ out.sort((a, b) => Number(b.name === "origin") - Number(a.name === "origin"));
260
+ return out.map((r) => r.url);
261
+ }
262
+ function readSmall(file) {
263
+ try {
264
+ const st = statSync(file);
265
+ if (!st.isFile() || st.size > 256 * 1024)
266
+ return undefined;
267
+ return readFileSync(file, "utf8");
268
+ }
269
+ catch {
270
+ return undefined;
271
+ }
272
+ }
273
+ /**
274
+ * Whether `d` is a bare git repository: `HEAD`, `objects/` and `refs/` in it, or a `config` that
275
+ * says `bare = true` (a folder named `.git` is a working tree's, found from its parent instead).
276
+ */
277
+ function isBareRepo(d) {
278
+ if (basename(d) === ".git")
279
+ return false;
280
+ const st = (p) => {
281
+ try {
282
+ return statSync(p);
283
+ }
284
+ catch {
285
+ return undefined;
286
+ }
287
+ };
288
+ if (st(join(d, "HEAD"))?.isFile() && st(join(d, "objects"))?.isDirectory() && st(join(d, "refs"))?.isDirectory())
289
+ return true;
290
+ return /^\s*bare\s*=\s*true\s*$/im.test(readSmall(join(d, "config")) ?? "");
291
+ }
292
+ /** The git project whose git dir is `gitDir`, found at the folder `root`. */
293
+ function gitRef(gitDir, root) {
294
+ let common = gitDir;
295
+ const cd = readSmall(join(gitDir, "commondir"))?.trim();
296
+ if (cd)
297
+ common = resolve(gitDir, cd);
298
+ common = real(common);
299
+ const urls = remotesOf(readSmall(join(common, "config")) ?? "");
300
+ const remote = urls.map(normalizeRemote).find((x) => x !== undefined);
301
+ const main = basename(common) === ".git" ? dirname(common) : common;
302
+ const name = clean(remote ? (remote.split("/").pop() ?? "") : basename(main)) || clean(basename(root)) || "project";
303
+ return {
304
+ id: `pj_${sha(`git\n${remote ?? ""}\n${common}`).slice(0, 24)}`,
305
+ name,
306
+ kind: "git",
307
+ root,
308
+ ...(remote ? { remote } : {}),
309
+ ...(existsSync(join(root, PRIVATE_MARKER)) ? { repoPrivate: true } : {}),
310
+ };
311
+ }
312
+ /** Whether `p` names something that is there, its trailing pattern parts (`*.log`, `{a,b}`) left out. */
313
+ function present(p) {
314
+ let q = resolve(p);
315
+ while (/[*?[\]{}]/.test(basename(q)) && dirname(q) !== q)
316
+ q = dirname(q);
317
+ try {
318
+ statSync(q);
319
+ return true;
320
+ }
321
+ catch {
322
+ return false;
323
+ }
324
+ }
325
+ /**
326
+ * The project `dir` belongs to, read from the files alone (git is never run: no hook, fsmonitor
327
+ * or config of the repository's can execute). A `.git` directory or `gitdir:` file up the tree
328
+ * marks a working tree; its common dir (`commondir` for a linked worktree) identifies the clone.
329
+ * A bare repository (isBareRepo) is a git project too, and a `.git` that can't be read as one is
330
+ * a folder project of its own.
331
+ *
332
+ * Outside git, a folder project. With `doc` (the policies), the nearest folder at or above `dir`
333
+ * that has a policy of its own is the project when that is `dir`'s own folder, or when its share
334
+ * covers subfolders (`covers`, given with `p2p project share --subfolders`; a policy without it
335
+ * is for that folder alone, as before). The walk stops at the first folder with a policy (the
336
+ * nearest one wins, so a private subfolder stays private; one that doesn't cover leaves `dir`'s
337
+ * own folder as the project), and it never crosses:
338
+ * - a git repository (found first: a nested repository is always its own project);
339
+ * - a `.p2p-private` (at or above `dir`: the folder project is private, whatever covers it);
340
+ * - a folder whose `.git` or `.p2p-private` the path itself names (namedStop: a command that may
341
+ * have just removed it);
342
+ * - the nearest existing folder, when `dir` itself isn't there (deleted or moved since the
343
+ * session named it, or not made yet): that folder is the project unless it has a policy, so a
344
+ * repository removed after a session read it is never covered from above.
345
+ * Without `doc` (sharing, `project show`): the folder itself.
346
+ */
347
+ export function projectOf(dir, doc) {
348
+ const given = resolve(dir);
349
+ const start = existingDir(given);
350
+ let cur = start;
351
+ for (let i = 0; i < 4096; i++) {
352
+ const dotgit = join(cur, ".git");
353
+ // Anything named .git here (a folder, a file, a symlink, even a broken or unreadable one) ends
354
+ // the walk: this folder is its own project, never the parent repository's.
355
+ let isThere;
356
+ try {
357
+ lstatSync(dotgit);
358
+ isThere = true;
359
+ }
360
+ catch {
361
+ isThere = false;
362
+ }
363
+ if (isThere) {
364
+ let st;
365
+ try {
366
+ st = statSync(dotgit);
367
+ }
368
+ catch {
369
+ st = undefined;
370
+ }
371
+ let gitDir;
372
+ if (st?.isDirectory())
373
+ gitDir = dotgit;
374
+ else if (st?.isFile()) {
375
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readSmall(dotgit) ?? "");
376
+ if (m)
377
+ gitDir = resolve(cur, m[1]);
378
+ }
379
+ if (!gitDir || !existsSync(gitDir)) {
380
+ // A .git that can't be read as one: a folder project at this level (private until shared).
381
+ return { id: dirProjectId(cur), name: clean(basename(cur)) || "folder", kind: "dir", root: cur };
382
+ }
383
+ return gitRef(gitDir, cur);
384
+ }
385
+ // A bare repository (a clone with no working tree): a git project, never a shared folder's.
386
+ if (isBareRepo(cur))
387
+ return gitRef(cur, cur);
388
+ const up = dirname(cur);
389
+ if (up === cur)
390
+ break;
391
+ cur = up;
392
+ }
393
+ const dirRef = (root, repoPrivate) => ({ id: dirProjectId(root), name: clean(basename(root)) || "folder", kind: "dir", root, ...(repoPrivate ? { repoPrivate: true } : {}) });
394
+ // A .p2p-private at or above the folder (no repository in between, or the walk above found it):
395
+ // the folder is private, whatever a policy above says.
396
+ let marked = false;
397
+ for (let c = start, i = 0; i < 4096; i++) {
398
+ if (existsSync(join(c, PRIVATE_MARKER))) {
399
+ marked = true;
400
+ break;
401
+ }
402
+ const up = dirname(c);
403
+ if (up === c)
404
+ break;
405
+ c = up;
406
+ }
407
+ if (!doc || marked)
408
+ return dirRef(start, marked);
409
+ // The walk stops at a folder the path names a marker in (it may be gone now: never covered from
410
+ // above), and at `start` itself when the path isn't there (only its nearest parent is).
411
+ const named = namedStop(given);
412
+ const ns = named === undefined ? undefined : existingDir(named);
413
+ const stop = !present(given) ? start : ns === undefined ? undefined : within(start, ns) ? ns : start;
414
+ for (let c = start, i = 0; i < 4096; i++) {
415
+ const rec = doc.projects[dirProjectId(c)];
416
+ if (rec)
417
+ return c === start || rec.covers === true ? dirRef(c, false) : dirRef(start, false);
418
+ if (c === stop)
419
+ break;
420
+ const up = dirname(c);
421
+ if (up === c)
422
+ break;
423
+ c = up;
424
+ }
425
+ return dirRef(start, false);
426
+ }
427
+ const clean = (s) => sanitizePeerText(s, 64).replace(/[^\w.@+-]/g, "").slice(0, 64);
428
+ // ---------------------------------------------------------------------------
429
+ // Policies
430
+ export async function projectsDoc(app) {
431
+ const d = (await app.state.get("projects"));
432
+ return d && d.v === 1 && d.projects && typeof d.projects === "object" ? d : { v: 1, projects: {} };
433
+ }
434
+ /** A project's share as stored, or `private` (no policy: private by default). */
435
+ export function shareOf(doc, id) {
436
+ const r = doc.projects[id];
437
+ if (!r || r.share === "private" || typeof r.share !== "object")
438
+ return "private";
439
+ const circles = Array.isArray(r.share.circles) ? r.share.circles.filter((x) => typeof x === "string") : [];
440
+ const people = Array.isArray(r.share.people) ? r.share.people.filter((x) => typeof x === "string") : [];
441
+ return circles.length + people.length > 0 ? { circles, people } : "private";
442
+ }
443
+ export async function projectView(app, ref, doc) {
444
+ const d = doc ?? (await projectsDoc(app));
445
+ const share = shareOf(d, ref.id);
446
+ const circles = [];
447
+ const people = [];
448
+ if (share !== "private") {
449
+ for (const cid of share.circles) {
450
+ const rec = await app.store.getCircle(cid);
451
+ const c = await loadCircle(app.store, cid).catch(() => undefined);
452
+ circles.push({ cid, ...(c ? { name: sanitizePeerText(c.chain.head.name, 64) } : {}), ...(c && circlePolicy(c.chain.head) === "open" ? { open: true } : {}), joined: rec?.joinedByMe === true });
453
+ }
454
+ for (const u of share.people)
455
+ people.push({ userId: u, address: await app.addressOf(u) });
456
+ }
457
+ const policy = share === "private" || ref.repoPrivate ? "private" : "shared";
458
+ const why = ref.repoPrivate ? `the repository asks to stay private (${PRIVATE_MARKER} at its top level)` : !d.projects[ref.id] ? "unmapped" : undefined;
459
+ return {
460
+ id: ref.id,
461
+ name: ref.name,
462
+ kind: ref.kind,
463
+ root: ref.root,
464
+ ...(ref.remote ? { remote: ref.remote } : {}),
465
+ policy,
466
+ circles,
467
+ people,
468
+ ...(why ? { why } : {}),
469
+ ...(ref.repoPrivate ? { repoPrivate: true } : {}),
470
+ ...(d.projects[ref.id]?.covers === true && ref.kind === "dir" ? { covers: true } : {}),
471
+ graph: projectGraphTarget(app, ref, d),
472
+ };
473
+ }
474
+ /**
475
+ * Why `root` may not cover its subfolders (a share for it alone is still allowed), or undefined:
476
+ * the file system's root, a home folder or a folder above one (`$HOME`, `/Users`, `/home/<u>`),
477
+ * the temporary folders (`/tmp`, `/private/tmp`, `/var/folders/…`, os.tmpdir() and above it), and
478
+ * the system's top folders. Everything below them would be one project.
479
+ */
480
+ export function broadRoot(root, env = {}) {
481
+ const norm = (p) => {
482
+ const r = resolve(p);
483
+ return process.platform === "win32" ? r.toLowerCase() : r;
484
+ };
485
+ const forms = (p) => [...new Set([norm(p), norm(real(p))])];
486
+ const at = forms(root);
487
+ const isOrAbove = (dir) => !!dir && isAbsolute(dir) && forms(dir).some((d) => at.some((r) => within(d, r)));
488
+ if (at.some((r) => dirname(r) === r))
489
+ return "the file system's root";
490
+ const homes = [homedir(), env.HOME, env.USERPROFILE].filter((x) => typeof x === "string" && x !== "");
491
+ if (homes.some(isOrAbove))
492
+ return "a home folder (or a folder that holds one)";
493
+ if (isOrAbove(tmpdir()) || isOrAbove(env.TMPDIR))
494
+ return "the temporary folder (or a folder that holds it)";
495
+ for (const r of at) {
496
+ const parts = r.split(/[\\/]+/).filter(Boolean);
497
+ const top = (parts[0] ?? "").toLowerCase();
498
+ if (!/^[a-z]:$/i.test(top) && parts.length === 1)
499
+ return "a top-level system folder";
500
+ if (/^[a-z]:$/i.test(parts[0] ?? "") && parts.length <= 2 && (parts.length === 1 || (parts[1] ?? "").toLowerCase() === "users"))
501
+ return "a drive's root or its Users folder";
502
+ if (/^[a-z]:$/i.test(parts[0] ?? "") && parts.length === 3 && (parts[1] ?? "").toLowerCase() === "users")
503
+ return "a home folder";
504
+ if (["home", "users"].includes(top) && parts.length <= 2)
505
+ return "a home folder (or the folder that holds them)";
506
+ if (top === "tmp" && parts.length === 1)
507
+ return "the temporary folder";
508
+ if (top === "private" && parts.length <= 2)
509
+ return "a system folder";
510
+ if (top === "private" && (parts[1] === "tmp" || parts[1] === "var") && parts.length === 2)
511
+ return "the temporary folder";
512
+ const vf = top === "var" ? 1 : top === "private" && parts[1] === "var" ? 2 : -1;
513
+ if (vf > 0 && parts[vf] === "folders" && parts.length <= vf + 4)
514
+ return "the temporary folder (or a folder that holds it)";
515
+ if (vf > 0 && parts.length <= vf + 1)
516
+ return "a system folder";
517
+ if (top === "run" && parts.length <= 3)
518
+ return "a system folder";
519
+ if (["volumes", "mnt", "media"].includes(top) && parts.length <= 2)
520
+ return "a volume's root";
521
+ }
522
+ return undefined;
523
+ }
524
+ /** At most this deep and this many entries `nestedBoundaries` looks through below a covering share. */
525
+ export const NESTED_SCAN_DEPTH = 4;
526
+ export const NESTED_SCAN_ENTRIES = 2000;
527
+ /**
528
+ * The nested git repositories (a `.git`, or a bare repository) and `.p2p-private` folders below
529
+ * `root`, for the warning a covering share prints: each stays its own project, but only while its
530
+ * marker is there. Bounded (NESTED_SCAN_DEPTH, NESTED_SCAN_ENTRIES: `capped` past it); symlinks
531
+ * are never followed.
532
+ */
533
+ export function nestedBoundaries(root) {
534
+ const repos = [];
535
+ const priv = [];
536
+ let seen = 0;
537
+ let capped = false;
538
+ let level = [root];
539
+ for (let depth = 1; depth <= NESTED_SCAN_DEPTH && level.length > 0 && !capped; depth++) {
540
+ const next = [];
541
+ for (const d of level) {
542
+ let entries;
543
+ try {
544
+ entries = readdirSync(d, { withFileTypes: true });
545
+ }
546
+ catch {
547
+ continue;
548
+ }
549
+ for (const e of entries) {
550
+ if (++seen > NESTED_SCAN_ENTRIES) {
551
+ capped = true;
552
+ break;
553
+ }
554
+ if (!e.isDirectory() || e.isSymbolicLink())
555
+ continue;
556
+ const p = join(d, e.name);
557
+ if (e.name === ".git")
558
+ continue;
559
+ if (existsSync(join(p, ".git")) || isBareRepo(p)) {
560
+ repos.push(p);
561
+ continue;
562
+ }
563
+ if (existsSync(join(p, PRIVATE_MARKER)))
564
+ priv.push(p);
565
+ next.push(p);
566
+ }
567
+ if (capped)
568
+ break;
569
+ }
570
+ level = next;
571
+ }
572
+ return { repos, private: priv, capped };
573
+ }
574
+ /**
575
+ * `p2p project share`: share the project at `dir` with circles you joined and friends. Replaces the
576
+ * project's shares with exactly these (`add` keeps the ones it has). Only ever the person's
577
+ * command: no session or file can run it for them (the mod and the Codex bridge refuse it from a
578
+ * model).
579
+ */
580
+ export async function shareProject(app, dir, targets) {
581
+ const ref = projectOf(dir);
582
+ if (ref.repoPrivate) {
583
+ throw new CliError("repo_private", `${ref.name} asks to stay private: its repository has ${PRIVATE_MARKER} at the top level. Peer2Peer never shares it; remove that file from your copy first if you mean to`);
584
+ }
585
+ const warnings = [];
586
+ // Subfolders are covered only when asked, and never below a root that holds everything.
587
+ let subfolders = targets.subfolders === true;
588
+ if (subfolders && ref.kind === "git") {
589
+ warnings.push(`${ref.name} is a git repository: its subfolders are part of it already (--subfolders is for folders outside git)`);
590
+ subfolders = false;
591
+ }
592
+ if (subfolders) {
593
+ const broad = broadRoot(ref.root, app.env);
594
+ if (broad)
595
+ throw new CliError("usage", `${ref.root} is ${broad}: a share there can't cover its subfolders (share it without --subfolders, or share the folders below it you mean)`);
596
+ const n = nestedBoundaries(ref.root);
597
+ const list = (xs) => `${xs.slice(0, 10).join(", ")}${xs.length > 10 ? ` and ${xs.length - 10} more` : ""}`;
598
+ if (n.repos.length > 0)
599
+ warnings.push(`git repositories below ${ref.root} stay their own projects (private until you share each one), only while their .git is there: ${list(n.repos)}`);
600
+ if (n.private.length > 0)
601
+ warnings.push(`folders below ${ref.root} with ${PRIVATE_MARKER} stay private: ${list(n.private)}`);
602
+ if (n.capped)
603
+ warnings.push(`stopped looking for repositories below ${ref.root} after ${NESTED_SCAN_ENTRIES} entries (${NESTED_SCAN_DEPTH} levels deep): there may be more than listed`);
604
+ }
605
+ const { resolveCircle } = await import("./circle-ops.js");
606
+ const circles = [];
607
+ for (const c of targets.circles ?? []) {
608
+ const r = await resolveCircle(app, c);
609
+ if (!r.record.joinedByMe)
610
+ throw new CliError("usage", `you haven't joined circle ${c}`);
611
+ if (!circles.includes(r.record.cid))
612
+ circles.push(r.record.cid);
613
+ const lc = await loadCircle(app.store, r.record.cid).catch(() => undefined);
614
+ if (lc && circlePolicy(lc.chain.head) === "open")
615
+ warnings.push(`circle ${r.record.cid} is open: anyone its owner admits will see ${ref.name}'s sessions`);
616
+ }
617
+ const people = [];
618
+ if ((targets.people ?? []).length > 0) {
619
+ const friends = await liveFriendshipsV3(app.store, app.signerCtx());
620
+ for (const p of targets.people ?? []) {
621
+ const u = await app.resolveUser(p);
622
+ if (u === app.userId)
623
+ continue;
624
+ if (await app.store.isBlocked(u))
625
+ throw new CliError("blocked", `you blocked ${p}`);
626
+ if (!friends.some((f) => f.inviter === u || f.invitee === u))
627
+ throw new CliError("usage", `${await app.addressOf(u)} isn't your friend: share with a circle they're in, or befriend them first`);
628
+ if (!people.includes(u))
629
+ people.push(u);
630
+ }
631
+ }
632
+ if (circles.length + people.length === 0)
633
+ throw new CliError("usage", "name a circle or a friend to share with (or `p2p project private`)");
634
+ const doc = await app.state.update("projects", (cur) => {
635
+ const d = cur?.v === 1 ? cur : { v: 1, projects: {} };
636
+ const old = shareOf(d, ref.id);
637
+ const keep = targets.add && old !== "private" ? old : { circles: [], people: [] };
638
+ const share = { circles: [...new Set([...keep.circles, ...circles])], people: [...new Set([...keep.people, ...people])] };
639
+ if (share.circles.length + share.people.length > MAX_PROJECT_SHARES)
640
+ throw new CliError("usage", `a project is shared with at most ${MAX_PROJECT_SHARES} circles and people`);
641
+ // --add keeps whether it covers its subfolders; a share made afresh covers them only when asked.
642
+ const covers = subfolders || (targets.add === true && targets.subfolders === undefined && d.projects[ref.id]?.covers === true);
643
+ const next = { ...d, projects: { ...d.projects, [ref.id]: { name: ref.name, root: ref.root, ...(ref.remote ? { remote: ref.remote } : {}), share, ...(covers ? { covers: true } : {}), at: Date.now() } } };
644
+ return { next: next, result: next };
645
+ });
646
+ return { project: await projectView(app, ref, doc), warnings };
647
+ }
648
+ /** `p2p project private`: only your own devices see the project's sessions (the default). */
649
+ export async function makeProjectPrivate(app, dir) {
650
+ const ref = projectOf(dir);
651
+ const doc = await app.state.update("projects", (cur) => {
652
+ const d = cur?.v === 1 ? cur : { v: 1, projects: {} };
653
+ const next = { ...d, projects: { ...d.projects, [ref.id]: { name: ref.name, root: ref.root, ...(ref.remote ? { remote: ref.remote } : {}), share: "private", at: Date.now() } } };
654
+ return { next: next, result: next };
655
+ });
656
+ return projectView(app, ref, doc);
657
+ }
658
+ /** `p2p project ls`: every project with a policy on this device. */
659
+ export async function listProjects(app) {
660
+ const doc = await projectsDoc(app);
661
+ const out = [];
662
+ for (const [id, r] of Object.entries(doc.projects)) {
663
+ out.push(await projectView(app, { id, name: r.name, kind: r.remote !== undefined || existsSync(join(r.root, ".git")) ? "git" : "dir", root: r.root, ...(r.remote ? { remote: r.remote } : {}) }, doc));
664
+ }
665
+ return out.sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
666
+ }
667
+ /** `p2p project show`: the project at `dir` (a shared folder above it covers it), its policy and why. */
668
+ export async function showProject(app, dir) {
669
+ const doc = await projectsDoc(app);
670
+ return projectView(app, projectOf(dir, doc), doc);
671
+ }
672
+ // ---------------------------------------------------------------------------
673
+ // Sessions
674
+ /**
675
+ * Binds a session to the projects of `dirs` (sticky: a session's projects only ever grow until it
676
+ * ends), plus a constraint an own-device message carried. The person's own session is never
677
+ * bound; another caller naming it is refused. A session an agent names (agentContext) that no
678
+ * front end of this user has registered (personTokenOk) starts private.
679
+ */
680
+ export async function bindSession(app, sid, dirs, o = {}) {
681
+ if (sid === PERSON_SESSION) {
682
+ if (o.person)
683
+ return undefined;
684
+ throw new CliError("usage", `session ${PERSON_SESSION} is your own terminal's (p2p tui, or p2p send typed with no --from-session); an agent sends from its own session`);
685
+ }
686
+ // Folder projects follow the policies (a shared folder covers its subfolders): read once, before the lock.
687
+ const doc = dirs.length > 0 ? await projectsDoc(app) : undefined;
688
+ const refs = new Map();
689
+ for (const d of dirs) {
690
+ if (typeof d !== "string" || d.trim() === "")
691
+ continue;
692
+ // A device or pseudo file (2>/dev/null) is no project; a path that isn't there yet still binds its parent's.
693
+ if (pseudoPath(d))
694
+ continue;
695
+ const r = projectOf(d, doc);
696
+ const one = refs.get(r.id) ?? { ref: r, under: new Set() };
697
+ // A folder a shared folder above covered: remembered, so a policy it gets later still narrows this session.
698
+ if (r.kind === "dir") {
699
+ const at = existingDir(d);
700
+ if (at !== r.root && within(at, r.root))
701
+ one.under.add(at);
702
+ }
703
+ refs.set(r.id, one);
704
+ }
705
+ // Who may speak for a session (statuses, sends): its front end (the person token), or, for a session
706
+ // no front end registered, a caller outside any agent's session. An agent's own shell never may.
707
+ const front = app.front === true;
708
+ if (!o.inbound && !front && agentContext(app.env)) {
709
+ throw new CliError("refused", `session ${sid}: inside an agent's session only its front end speaks for a session (the Claude mod's SendMessage, the Codex bridge's p2p_send), never the shell`);
710
+ }
711
+ // A session nobody has used yet, without the front end's token: the person confirms it on their own
712
+ // terminal (a status, a send, an extension send or state alike; a detached process can't).
713
+ if (!o.inbound && !front && !(await sessionBinding(app, sid))) {
714
+ if (!(await app.confirmTty(`p2p is about to speak for a new session ${sid}.`))) {
715
+ throw new CliError("refused", `session ${sid} is new: without your front end's token, confirm it with "yes" on your own terminal (read from the terminal itself, never stdin or a flag)`);
716
+ }
717
+ }
718
+ const now = Date.now();
719
+ return app.state.update("sessionProjects", (cur) => {
720
+ const all = { ...(cur ?? {}) };
721
+ for (const [k, v] of Object.entries(all))
722
+ if (!v || typeof v.at !== "number" || now - v.at > SESSION_BINDING_TTL_MS)
723
+ delete all[k];
724
+ const have = all[sid];
725
+ // A session a front end registered is that front end's: nobody else acts on it, not even to narrow it.
726
+ if (!o.inbound && !front && have?.registered) {
727
+ throw new CliError("refused", `session ${sid} belongs to a front end of yours (the Claude mod or the Codex bridge): only it speaks for that session`);
728
+ }
729
+ const projects = { ...(have?.projects ?? {}) };
730
+ const why = new Set(have?.overWhy ?? []);
731
+ if (o.over === true)
732
+ why.add("front");
733
+ else if (Array.isArray(o.over))
734
+ for (const w of overWhys(o.over))
735
+ why.add(w);
736
+ // A binding from before overWhy kept only `over`: it stays over (said as such: legacy-over).
737
+ let over = have?.over === true || why.size > 0;
738
+ for (const { ref: r, under } of refs.values()) {
739
+ const prev = projects[r.id];
740
+ if (!prev && Object.keys(projects).length >= MAX_SESSION_PROJECTS) {
741
+ over = true;
742
+ why.add("projects");
743
+ continue;
744
+ }
745
+ // Once a repository asked for privacy, it stays asked for this session; covered folders only add up.
746
+ const all = new Set([...(prev?.under ?? []), ...under]);
747
+ const underOver = prev?.underOver === true || all.size > MAX_UNDER;
748
+ projects[r.id] = {
749
+ name: r.name,
750
+ root: prev?.root ?? r.root,
751
+ ...(r.repoPrivate || prev?.repoPrivate ? { repoPrivate: true } : {}),
752
+ ...(!underOver && all.size > 0 ? { under: [...all].sort() } : {}),
753
+ ...(underOver ? { underOver: true } : {}),
754
+ };
755
+ }
756
+ const constraints = [...(have?.constraints ?? [])];
757
+ if (o.constraint !== undefined && !constraints.some((c) => JSON.stringify(c) === JSON.stringify(o.constraint))) {
758
+ if (constraints.length >= MAX_SESSION_CONSTRAINTS) {
759
+ over = true;
760
+ why.add("constraints");
761
+ }
762
+ else
763
+ constraints.push(o.constraint);
764
+ }
765
+ const registered = front || have?.registered === true;
766
+ const unregistered = !registered && have?.unregistered === true;
767
+ const next = {
768
+ projects,
769
+ ...(over ? { over: true } : {}),
770
+ ...(why.size > 0 ? { overWhy: [...why] } : {}),
771
+ ...(constraints.length ? { constraints } : {}),
772
+ ...(unregistered ? { unregistered: true } : {}),
773
+ ...(registered ? { registered: true } : {}),
774
+ since: typeof have?.since === "number" ? have.since : now,
775
+ at: now,
776
+ };
777
+ return { next: { ...all, [sid]: next }, result: next };
778
+ });
779
+ }
780
+ // ---------------------------------------------------------------------------
781
+ // Who is calling: the person's front end, or an agent
782
+ /**
783
+ * The variables Claude Code and Codex set in the commands their agents run (an allow-list, from
784
+ * their documentation and source: docs/security/threat-model.md "Project boundaries"). Variables a
785
+ * person sets in their own shell (CODEX_HOME, CODEX_API_KEY, CODEX_PROFILE) never count.
786
+ */
787
+ export const AGENT_ENV_VARS = [
788
+ // Claude Code (code.claude.com/docs/en/env-vars): its Bash, PowerShell and Monitor tools, hooks.
789
+ "CLAUDECODE",
790
+ "CLAUDE_CODE_CHILD_SESSION",
791
+ // Codex (openai/codex codex-rs core/src/unified_exec/process_manager.rs, exec_env.rs, sandboxing/mod.rs):
792
+ // every model tool call, the sandbox markers, and the thread (its user `!` shell sets the last two too).
793
+ "CODEX_TOOL_CALL_ID",
794
+ "CODEX_CI",
795
+ "CODEX_SANDBOX",
796
+ "CODEX_SANDBOX_NETWORK_DISABLED",
797
+ "CODEX_THREAD_ID",
798
+ "CODEX_SESSION_ID",
799
+ ];
800
+ /** Whether the environment says this runs inside an agent's tool call. */
801
+ export function agentEnv(env) {
802
+ if (!env)
803
+ return false;
804
+ return AGENT_ENV_VARS.some((k) => (env[k] ?? "") !== "");
805
+ }
806
+ /** Whether this call runs on an agent's behalf: its environment, or a Claude Code or Codex ancestor (ancestry.ts). */
807
+ export function agentContext(env) {
808
+ return agentEnv(env) || agentAncestor();
809
+ }
810
+ export { isAgentProcess };
811
+ /** `<home>/cli/person.key`: a random secret the person's front ends (the Claude mod, the Codex bridge) pass back as P2P_PERSON_TOKEN. */
812
+ export function personTokenFile(home) {
813
+ return join(home, "cli", "person.key");
814
+ }
815
+ const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
816
+ /** The person token, made once (exclusively, 0600, in the CLI's own folder, which the mod's guards keep from the model). */
817
+ export function personToken(home) {
818
+ const f = personTokenFile(home);
819
+ const read = () => {
820
+ try {
821
+ const t = readFileSync(f, "utf8").trim();
822
+ return TOKEN_RE.test(t) ? t : undefined;
823
+ }
824
+ catch {
825
+ return undefined;
826
+ }
827
+ };
828
+ const have = read();
829
+ if (have)
830
+ return have;
831
+ mkdirSync(join(home, "cli"), { recursive: true, mode: 0o700 });
832
+ const t = randomBytes(32).toString("base64url");
833
+ try {
834
+ writeFileSync(f, t, { mode: 0o600, flag: "wx" });
835
+ return t;
836
+ }
837
+ catch {
838
+ // Made meanwhile by another process (or a file in the way): that one, if it is a token.
839
+ const again = read();
840
+ if (again)
841
+ return again;
842
+ throw new CliError("conflict", `${f} isn't a person token: remove it and run the command again`);
843
+ }
844
+ }
845
+ /** Whether P2P_PERSON_TOKEN is this home's person token (read only: a missing file is no match). */
846
+ export function personTokenOk(env, home) {
847
+ const given = env?.P2P_PERSON_TOKEN?.trim();
848
+ if (!given || typeof home !== "string" || home === "")
849
+ return false;
850
+ let t;
851
+ try {
852
+ t = readFileSync(personTokenFile(home), "utf8").trim();
853
+ }
854
+ catch {
855
+ return false;
856
+ }
857
+ const a = Buffer.from(given);
858
+ const b = Buffer.from(t);
859
+ return a.length === b.length && b.length >= 32 && timingSafeEqual(a, b);
860
+ }
861
+ /**
862
+ * Checks the person token once, at the start of a command, and takes it out of the environment
863
+ * (this object and the process's), so no child (git, ix, an extension's tool) ever inherits it.
864
+ */
865
+ export function takePersonToken(env, home) {
866
+ const ok = personTokenOk(env, home);
867
+ delete env.P2P_PERSON_TOKEN;
868
+ delete process.env.P2P_PERSON_TOKEN;
869
+ return ok;
870
+ }
871
+ /**
872
+ * Lets a command that widens who reaches this user (sharing a project, a session, a default
873
+ * circle, invites, joins, trust, friends) run only for the person: their front end's token; or,
874
+ * outside any agent's session, their "yes" typed on the controlling terminal (never stdin, never a
875
+ * flag: a process detached from every terminal can't give it). Reads are never asked, except for
876
+ * the person's own messages (history.ts), which pass their own `why`.
877
+ */
878
+ export async function assertPersonForWidening(app, what, confirm, why = "changes who reaches you") {
879
+ if (app.front === true)
880
+ return;
881
+ if (agentContext(app.env)) {
882
+ throw new CliError("refused", `\`p2p ${what}\` ${why}, so only you run it: in your own terminal (not inside Claude Code or Codex), or with /peers in Claude Code. It was refused here because it runs inside an agent's session`);
883
+ }
884
+ if (!(await confirm(`p2p ${what} ${why}.`))) {
885
+ throw new CliError("refused", `\`p2p ${what}\` ${why}: confirm it with "yes" on your own terminal (it is read from the terminal itself, so a script or a process without one can't)`);
886
+ }
887
+ }
888
+ /**
889
+ * For an act on a session that binds nothing (a delivery receipt): the session's front end (its
890
+ * token); or, outside any agent's session, a caller acting for a session no front end registered.
891
+ * An agent's own shell never may, as for statuses and sends (bindSession).
892
+ */
893
+ export async function assertSpeaksFor(app, sid) {
894
+ if (app.front === true)
895
+ return;
896
+ if (agentContext(app.env)) {
897
+ throw new CliError("refused", `session ${sid}: inside an agent's session only its front end speaks for a session (the Claude mod, the Codex bridge), never the shell`);
898
+ }
899
+ if ((await sessionBinding(app, sid))?.registered) {
900
+ throw new CliError("refused", `session ${sid} belongs to a front end of yours (the Claude mod or the Codex bridge): only it speaks for that session`);
901
+ }
902
+ }
903
+ /** Whether a person-only path (session `tui`) may run here: the person's front end, or no agent in sight (then a terminal "yes" too). */
904
+ export function personHere(app) {
905
+ return app.front === true || !agentContext(app.env);
906
+ }
907
+ export async function sessionBinding(app, sid) {
908
+ return (await app.state.get("sessionProjects"))?.[sid];
909
+ }
910
+ const OVER_TEXT = {
911
+ projects: `it worked in more than ${MAX_SESSION_PROJECTS} projects`,
912
+ folders: "it worked in more folders than Peer2Peer keeps track of for one session",
913
+ unresolved: "a command it ran named a path Peer2Peer couldn't resolve (one that starts with a variable or a command substitution its front end doesn't know the value of, like $X/… or $(…)/…), so which project that path is in can't be told",
914
+ front: "its front end couldn't keep track of every folder it worked in (a forked conversation, or a record it couldn't read)",
915
+ constraints: `more than ${MAX_SESSION_CONSTRAINTS} sessions of yours sent it messages`,
916
+ "legacy-over": "it worked in more projects or folders than Peer2Peer keeps track of, or named a path Peer2Peer couldn't resolve",
917
+ };
918
+ /**
919
+ * Every policy a bound project answers to: its own, and, for a folder project a shared folder
920
+ * covered, each policy a covered subfolder (or a folder between it and the root) has since been
921
+ * given. Past MAX_UNDER covered subfolders, every folder policy below the root.
922
+ */
923
+ function boundShares(doc, id, p) {
924
+ const out = [{ share: shareOf(doc, id), mapped: doc.projects[id] !== undefined, name: p.name }];
925
+ const root = p.root;
926
+ if (typeof root !== "string" || root === "")
927
+ return out;
928
+ const seen = new Set([id]);
929
+ const add = (pid) => {
930
+ const r = doc.projects[pid];
931
+ if (seen.has(pid) || !r)
932
+ return;
933
+ seen.add(pid);
934
+ out.push({ share: shareOf(doc, pid), mapped: true, name: clean(String(r.name ?? "")) || p.name });
935
+ };
936
+ // Subfolders it covered, and its share no longer covers them (shared again without --subfolders): private.
937
+ if ((p.underOver || (p.under?.length ?? 0) > 0) && doc.projects[id]?.covers !== true)
938
+ out.push({ share: "private", mapped: true, name: p.name });
939
+ if (p.underOver) {
940
+ for (const [pid, r] of Object.entries(doc.projects))
941
+ if (typeof r?.root === "string" && r.root !== root && within(r.root, root) && pid === dirProjectId(r.root))
942
+ add(pid);
943
+ return out;
944
+ }
945
+ for (const f of p.under ?? []) {
946
+ if (typeof f !== "string")
947
+ continue;
948
+ for (let c = f, i = 0; i < 4096 && c !== root && within(c, root); i++) {
949
+ add(dirProjectId(c));
950
+ const up = dirname(c);
951
+ if (up === c)
952
+ break;
953
+ c = up;
954
+ }
955
+ }
956
+ return out;
957
+ }
958
+ /** Why a binding is private, every cause (no network: `disjoint` needs the store, see sessionCeiling). */
959
+ export function privateReasons(doc, b) {
960
+ const out = [];
961
+ if (b.over)
962
+ for (const w of b.overWhy?.length ? overWhys(b.overWhy) : ["legacy-over"])
963
+ out.push({ cause: w, why: OVER_TEXT[w] });
964
+ if (b.unregistered)
965
+ out.push({ cause: "unregistered", why: "an agent named it, and no front end of yours has registered it" });
966
+ for (const [id, p] of Object.entries(b.projects)) {
967
+ if (p.repoPrivate) {
968
+ out.push({ cause: "repo-private", why: `${p.name} asks to stay private (${PRIVATE_MARKER})`, project: p.name });
969
+ continue;
970
+ }
971
+ for (const s of boundShares(doc, id, p)) {
972
+ if (s.share !== "private")
973
+ continue;
974
+ out.push(s.mapped ? { cause: "private", why: `${s.name} is private`, project: s.name } : { cause: "unshared", why: `${s.name} isn't shared (projects are private until you share them)`, project: s.name });
975
+ break;
976
+ }
977
+ }
978
+ if ((b.constraints ?? []).includes("private"))
979
+ out.push({ cause: "sent-private", why: "a private session of yours sent it a message" });
980
+ return out;
981
+ }
982
+ /**
983
+ * What the person can do about a private session, for an error a model may read: a share only
984
+ * when a share can lift it, never the "share each project" hint for a cause that lasts until the
985
+ * session ends (a cap, an unresolved path, a dropped front end, `.p2p-private`, a private
986
+ * session's message).
987
+ */
988
+ export function privateRemedy(causes, names) {
989
+ if (causes.some((c) => STICKY.has(c))) {
990
+ return "sharing a project can't change that, and it lasts until the session ends: start a new session for the work you want to share (`p2p session show <session>` in your own terminal, or /peers session in Claude Code, lists what it is bound to and why)";
991
+ }
992
+ const parts = [];
993
+ if (causes.includes("unregistered"))
994
+ parts.push("send from the session's own front end (SendMessage in Claude Code, p2p_send in Codex), which registers it");
995
+ if (causes.some((c) => c === "private" || c === "unshared" || c === "disjoint") || parts.length === 0)
996
+ parts.push(shareHint(names));
997
+ return parts.join("; and ");
998
+ }
999
+ /** Whether a ceiling's privacy can only end with the session (privateRemedy says to start a new one). */
1000
+ export function stickyPrivate(c) {
1001
+ return c.kind === "private" && c.causes.some((x) => STICKY.has(x));
1002
+ }
1003
+ /**
1004
+ * The most a session may reach: the intersection of every bound project's policy. Unmapped,
1005
+ * private and repository-private projects make it private, and so does an empty intersection.
1006
+ */
1007
+ export async function sessionCeiling(app, sid, binding) {
1008
+ if (sid === PERSON_SESSION)
1009
+ return { kind: "none" };
1010
+ const b = binding === null ? undefined : (binding ?? (await sessionBinding(app, sid)));
1011
+ if (!b || (Object.keys(b.projects).length === 0 && !b.constraints?.length && !b.unregistered && !b.over))
1012
+ return { kind: "none" };
1013
+ const doc = await projectsDoc(app);
1014
+ const reasons = privateReasons(doc, b);
1015
+ if (reasons.length > 0)
1016
+ return privateOf(reasons);
1017
+ let circles;
1018
+ let people;
1019
+ const shares = [];
1020
+ for (const [id, p] of Object.entries(b.projects))
1021
+ for (const s of boundShares(doc, id, p))
1022
+ shares.push({ name: s.name, share: s.share });
1023
+ for (const c of b.constraints ?? [])
1024
+ shares.push({ name: "a session of yours that sent it a message", share: c });
1025
+ for (const { share } of shares) {
1026
+ if (share === "private")
1027
+ continue;
1028
+ circles = circles ? new Set(share.circles.filter((c) => circles.has(c))) : new Set(share.circles);
1029
+ people = people ? new Set(share.people.filter((u) => people.has(u))) : new Set(share.people);
1030
+ }
1031
+ const joined = [];
1032
+ for (const c of circles ?? [])
1033
+ if ((await app.store.getCircle(c))?.joinedByMe === true)
1034
+ joined.push(c);
1035
+ const blocks = new Set((await app.store.listBlocks()).map((x) => x.userId));
1036
+ // People only while they are still friends (an unfriend ends a share as it ends everything else).
1037
+ const friends = (people?.size ?? 0) > 0 ? await friendIds(app) : new Set();
1038
+ const ppl = [...(people ?? [])].filter((u) => !blocks.has(u) && u !== app.userId && friends.has(u));
1039
+ if (joined.length + ppl.length === 0) {
1040
+ const names = [...new Set(shares.map((x) => x.name))];
1041
+ return privateOf([{ cause: "disjoint", why: names.length > 1 ? `its projects (${names.join(", ")}) share nobody in common` : `${names[0]} shares nobody you can reach` }], names);
1042
+ }
1043
+ return { kind: "shared", circles: joined.sort(), people: ppl.sort() };
1044
+ }
1045
+ /** A private ceiling from its reasons: the first said in full, the count of the rest (`p2p session show` lists them all). */
1046
+ function privateOf(reasons, names) {
1047
+ const more = reasons.length - 1;
1048
+ const blocking = names ?? [...new Set(reasons.map((r) => r.project).filter((x) => x !== undefined))];
1049
+ return {
1050
+ kind: "private",
1051
+ why: `${reasons[0].why}${more > 0 ? ` (and ${more} more reason${more === 1 ? "" : "s"})` : ""}`,
1052
+ causes: [...new Set(reasons.map((r) => r.cause))],
1053
+ ...(blocking.length ? { blocking } : {}),
1054
+ };
1055
+ }
1056
+ /** Everyone a ceiling lets in (besides this user): members of its circles who stand in them, and its people. */
1057
+ export async function ceilingAudience(app, c) {
1058
+ if (c.kind === "none")
1059
+ return undefined;
1060
+ const out = new Set();
1061
+ if (c.kind === "private")
1062
+ return out;
1063
+ const stands = await standsLookup(app.store, app.userId);
1064
+ for (const cid of c.circles) {
1065
+ const lc = await loadCircle(app.store, cid).catch(() => undefined);
1066
+ if (!lc || !stands(app.userId, cid))
1067
+ continue;
1068
+ for (const m of lc.chain.head.members)
1069
+ if (m !== app.userId && stands(m, cid))
1070
+ out.add(m);
1071
+ }
1072
+ for (const u of c.people)
1073
+ out.add(u);
1074
+ const blocks = new Set((await app.store.listBlocks()).map((x) => x.userId));
1075
+ for (const u of [...out])
1076
+ if (blocks.has(u))
1077
+ out.delete(u);
1078
+ return out;
1079
+ }
1080
+ /** How to tell the person to share, for an error a model may read: the person's command, never a flag for the caller. */
1081
+ export function shareHint(names) {
1082
+ const what = names.length === 1 ? `the project ${names[0]}` : `each of ${names.join(", ")}`;
1083
+ return `only the person can widen this, by sharing ${what} themselves: \`p2p project share <circle or friend>\` run in it (or /peers project share in Claude Code)`;
1084
+ }
1085
+ /**
1086
+ * The exfiltration barrier: may session `sid` send to `userId`? Your own devices always; the
1087
+ * person's own session always; anyone else only within the session's project ceiling.
1088
+ */
1089
+ export async function assertMayReach(app, sid, userId, o = {}) {
1090
+ if (userId === app.userId || o.person || sid === PERSON_SESSION)
1091
+ return;
1092
+ const c = await sessionCeiling(app, sid);
1093
+ if (c.kind === "none")
1094
+ return;
1095
+ const aud = await ceilingAudience(app, c);
1096
+ if (aud?.has(userId))
1097
+ return;
1098
+ const b = await sessionBinding(app, sid);
1099
+ const names = Object.values(b?.projects ?? {}).map((p) => p.name);
1100
+ const who = o.address ?? (await app.addressOf(userId));
1101
+ const why = c.kind === "private" ? c.why : `${who} isn't in the circles or people ${names.length > 1 ? "all its projects share" : "its project shares"}`;
1102
+ const remedy = c.kind === "private" ? privateRemedy(c.causes, c.blocking?.length ? c.blocking : names) : shareHint(names);
1103
+ throw new CliError("not_shared", `session ${sid} works in ${names.join(", ") || "a project"}, and Peer2Peer won't carry anything from it to ${who}: ${why}. ${remedy.charAt(0).toUpperCase()}${remedy.slice(1)}`, {
1104
+ delivered: false,
1105
+ project: { names, policy: c.kind, ...(c.kind === "private" ? { causes: c.causes, ...(stickyPrivate(c) ? { sticky: true } : {}) } : {}) },
1106
+ });
1107
+ }
1108
+ /** Friends of this user (live friendships), for the roster's named parts. */
1109
+ export async function friendIds(app) {
1110
+ const out = new Set();
1111
+ for (const f of await liveFriendshipsV3(app.store, app.signerCtx()))
1112
+ out.add(f.inviter === app.userId ? f.invitee : f.inviter);
1113
+ return out;
1114
+ }
1115
+ export async function sessionProjectView(app, sid) {
1116
+ const b = await sessionBinding(app, sid);
1117
+ const c = await sessionCeiling(app, sid, b ?? null);
1118
+ const projects = Object.entries(b?.projects ?? {}).map(([id, p]) => ({ id, name: p.name, ...(p.repoPrivate ? { repoPrivate: true } : {}) }));
1119
+ if (c.kind === "private")
1120
+ return { projects, policy: "private", why: c.why, causes: c.causes };
1121
+ if (c.kind === "shared")
1122
+ return { projects, policy: "shared", circles: c.circles, people: c.people };
1123
+ return { projects, policy: "none" };
1124
+ }
1125
+ /**
1126
+ * `p2p session show <sid>`: read only, and the person's: their front end (the person token) or
1127
+ * their own terminal outside any agent's session. An agent's shell is refused, so no session reads
1128
+ * another's bindings (or its own: the model has the not_shared reason already).
1129
+ */
1130
+ export async function showSession(app, sid) {
1131
+ if (app.front !== true && agentContext(app.env)) {
1132
+ throw new CliError("refused", "`p2p session show` lists a session's projects and why it is private, which is for you to read: run it in your own terminal (not inside Claude Code or Codex), or type /peers session in Claude Code");
1133
+ }
1134
+ if (sid === PERSON_SESSION)
1135
+ return { sid, policy: "none", reasons: [], projects: [], constraints: 0 };
1136
+ const b = await sessionBinding(app, sid);
1137
+ const c = await sessionCeiling(app, sid, b ?? null);
1138
+ const doc = await projectsDoc(app);
1139
+ const reasons = b ? privateReasons(doc, b) : [];
1140
+ if (c.kind === "private" && reasons.length === 0)
1141
+ reasons.push({ cause: c.causes[0] ?? "disjoint", why: c.why });
1142
+ const projects = [];
1143
+ for (const [id, p] of Object.entries(b?.projects ?? {})) {
1144
+ const root = typeof p.root === "string" && p.root !== "" ? p.root : (doc.projects[id]?.root ?? "");
1145
+ const kind = root !== "" && dirProjectId(root) === id ? "dir" : "git";
1146
+ const v = await projectView(app, { id, name: p.name, kind, root, ...(doc.projects[id]?.remote ? { remote: doc.projects[id].remote } : {}), ...(p.repoPrivate ? { repoPrivate: true } : {}) }, doc);
1147
+ projects.push({ ...v, ...(p.under?.length ? { under: [...p.under] } : {}), ...(p.underOver ? { underOver: true } : {}) });
1148
+ }
1149
+ return {
1150
+ sid,
1151
+ policy: c.kind,
1152
+ reasons,
1153
+ ...(c.kind === "private" ? { remedy: privateRemedy(c.causes, c.blocking?.length ? c.blocking : projects.map((x) => x.name)) } : {}),
1154
+ ...(c.kind === "shared" ? { circles: c.circles, people: c.people } : {}),
1155
+ projects,
1156
+ constraints: b?.constraints?.length ?? 0,
1157
+ };
1158
+ }
1159
+ /**
1160
+ * The one-time notice for a user who relied on the default circle: shown once per device, the
1161
+ * first time a session of theirs is private only because its project was never shared.
1162
+ */
1163
+ export async function defaultCircleNotice(app, sid) {
1164
+ const def = app.self?.defaultCircle;
1165
+ if (!def || (await app.store.getCircle(def))?.joinedByMe !== true)
1166
+ return undefined;
1167
+ const b = await sessionBinding(app, sid);
1168
+ if (!b)
1169
+ return undefined;
1170
+ const doc = await projectsDoc(app);
1171
+ if (doc.noticeAt !== undefined)
1172
+ return undefined;
1173
+ const unmapped = Object.entries(b.projects).filter(([id, p]) => !doc.projects[id] && !p.repoPrivate);
1174
+ if (unmapped.length === 0)
1175
+ return undefined;
1176
+ const shown = await app.state.update("projects", (cur) => {
1177
+ const d = cur?.v === 1 ? cur : { v: 1, projects: {} };
1178
+ if (d.noticeAt !== undefined)
1179
+ return { result: false };
1180
+ return { next: { ...d, noticeAt: Date.now() }, result: true };
1181
+ });
1182
+ if (!shown)
1183
+ return undefined;
1184
+ const name = unmapped[0][1].name;
1185
+ return `project boundaries: sessions no longer follow your default circle (${def}). Each project is private until you share it, so this session in ${name} is seen only by your own devices. To share ${name} with that circle, run \`p2p project share ${def}\` in it (or /peers project share in Claude Code); \`p2p project ls\` lists what you shared`;
1186
+ }
1187
+ /** The text of the one-time notice starts so (the mod and the Codex bridge match it). */
1188
+ export const PROJECT_NOTICE_PREFIX = "project boundaries:";
1189
+ /** `s` without trailing slashes (a loop, not a regex: linear on any input). */
1190
+ function trimSlashes(s) {
1191
+ let n = s.length;
1192
+ while (n > 0 && s.charCodeAt(n - 1) === 47)
1193
+ n--;
1194
+ return s.slice(0, n);
1195
+ }
1196
+ /** What `p2p doctor` and `p2p project show` print for a local target. */
1197
+ export const GRAPH_LOCAL_ONLY = "local only";
1198
+ /** Ix's own default backend (ix-cli config.ts DEFAULT_ENDPOINT): `ix docker` runs it on this machine. */
1199
+ export const DEFAULT_IX_ENDPOINT = "http://localhost:8090";
1200
+ /**
1201
+ * Whether `url` is an Ix backend on this machine: http(s) to localhost, 127.0.0.0/8 or ::1, with no
1202
+ * credentials, query or fragment. Anything else (a cloud URL, a LAN host, `localhost.example.com`,
1203
+ * `http://127.0.0.1@evil.example`) is not.
1204
+ */
1205
+ export function isLoopbackEndpoint(url) {
1206
+ if (typeof url !== "string" || url.length > 512 || /[\s\0]/.test(url))
1207
+ return false;
1208
+ let u;
1209
+ try {
1210
+ u = new URL(url);
1211
+ }
1212
+ catch {
1213
+ return false;
1214
+ }
1215
+ if ((u.protocol !== "http:" && u.protocol !== "https:") || u.username || u.password || u.search || u.hash)
1216
+ return false;
1217
+ const h = u.hostname.toLowerCase();
1218
+ return h === "localhost" || h === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
1219
+ }
1220
+ /** A loopback endpoint as one canonical string: `origin + pathname`, trailing slashes dropped. Undefined when it isn't one. */
1221
+ export function normalizeLoopbackEndpoint(url) {
1222
+ if (!isLoopbackEndpoint(url))
1223
+ return undefined;
1224
+ const u = new URL(url.trim());
1225
+ return trimSlashes(u.origin + u.pathname);
1226
+ }
1227
+ /**
1228
+ * The local Ix endpoint every `local` target names: `ixEndpoint` in config.json (the person's own
1229
+ * file) when it is a loopback URL, else Ix's default. Never from the environment (an agent or a
1230
+ * project config can set that), and never a non-loopback URL. On a shared machine another user can
1231
+ * listen on a loopback port first (threat model, "Graph targets").
1232
+ */
1233
+ export function localGraphEndpoint(_env, file) {
1234
+ return normalizeLoopbackEndpoint(typeof file?.ixEndpoint === "string" ? file.ixEndpoint.trim() : undefined) ?? DEFAULT_IX_ENDPOINT;
1235
+ }
1236
+ /**
1237
+ * The circles that have a shared graph, and its endpoint. None yet: the shared cloud graph (epic #41
1238
+ * piece 3) comes in a later PR, which fills this from settled, person-made state. Nothing in the
1239
+ * environment, config.json, a repository or a peer's message can add to it.
1240
+ */
1241
+ export const SHARED_GRAPHS = new Map();
1242
+ /**
1243
+ * The graph target of a set of projects (pure: graphTarget gathers the inputs). Intersection, like
1244
+ * the session ceiling: any private, repository-private or unmapped project makes it local, and so
1245
+ * does an empty set. A shared target needs every input shared with the same circle, and exactly one
1246
+ * such circle with a shared graph (an https endpoint); people-only shares, no common circle, or a
1247
+ * choice of several circles all stay local.
1248
+ */
1249
+ export function graphTargetOf(inputs, o) {
1250
+ const local = (why) => ({ kind: "local", endpoint: o.local, why });
1251
+ if (inputs.length === 0)
1252
+ return local("no project: nothing is shared");
1253
+ let circles;
1254
+ for (const i of inputs) {
1255
+ if (i.repoPrivate)
1256
+ return local(`${i.name} asks to stay private (${PRIVATE_MARKER})`);
1257
+ if (i.share === "private" || typeof i.share !== "object")
1258
+ return local(`${i.name} is private`);
1259
+ const cs = Array.isArray(i.share.circles) ? i.share.circles.filter((c) => typeof c === "string") : [];
1260
+ circles = circles ? new Set(cs.filter((c) => circles.has(c))) : new Set(cs);
1261
+ }
1262
+ if (!circles || circles.size === 0)
1263
+ return local(inputs.length > 1 ? "its projects share no circle in common" : `${inputs[0].name} isn't shared with a circle`);
1264
+ const graphs = o.sharedGraphs ?? SHARED_GRAPHS;
1265
+ const withGraph = [...circles].filter((c) => {
1266
+ const ep = graphs.get(c);
1267
+ return normalizeSharedEndpoint(ep) !== undefined;
1268
+ });
1269
+ if (withGraph.length === 0)
1270
+ return local("no shared graph for its circle yet: Ix stays on this machine");
1271
+ if (withGraph.length > 1)
1272
+ return local("it is shared with more than one circle that has a shared graph: Ix stays on this machine");
1273
+ return { kind: "shared", circle: withGraph[0], endpoint: normalizeSharedEndpoint(graphs.get(withGraph[0])) };
1274
+ }
1275
+ /** A shared graph's endpoint as `origin + pathname` (https, off this machine, no credentials, query or fragment), else undefined. */
1276
+ export function normalizeSharedEndpoint(url) {
1277
+ if (typeof url !== "string" || url.length > 512 || /[\s\0]/.test(url))
1278
+ return undefined;
1279
+ let u;
1280
+ try {
1281
+ u = new URL(url);
1282
+ }
1283
+ catch {
1284
+ return undefined;
1285
+ }
1286
+ if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || isLoopbackEndpoint(url))
1287
+ return undefined;
1288
+ return trimSlashes(u.origin + u.pathname);
1289
+ }
1290
+ /**
1291
+ * The chokepoint for every Ix call Peer2Peer makes or lets an extension make (ext-ix takes its
1292
+ * endpoint only from here, ExtContext.graphTarget): the graph a session, the folders it works in,
1293
+ * or both may reach. A session bound to a private project, or one whose ceiling is private for any
1294
+ * reason (an unregistered agent session, too many projects, a private session's message), is local.
1295
+ * The folders' own projects are intersected in, so a session can't name a shared sibling to widen
1296
+ * a private repository it works in. The process's own cwd and every path the call names (`paths`:
1297
+ * its targets, `--path`, `--changed`, the child's cwd) are intersected in as well. A named session
1298
+ * that isn't bound yet is local, and a `shared` result needs a session a front end registered (its
1299
+ * person token). Read only: binds nothing.
1300
+ */
1301
+ export async function graphTarget(app, o = {}, sharedGraphs = SHARED_GRAPHS) {
1302
+ const lo = localGraphEndpoint(app.env, app.file);
1303
+ const local = (why) => ({ kind: "local", endpoint: lo, why });
1304
+ if (o.over)
1305
+ return local(`it works in more than ${MAX_SESSION_DIRS} folders`);
1306
+ // The paths a call names (its targets, --path, --changed, the child's cwd): absolute only, capped.
1307
+ const paths = o.paths ?? [];
1308
+ if (paths.length > MAX_GRAPH_PATHS)
1309
+ return local(`a call named more than ${MAX_GRAPH_PATHS} paths`);
1310
+ if (paths.some((p) => typeof p !== "string" || !isAbsolute(p)))
1311
+ return local("a call named a path that isn't absolute");
1312
+ const doc = await projectsDoc(app);
1313
+ const inputs = [];
1314
+ let registered = false;
1315
+ if (o.sid !== undefined && o.sid !== PERSON_SESSION) {
1316
+ const b = await sessionBinding(app, o.sid);
1317
+ registered = b?.registered === true;
1318
+ const c = await sessionCeiling(app, o.sid, b ?? null);
1319
+ if (c.kind === "private")
1320
+ return local(`session ${o.sid} is private: ${c.why}`);
1321
+ // A session no front end has bound yet has no ceiling to intersect: fail closed.
1322
+ if (c.kind === "none")
1323
+ return local(`session ${o.sid} isn't bound to a project yet`);
1324
+ if (c.kind === "shared")
1325
+ inputs.push({ name: `session ${o.sid}`, share: { circles: c.circles, people: c.people } });
1326
+ }
1327
+ const seen = new Set();
1328
+ // The process's real cwd always counts too: P2P_WORKDIR replaces it for display, never for the boundary.
1329
+ for (const d of [...(o.dirs ?? []), process.cwd(), ...paths]) {
1330
+ if (typeof d !== "string" || d.trim() === "")
1331
+ continue;
1332
+ const r = projectOf(d);
1333
+ if (seen.has(r.id))
1334
+ continue;
1335
+ seen.add(r.id);
1336
+ if (seen.size > MAX_SESSION_PROJECTS)
1337
+ return local(`it works in more than ${MAX_SESSION_PROJECTS} projects`);
1338
+ inputs.push({ name: r.name, share: shareOf(doc, r.id), ...(r.repoPrivate ? { repoPrivate: true } : {}) });
1339
+ }
1340
+ const t = graphTargetOf(inputs, { local: lo, sharedGraphs });
1341
+ // A shared graph only for a session a front end of this user registered (its token), never a bare call.
1342
+ if (t.kind === "shared" && !registered)
1343
+ return local(o.sid ? `session ${o.sid} isn't registered by a front end of yours` : "no session: only a session your front end registered may reach a shared graph");
1344
+ return t;
1345
+ }
1346
+ /** At most this many paths one Ix call may name for its graph target; past it, local. */
1347
+ export const MAX_GRAPH_PATHS = 64;
1348
+ /** One project's graph target (`p2p project show`, `p2p doctor`). */
1349
+ export function projectGraphTarget(app, ref, doc) {
1350
+ const lo = localGraphEndpoint(app.env, app.file);
1351
+ return graphTargetOf([{ name: ref.name, share: shareOf(doc, ref.id), ...(ref.repoPrivate ? { repoPrivate: true } : {}) }], { local: lo });
1352
+ }
1353
+ /** How a target reads in one line: `local only (http://localhost:8090)`, or the circle's shared graph. */
1354
+ export function describeGraphTarget(t) {
1355
+ return t.kind === "local" ? `${GRAPH_LOCAL_ONLY} (${t.endpoint})` : `the shared graph of circle ${t.circle} (${t.endpoint})`;
1356
+ }
1357
+ /**
1358
+ * The Ix variables that could send an `ix` call somewhere other than its graph target, or carry a
1359
+ * cloud credential: Ix Pro's PAT mode (IX_PAT, IX_ORG, its endpoint override), the cloud push and
1360
+ * ingestion knobs, the OAuth secret, auto-map routing to the cloud. Every IX_* variable outside
1361
+ * IX_KEEP is dropped as well; these are named so tests and docs can point at them.
1362
+ */
1363
+ export const IX_CLOUD_ENV = ["IX_ENDPOINT", "IX_PAT", "IX_ORG", "IX_ORG_ID", "IX_PUSH_ENDPOINT", "IX_PUSH_TOKEN", "IX_OAUTH_CLIENT_SECRET", "IX_AUTO_MAP_CLOUD", "IX_AUTO_MAP", "IX_KARTR_UI_URL", "IX_VIEW_BACKEND_URL", "IX_VIEW_BACKEND_TOKEN"];
1364
+ /** IX_* variables an `ix` call keeps: which binary (read by ext-ix, not ix), where Ix keeps its local state, and the local backend's token (Ix sends it to a loopback endpoint only). */
1365
+ export const IX_KEEP = ["IX_BIN", "IX_HOME", "IX_TOKEN"];
1366
+ /**
1367
+ * The environment an extension gets (ExtContext.env), with the target pinned: every IX_* variable
1368
+ * outside IX_KEEP set to undefined (so a `{...process.env, ...ctx.env}` merge drops it too: an older
1369
+ * ext-ix spreads it), IX_ENDPOINT set to the target's endpoint, and readers kept from starting a
1370
+ * background `ix map` (Ix Pro routes a map to the cloud when an org session is active, whatever
1371
+ * IX_ENDPOINT says). Defence in depth: ext-ix builds its own allowlisted env from the target.
1372
+ */
1373
+ export function graphPinnedEnv(env, target, base = process.env) {
1374
+ const out = { ...env };
1375
+ const keep = new Set(IX_KEEP);
1376
+ for (const k of new Set([...Object.keys(base), ...Object.keys(env)]))
1377
+ if (/^IX_/i.test(k) && !keep.has(k.toUpperCase()))
1378
+ out[k] = undefined;
1379
+ out.IX_ENDPOINT = target.endpoint;
1380
+ out.IX_MAP_BACKGROUND_REFRESH = "0";
1381
+ out.IX_NO_UPDATE_CHECK = "1";
1382
+ return out;
1383
+ }