@peer2peer/cli 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -11
- package/dist/app.d.ts +78 -0
- package/dist/app.js +150 -39
- package/dist/cli.d.ts +24 -3
- package/dist/cli.js +244 -29
- package/dist/config.d.ts +5 -0
- package/dist/doctor.d.ts +71 -2
- package/dist/doctor.js +95 -16
- package/dist/ext-host.js +5 -1
- package/dist/extensions.js +2 -2
- package/dist/identity.d.ts +29 -3
- package/dist/identity.js +74 -12
- 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 +9 -2
- package/dist/projects.d.ts +70 -3
- package/dist/projects.js +305 -19
- package/dist/rotation.js +15 -7
- 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/package.json +6 -3
package/dist/projects.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
// session: never bound, no ceiling.
|
|
23
23
|
import { agentAncestor, isAgentProcess } from "./ancestry.js";
|
|
24
24
|
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
25
|
-
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
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.
|
|
@@ -842,6 +1049,65 @@ export function personToken(home) {
|
|
|
842
1049
|
throw new CliError("conflict", `${f} isn't a person token: remove it and run the command again`);
|
|
843
1050
|
}
|
|
844
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
|
+
}
|
|
845
1111
|
/** Whether P2P_PERSON_TOKEN is this home's person token (read only: a missing file is no match). */
|
|
846
1112
|
export function personTokenOk(env, home) {
|
|
847
1113
|
const given = env?.P2P_PERSON_TOKEN?.trim();
|
|
@@ -875,8 +1141,15 @@ export function takePersonToken(env, home) {
|
|
|
875
1141
|
* flag: a process detached from every terminal can't give it). Reads are never asked, except for
|
|
876
1142
|
* the person's own messages (history.ts), which pass their own `why`.
|
|
877
1143
|
*/
|
|
878
|
-
export async function assertPersonForWidening(app, what, confirm, why = "changes who reaches you") {
|
|
879
|
-
|
|
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)
|
|
880
1153
|
return;
|
|
881
1154
|
if (agentContext(app.env)) {
|
|
882
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`);
|
|
@@ -1038,7 +1311,7 @@ export async function sessionCeiling(app, sid, binding) {
|
|
|
1038
1311
|
const ppl = [...(people ?? [])].filter((u) => !blocks.has(u) && u !== app.userId && friends.has(u));
|
|
1039
1312
|
if (joined.length + ppl.length === 0) {
|
|
1040
1313
|
const names = [...new Set(shares.map((x) => x.name))];
|
|
1041
|
-
return privateOf([{ cause: "disjoint", why: names.length > 1 ? `its projects (${names
|
|
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);
|
|
1042
1315
|
}
|
|
1043
1316
|
return { kind: "shared", circles: joined.sort(), people: ppl.sort() };
|
|
1044
1317
|
}
|
|
@@ -1077,9 +1350,14 @@ export async function ceilingAudience(app, c) {
|
|
|
1077
1350
|
out.delete(u);
|
|
1078
1351
|
return out;
|
|
1079
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
|
+
}
|
|
1080
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. */
|
|
1081
1359
|
export function shareHint(names) {
|
|
1082
|
-
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)}`;
|
|
1083
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)`;
|
|
1084
1362
|
}
|
|
1085
1363
|
/**
|
|
@@ -1100,7 +1378,7 @@ export async function assertMayReach(app, sid, userId, o = {}) {
|
|
|
1100
1378
|
const who = o.address ?? (await app.addressOf(userId));
|
|
1101
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"}`;
|
|
1102
1380
|
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
|
|
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)}`, {
|
|
1104
1382
|
delivered: false,
|
|
1105
1383
|
project: { names, policy: c.kind, ...(c.kind === "private" ? { causes: c.causes, ...(stickyPrivate(c) ? { sticky: true } : {}) } : {}) },
|
|
1106
1384
|
});
|
|
@@ -1354,6 +1632,14 @@ export function projectGraphTarget(app, ref, doc) {
|
|
|
1354
1632
|
export function describeGraphTarget(t) {
|
|
1355
1633
|
return t.kind === "local" ? `${GRAPH_LOCAL_ONLY} (${t.endpoint})` : `the shared graph of circle ${t.circle} (${t.endpoint})`;
|
|
1356
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
|
+
}
|
|
1357
1643
|
/**
|
|
1358
1644
|
* The Ix variables that could send an `ix` call somewhere other than its graph target, or carry a
|
|
1359
1645
|
* cloud credential: Ix Pro's PAT mode (IX_PAT, IX_ORG, its endpoint override), the cloud push and
|
package/dist/rotation.js
CHANGED
|
@@ -64,6 +64,7 @@ import { deliverCircle, memberCaps, ownerPublish, signOwnJoin } from "./circle-o
|
|
|
64
64
|
import { accept, dropHeld, getHeld, hold, mintInvite, withHeldId } from "./social.js";
|
|
65
65
|
import { exportAll, exportCircle, mergeRemovals, sendSync } from "./sync.js";
|
|
66
66
|
import { linkJoin } from "./identity.js";
|
|
67
|
+
import { renewPersonToken } from "./projects.js";
|
|
67
68
|
import { makeEvent, receiving } from "./inbound.js";
|
|
68
69
|
const STEPS = ["created", "published", "devices", "social", "final", "done"];
|
|
69
70
|
const rotationDir = (home) => join(home, "rotation");
|
|
@@ -157,10 +158,10 @@ function certLabel(cert) {
|
|
|
157
158
|
return "";
|
|
158
159
|
}
|
|
159
160
|
}
|
|
160
|
-
/** Our own identity's chain, verified (or undefined). */
|
|
161
|
+
/** Our own identity's chain, verified (or undefined); pending heads never narrow our own view (#65 review M1). */
|
|
161
162
|
async function ownChain(app) {
|
|
162
163
|
const stored = await app.store.getIdentity(app.userId);
|
|
163
|
-
return stored && stored.versions.length > 0 ? IdentityChain.fromStored(stored) : undefined;
|
|
164
|
+
return stored && stored.versions.length > 0 ? IdentityChain.fromStored({ ...stored, pendingHeads: [] }) : undefined;
|
|
164
165
|
}
|
|
165
166
|
/**
|
|
166
167
|
* The newest version of our identity that is not a rotation's final one:
|
|
@@ -189,7 +190,8 @@ async function foreignRotations(app) {
|
|
|
189
190
|
return [];
|
|
190
191
|
const log = await app.store.getPublishLog();
|
|
191
192
|
const out = [];
|
|
192
|
-
|
|
193
|
+
// Every held tip, a stray's too (#74): a rotation on any held branch is the owner's to know about.
|
|
194
|
+
for (const t of chain.allTips()) {
|
|
193
195
|
if (t.rotation === undefined || log.published.includes(t.hash))
|
|
194
196
|
continue;
|
|
195
197
|
try {
|
|
@@ -505,8 +507,10 @@ async function begin(app, opts) {
|
|
|
505
507
|
}
|
|
506
508
|
else {
|
|
507
509
|
await app.connectAndDrain();
|
|
508
|
-
// Build on the relays' head: a stale view could miss a competing rotation or a new device.
|
|
509
|
-
|
|
510
|
+
// Build on the relays' head: a stale view could miss a competing rotation or a new device. #67: a listed
|
|
511
|
+
// relay serving versions that don't connect (a thief's, signed with the old identity key) is left out
|
|
512
|
+
// when the others confirm the head (App.ownStrictFallback): rotation is the remedy for exactly that.
|
|
513
|
+
await app.refreshIdentity(app.userId, app.relays, { force: true, strict: true, setAside: { unconnected: true } });
|
|
510
514
|
}
|
|
511
515
|
const view = await app.ownView();
|
|
512
516
|
const foreign = await foreignRotations(app);
|
|
@@ -585,6 +589,9 @@ async function begin(app, opts) {
|
|
|
585
589
|
await rm(home, { recursive: true, force: true });
|
|
586
590
|
const napp = await appAt(app, home);
|
|
587
591
|
const self = { name: base.name, relays: [...base.relays], createdAt: Date.now() };
|
|
592
|
+
// The new identity's home gets its own person token (projects.ts renewPersonToken), before its keys;
|
|
593
|
+
// front ends read it again.
|
|
594
|
+
renewPersonToken(home);
|
|
588
595
|
await napp.state.put("keys", newKeysDoc(newIk.userId, device, cert, newIk));
|
|
589
596
|
await napp.state.put("self", self);
|
|
590
597
|
await napp.load(true);
|
|
@@ -971,12 +978,13 @@ async function publishFinal(app, st) {
|
|
|
971
978
|
const ik = app.requireKeyholder("Publishing your old identity's final version");
|
|
972
979
|
const contesting = st.contest || (await foreignRotations(app)).length > 0;
|
|
973
980
|
await app.connect({ allowNone: true });
|
|
974
|
-
|
|
981
|
+
// #67: as in begin, a relay serving versions that don't connect is left out when the others confirm the head.
|
|
982
|
+
await app.refreshIdentity(app.userId, app.relays, contesting ? { force: true, quiet: true } : { force: true, strict: true, setAside: { unconnected: true } });
|
|
975
983
|
const chain = await ownChain(app);
|
|
976
984
|
if (!chain)
|
|
977
985
|
throw new CliError("no_identity", "this device holds no identity document for its user");
|
|
978
986
|
const tips = chain.tips();
|
|
979
|
-
const mine =
|
|
987
|
+
const mine = chain.allTips().find((t) => t.rotation !== undefined && rotationKey(t.rotation) === rotationKey(st.statement));
|
|
980
988
|
if (mine) {
|
|
981
989
|
// Published by an interrupted run: make sure the relays have it.
|
|
982
990
|
const r = await app.publishDoc(mine.jws, mine.relays);
|
package/dist/sessions.d.ts
CHANGED
|
@@ -241,6 +241,14 @@ export interface SendOpts {
|
|
|
241
241
|
* session is theirs, never bound to a project. Set only by those two paths, never from a flag.
|
|
242
242
|
*/
|
|
243
243
|
person?: boolean;
|
|
244
|
+
/**
|
|
245
|
+
* Set by sendMessage to whether a copy of this message may have reached a relay: true from the
|
|
246
|
+
* moment one is about to go out, and after delivery whether one did or was written to a relay
|
|
247
|
+
* whose answer never came. sendSharing undoes its share only while it is false.
|
|
248
|
+
*/
|
|
249
|
+
wire?: {
|
|
250
|
+
maybe: boolean;
|
|
251
|
+
};
|
|
244
252
|
}
|
|
245
253
|
export interface SendResult {
|
|
246
254
|
delivered: boolean;
|
package/dist/sessions.js
CHANGED
|
@@ -21,7 +21,7 @@ import { enqueue, flushOutbox, OUTBOX_RETRYABLE, OUTBOX_TTL_MS, retryable } from
|
|
|
21
21
|
import { basename, dirname, resolve as resolvePath } from "node:path";
|
|
22
22
|
import { createRosterV3, displayStatus, extensionFallbackText, FALLBACK_MAX, isExtensionKind, isLive, isSafeRelativePath, liveFriendshipsV3, loadCircle, partyAuthorizedV3, sanitizePeerText, sha256, standsLookup, circlePolicy, isStatusCap, STATUS_CAP_MAX_LEN, STATUS_CAPS_MAX, STATUS_CAP_RECEIPTS, STATUS_CAP_AGENTS, STATUS_AGENTS_MAX, STATUS_AGENT_FILES_MAX, STATUS_AGENT_TASK_MAX, isStatusAgentBranch, isStatusAgentFile, isStatusAgentId, isStatusAgentType, statusAgentsError, summaryWithAgents, redactSecrets, stripAbsolutePaths, parseBound, } from "@peer2peer/core/v3";
|
|
23
23
|
import { CliError } from "./errors.js";
|
|
24
|
-
import { assertMayReach, bindSession, ceilingAudience, defaultCircleNotice, friendIds, PERSON_SESSION, sessionBinding, agentContext, sessionCeiling, sessionProjectView, sessionDirs, sessionWorkdir, MAX_SESSION_DIRS, overWhys, privateRemedy, shareHint, } from "./projects.js";
|
|
24
|
+
import { assertMayReach, bindSession, ceilingAudience, defaultCircleNotice, friendIds, PERSON_SESSION, sessionBinding, agentContext, sessionCeiling, sessionProjectView, sessionDirs, sessionWorkdir, MAX_SESSION_DIRS, SCRATCH_ENV, sessionScratch, overWhys, privateRemedy, shareHint, } from "./projects.js";
|
|
25
25
|
import { renderExtension } from "./extensions.js";
|
|
26
26
|
import { fromOf, makeEvent } from "./inbound.js";
|
|
27
27
|
import { receiptsEnabled, statusCapsEnabled } from "./config.js";
|
|
@@ -711,9 +711,15 @@ async function rosterCircleOf(app, own, sid) {
|
|
|
711
711
|
/** `user`, `user [ref]`, `user/ref` or `user/sid`. */
|
|
712
712
|
export function parseTarget(to) {
|
|
713
713
|
const s = to.trim();
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
714
|
+
// `user [ref]`, scanned from the end (a backtracking regex here was quadratic on long whitespace runs).
|
|
715
|
+
const n = s.length;
|
|
716
|
+
if (n >= 8 && s[n - 1] === "]" && s[n - 8] === "[") {
|
|
717
|
+
const ref = s.slice(n - 7, n - 1);
|
|
718
|
+
const user = s.slice(0, n - 8).trimEnd();
|
|
719
|
+
// As /^(.*?)\s*\[([0-9a-f]{6})\]$/ did: `.` never spans a line break.
|
|
720
|
+
if (/^[0-9a-f]{6}$/.test(ref) && !/[\n\r\u2028\u2029]/.test(user))
|
|
721
|
+
return { user: user.trim(), pick: ref };
|
|
722
|
+
}
|
|
717
723
|
// userIds, addresses and petnames never contain "/", so the last one separates a session.
|
|
718
724
|
const i = s.lastIndexOf("/");
|
|
719
725
|
if (i > 0 && i < s.length - 1)
|
|
@@ -860,22 +866,41 @@ export async function tuiTaintNote(app, toUserId, now = Date.now()) {
|
|
|
860
866
|
export async function sendSharing(app, o) {
|
|
861
867
|
const sid = checkSid(o.fromSession, "--from-session");
|
|
862
868
|
const uid = await app.resolveUser(o.to.replace(/\s*\[[^\]]*\]\s*$/, "").replace(/\/[^/]*$/, ""));
|
|
863
|
-
let added
|
|
864
|
-
if (uid !== app.userId
|
|
865
|
-
await
|
|
866
|
-
|
|
869
|
+
let added;
|
|
870
|
+
if (uid !== app.userId) {
|
|
871
|
+
const had = await getSession(app, sid);
|
|
872
|
+
if (!(await rosterAudience(app, had)).includes(uid))
|
|
873
|
+
added = { ver: (await roster(app, sid, { add: [uid] })).ver, had };
|
|
867
874
|
}
|
|
875
|
+
const wire = { maybe: false };
|
|
868
876
|
try {
|
|
869
|
-
const result = await sendMessage(app, { ...o, person: true });
|
|
877
|
+
const result = await sendMessage(app, { ...o, person: true, wire });
|
|
870
878
|
return added ? { result, shared: { userId: uid, address: await app.addressOf(uid) } } : { result };
|
|
871
879
|
}
|
|
872
880
|
catch (e) {
|
|
873
|
-
//
|
|
874
|
-
|
|
875
|
-
|
|
881
|
+
// Undone only when nothing can have gone out (issue #3): a send cut off by the command deadline
|
|
882
|
+
// (`outcome_unknown`), or one a relay may have stored without answering, may have reached them,
|
|
883
|
+
// and their reply must still land here.
|
|
884
|
+
if (added && !wire.maybe)
|
|
885
|
+
await unshare(app, sid, uid, added).catch(() => undefined);
|
|
876
886
|
throw e;
|
|
877
887
|
}
|
|
878
888
|
}
|
|
889
|
+
/**
|
|
890
|
+
* Takes back the share sendSharing made for a send that never went out: only while the roster is
|
|
891
|
+
* still exactly the version that share wrote (issue #3). Anything since (another send's share, the
|
|
892
|
+
* person's own `session roster`, a status following the project) stands as it is. Back to whom it
|
|
893
|
+
* was shared with before, `uid` included if they were on it already, and following the default
|
|
894
|
+
* again if it did.
|
|
895
|
+
*/
|
|
896
|
+
async function unshare(app, sid, uid, added) {
|
|
897
|
+
await writeRoster(app, sid, (have) => {
|
|
898
|
+
if (!have || have.ver !== added.ver)
|
|
899
|
+
return undefined;
|
|
900
|
+
const parts = added.had.parts.includes(uid) ? have.parts : have.parts.filter((u) => u !== uid);
|
|
901
|
+
return { vis: have.vis, ...(have.circle ? { circle: have.circle } : {}), parts, ...(added.had.auto !== undefined ? { auto: added.had.auto } : {}) };
|
|
902
|
+
});
|
|
903
|
+
}
|
|
879
904
|
export async function sendMessage(app, o) {
|
|
880
905
|
const fromSession = checkSid(o.fromSession, "--from-session");
|
|
881
906
|
if (Buffer.byteLength(o.text, "utf8") > MAX_TEXT_BYTES)
|
|
@@ -903,6 +928,8 @@ export async function sendMessage(app, o) {
|
|
|
903
928
|
// whole message for `rcpt` (§4.3). Not when this device can't reach a relay either: the sealed copy
|
|
904
929
|
// may wait in the outbox for days, long past the status that advertised it (pre-release review R2).
|
|
905
930
|
const rcpt = o.text !== "" && !offline && offlineSince === undefined && (await asksReceipts(app, target.own, target.sid)) ? newReceiptId() : undefined;
|
|
931
|
+
// Whether a copy that may reach them still asks (below: copies kept for later are sealed without it).
|
|
932
|
+
let receiptAsked = rcpt !== undefined;
|
|
906
933
|
if (o.text !== "") {
|
|
907
934
|
// Anything this device couldn't send earlier goes first (order, and it may be the same peer).
|
|
908
935
|
if (!offline)
|
|
@@ -911,14 +938,42 @@ export async function sendMessage(app, o) {
|
|
|
911
938
|
const plaintext = { text: o.text, ...(rcpt ? { rcpt } : {}), ...(rosterJws ? { roster: rosterJws } : {}), ...(o.person ? {} : await ownBound(app, fromSession, target, userId)) };
|
|
912
939
|
if (rcpt)
|
|
913
940
|
await rememberWanted(app, rcpt, { to: userId, own: target.own, ref: to.ref, fromSession });
|
|
914
|
-
|
|
941
|
+
const local = userId === app.userId && target.did ? { onlyDevices: [target.did], ...localSend(app, target, fromSession, o.person === true) } : {};
|
|
942
|
+
d = await app.deliver(userId, "msg", target, plaintext, {
|
|
943
|
+
...local,
|
|
944
|
+
beforeSend: async (copies) => {
|
|
945
|
+
// From here a copy may go out (sendSharing's undo reads this).
|
|
946
|
+
if (o.wire)
|
|
947
|
+
o.wire.maybe = true;
|
|
948
|
+
await local.beforeSend?.(copies);
|
|
949
|
+
},
|
|
950
|
+
});
|
|
915
951
|
const unsent = d.unsent ?? [];
|
|
952
|
+
// The devices whose copy went out on a connection whose answer never came (it may be stored).
|
|
953
|
+
const written = new Set((d.errors ?? []).filter((e) => e.written).map((e) => e.did));
|
|
954
|
+
if (o.wire)
|
|
955
|
+
o.wire.maybe = d.relays.length > 0 || written.size > 0;
|
|
916
956
|
if (d.relays.length === 0 && !retryable(unsent)) {
|
|
917
957
|
throw new CliError("undelivered", `delivered via 0 relays${d.errors?.length ? ` (${[...new Set(d.errors.map((e) => e.code))].join(", ")})` : ""}`, { delivered: false, to });
|
|
918
958
|
}
|
|
919
959
|
// Copies no relay took, for reasons a retry gets past: kept, sealed, for watch to send. When
|
|
920
960
|
// other copies did go out the message is delivered already; these reach the other devices.
|
|
921
|
-
|
|
961
|
+
let later = d.relays.length === 0 ? unsent : unsent.filter((u) => u.codes.every((c) => OUTBOX_RETRYABLE.has(c)));
|
|
962
|
+
// A copy kept for later never asks for a receipt (issue #3, §4.3): it may go out days from now,
|
|
963
|
+
// after the recipient's client downgraded, and a client without receipts.v1 rejects the whole
|
|
964
|
+
// message for `rcpt`. Sealed again without it, unless it went out on a connection already (a
|
|
965
|
+
// relay may hold it: a second envelope could deliver the message twice; the outbox resends those
|
|
966
|
+
// same bytes, which the recipient's replay window drops).
|
|
967
|
+
if (rcpt && later.length > 0) {
|
|
968
|
+
const fresh = later.filter((u) => !written.has(u.did));
|
|
969
|
+
if (fresh.length > 0) {
|
|
970
|
+
const { rcpt: _asked, ...plain } = plaintext;
|
|
971
|
+
void _asked;
|
|
972
|
+
const resealed = await app.seal(userId, "msg", target, plain, { onlyDevices: fresh.map((u) => u.did), ...(local.beforeSend ? { beforeSend: local.beforeSend } : {}) });
|
|
973
|
+
later = [...later.filter((u) => written.has(u.did)), ...resealed.map((c) => ({ ...c, codes: [] }))];
|
|
974
|
+
}
|
|
975
|
+
receiptAsked = d.relays.length > 0 || later.some((u) => written.has(u.did));
|
|
976
|
+
}
|
|
922
977
|
if (later.length > 0)
|
|
923
978
|
outboxed = await enqueue(app, later, { kind: "msg", dest: to, fromSession });
|
|
924
979
|
}
|
|
@@ -948,7 +1003,7 @@ export async function sendMessage(app, o) {
|
|
|
948
1003
|
...(d ? { messageId: `m${Date.now().toString(36)}` } : {}),
|
|
949
1004
|
...(o.notifyWhenIdle ? { notifyWhenIdle: true } : {}),
|
|
950
1005
|
...queued,
|
|
951
|
-
...(d ? (rcpt ? { receipts: "requested", receiptId: rcpt } : { receipts: "unsupported" }) : {}),
|
|
1006
|
+
...(d ? (rcpt && receiptAsked ? { receipts: "requested", receiptId: rcpt } : { receipts: "unsupported" }) : {}),
|
|
952
1007
|
};
|
|
953
1008
|
}
|
|
954
1009
|
/**
|
|
@@ -1117,7 +1172,9 @@ export async function bindFromEnv(app, sid, extra = [], o = {}) {
|
|
|
1117
1172
|
const over = new Set([...why, ...(o.over ?? [])]);
|
|
1118
1173
|
if (extra.length > MAX_SESSION_DIRS)
|
|
1119
1174
|
over.add("folders");
|
|
1120
|
-
|
|
1175
|
+
// The session's own scratch, as its front end names it: only a front end holding the person token.
|
|
1176
|
+
const scratch = app.front === true ? sessionScratch(app.env[SCRATCH_ENV]) : undefined;
|
|
1177
|
+
await bindSession(app, sid, [...dirs, ...extra.slice(0, MAX_SESSION_DIRS)], { ...(o.person ? { person: true } : {}), ...(over.size > 0 ? { over: [...over] } : {}), ...(scratch ? { scratch } : {}) });
|
|
1121
1178
|
}
|
|
1122
1179
|
/** A front end's `--project-dirs-over` as reasons: a bare flag (an older front end) is `front`. */
|
|
1123
1180
|
function overOf(v) {
|