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
@@ -14,35 +14,282 @@
14
14
  *
15
15
  * So: the write reports success, and the dirty flag is cleared ONLY once it lands.
16
16
  */
17
- import { readFileSync, writeFileSync } from "fs";
17
+ import { randomBytes } from "crypto";
18
+ import {
19
+ chmodSync,
20
+ copyFileSync,
21
+ lstatSync,
22
+ readFileSync,
23
+ realpathSync,
24
+ renameSync,
25
+ type Stats,
26
+ unlinkSync,
27
+ writeFileSync,
28
+ } from "fs";
29
+ import { dirname, isAbsolute, join, parse, resolve, sep } from "path";
30
+ import { redactSecrets } from "./redact.ts";
18
31
 
19
32
  export type Warn = (message: string) => void;
20
33
 
34
+ export interface PersistCursorFsOps {
35
+ renameSync?: (oldPath: string, newPath: string) => void;
36
+ copyFileSync?: (src: string, dest: string) => void;
37
+ }
38
+
39
+ const MAX_CURSOR_BYTES = 4 * 1024 * 1024;
40
+ const MAX_CURSOR_ENTRIES = 50_000;
41
+ const RESERVED_PROTO_KEY = /^(?:__proto__|constructor|prototype)$/i;
42
+ let tmpCounter = 0;
43
+
44
+ function scrubDiag(value: unknown): string {
45
+ return redactSecrets(String(value ?? ""))
46
+ .replace(/\b(https?:\/\/)([^/\s@]*@)/gi, "$1[REDACTED]@")
47
+ .replace(/\b(?:Bearer|Basic)\s+[^\s"'<>\\]+/gi, "[REDACTED]")
48
+ .replace(
49
+ /(?:ac_|mcp_at_|mcp_rt_|mcp_|agent_key_|sk-|rk_live_|rk_test_|whsec_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|mr_|AIza|AKIA|ASIA)[A-Za-z0-9+/=._-]{8,}/g,
50
+ "[REDACTED]",
51
+ )
52
+ .replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ");
53
+ }
54
+
55
+ function isDarwinCanonicalRootLink(dir: string, st: Stats): boolean {
56
+ if (
57
+ process.platform !== "darwin" ||
58
+ (dir !== "/var" && dir !== "/tmp" && dir !== "/etc") ||
59
+ !st.isSymbolicLink()
60
+ ) {
61
+ return false;
62
+ }
63
+ try {
64
+ return (
65
+ realpathSync(dir) === `/private${dir}` &&
66
+ !lstatSync("/private").isSymbolicLink() &&
67
+ lstatSync("/private").isDirectory() &&
68
+ !lstatSync(`/private${dir}`).isSymbolicLink() &&
69
+ lstatSync(`/private${dir}`).isDirectory()
70
+ );
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ function hasSafeRawDotDotAncestors(rawDirPath: string): boolean {
77
+ const absRaw = isAbsolute(rawDirPath) ? rawDirPath : `${process.cwd()}${sep}${rawDirPath}`;
78
+ const root = parse(absRaw).root;
79
+ const segments = absRaw.slice(root.length).split(/[\\/]+/).filter(Boolean);
80
+ if (!segments.includes("..")) return true;
81
+ let cur = root;
82
+ for (const seg of segments) {
83
+ if (seg === ".") continue;
84
+ if (seg === "..") {
85
+ cur = dirname(cur);
86
+ continue;
87
+ }
88
+ const next = join(cur, seg);
89
+ try {
90
+ const st = lstatSync(next);
91
+ if (st.isSymbolicLink() && !isDarwinCanonicalRootLink(next, st)) {
92
+ return false;
93
+ }
94
+ } catch (err) {
95
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") return false;
96
+ }
97
+ cur = next;
98
+ }
99
+ return true;
100
+ }
101
+
102
+ function hasSafeAncestorDirs(targetFile: string): boolean {
103
+ if (typeof targetFile !== "string" || !targetFile || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(targetFile)) {
104
+ return false;
105
+ }
106
+ const rawParent = dirname(isAbsolute(targetFile) ? targetFile : `${process.cwd()}${sep}${targetFile}`);
107
+ if (!hasSafeRawDotDotAncestors(rawParent)) {
108
+ return false;
109
+ }
110
+ let dir = resolve(rawParent);
111
+ while (true) {
112
+ let st;
113
+ try {
114
+ st = lstatSync(dir);
115
+ } catch {
116
+ return false;
117
+ }
118
+ const isDarwinRootLink = isDarwinCanonicalRootLink(dir, st);
119
+ if (!isDarwinRootLink && (st.isSymbolicLink() || !st.isDirectory())) {
120
+ return false;
121
+ }
122
+ const parent = dirname(dir);
123
+ if (parent === dir) break;
124
+ dir = parent;
125
+ }
126
+ return true;
127
+ }
128
+
129
+ /**
130
+ * Sanitize an agent_id into a cross-platform safe filename slug (no `/`, `\`, `..`,
131
+ * or Windows NTFS invalid chars like `:`), while keeping standard `[A-Za-z0-9._-]+`
132
+ * agent IDs 100% unchanged so existing cursor files continue to match.
133
+ */
134
+ export function safeAgentCursorSlug(agentId: string): string {
135
+ const cleaned = String(agentId || "")
136
+ .trim()
137
+ .replace(/[^A-Za-z0-9._-]/g, "_")
138
+ .slice(0, 128);
139
+ if (!cleaned || cleaned === "." || cleaned === ".." || RESERVED_PROTO_KEY.test(cleaned)) return "_";
140
+ return cleaned;
141
+ }
142
+
143
+ export function cursorFileForAgent(configDir: string, agentId: string): string {
144
+ return join(configDir, `last-seen-msg-ts-${safeAgentCursorSlug(agentId)}.json`);
145
+ }
146
+
21
147
  /**
22
148
  * Read a persisted channel→timestamp map.
23
149
  *
24
150
  * A missing file is the normal first-run case and stays quiet. Anything else — corrupt
25
- * JSON, bad permissions — means we are silently resetting state we were supposed to
26
- * remember, and this runs ONCE at startup: there is no second attempt to notice it.
151
+ * JSON, non-object JSON, non-string values, bad permissions — means we are resetting state
152
+ * we were supposed to remember, and this runs ONCE at startup: warn loudly.
27
153
  */
28
154
  export function loadCursor(file: string, warn: Warn): Map<string, string> {
29
155
  try {
30
- return new Map(Object.entries(JSON.parse(readFileSync(file, "utf-8")) as Record<string, string>));
156
+ if (!hasSafeAncestorDirs(file)) {
157
+ let exists = false;
158
+ try {
159
+ lstatSync(file);
160
+ exists = true;
161
+ } catch (err) {
162
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") exists = true;
163
+ }
164
+ if (!exists) return new Map();
165
+ throw new Error("cursor parent path must be a real directory");
166
+ }
167
+ const st = lstatSync(file);
168
+ if (st.isSymbolicLink() || !st.isFile()) {
169
+ throw new Error("cursor path must be a regular file");
170
+ }
171
+ if (st.size > MAX_CURSOR_BYTES) {
172
+ throw new Error(`cursor file exceeds ${MAX_CURSOR_BYTES} byte limit`);
173
+ }
174
+ const parsed = JSON.parse(readFileSync(file, "utf-8")) as unknown;
175
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
176
+ throw new Error("cursor root must be a JSON object");
177
+ }
178
+ const entries: Array<[string, string]> = [];
179
+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
180
+ if (RESERVED_PROTO_KEY.test(k)) continue;
181
+ if (typeof v !== "string") {
182
+ throw new Error(`cursor value for ${scrubDiag(k)} must be a string`);
183
+ }
184
+ if (!k || k.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
185
+ throw new Error(`cursor entry for ${scrubDiag(k)} contains invalid characters or length`);
186
+ }
187
+ if (entries.length >= MAX_CURSOR_ENTRIES) {
188
+ throw new Error(`cursor entry count exceeds ${MAX_CURSOR_ENTRIES}`);
189
+ }
190
+ entries.push([k, v]);
191
+ }
192
+ return new Map(entries);
31
193
  } catch (e) {
32
194
  if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") {
33
- warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}\n`);
195
+ warn(`[agentchat] WARNING: could not read ${scrubDiag(file)} — resetting that state: ${scrubDiag(e)}\n`);
34
196
  }
35
197
  return new Map();
36
198
  }
37
199
  }
38
200
 
39
- /** Write the cursor to disk. Returns true iff it actually landed. Never throws. */
40
- export function persistCursor(file: string, cursor: Map<string, string>, warn: Warn): boolean {
201
+ /** Write the cursor to disk atomically (0600 tmp + rename, with Windows NTFS EPERM/EACCES fallback). Returns true iff it actually landed. Never throws. */
202
+ export function persistCursor(
203
+ file: string,
204
+ cursor: Map<string, string>,
205
+ warn: Warn,
206
+ fsOps?: PersistCursorFsOps,
207
+ ): boolean {
208
+ try {
209
+ const parentStat = lstatSync(dirname(file));
210
+ if (parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(file)) {
211
+ warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: parent is not a real directory\n`);
212
+ return false;
213
+ }
214
+ } catch (e) {
215
+ warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}\n`);
216
+ return false;
217
+ }
41
218
  try {
42
- writeFileSync(file, JSON.stringify(Object.fromEntries(cursor)));
219
+ const existing = lstatSync(file);
220
+ if (existing.isSymbolicLink() || !existing.isFile()) {
221
+ warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: target is not a regular file\n`);
222
+ return false;
223
+ }
224
+ } catch (e) {
225
+ if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") {
226
+ warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}\n`);
227
+ return false;
228
+ }
229
+ }
230
+ const validEntries: Array<[string, string]> = [];
231
+ for (const [k, v] of cursor) {
232
+ if (!k || k.length > 256 || RESERVED_PROTO_KEY.test(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || typeof v !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
233
+ continue;
234
+ }
235
+ validEntries.push([k, v]);
236
+ }
237
+ const boundedEntries =
238
+ validEntries.length > MAX_CURSOR_ENTRIES
239
+ ? validEntries.slice(validEntries.length - MAX_CURSOR_ENTRIES)
240
+ : validEntries;
241
+ const payloadObj: Record<string, string> = Object.create(null);
242
+ for (const [k, v] of boundedEntries) {
243
+ payloadObj[k] = v;
244
+ }
245
+ const renameFn = fsOps?.renameSync ?? renameSync;
246
+ const copyFn = fsOps?.copyFileSync ?? copyFileSync;
247
+ const tmp = `${file}.${process.pid}.${Date.now()}.${++tmpCounter}.${randomBytes(4).toString("hex")}.tmp`;
248
+ try {
249
+ writeFileSync(tmp, JSON.stringify(payloadObj), { mode: 0o600, flag: "wx" });
250
+ if (process.platform !== "win32") {
251
+ chmodSync(tmp, 0o600);
252
+ }
253
+ if (!hasSafeAncestorDirs(file)) {
254
+ throw new Error("parent is not a real directory");
255
+ }
256
+ const current = lstatSync(file, { throwIfNoEntry: false });
257
+ if (current && (current.isSymbolicLink() || !current.isFile())) {
258
+ throw new Error("target was replaced by a symlink or non-file");
259
+ }
260
+ try {
261
+ renameFn(tmp, file);
262
+ } catch (renameErr) {
263
+ const code = (renameErr as NodeJS.ErrnoException)?.code;
264
+ if (code === "EPERM" || code === "EACCES") {
265
+ if (!hasSafeAncestorDirs(file)) {
266
+ throw new Error("parent is not a real directory");
267
+ }
268
+ const recheck = lstatSync(file, { throwIfNoEntry: false });
269
+ if (recheck && (recheck.isSymbolicLink() || !recheck.isFile())) {
270
+ throw new Error("target was replaced by a symlink or non-file");
271
+ }
272
+ copyFn(tmp, file);
273
+ if (process.platform !== "win32") {
274
+ chmodSync(file, 0o600);
275
+ }
276
+ try {
277
+ unlinkSync(tmp);
278
+ } catch {
279
+ /* ignore cleanup error */
280
+ }
281
+ return true;
282
+ }
283
+ throw renameErr;
284
+ }
43
285
  return true;
44
286
  } catch (e) {
45
- warn(`[agentchat] WARNING: failed to persist read cursor to ${file}: ${e}\n`);
287
+ try {
288
+ unlinkSync(tmp);
289
+ } catch {
290
+ /* ignore cleanup error */
291
+ }
292
+ warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}\n`);
46
293
  return false;
