dsh-delete-guard 2.2.3 → 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +313 -0
- package/README.en.md +79 -12
- package/README.ja.md +65 -11
- package/README.md +59 -7
- package/SECURITY.md +127 -3
- package/cordis.patch.yml +2 -0
- package/lib/guard.js +256 -167
- package/lib/index.js +187 -6
- package/lib/move-guard.js +17 -0
- package/lib/rewrite-guard.js +925 -0
- package/lib/shell-text.js +205 -0
- package/lib/staging.js +292 -0
- package/package.json +2 -2
package/lib/index.js
CHANGED
|
@@ -35,6 +35,7 @@ import { stat } from 'node:fs/promises';
|
|
|
35
35
|
import { classifyCommand } from './guard.js';
|
|
36
36
|
import { recyclePaths, recycleBinUsage } from './recycle.js';
|
|
37
37
|
import { validateTrashTarget, workspaceRootReason } from './move-guard.js';
|
|
38
|
+
import { defaultStagingRoot, isNetworkPath, stageForRecycle } from './staging.js';
|
|
38
39
|
|
|
39
40
|
export const name = 'delete-guard';
|
|
40
41
|
export const inject = ['tools', 'systemPrompt'];
|
|
@@ -73,6 +74,31 @@ const SHELL_TOOLS = new Map([
|
|
|
73
74
|
['terminal_write', { field: 'text', dialect: 'pwsh' }],
|
|
74
75
|
]);
|
|
75
76
|
|
|
77
|
+
/**
|
|
78
|
+
* A cheap "could this command possibly touch files, the bin, or an interpreter?"
|
|
79
|
+
* test, used to skip the full classifier.
|
|
80
|
+
*
|
|
81
|
+
* Must be **over-inclusive**: every rule in `guard.js` needs at least one of these
|
|
82
|
+
* signals to fire, so anything this misses is a command that no rule could have
|
|
83
|
+
* matched anyway. The cost of a false positive is a few hundred microseconds; the
|
|
84
|
+
* cost of a false negative would be an unguarded command.
|
|
85
|
+
*/
|
|
86
|
+
const MAY_TOUCH_FILES = new RegExp([
|
|
87
|
+
// delete verbs
|
|
88
|
+
'\\b(?:Remove-Item|ri|del|erase|rd|rmdir|rm|unlink|clear-content)\\b',
|
|
89
|
+
// write verbs and redirects
|
|
90
|
+
'\\b(?:Set-Content|Out-File|Add-Content|Export-Csv|Tee-Object|Copy-Item|Move-Item|New-Item|::Write\\w+|::Create\\w*)\\b',
|
|
91
|
+
'>{1}(?!>)',
|
|
92
|
+
// readers (they matter to the in-place rule)
|
|
93
|
+
'\\b(?:Get-Content|ReadAllText|ReadAllLines|Import-Csv|Select-String|OpenText)\\b',
|
|
94
|
+
// interpreters, inline bodies, opaque constructs
|
|
95
|
+
'\\b(?:bash|sh|zsh|pwsh|powershell|node|python|python3|perl|ruby|cmd(?:\\.exe)?)\\b',
|
|
96
|
+
'\\$-{0,1}\\(|`|<<|\\bxargs\\b|\\bfind\\b',
|
|
97
|
+
// trash / wipe / bin surfaces
|
|
98
|
+
'\\b(?:sdelete|sdelete64|shred|srm|wipe|cipher|format|robocopy|Invoke-Expression|iex|Add-Type)\\b',
|
|
99
|
+
'recycle|namespace\\(\\s*(?:10|0xa)\\s*\\)|invokeverb|\\bdoit\\b|\\.verbs\\s*\\(|shemptyrecyclebin',
|
|
100
|
+
].join('|'), 'i');
|
|
101
|
+
|
|
76
102
|
/**
|
|
77
103
|
* Reject an empty path list before any I/O.
|
|
78
104
|
* @param paths - candidate paths.
|
|
@@ -86,6 +112,32 @@ function cleanPaths(paths) {
|
|
|
86
112
|
.filter((p) => p.length > 0);
|
|
87
113
|
}
|
|
88
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Whether a shell command is a dry run (`-WhatIf`).
|
|
117
|
+
*
|
|
118
|
+
* Token-level on purpose. A textual test is fooled by the word appearing in a
|
|
119
|
+
* comment or inside a string value — measured 2026-11-25: with a textual test,
|
|
120
|
+
* `Set-Content $f $t # always -WhatIf first` and
|
|
121
|
+
* `Set-Content -Value "run -WhatIf then finish"` were both treated as dry runs even
|
|
122
|
+
* though they really write.
|
|
123
|
+
*
|
|
124
|
+
* `-WhatIf:$false` / `-WhatIf:$true` are **not** dry runs: the first really executes,
|
|
125
|
+
* and neither is the bare preview the switch is for.
|
|
126
|
+
*
|
|
127
|
+
* @param command - the raw command text.
|
|
128
|
+
* @returns whether the command would only preview.
|
|
129
|
+
*/
|
|
130
|
+
function isDryRun(command) {
|
|
131
|
+
if (typeof command !== 'string' || !/-whatif/i.test(command)) return false;
|
|
132
|
+
for (const line of command.split(/\r?\n/)) {
|
|
133
|
+
// Strip a trailing PowerShell comment so `… -WhatIf` in prose does not count.
|
|
134
|
+
const code = line.replace(/(?:^|\s)#.*$/, '');
|
|
135
|
+
// A `-WhatIf` token that is not followed by a `:` (i.e. not `:$false`).
|
|
136
|
+
if (/(?:^|\s)-whatif(?![:\w-])/i.test(code)) return true;
|
|
137
|
+
}
|
|
138
|
+
return false;
|
|
139
|
+
}
|
|
140
|
+
|
|
89
141
|
/**
|
|
90
142
|
* Resolve the workspace root the sandbox policy reports, falling back to the
|
|
91
143
|
* process working directory. The fallback matters: without a sandbox service
|
|
@@ -117,10 +169,16 @@ export function apply(ctx, config = {}) {
|
|
|
117
169
|
forbidEmptyRecycleBin = true,
|
|
118
170
|
forbidWipe = true,
|
|
119
171
|
blockScriptDeletes = true,
|
|
172
|
+
blockTruncatingWrites = true,
|
|
173
|
+
uncRecoverableMove = true,
|
|
174
|
+
stagingRoot,
|
|
120
175
|
} = config;
|
|
121
176
|
|
|
122
|
-
const guardOptions = { forbidEmptyRecycleBin, forbidWipe, blockScriptDeletes };
|
|
177
|
+
const guardOptions = { forbidEmptyRecycleBin, forbidWipe, blockScriptDeletes, blockTruncatingWrites };
|
|
123
178
|
const workspaceRoot = resolveWorkspaceRoot(ctx);
|
|
179
|
+
const stageRoot = typeof stagingRoot === 'string' && stagingRoot.trim().length > 0
|
|
180
|
+
? stagingRoot.trim()
|
|
181
|
+
: defaultStagingRoot();
|
|
124
182
|
|
|
125
183
|
// --- 1. Intercept destructive shell commands ------------------------------
|
|
126
184
|
|
|
@@ -136,6 +194,20 @@ export function apply(ctx, config = {}) {
|
|
|
136
194
|
const command = args[spec.field];
|
|
137
195
|
if (typeof command !== 'string') return next();
|
|
138
196
|
|
|
197
|
+
// Cheap precondition: a command that cannot possibly delete or destroy content
|
|
198
|
+
// is not worth the full classifier.
|
|
199
|
+
//
|
|
200
|
+
// The classifier is ~250 µs on a long command (dozens of regexes over the whole
|
|
201
|
+
// text), which is real money on the tool-call path — the host pays it before
|
|
202
|
+
// every shell call. Two regexes cost ~1.8 µs and skip 88% of commands: measured
|
|
203
|
+
// on 6,000 real commands, only 11.6% mention both a reader and a writer.
|
|
204
|
+
//
|
|
205
|
+
// Deliberately over-inclusive: any mention of a delete verb, a write verb, a
|
|
206
|
+
// redirect, an interpreter, or a bin API lets the command through to the full
|
|
207
|
+
// check. A false positive here only costs time; a false negative would skip the
|
|
208
|
+
// guard, so the net is wide.
|
|
209
|
+
if (!MAY_TOUCH_FILES.test(command)) return next();
|
|
210
|
+
|
|
139
211
|
const verdict = classifyCommand(command, {
|
|
140
212
|
...guardOptions,
|
|
141
213
|
// The tool name identifies the shell language, which decides
|
|
@@ -155,6 +227,31 @@ export function apply(ctx, config = {}) {
|
|
|
155
227
|
|
|
156
228
|
// action === 'rewrite': steer the model to the recoverable path.
|
|
157
229
|
const list = verdict.targets.map((t) => `"${t}"`).join(', ');
|
|
230
|
+
|
|
231
|
+
// A dry run must not be turned into an instruction to really delete.
|
|
232
|
+
//
|
|
233
|
+
// Measured 2026-11-25: `Remove-Item -LiteralPath x.txt -WhatIf` classified as
|
|
234
|
+
// `rewrite/delete`, and this branch told the model to re-run it as `file_trash`
|
|
235
|
+
// — i.e. the user asked to preview and the guard advised destroying the file.
|
|
236
|
+
// That is a safety inversion, not a false positive. The reverse also happened:
|
|
237
|
+
// `Remove-Item -WhatIf x.txt` was refused as "no explicit operands" because
|
|
238
|
+
// `-WhatIf` was listed as a flag that consumes its value.
|
|
239
|
+
//
|
|
240
|
+
// The fix renders dry runs differently rather than omitting the statement from
|
|
241
|
+
// classification: dropping statements would let a real write be exempted by the
|
|
242
|
+
// word `-WhatIf` appearing in a comment or a string value.
|
|
243
|
+
if (isDryRun(command)) {
|
|
244
|
+
return {
|
|
245
|
+
kind: 'deny',
|
|
246
|
+
reason:
|
|
247
|
+
`This command is a dry run (\`-WhatIf\`), so nothing was executed and nothing needs to be deleted. ` +
|
|
248
|
+
`The guard does not rewrite dry runs into real deletions.\n\n` +
|
|
249
|
+
`If you actually meant to delete ${list}, call ${TRASH_TOOL} with those paths. If you only wanted to ` +
|
|
250
|
+
`preview, the command you just ran was correct — but remove \`-WhatIf\` would really delete, so don't.`,
|
|
251
|
+
info: { name: 'DeleteGuardError', code: 'DELETE_GUARD_DRY_RUN' },
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
158
255
|
return {
|
|
159
256
|
kind: 'deny',
|
|
160
257
|
reason:
|
|
@@ -203,9 +300,30 @@ export function apply(ctx, config = {}) {
|
|
|
203
300
|
schema: {
|
|
204
301
|
type: 'object',
|
|
205
302
|
additionalProperties: false,
|
|
206
|
-
required: ['recycled', 'failures'],
|
|
303
|
+
required: ['recycled', 'staged', 'failures'],
|
|
207
304
|
properties: {
|
|
208
305
|
recycled: { type: 'array', items: { type: 'string' } },
|
|
306
|
+
// Items deleted from a volume with no Recycle Bin (a UNC share): the
|
|
307
|
+
// content was copied to a local NTFS volume, verified, recycled there,
|
|
308
|
+
// and only then removed from its original location. Reported apart from
|
|
309
|
+
// `recycled` because the original path is *not* in the bin — its
|
|
310
|
+
// content is.
|
|
311
|
+
staged: {
|
|
312
|
+
type: 'array',
|
|
313
|
+
items: {
|
|
314
|
+
type: 'object',
|
|
315
|
+
additionalProperties: false,
|
|
316
|
+
required: ['path', 'staged', 'recycled', 'sourceRemoved'],
|
|
317
|
+
properties: {
|
|
318
|
+
path: { type: 'string' },
|
|
319
|
+
staged: { type: 'string' },
|
|
320
|
+
recycled: { type: 'boolean' },
|
|
321
|
+
sourceRemoved: { type: 'boolean' },
|
|
322
|
+
verification: { type: 'string' },
|
|
323
|
+
remaining: { type: 'array', items: { type: 'string' } },
|
|
324
|
+
},
|
|
325
|
+
},
|
|
326
|
+
},
|
|
209
327
|
failures: {
|
|
210
328
|
type: 'array',
|
|
211
329
|
items: {
|
|
@@ -226,13 +344,26 @@ export function apply(ctx, config = {}) {
|
|
|
226
344
|
lines.push(`Moved to the Recycle Bin (${value.recycled.length}):`);
|
|
227
345
|
for (const p of value.recycled) lines.push(` ${p}`);
|
|
228
346
|
}
|
|
347
|
+
if (value.staged.length > 0) {
|
|
348
|
+
lines.push(`Deleted from a location with no Recycle Bin (${value.staged.length}):`);
|
|
349
|
+
for (const s of value.staged) {
|
|
350
|
+
lines.push(` ${s.path}`);
|
|
351
|
+
lines.push(` content copied to ${s.staged} and recycled from there (verified: ${s.verification ?? 'n/a'})`);
|
|
352
|
+
lines.push(
|
|
353
|
+
s.sourceRemoved
|
|
354
|
+
? ` the original at that share was removed after the copy was verified — the share has no Recycle Bin, `
|
|
355
|
+
+ 'so restoring means finding this entry in the local Recycle Bin, whose original location is the staging path'
|
|
356
|
+
: ` ⚠ the original is still there: removing it failed${s.remaining?.length ? ` (${s.remaining.join(', ')})` : ''}`,
|
|
357
|
+
);
|
|
358
|
+
}
|
|
359
|
+
}
|
|
229
360
|
if (value.failures.length > 0) {
|
|
230
361
|
lines.push(`Failed (${value.failures.length}):`);
|
|
231
362
|
for (const f of value.failures) lines.push(` ${f.path}: ${f.error}`);
|
|
232
363
|
}
|
|
233
364
|
if (lines.length === 0) lines.push('Nothing was deleted: no usable paths were provided.');
|
|
234
365
|
lines.push('');
|
|
235
|
-
lines.push('
|
|
366
|
+
lines.push('Items reported above are recoverable from the local Recycle Bin; they were not permanently erased.');
|
|
236
367
|
return [{ type: 'text', text: lines.join('\n') }];
|
|
237
368
|
},
|
|
238
369
|
},
|
|
@@ -241,6 +372,7 @@ export function apply(ctx, config = {}) {
|
|
|
241
372
|
if (paths.length === 0) {
|
|
242
373
|
return {
|
|
243
374
|
recycled: [],
|
|
375
|
+
staged: [],
|
|
244
376
|
failures: [{ path: '(none)', error: 'no usable paths were supplied' }],
|
|
245
377
|
};
|
|
246
378
|
}
|
|
@@ -276,13 +408,52 @@ export function apply(ctx, config = {}) {
|
|
|
276
408
|
}
|
|
277
409
|
}
|
|
278
410
|
|
|
279
|
-
|
|
280
|
-
|
|
411
|
+
// A network location has no Recycle Bin, so the bridge would refuse it. When
|
|
412
|
+
// staging is enabled the item is copied to a local NTFS volume, verified,
|
|
413
|
+
// recycled from there, and only then removed from the share: the content is
|
|
414
|
+
// recoverable, the path is not. See staging.js for the step order and for
|
|
415
|
+
// what "verified" does and does not cover.
|
|
416
|
+
const staged = [];
|
|
417
|
+
const direct = [];
|
|
418
|
+
for (const path of absolute) {
|
|
419
|
+
if (!isNetworkPath(path)) {
|
|
420
|
+
direct.push(path);
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
if (!uncRecoverableMove) {
|
|
424
|
+
failures.push({
|
|
425
|
+
path,
|
|
426
|
+
error: 'a network location has no Recycle Bin, so recycling here would erase the item permanently. '
|
|
427
|
+
+ 'Copy it to a local NTFS path first, or delete it from Explorer where Windows can warn the user.',
|
|
428
|
+
});
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
const outcome = await stageForRecycle(path, {
|
|
432
|
+
stagingRoot: stageRoot,
|
|
433
|
+
recycle: (list) => recyclePaths(list, { signal: exec.signal }),
|
|
434
|
+
});
|
|
435
|
+
if (outcome.ok) {
|
|
436
|
+
staged.push({
|
|
437
|
+
path,
|
|
438
|
+
staged: outcome.staged,
|
|
439
|
+
recycled: true,
|
|
440
|
+
sourceRemoved: outcome.sourceRemoved,
|
|
441
|
+
verification: outcome.verification,
|
|
442
|
+
...(outcome.remaining === undefined ? {} : { remaining: outcome.remaining }),
|
|
443
|
+
});
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
failures.push({ path, error: outcome.error });
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
if (direct.length === 0) {
|
|
450
|
+
return { recycled: [], staged, failures };
|
|
281
451
|
}
|
|
282
452
|
|
|
283
|
-
const result = await recyclePaths(
|
|
453
|
+
const result = await recyclePaths(direct, { signal: exec.signal });
|
|
284
454
|
return {
|
|
285
455
|
recycled: result.recycled,
|
|
456
|
+
staged,
|
|
286
457
|
failures: [...failures, ...result.failures],
|
|
287
458
|
};
|
|
288
459
|
},
|
|
@@ -351,6 +522,10 @@ export function apply(ctx, config = {}) {
|
|
|
351
522
|
' commands typed into a persistent terminal (`terminal_send`), which is judged the same way.',
|
|
352
523
|
'- In a Git Bash session, pass paths to `file_trash` as Windows paths (`C:\\tmp\\x`), not POSIX ones.',
|
|
353
524
|
' `/c/tmp/x` is translated to `C:\\tmp\\x` for you; `~` and other mount points (`/tmp`, `/usr`) are refused.',
|
|
525
|
+
'- A network share (`\\\\host\\share\\…`) has no Recycle Bin. `file_trash` handles it by copying the item to',
|
|
526
|
+
' a local NTFS volume, verifying the copy, recycling that, and only then removing the original — so the',
|
|
527
|
+
' content is recoverable from the local bin, while the share path itself is not. Do not `Move-Item` or',
|
|
528
|
+
' `robocopy /MOV` something off a share to "delete" it: that erases the source with no bin record at all.',
|
|
354
529
|
'- Do NOT empty or modify the Recycle Bin (`Clear-RecycleBin` in any form — bare, `&`, inside a',
|
|
355
530
|
' child shell, or encoded; `SHEmptyRecycleBin`; driving the bin items\' own shell verbs; walking',
|
|
356
531
|
' `$Recycle.Bin`). All of those are blocked.',
|
|
@@ -359,6 +534,12 @@ export function apply(ctx, config = {}) {
|
|
|
359
534
|
'- Do NOT use permanent-erase tools (`shred`, `sdelete`, `srm`, `cipher /w`). That is blocked.',
|
|
360
535
|
'- Do NOT put deletions inside shell scripts or inline `-Command` / `-e` strings; they cannot be',
|
|
361
536
|
' routed to the Recycle Bin and will be refused.',
|
|
537
|
+
'- Do NOT read a file and overwrite that same file in one shell command (`Get-Content f … |',
|
|
538
|
+
' Set-Content f`, `sed -i f`, `cat f > f`). A wrong slice or filter then replaces the only copy.',
|
|
539
|
+
' Copy it to `<name>.bak-<timestamp>` first, or use the `write` / `edit` tools. A network share has',
|
|
540
|
+
' no Recycle Bin, so nothing there can be recovered after the fact.',
|
|
541
|
+
'- Before slicing with an index (`$lines[0..($idx-1)]`), assert it: `if (-not $idx) { throw "anchor',
|
|
542
|
+
' not found" }`. A null endpoint silently becomes `0..-2`, i.e. the first line plus the last two.',
|
|
362
543
|
`- To overwrite a file, prefer the \`write\` / \`edit\` tools. Use \`${TRASH_TOOL}\` only when a path must go away.`,
|
|
363
544
|
`- \`${STATUS_TOOL}\` reports current bin occupancy if you need to confirm a deletion landed.`,
|
|
364
545
|
].join('\n'),
|
package/lib/move-guard.js
CHANGED
|
@@ -48,6 +48,11 @@ function forbiddenReason(p) {
|
|
|
48
48
|
if (/^[a-z]:[\\/]windows(?:[\\/]|$)/i.test(p)) return 'the Windows directory';
|
|
49
49
|
if (/^[a-z]:[\\/]program files(?: \(x86\))?(?:[\\/]|$)/i.test(p)) return 'Program Files';
|
|
50
50
|
if (isRecycleBinStorage(p)) return 'the Recycle Bin storage directory itself';
|
|
51
|
+
// A share root (`\\host\share`) is the network equivalent of a drive root: it is
|
|
52
|
+
// not an item, and staging it would copy (and then delete) everything on the
|
|
53
|
+
// share. `\\host` alone is not even a location.
|
|
54
|
+
const unc = /^[\\/]{2}([^\\/]+)(?:[\\/]([^\\/]+))?[\\/]?$/.exec(p);
|
|
55
|
+
if (unc !== null) return unc[2] === undefined ? 'a network host, not a path' : 'a network share root';
|
|
51
56
|
return undefined;
|
|
52
57
|
}
|
|
53
58
|
|
|
@@ -74,6 +79,18 @@ export function validateTrashTarget(raw, cwd) {
|
|
|
74
79
|
return { ok: false, error: `unresolvable path: ${error.message}` };
|
|
75
80
|
}
|
|
76
81
|
|
|
82
|
+
// `\\host` (a host with no share) is not a path: `resolve` reads it as a
|
|
83
|
+
// drive-relative path and yields `<cwd drive>:\host` — a *local* file that has
|
|
84
|
+
// nothing to do with the share the caller meant. Refuse the shape instead of
|
|
85
|
+
// recycling something else (measured: `resolve('\\\\host')` → `F:\host`).
|
|
86
|
+
if (/^[\\/]{2}[^\\/]/.test(text) && !/^[\\/]{2}/.test(absolute)) {
|
|
87
|
+
return {
|
|
88
|
+
ok: false,
|
|
89
|
+
error: `refusing "${text}": that names a network host but no share, so it is not a path. `
|
|
90
|
+
+ 'Use the full `\\\\host\\share\\...` form.',
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
77
94
|
const reason = forbiddenReason(absolute);
|
|
78
95
|
if (reason !== undefined) {
|
|
79
96
|
return { ok: false, error: `refusing to recycle ${reason}: "${absolute}"` };
|