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
@@ -52,6 +52,9 @@ class MockServer {
52
52
  if (masked) for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4];
53
53
  buf = buf.subarray(off + maskLen + len);
54
54
  if (opcode === 8) {
55
+ try {
56
+ socket.write(Buffer.from([0x88, 0x00]));
57
+ } catch {}
55
58
  socket.end();
56
59
  return;
57
60
  }
@@ -176,3 +179,327 @@ test("client reconnects after a transient drop and re-authenticates", async () =
176
179
  await server.close();
177
180
  }
178
181
  });
182
+
183
+ test("auth_error rejects connect() immediately and stops reconnect loops", async () => {
184
+ const server = new MockServer();
185
+ const port = await server.listen();
186
+ server.onMessage = (msg, socket) => {
187
+ if (msg.type === "auth") {
188
+ server.send(socket, { type: "auth_error", error: "invalid_token" });
189
+ }
190
+ };
191
+ const client = new MuseAgentChatClient({
192
+ url: `ws://127.0.0.1:${port}`,
193
+ agentId: "muse-bot",
194
+ token: "bad-token",
195
+ initialReconnectDelayMs: 25,
196
+ maxReconnectDelayMs: 50,
197
+ });
198
+ try {
199
+ await assert.rejects(() => client.connect(), /invalid_token/);
200
+ await new Promise((r) => setTimeout(r, 90));
201
+ assert.equal(server.connections, 1);
202
+ } finally {
203
+ client.disconnect();
204
+ await server.close();
205
+ }
206
+ });
207
+
208
+ test("connectTimeoutMs rejects stalled auth handshakes cleanly", async () => {
209
+ const server = new MockServer();
210
+ const port = await server.listen();
211
+ server.onMessage = () => {
212
+ // Intentionally never reply to auth
213
+ };
214
+ const client = new MuseAgentChatClient({
215
+ url: `ws://127.0.0.1:${port}`,
216
+ agentId: "muse-bot",
217
+ token: "t",
218
+ connectTimeoutMs: 80,
219
+ initialReconnectDelayMs: 25,
220
+ });
221
+ try {
222
+ await assert.rejects(() => client.connect(), /timed out/);
223
+ await new Promise((r) => setTimeout(r, 80));
224
+ assert.equal(server.connections, 1);
225
+ } finally {
226
+ client.disconnect();
227
+ await server.close();
228
+ }
229
+ });
230
+
231
+ test("thread_reply delivery, shard_moved reconnect, and async onMessage error routing", async () => {
232
+ const server = new MockServer();
233
+ const port = await server.listen();
234
+ server.onMessage = (msg, socket) => {
235
+ if (msg.type === "auth") {
236
+ server.send(socket, { type: "auth_ok", agent_id: msg.agent_id, session_id: `s-${server.connections}` });
237
+ }
238
+ };
239
+ const inbound = [];
240
+ const errors = [];
241
+ let reconnected = 0;
242
+ const client = new MuseAgentChatClient({
243
+ url: `ws://127.0.0.1:${port}`,
244
+ agentId: "muse-bot",
245
+ token: "t",
246
+ heartbeatIntervalMs: 60_000,
247
+ initialReconnectDelayMs: 5_000,
248
+ maxReconnectDelayMs: 10_000,
249
+ onReconnect: () => {
250
+ reconnected += 1;
251
+ },
252
+ });
253
+ client.onError((err) => errors.push(err.message));
254
+ client.onMessage(async (m) => {
255
+ inbound.push(m);
256
+ if (m.content === "boom") throw new Error("handler_boom");
257
+ });
258
+ try {
259
+ await client.connect();
260
+ server.send(server.sockets[0], {
261
+ type: "thread_reply",
262
+ id: "tr1",
263
+ channel_id: "general",
264
+ parent_id: "root-99",
265
+ sender_id: "alice",
266
+ sender_type: "agent",
267
+ content: "boom",
268
+ content_type: "text",
269
+ timestamp: new Date().toISOString(),
270
+ });
271
+ await waitFor(() => inbound.length === 1 && errors.includes("handler_boom"), "thread_reply + async error");
272
+ assert.equal(inbound[0].thread_id, "root-99");
273
+
274
+ // shard_moved with within_ms:50 should bypass the 5_000ms exponential backoff ([200ms, 250ms))
275
+ server.send(server.sockets[0], { type: "shard_moved", within_ms: 50 });
276
+ await waitFor(() => reconnected >= 1 && client.session === "s-2", "fast shard_moved reconnect", 1500);
277
+ } finally {
278
+ client.disconnect();
279
+ await server.close();
280
+ }
281
+ });
282
+
283
+ test("reconnect auth timeout recovers from stalled half-open socket and re-joins channel_created rooms without duplicates", async () => {
284
+ const server = new MockServer();
285
+ const port = await server.listen();
286
+ server.onMessage = (msg, socket) => {
287
+ if (msg.type === "auth") {
288
+ // Connection #2 stalls without sending auth_ok; connections #1 and #3 succeed!
289
+ if (server.connections === 2) return;
290
+ server.send(socket, { type: "auth_ok", agent_id: msg.agent_id, session_id: `s-${server.connections}` });
291
+ }
292
+ };
293
+ const client = new MuseAgentChatClient({
294
+ url: `ws://127.0.0.1:${port}`,
295
+ agentId: "muse-bot",
296
+ token: "t",
297
+ connectTimeoutMs: 80,
298
+ heartbeatIntervalMs: 60_000,
299
+ initialReconnectDelayMs: 30,
300
+ maxReconnectDelayMs: 60,
301
+ onReconnect: () => {
302
+ client.joinChannel("static-room");
303
+ },
304
+ });
305
+ try {
306
+ await client.connect();
307
+ client.joinChannel("static-room");
308
+ // Runtime channel_created joins dm-runtime-1
309
+ server.send(server.sockets[0], { type: "channel_created", channel_id: "dm-runtime-1" });
310
+ await waitFor(
311
+ () => server.received.filter((m) => m.type === "join_channel" && m.channel_id === "dm-runtime-1").length === 1,
312
+ "initial channel_created join",
313
+ );
314
+
315
+ // Drop connection #1 -> connection #2 hangs on auth -> times out after 80ms -> connection #3 recovers!
316
+ server.received.length = 0;
317
+ server.sockets[0].destroy();
318
+ await waitFor(() => client.session === "s-3", "recovery onto connection #3 after stalled #2", 3000);
319
+ await waitFor(
320
+ () => server.received.filter((m) => m.type === "join_channel").length >= 2,
321
+ "rejoin both static and runtime channels",
322
+ );
323
+ const rejoined = server.received.filter((m) => m.type === "join_channel").map((m) => m.channel_id);
324
+ assert.deepEqual(rejoined, ["static-room", "dm-runtime-1"]);
325
+ } finally {
326
+ client.disconnect();
327
+ await server.close();
328
+ }
329
+ });
330
+
331
+ test("Campaign #97: MuseAgentChatClient ignores non-object/array frames, caps joinedChannels, and avoids backoff NaN overflow", async () => {
332
+ const server = new MockServer();
333
+ const port = await server.listen();
334
+ server.onMessage = (msg, socket) => {
335
+ if (msg.type === "auth") {
336
+ server.send(socket, { type: "auth_ok", agent_id: msg.agent_id, session_id: `s-${server.connections}` });
337
+ }
338
+ };
339
+ const debugEvents = [];
340
+ const client = new MuseAgentChatClient({
341
+ url: `ws://127.0.0.1:${port}`,
342
+ agentId: "muse-bot",
343
+ token: "t",
344
+ initialReconnectDelayMs: 0,
345
+ maxReconnectDelayMs: 50,
346
+ onDebug: (event, meta) => debugEvents.push({ event, meta }),
347
+ });
348
+ try {
349
+ await client.connect();
350
+ // Non-object / array frames must be ignored cleanly without throwing
351
+ client.handleMessage("null");
352
+ client.handleMessage("123");
353
+ client.handleMessage('["array","frame"]');
354
+ // Control-char / oversize channel_created must be rejected, and valid channels capped at 256
355
+ client.handleMessage(JSON.stringify({ type: "channel_created", channel_id: "bad\nroom" }));
356
+ for (let i = 0; i < 270; i++) {
357
+ client.joinChannel(`room-${i}`);
358
+ }
359
+ assert.equal(client.joinedChannels.size, 256);
360
+
361
+ // Simulate extreme reconnectAttempt=2000 with initialReconnectDelayMs=0 (previously 0 * Infinity === NaN!)
362
+ client.reconnectAttempt = 2000;
363
+ server.sockets[0].destroy();
364
+ await waitFor(() => debugEvents.some((e) => e.event === "reconnect:scheduled"), "reconnect scheduled");
365
+ const sched = debugEvents.find((e) => e.event === "reconnect:scheduled");
366
+ assert.equal(Number.isFinite(sched.meta.delayMs), true);
367
+ assert.equal(sched.meta.delayMs, 0);
368
+ } finally {
369
+ client.disconnect();
370
+ await server.close();
371
+ }
372
+ });
373
+
374
+ test("constructor requires credential-free wss or loopback ws URLs", () => {
375
+ const options = { agentId: "muse-bot", token: "t" };
376
+ for (const url of ["wss://agents-chat.com/ws", "ws://127.0.0.1:1", "ws://localhost/ws", "ws://LOCALHOST:99", "ws://[::1]:80/ws"]) {
377
+ assert.doesNotThrow(() => new MuseAgentChatClient({ ...options, url }));
378
+ }
379
+ for (const url of ["bad-url", "https://agents-chat.com", "file:///tmp/ws", "ws://agents-chat.com", "ws://localhost.evil", "ws://192.168.1.1", "wss://user:secret@agents-chat.com", "ws://user@localhost", "wss://:secret@localhost"]) {
380
+ assert.throws(() => new MuseAgentChatClient({ ...options, url }), /Muse.*URL|credentials/);
381
+ }
382
+ });
383
+
384
+ function fakeSockets(t) {
385
+ const sockets = [];
386
+ class FakeSocket {
387
+ static OPEN = 1;
388
+ readyState = 0;
389
+ sent = [];
390
+ closeCalls = 0;
391
+ constructor() { sockets.push(this); }
392
+ send(raw) {
393
+ if (this.sendError) throw new Error(this.sendError);
394
+ this.sent.push(JSON.parse(raw));
395
+ }
396
+ close() { this.closeCalls += 1; this.readyState = 3; this.onclose?.(); }
397
+ open() { this.readyState = 1; this.onopen?.(); }
398
+ frame(payload) { this.onmessage?.({ data: JSON.stringify(payload) }); }
399
+ }
400
+ const original = Object.getOwnPropertyDescriptor(globalThis, "WebSocket");
401
+ Object.defineProperty(globalThis, "WebSocket", { configurable: true, writable: true, value: FakeSocket });
402
+ t.after(() => Object.defineProperty(globalThis, "WebSocket", original));
403
+ const client = new MuseAgentChatClient({ url: "ws://localhost:1", agentId: "muse-bot", token: "t", connectTimeoutMs: 0 });
404
+ t.after(() => client.disconnect());
405
+ return { sockets, client };
406
+ }
407
+
408
+ test("repeated connect ignores every stale socket callback and heartbeat", async (t) => {
409
+ const { sockets, client } = fakeSockets(t);
410
+ const heartbeats = [];
411
+ t.mock.method(globalThis, "setInterval", (callback) => { heartbeats.push(callback); return { unref() {} }; });
412
+ t.mock.method(globalThis, "clearInterval", () => {});
413
+ const errors = [];
414
+ const inbound = [];
415
+ client.onError((err) => errors.push(err.message));
416
+ client.onMessage((m) => inbound.push(m));
417
+ const first = client.connect();
418
+ const old = sockets[0];
419
+ old.open(); old.frame({ type: "auth_ok", session_id: "old" });
420
+ await first;
421
+ const second = client.connect();
422
+ const current = sockets[1];
423
+ const before = old.sent.length;
424
+ old.onopen();
425
+ old.frame({ type: "auth_ok", session_id: "stale" });
426
+ old.frame({ type: "message", content: "stale" });
427
+ old.frame({ type: "auth_error", error: "stale error" });
428
+ old.onerror(); old.onclose(); heartbeats[0]();
429
+ assert.equal(old.sent.length, before);
430
+ assert.equal(client.session, null);
431
+ assert.equal(client.heartbeatTimer, null);
432
+ assert.equal(client.reconnectTimer, null);
433
+ assert.deepEqual(errors, []);
434
+ assert.deepEqual(inbound, []);
435
+ current.open(); current.frame({ type: "auth_ok", session_id: "current" });
436
+ await second;
437
+ const timer = client.heartbeatTimer;
438
+ old.onclose(); old.onerror(); old.frame({ type: "auth_ok", session_id: "stale-again" });
439
+ assert.equal(client.session, "current");
440
+ assert.equal(client.heartbeatTimer, timer);
441
+ heartbeats[1]();
442
+ assert.equal(current.sent.at(-1).type, "ping");
443
+ current.frame({ type: "message", content: "fresh" });
444
+ assert.equal(inbound[0].content, "fresh");
445
+ });
446
+
447
+ test("disconnect detaches socket before synchronous close and settles pending lifecycle", async (t) => {
448
+ const { sockets, client } = fakeSockets(t);
449
+ const errors = [];
450
+ client.onError((err) => errors.push(err.message));
451
+ const connecting = assert.rejects(client.connect(), /Disconnected before authentication/);
452
+ const closed = client.waitUntilClosed();
453
+ const old = sockets[0];
454
+ let detached = false;
455
+ old.close = () => {
456
+ detached = client.ws === null;
457
+ old.onclose();
458
+ old.onerror();
459
+ old.frame({ type: "auth_ok", session_id: "late" });
460
+ throw new Error("close failed");
461
+ };
462
+ assert.doesNotThrow(() => client.disconnect());
463
+ await connecting;
464
+ await closed;
465
+ assert.equal(detached, true);
466
+ assert.equal(client.ws, null);
467
+ assert.equal(client.session, null);
468
+ assert.equal(client.reconnectTimer, null);
469
+ assert.equal(client.lifecycleResolve, null);
470
+ assert.deepEqual(errors, []);
471
+ });
472
+
473
+ test("synchronous auth send failure rejects connect and reports through onError", async (t) => {
474
+ const { sockets, client } = fakeSockets(t);
475
+ const errors = [];
476
+ client.onError((err) => errors.push(err.message));
477
+ const rejected = assert.rejects(client.connect(), /auth send failed/);
478
+ sockets[0].sendError = "auth send failed";
479
+ assert.doesNotThrow(() => sockets[0].open());
480
+ await rejected;
481
+ assert.deepEqual(errors, ["auth send failed"]);
482
+ assert.equal(sockets[0].closeCalls, 1);
483
+ assert.equal(client.heartbeatTimer, null);
484
+ });
485
+
486
+ test("heartbeat catches synchronous send failure and closes for reconnect", async (t) => {
487
+ const { sockets, client } = fakeSockets(t);
488
+ let heartbeat;
489
+ t.mock.method(globalThis, "setInterval", (callback) => { heartbeat = callback; return { unref() {} }; });
490
+ t.mock.method(globalThis, "clearInterval", () => {});
491
+ const errors = [];
492
+ client.onError((err) => errors.push(err.message));
493
+ const connected = client.connect();
494
+ sockets[0].open(); sockets[0].frame({ type: "auth_ok", session_id: "s" });
495
+ await connected;
496
+ sockets[0].sendError = "ping send failed";
497
+ assert.doesNotThrow(() => heartbeat());
498
+ assert.deepEqual(errors, ["ping send failed"]);
499
+ assert.equal(sockets[0].closeCalls, 1);
500
+ assert.equal(client.session, null);
501
+ assert.notEqual(client.reconnectTimer, null);
502
+ client.disconnect();
503
+ assert.doesNotThrow(() => heartbeat());
504
+ assert.deepEqual(errors, ["ping send failed"]);
505
+ });
@@ -1,9 +1,10 @@
1
1
  import test from "node:test";
