dsh-delete-guard 0.0.0-stage → 2.2.3

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/lib/index.js ADDED
@@ -0,0 +1,389 @@
1
+ /**
2
+ * dsh-delete-guard — force every DSH file deletion through the OS Recycle Bin.
3
+ *
4
+ * Where this hooks
5
+ * ----------------
6
+ * `tools/pre-execute` (a waterfall on `ctx.tools`). That is the seam DSH 0.1.7
7
+ * actually routes every model tool call through, and `PreToolDecision` there can
8
+ * return `{ kind: 'deny' }`.
9
+ *
10
+ * It deliberately does NOT monkey-patch the shell executor. `ctx.shell` in 0.1.7
11
+ * is a `ShellExecutor` with only `resolve()` and `execute()`; there is no
12
+ * `run()`/`start()` to wrap, so a wrapper installed there is never consulted and
13
+ * every delete proceeds unguarded while appearing protected.
14
+ *
15
+ * What it does with a delete
16
+ * --------------------------
17
+ * A recognised delete is not merely denied: the operands are parsed out and the
18
+ * call is denied with a message instructing the model to re-issue the deletion
19
+ * through the `file_trash` tool this plugin registers, which performs a real
20
+ * `SHFileOperationW(FOF_ALLOWUNDO)` move. Pre-execute cannot rewrite arguments
21
+ * (`ToolExecution.arguments` is frozen and already logged), so denial plus a
22
+ * redirect is the correct shape.
23
+ *
24
+ * Known limits, stated honestly
25
+ * -----------------------------
26
+ * A delete executed *inside* a script body is not rewritten. `blockScriptDeletes`
27
+ * denies inline `-Command`/`-File`/`-e` invocations that contain delete verbs,
28
+ * but a script file whose contents the guard never sees can still erase data if
29
+ * the model writes one and runs it by a path that contains no delete verb. The
30
+ * system-prompt section asks the model not to; that part is guidance, not a
31
+ * guarantee.
32
+ */
33
+
34
+ import { stat } from 'node:fs/promises';
35
+ import { classifyCommand } from './guard.js';
36
+ import { recyclePaths, recycleBinUsage } from './recycle.js';
37
+ import { validateTrashTarget, workspaceRootReason } from './move-guard.js';
38
+
39
+ export const name = 'delete-guard';
40
+ export const inject = ['tools', 'systemPrompt'];
41
+
42
+ /** Tool name the model must use for every deletion. */
43
+ const TRASH_TOOL = 'file_trash';
44
+ /** Tool name for reporting recycle-bin state. */
45
+ const STATUS_TOOL = 'trash_status';
46
+ /** System-prompt section identifier. */
47
+ const PROMPT_SECTION = 'delete-guard';
48
+ /** Ordering hint for the prompt section. */
49
+ const PROMPT_ORDER = 60;
50
+
51
+ /**
52
+ * Tools that carry a shell command, and where the command text lives.
53
+ *
54
+ * The guard used to look at `pwsh` and `bash` only, which left DSH's persistent
55
+ * terminal uncovered: `terminal_send` types a command into a live PTY, so it
56
+ * never passes through either shell tool. Measured 2026-10-23 in this install —
57
+ * `terminal_send` ran `Remove-Item …` while the guard sat on the same call path
58
+ * and said nothing.
59
+ *
60
+ * `dialect` decides two rules: `$( … )` opacity (pwsh-only) and POSIX path
61
+ * translation (bash-only). A terminal session does not say which shell it is, so
62
+ * it is judged as `pwsh` — that refuses more, not less.
63
+ */
64
+ const SHELL_TOOLS = new Map([
65
+ ['pwsh', { field: 'command', dialect: 'pwsh' }],
66
+ ['powershell', { field: 'command', dialect: 'pwsh' }],
67
+ ['cmd', { field: 'command', dialect: 'pwsh' }],
68
+ ['bash', { field: 'command', dialect: 'bash' }],
69
+ ['sh', { field: 'command', dialect: 'bash' }],
70
+ ['zsh', { field: 'command', dialect: 'bash' }],
71
+ ['shell', { field: 'command', dialect: 'bash' }],
72
+ ['terminal_send', { field: 'text', dialect: 'pwsh' }],
73
+ ['terminal_write', { field: 'text', dialect: 'pwsh' }],
74
+ ]);
75
+
76
+ /**
77
+ * Reject an empty path list before any I/O.
78
+ * @param paths - candidate paths.
79
+ * @returns the non-empty trimmed list.
80
+ */
81
+ function cleanPaths(paths) {
82
+ if (!Array.isArray(paths)) return [];
83
+ return paths
84
+ .filter((p) => typeof p === 'string')
85
+ .map((p) => p.trim())
86
+ .filter((p) => p.length > 0);
87
+ }
88
+
89
+ /**
90
+ * Resolve the workspace root the sandbox policy reports, falling back to the
91
+ * process working directory. The fallback matters: without a sandbox service
92
+ * the `file_trash` path would have no root to compare against, and the guard
93
+ * would silently lose its workspace check.
94
+ * @param ctx - the Cordis context.
95
+ * @returns an absolute path, or `undefined` when nothing resolved.
96
+ */
97
+ function resolveWorkspaceRoot(ctx) {
98
+ try {
99
+ const value = ctx.sandboxPolicy?.resolve?.({})?.workspaceRoot;
100
+ if (typeof value === 'string' && value.trim().length > 0) return value;
101
+ } catch {
102
+ // Absent or misbehaving policy service: fall back rather than skip the check.
103
+ }
104
+ return process.cwd();
105
+ }
106
+
107
+ /**
108
+ * Plugin entry point.
109
+ * @param ctx - the Cordis context.
110
+ * @param config - plugin configuration.
111
+ */
112
+ export function apply(ctx, config = {}) {
113
+ if (config.enabled === false) return;
114
+
115
+ const {
116
+ blockDestructiveCommands = true,
117
+ forbidEmptyRecycleBin = true,
118
+ forbidWipe = true,
119
+ blockScriptDeletes = true,
120
+ } = config;
121
+
122
+ const guardOptions = { forbidEmptyRecycleBin, forbidWipe, blockScriptDeletes };
123
+ const workspaceRoot = resolveWorkspaceRoot(ctx);
124
+
125
+ // --- 1. Intercept destructive shell commands ------------------------------
126
+
127
+ if (blockDestructiveCommands) {
128
+ ctx.on('tools/pre-execute', async (exec, next) => {
129
+ // Only the tools that carry a shell command: the two shell tools plus the
130
+ // persistent terminal, which types into a live PTY.
131
+ const spec = SHELL_TOOLS.get(exec.name);
132
+ if (spec === undefined) return next();
133
+
134
+ const args = exec.arguments;
135
+ if (args === null || typeof args !== 'object') return next();
136
+ const command = args[spec.field];
137
+ if (typeof command !== 'string') return next();
138
+
139
+ const verdict = classifyCommand(command, {
140
+ ...guardOptions,
141
+ // The tool name identifies the shell language, which decides
142
+ // dialect-scoped rules such as `$( … )` and POSIX path translation.
143
+ dialect: spec.dialect,
144
+ });
145
+
146
+ if (verdict.action === 'allow') return next();
147
+
148
+ if (verdict.action === 'deny') {
149
+ return {
150
+ kind: 'deny',
151
+ reason: verdict.reason,
152
+ info: { name: 'DeleteGuardError', code: `DELETE_GUARD_${verdict.kind.toUpperCase()}` },
153
+ };
154
+ }
155
+
156
+ // action === 'rewrite': steer the model to the recoverable path.
157
+ const list = verdict.targets.map((t) => `"${t}"`).join(', ');
158
+ return {
159
+ kind: 'deny',
160
+ reason:
161
+ `The recycle-bin guard blocked this delete. Deleting through the shell erases files permanently, ` +
162
+ `so all deletions must go through the ${TRASH_TOOL} tool, which moves them to the OS Recycle Bin ` +
163
+ `where they stay recoverable.\n\n` +
164
+ `Re-run this as: ${TRASH_TOOL} with paths = [${list}]\n\n` +
165
+ `If those paths are wrong or you meant a different target, read the directory first and re-issue ` +
166
+ `the call with explicit literal paths.`,
167
+ info: { name: 'DeleteGuardError', code: 'DELETE_GUARD_REWRITE' },
168
+ };
169
+ });
170
+ }
171
+
172
+ // --- 2. The tool the model must use instead -------------------------------
173
+
174
+ ctx.tools.register({
175
+ name: TRASH_TOOL,
176
+ description:
177
+ 'Delete files or directories by moving them to the OS Recycle Bin, where they remain recoverable. ' +
178
+ 'This is the only permitted way to delete anything. Never use pwsh/bash with Remove-Item, del, rm, rd or rmdir. ' +
179
+ 'The operation fails loudly rather than falling back to a permanent erase.',
180
+ // `ctx.tools.register` passes parameters through verbatim (only `defineTool`
181
+ // compiles the flat DSL), so hand-write standard JSON Schema here — the
182
+ // model endpoint rejects the un-compiled flat map with 11129.
183
+ parameters: {
184
+ type: 'object',
185
+ additionalProperties: false,
186
+ properties: {
187
+ paths: {
188
+ type: 'array',
189
+ description: 'Absolute or workspace-relative paths to move to the Recycle Bin.',
190
+ items: { type: 'string' },
191
+ },
192
+ reason: {
193
+ type: 'string',
194
+ description: 'Optional short note on why these paths are being deleted.',
195
+ },
196
+ },
197
+ required: ['paths'],
198
+ },
199
+ output: {
200
+ // Raw JSON Schema (not the authoring DSL): `required` is an object-only
201
+ // key here. It must be an array of property names on the object, never a
202
+ // per-node flag — the host rejects `required` on array/string nodes.
203
+ schema: {
204
+ type: 'object',
205
+ additionalProperties: false,
206
+ required: ['recycled', 'failures'],
207
+ properties: {
208
+ recycled: { type: 'array', items: { type: 'string' } },
209
+ failures: {
210
+ type: 'array',
211
+ items: {
212
+ type: 'object',
213
+ additionalProperties: false,
214
+ required: ['path', 'error'],
215
+ properties: {
216
+ path: { type: 'string' },
217
+ error: { type: 'string' },
218
+ },
219
+ },
220
+ },
221
+ },
222
+ },
223
+ render: (_args, value) => {
224
+ const lines = [];
225
+ if (value.recycled.length > 0) {
226
+ lines.push(`Moved to the Recycle Bin (${value.recycled.length}):`);
227
+ for (const p of value.recycled) lines.push(` ${p}`);
228
+ }
229
+ if (value.failures.length > 0) {
230
+ lines.push(`Failed (${value.failures.length}):`);
231
+ for (const f of value.failures) lines.push(` ${f.path}: ${f.error}`);
232
+ }
233
+ if (lines.length === 0) lines.push('Nothing was deleted: no usable paths were provided.');
234
+ lines.push('');
235
+ lines.push('These items are recoverable from the Recycle Bin; they were not permanently erased.');
236
+ return [{ type: 'text', text: lines.join('\n') }];
237
+ },
238
+ },
239
+ async execute(args, exec) {
240
+ const paths = cleanPaths(args.paths);
241
+ if (paths.length === 0) {
242
+ return {
243
+ recycled: [],
244
+ failures: [{ path: '(none)', error: 'no usable paths were supplied' }],
245
+ };
246
+ }
247
+
248
+ const cwd = exec.agent?.session?.cwd ?? process.cwd();
249
+
250
+ // The shell-side guard can only police deletes the model runs through
251
+ // pwsh/bash. A direct file_trash call has no command text to scan, so the
252
+ // operands are policed here: resolve each one, refuse the filesystem
253
+ // roots whose Recycle Bin store lives inside them, and refuse the session
254
+ // workspace root. See move-guard.js for why a "recoverable" excuse does
255
+ // not cover these.
256
+ const absolute = [];
257
+ const failures = [];
258
+ for (const raw of paths) {
259
+ const verdict = validateTrashTarget(raw, cwd);
260
+ if (!verdict.ok) {
261
+ failures.push({ path: raw, error: verdict.error });
262
+ continue;
263
+ }
264
+ const rootReason = workspaceRootReason(verdict.path, workspaceRoot);
265
+ if (rootReason !== undefined) {
266
+ failures.push({ path: verdict.path, error: rootReason });
267
+ continue;
268
+ }
269
+ // Verify existence up front so a typo is reported as a missing path
270
+ // rather than as a shell-level failure.
271
+ try {
272
+ await stat(verdict.path);
273
+ absolute.push(verdict.path);
274
+ } catch {
275
+ failures.push({ path: verdict.path, error: 'no such file or directory' });
276
+ }
277
+ }
278
+
279
+ if (absolute.length === 0) {
280
+ return { recycled: [], failures };
281
+ }
282
+
283
+ const result = await recyclePaths(absolute, { signal: exec.signal });
284
+ return {
285
+ recycled: result.recycled,
286
+ failures: [...failures, ...result.failures],
287
+ };
288
+ },
289
+ });
290
+
291
+ // --- 3. Recycle-bin reporting --------------------------------------------
292
+
293
+ ctx.tools.register({
294
+ name: STATUS_TOOL,
295
+ description:
296
+ 'Report how many items and bytes currently sit in the OS Recycle Bin for a drive. ' +
297
+ 'Use this to confirm deletions landed in the bin rather than being erased.',
298
+ parameters: {
299
+ type: 'object',
300
+ additionalProperties: false,
301
+ properties: {
302
+ drive: {
303
+ type: 'string',
304
+ description: 'Drive letter like "C:" or "D:". Defaults to the system drive.',
305
+ },
306
+ },
307
+ },
308
+ output: {
309
+ schema: {
310
+ type: 'object',
311
+ additionalProperties: false,
312
+ required: ['drive', 'items', 'bytes'],
313
+ properties: {
314
+ drive: { type: 'string' },
315
+ items: { type: 'integer' },
316
+ bytes: { type: 'integer' },
317
+ },
318
+ },
319
+ render: (_args, value) => [
320
+ {
321
+ type: 'text',
322
+ // `drive` already carries its colon when it came from the caller
323
+ // (`F:`), so appending another one printed "Recycle Bin on F::".
324
+ text: `Recycle Bin on ${String(value.drive).replace(/:+$/, '')}: ${value.items} item(s), ${formatBytes(value.bytes)}.`,
325
+ },
326
+ ],
327
+ },
328
+ async execute(args, exec) {
329
+ const drive = typeof args.drive === 'string' && args.drive.trim().length > 0
330
+ ? args.drive.trim()
331
+ : undefined;
332
+ const usage = await recycleBinUsage(drive, { signal: exec.signal });
333
+ return { drive: drive ?? '(system drive)', items: usage.items, bytes: usage.bytes };
334
+ },
335
+ });
336
+
337
+ // --- 4. System-prompt guidance -------------------------------------------
338
+
339
+ try {
340
+ ctx.systemPrompt.section({
341
+ name: PROMPT_SECTION,
342
+ order: PROMPT_ORDER,
343
+ text: [
344
+ '## Deletion policy: OS Recycle Bin only',
345
+ '',
346
+ `Every deletion must go through the \`${TRASH_TOOL}\` tool. It moves the target into the OS Recycle Bin,`,
347
+ 'so the user can recover it. Items deleted any other way are gone for good.',
348
+ '',
349
+ `- Do NOT run \`Remove-Item\`, \`del\`, \`erase\`, \`rd\`, \`rmdir\`, \`rm\`, \`unlink\` or \`rd\` through pwsh/bash.`,
350
+ ` The recycle-bin guard blocks them and returns an error telling you to use \`${TRASH_TOOL}\`. That includes`,
351
+ ' commands typed into a persistent terminal (`terminal_send`), which is judged the same way.',
352
+ '- In a Git Bash session, pass paths to `file_trash` as Windows paths (`C:\\tmp\\x`), not POSIX ones.',
353
+ ' `/c/tmp/x` is translated to `C:\\tmp\\x` for you; `~` and other mount points (`/tmp`, `/usr`) are refused.',
354
+ '- Do NOT empty or modify the Recycle Bin (`Clear-RecycleBin` in any form — bare, `&`, inside a',
355
+ ' child shell, or encoded; `SHEmptyRecycleBin`; driving the bin items\' own shell verbs; walking',
356
+ ' `$Recycle.Bin`). All of those are blocked.',
357
+ '- Restoring a deleted item is allowed: read the `$I` record under `C:\\$Recycle.Bin\\<SID>\\` for the',
358
+ ' original path and move the paired `$R` file back. Do not use the bin items\' shell verbs to do it.',
359
+ '- Do NOT use permanent-erase tools (`shred`, `sdelete`, `srm`, `cipher /w`). That is blocked.',
360
+ '- Do NOT put deletions inside shell scripts or inline `-Command` / `-e` strings; they cannot be',
361
+ ' routed to the Recycle Bin and will be refused.',
362
+ `- To overwrite a file, prefer the \`write\` / \`edit\` tools. Use \`${TRASH_TOOL}\` only when a path must go away.`,
363
+ `- \`${STATUS_TOOL}\` reports current bin occupancy if you need to confirm a deletion landed.`,
364
+ ].join('\n'),
365
+ });
366
+ } catch (error) {
367
+ // A host without the system-prompt service still gets the enforcement half.
368
+ ctx.logger?.warn?.('delete-guard: systemPrompt section not registered:', error.message);
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Format a byte count for display.
374
+ * @param bytes - the count.
375
+ * @returns a human-readable string.
376
+ */
377
+ function formatBytes(bytes) {
378
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes)) return 'unknown';
379
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
380
+ let value = bytes;
381
+ let unit = 0;
382
+ while (value >= 1024 && unit < units.length - 1) {
383
+ value /= 1024;
384
+ unit += 1;
385
+ }
386
+ return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`;
387
+ }
388
+
389
+ export { classifyCommand } from './guard.js';
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Operand guard for the `file_trash` tool path.
3
+ *
4
+ * `guard.js` polices the *shell* side: a delete command the model tries to run
5
+ * through pwsh/bash is denied and redirected here. This module polices the
6
+ * landing side — the model calling `file_trash` directly, which no shell
7
+ * interception sees.
8
+ *
9
+ * Both reach the Recycle Bin, so a bare "recycling is recoverable" argument
10
+ * would make this redundant. It is not: the Windows Recycle Bin is *not*
11
+ * exempt from the paths below. Recycle Bin storage lives on the same volume
12
+ * it serves, so recycling `C:\` moves the contents of `C:\$Recycle.Bin` into
13
+ * `C:\$Recycle.Bin` — undefined behaviour at best, and the OS may simply
14
+ * complete the erase. A drive root, the Windows directory, and a reparse
15
+ * point to a parent all fall in that class.
16
+ *
17
+ * Pure: no I/O, no ctx, directly unit-testable.
18
+ */
19
+
20
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
21
+
22
+ /**
23
+ * Recycle Bin storage directory at the root of any volume.
24
+ *
25
+ * Judged *after* stripping the drive prefix rather than with one anchored
26
+ * pattern: `resolve()` yields `C:\$Recycle.Bin`, so a rule anchored on a
27
+ * leading separator would only ever match `\`-relative text and silently pass
28
+ * every absolute path. The ancestor form `C:\RECYCLER` (pre-Vista, still
29
+ * present on some volumes) is refused for the same reason.
30
+ *
31
+ * @param p - a normalized absolute path.
32
+ * @returns whether the path names that directory or sits inside it.
33
+ */
34
+ function isRecycleBinStorage(p) {
35
+ const driveLess = /^[a-z]:/i.test(p) ? p.slice(2) : p;
36
+ return /^[\\/]+(?:\$recycle\.bin|recycler)(?:[\\/]|$)/i.test(driveLess);
37
+ }
38
+
39
+ /**
40
+ * Paths the filesystem itself treats as roots, where recycling is meaningless
41
+ * or actively destructive to the bin's own store.
42
+ * @param p - a normalized absolute path.
43
+ * @returns the refusal reason, or `undefined` when the path is acceptable.
44
+ */
45
+ function forbiddenReason(p) {
46
+ if (/^[a-z]:[\\/]?$/i.test(p)) return 'a drive root';
47
+ if (/^[\\/]+$/.test(p)) return 'the filesystem root';
48
+ if (/^[a-z]:[\\/]windows(?:[\\/]|$)/i.test(p)) return 'the Windows directory';
49
+ if (/^[a-z]:[\\/]program files(?: \(x86\))?(?:[\\/]|$)/i.test(p)) return 'Program Files';
50
+ if (isRecycleBinStorage(p)) return 'the Recycle Bin storage directory itself';
51
+ return undefined;
52
+ }
53
+
54
+ /**
55
+ * Resolve and validate one model-supplied trash target.
56
+ *
57
+ * `..` segments are resolved rather than rejected: the resulting path is what
58
+ * the guard judges, so `..\..` cannot smuggle an operand past the root checks.
59
+ * A `..` that escapes the volume root collapses onto the root itself, which the
60
+ * drive-root rule then catches.
61
+ *
62
+ * @param raw - the path as written by the model.
63
+ * @param cwd - the session working directory, used for relative operands.
64
+ * @returns `{ ok: true, path }` with an absolute path, or `{ ok: false, error }`.
65
+ */
66
+ export function validateTrashTarget(raw, cwd) {
67
+ const text = typeof raw === 'string' ? raw.trim() : '';
68
+ if (text.length === 0) return { ok: false, error: 'empty path' };
69
+
70
+ let absolute;
71
+ try {
72
+ absolute = isAbsolute(text) ? resolve(text) : resolve(cwd ?? process.cwd(), text);
73
+ } catch (error) {
74
+ return { ok: false, error: `unresolvable path: ${error.message}` };
75
+ }
76
+
77
+ const reason = forbiddenReason(absolute);
78
+ if (reason !== undefined) {
79
+ return { ok: false, error: `refusing to recycle ${reason}: "${absolute}"` };
80
+ }
81
+
82
+ return { ok: true, path: absolute };
83
+ }
84
+
85
+ /**
86
+ * Whether `child` sits strictly beneath `parent`.
87
+ * @param child - the candidate descendant.
88
+ * @param parent - the candidate ancestor.
89
+ * @returns whether `child` is inside `parent` and is not `parent` itself.
90
+ */
91
+ function isStrictlyWithin(child, parent) {
92
+ const rel = relative(parent, child);
93
+ return rel !== '' && !rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel);
94
+ }
95
+
96
+ /**
97
+ * Reject an attempt to recycle the session workspace root or one of its
98
+ * ancestors: that removes the directory the session is operating in, and no
99
+ * later turn can restore its own working context from the bin alone.
100
+ *
101
+ * Deliberately narrow. Deleting *inside* the workspace is the ordinary case and
102
+ * stays allowed — an earlier revision rejected anything under the root, which
103
+ * would have made the tool useless rather than safe.
104
+ *
105
+ * A missing `workspaceRoot` disables this half only; the root rules in
106
+ * {@link validateTrashTarget} are unconditional.
107
+ *
108
+ * @param target - an absolute path already accepted by {@link validateTrashTarget}.
109
+ * @param workspaceRoot - the sandbox policy's workspace root, when one resolved.
110
+ * @returns the refusal reason, or `undefined` when the target is acceptable.
111
+ */
112
+ export function workspaceRootReason(target, workspaceRoot) {
113
+ if (typeof workspaceRoot !== 'string' || workspaceRoot.trim().length === 0) return undefined;
114
+
115
+ let root;
116
+ try {
117
+ root = resolve(workspaceRoot);
118
+ } catch {
119
+ return undefined;
120
+ }
121
+
122
+ if (target === root) return `refusing to recycle the session workspace root itself: "${target}"`;
123
+ if (isStrictlyWithin(root, target)) {
124
+ return `refusing to recycle a parent of the session workspace: "${target}"`;
125
+ }
126
+ return undefined;
127
+ }
package/lib/recycle.js ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Windows Recycle Bin bridge.
3
+ *
4
+ * Moving a file to the Recycle Bin is not a rename: the shell maintains a
5
+ * per-volume `$Recycle.Bin\<sid>\` store plus `$I`/`$R` metadata pairs. Doing
6
+ * that by hand is how people corrupt the bin. So this module does not
7
+ * reimplement it — it shells out to the same Win32 API Explorer uses
8
+ * (`SHFileOperationW` with `FOF_ALLOWUNDO`) via a generated PowerShell script.
9
+ *
10
+ * Capacity is reported with `SHQueryRecycleBin`. There is deliberately no
11
+ * free-space pre-check: on an NTFS volume the bin lives on the same volume as
12
+ * the item, so a recycle is a rename and consumes no space — a "do you have
13
+ * room" gate would only refuse harmless deletes. What must be checked up front
14
+ * is whether the volume *has* a bin at all: see Test-RecyclableVolume in the
15
+ * PowerShell bridge (UNC and exFAT/FAT32 paths are refused, because
16
+ * SHFileOperationW erases there and still reports success).
17
+ */
18
+
19
+ import { spawn } from 'node:child_process';
20
+ import { existsSync } from 'node:fs';
21
+ import { fileURLToPath } from 'node:url';
22
+ import { dirname, join } from 'node:path';
23
+
24
+ const HERE = dirname(fileURLToPath(import.meta.url));
25
+
26
+ /** Absolute path to the PowerShell bridge script. */
27
+ export const BRIDGE_SCRIPT = join(HERE, '..', 'scripts', 'recycle-bin.ps1');
28
+
29
+ /**
30
+ * Candidate PowerShell executables, most capable first.
31
+ * @returns the resolved executable path, or `pwsh` as a PATH-resolved fallback.
32
+ */
33
+ export function resolvePowershell() {
34
+ const candidates = [
35
+ 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',
36
+ 'C:\\Program Files\\PowerShell\\6\\pwsh.exe',
37
+ join(process.env.LOCALAPPDATA ?? '', 'Microsoft\\WindowsApps\\pwsh.exe'),
38
+ ];
39
+ for (const candidate of candidates) {
40
+ if (candidate.length > 0 && existsSync(candidate)) return candidate;
41
+ }
42
+ return 'pwsh.exe';
43
+ }
44
+
45
+ /**
46
+ * Run the bridge script with a JSON request on stdin and parse its JSON reply.
47
+ *
48
+ * The script is invoked with `-NoProfile -NonInteractive` so a user profile
49
+ * cannot change behaviour. stdout carries exactly one JSON document.
50
+ *
51
+ * @param request - the bridge request object.
52
+ * @param options - `signal` for cancellation, `timeoutMs` for a hard deadline.
53
+ * @returns the parsed bridge response.
54
+ * @throws when the process fails to start, times out, or emits malformed JSON.
55
+ */
56
+ export function callBridge(request, options = {}) {
57
+ const { signal, timeoutMs = 120_000 } = options;
58
+ const exe = resolvePowershell();
59
+
60
+ return new Promise((resolve, reject) => {
61
+ const child = spawn(
62
+ exe,
63
+ ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', BRIDGE_SCRIPT],
64
+ { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true },
65
+ );
66
+
67
+ let stdout = '';
68
+ let stderr = '';
69
+ let settled = false;
70
+
71
+ const finish = (fn, value) => {
72
+ if (settled) return;
73
+ settled = true;
74
+ clearTimeout(timer);
75
+ if (signal !== undefined) signal.removeEventListener('abort', onAbort);
76
+ fn(value);
77
+ };
78
+
79
+ const onAbort = () => {
80
+ child.kill();
81
+ const error = new Error('recycle-bin bridge aborted');
82
+ error.name = 'AbortError';
83
+ finish(reject, error);
84
+ };
85
+
86
+ const timer = setTimeout(() => {
87
+ child.kill();
88
+ finish(reject, new Error(`recycle-bin bridge timed out after ${timeoutMs}ms`));
89
+ }, timeoutMs);
90
+
91
+ if (signal !== undefined) {
92
+ if (signal.aborted) {
93
+ onAbort();
94
+ return;
95
+ }
96
+ signal.addEventListener('abort', onAbort, { once: true });
97
+ }
98
+
99
+ child.stdout.setEncoding('utf8');
100
+ child.stderr.setEncoding('utf8');
101
+ child.stdout.on('data', (chunk) => {
102
+ stdout += chunk;
103
+ });
104
+ child.stderr.on('data', (chunk) => {
105
+ stderr += chunk;
106
+ });
107
+
108
+ child.on('error', (error) => {
109
+ finish(reject, new Error(`failed to launch PowerShell (${exe}): ${error.message}`));
110
+ });
111
+
112
+ child.on('close', (code) => {
113
+ if (settled) return;
114
+ const text = stdout.trim();
115
+ if (text.length === 0) {
116
+ finish(
117
+ reject,
118
+ new Error(`recycle-bin bridge produced no output (exit ${code}). stderr: ${stderr.trim()}`),
119
+ );
120
+ return;
121
+ }
122
+ try {
123
+ finish(resolve, JSON.parse(text));
124
+ } catch (error) {
125
+ finish(
126
+ reject,
127
+ new Error(`recycle-bin bridge returned malformed JSON: ${error.message}. raw: ${text.slice(0, 500)}`),
128
+ );
129
+ }
130
+ });
131
+
132
+ child.stdin.on('error', () => {
133
+ /* The child may exit before reading stdin; the close handler reports. */
134
+ });
135
+ child.stdin.end(JSON.stringify(request), 'utf8');
136
+ });
137
+ }
138
+
139
+ /**
140
+ * Move paths into the Recycle Bin.
141
+ *
142
+ * @param paths - file or directory paths to recycle.
143
+ * @param options - `signal` for cancellation.
144
+ * @returns `{ recycled, failures }` with per-path outcomes.
145
+ */
146
+ export async function recyclePaths(paths, options = {}) {
147
+ if (paths.length === 0) return { recycled: [], failures: [] };
148
+ const response = await callBridge(
149
+ { op: 'recycle', paths },
150
+ { signal: options.signal },
151
+ );
152
+ return {
153
+ recycled: Array.isArray(response.recycled) ? response.recycled : [],
154
+ failures: Array.isArray(response.failures) ? response.failures : [],
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Query Recycle Bin occupancy for one volume.
160
+ *
161
+ * @param drive - a drive letter like `C:`; defaults to the system drive.
162
+ * @param options - `signal` for cancellation.
163
+ * @returns `{ items, bytes }`.
164
+ */
165
+ export async function recycleBinUsage(drive, options = {}) {
166
+ const response = await callBridge(
167
+ { op: 'usage', drive },
168
+ { signal: options.signal },
169
+ );
170
+ return {
171
+ items: typeof response.items === 'number' ? response.items : 0,
172
+ bytes: typeof response.bytes === 'number' ? response.bytes : 0,
173
+ };
174
+ }