diff --git a/runners/agent-runner/src/claude-query-runner.ts b/runners/agent-runner/src/claude-query-runner.ts index b1cbc0c..6aa0dc4 100644 --- a/runners/agent-runner/src/claude-query-runner.ts +++ b/runners/agent-runner/src/claude-query-runner.ts @@ -33,6 +33,7 @@ import { } from './reply-language-guard.js'; import { buildClaudeReadonlySandboxSettings } from './reviewer-runtime.js'; import { + createCredentialsGuardHook, createPreCompactHook, createReviewerBashGuardHook, createSanitizeBashHook, @@ -272,8 +273,12 @@ class ClaudeQueryRunner { { matcher: 'Bash', hooks: readonlyReviewerRuntime - ? [createReviewerBashGuardHook(), createSanitizeBashHook()] - : [createSanitizeBashHook()], + ? [ + createCredentialsGuardHook(), + createReviewerBashGuardHook(), + createSanitizeBashHook(), + ] + : [createCredentialsGuardHook(), createSanitizeBashHook()], }, ], }, diff --git a/runners/agent-runner/src/runner-hooks.ts b/runners/agent-runner/src/runner-hooks.ts index accc8ba..17c2875 100644 --- a/runners/agent-runner/src/runner-hooks.ts +++ b/runners/agent-runner/src/runner-hooks.ts @@ -284,6 +284,43 @@ export function createSanitizeBashHook(): HookCallback { }; } +const CREDENTIALS_FILE_PATTERN = /\.credentials\.json/; +const CREDENTIALS_COPY_PATTERN = + /(?:^|[\s;&|(`])(?:cp|mv|ln|rsync|scp|install|tee)\s|copyFile|writeFileSync|>\s*\S*\.credentials\.json/; + +/** + * A copy of the Claude OAuth credentials carries the refresh token. A Claude + * CLI run against that copy (a "harmless" test) refreshes it, which rotates + * the token family and revokes the token EJClaw and every room use: all rooms + * fail with "401 OAuth access token has been revoked" until a manual re-login + * (2026-11-02). Reading the file stays allowed; copying or writing one is not. + */ +export function isClaudeCredentialsCopyCommand(command: string): boolean { + return ( + CREDENTIALS_FILE_PATTERN.test(command) && + CREDENTIALS_COPY_PATTERN.test(command) + ); +} + +export function createCredentialsGuardHook(): HookCallback { + return async (input, _toolUseId, _context) => { + const preInput = input as PreToolUseHookInput; + const command = (preInput.tool_input as { command?: string })?.command; + if (!command || !isClaudeCredentialsCopyCommand(command)) return {}; + return { + hookSpecificOutput: { + hookEventName: 'PreToolUse', + permissionDecision: 'deny', + permissionDecisionReason: + 'EJClaw blocks copying or writing Claude .credentials.json files: a ' + + 'Claude CLI using a copy refreshes the shared login and logs out every ' + + 'room. Test with fake tokens in a fresh dir instead, and never give a ' + + 'test the real refresh token.', + }, + }; + }; +} + export function createReviewerBashGuardHook(): HookCallback { return async (input, _toolUseId, _context) => { const preInput = input as PreToolUseHookInput; diff --git a/runners/agent-runner/test/credentials-guard.test.ts b/runners/agent-runner/test/credentials-guard.test.ts new file mode 100644 index 0000000..382dba6 --- /dev/null +++ b/runners/agent-runner/test/credentials-guard.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; + +import { + createCredentialsGuardHook, + isClaudeCredentialsCopyCommand, +} from '../src/runner-hooks.js'; + +describe('isClaudeCredentialsCopyCommand', () => { + it('blocks the 2026-11-02 test commands that copied the real login', () => { + expect( + isClaudeCredentialsCopyCommand( + 'mkdir -p oauthtest/a && cp /home/claude/EJClaw/data/claude/.credentials.json oauthtest/a/.credentials.json', + ), + ).toBe(true); + expect( + isClaudeCredentialsCopyCommand( + `bun -e 'const c=JSON.parse(fs.readFileSync("data/claude/.credentials.json","utf8")); fs.writeFileSync("b/.credentials.json",JSON.stringify(c))'`, + ), + ).toBe(true); + expect( + isClaudeCredentialsCopyCommand( + 'cat data/claude/.credentials.json > /tmp/x/.credentials.json', + ), + ).toBe(true); + }); + + it('allows reading or inspecting the credentials file', () => { + expect( + isClaudeCredentialsCopyCommand( + 'ls -la data/sessions/x/services/claude/.claude/.credentials.json', + ), + ).toBe(false); + expect( + isClaudeCredentialsCopyCommand( + `bun -e 'const a=JSON.parse(require("fs").readFileSync("data/claude/.credentials.json","utf8")); console.log(a.claudeAiOauth.expiresAt)'`, + ), + ).toBe(false); + expect(isClaudeCredentialsCopyCommand('cp a.txt b.txt')).toBe(false); + }); +}); + +describe('createCredentialsGuardHook', () => { + it('denies a copy and passes other commands through', async () => { + const hook = createCredentialsGuardHook(); + const signal = new AbortController().signal; + const denied = await hook( + { + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command: 'cp data/claude/.credentials.json /tmp/c/' }, + } as never, + undefined, + { signal }, + ); + expect(denied).toMatchObject({ + hookSpecificOutput: { permissionDecision: 'deny' }, + }); + const allowed = await hook( + { + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command: 'git status' }, + } as never, + undefined, + { signal }, + ); + expect(allowed).toEqual({}); + }); +}); diff --git a/src/agent-error-detection.test.ts b/src/agent-error-detection.test.ts index 37a0c46..152d7a3 100644 --- a/src/agent-error-detection.test.ts +++ b/src/agent-error-detection.test.ts @@ -5,6 +5,7 @@ import { classifyClaudeAuthError, classifyCodexAuthError, detectClaudeProviderFailureMessage, + isClaudeAuthError, isClaudeOrgAccessDeniedMessage, isClaudeSafetyRefusalMessage, isClaudeUsageExhaustedMessage, @@ -32,6 +33,19 @@ describe('agent-error-detection', () => { ).toBe(false); }); + it('classifies a revoked OAuth token as auth-expired', () => { + const banner = + 'Failed to authenticate. API Error: 401 OAuth access token has been revoked.'; + expect(classifyClaudeAuthError(banner).category).toBe('auth-expired'); + expect(isClaudeAuthError(banner)).toBe(true); + }); + + it('does not treat an answer that quotes the 401 banner as an auth error', () => { + const answer = + 'TASK_DONE\n\n원인 분석: 채널에서 "Failed to authenticate. API Error: 401 OAuth access token has been revoked." 오류가 반복됐습니다.'; + expect(isClaudeAuthError(answer)).toBe(false); + }); + it('detects Claude org access denied banners', () => { expect( isClaudeOrgAccessDeniedMessage( diff --git a/src/agent-error-detection.ts b/src/agent-error-detection.ts index 0f4bf53..eb83d04 100644 --- a/src/agent-error-detection.ts +++ b/src/agent-error-detection.ts @@ -16,10 +16,16 @@ const CLAUDE_HIT_LIMIT_BANNER = new RegExp( `^you(?:'ve| have) ${CLAUDE_HIT_LIMIT_PATTERN.source}`, ); +/** + * The CLI's own short auth-failure banner. Only text that starts with it + * counts: an answer that merely quotes the error (e.g. a report about a 401) + * is a real reply and must not be suppressed. + */ export function isClaudeAuthError(text: string): boolean { - const lower = text.toLowerCase(); + const lower = text.trim().toLowerCase(); + if (lower.length > 600) return false; return ( - lower.includes('failed to authenticate') && + lower.startsWith('failed to authenticate') && (lower.includes('401') || lower.includes('authentication_error')) ); } @@ -47,6 +53,7 @@ export function isClaudeAuthExpiredMessage(text: string): boolean { const looksLikeAuthFailure = normalized.startsWith('failed to authenticate'); const hasExpiredTokenMarker = normalized.includes('oauth token has expired') || + normalized.includes('has been revoked') || normalized.includes('authentication_error') || normalized.includes('obtain a new token') || normalized.includes('refresh your existing token') || @@ -375,6 +382,7 @@ export function classifyClaudeAuthError( lower.includes('authentication_error')) && (lower.includes('401') || lower.includes('unauthorized')) && (lower.includes('oauth token has expired') || + lower.includes('has been revoked') || lower.includes('obtain a new token') || lower.includes('refresh your existing token') || lower.includes('invalid authentication credentials') || diff --git a/src/group-queue.ts b/src/group-queue.ts index 2096071..bfab299 100644 --- a/src/group-queue.ts +++ b/src/group-queue.ts @@ -67,6 +67,11 @@ export class GroupQueue { this.processMessagesFn = fn; } + /** Message runs and scheduled tasks currently running, across all groups. */ + getActiveRunCount(): number { + return this.activeCount; + } + /** Notified when a group starts or finishes a run (activeCount changes). */ setOnActivityChange(fn: () => void): void { this.onActivityChange = fn; diff --git a/src/index.ts b/src/index.ts index a424b3f..57b9972 100644 --- a/src/index.ts +++ b/src/index.ts @@ -250,7 +250,9 @@ async function main(): Promise { const processStartedAtMs = Date.now(); initDatabase(); logger.info('Database initialized'); - startTokenRefreshLoop(); + startTokenRefreshLoop({ + hasActiveAgents: () => queue.getActiveRunCount() > 0, + }); runtimeState.loadState(); diff --git a/src/message-agent-executor.test.ts b/src/message-agent-executor.test.ts index 40e4617..f2209a0 100644 --- a/src/message-agent-executor.test.ts +++ b/src/message-agent-executor.test.ts @@ -192,6 +192,8 @@ vi.mock('./claude-oauth-token.js', () => ({ vi.mock('./token-refresh.js', () => ({ forceRefreshToken: vi.fn(async () => null), + isReloginRequired: vi.fn(() => false), + RELOGIN_REQUIRED_MESSAGE: 'test: claude re-login required', })); vi.mock('./sqlite-memory-store.js', () => ({ @@ -2816,6 +2818,7 @@ describe('runAgentForGroup Claude failure recovery', () => { 'test-oauth-token', ); vi.mocked(tokenRefresh.forceRefreshToken).mockResolvedValue(null); + vi.mocked(tokenRefresh.isReloginRequired).mockReturnValue(false); }); it('force-refreshes the Claude token and retries once on auth-expired', async () => { @@ -3472,6 +3475,73 @@ describe('runAgentForGroup Claude failure recovery', () => { expect(outputs).toEqual([CLAUDE_SAFETY_REFUSAL_NOTICE]); }); + it('closes the task and tells the room when the Claude login is gone', async () => { + const outputs: string[] = []; + const revoked = + 'Failed to authenticate. API Error: 401 OAuth access token has been revoked.'; + const pairedTask = { + id: 'paired-task-relogin', + chat_jid: 'group@test', + group_folder: 'test-claude', + owner_service_id: 'claude', + reviewer_service_id: 'codex-review', + title: null, + source_ref: 'HEAD', + plan_notes: null, + round_trip_count: 0, + review_requested_at: null, + status: 'active' as const, + arbiter_verdict: null, + arbiter_requested_at: null, + completion_reason: null, + created_at: '2026-04-06T00:00:00.000Z', + updated_at: '2026-04-06T00:00:00.000Z', + }; + vi.mocked( + pairedExecutionContext.preparePairedExecutionContext, + ).mockReturnValue({ task: pairedTask, workspace: null, envOverrides: {} }); + vi.mocked(db.getPairedTaskById).mockReturnValue(pairedTask); + vi.mocked(db.updatePairedTaskIfUnchanged).mockReturnValue(true); + // The forced check found the token revoked and refreshing failed. + vi.mocked(tokenRefresh.forceRefreshToken).mockImplementation(async () => { + vi.mocked(tokenRefresh.isReloginRequired).mockReturnValue(true); + return null; + }); + vi.mocked(agentRunner.runAgentProcess).mockImplementationOnce( + async (_group, _input, _onProcess, onOutput) => { + await onOutput?.({ status: 'success', result: revoked }); + return { status: 'success', result: revoked }; + }, + ); + + const result = await runAgentForGroup(makeDeps(), { + group: makeGroup(), + prompt: 'hello', + chatJid: 'group@test', + runId: 'run-relogin-required', + onOutput: async (output) => { + const text = + output.output && 'text' in output.output + ? output.output.text + : output.result; + if (typeof text === 'string') outputs.push(text); + }, + }); + + expect(result).toBe('success'); + expect(agentRunner.runAgentProcess).toHaveBeenCalledTimes(1); + expect(tokenRefresh.forceRefreshToken).toHaveBeenCalledTimes(1); + expect(db.updatePairedTaskIfUnchanged).toHaveBeenCalledWith( + 'paired-task-relogin', + '2026-04-06T00:00:00.000Z', + expect.objectContaining({ + status: 'completed', + completion_reason: 'claude_relogin_required', + }), + ); + expect(outputs).toEqual(['test: claude re-login required']); + }); + it('returns error after repeated retryable Claude session failures', async () => { vi.mocked( sessionRecovery.shouldRetryFreshSessionOnAgentFailure, diff --git a/src/message-agent-executor.ts b/src/message-agent-executor.ts index a499873..d4bd93a 100644 --- a/src/message-agent-executor.ts +++ b/src/message-agent-executor.ts @@ -34,6 +34,11 @@ import { isUsageAlignmentBypassed, } from './usage-alignment-hold.js'; import { completePairedTaskWithReason } from './paired-task-status.js'; +import { + forceRefreshToken, + isReloginRequired, + RELOGIN_REQUIRED_MESSAGE, +} from './token-refresh.js'; import { prepareMessageAgentExecutionTarget } from './message-agent-executor-target.js'; import { shouldRetryFreshSessionOnAgentFailure } from './session-recovery.js'; import { bindPairedSessionToTask } from './paired-session-binding.js'; @@ -53,6 +58,10 @@ import { /** completion_reason of a paired task closed because Claude's safeguards refused it. */ export const CLAUDE_SAFETY_REFUSAL_COMPLETION_REASON = 'claude_safety_refusal'; +/** completion_reason of a paired task closed because the Claude login is gone. */ +export const CLAUDE_RELOGIN_REQUIRED_COMPLETION_REASON = + 'claude_relogin_required'; + export const CLAUDE_SAFETY_REFUSAL_NOTICE = 'Claude 안전 필터가 이 요청을 차단해서 처리하지 못했습니다. 이 방의 Claude 세션은 초기화했습니다. 요청을 조금 바꿔서 다시 보내 주세요. 에러 원문은 붙이지 말아 주세요.'; @@ -246,6 +255,9 @@ async function reportClaudeUsageLimitToRoom( }); return true; } + if (args.reason === 'auth-expired') { + return reportClaudeReloginRequired(args); + } if (args.reason !== 'safety-refusal') return false; const task = args.pairedTaskId ? getPairedTaskById(args.pairedTaskId) @@ -266,6 +278,48 @@ async function reportClaudeUsageLimitToRoom( return true; } +/** + * A Claude run failed with a 401. The retry path has usually force-checked the + * token already; a failure after visible output has not, so check here. When + * the token is valid again, return false and let the normal retry continue. + * When the login is gone, close the task and tell the room, instead of letting + * owner/arbiter retries fail silently until someone asks why the bot stopped. + */ +async function reportClaudeReloginRequired(args: { + activeRole: PairedRoomRole; + pairedTaskId?: string; + errorText?: string | null; + pairedExecutionLifecycle: Pick< + PairedExecutionLifecycle, + 'updateSummary' | 'completeImmediately' + >; + onOutput?: (output: AgentOutput) => Promise; + log: { warn: (obj: Record, msg: string) => void }; +}): Promise { + if (!isReloginRequired()) await forceRefreshToken(); + if (!isReloginRequired()) return false; + const task = args.pairedTaskId + ? getPairedTaskById(args.pairedTaskId) + : undefined; + if (task) { + completePairedTaskWithReason( + task, + CLAUDE_RELOGIN_REQUIRED_COMPLETION_REASON, + ); + } + args.log.warn( + { role: args.activeRole, errorText: args.errorText }, + 'Claude login is gone; closed the task and asked the room to re-login', + ); + await deliverNoticeAndFailExecution({ + notice: RELOGIN_REQUIRED_MESSAGE, + summary: RELOGIN_REQUIRED_MESSAGE, + pairedExecutionLifecycle: args.pairedExecutionLifecycle, + onOutput: args.onOutput, + }); + return true; +} + /** * Owner finalize without an agent run (see paired-finalize.ts): close the task * and deliver the already-reviewed answer as the final message. Returns false diff --git a/src/streamed-output-evaluator.ts b/src/streamed-output-evaluator.ts index 555b386..23b7769 100644 --- a/src/streamed-output-evaluator.ts +++ b/src/streamed-output-evaluator.ts @@ -222,7 +222,9 @@ function classifyClaudeSuccessTrigger( } if ( isClaudeAuthExpiredMessage(outputText) || - authClassification.category === 'auth-expired' + // Only the CLI's own banner, not an answer that quotes the error. + (authClassification.category === 'auth-expired' && + isClaudeAuthError(outputText)) ) { return 'auth-expired'; } diff --git a/src/token-refresh-force.test.ts b/src/token-refresh-force.test.ts new file mode 100644 index 0000000..a15fb16 --- /dev/null +++ b/src/token-refresh-force.test.ts @@ -0,0 +1,137 @@ +import fs from 'fs'; +import path from 'path'; + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const tmp = vi.hoisted(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodeFs = require('fs') as typeof import('fs'); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodeOs = require('os') as typeof import('os'); + // eslint-disable-next-line @typescript-eslint/no-require-imports + const nodePath = require('path') as typeof import('path'); + return nodeFs.mkdtempSync(nodePath.join(nodeOs.tmpdir(), 'ejclaw-force-')); +}); + +// Never scan or rewrite the real session credentials or .env. +vi.mock('./config.js', async (importOriginal) => ({ + ...(await importOriginal()), + DATA_DIR: tmp, +})); +vi.mock('./claude-oauth-token.js', () => ({ + getConfiguredClaudeToken: vi.fn(() => undefined), + setCurrentClaudeToken: vi.fn(), + getCurrentClaudeToken: vi.fn(() => undefined), +})); + +import { + forceRefreshToken, + isReloginRequired, + probeAccessToken, + resetAuthFailureStateForTests, +} from './token-refresh.js'; + +const credsPath = path.join(tmp, 'claude', '.credentials.json'); + +function writeCreds(accessToken: string, refreshToken = 'rt-old'): void { + fs.mkdirSync(path.dirname(credsPath), { recursive: true }); + fs.writeFileSync( + credsPath, + JSON.stringify({ + claudeAiOauth: { + accessToken, + refreshToken, + expiresAt: Date.now() + 7 * 60 * 60 * 1000, + scopes: ['user:inference'], + }, + }), + ); +} + +function mockFetch(handlers: { + profile: (token: string) => number; + token?: () => number; +}) { + const fetchMock = vi.fn(async (url: string, init?: RequestInit) => { + if (url.endsWith('/api/oauth/profile')) { + const auth = new Headers(init?.headers).get('Authorization') ?? ''; + const status = handlers.profile(auth.replace('Bearer ', '')); + return new Response('{}', { status }); + } + const status = handlers.token?.() ?? 400; + return new Response('{"error":"invalid_grant"}', { status }); + }); + vi.stubGlobal('fetch', fetchMock); + return fetchMock; +} + +const tokenCalls = (fetchMock: ReturnType) => + fetchMock.mock.calls.filter(([url]) => String(url).includes('/oauth/token')) + .length; + +beforeEach(() => { + process.env.CLAUDE_CREDENTIALS_PATH = credsPath; + resetAuthFailureStateForTests(); +}); + +afterEach(() => { + vi.unstubAllGlobals(); + delete process.env.CLAUDE_CREDENTIALS_PATH; +}); + +describe('probeAccessToken', () => { + it('reports a 401 as rejected, 200 as valid, other failures as unknown', async () => { + const reply = (status: number) => + vi.fn( + async () => new Response('{}', { status }), + ) as unknown as typeof fetch; + expect(await probeAccessToken('t', reply(401))).toBe('rejected'); + expect(await probeAccessToken('t', reply(200))).toBe('valid'); + expect(await probeAccessToken('t', reply(500))).toBe('unknown'); + const throwing = vi.fn(async () => { + throw new Error('offline'); + }) as unknown as typeof fetch; + expect(await probeAccessToken('t', throwing)).toBe('unknown'); + }); +}); + +describe('forceRefreshToken after a 401', () => { + it('returns the stored token without refreshing when the API still accepts it', async () => { + writeCreds('live'); + const fetchMock = mockFetch({ profile: () => 200 }); + + expect(await forceRefreshToken()).toBe('live'); + expect(tokenCalls(fetchMock)).toBe(0); + expect(isReloginRequired()).toBe(false); + }); + + it('flags re-login at once when a revoked token cannot be refreshed', async () => { + // The token still has hours left by expiresAt, but the API revoked it. + writeCreds('revoked'); + const fetchMock = mockFetch({ profile: () => 401, token: () => 400 }); + + expect(await forceRefreshToken()).toBeNull(); + expect(tokenCalls(fetchMock)).toBe(1); + expect(isReloginRequired()).toBe(true); + + // Later checks must not mistake the dead token for a recovery. + expect(await forceRefreshToken()).toBeNull(); + expect(tokenCalls(fetchMock)).toBe(1); + expect(isReloginRequired()).toBe(true); + }); + + it('clears the re-login state once a re-login writes a new token', async () => { + writeCreds('revoked'); + mockFetch({ profile: (t) => (t === 'revoked' ? 401 : 200) }); + await forceRefreshToken(); + expect(isReloginRequired()).toBe(true); + + writeCreds('after-relogin', 'rt-new'); + expect(await forceRefreshToken()).toBe('after-relogin'); + expect(isReloginRequired()).toBe(false); + }); +}); + +afterEach(() => { + fs.rmSync(path.join(tmp, 'claude'), { recursive: true, force: true }); +}); diff --git a/src/token-refresh.test.ts b/src/token-refresh.test.ts index a39ee85..e1a0f41 100644 --- a/src/token-refresh.test.ts +++ b/src/token-refresh.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest'; import { applyUpdatedTokenToEnvContent, collectSessionCredentialPaths, + isRefreshDue, pickFreshestOAuth, shouldAdoptSessionOAuth, shouldStartTokenRefreshLoop, @@ -166,3 +167,19 @@ describe('collectSessionCredentialPaths (real session layout)', () => { expect(collectSessionCredentialPaths('/s', () => [])).toEqual([]); }); }); + +describe('isRefreshDue', () => { + const min = 60 * 1000; + it('refreshes early only while no agent is running', () => { + expect(isRefreshDue(150 * min, false)).toBe(true); + expect(isRefreshDue(150 * min, true)).toBe(false); + }); + + it('always refreshes inside the last hour, busy or not', () => { + expect(isRefreshDue(55 * min, true)).toBe(true); + }); + + it('leaves a token with more than three hours alone', () => { + expect(isRefreshDue(200 * min, false)).toBe(false); + }); +}); diff --git a/src/token-refresh.ts b/src/token-refresh.ts index 6afae28..05fca5e 100644 --- a/src/token-refresh.ts +++ b/src/token-refresh.ts @@ -25,6 +25,7 @@ import { } from './claude-credentials-path.js'; const TOKEN_URL = 'https://api.anthropic.com/v1/oauth/token'; +const PROFILE_URL = 'https://api.anthropic.com/api/oauth/profile'; const CLIENT_ID = '9d1c250a-e61b-44d9-88ed-5944d1962f5e'; const DEFAULT_SCOPES = [ 'user:profile', @@ -42,6 +43,13 @@ const CHECK_INTERVAL_MS = 5 * 60 * 1000; // rotate on their own. That shrinks the cross-process refresh race that was // revoking the whole token family (see loadFreshestCredentials below). const REFRESH_BEFORE_EXPIRY_MS = 60 * 60 * 1000; +// Refreshing revokes the previous access token at once, and a running agent +// holds that token in CLAUDE_CODE_OAUTH_TOKEN (Claude Code will not swap an env +// token on a 401), so every agent running at refresh time dies with "401 OAuth +// access token has been revoked". Refresh early while no agent is running; +// only fall back to the hard REFRESH_BEFORE_EXPIRY_MS deadline when the +// service stays busy for the whole window. +const IDLE_REFRESH_BEFORE_EXPIRY_MS = 3 * 60 * 60 * 1000; const REQUEST_TIMEOUT_MS = 15_000; // After the refresh token itself has expired (or the endpoint keeps rejecting @@ -53,11 +61,19 @@ const GIVE_UP_AFTER_MS = 30 * 60 * 1000; /** User-facing message shown when an account needs a manual re-login. */ export const RELOGIN_REQUIRED_MESSAGE = - '로그인 정보를 찾을 수 없습니다. 재로그인 해주세요.'; + '⚠️ 클로드 로그인이 풀려서 작업을 진행할 수 없습니다. ' + + '기본_codex 방에서 "클로드 로그인 주소 보내줘"라고 하시면 재로그인 링크를 받을 수 있습니다. ' + + '재로그인한 뒤 이 방에 "계속"이라고 보내 주시면 이어서 진행합니다.'; interface AuthFailureState { firstFailureAt: number; gaveUp: boolean; + /** + * Access token the API rejected outright (revoked). It still looks valid by + * its expiresAt, so the periodic check must not treat it as a recovery; only + * a different token (a re-login) clears the state. + */ + deadAccessToken?: string; } // Continuous-refresh-failure tracking. Cleared as soon as a valid token // appears again (e.g. after a manual re-login rewrites the creds file). @@ -73,7 +89,13 @@ export function isReloginRequired(): boolean { } /** Clear failure tracking once a valid token is observed again. */ -function recordAuthSuccess(): void { +function recordAuthSuccess(accessToken?: string): void { + if ( + authFailure?.deadAccessToken && + (!accessToken || accessToken === authFailure.deadAccessToken) + ) { + return; + } if (authFailure) { authFailure = null; logger.info('Claude OAuth recovered — cleared re-login-required state'); @@ -105,6 +127,73 @@ function recordAuthFailure(): boolean { return state.gaveUp; } +/** + * The API rejected the current token and refreshing failed too: the login is + * gone, so stop retrying right away instead of after GIVE_UP_AFTER_MS. + */ +function markReloginRequired(deadAccessToken: string): void { + authFailure = { + firstFailureAt: authFailure?.firstFailureAt ?? Date.now(), + gaveUp: true, + deadAccessToken, + }; + logger.error( + 'Claude OAuth token was rejected and could not be refreshed — manual ' + + 're-login required (run claude_relogin.sh)', + ); +} + +/** Test hook: reset the module-level failure state. */ +export function resetAuthFailureStateForTests(): void { + authFailure = null; +} + +export type AccessTokenProbe = 'valid' | 'rejected' | 'unknown'; + +/** + * Ask the API whether an access token is still accepted. A revoked token keeps + * its expiresAt, so the expiry alone cannot tell a dead token from a live one. + * Only a 401 counts as rejected; network errors and other statuses are unknown. + */ +export async function probeAccessToken( + token: string, + fetchImpl: typeof fetch = fetch, +): Promise { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); + try { + const res = await fetchImpl(PROFILE_URL, { + method: 'GET', + headers: { + Authorization: `Bearer ${token}`, + 'anthropic-beta': 'oauth-2025-04-20', + }, + signal: controller.signal, + }); + if (res.status === 401) return 'rejected'; + return res.ok ? 'valid' : 'unknown'; + } catch (err) { + logger.warn( + { err: getErrorMessage(err) }, + 'Claude OAuth token probe failed', + ); + return 'unknown'; + } finally { + clearTimeout(timeout); + } +} + +/** Pure refresh-timing decision for a token with `remainingMs` left. */ +export function isRefreshDue( + remainingMs: number, + agentsActive: boolean, +): boolean { + if (remainingMs <= REFRESH_BEFORE_EXPIRY_MS) return true; + return !agentsActive && remainingMs <= IDLE_REFRESH_BEFORE_EXPIRY_MS; +} + +let hasActiveAgents: () => boolean = () => false; + export function shouldStartTokenRefreshLoop( serviceAgentType: AgentType, ): boolean { @@ -321,7 +410,7 @@ export function syncClaudeSessionAuthBack(sessionClaudeDir: string): boolean { // stale copies (old refresh tokens that could trigger family revocation) are // overwritten with the current one. writeCredentials(sessionCreds); - recordAuthSuccess(); + recordAuthSuccess(sOauth.accessToken); logger.info( { newExpiryMin: Math.round((sOauth.expiresAt - Date.now()) / 60000), @@ -546,16 +635,35 @@ async function doCheckAndRefreshCredentials(opts?: { const now = Date.now(); const remaining = oauth.expiresAt - now; - if (remaining > REFRESH_BEFORE_EXPIRY_MS) { + // A forced check comes from a 401. Expiry cannot reveal a revoked token, so + // ask the API; a rejected token must be refreshed even though it "looks" + // valid, otherwise every retry reuses the same dead token. + const rejected = + opts?.force === true && + !isReloginRequired() && + (await probeAccessToken(oauth.accessToken)) === 'rejected'; + if (rejected) { + logger.warn( + { remainingMin: Math.round(remaining / 60000) }, + 'Claude OAuth token was rejected by the API before its expiry', + ); + } + + // A forced (401) check only refreshes a rejected or nearly expired token. + const due = + rejected || isRefreshDue(remaining, opts?.force ? true : hasActiveAgents()); + if (!due) { // A valid token is present again (typically after a manual re-login rewrote // the credentials file) — drop any prior "re-login required" state. - recordAuthSuccess(); + recordAuthSuccess(oauth.accessToken); if (!opts?.force && !freshest.adoptedFromSession) { logger.debug( { remainingMin: Math.round(remaining / 60000) }, 'Token still valid, no refresh needed', ); } + // Still the token the API rejected: there is nothing usable to retry with. + if (isReloginRequired()) return null; // Token is valid; only report a token when it actually changed (adopted) or // a caller forced the check and wants a usable token back to retry with. return freshest.adoptedFromSession || opts?.force @@ -586,7 +694,7 @@ async function doCheckAndRefreshCredentials(opts?: { try { const response = await refreshToken(rt, oauth.scopes || DEFAULT_SCOPES); - recordAuthSuccess(); + recordAuthSuccess(response.access_token); oauth.accessToken = response.access_token; oauth.refreshToken = response.refresh_token || rt; oauth.expiresAt = Date.now() + response.expires_in * 1000; @@ -612,12 +720,14 @@ async function doCheckAndRefreshCredentials(opts?: { const recoveredOauth = recovered?.creds.claudeAiOauth; if ( recoveredOauth && - recoveredOauth.expiresAt - Date.now() > REFRESH_BEFORE_EXPIRY_MS + recoveredOauth.expiresAt - Date.now() > REFRESH_BEFORE_EXPIRY_MS && + // The token the API just rejected is no recovery, however long it has. + !(rejected && recoveredOauth.accessToken === oauth.accessToken) ) { if (recovered.adoptedFromSession) { writeCredentials(recovered.creds); } - recordAuthSuccess(); + recordAuthSuccess(recoveredOauth.accessToken); logger.warn( { remainingMin: Math.round( @@ -628,6 +738,10 @@ async function doCheckAndRefreshCredentials(opts?: { ); return recoveredOauth.accessToken; } + if (rejected) { + markReloginRequired(oauth.accessToken); + return null; + } const gaveUp = recordAuthFailure(); logger.error( { @@ -650,7 +764,11 @@ async function checkAndRefresh(): Promise { let refreshInterval: ReturnType | null = null; -export function startTokenRefreshLoop(): void { +export function startTokenRefreshLoop(options?: { + /** True while any agent run is in flight (see IDLE_REFRESH_BEFORE_EXPIRY_MS). */ + hasActiveAgents?: () => boolean; +}): void { + if (options?.hasActiveAgents) hasActiveAgents = options.hasActiveAgents; const refreshEnabled = process.env.CLAUDE_TOKEN_REFRESH_USE_CREDENTIALS === 'true' || process.env.CLAUDE_TOKEN_REFRESH_USE_HOME_CREDENTIALS === 'true';