agentschat-mcp 0.36.25 → 0.36.26

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.
Files changed (82) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/codex/README.md +1 -1
  3. package/codex/app-server.ts +79 -22
  4. package/codex/bots-config.ts +31 -11
  5. package/codex/bridge.ts +123 -25
  6. package/codex/config.ts +128 -21
  7. package/codex/gui-channel.ts +66 -9
  8. package/codex/inbox-sync.ts +65 -12
  9. package/codex/loop-grants.ts +41 -11
  10. package/codex/manager.ts +101 -25
  11. package/codex/owner.ts +81 -9
  12. package/codex/processes.ts +51 -7
  13. package/codex/run.ts +70 -17
  14. package/codex/runtime-home.ts +41 -11
  15. package/codex/thread-history.ts +77 -30
  16. package/codex/transport.ts +122 -19
  17. package/connector/auth.ts +57 -5
  18. package/connector/backfill.ts +92 -10
  19. package/connector/descriptor.ts +27 -1
  20. package/connector/identities.ts +82 -14
  21. package/connector/ingest.ts +11 -2
  22. package/connector/normalize.ts +32 -12
  23. package/connector/run.ts +314 -67
  24. package/connector/server.ts +95 -26
  25. package/dist/codex-bots.js +410 -73
  26. package/dist/codex-bridge.js +1996 -576
  27. package/dist/connector.js +1286 -493
  28. package/dist/dsh.js +1776 -299
  29. package/dist/muse.js +967 -221
  30. package/dist/server.js +4277 -929
  31. package/dsh/client.js +7 -5
  32. package/dsh/identity-ui/client.js +7 -5
  33. package/dsh/identity-ui/index.js +43 -8
  34. package/dsh/inbound-bridge/index.js +595 -146
  35. package/dsh/src/cli.ts +430 -91
  36. package/dsh/src/patch.ts +295 -15
  37. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  38. package/dsh/tests/dsh.test.ts +990 -3
  39. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  40. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  41. package/muse/src/bridge.ts +54 -13
  42. package/muse/src/cli.ts +226 -41
  43. package/muse/src/client.ts +249 -34
  44. package/muse/src/config.ts +128 -12
  45. package/muse/src/policy.ts +28 -8
  46. package/muse/src/types.ts +1 -0
  47. package/muse/src/typing.ts +18 -1
  48. package/muse/src/wake.ts +237 -35
  49. package/muse/tests/bridge.test.mjs +131 -0
  50. package/muse/tests/client.test.mjs +327 -0
  51. package/muse/tests/config.test.mjs +78 -1
  52. package/muse/tests/hardening.test.mjs +199 -0
  53. package/muse/tests/hardening126.test.mjs +292 -0
  54. package/muse/tests/policy.test.mjs +83 -1
  55. package/muse/tests/wake.test.mjs +134 -6
  56. package/package.json +1 -1
  57. package/scripts/ensure-grok-wakes.mjs +93 -8
  58. package/scripts/example-url-wake-receiver.mjs +254 -61
  59. package/scripts/grok-bind-register.sh +38 -8
  60. package/skills/onboarding.md +9 -9
  61. package/src/argcheck.ts +113 -33
  62. package/src/cli.mjs +98 -14
  63. package/src/dedup.ts +57 -8
  64. package/src/grok-bind.ts +160 -33
  65. package/src/heartbeat.ts +39 -11
  66. package/src/identity-guard.ts +93 -20
  67. package/src/identity.ts +67 -11
  68. package/src/mentions.ts +26 -5
  69. package/src/onboarding-status.ts +134 -11
  70. package/src/profile-selection.ts +269 -18
  71. package/src/profile-store.ts +222 -28
  72. package/src/read-cursor.ts +256 -9
  73. package/src/reconnect.ts +98 -2
  74. package/src/redact.ts +34 -15
  75. package/src/rest-cli.ts +713 -159
  76. package/src/server.ts +285 -93
  77. package/src/session-bind.ts +731 -132
  78. package/src/session-route.ts +183 -12
  79. package/src/team-lead-skill.ts +3 -0
  80. package/src/timestamps.ts +56 -23
  81. package/src/tool-annotations.ts +10 -1
  82. package/src/wake.ts +510 -91
package/codex/manager.ts CHANGED
@@ -1,41 +1,84 @@
1
1
  import { spawn, type ChildProcess } from "node:child_process";
2
- import { mkdirSync, openSync, closeSync, readFileSync, writeFileSync, unlinkSync, existsSync, renameSync } from "node:fs";
3
- import { join, resolve } from "node:path";
2
+ import { mkdirSync, openSync, closeSync, readFileSync, writeFileSync, unlinkSync, lstatSync } from "node:fs";
3
+ import { join, resolve, dirname } from "node:path";
4
4
  import { homedir } from "node:os";
5
5
  import { createHash } from "node:crypto";
6
+ import { fileURLToPath } from "node:url";
6
7
  import { parseArgs } from "node:util";
7
8
  import { loadBots, defaultRegistry, type BotConfig } from "./bots-config.ts";
9
+ import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
8
10
  import { codexPresent } from "./processes.ts";
9
- const { values } = parseArgs({ options: { "codex-bots": { type: "boolean" }, config: { type: "string" }, "watch-codex": { type: "boolean" }, check: { type: "boolean" }, status: { type: "boolean" }, help: { type: "boolean" } } });
10
- const root = join(homedir(), ".agentschat/codex-bots"), registry = resolve(values.config ?? defaultRegistry());
11
+ let values: { config?: string; "watch-codex"?: boolean; check?: boolean; status?: boolean; help?: boolean } = {};
12
+ const root = join(homedir(), ".agentschat/codex-bots");
13
+ let registry = "";
11
14
  const statusFile = join(root, "status.json"), lock = join(root, "manager.lock");
