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/config.ts CHANGED
@@ -1,22 +1,25 @@
1
- import { existsSync, readFileSync, realpathSync, statSync } from "node:fs";
1
+ import { copyFileSync, lstatSync, readFileSync, realpathSync, renameSync, unlinkSync, type Stats } from "node:fs";
2
2
  import { homedir } from "node:os";
3
- import { isAbsolute, join, resolve } from "node:path";
3
+ import { dirname, isAbsolute, join, parse as parsePath, resolve } from "node:path";
4
4
  import { createHash } from "node:crypto";
5
5
  import { validateIdentityProfile } from "../src/identity.ts";
6
6
  import { parse as parseToml } from "smol-toml";
7
+ import { blockedServerHost } from "./owner.ts";
7
8
 
8
9
  export type PermissionMode = "full-access" | "read-only";
9
10
  // App Server advertises model-specific, nonempty effort names via model/list.
10
11
  export type ReasoningEffort = string;
12
+ const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
11
13
  export function reasoningEffort(value: unknown): ReasoningEffort | undefined {
12
14
  if (value === undefined) return undefined;
13
- if (typeof value !== "string" || !value.trim())
15
+ if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
14
16
  throw new Error("effort must be a nonempty model-supported reasoning effort name");
15
17
  return value.trim();
16
18
  }
17
19
  export function modelName(value: unknown): string | undefined {
18
20
  if (value === undefined) return undefined;
19
- if (typeof value !== "string" || !value.trim()) throw new Error("model must be a nonempty model ID");
21
+ if (typeof value !== "string" || !value.trim() || CONTROL_CHAR_RE.test(value))
22
+ throw new Error("model must be a nonempty model ID");
20
23
  return value.trim();
21
24
  }
22
25
  export function permissionMode(value: unknown): PermissionMode {
@@ -36,22 +39,116 @@ export interface BridgeConfig {
36
39
  codexBin: string; stateDir: string; codexHomeMode?: CodexHomeMode; permissions: PermissionMode; effort?: ReasoningEffort; model?: string;
37
40
  }
38
41
  export interface IdentitySettings { state_root?: string; codex_home_mode?: CodexHomeMode; permissions?: PermissionMode; effort?: ReasoningEffort; model?: string; profile?: string; agent_id?: string; channels?: string[]; senders?: string[]; api_url?: string; ws_url?: string }
42
+ const MAX_CONFIG_BYTES = 1_048_576;
43
+ export function reservedProfileStem(selector: string): boolean {
44
+ return ["__proto__", "constructor", "prototype", "grok-binds", "session-binds", "agy-binds",
45
+ "cursor", "read-cursors", "wake-pids", "config", "codex-bots"].includes(selector.replace(/\.json$/i, "").toLowerCase());
46
+ }
47
+ function checkSingleAncestorDir(path: string): void {
48
+ const stat = lstatSync(path, { throwIfNoEntry: false });
49
+ if (!stat) return;
50
+ if (stat.isSymbolicLink()) {
51
+ // These exact Darwin system aliases are safe; arbitrary user links are not.
52
+ const target = `/private${path}`;
53
+ if (process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(path) && realpathSync(path) === target) {
54
+ const priv = lstatSync("/private", { throwIfNoEntry: false });
55
+ if (!priv || priv.isSymbolicLink() || !priv.isDirectory()) {
56
+ throw new Error("Config path must be a non-symlink directory: /private");
57
+ }
58
+ assertDirectoryAncestors(target);
59
+ return;
60
+ }
61
+ throw new Error(`Config path must be a non-symlink directory: ${path}`);
62
+ }
63
+ if (!stat.isDirectory()) throw new Error(`Config path must be a non-symlink directory: ${path}`);
64
+ }
65
+ /** Inspect every existing directory before reads or recursive creation, including raw `symlink/..` segments. */
66
+ export function assertDirectoryAncestors(directory: string): void {
67
+ if (typeof directory !== "string" || !directory.trim() || CONTROL_CHAR_RE.test(directory)) {
68
+ throw new Error(`Config path must be a non-symlink directory: ${String(directory)}`);
69
+ }
70
+ if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(directory)) {
71
+ let cur: string;
72
+ let remainder: string;
73
+ if (isAbsolute(directory)) {
74
+ const root = parsePath(directory).root || "/";
75
+ cur = root;
76
+ remainder = directory.slice(root.length);
77
+ checkSingleAncestorDir(cur);
78
+ } else {
79
+ const base = resolve(process.cwd());
80
+ assertDirectoryAncestors(base);
81
+ cur = base;
82
+ remainder = directory;
83
+ }
84
+ for (const seg of remainder.split(/[\\/]+/)) {
85
+ if (!seg || seg === ".") continue;
86
+ cur = seg === ".." ? dirname(cur) : join(cur, seg);
87
+ checkSingleAncestorDir(cur);
88
+ }
89
+ }
90
+ const paths: string[] = [];
91
+ for (let path = resolve(directory);; path = dirname(path)) {
92
+ paths.unshift(path);
93
+ if (dirname(path) === path) break;
94
+ }
95
+ for (const path of paths) checkSingleAncestorDir(path);
96
+ }
97
+
98
+ /** Atomically replace a regular file, with Windows NTFS EPERM/EACCES fallback. */
99
+ export function atomicReplaceRegularFile(
100
+ tmp: string,
101
+ target: string,
102
+ verifySafeTarget: () => void,
103
+ opts?: { platform?: NodeJS.Platform; rename?: typeof renameSync },
104
+ ): void {
105
+ verifySafeTarget();
106
+ const rename = opts?.rename ?? renameSync;
107
+ const platform = opts?.platform ?? process.platform;
108
+ try {
109
+ rename(tmp, target);
110
+ } catch (err: any) {
111
+ if (platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
112
+ verifySafeTarget();
113
+ copyFileSync(tmp, target);
114
+ unlinkSync(tmp);
115
+ return;
116
+ }
117
+ throw err;
118
+ }
119
+ }
120
+ function checkedPath(path: string, directory = false): Stats | undefined {
121
+ assertDirectoryAncestors(dirname(path));
122
+ let stat: Stats;
123
+ try { stat = lstatSync(path); }
124
+ catch (error: any) { if (error.code === "ENOENT") return undefined; throw error; }
125
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile()))
126
+ throw new Error(directory ? `Config directory must be a non-symlink directory: ${path}` : `Selected profile is not a regular file: ${path}`);
127
+ if (!directory && stat.size > MAX_CONFIG_BYTES) throw new Error(`Config file exceeds 1 MiB: ${path}`);
128
+ return stat;
129
+ }
39
130
  function readJson(file: string): any {
40
- try { return JSON.parse(readFileSync(file, "utf8")); }
131
+ let value: any;
132
+ try { value = JSON.parse(readFileSync(file, "utf8")); }
41
133
  catch { throw new Error(`Cannot read valid JSON: ${file}`); }
134
+ if (value && typeof value === "object" && Object.hasOwn(value, "__proto__")) throw new Error("Invalid JSON prototype key");
135
+ return value;
42
136
  }