2
2
  import assert from "node:assert/strict";
3
- import { writeFileSync, mkdtempSync } from "node:fs";
3
+ import { writeFileSync, mkdtempSync, symlinkSync, readFileSync, statSync } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { join } from "node:path";
6
6
  import { loadConfig, redact } from "../src/config.ts";
7
+ import { arg, registerOnly } from "../src/cli.ts";
7
8
 
8
9
  test("redact never leaks a token", () => {
9
10
  assert.equal(redact("ac_1234567890"), "ac****90");
@@ -22,3 +23,79 @@ test("env wins over profile file, and missing identity throws", () => {
22
23
  assert.equal(fromProfile.agentId, "profile-bot");
23
24
  assert.throws(() => loadConfig({}, join(dir, "missing.json")), /Missing AgentsChat identity/);
24
25
  });
26
+
27
+ test("Campaign #97: loadConfig ignores symlinked profiles, rejects whitespace credentials, and blocks remote plaintext/credentialed URLs", () => {
28
+ const dir = mkdtempSync(join(tmpdir(), "muse-cfg97-"));
29
+ const realProfile = join(dir, "real.json");
30
+ const symProfile = join(dir, "sym.json");
31
+ writeFileSync(realProfile, JSON.stringify({ agentId: "sym-bot", token: "sym-token" }));
32
+ symlinkSync(realProfile, symProfile);
33
+
34
+ assert.throws(() => loadConfig({}, symProfile), /Missing AgentsChat identity/);
35
+ assert.throws(
36
+ () => loadConfig({ AGENTCHAT_AGENT_ID: " ", AGENTCHAT_TOKEN: "tok" }, join(dir, "none.json")),
37
+ /Missing AgentsChat identity/,
38
+ );
39
+ assert.throws(
40
+ () => loadConfig({ AGENTCHAT_AGENT_ID: "b", AGENTCHAT_TOKEN: "t", AGENTCHAT_WS_URL: "ws://agents-chat.com/ws" }),
41
+ /Remote Muse ws URL must use wss/,
42
+ );
43
+ assert.throws(
44
+ () => loadConfig({ AGENTCHAT_AGENT_ID: "b", AGENTCHAT_TOKEN: "t", AGENTCHAT_REST_URL: "https://u:p@agents-chat.com" }),
45
+ /Embedded credentials/,
46
+ );
47
+ const localOk = loadConfig({
48
+ AGENTCHAT_AGENT_ID: " b ",
49
+ AGENTCHAT_TOKEN: " t ",
50
+ AGENTCHAT_WS_URL: "ws://127.0.0.1:8080/ws",
51
+ AGENTCHAT_REST_URL: "http://localhost:8080",
52
+ });
53
+ assert.equal(localOk.agentId, "b");
54
+ assert.equal(localOk.token, "t");
55
+ });
56
+
57
+ test("Campaign #109 KR4: cli arg() ignores adjacent flags and registerOnly() rejects dangling symlinks, prototype agentIds, and control-char credentials", async () => {
58
+ assert.equal(arg("--name", ["--register-only", "--name", "--wake"]), undefined);
59
+ assert.equal(arg("--name", ["--register-only", "--name", "muse-bot"]), "muse-bot");
60
+
61
+ const dir = mkdtempSync(join(tmpdir(), "muse-cli109-"));
62
+ const victim = join(dir, "victim.json");
63
+ const danglingProfile = join(dir, "dangling-muse.json");
64
+ symlinkSync(victim, danglingProfile);
65
+
66
+ let networkCalled = false;
67
+ await assert.rejects(
68
+ () =>
69
+ registerOnly("muse-bot", "http://127.0.0.1:8080", danglingProfile, async () => {
70
+ networkCalled = true;
71
+ return new Response(JSON.stringify({ agentId: "bot-1", token: "ac_ok" }), { status: 200 });
72
+ }),
73
+ /symlink/,
74
+ );
75
+ assert.equal(networkCalled, false);
76
+
77
+ const cleanProfile = join(dir, "clean-muse.json");
78
+ await assert.rejects(
79
+ () =>
80
+ registerOnly("muse-bot", "http://127.0.0.1:8080", cleanProfile, async () => {
81
+ return new Response(JSON.stringify({ agentId: "constructor", token: "ac_ok" }), { status: 200 });
82
+ }),
83
+ /unsafe agent id or token/,
84
+ );
85
+ await assert.rejects(
86
+ () =>
87
+ registerOnly("muse-bot", "http://127.0.0.1:8080", cleanProfile, async () => {
88
+ return new Response(JSON.stringify({ agentId: "bot-1", token: "ac_bad\ntok" }), { status: 200 });
89
+ }),
90
+ /unsafe agent id or token/,
91
+ );
92
+
93
+ await registerOnly("muse-bot", "http://127.0.0.1:8080", cleanProfile, async () => {
94
+ return new Response(JSON.stringify({ agentId: "bot-109", token: "ac_clean_109" }), { status: 200 });
95
+ });
96
+ const saved = JSON.parse(readFileSync(cleanProfile, "utf8"));
97
+ assert.deepEqual(saved, { agentId: "bot-109", token: "ac_clean_109" });
98
+ if (process.platform !== "win32") {
99
+ assert.equal(statSync(cleanProfile).mode & 0o777, 0o600);
100
+ }
101
+ });
@@ -0,0 +1,199 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import fs from "node:fs";
4
+ import { syncBuiltinESMExports } from "node:module";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { shouldDispatch } from "../src/policy.ts";
8
+ import { buildMuseWakePrompt, fireWake, appendWakeQueue } from "../src/wake.ts";
9
+ import { loadConfig } from "../src/config.ts";
10
+ import * as config from "../src/config.ts";
11
+ import { registerOnly } from "../src/cli.ts";
12
+
13
+ const root = () => fs.mkdtempSync(join(tmpdir(), "muse119-"));
14
+ const identity = { AGENTCHAT_AGENT_ID: "bot", AGENTCHAT_TOKEN: "tok" };
15
+ const response = () => new Response('{"agentId":"bot","token":"tok"}');
16
+ const register = (file, fetchImpl = async () => response(), url = "http://127.0.0.1:8080") =>
17
+ registerOnly("muse", url, file, fetchImpl);
18
+ function hook(name, impl, run) {
19
+ const original = fs[name];
20
+ fs[name] = (...args) => impl(original, ...args);
21
+ syncBuiltinESMExports();
22
+ try { return run(); } finally { fs[name] = original; syncBuiltinESMExports(); }
23
+ }
24
+ async function hookAsync(name, impl, run) {
25
+ const original = fs[name];
26
+ fs[name] = (...args) => impl(original, ...args);
27
+ syncBuiltinESMExports();
28
+ try { return await run(); } finally { fs[name] = original; syncBuiltinESMExports(); }
29
+ }
30
+
31
+ test("119: unknown-kind DM colon parity preserves explicit group and self guards", () => {
32
+ for (const channel_id of ["dm:one", "DM:two", "dm-one", "DM-two"]) {
33
+ const msg = { channel_id, sender_id: "alice", content: "hello" };
34
+ assert.equal(shouldDispatch(msg, { agentId: "bot" }), true);
35
+ assert.equal(shouldDispatch(msg, { agentId: "bot", channelKind: "group" }), false);
36
+ assert.equal(shouldDispatch({ ...msg, sender_id: "bot" }, { agentId: "bot" }), false);
37
+ }
38
+ });
39
+
40
+ test("119: prompt headers remove every C0/DEL character and bound all three identifiers", () => {
41
+ const dirty = "x" + Array.from({length: 32}, (_, i) => String.fromCharCode(i)).join("") + "\x7f" + "z".repeat(200);
42
+ const clean = dirty.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 128);
43
+ const prompt = buildMuseWakePrompt({ type: "message", channel_id: dirty, sender_id: dirty, message_id: dirty });
44
+ assert.doesNotMatch(prompt, /[\x00-\x1f\x7f]/);
45
+ assert.equal(prompt.split(clean).length - 1, 4);
46
+ assert.ok(!prompt.includes("z".repeat(129)));
47
+ });
48
+
49
+ test("119: wake blocks credentials, zero port and remote metadata/private/link-local literals before transport", async () => {
50
+ let calls = 0;
51
+ for (const host of ["169.254.169.254", "169.254.1.2", "0xa9fea9fe", "metadata.google.internal", "metadata.goog.", "[::ffff:169.254.169.254]", "[::ffff:0:169.254.169.254]", "[fe80::1]", "[fc00::1]", "10.0.0.1", "172.16.1.1", "192.168.0.1", "example.com:0", "user:secret@example.com"]) {
52
+ await fireWake({}, { url: `http://${host}/wake`, fetchImpl: async () => { calls++; return response(); } });
53
+ }
54
+ assert.equal(calls, 0);
55
+ for (const url of ["http://localhost:9999/wake", "http://127.0.0.1:9999/wake", "http://[::1]:9999/wake", "https://example.com/wake"]) {
56
+ await fireWake({}, { url, fetchImpl: async (_, init) => { calls++; assert.equal(init.redirect, "error"); return response(); } });
57
+ }
58
+ assert.equal(calls, 4);
59
+ });
60
+
61
+ test("119: config and registration reject ambiguous endpoint input before any network or mkdir", async () => {
62
+ for (const suffix of [":0", "/?a=1", "/#hash", "/?", "/#", "/a\\b", '/a"b', "/<x>"]) {
63
+ const url = `https://example.com${suffix}`;
64
+ for (const [key, value] of [["AGENTCHAT_REST_URL", url], ["AGENTCHAT_WS_URL", url.replace("https:", "wss:")]]) {
65
+ assert.throws(() => loadConfig({ ...identity, [key]: value }, join(root(), "none")), /URL/);
66
+ }
67
+ const dir = root(); const file = join(dir, "new", "profile");
68
+ await assert.rejects(register(file, async () => { assert.fail("network reached"); }, url), /URL/);
69
+ assert.equal(fs.existsSync(join(dir, "new")), false);
70
+ }
71
+ for (const url of [" https://example.com", "https://example.com ", "https://exa\nmple.com"]) {
72
+ assert.throws(() => loadConfig({ ...identity, AGENTCHAT_REST_URL: url }), /URL/);
73
+ await assert.rejects(register(join(root(), "p"), async () => { assert.fail("network reached"); }, url), /URL/);
74
+ }
75
+ });
76
+
77
+ test("119: profile own proto and unsafe IDs cannot supply an identity", async () => {
78
+ const file = join(root(), "profile");
79
+ fs.writeFileSync(file, '{"agentId":"bot","token":"tok","__proto__":{}}');
80
+ assert.throws(() => loadConfig({}, file), /Missing/);
81
+ for (const agentId of [".", "..", "__PROTO__", "Constructor", "PROTOTYPE", "a/b", "a\\b", "a b", "a\tb", "a\x7fb"]) {
82
+ assert.throws(() => loadConfig({ ...identity, AGENTCHAT_AGENT_ID: agentId }, file), /identity/);
83
+ await assert.rejects(register(file, async () => new Response(JSON.stringify({ agentId, token: "tok" }))), /unsafe/);
84
+ }
85
+ for (const agentId of ["a", "bot-1", "bot_2", "bot.name", "机器人"]) {
86
+ assert.equal(loadConfig({ ...identity, AGENTCHAT_AGENT_ID: agentId }, file).agentId, agentId);
87
+ }
88
+ });
89
+
90
+ test("119: registration streams exact 1MiB response across split Unicode, rejects byte +1 and cancels", async () => {
91
+ const file = join(root(), "profile");
92
+ const encoder = new TextEncoder();
93
+ const base = JSON.stringify({ agentId: "bot", token: "tok", extra: "汉🙂" });
94
+ const bytes = encoder.encode(base + " ".repeat(1024 * 1024 - encoder.encode(base).length));
95
+ const split = encoder.encode(base.slice(0, base.indexOf("汉"))).length + 1;
96
+ let initSeen;
97
+ await register(file, async (_, init) => {
98
+ initSeen = init;
99
+ return new Response(new ReadableStream({ start(c) { c.enqueue(bytes.slice(0, split)); c.enqueue(bytes.slice(split)); c.close(); } }));
100
+ });
101
+ assert.equal(initSeen.redirect, "error");
102
+ assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")), { agentId: "bot", token: "tok" });
103
+ assert.equal(fs.statSync(file).mode & 0o777, 0o600);
104
+ for (const status of [200, 500]) {
105
+ let cancelled = false;
106
+ let sent = false;
107
+ await assert.rejects(register(file, async () => new Response(new ReadableStream({
108
+ pull(c) { if (sent) c.close(); else { sent = true; c.enqueue(new Uint8Array(1024 * 1024 + 1)); } },
109
+ cancel() { cancelled = true; return new Promise(() => {}); },
110
+ }, { highWaterMark: 0 }), {status, headers: { "content-length": "1" }})), /1MiB/);
111
+ assert.equal(cancelled, true);
112
+ }
113
+ });
114
+
115
+ test("119: malformed/truncated UTF8, nonobject and own-proto registration responses preserve profile", async () => {
116
+ const file = join(root(), "profile"); fs.writeFileSync(file, "original");
117
+ for (const body of [new Uint8Array([0xc3, 0x28]), new Uint8Array([0xe2, 0x82]), "null", "[]", '{"agentId":"bot","token":"tok","__proto__":{}}']) {
118
+ await assert.rejects(register(file, async () => new Response(body)));
119
+ assert.equal(fs.readFileSync(file, "utf8"), "original");
120
+ }
121
+ });
122
+
123
+ test("119: ancestor symlinks are rejected before recursive mkdir for queue and profile", async () => {
124
+ const dir = root(); const outside = root(); const link = join(dir, "link"); fs.symlinkSync(outside, link);
125
+ const file = join(link, "new", "nested", "file");
126
+ assert.throws(() => appendWakeQueue(file, { type: "message" }), /symlink/);
127
+ await assert.rejects(register(file, async () => { assert.fail("network reached"); }), /symlink/);
128
+ assert.equal(fs.existsSync(join(outside, "new")), false);
129
+ const traversal = `${link}/../muse119-traversal-${process.pid}/file`;
130
+ assert.throws(() => appendWakeQueue(traversal, { type: "message" }), /symlink/);
131
+ await assert.rejects(register(traversal, async () => { assert.fail("network reached"); }), /symlink/);
132
+ });
133
+
134
+ test("119: append rechecks target after reading and rotation rejects a replacement directory", () => {
135
+ const file = join(root(), "queue"); fs.writeFileSync(file, '{"message_id":"old"}\n');
136
+ hook("readFileSync", (original, path, ...args) => {
137
+ const data = original(path, ...args);
138
+ if (path === file) { fs.unlinkSync(file); fs.mkdirSync(file); }
139
+ return data;
140
+ }, () => assert.throws(() => appendWakeQueue(file, { type: "message", message_id: "new" }), /non-regular/));
141
+ fs.rmdirSync(file); fs.writeFileSync(file, '{"message_id":"old"}\n');
142
+ hook("writeFileSync", (original, path, ...args) => {
143
+ const result = original(path, ...args);
144
+ if (String(path).endsWith(".tmp")) { fs.unlinkSync(file); fs.mkdirSync(file); }
145
+ return result;
146
+ }, () => assert.throws(() => appendWakeQueue(file, { type: "message", message_id: "new" }, 1), /non-regular/));
147
+ assert.deepEqual(fs.readdirSync(join(file, "..")), ["queue"]);
148
+ });
149
+
150
+ test("119: registration rechecks target after temp write and removes only its temporary file", async () => {
151
+ const file = join(root(), "profile"); fs.writeFileSync(file, "old");
152
+ await hookAsync("writeFileSync", (original, path, ...args) => {
153
+ const result = original(path, ...args);
154
+ if (String(path).endsWith(".tmp")) { fs.unlinkSync(file); fs.mkdirSync(file); }
155
+ return result;
156
+ }, () => assert.rejects(register(file), /non-regular/));
157
+ assert.deepEqual(fs.readdirSync(join(file, "..")), ["profile"]);
158
+ });
159
+
160
+ test("119: exclusive private temp writes refuse preexisting symlinks in rotation and registration", async () => {
161
+ const dir = root(); const file = join(dir, "queue"); const victim = join(dir, "victim");
162
+ fs.writeFileSync(victim, "keep"); fs.writeFileSync(file, '{"message_id":"old"}\n');
163
+ const intercept = (original, path, data, opts) => {
164
+ if (String(path).endsWith(".tmp")) {
165
+ assert.equal(opts.flag, "wx"); assert.equal(opts.mode, 0o600); fs.symlinkSync(victim, path);
166
+ }
167
+ return original(path, data, opts);
168
+ };
169
+ hook("writeFileSync", intercept, () => assert.throws(() => appendWakeQueue(file, { type: "message" }, 1), /EEXIST/));
170
+ await hookAsync("writeFileSync", intercept, () => assert.rejects(register(join(dir, "profile")), /EEXIST/));
171
+ assert.equal(fs.readFileSync(victim, "utf8"), "keep");
172
+ assert.deepEqual(fs.readdirSync(dir).sort(), ["queue", "victim"]);
173
+ });
174
+
175
+ test("119: single-line rotation remains bounded and keeps a private regular queue", () => {
176
+ const file = join(root(), "queue");
177
+ for (let i = 0; i < 4; i++) appendWakeQueue(file, { type: "message", message_id: String(i) }, 1);
178
+ assert.deepEqual(fs.readFileSync(file, "utf8").trim().split("\n").map(JSON.parse), [{ type: "message", message_id: "3" }]);
179
+ assert.equal(fs.statSync(file).mode & 0o777, 0o600);
180
+ });
181
+
182
+
183
+ test("119: macOS allows only the three canonical system symlinks", () => {
184
+ const platform = Object.getOwnPropertyDescriptor(process, "platform");
185
+ Object.defineProperty(process, "platform", { value: "darwin" });
186
+ try {
187
+ for (const dir of ["/var", "/tmp", "/etc"]) {
188
+ const stat = path => ({ isSymbolicLink: () => path === dir, isDirectory: () => path !== dir });
189
+ hook("lstatSync", (_, path) => stat(path), () => {
190
+ hook("realpathSync", (_, path) => `/private${path}`, () => {
191
+ assert.doesNotThrow(() => config.assertSafeParentDirectories(`${dir}/nested/file`));
192
+ });
193
+ hook("realpathSync", () => "/attacker", () => {
194
+ assert.throws(() => config.assertSafeParentDirectories(`${dir}/nested/file`), /symlink/);
195
+ });
196
+ });
197
+ }
198
+ } finally { Object.defineProperty(process, "platform", platform); }
199
+ });