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(analytics): avoid persisting inferred API key ownership

Antigravity Assistant934c133103db
diff --git a/open-sse/services/compression/lite.ts b/open-sse/services/compression/lite.ts
index 8ee5b6d4f9..9bc26f39f0 100644
--- a/open-sse/services/compression/lite.ts
+++ b/open-sse/services/compression/lite.ts
@@ -12,6 +12,11 @@ interface ChatBody {
[key: string]: unknown;
}
+interface LiteCompressionOptions {
+ model?: string;
+ supportsVision?: boolean | null;
+}
+
export function collapseWhitespace(body: ChatBody): {
body: ChatBody;
applied: boolean;
@@ -92,11 +97,13 @@ export function removeRedundantContent(body: ChatBody): {
export function replaceImageUrls(
body: ChatBody,
- model?: string
+ options?: LiteCompressionOptions | string
): { body: ChatBody; applied: boolean } {
if (!body.messages) return { body, applied: false };
- const isVisionModel = model && /\b(vision|gpt-4o|claude-3|gemini-1\.5|gemini-2)\b/i.test(model);
- if (isVisionModel) return { body, applied: false };
+ const supportsVision =
+ typeof options === "object" && options !== null ? options.supportsVision : undefined;
+ if (supportsVision !== false) return { body, applied: false };
+
let applied = false;
const messages = body.messages.map((msg) => {
if (!Array.isArray(msg.content)) return msg;
@@ -126,7 +133,7 @@ export function replaceImageUrls(
export function applyLiteCompression(
body: Record<string, unknown>,
- options?: { model?: string }
+ options?: LiteCompressionOptions
): CompressionResult {
const originalBody = body;
let current = body as ChatBody;
@@ -148,7 +155,7 @@ export function applyLiteCompression(
current = r4.body;
if (r4.applied) techniquesApplied.push("redundant-remove");
- const r5 = replaceImageUrls(current, options?.model);
+ const r5 = replaceImageUrls(current, options);
current = r5.body;
if (r5.applied) techniquesApplied.push("image-placeholder");
diff --git a/open-sse/services/compression/strategySelector.ts b/open-sse/services/compression/strategySelector.ts
index bb77a8b92c..59164c8ce9 100644
--- a/open-sse/services/compression/strategySelector.ts
+++ b/open-sse/services/compression/strategySelector.ts
@@ -59,7 +59,7 @@ export function selectCompressionStrategy(
export function applyCompression(
body: Record<string, unknown>,
mode: CompressionMode,
- options?: { model?: string; config?: CompressionConfig }
+ options?: { model?: string; supportsVision?: boolean | null; config?: CompressionConfig }
): CompressionResult {
if (mode === "off") {
return { body, compressed: false, stats: null };
diff --git a/src/app/api/admin/concurrency/route.ts b/src/app/api/admin/concurrency/route.ts
index 6bbf79b05f..0d6f59bf51 100644
--- a/src/app/api/admin/concurrency/route.ts
+++ b/src/app/api/admin/concurrency/route.ts
@@ -4,8 +4,12 @@ import {
getStats as getSemaphoreStats,
resetAll as resetAllSemaphores,
} from "@omniroute/open-sse/services/accountSemaphore.ts";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
+
+export async function GET(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
-export async function GET() {
return NextResponse.json({
timestamp: new Date().toISOString(),
rateLimits: getAllRateLimitStatus(),
@@ -14,6 +18,9 @@ export async function GET() {
}
export async function POST(request: Request) {
+ const authError = await requireManagementAuth(request);
+ if (authError) return authError;
+
const url = new URL(request.url);
const action = url.searchParams.get("action");
if (action === "reset-semaphores") {
diff --git a/src/app/api/analytics/compression/route.ts b/src/app/api/analytics/compression/route.ts
index 35d3ca4e40..a81e6fef80 100644
--- a/src/app/api/analytics/compression/route.ts
+++ b/src/app/api/analytics/compression/route.ts
@@ -6,12 +6,12 @@
*/
import { NextResponse } from "next/server";
-import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";
import { getCompressionAnalyticsSummary } from "@/lib/db/compressionAnalytics";
+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";
export async function GET(req: Request) {
- const policy = await enforceApiKeyPolicy(req, "analytics");
- if (policy.rejection) return policy.rejection;
+ const authError = await requireManagementAuth(req);
+ if (authError) return authError;
try {
const url = new URL(req.url);
diff --git a/src/app/api/usage/analytics/route.ts b/src/app/api/usage/analytics/route.ts
index f696050a24..60ed43c6a1 100644
--- a/src/app/api/usage/analytics/route.ts
+++ b/src/app/api/usage/analytics/route.ts
@@ -137,112 +137,6 @@ export async function GET(request: Request) {
const db = getDbInstance();
- // ── Enrich entries with missing apiKeyName ──────────────────────────
- try {
- // Only run enrichment if there are actually NULL entries
- const hasNull = db
- .prepare(
- "SELECT 1 FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL LIMIT 1"
- )
- .get();
- if (hasNull) {
- // Step 1: dominant key per connectionId from existing usage data
- db.prepare(
- `
- UPDATE usage_history
- SET
- api_key_name = (
- SELECT uh2.api_key_name
- FROM usage_history AS uh2
- WHERE uh2.connection_id = usage_history.connection_id
- AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''
- GROUP BY uh2.api_key_name
- ORDER BY COUNT(*) DESC
- LIMIT 1
- ),
- api_key_id = COALESCE(api_key_id, (
- SELECT uh2.api_key_id
- FROM usage_history AS uh2
- WHERE uh2.connection_id = usage_history.connection_id
- AND uh2.api_key_name IS NOT NULL AND uh2.api_key_name != ''
- GROUP BY uh2.api_key_name
- ORDER BY COUNT(*) DESC
- LIMIT 1
- ))
- WHERE (api_key_name IS NULL OR api_key_name = '')
- AND connection_id IS NOT NULL
- AND EXISTS (
- SELECT 1 FROM usage_history AS uh3
- WHERE uh3.connection_id = usage_history.connection_id
- AND uh3.api_key_name IS NOT NULL AND uh3.api_key_name != ''
- )
- `
- ).run();
-
- // Step 2 & 3: For still unresolved connections, check apiKeys config
- const stillNull = db
- .prepare(
- "SELECT DISTINCT connection_id FROM usage_history WHERE (api_key_name IS NULL OR api_key_name = '') AND connection_id IS NOT NULL"
- )
- .all();
- if (stillNull.length > 0) {
- const { getApiKeys } = await import("@/lib/localDb");
- const apiKeys = (await getApiKeys()) as any[];
-
- const updateStmt = db.prepare(
- "UPDATE usage_history SET api_key_name = ?, api_key_id = ? WHERE connection_id = ? AND (api_key_name IS NULL OR api_key_name = '')"
- );
- const updateMany = db.transaction((updates: any[]) => {
- for (const u of updates) updateStmt.run(u.name, u.id, u.cid);
- });
-
- const updates = [];
- const orphanIds = new Set(stillNull.map((r: any) => r.connection_id));
-
- for (const ak of apiKeys) {
- const allowed = Array.isArray(ak.allowedConnections) ? ak.allowedConnections : [];
- const keyName = ak.name || ak.id;
- const keyId = ak.id || null;
- for (const cid of allowed) {
- if (typeof cid === "string" && orphanIds.has(cid)) {
- updates.push({ name: keyName, id: keyId, cid });
- orphanIds.delete(cid);
- }
- }
- }
-
- if (orphanIds.size > 0) {
- const unrestrictedKeys = apiKeys.filter(
- (ak: any) =>
- !Array.isArray(ak.allowedConnections) || ak.allowedConnections.length === 0
- );
- if (unrestrictedKeys.length > 0) {
- let bestKey = unrestrictedKeys[0];
- let bestCount = -1;
- for (const uk of unrestrictedKeys) {
- const countRow = db
- .prepare("SELECT COUNT(*) as c FROM usage_history WHERE api_key_name = ?")
- .get(uk.name || uk.id) as any;
- if (countRow.c > bestCount) {
- bestCount = countRow.c;
- bestKey = uk;
- }
- }
- const fallbackName = bestKey.name || bestKey.id;
- const fallbackId = bestKey.id || null;
- for (const cid of orphanIds) {
- updates.push({ name: fallbackName, id: fallbackId, cid });
- }
- }
- }
-
- if (updates.length > 0) updateMany(updates);
- }
- }
- } catch (e) {
- console.error("Failed to backfill missing api_key_name:", e);
- }
-
const conditions = [];
const params: Record<string, string> = {};
@@ -466,10 +360,7 @@ export async function GET(request: Request) {
)
.all(params) as Array<Record<string, unknown>>;
- const apiKeyWhereClause = appendWhereCondition(
- whereClause,
- "(api_key_id IS NOT NULL AND api_key_id != '') OR (api_key_name IS NOT NULL AND api_key_name != '')"
- );
+ const apiKeyWhereClause = whereClause;
const apiKeyRows = db
.prepare(
`
diff --git a/tests/integration/compression-pipeline.test.ts b/tests/integration/compression-pipeline.test.ts
index 99b4702458..0df20fdbd3 100644
--- a/tests/integration/compression-pipeline.test.ts
+++ b/tests/integration/compression-pipeline.test.ts
@@ -5,7 +5,10 @@ import {
getEffectiveMode,
applyCompression,
} from "../../open-sse/services/compression/strategySelector.ts";
-import { applyLiteCompression } from "../../open-sse/services/compression/lite.ts";
+import {
+ applyLiteCompression,
+ replaceImageUrls,
+} from "../../open-sse/services/compression/lite.ts";
import {
createCompressionStats,
estimateCompressionTokens,
@@ -108,6 +111,31 @@ describe("Full Compression Pipeline", () => {
assert.ok(result.stats.techniquesUsed.length >= 1);
});
+ it("lite compression preserves multimodal image payloads unless non-vision is explicit", () => {
+ const dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB";
+ const body = {
+ messages: [
+ {
+ role: "user",
+ content: [
+ { type: "text", text: "Describe this image" },
+ { type: "image_url", image_url: { url: dataUrl } },
+ ],
+ },
+ ],
+ };
+
+ const preserved = applyLiteCompression(body, { model: "openai/gpt-4.1" });
+ assert.equal(preserved.compressed, false);
+ assert.deepEqual(preserved.body, body);
+
+ const placeholder = replaceImageUrls(body, { model: "text-only-model", supportsVision: false });
+ assert.equal(placeholder.applied, true);
+ const content = placeholder.body.messages?.[0]?.content;
+ assert.ok(Array.isArray(content));
+ assert.deepEqual(content[1], { type: "text", text: "[image: png]" });
+ });
+
it("token estimation is consistent", () => {
const text = "hello world this is a test";
const tokens = estimateCompressionTokens(text);
diff --git a/tests/unit/compression/compressionAnalytics.test.ts b/tests/unit/compression/compressionAnalytics.test.ts
index 6c473f1ab9..7bfb290c01 100644
--- a/tests/unit/compression/compressionAnalytics.test.ts
+++ b/tests/unit/compression/compressionAnalytics.test.ts
@@ -7,11 +7,11 @@ import { join } from "node:path";
const tmpDir = mkdtempSync(join(tmpdir(), "omniroute-test-"));
process.env.DATA_DIR = tmpDir;
-import {
- insertCompressionAnalyticsRow,
- getCompressionAnalyticsSummary,
-} from "../../../src/lib/db/compressionAnalytics.js";
-import { getDbInstance } from "../../../src/lib/db/core.js";
+const core = await import("../../../src/lib/db/core.ts");
+core.resetDbInstance();
+const { insertCompressionAnalyticsRow, getCompressionAnalyticsSummary } =
+ await import("../../../src/lib/db/compressionAnalytics.ts");
+const { getDbInstance } = core;
describe("compressionAnalytics", () => {
before(() => {
@@ -39,6 +39,7 @@ describe("compressionAnalytics", () => {
});
after(() => {
+ core.closeDbInstance();
rmSync(tmpDir, { recursive: true, force: true });
});
diff --git a/tests/unit/management-auth-hardening.test.ts b/tests/unit/management-auth-hardening.test.ts
index 7a1f4a23e1..2b14e81a3e 100644
--- a/tests/unit/management-auth-hardening.test.ts
+++ b/tests/unit/management-auth-hardening.test.ts
@@ -16,3 +16,30 @@ test("Codex apply-local auth route requires management authentication before loc
content.indexOf("ensureCliConfigWriteAllowed()")
);
});
+
+test("admin concurrency route requires management authentication before read or reset", () => {
+ const content = fs.readFileSync("src/app/api/admin/concurrency/route.ts", "utf8");
+
+ assert.ok(content.includes('from "@/lib/api/requireManagementAuth"'));
+ assert.ok(content.includes("const authError = await requireManagementAuth(request);"));
+ assert.ok(content.includes("if (authError) return authError;"));
+ assert.ok(
+ content.indexOf("requireManagementAuth(request)") < content.indexOf("getAllRateLimitStatus()")
+ );
+ assert.ok(
+ content.indexOf("requireManagementAuth(request)") < content.indexOf("resetAllSemaphores()")
+ );
+});
+
+test("compression analytics route requires management authentication before returning metrics", () => {
+ const content = fs.readFileSync("src/app/api/analytics/compression/route.ts", "utf8");
+
+ assert.ok(content.includes('from "@/lib/api/requireManagementAuth"'));
+ assert.ok(!content.includes("enforceApiKeyPolicy"));
+ assert.ok(content.includes("const authError = await requireManagementAuth(req);"));
+ assert.ok(content.includes("if (authError) return authError;"));
+ assert.ok(
+ content.indexOf("requireManagementAuth(req)") <
+ content.indexOf("getCompressionAnalyticsSummary(")
+ );
+});
diff --git a/tests/unit/usage-analytics-route.test.ts b/tests/unit/usage-analytics-route.test.ts
index 25d8cc7c48..7467a31ebc 100644
--- a/tests/unit/usage-analytics-route.test.ts
+++ b/tests/unit/usage-analytics-route.test.ts
@@ -6,9 +6,12 @@ import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-usage-analytics-route-"));
process.env.DATA_DIR = TEST_DATA_DIR;
+const ORIGINAL_API_KEY_SECRET = process.env.API_KEY_SECRET;
+process.env.API_KEY_SECRET = "test-usage-analytics-secret";
const core = await import("../../src/lib/db/core.ts");
const localDb = await import("../../src/lib/localDb.ts");
+const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
const usageHistory = await import("../../src/lib/usage/usageHistory.ts");
const analyticsRoute = await import("../../src/app/api/usage/analytics/route.ts");
@@ -17,6 +20,7 @@ const EXPECTED_TOTAL_COST = 0.020925;
async function resetStorage() {
core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
clearPendingRequests();
@@ -70,7 +74,14 @@ test.beforeEach(async () => {
test.after(() => {
core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+
+ if (ORIGINAL_API_KEY_SECRET === undefined) {
+ delete process.env.API_KEY_SECRET;
+ } else {
+ process.env.API_KEY_SECRET = ORIGINAL_API_KEY_SECRET;
+ }
});
test("GET /api/usage/analytics returns summary with aggregated metrics", async () => {
@@ -173,6 +184,31 @@ test("GET /api/usage/analytics includes cost by API key", async () => {
assertClose(body.byApiKey[0].cost, body.summary.totalCost);
});
+test("GET /api/usage/analytics does not persist guessed API key attribution", async () => {
+ await localDb.updatePricing({
+ openai: { "gpt-4o": { input: 2.5, output: 10 } },
+ });
+ await apiKeysDb.createApiKey("Unrestricted Key", "machine1234567890");
+
+ const db = core.getDbInstance();
+ db.prepare(
+ `INSERT INTO usage_history (provider, model, connection_id, api_key_id, api_key_name, tokens_input, tokens_output, success, latency_ms, timestamp)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
+ ).run("openai", "gpt-4o", "legacy-conn", null, null, 100, 50, 1, 200, new Date().toISOString());
+
+ const response = await analyticsRoute.GET(makeRequest("http://localhost/api/usage/analytics"));
+ const body = await response.json();
+
+ assert.equal(response.status, 200);
+ assert.ok(body.byApiKey.some((row) => row.apiKeyName === "Unknown API key"));
+
+ const row = db
+ .prepare("SELECT api_key_id, api_key_name FROM usage_history WHERE connection_id = ?")
+ .get("legacy-conn") as { api_key_id: string | null; api_key_name: string | null };
+ assert.equal(row.api_key_id, null);
+ assert.equal(row.api_key_name, null);
+});
+
test("GET /api/usage/analytics returns weeklyPattern for the costs dashboard", async () => {
await seedAnalyticsData();