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>repo0> scope covers notification access; run <1>gh auth refresh -s notifications1> to grant that scope explicitly.",
- "intro_token": "Uses the token your local <0>gh0> 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 login1> and <2>gh auth refresh2> 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>gh0> 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 login1> and <2>gh auth refresh2> keep working without re-authenticating here."
- />
-
-
-
- ,
- ,
- ,
- ]}
- defaults="The scopes come from the GitHub CLI and cannot be changed from Gitify. Its <0>repo0> scope covers notification access; run <1>gh auth refresh -s notifications1> 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')}
+
+
+ )}
+
renders correctly 1`] =
class="prc-Text-Text-9mHv3"
data-component="Text"
>
- Change only if you are using GitHub Enterprise Server
+ Change only for GitHub Enterprise Server.
diff --git a/src/renderer/routes/routes.visual.test.tsx b/src/renderer/routes/routes.visual.test.tsx
index 31cef0ee6..0a22bc061 100644
--- a/src/renderer/routes/routes.visual.test.tsx
+++ b/src/renderer/routes/routes.visual.test.tsx
@@ -155,6 +155,14 @@ async function captureRoute(
settings: { ...route.state?.settings, ...settings },
});
+ if (route.name === 'login-github-cli') {
+ await vi.waitFor(() => {
+ if (!document.querySelector('[data-testid="login-submit"]:enabled')) {
+ throw new Error('Waiting for GitHub CLI accounts to load');
+ }
+ });
+ }
+
// These baselines capture idle routes. Hover/focus interactions have their
// own coverage; park the pointer on empty sidebar space between captures.
await page.getByTestId('visual-root').hover({ position: { x: 1, y: 399 } });
diff --git a/src/renderer/stores/types.ts b/src/renderer/stores/types.ts
index 8c51ce06a..f401ebaaf 100644
--- a/src/renderer/stores/types.ts
+++ b/src/renderer/stores/types.ts
@@ -1,3 +1,5 @@
+import type { GitHubCliIdentity } from '../../shared/events';
+
import type {
Account,
AccountUUID,
@@ -42,6 +44,7 @@ export interface AccountsActions {
forge?: Forge,
username?: string,
clientId?: ClientID,
+ cliIdentity?: GitHubCliIdentity,
) => Promise;
/**
diff --git a/src/renderer/stores/useAccountsStore.test.ts b/src/renderer/stores/useAccountsStore.test.ts
index 433754e51..b8286f32d 100644
--- a/src/renderer/stores/useAccountsStore.test.ts
+++ b/src/renderer/stores/useAccountsStore.test.ts
@@ -18,6 +18,7 @@ import { getAccountUUID } from '../utils/auth/utils';
import * as logger from '../utils/core/logger';
import * as apiClient from '../utils/forges/github/client';
import { getAdapter } from '../utils/forges/registry';
+import * as comms from '../utils/system/comms';
import { DEFAULT_ACCOUNTS_STATE } from './defaults';
import useAccountsStore, { sanitizeAccounts } from './useAccountsStore';
@@ -121,6 +122,41 @@ describe('renderer/stores/useAccountsStore.ts', () => {
expect(account.token).toBe(mockCustomOAuthAppAccount.token);
expect(account.clientId).toBeUndefined();
});
+
+ it.each(['alice', 'mona-cat_octo'])('preserves the CLI identity for %s', (login) => {
+ const [account] = sanitizeAccounts([
+ {
+ ...mockGitHubCliAccount,
+ cliIdentity: { kind: 'account', login },
+ },
+ ]);
+
+ expect(account.cliIdentity).toEqual({ kind: 'account', login });
+ });
+
+ it('preserves the environment CLI identity', () => {
+ const [account] = sanitizeAccounts([
+ { ...mockGitHubCliAccount, cliIdentity: { kind: 'environment' } },
+ ]);
+
+ expect(account.cliIdentity).toEqual({ kind: 'environment' });
+ });
+
+ it.each([
+ { kind: 'account', login: 'not a login' },
+ { kind: 'account', login: 'alice; rm -rf /' },
+ { kind: 'account' },
+ { kind: 'unknown' },
+ { login: 'alice' },
+ 'alice',
+ ])('drops a malformed CLI identity %o', (cliIdentity) => {
+ const [account] = sanitizeAccounts([
+ { ...mockGitHubCliAccount, cliIdentity: cliIdentity as never },
+ ]);
+
+ expect(account).toBeDefined();
+ expect(account.cliIdentity).toBeUndefined();
+ });
});
it.each([
@@ -270,8 +306,8 @@ describe('renderer/stores/useAccountsStore.ts', () => {
expect(useAccountsStore.getState().accounts).toHaveLength(1);
});
- test('replaces all CLI accounts for the host after validating the new user', async () => {
- const previous = structuredClone(mockGitHubCliAccount);
+ test('replaces unpinned CLI accounts for the same user after validating the new login', async () => {
+ const previous = { ...structuredClone(mockGitHubCliAccount), user: expectedUser() };
const otherHost = { ...previous, hostname: mockGitHubEnterpriseServerAccount.hostname };
useAccountsStore.setState({
accounts: [
@@ -296,6 +332,96 @@ describe('renderer/stores/useAccountsStore.ts', () => {
expect(invalidate).toHaveBeenCalledWith(previous);
});
+ test('keeps CLI accounts pinned to different identities on one host', async () => {
+ const alice = {
+ ...structuredClone(mockGitHubCliAccount),
+ user: expectedUser(),
+ cliIdentity: { kind: 'account' as const, login: 'alice' },
+ };
+ useAccountsStore.setState({ accounts: [alice] });
+ fetchAuthenticatedUserDetailsSpy.mockResolvedValueOnce({
+ status: 200,
+ url: 'https://api.github.com/user',
+ data: { ...mockRawUser('bob'), id: 2 } as GetAuthenticatedUserResponse,
+ headers: { 'x-oauth-scopes': getRecommendedScopeNames().join(', ') },
+ });
+
+ await useAccountsStore
+ .getState()
+ .createAccount(
+ 'GitHub CLI',
+ '' as Token,
+ alice.hostname,
+ 'github',
+ undefined,
+ undefined,
+ {
+ kind: 'account',
+ login: 'bob',
+ },
+ );
+
+ const accounts = useAccountsStore.getState().accounts;
+ expect(accounts).toHaveLength(2);
+ expect(accounts.map((account) => account.cliIdentity)).toEqual([
+ { kind: 'account', login: 'alice' },
+ { kind: 'account', login: 'bob' },
+ ]);
+ });
+
+ test('updates the CLI account pinned to the same login', async () => {
+ const alice = {
+ ...structuredClone(mockGitHubCliAccount),
+ user: expectedUser(),
+ cliIdentity: { kind: 'account' as const, login: 'alice' },
+ };
+ useAccountsStore.setState({ accounts: [alice] });
+
+ await useAccountsStore
+ .getState()
+ .createAccount(
+ 'GitHub CLI',
+ '' as Token,
+ alice.hostname,
+ 'github',
+ undefined,
+ undefined,
+ {
+ kind: 'account',
+ login: 'ALICE',
+ },
+ );
+
+ expect(useAccountsStore.getState().accounts).toHaveLength(1);
+ });
+
+ test('collapses an environment login into an existing account for the same user', async () => {
+ const alice = {
+ ...structuredClone(mockGitHubCliAccount),
+ user: expectedUser(),
+ cliIdentity: { kind: 'account' as const, login: 'alice' },
+ };
+ useAccountsStore.setState({ accounts: [alice] });
+
+ await useAccountsStore
+ .getState()
+ .createAccount(
+ 'GitHub CLI',
+ '' as Token,
+ alice.hostname,
+ 'github',
+ undefined,
+ undefined,
+ {
+ kind: 'environment',
+ },
+ );
+
+ const accounts = useAccountsStore.getState().accounts;
+ expect(accounts).toHaveLength(1);
+ expect(accounts[0].cliIdentity).toEqual({ kind: 'environment' });
+ });
+
test('keeps the previous CLI account when the new login fails', async () => {
const previous = structuredClone(mockGitHubCliAccount);
useAccountsStore.setState({ accounts: [previous] });
@@ -307,6 +433,22 @@ describe('renderer/stores/useAccountsStore.ts', () => {
expect(useAccountsStore.getState().accounts).toEqual([previous]);
});
+
+ test('does not enroll a CLI token without notification access', async () => {
+ fetchAuthenticatedUserDetailsSpy.mockResolvedValueOnce({
+ status: 200,
+ url: 'https://api.github.com/user',
+ data: mockAuthenticatedResponse as GetAuthenticatedUserResponse,
+ headers: { 'x-oauth-scopes': 'public_repo, read:org' },
+ });
+
+ await expect(
+ useAccountsStore
+ .getState()
+ .createAccount('GitHub CLI', '' as Token, mockGitHubCliAccount.hostname),
+ ).rejects.toThrow('gh auth refresh -s notifications');
+ expect(useAccountsStore.getState().accounts).toEqual([]);
+ });
});
describe('GitHub Enterprise Server accounts', () => {
@@ -374,6 +516,42 @@ describe('renderer/stores/useAccountsStore.ts', () => {
});
});
+ describe('refreshAccount', () => {
+ it('pins a legacy CLI account in place without changing its UUID', async () => {
+ const legacy = {
+ ...structuredClone(mockGitHubCliAccount),
+ user: { id: '1', login: 'octocat', name: 'Mona Lisa Octocat', avatar: null },
+ };
+ useAccountsStore.setState({ accounts: [legacy] });
+ const originalUUID = getAccountUUID(legacy);
+ const listSpy = vi.spyOn(comms, 'listGitHubCliAccounts').mockResolvedValueOnce({
+ accounts: [{ identity: { kind: 'account', login: 'authenticated-user' }, active: true }],
+ });
+
+ const refreshed = await useAccountsStore.getState().refreshAccount(legacy);
+
+ expect(listSpy).toHaveBeenCalledWith(legacy.hostname);
+ expect(refreshed.cliIdentity).toEqual({ kind: 'account', login: 'authenticated-user' });
+ expect(getAccountUUID(refreshed)).toBe(originalUUID);
+ expect(useAccountsStore.getState().accounts).toHaveLength(1);
+ });
+
+ it('leaves an already pinned account alone', async () => {
+ const pinned = {
+ ...structuredClone(mockGitHubCliAccount),
+ user: { id: '1', login: 'octocat', name: 'Mona Lisa Octocat', avatar: null },
+ cliIdentity: { kind: 'account' as const, login: 'alice' },
+ };
+ useAccountsStore.setState({ accounts: [pinned] });
+ const listSpy = vi.spyOn(comms, 'listGitHubCliAccounts');
+
+ await useAccountsStore.getState().refreshAccount(pinned);
+
+ expect(listSpy).not.toHaveBeenCalled();
+ expect(pinned.cliIdentity).toEqual({ kind: 'account', login: 'alice' });
+ });
+ });
+
describe('removeAccount', () => {
test('removes an account', () => {
useAccountsStore.setState({
diff --git a/src/renderer/stores/useAccountsStore.ts b/src/renderer/stores/useAccountsStore.ts
index e98426ee8..f867a64f9 100644
--- a/src/renderer/stores/useAccountsStore.ts
+++ b/src/renderer/stores/useAccountsStore.ts
@@ -1,14 +1,19 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
+import type { GitHubCliIdentity } from '../../shared/events';
+
import { Constants } from '../constants';
import type { Account, ClientID, Forge, Hostname, Token } from '../types';
import type { AuthMethod } from '../utils/auth/types';
import type { AccountsState, AccountsStore } from './types';
+import i18n from '../i18n';
+import { sanitizeCliIdentity } from '../utils/auth/identity';
+import { externallyManagedScopes, hasRequiredScopes } from '../utils/auth/scopes';
import { getAccountUUID, refreshAccount } from '../utils/auth/utils';
-import { rendererLogInfo, rendererLogWarn } from '../utils/core/logger';
+import { rendererLogError, rendererLogInfo, rendererLogWarn, toError } from '../utils/core/logger';
import { getAccountAdapter, getAdapter, isKnownForge } from '../utils/forges/registry';
import { decryptValue, encryptValue } from '../utils/system/comms';
import { DEFAULT_ACCOUNTS_STATE } from './defaults';
@@ -31,6 +36,32 @@ function migrateLegacyAuthMethod(method: string): AuthMethod {
}
}
+/** Case-insensitive key for a CLI identity, or `undefined` when none is pinned. */
+function cliIdentityKey(identity: GitHubCliIdentity | undefined): string | undefined {
+ if (!identity) {
+ return undefined;
+ }
+
+ return identity.kind === 'account' ? `account:${identity.login.toLowerCase()}` : 'environment';
+}
+
+/**
+ * Whether a stored CLI account and an incoming CLI login represent the same
+ * identity. Different `gh` logins are different users, but the same user can be
+ * reachable through the environment credential and a stored login, so a shared
+ * user id also counts as the same account.
+ */
+function sharesCliIdentity(existing: Account, incoming: Account): boolean {
+ const existingKey = cliIdentityKey(existing.cliIdentity);
+ const incomingKey = cliIdentityKey(incoming.cliIdentity);
+
+ if (existingKey && incomingKey && existingKey === incomingKey) {
+ return true;
+ }
+
+ return existing.user?.id !== undefined && existing.user.id === incoming.user?.id;
+}
+
/**
* Sanitise persisted accounts state. Persisted JSON is untrusted (XSS, malicious
* extension, file-system tampering), so we project only the known fields,
@@ -53,6 +84,7 @@ export function sanitizeAccounts(accounts: Account[]): Account[] {
token: a.token,
clientId: a.clientId,
username: a.username,
+ cliIdentity: sanitizeCliIdentity(a.cliIdentity),
user: a.user,
scopes: a.scopes,
};
@@ -78,6 +110,7 @@ const useAccountsStore = create()(
forge: Forge = 'github',
username?: string,
clientId?: ClientID,
+ cliIdentity?: GitHubCliIdentity,
) => {
const encryptedToken = (await encryptValue(token)) as Token;
@@ -89,19 +122,33 @@ const useAccountsStore = create()(
token: encryptedToken,
clientId,
username,
+ cliIdentity,
user: null, // Will be updated during the refresh call below
};
newAccount = await refreshAccount(newAccount);
- const newAccountUUID = getAccountUUID(newAccount);
-
- const accounts = get().accounts;
const adapter = getAdapter(forge);
const isCliAccount = method === adapter.cliAuth?.authMethod;
+ const managedScopes = isCliAccount ? externallyManagedScopes(newAccount) : undefined;
+ if (managedScopes && !hasRequiredScopes(newAccount)) {
+ throw new Error(
+ i18n.t(
+ 'login.cli.missing_notification_scope',
+ 'This account needs notification access. Run `{{command}}` for this account, then retry.',
+ { command: managedScopes.command },
+ ),
+ );
+ }
+
+ const newAccountUUID = getAccountUUID(newAccount);
+ const accounts = get().accounts;
const replacesAccount = (account: Account) => {
if (isCliAccount) {
return (
- account.forge === forge && account.hostname === hostname && account.method === method
+ account.forge === forge &&
+ account.hostname === hostname &&
+ account.method === method &&
+ sharesCliIdentity(account, newAccount)
);
}
if (adapter.getOrigin) {
@@ -145,6 +192,25 @@ const useAccountsStore = create()(
refreshAccount: async (account: Account): Promise => {
const refreshed = await refreshAccount(account);
+
+ const { cliAuth } = getAdapter(refreshed.forge);
+ if (refreshed.method === cliAuth?.authMethod && !refreshed.cliIdentity && refreshed.user) {
+ try {
+ refreshed.cliIdentity = await cliAuth.identify?.(
+ refreshed.hostname,
+ refreshed.user.login,
+ );
+ } catch (err) {
+ // Leave the account on the legacy active-account path; its normal
+ // authentication error surface still applies.
+ rendererLogError(
+ 'refreshAccount',
+ `failed to pin CLI identity for ${refreshed.hostname}`,
+ toError(err),
+ );
+ }
+ }
+
const refreshedUUID = getAccountUUID(refreshed);
// Persist the refreshed account details
diff --git a/src/renderer/types.ts b/src/renderer/types.ts
index 2fb4c5d4e..be03d1dec 100644
--- a/src/renderer/types.ts
+++ b/src/renderer/types.ts
@@ -3,7 +3,7 @@ import type { FC } from 'react';
import type { Icon, OcticonProps } from '@primer/octicons-react';
import type { Button } from '@primer/react';
-import type { AutomaticUpdates, TrayIconAppearance } from '../shared/events';
+import type { AutomaticUpdates, GitHubCliIdentity, TrayIconAppearance } from '../shared/events';
// Derived from public @primer/react component props rather than internal types
export type VariantType = NonNullable['variant']>;
@@ -77,6 +77,12 @@ export interface Account {
clientId?: ClientID;
/** Atlassian account email — required for Bitbucket Basic Auth (email:token). */
username?: string;
+ /**
+ * Identity this GitHub CLI account is pinned to. Absent for accounts created
+ * before identities were recorded (and for non-CLI methods); those resolve
+ * whichever account the CLI currently treats as active.
+ */
+ cliIdentity?: GitHubCliIdentity;
user: GitifyUser | null;
scopes?: string[];
}
diff --git a/src/renderer/utils/auth/identity.ts b/src/renderer/utils/auth/identity.ts
index 1f4a89aae..e04a9e121 100644
--- a/src/renderer/utils/auth/identity.ts
+++ b/src/renderer/utils/auth/identity.ts
@@ -1,5 +1,35 @@
+import type { GitHubCliIdentity } from '../../../shared/events';
+import { isValidGitHubCliLogin } from '../../../shared/githubCli';
+
import type { Account, AccountUUID } from '../../types';
+/**
+ * Validate a CLI identity loaded from persisted state.
+ *
+ * Persisted JSON is untrusted, and a login reaches `gh` arguments through the
+ * bridge, so unknown kinds and malformed logins are dropped rather than kept.
+ *
+ * @param value - Candidate identity from persisted account state.
+ * @returns The identity when it is well formed, otherwise `undefined`.
+ */
+export function sanitizeCliIdentity(value: unknown): GitHubCliIdentity | undefined {
+ if (typeof value !== 'object' || value === null) {
+ return undefined;
+ }
+
+ const candidate = value as { kind?: unknown; login?: unknown };
+
+ if (candidate.kind === 'environment') {
+ return { kind: 'environment' };
+ }
+
+ if (candidate.kind === 'account' && isValidGitHubCliLogin(candidate.login)) {
+ return { kind: 'account', login: candidate.login };
+ }
+
+ return undefined;
+}
+
/**
* Return true if `hostname` is a valid DNS hostname (e.g. `github.com`).
* Accepts hostnames with 2-6 character TLDs; rejects IP addresses and bare labels.
diff --git a/src/renderer/utils/forges/github/adapter.test.ts b/src/renderer/utils/forges/github/adapter.test.ts
index 6cea6e666..b7ce90240 100644
--- a/src/renderer/utils/forges/github/adapter.test.ts
+++ b/src/renderer/utils/forges/github/adapter.test.ts
@@ -48,6 +48,13 @@ describe('renderer/utils/forges/github/adapter.ts', () => {
expect(githubAdapter.defaultHostname).toBe('github.com');
});
+ it('exposes identity-aware CLI support', () => {
+ expect(githubAdapter.cliAuth).toMatchObject({ authMethod: 'GitHub CLI' });
+ expect(githubAdapter.cliAuth?.listAccounts).toBeTypeOf('function');
+ expect(githubAdapter.cliAuth?.resolveToken).toBeTypeOf('function');
+ expect(githubAdapter.cliAuth?.identify).toBeTypeOf('function');
+ });
+
it('validates a 40-character token', () => {
expect(githubAdapter.validateToken('a'.repeat(40) as Token)).toBe(true);
expect(githubAdapter.validateToken('short' as Token)).toBe(false);
diff --git a/src/renderer/utils/forges/github/adapter.ts b/src/renderer/utils/forges/github/adapter.ts
index 99c3ed7d8..741b7f2f4 100644
--- a/src/renderer/utils/forges/github/adapter.ts
+++ b/src/renderer/utils/forges/github/adapter.ts
@@ -17,7 +17,12 @@ import {
isValidToken,
} from './auth';
import { githubCapabilities } from './capabilities';
-import { forgetGitHubCliToken, resolveGitHubCliToken } from './cli';
+import {
+ forgetGitHubCliTokens,
+ identifyGitHubCliIdentity,
+ listGitHubCliAccounts,
+ resolveGitHubCliToken,
+} from './cli';
import {
fetchAuthenticatedUserDetails,
ignoreNotificationThreadSubscription,
@@ -37,7 +42,7 @@ async function fetchAuthenticatedUser(account: Account): Promise {
clearOctokitClientCacheForAccount(account);
- forgetGitHubCliToken(account.hostname);
+ forgetGitHubCliTokens(account.hostname);
},
listNotifications,
markThreadAsRead: async (account, threadId) => {
diff --git a/src/renderer/utils/forges/github/cli.test.ts b/src/renderer/utils/forges/github/cli.test.ts
index 03db1687a..d87d990b8 100644
--- a/src/renderer/utils/forges/github/cli.test.ts
+++ b/src/renderer/utils/forges/github/cli.test.ts
@@ -1,18 +1,26 @@
import type { Hostname } from '../../../types';
import * as comms from '../../system/comms';
-import { forgetGitHubCliToken, resolveGitHubCliToken } from './cli';
+import {
+ forgetGitHubCliToken,
+ forgetGitHubCliTokens,
+ identifyGitHubCliIdentity,
+ listGitHubCliAccounts,
+ resolveGitHubCliToken,
+} from './cli';
const GITHUB = 'github.com' as Hostname;
const ENTERPRISE = 'github.example.com' as Hostname;
describe('renderer/utils/forges/github/cli.ts', () => {
const readToken = vi.spyOn(comms, 'readGitHubCliToken');
+ const readAccounts = vi.spyOn(comms, 'listGitHubCliAccounts');
beforeEach(() => {
- forgetGitHubCliToken(GITHUB);
- forgetGitHubCliToken(ENTERPRISE);
+ forgetGitHubCliTokens(GITHUB);
+ forgetGitHubCliTokens(ENTERPRISE);
readToken.mockReset();
+ readAccounts.mockReset();
});
it('collapses concurrent resolutions onto one CLI read', async () => {
@@ -55,8 +63,8 @@ describe('renderer/utils/forges/github/cli.ts', () => {
});
it('resolves each host against its own CLI entry', async () => {
- readToken.mockImplementation(async (hostname) =>
- hostname === GITHUB ? { token: 'gho_cloud' } : { token: 'gho_enterprise' },
+ readToken.mockImplementation(async (request) =>
+ request.hostname === GITHUB ? { token: 'gho_cloud' } : { token: 'gho_enterprise' },
);
await expect(resolveGitHubCliToken(GITHUB)).resolves.toBe('gho_cloud');
@@ -121,4 +129,104 @@ describe('renderer/utils/forges/github/cli.ts', () => {
'GitHub CLI could not provide a token for github.com: keyring is locked',
);
});
+
+ it('names the pinned account when its credential is gone', async () => {
+ readToken.mockResolvedValue({ error: 'GH_NOT_AUTHENTICATED' });
+
+ await expect(
+ resolveGitHubCliToken(GITHUB, { kind: 'account', login: 'alice' }),
+ ).rejects.toThrow(
+ 'GitHub CLI has no token for github.com account alice. Run `gh auth login --hostname github.com` and try again.',
+ );
+ });
+
+ it('resolves different identities on one host separately', async () => {
+ readToken.mockImplementation(async ({ identity }) => ({
+ token: identity?.kind === 'account' ? `gho_${identity.login}` : 'gho_active',
+ }));
+
+ const [alice, bob] = await Promise.all([
+ resolveGitHubCliToken(GITHUB, { kind: 'account', login: 'alice' }),
+ resolveGitHubCliToken(GITHUB, { kind: 'account', login: 'bob' }),
+ ]);
+
+ expect([alice, bob]).toEqual(['gho_alice', 'gho_bob']);
+ expect(readToken).toHaveBeenCalledTimes(2);
+ });
+
+ it('collapses concurrent reads for one identity onto one CLI call', async () => {
+ readToken.mockResolvedValue({ token: 'gho_alice' });
+ const identity = { kind: 'account', login: 'alice' } as const;
+
+ await Promise.all([
+ resolveGitHubCliToken(GITHUB, identity),
+ resolveGitHubCliToken(GITHUB, identity),
+ ]);
+
+ expect(readToken).toHaveBeenCalledTimes(1);
+ });
+
+ it('forgets one identity without disturbing another', async () => {
+ readToken.mockImplementation(async ({ identity }) => ({
+ token: identity?.kind === 'account' ? `gho_${identity.login}_second` : 'gho_active',
+ }));
+
+ await resolveGitHubCliToken(GITHUB, { kind: 'account', login: 'alice' });
+ await resolveGitHubCliToken(GITHUB, { kind: 'account', login: 'bob' });
+ forgetGitHubCliToken(GITHUB, { kind: 'account', login: 'alice' });
+ await resolveGitHubCliToken(GITHUB, { kind: 'account', login: 'bob' });
+
+ expect(readToken).toHaveBeenCalledTimes(3);
+ });
+
+ describe('listing identities', () => {
+ it('maps the CLI list onto renderer choices', async () => {
+ readAccounts.mockResolvedValue({
+ accounts: [{ identity: { kind: 'account', login: 'alice' }, active: true }],
+ });
+
+ await expect(listGitHubCliAccounts(GITHUB)).resolves.toEqual({
+ accounts: [{ identity: { kind: 'account', login: 'alice' }, active: true }],
+ });
+ });
+
+ it('maps an unsupported CLI onto the renderer fallback code', async () => {
+ readAccounts.mockResolvedValue({ error: 'GH_ACCOUNTS_UNSUPPORTED' });
+
+ await expect(listGitHubCliAccounts(GITHUB)).resolves.toEqual({
+ error: 'CLI_UNSUPPORTED',
+ detail: undefined,
+ });
+ });
+
+ it('identifies a stored login ignoring case', async () => {
+ readAccounts.mockResolvedValue({
+ accounts: [
+ { identity: { kind: 'account', login: 'Alice' }, active: false },
+ { identity: { kind: 'environment' }, active: true },
+ ],
+ });
+
+ await expect(identifyGitHubCliIdentity(GITHUB, 'alice')).resolves.toEqual({
+ kind: 'account',
+ login: 'Alice',
+ });
+ });
+
+ it('falls back to the environment identity when no stored login matches', async () => {
+ readAccounts.mockResolvedValue({
+ accounts: [{ identity: { kind: 'environment' }, active: true }],
+ });
+
+ await expect(identifyGitHubCliIdentity(GITHUB, 'alice')).resolves.toEqual({
+ kind: 'environment',
+ });
+ });
+
+ it('leaves the account unpinned when the CLI cannot be read', async () => {
+ readAccounts.mockResolvedValue({ error: 'GH_FAILED', detail: 'keyring is locked' });
+
+ await expect(identifyGitHubCliIdentity(GITHUB, 'alice')).resolves.toBeUndefined();
+ });
+ });
});
diff --git a/src/renderer/utils/forges/github/cli.ts b/src/renderer/utils/forges/github/cli.ts
index bbd059781..6a99b6b54 100644
--- a/src/renderer/utils/forges/github/cli.ts
+++ b/src/renderer/utils/forges/github/cli.ts
@@ -1,62 +1,158 @@
-import type { GitHubCliTokenError } from '../../../../shared/events';
+import type {
+ GitHubCliAccountsError,
+ GitHubCliIdentity,
+ GitHubCliTokenError,
+} from '../../../../shared/events';
import type { Hostname, Token } from '../../../types';
+import type { CliAccountsError, CliAccountsResult } from '../types';
-import { readGitHubCliToken } from '../../system/comms';
+import { listGitHubCliAccounts as readCliAccounts, readGitHubCliToken } from '../../system/comms';
/**
- * Concurrent CLI reads share one promise per host. Settled reads are removed
- * so the next request observes credential changes in the CLI.
+ * Concurrent CLI reads share one promise per host and identity. Settled reads
+ * are removed so the next request observes credential changes in the CLI.
*/
-const cliTokens = new Map>();
+const cliTokens = new Map>();
+
+const ACCOUNTS_ERROR: Record = {
+ GH_NOT_FOUND: 'CLI_NOT_FOUND',
+ GH_NOT_AUTHENTICATED: 'CLI_NOT_AUTHENTICATED',
+ GH_ACCOUNTS_UNSUPPORTED: 'CLI_UNSUPPORTED',
+ GH_TIMED_OUT: 'CLI_TIMED_OUT',
+ GH_FAILED: 'CLI_FAILED',
+};
/**
- * Resolve the GitHub CLI token for `hostname`.
+ * Resolve the GitHub CLI token for `hostname`, optionally for a specific
+ * identity. Resolving by identity reads that account's credential without
+ * changing which account the CLI treats as active.
*
* @param hostname - Host to resolve the token for.
- * @returns The token the CLI holds for that host.
- * @throws If the CLI is missing, not logged in to the host, or failed.
+ * @param identity - Identity to address; omitted for the CLI's active account.
+ * @returns The token the CLI holds for that host and identity.
+ * @throws If the CLI is missing, not logged in, or failed.
*/
-export function resolveGitHubCliToken(hostname: Hostname): Promise {
- const inFlight = cliTokens.get(hostname);
+export function resolveGitHubCliToken(
+ hostname: Hostname,
+ identity?: GitHubCliIdentity,
+): Promise {
+ const key = cacheKey(hostname, identity);
+ const inFlight = cliTokens.get(key);
if (inFlight) {
return inFlight;
}
- const read = readCliToken(hostname).finally(() => {
- if (cliTokens.get(hostname) === read) {
- cliTokens.delete(hostname);
+ const read = readCliToken(hostname, identity).finally(() => {
+ if (cliTokens.get(key) === read) {
+ cliTokens.delete(key);
}
});
- cliTokens.set(hostname, read);
+ cliTokens.set(key, read);
return read;
}
-export function forgetGitHubCliToken(hostname: Hostname): void {
- cliTokens.delete(hostname);
+/**
+ * Forget the cached credential for one host and identity, so the next request
+ * re-reads the CLI.
+ */
+export function forgetGitHubCliToken(hostname: Hostname, identity?: GitHubCliIdentity): void {
+ cliTokens.delete(cacheKey(hostname, identity));
}
-async function readCliToken(hostname: Hostname): Promise {
- const result = await readGitHubCliToken(hostname);
+/**
+ * Forget every cached credential for a host, across all identities. Used when
+ * an account's credential changes or the account is removed.
+ */
+export function forgetGitHubCliTokens(hostname: Hostname): void {
+ const prefix = `${hostname}\0`;
+ for (const key of cliTokens.keys()) {
+ if (key.startsWith(prefix)) {
+ cliTokens.delete(key);
+ }
+ }
+}
+
+/**
+ * List the identities the GitHub CLI holds for `hostname`.
+ *
+ * @param hostname - Host to list identities for.
+ * @returns The usable identities, or a classified failure.
+ */
+export async function listGitHubCliAccounts(hostname: Hostname): Promise {
+ const result = await readCliAccounts(hostname);
if (result.error) {
- throw new Error(describeFailure(result.error, result.detail, hostname));
+ return { error: ACCOUNTS_ERROR[result.error], detail: result.detail };
+ }
+
+ return { accounts: result.accounts };
+}
+
+/**
+ * Map a resolved GitHub login onto one of the host's CLI identities. A stored
+ * account wins over the environment credential; when the login matches
+ * neither, no identity is recorded and the account keeps using the active one.
+ */
+export async function identifyGitHubCliIdentity(
+ hostname: Hostname,
+ login: string,
+): Promise {
+ const result = await listGitHubCliAccounts(hostname);
+
+ if (result.error) {
+ return undefined;
+ }
+
+ const normalized = login.toLowerCase();
+ const stored = result.accounts.find(
+ (account) =>
+ account.identity.kind === 'account' && account.identity.login.toLowerCase() === normalized,
+ );
+
+ if (stored) {
+ return stored.identity;
+ }
+
+ return result.accounts.find((account) => account.identity.kind === 'environment')?.identity;
+}
+
+async function readCliToken(hostname: Hostname, identity?: GitHubCliIdentity): Promise {
+ const result = await readGitHubCliToken({ hostname, identity });
+
+ if (result.error) {
+ throw new Error(describeFailure(result.error, result.detail, hostname, identity));
}
return result.token as Token;
}
+function cacheKey(hostname: Hostname, identity?: GitHubCliIdentity): string {
+ return `${hostname}\0${identityKey(identity)}`;
+}
+
+function identityKey(identity?: GitHubCliIdentity): string {
+ if (!identity) {
+ return 'active';
+ }
+
+ return identity.kind === 'account' ? `account:${identity.login.toLowerCase()}` : 'environment';
+}
+
function describeFailure(
error: GitHubCliTokenError,
detail: string | undefined,
hostname: Hostname,
+ identity?: GitHubCliIdentity,
): string {
switch (error) {
case 'GH_NOT_FOUND':
return 'GitHub CLI (gh) was not found. Install it from https://cli.github.com, log in, and try again.';
case 'GH_NOT_AUTHENTICATED':
- return `GitHub CLI has no token for ${hostname}. Run \`gh auth login --hostname ${hostname}\` and try again.`;
+ return identity?.kind === 'account'
+ ? `GitHub CLI has no token for ${hostname} account ${identity.login}. Run \`gh auth login --hostname ${hostname}\` and try again.`
+ : `GitHub CLI has no token for ${hostname}. Run \`gh auth login --hostname ${hostname}\` and try again.`;
case 'GH_TIMED_OUT':
return `GitHub CLI did not respond within 10 seconds for ${hostname}. It may be waiting on a keychain prompt.`;
default:
diff --git a/src/renderer/utils/forges/github/octokit.test.ts b/src/renderer/utils/forges/github/octokit.test.ts
index 1c96a8833..601dc0554 100644
--- a/src/renderer/utils/forges/github/octokit.test.ts
+++ b/src/renderer/utils/forges/github/octokit.test.ts
@@ -203,7 +203,7 @@ describe('renderer/utils/forges/github/octokit.ts', () => {
await octokit.request('GET /user');
expect(authorizations).toEqual(['token gho_live']);
- expect(resolveSpy).toHaveBeenCalledWith(mockGitHubCliAccount.hostname);
+ expect(resolveSpy).toHaveBeenCalledWith(mockGitHubCliAccount.hostname, undefined);
expect(mockDecryptValue).not.toHaveBeenCalled();
});
@@ -221,7 +221,7 @@ describe('renderer/utils/forges/github/octokit.ts', () => {
expect(response.status).toBe(200);
expect(authorizations).toEqual(['token gho_stale', 'token gho_rotated']);
// Without this the memo would keep serving the stale token.
- expect(forgetSpy).toHaveBeenCalledWith(mockGitHubCliAccount.hostname);
+ expect(forgetSpy).toHaveBeenCalledWith(mockGitHubCliAccount.hostname, undefined);
});
it('gives up when the re-read credential is rejected too', async () => {
@@ -233,5 +233,35 @@ describe('renderer/utils/forges/github/octokit.ts', () => {
await expect(octokit.request('GET /user')).rejects.toThrow('Bad credentials');
expect(fetchMock).toHaveBeenCalledTimes(2);
});
+
+ it('resolves each pinned account with its own identity', async () => {
+ const alice = {
+ ...mockGitHubCliAccount,
+ cliIdentity: { kind: 'account' as const, login: 'alice' },
+ };
+ const bob = {
+ ...mockGitHubCliAccount,
+ cliIdentity: { kind: 'account' as const, login: 'bob' },
+ };
+ const resolveSpy = vi
+ .spyOn(cli, 'resolveGitHubCliToken')
+ .mockImplementation(
+ async (_hostname, identity) =>
+ (identity?.kind === 'account' && identity.login === 'alice'
+ ? 'gho_alice'
+ : 'gho_bob') as Token,
+ );
+ const { authorizations } = stubFetch([200, 200]);
+
+ const aliceClient = await createOctokitClientUncached(alice, 'rest');
+ const bobClient = await createOctokitClientUncached(bob, 'rest');
+
+ await aliceClient.request('GET /user');
+ await bobClient.request('GET /user');
+
+ expect(authorizations).toEqual(['token gho_alice', 'token gho_bob']);
+ expect(resolveSpy).toHaveBeenNthCalledWith(1, alice.hostname, alice.cliIdentity);
+ expect(resolveSpy).toHaveBeenNthCalledWith(2, bob.hostname, bob.cliIdentity);
+ });
});
});
diff --git a/src/renderer/utils/forges/github/octokit.ts b/src/renderer/utils/forges/github/octokit.ts
index 0fb38f995..6caf2aa48 100644
--- a/src/renderer/utils/forges/github/octokit.ts
+++ b/src/renderer/utils/forges/github/octokit.ts
@@ -108,13 +108,13 @@ export async function createOctokitClientUncached(
* this client until the account is refreshed.
*/
function authenticateFromCli(client: OctokitClient, account: Account): void {
- const { hostname } = account;
+ const { hostname, cliIdentity } = account;
const expectedUserId = account.user?.id;
let verifiedToken: Token | undefined;
client.hook.wrap('request', async (request, options) => {
const authenticatedRequest = async () => {
- const token = await resolveGitHubCliToken(hostname);
+ const token = await resolveGitHubCliToken(hostname, cliIdentity);
const headers = { ...options.headers, authorization: `token ${token}` };
if (expectedUserId && token !== verifiedToken) {
@@ -151,7 +151,7 @@ function authenticateFromCli(client: OctokitClient, account: Account): void {
throw err;
}
- forgetGitHubCliToken(hostname);
+ forgetGitHubCliToken(hostname, cliIdentity);
return await authenticatedRequest();
}
diff --git a/src/renderer/utils/forges/types.ts b/src/renderer/utils/forges/types.ts
index bd7fc5362..e6cd9c38d 100644
--- a/src/renderer/utils/forges/types.ts
+++ b/src/renderer/utils/forges/types.ts
@@ -2,6 +2,8 @@ import type { FC } from 'react';
import type { OcticonProps } from '@primer/octicons-react';
+import type { GitHubCliIdentity } from '../../../shared/events';
+
import type {
Account,
ClientID,
@@ -353,6 +355,31 @@ export interface CustomOAuthAppSupport {
getNewOAuthAppUrl(hostname: Hostname): Link;
}
+/**
+ * One identity a local CLI can supply a credential for. `active` mirrors the
+ * CLI's own notion of the identity it currently treats as active.
+ */
+export interface CliAccountChoice {
+ identity: GitHubCliIdentity;
+ active: boolean;
+}
+
+/** Why a local CLI could not list its identities for a host. */
+export type CliAccountsError =
+ | 'CLI_NOT_FOUND'
+ | 'CLI_NOT_AUTHENTICATED'
+ | 'CLI_UNSUPPORTED'
+ | 'CLI_TIMED_OUT'
+ | 'CLI_FAILED';
+
+/**
+ * Result of listing a local CLI's identities for a host. An empty list is a
+ * normal answer, not an error.
+ */
+export type CliAccountsResult =
+ | { accounts: CliAccountChoice[]; error?: never; detail?: never }
+ | { accounts?: never; error: CliAccountsError; detail?: string };
+
/**
* Local-CLI credential capability bundle. Present only on forges whose
* official CLI stores a token Gitify can reuse (GitHub's `gh` today).
@@ -360,11 +387,20 @@ export interface CustomOAuthAppSupport {
export interface CliAuthSupport {
/** Auth method recorded on accounts created from the CLI's credential. */
authMethod: AuthMethod;
+ /** List the identities the CLI holds for `hostname`. */
+ listAccounts(hostname: Hostname): Promise;
/**
* Read the token the CLI holds for `hostname`.
*
+ * @param hostname - Host to read a token for.
+ * @param identity - Identity to address; omitted for the CLI's active account.
* @throws With a user-facing message when the CLI is absent, is not logged
- * in to the host, or failed.
+ * in to the host or identity, or failed.
+ */
+ resolveToken(hostname: Hostname, identity?: GitHubCliIdentity): Promise;
+ /**
+ * Map a resolved GitHub login onto one of the host's CLI identities. Used to
+ * pin accounts created before identities were recorded.
*/
- resolveToken(hostname: Hostname): Promise;
+ identify?(hostname: Hostname, login: string): Promise;
}
diff --git a/src/renderer/utils/system/comms.ts b/src/renderer/utils/system/comms.ts
index f482031c2..84b9d3771 100644
--- a/src/renderer/utils/system/comms.ts
+++ b/src/renderer/utils/system/comms.ts
@@ -1,4 +1,6 @@
import type {
+ IGitHubCliAccountsResult,
+ IGitHubCliTokenRequest,
IGitHubCliTokenResult,
ISafeStorageDecryptResult,
TrayIconAppearance,
@@ -58,11 +60,23 @@ export async function decryptValue(value: string): Promise {
- return await window.gitify.githubCliToken(hostname);
+export async function readGitHubCliToken(
+ request: IGitHubCliTokenRequest,
+): Promise {
+ return await window.gitify.githubCliToken(request);
+}
+
+/**
+ * Lists the identities the locally installed GitHub CLI holds for a host.
+ *
+ * @param hostname - The host to list identities for.
+ * @returns The usable identities, or a classified failure.
+ */
+export async function listGitHubCliAccounts(hostname: string): Promise {
+ return await window.gitify.githubCliAccounts(hostname);
}
/**
diff --git a/src/shared/events.ts b/src/shared/events.ts
index d364798e1..c7aa6b748 100644
--- a/src/shared/events.ts
+++ b/src/shared/events.ts
@@ -24,6 +24,7 @@ export const EVENTS = {
SAFE_STORAGE_ENCRYPT: `${P}safe-storage-encrypt`,
SAFE_STORAGE_DECRYPT: `${P}safe-storage-decrypt`,
GITHUB_CLI_TOKEN: `${P}github-cli-token`,
+ GITHUB_CLI_ACCOUNTS: `${P}github-cli-accounts`,
NOTIFICATION_SOUND_PATH: `${P}notification-sound-path`,
OPEN_EXTERNAL: `${P}open-external`,
RESET_APP: `${P}reset-app`,
@@ -127,6 +128,47 @@ export type IGitHubCliTokenResult =
| { token: string; error?: never; detail?: never }
| { token?: never; error: GitHubCliTokenError; detail?: string };
+/**
+ * An identity the GitHub CLI can resolve a credential for: a stored account
+ * addressed by login, or the credential supplied through the CLI's environment.
+ */
+export type GitHubCliIdentity = { kind: 'account'; login: string } | { kind: 'environment' };
+
+/**
+ * One identity the GitHub CLI reports for a host. `active` mirrors the CLI's
+ * own notion of the account it currently treats as active.
+ */
+export interface IGitHubCliAccount {
+ identity: GitHubCliIdentity;
+ active: boolean;
+}
+
+/** Why the GitHub CLI could not list its identities for a host. */
+export type GitHubCliAccountsError =
+ | 'GH_NOT_FOUND'
+ | 'GH_NOT_AUTHENTICATED'
+ | 'GH_ACCOUNTS_UNSUPPORTED'
+ | 'GH_TIMED_OUT'
+ | 'GH_FAILED';
+
+/**
+ * Result of listing the identities the GitHub CLI holds for a host. An empty
+ * list is a normal answer, not an error; `detail` carries the CLI's own first
+ * line of stderr when it has one.
+ */
+export type IGitHubCliAccountsResult =
+ | { accounts: IGitHubCliAccount[]; error?: never; detail?: never }
+ | { accounts?: never; error: GitHubCliAccountsError; detail?: string };
+
+/**
+ * Request for one of the GitHub CLI's credentials. Omitting `identity` asks for
+ * the CLI's active account, which is how pre-pinning accounts keep working.
+ */
+export interface IGitHubCliTokenRequest {
+ hostname: string;
+ identity?: GitHubCliIdentity;
+}
+
/** A structured request to publish an operating-system notification. */
export interface INativeNotificationPayload {
/** Short, opaque identity for this notification. */
@@ -205,9 +247,13 @@ export type EventContracts = AssertEventCoverage<{
response: ISafeStorageDecryptResult;
};
[EVENTS.GITHUB_CLI_TOKEN]: {
- request: string;
+ request: IGitHubCliTokenRequest;
response: IGitHubCliTokenResult;
};
+ [EVENTS.GITHUB_CLI_ACCOUNTS]: {
+ request: string;
+ response: IGitHubCliAccountsResult;
+ };
[EVENTS.NOTIFICATION_SOUND_PATH]: { request: undefined; response: string };
[EVENTS.OPEN_EXTERNAL]: { request: IOpenExternal; response: undefined };
[EVENTS.RESET_APP]: { request: undefined; response: undefined };
diff --git a/src/shared/githubCli.ts b/src/shared/githubCli.ts
new file mode 100644
index 000000000..d530138a0
--- /dev/null
+++ b/src/shared/githubCli.ts
@@ -0,0 +1,6 @@
+/** GitHub logins are up to 39 characters, including the `_shortcode` on managed accounts. */
+const LOGIN_PATTERN = /^[a-z0-9][a-z0-9_-]{0,38}$/i;
+
+export function isValidGitHubCliLogin(login: unknown): login is string {
+ return typeof login === 'string' && LOGIN_PATTERN.test(login);
+}