Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions src/main/claude-accounts/claude-account-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,29 @@ describe('ClaudeAccountService', () => {
await expect(adding).rejects.toThrow('cancelled')
})

it('opens the link of a WSL sign-in through the desktop opener', async () => {
const LINK =
'https://claude.com/cai/oauth/authorize?redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fcallback'
const f = fixture()
const opened: string[] = []
f.service.setWslSignInLinkOpener((link) => opened.push(link))
f.runtimeAuth.prepareAccountFolder.mockImplementation(async (id: string) => {
mkdirSync(f.home(id), { recursive: true })
return { configDir: `/home/u/claude-profiles/${id}/home`, readPath: f.home(id) }
})
f.runLogin.mockImplementationOnce(async (_args, config, _timeoutMs, options) => {
expect(options?.browser).toBe(
`/home/u/claude-profiles/${newId(f)}/home/.orca-sign-in-browser`
)
writeFileSync(join(config.windowsPath, '.orca-sign-in-browser.link'), LINK)
await vi.waitFor(() => expect(opened).toEqual([LINK]))
f.signIn(newId(f), 'wsl@example.test')
return ''
})
await f.service.addAccount({ runtime: 'wsl', wslDistro: 'Ubuntu' })
expect(opened).toEqual([LINK])
})

it('runs a WSL login against the guest folder', async () => {
const f = fixture()
f.runtimeAuth.prepareAccountFolder.mockImplementation(async (id: string) => {
Expand Down
142 changes: 142 additions & 0 deletions src/main/claude-accounts/claude-login-session.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process'
import { runClaudeLoginSession } from './claude-login-session'

const LINK =
'https://claude.com/cai/oauth/authorize?code=true&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fcallback&state=s'
const LINUX_HOME = '/home/u/claude-profiles/a/home'
const roots: string[] = []
type RunCommand = (
args: string[],
config: ClaudeCommandConfig,
timeoutMs: number,
options?: ClaudeCommandOptions
) => Promise<string>
afterEach(() => roots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })))

function folder(runtime: 'wsl' | 'host'): ClaudeCommandConfig {
const windowsPath = mkdtempSync(join(tmpdir(), 'claude-login-session-'))
roots.push(windowsPath)
return runtime === 'wsl'
? { windowsPath, linuxPath: LINUX_HOME, wslDistro: 'Ubuntu' }
: { windowsPath, linuxPath: null, wslDistro: null }
}

// Stands in for Claude running BROWSER with `link`, then finishing once `done` says so.
function claudeHandsOver(config: ClaudeCommandConfig, link: string, done: () => boolean) {
return vi.fn<RunCommand>(async () => {
writeFileSync(join(config.windowsPath, '.orca-sign-in-browser.link'), link)
await vi.waitFor(() => expect(done()).toBe(true))
return ''
})
}

describe('runClaudeLoginSession', () => {
it('opens a WSL login link on this computer and cleans up the stand-in', async () => {
const config = folder('wsl')
const openWslSignInLink = vi.fn()
const runCommand = claudeHandsOver(config, LINK, () => openWslSignInLink.mock.calls.length > 0)
await runClaudeLoginSession(config, { runCommand, setCancel: vi.fn(), openWslSignInLink })
expect(runCommand.mock.calls[0][3]).toMatchObject({
browser: `${LINUX_HOME}/.orca-sign-in-browser`
})
expect(openWslSignInLink).toHaveBeenCalledExactlyOnceWith(LINK)
expect(readdirSync(config.windowsPath)).toEqual([])
})

it('copies rather than opens a WSL link when the user asked for Copy link', async () => {
const config = folder('wsl')
const openWslSignInLink = vi.fn()
const onLink = vi.fn()
const runCommand = claudeHandsOver(config, LINK, () => onLink.mock.calls.length > 0)
await runClaudeLoginSession(
config,
{ runCommand, setCancel: vi.fn(), openWslSignInLink },
onLink
)
expect(onLink).toHaveBeenCalledExactlyOnceWith(LINK)
expect(openWslSignInLink).not.toHaveBeenCalled()
})

it('leaves a local login to open its own browser', async () => {
const config = folder('host')
const openWslSignInLink = vi.fn()
const runCommand = vi.fn<RunCommand>(async (_args, _config, _ms, options) => {
expect(options?.browser).toBeUndefined()
expect(existsSync(join(config.windowsPath, '.orca-sign-in-browser'))).toBe(false)
return ''
})
await runClaudeLoginSession(config, { runCommand, setCancel: vi.fn(), openWslSignInLink })
expect(runCommand).toHaveBeenCalledTimes(1)
expect(openWslSignInLink).not.toHaveBeenCalled()
})

it('changes nothing for a WSL login where nothing can open a link', async () => {
const config = folder('wsl')
const runCommand = vi.fn<RunCommand>(async () => '')
await runClaudeLoginSession(config, { runCommand, setCancel: vi.fn() })
expect(runCommand.mock.calls[0]).toEqual([
['auth', 'login', '--claudeai'],
config,
expect.any(Number),
expect.objectContaining({ browser: undefined })
])
})

it('never opens a link that is not a Claude sign-in, and keeps the login going', async () => {
const config = folder('wsl')
const openWslSignInLink = vi.fn()
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const runCommand = claudeHandsOver(config, 'http://claude.com/oauth', () =>
warn.mock.calls.some(([message]) => String(message).includes('unexpected sign-in link'))
)
await expect(
runClaudeLoginSession(config, { runCommand, setCancel: vi.fn(), openWslSignInLink })
).resolves.toBeUndefined()
expect(openWslSignInLink).not.toHaveBeenCalled()
warn.mockRestore()
})

it('never opens a link for a WSL login the user already cancelled', async () => {
const config = folder('wsl')
const openWslSignInLink = vi.fn()
let cancel: (() => boolean) | null = null
const runCommand = vi.fn<RunCommand>(async (_args, _config, _ms, options) => {
// Claude writes its link as the cancel lands.
writeFileSync(join(config.windowsPath, '.orca-sign-in-browser.link'), LINK)
expect(cancel?.()).toBe(true)
expect(options?.signal?.aborted).toBe(true)
// Give the link watcher its chance to read the file.
await new Promise((resolve) => setTimeout(resolve, 300))
throw new Error('Claude sign-in was cancelled.')
})
await expect(
runClaudeLoginSession(config, {
runCommand,
setCancel: (next) => {
cancel ??= next
},
openWslSignInLink
})
).rejects.toThrow('cancelled')
expect(openWslSignInLink).not.toHaveBeenCalled()
})

it('runs a WSL login unchanged when the stand-in cannot be written', async () => {
const config = { ...folder('wsl'), windowsPath: join(tmpdir(), 'missing-claude-folder', 'x') }
const openWslSignInLink = vi.fn()
const runCommand = vi.fn<RunCommand>(async () => '')
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
await runClaudeLoginSession(config, { runCommand, setCancel: vi.fn(), openWslSignInLink })
warn.mockRestore()
expect(runCommand.mock.calls[0]).toEqual([
['auth', 'login', '--claudeai'],
config,
expect.any(Number),
expect.objectContaining({ browser: undefined })
])
})
})
45 changes: 40 additions & 5 deletions src/main/claude-accounts/claude-login-session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CLAUDE_SIGN_IN_FAILED_MESSAGE } from '../../shared/claude-sign-in-link'
import type { ClaudeCommandConfig, ClaudeCommandOptions } from './claude-command-process'
import { prepareClaudeSignInBrowser } from './claude-sign-in-browser'
import { prepareClaudeSignInBrowser, type ClaudeSignInBrowser } from './claude-sign-in-browser'

