1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
|
/**
* Shell Command Parser and Processor
*
* Provides advanced shell command parsing with support for:
* - Complex shell operators (||, &&, ;;, |&, <(, <<<, >>, >&, <&, etc.)
* - Quote handling (single and double quotes)
* - Variable substitution with ${} syntax
* - Pattern matching and globbing
* - Safe escaping for command injection protection
*/
class ShellParser {
constructor() {
// Shell operators that need special handling
this.SHELL_OPERATORS = [
"\\|\\|", // Logical OR
"\\&\\&", // Logical AND
";;", // Command separator
"\\|\\&", // Pipe with stderr
"\\<\\(", // Process substitution
"\\<\\<\\<", // Here string
">>", // Append redirect
">\\&", // Redirect with file descriptor
"<\\&", // Input redirect with file descriptor
"[&;()|<>]", // Basic operators
];
this.operatorPattern = `(?:${this.SHELL_OPERATORS.join("|")})`;
this.operatorRegex = new RegExp(`^${this.operatorPattern}$`);
// Characters that need escaping in shell contexts
this.SHELL_META_CHARS = "|&;()<> \t";
// Patterns for quoted strings
this.DOUBLE_QUOTE_PATTERN = '"((\\\\"|[^"])*?)"';
this.SINGLE_QUOTE_PATTERN = "'((\\\\'|[^'])*?)'";
this.COMMENT_PATTERN = /^#$/;
// Quote characters
this.SINGLE_QUOTE = "'";
this.DOUBLE_QUOTE = '"';
this.VARIABLE_PREFIX = "$";
// Generate unique delimiter for variable substitution
this.DELIMITER = this.generateUniqueDelimiter();
this.delimiterRegex = new RegExp(`^${this.DELIMITER}`);
}
/**
* Generate a unique delimiter for variable substitution
* @returns {string} Unique delimiter string
*/
generateUniqueDelimiter() {
let delimiter = "";
const maxValue = 4294967296; // 2^32
for (let i = 0; i < 4; i++) {
delimiter += (maxValue * Math.random()).toString(16);
}
return delimiter;
}
/**
* Escape shell command arguments for safe execution
* @param {Array} args - Array of command arguments
* @returns {string} Safely escaped command string
*/
escapeShellCommand(args) {
return args
.map((arg) => {
if (arg === "") return "''";
// Handle objects with operation property
if (arg && typeof arg === "object" && arg.op) {
return arg.op.replace(/(.)/g, "\\$1");
}
// Handle strings with spaces but no single quotes
if (/["\s]/.test(arg) && !/'/.test(arg)) {
return "'" + arg.replace(/(['\\])/g, "\\$1") + "'";
}
// Handle strings with quotes and spaces
if (/["'\s]/.test(arg)) {
return '"' + arg.replace(/(["\\$`!])/g, "\\$1") + '"';
}
// Escape other shell metacharacters
return String(arg).replace(
/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,
"$1\\$2",
);
})
.join(" ");
}
/**
* Find all regex matches with proper index handling
* @param {string} text - Text to search
* @param {RegExp} regex - Regular expression to match
* @returns {Array} Array of match results
*/
findMatches(text, regex) {
const originalIndex = regex.lastIndex;
const matches = [];
let match;
while ((match = regex.exec(text))) {
matches.push(match);
// Prevent infinite loops on zero-width matches
if (regex.lastIndex === match.index) {
regex.lastIndex += 1;
}
}
regex.lastIndex = originalIndex;
return matches;
}
/**
* Substitute variables in shell commands
* @param {Object|Function} variables - Variable mapping or function
* @param {string} delimiter - Delimiter prefix
* @param {string} key - Variable key to substitute
* @returns {string} Substituted value
*/
substituteVariable(variables, delimiter, key) {
const value =
typeof variables === "function" ? variables(key) : variables[key];
if (typeof value === "undefined" && key !== "") {
return "";
} else if (typeof value === "undefined") {
return "$";
}
if (typeof value === "object") {
return (
delimiter + this.DELIMITER + JSON.stringify(value) + this.DELIMITER
);
}
return delimiter + value;
}
/**
* Parse shell command with variable substitution and quote handling
* @param {string} command - Shell command to parse
* @param {Object|Function} variables - Variable mapping
* @param {Object} options - Parsing options
* @returns {Array} Parsed command tokens
*/
parseShellCommand(command, variables = {}, options = {}) {
const escapeChar = options.escape || "\\";
// Build regex pattern for tokenization
const tokenPattern = `(\\${escapeChar}['"\${this.SHELL_META_CHARS}]|[^\\s'"${this.SHELL_META_CHARS}])+`;
const fullPattern = [
`(${this.operatorPattern})`,
`(${tokenPattern}|${this.DOUBLE_QUOTE_PATTERN}|${this.SINGLE_QUOTE_PATTERN})+`,
].join("|");
const tokenRegex = new RegExp(fullPattern, "g");
const matches = this.findMatches(command, tokenRegex);
if (matches.length === 0) return [];
let commentFound = false;
return matches
.map((match) => {
const token = match[0];
if (!token || commentFound) return undefined;
// Handle shell operators
if (this.operatorRegex.test(token)) {
return { op: token };
}
let inQuotes = false;
let escaped = false;
let result = "";
let isGlob = false;
let currentQuote = null;
const processVariableSubstitution = () => {
let pos = i + 1;
let varName, endPos;
const nextChar = token.charAt(pos);
if (nextChar === "{") {
pos++;
if (token.charAt(pos) === "}") {
throw new Error(`Bad substitution: ${token.slice(i, pos + 1)}`);
}
endPos = token.indexOf("}", pos);
if (endPos < 0) {
throw new Error(`Bad substitution: ${token.slice(i)}`);
}
varName = token.slice(pos, endPos);
i = endPos;
} else if (/[*@#?$!_-]/.test(nextChar)) {
varName = nextChar;
i = pos;
} else {
const remaining = token.slice(pos);
const match = remaining.match(/[^\w\d_]/);
if (!match) {
varName = remaining;
i = token.length - 1;
} else {
varName = remaining.slice(0, match.index);
i = pos + match.index - 1;
}
}
return this.substituteVariable(variables, "", varName);
};
// Process each character in the token
for (let i = 0; i < token.length; i++) {
const char = token.charAt(i);
// Track glob patterns (* and ?)
isGlob = isGlob || (!inQuotes && (char === "*" || char === "?"));
if (escaped) {
result += char;
escaped = false;
} else if (inQuotes) {
if (char === currentQuote) {
inQuotes = false;
currentQuote = null;
} else if (currentQuote === this.SINGLE_QUOTE) {
result += char;
} else if (char === escapeChar) {
i++;
const nextChar = token.charAt(i);
if (
nextChar === this.DOUBLE_QUOTE ||
nextChar === escapeChar ||
nextChar === this.VARIABLE_PREFIX
) {
result += nextChar;
} else {
result += escapeChar + nextChar;
}
} else if (char === this.VARIABLE_PREFIX) {
result += processVariableSubstitution();
} else {
result += char;
}
} else if (char === this.DOUBLE_QUOTE || char === this.SINGLE_QUOTE) {
inQuotes = true;
currentQuote = char;
} else if (this.operatorRegex.test(char)) {
return { op: token };
} else if (this.COMMENT_PATTERN.test(char)) {
commentFound = true;
const comment = { comment: command.slice(match.index + i + 1) };
return result.length ? [result, comment] : [comment];
} else if (char === escapeChar) {
escaped = true;
} else if (char === this.VARIABLE_PREFIX) {
result += processVariableSubstitution();
} else {
result += char;
}
}
// Return glob pattern or regular string
if (isGlob) {
return { op: "glob", pattern: result };
}
return result;
})
.reduce((acc, token) => {
return typeof token === "undefined" ? acc : acc.concat(token);
}, []);
}
/**
* Main parsing function with post-processing
* @param {string} command - Shell command string
* @param {Object|Function} variables - Variable mapping
* @param {Object} options - Parsing options
* @returns {Array} Final parsed command tokens
*/
parse(command, variables, options) {
const tokens = this.parseShellCommand(command, variables, options);
if (typeof variables !== "function") {
return tokens;
}
// Post-process tokens for function-based variable substitution
return tokens.reduce((result, token) => {
if (typeof token === "object") {
return result.concat(token);
}
const parts = token.split(
new RegExp(`(${this.DELIMITER}.*?${this.DELIMITER})`, "g"),
);
if (parts.length === 1) {
return result.concat(parts[0]);
}
return result.concat(
parts.filter(Boolean).map((part) => {
if (this.delimiterRegex.test(part)) {
return JSON.parse(part.split(this.DELIMITER)[1]);
}
return part;
}),
);
}, []);
}
}
/**
* Shell command parser utilities
*/
class ShellUtils {
static quote = new ShellParser().escapeShellCommand.bind(new ShellParser());
static parse = new ShellParser().parse.bind(new ShellParser());
}
module.exports = {
ShellParser,
ShellUtils,
};
|