@peer2peer/codex-bridge 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/knobs.js ADDED
@@ -0,0 +1,1020 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Where the bridge's security-relevant settings may come from.
4
+ //
5
+ // Codex merges config layers: user (`CODEX_HOME/config.toml`), profile,
6
+ // then project layers (`.codex/config.toml` in the cwd, its parents and the
7
+ // repo root) for projects the person marked trusted, then `-c` flags.
8
+ // `mcp_servers` is not on Codex's project-local denylist
9
+ // (`codex-rs/config/src/loader/mod.rs`, PROJECT_LOCAL_CONFIG_DENYLIST), so a
10
+ // trusted repo's `.codex/config.toml` can add to `mcp_servers.peer2peer.env`,
11
+ // for example `P2P_AUTO_DELIVER = "p2p:<attacker>"`. A repo is content, not
12
+ // the person, so the bridge takes every knob that loosens a rule, redirects
13
+ // a confirmation, or picks which identity, binary or Codex home it uses
14
+ // ONLY from the user-level config's `[mcp_servers.peer2peer.env]` table. An
15
+ // environment value that differs is ignored, with a warning. A knob that
16
+ // only tightens (P2P_SHARE_STATUS=0) is honoured from either place.
17
+ //
18
+ // CODEX_HOME locates that user config, so it is bootstrapped separately.
19
+ // A value in a temp folder (/tmp, TMPDIR, ...), in the project (cwd and
20
+ // repo), not owned by the person or world-writable is always refused. Else
21
+ // it counts only when Codex itself (this server's parent process) runs with
22
+ // the same CODEX_HOME, where the OS lets the bridge read the parent's
23
+ // environment; where it can't (Windows, a non-dumpable Codex on Linux), only
24
+ // when the person's `p2p codex install --write` pinned it (pinFile). Else
25
+ // ~/.codex.
26
+ //
27
+ // The same merge lets a trusted repo replace `mcp_servers.peer2peer`'s
28
+ // command, args, cwd or env (HOME, TMPDIR, PATH) outright, so all of this
29
+ // is defence in depth. ~ comes from the user database, never $HOME; the
30
+ // EFFECTIVE Codex home and P2P_HOME are checked every time; and a HOME
31
+ // that isn't the person's, or a project config touching
32
+ // `mcp_servers.peer2peer` at all, makes the bridge hold everything and
33
+ // refuse every release (locationPolicy).
34
+ import { execFile, execFileSync } from "node:child_process";
35
+ import { randomBytes } from "node:crypto";
36
+ import { chmodSync, closeSync, constants as fsConstants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
37
+ import { readFile, readlink } from "node:fs/promises";
38
+ import { homedir, tmpdir, userInfo } from "node:os";
39
+ import { basename, delimiter, dirname, isAbsolute, join } from "node:path";
40
+ import { isInside } from "./lib.js";
41
+ /** Knobs taken only from the user-level config. */
42
+ export const GUARDED_KNOBS = [
43
+ "P2P_AUTO_DELIVER",
44
+ "P2P_CODEX_CONFIRM_TTY",
45
+ "P2P_CODEX_CONFIRM_RATE",
46
+ "P2P_CODEX_QUEUE",
47
+ "P2P_CODEX_BIN",
48
+ "P2P_CODEX_META_LOG",
49
+ "P2P_BIN",
50
+ "P2P_HOME",
51
+ "P2P_RELAY_TRANSPORT",
52
+ "P2P_DEFAULT_RELAYS",
53
+ // The Ix CLI ext-ix runs (`$IX_BIN impact …`): a project-set /bin/sh would run the repo's scripts.
54
+ "IX_BIN",
55
+ ];
56
+ /** Knobs that only tighten: honoured from the environment too. */
57
+ export const TIGHTEN_ONLY = ["P2P_SHARE_STATUS", "IX_PEERS_SHARE_STATUS"];
58
+ /** The default P2P home's folder name under the person's home. */
59
+ export const DEFAULT_P2P_DIR = ".p2p";
60
+ function skipWs(sc) {
61
+ while (sc.i < sc.s.length && (sc.s[sc.i] === " " || sc.s[sc.i] === "\t"))
62
+ sc.i++;
63
+ }
64
+ function readKey(sc) {
65
+ const parts = [];
66
+ for (;;) {
67
+ skipWs(sc);
68
+ const c = sc.s[sc.i];
69
+ if (c === '"' || c === "'") {
70
+ const v = readString(sc);
71
+ if (v === null)
72
+ return null;
73
+ parts.push(v);
74
+ }
75
+ else {
76
+ const m = /^[A-Za-z0-9_-]+/.exec(sc.s.slice(sc.i));
77
+ if (!m)
78
+ return null;
79
+ parts.push(m[0]);
80
+ sc.i += m[0].length;
81
+ }
82
+ skipWs(sc);
83
+ if (sc.s[sc.i] === ".") {
84
+ sc.i++;
85
+ continue;
86
+ }
87
+ return parts;
88
+ }
89
+ }
90
+ function readString(sc) {
91
+ const q = sc.s[sc.i];
92
+ if (q === "'") {
93
+ const end = sc.s.indexOf("'", sc.i + 1);
94
+ if (end < 0)
95
+ return null;
96
+ const v = sc.s.slice(sc.i + 1, end);
97
+ sc.i = end + 1;
98
+ return v;
99
+ }
100
+ if (q !== '"')
101
+ return null;
102
+ let out = "";
103
+ for (let j = sc.i + 1; j < sc.s.length; j++) {
104
+ const c = sc.s[j];
105
+ if (c === '"') {
106
+ sc.i = j + 1;
107
+ return out;
108
+ }
109
+ if (c === "\n")
110
+ return null;
111
+ if (c !== "\\") {
112
+ out += c;
113
+ continue;
114
+ }
115
+ const e = sc.s[++j];
116
+ const simple = { '"': '"', "\\": "\\", n: "\n", t: "\t", r: "\r", b: "\b", f: "\f" };
117
+ if (e !== undefined && simple[e] !== undefined)
118
+ out += simple[e];
119
+ else if (e === "u" || e === "U") {
120
+ const len = e === "u" ? 4 : 8;
121
+ const hex = sc.s.slice(j + 1, j + 1 + len);
122
+ if (!/^[0-9A-Fa-f]+$/.test(hex) || hex.length !== len)
123
+ return null;
124
+ out += String.fromCodePoint(parseInt(hex, 16));
125
+ j += len;
126
+ }
127
+ else
128
+ return null;
129
+ }
130
+ return null;
131
+ }
132
+ /** A scalar value as a string (strings, numbers, booleans); null for anything else. */
133
+ function readScalar(sc) {
134
+ skipWs(sc);
135
+ const c = sc.s[sc.i];
136
+ if (c === '"' || c === "'") {
137
+ if (sc.s.startsWith('"""', sc.i) || sc.s.startsWith("'''", sc.i))
138
+ return null;
139
+ return readString(sc);
140
+ }
141
+ const m = /^[A-Za-z0-9_.+:-]+/.exec(sc.s.slice(sc.i));
142
+ if (!m)
143
+ return null;
144
+ sc.i += m[0].length;
145
+ return m[0];
146
+ }
147
+ function readInlineTable(sc, into) {
148
+ if (sc.s[sc.i] !== "{")
149
+ return false;
150
+ sc.i++;
151
+ for (;;) {
152
+ skipWs(sc);
153
+ if (sc.s[sc.i] === "}") {
154
+ sc.i++;
155
+ return true;
156
+ }
157
+ const key = readKey(sc);
158
+ if (!key)
159
+ return false;
160
+ skipWs(sc);
161
+ if (sc.s[sc.i] !== "=")
162
+ return false;
163
+ sc.i++;
164
+ skipWs(sc);
165
+ if (sc.s[sc.i] === "{") {
166
+ if (!readInlineTable(sc, (k, v) => into([...key, ...k], v)))
167
+ return false;
168
+ }
169
+ else {
170
+ const v = readScalar(sc);
171
+ if (v === null)
172
+ return false;
173
+ into(key, v);
174
+ }
175
+ skipWs(sc);
176
+ if (sc.s[sc.i] === ",")
177
+ sc.i++;
178
+ }
179
+ }
180
+ /**
181
+ * Scans `s` (the rest of a value, or a whole line inside one) from `state`:
182
+ * strings of all four kinds (so a `"""` or `'''` string's contents are
183
+ * never read as TOML), comments, and `[`/`{` nesting. A single-line string
184
+ * left open at the end of a line marks the text malformed.
185
+ */
186
+ function scanTail(s, state) {
187
+ const st = { ...state };
188
+ for (let i = 0; i < s.length; i++) {
189
+ const c = s[i];
190
+ if (st.quote === '"""' || st.quote === "'''") {
191
+ if (st.quote === '"""' && c === "\\")
192
+ i++;
193
+ else if (s.startsWith(st.quote, i)) {
194
+ // A closing delimiter may carry up to two more quote characters (part of the string).
195
+ let j = i + 3;
196
+ while (j < s.length && j < i + 5 && s[j] === st.quote[0])
197
+ j++;
198
+ i = j - 1;
199
+ st.quote = null;
200
+ }
201
+ continue;
202
+ }
203
+ if (st.quote) {
204
+ if (c === "\\" && st.quote === '"')
205
+ i++;
206
+ else if (c === st.quote)
207
+ st.quote = null;
208
+ continue;
209
+ }
210
+ if (s.startsWith('"""', i) || s.startsWith("'''", i)) {
211
+ st.quote = s.slice(i, i + 3);
212
+ i += 2;
213
+ }
214
+ else if (c === '"' || c === "'")
215
+ st.quote = c;
216
+ else if (c === "#")
217
+ break;
218
+ else if (c === "[" || c === "{")
219
+ st.depth++;
220
+ else if (c === "]" || c === "}")
221
+ st.depth--;
222
+ }
223
+ if (st.quote === '"' || st.quote === "'") {
224
+ st.bad = true;
225
+ st.quote = null;
226
+ }
227
+ return st;
228
+ }
229
+ const isOpen = (t) => t.depth > 0 || t.quote !== null;
230
+ /**
231
+ * The string values under `table` (a dotted path such as
232
+ * `mcp_servers.peer2peer.env`) in a TOML document: from `[table]`, from an
233
+ * inline `env = { … }` in the parent table, and from dotted keys. Only what
234
+ * Codex's config can hold there (string values) is read; null when the text
235
+ * can't be read with confidence (the caller then trusts nothing from it).
236
+ * Values that span lines (multi-line strings, arrays, inline tables) are
237
+ * skipped whole, so their contents are never read as keys; one under our
238
+ * table means null.
239
+ */
240
+ export function readTomlTable(text, table, touched) {
241
+ const out = {};
242
+ const isPrefix = (a, b) => a.length <= b.length && a.every((x, i) => x === b[i]);
243
+ const take = (full, value) => {
244
+ if (isPrefix(table, full))
245
+ touched?.();
246
+ if (full.length === table.length + 1 && isPrefix(table, full))
247
+ out[full[table.length]] = value;
248
+ };
249
+ let current = [];
250
+ // Inside a value of some other key that spans lines.
251
+ let tail = { depth: 0, quote: null, bad: false };
252
+ for (const raw of text.split(/\r?\n/)) {
253
+ if (isOpen(tail)) {
254
+ tail = scanTail(raw, tail);
255
+ if (tail.bad || tail.depth < 0)
256
+ return null;
257
+ continue;
258
+ }
259
+ const line = raw.trim();
260
+ if (line === "" || line.startsWith("#"))
261
+ continue;
262
+ if (line.startsWith("[")) {
263
+ const isArray = line.startsWith("[[");
264
+ const hsc = { s: line, i: isArray ? 2 : 1 };
265
+ const key = readKey(hsc);
266
+ if (!key || !line.slice(hsc.i).startsWith(isArray ? "]]" : "]"))
267
+ return null;
268
+ const after = scanTail(line.slice(hsc.i + (isArray ? 2 : 1)), tail);
269
+ if (after.bad || after.depth !== 0 || after.quote !== null)
270
+ return null;
271
+ if (isPrefix(table, key))
272
+ touched?.();
273
+ // An array of tables never holds our table.
274
+ current = isArray ? ["\u0000"] : key;
275
+ continue;
276
+ }
277
+ const sc = { s: raw, i: 0 };
278
+ const key = readKey(sc);
279
+ if (!key)
280
+ return null;
281
+ skipWs(sc);
282
+ if (sc.s[sc.i] !== "=")
283
+ return null;
284
+ sc.i++;
285
+ skipWs(sc);
286
+ const full = [...current, ...key];
287
+ const relevant = isPrefix(full, table) || isPrefix(table, full);
288
+ const valueAt = sc.i;
289
+ const rest = scanTail(sc.s.slice(valueAt), tail);
290
+ if (rest.bad || rest.depth < 0)
291
+ return null;
292
+ if (isOpen(rest)) {
293
+ // A value spanning lines: never ours to read; skipped whole when it isn't under our table.
294
+ if (relevant)
295
+ return null;
296
+ tail = rest;
297
+ continue;
298
+ }
299
+ const c = sc.s[valueAt];
300
+ if (sc.s.startsWith('"""', valueAt) || sc.s.startsWith("'''", valueAt)) {
301
+ if (relevant)
302
+ return null;
303
+ continue;
304
+ }
305
+ if (c === "{") {
306
+ if (!readInlineTable(sc, (k, v) => take([...full, ...k], v)) && relevant)
307
+ return null;
308
+ continue;
309
+ }
310
+ if (c === "[") {
311
+ if (relevant && full.length >= table.length + 1)
312
+ return null;
313
+ continue;
314
+ }
315
+ const v = readScalar(sc);
316
+ if (v === null) {
317
+ if (relevant)
318
+ return null;
319
+ continue;
320
+ }
321
+ if (relevant)
322
+ take(full, v);
323
+ }
324
+ if (isOpen(tail))
325
+ return null;
326
+ return out;
327
+ }
328
+ /**
329
+ * Whether a TOML document sets anything under `table` (a header, a key, an
330
+ * inline table, a value spanning lines), matched on decoded keys (quoted,
331
+ * literal and \u-escaped spellings alike). Fails closed: true whenever the
332
+ * text can't be read with confidence, for any reason (a value the reader
333
+ * doesn't take, such as a `"""` string or an array under the table, or text
334
+ * it can't parse at all).
335
+ */
336
+ export function touchesTable(text, table) {
337
+ let hit = false;
338
+ const r = readTomlTable(text, table, () => (hit = true));
339
+ return hit || r === null;
340
+ }
341
+ // ── the policy ──────────────────────────────────────────────────────────────
342
+ /** The parent process's value of `name`, where the OS shows it (Linux /proc, macOS ps -E); undefined when it can't be told. */
343
+ export async function parentEnvValue(name, ppid = process.ppid) {
344
+ try {
345
+ if (process.platform === "linux") {
346
+ const raw = await readFile(`/proc/${ppid}/environ`, "utf8");
347
+ for (const entry of raw.split("\0"))
348
+ if (entry.startsWith(`${name}=`))
349
+ return entry.slice(name.length + 1);
350
+ return null; // readable, and not set
351
+ }
352
+ if (process.platform === "darwin") {
353
+ const ps = (args) => new Promise((resolve, reject) => execFile("/bin/ps", [...args, "-ww", "-o", "command=", "-p", String(ppid)], { timeout: 3_000, maxBuffer: 4_000_000, env: safeExecEnv() }, (e, so) => (e ? reject(e) : resolve(String(so)))));
354
+ const [withEnv, command] = await Promise.all([ps(["-E"]), ps([])]);
355
+ return envFromPs(withEnv, command, name);
356
+ }
357
+ }
358
+ catch { }
359
+ return undefined;
360
+ }
361
+ /**
362
+ * The working folder of Codex itself (this server's parent), where the OS
363
+ * shows it (Linux /proc, macOS lsof): a project config can move the
364
+ * server's own cwd (`mcp_servers.peer2peer.cwd`), not Codex's.
365
+ */
366
+ export async function parentCwd(ppid = process.ppid) {
367
+ try {
368
+ if (process.platform === "linux")
369
+ return await readlink(`/proc/${ppid}/cwd`);
370
+ if (process.platform === "darwin") {
371
+ const out = await new Promise((resolve, reject) => execFile("/usr/sbin/lsof", ["-a", "-p", String(ppid), "-d", "cwd", "-Fn"], { timeout: 3_000, maxBuffer: 1_000_000, env: safeExecEnv() }, (e, so) => (e ? reject(e) : resolve(String(so)))));
372
+ const line = out.split("\n").find((l) => l.startsWith("n/"));
373
+ return line ? line.slice(1) : undefined;
374
+ }
375
+ }
376
+ catch { }
377
+ return undefined;
378
+ }
379
+ /**
380
+ * One variable from macOS `ps -E -o command=` output, given the plain
381
+ * `ps -o command=` output of the same process: ps appends the environment
382
+ * after the command and its arguments, so only what follows that prefix is
383
+ * read (a ` CODEX_HOME=` in an argument never counts). A value runs to the
384
+ * next ` NAME=` or the end, so paths with spaces survive. undefined ("can't
385
+ * tell") when the prefix doesn't match, the environment is hidden (no HOME=;
386
+ * macOS hides it for platform binaries such as /bin/sh), or the variable
387
+ * appears more than once; null when it is plainly not set.
388
+ */
389
+ export function envFromPs(withEnv, command, name) {
390
+ const full = withEnv.replace(/\r?\n$/, "");
391
+ const cmd = command.replace(/\r?\n$/, "");
392
+ if (cmd === "" || !full.startsWith(cmd))
393
+ return undefined;
394
+ const envPart = full.slice(cmd.length);
395
+ if (envPart !== "" && !envPart.startsWith(" "))
396
+ return undefined;
397
+ // Each ` NAME=` starts a variable; the text up to the next one is its value.
398
+ const starts = [...envPart.matchAll(/ ([A-Za-z_][A-Za-z0-9_]*)=/g)];
399
+ if (!starts.some((m) => m[1] === "HOME"))
400
+ return undefined;
401
+ const hits = starts.map((m, i) => ({ m, i })).filter(({ m }) => m[1] === name);
402
+ if (hits.length === 0)
403
+ return null;
404
+ // Another value holding ` NAME=` can't be told from the variable itself: can't tell.
405
+ if (hits.length > 1 || envPart.split(` ${name}=`).length - 1 !== 1)
406
+ return undefined;
407
+ const { m, i } = hits[0];
408
+ const from = m.index + m[0].length;
409
+ const next = starts[i + 1];
410
+ return envPart.slice(from, next ? next.index : envPart.length);
411
+ }
412
+ // ── running other programs ──────────────────────────────────────────────────
413
+ /**
414
+ * P2P_* variables a child never gets: they load code (extensions), point
415
+ * the CLI at other files, or change what this session tells peers
416
+ * (P2P_STATUS_CAPS, review L2: which status fields go on the wire), and a
417
+ * project config can set them in the server's env. (The guarded knobs come
418
+ * from the user-level config; status caps from `"statusCaps"` in the p2p
419
+ * home's config.json.)
420
+ */
421
+ export const CHILD_P2P_DENY = ["P2P_PERSON_TOKEN", "P2P_EXTENSION_PATH", "P2P_EXTENSIONS", "P2P_EXTENSION_EXCLUDE", "P2P_DEFAULTS_FILE", "P2P_WRITE_VECTORS", "P2P_GO_VECTORS", "P2P_STATUS_CAPS"];
422
+ /** Exact names (besides P2P_* and LC_*) a child may get from the bridge's env. */
423
+ const CHILD_ALLOW = ["LANG", "TZ", "TERM"];
424
+ function isRegularFile(p) {
425
+ try {
426
+ return statSync(p).isFile();
427
+ }
428
+ catch {
429
+ return false;
430
+ }
431
+ }
432
+ const CHILD_ALLOW_WIN = ["SYSTEMROOT", "APPDATA", "LOCALAPPDATA"];
433
+ /**
434
+ * The environment for the programs the bridge runs (`p2p`, `p2p watch`,
435
+ * `codex queue`), built from an allowlist: a fixed PATH (the node running
436
+ * this server, then the system folders), HOME (USERPROFILE on Windows)
437
+ * from the user database, P2P_* (minus CHILD_P2P_DENY), LANG, LC_*, TZ,
438
+ * TERM, and SYSTEMROOT/APPDATA/LOCALAPPDATA on Windows, plus `extra`.
439
+ * Nothing else: no NODE_OPTIONS, NODE_TLS_REJECT_UNAUTHORIZED, proxies,
440
+ * NODE_ICU_DATA, GCONV_PATH, LD_* or DYLD_*. Names compare
441
+ * case-insensitively, as on Windows.
442
+ */
443
+ export function childEnv(env, extra = {}) {
444
+ const win = process.platform === "win32";
445
+ const deny = new Set(CHILD_P2P_DENY);
446
+ const exact = new Set([...CHILD_ALLOW, ...(win ? CHILD_ALLOW_WIN : [])]);
447
+ const out = {};
448
+ for (const [k, v] of Object.entries(env)) {
449
+ if (v === undefined)
450
+ continue;
451
+ const K = k.toUpperCase();
452
+ if ((K.startsWith("P2P_") && !deny.has(K)) || K.startsWith("LC_") || exact.has(K))
453
+ out[k] = v;
454
+ // ext-ix runs the Ix CLI from IX_BIN (validated by effectiveEnv): passed on only as an absolute path to a regular file.
455
+ else if (K === "IX_BIN" && isAbsolute(v) && isRegularFile(v))
456
+ out[k] = v;
457
+ }
458
+ out.PATH = [dirname(process.execPath), ...SAFE_PATH_DIRS].join(delimiter);
459
+ if (win)
460
+ out.USERPROFILE = userHome();
461
+ else
462
+ out.HOME = userHome();
463
+ for (const [k, v] of Object.entries(extra))
464
+ if (v !== undefined)
465
+ out[k] = v;
466
+ return out;
467
+ }
468
+ /** System folders only: never the PATH a project config may have put in the server's env. */
469
+ export const SAFE_PATH_DIRS = process.platform === "win32" ? [] : ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
470
+ /**
471
+ * A scrubbed environment for helper programs (git, ps, lsof, ss, getconf):
472
+ * a fixed system PATH, the person's home from the user database, and
473
+ * nothing else (no GIT_*, no project-set PATH, no LD_* or DYLD_*).
474
+ */
475
+ export function safeExecEnv() {
476
+ if (process.platform === "win32") {
477
+ const sys = process.env.SystemRoot ?? "C:\\Windows";
478
+ return { SystemRoot: sys, PATH: join(sys, "System32"), USERPROFILE: userHome() };
479
+ }
480
+ return { PATH: SAFE_PATH_DIRS.join(":"), HOME: userHome(), LC_ALL: "C" };
481
+ }
482
+ /**
483
+ * A program by absolute path, looked up in fixed folders (the system ones,
484
+ * then `extra`), never through the environment's PATH; undefined when none
485
+ * has it.
486
+ */
487
+ export function safeBinary(name, extra = []) {
488
+ const dirs = process.platform === "win32" ? extra : [...SAFE_PATH_DIRS, ...extra];
489
+ const names = process.platform === "win32" ? [`${name}.exe`, `${name}.cmd`] : [name];
490
+ for (const d of dirs) {
491
+ for (const n of names) {
492
+ const p = join(d, n);
493
+ try {
494
+ if (statSync(p).isFile())
495
+ return p;
496
+ }
497
+ catch { }
498
+ }
499
+ }
500
+ return undefined;
501
+ }
502
+ /** git by absolute path: the system's, else Homebrew's or /usr/local's, else Git for Windows'. */
503
+ export function gitBinary() {
504
+ return safeBinary("git", process.platform === "win32" ? ["C:\\Program Files\\Git\\cmd", "C:\\Program Files\\Git\\bin"] : ["/opt/homebrew/bin", "/usr/local/bin"]);
505
+ }
506
+ /**
507
+ * Folders an installed `codex` usually lives in (npm, Homebrew, cargo, a
508
+ * user bin), for a bare `codex` when P2P_CODEX_BIN isn't an absolute path.
509
+ */
510
+ export function codexBinDirs(home = userHome()) {
511
+ return ["/opt/homebrew/bin", "/usr/local/bin", join(home, ".local", "bin"), join(home, ".cargo", "bin"), join(home, ".npm-global", "bin"), join(home, ".bun", "bin"), join(home, ".volta", "bin")];
512
+ }
513
+ // ── where settings and trusted files may live ───────────────────────────────
514
+ /**
515
+ * The person's home folder from the user database, never $HOME (a project
516
+ * config can set HOME in the server's env, which would move ~/.codex,
517
+ * the P2P home and the pin file).
518
+ */
519
+ export function userHome() {
520
+ try {
521
+ const h = userInfo().homedir;
522
+ if (h)
523
+ return h;
524
+ }
525
+ catch { }
526
+ return homedir();
527
+ }
528
+ /** Why the environment's HOME (USERPROFILE on Windows) isn't the person's home folder; undefined when it is or isn't set. */
529
+ export function homeRefusal(env, home = userHome()) {
530
+ const name = process.platform === "win32" ? "USERPROFILE" : "HOME";
531
+ const v = env[name]?.trim();
532
+ if (!v || samePath(v, home) || samePath(realish(v), realish(home)))
533
+ return undefined;
534
+ return `${name}=${v} isn't your home folder (${home}); a project config may have set it`;
535
+ }
536
+ let darwinTemp;
537
+ /** macOS's per-user temp folder (/var/folders/…/T) from confstr, never from TMPDIR; undefined elsewhere. */
538
+ export function darwinUserTempDir() {
539
+ if (process.platform !== "darwin")
540
+ return undefined;
541
+ if (darwinTemp === undefined) {
542
+ try {
543
+ darwinTemp = execFileSync("/usr/bin/getconf", ["DARWIN_USER_TEMP_DIR"], { encoding: "utf8", timeout: 3_000, env: {}, stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
544
+ }
545
+ catch {
546
+ darwinTemp = null;
547
+ }
548
+ }
549
+ return darwinTemp ?? undefined;
550
+ }
551
+ /**
552
+ * Folders anyone, or a sandboxed command, can write: the system temp
553
+ * folders and the person's own (macOS confstr, Windows' AppData\Local\Temp),
554
+ * which TMPDIR can't take away. TMPDIR values given (and os.tmpdir()) are
555
+ * added too: they only ever add folders.
556
+ */
557
+ export function tempRoots(tmp) {
558
+ const out = ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp", "/dev/shm", darwinUserTempDir(), ...(process.platform === "win32" ? [join(userHome(), "AppData", "Local", "Temp")] : []), tmpdir(), ...(tmp ?? [])];
559
+ return [...new Set(out.map((d) => d?.trim()).filter((d) => !!d))];
560
+ }
561
+ /** Folders Codex itself lets the sandbox write under a Codex home (its memories), for each Codex home given and ~/.codex. */
562
+ export function codexGranted(codexHomes, home = userHome()) {
563
+ return [...new Set([...codexHomes, join(home, ".codex")].flatMap((h) => [join(h, "memories"), join(h, "memories_v2")]))];
564
+ }
565
+ /**
566
+ * An absolute path with symlinks resolved (macOS's /var is /private/var, and
567
+ * git reports the resolved toplevel). A file not written yet resolves by its
568
+ * folder.
569
+ */
570
+ export function realish(path) {
571
+ try {
572
+ return realpathSync.native(path);
573
+ }
574
+ catch {
575
+ try {
576
+ return join(realpathSync.native(dirname(path)), basename(path));
577
+ }
578
+ catch {
579
+ return path;
580
+ }
581
+ }
582
+ }
583
+ /**
584
+ * Why `path` lies where a project config or a sandboxed command could put
585
+ * files (a temp folder, the project), symlinks resolved on both sides; else
586
+ * undefined.
587
+ */
588
+ export function unsafeLocation(path, o) {
589
+ const paths = [path, realish(path)];
590
+ const home = o.home ?? userHome();
591
+ // The person's own config folders aren't project files when the project is the home folder itself (cwd = ~).
592
+ const own = [join(home, ".codex"), join(home, DEFAULT_P2P_DIR)].flatMap((d) => [d, realish(d)]);
593
+ const isOwn = paths.some((p) => own.some((d) => isInside(p, d)));
594
+ const check = (roots, what, skipHome = false) => {
595
+ for (const r of roots) {
596
+ if (skipHome && isOwn && isHomeFolder(r, home))
597
+ continue;
598
+ for (const root of [r, realish(r)])
599
+ for (const p of paths)
600
+ if (isInside(p, root))
601
+ return `${p} is inside ${what} ${root}`;
602
+ }
603
+ return undefined;
604
+ };
605
+ return check(o.temp, "the temp folder") ?? check(o.granted ?? [], "a folder Codex lets the sandbox write,") ?? check(o.projectDirs, "the project", true);
606
+ }
607
+ /**
608
+ * Why a folder (and its config.toml, when there) may hold someone else's
609
+ * files: not a folder, not this user's, or world-writable; else undefined.
610
+ * A symlinked config.toml (stow, chezmoi, Nix) is judged by its target: a
611
+ * regular file outside temp folders, Codex-granted folders and the project
612
+ * (`where`), owned by the person (or by root, as in /nix/store), and
613
+ * writable by no group or others. A missing folder counts only without
614
+ * `allowMissing`.
615
+ */
616
+ export function notPrivate(dir, o = {}) {
617
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
618
+ let st;
619
+ try {
620
+ st = statSync(dir);
621
+ }
622
+ catch {
623
+ return o.allowMissing ? undefined : `${dir} doesn't exist`;
624
+ }
625
+ const bad = (p, s) => {
626
+ if (uid !== undefined && s.uid !== uid)
627
+ return `${p} isn't owned by you`;
628
+ if (process.platform !== "win32" && (s.mode & 0o002) !== 0)
629
+ return `${p} is world-writable`;
630
+ return undefined;
631
+ };
632
+ if (!st.isDirectory())
633
+ return `${dir} isn't a folder`;
634
+ const d = bad(dir, st);
635
+ if (d)
636
+ return d;
637
+ const config = join(dir, "config.toml");
638
+ let cst;
639
+ try {
640
+ cst = lstatSync(config);
641
+ }
642
+ catch {
643
+ return undefined;
644
+ }
645
+ if (!cst.isSymbolicLink())
646
+ return bad(config, cst);
647
+ let target;
648
+ let tst;
649
+ try {
650
+ target = realpathSync.native(config);
651
+ tst = statSync(target);
652
+ }
653
+ catch {
654
+ return `${config} is a symbolic link to nothing readable`;
655
+ }
656
+ if (!tst.isFile())
657
+ return `${config} links to ${target}, which isn't a regular file`;
658
+ const where = o.where ? unsafeLocation(target, o.where) : undefined;
659
+ if (where)
660
+ return `${config} links to ${target}: ${where}`;
661
+ if (uid !== undefined && tst.uid !== uid && tst.uid !== 0)
662
+ return `${config} links to ${target}, which isn't owned by you (or root)`;
663
+ if (process.platform !== "win32" && (tst.mode & 0o022) !== 0)
664
+ return `${config} links to ${target}, which a group or others can write`;
665
+ // Every folder above the target: someone else could swap the file otherwise.
666
+ const above = foldersAboveProblem(target);
667
+ return above ? `${config} links to ${target}, and ${above}` : undefined;
668
+ }
669
+ /**
670
+ * Why someone other than the person (or root) could replace `file`: a
671
+ * folder above it isn't owned by the person or root, or is group- or
672
+ * world-writable without the sticky bit; else undefined. `file` is taken as
673
+ * resolved (no symlinks on its path). Not checked on Windows.
674
+ */
675
+ export function foldersAboveProblem(file) {
676
+ if (process.platform === "win32")
677
+ return undefined;
678
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
679
+ for (let d = dirname(file);; d = dirname(d)) {
680
+ let ds;
681
+ try {
682
+ ds = lstatSync(d);
683
+ }
684
+ catch {
685
+ return `${d} can't be checked`;
686
+ }
687
+ if (uid !== undefined && ds.uid !== uid && ds.uid !== 0)
688
+ return `${d} isn't owned by you (or root)`;
689
+ if ((ds.mode & 0o022) !== 0 && (ds.mode & 0o1000) === 0)
690
+ return `${d} is group- or world-writable without the sticky bit`;
691
+ if (dirname(d) === d)
692
+ break;
693
+ }
694
+ return undefined;
695
+ }
696
+ /**
697
+ * The CODEX_HOMEs `p2p codex install --write` pinned, one per line, in a
698
+ * file at a fixed place outside any project (codex/codex-homes in the
699
+ * default P2P home, with ~ from the user database): not under the
700
+ * environment's P2P_HOME or HOME, which a project config can set too.
701
+ */
702
+ export function pinFile(home = userHome()) {
703
+ return join(home, DEFAULT_P2P_DIR, "codex", "codex-homes");
704
+ }
705
+ /** Why a folder on the pin file's path may be someone else's: a symlink, not a folder, not this user's, or group/world-writable. */
706
+ function pinDirProblem(dir) {
707
+ let st;
708
+ try {
709
+ st = lstatSync(dir);
710
+ }
711
+ catch {
712
+ return `${dir} doesn't exist`;
713
+ }
714
+ if (st.isSymbolicLink() || !st.isDirectory())
715
+ return `${dir} isn't a real folder`;
716
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
717
+ if (uid !== undefined && st.uid !== uid)
718
+ return `${dir} isn't owned by you`;
719
+ if (process.platform !== "win32" && (st.mode & 0o022) !== 0)
720
+ return `${dir} is group- or world-writable`;
721
+ return undefined;
722
+ }
723
+ const NOFOLLOW = fsConstants.O_NOFOLLOW ?? 0;
724
+ /**
725
+ * The pinned CODEX_HOMEs: only from a regular file of this user that nobody
726
+ * else can write, opened without following a symlink and checked on the
727
+ * open descriptor, in folders (the P2P home and its codex/) of this user
728
+ * that nobody else can write; [] otherwise.
729
+ */
730
+ export function readPins(file = pinFile()) {
731
+ if (pinDirProblem(dirname(file)) || pinDirProblem(dirname(dirname(file))))
732
+ return [];
733
+ let fd;
734
+ try {
735
+ fd = openSync(file, fsConstants.O_RDONLY | NOFOLLOW);
736
+ const st = fstatSync(fd);
737
+ if (!st.isFile())
738
+ return [];
739
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
740
+ if (uid !== undefined && st.uid !== uid)
741
+ return [];
742
+ if (process.platform !== "win32" && (st.mode & 0o022) !== 0)
743
+ return [];
744
+ return readFileSync(fd, "utf8")
745
+ .split(/\r?\n/)
746
+ .map((l) => l.trim())
747
+ .filter((l) => l !== "" && !l.startsWith("#"));
748
+ }
749
+ catch {
750
+ return [];
751
+ }
752
+ finally {
753
+ if (fd !== undefined)
754
+ closeSync(fd);
755
+ }
756
+ }
757
+ const samePath = (a, b) => isInside(a, b) && isInside(b, a);
758
+ /**
759
+ * Records (or with `remove`, drops) a CODEX_HOME in the pin file; the
760
+ * person's `p2p codex install --write` only. Its folders are made (or
761
+ * tightened to) 0700; the new file is written through a fresh temp file
762
+ * (O_EXCL, no symlink followed) and renamed into place.
763
+ */
764
+ export function writePin(codexHome, o = {}) {
765
+ const file = o.file ?? pinFile();
766
+ for (const dir of [dirname(dirname(file)), dirname(file)]) {
767
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
768
+ if (lstatSync(dir).isSymbolicLink())
769
+ throw new Error(`${dir} is a symbolic link: not writing the CODEX_HOME pin there`);
770
+ if (process.platform !== "win32")
771
+ chmodSync(dir, 0o700);
772
+ }
773
+ const pins = readPins(file);
774
+ const has = pins.some((p) => samePath(p, codexHome));
775
+ if (o.remove ? !has : has)
776
+ return false;
777
+ const next = o.remove ? pins.filter((p) => !samePath(p, codexHome)) : [...pins, codexHome];
778
+ const tmp = `${file}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
779
+ const fd = openSync(tmp, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | NOFOLLOW, 0o600);
780
+ try {
781
+ writeFileSync(fd, ["# CODEX_HOMEs `p2p codex install --write` set up; the Codex bridge trusts no other when it can't read Codex's own environment.", ...next, ""].join("\n"));
782
+ }
783
+ finally {
784
+ closeSync(fd);
785
+ }
786
+ renameSync(tmp, file);
787
+ return true;
788
+ }
789
+ /**
790
+ * The environment the bridge (and every `p2p` it runs) uses: guarded knobs
791
+ * from the user-level config only, tighten-only knobs from either place,
792
+ * everything else as given.
793
+ */
794
+ export async function effectiveEnv(o) {
795
+ const warnings = [];
796
+ const home = o.home ?? userHome();
797
+ const defaultCodexHome = join(home, ".codex");
798
+ const given = o.env.CODEX_HOME?.trim();
799
+ let codexHome = defaultCodexHome;
800
+ if (given && given !== defaultCodexHome) {
801
+ const ignore = (why) => warnings.push(`ignored CODEX_HOME=${given}: ${why}; using ${defaultCodexHome}`);
802
+ // Never a folder a project config or a sandboxed command could fill, whatever else says so.
803
+ const refused = !isAbsolute(given)
804
+ ? "not an absolute path"
805
+ : (() => {
806
+ const where = { projectDirs: o.projectDirs, temp: o.temp ?? tempRoots([o.env.TMPDIR]), granted: codexGranted([given], home), home };
807
+ return unsafeLocation(given, where) ?? (o.privacy ?? ((d, w) => notPrivate(d, w ? { where: w } : {})))(given, where);
808
+ })();
809
+ if (refused)
810
+ ignore(refused);
811
+ else {
812
+ const parent = await (o.parentValue ?? parentEnvValue)("CODEX_HOME");
813
+ if (parent !== undefined) {
814
+ // The OS shows Codex's own environment: only its value counts.
815
+ if (parent === given)
816
+ codexHome = given;
817
+ else
818
+ ignore(`Codex itself runs with ${parent === null ? "the default" : parent}`);
819
+ }
820
+ else if ((o.pins ?? (() => readPins(pinFile(home))))().some((p) => samePath(p, given) || samePath(realish(p), realish(given)))) {
821
+ // Codex's environment can't be read here (Windows, a non-dumpable Codex): only a CODEX_HOME the person's installer pinned.
822
+ codexHome = given;
823
+ }
824
+ else {
825
+ ignore(`Codex's own environment can't be read here, so only a CODEX_HOME that \`p2p codex install --write\` set up (pinned in ${pinFile(home)}) counts; run it with this CODEX_HOME in your own terminal`);
826
+ }
827
+ }
828
+ }
829
+ const readConfig = o.readConfig ?? ((p) => readFile(p, "utf8").catch(() => null));
830
+ const text = await readConfig(join(codexHome, "config.toml"));
831
+ let user = {};
832
+ if (text !== null) {
833
+ const parsed = readTomlTable(text, ["mcp_servers", "peer2peer", "env"]);
834
+ if (parsed === null)
835
+ warnings.push("couldn't read [mcp_servers.peer2peer.env] in the user-level config.toml with confidence: using defaults for the guarded settings");
836
+ else
837
+ user = parsed;
838
+ }
839
+ const env = { ...o.env, CODEX_HOME: codexHome };
840
+ for (const k of GUARDED_KNOBS) {
841
+ const from = o.env[k];
842
+ const want = user[k];
843
+ if (from !== want && from !== undefined)
844
+ warnings.push(`ignored ${k} from the environment: set it in [mcp_servers.peer2peer.env] in ${join(codexHome, "config.toml")} (a project config can't override it there)`);
845
+ if (want === undefined)
846
+ delete env[k];
847
+ else
848
+ env[k] = want;
849
+ }
850
+ for (const k of TIGHTEN_ONLY)
851
+ if (o.env[k] === "0" || user[k] === "0")
852
+ env[k] = "0";
853
+ // IX_BIN (the Ix CLI ext-ix runs): a guarded knob, so only the user-level config's value (the loop
854
+ // above already dropped an env value); and only a file nobody else can replace, outside the project.
855
+ const ixBin = ixBinOf(user.IX_BIN, { projectDirs: o.projectDirs, temp: o.temp ?? tempRoots([o.env.TMPDIR]), granted: codexGranted([codexHome], home), home });
856
+ if (ixBin.value)
857
+ env.IX_BIN = ixBin.value;
858
+ else
859
+ delete env.IX_BIN;
860
+ if (ixBin.warning)
861
+ warnings.push(ixBin.warning);
862
+ const p2pHome = env.P2P_HOME?.trim() || join(home, DEFAULT_P2P_DIR);
863
+ env.P2P_HOME = p2pHome;
864
+ const refusal = await locationPolicy({
865
+ env: o.env,
866
+ home,
867
+ codexHome,
868
+ p2pHome,
869
+ projectDirs: o.projectDirs,
870
+ temp: o.temp ?? tempRoots([o.env.TMPDIR]),
871
+ privacy: o.privacy ?? ((d, where) => notPrivate(d, { allowMissing: true, ...(where ? { where } : {}) })),
872
+ projectConfigDirs: o.projectConfigDirs ?? [],
873
+ readConfig,
874
+ });
875
+ if (refusal)
876
+ warnings.push(`holding every message and refusing every release: ${refusal}`);
877
+ const serverCwd = text !== null ? readTomlTable(text, ["mcp_servers", "peer2peer"])?.cwd : undefined;
878
+ return { env, codexHome, p2pHome, warnings, ...(refusal ? { refusal } : {}), ...(serverCwd ? { serverCwd } : {}) };
879
+ }
880
+ /**
881
+ * IX_BIN, resolved (the real path is what is checked and forwarded), when
882
+ * it is an absolute path to an existing regular file outside temp folders, Codex-granted folders and the project,
883
+ * owned by the person or root, writable by no group or others, in folders
884
+ * nobody else can write (foldersAboveProblem); else why not.
885
+ */
886
+ export function ixBinOf(raw, where) {
887
+ const v = raw?.trim();
888
+ if (!v)
889
+ return {};
890
+ if (!isAbsolute(v))
891
+ return { warning: `ignored IX_BIN=${v}: it must be an absolute path` };
892
+ try {
893
+ if (!statSync(v).isFile())
894
+ return { warning: `ignored IX_BIN=${v}: not a regular file` };
895
+ }
896
+ catch {
897
+ return { warning: `ignored IX_BIN=${v}: no such file` };
898
+ }
899
+ const unsafe = unsafeLocation(v, where);
900
+ if (unsafe)
901
+ return { warning: `ignored IX_BIN=${v}: ${unsafe}` };
902
+ const real = realish(v);
903
+ // The resolved file too: a symlink in a safe folder may point into /tmp (sticky, so the folder walk passes).
904
+ const unsafeReal = unsafeLocation(real, where);
905
+ if (unsafeReal)
906
+ return { warning: `ignored IX_BIN=${v}: it resolves to ${real}, and ${unsafeReal}` };
907
+ let st;
908
+ try {
909
+ st = statSync(real);
910
+ }
911
+ catch {
912
+ return { warning: `ignored IX_BIN=${v}: ${real} can't be checked` };
913
+ }
914
+ const uid = typeof process.getuid === "function" ? process.getuid() : undefined;
915
+ if (uid !== undefined && st.uid !== uid && st.uid !== 0)
916
+ return { warning: `ignored IX_BIN=${v}: ${real} isn't owned by you (or root)` };
917
+ if (process.platform !== "win32" && (st.mode & 0o022) !== 0)
918
+ return { warning: `ignored IX_BIN=${v}: ${real} is writable by a group or others` };
919
+ const above = foldersAboveProblem(real);
920
+ if (above)
921
+ return { warning: `ignored IX_BIN=${v}: ${above}` };
922
+ // The path checked is the one forwarded: a symlink can't be repointed after the check.
923
+ return { value: real };
924
+ }
925
+ /** Whether `dir` is the person's home folder itself (symlinks resolved). */
926
+ export function isHomeFolder(dir, home = userHome()) {
927
+ return samePath(dir, home) || samePath(realish(dir), realish(home));
928
+ }
929
+ /**
930
+ * What Codex's own working folder says about the server's. Unknown (the OS
931
+ * doesn't show it: Windows, lsof missing): the project can't be confirmed,
932
+ * so releases are refused, with a warning. Known but different from the
933
+ * server's cwd: a cwd override moved the server; unless the user-level
934
+ * config set that cwd, a project config did, and the bridge holds
935
+ * everything.
936
+ */
937
+ export function cwdPolicy(o) {
938
+ const same = (a, b) => samePath(a, b) || samePath(realish(a), realish(b));
939
+ if (o.codexCwd === undefined) {
940
+ const releaseRefusal = "Codex's own working folder can't be read here, so the project this session works in can't be confirmed";
941
+ return { releaseRefusal, warning: `refusing releases: ${releaseRefusal}` };
942
+ }
943
+ if (same(o.serverCwd, o.codexCwd))
944
+ return {};
945
+ if (o.configuredCwd && same(o.serverCwd, o.configuredCwd))
946
+ return {};
947
+ const refusal = `this server runs in ${o.serverCwd}, not in Codex's working folder ${o.codexCwd}, and the user-level config doesn't set that cwd (a project config may have moved it)`;
948
+ return { refusal, warning: `holding every message and refusing every release: ${refusal}` };
949
+ }
950
+ /**
951
+ * Why the bridge must hold everything and refuse every release, checked on
952
+ * the EFFECTIVE Codex home and P2P_HOME every time (whether or not
953
+ * CODEX_HOME was given): HOME isn't the person's home folder; either lies
954
+ * in a temp folder, a folder Codex lets the sandbox write, or the project;
955
+ * either isn't private to the person; or a project config touches
956
+ * `mcp_servers.peer2peer` at all (a trusted project can replace this
957
+ * server's command, args, cwd and env outright: Codex merges
958
+ * `mcp_servers` from project layers).
959
+ */
960
+ export async function locationPolicy(o) {
961
+ const h = homeRefusal(o.env, o.home);
962
+ if (h)
963
+ return h;
964
+ const where = { projectDirs: o.projectDirs, temp: o.temp, granted: codexGranted([o.codexHome], o.home), home: o.home };
965
+ for (const [name, dir] of [
966
+ ["the Codex home", o.codexHome],
967
+ ["P2P_HOME", o.p2pHome],
968
+ ]) {
969
+ const why = unsafeLocation(dir, where) ?? o.privacy(dir, where);
970
+ if (why)
971
+ return `${name} isn't safe: ${why}`;
972
+ }
973
+ return projectOverride(o.projectConfigDirs, o.codexHome, o.readConfig);
974
+ }
975
+ /**
976
+ * Why a project config among `dirs` (each one's `.codex/config.toml`)
977
+ * replaces or changes this server: it touches `mcp_servers.peer2peer` at
978
+ * all. The person's own Codex home (cwd = ~) is the user layer, skipped.
979
+ */
980
+ export async function projectOverride(dirs, codexHome, readConfig) {
981
+ for (const dir of dirs) {
982
+ const codexDir = join(dir, ".codex");
983
+ if (samePath(codexDir, codexHome) || samePath(realish(codexDir), realish(codexHome)))
984
+ continue;
985
+ const file = join(codexDir, "config.toml");
986
+ const text = await readConfig(file);
987
+ if (text !== null && touchesTable(text, ["mcp_servers", "peer2peer"]))
988
+ return `the project config ${file} sets mcp_servers.peer2peer (a trusted project can replace this server)`;
989
+ }
990
+ return undefined;
991
+ }
992
+ /** The folders whose `.codex/config.toml` Codex reads as project layers for `cwd`: it and each parent up to the repo root (just `cwd` outside a repo). */
993
+ export function projectConfigDirsOf(cwd, top) {
994
+ const out = [cwd];
995
+ if (!top || !isInside(cwd, top))
996
+ return out;
997
+ let d = cwd;
998
+ while (!samePath(d, top)) {
999
+ const up = dirname(d);
1000
+ if (up === d)
1001
+ break;
1002
+ d = up;
1003
+ out.push(d);
1004
+ }
1005
+ return out;
1006
+ }
1007
+ /**
1008
+ * The P2P_HOME the bridges use, for the person's `p2p codex …` commands and
1009
+ * the hooks: the user-level config's value when it sets one (that's what the
1010
+ * bridge takes), else the environment's, else ~/.p2p.
1011
+ */
1012
+ export function bridgeHome(env, home = userHome()) {
1013
+ const codexHome = env.CODEX_HOME?.trim() || join(home, ".codex");
1014
+ let fromConfig;
1015
+ try {
1016
+ fromConfig = readTomlTable(readFileSync(join(codexHome, "config.toml"), "utf8"), ["mcp_servers", "peer2peer", "env"])?.P2P_HOME?.trim();
1017
+ }
1018
+ catch { }
1019
+ return fromConfig || env.P2P_HOME?.trim() || join(home, DEFAULT_P2P_DIR);
1020
+ }