agentschat-mcp 0.36.25 → 0.36.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +10 -10
  3. package/codex/README.md +4 -4
  4. package/codex/app-server.ts +101 -22
  5. package/codex/bots-config.ts +32 -11
  6. package/codex/bridge.ts +127 -28
  7. package/codex/config.ts +137 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +77 -12
  10. package/codex/loop-grants.ts +49 -11
  11. package/codex/manager.ts +108 -27
  12. package/codex/owner.ts +106 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +51 -11
  16. package/codex/thread-history.ts +87 -30
  17. package/codex/transport.ts +135 -22
  18. package/connector/README.md +1 -1
  19. package/connector/auth.ts +57 -5
  20. package/connector/backfill.ts +92 -10
  21. package/connector/descriptor.ts +27 -1
  22. package/connector/identities.ts +82 -14
  23. package/connector/ingest.ts +11 -2
  24. package/connector/normalize.ts +32 -12
  25. package/connector/run.ts +314 -67
  26. package/connector/server.ts +95 -26
  27. package/cordis.patch.yml +4 -2
  28. package/dist/codex-bots.js +437 -75
  29. package/dist/codex-bridge.js +2111 -582
  30. package/dist/connector.js +1300 -493
  31. package/dist/dsh.js +1789 -299
  32. package/dist/muse.js +967 -221
  33. package/dist/server.js +4410 -919
  34. package/dsh/README.md +1 -1
  35. package/dsh/client.js +7 -5
  36. package/dsh/identity-ui/client.js +7 -5
  37. package/dsh/identity-ui/index.js +43 -8
  38. package/dsh/inbound-bridge/index.js +677 -154
  39. package/dsh/src/cli.ts +430 -91
  40. package/dsh/src/patch.ts +295 -15
  41. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  42. package/dsh/tests/dsh.test.ts +1174 -3
  43. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  44. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  45. package/muse/src/bridge.ts +54 -13
  46. package/muse/src/cli.ts +226 -41
  47. package/muse/src/client.ts +249 -34
  48. package/muse/src/config.ts +128 -12
  49. package/muse/src/policy.ts +28 -8
  50. package/muse/src/types.ts +1 -0
  51. package/muse/src/typing.ts +18 -1
  52. package/muse/src/wake.ts +237 -35
  53. package/muse/tests/bridge.test.mjs +131 -0
  54. package/muse/tests/client.test.mjs +327 -0
  55. package/muse/tests/config.test.mjs +78 -1
  56. package/muse/tests/hardening.test.mjs +199 -0
  57. package/muse/tests/hardening126.test.mjs +292 -0
  58. package/muse/tests/policy.test.mjs +83 -1
  59. package/muse/tests/wake.test.mjs +134 -6
  60. package/package.json +3 -3
  61. package/scripts/ensure-grok-wakes.mjs +93 -8
  62. package/scripts/example-url-wake-receiver.mjs +254 -61
  63. package/scripts/grok-bind-register.sh +38 -8
  64. package/skills/onboarding.md +15 -15
  65. package/src/argcheck.ts +113 -33
  66. package/src/cli.mjs +100 -16
  67. package/src/dedup.ts +57 -8
  68. package/src/grok-bind.ts +182 -33
  69. package/src/heartbeat.ts +39 -11
  70. package/src/identity-guard.ts +93 -20
  71. package/src/identity.ts +67 -11
  72. package/src/mentions.ts +26 -5
  73. package/src/onboarding-status.ts +134 -11
  74. package/src/profile-selection.ts +299 -18
  75. package/src/profile-store.ts +248 -30
  76. package/src/read-cursor.ts +280 -9
  77. package/src/reconnect.ts +98 -2
  78. package/src/redact.ts +34 -15
  79. package/src/rest-cli.ts +713 -159
  80. package/src/server.ts +286 -94
  81. package/src/session-bind.ts +777 -134
  82. package/src/session-route.ts +183 -12
  83. package/src/team-lead-skill.ts +3 -0
  84. package/src/timestamps.ts +56 -23
  85. package/src/tool-annotations.ts +10 -1
  86. package/src/wake.ts +510 -91
@@ -2,8 +2,48 @@ import { randomUUID } from "node:crypto";
2
2
  import WebSocket from "ws";
3
3
  import type { BridgeConfig } from "./config.ts";
4
4
  import { HeartbeatMonitor } from "../src/heartbeat.ts";
5
+ import { resolveDrainReconnectDelay } from "../src/reconnect.ts";
5
6
  import { InboxSync } from "./inbox-sync.ts";
6
7
 
