@peer2peer/cli 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/pretty.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // NO_COLOR, TERM=dumb (and FORCE_COLOR) decide `color` (tui/terminal.ts colorWanted).
12
12
  import { COLOR, PLAIN } from "./prompt/picker.js";
13
13
  import { cell, clean, displayWidth } from "./tui/sanitize.js";
14
+ import { shortCode } from "./format.js";
14
15
  import { DATA_FLOW_HEADING } from "./doctor.js";
15
16
  const styleOf = (p) => (p.color ? COLOR : PLAIN);
16
17
  const nowOf = (p) => p.now ?? Date.now() / 1000;
@@ -144,7 +145,7 @@ export function prettyCodes(rows, p) {
144
145
  return [
145
146
  heading(`Invites (${rows.length})`, st),
146
147
  table(["CODE", "FOR", "JOINS", "STATUS"], rows.map((r) => [
147
- t(r.status === "open" || r.status === "taken" ? r.code : r.code.replace(/[^/]*$/, (c) => `${c.slice(0, 4)}…`), 44, st.dim),
148
+ t((r.status === "open" || r.status === "taken") && !r.redacted ? r.code : shortCode(r.code), 44, st.dim),
148
149
  t(r.to ? clean(r.to.address) : (r.label ?? "anyone"), 28),
149
150
  t(r.circles.length ? r.circles.map((c) => clean(c.name)).join(", ") : "friend only", 32),
150
151
  status(r),
package/dist/procstart.js CHANGED
@@ -5,7 +5,7 @@
5
5
  // claim from another local process is found (rare), so a spawn is fine. Undefined when the
6
6
  // platform can't say cheaply: the caller then keeps going by the pid alone.
7
7
  import { execFileSync } from "node:child_process";
8
- import { readFileSync } from "node:fs";
8
+ import { existsSync, readFileSync } from "node:fs";
9
9
  let bootMs;
10
10
  function linuxStartMs(pid) {
11
11
  // Field 22 of /proc/<pid>/stat: start time in clock ticks after boot (USER_HZ, 100 on Linux).
@@ -22,9 +22,17 @@ function linuxStartMs(pid) {
22
22
  }
23
23
  return bootMs + (ticks / 100) * 1000;
24
24
  }
25
+ /** ps by absolute path (#99 review): never whatever `ps` comes first on PATH. */
26
+ const PS = ["/bin/ps", "/usr/bin/ps"].find((p) => existsSync(p));
25
27
  function psStartMs(pid) {
26
- const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], env: { LC_ALL: "C", PATH: process.env.PATH ?? "" } }).trim();
27
- const t = Date.parse(out);
28
+ if (!PS)
29
+ return undefined;
30
+ // TZ=UTC, and read back as UTC (#99 review): lstart prints local time without a zone, so a time zone change
31
+ // between two processes (automatic time zone, travel) would otherwise move every answer by hours.
32
+ const out = execFileSync(PS, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"], env: { LC_ALL: "C", TZ: "UTC" } }).trim();
33
+ if (!out)
34
+ return undefined;
35
+ const t = Date.parse(`${out} GMT`);
28
36
  return Number.isFinite(t) ? t : undefined;
29
37
  }
30
38
  /**
@@ -317,25 +317,67 @@ export declare function agentEnv(env: Record<string, string | undefined> | undef
317
317
  /** Whether this call runs on an agent's behalf: its environment, or a Claude Code or Codex ancestor (ancestry.ts). */
318
318
  export declare function agentContext(env: Record<string, string | undefined> | undefined): boolean;
319
319
  export { isAgentProcess };
320
- /** `<home>/cli/person.key`: a random secret the person's front ends (the Claude mod, the Codex bridge) pass back as P2P_PERSON_TOKEN. */
320
+ /**
321
+ * `<home>/cli/person.key`: the secret the person's front ends (the Claude mod, the Codex bridge)
322
+ * pass back as P2P_PERSON_TOKEN. On a home with an identity it is derived, never just stored: an
323
+ * HMAC under this device's signing key over the home's salt (`person.salt`, replaced whenever an
324
+ * identity is created or restored here), so a person.key that anything else wrote never verifies
325
+ * (personTokenOk recomputes it). On a fresh home (no identity yet) it is a random value, as the
326
+ * front ends make it on a first run.
327
+ */
321
328
  export declare function personTokenFile(home: string): string;
322
- /** The person token, made once (exclusively, 0600, in the CLI's own folder, which the mod's guards keep from the model). */
329
+ /** `<home>/cli/person.salt`: the per-home salt of the derived person token (replaced with the identity). */
330
+ export declare function personSaltFile(home: string): string;
331
+ /**
332
+ * Whether the files the person token rests on are this home's own: the `cli` folder, its keys and
333
+ * self documents, the token and its salt, and the `v3` store are no symbolic links, and the keys
334
+ * and self documents have one link each (the CLI writes them by rename, so a second hard link was
335
+ * made by something else). A home put together from links to another home's files (to pair that
336
+ * identity's keys with a token of the maker's choosing) is never the person's.
337
+ */
338
+ export declare function homeFilesOwn(home: string): boolean;
339
+ /**
340
+ * Whether `token` is the one the identity keys `spk` derive in `home` (its salt), and the home's
341
+ * files are its own. Run against the keys a command actually loaded (App.load), so a home whose
342
+ * files changed after the token was checked never lends the token to other keys.
343
+ */
344
+ export declare function personTokenMatchesKeys(home: string, spk: string, token: string): boolean;
345
+ /**
346
+ * The person token, made or brought up to date in the CLI's own folder (0600; the mod's guards keep
347
+ * the model from it). With an identity here: the derived token, written to person.key when the
348
+ * file holds anything else (a home from before derived tokens, a front end's random first-run
349
+ * value), never into a home whose files aren't its own (homeFilesOwn: "" then). Without one: the
350
+ * random first-run token, made once, exclusively.
351
+ */
323
352
  export declare function personToken(home: string): string;
324
353
  /**
325
354
  * Replaces the person token with a fresh one. Called whenever an identity is first created or
326
- * restored on a home (init, link join, backup restore; setup and join create through init): a
327
- * person.key that was already there may have been put there by anything that could write the
328
- * folder before the identity existed, so it must not keep standing in for the person afterwards.
329
- * The command that creates the identity checked its token when it started, so a front end's first
330
- * run still works; the front ends read person.key again when the CLI refuses their old token
331
- * (`person_token_stale`). Written whole: a new 0600 file made exclusively beside it, then renamed
332
- * over it (a planted symlink is replaced, never followed).
333
- */
334
- export declare function renewPersonToken(home: string): string;
355
+ * restored on a home (init, link join, backup restore; setup and join create through init; the new
356
+ * home a rotation makes), with the new identity's device signing seed (`spk`): a fresh salt, and
357
+ * the token it derives. A person.key that was already there may have been put there by anything
358
+ * that could write the folder before the identity existed, so it must not keep standing in for the
359
+ * person afterwards (it never verifies against the derived token). The command that creates the
360
+ * identity checked its token when it started, so a front end's first run still works; the front
361
+ * ends read person.key again when the CLI refuses their old token (`person_token_stale`). Written
362
+ * whole, before any key is written: if this fails, no identity is made here.
363
+ */
364
+ export declare function renewPersonToken(home: string, spk?: string): string;
335
365
  /** Whether `home` holds an identity: its keys and self documents (state.ts keeps them at <home>/cli/keys.json and self.json). */
336
366
  export declare function identityHere(home: string): boolean;
337
- /** Whether P2P_PERSON_TOKEN is this home's person token (read only: a missing file is no match). */
367
+ /**
368
+ * Whether P2P_PERSON_TOKEN is this home's person token (read only). It must be what person.key
369
+ * holds (a missing file is no match) and, on a home with an identity, the token that identity
370
+ * derives (recomputed here: a person.key written by anything else never verifies). Never on a home
371
+ * whose files aren't its own (homeFilesOwn).
372
+ */
338
373
  export declare function personTokenOk(env: Record<string, string | undefined> | undefined, home: string | undefined): boolean;
374
+ /**
375
+ * After a refused token: brings a person.key that holds something else (a front end's first-run
376
+ * value on a home that has an identity now, one from before derived tokens) up to the derived token,
377
+ * so the front end that reads it again gets one that verifies. A missing person.key stays missing
378
+ * (the next command makes it), and nothing is written into a home whose files aren't its own.
379
+ */
380
+ export declare function healPersonToken(home: string): void;
339
381
  /**
340
382
  * Checks the person token once, at the start of a command, and takes it out of the environment
341
383
  * (this object and the process's), so no child (git, ix, an extension's tool) ever inherits it.
@@ -366,6 +408,10 @@ export declare function assertSpeaksFor(app: App, sid: string): Promise<void>;
366
408
  export declare function personHere(app: Pick<App, "env"> & {
367
409
  front?: boolean;
368
410
  }): boolean;
411
+ /** personHere for a person-only act: an unreadable process tree counts as an agent's session (fail closed). */
412
+ export declare function personHereStrict(app: Pick<App, "env"> & {
413
+ front?: boolean;
414
+ }): boolean;
369
415
  export declare function sessionBinding(app: App, sid: string): Promise<SessionBinding | undefined>;
370
416
  /** One reason a session is private, as said to the person (and to a model that reads a refusal). */
371
417
  export interface PrivateReason {
package/dist/projects.js CHANGED
@@ -20,13 +20,14 @@
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";
23
+ import { agentAncestor, ancestryUnknown, ancestryWhy, isAgentProcess } from "./ancestry.js";
24
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
25
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";
29
29
  import { CliError } from "./errors.js";
30
+ import { signingSeedSync } from "./keystore.js";
30
31
  /** The person's own terminal session (`p2p tui`, `p2p send` with no --from-session). */
31
32
  export const PERSON_SESSION = "tui";
32
33
  /** The committed file a repository may carry to ask for privacy (it can never widen anything). */
@@ -1015,57 +1016,93 @@ export function agentContext(env) {
1015
1016
  return agentEnv(env) || agentAncestor();
1016
1017
  }
1017
1018
  export { isAgentProcess };
1018
- /** `<home>/cli/person.key`: a random secret the person's front ends (the Claude mod, the Codex bridge) pass back as P2P_PERSON_TOKEN. */
1019
+ /**
1020
+ * `<home>/cli/person.key`: the secret the person's front ends (the Claude mod, the Codex bridge)
1021
+ * pass back as P2P_PERSON_TOKEN. On a home with an identity it is derived, never just stored: an
1022
+ * HMAC under this device's signing key over the home's salt (`person.salt`, replaced whenever an
1023
+ * identity is created or restored here), so a person.key that anything else wrote never verifies
1024
+ * (personTokenOk recomputes it). On a fresh home (no identity yet) it is a random value, as the
1025
+ * front ends make it on a first run.
1026
+ */
1019
1027
  export function personTokenFile(home) {
1020
1028
  return join(home, "cli", "person.key");
1021
1029
  }
1030
+ /** `<home>/cli/person.salt`: the per-home salt of the derived person token (replaced with the identity). */
1031
+ export function personSaltFile(home) {
1032
+ return join(home, "cli", "person.salt");
1033
+ }
1022
1034
  const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/;
1023
- /** The person token, made once (exclusively, 0600, in the CLI's own folder, which the mod's guards keep from the model). */
1024
- export function personToken(home) {
1025
- const f = personTokenFile(home);
1026
- const read = () => {
1027
- try {
1028
- const t = readFileSync(f, "utf8").trim();
1029
- return TOKEN_RE.test(t) ? t : undefined;
1030
- }
1031
- catch {
1032
- return undefined;
1033
- }
1034
- };
1035
- const have = read();
1036
- if (have)
1037
- return have;
1038
- mkdirSync(join(home, "cli"), { recursive: true, mode: 0o700 });
1039
- const t = randomBytes(32).toString("base64url");
1035
+ const TOKEN_LABEL = "peer2peer/person-token/v1\0";
1036
+ /** The token for `spk` (a device's b64u signing seed) and `salt`: base64url of HMAC-SHA256, 43 characters. */
1037
+ function deriveToken(spk, salt) {
1038
+ return createHmac("sha256", Buffer.from(spk, "base64url")).update(TOKEN_LABEL).update(salt).digest("base64url");
1039
+ }
1040
+ function readTrim(f) {
1040
1041
  try {
1041
- writeFileSync(f, t, { mode: 0o600, flag: "wx" });
1042
- return t;
1042
+ return readFileSync(f, "utf8").trim();
1043
1043
  }
1044
1044
  catch {
1045
- // Made meanwhile by another process (or a file in the way): that one, if it is a token.
1046
- const again = read();
1047
- if (again)
1048
- return again;
1049
- throw new CliError("conflict", `${f} isn't a person token: remove it and run the command again`);
1045
+ return undefined;
1050
1046
  }
1051
1047
  }
1052
1048
  /**
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).
1049
+ * Whether the files the person token rests on are this home's own: the `cli` folder, its keys and
1050
+ * self documents, the token and its salt, and the `v3` store are no symbolic links, and the keys
1051
+ * and self documents have one link each (the CLI writes them by rename, so a second hard link was
1052
+ * made by something else). A home put together from links to another home's files (to pair that
1053
+ * identity's keys with a token of the maker's choosing) is never the person's.
1061
1054
  */
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");
1055
+ export function homeFilesOwn(home) {
1056
+ const cli = join(home, "cli");
1057
+ try {
1058
+ const d = lstatSync(cli);
1059
+ if (d.isSymbolicLink() || !d.isDirectory())
1060
+ return false;
1061
+ }
1062
+ catch (e) {
1063
+ return e.code === "ENOENT";
1064
+ }
1065
+ const checks = [
1066
+ [join(cli, "keys.json"), true],
1067
+ [join(cli, "self.json"), true],
1068
+ [personTokenFile(home), false],
1069
+ [personSaltFile(home), false],
1070
+ [join(home, "v3"), false],
1071
+ ];
1072
+ for (const [p, single] of checks) {
1073
+ let st;
1074
+ try {
1075
+ st = lstatSync(p);
1076
+ }
1077
+ catch (e) {
1078
+ if (e.code === "ENOENT")
1079
+ continue;
1080
+ return false;
1081
+ }
1082
+ if (st.isSymbolicLink())
1083
+ return false;
1084
+ if (single && st.nlink !== 1)
1085
+ return false;
1086
+ }
1087
+ return true;
1088
+ }
1089
+ /** The person token this home's identity derives (undefined: no identity, no salt yet, or keys that can't be read). */
1090
+ function derivedToken(home) {
1091
+ if (!identityHere(home))
1092
+ return undefined;
1093
+ const salt = readTrim(personSaltFile(home));
1094
+ if (!salt || !TOKEN_RE.test(salt))
1095
+ return undefined;
1096
+ // From keys.json, or from the OS keychain when the keys are kept there (keystore.ts).
1097
+ const spk = signingSeedSync(home);
1098
+ return spk ? deriveToken(spk, salt) : undefined;
1099
+ }
1100
+ /** Writes `text` to `f` whole: a new 0600 file made exclusively beside it, renamed over it (a planted symlink is replaced, not followed). */
1101
+ function writeWhole(f, text) {
1102
+ mkdirSync(dirname(f), { recursive: true, mode: 0o700 });
1066
1103
  const tmp = `${f}.${randomBytes(6).toString("hex")}.tmp`;
1067
1104
  try {
1068
- writeFileSync(tmp, t, { mode: 0o600, flag: "wx" });
1105
+ writeFileSync(tmp, text, { mode: 0o600, flag: "wx" });
1069
1106
  let cleared = false;
1070
1107
  for (let tries = 0;; tries++) {
1071
1108
  try {
@@ -1073,7 +1110,7 @@ export function renewPersonToken(home) {
1073
1110
  break;
1074
1111
  }
1075
1112
  catch (e) {
1076
- // Something that isn't a file is in the way (a directory): it goes, then the new token.
1113
+ // Something that isn't a file is in the way (a directory): it goes, then the new file.
1077
1114
  if (!cleared && isDirectory(f)) {
1078
1115
  rmSync(f, { recursive: true, force: true });
1079
1116
  cleared = true;
@@ -1090,7 +1127,104 @@ export function renewPersonToken(home) {
1090
1127
  }
1091
1128
  catch (e) {
1092
1129
  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`);
1130
+ throw e;
1131
+ }
1132
+ }
1133
+ /**
1134
+ * The home's salt, made once: exclusively when there is none (two first runs at once agree on
1135
+ * the one that was made first), replaced whole when what is there isn't a salt.
1136
+ */
1137
+ function ensureSalt(home) {
1138
+ const f = personSaltFile(home);
1139
+ if (TOKEN_RE.test(readTrim(f) ?? ""))
1140
+ return;
1141
+ if (!existsSync(f)) {
1142
+ try {
1143
+ writeFileSync(f, randomBytes(32).toString("base64url"), { mode: 0o600, flag: "wx" });
1144
+ return;
1145
+ }
1146
+ catch {
1147
+ // made meanwhile by another process: that one, if it is a salt
1148
+ if (TOKEN_RE.test(readTrim(f) ?? ""))
1149
+ return;
1150
+ }
1151
+ }
1152
+ writeWhole(f, randomBytes(32).toString("base64url"));
1153
+ }
1154
+ /**
1155
+ * Whether `token` is the one the identity keys `spk` derive in `home` (its salt), and the home's
1156
+ * files are its own. Run against the keys a command actually loaded (App.load), so a home whose
1157
+ * files changed after the token was checked never lends the token to other keys.
1158
+ */
1159
+ export function personTokenMatchesKeys(home, spk, token) {
1160
+ if (!homeFilesOwn(home))
1161
+ return false;
1162
+ const salt = readTrim(personSaltFile(home));
1163
+ if (!salt || !TOKEN_RE.test(salt))
1164
+ return false;
1165
+ return same(token, deriveToken(spk, salt));
1166
+ }
1167
+ /**
1168
+ * The person token, made or brought up to date in the CLI's own folder (0600; the mod's guards keep
1169
+ * the model from it). With an identity here: the derived token, written to person.key when the
1170
+ * file holds anything else (a home from before derived tokens, a front end's random first-run
1171
+ * value), never into a home whose files aren't its own (homeFilesOwn: "" then). Without one: the
1172
+ * random first-run token, made once, exclusively.
1173
+ */
1174
+ export function personToken(home) {
1175
+ const f = personTokenFile(home);
1176
+ if (identityHere(home)) {
1177
+ if (!homeFilesOwn(home))
1178
+ return "";
1179
+ ensureSalt(home);
1180
+ const want = derivedToken(home);
1181
+ if (!want)
1182
+ return "";
1183
+ if (readTrim(f) !== want)
1184
+ writeWhole(f, want);
1185
+ return want;
1186
+ }
1187
+ const read = () => {
1188
+ const t = readTrim(f);
1189
+ return t && TOKEN_RE.test(t) ? t : undefined;
1190
+ };
1191
+ const have = read();
1192
+ if (have)
1193
+ return have;
1194
+ mkdirSync(join(home, "cli"), { recursive: true, mode: 0o700 });
1195
+ const t = randomBytes(32).toString("base64url");
1196
+ try {
1197
+ writeFileSync(f, t, { mode: 0o600, flag: "wx" });
1198
+ return t;
1199
+ }
1200
+ catch {
1201
+ // Made meanwhile by another process (or a file in the way): that one, if it is a token.
1202
+ const again = read();
1203
+ if (again)
1204
+ return again;
1205
+ throw new CliError("conflict", `${f} isn't a person token: remove it and run the command again`);
1206
+ }
1207
+ }
1208
+ /**
1209
+ * Replaces the person token with a fresh one. Called whenever an identity is first created or
1210
+ * restored on a home (init, link join, backup restore; setup and join create through init; the new
1211
+ * home a rotation makes), with the new identity's device signing seed (`spk`): a fresh salt, and
1212
+ * the token it derives. A person.key that was already there may have been put there by anything
1213
+ * that could write the folder before the identity existed, so it must not keep standing in for the
1214
+ * person afterwards (it never verifies against the derived token). The command that creates the
1215
+ * identity checked its token when it started, so a front end's first run still works; the front
1216
+ * ends read person.key again when the CLI refuses their old token (`person_token_stale`). Written
1217
+ * whole, before any key is written: if this fails, no identity is made here.
1218
+ */
1219
+ export function renewPersonToken(home, spk) {
1220
+ const salt = randomBytes(32).toString("base64url");
1221
+ const t = spk ? deriveToken(spk, salt) : randomBytes(32).toString("base64url");
1222
+ try {
1223
+ writeWhole(personSaltFile(home), salt);
1224
+ writeWhole(personTokenFile(home), t);
1225
+ }
1226
+ catch (e) {
1227
+ 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`);
1094
1228
  }
1095
1229
  return t;
1096
1230
  }
@@ -1108,22 +1242,47 @@ export function identityHere(home) {
1108
1242
  // Both documents, as App.load requires: keys alone are an identity whose creation didn't finish.
1109
1243
  return existsSync(join(home, "cli", "keys.json")) && existsSync(join(home, "cli", "self.json"));
1110
1244
  }
1111
- /** Whether P2P_PERSON_TOKEN is this home's person token (read only: a missing file is no match). */
1245
+ /**
1246
+ * Whether P2P_PERSON_TOKEN is this home's person token (read only). It must be what person.key
1247
+ * holds (a missing file is no match) and, on a home with an identity, the token that identity
1248
+ * derives (recomputed here: a person.key written by anything else never verifies). Never on a home
1249
+ * whose files aren't its own (homeFilesOwn).
1250
+ */
1112
1251
  export function personTokenOk(env, home) {
1113
1252
  const given = env?.P2P_PERSON_TOKEN?.trim();
1114
1253
  if (!given || typeof home !== "string" || home === "")
1115
1254
  return false;
1116
- let t;
1117
- try {
1118
- t = readFileSync(personTokenFile(home), "utf8").trim();
1119
- }
1120
- catch {
1255
+ if (!homeFilesOwn(home))
1121
1256
  return false;
1122
- }
1257
+ const t = readTrim(personTokenFile(home));
1258
+ if (t === undefined || !same(given, t))
1259
+ return false;
1260
+ if (!identityHere(home))
1261
+ return true;
1262
+ const want = derivedToken(home);
1263
+ return want !== undefined && same(given, want);
1264
+ }
1265
+ function same(given, t) {
1123
1266
  const a = Buffer.from(given);
1124
1267
  const b = Buffer.from(t);
1125
1268
  return a.length === b.length && b.length >= 32 && timingSafeEqual(a, b);
1126
1269
  }
1270
+ /**
1271
+ * After a refused token: brings a person.key that holds something else (a front end's first-run
1272
+ * value on a home that has an identity now, one from before derived tokens) up to the derived token,
1273
+ * so the front end that reads it again gets one that verifies. A missing person.key stays missing
1274
+ * (the next command makes it), and nothing is written into a home whose files aren't its own.
1275
+ */
1276
+ export function healPersonToken(home) {
1277
+ if (!identityHere(home) || !existsSync(personTokenFile(home)))
1278
+ return;
1279
+ try {
1280
+ personToken(home);
1281
+ }
1282
+ catch {
1283
+ // the next command tries again
1284
+ }
1285
+ }
1127
1286
  /**
1128
1287
  * Checks the person token once, at the start of a command, and takes it out of the environment
1129
1288
  * (this object and the process's), so no child (git, ix, an extension's tool) ever inherits it.
@@ -1154,6 +1313,11 @@ export async function assertPersonForWidening(app, what, confirm, why = "changes
1154
1313
  if (agentContext(app.env)) {
1155
1314
  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
1315
  }
1316
+ // Fail closed: a process tree that couldn't be read (no /proc, no system `ps`, a process gone
1317
+ // mid-walk) may be an agent's session. The person's token still works (above).
1318
+ if (ancestryUnknown()) {
1319
+ 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()})` : ""}`);
1320
+ }
1157
1321
  if (!(await confirm(`p2p ${what} ${why}.`))) {
1158
1322
  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
1323
  }
@@ -1177,6 +1341,10 @@ export async function assertSpeaksFor(app, sid) {
1177
1341
  export function personHere(app) {
1178
1342
  return app.front === true || !agentContext(app.env);
1179
1343
  }
1344
+ /** personHere for a person-only act: an unreadable process tree counts as an agent's session (fail closed). */
1345
+ export function personHereStrict(app) {
1346
+ return app.front === true || (!agentContext(app.env) && !ancestryUnknown());
1347
+ }
1180
1348
  export async function sessionBinding(app, sid) {
1181
1349
  return (await app.state.get("sessionProjects"))?.[sid];
1182
1350
  }
@@ -0,0 +1,17 @@
1
+ /** #91 review: where a running rotation step records who it is (one run per home at a time). */
2
+ export declare const rotationLockOf: (home: string) => string;
3
+ /**
4
+ * Runs `fn` holding the rotation lock of `home`, so a second run (`--resume --contest` while the first is in
5
+ * followers(), or `--plan --exclude X` while a `--resume --yes` run saves) can't have its state overwritten by the
6
+ * other's saves.
7
+ *
8
+ * The lock is created with O_EXCL and records the run (LockRecord). A lock left by a run that no longer runs
9
+ * (lockLive), or an empty one older than EMPTY_STALE_MS, is taken over, exclusively (#99): the run first creates,
10
+ * with O_EXCL, a takeover marker named after the stale lock's exact content. Only the run that creates it removes the
11
+ * lock, and only while the lock still holds that content; nothing else removes a lock with that content (its own run
12
+ * is gone). Then it takes the lock with O_EXCL like any other run. So two runs taking over the same stale lock leave
13
+ * exactly one owner: the other's marker fails, or (created after the first removed its marker, which is after the
14
+ * first took the lock) it finds the first's live lock and refuses. A fresh run racing a takeover gets the lock or
15
+ * doesn't, by O_EXCL. Every refusal names the lock file.
16
+ */
17
+ export declare function withRotationLock<T>(home: string, fn: () => Promise<T>): Promise<T>;