(filePath, label = "API")
| 146 | * @returns {string} The (hex) API key. |
| 147 | */ |
| 148 | export function getOrCreatePersistedApiKey(filePath, label = "API") { |
| 149 | const cached = persistedApiKeyCache.get(filePath); |
| 150 | if (cached) return cached; |
| 151 | |
| 152 | // Try to read an existing key. |
| 153 | try { |
| 154 | const existing = readFileSync(filePath, "utf8").trim(); |
| 155 | if (existing) { |
| 156 | persistedApiKeyCache.set(filePath, existing); |
| 157 | return existing; |
| 158 | } |
| 159 | // File exists but is empty -- treat as if missing and regenerate. |
| 160 | } catch (error) { |
| 161 | if (!isEnoentError(error)) { |
| 162 | console.warn( |
| 163 | `Could not read persisted ${label} API key from ${filePath}: ${error.message}. Regenerating.`, |
| 164 | ); |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // Generate and persist a new key. |
| 169 | const newKey = generateRandomApiKey(); |
| 170 | try { |
| 171 | mkdirSync(path.dirname(filePath), { recursive: true }); |
| 172 | writeFileSync(filePath, `${newKey}\n`, { mode: 0o600 }); |
| 173 | } catch (error) { |
| 174 | console.warn( |
| 175 | `Could not persist ${label} API key to ${filePath}: ${error.message}. Falling back to in-memory key (will not survive restarts).`, |
| 176 | ); |
| 177 | } |
| 178 | persistedApiKeyCache.set(filePath, newKey); |
| 179 | return newKey; |
| 180 | } |
| 181 | |
| 182 | /** |
| 183 | * Clear the in-memory cache used by {@link getOrCreatePersistedSessionApiKey}. |
no test coverage detected