// Why 10 minutes: copying the link into a private window takes longer than one click.
const LOGIN_TIMEOUT_MS = 600_000
Expand All @@ -13,6 +13,8 @@ type ClaudeLoginSessionDependencies = {
options?: ClaudeCommandOptions
) => Promise<string>
setCancel: (cancel: (() => boolean) | null) => void
/** Opens a WSL login's sign-in link on this computer; absent where Orca cannot open one. */
openWslSignInLink?: ((signInLink: string) => void) | null
}

/** Runs a hidden `claude auth login` that writes its login straight into the account's folder.
Expand All @@ -33,14 +35,36 @@ export async function runClaudeLoginSession(
return true
})
try {
// Why: stock distros have no xdg-open, wslview or BROWSER, so Claude in WSL opens nothing.
const openLink =
!onLink && folder.linuxPath !== null && folder.wslDistro !== null
? (dependencies.openWslSignInLink ?? undefined)
: undefined
// Why: if setup fails this throws; falling back would let Claude open the browser the user avoided.
const browser = onLink ? await prepareClaudeSignInBrowser(folder) : null
void browser?.nextLink(watch.signal).then((signInLink) => {
const browser = onLink
? await prepareClaudeSignInBrowser(folder)
: openLink
? await prepareOpenerBrowser(folder)
: null
const deliverLink = onLink ?? openLink
// Why both signals: a cancelled login must not open a tab for a link Claude wrote as it died.
const stopped = AbortSignal.any([watch.signal, controller.signal])
// Why the full login window: auto-open never ends the login, and a cold distro can be slow.
const waitMs = onLink ? undefined : LOGIN_TIMEOUT_MS
void browser?.nextLink(stopped, waitMs).then((signInLink) => {
if (stopped.aborted) {
return
}
if (signInLink) {
onLink?.(signInLink)
} else if (!watch.signal.aborted) {
deliverLink?.(signInLink)
return
}
if (onLink) {
linkMissing = true
controller.abort()
} else {
// Why not end it: the login stays cancellable and Copy link remains the fallback.
console.warn('[claude-accounts] Claude handed over no WSL sign-in link to open.')
}
})
try {
Expand All @@ -61,3 +85,14 @@ export async function runClaudeLoginSession(
dependencies.setCancel(null)
}
}

// Why null on failure: an auto-open that cannot be set up leaves the login as it was before.
async function prepareOpenerBrowser(
folder: ClaudeCommandConfig
): Promise<ClaudeSignInBrowser | null> {
try {
return await prepareClaudeSignInBrowser(folder)
} catch {
return null
}
}
12 changes: 8 additions & 4 deletions src/main/claude-accounts/claude-sign-in-browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export type ClaudeSignInBrowser = {
/** BROWSER as the Claude process sees it. */
path: string
/** The localhost-callback link Claude handed BROWSER; null if stopped, late, or not one. */
nextLink: (signal: AbortSignal) => Promise<string | null>
nextLink: (signal: AbortSignal, waitMs?: number) => Promise<string | null>
dispose: () => Promise<void>
}

