diff --git a/src/main/orca-cloud-agents/claude-setup-code.ts b/src/main/orca-cloud-agents/claude-setup-code.ts index a3a41c06f08..762fd0f70b3 100644 --- a/src/main/orca-cloud-agents/claude-setup-code.ts +++ b/src/main/orca-cloud-agents/claude-setup-code.ts @@ -2,8 +2,11 @@ // person pastes it into Orca: the bare `code#state`, or the whole callback URL copied from the address // bar. Normalized here before it is typed into the waiting `claude setup-token`; never logged or kept. -// Anthropic's codes and states are URL-safe base64 joined by '#'. -const CODE_SHAPE = /^[A-Za-z0-9_-]{8,512}(?:#[A-Za-z0-9_-]{8,512})?$/ +// Anthropic's codes and states are URL-safe base64 joined by '#'. RS-1: Claude Code (2.1.323, its +// pasted-code prompt) trims the line, splits it on '#', and refuses anything without both halves +// ("Invalid code. Please make sure the full code was copied."), so a code without its state is refused +// here, before it reaches the CLI. +const CODE_SHAPE = /^[A-Za-z0-9_-]{8,512}#[A-Za-z0-9_-]{8,512}$/ const CALLBACK_HOSTS = new Set([ 'platform.claude.com', 'console.anthropic.com', @@ -13,7 +16,8 @@ const CALLBACK_HOSTS = new Set([ /** The code the CLI expects, or null when the paste isn't one (the caller says so, without echoing it). */ export function normalizeClaudeSetupCode(raw: string): string | null { - const value = raw.trim() + // A code copied across a wrapped line keeps its pieces; URL-safe base64 has no whitespace of its own. + const value = raw.replace(/\s+/g, '') // A setup-token or API key pasted here is not a sign-in code; it never goes to the CLI's prompt. if (/^sk-ant-/i.test(value)) { return null @@ -30,10 +34,10 @@ export function normalizeClaudeSetupCode(raw: string): string | null { } const code = url.searchParams.get('code') const state = url.searchParams.get('state') - if (!code) { + if (!code || !state) { return null } - const joined = state ? `${code}#${state}` : code + const joined = `${code}#${state}` return CODE_SHAPE.test(joined) ? joined : null } return CODE_SHAPE.test(value) ? value : null diff --git a/src/main/orca-cloud-agents/claude-setup-token-real-output.test.ts b/src/main/orca-cloud-agents/claude-setup-token-real-output.test.ts new file mode 100644 index 00000000000..cacce92dd5c --- /dev/null +++ b/src/main/orca-cloud-agents/claude-setup-token-real-output.test.ts @@ -0,0 +1,151 @@ +// RS-1: `claude setup-token` output and pasted codes as Claude Code really produces them. Every fixture +// below is built from Claude Code 2.1.323's own bundled source (read from the installed CLI binary, never +// run): the success block is +// ✓ Long-lived authentication token created successfully! (Ink ) +// Your OAuth token (valid for ): (gap: 1 between rows) +// (Ink , wraps at width) +// Store this token securely. You won't be able to see it again. +// Use this token by setting: export CLAUDE_CODE_OAUTH_TOKEN= +// the sign-in link is an OSC 8 hyperlink (`assumeSupport: true`) around the dim URL text, the prompt is +// "Paste code here if prompted > ", and a pasted line is trimmed and split on '#': without both halves the +// CLI answers "Invalid code. Please make sure the full code was copied."; a code from another sign-in gets +// "That code is not from this sign-in. Paste the code shown after opening the address above."; a code the +// server refuses gets "That code wasn't accepted. It may be incomplete, expired, …". A pseudo-terminal +// ends every line with CRLF. All tokens and codes here are fake. +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + findAuthorizeUrl, + findSetupToken, + runClaudeSetupToken, + type SetupTokenProcess +} from './claude-setup-token-runner' +import { normalizeClaudeSetupCode } from './claude-setup-code' + +const TOKEN = `sk-ant-oat01-${'Zz9_-q'.repeat(16)}` +const AUTHORIZE = + 'https://claude.ai/oauth/authorize?code=true&client_id=fake&response_type=code&redirect_uri=https%3A%2F%2Fplatform.claude.com%2Foauth%2Fcode%2Fcallback&state=FAKEstate0123456789' +const ESC = '\u001b' +const green = (text: string) => `${ESC}[32m${text}${ESC}[39m` +const yellow = (text: string) => `${ESC}[33m${text}${ESC}[39m` +const dim = (text: string) => `${ESC}[2m${text}${ESC}[22m` +const osc8 = (url: string, text: string) => `${ESC}]8;;${url}${ESC}\\${text}${ESC}]8;;${ESC}\\` +const crlf = (...lines: string[]) => lines.join('\r\n') + +function successBlock(tokenRows: string[]): string { + return crlf( + '', + green('✓ Long-lived authentication token created successfully!'), + '', + 'Your OAuth token (valid for 1 year):', + '', + ...tokenRows.map(yellow), + '', + dim("Store this token securely. You won't be able to see it again."), + '', + dim('Use this token by setting: export CLAUDE_CODE_OAUTH_TOKEN='), + '' + ) +} + +describe('findSetupToken on real output (Claude Code 2.1.323)', () => { + it('reads the token from the CRLF, coloured success block, ignoring the "" hint line', () => { + expect(findSetupToken(successBlock([TOKEN]), false)).toBe(TOKEN) + }) + + it('a token Ink wrapped at the terminal width is joined, never captured cut short', () => { + for (const width of [40, 64, 80]) { + const rows = TOKEN.match(new RegExp(`.{1,${width}}`, 'g')) ?? [] + expect(rows.length).toBeGreaterThan(1) + expect(findSetupToken(successBlock(rows), false)).toBe(TOKEN) + } + }) + + it('a wrapped row padded with trailing spaces (Ink fills the line) still joins', () => { + const rows = [`${TOKEN.slice(0, 50)} `, TOKEN.slice(50)] + expect(findSetupToken(successBlock(rows), false)).toBe(TOKEN) + }) + + it('a banner before and trailing lines after never extend or replace the token', () => { + const banner = crlf(`${ESC}[?25l${ESC}[2K${ESC}[1G` + dim('Welcome to Claude Code'), '') + const after = crlf('', `${ESC}[?25h`, 'Press Enter to continue') + expect(findSetupToken(`${banner}${successBlock([TOKEN])}${after}`, false)).toBe(TOKEN) + }) +}) + +describe('findAuthorizeUrl on real output (Claude Code 2.1.323)', () => { + it('finds the link inside its OSC 8 hyperlink, with CRLF around it', () => { + const screen = crlf( + dim("Browser didn't open? Use the url below to sign in ") + 'claude.ai', + osc8(AUTHORIZE, dim(AUTHORIZE)), + '', + 'Paste code here if prompted > ' + ) + expect(findAuthorizeUrl(screen)).toBe(AUTHORIZE) + }) +}) + +describe('normalizeClaudeSetupCode on real pastes', () => { + const CODE = 'FAKEcode0123456789abcdef#FAKEstate0123456789' + it('takes the bare code#state and the full callback URL, both as code#state', () => { + expect(normalizeClaudeSetupCode(` ${CODE}\r\n`)).toBe(CODE) + expect( + normalizeClaudeSetupCode( + 'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123456789abcdef&state=FAKEstate0123456789' + ) + ).toBe(CODE) + }) + it('joins a code copied across a wrapped line', () => { + expect(normalizeClaudeSetupCode('FAKEcode0123\n456789abcdef#FAKEstate01234\r\n56789')).toBe( + CODE + ) + }) + it('refuses a code without its state (the CLI would answer "Invalid code")', () => { + expect(normalizeClaudeSetupCode('FAKEcode0123456789abcdef')).toBeNull() + expect( + normalizeClaudeSetupCode( + 'https://platform.claude.com/oauth/code/callback?code=FAKEcode0123456789abcdef' + ) + ).toBeNull() + }) +}) + +describe('runClaudeSetupToken: the CLI refusing a pasted code (Claude Code 2.1.323 wording)', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => vi.useRealTimers()) + + for (const refusal of [ + 'Invalid code. Please make sure the full code was copied.', + 'That code is not from this sign-in. Paste the code shown after opening the address above.', + "That code wasn't accepted. It may be incomplete, expired, already used, or from an earlier sign-in attempt. Sign in again to get a new code." + ]) { + it(`starts over on "${refusal.slice(0, 32)}…"`, async () => { + let onData: (chunk: string) => void = () => {} + const writes: string[] = [] + const child: SetupTokenProcess = { + onData: (listener) => { + onData = listener + }, + onExit: () => {}, + kill: () => {}, + write: (data) => void writes.push(data) + } + const submits: ((code: string) => boolean)[] = [] + const onCodeRejected = vi.fn() + const controller = new AbortController() + void runClaudeSetupToken({ + spawn: async () => child, + signal: controller.signal, + timeoutMs: 60_000, + onAcceptsCode: (submit) => void submits.push(submit), + onCodeRejected + }) + await vi.advanceTimersByTimeAsync(0) + onData(crlf(osc8(AUTHORIZE, AUTHORIZE), 'Paste code here if prompted > ')) + expect(submits[0]?.('FAKEcode0123456789abcdef#FAKEstate0123456789')).toBe(true) + await vi.advanceTimersByTimeAsync(200) + onData(crlf('', refusal, 'Paste code here if prompted > ')) + expect(onCodeRejected).toHaveBeenCalledTimes(1) + controller.abort() + }) + } +}) diff --git a/src/main/orca-cloud-agents/claude-setup-token-runner.ts b/src/main/orca-cloud-agents/claude-setup-token-runner.ts index 1cb3901a860..b6ba74c726f 100644 --- a/src/main/orca-cloud-agents/claude-setup-token-runner.ts +++ b/src/main/orca-cloud-agents/claude-setup-token-runner.ts @@ -51,15 +51,39 @@ const DENIED = /\baccess_denied\b|authorization (?:request )?(?:was )?denied|sign-?in (?:was )?denied|login (?:was )?denied/i const AUTHORIZE_HOSTS = new Set(['claude.ai', 'claude.com', 'console.anthropic.com']) const LINK = /https:\/\/[^\s"'<>]+(?=\s)/g -// The CLI's answer to a pasted code it could not exchange; it then waits for Enter to start over. -const CODE_REJECTED = /code wasn.t accepted|Invalid authorization code|OAuth error/i +// The CLI's answer to a pasted code it could not take; it then waits for Enter to start over. RS-1: the +// wording is Claude Code's own (2.1.323): an exchange the server refused ("That code wasn't accepted…"), +// a paste without both halves ("Invalid code. Please make sure the full code was copied."), and a code +// from another sign-in ("That code is not from this sign-in…"). +const CODE_REJECTED = + /code wasn.t accepted|Invalid authorization code|Invalid code\b|code is not from this sign-in|OAuth error/i // Ink reads a chunk ending in Enter as a paste; the code and the Enter go in separately. const ENTER_AFTER_CODE_MS = 150 // Long enough to read the rejection; then Enter starts a fresh sign-in (new link, new code). const RETRY_AFTER_REJECT_MS = 500 function plainText(raw: string): string { - return raw.replace(INLINE_ESCAPE, '').replace(TERMINAL_ESCAPE, '\n') + // RS-1: a pseudo-terminal ends lines with CRLF; one line break, not two (a blank line means a gap). + return raw.replace(/\r\n/g, '\n').replace(INLINE_ESCAPE, '').replace(TERMINAL_ESCAPE, '\n') +} + +// RS-1: Claude Code prints the token as one Ink , which wraps at the terminal's width (2.1.323: +// `Your OAuth token (valid for …):`, the token, then a blank line and `Store this token securely…`). +// Orca's pty is 1000 columns, so it shouldn't wrap; if it ever does, the continuation is the very next +// line and holds only token characters, while the line after the whole token is blank. Join those, so a +// wrapped token is never captured cut short. +const WRAPPED_TOKEN = /(sk-ant-oat01-[A-Za-z0-9_-]+)[ \t]*\n[ \t]*([A-Za-z0-9_-]+)[ \t]*(?=\n|$)/g + +function joinWrappedToken(plain: string): string { + let joined = plain + for (let pass = 0; pass < 8; pass += 1) { + const next = joined.replace(WRAPPED_TOKEN, '$1$2') + if (next === joined) { + return joined + } + joined = next + } + return joined } /** @@ -68,7 +92,7 @@ function plainText(raw: string): string { * a repaint never beats the whole one. Exported for tests; callers never log its result. */ export function findSetupToken(text: string, final: boolean): string | null { - const plain = plainText(text) + const plain = joinWrappedToken(plainText(text)) let found: string | null = null for (const match of plain.matchAll(TOKEN_CANDIDATE)) { const end = (match.index ?? 0) + match[0].length