|
1 | | - |
2 | | - |
3 | | -import { AuthInfo, Connection } from '@salesforce/core'; |
| 1 | +import { Connection, Org } from '@salesforce/core'; |
4 | 2 | import { LogLevel } from '@salesforce/code-analyzer-engine-api'; |
5 | | -import { AuthConfig } from '../types'; |
6 | | - |
7 | | -/** |
8 | | - * TEMPORARY: Hardcoded credentials for testing |
9 | | - * TODO: Implement SF CLI, env vars, and OAuth in future PR |
10 | | - * NEVER commit real credentials - use 'YOUR_ACCESS_TOKEN_HERE' as placeholder |
11 | | - */ |
12 | | -const HARDCODED_ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN_HERE'; // Get from: sf org display --verbose |
13 | | -const HARDCODED_INSTANCE_URL = 'https://yourorg.my.salesforce.com'; // e.g., https://yourorg.my.salesforce.com |
| 3 | +import { AuthConfig, OrgJwtResponse } from '../types'; |
14 | 4 |
|
15 | 5 | /** |
16 | | - * Handles authentication to Salesforce orgs for ApexGuru API access |
17 | | - * TODO: Currently uses hardcoded credentials only. Implement proper auth in future PR. |
| 6 | + * Handles authentication to Salesforce orgs for ApexGuru API access. |
18 | 7 | */ |
19 | 8 | export class ApexGuruAuthService { |
| 9 | + // Configuration constants |
| 10 | + private static readonly DEFAULT_FEATURE_ID = 'CodeAnalyzer'; |
| 11 | + private static readonly ORG_JWT_ENDPOINT_PATH = '/ide/auth'; |
| 12 | + |
20 | 13 | private connection?: Connection; |
| 14 | + private orgJwt?: string; |
21 | 15 | private readonly emitLogEvent: (logLevel: LogLevel, message: string) => void; |
22 | 16 |
|
23 | 17 | constructor(emitLogEvent: (logLevel: LogLevel, message: string) => void = () => {}) { |
24 | 18 | this.emitLogEvent = emitLogEvent; |
25 | 19 | } |
26 | 20 |
|
27 | 21 | /** |
28 | | - * Initialize connection to Salesforce org |
29 | | - * TODO: Implement SF CLI, env vars, and OAuth in future PR |
30 | | - * @param _config - Auth configuration (currently unused, for future implementation) |
| 22 | + * Initialize connection to Salesforce org using one of two methods: |
| 23 | + * |
| 24 | + * Method 1: SF CLI org with --target-org flag |
| 25 | + * config.targetOrg = 'myorg' or 'user@example.com' |
| 26 | + * |
| 27 | + * Method 2: SF CLI default org (fallback) |
| 28 | + * No config provided - uses SF CLI default org |
| 29 | + * |
| 30 | + * @param config - Auth configuration |
31 | 31 | */ |
32 | | - async initialize(_config: AuthConfig): Promise<void> { |
33 | | - // Use hardcoded credentials (temporary implementation) |
34 | | - this.emitLogEvent(LogLevel.Warn, '⚠️ Using HARDCODED authentication credentials (for testing)'); |
| 32 | + async initialize(config: AuthConfig): Promise<void> { |
| 33 | + // Method 1: SF CLI org (alias or username) via --target-org flag |
| 34 | + if (config.targetOrg) { |
| 35 | + this.emitLogEvent(LogLevel.Fine, `Authenticating with org: ${config.targetOrg}`); |
| 36 | + try { |
| 37 | + const org = await Org.create({ aliasOrUsername: config.targetOrg }); |
| 38 | + this.connection = org.getConnection(); |
| 39 | + this.emitLogEvent(LogLevel.Fine, `Successfully authenticated to org`); |
| 40 | + return; |
| 41 | + } catch { |
| 42 | + this.emitLogEvent(LogLevel.Error, `Failed to authenticate with org: ${config.targetOrg}`); |
| 43 | + throw new Error( |
| 44 | + `Failed to authenticate with org '${config.targetOrg}'. ` + |
| 45 | + 'Please verify the org alias/username and ensure you are authenticated:\n' + |
| 46 | + ' sf org list\n' + |
| 47 | + ' sf org login web' |
| 48 | + ); |
| 49 | + } |
| 50 | + } |
35 | 51 |
|
36 | | - // Validate that credentials were actually set |
37 | | - if (!HARDCODED_ACCESS_TOKEN || HARDCODED_ACCESS_TOKEN.includes('YOUR_ACCESS_TOKEN')) { |
| 52 | + // Method 2: SF CLI default org (fallback) |
| 53 | + this.emitLogEvent(LogLevel.Fine, 'No target org specified, using default org'); |
| 54 | + try { |
| 55 | + const org = await Org.create({}); |
| 56 | + this.connection = org.getConnection(); |
| 57 | + this.emitLogEvent(LogLevel.Fine, 'Successfully authenticated to default org'); |
| 58 | + } catch { |
| 59 | + this.emitLogEvent(LogLevel.Error, 'Failed to authenticate: No default org found'); |
38 | 60 | throw new Error( |
39 | | - 'Hardcoded credentials not set! Edit ApexGuruAuthService.ts and set:\n' + |
40 | | - ' - HARDCODED_ACCESS_TOKEN (get from: sf org display --verbose)\n' + |
41 | | - ' - HARDCODED_INSTANCE_URL (e.g., https://yourorg.my.salesforce.com)' |
| 61 | + 'No default org found. Please either:\n' + |
| 62 | + ' 1. Set a default org: sf config set target-org <org-alias>\n' + |
| 63 | + ' 2. Pass --target-org flag: sf code-analyzer run --target-org <org-alias> ...\n' + |
| 64 | + ' 3. Authenticate to an org: sf org login web' |
42 | 65 | ); |
43 | 66 | } |
44 | | - |
45 | | - this.connection = await Connection.create({ |
46 | | - authInfo: await AuthInfo.create({ |
47 | | - accessTokenOptions: { |
48 | | - accessToken: HARDCODED_ACCESS_TOKEN, |
49 | | - instanceUrl: HARDCODED_INSTANCE_URL |
50 | | - } |
51 | | - }) |
52 | | - }); |
53 | 67 | } |
54 | 68 |
|
55 | 69 | /** |
@@ -86,4 +100,95 @@ export class ApexGuruAuthService { |
86 | 100 | getApiVersion(): string { |
87 | 101 | return this.getConnection().version || '64.0'; |
88 | 102 | } |
| 103 | + |
| 104 | + /** |
| 105 | + * Helper method to perform fetch with logging |
| 106 | + * @param endpoint - The endpoint URL |
| 107 | + * @param logMessage - Log message to emit before fetch |
| 108 | + * @param options - Fetch options |
| 109 | + * @returns Promise<Response> - The fetch response |
| 110 | + */ |
| 111 | + private async fetchWithLogging( |
| 112 | + endpoint: string, |
| 113 | + logMessage: string, |
| 114 | + options: RequestInit |
| 115 | + ): Promise<Response> { |
| 116 | + this.emitLogEvent(LogLevel.Fine, logMessage); |
| 117 | + return await fetch(endpoint, options); |
| 118 | + } |
| 119 | + |
| 120 | + /** |
| 121 | + * Mint an Org JWT token for SFAP API access |
| 122 | + * |
| 123 | + * @param featureId - Feature ID for tracking (default: CodeAnalyzer) |
| 124 | + * @returns Promise<string> - The Org JWT token |
| 125 | + * @throws Error if minting fails |
| 126 | + */ |
| 127 | + async mintOrgJwt(featureId: string = ApexGuruAuthService.DEFAULT_FEATURE_ID): Promise<string> { |
| 128 | + const accessToken = this.getAccessToken(); |
| 129 | + const instanceUrl = this.getInstanceUrl(); |
| 130 | + const endpoint = `${instanceUrl}${ApexGuruAuthService.ORG_JWT_ENDPOINT_PATH}`; |
| 131 | + |
| 132 | + const response = await this.fetchWithLogging( |
| 133 | + endpoint, |
| 134 | + 'Minting Org JWT for SFAP API access', |
| 135 | + { |
| 136 | + method: 'POST', |
| 137 | + headers: { |
| 138 | + 'Accept': 'application/json', |
| 139 | + 'Authorization': `Bearer ${accessToken}`, |
| 140 | + 'X-Feature-Id': featureId, |
| 141 | + 'Content-Type': 'application/json' |
| 142 | + } |
| 143 | + } |
| 144 | + ); |
| 145 | + |
| 146 | + try { |
| 147 | + |
| 148 | + if (!response.ok) { |
| 149 | + const errorText = await response.text(); |
| 150 | + this.emitLogEvent(LogLevel.Error, `Failed to mint Org JWT: HTTP ${response.status}`); |
| 151 | + throw new Error( |
| 152 | + `Failed to mint Org JWT: ${response.status} ${response.statusText}. ` + |
| 153 | + `Response: ${errorText}` |
| 154 | + ); |
| 155 | + } |
| 156 | + |
| 157 | + const data = await response.json() as OrgJwtResponse; |
| 158 | + |
| 159 | + if (!data.jwt) { |
| 160 | + this.emitLogEvent(LogLevel.Error, 'Org JWT response missing jwt field'); |
| 161 | + throw new Error('Org JWT response missing jwt field'); |
| 162 | + } |
| 163 | + |
| 164 | + this.orgJwt = data.jwt; |
| 165 | + this.emitLogEvent(LogLevel.Fine, 'Successfully minted Org JWT'); |
| 166 | + return data.jwt; |
| 167 | + |
| 168 | + } catch (error) { |
| 169 | + const errorMessage = error instanceof Error ? error.message : String(error); |
| 170 | + this.emitLogEvent(LogLevel.Error, 'Org JWT minting failed'); |
| 171 | + throw new Error(`Org JWT minting failed: ${errorMessage}`); |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + /** |
| 176 | + * Get the cached Org JWT token |
| 177 | + * @returns The Org JWT if available, undefined otherwise |
| 178 | + */ |
| 179 | + getOrgJwt(): string | undefined { |
| 180 | + return this.orgJwt; |
| 181 | + } |
| 182 | + |
| 183 | + /** |
| 184 | + * Get or mint the Org JWT token |
| 185 | + * If already minted, returns the cached token. Otherwise, mints a new one. |
| 186 | + * @returns Promise<string> - The Org JWT token |
| 187 | + */ |
| 188 | + async getOrMintOrgJwt(): Promise<string> { |
| 189 | + if (this.orgJwt) { |
| 190 | + return this.orgJwt; |
| 191 | + } |
| 192 | + return await this.mintOrgJwt(); |
| 193 | + } |
89 | 194 | } |
0 commit comments