dsh-vigil 0.0.1
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/LICENSE +201 -0
- package/README.md +188 -0
- package/client.js +4652 -0
- package/cordis.patch.yml +7 -0
- package/docs/DETAIL.md +66 -0
- package/icon.png +0 -0
- package/illustrations/notice.png +0 -0
- package/illustrations/warning.png +0 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +75 -0
- package/rules/audit.yaml +130 -0
- package/rules/manifest.json +7 -0
- package/rules/sentinel.yaml +289 -0
- package/src/alert-route.js +194 -0
- package/src/approval.js +398 -0
- package/src/artwork-route.js +87 -0
- package/src/audit/ast.js +213 -0
- package/src/audit/install-scan.js +127 -0
- package/src/audit/lexer.js +307 -0
- package/src/audit/narrative.js +320 -0
- package/src/audit/rules.js +1440 -0
- package/src/audit/scan.js +880 -0
- package/src/audit-clear-route.js +89 -0
- package/src/audit-feed.js +265 -0
- package/src/audit-log.js +887 -0
- package/src/config-schema.js +194 -0
- package/src/config.js +580 -0
- package/src/delete/command-kinds.js +46 -0
- package/src/delete/lex.js +46 -0
- package/src/delete/parser-posix.js +1427 -0
- package/src/delete/parser-pwsh.js +1729 -0
- package/src/delete/parser.js +2082 -0
- package/src/delete/policy.js +680 -0
- package/src/delete/quarantine.js +417 -0
- package/src/index.js +1134 -0
- package/src/install-scan-route.js +58 -0
- package/src/install-watch.js +389 -0
- package/src/integrity.js +509 -0
- package/src/live-config.js +88 -0
- package/src/quarantine-route.js +74 -0
- package/src/quarantine-view.js +44 -0
- package/src/rules/pack.js +423 -0
- package/src/rules/update.js +341 -0
- package/src/rules/yaml.js +186 -0
- package/src/sage-action-route.js +63 -0
- package/src/sage-provision.js +716 -0
- package/src/sentinel/guard.js +392 -0
- package/src/sentinel/hook.js +546 -0
- package/src/sentinel/rules.js +488 -0
- package/src/sentinel/sage-load.js +79 -0
- package/src/sentinel/sage.js +550 -0
- package/src/tools.js +727 -0
- package/src/update-check.js +339 -0
- package/src/util.js +400 -0
- package/threats/README.md +25 -0
|
@@ -0,0 +1,1729 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Windows shell deletion-intent parser: PowerShell 5.1/7 + cmd.exe.
|
|
3
|
+
*
|
|
4
|
+
* Internal module used by `parser.js`. Pure string analysis only: no process
|
|
5
|
+
* spawning, no filesystem access, no dependencies. It never throws; internal
|
|
6
|
+
* failures degrade to an `unparsed` statement.
|
|
7
|
+
*
|
|
8
|
+
* The parser emits *partial statements* whose `rawTargets` are resolved to
|
|
9
|
+
* absolute paths later by parser.js (shared expansion/root-classification).
|
|
10
|
+
*
|
|
11
|
+
* Masking convention (same as parser-posix): a `\u0001` sentinel protects a
|
|
12
|
+
* literal character from later variable expansion (e.g. `` `$ `` or `'$x'`).
|
|
13
|
+
*
|
|
14
|
+
* @module delete/parser-pwsh
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { ESC, MAX_TOKENS, unmask, commandName as baseName } from './lex.js'
|
|
18
|
+
|
|
19
|
+
/** PowerShell aliases relevant to deletion / listing. */
|
|
20
|
+
const PWSH_ALIASES = new Map([
|
|
21
|
+
['rm', 'remove-item'],
|
|
22
|
+
['del', 'remove-item'],
|
|
23
|
+
['erase', 'remove-item'],
|
|
24
|
+
['rd', 'remove-item'],
|
|
25
|
+
['rmdir', 'remove-item'],
|
|
26
|
+
['ri', 'remove-item'],
|
|
27
|
+
['remove-item', 'remove-item'],
|
|
28
|
+
['gci', 'get-childitem'],
|
|
29
|
+
['ls', 'get-childitem'],
|
|
30
|
+
['dir', 'get-childitem'],
|
|
31
|
+
['get-childitem', 'get-childitem'],
|
|
32
|
+
['get-item', 'get-item'],
|
|
33
|
+
['gi', 'get-item'],
|
|
34
|
+
['gc', 'get-content'],
|
|
35
|
+
['cat', 'get-content'],
|
|
36
|
+
['type', 'get-content'],
|
|
37
|
+
['where', 'where-object'],
|
|
38
|
+
['where-object', 'where-object'],
|
|
39
|
+
['?', 'where-object'],
|
|
40
|
+
['%', 'foreach-object'],
|
|
41
|
+
['foreach', 'foreach-object'],
|
|
42
|
+
['foreach-object', 'foreach-object'],
|
|
43
|
+
['select', 'select-object'],
|
|
44
|
+
['select-object', 'select-object'],
|
|
45
|
+
['iex', 'invoke-expression'],
|
|
46
|
+
['invoke-expression', 'invoke-expression'],
|
|
47
|
+
['iwr', 'invoke-webrequest'],
|
|
48
|
+
['irm', 'invoke-restmethod'],
|
|
49
|
+
['cp', 'copy-item'],
|
|
50
|
+
['copy', 'copy-item'],
|
|
51
|
+
['mv', 'move-item'],
|
|
52
|
+
['move', 'move-item'],
|
|
53
|
+
['ni', 'new-item'],
|
|
54
|
+
['si', 'set-item'],
|
|
55
|
+
['sc', 'set-content'],
|
|
56
|
+
['ac', 'add-content'],
|
|
57
|
+
['clc', 'clear-content'],
|
|
58
|
+
['cli', 'clear-item'],
|
|
59
|
+
]);
|
|
60
|
+
|
|
61
|
+
/** Parameters of Remove-Item relevant to static deletion analysis. */
|
|
62
|
+
const REMOVE_ITEM_PARAMS = [
|
|
63
|
+
'path',
|
|
64
|
+
'literalpath',
|
|
65
|
+
'filter',
|
|
66
|
+
'include',
|
|
67
|
+
'exclude',
|
|
68
|
+
'recurse',
|
|
69
|
+
'force',
|
|
70
|
+
'whatif',
|
|
71
|
+
'confirm',
|
|
72
|
+
'verbose',
|
|
73
|
+
'debug',
|
|
74
|
+
'erroraction',
|
|
75
|
+
'warningaction',
|
|
76
|
+
'informationaction',
|
|
77
|
+
'progressaction',
|
|
78
|
+
'credential',
|
|
79
|
+
'stream',
|
|
80
|
+
'usetransaction',
|
|
81
|
+
'passthru',
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
/** Short/ambiguous parameter spellings agents actually type. */
|
|
85
|
+
const REMOVE_ITEM_PARAM_ALIASES = Object.assign(Object.create(null), {
|
|
86
|
+
p: 'path',
|
|
87
|
+
pat: 'path',
|
|
88
|
+
pa: 'path',
|
|
89
|
+
lp: 'literalpath',
|
|
90
|
+
l: 'literalpath',
|
|
91
|
+
r: 'recurse',
|
|
92
|
+
rec: 'recurse',
|
|
93
|
+
f: 'force',
|
|
94
|
+
fo: 'force',
|
|
95
|
+
wi: 'whatif',
|
|
96
|
+
w: 'whatif',
|
|
97
|
+
c: 'confirm',
|
|
98
|
+
cf: 'confirm',
|
|
99
|
+
inc: 'include',
|
|
100
|
+
i: 'include',
|
|
101
|
+
exc: 'exclude',
|
|
102
|
+
e: 'exclude',
|
|
103
|
+
fi: 'filter',
|
|
104
|
+
'': null,
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
/** Parameters that consume one following value when no `:` value is given. */
|
|
108
|
+
const PARAM_WITH_VALUE = new Set([
|
|
109
|
+
'erroraction',
|
|
110
|
+
'warningaction',
|
|
111
|
+
'informationaction',
|
|
112
|
+
'progressaction',
|
|
113
|
+
'credential',
|
|
114
|
+
'stream',
|
|
115
|
+
]);
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Default object shape for a partial statement.
|
|
119
|
+
* @param {object} fields
|
|
120
|
+
* @returns {object}
|
|
121
|
+
*/
|
|
122
|
+
function makePartial(fields) {
|
|
123
|
+
return Object.assign(
|
|
124
|
+
{
|
|
125
|
+
shell: 'pwsh',
|
|
126
|
+
text: '',
|
|
127
|
+
command: '',
|
|
128
|
+
isDelete: false,
|
|
129
|
+
dryRun: false,
|
|
130
|
+
recursive: false,
|
|
131
|
+
force: false,
|
|
132
|
+
wildcard: false,
|
|
133
|
+
deleteKind: 'none',
|
|
134
|
+
unparsed: false,
|
|
135
|
+
notes: [],
|
|
136
|
+
risks: [],
|
|
137
|
+
rawTargets: [],
|
|
138
|
+
},
|
|
139
|
+
fields,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Detect glob characters in a PowerShell argument (wildcards are expanded by
|
|
145
|
+
* the cmdlet, quoted or not; `-LiteralPath` callers disable this).
|
|
146
|
+
* @param {string} text
|
|
147
|
+
* @returns {{hasGlob:boolean, globKind:string}}
|
|
148
|
+
*/
|
|
149
|
+
function psGlobFromText(text) {
|
|
150
|
+
const value = String(text || '');
|
|
151
|
+
const kinds = new Set();
|
|
152
|
+
if (value.includes('*')) kinds.add('asterisk');
|
|
153
|
+
if (value.includes('?')) kinds.add('question');
|
|
154
|
+
if (/\[[^\]]*\]/.test(value)) kinds.add('bracket');
|
|
155
|
+
if (kinds.size === 0) return { hasGlob: false, globKind: 'none' };
|
|
156
|
+
if (kinds.size > 1) return { hasGlob: true, globKind: 'mixed' };
|
|
157
|
+
return { hasGlob: true, globKind: kinds.values().next().value };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Build a raw target from a PowerShell token.
|
|
162
|
+
* @param {{value:string, hasGlob?:boolean, globKind?:string}} token
|
|
163
|
+
* @param {boolean} literal `-LiteralPath` semantics: never a glob
|
|
164
|
+
* @param {object} [extra]
|
|
165
|
+
* @returns {object}
|
|
166
|
+
*/
|
|
167
|
+
function psTarget(token, literal, extra) {
|
|
168
|
+
const glob = literal ? { hasGlob: false, globKind: 'none' } : { hasGlob: Boolean(token.hasGlob), globKind: token.globKind || 'none' };
|
|
169
|
+
// `(Join-Path $x y)` / `$(...)` is computed at runtime: resolving the literal
|
|
170
|
+
// text as a path would invent a target and hide the real one.
|
|
171
|
+
const synthetic = /^\s*\$?\(/.test(String(token.value ?? ''));
|
|
172
|
+
return Object.assign(
|
|
173
|
+
{
|
|
174
|
+
raw: unmask(token.value),
|
|
175
|
+
text: token.value,
|
|
176
|
+
hasGlob: glob.hasGlob,
|
|
177
|
+
globKind: glob.globKind,
|
|
178
|
+
...(synthetic ? { synthetic: true } : {}),
|
|
179
|
+
},
|
|
180
|
+
extra || {},
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Build a raw target from an inline parameter value (`-Path:C:\x`).
|
|
186
|
+
* @param {string} value masked value
|
|
187
|
+
* @param {boolean} literal
|
|
188
|
+
* @returns {object}
|
|
189
|
+
*/
|
|
190
|
+
function psTargetInline(value, literal) {
|
|
191
|
+
const glob = literal ? { hasGlob: false, globKind: 'none' } : psGlobFromText(value);
|
|
192
|
+
const synthetic = /^\s*\$?\(/.test(String(value ?? ''));
|
|
193
|
+
return {
|
|
194
|
+
raw: unmask(value),
|
|
195
|
+
text: value,
|
|
196
|
+
hasGlob: glob.hasGlob,
|
|
197
|
+
globKind: glob.globKind,
|
|
198
|
+
...(synthetic ? { synthetic: true } : {}),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** A synthetic `.` root token / target. */
|
|
203
|
+
function dotToken() {
|
|
204
|
+
return { value: '.', text: '.', raw: '.', hasGlob: false, globKind: 'none' };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Parse a PowerShell parameter word.
|
|
209
|
+
* @param {string} value
|
|
210
|
+
* @returns {{name:string, inline:string|undefined}|null}
|
|
211
|
+
*/
|
|
212
|
+
function parseParamName(value) {
|
|
213
|
+
if (typeof value !== 'string' || value.length < 2 || value[0] !== '-' || value === '--%') return null;
|
|
214
|
+
const match = /^-([A-Za-z][A-Za-z0-9_]*)(?::([\s\S]*))?$/.exec(value);
|
|
215
|
+
if (!match) return null;
|
|
216
|
+
return { name: match[1].toLowerCase(), inline: match[2] };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Resolve a (possibly abbreviated) Remove-Item parameter name.
|
|
221
|
+
* @param {string} name
|
|
222
|
+
* @returns {string|null}
|
|
223
|
+
*/
|
|
224
|
+
function resolveDeleteParam(name) {
|
|
225
|
+
if (name === '') return null;
|
|
226
|
+
if (Object.prototype.hasOwnProperty.call(REMOVE_ITEM_PARAM_ALIASES, name)) {
|
|
227
|
+
return REMOVE_ITEM_PARAM_ALIASES[name] || null;
|
|
228
|
+
}
|
|
229
|
+
const matches = REMOVE_ITEM_PARAMS.filter((param) => param.startsWith(name));
|
|
230
|
+
if (matches.length === 1) return matches[0];
|
|
231
|
+
if (matches.length > 1) {
|
|
232
|
+
const exact = matches.find((param) => param === name);
|
|
233
|
+
if (exact) return exact;
|
|
234
|
+
// Prefer the first parameter in canonical order (path, literalpath, ...).
|
|
235
|
+
return matches[0];
|
|
236
|
+
}
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Interpret a PowerShell boolean value / switch presence.
|
|
242
|
+
* @param {string|undefined} inline
|
|
243
|
+
* @returns {boolean}
|
|
244
|
+
*/
|
|
245
|
+
function booleanValue(inline) {
|
|
246
|
+
if (inline === undefined) return true;
|
|
247
|
+
const value = unmask(inline).trim().toLowerCase().replace(/^["']|["']$/g, '');
|
|
248
|
+
if (value === 'false' || value === '$false' || value === '0' || value === 'no') return false;
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Find the closing bracket matching `open`.
|
|
254
|
+
* @param {string} src
|
|
255
|
+
* @param {number} open
|
|
256
|
+
* @param {string} openChar
|
|
257
|
+
* @param {string} closeChar
|
|
258
|
+
* @returns {number} index of the closing char, or `src.length`
|
|
259
|
+
*/
|
|
260
|
+
function findMatching(src, open, openChar, closeChar) {
|
|
261
|
+
let depth = 0;
|
|
262
|
+
let quote = null;
|
|
263
|
+
for (let i = open; i < src.length; i += 1) {
|
|
264
|
+
const c = src[i];
|
|
265
|
+
if (quote === "'") {
|
|
266
|
+
if (c === "'") {
|
|
267
|
+
if (src[i + 1] === "'") {
|
|
268
|
+
i += 1;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
quote = null;
|
|
272
|
+
}
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
if (quote === '"') {
|
|
276
|
+
if (c === '`') {
|
|
277
|
+
i += 1;
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
if (c === '"') {
|
|
281
|
+
if (src[i + 1] === '"') {
|
|
282
|
+
i += 1;
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
quote = null;
|
|
286
|
+
}
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (c === "'" || c === '"') {
|
|
290
|
+
quote = c;
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
if (c === openChar) depth += 1;
|
|
294
|
+
else if (c === closeChar) {
|
|
295
|
+
depth -= 1;
|
|
296
|
+
if (depth === 0) return i;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return src.length;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Split PowerShell arguments on top-level commas.
|
|
304
|
+
* @param {string} src
|
|
305
|
+
* @returns {string[]}
|
|
306
|
+
*/
|
|
307
|
+
function splitPwshArguments(src) {
|
|
308
|
+
const parts = [];
|
|
309
|
+
let start = 0;
|
|
310
|
+
let quote = null;
|
|
311
|
+
let depth = 0;
|
|
312
|
+
for (let i = 0; i < src.length; i += 1) {
|
|
313
|
+
const c = src[i];
|
|
314
|
+
if (quote === "'") {
|
|
315
|
+
if (c === "'") quote = null;
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
if (quote === '"') {
|
|
319
|
+
if (c === '`') i += 1;
|
|
320
|
+
else if (c === '"') quote = null;
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
if (c === "'" || c === '"') {
|
|
324
|
+
quote = c;
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (c === '(' || c === '[' || c === '{') depth += 1;
|
|
328
|
+
else if (c === ')' || c === ']' || c === '}') depth -= 1;
|
|
329
|
+
else if (c === ',' && depth === 0) {
|
|
330
|
+
parts.push(src.slice(start, i));
|
|
331
|
+
start = i + 1;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
parts.push(src.slice(start));
|
|
335
|
+
return parts.map((part) => part.trim()).filter((part) => part.length > 0);
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Tokenize one PowerShell pipeline stage.
|
|
340
|
+
*
|
|
341
|
+
* Quotes, backtick escapes, `$(...)`, `@(...)`, script blocks `{...}` and
|
|
342
|
+
* here-strings are kept inside a single token where appropriate.
|
|
343
|
+
*
|
|
344
|
+
* @param {string} src
|
|
345
|
+
* @returns {Array<object>}
|
|
346
|
+
*/
|
|
347
|
+
function tokenizePwsh(src) {
|
|
348
|
+
const tokens = [];
|
|
349
|
+
const n = src.length;
|
|
350
|
+
let i = 0;
|
|
351
|
+
|
|
352
|
+
while (i < n && tokens.length < MAX_TOKENS) {
|
|
353
|
+
const c = src[i];
|
|
354
|
+
if (c === ' ' || c === '\t' || c === '\r' || c === '\n') {
|
|
355
|
+
i += 1;
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
if (c === '#' && (i === 0 || /\s/.test(src[i - 1]))) break;
|
|
359
|
+
if (c === ';' || c === '|' || c === ',') {
|
|
360
|
+
i += 1;
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (c === '&' && src[i + 1] !== '&') {
|
|
364
|
+
i += 1;
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
// Redirection operators (`>`, `>>`, `2>&1`, `*>` ...).
|
|
368
|
+
const redirect = /^(?:[0-9*])?(?:>>|>|<)(?:&[0-9]+)?/.exec(src.slice(i));
|
|
369
|
+
if (redirect) {
|
|
370
|
+
i += redirect[0].length;
|
|
371
|
+
tokens.push({ op: true, value: redirect[0], raw: redirect[0] });
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
// Here-strings @" ... "@ / @' ... '@
|
|
375
|
+
if (c === '@' && (src[i + 1] === '"' || src[i + 1] === "'")) {
|
|
376
|
+
const quoteChar = src[i + 1];
|
|
377
|
+
const lineStart = /^\r?\n/.exec(src.slice(i + 2));
|
|
378
|
+
if (lineStart) {
|
|
379
|
+
const terminator = '\n' + quoteChar + '@';
|
|
380
|
+
let end = src.indexOf(terminator, i + 2 + lineStart[0].length);
|
|
381
|
+
let content;
|
|
382
|
+
if (end < 0) {
|
|
383
|
+
end = n;
|
|
384
|
+
content = src.slice(i + 2 + lineStart[0].length);
|
|
385
|
+
} else {
|
|
386
|
+
content = src.slice(i + 2 + lineStart[0].length, end);
|
|
387
|
+
end += terminator.length;
|
|
388
|
+
}
|
|
389
|
+
tokens.push({ value: content, raw: content, quoted: true, hasGlob: false, globKind: 'none' });
|
|
390
|
+
i = Math.min(end, n);
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
const before = i;
|
|
396
|
+
let value = '';
|
|
397
|
+
let raw = '';
|
|
398
|
+
let quote = null;
|
|
399
|
+
let quotedAny = false;
|
|
400
|
+
let hasSub = false;
|
|
401
|
+
|
|
402
|
+
while (i < n) {
|
|
403
|
+
const ch = src[i];
|
|
404
|
+
if (quote === "'") {
|
|
405
|
+
if (ch === "'") {
|
|
406
|
+
if (src[i + 1] === "'") {
|
|
407
|
+
value += "'";
|
|
408
|
+
raw += "'";
|
|
409
|
+
i += 2;
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
quote = null;
|
|
413
|
+
i += 1;
|
|
414
|
+
continue;
|
|
415
|
+
}
|
|
416
|
+
if (ch === '$' || ch === '%') value += ESC + ch;
|
|
417
|
+
else value += ch;
|
|
418
|
+
raw += ch;
|
|
419
|
+
i += 1;
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (quote === '"') {
|
|
423
|
+
if (ch === '"') {
|
|
424
|
+
if (src[i + 1] === '"') {
|
|
425
|
+
value += '"';
|
|
426
|
+
raw += '"';
|
|
427
|
+
i += 2;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
quote = null;
|
|
431
|
+
i += 1;
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
if (ch === '`') {
|
|
435
|
+
const next = src[i + 1];
|
|
436
|
+
if (next === undefined) {
|
|
437
|
+
i += 1;
|
|
438
|
+
continue;
|
|
439
|
+
}
|
|
440
|
+
if (next === '$' || next === '%' || next === '`') value += ESC + next;
|
|
441
|
+
else if (next === 'n') value += '\n';
|
|
442
|
+
else if (next === 't') value += '\t';
|
|
443
|
+
else if (next === 'r') value += '\r';
|
|
444
|
+
else if (next === '0') value += '\0';
|
|
445
|
+
else value += next;
|
|
446
|
+
raw += next;
|
|
447
|
+
i += 2;
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
450
|
+
if (ch === '$' && src[i + 1] === '(') {
|
|
451
|
+
const end = findMatching(src, i + 1, '(', ')');
|
|
452
|
+
const segment = src.slice(i, Math.min(end + 1, n));
|
|
453
|
+
value += segment;
|
|
454
|
+
raw += segment;
|
|
455
|
+
hasSub = true;
|
|
456
|
+
i = Math.min(end + 1, n);
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
value += ch;
|
|
460
|
+
raw += ch;
|
|
461
|
+
i += 1;
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// Unquoted.
|
|
466
|
+
if (ch === "'" || ch === '"') {
|
|
467
|
+
quote = ch;
|
|
468
|
+
quotedAny = true;
|
|
469
|
+
i += 1;
|
|
470
|
+
continue;
|
|
471
|
+
}
|
|
472
|
+
if (ch === '`') {
|
|
473
|
+
const next = src[i + 1];
|
|
474
|
+
if (next === undefined) {
|
|
475
|
+
i += 1;
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
if (next === '$' || next === '%' || next === '`') value += ESC + next;
|
|
479
|
+
else if (next === 'n') value += '\n';
|
|
480
|
+
else if (next === 't') value += '\t';
|
|
481
|
+
else if (next === 'r') value += '\r';
|
|
482
|
+
else if (next === '0') value += '\0';
|
|
483
|
+
else value += next;
|
|
484
|
+
raw += next;
|
|
485
|
+
i += 2;
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
if (ch === '$' && src[i + 1] === '(') {
|
|
489
|
+
const end = findMatching(src, i + 1, '(', ')');
|
|
490
|
+
const segment = src.slice(i, Math.min(end + 1, n));
|
|
491
|
+
value += segment;
|
|
492
|
+
raw += segment;
|
|
493
|
+
hasSub = true;
|
|
494
|
+
i = Math.min(end + 1, n);
|
|
495
|
+
continue;
|
|
496
|
+
}
|
|
497
|
+
if (ch === '@' && src[i + 1] === '(') {
|
|
498
|
+
const end = findMatching(src, i + 1, '(', ')');
|
|
499
|
+
const segment = src.slice(i, Math.min(end + 1, n));
|
|
500
|
+
value += segment;
|
|
501
|
+
raw += segment;
|
|
502
|
+
i = Math.min(end + 1, n);
|
|
503
|
+
continue;
|
|
504
|
+
}
|
|
505
|
+
if (ch === '@' && src[i + 1] === '{') {
|
|
506
|
+
const end = findMatching(src, i + 1, '{', '}');
|
|
507
|
+
const segment = src.slice(i, Math.min(end + 1, n));
|
|
508
|
+
value += segment;
|
|
509
|
+
raw += segment;
|
|
510
|
+
i = Math.min(end + 1, n);
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (ch === '(' || ch === '{' || ch === '[') {
|
|
514
|
+
const close = ch === '(' ? ')' : ch === '{' ? '}' : ']';
|
|
515
|
+
const end = findMatching(src, i, ch, close);
|
|
516
|
+
const segment = src.slice(i, Math.min(end + 1, n));
|
|
517
|
+
value += segment;
|
|
518
|
+
raw += segment;
|
|
519
|
+
i = Math.min(end + 1, n);
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') break;
|
|
523
|
+
if (ch === ';' || ch === '|' || ch === ',' || ch === '<' || ch === '>' || ch === '&') break;
|
|
524
|
+
value += ch;
|
|
525
|
+
raw += ch;
|
|
526
|
+
i += 1;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (value.length > 0 || raw.length > 0) {
|
|
530
|
+
// PowerShell wildcard expansion applies to the resulting string value
|
|
531
|
+
// regardless of quoting, so classify globs from the value itself.
|
|
532
|
+
const glob = psGlobFromText(value);
|
|
533
|
+
tokens.push({
|
|
534
|
+
value,
|
|
535
|
+
raw,
|
|
536
|
+
quoted: quotedAny,
|
|
537
|
+
hasSub,
|
|
538
|
+
hasGlob: glob.hasGlob,
|
|
539
|
+
globKind: glob.globKind,
|
|
540
|
+
});
|
|
541
|
+
}
|
|
542
|
+
if (i === before) i += 1;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
return tokens;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* Redirect targets a `>` (or `2>`) would truncate. `>>` appends, `> $null` and
|
|
550
|
+
* `> NUL` discard output, so none of them are destructive.
|
|
551
|
+
* @param {Array<object>} tokens
|
|
552
|
+
* @returns {Array<object>} target tokens
|
|
553
|
+
*/
|
|
554
|
+
function collectTruncateRedirects(tokens) {
|
|
555
|
+
const targets = [];
|
|
556
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
557
|
+
const token = tokens[i];
|
|
558
|
+
if (!token.op || !/^[0-9]?>$/.test(token.value)) continue;
|
|
559
|
+
const next = tokens[i + 1];
|
|
560
|
+
if (!next || next.op) continue;
|
|
561
|
+
const value = unmask(next.value ?? '').trim().replace(/^['"]|['"]$/g, '');
|
|
562
|
+
// `$null` / `NUL` / `/dev/null` discard output; they are not files.
|
|
563
|
+
if (value === '' || /^\$?(?:null|nul)$/i.test(value) || /^\/dev\/(?:null|stdout|stderr)$/.test(value)) continue;
|
|
564
|
+
targets.push(next);
|
|
565
|
+
}
|
|
566
|
+
return targets;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Drop redirection operators and their targets from a token list.
|
|
571
|
+
* @param {Array<object>} tokens
|
|
572
|
+
* @returns {Array<object>}
|
|
573
|
+
*/
|
|
574
|
+
function stripRedirects(tokens) {
|
|
575
|
+
const out = [];
|
|
576
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
577
|
+
if (tokens[i].op) {
|
|
578
|
+
if (i + 1 < tokens.length && !tokens[i + 1].op) i += 1;
|
|
579
|
+
continue;
|
|
580
|
+
}
|
|
581
|
+
out.push(tokens[i]);
|
|
582
|
+
}
|
|
583
|
+
return out;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Split a PowerShell chunk into pipeline stages at top-level `|`.
|
|
588
|
+
* `|` inside quotes, `(...)`, `$(...)` or `{...}` is left untouched.
|
|
589
|
+
* @param {string} src
|
|
590
|
+
* @returns {string[]}
|
|
591
|
+
*/
|
|
592
|
+
function splitPwshPipeline(src) {
|
|
593
|
+
const stages = [];
|
|
594
|
+
const n = src.length;
|
|
595
|
+
let start = 0;
|
|
596
|
+
let i = 0;
|
|
597
|
+
let quote = null;
|
|
598
|
+
let depth = 0;
|
|
599
|
+
while (i < n) {
|
|
600
|
+
const c = src[i];
|
|
601
|
+
if (quote === "'") {
|
|
602
|
+
if (c === "'") quote = null;
|
|
603
|
+
i += 1;
|
|
604
|
+
continue;
|
|
605
|
+
}
|
|
606
|
+
if (quote === '"') {
|
|
607
|
+
if (c === '`') {
|
|
608
|
+
i += 2;
|
|
609
|
+
continue;
|
|
610
|
+
}
|
|
611
|
+
if (c === '"') quote = null;
|
|
612
|
+
i += 1;
|
|
613
|
+
continue;
|
|
614
|
+
}
|
|
615
|
+
if (c === "'" || c === '"') {
|
|
616
|
+
quote = c;
|
|
617
|
+
i += 1;
|
|
618
|
+
continue;
|
|
619
|
+
}
|
|
620
|
+
if (c === '(' || c === '{') {
|
|
621
|
+
depth += 1;
|
|
622
|
+
i += 1;
|
|
623
|
+
continue;
|
|
624
|
+
}
|
|
625
|
+
if (c === ')' || c === '}') {
|
|
626
|
+
if (depth > 0) depth -= 1;
|
|
627
|
+
i += 1;
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
if (c === '|' && depth === 0) {
|
|
631
|
+
stages.push(src.slice(start, i));
|
|
632
|
+
i += 1;
|
|
633
|
+
start = i;
|
|
634
|
+
continue;
|
|
635
|
+
}
|
|
636
|
+
i += 1;
|
|
637
|
+
}
|
|
638
|
+
stages.push(src.slice(start));
|
|
639
|
+
return stages.map((stage) => stage.trim()).filter((stage) => stage.length > 0);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* Mask quoted strings / comments so heuristic scans do not match text literals.
|
|
644
|
+
* @param {string} src
|
|
645
|
+
* @returns {string}
|
|
646
|
+
*/
|
|
647
|
+
function maskPwshStrings(src) {
|
|
648
|
+
let out = '';
|
|
649
|
+
let i = 0;
|
|
650
|
+
const n = src.length;
|
|
651
|
+
while (i < n) {
|
|
652
|
+
const c = src[i];
|
|
653
|
+
if (c === "'") {
|
|
654
|
+
out += ' ';
|
|
655
|
+
i += 1;
|
|
656
|
+
while (i < n) {
|
|
657
|
+
if (src[i] === "'" && src[i + 1] === "'") {
|
|
658
|
+
out += ' ';
|
|
659
|
+
i += 2;
|
|
660
|
+
continue;
|
|
661
|
+
}
|
|
662
|
+
out += src[i] === '\n' ? '\n' : ' ';
|
|
663
|
+
if (src[i] === "'") {
|
|
664
|
+
i += 1;
|
|
665
|
+
break;
|
|
666
|
+
}
|
|
667
|
+
i += 1;
|
|
668
|
+
}
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
if (c === '"') {
|
|
672
|
+
out += ' ';
|
|
673
|
+
i += 1;
|
|
674
|
+
while (i < n) {
|
|
675
|
+
if (src[i] === '`') {
|
|
676
|
+
out += ' ';
|
|
677
|
+
i += 2;
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
680
|
+
out += src[i] === '\n' ? '\n' : ' ';
|
|
681
|
+
if (src[i] === '"') {
|
|
682
|
+
i += 1;
|
|
683
|
+
break;
|
|
684
|
+
}
|
|
685
|
+
i += 1;
|
|
686
|
+
}
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
if (c === '#') {
|
|
690
|
+
while (i < n && src[i] !== '\n') {
|
|
691
|
+
out += ' ';
|
|
692
|
+
i += 1;
|
|
693
|
+
}
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
out += c;
|
|
697
|
+
i += 1;
|
|
698
|
+
}
|
|
699
|
+
return out;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* Detect `[System.IO.File]::Delete(...)` / `[IO.Directory]::Delete(...,$true)`.
|
|
704
|
+
* Returns a partial statement when the stage is (or contains) such a call.
|
|
705
|
+
* @param {string} stageText
|
|
706
|
+
* @returns {object|null}
|
|
707
|
+
*/
|
|
708
|
+
function detectDotNetDelete(stageText) {
|
|
709
|
+
const match = /\[\s*(?:System\.)?([A-Za-z0-9_.]+)\s*\]\s*::\s*Delete\s*\(/i.exec(stageText);
|
|
710
|
+
if (!match) return detectInstanceDelete(stageText);
|
|
711
|
+
const className = match[1];
|
|
712
|
+
const direct = /^\s*[\[(]/.test(stageText) && match.index <= stageText.length - stageText.trimStart().length + 2;
|
|
713
|
+
if (!direct) {
|
|
714
|
+
return makePartial({
|
|
715
|
+
text: stageText.trim(),
|
|
716
|
+
command: className.toLowerCase() + '::delete',
|
|
717
|
+
isDelete: true,
|
|
718
|
+
deleteKind: 'io-delete',
|
|
719
|
+
unparsed: true,
|
|
720
|
+
notes: ['在脚本块/嵌套表达式中检测到 .NET Delete 调用,目标无法静态解析'],
|
|
721
|
+
risks: ['unknown-construct'],
|
|
722
|
+
});
|
|
723
|
+
}
|
|
724
|
+
const open = match.index + match[0].length - 1;
|
|
725
|
+
const close = findMatching(stageText, open, '(', ')');
|
|
726
|
+
const argsText = stageText.slice(open + 1, close);
|
|
727
|
+
const args = splitPwshArguments(argsText);
|
|
728
|
+
const literalClass = className.toLowerCase();
|
|
729
|
+
const rawTargets = [];
|
|
730
|
+
const notes = [];
|
|
731
|
+
const risks = [];
|
|
732
|
+
if (args.length > 0 && args[0]) {
|
|
733
|
+
const argTokens = tokenizePwsh(args[0]);
|
|
734
|
+
if (argTokens.length > 0) {
|
|
735
|
+
rawTargets.push(psTarget(argTokens[0], true, { note: '.NET API 删除目标' }));
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
let recursive = false;
|
|
739
|
+
if (literalClass.includes('directory')) {
|
|
740
|
+
recursive = args.length > 1 ? booleanValue(args[1]) : false;
|
|
741
|
+
if (recursive) notes.push('Directory.Delete(..., true) 递归删除目录');
|
|
742
|
+
} else if (literalClass.includes('file')) {
|
|
743
|
+
notes.push('File.Delete 删除单个文件');
|
|
744
|
+
} else {
|
|
745
|
+
notes.push('未知 .NET 类型的 Delete 调用(' + className + ')');
|
|
746
|
+
risks.push('unknown-construct');
|
|
747
|
+
}
|
|
748
|
+
if (!rawTargets.length) {
|
|
749
|
+
return makePartial({
|
|
750
|
+
text: stageText.trim(),
|
|
751
|
+
command: literalClass + '::delete',
|
|
752
|
+
isDelete: true,
|
|
753
|
+
recursive,
|
|
754
|
+
deleteKind: 'io-delete',
|
|
755
|
+
unparsed: true,
|
|
756
|
+
notes: notes.concat('Delete 调用缺少可解析的目标参数'),
|
|
757
|
+
risks: risks.concat('unknown-construct'),
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
return makePartial({
|
|
761
|
+
text: stageText.trim(),
|
|
762
|
+
command: literalClass + '::delete',
|
|
763
|
+
isDelete: true,
|
|
764
|
+
recursive,
|
|
765
|
+
deleteKind: 'io-delete',
|
|
766
|
+
notes,
|
|
767
|
+
risks,
|
|
768
|
+
rawTargets,
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
/**
|
|
773
|
+
* Detect an instance-method `.Delete(...)` call:
|
|
774
|
+
*
|
|
775
|
+
* `[System.IO.DirectoryInfo]::new("path").Delete($true)`
|
|
776
|
+
* `(New-Object System.IO.DirectoryInfo "path").Delete()`
|
|
777
|
+
* `$di.Delete($true)` → unparsed (target unknown)
|
|
778
|
+
*
|
|
779
|
+
* The static `[Type]::Delete(...)` form is handled above; this is the equally
|
|
780
|
+
* common instance form, which used to fall through to "not a delete".
|
|
781
|
+
* @param {string} stageText
|
|
782
|
+
* @returns {object|null}
|
|
783
|
+
*/
|
|
784
|
+
function detectInstanceDelete(stageText) {
|
|
785
|
+
const call = /\.\s*Delete\s*\(/i.exec(stageText);
|
|
786
|
+
if (!call) return null;
|
|
787
|
+
const head = stageText.slice(0, call.index);
|
|
788
|
+
const typeMatch = /\[\s*(?:System\.)?([A-Za-z0-9_.]+)\s*\]/i.exec(head);
|
|
789
|
+
const className = typeMatch ? typeMatch[1] : '';
|
|
790
|
+
const literal = /::\s*new\s*\(\s*(['"])([\s\S]*?)\1/i.exec(head)
|
|
791
|
+
|| /New-Object\s+(?:-TypeName\s+)?['"]?(?:System\.)?[A-Za-z0-9_.]+['"]?\s+(['"])([\s\S]*?)\1/i.exec(head);
|
|
792
|
+
const open = call.index + call[0].length - 1;
|
|
793
|
+
const close = findMatching(stageText, open, '(', ')');
|
|
794
|
+
const argsText = close > open ? stageText.slice(open + 1, close) : '';
|
|
795
|
+
const literalClass = className.toLowerCase();
|
|
796
|
+
const recursive = literalClass.includes('directory') ? /(?:^|[\s,;(])\$true\b/i.test(argsText) : false;
|
|
797
|
+
|
|
798
|
+
if (!literal) {
|
|
799
|
+
return makePartial({
|
|
800
|
+
text: stageText.trim(),
|
|
801
|
+
command: (literalClass || 'object') + '.delete()',
|
|
802
|
+
isDelete: true,
|
|
803
|
+
recursive,
|
|
804
|
+
deleteKind: 'io-delete',
|
|
805
|
+
unparsed: true,
|
|
806
|
+
notes: ['检测到 .NET 实例 Delete() 调用,目标无法静态解析'],
|
|
807
|
+
risks: ['unknown-construct'],
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
const tokens = tokenizePwsh(literal[2]);
|
|
811
|
+
if (tokens.length === 0) {
|
|
812
|
+
return makePartial({
|
|
813
|
+
text: stageText.trim(),
|
|
814
|
+
command: (literalClass || 'object') + '.delete()',
|
|
815
|
+
isDelete: true,
|
|
816
|
+
recursive,
|
|
817
|
+
deleteKind: 'io-delete',
|
|
818
|
+
unparsed: true,
|
|
819
|
+
notes: ['检测到 .NET 实例 Delete() 调用,但目标参数为空'],
|
|
820
|
+
risks: ['unknown-construct'],
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
const notes = ['.NET 实例 Delete() 调用'];
|
|
824
|
+
if (recursive) notes.push('DirectoryInfo.Delete(..., true) 递归删除目录');
|
|
825
|
+
return makePartial({
|
|
826
|
+
text: stageText.trim(),
|
|
827
|
+
command: (literalClass || 'object') + '.delete()',
|
|
828
|
+
isDelete: true,
|
|
829
|
+
recursive,
|
|
830
|
+
deleteKind: 'io-delete',
|
|
831
|
+
notes,
|
|
832
|
+
rawTargets: [psTarget(tokens[0], true, { note: '.NET 实例 Delete() 删除目标' })],
|
|
833
|
+
});
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Parse a truncating write (`Clear-Content`, `Set-Content`, `Out-File`).
|
|
838
|
+
*
|
|
839
|
+
* The file is emptied/overwritten, which is destructive for the old content but
|
|
840
|
+
* is not a `Remove-Item`; reuse the Remove-Item target parser after dropping the
|
|
841
|
+
* data parameters (`-Value`, `-InputObject`) so their payload is not mistaken
|
|
842
|
+
* for a path.
|
|
843
|
+
*
|
|
844
|
+
* @param {string} command normalized command name
|
|
845
|
+
* @param {Array<object>} args tokens after the command word
|
|
846
|
+
* @param {string} text stage text
|
|
847
|
+
* @returns {object} partial statement
|
|
848
|
+
*/
|
|
849
|
+
function parseTruncate(command, args, text) {
|
|
850
|
+
/** @type {Array<object>} */
|
|
851
|
+
const targetArgs = [];
|
|
852
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
853
|
+
const value = unmask(args[i].value ?? '');
|
|
854
|
+
if (/^-(?:value|inputobject)(?::|$)/i.test(value)) {
|
|
855
|
+
if (!value.includes(':') && i + 1 < args.length) i += 1;
|
|
856
|
+
continue;
|
|
857
|
+
}
|
|
858
|
+
targetArgs.push(args[i]);
|
|
859
|
+
}
|
|
860
|
+
const partial = parseRemoveItem(targetArgs, text);
|
|
861
|
+
partial.command = command;
|
|
862
|
+
partial.deleteKind = 'truncate';
|
|
863
|
+
partial.notes = [...(partial.notes ?? []), '该命令会清空或覆盖文件原有内容(截断写入)'];
|
|
864
|
+
if (!partial.isDelete) {
|
|
865
|
+
partial.isDelete = true;
|
|
866
|
+
partial.unparsed = true;
|
|
867
|
+
partial.risks = [...new Set([...(partial.risks ?? []), 'unknown-construct'])];
|
|
868
|
+
}
|
|
869
|
+
return partial;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Parse a move/rename source target (`Move-Item`, `Rename-Item`).
|
|
874
|
+
*
|
|
875
|
+
* The statement is deliberately `isDelete: false` (the delete policy does not
|
|
876
|
+
* gate moves), but the resolved source target is kept so self-protection can
|
|
877
|
+
* refuse moving the plugin/state directory away.
|
|
878
|
+
*
|
|
879
|
+
* @param {string} command normalized command name
|
|
880
|
+
* @param {Array<object>} args tokens after the command word
|
|
881
|
+
* @param {string} text stage text
|
|
882
|
+
* @returns {object} partial statement
|
|
883
|
+
*/
|
|
884
|
+
function parseMove(command, args, text) {
|
|
885
|
+
const partial = parseRemoveItem(args, text);
|
|
886
|
+
partial.command = command;
|
|
887
|
+
partial.isDelete = false;
|
|
888
|
+
partial.deleteKind = 'move';
|
|
889
|
+
// Resolve the source/target paths even though moves are not delete intents:
|
|
890
|
+
// self-protection must see a relative `mv a b` run from `cd <pluginDir>`.
|
|
891
|
+
partial.resolveTargets = true;
|
|
892
|
+
partial.notes = [...(partial.notes ?? []), '移动/重命名会改变文件位置(不在删除策略内)'];
|
|
893
|
+
return partial;
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* Parse `Remove-Item` parameters / positional targets.
|
|
898
|
+
* @param {Array<object>} args tokens after the command word
|
|
899
|
+
* @param {string} text stage text
|
|
900
|
+
* @returns {object} partial statement (may set `needsInput` when no target)
|
|
901
|
+
*/
|
|
902
|
+
function parseRemoveItem(args, text) {
|
|
903
|
+
let recursive = false;
|
|
904
|
+
let force = false;
|
|
905
|
+
let dryRun = false;
|
|
906
|
+
let wildcardFlag = false;
|
|
907
|
+
const notes = [];
|
|
908
|
+
const risks = [];
|
|
909
|
+
const rawTargets = [];
|
|
910
|
+
let i = 0;
|
|
911
|
+
let verbatim = false;
|
|
912
|
+
|
|
913
|
+
while (i < args.length) {
|
|
914
|
+
const token = args[i];
|
|
915
|
+
const value = token.value;
|
|
916
|
+
if (verbatim) {
|
|
917
|
+
rawTargets.push(psTarget(token, false));
|
|
918
|
+
i += 1;
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
if (value === '--%') {
|
|
922
|
+
verbatim = true;
|
|
923
|
+
i += 1;
|
|
924
|
+
continue;
|
|
925
|
+
}
|
|
926
|
+
const param = parseParamName(value);
|
|
927
|
+
if (!param) {
|
|
928
|
+
// `rm -rf` is a POSIX habit that PowerShell itself rejects; treat the
|
|
929
|
+
// combined flags as -Recurse -Force so the call still gets the recursive
|
|
930
|
+
// decision instead of slipping through as a single-file delete.
|
|
931
|
+
if (/^-[rR][fF]$|^-[fF][rR]$/.test(value)) {
|
|
932
|
+
recursive = true;
|
|
933
|
+
force = true;
|
|
934
|
+
notes.push('将 -rf 视为 -Recurse -Force(PowerShell 不接受组合短选项)');
|
|
935
|
+
i += 1;
|
|
936
|
+
continue;
|
|
937
|
+
}
|
|
938
|
+
if (value.startsWith('-') && value.length > 1) {
|
|
939
|
+
notes.push('未识别的参数 ' + value);
|
|
940
|
+
i += 1;
|
|
941
|
+
continue;
|
|
942
|
+
}
|
|
943
|
+
rawTargets.push(psTarget(token, false));
|
|
944
|
+
i += 1;
|
|
945
|
+
continue;
|
|
946
|
+
}
|
|
947
|
+
const resolved = resolveDeleteParam(param.name);
|
|
948
|
+
if (!resolved) {
|
|
949
|
+
// `rm -rf`: parseParamName sees the name "rf", which no Remove-Item
|
|
950
|
+
// parameter starts with. Read the habitual pair as -Recurse -Force.
|
|
951
|
+
if (param.name === 'rf' || param.name === 'fr') {
|
|
952
|
+
recursive = true;
|
|
953
|
+
force = true;
|
|
954
|
+
notes.push('将 -rf 视为 -Recurse -Force(PowerShell 不接受组合短选项)');
|
|
955
|
+
}
|
|
956
|
+
i += 1;
|
|
957
|
+
continue;
|
|
958
|
+
}
|
|
959
|
+
if (resolved === 'path' || resolved === 'literalpath') {
|
|
960
|
+
const literal = resolved === 'literalpath';
|
|
961
|
+
if (param.inline !== undefined) {
|
|
962
|
+
rawTargets.push(psTargetInline(param.inline, literal));
|
|
963
|
+
i += 1;
|
|
964
|
+
continue;
|
|
965
|
+
}
|
|
966
|
+
i += 1;
|
|
967
|
+
let consumed = false;
|
|
968
|
+
while (i < args.length && !parseParamName(args[i].value) && args[i].value !== '--%') {
|
|
969
|
+
rawTargets.push(psTarget(args[i], literal));
|
|
970
|
+
i += 1;
|
|
971
|
+
consumed = true;
|
|
972
|
+
}
|
|
973
|
+
if (!consumed) notes.push('-' + param.name + ' 缺少路径值');
|
|
974
|
+
continue;
|
|
975
|
+
}
|
|
976
|
+
if (resolved === 'filter' || resolved === 'include' || resolved === 'exclude') {
|
|
977
|
+
let pattern = param.inline;
|
|
978
|
+
if (pattern === undefined && i + 1 < args.length && !parseParamName(args[i + 1].value)) {
|
|
979
|
+
pattern = args[i + 1].value;
|
|
980
|
+
i += 1;
|
|
981
|
+
}
|
|
982
|
+
if (typeof pattern === 'string') {
|
|
983
|
+
const glob = psGlobFromText(pattern);
|
|
984
|
+
if (resolved === 'include') {
|
|
985
|
+
recursive = true;
|
|
986
|
+
notes.push('-Include 隐含 -Recurse');
|
|
987
|
+
}
|
|
988
|
+
if (glob.hasGlob) {
|
|
989
|
+
wildcardFlag = true;
|
|
990
|
+
notes.push('-' + param.name + ' 使用通配符模式:' + unmask(pattern));
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
i += 1;
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
if (resolved === 'recurse') {
|
|
997
|
+
recursive = booleanValue(param.inline);
|
|
998
|
+
i += 1;
|
|
999
|
+
continue;
|
|
1000
|
+
}
|
|
1001
|
+
if (resolved === 'force') {
|
|
1002
|
+
force = booleanValue(param.inline);
|
|
1003
|
+
i += 1;
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
if (resolved === 'whatif') {
|
|
1007
|
+
dryRun = booleanValue(param.inline);
|
|
1008
|
+
i += 1;
|
|
1009
|
+
continue;
|
|
1010
|
+
}
|
|
1011
|
+
if (resolved === 'confirm') {
|
|
1012
|
+
if (param.inline !== undefined && booleanValue(param.inline) === false) {
|
|
1013
|
+
notes.push('-Confirm:$false 已禁用确认');
|
|
1014
|
+
}
|
|
1015
|
+
i += 1;
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
if (resolved && PARAM_WITH_VALUE.has(resolved) && param.inline === undefined && i + 1 < args.length && !parseParamName(args[i + 1].value)) {
|
|
1019
|
+
i += 1; // skip the parameter value
|
|
1020
|
+
}
|
|
1021
|
+
i += 1;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
const partial = makePartial({
|
|
1025
|
+
text,
|
|
1026
|
+
command: 'remove-item',
|
|
1027
|
+
isDelete: true,
|
|
1028
|
+
dryRun,
|
|
1029
|
+
recursive,
|
|
1030
|
+
force,
|
|
1031
|
+
wildcard: wildcardFlag,
|
|
1032
|
+
deleteKind: 'remove-item',
|
|
1033
|
+
notes,
|
|
1034
|
+
risks,
|
|
1035
|
+
rawTargets,
|
|
1036
|
+
});
|
|
1037
|
+
if (!rawTargets.length) partial.needsInput = true;
|
|
1038
|
+
return partial;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* Extract pipeline-producer information from Get-ChildItem / Get-Item.
|
|
1043
|
+
* @param {string} command canonical command name
|
|
1044
|
+
* @param {Array<object>} args
|
|
1045
|
+
* @returns {{roots:Array<object>, recursive:boolean, wildcard:boolean}|null}
|
|
1046
|
+
*/
|
|
1047
|
+
function pwshProducerInfo(command, args) {
|
|
1048
|
+
if (!['get-childitem', 'get-item'].includes(command)) return null;
|
|
1049
|
+
const roots = [];
|
|
1050
|
+
let recursive = false;
|
|
1051
|
+
let wildcard = false;
|
|
1052
|
+
let i = 0;
|
|
1053
|
+
while (i < args.length) {
|
|
1054
|
+
const token = args[i];
|
|
1055
|
+
const param = parseParamName(token.value);
|
|
1056
|
+
if (!param) {
|
|
1057
|
+
if (!token.value.startsWith('-')) roots.push(token);
|
|
1058
|
+
i += 1;
|
|
1059
|
+
continue;
|
|
1060
|
+
}
|
|
1061
|
+
const resolved = resolveDeleteParam(param.name);
|
|
1062
|
+
if (resolved === 'path' || resolved === 'literalpath') {
|
|
1063
|
+
if (param.inline !== undefined) {
|
|
1064
|
+
roots.push({ value: param.inline, hasGlob: !(resolved === 'literalpath') && psGlobFromText(param.inline).hasGlob });
|
|
1065
|
+
i += 1;
|
|
1066
|
+
continue;
|
|
1067
|
+
}
|
|
1068
|
+
i += 1;
|
|
1069
|
+
while (i < args.length && !parseParamName(args[i].value)) {
|
|
1070
|
+
roots.push(args[i]);
|
|
1071
|
+
i += 1;
|
|
1072
|
+
}
|
|
1073
|
+
continue;
|
|
1074
|
+
}
|
|
1075
|
+
if (resolved === 'recurse') {
|
|
1076
|
+
recursive = booleanValue(param.inline);
|
|
1077
|
+
i += 1;
|
|
1078
|
+
continue;
|
|
1079
|
+
}
|
|
1080
|
+
if (resolved === 'filter' || resolved === 'include' || resolved === 'exclude') {
|
|
1081
|
+
let pattern = param.inline;
|
|
1082
|
+
if (pattern === undefined && i + 1 < args.length) {
|
|
1083
|
+
pattern = args[i + 1].value;
|
|
1084
|
+
i += 1;
|
|
1085
|
+
}
|
|
1086
|
+
if (typeof pattern === 'string') {
|
|
1087
|
+
const glob = psGlobFromText(pattern);
|
|
1088
|
+
if (glob.hasGlob) wildcard = true;
|
|
1089
|
+
// Upstream `-Include` / glob `-Filter` implies a recursive producer
|
|
1090
|
+
// per FR-3.1 pipeline backtracking requirements.
|
|
1091
|
+
if (resolved === 'include' || (resolved === 'filter' && glob.hasGlob)) recursive = true;
|
|
1092
|
+
}
|
|
1093
|
+
i += 1;
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
i += 1;
|
|
1097
|
+
}
|
|
1098
|
+
if (!roots.length) roots.push(dotToken());
|
|
1099
|
+
return {
|
|
1100
|
+
roots: roots.map((token) => psTarget(token, false)),
|
|
1101
|
+
recursive,
|
|
1102
|
+
wildcard,
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
/**
|
|
1107
|
+
* Parse one PowerShell pipeline stage.
|
|
1108
|
+
* @param {string} stageText
|
|
1109
|
+
* @param {number} depth nesting guard for `foreach` statements
|
|
1110
|
+
* @returns {{partial: object|null, producer: object|null}}
|
|
1111
|
+
*/
|
|
1112
|
+
function parsePwshStage(stageText, depth) {
|
|
1113
|
+
const dotnet = detectDotNetDelete(stageText);
|
|
1114
|
+
if (dotnet) return { partial: dotnet, producer: null };
|
|
1115
|
+
|
|
1116
|
+
const rawTokens = tokenizePwsh(stageText);
|
|
1117
|
+
const redirTargets = collectTruncateRedirects(rawTokens);
|
|
1118
|
+
const tokens = stripRedirects(rawTokens);
|
|
1119
|
+
let index = 0;
|
|
1120
|
+
while (index < tokens.length) {
|
|
1121
|
+
const value = tokens[index].value;
|
|
1122
|
+
if (!value || value === '&') {
|
|
1123
|
+
index += 1;
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
// Skip assignment prefixes such as `$x = ...` (not a command invocation).
|
|
1127
|
+
if (/^\$[A-Za-z_][A-Za-z0-9_:]*$/.test(value) && tokens[index + 1] && tokens[index + 1].value === '=') {
|
|
1128
|
+
index += 3;
|
|
1129
|
+
continue;
|
|
1130
|
+
}
|
|
1131
|
+
break;
|
|
1132
|
+
}
|
|
1133
|
+
if (index >= tokens.length) return { partial: null, producer: null };
|
|
1134
|
+
const commandWord = tokens[index].value;
|
|
1135
|
+
let command = baseName(commandWord);
|
|
1136
|
+
command = PWSH_ALIASES.get(command) || command;
|
|
1137
|
+
const args = tokens.slice(index + 1);
|
|
1138
|
+
const stage = stageText.trim();
|
|
1139
|
+
|
|
1140
|
+
// `command > file` truncates `file` before the command even runs. `>>` only
|
|
1141
|
+
// appends; `> $null` / `> NUL` discard output and touch no file.
|
|
1142
|
+
const deleteOrTruncate = command === 'remove-item' || command === 'clear-content'
|
|
1143
|
+
|| command === 'set-content' || command === 'out-file' || command === 'invoke-expression';
|
|
1144
|
+
if (redirTargets.length > 0 && !deleteOrTruncate) {
|
|
1145
|
+
return {
|
|
1146
|
+
partial: makePartial({
|
|
1147
|
+
text: stage,
|
|
1148
|
+
command: 'redirect',
|
|
1149
|
+
isDelete: true,
|
|
1150
|
+
deleteKind: 'truncate',
|
|
1151
|
+
notes: ['重定向符号 > 会截断目标文件(>> 只追加)'],
|
|
1152
|
+
rawTargets: redirTargets.map(token => psTarget(token, false)),
|
|
1153
|
+
}),
|
|
1154
|
+
producer: null,
|
|
1155
|
+
};
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
if (command === 'remove-item') {
|
|
1159
|
+
return { partial: parseRemoveItem(args, stage), producer: null };
|
|
1160
|
+
}
|
|
1161
|
+
// Truncating writes destroy the old content just like a delete, but they are
|
|
1162
|
+
// not `Remove-Item`; without this they were silently allowed on any file.
|
|
1163
|
+
if (command === 'clear-content' || command === 'set-content' || command === 'out-file') {
|
|
1164
|
+
return { partial: parseTruncate(command, args, stage), producer: null };
|
|
1165
|
+
}
|
|
1166
|
+
// Moves are not deletions for the delete policy, but they are destructive for
|
|
1167
|
+
// the source location; self-protection needs their targets.
|
|
1168
|
+
if (command === 'move-item' || command === 'rename-item') {
|
|
1169
|
+
return { partial: parseMove(command, args, stage), producer: null };
|
|
1170
|
+
}
|
|
1171
|
+
if (command === 'invoke-expression') {
|
|
1172
|
+
return {
|
|
1173
|
+
partial: makePartial({
|
|
1174
|
+
text: stage,
|
|
1175
|
+
command: 'invoke-expression',
|
|
1176
|
+
isDelete: true,
|
|
1177
|
+
deleteKind: 'other',
|
|
1178
|
+
unparsed: true,
|
|
1179
|
+
notes: ['Invoke-Expression 动态执行命令,无法静态确认删除意图'],
|
|
1180
|
+
risks: ['unknown-construct'],
|
|
1181
|
+
}),
|
|
1182
|
+
producer: null,
|
|
1183
|
+
};
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
const producer = pwshProducerInfo(command, args);
|
|
1187
|
+
if (producer) {
|
|
1188
|
+
return {
|
|
1189
|
+
partial: makePartial({ text: stage, command }),
|
|
1190
|
+
producer,
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
// Script blocks / nested pipelines that contain a delete call
|
|
1195
|
+
// (`foreach ($d in $dirs) { Remove-Item ... $d }`, `... | ForEach-Object { ... }`).
|
|
1196
|
+
const masked = maskPwshStrings(stage);
|
|
1197
|
+
const looksLikeDelete = /(?:^|[\s{|;])(?:Remove-Item|ri|rm|del|erase|rd|rmdir)\b/i.test(masked) || /(?:^|::)\.?\s*Delete\s*\(/i.test(stage) || /\.\s*Delete\s*\(/i.test(stage);
|
|
1198
|
+
if (looksLikeDelete && /[{|]/.test(masked)) {
|
|
1199
|
+
const ioDelete = /\.\s*Delete\s*\(\s*\)?/i.test(masked) || /::\s*Delete\s*\(/i.test(masked);
|
|
1200
|
+
const recursive = /(?:^|[\s{|;])-recurse\b/i.test(masked);
|
|
1201
|
+
const force = /(?:^|[\s{|;])-force\b/i.test(masked);
|
|
1202
|
+
let variableName = null;
|
|
1203
|
+
const foreachLoop = /foreach\s*\(\s*\$([A-Za-z_][A-Za-z0-9_]*)/i.exec(masked);
|
|
1204
|
+
if (foreachLoop) variableName = '$' + foreachLoop[1];
|
|
1205
|
+
else if (/\$_/.test(masked)) variableName = '$_';
|
|
1206
|
+
else {
|
|
1207
|
+
const varArg = /(?:Remove-Item|ri|rm|del|erase|rd|rmdir)\b[^{}|;]*?(\$[A-Za-z_][A-Za-z0-9_]*)/i.exec(masked);
|
|
1208
|
+
if (varArg) variableName = varArg[1];
|
|
1209
|
+
}
|
|
1210
|
+
const rawTargets = variableName
|
|
1211
|
+
? [{ raw: variableName, text: variableName, hasGlob: false, globKind: 'none', scopeOverride: 'variable' }]
|
|
1212
|
+
: [];
|
|
1213
|
+
const notes = ['在脚本块或嵌套管道中检测到删除调用,目标无法静态解析'];
|
|
1214
|
+
if (recursive) notes.push('脚本块中的删除命令带有 -Recurse');
|
|
1215
|
+
return {
|
|
1216
|
+
partial: makePartial({
|
|
1217
|
+
text: stage,
|
|
1218
|
+
command,
|
|
1219
|
+
isDelete: true,
|
|
1220
|
+
recursive,
|
|
1221
|
+
force,
|
|
1222
|
+
deleteKind: ioDelete ? 'io-delete' : 'other',
|
|
1223
|
+
unparsed: true,
|
|
1224
|
+
notes,
|
|
1225
|
+
risks: ['unknown-construct'],
|
|
1226
|
+
rawTargets,
|
|
1227
|
+
}),
|
|
1228
|
+
producer: null,
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
return { partial: makePartial({ text: stage, command }), producer: null };
|
|
1233
|
+
}
|
|
1234
|
+
|
|
1235
|
+
/**
|
|
1236
|
+
* Parse a PowerShell chunk (which may be a pipeline).
|
|
1237
|
+
* @param {string} chunkText
|
|
1238
|
+
* @param {number} [depth]
|
|
1239
|
+
* @returns {object[]} partial statements
|
|
1240
|
+
*/
|
|
1241
|
+
export function parsePwshStatements(chunkText, depth) {
|
|
1242
|
+
const stages = splitPwshPipeline(String(chunkText || ''));
|
|
1243
|
+
const out = [];
|
|
1244
|
+
let upstream = null;
|
|
1245
|
+
|
|
1246
|
+
for (const stageText of stages) {
|
|
1247
|
+
let parsed;
|
|
1248
|
+
try {
|
|
1249
|
+
parsed = parsePwshStage(stageText, depth || 0);
|
|
1250
|
+
} catch {
|
|
1251
|
+
out.push(
|
|
1252
|
+
makePartial({
|
|
1253
|
+
text: stageText.trim(),
|
|
1254
|
+
command: '',
|
|
1255
|
+
unparsed: true,
|
|
1256
|
+
risks: ['unknown-construct'],
|
|
1257
|
+
notes: ['PowerShell 解析异常,已降级为不可解析语句'],
|
|
1258
|
+
}),
|
|
1259
|
+
);
|
|
1260
|
+
continue;
|
|
1261
|
+
}
|
|
1262
|
+
if (!parsed.partial) continue;
|
|
1263
|
+
const partial = parsed.partial;
|
|
1264
|
+
|
|
1265
|
+
if (partial.isDelete && partial.rawTargets.length === 0) {
|
|
1266
|
+
if (upstream) {
|
|
1267
|
+
const roots = upstream.roots && upstream.roots.length ? upstream.roots : [psTarget(dotToken(), false)];
|
|
1268
|
+
partial.rawTargets = roots.map((target) => Object.assign({}, target, { viaPipeline: true, note: '目标来自管道上游' }));
|
|
1269
|
+
partial.recursive = partial.recursive || upstream.recursive;
|
|
1270
|
+
partial.wildcard = partial.wildcard || upstream.wildcard;
|
|
1271
|
+
partial.risks.push('pipeline-generic');
|
|
1272
|
+
partial.notes.push('删除目标由管道从上游命令传递,实际范围取决于上游输出');
|
|
1273
|
+
delete partial.needsInput;
|
|
1274
|
+
} else {
|
|
1275
|
+
partial.unparsed = true;
|
|
1276
|
+
partial.risks.push('unknown-construct');
|
|
1277
|
+
partial.notes.push('删除命令缺少可解析的删除目标');
|
|
1278
|
+
}
|
|
1279
|
+
} else if (partial.isDelete) {
|
|
1280
|
+
delete partial.needsInput;
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
out.push(partial);
|
|
1284
|
+
if (parsed.producer) upstream = parsed.producer;
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
return out;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
/* ------------------------------------------------------------------------- *
|
|
1291
|
+
* cmd.exe support
|
|
1292
|
+
* ------------------------------------------------------------------------- */
|
|
1293
|
+
|
|
1294
|
+
/**
|
|
1295
|
+
* Build a cmd partial statement.
|
|
1296
|
+
* @param {object} fields
|
|
1297
|
+
* @returns {object}
|
|
1298
|
+
*/
|
|
1299
|
+
function makeCmdPartial(fields) {
|
|
1300
|
+
return makePartial(Object.assign({ shell: 'cmd' }, fields));
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
/**
|
|
1304
|
+
* Build a target from a cmd token.
|
|
1305
|
+
* @param {{value:string}} token
|
|
1306
|
+
* @param {object} [extra]
|
|
1307
|
+
* @returns {object}
|
|
1308
|
+
*/
|
|
1309
|
+
function cmdTarget(token, extra) {
|
|
1310
|
+
const value = token.value;
|
|
1311
|
+
let globKind = 'none';
|
|
1312
|
+
const kinds = new Set();
|
|
1313
|
+
if (value.includes('*')) kinds.add('asterisk');
|
|
1314
|
+
if (value.includes('?')) kinds.add('question');
|
|
1315
|
+
if (kinds.size > 1) globKind = 'mixed';
|
|
1316
|
+
else if (kinds.size === 1) globKind = kinds.values().next().value;
|
|
1317
|
+
return Object.assign(
|
|
1318
|
+
{
|
|
1319
|
+
raw: value,
|
|
1320
|
+
text: value,
|
|
1321
|
+
hasGlob: globKind !== 'none',
|
|
1322
|
+
globKind,
|
|
1323
|
+
},
|
|
1324
|
+
extra || {},
|
|
1325
|
+
);
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
/**
|
|
1329
|
+
* Tokenize a cmd.exe command line (double quotes group words).
|
|
1330
|
+
* @param {string} src
|
|
1331
|
+
* @returns {Array<{value:string, raw:string}>}
|
|
1332
|
+
*/
|
|
1333
|
+
function tokenizeCmd(src) {
|
|
1334
|
+
const tokens = [];
|
|
1335
|
+
const n = src.length;
|
|
1336
|
+
let i = 0;
|
|
1337
|
+
while (i < n && tokens.length < MAX_TOKENS) {
|
|
1338
|
+
const c = src[i];
|
|
1339
|
+
if (/\s/.test(c)) {
|
|
1340
|
+
i += 1;
|
|
1341
|
+
continue;
|
|
1342
|
+
}
|
|
1343
|
+
if (c === '|' || c === '&' || c === ';') {
|
|
1344
|
+
i += 1;
|
|
1345
|
+
continue;
|
|
1346
|
+
}
|
|
1347
|
+
const before = i;
|
|
1348
|
+
let value = '';
|
|
1349
|
+
while (i < n) {
|
|
1350
|
+
const ch = src[i];
|
|
1351
|
+
if (ch === '"') {
|
|
1352
|
+
i += 1;
|
|
1353
|
+
while (i < n && src[i] !== '"') {
|
|
1354
|
+
value += src[i];
|
|
1355
|
+
i += 1;
|
|
1356
|
+
}
|
|
1357
|
+
if (src[i] === '"') i += 1;
|
|
1358
|
+
continue;
|
|
1359
|
+
}
|
|
1360
|
+
if (ch === '^' && i + 1 < n) {
|
|
1361
|
+
value += src[i + 1];
|
|
1362
|
+
i += 2;
|
|
1363
|
+
continue;
|
|
1364
|
+
}
|
|
1365
|
+
if (/\s/.test(ch) || ch === '|' || ch === '&' || ch === ';') break;
|
|
1366
|
+
value += ch;
|
|
1367
|
+
i += 1;
|
|
1368
|
+
}
|
|
1369
|
+
if (value.length > 0) tokens.push({ value, raw: value });
|
|
1370
|
+
if (i === before) i += 1;
|
|
1371
|
+
}
|
|
1372
|
+
return tokens;
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
/**
|
|
1376
|
+
* Parse `del` / `erase`.
|
|
1377
|
+
* @param {Array<{value:string}>} args
|
|
1378
|
+
* @param {string} text
|
|
1379
|
+
* @param {string} command
|
|
1380
|
+
* @returns {object}
|
|
1381
|
+
*/
|
|
1382
|
+
function parseCmdDel(args, text, command) {
|
|
1383
|
+
let recursive = false;
|
|
1384
|
+
let force = false;
|
|
1385
|
+
const notes = [];
|
|
1386
|
+
const rawTargets = [];
|
|
1387
|
+
for (const token of args) {
|
|
1388
|
+
const value = token.value;
|
|
1389
|
+
if (/^\/[A-Za-z]/.test(value)) {
|
|
1390
|
+
const option = value.slice(1).toLowerCase();
|
|
1391
|
+
if (option.startsWith('s')) recursive = true;
|
|
1392
|
+
else if (option.startsWith('f') || option.startsWith('q')) force = true;
|
|
1393
|
+
else if (option.startsWith('p')) notes.push('/p 为交互确认');
|
|
1394
|
+
else if (option.startsWith('a')) notes.push('/a 按文件属性筛选目标');
|
|
1395
|
+
else notes.push('未识别的 del 选项 ' + value);
|
|
1396
|
+
continue;
|
|
1397
|
+
}
|
|
1398
|
+
rawTargets.push(cmdTarget(token));
|
|
1399
|
+
}
|
|
1400
|
+
if (!rawTargets.length) {
|
|
1401
|
+
return makeCmdPartial({
|
|
1402
|
+
text,
|
|
1403
|
+
command,
|
|
1404
|
+
isDelete: true,
|
|
1405
|
+
recursive,
|
|
1406
|
+
force,
|
|
1407
|
+
deleteKind: 'del',
|
|
1408
|
+
unparsed: true,
|
|
1409
|
+
notes: notes.concat(command + ' 缺少可解析的删除目标'),
|
|
1410
|
+
risks: ['unknown-construct'],
|
|
1411
|
+
});
|
|
1412
|
+
}
|
|
1413
|
+
return makeCmdPartial({
|
|
1414
|
+
text,
|
|
1415
|
+
command,
|
|
1416
|
+
isDelete: true,
|
|
1417
|
+
recursive,
|
|
1418
|
+
force,
|
|
1419
|
+
deleteKind: 'del',
|
|
1420
|
+
notes,
|
|
1421
|
+
rawTargets,
|
|
1422
|
+
});
|
|
1423
|
+
}
|
|
1424
|
+
|
|
1425
|
+
/**
|
|
1426
|
+
* Parse `rd` / `rmdir` (cmd.exe built-in).
|
|
1427
|
+
* @param {Array<{value:string}>} args
|
|
1428
|
+
* @param {string} text
|
|
1429
|
+
* @param {string} command
|
|
1430
|
+
* @returns {object}
|
|
1431
|
+
*/
|
|
1432
|
+
function parseCmdRd(args, text, command) {
|
|
1433
|
+
let recursive = false;
|
|
1434
|
+
let force = false;
|
|
1435
|
+
const notes = [];
|
|
1436
|
+
const rawTargets = [];
|
|
1437
|
+
for (const token of args) {
|
|
1438
|
+
const value = token.value;
|
|
1439
|
+
if (/^\/[A-Za-z]/.test(value)) {
|
|
1440
|
+
const option = value.slice(1).toLowerCase();
|
|
1441
|
+
if (option.startsWith('s')) recursive = true;
|
|
1442
|
+
else if (option.startsWith('q')) force = true;
|
|
1443
|
+
else notes.push('未识别的 ' + command + ' 选项 ' + value);
|
|
1444
|
+
continue;
|
|
1445
|
+
}
|
|
1446
|
+
rawTargets.push(cmdTarget(token));
|
|
1447
|
+
}
|
|
1448
|
+
if (!rawTargets.length) {
|
|
1449
|
+
return makeCmdPartial({
|
|
1450
|
+
text,
|
|
1451
|
+
command,
|
|
1452
|
+
isDelete: true,
|
|
1453
|
+
recursive,
|
|
1454
|
+
force,
|
|
1455
|
+
deleteKind: command === 'rd' ? 'rd' : 'rmdir',
|
|
1456
|
+
unparsed: true,
|
|
1457
|
+
notes: notes.concat(command + ' 缺少可解析的删除目标'),
|
|
1458
|
+
risks: ['unknown-construct'],
|
|
1459
|
+
});
|
|
1460
|
+
}
|
|
1461
|
+
return makeCmdPartial({
|
|
1462
|
+
text,
|
|
1463
|
+
command,
|
|
1464
|
+
isDelete: true,
|
|
1465
|
+
recursive,
|
|
1466
|
+
force,
|
|
1467
|
+
deleteKind: command === 'rd' ? 'rd' : 'rmdir',
|
|
1468
|
+
notes,
|
|
1469
|
+
rawTargets,
|
|
1470
|
+
});
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
/**
|
|
1474
|
+
* Parse `robocopy SRC DST /MIR` or `/PURGE`.
|
|
1475
|
+
* @param {Array<{value:string}>} args
|
|
1476
|
+
* @param {string} text
|
|
1477
|
+
* @returns {object|null}
|
|
1478
|
+
*/
|
|
1479
|
+
function parseRobocopy(args, text) {
|
|
1480
|
+
let mirror = false;
|
|
1481
|
+
let purge = false;
|
|
1482
|
+
let dryRun = false;
|
|
1483
|
+
const positional = [];
|
|
1484
|
+
const notes = [];
|
|
1485
|
+
for (const token of args) {
|
|
1486
|
+
const value = token.value;
|
|
1487
|
+
if (value.startsWith('/') && value.length > 1) {
|
|
1488
|
+
const option = value.slice(1).toLowerCase();
|
|
1489
|
+
if (option === 'mir') mirror = true;
|
|
1490
|
+
else if (option === 'purge') purge = true;
|
|
1491
|
+
else if (option === 'l' || option === 'list') dryRun = true;
|
|
1492
|
+
else if (option === 'mov' || option === 'move') notes.push('/MOVE 会从源目录删除已移动的文件');
|
|
1493
|
+
continue;
|
|
1494
|
+
}
|
|
1495
|
+
positional.push(token);
|
|
1496
|
+
}
|
|
1497
|
+
if (!mirror && !purge) return null;
|
|
1498
|
+
if (!positional.length) {
|
|
1499
|
+
return makeCmdPartial({
|
|
1500
|
+
text,
|
|
1501
|
+
command: 'robocopy',
|
|
1502
|
+
isDelete: true,
|
|
1503
|
+
recursive: true,
|
|
1504
|
+
deleteKind: 'robocopy-mirror',
|
|
1505
|
+
unparsed: true,
|
|
1506
|
+
notes: ['robocopy 缺少源/目标目录参数'],
|
|
1507
|
+
risks: ['mirror-delete', 'unknown-construct'],
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
const dest = positional.length > 1 ? positional[1] : null;
|
|
1511
|
+
notes.push(
|
|
1512
|
+
mirror
|
|
1513
|
+
? 'robocopy /MIR 会把目标目录(DST,本例中的删除目标)镜像成源目录,删除 DST 中源端不存在的文件'
|
|
1514
|
+
: 'robocopy /PURGE 会删除目标目录(DST)中源端不存在的文件',
|
|
1515
|
+
);
|
|
1516
|
+
if (!dest) {
|
|
1517
|
+
return makeCmdPartial({
|
|
1518
|
+
text,
|
|
1519
|
+
command: 'robocopy',
|
|
1520
|
+
isDelete: true,
|
|
1521
|
+
dryRun,
|
|
1522
|
+
recursive: true,
|
|
1523
|
+
deleteKind: 'robocopy-mirror',
|
|
1524
|
+
unparsed: true,
|
|
1525
|
+
notes: notes.concat('未找到 robocopy 目标目录(DST)'),
|
|
1526
|
+
risks: ['mirror-delete', 'unknown-construct'],
|
|
1527
|
+
});
|
|
1528
|
+
}
|
|
1529
|
+
return makeCmdPartial({
|
|
1530
|
+
text,
|
|
1531
|
+
command: 'robocopy',
|
|
1532
|
+
isDelete: true,
|
|
1533
|
+
dryRun,
|
|
1534
|
+
recursive: true,
|
|
1535
|
+
deleteKind: 'robocopy-mirror',
|
|
1536
|
+
notes,
|
|
1537
|
+
risks: ['mirror-delete'],
|
|
1538
|
+
rawTargets: [cmdTarget(dest, { note: 'robocopy 目标目录 DST' })],
|
|
1539
|
+
});
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* Parse a cmd `for` loop; the loop variable makes the intent uncertain.
|
|
1544
|
+
* @param {Array<{value:string}>} tokens full token list (starting with `for`)
|
|
1545
|
+
* @param {string} text
|
|
1546
|
+
* @param {number} depth
|
|
1547
|
+
* @returns {{partial: object|null, producer: null}}
|
|
1548
|
+
*/
|
|
1549
|
+
function parseCmdFor(tokens, text, depth) {
|
|
1550
|
+
const doIndex = tokens.findIndex((token) => token.value.toLowerCase() === 'do');
|
|
1551
|
+
if (doIndex < 0 || doIndex + 1 >= tokens.length) {
|
|
1552
|
+
return {
|
|
1553
|
+
partial: makeCmdPartial({
|
|
1554
|
+
text: text.trim(),
|
|
1555
|
+
command: 'for',
|
|
1556
|
+
unparsed: true,
|
|
1557
|
+
notes: ['cmd for 循环缺少 do 子句,无法静态解析'],
|
|
1558
|
+
risks: ['unknown-construct'],
|
|
1559
|
+
}),
|
|
1560
|
+
producer: null,
|
|
1561
|
+
};
|
|
1562
|
+
}
|
|
1563
|
+
const innerTokens = tokens.slice(doIndex + 1);
|
|
1564
|
+
const innerText = innerTokens.map((token) => token.raw).join(' ');
|
|
1565
|
+
const inner = parseCmdStage(innerText, (depth || 0) + 1);
|
|
1566
|
+
const loopVarToken = innerTokens.find((token) => /^%%?[A-Za-z]$/.test(token.value));
|
|
1567
|
+
const loopVar = loopVarToken ? loopVarToken.value : null;
|
|
1568
|
+
if (!inner.partial || !inner.partial.isDelete) {
|
|
1569
|
+
return {
|
|
1570
|
+
partial: makeCmdPartial({
|
|
1571
|
+
text: text.trim(),
|
|
1572
|
+
command: 'for',
|
|
1573
|
+
notes: ['cmd for 循环中未发现删除命令'],
|
|
1574
|
+
}),
|
|
1575
|
+
producer: null,
|
|
1576
|
+
};
|
|
1577
|
+
}
|
|
1578
|
+
const rawTargets = (inner.partial.rawTargets || []).map((target) => {
|
|
1579
|
+
if (loopVar && target.raw === loopVar) {
|
|
1580
|
+
return Object.assign({}, target, { scopeOverride: 'variable' });
|
|
1581
|
+
}
|
|
1582
|
+
if (/%{1,2}[A-Za-z]/.test(target.raw)) {
|
|
1583
|
+
return Object.assign({}, target, { scopeOverride: 'variable' });
|
|
1584
|
+
}
|
|
1585
|
+
return target;
|
|
1586
|
+
});
|
|
1587
|
+
if (!rawTargets.length && loopVar) {
|
|
1588
|
+
rawTargets.push({ raw: loopVar, text: loopVar, hasGlob: false, globKind: 'none', scopeOverride: 'variable' });
|
|
1589
|
+
}
|
|
1590
|
+
return {
|
|
1591
|
+
partial: makeCmdPartial({
|
|
1592
|
+
text: text.trim(),
|
|
1593
|
+
command: 'for',
|
|
1594
|
+
isDelete: true,
|
|
1595
|
+
recursive: Boolean(inner.partial.recursive),
|
|
1596
|
+
force: Boolean(inner.partial.force),
|
|
1597
|
+
deleteKind: inner.partial.deleteKind,
|
|
1598
|
+
unparsed: true,
|
|
1599
|
+
notes: (inner.partial.notes || []).concat('cmd for 循环变量无法静态展开,实际删除范围不确定'),
|
|
1600
|
+
risks: (inner.partial.risks || []).concat('unknown-construct'),
|
|
1601
|
+
rawTargets,
|
|
1602
|
+
}),
|
|
1603
|
+
producer: null,
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
/**
|
|
1608
|
+
* Parse one cmd.exe pipeline stage.
|
|
1609
|
+
* @param {string} stageText
|
|
1610
|
+
* @param {number} depth
|
|
1611
|
+
* @returns {{partial: object|null, producer: null}}
|
|
1612
|
+
*/
|
|
1613
|
+
function parseCmdMove(args, text, command) {
|
|
1614
|
+
const rawTargets = [];
|
|
1615
|
+
const notes = [];
|
|
1616
|
+
let force = false;
|
|
1617
|
+
for (const token of args) {
|
|
1618
|
+
const value = token.value;
|
|
1619
|
+
if (/^\/[A-Za-z]/.test(value)) {
|
|
1620
|
+
const option = value.slice(1).toLowerCase();
|
|
1621
|
+
if (option.startsWith('y')) force = true;
|
|
1622
|
+
else notes.push('未识别的 ' + command + ' 选项 ' + value);
|
|
1623
|
+
continue;
|
|
1624
|
+
}
|
|
1625
|
+
rawTargets.push(cmdTarget(token));
|
|
1626
|
+
}
|
|
1627
|
+
if (rawTargets.length < 2) {
|
|
1628
|
+
return makeCmdPartial({
|
|
1629
|
+
text,
|
|
1630
|
+
command,
|
|
1631
|
+
isDelete: false,
|
|
1632
|
+
force,
|
|
1633
|
+
deleteKind: 'move',
|
|
1634
|
+
resolveTargets: true,
|
|
1635
|
+
unparsed: true,
|
|
1636
|
+
notes: notes.concat(command + ' 缺少源/目标,无法确认移动范围'),
|
|
1637
|
+
risks: ['move', 'unknown-construct'],
|
|
1638
|
+
rawTargets,
|
|
1639
|
+
});
|
|
1640
|
+
}
|
|
1641
|
+
return makeCmdPartial({
|
|
1642
|
+
text,
|
|
1643
|
+
command,
|
|
1644
|
+
isDelete: false,
|
|
1645
|
+
force,
|
|
1646
|
+
deleteKind: 'move',
|
|
1647
|
+
resolveTargets: true,
|
|
1648
|
+
notes: notes.concat(command + ' 会移动/重命名目标'),
|
|
1649
|
+
risks: ['move'],
|
|
1650
|
+
rawTargets,
|
|
1651
|
+
});
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
function parseCmdStage(stageText, depth) {
|
|
1655
|
+
const tokens = tokenizeCmd(stageText);
|
|
1656
|
+
if (!tokens.length) return { partial: null, producer: null };
|
|
1657
|
+
const command = baseName(tokens[0].value);
|
|
1658
|
+
if (command === 'for') return parseCmdFor(tokens, stageText, depth || 0);
|
|
1659
|
+
const args = tokens.slice(1);
|
|
1660
|
+
if (command === 'del' || command === 'erase') {
|
|
1661
|
+
return { partial: parseCmdDel(args, stageText.trim(), command), producer: null };
|
|
1662
|
+
}
|
|
1663
|
+
if (command === 'rd' || command === 'rmdir') {
|
|
1664
|
+
return { partial: parseCmdRd(args, stageText.trim(), command), producer: null };
|
|
1665
|
+
}
|
|
1666
|
+
if (command === 'move' || command === 'ren' || command === 'rename') {
|
|
1667
|
+
return { partial: parseCmdMove(args, stageText.trim(), command), producer: null };
|
|
1668
|
+
}
|
|
1669
|
+
if (command === 'robocopy') {
|
|
1670
|
+
const partial = parseRobocopy(args, stageText.trim());
|
|
1671
|
+
if (partial) return { partial, producer: null };
|
|
1672
|
+
}
|
|
1673
|
+
return {
|
|
1674
|
+
partial: makeCmdPartial({ text: stageText.trim(), command }),
|
|
1675
|
+
producer: null,
|
|
1676
|
+
};
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
/**
|
|
1680
|
+
* Split a cmd chunk into pipeline stages on unquoted `|`.
|
|
1681
|
+
* @param {string} src
|
|
1682
|
+
* @returns {string[]}
|
|
1683
|
+
*/
|
|
1684
|
+
function splitCmdPipeline(src) {
|
|
1685
|
+
const stages = [];
|
|
1686
|
+
let start = 0;
|
|
1687
|
+
let inQuotes = false;
|
|
1688
|
+
for (let i = 0; i < src.length; i += 1) {
|
|
1689
|
+
const c = src[i];
|
|
1690
|
+
if (c === '"') {
|
|
1691
|
+
inQuotes = !inQuotes;
|
|
1692
|
+
continue;
|
|
1693
|
+
}
|
|
1694
|
+
if (c === '|' && !inQuotes) {
|
|
1695
|
+
stages.push(src.slice(start, i));
|
|
1696
|
+
start = i + 1;
|
|
1697
|
+
}
|
|
1698
|
+
}
|
|
1699
|
+
stages.push(src.slice(start));
|
|
1700
|
+
return stages.map((stage) => stage.trim()).filter((stage) => stage.length > 0);
|
|
1701
|
+
}
|
|
1702
|
+
|
|
1703
|
+
/**
|
|
1704
|
+
* Parse a cmd.exe chunk (which may be a pipeline).
|
|
1705
|
+
* @param {string} chunkText
|
|
1706
|
+
* @param {number} [depth]
|
|
1707
|
+
* @returns {object[]} partial statements
|
|
1708
|
+
*/
|
|
1709
|
+
export function parseCmdStatements(chunkText, depth) {
|
|
1710
|
+
const out = [];
|
|
1711
|
+
for (const stageText of splitCmdPipeline(String(chunkText || ''))) {
|
|
1712
|
+
try {
|
|
1713
|
+
const parsed = parseCmdStage(stageText, depth || 0);
|
|
1714
|
+
if (parsed.partial) out.push(parsed.partial);
|
|
1715
|
+
} catch {
|
|
1716
|
+
out.push(
|
|
1717
|
+
makeCmdPartial({
|
|
1718
|
+
text: stageText.trim(),
|
|
1719
|
+
command: '',
|
|
1720
|
+
unparsed: true,
|
|
1721
|
+
risks: ['unknown-construct'],
|
|
1722
|
+
notes: ['cmd 解析异常,已降级为不可解析语句'],
|
|
1723
|
+
}),
|
|
1724
|
+
);
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
return out;
|
|
1728
|
+
}
|
|
1729
|
+
|