agentschat-mcp 0.36.25 → 0.36.27

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 (86) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +10 -10
  3. package/codex/README.md +4 -4
  4. package/codex/app-server.ts +101 -22
  5. package/codex/bots-config.ts +32 -11
  6. package/codex/bridge.ts +127 -28
  7. package/codex/config.ts +137 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +77 -12
  10. package/codex/loop-grants.ts +49 -11
  11. package/codex/manager.ts +108 -27
  12. package/codex/owner.ts +106 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +51 -11
  16. package/codex/thread-history.ts +87 -30
  17. package/codex/transport.ts +135 -22
  18. package/connector/README.md +1 -1
  19. package/connector/auth.ts +57 -5
  20. package/connector/backfill.ts +92 -10
  21. package/connector/descriptor.ts +27 -1
  22. package/connector/identities.ts +82 -14
  23. package/connector/ingest.ts +11 -2
  24. package/connector/normalize.ts +32 -12
  25. package/connector/run.ts +314 -67
  26. package/connector/server.ts +95 -26
  27. package/cordis.patch.yml +4 -2
  28. package/dist/codex-bots.js +437 -75
  29. package/dist/codex-bridge.js +2111 -582
  30. package/dist/connector.js +1300 -493
  31. package/dist/dsh.js +1789 -299
  32. package/dist/muse.js +967 -221
  33. package/dist/server.js +4410 -919
  34. package/dsh/README.md +1 -1
  35. package/dsh/client.js +7 -5
  36. package/dsh/identity-ui/client.js +7 -5
  37. package/dsh/identity-ui/index.js +43 -8
  38. package/dsh/inbound-bridge/index.js +677 -154
  39. package/dsh/src/cli.ts +430 -91
  40. package/dsh/src/patch.ts +295 -15
  41. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  42. package/dsh/tests/dsh.test.ts +1174 -3
  43. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  44. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  45. package/muse/src/bridge.ts +54 -13
  46. package/muse/src/cli.ts +226 -41
  47. package/muse/src/client.ts +249 -34
  48. package/muse/src/config.ts +128 -12
  49. package/muse/src/policy.ts +28 -8
  50. package/muse/src/types.ts +1 -0
  51. package/muse/src/typing.ts +18 -1
  52. package/muse/src/wake.ts +237 -35
  53. package/muse/tests/bridge.test.mjs +131 -0
  54. package/muse/tests/client.test.mjs +327 -0
  55. package/muse/tests/config.test.mjs +78 -1
  56. package/muse/tests/hardening.test.mjs +199 -0
  57. package/muse/tests/hardening126.test.mjs +292 -0
  58. package/muse/tests/policy.test.mjs +83 -1
  59. package/muse/tests/wake.test.mjs +134 -6
  60. package/package.json +3 -3
  61. package/scripts/ensure-grok-wakes.mjs +93 -8
  62. package/scripts/example-url-wake-receiver.mjs +254 -61
  63. package/scripts/grok-bind-register.sh +38 -8
  64. package/skills/onboarding.md +15 -15
  65. package/src/argcheck.ts +113 -33
  66. package/src/cli.mjs +100 -16
  67. package/src/dedup.ts +57 -8
  68. package/src/grok-bind.ts +182 -33
  69. package/src/heartbeat.ts +39 -11
  70. package/src/identity-guard.ts +93 -20
  71. package/src/identity.ts +67 -11
  72. package/src/mentions.ts +26 -5
  73. package/src/onboarding-status.ts +134 -11
  74. package/src/profile-selection.ts +299 -18
  75. package/src/profile-store.ts +248 -30
  76. package/src/read-cursor.ts +280 -9
  77. package/src/reconnect.ts +98 -2
  78. package/src/redact.ts +34 -15
  79. package/src/rest-cli.ts +713 -159
  80. package/src/server.ts +286 -94
  81. package/src/session-bind.ts +777 -134
  82. package/src/session-route.ts +183 -12
  83. package/src/team-lead-skill.ts +3 -0
  84. package/src/timestamps.ts +56 -23
  85. package/src/tool-annotations.ts +10 -1
  86. package/src/wake.ts +510 -91
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,45 @@
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
+ const RUNTIME_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
7
+
6
8
  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. */ }
