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