@peer2peer/cli 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +21 -15
- package/dist/app.d.ts +83 -0
- package/dist/app.js +155 -40
- package/dist/cli.d.ts +76 -6
- package/dist/cli.js +386 -34
- package/dist/config.d.ts +52 -0
- package/dist/config.js +51 -0
- package/dist/doctor.d.ts +84 -1
- package/dist/doctor.js +198 -6
- package/dist/ext-host.d.ts +6 -0
- package/dist/ext-host.js +41 -3
- package/dist/extensions.d.ts +101 -0
- package/dist/extensions.js +13 -2
- package/dist/graph-memory.d.ts +107 -0
- package/dist/graph-memory.js +393 -0
- package/dist/history.d.ts +155 -0
- package/dist/history.js +697 -0
- package/dist/identity.d.ts +31 -2
- package/dist/identity.js +80 -10
- package/dist/inbound.js +4 -1
- package/dist/ix-local.d.ts +128 -0
- package/dist/ix-local.js +260 -0
- package/dist/pretty.d.ts +3 -1
- package/dist/pretty.js +9 -2
- package/dist/projects.d.ts +330 -12
- package/dist/projects.js +1044 -74
- package/dist/receipts.js +3 -1
- package/dist/rotation.js +15 -7
- package/dist/sessions.d.ts +28 -5
- package/dist/sessions.js +182 -30
- package/dist/social.js +11 -0
- package/dist/state.d.ts +26 -0
- package/dist/state.js +3 -0
- package/dist/tui/model.d.ts +7 -1
- package/dist/tui/model.js +8 -4
- package/dist/tui/tui.d.ts +9 -2
- package/dist/tui/tui.js +47 -6
- package/dist/tui/view.js +6 -4
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/watch.js +6 -0
- package/package.json +6 -3
package/dist/projects.js
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
//
|
|
5
5
|
// - A project is a git repository, keyed by its normalised remote URL (if any) and its git
|
|
6
6
|
// common dir, so every worktree and subfolder of one clone is the same project. Outside git,
|
|
7
|
-
// the real path of the folder
|
|
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.
|
|
8
10
|
// - Its policy lives only in this user's state (`<home>/cli/projects`): shared with circles and
|
|
9
11
|
// named people, or private. A project with no policy is private: only this user's own devices
|
|
10
12
|
// see its sessions. Nothing in a repository can widen that; a committed `.p2p-private` file at
|
|
@@ -20,8 +22,9 @@
|
|
|
20
22
|
// session: never bound, no ceiling.
|
|
21
23
|
import { agentAncestor, isAgentProcess } from "./ancestry.js";
|
|
22
24
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
23
|
-
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
24
|
-
import {
|
|
25
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { homedir, tmpdir } from "node:os";
|
|
27
|
+
import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
25
28
|
import { circlePolicy, liveFriendshipsV3, loadCircle, sanitizePeerText, standsLookup } from "@peer2peer/core/v3";
|
|
26
29
|
import { CliError } from "./errors.js";
|
|
27
30
|
/** The person's own terminal session (`p2p tui`, `p2p send` with no --from-session). */
|
|
@@ -54,19 +57,39 @@ export function sessionWorkdir(env) {
|
|
|
54
57
|
export function sessionDirs(env) {
|
|
55
58
|
const extra = (env.P2P_PROJECT_DIRS ?? "").split(delimiter).filter((x) => x.trim() !== "" && isAbsolute(x.trim()));
|
|
56
59
|
// Past the cap (or when the front end says it dropped some): private, never "the first N".
|
|
57
|
-
const
|
|
58
|
-
|
|
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];
|
|
59
74
|
}
|
|
60
75
|
/** At most this many folders a front end passes per call; past it the session is private. */
|
|
61
76
|
export const MAX_SESSION_DIRS = 512;
|
|
62
|
-
/**
|
|
63
|
-
|
|
77
|
+
/**
|
|
78
|
+
* At most this many projects per session; past it the session is private. A storage bound only:
|
|
79
|
+
* a session's ceiling is the intersection of all its projects' policies, so a higher cap never
|
|
80
|
+
* lets a session reach anyone a smaller one wouldn't.
|
|
81
|
+
*/
|
|
82
|
+
export const MAX_SESSION_PROJECTS = 64;
|
|
64
83
|
/** Bindings of sessions not seen for this long are dropped. */
|
|
65
84
|
export const SESSION_BINDING_TTL_MS = 30 * 24 * 3600 * 1000;
|
|
66
85
|
/** At most this many circles and people in one project's policy. */
|
|
67
86
|
export const MAX_PROJECT_SHARES = 32;
|
|
68
87
|
/** At most this many constraints a session keeps; past it, private. */
|
|
69
88
|
export const MAX_SESSION_CONSTRAINTS = 16;
|
|
89
|
+
/** At most this many covered subfolders a bound folder project remembers; past it, every policy below it counts. */
|
|
90
|
+
export const MAX_UNDER = 64;
|
|
91
|
+
/** Causes no share can lift: the session stays private until it ends. */
|
|
92
|
+
const STICKY = new Set(["projects", "folders", "unresolved", "front", "constraints", "legacy-over", "repo-private", "sent-private"]);
|
|
70
93
|
// ---------------------------------------------------------------------------
|
|
71
94
|
// Project identity
|
|
72
95
|
const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex");
|
|
@@ -84,9 +107,43 @@ function real(p) {
|
|
|
84
107
|
}
|
|
85
108
|
}
|
|
86
109
|
}
|
|
87
|
-
/**
|
|
110
|
+
/** Whether a path, as written, has a `..` segment (`a/../b`, `..`, `a/..`). */
|
|
111
|
+
export function hasDotDot(p) {
|
|
112
|
+
return p.split(/[\\/]/).includes("..");
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* `p` as the file system walks it (POSIX): each existing prefix is resolved through its symlinks
|
|
116
|
+
* before the next segment applies, so `link/../x` is the link's target's parent's `x`, never the
|
|
117
|
+
* `x` beside the link (path.resolve collapses `..` as text). Past the first segment that doesn't
|
|
118
|
+
* exist, the rest is applied as text. Relative paths start at the process's cwd. On Windows,
|
|
119
|
+
* path.resolve.
|
|
120
|
+
*/
|
|
121
|
+
export function physicalPath(p) {
|
|
122
|
+
const abs = isAbsolute(p) ? p : `${process.cwd()}${sep}${p}`;
|
|
123
|
+
if (process.platform === "win32")
|
|
124
|
+
return resolve(abs);
|
|
125
|
+
let cur = "/";
|
|
126
|
+
for (const c of abs.split("/")) {
|
|
127
|
+
if (c === "" || c === ".")
|
|
128
|
+
continue;
|
|
129
|
+
if (c === "..") {
|
|
130
|
+
cur = dirname(cur);
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
const next = cur === "/" ? `/${c}` : `${cur}/${c}`;
|
|
134
|
+
try {
|
|
135
|
+
lstatSync(next);
|
|
136
|
+
cur = real(next);
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
cur = next;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return cur;
|
|
143
|
+
}
|
|
144
|
+
/** The nearest existing directory at or above `p` (walked as the file system does: physicalPath), as a real path. */
|
|
88
145
|
function existingDir(p) {
|
|
89
|
-
let cur =
|
|
146
|
+
let cur = physicalPath(p);
|
|
90
147
|
for (let i = 0; i < 4096; i++) {
|
|
91
148
|
try {
|
|
92
149
|
const st = statSync(cur);
|
|
@@ -101,6 +158,87 @@ function existingDir(p) {
|
|
|
101
158
|
}
|
|
102
159
|
return cur;
|
|
103
160
|
}
|
|
161
|
+
/** Device and pseudo-file roots: what is under them is never a project (POSIX). */
|
|
162
|
+
const PSEUDO_ROOTS = ["/dev", "/proc", "/sys"];
|
|
163
|
+
/**
|
|
164
|
+
* Whether `p` is a device or pseudo file (`/dev/null`, `/dev/tty`, `/proc/self/status`), never a
|
|
165
|
+
* project: it exists, isn't a folder, and its real path stays under /dev (and isn't a regular
|
|
166
|
+
* file there, like one in /dev/shm), /proc or /sys. A path through /proc to a real file
|
|
167
|
+
* (`/proc/self/cwd/x`, `/proc/<pid>/root/…`) resolves out of it and binds as usual; one that
|
|
168
|
+
* doesn't exist binds its nearest existing parent as every path does.
|
|
169
|
+
*/
|
|
170
|
+
export function pseudoPath(p) {
|
|
171
|
+
if (process.platform === "win32" || typeof p !== "string" || !isAbsolute(p))
|
|
172
|
+
return false;
|
|
173
|
+
// Named there, too: a link elsewhere (a repository's file that points at /dev/null) binds as its folder.
|
|
174
|
+
const at = resolve(p);
|
|
175
|
+
if (!PSEUDO_ROOTS.some((root) => at === root || at.startsWith(`${root}/`)))
|
|
176
|
+
return false;
|
|
177
|
+
let st;
|
|
178
|
+
try {
|
|
179
|
+
st = statSync(p);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
if (st.isDirectory())
|
|
185
|
+
return false;
|
|
186
|
+
const r = real(p);
|
|
187
|
+
const under = (root) => r === root || r.startsWith(`${root}/`);
|
|
188
|
+
if (under("/dev"))
|
|
189
|
+
return !st.isFile();
|
|
190
|
+
return PSEUDO_ROOTS.slice(1).some(under);
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Whether a path component holds a brace expansion with a choice: a `{`, then `,` or `..` with no
|
|
194
|
+
* brace between, then `}` (`{.git,x}`, `{a..z}`). One pass, so it stays linear on any input.
|
|
195
|
+
*/
|
|
196
|
+
export function braceChoice(c) {
|
|
197
|
+
let open = false;
|
|
198
|
+
let choice = false;
|
|
199
|
+
for (let i = 0; i < c.length; i++) {
|
|
200
|
+
const ch = c[i];
|
|
201
|
+
if (ch === "{") {
|
|
202
|
+
open = true;
|
|
203
|
+
choice = false;
|
|
204
|
+
}
|
|
205
|
+
else if (ch === "}") {
|
|
206
|
+
if (open && choice)
|
|
207
|
+
return true;
|
|
208
|
+
open = false;
|
|
209
|
+
}
|
|
210
|
+
else if (open && (ch === "," || (ch === "." && c[i + 1] === ".")))
|
|
211
|
+
choice = true;
|
|
212
|
+
}
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The folder holding the first path component that names a repository's marker (`.git`,
|
|
217
|
+
* PRIVATE_MARKER) or could match one (a glob or brace pattern a dotfile can match: `.g*`,
|
|
218
|
+
* `[.]git`, `{.git,x}`): a command naming it may remove it, so a shared folder above never
|
|
219
|
+
* covers that folder (projectOf). Lexical, on the path as given.
|
|
220
|
+
*/
|
|
221
|
+
function namedStop(p) {
|
|
222
|
+
const parts = p.split(/[\\/]/);
|
|
223
|
+
for (let i = 1; i < parts.length; i++) {
|
|
224
|
+
const c = parts[i];
|
|
225
|
+
const glob = ((c.startsWith(".") || c.startsWith("[")) && /[*?[]/.test(c)) || braceChoice(c);
|
|
226
|
+
if (c === ".git" || c === PRIVATE_MARKER || glob)
|
|
227
|
+
return parts.slice(0, i).join(sep) || sep;
|
|
228
|
+
}
|
|
229
|
+
return undefined;
|
|
230
|
+
}
|
|
231
|
+
/** Whether `p` is `dir` or below it (real paths, this platform's separator). */
|
|
232
|
+
function within(p, dir) {
|
|
233
|
+
if (p === dir)
|
|
234
|
+
return true;
|
|
235
|
+
const d = dir.endsWith(sep) ? dir : `${dir}${sep}`;
|
|
236
|
+
return p.startsWith(d);
|
|
237
|
+
}
|
|
238
|
+
/** A folder project's id: its real path, hashed. */
|
|
239
|
+
export function dirProjectId(root) {
|
|
240
|
+
return `pj_${sha(`dir\n${root}`).slice(0, 24)}`;
|
|
241
|
+
}
|
|
104
242
|
/**
|
|
105
243
|
* A remote URL as one canonical string: scheme, credentials, port-less ssh form, trailing `.git`
|
|
106
244
|
* and slashes dropped, host lower-cased. `https://u:t@GitHub.com/a/b.git` and `git@github.com:a/b`
|
|
@@ -170,27 +308,98 @@ function readSmall(file) {
|
|
|
170
308
|
return undefined;
|
|
171
309
|
}
|
|
172
310
|
}
|
|
311
|
+
/**
|
|
312
|
+
* Whether `d` is a bare git repository: `HEAD`, `objects/` and `refs/` in it, or a `config` that
|
|
313
|
+
* says `bare = true` (a folder named `.git` is a working tree's, found from its parent instead).
|
|
314
|
+
*/
|
|
315
|
+
function isBareRepo(d) {
|
|
316
|
+
if (basename(d) === ".git")
|
|
317
|
+
return false;
|
|
318
|
+
const st = (p) => {
|
|
319
|
+
try {
|
|
320
|
+
return statSync(p);
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
return undefined;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
if (st(join(d, "HEAD"))?.isFile() && st(join(d, "objects"))?.isDirectory() && st(join(d, "refs"))?.isDirectory())
|
|
327
|
+
return true;
|
|
328
|
+
return /^\s*bare\s*=\s*true\s*$/im.test(readSmall(join(d, "config")) ?? "");
|
|
329
|
+
}
|
|
330
|
+
/** The git project whose git dir is `gitDir`, found at the folder `root`. */
|
|
331
|
+
function gitRef(gitDir, root) {
|
|
332
|
+
let common = gitDir;
|
|
333
|
+
const cd = readSmall(join(gitDir, "commondir"))?.trim();
|
|
334
|
+
if (cd)
|
|
335
|
+
common = resolve(gitDir, cd);
|
|
336
|
+
common = real(common);
|
|
337
|
+
const urls = remotesOf(readSmall(join(common, "config")) ?? "");
|
|
338
|
+
const remote = urls.map(normalizeRemote).find((x) => x !== undefined);
|
|
339
|
+
const main = basename(common) === ".git" ? dirname(common) : common;
|
|
340
|
+
const name = clean(remote ? (remote.split("/").pop() ?? "") : basename(main)) || clean(basename(root)) || "project";
|
|
341
|
+
return {
|
|
342
|
+
id: `pj_${sha(`git\n${remote ?? ""}\n${common}`).slice(0, 24)}`,
|
|
343
|
+
name,
|
|
344
|
+
kind: "git",
|
|
345
|
+
root,
|
|
346
|
+
...(remote ? { remote } : {}),
|
|
347
|
+
...(existsSync(join(root, PRIVATE_MARKER)) ? { repoPrivate: true } : {}),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
/** Whether `p` names something that is there, its trailing pattern parts (`*.log`, `{a,b}`) left out. */
|
|
351
|
+
function present(p) {
|
|
352
|
+
let q = resolve(p);
|
|
353
|
+
while (/[*?[\]{}]/.test(basename(q)) && dirname(q) !== q)
|
|
354
|
+
q = dirname(q);
|
|
355
|
+
try {
|
|
356
|
+
statSync(q);
|
|
357
|
+
return true;
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
return false;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
173
363
|
/**
|
|
174
364
|
* The project `dir` belongs to, read from the files alone (git is never run: no hook, fsmonitor
|
|
175
365
|
* or config of the repository's can execute). A `.git` directory or `gitdir:` file up the tree
|
|
176
366
|
* marks a working tree; its common dir (`commondir` for a linked worktree) identifies the clone.
|
|
367
|
+
* A bare repository (isBareRepo) is a git project too, and a `.git` that can't be read as one is
|
|
368
|
+
* a folder project of its own.
|
|
369
|
+
*
|
|
370
|
+
* Outside git, a folder project. With `doc` (the policies), the nearest folder at or above `dir`
|
|
371
|
+
* that has a policy of its own is the project when that is `dir`'s own folder, or when its share
|
|
372
|
+
* covers subfolders (`covers`, given with `p2p project share --subfolders`; a policy without it
|
|
373
|
+
* is for that folder alone, as before). The walk stops at the first folder with a policy (the
|
|
374
|
+
* nearest one wins, so a private subfolder stays private; one that doesn't cover leaves `dir`'s
|
|
375
|
+
* own folder as the project), and it never crosses:
|
|
376
|
+
* - a git repository (found first: a nested repository is always its own project);
|
|
377
|
+
* - a `.p2p-private` (at or above `dir`: the folder project is private, whatever covers it);
|
|
378
|
+
* - a folder whose `.git` or `.p2p-private` the path itself names (namedStop: a command that may
|
|
379
|
+
* have just removed it);
|
|
380
|
+
* - the nearest existing folder, when `dir` itself isn't there (deleted or moved since the
|
|
381
|
+
* session named it, or not made yet): that folder is the project unless it has a policy, so a
|
|
382
|
+
* repository removed after a session read it is never covered from above.
|
|
383
|
+
* Without `doc` (sharing, `project show`): the folder itself.
|
|
177
384
|
*/
|
|
178
|
-
export function projectOf(dir) {
|
|
179
|
-
|
|
385
|
+
export function projectOf(dir, doc) {
|
|
386
|
+
// As the file system walks it: `link/../x` is beside the link's target, not beside the link.
|
|
387
|
+
const given = physicalPath(dir);
|
|
388
|
+
const start = existingDir(given);
|
|
180
389
|
let cur = start;
|
|
181
390
|
for (let i = 0; i < 4096; i++) {
|
|
182
391
|
const dotgit = join(cur, ".git");
|
|
183
392
|
// Anything named .git here (a folder, a file, a symlink, even a broken or unreadable one) ends
|
|
184
393
|
// the walk: this folder is its own project, never the parent repository's.
|
|
185
|
-
let
|
|
394
|
+
let isThere;
|
|
186
395
|
try {
|
|
187
396
|
lstatSync(dotgit);
|
|
188
|
-
|
|
397
|
+
isThere = true;
|
|
189
398
|
}
|
|
190
399
|
catch {
|
|
191
|
-
|
|
400
|
+
isThere = false;
|
|
192
401
|
}
|
|
193
|
-
if (
|
|
402
|
+
if (isThere) {
|
|
194
403
|
let st;
|
|
195
404
|
try {
|
|
196
405
|
st = statSync(dotgit);
|
|
@@ -208,34 +417,51 @@ export function projectOf(dir) {
|
|
|
208
417
|
}
|
|
209
418
|
if (!gitDir || !existsSync(gitDir)) {
|
|
210
419
|
// A .git that can't be read as one: a folder project at this level (private until shared).
|
|
211
|
-
return { id:
|
|
212
|
-
}
|
|
213
|
-
{
|
|
214
|
-
let common = gitDir;
|
|
215
|
-
const cd = readSmall(join(gitDir, "commondir"))?.trim();
|
|
216
|
-
if (cd)
|
|
217
|
-
common = resolve(gitDir, cd);
|
|
218
|
-
common = real(common);
|
|
219
|
-
const urls = remotesOf(readSmall(join(common, "config")) ?? "");
|
|
220
|
-
const remote = urls.map(normalizeRemote).find((x) => x !== undefined);
|
|
221
|
-
const main = basename(common) === ".git" ? dirname(common) : common;
|
|
222
|
-
const name = clean(remote ? (remote.split("/").pop() ?? "") : basename(main)) || clean(basename(cur)) || "project";
|
|
223
|
-
return {
|
|
224
|
-
id: `pj_${sha(`git\n${remote ?? ""}\n${common}`).slice(0, 24)}`,
|
|
225
|
-
name,
|
|
226
|
-
kind: "git",
|
|
227
|
-
root: cur,
|
|
228
|
-
...(remote ? { remote } : {}),
|
|
229
|
-
...(existsSync(join(cur, PRIVATE_MARKER)) ? { repoPrivate: true } : {}),
|
|
230
|
-
};
|
|
420
|
+
return { id: dirProjectId(cur), name: clean(basename(cur)) || "folder", kind: "dir", root: cur, brokenGit: true };
|
|
231
421
|
}
|
|
422
|
+
return gitRef(gitDir, cur);
|
|
232
423
|
}
|
|
424
|
+
// A bare repository (a clone with no working tree): a git project, never a shared folder's.
|
|
425
|
+
if (isBareRepo(cur))
|
|
426
|
+
return gitRef(cur, cur);
|
|
233
427
|
const up = dirname(cur);
|
|
234
428
|
if (up === cur)
|
|
235
429
|
break;
|
|
236
430
|
cur = up;
|
|
237
431
|
}
|
|
238
|
-
|
|
432
|
+
const dirRef = (root, repoPrivate) => ({ id: dirProjectId(root), name: clean(basename(root)) || "folder", kind: "dir", root, ...(repoPrivate ? { repoPrivate: true } : {}) });
|
|
433
|
+
// A .p2p-private at or above the folder (no repository in between, or the walk above found it):
|
|
434
|
+
// the folder is private, whatever a policy above says.
|
|
435
|
+
let marked = false;
|
|
436
|
+
for (let c = start, i = 0; i < 4096; i++) {
|
|
437
|
+
if (existsSync(join(c, PRIVATE_MARKER))) {
|
|
438
|
+
marked = true;
|
|
439
|
+
break;
|
|
440
|
+
}
|
|
441
|
+
const up = dirname(c);
|
|
442
|
+
if (up === c)
|
|
443
|
+
break;
|
|
444
|
+
c = up;
|
|
445
|
+
}
|
|
446
|
+
if (!doc || marked)
|
|
447
|
+
return dirRef(start, marked);
|
|
448
|
+
// The walk stops at a folder the path names a marker in (it may be gone now: never covered from
|
|
449
|
+
// above), and at `start` itself when the path isn't there (only its nearest parent is).
|
|
450
|
+
const named = namedStop(given);
|
|
451
|
+
const ns = named === undefined ? undefined : existingDir(named);
|
|
452
|
+
const stop = !present(given) ? start : ns === undefined ? undefined : within(start, ns) ? ns : start;
|
|
453
|
+
for (let c = start, i = 0; i < 4096; i++) {
|
|
454
|
+
const rec = doc.projects[dirProjectId(c)];
|
|
455
|
+
if (rec)
|
|
456
|
+
return c === start || rec.covers === true ? dirRef(c, false) : dirRef(start, false);
|
|
457
|
+
if (c === stop)
|
|
458
|
+
break;
|
|
459
|
+
const up = dirname(c);
|
|
460
|
+
if (up === c)
|
|
461
|
+
break;
|
|
462
|
+
c = up;
|
|
463
|
+
}
|
|
464
|
+
return dirRef(start, false);
|
|
239
465
|
}
|
|
240
466
|
const clean = (s) => sanitizePeerText(s, 64).replace(/[^\w.@+-]/g, "").slice(0, 64);
|
|
241
467
|
// ---------------------------------------------------------------------------
|
|
@@ -280,8 +506,110 @@ export async function projectView(app, ref, doc) {
|
|
|
280
506
|
people,
|
|
281
507
|
...(why ? { why } : {}),
|
|
282
508
|
...(ref.repoPrivate ? { repoPrivate: true } : {}),
|
|
509
|
+
...(d.projects[ref.id]?.covers === true && ref.kind === "dir" ? { covers: true } : {}),
|
|
510
|
+
graph: projectGraphTarget(app, ref, d),
|
|
283
511
|
};
|
|
284
512
|
}
|
|
513
|
+
/**
|
|
514
|
+
* Why `root` may not cover its subfolders (a share for it alone is still allowed), or undefined:
|
|
515
|
+
* the file system's root, a home folder or a folder above one (`$HOME`, `/Users`, `/home/<u>`),
|
|
516
|
+
* the temporary folders (`/tmp`, `/private/tmp`, `/var/folders/…`, os.tmpdir() and above it), and
|
|
517
|
+
* the system's top folders. Everything below them would be one project.
|
|
518
|
+
*/
|
|
519
|
+
export function broadRoot(root, env = {}) {
|
|
520
|
+
const norm = (p) => {
|
|
521
|
+
const r = resolve(p);
|
|
522
|
+
return process.platform === "win32" ? r.toLowerCase() : r;
|
|
523
|
+
};
|
|
524
|
+
const forms = (p) => [...new Set([norm(p), norm(real(p))])];
|
|
525
|
+
const at = forms(root);
|
|
526
|
+
const isOrAbove = (dir) => !!dir && isAbsolute(dir) && forms(dir).some((d) => at.some((r) => within(d, r)));
|
|
527
|
+
if (at.some((r) => dirname(r) === r))
|
|
528
|
+
return "the file system's root";
|
|
529
|
+
const homes = [homedir(), env.HOME, env.USERPROFILE].filter((x) => typeof x === "string" && x !== "");
|
|
530
|
+
if (homes.some(isOrAbove))
|
|
531
|
+
return "a home folder (or a folder that holds one)";
|
|
532
|
+
if (isOrAbove(tmpdir()) || isOrAbove(env.TMPDIR))
|
|
533
|
+
return "the temporary folder (or a folder that holds it)";
|
|
534
|
+
for (const r of at) {
|
|
535
|
+
const parts = r.split(/[\\/]+/).filter(Boolean);
|
|
536
|
+
const top = (parts[0] ?? "").toLowerCase();
|
|
537
|
+
if (!/^[a-z]:$/i.test(top) && parts.length === 1)
|
|
538
|
+
return "a top-level system folder";
|
|
539
|
+
if (/^[a-z]:$/i.test(parts[0] ?? "") && parts.length <= 2 && (parts.length === 1 || (parts[1] ?? "").toLowerCase() === "users"))
|
|
540
|
+
return "a drive's root or its Users folder";
|
|
541
|
+
if (/^[a-z]:$/i.test(parts[0] ?? "") && parts.length === 3 && (parts[1] ?? "").toLowerCase() === "users")
|
|
542
|
+
return "a home folder";
|
|
543
|
+
if (["home", "users"].includes(top) && parts.length <= 2)
|
|
544
|
+
return "a home folder (or the folder that holds them)";
|
|
545
|
+
if (top === "tmp" && parts.length === 1)
|
|
546
|
+
return "the temporary folder";
|
|
547
|
+
if (top === "private" && parts.length <= 2)
|
|
548
|
+
return "a system folder";
|
|
549
|
+
if (top === "private" && (parts[1] === "tmp" || parts[1] === "var") && parts.length === 2)
|
|
550
|
+
return "the temporary folder";
|
|
551
|
+
const vf = top === "var" ? 1 : top === "private" && parts[1] === "var" ? 2 : -1;
|
|
552
|
+
if (vf > 0 && parts[vf] === "folders" && parts.length <= vf + 4)
|
|
553
|
+
return "the temporary folder (or a folder that holds it)";
|
|
554
|
+
if (vf > 0 && parts.length <= vf + 1)
|
|
555
|
+
return "a system folder";
|
|
556
|
+
if (top === "run" && parts.length <= 3)
|
|
557
|
+
return "a system folder";
|
|
558
|
+
if (["volumes", "mnt", "media"].includes(top) && parts.length <= 2)
|
|
559
|
+
return "a volume's root";
|
|
560
|
+
}
|
|
561
|
+
return undefined;
|
|
562
|
+
}
|
|
563
|
+
/** At most this deep and this many entries `nestedBoundaries` looks through below a covering share. */
|
|
564
|
+
export const NESTED_SCAN_DEPTH = 4;
|
|
565
|
+
export const NESTED_SCAN_ENTRIES = 2000;
|
|
566
|
+
/**
|
|
567
|
+
* The nested git repositories (a `.git`, or a bare repository) and `.p2p-private` folders below
|
|
568
|
+
* `root`, for the warning a covering share prints: each stays its own project, but only while its
|
|
569
|
+
* marker is there. Bounded (NESTED_SCAN_DEPTH, NESTED_SCAN_ENTRIES: `capped` past it); symlinks
|
|
570
|
+
* are never followed.
|
|
571
|
+
*/
|
|
572
|
+
export function nestedBoundaries(root) {
|
|
573
|
+
const repos = [];
|
|
574
|
+
const priv = [];
|
|
575
|
+
let seen = 0;
|
|
576
|
+
let capped = false;
|
|
577
|
+
let level = [root];
|
|
578
|
+
for (let depth = 1; depth <= NESTED_SCAN_DEPTH && level.length > 0 && !capped; depth++) {
|
|
579
|
+
const next = [];
|
|
580
|
+
for (const d of level) {
|
|
581
|
+
let entries;
|
|
582
|
+
try {
|
|
583
|
+
entries = readdirSync(d, { withFileTypes: true });
|
|
584
|
+
}
|
|
585
|
+
catch {
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
for (const e of entries) {
|
|
589
|
+
if (++seen > NESTED_SCAN_ENTRIES) {
|
|
590
|
+
capped = true;
|
|
591
|
+
break;
|
|
592
|
+
}
|
|
593
|
+
if (!e.isDirectory() || e.isSymbolicLink())
|
|
594
|
+
continue;
|
|
595
|
+
const p = join(d, e.name);
|
|
596
|
+
if (e.name === ".git")
|
|
597
|
+
continue;
|
|
598
|
+
if (existsSync(join(p, ".git")) || isBareRepo(p)) {
|
|
599
|
+
repos.push(p);
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (existsSync(join(p, PRIVATE_MARKER)))
|
|
603
|
+
priv.push(p);
|
|
604
|
+
next.push(p);
|
|
605
|
+
}
|
|
606
|
+
if (capped)
|
|
607
|
+
break;
|
|
608
|
+
}
|
|
609
|
+
level = next;
|
|
610
|
+
}
|
|
611
|
+
return { repos, private: priv, capped };
|
|
612
|
+
}
|
|
285
613
|
/**
|
|
286
614
|
* `p2p project share`: share the project at `dir` with circles you joined and friends. Replaces the
|
|
287
615
|
* project's shares with exactly these (`add` keeps the ones it has). Only ever the person's
|
|
@@ -293,9 +621,28 @@ export async function shareProject(app, dir, targets) {
|
|
|
293
621
|
if (ref.repoPrivate) {
|
|
294
622
|
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`);
|
|
295
623
|
}
|
|
624
|
+
const warnings = [];
|
|
625
|
+
// Subfolders are covered only when asked, and never below a root that holds everything.
|
|
626
|
+
let subfolders = targets.subfolders === true;
|
|
627
|
+
if (subfolders && ref.kind === "git") {
|
|
628
|
+
warnings.push(`${ref.name} is a git repository: its subfolders are part of it already (--subfolders is for folders outside git)`);
|
|
629
|
+
subfolders = false;
|
|
630
|
+
}
|
|
631
|
+
if (subfolders) {
|
|
632
|
+
const broad = broadRoot(ref.root, app.env);
|
|
633
|
+
if (broad)
|
|
634
|
+
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)`);
|
|
635
|
+
const n = nestedBoundaries(ref.root);
|
|
636
|
+
const list = (xs) => `${xs.slice(0, 10).join(", ")}${xs.length > 10 ? ` and ${xs.length - 10} more` : ""}`;
|
|
637
|
+
if (n.repos.length > 0)
|
|
638
|
+
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)}`);
|
|
639
|
+
if (n.private.length > 0)
|
|
640
|
+
warnings.push(`folders below ${ref.root} with ${PRIVATE_MARKER} stay private: ${list(n.private)}`);
|
|
641
|
+
if (n.capped)
|
|
642
|
+
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`);
|
|
643
|
+
}
|
|
296
644
|
const { resolveCircle } = await import("./circle-ops.js");
|
|
297
645
|
const circles = [];
|
|
298
|
-
const warnings = [];
|
|
299
646
|
for (const c of targets.circles ?? []) {
|
|
300
647
|
const r = await resolveCircle(app, c);
|
|
301
648
|
if (!r.record.joinedByMe)
|
|
@@ -330,7 +677,9 @@ export async function shareProject(app, dir, targets) {
|
|
|
330
677
|
const share = { circles: [...new Set([...keep.circles, ...circles])], people: [...new Set([...keep.people, ...people])] };
|
|
331
678
|
if (share.circles.length + share.people.length > MAX_PROJECT_SHARES)
|
|
332
679
|
throw new CliError("usage", `a project is shared with at most ${MAX_PROJECT_SHARES} circles and people`);
|
|
333
|
-
|
|
680
|
+
// --add keeps whether it covers its subfolders; a share made afresh covers them only when asked.
|
|
681
|
+
const covers = subfolders || (targets.add === true && targets.subfolders === undefined && d.projects[ref.id]?.covers === true);
|
|
682
|
+
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() } } };
|
|
334
683
|
return { next: next, result: next };
|
|
335
684
|
});
|
|
336
685
|
return { project: await projectView(app, ref, doc), warnings };
|
|
@@ -354,9 +703,141 @@ export async function listProjects(app) {
|
|
|
354
703
|
}
|
|
355
704
|
return out.sort((a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id));
|
|
356
705
|
}
|
|
357
|
-
/** `p2p project show`: the project at `dir
|
|
706
|
+
/** `p2p project show`: the project at `dir` (a shared folder above it covers it), its policy and why. */
|
|
358
707
|
export async function showProject(app, dir) {
|
|
359
|
-
|
|
708
|
+
const doc = await projectsDoc(app);
|
|
709
|
+
return projectView(app, projectOf(dir, doc), doc);
|
|
710
|
+
}
|
|
711
|
+
/** The variable a front end names its session's scratch in (JSON: `{sid, tmp: [..], config, job}`). */
|
|
712
|
+
export const SCRATCH_ENV = "P2P_SESSION_SCRATCH";
|
|
713
|
+
/** At most this many entries a scratch folder is scanned for symlinks; past it nothing in it is skipped (fails closed: paths there bind). */
|
|
714
|
+
export const SCRATCH_SCAN_ENTRIES = 4096;
|
|
715
|
+
const SCRATCH_SID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
|
|
716
|
+
const JOB_ID_RE = /^[A-Za-z0-9][\w.-]{7,127}$/;
|
|
717
|
+
/** `p` as a real path, when it is a folder of this user's own and not a symlink itself. */
|
|
718
|
+
function ownDir(p) {
|
|
719
|
+
if (!isAbsolute(p))
|
|
720
|
+
return undefined;
|
|
721
|
+
try {
|
|
722
|
+
const st = lstatSync(p);
|
|
723
|
+
if (!st.isDirectory() || st.isSymbolicLink())
|
|
724
|
+
return undefined;
|
|
725
|
+
const uid = process.getuid?.();
|
|
726
|
+
if (uid !== undefined && st.uid !== uid)
|
|
727
|
+
return undefined;
|
|
728
|
+
return real(p);
|
|
729
|
+
}
|
|
730
|
+
catch {
|
|
731
|
+
return undefined;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* The scratch a front end named (SCRATCH_ENV), checked: the id's shape; each folder there this
|
|
736
|
+
* user's own and not a symlink; the temporary one named as Claude Code names it (`claude-<uid>`);
|
|
737
|
+
* the job folder right in `<config>/jobs`, its name the start of the id. Anything else: none.
|
|
738
|
+
*/
|
|
739
|
+
export function sessionScratch(raw) {
|
|
740
|
+
// Not on Windows until it is verified there (no owner check, no per-user folder name).
|
|
741
|
+
if (process.platform === "win32")
|
|
742
|
+
return undefined;
|
|
743
|
+
if (typeof raw !== "string" || raw === "" || raw.length > 16 * 1024)
|
|
744
|
+
return undefined;
|
|
745
|
+
let o;
|
|
746
|
+
try {
|
|
747
|
+
const j = JSON.parse(raw);
|
|
748
|
+
if (!j || typeof j !== "object" || Array.isArray(j))
|
|
749
|
+
return undefined;
|
|
750
|
+
o = j;
|
|
751
|
+
}
|
|
752
|
+
catch {
|
|
753
|
+
return undefined;
|
|
754
|
+
}
|
|
755
|
+
const sid = o.sid;
|
|
756
|
+
if (typeof sid !== "string" || !SCRATCH_SID_RE.test(sid))
|
|
757
|
+
return undefined;
|
|
758
|
+
const path = (v) => (typeof v === "string" && v !== "" && v.length <= 4096 && !/[\0\n]/.test(v) && isAbsolute(v) ? resolve(v) : undefined);
|
|
759
|
+
const bases = new Set();
|
|
760
|
+
const jobs = new Set();
|
|
761
|
+
// Claude Code's per-user temporary folder (`claude-<uid>`; 0 where there is no uid), in each temporary root it may use.
|
|
762
|
+
const tmpName = `claude-${process.getuid?.() ?? 0}`;
|
|
763
|
+
for (const t of Array.isArray(o.tmp) ? o.tmp.slice(0, 4) : []) {
|
|
764
|
+
const at = path(t);
|
|
765
|
+
const b = at === undefined ? undefined : ownDir(join(at, tmpName));
|
|
766
|
+
if (b)
|
|
767
|
+
bases.add(b);
|
|
768
|
+
}
|
|
769
|
+
const config = path(o.config);
|
|
770
|
+
if (config !== undefined) {
|
|
771
|
+
const projects = ownDir(join(config, "projects"));
|
|
772
|
+
if (projects)
|
|
773
|
+
bases.add(projects);
|
|
774
|
+
const job = path(o.job);
|
|
775
|
+
const jobsDir = ownDir(join(config, "jobs"));
|
|
776
|
+
if (job !== undefined && jobsDir !== undefined && dirname(job) === join(config, "jobs")) {
|
|
777
|
+
const id = basename(job);
|
|
778
|
+
const r = JOB_ID_RE.test(id) && sid.startsWith(id) ? ownDir(job) : undefined;
|
|
779
|
+
if (r && dirname(r) === jobsDir)
|
|
780
|
+
jobs.add(r);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
return bases.size + jobs.size > 0 ? { sid, bases: [...bases], jobs: [...jobs] } : undefined;
|
|
784
|
+
}
|
|
785
|
+
/** The scratch folder (`<base>/<project>/<sid>`, or the job folder) the real folder `dir` is in, if any. */
|
|
786
|
+
export function scratchRoot(dir, s) {
|
|
787
|
+
for (const j of s.jobs)
|
|
788
|
+
if (within(dir, j))
|
|
789
|
+
return j;
|
|
790
|
+
for (const b of s.bases) {
|
|
791
|
+
if (dir === b || !within(dir, b))
|
|
792
|
+
continue;
|
|
793
|
+
const parts = dir.slice(b.endsWith(sep) ? b.length : b.length + 1).split(sep);
|
|
794
|
+
if (parts.length >= 2 && parts[0] !== "" && parts[1] === s.sid)
|
|
795
|
+
return join(b, parts[0], parts[1]);
|
|
796
|
+
}
|
|
797
|
+
return undefined;
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* What every symlink anywhere in a scratch folder points at: a link out of it, read through
|
|
801
|
+
* `link/…`, `link/../…` or as a file in a folder, binds its target. Undefined when that can't be
|
|
802
|
+
* told (a folder or link that can't be read, more than SCRATCH_SCAN_ENTRIES entries): then
|
|
803
|
+
* nothing in that scratch folder is skipped.
|
|
804
|
+
*/
|
|
805
|
+
function scratchLinks(root) {
|
|
806
|
+
const out = [];
|
|
807
|
+
const stack = [root];
|
|
808
|
+
let seen = 0;
|
|
809
|
+
while (stack.length > 0) {
|
|
810
|
+
const d = stack.pop();
|
|
811
|
+
let ents;
|
|
812
|
+
try {
|
|
813
|
+
ents = readdirSync(d, { withFileTypes: true });
|
|
814
|
+
}
|
|
815
|
+
catch {
|
|
816
|
+
return undefined;
|
|
817
|
+
}
|
|
818
|
+
for (const e of ents) {
|
|
819
|
+
if (++seen > SCRATCH_SCAN_ENTRIES)
|
|
820
|
+
return undefined;
|
|
821
|
+
const p = join(d, e.name);
|
|
822
|
+
if (e.isSymbolicLink()) {
|
|
823
|
+
try {
|
|
824
|
+
out.push(realpathSync(p));
|
|
825
|
+
}
|
|
826
|
+
catch {
|
|
827
|
+
// Dangling, or a loop: where it points.
|
|
828
|
+
try {
|
|
829
|
+
out.push(resolve(d, readlinkSync(p)));
|
|
830
|
+
}
|
|
831
|
+
catch {
|
|
832
|
+
return undefined;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
else if (e.isDirectory())
|
|
837
|
+
stack.push(p);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
return out;
|
|
360
841
|
}
|
|
361
842
|
// ---------------------------------------------------------------------------
|
|
362
843
|
// Sessions
|
|
@@ -372,12 +853,61 @@ export async function bindSession(app, sid, dirs, o = {}) {
|
|
|
372
853
|
return undefined;
|
|
373
854
|
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`);
|
|
374
855
|
}
|
|
856
|
+
// Folder projects follow the policies (a shared folder covers its subfolders): read once, before the lock.
|
|
857
|
+
const doc = dirs.length > 0 ? await projectsDoc(app) : undefined;
|
|
375
858
|
const refs = new Map();
|
|
859
|
+
const add = (d, r) => {
|
|
860
|
+
const one = refs.get(r.id) ?? { ref: r, under: new Set() };
|
|
861
|
+
// A folder a shared folder above covered: remembered, so a policy it gets later still narrows this session.
|
|
862
|
+
if (r.kind === "dir") {
|
|
863
|
+
const at = existingDir(d);
|
|
864
|
+
if (at !== r.root && within(at, r.root))
|
|
865
|
+
one.under.add(at);
|
|
866
|
+
}
|
|
867
|
+
refs.set(r.id, one);
|
|
868
|
+
};
|
|
869
|
+
// The session's own scratch (SessionScratch) is the session, not a project: a path in it binds
|
|
870
|
+
// nothing, unless it is a repository or `.p2p-private` (a clone made there keeps its identity),
|
|
871
|
+
// a folder the person gave a policy of its own, or a path that names a `.git` or `.p2p-private`
|
|
872
|
+
// (namedStop: a command that may remove one), or a `.git` that can't be read. A symlink in it
|
|
873
|
+
// binds what it points at. A path written with a `..` segment never gets the exemption: it binds
|
|
874
|
+
// where the file system takes it, as everywhere else.
|
|
875
|
+
const scans = new Map();
|
|
876
|
+
const scratchOf = (d, r) => {
|
|
877
|
+
const s = o.scratch;
|
|
878
|
+
if (!s || r.kind !== "dir" || r.repoPrivate || r.brokenGit || hasDotDot(d) || doc?.projects[r.id] !== undefined || namedStop(physicalPath(d)) !== undefined)
|
|
879
|
+
return undefined;
|
|
880
|
+
return scratchRoot(r.root, s);
|
|
881
|
+
};
|
|
882
|
+
// Binds what a scratch folder's symlinks point at (once per folder; one into another scratch folder
|
|
883
|
+
// of this session's has that one's bound too). False when they couldn't all be read: then a path
|
|
884
|
+
// in it binds as any folder's.
|
|
885
|
+
const scanned = (root) => {
|
|
886
|
+
if (!scans.has(root)) {
|
|
887
|
+
const links = scratchLinks(root);
|
|
888
|
+
scans.set(root, links);
|
|
889
|
+
for (const t of links ?? []) {
|
|
890
|
+
if (pseudoPath(t))
|
|
891
|
+
continue;
|
|
892
|
+
const tr = projectOf(t, doc);
|
|
893
|
+
const at = scratchOf(t, tr);
|
|
894
|
+
if (at === undefined || !scanned(at))
|
|
895
|
+
add(t, tr);
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
return scans.get(root) !== undefined;
|
|
899
|
+
};
|
|
376
900
|
for (const d of dirs) {
|
|
377
901
|
if (typeof d !== "string" || d.trim() === "")
|
|
378
902
|
continue;
|
|
379
|
-
|
|
380
|
-
|
|
903
|
+
// A device or pseudo file (2>/dev/null) is no project; a path that isn't there yet still binds its parent's.
|
|
904
|
+
if (pseudoPath(d))
|
|
905
|
+
continue;
|
|
906
|
+
const r = projectOf(d, doc);
|
|
907
|
+
const root = scratchOf(d, r);
|
|
908
|
+
if (root !== undefined && scanned(root))
|
|
909
|
+
continue;
|
|
910
|
+
add(d, r);
|
|
381
911
|
}
|
|
382
912
|
// Who may speak for a session (statuses, sends): its front end (the person token), or, for a session
|
|
383
913
|
// no front end registered, a caller outside any agent's session. An agent's own shell never may.
|
|
@@ -404,20 +934,38 @@ export async function bindSession(app, sid, dirs, o = {}) {
|
|
|
404
934
|
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`);
|
|
405
935
|
}
|
|
406
936
|
const projects = { ...(have?.projects ?? {}) };
|
|
407
|
-
|
|
408
|
-
|
|
937
|
+
const why = new Set(have?.overWhy ?? []);
|
|
938
|
+
if (o.over === true)
|
|
939
|
+
why.add("front");
|
|
940
|
+
else if (Array.isArray(o.over))
|
|
941
|
+
for (const w of overWhys(o.over))
|
|
942
|
+
why.add(w);
|
|
943
|
+
// A binding from before overWhy kept only `over`: it stays over (said as such: legacy-over).
|
|
944
|
+
let over = have?.over === true || why.size > 0;
|
|
945
|
+
for (const { ref: r, under } of refs.values()) {
|
|
409
946
|
const prev = projects[r.id];
|
|
410
947
|
if (!prev && Object.keys(projects).length >= MAX_SESSION_PROJECTS) {
|
|
411
948
|
over = true;
|
|
949
|
+
why.add("projects");
|
|
412
950
|
continue;
|
|
413
951
|
}
|
|
414
|
-
// Once a repository asked for privacy, it stays asked for this session.
|
|
415
|
-
|
|
952
|
+
// Once a repository asked for privacy, it stays asked for this session; covered folders only add up.
|
|
953
|
+
const all = new Set([...(prev?.under ?? []), ...under]);
|
|
954
|
+
const underOver = prev?.underOver === true || all.size > MAX_UNDER;
|
|
955
|
+
projects[r.id] = {
|
|
956
|
+
name: r.name,
|
|
957
|
+
root: prev?.root ?? r.root,
|
|
958
|
+
...(r.repoPrivate || prev?.repoPrivate ? { repoPrivate: true } : {}),
|
|
959
|
+
...(!underOver && all.size > 0 ? { under: [...all].sort() } : {}),
|
|
960
|
+
...(underOver ? { underOver: true } : {}),
|
|
961
|
+
};
|
|
416
962
|
}
|
|
417
963
|
const constraints = [...(have?.constraints ?? [])];
|
|
418
964
|
if (o.constraint !== undefined && !constraints.some((c) => JSON.stringify(c) === JSON.stringify(o.constraint))) {
|
|
419
|
-
if (constraints.length >= MAX_SESSION_CONSTRAINTS)
|
|
965
|
+
if (constraints.length >= MAX_SESSION_CONSTRAINTS) {
|
|
420
966
|
over = true;
|
|
967
|
+
why.add("constraints");
|
|
968
|
+
}
|
|
421
969
|
else
|
|
422
970
|
constraints.push(o.constraint);
|
|
423
971
|
}
|
|
@@ -426,9 +974,11 @@ export async function bindSession(app, sid, dirs, o = {}) {
|
|
|
426
974
|
const next = {
|
|
427
975
|
projects,
|
|
428
976
|
...(over ? { over: true } : {}),
|
|
977
|
+
...(why.size > 0 ? { overWhy: [...why] } : {}),
|
|
429
978
|
...(constraints.length ? { constraints } : {}),
|
|
430
979
|
...(unregistered ? { unregistered: true } : {}),
|
|
431
980
|
...(registered ? { registered: true } : {}),
|
|
981
|
+
since: typeof have?.since === "number" ? have.since : now,
|
|
432
982
|
at: now,
|
|
433
983
|
};
|
|
434
984
|
return { next: { ...all, [sid]: next }, result: next };
|
|
@@ -499,6 +1049,65 @@ export function personToken(home) {
|
|
|
499
1049
|
throw new CliError("conflict", `${f} isn't a person token: remove it and run the command again`);
|
|
500
1050
|
}
|
|
501
1051
|
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Replaces the person token with a fresh one. Called whenever an identity is first created or
|
|
1054
|
+
* restored on a home (init, link join, backup restore; setup and join create through init): a
|
|
1055
|
+
* person.key that was already there may have been put there by anything that could write the
|
|
1056
|
+
* folder before the identity existed, so it must not keep standing in for the person afterwards.
|
|
1057
|
+
* The command that creates the identity checked its token when it started, so a front end's first
|
|
1058
|
+
* run still works; the front ends read person.key again when the CLI refuses their old token
|
|
1059
|
+
* (`person_token_stale`). Written whole: a new 0600 file made exclusively beside it, then renamed
|
|
1060
|
+
* over it (a planted symlink is replaced, never followed).
|
|
1061
|
+
*/
|
|
1062
|
+
export function renewPersonToken(home) {
|
|
1063
|
+
const f = personTokenFile(home);
|
|
1064
|
+
mkdirSync(join(home, "cli"), { recursive: true, mode: 0o700 });
|
|
1065
|
+
const t = randomBytes(32).toString("base64url");
|
|
1066
|
+
const tmp = `${f}.${randomBytes(6).toString("hex")}.tmp`;
|
|
1067
|
+
try {
|
|
1068
|
+
writeFileSync(tmp, t, { mode: 0o600, flag: "wx" });
|
|
1069
|
+
let cleared = false;
|
|
1070
|
+
for (let tries = 0;; tries++) {
|
|
1071
|
+
try {
|
|
1072
|
+
renameSync(tmp, f);
|
|
1073
|
+
break;
|
|
1074
|
+
}
|
|
1075
|
+
catch (e) {
|
|
1076
|
+
// Something that isn't a file is in the way (a directory): it goes, then the new token.
|
|
1077
|
+
if (!cleared && isDirectory(f)) {
|
|
1078
|
+
rmSync(f, { recursive: true, force: true });
|
|
1079
|
+
cleared = true;
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
// Windows: a virus scanner or indexer briefly holding the old file. Retried for about a second.
|
|
1083
|
+
if (process.platform === "win32" && RENAME_BUSY.has(e.code ?? "") && tries < 20) {
|
|
1084
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
1085
|
+
continue;
|
|
1086
|
+
}
|
|
1087
|
+
throw e;
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
catch (e) {
|
|
1092
|
+
rmSync(tmp, { force: true });
|
|
1093
|
+
throw new CliError("conflict", `couldn't replace the person token in ${f} (${e.code ?? "error"}): nothing was set up here. Remove that file and run the command again`);
|
|
1094
|
+
}
|
|
1095
|
+
return t;
|
|
1096
|
+
}
|
|
1097
|
+
const RENAME_BUSY = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
1098
|
+
function isDirectory(p) {
|
|
1099
|
+
try {
|
|
1100
|
+
return lstatSync(p).isDirectory();
|
|
1101
|
+
}
|
|
1102
|
+
catch {
|
|
1103
|
+
return false;
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
/** Whether `home` holds an identity: its keys and self documents (state.ts keeps them at <home>/cli/keys.json and self.json). */
|
|
1107
|
+
export function identityHere(home) {
|
|
1108
|
+
// Both documents, as App.load requires: keys alone are an identity whose creation didn't finish.
|
|
1109
|
+
return existsSync(join(home, "cli", "keys.json")) && existsSync(join(home, "cli", "self.json"));
|
|
1110
|
+
}
|
|
502
1111
|
/** Whether P2P_PERSON_TOKEN is this home's person token (read only: a missing file is no match). */
|
|
503
1112
|
export function personTokenOk(env, home) {
|
|
504
1113
|
const given = env?.P2P_PERSON_TOKEN?.trim();
|
|
@@ -529,16 +1138,39 @@ export function takePersonToken(env, home) {
|
|
|
529
1138
|
* Lets a command that widens who reaches this user (sharing a project, a session, a default
|
|
530
1139
|
* circle, invites, joins, trust, friends) run only for the person: their front end's token; or,
|
|
531
1140
|
* outside any agent's session, their "yes" typed on the controlling terminal (never stdin, never a
|
|
532
|
-
* flag: a process detached from every terminal can't give it). Reads are never asked
|
|
1141
|
+
* flag: a process detached from every terminal can't give it). Reads are never asked, except for
|
|
1142
|
+
* the person's own messages (history.ts), which pass their own `why`.
|
|
533
1143
|
*/
|
|
534
|
-
export async function assertPersonForWidening(app, what, confirm) {
|
|
1144
|
+
export async function assertPersonForWidening(app, what, confirm, why = "changes who reaches you", opts = {}) {
|
|
1145
|
+
// `noTokenBeforeIdentity`: what makes this device someone's (a link code makes it the code's
|
|
1146
|
+
// identity; setup links or joins). On a home with no identity yet the person token doesn't stand
|
|
1147
|
+
// in for the person there: no front end runs these (link and setup are refused in the Claude mod
|
|
1148
|
+
// and the Codex bridge), and a person.key on a fresh home may have been put there by anything that
|
|
1149
|
+
// can write the folder. (`join` and `accept` keep it: the mod's typed /peers join on a fresh
|
|
1150
|
+
// install is the documented first run.)
|
|
1151
|
+
const tokenCounts = !opts.noTokenBeforeIdentity || (typeof app.home === "string" && identityHere(app.home));
|
|
1152
|
+
if (app.front === true && tokenCounts)
|
|
1153
|
+
return;
|
|
1154
|
+
if (agentContext(app.env)) {
|
|
1155
|
+
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`);
|
|
1156
|
+
}
|
|
1157
|
+
if (!(await confirm(`p2p ${what} ${why}.`))) {
|
|
1158
|
+
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)`);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
/**
|
|
1162
|
+
* For an act on a session that binds nothing (a delivery receipt): the session's front end (its
|
|
1163
|
+
* token); or, outside any agent's session, a caller acting for a session no front end registered.
|
|
1164
|
+
* An agent's own shell never may, as for statuses and sends (bindSession).
|
|
1165
|
+
*/
|
|
1166
|
+
export async function assertSpeaksFor(app, sid) {
|
|
535
1167
|
if (app.front === true)
|
|
536
1168
|
return;
|
|
537
1169
|
if (agentContext(app.env)) {
|
|
538
|
-
throw new CliError("refused",
|
|
1170
|
+
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`);
|
|
539
1171
|
}
|
|
540
|
-
if (
|
|
541
|
-
throw new CliError("refused",
|
|
1172
|
+
if ((await sessionBinding(app, sid))?.registered) {
|
|
1173
|
+
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`);
|
|
542
1174
|
}
|
|
543
1175
|
}
|
|
544
1176
|
/** 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). */
|
|
@@ -548,6 +1180,99 @@ export function personHere(app) {
|
|
|
548
1180
|
export async function sessionBinding(app, sid) {
|
|
549
1181
|
return (await app.state.get("sessionProjects"))?.[sid];
|
|
550
1182
|
}
|
|
1183
|
+
const OVER_TEXT = {
|
|
1184
|
+
projects: `it worked in more than ${MAX_SESSION_PROJECTS} projects`,
|
|
1185
|
+
folders: "it worked in more folders than Peer2Peer keeps track of for one session",
|
|
1186
|
+
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",
|
|
1187
|
+
front: "its front end couldn't keep track of every folder it worked in (a forked conversation, or a record it couldn't read)",
|
|
1188
|
+
constraints: `more than ${MAX_SESSION_CONSTRAINTS} sessions of yours sent it messages`,
|
|
1189
|
+
"legacy-over": "it worked in more projects or folders than Peer2Peer keeps track of, or named a path Peer2Peer couldn't resolve",
|
|
1190
|
+
};
|
|
1191
|
+
/**
|
|
1192
|
+
* Every policy a bound project answers to: its own, and, for a folder project a shared folder
|
|
1193
|
+
* covered, each policy a covered subfolder (or a folder between it and the root) has since been
|
|
1194
|
+
* given. Past MAX_UNDER covered subfolders, every folder policy below the root.
|
|
1195
|
+
*/
|
|
1196
|
+
function boundShares(doc, id, p) {
|
|
1197
|
+
const out = [{ share: shareOf(doc, id), mapped: doc.projects[id] !== undefined, name: p.name }];
|
|
1198
|
+
const root = p.root;
|
|
1199
|
+
if (typeof root !== "string" || root === "")
|
|
1200
|
+
return out;
|
|
1201
|
+
const seen = new Set([id]);
|
|
1202
|
+
const add = (pid) => {
|
|
1203
|
+
const r = doc.projects[pid];
|
|
1204
|
+
if (seen.has(pid) || !r)
|
|
1205
|
+
return;
|
|
1206
|
+
seen.add(pid);
|
|
1207
|
+
out.push({ share: shareOf(doc, pid), mapped: true, name: clean(String(r.name ?? "")) || p.name });
|
|
1208
|
+
};
|
|
1209
|
+
// Subfolders it covered, and its share no longer covers them (shared again without --subfolders): private.
|
|
1210
|
+
if ((p.underOver || (p.under?.length ?? 0) > 0) && doc.projects[id]?.covers !== true)
|
|
1211
|
+
out.push({ share: "private", mapped: true, name: p.name });
|
|
1212
|
+
if (p.underOver) {
|
|
1213
|
+
for (const [pid, r] of Object.entries(doc.projects))
|
|
1214
|
+
if (typeof r?.root === "string" && r.root !== root && within(r.root, root) && pid === dirProjectId(r.root))
|
|
1215
|
+
add(pid);
|
|
1216
|
+
return out;
|
|
1217
|
+
}
|
|
1218
|
+
for (const f of p.under ?? []) {
|
|
1219
|
+
if (typeof f !== "string")
|
|
1220
|
+
continue;
|
|
1221
|
+
for (let c = f, i = 0; i < 4096 && c !== root && within(c, root); i++) {
|
|
1222
|
+
add(dirProjectId(c));
|
|
1223
|
+
const up = dirname(c);
|
|
1224
|
+
if (up === c)
|
|
1225
|
+
break;
|
|
1226
|
+
c = up;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
return out;
|
|
1230
|
+
}
|
|
1231
|
+
/** Why a binding is private, every cause (no network: `disjoint` needs the store, see sessionCeiling). */
|
|
1232
|
+
export function privateReasons(doc, b) {
|
|
1233
|
+
const out = [];
|
|
1234
|
+
if (b.over)
|
|
1235
|
+
for (const w of b.overWhy?.length ? overWhys(b.overWhy) : ["legacy-over"])
|
|
1236
|
+
out.push({ cause: w, why: OVER_TEXT[w] });
|
|
1237
|
+
if (b.unregistered)
|
|
1238
|
+
out.push({ cause: "unregistered", why: "an agent named it, and no front end of yours has registered it" });
|
|
1239
|
+
for (const [id, p] of Object.entries(b.projects)) {
|
|
1240
|
+
if (p.repoPrivate) {
|
|
1241
|
+
out.push({ cause: "repo-private", why: `${p.name} asks to stay private (${PRIVATE_MARKER})`, project: p.name });
|
|
1242
|
+
continue;
|
|
1243
|
+
}
|
|
1244
|
+
for (const s of boundShares(doc, id, p)) {
|
|
1245
|
+
if (s.share !== "private")
|
|
1246
|
+
continue;
|
|
1247
|
+
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 });
|
|
1248
|
+
break;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
if ((b.constraints ?? []).includes("private"))
|
|
1252
|
+
out.push({ cause: "sent-private", why: "a private session of yours sent it a message" });
|
|
1253
|
+
return out;
|
|
1254
|
+
}
|
|
1255
|
+
/**
|
|
1256
|
+
* What the person can do about a private session, for an error a model may read: a share only
|
|
1257
|
+
* when a share can lift it, never the "share each project" hint for a cause that lasts until the
|
|
1258
|
+
* session ends (a cap, an unresolved path, a dropped front end, `.p2p-private`, a private
|
|
1259
|
+
* session's message).
|
|
1260
|
+
*/
|
|
1261
|
+
export function privateRemedy(causes, names) {
|
|
1262
|
+
if (causes.some((c) => STICKY.has(c))) {
|
|
1263
|
+
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)";
|
|
1264
|
+
}
|
|
1265
|
+
const parts = [];
|
|
1266
|
+
if (causes.includes("unregistered"))
|
|
1267
|
+
parts.push("send from the session's own front end (SendMessage in Claude Code, p2p_send in Codex), which registers it");
|
|
1268
|
+
if (causes.some((c) => c === "private" || c === "unshared" || c === "disjoint") || parts.length === 0)
|
|
1269
|
+
parts.push(shareHint(names));
|
|
1270
|
+
return parts.join("; and ");
|
|
1271
|
+
}
|
|
1272
|
+
/** Whether a ceiling's privacy can only end with the session (privateRemedy says to start a new one). */
|
|
1273
|
+
export function stickyPrivate(c) {
|
|
1274
|
+
return c.kind === "private" && c.causes.some((x) => STICKY.has(x));
|
|
1275
|
+
}
|
|
551
1276
|
/**
|
|
552
1277
|
* The most a session may reach: the intersection of every bound project's policy. Unmapped,
|
|
553
1278
|
* private and repository-private projects make it private, and so does an empty intersection.
|
|
@@ -558,27 +1283,18 @@ export async function sessionCeiling(app, sid, binding) {
|
|
|
558
1283
|
const b = binding === null ? undefined : (binding ?? (await sessionBinding(app, sid)));
|
|
559
1284
|
if (!b || (Object.keys(b.projects).length === 0 && !b.constraints?.length && !b.unregistered && !b.over))
|
|
560
1285
|
return { kind: "none" };
|
|
561
|
-
if (b.over)
|
|
562
|
-
return { kind: "private", why: `it worked in more than ${MAX_SESSION_PROJECTS} projects (or ${MAX_SESSION_DIRS} folders)` };
|
|
563
|
-
if (b.unregistered)
|
|
564
|
-
return { kind: "private", why: "an agent named it, and no front end of yours has registered it" };
|
|
565
1286
|
const doc = await projectsDoc(app);
|
|
1287
|
+
const reasons = privateReasons(doc, b);
|
|
1288
|
+
if (reasons.length > 0)
|
|
1289
|
+
return privateOf(reasons);
|
|
566
1290
|
let circles;
|
|
567
1291
|
let people;
|
|
568
1292
|
const shares = [];
|
|
569
|
-
for (const [id, p] of Object.entries(b.projects))
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
if (share === "private")
|
|
574
|
-
return { kind: "private", why: doc.projects[id] ? `${p.name} is private` : `${p.name} isn't shared (projects are private until you share them)` };
|
|
575
|
-
shares.push({ name: p.name, share });
|
|
576
|
-
}
|
|
577
|
-
for (const c of b.constraints ?? []) {
|
|
578
|
-
if (c === "private")
|
|
579
|
-
return { kind: "private", why: "a private session of yours sent it a message" };
|
|
1293
|
+
for (const [id, p] of Object.entries(b.projects))
|
|
1294
|
+
for (const s of boundShares(doc, id, p))
|
|
1295
|
+
shares.push({ name: s.name, share: s.share });
|
|
1296
|
+
for (const c of b.constraints ?? [])
|
|
580
1297
|
shares.push({ name: "a session of yours that sent it a message", share: c });
|
|
581
|
-
}
|
|
582
1298
|
for (const { share } of shares) {
|
|
583
1299
|
if (share === "private")
|
|
584
1300
|
continue;
|
|
@@ -594,11 +1310,22 @@ export async function sessionCeiling(app, sid, binding) {
|
|
|
594
1310
|
const friends = (people?.size ?? 0) > 0 ? await friendIds(app) : new Set();
|
|
595
1311
|
const ppl = [...(people ?? [])].filter((u) => !blocks.has(u) && u !== app.userId && friends.has(u));
|
|
596
1312
|
if (joined.length + ppl.length === 0) {
|
|
597
|
-
const names = shares.map((x) => x.name);
|
|
598
|
-
return {
|
|
1313
|
+
const names = [...new Set(shares.map((x) => x.name))];
|
|
1314
|
+
return privateOf([{ cause: "disjoint", why: names.length > 1 ? `its projects (${nameList(names)}) share nobody in common` : `${names[0]} shares nobody you can reach` }], names);
|
|
599
1315
|
}
|
|
600
1316
|
return { kind: "shared", circles: joined.sort(), people: ppl.sort() };
|
|
601
1317
|
}
|
|
1318
|
+
/** A private ceiling from its reasons: the first said in full, the count of the rest (`p2p session show` lists them all). */
|
|
1319
|
+
function privateOf(reasons, names) {
|
|
1320
|
+
const more = reasons.length - 1;
|
|
1321
|
+
const blocking = names ?? [...new Set(reasons.map((r) => r.project).filter((x) => x !== undefined))];
|
|
1322
|
+
return {
|
|
1323
|
+
kind: "private",
|
|
1324
|
+
why: `${reasons[0].why}${more > 0 ? ` (and ${more} more reason${more === 1 ? "" : "s"})` : ""}`,
|
|
1325
|
+
causes: [...new Set(reasons.map((r) => r.cause))],
|
|
1326
|
+
...(blocking.length ? { blocking } : {}),
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
602
1329
|
/** Everyone a ceiling lets in (besides this user): members of its circles who stand in them, and its people. */
|
|
603
1330
|
export async function ceilingAudience(app, c) {
|
|
604
1331
|
if (c.kind === "none")
|
|
@@ -623,9 +1350,14 @@ export async function ceilingAudience(app, c) {
|
|
|
623
1350
|
out.delete(u);
|
|
624
1351
|
return out;
|
|
625
1352
|
}
|
|
1353
|
+
/** Project names for a message: the first MESSAGE_NAMES, then how many more (`p2p session show` lists them all). */
|
|
1354
|
+
const MESSAGE_NAMES = 16;
|
|
1355
|
+
function nameList(names) {
|
|
1356
|
+
return `${names.slice(0, MESSAGE_NAMES).join(", ")}${names.length > MESSAGE_NAMES ? ` and ${names.length - MESSAGE_NAMES} more` : ""}`;
|
|
1357
|
+
}
|
|
626
1358
|
/** How to tell the person to share, for an error a model may read: the person's command, never a flag for the caller. */
|
|
627
1359
|
export function shareHint(names) {
|
|
628
|
-
const what = names.length === 1 ? `the project ${names[0]}` : `each of ${names
|
|
1360
|
+
const what = names.length === 1 ? `the project ${names[0]}` : `each of ${nameList(names)}`;
|
|
629
1361
|
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)`;
|
|
630
1362
|
}
|
|
631
1363
|
/**
|
|
@@ -645,9 +1377,10 @@ export async function assertMayReach(app, sid, userId, o = {}) {
|
|
|
645
1377
|
const names = Object.values(b?.projects ?? {}).map((p) => p.name);
|
|
646
1378
|
const who = o.address ?? (await app.addressOf(userId));
|
|
647
1379
|
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"}`;
|
|
648
|
-
|
|
1380
|
+
const remedy = c.kind === "private" ? privateRemedy(c.causes, c.blocking?.length ? c.blocking : names) : shareHint(names);
|
|
1381
|
+
throw new CliError("not_shared", `session ${sid} works in ${nameList(names) || "a project"}, and Peer2Peer won't carry anything from it to ${who}: ${why}. ${remedy.charAt(0).toUpperCase()}${remedy.slice(1)}`, {
|
|
649
1382
|
delivered: false,
|
|
650
|
-
project: { names, policy: c.kind },
|
|
1383
|
+
project: { names, policy: c.kind, ...(c.kind === "private" ? { causes: c.causes, ...(stickyPrivate(c) ? { sticky: true } : {}) } : {}) },
|
|
651
1384
|
});
|
|
652
1385
|
}
|
|
653
1386
|
/** Friends of this user (live friendships), for the roster's named parts. */
|
|
@@ -662,11 +1395,45 @@ export async function sessionProjectView(app, sid) {
|
|
|
662
1395
|
const c = await sessionCeiling(app, sid, b ?? null);
|
|
663
1396
|
const projects = Object.entries(b?.projects ?? {}).map(([id, p]) => ({ id, name: p.name, ...(p.repoPrivate ? { repoPrivate: true } : {}) }));
|
|
664
1397
|
if (c.kind === "private")
|
|
665
|
-
return { projects, policy: "private", why: c.why };
|
|
1398
|
+
return { projects, policy: "private", why: c.why, causes: c.causes };
|
|
666
1399
|
if (c.kind === "shared")
|
|
667
1400
|
return { projects, policy: "shared", circles: c.circles, people: c.people };
|
|
668
1401
|
return { projects, policy: "none" };
|
|
669
1402
|
}
|
|
1403
|
+
/**
|
|
1404
|
+
* `p2p session show <sid>`: read only, and the person's: their front end (the person token) or
|
|
1405
|
+
* their own terminal outside any agent's session. An agent's shell is refused, so no session reads
|
|
1406
|
+
* another's bindings (or its own: the model has the not_shared reason already).
|
|
1407
|
+
*/
|
|
1408
|
+
export async function showSession(app, sid) {
|
|
1409
|
+
if (app.front !== true && agentContext(app.env)) {
|
|
1410
|
+
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");
|
|
1411
|
+
}
|
|
1412
|
+
if (sid === PERSON_SESSION)
|
|
1413
|
+
return { sid, policy: "none", reasons: [], projects: [], constraints: 0 };
|
|
1414
|
+
const b = await sessionBinding(app, sid);
|
|
1415
|
+
const c = await sessionCeiling(app, sid, b ?? null);
|
|
1416
|
+
const doc = await projectsDoc(app);
|
|
1417
|
+
const reasons = b ? privateReasons(doc, b) : [];
|
|
1418
|
+
if (c.kind === "private" && reasons.length === 0)
|
|
1419
|
+
reasons.push({ cause: c.causes[0] ?? "disjoint", why: c.why });
|
|
1420
|
+
const projects = [];
|
|
1421
|
+
for (const [id, p] of Object.entries(b?.projects ?? {})) {
|
|
1422
|
+
const root = typeof p.root === "string" && p.root !== "" ? p.root : (doc.projects[id]?.root ?? "");
|
|
1423
|
+
const kind = root !== "" && dirProjectId(root) === id ? "dir" : "git";
|
|
1424
|
+
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);
|
|
1425
|
+
projects.push({ ...v, ...(p.under?.length ? { under: [...p.under] } : {}), ...(p.underOver ? { underOver: true } : {}) });
|
|
1426
|
+
}
|
|
1427
|
+
return {
|
|
1428
|
+
sid,
|
|
1429
|
+
policy: c.kind,
|
|
1430
|
+
reasons,
|
|
1431
|
+
...(c.kind === "private" ? { remedy: privateRemedy(c.causes, c.blocking?.length ? c.blocking : projects.map((x) => x.name)) } : {}),
|
|
1432
|
+
...(c.kind === "shared" ? { circles: c.circles, people: c.people } : {}),
|
|
1433
|
+
projects,
|
|
1434
|
+
constraints: b?.constraints?.length ?? 0,
|
|
1435
|
+
};
|
|
1436
|
+
}
|
|
670
1437
|
/**
|
|
671
1438
|
* The one-time notice for a user who relied on the default circle: shown once per device, the
|
|
672
1439
|
* first time a session of theirs is private only because its project was never shared.
|
|
@@ -697,3 +1464,206 @@ export async function defaultCircleNotice(app, sid) {
|
|
|
697
1464
|
}
|
|
698
1465
|
/** The text of the one-time notice starts so (the mod and the Codex bridge match it). */
|
|
699
1466
|
export const PROJECT_NOTICE_PREFIX = "project boundaries:";
|
|
1467
|
+
/** `s` without trailing slashes (a loop, not a regex: linear on any input). */
|
|
1468
|
+
function trimSlashes(s) {
|
|
1469
|
+
let n = s.length;
|
|
1470
|
+
while (n > 0 && s.charCodeAt(n - 1) === 47)
|
|
1471
|
+
n--;
|
|
1472
|
+
return s.slice(0, n);
|
|
1473
|
+
}
|
|
1474
|
+
/** What `p2p doctor` and `p2p project show` print for a local target. */
|
|
1475
|
+
export const GRAPH_LOCAL_ONLY = "local only";
|
|
1476
|
+
/** Ix's own default backend (ix-cli config.ts DEFAULT_ENDPOINT): `ix docker` runs it on this machine. */
|
|
1477
|
+
export const DEFAULT_IX_ENDPOINT = "http://localhost:8090";
|
|
1478
|
+
/**
|
|
1479
|
+
* Whether `url` is an Ix backend on this machine: http(s) to localhost, 127.0.0.0/8 or ::1, with no
|
|
1480
|
+
* credentials, query or fragment. Anything else (a cloud URL, a LAN host, `localhost.example.com`,
|
|
1481
|
+
* `http://127.0.0.1@evil.example`) is not.
|
|
1482
|
+
*/
|
|
1483
|
+
export function isLoopbackEndpoint(url) {
|
|
1484
|
+
if (typeof url !== "string" || url.length > 512 || /[\s\0]/.test(url))
|
|
1485
|
+
return false;
|
|
1486
|
+
let u;
|
|
1487
|
+
try {
|
|
1488
|
+
u = new URL(url);
|
|
1489
|
+
}
|
|
1490
|
+
catch {
|
|
1491
|
+
return false;
|
|
1492
|
+
}
|
|
1493
|
+
if ((u.protocol !== "http:" && u.protocol !== "https:") || u.username || u.password || u.search || u.hash)
|
|
1494
|
+
return false;
|
|
1495
|
+
const h = u.hostname.toLowerCase();
|
|
1496
|
+
return h === "localhost" || h === "[::1]" || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
|
|
1497
|
+
}
|
|
1498
|
+
/** A loopback endpoint as one canonical string: `origin + pathname`, trailing slashes dropped. Undefined when it isn't one. */
|
|
1499
|
+
export function normalizeLoopbackEndpoint(url) {
|
|
1500
|
+
if (!isLoopbackEndpoint(url))
|
|
1501
|
+
return undefined;
|
|
1502
|
+
const u = new URL(url.trim());
|
|
1503
|
+
return trimSlashes(u.origin + u.pathname);
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* The local Ix endpoint every `local` target names: `ixEndpoint` in config.json (the person's own
|
|
1507
|
+
* file) when it is a loopback URL, else Ix's default. Never from the environment (an agent or a
|
|
1508
|
+
* project config can set that), and never a non-loopback URL. On a shared machine another user can
|
|
1509
|
+
* listen on a loopback port first (threat model, "Graph targets").
|
|
1510
|
+
*/
|
|
1511
|
+
export function localGraphEndpoint(_env, file) {
|
|
1512
|
+
return normalizeLoopbackEndpoint(typeof file?.ixEndpoint === "string" ? file.ixEndpoint.trim() : undefined) ?? DEFAULT_IX_ENDPOINT;
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* The circles that have a shared graph, and its endpoint. None yet: the shared cloud graph (epic #41
|
|
1516
|
+
* piece 3) comes in a later PR, which fills this from settled, person-made state. Nothing in the
|
|
1517
|
+
* environment, config.json, a repository or a peer's message can add to it.
|
|
1518
|
+
*/
|
|
1519
|
+
export const SHARED_GRAPHS = new Map();
|
|
1520
|
+
/**
|
|
1521
|
+
* The graph target of a set of projects (pure: graphTarget gathers the inputs). Intersection, like
|
|
1522
|
+
* the session ceiling: any private, repository-private or unmapped project makes it local, and so
|
|
1523
|
+
* does an empty set. A shared target needs every input shared with the same circle, and exactly one
|
|
1524
|
+
* such circle with a shared graph (an https endpoint); people-only shares, no common circle, or a
|
|
1525
|
+
* choice of several circles all stay local.
|
|
1526
|
+
*/
|
|
1527
|
+
export function graphTargetOf(inputs, o) {
|
|
1528
|
+
const local = (why) => ({ kind: "local", endpoint: o.local, why });
|
|
1529
|
+
if (inputs.length === 0)
|
|
1530
|
+
return local("no project: nothing is shared");
|
|
1531
|
+
let circles;
|
|
1532
|
+
for (const i of inputs) {
|
|
1533
|
+
if (i.repoPrivate)
|
|
1534
|
+
return local(`${i.name} asks to stay private (${PRIVATE_MARKER})`);
|
|
1535
|
+
if (i.share === "private" || typeof i.share !== "object")
|
|
1536
|
+
return local(`${i.name} is private`);
|
|
1537
|
+
const cs = Array.isArray(i.share.circles) ? i.share.circles.filter((c) => typeof c === "string") : [];
|
|
1538
|
+
circles = circles ? new Set(cs.filter((c) => circles.has(c))) : new Set(cs);
|
|
1539
|
+
}
|
|
1540
|
+
if (!circles || circles.size === 0)
|
|
1541
|
+
return local(inputs.length > 1 ? "its projects share no circle in common" : `${inputs[0].name} isn't shared with a circle`);
|
|
1542
|
+
const graphs = o.sharedGraphs ?? SHARED_GRAPHS;
|
|
1543
|
+
const withGraph = [...circles].filter((c) => {
|
|
1544
|
+
const ep = graphs.get(c);
|
|
1545
|
+
return normalizeSharedEndpoint(ep) !== undefined;
|
|
1546
|
+
});
|
|
1547
|
+
if (withGraph.length === 0)
|
|
1548
|
+
return local("no shared graph for its circle yet: Ix stays on this machine");
|
|
1549
|
+
if (withGraph.length > 1)
|
|
1550
|
+
return local("it is shared with more than one circle that has a shared graph: Ix stays on this machine");
|
|
1551
|
+
return { kind: "shared", circle: withGraph[0], endpoint: normalizeSharedEndpoint(graphs.get(withGraph[0])) };
|
|
1552
|
+
}
|
|
1553
|
+
/** A shared graph's endpoint as `origin + pathname` (https, off this machine, no credentials, query or fragment), else undefined. */
|
|
1554
|
+
export function normalizeSharedEndpoint(url) {
|
|
1555
|
+
if (typeof url !== "string" || url.length > 512 || /[\s\0]/.test(url))
|
|
1556
|
+
return undefined;
|
|
1557
|
+
let u;
|
|
1558
|
+
try {
|
|
1559
|
+
u = new URL(url);
|
|
1560
|
+
}
|
|
1561
|
+
catch {
|
|
1562
|
+
return undefined;
|
|
1563
|
+
}
|
|
1564
|
+
if (u.protocol !== "https:" || u.username || u.password || u.search || u.hash || isLoopbackEndpoint(url))
|
|
1565
|
+
return undefined;
|
|
1566
|
+
return trimSlashes(u.origin + u.pathname);
|
|
1567
|
+
}
|
|
1568
|
+
/**
|
|
1569
|
+
* The chokepoint for every Ix call Peer2Peer makes or lets an extension make (ext-ix takes its
|
|
1570
|
+
* endpoint only from here, ExtContext.graphTarget): the graph a session, the folders it works in,
|
|
1571
|
+
* or both may reach. A session bound to a private project, or one whose ceiling is private for any
|
|
1572
|
+
* reason (an unregistered agent session, too many projects, a private session's message), is local.
|
|
1573
|
+
* The folders' own projects are intersected in, so a session can't name a shared sibling to widen
|
|
1574
|
+
* a private repository it works in. The process's own cwd and every path the call names (`paths`:
|
|
1575
|
+
* its targets, `--path`, `--changed`, the child's cwd) are intersected in as well. A named session
|
|
1576
|
+
* that isn't bound yet is local, and a `shared` result needs a session a front end registered (its
|
|
1577
|
+
* person token). Read only: binds nothing.
|
|
1578
|
+
*/
|
|
1579
|
+
export async function graphTarget(app, o = {}, sharedGraphs = SHARED_GRAPHS) {
|
|
1580
|
+
const lo = localGraphEndpoint(app.env, app.file);
|
|
1581
|
+
const local = (why) => ({ kind: "local", endpoint: lo, why });
|
|
1582
|
+
if (o.over)
|
|
1583
|
+
return local(`it works in more than ${MAX_SESSION_DIRS} folders`);
|
|
1584
|
+
// The paths a call names (its targets, --path, --changed, the child's cwd): absolute only, capped.
|
|
1585
|
+
const paths = o.paths ?? [];
|
|
1586
|
+
if (paths.length > MAX_GRAPH_PATHS)
|
|
1587
|
+
return local(`a call named more than ${MAX_GRAPH_PATHS} paths`);
|
|
1588
|
+
if (paths.some((p) => typeof p !== "string" || !isAbsolute(p)))
|
|
1589
|
+
return local("a call named a path that isn't absolute");
|
|
1590
|
+
const doc = await projectsDoc(app);
|
|
1591
|
+
const inputs = [];
|
|
1592
|
+
let registered = false;
|
|
1593
|
+
if (o.sid !== undefined && o.sid !== PERSON_SESSION) {
|
|
1594
|
+
const b = await sessionBinding(app, o.sid);
|
|
1595
|
+
registered = b?.registered === true;
|
|
1596
|
+
const c = await sessionCeiling(app, o.sid, b ?? null);
|
|
1597
|
+
if (c.kind === "private")
|
|
1598
|
+
return local(`session ${o.sid} is private: ${c.why}`);
|
|
1599
|
+
// A session no front end has bound yet has no ceiling to intersect: fail closed.
|
|
1600
|
+
if (c.kind === "none")
|
|
1601
|
+
return local(`session ${o.sid} isn't bound to a project yet`);
|
|
1602
|
+
if (c.kind === "shared")
|
|
1603
|
+
inputs.push({ name: `session ${o.sid}`, share: { circles: c.circles, people: c.people } });
|
|
1604
|
+
}
|
|
1605
|
+
const seen = new Set();
|
|
1606
|
+
// The process's real cwd always counts too: P2P_WORKDIR replaces it for display, never for the boundary.
|
|
1607
|
+
for (const d of [...(o.dirs ?? []), process.cwd(), ...paths]) {
|
|
1608
|
+
if (typeof d !== "string" || d.trim() === "")
|
|
1609
|
+
continue;
|
|
1610
|
+
const r = projectOf(d);
|
|
1611
|
+
if (seen.has(r.id))
|
|
1612
|
+
continue;
|
|
1613
|
+
seen.add(r.id);
|
|
1614
|
+
if (seen.size > MAX_SESSION_PROJECTS)
|
|
1615
|
+
return local(`it works in more than ${MAX_SESSION_PROJECTS} projects`);
|
|
1616
|
+
inputs.push({ name: r.name, share: shareOf(doc, r.id), ...(r.repoPrivate ? { repoPrivate: true } : {}) });
|
|
1617
|
+
}
|
|
1618
|
+
const t = graphTargetOf(inputs, { local: lo, sharedGraphs });
|
|
1619
|
+
// A shared graph only for a session a front end of this user registered (its token), never a bare call.
|
|
1620
|
+
if (t.kind === "shared" && !registered)
|
|
1621
|
+
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");
|
|
1622
|
+
return t;
|
|
1623
|
+
}
|
|
1624
|
+
/** At most this many paths one Ix call may name for its graph target; past it, local. */
|
|
1625
|
+
export const MAX_GRAPH_PATHS = 64;
|
|
1626
|
+
/** One project's graph target (`p2p project show`, `p2p doctor`). */
|
|
1627
|
+
export function projectGraphTarget(app, ref, doc) {
|
|
1628
|
+
const lo = localGraphEndpoint(app.env, app.file);
|
|
1629
|
+
return graphTargetOf([{ name: ref.name, share: shareOf(doc, ref.id), ...(ref.repoPrivate ? { repoPrivate: true } : {}) }], { local: lo });
|
|
1630
|
+
}
|
|
1631
|
+
/** How a target reads in one line: `local only (http://localhost:8090)`, or the circle's shared graph. */
|
|
1632
|
+
export function describeGraphTarget(t) {
|
|
1633
|
+
return t.kind === "local" ? `${GRAPH_LOCAL_ONLY} (${t.endpoint})` : `the shared graph of circle ${t.circle} (${t.endpoint})`;
|
|
1634
|
+
}
|
|
1635
|
+
/** A target with, for a local one, why: the one wording `p2p project show|ls` and `p2p doctor` print. */
|
|
1636
|
+
export function graphTargetLine(t) {
|
|
1637
|
+
return `${describeGraphTarget(t)}${t.kind === "local" && t.why ? `: ${t.why}` : ""}`;
|
|
1638
|
+
}
|
|
1639
|
+
/** Who can read what a graph target holds: Ix keeps it in plaintext (docs/security/encryption.md). */
|
|
1640
|
+
export function graphPlaintextNote(t) {
|
|
1641
|
+
return t.kind === "local" ? "the local Ix backend keeps it in plaintext on this machine" : "the shared graph keeps it in plaintext that its operator can read";
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* The Ix variables that could send an `ix` call somewhere other than its graph target, or carry a
|
|
1645
|
+
* cloud credential: Ix Pro's PAT mode (IX_PAT, IX_ORG, its endpoint override), the cloud push and
|
|
1646
|
+
* ingestion knobs, the OAuth secret, auto-map routing to the cloud. Every IX_* variable outside
|
|
1647
|
+
* IX_KEEP is dropped as well; these are named so tests and docs can point at them.
|
|
1648
|
+
*/
|
|
1649
|
+
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"];
|
|
1650
|
+
/** 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). */
|
|
1651
|
+
export const IX_KEEP = ["IX_BIN", "IX_HOME", "IX_TOKEN"];
|
|
1652
|
+
/**
|
|
1653
|
+
* The environment an extension gets (ExtContext.env), with the target pinned: every IX_* variable
|
|
1654
|
+
* outside IX_KEEP set to undefined (so a `{...process.env, ...ctx.env}` merge drops it too: an older
|
|
1655
|
+
* ext-ix spreads it), IX_ENDPOINT set to the target's endpoint, and readers kept from starting a
|
|
1656
|
+
* background `ix map` (Ix Pro routes a map to the cloud when an org session is active, whatever
|
|
1657
|
+
* IX_ENDPOINT says). Defence in depth: ext-ix builds its own allowlisted env from the target.
|
|
1658
|
+
*/
|
|
1659
|
+
export function graphPinnedEnv(env, target, base = process.env) {
|
|
1660
|
+
const out = { ...env };
|
|
1661
|
+
const keep = new Set(IX_KEEP);
|
|
1662
|
+
for (const k of new Set([...Object.keys(base), ...Object.keys(env)]))
|
|
1663
|
+
if (/^IX_/i.test(k) && !keep.has(k.toUpperCase()))
|
|
1664
|
+
out[k] = undefined;
|
|
1665
|
+
out.IX_ENDPOINT = target.endpoint;
|
|
1666
|
+
out.IX_MAP_BACKGROUND_REFRESH = "0";
|
|
1667
|
+
out.IX_NO_UPDATE_CHECK = "1";
|
|
1668
|
+
return out;
|
|
1669
|
+
}
|