Compare commits

...

4 Commits

Author SHA1 Message Date
github-actions[bot]
c0b8a59a23 chore(main): release 0.5.1 (#776)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-04-20 12:47:40 +08:00
Kevin Codex
aab489055c fix: require trusted approval for sandbox override (#778) 2026-04-20 12:01:44 +08:00
Kevin Codex
7002cb302b fix: enforce Bash path constraints after sandbox allow (#777) 2026-04-20 11:46:24 +08:00
Kevin Codex
739b8d1f40 fix: enforce MCP OAuth callback state before errors (#775) 2026-04-20 09:36:05 +08:00
15 changed files with 364 additions and 105 deletions

View File

@@ -1,3 +1,3 @@
{ {
".": "0.5.0" ".": "0.5.1"
} }

View File

@@ -1,5 +1,14 @@
# Changelog # Changelog
## [0.5.1](https://github.com/Gitlawb/openclaude/compare/v0.5.0...v0.5.1) (2026-04-20)
### Bug Fixes
* enforce Bash path constraints after sandbox allow ([#777](https://github.com/Gitlawb/openclaude/issues/777)) ([7002cb3](https://github.com/Gitlawb/openclaude/commit/7002cb302b78ea2a19da3f26226de24e2903fa1d))
* enforce MCP OAuth callback state before errors ([#775](https://github.com/Gitlawb/openclaude/issues/775)) ([739b8d1](https://github.com/Gitlawb/openclaude/commit/739b8d1f40fde0e401a5cbd2b9a55d88bd5124ad))
* require trusted approval for sandbox override ([#778](https://github.com/Gitlawb/openclaude/issues/778)) ([aab4890](https://github.com/Gitlawb/openclaude/commit/aab489055c53dd64369414116fe93226d2656273))
## [0.5.0](https://github.com/Gitlawb/openclaude/compare/v0.4.0...v0.5.0) (2026-04-20) ## [0.5.0](https://github.com/Gitlawb/openclaude/compare/v0.4.0...v0.5.0) (2026-04-20)

View File

@@ -1,6 +1,6 @@
{ {
"name": "@gitlawb/openclaude", "name": "@gitlawb/openclaude",
"version": "0.5.0", "version": "0.5.1",
"description": "Claude Code opened to any LLM — OpenAI, Gemini, DeepSeek, Ollama, and 200+ models", "description": "Claude Code opened to any LLM — OpenAI, Gemini, DeepSeek, Ollama, and 200+ models",
"type": "module", "type": "module",
"bin": { "bin": {

View File

@@ -114,8 +114,8 @@ export const SandboxSettingsSchema = lazySchema(() =>
.boolean() .boolean()
.optional() .optional()
.describe( .describe(
'Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. ' + 'Allow trusted, user-initiated commands to run outside the sandbox. ' +
'When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. ' + 'When false, sandbox override requests are ignored and all commands must run sandboxed. ' +
'Default: true.', 'Default: true.',
), ),
network: SandboxNetworkConfigSchema(), network: SandboxNetworkConfigSchema(),

View File

@@ -0,0 +1,61 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { validateOAuthCallbackParams } from './auth.js'
test('OAuth callback rejects error parameters before state validation can be bypassed', () => {
const result = validateOAuthCallbackParams(
{
error: 'access_denied',
error_description: 'denied by provider',
},
'expected-state',
)
assert.deepEqual(result, { type: 'state_mismatch' })
})
test('OAuth callback accepts provider errors only when state matches', () => {
const result = validateOAuthCallbackParams(
{
state: 'expected-state',
error: 'access_denied',
error_description: 'denied by provider',
error_uri: 'https://example.test/error',
},
'expected-state',
)
assert.deepEqual(result, {
type: 'error',
error: 'access_denied',
errorDescription: 'denied by provider',
errorUri: 'https://example.test/error',
message:
'OAuth error: access_denied - denied by provider (See: https://example.test/error)',
})
})
test('OAuth callback accepts authorization codes only when state matches', () => {
assert.deepEqual(
validateOAuthCallbackParams(
{
state: 'expected-state',
code: 'auth-code',
},
'expected-state',
),
{ type: 'code', code: 'auth-code' },
)
assert.deepEqual(
validateOAuthCallbackParams(
{
state: 'wrong-state',
code: 'auth-code',
},
'expected-state',
),
{ type: 'state_mismatch' },
)
})

View File

@@ -124,6 +124,74 @@ function redactSensitiveUrlParams(url: string): string {
} }
} }
type OAuthCallbackParamValue = string | string[] | null | undefined
type OAuthCallbackValidationResult =
| { type: 'code'; code: string }
| {
type: 'error'
error: string
errorDescription: string
errorUri: string
message: string
}
| { type: 'missing_result' }
| { type: 'state_mismatch' }
function getFirstOAuthCallbackParam(
value: OAuthCallbackParamValue,
): string | undefined {
if (Array.isArray(value)) {
return value.find(item => item.length > 0)
}
return value && value.length > 0 ? value : undefined
}
export function validateOAuthCallbackParams(
params: {
code?: OAuthCallbackParamValue
state?: OAuthCallbackParamValue
error?: OAuthCallbackParamValue
error_description?: OAuthCallbackParamValue
error_uri?: OAuthCallbackParamValue
},
oauthState: string,
): OAuthCallbackValidationResult {
const code = getFirstOAuthCallbackParam(params.code)
const state = getFirstOAuthCallbackParam(params.state)
const error = getFirstOAuthCallbackParam(params.error)
const errorDescription =
getFirstOAuthCallbackParam(params.error_description) ?? ''
const errorUri = getFirstOAuthCallbackParam(params.error_uri) ?? ''
if (state !== oauthState) {
return { type: 'state_mismatch' }
}
if (error) {
let message = `OAuth error: ${error}`
if (errorDescription) {
message += ` - ${errorDescription}`
}
if (errorUri) {
message += ` (See: ${errorUri})`
}
return {
type: 'error',
error,
errorDescription,
errorUri,
message,
}
}
if (code) {
return { type: 'code', code }
}
return { type: 'missing_result' }
}
/** /**
* Some OAuth servers (notably Slack) return HTTP 200 for all responses, * Some OAuth servers (notably Slack) return HTTP 200 for all responses,
* signaling errors via the JSON body instead. The SDK's executeTokenRequest * signaling errors via the JSON body instead. The SDK's executeTokenRequest
@@ -1058,30 +1126,31 @@ export async function performMCPOAuthFlow(
options.onWaitingForCallback((callbackUrl: string) => { options.onWaitingForCallback((callbackUrl: string) => {
try { try {
const parsed = new URL(callbackUrl) const parsed = new URL(callbackUrl)
const code = parsed.searchParams.get('code') const result = validateOAuthCallbackParams(
const state = parsed.searchParams.get('state') {
const error = parsed.searchParams.get('error') code: parsed.searchParams.get('code'),
state: parsed.searchParams.get('state'),
error: parsed.searchParams.get('error'),
error_description:
parsed.searchParams.get('error_description'),
error_uri: parsed.searchParams.get('error_uri'),
},
oauthState,
)
if (error) { if (result.type === 'state_mismatch') {
const errorDescription = // Ignore so a stray or malicious URL cannot cancel an active flow.
parsed.searchParams.get('error_description') || ''
cleanup()
rejectOnce(
new Error(`OAuth error: ${error} - ${errorDescription}`),
)
return return
} }
if (!code) { if (result.type === 'missing_result') {
// Not a valid callback URL, ignore so the user can try again // Not a valid callback URL, ignore so the user can try again.
return return
} }
if (state !== oauthState) { if (result.type === 'error') {
cleanup() cleanup()
rejectOnce( rejectOnce(new Error(result.message))
new Error('OAuth state mismatch - possible CSRF attack'),
)
return return
} }
@@ -1090,7 +1159,7 @@ export async function performMCPOAuthFlow(
`Received auth code via manual callback URL`, `Received auth code via manual callback URL`,
) )
cleanup() cleanup()
resolveOnce(code) resolveOnce(result.code)
} catch { } catch {
// Invalid URL, ignore so the user can try again // Invalid URL, ignore so the user can try again
} }
@@ -1101,53 +1170,49 @@ export async function performMCPOAuthFlow(
const parsedUrl = parse(req.url || '', true) const parsedUrl = parse(req.url || '', true)
if (parsedUrl.pathname === '/callback') { if (parsedUrl.pathname === '/callback') {
const code = parsedUrl.query.code as string const result = validateOAuthCallbackParams(
const state = parsedUrl.query.state as string parsedUrl.query,
const error = parsedUrl.query.error oauthState,
const errorDescription = parsedUrl.query.error_description as string )
const errorUri = parsedUrl.query.error_uri as string
// Validate OAuth state to prevent CSRF attacks // Validate OAuth state to prevent CSRF attacks
if (!error && state !== oauthState) { if (result.type === 'state_mismatch') {
res.writeHead(400, { 'Content-Type': 'text/html' }) res.writeHead(400, { 'Content-Type': 'text/html' })
res.end( res.end(
`<h1>Authentication Error</h1><p>Invalid state parameter. Please try again.</p><p>You can close this window.</p>`, `<h1>Authentication Error</h1><p>Invalid state parameter. Please try again.</p><p>You can close this window.</p>`,
) )
cleanup()
rejectOnce(new Error('OAuth state mismatch - possible CSRF attack'))
return return
} }
if (error) { if (result.type === 'missing_result') {
res.writeHead(400, { 'Content-Type': 'text/html' })
res.end(
`<h1>Authentication Error</h1><p>Missing OAuth result. Please try again.</p><p>You can close this window.</p>`,
)
return
}
if (result.type === 'error') {
res.writeHead(200, { 'Content-Type': 'text/html' }) res.writeHead(200, { 'Content-Type': 'text/html' })
// Sanitize error messages to prevent XSS // Sanitize error messages to prevent XSS
const sanitizedError = xss(String(error)) const sanitizedError = xss(result.error)
const sanitizedErrorDescription = errorDescription const sanitizedErrorDescription = result.errorDescription
? xss(String(errorDescription)) ? xss(result.errorDescription)
: '' : ''
res.end( res.end(
`<h1>Authentication Error</h1><p>${sanitizedError}: ${sanitizedErrorDescription}</p><p>You can close this window.</p>`, `<h1>Authentication Error</h1><p>${sanitizedError}: ${sanitizedErrorDescription}</p><p>You can close this window.</p>`,
) )
cleanup() cleanup()
let errorMessage = `OAuth error: ${error}` rejectOnce(new Error(result.message))
if (errorDescription) {
errorMessage += ` - ${errorDescription}`
}
if (errorUri) {
errorMessage += ` (See: ${errorUri})`
}
rejectOnce(new Error(errorMessage))
return return
} }
if (code) { res.writeHead(200, { 'Content-Type': 'text/html' })
res.writeHead(200, { 'Content-Type': 'text/html' }) res.end(
res.end( `<h1>Authentication Successful</h1><p>You can close this window. Return to Claude Code.</p>`,
`<h1>Authentication Successful</h1><p>You can close this window. Return to Claude Code.</p>`, )
) cleanup()
cleanup() resolveOnce(result.code)
resolveOnce(code)
}
} }
}) })

View File

@@ -240,21 +240,28 @@ For commands that are harder to parse at a glance (piped commands, obscure flags
- curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements"`), - curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements"`),
run_in_background: semanticBoolean(z.boolean().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`), run_in_background: semanticBoolean(z.boolean().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`),
dangerouslyDisableSandbox: semanticBoolean(z.boolean().optional()).describe('Set this to true to dangerously override sandbox mode and run commands without sandboxing.'), dangerouslyDisableSandbox: semanticBoolean(z.boolean().optional()).describe('Set this to true to dangerously override sandbox mode and run commands without sandboxing.'),
_dangerouslyDisableSandboxApproved: z.boolean().optional().describe('Internal: user-approved sandbox override'),
_simulatedSedEdit: z.object({ _simulatedSedEdit: z.object({
filePath: z.string(), filePath: z.string(),
newContent: z.string() newContent: z.string()
}).optional().describe('Internal: pre-computed sed edit result from preview') }).optional().describe('Internal: pre-computed sed edit result from preview')
})); }));
// Always omit _simulatedSedEdit from the model-facing schema. It is an internal-only // Always omit internal-only fields from the model-facing schema.
// field set by SedEditPermissionRequest after the user approves a sed edit preview. // _simulatedSedEdit is set by SedEditPermissionRequest after the user approves a
// Exposing it in the schema would let the model bypass permission checks and the // sed edit preview; exposing it would let the model bypass permission checks and
// sandbox by pairing an innocuous command with an arbitrary file write. // the sandbox by pairing an innocuous command with an arbitrary file write.
// dangerouslyDisableSandbox is also omitted because sandbox escape must be tied
// to trusted user/internal provenance, not model-controlled tool input.
// Also conditionally remove run_in_background when background tasks are disabled. // Also conditionally remove run_in_background when background tasks are disabled.
const inputSchema = lazySchema(() => isBackgroundTasksDisabled ? fullInputSchema().omit({ const inputSchema = lazySchema(() => isBackgroundTasksDisabled ? fullInputSchema().omit({
run_in_background: true, run_in_background: true,
dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true,
_simulatedSedEdit: true _simulatedSedEdit: true
}) : fullInputSchema().omit({ }) : fullInputSchema().omit({
dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true,
_simulatedSedEdit: true _simulatedSedEdit: true
})); }));
type InputSchema = ReturnType<typeof inputSchema>; type InputSchema = ReturnType<typeof inputSchema>;

View File

@@ -0,0 +1,59 @@
import { afterEach, expect, test } from 'bun:test'
import { getEmptyToolPermissionContext } from '../../Tool.js'
import { SandboxManager } from '../../utils/sandbox/sandbox-adapter.js'
import { bashToolHasPermission } from './bashPermissions.js'
const originalSandboxMethods = {
isSandboxingEnabled: SandboxManager.isSandboxingEnabled,
isAutoAllowBashIfSandboxedEnabled:
SandboxManager.isAutoAllowBashIfSandboxedEnabled,
areUnsandboxedCommandsAllowed: SandboxManager.areUnsandboxedCommandsAllowed,
getExcludedCommands: SandboxManager.getExcludedCommands,
}
afterEach(() => {
SandboxManager.isSandboxingEnabled =
originalSandboxMethods.isSandboxingEnabled
SandboxManager.isAutoAllowBashIfSandboxedEnabled =
originalSandboxMethods.isAutoAllowBashIfSandboxedEnabled
SandboxManager.areUnsandboxedCommandsAllowed =
originalSandboxMethods.areUnsandboxedCommandsAllowed
SandboxManager.getExcludedCommands = originalSandboxMethods.getExcludedCommands
})
function makeToolUseContext() {
const toolPermissionContext = getEmptyToolPermissionContext()
return {
abortController: new AbortController(),
options: {
isNonInteractiveSession: false,
},
getAppState() {
return {
toolPermissionContext,
}
},
} as never
}
test('sandbox auto-allow still enforces Bash path constraints', async () => {
;(globalThis as unknown as { MACRO: { VERSION: string } }).MACRO = {
VERSION: 'test',
}
SandboxManager.isSandboxingEnabled = () => true
SandboxManager.isAutoAllowBashIfSandboxedEnabled = () => true
SandboxManager.areUnsandboxedCommandsAllowed = () => true
SandboxManager.getExcludedCommands = () => []
const result = await bashToolHasPermission(
{ command: 'cat ../../../../../etc/passwd' },
makeToolUseContext(),
)
expect(result.behavior).toBe('ask')
expect(result.message).toContain('was blocked')
expect(result.message).toContain('/etc/passwd')
})

View File

@@ -1814,7 +1814,10 @@ export async function bashToolHasPermission(
input, input,
appState.toolPermissionContext, appState.toolPermissionContext,
) )
if (sandboxAutoAllowResult.behavior !== 'passthrough') { if (
sandboxAutoAllowResult.behavior === 'deny' ||
sandboxAutoAllowResult.behavior === 'ask'
) {
return sandboxAutoAllowResult return sandboxAutoAllowResult
} }
} }

View File

@@ -179,9 +179,6 @@ function getSimpleSandboxSection(): string {
const networkRestrictionConfig = SandboxManager.getNetworkRestrictionConfig() const networkRestrictionConfig = SandboxManager.getNetworkRestrictionConfig()
const allowUnixSockets = SandboxManager.getAllowUnixSockets() const allowUnixSockets = SandboxManager.getAllowUnixSockets()
const ignoreViolations = SandboxManager.getIgnoreViolations() const ignoreViolations = SandboxManager.getIgnoreViolations()
const allowUnsandboxedCommands =
SandboxManager.areUnsandboxedCommandsAllowed()
// Replace the per-UID temp dir literal (e.g. /private/tmp/claude-1001/) with // Replace the per-UID temp dir literal (e.g. /private/tmp/claude-1001/) with
// "$TMPDIR" so the prompt is identical across users — avoids busting the // "$TMPDIR" so the prompt is identical across users — avoids busting the
// cross-user global prompt cache. The sandbox already sets $TMPDIR at runtime. // cross-user global prompt cache. The sandbox already sets $TMPDIR at runtime.
@@ -225,38 +222,9 @@ function getSimpleSandboxSection(): string {
) )
} }
const sandboxOverrideItems: Array<string | string[]> =
allowUnsandboxedCommands
? [
'You should always default to running commands within the sandbox. Do NOT attempt to set `dangerouslyDisableSandbox: true` unless:',
[
'The user *explicitly* asks you to bypass sandbox',
'A specific command just failed and you see evidence of sandbox restrictions causing the failure. Note that commands can fail for many reasons unrelated to the sandbox (missing files, wrong arguments, network issues, etc.).',
],
'Evidence of sandbox-caused failures includes:',
[
'"Operation not permitted" errors for file/network operations',
'Access denied to specific paths outside allowed directories',
'Network connection failures to non-whitelisted hosts',
'Unix socket connection errors',
],
'When you see evidence of sandbox-caused failure:',
[
"Immediately retry with `dangerouslyDisableSandbox: true` (don't ask, just do it)",
'Briefly explain what sandbox restriction likely caused the failure. Be sure to mention that the user can use the `/sandbox` command to manage restrictions.',
'This will prompt the user for permission',
],
'Treat each command you execute with `dangerouslyDisableSandbox: true` individually. Even if you have recently run a command with this setting, you should default to running future commands within the sandbox.',
'Do not suggest adding sensitive paths like ~/.bashrc, ~/.zshrc, ~/.ssh/*, or credential files to the sandbox allowlist.',
]
: [
'All commands MUST run in sandbox mode - the `dangerouslyDisableSandbox` parameter is disabled by policy.',
'Commands cannot run outside the sandbox under any circumstances.',
'If a command fails due to sandbox restrictions, work with the user to adjust sandbox settings instead.',
]
const items: Array<string | string[]> = [ const items: Array<string | string[]> = [
...sandboxOverrideItems, 'Commands MUST run in sandbox mode. If a command fails due to sandbox restrictions, explain the likely restriction and work with the user to adjust sandbox settings or run an explicit user-initiated shell command.',
'Do not suggest adding sensitive paths like ~/.bashrc, ~/.zshrc, ~/.ssh/*, or credential files to the sandbox allowlist.',
'For temporary files, always use the `$TMPDIR` environment variable. TMPDIR is automatically set to the correct sandbox-writable directory in sandbox mode. Do NOT use `/tmp` directly - use `$TMPDIR` instead.', 'For temporary files, always use the `$TMPDIR` environment variable. TMPDIR is automatically set to the correct sandbox-writable directory in sandbox mode. Do NOT use `/tmp` directly - use `$TMPDIR` instead.',
] ]

View File

@@ -0,0 +1,74 @@
import { afterEach, expect, test } from 'bun:test'
import { SandboxManager } from '../../utils/sandbox/sandbox-adapter.js'
import { BashTool } from './BashTool.js'
import { PowerShellTool } from '../PowerShellTool/PowerShellTool.js'
import { shouldUseSandbox } from './shouldUseSandbox.js'
const originalSandboxMethods = {
isSandboxingEnabled: SandboxManager.isSandboxingEnabled,
areUnsandboxedCommandsAllowed: SandboxManager.areUnsandboxedCommandsAllowed,
}
afterEach(() => {
SandboxManager.isSandboxingEnabled =
originalSandboxMethods.isSandboxingEnabled
SandboxManager.areUnsandboxedCommandsAllowed =
originalSandboxMethods.areUnsandboxedCommandsAllowed
})
test('model-facing Bash schema rejects dangerouslyDisableSandbox', () => {
const result = BashTool.inputSchema.safeParse({
command: 'cat /etc/passwd',
dangerouslyDisableSandbox: true,
})
expect(result.success).toBe(false)
})
test('model-facing PowerShell schema rejects dangerouslyDisableSandbox', () => {
const result = PowerShellTool.inputSchema.safeParse({
command: 'Get-Content C:\\Windows\\System32\\drivers\\etc\\hosts',
dangerouslyDisableSandbox: true,
})
expect(result.success).toBe(false)
})
test('model-controlled dangerouslyDisableSandbox does not bypass sandbox', () => {
SandboxManager.isSandboxingEnabled = () => true
SandboxManager.areUnsandboxedCommandsAllowed = () => true
expect(
shouldUseSandbox({
command: 'cat /etc/passwd',
dangerouslyDisableSandbox: true,
}),
).toBe(true)
})
test('trusted internal approval can disable sandbox when policy allows it', () => {
SandboxManager.isSandboxingEnabled = () => true
SandboxManager.areUnsandboxedCommandsAllowed = () => true
expect(
shouldUseSandbox({
command: 'cat /etc/passwd',
dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true,
}),
).toBe(false)
})
test('trusted internal approval cannot disable sandbox when policy forbids it', () => {
SandboxManager.isSandboxingEnabled = () => true
SandboxManager.areUnsandboxedCommandsAllowed = () => false
expect(
shouldUseSandbox({
command: 'cat /etc/passwd',
dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true,
}),
).toBe(true)
})

View File

@@ -13,6 +13,7 @@ import {
type SandboxInput = { type SandboxInput = {
command?: string command?: string
dangerouslyDisableSandbox?: boolean dangerouslyDisableSandbox?: boolean
_dangerouslyDisableSandboxApproved?: boolean
} }
// NOTE: excludedCommands is a user-facing convenience feature, not a security boundary. // NOTE: excludedCommands is a user-facing convenience feature, not a security boundary.
@@ -141,9 +142,13 @@ export function shouldUseSandbox(input: Partial<SandboxInput>): boolean {
return false return false
} }
// Don't sandbox if explicitly overridden AND unsandboxed commands are allowed by policy // Only trusted internal callers may request an unsandboxed command. The
// model-facing Bash schema omits _dangerouslyDisableSandboxApproved, so a
// tool_use payload cannot disable the sandbox by setting
// dangerouslyDisableSandbox directly.
if ( if (
input.dangerouslyDisableSandbox && input.dangerouslyDisableSandbox &&
input._dangerouslyDisableSandboxApproved &&
SandboxManager.areUnsandboxedCommandsAllowed() SandboxManager.areUnsandboxedCommandsAllowed()
) { ) {
return false return false

View File

@@ -230,13 +230,20 @@ const fullInputSchema = lazySchema(() => z.strictObject({
timeout: semanticNumber(z.number().optional()).describe(`Optional timeout in milliseconds (max ${getMaxTimeoutMs()})`), timeout: semanticNumber(z.number().optional()).describe(`Optional timeout in milliseconds (max ${getMaxTimeoutMs()})`),
description: z.string().optional().describe('Clear, concise description of what this command does in active voice.'), description: z.string().optional().describe('Clear, concise description of what this command does in active voice.'),
run_in_background: semanticBoolean(z.boolean().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`), run_in_background: semanticBoolean(z.boolean().optional()).describe(`Set to true to run this command in the background. Use Read to read the output later.`),
dangerouslyDisableSandbox: semanticBoolean(z.boolean().optional()).describe('Set this to true to dangerously override sandbox mode and run commands without sandboxing.') dangerouslyDisableSandbox: semanticBoolean(z.boolean().optional()).describe('Set this to true to dangerously override sandbox mode and run commands without sandboxing.'),
_dangerouslyDisableSandboxApproved: z.boolean().optional().describe('Internal: user-approved sandbox override')
})); }));
// Conditionally remove run_in_background from schema when background tasks are disabled // Omit internal-only sandbox override fields from the model-facing schema.
// Conditionally remove run_in_background from schema when background tasks are disabled.
const inputSchema = lazySchema(() => isBackgroundTasksDisabled ? fullInputSchema().omit({ const inputSchema = lazySchema(() => isBackgroundTasksDisabled ? fullInputSchema().omit({
run_in_background: true run_in_background: true,
}) : fullInputSchema()); dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true
}) : fullInputSchema().omit({
dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true
}));
type InputSchema = ReturnType<typeof inputSchema>; type InputSchema = ReturnType<typeof inputSchema>;
// Use fullInputSchema for the type to always include run_in_background // Use fullInputSchema for the type to always include run_in_background
@@ -697,7 +704,8 @@ async function* runPowerShellCommand({
description, description,
timeout, timeout,
run_in_background, run_in_background,
dangerouslyDisableSandbox dangerouslyDisableSandbox,
_dangerouslyDisableSandboxApproved
} = input; } = input;
const timeoutMs = Math.min(timeout || getDefaultTimeoutMs(), getMaxTimeoutMs()); const timeoutMs = Math.min(timeout || getDefaultTimeoutMs(), getMaxTimeoutMs());
let fullOutput = ''; let fullOutput = '';
@@ -749,7 +757,8 @@ async function* runPowerShellCommand({
// The explicit platform check is redundant-but-obvious. // The explicit platform check is redundant-but-obvious.
shouldUseSandbox: getPlatform() === 'windows' ? false : shouldUseSandbox({ shouldUseSandbox: getPlatform() === 'windows' ? false : shouldUseSandbox({
command, command,
dangerouslyDisableSandbox dangerouslyDisableSandbox,
_dangerouslyDisableSandboxApproved
}), }),
shouldAutoBackground shouldAutoBackground
}); });

View File

@@ -662,10 +662,6 @@ export function normalizeToolInput<T extends Tool>(
...(timeout !== undefined && { timeout }), ...(timeout !== undefined && { timeout }),
...(description !== undefined && { description }), ...(description !== undefined && { description }),
...(run_in_background !== undefined && { run_in_background }), ...(run_in_background !== undefined && { run_in_background }),
...('dangerouslyDisableSandbox' in parsed &&
parsed.dangerouslyDisableSandbox !== undefined && {
dangerouslyDisableSandbox: parsed.dangerouslyDisableSandbox,
}),
} as z.infer<T['inputSchema']> } as z.infer<T['inputSchema']>
} }
case FileEditTool.name: { case FileEditTool.name: {

View File

@@ -65,10 +65,11 @@ export async function processBashCommand(inputString: string, precedingInputBloc
}); });
}; };
// User-initiated `!` commands run outside sandbox. Both shell tools honor // User-initiated `!` commands run outside sandbox when policy allows it.
// dangerouslyDisableSandbox (checked against areUnsandboxedCommandsAllowed() // Bash requires an internal approval marker so model-controlled tool input
// in shouldUseSandbox.ts). PS sandbox is Linux/macOS/WSL2 only — on Windows // cannot disable sandboxing by setting dangerouslyDisableSandbox directly.
// native, shouldUseSandbox() returns false regardless (unsupported platform). // PS sandbox is Linux/macOS/WSL2 only — on Windows native, shouldUseSandbox()
// returns false regardless (unsupported platform).
// Lazy-require PowerShellTool so its ~300KB chunk only loads when the // Lazy-require PowerShellTool so its ~300KB chunk only loads when the
// user has actually selected the powershell default shell. // user has actually selected the powershell default shell.
type PSMod = typeof import('src/tools/PowerShellTool/PowerShellTool.js'); type PSMod = typeof import('src/tools/PowerShellTool/PowerShellTool.js');
@@ -81,10 +82,12 @@ export async function processBashCommand(inputString: string, precedingInputBloc
const shellTool = PowerShellTool ?? BashTool; const shellTool = PowerShellTool ?? BashTool;
const response = PowerShellTool ? await PowerShellTool.call({ const response = PowerShellTool ? await PowerShellTool.call({
command: inputString, command: inputString,
dangerouslyDisableSandbox: true dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true
}, bashModeContext, undefined, undefined, onProgress) : await BashTool.call({ }, bashModeContext, undefined, undefined, onProgress) : await BashTool.call({
command: inputString, command: inputString,
dangerouslyDisableSandbox: true dangerouslyDisableSandbox: true,
_dangerouslyDisableSandboxApproved: true
}, bashModeContext, undefined, undefined, onProgress); }, bashModeContext, undefined, undefined, onProgress);
const data = response.data; const data = response.data;
if (!data) { if (!data) {