9
+ if (!bin || RUNTIME_CTRL_RE.test(bin)) return undefined;
10
+ const exts = process.platform === "win32" && !/\.[A-Za-z0-9]+$/.test(bin)
11
+ ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean)]
12
+ : [""];
13
+ const bases = isAbsolute(bin) || bin.includes("/") || bin.includes("\\")
14
+ ? [resolve(bin)]
15
+ : (process.env.PATH ?? "").split(delimiter).filter(Boolean).map(dir => join(dir, bin));
16
+ for (const base of bases) {
17
+ for (const ext of exts) {
18
+ const candidate = base + ext;
19
+ try { accessSync(candidate, constants.X_OK); return realpathSync(candidate); } catch { /* Try the next PATH entry. */ }
20
+ }
10
21
  }
11
22
  }
12
23
 
24
+ function assertDirectoryLeaf(path: string, label: string) {
25
+ const info = lstatSync(path, { throwIfNoEntry: false });
26
+ if (info?.isSymbolicLink()) throw new Error(`${label} must not be a symlink`);
27
+ if (info && !info.isDirectory()) throw new Error(`${label} must be a directory`);
28
+ }
29
+
30
+ function prepareHomeDirectory(stateDir: string, home: string) {
31
+ assertDirectoryLeaf(stateDir, "Bot state directory");
32
+ assertDirectoryLeaf(home, "Bot runtime home");
33
+ assertDirectoryAncestors(stateDir);
34
+ assertDirectoryAncestors(home);
35
+ mkdirSync(home, { recursive: true, mode: 0o700 });
36
+ }
37
+
13
38
  /** Inspect metadata only; never follow a runtime-state link into another home. */