12
- interface Worker { child?: ChildProcess; config: BotConfig; fingerprint: string; failures: number; next: number; status: string }
15
+ export interface Worker { child?: ChildProcess; config: BotConfig; fingerprint: string; failures: number; next: number; status: string }
13
16
  const workers = new Map<string, Worker>();
14
- let stopping = false, missing = 0, timer: ReturnType<typeof setTimeout> | undefined;
15
- function removeDeadLock(file: string) {
16
- if (!existsSync(file)) return;
17
- const pid = Number(readFileSync(file, "utf8"));
18
- if (!Number.isInteger(pid) || pid <= 0) return;
19
- try { process.kill(pid, 0); } catch (e: any) { if (e.code === "ESRCH") unlinkSync(file); }
17
+ let stopping = false, missing = 0, saveSeq = 0, timer: ReturnType<typeof setTimeout> | undefined;
18
+ export function removeDeadLock(file: string) {
19
+ let raw: string;
20
+ try {
21
+ assertDirectoryAncestors(dirname(file));
22
+ const stat = lstatSync(file);
23
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 64 * 1024) return;
24
+ raw = readFileSync(file, "utf8").trim();
25
+ } catch { return; }
26
+ const pid = Number(raw);
27
+ if (!/^\d+$/.test(raw) || !Number.isSafeInteger(pid) || pid <= 0) {
28
+ try { unlinkSync(file); } catch {}
29
+ return;
30
+ }
31
+ try { process.kill(pid, 0); } catch (e: any) { if (e.code === "ESRCH") try { unlinkSync(file); } catch {} }
20
32
  }