47
294
  }
48
295
  }
package/src/reconnect.ts CHANGED
@@ -6,7 +6,103 @@
6
6
  * min() a long outage would push each successive reconnect unboundedly far out.
7
7
  * Extracted from ws.onclose so the cap and jitter bound can be unit-tested.
8
8
  */
9
+ const MAX_TIMEOUT_MS = 2_147_483_647;
10
+
11
+ function safeUnitRand(rand: () => number): number {
12
+ let r: number;
13
+ try {
14
+ r = rand();
15
+ } catch {
16
+ return 0;
17
+ }
18
+ if (!Number.isFinite(r) || r <= 0) return 0;
19
+ return r >= 1 ? 0.999999 : r;
20
+ }
21
+
9
22
  export function computeReconnectDelay(attempt: number, rand: () => number = Math.random): number {
10
- const jitter = rand() * 3000; // 0–3s
11
- return Math.min(attempt * 2, 30) * 1000 + jitter;
23
+ const safeAttempt =
24
+ typeof attempt === "number" && !Number.isNaN(attempt)
25
+ ? attempt === Infinity
26
+ ? 15
27
+ : Math.max(0, Math.min(attempt, 15))
28
+ : 0;
29
+ const jitter = safeUnitRand(rand) * 3000; // 0–3s
30
+ return Math.min(safeAttempt * 2, 30) * 1000 + jitter;
31
+ }
32
+
33
+ export function computePleaseReconnectDelay(jitterMs?: unknown, rand: () => number = Math.random): number {
34
+ const maxJitter =
35
+ typeof jitterMs === "number" && Number.isFinite(jitterMs) && jitterMs > 0
36
+ ? Math.min(Math.floor(jitterMs), 10_000)
37
+ : 2_000;
38
+ return 200 + Math.floor(safeUnitRand(rand) * maxJitter);
39
+ }
40
+
41
+ /**
42
+ * Compute jittered reconnect delay for both `please_reconnect` (`jitter_ms`)
43
+ * and `shard_moved` / admin fleet drain (`within_ms` or no field -> [200ms, 2200ms]),
44
+ * avoiding thundering-herd simultaneous reconnects across connected MCP clients.
45
+ */
46
+ export function resolveDrainReconnectDelay(
47
+ frame?: { jitter_ms?: unknown; within_ms?: unknown } | null,
48
+ rand: () => number = Math.random,
49
+ ): number {
50
+ const safeFrame =
51
+ frame && typeof frame === "object" && !Array.isArray(frame) && !Object.prototype.hasOwnProperty.call(frame, "__proto__")
52
+ ? frame
53
+ : null;
54
+ return computePleaseReconnectDelay(safeFrame?.jitter_ms ?? safeFrame?.within_ms, rand);
55
+ }
56
+
57
+ /**
58
+ * Compose an optional caller `AbortSignal` with a bounded `timeoutMs` timer
59
+ * (unref'd so background timers never hold the event loop open). Ensures
60
+ * passing `init.signal` into `apiFetch` never silently disables `timeoutMs`.
61
+ */
62
+ export function withTimeoutController(
63
+ parentSignal: AbortSignal | null | undefined,
64
+ timeoutMs: number,
65
+ ): { signal: AbortSignal; cleanup: () => void } {
66
+ const controller = new AbortController();
67
+ let timer: ReturnType<typeof setTimeout> | null = null;
68
+ const onParentAbort = () => {
69
+ if (timer) {
70
+ clearTimeout(timer);
71
+ timer = null;
72
+ }
73
+ if (!controller.signal.aborted) {
74
+ controller.abort(parentSignal?.reason);
75
+ }
76
+ };
77
+ if (parentSignal) {
78
+ if (parentSignal.aborted) {
79
+ controller.abort(parentSignal.reason);
80
+ return { signal: controller.signal, cleanup: () => {} };
81
+ }
82
+ parentSignal.addEventListener("abort", onParentAbort, { once: true });
83
+ }
84
+ const boundedTimeoutMs =
85
+ typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
86
+ ? Math.min(Math.floor(timeoutMs), MAX_TIMEOUT_MS)
87
+ : 0;
88
+ if (boundedTimeoutMs > 0) {
89
+ timer = setTimeout(() => {
90
+ timer = null;
91
+ if (parentSignal) parentSignal.removeEventListener("abort", onParentAbort);
92
+ const err = new Error(`HTTP request timed out after ${boundedTimeoutMs}ms`);
93
+ err.name = "TimeoutError";
94
+ controller.abort(err);
95
+ }, boundedTimeoutMs);
96
+ (timer as any)?.unref?.();
97
+ }
98
+ return {
99
+ signal: controller.signal,
100
+ cleanup: () => {
101
+ if (timer) {
102
+ clearTimeout(timer);
103
+ timer = null;
104
+ }
105
+ if (parentSignal) parentSignal.removeEventListener("abort", onParentAbort);
106
+ },
107
+ };
12
108
  }