14
39
  function assertIndependentTree(home: string, allowedAuthOrigin?: string, codexExecutable?: string) {
15
40
  if (lstatSync(home).isSymbolicLink()) throw new Error("Independent Codex home must not be a symlink");
16
- const inspect = (dir: string) => {
41
+ const inspect = (dir: string, depth = 0) => {
42
+ if (depth > 32) throw new Error("Independent Codex home directory depth exceeds 32");
17
43
  for (const name of readdirSync(dir)) {
18
44
  const path = join(dir, name), info = lstatSync(path);
19
45
  if (info.isSymbolicLink()) {
@@ -26,7 +52,8 @@ function assertIndependentTree(home: string, allowedAuthOrigin?: string, codexEx
26
52
  }
27
53
  throw new Error("Independent Codex home must not link configuration or runtime state");
28
54
  }
29
- if (info.isDirectory()) inspect(path);
55
+ if (info.isDirectory()) inspect(path, depth + 1);
56
+ else if (!info.isFile()) throw new Error("Independent Codex home must contain only regular files and directories");
30
57
  }
31
58
  };
32
59
  inspect(home);
@@ -35,20 +62,31 @@ function assertIndependentTree(home: string, allowedAuthOrigin?: string, codexEx
35
62
  /** Reuse operator configuration, never the desktop's databases, sessions or writer locks. */
36
63
  export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_HOME || join(homedir(), ".codex"), mode: CodexHomeMode = "linked", codexBin = "codex") {
37
64
  if (mode !== "linked" && mode !== "isolated" && mode !== "auth-only") throw new Error("Invalid Codex home mode");
65
+ if (typeof stateDir !== "string" || !stateDir.trim() || stateDir.length > 4096 || RUNTIME_CTRL_RE.test(stateDir)) {
66
+ throw new Error("Invalid bot state directory");
67
+ }
38
68
  // Isolated mode deliberately never inspects, copies or links source configuration.
39
69
  // Authentication must be set up independently by the operator, with permission.
40
70
  if (mode === "isolated") {
41
71
  const home = join(stateDir, "codex-home-isolated");
42
- mkdirSync(home, { recursive: true, mode: 0o700 });
72
+ prepareHomeDirectory(stateDir, home);
43
73
  assertIndependentTree(home, undefined, executablePath(codexBin));
44
74
  return { home: realpathSync(home) };
45
75
  }
76
+ if (typeof source !== "string" || !source.trim() || source.length > 4096 || RUNTIME_CTRL_RE.test(source)) {
77
+ throw new Error("Invalid Codex source home");
78
+ }
79
+ assertDirectoryLeaf(source, "Source Codex home");
80
+ assertDirectoryAncestors(source);
46
81
  if (mode === "auth-only") {
47
82
  const legacyHome = realpathSync(source);
48
83
  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");
84
+ const originStat = lstatSync(origin, { throwIfNoEntry: false });
85
+ if (!originStat || originStat.isSymbolicLink() || !originStat.isFile()) {
86
+ throw new Error("auth-only requires an existing regular auth.json; authorize its use explicitly");
87
+ }
50
88
  const home = join(stateDir, "codex-home-auth-only");
51
- mkdirSync(home, { recursive: true, mode: 0o700 });
89
+ prepareHomeDirectory(stateDir, home);
52
90
  if (lstatSync(home).isSymbolicLink() || realpathSync(home) === legacyHome) throw new Error("auth-only home must be independent");
53
91
  // A reused directory must not smuggle in unrelated configuration or plugins.
54
92
  for (const name of ["config.toml", "AGENTS.md", "rules", "plugins", "hooks.json"]) {
@@ -56,7 +94,8 @@ export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_
56
94
  throw new Error("auth-only home contains unexpected configuration; use a fresh state root");
57
95
  }
58
96
  const skills = join(home, "skills");
59
- if (existsSync(skills) && (!lstatSync(skills).isDirectory() || readdirSync(skills).some(name => name !== ".system")))
97
+ const skillsInfo = lstatSync(skills, { throwIfNoEntry: false });
98
+ if (skillsInfo && (skillsInfo.isSymbolicLink() || !skillsInfo.isDirectory() || readdirSync(skills).some(name => name !== ".system")))
60
99
  throw new Error("auth-only home contains unexpected custom skills");
61
100
  assertIndependentTree(home, origin, executablePath(codexBin));
62
101
  const target = join(home, "auth.json");
@@ -68,8 +107,9 @@ export function prepareRuntimeHome(stateDir: string, source = process.env.CODEX_
68
107
  }
69
108
  const legacyHome = existsSync(source) ? realpathSync(source) : resolve(source);
70
109
  const home = join(stateDir, "codex-home");
71
- mkdirSync(home, {recursive:true, mode:0o700});
110
+ prepareHomeDirectory(stateDir, home);
72
111
  if (realpathSync(home) === legacyHome) throw new Error("Bot runtime home must differ from desktop Codex home");
112
+ if (lstatSync(home).isSymbolicLink()) throw new Error("Bot runtime home must not be a symlink");
73
113
  for (const name of ["config.toml", "auth.json", "AGENTS.md", "skills", "rules", "plugins", "hooks.json", "models_cache.json"]) {
74
114
  const origin = join(legacyHome, name), target = join(home, name);
75
115
  if (!existsSync(origin)) continue;
@@ -1,10 +1,22 @@
1
- import { createHash } from "node:crypto";
2
- import { mkdirSync, renameSync, writeFileSync } from "node:fs";
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { chmodSync, lstatSync, mkdirSync, unlinkSync, writeFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
+ import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
5
+
6
+ const HISTORY_FORBIDDEN_KEYS = new Set<string>([
7
+ "__proto__",
8
+ "prototype",
9
+ ...Object.getOwnPropertyNames(Object.prototype),
10
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
11
+ ]);
12
+ const isHistoryForbiddenKey = (key: string) => HISTORY_FORBIDDEN_KEYS.has(key) || HISTORY_FORBIDDEN_KEYS.has(key.toLowerCase());
4
13
 
5
14
  export interface ThreadHistory { id: string; createdAt?: number; turns: any[] }
6
15
  export function priorChannelThreads(threads: Record<string, string>, channel: string): string[] {
7
- return [...new Set(Object.entries(threads).filter(([key]) => {
16
+ if (!threads || typeof threads !== "object" || typeof channel !== "string" || !channel) return [];
17
+ return [...new Set(Object.entries(threads).filter(([key, id]) => {
18
+ if (isHistoryForbiddenKey(key)) return false;
19
+ if (typeof id !== "string" || !id.trim()) return false;
8
20
  if (key === channel) return true;
9
21
  try { const parts = JSON.parse(key); return Array.isArray(parts) && parts[0] === channel; }
10
22
  catch { return false; }
@@ -13,43 +25,88 @@ export function priorChannelThreads(threads: Record<string, string>, channel: st
13
25
 
14
26
  /** Keep complete source turns privately; seed the new task with past chat, not old instructions. */
15
27
  export function preserveChannelHistory(directory: string, channel: string, histories: ThreadHistory[], redact: (s: string) => string): string {
16
- const root = join(directory, "history"); mkdirSync(root, {recursive:true, mode:0o700});
28
+ if (typeof channel !== "string" || !channel.trim() || channel !== channel.trim() || channel.length > 256 ||
29
+ channel === "." || channel.includes("..") || /[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel) ||
30
+ /%(?:2e%2e|2f|5c|00)/i.test(channel) || isHistoryForbiddenKey(channel)) {
31
+ throw new Error("Invalid history channel");
32
+ }
33
+ const checkDirectory = (path: string) => {
34
+ try {
35
+ const stat = lstatSync(path);
36
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("History directory must be a non-symlink directory");
37
+ } catch (error: any) { if (error.code !== "ENOENT") throw error; }
38
+ };
39
+ assertDirectoryAncestors(directory);
40
+ const root = join(directory, "history");
41
+ checkDirectory(directory);
42
+ checkDirectory(root);
43
+ mkdirSync(root, {recursive:true, mode:0o700});
44
+ checkDirectory(root);
45
+ if (process.platform !== "win32") chmodSync(root, 0o700);
17
46
  const file = join(root, createHash("sha256").update(channel).digest("hex").slice(0,24) + ".json");
18
- writeFileSync(file + ".tmp", redact(JSON.stringify({channel_id:channel, threads:histories})), {mode:0o600});
19
- renameSync(file + ".tmp", file);
47
+ try {
48
+ const stat = lstatSync(file);
49
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("History archive must be a regular file, not a symlink");
50
+ } catch (e: any) {
51
+ if (e.code !== "ENOENT") throw e;
52
+ }
53
+ const tmp = `${file}.${process.pid}.${Date.now()}.${randomBytes(4).toString("hex")}.tmp`;
54
+ try {
55
+ writeFileSync(tmp, redact(JSON.stringify({channel_id:channel, threads:histories})), {flag:"wx", mode:0o600});
56
+ if (process.platform !== "win32") chmodSync(tmp, 0o600);
57
+ atomicReplaceRegularFile(tmp, file, () => {
58
+ try {
59
+ const stat = lstatSync(file);
60
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("History archive must be a regular file, not a symlink");
61
+ } catch (error: any) { if (error.code !== "ENOENT") throw error; }
62
+ });
63
+ } catch (err) {
64
+ try { unlinkSync(tmp); } catch { /* Best-effort temp cleanup. */ }
65
+ throw err;
66
+ }
20
67
  const records: { order: string; sequence: number; value: any }[] = [];
21
68
  let sequence = 0;
22
- for (const history of histories) for (const turn of history.turns) {
23
- // Codex turn IDs are UUIDv7 and sort by creation time; keep item order within a turn.
24
- const order = String(turn.id ?? history.createdAt ?? history.id);
25
- for (const item of turn.items ?? []) {
26
- if (item.type === "userMessage") {
27
- let text = (item.content ?? []).filter((part: any) => part.type === "text").map((part: any) => part.text).join("\n");
28
- const marker = "AgentsChat message:\n";
29
- if (text.includes(marker)) {
30
- try {
31
- const message = JSON.parse(text.slice(text.lastIndexOf(marker) + marker.length));
32
- if (message.channel_id === channel) records.push({order,sequence:sequence++,value:{...message,role:"user"}});
33
- continue;
34
- } catch { /* Older bridges used plain-text envelopes; retain them below. */ }
35
- }
36
- // Do not recursively import a previous migration's large preview.
37
- // The complete source remains in the private export; real messages above
38
- // have already been extracted from their envelope.
39
- if (text.startsWith("Previous conversations for this channel have been consolidated.")) {
40
- const end = text.lastIndexOf("End of historical context.\n");
41
- if (end >= 0) text = text.slice(end + "End of historical context.\n".length);
69
+ for (const history of Array.isArray(histories) ? histories : []) {
70
+ if (!history || typeof history !== "object") continue;
71
+ for (const turn of Array.isArray(history.turns) ? history.turns : []) {
72
+ if (!turn || typeof turn !== "object") continue;
73
+ // Codex turn IDs are UUIDv7 and sort by creation time; keep item order within a turn.
74
+ const order = String(turn.id ?? history.createdAt ?? history.id);
75
+ for (const item of Array.isArray(turn.items) ? turn.items : []) {
76
+ if (!item || typeof item !== "object") continue;
77
+ if (item.type === "userMessage") {
78
+ const contentParts = Array.isArray(item.content) ? item.content : [];
79
+ let text = contentParts.filter((part: any) => part?.type === "text" && typeof part.text === "string").map((part: any) => part.text).join("\n");
80
+ const marker = "AgentsChat message:\n";
81
+ if (text.includes(marker)) {
82
+ try {
83
+ let message = JSON.parse(text.slice(text.lastIndexOf(marker) + marker.length));
84
+ if (message && typeof message === "object" && !Array.isArray(message)) {
85
+ message = Object.fromEntries(Object.entries(message).filter(([key]) =>
86
+ !isHistoryForbiddenKey(key)));
87
+ if (message.channel_id === channel) records.push({order,sequence:sequence++,value:{...message,role:"user"}});
88
+ continue;
89
+ }
90
+ } catch { /* Older bridges used plain-text envelopes; retain them below. */ }
91
+ }
92
+ // Do not recursively import a previous migration's large preview.
93
+ // The complete source remains in the private export; real messages above
94
+ // have already been extracted from their envelope.
95
+ if (text.startsWith("Previous conversations for this channel have been consolidated.")) {
96
+ const end = text.lastIndexOf("End of historical context.\n");
97
+ if (end >= 0) text = text.slice(end + "End of historical context.\n".length);
98
+ }
99
+ if (text.trim()) records.push({order,sequence:sequence++,value:{role:"user",content:text}});
100
+ } else if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer") && typeof item.text === "string") {
101
+ records.push({order,sequence:sequence++,value:{role:"assistant",content:item.text}});
42
102
  }
43
- if (text.trim()) records.push({order,sequence:sequence++,value:{role:"user",content:text}});
44
- } else if (item.type === "agentMessage" && (!item.phase || item.phase === "final_answer")) {
45
- records.push({order,sequence:sequence++,value:{role:"assistant",content:item.text}});
46
103
  }
47
104
  }
48
105
  }
49
106
  records.sort((a,b) => a.order.localeCompare(b.order) || a.sequence-b.sequence);
50
107
  const seen = new Set<string>();
51
108
  const lines = records.filter(({value}) => {
52
- if (!value.id) return true;
109
+ if (typeof value.id !== "string" || !value.id) return true;
53
110
  if (seen.has(value.id)) return false;
54
111
  seen.add(value.id); return true;
55
112
  }).map(({value}) => redact(JSON.stringify(value)));