Files
EJClaw/src/token-refresh.test.ts
Codex 3f2e364c73 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>
2026-11-02 10:45:21 +09:00

186 lines
5.8 KiB
TypeScript

import { describe, expect, it } from 'vitest';
import {
applyUpdatedTokenToEnvContent,
collectSessionCredentialPaths,
isRefreshDue,
pickFreshestOAuth,
shouldAdoptSessionOAuth,
shouldStartTokenRefreshLoop,
} from './token-refresh.js';
function creds(expiresAt: number, refreshToken = 'rt') {
return {
claudeAiOauth: {
accessToken: `at-${expiresAt}`,
refreshToken,
expiresAt,
scopes: [] as string[],
},
};
}
describe('shouldStartTokenRefreshLoop', () => {
it('starts refresh for the Claude service', () => {
expect(shouldStartTokenRefreshLoop('claude-code')).toBe(true);
});
it('skips refresh for the Codex service', () => {
expect(shouldStartTokenRefreshLoop('codex')).toBe(false);
});
it('rewrites both the single-token and legacy list env vars when present', () => {
const next = applyUpdatedTokenToEnvContent(
[
'CLAUDE_CODE_OAUTH_TOKEN=old-primary',
'CLAUDE_CODE_OAUTH_TOKENS=old-primary',
'OTHER=value',
].join('\n'),
'new-primary',
);
expect(next).toContain('CLAUDE_CODE_OAUTH_TOKEN=new-primary');
expect(next).toContain('CLAUDE_CODE_OAUTH_TOKENS=new-primary');
expect(next).toContain('OTHER=value');
});
it('only rewrites the single-token env var when the list is absent', () => {
const next = applyUpdatedTokenToEnvContent(
['CLAUDE_CODE_OAUTH_TOKEN=old-primary', 'OTHER=value'].join('\n'),
'new-primary',
);
expect(next).toContain('CLAUDE_CODE_OAUTH_TOKEN=new-primary');
expect(next).not.toContain('CLAUDE_CODE_OAUTH_TOKENS');
});
it('appends CLAUDE_CODE_OAUTH_TOKEN when neither var exists', () => {
expect(applyUpdatedTokenToEnvContent('OTHER=value\n', 'tok')).toBe(
'OTHER=value\nCLAUDE_CODE_OAUTH_TOKEN=tok\n',
);
});
});
describe('pickFreshestOAuth', () => {
it('adopts a session copy that expires later than the source', () => {
const best = pickFreshestOAuth([
{ label: 'source', creds: creds(1000) },
{ label: 'sessionA', creds: creds(5000) },
{ label: 'sessionB', creds: creds(3000) },
]);
expect(best?.label).toBe('sessionA');
});
it('keeps the source on ties so we do not churn copies needlessly', () => {
const best = pickFreshestOAuth([
{ label: 'source', creds: creds(5000) },
{ label: 'sessionA', creds: creds(5000) },
]);
expect(best?.label).toBe('source');
});
it('ignores candidates without a refresh token or numeric expiry', () => {
const best = pickFreshestOAuth([
{ label: 'source', creds: creds(1000) },
{ label: 'noRefresh', creds: creds(9000, '') },
{ label: 'missing', creds: null },
]);
expect(best?.label).toBe('source');
});
it('returns null when no candidate is usable', () => {
expect(
pickFreshestOAuth([
{ label: 'source', creds: null },
{ label: 'noRefresh', creds: creds(9000, '') },
]),
).toBeNull();
});
});
describe('shouldAdoptSessionOAuth (session→canonical write-back)', () => {
const oauth = (expiresAt: number, extra: Record<string, unknown> = {}) => ({
accessToken: `at-${expiresAt}`,
refreshToken: `rt-${expiresAt}`,
expiresAt,
scopes: [] as string[],
...extra,
});
it('adopts a session token strictly newer than canonical', () => {
expect(shouldAdoptSessionOAuth(oauth(2000), oauth(1000))).toBe(true);
});
it('does not regress to an older or equal session token', () => {
expect(shouldAdoptSessionOAuth(oauth(1000), oauth(2000))).toBe(false);
expect(shouldAdoptSessionOAuth(oauth(2000), oauth(2000))).toBe(false);
});
it('adopts when canonical is missing/invalid', () => {
expect(shouldAdoptSessionOAuth(oauth(1000), null)).toBe(true);
});
it('rejects an invalid session token', () => {
expect(shouldAdoptSessionOAuth(null, oauth(1000))).toBe(false);
expect(
shouldAdoptSessionOAuth(
{ accessToken: '', refreshToken: '', expiresAt: 5000, scopes: [] },
oauth(1000),
),
).toBe(false);
});
it('refuses to cross subscription types', () => {
expect(
shouldAdoptSessionOAuth(
oauth(2000, { subscriptionType: 'pro' }),
oauth(1000, { subscriptionType: 'max' }),
),
).toBe(false);
});
});
describe('collectSessionCredentialPaths (real session layout)', () => {
it('builds service group + task credential paths, not <group>/.claude', () => {
const tree: Record<string, string[]> = {
'/s': ['iger', 'javis_bot'],
'/s/iger/services': ['claude'],
'/s/iger/services/claude/tasks': ['task-1'],
'/s/javis_bot/services': ['claude'],
'/s/javis_bot/services/claude/tasks': [],
};
const paths = collectSessionCredentialPaths('/s', (dir) => tree[dir] ?? []);
expect(paths).toContain(
'/s/iger/services/claude/.claude/.credentials.json',
);
expect(paths).toContain(
'/s/iger/services/claude/tasks/task-1/.claude/.credentials.json',
);
expect(paths).toContain(
'/s/javis_bot/services/claude/.claude/.credentials.json',
);
// Must NOT use the old broken <group>/.claude path that matched nothing.
expect(paths).not.toContain('/s/iger/.claude/.credentials.json');
});
it('returns nothing when there are no session folders', () => {
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);
});
});