8
+ const TRANSPORT_FORBIDDEN_KEYS = new Set<string>([
9
+ "__proto__",
10
+ "prototype",
11
+ ...Object.getOwnPropertyNames(Object.prototype),
12
+ ...Object.getOwnPropertyNames(Object.prototype).map(k => k.toLowerCase()),
13
+ ]);
14
+ const cleanTransportLog = (value: string) => value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ");
15
+ function safeChannel(channel: unknown): channel is string {
16
+ return typeof channel === "string" && channel.trim().length > 0 && channel === channel.trim() && channel.length <= 128 &&
17
+ !/[.\/\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channel) && !/%(?:2e%2e|2f|5c|00)/i.test(channel) &&
18
+ !TRANSPORT_FORBIDDEN_KEYS.has(channel) && !TRANSPORT_FORBIDDEN_KEYS.has(channel.toLowerCase());
19
+ }
20
+ function requireChannel(channel: unknown): asserts channel is string {
21
+ if (!safeChannel(channel)) throw new Error("Invalid AgentsChat channel");
22
+ }
23
+ function apiUrl(path: string, base: string): URL {
24
+ const invalid = () => new Error("Invalid AgentsChat API path");
25
+ if (typeof path !== "string" || !path.startsWith("/") || path.startsWith("//") || /[\x00-\x1f\x7f-\x9f\u2028\u2029\\]/.test(path)) throw invalid();
26
+ try {
27
+ const pathname = path.split(/[?#]/, 1)[0]!;
28
+ if (/%25(?:2e|2f|5c|00)/i.test(pathname)) throw invalid();
29
+ const decoded = decodeURIComponent(pathname);
30
+ if ([pathname, decoded].some(value => value.split("/").includes("..")) || /[\x00-\x1f\x7f-\x9f\u2028\u2029\\]/.test(decoded)) throw invalid();
31
+ const origin = new URL(base).origin, resolved = new URL(path, base);
32
+ if (resolved.origin !== origin) throw invalid();
33
+ return resolved;
34
+ } catch { throw invalid(); }
35
+ }
36
+ function rawWsFrameBytes(raw: WebSocket.RawData): number {
37
+ if (Buffer.isBuffer(raw)) return raw.byteLength;
38
+ if (raw instanceof ArrayBuffer) return raw.byteLength;
39
+ if (Array.isArray(raw)) {
40
+ let total = 0;
41
+ for (const chunk of raw) total += chunk.byteLength;
42
+ return total;
43
+ }
44
+ return Buffer.byteLength(String(raw), "utf8");
45
+ }
46
+
7
47
  export class AgentsChatTransport {
8
48
  private socket?: WebSocket;
9
49
  private authenticated = false;
@@ -17,44 +57,84 @@ export class AgentsChatTransport {
17
57
  private syncTimer?: ReturnType<typeof setInterval>;
18
58
  constructor(private config: BridgeConfig, private receive: (m: unknown) => void, private log: (s: string) => void = console.error,
19
59
  recover?: (m: unknown) => boolean, private syncIntervalMs = 60_000) {
60
+ this.syncIntervalMs = Number.isFinite(syncIntervalMs) && syncIntervalMs > 0
61
+ ? Math.min(Math.floor(syncIntervalMs), 2_147_483_647) : 60_000;
20
62
  if (recover) this.inboxSync = new InboxSync(config.stateDir, path => this.api(path), recover,
21
63
  () => !this.closed && this.authenticated, log);
22
64
  }
23
65
  async api(path: string, body?: unknown) {
66
+ const resolved = apiUrl(path, this.config.apiUrl);
24
67
  let response: Response;
25
68
  try {
26
- response = await fetch(this.config.apiUrl + path, { method: body ? "POST" : "GET", redirect: "error",
69
+ response = await fetch(resolved, { method: body ? "POST" : "GET", redirect: "error",
27
70
  headers: { Authorization: `Bearer ${this.config.token}`, "Content-Type": "application/json" },
28
71
  ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(15_000) });
29
72
  } catch { throw new Error("AgentsChat request failed or timed out"); }
30
- if (!response.ok) throw new Error(`AgentsChat HTTP ${response.status}`);
31
- try { return await response.json(); } catch { throw new Error("Invalid AgentsChat response"); }
73
+ if (!response.ok) {
74
+ try { await response.body?.cancel?.(); } catch { /* Preserve the HTTP error. */ }
75
+ throw new Error(`AgentsChat HTTP ${response.status}`);
76
+ }
77
+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
78
+ try {
79
+ reader = response.body?.getReader();
80
+ if (!reader) throw new Error("Missing response body");
81
+ const decoder = new TextDecoder("utf-8", { fatal: true });
82
+ let bytes = 0, text = "";
83
+ while (true) {
84
+ const { done, value } = await reader.read();
85
+ if (done) break;
86
+ bytes += value.byteLength;
87
+ if (bytes > 4 * 1024 * 1024) {
88
+ try { await reader.cancel(); } catch { /* Preserve the invalid-response error. */ }
89
+ throw new Error("Response too large");
90
+ }
91
+ text += decoder.decode(value, { stream: true });
92
+ }
93
+ const value = JSON.parse(text + decoder.decode());
94
+ if (value && typeof value === "object" && Object.hasOwn(value, "__proto__")) throw new Error("Invalid JSON prototype key");
95
+ return value;
96
+ } catch { throw new Error("Invalid AgentsChat response"); }
97
+ finally { reader?.releaseLock(); }
32
98
  }
33
99
  setTyping(channel: string, active: boolean) {
100
+ requireChannel(channel);
34
101
  clearInterval(this.typing.get(channel)); this.typing.delete(channel);
35
102
  if (!active || this.closed) return;
103
+ if (this.typing.size >= 64) throw new Error("AgentsChat typing limit reached");
36
104
  const pulse = () => {
37
- if (this.authenticated && this.socket?.readyState === WebSocket.OPEN)
38
- this.socket.send(JSON.stringify({ type: "typing", channel_id: channel, sender_id: this.config.agentId, cross_pod: true }));
105
+ if (this.authenticated && this.socket?.readyState === WebSocket.OPEN) {
106
+ try { this.socket.send(JSON.stringify({ type: "typing", channel_id: channel, sender_id: this.config.agentId, cross_pod: true })); }
107
+ catch { /* The socket may close between the state check and send. */ }
108
+ }
39
109
  };
40
- pulse(); this.typing.set(channel, setInterval(pulse, 2000));
110
+ pulse();
111
+ const typingTimer = setInterval(pulse, 2000);
112
+ typingTimer.unref?.();
113
+ this.typing.set(channel, typingTimer);
114
+ }
115
+ private clearTyping() {
116
+ for (const timer of this.typing.values()) clearInterval(timer);
117
+ this.typing.clear();
41
118
  }
42
119
  private rejectPending() {
43
120
  for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error("AgentsChat acknowledgement unavailable")); }
44
121
  this.pending.clear();
45
122
  }
46
123
  async send(channel: string, text: string) {
124
+ requireChannel(channel);
47
125
  // Use the authenticated connection and wait for the server's delivery ACK.
48
126
  // Never fall back after an attempted send: an ACK may have been lost.
49
127
  if (this.authenticated && this.socket?.readyState === WebSocket.OPEN) {
128
+ if (this.pending.size >= 256) throw new Error("AgentsChat pending message limit reached");
50
129
  const id = randomUUID();
51
130
  await new Promise<void>((resolve, reject) => {
52
131
  const timer = setTimeout(() => { this.pending.delete(id); reject(new Error("AgentsChat acknowledgement timed out")); }, 15000);
132
+ timer.unref?.();
53
133
  this.pending.set(id, { resolve, reject, timer });
54
- this.socket!.send(JSON.stringify({ type: "message", id, channel_id: channel,
134
+ try { this.socket!.send(JSON.stringify({ type: "message", id, channel_id: channel,
55
135
  sender_id: this.config.agentId, sender_type: "agent", content_type: "text", content: text }), error => {
56
136
  if (error) { clearTimeout(timer); this.pending.delete(id); reject(new Error("AgentsChat socket send failed")); }
57
- });
137
+ }); } catch { clearTimeout(timer); this.pending.delete(id); reject(new Error("AgentsChat socket send failed")); }
58
138
  });
59
139
  return;
60
140
  }
@@ -64,12 +144,22 @@ export class AgentsChatTransport {
64
144
  }
65
145
  start() {
66
146
  if (this.closed) return;
147
+ clearTimeout(this.retry); this.retry = undefined;
148
+ clearInterval(this.syncTimer); this.syncTimer = undefined;
149
+ this.heartbeat?.stop(); this.heartbeat = undefined;
150
+ this.authenticated = false; this.clearTyping(); this.rejectPending();
151
+ const previous = this.socket; this.socket = undefined;
152
+ previous?.terminate();
67
153
  const socket = new WebSocket(this.config.wsUrl, { maxPayload: 1_048_576, handshakeTimeout: 15_000 });
68
154
  this.socket = socket;
69
155
  const current = () => !this.closed && this.socket === socket;
70
- const send = (value: unknown) => { if (current() && socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(value)); };
156
+ const send = (value: unknown) => {
157
+ if (current() && socket.readyState === WebSocket.OPEN) {
158
+ try { socket.send(JSON.stringify(value)); } catch { /* A concurrent close is handled below. */ }
159
+ }
160
+ };
71
161
  const join = (channel: string) => {
72
- if (!this.config.channels.length || this.config.channels.includes(channel)) {
162
+ if (safeChannel(channel) && (!this.config.channels.length || this.config.channels.includes(channel))) {
73
163
  this.inboxSync?.watch(channel);
74
164
  send({ type: "join_channel", channel_id: channel, agent_id: this.config.agentId });
75
165
  }
@@ -79,36 +169,59 @@ export class AgentsChatTransport {
79
169
  this.heartbeat.start();
80
170
  socket.on("open", () => send({ type: "auth", agent_id: this.config.agentId, token: this.config.token, capabilities: ["chat", "codex"] }));
81
171
  socket.on("message", raw => {
82
- if (!current()) return;
172
+ if (!current() || rawWsFrameBytes(raw) > 1_048_576) return;
83
173
  let data: any; try { data = JSON.parse(String(raw)); } catch { return; }
84
- this.heartbeat?.receivedPong();
174
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.hasOwn(data, "__proto__")) return;
175
+ if (data.type !== "auth_error") this.heartbeat?.receivedPong();
85
176
  if (data.type === "auth_ok") {
86
- this.authenticated = true; this.delay = 1000; this.log(`AgentsChat connected as ${this.config.agentId}`);
87
- if (this.inboxSync && !this.syncTimer) this.syncTimer = setInterval(() => { void this.inboxSync!.sync(); }, this.syncIntervalMs);
177
+ this.authenticated = true; this.delay = 1000; this.log(cleanTransportLog(`AgentsChat connected as ${this.config.agentId}`));
178
+ if (this.inboxSync && !this.syncTimer) {
179
+ this.syncTimer = setInterval(() => { void this.inboxSync!.sync(); }, this.syncIntervalMs);
180
+ this.syncTimer.unref?.();
181
+ }
88
182
  void this.api("/api/channels/mine").then((body: any) => {
89
183
  if (!current()) return;
90
184
  const channels = Array.isArray(body) ? body : body.channels;
91
185
  if (!Array.isArray(channels)) throw new Error("Invalid membership response");
92
- const ids = channels.map((c: any) => c.id ?? c.channel_id).filter((id: any) => typeof id === "string" &&
186
+ const ids = channels.map((c: any) => c?.id ?? c?.channel_id).filter((id: any) => safeChannel(id) &&
93
187
  (!this.config.channels.length || this.config.channels.includes(id)));
94
188
  this.inboxSync?.memberships(ids);
95
189
  for (const id of ids) join(id);
96
190
  void this.inboxSync?.sync();
97
191
  }).catch(() => { if (current()) { this.log("Membership sync failed; reconnecting"); socket.terminate(); } });
98
192
  } else if (data.type === "message_ack") {
99
- const id = data.message_id ?? data.id, pending = this.pending.get(id);
100
- if (pending) { clearTimeout(pending.timer); this.pending.delete(id); pending.resolve(); }
193
+ const id = data.message_id ?? data.id;
194
+ if (typeof id === "string") {
195
+ const pending = this.pending.get(id);
196
+ if (pending) { clearTimeout(pending.timer); this.pending.delete(id); pending.resolve(); }
197
+ }
101
198
  } else if (data.type === "channel_created" && typeof data.channel_id === "string") join(data.channel_id);
102
199
  else if (["message", "thread_reply"].includes(data.type)) this.receive(data);
103
- else if (data.type === "shard_moved" || data.type === "please_reconnect") socket.terminate();
104
- else if (data.type === "auth_error" || data.type === "error") this.log("AgentsChat returned an error; check account and channel permissions");
200
+ else if (data.type === "shard_moved" || data.type === "please_reconnect") {
201
+ this.delay = resolveDrainReconnectDelay(data);
202
+ socket.terminate();
203
+ } else if (data.type === "auth_error") {
204
+ this.log("AgentsChat authentication rejected; check profile token (backing off 30s)");
205
+ this.delay = 30_000;
206
+ socket.close();
207
+ } else if (data.type === "error") this.log("AgentsChat returned an error; check account and channel permissions");
105
208
  });
106
209
  socket.on("error", () => this.log("AgentsChat socket error"));
107
210
  socket.on("close", () => {
108
211
  if (!current()) return;
109
- this.authenticated = false; this.rejectPending(); this.heartbeat?.stop(); this.log("AgentsChat disconnected; reconnecting with history reconciliation");
110
- this.retry = setTimeout(() => this.start(), this.delay); this.delay = Math.min(this.delay * 2, 30_000);
212
+ clearInterval(this.syncTimer); this.syncTimer = undefined;
213
+ this.authenticated = false; this.clearTyping(); this.rejectPending(); this.heartbeat?.stop(); this.log("AgentsChat disconnected; reconnecting with history reconciliation");
214
+ this.retry = setTimeout(() => this.start(), this.delay);
215
+ this.retry.unref?.();
216
+ this.delay = Math.min(this.delay * 2, 30_000);
111
217
  });
112
218
  }
113
- stop() { for (const timer of this.typing.values()) clearInterval(timer); this.typing.clear(); this.closed = true; this.authenticated = false; this.rejectPending(); clearTimeout(this.retry); clearInterval(this.syncTimer); this.heartbeat?.stop(); this.socket?.terminate(); }
219
+ stop() {
220
+ this.closed = true; this.authenticated = false; this.clearTyping(); this.rejectPending();
221
+ clearTimeout(this.retry); this.retry = undefined;
222
+ clearInterval(this.syncTimer); this.syncTimer = undefined;
223
+ this.heartbeat?.stop(); this.heartbeat = undefined;
224
+ const socket = this.socket; this.socket = undefined;
225
+ socket?.terminate();
226
+ }
114
227
  }
@@ -74,7 +74,7 @@ Version 0.36.13 can run an established connection but still gates registration o
74
74
  Terms acceptance. A local checkout must contain the new workflow, and its rebuilt
75
75
  CLI guidance must confirm it before setup.
76
76
  Requires Node ≥22, Bun ≥1.0 for installing/building, and a configured Hermes
77
- v0.21.1 profile. In a reviewed `AgentsChatProtocol/mcp-plugin` checkout:
77
+ v0.21.1 profile. In a reviewed `AgentsChat/mcp-plugin` checkout:
78
78
 
79
79
  ```bash
80
80
  bun install
package/connector/auth.ts CHANGED
@@ -38,6 +38,8 @@ export function sign(payload: string, secret: string): string {
38
38
 
39
39
  /** Constant-time check that `sigHex` is a valid HMAC of `payload` under ANY of `secrets`. */
40
40
  export function verifySignature(payload: string, sigHex: string, secrets: readonly string[]): boolean {
41
+ if (typeof payload !== "string" || !Array.isArray(secrets)) return false;
42
+ if (typeof sigHex !== "string" || !/^[0-9a-f]{64}$/i.test(sigHex)) return false;
41
43
  let sigBuf: Buffer;
42
44
  try {
43
45
  sigBuf = Buffer.from(sigHex, "hex");
@@ -46,7 +48,14 @@ export function verifySignature(payload: string, sigHex: string, secrets: readon
46
48
  }
47
49
  if (sigBuf.length === 0) return false;
48
50
  for (const secret of secrets) {
49
- if (!secret) continue;
51
+ if (
52
+ typeof secret !== "string" ||
53
+ secret.length === 0 ||
54
+ secret.length > 8192 ||
55
+ DISALLOWED_TOKEN_PAYLOAD_CTRL_RE.test(secret)
56
+ ) {
57
+ continue;
58
+ }
50
59
  const expected = Buffer.from(hmacHex(payload, secret), "hex");
51
60
  if (expected.length !== sigBuf.length) continue; // no timing leak on length
52
61
  if (timingSafeEqual(sigBuf, expected)) return true;
@@ -58,8 +67,32 @@ export function verifySignature(payload: string, sigHex: string, secrets: readon
58
67
  * Build a signed, optionally-expiring token (mirrors auth.py `make_token`).
59
68
  * `base64url(f"{payload}:{exp}:{sig}")`, unpadded; `exp` is unix-seconds, 0 = never.
60
69
  */
70
+ const DISALLOWED_TOKEN_PAYLOAD_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
71
+ const PROTOTYPE_PAYLOAD_KEYS = new Set(["__proto__", "constructor", "prototype"]);
72
+ const STRICT_BASE64URL_RE = /^[A-Za-z0-9_-]+$/;
73
+
61
74
  export function makeToken(payload: string, secret: string, ttlSeconds = 0): string {
62
- const exp = ttlSeconds > 0 ? Math.floor(Date.now() / 1000) + ttlSeconds : 0;
75
+ if (
76
+ typeof payload !== "string" ||
77
+ payload.length > 8192 ||
78
+ DISALLOWED_TOKEN_PAYLOAD_CTRL_RE.test(payload) ||
79
+ PROTOTYPE_PAYLOAD_KEYS.has(payload.toLowerCase())
80
+ ) {
81
+ throw new Error("invalid token payload");
82
+ }
83
+ if (
84
+ typeof secret !== "string" ||
85
+ secret.length === 0 ||
86
+ secret.length > 8192 ||
87
+ DISALLOWED_TOKEN_PAYLOAD_CTRL_RE.test(secret)
88
+ ) {
89
+ throw new Error("invalid token secret");
90
+ }
91
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds < 0) {
92
+ throw new RangeError("ttlSeconds must be finite and non-negative");
93
+ }
94
+ const exp = ttlSeconds > 0 ? Math.ceil(Math.floor(Date.now() / 1000) + ttlSeconds) : 0;
95
+ if (!Number.isSafeInteger(exp)) throw new RangeError("expiration exceeds safe integer range");
63
96
  const signed = `${payload}:${exp}`;
64
97
  const sig = hmacHex(signed, secret);
65
98
  return Buffer.from(`${signed}:${sig}`, "utf8").toString("base64url");
@@ -80,18 +113,37 @@ export function makeUpgradeToken(
80
113
  * any signature not matching a secret in the verify list.
81
114
  */
82
115
  export function verifyToken(token: string, secrets: readonly string[]): string | null {
116
+ if (
117
+ typeof token !== "string" ||
118
+ token.length === 0 ||
119
+ token.length > 4096 ||
120
+ !STRICT_BASE64URL_RE.test(token) ||
121
+ !Array.isArray(secrets)
122
+ ) {
123
+ return null;
124
+ }
83
125
  let decoded: string;
84
126
  try {
85
- decoded = Buffer.from(token, "base64url").toString("utf8");
127
+ const rawBuf = Buffer.from(token, "base64url");
128
+ if (rawBuf.toString("base64url") !== token) return null;
129
+ decoded = rawBuf.toString("utf8");
86
130
  } catch {
87
131
  return null;
88
132
  }
89
133
  const parts = decoded.split(":");
90
134
  if (parts.length < 3) return null;
91
135
  const sig = parts[parts.length - 1];
92
- const exp = Number.parseInt(parts[parts.length - 2], 10);
93
- if (!Number.isFinite(exp)) return null;
136
+ const expText = parts[parts.length - 2];
137
+ if (!/^\d+$/.test(expText)) return null;
138
+ const exp = Number(expText);
139
+ if (!Number.isSafeInteger(exp) || String(exp) !== expText) return null;
94
140
  const payload = parts.slice(0, -2).join(":");
141
+ if (
142
+ DISALLOWED_TOKEN_PAYLOAD_CTRL_RE.test(payload) ||
143
+ PROTOTYPE_PAYLOAD_KEYS.has(payload.toLowerCase())
144
+ ) {
145
+ return null;
146
+ }
95
147
  if (exp !== 0 && Math.floor(Date.now() / 1000) > exp) return null;
96
148
  const signed = `${payload}:${exp}`;
97
149
  return verifySignature(signed, sig, secrets) ? payload : null;
@@ -6,32 +6,114 @@
6
6
  * Timestamp comparison uses the same padded-ISO cursor as the MCP path so
7
7
  * lexical `>` matches chronology (whole-second vs fractional).
8
8
  */
9
+ import { join } from "node:path";
9
10
  import { normalizeTimestampForCursor } from "../src/timestamps.ts";
10
11
  import { serverLoopTick, type AgentsChatMessage } from "./normalize.ts";
11
12
 
12
13
  export type BackfillMsg = AgentsChatMessage;
13
14
 
15
+ const CANONICAL_CURSOR_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/;
16
+ const RESERVED_CURSOR_BOT_NAMES = /^(?:__proto__|constructor|prototype|con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;
17
+
18
+ export function canonicalCursorTimestamp(raw: unknown): string | null {
19
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 128) return null;
20
+ const norm = normalizeTimestampForCursor(raw, "after");
21
+ return typeof norm === "string" && CANONICAL_CURSOR_TS_RE.test(norm) ? norm : null;
22
+ }
23
+
24
+ function isPlainMessageRecord(m: unknown): m is BackfillMsg {
25
+ return Boolean(
26
+ m &&
27
+ typeof m === "object" &&
28
+ !Array.isArray(m) &&
29
+ !Object.prototype.hasOwnProperty.call(m, "__proto__"),
30
+ );
31
+ }
32
+
33
+ function compareNormalizedTimestamps(aRaw: unknown, bRaw: unknown): number {
34
+ const aNorm = canonicalCursorTimestamp(aRaw) ?? "";
35
+ const bNorm = canonicalCursorTimestamp(bRaw) ?? "";
36
+ return aNorm < bNorm ? -1 : aNorm > bNorm ? 1 : 0;
37
+ }
38
+
14
39
  export function planBackfill(
15
40
  after: string | undefined,
16
41
  msgs: BackfillMsg[],
17
42
  agentId: string,
18
43
  ): { seed?: string; replay: BackfillMsg[] } {
19
44
  const list = Array.isArray(msgs) ? msgs : [];
20
- if (!after) {
21
- let newest = "";
45
+ const afterTs = canonicalCursorTimestamp(after);
46
+ if (!afterTs) {
47
+ let newestRaw = "";
48
+ let newestNorm = "";
22
49
  for (const m of list) {
23
- const t = String(m?.timestamp || "");
24
- if (t > newest) newest = t;
50
+ if (!isPlainMessageRecord(m) || typeof m.content !== "string" || m.content === "__typing__") continue;
51
+ const raw = typeof m.timestamp === "string" ? m.timestamp : "";
52
+ const norm = canonicalCursorTimestamp(raw);
53
+ if (!norm) continue;
54
+ if (norm > newestNorm) {
55
+ newestNorm = norm;
56
+ newestRaw = raw;
57
+ }
25
58
  }
26
- return newest ? { seed: newest, replay: [] } : { replay: [] };
59
+ return newestRaw ? { seed: newestRaw, replay: [] } : { replay: [] };
27
60
  }
28
- const afterTs = normalizeTimestampForCursor(after, "after") || after;
29
61
  const replay = list.filter((m) => {
30
- if (!m || m.content === "__typing__") return false;
62
+ if (!isPlainMessageRecord(m) || typeof m.content !== "string" || m.content === "__typing__") return false;
31
63
  if (m.sender_id === agentId && !serverLoopTick(m)) return false;
32
- const msgTs = normalizeTimestampForCursor(m.timestamp, "after");
33
- return typeof msgTs === "string" && msgTs > afterTs;
64
+ const msgTs = canonicalCursorTimestamp(m.timestamp);
65
+ return msgTs !== null && msgTs > afterTs;
34
66
  });
35
- replay.sort((a, b) => String(a.timestamp ?? "").localeCompare(String(b.timestamp ?? "")));
67
+ replay.sort((a, b) => compareNormalizedTimestamps(a.timestamp, b.timestamp));
36
68
  return { replay };
37
69
  }
70
+
71
+ /**
72
+ * Select up to 10 chronological channel context messages strictly after `sinceTs`
73
+ * (excluding typing placeholders and `excludeId`), using padded ISO comparison so
74
+ * whole-second (`...Z`) and fractional (`....500Z`) timestamps never invert order.
75
+ */
76
+ export function selectChannelContextMessages(
77
+ msgs: BackfillMsg[],
78
+ sinceTs?: string,
79
+ excludeId?: string,
80
+ ): BackfillMsg[] {
81
+ const list = Array.isArray(msgs) ? msgs : [];
82
+ const filtered = list
83
+ .filter(
84
+ (m) =>
85
+ isPlainMessageRecord(m) &&
86
+ typeof m.content === "string" &&
87
+ m.content.length > 0 &&
88
+ m.content !== "__typing__" &&
89
+ (!excludeId || m.id !== excludeId),
90
+ )
91
+ .sort((a, b) => compareNormalizedTimestamps(a.timestamp, b.timestamp));
92
+ if (!sinceTs) return filtered.slice(-10);
93
+ const normSince = canonicalCursorTimestamp(sinceTs);
94
+ if (!normSince) return [];
95
+ return filtered
96
+ .filter((m) => {
97
+ const norm = canonicalCursorTimestamp(m.timestamp);
98
+ return norm !== null && norm > normSince;
99
+ })
100
+ .slice(-10);
101
+ }
102
+
103
+ /**
104
+ * Sanitize `botId` when building per-bot cursor filenames so path separators,
105
+ * `..` traversal segments, or Windows-invalid filename characters cannot escape
106
+ * `cursorDir` or fail persistence while keeping standard agent IDs unchanged.
107
+ */
108
+ export function safeCursorBotFile(cursorDir: string, botId: string): string {
109
+ const raw = typeof botId === "string" && botId.trim() ? botId : "default";
110
+ const cleaned = raw
111
+ .replace(/[^A-Za-z0-9._-]/g, "_")
112
+ .replace(/\.+$/, "")
113
+ .replace(/\.{2,}/g, "_");
114
+ const safeId =
115
+ cleaned && !RESERVED_CURSOR_BOT_NAMES.test(cleaned)
116
+ ? cleaned.slice(0, 128)
117
+ : "default";
118
+ return join(cursorDir, `last-seen-msg-ts-${safeId}.json`);
119
+ }
@@ -36,7 +36,33 @@ export const SUPPORTED_OPS = ["send", "typing", "get_chat_info"] as const;
36
36
  * Build the descriptor the connector hands the gateway at handshake.
37
37
  * Single-tenant agentschat: narrow, honest capability set.
38
38
  */
39
+ const DESCRIPTOR_PROTO_KEYS = new Set([
40
+ "prototype",
41
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
42
+ ]);
43
+
39
44
  export function buildDescriptor(overrides: Partial<CapabilityDescriptor> = {}): CapabilityDescriptor {
45
+ if (
46
+ !overrides ||
47
+ typeof overrides !== "object" ||
48
+ Array.isArray(overrides) ||
49
+ Object.prototype.hasOwnProperty.call(overrides, "__proto__")
50
+ ) {
51
+ throw new Error("invalid descriptor overrides");
52
+ }
53
+ const keys = new Set<string>();
54
+ for (const key of Object.keys(overrides)) {
55
+ const trimmed = key.trim();
56
+ if (!trimmed || DESCRIPTOR_PROTO_KEYS.has(trimmed.toLowerCase()) ||
57
+ keys.has(trimmed)) throw new Error("invalid or duplicate descriptor override key");
58
+ keys.add(trimmed);
59
+ }
60
+ if ([...keys].some(key => !Object.hasOwn(overrides, key))) {
61
+ throw new Error("descriptor override keys must not contain surrounding whitespace");
62
+ }
63
+ const resolvedOps = Array.isArray(overrides.supported_ops)
64
+ ? [...overrides.supported_ops]
65
+ : [...SUPPORTED_OPS];
40
66
  return {
41
67
  contract_version: CONTRACT_VERSION,
42
68
  platform: "agentschat",
@@ -50,7 +76,7 @@ export function buildDescriptor(overrides: Partial<CapabilityDescriptor> = {}):
50
76
  emoji: "🤖",
51
77
  pii_safe: false,
52
78
  platform_hint: "AgentsChat named skills are reusable instructions. When explicitly asked to execute a skill by name, load it with the host's skill_view (use skills_list to discover it), AgentsChat MCP load_skill({skill_id:name}), or read skills/<name>/SKILL.md from the installed AgentsChat MCP package in this runtime. Report a missing loader or skill; do not pretend it ran. Keep skill text out of chat and keep replies in the originating chat.",
53
- supported_ops: [...SUPPORTED_OPS],
54
79
  ...overrides,
80
+ supported_ops: resolvedOps,
55
81
  };
56
82
  }
@@ -35,21 +35,83 @@ export interface Identity {
35
35
  profile?: string;
36
36
  }
37
37
 
38
- export class IdentityTable {
39
- private readonly byBot = new Map<string, Identity>();
38
+ const GATEWAY_PROTO_KEYS = new Set(["__proto__", "constructor", "prototype"]);
39
+ const IDENTITY_PROTO_KEYS = new Set([
40
+ "prototype",
41
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
42
+ ]);
43
+ const IDENTITY_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
44
+
45
+ export function validIdentityId(value: unknown): value is string {
46
+ return typeof value === "string" && value.length > 0 && value.length <= 128 && value !== "." && value !== ".." &&
47
+ !value.includes("..") && !/(?:%2f|%5c|%00|%2e%2e)/i.test(value) &&
48
+ !/[/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value) &&
49
+ !IDENTITY_PROTO_KEYS.has(value.toLowerCase());
50
+ }
40
51
 
41
- constructor(identities: Identity[]) {
42
- for (const id of identities) {
43
- if (this.byBot.has(id.botId)) {
44
- throw new Error(`duplicate identity botId "${id.botId}" — ambiguous routing`);
52
+ function validOptionalProfile(profile: unknown): boolean {
53
+ if (profile === undefined) return true;
54
+ if (typeof profile !== "string" || IDENTITY_CTRL_RE.test(profile)) return false;
55
+ const trimmed = profile.trim();
56
+ return (
57
+ trimmed.length > 0 &&
58
+ trimmed.length <= 128 &&
59
+ trimmed !== "." &&
60
+ !trimmed.includes("..") &&
61
+ !/[/\\]/.test(trimmed) &&
62
+ !/(?:%2f|%5c|%00|%2e%2e)/i.test(trimmed) &&
63
+ !IDENTITY_PROTO_KEYS.has(trimmed.toLowerCase())
64
+ );
65
+ }
66
+
67
+ /** Validate the whole candidate set before exposing any credentials or replacing state. */
68
+ function validateIdentities(identities: readonly Identity[], allowEmptyCredentials = false): void {
69
+ const bots = new Set<string>();
70
+ const agents = new Set<string>();
71
+ for (const id of identities) {
72
+ if (!id || !validIdentityId(id.botId) || !validIdentityId(id.agentId)) {
73
+ throw new Error("invalid identity botId or agentId");
74
+ }
75
+ if ([id.token, id.gatewayId, id.secret].some(value =>
76
+ typeof value !== "string" || (!value.trim() && !(allowEmptyCredentials && value === "")))) {
77
+ throw new Error("missing identity credentials");
78
+ }
79
+ if (!allowEmptyCredentials) {
80
+ if (
81
+ IDENTITY_CTRL_RE.test(id.gatewayId) ||
82
+ id.gatewayId.length > 256 ||
83
+ GATEWAY_PROTO_KEYS.has(id.gatewayId.trim().toLowerCase())
84
+ ) {
85
+ throw new Error("invalid identity gatewayId");
86
+ }
87
+ if (IDENTITY_CTRL_RE.test(id.token) || IDENTITY_CTRL_RE.test(id.secret)) {
88
+ throw new Error("invalid identity credentials");
45
89
  }
46
- this.byBot.set(id.botId, id);
47
90
  }
91
+ if (!validOptionalProfile(id.profile)) {
92
+ throw new Error("invalid identity profile");
93
+ }
94
+ if (bots.has(id.botId.trim()) || agents.has(id.agentId.trim())) {
95
+ throw new Error("duplicate identity botId or agentId — ambiguous routing");
96
+ }
97
+ bots.add(id.botId.trim());
98
+ agents.add(id.agentId.trim());
99
+ }
100
+ }
101
+
102
+ export class IdentityTable {
103
+ private readonly byBot = new Map<string, Identity>();
104
+
105
+ constructor(identities: Identity[], opts?: { allowEmptyCredentials?: boolean }) {
106
+ // Legacy embedding uses an empty-credential placeholder only at construction.
107
+ // Replacements and platform credential lookups always retain strict validation.
108
+ validateIdentities(identities, opts?.allowEmptyCredentials === true);
109
+ this.install(identities);
48
110
  }
49
111
 
50
112
  /** The identity fronting `botId`, or null when unregistered (fail closed). */
51
113
  forBot(botId: string): Identity | null {
52
- return this.byBot.get(botId) ?? null;
114
+ return validIdentityId(botId) ? this.byBot.get(botId) ?? null : null;
53
115
  }
54
116
 
55
117
  isSingle(): boolean {
@@ -69,12 +131,17 @@ export class IdentityTable {
69
131
  * duplicate botIds the same way the constructor does.
70
132
  */
71
133
  replace(identities: Identity[]): void {
134
+ validateIdentities(identities);
135
+ this.install(identities);
136
+ }
137
+
138
+ private install(identities: Identity[]): void {
72
139
  const next = new Map<string, Identity>();
73
140
  for (const id of identities) {
74
141
  if (next.has(id.botId)) {
75
142
  throw new Error(`duplicate identity botId "${id.botId}" — ambiguous routing`);
76
143
  }
77
- next.set(id.botId, id);
144
+ next.set(id.botId, Object.freeze({ ...id }));
78
145
  }
79
146
  this.byBot.clear();
80
147
  for (const [k, v] of next) this.byBot.set(k, v);
@@ -83,7 +150,8 @@ export class IdentityTable {
83
150
 
84
151
  /** Platform hooks must never substitute another identity's credentials. */
85
152
  export function requireIdentity(identities: readonly Identity[], botId: string): Identity {
86
- const id = identities.find(id => id.botId === botId);
153
+ validateIdentities(identities);
154
+ const id = validIdentityId(botId) ? identities.find(id => id.botId === botId) : undefined;
87
155
  if (!id) throw new Error(`unknown identity: ${botId}`);
88
156
  return id;
89
157
  }
@@ -121,7 +189,7 @@ function matchesExactMention(content: string, id: string): boolean {
121
189
 
122
190
  /** All exact addressed targets, once each, in identity-table order. */
123
191
  export function routeInboundTargets(table: IdentityTable, ctx: InboundContext): Identity[] {
124
- if (ctx.channel_id?.startsWith("dm-")) {
192
+ if (/^dm[-:]/i.test(ctx.channel_id ?? "")) {
125
193
  const owner = ctx.dmOwnerBotId ? table.forBot(ctx.dmOwnerBotId) : null;
126
194
  return owner ? [owner] : [];
127
195
  }
@@ -132,7 +200,7 @@ export function routeInboundTargets(table: IdentityTable, ctx: InboundContext):
132
200
 
133
201
  export function routeInbound(table: IdentityTable, ctx: InboundContext): Identity | null {
134
202
  // DM: route to the identity that owns the DM channel.
135
- if (ctx.channel_id?.startsWith("dm-")) {
203
+ if (/^dm[-:]/i.test(ctx.channel_id ?? "")) {
136
204
  return ctx.dmOwnerBotId ? table.forBot(ctx.dmOwnerBotId) : null;
137
205
  }
138
206
  // Group/channel: an explicit mentioned_ids annotation wins when present.
@@ -179,7 +247,7 @@ export function resolveOutbound(table: IdentityTable, botId: string): Identity |
179
247
  */
180
248
  export function hermesSourceProfile(id: Identity, frontedCount: number): string | undefined {
181
249
  const named = typeof id.profile === "string" ? id.profile.trim() : "";
182
- if (named) return named;
183
- if (frontedCount > 1) return id.botId;
250
+ if (named && validOptionalProfile(id.profile)) return named;
251
+ if (frontedCount > 1 && validIdentityId(id.botId)) return id.botId;
184
252
  return undefined;
185
253
  }