mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-17 23:52:24 +00:00
feat(settings): KI-provider — OpenAI key field, model preset dropdown, gated OAuth
Bucket C of the v1.4.3 polish pass. Three independent bugs in the KI-provider settings, fixed together because they all live on the same panel: 1. **Selecting "OpenAI" left no way to provide a key.** The schema stored Anthropic and Local API keys, but OPENAI was a valid `aiProvider` value with no matching credential column — the resolver silently fell through to the admin-level OpenAI key. So a self-hosted user who picked OpenAI and typed nothing got the admin's key (might not exist), and a user who *wanted* their own OpenAI key had no UI surface to enter it. Migration `0026_user_ai_openai_key` adds `users.ai_openai_key_ encrypted`. The resolver's `OPENAI` branch now picks up the user-level key first and only falls back to admin if the user slot is empty. The settings UI grew an OpenAI-key field gated on `provider === "OPENAI"` mirroring the Anthropic flow. The `/api/ai/test` override schema accepts `openaiKey` so the "Verbindung testen" button can validate an unsaved key without persisting plaintext. 2. **Model field was a freetext Input, easy to typo.** Replaced with a `<select>` populated from `MODEL_PRESETS` per provider: gpt-4o / gpt-4o-mini / gpt-4-turbo / gpt-5 / o3-mini for OPENAI; claude-sonnet-4-6 / claude-opus-4-7 / claude-haiku-4-5 / claude- 3-5-sonnet-latest for ANTHROPIC; llama3.1:8b / llama3.1:70b / mistral / qwen2.5 for LOCAL. An "Eigenes…" sentinel still surfaces the freetext Input so power users can target preview models or fine-tunes. The dropdown disables when no provider is chosen — saves the user from filling a model that won't be used. 3. **"Mit ChatGPT verbinden" silently bounced to chatgpt.com login with no OAuth grant.** The authorize URL was built without a `client_id` parameter, so chatgpt.com couldn't recognise the request as an OAuth handshake — it just rendered the regular login form. The user came back, nothing connected, the button "did nothing". Added `CODEX_OAUTH_CLIENT_ID` env var. The URL builder now throws `CodexOAuthNotConfiguredError` if it's unset; the authorize route maps that to a 503 with an actionable message instead of dispatching the dead URL. The settings card reads `codexOauthConfigured` from `/api/insights/settings` and hides the Connect button when the flag is false, replacing it with a tiny italicised "ChatGPT-OAuth ist auf dieser Instanz nicht konfiguriert — nutze stattdessen einen eigenen API-Key unten." `CHATGPT_OAUTH` was also removed as a manually-selectable provider option in the dropdown — the top connect button is the path; having both confused the affordance. Refresh + token-exchange both forward the client_id now too. Test fixture seeds `process.env.CODEX_OAUTH_CLIENT_ID="test_client_id"` in `beforeEach` so the existing URL-shape assertion still works, plus a new test asserts the unset case throws. Tests + typecheck green (670/670 — one new assertion). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
622099c0fd
commit
c05f48f520
10 files changed
+317
-49
No files matched your search
@@ -1,5 +1,10 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { generatePKCE, generateState, buildAuthorizationUrl } from "../codex-oauth";
|
||||
import { afterEach, beforeEach, describe, it, expect } from "vitest";
|
||||
import {
|
||||
generatePKCE,
|
||||
generateState,
|
||||
buildAuthorizationUrl,
|
||||
CodexOAuthNotConfiguredError,
|
||||
} from "../codex-oauth";
|
||||
|
||||
describe("codex-oauth", () => {
|
||||
describe("generatePKCE", () => {
|
||||
@@ -29,6 +34,26 @@ describe("codex-oauth", () => {
|
||||
});
|
||||
|
||||
describe("buildAuthorizationUrl", () => {
|
||||
const ORIGINAL_CLIENT_ID = process.env.CODEX_OAUTH_CLIENT_ID;
|
||||
|
||||
beforeEach(() => {
|
||||
// v1.4.3: the URL builder requires CODEX_OAUTH_CLIENT_ID. The
|
||||
// v1.4.2 build silently dropped this so the resulting URL just
|
||||
// hit chatgpt.com login with no OAuth grant flow at all — the
|
||||
// "Connect with ChatGPT" button effectively did nothing in
|
||||
// production. Setting an explicit value here keeps the test
|
||||
// hermetic regardless of the runner env.
|
||||
process.env.CODEX_OAUTH_CLIENT_ID = "test_client_id";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (ORIGINAL_CLIENT_ID === undefined) {
|
||||
delete process.env.CODEX_OAUTH_CLIENT_ID;
|
||||
} else {
|
||||
process.env.CODEX_OAUTH_CLIENT_ID = ORIGINAL_CLIENT_ID;
|
||||
}
|
||||
});
|
||||
|
||||
it("builds correct URL with all params", () => {
|
||||
const url = buildAuthorizationUrl({
|
||||
codeChallenge: "test-challenge",
|
||||
@@ -40,10 +65,22 @@ describe("codex-oauth", () => {
|
||||
expect(parsed.origin).toBe("https://chatgpt.com");
|
||||
expect(parsed.pathname).toBe("/authorize");
|
||||
expect(parsed.searchParams.get("response_type")).toBe("code");
|
||||
expect(parsed.searchParams.get("client_id")).toBe("test_client_id");
|
||||
expect(parsed.searchParams.get("code_challenge")).toBe("test-challenge");
|
||||
expect(parsed.searchParams.get("code_challenge_method")).toBe("S256");
|
||||
expect(parsed.searchParams.get("state")).toBe("test-state");
|
||||
expect(parsed.searchParams.get("redirect_uri")).toBe("https://example.com/callback");
|
||||
});
|
||||
|
||||
it("throws CodexOAuthNotConfiguredError when CODEX_OAUTH_CLIENT_ID is unset", () => {
|
||||
delete process.env.CODEX_OAUTH_CLIENT_ID;
|
||||
expect(() =>
|
||||
buildAuthorizationUrl({
|
||||
codeChallenge: "x",
|
||||
state: "y",
|
||||
redirectUri: "https://example.com/cb",
|
||||
}),
|
||||
).toThrow(CodexOAuthNotConfiguredError);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,33 @@ export function generateState(): string {
|
||||
return base64url(randomBytes(32));
|
||||
}
|
||||
|
||||
/**
|
||||
* Throws when the operator has not configured `CODEX_OAUTH_CLIENT_ID` —
|
||||
* the v1.4.2 build silently dropped the param and rendered a generic
|
||||
* chatgpt.com login that never returned a code, so the "Connect with
|
||||
* ChatGPT" button effectively did nothing. Failing here lets the route
|
||||
* surface a 503 with an actionable message instead of redirecting to
|
||||
* a dead-end page.
|
||||
*/
|
||||
export class CodexOAuthNotConfiguredError extends Error {
|
||||
constructor() {
|
||||
super(
|
||||
"Codex OAuth is not configured on this instance — set CODEX_OAUTH_CLIENT_ID",
|
||||
);
|
||||
this.name = "CodexOAuthNotConfiguredError";
|
||||
}
|
||||
}
|
||||
|
||||
export function getCodexClientId(): string {
|
||||
const id = process.env.CODEX_OAUTH_CLIENT_ID?.trim();
|
||||
if (!id) throw new CodexOAuthNotConfiguredError();
|
||||
return id;
|
||||
}
|
||||
|
||||
export function isCodexOAuthConfigured(): boolean {
|
||||
return Boolean(process.env.CODEX_OAUTH_CLIENT_ID?.trim());
|
||||
}
|
||||
|
||||
export function buildAuthorizationUrl(params: {
|
||||
codeChallenge: string;
|
||||
state: string;
|
||||
@@ -22,6 +49,7 @@ export function buildAuthorizationUrl(params: {
|
||||
}): string {
|
||||
const url = new URL("https://chatgpt.com/authorize");
|
||||
url.searchParams.set("response_type", "code");
|
||||
url.searchParams.set("client_id", getCodexClientId());
|
||||
url.searchParams.set("code_challenge", params.codeChallenge);
|
||||
url.searchParams.set("code_challenge_method", "S256");
|
||||
url.searchParams.set("state", params.state);
|
||||
@@ -46,6 +74,7 @@ export async function exchangeCodeForTokens(params: {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
grant_type: "authorization_code",
|
||||
client_id: getCodexClientId(),
|
||||
code: params.code,
|
||||
code_verifier: params.codeVerifier,
|
||||
redirect_uri: params.redirectUri,
|
||||
@@ -65,6 +94,7 @@ export async function refreshAccessToken(refreshToken: string): Promise<TokenRes
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
grant_type: "refresh_token",
|
||||
client_id: getCodexClientId(),
|
||||
refresh_token: refreshToken,
|
||||
}),
|
||||
});
|
||||
|
||||
+34
-11
@@ -32,11 +32,7 @@ type UserAIRow = {
|
||||
aiBaseUrl: string | null;
|
||||
aiAnthropicKeyEncrypted: string | null;
|
||||
aiLocalKeyEncrypted: string | null;
|
||||
// legacy admin-key fallback (OpenAI uses adminAiKeyEncrypted via app_settings)
|
||||
// We store user-level OpenAI key in aiAnthropicKeyEncrypted? No — for OPENAI
|
||||
// selection at user-level we read app-settings admin key. The user override
|
||||
// for OpenAI is intentionally minimal: provider+model+baseUrl. Personal keys
|
||||
// are scoped to Anthropic/Local for now (matches the migration columns).
|
||||
aiOpenaiKeyEncrypted: string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -66,11 +62,19 @@ function buildUserProvider(row: UserAIRow): AIProvider | null {
|
||||
baseUrl: row.aiBaseUrl,
|
||||
});
|
||||
}
|
||||
case "OPENAI":
|
||||
// User selected OPENAI but personal keys live in admin app_settings;
|
||||
// signal "use admin OpenAI" by returning null and letting caller fall
|
||||
// through to resolveAdminProvider().
|
||||
return null;
|
||||
case "OPENAI": {
|
||||
// v1.4.3: user-level OpenAI key gets first crack — only fall back
|
||||
// to the admin key if the user hasn't supplied their own. The
|
||||
// model-default mirrors the admin path for consistency so a saved
|
||||
// user "OPENAI" without an explicit model still produces an
|
||||
// OpenAIClient with `gpt-4o-mini`.
|
||||
if (!row.aiOpenaiKeyEncrypted) return null;
|
||||
return new OpenAIClient({
|
||||
apiKey: decrypt(row.aiOpenaiKeyEncrypted),
|
||||
model: row.aiModel ?? "gpt-4o-mini",
|
||||
baseUrl: row.aiBaseUrl ?? "https://api.openai.com/v1",
|
||||
});
|
||||
}
|
||||
case "CHATGPT_OAUTH":
|
||||
// Caller handles Codex OAuth via the dedicated branch; signal here.
|
||||
return null;
|
||||
@@ -209,6 +213,7 @@ export async function resolveProvider(userId: string): Promise<AIProvider> {
|
||||
aiBaseUrl: true,
|
||||
aiAnthropicKeyEncrypted: true,
|
||||
aiLocalKeyEncrypted: true,
|
||||
aiOpenaiKeyEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -241,6 +246,7 @@ export type AITestOverride = {
|
||||
baseUrl?: string | null;
|
||||
anthropicKey?: string | null;
|
||||
localKey?: string | null;
|
||||
openaiKey?: string | null;
|
||||
};
|
||||
|
||||
export class AITestConfigError extends Error {
|
||||
@@ -270,6 +276,7 @@ export async function resolveProviderForTest(
|
||||
aiBaseUrl: true,
|
||||
aiAnthropicKeyEncrypted: true,
|
||||
aiLocalKeyEncrypted: true,
|
||||
aiOpenaiKeyEncrypted: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -333,11 +340,27 @@ export async function resolveProviderForTest(
|
||||
throw new AITestConfigError(422, "ChatGPT OAuth is not connected");
|
||||
}
|
||||
case "OPENAI": {
|
||||
// Test path mirrors the persistent resolution: user key first,
|
||||
// admin fallback if absent. We accept an `openaiKey` override
|
||||
// from the test endpoint so a user can verify a not-yet-saved
|
||||
// key dropdown change without persisting anything.
|
||||
const userKey =
|
||||
override.openaiKey?.trim() ||
|
||||
(stored?.aiOpenaiKeyEncrypted
|
||||
? decrypt(stored.aiOpenaiKeyEncrypted)
|
||||
: "");
|
||||
if (userKey) {
|
||||
return new OpenAIClient({
|
||||
apiKey: userKey,
|
||||
model: model || "gpt-4o-mini",
|
||||
baseUrl: baseUrl || "https://api.openai.com/v1",
|
||||
});
|
||||
}
|
||||
const admin = await resolveAdminProvider();
|
||||
if (admin.type === "none") {
|
||||
throw new AITestConfigError(
|
||||
422,
|
||||
"Admin OpenAI key is not configured for this instance",
|
||||
"OpenAI key not configured (neither user nor admin)",
|
||||
);
|
||||
}
|
||||
return admin;
|
||||
|
||||
Reference in new issue
Block a user