@mwillbanks/ast-mcp 0.1.2 → 0.2.0
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/README.md +71 -22
- package/dist/ast-mcp.js +301 -101
- package/dist/ast-mcp.js.map +107 -27
- package/package.json +3 -1
- package/src/ast-bro/capability.ts +3 -8
- package/src/ast-bro/client.ts +18 -2
- package/src/ast-bro/result.ts +5 -12
- package/src/cli.ts +112 -13
- package/src/config-cli.ts +54 -0
- package/src/config.ts +886 -0
- package/src/helpers/aider.ts +252 -0
- package/src/helpers/ast-bro.ts +64 -0
- package/src/helpers/config.ts +149 -0
- package/src/helpers/hook.ts +60 -0
- package/src/helpers/installer.ts +249 -0
- package/src/helpers/json.ts +19 -0
- package/src/helpers/mcp-schema.ts +31 -0
- package/src/helpers/process.ts +31 -0
- package/src/helpers/string.ts +97 -0
- package/src/hook.ts +135 -40
- package/src/http-entry.ts +1 -1
- package/src/http.ts +118 -103
- package/src/installer-transport.ts +190 -0
- package/src/installer.ts +596 -235
- package/src/mcp-cli.ts +104 -0
- package/src/patch/aider.ts +6 -199
- package/src/patch/engine.ts +271 -197
- package/src/runtime/dependencies.ts +161 -8
- package/src/runtime/file-delete.ts +13 -9
- package/src/runtime/file-read.ts +91 -57
- package/src/runtime/file-rename.ts +158 -0
- package/src/runtime/format.ts +57 -34
- package/src/runtime/paths.ts +30 -16
- package/src/runtime/policy.ts +21 -0
- package/src/runtime/process-input.ts +14 -4
- package/src/service.ts +219 -0
- package/src/shell-policy.ts +331 -0
- package/src/stdio.ts +47 -35
- package/src/tools/ast-bro.ts +12 -6
- package/src/tools/configured.ts +28 -0
- package/src/tools/files.ts +24 -27
- package/src/tools/index.ts +5 -3
- package/src/tools/lifecycle.ts +69 -55
- package/templates/skills/ast-mcp/SKILL.md +7 -6
- package/templates/skills/ast-mcp/evals/batch.evals.json +48 -0
- package/templates/skills/ast-mcp/evals/evals.json +1 -0
- package/templates/skills/ast-mcp/evals/score.test.ts +175 -0
- package/templates/skills/ast-mcp/evals/score.ts +304 -267
- package/templates/skills/ast-mcp/evals/semantic.test.ts +322 -0
- package/templates/skills/ast-mcp/evals/semantic.ts +390 -135
- package/templates/skills/ast-mcp/evals/shell-policy.ts +252 -0
- package/templates/skills/ast-mcp/evals/source.test.ts +46 -0
- package/templates/skills/ast-mcp/evals/source.ts +164 -0
- package/templates/skills/ast-mcp/evals/trigger-queries.json +1 -1
- package/templates/skills/ast-mcp/references/installation.md +24 -11
- package/templates/skills/ast-mcp/references/patch-state-machine.md +5 -5
- package/templates/skills/ast-mcp/references/tool-catalog.md +4 -2
- package/templates/skills/ast-mcp/scripts/check-install.ts +312 -110
package/src/runtime/paths.ts
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
import { lstat, realpath } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { currentConfig } from "../config";
|
|
3
4
|
|
|
4
|
-
function configuredRoots(): string[] {
|
|
5
|
-
return (
|
|
6
|
-
process.env.AST_MCP_ROOTS?.split(path.delimiter).filter(Boolean) ?? [
|
|
7
|
-
process.cwd(),
|
|
8
|
-
]
|
|
9
|
-
).map((item) => path.resolve(item));
|
|
5
|
+
async function configuredRoots(): Promise<string[]> {
|
|
6
|
+
return (await currentConfig()).workspace.roots;
|
|
10
7
|
}
|
|
11
8
|
function within(root: string, target: string): boolean {
|
|
12
9
|
const relative = path.relative(root, target);
|
|
@@ -17,16 +14,23 @@ function within(root: string, target: string): boolean {
|
|
|
17
14
|
}
|
|
18
15
|
|
|
19
16
|
async function allowedRoots(): Promise<string[]> {
|
|
20
|
-
const
|
|
17
|
+
const config = await currentConfig();
|
|
21
18
|
const roots = await Promise.all(
|
|
22
|
-
configuredRoots().map(async (root) =>
|
|
19
|
+
(await configuredRoots()).map(async (root) =>
|
|
20
|
+
realpath(root).catch(() => root),
|
|
21
|
+
),
|
|
22
|
+
);
|
|
23
|
+
const trustedRoots = await Promise.all(
|
|
24
|
+
config.trustedRoots.map(async (root) => realpath(root).catch(() => root)),
|
|
23
25
|
);
|
|
24
26
|
if (
|
|
25
|
-
|
|
26
|
-
roots.some(
|
|
27
|
+
!config.safety.allowExternalRoots &&
|
|
28
|
+
roots.some(
|
|
29
|
+
(root) => !trustedRoots.some((trustedRoot) => within(trustedRoot, root)),
|
|
30
|
+
)
|
|
27
31
|
)
|
|
28
32
|
throw new Error(
|
|
29
|
-
"
|
|
33
|
+
"Configured workspace roots contain a root outside the trusted project boundary; set safety.allow_external_roots=true or AST_MCP_ALLOW_EXTERNAL_ROOTS=1 to opt in",
|
|
30
34
|
);
|
|
31
35
|
return roots;
|
|
32
36
|
}
|
|
@@ -43,6 +47,7 @@ export async function rootForPath(filePath: string): Promise<string> {
|
|
|
43
47
|
return root;
|
|
44
48
|
}
|
|
45
49
|
export async function resolveWritablePath(filePath: string): Promise<string> {
|
|
50
|
+
const config = await currentConfig();
|
|
46
51
|
const roots = await allowedRoots();
|
|
47
52
|
const absolute = path.isAbsolute(filePath)
|
|
48
53
|
? filePath
|
|
@@ -63,11 +68,20 @@ export async function resolveWritablePath(filePath: string): Promise<string> {
|
|
|
63
68
|
}
|
|
64
69
|
const resolved = path.join(existing, ...missing, path.basename(absolute));
|
|
65
70
|
if (!roots.some((root) => within(root, resolved)))
|
|
66
|
-
throw new Error(
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
71
|
+
throw new Error(
|
|
72
|
+
`Path is outside AST_MCP_ROOTS/configured workspace roots: ${filePath}`,
|
|
73
|
+
);
|
|
74
|
+
const metadata = await lstat(resolved).catch(() => undefined);
|
|
75
|
+
if (!metadata?.isSymbolicLink()) return resolved;
|
|
76
|
+
if (!config.safety.followSymlinks)
|
|
77
|
+
throw new Error(`Symbolic-link targets are not permitted: ${filePath}`);
|
|
78
|
+
const target = await realpath(resolved);
|
|
79
|
+
if (!roots.some((root) => within(root, target)))
|
|
80
|
+
throw new Error(
|
|
81
|
+
`Symbolic-link target is outside configured workspace roots: ${filePath}`,
|
|
82
|
+
);
|
|
83
|
+
return target;
|
|
70
84
|
}
|
|
71
|
-
export function rootsForDisplay(): string[] {
|
|
85
|
+
export async function rootsForDisplay(): Promise<string[]> {
|
|
72
86
|
return configuredRoots();
|
|
73
87
|
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { currentConfig } from "../config";
|
|
2
|
+
|
|
3
|
+
export async function requireExpectedHash(
|
|
4
|
+
expectedSha256: string | undefined,
|
|
5
|
+
operation: string,
|
|
6
|
+
): Promise<void> {
|
|
7
|
+
if (!expectedSha256 && (await currentConfig()).safety.requireHash)
|
|
8
|
+
throw new Error(
|
|
9
|
+
`${operation} requires expectedSha256 while safety.require_hash is enabled`,
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function verifyExpectedHash(
|
|
14
|
+
expectedSha256: string | undefined,
|
|
15
|
+
actualSha256: string,
|
|
16
|
+
): void {
|
|
17
|
+
if (expectedSha256 && expectedSha256 !== actualSha256)
|
|
18
|
+
throw new Error(
|
|
19
|
+
`Stale file context: expected ${expectedSha256}, found ${actualSha256}`,
|
|
20
|
+
);
|
|
21
|
+
}
|
|
@@ -3,21 +3,31 @@ export function runCommandInput(
|
|
|
3
3
|
command: string,
|
|
4
4
|
args: string[],
|
|
5
5
|
input: string,
|
|
6
|
+
options: { cwd?: string; timeoutMs?: number } = {},
|
|
6
7
|
): Promise<{ stdout: string; stderr: string }> {
|
|
8
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
7
9
|
return new Promise((resolve, reject) => {
|
|
8
10
|
const child = execFile(
|
|
9
11
|
command,
|
|
10
12
|
args,
|
|
11
|
-
{
|
|
13
|
+
{
|
|
14
|
+
cwd: options.cwd,
|
|
15
|
+
encoding: "utf8",
|
|
16
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
17
|
+
timeout: timeoutMs,
|
|
18
|
+
},
|
|
12
19
|
(error, stdout, stderr) => {
|
|
13
|
-
if (error)
|
|
20
|
+
if (error) {
|
|
21
|
+
const detail = (stderr || stdout || error.message).trim();
|
|
14
22
|
reject(
|
|
15
23
|
new Error(
|
|
16
|
-
|
|
24
|
+
error.killed
|
|
25
|
+
? `${command} timed out after ${timeoutMs}ms${detail ? `: ${detail}` : ""}`
|
|
26
|
+
: `${command} failed: ${detail}`,
|
|
17
27
|
{ cause: error },
|
|
18
28
|
),
|
|
19
29
|
);
|
|
20
|
-
else resolve({ stderr, stdout });
|
|
30
|
+
} else resolve({ stderr, stdout });
|
|
21
31
|
},
|
|
22
32
|
);
|
|
23
33
|
child.stdin?.end(input);
|
package/src/service.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, rm, writeFile } from "node:fs/promises";
|
|
3
|
+
import { createServer } from "node:net";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import type { HttpEndpoint } from "./installer-transport";
|
|
6
|
+
|
|
7
|
+
export type ServiceScope = "local" | "global";
|
|
8
|
+
export type ServiceCommandRunner = (
|
|
9
|
+
command: string[],
|
|
10
|
+
ignoreFailure?: boolean,
|
|
11
|
+
) => Promise<void>;
|
|
12
|
+
|
|
13
|
+
export interface ServiceOptions {
|
|
14
|
+
cliEntry: string;
|
|
15
|
+
endpoint: HttpEndpoint;
|
|
16
|
+
home: string;
|
|
17
|
+
platform?: NodeJS.Platform;
|
|
18
|
+
root: string;
|
|
19
|
+
runner?: ServiceCommandRunner;
|
|
20
|
+
scope: ServiceScope;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ServicePlan {
|
|
24
|
+
content: string;
|
|
25
|
+
file: string;
|
|
26
|
+
id: string;
|
|
27
|
+
installCommands: string[][];
|
|
28
|
+
removeCommands: string[][];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function xml(value: string) {
|
|
32
|
+
return value
|
|
33
|
+
.replaceAll("&", "&")
|
|
34
|
+
.replaceAll("<", "<")
|
|
35
|
+
.replaceAll(">", ">")
|
|
36
|
+
.replaceAll('"', """)
|
|
37
|
+
.replaceAll("'", "'");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function systemd(value: string) {
|
|
41
|
+
return value.replaceAll("\\", "\\\\").replaceAll('"', '\\"');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function serviceIdentity(scope: ServiceScope, root: string) {
|
|
45
|
+
if (scope === "global") return "ast-mcp";
|
|
46
|
+
const digest = createHash("sha256")
|
|
47
|
+
.update(path.resolve(root))
|
|
48
|
+
.digest("hex")
|
|
49
|
+
.slice(0, 12);
|
|
50
|
+
return `ast-mcp-${digest}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function createServicePlan(options: ServiceOptions): ServicePlan {
|
|
54
|
+
const platform = options.platform ?? process.platform;
|
|
55
|
+
if (platform === "win32")
|
|
56
|
+
throw new Error(
|
|
57
|
+
"Managed ast-mcp services are not supported on Windows; start `ast-mcp mcp --transport http` manually",
|
|
58
|
+
);
|
|
59
|
+
if (platform !== "darwin" && platform !== "linux")
|
|
60
|
+
throw new Error(
|
|
61
|
+
`Managed ast-mcp services are not supported on ${platform}; start the HTTP transport manually`,
|
|
62
|
+
);
|
|
63
|
+
const id = serviceIdentity(options.scope, options.root);
|
|
64
|
+
const args = [
|
|
65
|
+
options.cliEntry,
|
|
66
|
+
"mcp",
|
|
67
|
+
"--transport",
|
|
68
|
+
"http",
|
|
69
|
+
"--host",
|
|
70
|
+
options.endpoint.host,
|
|
71
|
+
"--port",
|
|
72
|
+
String(options.endpoint.port),
|
|
73
|
+
];
|
|
74
|
+
const environment =
|
|
75
|
+
options.scope === "local"
|
|
76
|
+
? { AST_MCP_PROJECT_ROOT: path.resolve(options.root) }
|
|
77
|
+
: {};
|
|
78
|
+
if (platform === "darwin") {
|
|
79
|
+
const label = `com.mwillbanks.${id}`;
|
|
80
|
+
const file = path.join(
|
|
81
|
+
options.home,
|
|
82
|
+
"Library/LaunchAgents",
|
|
83
|
+
`${label}.plist`,
|
|
84
|
+
);
|
|
85
|
+
const state = path.join(options.home, ".local/state/ast-mcp");
|
|
86
|
+
const programArguments = [process.execPath, ...args]
|
|
87
|
+
.map((value) => ` <string>${xml(value)}</string>`)
|
|
88
|
+
.join("\n");
|
|
89
|
+
const environmentVariables = Object.entries(environment)
|
|
90
|
+
.map(
|
|
91
|
+
([name, value]) =>
|
|
92
|
+
` <key>${xml(name)}</key>\n <string>${xml(value)}</string>`,
|
|
93
|
+
)
|
|
94
|
+
.join("\n");
|
|
95
|
+
const environmentBlock = environmentVariables
|
|
96
|
+
? `\n <key>EnvironmentVariables</key>\n <dict>\n${environmentVariables}\n </dict>`
|
|
97
|
+
: "";
|
|
98
|
+
const content = `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n <key>Label</key>\n <string>${label}</string>\n <key>ProgramArguments</key>\n <array>\n${programArguments}\n </array>${environmentBlock}\n <key>WorkingDirectory</key>\n <string>${xml(options.scope === "local" ? path.resolve(options.root) : options.home)}</string>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>StandardOutPath</key>\n <string>${xml(path.join(state, `${id}.out.log`))}</string>\n <key>StandardErrorPath</key>\n <string>${xml(path.join(state, `${id}.err.log`))}</string>\n</dict>\n</plist>\n`;
|
|
99
|
+
const domain = `gui/${typeof process.getuid === "function" ? process.getuid() : 501}`;
|
|
100
|
+
return {
|
|
101
|
+
content,
|
|
102
|
+
file,
|
|
103
|
+
id,
|
|
104
|
+
installCommands: [
|
|
105
|
+
["launchctl", "bootout", domain, file],
|
|
106
|
+
["launchctl", "bootstrap", domain, file],
|
|
107
|
+
["launchctl", "kickstart", "-k", `${domain}/${label}`],
|
|
108
|
+
],
|
|
109
|
+
removeCommands: [["launchctl", "bootout", domain, file]],
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const file = path.join(options.home, ".config/systemd/user", `${id}.service`);
|
|
113
|
+
const environmentLines = Object.entries(environment)
|
|
114
|
+
.map(([name, value]) => `Environment="${name}=${systemd(value)}"`)
|
|
115
|
+
.join("\n");
|
|
116
|
+
const command = [process.execPath, ...args]
|
|
117
|
+
.map((value) => `"${systemd(value)}"`)
|
|
118
|
+
.join(" ");
|
|
119
|
+
const workingDirectory = systemd(
|
|
120
|
+
options.scope === "local" ? path.resolve(options.root) : options.home,
|
|
121
|
+
);
|
|
122
|
+
const content = `[Unit]\nDescription=ast-mcp Streamable HTTP (${id})\nAfter=network.target\n\n[Service]\nType=simple\nWorkingDirectory="${workingDirectory}"\n${environmentLines ? `${environmentLines}\n` : ""}ExecStart=${command}\nRestart=on-failure\nRestartSec=2\n\n[Install]\nWantedBy=default.target\n`;
|
|
123
|
+
return {
|
|
124
|
+
content,
|
|
125
|
+
file,
|
|
126
|
+
id,
|
|
127
|
+
installCommands: [
|
|
128
|
+
["systemctl", "--user", "daemon-reload"],
|
|
129
|
+
["systemctl", "--user", "enable", "--now", `${id}.service`],
|
|
130
|
+
],
|
|
131
|
+
removeCommands: [
|
|
132
|
+
["systemctl", "--user", "disable", "--now", `${id}.service`],
|
|
133
|
+
],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function assertPortAvailable(endpoint: HttpEndpoint) {
|
|
138
|
+
const server = createServer();
|
|
139
|
+
try {
|
|
140
|
+
await new Promise<void>((resolve, reject) => {
|
|
141
|
+
server.once("error", reject);
|
|
142
|
+
server.listen(endpoint.port, endpoint.host, resolve);
|
|
143
|
+
});
|
|
144
|
+
} catch (error) {
|
|
145
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
146
|
+
throw new Error(
|
|
147
|
+
code === "EADDRINUSE"
|
|
148
|
+
? `Cannot install the managed service because ${endpoint.host}:${endpoint.port} is already in use`
|
|
149
|
+
: `Cannot bind managed service endpoint ${endpoint.host}:${endpoint.port}: ${error instanceof Error ? error.message : String(error)}`,
|
|
150
|
+
);
|
|
151
|
+
} finally {
|
|
152
|
+
if (server.listening)
|
|
153
|
+
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export const runServiceCommand: ServiceCommandRunner = async (
|
|
158
|
+
command,
|
|
159
|
+
ignoreFailure,
|
|
160
|
+
) => {
|
|
161
|
+
const child = Bun.spawn(command, { stderr: "pipe", stdout: "pipe" });
|
|
162
|
+
const [exitCode, stderr] = await Promise.all([
|
|
163
|
+
child.exited,
|
|
164
|
+
new Response(child.stderr).text(),
|
|
165
|
+
]);
|
|
166
|
+
if (exitCode !== 0 && !ignoreFailure)
|
|
167
|
+
throw new Error(
|
|
168
|
+
`Service command failed (${command.join(" ")}): ${stderr.trim() || `exit ${exitCode}`}`,
|
|
169
|
+
);
|
|
170
|
+
};
|
|
171
|
+
const defaultRunner = runServiceCommand;
|
|
172
|
+
|
|
173
|
+
export async function waitForService(url: string) {
|
|
174
|
+
for (let attempt = 0; attempt < 25; attempt += 1) {
|
|
175
|
+
try {
|
|
176
|
+
const response = await fetch(url);
|
|
177
|
+
if (response.status < 500) return;
|
|
178
|
+
} catch {
|
|
179
|
+
// The service may still be starting.
|
|
180
|
+
}
|
|
181
|
+
await Bun.sleep(100);
|
|
182
|
+
}
|
|
183
|
+
throw new Error(`Managed ast-mcp service did not become ready at ${url}`);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function preflightService(options: ServiceOptions) {
|
|
187
|
+
const plan = createServicePlan(options);
|
|
188
|
+
if (!(await lstat(plan.file).catch(() => undefined)))
|
|
189
|
+
await assertPortAvailable(options.endpoint);
|
|
190
|
+
return plan;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export async function installService(options: ServiceOptions) {
|
|
194
|
+
const plan = await preflightService(options);
|
|
195
|
+
const runner = options.runner ?? defaultRunner;
|
|
196
|
+
await mkdir(path.dirname(plan.file), { recursive: true });
|
|
197
|
+
if ((options.platform ?? process.platform) === "darwin")
|
|
198
|
+
await mkdir(path.join(options.home, ".local/state/ast-mcp"), {
|
|
199
|
+
recursive: true,
|
|
200
|
+
});
|
|
201
|
+
await writeFile(plan.file, plan.content);
|
|
202
|
+
for (let index = 0; index < plan.installCommands.length; index += 1)
|
|
203
|
+
await runner(
|
|
204
|
+
plan.installCommands[index],
|
|
205
|
+
index === 0 && plan.installCommands[index][0] === "launchctl",
|
|
206
|
+
);
|
|
207
|
+
if (!options.runner) await waitForService(options.endpoint.url);
|
|
208
|
+
return plan;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export async function removeService(options: ServiceOptions) {
|
|
212
|
+
const plan = createServicePlan(options);
|
|
213
|
+
const runner = options.runner ?? defaultRunner;
|
|
214
|
+
for (const command of plan.removeCommands) await runner(command, true);
|
|
215
|
+
await rm(plan.file, { force: true });
|
|
216
|
+
if ((options.platform ?? process.platform) === "linux")
|
|
217
|
+
await runner(["systemctl", "--user", "daemon-reload"], true);
|
|
218
|
+
return plan;
|
|
219
|
+
}
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { type Command, parse } from "unbash";
|
|
2
|
+
|
|
3
|
+
const mutators = new Set([
|
|
4
|
+
"apply_patch",
|
|
5
|
+
"patch",
|
|
6
|
+
"truncate",
|
|
7
|
+
"touch",
|
|
8
|
+
"rm",
|
|
9
|
+
"unlink",
|
|
10
|
+
"mv",
|
|
11
|
+
"rename",
|
|
12
|
+
"ed",
|
|
13
|
+
"set-content",
|
|
14
|
+
"add-content",
|
|
15
|
+
"clear-content",
|
|
16
|
+
"out-file",
|
|
17
|
+
"remove-item",
|
|
18
|
+
"move-item",
|
|
19
|
+
"new-item",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
const wrappers = new Set([
|
|
23
|
+
"env",
|
|
24
|
+
"command",
|
|
25
|
+
"builtin",
|
|
26
|
+
"exec",
|
|
27
|
+
"sudo",
|
|
28
|
+
"doas",
|
|
29
|
+
"nice",
|
|
30
|
+
"nohup",
|
|
31
|
+
"stdbuf",
|
|
32
|
+
"busybox",
|
|
33
|
+
"timeout",
|
|
34
|
+
"chrt",
|
|
35
|
+
]);
|
|
36
|
+
|
|
37
|
+
const wrapperValueOptions: Record<string, Set<string>> = {
|
|
38
|
+
doas: new Set([
|
|
39
|
+
"-u",
|
|
40
|
+
"-g",
|
|
41
|
+
"-p",
|
|
42
|
+
"-r",
|
|
43
|
+
"-t",
|
|
44
|
+
"-C",
|
|
45
|
+
"-D",
|
|
46
|
+
"-R",
|
|
47
|
+
"-T",
|
|
48
|
+
"--user",
|
|
49
|
+
"--group",
|
|
50
|
+
"--prompt",
|
|
51
|
+
"--role",
|
|
52
|
+
"--type",
|
|
53
|
+
"--close-from",
|
|
54
|
+
"--chdir",
|
|
55
|
+
"--chroot",
|
|
56
|
+
"--command-timeout",
|
|
57
|
+
]),
|
|
58
|
+
env: new Set(["-u", "-C", "--unset", "--chdir"]),
|
|
59
|
+
nice: new Set(["-n", "--adjustment"]),
|
|
60
|
+
sudo: new Set([
|
|
61
|
+
"-u",
|
|
62
|
+
"-g",
|
|
63
|
+
"-p",
|
|
64
|
+
"-r",
|
|
65
|
+
"-t",
|
|
66
|
+
"-C",
|
|
67
|
+
"-D",
|
|
68
|
+
"-R",
|
|
69
|
+
"-T",
|
|
70
|
+
"--user",
|
|
71
|
+
"--group",
|
|
72
|
+
"--prompt",
|
|
73
|
+
"--role",
|
|
74
|
+
"--type",
|
|
75
|
+
"--close-from",
|
|
76
|
+
"--chdir",
|
|
77
|
+
"--chroot",
|
|
78
|
+
"--command-timeout",
|
|
79
|
+
]),
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
function commandName(value = "") {
|
|
83
|
+
return value.split("/").at(-1)?.toLowerCase() ?? "";
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function skipWrapper(values: string[], index: number) {
|
|
87
|
+
const wrapper = commandName(values[index]);
|
|
88
|
+
let cursor = index + 1;
|
|
89
|
+
while (values[cursor]?.startsWith("-")) {
|
|
90
|
+
const option = values[cursor] as string;
|
|
91
|
+
cursor += wrapperValueOptions[wrapper]?.has(option) ? 2 : 1;
|
|
92
|
+
}
|
|
93
|
+
if (wrapper === "env")
|
|
94
|
+
while (/^[A-Za-z_][A-Za-z0-9_]*=/.test(values[cursor] ?? "")) cursor += 1;
|
|
95
|
+
if ((wrapper === "timeout" || wrapper === "chrt") && cursor < values.length)
|
|
96
|
+
cursor += 1;
|
|
97
|
+
return cursor;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function executable(command: Command) {
|
|
101
|
+
const values = [command.name, ...command.suffix].map(
|
|
102
|
+
(word) => word?.value ?? "",
|
|
103
|
+
);
|
|
104
|
+
let index = 0;
|
|
105
|
+
while (wrappers.has(commandName(values[index])))
|
|
106
|
+
index = skipWrapper(values, index);
|
|
107
|
+
return { args: values.slice(index + 1), name: commandName(values[index]) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function inlineMutates(source: string) {
|
|
111
|
+
const value = source.toLowerCase();
|
|
112
|
+
if (
|
|
113
|
+
[
|
|
114
|
+
"writefile(",
|
|
115
|
+
"writefilesync(",
|
|
116
|
+
"appendfile(",
|
|
117
|
+
"appendfilesync(",
|
|
118
|
+
"bun.write(",
|
|
119
|
+
"deno.write",
|
|
120
|
+
".write_text(",
|
|
121
|
+
".write_bytes(",
|
|
122
|
+
"unlink(",
|
|
123
|
+
"unlinksync(",
|
|
124
|
+
"rmsync(",
|
|
125
|
+
"truncate(",
|
|
126
|
+
"truncatesync(",
|
|
127
|
+
"mkdir(",
|
|
128
|
+
"rename(",
|
|
129
|
+
"renamesync(",
|
|
130
|
+
].some((marker) => value.includes(marker))
|
|
131
|
+
)
|
|
132
|
+
return true;
|
|
133
|
+
const opens = value.includes("open(") || value.includes("opensync(");
|
|
134
|
+
return (
|
|
135
|
+
opens &&
|
|
136
|
+
([', "w', ", 'w", ', "a', ", 'a", ', "x', ", 'x", ', "r+', ", 'r+"].some(
|
|
137
|
+
(marker) => value.includes(marker),
|
|
138
|
+
) ||
|
|
139
|
+
/\bmode\s*=\s*["'](?:[wax]|r\+)/.test(value))
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function payloadAfter(args: string[], flags: string[]) {
|
|
144
|
+
const index = args.findIndex(
|
|
145
|
+
(arg) =>
|
|
146
|
+
flags.includes(arg) || flags.some((flag) => arg.startsWith(`${flag}=`)),
|
|
147
|
+
);
|
|
148
|
+
if (index < 0) return undefined;
|
|
149
|
+
const argument = args[index];
|
|
150
|
+
const separator = argument.indexOf("=");
|
|
151
|
+
return separator >= 0 ? argument.slice(separator + 1) : args[index + 1];
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
type CommandMutationHandler = (args: string[]) => boolean;
|
|
155
|
+
|
|
156
|
+
function sedMutates(args: string[]) {
|
|
157
|
+
return args.some(
|
|
158
|
+
(arg) =>
|
|
159
|
+
arg === "--in-place" ||
|
|
160
|
+
arg.startsWith("--in-place=") ||
|
|
161
|
+
/^-[^-]*i/.test(arg),
|
|
162
|
+
);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function astGrepMutates(args: string[]) {
|
|
166
|
+
const rewrites = args.some(
|
|
167
|
+
(arg) => arg === "--rewrite" || arg.startsWith("--rewrite="),
|
|
168
|
+
);
|
|
169
|
+
return rewrites && args.some((arg) => arg === "-U" || arg === "--update-all");
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function findMutates(args: string[]) {
|
|
173
|
+
if (args.includes("-delete")) return true;
|
|
174
|
+
const action = args.findIndex((arg) =>
|
|
175
|
+
["-exec", "-execdir", "-ok", "-okdir"].includes(arg),
|
|
176
|
+
);
|
|
177
|
+
return action >= 0 && shellMutates(args.slice(action + 1).join(" "));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function shellInterpreterMutates(args: string[]) {
|
|
181
|
+
const grouped = args.findIndex((arg) => /^-[A-Za-z]*c[A-Za-z]*$/.test(arg));
|
|
182
|
+
const payload =
|
|
183
|
+
payloadAfter(args, ["-c", "--command", "-Command"]) ??
|
|
184
|
+
(grouped >= 0 ? args[grouped + 1] : undefined);
|
|
185
|
+
return payload ? shellMutates(payload) : false;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function inlineInterpreterMutates(name: string, args: string[]) {
|
|
189
|
+
const flags = name.startsWith("python") ? ["-c"] : ["-e", "--eval"];
|
|
190
|
+
const payload = payloadAfter(args, flags);
|
|
191
|
+
return payload ? inlineMutates(payload) : false;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const shellInterpreters = new Set([
|
|
195
|
+
"bash",
|
|
196
|
+
"sh",
|
|
197
|
+
"zsh",
|
|
198
|
+
"dash",
|
|
199
|
+
"ksh",
|
|
200
|
+
"fish",
|
|
201
|
+
"pwsh",
|
|
202
|
+
"powershell",
|
|
203
|
+
]);
|
|
204
|
+
const mutationHandlers: Record<string, CommandMutationHandler> = {
|
|
205
|
+
"ast-grep": astGrepMutates,
|
|
206
|
+
eval: (args) => shellMutates(args.join(" ")),
|
|
207
|
+
find: findMutates,
|
|
208
|
+
sed: sedMutates,
|
|
209
|
+
xargs: (args) => shellMutates(args.join(" ")),
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
function originalCommandDecision(
|
|
213
|
+
original: string,
|
|
214
|
+
args: string[],
|
|
215
|
+
): boolean | undefined {
|
|
216
|
+
if (
|
|
217
|
+
original === "command" &&
|
|
218
|
+
args.some((arg) => arg === "-v" || arg === "-V")
|
|
219
|
+
)
|
|
220
|
+
return false;
|
|
221
|
+
if (original !== "env") return undefined;
|
|
222
|
+
const dispatched = payloadAfter(args, ["-S", "--split-string"]);
|
|
223
|
+
return dispatched ? shellMutates(dispatched) : undefined;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function commandMutates(command: Command) {
|
|
227
|
+
const original = commandName(command.name?.value);
|
|
228
|
+
const originalArgs = command.suffix.map((word) => word.value);
|
|
229
|
+
const originalDecision = originalCommandDecision(original, originalArgs);
|
|
230
|
+
if (originalDecision !== undefined) return originalDecision;
|
|
231
|
+
const { args, name } = executable(command);
|
|
232
|
+
if (name === "git") return false;
|
|
233
|
+
if (mutators.has(name)) return true;
|
|
234
|
+
const handler = mutationHandlers[name];
|
|
235
|
+
if (handler) return handler(args);
|
|
236
|
+
if (shellInterpreters.has(name)) return shellInterpreterMutates(args);
|
|
237
|
+
if (/^(?:node|python\d*(?:\.\d+)*|ruby|perl|php|bun|deno)$/.test(name))
|
|
238
|
+
return inlineInterpreterMutates(name, args);
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function nodeChildren(value: Record<string, unknown>) {
|
|
243
|
+
const node = value as {
|
|
244
|
+
command?: unknown;
|
|
245
|
+
commands?: unknown[];
|
|
246
|
+
parts?: unknown[];
|
|
247
|
+
script?: unknown;
|
|
248
|
+
};
|
|
249
|
+
return [
|
|
250
|
+
node.script,
|
|
251
|
+
node.command,
|
|
252
|
+
...(node.commands ?? []),
|
|
253
|
+
...(node.parts ?? []),
|
|
254
|
+
];
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function visit(value: unknown): boolean {
|
|
258
|
+
if (!value || typeof value !== "object") return false;
|
|
259
|
+
if (Array.isArray(value)) return value.some(visit);
|
|
260
|
+
const node = value as { type?: string };
|
|
261
|
+
if (node.type === "Command" && commandMutates(value as Command)) return true;
|
|
262
|
+
if (nodeChildren(value as Record<string, unknown>).some(visit)) return true;
|
|
263
|
+
return Object.values(value).some(visit);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function shellMutates(source: string) {
|
|
267
|
+
if (source.length > 100_000) return false;
|
|
268
|
+
try {
|
|
269
|
+
const script = parse(source);
|
|
270
|
+
return script.errors?.length ? false : visit(script);
|
|
271
|
+
} catch {
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const embeddedKeys = new Set(["cmd", "command", "script", "source", "code"]);
|
|
277
|
+
|
|
278
|
+
function stringLiteral(source: string, start: number) {
|
|
279
|
+
const quote = source[start];
|
|
280
|
+
if (quote !== '"' && quote !== "'" && quote !== "`") return undefined;
|
|
281
|
+
let value = "";
|
|
282
|
+
for (let index = start + 1; index < source.length; index++) {
|
|
283
|
+
const character = source[index];
|
|
284
|
+
if (character === "\\" && index + 1 < source.length) {
|
|
285
|
+
value += source[++index];
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (character === quote) return { end: index + 1, value };
|
|
289
|
+
value += character;
|
|
290
|
+
}
|
|
291
|
+
return undefined;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
interface EmbeddedKey {
|
|
295
|
+
end: number;
|
|
296
|
+
key: string;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function embeddedKey(source: string, index: number): EmbeddedKey | undefined {
|
|
300
|
+
const literal = stringLiteral(source, index);
|
|
301
|
+
if (literal) return { end: literal.end, key: literal.value };
|
|
302
|
+
if (!/[A-Za-z_$]/.test(source[index] ?? "")) return undefined;
|
|
303
|
+
let end = index;
|
|
304
|
+
while (/[A-Za-z0-9_$]/.test(source[end] ?? "")) end += 1;
|
|
305
|
+
return { end, key: source.slice(index, end) };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function skipWhitespace(source: string, index: number) {
|
|
309
|
+
while (/\s/.test(source[index] ?? "")) index += 1;
|
|
310
|
+
return index;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function embeddedPayload(source: string, key: EmbeddedKey) {
|
|
314
|
+
let index = skipWhitespace(source, key.end);
|
|
315
|
+
if (source[index] !== ":") return undefined;
|
|
316
|
+
index = skipWhitespace(source, index + 1);
|
|
317
|
+
return stringLiteral(source, index)?.value;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
export function embeddedShellMutates(source: string) {
|
|
321
|
+
if (source.length > 100_000) return false;
|
|
322
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
323
|
+
const key = embeddedKey(source, index);
|
|
324
|
+
if (!key) continue;
|
|
325
|
+
index = key.end - 1;
|
|
326
|
+
if (!embeddedKeys.has(key.key)) continue;
|
|
327
|
+
const payload = embeddedPayload(source, key);
|
|
328
|
+
if (payload && shellMutates(payload)) return true;
|
|
329
|
+
}
|
|
330
|
+
return false;
|
|
331
|
+
}
|