kritya 0.8.21-beta → 0.8.23-beta
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/dist/agent/toolExecutor.js +33 -1
- package/dist/atomicWrite.js +16 -2
- package/dist/audit/audit.js +2 -2
- package/dist/config/config.js +118 -15
- package/dist/config/debug.js +30 -0
- package/dist/config/jsonSafety.js +69 -0
- package/dist/hooks/hooks.js +9 -2
- package/dist/index.js +7 -0
- package/dist/mcp/client.js +14 -35
- package/dist/mcp/eraDetect.js +17 -12
- package/dist/mcp/oauth.js +29 -7
- package/dist/mcp/servers.js +18 -3
- package/dist/mcp/transport.js +18 -8
- package/dist/mcp/transportModern.js +7 -2
- package/dist/net/urlSafety.js +89 -0
- package/dist/permissions/danger.js +41 -1
- package/dist/provider/client.js +5 -0
- package/dist/session/store.js +96 -13
- package/dist/shell/background.js +38 -3
- package/dist/telemetry/otlp.js +18 -7
- package/dist/telemetry/tracer.js +2 -2
- package/dist/tools/document/docx.js +6 -0
- package/dist/tools/document/pdf.js +22 -2
- package/dist/tools/document/pptx.js +5 -2
- package/dist/tools/document/xlsx.js +5 -20
- package/dist/tools/document/zipSafety.js +34 -0
- package/dist/tools/document.js +12 -0
- package/dist/tools/fetchUrl.js +22 -16
- package/dist/tools/notebook.js +13 -0
- package/dist/tools/shell.js +6 -1
- package/package.json +3 -2
package/dist/mcp/servers.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { sanitizeMcpServersRecord } from "../config/config.js";
|
|
4
|
+
import { assertJsonWithinLimits } from "../config/jsonSafety.js";
|
|
5
|
+
import { warnUser } from "../config/debug.js";
|
|
3
6
|
/**
|
|
4
7
|
* Where MCP server definitions come from and how they combine:
|
|
5
8
|
*
|
|
@@ -83,13 +86,23 @@ function isServerConfig(v) {
|
|
|
83
86
|
* degrade to "no project servers", not break startup.
|
|
84
87
|
*/
|
|
85
88
|
export function loadProjectMcpServers(workspace) {
|
|
86
|
-
|
|
89
|
+
const file = path.join(workspace, ".mcp.json");
|
|
90
|
+
let raw;
|
|
87
91
|
try {
|
|
88
|
-
|
|
92
|
+
raw = fs.readFileSync(file, "utf8");
|
|
89
93
|
}
|
|
90
94
|
catch {
|
|
91
95
|
return undefined;
|
|
92
96
|
}
|
|
97
|
+
let parsed;
|
|
98
|
+
try {
|
|
99
|
+
assertJsonWithinLimits(raw, ".mcp.json");
|
|
100
|
+
parsed = JSON.parse(raw);
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
warnUser(`loadProjectMcpServers(${file})`, err);
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
93
106
|
if (!parsed?.mcpServers || typeof parsed.mcpServers !== "object")
|
|
94
107
|
return undefined;
|
|
95
108
|
const servers = {};
|
|
@@ -97,7 +110,9 @@ export function loadProjectMcpServers(workspace) {
|
|
|
97
110
|
if (isServerConfig(cfg))
|
|
98
111
|
servers[name] = cfg;
|
|
99
112
|
}
|
|
100
|
-
|
|
113
|
+
if (!Object.keys(servers).length)
|
|
114
|
+
return undefined;
|
|
115
|
+
return sanitizeMcpServersRecord(servers, ".mcp.json mcpServers");
|
|
101
116
|
}
|
|
102
117
|
/**
|
|
103
118
|
* Combine plugin, project, and global server definitions, expanding ${VAR} in
|
package/dist/mcp/transport.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { McpAuthRequiredError, OAuthSession, parseWwwAuthenticate } from "./oauth.js";
|
|
3
3
|
import { planSpawn } from "./spawnWin.js";
|
|
4
|
+
import { pinnedDispatcherAllowLoopback } from "../net/urlSafety.js";
|
|
4
5
|
/** Same-origin redirects we'll follow before calling it a loop. */
|
|
5
6
|
const MAX_REDIRECTS = 5;
|
|
6
7
|
function isRedirect(status) {
|
|
@@ -212,7 +213,7 @@ export class HttpTransport {
|
|
|
212
213
|
let url = this.url;
|
|
213
214
|
// Bounded, because a redirect chain is otherwise a free loop.
|
|
214
215
|
for (let hop = 0;; hop++) {
|
|
215
|
-
const
|
|
216
|
+
const init = {
|
|
216
217
|
method: "POST",
|
|
217
218
|
headers: await this.buildHeaders(),
|
|
218
219
|
body,
|
|
@@ -224,7 +225,12 @@ export class HttpTransport {
|
|
|
224
225
|
// Cancelling has to tear the socket down too, or the request stays in
|
|
225
226
|
// flight for the full timeout after the user has walked away.
|
|
226
227
|
signal: withTimeout(timeoutMs, signal),
|
|
227
|
-
|
|
228
|
+
// DNS-pin every connection, not just the URL kritya validated once at
|
|
229
|
+
// server-config time — closes the DNS-rebinding gap between that
|
|
230
|
+
// check and the actual connect.
|
|
231
|
+
dispatcher: pinnedDispatcherAllowLoopback,
|
|
232
|
+
};
|
|
233
|
+
const res = await fetch(url, init);
|
|
228
234
|
if (!isRedirect(res.status))
|
|
229
235
|
return res;
|
|
230
236
|
const location = res.headers.get("location");
|
|
@@ -284,12 +290,16 @@ export class HttpTransport {
|
|
|
284
290
|
if (!this.sessionId)
|
|
285
291
|
return;
|
|
286
292
|
this.buildHeaders()
|
|
287
|
-
.then((headers) =>
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
+
.then((headers) => {
|
|
294
|
+
const init = {
|
|
295
|
+
method: "DELETE",
|
|
296
|
+
headers,
|
|
297
|
+
redirect: "manual",
|
|
298
|
+
signal: AbortSignal.timeout(3_000),
|
|
299
|
+
dispatcher: pinnedDispatcherAllowLoopback,
|
|
300
|
+
};
|
|
301
|
+
return fetch(this.url, init);
|
|
302
|
+
})
|
|
293
303
|
.catch(() => { });
|
|
294
304
|
}
|
|
295
305
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { McpAuthRequiredError, OAuthSession, parseWwwAuthenticate } from "./oauth.js";
|
|
2
2
|
import { withTimeout } from "./transport.js";
|
|
3
3
|
import { modernMeta, MODERN_PROTOCOL_VERSION } from "./eraDetect.js";
|
|
4
|
+
import { pinnedDispatcherAllowLoopback } from "../net/urlSafety.js";
|
|
4
5
|
/** Same-origin redirects we'll follow before calling it a loop. */
|
|
5
6
|
const MAX_REDIRECTS = 5;
|
|
6
7
|
/** How much of a server's stderr to keep for diagnostics, and how much to report. */
|
|
@@ -333,13 +334,17 @@ export class ModernHttpTransport {
|
|
|
333
334
|
const body = JSON.stringify(msg);
|
|
334
335
|
let url = this.url;
|
|
335
336
|
for (let hop = 0;; hop++) {
|
|
336
|
-
const
|
|
337
|
+
const init = {
|
|
337
338
|
method: "POST",
|
|
338
339
|
headers: await this.buildHeaders(msg),
|
|
339
340
|
body,
|
|
340
341
|
redirect: "manual",
|
|
341
342
|
signal: withTimeout(timeoutMs, signal),
|
|
342
|
-
|
|
343
|
+
// DNS-pin the connection so a rebind between server-config validation
|
|
344
|
+
// and this request can't redirect it to a private address.
|
|
345
|
+
dispatcher: pinnedDispatcherAllowLoopback,
|
|
346
|
+
};
|
|
347
|
+
const res = await fetch(url, init);
|
|
343
348
|
if (!isRedirect(res.status))
|
|
344
349
|
return res;
|
|
345
350
|
const location = res.headers.get("location");
|
package/dist/net/urlSafety.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { lookup as dnsLookup } from "node:dns/promises";
|
|
2
|
+
import { Agent } from "undici";
|
|
1
3
|
/**
|
|
2
4
|
* Shared "is this host on a private/internal network" check, used by both
|
|
3
5
|
* fetch_url (src/tools/fetchUrl.ts) and the MCP HTTP transport guard
|
|
@@ -156,3 +158,90 @@ export function isLoopbackHost(rawHost) {
|
|
|
156
158
|
return isLoopbackIPv6Groups(v6);
|
|
157
159
|
return false;
|
|
158
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Reject a URL reachable only over plaintext, or pointed at a private/
|
|
163
|
+
* internal address — the shared choke point for every URL kritya's own
|
|
164
|
+
* process fetches on the user's behalf with credentials attached (MCP
|
|
165
|
+
* server URLs, OAuth discovery/token/revocation endpoints, …). `label`
|
|
166
|
+
* identifies the source in the thrown error (a server name, "OAuth token
|
|
167
|
+
* endpoint", etc). Loopback is exempt from the https requirement: that's
|
|
168
|
+
* this app talking to itself, nothing on the wire to sniff.
|
|
169
|
+
*/
|
|
170
|
+
export function assertSafeUrl(label, url) {
|
|
171
|
+
let parsed;
|
|
172
|
+
try {
|
|
173
|
+
parsed = new URL(url);
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
throw new Error(`${label} has an invalid url: ${url}`);
|
|
177
|
+
}
|
|
178
|
+
// https alone doesn't mean the traffic (incl. any bearer token) stays
|
|
179
|
+
// where the caller intends — a URL pointing at 169.254.169.254 or another
|
|
180
|
+
// private/internal address would still ship credentials there.
|
|
181
|
+
if (!isLoopbackHost(parsed.hostname) && isPrivateOrLoopbackHost(parsed.hostname)) {
|
|
182
|
+
throw new Error(`${label} points at a private/internal address (${parsed.hostname}) — refusing to connect.`);
|
|
183
|
+
}
|
|
184
|
+
if (parsed.protocol === "https:")
|
|
185
|
+
return parsed;
|
|
186
|
+
if (parsed.protocol === "http:" && isLoopbackHost(parsed.hostname))
|
|
187
|
+
return parsed;
|
|
188
|
+
if (parsed.protocol !== "http:") {
|
|
189
|
+
throw new Error(`${label} uses unsupported scheme "${parsed.protocol}" — use https://`);
|
|
190
|
+
}
|
|
191
|
+
throw new Error(`${label} uses plain http:// (${parsed.host}), which would carry credentials in cleartext. ` +
|
|
192
|
+
`Use https:// (localhost is exempt).`);
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The actual SSRF boundary, shared by every outbound fetch kritya's own
|
|
196
|
+
* process makes on the user's behalf (fetch_url, MCP HTTP/SSE transports,
|
|
197
|
+
* OAuth discovery/registration/token/revocation, OTLP export): a connect-time
|
|
198
|
+
* `lookup` on a dedicated undici Agent, so the address that gets validated is
|
|
199
|
+
* the exact address the socket connects to — one DNS answer, not two.
|
|
200
|
+
* Checking a hostname once up front (assertSafeUrl) and letting `fetch`
|
|
201
|
+
* re-resolve it independently leaves a TOCTOU window: attacker-controlled or
|
|
202
|
+
* short-TTL DNS can answer differently the second time (DNS rebinding).
|
|
203
|
+
* Pinning the lookup closes that regardless of hop, hostname, or TTL.
|
|
204
|
+
*
|
|
205
|
+
* `isBlockedAddress` is pluggable because the two callers disagree on
|
|
206
|
+
* loopback: fetch_url refuses it outright (assertPublicUrl), while MCP
|
|
207
|
+
* servers and OAuth endpoints are routinely run locally during development
|
|
208
|
+
* and assertSafeUrl deliberately exempts loopback there. Each dispatcher
|
|
209
|
+
* instance holds no per-host state beyond ordinary connection pooling, so
|
|
210
|
+
* it's safe to share across every call site that uses the same policy.
|
|
211
|
+
*/
|
|
212
|
+
function createPinnedDispatcher(isBlockedAddress) {
|
|
213
|
+
return new Agent({
|
|
214
|
+
connect: {
|
|
215
|
+
lookup(hostname, options, callback) {
|
|
216
|
+
dnsLookup(hostname, { all: true })
|
|
217
|
+
.then((addresses) => {
|
|
218
|
+
if (addresses.length === 0) {
|
|
219
|
+
callback(new Error(`Could not resolve ${hostname}`), []);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const bad = addresses.find((a) => isBlockedAddress(a.address));
|
|
223
|
+
if (bad) {
|
|
224
|
+
callback(new Error(`Refusing to connect to ${hostname}: resolves to private/internal address ${bad.address}`), []);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
if (options.all) {
|
|
228
|
+
callback(null, addresses);
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
const chosen = addresses[0];
|
|
232
|
+
callback(null, chosen.address, chosen.family);
|
|
233
|
+
}
|
|
234
|
+
})
|
|
235
|
+
.catch((err) => callback(err, []));
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
/** For callers that never allow loopback either (fetch_url). */
|
|
241
|
+
export const pinnedDispatcher = createPinnedDispatcher(isPrivateOrLoopbackHost);
|
|
242
|
+
/**
|
|
243
|
+
* For callers that follow assertSafeUrl's policy: loopback is fine (a locally
|
|
244
|
+
* running MCP server or OAuth endpoint during development), other private/
|
|
245
|
+
* internal ranges are not.
|
|
246
|
+
*/
|
|
247
|
+
export const pinnedDispatcherAllowLoopback = createPinnedDispatcher((address) => !isLoopbackHost(address) && isPrivateOrLoopbackHost(address));
|
|
@@ -3,7 +3,31 @@
|
|
|
3
3
|
* matches, kritya forces a permission prompt with a warning even if the
|
|
4
4
|
* command would otherwise be covered by an allowlist rule or an "always allow"
|
|
5
5
|
* choice — so a blanket `shell(*)` allow can't silently run `rm -rf /`.
|
|
6
|
+
*
|
|
7
|
+
* This is pattern matching over command text, not a shell parser — it can
|
|
8
|
+
* only see danger words that actually appear in the string. It normalizes
|
|
9
|
+
* one specific evasion ($IFS in place of a space) and flags several ways of
|
|
10
|
+
* running an opaque payload (eval, base64 -d, an interpreter's -c/-e,
|
|
11
|
+
* PowerShell's -EncodedCommand), but a command that reassembles a dangerous
|
|
12
|
+
* word at runtime without those (e.g. `a=r;b=m;$a$b -rf /`, or piping
|
|
13
|
+
* through `tr`/`rev`) has no literal substring left to match and will not be
|
|
14
|
+
* caught. Sandboxing (src/shell/sandbox.ts) is the actual backstop for that
|
|
15
|
+
* gap, not a replacement for closing it here.
|
|
6
16
|
*/
|
|
17
|
+
/**
|
|
18
|
+
* `$IFS`/`${IFS}` in place of a literal space is a well-known filter-bypass
|
|
19
|
+
* trick (`rm${IFS}-rf${IFS}/` runs exactly like `rm -rf /`, but every
|
|
20
|
+
* pattern below that requires `\s+` between a command and its arguments
|
|
21
|
+
* never sees a whitespace character to match). Since this is purely a
|
|
22
|
+
* word-separator substitution — nothing about how the shell actually runs
|
|
23
|
+
* the command — normalizing it to a literal space before pattern matching
|
|
24
|
+
* catches the same commands the patterns already catch, without changing
|
|
25
|
+
* what any of them mean.
|
|
26
|
+
*/
|
|
27
|
+
const IFS_RE = /\$\{IFS[^}]*\}|\$IFS\b/g;
|
|
28
|
+
function normalizeForDangerCheck(command) {
|
|
29
|
+
return command.replace(IFS_RE, " ");
|
|
30
|
+
}
|
|
7
31
|
const PATTERNS = [
|
|
8
32
|
{
|
|
9
33
|
re: /\brm\s+.*(-[a-z]*[rf][a-z]*\b|--recursive\b|--force\b|--no-preserve-root\b)/i,
|
|
@@ -83,11 +107,27 @@ const PATTERNS = [
|
|
|
83
107
|
re: /\b(python3?|node|ruby|perl)\b\s+(-c|-e)\b/i,
|
|
84
108
|
label: "running an inline script (bypasses command-text inspection)",
|
|
85
109
|
},
|
|
110
|
+
{
|
|
111
|
+
// Shells' inline-command flag is -c specifically; unlike the
|
|
112
|
+
// interpreters above, -e means something else for a shell (errexit) and
|
|
113
|
+
// would false-positive on an ordinary `bash -e build.sh`.
|
|
114
|
+
re: /\b(bash|sh|zsh|dash|ksh)\b\s+-c\b/i,
|
|
115
|
+
label: "running an inline shell command (bypasses command-text inspection)",
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
// PowerShell accepts any unambiguous prefix of -EncodedCommand (-enc,
|
|
119
|
+
// -encodedcommand, ...); "en" is enough to disambiguate it from every
|
|
120
|
+
// other powershell.exe flag (-ExecutionPolicy starts "ex", not "en").
|
|
121
|
+
// This is the same base64-obfuscation evasion the generic `base64 -d`
|
|
122
|
+
// pattern above catches for POSIX shells, just spelled differently.
|
|
123
|
+
re: /\b(powershell(\.exe)?|pwsh)\b.*\s-en[a-z]*\b/i,
|
|
124
|
+
label: "running a base64-encoded PowerShell command (-EncodedCommand)",
|
|
125
|
+
},
|
|
86
126
|
{ re: /\bexec\s+\d*[<>]/i, label: "redirecting a shell's own file descriptors (exec)" },
|
|
87
127
|
];
|
|
88
128
|
/** Returns a human-readable danger label if the command is destructive, else null. */
|
|
89
129
|
export function classifyDanger(command) {
|
|
90
|
-
const cmd = command.trim();
|
|
130
|
+
const cmd = normalizeForDangerCheck(command.trim());
|
|
91
131
|
for (const { re, label } of PATTERNS) {
|
|
92
132
|
if (re.test(cmd))
|
|
93
133
|
return label;
|
package/dist/provider/client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import OpenAI from "openai";
|
|
2
2
|
import { NVIDIA_BASE_URL } from "../config/config.js";
|
|
3
|
+
import { assertSafeUrl } from "../net/urlSafety.js";
|
|
3
4
|
import { NOOP_TRACER } from "../telemetry/tracer.js";
|
|
4
5
|
import { recoverToolCalls } from "./textToolCalls.js";
|
|
5
6
|
/** Retry transient provider failures (429 / 5xx / network) with backoff. */
|
|
@@ -192,6 +193,10 @@ export class ProviderClient {
|
|
|
192
193
|
maxTokens;
|
|
193
194
|
streamIdleTimeoutMs;
|
|
194
195
|
constructor(apiKey, baseURL = NVIDIA_BASE_URL, sampling = {}, timeouts = {}) {
|
|
196
|
+
// Provider URLs can carry an API key, so apply the same scheme and
|
|
197
|
+
// private-network protections used by MCP HTTP endpoints before handing
|
|
198
|
+
// the URL to the SDK.
|
|
199
|
+
assertSafeUrl("provider base URL", baseURL);
|
|
195
200
|
// We do our own streaming-aware retry loop, so disable the SDK's.
|
|
196
201
|
this.client = new OpenAI({
|
|
197
202
|
apiKey,
|
package/dist/session/store.js
CHANGED
|
@@ -4,7 +4,56 @@ import path from "node:path";
|
|
|
4
4
|
import { writeFileAtomicSync } from "../atomicWrite.js";
|
|
5
5
|
import { CONFIG_DIR } from "../config/config.js";
|
|
6
6
|
import { hardenWindowsDir } from "../config/winAcl.js";
|
|
7
|
-
import { debugLog } from "../config/debug.js";
|
|
7
|
+
import { debugLog, warnUser } from "../config/debug.js";
|
|
8
|
+
/**
|
|
9
|
+
* A session file loaded whole into memory has no upper bound otherwise —
|
|
10
|
+
* `--continue` on a pathologically large transcript (corruption, a runaway
|
|
11
|
+
* write loop, or an adversarial file dropped into the session directory)
|
|
12
|
+
* would try to allocate the entire thing at once. Above this size, only the
|
|
13
|
+
* most recent bytes are read; older history is dropped rather than the
|
|
14
|
+
* resume failing outright.
|
|
15
|
+
*/
|
|
16
|
+
const MAX_SESSION_FILE_BYTES = 50 * 1024 * 1024;
|
|
17
|
+
/**
|
|
18
|
+
* Upper bound on a single message body persisted to a session file. Guards
|
|
19
|
+
* against a runaway model response or tool result ballooning the transcript
|
|
20
|
+
* — the live in-memory turn is unaffected, only what gets written to disk
|
|
21
|
+
* (and so what a future `loadFile` would have to hold in memory at once).
|
|
22
|
+
*/
|
|
23
|
+
const MAX_MESSAGE_CONTENT_CHARS = 2_000_000;
|
|
24
|
+
/** Cap `message.content` in place when it's a plain string over the limit. */
|
|
25
|
+
function capMessageContent(message) {
|
|
26
|
+
if (typeof message.content !== "string" || message.content.length <= MAX_MESSAGE_CONTENT_CHARS) {
|
|
27
|
+
return message;
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
...message,
|
|
31
|
+
content: message.content.slice(0, MAX_MESSAGE_CONTENT_CHARS) +
|
|
32
|
+
`\n... [truncated, ${message.content.length - MAX_MESSAGE_CONTENT_CHARS} more characters]`,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Read `filePath`, capped to the last `maxBytes` bytes when it exceeds that
|
|
37
|
+
* size. The byte cut can land mid-line, so the leading partial line is
|
|
38
|
+
* dropped — callers parse one JSON message per line and would otherwise
|
|
39
|
+
* choke on (or silently misparse) a truncated first line.
|
|
40
|
+
*/
|
|
41
|
+
export function readSessionFileCapped(filePath, maxBytes = MAX_SESSION_FILE_BYTES) {
|
|
42
|
+
const size = fs.statSync(filePath).size;
|
|
43
|
+
if (size <= maxBytes)
|
|
44
|
+
return fs.readFileSync(filePath, "utf8");
|
|
45
|
+
const fd = fs.openSync(filePath, "r");
|
|
46
|
+
try {
|
|
47
|
+
const buffer = Buffer.alloc(maxBytes);
|
|
48
|
+
fs.readSync(fd, buffer, 0, maxBytes, size - maxBytes);
|
|
49
|
+
const text = buffer.toString("utf8");
|
|
50
|
+
const firstNewline = text.indexOf("\n");
|
|
51
|
+
return firstNewline === -1 ? "" : text.slice(firstNewline + 1);
|
|
52
|
+
}
|
|
53
|
+
finally {
|
|
54
|
+
fs.closeSync(fd);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
8
57
|
function sessionDir(workspace) {
|
|
9
58
|
const hash = crypto.createHash("sha1").update(workspace).digest("hex").slice(0, 12);
|
|
10
59
|
return path.join(CONFIG_DIR, "sessions", hash);
|
|
@@ -78,7 +127,7 @@ export class SessionStore {
|
|
|
78
127
|
writeSessionFile(this.tasksFilePath(), JSON.stringify(tasks));
|
|
79
128
|
}
|
|
80
129
|
catch (err) {
|
|
81
|
-
|
|
130
|
+
warnUser(`SessionStore.saveTasks(${this.tasksFilePath()})`, err);
|
|
82
131
|
}
|
|
83
132
|
}
|
|
84
133
|
/** Loads the task checklist saved alongside a given session file, if any. */
|
|
@@ -106,7 +155,7 @@ export class SessionStore {
|
|
|
106
155
|
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
107
156
|
hardenWindowsDir(CONFIG_DIR);
|
|
108
157
|
if (seed.length) {
|
|
109
|
-
writeSessionFile(this.file, seed.map((m) => JSON.stringify(m) + "\n").join(""));
|
|
158
|
+
writeSessionFile(this.file, seed.map((m) => JSON.stringify(capMessageContent(m)) + "\n").join(""));
|
|
110
159
|
}
|
|
111
160
|
}
|
|
112
161
|
/**
|
|
@@ -123,11 +172,13 @@ export class SessionStore {
|
|
|
123
172
|
try {
|
|
124
173
|
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
125
174
|
hardenWindowsDir(CONFIG_DIR);
|
|
126
|
-
fs.appendFileSync(this.file, JSON.stringify(message) + "\n", {
|
|
175
|
+
fs.appendFileSync(this.file, JSON.stringify(capMessageContent(message)) + "\n", {
|
|
176
|
+
mode: 0o600,
|
|
177
|
+
});
|
|
127
178
|
}
|
|
128
179
|
catch (err) {
|
|
129
180
|
// Persistence is best-effort; never crash the session over it.
|
|
130
|
-
|
|
181
|
+
warnUser(`SessionStore.append(${this.file})`, err);
|
|
131
182
|
}
|
|
132
183
|
}
|
|
133
184
|
/** Start over with a fresh session file (used by /clear). */
|
|
@@ -146,11 +197,11 @@ export class SessionStore {
|
|
|
146
197
|
try {
|
|
147
198
|
fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 });
|
|
148
199
|
hardenWindowsDir(CONFIG_DIR);
|
|
149
|
-
writeSessionFile(this.file, messages.map((m) => JSON.stringify(m) + "\n").join(""));
|
|
200
|
+
writeSessionFile(this.file, messages.map((m) => JSON.stringify(capMessageContent(m)) + "\n").join(""));
|
|
150
201
|
}
|
|
151
202
|
catch (err) {
|
|
152
203
|
// Persistence is best-effort; never crash the session over it.
|
|
153
|
-
|
|
204
|
+
warnUser(`SessionStore.overwrite(${this.file})`, err);
|
|
154
205
|
}
|
|
155
206
|
}
|
|
156
207
|
/**
|
|
@@ -159,21 +210,53 @@ export class SessionStore {
|
|
|
159
210
|
* accept a session path from outside the process (e.g. the Electron
|
|
160
211
|
* renderer over IPC) must check this before loading it: without it,
|
|
161
212
|
* "load this session" is really "read any file the OS user can read".
|
|
213
|
+
*
|
|
214
|
+
* The lexical check (path.relative on the unresolved names) only rules out
|
|
215
|
+
* `..` segments in the string itself — it doesn't notice a symlink planted
|
|
216
|
+
* inside the session directory that points somewhere else entirely. Such a
|
|
217
|
+
* symlink would have a path that lexically resolves inside the session dir
|
|
218
|
+
* while the filesystem happily follows it out. Canonicalizing with
|
|
219
|
+
* fs.realpathSync and re-checking containment against that catches it: a
|
|
220
|
+
* symlink escaping the directory resolves to a real path outside it and
|
|
221
|
+
* gets rejected, exactly like an out-of-tree file would.
|
|
162
222
|
*/
|
|
163
223
|
static isSessionFile(workspace, filePath) {
|
|
164
224
|
const dir = sessionDir(workspace);
|
|
165
225
|
const resolved = path.resolve(dir, filePath);
|
|
166
226
|
const relative = path.relative(dir, resolved);
|
|
167
|
-
|
|
168
|
-
relative
|
|
169
|
-
|
|
170
|
-
|
|
227
|
+
if (!resolved.endsWith(".jsonl") ||
|
|
228
|
+
relative === "" ||
|
|
229
|
+
relative.startsWith("..") ||
|
|
230
|
+
path.isAbsolute(relative)) {
|
|
231
|
+
return false;
|
|
232
|
+
}
|
|
233
|
+
let realDir;
|
|
234
|
+
let realFile;
|
|
235
|
+
try {
|
|
236
|
+
realDir = fs.realpathSync(dir);
|
|
237
|
+
realFile = fs.realpathSync(resolved);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// Doesn't exist, or a component along the way isn't accessible —
|
|
241
|
+
// either way there's nothing real to load.
|
|
242
|
+
return false;
|
|
243
|
+
}
|
|
244
|
+
const realRelative = path.relative(realDir, realFile);
|
|
245
|
+
if (realRelative === "" || realRelative.startsWith("..") || path.isAbsolute(realRelative)) {
|
|
246
|
+
return false;
|
|
247
|
+
}
|
|
248
|
+
try {
|
|
249
|
+
return fs.statSync(realFile).isFile();
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
171
254
|
}
|
|
172
255
|
static loadFile(filePath) {
|
|
173
256
|
const messages = [];
|
|
174
257
|
let raw;
|
|
175
258
|
try {
|
|
176
|
-
raw =
|
|
259
|
+
raw = readSessionFileCapped(filePath);
|
|
177
260
|
}
|
|
178
261
|
catch {
|
|
179
262
|
return messages;
|
|
@@ -194,7 +277,7 @@ export class SessionStore {
|
|
|
194
277
|
static readLines(filePath) {
|
|
195
278
|
let raw;
|
|
196
279
|
try {
|
|
197
|
-
raw =
|
|
280
|
+
raw = readSessionFileCapped(filePath);
|
|
198
281
|
}
|
|
199
282
|
catch {
|
|
200
283
|
return [];
|
package/dist/shell/background.js
CHANGED
|
@@ -2,7 +2,10 @@ import { spawn } from "node:child_process";
|
|
|
2
2
|
import os from "node:os";
|
|
3
3
|
import { scrubbedShellEnv } from "../config/config.js";
|
|
4
4
|
import { buildSandboxedCommand, requiresSandbox, sandboxUnavailableReason, shouldSandbox, } from "./sandbox.js";
|
|
5
|
+
import { redactSecrets } from "../tools/secretScan.js";
|
|
5
6
|
const MAX_BUFFER_CHARS = 50_000;
|
|
7
|
+
const MAX_COMPLETED_PROCESSES = 100;
|
|
8
|
+
const COMPLETED_PROCESS_RETENTION_MS = 5 * 60_000;
|
|
6
9
|
/**
|
|
7
10
|
* Registry of long-running processes the agent started with shell
|
|
8
11
|
* background:true (dev servers, watchers). Captures a rolling tail of
|
|
@@ -54,9 +57,19 @@ class BackgroundManager {
|
|
|
54
57
|
// approach) mis-parses commands that themselves contain quotes.
|
|
55
58
|
proc = spawn(command, { ...spawnOpts, shell: true });
|
|
56
59
|
}
|
|
57
|
-
|
|
60
|
+
// Keep secrets out of the long-lived registry. The child still receives
|
|
61
|
+
// the original command, but the retained command is redacted.
|
|
62
|
+
const entry = {
|
|
63
|
+
proc,
|
|
64
|
+
command: redactSecrets(command).redacted,
|
|
65
|
+
buffer: "",
|
|
66
|
+
exitCode: null,
|
|
67
|
+
running: true,
|
|
68
|
+
};
|
|
58
69
|
const append = (chunk) => {
|
|
59
|
-
|
|
70
|
+
// Re-scan the rolling buffer so a secret split across stream chunks is
|
|
71
|
+
// redacted before it is retained.
|
|
72
|
+
entry.buffer = redactSecrets(entry.buffer + chunk.toString()).redacted;
|
|
60
73
|
if (entry.buffer.length > MAX_BUFFER_CHARS) {
|
|
61
74
|
entry.buffer = entry.buffer.slice(-MAX_BUFFER_CHARS);
|
|
62
75
|
}
|
|
@@ -68,21 +81,43 @@ class BackgroundManager {
|
|
|
68
81
|
proc.on("exit", (code) => {
|
|
69
82
|
entry.running = false;
|
|
70
83
|
entry.exitCode = code;
|
|
84
|
+
entry.finishedAt = Date.now();
|
|
71
85
|
proc.stdout?.destroy();
|
|
72
86
|
proc.stderr?.destroy();
|
|
73
87
|
cleanup?.();
|
|
88
|
+
this.scheduleCleanup(id, entry);
|
|
74
89
|
});
|
|
75
90
|
proc.on("error", (err) => {
|
|
76
91
|
entry.running = false;
|
|
77
|
-
entry.
|
|
92
|
+
entry.finishedAt = Date.now();
|
|
93
|
+
entry.buffer = redactSecrets(`${entry.buffer}\n[failed to start: ${err.message}]`).redacted;
|
|
78
94
|
// If the sandbox binary itself fails to spawn, "exit" may never fire, so
|
|
79
95
|
// the macOS temp profile would leak. cleanup is fs.rm({force:true}),
|
|
80
96
|
// which is idempotent, so running it from both handlers is safe.
|
|
81
97
|
cleanup?.();
|
|
98
|
+
this.scheduleCleanup(id, entry);
|
|
82
99
|
});
|
|
83
100
|
this.procs.set(id, entry);
|
|
101
|
+
this.pruneCompleted();
|
|
84
102
|
return { id };
|
|
85
103
|
}
|
|
104
|
+
scheduleCleanup(id, entry) {
|
|
105
|
+
const timer = setTimeout(() => {
|
|
106
|
+
if (this.procs.get(id) === entry && !entry.running)
|
|
107
|
+
this.procs.delete(id);
|
|
108
|
+
}, COMPLETED_PROCESS_RETENTION_MS);
|
|
109
|
+
timer.unref();
|
|
110
|
+
this.pruneCompleted();
|
|
111
|
+
}
|
|
112
|
+
pruneCompleted() {
|
|
113
|
+
const completed = [...this.procs.entries()]
|
|
114
|
+
.filter(([, entry]) => !entry.running)
|
|
115
|
+
.sort(([, a], [, b]) => (a.finishedAt ?? 0) - (b.finishedAt ?? 0));
|
|
116
|
+
while (completed.length > MAX_COMPLETED_PROCESSES) {
|
|
117
|
+
const [id] = completed.shift();
|
|
118
|
+
this.procs.delete(id);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
86
121
|
signal(entry, sig) {
|
|
87
122
|
try {
|
|
88
123
|
if (os.platform() !== "win32" && entry.proc.pid) {
|
package/dist/telemetry/otlp.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { warnUser } from "../config/debug.js";
|
|
2
|
+
import { assertSafeUrl, pinnedDispatcherAllowLoopback, } from "../net/urlSafety.js";
|
|
2
3
|
function toAnyValue(value) {
|
|
3
4
|
if (typeof value === "string")
|
|
4
5
|
return { stringValue: value };
|
|
@@ -97,14 +98,21 @@ export function encodeMetricsSnapshot(points, resource) {
|
|
|
97
98
|
*/
|
|
98
99
|
export function postOtlp(endpoint, path, body, headers) {
|
|
99
100
|
try {
|
|
100
|
-
|
|
101
|
+
// Same DNS-pinning + private-address policy as MCP server URLs and OAuth
|
|
102
|
+
// endpoints (loopback ok, other private ranges refused): KRITYA_OTEL_ENDPOINT
|
|
103
|
+
// is user config, not attacker input, but there's no reason this one
|
|
104
|
+
// outbound path should be less protected than the others.
|
|
105
|
+
const url = assertSafeUrl("OTLP endpoint", `${endpoint.replace(/\/+$/, "")}${path}`);
|
|
106
|
+
const init = {
|
|
101
107
|
method: "POST",
|
|
102
108
|
headers: { "content-type": "application/json", ...(headers ?? {}) },
|
|
103
109
|
body: JSON.stringify(body),
|
|
104
|
-
|
|
110
|
+
dispatcher: pinnedDispatcherAllowLoopback,
|
|
111
|
+
};
|
|
112
|
+
fetch(url.href, init).catch((err) => warnUser(`postOtlp(${path})`, err));
|
|
105
113
|
}
|
|
106
114
|
catch (err) {
|
|
107
|
-
|
|
115
|
+
warnUser(`postOtlp(${path})`, err);
|
|
108
116
|
}
|
|
109
117
|
}
|
|
110
118
|
/**
|
|
@@ -116,13 +124,16 @@ export function postOtlp(endpoint, path, body, headers) {
|
|
|
116
124
|
*/
|
|
117
125
|
export async function postOtlpAndWait(endpoint, path, body, headers) {
|
|
118
126
|
try {
|
|
119
|
-
|
|
127
|
+
const url = assertSafeUrl("OTLP endpoint", `${endpoint.replace(/\/+$/, "")}${path}`);
|
|
128
|
+
const init = {
|
|
120
129
|
method: "POST",
|
|
121
130
|
headers: { "content-type": "application/json", ...(headers ?? {}) },
|
|
122
131
|
body: JSON.stringify(body),
|
|
123
|
-
|
|
132
|
+
dispatcher: pinnedDispatcherAllowLoopback,
|
|
133
|
+
};
|
|
134
|
+
await fetch(url.href, init);
|
|
124
135
|
}
|
|
125
136
|
catch (err) {
|
|
126
|
-
|
|
137
|
+
warnUser(`postOtlpAndWait(${path})`, err);
|
|
127
138
|
}
|
|
128
139
|
}
|
package/dist/telemetry/tracer.js
CHANGED
|
@@ -3,7 +3,7 @@ import fs from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { CONFIG_DIR } from "../config/config.js";
|
|
5
5
|
import { hardenWindowsDir } from "../config/winAcl.js";
|
|
6
|
-
import { debugLog } from "../config/debug.js";
|
|
6
|
+
import { debugLog, warnUser } from "../config/debug.js";
|
|
7
7
|
import { VERSION } from "../version.js";
|
|
8
8
|
import { encodeSpan, postOtlp } from "./otlp.js";
|
|
9
9
|
function nowUnixNano() {
|
|
@@ -158,7 +158,7 @@ function fileSink(file) {
|
|
|
158
158
|
}
|
|
159
159
|
catch (err) {
|
|
160
160
|
// best-effort: telemetry must never crash a turn
|
|
161
|
-
|
|
161
|
+
warnUser(`tracer.fileSink(${file})`, err);
|
|
162
162
|
}
|
|
163
163
|
};
|
|
164
164
|
}
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import mammoth from "mammoth";
|
|
2
2
|
import { Document, HeadingLevel, Packer, Paragraph, TextRun } from "docx";
|
|
3
3
|
import { validateBlocks } from "./types.js";
|
|
4
|
+
import { loadSafeZip } from "./zipSafety.js";
|
|
4
5
|
export async function readDocx(buf) {
|
|
6
|
+
// .docx is a zip container, and mammoth decompresses every entry with no
|
|
7
|
+
// size limit — same decompression-bomb exposure as .xlsx (see
|
|
8
|
+
// zipSafety.ts). Validate declared uncompressed size before handing the
|
|
9
|
+
// buffer to mammoth.
|
|
10
|
+
await loadSafeZip(buf);
|
|
5
11
|
const result = await mammoth.extractRawText({ buffer: buf });
|
|
6
12
|
return result.value;
|
|
7
13
|
}
|