21
- function save() {
22
- writeFileSync(statusFile + ".tmp", JSON.stringify({ pid: process.pid, updated_at: new Date().toISOString(), bots: [...workers.values()].map(w => ({ name: w.config.name, agent_id: w.config.agentId, workdir: w.config.cwd, effort: w.config.effort, model: w.config.model, pid: w.child?.pid, status: w.status })) }, null, 2), { mode: 0o600 });
23
- renameSync(statusFile + ".tmp", statusFile);
33
+ export function save(rootDir = root) {
34
+ const statusFile = join(rootDir, "status.json");
35
+ const tmp = `${statusFile}.${process.pid}.${++saveSeq}.tmp`;
36
+ let created = false;
37
+ try {
38
+ assertDirectoryAncestors(rootDir);
39
+ const dir = lstatSync(rootDir);
40
+ if (dir.isSymbolicLink() || !dir.isDirectory()) return;
41
+ try { if (lstatSync(statusFile).isSymbolicLink()) return; }
42
+ catch (e: any) { if (e.code !== "ENOENT") return; }
43
+ writeFileSync(tmp, JSON.stringify({ pid: process.pid, updated_at: new Date().toISOString(), bots: [...workers.values()].map(w => ({ name: w.config.name, agent_id: w.config.agentId, workdir: w.config.cwd, effort: w.config.effort, model: w.config.model, pid: w.child?.pid, status: w.status })) }, null, 2), { mode: 0o600, flag: "wx" });
44
+ created = true;
45
+ atomicReplaceRegularFile(tmp, statusFile, () => {
46
+ assertDirectoryAncestors(rootDir);
47
+ const currentDir = lstatSync(rootDir);
48
+ const currentFile = lstatSync(statusFile, { throwIfNoEntry: false });
49
+ if (currentDir.isSymbolicLink() || !currentDir.isDirectory() ||
50
+ (currentFile && (currentFile.isSymbolicLink() || !currentFile.isFile()))) throw new Error("Unsafe status destination");
51
+ });
52
+ } catch {
53
+ if (created) try { unlinkSync(tmp); } catch {}
54
+ }
24
55
  }
25
- async function stop(w: Worker) {
56
+ export async function stop(w: Worker) {
26
57
  const child = w.child;
27
58
  if (child && child.exitCode === null && child.signalCode === null) await new Promise<void>(done => {
28
59
  const timeout = setTimeout(() => killGroup(child), 20_000);
29
- child.once("exit", () => { clearTimeout(timeout); killGroup(child); done(); }); child.kill("SIGTERM");
60
+ timeout.unref?.();
61
+ const exited = () => { clearTimeout(timeout); killGroup(child); done(); };
62
+ child.once("exit", exited);
63
+ try { child.kill("SIGTERM"); }
64
+ catch { clearTimeout(timeout); child.removeListener("exit", exited); done(); }
30
65
  });
31
66
  w.child = undefined; w.status = "stopped";
32
67
  }
33
- function killGroup(child: ChildProcess) { if (child.pid) try { process.kill(-child.pid, "SIGKILL"); } catch {} }
34
- function start(w: Worker) {
68
+ function killGroup(child: ChildProcess) {
69
+ if (!child.pid) return;
70
+ if (process.platform !== "win32") {
71
+ try { process.kill(-child.pid, "SIGKILL"); return; } catch {}
72
+ }
73
+ try { child.kill("SIGKILL"); } catch {}
74
+ }
75
+ export function start(w: Worker, spawnWorker = spawn) {
35
76
  removeDeadLock(join(w.config.stateDir, "bridge.lock")); w.status = "starting";
36
- const child = spawn(process.execPath, [resolve(process.argv[1]!), "--codex-bridge", "--managed-worker"], { cwd: w.config.cwd, detached: true, stdio: ["ignore", "pipe", "pipe", "ipc"] });
77
+ const child = spawnWorker(process.execPath, [resolve(process.argv[1]!), "--codex-bridge", "--managed-worker"], { cwd: w.config.cwd, detached: process.platform !== "win32", windowsHide: true, stdio: ["ignore", "pipe", "pipe", "ipc"] });
37
78
  w.child = child;
38
- child.once("spawn", () => child.send(w.config, () => {}));
79
+ child.once("spawn", () => {
80
+ if (child.connected) try { child.send(w.config, () => {}); } catch {}
81
+ });
39
82
  let buffer = "";
40
83
  child.stderr?.on("data", data => {
41
84
  buffer = (buffer + String(data)).slice(-8192);
@@ -61,21 +104,54 @@ async function tick() {
61
104
  missing = active ? 0 : missing + 1;
62
105
  for (const w of workers.values()) {
63
106
  if (stopping) break;
64
- if (active && !w.child && Date.now() >= w.next) start(w);
107
+ const now = Date.now();
108
+ if (w.next - now > 60_000) w.next = now + 60_000;
109
+ if (active && !w.child && now >= w.next) start(w);
65
110
  else if (!active && missing >= 2 && w.child) await stop(w);
66
111
  }
67
112
  save();
68
113
  }
114
+ export function removeOwnedLock(file: string) {
115
+ try {
116
+ assertDirectoryAncestors(dirname(file));
117
+ const stat = lstatSync(file);
118
+ if (!stat.isSymbolicLink() && stat.isFile() && stat.size <= 64 * 1024 && readFileSync(file, "utf8").trim() === String(process.pid)) unlinkSync(file);
119
+ } catch {}
120
+ }
69
121
  async function main() {
70
122
  if (values.help) { console.log("agentschat-mcp --codex-bots [--config FILE] [--watch-codex] [--check|--status]\nCentral registry: ~/.agentschat/codex-bots.json; profiles: ~/.agentschat/profiles\nWatch polls external Codex processes every 5 seconds."); return; }
71
- if (values.status) { console.log(readFileSync(statusFile, "utf8")); return; }
123
+ if (values.status) {
124
+ try {
125
+ assertDirectoryAncestors(root);
126
+ const stat = lstatSync(statusFile);
127
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1_048_576) throw new Error("Unsafe status file");
128
+ const raw = readFileSync(statusFile, "utf8"), status = JSON.parse(raw);
129
+ if (!status || typeof status !== "object" || Array.isArray(status) ||
130
+ Object.prototype.hasOwnProperty.call(status, "__proto__")) throw new Error("Invalid status file");
131
+ console.log(raw);
132
+ } catch { console.error("Bot manager status unavailable; status file is missing, unsafe, or unreadable"); process.exitCode = 1; }
133
+ return;
134
+ }
72
135
  const configs = loadBots(registry);
73
136
  if (values.check) { console.log(JSON.stringify(configs.map(c => ({ name: c.name, agent_id: c.agentId, workdir: c.cwd, profile: c.profileFile })))); return; }
74
- mkdirSync(root, { recursive: true, mode: 0o700 }); removeDeadLock(lock);
137
+ for (const directory of [join(homedir(), ".agentschat"), root]) {
138
+ const stat = lstatSync(directory, { throwIfNoEntry: false });
139
+ if (stat && (stat.isSymbolicLink() || !stat.isDirectory())) throw new Error("Unsafe manager directory");
140
+ }
141
+ assertDirectoryAncestors(root);
142
+ mkdirSync(root, { recursive: true, mode: 0o700 });
143
+ const dir = lstatSync(root);
144
+ if (dir.isSymbolicLink() || !dir.isDirectory()) throw new Error("Unsafe manager directory");
145
+ removeDeadLock(lock);
146
+ if (lstatSync(lock, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error("Unsafe manager lock");
75
147
  const fd = openSync(lock, "wx", 0o600); writeFileSync(fd, String(process.pid)); closeSync(fd);
76
148
  let running: Promise<void> = Promise.resolve();
77
149
  const loop = () => { running = tick().catch(() => console.error("Supervisor tick failed")).finally(() => { if (!stopping) timer = setTimeout(loop, 5000); }); };
78
- const shutdown = async () => { if (stopping) return; stopping = true; clearTimeout(timer); await running; await Promise.all([...workers.values()].map(stop)); save(); if (readFileSync(lock, "utf8") === String(process.pid)) unlinkSync(lock); };
150
+ const shutdown = async () => { if (stopping) return; stopping = true; clearTimeout(timer); await running; await Promise.all([...workers.values()].map(stop)); save(); removeOwnedLock(lock); };
79
151
  process.once("SIGINT", () => void shutdown()); process.once("SIGTERM", () => void shutdown()); loop();
80
152
  }
81
- main().catch(() => { console.error("Bot manager failed; check registry, profile permissions, and existing manager"); process.exitCode = 1; });
153
+ if (import.meta.main || process.argv.includes("--codex-bots") || (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url))) {
154
+ ({ values } = parseArgs({ options: { "codex-bots": { type: "boolean" }, config: { type: "string" }, "watch-codex": { type: "boolean" }, check: { type: "boolean" }, status: { type: "boolean" }, help: { type: "boolean" } } }));
155
+ registry = resolve(values.config ?? defaultRegistry());
156
+ main().catch(() => { console.error("Bot manager failed; check registry, profile permissions, and existing manager"); process.exitCode = 1; });
157
+ }
package/codex/owner.ts CHANGED
@@ -1,3 +1,54 @@
1
+ /** URL parsing canonicalizes numeric IPv4 and mapped IPv6 before this check. */
2
+ export function blockedServerHost(url: URL): boolean {
3
+ const host = url.hostname.toLowerCase().replace(/\.+$/, "").replace(/^\[|\]$/g, "");
4
+ if (!host || host === "0.0.0.0" || /^0\./.test(host) || host === "::" || host === "0:0:0:0:0:0:0:0" ||
5
+ /^169\.254\./.test(host) || host === "100.100.100.200" ||
6
+ host === "fd00:ec2::254" || host === "fd00:ec2:0:0:0:0:0:254" ||
7
+ host === "metadata" || host === "instance-data" ||
8
+ host === "metadata.google.internal" || host.endsWith(".metadata.google.internal") ||
9
+ host === "metadata.goog" || host.endsWith(".metadata.goog") ||
10
+ /^fe[89ab][0-9a-f]:/.test(host)) {
11
+ return true;
12
+ }
13
+ if (host.startsWith("::ffff:")) {
14
+ const rawTail = host.slice(7);
15
+ if (rawTail === "0:0" || rawTail === "0.0.0.0") return true;
16
+ const tail = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(rawTail) ? rawTail.slice(2) : rawTail;
17
+ if (tail === "0:0" || tail === "0.0.0.0" || /^0\./.test(tail) || /^[0-9a-f]{1,2}:[0-9a-f]{1,4}$/.test(tail) ||
18
+ /^127\./.test(tail) || /^7f[0-9a-f]{2}:/.test(tail) ||
19
+ /^169\.254\./.test(tail) || /^a9fe:/.test(tail) ||
20
+ tail === "100.100.100.200" || tail === "6464:64c8") {
21
+ return true;
22
+ }
23
+ }
24
+ return false;
25
+ }
26
+
27
+ /** Read bounded response bytes before decoding or parsing untrusted JSON. */
28
+ async function ownerJson(response: Response): Promise<unknown> {
29
+ if (!response.body) throw new Error("Missing owner response");
30
+ const reader = response.body.getReader();
31
+ const chunks: Uint8Array[] = [];
32
+ let size = 0;
33
+ try {
34
+ while (true) {
35
+ const { done, value } = await reader.read();
36
+ if (done) break;
37
+ size += value.byteLength;
38
+ if (size > 65_536) {
39
+ // Cancel without awaiting a possibly stalled transport cancellation.
40
+ void reader.cancel().catch(() => {});
41
+ throw new Error("Owner response exceeds size limit");
42
+ }
43
+ chunks.push(value);
44
+ }
45
+ } finally { reader.releaseLock(); }
46
+ const bytes = new Uint8Array(size);
47
+ let offset = 0;
48
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
49
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
50
+ }
51
+
1
52
  /** Resolve only this authenticated bot's owner; callers must compare sender IDs. */
2
53
  export async function getBotOwner(
3
54
  base: string,
@@ -6,7 +57,16 @@ export async function getBotOwner(
6
57
  request: typeof fetch = fetch,
7
58
  ): Promise<string | null> {
8
59
  try {
9
- const origin = base.replace(/\/+$/, "");
60
+ if (!base || base !== base.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(base) ||
61
+ !agentId || agentId !== agentId.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId) ||
62
+ /%(?:2e%2e|2f|5c|00)/i.test(agentId) ||
63
+ [".", "..", "__proto__", "constructor", "prototype"].includes(agentId.toLowerCase()) || /[\/\\\s]/.test(agentId) ||
64
+ !token || token !== token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) return null;
65
+ const parsed = new URL(base);
66
+ const loopback = ["127.0.0.1", "localhost", "[::1]", "::1"].includes(parsed.hostname.toLowerCase().replace(/\.$/, ""));
67
+ if (blockedServerHost(parsed) || (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) ||
68
+ parsed.username || parsed.password || parsed.search || parsed.hash || parsed.port === "0") return null;
69
+ const origin = parsed.href.replace(/\/+$/, "");
10
70
  const options: RequestInit = {
11
71
  method: "GET",
12
72
  headers: { Authorization: `Bearer ${token}` },
@@ -14,19 +74,31 @@ export async function getBotOwner(
14
74
  redirect: "error",
15
75
  signal: AbortSignal.timeout(8_000),
16
76
  };
17
- const [statusResponse, entitlementResponse] = await Promise.all([
77
+ const [statusSettled, entitlementSettled] = await Promise.allSettled([
18
78
  request(`${origin}/api/account/onboarding`, options),
19
79
  request(`${origin}/api/me/entitlements`, options),
20
80
  ]);
21
- if (!statusResponse.ok || !entitlementResponse.ok) return null;
22
- const [status, entitlement] = await Promise.all([
23
- statusResponse.json(),
24
- entitlementResponse.json(),
81
+ const statusResponse = statusSettled.status === "fulfilled" ? statusSettled.value : null;
82
+ const entitlementResponse = entitlementSettled.status === "fulfilled" ? entitlementSettled.value : null;
83
+ if (!statusResponse?.ok || !entitlementResponse?.ok) {
84
+ await Promise.allSettled([
85
+ statusResponse?.body?.cancel(),
86
+ entitlementResponse?.body?.cancel(),
87
+ ]);
88
+ return null;
89
+ }
90
+ const [statusValue, entitlementValue] = await Promise.all([
91
+ ownerJson(statusResponse),
92
+ ownerJson(entitlementResponse),
25
93
  ]);
26
- if (!status || Array.isArray(status) || status.agent_id !== agentId || status.claimed !== true) return null;
27
- if (!entitlement || Array.isArray(entitlement)) return null;
94
+ const status = statusValue as Record<string, unknown> | null;
95
+ const entitlement = entitlementValue as Record<string, unknown> | null;
96
+ if (!status || typeof status !== "object" || Array.isArray(status) || Object.hasOwn(status, "__proto__") || status.agent_id !== agentId || status.claimed !== true) return null;
97
+ if (!entitlement || typeof entitlement !== "object" || Array.isArray(entitlement) || Object.hasOwn(entitlement, "__proto__")) return null;
28
98
  const owner = entitlement.owner_account_id;
29
- return typeof owner === "string" && owner.trim().length > 0 && owner !== agentId ? owner : null;
99
+ return typeof owner === "string" && owner.trim().length > 0 && owner === owner.trim() &&
100
+ !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(owner) && !/%(?:2e%2e|2f|5c|00)/i.test(owner) && owner !== agentId &&
101
+ ![".", "..", "__proto__", "constructor", "prototype"].includes(owner.toLowerCase()) ? owner : null;
30
102
  } catch {
31
103
  // Missing endpoints, failed authentication and unavailable ownership all fail closed.
32
104
  // Never retain a previous owner or expose response bodies / credentials in diagnostics.
@@ -1,21 +1,65 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
- import { basename } from "node:path";
4
3
 
5
4
  export interface ProcessRow { pid: number; ppid: number; command: string }
6
5
  export function parseProcesses(text: string): ProcessRow[] {
7
- return text.split("\n").flatMap(line => {
6
+ if (typeof text !== "string" || !text) return [];
7
+ return text.split(/\r?\n/, 65_536).flatMap(line => {
8
+ if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(line)) return [];
8
9
  const m = /^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(line);
9
- return m ? [{ pid: Number(m[1]), ppid: Number(m[2]), command: m[3]!.trim() }] : [];
10
+ if (!m) return [];
11
+ const pid = Number(m[1]), ppid = Number(m[2]);
12
+ return Number.isSafeInteger(pid) && pid > 0 && Number.isSafeInteger(ppid) && ppid >= 0
13
+ ? [{ pid, ppid, command: m[3]!.trim() }] : [];
10
14
  });
11
15
  }
16
+ function commandBasename(cmd: string): string {
17
+ const trimmed = cmd.trim();
18
+ const basename = (path: string) => (path.split(/[\\/]/).pop() || "").trim().replace(/\.(?:exe|cmd|bat)$/i, "").toLowerCase();
19
+ if (trimmed.startsWith('"')) {
20
+ const end = trimmed.indexOf('"', 1);
21
+ return end < 0 ? "" : basename(trimmed.slice(1, end));
22
+ }
23
+ const first = trimmed.split(/\s+/, 1)[0]!;
24
+ return basename(first) === "codex" ? "codex" : basename(trimmed);
25
+ }
12
26
  export function externalCodexPresent(rows: ProcessRow[], managerPid: number): boolean {
13
- const children = new Set([managerPid]);
14
- let changed = true;
15
- while (changed) { changed = false; for (const row of rows) if (children.has(row.ppid) && !children.has(row.pid)) { children.add(row.pid); changed = true; } }
16
- return rows.some(r => !children.has(r.pid) && basename(r.command) === "codex");
27
+ if (!Array.isArray(rows) || rows.length === 0) return false;
28
+ const children = new Set<number>(Number.isSafeInteger(managerPid) && managerPid > 0 ? [managerPid] : []);
29
+ const byParent = new Map<number, number[]>();
30
+ for (const row of rows) {
31
+ if (!row || !Number.isSafeInteger(row.pid) || row.pid <= 0) continue;
32
+ const ppid = row.ppid;
33
+ if (!Number.isSafeInteger(ppid) || ppid < 0) continue;
34
+ const siblings = byParent.get(ppid);
35
+ if (siblings) siblings.push(row.pid);
36
+ else byParent.set(ppid, [row.pid]);
37
+ }
38
+ const queue = [...children];
39
+ for (let i = 0; i < queue.length; i++) {
40
+ for (const pid of byParent.get(queue[i]!) ?? []) {
41
+ if (children.has(pid)) continue;
42
+ children.add(pid); queue.push(pid);
43
+ }
44
+ }
45
+ return rows.some(r => Boolean(r) && typeof r.command === "string" && Number.isSafeInteger(r.pid) && r.pid > 0 && !children.has(r.pid) && commandBasename(r.command) === "codex");
17
46
  }
18
47
  export async function codexPresent(managerPid = process.pid): Promise<boolean> {
48
+ if (process.platform === "win32") {
49
+ const { stdout } = await promisify(execFile)(
50
+ "powershell.exe",
51
+ [
52
+ "-NoProfile",
53
+ "-NonInteractive",
54
+ "-ExecutionPolicy",
55
+ "Bypass",
56
+ "-Command",
57
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId) $($_.Name)\" }",
58
+ ],
59
+ { timeout: 5000, maxBuffer: 4 * 1024 * 1024, windowsHide: true },
60
+ );
61
+ return externalCodexPresent(parseProcesses(stdout), managerPid);
62
+ }
19
63
  const { stdout } = await promisify(execFile)("/bin/ps", ["-axo", "pid=,ppid=,comm="], { timeout: 5000, maxBuffer: 4 * 1024 * 1024 });
20
64
  return externalCodexPresent(parseProcesses(stdout), managerPid);
21
65
  }
package/codex/run.ts CHANGED
@@ -3,13 +3,13 @@ import { redactSecrets } from "../src/redact.ts";
3
3
  import { getBotOwner } from "./owner.ts";
4
4
  import { getOnboardingStatus } from "../src/onboarding-status.ts";
5
5
  import { GuiChannel } from "./gui-channel.ts";
6
- import { readFileSync } from "node:fs";
6
+ import { readFileSync, lstatSync } from "node:fs";
7
7
  import { homedir } from "node:os";
8
- import { join } from "node:path";
8
+ import { join, dirname } from "node:path";
9
9
  import { loadBots } from "./bots-config.ts";
10
10
  import type { BridgeConfig } from "./config.ts";
11
11
  import { parseArgs } from "node:util";
12
- import { resolveConfig } from "./config.ts";
12
+ import { assertDirectoryAncestors, resolveConfig } from "./config.ts";
13
13
  import { AppServer } from "./app-server.ts";
14
14
  import { Bridge } from "./bridge.ts";
15
15
  import { AgentsChatTransport } from "./transport.ts";
@@ -42,15 +42,29 @@ See codex/README.md for setup, verification, limitations and recovery.
42
42
  `;
43
43
 
44
44
  let codex: AppServer | undefined, bridge: Bridge | undefined, transport: AgentsChatTransport | undefined;
45
+ function isPlainObject(value: unknown): value is Record<string, unknown> {
46
+ return value !== null && typeof value === "object" && !Array.isArray(value) &&
47
+ (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
48
+ }
49
+ const IPC_CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
50
+ function isCleanIpcString(value: unknown, allowEmpty = false): value is string {
51
+ return typeof value === "string" && (allowEmpty || value.length > 0) && !IPC_CONTROL_CHAR_RE.test(value);
52
+ }
45
53
  async function main() {
46
54
  const { values } = parseArgs({ options: { "codex-bridge": { type: "boolean" }, cwd: { type: "string" },
47
55
  "state-root": { type: "string" }, "codex-home-mode": { type: "string" }, "conversations": { type: "boolean" }, "read-conversation": { type: "string" }, "gui-thread": { type: "string" }, "gui-message-file": { type: "string" }, "gui-status": { type: "boolean" }, "managed-worker": { type: "boolean" }, registry: { type: "string" }, bot: { type: "string" }, profile: { type: "string" }, "codex-bin": { type: "string" }, check: { type: "boolean" }, "onboarding-status": { type: "boolean" },
48
56
  help: { type: "boolean", short: "h" } }, strict: true });
49
57
  if (values.help) { console.log(HELP); return; }
50
58
  if (values["gui-thread"] || values["gui-message-file"] || values["gui-status"]) {
59
+ const parent = lstatSync(join(homedir(), ".agentschat"), { throwIfNoEntry: false });
60
+ if (parent && (parent.isSymbolicLink() || !parent.isDirectory())) throw new Error("GUI parent must be a real directory, not a symlink");
51
61
  const channel = new GuiChannel(join(homedir(), ".agentschat/codex-gui-outbox"), values["gui-thread"] ? [values["gui-thread"]] : []);
52
62
  if (values["gui-status"]) { console.log(JSON.stringify(channel.list().map(({prompt, ...receipt}) => receipt))); return; }
53
63
  if (!values["gui-thread"] || !values["gui-message-file"]) throw new Error("GUI submission requires --gui-thread and --gui-message-file");
64
+ assertDirectoryAncestors(dirname(values["gui-message-file"]));
65
+ const stat = lstatSync(values["gui-message-file"]);
66
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("GUI message must be a regular file, not a symlink");
67
+ if (stat.size > 256 * 1024) throw new Error("GUI message file exceeds 256 KiB");
54
68
  const {prompt, ...receipt} = channel.enqueue(values["gui-thread"], readFileSync(values["gui-message-file"], "utf8"));
55
69
  console.log(JSON.stringify(receipt)); return;
56
70
  }
@@ -58,7 +72,25 @@ async function main() {
58
72
  const snapshot = values["managed-worker"] ? await new Promise<BridgeConfig>((resolve, reject) => {
59
73
  if (!process.connected) { reject(new Error("Managed worker needs parent IPC")); return; }
60
74
  const timer = setTimeout(() => reject(new Error("Parent configuration missing")), 10000);
61
- process.once("message", config => { clearTimeout(timer); resolve(config as BridgeConfig); });
75
+ timer.unref?.();
76
+ process.once("message", config => {
77
+ clearTimeout(timer);
78
+ if (!isPlainObject(config) || Object.prototype.hasOwnProperty.call(config, "__proto__") ||
79
+ !isCleanIpcString(config.cwd) ||
80
+ !isCleanIpcString(config.stateDir) ||
81
+ !isCleanIpcString(config.agentId) ||
82
+ !isCleanIpcString(config.token) ||
83
+ !isCleanIpcString(config.apiUrl, true) ||
84
+ !isCleanIpcString(config.wsUrl, true) ||
85
+ (config.codexBin !== undefined && !isCleanIpcString(config.codexBin)) ||
86
+ (config.model !== undefined && !isCleanIpcString(config.model)) ||
87
+ (config.effort !== undefined && !isCleanIpcString(config.effort)) ||
88
+ (config.permissions !== undefined && config.permissions !== "full-access" && config.permissions !== "read-only") ||
89
+ (config.codexHomeMode !== undefined && config.codexHomeMode !== "linked" && config.codexHomeMode !== "isolated" && config.codexHomeMode !== "auth-only") ||
90
+ (config.channels !== undefined && (!Array.isArray(config.channels) || config.channels.some(ch => !isCleanIpcString(ch)))) ||
91
+ (config.senders !== undefined && (!Array.isArray(config.senders) || config.senders.some(s => !isCleanIpcString(s))))) { reject(new Error("Invalid parent configuration")); return; }
92
+ resolve(config as unknown as BridgeConfig);
93
+ });
62
94
  }) : undefined;
63
95
  const c = snapshot ?? (values.bot ? loadBots(values.registry).find(b => b.name === values.bot) : resolveConfig({ cwd: values.cwd, profile: values.profile, codexBin: values["codex-bin"], stateRoot: values["state-root"], codexHomeMode: values["codex-home-mode"] }));
64
96
  if (!c) throw new Error("Bot is absent or disabled");
@@ -72,16 +104,31 @@ async function main() {
72
104
  const runtime = prepareRuntimeHome(c.stateDir, undefined, c.codexHomeMode, c.codexBin);
73
105
  codex = new AppServer(c.codexBin, undefined, undefined, c.permissions, runtime, c.effort, c.model, { profileFile: c.profileFile, agentId: c.agentId, apiUrl: c.apiUrl, wsUrl: c.wsUrl });
74
106
  if (values.conversations || values["read-conversation"]) {
75
- const state = JSON.parse(readFileSync(join(c.stateDir, "state.json"), "utf8"));
76
- const channels = state.channels ?? {};
77
- if (values.conversations) { console.log(JSON.stringify(Object.entries(channels).map(([channel, data]: [string, any]) => ({channel, thread:data.thread, isolated:data.namespace===runtime.home})))); return; }
78
- const channel = channels[values["read-conversation"]!];
79
- if (!channel) throw new Error("Unknown conversation channel");
107
+ const dir = lstatSync(c.stateDir), stateFile = join(c.stateDir, "state.json");
108
+ if (dir.isSymbolicLink() || !dir.isDirectory()) throw new Error("Conversation state must use a real directory");
109
+ assertDirectoryAncestors(c.stateDir);
110
+ const stat = lstatSync(stateFile);
111
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024) throw new Error("Unsafe conversation state file");
112
+ const state = JSON.parse(readFileSync(stateFile, "utf8"));
113
+ if (!isPlainObject(state) || Object.prototype.hasOwnProperty.call(state, "__proto__")) throw new Error("Invalid conversation state");
114
+ const channels = state?.channels === undefined ? {} : state.channels;
115
+ if (!isPlainObject(channels) || Object.prototype.hasOwnProperty.call(channels, "__proto__")) throw new Error("Invalid conversation channels");
116
+ const safeOutput = (value: unknown) => {
117
+ const text = JSON.stringify(value);
118
+ return redactSecrets(typeof c.token === "string" && c.token.length > 0 ? text.split(c.token).join("[REDACTED]") : text);
119
+ };
120
+ if (values.conversations) { console.log(safeOutput(Object.entries(channels).map(([channel, data]: [string, any]) => ({channel, thread:data.thread, isolated:data.namespace===runtime.home})))); return; }
121
+ const key = values["read-conversation"]!;
122
+ if (!Object.prototype.hasOwnProperty.call(channels, key)) throw new Error("Unknown conversation channel");
123
+ const channel = channels[key];
124
+ if (!isPlainObject(channel) || typeof channel.thread !== "string" || !channel.thread) throw new Error("Invalid conversation channel");
80
125
  if (channel.namespace && channel.namespace !== runtime.home) throw new Error("Conversation belongs to a different runtime home");
81
126
  await codex.start();
82
- const history = channel.namespace ? await codex.readThread(channel.thread) : await codex.readLegacyThread(channel.thread);
83
- console.log(redactSecrets(JSON.stringify(history).split(c.token).join("[REDACTED]")));
84
- codex.close(); return;
127
+ try {
128
+ const history = channel.namespace ? await codex.readThread(channel.thread) : await codex.readLegacyThread(channel.thread);
129
+ console.log(safeOutput(history));
130
+ } finally { codex.close(); }
131
+ return;
85
132
  }
86
133
  if (c.permissions === "full-access") {
87
134
  const identityStatus = await getOnboardingStatus(c.apiUrl, c.agentId, c.token);
@@ -91,9 +138,11 @@ async function main() {
91
138
  }
92
139
  if (values.check) {
93
140
  await codex.start();
94
- console.log("Official app-server initialization: OK (no chat connection or generation)");
95
- console.log(JSON.stringify({ authentication: await codex.authenticationStatus(), generation_verified: false, reply_verified: false, codex_home_mode: c.codexHomeMode ?? "linked" }));
96
- codex.close(); return;
141
+ try {
142
+ console.log("Official app-server initialization: OK (no chat connection or generation)");
143
+ console.log(JSON.stringify({ authentication: await codex.authenticationStatus(), generation_verified: false, reply_verified: false, codex_home_mode: c.codexHomeMode ?? "linked" }));
144
+ } finally { codex.close(); }
145
+ return;
97
146
  }
98
147
  transport = new AgentsChatTransport(c, m => { bridge!.accept(m); }, console.error, m => bridge!.recover(m));
99
148
  bridge = new Bridge(c, codex, (chat, text) => transport!.send(chat, text), console.error, (chat, active) => transport!.setTyping(chat, active), () => getBotOwner(c.apiUrl, c.agentId, c.token), () => transport!.api("/api/loops/mine"));
@@ -107,7 +156,11 @@ async function main() {
107
156
  void bridge.drain(); transport.start();
108
157
  }
109
158
  main().catch(async e => {
110
- // Do not echo arbitrary parse errors or subprocess output containing credentials.
111
- console.error(`Bridge startup failed: ${e instanceof Error && !/token|secret/i.test(e.message) ? e.message : "invalid configuration"}`);
159
+ // Do not echo arbitrary parse errors, terminal escape codes, or subprocess output containing credentials.
160
+ const rawMessage = e instanceof Error
161
+ ? e.message.replace(/\x1b\[[0-9;]*[A-Za-z]|[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ").trim()
162
+ : "";
163
+ const diagnostic = rawMessage ? redactSecrets(rawMessage) : "invalid configuration";
164
+ console.error(`Bridge startup failed: ${/token|secret|bearer|password|key|cookie|authorization|credential/i.test(diagnostic) ? "invalid configuration" : diagnostic}`);
112
165
  transport?.stop(); codex?.close(); await bridge?.stop(); process.exitCode = 1;
113
166
  });
@@ -1,19 +1,43 @@
1
1
  import { existsSync, mkdirSync, readdirSync, accessSync, constants, lstatSync, readlinkSync, realpathSync, symlinkSync } from "node:fs";
2
- import type { CodexHomeMode } from "./config.ts";
2
+ import { assertDirectoryAncestors, type CodexHomeMode } from "./config.ts";
3
3
  import { homedir } from "node:os";
4
4
  import { delimiter, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
 
6
6
  function executablePath(bin: string): string | undefined {
7
- const candidates = isAbsolute(bin) || bin.includes("/") ? [resolve(bin)] : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map(dir => join(dir, bin));
8
- for (const candidate of candidates) {
9
- try { accessSync(candidate, constants.X_OK); return realpathSync(candidate); } catch { /* Try the next PATH entry. */ }
7
+ if (!bin || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(bin)) return undefined;
8
+ const exts = process.platform === "win32" && !/\.[A-Za-z0-9]+$/.test(bin)
9
+ ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)]
10
+ : [""];
11
+ const bases = isAbsolute(bin) || bin.includes("/") || bin.includes("\\")
12
+ ? [resolve(bin)]
13
+ : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map(dir => join(dir, bin));
14
+ for (const base of bases) {
15
+ for (const ext of exts) {
16
+ const candidate = base + ext;
17
+ try { accessSync(candidate, constants.X_OK); return realpathSync(candidate); } catch { /* Try the next PATH entry. */ }
18
+ }
10
19
  }
11
20
  }
12
21
 
22
+ function assertDirectoryLeaf(path: string, label: string) {
23
+ const info = lstatSync(path, { throwIfNoEntry: false });
24
+ if (info?.isSymbolicLink()) throw new Error(`${label} must not be a symlink`);
25
+ if (info && !info.isDirectory()) throw new Error(`${label} must be a directory`);
26
+ }
27
+
28
+ function prepareHomeDirectory(stateDir: string, home: string) {
29
+ assertDirectoryLeaf(stateDir, "Bot state directory");
30
+ assertDirectoryLeaf(home, "Bot runtime home");
31
+ assertDirectoryAncestors(stateDir);
32
+ assertDirectoryAncestors(home);
33
+ mkdirSync(home, { recursive: true, mode: 0o700 });
34
+ }
35
+
13
36
  /** Inspect metadata only; never follow a runtime-state link into another home. */
14
37
  function assertIndependentTree(home: string, allowedAuthOrigin?: string, codexExecutable?: string) {
15
38
  if (lstatSync(home).isSymbolicLink()) throw new Error("Independent Codex home must not be a symlink");
16
- const inspect = (dir: string) => {
39
+ const inspect = (dir: string, depth = 0) => {
40
+ if (depth > 32) throw new Error("Independent Codex home directory depth exceeds 32");
17
41
  for (const name of readdirSync(dir)) {
18
42
  const path = join(dir, name), info = lstatSync(path);
19
43
  if (info.isSymbolicLink()) {
@@ -26,7 +50,8 @@ function assertIndependentTree(home: string, allowedAuthOrigin?: string, codexEx
26
50
  }
27
51
  throw new Error("Independent Codex home must not link configuration or runtime state");
28
52
  }
29
- if (info.isDirectory()) inspect(path);
53
+ if (info.isDirectory()) inspect(path, depth + 1);
54
+ else if (!info.isFile()) throw new Error("Independent Codex home must contain only regular files and directories");
30
55
  }
31
56
  };
32
57
  inspect(home);
@@ -39,16 +64,19 @@ export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_
39
64
  // Authentication must be set up independently by the operator, with permission.
40
65
  if (mode === "isolated") {
41
66
  const home = join(stateDir, "codex-home-isolated");
42
- mkdirSync(home, { recursive: true, mode: 0o700 });
67
+ prepareHomeDirectory(stateDir, home);
43
68
  assertIndependentTree(home, undefined, executablePath(codexBin));
44
69
  return { home: realpathSync(home) };
45
70
  }
46
71
  if (mode === "auth-only") {
47
72
  const legacyHome = realpathSync(source);
48
73
  const origin = join(legacyHome, "auth.json");
49
- if (!lstatSync(origin).isFile()) throw new Error("auth-only requires an existing regular auth.json; authorize its use explicitly");
74
+ const originStat = lstatSync(origin, { throwIfNoEntry: false });
75
+ if (!originStat || originStat.isSymbolicLink() || !originStat.isFile()) {
76
+ throw new Error("auth-only requires an existing regular auth.json; authorize its use explicitly");
77
+ }
50
78
  const home = join(stateDir, "codex-home-auth-only");
51
- mkdirSync(home, { recursive: true, mode: 0o700 });
79
+ prepareHomeDirectory(stateDir, home);
52
80
  if (lstatSync(home).isSymbolicLink() || realpathSync(home) === legacyHome) throw new Error("auth-only home must be independent");
53
81
  // A reused directory must not smuggle in unrelated configuration or plugins.
54
82
  for (const name of ["config.toml", "AGENTS.md", "rules", "plugins", "hooks.json"]) {
@@ -56,7 +84,8 @@ export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_
56
84
  throw new Error("auth-only home contains unexpected configuration; use a fresh state root");
57
85
  }
58
86
  const skills = join(home, "skills");
59
- if (existsSync(skills) && (!lstatSync(skills).isDirectory() || readdirSync(skills).some(name => name !== ".system")))
87
+ const skillsInfo = lstatSync(skills, { throwIfNoEntry: false });
88
+ if (skillsInfo && (skillsInfo.isSymbolicLink() || !skillsInfo.isDirectory() || readdirSync(skills).some(name => name !== ".system")))
60
89
  throw new Error("auth-only home contains unexpected custom skills");
61
90
  assertIndependentTree(home, origin, executablePath(codexBin));
62
91
  const target = join(home, "auth.json");
@@ -68,8 +97,9 @@ export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_
68
97
  }
69
98
  const legacyHome = existsSync(source) ? realpathSync(source) : resolve(source);
70
99
  const home = join(stateDir, "codex-home");
71
- mkdirSync(home, {recursive:true, mode:0o700});
100
+ prepareHomeDirectory(stateDir, home);
72
101
  if (realpathSync(home) === legacyHome) throw new Error("Bot runtime home must differ from desktop Codex home");
102
+ if (lstatSync(home).isSymbolicLink()) throw new Error("Bot runtime home must not be a symlink");
73
103
  for (const name of ["config.toml", "auth.json", "AGENTS.md", "skills", "rules", "plugins", "hooks.json", "models_cache.json"]) {
74
104
  const origin = join(legacyHome, name), target = join(home, name);
75
105
  if (!existsSync(origin)) continue;