agentschat-mcp 0.36.24 → 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 (84) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +8 -0
  3. package/codex/README.md +1 -1
  4. package/codex/app-server.ts +79 -22
  5. package/codex/bots-config.ts +31 -11
  6. package/codex/bridge.ts +123 -25
  7. package/codex/config.ts +128 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +65 -12
  10. package/codex/loop-grants.ts +41 -11
  11. package/codex/manager.ts +101 -25
  12. package/codex/owner.ts +81 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +41 -11
  16. package/codex/thread-history.ts +77 -30
  17. package/codex/transport.ts +122 -19
  18. package/connector/auth.ts +57 -5
  19. package/connector/backfill.ts +92 -10
  20. package/connector/descriptor.ts +27 -1
  21. package/connector/identities.ts +82 -14
  22. package/connector/ingest.ts +11 -2
  23. package/connector/normalize.ts +32 -12
  24. package/connector/run.ts +314 -67
  25. package/connector/server.ts +95 -26
  26. package/dist/codex-bots.js +410 -73
  27. package/dist/codex-bridge.js +1996 -576
  28. package/dist/connector.js +1286 -493
  29. package/dist/dsh.js +1776 -299
  30. package/dist/muse.js +967 -221
  31. package/dist/server.js +7645 -1172
  32. package/dsh/client.js +7 -5
  33. package/dsh/identity-ui/client.js +7 -5
  34. package/dsh/identity-ui/index.js +43 -8
  35. package/dsh/inbound-bridge/index.js +595 -146
  36. package/dsh/src/cli.ts +430 -91
  37. package/dsh/src/patch.ts +295 -15
  38. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  39. package/dsh/tests/dsh.test.ts +990 -3
  40. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  41. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  42. package/muse/src/bridge.ts +54 -13
  43. package/muse/src/cli.ts +226 -41
  44. package/muse/src/client.ts +249 -34
  45. package/muse/src/config.ts +128 -12
  46. package/muse/src/policy.ts +28 -8
  47. package/muse/src/types.ts +1 -0
  48. package/muse/src/typing.ts +18 -1
  49. package/muse/src/wake.ts +237 -35
  50. package/muse/tests/bridge.test.mjs +131 -0
  51. package/muse/tests/client.test.mjs +327 -0
  52. package/muse/tests/config.test.mjs +78 -1
  53. package/muse/tests/hardening.test.mjs +199 -0
  54. package/muse/tests/hardening126.test.mjs +292 -0
  55. package/muse/tests/policy.test.mjs +83 -1
  56. package/muse/tests/wake.test.mjs +134 -6
  57. package/package.json +3 -3
  58. package/scripts/ensure-grok-wakes.mjs +93 -8
  59. package/scripts/example-url-wake-receiver.mjs +254 -61
  60. package/scripts/grok-bind-register.sh +38 -8
  61. package/skills/agentschat-team-lead/SKILL.md +1 -1
  62. package/skills/onboarding.md +14 -10
  63. package/src/argcheck.ts +1890 -1
  64. package/src/cli.mjs +98 -14
  65. package/src/dedup.ts +57 -8
  66. package/src/grok-bind.ts +160 -33
  67. package/src/heartbeat.ts +39 -11
  68. package/src/identity-guard.ts +93 -20
  69. package/src/identity.ts +67 -11
  70. package/src/mentions.ts +26 -5
  71. package/src/onboarding-status.ts +134 -11
  72. package/src/profile-selection.ts +269 -18
  73. package/src/profile-store.ts +222 -28
  74. package/src/read-cursor.ts +256 -9
  75. package/src/reconnect.ts +98 -2
  76. package/src/redact.ts +34 -15
  77. package/src/rest-cli.ts +713 -159
  78. package/src/server.ts +2487 -342
  79. package/src/session-bind.ts +731 -132
  80. package/src/session-route.ts +183 -12
  81. package/src/team-lead-skill.ts +3 -0
  82. package/src/timestamps.ts +56 -23
  83. package/src/tool-annotations.ts +22 -1
  84. package/src/wake.ts +524 -90
