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

Scope API key reveal to Api Manager (#740)

Randid352b6b509dc
diff --git a/.env.example b/.env.example
index 973ca0efe3..aa65001376 100644
--- a/.env.example
+++ b/.env.example
@@ -40,6 +40,7 @@ MACHINE_ID_SALT=endpoint-proxy-salt
ENABLE_REQUEST_LOGS=false
AUTH_COOKIE_SECURE=false
REQUIRE_API_KEY=false
+ALLOW_API_KEY_REVEAL=false
# Input Sanitizer (FASE-01 — prompt injection & PII protection)
# INPUT_SANITIZER_ENABLED=true
diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md
index f2582cf288..11a475bdb9 100644
--- a/docs/USER_GUIDE.md
+++ b/docs/USER_GUIDE.md
@@ -519,6 +519,7 @@ post_install() {
| `CLOUD_URL` | `https://omniroute.dev` | Cloud sync endpoint base URL |
| `API_KEY_SECRET` | `endpoint-proxy-api-key-secret` | HMAC secret for generated API keys |
| `REQUIRE_API_KEY` | `false` | Enforce Bearer API key on `/v1/*` |
+| `ALLOW_API_KEY_REVEAL` | `false` | Allow Api Manager to copy full API keys on demand |
| `ENABLE_REQUEST_LOGS` | `false` | Enables request/response logs |
| `AUTH_COOKIE_SECURE` | `false` | Force `Secure` auth cookie (behind HTTPS reverse proxy) |
| `OMNIROUTE_MEMORY_MB` | `512` | Node.js heap limit in MB |
diff --git a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx
index 2155a01e61..2b6b37fb24 100644
--- a/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx
+++ b/src/app/(dashboard)/dashboard/api-manager/ApiManagerPageClient.tsx
@@ -111,6 +111,7 @@ export default function ApiManagerPageClient() {
const [isSubmitting, setIsSubmitting] = useState(false);
const [usageStats, setUsageStats] = useState<Record<string, KeyUsageStats>>({});
const [sessionCounts, setSessionCounts] = useState<Record<string, number>>({});
+ const [allowKeyReveal, setAllowKeyReveal] = useState(false);
const { copied, copy } = useCopyToClipboard();
@@ -150,6 +151,7 @@ export default function ApiManagerPageClient() {
if (res.ok) {
const data = await res.json();
setKeys(data.keys || []);
+ setAllowKeyReveal(data.allowKeyReveal === true);
// Fetch usage stats after keys are loaded
fetchUsageStats(data.keys || []);
fetchSessionCounts(data.keys || []);
@@ -288,6 +290,25 @@ export default function ApiManagerPageClient() {
setShowPermissionsModal(true);
};
+ const handleCopyExistingKey = async (keyId: string) => {
+ if (!keyId) return;
+
+ try {
+ const res = await fetch(`/api/keys/${encodeURIComponent(keyId)}/reveal`);
+ if (!res.ok) {
+ console.log("Error revealing key:", await res.text());
+ return;
+ }
+
+ const data = await res.json();
+ if (typeof data?.key === "string") {
+ await copy(data.key, `existing_key_${keyId}`);
+ }
+ } catch (error) {
+ console.log("Error copying existing key:", error);
+ }
+ };
+
const handleUpdatePermissions = async (
allowedModels: string[],
noLog: boolean,
@@ -560,12 +581,25 @@ export default function ApiManagerPageClient() {
</div>
<div className="col-span-3 flex items-center gap-1.5">
<code className="text-sm text-text-muted font-mono truncate">{key.key}</code>
- <span
- className="p-1 text-text-muted/40 opacity-0 group-hover:opacity-100 transition-all shrink-0 cursor-help"
- title={t("keyOnlyAvailableAtCreation")}
- >
- <span className="material-symbols-outlined text-[14px]">lock</span>
- </span>
+ {allowKeyReveal ? (
+ <button
+ onClick={() => handleCopyExistingKey(key.id)}
+ className="p-1 text-text-muted/60 hover:text-primary transition-colors shrink-0"
+ title={tc("copy")}
+ aria-label={tc("copy")}
+ >
+ <span className="material-symbols-outlined text-[14px]">
+ {copied === `existing_key_${key.id}` ? "check" : "content_copy"}
+ </span>
+ </button>
+ ) : (
+ <span
+ className="p-1 text-text-muted/40 opacity-0 group-hover:opacity-100 transition-all shrink-0 cursor-help"
+ title={t("keyOnlyAvailableAtCreation")}
+ >
+ <span className="material-symbols-outlined text-[14px]">lock</span>
+ </span>
+ )}
</div>
<div className="col-span-2 flex items-center">
<div className="flex flex-col items-start gap-1">
diff --git a/src/app/api/keys/[id]/reveal/route.ts b/src/app/api/keys/[id]/reveal/route.ts
new file mode 100644
index 0000000000..d98dd37dc2
--- /dev/null
+++ b/src/app/api/keys/[id]/reveal/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse } from "next/server";
+import { getApiKeyById } from "@/lib/localDb";
+import { isApiKeyRevealEnabled } from "@/lib/apiKeyExposure";
+
+// GET /api/keys/[id]/reveal - Reveal full API key for explicit copy actions
+export async function GET(_request, { params }) {
+ try {
+ if (!isApiKeyRevealEnabled()) {
+ return NextResponse.json({ error: "API key reveal is disabled" }, { status: 403 });
+ }
+
+ const { id } = await params;
+ const key = await getApiKeyById(id);
+
+ if (!key || typeof key.key !== "string") {
+ return NextResponse.json({ error: "Key not found" }, { status: 404 });
+ }
+
+ return NextResponse.json({ key: key.key });
+ } catch (error) {
+ console.log("Error revealing key:", error);
+ return NextResponse.json({ error: "Failed to reveal key" }, { status: 500 });
+ }
+}
diff --git a/src/app/api/keys/route.ts b/src/app/api/keys/route.ts
index fc4393d2ac..2ebb23b79b 100644
--- a/src/app/api/keys/route.ts
+++ b/src/app/api/keys/route.ts
@@ -4,17 +4,17 @@ import { getConsistentMachineId } from "@/shared/utils/machineId";
import { syncToCloud } from "@/lib/cloudSync";
import { createKeySchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
+import { isApiKeyRevealEnabled, maskStoredApiKey } from "@/lib/apiKeyExposure";
// GET /api/keys - List API keys
export async function GET() {
try {
const keys = await getApiKeys();
- // Mask key values — users should never see full keys after creation
const maskedKeys = keys.map((k) => ({
...k,
- key: typeof k.key === "string" ? k.key.slice(0, 8) + "****" + k.key.slice(-4) : null,
+ key: maskStoredApiKey(k.key),
}));
- return NextResponse.json({ keys: maskedKeys });
+ return NextResponse.json({ keys: maskedKeys, allowKeyReveal: isApiKeyRevealEnabled() });
} catch (error) {
console.log("Error fetching keys:", error);
return NextResponse.json({ error: "Failed to fetch keys" }, { status: 500 });
diff --git a/src/lib/apiKeyExposure.ts b/src/lib/apiKeyExposure.ts
new file mode 100644
index 0000000000..2a787508aa
--- /dev/null
+++ b/src/lib/apiKeyExposure.ts
@@ -0,0 +1,13 @@
+const ENABLED_VALUES = new Set(["1", "true", "yes", "on"]);
+
+export function isApiKeyRevealEnabled(): boolean {
+ const raw = String(process.env.ALLOW_API_KEY_REVEAL || "")
+ .trim()
+ .toLowerCase();
+ return ENABLED_VALUES.has(raw);
+}
+
+export function maskStoredApiKey(key: unknown): string | null {
+ if (typeof key !== "string") return null;
+ return key.slice(0, 8) + "****" + key.slice(-4);
+}
diff --git a/tests/unit/api-key-reveal-route.test.mjs b/tests/unit/api-key-reveal-route.test.mjs
new file mode 100644
index 0000000000..f5929cbb95
--- /dev/null
+++ b/tests/unit/api-key-reveal-route.test.mjs
@@ -0,0 +1,79 @@
+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-api-key-reveal-"));
+process.env.DATA_DIR = TEST_DATA_DIR;
+process.env.API_KEY_SECRET = "test-api-key-secret";
+
+const core = await import("../../src/lib/db/core.ts");
+const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
+const listRoute = await import("../../src/app/api/keys/route.ts");
+const revealRoute = await import("../../src/app/api/keys/[id]/reveal/route.ts");
+
+const MACHINE_ID = "1234567890abcdef";
+
+async function resetStorage() {
+ delete process.env.ALLOW_API_KEY_REVEAL;
+ core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
+}
+
+function maskKey(key) {
+ return key.slice(0, 8) + "****" + key.slice(-4);
+}
+
+test.beforeEach(async () => {
+ await resetStorage();
+});
+
+test.after(async () => {
+ delete process.env.ALLOW_API_KEY_REVEAL;
+ core.resetDbInstance();
+ apiKeysDb.resetApiKeyState();
+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
+});
+
+test("GET /api/keys stays masked even when reveal is enabled", async () => {
+ process.env.ALLOW_API_KEY_REVEAL = "true";
+ const created = await apiKeysDb.createApiKey("Primary Key", MACHINE_ID);
+
+ const response = await listRoute.GET();
+ const body = await response.json();
+
+ assert.equal(response.status, 200);
+ assert.equal(body.allowKeyReveal, true);
+ assert.equal(Array.isArray(body.keys), true);
+ assert.equal(body.keys[0].key, maskKey(created.key));
+});
+
+test("GET /api/keys/[id]/reveal rejects requests when reveal is disabled", async () => {
+ const created = await apiKeysDb.createApiKey("Primary Key", MACHINE_ID);
+ const request = new Request(`http://localhost/api/keys/${created.id}/reveal`);
+
+ const response = await revealRoute.GET(request, {
+ params: Promise.resolve({ id: created.id }),
+ });
+ const body = await response.json();
+
+ assert.equal(response.status, 403);
+ assert.equal(body.error, "API key reveal is disabled");
+});
+
+test("GET /api/keys/[id]/reveal returns the full key when reveal is enabled", async () => {
+ process.env.ALLOW_API_KEY_REVEAL = "true";
+ const created = await apiKeysDb.createApiKey("Primary Key", MACHINE_ID);
+ const request = new Request(`http://localhost/api/keys/${created.id}/reveal`);
+
+ const response = await revealRoute.GET(request, {
+ params: Promise.resolve({ id: created.id }),
+ });
+ const body = await response.json();
+
+ assert.equal(response.status, 200);
+ assert.equal(body.key, created.key);
+});