Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,15 @@ When adding code that mutates provider state or sends commands (`load_model`, et
4. Check the cleanup path — `Disconnect()` must clear any per-provider state you add.
5. Verify pre-existing invariants: `maxModelSlots`, heartbeat field omission semantics (`nil` vs empty), and the 3x memory gate on the provider side.

## Code Structure & Modularity

Keep the codebase modular, never monolithic.

- Prefer small, single-responsibility files over large catch-all ones. Split by concern: types, pure helpers, data/IO hooks, UI pieces, and a thin orchestrator that wires them together.
- Group a feature's files into a dedicated module/folder with a thin entry point. Examples: the coordinator's top-level Go packages (`registry/`, `billing/`, `store/`), and `console-ui/src/components/api-keys/` (`constants`, `format`, `limits`, `Modal`, `KeyForm`, `KeyCard`, a `useApiKeys` data hook, and a thin `ApiKeysManager` orchestrator).
- One file/component should do one thing. If a file mixes several concerns or grows past a few hundred lines, that's a signal to split it.
- **At the end of every large piece of work, do a refactor pass to make it modular before calling it done.** Extract helpers/types/hooks into focused files, delete dead code, and keep the public entry point thin. The refactor must be behavior-preserving — build, lint, and tests stay green.

## Formatting

A pre-commit hook in `.githooks/pre-commit` checks staged files only. It is enabled via:
Expand Down
11 changes: 10 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,18 @@ Every new feature or non-trivial change must ship with tests. Don't rely on "the

The goal is "next engineer can change this and CI tells them if they broke it," not "it worked on my machine today."

## Code Structure & Modularity

Keep the codebase modular, never monolithic.

- Prefer small, single-responsibility files over large catch-all ones. Split by concern: types, pure helpers, data/IO hooks, UI pieces, and a thin orchestrator that wires them together.
- Group a feature's files into a dedicated module/folder with a thin entry point. Examples: the coordinator's top-level Go packages (`registry/`, `billing/`, `store/`), and `console-ui/src/components/api-keys/` (`constants`, `format`, `limits`, `Modal`, `KeyForm`, `KeyCard`, a `useApiKeys` data hook, and a thin `ApiKeysManager` orchestrator).
- One file/component should do one thing. If a file mixes several concerns or grows past a few hundred lines, that's a signal to split it.
- **At the end of every large piece of work, do a refactor pass to make it modular before calling it done.** Extract helpers/types/hooks into focused files, delete dead code, and keep the public entry point thin. The refactor must be behavior-preserving — build, lint, and tests stay green.

## Quality Gate

After completing each objective (task, plan phase, or discrete unit of work), spawn **both** reviewers in parallel:
After completing each objective (task, plan phase, or discrete unit of work), first do a modular refactor pass on any large change (see **Code Structure & Modularity**), then spawn **both** reviewers in parallel:

1. **Codex rescue subagent** (`codex:codex-rescue`) — reviews the diff for correctness, regressions, and build/test pass
2. **Claude Code subagent** (`Agent` tool, general-purpose) — independently reviews the same diff for correctness, edge cases, and code quality
Expand Down
207 changes: 207 additions & 0 deletions console-ui/__tests__/api-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,3 +329,210 @@ describe("POST /api/invite/redeem", () => {
expect(data.error.message).toBe("Invalid code");
});
});

// =========================================================================
// /api/keys (list + create)
// =========================================================================

function upstreamJson(status: number, body: unknown): Response {
return new Response(JSON.stringify(body), {
status,
headers: { "Content-Type": "application/json" },
});
}

