diff --git a/src/__helpers__/gitify-bridge.ts b/src/__helpers__/gitify-bridge.ts index 4a49820a7..b3df4b80d 100644 --- a/src/__helpers__/gitify-bridge.ts +++ b/src/__helpers__/gitify-bridge.ts @@ -21,6 +21,9 @@ export function createGitifyBridgeApi(platform: TestPlatform = 'macos'): Window[ decryptValue: vi.fn().mockResolvedValue({ token: 'decrypted' }), encryptValue: vi.fn().mockResolvedValue('encrypted'), githubCliToken: vi.fn().mockResolvedValue({ token: 'gh-cli-token' }), + githubCliAccounts: vi.fn().mockResolvedValue({ + accounts: [{ identity: { kind: 'account', login: 'octocat' }, active: true }], + }), setWindowVibrancy: vi.fn().mockResolvedValue(undefined), setNativeTheme: vi.fn().mockResolvedValue(undefined), platform: { diff --git a/src/main/handlers/github-cli.test.ts b/src/main/handlers/github-cli.test.ts index d1c0b2484..0d7197084 100644 --- a/src/main/handlers/github-cli.test.ts +++ b/src/main/handlers/github-cli.test.ts @@ -1,6 +1,6 @@ import { delimiter } from 'node:path'; -import { readGitHubCliToken } from './github-cli'; +import { readGitHubCliToken, listGitHubCliAccounts } from './github-cli'; const execFileMock = vi.fn(); @@ -38,7 +38,9 @@ describe('main/handlers/github-cli.ts', () => { it('returns the token the CLI holds for the host', async () => { execFileMock.mockResolvedValue({ stdout: 'gho_token\n', stderr: '' }); - await expect(readGitHubCliToken('github.com')).resolves.toEqual({ token: 'gho_token' }); + await expect(readGitHubCliToken({ hostname: 'github.com' })).resolves.toEqual({ + token: 'gho_token', + }); expect(execFileMock).toHaveBeenCalledWith( 'gh', ['auth', 'token', '--hostname', 'github.com'], @@ -46,10 +48,59 @@ describe('main/handlers/github-cli.ts', () => { ); }); + it.each(['alice', 'mona-cat_octo'])('addresses %s with --user', async (login) => { + execFileMock.mockResolvedValue({ stdout: 'gho_alice\n', stderr: '' }); + + await expect( + readGitHubCliToken({ + hostname: 'github.com', + identity: { kind: 'account', login }, + }), + ).resolves.toEqual({ token: 'gho_alice' }); + expect(execFileMock.mock.calls[0][1]).toEqual([ + 'auth', + 'token', + '--hostname', + 'github.com', + '--user', + login, + ]); + }); + + it('resolves the environment identity without --user', async () => { + process.env.GH_TOKEN = 'gho_from_shell'; + execFileMock.mockResolvedValue({ stdout: 'gho_from_shell\n', stderr: '' }); + + await expect( + readGitHubCliToken({ hostname: 'github.com', identity: { kind: 'environment' } }), + ).resolves.toEqual({ token: 'gho_from_shell' }); + expect(execFileMock.mock.calls[0][1]).toEqual(['auth', 'token', '--hostname', 'github.com']); + }); + + it('fails closed when the environment credential has gone away', async () => { + delete process.env.GH_TOKEN; + delete process.env.GITHUB_TOKEN; + + await expect( + readGitHubCliToken({ hostname: 'github.com', identity: { kind: 'environment' } }), + ).resolves.toEqual({ error: 'GH_NOT_AUTHENTICATED' }); + expect(execFileMock).not.toHaveBeenCalled(); + }); + + it('refuses a login it cannot vouch for without spawning the CLI', async () => { + await expect( + readGitHubCliToken({ + hostname: 'github.com', + identity: { kind: 'account', login: 'alice; rm -rf /' }, + }), + ).resolves.toEqual({ error: 'GH_FAILED' }); + expect(execFileMock).not.toHaveBeenCalled(); + }); + it('never leaves an empty PATH element, which would search the working directory', async () => { delete process.env.PATH; - await readGitHubCliToken('github.com'); + await readGitHubCliToken({ hostname: 'github.com' }); expect(spawnedEnv().PATH?.split(delimiter)).not.toContain(''); }); @@ -57,7 +108,7 @@ describe('main/handlers/github-cli.ts', () => { it("passes an ambient token through, since it can be the CLI's only credential", async () => { process.env.GH_TOKEN = 'gho_from_shell'; - await readGitHubCliToken('github.com'); + await readGitHubCliToken({ hostname: 'github.com' }); expect(spawnedEnv().GH_TOKEN).toBe('gho_from_shell'); }); @@ -65,7 +116,9 @@ describe('main/handlers/github-cli.ts', () => { it('reports a missing CLI', async () => { execFileMock.mockRejectedValue(Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' })); - await expect(readGitHubCliToken('github.com')).resolves.toEqual({ error: 'GH_NOT_FOUND' }); + await expect(readGitHubCliToken({ hostname: 'github.com' })).resolves.toEqual({ + error: 'GH_NOT_FOUND', + }); }); it('reports a CLI with no token for the host', async () => { @@ -76,7 +129,7 @@ describe('main/handlers/github-cli.ts', () => { }), ); - await expect(readGitHubCliToken('github.example.com')).resolves.toEqual({ + await expect(readGitHubCliToken({ hostname: 'github.example.com' })).resolves.toEqual({ error: 'GH_NOT_AUTHENTICATED', }); }); @@ -84,7 +137,7 @@ describe('main/handlers/github-cli.ts', () => { it('treats empty CLI output as no token', async () => { execFileMock.mockResolvedValue({ stdout: '\n', stderr: '' }); - await expect(readGitHubCliToken('github.com')).resolves.toEqual({ + await expect(readGitHubCliToken({ hostname: 'github.com' })).resolves.toEqual({ error: 'GH_NOT_AUTHENTICATED', }); }); @@ -92,7 +145,9 @@ describe('main/handlers/github-cli.ts', () => { it('reports a timed-out CLI separately, since a keychain prompt blocks it', async () => { execFileMock.mockRejectedValue(Object.assign(new Error('killed'), { killed: true })); - await expect(readGitHubCliToken('github.com')).resolves.toEqual({ error: 'GH_TIMED_OUT' }); + await expect(readGitHubCliToken({ hostname: 'github.com' })).resolves.toEqual({ + error: 'GH_TIMED_OUT', + }); }); it("carries the CLI's own reason for an unclassified failure", async () => { @@ -100,16 +155,95 @@ describe('main/handlers/github-cli.ts', () => { Object.assign(new Error('exit 1'), { code: 1, stderr: 'keyring is locked\nmore detail' }), ); - await expect(readGitHubCliToken('github.com')).resolves.toEqual({ + await expect(readGitHubCliToken({ hostname: 'github.com' })).resolves.toEqual({ error: 'GH_FAILED', detail: 'keyring is locked', }); }); it('never spawns the CLI for a hostname it cannot vouch for', async () => { - await expect(readGitHubCliToken('github.com; rm -rf /')).resolves.toEqual({ + await expect(readGitHubCliToken({ hostname: 'github.com; rm -rf /' })).resolves.toEqual({ error: 'GH_FAILED', }); expect(execFileMock).not.toHaveBeenCalled(); }); + + describe('listing identities', () => { + it('lists personal and enterprise managed accounts and marks the active one', async () => { + execFileMock.mockResolvedValue({ + stdout: JSON.stringify({ + hosts: { + 'github.com': [ + { state: 'success', active: true, login: 'mona-cat_octo', tokenSource: 'keyring' }, + { state: 'success', active: false, login: 'alice', tokenSource: 'keyring' }, + { state: 'error', active: false, login: 'carol', tokenSource: 'keyring' }, + ], + }, + }), + stderr: '', + }); + + await expect(listGitHubCliAccounts('github.com')).resolves.toEqual({ + accounts: [ + { identity: { kind: 'account', login: 'mona-cat_octo' }, active: true }, + { identity: { kind: 'account', login: 'alice' }, active: false }, + ], + }); + expect(execFileMock).toHaveBeenCalledWith( + 'gh', + ['auth', 'status', '--hostname', 'github.com', '--json', 'hosts'], + expect.anything(), + ); + }); + + it('reports the environment credential as its own identity', async () => { + execFileMock.mockResolvedValue({ + stdout: JSON.stringify({ + hosts: { + 'github.com': [{ state: 'success', active: true, login: '', tokenSource: 'GH_TOKEN' }], + }, + }), + stderr: '', + }); + + await expect(listGitHubCliAccounts('github.com')).resolves.toEqual({ + accounts: [{ identity: { kind: 'environment' }, active: true }], + }); + }); + + it('returns an empty list for a host with no identities', async () => { + execFileMock.mockResolvedValue({ stdout: '{"hosts":{}}', stderr: '' }); + + await expect(listGitHubCliAccounts('github.example.com')).resolves.toEqual({ + accounts: [], + }); + }); + + it('reports an unsupported CLI rather than an empty list', async () => { + execFileMock.mockRejectedValue( + Object.assign(new Error('exit 1'), { code: 1, stderr: 'unknown flag: --json' }), + ); + + await expect(listGitHubCliAccounts('github.com')).resolves.toEqual({ + error: 'GH_ACCOUNTS_UNSUPPORTED', + }); + }); + + it('reports a missing CLI while listing', async () => { + execFileMock.mockRejectedValue( + Object.assign(new Error('spawn gh ENOENT'), { code: 'ENOENT' }), + ); + + await expect(listGitHubCliAccounts('github.com')).resolves.toEqual({ + error: 'GH_NOT_FOUND', + }); + }); + + it('never spawns the CLI for a hostname it cannot vouch for while listing', async () => { + await expect(listGitHubCliAccounts('github.com; rm -rf /')).resolves.toEqual({ + error: 'GH_FAILED', + }); + expect(execFileMock).not.toHaveBeenCalled(); + }); + }); }); diff --git a/src/main/handlers/github-cli.ts b/src/main/handlers/github-cli.ts index aa3e205cc..fce47d187 100644 --- a/src/main/handlers/github-cli.ts +++ b/src/main/handlers/github-cli.ts @@ -3,8 +3,17 @@ import { homedir } from 'node:os'; import { delimiter } from 'node:path'; import { promisify } from 'node:util'; -import type { GitHubCliTokenError, IGitHubCliTokenResult } from '../../shared/events'; +import type { + GitHubCliAccountsError, + GitHubCliIdentity, + GitHubCliTokenError, + IGitHubCliAccount, + IGitHubCliAccountsResult, + IGitHubCliTokenRequest, + IGitHubCliTokenResult, +} from '../../shared/events'; import { EVENTS } from '../../shared/events'; +import { isValidGitHubCliLogin } from '../../shared/githubCli'; import { logError, toError } from '../../shared/logger'; import { isWindows } from '../../shared/platform'; @@ -29,24 +38,182 @@ const EXTRA_PATH_ENTRIES = isWindows() const HOSTNAME_PATTERN = /^[a-z0-9][a-z0-9.-]*$/i; /** - * Ask the locally installed GitHub CLI for the token it holds for `hostname`. + * Credential sources `gh` reports for a token it reads from the environment + * rather than from its credential store. + */ +const ENVIRONMENT_TOKEN_SOURCES = new Set([ + 'GH_TOKEN', + 'GITHUB_TOKEN', + 'GH_ENTERPRISE_TOKEN', + 'GITHUB_ENTERPRISE_TOKEN', +]); + +/** The subset of `gh auth status --json hosts` this handler relies on. */ +interface IRawCliAccount { + login?: string; + active?: boolean; + state?: string; + tokenSource?: string; +} + +interface IRawCliHosts { + hosts?: Record; +} + +function buildEnv(): NodeJS.ProcessEnv { + return { ...process.env, PATH: buildPath() }; +} + +/** + * List the identities the locally installed GitHub CLI holds for `hostname`. * - * Whatever the CLI resolves is what Gitify uses, including a token it takes - * from `GH_TOKEN`/`GH_ENTERPRISE_TOKEN`: for some users that environment token - * is the only credential `gh` has. + * A stored account is identified by its login; a credential supplied through + * the CLI's environment is reported as the separate `environment` identity. + * Identities the CLI reports as unusable are omitted, and an empty list is a + * normal answer rather than a failure. * - * @param hostname - Host to read the token for (e.g. `github.com`). + * @param hostname - Host to list identities for (e.g. `github.com`). + * @returns The usable identities, or a classified failure with an optional detail line. + */ +export async function listGitHubCliAccounts(hostname: string): Promise { + if (!isValidHostname(hostname)) { + return { error: 'GH_FAILED' }; + } + + try { + const { stdout } = await execFileAsync( + 'gh', + ['auth', 'status', '--hostname', hostname, '--json', 'hosts'], + { env: buildEnv(), timeout: 10_000 }, + ); + + return { accounts: parseCliAccounts(stdout) }; + } catch (err) { + const { error, detail } = classifyAccountsFailure(err); + + if (error === 'GH_FAILED') { + logError( + 'main:github-cli-accounts', + `Failed to list gh accounts for ${hostname}`, + toError(err), + ); + } + + return { error, detail }; + } +} + +function isValidHostname(hostname: string): boolean { + return typeof hostname === 'string' && HOSTNAME_PATTERN.test(hostname); +} + +function parseCliAccounts(stdout: string): IGitHubCliAccount[] { + const parsed = JSON.parse(stdout) as IRawCliHosts; + const entries = Object.values(parsed.hosts ?? {}).flat(); + const accounts: IGitHubCliAccount[] = []; + let environmentReported = false; + + for (const entry of entries) { + if (entry.state !== 'success') { + continue; + } + + if (isEnvironmentIdentity(entry)) { + if (!environmentReported) { + accounts.push({ identity: { kind: 'environment' }, active: entry.active === true }); + environmentReported = true; + } + continue; + } + + if (!isValidGitHubCliLogin(entry.login)) { + continue; + } + + accounts.push({ + identity: { kind: 'account', login: entry.login }, + active: entry.active === true, + }); + } + + return accounts; +} + +function isEnvironmentIdentity(entry: IRawCliAccount): boolean { + return ( + !entry.login && + typeof entry.tokenSource === 'string' && + ENVIRONMENT_TOKEN_SOURCES.has(entry.tokenSource) + ); +} + +function classifyAccountsFailure(err: unknown): { + error: GitHubCliAccountsError; + detail?: string; +} { + const { code, killed, stderr } = err as { + code?: string | number; + killed?: boolean; + stderr?: string; + }; + const text = stderr ?? ''; + + if (code === 'ENOENT') { + return { error: 'GH_NOT_FOUND' }; + } + + if (killed) { + return { error: 'GH_TIMED_OUT' }; + } + + if (/unknown flag|unknown shorthand flag|flag provided but not defined/i.test(text)) { + return { error: 'GH_ACCOUNTS_UNSUPPORTED' }; + } + + if (/no oauth token found|not logged in/i.test(text)) { + return { error: 'GH_NOT_AUTHENTICATED' }; + } + + return { error: 'GH_FAILED', detail: text.trim().split('\n')[0] || undefined }; +} + +/** + * Ask the locally installed GitHub CLI for the credential it holds for + * `hostname`. A named account is resolved with `--user`, which reads that + * account's token without changing which account the CLI treats as active; an + * environment identity is resolved without it, and fails closed when the + * environment token has gone away rather than falling back to an active account. + * + * @param request - Host to read a token for, and the identity to address. * @returns The CLI token, or a classified failure with an optional detail line. */ -export async function readGitHubCliToken(hostname: string): Promise { - if (typeof hostname !== 'string' || !HOSTNAME_PATTERN.test(hostname)) { +export async function readGitHubCliToken( + request: IGitHubCliTokenRequest, +): Promise { + if (typeof request !== 'object' || request === null) { + return { error: 'GH_FAILED' }; + } + + const { hostname, identity } = request; + + if (!isValidHostname(hostname) || !isValidIdentity(identity)) { return { error: 'GH_FAILED' }; } - const env: NodeJS.ProcessEnv = { ...process.env, PATH: buildPath() }; + const env = buildEnv(); + + if (identity?.kind === 'environment' && !hasEnvironmentToken(env)) { + return { error: 'GH_NOT_AUTHENTICATED' }; + } + + const args = ['auth', 'token', '--hostname', hostname]; + + if (identity?.kind === 'account') { + args.push('--user', identity.login); + } try { - const { stdout } = await execFileAsync('gh', ['auth', 'token', '--hostname', hostname], { + const { stdout } = await execFileAsync('gh', args, { env, timeout: 10_000, }); @@ -65,6 +232,26 @@ export async function readGitHubCliToken(hostname: string): Promise Boolean(env[source])); +} + /** * An empty PATH element means "the current directory" to `execvp`, so an unset * PATH must not leave one behind. @@ -103,5 +290,6 @@ function classifyFailure(err: unknown): { * possible from the main process, so the renderer asks for the token per host. */ export function registerGitHubCliHandlers(): void { - handleMainEvent(EVENTS.GITHUB_CLI_TOKEN, (_, hostname) => readGitHubCliToken(hostname)); + handleMainEvent(EVENTS.GITHUB_CLI_TOKEN, (_, request) => readGitHubCliToken(request)); + handleMainEvent(EVENTS.GITHUB_CLI_ACCOUNTS, (_, hostname) => listGitHubCliAccounts(hostname)); } diff --git a/src/preload/index.test.ts b/src/preload/index.test.ts index a1a794378..d022eebe2 100644 --- a/src/preload/index.test.ts +++ b/src/preload/index.test.ts @@ -51,6 +51,11 @@ interface TestApi { showUpdateNotifications: boolean; }) => void; setUseX11Backend: (value: boolean) => void; + githubCliToken: (request: { + hostname: string; + identity?: { kind: 'environment' } | { kind: 'account'; login: string }; + }) => Promise; + githubCliAccounts: (hostname: string) => Promise; app: { version: () => Promise; show?: () => void; hide?: () => void }; nativeNotifications: { show: (payload: { id: string; title: string; body: string; actionLabel?: string }) => void; @@ -113,6 +118,29 @@ describe('preload/index', () => { }); }); + it('githubCliToken forwards the identity-aware request', () => { + const api = getExposedApi(); + const request = { + hostname: 'github.com', + identity: { kind: 'account' as const, login: 'alice' }, + }; + + void api.githubCliToken(request); + + expect(invokeMainEventMock).toHaveBeenCalledWith(EVENTS.GITHUB_CLI_TOKEN, request); + }); + + it('githubCliAccounts forwards the hostname', () => { + const api = getExposedApi(); + + void api.githubCliAccounts('github.example.com'); + + expect(invokeMainEventMock).toHaveBeenCalledWith( + EVENTS.GITHUB_CLI_ACCOUNTS, + 'github.example.com', + ); + }); + it('openExternalLink sends event with payload', async () => { const api = getExposedApi(); diff --git a/src/preload/index.ts b/src/preload/index.ts index 75f02623b..4a0de2dd8 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -1,6 +1,7 @@ import { contextBridge, webFrame } from 'electron'; import type { + IGitHubCliTokenRequest, IKeyboardShortcut, INativeNotificationActionEvent, INativeNotificationClickEvent, @@ -56,10 +57,19 @@ export const api = { /** * Read the token the locally installed GitHub CLI holds for a host. * - * @param hostname - Host to read the token for (e.g. `github.com`). + * @param request - Host to read the token for, and the identity to address. * @returns The CLI token, or a classified failure with an optional detail line. */ - githubCliToken: (hostname: string) => invokeMainEvent(EVENTS.GITHUB_CLI_TOKEN, hostname), + githubCliToken: (request: IGitHubCliTokenRequest) => + invokeMainEvent(EVENTS.GITHUB_CLI_TOKEN, request), + + /** + * List the identities the locally installed GitHub CLI holds for a host. + * + * @param hostname - Host to list identities for (e.g. `github.com`). + * @returns The usable identities, or a classified failure. + */ + githubCliAccounts: (hostname: string) => invokeMainEvent(EVENTS.GITHUB_CLI_ACCOUNTS, hostname), /** * Enable or disable launching the application at system login. diff --git a/src/renderer/hooks/useLogins.test.tsx b/src/renderer/hooks/useLogins.test.tsx index 635034455..192f77872 100644 --- a/src/renderer/hooks/useLogins.test.tsx +++ b/src/renderer/hooks/useLogins.test.tsx @@ -79,10 +79,60 @@ describe('renderer/hooks/useLogins.ts', () => { await result.current.loginWithCli('github', Constants.GITHUB_HOSTNAME); }); - expect(createAccountSpy).toHaveBeenCalledWith('GitHub CLI', '', 'github.com', 'github'); + expect(createAccountSpy).toHaveBeenCalledWith( + 'GitHub CLI', + '', + 'github.com', + 'github', + undefined, + undefined, + undefined, + ); expect(removeAccountNotificationsMock).toHaveBeenCalledWith(mockGitHubCliAccount); }); + it('threads the chosen CLI identity through resolution and account creation', async () => { + const identity = { kind: 'account' as const, login: 'alice' }; + const resolveSpy = vi + .spyOn(getAdapter('github').cliAuth!, 'resolveToken') + .mockResolvedValue('cli-token' as Token); + const { result } = renderLoginsHook(); + + await act(async () => { + await result.current.loginWithCli('github', Constants.GITHUB_HOSTNAME, identity); + }); + + expect(resolveSpy).toHaveBeenCalledWith(Constants.GITHUB_HOSTNAME, identity); + expect(createAccountSpy).toHaveBeenCalledWith( + 'GitHub CLI', + '', + 'github.com', + 'github', + undefined, + undefined, + identity, + ); + }); + + it('keeps another pinned CLI account notifications when adding a different identity', async () => { + const alice = { + ...mockGitHubCliAccount, + cliIdentity: { kind: 'account' as const, login: 'alice' }, + }; + useAccountsStore.setState({ accounts: [alice] }); + vi.spyOn(getAdapter('github').cliAuth!, 'resolveToken').mockResolvedValue('cli-token' as Token); + const { result } = renderLoginsHook(); + + await act(async () => { + await result.current.loginWithCli('github', Constants.GITHUB_HOSTNAME, { + kind: 'account', + login: 'bob', + }); + }); + + expect(removeAccountNotificationsMock).not.toHaveBeenCalledWith(alice); + }); + it('keeps old CLI notifications when replacement login fails', async () => { useAccountsStore.setState({ accounts: [mockGitHubCliAccount] }); vi.spyOn(getAdapter('github').cliAuth!, 'resolveToken').mockResolvedValue('cli-token' as Token); diff --git a/src/renderer/hooks/useLogins.ts b/src/renderer/hooks/useLogins.ts index d03d0393d..10576f395 100644 --- a/src/renderer/hooks/useLogins.ts +++ b/src/renderer/hooks/useLogins.ts @@ -2,6 +2,8 @@ import { useCallback } from 'react'; import { useQueryClient } from '@tanstack/react-query'; +import type { GitHubCliIdentity } from '../../shared/events'; + import { useAccountsStore } from '../stores'; import type { Account, ClientID, Forge, Hostname, Token } from '../types'; @@ -16,6 +18,22 @@ import { getAccountAdapter, getAdapter } from '../utils/forges/registry'; import { encryptValue } from '../utils/system/comms'; import { useNotificationActions } from './notifications/useNotificationActions'; +/** Whether two CLI identities address the same account. */ +function sameCliIdentity( + existing: GitHubCliIdentity | undefined, + incoming: GitHubCliIdentity | undefined, +): boolean { + if (!existing || !incoming || existing.kind !== incoming.kind) { + return false; + } + + if (existing.kind === 'environment' || incoming.kind === 'environment') { + return true; + } + + return existing.login.toLowerCase() === incoming.login.toLowerCase(); +} + interface LoginsState { loginWithDeviceFlowStart: ( forge: Forge, @@ -30,7 +48,7 @@ interface LoginsState { hostname: Hostname, clientId?: ClientID, ) => Promise; - loginWithCli: (forge: Forge, hostname: Hostname) => Promise; + loginWithCli: (forge: Forge, hostname: Hostname, identity?: GitHubCliIdentity) => Promise; loginWithPersonalAccessToken: (data: LoginPersonalAccessTokenOptions) => Promise; logoutFromAccount: (account: Account) => void; } @@ -118,25 +136,40 @@ export const useLogins = (): LoginsState => { * * The token is resolved here only to fail fast while the login screen is * still up. Nothing persists it: the CLI is re-read for every API request, so - * the account carries no credential of its own. + * the account carries no credential of its own. The chosen CLI identity is + * recorded so those reads address the same account each time. */ const loginWithCli = useCallback( - async (forge: Forge, hostname: Hostname) => { + async (forge: Forge, hostname: Hostname, identity?: GitHubCliIdentity) => { const { cliAuth } = getAdapter(forge); if (!cliAuth) { throw new Error(`CLI login is not supported for forge "${forge}".`); } - await cliAuth.resolveToken(hostname); + await cliAuth.resolveToken(hostname, identity); - const existingAccounts = useAccountsStore - .getState() - .accounts.filter( - (a) => a.forge === forge && a.hostname === hostname && a.method === cliAuth.authMethod, - ); - await createAccountInStore(cliAuth.authMethod, '' as Token, hostname, forge); + const beforeLogin = useAccountsStore.getState().accounts; + await createAccountInStore( + cliAuth.authMethod, + '' as Token, + hostname, + forge, + undefined, + undefined, + identity, + ); - existingAccounts.forEach((account) => removeAccountNotifications(account)); + beforeLogin + .filter( + (account) => + account.forge === forge && + account.hostname === hostname && + account.method === cliAuth.authMethod && + // Unpinned accounts predate identity selection; only one can exist + // per host, and any CLI login replaces it. + (account.cliIdentity === undefined || sameCliIdentity(account.cliIdentity, identity)), + ) + .forEach((account) => removeAccountNotifications(account)); await queryClient.invalidateQueries({ queryKey: notificationsKeys.all }); }, diff --git a/src/renderer/i18n/locales/en.json b/src/renderer/i18n/locales/en.json index 80d42fa9f..faa50312c 100644 --- a/src/renderer/i18n/locales/en.json +++ b/src/renderer/i18n/locales/en.json @@ -194,13 +194,25 @@ "login": { "choose_forge": "Choose a forge", "cli": { + "account": "Account", + "account_active": "{{login}} (active)", + "account_enrolled": "{{login}} (already in Gitify)", + "account_placeholder": "Select an account", + "account_required": "Choose an account", + "accounts_failed": "Could not load GitHub CLI accounts for {{hostname}}.", + "accounts_loading": "Loading GitHub CLI accounts…", + "accounts_unsupported": "Using the active account. Update GitHub CLI to choose another.", + "all_accounts_enrolled": "All accounts already in Gitify", + "environment_token": "Environment token", "form_errors": "Form errors", "hostname": "Hostname", - "hostname_caption": "Change only if you are using GitHub Enterprise Server", + "hostname_caption": "Change only for GitHub Enterprise Server.", "hostname_invalid": "Hostname format is invalid", - "intro_scopes": "The scopes come from the GitHub CLI and cannot be changed from Gitify. Its <0>repo scope covers notification access; run <1>gh auth refresh -s notifications to grant that scope explicitly.", - "intro_token": "Uses the token your local <0>gh install already holds, so no token has to be created or pasted. Gitify reads it from the CLI on every refresh, which means <1>gh auth login and <2>gh auth refresh keep working without re-authenticating here.", + "intro": "Gitify uses your existing GitHub CLI login. There’s no token to paste, and Gitify picks up token refreshes automatically.", + "intro_scopes": "Before adding the account, Gitify checks for notification access. Either “repo” or “notifications” is enough.", "login_failed": "Failed to login with GitHub CLI against {{hostname}}", + "missing_notification_scope": "This account needs notification access. Run `{{command}}` for this account, then retry.", + "no_accounts": "No usable accounts for {{hostname}}. Run `gh auth login --hostname {{hostname}}`.", "title": "Login with GitHub CLI" }, "continue_with": "Continue with {{name}}", diff --git a/src/renderer/routes/LoginStates.visual.test.tsx b/src/renderer/routes/LoginStates.visual.test.tsx index 2a8e69e01..93d8561cb 100644 --- a/src/renderer/routes/LoginStates.visual.test.tsx +++ b/src/renderer/routes/LoginStates.visual.test.tsx @@ -4,6 +4,7 @@ import { page } from 'vite-plus/test/browser'; import { setLoginsOverrides } from '../__helpers__/hook-mocks'; import { renderRoute } from '../__helpers__/visual-utils'; +import { mockGitHubCliAccount } from '../__mocks__/account-mocks'; import { DesignLanguage, Theme } from '../types'; @@ -85,9 +86,7 @@ async function captureCliError(theme: Theme, designLanguage: DesignLanguage) { initialEntries: ['/login/github/cli'], }); - await waitFor(() => - expect(document.querySelector('[data-testid="login-submit"]')).not.toBeNull(), - ); + await waitFor(() => expect(document.querySelector('[data-testid="login-submit"]')).toBeEnabled()); await page.getByTestId('login-submit').click(); await waitForLoginError(); await movePointerAway(); @@ -97,6 +96,52 @@ async function captureCliError(theme: Theme, designLanguage: DesignLanguage) { ); } +async function captureCliAccounts(theme: Theme, designLanguage: DesignLanguage) { + vi.mocked(window.gitify.githubCliAccounts).mockResolvedValue({ + accounts: [ + { identity: { kind: 'account', login: 'octocat' }, active: true }, + { identity: { kind: 'account', login: 'octocat-work' }, active: false }, + ], + }); + + renderRoute(, { + accounts: [{ ...mockGitHubCliAccount, cliIdentity: { kind: 'account', login: 'octocat' } }], + theme, + designLanguage, + initialEntries: ['/login/github/cli'], + }); + + await waitFor(() => { + const picker = page.getByTestId('login-cli-account').element(); + const contents = picker.closest('.gitify-scroll-fade')!; + expect(contents.scrollHeight).toBeLessThanOrEqual(contents.clientHeight); + }); + await movePointerAway(); + + await expect(page.getByTestId('visual-root')).toMatchScreenshot( + `login-cli-accounts-${theme.toLowerCase()}-${designLanguage}`, + ); +} + +async function captureCliNoAccounts(theme: Theme, designLanguage: DesignLanguage) { + vi.mocked(window.gitify.githubCliAccounts).mockResolvedValue({ accounts: [] }); + + renderRoute(, { + theme, + designLanguage, + initialEntries: ['/login/github/cli'], + }); + + await waitFor(() => + expect(document.querySelector('[data-testid="login-cli-no-accounts"]')).not.toBeNull(), + ); + await movePointerAway(); + + await expect(page.getByTestId('visual-root')).toMatchScreenshot( + `login-cli-no-accounts-${theme.toLowerCase()}-${designLanguage}`, + ); +} + describe('renderer/routes/Login error states visual regression', () => { describe.each(THEME_VARIANTS)('$theme $designLanguage', ({ designLanguage, theme }) => { it('captures the PAT credentials error', async () => { @@ -116,5 +161,17 @@ describe('renderer/routes/Login error states visual regression', () => { expect(document.querySelector('[data-testid="login-errors"]')).not.toBeNull(); }); + + it('captures the CLI account picker', async () => { + await captureCliAccounts(theme, designLanguage); + + expect(document.querySelector('[data-testid="login-cli-account"]')).not.toBeNull(); + }); + + it('captures the CLI empty-account state', async () => { + await captureCliNoAccounts(theme, designLanguage); + + expect(document.querySelector('[data-testid="login-cli-no-accounts"]')).not.toBeNull(); + }); }); }); diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-dark-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-dark-classic-chromium-linux.png new file mode 100644 index 000000000..d1dcf504f Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-dark-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-dark-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-dark-glass-chromium-linux.png new file mode 100644 index 000000000..7131d937e Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-dark-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-light-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-light-classic-chromium-linux.png new file mode 100644 index 000000000..9bc75b1c8 Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-light-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-light-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-light-glass-chromium-linux.png new file mode 100644 index 000000000..f2f43f19a Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-accounts-light-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-classic-chromium-linux.png index e168a84dd..c9d362e16 100644 Binary files a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-glass-chromium-linux.png index cc2dfd147..2c7e29f53 100644 Binary files a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-dark-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-classic-chromium-linux.png index cafc708bc..580f7d8eb 100644 Binary files a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-glass-chromium-linux.png index e6b40371a..43e6abdac 100644 Binary files a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-error-light-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-dark-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-dark-classic-chromium-linux.png new file mode 100644 index 000000000..5607e68ad Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-dark-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-dark-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-dark-glass-chromium-linux.png new file mode 100644 index 000000000..ef6ce9e05 Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-dark-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-light-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-light-classic-chromium-linux.png new file mode 100644 index 000000000..f2b9bdb28 Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-light-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-light-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-light-glass-chromium-linux.png new file mode 100644 index 000000000..ea6969dda Binary files /dev/null and b/src/renderer/routes/__screenshots__/LoginStates.visual.test.tsx/login-cli-no-accounts-light-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-classic-chromium-linux.png index a1802a9cb..c9c20271c 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-glass-chromium-linux.png index 07eebc3ef..db30749a4 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-dark-glass-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-classic-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-classic-chromium-linux.png index 16f0c2a82..588cffa72 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-classic-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-classic-chromium-linux.png differ diff --git a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-glass-chromium-linux.png b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-glass-chromium-linux.png index 242269fec..1f303b90c 100644 Binary files a/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-glass-chromium-linux.png and b/src/renderer/routes/__screenshots__/routes.visual.test.tsx/login-github-cli-light-glass-chromium-linux.png differ diff --git a/src/renderer/routes/github/LoginWithGitHubCLI.test.tsx b/src/renderer/routes/github/LoginWithGitHubCLI.test.tsx index d0f778b88..1d29698d8 100644 --- a/src/renderer/routes/github/LoginWithGitHubCLI.test.tsx +++ b/src/renderer/routes/github/LoginWithGitHubCLI.test.tsx @@ -1,32 +1,57 @@ -import { screen, waitFor } from '@testing-library/react'; +import { screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { navigateMock, renderWithProviders } from '../../__helpers__/test-utils'; -import { mockGitHubEnterpriseServerAccount } from '../../__mocks__/account-mocks'; +import { + mockGitHubCliAccount, + mockGitHubCloudAccount, + mockGitHubEnterpriseServerAccount, +} from '../../__mocks__/account-mocks'; + +import type { IGitHubCliAccountsResult } from '../../../shared/events'; import * as logger from '../../utils/core/logger'; import { GitHubLoginWithCLIRoute } from './LoginWithGitHubCLI'; +const SINGLE_ACCOUNT: IGitHubCliAccountsResult = { + accounts: [{ identity: { kind: 'account', login: 'octocat' }, active: true }], +}; + +const ACTIVE_OCTOCAT = { kind: 'account' as const, login: 'octocat' }; + +function stubAccounts(result: IGitHubCliAccountsResult): void { + vi.mocked(window.gitify.githubCliAccounts).mockResolvedValue(result); +} + +async function waitForLoginReady(): Promise { + const button = screen.getByRole('button', { name: 'Login' }); + await waitFor(() => expect(button).toBeEnabled()); + return button; +} + describe('renderer/routes/github/LoginWithGitHubCLI.tsx', () => { const loginWithCliMock = vi.fn(); - it('renders correctly', () => { + it('renders correctly', async () => { const tree = renderWithProviders(); + await waitForLoginReady(); + expect(tree.container).toMatchSnapshot(); }); - it('logs in against github.com without asking for a token', async () => { + it('logs in against github.com with the offered identity', async () => { loginWithCliMock.mockResolvedValueOnce(undefined); renderWithProviders(, { loginWithCli: loginWithCliMock }); expect(screen.queryByTestId('login-token')).not.toBeInTheDocument(); - await userEvent.click(screen.getByRole('button', { name: 'Login' })); + const button = await waitForLoginReady(); + await userEvent.click(button); await waitFor(() => { - expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.com'); + expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.com', ACTIVE_OCTOCAT); expect(navigateMock).toHaveBeenCalledWith('/'); }); }); @@ -39,10 +64,11 @@ describe('renderer/routes/github/LoginWithGitHubCLI.tsx', () => { const hostname = screen.getByRole('textbox', { name: /Hostname/ }); await userEvent.clear(hostname); await userEvent.type(hostname, 'github.gitify.io'); - await userEvent.click(screen.getByRole('button', { name: 'Login' })); + const button = await waitForLoginReady(); + await userEvent.click(button); await waitFor(() => - expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.gitify.io'), + expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.gitify.io', ACTIVE_OCTOCAT), ); }); @@ -81,7 +107,8 @@ describe('renderer/routes/github/LoginWithGitHubCLI.tsx', () => { renderWithProviders(, { loginWithCli: loginWithCliMock }); - await userEvent.click(screen.getByRole('button', { name: 'Login' })); + const button = await waitForLoginReady(); + await userEvent.click(button); await waitFor(() => expect(screen.getByTestId('login-errors')).toHaveTextContent( @@ -90,4 +117,233 @@ describe('renderer/routes/github/LoginWithGitHubCLI.tsx', () => { ); expect(navigateMock).not.toHaveBeenCalledWith('/'); }); + + it('lists every stored account and preselects the active one', async () => { + stubAccounts({ + accounts: [ + { identity: { kind: 'account', login: 'alice' }, active: true }, + { identity: { kind: 'account', login: 'bob' }, active: false }, + ], + }); + + renderWithProviders(, { loginWithCli: loginWithCliMock }); + + const select = await screen.findByTestId('login-cli-account'); + expect(await waitForLoginReady()).toBeEnabled(); + expect(select).toHaveValue('account:alice'); + expect(within(select).getByRole('option', { name: 'alice (active)' })).toBeInTheDocument(); + expect(within(select).getByRole('option', { name: 'bob' })).toBeInTheDocument(); + }); + + it('logs in with the enterprise managed account the user picks', async () => { + loginWithCliMock.mockResolvedValueOnce(undefined); + stubAccounts({ + accounts: [ + { identity: { kind: 'account', login: 'alice' }, active: true }, + { identity: { kind: 'account', login: 'mona-cat_octo' }, active: false }, + ], + }); + + renderWithProviders(, { loginWithCli: loginWithCliMock }); + + const select = await screen.findByTestId('login-cli-account'); + await userEvent.selectOptions(select, 'account:mona-cat_octo'); + await userEvent.click(await waitForLoginReady()); + + await waitFor(() => + expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.com', { + kind: 'account', + login: 'mona-cat_octo', + }), + ); + }); + + it('disables already enrolled accounts and preselects the only available account', async () => { + stubAccounts({ + accounts: [ + { identity: { kind: 'account', login: 'alice' }, active: true }, + { identity: { kind: 'account', login: 'bob' }, active: false }, + ], + }); + renderWithProviders(, { + accounts: [ + { ...mockGitHubCloudAccount, user: { ...mockGitHubCloudAccount.user!, login: 'Alice' } }, + ], + }); + + const select = await screen.findByTestId('login-cli-account'); + expect( + within(select).getByRole('option', { name: 'alice (already in Gitify)' }), + ).toBeDisabled(); + expect(select).toHaveValue('account:bob'); + expect(await waitForLoginReady()).toBeEnabled(); + }); + + it('blocks login when the only CLI account is already enrolled', async () => { + renderWithProviders(, { + accounts: [{ ...mockGitHubCliAccount, cliIdentity: ACTIVE_OCTOCAT }], + }); + + const select = await screen.findByTestId('login-cli-account'); + expect( + within(select).getByRole('option', { name: 'octocat (already in Gitify)' }), + ).toBeDisabled(); + expect(select).toHaveValue(''); + expect( + within(select).getByRole('option', { name: 'All accounts already in Gitify' }), + ).toBeVisible(); + expect(screen.getByRole('button', { name: 'Login' })).toBeDisabled(); + }); + + it('offers the environment credential as its own choice', async () => { + loginWithCliMock.mockResolvedValueOnce(undefined); + stubAccounts({ + accounts: [ + { identity: { kind: 'account', login: 'alice' }, active: false }, + { identity: { kind: 'environment' }, active: true }, + ], + }); + + renderWithProviders(, { loginWithCli: loginWithCliMock }); + + const select = await screen.findByTestId('login-cli-account'); + expect(within(select).getByRole('option', { name: 'Environment token' })).toBeInTheDocument(); + await userEvent.selectOptions(select, 'environment'); + await userEvent.click(await waitForLoginReady()); + + await waitFor(() => + expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.com', { + kind: 'environment', + }), + ); + }); + + it('hides the choice when only one account is offered', async () => { + renderWithProviders(, { loginWithCli: loginWithCliMock }); + + await waitForLoginReady(); + + expect(screen.queryByTestId('login-cli-account')).not.toBeInTheDocument(); + }); + + it('explains how to add an account when the CLI has none', async () => { + stubAccounts({ accounts: [] }); + renderWithProviders(, { loginWithCli: loginWithCliMock }); + + await waitFor(() => expect(screen.getByTestId('login-cli-no-accounts')).toBeVisible()); + + expect(screen.getByTestId('login-cli-no-accounts')).toHaveTextContent('gh auth login'); + expect(screen.getByRole('button', { name: 'Login' })).toBeDisabled(); + }); + + it('disables login when the CLI account list cannot be read', async () => { + stubAccounts({ error: 'GH_FAILED', detail: 'keyring is locked' }); + renderWithProviders(, { loginWithCli: loginWithCliMock }); + + await waitFor(() => + expect(screen.getByText(/Could not load GitHub CLI accounts/)).toBeVisible(), + ); + expect(screen.getByRole('button', { name: 'Login' })).toBeDisabled(); + }); + + it('falls back to the active account on a CLI that cannot list accounts', async () => { + loginWithCliMock.mockResolvedValueOnce(undefined); + stubAccounts({ error: 'GH_ACCOUNTS_UNSUPPORTED' }); + renderWithProviders(, { loginWithCli: loginWithCliMock }); + + const button = await waitForLoginReady(); + expect(screen.queryByTestId('login-cli-account')).not.toBeInTheDocument(); + expect(screen.getByText(/Using the active account/)).toBeVisible(); + + await userEvent.click(button); + + await waitFor(() => + expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.com', undefined), + ); + }); + + it('preselects the pinned identity when re-authenticating', async () => { + const account = { + ...mockGitHubCliAccount, + cliIdentity: { kind: 'account' as const, login: 'bob' }, + }; + stubAccounts({ + accounts: [ + { identity: { kind: 'account', login: 'alice' }, active: true }, + { identity: { kind: 'account', login: 'bob' }, active: false }, + ], + }); + + renderWithProviders(, { + accounts: [account], + initialEntries: [ + { + pathname: '/login/github/cli', + state: { + account, + }, + }, + ], + }); + + const select = await screen.findByTestId('login-cli-account'); + expect(select).toHaveValue('account:bob'); + expect(within(select).getByRole('option', { name: 'bob' })).toBeEnabled(); + }); + + it('requires a new choice when the pinned identity is gone', async () => { + stubAccounts({ + accounts: [ + { identity: { kind: 'account', login: 'alice' }, active: true }, + { identity: { kind: 'account', login: 'bob' }, active: false }, + ], + }); + + renderWithProviders(, { + initialEntries: [ + { + pathname: '/login/github/cli', + state: { + account: { + ...mockGitHubEnterpriseServerAccount, + cliIdentity: { kind: 'account', login: 'carol' }, + }, + }, + }, + ], + }); + + expect(await screen.findByTestId('login-cli-account')).toHaveValue(''); + expect(screen.getByRole('button', { name: 'Login' })).toBeDisabled(); + }); + + it('reloads the account list when the hostname changes', async () => { + stubAccounts(SINGLE_ACCOUNT); + vi.mocked(window.gitify.githubCliAccounts) + .mockResolvedValueOnce(SINGLE_ACCOUNT) + .mockResolvedValueOnce({ + accounts: [{ identity: { kind: 'account', login: 'enterprise' }, active: true }], + }); + + renderWithProviders(, { loginWithCli: loginWithCliMock }); + await waitForLoginReady(); + + const hostname = screen.getByRole('textbox', { name: /Hostname/ }); + await userEvent.clear(hostname); + await userEvent.type(hostname, 'github.gitify.io'); + const button = await waitForLoginReady(); + + await waitFor(() => + expect(window.gitify.githubCliAccounts).toHaveBeenLastCalledWith('github.gitify.io'), + ); + expect(screen.queryByTestId('login-cli-account')).not.toBeInTheDocument(); + await userEvent.click(button); + + await waitFor(() => + expect(loginWithCliMock).toHaveBeenCalledWith('github', 'github.gitify.io', { + kind: 'account', + login: 'enterprise', + }), + ); + }); }); diff --git a/src/renderer/routes/github/LoginWithGitHubCLI.tsx b/src/renderer/routes/github/LoginWithGitHubCLI.tsx index 48ac2c6b2..4e26a8911 100644 --- a/src/renderer/routes/github/LoginWithGitHubCLI.tsx +++ b/src/renderer/routes/github/LoginWithGitHubCLI.tsx @@ -1,13 +1,25 @@ -import { useCallback, useState } from 'react'; -import { Trans, useTranslation } from 'react-i18next'; +import { useCallback, useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; import { useLocation, useNavigate } from 'react-router'; import { SignInIcon, TerminalIcon } from '@primer/octicons-react'; -import { Banner, Button, FormControl, Stack, Text, TextInput } from '@primer/react'; +import { + Banner, + Button, + FormControl, + Select, + Spinner, + Stack, + Text, + TextInput, +} from '@primer/react'; + +import type { GitHubCliIdentity } from '../../../shared/events'; import { Constants } from '../../constants'; import { useLogins } from '../../hooks/useLogins'; +import { useAccountsStore } from '../../stores'; import { Contents } from '../../components/layout/Contents'; import { Page } from '../../components/layout/Page'; @@ -15,16 +27,78 @@ import { Footer } from '../../components/primitives/Footer'; import { Header } from '../../components/primitives/Header'; import type { Account, Hostname } from '../../types'; +import type { CliAccountChoice, CliAccountsError } from '../../utils/forges/types'; import i18n from '../../i18n'; import { summarizeLoginError } from '../../utils/auth/loginValidation'; -import { isValidHostname } from '../../utils/auth/utils'; +import { getAccountUUID, isValidHostname } from '../../utils/auth/utils'; import { rendererLogError, toError } from '../../utils/core/logger'; +import { getAdapter } from '../../utils/forges/registry'; interface LocationState { account?: Account; } +type AccountsState = + | { status: 'idle' } + | { status: 'loading' } + | { status: 'ready'; accounts: CliAccountChoice[] } + | { status: 'unsupported' } + | { status: 'failed'; error: CliAccountsError }; + +/** How long to wait after the hostname settles before asking the CLI. */ +const ACCOUNTS_DEBOUNCE_MS = 250; + +const ENVIRONMENT_VALUE = 'environment'; + +/** Stable option value for an identity; also its cache and comparison key. */ +function identityValue(identity: GitHubCliIdentity): string { + return identity.kind === 'account' ? `account:${identity.login}` : ENVIRONMENT_VALUE; +} + +function identityFromValue(value: string): GitHubCliIdentity | undefined { + if (value === ENVIRONMENT_VALUE) { + return { kind: 'environment' }; + } + + return value.startsWith('account:') + ? { kind: 'account', login: value.slice('account:'.length) } + : undefined; +} + +function sameIdentity(left: GitHubCliIdentity, right: GitHubCliIdentity): boolean { + if (left.kind !== right.kind) { + return false; + } + + if (left.kind === 'environment' || right.kind === 'environment') { + return true; + } + + return left.login.toLowerCase() === right.login.toLowerCase(); +} + +/** + * Choose the identity to preselect: a still-offered pinned identity wins; + * otherwise the only offered identity, otherwise the CLI's active one. + * A pinned identity that is no longer offered selects nothing, so the user + * must choose rather than silently signing in as someone else. + */ +function preferredIdentity( + accounts: CliAccountChoice[], + pinned: GitHubCliIdentity | undefined, +): GitHubCliIdentity | undefined { + if (pinned) { + return accounts.find((account) => sameIdentity(account.identity, pinned))?.identity; + } + + if (accounts.length === 1) { + return accounts[0].identity; + } + + return accounts.find((account) => account.active)?.identity; +} + export function GitHubLoginWithCLIRoute() { const { t } = useTranslation(); const navigate = useNavigate(); @@ -32,24 +106,113 @@ export function GitHubLoginWithCLIRoute() { const { account: reAuthAccount } = (location.state ?? {}) as LocationState; const { loginWithCli } = useLogins(); + const enrolledAccounts = useAccountsStore((state) => state.accounts); const [hostname, setHostname] = useState( reAuthAccount?.hostname ?? Constants.GITHUB_HOSTNAME, ); + const [accountsResult, setAccountsResult] = useState<{ + hostname: Hostname; + state: AccountsState; + } | null>(null); + const [userSelection, setUserSelection] = useState<{ + hostname: Hostname; + identity?: GitHubCliIdentity; + } | null>(null); const [isLoggingIn, setIsLoggingIn] = useState(false); const [error, setError] = useState(null); - const handleSubmit = useCallback(async () => { + const pinnedIdentity = reAuthAccount?.cliIdentity; + + useEffect(() => { + if (!hostname || !isValidHostname(hostname)) { + return; + } + + let cancelled = false; + + const timer = setTimeout(() => { + void loadAccounts(hostname).then((state) => { + if (!cancelled) { + setAccountsResult({ hostname, state }); + } + }); + }, ACCOUNTS_DEBOUNCE_MS); + + return () => { + cancelled = true; + clearTimeout(timer); + }; + }, [hostname]); + + // Derived during render so a hostname change immediately disables Login and + // clears the old host's choice without an effect-driven state update. + let accountsState: AccountsState = { status: 'idle' }; + if (isValidHostname(hostname)) { + accountsState = + accountsResult?.hostname === hostname ? accountsResult.state : { status: 'loading' }; + } + + const offeredAccounts = accountsState.status === 'ready' ? accountsState.accounts : []; + const reAuthUUID = reAuthAccount && getAccountUUID(reAuthAccount); + const enrolledForHost = enrolledAccounts.filter( + (account) => + account.forge === 'github' && + account.hostname.toLowerCase() === hostname.toLowerCase() && + getAccountUUID(account) !== reAuthUUID, + ); + const isEnrolled = ({ identity }: CliAccountChoice) => + enrolledForHost.some( + (account) => + (account.cliIdentity && sameIdentity(account.cliIdentity, identity)) || + (identity.kind === 'account' && + account.user?.login.toLowerCase() === identity.login.toLowerCase()), + ); + const availableAccounts = offeredAccounts.filter((account) => !isEnrolled(account)); + const defaultIdentity = preferredIdentity(availableAccounts, pinnedIdentity); + + const selectedIdentity = + userSelection?.hostname === hostname ? userSelection.identity : defaultIdentity; + const selectedAccount = selectedIdentity + ? availableAccounts.find((account) => sameIdentity(account.identity, selectedIdentity)) + : undefined; + + const pinnedStillOffered = + !pinnedIdentity || + accountsState.status !== 'ready' || + availableAccounts.some((account) => sameIdentity(account.identity, pinnedIdentity)); + + const allEnrolled = offeredAccounts.length > 0 && availableAccounts.length === 0; + const showPicker = offeredAccounts.length > 1 || allEnrolled || !pinnedStillOffered; + + const accountChoiceReady = + accountsState.status === 'unsupported' || + accountsState.status === 'idle' || + selectedAccount !== undefined; + + const selectIdentity = useCallback( + (value: string) => { + setUserSelection({ hostname, identity: identityFromValue(value) }); + }, + [hostname], + ); + + const handleSubmit = async () => { if (!hostname || !isValidHostname(hostname)) { setError(i18n.t('login.cli.hostname_invalid', 'Hostname format is invalid')); return; } + if (!accountChoiceReady) { + setError(i18n.t('login.cli.account_required', 'Choose an account')); + return; + } + setError(null); setIsLoggingIn(true); try { - await loginWithCli('github', hostname); + await loginWithCli('github', hostname, selectedAccount?.identity); void navigate('/'); } catch (err) { rendererLogError('loginWithCli', 'Failed to login with GitHub CLI', toError(err)); @@ -62,7 +225,7 @@ export function GitHubLoginWithCLIRoute() { } finally { setIsLoggingIn(false); } - }, [hostname, loginWithCli, navigate]); + }; return ( @@ -80,38 +243,26 @@ export function GitHubLoginWithCLIRoute() { )} - - , - , - , - ]} - defaults="Uses the token your local <0>gh install already holds, so no token has to be created or pasted. Gitify reads it from the CLI on every refresh, which means <1>gh auth login and <2>gh auth refresh keep working without re-authenticating here." - /> - - - - , - , - , - ]} - defaults="The scopes come from the GitHub CLI and cannot be changed from Gitify. Its <0>repo scope covers notification access; run <1>gh auth refresh -s notifications to grant that scope explicitly." - /> - + + + {t( + 'login.cli.intro', + 'Gitify uses your existing GitHub CLI login. There’s no token to paste, and Gitify picks up token refreshes automatically.', + )} + + + {t( + 'login.cli.intro_scopes', + 'Before adding the account, Gitify checks for notification access. Either “repo” or “notifications” is enough.', + )} + + {t('login.cli.hostname', 'Hostname')} - {t( - 'login.cli.hostname_caption', - 'Change only if you are using GitHub Enterprise Server', - )} + {t('login.cli.hostname_caption', 'Change only for GitHub Enterprise Server.')} + + {accountsState.status === 'loading' && ( + + + + {t('login.cli.accounts_loading', 'Loading GitHub CLI accounts…')} + + + )} + + {accountsState.status === 'failed' && ( + + {t( + 'login.cli.accounts_failed', + 'Could not load GitHub CLI accounts for {{hostname}}.', + { hostname }, + )} + + )} + + {accountsState.status === 'ready' && accountsState.accounts.length === 0 && ( + + {t( + 'login.cli.no_accounts', + 'No usable accounts for {{hostname}}. Run `gh auth login --hostname {{hostname}}`.', + { hostname }, + )} + + } + hideTitle + title={t('login.cli.form_errors', 'Form errors')} + variant="warning" + /> + )} + + {accountsState.status === 'unsupported' && ( + + {t( + 'login.cli.accounts_unsupported', + 'Using the active account. Update GitHub CLI to choose another.', + )} + + )} + + {showPicker && accountsState.status === 'ready' && ( + + {t('login.cli.account', 'Account')} + + + )}