Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(github): isolate terminal token overrides from account flows
Dash0cc6ae6287fc
diff --git a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.tsindex fd525a72b8..575de86099 100644--- a/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts+++ b/apps/desktop/src/main/__tests__/gitContextGhCliTokenSource.test.ts@@ -115,12 +115,7 @@ describe('createGhCliTokenSource', () => {it('可用性探测只执行静默账号 API,不读取或污染 token cache', async () => {const execFileFn = vi.fn(- (- _file: string,- args: string[],- opts: { timeout: number },- cb: ExecCb,- ) => {+ (_file: string, args: string[], opts: { timeout: number }, cb: ExecCb) => {if (args[0] === 'api') {expect(opts.timeout).toBeLessThanOrEqual(1_000);cb(null, '', '');@@ -137,7 +132,7 @@ describe('createGhCliTokenSource', () => {expect(execFileFn).toHaveBeenCalledWith(expectedGhExecutable,['api', '--hostname', 'github.com', 'user', '--silent'],- { timeout: expect.any(Number) },+ { timeout: expect.any(Number), env: expect.any(Object) },expect.any(Function),);expect(await src.readToken()).toBe('gho_after_probe');@@ -145,7 +140,9 @@ describe('createGhCliTokenSource', () => {});it('可用性探测失败只返回 false,不把 stderr/输出写进日志', async () => {- const execFileFn = execMock((_file, cb) => cb(new Error('not logged in'), 'secret-like-output', ''));+ const execFileFn = execMock((_file, cb) =>+ cb(new Error('not logged in'), 'secret-like-output', ''),+ );const src = createGhCliTokenSource({ execFileFn, existsFn: () => false });expect(await src.probeAvailability()).toBe(false);expect(execFileFn).toHaveBeenCalledTimes(1);diff --git a/apps/desktop/src/main/__tests__/githubSetupActiveAccount.test.ts b/apps/desktop/src/main/__tests__/githubSetupActiveAccount.test.tsindex be488bfc91..2017fb5eaa 100644--- a/apps/desktop/src/main/__tests__/githubSetupActiveAccount.test.ts+++ b/apps/desktop/src/main/__tests__/githubSetupActiveAccount.test.ts@@ -1,4 +1,5 @@-import { expect, it, vi } from 'vitest';+import { EventEmitter } from 'node:events';+import { afterEach, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({ execFile: vi.fn(), spawn: vi.fn() }));vi.mock('node:child_process', () => mocks);@@ -7,6 +8,59 @@ vi.mock('../managed-tools/installer', () => ({ installTool: vi.fn() }));import { createGithubSetup } from '../git-context/githubSetup';import { createGhCliTokenSource } from '../git-context/ghCliTokenSource';+afterEach(() => {+ vi.unstubAllEnvs();+ vi.clearAllMocks();+});++it.each(['GH_TOKEN', 'GITHUB_TOKEN', 'gh_token'])(+ 'ignores %s throughout saved-account login and reads',+ async (key) => {+ vi.stubEnv(key, 'invalid-test-override');+ vi.stubEnv('HTTPS_PROXY', 'http://example.test:8080');+ let loggedIn = false;+ const checkEnv = (env: NodeJS.ProcessEnv) => {+ expect(+ Object.keys(env).some((name) => ['GH_TOKEN', 'GITHUB_TOKEN'].includes(name.toUpperCase())),+ ).toBe(false);+ expect(env.HTTPS_PROXY).toBe('http://example.test:8080');+ };+ mocks.execFile.mockImplementation((_binary, args, options, callback) => {+ checkEnv(options.env);+ callback(+ args[0] === 'api' && !loggedIn ? new Error('not logged in') : null,+ args[0] === 'auth' ? 'saved-test-token' : '',+ '',+ );+ });+ mocks.spawn.mockImplementation((_binary, _args, options) => {+ checkEnv(options.env);+ const child = Object.assign(new EventEmitter(), {+ stderr: new EventEmitter(),+ stdout: { resume: vi.fn() },+ kill: vi.fn(),+ });+ queueMicrotask(() => {+ child.stderr.emit('data', Buffer.from('one-time code: ABCD-EFGH'));+ loggedIn = true;+ child.emit('close', 0);+ });+ return child;+ });+ const setup = createGithubSetup('unused', vi.fn());+ setup.start();+ await vi.waitFor(() => expect(setup.snapshot().phase).toBe('connected'));+ expect(mocks.spawn).toHaveBeenCalledOnce();+ const source = createGhCliTokenSource({+ execFileFn: mocks.execFile,+ resolveBinary: async () => 'gh',+ });+ expect(await source.probeAvailability()).toBe(true);+ expect(await source.readToken()).toBe('saved-test-token');+ expect(process.env[key]).toBe('invalid-test-override');+ },+);+it('connects with a valid active account even when a secondary account has expired', async () => {mocks.execFile.mockImplementation((_binary, args, _options, callback) => {const failure = args.includes('--active')diff --git a/apps/desktop/src/main/git-context/ghCliTokenSource.ts b/apps/desktop/src/main/git-context/ghCliTokenSource.tsindex 9d9b9982fe..c41e734103 100644--- a/apps/desktop/src/main/git-context/ghCliTokenSource.ts+++ b/apps/desktop/src/main/git-context/ghCliTokenSource.ts@@ -26,6 +26,15 @@ const log = createLogger('git-context/gh-cli');// --silent discards the account response; callers only consume the exit code.export const GH_AUTH_CHECK_ARGS = ['api', '--hostname', 'github.com', 'user', '--silent'];+/** Host account flows use gh's saved login, never a terminal token override. */+export function ghAccountEnv(): NodeJS.ProcessEnv {+ return Object.fromEntries(+ Object.entries(process.env).filter(+ ([key]) => !['GH_TOKEN', 'GITHUB_TOKEN'].includes(key.toUpperCase()),+ ),+ );+}+const DEFAULT_CACHE_TTL_MS = 5 * 60_000;const DEFAULT_NEGATIVE_CACHE_TTL_MS = 30_000;const GH_TIMEOUT_MS = 3_000;@@ -36,7 +45,7 @@ export interface GhCliTokenSourceDeps {execFileFn?: (file: string,args: string[],- opts: { timeout: number },+ opts: { timeout: number; env: NodeJS.ProcessEnv },cb: (err: Error | null, stdout: string, stderr: string) => void,) => void;existsFn?: (p: string) => boolean;@@ -106,7 +115,7 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliToexecFileFn(bin,['auth', 'token', '--hostname', 'github.com'],- { timeout: GH_TIMEOUT_MS },+ { timeout: GH_TIMEOUT_MS, env: ghAccountEnv() },(err, stdout) => {if (err) {// 失败只 debug 级记录;原因分类留给 UI 决定引导动作。@@ -153,7 +162,7 @@ export function createGhCliTokenSource(deps: GhCliTokenSourceDeps = {}): GhCliToexecFileFn(bin,GH_AUTH_CHECK_ARGS,- { timeout: GH_PROBE_TIMEOUT_MS },+ { timeout: GH_PROBE_TIMEOUT_MS, env: ghAccountEnv() },(err) => resolve(err === null),);} catch {diff --git a/apps/desktop/src/main/git-context/githubSetup.ts b/apps/desktop/src/main/git-context/githubSetup.tsindex 45d30ea70c..3df5d742a8 100644--- a/apps/desktop/src/main/git-context/githubSetup.ts+++ b/apps/desktop/src/main/git-context/githubSetup.ts@@ -3,7 +3,7 @@ import type { GithubSetupState } from '../../shared/githubSetup.js';import { installTool } from '../managed-tools/installer.js';import { ghArtifact, GH_VERSION } from './ghArtifact.js';import { resolveGhBinary } from './ghBinary.js';-import { GH_AUTH_CHECK_ARGS } from './ghCliTokenSource.js';+import { GH_AUTH_CHECK_ARGS, ghAccountEnv } from './ghCliTokenSource.js';interface SetupDeps {resolveBinary(): Promise<string>;@@ -84,9 +84,14 @@ export class GithubSetup {function check(binary: string, args: string[], expected?: string): Promise<boolean> {return new Promise((resolve) => {- execFile(binary, args, { timeout: 15_000, windowsHide: true }, (err, stdout) => {- resolve(!err && (!expected || stdout.startsWith(`gh version ${expected} `)));- });+ execFile(+ binary,+ args,+ { timeout: 15_000, windowsHide: true, env: ghAccountEnv() },+ (err, stdout) => {+ resolve(!err && (!expected || stdout.startsWith(`gh version ${expected} `)));+ },+ );});}@@ -124,7 +129,7 @@ export function loginWithGh({stdio: ['ignore', 'pipe', 'pipe'],windowsHide: true,- env: { ...process.env, NO_COLOR: '1', GH_PROMPT_DISABLED: '1' },+ env: { ...ghAccountEnv(), NO_COLOR: '1', GH_PROMPT_DISABLED: '1' },},);let output = '';diff --git a/docs/dev-rules/verified-downloads.md b/docs/dev-rules/verified-downloads.mdindex 4c1c8d33b7..17040954ae 100644--- a/docs/dev-rules/verified-downloads.md+++ b/docs/dev-rules/verified-downloads.md@@ -63,6 +63,9 @@ Renderer 只接收阶段、进度、设备码和固定 GitHub 授权地址,不登录前后及插件探测共用 `gh api --hostname github.com user --silent` 检查当前活动账号,兼容不支持 `auth status --active` 的旧版 gh,也避免失效备用账号干扰;只消费退出码,不读取账号响应或 token。成功后清除 token 和 PR 缓存,通过 `git-context:github-connected` 立即刷新顶栏及侧栏。缓存代数隔离登录前的在途响应。+宿主管理的检查、登录和取 token 共用 `ghAccountEnv()`,仅在子进程环境中移除+`GH_TOKEN` / `GITHUB_TOKEN`(含 Windows 大小写变体),统一使用 gh 保存的本机账号;+保留代理与配置目录,不修改全局环境或 Agent 终端的 token。回归见 `githubSetupActiveAccount.test.ts`。安装/登录 IPC 仅限受信本机主窗口,不开放给共享任务或 device-link;SSH/手机远程查看继续使用被控端现有 PR 查询和刷新通道,不会误操作控制端的 GitHub 账号。