(
id: string,
pb: PBService<{ entries: any }>,
callerModule?: { source: 'app' | 'core'; id: string }
)
| 44 | async function getAPIKey( |
| 45 | id: string, |
| 46 | pb: PBService<{ entries: any }>, |
| 47 | callerModule?: { source: 'app' | 'core'; id: string } |
| 48 | ): Promise<string> { |
| 49 | try { |
| 50 | if (!callerModule) { |
| 51 | throw new Error( |
| 52 | 'Unable to determine caller module for API key validation.' |
| 53 | ) |
| 54 | } |
| 55 | |
| 56 | const rawPb = pb.instance as unknown as { |
| 57 | _apiKeyCache?: Map<string, { key: string; exposable: boolean }> |
| 58 | } |
| 59 | |
| 60 | if (!rawPb._apiKeyCache) { |
| 61 | rawPb._apiKeyCache = new Map() |
| 62 | } |
| 63 | |
| 64 | const cached = rawPb._apiKeyCache.get(id) |
| 65 | |
| 66 | if (cached !== undefined) { |
| 67 | if (!cached.exposable) { |
| 68 | await validateCallerAccess(callerModule, id) |
| 69 | } |
| 70 | |
| 71 | return cached.key |
| 72 | } |
| 73 | |
| 74 | const record = await pb.instance |
| 75 | .collection('api_keys__entries') |
| 76 | .getFirstListItem(`keyId = "${id}"`) |
| 77 | .catch(err => { |
| 78 | throw new Error(`Failed to retrieve API key for ${id}: ${err.message}`) |
| 79 | }) |
| 80 | |
| 81 | if (!record.exposable) { |
| 82 | await validateCallerAccess(callerModule, id) |
| 83 | } |
| 84 | |
| 85 | try { |
| 86 | logger.info( |
| 87 | `API key for ${chalk.blue(id)} retrieved by ${chalk.blue(callerModule.source)}:${chalk.blue(callerModule.id)}` |
| 88 | ) |
| 89 | |
| 90 | const decrypted = decrypt2(record.key, process.env.MASTER_KEY!) |
| 91 | rawPb._apiKeyCache.set(id, { |
| 92 | key: decrypted, |
| 93 | exposable: record.exposable |
| 94 | }) |
| 95 | |
| 96 | return decrypted |
| 97 | } catch { |
| 98 | throw new Error(`Failed to decrypt API key for ${id}.`) |
| 99 | } |
| 100 | } catch (err) { |
| 101 | throw new Error( |
no test coverage detected