package/src/redact.ts CHANGED
@@ -15,42 +15,61 @@ export interface RedactOptions {
15
15
  }
16
16
 
17
17
  export function redactSecrets(text: string, opts?: RedactOptions): string {
18
+ if (typeof text !== "string" || !text) return "";
18
19
  const step = opts?.preserveAcKeys
19
20
  ? text
20
21
  : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
21
- return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
22
+ return step
23
+ .replace(
24
+ /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|$)/g,
25
+ "***PRIVATE_KEY_REDACTED***",
26
+ )
27
+ .replace(/mcp_(?:at|rt|code)_[A-Za-z0-9_-]{16,}/g, "mcp_***REDACTED***")
28
+ .replace(/agent_key_[A-Za-z0-9_-]{12,}/g, "agent_key_***REDACTED***")
29
+ .replace(/whsec_[A-Za-z0-9_-]{12,}/g, "whsec_***REDACTED***")
30
+ .replace(/\bsk-(?:proj-|ant-|live-|test-)?[A-Za-z0-9_-]{16,}/g, "sk-***REDACTED***")
31
+ .replace(/\brk_(?:live|test)_[A-Za-z0-9]{12,}/g, "rk_***REDACTED***")
32
+ .replace(/\bgh[pousr]_[A-Za-z0-9_]{16,}/g, "gh_***REDACTED***")
33
+ .replace(/\bgithub_pat_[A-Za-z0-9_]{16,}/g, "github_pat_***REDACTED***")
34
+ .replace(/\bglpat-[A-Za-z0-9_-]{12,}/g, "glpat-***REDACTED***")
35
+ .replace(/\bxox[baprs]-[A-Za-z0-9-]{10,}/g, "xox-***REDACTED***")
36
+ .replace(/\bhf_[A-Za-z0-9]{20,}/g, "hf_***REDACTED***")
37
+ .replace(/\bnpm_[A-Za-z0-9]{20,}/g, "npm_***REDACTED***")
38
+ .replace(/\bAIza[0-9A-Za-z_-]{20,}/g, "AIza***REDACTED***")
39
+ .replace(/(?<![A-Za-z0-9])(?:AKIA|ASIA)[0-9A-Z]{16}(?![A-Za-z0-9])/g, "AKIA***REDACTED***")
40
+ .replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
22
41
  }
