Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(db): dedup duplicate API keys per provider on connection create (#3023) (#3100)

Diego Rodrigues de Sa e Souza5f3b1e8cdea6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ae1d0f2ce0..72fc125322 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,7 @@ _Development cycle in progress — entries are added as work merges into `releas
### 🔧 Bug Fixes
+- **db:** stop accepting duplicate API keys for the same provider — `createProviderConnection` now dedups by the decrypted key value (not just by name), so re-adding the same key under a different/blank name updates the existing connection instead of inserting a second row. Whitespace-only differences also dedup. ([#3023](https://github.com/diegosouzapw/OmniRoute/issues/3023))
- **dashboard:** "Import from /models" now works for no-auth providers (e.g. OpenCode Free) — the button used to silently no-op because no-auth providers have no connection row, so `handleImportModels` returned early and the models route 404'd. The route now serves the provider's model catalog when called with a no-auth provider id, and the dashboard falls back to the provider id when there is no connection. ([#3047](https://github.com/diegosouzapw/OmniRoute/issues/3047))
- **providers:** forward Grok's paired `sso-rw` cookie for grok-web — both the executor and the connection validator now send `sso=…; sso-rw=…` (via the new `buildGrokCookieHeader` helper) when the pasted blob carries `sso-rw`, fixing the `403` _"Request rejected by anti-bot rules"_ that Grok returns for `sso` alone. The add-account hint now asks for the full cookie line. ([#3063](https://github.com/diegosouzapw/OmniRoute/issues/3063))
- **providers:** fix claude-web persistent 403 — `execute()` was calling the synchronous `normalizeClaudeSessionCookie()` which never injects `cf_clearance`; changed to async `normalizeClaudeSessionCookieWithAutoRefresh()` with `allowAutoSolve:true`. Also removes dead executor `claude-web-auto-refresh.ts` and correctly reclassifies `duckduckgo-web` and `veoaifree-web` as `NOAUTH_PROVIDERS`. (#3090 — thanks @oyi77)
diff --git a/src/lib/db/providers.ts b/src/lib/db/providers.ts
index 4c922f06fb..d50d299c67 100644
--- a/src/lib/db/providers.ts
+++ b/src/lib/db/providers.ts
@@ -195,13 +195,34 @@ export async function createProviderConnection(data: JsonRecord) {
)
.get(data.provider, data.email) as JsonRecord | undefined) || null;
}
- } else if (data.authType === "apikey" && data.name) {
- existing =
- (db
- .prepare(
- "SELECT * FROM provider_connections WHERE provider = ? AND auth_type = 'apikey' AND name = ?"
- )
- .get(data.provider, data.name) as JsonRecord | undefined) || null;
+ } else if (data.authType === "apikey") {
+ // Name-based upsert (existing behavior): same provider + same name → update.
+ if (data.name) {
+ existing =
+ (db
+ .prepare(
+ "SELECT * FROM provider_connections WHERE provider = ? AND auth_type = 'apikey' AND name = ?"
+ )
+ .get(data.provider, data.name) as JsonRecord | undefined) || null;
+ }
+ // #3023 — dedup by API key value: re-adding the same key (under a different
+ // or blank name) must update the existing connection, not insert a duplicate
+ // row. Stored keys use non-deterministic AES-GCM, so ciphertext can't be
+ // compared directly — decrypt each apikey row for this provider and match the
+ // plaintext (trimmed) instead.
+ const newApiKey = typeof data.apiKey === "string" ? data.apiKey.trim() : "";
+ if (!existing && newApiKey) {
+ const apiKeyRows = db
+ .prepare("SELECT * FROM provider_connections WHERE provider = ? AND auth_type = 'apikey'")
+ .all(data.provider) as JsonRecord[];
+ for (const row of apiKeyRows) {
+ const decrypted = decryptConnectionFields(toRecord(rowToCamel(row)));
+ if (toStringOrNull(decrypted.apiKey)?.trim() === newApiKey) {
+ existing = row;
+ break;
+ }
+ }
+ }
}
if (existing) {
diff --git a/tests/unit/provider-connection-apikey-dedup.test.ts b/tests/unit/provider-connection-apikey-dedup.test.ts
new file mode 100644
index 0000000000..b0e05a0d5d
--- /dev/null
+++ b/tests/unit/provider-connection-apikey-dedup.test.ts
@@ -0,0 +1,87 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-apikey-dedup-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "apikey-dedup-test-secret";
+
+const core = await import("../../src/lib/db/core.ts");
+const providersDb = await import("../../src/lib/db/providers.ts");
+
+async function resetStorage() {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+test.beforeEach(resetStorage);
+
+test.after(() => {
+ core.resetDbInstance();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+async function apiKeyConnections(provider: string) {
+ const all = await providersDb.getProviderConnections({});
+ return all.filter((c: any) => c.provider === provider && c.authType === "apikey");
+}
+
+// #3023 — adding the same API key twice (even under a different name) used to
+// create a duplicate connection row. It must now dedup onto the existing one.
+test("re-adding the same API key dedups instead of creating a duplicate (#3023)", async () => {
+ const first = await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "key A",
+ apiKey: "sk-DUP-123456",
+ });
+ const second = await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "key B (same secret)",
+ apiKey: "sk-DUP-123456",
+ });
+
+ const conns = await apiKeyConnections("openai");
+ assert.equal(conns.length, 1, "a duplicate API key must not create a second row");
+ assert.equal(second.id, first.id, "the duplicate must update the existing connection");
+});
+
+// Whitespace-only differences in the pasted key still dedup.
+test("re-adding the same API key with surrounding whitespace still dedups (#3023)", async () => {
+ await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "key A",
+ apiKey: "sk-TRIM-9",
+ });
+ await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "key B",
+ apiKey: " sk-TRIM-9 ",
+ });
+
+ assert.equal((await apiKeyConnections("openai")).length, 1);
+});
+
+// Genuinely different keys remain separate connections.
+test("different API keys for the same provider create separate connections (#3023)", async () => {
+ await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "key A",
+ apiKey: "sk-AAA",
+ });
+ await providersDb.createProviderConnection({
+ provider: "openai",
+ authType: "apikey",
+ name: "key B",
+ apiKey: "sk-BBB",
+ });
+
+ assert.equal((await apiKeyConnections("openai")).length, 2);
+});