agentschat-mcp 0.36.24 → 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.
- package/CHANGELOG.md +12 -0
- package/README.md +8 -0
- package/codex/README.md +1 -1
- package/codex/app-server.ts +79 -22
- package/codex/bots-config.ts +31 -11
- package/codex/bridge.ts +123 -25
- package/codex/config.ts +128 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +65 -12
- package/codex/loop-grants.ts +41 -11
- package/codex/manager.ts +101 -25
- package/codex/owner.ts +81 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +41 -11
- package/codex/thread-history.ts +77 -30
- package/codex/transport.ts +122 -19
- 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/dist/codex-bots.js +410 -73
- package/dist/codex-bridge.js +1996 -576
- package/dist/connector.js +1286 -493
- package/dist/dsh.js +1776 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +7645 -1172
- 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 +595 -146
- 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 +990 -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/agentschat-team-lead/SKILL.md +1 -1
- package/skills/onboarding.md +14 -10
- package/src/argcheck.ts +1890 -1
- package/src/cli.mjs +98 -14
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +160 -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 +269 -18
- package/src/profile-store.ts +222 -28
- package/src/read-cursor.ts +256 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +2487 -342
- package/src/session-bind.ts +731 -132
- 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 +22 -1
- package/src/wake.ts +524 -90
package/src/profile-selection.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync, type Stats } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, isAbsolute, join, parse, relative, resolve } from "node:path";
|
|
3
4
|
|
|
4
5
|
export interface ProjectProfileSelection {
|
|
5
6
|
selector: string;
|
|
@@ -9,37 +10,287 @@ export interface ProjectProfileSelection {
|
|
|
9
10
|
wsUrl?: string;
|
|
10
11
|
}
|
|
11
12
|
|
|
13
|
+
const MAX_PROJECT_CONFIG_BYTES = 64 * 1024;
|
|
14
|
+
const MAX_PROJECT_PROFILE_BYTES = 1_048_576;
|
|
15
|
+
const FORBIDDEN_CREDENTIAL_KEYS = new Set([
|
|
16
|
+
"token",
|
|
17
|
+
"access_token",
|
|
18
|
+
"refresh_token",
|
|
19
|
+
"id_token",
|
|
20
|
+
"oauth_token",
|
|
21
|
+
"api_token",
|
|
22
|
+
"key",
|
|
23
|
+
"api_key",
|
|
24
|
+
"agent_key",
|
|
25
|
+
"private_key",
|
|
26
|
+
"secret",
|
|
27
|
+
"client_secret",
|
|
28
|
+
"webhook_secret",
|
|
29
|
+
"password",
|
|
30
|
+
"authorization",
|
|
31
|
+
"bearer",
|
|
32
|
+
"cookie",
|
|
33
|
+
]);
|
|
34
|
+
const PROTOTYPE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
|
|
35
|
+
const RESERVED_SIDECAR_STEMS = new Set([
|
|
36
|
+
"grok-binds",
|
|
37
|
+
"session-binds",
|
|
38
|
+
"agy-binds",
|
|
39
|
+
"cursor",
|
|
40
|
+
"read-cursors",
|
|
41
|
+
"wake-pids",
|
|
42
|
+
"config",
|
|
43
|
+
"codex-bots",
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
function safeLstat(target: string): Stats | undefined {
|
|
47
|
+
try {
|
|
48
|
+
return lstatSync(target);
|
|
49
|
+
} catch (err: any) {
|
|
50
|
+
if (err && err.code === "ENOENT") return undefined;
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const PROJECT_CONTROL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
|
|
56
|
+
|
|
57
|
+
function isAllowedDarwinSystemLink(dirPath: string): boolean {
|
|
58
|
+
if (process.platform !== "darwin") return false;
|
|
59
|
+
if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc") return false;
|
|
60
|
+
try {
|
|
61
|
+
const expected = `/private${dirPath}`;
|
|
62
|
+
return (
|
|
63
|
+
readlinkSync(dirPath) === `private${dirPath}` &&
|
|
64
|
+
realpathSync(dirPath) === expected &&
|
|
65
|
+
!lstatSync("/private").isSymbolicLink() &&
|
|
66
|
+
lstatSync("/private").isDirectory() &&
|
|
67
|
+
!lstatSync(expected).isSymbolicLink() &&
|
|
68
|
+
statSync(expected).isDirectory()
|
|
69
|
+
);
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function hasSafeRawDotDotSegments(rawPath: string, baseDir?: string): boolean {
|
|
76
|
+
if (!rawPath.includes("..")) return true;
|
|
77
|
+
const baseAbs = isAbsolute(rawPath) ? rawPath : `${baseDir ? resolve(baseDir) : process.cwd()}/${rawPath}`;
|
|
78
|
+
const root = parse(baseAbs).root;
|
|
79
|
+
const rawParts = baseAbs.slice(root.length).split(/[\\/]+/).filter(Boolean);
|
|
80
|
+
let cur = root;
|
|
81
|
+
for (const part of rawParts) {
|
|
82
|
+
if (part === ".") continue;
|
|
83
|
+
if (part === "..") {
|
|
84
|
+
cur = resolve(cur, "..");
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
cur = join(cur, part);
|
|
88
|
+
try {
|
|
89
|
+
const st = lstatSync(cur);
|
|
90
|
+
if (st.isSymbolicLink()) {
|
|
91
|
+
if (isAllowedDarwinSystemLink(cur)) continue;
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
if (!st.isDirectory()) return false;
|
|
95
|
+
} catch (err: any) {
|
|
96
|
+
if (err && err.code === "ENOENT") continue;
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function hasSafeDirChain(dirPath: string, baseDir?: string): boolean {
|
|
104
|
+
if (!dirPath || PROJECT_CONTROL_RE.test(dirPath)) return false;
|
|
105
|
+
if (!hasSafeRawDotDotSegments(dirPath, baseDir)) return false;
|
|
106
|
+
const abs = baseDir && !isAbsolute(dirPath) ? resolve(baseDir, dirPath) : resolve(dirPath);
|
|
107
|
+
const root = parse(abs).root;
|
|
108
|
+
const rel = abs.slice(root.length);
|
|
109
|
+
const segments = rel.split(/[\\/]+/).filter(Boolean);
|
|
110
|
+
let cur = root;
|
|
111
|
+
for (let i = 0; i < segments.length; i++) {
|
|
112
|
+
cur = join(cur, segments[i]!);
|
|
113
|
+
let st: Stats;
|
|
114
|
+
try {
|
|
115
|
+
st = lstatSync(cur);
|
|
116
|
+
} catch (err: any) {
|
|
117
|
+
if (err && err.code === "ENOENT") return true;
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
if (st.isSymbolicLink()) {
|
|
121
|
+
if (isAllowedDarwinSystemLink(cur)) continue;
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
if (!st.isDirectory()) return false;
|
|
125
|
+
}
|
|
126
|
+
return true;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function isLoopbackHost(hostname: string): boolean {
|
|
130
|
+
const lower = hostname.toLowerCase().replace(/\.$/, "");
|
|
131
|
+
return lower === "127.0.0.1" || lower === "localhost" || lower === "[::1]" || lower === "::1";
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function isUnsafeMetadataOrLinkLocalHost(hostname: string): boolean {
|
|
135
|
+
const lower = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
136
|
+
if (
|
|
137
|
+
lower === "metadata.google.internal" ||
|
|
138
|
+
lower.endsWith(".metadata.google.internal") ||
|
|
139
|
+
lower === "metadata" ||
|
|
140
|
+
lower === "metadata.goog" ||
|
|
141
|
+
lower.endsWith(".metadata.goog") ||
|
|
142
|
+
lower === "instance-data" ||
|
|
143
|
+
lower === "100.100.100.200" ||
|
|
144
|
+
lower === "0.0.0.0" ||
|
|
145
|
+
lower === "::" ||
|
|
146
|
+
lower === "0:0:0:0:0:0:0:0" ||
|
|
147
|
+
lower === "fd00:ec2::254"
|
|
148
|
+
) {
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(lower)) {
|
|
152
|
+
const [a, b] = lower.split(".").map(Number);
|
|
153
|
+
if (a === 0 || (a === 169 && b === 254)) return true;
|
|
154
|
+
}
|
|
155
|
+
if (/^fe[89ab][0-9a-f]*:/.test(lower)) return true;
|
|
156
|
+
if (lower.startsWith("::ffff:")) {
|
|
157
|
+
const tail = lower.slice("::ffff:".length);
|
|
158
|
+
const afterZero = tail.startsWith("0:") ? tail.slice(2) : "";
|
|
159
|
+
const tailParts = afterZero && (afterZero.includes(".") || afterZero.includes(":")) ? afterZero : tail;
|
|
160
|
+
if (tailParts === "0.0.0.0" || tailParts === "100.100.100.200" || /^0\.\d+\.\d+\.\d+$/.test(tailParts)) return true;
|
|
161
|
+
if (/^169\.254\.\d{1,3}\.\d{1,3}$/.test(tailParts)) return true;
|
|
162
|
+
const hexMatch = tailParts.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
163
|
+
if (hexMatch) {
|
|
164
|
+
const hi = parseInt(hexMatch[1]!, 16);
|
|
165
|
+
const lo = parseInt(hexMatch[2]!, 16);
|
|
166
|
+
if (((hi >> 8) & 0xff) === 0) return true;
|
|
167
|
+
if (((hi >> 8) & 0xff) === 169 && (hi & 0xff) === 254) return true;
|
|
168
|
+
if (hi === 0x6464 && lo === 0x64c8) return true;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function isSafeProjectAgentId(id: string): boolean {
|
|
175
|
+
return (
|
|
176
|
+
id.length > 0 &&
|
|
177
|
+
id.length <= 128 &&
|
|
178
|
+
id !== "." &&
|
|
179
|
+
!id.includes("..") &&
|
|
180
|
+
!/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(id) &&
|
|
181
|
+
!/(?:%2e|%2f|%5c|%00)/i.test(id) &&
|
|
182
|
+
!PROTOTYPE_KEYS.has(id.toLowerCase())
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
12
186
|
/** Read only this project's binding. Never scan parents or choose a sibling bot. */
|
|
13
187
|
export function projectProfileSelector(cwd: string): ProjectProfileSelection | undefined {
|
|
14
|
-
|
|
188
|
+
if (!cwd || PROJECT_CONTROL_RE.test(cwd) || !hasSafeRawDotDotSegments(cwd)) {
|
|
189
|
+
throw new Error("Refusing symlinked or non-directory project .agentschat");
|
|
190
|
+
}
|
|
191
|
+
const resolvedCwd = resolve(cwd);
|
|
192
|
+
const projectDir = join(resolvedCwd, ".agentschat");
|
|
193
|
+
const dirStat = safeLstat(projectDir);
|
|
194
|
+
if (!dirStat) return undefined;
|
|
195
|
+
if (dirStat.isSymbolicLink() || !dirStat.isDirectory() || !hasSafeDirChain(projectDir)) {
|
|
196
|
+
throw new Error("Refusing symlinked or non-directory project .agentschat");
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const config = join(projectDir, "config.json");
|
|
15
200
|
let doc: any = {};
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
201
|
+
const configStat = safeLstat(config);
|
|
202
|
+
if (configStat) {
|
|
203
|
+
if (configStat.isSymbolicLink() || !configStat.isFile() || configStat.size > MAX_PROJECT_CONFIG_BYTES) {
|
|
204
|
+
throw new Error("Invalid project .agentschat/config.json; repair it before choosing an identity");
|
|
205
|
+
}
|
|
206
|
+
let raw: string;
|
|
207
|
+
try {
|
|
208
|
+
raw = readFileSync(config, "utf8");
|
|
209
|
+
doc = JSON.parse(raw);
|
|
210
|
+
} catch {
|
|
211
|
+
throw new Error("Invalid project .agentschat/config.json; repair it before choosing an identity");
|
|
212
|
+
}
|
|
19
213
|
if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new Error("Invalid project identity configuration");
|
|
214
|
+
if (
|
|
215
|
+
Object.prototype.hasOwnProperty.call(doc, "__proto__") ||
|
|
216
|
+
Object.keys(doc).some((k) => PROTOTYPE_KEYS.has(k.toLowerCase()) || FORBIDDEN_CREDENTIAL_KEYS.has(k.toLowerCase()))
|
|
217
|
+
) {
|
|
218
|
+
throw new Error("Credentials must not be stored in project .agentschat/config.json");
|
|
219
|
+
}
|
|
20
220
|
for (const field of ["profile", "agent_id", "api_url", "ws_url"]) {
|
|
21
|
-
if (doc[field] !== undefined && (typeof doc[field] !== "string" || !doc[field].trim()
|
|
221
|
+
if (doc[field] !== undefined && (typeof doc[field] !== "string" || !doc[field].trim() || PROJECT_CONTROL_RE.test(doc[field]))) {
|
|
222
|
+
throw new Error(`Invalid project ${field}`);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (doc.agent_id !== undefined && !isSafeProjectAgentId((doc.agent_id as string).trim())) {
|
|
226
|
+
throw new Error("Invalid project agent_id");
|
|
22
227
|
}
|
|
23
228
|
for (const [field, protocols] of [["api_url", ["https:", "http:"]], ["ws_url", ["wss:", "ws:"]]] as const) {
|
|
24
229
|
if (doc[field] === undefined) continue;
|
|
230
|
+
const rawUrl = (doc[field] as string).trim();
|
|
25
231
|
let url: URL;
|
|
26
|
-
try { url = new URL(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
232
|
+
try { url = new URL(rawUrl); } catch { throw new Error(`Invalid project ${field}`); }
|
|
233
|
+
const portBad = /:0+(?:\/|$)/.test(rawUrl) || (url.port !== "" && (!Number.isInteger(Number(url.port)) || Number(url.port) < 1 || Number(url.port) > 65535));
|
|
234
|
+
if (
|
|
235
|
+
portBad ||
|
|
236
|
+
!(protocols as readonly string[]).includes(url.protocol) ||
|
|
237
|
+
url.username ||
|
|
238
|
+
url.password ||
|
|
239
|
+
url.search ||
|
|
240
|
+
url.hash ||
|
|
241
|
+
isUnsafeMetadataOrLinkLocalHost(url.hostname) ||
|
|
242
|
+
(!url.protocol.endsWith("s:") && !isLoopbackHost(url.hostname))
|
|
243
|
+
) {
|
|
244
|
+
throw new Error(`Invalid project ${field}: require TLS (except loopback), safe host, and no credentials/query`);
|
|
245
|
+
}
|
|
30
246
|
}
|
|
31
247
|
}
|
|
32
248
|
const settings = {
|
|
33
|
-
...(doc.agent_id !== undefined ? { agentId: doc.agent_id as string } : {}),
|
|
34
|
-
...(doc.api_url !== undefined ? { apiUrl: doc.api_url as string } : {}),
|
|
35
|
-
...(doc.ws_url !== undefined ? { wsUrl: doc.ws_url as string } : {}),
|
|
249
|
+
...(doc.agent_id !== undefined ? { agentId: (doc.agent_id as string).trim() } : {}),
|
|
250
|
+
...(doc.api_url !== undefined ? { apiUrl: (doc.api_url as string).trim() } : {}),
|
|
251
|
+
...(doc.ws_url !== undefined ? { wsUrl: (doc.ws_url as string).trim() } : {}),
|
|
36
252
|
};
|
|
37
253
|
if (doc.profile !== undefined) {
|
|
38
|
-
const value = doc.profile as string;
|
|
39
|
-
|
|
254
|
+
const value = (doc.profile as string).trim();
|
|
255
|
+
const stemLower = value.replace(/\.json$/i, "").toLowerCase();
|
|
256
|
+
if (
|
|
257
|
+
value === "." ||
|
|
258
|
+
value === ".." ||
|
|
259
|
+
PROTOTYPE_KEYS.has(stemLower) ||
|
|
260
|
+
(!value.includes("/") && !value.includes("\\") && RESERVED_SIDECAR_STEMS.has(stemLower))
|
|
261
|
+
) {
|
|
262
|
+
throw new Error("Invalid project profile");
|
|
263
|
+
}
|
|
264
|
+
if (value.startsWith("~/") || value.startsWith("~\\")) {
|
|
265
|
+
const homeBase = resolve(homedir());
|
|
266
|
+
const resolvedHomeTarget = resolve(homeBase, value.slice(2));
|
|
267
|
+
const relHome = relative(homeBase, resolvedHomeTarget);
|
|
268
|
+
if (!relHome || relHome.startsWith("..") || isAbsolute(relHome) || !hasSafeRawDotDotSegments(value.slice(2), homeBase) || !hasSafeDirChain(dirname(resolvedHomeTarget))) {
|
|
269
|
+
throw new Error("Invalid project profile: home-relative path traversal");
|
|
270
|
+
}
|
|
271
|
+
return { selector: value, source: "project-config", ...settings };
|
|
272
|
+
}
|
|
273
|
+
if (!isAbsolute(value) && (value.includes("/") || value.includes("\\"))) {
|
|
274
|
+
const resolvedTarget = resolve(resolvedCwd, value);
|
|
275
|
+
const rel = relative(resolvedCwd, resolvedTarget);
|
|
276
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel) || !hasSafeRawDotDotSegments(value, resolvedCwd) || !hasSafeDirChain(dirname(resolvedTarget))) {
|
|
277
|
+
throw new Error("Invalid project profile: relative path must stay within project directory");
|
|
278
|
+
}
|
|
279
|
+
return { selector: resolvedTarget, source: "project-config", ...settings };
|
|
280
|
+
}
|
|
281
|
+
if (isAbsolute(value) && (!hasSafeRawDotDotSegments(value) || !hasSafeDirChain(dirname(value)))) {
|
|
282
|
+
throw new Error("Invalid project profile: symlinked parent directory");
|
|
283
|
+
}
|
|
284
|
+
return { selector: value, source: "project-config", ...settings };
|
|
285
|
+
}
|
|
286
|
+
const profile = join(projectDir, "profile.json");
|
|
287
|
+
const profileStat = safeLstat(profile);
|
|
288
|
+
if (profileStat) {
|
|
289
|
+
if (profileStat.isSymbolicLink() || !profileStat.isFile() || profileStat.size > MAX_PROJECT_PROFILE_BYTES) {
|
|
290
|
+
throw new Error("Refusing symlinked or non-regular project .agentschat/profile.json");
|
|
291
|
+
}
|
|
292
|
+
return { selector: profile, source: "project-profile", ...settings };
|
|
40
293
|
}
|
|
41
|
-
const profile = join(cwd, ".agentschat/profile.json");
|
|
42
|
-
if (existsSync(profile)) return { selector: profile, source: "project-profile", ...settings };
|
|
43
294
|
// A declared agent/server scope must never silently disappear into a global identity.
|
|
44
295
|
if (Object.keys(settings).length) throw new Error("Project identity/server settings require a profile binding");
|
|
45
296
|
}
|
package/src/profile-store.ts
CHANGED
|
@@ -15,43 +15,193 @@
|
|
|
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 CONTROL_CHAR_GLOBAL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/g;
|
|
39
|
+
const DARWIN_SYSTEM_SYMLINKS = new Set(["/var", "/tmp", "/etc"]);
|
|
40
|
+
|
|
41
|
+
function sanitizeWarnPart(value: unknown): string {
|
|
42
|
+
return redactSecrets(String(value ?? ""))
|
|
43
|
+
.replace(/\b(https?:\/\/?)([^/\s@]*@)/gi, "$1[REDACTED]@")
|
|
44
|
+
.replace(/\b(?:Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "[REDACTED]")
|
|
45
|
+
.replace(
|
|
46
|
+
/\b(?: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,
|
|
47
|
+
"[REDACTED]",
|
|
48
|
+
)
|
|
49
|
+
.replace(CONTROL_CHAR_GLOBAL_RE, "?");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function safeLstat(target: string): Stats | undefined {
|
|
53
|
+
try {
|
|
54
|
+
return lstatSync(target);
|
|
55
|
+
} catch (err: any) {
|
|
56
|
+
if (err && err.code === "ENOENT") return undefined;
|
|
57
|
+
throw err;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isAllowedDarwinSystemSymlink(dirPath: string): boolean {
|
|
62
|
+
if (process.platform !== "darwin" || !DARWIN_SYSTEM_SYMLINKS.has(dirPath)) return false;
|
|
63
|
+
try {
|
|
64
|
+
const resolved = realpathSync(dirPath);
|
|
65
|
+
if (resolved !== `/private${dirPath}`) return false;
|
|
66
|
+
const privSt = lstatSync("/private");
|
|
67
|
+
if (!privSt.isDirectory() || privSt.isSymbolicLink()) return false;
|
|
68
|
+
const realSt = lstatSync(resolved);
|
|
69
|
+
return realSt.isDirectory() && !realSt.isSymbolicLink();
|
|
70
|
+
} catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function hasSafeRawDotDotAncestors(targetPath: string): boolean {
|
|
76
|
+
if (!targetPath.includes("..")) return true;
|
|
77
|
+
const rawParent = dirname(targetPath);
|
|
78
|
+
const parts = rawParent.split(/[\\/]+/);
|
|
79
|
+
let acc = rawParent.startsWith("/") ? "/" : /^[A-Za-z]:/.test(rawParent) ? parts[0] + "\\" : process.cwd();
|
|
80
|
+
const startIdx = rawParent.startsWith("/") ? 1 : /^[A-Za-z]:/.test(rawParent) ? 1 : 0;
|
|
81
|
+
for (let i = startIdx; i < parts.length; i++) {
|
|
82
|
+
const seg = parts[i];
|
|
83
|
+
if (!seg || seg === ".") continue;
|
|
84
|
+
acc = seg === ".." ? dirname(acc) : join(acc, seg);
|
|
85
|
+
const st = safeLstat(acc);
|
|
86
|
+
if (st) {
|
|
87
|
+
if (st.isSymbolicLink()) {
|
|
88
|
+
if (!isAllowedDarwinSystemSymlink(acc)) return false;
|
|
89
|
+
} else if (!st.isDirectory()) {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function hasSafeAncestorDirs(targetPath: string): boolean {
|
|
98
|
+
if (!hasSafeRawDotDotAncestors(targetPath)) return false;
|
|
99
|
+
let cur = dirname(resolve(targetPath));
|
|
100
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
101
|
+
const st = safeLstat(cur);
|
|
102
|
+
if (st) {
|
|
103
|
+
if (st.isSymbolicLink()) {
|
|
104
|
+
if (!isAllowedDarwinSystemSymlink(cur)) return false;
|
|
105
|
+
} else if (!st.isDirectory()) {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
const parent = dirname(cur);
|
|
110
|
+
if (parent === cur) break;
|
|
111
|
+
cur = parent;
|
|
112
|
+
}
|
|
113
|
+
return true;
|
|
114
|
+
}
|
|
25
115
|
|
|
26
116
|
export function safeWriteProfile(path: string, data: unknown, warn: Warn = defaultWarn): void {
|
|
117
|
+
const parentDir = dirname(path);
|
|
118
|
+
const parentStat = safeLstat(parentDir);
|
|
119
|
+
if (!parentStat || parentStat.isSymbolicLink() || !parentStat.isDirectory() || !hasSafeAncestorDirs(path)) {
|
|
120
|
+
throw new Error(`Refusing to write profile into invalid or symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const pathStat = safeLstat(path);
|
|
124
|
+
if (pathStat?.isSymbolicLink()) {
|
|
125
|
+
throw new Error(`Refusing to write profile through symlink: ${sanitizeWarnPart(path)}`);
|
|
126
|
+
}
|
|
127
|
+
|
|
27
128
|
const tmp = path + ".tmp";
|
|
28
129
|
|
|
29
|
-
// Residue from an earlier crash
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
130
|
+
// Residue from an earlier crash (including dangling symlinks where existsSync is false!)
|
|
131
|
+
// must be unlinked via lstatSync first so exclusive create (`wx`) always starts fresh at 0600.
|
|
132
|
+
const tmpStat = safeLstat(tmp);
|
|
133
|
+
if (tmpStat) {
|
|
134
|
+
try {
|
|
135
|
+
unlinkSync(tmp);
|
|
136
|
+
} catch (e) {
|
|
137
|
+
warn(`[agentchat] WARNING: stale ${sanitizeWarnPart(tmp)} could not be removed: ${sanitizeWarnPart(e)}\n`);
|
|
138
|
+
}
|
|
34
139
|
}
|
|
35
140
|
|
|
36
|
-
// Created fresh
|
|
37
|
-
writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 });
|
|
38
|
-
renameSync(tmp, path);
|
|
141
|
+
// Created fresh with exclusive `wx` → refuses symlinks/races and guarantees mode 0600 from instant of creation.
|
|
142
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600, flag: "wx" });
|
|
39
143
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
144
|
+
// Re-verify parent and target right before renameSync to narrow TOCTOU symlink swaps.
|
|
145
|
+
const currentParent = safeLstat(parentDir);
|
|
146
|
+
if (!currentParent || currentParent.isSymbolicLink() || !currentParent.isDirectory() || !hasSafeAncestorDirs(path)) {
|
|
147
|
+
try { unlinkSync(tmp); } catch {}
|
|
148
|
+
throw new Error(`Refusing to write profile into symlinked parent directory: ${sanitizeWarnPart(parentDir)}`);
|
|
149
|
+
}
|
|
150
|
+
if (safeLstat(path)?.isSymbolicLink()) {
|
|
151
|
+
try { unlinkSync(tmp); } catch {}
|
|
152
|
+
throw new Error(`Refusing to overwrite symlinked profile: ${sanitizeWarnPart(path)}`);
|
|
44
153
|
}
|
|
45
154
|
|
|
46
155
|
try {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
156
|
+
renameSync(tmp, path);
|
|
157
|
+
} catch (err: any) {
|
|
158
|
+
if (process.platform === "win32" && (err?.code === "EPERM" || err?.code === "EACCES")) {
|
|
159
|
+
// On Windows NTFS, antivirus or search indexers can momentarily hold `path` open,
|
|
160
|
+
// causing atomic MoveFileEx to return EPERM/EACCES. Fall back to copy+unlink when
|
|
161
|
+
// `path` is not a symlink or directory.
|
|
162
|
+
const winTarget = safeLstat(path);
|
|
163
|
+
if (winTarget?.isSymbolicLink() || winTarget?.isDirectory()) {
|
|
164
|
+
try { unlinkSync(tmp); } catch {}
|
|
165
|
+
throw new Error(`Refusing to overwrite symlinked or directory profile: ${sanitizeWarnPart(path)}`);
|
|
166
|
+
}
|
|
167
|
+
copyFileSync(tmp, path);
|
|
168
|
+
try {
|
|
169
|
+
unlinkSync(tmp);
|
|
170
|
+
} catch {}
|
|
171
|
+
} else {
|
|
172
|
+
throw err;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// POSIX mode bits (0600) do not exist on Windows NTFS (`statSync().mode & 0o777` is always 0666);
|
|
177
|
+
// Windows protects `%USERPROFILE%\.agentschat` via user-profile NTFS ACL inheritance instead.
|
|
178
|
+
if (process.platform !== "win32") {
|
|
179
|
+
const postStat = safeLstat(path);
|
|
180
|
+
if (!postStat || postStat.isSymbolicLink() || !postStat.isFile()) {
|
|
181
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target\n`);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
chmodSync(path, 0o600);
|
|
186
|
+
} catch (e) {
|
|
187
|
+
warn(`[agentchat] WARNING: could not chmod ${sanitizeWarnPart(path)} to 0600: ${sanitizeWarnPart(e)}\n`);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
try {
|
|
191
|
+
const verified = safeLstat(path);
|
|
192
|
+
if (!verified || verified.isSymbolicLink() || !verified.isFile()) {
|
|
193
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: non-regular target\n`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const mode = verified.mode & 0o777;
|
|
197
|
+
if (mode !== 0o600) {
|
|
198
|
+
warn(
|
|
199
|
+
`[agentchat] WARNING: ${sanitizeWarnPart(path)} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${sanitizeWarnPart(path)}\n`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
} catch (e) {
|
|
203
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${sanitizeWarnPart(path)}: ${sanitizeWarnPart(e)}\n`);
|
|
52
204
|
}
|
|
53
|
-
} catch (e) {
|
|
54
|
-
warn(`[agentchat] WARNING: could not verify permissions of ${path}: ${e}\n`);
|
|
55
205
|
}
|
|
56
206
|
}
|
|
57
207
|
|
|
@@ -63,13 +213,29 @@ export interface DefaultProfileCollision {
|
|
|
63
213
|
|
|
64
214
|
const NON_PROFILE_JSON_FILES = new Set([
|
|
65
215
|
"session-binds.json",
|
|
216
|
+
"session-binds.meta.json",
|
|
217
|
+
"session-binds-meta.json",
|
|
218
|
+
"session-binds_meta.json",
|
|
219
|
+
"agy-session-binds.json",
|
|
220
|
+
"agy-session-binds.meta.json",
|
|
221
|
+
"agy-session-binds_meta.json",
|
|
66
222
|
"agy-binds.json",
|
|
223
|
+
"agy-binds.meta.json",
|
|
224
|
+
"agy-binds-meta.json",
|
|
225
|
+
"agy-binds_meta.json",
|
|
67
226
|
"grok-binds.json",
|
|
68
227
|
"grok-binds-meta.json",
|
|
69
228
|
"grok-binds.meta.json",
|
|
229
|
+
"grok-binds_meta.json",
|
|
70
230
|
"identity-guard.json",
|
|
231
|
+
"cursor.json",
|
|
232
|
+
"read-cursors.json",
|
|
233
|
+
"mention-timestamps.json",
|
|
234
|
+
"wake-pids.json",
|
|
235
|
+
"codex-bots.json",
|
|
71
236
|
"dsh.json",
|
|
72
237
|
"config.json",
|
|
238
|
+
"muse.json",
|
|
73
239
|
]);
|
|
74
240
|
|
|
75
241
|
/**
|
|
@@ -82,42 +248,70 @@ export function findDefaultProfileCollision(
|
|
|
82
248
|
configDir: string,
|
|
83
249
|
defaultProfilePath: string,
|
|
84
250
|
): DefaultProfileCollision | null {
|
|
85
|
-
if (!defaultProfilePath || !
|
|
251
|
+
if (!defaultProfilePath || !hasSafeAncestorDirs(defaultProfilePath)) return null;
|
|
252
|
+
const defStat = safeLstat(defaultProfilePath);
|
|
253
|
+
if (!defStat || defStat.isSymbolicLink() || !defStat.isFile() || defStat.size > MAX_PROFILE_JSON_BYTES) {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
86
256
|
let defParsed: { agent_id?: unknown; display_name?: unknown; token?: unknown };
|
|
87
257
|
try {
|
|
88
258
|
defParsed = JSON.parse(readFileSync(defaultProfilePath, "utf8"));
|
|
89
259
|
} catch {
|
|
90
260
|
return null;
|
|
91
261
|
}
|
|
92
|
-
if (
|
|
262
|
+
if (
|
|
263
|
+
!defParsed ||
|
|
264
|
+
typeof defParsed !== "object" ||
|
|
265
|
+
Array.isArray(defParsed) ||
|
|
266
|
+
Object.prototype.hasOwnProperty.call(defParsed, "__proto__")
|
|
267
|
+
) {
|
|
268
|
+
return null;
|
|
269
|
+
}
|
|
93
270
|
const defAgentId = typeof defParsed.agent_id === "string" ? defParsed.agent_id.trim() : "";
|
|
94
271
|
const defDisplayName =
|
|
95
272
|
typeof defParsed.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
|
|
96
273
|
if (!defAgentId && !defDisplayName) return null;
|
|
97
274
|
|
|
275
|
+
const cfgStat = safeLstat(configDir);
|
|
276
|
+
if (!cfgStat || cfgStat.isSymbolicLink() || !cfgStat.isDirectory() || !hasSafeAncestorDirs(join(configDir, "probe"))) {
|
|
277
|
+
return null;
|
|
278
|
+
}
|
|
279
|
+
|
|
98
280
|
const resolvedDefault = resolve(defaultProfilePath);
|
|
99
281
|
for (const dir of [join(configDir, "profiles"), configDir]) {
|
|
100
|
-
|
|
282
|
+
const dirStat = safeLstat(dir);
|
|
283
|
+
if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) continue;
|
|
101
284
|
let files: string[] = [];
|
|
102
285
|
try {
|
|
103
|
-
files = readdirSync(dir).filter((f) =>
|
|
286
|
+
files = readdirSync(dir).filter((f) => /\.json$/i.test(f));
|
|
104
287
|
} catch {
|
|
105
288
|
continue;
|
|
106
289
|
}
|
|
107
290
|
for (const file of files) {
|
|
108
|
-
if (NON_PROFILE_JSON_FILES.has(file)) continue;
|
|
291
|
+
if (NON_PROFILE_JSON_FILES.has(file.toLowerCase())) continue;
|
|
109
292
|
const candidatePath = join(dir, file);
|
|
110
293
|
if (resolve(candidatePath) === resolvedDefault) continue;
|
|
111
|
-
const baseName = file.replace(/\.json
|
|
294
|
+
const baseName = file.replace(/\.json$/i, "");
|
|
112
295
|
if (baseName.toLowerCase() === "profile") continue;
|
|
113
296
|
|
|
297
|
+
const candStat = safeLstat(candidatePath);
|
|
298
|
+
if (!candStat || candStat.isSymbolicLink() || !candStat.isFile() || candStat.size > MAX_PROFILE_JSON_BYTES) {
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
114
301
|
let candidate: { agent_id?: unknown; display_name?: unknown; token?: unknown };
|
|
115
302
|
try {
|
|
116
303
|
candidate = JSON.parse(readFileSync(candidatePath, "utf8"));
|
|
117
304
|
} catch {
|
|
118
305
|
continue;
|
|
119
306
|
}
|
|
120
|
-
if (
|
|
307
|
+
if (
|
|
308
|
+
!candidate ||
|
|
309
|
+
typeof candidate !== "object" ||
|
|
310
|
+
Array.isArray(candidate) ||
|
|
311
|
+
Object.prototype.hasOwnProperty.call(candidate, "__proto__")
|
|
312
|
+
) {
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
121
315
|
const candAgentId = typeof candidate.agent_id === "string" ? candidate.agent_id.trim() : "";
|
|
122
316
|
const candToken = typeof candidate.token === "string" ? candidate.token.trim() : "";
|
|
123
317
|
if (!candAgentId || !candToken) continue;
|