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
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ SUPABASE_SECRET_KEY=
# NVIDIA AI provider
NVIDIA_API_KEY=
NVIDIA_KIMI_MODEL=moonshotai/kimi-k3
NVIDIA_RESEARCH_MODEL=z-ai/glm-5-3-flash
NVIDIA_RESEARCH_MODEL=z-ai/glm-5.3-flash

# Free trial — three days of access granted once, automatically, to a new
# account (see supabase/migrations/20261013_free_trial.sql).
Expand Down
90 changes: 72 additions & 18 deletions lib/ai/nvidia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,84 @@ import { parseSSEPayload } from "@/lib/ai/sse";
import { normalizeAIUsage, type AICompletionInput, type AICompletionResult } from "@/lib/ai/types";

const DEFAULT_KIMI_MODEL = "moonshotai/kimi-k3";
const DEFAULT_RESEARCH_MODEL = "z-ai/glm-5-3-flash";
// The dash in "glm-5-3" is page-slug styling; the API model ID keeps the dot
// ("glm-5.3-flash"). The dashed form is not a catalog model — NVIDIA's gateway
// answers 404 ("404 page not found") for it.
const DEFAULT_RESEARCH_MODEL = "z-ai/glm-5.3-flash";
const LEGACY_RESEARCH_MODEL_ALIASES: Record<string, string> = {
// Dotted form was sent briefly and NVIDIA rejects it (404 unknown model).
"z-ai/glm-5.3-flash": DEFAULT_RESEARCH_MODEL,
// Dashed form shipped in .env.example and deployed env vars; auto-heal it.
"z-ai/glm-5-3-flash": DEFAULT_RESEARCH_MODEL,
"deepseek-ai/deepseek-v4-flash-0731": DEFAULT_RESEARCH_MODEL,
"minimaxai/minimax-m3": DEFAULT_RESEARCH_MODEL,
};

/** Every hosted NVIDIA key (build.nvidia.com / NGC) carries this prefix. */
const NVIDIA_KEY_PREFIX = "nvapi-";

/**
* Resolve a model env override, failing closed when the value looks like an
* API key. A key pasted into NVIDIA_KIMI_MODEL / NVIDIA_RESEARCH_MODEL is
* otherwise sent to NVIDIA as the *model name* — the gateway answers 404
* ("404 page not found") and the raw key is echoed straight back to end users
* inside the error message. Refusing to start turns that silent key leak into
* an actionable operator error.
*/
function resolveModel(envValue: string | undefined, fallback: string, envName: string): string {
const configured = envValue?.trim();
if (!configured) return fallback;
if (configured.startsWith(NVIDIA_KEY_PREFIX)) {
throw new ApiError(
500,
"nvidia_model_misconfigured",
`${envName} looks like an API key, not a model ID. Move that value into NVIDIA_API_KEY and set ${envName} to a model ID (for example ${fallback}), or delete ${envName} to use the default.`,
);
}
return configured;
}

/**
* Read and validate the hosted NVIDIA key. Kept synchronous (like the model
* guard above) so misconfiguration surfaces as an immediate, typed ApiError
* from the public callers below instead of a stray async rejection.
*/
function requireNvidiaApiKey(): string {
const apiKey = process.env.NVIDIA_API_KEY?.trim();

if (!apiKey) {
throw new ApiError(
500,
"nvidia_not_configured",
"The NVIDIA AI provider is not configured yet. Add NVIDIA_API_KEY.",
);
}

// The endpoint is pinned to integrate.api.nvidia.com, whose keys always
// start with `nvapi-`. Anything else here is the classic swapped-env mistake
// (the model ID was pasted into NVIDIA_API_KEY); fail closed with an
// actionable error instead of streaming NVIDIA's auth failure to the user.
if (!apiKey.startsWith(NVIDIA_KEY_PREFIX)) {
throw new ApiError(
500,
"nvidia_key_misconfigured",
"NVIDIA_API_KEY does not look like a hosted NVIDIA key — hosted keys start with \"nvapi-\". Check that a model ID was not pasted into NVIDIA_API_KEY by mistake.",
);
}

return apiKey;
}

