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.
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Shell-text lexing, shared by the delete guard and the overwrite guard.
3
+ *
4
+ * These four helpers are the only part of the matcher that is genuinely about
5
+ * *text* rather than about a rule: splitting a command into statements, turning a
6
+ * statement into argv-like words, unwrapping quotes, and finding the word that
7
+ * names what a statement runs. They live here rather than in `guard.js` because
8
+ * two rule modules now need them — and because a rule module that imports the
9
+ * rule module beside it (guard.js → rewrite-guard.js → guard.js) is a cycle, not
10
+ * an architecture.
11
+ *
12
+ * Everything here is pure and dialect-agnostic on purpose: the differences that
13
+ * matter (PowerShell's `$( … )` opacity, MSYS path translation) belong to the
14
+ * rules, not to the lexer.
15
+ */
16
+
17
+ /**
18
+ * Strip a single layer of shell quote characters.
19
+ * @param token - raw operand token.
20
+ * @returns the token without surrounding quotes.
21
+ */
22
+ export function unquote(token) {
23
+ const t = token.trim();
24
+ if (t.length >= 2) {
25
+ const first = t[0];
26
+ const last = t[t.length - 1];
27
+ if ((first === '"' && last === '"') || (first === "'" && last === "'")) {
28
+ return t.slice(1, -1);
29
+ }
30
+ }
31
+ return t;
32
+ }
33
+
34
+ /**
35
+ * Split a command string into statements on unquoted separators, so each
36
+ * statement can be classified independently.
37
+ *
38
+ * Braces are separators. PowerShell wraps a delete in a script block all the
39
+ * time — `if (Test-Path $p) { Remove-Item $p }`, `foreach ($f in $fs) { … }`,
40
+ * `& { … }`, `try { … }`, `… | ForEach-Object { … }` — and a splitter that only
41
+ * honours `;` and newlines leaves the verb inside the block where the
42
+ * first-token matcher never reaches it. That is not a theoretical gap: it is
43
+ * exactly how a real `Remove-Item` ran unguarded on 2026-10-18, while the same
44
+ * delete written across three lines was caught (the newline happened to be a
45
+ * separator).
46
+ *
47
+ * `${name}` is the one brace form that is a variable rather than a block, so it
48
+ * is consumed whole. Shredding it into `$` + `NAME}` would turn a delete
49
+ * target of `${TARGET_DIR}` into a literal `$`, which is worse than missing it:
50
+ * the redirect message would name a path that does not exist.
51
+ *
52
+ * @param command - full command text.
53
+ * @returns the statement strings, trimmed and non-empty.
54
+ */
55
+ export function splitStatements(command) {
56
+ const out = [];
57
+ let buf = '';
58
+ let quote = null;
59
+ for (let i = 0; i < command.length; i += 1) {
60
+ const ch = command[i];
61
+ if (quote !== null) {
62
+ buf += ch;
63
+ if (ch === quote) quote = null;
64
+ continue;
65
+ }
66
+ if (ch === '"' || ch === "'") {
67
+ quote = ch;
68
+ buf += ch;
69
+ continue;
70
+ }
71
+ if (ch === '{' && buf.endsWith('$')) {
72
+ const close = command.indexOf('}', i + 1);
73
+ const end = close === -1 ? command.length : close + 1;
74
+ buf += command.slice(i, end);
75
+ i = end - 1;
76
+ continue;
77
+ }
78
+ const isSep =
79
+ ch === ';' ||
80
+ ch === '\n' ||
81
+ ch === '\r' ||
82
+ ch === '|' ||
83
+ ch === '&' ||
84
+ ch === '{' ||
85
+ ch === '}';
86
+ if (isSep) {
87
+ if (buf.trim().length > 0) out.push(buf.trim());
88
+ buf = '';
89
+ continue;
90
+ }
91
+ buf += ch;
92
+ }
93
+ if (buf.trim().length > 0) out.push(buf.trim());
94
+ return out;
95
+ }
96
+
97
+ /**
98
+ * Tokenize a single statement into argv-like words, honouring quotes.
99
+ * @param statement - one statement.
100
+ * @returns the token list.
101
+ */
102
+ export function tokenize(statement) {
103
+ const out = [];
104
+ let buf = '';
105
+ let quote = null;
106
+ let started = false;
107
+ for (let i = 0; i < statement.length; i += 1) {
108
+ const ch = statement[i];
109
+ if (quote !== null) {
110
+ if (ch === quote) {
111
+ quote = null;
112
+ } else {
113
+ buf += ch;
114
+ }
115
+ started = true;
116
+ continue;
117
+ }
118
+ if (ch === '"' || ch === "'") {
119
+ quote = ch;
120
+ started = true;
121
+ continue;
122
+ }
123
+ if (ch === ' ' || ch === '\t') {
124
+ if (started) {
125
+ out.push(buf);
126
+ buf = '';
127
+ started = false;
128
+ }
129
+ continue;
130
+ }
131
+ buf += ch;
132
+ started = true;
133
+ }
134
+ if (started) out.push(buf);
135
+ return out;
136
+ }
137
+
138
+ /**
139
+ * Find the command word of one statement: the token that names the thing being
140
+ * run, with the wrapper prefixes removed the same way `parseDeleteStatement`
141
+ * removes them (`&`, `.`, `(`, `@(`, `$x =`) and quotes stripped.
142
+ *
143
+ * `& "Clear-RecycleBin"` is the case that motivated this: the statement
144
+ * splitter treats `&` as a separator, so what is left is a bare quoted name, and
145
+ * a `^clear-recyclebin` regex over raw text never saw it.
146
+ *
147
+ * @param statement - one statement.
148
+ * @returns the command word, or `''`.
149
+ */
150
+ export function commandWord(statement) {
151
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
152
+ for (let i = 0; i < tokens.length; i += 1) {
153
+ const t = tokens[i];
154
+ if (/^(?:[(\[{@&.]+|\$\(|=)$/.test(t)) continue;
155
+ const glued = /^[(\[{@&]+(.+)$/.exec(t);
156
+ if (glued !== null) return unquote(glued[1]).trim();
157
+ if (/^\$[A-Za-z_][\w:]*$/.test(t) && tokens[i + 1] === '=') {
158
+ i += 1;
159
+ continue;
160
+ }
161
+ const assign = /^\$[A-Za-z_][\w:]*\s*=\s*(.+)$/.exec(t);
162
+ if (assign !== null) return assign[1].trim();
163
+ return unquote(t).trim();
164
+ }
165
+ return '';
166
+ }
167
+
168
+ /**
169
+ * The tokens of one statement with the same wrapper prefixes removed that
170
+ * `commandWord` steps over: leading `(`, `$(`, `@(`, `&`, `.`, `=` tokens, a
171
+ * wrapper glued to the first word, and a `$name =` assignment.
172
+ *
173
+ * Rules that need the *operand list* rather than just the command word (the
174
+ * overwrite guard asks "which file is this writing?") cannot re-derive it from
175
+ * `commandWord`'s return value, which drops everything after the first word.
176
+ *
177
+ * @param statement - one statement.
178
+ * @returns the remaining tokens, first one being the command word.
179
+ */
180
+ export function statementTokens(statement) {
181
+ const tokens = tokenize(statement).filter((t) => t.length > 0);
182
+ for (let guard = 0; guard < tokens.length; guard += 1) {
183
+ const t = tokens[0];
184
+ if (/^(?:[(\[{@&.]+|\$\(|=)$/.test(t)) {
185
+ tokens.shift();
186
+ continue;
187
+ }
188
+ const glued = /^[(\[{@&]+(.+)$/.exec(t);
189
+ if (glued !== null) {
190
+ tokens[0] = glued[1];
191
+ continue;
192
+ }
193
+ if (/^\$[A-Za-z_][\w:]*$/.test(t) && tokens[1] === '=') {
194
+ tokens.splice(0, 2);
195
+ continue;
196
+ }
197
+ const assign = /^\$[A-Za-z_][\w:]*\s*=\s*(.+)$/.exec(t);
198
+ if (assign !== null) {
199
+ tokens[0] = assign[1];
200
+ continue;
201
+ }
202
+ break;
203
+ }
204
+ return tokens;
205
+ }
package/lib/staging.js ADDED
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Deletions on volumes that have no Recycle Bin.
3
+ *
4
+ * The Windows Recycle Bin is a per-volume NTFS facility. On a UNC path (and on
5
+ * exFAT/FAT32 volumes) `SHFileOperationW(FOF_ALLOWUNDO)` does not recycle: it
6
+ * erases and returns 0, which is why `scripts/recycle-bin.ps1` refuses those
7
+ * paths up front (reproduced 2026-10-23; see the e2e case "a path with no Recycle
8
+ * Bin is refused").
9
+ *
10
+ * Refusing is safe but not useful: the deletion the user asked for never happens,
11
+ * and the model has to invent a workaround. This module is the missing step, and
12
+ * what it does has to be described exactly, because it is *not* a recycle:
13
+ *
14
+ * 1. copy the item to a staging directory on a volume that does have a bin;
15
+ * 2. verify the copy against the original (same entries, same kinds, same sizes);
16
+ * 3. recycle the staged copy — the item is now in the bin, restorable;
17
+ * 4. only then remove the original, which is an ordinary permanent delete
18
+ * because there is no bin on that volume to hold it.
19
+ *
20
+ * So the guarantee is about *content*, not about the original path: after a
21
+ * successful staging delete the bytes live in the local bin, and the item at the
22
+ * original location is gone. Windows' own cross-volume `Move-Item` behaves the
23
+ * same way (copy, then unlink the source), with one difference that matters: it
24
+ * does not verify and does not leave a bin record.
25
+ *
26
+ * What is deliberately refused
27
+ * ----------------------------
28
+ * - **Reparse points** (junctions/symlinks) anywhere in the tree. A copy either
29
+ * dereferences them — duplicating data that is not the item — or needs
30
+ * privileges to recreate them. Neither is a faithful copy, so the delete stops
31
+ * and says so.
32
+ * - **Not enough free space** on the staging volume, checked before copying from
33
+ * the measured size, so a 50 GB tree fails in a second instead of halfway.
34
+ *
35
+ * What is verified, and what is not
36
+ * ---------------------------------
37
+ * Verified: the set of relative paths, each entry's kind, and each file's size.
38
+ * Not verified: content hashes. Hashing both sides doubles the I/O on a tree that
39
+ * may be tens of gigabytes; sizes plus entry sets catch truncation, which is the
40
+ * failure mode that actually destroys data. This is stated in the tool's result
41
+ * so nobody reads more into "verified" than it means.
42
+ *
43
+ * The step order is the safety property: the source is removed **after** the
44
+ * bridge confirms the staged copy is in the bin. Every earlier failure leaves the
45
+ * original untouched.
46
+ */
47
+
48
+ import { cp, lstat, mkdir, readdir, rm, statfs } from 'node:fs/promises';
49
+ import { basename, join } from 'node:path';
50
+
51
+ /**
52
+ * Whether a path names a network location (`\\host\share\…` or `//host/share/…`).
53
+ *
54
+ * Matched on the prefix alone, before any I/O: the judgement must not depend on
55
+ * the share being reachable, and a path that starts with two separators is never
56
+ * local on Windows.
57
+ *
58
+ * @param p - a path as written.
59
+ * @returns whether it is a UNC path.
60
+ */
61
+ export function isNetworkPath(p) {
62
+ return /^[\\/]{2}[^\\/]/.test(String(p ?? ''));
63
+ }
64
+
65
+ /**
66
+ * Whether a UNC path names the share itself (`\\host\share`) or the host alone
67
+ * (`\\host`) rather than an item inside it. Deleting those is a
68
+ * filesystem-root-class operation, not a file delete.
69
+ *
70
+ * @param p - a path as written.
71
+ * @returns whether it is a share root (or a bare host).
72
+ */
73
+ function isShareRoot(p) {
74
+ const parts = String(p).slice(2).split(/[\\/]+/).filter((part) => part.length > 0);
75
+ return parts.length <= 2;
76
+ }
77
+
78
+ /**
79
+ * The staging directory used when the config names none.
80
+ * @returns an absolute path under the user's local application data.
81
+ */
82
+ export function defaultStagingRoot() {
83
+ const base = process.env.LOCALAPPDATA ?? join(process.env.USERPROFILE ?? '.', 'AppData', 'Local');
84
+ return join(base, 'dsh-delete-guard', 'staging');
85
+ }
86
+
87
+ /**
88
+ * A local timestamp for the staging directory name: readable, sortable, and the
89
+ * only thing that identifies *when* the item left the share.
90
+ * @param now - the clock reading.
91
+ * @returns e.g. `20261115-002512`.
92
+ */
93
+ function stampOf(now) {
94
+ const pad = (n) => String(n).padStart(2, '0');
95
+ return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`
96
+ + `-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
97
+ }
98
+
99
+ /**
100
+ * Describe a tree as relative path → { kind, size }, refusing reparse points.
101
+ *
102
+ * The refusal is a throw rather than a flag because every caller has to stop:
103
+ * there is no correct continuation after "this tree cannot be copied faithfully".
104
+ *
105
+ * @param root - absolute path of the file or directory.
106
+ * @param rel - the sub-path being walked.
107
+ * @param out - accumulator.
108
+ * @returns the map, keyed by relative path (`.` for a single file).
109
+ * @throws when the tree contains a reparse point or cannot be read.
110
+ */
111
+ async function walkTree(root, rel = '', out = new Map()) {
112
+ const abs = rel === '' ? root : join(root, rel);
113
+ const info = await lstat(abs);
114
+ if (info.isSymbolicLink()) {
115
+ const error = new Error(
116
+ `it contains a reparse point (junction or symlink) at "${rel || '.'}": a copy would either duplicate `
117
+ + 'the target\'s contents or need privileges to recreate the link, so nothing here is a faithful copy',
118
+ );
119
+ error.code = 'EREPARSE';
120
+ throw error;
121
+ }
122
+ if (info.isDirectory()) {
123
+ if (rel !== '') out.set(rel, { kind: 'dir' });
124
+ const names = (await readdir(abs)).sort();
125
+ for (const name of names) {
126
+ await walkTree(root, rel === '' ? name : join(rel, name), out);
127
+ }
128
+ return out;
129
+ }
130
+ out.set(rel === '' ? '.' : rel, { kind: 'file', size: info.size });
131
+ return out;
132
+ }
133
+
134
+ /**
135
+ * Total bytes of a walked tree.
136
+ * @param tree - the map from {@link walkTree}.
137
+ * @returns the sum of file sizes.
138
+ */
139
+ function totalBytes(tree) {
140
+ let bytes = 0;
141
+ for (const entry of tree.values()) {
142
+ if (entry.kind === 'file') bytes += entry.size;
143
+ }
144
+ return bytes;
145
+ }
146
+
147
+ /**
148
+ * Compare two walked trees and name the first difference.
149
+ * @param original - the source tree.
150
+ * @param copy - the staged tree.
151
+ * @returns a human-readable difference, or `undefined` when they match.
152
+ */
153
+ export function compareTrees(original, copy) {
154
+ for (const [rel, entry] of original) {
155
+ const other = copy.get(rel);
156
+ if (other === undefined) return `"${rel}" is missing from the copy`;
157
+ if (other.kind !== entry.kind) return `"${rel}" changed kind (${entry.kind} → ${other.kind})`;
158
+ if (entry.kind === 'file' && other.size !== entry.size) {
159
+ return `"${rel}" has ${other.size} bytes in the copy, ${entry.size} in the original`;
160
+ }
161
+ }
162
+ for (const rel of copy.keys()) {
163
+ if (!original.has(rel)) return `"${rel}" is in the copy but not in the original`;
164
+ }
165
+ return undefined;
166
+ }
167
+
168
+ /**
169
+ * Copy → verify → recycle the copy → remove the original.
170
+ *
171
+ * Every step before the last can fail without touching the original, and the last
172
+ * one only runs after the bridge has confirmed the staged copy left for the bin.
173
+ *
174
+ * @param source - the UNC path to delete.
175
+ * @param options - `stagingRoot` (absolute), `recycle` (the bridge call, injected
176
+ * so this module stays testable and so the plugin has one recycle path),
177
+ * `copy` (the copy primitive, injected for the same reason), `now`.
178
+ * @returns a result the tool can report verbatim.
179
+ */
180
+ export async function stageForRecycle(source, options = {}) {
181
+ const { stagingRoot = defaultStagingRoot(), recycle, copy = cp, now = new Date() } = options;
182
+ if (typeof recycle !== 'function') throw new TypeError('stageForRecycle needs a recycle function');
183
+
184
+ if (isNetworkPath(source) && isShareRoot(source)) {
185
+ return { ok: false, error: 'refusing to delete a network share root itself' };
186
+ }
187
+ const name = basename(String(source).replace(/[\\/]+$/, ''));
188
+ if (name.length === 0) {
189
+ return { ok: false, error: 'refusing a path with no item name' };
190
+ }
191
+
192
+ let original;
193
+ try {
194
+ original = await walkTree(source);
195
+ } catch (error) {
196
+ return { ok: false, error: `cannot stage this item: ${error.message}` };
197
+ }
198
+ const bytes = totalBytes(original);
199
+
200
+ try {
201
+ await mkdir(stagingRoot, { recursive: true });
202
+ } catch (error) {
203
+ return { ok: false, error: `cannot create the staging directory "${stagingRoot}": ${error.message}` };
204
+ }
205
+
206
+ // Fail in a second rather than halfway through a copy, and say the numbers: the
207
+ // caller has to know whether to free space, shrink the target, or pick another
208
+ // staging volume (config `stagingRoot`).
209
+ try {
210
+ const space = await statfs(stagingRoot);
211
+ const free = Number(space.bavail) * Number(space.bsize);
212
+ if (Number.isFinite(free) && free < bytes * 1.02 + 64 * 1024 * 1024) {
213
+ return {
214
+ ok: false,
215
+ error: `not enough free space on the staging volume for "${stagingRoot}": `
216
+ + `the item is ${bytes} bytes and ${free} are available. Free space there, or point `
217
+ + '`stagingRoot` at another local NTFS volume.',
218
+ };
219
+ }
220
+ } catch {
221
+ // No statfs support: the copy will report a real failure if space runs out.
222
+ }
223
+
224
+ const stageDir = join(stagingRoot, `${stampOf(now)}-${name}`);
225
+ const dest = join(stageDir, name);
226
+
227
+ try {
228
+ await mkdir(stageDir);
229
+ } catch (error) {
230
+ return { ok: false, error: `cannot create the staging folder "${stageDir}": ${error.message}` };
231
+ }
232
+
233
+ try {
234
+ await copy(source, dest, { recursive: true, preserveTimestamps: true, dereference: false });
235
+ } catch (error) {
236
+ return {
237
+ ok: false,
238
+ staged: stageDir,
239
+ error: `copying to the local staging volume failed: ${error.message}. The original was not touched; `
240
+ + `a partial copy may be left at "${stageDir}".`,
241
+ };
242
+ }
243
+
244
+ let stagedTree;
245
+ try {
246
+ stagedTree = await walkTree(dest);
247
+ } catch (error) {
248
+ return { ok: false, staged: stageDir, error: `cannot verify the copy: ${error.message}` };
249
+ }
250
+ const difference = compareTrees(original, stagedTree);
251
+ if (difference !== undefined) {
252
+ return {
253
+ ok: false,
254
+ staged: stageDir,
255
+ error: `the copy does not match the original (${difference}), so nothing was deleted. `
256
+ + `The copy is at "${stageDir}" for inspection.`,
257
+ };
258
+ }
259
+ const verification = `${original.size} entries, ${bytes} bytes`;
260
+
261
+ // The copy is in the bin or nothing is: this is the step that turns "copied"
262
+ // into "recoverable".
263
+ const recycling = await recycle([stageDir]);
264
+ if (!Array.isArray(recycling.recycled) || recycling.recycled.length !== 1) {
265
+ const why = recycling.failures?.[0]?.error ?? 'the recycle-bin bridge did not confirm it';
266
+ return {
267
+ ok: false,
268
+ staged: stageDir,
269
+ error: `the verified copy could not be moved into the Recycle Bin (${why}), so the original was kept. `
270
+ + `The copy is at "${stageDir}".`,
271
+ };
272
+ }
273
+
274
+ try {
275
+ await rm(source, { recursive: true, force: false, maxRetries: 1 });
276
+ } catch (error) {
277
+ const remaining = await walkTree(source)
278
+ .then((tree) => [...tree.keys()].slice(0, 20))
279
+ .catch(() => []);
280
+ return {
281
+ ok: true,
282
+ staged: stageDir,
283
+ recycled: true,
284
+ verification,
285
+ sourceRemoved: false,
286
+ remaining,
287
+ error: `the content is in the Recycle Bin, but removing the original failed: ${error.message}`,
288
+ };
289
+ }
290
+
291
+ return { ok: true, staged: stageDir, recycled: true, verification, sourceRemoved: true };
292
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-delete-guard",
3
- "version": "2.2.3",
4
- "description": "Force every DSH file deletion through the OS Recycle Bin. Intercepts shell tool calls at tools/pre-execute (pwsh, bash, cmd, the persistent terminal), rewrites destructive delete commands into a recoverable recycle-bin move (Win32 SHFileOperation / SHQueryRecycleBin), and blocks permanent-erase escapes.",
3
+ "version": "2.4.2",
4
+ "description": "Force every DSH file deletion through the OS Recycle Bin. Intercepts shell tool calls at tools/pre-execute (pwsh, bash, cmd, the persistent terminal), rewrites destructive delete commands into a recoverable recycle-bin move (Win32 SHFileOperation / SHQueryRecycleBin), and blocks permanent-erase escapes — including content destroyed without a delete verb (in-place rewrites of the only copy, unchecked null slice endpoints). Deletions on UNC shares — which have no Recycle Bin — are staged to a local NTFS volume, verified, and recycled from there before the original is removed.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {