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
@@ -1,5 +1,10 @@
1
- import { describe, expect, test } from "bun:test";
2
- import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1
+ import { describe, expect, spyOn, test } from "bun:test";
2
+ import { runInNewContext } from "node:vm";
3
+ import { apply as applyIdentityHost } from "../identity-ui/index.js";
4
+ import { createHmac } from "node:crypto";
5
+ import * as fs from "node:fs";
6
+ import * as crypto from "node:crypto";
7
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
3
8
  import { join, resolve } from "node:path";
4
9
  import { tmpdir } from "node:os";
5
10
  import {
@@ -8,10 +13,112 @@ import {
8
13
  mergeDshCordisPatch,
9
14
  resolveDshPatchPath,
10
15
  } from "../src/patch.ts";
11
- import { loadDshConfig, safeDshConfig } from "../src/cli.ts";
16
+ import { loadDshConfig, main, registerOnly, runDshHeadlessResponder, safeDshConfig } from "../src/cli.ts";
17
+ import { TypingHeartbeat } from "../../muse/src/typing.ts";
18
+ import { MuseBridge } from "../../muse/src/bridge.ts";
19
+ import { MuseAgentChatClient } from "../../muse/src/client.ts";
20
+ import {
21
+ apply as applyInboundBridge,
22
+ isAllowedLocalOrigin,
23
+ MAX_HTTP_BODY_BYTES,
24
+ verifySignature,
25
+ } from "../inbound-bridge/index.js";
12
26
 
13
27
  const ROOT = resolve(import.meta.dir, "../..");
14
28
 
29
+ test("DSH rejects embedded URL credentials in configuration and patch arguments", () => {
30
+ const env = { AGENTCHAT_AGENT_ID: "bot", AGENTCHAT_TOKEN: "test-token" };
31
+ for (const auth of ["user:secret@", "user@", ":secret@"]) {
32
+ expect(() => buildMcpAgentsChatArgs({ apiUrl: `https://${auth}test.invalid` })).toThrow(/Invalid/);
33
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_REST_URL: `https://${auth}test.invalid` })).toThrow(/Invalid/);
34
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: `wss://${auth}test.invalid/ws` })).toThrow(/Invalid/);
35
+ }
36
+ });
37
+
38
+ test("patch and registration reject symlinked parents and ancestors without changing victims", async () => {
39
+ const dir = mkdtempSync(join(tmpdir(), "dsh-parent-"));
40
+ const request = spyOn(globalThis, "fetch").mockImplementation((async () => Response.json({ agentId: "bot", token: "test-token" })) as unknown as typeof fetch);
41
+ try {
42
+ const real = join(dir, "real");
43
+ mkdirSync(real);
44
+ symlinkSync(real, join(dir, "link"));
45
+ for (const home of [join(dir, "link"), join(dir, "link", "missing")]) {
46
+ expect(() => applyDshCordisPatchFile({ dshHome: home })).toThrow(/parent/);
47
+ await expect(registerOnly("bot", "https://test.invalid", join(home, "dsh.json"))).rejects.toThrow(/parent/);
48
+ }
49
+ expect(request).not.toHaveBeenCalled();
50
+ expect(readdirSync(real)).toEqual([]);
51
+ applyDshCordisPatchFile({ dshHome: real });
52
+ await registerOnly("bot", "https://test.invalid", join(real, "dsh.json"));
53
+ expect(readdirSync(real).sort()).toEqual(["cordis.patch.yml", "dsh.json"]);
54
+ expect(JSON.parse(readFileSync(join(real, "dsh.json"), "utf8"))).toEqual({ agentId: "bot", token: "test-token" });
55
+ } finally { request.mockRestore(); rmSync(dir, { recursive: true, force: true }); }
56
+ });
57
+
58
+ test("CLI missing values reject a following flag without network IO", async () => {
59
+ const request = spyOn(globalThis, "fetch").mockRejectedValue(new Error("unexpected network"));
60
+ try {
61
+ await expect(main(["--register-only", "--name", "--send", "channel"])).rejects.toThrow(/requires --name/);
62
+ expect(request).not.toHaveBeenCalled();
63
+ } finally { request.mockRestore(); }
64
+ });
65
+
66
+ test("exclusive temporary writes preserve colliding symlinks and their targets", async () => {
67
+ const dir = mkdtempSync(join(tmpdir(), "dsh-exclusive-"));
68
+ const random = spyOn(crypto, "randomBytes").mockImplementation((() => Buffer.from("12345678", "hex")) as typeof crypto.randomBytes);
69
+ const request = spyOn(globalThis, "fetch").mockImplementation((async () => Response.json({ agentId: "bot", token: "test-token" })) as unknown as typeof fetch);
70
+ try {
71
+ const victim = join(dir, "victim");
72
+ writeFileSync(victim, "untouched");
73
+ for (const name of ["cordis.patch.yml", "dsh.json"]) {
74
+ const target = join(dir, name);
75
+ const temp = `${target}.${process.pid}.12345678.tmp`;
76
+ symlinkSync(victim, temp);
77
+ if (name === "dsh.json") {
78
+ await expect(registerOnly("bot", "https://test.invalid", target)).rejects.toThrow(/EEXIST/);
79
+ } else {
80
+ expect(() => applyDshCordisPatchFile({ dshHome: dir })).toThrow(/EEXIST/);
81
+ }
82
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
83
+ expect(existsSync(temp)).toBe(true);
84
+ expect(existsSync(target)).toBe(false);
85
+ }
86
+ } finally { random.mockRestore(); request.mockRestore(); rmSync(dir, { recursive: true, force: true }); }
87
+ });
88
+
89
+ test("headless responder defaults invalid timeouts and clamps overflow without killing a valid child", async () => {
90
+ if (process.platform === "win32") return;
91
+ const dir = mkdtempSync(join(tmpdir(), "dsh-timeout-"));
92
+ try {
93
+ const bin = join(dir, "responder");
94
+ writeFileSync(bin, "#!/bin/sh\nsleep 0.03\nprintf 'reply'\n", { mode: 0o700 });
95
+ for (const timeoutMs of [NaN, Infinity, -Infinity, 0, -1, 2 ** 31, Number.MAX_VALUE]) {
96
+ expect(await runDshHeadlessResponder("hello", { dshBin: bin, timeoutMs })).toBe("reply");
97
+ }
98
+ } finally { rmSync(dir, { recursive: true, force: true }); }
99
+ });
100
+
101
+ test("listen classifies uppercase legacy DMs as direct channels", async () => {
102
+ const priorId = process.env.AGENTCHAT_AGENT_ID;
103
+ const priorToken = process.env.AGENTCHAT_TOKEN;
104
+ process.env.AGENTCHAT_AGENT_ID = "dsh-test-bot";
105
+ process.env.AGENTCHAT_TOKEN = "test-token";
106
+ let kinds: unknown;
107
+ const start = spyOn(MuseBridge.prototype, "start").mockImplementation(async function (this: MuseBridge) {
108
+ kinds = (this as unknown as { opts: { channelKinds: unknown } }).opts.channelKinds;
109
+ });
110
+ const closed = spyOn(MuseAgentChatClient.prototype, "waitUntilClosed").mockResolvedValue();
111
+ try {
112
+ await main(["--listen", "--channel", "DM-legacy", "--channel", "dm-lower", "--channel", "group"]);
113
+ expect(kinds).toEqual({ "DM-legacy": "direct", "dm-lower": "direct", group: "group" });
114
+ await expect(main(["--send", "--text", "hi"])).rejects.toThrow(/requires a channel id/);
115
+ } finally {
116
+ start.mockRestore(); closed.mockRestore();
117
+ if (priorId === undefined) delete process.env.AGENTCHAT_AGENT_ID; else process.env.AGENTCHAT_AGENT_ID = priorId;
118
+ if (priorToken === undefined) delete process.env.AGENTCHAT_TOKEN; else process.env.AGENTCHAT_TOKEN = priorToken;
119
+ }
120
+ });
121
+
15
122
  describe("DeepSeek Harness (dsh) integration", () => {
16
123
  test("package.json declares full dsh bundle (host + client + cordis.patch.yml) and ships all entrypoints", () => {
17
124
  const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
@@ -128,4 +235,884 @@ describe("DeepSeek Harness (dsh) integration", () => {
128
235
  buildMcpAgentsChatArgs({ agentsChatProfile: "MyDsh", apiUrl: "https://agents-chat.com" }),
129
236
  ).toEqual(["-y", "agentschat-mcp@latest", "--profile", "MyDsh", "--url", "https://agents-chat.com"]);
130
237
  });
238
+
239
+ test("Campaign #93: mergeDshCordisPatch splices inside - insert: before later - replace: blocks and matches 2-space indent", () => {
240
+ const multiBlock = [
241
+ "# Multi-block patch file",
242
+ "- insert:",
243
+ " - id: local-proxy",
244
+ " name: 'file:///tmp/proxy.js'",
245
+ "",
246
+ "- replace:",
247
+ " - id: ui-settings",
248
+ " config:",
249
+ " theme: 'dark'",
250
+ "",
251
+ ].join("\n");
252
+
253
+ const res = mergeDshCordisPatch(multiBlock, { agentsChatProfile: "MultiBot" });
254
+ expect(res.changed).toBe(true);
255
+ const insertIdx = res.content.indexOf("- insert:");
256
+ const mcpIdx = res.content.indexOf(" - id: mcp-agentschat");
257
+ const replaceIdx = res.content.indexOf("- replace:");
258
+ expect(insertIdx).toBeGreaterThanOrEqual(0);
259
+ expect(mcpIdx).toBeGreaterThan(insertIdx);
260
+ // Must appear BEFORE `- replace:`, not appended to EOF inside `- replace:`!
261
+ expect(mcpIdx).toBeLessThan(replaceIdx);
262
+ expect(res.content).toContain(" - id: mcp-agentschat\n name: '@deepseek-ai/dsh-mcp-client'");
263
+ expect(mergeDshCordisPatch(res.content).changed).toBe(false);
264
+ });
265
+
266
+ test("Campaign #93: resolveDshPatchPath rejects traversal profiles and applyDshCordisPatchFile leaves no .tmp residue", () => {
267
+ expect(() => resolveDshPatchPath({ dshProfile: "../escape" })).toThrow("Invalid DSH profile name");
268
+ expect(() => resolveDshPatchPath({ dshProfile: "a/b" })).toThrow("Invalid DSH profile name");
269
+ expect(() => resolveDshPatchPath({ dshProfile: " " })).toThrow("Invalid DSH profile name");
270
+ });
271
+
272
+ test("Campaign #96: patch & CLI helpers block prototype keys, flag injection, symlinks, and invalid URLs", async () => {
273
+ expect(() => resolveDshPatchPath({ dshProfile: "foo..bar" })).toThrow("Invalid DSH profile name");
274
+ expect(() => resolveDshPatchPath({ dshProfile: "__proto__" })).toThrow("Invalid DSH profile name");
275
+ expect(() => resolveDshPatchPath({ dshProfile: "constructor" })).toThrow("Invalid DSH profile name");
276
+
277
+ expect(() => buildMcpAgentsChatArgs({ packageSpec: "--eval=evil" })).toThrow("Invalid packageSpec");
278
+ expect(() => buildMcpAgentsChatArgs({ agentsChatProfile: "--url=https://evil.example" })).toThrow(
279
+ "Invalid AgentsChat profile name",
280
+ );
281
+ expect(() => buildMcpAgentsChatArgs({ agentsChatProfile: "__proto__" })).toThrow(
282
+ "Invalid AgentsChat profile name",
283
+ );
284
+ expect(() => buildMcpAgentsChatArgs({ apiUrl: "javascript:alert(1)" })).toThrow("Invalid AgentsChat API URL");
285
+ expect(() => buildMcpAgentsChatArgs({ apiUrl: "--flag" })).toThrow("Invalid AgentsChat API URL");
286
+
287
+ const dir = mkdtempSync(join(tmpdir(), "dsh-c96-patch-"));
288
+ try {
289
+ const target = join(dir, "victim.yml");
290
+ writeFileSync(target, "keep: true\n", "utf8");
291
+ const linkPatch = join(dir, "cordis.patch.yml");
292
+ symlinkSync(target, linkPatch);
293
+ expect(() => applyDshCordisPatchFile({ dshHome: dir })).toThrow(/non-regular or symlinked/);
294
+ expect(readFileSync(target, "utf8")).toBe("keep: true\n");
295
+
296
+ const cfgLink = join(dir, "dsh-link.json");
297
+ const realCfg = join(dir, "real-dsh.json");
298
+ writeFileSync(realCfg, JSON.stringify({ agentId: "bot-1", token: "ac_1234567890" }), "utf8");
299
+ symlinkSync(realCfg, cfgLink);
300
+ expect(() => loadDshConfig({}, cfgLink)).toThrow(/Missing AgentsChat identity/);
301
+ expect(() => loadDshConfig({ AGENTCHAT_AGENT_ID: " ", AGENTCHAT_TOKEN: "ac_1234567890" }, join(dir, "none.json"))).toThrow(
302
+ /Missing AgentsChat identity/,
303
+ );
304
+ expect(() =>
305
+ loadDshConfig(
306
+ { AGENTCHAT_AGENT_ID: "bot-1", AGENTCHAT_TOKEN: "ac_1234567890", AGENTCHAT_WS_URL: "https://not-ws.example" },
307
+ join(dir, "none.json"),
308
+ ),
309
+ ).toThrow(/Unsupported AgentChat WebSocket protocol/);
310
+
311
+ expect(await runDshHeadlessResponder("hi", { dshProfile: "--evil-flag" })).toBeNull();
312
+ } finally {
313
+ rmSync(dir, { recursive: true, force: true });
314
+ }
315
+ });
316
+
317
+ test("Campaign #96: verifySignature enforces exact 64-hex HMAC and isAllowedLocalOrigin rejects external/null origins", () => {
318
+ const secret = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
319
+ const body = '{"message_id":"m1","content":"hello"}';
320
+ const validSig = createHmac("sha256", secret).update(body, "utf8").digest("hex");
321
+
322
+ expect(verifySignature(body, validSig, secret)).toBe(true);
323
+ expect(verifySignature(body, `sha256=${validSig}`, secret)).toBe(true);
324
+ // Reject trailing non-hex garbage that Buffer.from(..., 'hex') would otherwise silently truncate!
325
+ expect(verifySignature(body, `${validSig}zzzz`, secret)).toBe(false);
326
+ expect(verifySignature(body, validSig.slice(0, 62), secret)).toBe(false);
327
+ expect(verifySignature(body, "g".repeat(64), secret)).toBe(false);
328
+
329
+ expect(isAllowedLocalOrigin("http://127.0.0.1:8799")).toBe(true);
330
+ expect(isAllowedLocalOrigin("http://localhost:3000")).toBe(true);
331
+ expect(isAllowedLocalOrigin("http://[::1]:5173")).toBe(true);
332
+ expect(isAllowedLocalOrigin("tauri://localhost")).toBe(true);
333
+ expect(isAllowedLocalOrigin("app://dsh.local")).toBe(true);
334
+ expect(isAllowedLocalOrigin("file://")).toBe(true);
335
+
336
+ expect(isAllowedLocalOrigin("https://evil.example")).toBe(false);
337
+ expect(isAllowedLocalOrigin("http://127.0.0.1.evil.example")).toBe(false);
338
+ expect(isAllowedLocalOrigin("http://127.0.0.1:99999")).toBe(false);
339
+ expect(isAllowedLocalOrigin("null")).toBe(false);
340
+ expect(isAllowedLocalOrigin("")).toBe(false);
341
+ });
342
+
343
+ test("Campaign #96: inbound bridge loopback server blocks cross-origin CSRF, prototype binds, and >64KiB bodies", async () => {
344
+ const dir = mkdtempSync(join(tmpdir(), "dsh-c96-bridge-"));
345
+ let cleanup: (() => void) | undefined;
346
+ try {
347
+ const profilesDir = join(dir, "profiles");
348
+ mkdirSync(profilesDir, { recursive: true });
349
+ writeFileSync(
350
+ join(profilesDir, "DshTest.json"),
351
+ JSON.stringify({ agent_id: "dsh-bot-96", token: "ac_secret_96969696", display_name: "DSH 96" }),
352
+ "utf8",
353
+ );
354
+ writeFileSync(
355
+ join(dir, "session-binds.json"),
356
+ '{"__proto__":"DshTest","session-good":"DshTest"}',
357
+ "utf8",
358
+ );
359
+
360
+ const delivered: unknown[] = [];
361
+ let listenPort = 0;
362
+ await new Promise<void>((resolveReady) => {
363
+ const fakeCtx = {
364
+ get(service: string) {
365
+ if (service === "agents") {
366
+ return {
367
+ roots: () => [
368
+ {
369
+ id: "session-good",
370
+ status: "idle",
371
+ session: "s1",
372
+ followup(msg: unknown) {
373
+ delivered.push(msg);
374
+ },
375
+ },
376
+ ],
377
+ };
378
+ }
379
+ return undefined;
380
+ },
381
+ effect(fn: () => () => void) {
382
+ cleanup = fn();
383
+ },
384
+ };
385
+ applyInboundBridge(fakeCtx, {
386
+ port: 0,
387
+ mcpBin: "",
388
+ agentschatDir: dir,
389
+ logPath: join(dir, "bridge.log"),
390
+ onListening({ port }: { port: number }) {
391
+ listenPort = port;
392
+ resolveReady();
393
+ },
394
+ });
395
+ });
396
+
397
+ const base = `http://127.0.0.1:${listenPort}`;
398
+
399
+ // 1. Cross-origin browser request (evil website & sandboxed `Origin: null`) -> 403 without ACAO
400
+ const evilGet = await fetch(`${base}/identity`, {
401
+ headers: { Origin: "https://attacker.example" },
402
+ });
403
+ expect(evilGet.status).toBe(403);
404
+ expect(evilGet.headers.get("access-control-allow-origin")).toBeNull();
405
+
406
+ const nullOriginPreflight = await fetch(`${base}/identity/bind`, {
407
+ method: "OPTIONS",
408
+ headers: { Origin: "null" },
409
+ });
410
+ expect(nullOriginPreflight.status).toBe(403);
411
+ expect(nullOriginPreflight.headers.get("access-control-allow-origin")).toBeNull();
412
+
413
+ // 2. Allowed local DSH UI origin -> echoed specifically with Vary: Origin (never '*') + __proto__ stripped
414
+ const localGet = await fetch(`${base}/identity`, {
415
+ headers: { Origin: "http://127.0.0.1:3000" },
416
+ });
417
+ expect(localGet.status).toBe(200);
418
+ expect(localGet.headers.get("access-control-allow-origin")).toBe("http://127.0.0.1:3000");
419
+ expect(localGet.headers.get("vary")).toContain("Origin");
420
+ const idBody = (await localGet.json()) as { binds: Record<string, string> };
421
+ expect(Object.prototype.hasOwnProperty.call(idBody.binds, "__proto__")).toBe(false);
422
+ expect(idBody.binds).toEqual({});
423
+
424
+ // 3. Prototype-key bind attempt rejected with 400
425
+ const protoBind = await fetch(`${base}/identity/bind`, {
426
+ method: "POST",
427
+ headers: { "content-type": "application/json", Origin: "http://localhost:5173" },
428
+ body: JSON.stringify({ sessionId: "__proto__", profileName: "DshTest" }),
429
+ });
430
+ expect(protoBind.status).toBe(400);
431
+
432
+ // 4. Oversized (> 64 KiB) wake body rejected with 413
433
+ const secret = readFileSync(join(dir, "dsh-inbound.secret"), "utf8").trim();
434
+ const hugeBody = JSON.stringify({ message_id: "huge", content: "x".repeat(MAX_HTTP_BODY_BYTES + 1024) });
435
+ const hugeSig = createHmac("sha256", secret).update(hugeBody, "utf8").digest("hex");
436
+ try {
437
+ const hugeWake = await fetch(`${base}/agentschat/wake`, {
438
+ method: "POST",
439
+ headers: { "content-type": "application/json", "x-agentschat-signature": hugeSig },
440
+ body: hugeBody,
441
+ });
442
+ expect(hugeWake.status).toBe(413);
443
+ } catch {
444
+ // Socket reset on req.destroy() after 413 write is also acceptable on fast loopback drains
445
+ }
446
+ expect(delivered.length).toBe(0);
447
+
448
+ // 5. Valid signed wake within bounds delivers cleanly into bound idle session
449
+ const okPayload = JSON.stringify({
450
+ message_id: "msg-96-ok",
451
+ channel_id: "dm-96",
452
+ sender_id: "peer-1",
453
+ content: "ping 96",
454
+ target_session_id: "session-good",
455
+ });
456
+ const okSig = createHmac("sha256", secret).update(okPayload, "utf8").digest("hex");
457
+ const okWake = await fetch(`${base}/agentschat/wake`, {
458
+ method: "POST",
459
+ headers: { "content-type": "application/json", "x-agentschat-signature": okSig },
460
+ body: okPayload,
461
+ });
462
+ expect(okWake.status).toBe(200);
463
+ expect(delivered.length).toBe(1);
464
+ } finally {
465
+ cleanup?.();
466
+ rmSync(dir, { recursive: true, force: true });
467
+ }
468
+ });
469
+
470
+ test("Campaign #109 KR3: enforces TLS on remote ws/http URLs while allowing loopback, classifies dm: as direct, validates --name, and rejects >1MiB patch files", async () => {
471
+ const env = { AGENTCHAT_AGENT_ID: "bot-109", AGENTCHAT_TOKEN: "ac_token_109" };
472
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: "ws://remote.example/ws" })).toThrow(/TLS/);
473
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_REST_URL: "http://remote.example" })).toThrow(/TLS/);
474
+ expect(() => buildMcpAgentsChatArgs({ apiUrl: "http://remote.example" })).toThrow(/Invalid AgentsChat API URL/);
475
+
476
+ expect(loadDshConfig({ ...env, AGENTCHAT_WS_URL: "ws://127.0.0.1:8787/ws", AGENTCHAT_REST_URL: "http://localhost:8787" }).wsUrl).toBe(
477
+ "ws://127.0.0.1:8787/ws",
478
+ );
479
+ expect(buildMcpAgentsChatArgs({ apiUrl: "http://127.0.0.1:8787" })).toContain("http://127.0.0.1:8787");
480
+
481
+ await expect(registerOnly(" ", "https://agents-chat.com")).rejects.toThrow(/Invalid --name/);
482
+ await expect(registerOnly("bad\nname", "https://agents-chat.com")).rejects.toThrow(/Invalid --name/);
483
+ await expect(registerOnly("good-bot", "http://remote.example")).rejects.toThrow(/TLS/);
484
+
485
+ const priorId = process.env.AGENTCHAT_AGENT_ID;
486
+ const priorToken = process.env.AGENTCHAT_TOKEN;
487
+ process.env.AGENTCHAT_AGENT_ID = "dsh-test-bot";
488
+ process.env.AGENTCHAT_TOKEN = "test-token";
489
+ let kinds: unknown;
490
+ const start = spyOn(MuseBridge.prototype, "start").mockImplementation(async function (this: MuseBridge) {
491
+ kinds = (this as unknown as { opts: { channelKinds: unknown } }).opts.channelKinds;
492
+ });
493
+ const closed = spyOn(MuseAgentChatClient.prototype, "waitUntilClosed").mockResolvedValue();
494
+ try {
495
+ await main(["--listen", "--channel", "dm:colon-direct", "--channel", "DM:upper-colon"]);
496
+ expect(kinds).toEqual({ "dm:colon-direct": "direct", "DM:upper-colon": "direct" });
497
+ } finally {
498
+ start.mockRestore();
499
+ closed.mockRestore();
500
+ if (priorId === undefined) delete process.env.AGENTCHAT_AGENT_ID; else process.env.AGENTCHAT_AGENT_ID = priorId;
501
+ if (priorToken === undefined) delete process.env.AGENTCHAT_TOKEN; else process.env.AGENTCHAT_TOKEN = priorToken;
502
+ }
503
+
504
+ const dir = mkdtempSync(join(tmpdir(), "dsh-c109-oversize-"));
505
+ try {
506
+ const patchFile = join(dir, "cordis.patch.yml");
507
+ writeFileSync(patchFile, "# comment\n" + "x".repeat(1_050_000), "utf8");
508
+ expect(() => applyDshCordisPatchFile({ dshHome: dir })).toThrow(/oversized/);
509
+ } finally {
510
+ rmSync(dir, { recursive: true, force: true });
511
+ }
512
+ });
513
+ });
514
+
515
+ async function startTestInbound(
516
+ dir: string,
517
+ options: Record<string, unknown> = {},
518
+ delivered: unknown[] = [],
519
+ ): Promise<{ base: string; stop: () => void }> {
520
+ let stop = () => {};
521
+ const base = await new Promise<string>((ready) => {
522
+ applyInboundBridge({
523
+ get(service: string) {
524
+ if (service === "agents") return { roots: () => [{
525
+ id: "session-test", status: "idle", session: "test",
526
+ followup(message: unknown) { delivered.push(message); },
527
+ }] };
528
+ return undefined;
529
+ },
530
+ effect(fn: () => () => void) { stop = fn(); },
531
+ }, {
532
+ port: 0, mcpBin: "", agentschatDir: dir, logPath: join(dir, "bridge.log"),
533
+ ...options,
534
+ onListening({ port }: { port: number }) { ready(`http://127.0.0.1:${port}`); },
535
+ });
536
+ });
537
+ return { base, stop };
538
+ }
539
+
540
+ function postJson(base: string, path: string, body: unknown): Promise<Response> {
541
+ return fetch(`${base}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
542
+ }
543
+
544
+ test("DSH REST URL, profile and home guards reject ambiguous inputs and keep loopback working", () => {
545
+ const env = { AGENTCHAT_AGENT_ID: "bot", AGENTCHAT_TOKEN: "test-token" };
546
+ for (const url of ["https://example.com:0", "http://localhost:0", "https://example.com?x=1", "https://example.com#x", 'https://example.com/"', "https://example.com/<x>", "https://example.com/\\x", "https://example.com/a b", " https://example.com", "https://example.com\n"]) {
547
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_REST_URL: url })).toThrow();
548
+ }
549
+ for (const url of ["https://example.com:0", "http://localhost:0", "https://example.com?x=1", "https://example.com#x"]) {
550
+ expect(() => buildMcpAgentsChatArgs({ apiUrl: url })).toThrow();
551
+ }
552
+ for (const url of ["wss://example.com:0/ws", "ws://127.0.0.1:0/ws", 'wss://example.com/"', "wss://example.com/\\x"]) {
553
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: url })).toThrow();
554
+ }
555
+ for (const profile of ["CONSTRUCTOR", "Prototype", "__PrOtO__"]) {
556
+ expect(() => resolveDshPatchPath({ dshProfile: profile })).toThrow();
557
+ expect(() => buildMcpAgentsChatArgs({ agentsChatProfile: profile })).toThrow();
558
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_AGENT_ID: profile })).toThrow();
559
+ }
560
+ for (const home of ["relative", "./relative", "../relative", "-option", "/tmp/bad\npath", "/" + "x".repeat(4096)]) {
561
+ expect(() => resolveDshPatchPath({ dshHome: home })).toThrow(/Invalid DSH home/);
562
+ }
563
+ expect(resolveDshPatchPath({ dshHome: "/" + "x".repeat(4095) }).length).toBeGreaterThan(4096);
564
+ expect(loadDshConfig({ ...env, AGENTCHAT_WS_URL: "ws://127.0.0.1:8787/ws", AGENTCHAT_REST_URL: "http://localhost:8787" }).restUrl).toBe("http://localhost:8787");
565
+ });
566
+
567
+ test("DSH rejects own __proto__ in config JSON", () => {
568
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-config-"));
569
+ try {
570
+ const path = join(dir, "dsh.json");
571
+ writeFileSync(path, '{"__proto__":{},"agentId":"bot","token":"test-token"}');
572
+ expect(() => loadDshConfig({}, path)).toThrow(/Missing/);
573
+ writeFileSync(path, '{"agentId":"bot","token":"test-token"}');
574
+ expect(loadDshConfig({}, path).agentId).toBe("bot");
575
+ } finally { rmSync(dir, { recursive: true, force: true }); }
576
+ });
577
+
578
+ test("registration rejects unsafe returned IDs before writing", async () => {
579
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-ids-"));
580
+ let agentId = "";
581
+ const request = spyOn(globalThis, "fetch").mockImplementation((async () => Response.json({ agentId, token: "test-token" })) as unknown as typeof fetch);
582
+ try {
583
+ for (agentId of [".", "..", "CONSTRUCTOR", "Prototype", "__PrOtO__", "bad/id", "bad\\id", "bad id", "bad\nid", " bad", "bad\u007f"]) {
584
+ await expect(registerOnly("bot", "https://example.com", join(dir, "dsh.json"))).rejects.toThrow(/valid agent/);
585
+ expect(existsSync(join(dir, "dsh.json"))).toBe(false);
586
+ }
587
+ agentId = "valid-bot.1";
588
+ await registerOnly("bot", "https://example.com", join(dir, "dsh.json"));
589
+ expect(JSON.parse(readFileSync(join(dir, "dsh.json"), "utf8")).agentId).toBe(agentId);
590
+ } finally { request.mockRestore(); rmSync(dir, { recursive: true, force: true }); }
591
+ });
592
+
593
+ test("registration bounds actual streamed bytes at 1MiB and cancels oversized responses", async () => {
594
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-size-"));
595
+ const valid = JSON.stringify({ agentId: "bot", token: "test-token" });
596
+ let cancelled = false;
597
+ let oversized = true;
598
+ const request = spyOn(globalThis, "fetch").mockImplementation((async () => {
599
+ if (!oversized) return new Response(valid + " ".repeat(1024 * 1024 - valid.length));
600
+ let index = 0;
601
+ return new Response(new ReadableStream<Uint8Array>({
602
+ pull(controller) { controller.enqueue(new Uint8Array(++index <= 16 ? 65536 : 1).fill(32)); },
603
+ cancel() { cancelled = true; },
604
+ }), { headers: { "content-length": "1" } });
605
+ }) as unknown as typeof fetch);
606
+ try {
607
+ await expect(registerOnly("bot", "https://example.com", join(dir, "dsh.json"))).rejects.toThrow(/exceeds 1MiB/);
608
+ expect(cancelled).toBe(true);
609
+ expect(existsSync(join(dir, "dsh.json"))).toBe(false);
610
+ oversized = false;
611
+ await registerOnly("bot", "https://example.com", join(dir, "dsh.json"));
612
+ expect(JSON.parse(readFileSync(join(dir, "dsh.json"), "utf8")).agentId).toBe("bot");
613
+ } finally { request.mockRestore(); rmSync(dir, { recursive: true, force: true }); }
614
+ });
615
+
616
+ test("registration rechecks a target swapped to a symlink after temp creation", async () => {
617
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-race-"));
618
+ const target = join(dir, "dsh.json"), victim = join(dir, "victim");
619
+ writeFileSync(victim, "untouched");
620
+ const request = spyOn(globalThis, "fetch").mockImplementation((async () => Response.json({ agentId: "bot", token: "test-token" })) as unknown as typeof fetch);
621
+ const originalWrite = fs.writeFileSync;
622
+ const write = spyOn(fs, "writeFileSync").mockImplementation(((path: any, ...args: any[]) => {
623
+ (originalWrite as any)(path, ...args);
624
+ if (String(path).startsWith(`${target}.`) && String(path).endsWith(".tmp")) symlinkSync(victim, target);
625
+ }) as typeof fs.writeFileSync);
626
+ try {
627
+ await expect(registerOnly("bot", "https://example.com", target)).rejects.toThrow(/non-regular/);
628
+ expect(fs.lstatSync(target).isSymbolicLink()).toBe(true);
629
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
630
+ expect(readdirSync(dir).some((name) => name.endsWith(".tmp"))).toBe(false);
631
+ } finally { write.mockRestore(); request.mockRestore(); rmSync(dir, { recursive: true, force: true }); }
632
+ });
633
+
634
+ test("inbound prompts classify dm: and DM- and bound sanitized header fields", async () => {
635
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-prompt-"));
636
+ const delivered: any[] = [];
637
+ const bridge = await startTestInbound(dir, {}, delivered);
638
+ try {
639
+ const secret = readFileSync(join(dir, "dsh-inbound.secret"), "utf8").trim();
640
+ for (const channel of ["dm:legacy", "DM-legacy", "group"]) {
641
+ const payload = JSON.stringify({ channel_id: channel + "\n" + "x".repeat(200), message_id: "msg-" + channel + "\r\n" + "m".repeat(200), sender_id: "peer\u0000\u007f\n" + "s".repeat(200), content: "hello\nworld", target_session_id: "session-test" });
642
+ const response = await fetch(`${bridge.base}/agentschat/wake`, { method: "POST", headers: { "x-agentschat-signature": createHmac("sha256", secret).update(payload).digest("hex") }, body: payload });
643
+ expect(response.status).toBe(200);
644
+ const rendered = JSON.stringify(delivered.at(-1));
645
+ const message = delivered.at(-1);
646
+ const text = typeof message.content === "string" ? message.content : message.content[0].text;
647
+ expect(text).toContain(`kind: ${channel === "group" ? "channel message" : "direct message"}`);
648
+ expect(text).toContain("hello\nworld");
649
+ const lines = text.split("\n");
650
+ for (const label of ["channel_id: ", "message_id: ", "from: "]) {
651
+ const line = lines.find((line: string) => line.startsWith(label))!;
652
+ expect(line.slice(label.length)).toHaveLength(128);
653
+ expect(line).not.toMatch(/[\x00-\x1f\x7f]/);
654
+ }
655
+ expect(rendered).not.toContain("\\u0000");
656
+ }
657
+ expect(delivered).toHaveLength(3);
658
+ } finally { bridge.stop(); rmSync(dir, { recursive: true, force: true }); }
659
+ });
660
+
661
+ test("inbound identity filters case-insensitive keys, own proto documents, and reads .JSON", async () => {
662
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-profiles-"));
663
+ mkdirSync(join(dir, "profiles"));
664
+ for (const name of ["Good.JSON", "CONSTRUCTOR.json", "Prototype.JSON"]) writeFileSync(join(dir, "profiles", name), JSON.stringify({ agent_id: "bot" }));
665
+ writeFileSync(join(dir, "profiles", "Dirty.json"), '{"__proto__":{},"agent_id":"dirty"}');
666
+ writeFileSync(join(dir, "session-binds.json"), '{"__proto__":{},"session-ok":"Good"}');
667
+ const bridge = await startTestInbound(dir);
668
+ try {
669
+ let data = await (await fetch(`${bridge.base}/identity`)).json() as any;
670
+ expect(data.profiles.map((p: any) => p.name)).toEqual(["Good"]);
671
+ expect(data.binds).toEqual({});
672
+ for (const sessionId of [".", "..", "CONSTRUCTOR", "Prototype", "a/b", "a\\b"]) {
673
+ expect((await postJson(bridge.base, "/identity/bind", { sessionId, profileName: "Good" })).status).toBe(400);
674
+ }
675
+ expect((await postJson(bridge.base, "/identity/bind", { sessionId: "session-test", profileName: "Good" })).status).toBe(200);
676
+ data = await (await fetch(`${bridge.base}/identity`)).json();
677
+ expect(data.binds).toEqual({ "session-test": "Good" });
678
+ } finally { bridge.stop(); rmSync(dir, { recursive: true, force: true }); }
679
+ });
680
+
681
+ test("identity/create rejects remote HTTP, credentials, port zero, queries and fragments before fetch", async () => {
682
+ const realFetch = globalThis.fetch;
683
+ let registrations = 0;
684
+ const request = spyOn(globalThis, "fetch").mockImplementation(((input: any, init: any) => {
685
+ if (String(input).endsWith("/api/account/register")) { registrations++; return Promise.resolve(Response.json({ agentId: "bot", token: "test-token" })); }
686
+ return realFetch(input, init);
687
+ }) as typeof fetch);
688
+ try {
689
+ for (const apiUrl of ["http://remote.example", "https://example.com:0", "http://localhost:0", "https://user:pass@example.com", "https://example.com?x=1", "https://example.com#x"]) {
690
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-url-"));
691
+ const bridge = await startTestInbound(dir, { apiUrl });
692
+ try {
693
+ expect((await postJson(bridge.base, "/identity/create", { name: "test" })).status).toBe(400);
694
+ expect(readdirSync(join(dir, "profiles"))).toEqual([]);
695
+ } finally { bridge.stop(); rmSync(dir, { recursive: true, force: true }); }
696
+ }
697
+ expect(registrations).toBe(0);
698
+ for (const apiUrl of ["https://example.com", "http://localhost:8787", "http://127.0.0.1:8787", "http://[::1]:8787"]) {
699
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-local-"));
700
+ const bridge = await startTestInbound(dir, { apiUrl });
701
+ try { expect((await postJson(bridge.base, "/identity/create", { name: "test" })).status).toBe(200); }
702
+ finally { bridge.stop(); rmSync(dir, { recursive: true, force: true }); }
703
+ }
704
+ expect(registrations).toBe(4);
705
+ } finally { request.mockRestore(); }
706
+ });
707
+
708
+ test("identity/create rejects oversized responses and unsafe agent IDs, scrubs OAuth, webhook and JWT errors", async () => {
709
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-response-"));
710
+ const bridge = await startTestInbound(dir, { apiUrl: "https://example.com" });
711
+ const realFetch = globalThis.fetch;
712
+ let response = () => Response.json({});
713
+ const request = spyOn(globalThis, "fetch").mockImplementation(((input: any, init: any) => String(input).endsWith("/api/account/register") ? Promise.resolve(response()) : realFetch(input, init)) as typeof fetch);
714
+ try {
715
+ response = () => new Response(" ".repeat(1024 * 1024 + 1), { headers: { "content-length": "1" } });
716
+ let result = await postJson(bridge.base, "/identity/create", { name: "test" });
717
+ expect(result.status).toBe(500);
718
+ expect((await result.json() as any).error).toContain("1MiB");
719
+ for (const agentId of ["CONSTRUCTOR", "Prototype", "bad id", "bad/id", "bad\\id", ".", "..", " bad", "bad\n"]) {
720
+ response = () => Response.json({ agentId, token: "test-token" });
721
+ expect((await postJson(bridge.base, "/identity/create", { name: "test" })).status).toBe(502);
722
+ }
723
+ const secrets = ["mcp_at_abcdefgh", "mcp_rt_abcdefgh", "mcp_code_abcdefgh", "whsec_abcdefgh", "eyJabcdefghij.abc.sig"];
724
+ response = () => new Response(secrets.join(" "), { status: 400 });
725
+ result = await postJson(bridge.base, "/identity/create", { name: "test" });
726
+ expect(result.status).toBe(502);
727
+ const text = await result.text();
728
+ for (const secret of secrets) expect(text).not.toContain(secret);
729
+ expect(text.match(/REDACTED/g)).toHaveLength(5);
730
+ response = () => new Response("x".repeat(190) + " " + secrets[0], { status: 400 });
731
+ result = await postJson(bridge.base, "/identity/create", { name: "test" });
732
+ expect(await result.text()).not.toContain("mcp_at_");
733
+ expect(readdirSync(join(dir, "profiles"))).toEqual([]);
734
+ } finally { request.mockRestore(); bridge.stop(); rmSync(dir, { recursive: true, force: true }); }
735
+ });
736
+
737
+ test("inbound secret, bind, profile and log writes refuse symlinked parents", async () => {
738
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-parents-"));
739
+ mkdirSync(join(dir, "real"));
740
+ symlinkSync(join(dir, "real"), join(dir, "link"));
741
+ try {
742
+ let effects = 0;
743
+ applyInboundBridge({ get() {}, effect() { effects++; } }, { port: 0, mcpBin: "", agentschatDir: join(dir, "link"), logPath: join(dir, "link", "log") });
744
+ expect(effects).toBe(0);
745
+ expect(readdirSync(join(dir, "real"))).toEqual([]);
746
+ const bridge = await startTestInbound(dir, { logPath: join(dir, "link", "log") });
747
+ try {
748
+ symlinkSync(join(dir, "real"), join(dir, "profiles"));
749
+ expect((await postJson(bridge.base, "/identity/create", { name: "test" })).status).toBe(500);
750
+ expect(readdirSync(join(dir, "real"))).toEqual([]);
751
+ } finally { bridge.stop(); }
752
+ } finally { rmSync(dir, { recursive: true, force: true }); }
753
+ });
754
+
755
+ test("inbound exclusive temp writes preserve collisions for secrets, binds and profiles", async () => {
756
+ for (const kind of ["secret", "bind", "profile"]) {
757
+ const dir = mkdtempSync(join(tmpdir(), `dsh118-exclusive-${kind}-`));
758
+ const victim = join(dir, "victim");
759
+ writeFileSync(victim, "untouched");
760
+ let collided = "";
761
+ let stop = () => {};
762
+ const originalWrite = fs.writeFileSync;
763
+ const writes = spyOn(fs, "writeFileSync").mockImplementation(((path: any, ...args: any[]) => {
764
+ const name = String(path);
765
+ const matches = name.endsWith(".tmp") && (kind === "secret" ? name.includes("dsh-inbound.secret.") : kind === "bind" ? name.includes("session-binds.json.") : name.includes("test.json."));
766
+ if (matches) { collided = name; symlinkSync(victim, name); }
767
+ return (originalWrite as any)(path, ...args);
768
+ }) as typeof fs.writeFileSync);
769
+ const realFetch = globalThis.fetch;
770
+ const request = spyOn(globalThis, "fetch").mockImplementation(((input: any, init: any) => String(input).endsWith("/api/account/register") ? Promise.resolve(Response.json({ agentId: "bot", token: "test-token" })) : realFetch(input, init)) as typeof fetch);
771
+ try {
772
+ if (kind === "secret") {
773
+ let effects = 0;
774
+ applyInboundBridge({ get() {}, effect() { effects++; } }, { port: 0, mcpBin: "", agentschatDir: dir, logPath: join(dir, "log") });
775
+ expect(effects).toBe(0);
776
+ } else {
777
+ const bridge = await startTestInbound(dir, { apiUrl: "https://example.com" });
778
+ stop = bridge.stop;
779
+ const result = await postJson(bridge.base, kind === "bind" ? "/identity/unbind" : "/identity/create", { sessionId: "session-test", name: "test" });
780
+ expect(result.status).toBe(500);
781
+ }
782
+ expect(collided).not.toBe("");
783
+ expect(fs.lstatSync(collided).isSymbolicLink()).toBe(true);
784
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
785
+ } finally { request.mockRestore(); writes.mockRestore(); stop(); rmSync(dir, { recursive: true, force: true }); }
786
+ }
787
+ });
788
+
789
+ test("inbound rechecks secret, bind and profile targets immediately before rename", async () => {
790
+ for (const kind of ["secret", "bind", "profile"]) {
791
+ const dir = mkdtempSync(join(tmpdir(), `dsh118-recheck-${kind}-`));
792
+ const victim = join(dir, "victim");
793
+ writeFileSync(victim, "untouched");
794
+ let swapped = "";
795
+ let stop = () => {};
796
+ const originalWrite = fs.writeFileSync;
797
+ const writes = spyOn(fs, "writeFileSync").mockImplementation(((path: any, ...args: any[]) => {
798
+ const result = (originalWrite as any)(path, ...args);
799
+ const name = String(path);
800
+ const matches = name.endsWith(".tmp") && (kind === "secret" ? name.includes("dsh-inbound.secret.") : kind === "bind" ? name.includes("session-binds.json.") : name.includes("test.json."));
801
+ if (matches) {
802
+ swapped = kind === "secret" ? join(dir, "dsh-inbound.secret") : kind === "bind" ? join(dir, "session-binds.json") : join(dir, "profiles", "test.json");
803
+ symlinkSync(victim, swapped);
804
+ }
805
+ return result;
806
+ }) as typeof fs.writeFileSync);
807
+ const realFetch = globalThis.fetch;
808
+ const request = spyOn(globalThis, "fetch").mockImplementation(((input: any, init: any) => String(input).endsWith("/api/account/register") ? Promise.resolve(Response.json({ agentId: "bot", token: "test-token" })) : realFetch(input, init)) as typeof fetch);
809
+ try {
810
+ if (kind === "secret") {
811
+ let effects = 0;
812
+ applyInboundBridge({ get() {}, effect() { effects++; } }, { port: 0, mcpBin: "", agentschatDir: dir, logPath: join(dir, "log") });
813
+ expect(effects).toBe(0);
814
+ } else {
815
+ const bridge = await startTestInbound(dir, { apiUrl: "https://example.com" });
816
+ stop = bridge.stop;
817
+ const result = await postJson(bridge.base, kind === "bind" ? "/identity/unbind" : "/identity/create", { sessionId: "session-test", name: "test" });
818
+ expect(result.status).toBe(500);
819
+ }
820
+ expect(swapped).not.toBe("");
821
+ expect(fs.lstatSync(swapped).isSymbolicLink()).toBe(true);
822
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
823
+ expect(readdirSync(dir).some((name) => name.endsWith(".tmp"))).toBe(false);
824
+ if (existsSync(join(dir, "profiles"))) expect(readdirSync(join(dir, "profiles")).some((name) => name.endsWith(".tmp"))).toBe(false);
825
+ } finally { request.mockRestore(); writes.mockRestore(); stop(); rmSync(dir, { recursive: true, force: true }); }
826
+ }
827
+ });
828
+
829
+ test("bound DSH clients strip .JSON case-insensitively and skip reserved or own-proto profiles", async () => {
830
+ const dir = mkdtempSync(join(tmpdir(), "dsh118-bound-"));
831
+ const envNames = ["AGENTSCHAT_CONFIG_DIR", "AGENTCHAT_AGENT_ID", "AGENTCHAT_TOKEN"] as const;
832
+ const previous = Object.fromEntries(envNames.map((name) => [name, process.env[name]]));
833
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
834
+ const listeners = signals.map((signal) => new Set(process.listeners(signal)));
835
+ process.env.AGENTSCHAT_CONFIG_DIR = dir;
836
+ process.env.AGENTCHAT_AGENT_ID = "primary-test";
837
+ process.env.AGENTCHAT_TOKEN = "test-token";
838
+ mkdirSync(join(dir, "profiles"));
839
+ writeFileSync(join(dir, "session-binds.json"), JSON.stringify({ "session-ok": "Good.JSON", "session-bad": "CONSTRUCTOR.JSON", "session-dirty": "Dirty.JSON" }));
840
+ for (const name of ["Good", "CONSTRUCTOR"]) writeFileSync(join(dir, "profiles", `${name}.json`), JSON.stringify({ agent_id: name, token: "test-token" }));
841
+ writeFileSync(join(dir, "profiles", "Dirty.json"), '{"__proto__":{},"agent_id":"dirty","token":"test-token"}');
842
+ let connections = 0;
843
+ const connect = spyOn(MuseAgentChatClient.prototype, "connect").mockImplementation(async () => { connections++; });
844
+ const joinChannel = spyOn(MuseAgentChatClient.prototype, "joinChannel").mockImplementation(() => {});
845
+ const disconnect = spyOn(MuseAgentChatClient.prototype, "disconnect").mockImplementation(() => {});
846
+ const closed = spyOn(MuseAgentChatClient.prototype, "waitUntilClosed").mockResolvedValue();
847
+ try {
848
+ await main(["--wake"]);
849
+ expect(connections).toBe(2); // Primary + Good; neither reserved nor dirty.
850
+ } finally {
851
+ connect.mockRestore(); joinChannel.mockRestore(); disconnect.mockRestore(); closed.mockRestore();
852
+ signals.forEach((signal, index) => {
853
+ for (const listener of process.listeners(signal)) if (!listeners[index]!.has(listener)) process.removeListener(signal, listener);
854
+ });
855
+ for (const name of envNames) { if (previous[name] === undefined) delete process.env[name]; else process.env[name] = previous[name]; }
856
+ rmSync(dir, { recursive: true, force: true });
857
+ }
858
+ });
859
+
860
+ // Render the shipped browser modules with a minimal React/slot host. No DOM or network.
861
+ function renderIdentityChip(file: string, data: unknown, sessionId: string): any {
862
+ const react = {
863
+ createElement: (type: unknown, props: any, ...children: unknown[]) => ({ type, props, children }),
864
+ useState: (() => { let i = 0; return () => [[data, true, "", false][i++], () => {}]; })(),
865
+ useCallback: (fn: unknown) => fn,
866
+ useEffect: () => {},
867
+ };
868
+ let module: any;
869
+ const window = { __ModuleLoader__: { load(value: unknown) { module = value; } } };
870
+ runInNewContext(readFileSync(join(ROOT, "dsh", file), "utf8"), { window, fetch: () => Promise.resolve({}), });
871
+ const plugin = module.factory(() => react);
872
+ let chip: any;
873
+ plugin.apply({ slots: { inject(_name: string, fn: () => void) { fn(); }, register(_options: any, component: any) { chip = component; } } });
874
+ return chip({ sessionId });
875
+ }
876
+
877
+ function identityElements(tree: any): any[] {
878
+ if (!tree || typeof tree !== "object") return [];
879
+ if (Array.isArray(tree)) return tree.flatMap(identityElements);
880
+ return [tree, ...(tree.children ?? []).flatMap(identityElements)];
881
+ }
882
+
883
+ test("identity clients render null/non-object binds and malformed profiles without crashing", () => {
884
+ for (const file of ["client.js", "identity-ui/client.js"]) {
885
+ for (const binds of [null, undefined, false, 7, "oops", {}]) {
886
+ for (const profiles of [null, undefined, false, 7, "oops", {}]) {
887
+ expect(() => renderIdentityChip(file, { binds, profiles }, "session-ok")).not.toThrow();
888
+ }
889
+ }
890
+ const tree = renderIdentityChip(file, { binds: {}, profiles: [null, false, 7, { name: "missing" }, { name: "numeric", agentId: 42 }, { name: "null", agentId: null }] }, "session-ok");
891
+ expect(identityElements(tree).filter((el) => el.type === "button")).toHaveLength(5);
892
+ }
893
+ });
894
+
895
+ test("identity clients never resolve inherited session binds, but render own binds and protected links", () => {
896
+ for (const file of ["client.js", "identity-ui/client.js"]) {
897
+ for (const session of ["constructor", "toString", "__proto__"]) {
898
+ let reads = 0;
899
+ const inherited = Object.create(Object.defineProperty({}, session, { get() { reads++; return "stolen"; } }));
900
+ const profiles = [{ name: "stolen", agentId: "stolen-agent" }];
901
+ const tree = renderIdentityChip(file, { binds: inherited, profiles }, session);
902
+ expect(reads).toBe(0);
903
+ expect(identityElements(tree).some((el) => el.type === "a")).toBe(false);
904
+ const own = Object.fromEntries([[session, "stolen"]]);
905
+ const links = identityElements(renderIdentityChip(file, { binds: own, profiles }, session)).filter((el) => el.type === "a");
906
+ expect(links).toHaveLength(1);
907
+ expect(links[0].props).toMatchObject({ href: "https://agents-chat.com/chat/stolen-agent", target: "_blank", rel: "noopener noreferrer" });
908
+ }
909
+ }
910
+ });
911
+
912
+ test("identity host log creates a private file and stays within the 256KiB budget", () => {
913
+ const dir = mkdtempSync(join(tmpdir(), "dsh122-log-"));
914
+ const path = join(dir, ".dsh", "agentschat-identity-host.log");
915
+ mkdirSync(join(dir, ".dsh"));
916
+ try {
917
+ applyIdentityHost({}, { homeDir: dir });
918
+ expect(readFileSync(path, "utf8")).toMatch(/^\d{4}-.* host half applied\n$/);
919
+ if (process.platform !== "win32") expect(fs.statSync(path).mode & 0o777).toBe(0o600);
920
+ for (const size of [256 * 1024 - 1, 256 * 1024, 256 * 1024 + 1]) {
921
+ writeFileSync(path, "x".repeat(size));
922
+ applyIdentityHost({}, { homeDir: dir });
923
+ expect(fs.statSync(path).size).toBe(size);
924
+ }
925
+ writeFileSync(path, "x".repeat(256 * 1024 - 100));
926
+ applyIdentityHost({}, { homeDir: dir });
927
+ expect(fs.statSync(path).size).toBeGreaterThan(256 * 1024 - 100);
928
+ expect(fs.statSync(path).size).toBeLessThanOrEqual(256 * 1024);
929
+ } finally { rmSync(dir, { recursive: true, force: true }); }
930
+ });
931
+
932
+ test("identity host log refuses symlinked targets, parents, ancestors and non-regular targets", () => {
933
+ const dir = mkdtempSync(join(tmpdir(), "dsh122-links-"));
934
+ const victim = join(dir, "victim");
935
+ writeFileSync(victim, "untouched");
936
+ const home = join(dir, "home");
937
+ mkdirSync(join(home, ".dsh"), { recursive: true });
938
+ const log = join(home, ".dsh", "agentschat-identity-host.log");
939
+ try {
940
+ symlinkSync(victim, log);
941
+ applyIdentityHost({}, { homeDir: home });
942
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
943
+ fs.unlinkSync(log); mkdirSync(log);
944
+ applyIdentityHost({}, { homeDir: home });
945
+ expect(fs.statSync(log).isDirectory()).toBe(true);
946
+ rmSync(log, { recursive: true });
947
+ symlinkSync(home, join(dir, "alias"));
948
+ for (const root of [join(dir, "alias"), join(dir, "alias", "nested")]) applyIdentityHost({}, { homeDir: root });
949
+ expect(readdirSync(join(home, ".dsh"))).toEqual([]);
950
+ rmSync(join(home, ".dsh"), { recursive: true });
951
+ mkdirSync(join(dir, "outside")); symlinkSync(join(dir, "outside"), join(home, ".dsh"));
952
+ applyIdentityHost({}, { homeDir: home });
953
+ expect(readdirSync(join(dir, "outside"))).toEqual([]);
954
+ } finally { rmSync(dir, { recursive: true, force: true }); }
955
+ });
956
+
957
+ test("identity host log refuses a target swapped to a symlink between lstat and open", () => {
958
+ const dir = mkdtempSync(join(tmpdir(), "dsh122-open-"));
959
+ mkdirSync(join(dir, ".dsh"));
960
+ const log = join(dir, ".dsh", "agentschat-identity-host.log"), victim = join(dir, "victim");
961
+ writeFileSync(log, "log"); writeFileSync(victim, "untouched");
962
+ const original = fs.openSync;
963
+ const open = spyOn(fs, "openSync").mockImplementation(((path: any, ...args: any[]) => {
964
+ if (path === log) { fs.unlinkSync(log); symlinkSync(victim, log); }
965
+ return (original as any)(path, ...args);
966
+ }) as typeof fs.openSync);
967
+ try {
968
+ applyIdentityHost({}, { homeDir: dir });
969
+ expect(open).toHaveBeenCalled();
970
+ expect(readFileSync(victim, "utf8")).toBe("untouched");
971
+ } finally { open.mockRestore(); rmSync(dir, { recursive: true, force: true }); }
972
+ });
973
+
974
+ test("DSH config, registration and patch reject canonical cloud-metadata and link-local hosts", async () => {
975
+ const env = { AGENTCHAT_AGENT_ID: "bot", AGENTCHAT_TOKEN: "test-token" };
976
+ const request = spyOn(globalThis, "fetch").mockRejectedValue(new Error("unexpected fetch"));
977
+ const hosts = ["169.254.169.254", "169.254.0.0", "169.254.255.255", "metadata.google.internal", "METADATA.GOOG.", "[fe80::1]", "[febf:ffff::1]", "[FE90::1234]", "[::ffff:169.254.42.7]", "[::ffff:0:169.254.42.7]", "[0:0:0:0:0:ffff:a9fe:1]", "[::ffff:0:a9fe:ffff]", "0xa9fea9fe", "2852039166"];
978
+ try {
979
+ for (const host of hosts) {
980
+ expect(() => buildMcpAgentsChatArgs({ apiUrl: `https://${host}` })).toThrow(/Invalid/);
981
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_REST_URL: `https://${host}` })).toThrow(/Invalid/);
982
+ expect(() => loadDshConfig({ ...env, AGENTCHAT_WS_URL: `wss://${host}/ws` })).toThrow(/Invalid/);
983
+ await expect(registerOnly("bot", `https://${host}`)).rejects.toThrow(/Invalid/);
984
+ }
985
+ expect(request).not.toHaveBeenCalled();
986
+ for (const host of ["example.com", "metadata.goog.example.com", "169.253.255.255", "169.255.0.0", "[fe7f::1]", "[fec0::1]", "[::ffff:169.253.1.1]"]) {
987
+ expect(buildMcpAgentsChatArgs({ apiUrl: `https://${host}` })).toContain(`https://${host}`);
988
+ expect(loadDshConfig({ ...env, AGENTCHAT_WS_URL: `wss://${host}/ws` }).wsUrl).toBe(`wss://${host}/ws`);
989
+ }
990
+ for (const url of ["http://localhost:8787", "http://127.0.0.1:8787", "http://[::1]:8787"]) expect(buildMcpAgentsChatArgs({ apiUrl: url })).toContain(url);
991
+ } finally { request.mockRestore(); }
992
+ });
993
+
994
+ test("registration rejects non-object and own-proto JSON before writing and logs the cleaned name", async () => {
995
+ const dir = mkdtempSync(join(tmpdir(), "dsh122-register-"));
996
+ const path = join(dir, "identity.json");
997
+ let body = "";
998
+ const request = spyOn(globalThis, "fetch").mockImplementation((async () => new Response(body)) as unknown as typeof fetch);
999
+ const log = spyOn(console, "log").mockImplementation(() => {});
1000
+ try {
1001
+ for (body of ["null", "[]", "true", "3", '"text"', '{"__proto__":{},"agentId":"bot","token":"test-token"}']) {
1002
+ await expect(registerOnly("bot", "https://example.com", path)).rejects.toThrow(/registration response object/);
1003
+ expect(existsSync(path)).toBe(false);
1004
+ }
1005
+ body = '{"agentId":"bot","token":"test-token"}';
1006
+ await registerOnly("\r\n clean-bot \n", "https://example.com", path);
1007
+ expect(JSON.parse(String(request.mock.calls.at(-1)![1]!.body)).name).toBe("clean-bot");
1008
+ const logs = log.mock.calls.map((args) => args.join(" ")).join(" ");
1009
+ expect(logs).toContain("'clean-bot'");
1010
+ expect(logs).not.toMatch(/[\r\n]/);
1011
+ } finally { request.mockRestore(); log.mockRestore(); rmSync(dir, { recursive: true, force: true }); }
1012
+ });
1013
+
1014
+ test("all channel and send flags validate before connecting, including repeated and missing values", async () => {
1015
+ const connect = spyOn(MuseAgentChatClient.prototype, "connect").mockRejectedValue(new Error("unexpected connect"));
1016
+ try {
1017
+ for (const value of [undefined, "", " ", " bad", "bad id", "--listen", ".", "..", "a/b", "a\\b", "constructor", "Prototype", "__PrOtO__", "toString", "valueOf", "hasOwnProperty", "bad\n", "bad\x00", "bad\x7f"]) {
1018
+ const values = value === undefined ? [] : [value];
1019
+ for (const args of [["--listen", "--channel", ...values], ["--wake", "--channel", "good", "--channel", ...values], ["--send", ...values, "--text", "hello"]]) {
1020
+ await expect(main(args)).rejects.toThrow(/channel id/);
1021
+ }
1022
+ }
1023
+ expect(connect).not.toHaveBeenCalled();
1024
+ } finally { connect.mockRestore(); }
1025
+ });
1026
+
1027
+ async function withDshIdentity(fn: () => Promise<void>) {
1028
+ const names = ["AGENTCHAT_AGENT_ID", "AGENTCHAT_TOKEN", "AGENTCHAT_CHANNEL_ID", "AGENTSCHAT_CONFIG_DIR", "DSH_BIN", "DSH_WAKE_QUEUE"] as const;
1029
+ const previous = names.map((name) => process.env[name]);
1030
+ const dir = mkdtempSync(join(tmpdir(), "dsh122-env-"));
1031
+ process.env.AGENTCHAT_AGENT_ID = "dsh-test-bot"; process.env.AGENTCHAT_TOKEN = "test-token";
1032
+ delete process.env.AGENTCHAT_CHANNEL_ID;
1033
+ process.env.AGENTSCHAT_CONFIG_DIR = dir; process.env.DSH_WAKE_QUEUE = join(dir, "queue");
1034
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"] as const;
1035
+ const listeners = signals.map((signal) => new Set(process.listeners(signal)));
1036
+ try { await fn(); } finally {
1037
+ signals.forEach((signal, i) => { for (const listener of process.listeners(signal)) if (!listeners[i]!.has(listener)) process.removeListener(signal, listener); });
1038
+ names.forEach((name, i) => { if (previous[i] === undefined) delete process.env[name]; else process.env[name] = previous[i]; });
1039
+ rmSync(dir, { recursive: true, force: true });
1040
+ }
1041
+ }
1042
+
1043
+ test("listen logs redact controls/secrets while prompt headers strip controls and preserve message text", async () => {
1044
+ if (process.platform === "win32") return;
1045
+ await withDshIdentity(async () => {
1046
+ const bin = join(process.env.AGENTSCHAT_CONFIG_DIR!, "responder");
1047
+ writeFileSync(bin, '#!/bin/sh\nprintf "%s" "$3"\n', { mode: 0o700 });
1048
+ process.env.DSH_BIN = bin;
1049
+ let prompt: string | null = null;
1050
+ const message = { channel_id: "room\r\nforged\x00\x7f", sender_id: "sender\r\nforged\x01\x7f", content: "hello\nworld ac_12345678901234567890\x1b[31m", id: "id" };
1051
+ const start = spyOn(MuseBridge.prototype, "start").mockImplementation(async function (this: MuseBridge) {
1052
+ prompt = await (this as any).opts.responder({ message, context: "recent\ncontext" });
1053
+ });
1054
+ const closed = spyOn(MuseAgentChatClient.prototype, "waitUntilClosed").mockResolvedValue();
1055
+ const log = spyOn(console, "log").mockImplementation(() => {});
1056
+ try {
1057
+ await main(["--listen", "--channel", "room"]);
1058
+ expect(String(prompt)).toContain("channel roomforged.");
1059
+ expect(String(prompt)).toContain("Latest message from senderforged: hello\nworld");
1060
+ expect(String(prompt)).toContain(message.content);
1061
+ expect(String(prompt)).toContain("recent\ncontext");
1062
+ const inbound = log.mock.calls.map((args) => args.join(" ")).find((line) => line.startsWith("[inbound]"))!;
1063
+ expect(inbound).toContain("****");
1064
+ expect(inbound).not.toContain("ac_12345678901234567890");
1065
+ expect(inbound).not.toMatch(/[\x00-\x1f\x7f]/);
1066
+ } finally { start.mockRestore(); closed.mockRestore(); log.mockRestore(); }
1067
+ });
1068
+ });
1069
+
1070
+ test("wake logs scrub controls and secrets from inbound routing metadata", async () => {
1071
+ await withDshIdentity(async () => {
1072
+ let client: any;
1073
+ const connect = spyOn(MuseAgentChatClient.prototype, "connect").mockImplementation(async function (this: MuseAgentChatClient) { client = this; });
1074
+ const closed = spyOn(MuseAgentChatClient.prototype, "waitUntilClosed").mockImplementation(async () => {
1075
+ for (const handler of client.messageHandlers) handler({ channel_id: "dm:room\r\n\x1b", sender_id: "peer\r\nac_12345678901234567890\x7f", id: "msg\x00", content: "hello" });
1076
+ });
1077
+ const typing = spyOn(TypingHeartbeat.prototype, "start").mockImplementation(() => {});
1078
+ const joinChannel = spyOn(MuseAgentChatClient.prototype, "joinChannel").mockImplementation(() => {});
1079
+ const disconnect = spyOn(MuseAgentChatClient.prototype, "disconnect").mockImplementation(() => {});
1080
+ const log = spyOn(console, "log").mockImplementation(() => {});
1081
+ try {
1082
+ await main(["--wake", "--channel", "room"]);
1083
+ const lines = log.mock.calls.map((args) => args.join(" ")).filter((line) => line.startsWith("[dsh-wake]"));
1084
+ expect(lines.length).toBeGreaterThan(0);
1085
+ for (const line of lines) { expect(line).not.toMatch(/[\x00-\x1f\x7f]/); expect(line).not.toContain("ac_12345678901234567890"); }
1086
+ expect(lines.some((line) => line.includes("****"))).toBe(true);
1087
+ } finally { connect.mockRestore(); closed.mockRestore(); typing.mockRestore(); joinChannel.mockRestore(); disconnect.mockRestore(); log.mockRestore(); }
1088
+ });
1089
+ });
1090
+
1091
+ test("wake validates the fallback WebSocket URL when the primary identity config fails", async () => {
1092
+ const previous = process.env.AGENTCHAT_WS_URL;
1093
+ const connect = spyOn(MuseAgentChatClient.prototype, "connect").mockRejectedValue(new Error("unexpected connect"));
1094
+ try {
1095
+ await withDshIdentity(async () => {
1096
+ process.env.AGENTCHAT_WS_URL = "wss://[::ffff:0:169.254.169.254]/ws";
1097
+ await expect(main(["--wake"])).rejects.toThrow(/Invalid AgentChat WebSocket URL/);
1098
+ expect(connect).not.toHaveBeenCalled();
1099
+ });
1100
+ } finally {
1101
+ connect.mockRestore();
1102
+ if (previous === undefined) delete process.env.AGENTCHAT_WS_URL; else process.env.AGENTCHAT_WS_URL = previous;
1103
+ }
1104
+ });
1105
+
1106
+ test("configured default channels reject prototype keys before listen or wake connects", async () => {
1107
+ await withDshIdentity(async () => {
1108
+ const connect = spyOn(MuseAgentChatClient.prototype, "connect").mockRejectedValue(new Error("unexpected connect"));
1109
+ try {
1110
+ for (const channel of ["constructor", "__proto__", "toString", "bad/id", "bad\\id", "bad\x7fid"]) {
1111
+ process.env.AGENTCHAT_CHANNEL_ID = channel;
1112
+ await expect(main(["--listen"])).rejects.toThrow(/channel id/);
1113
+ await expect(main(["--wake"])).rejects.toThrow(/channel id/);
1114
+ }
1115
+ expect(connect).not.toHaveBeenCalled();
1116
+ } finally { connect.mockRestore(); }
1117
+ });
131
1118
  });