Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
154 changes: 154 additions & 0 deletions apps/api/src/routes/chat.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";

import { app } from "@/index.js";
import { createTestUser, deleteAll } from "@/testing.js";

import { db, eq, tables } from "@llmgateway/db";
import { ONBOARDING_MAX_TOKENS, ONBOARDING_MODEL } from "@llmgateway/shared";

// The onboarding wizard's "try it now" request runs through this proxy: the
// gateway refuses cross-origin browser calls, so the UI posts here with its
// session cookie and the server forwards to the gateway. A brand new
// organization has no credits, so that first call is sponsored by a
// platform-owned key — which means the endpoint has to stay session-gated (the
// UI must send its cookie), and the sponsored path has to pin what it spends
// rather than trusting the request body.

describe("chat completion proxy", () => {
let token: string;
let gatewayRequests: {
url: string;
authorization: string | null;
body: Record<string, unknown>;
}[] = [];

beforeEach(async () => {
token = await createTestUser();
gatewayRequests = [];
process.env.ONBOARDING_CHAT_API_KEY = "platform-onboarding-key";

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const originalFetch = globalThis.fetch;
vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.toString()
: input.url;

if (!url.includes("/chat/completions")) {
return await originalFetch(input, init);
}

gatewayRequests.push({
url,
authorization: new Headers(init?.headers).get("authorization"),
body: JSON.parse(String(init?.body ?? "{}")),
});

return new Response(
JSON.stringify({
id: "chatcmpl-proxy",
model: ONBOARDING_MODEL,
choices: [
{
index: 0,
message: { role: "assistant", content: "Hello from the gateway" },
finish_reason: "stop",
},
],
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
});
});

afterEach(async () => {
vi.restoreAllMocks();
delete process.env.ONBOARDING_CHAT_API_KEY;
await deleteAll();
});

function request(body: Record<string, unknown>, cookie?: string) {
return app.request("/chat/completion", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(cookie ? { Cookie: cookie } : {}),
},
body: JSON.stringify({
messages: [{ role: "user", content: "Hello!" }],
...body,
}),
});
}

test("rejects an unauthenticated request", async () => {
const res = await request({ model: "auto", apiKey: "test-token" });

expect(res.status).toBe(401);
expect(gatewayRequests).toHaveLength(0);
});

test("sponsors the first onboarding call with the platform key", async () => {
const res = await request(
{ model: ONBOARDING_MODEL, apiKey: "user-token", onboarding: true },
token,
);

expect(res.status).toBe(200);
expect(gatewayRequests).toHaveLength(1);
expect(gatewayRequests[0].url).toContain("/v1/chat/completions");
expect(gatewayRequests[0].authorization).toBe(
"Bearer platform-onboarding-key",
);
expect(gatewayRequests[0].body).toMatchObject({
model: ONBOARDING_MODEL,
onboarding: true,
max_tokens: ONBOARDING_MAX_TOKENS,
});
});

test("pins the sponsored model instead of trusting the request", async () => {
await request(
{ model: "gpt-4o", apiKey: "user-token", onboarding: true },
token,
);

expect(gatewayRequests[0].body.model).toBe(ONBOARDING_MODEL);
});

test("stops sponsoring once onboarding is complete", async () => {
await db
.update(tables.user)
.set({ onboardingCompleted: true })
.where(eq(tables.user.id, "test-user-id"));

await request(
{ model: ONBOARDING_MODEL, apiKey: "user-token", onboarding: true },
token,
);

expect(gatewayRequests[0].authorization).toBe("Bearer user-token");
expect(gatewayRequests[0].body).not.toHaveProperty("max_tokens");
});

test("falls back to the caller's key when no platform key is configured", async () => {
delete process.env.ONBOARDING_CHAT_API_KEY;

await request(
{ model: ONBOARDING_MODEL, apiKey: "user-token", onboarding: true },
token,
);

expect(gatewayRequests[0].authorization).toBe("Bearer user-token");
});

test("leaves non-onboarding requests on the caller's key", async () => {
await request({ model: "gpt-4o", apiKey: "user-token" }, token);

expect(gatewayRequests[0].authorization).toBe("Bearer user-token");
expect(gatewayRequests[0].body.model).toBe("gpt-4o");
expect(gatewayRequests[0].body).not.toHaveProperty("onboarding");
});
});
36 changes: 33 additions & 3 deletions apps/api/src/routes/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,26 @@ import { z } from "zod";

import { getGatewayUrl } from "@/utils/playground-key.js";

import { db } from "@llmgateway/db";
import { logger } from "@llmgateway/logger";
import { ONBOARDING_MAX_TOKENS, ONBOARDING_MODEL } from "@llmgateway/shared";

import type { ServerTypes } from "@/vars.js";

