({ dir, secretKey })
| 212 | * environment rather than from a file beside this one. |
| 213 | */ |
| 214 | export function createEncryptedFileStore({ dir, secretKey }) { |
| 215 | if (!dir || !secretKey) { |
| 216 | throw new Error("An encrypted secret file needs a directory and a key."); |
| 217 | } |
| 218 | const filePath = path.join(dir, SECRETS_FILENAME); |
| 219 | const key = Buffer.from( |
| 220 | hkdfSync( |
| 221 | "sha256", |
| 222 | secretKey, |
| 223 | "openhands-agent-canvas", |
| 224 | "mars-secrets/v1", |
| 225 | 32, |
| 226 | ), |
| 227 | ); |
| 228 | |
| 229 | function load() { |
| 230 | try { |
| 231 | const parsed = JSON.parse(readFileSync(filePath, "utf8")); |
| 232 | return parsed?.version === SECRETS_FILE_VERSION && |
| 233 | parsed.entries && |
| 234 | typeof parsed.entries === "object" |
| 235 | ? parsed.entries |
| 236 | : {}; |
| 237 | } catch { |
| 238 | return {}; |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | function save(entries) { |
| 243 | mkdirSync(dir, { recursive: true, mode: 0o700 }); |
| 244 | const temporary = `${filePath}.${process.pid}.tmp`; |
| 245 | writeFileSync( |
| 246 | temporary, |
| 247 | JSON.stringify({ version: SECRETS_FILE_VERSION, entries }), |
| 248 | { mode: 0o600 }, |
| 249 | ); |
| 250 | renameSync(temporary, filePath); |
| 251 | } |
| 252 | |
| 253 | return { |
| 254 | kind: SECRET_STORE_FILE, |
| 255 | label: "encrypted file", |
| 256 | isPersistent: true, |
| 257 | read(account) { |
| 258 | const entry = load()[account]; |
| 259 | if (!entry) return null; |
| 260 | try { |
| 261 | const decipher = createDecipheriv( |
| 262 | "aes-256-gcm", |
| 263 | key, |
| 264 | Buffer.from(entry.iv, "base64"), |
| 265 | ); |
| 266 | decipher.setAuthTag(Buffer.from(entry.tag, "base64")); |
| 267 | return Buffer.concat([ |
| 268 | decipher.update(Buffer.from(entry.data, "base64")), |
| 269 | decipher.final(), |
| 270 | ]).toString("utf8"); |
| 271 | } catch { |
no outgoing calls