@peer2peer/cli 0.1.1 → 0.1.3
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 +16 -12
- package/dist/ancestry.d.ts +42 -2
- package/dist/ancestry.js +215 -32
- package/dist/app.d.ts +120 -0
- package/dist/app.js +254 -42
- package/dist/cli.d.ts +53 -5
- package/dist/cli.js +375 -35
- package/dist/config.d.ts +5 -0
- package/dist/doctor.d.ts +71 -2
- package/dist/doctor.js +123 -16
- package/dist/ext-host.js +5 -1
- package/dist/extensions.js +2 -2
- package/dist/format.d.ts +2 -0
- package/dist/format.js +5 -1
- package/dist/identity.d.ts +35 -5
- package/dist/identity.js +103 -26
- package/dist/ix-local.d.ts +63 -11
- package/dist/ix-local.js +81 -24
- package/dist/pretty.d.ts +3 -1
- package/dist/pretty.js +11 -3
- package/dist/projects.d.ts +119 -6
- package/dist/projects.js +494 -36
- package/dist/rotation.d.ts +20 -1
- package/dist/rotation.js +294 -20
- package/dist/sessions.d.ts +8 -0
- package/dist/sessions.js +73 -16
- package/dist/social.js +11 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/watch.js +43 -13
- package/package.json +6 -3
package/dist/projects.js
CHANGED
|
@@ -20,9 +20,9 @@
|
|
|
20
20
|
// session (messages, extension kinds, offline copies) are refused to anyone outside it.
|
|
21
21
|
// - `p2p tui` and `p2p send` typed at a terminal with no --from-session are the person's own
|
|
22
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";
|
|
23
|
+
import { agentAncestor, ancestryUnknown, ancestryWhy, isAgentProcess } from "./ancestry.js";
|
|
24
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
25
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
26
26
|
import { homedir, tmpdir } from "node:os";
|
|
27
27
|
import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
|
|
28
28
|
import { circlePolicy, liveFriendshipsV3, loadCircle, sanitizePeerText, standsLookup } from "@peer2peer/core/v3";
|
|
@@ -74,8 +74,12 @@ export function overWhys(v) {
|
|
|
74
74
|
}
|
|
75
75
|
/** At most this many folders a front end passes per call; past it the session is private. */
|
|
76
76
|
export const MAX_SESSION_DIRS = 512;
|
|
77
|
-
/**
|
|
78
|
-
|
|
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;
|
|
79
83
|
/** Bindings of sessions not seen for this long are dropped. */
|
|
80
84
|
export const SESSION_BINDING_TTL_MS = 30 * 24 * 3600 * 1000;
|
|
81
85
|
/** At most this many circles and people in one project's policy. */
|
|
@@ -103,9 +107,43 @@ function real(p) {
|
|
|
103
107
|
}
|
|
104
108
|
}
|
|
105
109
|
}
|
|
106
|
-
/**
|
|
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. */
|
|
107
145
|
function existingDir(p) {
|
|
108
|
-
let cur =
|
|
146
|
+
let cur = physicalPath(p);
|
|
109
147
|
for (let i = 0; i < 4096; i++) {
|
|
110
148
|
try {
|
|
111
149
|
const st = statSync(cur);
|
|
@@ -345,7 +383,8 @@ function present(p) {
|
|
|
345
383
|
* Without `doc` (sharing, `project show`): the folder itself.
|
|
346
384
|
*/
|
|
347
385
|
export function projectOf(dir, doc) {
|
|
348
|
-
|
|
386
|
+
// As the file system walks it: `link/../x` is beside the link's target, not beside the link.
|
|
387
|
+
const given = physicalPath(dir);
|
|
349
388
|
const start = existingDir(given);
|
|
350
389
|
let cur = start;
|
|
351
390
|
for (let i = 0; i < 4096; i++) {
|
|
@@ -378,7 +417,7 @@ export function projectOf(dir, doc) {
|
|
|
378
417
|
}
|
|
379
418
|
if (!gitDir || !existsSync(gitDir)) {
|
|
380
419
|
// 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 };
|
|
420
|
+
return { id: dirProjectId(cur), name: clean(basename(cur)) || "folder", kind: "dir", root: cur, brokenGit: true };
|
|
382
421
|
}
|
|
383
422
|
return gitRef(gitDir, cur);
|
|
384
423
|
}
|
|
@@ -669,6 +708,137 @@ export async function showProject(app, dir) {
|
|
|
669
708
|
const doc = await projectsDoc(app);
|
|
670
709
|
return projectView(app, projectOf(dir, doc), doc);
|
|
671
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;
|
|
841
|
+
}
|
|
672
842
|
// ---------------------------------------------------------------------------
|
|
673
843
|
// Sessions
|
|
674
844
|
/**
|
|
@@ -686,13 +856,7 @@ export async function bindSession(app, sid, dirs, o = {}) {
|
|
|
686
856
|
// Folder projects follow the policies (a shared folder covers its subfolders): read once, before the lock.
|
|
687
857
|
const doc = dirs.length > 0 ? await projectsDoc(app) : undefined;
|
|
688
858
|
const refs = new Map();
|
|
689
|
-
|
|
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);
|
|
859
|
+
const add = (d, r) => {
|
|
696
860
|
const one = refs.get(r.id) ?? { ref: r, under: new Set() };
|
|
697
861
|
// A folder a shared folder above covered: remembered, so a policy it gets later still narrows this session.
|
|
698
862
|
if (r.kind === "dir") {
|
|
@@ -701,6 +865,49 @@ export async function bindSession(app, sid, dirs, o = {}) {
|
|
|
701
865
|
one.under.add(at);
|
|
702
866
|
}
|
|
703
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
|
+
};
|
|
900
|
+
for (const d of dirs) {
|
|
901
|
+
if (typeof d !== "string" || d.trim() === "")
|
|
902
|
+
continue;
|
|
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);
|
|
704
911
|
}
|
|
705
912
|
// Who may speak for a session (statuses, sends): its front end (the person token), or, for a session
|
|
706
913
|
// no front end registered, a caller outside any agent's session. An agent's own shell never may.
|
|
@@ -808,22 +1015,182 @@ export function agentContext(env) {
|
|
|
808
1015
|
return agentEnv(env) || agentAncestor();
|
|
809
1016
|
}
|
|
810
1017
|
export { isAgentProcess };
|
|
811
|
-
/**
|
|
1018
|
+
/**
|
|
1019
|
+
* `<home>/cli/person.key`: the secret the person's front ends (the Claude mod, the Codex bridge)
|
|
1020
|
+
* pass back as P2P_PERSON_TOKEN. On a home with an identity it is derived, never just stored: an
|
|
1021
|
+
* HMAC under this device's signing key over the home's salt (`person.salt`, replaced whenever an
|
|
1022
|
+
* identity is created or restored here), so a person.key that anything else wrote never verifies
|
|
1023
|
+
* (personTokenOk recomputes it). On a fresh home (no identity yet) it is a random value, as the
|
|
1024
|
+
* front ends make it on a first run.
|
|
1025
|
+
*/
|
|
812
1026
|
export function personTokenFile(home) {
|
|
813
1027
|
return join(home, "cli", "person.key");
|
|
814
1028
|
}
|
|
1029
|
+
/** `<home>/cli/person.salt`: the per-home salt of the derived person token (replaced with the identity). */
|
|
1030
|
+
export function personSaltFile(home) {
|
|
1031
|
+
return join(home, "cli", "person.salt");
|
|
1032
|
+
}
|
|
815
1033
|
const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
1034
|
+
const TOKEN_LABEL = "peer2peer/person-token/v1\0";
|
|
1035
|
+
/** The token for `spk` (a device's b64u signing seed) and `salt`: base64url of HMAC-SHA256, 43 characters. */
|
|
1036
|
+
function deriveToken(spk, salt) {
|
|
1037
|
+
return createHmac("sha256", Buffer.from(spk, "base64url")).update(TOKEN_LABEL).update(salt).digest("base64url");
|
|
1038
|
+
}
|
|
1039
|
+
function readTrim(f) {
|
|
1040
|
+
try {
|
|
1041
|
+
return readFileSync(f, "utf8").trim();
|
|
1042
|
+
}
|
|
1043
|
+
catch {
|
|
1044
|
+
return undefined;
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
/**
|
|
1048
|
+
* Whether the files the person token rests on are this home's own: the `cli` folder, its keys and
|
|
1049
|
+
* self documents, the token and its salt, and the `v3` store are no symbolic links, and the keys
|
|
1050
|
+
* and self documents have one link each (the CLI writes them by rename, so a second hard link was
|
|
1051
|
+
* made by something else). A home put together from links to another home's files (to pair that
|
|
1052
|
+
* identity's keys with a token of the maker's choosing) is never the person's.
|
|
1053
|
+
*/
|
|
1054
|
+
export function homeFilesOwn(home) {
|
|
1055
|
+
const cli = join(home, "cli");
|
|
1056
|
+
try {
|
|
1057
|
+
const d = lstatSync(cli);
|
|
1058
|
+
if (d.isSymbolicLink() || !d.isDirectory())
|
|
1059
|
+
return false;
|
|
1060
|
+
}
|
|
1061
|
+
catch (e) {
|
|
1062
|
+
return e.code === "ENOENT";
|
|
1063
|
+
}
|
|
1064
|
+
const checks = [
|
|
1065
|
+
[join(cli, "keys.json"), true],
|
|
1066
|
+
[join(cli, "self.json"), true],
|
|
1067
|
+
[personTokenFile(home), false],
|
|
1068
|
+
[personSaltFile(home), false],
|
|
1069
|
+
[join(home, "v3"), false],
|
|
1070
|
+
];
|
|
1071
|
+
for (const [p, single] of checks) {
|
|
1072
|
+
let st;
|
|
820
1073
|
try {
|
|
821
|
-
|
|
822
|
-
|
|
1074
|
+
st = lstatSync(p);
|
|
1075
|
+
}
|
|
1076
|
+
catch (e) {
|
|
1077
|
+
if (e.code === "ENOENT")
|
|
1078
|
+
continue;
|
|
1079
|
+
return false;
|
|
1080
|
+
}
|
|
1081
|
+
if (st.isSymbolicLink())
|
|
1082
|
+
return false;
|
|
1083
|
+
if (single && st.nlink !== 1)
|
|
1084
|
+
return false;
|
|
1085
|
+
}
|
|
1086
|
+
return true;
|
|
1087
|
+
}
|
|
1088
|
+
/** The person token this home's identity derives (undefined: no identity, no salt yet, or keys that can't be read). */
|
|
1089
|
+
function derivedToken(home) {
|
|
1090
|
+
if (!identityHere(home))
|
|
1091
|
+
return undefined;
|
|
1092
|
+
const salt = readTrim(personSaltFile(home));
|
|
1093
|
+
if (!salt || !TOKEN_RE.test(salt))
|
|
1094
|
+
return undefined;
|
|
1095
|
+
let spk;
|
|
1096
|
+
try {
|
|
1097
|
+
spk = JSON.parse(readFileSync(join(home, "cli", "keys.json"), "utf8")).spk;
|
|
1098
|
+
}
|
|
1099
|
+
catch {
|
|
1100
|
+
return undefined;
|
|
1101
|
+
}
|
|
1102
|
+
return typeof spk === "string" && spk !== "" ? deriveToken(spk, salt) : undefined;
|
|
1103
|
+
}
|
|
1104
|
+
/** Writes `text` to `f` whole: a new 0600 file made exclusively beside it, renamed over it (a planted symlink is replaced, not followed). */
|
|
1105
|
+
function writeWhole(f, text) {
|
|
1106
|
+
mkdirSync(dirname(f), { recursive: true, mode: 0o700 });
|
|
1107
|
+
const tmp = `${f}.${randomBytes(6).toString("hex")}.tmp`;
|
|
1108
|
+
try {
|
|
1109
|
+
writeFileSync(tmp, text, { mode: 0o600, flag: "wx" });
|
|
1110
|
+
let cleared = false;
|
|
1111
|
+
for (let tries = 0;; tries++) {
|
|
1112
|
+
try {
|
|
1113
|
+
renameSync(tmp, f);
|
|
1114
|
+
break;
|
|
1115
|
+
}
|
|
1116
|
+
catch (e) {
|
|
1117
|
+
// Something that isn't a file is in the way (a directory): it goes, then the new file.
|
|
1118
|
+
if (!cleared && isDirectory(f)) {
|
|
1119
|
+
rmSync(f, { recursive: true, force: true });
|
|
1120
|
+
cleared = true;
|
|
1121
|
+
continue;
|
|
1122
|
+
}
|
|
1123
|
+
// Windows: a virus scanner or indexer briefly holding the old file. Retried for about a second.
|
|
1124
|
+
if (process.platform === "win32" && RENAME_BUSY.has(e.code ?? "") && tries < 20) {
|
|
1125
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
1126
|
+
continue;
|
|
1127
|
+
}
|
|
1128
|
+
throw e;
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
catch (e) {
|
|
1133
|
+
rmSync(tmp, { force: true });
|
|
1134
|
+
throw e;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* The home's salt, made once: exclusively when there is none (two first runs at once agree on
|
|
1139
|
+
* the one that was made first), replaced whole when what is there isn't a salt.
|
|
1140
|
+
*/
|
|
1141
|
+
function ensureSalt(home) {
|
|
1142
|
+
const f = personSaltFile(home);
|
|
1143
|
+
if (TOKEN_RE.test(readTrim(f) ?? ""))
|
|
1144
|
+
return;
|
|
1145
|
+
if (!existsSync(f)) {
|
|
1146
|
+
try {
|
|
1147
|
+
writeFileSync(f, randomBytes(32).toString("base64url"), { mode: 0o600, flag: "wx" });
|
|
1148
|
+
return;
|
|
823
1149
|
}
|
|
824
1150
|
catch {
|
|
825
|
-
|
|
1151
|
+
// made meanwhile by another process: that one, if it is a salt
|
|
1152
|
+
if (TOKEN_RE.test(readTrim(f) ?? ""))
|
|
1153
|
+
return;
|
|
826
1154
|
}
|
|
1155
|
+
}
|
|
1156
|
+
writeWhole(f, randomBytes(32).toString("base64url"));
|
|
1157
|
+
}
|
|
1158
|
+
/**
|
|
1159
|
+
* Whether `token` is the one the identity keys `spk` derive in `home` (its salt), and the home's
|
|
1160
|
+
* files are its own. Run against the keys a command actually loaded (App.load), so a home whose
|
|
1161
|
+
* files changed after the token was checked never lends the token to other keys.
|
|
1162
|
+
*/
|
|
1163
|
+
export function personTokenMatchesKeys(home, spk, token) {
|
|
1164
|
+
if (!homeFilesOwn(home))
|
|
1165
|
+
return false;
|
|
1166
|
+
const salt = readTrim(personSaltFile(home));
|
|
1167
|
+
if (!salt || !TOKEN_RE.test(salt))
|
|
1168
|
+
return false;
|
|
1169
|
+
return same(token, deriveToken(spk, salt));
|
|
1170
|
+
}
|
|
1171
|
+
/**
|
|
1172
|
+
* The person token, made or brought up to date in the CLI's own folder (0600; the mod's guards keep
|
|
1173
|
+
* the model from it). With an identity here: the derived token, written to person.key when the
|
|
1174
|
+
* file holds anything else (a home from before derived tokens, a front end's random first-run
|
|
1175
|
+
* value), never into a home whose files aren't its own (homeFilesOwn: "" then). Without one: the
|
|
1176
|
+
* random first-run token, made once, exclusively.
|
|
1177
|
+
*/
|
|
1178
|
+
export function personToken(home) {
|
|
1179
|
+
const f = personTokenFile(home);
|
|
1180
|
+
if (identityHere(home)) {
|
|
1181
|
+
if (!homeFilesOwn(home))
|
|
1182
|
+
return "";
|
|
1183
|
+
ensureSalt(home);
|
|
1184
|
+
const want = derivedToken(home);
|
|
1185
|
+
if (!want)
|
|
1186
|
+
return "";
|
|
1187
|
+
if (readTrim(f) !== want)
|
|
1188
|
+
writeWhole(f, want);
|
|
1189
|
+
return want;
|
|
1190
|
+
}
|
|
1191
|
+
const read = () => {
|
|
1192
|
+
const t = readTrim(f);
|
|
1193
|
+
return t && TOKEN_RE.test(t) ? t : undefined;
|
|
827
1194
|
};
|
|
828
1195
|
const have = read();
|
|
829
1196
|
if (have)
|
|
@@ -842,22 +1209,84 @@ export function personToken(home) {
|
|
|
842
1209
|
throw new CliError("conflict", `${f} isn't a person token: remove it and run the command again`);
|
|
843
1210
|
}
|
|
844
1211
|
}
|
|
845
|
-
/**
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
1212
|
+
/**
|
|
1213
|
+
* Replaces the person token with a fresh one. Called whenever an identity is first created or
|
|
1214
|
+
* restored on a home (init, link join, backup restore; setup and join create through init; the new
|
|
1215
|
+
* home a rotation makes), with the new identity's device signing seed (`spk`): a fresh salt, and
|
|
1216
|
+
* the token it derives. A person.key that was already there may have been put there by anything
|
|
1217
|
+
* that could write the folder before the identity existed, so it must not keep standing in for the
|
|
1218
|
+
* person afterwards (it never verifies against the derived token). The command that creates the
|
|
1219
|
+
* identity checked its token when it started, so a front end's first run still works; the front
|
|
1220
|
+
* ends read person.key again when the CLI refuses their old token (`person_token_stale`). Written
|
|
1221
|
+
* whole, before any key is written: if this fails, no identity is made here.
|
|
1222
|
+
*/
|
|
1223
|
+
export function renewPersonToken(home, spk) {
|
|
1224
|
+
const salt = randomBytes(32).toString("base64url");
|
|
1225
|
+
const t = spk ? deriveToken(spk, salt) : randomBytes(32).toString("base64url");
|
|
851
1226
|
try {
|
|
852
|
-
|
|
1227
|
+
writeWhole(personSaltFile(home), salt);
|
|
1228
|
+
writeWhole(personTokenFile(home), t);
|
|
1229
|
+
}
|
|
1230
|
+
catch (e) {
|
|
1231
|
+
throw new CliError("conflict", `couldn't replace the person token in ${personTokenFile(home)} (${e.code ?? "error"}): nothing was set up here. Remove that file and run the command again`);
|
|
1232
|
+
}
|
|
1233
|
+
return t;
|
|
1234
|
+
}
|
|
1235
|
+
const RENAME_BUSY = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
1236
|
+
function isDirectory(p) {
|
|
1237
|
+
try {
|
|
1238
|
+
return lstatSync(p).isDirectory();
|
|
853
1239
|
}
|
|
854
1240
|
catch {
|
|
855
1241
|
return false;
|
|
856
1242
|
}
|
|
1243
|
+
}
|
|
1244
|
+
/** Whether `home` holds an identity: its keys and self documents (state.ts keeps them at <home>/cli/keys.json and self.json). */
|
|
1245
|
+
export function identityHere(home) {
|
|
1246
|
+
// Both documents, as App.load requires: keys alone are an identity whose creation didn't finish.
|
|
1247
|
+
return existsSync(join(home, "cli", "keys.json")) && existsSync(join(home, "cli", "self.json"));
|
|
1248
|
+
}
|
|
1249
|
+
/**
|
|
1250
|
+
* Whether P2P_PERSON_TOKEN is this home's person token (read only). It must be what person.key
|
|
1251
|
+
* holds (a missing file is no match) and, on a home with an identity, the token that identity
|
|
1252
|
+
* derives (recomputed here: a person.key written by anything else never verifies). Never on a home
|
|
1253
|
+
* whose files aren't its own (homeFilesOwn).
|
|
1254
|
+
*/
|
|
1255
|
+
export function personTokenOk(env, home) {
|
|
1256
|
+
const given = env?.P2P_PERSON_TOKEN?.trim();
|
|
1257
|
+
if (!given || typeof home !== "string" || home === "")
|
|
1258
|
+
return false;
|
|
1259
|
+
if (!homeFilesOwn(home))
|
|
1260
|
+
return false;
|
|
1261
|
+
const t = readTrim(personTokenFile(home));
|
|
1262
|
+
if (t === undefined || !same(given, t))
|
|
1263
|
+
return false;
|
|
1264
|
+
if (!identityHere(home))
|
|
1265
|
+
return true;
|
|
1266
|
+
const want = derivedToken(home);
|
|
1267
|
+
return want !== undefined && same(given, want);
|
|
1268
|
+
}
|
|
1269
|
+
function same(given, t) {
|
|
857
1270
|
const a = Buffer.from(given);
|
|
858
1271
|
const b = Buffer.from(t);
|
|
859
1272
|
return a.length === b.length && b.length >= 32 && timingSafeEqual(a, b);
|
|
860
1273
|
}
|
|
1274
|
+
/**
|
|
1275
|
+
* After a refused token: brings a person.key that holds something else (a front end's first-run
|
|
1276
|
+
* value on a home that has an identity now, one from before derived tokens) up to the derived token,
|
|
1277
|
+
* so the front end that reads it again gets one that verifies. A missing person.key stays missing
|
|
1278
|
+
* (the next command makes it), and nothing is written into a home whose files aren't its own.
|
|
1279
|
+
*/
|
|
1280
|
+
export function healPersonToken(home) {
|
|
1281
|
+
if (!identityHere(home) || !existsSync(personTokenFile(home)))
|
|
1282
|
+
return;
|
|
1283
|
+
try {
|
|
1284
|
+
personToken(home);
|
|
1285
|
+
}
|
|
1286
|
+
catch {
|
|
1287
|
+
// the next command tries again
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
861
1290
|
/**
|
|
862
1291
|
* Checks the person token once, at the start of a command, and takes it out of the environment
|
|
863
1292
|
* (this object and the process's), so no child (git, ix, an extension's tool) ever inherits it.
|
|
@@ -875,12 +1304,24 @@ export function takePersonToken(env, home) {
|
|
|
875
1304
|
* flag: a process detached from every terminal can't give it). Reads are never asked, except for
|
|
876
1305
|
* the person's own messages (history.ts), which pass their own `why`.
|
|
877
1306
|
*/
|
|
878
|
-
export async function assertPersonForWidening(app, what, confirm, why = "changes who reaches you") {
|
|
879
|
-
|
|
1307
|
+
export async function assertPersonForWidening(app, what, confirm, why = "changes who reaches you", opts = {}) {
|
|
1308
|
+
// `noTokenBeforeIdentity`: what makes this device someone's (a link code makes it the code's
|
|
1309
|
+
// identity; setup links or joins). On a home with no identity yet the person token doesn't stand
|
|
1310
|
+
// in for the person there: no front end runs these (link and setup are refused in the Claude mod
|
|
1311
|
+
// and the Codex bridge), and a person.key on a fresh home may have been put there by anything that
|
|
1312
|
+
// can write the folder. (`join` and `accept` keep it: the mod's typed /peers join on a fresh
|
|
1313
|
+
// install is the documented first run.)
|
|
1314
|
+
const tokenCounts = !opts.noTokenBeforeIdentity || (typeof app.home === "string" && identityHere(app.home));
|
|
1315
|
+
if (app.front === true && tokenCounts)
|
|
880
1316
|
return;
|
|
881
1317
|
if (agentContext(app.env)) {
|
|
882
1318
|
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
1319
|
}
|
|
1320
|
+
// Fail closed: a process tree that couldn't be read (no /proc, no system `ps`, a process gone
|
|
1321
|
+
// mid-walk) may be an agent's session. The person's token still works (above).
|
|
1322
|
+
if (ancestryUnknown()) {
|
|
1323
|
+
throw new CliError("refused", `\`p2p ${what}\` ${why}, so only you run it: with /peers in Claude Code, or with your person token (P2P_PERSON_TOKEN). It was refused here because p2p couldn't read its process tree to tell whether it runs inside an agent's session${ancestryWhy() ? ` (${ancestryWhy()})` : ""}`);
|
|
1324
|
+
}
|
|
884
1325
|
if (!(await confirm(`p2p ${what} ${why}.`))) {
|
|
885
1326
|
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
1327
|
}
|
|
@@ -904,6 +1345,10 @@ export async function assertSpeaksFor(app, sid) {
|
|
|
904
1345
|
export function personHere(app) {
|
|
905
1346
|
return app.front === true || !agentContext(app.env);
|
|
906
1347
|
}
|
|
1348
|
+
/** personHere for a person-only act: an unreadable process tree counts as an agent's session (fail closed). */
|
|
1349
|
+
export function personHereStrict(app) {
|
|
1350
|
+
return app.front === true || (!agentContext(app.env) && !ancestryUnknown());
|
|
1351
|
+
}
|
|
907
1352
|
export async function sessionBinding(app, sid) {
|
|
908
1353
|
return (await app.state.get("sessionProjects"))?.[sid];
|
|
909
1354
|
}
|
|
@@ -1038,7 +1483,7 @@ export async function sessionCeiling(app, sid, binding) {
|
|
|
1038
1483
|
const ppl = [...(people ?? [])].filter((u) => !blocks.has(u) && u !== app.userId && friends.has(u));
|
|
1039
1484
|
if (joined.length + ppl.length === 0) {
|
|
1040
1485
|
const names = [...new Set(shares.map((x) => x.name))];
|
|
1041
|
-
return privateOf([{ cause: "disjoint", why: names.length > 1 ? `its projects (${names
|
|
1486
|
+
return privateOf([{ cause: "disjoint", why: names.length > 1 ? `its projects (${nameList(names)}) share nobody in common` : `${names[0]} shares nobody you can reach` }], names);
|
|
1042
1487
|
}
|
|
1043
1488
|
return { kind: "shared", circles: joined.sort(), people: ppl.sort() };
|
|
1044
1489
|
}
|
|
@@ -1077,9 +1522,14 @@ export async function ceilingAudience(app, c) {
|
|
|
1077
1522
|
out.delete(u);
|
|
1078
1523
|
return out;
|
|
1079
1524
|
}
|
|
1525
|
+
/** Project names for a message: the first MESSAGE_NAMES, then how many more (`p2p session show` lists them all). */
|
|
1526
|
+
const MESSAGE_NAMES = 16;
|
|
1527
|
+
function nameList(names) {
|
|
1528
|
+
return `${names.slice(0, MESSAGE_NAMES).join(", ")}${names.length > MESSAGE_NAMES ? ` and ${names.length - MESSAGE_NAMES} more` : ""}`;
|
|
1529
|
+
}
|
|
1080
1530
|
/** 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
1531
|
export function shareHint(names) {
|
|
1082
|
-
const what = names.length === 1 ? `the project ${names[0]}` : `each of ${names
|
|
1532
|
+
const what = names.length === 1 ? `the project ${names[0]}` : `each of ${nameList(names)}`;
|
|
1083
1533
|
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
1534
|
}
|
|
1085
1535
|
/**
|
|
@@ -1100,7 +1550,7 @@ export async function assertMayReach(app, sid, userId, o = {}) {
|
|
|
1100
1550
|
const who = o.address ?? (await app.addressOf(userId));
|
|
1101
1551
|
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
1552
|
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
|
|
1553
|
+
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)}`, {
|
|
1104
1554
|
delivered: false,
|
|
1105
1555
|
project: { names, policy: c.kind, ...(c.kind === "private" ? { causes: c.causes, ...(stickyPrivate(c) ? { sticky: true } : {}) } : {}) },
|
|
1106
1556
|
});
|
|
@@ -1354,6 +1804,14 @@ export function projectGraphTarget(app, ref, doc) {
|
|
|
1354
1804
|
export function describeGraphTarget(t) {
|
|
1355
1805
|
return t.kind === "local" ? `${GRAPH_LOCAL_ONLY} (${t.endpoint})` : `the shared graph of circle ${t.circle} (${t.endpoint})`;
|
|
1356
1806
|
}
|
|
1807
|
+
/** A target with, for a local one, why: the one wording `p2p project show|ls` and `p2p doctor` print. */
|
|
1808
|
+
export function graphTargetLine(t) {
|
|
1809
|
+
return `${describeGraphTarget(t)}${t.kind === "local" && t.why ? `: ${t.why}` : ""}`;
|
|
1810
|
+
}
|
|
1811
|
+
/** Who can read what a graph target holds: Ix keeps it in plaintext (docs/security/encryption.md). */
|
|
1812
|
+
export function graphPlaintextNote(t) {
|
|
1813
|
+
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";
|
|
1814
|
+
}
|
|
1357
1815
|
/**
|
|
1358
1816
|
* The Ix variables that could send an `ix` call somewhere other than its graph target, or carry a
|
|
1359
1817
|
* cloud credential: Ix Pro's PAT mode (IX_PAT, IX_ORG, its endpoint override), the cloud push and
|