describe("/api/keys", () => {
it("GET proxies Privy auth to coordinator /v1/keys and ignores x-coordinator-url", async () => {
upstreamFetch.mockResolvedValueOnce(upstreamOk({ object: "list", data: [] }));

const { GET } = await import("@/app/api/keys/route");
const req = makeRequest("/api/keys", {
headers: {
authorization: "Bearer privy-1",
"x-coordinator-url": "https://attacker.example.com",
},
});
const res = await GET(req);

expect(res.status).toBe(200);
const [url, opts] = upstreamFetch.mock.calls[0];
expect(url).toBe(`${DEFAULT_COORD}/v1/keys`);
expect(opts.headers.Authorization).toBe("Bearer privy-1");
});

it("GET falls back to the privy-token cookie", async () => {
upstreamFetch.mockResolvedValueOnce(upstreamOk({ object: "list", data: [] }));

const { GET } = await import("@/app/api/keys/route");
const req = makeRequest("/api/keys", {
headers: { cookie: "privy-token=cookie-tok" },
});
const res = await GET(req);

expect(res.status).toBe(200);
const [, opts] = upstreamFetch.mock.calls[0];
expect(opts.headers.Authorization).toBe("Bearer cookie-tok");
});

it("GET rejects missing auth with 401", async () => {
const { GET } = await import("@/app/api/keys/route");
const res = await GET(makeRequest("/api/keys"));

expect(res.status).toBe(401);
expect(upstreamFetch).not.toHaveBeenCalled();
});

it("POST forwards the body and passes through the once-only secret", async () => {
upstreamFetch.mockResolvedValueOnce(
upstreamJson(201, { key: "sk-db-secret", data: { id: "key_1", name: "prod" } })
);

const { POST } = await import("@/app/api/keys/route");
const req = makeRequest("/api/keys", {
method: "POST",
headers: { "Content-Type": "application/json", authorization: "Bearer privy-1" },
body: JSON.stringify({ name: "prod", limit_usd: 5 }),
});
const res = await POST(req);

expect(res.status).toBe(201);
const data = await res.json();
expect(data.key).toBe("sk-db-secret");

const [url, opts] = upstreamFetch.mock.calls[0];
expect(url).toBe(`${DEFAULT_COORD}/v1/keys`);
expect(opts.method).toBe("POST");
expect(opts.headers.Authorization).toBe("Bearer privy-1");
expect(JSON.parse(opts.body)).toEqual({ name: "prod", limit_usd: 5 });
});

it("POST passes through upstream error status + JSON", async () => {
upstreamFetch.mockResolvedValueOnce(upstreamJson(400, { error: { message: "bad name" } }));

const { POST } = await import("@/app/api/keys/route");
const req = makeRequest("/api/keys", {
method: "POST",
headers: { "Content-Type": "application/json", authorization: "Bearer privy-1" },
body: JSON.stringify({}),
});
const res = await POST(req);

expect(res.status).toBe(400);
const data = await res.json();
expect(data.error.message).toBe("bad name");
});
});

// =========================================================================
// /api/keys/[id] (get + patch + delete)
// =========================================================================

describe("/api/keys/[id]", () => {
const ctx = (id: string) => ({ params: Promise.resolve({ id }) });

it("GET proxies to /v1/keys/{id}", async () => {
upstreamFetch.mockResolvedValueOnce(upstreamOk({ id: "key_1", name: "prod" }));

const { GET } = await import("@/app/api/keys/[id]/route");
const req = makeRequest("/api/keys/key_1", { headers: { authorization: "Bearer privy-1" } });
const res = await GET(req, ctx("key_1"));

expect(res.status).toBe(200);
const [url, opts] = upstreamFetch.mock.calls[0];
expect(url).toBe(`${DEFAULT_COORD}/v1/keys/key_1`);
expect(opts.headers.Authorization).toBe("Bearer privy-1");
});

it("PATCH forwards the body (including null to clear a field)", async () => {
upstreamFetch.mockResolvedValueOnce(upstreamOk({ id: "key_1", disabled: true }));

const { PATCH } = await import("@/app/api/keys/[id]/route");
const req = makeRequest("/api/keys/key_1", {
method: "PATCH",
headers: { "Content-Type": "application/json", authorization: "Bearer privy-1" },
body: JSON.stringify({ disabled: true, limit_usd: null }),
});
const res = await PATCH(req, ctx("key_1"));

expect(res.status).toBe(200);
const [url, opts] = upstreamFetch.mock.calls[0];
expect(url).toBe(`${DEFAULT_COORD}/v1/keys/key_1`);
expect(opts.method).toBe("PATCH");
expect(JSON.parse(opts.body)).toEqual({ disabled: true, limit_usd: null });
});

it("DELETE proxies to /v1/keys/{id} and passes through the revoked status", async () => {
upstreamFetch.mockResolvedValueOnce(upstreamOk({ status: "revoked" }));

const { DELETE } = await import("@/app/api/keys/[id]/route");
const req = makeRequest("/api/keys/key_1", {
method: "DELETE",
headers: { authorization: "Bearer privy-1" },
});
const res = await DELETE(req, ctx("key_1"));

expect(res.status).toBe(200);
const data = await res.json();
expect(data.status).toBe("revoked");
const [url, opts] = upstreamFetch.mock.calls[0];
expect(url).toBe(`${DEFAULT_COORD}/v1/keys/key_1`);
expect(opts.method).toBe("DELETE");
});

it("URL-encodes the key id", async () => {
upstreamFetch.mockResolvedValueOnce(upstreamOk({ id: "weird id" }));

const { GET } = await import("@/app/api/keys/[id]/route");
const req = makeRequest("/api/keys/weird", { headers: { authorization: "Bearer p" } });
await GET(req, ctx("weird id"));

const [url] = upstreamFetch.mock.calls[0];
expect(url).toBe(`${DEFAULT_COORD}/v1/keys/weird%20id`);
});

it("rejects missing auth with 401", async () => {
const { DELETE } = await import("@/app/api/keys/[id]/route");
const res = await DELETE(makeRequest("/api/keys/key_1", { method: "DELETE" }), ctx("key_1"));

expect(res.status).toBe(401);
expect(upstreamFetch).not.toHaveBeenCalled();
});
});

// =========================================================================
// /api/keys/[id]/rotate
// =========================================================================