const chat = new OpenAPIHono<ServerTypes>();

// A brand new organization has no credits, so the onboarding wizard's first
// call is sponsored by a platform-owned key. Because we pay for it, the
// sponsored path pins the model and an output cap server-side instead of
// trusting the request, and only applies to an account that hasn't finished
// onboarding yet. Without a platform key configured (self-hosted, local dev)
// the call falls back to the account's own key, exactly as before.
function getOnboardingApiKey() {
return (
process.env.ONBOARDING_CHAT_API_KEY ?? process.env.SUPPORT_CHAT_API_KEY
);
}

const chatCompletionSchema = z.object({
messages: z.array(
z.object({
Expand Down Expand Up @@ -49,22 +63,38 @@ chat.openapi(completionRoute, async (c) => {
const { messages, model, stream, apiKey, free_models_only, onboarding } =
body;

const sessionUser = c.get("user");
const onboardingApiKey = getOnboardingApiKey();
const sponsored = Boolean(
onboarding &&
onboardingApiKey &&
sessionUser &&
!(
await db.query.user.findFirst({
where: { id: { eq: sessionUser.id } },
columns: { onboardingCompleted: true },
})
)?.onboardingCompleted,
);

// Require user to provide their own API key
if (!apiKey) {
if (!sponsored && !apiKey) {
return c.json({ error: "API key is required" }, 400);
}
const authToken = apiKey;
const authToken = sponsored ? onboardingApiKey! : apiKey!;

const response = await fetch(`${getGatewayUrl()}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${authToken}`,
...(sponsored && { "x-source": "onboarding" }),
},
body: JSON.stringify({
model,
model: sponsored ? ONBOARDING_MODEL : model,
messages,
stream,
...(sponsored && { max_tokens: ONBOARDING_MAX_TOKENS }),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
...(free_models_only !== undefined && { free_models_only }),
...(onboarding !== undefined && { onboarding }),
}),
Expand Down
40 changes: 40 additions & 0 deletions apps/api/src/utils/playground-key.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { afterEach, describe, expect, test } from "vitest";

import { getGatewayUrl } from "@/utils/playground-key.js";

describe("getGatewayUrl", () => {
const previousGatewayUrl = process.env.GATEWAY_URL;
const previousNodeEnv = process.env.NODE_ENV;

afterEach(() => {
if (previousGatewayUrl === undefined) {
delete process.env.GATEWAY_URL;
} else {
process.env.GATEWAY_URL = previousGatewayUrl;
}
process.env.NODE_ENV = previousNodeEnv;
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Deployments and local `.envrc` blocks write GATEWAY_URL both ways, and
// every caller appends a `/v1` path to what this returns.
test("appends the /v1 suffix when GATEWAY_URL omits it", () => {
process.env.GATEWAY_URL = "http://localhost:4001";
expect(getGatewayUrl()).toBe("http://localhost:4001/v1");
});

test("keeps a single /v1 suffix when GATEWAY_URL already has it", () => {
process.env.GATEWAY_URL = "https://api.llmgateway.io/v1";
expect(getGatewayUrl()).toBe("https://api.llmgateway.io/v1");
});

test("tolerates a trailing slash", () => {
process.env.GATEWAY_URL = "https://api.llmgateway.io/v1/";
expect(getGatewayUrl()).toBe("https://api.llmgateway.io/v1");
});

test("falls back to the local gateway in development", () => {
delete process.env.GATEWAY_URL;
process.env.NODE_ENV = "development";
expect(getGatewayUrl()).toBe("http://localhost:4001/v1");
});
});
16 changes: 10 additions & 6 deletions apps/api/src/utils/playground-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@ import type { Context } from "hono";
export const PLAYGROUND_KEY_COOKIE_NAME = "llmgateway_playground_key";

export function getGatewayUrl() {
return (
process.env.GATEWAY_URL ??
(process.env.NODE_ENV === "development"
? "http://localhost:4001/v1"
: "https://api.llmgateway.io/v1")
);
const configured = process.env.GATEWAY_URL?.trim();
if (configured) {
// GATEWAY_URL is set both with and without the `/v1` suffix depending on
// the environment (the frontends strip it off, every caller of this
// helper appends `/v1` paths), so normalize to exactly one `/v1`.
return `${configured.replace(/\/+$/, "").replace(/\/v1$/, "")}/v1`;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
return process.env.NODE_ENV === "development"
? "http://localhost:4001/v1"
: "https://api.llmgateway.io/v1";
}

interface PlaygroundKeyUser {
Expand Down
2 changes: 2 additions & 0 deletions apps/ui/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

# testing
/coverage
/test-results
/playwright-report

# next.js
/.next/
Expand Down
Loading
Loading