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.
- package/CHANGELOG.md +7 -0
- package/README.md +10 -10
- package/codex/README.md +4 -4
- package/codex/app-server.ts +101 -22
- package/codex/bots-config.ts +32 -11
- package/codex/bridge.ts +127 -28
- package/codex/config.ts +137 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +77 -12
- package/codex/loop-grants.ts +49 -11
- package/codex/manager.ts +108 -27
- package/codex/owner.ts +106 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +51 -11
- package/codex/thread-history.ts +87 -30
- package/codex/transport.ts +135 -22
- package/connector/README.md +1 -1
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/cordis.patch.yml +4 -2
- package/dist/codex-bots.js +437 -75
- package/dist/codex-bridge.js +2111 -582
- package/dist/connector.js +1300 -493
- package/dist/dsh.js +1789 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +4410 -919
- package/dsh/README.md +1 -1
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +677 -154
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +1174 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +3 -3
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/onboarding.md +15 -15
- package/src/argcheck.ts +113 -33
- package/src/cli.mjs +100 -16
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +182 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +299 -18
- package/src/profile-store.ts +248 -30
- package/src/read-cursor.ts +280 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +286 -94
- package/src/session-bind.ts +777 -134
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +10 -1
- package/src/wake.ts +510 -91
package/src/profile-store.ts
CHANGED
|
@@ -15,43 +15,208 @@
|
|
|
15
15
|
* bare `catch {}` — the key could sit world-readable with nothing said. Never swallow
|
|
16
16
|
* it, and verify the result instead of assuming it took.
|
|
17
17
|
*/
|
|
18
|
-
import {
|
|
19
|
-
|
|
18
|
+
import {
|
|
19
|
+
lstatSync,
|
|
20
|
+
realpathSync,
|
|
21
|
+
writeFileSync,
|
|
22
|
+
renameSync,
|
|
23
|
+
copyFileSync,
|
|
24
|
+
chmodSync,
|
|
25
|
+
unlinkSync,
|
|
26
|
+
readdirSync,
|
|
27
|
+
readFileSync,
|
|
28
|
+
type Stats,
|
|
29
|
+
} from "fs";
|
|
30
|
+
import { dirname, join, resolve } from "path";
|
|
31
|
+
import { redactSecrets } from "./redact.ts";
|
|
20
32
|
|
|
21
33
|
/** Where diagnostics go. Injectable so tests can assert on them. */
|
|
22
34
|
export type Warn = (message: string) => void;
|
|
23
35
|
|
|
24
36
|
const defaultWarn: Warn = (m) => process.stderr.write(m);
|
|
37
|
+
const MAX_PROFILE_JSON_BYTES = 64 * 1024;
|
|
38
|
+
const MAX_PROFILE_PATH_LEN = 4096;
|
|
39
|
+
const CONTROL_CHAR_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
40
|
+
const CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g;
|
|
41
|
+
const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
|
|
42
|
+
const RESERVED_PROTO_STEMS = new Set([
|
|
43
|
+
"__proto__",
|
|
44
|
+
"constructor",
|
|
45
|
+
"prototype",
|
|
46
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
|
|
47
|
+
]);
|
|
48
|
+
const DARWIN_SYSTEM_SYMLINKS = new Set(["/var", "/tmp", "/etc"]);
|
|
49
|
+
|
|
50
|
+
function sanitizeWarnPart(value: unknown): string {
|
|
51
|
+
return redactSecrets(String(value ?? ""))
|
|
52
|
+
.replace(/\b(https?:\/\/?)([^/\s@]*@)/gi, "$1[REDACTED]@")
|
|
53
|
+
.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]")
|
|
54
|
+
.replace(
|
|
55
|
+
/(?:ac_|mcp_at_|mcp_rt_|mcp_|agent_key_|sk-|whsec_|rk_(?:live|test)_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|mr_|AIza|(?:AKIA|ASIA))[A-Za-z0-9_+/=.-]{8,}/g,
|
|
56
|
+
"[REDACTED]",
|
|
57
|
+
)
|
|
58
|
+
.replace(CONTROL_CHAR_GLOBAL_RE, "?");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function safeLstat(target: string): Stats | undefined {
|
|
62
|
+
try {
|
|
63
|
+
return lstatSync(target);
|
|
64
|
+
} catch (err: any) {
|
|
65
|
+
if (err && err.code === "ENOENT") return undefined;
|
|
66
|
+
throw err;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function isAllowedDarwinSystemSymlink(dirPath: string): boolean {
|
|
71
|
+
if (process.platform !== "darwin" || !DARWIN_SYSTEM_SYMLINKS.has(dirPath)) return false;
|
|
72
|
+
try {
|
|
73
|
+
const resolved = realpathSync(dirPath);
|
|
74
|
+
if (resolved !== `/private${dirPath}`) return false;
|
|
75
|
+
const privSt = lstatSync("/private");
|
|
76
|
+
if (!privSt.isDirectory() || privSt.isSymbolicLink()) return false;
|
|
77
|
+
const realSt = lstatSync(resolved);
|
|
78
|
+
return realSt.isDirectory() && !realSt.isSymbolicLink();
|
|
79
|
+
} catch {
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function hasSafeRawDotDotAncestors(targetPath: string): boolean {
|
|
85
|
+
if (!targetPath.includes("..")) return true;
|
|
86
|
+
const rawParent = dirname(targetPath);
|
|
87
|
+
const parts = rawParent.split(/[\\/]+/);
|
|
88
|
+
let acc = rawParent.startsWith("/") ? "/" : /^[A-Za-z]:/.test(rawParent) ? parts[0] + "\\" : process.cwd();
|
|
89
|
+
const startIdx = rawParent.startsWith("/") ? 1 : /^[A-Za-z]:/.test(rawParent) ? 1 : 0;
|
|
90
|
+
for (let i = startIdx; i < parts.length; i++) {
|
|
91
|
+
const seg = parts[i];
|
|
92
|
+
if (!seg || seg === ".") continue;
|
|
93
|
+
acc = seg === ".." ? dirname(acc) : join(acc, seg);
|
|
94
|
+
const st = safeLstat(acc);
|
|
95
|
+
if (st) {
|
|
96
|
+
if (st.isSymbolicLink()) {
|
|
97
|
+
if (!isAllowedDarwinSystemSymlink(acc)) return false;
|
|
98
|
+
} else if (!st.isDirectory()) {
|
|
99
|
+
return false;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function hasSafeAncestorDirs(targetPath: string): boolean {
|
|
107
|
+
if (!hasSafeRawDotDotAncestors(targetPath)) return false;
|
|
108
|
+
let cur = dirname(resolve(targetPath));
|
|
109
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
110
|
+
const st = safeLstat(cur);
|
|
111
|
+
if (st) {
|
|
112
|
+
if (st.isSymbolicLink()) {
|
|
113
|
+
if (!isAllowedDarwinSystemSymlink(cur)) return false;
|
|
114
|
+
} else if (!st.isDirectory()) {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
const parent = dirname(cur);
|
|
119
|
+
if (parent === cur) break;
|
|
120
|
+
cur = parent;
|
|
121
|
+
}
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
25
124
|
|
|
26
125
|
export function safeWriteProfile(path: string, data: unknown, warn: Warn = defaultWarn): void {
|
|
126
|
+
if (typeof path !== "string" || !path || path.length > MAX_PROFILE_PATH_LEN || path.includes("\x00")) {
|
|
127
|
+
throw new Error(`Refusing to write profile into invalid path: ${sanitizeWarnPart(path)}`);
|
|
128
|
+
}
|
|
129
|
+
const parentDir = dirname(path);
|
|
130
|
+
const parentStat = safeLstat(parentDir);
|
|
131
|
+
if (!parentStat || parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(path)) {
|
|
132
|
+
throw new Error(`Refusing to write profile into invalid or symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const pathStat = safeLstat(path);
|
|
136
|
+
if (pathStat?.isSymbolicLink()) {
|
|
137
|
+
throw new Error(`Refusing to write profile through symlink: ${sanitizeWarnPart(path)}`);
|
|
138
|
+
}
|
|
139
|
+
if (pathStat && !pathStat.isFile() && !pathStat.isDirectory()) {
|
|
140
|
+
throw new Error(`Refusing to write profile into non-regular target: ${sanitizeWarnPart(path)}`);
|
|
141
|
+
}
|
|
142
|
+
|
|
27
143
|
const tmp = path + ".tmp";
|
|
28
144
|
|
|
29
|
-
// Residue from an earlier crash
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
145
|
+
// Residue from an earlier crash (including dangling symlinks where existsSync is false!)
|
|
146
|
+
// must be unlinked via lstatSync first so exclusive create (`wx`) always starts fresh at 0600.
|
|
147
|
+
const tmpStat = safeLstat(tmp);
|
|
148
|
+
if (tmpStat) {
|
|
149
|
+
try {
|
|
150
|
+
unlinkSync(tmp);
|
|
151
|
+
} catch (e) {
|
|
152
|
+
warn(`[agentchat] WARNING: stale ${sanitizeWarnPart(tmp)} could not be removed: ${sanitizeWarnPart(e)}\n`);
|
|
153
|
+
}
|
|
34
154
|
}
|
|
35
155
|
|
|
36
|
-
// Created fresh
|
|
37
|
-
writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
38
|
-
renameSync(tmp, path);
|
|
156
|
+
// Created fresh with exclusive `wx` → refuses symlinks/races and guarantees mode 0600 from instant of creation.
|
|
157
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600, flag: "wx" });
|
|
39
158
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
159
|
+
// Re-verify parent and target right before renameSync to narrow TOCTOU symlink swaps.
|
|
160
|
+
const currentParent = safeLstat(parentDir);
|
|
161
|
+
if (!currentParent || currentParent.isSymbolicLink() || !currentParent.isDirectory() || !hasSafeAncestorDirs(path)) {
|
|
162
|
+
try { unlinkSync(tmp); } catch {}
|
|
163
|
+
throw new Error(`Refusing to write profile into symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
|
|
164
|
+
}
|
|
165
|
+
if (safeLstat(path)?.isSymbolicLink()) {
|
|
166
|
+
try { unlinkSync(tmp); } catch {}
|
|
167
|
+
throw new Error(`Refusing to overwrite symlinked profile: ${sanitizeWarnPart(path)}`);
|
|
44
168
|
}
|
|
45
169
|
|
|
46
170
|
try {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
171
|
+
renameSync(tmp, path);
|
|
172
|
+
} catch (err: any) {
|
|
173
|
+
if (process.platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
|
|
174
|
+
// On Windows NTFS, antivirus or search indexers can momentarily hold `path` open,
|
|
175
|
+
// causing atomic MoveFileEx to return EPERM/EACCES. Fall back to copy+unlink when
|
|
176
|
+
// `path` is not a symlink or directory.
|
|
177
|
+
const winTarget = safeLstat(path);
|
|
178
|
+
if (winTarget?.isSymbolicLink() || winTarget?.isDirectory()) {
|
|
179
|
+
try { unlinkSync(tmp); } catch {}
|
|
180
|
+
throw new Error(`Refusing to overwrite symlinked or directory profile: ${sanitizeWarnPart(path)}`);
|
|
181
|
+
}
|
|
182
|
+
copyFileSync(tmp, path);
|
|
183
|
+
try {
|
|
184
|
+
unlinkSync(tmp);
|
|
185
|
+
} catch {}
|
|
186
|
+
} else {
|
|
187
|
+
throw err;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// POSIX mode bits (0600) do not exist on Windows NTFS (`statSync().mode & 0o777` is always 0666);
|
|
192
|
+
// Windows protects `%USERPROFILE%\.agentschat` via user-profile NTFS ACL inheritance instead.
|
|
193
|
+
if (process.platform !== "win32") {
|
|
194
|
+
const postStat = safeLstat(path);
|
|
195
|
+
if (!postStat || postStat.isSymbolicLink() || !postStat.isFile()) {
|
|
196
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target\n`);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
try {
|
|
200
|
+
chmodSync(path, 0o600);
|
|
201
|
+
} catch (e) {
|
|
202
|
+
warn(`[agentchat] WARNING: could not chmod ${sanitizeWarnPart(path)} to 0600: ${sanitizeWarnPart(e)}\n`);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
try {
|
|
206
|
+
const verified = safeLstat(path);
|
|
207
|
+
if (!verified || verified.isSymbolicLink() || !verified.isFile()) {
|
|
208
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target\n`);
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const mode = verified.mode & 0o777;
|
|
212
|
+
if (mode !== 0o600) {
|
|
213
|
+
warn(
|
|
214
|
+
`[agentchat] WARNING: ${sanitizeWarnPart(path)} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${sanitizeWarnPart(path)}\n`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
} catch (e) {
|
|
218
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: ${sanitizeWarnPart(e)}\n`);
|
|
52
219
|
}
|
|
53
|
-
} catch (e) {
|
|
54
|
-
warn(`[agentchat] WARNING: could not verify permissions of ${path}: ${e}\n`);
|
|
55
220
|
}
|
|
56
221
|
}
|
|
57
222
|
|
|
@@ -63,13 +228,29 @@ export interface DefaultProfileCollision {
|
|
|
63
228
|
|
|
64
229
|
const NON_PROFILE_JSON_FILES = new Set([
|
|
65
230
|
"session-binds.json",
|
|
231
|
+
"session-binds.meta.json",
|
|
232
|
+
"session-binds-meta.json",
|
|
233
|
+
"session-binds_meta.json",
|
|
234
|
+
"agy-session-binds.json",
|
|
235
|
+
"agy-session-binds.meta.json",
|
|
236
|
+
"agy-session-binds_meta.json",
|
|
66
237
|
"agy-binds.json",
|
|
238
|
+
"agy-binds.meta.json",
|
|
239
|
+
"agy-binds-meta.json",
|
|
240
|
+
"agy-binds_meta.json",
|
|
67
241
|
"grok-binds.json",
|
|
68
242
|
"grok-binds-meta.json",
|
|
69
243
|
"grok-binds.meta.json",
|
|
244
|
+
"grok-binds_meta.json",
|
|
70
245
|
"identity-guard.json",
|
|
246
|
+
"cursor.json",
|
|
247
|
+
"read-cursors.json",
|
|
248
|
+
"mention-timestamps.json",
|
|
249
|
+
"wake-pids.json",
|
|
250
|
+
"codex-bots.json",
|
|
71
251
|
"dsh.json",
|
|
72
252
|
"config.json",
|
|
253
|
+
"muse.json",
|
|
73
254
|
]);
|
|
74
255
|
|
|
75
256
|
/**
|
|
@@ -82,45 +263,82 @@ export function findDefaultProfileCollision(
|
|
|
82
263
|
configDir: string,
|
|
83
264
|
defaultProfilePath: string,
|
|
84
265
|
): DefaultProfileCollision | null {
|
|
85
|
-
if (!defaultProfilePath || !
|
|
266
|
+
if (!defaultProfilePath || !hasSafeAncestorDirs(defaultProfilePath)) return null;
|
|
267
|
+
const defStat = safeLstat(defaultProfilePath);
|
|
268
|
+
if (!defStat || defStat.isSymbolicLink() || !defStat.isFile() || defStat.size > MAX_PROFILE_JSON_BYTES) {
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
86
271
|
let defParsed: { agent_id?: unknown; display_name?: unknown; token?: unknown };
|
|
87
272
|
try {
|
|
88
273
|
defParsed = JSON.parse(readFileSync(defaultProfilePath, "utf8"));
|
|
89
274
|
} catch {
|
|
90
275
|
return null;
|
|
91
276
|
}
|
|
92
|
-
if (
|
|
277
|
+
if (
|
|
278
|
+
!defParsed ||
|
|
279
|
+
typeof defParsed !== "object" ||
|
|
280
|
+
Array.isArray(defParsed) ||
|
|
281
|
+
Object.prototype.hasOwnProperty.call(defParsed, "__proto__")
|
|
282
|
+
) {
|
|
283
|
+
return null;
|
|
284
|
+
}
|
|
93
285
|
const defAgentId = typeof defParsed.agent_id === "string" ? defParsed.agent_id.trim() : "";
|
|
94
286
|
const defDisplayName =
|
|
95
287
|
typeof defParsed.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
|
|
96
288
|
if (!defAgentId && !defDisplayName) return null;
|
|
97
289
|
|
|
290
|
+
const cfgStat = safeLstat(configDir);
|
|
291
|
+
if (!cfgStat || cfgStat.isSymbolicLink() || !cfgStat.isDirectory() || !hasSafeAncestorDirs(join(configDir, "probe"))) {
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
|
|
98
295
|
const resolvedDefault = resolve(defaultProfilePath);
|
|
99
296
|
for (const dir of [join(configDir, "profiles"), configDir]) {
|
|
100
|
-
|
|
297
|
+
const dirStat = safeLstat(dir);
|
|
298
|
+
if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue;
|
|
101
299
|
let files: string[] = [];
|
|
102
300
|
try {
|
|
103
|
-
files = readdirSync(dir).filter((f) =>
|
|
301
|
+
files = readdirSync(dir).filter((f) => /\.json$/i.test(f));
|
|
104
302
|
} catch {
|
|
105
303
|
continue;
|
|
106
304
|
}
|
|
107
305
|
for (const file of files) {
|
|
108
|
-
if (NON_PROFILE_JSON_FILES.has(file)) continue;
|
|
306
|
+
if (NON_PROFILE_JSON_FILES.has(file.toLowerCase())) continue;
|
|
109
307
|
const candidatePath = join(dir, file);
|
|
110
308
|
if (resolve(candidatePath) === resolvedDefault) continue;
|
|
111
|
-
const baseName = file.replace(/\.json
|
|
112
|
-
|
|
309
|
+
const baseName = file.replace(/\.json$/i, "");
|
|
310
|
+
const baseLower = baseName.toLowerCase();
|
|
311
|
+
if (
|
|
312
|
+
baseLower === "profile" ||
|
|
313
|
+
RESERVED_PROTO_STEMS.has(baseLower) ||
|
|
314
|
+
WINDOWS_DEVICE_STEM_RE.test(baseName)
|
|
315
|
+
) {
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
113
318
|
|
|
319
|
+
const candStat = safeLstat(candidatePath);
|
|
320
|
+
if (!candStat || candStat.isSymbolicLink() || !candStat.isFile() || candStat.size > MAX_PROFILE_JSON_BYTES) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
114
323
|
let candidate: { agent_id?: unknown; display_name?: unknown; token?: unknown };
|
|
115
324
|
try {
|
|
116
325
|
candidate = JSON.parse(readFileSync(candidatePath, "utf8"));
|
|
117
326
|
} catch {
|
|
118
327
|
continue;
|
|
119
328
|
}
|
|
120
|
-
if (
|
|
329
|
+
if (
|
|
330
|
+
!candidate ||
|
|
331
|
+
typeof candidate !== "object" ||
|
|
332
|
+
Array.isArray(candidate) ||
|
|
333
|
+
Object.prototype.hasOwnProperty.call(candidate, "__proto__")
|
|
334
|
+
) {
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
121
337
|
const candAgentId = typeof candidate.agent_id === "string" ? candidate.agent_id.trim() : "";
|
|
122
338
|
const candToken = typeof candidate.token === "string" ? candidate.token.trim() : "";
|
|
123
|
-
if (!candAgentId || !candToken)
|
|
339
|
+
if (!candAgentId || !candToken || CONTROL_CHAR_RE.test(candAgentId) || RESERVED_PROTO_STEMS.has(candAgentId.toLowerCase())) {
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
124
342
|
|
|
125
343
|
if (defAgentId && candAgentId === defAgentId) {
|
|
126
344
|
return { collidingName: baseName, collidingPath: candidatePath, reason: "agent_id" };
|
package/src/read-cursor.ts
CHANGED
|
@@ -14,35 +14,306 @@
|
|
|
14
14
|
*
|
|
15
15
|
* So: the write reports success, and the dirty flag is cleared ONLY once it lands.
|
|
16
16
|
*/
|
|
17
|
-
import {
|
|
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 MAX_CURSOR_PATH_LEN = 4096;
|
|
42
|
+
const WINDOWS_DEVICE_STEM_RE = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/i;
|
|
43
|
+
const RESERVED_PROTO_KEYS = new Set([
|
|
44
|
+
"__proto__",
|
|
45
|
+
"constructor",
|
|
46
|
+
"prototype",
|
|
47
|
+
...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
|
|
48
|
+
]);
|
|
49
|
+
let tmpCounter = 0;
|
|
50
|
+
|
|
51
|
+
function isReservedCursorKey(key: string): boolean {
|
|
52
|
+
return RESERVED_PROTO_KEYS.has(key.toLowerCase());
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function scrubDiag(value: unknown): string {
|
|
56
|
+
return redactSecrets(String(value ?? ""))
|
|
57
|
+
.replace(/\b(https?:\/\/)([^/\s@]*@)/gi, "$1[REDACTED]@")
|
|
58
|
+
.replace(/\b(?:Bearer|Basic)\s+[^\s"'<>\\]+/gi, "[REDACTED]")
|
|
59
|
+
.replace(
|
|
60
|
+
/(?: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,
|
|
61
|
+
"[REDACTED]",
|
|
62
|
+
)
|
|
63
|
+
.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isDarwinCanonicalRootLink(dir: string, st: Stats): boolean {
|
|
67
|
+
if (
|
|
68
|
+
process.platform !== "darwin" ||
|
|
69
|
+
(dir !== "/var" && dir !== "/tmp" && dir !== "/etc") ||
|
|
70
|
+
!st.isSymbolicLink()
|
|
71
|
+
) {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
return (
|
|
76
|
+
realpathSync(dir) === `/private${dir}` &&
|
|
77
|
+
!lstatSync("/private").isSymbolicLink() &&
|
|
78
|
+
lstatSync("/private").isDirectory() &&
|
|
79
|
+
!lstatSync(`/private${dir}`).isSymbolicLink() &&
|
|
80
|
+
lstatSync(`/private${dir}`).isDirectory()
|
|
81
|
+
);
|
|
82
|
+
} catch {
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function hasSafeRawDotDotAncestors(rawDirPath: string): boolean {
|
|
88
|
+
const absRaw = isAbsolute(rawDirPath) ? rawDirPath : `${process.cwd()}${sep}${rawDirPath}`;
|
|
89
|
+
const root = parse(absRaw).root;
|
|
90
|
+
const segments = absRaw.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
91
|
+
if (!segments.includes("..")) return true;
|
|
92
|
+
let cur = root;
|
|
93
|
+
for (const seg of segments) {
|
|
94
|
+
if (seg === ".") continue;
|
|
95
|
+
if (seg === "..") {
|
|
96
|
+
cur = dirname(cur);
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
const next = join(cur, seg);
|
|
100
|
+
try {
|
|
101
|
+
const st = lstatSync(next);
|
|
102
|
+
if (st.isSymbolicLink() && !isDarwinCanonicalRootLink(next, st)) {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
} catch (err) {
|
|
106
|
+
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") return false;
|
|
107
|
+
}
|
|
108
|
+
cur = next;
|
|
109
|
+
}
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function hasSafeAncestorDirs(targetFile: string): boolean {
|
|
114
|
+
if (typeof targetFile !== "string" || !targetFile || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(targetFile)) {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
const rawParent = dirname(isAbsolute(targetFile) ? targetFile : `${process.cwd()}${sep}${targetFile}`);
|
|
118
|
+
if (!hasSafeRawDotDotAncestors(rawParent)) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
let dir = resolve(rawParent);
|
|
122
|
+
while (true) {
|
|
123
|
+
let st;
|
|
124
|
+
try {
|
|
125
|
+
st = lstatSync(dir);
|
|
126
|
+
} catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
const isDarwinRootLink = isDarwinCanonicalRootLink(dir, st);
|
|
130
|
+
if (!isDarwinRootLink && (st.isSymbolicLink() || !st.isDirectory())) {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
const parent = dirname(dir);
|
|
134
|
+
if (parent === dir) break;
|
|
135
|
+
dir = parent;
|
|
136
|
+
}
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Sanitize an agent_id into a cross-platform safe filename slug (no `/`, `\`, `..`,
|
|
142
|
+
* or Windows NTFS invalid chars like `:`), while keeping standard `[A-Za-z0-9._-]+`
|
|
143
|
+
* agent IDs 100% unchanged so existing cursor files continue to match.
|
|
144
|
+
*/
|
|
145
|
+
export function safeAgentCursorSlug(agentId: string): string {
|
|
146
|
+
const cleaned = String(agentId || "")
|
|
147
|
+
.trim()
|
|
148
|
+
.replace(/[^A-Za-z0-9._-]/g, "_")
|
|
149
|
+
.replace(/\.+$/g, "")
|
|
150
|
+
.slice(0, 128);
|
|
151
|
+
if (
|
|
152
|
+
!cleaned ||
|
|
153
|
+
cleaned === "." ||
|
|
154
|
+
cleaned.includes("..") ||
|
|
155
|
+
WINDOWS_DEVICE_STEM_RE.test(cleaned) ||
|
|
156
|
+
isReservedCursorKey(cleaned)
|
|
157
|
+
) {
|
|
158
|
+
return "_";
|
|
159
|
+
}
|
|
160
|
+
return cleaned;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function cursorFileForAgent(configDir: string, agentId: string): string {
|
|
164
|
+
return join(configDir, `last-seen-msg-ts-${safeAgentCursorSlug(agentId)}.json`);
|
|
165
|
+
}
|
|
166
|
+
|
|
21
167
|
/**
|
|
22
168
|
* Read a persisted channel→timestamp map.
|
|
23
169
|
*
|
|
24
170
|
* A missing file is the normal first-run case and stays quiet. Anything else — corrupt
|
|
25
|
-
* JSON, bad permissions — means we are
|
|
26
|
-
* remember, and this runs ONCE at startup:
|
|
171
|
+
* JSON, non-object JSON, non-string values, bad permissions — means we are resetting state
|
|
172
|
+
* we were supposed to remember, and this runs ONCE at startup: warn loudly.
|
|
27
173
|
*/
|
|
28
174
|
export function loadCursor(file: string, warn: Warn): Map<string, string> {
|
|
29
175
|
try {
|
|
30
|
-
|
|
176
|
+
if (!hasSafeAncestorDirs(file)) {
|
|
177
|
+
let exists = false;
|
|
178
|
+
try {
|
|
179
|
+
lstatSync(file);
|
|
180
|
+
exists = true;
|
|
181
|
+
} catch (err) {
|
|
182
|
+
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") exists = true;
|
|
183
|
+
}
|
|
184
|
+
if (!exists) return new Map();
|
|
185
|
+
throw new Error("cursor parent path must be a real directory");
|
|
186
|
+
}
|
|
187
|
+
const st = lstatSync(file);
|
|
188
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
189
|
+
throw new Error("cursor path must be a regular file");
|
|
190
|
+
}
|
|
191
|
+
if (st.size > MAX_CURSOR_BYTES) {
|
|
192
|
+
throw new Error(`cursor file exceeds ${MAX_CURSOR_BYTES} byte limit`);
|
|
193
|
+
}
|
|
194
|
+
const parsed = JSON.parse(readFileSync(file, "utf-8")) as unknown;
|
|
195
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
196
|
+
throw new Error("cursor root must be a JSON object");
|
|
197
|
+
}
|
|
198
|
+
const entries: Array<[string, string]> = [];
|
|
199
|
+
for (const [k, v] of Object.entries(parsed as Record<string, unknown>)) {
|
|
200
|
+
if (isReservedCursorKey(k)) continue;
|
|
201
|
+
if (typeof v !== "string") {
|
|
202
|
+
throw new Error(`cursor value for ${scrubDiag(k)} must be a string`);
|
|
203
|
+
}
|
|
204
|
+
if (!k || k.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
|
|
205
|
+
throw new Error(`cursor entry for ${scrubDiag(k)} contains invalid characters or length`);
|
|
206
|
+
}
|
|
207
|
+
if (entries.length >= MAX_CURSOR_ENTRIES) {
|
|
208
|
+
throw new Error(`cursor entry count exceeds ${MAX_CURSOR_ENTRIES}`);
|
|
209
|
+
}
|
|
210
|
+
entries.push([k, v]);
|
|
211
|
+
}
|
|
212
|
+
return new Map(entries);
|
|
31
213
|
} catch (e) {
|
|
32
214
|
if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") {
|
|
33
|
-
warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}\n`);
|
|
215
|
+
warn(`[agentchat] WARNING: could not read ${scrubDiag(file)} — resetting that state: ${scrubDiag(e)}\n`);
|
|
34
216
|
}
|
|
35
217
|
return new Map();
|
|
36
218
|
}
|
|
37
219
|
}
|
|
38
220
|
|
|
39
|
-
/** Write the cursor to disk. Returns true iff it actually landed. Never throws. */
|
|
40
|
-
export function persistCursor(
|
|
221
|
+
/** Write the cursor to disk atomically (0600 tmp + rename, with Windows NTFS EPERM/EACCES fallback). Returns true iff it actually landed. Never throws. */
|
|
222
|
+
export function persistCursor(
|
|
223
|
+
file: string,
|
|
224
|
+
cursor: Map<string, string>,
|
|
225
|
+
warn: Warn,
|
|
226
|
+
fsOps?: PersistCursorFsOps,
|
|
227
|
+
): boolean {
|
|
228
|
+
if (typeof file !== "string" || !file || file.length > MAX_CURSOR_PATH_LEN || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(file)) {
|
|
229
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: invalid cursor file path\n`);
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
const parentStat = lstatSync(dirname(file));
|
|
234
|
+
if (parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(file)) {
|
|
235
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: parent is not a real directory\n`);
|
|
236
|
+
return false;
|
|
237
|
+
}
|
|
238
|
+
} catch (e) {
|
|
239
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}\n`);
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
41
242
|
try {
|
|
42
|
-
|
|
243
|
+
const existing = lstatSync(file);
|
|
244
|
+
if (existing.isSymbolicLink() || !existing.isFile()) {
|
|
245
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: target is not a regular file\n`);
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
} catch (e) {
|
|
249
|
+
if ((e as NodeJS.ErrnoException)?.code !== "ENOENT") {
|
|
250
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}\n`);
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
const validEntries: Array<[string, string]> = [];
|
|
255
|
+
for (const [k, v] of cursor) {
|
|
256
|
+
if (!k || k.length > 256 || isReservedCursorKey(k) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(k) || typeof v !== "string" || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(v) || v.length > 256) {
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
validEntries.push([k, v]);
|
|
260
|
+
}
|
|
261
|
+
const boundedEntries =
|
|
262
|
+
validEntries.length > MAX_CURSOR_ENTRIES
|
|
263
|
+
? validEntries.slice(validEntries.length - MAX_CURSOR_ENTRIES)
|
|
264
|
+
: validEntries;
|
|
265
|
+
const payloadObj: Record<string, string> = Object.create(null);
|
|
266
|
+
for (const [k, v] of boundedEntries) {
|
|
267
|
+
payloadObj[k] = v;
|
|
268
|
+
}
|
|
269
|
+
const renameFn = fsOps?.renameSync ?? renameSync;
|
|
270
|
+
const copyFn = fsOps?.copyFileSync ?? copyFileSync;
|
|
271
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.${++tmpCounter}.${randomBytes(4).toString("hex")}.tmp`;
|
|
272
|
+
try {
|
|
273
|
+
writeFileSync(tmp, JSON.stringify(payloadObj), { mode: 0o600, flag: "wx" });
|
|
274
|
+
if (process.platform !== "win32") {
|
|
275
|
+
chmodSync(tmp, 0o600);
|
|
276
|
+
}
|
|
277
|
+
if (!hasSafeAncestorDirs(file)) {
|
|
278
|
+
throw new Error("parent is not a real directory");
|
|
279
|
+
}
|
|
280
|
+
const current = lstatSync(file, { throwIfNoEntry: false });
|
|
281
|
+
if (current && (current.isSymbolicLink() || !current.isFile())) {
|
|
282
|
+
throw new Error("target was replaced by a symlink or non-file");
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
renameFn(tmp, file);
|
|
286
|
+
} catch (renameErr) {
|
|
287
|
+
const code = (renameErr as NodeJS.ErrnoException)?.code;
|
|
288
|
+
if (code === "EPERM" || code === "EACCES") {
|
|
289
|
+
if (!hasSafeAncestorDirs(file)) {
|
|
290
|
+
throw new Error("parent is not a real directory");
|
|
291
|
+
}
|
|
292
|
+
const recheck = lstatSync(file, { throwIfNoEntry: false });
|
|
293
|
+
if (recheck && (recheck.isSymbolicLink() || !recheck.isFile())) {
|
|
294
|
+
throw new Error("target was replaced by a symlink or non-file");
|
|
295
|
+
}
|
|
296
|
+
copyFn(tmp, file);
|
|
297
|
+
if (process.platform !== "win32") {
|
|
298
|
+
chmodSync(file, 0o600);
|
|
299
|
+
}
|
|
300
|
+
try {
|
|
301
|
+
unlinkSync(tmp);
|
|
302
|
+
} catch {
|
|
303
|
+
/* ignore cleanup error */
|
|
304
|
+
}
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
throw renameErr;
|
|
308
|
+
}
|
|
43
309
|
return true;
|
|
44
310
|
} catch (e) {
|
|
45
|
-
|
|
311
|
+
try {
|
|
312
|
+
unlinkSync(tmp);
|
|
313
|
+
} catch {
|
|
314
|
+
/* ignore cleanup error */
|
|
315
|
+
}
|
|
316
|
+
warn(`[agentchat] WARNING: failed to persist read cursor to ${scrubDiag(file)}: ${scrubDiag(e)}\n`);
|
|
46
317
|
return false;
|
|
47
318
|
}
|
|
48
319
|
}
|