fix: stop silent Claude 401 stalls and token-family revocations

- Refreshing the OAuth token revokes the old access token, and agents hold it
  in CLAUDE_CODE_OAUTH_TOKEN (Claude Code keeps env tokens on 401). Refresh
  early only while no run is active; keep the 1h hard deadline.
- forceRefreshToken (after a 401) now probes /api/oauth/profile: a revoked
  token keeps its expiresAt, so it was handed back unchanged forever. A
  rejected token is refreshed; if that fails, re-login is flagged at once and
  held until a different token appears.
- Classify "OAuth access token has been revoked" as auth-expired. When the
  login is gone, close the paired task and tell the room to re-login instead
  of looping owner/arbiter retries with suppressed output.
- Only suppress the CLI's own short 401 banner, not an answer quoting it
  (a sketchup-app TASK_DONE report was swallowed this way).
- Runner denies Bash commands that copy or write .credentials.json: a CLI test
  against a copied login refreshed the real token family on 2026-11-02 and
  logged out every room.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codex
2026-11-02 10:45:21 +09:00
parent 0ce79c8d0c
commit 3f2e364c73
13 changed files with 553 additions and 15 deletions

View File

@@ -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<AccessTokenProbe> {
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<void> {
let refreshInterval: ReturnType<typeof setInterval> | 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';