Expand Down Expand Up @@ -67,13 +67,17 @@ export async function prepareClaudeSignInBrowser(
}
return {
path: isWsl && folder.linuxPath ? posix.join(folder.linuxPath, HELPER_NAME) : helperPath,
nextLink: (signal) => pollForLink(linkPath, signal),
nextLink: (signal, waitMs = LINK_WAIT_MS) => pollForLink(linkPath, signal, waitMs),
dispose
}
}

async function pollForLink(linkPath: string, signal: AbortSignal): Promise<string | null> {
const deadline = Date.now() + LINK_WAIT_MS
async function pollForLink(
linkPath: string,
signal: AbortSignal,
waitMs: number
): Promise<string | null> {
const deadline = Date.now() + waitMs
while (!signal.aborted && Date.now() < deadline) {
const signInLink = await readFile(linkPath, 'utf8').then(
(text) => text.trim(),
Expand Down
9 changes: 8 additions & 1 deletion src/main/claude-accounts/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export class ClaudeAccountService {
private mutationQueue: Promise<unknown> = Promise.resolve()
private cancelPendingClaudeLogin: (() => boolean) | null = null
private pendingSignInLink: Promise<string | null> | null = null
private openWslSignInLink: ((signInLink: string) => void) | null = null
private readonly selection: ClaudeAccountSelection
private readonly registration: ClaudeAccountRegistration

Expand Down Expand Up @@ -66,6 +67,11 @@ export class ClaudeAccountService {
return this.cancelPendingClaudeLogin?.() ?? false
}

/** Lets the desktop open a WSL sign-in's link; orcad never sets one. */
setWslSignInLinkOpener(opener: ((signInLink: string) => void) | null): void {
this.openWslSignInLink = opener
}

beginSignIn(request: ClaudeSignInRequest = {}): Promise<ClaudeAccountSignIn> {
return this.serializeMutation(() => this.registration.begin(request))
}
Expand Down Expand Up @@ -120,7 +126,8 @@ export class ClaudeAccountService {
runCommand: this.runLoginCommand,
setCancel: (cancel) => {
this.cancelPendingClaudeLogin = cancel
}
},
openWslSignInLink: this.openWslSignInLink
},
signInLink?.resolve
)
Expand Down
10 changes: 10 additions & 0 deletions src/main/codex-accounts/codex-login-auth-url.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import { stripAnsiEscapeSequences } from '../../shared/ansi-escape-sequences'

const AUTH_URL_MARKER = 'navigate to this url to authenticate:'
const CODEX_AUTH_HOST = 'auth.openai.com'

/** OpenAI's sign-in page, the only link Orca opens for a codex login. */
export function isCodexLoginAuthUrl(authUrl: string): boolean {
try {
return new URL(authUrl).hostname === CODEX_AUTH_HOST
} catch {
return false
}
}

/**
* The browser sign-in link `codex login` prints, or null while its output has
Expand Down
Loading
Loading