/** Max mode: the larger reasoning model. */
export function callNvidiaKimi(input: AICompletionInput) {
return callNvidiaModel(input, process.env.NVIDIA_KIMI_MODEL || DEFAULT_KIMI_MODEL, "nvidia-kimi");
const model = resolveModel(process.env.NVIDIA_KIMI_MODEL, DEFAULT_KIMI_MODEL, "NVIDIA_KIMI_MODEL");
return callNvidiaModel(input, requireNvidiaApiKey(), model, "nvidia-kimi");
}

/** Quick and thorough modes: the configured NVIDIA research model through NIM. */
export function callNvidiaResearch(input: AICompletionInput) {
const configuredModel = process.env.NVIDIA_RESEARCH_MODEL?.trim() || DEFAULT_RESEARCH_MODEL;
const configuredModel = resolveModel(process.env.NVIDIA_RESEARCH_MODEL, DEFAULT_RESEARCH_MODEL, "NVIDIA_RESEARCH_MODEL");
const model = LEGACY_RESEARCH_MODEL_ALIASES[configuredModel] || configuredModel;

return callNvidiaModel(input, model, "nvidia");
return callNvidiaModel(input, requireNvidiaApiKey(), model, "nvidia");
}

/** Redact bearer tokens and API keys from a provider message before logging or display. */
Expand Down Expand Up @@ -64,18 +123,13 @@ async function readProviderError(response: Response) {
/** Call an NVIDIA NIM chat model and return its output as a cancellable SSE stream. */
async function callNvidiaModel(
input: AICompletionInput,
apiKey: string,
model: string,
provider: "nvidia" | "nvidia-kimi",
): Promise<AICompletionResult> {
const apiKey = process.env.NVIDIA_API_KEY;

if (!apiKey) {
throw new ApiError(
500,
"nvidia_not_configured",
"The NVIDIA AI provider is not configured yet. Add NVIDIA_API_KEY.",
);
}
// Model names are interpolated into client-visible error strings below.
// Redact first so a misconfigured value can never be echoed to users raw.
const safeModel = redactProviderMessage(model);

const maxTokens = input.maxTokens ?? 12_000;
const timeoutMs = maxTokens <= 2_000 ? 75_000 : 240_000;
Expand Down Expand Up @@ -136,7 +190,7 @@ async function callNvidiaModel(
if (!response.ok) {
const providerMessage = await readProviderError(response);
emit({
error: `NVIDIA ${model} request failed (${response.status}): ${providerMessage}`,
error: `NVIDIA ${safeModel} request failed (${response.status}): ${providerMessage}`,
});
emit({ finishReason: "error" });
emit({ done: true });
Expand All @@ -157,10 +211,10 @@ async function callNvidiaModel(
let sawAnyData = false;

const emitProviderError = (message: string) => {
logger.error(`NVIDIA ${model} stream error`, {
logger.error(`NVIDIA ${safeModel} stream error`, {
detail: redactProviderMessage(message).slice(0, 500),
});
emit({ error: `NVIDIA ${model} request failed: ${redactProviderMessage(message)}` });
emit({ error: `NVIDIA ${safeModel} request failed: ${redactProviderMessage(message)}` });
finishReason = "error";
emit({ finishReason });
};
Expand Down
6 changes: 4 additions & 2 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ SUPABASE_JWKS_URL=https://YOUR_PROJECT.supabase.co/auth/v1/.well-known/jwks.json

NVIDIA_API_KEY=
NVIDIA_KIMI_MODEL=moonshotai/kimi-k3
NVIDIA_RESEARCH_MODEL=z-ai/glm-5-3-flash
NVIDIA_RESEARCH_MODEL=z-ai/glm-5.3-flash

ADMIN_SESSION_SECRET=
ADMIN_OWNER_UIDS=
Expand Down Expand Up @@ -162,7 +162,9 @@ Supabase Authentication → Providers → Google must be enabled with the matchi

## AI provider configuration

AI requests are authenticated server-side and continue to use the existing paid-access and request-rate controls. Every mode runs through NVIDIA NIM (`https://integrate.api.nvidia.com/v1/chat/completions`) using the server-only `NVIDIA_API_KEY`, and only the model differs: **Max** uses `moonshotai/kimi-k3` (`NVIDIA_KIMI_MODEL`), while **Thorough** and **Quick** use `z-ai/glm-5-3-flash` (`NVIDIA_RESEARCH_MODEL`), with Quick on the smaller output budget and Thorough on the larger one. There is deliberately no base-URL variable — the NVIDIA endpoint is fixed — and no second provider is configured, so an absent `NVIDIA_API_KEY` disables AI features instead of falling back to another vendor. Do not expose provider keys through any `NEXT_PUBLIC_*` variable. The NVIDIA key previously pasted into chat must be rotated before use.
AI requests are authenticated server-side and continue to use the existing paid-access and request-rate controls. Every mode runs through NVIDIA NIM (`https://integrate.api.nvidia.com/v1/chat/completions`) using the server-only `NVIDIA_API_KEY`, and only the model differs: **Max** uses `moonshotai/kimi-k3` (`NVIDIA_KIMI_MODEL`), while **Thorough** and **Quick** use `z-ai/glm-5.3-flash` (`NVIDIA_RESEARCH_MODEL`), with Quick on the smaller output budget and Thorough on the larger one. There is deliberately no base-URL variable — the NVIDIA endpoint is fixed — and no second provider is configured, so an absent `NVIDIA_API_KEY` disables AI features instead of falling back to another vendor. Do not expose provider keys through any `NEXT_PUBLIC_*` variable. The NVIDIA key previously pasted into chat must be rotated before use.

**Troubleshooting — `NVIDIA <model> request failed (404): 404 page not found`:** two known causes. **1. Swapped env vars:** the message shows your `nvapi-...` key where the model name should be — the key was pasted into `NVIDIA_KIMI_MODEL` / `NVIDIA_RESEARCH_MODEL`. Only `NVIDIA_API_KEY` may contain the key; the model variables must hold model IDs (see `.env.example`) or be deleted to use the defaults. The provider fails closed with `nvidia_model_misconfigured` / `nvidia_key_misconfigured` errors naming the swapped variable, and an exposed key must be rotated at build.nvidia.com. **2. Stale model ID:** the message shows a real-looking model that NVIDIA's catalog no longer serves under that spelling — e.g. the dashed `z-ai/glm-5-3-flash` (the API ID keeps the dot: `z-ai/glm-5.3-flash`). Check the current ID on the model's build.nvidia.com page and update `NVIDIA_RESEARCH_MODEL` / `NVIDIA_KIMI_MODEL`. The known retired spellings are remapped automatically in `lib/ai/nvidia.ts`.


## License
Expand Down
170 changes: 170 additions & 0 deletions tests/nvidia-model-guard.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { describe, it, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";

import { ApiError } from "@/lib/api";
import { callNvidiaKimi, callNvidiaResearch } from "@/lib/ai/nvidia";

// Regression tests for the misconfiguration behind
// "NVIDIA nvapi-... request failed (404): 404 page not found": an API key
// sitting in a *model* env var. Before the guard, that value was sent upstream
// as the model name (gateway 404) and echoed back to end users inside the
// error string — a key leak. The provider must fail closed with an actionable
// operator error instead.

const KEY_ENV = "NVIDIA_API_KEY";
const MODEL_ENVS = ["NVIDIA_KIMI_MODEL", "NVIDIA_RESEARCH_MODEL"] as const;

const VALID_KEY = "nvapi-test-key-0000000000000000000000000000000";

const savedEnv: Record<string, string | undefined> = {};
const originalFetch = globalThis.fetch;

/** Hermetic stand-in for the NVIDIA gateway: 200 with an empty SSE body. */
function stubFetchOk() {
globalThis.fetch = async () =>
new Response(
new ReadableStream<Uint8Array>({ start(controller) { controller.close(); } }),
{ status: 200, headers: { "content-type": "text/event-stream" } },
);
}

/** Drain a result stream into plain text so its events can be asserted on. */
async function readAll(result: { stream?: ReadableStream<Uint8Array> }) {
assert.ok(result.stream, "NVIDIA adapter must return a stream");
const reader = result.stream.getReader();
const decoder = new TextDecoder();
let text = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
text += decoder.decode(value, { stream: true });
}
return text;
}

const input = {
messages: [{ role: "user" as const, content: "hello" }],
};

beforeEach(() => {
for (const name of [KEY_ENV, ...MODEL_ENVS]) savedEnv[name] = process.env[name];
process.env[KEY_ENV] = VALID_KEY;
for (const name of MODEL_ENVS) delete process.env[name];
stubFetchOk();
});

afterEach(() => {
for (const [name, value] of Object.entries(savedEnv)) {
if (value === undefined) delete process.env[name];
else process.env[name] = value;
}
globalThis.fetch = originalFetch;
});

describe("NVIDIA model env guard", () => {
it("rejects an API key pasted into NVIDIA_KIMI_MODEL before any network call", () => {
process.env.NVIDIA_KIMI_MODEL = "nvapi-leaked-in-the-wrong-variable-123";

assert.throws(
() => callNvidiaKimi(input),
(error: unknown) => {
assert.ok(error instanceof ApiError);
assert.equal(error.status, 500);
assert.equal(error.code, "nvidia_model_misconfigured");
// Actionable: names the broken variable and the fix.
assert.match(error.message, /NVIDIA_KIMI_MODEL/);
assert.match(error.message, /NVIDIA_API_KEY/);
// Never echoes the leaked key material back to anyone.
assert.ok(!error.message.includes("nvapi-leaked"));
return true;
},
);
});

it("rejects an API key pasted into NVIDIA_RESEARCH_MODEL", () => {
process.env.NVIDIA_RESEARCH_MODEL = "nvapi-leaked-in-the-wrong-variable-456";

assert.throws(
() => callNvidiaResearch(input),
(error: unknown) => {
assert.ok(error instanceof ApiError);
assert.equal(error.code, "nvidia_model_misconfigured");
assert.match(error.message, /NVIDIA_RESEARCH_MODEL/);
assert.ok(!error.message.includes("nvapi-leaked"));
return true;
},
);
});

it("rejects the reverse swap: a model ID sitting in NVIDIA_API_KEY", () => {
process.env.NVIDIA_API_KEY = "moonshotai/kimi-k3";

assert.throws(
() => callNvidiaKimi(input),
(error: unknown) => {
assert.ok(error instanceof ApiError);
assert.equal(error.status, 500);
assert.equal(error.code, "nvidia_key_misconfigured");
assert.match(error.message, /NVIDIA_API_KEY/);
// The guidance itself must not contain the swapped-in value verbatim.
assert.ok(!error.message.includes("moonshotai"));
return true;
},
);
});

it("still fails closed when NVIDIA_API_KEY is absent entirely", () => {
delete process.env[KEY_ENV];

assert.throws(
() => callNvidiaResearch(input),
(error: unknown) => {
assert.ok(error instanceof ApiError);
assert.equal(error.code, "nvidia_not_configured");
return true;
},
);
});
});

describe("NVIDIA model resolution still works for valid config", () => {
it("uses the default models when no overrides are set", async () => {
assert.equal((await callNvidiaKimi(input)).model, "moonshotai/kimi-k3");
assert.equal((await callNvidiaResearch(input)).model, "z-ai/glm-5.3-flash");
});

it("accepts a real model ID override", async () => {
process.env.NVIDIA_RESEARCH_MODEL = "z-ai/glm-5.3-flash";
assert.equal((await callNvidiaResearch(input)).model, "z-ai/glm-5.3-flash");
});

it("auto-heals the dashed research model form shipped in older env config", async () => {
// "z-ai/glm-5-3-flash" (dash, not dot) was the old default and 404s at the
// gateway; deployed env vars holding it must keep working.
process.env.NVIDIA_RESEARCH_MODEL = "z-ai/glm-5-3-flash";
assert.equal((await callNvidiaResearch(input)).model, "z-ai/glm-5.3-flash");
});
});

describe("NVIDIA error strings are safe to show end users", () => {
it("streams an actionable message for a gateway 404", async () => {
// What NVIDIA's gateway returns for an unknown model: plain-text 404.
globalThis.fetch = async () => new Response("404 page not found", { status: 404 });

const text = await readAll(await callNvidiaResearch(input));
assert.match(text, /NVIDIA z-ai\/glm-5\.3-flash request failed \(404\): 404 page not found/);
assert.ok(!text.includes(VALID_KEY), "streamed error must never contain the API key");
});

it("redacts key material a provider embeds in its error body", async () => {
globalThis.fetch = async () =>
new Response(
JSON.stringify({ error: { message: "Rejected Bearer nvapi-abc123secret from account" } }),
{ status: 401, headers: { "content-type": "application/json" } },
);

const text = await readAll(await callNvidiaResearch(input));
assert.ok(!text.includes("nvapi-abc123secret"), "provider-echoed key must be redacted");
assert.match(text, /\[redacted\]/);
});
});
Loading