From e2df39ab75f9d9d87d7a81012a32cb862913a754 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Thu, 16 Jul 2026 17:31:15 -0700 Subject: [PATCH] Surface per-host gh auth state for GitHub Enterprise diagnoseGhAuth accepts the host a surface needs credentials for, scopes the account/scope diagnosis to that host, and reports whether gh has any login there; GhAuthErrorHelp renders host-qualified login/refresh commands so an unauthenticated GHES host stops masquerading as a github.com scope problem. Also fixes the mobile paste-intent expectation for host-carrying parsed links. Co-authored-by: Orca --- src/main/github/auth-diagnose.test.ts | 55 ++++++++++++++++++- src/main/github/auth-diagnose.ts | 17 +++++- src/main/ipc/github.ts | 4 +- src/preload/api-types.ts | 2 +- src/preload/index.ts | 3 +- .../github-project/GhAuthErrorHelp.tsx | 45 +++++++++++++-- src/shared/github-auth-types.ts | 7 +++ 7 files changed, 120 insertions(+), 13 deletions(-) diff --git a/src/main/github/auth-diagnose.test.ts b/src/main/github/auth-diagnose.test.ts index 35e3775b4..1218824f8 100644 --- a/src/main/github/auth-diagnose.test.ts +++ b/src/main/github/auth-diagnose.test.ts @@ -1,5 +1,11 @@ -import { describe, expect, it } from 'vitest' -import { parseAuthStatus } from './auth-diagnose' +import { describe, expect, it, vi } from 'vitest' + +const { ghExecFileAsyncMock } = vi.hoisted(() => ({ ghExecFileAsyncMock: vi.fn() })) + +vi.mock('../git/runner', () => ({ + ghExecFileAsync: ghExecFileAsyncMock +})) +import { diagnoseGhAuth, parseAuthStatus } from './auth-diagnose' describe('parseAuthStatus', () => { it('parses an env-shadowed login alongside a keyring login (real gh output)', () => { @@ -95,3 +101,48 @@ ghe.acme.io expect(accounts[0].host).toBe('github.acme.io') }) }) + +describe('diagnoseGhAuth host scoping', () => { + const TWO_HOST_STATUS = `github.com + ✓ Logged in to github.com account alice (keyring) + - Active account: true + - Token scopes: 'project', 'read:org', 'repo' +ghe.acme.io + ✓ Logged in to ghe.acme.io account bob (keyring) + - Active account: true + - Token scopes: 'repo' +` + + it('reports an unauthenticated required host and keeps scope advice host-scoped', async () => { + ghExecFileAsyncMock.mockResolvedValue({ stdout: TWO_HOST_STATUS, stderr: '' }) + + const diag = await diagnoseGhAuth('github.other-corp.com') + + expect(diag.requiredHost).toBe('github.other-corp.com') + expect(diag.requiredHostAuthenticated).toBe(false) + expect(diag.activeAccount).toBeNull() + }) + + it("scopes the diagnosis to the required host's account", async () => { + ghExecFileAsyncMock.mockResolvedValue({ stdout: TWO_HOST_STATUS, stderr: '' }) + + const diag = await diagnoseGhAuth('GHE.Acme.IO') + + expect(diag.requiredHost).toBe('ghe.acme.io') + expect(diag.requiredHostAuthenticated).toBe(true) + expect(diag.activeAccount?.user).toBe('bob') + // Why: bob's GHES token lacks project/read:org even though alice's + // github.com token has them — advice must reflect the required host. + expect(diag.missingScopes).toEqual(['project', 'read:org']) + }) + + it('keeps legacy host-less behavior byte-identical', async () => { + ghExecFileAsyncMock.mockResolvedValue({ stdout: TWO_HOST_STATUS, stderr: '' }) + + const diag = await diagnoseGhAuth() + + expect(diag.requiredHost).toBeNull() + expect(diag.requiredHostAuthenticated).toBeNull() + expect(diag.activeAccount?.user).toBe('alice') + }) +}) diff --git a/src/main/github/auth-diagnose.ts b/src/main/github/auth-diagnose.ts index aeaf4b9e2..3c0678559 100644 --- a/src/main/github/auth-diagnose.ts +++ b/src/main/github/auth-diagnose.ts @@ -90,7 +90,7 @@ export function parseAuthStatus(text: string): GhAuthAccount[] { return accounts } -export async function diagnoseGhAuth(): Promise { +export async function diagnoseGhAuth(requiredHost?: string): Promise { let raw = '' let ghAvailable = true try { @@ -118,7 +118,16 @@ export async function diagnoseGhAuth(): Promise { } } const accounts = parseAuthStatus(raw) - const active = accounts.find((a) => a.active) ?? accounts[0] ?? null + // Why: when the caller names a host (a GHES origin), scope the diagnosis to + // that host's account — the github.com account's scopes are irrelevant to it. + const normalizedRequiredHost = requiredHost?.trim().toLowerCase() || null + const hostAccounts = normalizedRequiredHost + ? accounts.filter((a) => a.host.toLowerCase() === normalizedRequiredHost) + : accounts + const active = + hostAccounts.find((a) => a.active) ?? + hostAccounts[0] ?? + (normalizedRequiredHost ? null : (accounts.find((a) => a.active) ?? accounts[0] ?? null)) const envTokenInProcess: 'GITHUB_TOKEN' | 'GH_TOKEN' | null = process.env.GH_TOKEN ? 'GH_TOKEN' : process.env.GITHUB_TOKEN @@ -141,6 +150,8 @@ export async function diagnoseGhAuth(): Promise { envTokenInProcess, missingScopes, requiredScopes: [...REQUIRED_SCOPES], - hasKeyringFallback: Boolean(keyringFallback && keyringFallback !== active) + hasKeyringFallback: Boolean(keyringFallback && keyringFallback !== active), + requiredHost: normalizedRequiredHost, + requiredHostAuthenticated: normalizedRequiredHost ? hostAccounts.length > 0 : null } } diff --git a/src/main/ipc/github.ts b/src/main/ipc/github.ts index 1aa3fbb43..be0b9af0e 100644 --- a/src/main/ipc/github.ts +++ b/src/main/ipc/github.ts @@ -1161,7 +1161,9 @@ export function registerGitHubHandlers(store: Store, stats: StatsCollector): voi getRateLimit(args?.force ? { force: true } : undefined) ) - ipcMain.handle('gh:diagnoseAuth', () => diagnoseGhAuth()) + ipcMain.handle('gh:diagnoseAuth', (_event, args?: { host?: string }) => + diagnoseGhAuth(args?.host) + ) // ── GitHub ProjectV2 view handlers ───────────────────────────────── // Why: registered unconditionally so enabling the experimental flag at diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index a75f48aee..a0b8aa1c6 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1758,7 +1758,7 @@ export type PreloadApi = { * shell and silently shadows the keyring credential — in that case * `gh auth refresh` is a no-op and the UI must say so. */ - diagnoseAuth: () => Promise + diagnoseAuth: (args?: { host?: string }) => Promise // ── ProjectV2 (GitHub Projects) ───────────────────────────────── listAccessibleProjects: ( args?: ListAccessibleProjectsArgs diff --git a/src/preload/index.ts b/src/preload/index.ts index 1adab8ca7..cf4a5d857 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1540,7 +1540,8 @@ const api = { rateLimit: (args?: { force?: boolean }): Promise => ipcRenderer.invoke('gh:rateLimit', args), - diagnoseAuth: (): Promise => ipcRenderer.invoke('gh:diagnoseAuth'), + diagnoseAuth: (args?: { host?: string }): Promise => + ipcRenderer.invoke('gh:diagnoseAuth', args), // ── ProjectV2 (GitHub Projects) ─────────────────────────────────── listAccessibleProjects: ( diff --git a/src/renderer/src/components/github-project/GhAuthErrorHelp.tsx b/src/renderer/src/components/github-project/GhAuthErrorHelp.tsx index 9131094bd..84e0d1687 100644 --- a/src/renderer/src/components/github-project/GhAuthErrorHelp.tsx +++ b/src/renderer/src/components/github-project/GhAuthErrorHelp.tsx @@ -21,6 +21,20 @@ type AuthErrorKind = 'auth_required' | 'scope_missing' const REFRESH_CMD = 'gh auth refresh -s project -s read:org -s repo' const LOGIN_CMD = 'gh auth login' +// Why: GHES credentials are per-host — a bare `gh auth login` signs into +// github.com and leaves the Enterprise host exactly as broken as before. +function loginCommandForHost(host: string | null | undefined): string { + return host && host.toLowerCase() !== 'github.com' + ? `gh auth login --hostname ${host}` + : LOGIN_CMD +} + +function refreshCommandForHost(host: string | null | undefined): string { + return host && host.toLowerCase() !== 'github.com' + ? `gh auth refresh --hostname ${host} -s project -s read:org -s repo` + : REFRESH_CMD +} + // AGENTS.md requires platform-specific shell guidance. The env-shadow // remediation needs different commands per host shell — bash/zsh on // macOS/Linux vs PowerShell on Windows. @@ -130,6 +144,24 @@ function buildRemediation( } } + // Why: an Enterprise host with no gh account at all outranks every other + // diagnosis — env-token or scope advice for github.com would be misleading. + if (diag.requiredHost && diag.requiredHostAuthenticated === false) { + return { + summary: `\`gh\` is not signed in to ${diag.requiredHost}.`, + detail: `GitHub Enterprise hosts need their own \`gh\` login, separate from github.com. Run the login command in a terminal, complete the browser flow on ${diag.requiredHost}, then reload.`, + commands: [ + { + label: translate( + 'auto.components.github.project.GhAuthErrorHelp.9c2da6353b', + 'Copy login command' + ), + command: loginCommandForHost(diag.requiredHost) + } + ] + } + } + if (!diag.ghAvailable) { return { summary: 'GitHub CLI (`gh`) is not installed or not on PATH.', @@ -191,7 +223,7 @@ function buildRemediation( 'auto.components.github.project.GhAuthErrorHelp.9c2da6353b', 'Copy login command' ), - command: LOGIN_CMD + command: loginCommandForHost(diag.requiredHost) } ] } @@ -213,7 +245,7 @@ function buildRemediation( 'auto.components.github.project.GhAuthErrorHelp.3fefeebde4', 'Copy refresh command' ), - command: REFRESH_CMD + command: refreshCommandForHost(diag.requiredHost) } ] } @@ -242,16 +274,19 @@ function buildRemediation( export function GhAuthErrorHelp({ error, - variant = 'block' + variant = 'block', + host }: { error: GitHubProjectViewError & { type: AuthErrorKind } variant?: 'block' | 'banner' + /** GHES host the failing surface talks to; scopes the diagnosis per host. */ + host?: string }): React.JSX.Element { const [diag, setDiag] = useState(null) useEffect(() => { let cancelled = false window.api.gh - .diagnoseAuth() + .diagnoseAuth(host ? { host } : undefined) .then((d) => { if (!cancelled) { setDiag(d) @@ -262,7 +297,7 @@ export function GhAuthErrorHelp({ return () => { cancelled = true } - }, []) + }, [host]) const remedy = buildRemediation(error.message, error.type, diag) const docsUrl = remedy.docsUrl diff --git a/src/shared/github-auth-types.ts b/src/shared/github-auth-types.ts index 9c39879db..b0ce3fa90 100644 --- a/src/shared/github-auth-types.ts +++ b/src/shared/github-auth-types.ts @@ -36,4 +36,11 @@ export type GhAuthDiagnostic = { * that the user could fall back to by unsetting the env var. */ hasKeyringFallback: boolean + /** + * The GitHub host the caller needs credentials for (e.g. a GHES origin). + * Null when the probe ran without host context. + */ + requiredHost: string | null + /** Whether gh has any account for `requiredHost`; null without host context. */ + requiredHostAuthenticated: boolean | null }