Compare commits
1 Commits
ralph/feat
...
docs/auto-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
74997468de |
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
"task-master-ai": patch
|
|
||||||
---
|
|
||||||
|
|
||||||
Improve auth token refresh flow
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
---
|
|
||||||
"task-master-ai": minor
|
|
||||||
---
|
|
||||||
|
|
||||||
Add 4.5 haiku and sonnet to supported models for claude-code and anthropic ai providers
|
|
||||||
@@ -143,7 +143,7 @@ export class AuthCommand extends Command {
|
|||||||
*/
|
*/
|
||||||
private async executeStatus(): Promise<void> {
|
private async executeStatus(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const result = this.displayStatus();
|
const result = await this.displayStatus();
|
||||||
this.setLastResult(result);
|
this.setLastResult(result);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
this.handleError(error);
|
this.handleError(error);
|
||||||
@@ -171,8 +171,8 @@ export class AuthCommand extends Command {
|
|||||||
/**
|
/**
|
||||||
* Display authentication status
|
* Display authentication status
|
||||||
*/
|
*/
|
||||||
private displayStatus(): AuthResult {
|
private async displayStatus(): Promise<AuthResult> {
|
||||||
const credentials = this.authManager.getCredentials();
|
const credentials = await this.authManager.getCredentials();
|
||||||
|
|
||||||
console.log(chalk.cyan('\n🔐 Authentication Status\n'));
|
console.log(chalk.cyan('\n🔐 Authentication Status\n'));
|
||||||
|
|
||||||
@@ -325,7 +325,7 @@ export class AuthCommand extends Command {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
if (!continueAuth) {
|
if (!continueAuth) {
|
||||||
const credentials = this.authManager.getCredentials();
|
const credentials = await this.authManager.getCredentials();
|
||||||
ui.displaySuccess('Using existing authentication');
|
ui.displaySuccess('Using existing authentication');
|
||||||
|
|
||||||
if (credentials) {
|
if (credentials) {
|
||||||
@@ -490,7 +490,7 @@ export class AuthCommand extends Command {
|
|||||||
/**
|
/**
|
||||||
* Get current credentials (for programmatic usage)
|
* Get current credentials (for programmatic usage)
|
||||||
*/
|
*/
|
||||||
getCredentials(): AuthCredentials | null {
|
getCredentials(): Promise<AuthCredentials | null> {
|
||||||
return this.authManager.getCredentials();
|
return this.authManager.getCredentials();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ export class ContextCommand extends Command {
|
|||||||
*/
|
*/
|
||||||
private async executeShow(): Promise<void> {
|
private async executeShow(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const result = this.displayContext();
|
const result = await this.displayContext();
|
||||||
this.setLastResult(result);
|
this.setLastResult(result);
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
this.handleError(error);
|
this.handleError(error);
|
||||||
@@ -126,7 +126,7 @@ export class ContextCommand extends Command {
|
|||||||
/**
|
/**
|
||||||
* Display current context
|
* Display current context
|
||||||
*/
|
*/
|
||||||
private displayContext(): ContextResult {
|
private async displayContext(): Promise<ContextResult> {
|
||||||
// Check authentication first
|
// Check authentication first
|
||||||
if (!this.authManager.isAuthenticated()) {
|
if (!this.authManager.isAuthenticated()) {
|
||||||
console.log(chalk.yellow('✗ Not authenticated'));
|
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'));
|
console.log(chalk.cyan('\n🌍 Workspace Context\n'));
|
||||||
|
|
||||||
@@ -250,7 +250,7 @@ export class ContextCommand extends Command {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
// Update context
|
// Update context
|
||||||
this.authManager.updateContext({
|
await this.authManager.updateContext({
|
||||||
orgId: selectedOrg.id,
|
orgId: selectedOrg.id,
|
||||||
orgName: selectedOrg.name,
|
orgName: selectedOrg.name,
|
||||||
// Clear brief when changing org
|
// Clear brief when changing org
|
||||||
@@ -263,7 +263,7 @@ export class ContextCommand extends Command {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
action: 'select-org',
|
action: 'select-org',
|
||||||
context: this.authManager.getContext() || undefined,
|
context: (await this.authManager.getContext()) || undefined,
|
||||||
message: `Selected organization: ${selectedOrg.name}`
|
message: `Selected organization: ${selectedOrg.name}`
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -284,7 +284,7 @@ export class ContextCommand extends Command {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if org is selected
|
// Check if org is selected
|
||||||
const context = this.authManager.getContext();
|
const context = await this.authManager.getContext();
|
||||||
if (!context?.orgId) {
|
if (!context?.orgId) {
|
||||||
ui.displayError(
|
ui.displayError(
|
||||||
'No organization selected. Run "tm context org" first.'
|
'No organization selected. Run "tm context org" first.'
|
||||||
@@ -343,7 +343,7 @@ export class ContextCommand extends Command {
|
|||||||
if (selectedBrief) {
|
if (selectedBrief) {
|
||||||
// Update context with brief
|
// Update context with brief
|
||||||
const briefName = `Brief ${selectedBrief.id.slice(0, 8)}`;
|
const briefName = `Brief ${selectedBrief.id.slice(0, 8)}`;
|
||||||
this.authManager.updateContext({
|
await this.authManager.updateContext({
|
||||||
briefId: selectedBrief.id,
|
briefId: selectedBrief.id,
|
||||||
briefName: briefName
|
briefName: briefName
|
||||||
});
|
});
|
||||||
@@ -353,12 +353,12 @@ export class ContextCommand extends Command {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
action: 'select-brief',
|
action: 'select-brief',
|
||||||
context: this.authManager.getContext() || undefined,
|
context: (await this.authManager.getContext()) || undefined,
|
||||||
message: `Selected brief: ${selectedBrief.name}`
|
message: `Selected brief: ${selectedBrief.name}`
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
// Clear brief selection
|
// Clear brief selection
|
||||||
this.authManager.updateContext({
|
await this.authManager.updateContext({
|
||||||
briefId: undefined,
|
briefId: undefined,
|
||||||
briefName: undefined
|
briefName: undefined
|
||||||
});
|
});
|
||||||
@@ -368,7 +368,7 @@ export class ContextCommand extends Command {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
action: 'select-brief',
|
action: 'select-brief',
|
||||||
context: this.authManager.getContext() || undefined,
|
context: (await this.authManager.getContext()) || undefined,
|
||||||
message: 'Cleared brief selection'
|
message: 'Cleared brief selection'
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -491,7 +491,7 @@ export class ContextCommand extends Command {
|
|||||||
|
|
||||||
// Update context: set org and brief
|
// Update context: set org and brief
|
||||||
const briefName = `Brief ${brief.id.slice(0, 8)}`;
|
const briefName = `Brief ${brief.id.slice(0, 8)}`;
|
||||||
this.authManager.updateContext({
|
await this.authManager.updateContext({
|
||||||
orgId: brief.accountId,
|
orgId: brief.accountId,
|
||||||
orgName,
|
orgName,
|
||||||
briefId: brief.id,
|
briefId: brief.id,
|
||||||
@@ -508,7 +508,7 @@ export class ContextCommand extends Command {
|
|||||||
this.setLastResult({
|
this.setLastResult({
|
||||||
success: true,
|
success: true,
|
||||||
action: 'set',
|
action: 'set',
|
||||||
context: this.authManager.getContext() || undefined,
|
context: (await this.authManager.getContext()) || undefined,
|
||||||
message: 'Context set from brief'
|
message: 'Context set from brief'
|
||||||
});
|
});
|
||||||
} catch (error: any) {
|
} 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');
|
ui.displaySuccess('Context updated');
|
||||||
|
|
||||||
// Display what was set
|
// Display what was set
|
||||||
@@ -631,7 +631,7 @@ export class ContextCommand extends Command {
|
|||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
action: 'set',
|
action: 'set',
|
||||||
context: this.authManager.getContext() || undefined,
|
context: (await this.authManager.getContext()) || undefined,
|
||||||
message: 'Context updated'
|
message: 'Context updated'
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -682,7 +682,7 @@ export class ContextCommand extends Command {
|
|||||||
/**
|
/**
|
||||||
* Get current context (for programmatic usage)
|
* Get current context (for programmatic usage)
|
||||||
*/
|
*/
|
||||||
getContext(): UserContext | null {
|
getContext(): Promise<UserContext | null> {
|
||||||
return this.authManager.getContext();
|
return this.authManager.getContext();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,18 @@ sidebarTitle: "CLI Commands"
|
|||||||
```bash
|
```bash
|
||||||
# Show the next task to work on based on dependencies and status
|
# Show the next task to work on based on dependencies and status
|
||||||
task-master next
|
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>
|
</Accordion>
|
||||||
|
|
||||||
|
|||||||
30
output.txt
Normal file
30
output.txt
Normal file
File diff suppressed because one or more lines are too long
@@ -35,7 +35,7 @@ vi.mock('./credential-store.js', () => {
|
|||||||
}
|
}
|
||||||
saveCredentials() {}
|
saveCredentials() {}
|
||||||
clearCredentials() {}
|
clearCredentials() {}
|
||||||
hasCredentials() {
|
hasValidCredentials() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,8 @@ export class AuthManager {
|
|||||||
private oauthService: OAuthService;
|
private oauthService: OAuthService;
|
||||||
private supabaseClient: SupabaseAuthClient;
|
private supabaseClient: SupabaseAuthClient;
|
||||||
private organizationService?: OrganizationService;
|
private organizationService?: OrganizationService;
|
||||||
|
private logger = getLogger('AuthManager');
|
||||||
|
private refreshPromise: Promise<AuthCredentials> | null = null;
|
||||||
|
|
||||||
private constructor(config?: Partial<AuthConfig>) {
|
private constructor(config?: Partial<AuthConfig>) {
|
||||||
this.credentialStore = CredentialStore.getInstance(config);
|
this.credentialStore = CredentialStore.getInstance(config);
|
||||||
@@ -81,10 +83,60 @@ export class AuthManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get stored authentication credentials
|
* Get stored authentication credentials
|
||||||
* Returns credentials as-is (even if expired). Refresh must be triggered explicitly
|
* Automatically refreshes the token if expired
|
||||||
* via refreshToken() or will occur automatically when using the Supabase client for API calls.
|
|
||||||
*/
|
*/
|
||||||
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();
|
return this.credentialStore.getCredentials();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,26 +219,25 @@ export class AuthManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if authenticated (credentials exist, regardless of expiration)
|
* Check if authenticated
|
||||||
* @returns true if credentials are stored, including expired credentials
|
|
||||||
*/
|
*/
|
||||||
isAuthenticated(): boolean {
|
isAuthenticated(): boolean {
|
||||||
return this.credentialStore.hasCredentials();
|
return this.credentialStore.hasValidCredentials();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get the current user context (org/brief selection)
|
* Get the current user context (org/brief selection)
|
||||||
*/
|
*/
|
||||||
getContext(): UserContext | null {
|
async getContext(): Promise<UserContext | null> {
|
||||||
const credentials = this.getCredentials();
|
const credentials = await this.getCredentials();
|
||||||
return credentials?.selectedContext || null;
|
return credentials?.selectedContext || null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the user context (org/brief selection)
|
* Update the user context (org/brief selection)
|
||||||
*/
|
*/
|
||||||
updateContext(context: Partial<UserContext>): void {
|
async updateContext(context: Partial<UserContext>): Promise<void> {
|
||||||
const credentials = this.getCredentials();
|
const credentials = await this.getCredentials();
|
||||||
if (!credentials) {
|
if (!credentials) {
|
||||||
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
|
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
|
||||||
}
|
}
|
||||||
@@ -211,8 +262,8 @@ export class AuthManager {
|
|||||||
/**
|
/**
|
||||||
* Clear the user context
|
* Clear the user context
|
||||||
*/
|
*/
|
||||||
clearContext(): void {
|
async clearContext(): Promise<void> {
|
||||||
const credentials = this.getCredentials();
|
const credentials = await this.getCredentials();
|
||||||
if (!credentials) {
|
if (!credentials) {
|
||||||
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
|
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
|
||||||
}
|
}
|
||||||
@@ -229,7 +280,7 @@ export class AuthManager {
|
|||||||
private async getOrganizationService(): Promise<OrganizationService> {
|
private async getOrganizationService(): Promise<OrganizationService> {
|
||||||
if (!this.organizationService) {
|
if (!this.organizationService) {
|
||||||
// First check if we have credentials with a token
|
// First check if we have credentials with a token
|
||||||
const credentials = this.getCredentials();
|
const credentials = await this.getCredentials();
|
||||||
if (!credentials || !credentials.token) {
|
if (!credentials || !credentials.token) {
|
||||||
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
|
throw new AuthenticationError('Not authenticated', 'NOT_AUTHENTICATED');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(expiredCredentials);
|
credentialStore.saveCredentials(expiredCredentials);
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).toBeNull();
|
expect(retrieved).toBeNull();
|
||||||
});
|
});
|
||||||
@@ -69,7 +69,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(validCredentials);
|
credentialStore.saveCredentials(validCredentials);
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).not.toBeNull();
|
expect(retrieved).not.toBeNull();
|
||||||
expect(retrieved?.token).toBe('valid-token');
|
expect(retrieved?.token).toBe('valid-token');
|
||||||
@@ -92,25 +92,6 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
expect(retrieved).not.toBeNull();
|
expect(retrieved).not.toBeNull();
|
||||||
expect(retrieved?.token).toBe('expired-token');
|
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', () => {
|
describe('Clock Skew Tolerance', () => {
|
||||||
@@ -127,7 +108,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(almostExpiredCredentials);
|
credentialStore.saveCredentials(almostExpiredCredentials);
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).toBeNull();
|
expect(retrieved).toBeNull();
|
||||||
});
|
});
|
||||||
@@ -145,7 +126,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(validCredentials);
|
credentialStore.saveCredentials(validCredentials);
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).not.toBeNull();
|
expect(retrieved).not.toBeNull();
|
||||||
expect(retrieved?.token).toBe('valid-token');
|
expect(retrieved?.token).toBe('valid-token');
|
||||||
@@ -165,7 +146,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(credentials);
|
credentialStore.saveCredentials(credentials);
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).not.toBeNull();
|
expect(retrieved).not.toBeNull();
|
||||||
expect(typeof retrieved?.expiresAt).toBe('number'); // Normalized to number
|
expect(typeof retrieved?.expiresAt).toBe('number'); // Normalized to number
|
||||||
@@ -183,7 +164,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(credentials);
|
credentialStore.saveCredentials(credentials);
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).not.toBeNull();
|
expect(retrieved).not.toBeNull();
|
||||||
expect(typeof retrieved?.expiresAt).toBe('number');
|
expect(typeof retrieved?.expiresAt).toBe('number');
|
||||||
@@ -204,7 +185,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
mode: 0o600
|
mode: 0o600
|
||||||
});
|
});
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).toBeNull();
|
expect(retrieved).toBeNull();
|
||||||
});
|
});
|
||||||
@@ -222,7 +203,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
mode: 0o600
|
mode: 0o600
|
||||||
});
|
});
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
expect(retrieved).toBeNull();
|
expect(retrieved).toBeNull();
|
||||||
});
|
});
|
||||||
@@ -263,15 +244,15 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(credentials);
|
credentialStore.saveCredentials(credentials);
|
||||||
|
|
||||||
const retrieved = credentialStore.getCredentials({ allowExpired: false });
|
const retrieved = credentialStore.getCredentials();
|
||||||
|
|
||||||
// Should be normalized to number for runtime use
|
// Should be normalized to number for runtime use
|
||||||
expect(typeof retrieved?.expiresAt).toBe('number');
|
expect(typeof retrieved?.expiresAt).toBe('number');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('hasCredentials', () => {
|
describe('hasValidCredentials', () => {
|
||||||
it('should return true for expired credentials', () => {
|
it('should return false for expired credentials', () => {
|
||||||
const expiredCredentials: AuthCredentials = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired-token',
|
token: 'expired-token',
|
||||||
refreshToken: 'refresh-token',
|
refreshToken: 'refresh-token',
|
||||||
@@ -283,7 +264,7 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(expiredCredentials);
|
credentialStore.saveCredentials(expiredCredentials);
|
||||||
|
|
||||||
expect(credentialStore.hasCredentials()).toBe(true);
|
expect(credentialStore.hasValidCredentials()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return true for valid credentials', () => {
|
it('should return true for valid credentials', () => {
|
||||||
@@ -298,11 +279,11 @@ describe('CredentialStore - Token Expiration', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(validCredentials);
|
credentialStore.saveCredentials(validCredentials);
|
||||||
|
|
||||||
expect(credentialStore.hasCredentials()).toBe(true);
|
expect(credentialStore.hasValidCredentials()).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return false when no credentials exist', () => {
|
it('should return false when no credentials exist', () => {
|
||||||
expect(credentialStore.hasCredentials()).toBe(false);
|
expect(credentialStore.hasValidCredentials()).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -197,7 +197,7 @@ describe('CredentialStore', () => {
|
|||||||
JSON.stringify(mockCredentials)
|
JSON.stringify(mockCredentials)
|
||||||
);
|
);
|
||||||
|
|
||||||
const result = store.getCredentials({ allowExpired: false });
|
const result = store.getCredentials();
|
||||||
|
|
||||||
expect(result).toBeNull();
|
expect(result).toBeNull();
|
||||||
expect(mockLogger.warn).toHaveBeenCalledWith(
|
expect(mockLogger.warn).toHaveBeenCalledWith(
|
||||||
@@ -226,31 +226,6 @@ describe('CredentialStore', () => {
|
|||||||
expect(result).not.toBeNull();
|
expect(result).not.toBeNull();
|
||||||
expect(result?.token).toBe('expired-token');
|
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', () => {
|
describe('saveCredentials with timestamp normalization', () => {
|
||||||
@@ -476,7 +451,7 @@ describe('CredentialStore', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('hasCredentials', () => {
|
describe('hasValidCredentials', () => {
|
||||||
it('should return true when valid unexpired credentials exist', () => {
|
it('should return true when valid unexpired credentials exist', () => {
|
||||||
const futureDate = new Date(Date.now() + 3600000); // 1 hour from now
|
const futureDate = new Date(Date.now() + 3600000); // 1 hour from now
|
||||||
const credentials = {
|
const credentials = {
|
||||||
@@ -490,10 +465,10 @@ describe('CredentialStore', () => {
|
|||||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||||
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(credentials));
|
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 pastDate = new Date(Date.now() - 3600000); // 1 hour ago
|
||||||
const credentials = {
|
const credentials = {
|
||||||
token: 'expired-token',
|
token: 'expired-token',
|
||||||
@@ -506,13 +481,13 @@ describe('CredentialStore', () => {
|
|||||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
vi.mocked(fs.existsSync).mockReturnValue(true);
|
||||||
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(credentials));
|
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', () => {
|
it('should return false when no credentials exist', () => {
|
||||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
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', () => {
|
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.readFileSync).mockReturnValue('invalid json {');
|
||||||
vi.mocked(fs.renameSync).mockImplementation(() => undefined);
|
vi.mocked(fs.renameSync).mockImplementation(() => undefined);
|
||||||
|
|
||||||
expect(store.hasCredentials()).toBe(false);
|
expect(store.hasValidCredentials()).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return false for credentials without expiry', () => {
|
it('should return false for credentials without expiry', () => {
|
||||||
@@ -535,7 +510,7 @@ describe('CredentialStore', () => {
|
|||||||
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(credentials));
|
vi.mocked(fs.readFileSync).mockReturnValue(JSON.stringify(credentials));
|
||||||
|
|
||||||
// Credentials without expiry are considered invalid
|
// Credentials without expiry are considered invalid
|
||||||
expect(store.hasCredentials()).toBe(false);
|
expect(store.hasValidCredentials()).toBe(false);
|
||||||
|
|
||||||
// Should log warning about missing expiration
|
// Should log warning about missing expiration
|
||||||
expect(mockLogger.warn).toHaveBeenCalledWith(
|
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
|
// Spy on getCredentials to verify it's called with correct params
|
||||||
const getCredentialsSpy = vi.spyOn(store, 'getCredentials');
|
const getCredentialsSpy = vi.spyOn(store, 'getCredentials');
|
||||||
|
|
||||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||||
store.hasCredentials();
|
store.hasValidCredentials();
|
||||||
|
|
||||||
expect(getCredentialsSpy).toHaveBeenCalledWith({ allowExpired: true });
|
expect(getCredentialsSpy).toHaveBeenCalledWith({ allowExpired: false });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -54,12 +54,9 @@ export class CredentialStore {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Get stored authentication credentials
|
* Get stored authentication credentials
|
||||||
* @param options.allowExpired - Whether to return expired credentials (default: true)
|
|
||||||
* @returns AuthCredentials with expiresAt as number (milliseconds) for runtime use
|
* @returns AuthCredentials with expiresAt as number (milliseconds) for runtime use
|
||||||
*/
|
*/
|
||||||
getCredentials({
|
getCredentials(options?: { allowExpired?: boolean }): AuthCredentials | null {
|
||||||
allowExpired = true
|
|
||||||
}: { allowExpired?: boolean } = {}): AuthCredentials | null {
|
|
||||||
try {
|
try {
|
||||||
if (!fs.existsSync(this.config.configFile)) {
|
if (!fs.existsSync(this.config.configFile)) {
|
||||||
return null;
|
return null;
|
||||||
@@ -93,6 +90,7 @@ export class CredentialStore {
|
|||||||
|
|
||||||
// Check if the token has expired (with clock skew tolerance)
|
// Check if the token has expired (with clock skew tolerance)
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
const allowExpired = options?.allowExpired ?? false;
|
||||||
if (now >= expiresAtMs - this.CLOCK_SKEW_MS && !allowExpired) {
|
if (now >= expiresAtMs - this.CLOCK_SKEW_MS && !allowExpired) {
|
||||||
this.logger.warn(
|
this.logger.warn(
|
||||||
'Authentication token has expired or is about to expire',
|
'Authentication token has expired or is about to expire',
|
||||||
@@ -105,7 +103,7 @@ export class CredentialStore {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return credentials (even if expired) to enable refresh flows
|
// Return valid token
|
||||||
return authData;
|
return authData;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(
|
this.logger.error(
|
||||||
@@ -201,11 +199,10 @@ export class CredentialStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if credentials exist (regardless of expiration status)
|
* Check if credentials exist and are valid
|
||||||
* @returns true if credentials are stored, including expired credentials
|
|
||||||
*/
|
*/
|
||||||
hasCredentials(): boolean {
|
hasValidCredentials(): boolean {
|
||||||
const credentials = this.getCredentials({ allowExpired: true });
|
const credentials = this.getCredentials({ allowExpired: false });
|
||||||
return credentials !== null;
|
return credentials !== null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -281,26 +281,15 @@ export class OAuthService {
|
|||||||
// Exchange code for session using PKCE
|
// Exchange code for session using PKCE
|
||||||
const session = await this.supabaseClient.exchangeCodeForSession(code);
|
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
|
// Save authentication data
|
||||||
const authData: AuthCredentials = {
|
const authData: AuthCredentials = {
|
||||||
token: session.access_token,
|
token: session.access_token,
|
||||||
refreshToken: session.refresh_token,
|
refreshToken: session.refresh_token,
|
||||||
userId: session.user.id,
|
userId: session.user.id,
|
||||||
email: session.user.email,
|
email: session.user.email,
|
||||||
expiresAt,
|
expiresAt: session.expires_at
|
||||||
|
? new Date(session.expires_at * 1000).toISOString()
|
||||||
|
: undefined,
|
||||||
tokenType: 'standard',
|
tokenType: 'standard',
|
||||||
savedAt: new Date().toISOString()
|
savedAt: new Date().toISOString()
|
||||||
};
|
};
|
||||||
@@ -351,18 +340,10 @@ export class OAuthService {
|
|||||||
// Get user info from the session
|
// Get user info from the session
|
||||||
const user = await this.supabaseClient.getUser();
|
const user = await this.supabaseClient.getUser();
|
||||||
|
|
||||||
// Calculate expiration time - can be overridden with TM_TOKEN_EXPIRY_MINUTES
|
// Calculate expiration time
|
||||||
let expiresAt: string | undefined;
|
const expiresAt = expiresIn
|
||||||
const tokenExpiryMinutes = process.env.TM_TOKEN_EXPIRY_MINUTES;
|
? new Date(Date.now() + parseInt(expiresIn) * 1000).toISOString()
|
||||||
if (tokenExpiryMinutes) {
|
: undefined;
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Save authentication data
|
// Save authentication data
|
||||||
const authData: AuthCredentials = {
|
const authData: AuthCredentials = {
|
||||||
@@ -370,7 +351,7 @@ export class OAuthService {
|
|||||||
refreshToken: refreshToken || undefined,
|
refreshToken: refreshToken || undefined,
|
||||||
userId: user?.id || 'unknown',
|
userId: user?.id || 'unknown',
|
||||||
email: user?.email,
|
email: user?.email,
|
||||||
expiresAt,
|
expiresAt: expiresAt,
|
||||||
tokenType: 'standard',
|
tokenType: 'standard',
|
||||||
savedAt: new Date().toISOString()
|
savedAt: new Date().toISOString()
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -98,11 +98,11 @@ export class SupabaseSessionStorage implements SupportedStorage {
|
|||||||
// Only handle Supabase session keys
|
// Only handle Supabase session keys
|
||||||
if (key === STORAGE_KEY || key.includes('auth-token')) {
|
if (key === STORAGE_KEY || key.includes('auth-token')) {
|
||||||
try {
|
try {
|
||||||
this.logger.info('Supabase called setItem - storing refreshed session');
|
|
||||||
|
|
||||||
// Parse the session and update our credentials
|
// Parse the session and update our credentials
|
||||||
const sessionUpdates = this.parseSessionToCredentials(value);
|
const sessionUpdates = this.parseSessionToCredentials(value);
|
||||||
const existingCredentials = this.store.getCredentials();
|
const existingCredentials = this.store.getCredentials({
|
||||||
|
allowExpired: true
|
||||||
|
});
|
||||||
|
|
||||||
if (sessionUpdates.token) {
|
if (sessionUpdates.token) {
|
||||||
const updatedCredentials: AuthCredentials = {
|
const updatedCredentials: AuthCredentials = {
|
||||||
@@ -113,9 +113,6 @@ export class SupabaseSessionStorage implements SupportedStorage {
|
|||||||
} as AuthCredentials;
|
} as AuthCredentials;
|
||||||
|
|
||||||
this.store.saveCredentials(updatedCredentials);
|
this.store.saveCredentials(updatedCredentials);
|
||||||
this.logger.info(
|
|
||||||
'Successfully saved refreshed credentials from Supabase'
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error('Error setting session:', error);
|
this.logger.error('Error setting session:', error);
|
||||||
|
|||||||
@@ -17,11 +17,10 @@ export class SupabaseAuthClient {
|
|||||||
private client: SupabaseJSClient | null = null;
|
private client: SupabaseJSClient | null = null;
|
||||||
private sessionStorage: SupabaseSessionStorage;
|
private sessionStorage: SupabaseSessionStorage;
|
||||||
private logger = getLogger('SupabaseAuthClient');
|
private logger = getLogger('SupabaseAuthClient');
|
||||||
private credentialStore: CredentialStore;
|
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.credentialStore = CredentialStore.getInstance();
|
const credentialStore = CredentialStore.getInstance();
|
||||||
this.sessionStorage = new SupabaseSessionStorage(this.credentialStore);
|
this.sessionStorage = new SupabaseSessionStorage(credentialStore);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export class StorageFactory {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
// Use auth token from AuthManager (synchronous - no auto-refresh here)
|
// Use auth token from AuthManager (synchronous - no auto-refresh here)
|
||||||
const credentials = authManager.getCredentials();
|
const credentials = authManager.getCredentialsSync();
|
||||||
if (credentials) {
|
if (credentials) {
|
||||||
// Merge with existing storage config, ensuring required fields
|
// Merge with existing storage config, ensuring required fields
|
||||||
const nextStorage: StorageSettings = {
|
const nextStorage: StorageSettings = {
|
||||||
@@ -103,7 +103,7 @@ export class StorageFactory {
|
|||||||
|
|
||||||
// Then check if authenticated via AuthManager
|
// Then check if authenticated via AuthManager
|
||||||
if (authManager.isAuthenticated()) {
|
if (authManager.isAuthenticated()) {
|
||||||
const credentials = authManager.getCredentials();
|
const credentials = authManager.getCredentialsSync();
|
||||||
if (credentials) {
|
if (credentials) {
|
||||||
// Configure API storage with auth credentials
|
// Configure API storage with auth credentials
|
||||||
const nextStorage: StorageSettings = {
|
const nextStorage: StorageSettings = {
|
||||||
|
|||||||
@@ -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
|
// Set up expired credentials with refresh token
|
||||||
const expiredCredentials: AuthCredentials = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired_access_token',
|
token: 'expired_access_token',
|
||||||
@@ -63,16 +63,50 @@ describe('AuthManager Token Refresh', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(expiredCredentials);
|
credentialStore.saveCredentials(expiredCredentials);
|
||||||
|
|
||||||
// Get credentials should return them even if expired
|
// Mock the refreshToken method to track calls
|
||||||
// Refresh will be handled by explicit calls or client operations
|
const refreshTokenSpy = vi.spyOn(authManager as any, 'refreshToken');
|
||||||
const credentials = authManager.getCredentials();
|
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();
|
refreshTokenSpy.mockResolvedValue({
|
||||||
expect(credentials?.token).toBe('expired_access_token');
|
token: mockSession.access_token,
|
||||||
expect(credentials?.refreshToken).toBe('valid_refresh_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
|
// Set up valid (non-expired) credentials
|
||||||
const validCredentials: AuthCredentials = {
|
const validCredentials: AuthCredentials = {
|
||||||
token: 'valid_access_token',
|
token: 'valid_access_token',
|
||||||
@@ -85,14 +119,17 @@ describe('AuthManager Token Refresh', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(validCredentials);
|
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(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
|
// Set up expired credentials WITHOUT refresh token
|
||||||
// We still return them - it's up to the caller to handle
|
|
||||||
const expiredCredentials: AuthCredentials = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired_access_token',
|
token: 'expired_access_token',
|
||||||
refreshToken: undefined,
|
refreshToken: undefined,
|
||||||
@@ -104,19 +141,17 @@ describe('AuthManager Token Refresh', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(expiredCredentials);
|
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();
|
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
|
// Set up expired credentials with refresh token
|
||||||
const expiredCredentials: AuthCredentials = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired_access_token',
|
token: 'expired_access_token',
|
||||||
@@ -129,11 +164,13 @@ describe('AuthManager Token Refresh', () => {
|
|||||||
|
|
||||||
credentialStore.saveCredentials(expiredCredentials);
|
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
|
const credentials = await authManager.getCredentials();
|
||||||
expect(credentials).not.toBeNull();
|
|
||||||
expect(credentials?.token).toBe('expired_access_token');
|
expect(credentials).toBeNull();
|
||||||
expect(credentials?.refreshToken).toBe('invalid_refresh_token');
|
expect(refreshTokenSpy).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -76,7 +76,7 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('Expired Token Detection', () => {
|
describe('Expired Token Detection', () => {
|
||||||
it('should return expired token for Supabase to refresh', () => {
|
it('should detect expired token', async () => {
|
||||||
// Set up expired credentials
|
// Set up expired credentials
|
||||||
const expiredCredentials: AuthCredentials = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired-token',
|
token: 'expired-token',
|
||||||
@@ -91,15 +91,24 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
authManager = AuthManager.getInstance();
|
||||||
|
|
||||||
// Get credentials returns them even if expired
|
// Mock the Supabase refreshSession to return new tokens
|
||||||
const credentials = authManager.getCredentials();
|
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).not.toBeNull();
|
||||||
expect(credentials?.token).toBe('expired-token');
|
expect(credentials?.token).toBe('new-access-token-xyz');
|
||||||
expect(credentials?.refreshToken).toBe('valid-refresh-token');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return valid token', () => {
|
it('should not refresh valid token', async () => {
|
||||||
// Set up valid credentials
|
// Set up valid credentials
|
||||||
const validCredentials: AuthCredentials = {
|
const validCredentials: AuthCredentials = {
|
||||||
token: 'valid-token',
|
token: 'valid-token',
|
||||||
@@ -114,14 +123,22 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
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');
|
expect(credentials?.token).toBe('valid-token');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Token Refresh Flow', () => {
|
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 = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'old-token',
|
token: 'old-token',
|
||||||
refreshToken: 'old-refresh-token',
|
refreshToken: 'old-refresh-token',
|
||||||
@@ -145,24 +162,23 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
'refreshSession'
|
'refreshSession'
|
||||||
).mockResolvedValue(mockRefreshedSession);
|
).mockResolvedValue(mockRefreshedSession);
|
||||||
|
|
||||||
// Explicitly call refreshToken() method
|
const refreshedCredentials = await authManager.getCredentials();
|
||||||
const refreshedCredentials = await authManager.refreshToken();
|
|
||||||
|
|
||||||
expect(refreshedCredentials).not.toBeNull();
|
expect(refreshedCredentials).not.toBeNull();
|
||||||
expect(refreshedCredentials.token).toBe('new-access-token-xyz');
|
expect(refreshedCredentials?.token).toBe('new-access-token-xyz');
|
||||||
expect(refreshedCredentials.refreshToken).toBe('new-refresh-token-xyz');
|
expect(refreshedCredentials?.refreshToken).toBe('new-refresh-token-xyz');
|
||||||
|
|
||||||
// Verify context was preserved
|
// Verify context was preserved
|
||||||
expect(refreshedCredentials.selectedContext?.orgId).toBe('test-org');
|
expect(refreshedCredentials?.selectedContext?.orgId).toBe('test-org');
|
||||||
expect(refreshedCredentials.selectedContext?.briefId).toBe('test-brief');
|
expect(refreshedCredentials?.selectedContext?.briefId).toBe('test-brief');
|
||||||
|
|
||||||
// Verify new expiration is in the future
|
// 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();
|
const now = Date.now();
|
||||||
expect(newExpiry).toBeGreaterThan(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 = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired-token',
|
token: 'expired-token',
|
||||||
refreshToken: 'invalid-refresh-token',
|
refreshToken: 'invalid-refresh-token',
|
||||||
@@ -182,11 +198,12 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
'refreshSession'
|
'refreshSession'
|
||||||
).mockRejectedValue(new Error('Refresh token expired'));
|
).mockRejectedValue(new Error('Refresh token expired'));
|
||||||
|
|
||||||
// Explicit refreshToken() call should throw
|
const credentials = await authManager.getCredentials();
|
||||||
await expect(authManager.refreshToken()).rejects.toThrow();
|
|
||||||
|
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 = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired-token',
|
token: 'expired-token',
|
||||||
// No refresh token
|
// No refresh token
|
||||||
@@ -200,21 +217,18 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
authManager = AuthManager.getInstance();
|
||||||
|
|
||||||
const credentials = authManager.getCredentials();
|
const credentials = await authManager.getCredentials();
|
||||||
|
|
||||||
// Credentials are returned even without refresh token
|
expect(credentials).toBeNull();
|
||||||
expect(credentials).not.toBeNull();
|
|
||||||
expect(credentials?.token).toBe('expired-token');
|
|
||||||
expect(credentials?.refreshToken).toBeUndefined();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return null if credentials missing expiresAt', () => {
|
it('should return null if credentials missing expiresAt', async () => {
|
||||||
const credentialsWithoutExpiry: AuthCredentials = {
|
const credentialsWithoutExpiry: AuthCredentials = {
|
||||||
token: 'test-token',
|
token: 'test-token',
|
||||||
refreshToken: 'refresh-token',
|
refreshToken: 'refresh-token',
|
||||||
userId: 'test-user-id',
|
userId: 'test-user-id',
|
||||||
email: 'test@example.com',
|
email: 'test@example.com',
|
||||||
// Missing expiresAt - invalid token
|
// Missing expiresAt
|
||||||
savedAt: new Date().toISOString()
|
savedAt: new Date().toISOString()
|
||||||
} as any;
|
} as any;
|
||||||
|
|
||||||
@@ -222,17 +236,16 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
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();
|
expect(credentials).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Clock Skew Tolerance', () => {
|
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)
|
// Token expires in 15 seconds (within 30-second buffer)
|
||||||
// Supabase will handle refresh automatically
|
|
||||||
const almostExpiredCredentials: AuthCredentials = {
|
const almostExpiredCredentials: AuthCredentials = {
|
||||||
token: 'almost-expired-token',
|
token: 'almost-expired-token',
|
||||||
refreshToken: 'valid-refresh-token',
|
refreshToken: 'valid-refresh-token',
|
||||||
@@ -246,16 +259,23 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
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)
|
const credentials = await authManager.getCredentials();
|
||||||
expect(credentials).not.toBeNull();
|
|
||||||
expect(credentials?.token).toBe('almost-expired-token');
|
// Should trigger refresh due to 30-second buffer
|
||||||
expect(credentials?.refreshToken).toBe('valid-refresh-token');
|
expect(mockRefreshSession).toHaveBeenCalledTimes(1);
|
||||||
|
expect(credentials?.token).toBe('new-access-token-xyz');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should return valid token well before expiry', () => {
|
it('should not refresh token well before expiry', async () => {
|
||||||
// Token expires in 5 minutes
|
// Token expires in 5 minutes (well outside 30-second buffer)
|
||||||
const validCredentials: AuthCredentials = {
|
const validCredentials: AuthCredentials = {
|
||||||
token: 'valid-token',
|
token: 'valid-token',
|
||||||
refreshToken: 'valid-refresh-token',
|
refreshToken: 'valid-refresh-token',
|
||||||
@@ -269,17 +289,21 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
authManager = AuthManager.getInstance();
|
||||||
|
|
||||||
const credentials = authManager.getCredentials();
|
const mockRefreshSession = vi.fn();
|
||||||
|
vi.spyOn(
|
||||||
|
authManager['supabaseClient'],
|
||||||
|
'refreshSession'
|
||||||
|
).mockImplementation(mockRefreshSession);
|
||||||
|
|
||||||
// Valid credentials are returned as-is
|
const credentials = await authManager.getCredentials();
|
||||||
expect(credentials).not.toBeNull();
|
|
||||||
|
expect(mockRefreshSession).not.toHaveBeenCalled();
|
||||||
expect(credentials?.token).toBe('valid-token');
|
expect(credentials?.token).toBe('valid-token');
|
||||||
expect(credentials?.refreshToken).toBe('valid-refresh-token');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Synchronous vs Async Methods', () => {
|
describe('Synchronous vs Async Methods', () => {
|
||||||
it('getCredentials should return expired credentials', () => {
|
it('getCredentialsSync should not trigger refresh', () => {
|
||||||
const expiredCredentials: AuthCredentials = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired-token',
|
token: 'expired-token',
|
||||||
refreshToken: 'valid-refresh-token',
|
refreshToken: 'valid-refresh-token',
|
||||||
@@ -293,17 +317,40 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
authManager = AuthManager.getInstance();
|
||||||
|
|
||||||
// Returns credentials even if expired - Supabase will handle refresh
|
// Synchronous call should return null without refresh
|
||||||
const credentials = authManager.getCredentials();
|
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).not.toBeNull();
|
||||||
expect(credentials?.token).toBe('expired-token');
|
expect(credentials?.token).toBe('new-access-token-xyz');
|
||||||
expect(credentials?.refreshToken).toBe('valid-refresh-token');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Multiple Concurrent Calls', () => {
|
describe('Multiple Concurrent Calls', () => {
|
||||||
it('should handle concurrent getCredentials calls gracefully', () => {
|
it('should handle concurrent getCredentials calls gracefully', async () => {
|
||||||
const expiredCredentials: AuthCredentials = {
|
const expiredCredentials: AuthCredentials = {
|
||||||
token: 'expired-token',
|
token: 'expired-token',
|
||||||
refreshToken: 'valid-refresh-token',
|
refreshToken: 'valid-refresh-token',
|
||||||
@@ -317,20 +364,29 @@ describe('AuthManager - Token Auto-Refresh Integration', () => {
|
|||||||
|
|
||||||
authManager = AuthManager.getInstance();
|
authManager = AuthManager.getInstance();
|
||||||
|
|
||||||
// Make multiple concurrent calls (synchronous now)
|
const mockRefreshSession = vi
|
||||||
const creds1 = authManager.getCredentials();
|
.fn()
|
||||||
const creds2 = authManager.getCredentials();
|
.mockResolvedValue(mockRefreshedSession);
|
||||||
const creds3 = authManager.getCredentials();
|
vi.spyOn(
|
||||||
|
authManager['supabaseClient'],
|
||||||
|
'refreshSession'
|
||||||
|
).mockImplementation(mockRefreshSession);
|
||||||
|
|
||||||
// All should get the same credentials (even if expired)
|
// Make multiple concurrent calls
|
||||||
expect(creds1?.token).toBe('expired-token');
|
const [creds1, creds2, creds3] = await Promise.all([
|
||||||
expect(creds2?.token).toBe('expired-token');
|
authManager.getCredentials(),
|
||||||
expect(creds3?.token).toBe('expired-token');
|
authManager.getCredentials(),
|
||||||
|
authManager.getCredentials()
|
||||||
|
]);
|
||||||
|
|
||||||
// All include refresh token for Supabase to use
|
// All should get the refreshed token
|
||||||
expect(creds1?.refreshToken).toBe('valid-refresh-token');
|
expect(creds1?.token).toBe('new-access-token-xyz');
|
||||||
expect(creds2?.refreshToken).toBe('valid-refresh-token');
|
expect(creds2?.token).toBe('new-access-token-xyz');
|
||||||
expect(creds3?.refreshToken).toBe('valid-refresh-token');
|
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();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -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
|
* Validates Claude Code AI provider custom settings
|
||||||
* @param {object} settings The settings to validate
|
* @param {object} settings The settings to validate
|
||||||
|
|||||||
@@ -43,28 +43,6 @@
|
|||||||
"allowed_roles": ["main", "fallback"],
|
"allowed_roles": ["main", "fallback"],
|
||||||
"max_tokens": 8192,
|
"max_tokens": 8192,
|
||||||
"supported": true
|
"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": [
|
"claude-code": [
|
||||||
@@ -89,17 +67,6 @@
|
|||||||
"allowed_roles": ["main", "fallback", "research"],
|
"allowed_roles": ["main", "fallback", "research"],
|
||||||
"max_tokens": 64000,
|
"max_tokens": 64000,
|
||||||
"supported": true
|
"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": [
|
"codex-cli": [
|
||||||
|
|||||||
@@ -12,10 +12,7 @@
|
|||||||
|
|
||||||
import { createClaudeCode } from 'ai-sdk-provider-claude-code';
|
import { createClaudeCode } from 'ai-sdk-provider-claude-code';
|
||||||
import { BaseAIProvider } from './base-provider.js';
|
import { BaseAIProvider } from './base-provider.js';
|
||||||
import {
|
import { getClaudeCodeSettingsForCommand } from '../../scripts/modules/config-manager.js';
|
||||||
getClaudeCodeSettingsForCommand,
|
|
||||||
getSupportedModelsForProvider
|
|
||||||
} from '../../scripts/modules/config-manager.js';
|
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
import { log } from '../../scripts/modules/utils.js';
|
import { log } from '../../scripts/modules/utils.js';
|
||||||
|
|
||||||
@@ -27,24 +24,14 @@ let _claudeCliAvailable = null;
|
|||||||
*
|
*
|
||||||
* Features:
|
* Features:
|
||||||
* - No API key required (uses local Claude Code CLI)
|
* - 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
|
* - Command-specific configuration support
|
||||||
*/
|
*/
|
||||||
export class ClaudeCodeProvider extends BaseAIProvider {
|
export class ClaudeCodeProvider extends BaseAIProvider {
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
this.name = 'Claude Code';
|
this.name = 'Claude Code';
|
||||||
// Load supported models from supported-models.json
|
this.supportedModels = ['sonnet', 'opus'];
|
||||||
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.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Claude Code requires explicit JSON schema mode
|
// Claude Code requires explicit JSON schema mode
|
||||||
this.needsExplicitJsonSchema = true;
|
this.needsExplicitJsonSchema = true;
|
||||||
// Claude Code does not support temperature parameter
|
// Claude Code does not support temperature parameter
|
||||||
|
|||||||
@@ -10,10 +10,7 @@ import { createCodexCli } from 'ai-sdk-provider-codex-cli';
|
|||||||
import { BaseAIProvider } from './base-provider.js';
|
import { BaseAIProvider } from './base-provider.js';
|
||||||
import { execSync } from 'child_process';
|
import { execSync } from 'child_process';
|
||||||
import { log } from '../../scripts/modules/utils.js';
|
import { log } from '../../scripts/modules/utils.js';
|
||||||
import {
|
import { getCodexCliSettingsForCommand } from '../../scripts/modules/config-manager.js';
|
||||||
getCodexCliSettingsForCommand,
|
|
||||||
getSupportedModelsForProvider
|
|
||||||
} from '../../scripts/modules/config-manager.js';
|
|
||||||
|
|
||||||
export class CodexCliProvider extends BaseAIProvider {
|
export class CodexCliProvider extends BaseAIProvider {
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -23,17 +20,8 @@ export class CodexCliProvider extends BaseAIProvider {
|
|||||||
this.needsExplicitJsonSchema = false;
|
this.needsExplicitJsonSchema = false;
|
||||||
// Codex CLI does not support temperature parameter
|
// Codex CLI does not support temperature parameter
|
||||||
this.supportsTemperature = false;
|
this.supportsTemperature = false;
|
||||||
// Load supported models from supported-models.json
|
// Restrict to supported models for OAuth subscription usage
|
||||||
this.supportedModels = getSupportedModelsForProvider('codex-cli');
|
this.supportedModels = ['gpt-5', 'gpt-5-codex'];
|
||||||
|
|
||||||
// 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.'
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// CLI availability check cache
|
// CLI availability check cache
|
||||||
this._codexCliChecked = false;
|
this._codexCliChecked = false;
|
||||||
this._codexCliAvailable = null;
|
this._codexCliAvailable = null;
|
||||||
|
|||||||
@@ -43,9 +43,9 @@ describe('Claude Code Error Handling', () => {
|
|||||||
|
|
||||||
// These should work even if CLI is not available
|
// These should work even if CLI is not available
|
||||||
expect(provider.name).toBe('Claude Code');
|
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('sonnet')).toBe(true);
|
||||||
expect(provider.isModelSupported('haiku')).toBe(true);
|
expect(provider.isModelSupported('haiku')).toBe(false);
|
||||||
expect(provider.isRequiredApiKey()).toBe(false);
|
expect(provider.isRequiredApiKey()).toBe(false);
|
||||||
expect(() => provider.validateAuth()).not.toThrow();
|
expect(() => provider.validateAuth()).not.toThrow();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -40,14 +40,14 @@ describe('Claude Code Integration (Optional)', () => {
|
|||||||
it('should create a working provider instance', () => {
|
it('should create a working provider instance', () => {
|
||||||
const provider = new ClaudeCodeProvider();
|
const provider = new ClaudeCodeProvider();
|
||||||
expect(provider.name).toBe('Claude Code');
|
expect(provider.name).toBe('Claude Code');
|
||||||
expect(provider.getSupportedModels()).toEqual(['opus', 'sonnet', 'haiku']);
|
expect(provider.getSupportedModels()).toEqual(['sonnet', 'opus']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should support model validation', () => {
|
it('should support model validation', () => {
|
||||||
const provider = new ClaudeCodeProvider();
|
const provider = new ClaudeCodeProvider();
|
||||||
expect(provider.isModelSupported('sonnet')).toBe(true);
|
expect(provider.isModelSupported('sonnet')).toBe(true);
|
||||||
expect(provider.isModelSupported('opus')).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);
|
expect(provider.isModelSupported('unknown')).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
// Import after mocking
|
||||||
const { ClaudeCodeProvider } = await import(
|
const { ClaudeCodeProvider } = await import(
|
||||||
'../../../src/ai-providers/claude-code.js'
|
'../../../src/ai-providers/claude-code.js'
|
||||||
@@ -104,13 +96,13 @@ describe('ClaudeCodeProvider', () => {
|
|||||||
describe('model support', () => {
|
describe('model support', () => {
|
||||||
it('should return supported models', () => {
|
it('should return supported models', () => {
|
||||||
const models = provider.getSupportedModels();
|
const models = provider.getSupportedModels();
|
||||||
expect(models).toEqual(['opus', 'sonnet', 'haiku']);
|
expect(models).toEqual(['sonnet', 'opus']);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should check if model is supported', () => {
|
it('should check if model is supported', () => {
|
||||||
expect(provider.isModelSupported('sonnet')).toBe(true);
|
expect(provider.isModelSupported('sonnet')).toBe(true);
|
||||||
expect(provider.isModelSupported('opus')).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);
|
expect(provider.isModelSupported('unknown')).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ jest.unstable_mockModule('ai-sdk-provider-codex-cli', () => ({
|
|||||||
// Mock config getters
|
// Mock config getters
|
||||||
jest.unstable_mockModule('../../../scripts/modules/config-manager.js', () => ({
|
jest.unstable_mockModule('../../../scripts/modules/config-manager.js', () => ({
|
||||||
getCodexCliSettingsForCommand: jest.fn(() => ({ allowNpx: true })),
|
getCodexCliSettingsForCommand: jest.fn(() => ({ allowNpx: true })),
|
||||||
getSupportedModelsForProvider: jest.fn(() => ['gpt-5', 'gpt-5-codex']),
|
|
||||||
// Provide commonly imported getters to satisfy other module imports if any
|
// Provide commonly imported getters to satisfy other module imports if any
|
||||||
getDebugFlag: jest.fn(() => false),
|
getDebugFlag: jest.fn(() => false),
|
||||||
getLogLevel: jest.fn(() => 'info')
|
getLogLevel: jest.fn(() => 'info')
|
||||||
|
|||||||
Reference in New Issue
Block a user