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
package/src/heartbeat.ts CHANGED
@@ -28,15 +28,22 @@ export class HeartbeatMonitor {
28
28
  /** Guard against overlapping reconnect calls */
29
29
  private reconnecting = false;
30
30
 
31
+ public readonly pingInterval: number;
32
+ public readonly pongTimeout: number;
33
+ public readonly connectTimeout: number;
34
+
31
35
  constructor(
32
36
  private deps: HeartbeatDeps,
33
37
  /** How often to send a ping (ms) */
34
- public readonly pingInterval: number = 30_000,
38
+ pingInterval: number = 30_000,
35
39
  /** Max time without a pong before we consider connection dead (ms) */
36
- public readonly pongTimeout: number = 90_000,
40
+ pongTimeout: number = 90_000,
37
41
  /** Max time to stay in CONNECTING before forcing retry (ms) */
38
- public readonly connectTimeout: number = 30_000,
42
+ connectTimeout: number = 30_000,
39
43
  ) {
44
+ this.pingInterval = Number.isFinite(pingInterval) && pingInterval > 0 ? Math.max(1, Math.min(Math.floor(pingInterval), 2_147_483_647)) : 30_000;
45
+ this.pongTimeout = Number.isFinite(pongTimeout) && pongTimeout > 0 ? Math.max(1, Math.min(Math.floor(pongTimeout), 2_147_483_647)) : 90_000;
46
+ this.connectTimeout = Number.isFinite(connectTimeout) && connectTimeout > 0 ? Math.max(1, Math.min(Math.floor(connectTimeout), 2_147_483_647)) : 30_000;
40
47
  this.lastPong = Date.now();
41
48
  }
42
49
 
@@ -54,6 +61,7 @@ export class HeartbeatMonitor {
54
61
  this.connectingSince = null;
55
62
  this.reconnecting = false;
56
63
  this.timer = setInterval(() => this.tick(), this.pingInterval);
64
+ (this.timer as unknown as { unref?: () => void })?.unref?.();
57
65
  }
58
66
 
59
67
  /** Stop the heartbeat timer */
@@ -71,24 +79,39 @@ export class HeartbeatMonitor {
71
79
 
72
80
  /** Exposed for testing — runs one heartbeat cycle */
73
81
  tick() {
74
- const state = this.deps.getReadyState();
82
+ let state: number;
83
+ try {
84
+ state = this.deps.getReadyState();
85
+ } catch {
86
+ this.connectingSince = null;
87
+ this.safeReconnect("readyState failed");
88
+ return;
89
+ }
75
90
 
91
+ const now = Date.now();
76
92
  if (state === WS_OPEN) {
77
93
  this.connectingSince = null;
78
- if (Date.now() - this.lastPong > this.pongTimeout) {
94
+ if (this.lastPong > now) {
95
+ this.lastPong = now;
96
+ }
97
+ if (now - this.lastPong > this.pongTimeout) {
79
98
  // No pong in too long — force reconnect
80
99
  this.safeReconnect("pong timeout");
81
100
  return;
82
101
  }
83
- this.deps.sendPing();
102
+ try {
103
+ this.deps.sendPing();
104
+ } catch {
105
+ this.safeReconnect("ping send failed");
106
+ }
84
107
  return;
85
108
  }
86
109
 
87
110
  if (state === WS_CONNECTING) {
88
- // Track how long we've been stuck in CONNECTING
89
- if (!this.connectingSince) {
90
- this.connectingSince = Date.now();
91
- } else if (Date.now() - this.connectingSince > this.connectTimeout) {
111
+ // Track how long we've been stuck in CONNECTING (recovering from backward NTP jumps)
112
+ if (this.connectingSince === null || this.connectingSince > now) {
113
+ this.connectingSince = now;
114
+ } else if (now - this.connectingSince > this.connectTimeout) {
92
115
  // Stuck in CONNECTING too long (server probably still down) — force retry
93
116
  this.connectingSince = null;
94
117
  this.safeReconnect("connect timeout");
@@ -104,6 +127,11 @@ export class HeartbeatMonitor {
104
127
  private safeReconnect(reason: string) {
105
128
  if (this.reconnecting) return; // already in progress
106
129
  this.reconnecting = true;
107
- this.deps.reconnect();
130
+ try {
131
+ this.deps.reconnect();
132
+ } catch {
133
+ // Never permanently wedge `reconnecting = true` or crash the interval loop if reconnect throws.
134
+ this.reconnecting = false;
135
+ }
108
136
  }
109
137
  }
@@ -53,28 +53,80 @@ export type GuardVerdict =
53
53
  | { kind: "warn"; message: string }
54
54
  | { kind: "gate"; message: string };
55
55
 
56
+ import { redactSecrets } from "./redact.ts";
57
+
56
58
  export const IDENTITY_GUARD_FILENAME = "identity-guard.json";
59
+ const MAX_GUARD_SELECTORS = 256;
57
60
 
58
61
  export function emptyGuardRecord(): IdentityGuardRecord {
59
62
  return { bySelector: {}, lastEffective: null };
60
63
  }
61
64
 
65
+ function isUnsafeSelectorKey(key: string): boolean {
66
+ const lower = key.toLowerCase();
67
+ return lower === "__proto__" || lower === "constructor" || lower === "prototype";
68
+ }
69
+
70
+ const GUARD_CONTROL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
71
+
72
+ function cleanDisplayToken(raw: unknown, maxLen = 128): string {
73
+ if (typeof raw !== "string") return "";
74
+ return redactSecrets(raw)
75
+ .replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]")
76
+ .replace(/\b(?:agent_key_|sk-|whsec_|gh[pousr]_|github_pat_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g, "[REDACTED]")
77
+ .replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, "")
78
+ .trim()
79
+ .slice(0, maxLen);
80
+ }
81
+
62
82
  /** Parse a persisted record; anything unreadable/malformed is an empty record (never blocks boot). */
63
83
  export function parseGuardRecord(text: string | null): IdentityGuardRecord {
64
- if (!text) return emptyGuardRecord();
84
+ if (!text || typeof text !== "string" || text.length > 262_144) return emptyGuardRecord();
65
85
  try {
66
86
  const raw = JSON.parse(text);
67
- if (!raw || typeof raw !== "object") return emptyGuardRecord();
87
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.prototype.hasOwnProperty.call(raw, "__proto__")) {
88
+ return emptyGuardRecord();
89
+ }
90
+ const bySelector: Record<string, string> = {};
91
+ if (
92
+ raw.bySelector &&
93
+ typeof raw.bySelector === "object" &&
94
+ !Array.isArray(raw.bySelector)
95
+ ) {
96
+ for (const [k, v] of Object.entries(raw.bySelector as Record<string, unknown>)) {
97
+ if (Object.keys(bySelector).length >= MAX_GUARD_SELECTORS) break;
98
+ if (GUARD_CONTROL_RE.test(k) || typeof v !== "string" || GUARD_CONTROL_RE.test(v)) continue;
99
+ const key = k.trim();
100
+ const val = v.trim();
101
+ if (!key || key.length > 128 || isUnsafeSelectorKey(key) || !val || val.length > 128) continue;
102
+ bySelector[key] = val;
103
+ }
104
+ }
105
+ const rawLast = raw.lastEffective;
106
+ const validRawLast =
107
+ rawLast &&
108
+ typeof rawLast === "object" &&
109
+ !Array.isArray(rawLast) &&
110
+ !Object.prototype.hasOwnProperty.call(rawLast, "__proto__");
111
+ const cleanAgentId =
112
+ validRawLast && typeof rawLast.agentId === "string"
113
+ ? cleanDisplayToken(rawLast.agentId, 128)
114
+ : "";
115
+ const cleanDecl =
116
+ validRawLast && rawLast.declaredName
117
+ ? cleanDisplayToken(String(rawLast.declaredName), 128)
118
+ : "";
68
119
  return {
69
- bySelector: raw.bySelector && typeof raw.bySelector === "object" ? { ...raw.bySelector } : {},
70
- lastEffective: raw.lastEffective && typeof raw.lastEffective.agentId === "string"
71
- ? {
72
- agentId: raw.lastEffective.agentId,
73
- source: String(raw.lastEffective.source ?? "unknown"),
74
- ...(raw.lastEffective.declaredName ? { declaredName: String(raw.lastEffective.declaredName) } : {}),
75
- ts: String(raw.lastEffective.ts ?? ""),
76
- }
77
- : null,
120
+ bySelector,
121
+ lastEffective:
122
+ cleanAgentId.length > 0 && !isUnsafeSelectorKey(cleanAgentId)
123
+ ? {
124
+ agentId: cleanAgentId,
125
+ source: cleanDisplayToken(String(rawLast.source ?? "unknown"), 64) || "unknown",
126
+ ...(cleanDecl ? { declaredName: cleanDecl } : {}),
127
+ ts: cleanDisplayToken(String(rawLast.ts ?? ""), 64),
128
+ }
129
+ : null,
78
130
  };
79
131
  } catch {
80
132
  return emptyGuardRecord();
@@ -91,27 +143,40 @@ export function decideIdentityGuard(prev: IdentityGuardRecord, current: GuardIde
91
143
  if (!last) return { kind: "ok" }; // first recorded boot — nothing to drift from
92
144
  if (last.agentId === current.agentId) return { kind: "ok" };
93
145
 
146
+ const safeLastId = cleanDisplayToken(last.agentId, 128);
147
+ const safeLastSrc = cleanDisplayToken(last.source, 64) || "unknown";
148
+ const safeLastDecl = last.declaredName ? cleanDisplayToken(last.declaredName, 128) : "";
149
+ const safeCurId = cleanDisplayToken(current.agentId, 128);
150
+
94
151
  if (current.source === "default") {
95
152
  // THE incident pattern: we used to run as X (possibly via an explicit
96
153
  // selector), and this boot silently landed on the default profile Y.
97
154
  return {
98
155
  kind: "gate",
99
156
  message:
100
- `IDENTITY CHANGED after reconnect/restart: previously trusted as "${last.agentId}" ` +
101
- `(via ${last.source}${last.declaredName ? ` "${last.declaredName}"` : ""}), but this boot resolved the DEFAULT profile ` +
102
- `"${current.agentId}". Silent fallback is how wrong-identity posts happen — write actions are REFUSED until identity is confirmed. ` +
157
+ `IDENTITY CHANGED after reconnect/restart: previously trusted as "${safeLastId}" ` +
158
+ `(via ${safeLastSrc}${safeLastDecl ? ` "${safeLastDecl}"` : ""}), but this boot resolved the DEFAULT profile ` +
159
+ `"${safeCurId}". Silent fallback is how wrong-identity posts happen — write actions are REFUSED until identity is confirmed. ` +
103
160
  `Run whoami to inspect and confirm, or relaunch with the intended profile selector.`,
104
161
  };
105
162
  }
106
163
 
107
- if (current.declaredName && prev.bySelector[current.declaredName] && prev.bySelector[current.declaredName] !== current.agentId) {
164
+ const prevSelectorAgent =
165
+ current.declaredName &&
166
+ !isUnsafeSelectorKey(current.declaredName) &&
167
+ Object.hasOwn(prev.bySelector, current.declaredName)
168
+ ? prev.bySelector[current.declaredName]
169
+ : undefined;
170
+ if (current.declaredName && typeof prevSelectorAgent === "string" && prevSelectorAgent !== current.agentId) {
108
171
  // Same selector, different identity: the profile file behind the selector
109
172
  // changed (likely an intentional edit). Loud, but not gated.
173
+ const safeCurDecl = cleanDisplayToken(current.declaredName, 128);
174
+ const safePrevSel = cleanDisplayToken(prevSelectorAgent, 128);
110
175
  return {
111
176
  kind: "warn",
112
177
  message:
113
- `identity for selector "${current.declaredName}" changed: was "${prev.bySelector[current.declaredName]}", ` +
114
- `now "${current.agentId}". If you edited the profile on purpose, ignore this; if not, investigate before posting.`,
178
+ `identity for selector "${safeCurDecl}" changed: was "${safePrevSel}", ` +
179
+ `now "${safeCurId}". If you edited the profile on purpose, ignore this; if not, investigate before posting.`,
115
180
  };
116
181
  }
117
182
 
@@ -134,7 +199,13 @@ export function advanceGuardRecord(
134
199
  ): IdentityGuardRecord {
135
200
  const next: IdentityGuardRecord = { bySelector: { ...prev.bySelector }, lastEffective: prev.lastEffective };
136
201
  if (!current.agentId) return next;
137
- if (current.declaredName) next.bySelector[current.declaredName] = current.agentId;
202
+ if (current.declaredName && !isUnsafeSelectorKey(current.declaredName)) {
203
+ if (!Object.hasOwn(next.bySelector, current.declaredName) && Object.keys(next.bySelector).length >= MAX_GUARD_SELECTORS) {
204
+ const oldestKey = Object.keys(next.bySelector)[0];
205
+ if (oldestKey !== undefined) delete next.bySelector[oldestKey];
206
+ }
207
+ next.bySelector[current.declaredName] = current.agentId;
208
+ }
138
209
  if (trusted) {
139
210
  next.lastEffective = {
140
211
  agentId: current.agentId,
@@ -176,9 +247,11 @@ export const EXPECT_PIN_EXEMPT_TOOLS = new Set(["whoami", "switch_profile", "con
176
247
  export function expectedAgentIdViolation(expected: string | null, liveAgentId: string): string | null {
177
248
  if (!expected) return null;
178
249
  if (liveAgentId === expected) return null;
250
+ const safeLive = cleanDisplayToken(liveAgentId, 128) || "(none)";
251
+ const safeExpected = cleanDisplayToken(expected, 128) || "(invalid-pin)";
179
252
  return (
180
- `IDENTITY PIN: this MCP process is "${liveAgentId || "(none)"}" but AGENTCHAT_EXPECT_AGENT_ID is "${expected}". ` +
253
+ `IDENTITY PIN: this MCP process is "${safeLive}" but AGENTCHAT_EXPECT_AGENT_ID is "${safeExpected}". ` +
181
254
  `Write tools are refused so nothing posts under the wrong identity. ` +
182
- `Call switch_profile with the profile for ${expected} (then whoami), or relaunch with the correct --profile / AGENTSCHAT_PROFILE.`
255
+ `Call switch_profile with the profile for ${safeExpected} (then whoami), or relaunch with the correct --profile / AGENTSCHAT_PROFILE.`
183
256
  );
184
257
  }
package/src/identity.ts CHANGED
@@ -59,14 +59,55 @@ export interface IdentityInputs {
59
59
  fallbackName: string;
60
60
  }
61
61
 
62
+ import { redactSecrets } from "./redact.ts";
63
+
64
+ const RESERVED_IDENTITY_IDS = new Set(["__proto__", "constructor", "prototype"]);
65
+ const MAX_DISPLAY_NAME_LEN = 128;
66
+ const MAX_AGENT_ID_LEN = 128;
67
+ const MAX_CAPABILITIES_LEN = 64;
68
+
69
+ const CONTROL_OR_SEP_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
70
+
71
+ function isValidDisplayName(raw: unknown): raw is string {
72
+ if (typeof raw !== "string" || CONTROL_OR_SEP_RE.test(raw)) return false;
73
+ const trimmed = raw.trim();
74
+ return trimmed.length > 0 && trimmed.length <= MAX_DISPLAY_NAME_LEN && !RESERVED_IDENTITY_IDS.has(trimmed.toLowerCase());
75
+ }
76
+
77
+ function isValidProfileAgentId(raw: unknown): raw is string {
78
+ if (typeof raw !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029/\\\s]/.test(raw) || /(?:%2e|%2f|%5c|%00)/i.test(raw)) return false;
79
+ const trimmed = raw.trim();
80
+ return (
81
+ trimmed.length > 0 &&
82
+ trimmed === raw &&
83
+ trimmed.length <= MAX_AGENT_ID_LEN &&
84
+ trimmed !== "." &&
85
+ !trimmed.includes("..") &&
86
+ !RESERVED_IDENTITY_IDS.has(trimmed.toLowerCase())
87
+ );
88
+ }
89
+
90
+ function sanitizeDiagnosticField(raw: string | undefined, fallback = "(unknown)"): string {
91
+ if (typeof raw !== "string") return fallback;
92
+ const cleaned = redactSecrets(raw)
93
+ .replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]")
94
+ .replace(/\b(?:agent_key_|sk-|whsec_|gh[pousr]_|github_pat_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g, "[REDACTED]")
95
+ .replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ")
96
+ .trim();
97
+ return cleaned.length > 0 ? cleaned.slice(0, 256) : fallback;
98
+ }
99
+
62
100
  export function decideIdentity(i: IdentityInputs): IdentityDecision {
63
101
  // An existing profile is authoritative — this is the overwhelmingly common path.
64
102
  if (i.profileExists) return { mode: "profile" };
65
103
 
104
+ const safeProfileFile = sanitizeDiagnosticField(i.profileFile, "(unknown-path)");
105
+
66
106
  // A selected existing identity cannot be replaced by credentials or registration
67
107
  // flags when its backing file is missing. --name is the separate creation path.
68
108
  if (i.source !== "default" && i.source !== "flag-name") {
69
- return { mode: "error", message: `no profile for "${i.declaredName ?? "(unknown)"}" at ${i.profileFile}. Refusing to auto-register or fall back to another identity; repair the selection or use --name <new-name> separately.` };
109
+ const safeDeclared = sanitizeDiagnosticField(i.declaredName, "(unknown)");
110
+ return { mode: "error", message: `no profile for "${safeDeclared}" at ${safeProfileFile}. Refusing to auto-register or fall back to another identity; repair the selection or use --name <new-name> separately.` };
70
111
  }
71
112
 
72
113
  // Credentials handed to us directly: we can authenticate, so there is nothing to
@@ -75,16 +116,26 @@ export function decideIdentity(i: IdentityInputs): IdentityDecision {
75
116
  if (i.hasToken) return { mode: "env-creds" };
76
117
 
77
118
  // Explicit opt-in to creating a new account.
78
- if (i.cliName) return { mode: "register", displayName: i.cliName };
79
- if (i.registerFlag) return { mode: "register", displayName: i.fallbackName };
119
+ if (i.cliName !== undefined) {
120
+ if (!isValidDisplayName(i.cliName)) {
121
+ return { mode: "error", message: `invalid --name value: display name must be 1..${MAX_DISPLAY_NAME_LEN} chars, non-reserved, and free of control characters.` };
122
+ }
123
+ return { mode: "register", displayName: i.cliName.trim() };
124
+ }
125
+ if (i.registerFlag) {
126
+ if (!isValidDisplayName(i.fallbackName)) {
127
+ return { mode: "error", message: `invalid fallback display name for --register.` };
128
+ }
129
+ return { mode: "register", displayName: i.fallbackName.trim() };
130
+ }
80
131
 
81
132
  // An identity was named but no profile backs it. Do NOT invent one.
82
133
  if (i.source !== "default") {
83
- const name = i.declaredName ?? i.cliName ?? "(unknown)";
134
+ const name = sanitizeDiagnosticField(i.declaredName ?? i.cliName, "(unknown)");
84
135
  return {
85
136
  mode: "error",
86
137
  message:
87
- `no profile for "${name}" at ${i.profileFile}.\n` +
138
+ `no profile for "${name}" at ${safeProfileFile}.\n` +
88
139
  ` Refusing to auto-register — that creates a real account under a name you did not choose.\n` +
89
140
  ` Use an existing profile: --profile <name> (or AGENTSCHAT_PROFILE=<name>)\n` +
90
141
  ` Register a NEW agent: --name <new-name> (or --register)\n` +
@@ -98,7 +149,7 @@ export function decideIdentity(i: IdentityInputs): IdentityDecision {
98
149
  reason:
99
150
  `no agent identity configured — running ANONYMOUS (tools are listed; any call needing auth will fail).\n` +
100
151
  ` Refusing to auto-register: it would create a real account and persist its\n` +
101
- ` credentials to the shared default profile (${i.profileFile}), which every later\n` +
152
+ ` credentials to the shared default profile (${safeProfileFile}), which every later\n` +
102
153
  ` identity-less session would then load as its own.\n` +
103
154
  ` To fix: --name <your-agent> register a new agent\n` +
104
155
  ` --profile <name> use an existing profile (or AGENTSCHAT_PROFILE=<name>)\n` +
@@ -108,13 +159,18 @@ export function decideIdentity(i: IdentityInputs): IdentityDecision {
108
159
 
109
160
  /** Validate effective credentials without including credential values in errors. */
110
161
  export function validateIdentityProfile(profile: any, file: string, allowDevToken = false): void {
111
- const nonempty = (value: unknown) => typeof value === "string" && value.trim().length > 0;
162
+ const cleanNonempty = (value: unknown): value is string =>
163
+ typeof value === "string" && value.trim().length > 0 && value.length <= 4096 && !CONTROL_OR_SEP_RE.test(value);
164
+ const safeFile = sanitizeDiagnosticField(file, "(unknown-path)");
112
165
  if (!profile || typeof profile !== "object" || Array.isArray(profile) ||
113
- !nonempty(profile.agent_id) || !nonempty(profile.token) ||
114
- (!allowDevToken && profile.token === "dev-token") ||
166
+ Object.prototype.hasOwnProperty.call(profile, "__proto__") ||
167
+ !isValidProfileAgentId(profile.agent_id) ||
168
+ !cleanNonempty(profile.token) ||
169
+ (!allowDevToken && profile.token.trim() === "dev-token") ||
115
170
  (profile.capabilities !== undefined && (!Array.isArray(profile.capabilities) ||
116
- !profile.capabilities.every(nonempty)))) {
117
- throw new Error(`Invalid identity profile at ${file}. Use --profile <valid-name>, or provide a paired --id / AGENTCHAT_AGENT_ID and --token / AGENTCHAT_TOKEN; token must not be empty or dev-token and capabilities must be a string array.`);
171
+ profile.capabilities.length > MAX_CAPABILITIES_LEN ||
172
+ !profile.capabilities.every((c: unknown) => cleanNonempty(c) && (c as string).length <= 64)))) {
173
+ throw new Error(`Invalid identity profile at ${safeFile}. Use --profile <valid-name>, or provide a paired --id / AGENTCHAT_AGENT_ID and --token / AGENTCHAT_TOKEN; token must not be empty or dev-token and capabilities must be a string array.`);
118
174
  }
119
175
  }
120
176
 
package/src/mentions.ts CHANGED
@@ -14,10 +14,31 @@
14
14
  * Extracted from server.ts so it can be unit-tested without loading the
15
15
  * side-effecting server entrypoint (which opens a WebSocket on import).
16
16
  */
17
+ const MAX_MENTION_ID_CHARS = 128;
18
+ const MAX_MENTION_CONTENT_CHARS = 100_000;
19
+ const PROTOTYPE_MENTION_IDS = new Set(["__proto__", "constructor", "prototype"]);
20
+
17
21
  export function matchesMention(content: string, agentId: string): boolean {
18
- if (!content || !agentId) return false;
19
- if (content.includes(`@${agentId}`)) return true;
20
- const idEsc = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21
- const displayMentionRe = new RegExp(`@[^(\\n]+\\(${idEsc}\\)`);
22
- return displayMentionRe.test(content);
22
+ if (typeof content !== "string" || typeof agentId !== "string") return false;
23
+ if (/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId)) return false;
24
+ const trimmedId = agentId.trim();
25
+ if (
26
+ !content ||
27
+ !trimmedId ||
28
+ trimmedId.length > MAX_MENTION_ID_CHARS ||
29
+ trimmedId === "." ||
30
+ trimmedId === ".." ||
31
+ /[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(trimmedId) ||
32
+ PROTOTYPE_MENTION_IDS.has(trimmedId.toLowerCase())
33
+ ) {
34
+ return false;
35
+ }
36
+ const hay = content.length > MAX_MENTION_CONTENT_CHARS ? content.slice(0, MAX_MENTION_CONTENT_CHARS) : content;
37
+ const idEsc = trimmedId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
38
+ const bareMentionRe = new RegExp(`(?<![A-Za-z0-9_])@${idEsc}(?![A-Za-z0-9_-]|\\.[A-Za-z0-9])`);
39
+ if (bareMentionRe.test(hay)) return true;
40
+ const displayMentionRe = new RegExp(
41
+ `(?<![A-Za-z0-9_])@[^\\s(@,:;<>"'\\x60\\n]+(?: [^\\s(@,:;<>"'\\x60\\n]+){0,4}\\(${idEsc}\\)`,
42
+ );
43
+ return displayMentionRe.test(hay);
23
44
  }
@@ -2,25 +2,148 @@ export interface OnboardingStatus {
2
2
  agent_id: string; claimed: boolean | null; authentication: "ok" | "failed" | "unknown";
3
3
  chat_url: string; claim_url: string; next_step: "join_public_chat" | "verify_reply" | "check_identity";
4
4
  }
5
+ const DEFAULT_PUBLIC_BASE = "https://agents-chat.com";
6
+
7
+ function isForbiddenMetadataOrLinkLocalHost(host: string): boolean {
8
+ if (
9
+ host === "metadata" ||
10
+ host === "instance-data" ||
11
+ host === "metadata.google.internal" ||
12
+ host.endsWith(".metadata.google.internal") ||
13
+ host === "metadata.goog" ||
14
+ host.endsWith(".metadata.goog") ||
15
+ host === "169.254.169.254" ||
16
+ host === "100.100.100.200" ||
17
+ host === "0.0.0.0"
18
+ ) {
19
+ return true;
20
+ }
21
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) {
22
+ const [a, b] = host.split(".").map(Number);
23
+ if (a === 0 || (a === 169 && b === 254)) return true;
24
+ }
25
+ if (host.startsWith("[") && host.endsWith("]")) {
26
+ const inner = host.slice(1, -1).toLowerCase();
27
+ if (
28
+ inner === "::" ||
29
+ inner === "0:0:0:0:0:0:0:0" ||
30
+ inner === "fd00:ec2::254" ||
31
+ /^fe[89ab][0-9a-f]*:/i.test(inner)
32
+ ) {
33
+ return true;
34
+ }
35
+ if (/^::ffff:(?:0:)?(?:0\.0\.0\.0|0:[0-9a-f]{1,4}$|169\.254\.|a9fe:|100\.100\.100\.200$|6464:64c8$)/i.test(inner)) {
36
+ return true;
37
+ }
38
+ }
39
+ return false;
40
+ }
41
+
42
+ function isSafeOnboardingBase(base: string): boolean {
43
+ try {
44
+ if (!base || base !== base.trim() || /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(base)) return false;
45
+ if (/:0(?:\/|$)/.test(base)) return false;
46
+ const parsed = new URL(base);
47
+ const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
48
+ if (!host || isForbiddenMetadataOrLinkLocalHost(host)) return false;
49
+ if (parsed.port !== "") {
50
+ const p = Number(parsed.port);
51
+ if (!Number.isInteger(p) || p < 1 || p > 65535) return false;
52
+ }
53
+ const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "[::1]" || host === "::1";
54
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && isLoopback)) return false;
55
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) return false;
56
+ return true;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ function isSafeOnboardingAgentId(id: string): boolean {
63
+ if (!id || id.length > 128 || /[\x00-\x1f\x7f-\x9f\u2028\u2029\s/\\]/.test(id)) return false;
64
+ if (id === "." || id.includes("..")) return false;
65
+ const lower = id.toLowerCase();
66
+ if (lower === "__proto__" || lower === "constructor" || lower === "prototype") return false;
67
+ return true;
68
+ }
69
+
70
+ const MAX_ONBOARDING_JSON_BYTES = 64 * 1024;
71
+
72
+ async function readBoundedJson(r: Response, maxBytes = MAX_ONBOARDING_JSON_BYTES): Promise<unknown> {
73
+ const rawContentLen = r.headers?.get?.("content-length");
74
+ if (rawContentLen !== null && rawContentLen !== undefined && rawContentLen.trim() !== "") {
75
+ const trimmedLen = rawContentLen.trim();
76
+ if (!/^\d+$/.test(trimmedLen) || Number(trimmedLen) > maxBytes) {
77
+ try { await r.body?.cancel?.(); } catch {}
78
+ throw new Error("onboarding response too large");
79
+ }
80
+ }
81
+ if (!r.body) {
82
+ const txt = await r.text();
83
+ if (Buffer.byteLength(txt, "utf8") > maxBytes) throw new Error("onboarding response too large");
84
+ return JSON.parse(txt);
85
+ }
86
+ const reader = r.body.getReader();
87
+ const chunks: Uint8Array[] = [];
88
+ let total = 0;
89
+ try {
90
+ while (true) {
91
+ const { done, value } = await reader.read();
92
+ if (done) break;
93
+ if (value) {
94
+ total += value.byteLength;
95
+ if (total > maxBytes) {
96
+ await reader.cancel().catch(() => {});
97
+ throw new Error("onboarding response too large");
98
+ }
99
+ chunks.push(value);
100
+ }
101
+ }
102
+ } finally {
103
+ try { reader.releaseLock(); } catch {}
104
+ }
105
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
106
+ }
107
+
5
108
  export async function getOnboardingStatus(base: string, agentId: string, token: string, request: (url: string, options: RequestInit) => Promise<Response> = fetch): Promise<OnboardingStatus> {
6
- const chat = `${base.replace(/\/$/, "")}/chat/${encodeURIComponent(agentId)}`;
7
- const result: OnboardingStatus = {agent_id: agentId, claimed: null, authentication: "unknown", chat_url: chat,
109
+ const cleanBase = typeof base === "string" ? base.trim().replace(/\/+$/, "") : "";
110
+ const rawAgentId = typeof agentId === "string" ? agentId.trim() : "";
111
+ const validAgent = isSafeOnboardingAgentId(rawAgentId);
112
+ const safeAgentId = validAgent ? rawAgentId : "";
113
+ const validBase = Boolean(cleanBase && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(cleanBase) && isSafeOnboardingBase(cleanBase));
114
+ const safeDisplayBase = validBase ? cleanBase : DEFAULT_PUBLIC_BASE;
115
+ const chat = `${safeDisplayBase}/chat/${encodeURIComponent(safeAgentId)}`;
116
+ const result: OnboardingStatus = {agent_id: safeAgentId, claimed: null, authentication: "unknown", chat_url: chat,
8
117
  claim_url: `${chat}?claim=1`, next_step: "check_identity"};
118
+ if (!validBase || !validAgent ||
119
+ typeof token !== "string" || !token.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) {
120
+ return result;
121
+ }
9
122
  try {
10
- const r = await request(`${base.replace(/\/$/, "")}/api/account/onboarding`, {
11
- headers: {Authorization: `Bearer ${token}`}, cache: "no-store", signal: AbortSignal.timeout(8000), redirect: "error",
123
+ const r = await request(`${cleanBase}/api/account/onboarding`, {
124
+ headers: {Authorization: `Bearer ${token.trim()}`}, cache: "no-store", signal: AbortSignal.timeout(8000), redirect: "error",
12
125
  });
13
- if (r.status === 401 || r.status === 403) { result.authentication = "failed"; return result; }
14
- if (!r.ok) return result;
15
- const data = await r.json() as any;
16
- if (data.agent_id !== agentId || typeof data.claimed !== "boolean") return result;
126
+ if (r.status === 401 || r.status === 403) {
127
+ try { await r.body?.cancel?.(); } catch {}
128
+ result.authentication = "failed";
129
+ return result;
130
+ }
131
+ if (!r.ok) {
132
+ try { await r.body?.cancel?.(); } catch {}
133
+ return result;
134
+ }
135
+ const data = await readBoundedJson(r) as any;
136
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.prototype.hasOwnProperty.call(data, "__proto__") || data.agent_id !== safeAgentId || typeof data.claimed !== "boolean") return result;
17
137
  result.authentication = "ok"; result.claimed = data.claimed;
18
138
  result.next_step = data.claimed ? "verify_reply" : "join_public_chat";
19
139
  } catch { /* Network/unsupported endpoint is unknown, never unclaimed. */ }
20
140
  return result;
21
141
  }
22
142
  export function claimSummary(status: OnboardingStatus): string {
23
- if (status.claimed === true) return "Claimed: yes — verify an actual message/reply in the authorized conversation before marking setup complete.";
24
- if (status.claimed === false) return `Claimed: NO — public group chat can proceed within the authorized scope and service limits. Claiming unlocks DMs, private channels and owner features: open ${status.claim_url} and enter the token from your private profile.`;
25
- return `Claimed: unknown — ownership could not be verified. Check the service and account; do not register a replacement. Claim entry: ${status.claim_url}`;
143
+ const safeClaimUrl = typeof status?.claim_url === "string"
144
+ ? status.claim_url.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, "").slice(0, 512)
145
+ : "";
146
+ if (status?.claimed === true) return "Claimed: yes — verify an actual message/reply in the authorized conversation before marking setup complete.";
147
+ if (status?.claimed === false) return `Claimed: NO — public group chat can proceed within the authorized scope and service limits. Claiming unlocks DMs, private channels and owner features: open ${safeClaimUrl} and enter the token from your private profile.`;
148
+ return `Claimed: unknown — ownership could not be verified. Check the service and account; do not register a replacement. Claim entry: ${safeClaimUrl}`;
26
149
  }