describe("/api/keys/[id]/rotate", () => {
it("POST proxies to /v1/keys/{id}/rotate and returns the new secret", async () => {
upstreamFetch.mockResolvedValueOnce(
upstreamJson(200, { key: "sk-db-new", data: { id: "key_1" } })
);

const { POST } = await import("@/app/api/keys/[id]/rotate/route");
const req = makeRequest("/api/keys/key_1/rotate", {
method: "POST",
headers: { authorization: "Bearer privy-1" },
});
const res = await POST(req, { params: Promise.resolve({ id: "key_1" }) });

expect(res.status).toBe(200);
const data = await res.json();
expect(data.key).toBe("sk-db-new");

const [url, opts] = upstreamFetch.mock.calls[0];
expect(url).toBe(`${DEFAULT_COORD}/v1/keys/key_1/rotate`);
expect(opts.method).toBe("POST");
expect(opts.headers.Authorization).toBe("Bearer privy-1");
});

it("rejects missing auth with 401", async () => {
const { POST } = await import("@/app/api/keys/[id]/rotate/route");
const res = await POST(makeRequest("/api/keys/key_1/rotate", { method: "POST" }), {
params: Promise.resolve({ id: "key_1" }),
});

expect(res.status).toBe(401);
expect(upstreamFetch).not.toHaveBeenCalled();
});
});
96 changes: 96 additions & 0 deletions console-ui/__tests__/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ import {
fetchModels,
fetchPricing,
healthCheck,
listApiKeys,
createApiKey,
updateApiKey,
deleteApiKey,
rotateApiKey,
} from "@/lib/api";

// ---------------------------------------------------------------------------
Expand Down Expand Up @@ -322,6 +327,97 @@ describe("healthCheck", () => {
});
});

// ---------------------------------------------------------------------------
// API key management client (Privy-authenticated, /api/keys proxy)
// ---------------------------------------------------------------------------

describe("API key management client", () => {
it("listApiKeys GETs /api/keys with a Bearer token and unwraps data", async () => {
fetchMock.mockResolvedValueOnce(
jsonResponse({ object: "list", data: [{ id: "key_1", name: "prod" }] })
);

const result = await listApiKeys("privy-tok");

const [url, opts] = fetchMock.mock.calls[0];
expect(url).toBe("/api/keys");
expect(opts.headers.Authorization).toBe("Bearer privy-tok");
expect(opts.headers["x-api-key"]).toBeUndefined();
expect(result).toEqual([{ id: "key_1", name: "prod" }]);
});

it("listApiKeys throws the server error message on failure", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ error: { message: "forbidden" } }, 403));
await expect(listApiKeys("t")).rejects.toThrow("forbidden");
});

it("createApiKey POSTs the body and returns the once-only secret", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ key: "sk-db-x", data: { id: "key_2" } }));

const result = await createApiKey("t", {
name: "prod",
limit_usd: 10,
limit_reset: "monthly",
});

const [url, opts] = fetchMock.mock.calls[0];
expect(url).toBe("/api/keys");
expect(opts.method).toBe("POST");
expect(opts.headers.Authorization).toBe("Bearer t");
expect(JSON.parse(opts.body)).toEqual({
name: "prod",
limit_usd: 10,
limit_reset: "monthly",
});
expect(result.key).toBe("sk-db-x");
expect(result.data.id).toBe("key_2");
});

it("updateApiKey PATCHes /api/keys/{id} and forwards null to clear a field", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ id: "key_2", disabled: true }));

await updateApiKey("t", "key_2", { disabled: true, limit_usd: null });

const [url, opts] = fetchMock.mock.calls[0];
expect(url).toBe("/api/keys/key_2");
expect(opts.method).toBe("PATCH");
expect(opts.headers.Authorization).toBe("Bearer t");
expect(JSON.parse(opts.body)).toEqual({ disabled: true, limit_usd: null });
});

it("deleteApiKey DELETEs /api/keys/{id}", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ status: "revoked" }));

await deleteApiKey("t", "key_2");

const [url, opts] = fetchMock.mock.calls[0];
expect(url).toBe("/api/keys/key_2");
expect(opts.method).toBe("DELETE");
expect(opts.headers.Authorization).toBe("Bearer t");
});

it("rotateApiKey POSTs /api/keys/{id}/rotate and returns the new secret", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ key: "sk-db-rot", data: { id: "key_2" } }));

const result = await rotateApiKey("t", "key_2");

const [url, opts] = fetchMock.mock.calls[0];
expect(url).toBe("/api/keys/key_2/rotate");
expect(opts.method).toBe("POST");
expect(opts.headers.Authorization).toBe("Bearer t");
expect(result.key).toBe("sk-db-rot");
});

it("URL-encodes the key id in management routes", async () => {
fetchMock.mockResolvedValueOnce(jsonResponse({ status: "revoked" }));

await deleteApiKey("t", "key/with space");

const [url] = fetchMock.mock.calls[0];
expect(url).toBe("/api/keys/key%2Fwith%20space");
});
});

// ---------------------------------------------------------------------------
// proxyHeaders
// ---------------------------------------------------------------------------
Expand Down
Loading
Loading