From e0db79c789e2e98f2f51ae264de132a1a4c414f0 Mon Sep 17 00:00:00 2001 From: Savas Neto Date: Tue, 3 Nov 2026 16:25:13 -0300 Subject: [PATCH] fix(security): require workspace trust in Verboo mode Verboo mode skipped the TrustDialog and still marked every folder as trusted, so project hooks, apiKeyHelper, MCP headersHelper, statusLine, project env and plugin marketplaces declared in a freshly cloned repo ran without a prompt. Port upstream's provider-free gate (setupScreenGates, OpenClaude #1864) and show the trust prompt once per folder for every provider. Declining exits before anything runs; headless -p is unchanged. The dialog no longer links to the Claude Code security guide. The PTY e2e harness gains trusted/projectFiles/settingSources options and covers both the decline and accept paths with a SessionStart hook. Co-Authored-By: Claude Opus 5.5 --- scripts/e2e/cli.e2e.mjs | 37 ++++++++++++ scripts/e2e/terminal.mjs | 15 +++-- src/__tests__/verbooWorkspaceTrust.test.ts | 44 ++++++++++++++ src/components/TrustDialog/TrustDialog.tsx | 6 +- src/interactiveHelpers.tsx | 17 +++++- src/utils/setupScreenGates.test.ts | 69 ++++++++++++++++++++++ src/utils/setupScreenGates.ts | 29 +++++++++ 7 files changed, 208 insertions(+), 9 deletions(-) create mode 100644 src/__tests__/verbooWorkspaceTrust.test.ts create mode 100644 src/utils/setupScreenGates.test.ts create mode 100644 src/utils/setupScreenGates.ts diff --git a/scripts/e2e/cli.e2e.mjs b/scripts/e2e/cli.e2e.mjs index 018d2c72b6..2c5256de65 100644 --- a/scripts/e2e/cli.e2e.mjs +++ b/scripts/e2e/cli.e2e.mjs @@ -190,3 +190,40 @@ test('an agent hitting max_turns reports its limit and confirmed usage', { timeo for (const record of records) assert.equal(record.tokenUsage.confirmed, 144) } finally { await cli.stop() } }) + +// Workspace trust: a freshly cloned repository must not run project hooks +// before the user accepts the trust prompt (regression: Verboo mode used to +// mark every folder as trusted without asking). +const hookProject = { + '.verboo/settings.json': JSON.stringify({ hooks: { SessionStart: [{ hooks: [{ type: 'command', command: 'echo ran > hook-ran.txt' }] }] } }), +} +const hookRan = async cli => readdir(cli.project).then(files => files.includes('hook-ran.txt')) + +test('untrusted project: declining the trust prompt exits before project hooks run', { timeout: 60_000 }, async () => { + const cli = await startCli({ columns: 120, rows: 40, trusted: false, settingSources: 'user,project', projectFiles: hookProject }) + try { + await cli.waitFor(() => cli.screen().includes('Yes, I trust this folder')) + assert.equal(await hookRan(cli), false) + cli.write('\x1b[B') + await cli.waitFor(() => /❯ 2\. No, exit/.test(cli.screen())) + cli.write('\r') + const { exitCode } = await cli.exit + assert.equal(exitCode, 1) + assert.equal(await hookRan(cli), false) + assert.deepEqual(cli.router.requests, []) + } finally { await cli.stop() } +}) + +test('untrusted project: accepting the trust prompt runs hooks and remembers the folder', { timeout: 60_000 }, async () => { + const cli = await startCli({ columns: 120, rows: 40, trusted: false, settingSources: 'user,project', projectFiles: hookProject }) + try { + await cli.waitFor(() => cli.screen().includes('Yes, I trust this folder')) + assert.equal(await hookRan(cli), false) + cli.write('\r') + await cli.waitFor(() => cli.screen().includes('❯') && !cli.screen().includes('Yes, I trust this folder')) + await cli.waitFor(() => hookRan(cli)) + const config = JSON.parse(await readFile(join(cli.config, '.config.json'), 'utf8')) + const key = cli.project.replaceAll('\\', '/') + assert.equal(config.projects?.[key]?.hasTrustDialogAccepted, true) + } finally { await cli.stop() } +}) diff --git a/scripts/e2e/terminal.mjs b/scripts/e2e/terminal.mjs index e34cc646a8..ab766ecb04 100644 --- a/scripts/e2e/terminal.mjs +++ b/scripts/e2e/terminal.mjs @@ -12,7 +12,7 @@ import { deflateRawSync } from 'node:zlib' import { createFakeRouter } from './fake-router.mjs' import { CODEX_FIXTURE_README, createCodexFixtureCredentialRecord, createCodexRouter } from './codex-router.mjs' -export async function startCli({ columns = 80, rows = 24, fullscreen = false, usePty = true, slashCommands = false, model = 'fixture-model', args = [], routerOptions, codexOptions } = {}) { +export async function startCli({ columns = 80, rows = 24, fullscreen = false, usePty = true, slashCommands = false, model = 'fixture-model', args = [], routerOptions, codexOptions, trusted = true, projectFiles = {}, settingSources = 'user' } = {}) { const consumer = (await readFile(resolve('.artifacts/package/consumer-path.txt'), 'utf8')).trim() const root = resolve('.artifacts/pty') await mkdir(root, { recursive: true }) @@ -27,8 +27,15 @@ export async function startCli({ columns = 80, rows = 24, fullscreen = false, us const git = spawnSync('git', ['init', '-q', project], { encoding: 'utf8' }) if (git.status !== 0) throw new Error(git.stderr || 'Could not isolate fixture project') await writeFile(join(project, 'README.md'), `${CODEX_FIXTURE_README}\n`) + for (const [relativePath, contents] of Object.entries(projectFiles)) { + await mkdir(dirname(join(project, relativePath)), { recursive: true }) + await writeFile(join(project, relativePath), contents) + } const projectConfigKey = project.replaceAll('\\', '/') - await writeFile(join(config, '.config.json'), JSON.stringify({ theme: 'dark', hasCompletedOnboarding: true, bypassPermissionsModeAccepted: true, projects: { [projectConfigKey]: { hasTrustDialogAccepted: true } } })) + // Untrusted fixtures leave the project out of the config so the workspace + // trust prompt appears exactly as it does for a freshly cloned repository. + const projects = trusted ? { [projectConfigKey]: { hasTrustDialogAccepted: true } } : {} + await writeFile(join(config, '.config.json'), JSON.stringify({ theme: 'dark', hasCompletedOnboarding: true, bypassPermissionsModeAccepted: true, projects })) const router = await createFakeRouter(routerOptions) const codexRouter = codexOptions ? await createCodexRouter({ projectRoot: project, ...codexOptions }) : undefined let codexFixtureBin @@ -72,7 +79,7 @@ export async function startCli({ columns = 80, rows = 24, fullscreen = false, us terminal.unicode.activeVersion = '11' let child let stderr = '' - const cliArgs = ['--import', pathToFileURL(resolve('scripts/e2e/transport-preload.mjs')).href, join(consumer, 'node_modules/@verboo/code/bin/verboo'), '--model', model, '--dangerously-skip-permissions', '--setting-sources', 'user', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', ...(slashCommands ? [] : ['--disable-slash-commands']), '--debug-file', join(dir, 'debug.log'), ...args] + const cliArgs = ['--import', pathToFileURL(resolve('scripts/e2e/transport-preload.mjs')).href, join(consumer, 'node_modules/@verboo/code/bin/verboo'), '--model', model, '--dangerously-skip-permissions', '--setting-sources', settingSources, '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}', ...(slashCommands ? [] : ['--disable-slash-commands']), '--debug-file', join(dir, 'debug.log'), ...args] try { if (usePty) { child = pty.spawn(process.execPath, cliArgs, { cwd: project, env, cols: columns, rows, name: 'xterm-256color' }) @@ -110,7 +117,7 @@ export async function startCli({ columns = 80, rows = 24, fullscreen = false, us }) const exit = new Promise(resolve => child.onExit(value => { exited = value; resolve(value) })) return { - dir, router, codexRouter, frames, chunks, screen, get raw() { return raw }, get exited() { return exited }, exit, + dir, project, config, router, codexRouter, frames, chunks, screen, get raw() { return raw }, get exited() { return exited }, exit, write(data) { child.write(data) }, resize(cols, rows) { terminal.resize(cols, rows); child.resize(cols, rows) }, async waitFor(predicate, timeout = 20_000) { diff --git a/src/__tests__/verbooWorkspaceTrust.test.ts b/src/__tests__/verbooWorkspaceTrust.test.ts new file mode 100644 index 0000000000..dd02d849bc --- /dev/null +++ b/src/__tests__/verbooWorkspaceTrust.test.ts @@ -0,0 +1,44 @@ +/** + * Workspace trust in Verboo mode. + * + * showSetupScreens cannot be imported under bun test (its import chain trips + * the compile-time feature() macro checker), so the wiring is asserted + * structurally here and behaviorally in setupScreenGates.test.ts and the PTY + * e2e suite (scripts/e2e/cli.e2e.mjs). + */ + +import { describe, expect, test } from 'bun:test' +import { resolve } from 'path' + +const SRC = resolve(import.meta.dir, '..') +const file = (relative: string) => Bun.file(resolve(SRC, relative)) + +describe('workspace trust prompt in Verboo mode', () => { + test('the trust dialog is gated by getRequiredSetupScreens, not by the provider', async () => { + const content = await file('interactiveHelpers.tsx').text() + expect(content).toContain('if (setupScreens.trustDialog)') + expect(content).not.toMatch(/usesAnthropicSetup\s*&&\s*!checkHasTrustDialogAccepted\(\)/) + }) + + test('auth runs first, then the dialog, and only then trust is marked and env applied', async () => { + const content = await file('interactiveHelpers.tsx').text() + const auth = content.indexOf('await ensureVerbooAuthenticated()') + const dialog = content.indexOf("await import('./components/TrustDialog/TrustDialog.js')") + const markTrusted = content.indexOf('setSessionTrustAccepted(true)') + const applyEnv = content.indexOf('applyConfigEnvironmentVariables()') + expect(auth).toBeGreaterThan(-1) + expect(dialog).toBeGreaterThan(auth) + expect(markTrusted).toBeGreaterThan(dialog) + expect(applyEnv).toBeGreaterThan(markTrusted) + }) + + test('declining the dialog exits instead of returning to setup', async () => { + const content = await file('components/TrustDialog/TrustDialog.tsx').text() + expect(content).toMatch(/value === "exit"\)\s*{\s*gracefulShutdownSync\(1\)/) + }) + + test('the dialog no longer links to the Claude Code security guide', async () => { + const content = await file('components/TrustDialog/TrustDialog.tsx').text() + expect(content).not.toContain('code.claude.com') + }) +}) diff --git a/src/components/TrustDialog/TrustDialog.tsx b/src/components/TrustDialog/TrustDialog.tsx index 6196cdf8f1..991c4c472a 100644 --- a/src/components/TrustDialog/TrustDialog.tsx +++ b/src/components/TrustDialog/TrustDialog.tsx @@ -5,7 +5,7 @@ import { logEvent } from 'src/services/analytics/index.js'; import { setSessionTrustAccepted } from '../../bootstrap/state.js'; import type { Command } from '../../commands.js'; import { useExitOnCtrlCDWithKeybindings } from '../../hooks/useExitOnCtrlCDWithKeybindings.js'; -import { Box, Link, Text } from '../../ink.js'; +import { Box, Text } from '../../ink.js'; import { useKeybinding } from '../../keybindings/useKeybinding.js'; import { getMcpConfigsByScope } from '../../services/mcp/config.js'; import { BASH_TOOL_NAME } from '../../tools/BashTool/toolName.js'; @@ -217,7 +217,9 @@ export function TrustDialog(t0) { } let t19; if ($[23] === Symbol.for("react.memo_cache_sentinel")) { - t19 = Security guide; + // VERBOO-BRAND: o guia de segurança upstream é do Claude Code; sem página + // equivalente da Verboo, o link sai. + t19 = null; $[23] = t19; } else { t19 = $[23]; diff --git a/src/interactiveHelpers.tsx b/src/interactiveHelpers.tsx index ab6d38578a..362dd51234 100644 --- a/src/interactiveHelpers.tsx +++ b/src/interactiveHelpers.tsx @@ -20,6 +20,7 @@ import { onChangeAppState } from './state/onChangeAppState.js'; import { normalizeApiKeyForConfig } from './utils/authPortable.js'; import { getExternalClaudeMdIncludes, getMemoryFiles, shouldShowClaudeMdExternalIncludesWarning } from './utils/claudemd.js'; import { checkHasTrustDialogAccepted, getCustomApiKeyStatus, getGlobalConfig, saveGlobalConfig } from './utils/config.js'; +import { getRequiredSetupScreens } from './utils/setupScreenGates.js'; import { updateDeepLinkTerminalPreference } from './utils/deepLink/terminalPreference.js'; import { isEnvTruthy, isRunningOnHomespace } from './utils/envUtils.js'; import { type FpsMetrics, FpsTracker } from './utils/fpsTracker.js'; @@ -142,15 +143,25 @@ export async function showSetupScreens(root: Root, permissionMode: PermissionMod // Note: non-interactive sessions (CI/CD with -p) never reach showSetupScreens at all. // Skip permission checks in claubbit if (!isEnvTruthy(process.env.CLAUBBIT)) { - // Skip trust dialog UI for third-party providers (no Anthropic auth), but still - // run trust state initialization below so the REPL mounts correctly. - if (usesAnthropicSetup && !checkHasTrustDialogAccepted()) { + // VERBOO-BRAND: a confiança de pasta vale para qualquer provedor (upstream + // #1864). Antes o modo Verboo pulava o TrustDialog e marcava a confiança + // como aceita, então hooks/helpers/env de um repo clonado rodavam sem + // pergunta. O gate agora é o mesmo do upstream e não depende do provedor. + const setupScreens = getRequiredSetupScreens({ + theme: config.theme, + hasCompletedOnboarding: config.hasCompletedOnboarding, + trustDialogAccepted: checkHasTrustDialogAccepted(), + isClaubbit: isEnvTruthy(process.env.CLAUBBIT) + }); + if (setupScreens.trustDialog) { const { TrustDialog } = await import('./components/TrustDialog/TrustDialog.js'); await showSetupDialog(root, done => ); } + // Only reached after the dialog was accepted (or trust was already saved): + // "No", Esc and Ctrl+C in TrustDialog call gracefulShutdownSync. // Signal that trust has been verified for this session. // GrowthBook checks this to decide whether to include auth headers. // Critical for third-party providers: without this, downstream config lookups diff --git a/src/utils/setupScreenGates.test.ts b/src/utils/setupScreenGates.test.ts new file mode 100644 index 0000000000..407f23f0ed --- /dev/null +++ b/src/utils/setupScreenGates.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from 'bun:test' + +import { getRequiredSetupScreens } from './setupScreenGates.js' + +// Behavioral coverage for the first-run screen gating (#1864). The seam is +// deliberately provider-free — there is no input to vary by provider, which +// IS the fix: a third-party (or any) provider gets the same onboarding and +// workspace-trust decisions as the Anthropic account flow. +// showSetupScreens itself cannot be imported under bun test (its import +// chain trips the compile-time feature() macro checker), so the wiring is +// asserted structurally in src/__tests__/bugfixes.test.ts. + +describe('getRequiredSetupScreens', () => { + const completed = { + theme: 'dark', + hasCompletedOnboarding: true, + trustDialogAccepted: true, + isClaubbit: false, + } + + test('fresh install shows both screens', () => { + expect( + getRequiredSetupScreens({ + theme: undefined, + hasCompletedOnboarding: undefined, + trustDialogAccepted: false, + isClaubbit: false, + }), + ).toEqual({ onboarding: true, trustDialog: true }) + }) + + test('fully set-up install shows neither', () => { + expect(getRequiredSetupScreens(completed)).toEqual({ + onboarding: false, + trustDialog: false, + }) + }) + + test('onboarding re-shows when the theme is missing even if completed once', () => { + expect( + getRequiredSetupScreens({ ...completed, theme: undefined }).onboarding, + ).toBe(true) + }) + + test('onboarding re-shows when never completed even with a theme set', () => { + expect( + getRequiredSetupScreens({ ...completed, hasCompletedOnboarding: false }) + .onboarding, + ).toBe(true) + }) + + test('trust dialog shows whenever unaccepted, independent of onboarding state', () => { + expect( + getRequiredSetupScreens({ ...completed, trustDialogAccepted: false }) + .trustDialog, + ).toBe(true) + }) + + test('claubbit skips the trust dialog but never onboarding', () => { + const result = getRequiredSetupScreens({ + theme: undefined, + hasCompletedOnboarding: false, + trustDialogAccepted: false, + isClaubbit: true, + }) + expect(result.trustDialog).toBe(false) + expect(result.onboarding).toBe(true) + }) +}) diff --git a/src/utils/setupScreenGates.ts b/src/utils/setupScreenGates.ts new file mode 100644 index 0000000000..559ce74f9c --- /dev/null +++ b/src/utils/setupScreenGates.ts @@ -0,0 +1,29 @@ +/** + * Pure gating decisions for the first-run setup screens, extracted from + * showSetupScreens (interactiveHelpers.tsx) as an importable seam: + * interactiveHelpers cannot be imported in tests — its import chain trips + * Bun's compile-time feature() macro checker before mocks can intercept — + * so behavioral coverage lives against this module instead (the same pattern + * as the dev-channels registration seam). + * + * Deliberately provider-free: NO input carries which API provider is active. + * That absence is the fix (#1864) — onboarding (theme + safety notes) is + * universal, with Onboarding.tsx itself dropping the OAuth/preflight steps + * when Anthropic auth is off, and workspace trust is exactly as load-bearing + * over a local model as over Anthropic. Re-introducing a provider parameter + * here should be treated as a regression signal in review. + */ +export function getRequiredSetupScreens(options: { + theme: string | undefined + hasCompletedOnboarding: boolean | undefined + trustDialogAccepted: boolean + isClaubbit: boolean +}): { onboarding: boolean; trustDialog: boolean } { + return { + // Always show onboarding at least once (theme unset or never completed). + onboarding: !options.theme || !options.hasCompletedOnboarding, + // The trust dialog is the workspace trust boundary; only the claubbit + // harness (which owns its own trust story) skips it. + trustDialog: !options.isClaubbit && !options.trustDialogAccepted, + } +}