23
42
 
24
- const PHONE_PII_RE = /^\+?\d[\d\s()-]{5,}$/;
43
+ const PHONE_PII_RE = /^\+?\d[\d\s()-]{5,}[\d)]$/;
44
+ const PII_CONTROL_STRIP_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g;
45
+
46
+ function isPhoneShapedPii(s: string): boolean {
47
+ return PHONE_PII_RE.test(s) && s.replace(/\D/g, "").length >= 7;
48
+ }
25
49
 
26
50
  /**
27
51
  * True when an identifier looks like a human login email or phone number
28
52
  * rather than an agent handle. Matches the AgentsChat Server PII contract.
29
53
  */
30
54
  export function isHumanPiiHandle(rawId: unknown): boolean {
31
- const s = String(rawId ?? "").trim();
55
+ const s = String(rawId ?? "").replace(PII_CONTROL_STRIP_RE, "").trim();
32
56
  if (!s) return false;
33
57
  if (s.includes("@")) return true;
34
- if (PHONE_PII_RE.test(s)) return true;
58
+ if (isPhoneShapedPii(s)) return true;
35
59
  return false;
36
60
  }
37
61
 
38
62
  /**
39
- * Mask human login emails (`user@domain` -> `user:us***`) and phone numbers
40
- * (`+86 138...99` -> `user:phone_***99`) while preserving non-PII agent handles
41
- * in full (no 8/12-char truncation).
63
+ * Preserve human login emails (`swswordholy@gmail.com`) and non-PII agent handles
64
+ * in full so bots can recognize human teammates, while masking phone numbers
65
+ * (`+86 138...99` -> `user:phone_***99`), secrets, and control characters.
42
66
  */
43
67
  export function redactParticipantPii(rawId: unknown): string {
44
- const s = String(rawId ?? "").trim();
68
+ const s = redactSecrets(String(rawId ?? "").replace(PII_CONTROL_STRIP_RE, "").trim());
45
69
  if (!s) return "unknown";
46
- const atIdx = s.indexOf("@");
47
- if (atIdx >= 0) {
48
- const local = s.slice(0, atIdx).replace(/[^a-zA-Z0-9]/g, "");
49
- return `user:${(local.slice(0, 2) || "u").toLowerCase()}***`;
50
- }
51
- if (PHONE_PII_RE.test(s)) {
70
+ if (isPhoneShapedPii(s)) {
52
71
  const digits = s.replace(/\D/g, "");
53
72
  return `user:phone_***${digits.slice(-2) || "00"}`;
54
73
  }
55
- return s;
74
+ return s.slice(0, 128);
56
75
  }