File size: 8,653 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
341
342
343
344
345
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { parse as shellParse } from 'shell-quote';
import {
  extractStringFromParseEntry,
  initializeShellParsers,
  splitCommands,
  stripShellWrapper,
} from '../../utils/shell-utils.js';
import { isSubpath, resolveToRealPath } from '../../utils/paths.js';

/**
 * Determines if a command is strictly approved for execution on Windows.
 * A command is approved if it's composed entirely of tools explicitly listed in `approvedTools`
 * OR if it's composed of known safe, read-only Windows commands.
 *
 * @param command - The full command string to execute.
 * @param args - The arguments for the command.
 * @param approvedTools - A list of explicitly approved tool names (e.g., ['npm', 'git']).
 * @param cwd - Optional working directory
 * @param workspaceRoot - Optional workspace root directory
 * @returns true if the command is strictly approved, false otherwise.
 */
export async function isStrictlyApproved(
  command: string,
  args: string[],
  approvedTools?: string[],
  cwd?: string,
  workspaceRoot?: string,
): Promise<boolean> {
  const tools = approvedTools ?? [];

  await initializeShellParsers();

  const fullCmd = [command, ...args].join(' ');
  const stripped = stripShellWrapper(fullCmd);

  const pipelineCommands = splitCommands(stripped);

  // Fallback for simple commands or parsing failures
  if (pipelineCommands.length === 0) {
    return (
      tools.includes(command) ||
      isKnownSafeCommand([command, ...args], cwd, workspaceRoot)
    );
  }

  // Check every segment of the pipeline
  return pipelineCommands.every((cmdString) => {
    const trimmed = cmdString.trim();
    if (!trimmed) return true;

    const parsedArgs = shellParse(trimmed).map(extractStringFromParseEntry);
    if (parsedArgs.length === 0) return true;

    let root = parsedArgs[0].toLowerCase();
    if (root.endsWith('.exe')) {
      root = root.slice(0, -4);
    }
    // The segment is approved if the root tool is in the allowlist OR if the whole segment is safe.
    return (
      tools.some((t) => t.toLowerCase() === root) ||
      isKnownSafeCommand(parsedArgs, cwd, workspaceRoot)
    );
  });
}

function isPathEscapingWorkspace(
  arg: string,
  workspaceRoot: string,
  cwd: string,
): boolean {
  if (!arg || typeof arg !== 'string') return false;

  if (arg.includes('$') || arg.includes('`') || arg.includes('%')) {
    return true;
  }

  let target: string;
  if (arg === '~' || arg.startsWith('~/') || arg.startsWith('~\\')) {
    const homeDir = os.homedir();
    target = path.win32.resolve(homeDir, arg.slice(2));
    if (!isSubpath(workspaceRoot, target)) {
      return true;
    }
  } else if (arg.startsWith('~')) {
    return true;
  } else if (path.win32.isAbsolute(arg) || path.isAbsolute(arg)) {
    target = path.win32.resolve(arg);
    if (!isSubpath(workspaceRoot, target)) {
      return true;
    }
  } else {
    target = path.win32.resolve(cwd, arg);
    if (!isSubpath(workspaceRoot, target)) {
      return true;
    }
  }

  let curr = target;
  while (
    curr &&
    isSubpath(workspaceRoot, curr) &&
    curr !== path.win32.dirname(curr)
  ) {
    try {
      const stat = fs.lstatSync(curr, { throwIfNoEntry: false });
      if (stat?.isSymbolicLink()) {
        const real = fs.realpathSync(curr);
        if (!isSubpath(workspaceRoot, real)) {
          return true;
        }
      }
    } catch {
      // ignore
    }
    curr = path.win32.dirname(curr);
  }

  return false;
}

/**
 * Checks if a Windows command is known to be safe (read-only).
 */
