Repository navigation
Expand file tree
/
Copy pathdeleteFiles.ts
More file actions
214 lines (187 loc) · 6.71 KB
/
Copy pathdeleteFiles.ts
File metadata and controls
214 lines (187 loc) · 6.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
/**
* mcp/skills/deleteFiles.ts — delete_files skill
*
* Permanently removes files and directories.
* Safety guards prevent deletion outside the user home directory and block
* known OS-critical paths. A dryRun mode lets Claude report impact first.
*
* IMPORTANT: Always obtain explicit user confirmation before calling this.
*
* Platform strategy
* -----------------
* Both fs.rm({ recursive, force }) — cross-platform Node.js
*
* Smoke test
* npx tsx -r dotenv/config mcp/skills/deleteFiles.ts
*/
import * as fs from "fs/promises";
import * as os from "os";
import * as nodePath from "path";
import { z } from "zod";
import { expandTilde } from "./_shared/expandTilde";
import { formatBytes } from "./_shared/formatBytes";
// -- Meta ---------------------------------------------------------------------
export const meta = {
name: "delete_files",
description:
"Permanently deletes the specified files or directories. " +
"ALWAYS obtain explicit user confirmation before calling. " +
"Restricted to paths within the user home directory. " +
"Use dryRun:true first to show the user what will be removed.",
riskLevel: "high",
destructive: true,
requiresConsent: true,
supportsDryRun: true,
affectedScope: ["user"],
auditRequired: true,
tccCategories: ["FullDiskAccess"],
// Acts only on explicitly enumerated paths and is idempotent on missing paths
// (a vanished path returns a per-path failure, never throws), so overlapping a
// cache sweeper is benign — exempt from the disjointness check.
footprint: { kind: "targeted" },
outputKeys: ["dryRun","deletedCount","freedBytes","freedHuman","items"],
schema: {
paths: z
.array(z.string().min(1))
.min(1)
.describe("Absolute paths of files or directories to delete."),
dryRun: z
.boolean()
.nullable().optional()
.describe(
"When true, reports what would be deleted without actually deleting. " +
"Default: false.",
),
},
} as const;
// -- Safety -------------------------------------------------------------------
const BLOCKED_DARWIN = new Set([
"/", "/usr", "/bin", "/sbin", "/etc", "/var",
"/System", "/Library", "/Applications", "/private", "/private/etc",
]);
const BLOCKED_WIN32 = [
"C:\\Windows",
"C:\\Program Files",
"C:\\Program Files (x86)",
"C:\\ProgramData",
"C:\\System Volume Information",
];
function assertSafe(target: string): void {
if (!nodePath.isAbsolute(target)) {
throw new Error(`Not an absolute path: ${target}`);
}
const platform = os.platform();
const home = os.homedir();
// Must be inside home directory
const rel = nodePath.relative(home, target);
if (rel.startsWith("..") || nodePath.isAbsolute(rel)) {
throw new Error(
`Path is outside home directory (${home}): ${target}. ` +
"delete_files only operates within the home directory.",
);
}
// Must not BE the home directory itself
if (rel === "") {
throw new Error(`Refusing to delete home directory itself: ${target}`);
}
// Must not be a known OS-critical path
if (platform === "win32") {
for (const blocked of BLOCKED_WIN32) {
if (target.toLowerCase().startsWith(blocked.toLowerCase())) {
throw new Error(`Refusing to delete system path: ${target}`);
}
}
} else {
if (BLOCKED_DARWIN.has(target)) {
throw new Error(`Refusing to delete system path: ${target}`);
}
}
}
// -- Helpers ------------------------------------------------------------------
// formatBytes is imported from _shared/formatBytes.
/** Recursively calculate the size of a directory or return file size. */
async function treeSize(target: string): Promise<number> {
let stat: Awaited<ReturnType<typeof fs.stat>>;
try {
stat = await fs.stat(target);
} catch {
return 0;
}
if (!stat.isDirectory()) return stat.size;
const children = await fs.readdir(target).catch(() => [] as string[]);
const sizes = await Promise.all(
children.map((c) => treeSize(nodePath.join(target, c))),
);
return sizes.reduce((a, b) => a + b, 0);
}
// -- Exported run function ----------------------------------------------------
export async function run({
paths,
dryRun = false,
}: {
paths: string[];
dryRun?: boolean;
}) {
const items = await Promise.all(
paths.map(async (p) => {
// Expand ~ / ~/ before resolve(): the executor LLM sometimes emits
// shorthand like "~/Downloads/foo.dmg". See _shared/expandTilde.ts.
const target = nodePath.resolve(expandTilde(p) ?? p);
// Safety check first
try {
assertSafe(target);
} catch (err) {
return {
path: target,
success: false,
error: (err as Error).message,
};
}
// Verify existence and guard against symlink-swap TOCTOU attacks.
// Using lstat (not stat) so we inspect the link itself, not its target.
// Refusing symlinks prevents an attacker from swapping a safe path for
// a symlink pointing at a critical file between our safety check and
// the actual fs.rm() call.
let entryStat: Awaited<ReturnType<typeof fs.lstat>>;
try {
entryStat = await fs.lstat(target);
} catch {
return { path: target, success: false, error: "Path does not exist or is not accessible." };
}
if (entryStat.isSymbolicLink()) {
return {
path: target,
success: false,
error: "Refusing to delete symbolic links. Resolve the link target and provide the real path.",
};
}
const sizeBytes = await treeSize(target);
if (dryRun) {
return { path: target, success: true, dryRun: true, sizeBytes, sizeHuman: formatBytes(sizeBytes) };
}
try {
await fs.rm(target, { recursive: true, force: true });
return { path: target, success: true, sizeBytes, sizeHuman: formatBytes(sizeBytes) };
} catch (err) {
return { path: target, success: false, error: (err as Error).message };
}
}),
);
const freedBytes = items
.filter((i) => i.success)
.reduce((sum, i) => sum + (i.sizeBytes ?? 0), 0);
return {
dryRun,
deletedCount: items.filter((i) => i.success && !i.dryRun).length,
freedBytes,
freedHuman: formatBytes(freedBytes),
items,
};
}
// -- CLI smoke test -----------------------------------------------------------
if (require.main === module) {
console.log("delete_files smoke test — dryRun mode only (no files actually deleted)");
run({ paths: [nodePath.join(os.homedir(), "nonexistent-test-file-xyz.tmp")], dryRun: true })
.then((r) => console.log(JSON.stringify(r, null, 2)))
.catch((err: Error) => { console.error(err.message); process.exit(1); });
}