Compare commits

..

1 Commits

Author SHA1 Message Date
github-actions[bot]
74997468de docs: auto-update documentation based on changes in next branch
This PR was automatically generated to update documentation based on recent changes.

  Original commit: feat: add next command to new command structure (#1312)\n\n\n

  Co-authored-by: Claude <claude-assistant@anthropic.com>
2025-10-15 13:32:45 +00:00
25 changed files with 362 additions and 337 deletions

View File

@@ -1,5 +0,0 @@
---
"task-master-ai": patch
---
Improve auth token refresh flow

View File

@@ -1,5 +0,0 @@
---
"task-master-ai": minor
---
Add 4.5 haiku and sonnet to supported models for claude-code and anthropic ai providers

View File

@@ -143,7 +143,7 @@ export class AuthCommand extends Command {
*/
private async executeStatus(): Promise<void> {
try {
const result = this.displayStatus();
const result = await this.displayStatus();
this.setLastResult(result);
} catch (error: any) {
this.handleError(error);
@@ -171,8 +171,8 @@ export class AuthCommand extends Command {
/**
* Display authentication status
*/
private displayStatus(): AuthResult {
const credentials = this.authManager.getCredentials();
private async displayStatus(): Promise<AuthResult> {
const credentials = await this.authManager.getCredentials();
console.log(chalk.cyan('\n🔐 Authentication Status\n'));
@@ -325,7 +325,7 @@ export class AuthCommand extends Command {
]);
if (!continueAuth) {
const credentials = this.authManager.getCredentials();
const credentials = await this.authManager.getCredentials();
ui.displaySuccess('Using existing authentication');
if (credentials) {
@@ -490,7 +490,7 @@ export class AuthCommand extends Command {
/**
* Get current credentials (for programmatic usage)
*/
getCredentials(): AuthCredentials | null {
getCredentials(): Promise<AuthCredentials | null> {
return this.authManager.getCredentials();
}

View File

@@ -115,7 +115,7 @@ export class ContextCommand extends Command {
*/
private async executeShow(): Promise<void> {
try {
const result = this.displayContext();
const result = await this.displayContext();
this.setLastResult(result);
} catch (error: any) {
this.handleError(error);
@@ -126,7 +126,7 @@ export class ContextCommand extends Command {
/**
* Display current context
*/
private displayContext(): ContextResult {
private async displayContext(): Promise<ContextResult> {
// Check authentication first
if (!this.authManager.isAuthenticated()) {
console.log(chalk.yellow('✗ Not authenticated'));
@@ -139,7 +139,7 @@ export class ContextCommand extends Command {
};
}
const context = this.authManager.getContext();
const context = await this.authManager.getContext();
console.log(chalk.cyan('\n🌍 Workspace Context\n'));
@@ -250,7 +250,7 @@ export class ContextCommand extends Command {
]);
// Update context
this.authManager.updateContext({
await this.authManager.updateContext({
orgId: selectedOrg.id,
orgName: selectedOrg.name,
// Clear brief when changing org
@@ -263,7 +263,7 @@ export class ContextCommand extends Command {
return {
success: true,
action: 'select-org',
context: this.authManager.getContext() || undefined,
context: (await this.authManager.getContext()) || undefined,
message: `Selected organization: ${selectedOrg.name}`
};
} catch (error) {
@@ -284,7 +284,7 @@ export class ContextCommand extends Command {
}
// Check if org is selected
const context = this.authManager.getContext();
const context = await this.authManager.getContext();
if (!context?.orgId) {
ui.displayError(
'No organization selected. Run "tm context org" first.'
@@ -343,7 +343,7 @@ export class ContextCommand extends Command {
if (selectedBrief) {
// Update context with brief
const briefName = `Brief ${selectedBrief.id.slice(0, 8)}`;
this.authManager.updateContext({
await this.authManager.updateContext({
briefId: selectedBrief.id,
briefName: briefName
});
@@ -353,12 +353,12 @@ export class ContextCommand extends Command {
return {
success: true,
action: 'select-brief',
context: this.authManager.getContext() || undefined,
context: (await this.authManager.getContext()) || undefined,
message: `Selected brief: ${selectedBrief.name}`
};
} else {
// Clear brief selection
this.authManager.updateContext({
await this.authManager.updateContext({
briefId: undefined,
briefName: undefined
});
@@ -368,7 +368,7 @@ export class ContextCommand extends Command {
return {
success: true,
action: 'select-brief',
context: this.authManager.getContext() || undefined,
context: (await this.authManager.getContext()) || undefined,
message: 'Cleared brief selection'
};
}
@@ -491,7 +491,7 @@ export class ContextCommand extends Command {
// Update context: set org and brief
const briefName = `Brief ${brief.id.slice(0, 8)}`;
this.authManager.updateContext({
await this.authManager.updateContext({
orgId: brief.accountId,
orgName,
briefId: brief.id,
@@ -508,7 +508,7 @@ export class ContextCommand extends Command {
this.setLastResult({
success: true,
action: 'set',
context: this.authManager.getContext() || undefined,
context: (await this.authManager.getContext()) || undefined,
message: 'Context set from brief'
});
} catch (error: any) {
@@ -613,7 +613,7 @@ export class ContextCommand extends Command {
};
}
this.authManager.updateContext(context);
await this.authManager.updateContext(context);
ui.displaySuccess('Context updated');
// Display what was set
@@ -631,7 +631,7 @@ export class ContextCommand extends Command {
return {
success: true,
action: 'set',
context: this.authManager.getContext() || undefined,
context: (await this.authManager.getContext()) || undefined,
message: 'Context updated'
};
} catch (error) {
@@ -682,7 +682,7 @@ export class ContextCommand extends Command {
/**
* Get current context (for programmatic usage)
*/
getContext(): UserContext | null {
getContext(): Promise<UserContext | null> {
return this.authManager.getContext();
}

View File

@@ -35,6 +35,18 @@ sidebarTitle: "CLI Commands"
```bash
# Show the next task to work on based on dependencies and status
task-master next
# Filter by tag
task-master next --tag <tag>
# Output in JSON format (useful for programmatic usage)
task-master next --format json
# Suppress output (useful for scripts)
task-master next --silent
# Specify project directory
task-master next --project /path/to/project
```
</Accordion>

30
output.txt Normal file

File diff suppressed because one or more lines are too long

View File

@@ -35,7 +35,7 @@ vi.mock('./credential-store.js', () => {
}
saveCredentials() {}
clearCredentials() {}
hasCredentials() {
hasValidCredentials() {
return false;
}
}

View File

@@ -29,6 +29,8 @@ export class AuthManager {
private oauthService: OAuthService;
private supabaseClient: SupabaseAuthClient;
private organizationService?: OrganizationService;
private logger = getLogger('AuthManager');
private refreshPromise: Promise<AuthCredentials> | null = null;
private constructor(config?: Partial<AuthConfig>) {
this.credentialStore = CredentialStore.getInstance(config);
@@ -81,10 +83,60 @@ export class AuthManager {
/**
* Get stored authentication credentials
* Returns credentials as-is (even if expired). Refresh must be triggered explicitly
* via refreshToken() or will occur automatically when using the Supabase client for API calls.
* Automatically refreshes the token if expired
*/
getCredentials(): AuthCredentials | null {
async getCredentials(): Promise<AuthCredentials | null> {
const credentials = this.credentialStore.getCredentials({
allowExpired: true
});
if (!credentials) {
return null;
}
// Check if credentials are expired (with 30-second clock skew buffer)
const CLOCK_SKEW_MS = 30_000;
const isExpired = credentials.expiresAt
? new Date(credentials.expiresAt).getTime() <= Date.now() + CLOCK_SKEW_MS
: false;
// If expired and we have a refresh token, attempt refresh
if (isExpired && credentials.refreshToken) {
// Return existing refresh promise if one is in progress
if (this.refreshPromise) {
try {
return await this.refreshPromise;
} catch {
return null;
}
}
try {
this.logger.info('Token expired, attempting automatic refresh...');
this.refreshPromise = this.refreshToken();
const result = await this.refreshPromise;
return result;
} catch (error) {
this.logger.warn('Automatic token refresh failed:', error);
return null;
} finally {
this.refreshPromise = null;
}
}
// Return null if expired and no refresh token
if (isExpired) {
return null;
}
return credentials;
}
/**
* Get stored authentication credentials (synchronous version)
* Does not attempt automatic refresh
*/
getCredentialsSync(): AuthCredentials | null {
return this.credentialStore.getCredentials();
}
@@ -167,26 +219,25 @@ export class AuthManager {
}
/**
* Check if authenticated (credentials exist, regardless of expiration)
* @returns true if credentials are stored, including expired credentials
* Check if authenticated
*/
isAuthenticated(): boolean {
return this.credentialStore.hasCredentials();
return this.credentialStore.hasValidCredentials();
}
/**
* Get the current user context (org/brief selection)
*/
getContext(): UserContext | null {
const credentials = this.getCredentials();
async getContext(): Promise<UserContext | null> {
const credentials = await this.getCredentials();
return credentials?.selectedContext || null;
}
/**
* Update the user context (org/brief selection)
*/
updateContext(context: Partial<UserContext>): void {
const credentials = this.getCredentials();
async updateContext(context: Partial<UserContext>): Promise<void> {
const credentials = await this.getCredentials();
if (!credentials) {
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
}
@@ -211,8 +262,8 @@ export class AuthManager {
/**
* Clear the user context
*/
clearContext(): void {
const credentials = this.getCredentials();
async clearContext(): Promise<void> {
const credentials = await this.getCredentials();
if (!credentials) {
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
}
@@ -229,7 +280,7 @@ export class AuthManager {
private async getOrganizationService(): Promise<OrganizationService> {
if (!this.organizationService) {
// First check if we have credentials with a token
const credentials = this.getCredentials();
const credentials = await this.getCredentials();
if (!credentials || !credentials.token) {
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
}

View File

@@ -52,7 +52,7 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(expiredCredentials);
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).toBeNull();
});
@@ -69,7 +69,7 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(validCredentials);
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).not.toBeNull();
expect(retrieved?.token).toBe('valid-token');
@@ -92,25 +92,6 @@ describe('CredentialStore - Token Expiration', () => {
expect(retrieved).not.toBeNull();
expect(retrieved?.token).toBe('expired-token');
});
it('should return expired token by default (allowExpired defaults to true)', () => {
const expiredCredentials: AuthCredentials = {
token: 'expired-token-default',
refreshToken: 'refresh-token',
userId: 'test-user',
email: 'test@example.com',
expiresAt: new Date(Date.now() - 60000).toISOString(),
savedAt: new Date().toISOString()
};
credentialStore.saveCredentials(expiredCredentials);
// Call without options - should default to allowExpired: true
const retrieved = credentialStore.getCredentials();
expect(retrieved).not.toBeNull();
expect(retrieved?.token).toBe('expired-token-default');
});
});
describe('Clock Skew Tolerance', () => {
@@ -127,7 +108,7 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(almostExpiredCredentials);
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).toBeNull();
});
@@ -145,7 +126,7 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(validCredentials);
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).not.toBeNull();
expect(retrieved?.token).toBe('valid-token');
@@ -165,7 +146,7 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(credentials);
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).not.toBeNull();
expect(typeof retrieved?.expiresAt).toBe('number'); // Normalized to number
@@ -183,7 +164,7 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(credentials);
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).not.toBeNull();
expect(typeof retrieved?.expiresAt).toBe('number');
@@ -204,7 +185,7 @@ describe('CredentialStore - Token Expiration', () => {
mode: 0o600
});
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).toBeNull();
});
@@ -222,7 +203,7 @@ describe('CredentialStore - Token Expiration', () => {
mode: 0o600
});
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
expect(retrieved).toBeNull();
});
@@ -263,15 +244,15 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(credentials);
const retrieved = credentialStore.getCredentials({ allowExpired: false });
const retrieved = credentialStore.getCredentials();
// Should be normalized to number for runtime use
expect(typeof retrieved?.expiresAt).toBe('number');
});
});
describe('hasCredentials', () => {
it('should return true for expired credentials', () => {
describe('hasValidCredentials', () => {
it('should return false for expired credentials', () => {
const expiredCredentials: AuthCredentials = {
token: 'expired-token',
refreshToken: 'refresh-token',
@@ -283,7 +264,7 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(expiredCredentials);
expect(credentialStore.hasCredentials()).toBe(true);
expect(credentialStore.hasValidCredentials()).toBe(false);
});
it('should return true for valid credentials', () => {
@@ -298,11 +279,11 @@ describe('CredentialStore - Token Expiration', () => {
credentialStore.saveCredentials(validCredentials);
expect(credentialStore.hasCredentials()).toBe(true);
expect(credentialStore.hasValidCredentials()).toBe(true);
});
it('should return false when no credentials exist', () => {
expect(credentialStore.hasCredentials()).toBe(false);
expect(credentialStore.hasValidCredentials()).toBe(false);
});
});
});

View File

@@ -197,7 +197,7 @@ describe('CredentialStore', () => {
JSON.stringify(mockCredentials)
);
const result = store.getCredentials({ allowExpired: false });
const result = store.getCredentials();
expect(result).toBeNull();
expect(mockLogger.warn).toHaveBeenCalledWith(
@@ -226,31 +226,6 @@ describe('CredentialStore', () => {
expect(result).not.toBeNull();
expect(result?.token).toBe('expired-token');
});
it('should return expired tokens by default (allowExpired defaults to true)', () => {
const expiredTimestamp = Date.now() - 3600000; // 1 hour ago
const mockCredentials = {
token: 'expired-token-default',
userId: 'user-expired',
expiresAt: expiredTimestamp,
tokenType: 'standard',
savedAt: new Date().toISOString()
};
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(
JSON.stringify(mockCredentials)
);
// Call without options - should default to allowExpired: true
const result = store.getCredentials();
expect(result).not.toBeNull();
expect(result?.token).toBe('expired-token-default');
expect(mockLogger.warn).not.toHaveBeenCalledWith(
expect.stringContaining('Authentication token has expired')
);
});
});
describe('saveCredentials with timestamp normalization', () => {
@@ -476,7 +451,7 @@ describe('CredentialStore', () => {
});
});
describe('hasCredentials', () => {
describe('hasValidCredentials', () => {
it('should return true when valid unexpired credentials exist', () => {
const futureDate = new Date(Date.now() + 3600000); // 1 hour from now
const credentials = {
@@ -490,10 +465,10 @@ describe('CredentialStore', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(credentials));
expect(store.hasCredentials()).toBe(true);
expect(store.hasValidCredentials()).toBe(true);
});
it('should return true when credentials are expired', () => {
it('should return false when credentials are expired', () => {
const pastDate = new Date(Date.now() - 3600000); // 1 hour ago
const credentials = {
token: 'expired-token',
@@ -506,13 +481,13 @@ describe('CredentialStore', () => {
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(credentials));
expect(store.hasCredentials()).toBe(true);
expect(store.hasValidCredentials()).toBe(false);
});
it('should return false when no credentials exist', () => {
vi.mocked(fs.existsSync).mockReturnValue(false);
expect(store.hasCredentials()).toBe(false);
expect(store.hasValidCredentials()).toBe(false);
});
it('should return false when file contains invalid JSON', () => {
@@ -520,7 +495,7 @@ describe('CredentialStore', () => {
vi.mocked(fs.readFileSync).mockReturnValue('invalid json {');
vi.mocked(fs.renameSync).mockImplementation(() => undefined);
expect(store.hasCredentials()).toBe(false);
expect(store.hasValidCredentials()).toBe(false);
});
it('should return false for credentials without expiry', () => {
@@ -535,7 +510,7 @@ describe('CredentialStore', () => {
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(credentials));
// Credentials without expiry are considered invalid
expect(store.hasCredentials()).toBe(false);
expect(store.hasValidCredentials()).toBe(false);
// Should log warning about missing expiration
expect(mockLogger.warn).toHaveBeenCalledWith(
@@ -543,14 +518,14 @@ describe('CredentialStore', () => {
);
});
it('should use allowExpired=true', () => {
it('should use allowExpired=false by default', () => {
// Spy on getCredentials to verify it's called with correct params
const getCredentialsSpy = vi.spyOn(store, 'getCredentials');
vi.mocked(fs.existsSync).mockReturnValue(false);
store.hasCredentials();
store.hasValidCredentials();
expect(getCredentialsSpy).toHaveBeenCalledWith({ allowExpired: true });
expect(getCredentialsSpy).toHaveBeenCalledWith({ allowExpired: false });
});
});

View File

@@ -54,12 +54,9 @@ export class CredentialStore {
/**
* Get stored authentication credentials
* @param options.allowExpired - Whether to return expired credentials (default: true)
* @returns AuthCredentials with expiresAt as number (milliseconds) for runtime use
*/
getCredentials({
allowExpired = true
}: { allowExpired?: boolean } = {}): AuthCredentials | null {
getCredentials(options?: { allowExpired?: boolean }): AuthCredentials | null {
try {
if (!fs.existsSync(this.config.configFile)) {
return null;
@@ -93,6 +90,7 @@ export class CredentialStore {
// Check if the token has expired (with clock skew tolerance)
const now = Date.now();
const allowExpired = options?.allowExpired ?? false;
if (now >= expiresAtMs - this.CLOCK_SKEW_MS && !allowExpired) {
this.logger.warn(
'Authentication token has expired or is about to expire',
@@ -105,7 +103,7 @@ export class CredentialStore {
return null;
}
// Return credentials (even if expired) to enable refresh flows
// Return valid token
return authData;
} catch (error) {
this.logger.error(
@@ -201,11 +199,10 @@ export class CredentialStore {
}
/**
* Check if credentials exist (regardless of expiration status)
* @returns true if credentials are stored, including expired credentials
* Check if credentials exist and are valid
*/
hasCredentials(): boolean {
const credentials = this.getCredentials({ allowExpired: true });
hasValidCredentials(): boolean {
const credentials = this.getCredentials({ allowExpired: false });
return credentials !== null;
}

View File

@@ -281,26 +281,15 @@ export class OAuthService {
// Exchange code for session using PKCE
const session = await this.supabaseClient.exchangeCodeForSession(code);
// Calculate expiration - can be overridden with TM_TOKEN_EXPIRY_MINUTES
let expiresAt: string | undefined;
const tokenExpiryMinutes = process.env.TM_TOKEN_EXPIRY_MINUTES;
if (tokenExpiryMinutes) {
const minutes = parseInt(tokenExpiryMinutes);
expiresAt = new Date(Date.now() + minutes * 60 * 1000).toISOString();
this.logger.warn(`Token expiry overridden to ${minutes} minute(s)`);
} else {
expiresAt = session.expires_at
? new Date(session.expires_at * 1000).toISOString()
: undefined;
}
// Save authentication data
const authData: AuthCredentials = {
token: session.access_token,
refreshToken: session.refresh_token,
userId: session.user.id,
email: session.user.email,
expiresAt,
expiresAt: session.expires_at
? new Date(session.expires_at * 1000).toISOString()
: undefined,
tokenType: 'standard',
savedAt: new Date().toISOString()
};
@@ -351,18 +340,10 @@ export class OAuthService {
// Get user info from the session
const user = await this.supabaseClient.getUser();
// Calculate expiration time - can be overridden with TM_TOKEN_EXPIRY_MINUTES
let expiresAt: string | undefined;
const tokenExpiryMinutes = process.env.TM_TOKEN_EXPIRY_MINUTES;
if (tokenExpiryMinutes) {
const minutes = parseInt(tokenExpiryMinutes);
expiresAt = new Date(Date.now() + minutes * 60 * 1000).toISOString();
this.logger.warn(`Token expiry overridden to ${minutes} minute(s)`);
} else {
expiresAt = expiresIn
? new Date(Date.now() + parseInt(expiresIn) * 1000).toISOString()
: undefined;
}
// Calculate expiration time
const expiresAt = expiresIn
? new Date(Date.now() + parseInt(expiresIn) * 1000).toISOString()
: undefined;
// Save authentication data
const authData: AuthCredentials = {
@@ -370,7 +351,7 @@ export class OAuthService {
refreshToken: refreshToken || undefined,
userId: user?.id || 'unknown',
email: user?.email,
expiresAt,
expiresAt: expiresAt,
tokenType: 'standard',
savedAt: new Date().toISOString()
};

View File

@@ -98,11 +98,11 @@ export class SupabaseSessionStorage implements SupportedStorage {
// Only handle Supabase session keys
if (key === STORAGE_KEY || key.includes('auth-token')) {
try {
this.logger.info('Supabase called setItem - storing refreshed session');
// Parse the session and update our credentials
const sessionUpdates = this.parseSessionToCredentials(value);
const existingCredentials = this.store.getCredentials();
const existingCredentials = this.store.getCredentials({
allowExpired: true
});
if (sessionUpdates.token) {
const updatedCredentials: AuthCredentials = {
@@ -113,9 +113,6 @@ export class SupabaseSessionStorage implements SupportedStorage {
} as AuthCredentials;
this.store.saveCredentials(updatedCredentials);
this.logger.info(
'Successfully saved refreshed credentials from Supabase'
);
}
} catch (error) {
this.logger.error('Error setting session:', error);

View File

@@ -17,11 +17,10 @@ export class SupabaseAuthClient {
private client: SupabaseJSClient | null = null;
private sessionStorage: SupabaseSessionStorage;
private logger = getLogger('SupabaseAuthClient');
private credentialStore: CredentialStore;
constructor() {
this.credentialStore = CredentialStore.getInstance();
this.sessionStorage = new SupabaseSessionStorage(this.credentialStore);
const credentialStore = CredentialStore.getInstance();
this.sessionStorage = new SupabaseSessionStorage(credentialStore);
}
/**

View File

@@ -73,7 +73,7 @@ export class StorageFactory {
);
}
// Use auth token from AuthManager (synchronous - no auto-refresh here)
const credentials = authManager.getCredentials();
const credentials = authManager.getCredentialsSync();
if (credentials) {
// Merge with existing storage config, ensuring required fields
const nextStorage: StorageSettings = {
@@ -103,7 +103,7 @@ export class StorageFactory {
// Then check if authenticated via AuthManager
if (authManager.isAuthenticated()) {
const credentials = authManager.getCredentials();
const credentials = authManager.getCredentialsSync();
if (credentials) {
// Configure API storage with auth credentials
const nextStorage: StorageSettings = {

View File

@@ -50,7 +50,7 @@ describe('AuthManager Token Refresh', () => {
}
});
it('should return expired credentials to enable refresh flows', () => {
it('should not make concurrent refresh requests', async () => {
// Set up expired credentials with refresh token
const expiredCredentials: AuthCredentials = {
token: 'expired_access_token',
@@ -63,16 +63,50 @@ describe('AuthManager Token Refresh', () => {
credentialStore.saveCredentials(expiredCredentials);
// Get credentials should return them even if expired
// Refresh will be handled by explicit calls or client operations
const credentials = authManager.getCredentials();
// Mock the refreshToken method to track calls
const refreshTokenSpy = vi.spyOn(authManager as any, 'refreshToken');
const mockSession: Session = {
access_token: 'new_access_token',
refresh_token: 'new_refresh_token',
expires_at: Math.floor(Date.now() / 1000) + 3600,
user: {
id: 'test-user-id',
email: 'test@example.com',
app_metadata: {},
user_metadata: {},
aud: 'authenticated',
created_at: new Date().toISOString()
}
};
expect(credentials).not.toBeNull();
expect(credentials?.token).toBe('expired_access_token');
expect(credentials?.refreshToken).toBe('valid_refresh_token');
refreshTokenSpy.mockResolvedValue({
token: mockSession.access_token,
refreshToken: mockSession.refresh_token,
userId: mockSession.user.id,
email: mockSession.user.email,
expiresAt: new Date(mockSession.expires_at! * 1000).toISOString(),
savedAt: new Date().toISOString()
});
// Make multiple concurrent calls to getCredentials
const promises = [
authManager.getCredentials(),
authManager.getCredentials(),
authManager.getCredentials()
];
const results = await Promise.all(promises);
// Verify all calls returned the same new credentials
expect(results[0]?.token).toBe('new_access_token');
expect(results[1]?.token).toBe('new_access_token');
expect(results[2]?.token).toBe('new_access_token');
// Verify refreshToken was only called once, not three times
expect(refreshTokenSpy).toHaveBeenCalledTimes(1);
});
it('should return valid credentials', () => {
it('should return valid credentials without attempting refresh', async () => {
// Set up valid (non-expired) credentials
const validCredentials: AuthCredentials = {
token: 'valid_access_token',
@@ -85,14 +119,17 @@ describe('AuthManager Token Refresh', () => {
credentialStore.saveCredentials(validCredentials);
const credentials = authManager.getCredentials();
// Spy on refreshToken to ensure it's not called
const refreshTokenSpy = vi.spyOn(authManager as any, 'refreshToken');
const credentials = await authManager.getCredentials();
expect(credentials?.token).toBe('valid_access_token');
expect(refreshTokenSpy).not.toHaveBeenCalled();
});
it('should return expired credentials even without refresh token', () => {
it('should return null if credentials are expired with no refresh token', async () => {
// Set up expired credentials WITHOUT refresh token
// We still return them - it's up to the caller to handle
const expiredCredentials: AuthCredentials = {
token: 'expired_access_token',
refreshToken: undefined,
@@ -104,19 +141,17 @@ describe('AuthManager Token Refresh', () => {
credentialStore.saveCredentials(expiredCredentials);
const credentials = authManager.getCredentials();
const credentials = await authManager.getCredentials();
// Returns credentials even if expired
expect(credentials).not.toBeNull();
expect(credentials?.token).toBe('expired_access_token');
});
it('should return null if no credentials exist', () => {
const credentials = authManager.getCredentials();
expect(credentials).toBeNull();
});
it('should return credentials regardless of refresh token validity', () => {
it('should return null if no credentials exist', async () => {
const credentials = await authManager.getCredentials();
expect(credentials).toBeNull();
});
it('should handle refresh failures gracefully', async () => {
// Set up expired credentials with refresh token
const expiredCredentials: AuthCredentials = {
token: 'expired_access_token',
@@ -129,11 +164,13 @@ describe('AuthManager Token Refresh', () => {
credentialStore.saveCredentials(expiredCredentials);
const credentials = authManager.getCredentials();
// Mock refreshToken to throw an error
const refreshTokenSpy = vi.spyOn(authManager as any, 'refreshToken');
refreshTokenSpy.mockRejectedValue(new Error('Refresh failed'));
// Returns credentials - refresh will be attempted by the client which will handle failure
expect(credentials).not.toBeNull();
expect(credentials?.token).toBe('expired_access_token');
expect(credentials?.refreshToken).toBe('invalid_refresh_token');
const credentials = await authManager.getCredentials();
expect(credentials).toBeNull();
expect(refreshTokenSpy).toHaveBeenCalledTimes(1);
});
});

View File

@@ -76,7 +76,7 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
});
describe('Expired Token Detection', () => {
it('should return expired token for Supabase to refresh', () => {
it('should detect expired token', async () => {
// Set up expired credentials
const expiredCredentials: AuthCredentials = {
token: 'expired-token',
@@ -91,15 +91,24 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
// Get credentials returns them even if expired
const credentials = authManager.getCredentials();
// Mock the Supabase refreshSession to return new tokens
const mockRefreshSession = vi
.fn()
.mockResolvedValue(mockRefreshedSession);
vi.spyOn(
authManager['supabaseClient'],
'refreshSession'
).mockImplementation(mockRefreshSession);
// Get credentials should trigger refresh
const credentials = await authManager.getCredentials();
expect(mockRefreshSession).toHaveBeenCalledTimes(1);
expect(credentials).not.toBeNull();
expect(credentials?.token).toBe('expired-token');
expect(credentials?.refreshToken).toBe('valid-refresh-token');
expect(credentials?.token).toBe('new-access-token-xyz');
});
it('should return valid token', () => {
it('should not refresh valid token', async () => {
// Set up valid credentials
const validCredentials: AuthCredentials = {
token: 'valid-token',
@@ -114,14 +123,22 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
const credentials = authManager.getCredentials();
// Mock refresh to ensure it's not called
const mockRefreshSession = vi.fn();
vi.spyOn(
authManager['supabaseClient'],
'refreshSession'
).mockImplementation(mockRefreshSession);
const credentials = await authManager.getCredentials();
expect(mockRefreshSession).not.toHaveBeenCalled();
expect(credentials?.token).toBe('valid-token');
});
});
describe('Token Refresh Flow', () => {
it('should manually refresh expired token and save new credentials', async () => {
it('should refresh expired token and save new credentials', async () => {
const expiredCredentials: AuthCredentials = {
token: 'old-token',
refreshToken: 'old-refresh-token',
@@ -145,24 +162,23 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
'refreshSession'
).mockResolvedValue(mockRefreshedSession);
// Explicitly call refreshToken() method
const refreshedCredentials = await authManager.refreshToken();
const refreshedCredentials = await authManager.getCredentials();
expect(refreshedCredentials).not.toBeNull();
expect(refreshedCredentials.token).toBe('new-access-token-xyz');
expect(refreshedCredentials.refreshToken).toBe('new-refresh-token-xyz');
expect(refreshedCredentials?.token).toBe('new-access-token-xyz');
expect(refreshedCredentials?.refreshToken).toBe('new-refresh-token-xyz');
// Verify context was preserved
expect(refreshedCredentials.selectedContext?.orgId).toBe('test-org');
expect(refreshedCredentials.selectedContext?.briefId).toBe('test-brief');
expect(refreshedCredentials?.selectedContext?.orgId).toBe('test-org');
expect(refreshedCredentials?.selectedContext?.briefId).toBe('test-brief');
// Verify new expiration is in the future
const newExpiry = new Date(refreshedCredentials.expiresAt!).getTime();
const newExpiry = new Date(refreshedCredentials!.expiresAt!).getTime();
const now = Date.now();
expect(newExpiry).toBeGreaterThan(now);
});
it('should throw error if manual refresh fails', async () => {
it('should return null if refresh fails', async () => {
const expiredCredentials: AuthCredentials = {
token: 'expired-token',
refreshToken: 'invalid-refresh-token',
@@ -182,11 +198,12 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
'refreshSession'
).mockRejectedValue(new Error('Refresh token expired'));
// Explicit refreshToken() call should throw
await expect(authManager.refreshToken()).rejects.toThrow();
const credentials = await authManager.getCredentials();
expect(credentials).toBeNull();
});
it('should return expired credentials even without refresh token', () => {
it('should return null if no refresh token available', async () => {
const expiredCredentials: AuthCredentials = {
token: 'expired-token',
// No refresh token
@@ -200,21 +217,18 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
const credentials = authManager.getCredentials();
const credentials = await authManager.getCredentials();
// Credentials are returned even without refresh token
expect(credentials).not.toBeNull();
expect(credentials?.token).toBe('expired-token');
expect(credentials?.refreshToken).toBeUndefined();
expect(credentials).toBeNull();
});
it('should return null if credentials missing expiresAt', () => {
it('should return null if credentials missing expiresAt', async () => {
const credentialsWithoutExpiry: AuthCredentials = {
token: 'test-token',
refreshToken: 'refresh-token',
userId: 'test-user-id',
email: 'test@example.com',
// Missing expiresAt - invalid token
// Missing expiresAt
savedAt: new Date().toISOString()
} as any;
@@ -222,17 +236,16 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
const credentials = authManager.getCredentials();
const credentials = await authManager.getCredentials();
// Tokens without valid expiration are considered invalid
// Should return null because no valid expiration
expect(credentials).toBeNull();
});
});
describe('Clock Skew Tolerance', () => {
it('should return credentials within 30-second expiry window', () => {
it('should refresh token within 30-second expiry window', async () => {
// Token expires in 15 seconds (within 30-second buffer)
// Supabase will handle refresh automatically
const almostExpiredCredentials: AuthCredentials = {
token: 'almost-expired-token',
refreshToken: 'valid-refresh-token',
@@ -246,16 +259,23 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
const credentials = authManager.getCredentials();
const mockRefreshSession = vi
.fn()
.mockResolvedValue(mockRefreshedSession);
vi.spyOn(
authManager['supabaseClient'],
'refreshSession'
).mockImplementation(mockRefreshSession);
// Credentials are returned (Supabase handles auto-refresh in background)
expect(credentials).not.toBeNull();
expect(credentials?.token).toBe('almost-expired-token');
expect(credentials?.refreshToken).toBe('valid-refresh-token');
const credentials = await authManager.getCredentials();
// Should trigger refresh due to 30-second buffer
expect(mockRefreshSession).toHaveBeenCalledTimes(1);
expect(credentials?.token).toBe('new-access-token-xyz');
});
it('should return valid token well before expiry', () => {
// Token expires in 5 minutes
it('should not refresh token well before expiry', async () => {
// Token expires in 5 minutes (well outside 30-second buffer)
const validCredentials: AuthCredentials = {
token: 'valid-token',
refreshToken: 'valid-refresh-token',
@@ -269,17 +289,21 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
const credentials = authManager.getCredentials();
const mockRefreshSession = vi.fn();
vi.spyOn(
authManager['supabaseClient'],
'refreshSession'
).mockImplementation(mockRefreshSession);
// Valid credentials are returned as-is
expect(credentials).not.toBeNull();
const credentials = await authManager.getCredentials();
expect(mockRefreshSession).not.toHaveBeenCalled();
expect(credentials?.token).toBe('valid-token');
expect(credentials?.refreshToken).toBe('valid-refresh-token');
});
});
describe('Synchronous vs Async Methods', () => {
it('getCredentials should return expired credentials', () => {
it('getCredentialsSync should not trigger refresh', () => {
const expiredCredentials: AuthCredentials = {
token: 'expired-token',
refreshToken: 'valid-refresh-token',
@@ -293,17 +317,40 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
// Returns credentials even if expired - Supabase will handle refresh
const credentials = authManager.getCredentials();
// Synchronous call should return null without refresh
const credentials = authManager.getCredentialsSync();
expect(credentials).toBeNull();
});
it('getCredentials async should trigger refresh', async () => {
const expiredCredentials: AuthCredentials = {
token: 'expired-token',
refreshToken: 'valid-refresh-token',
userId: 'test-user-id',
email: 'test@example.com',
expiresAt: new Date(Date.now() - 60000).toISOString(),
savedAt: new Date().toISOString()
};
credentialStore.saveCredentials(expiredCredentials);
authManager = AuthManager.getInstance();
vi.spyOn(
authManager['supabaseClient'],
'refreshSession'
).mockResolvedValue(mockRefreshedSession);
const credentials = await authManager.getCredentials();
expect(credentials).not.toBeNull();
expect(credentials?.token).toBe('expired-token');
expect(credentials?.refreshToken).toBe('valid-refresh-token');
expect(credentials?.token).toBe('new-access-token-xyz');
});
});
describe('Multiple Concurrent Calls', () => {
it('should handle concurrent getCredentials calls gracefully', () => {
it('should handle concurrent getCredentials calls gracefully', async () => {
const expiredCredentials: AuthCredentials = {
token: 'expired-token',
refreshToken: 'valid-refresh-token',
@@ -317,20 +364,29 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
authManager = AuthManager.getInstance();
// Make multiple concurrent calls (synchronous now)
const creds1 = authManager.getCredentials();
const creds2 = authManager.getCredentials();
const creds3 = authManager.getCredentials();
const mockRefreshSession = vi
.fn()
.mockResolvedValue(mockRefreshedSession);
vi.spyOn(
authManager['supabaseClient'],
'refreshSession'
).mockImplementation(mockRefreshSession);
// All should get the same credentials (even if expired)
expect(creds1?.token).toBe('expired-token');
expect(creds2?.token).toBe('expired-token');
expect(creds3?.token).toBe('expired-token');
// Make multiple concurrent calls
const [creds1, creds2, creds3] = await Promise.all([
authManager.getCredentials(),
authManager.getCredentials(),
authManager.getCredentials()
]);
// All include refresh token for Supabase to use
expect(creds1?.refreshToken).toBe('valid-refresh-token');
expect(creds2?.refreshToken).toBe('valid-refresh-token');
expect(creds3?.refreshToken).toBe('valid-refresh-token');
// All should get the refreshed token
expect(creds1?.token).toBe('new-access-token-xyz');
expect(creds2?.token).toBe('new-access-token-xyz');
expect(creds3?.token).toBe('new-access-token-xyz');
// Refresh might be called multiple times, but that's okay
// (ideally we'd debounce, but this is acceptable behavior)
expect(mockRefreshSession).toHaveBeenCalled();
});
});
});

View File

@@ -307,20 +307,6 @@ function validateProviderModelCombination(providerName, modelId) {
);
}
/**
* Gets the list of supported model IDs for a given provider from supported-models.json
* @param {string} providerName - The name of the provider (e.g., 'claude-code', 'anthropic')
* @returns {string[]} Array of supported model IDs, or empty array if provider not found
*/
export function getSupportedModelsForProvider(providerName) {
if (!MODEL_MAP[providerName]) {
return [];
}
return MODEL_MAP[providerName]
.filter((model) => model.supported !== false)
.map((model) => model.id);
}
/**
* Validates Claude Code AI provider custom settings
* @param {object} settings The settings to validate

View File

@@ -43,28 +43,6 @@
"allowed_roles": ["main", "fallback"],
"max_tokens": 8192,
"supported": true
},
{
"id": "claude-sonnet-4-5-20250929",
"swe_score": 0.73,
"cost_per_1m_tokens": {
"input": 3.0,
"output": 15.0
},
"allowed_roles": ["main", "fallback"],
"max_tokens": 64000,
"supported": true
},
{
"id": "claude-haiku-4-5-20251001",
"swe_score": 0.45,
"cost_per_1m_tokens": {
"input": 1.0,
"output": 5.0
},
"allowed_roles": ["main", "fallback"],
"max_tokens": 200000,
"supported": true
}
],
"claude-code": [
@@ -89,17 +67,6 @@
"allowed_roles": ["main", "fallback", "research"],
"max_tokens": 64000,
"supported": true
},
{
"id": "haiku",
"swe_score": 0.45,
"cost_per_1m_tokens": {
"input": 0,
"output": 0
},
"allowed_roles": ["main", "fallback", "research"],
"max_tokens": 200000,
"supported": true
}
],
"codex-cli": [

View File

@@ -12,10 +12,7 @@
import { createClaudeCode } from 'ai-sdk-provider-claude-code';
import { BaseAIProvider } from './base-provider.js';
import {
getClaudeCodeSettingsForCommand,
getSupportedModelsForProvider
} from '../../scripts/modules/config-manager.js';
import { getClaudeCodeSettingsForCommand } from '../../scripts/modules/config-manager.js';
import { execSync } from 'child_process';
import { log } from '../../scripts/modules/utils.js';
@@ -27,24 +24,14 @@ let _claudeCliAvailable = null;
*
* Features:
* - No API key required (uses local Claude Code CLI)
* - Supported models loaded from supported-models.json
* - Supports 'sonnet' and 'opus' models
* - Command-specific configuration support
*/
export class ClaudeCodeProvider extends BaseAIProvider {
constructor() {
super();
this.name = 'Claude Code';
// Load supported models from supported-models.json
this.supportedModels = getSupportedModelsForProvider('claude-code');
// Validate that models were loaded successfully
if (this.supportedModels.length === 0) {
log(
'warn',
'No supported models found for claude-code provider. Check supported-models.json configuration.'
);
}
this.supportedModels = ['sonnet', 'opus'];
// Claude Code requires explicit JSON schema mode
this.needsExplicitJsonSchema = true;
// Claude Code does not support temperature parameter

View File

@@ -10,10 +10,7 @@ import { createCodexCli } from 'ai-sdk-provider-codex-cli';
import { BaseAIProvider } from './base-provider.js';
import { execSync } from 'child_process';
import { log } from '../../scripts/modules/utils.js';
import {
getCodexCliSettingsForCommand,
getSupportedModelsForProvider
} from '../../scripts/modules/config-manager.js';
import { getCodexCliSettingsForCommand } from '../../scripts/modules/config-manager.js';
export class CodexCliProvider extends BaseAIProvider {
constructor() {
@@ -23,17 +20,8 @@ export class CodexCliProvider extends BaseAIProvider {
this.needsExplicitJsonSchema = false;
// Codex CLI does not support temperature parameter
this.supportsTemperature = false;
// Load supported models from supported-models.json
this.supportedModels = getSupportedModelsForProvider('codex-cli');
// Validate that models were loaded successfully
if (this.supportedModels.length === 0) {
log(
'warn',
'No supported models found for codex-cli provider. Check supported-models.json configuration.'
);
}
// Restrict to supported models for OAuth subscription usage
this.supportedModels = ['gpt-5', 'gpt-5-codex'];
// CLI availability check cache
this._codexCliChecked = false;
this._codexCliAvailable = null;

View File

@@ -43,9 +43,9 @@ describe('Claude Code Error Handling', () => {
// These should work even if CLI is not available
expect(provider.name).toBe('Claude Code');
expect(provider.getSupportedModels()).toEqual(['opus', 'sonnet', 'haiku']);
expect(provider.getSupportedModels()).toEqual(['sonnet', 'opus']);
expect(provider.isModelSupported('sonnet')).toBe(true);
expect(provider.isModelSupported('haiku')).toBe(true);
expect(provider.isModelSupported('haiku')).toBe(false);
expect(provider.isRequiredApiKey()).toBe(false);
expect(() => provider.validateAuth()).not.toThrow();
});

View File

@@ -40,14 +40,14 @@ describe('Claude Code Integration (Optional)', () => {
it('should create a working provider instance', () => {
const provider = new ClaudeCodeProvider();
expect(provider.name).toBe('Claude Code');
expect(provider.getSupportedModels()).toEqual(['opus', 'sonnet', 'haiku']);
expect(provider.getSupportedModels()).toEqual(['sonnet', 'opus']);
});
it('should support model validation', () => {
const provider = new ClaudeCodeProvider();
expect(provider.isModelSupported('sonnet')).toBe(true);
expect(provider.isModelSupported('opus')).toBe(true);
expect(provider.isModelSupported('haiku')).toBe(true);
expect(provider.isModelSupported('haiku')).toBe(false);
expect(provider.isModelSupported('unknown')).toBe(false);
});

View File

@@ -28,14 +28,6 @@ jest.unstable_mockModule('../../../src/ai-providers/base-provider.js', () => ({
}
}));
// Mock config getters
jest.unstable_mockModule('../../../scripts/modules/config-manager.js', () => ({
getClaudeCodeSettingsForCommand: jest.fn(() => ({})),
getSupportedModelsForProvider: jest.fn(() => ['opus', 'sonnet', 'haiku']),
getDebugFlag: jest.fn(() => false),
getLogLevel: jest.fn(() => 'info')
}));
// Import after mocking
const { ClaudeCodeProvider } = await import(
'../../../src/ai-providers/claude-code.js'
@@ -104,13 +96,13 @@ describe('ClaudeCodeProvider', () => {
describe('model support', () => {
it('should return supported models', () => {
const models = provider.getSupportedModels();
expect(models).toEqual(['opus', 'sonnet', 'haiku']);
expect(models).toEqual(['sonnet', 'opus']);
});
it('should check if model is supported', () => {
expect(provider.isModelSupported('sonnet')).toBe(true);
expect(provider.isModelSupported('opus')).toBe(true);
expect(provider.isModelSupported('haiku')).toBe(true);
expect(provider.isModelSupported('haiku')).toBe(false);
expect(provider.isModelSupported('unknown')).toBe(false);
});
});

View File

@@ -20,7 +20,6 @@ jest.unstable_mockModule('ai-sdk-provider-codex-cli', () => ({
// Mock config getters
jest.unstable_mockModule('../../../scripts/modules/config-manager.js', () => ({
getCodexCliSettingsForCommand: jest.fn(() => ({ allowNpx: true })),
getSupportedModelsForProvider: jest.fn(() => ['gpt-5', 'gpt-5-codex']),
// Provide commonly imported getters to satisfy other module imports if any
getDebugFlag: jest.fn(() => false),
getLogLevel: jest.fn(() => 'info')