mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-07-31 12:22:14 +03:00
* docs(changelog): record PR #1748 for next release * fix(models): apply blocked providers filter to non-chat catalog models (#1752) * chore(release): v3.7.5 — integrate ngrok tunnel and fix models filter (#1753, #1752) * chore(release): update changelog format for v3.7.5 * Speed up endpoint initial render * Address endpoint review feedback * Add endpoint loading model translations * fix: resolve build issues and implement memory UPSERT logic (#1763) * fix: resolve build issues for v3.7.5 and apply memory/translation fixes 1. antigravityHeaders.ts: restore ANTIGRAVITY_LOAD_CODE_ASSIST_* exports for oauth.ts compatibility 2. next.config.mjs: add @ngrok/ngrok to serverExternalPackages and webpack externals to handle native .node modules 3. Memory system: UPSERT logic to prevent duplicate entries with same apiKeyId + key 4. Chinese translations: complete CLI tools and memory dashboard localizations 5. Test fixes: unique keys for pagination tests to comply with unique constraint Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: address Gemini Code Assist review feedback 1. store.ts: add expires_at to UPDATE statement in UPSERT logic - Previously, expires_at was not being persisted to database on update - This caused state mismatch between returned Memory object and actual DB row 2. package-lock.json: revert react-markdown registry to official npmjs.org - Mirror-specific registry URL (npmmirror.com) should not be in lockfile Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> * fix(antigravity): normalize Gemini bridge payloads (#1769) * fix(antigravity): normalize Gemini bridge payloads Clamp Claude bridge output tokens, use Gemini-valid system roles and tool names, and serialize antigravity requests from a cloned body so Cloud Code payload shaping stays valid. * fix(cli): stop fallback after unsafe known paths Preserve known-path security checks by stopping command discovery when a configured CLI path is suspicious or non-executable, instead of falling through to PATH discovery. * test(memory): make query result assertion deterministic Avoid relying on database result ordering when checking filtered memory keys so the unit suite remains stable across runs. * fix(review): preserve safe cloning and CLI reasons Handle non-cloneable antigravity request bodies without throwing and preserve specific CLI known-path failure reasons instead of masking them as not_found. * fix(sse): propagate AbortSignal to pre-fetch semaphore and rate-limit awaits (#1771) When a combo target takes too long, the request-level deadline fires and calls abortController.abort() on the stream controller, but the abort signal never reaches pending awaits in acquireAccountSemaphore() or withRateLimit(). These awaits sit between stream controller creation and executor.execute(), causing requests to hang indefinitely past the 600s deadline. Pass streamController.signal to both functions so they can respond to abort events and terminate early when the request deadline expires. Signed-off-by: wucm667 <stevenwucongmin@gmail.com> * Fix model sync import handling (#1755) * Fix model sync import handling * Align model import storage semantics * Address model review feedback * fix(codex): stabilize copilot responses reasoning and tool replay (#1750) * chore(xiaomi): Update Xiaomi provider model list (#1759) * Move DB health to management API (#1757) * Move DB health to management API * Address DB health review feedback * fix(kiro): support organization IDC OAuth with regional endpoints and refresh (#1754) * fix(kiro): support organization IDC OAuth with regional endpoints and refresh * fix(kiro): refresh IDC tokens with stored region --------- Co-authored-by: ngocdb <ngocdb@ngocdb.local> * chore(workflows): add strict PR contributor credit policy - Add ABSOLUTE PROHIBITION section to review-prs.md - Add PR PROHIBITION rule to resolve-issues.md - Add contributor credit rule to AGENTS.md Review Focus - Based on audit finding: 37 PRs had code absorbed without merge credit * chore(release): acknowledge 29 community contributors with retroactive credit This commit formally recognizes 29 contributors whose code was manually integrated across releases v3.4.0 through v3.7.4 without proper GitHub merge credit. Their PRs were resolved locally due to merge conflicts but closed instead of merged, preventing them from appearing in the Contributors graph. We have updated our workflows to ensure this never happens again. Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: Benson K B <4044180+benzntech@users.noreply.github.com> Co-authored-by: clousky2020 <33016567+clousky2020@users.noreply.github.com> Co-authored-by: Raxxoor <7317522+dhaern@users.noreply.github.com> Co-authored-by: Jason Landbridge <15127381+JasonLandbridge@users.noreply.github.com> Co-authored-by: slewis3600 <35925982+slewis3600@users.noreply.github.com> Co-authored-by: Markus Hartung <12826053+hartmark@users.noreply.github.com> Co-authored-by: Hernan Javier Ardila Sanchez <204746071+herjarsa@users.noreply.github.com> Co-authored-by: 3_1_3_u <5846351+andruwa13@users.noreply.github.com> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: i1hwan <35260883+i1hwan@users.noreply.github.com> Co-authored-by: xandr0s <1709302+xandr0s@users.noreply.github.com> Co-authored-by: backryun <24198422+backryun@users.noreply.github.com> Co-authored-by: Owen <36758131+kang-heewon@users.noreply.github.com> Co-authored-by: Ravi Tharuma <25951435+RaviTharuma@users.noreply.github.com> Co-authored-by: Chris <3751981+christopher-s@users.noreply.github.com> Co-authored-by: Wellington Fonseca <5421548+wlfonseca@users.noreply.github.com> Co-authored-by: Ethan Hunt <136065060+only4copilot@users.noreply.github.com> Co-authored-by: tombii <6607822+tombii@users.noreply.github.com> Co-authored-by: AndrewDragonIV <7906124+AndrewDragonIV@users.noreply.github.com> Co-authored-by: Danh Thanh <50534210+dt418@users.noreply.github.com> Co-authored-by: Will F <30637450+willbnu@users.noreply.github.com> Co-authored-by: defhouse <232128212+defhouse@users.noreply.github.com> Co-authored-by: Skydwest <186351198+mercs2910@users.noreply.github.com> Co-authored-by: zenobit <6384793+zen0bit@users.noreply.github.com> Co-authored-by: Ivan <16905671+razllivan@users.noreply.github.com> Co-authored-by: foxy1402 <45601526+foxy1402@users.noreply.github.com> Co-authored-by: Luan Dias <65574834+luandiasrj@users.noreply.github.com> Co-authored-by: Sergei Korolev <891832+knopki@users.noreply.github.com> Co-authored-by: dail45 <69967573+dail45@users.noreply.github.com> * fix(combo): include 429 in provider circuit breaker to stop infinite retry on exhausted quotas (#1767) Previously, PROVIDER_FAILURE_ERROR_CODES only included {408, 500, 502, 503, 504}, meaning 429 responses never counted toward the circuit breaker threshold. This caused exhausted accounts to be retried every 3-5 seconds indefinitely instead of being blocked by the provider breaker. Adding 429 ensures persistent rate limiting triggers the circuit breaker after the configured failure threshold, giving the provider time to recover. * fix(claude): respect client thinking/effort params to prevent forced quota drain (#1761) Previously, OmniRoute unconditionally injected thinking: {type: 'adaptive'} and output_config: {effort: 'high'} for Claude Opus 4.7 in Claude Code client requests. This caused Claude Max 5h quota to drain in ~15 minutes. Now checks the original client body: if thinking or output_config are explicitly set (even to null or a different value), the injection is skipped. Users can opt-out by sending thinking: null or output_config: {effort: 'low'}. * Add MseeP.ai badge to README.md (#1727) Integrated into release/v3.7.5 * chore(docs): update CHANGELOG for PR #1727 * fix(tests): update stream-utils assertion for responses api compliance * feat: Fix support for claude-cli using Gemini provider (#1779) Integrated into release/v3.7.5 * fix(codex): align client identity metadata (#1778) Integrated into release/v3.7.5 * fix(blackbox-web): correct cookie name and populate session/subscription fields (#1776) Integrated into release/v3.7.5 * Fix Codex /responses/compact passthrough (#1777) Integrated into release/v3.7.5 * test(reasoning-cache): isolate DB state using mkdtempSync to prevent 401 middleware errors * chore(release): v3.7.5 — integrate remaining PRs and finalize stability * chore(config): remove local patch artifacts and trim workspace config Delete temporary patch scripts and local OMC session files that should not ship with the repository. Also remove the Next.js config file and expand editor and TypeScript exclusions to ignore large local workspace directories and reduce unnecessary indexing. * fix(antigravity): cap Claude bridge output tokens (#1785) Integrated into release/v3.7.5 * fix(codex): stabilize Copilot responses replay state (#1791) Integrated into release/v3.7.5 * fix(chatgpt-web): restore validator + expand model catalog to ChatGPT Plus tier (#1792) Integrated into release/v3.7.5 * fix(antigravity): scrub internal OmniRoute headers (#1794) Integrated into release/v3.7.5 * fix(grok-web): fix Grok validator and cookie parsing (#1793) Integrated into release/v3.7.5 * chore(release): v3.7.5 — finalize changelog for LTS patch * feat(api-keys): add rename support in permissions modal Add an editable key name field at the top of the permissions modal, allowing users to rename API keys alongside existing permission settings. The backend already supported name updates via PATCH /api/keys/:id — this wires the UI to send the name field and refreshes the key list on success. Changes: - Add keyName state and text input to PermissionsModal - Update handleUpdatePermissions to validate and send name in PATCH body - Add integration test for rename via PATCH (valid, empty, too-long names) - Update E2E mock to handle PATCH requests * chore(release): finalize v3.7.5 LTS release with schema and db initialization fixes * test: fix json escaping in stream-utilities test * fix(build): restore next.config.mjs that was accidentally deleted * fix(sse): decrement pending requests on passthrough mode failure (#1798) Integrated into release/v3.7.5 * fix(grok-web): repair validator probe + accept full cookie blobs (#1793) Integrated into release/v3.7.5 * docs(i18n): sync documentation updates to 40 languages --------- Signed-off-by: wucm667 <stevenwucongmin@gmail.com> Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com> Co-authored-by: R.D. <rogerproself@gmail.com> Co-authored-by: clousky2020 <33016567+clousky2020@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: cloudy <37777261+uwuclxdy@users.noreply.github.com> Co-authored-by: wucm667 <109257021+wucm667@users.noreply.github.com> Co-authored-by: Randi <55005611+rdself@users.noreply.github.com> Co-authored-by: ivan-mezentsev <ivan@mezentsev.me> Co-authored-by: backryun <bakryun0718@proton.me> Co-authored-by: Dao Bao Ngoc <42265865+daongoc315@users.noreply.github.com> Co-authored-by: ngocdb <ngocdb@ngocdb.local> Co-authored-by: Benson K B <4044180+benzntech@users.noreply.github.com> Co-authored-by: Raxxoor <7317522+dhaern@users.noreply.github.com> Co-authored-by: Jason Landbridge <15127381+JasonLandbridge@users.noreply.github.com> Co-authored-by: slewis3600 <35925982+slewis3600@users.noreply.github.com> Co-authored-by: Markus Hartung <12826053+hartmark@users.noreply.github.com> Co-authored-by: Hernan Javier Ardila Sanchez <204746071+herjarsa@users.noreply.github.com> Co-authored-by: 3_1_3_u <5846351+andruwa13@users.noreply.github.com> Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com> Co-authored-by: i1hwan <35260883+i1hwan@users.noreply.github.com> Co-authored-by: xandr0s <1709302+xandr0s@users.noreply.github.com> Co-authored-by: backryun <24198422+backryun@users.noreply.github.com> Co-authored-by: Owen <36758131+kang-heewon@users.noreply.github.com> Co-authored-by: Ravi Tharuma <25951435+RaviTharuma@users.noreply.github.com> Co-authored-by: Chris <3751981+christopher-s@users.noreply.github.com> Co-authored-by: Wellington Fonseca <5421548+wlfonseca@users.noreply.github.com> Co-authored-by: Ethan Hunt <136065060+only4copilot@users.noreply.github.com> Co-authored-by: tombii <6607822+tombii@users.noreply.github.com> Co-authored-by: AndrewDragonIV <7906124+AndrewDragonIV@users.noreply.github.com> Co-authored-by: Danh Thanh <50534210+dt418@users.noreply.github.com> Co-authored-by: Will F <30637450+willbnu@users.noreply.github.com> Co-authored-by: defhouse <232128212+defhouse@users.noreply.github.com> Co-authored-by: Skydwest <186351198+mercs2910@users.noreply.github.com> Co-authored-by: zenobit <6384793+zen0bit@users.noreply.github.com> Co-authored-by: Ivan <16905671+razllivan@users.noreply.github.com> Co-authored-by: foxy1402 <45601526+foxy1402@users.noreply.github.com> Co-authored-by: Luan Dias <65574834+luandiasrj@users.noreply.github.com> Co-authored-by: Sergei Korolev <891832+knopki@users.noreply.github.com> Co-authored-by: dail45 <69967573+dail45@users.noreply.github.com> Co-authored-by: MseeP.ai <mseep@skydeck.ai> Co-authored-by: Markus Hartung <mail@hartmark.se> Co-authored-by: Raxxoor <manker_lol@hotmail.com> Co-authored-by: Jack <5443152+hijak@users.noreply.github.com> Co-authored-by: Sergey Morozov <tr0st@bk.ru> Co-authored-by: payne <baboialex95@gmail.com> Co-authored-by: Antigravity Assistant <bot@antigravity.local> Co-authored-by: Andrew Munsell <andrew@wizardapps.net>
509 lines
17 KiB
TypeScript
509 lines
17 KiB
TypeScript
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";
|
|
import { makeManagementSessionRequest } from "../helpers/managementSession.ts";
|
|
|
|
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-api-keys-route-"));
|
|
process.env.DATA_DIR = TEST_DATA_DIR;
|
|
process.env.API_KEY_SECRET = "test-api-key-secret";
|
|
process.env.CLOUD_URL = "http://cloud.example";
|
|
|
|
const core = await import("../../src/lib/db/core.ts");
|
|
const apiKeysDb = await import("../../src/lib/db/apiKeys.ts");
|
|
const localDb = await import("../../src/lib/localDb.ts");
|
|
const compliance = await import("../../src/lib/compliance/index.ts");
|
|
const listRoute = await import("../../src/app/api/keys/route.ts");
|
|
const keyRoute = await import("../../src/app/api/keys/[id]/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;
|
|
delete process.env.INITIAL_PASSWORD;
|
|
core.resetDbInstance();
|
|
apiKeysDb.resetApiKeyState();
|
|
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
|
|
}
|
|
|
|
async function enableManagementAuth() {
|
|
process.env.INITIAL_PASSWORD = "bootstrap-password";
|
|
await localDb.updateSettings({ requireLogin: true, password: "" });
|
|
}
|
|
|
|
async function createManagementKey() {
|
|
return apiKeysDb.createApiKey("management", MACHINE_ID);
|
|
}
|
|
|
|
function makeRequest(
|
|
url: string | URL,
|
|
{ method = "GET", token, body }: { method?: string; token?: string; body?: unknown } = {}
|
|
) {
|
|
const headers = new Headers();
|
|
if (token) {
|
|
headers.set("authorization", `Bearer ${token}`);
|
|
}
|
|
if (body !== undefined) {
|
|
headers.set("content-type", "application/json");
|
|
}
|
|
|
|
return new Request(url, {
|
|
method,
|
|
headers,
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
}
|
|
|
|
test.beforeEach(async () => {
|
|
await resetStorage();
|
|
});
|
|
|
|
test.after(async () => {
|
|
await resetStorage();
|
|
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
|
|
});
|
|
|
|
test("API keys routes require management auth when login protection is enabled", async () => {
|
|
await enableManagementAuth();
|
|
|
|
const unauthenticated = await listRoute.GET(new Request("http://localhost/api/keys"));
|
|
const invalidToken = await listRoute.GET(
|
|
new Request("http://localhost/api/keys", {
|
|
headers: { authorization: "Bearer sk-invalid" },
|
|
})
|
|
);
|
|
|
|
const unauthenticatedBody = (await unauthenticated.json()) as any;
|
|
const invalidTokenBody = (await invalidToken.json()) as any;
|
|
|
|
assert.equal(unauthenticated.status, 401);
|
|
assert.equal(unauthenticatedBody.error.message, "Authentication required");
|
|
assert.equal(invalidToken.status, 403);
|
|
assert.equal(invalidTokenBody.error.message, "Invalid management token");
|
|
});
|
|
|
|
test("API keys POST also requires management auth when login protection is enabled", async () => {
|
|
await enableManagementAuth();
|
|
|
|
const unauthenticated = await listRoute.POST(
|
|
makeRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
body: { name: "Blocked Create" },
|
|
})
|
|
);
|
|
const invalidToken = await listRoute.POST(
|
|
makeRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
token: "sk-invalid",
|
|
body: { name: "Blocked Create" },
|
|
})
|
|
);
|
|
|
|
const unauthenticatedBody = (await unauthenticated.json()) as any;
|
|
const invalidTokenBody = (await invalidToken.json()) as any;
|
|
|
|
assert.equal(unauthenticated.status, 401);
|
|
assert.equal(unauthenticatedBody.error.message, "Authentication required");
|
|
assert.equal(invalidToken.status, 403);
|
|
assert.equal(invalidTokenBody.error.message, "Invalid management token");
|
|
});
|
|
|
|
test("POST /api/keys creates a key, preserves special characters, and persists noLog", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
const response = await listRoute.POST(
|
|
await makeManagementSessionRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
body: { name: "Key / Prod #1", noLog: true },
|
|
})
|
|
);
|
|
const body = (await response.json()) as any;
|
|
const stored = await apiKeysDb.getApiKeyById(body.id);
|
|
|
|
assert.equal(response.status, 201);
|
|
assert.equal(body.name, "Key / Prod #1");
|
|
assert.equal(body.noLog, true);
|
|
assert.match(body.key, /^sk-[a-z0-9-]+/i);
|
|
assert.equal(stored?.noLog, true);
|
|
assert.equal(compliance.isNoLog(body.id), true);
|
|
});
|
|
|
|
test("POST /api/keys validates missing and oversized names", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
|
|
const missingName = await listRoute.POST(
|
|
await makeManagementSessionRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
body: {},
|
|
})
|
|
);
|
|
const oversizedName = await listRoute.POST(
|
|
await makeManagementSessionRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
body: { name: "x".repeat(201) },
|
|
})
|
|
);
|
|
|
|
assert.equal(missingName.status, 400);
|
|
assert.equal(oversizedName.status, 400);
|
|
});
|
|
|
|
test("POST /api/keys returns a server error for malformed JSON payloads", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
|
|
const response = await listRoute.POST(
|
|
await makeManagementSessionRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: "{",
|
|
})
|
|
);
|
|
const body = (await response.json()) as any;
|
|
|
|
assert.equal(response.status, 500);
|
|
assert.equal(body.error, "Failed to create key");
|
|
});
|
|
|
|
test("GET /api/keys lists masked keys with pagination and GET /api/keys/[id] stays masked", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
const createdA = await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
|
|
const createdB = await apiKeysDb.createApiKey("Beta", MACHINE_ID);
|
|
|
|
const listResponse = await listRoute.GET(
|
|
await makeManagementSessionRequest("http://localhost/api/keys?limit=1&offset=1")
|
|
);
|
|
const getResponse = await keyRoute.GET(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${createdB.id}`),
|
|
{ params: Promise.resolve({ id: createdB.id }) }
|
|
);
|
|
|
|
const listBody = (await listResponse.json()) as any;
|
|
const getBody = (await getResponse.json()) as any;
|
|
|
|
assert.equal(listResponse.status, 200);
|
|
assert.equal(listBody.total, 3);
|
|
assert.equal(listBody.keys.length, 1);
|
|
assert.equal(listBody.keys[0].id, createdA.id);
|
|
assert.notEqual(listBody.keys[0].key, createdA.key);
|
|
assert.match(listBody.keys[0].key, /\*{4}/);
|
|
|
|
assert.equal(getResponse.status, 200);
|
|
assert.equal(getBody.id, createdB.id);
|
|
assert.notEqual(getBody.key, createdB.key);
|
|
assert.match(getBody.key, /\*{4}/);
|
|
});
|
|
|
|
test("GET /api/keys falls back to default pagination for invalid query params", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
|
|
await apiKeysDb.createApiKey("Beta", MACHINE_ID);
|
|
|
|
const response = await listRoute.GET(
|
|
await makeManagementSessionRequest("http://localhost/api/keys?limit=0&offset=-25")
|
|
);
|
|
const body = (await response.json()) as any;
|
|
|
|
assert.equal(response.status, 200);
|
|
assert.equal(body.total, 3);
|
|
assert.equal(body.keys.length, 3);
|
|
assert.equal(body.keys[0].name, "management");
|
|
});
|
|
|
|
test("GET /api/keys treats non-numeric pagination params as defaults", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
|
|
await apiKeysDb.createApiKey("Beta", MACHINE_ID);
|
|
|
|
const response = await listRoute.GET(
|
|
await makeManagementSessionRequest("http://localhost/api/keys?limit=abc&offset=xyz")
|
|
);
|
|
const body = (await response.json()) as any;
|
|
|
|
assert.equal(response.status, 200);
|
|
assert.equal(body.total, 3);
|
|
assert.equal(body.keys.length, 3);
|
|
assert.deepEqual(
|
|
body.keys.map((entry) => entry.name),
|
|
["management", "Alpha", "Beta"]
|
|
);
|
|
});
|
|
|
|
test("GET /api/keys uses default pagination when query params are absent and reports reveal support", async () => {
|
|
await enableManagementAuth();
|
|
process.env.ALLOW_API_KEY_REVEAL = "true";
|
|
const authKey = await createManagementKey();
|
|
const createdA = await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
|
|
const createdB = await apiKeysDb.createApiKey("Beta", MACHINE_ID);
|
|
|
|
const response = await listRoute.GET(
|
|
await makeManagementSessionRequest("http://localhost/api/keys")
|
|
);
|
|
const body = (await response.json()) as any;
|
|
|
|
assert.equal(response.status, 200);
|
|
assert.equal(body.total, 3);
|
|
assert.equal(body.allowKeyReveal, true);
|
|
assert.equal(body.keys.length, 3);
|
|
assert.deepEqual(
|
|
body.keys.map((entry) => entry.id).sort(),
|
|
[authKey.id, createdA.id, createdB.id].sort()
|
|
);
|
|
assert.ok(body.keys.every((entry) => entry.key !== undefined && entry.key !== ""));
|
|
});
|
|
|
|
test("POST /api/keys triggers cloud sync when cloud mode is enabled", async () => {
|
|
await enableManagementAuth();
|
|
await localDb.updateSettings({ cloudEnabled: true });
|
|
await createManagementKey();
|
|
const originalFetch = globalThis.fetch;
|
|
const calls = [];
|
|
globalThis.fetch = async (url, options = {}) => {
|
|
calls.push({ url, options });
|
|
return Response.json({ changes: { apiKeys: 1 } });
|
|
};
|
|
|
|
try {
|
|
const response = await listRoute.POST(
|
|
await makeManagementSessionRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
body: { name: "Cloud Synced Key" },
|
|
})
|
|
);
|
|
const body = (await response.json()) as any;
|
|
const syncPayload = JSON.parse(calls[0].options.body);
|
|
|
|
assert.equal(response.status, 201);
|
|
assert.equal(body.name, "Cloud Synced Key");
|
|
assert.equal(calls.length, 1);
|
|
assert.match(String(calls[0].url), /^http:\/\/cloud\.example\/sync\//);
|
|
assert.ok(Array.isArray(syncPayload.providers));
|
|
assert.ok(Array.isArray(syncPayload.apiKeys));
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("GET /api/keys returns 500 when the key store throws unexpectedly", async () => {
|
|
await apiKeysDb.createApiKey("Alpha", MACHINE_ID);
|
|
|
|
const db = core.getDbInstance();
|
|
const originalPrepare = db.prepare.bind(db);
|
|
const originalLog = console.log;
|
|
const originalError = console.error;
|
|
|
|
db.prepare = (sql) => {
|
|
if (String(sql).includes("FROM api_keys")) {
|
|
throw new Error("api keys offline");
|
|
}
|
|
return originalPrepare(sql);
|
|
};
|
|
apiKeysDb.resetApiKeyState();
|
|
// Suppress Pino structured log output during test
|
|
console.log = () => {};
|
|
console.error = () => {};
|
|
|
|
try {
|
|
const response = await listRoute.GET(new Request("http://localhost/api/keys"));
|
|
const body = (await response.json()) as any;
|
|
|
|
assert.equal(response.status, 500);
|
|
assert.equal(body.error, "Failed to fetch keys");
|
|
} finally {
|
|
db.prepare = originalPrepare;
|
|
apiKeysDb.resetApiKeyState();
|
|
console.log = originalLog;
|
|
console.error = originalError;
|
|
}
|
|
});
|
|
|
|
test("POST /api/keys still succeeds when cloud sync fails after creation", async () => {
|
|
await enableManagementAuth();
|
|
await localDb.updateSettings({ cloudEnabled: true });
|
|
await createManagementKey();
|
|
const originalFetch = globalThis.fetch;
|
|
let syncAttempts = 0;
|
|
|
|
globalThis.fetch = async () => {
|
|
syncAttempts += 1;
|
|
throw new Error("cloud sync offline");
|
|
};
|
|
|
|
try {
|
|
const response = await listRoute.POST(
|
|
await makeManagementSessionRequest("http://localhost/api/keys", {
|
|
method: "POST",
|
|
body: { name: "Cloud Failure Tolerated" },
|
|
})
|
|
);
|
|
const body = (await response.json()) as any;
|
|
const stored = await apiKeysDb.getApiKeyById(body.id);
|
|
|
|
assert.equal(response.status, 201);
|
|
assert.equal(body.name, "Cloud Failure Tolerated");
|
|
assert.equal(syncAttempts, 1);
|
|
assert.equal(stored?.name, "Cloud Failure Tolerated");
|
|
} finally {
|
|
globalThis.fetch = originalFetch;
|
|
}
|
|
});
|
|
|
|
test("GET /api/keys/[id] returns 404 for an unknown key and reveal is gated by the feature flag", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
const created = await apiKeysDb.createApiKey("Reveal Target", MACHINE_ID);
|
|
|
|
const missingResponse = await keyRoute.GET(
|
|
await makeManagementSessionRequest("http://localhost/api/keys/missing"),
|
|
{ params: Promise.resolve({ id: "missing" }) }
|
|
);
|
|
const revealDisabled = await revealRoute.GET(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}/reveal`),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
|
|
process.env.ALLOW_API_KEY_REVEAL = "true";
|
|
const revealEnabled = await revealRoute.GET(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}/reveal`),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
|
|
const missingBody = (await missingResponse.json()) as any;
|
|
const revealDisabledBody = (await revealDisabled.json()) as any;
|
|
const revealEnabledBody = (await revealEnabled.json()) as any;
|
|
|
|
assert.equal(missingResponse.status, 404);
|
|
assert.equal(missingBody.error, "Key not found");
|
|
assert.equal(revealDisabled.status, 403);
|
|
assert.equal(revealDisabledBody.error, "API key reveal is disabled");
|
|
assert.equal(revealEnabled.status, 200);
|
|
assert.equal(revealEnabledBody.key, created.key);
|
|
});
|
|
|
|
test("PATCH /api/keys/[id] updates permissions and rejects invalid payloads", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
const created = await apiKeysDb.createApiKey("Mutable", MACHINE_ID);
|
|
const patchResponse = await keyRoute.PATCH(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
|
|
method: "PATCH",
|
|
body: {
|
|
noLog: true,
|
|
allowedModels: ["gpt-4.1-mini"],
|
|
allowedConnections: [],
|
|
isActive: false,
|
|
maxSessions: 2,
|
|
},
|
|
}),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
const invalidJsonResponse = await keyRoute.PATCH(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
|
|
method: "PATCH",
|
|
headers: { "content-type": "application/json" },
|
|
body: "{",
|
|
}),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
const missingKeyResponse = await keyRoute.PATCH(
|
|
await makeManagementSessionRequest("http://localhost/api/keys/missing", {
|
|
method: "PATCH",
|
|
body: { noLog: false },
|
|
}),
|
|
{ params: Promise.resolve({ id: "missing" }) }
|
|
);
|
|
|
|
const patchBody = (await patchResponse.json()) as any;
|
|
const invalidJsonBody = (await invalidJsonResponse.json()) as any;
|
|
const missingKeyBody = (await missingKeyResponse.json()) as any;
|
|
const updated = await apiKeysDb.getApiKeyById(created.id);
|
|
|
|
assert.equal(patchResponse.status, 200);
|
|
assert.equal(patchBody.noLog, true);
|
|
assert.equal(patchBody.isActive, false);
|
|
assert.equal(patchBody.maxSessions, 2);
|
|
assert.deepEqual(updated?.allowedModels, ["gpt-4.1-mini"]);
|
|
assert.equal(updated?.noLog, true);
|
|
assert.equal(updated?.isActive, false);
|
|
assert.equal(invalidJsonResponse.status, 400);
|
|
assert.equal(invalidJsonBody.error.message, "Invalid request");
|
|
assert.equal(missingKeyResponse.status, 404);
|
|
assert.equal(missingKeyBody.error, "Key not found");
|
|
});
|
|
|
|
test("PATCH /api/keys/[id] renames a key and rejects invalid names", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
const created = await apiKeysDb.createApiKey("Original Name", MACHINE_ID);
|
|
|
|
// Valid rename
|
|
const renameResponse = await keyRoute.PATCH(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
|
|
method: "PATCH",
|
|
body: { name: "Renamed Key" },
|
|
}),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
const renameBody = (await renameResponse.json()) as any;
|
|
const renamed = await apiKeysDb.getApiKeyById(created.id);
|
|
|
|
assert.equal(renameResponse.status, 200);
|
|
assert.equal(renameBody.name, "Renamed Key");
|
|
assert.equal(renamed?.name, "Renamed Key");
|
|
|
|
// Empty name should be rejected by Zod schema (min(1))
|
|
const emptyNameResponse = await keyRoute.PATCH(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
|
|
method: "PATCH",
|
|
body: { name: " " },
|
|
}),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
assert.equal(emptyNameResponse.status, 400);
|
|
|
|
// Name too long should be rejected (max 200)
|
|
const longNameResponse = await keyRoute.PATCH(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
|
|
method: "PATCH",
|
|
body: { name: "x".repeat(201) },
|
|
}),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
assert.equal(longNameResponse.status, 400);
|
|
});
|
|
|
|
test("DELETE /api/keys/[id] removes keys and reports missing resources", async () => {
|
|
await enableManagementAuth();
|
|
await createManagementKey();
|
|
const created = await apiKeysDb.createApiKey("Disposable", MACHINE_ID);
|
|
|
|
const deleteResponse = await keyRoute.DELETE(
|
|
await makeManagementSessionRequest(`http://localhost/api/keys/${created.id}`, {
|
|
method: "DELETE",
|
|
}),
|
|
{ params: Promise.resolve({ id: created.id }) }
|
|
);
|
|
const missingDeleteResponse = await keyRoute.DELETE(
|
|
await makeManagementSessionRequest("http://localhost/api/keys/missing", {
|
|
method: "DELETE",
|
|
}),
|
|
{ params: Promise.resolve({ id: "missing" }) }
|
|
);
|
|
|
|
const deleteBody = (await deleteResponse.json()) as any;
|
|
const missingDeleteBody = (await missingDeleteResponse.json()) as any;
|
|
|
|
assert.equal(deleteResponse.status, 200);
|
|
assert.equal(deleteBody.message, "Key deleted successfully");
|
|
assert.equal(await apiKeysDb.getApiKeyById(created.id), null);
|
|
assert.equal(missingDeleteResponse.status, 404);
|
|
assert.equal(missingDeleteBody.error, "Key not found");
|
|
});
|