43
137
  function strings(value: unknown, name: string): string[] {
44
138
  if (value === undefined) return [];
45
- if (!Array.isArray(value) || value.some(x => typeof x !== "string" || !x.trim()))
139
+ if (!Array.isArray(value) || value.some(x => typeof x !== "string" || !x.trim() || CONTROL_CHAR_RE.test(x)))
46
140
  throw new Error(`${name} must be an array of nonempty strings`);
47
141
  return value;
48
142
  }
49
143
  export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?: string; stateRoot?: string; codexHomeMode?: string; settings?: IdentitySettings },
50
144
  env: NodeJS.ProcessEnv = process.env, home = homedir()): BridgeConfig {
145
+ assertDirectoryAncestors(opts.cwd ?? process.cwd());
51
146
  const cwd = realpathSync(opts.cwd ?? process.cwd());
52
147
  const configFile = join(cwd, ".agentschat/config.json");
53
- const project = opts.settings ?? (existsSync(configFile) ? readJson(configFile) : {});
148
+ if (opts.settings === undefined) checkedPath(join(cwd, ".agentschat"), true);
149
+ const project = opts.settings ?? (checkedPath(configFile) ? readJson(configFile) : {});
54
150
  if (!project || typeof project !== "object" || Array.isArray(project)) throw new Error("Invalid project config");
151
+ if (["__proto__", "constructor", "prototype"].some(key => Object.hasOwn(project, key))) throw new Error("Invalid project config prototype key");
55
152
  const allowed = new Set(["profile", "agent_id", "channels", "senders", "api_url", "ws_url", "permissions", "effort", "model", "state_root", "codex_home_mode"]);
56
153
  if (Object.keys(project).some(k => !allowed.has(k))) throw new Error("Unknown project config field (credentials belong in a private profile)");
57
154
  for (const k of ["profile", "agent_id", "api_url", "ws_url", "state_root"])
@@ -61,7 +158,8 @@ export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?:
61
158
  // must not execute the configured MCP command or inherit its token overrides.
62
159
  let codexProfile: string | undefined;
63
160
  const codexFile = join(cwd, ".codex/config.toml");
64
- if (opts.settings === undefined && existsSync(codexFile)) {
161
+ if (opts.settings === undefined) checkedPath(join(cwd, ".codex"), true);
162
+ if (opts.settings === undefined && checkedPath(codexFile)) {
65
163
  let doc: any;
66
164
  try { doc = parseToml(readFileSync(codexFile, "utf8")); }
67
165
  catch { throw new Error("Invalid project .codex/config.toml"); }
@@ -76,22 +174,29 @@ export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?:
76
174
  }
77
175
  const choices = [
78
176
  [opts.profile, "flag"], [project.profile, "project-config"],
79
- [opts.settings === undefined && existsSync(localProfile) ? localProfile : undefined, "project-profile"],
177
+ [opts.settings === undefined && checkedPath(localProfile) ? localProfile : undefined, "project-profile"],
80
178
  [codexProfile, "project-codex"],
81
179
  [env.AGENTSCHAT_PROFILE, "env"], [env.AGENTCHAT_PROFILE, "legacy-env"], ["profile", "default"],
82
180
  ];
83
181
  const [selector, source] = choices.find(([v]) => v !== undefined && v !== "") as [string, string];
182
+ if (typeof selector !== "string" || CONTROL_CHAR_RE.test(selector)) throw new Error("Invalid profile selector");
84
183
  let profileFile: string;
85
- if (selector.startsWith("~/")) profileFile = join(home, selector.slice(2));
86
- else if (isAbsolute(selector) || selector.includes("/")) profileFile = resolve(cwd, selector);
184
+ if (/^~[\\/]/.test(selector)) profileFile = join(home, selector.slice(2));
185
+ else if (isAbsolute(selector) || selector.includes("/") || selector.includes("\\")) profileFile = resolve(cwd, selector);
87
186
  else {
88
- const name = selector.endsWith(".json") ? selector : `${selector}.json`;
187
+ const stem = selector.replace(/\.json$/i, "");
188
+ if (!stem || selector.includes("..") || reservedProfileStem(selector)) {
189
+ throw new Error("Invalid central profile selector");
190
+ }
191
+ const name = /\.json$/i.test(selector) ? selector : `${selector}.json`;
89
192
  profileFile = join(home, ".agentschat/profiles", name);
90
- if (!existsSync(profileFile)) profileFile = join(home, ".agentschat", name);
91
- if (!existsSync(profileFile)) profileFile = join(home, ".agentchat", name);
193
+ if (!checkedPath(profileFile)) profileFile = join(home, ".agentschat", name);
194
+ if (!checkedPath(profileFile)) profileFile = join(home, ".agentchat", name);
92
195
  }
93
- if (!existsSync(profileFile)) throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
94
- if (process.platform !== "win32" && (statSync(profileFile).mode & 0o077)) throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
196
+ if (!checkedPath(profileFile)) throw new Error(`Selected profile missing: ${profileFile}; no identity fallback or registration`);
197
+ const profileStat = checkedPath(profileFile)!;
198
+ if (!profileStat.isFile()) throw new Error(`Selected profile is not a regular file: ${profileFile}`);
199
+ if (process.platform !== "win32" && (profileStat.mode & 0o077)) throw new Error(`Profile must be private (chmod 600): ${profileFile}`);
95
200
  const profile = readJson(profileFile);
96
201
  validateIdentityProfile(profile, profileFile);
97
202
  if (project.agent_id !== undefined && project.agent_id !== profile.agent_id) throw new Error("Project agent_id does not match selected profile");
@@ -99,16 +204,18 @@ export function resolveConfig(opts: { cwd?: string; profile?: string; codexBin?:
99
204
  const wsUrl = project.ws_url ?? `${apiUrl.replace(/^http/, "ws").replace(/\/$/, "")}/ws`;
100
205
  for (const [raw, protocols] of [[apiUrl, ["https:", "http:"]], [wsUrl, ["wss:", "ws:"]]] as const) {
101
206
  const url = new URL(raw);
102
- if (!(protocols as readonly string[]).includes(url.protocol) || url.username || url.password || url.search || url.hash ||
103
- (!url.protocol.endsWith("s:") && !["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
207
+ if (blockedServerHost(url) || !(protocols as readonly string[]).includes(url.protocol) || url.username || url.password || url.search || url.hash || url.port === "0" ||
208
+ (!url.protocol.endsWith("s:") && !["127.0.0.1", "localhost", "[::1]", "::1"].includes(url.hostname.toLowerCase().replace(/\.$/, "")))) throw new Error("Server URLs must use TLS (except loopback) and contain no credentials/query");
104
209
  }
105
210
  const canonicalApi = new URL(apiUrl).href.replace(/\/$/, "");
106
211
  const key = createHash("sha256").update(JSON.stringify([cwd, canonicalApi, profile.agent_id])).digest("hex").slice(0, 24);
107
212
  const root = opts.stateRoot ?? project.state_root;
108
- if (root !== undefined && (typeof root !== "string" || !root.trim())) throw new Error("Invalid state_root");
109
- const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : root.startsWith("~/") ? join(home, root.slice(2)) : resolve(cwd, root);
213
+ if (root !== undefined && (typeof root !== "string" || !root.trim() || CONTROL_CHAR_RE.test(root))) throw new Error("Invalid state_root");
214
+ const codexBin = opts.codexBin ?? "codex";
215
+ if (typeof codexBin !== "string" || !codexBin.trim() || CONTROL_CHAR_RE.test(codexBin)) throw new Error("Invalid codex_bin");
216
+ const stateRoot = root === undefined ? join(home, ".agentschat/codex-bridge") : /^~[\\/]/.test(root) ? join(home, root.slice(2)) : resolve(cwd, root);
110
217
  return { cwd, profileFile, source, codexHomeMode: codexHomeMode(opts.codexHomeMode ?? project.codex_home_mode), permissions: permissionMode(project.permissions), effort: reasoningEffort(project.effort), model: modelName(project.model), agentId: profile.agent_id, token: profile.token,
111
218
  apiUrl: canonicalApi, wsUrl, channels: strings(project.channels, "channels"),
112
- senders: strings(project.senders, "senders"), codexBin: opts.codexBin ?? "codex",
219
+ senders: strings(project.senders, "senders"), codexBin,
113
220
  stateDir: join(stateRoot, key) };
114
221
  }
@@ -1,5 +1,6 @@
1
+ import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
1
2
  import { randomUUID } from "node:crypto";
2
- import { mkdirSync, writeFileSync, readFileSync, renameSync, readdirSync, rmSync } from "node:fs";
3
+ import { mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, lstatSync } from "node:fs";
3
4
  import { join } from "node:path";
4
5
 
5
6
  export type GuiTool = "send_message_to_thread" | "read_thread";
@@ -15,14 +16,28 @@ function payload(result: any): any {
15
16
  if (Array.isArray(result?.content)) {
16
17
  const text = result.content.find((c: any) => c.type === "text")?.text;
17
18
  if (!text) throw new Error("GUI tool returned no receipt");
18
- return JSON.parse(text);
19
+ if (typeof text !== "string" || text.length > 1_048_576) throw new Error("GUI receipt exceeds size limit");
20
+ const parsed = JSON.parse(text);
21
+ if (parsed && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) throw new Error("Invalid GUI receipt");
22
+ return parsed;
19
23
  }
20
24
  return result;
21
25
  }
26
+ function validTarget(value: unknown): value is string {
27
+ return typeof value === "string" && value.trim() === value && value.length >= 1 && value.length <= 256 && value !== "." && value !== ".." &&
28
+ !/[\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) &&
29
+ !/%(?:2e%2e|2f|5c|00)|%25(?:2e|2f|5c|00)/i.test(value) &&
30
+ !["__proto__", "prototype", "constructor"].includes(value.toLowerCase());
31
+ }
22
32
  /** Private durable outbox. An authorized GUI host calls dispatch; enqueue is NOT delivery. */
23
33
  export class GuiChannel {
24
34
  constructor(private directory: string, private allowedThreads: readonly string[]) {
35
+ const existing = lstatSync(directory, { throwIfNoEntry: false });
36
+ if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) throw new Error("GUI outbox must be a real directory, not a symlink");
37
+ assertDirectoryAncestors(directory);
25
38
  mkdirSync(directory, { recursive: true, mode: 0o700 });
39
+ const stat = lstatSync(directory);
40
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("GUI outbox must be a real directory, not a symlink");
26
41
  }
27
42
  private path(id: string) {
28
43
  if (!/^[0-9a-f-]{36}$/.test(id)) throw new Error("Invalid delivery ID");
@@ -30,13 +45,44 @@ export class GuiChannel {
30
45
  }
31
46
  private save(entry: GuiDelivery) {
32
47
  const path = this.path(entry.id), temp = `${path}.${randomUUID()}.tmp`;
33
- writeFileSync(temp, JSON.stringify(entry), { mode: 0o600 }); renameSync(temp, path);
48
+ const stat = lstatSync(path, { throwIfNoEntry: false });
49
+ if (stat?.isSymbolicLink() || (stat && !stat.isFile())) throw new Error("GUI receipt must be a regular file, not a symlink");
50
+ try {
51
+ writeFileSync(temp, JSON.stringify(entry), { mode: 0o600, flag: "wx" });
52
+ atomicReplaceRegularFile(temp, path, () => {
53
+ const current = lstatSync(path, { throwIfNoEntry: false });
54
+ if (current && (current.isSymbolicLink() || !current.isFile())) throw new Error("GUI receipt must be a regular file, not a symlink");
55
+ });
56
+ } catch (error) {
57
+ // An exclusive-create collision belongs to another writer; leave it alone.
58
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") rmSync(temp, { force: true });
59
+ throw error;
60
+ }
61
+ }
62
+ get(id: string): GuiDelivery {
63
+ const path = this.path(id), stat = lstatSync(path);
64
+ if (stat.isSymbolicLink() || !stat.isFile()) throw new Error("GUI receipt must be a regular file, not a symlink");
65
+ if (stat.size > 1_048_576) throw new Error("GUI receipt exceeds size limit");
66
+ const entry = JSON.parse(readFileSync(path, "utf8"));
67
+ if (!entry || typeof entry !== "object" || Array.isArray(entry) || Object.prototype.hasOwnProperty.call(entry, "__proto__") || entry.id !== id ||
68
+ !validTarget(entry.threadId) || typeof entry.prompt !== "string" ||
69
+ typeof entry.createdAt !== "string" ||
70
+ !["pending", "sending", "submitted", "delivered", "uncertain"].includes(entry.status) ||
71
+ (entry.hostId !== undefined && !validTarget(entry.hostId)) ||
72
+ (entry.turnId !== undefined && typeof entry.turnId !== "string") ||
73
+ (entry.deliveredAt !== undefined && typeof entry.deliveredAt !== "string")) throw new Error("Invalid GUI receipt");
74
+ return entry;
34
75
  }
35
- get(id: string): GuiDelivery { return JSON.parse(readFileSync(this.path(id), "utf8")); }
36
76
  list(): GuiDelivery[] {
37
- return readdirSync(this.directory).filter(f => /^[0-9a-f-]{36}\.json$/.test(f)).map(f => this.get(f.slice(0, -5)));
77
+ const entries: GuiDelivery[] = [];
78
+ for (const file of readdirSync(this.directory)) {
79
+ if (!/^[0-9a-f-]{36}\.json$/.test(file)) continue;
80
+ try { entries.push(this.get(file.slice(0, -5))); } catch { /* Isolate damaged or unsafe receipts. */ }
81
+ }
82
+ return entries;
38
83
  }
39
84
  enqueue(threadId: string, text: string, hostId?: string): GuiDelivery {
85
+ if (!validTarget(threadId) || (hostId !== undefined && !validTarget(hostId))) throw new Error("Invalid GUI target");
40
86
  if (!this.allowedThreads.includes(threadId)) throw new Error("GUI target is not allowed");
41
87
  if (!text.trim() || text.length > 24000) throw new Error("GUI message must contain 1–24000 characters");
42
88
  const id = randomUUID();
@@ -46,7 +92,16 @@ export class GuiChannel {
46
92
  }
47
93
  async dispatch(id: string, call: GuiToolCaller): Promise<GuiDelivery> {
48
94
  const lock = `${this.path(id)}.lock`;
49
- mkdirSync(lock, { mode: 0o700 });
95
+ try { mkdirSync(lock, { mode: 0o700 }); }
96
+ catch (error) {
97
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
98
+ const stat = lstatSync(lock);
99
+ if (stat.isSymbolicLink()) throw new Error("GUI delivery lock must not be a symlink");
100
+ const ageMs = Date.now() - stat.mtimeMs;
101
+ if (!stat.isDirectory() || (ageMs >= -5 * 60_000 && ageMs <= 5 * 60_000)) throw error;
102
+ rmSync(lock, { recursive: true, force: true });
103
+ mkdirSync(lock, { mode: 0o700 });
104
+ }
50
105
  try {
51
106
  const entry = this.get(id);
52
107
  if (!this.allowedThreads.includes(entry.threadId)) throw new Error("GUI target is no longer allowed");
@@ -65,6 +120,7 @@ export class GuiChannel {
65
120
  if (entry.status === "sending") { entry.status = "uncertain"; this.save(entry); }
66
121
  try {
67
122
  let cursor: string | undefined;
123
+ const seenCursors = new Set<string>();
68
124
  for (let page = 0; page < 5; page++) {
69
125
  const history = payload(await call("read_thread", {...target, turnLimit: 10,
70
126
  maxOutputCharsPerItem: 32000, ...(cursor ? {cursor} : {})}));
@@ -75,11 +131,12 @@ export class GuiChannel {
75
131
  entry.status = "delivered"; entry.deliveredAt = new Date().toISOString(); entry.turnId = turn.id;
76
132
  this.save(entry); break;
77
133
  }
78
- cursor = history.page?.nextCursor;
79
- if (!cursor) break;
134
+ const nextCursor = history.page?.nextCursor;
135
+ if (typeof nextCursor !== "string" || !nextCursor.length || seenCursors.has(nextCursor)) break;
136
+ seenCursors.add(nextCursor); cursor = nextCursor;
80
137
  }
81
138
  } catch { /* Keep submitted/uncertain; an unavailable read is not proof of failure. */ }
82
139
  return entry;
83
- } finally { rmSync(lock, {recursive: true}); }
140
+ } finally { rmSync(lock, {recursive: true, force: true}); }
84
141
  }
85
142
  }
@@ -1,5 +1,7 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { randomBytes } from "node:crypto";
2
3
  import { join } from "node:path";
4
+ import { assertDirectoryAncestors, atomicReplaceRegularFile } from "./config.ts";
3
5
  import { normalizeTimestampForCursor } from "../src/timestamps.ts";
4
6
 
5
7
  interface Snapshot {
@@ -10,8 +12,20 @@ interface Snapshot {
10
12
  last_error?: string;
11
13
  }
12
14
  function timestamp(value: unknown): string {
13
- if (typeof value !== "string" || !Number.isFinite(Date.parse(value))) throw new Error("Invalid history timestamp");
14
- return normalizeTimestampForCursor(value, "after")!;
15
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}[Tt ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|z|[+-]\d{2}:\d{2})$/.test(value) || !Number.isFinite(Date.parse(value))) throw new Error("Invalid history timestamp");
16
+ const normalized = normalizeTimestampForCursor(value, "after");
17
+ if (!normalized || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/.test(normalized)) throw new Error("Invalid history timestamp");
18
+ return normalized;
19
+ }
20
+ function validChannel(channel: unknown): channel is string {
21
+ return typeof channel === "string" && channel.length > 0 && channel.length <= 128 && channel === channel.trim() && channel !== "."
22
+ && !channel.includes("..") && !/[\/\\]/.test(channel)
23
+ && !/%(?:2e%2e|2f|5c|00)/i.test(channel)
24
+ && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel)
25
+ && !["__proto__", "constructor", "prototype"].includes(channel.trim().toLowerCase());
26
+ }
27
+ function validateChannel(channel: unknown): asserts channel is string {
28
+ if (!validChannel(channel)) throw new Error("Invalid inbound channel");
15
29
  }
16
30
 
17
31
  /** REST checkpoints, independent of live WS delivery. Advancing a live cursor
@@ -24,19 +38,49 @@ export class InboxSync {
24
38
  constructor(stateDir: string, private api: (path: string) => Promise<any>,
25
39
  private receive: (message: unknown) => boolean, private active: () => boolean,
26
40
  private log: (message: string) => void = console.error) {
41
+ const existing = lstatSync(stateDir, { throwIfNoEntry: false });
42
+ if (existing && (existing.isSymbolicLink() || !existing.isDirectory())) throw new Error("Invalid inbound state directory");
43
+ assertDirectoryAncestors(stateDir);
27
44
  mkdirSync(stateDir, {recursive:true, mode:0o700});
45
+ const dirStat = lstatSync(stateDir);
46
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) throw new Error("Invalid inbound state directory");
47
+ if (process.platform !== "win32") chmodSync(stateDir, 0o700);
28
48
  this.file = join(stateDir, "inbound-cursors.json");
29
- this.state = existsSync(this.file) ? JSON.parse(readFileSync(this.file, "utf8")) : {version:1, channels:{}};
30
- if (this.state.version !== 1 || !this.state.channels || typeof this.state.channels !== "object" || Array.isArray(this.state.channels))
49
+ let fileStat;
50
+ try { fileStat = lstatSync(this.file); }
51
+ catch (err) { if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err; }
52
+ if (fileStat && (fileStat.isSymbolicLink() || !fileStat.isFile())) throw new Error("Invalid inbound cursors file");
53
+ if (fileStat && fileStat.size > 1_048_576) throw new Error("Inbound cursors exceed size limit");
54
+ this.state = fileStat ? JSON.parse(readFileSync(this.file, "utf8")) : {version:1, channels:{}};
55
+ if (!this.state || typeof this.state !== "object" || Array.isArray(this.state) || Object.hasOwn(this.state, "__proto__") || this.state.version !== 1 || !this.state.channels || typeof this.state.channels !== "object" || Array.isArray(this.state.channels) ||
56
+ Object.hasOwn(this.state.channels, "__proto__") || Object.keys(this.state.channels).length > 1024)
31
57
  throw new Error("Invalid inbound cursors; refusing to discard checkpoint");
32
- for (const value of Object.values(this.state.channels)) timestamp(value);
33
- this.state.channels = Object.assign(Object.create(null), this.state.channels);
58
+ const channels: Record<string, string> = Object.create(null);
59
+ for (const [channel, value] of Object.entries(this.state.channels)) {
60
+ if (!validChannel(channel)) continue;
61
+ timestamp(value);
62
+ channels[channel] = value;
63
+ }
64
+ this.state.channels = channels;
34
65
  }
35
66
  private save() {
36
- writeFileSync(this.file + ".tmp", JSON.stringify(this.state), {mode:0o600});
37
- renameSync(this.file + ".tmp", this.file);
67
+ const tmp = `${this.file}.${process.pid}.${Date.now()}.${randomBytes(4).toString("hex")}.tmp`;
68
+ let created = false;
69
+ try {
70
+ writeFileSync(tmp, JSON.stringify(this.state), {mode:0o600, flag:"wx"});
71
+ created = true;
72
+ atomicReplaceRegularFile(tmp, this.file, () => {
73
+ const current = lstatSync(this.file, { throwIfNoEntry: false });
74
+ if (current && (current.isSymbolicLink() || !current.isFile())) throw new Error("Invalid inbound cursors file");
75
+ });
76
+ } catch (err) {
77
+ if (created) { try { unlinkSync(tmp); } catch {} }
78
+ throw err;
79
+ }
38
80
  }
39
81
  watch(channel: string) {
82
+ validateChannel(channel);
83
+ if (!Object.hasOwn(this.state.channels, channel) && Object.keys(this.state.channels).length >= 1024) throw new Error("Inbound channel limit exceeded");
40
84
  this.channels.add(channel);
41
85
  // First installation/new membership starts now, never replays old requests.
42
86
  if (!Object.hasOwn(this.state.channels, channel)) {
@@ -44,8 +88,17 @@ export class InboxSync {
44
88
  }
45
89
  }
46
90
  memberships(channels: string[]) {
47
- this.channels.clear();
48
- for (const channel of channels) this.watch(channel);
91
+ for (const channel of channels) validateChannel(channel);
92
+ if (new Set([...Object.keys(this.state.channels), ...channels]).size > 1024) throw new Error("Inbound channel limit exceeded");
93
+ this.channels = new Set(channels);
94
+ let changed = false;
95
+ for (const channel of this.channels) {
96
+ if (!Object.hasOwn(this.state.channels, channel)) {
97
+ this.state.channels[channel] = timestamp(new Date().toISOString());
98
+ changed = true;
99
+ }
100
+ }
101
+ if (changed) this.save();
49
102
  }
50
103
  sync(): Promise<void> {
51
104
  if (!this.running) this.running = this.run().finally(() => {this.running = undefined;});
@@ -64,7 +117,7 @@ export class InboxSync {
64
117
  const messages = Array.isArray(body) ? body : body?.messages;
65
118
  if (!Array.isArray(messages)) throw new Error("Invalid history response");
66
119
  const rows = messages.map(m => {
67
- if (!m || m.channel_id !== channel || typeof m.id !== "string") throw new Error("Invalid history message");
120
+ if (!m || m.channel_id !== channel || typeof m.id !== "string" || m.id.trim().length === 0 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(m.id)) throw new Error("Invalid history message");
68
121
  return {message:m, time:timestamp(m.timestamp)};
69
122
  }).sort((a,b) => a.time.localeCompare(b.time));
70
123
  // One bounded page per channel per pass. Full pages continue next pass.
@@ -1,5 +1,6 @@
1
1
  import { lstatSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { assertDirectoryAncestors } from "./config.ts";
3
4
  import type { BridgeConfig } from "./config.ts";
4
5
 
5
6
  export interface LoopGrant {
@@ -20,24 +21,51 @@ export interface LoopTick {
20
21
 
21
22
  // An operator writes this local authorization only after an explicit owner request.
22
23
  // Neither chat content nor a server-created loop alone grants local execution.
23
- function grants(config: BridgeConfig): LoopGrant[] {
24
+ function grants(
25
+ config: BridgeConfig,
26
+ opts?: { platform?: NodeJS.Platform; getuid?: (() => number) | undefined },
27
+ ): LoopGrant[] {
24
28
  try {
29
+ const platform = opts?.platform ?? process.platform;
30
+ const getuid = opts && "getuid" in opts ? opts.getuid : process.getuid;
31
+ assertDirectoryAncestors(config.stateDir);
32
+ const directory = lstatSync(config.stateDir);
33
+ if (directory.isSymbolicLink() || !directory.isDirectory()) return [];
25
34
  const file = join(config.stateDir, "loop-grants.json"), stat = lstatSync(file);
26
- if (!stat.isFile() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.()) return [];
35
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 1_048_576) return [];
36
+ if (platform !== "win32") {
37
+ if (typeof getuid !== "function" || (stat.mode & 0o077) !== 0 || stat.uid !== getuid()) return [];
38
+ }
27
39
  const doc = JSON.parse(readFileSync(file, "utf8"));
28
- if (doc?.version !== 1 || !Array.isArray(doc.grants)) return [];
29
- return doc.grants.filter((g: any) => g &&
40
+ const ownProto = (value: any) => Object.prototype.hasOwnProperty.call(value, "__proto__");
41
+ if (doc?.version !== 1 || ownProto(doc) || !Array.isArray(doc.grants) || doc.grants.length > 256) return [];
42
+ const safeId = (value: unknown): value is string => typeof value === "string" && value.length > 0 &&
43
+ value.length <= 128 && value.trim() === value && value !== "." && value !== ".." &&
44
+ !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) &&
45
+ !["__proto__", "constructor", "prototype"].includes(value.toLowerCase());
46
+ const safeOwnerId = (value: unknown): value is string => typeof value === "string" && value.length > 0 &&
47
+ value.length <= 254 && value.trim() === value && value !== "." && !value.includes("..") &&
48
+ !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) && !/%(?:2e%2e|2f|5c|00)/i.test(value) &&
49
+ !["__proto__", "constructor", "prototype"].includes(value.toLowerCase());
50
+ return doc.grants.filter((g: any) => g && !ownProto(g) &&
30
51
  [g.loop_id, g.channel_id, g.agent_id, g.owner_id, g.prompt].every(v => typeof v === "string" && v.trim()) &&
52
+ /^loop_[A-Za-z0-9_-]+$/.test(g.loop_id) &&
53
+ [g.loop_id, g.channel_id, g.agent_id].every(safeId) &&
54
+ safeOwnerId(g.owner_id) &&
31
55
  g.agent_id === config.agentId && g.prompt.length <= 4000 &&
32
56
  Number.isSafeInteger(g.interval_ms) && g.interval_ms >= 60_000 && g.interval_ms <= 86_400_000);
33
57
  } catch { return []; }
34
58
  }
35
59
 
36
- export function authorizedLoopTick(raw: any, config: BridgeConfig): LoopGrant | null {
60
+ export function authorizedLoopTick(
61
+ raw: any,
62
+ config: BridgeConfig,
63
+ opts?: { platform?: NodeJS.Platform; getuid?: (() => number) | undefined },
64
+ ): LoopGrant | null {
37
65
  const tick = raw?.meta;
38
66
  if (raw?.sender_id !== config.agentId || tick?.kind !== "loop_tick" ||
39
67
  !Number.isSafeInteger(tick.next_tick_ms) || tick.next_tick_ms <= 0) return null;
40
- const matches = grants(config).filter(g => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
68
+ const matches = grants(config, opts).filter(g => g.loop_id === tick.loop_id && g.channel_id === raw.channel_id);
41
69
  if (matches.length !== 1) return null;
42
70
  const grant = matches[0]!;
43
71
  if (tick.prompt !== grant.prompt || tick.interval_ms !== grant.interval_ms ||
@@ -47,20 +75,22 @@ export function authorizedLoopTick(raw: any, config: BridgeConfig): LoopGrant |
47
75
  }
48
76
 
49
77
  export async function verifyLoopTick(raw: any, config: BridgeConfig, owner: string | null,
50
- list: () => Promise<unknown>): Promise<LoopGrant | null> {
51
- const grant = authorizedLoopTick(raw, config);
78
+ list: () => Promise<unknown>,
79
+ opts?: { platform?: NodeJS.Platform; getuid?: (() => number) | undefined }): Promise<LoopGrant | null> {
80
+ const grant = authorizedLoopTick(raw, config, opts);
52
81
  if (!grant || owner !== grant.owner_id || config.permissions !== "full-access") return null;
53
82
  let response: any;
54
83
  try { response = await list(); } catch { return null; }
55
- const rows = Array.isArray(response?.loops) ? response.loops.filter((r: any) => r?.loop_id === grant.loop_id) : [];
84
+ const rows = Array.isArray(response?.loops) && response.loops.length <= 1024 ? response.loops.filter((r: any) => r?.loop_id === grant.loop_id) : [];
56
85
  if (rows.length !== 1) return null;
57
86
  const loop = rows[0];
58
- if (loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt ||
87
+ if (!loop || loop.status !== "active" || loop.channel_id !== grant.channel_id || loop.prompt !== grant.prompt ||
59
88
  loop.interval_ms !== grant.interval_ms || loop.expires_at !== null ||
60
89
  (loop.mode !== undefined && loop.mode !== "static") ||
61
90
  !Number.isSafeInteger(loop.last_tick_at) || loop.last_tick_at <= 0 ||
91
+ !Number.isSafeInteger(loop.next_tick_ms) ||
62
92
  loop.next_tick_ms !== raw.meta.next_tick_ms || loop.last_tick_at + grant.interval_ms !== loop.next_tick_ms) return null;
63
93
  // Re-read after network I/O so local revocation during verification takes effect.
64
- const current = authorizedLoopTick(raw, config);
94
+ const current = authorizedLoopTick(raw, config, opts);
65
95
  return current && current.owner_id === owner ? current : null;
66
96
  }