| 49 | } |
| 50 | |
| 51 | async replace(apiKeys: ApiKeyConfig[]): Promise<ApiKeyConfig[]> { |
| 52 | const normalized = uniqueApiKeyConfigs(apiKeys); |
| 53 | const database = await this.getDatabase(); |
| 54 | const statement = database.prepare(` |
| 55 | INSERT INTO api_keys ( |
| 56 | id, |
| 57 | name, |
| 58 | encrypted_key, |
| 59 | encryption, |
| 60 | created_at, |
| 61 | expires_at, |
| 62 | limits_json |
| 63 | ) VALUES (?, ?, ?, ?, ?, ?, ?) |
| 64 | `); |
| 65 | |
| 66 | try { |
| 67 | database.exec("BEGIN TRANSACTION"); |
| 68 | database.exec("DELETE FROM api_keys"); |
| 69 | for (const apiKey of normalized) { |
| 70 | const stored = storeApiKey(apiKey.key); |
| 71 | statement.run( |
| 72 | apiKey.id, |
| 73 | apiKey.name ?? "", |
| 74 | stored.value, |
| 75 | stored.encryption, |
| 76 | apiKey.createdAt, |
| 77 | apiKey.expiresAt ?? "", |
| 78 | apiKey.limits ? JSON.stringify(apiKey.limits) : "" |
| 79 | ); |
| 80 | } |
| 81 | database.exec("COMMIT"); |
| 82 | secureDatabaseFilePermissions(this.dbFile); |
| 83 | return normalized; |
| 84 | } catch (error) { |
| 85 | try { |
| 86 | database.exec("ROLLBACK"); |
| 87 | } catch { |
| 88 | // Ignore rollback errors; the original write error is more useful. |
| 89 | } |
| 90 | secureDatabaseFilePermissions(this.dbFile); |
| 91 | throw error; |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | private async getDatabase(): Promise<SqlDatabase> { |
| 96 | if (this.database) { |