MCPcopy Create free account
hub / github.com/OpenHands/OpenHands / getOrCreatePersistedApiKey

Function getOrCreatePersistedApiKey

scripts/dev-safe.mjs:143–175  ·  view source on GitHub ↗
(filePath, label = "API")

Source from the content-addressed store, hash-verified

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

Callers 2

buildConfigFromPortsFunction · 0.85

Calls 2

generateRandomApiKeyFunction · 0.85
isEnoentErrorFunction · 0.70

Tested by

no test coverage detected