package/dsh/src/patch.ts CHANGED
@@ -1,31 +1,225 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { dirname, join } from "node:path";
1
+ import { randomBytes } from "node:crypto";
2
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
3
4
  import { homedir } from "node:os";
4
5
 
6
+ export interface DshPatchFsOps {
7
+ renameSync?: typeof renameSync;
8
+ copyFileSync?: typeof copyFileSync;
9
+ }
10
+
5
11
  export interface DshPatchOptions {
6
12
  dshHome?: string;
7
13
  dshProfile?: string;
8
14
  agentsChatProfile?: string;
9
15
  apiUrl?: string;
10
16
  packageSpec?: string;
17
+ fsOps?: DshPatchFsOps;
18
+ }
19
+
20
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
21
+ const DARWIN_ROOT_LINKS = new Set(["/var", "/tmp", "/etc"]);
22
+ const DSH_PATCH_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
23
+ const DSH_PATCH_PRETRIM_CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/;
24
+
25
+ function isAllowedDarwinSystemLink(dirPath: string): boolean {
26
+ if (process.platform !== "darwin" || !DARWIN_ROOT_LINKS.has(dirPath)) return false;
27
+ try {
28
+ const priv = lstatSync("/private");
29
+ if (priv.isSymbolicLink() || !priv.isDirectory()) return false;
30
+ const real = realpathSync(dirPath);
31
+ if (real !== `/private${dirPath}`) return false;
32
+ const target = lstatSync(real);
33
+ return !target.isSymbolicLink() && target.isDirectory();
34
+ } catch {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ function checkRawDotDotAncestors(rawPath: string): void {
40
+ const trimmed = rawPath.trim();
41
+ if (!trimmed || !isAbsolute(trimmed)) return;
42
+ const normalizedSep = process.platform === "win32" ? trimmed.replace(/\//g, "\\") : trimmed;
43
+ const sepChar = process.platform === "win32" ? "\\" : "/";
44
+ const parts = normalizedSep.split(sepChar);
45
+ if (!parts.includes("..")) return;
46
+ const winDrive = process.platform === "win32" && /^[A-Za-z]:$/.test(parts[0] || "");
47
+ let current = winDrive ? `${parts[0]}\\` : sepChar;
48
+ for (let i = 1; i < parts.length; i++) {
49
+ const seg = parts[i]!;
50
+ if (!seg || seg === ".") continue;
51
+ if (seg === "..") {
52
+ current = dirname(current);
53
+ continue;
54
+ }
55
+ const candidate = current.endsWith(sepChar) ? `${current}${seg}` : `${current}${sepChar}${seg}`;
56
+ if (i < parts.length - 1 || parts.slice(i + 1).includes("..")) {
57
+ if (!isAllowedDarwinSystemLink(candidate)) {
58
+ try {
59
+ const stat = lstatSync(candidate);
60
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
61
+ throw new Error(`Refusing symlinked or non-directory parent: ${candidate}`);
62
+ }
63
+ } catch (err: any) {
64
+ if (err?.code !== "ENOENT") throw err;
65
+ }
66
+ }
67
+ }
68
+ current = candidate;
69
+ }
70
+ }
71
+
72
+ export function checkParentDirectory(path: string): void {
73
+ if (typeof path !== "string" || !path.trim() || DSH_PATCH_CTRL_RE.test(path)) {
74
+ throw new Error("Invalid DSH target path");
75
+ }
76
+ checkRawDotDotAncestors(path);
77
+ let parent = dirname(resolve(path));
78
+ for (;;) {
79
+ if (!isAllowedDarwinSystemLink(parent)) {
80
+ try {
81
+ const stat = lstatSync(parent);
82
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
83
+ throw new Error(`Refusing symlinked or non-directory parent: ${parent}`);
84
+ }
85
+ } catch (err: any) {
86
+ if (err?.code !== "ENOENT") throw err;
87
+ }
88
+ }
89
+ const next = dirname(parent);
90
+ if (next === parent) break;
91
+ parent = next;
92
+ }
93
+ }
94
+
95
+ function isBlockedNormalizedHost(host: string): boolean {
96
+ if (!host) return true;
97
+ if (
98
+ host === "0.0.0.0" ||
99
+ /^0\./.test(host) ||
100
+ host === "::" ||
101
+ host === "0:0:0:0:0:0:0:0" ||
102
+ host === "100.100.100.200" ||
103
+ host === "fd00:ec2::254" ||
104
+ host === "fd00:ec2:0:0:0:0:0:254" ||
105
+ host === "metadata" ||
106
+ host === "instance-data" ||
107
+ host === "metadata.google.internal" ||
108
+ host.endsWith(".metadata.google.internal") ||
109
+ host === "metadata.goog" ||
110
+ host.endsWith(".metadata.goog") ||
111
+ /^169\.254\./.test(host)
112
+ ) {
113
+ return true;
114
+ }
115
+ if (
116
+ /^::ffff:(?:0:)?(?:a9fe:[0-9a-f]{1,4}|169\.254\.\d{1,3}\.\d{1,3}|6464:64c8|100\.100\.100\.200|[0-9a-f]{1,2}:[0-9a-f]{1,4}|0\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(
117
+ host,
118
+ ) ||
119
+ /^(?:0:){5}ffff:(?:a9fe:[0-9a-f]{1,4}|169\.254\.\d{1,3}\.\d{1,3}|6464:64c8|100\.100\.100\.200|[0-9a-f]{1,2}:[0-9a-f]{1,4}|0\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.test(
120
+ host,
121
+ )
122
+ ) {
123
+ return true;
124
+ }
125
+ const first = host.split(":")[0];
126
+ return host.includes(":") && /^[0-9a-f]{1,4}$/.test(first!) && (parseInt(first!, 16) & 0xffc0) === 0xfe80;
127
+ }
128
+
129
+ /** URL.hostname is canonicalized by WHATWG URL, including IPv4-in-IPv6. */
130
+ export function isBlockedDshHost(hostname: string): boolean {
131
+ const raw = hostname.trim().toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
132
+ if (isBlockedNormalizedHost(raw)) return true;
133
+ try {
134
+ const bracketed = raw.includes(":") ? `[${raw}]` : raw;
135
+ const canonical = new URL(`http://${bracketed}`).hostname.toLowerCase().replace(/\.$/, "").replace(/^\[|\]$/g, "");
136
+ if (canonical && canonical !== raw && isBlockedNormalizedHost(canonical)) return true;
137
+ } catch {
138
+ // Non-parseable host handled by caller's URL parser.
139
+ }
140
+ return false;
11
141
  }
12
142
 
13
143
  export function resolveDshPatchPath(opts: DshPatchOptions = {}): string {
14
144
  const home = opts.dshHome ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
15
- if (opts.dshProfile) {
16
- return join(home, "profiles", opts.dshProfile, "cordis.patch.yml");
145
+ if (!home || home.length > 4096 || home.startsWith("-") || !isAbsolute(home) || DSH_PATCH_CTRL_RE.test(home)) {
146
+ throw new Error("Invalid DSH home path");
147
+ }
148
+ if (opts.dshProfile !== undefined) {
149
+ if (typeof opts.dshProfile !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(opts.dshProfile)) {
150
+ throw new Error("Invalid DSH profile name");
151
+ }
152
+ const profile = opts.dshProfile.trim();
153
+ if (
154
+ !profile ||
155
+ profile.length > 64 ||
156
+ !/^[A-Za-z0-9._-]+$/.test(profile) ||
157
+ profile === "." ||
158
+ profile.includes("..") ||
159
+ FORBIDDEN_KEYS.has(profile.toLowerCase())
160
+ ) {
161
+ throw new Error("Invalid DSH profile name");
162
+ }
163
+ return join(home, "profiles", profile, "cordis.patch.yml");
17
164
  }
18
165
  return join(home, "cordis.patch.yml");
19
166
  }
20
167
 
21
168
  export function buildMcpAgentsChatArgs(opts: DshPatchOptions = {}): string[] {
22
- const pkg = opts.packageSpec ?? "agentschat-mcp@latest";
169
+ const rawPkg = opts.packageSpec ?? "agentschat-mcp@latest";
170
+ if (typeof rawPkg !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(rawPkg)) {
171
+ throw new Error("Invalid packageSpec");
172
+ }
173
+ const pkg = rawPkg.trim();
174
+ if (!pkg || pkg.startsWith("-") || /[\x00-\x20\x7f-\x9f\u2028\u2029]/.test(pkg)) {
175
+ throw new Error("Invalid packageSpec");
176
+ }
23
177
  const args = ["-y", pkg];
24
- if (opts.agentsChatProfile) {
25
- args.push("--profile", opts.agentsChatProfile);
178
+ if (opts.agentsChatProfile !== undefined && opts.agentsChatProfile !== "") {
179
+ if (typeof opts.agentsChatProfile !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(opts.agentsChatProfile)) {
180
+ throw new Error("Invalid AgentsChat profile name");
181
+ }
182
+ const profile = opts.agentsChatProfile.trim();
183
+ if (
184
+ !profile ||
185
+ profile.length > 64 ||
186
+ profile.startsWith("-") ||
187
+ profile.includes("..") ||
188
+ profile.includes("/") ||
189
+ profile.includes("\\") ||
190
+ FORBIDDEN_KEYS.has(profile.toLowerCase()) ||
191
+ DSH_PATCH_CTRL_RE.test(profile)
192
+ ) {
193
+ throw new Error("Invalid AgentsChat profile name");
194
+ }
195
+ args.push("--profile", profile);
26
196
  }
27
- if (opts.apiUrl) {
28
- args.push("--url", opts.apiUrl);
197
+ if (opts.apiUrl !== undefined && opts.apiUrl !== "") {
198
+ if (typeof opts.apiUrl !== "string" || DSH_PATCH_PRETRIM_CTRL_RE.test(opts.apiUrl)) {
199
+ throw new Error("Invalid AgentsChat API URL");
200
+ }
201
+ const rawUrl = opts.apiUrl.trim();
202
+ if (!rawUrl || rawUrl.startsWith("-") || /[\x00-\x20\x7f-\x9f\u2028\u2029]/.test(rawUrl)) {
203
+ throw new Error("Invalid AgentsChat API URL");
204
+ }
205
+ let parsed: URL;
206
+ try {
207
+ parsed = new URL(rawUrl);
208
+ } catch {
209
+ throw new Error("Invalid AgentsChat API URL");
210
+ }
211
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
212
+ const isLoopback = host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
213
+ if (
214
+ isBlockedDshHost(parsed.hostname) ||
215
+ parsed.username ||
216
+ parsed.password ||
217
+ parsed.port === "0" || parsed.search || parsed.hash ||
218
+ (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback))
219
+ ) {
220
+ throw new Error("Invalid AgentsChat API URL");
221
+ }
222
+ args.push("--url", rawUrl);
29
223
  }
30
224
  return args;
31
225
  }
@@ -84,11 +278,29 @@ export function mergeDshCordisPatch(existingContent: string, opts: DshPatchOptio
84
278
  return { content: `${prefix}${block}`, changed: true };
85
279
  }
86
280
 
87
- // Case 2: File already has a top-level `- insert:` block (like ~/.dsh/cordis.patch.yml)
88
- if (/^-\s*insert:\s*$/m.test(existingContent)) {
89
- const normalized = existingContent.endsWith("\n") ? existingContent : `${existingContent}\n`;
281
+ // Case 2: File already has a top-level `- insert:` block (e.g. ~/.dsh/cordis.patch.yml).
282
+ // Splice inside THAT `- insert:` block (preserving its child indent and stopping before
283
+ // any subsequent top-level `- replace:` / `- delete:` block so multi-block files stay valid YAML).
284
+ const normalizedLines = existingContent.replace(/\r\n/g, "\n").split("\n");
285
+ const insertLineIdx = normalizedLines.findIndex((line) => /^-\s*insert:\s*(?:#.*)?$/.test(line));
286
+ if (insertLineIdx >= 0) {
287
+ let detectedIndent: string | null = null;
288
+ let lastBodyLineIdx = insertLineIdx;
289
+ for (let i = insertLineIdx + 1; i < normalizedLines.length; i++) {
290
+ const line = normalizedLines[i]!;
291
+ if (/^\s*$/.test(line) || /^\s*#/.test(line)) continue;
292
+ if (/^\S/.test(line)) break;
293
+ const itemMatch = line.match(/^([ \t]+)-\s+/);
294
+ if (itemMatch && detectedIndent === null) {
295
+ detectedIndent = itemMatch[1]!;
296
+ }
297
+ lastBodyLineIdx = i;
298
+ }
299
+ const entryLines = renderMcpAgentsChatEntry(detectedIndent ?? " ", opts).split("\n");
300
+ normalizedLines.splice(lastBodyLineIdx + 1, 0, ...entryLines);
301
+ const merged = normalizedLines.join("\n");
90
302
  return {
91
- content: `${normalized}${renderMcpAgentsChatEntry(" ", opts)}\n`,
303
+ content: merged.endsWith("\n") ? merged : `${merged}\n`,
92
304
  changed: true,
93
305
  };
94
306
  }
@@ -106,12 +318,80 @@ export function applyDshCordisPatchFile(opts: DshPatchOptions = {}): {
106
318
  patchPath: string;
107
319
  changed: boolean;
108
320
  } {
321
+ const rawHome = opts.dshHome ?? process.env.DSH_HOME;
322
+ if (rawHome) {
323
+ checkRawDotDotAncestors(`${rawHome}/_`);
324
+ }
109
325
  const patchPath = resolveDshPatchPath(opts);
110
- const existing = existsSync(patchPath) ? readFileSync(patchPath, "utf8") : "";
326
+ checkParentDirectory(patchPath);
327
+ let existed = false;
328
+ let mode = 0o600;
329
+ try {
330
+ const lst = lstatSync(patchPath);
331
+ if (lst.isSymbolicLink() || !lst.isFile()) {
332
+ throw new Error(`Refusing to modify non-regular or symlinked DSH patch file: ${patchPath}`);
333
+ }
334
+ if (lst.size > 1_048_576) {
335
+ throw new Error(`Refusing to modify oversized DSH patch file (>1MiB): ${patchPath}`);
336
+ }
337
+ existed = true;
338
+ mode = lst.mode & 0o777;
339
+ } catch (err: any) {
340
+ if (err?.code !== "ENOENT") throw err;
341
+ }
342
+ const existing = existed ? readFileSync(patchPath, "utf8") : "";
111
343
  const { content, changed } = mergeDshCordisPatch(existing, opts);
112
344
  if (changed) {
113
345
  mkdirSync(dirname(patchPath), { recursive: true });
114
- writeFileSync(patchPath, content, "utf8");
346
+ checkParentDirectory(patchPath);
347
+ const tmp = `${patchPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
348
+ let created = false;
349
+ try {
350
+ writeFileSync(tmp, content, { encoding: "utf8", mode, flag: "wx" });
351
+ created = true;
352
+ checkParentDirectory(patchPath);
353
+ try {
354
+ const cur = lstatSync(patchPath);
355
+ if (cur.isSymbolicLink() || !cur.isFile()) {
356
+ throw new Error(`Refusing to overwrite symlinked or non-regular DSH patch file: ${patchPath}`);
357
+ }
358
+ } catch (err: any) {
359
+ if (err?.code !== "ENOENT") throw err;
360
+ }
361
+ const doRename = opts.fsOps?.renameSync ?? renameSync;
362
+ const doCopy = opts.fsOps?.copyFileSync ?? copyFileSync;
363
+ try {
364
+ doRename(tmp, patchPath);
365
+ } catch (renameErr: any) {
366
+ if (renameErr?.code !== "EPERM" && renameErr?.code !== "EACCES") {
367
+ throw renameErr;
368
+ }
369
+ checkParentDirectory(patchPath);
370
+ try {
371
+ const cur = lstatSync(patchPath);
372
+ if (cur.isSymbolicLink() || !cur.isFile()) {
373
+ throw new Error(`Refusing to overwrite symlinked or non-regular DSH patch file: ${patchPath}`);
374
+ }
375
+ } catch (err: any) {
376
+ if (err?.code !== "ENOENT") throw err;
377
+ }
378
+ doCopy(tmp, patchPath);
379
+ try {
380
+ unlinkSync(tmp);
381
+ } catch {}
382
+ created = false;
383
+ }
384
+ if (process.platform !== "win32") {
385
+ try {
386
+ chmodSync(patchPath, mode);
387
+ } catch {}
388
+ }
389
+ } catch (err) {
390
+ try {
391
+ if (created) unlinkSync(tmp);
392
+ } catch {}
393
+ throw err;
394
+ }
115
395
  }
116
396
  return { patchPath, changed };
117
397
  }
@@ -0,0 +1,207 @@
1
+ import { describe, expect, spyOn, test } from "bun:test";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { tmpdir } from "node:os";
5
+ import {
6
+ applyDshCordisPatchFile,
7
+ buildMcpAgentsChatArgs,
8
+ checkParentDirectory,
9
+ isBlockedDshHost,
10
+ } from "../src/patch.ts";
11
+ import { loadDshConfig, main, registerOnly } from "../src/cli.ts";
12
+ import { MuseAgentChatClient } from "../../muse/src/client.ts";
13
+
14
+ describe("Campaign #127 KR4: DSH patch & CLI hardening", () => {
15
+ test("isBlockedDshHost, buildMcpAgentsChatArgs & loadDshConfig block full SSRF metadata/unspecified hosts while allowing normal 3-label hosts", async () => {
16
+ const env = { AGENTCHAT_AGENT_ID: "dsh-bot", AGENTCHAT_TOKEN: "ac_token_127" };
17
+ const blockedHosts = [
18
+ "0.0.0.0",
19
+ "[::]",
20
+ "[0:0:0:0:0:0:0:0]",
21
+ "100.100.100.200",
22
+ "[fd00:ec2::254]",
23
+ "[fd00:ec2:0:0:0:0:0:254]",
24
+ "metadata",
25
+ "instance-data",
26
+ "sub.metadata.google.internal",
27
+ "sub.metadata.goog",
28
+ "[::ffff:100.100.100.200]",
29
+ "[::ffff:6464:64c8]",
30
+ "[::ffff:0:0]",
31
+ "[::ffff:0.0.0.0]",
32
+ ];
33
+ for (const host of blockedHosts) {
34
+ expect(isBlockedDshHost(host)).toBe(true);
35
+ expect(() => buildMcpAgentsChatArgs({ apiUrl: `https://${host}` })).toThrow(/Invalid/);
36
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_REST_URL: `https://${host}` })).toThrow(/Invalid/);
37
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: `wss://${host}/ws` })).toThrow(/Invalid/);
38
+ }
39
+
40
+ for (const allowedHost of ["staging-api.agentschat.internal", "metadata.goog.example.com", "agents-chat.com"]) {
41
+ expect(isBlockedDshHost(allowedHost)).toBe(false);
42
+ expect(buildMcpAgentsChatArgs({ apiUrl: `https://${allowedHost}` })).toContain(`https://${allowedHost}`);
43
+ expect(loadDshConfig({ ...env, AGENTCHAT_WS_URL: `wss://${allowedHost}/ws` }).wsUrl).toBe(
44
+ `wss://${allowedHost}/ws`,
45
+ );
46
+ }
47
+ });
48
+
49
+ test("checkParentDirectory, applyDshCordisPatchFile, registerOnly & loadDshConfig reject raw symlink_dir/.. traversal", async () => {
50
+ const dir = mkdtempSync(join(tmpdir(), "dsh127-rawdotdot-"));
51
+ try {
52
+ const realDir = join(dir, "real");
53
+ const siblingDir = join(dir, "sibling");
54
+ const outsideDir = join(dir, "outside");
55
+ mkdirSync(realDir, { recursive: true });
56
+ mkdirSync(siblingDir, { recursive: true });
57
+ mkdirSync(outsideDir, { recursive: true });
58
+
59
+ const linkInSibling = join(siblingDir, "escape-link");
60
+ symlinkSync(outsideDir, linkInSibling);
61
+
62
+ const dotDotTarget = `${linkInSibling}/../real/dsh.json`;
63
+ expect(() => checkParentDirectory(dotDotTarget)).toThrow(/parent/);
64
+ expect(() => applyDshCordisPatchFile({ dshHome: `${linkInSibling}/../real` })).toThrow(/parent/);
65
+ await expect(registerOnly("bot", "https://agents-chat.com", dotDotTarget)).rejects.toThrow(/parent/);
66
+
67
+ writeFileSync(join(realDir, "dsh.json"), JSON.stringify({ agentId: "stolen", token: "ac_stolen_123" }), "utf8");
68
+ expect(() => loadDshConfig({}, dotDotTarget)).toThrow(/Missing AgentsChat identity/);
69
+ } finally {
70
+ rmSync(dir, { recursive: true, force: true });
71
+ }
72
+ });
73
+
74
+ test("applyDshCordisPatchFile falls back cleanly on Windows NTFS EPERM/EACCES rename and rejects symlink swap", () => {
75
+ const dir = mkdtempSync(join(tmpdir(), "dsh127-win-"));
76
+ try {
77
+ const patchFile = join(dir, "cordis.patch.yml");
78
+ writeFileSync(patchFile, "# existing comment\n", "utf8");
79
+
80
+ let copyCount = 0;
81
+ const res = applyDshCordisPatchFile({
82
+ dshHome: dir,
83
+ agentsChatProfile: "WinBot",
84
+ fsOps: {
85
+ renameSync() {
86
+ const err: any = new Error("EPERM: operation not permitted, rename");
87
+ err.code = "EPERM";
88
+ throw err;
89
+ },
90
+ copyFileSync(src, dest) {
91
+ copyCount++;
92
+ writeFileSync(dest, readFileSync(src));
93
+ },
94
+ },
95
+ });
96
+ expect(res.changed).toBe(true);
97
+ expect(copyCount).toBe(1);
98
+ expect(readFileSync(patchFile, "utf8")).toContain("WinBot");
99
+
100
+ // Symlink swap during EACCES fallback must be rejected without touching victim
101
+ const dir2 = join(dir, "swap");
102
+ mkdirSync(dir2, { recursive: true });
103
+ const victim = join(dir2, "victim.yml");
104
+ writeFileSync(victim, "untouched\n", "utf8");
105
+ const swapPatch = join(dir2, "cordis.patch.yml");
106
+ expect(() =>
107
+ applyDshCordisPatchFile({
108
+ dshHome: dir2,
109
+ fsOps: {
110
+ renameSync() {
111
+ symlinkSync(victim, swapPatch);
112
+ const err: any = new Error("EACCES");
113
+ err.code = "EACCES";
114
+ throw err;
115
+ },
116
+ },
117
+ }),
118
+ ).toThrow(/symlinked or non-regular/);
119
+ expect(readFileSync(victim, "utf8")).toBe("untouched\n");
120
+ } finally {
121
+ rmSync(dir, { recursive: true, force: true });
122
+ }
123
+ });
124
+
125
+ test("validateHttpOrWsUrl rejects query/hash on WS URLs and isSafeAgentId enforces <=128 char bound", async () => {
126
+ const env = { AGENTCHAT_AGENT_ID: "bot", AGENTCHAT_TOKEN: "ac_token_127" };
127
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: "wss://agents-chat.com/ws?token=leak" })).toThrow(/Invalid/);
128
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: "wss://agents-chat.com/ws#frag" })).toThrow(/Invalid/);
129
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: "ws://127.0.0.1:8787/ws?debug=1" })).toThrow(/Invalid/);
130
+
131
+ expect(loadDshConfig({ ...env, AGENTCHAT_AGENT_ID: "a".repeat(128) }).agentId).toHaveLength(128);
132
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_AGENT_ID: "a".repeat(129) })).toThrow(/Missing AgentsChat identity/);
133
+ await expect(main(["--send", "c".repeat(129), "--text", "hi"])).rejects.toThrow(/channel id/);
134
+ });
135
+
136
+ test("syncBoundDshClients skips reserved sidecar basenames and symlinked profile directories", async () => {
137
+ const dir = mkdtempSync(join(tmpdir(), "dsh127-sidecars-"));
138
+ const envNames = ["AGENTSCHAT_CONFIG_DIR", "AGENTCHAT_AGENT_ID", "AGENTCHAT_TOKEN"] as const;
139
+ const prev = Object.fromEntries(envNames.map((k) => [k, process.env[k]]));
140
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
141
+ const beforeListeners = signals.map((s) => new Set(process.listeners(s)));
142
+ process.env.AGENTSCHAT_CONFIG_DIR = dir;
143
+ process.env.AGENTCHAT_AGENT_ID = "primary-127";
144
+ process.env.AGENTCHAT_TOKEN = "ac_primary_127";
145
+ mkdirSync(join(dir, "profiles"), { recursive: true });
146
+
147
+ const sidecars = [
148
+ "profile",
149
+ "session-binds",
150
+ "session-binds.meta",
151
+ "agy-binds.meta",
152
+ "grok-binds.meta",
153
+ "agy-session-binds",
154
+ "identity-guard",
155
+ "mention-timestamps",
156
+ "dsh",
157
+ "muse",
158
+ ];
159
+ const bindsMap: Record<string, string> = { "session-valid": "ValidBot" };
160
+ sidecars.forEach((sc, idx) => {
161
+ bindsMap[`session-sc-${idx}`] = sc;
162
+ const slug = sc.replace(/[^a-zA-Z0-9_-]/g, "_");
163
+ writeFileSync(join(dir, `${slug}.json`), JSON.stringify({ agent_id: `evil-${idx}`, token: "ac_evil" }), "utf8");
164
+ writeFileSync(
165
+ join(dir, "profiles", `${slug}.json`),
166
+ JSON.stringify({ agent_id: `evil-${idx}`, token: "ac_evil" }),
167
+ "utf8",
168
+ );
169
+ });
170
+ writeFileSync(
171
+ join(dir, "profiles", "ValidBot.json"),
172
+ JSON.stringify({ agent_id: "valid-bot-127", token: "ac_valid_127" }),
173
+ "utf8",
174
+ );
175
+ writeFileSync(join(dir, "session-binds.json"), JSON.stringify(bindsMap), "utf8");
176
+
177
+ const connectedIds: string[] = [];
178
+ const connect = spyOn(MuseAgentChatClient.prototype, "connect").mockImplementation(async function (
179
+ this: MuseAgentChatClient,
180
+ ) {
181
+ connectedIds.push((this as any).options?.agentId ?? (this as any).agentId);
182
+ });
183
+ const joinChannel = spyOn(MuseAgentChatClient.prototype, "joinChannel").mockImplementation(() => {});
184
+ const disconnect = spyOn(MuseAgentChatClient.prototype, "disconnect").mockImplementation(() => {});
185
+ const closed = spyOn(MuseAgentChatClient.prototype, "waitUntilClosed").mockResolvedValue();
186
+ try {
187
+ await main(["--wake"]);
188
+ expect(connectedIds).toEqual(["primary-127", "valid-bot-127"]);
189
+ expect(existsSync(join(dir, "profiles", "ValidBot.json"))).toBe(true);
190
+ } finally {
191
+ connect.mockRestore();
192
+ joinChannel.mockRestore();
193
+ disconnect.mockRestore();
194
+ closed.mockRestore();
195
+ signals.forEach((sig, i) => {
196
+ for (const l of process.listeners(sig)) {
197
+ if (!beforeListeners[i]!.has(l)) process.removeListener(sig, l);
198
+ }
199
+ });
200
+ for (const k of envNames) {
201
+ if (prev[k] === undefined) delete process.env[k];
202
+ else process.env[k] = prev[k];
203
+ }
204
+ rmSync(dir, { recursive: true, force: true });
205
+ }
206
+ });
207
+ });