export function isKnownSafeCommand(
  args: string[],
  cwd?: string,
  workspaceRoot?: string,
): boolean {
  if (!args || args.length === 0) return false;
  let cmd = args[0].toLowerCase();
  if (cmd.endsWith('.exe')) {
    cmd = cmd.slice(0, -4);
  }

  let effectiveWorkspace = workspaceRoot
    ? path.win32.isAbsolute(workspaceRoot)
      ? path.win32.resolve(workspaceRoot)
      : path.resolve(workspaceRoot)
    : cwd
      ? path.win32.isAbsolute(cwd)
        ? path.win32.resolve(cwd)
        : path.resolve(cwd)
      : process.cwd();
  try {
    effectiveWorkspace = resolveToRealPath(effectiveWorkspace);
  } catch {
    // Keep resolved path on failure
  }

  let effectiveCwd = cwd
    ? path.win32.isAbsolute(cwd)
      ? path.win32.resolve(cwd)
      : path.resolve(cwd)
    : effectiveWorkspace;
  try {
    effectiveCwd = resolveToRealPath(effectiveCwd);
  } catch {
    // Keep resolved path on failure
  }

  if (
    effectiveCwd !== effectiveWorkspace &&
    !isSubpath(effectiveWorkspace, effectiveCwd)
  ) {
    return false;
  }

  // Native Windows/PowerShell safe commands
  const safeCommands = new Set([
    '__read',
    '__write',
    'dir',
    'type',
    'echo',
    'cd',
    'pwd',
    'whoami',
    'hostname',
    'ver',
    'vol',
    'systeminfo',
    'attrib',
    'findstr',
    'where',
    'sort',
    'more',
    'get-childitem',
    'get-content',
    'get-location',
    'get-help',
    'get-process',
    'get-service',
    'get-eventlog',
    'select-string',
  ]);

  if (safeCommands.has(cmd)) {
    if (cmd === 'cd') {
      let hasPath = false;
      for (let i = 1; i < args.length; i++) {
        const arg = args[i];
        const isSwitch =
          arg.startsWith('-') ||
          (arg.startsWith('/') && /^\/[a-zA-Z0-9?]{1,4}(?::.*)?$/.test(arg));
        if (isSwitch) {
          continue;
        }
        hasPath = true;
        if (isPathEscapingWorkspace(arg, effectiveWorkspace, effectiveCwd)) {
          return false;
        }
      }
      if (!hasPath) {
        if (isPathEscapingWorkspace('~', effectiveWorkspace, effectiveCwd)) {
          return false;
        }
      }
      return true;
    }

    const fileReadingCommands = new Set([
      'dir',
      'type',
      'attrib',
      'more',
      'findstr',
      'get-childitem',
      'get-content',
      'select-string',
      '__read',
      'sort',
    ]);

    if (fileReadingCommands.has(cmd)) {
      let passedDoubleDash = false;
      for (let i = 1; i < args.length; i++) {
        const arg = args[i];
        if (!passedDoubleDash) {
          if (arg === '--') {
            passedDoubleDash = true;
            continue;
          }
          const isSwitch =
            arg.startsWith('-') ||
            (arg.startsWith('/') && /^\/[a-zA-Z0-9?]{1,4}(?::.*)?$/.test(arg));
          if (isSwitch) {
            const sepIdx =
              arg.indexOf('=') !== -1 ? arg.indexOf('=') : arg.indexOf(':');
            if (sepIdx !== -1) {
              const val = arg.slice(sepIdx + 1);
              if (
                isPathEscapingWorkspace(val, effectiveWorkspace, effectiveCwd)
              ) {
                return false;
              }
              continue;
            }

            if (arg.startsWith('-')) {
              try {
                const stat = fs.lstatSync(
                  path.win32.resolve(effectiveCwd, arg),
                  {
                    throwIfNoEntry: false,
                  },
                );
                if (!stat) {
                  continue;
                }
              } catch {
                continue;
              }
            } else {
              continue;
            }
          }
        }
        if (isPathEscapingWorkspace(arg, effectiveWorkspace, effectiveCwd)) {
          return false;
        }
      }
      return true;
    }

    return true;
  }

  // We allow git on Windows if it's read-only, using the same logic as POSIX
  if (cmd === 'git') {
    // For simplicity in this branch, we'll allow standard git read operations
    // In a full implementation, we'd port the sub-command validation too.
    const sub = args[1]?.toLowerCase();
    return ['status', 'log', 'diff', 'show', 'branch'].includes(sub);
  }

  return false;
}

/**
 * Checks if a Windows command is explicitly dangerous.
 */
export function isDangerousCommand(
  args: string[],
  _cwd?: string,
  _workspaceRoot?: string,
): boolean {
  if (!args || args.length === 0) return false;
  let cmd = args[0].toLowerCase();
  if (cmd.endsWith('.exe')) {
    cmd = cmd.slice(0, -4);
  }

  const dangerous = new Set([
    'del',
    'erase',
    'rd',
    'rmdir',
    'net',
    'reg',
    'sc',
    'format',
    'mklink',
    'takeown',
    'icacls',
    'powershell', // prevent shell escapes
    'pwsh',
    'cmd',
    'remove-item',
    'stop-process',
    'stop-service',
    'set-item',
    'new-item',
  ]);

  return dangerous.has(cmd);
}