@pyrokine/mcp-ssh 2.4.3 → 3.1.0

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.
@@ -1,106 +1,257 @@
1
- function pushRisk(categories, signals, category, signal) {
2
- categories.add(category);
3
- signals.push(signal);
4
- }
5
- function hasBackgroundOperator(command) {
6
- let quote;
7
- let escaped = false;
8
- for (let index = 0; index < command.length; ++index) {
9
- const character = command[index];
10
- if (escaped) {
11
- escaped = false;
12
- continue;
13
- }
14
- if (character === '\\' && quote !== "'") {
15
- escaped = true;
16
- continue;
17
- }
18
- if (quote) {
19
- if (character === quote) {
1
+ function withoutQuotedText(command, shell) {
2
+ let index = 0;
3
+ // Shell commands, here-doc input, and arithmetic share the same expansion scanner.
4
+ const scan = (mode, limit, closing) => {
5
+ let quote;
6
+ let parentheses = 0;
7
+ let result = '';
8
+ const hereDocs = [];
9
+ let delimiter;
10
+ while (index < limit) {
11
+ const char = command[index];
12
+ const next = command[index + 1];
13
+ if (delimiter) {
14
+ if (!quote && /[\s;&|<>()]/.test(char)) {
15
+ if (!delimiter.started && /[ \t]/.test(char)) {
16
+ ++index;
17
+ continue;
18
+ }
19
+ if (delimiter.started) {
20
+ hereDocs.push({
21
+ delimiter: delimiter.value,
22
+ expand: !delimiter.quoted,
23
+ stripTabs: delimiter.stripTabs,
24
+ });
25
+ }
26
+ delimiter = undefined;
27
+ continue;
28
+ }
29
+ if (char === '\\' && quote !== "'" && (!quote || /[$`"\\\n]/.test(next ?? ''))) {
30
+ if (next !== '\n') {
31
+ delimiter.started = true;
32
+ delimiter.quoted = true;
33
+ delimiter.value += next ?? '';
34
+ }
35
+ index += 2;
36
+ }
37
+ else if (quote && char === quote) {
38
+ quote = undefined;
39
+ ++index;
40
+ }
41
+ else if (!quote && (char === "'" || char === '"')) {
42
+ delimiter.started = true;
43
+ delimiter.quoted = true;
44
+ quote = char;
45
+ ++index;
46
+ }
47
+ else {
48
+ delimiter.started = true;
49
+ delimiter.value += char;
50
+ ++index;
51
+ }
52
+ continue;
53
+ }
54
+ const escapes = (shell === 'posix' &&
55
+ char === '\\' &&
56
+ quote !== "'" &&
57
+ ((mode === 'shell' && !quote) || /[$`"\\\n]/.test(next ?? ''))) ||
58
+ (shell === 'powershell' && char === '`' && quote !== "'") ||
59
+ (shell === 'cmd' && char === '^' && !quote);
60
+ if (escapes) {
61
+ result += next === '\n' ? '' : ' ';
62
+ index += 2;
63
+ continue;
64
+ }
65
+ if (shell === 'posix' && quote !== "'") {
66
+ if (char === '$' && next === '(') {
67
+ const arithmetic = command[index + 2] === '(';
68
+ index += arithmetic ? 3 : 2;
69
+ result += `;${scan(arithmetic ? 'arithmetic' : 'shell', limit, ')')};`;
70
+ if (arithmetic && command[index] === ')') {
71
+ ++index;
72
+ }
73
+ continue;
74
+ }
75
+ if (char === '`' && closing !== '`') {
76
+ ++index;
77
+ result += `;${scan('shell', limit, '`')};`;
78
+ continue;
79
+ }
80
+ }
81
+ if (!quote && mode !== 'input' && closing && char === closing && parentheses === 0) {
82
+ ++index;
83
+ return result;
84
+ }
85
+ if (mode === 'input') {
86
+ result += char === '\n' ? '\n' : ' ';
87
+ ++index;
88
+ continue;
89
+ }
90
+ if (quote && char === quote) {
20
91
  quote = undefined;
92
+ result += ' ';
21
93
  }
22
- continue;
23
- }
24
- if (character === "'" || character === '"') {
25
- quote = character;
26
- continue;
27
- }
28
- if (character !== '&') {
29
- continue;
30
- }
31
- const previous = command[index - 1];
32
- const next = command[index + 1];
33
- if (previous === '&' || next === '&' || previous === '>' || previous === '<' || next === '>') {
34
- continue;
94
+ else if (!quote && (char === '"' || (shell !== 'cmd' && char === "'"))) {
95
+ quote = char;
96
+ result += ' ';
97
+ }
98
+ else if (shell === 'posix' &&
99
+ !quote &&
100
+ char === '#' &&
101
+ (index === 0 || /[\s;&|()]/.test(command[index - 1]))) {
102
+ while (index < limit && command[index] !== '\n') {
103
+ ++index;
104
+ }
105
+ continue;
106
+ }
107
+ else if (shell === 'posix' && !quote && mode === 'shell' && char === '<' && next === '<') {
108
+ if (command[index + 2] === '<') {
109
+ result += '<<<';
110
+ index += 3;
111
+ continue;
112
+ }
113
+ const stripTabs = command[index + 2] === '-';
114
+ delimiter = { value: '', quoted: false, started: false, stripTabs };
115
+ index += stripTabs ? 3 : 2;
116
+ result += ' ';
117
+ continue;
118
+ }
119
+ else if (shell === 'posix' && !quote && char === '\n' && hereDocs.length > 0) {
120
+ ++index;
121
+ result += '\n';
122
+ for (const doc of hereDocs.splice(0)) {
123
+ const bodyStart = index;
124
+ let bodyEnd = limit;
125
+ let afterDelimiter = limit;
126
+ // Delimiters are case-sensitive; input quotes never change Shell quote state.
127
+ for (let lineStart = index; lineStart < limit;) {
128
+ let lineEnd = lineStart;
129
+ let line = '';
130
+ do {
131
+ const newline = command.indexOf('\n', lineEnd);
132
+ const end = newline === -1 || newline >= limit ? limit : newline;
133
+ let part = command.slice(lineEnd, end);
134
+ if (doc.stripTabs) {
135
+ part = part.replace(/^\t+/, '');
136
+ }
137
+ lineEnd = end < limit ? end + 1 : limit;
138
+ const continued = doc.expand && end < limit && /(?:^|[^\\])(?:\\\\)*\\$/.test(part);
139
+ line += continued ? part.slice(0, -1) : part;
140
+ if (!continued) {
141
+ break;
142
+ }
143
+ } while (lineEnd < limit);
144
+ if (line === doc.delimiter) {
145
+ bodyEnd = lineStart;
146
+ afterDelimiter = lineEnd;
147
+ break;
148
+ }
149
+ lineStart = lineEnd;
150
+ }
151
+ index = bodyStart;
152
+ if (doc.expand) {
153
+ result += scan('input', bodyEnd);
154
+ }
155
+ index = afterDelimiter;
156
+ result += '\n';
157
+ }
158
+ continue;
159
+ }
160
+ else {
161
+ if (!quote && (char === '(' || char === ')')) {
162
+ parentheses += char === '(' ? 1 : -1;
163
+ }
164
+ result += quote || mode === 'arithmetic' ? ' ' : char;
165
+ }
166
+ ++index;
35
167
  }
36
- return true;
37
- }
38
- return false;
168
+ return result;
169
+ };
170
+ return scan('shell', command.length);
39
171
  }
40
- export function classifyCommandRisk(command, timeout) {
172
+ function hasBackgroundOperator(command) {
173
+ return /(?:^|[^&<>])&(?=$|[^&>])/.test(command);
174
+ }
175
+ export function classifyCommandRisk(command, timeout, shell = 'posix') {
41
176
  const signals = [];
42
177
  const categories = new Set();
43
- const pipeCount = (command.match(/\|/g) ?? []).length;
44
- const lowerCommand = command.toLowerCase();
45
- const background = hasBackgroundOperator(command);
46
- const continuous = /\b(?:tail\s+-f|journalctl\s+-f|watch|top|htop)\b/.test(command);
47
- const unboundedFind = /\bfind\b/.test(command) && !/\s-maxdepth\s+\d+/.test(command);
48
- const recursiveGrep = /\bgrep\s+(?:-\S*R|--recursive)\b/.test(command);
49
- if (command.length > 500) {
50
- pushRisk(categories, signals, 'complexity-signal', 'long_command');
51
- }
52
- if (pipeCount >= 3) {
53
- pushRisk(categories, signals, 'complexity-signal', 'long_pipeline');
54
- }
55
- if (recursiveGrep) {
56
- pushRisk(categories, signals, 'long-running', 'recursive_grep');
57
- }
58
- if (unboundedFind) {
59
- pushRisk(categories, signals, 'long-running', 'unbounded_find');
60
- }
61
- if (/\b(?:python|python3|node|perl|ruby)\b/.test(command)) {
62
- pushRisk(categories, signals, 'script-execution', 'interpreter_script');
63
- }
64
- if (/\bsleep\s+\d{2,}\b/.test(command) || continuous) {
65
- pushRisk(categories, signals, 'long-running', continuous ? 'continuous_command' : 'long_sleep');
66
- }
67
- if (background) {
68
- pushRisk(categories, signals, 'process-control', 'background_task');
69
- }
70
- const recursiveRemove = /\brm\b(?=[^\n;|&]*(?:\s-[a-z]*r[a-z]*\b|\s--recursive\b))/.test(lowerCommand);
71
- if (recursiveRemove || /\b(?:dd\s+if=|mkfs|fdisk|parted|shutdown|reboot)\b/.test(lowerCommand)) {
72
- pushRisk(categories, signals, 'destructive', 'destructive_command');
73
- }
74
- const processControl = /\b(?:pkill|killall)\b/.test(lowerCommand) || /\bkill\s+(?!-0(?:\s|$))/.test(lowerCommand);
75
- if (processControl) {
76
- pushRisk(categories, signals, 'process-control', 'process_control');
178
+ const add = (category, signal) => {
179
+ categories.add(category);
180
+ signals.push(signal);
181
+ };
182
+ const executable = withoutQuotedText(command, shell).toLowerCase();
183
+ if (shell === 'posix') {
184
+ if (/(?:^|[;&|]\s*|\b(?:sudo|doas)\s+)(?:rm|mkfs|fdisk|parted|shutdown|reboot)(?=\s|$)/m.test(executable)) {
185
+ add('destructive', 'destructive_command');
186
+ }
187
+ if (/\b(?:sudo|su\s+-|doas)\s+/.test(executable)) {
188
+ add('privilege-escalation', 'privileged_command');
189
+ }
190
+ if (/\b(?:killall|pkill)\b|\bkill\s+(?!-0\b)/.test(executable)) {
191
+ add('process-control', 'process_control');
192
+ }
193
+ if (/\b(?:systemctl|service|docker|kubectl)\s+(?:restart|stop|kill|delete|rm|down)\b/.test(executable)) {
194
+ add('service-control', 'service_control');
195
+ }
196
+ if (!timeout || timeout > 300_000) {
197
+ if (/\b(?:find\s+\S+|grep\s+-\S*[rR])\b/.test(executable)) {
198
+ add('long-running', 'unbounded_search');
199
+ }
200
+ }
201
+ if (/\b(?:tail\s+-f|journalctl\s+-f|watch|top|htop)\b/.test(executable)) {
202
+ add('long-running', 'continuous_command');
203
+ }
204
+ if (hasBackgroundOperator(executable)) {
205
+ add('process-control', 'background_task');
206
+ }
77
207
  }
78
- if (/\b(?:systemctl|service|docker|kubectl)\s+(?:restart|stop|kill|delete|rm|down)\b/.test(lowerCommand)) {
79
- pushRisk(categories, signals, 'service-control', 'service_control');
208
+ else if (shell === 'cmd') {
209
+ if (/\b(?:del|erase|rmdir|rd)\s+(?!\/\?)|\bformat\s+[a-z]:/.test(executable)) {
210
+ add('destructive', 'destructive_command');
211
+ }
212
+ if (/\btaskkill\s+\/f\b/.test(executable)) {
213
+ add('process-control', 'process_control');
214
+ }
215
+ if (/\brunas\s+\/user:/.test(executable)) {
216
+ add('privilege-escalation', 'privileged_command');
217
+ }
218
+ if ((!timeout || timeout > 300_000) && /\bdir\s+\/s\b/.test(executable)) {
219
+ add('long-running', 'unbounded_search');
220
+ }
80
221
  }
81
- if (/\b(?:password|passwd|token|authorization|cookie|secret|private[_-]?key)\b/i.test(command)) {
82
- pushRisk(categories, signals, 'credential-bearing', 'credential_bearing');
222
+ else {
223
+ if (/\b(?:remove-item|clear-content|format-volume)\b\s+/.test(executable)) {
224
+ add('destructive', 'destructive_command');
225
+ }
226
+ if (/\b(?:stop-process|stop-service|restart-service)\b/.test(executable)) {
227
+ add('process-control', 'process_control');
228
+ }
229
+ if (/\bstart-process\b[^\r\n;]*-verb\s+runas\b/.test(executable)) {
230
+ add('privilege-escalation', 'privileged_command');
231
+ }
232
+ if ((!timeout || timeout > 300_000) && /\bget-childitem\b[^\r\n;]*-recurse\b/.test(executable)) {
233
+ add('long-running', 'unbounded_search');
234
+ }
83
235
  }
84
- if (/\bsu\s+-?\s*[a-zA-Z_][a-zA-Z0-9_-]*\s+-c\b/.test(command)) {
85
- pushRisk(categories, signals, 'user-switch', 'direct_su_command');
236
+ const credentialArgument = /--password\b|--token\b|\$env:(?:password|token|secret)\s*=/.test(executable) ||
237
+ (/\bset\s+"?/.test(executable) && /\bset\s+"?(?:password|token|secret)=/i.test(command));
238
+ const authorizationHeader = /\b(?:curl|wget)\b[^\r\n;]*(?:-h|--header)\s*/.test(executable) &&
239
+ /\b(?:curl|wget)\b[^\r\n;]*(?:-H|--header)\s+['"]?authorization:/i.test(command);
240
+ if (credentialArgument || authorizationHeader) {
241
+ add('credential-bearing', 'credential_argument');
86
242
  }
87
243
  if (signals.length === 0) {
88
244
  return undefined;
89
245
  }
90
- const boundedTimeout = timeout !== undefined && timeout > 0 && timeout <= 300_000;
91
- const high = categories.has('destructive') ||
92
- categories.has('service-control') ||
93
- categories.has('process-control') ||
94
- continuous ||
95
- ((unboundedFind || recursiveGrep) && !boundedTimeout);
246
+ const high = ['destructive', 'process-control', 'service-control', 'privilege-escalation'].some((category) => categories.has(category)) || signals.includes('continuous_command');
96
247
  return {
97
248
  level: high ? 'high' : 'medium',
98
- categories: Array.from(categories),
249
+ categories: [...categories],
99
250
  signals,
100
- suggestion: signals.includes('direct_su_command')
101
- ? '建议使用 ssh_exec 的 runAs 参数或 ssh_exec_as_user,避免手写 su 命令造成引用和环境加载差异'
251
+ suggestion: categories.has('privilege-escalation') && shell === 'posix'
252
+ ? 'Use runAs or ssh_exec_as_user for user switching'
102
253
  : high
103
- ? '长任务使用 ssh_operation_start,交互命令使用 ssh_pty_start,破坏性操作执行前确认目标范围'
104
- : '如输出较大,请设置 maxOutputSize 或重定向到远端文件后分块读取',
254
+ ? 'Confirm the target and scope before executing this command'
255
+ : 'Use a bounded timeout or redirect large output to a file',
105
256
  };
106
257
  }
@@ -1,3 +1,6 @@
1
+ import type { SFTPWrapper } from 'ssh2';
2
+ import type { RemotePathStyle } from './types.js';
3
+ import type { OpenSshConnection } from './openssh.js';
1
4
  export declare const DIRECTORY_VERIFY_MAX_ENTRIES = 50000;
2
5
  export declare const DIRECTORY_VERIFY_MAX_MISMATCHES = 20;
3
6
  export declare const DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES: number;
@@ -9,6 +12,7 @@ export type DirectoryVerifyRequest = {
9
12
  sha256?: boolean;
10
13
  owner?: boolean;
11
14
  mode?: boolean;
15
+ aclSddl?: string;
12
16
  deletions?: boolean;
13
17
  staleFiles?: boolean;
14
18
  maxEntries?: number;
@@ -23,7 +27,7 @@ type ManifestEntry = {
23
27
  owner: string;
24
28
  sha256?: string;
25
29
  };
26
- type DirectoryManifestLimitReason = 'entries' | 'file_bytes' | 'total_bytes';
30
+ type DirectoryManifestLimitReason = 'entries' | 'file_bytes' | 'total_bytes' | 'depth';
27
31
  export type DirectoryManifest = {
28
32
  entries: ManifestEntry[];
29
33
  count: number;
@@ -36,8 +40,8 @@ export type DirectoryManifest = {
36
40
  };
37
41
  export declare function matchesDirectoryExclude(relativePath: string, patterns: string[] | undefined): boolean;
38
42
  export declare function createLocalDirectoryManifest(rootPath: string, request: DirectoryVerifyRequest, exclude?: string[], followSymlinks?: boolean): Promise<DirectoryManifest>;
43
+ export declare function createRemoteDirectoryManifest(sftp: SFTPWrapper, rootPath: string, request: DirectoryVerifyRequest, exclude?: string[], followSymlinks?: boolean, style?: RemotePathStyle): Promise<DirectoryManifest>;
44
+ export declare function createOpenSshDirectoryManifest(connection: OpenSshConnection, rootPath: string, request: DirectoryVerifyRequest, timeout: number, exclude?: string[], followSymlinks?: boolean): Promise<DirectoryManifest>;
39
45
  export declare function createEmptyDirectoryManifest(): DirectoryManifest;
40
- export declare function buildRemoteDirectoryManifestCommand(rootPath: string, request: DirectoryVerifyRequest, exclude?: string[], followSymlinks?: boolean): string;
41
- export declare function parseRemoteDirectoryManifest(output: string): DirectoryManifest;
42
46
  export declare function compareDirectoryManifests(expected: DirectoryManifest, actual: DirectoryManifest, request: DirectoryVerifyRequest, deletionBaseline?: DirectoryManifest): Record<string, unknown>;
43
47
  export {};