From b64386992ab21d8d2fe9551ddc9275ebade3218a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sun, 24 May 2026 01:01:34 +0200 Subject: [PATCH] feat(den): add OpenAI OAuth provider flow Add Den API OpenAI OAuth device-flow routes/tests and Den Web provider UI for OAuth-backed provider credentials on top of the credential handling stack. --- .../den-api/src/routes/org/llm-providers.ts | 359 ++++++++++++++---- .../den-api/test/llm-providers-oauth.test.ts | 198 ++++++++++ .../_components/llm-provider-data.tsx | 8 + .../llm-provider-detail-screen.tsx | 8 +- .../llm-provider-editor-screen.tsx | 224 ++++++++++- .../_components/llm-providers-screen.tsx | 4 +- 6 files changed, 704 insertions(+), 97 deletions(-) create mode 100644 ee/apps/den-api/test/llm-providers-oauth.test.ts diff --git a/ee/apps/den-api/src/routes/org/llm-providers.ts b/ee/apps/den-api/src/routes/org/llm-providers.ts index e3c4438cca..5dd50e7d33 100644 --- a/ee/apps/den-api/src/routes/org/llm-providers.ts +++ b/ee/apps/den-api/src/routes/org/llm-providers.ts @@ -1,7 +1,6 @@ -import { and, desc, eq, inArray, isNotNull, isNull, or } from "@openwork-ee/den-db/drizzle" +import { and, desc, eq, inArray, isNotNull, or } from "@openwork-ee/den-db/drizzle" import { AuthUserTable, - InvitationTable, LlmProviderAccessTable, LlmProviderModelTable, LlmProviderTable, @@ -33,6 +32,10 @@ type LlmProviderAccessId = typeof LlmProviderAccessTable.$inferSelect.id type MemberId = typeof MemberTable.$inferSelect.id type TeamId = typeof TeamTable.$inferSelect.id type LlmProviderRow = typeof LlmProviderTable.$inferSelect +const OPENAI_AUTH_ISSUER = "https://auth.openai.com" +const OPENAI_CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann" +const OPENAI_DEVICE_REDIRECT_URI = `${OPENAI_AUTH_ISSUER}/deviceauth/callback` +const OPENAI_DEVICE_POLLING_SAFETY_MARGIN_MS = 3000 type RouteFailure = { status: number @@ -40,11 +43,6 @@ type RouteFailure = { message?: string } -function getInvitedMemberName(email: string) { - const [localPart, domain = "invited"] = email.split("@") - return `${localPart} ${domain.split(".")[0] ?? "invited"}`.trim() -} - const providerCatalogParamsSchema = z.object({ providerId: z.string().trim().min(1).max(255), }) @@ -108,12 +106,14 @@ const llmProviderWriteSchema = z.object({ }) } - if (value.credentialKind === "opencode_oauth" && value.source === "models_dev" && value.providerId?.trim().toLowerCase() !== "openai") { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ["credentialKind"], - message: "OpenCode OAuth credentials can only be used with the OpenAI catalog provider.", - }) + if (value.credentialKind === "opencode_oauth") { + if (value.source === "models_dev" && !isOpencodeOauthProviderAllowed(value.providerId)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ["credentialKind"], + message: "OpenCode OAuth credentials can only be used with the OpenAI catalog provider.", + }) + } } }) @@ -143,6 +143,24 @@ const conflictSchema = z.object({ message: z.string().optional(), }).meta({ ref: "ConflictError" }) +const openAiOauthStartResponseSchema = z.object({ + verificationUrl: z.string(), + userCode: z.string(), + deviceAuthId: z.string(), + intervalMs: z.number(), +}).meta({ ref: "OpenAiOauthStartResponse" }) + +const openAiOauthCompleteSchema = z.object({ + deviceAuthId: z.string().trim().min(1), + userCode: z.string().trim().min(1), +}) + +const openAiOauthCompleteResponseSchema = z.object({ + opencodeAuth: z.string(), + accountId: z.string().nullable(), + expires: z.number(), +}).meta({ ref: "OpenAiOauthCompleteResponse" }) + function createFailure(status: number, error: string, message?: string): RouteFailure { return { status, error, message } } @@ -151,55 +169,130 @@ function isRouteFailure(value: unknown): value is RouteFailure { return typeof value === "object" && value !== null && "status" in value && "error" in value } -function isOrganizationAdmin(payload: { currentMember: { isOwner: boolean; role: string } }) { - return payload.currentMember.isOwner || memberHasRole(payload.currentMember.role, "admin") +function parseJwtClaims(token: string): Record | null { + const parts = token.split(".") + if (parts.length !== 3 || !parts[1]) return null + try { + return JSON.parse(Buffer.from(parts[1], "base64url").toString()) as Record + } catch { + return null + } } -export function getCredentialFlags(provider: Pick) { - const hasApiKey = Boolean(provider.apiKey && provider.apiKey.trim().length > 0) - const hasOpencodeAuth = Boolean(provider.opencodeAuth && provider.opencodeAuth.trim().length > 0) - return { - hasApiKey, - hasOpencodeAuth, - hasCredential: provider.credentialKind === "opencode_oauth" ? hasOpencodeAuth : hasApiKey, +function extractOpenAiAccountId(tokens: { id_token?: string; access_token?: string }) { + const claims = tokens.id_token ? parseJwtClaims(tokens.id_token) : tokens.access_token ? parseJwtClaims(tokens.access_token) : null + if (!claims) return null + const apiAuth = claims["https://api.openai.com/auth"] + if (typeof claims.chatgpt_account_id === "string") return claims.chatgpt_account_id + if (apiAuth && typeof apiAuth === "object" && !Array.isArray(apiAuth) && typeof (apiAuth as Record).chatgpt_account_id === "string") { + return (apiAuth as Record).chatgpt_account_id + } + const organizations = claims.organizations + if (Array.isArray(organizations)) { + const first = organizations.find((entry): entry is Record => typeof entry === "object" && entry !== null && !Array.isArray(entry)) + if (typeof first?.id === "string") return first.id } + return null } -export function redactLlmProviderCredentials(provider: T): Omit & { apiKey: undefined; opencodeAuth: undefined } { +export async function startOpenAiDeviceAuth() { + const response = await fetch(`${OPENAI_AUTH_ISSUER}/api/accounts/deviceauth/usercode`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "User-Agent": "opencode/den", + }, + body: JSON.stringify({ client_id: OPENAI_CODEX_CLIENT_ID }), + }) + if (!response.ok) { + throw createFailure(502, "openai_oauth_start_failed", `OpenAI device authorization failed with ${response.status}.`) + } + const data = await response.json() as { device_auth_id?: unknown; user_code?: unknown; interval?: unknown } + if (typeof data.device_auth_id !== "string" || typeof data.user_code !== "string") { + throw createFailure(502, "openai_oauth_start_failed", "OpenAI device authorization response was incomplete.") + } + const interval = Math.max(Number.parseInt(String(data.interval ?? "5"), 10) || 5, 1) * 1000 return { - ...provider, - apiKey: undefined, - opencodeAuth: undefined, + verificationUrl: `${OPENAI_AUTH_ISSUER}/codex/device`, + userCode: data.user_code, + deviceAuthId: data.device_auth_id, + intervalMs: interval + OPENAI_DEVICE_POLLING_SAFETY_MARGIN_MS, } } -export function canImportLlmProviderCredential(payload: { currentMember: { isOwner: boolean; role: string } }) { - return isOrganizationAdmin(payload) -} +export async function completeOpenAiDeviceAuth(input: { deviceAuthId: string; userCode: string }) { + const deviceResponse = await fetch(`${OPENAI_AUTH_ISSUER}/api/accounts/deviceauth/token`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "User-Agent": "opencode/den", + }, + body: JSON.stringify({ + device_auth_id: input.deviceAuthId, + user_code: input.userCode, + }), + }) -function normalizeOpencodeAuth(value: string | undefined) { - const trimmed = value?.trim() ?? "" - if (!trimmed) return null - try { - const parsed = JSON.parse(trimmed) as unknown - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || (parsed as Record).type !== "oauth") { - throw new Error("invalid auth") - } - return JSON.stringify(parsed) - } catch { - throw createFailure(400, "invalid_opencode_auth", "OpenCode OAuth credential must be valid OAuth auth JSON.") + if (deviceResponse.status === 403 || deviceResponse.status === 404) { + throw createFailure(409, "openai_oauth_pending", "OpenAI authorization is not complete yet.") + } + if (!deviceResponse.ok) { + throw createFailure(502, "openai_oauth_complete_failed", `OpenAI device authorization failed with ${deviceResponse.status}.`) + } + const deviceData = await deviceResponse.json() as { authorization_code?: unknown; code_verifier?: unknown } + if (typeof deviceData.authorization_code !== "string" || typeof deviceData.code_verifier !== "string") { + throw createFailure(502, "openai_oauth_complete_failed", "OpenAI device token response was incomplete.") } -} -function buildLlmProviderCredentialPayload(provider: LlmProviderRow) { + const tokenResponse = await fetch(`${OPENAI_AUTH_ISSUER}/oauth/token`, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: deviceData.authorization_code, + redirect_uri: OPENAI_DEVICE_REDIRECT_URI, + client_id: OPENAI_CODEX_CLIENT_ID, + code_verifier: deviceData.code_verifier, + }).toString(), + }) + if (!tokenResponse.ok) { + throw createFailure(502, "openai_oauth_complete_failed", `OpenAI token exchange failed with ${tokenResponse.status}.`) + } + const tokens = await tokenResponse.json() as { id_token?: string; access_token?: string; refresh_token?: string; expires_in?: number } + if (!tokens.access_token || !tokens.refresh_token) { + throw createFailure(502, "openai_oauth_complete_failed", "OpenAI token response did not include OAuth tokens.") + } + const expires = Date.now() + (tokens.expires_in ?? 3600) * 1000 + const accountId = extractOpenAiAccountId(tokens) return { - ...redactLlmProviderCredentials(provider), - ...getCredentialFlags(provider), - apiKey: provider.credentialKind === "api_key" ? provider.apiKey : undefined, - opencodeAuth: provider.credentialKind === "opencode_oauth" ? provider.opencodeAuth : undefined, + opencodeAuth: JSON.stringify({ + type: "oauth", + refresh: tokens.refresh_token, + access: tokens.access_token, + expires, + ...(accountId ? { accountId } : {}), + }), + accountId, + expires, } } +function isOrganizationAdmin(payload: { currentMember: { isOwner: boolean; role: string } }) { + return payload.currentMember.isOwner || memberHasRole(payload.currentMember.role, "admin") +} + +export function isOpencodeOauthProviderAllowed(providerId: string | undefined | null) { + return providerId?.trim().toLowerCase() === "openai" +} + +export function canUseOpenAiOAuthCredentialFlow(payload: { currentMember: { isOwner: boolean; role: string } }) { + return isOrganizationAdmin(payload) +} + +export function canImportLlmProviderCredential(payload: { currentMember: { isOwner: boolean; role: string } }) { + return isOrganizationAdmin(payload) +} + function canManageLlmProvider( payload: { currentMember: { id: MemberId; isOwner: boolean; role: string } }, provider: LlmProviderRow, @@ -230,6 +323,66 @@ function parseLlmProviderAccessId(value: string) { return normalizeDenTypeId("llmProviderAccess", value) } +export function getCredentialFlags(provider: Pick) { + const hasApiKey = Boolean(provider.apiKey && provider.apiKey.trim().length > 0) + const hasOpencodeAuth = Boolean(provider.opencodeAuth && provider.opencodeAuth.trim().length > 0) + return { + hasApiKey, + hasOpencodeAuth, + hasCredential: provider.credentialKind === "opencode_oauth" ? hasOpencodeAuth : hasApiKey, + } +} + +export function redactLlmProviderCredentials(provider: T): Omit & { apiKey: undefined; opencodeAuth: undefined } { + return { + ...provider, + apiKey: undefined, + opencodeAuth: undefined, + } +} + +function buildLlmProviderCredentialPayload(provider: LlmProviderRow) { + return { + ...redactLlmProviderCredentials(provider), + ...getCredentialFlags(provider), + apiKey: provider.credentialKind === "api_key" ? provider.apiKey : undefined, + opencodeAuth: provider.credentialKind === "opencode_oauth" ? provider.opencodeAuth : undefined, + } +} + +function normalizeOpencodeAuth(value: string | undefined) { + const trimmed = value?.trim() + if (!trimmed) return null + + try { + const parsed = JSON.parse(trimmed) as unknown + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + throw new Error("OpenCode OAuth auth must be a JSON object.") + } + const auth = parsed as Record + if (auth.type !== "oauth") { + throw new Error('OpenCode OAuth auth must include "type": "oauth".') + } + if (typeof auth.access !== "string" || !auth.access.trim()) { + throw new Error("OpenCode OAuth auth must include an access token.") + } + if (typeof auth.refresh !== "string" || !auth.refresh.trim()) { + throw new Error("OpenCode OAuth auth must include a refresh token.") + } + if (typeof auth.expires !== "number" || !Number.isFinite(auth.expires) || auth.expires < 0) { + throw new Error("OpenCode OAuth auth must include a non-negative numeric expires value.") + } + } catch (error) { + throw createFailure( + 400, + "invalid_opencode_auth", + error instanceof Error ? error.message : "OpenCode OAuth auth must be valid JSON.", + ) + } + + return trimmed +} + function parseMemberId(value: string) { return normalizeDenTypeId("member", value) } @@ -290,7 +443,7 @@ async function resolveMemberIds(input: { const rows = await db .select({ id: MemberTable.id }) .from(MemberTable) - .where(and(eq(MemberTable.organizationId, input.organizationId), inArray(MemberTable.id, memberIds), isNull(MemberTable.removedAt))) + .where(and(eq(MemberTable.organizationId, input.organizationId), inArray(MemberTable.id, memberIds))) if (rows.length !== memberIds.length) { throw createFailure(404, "member_not_found") @@ -382,6 +535,9 @@ async function normalizeLlmProviderInput(input: z.infer left.name.localeCompare(right.name)), access: { - members: (memberAccessByProviderId.get(provider.id) ?? []).map((row) => { - const email = row.user?.email ?? row.invitation?.email ?? "invited@example.com" - return { - id: row.access.id, - orgMembershipId: row.member.id, - role: row.member.role, - user: { - id: row.user?.id ?? row.member.id, - name: row.user?.name ?? getInvitedMemberName(email), - email, - image: row.user?.image ?? null, - }, - createdAt: row.access.createdAt, - } - }), + members: (memberAccessByProviderId.get(provider.id) ?? []).map((row) => ({ + id: row.access.id, + orgMembershipId: row.member.id, + role: row.member.role, + user: row.user, + createdAt: row.access.createdAt, + })), teams: (teamAccessByProviderId.get(provider.id) ?? []).map((row) => ({ id: row.access.id, teamId: row.team.id, @@ -563,6 +707,69 @@ async function loadLlmProviders(input: { } export function registerOrgLlmProviderRoutes }>(app: Hono) { + app.post( + "/v1/llm-providers/openai-oauth/start", + describeRoute({ + tags: ["LLM Providers"], + summary: "Start OpenAI OAuth device flow", + description: "Starts the same OpenAI/ChatGPT device auth flow used by OpenCode and returns the user code.", + responses: { + 200: jsonResponse("OpenAI OAuth device flow started successfully.", openAiOauthStartResponseSchema), + 401: jsonResponse("The caller must be signed in to connect OpenAI.", unauthorizedSchema), + 403: jsonResponse("Only organization admins can connect OpenAI OAuth credentials.", forbiddenSchema), + 502: jsonResponse("OpenAI OAuth could not be started.", conflictSchema), + }, + }), + requireUserMiddleware, + resolveOrganizationContextMiddleware, + async (c) => { + const payload = c.get("organizationContext") + if (!canUseOpenAiOAuthCredentialFlow(payload)) { + return c.json({ error: "forbidden", message: "Only organization admins can connect OpenAI OAuth credentials." }, 403) + } + + try { + return c.json(await startOpenAiDeviceAuth()) + } catch (error) { + if (isRouteFailure(error)) return c.json({ error: error.error, message: error.message }, { status: error.status as 409 | 502 }) + throw error + } + }, + ) + + app.post( + "/v1/llm-providers/openai-oauth/complete", + describeRoute({ + tags: ["LLM Providers"], + summary: "Complete OpenAI OAuth device flow", + description: "Completes OpenAI device auth and returns an OpenCode-native OAuth auth object serialized as JSON.", + responses: { + 200: jsonResponse("OpenAI OAuth completed successfully.", openAiOauthCompleteResponseSchema), + 401: jsonResponse("The caller must be signed in to complete OpenAI auth.", unauthorizedSchema), + 403: jsonResponse("Only organization admins can connect OpenAI OAuth credentials.", forbiddenSchema), + 409: jsonResponse("OpenAI authorization is still pending.", conflictSchema), + 502: jsonResponse("OpenAI OAuth could not be completed.", conflictSchema), + }, + }), + requireUserMiddleware, + resolveOrganizationContextMiddleware, + jsonValidator(openAiOauthCompleteSchema), + async (c) => { + const payload = c.get("organizationContext") + if (!canUseOpenAiOAuthCredentialFlow(payload)) { + return c.json({ error: "forbidden", message: "Only organization admins can connect OpenAI OAuth credentials." }, 403) + } + + const input = c.req.valid("json") + try { + return c.json(await completeOpenAiDeviceAuth(input)) + } catch (error) { + if (isRouteFailure(error)) return c.json({ error: error.error, message: error.message }, { status: error.status as 409 | 502 }) + throw error + } + }, + ) + app.get( "/v1/llm-provider-catalog", describeRoute({ @@ -737,8 +944,7 @@ export function registerOrgLlmProviderRoutes ({ @@ -757,11 +963,11 @@ export function registerOrgLlmProviderRoutes { + seedRequiredEnv() + llmProviderModule = await import("../src/routes/org/llm-providers.js") +}) + +function createRouteApp() { + const app = new Hono() + llmProviderModule.registerOrgLlmProviderRoutes(app) + return app +} + +function jwtWithClaims(claims: Record) { + return [ + Buffer.from(JSON.stringify({ alg: "none" })).toString("base64url"), + Buffer.from(JSON.stringify(claims)).toString("base64url"), + "signature", + ].join(".") +} + +test("generic provider payload redaction removes API key and OAuth auth material", () => { + const redacted = llmProviderModule.redactLlmProviderCredentials({ + id: "llmProvider_secret_123", + apiKey: "sk-secret", + opencodeAuth: JSON.stringify({ type: "oauth", access: "access", refresh: "refresh", expires: 1 }), + }) + + expect(redacted).toEqual({ + id: "llmProvider_secret_123", + apiKey: undefined, + opencodeAuth: undefined, + }) +}) + +test("credential flags expose presence only, never credential values", () => { + expect(llmProviderModule.getCredentialFlags({ + credentialKind: "opencode_oauth", + apiKey: "sk-secret", + opencodeAuth: JSON.stringify({ type: "oauth", access: "access", refresh: "refresh", expires: 1 }), + })).toEqual({ hasApiKey: true, hasOpencodeAuth: true, hasCredential: true }) +}) + +test("OpenCode OAuth credential type rejects non-OpenAI providers", () => { + expect(llmProviderModule.isOpencodeOauthProviderAllowed("openai")).toBe(true) + expect(llmProviderModule.isOpencodeOauthProviderAllowed(" OpenAI ")).toBe(true) + expect(llmProviderModule.isOpencodeOauthProviderAllowed("anthropic")).toBe(false) + expect(llmProviderModule.isOpencodeOauthProviderAllowed(undefined)).toBe(false) +}) + +test("OAuth credential and import permission gates require organization admin role", () => { + const owner = { currentMember: { isOwner: true, role: "member" } } + const admin = { currentMember: { isOwner: false, role: "admin" } } + const creatorOnly = { currentMember: { isOwner: false, role: "member" } } + + expect(llmProviderModule.canUseOpenAiOAuthCredentialFlow(owner)).toBe(true) + expect(llmProviderModule.canUseOpenAiOAuthCredentialFlow(admin)).toBe(true) + expect(llmProviderModule.canUseOpenAiOAuthCredentialFlow(creatorOnly)).toBe(false) + expect(llmProviderModule.canImportLlmProviderCredential(owner)).toBe(true) + expect(llmProviderModule.canImportLlmProviderCredential(admin)).toBe(true) + expect(llmProviderModule.canImportLlmProviderCredential(creatorOnly)).toBe(false) +}) + +test("OpenAI OAuth routes require an authenticated caller before returning credential material", async () => { + const app = createRouteApp() + + const startResponse = await app.request("http://den.local/v1/llm-providers/openai-oauth/start", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({}), + }) + expect(startResponse.status).toBe(401) + await expect(startResponse.json()).resolves.toEqual({ error: "unauthorized" }) + + const completeResponse = await app.request("http://den.local/v1/llm-providers/openai-oauth/complete", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ deviceAuthId: "dev", userCode: "code" }), + }) + expect(completeResponse.status).toBe(401) + await expect(completeResponse.json()).resolves.toEqual({ error: "unauthorized" }) +}) + +test("purpose-specific import endpoint requires authentication", async () => { + const app = createRouteApp() + const response = await app.request("http://den.local/v1/llm-providers/llmProvider_secret_123/import-credential", { + method: "GET", + }) + + expect(response.status).toBe(401) + await expect(response.json()).resolves.toEqual({ error: "unauthorized" }) +}) + +test("OpenAI OAuth completion reports pending authorization without tokens", async () => { + const originalFetch = globalThis.fetch + globalThis.fetch = (async () => new Response(JSON.stringify({}), { status: 403 })) as typeof fetch + try { + await expect(llmProviderModule.completeOpenAiDeviceAuth({ + deviceAuthId: "device-pending", + userCode: "CODE", + })).rejects.toMatchObject({ error: "openai_oauth_pending", status: 409 }) + } finally { + globalThis.fetch = originalFetch + } +}) + +test("OpenAI OAuth start reports upstream failure without credential material", async () => { + const originalFetch = globalThis.fetch + globalThis.fetch = (async () => new Response(JSON.stringify({ error: "upstream" }), { status: 500 })) as typeof fetch + try { + await expect(llmProviderModule.startOpenAiDeviceAuth()).rejects.toMatchObject({ + error: "openai_oauth_start_failed", + status: 502, + }) + } finally { + globalThis.fetch = originalFetch + } +}) + +test("OpenAI OAuth completion reports token exchange failure without credential material", async () => { + const originalFetch = globalThis.fetch + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith("/api/accounts/deviceauth/token")) { + return Response.json({ authorization_code: "authorization-code", code_verifier: "verifier" }) + } + if (url.endsWith("/oauth/token")) { + return new Response(JSON.stringify({ error: "exchange_failed" }), { status: 500 }) + } + return new Response("not found", { status: 404 }) + }) as typeof fetch + + try { + await expect(llmProviderModule.completeOpenAiDeviceAuth({ + deviceAuthId: "device-failure", + userCode: "CODE", + })).rejects.toMatchObject({ error: "openai_oauth_complete_failed", status: 502 }) + } finally { + globalThis.fetch = originalFetch + } +}) + +test("OpenAI OAuth completion returns importable OpenCode OAuth auth on success", async () => { + const originalFetch = globalThis.fetch + const calls: string[] = [] + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = String(input) + calls.push(url) + if (url.endsWith("/api/accounts/deviceauth/token")) { + return Response.json({ authorization_code: "authorization-code", code_verifier: "verifier" }) + } + if (url.endsWith("/oauth/token")) { + return Response.json({ + access_token: jwtWithClaims({ chatgpt_account_id: "acct_123" }), + refresh_token: "refresh-token", + expires_in: 60, + }) + } + return new Response("not found", { status: 404 }) + }) as typeof fetch + + try { + const completed = await llmProviderModule.completeOpenAiDeviceAuth({ + deviceAuthId: "device-complete", + userCode: "CODE", + }) + const auth = JSON.parse(completed.opencodeAuth) as Record + + expect(calls).toHaveLength(2) + expect(auth.type).toBe("oauth") + expect(typeof auth.access).toBe("string") + expect(auth.refresh).toBe("refresh-token") + expect(auth.accountId).toBe("acct_123") + expect(completed.accountId).toBe("acct_123") + expect(typeof auth.expires).toBe("number") + } finally { + globalThis.fetch = originalFetch + } +}) + +test("LLM provider migration journal remains valid JSON", async () => { + const journal = await readFile(new URL("../../../packages/den-db/drizzle/meta/_journal.json", import.meta.url), "utf8") + const parsed = JSON.parse(journal) as { entries?: Array<{ tag?: string }> } + + expect(parsed.entries?.some((entry) => entry.tag === "0019_llm_provider_opencode_oauth")).toBe(true) +}) diff --git a/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-data.tsx b/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-data.tsx index 751b911462..53c89d7e0e 100644 --- a/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-data.tsx +++ b/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-data.tsx @@ -4,6 +4,7 @@ import { useEffect, useState } from "react"; import { getErrorMessage, requestJson } from "../../_lib/den-flow"; export type DenLlmProviderSource = "models_dev" | "custom" | "openwork"; +export type DenLlmProviderCredentialKind = "api_key" | "opencode_oauth"; export type DenLlmProviderModel = { id: string; @@ -41,7 +42,10 @@ export type DenLlmProvider = { providerId: string; name: string; providerConfig: Record; + credentialKind: DenLlmProviderCredentialKind; hasApiKey: boolean; + hasOpencodeAuth: boolean; + hasCredential: boolean; createdAt: string | null; updatedAt: string | null; canManage: boolean; @@ -178,6 +182,7 @@ function asLlmProvider(value: unknown): DenLlmProvider | null { value.source === "models_dev" || value.source === "custom" || value.source === "openwork" ? value.source : null; + const credentialKind = value.credentialKind === "opencode_oauth" ? "opencode_oauth" : "api_key"; if (!id || !organizationId || !createdByOrgMembershipId || !providerId || !name || !source) { return null; } @@ -190,7 +195,10 @@ function asLlmProvider(value: unknown): DenLlmProvider | null { providerId, name, providerConfig: asJsonRecord(value.providerConfig), + credentialKind, hasApiKey: value.hasApiKey === true, + hasOpencodeAuth: value.hasOpencodeAuth === true, + hasCredential: value.hasCredential === true || value.hasApiKey === true || value.hasOpencodeAuth === true, createdAt: asIsoString(value.createdAt), updatedAt: asIsoString(value.updatedAt), canManage: value.canManage === true, diff --git a/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-detail-screen.tsx b/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-detail-screen.tsx index c208bfdaa9..4b50aac65c 100644 --- a/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-detail-screen.tsx +++ b/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-detail-screen.tsx @@ -185,10 +185,10 @@ export function LlmProviderDetailScreen({
- {provider.hasApiKey + {provider.hasCredential ? "Credential saved" : "Credential missing"}
@@ -221,10 +221,10 @@ export function LlmProviderDetailScreen({

- Updated + Credential

- {formatProviderTimestamp(provider.updatedAt)} + {provider.credentialKind === "opencode_oauth" ? "OpenCode OAuth" : "API key"}

diff --git a/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-editor-screen.tsx b/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-editor-screen.tsx index fec4fc356b..d07a559201 100644 --- a/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-editor-screen.tsx +++ b/ee/apps/den-web/app/(den)/dashboard/_components/llm-provider-editor-screen.tsx @@ -34,6 +34,7 @@ import { requestLlmProviderCatalogDetail, useOrgLlmProviders, type DenLlmProvider, + type DenLlmProviderCredentialKind, type DenModelsDevProviderDetail, type DenModelsDevProviderSummary, } from "./llm-provider-data"; @@ -88,7 +89,18 @@ export function LlmProviderEditorScreen({ const [customConfigText, setCustomConfigText] = useState( buildCustomProviderTemplate(), ); + const [credentialKind, setCredentialKind] = + useState("api_key"); const [apiKey, setApiKey] = useState(""); + const [opencodeAuth, setOpencodeAuth] = useState(""); + const [openAiOauthBusy, setOpenAiOauthBusy] = useState(false); + const [openAiOauthError, setOpenAiOauthError] = useState(null); + const [openAiOauthSession, setOpenAiOauthSession] = useState<{ + verificationUrl: string; + userCode: string; + deviceAuthId: string; + intervalMs: number; + } | null>(null); const [selectedMemberIds, setSelectedMemberIds] = useState([]); const [selectedTeamIds, setSelectedTeamIds] = useState([]); const [saveBusy, setSaveBusy] = useState(false); @@ -146,7 +158,11 @@ export function LlmProviderEditorScreen({ ? buildEditableCustomProviderText(provider) : buildCustomProviderTemplate(), ); + setCredentialKind(provider.credentialKind); setApiKey(""); + setOpencodeAuth(""); + setOpenAiOauthError(null); + setOpenAiOauthSession(null); return; } @@ -159,9 +175,90 @@ export function LlmProviderEditorScreen({ ); setSelectedTeamIds([]); setCustomConfigText(buildCustomProviderTemplate()); + setCredentialKind("api_key"); setApiKey(""); + setOpencodeAuth(""); + setOpenAiOauthError(null); + setOpenAiOauthSession(null); }, [orgContext?.currentMember.id, provider]); + useEffect(() => { + setOpenAiOauthError(null); + setOpenAiOauthSession(null); + }, [credentialKind, selectedProviderId, source]); + + async function startOpenAiOauth() { + setOpenAiOauthBusy(true); + setOpenAiOauthError(null); + try { + const { response, payload } = await requestJson( + "/v1/llm-providers/openai-oauth/start", + { method: "POST", body: JSON.stringify({}) }, + 20000, + ); + if (!response.ok) { + throw new Error(getErrorMessage(payload, `Failed to start OpenAI OAuth (${response.status}).`)); + } + if (!payload || typeof payload !== "object") { + throw new Error("OpenAI OAuth response was empty."); + } + const data = payload as Record; + if ( + typeof data.verificationUrl !== "string" || + typeof data.userCode !== "string" || + typeof data.deviceAuthId !== "string" || + typeof data.intervalMs !== "number" + ) { + throw new Error("OpenAI OAuth response was incomplete."); + } + setOpenAiOauthSession({ + verificationUrl: data.verificationUrl, + userCode: data.userCode, + deviceAuthId: data.deviceAuthId, + intervalMs: data.intervalMs, + }); + window.open(data.verificationUrl, "_blank", "noopener,noreferrer"); + } catch (error) { + setOpenAiOauthError(error instanceof Error ? error.message : "Could not start OpenAI OAuth."); + } finally { + setOpenAiOauthBusy(false); + } + } + + async function completeOpenAiOauth() { + if (!openAiOauthSession) { + setOpenAiOauthError("Start OpenAI OAuth first."); + return; + } + setOpenAiOauthBusy(true); + setOpenAiOauthError(null); + try { + const { response, payload } = await requestJson( + "/v1/llm-providers/openai-oauth/complete", + { + method: "POST", + body: JSON.stringify({ + deviceAuthId: openAiOauthSession.deviceAuthId, + userCode: openAiOauthSession.userCode, + }), + }, + 20000, + ); + if (!response.ok) { + throw new Error(getErrorMessage(payload, response.status === 409 ? "OpenAI authorization is not complete yet." : `Failed to complete OpenAI OAuth (${response.status}).`)); + } + if (!payload || typeof payload !== "object" || typeof (payload as Record).opencodeAuth !== "string") { + throw new Error("OpenAI OAuth completion response was incomplete."); + } + setOpencodeAuth((payload as { opencodeAuth: string }).opencodeAuth); + setOpenAiOauthSession(null); + } catch (error) { + setOpenAiOauthError(error instanceof Error ? error.message : "Could not complete OpenAI OAuth."); + } finally { + setOpenAiOauthBusy(false); + } + } + useEffect(() => { if (source !== "models_dev" || !orgId || !selectedProviderId) { setCatalogDetail(null); @@ -286,6 +383,11 @@ export function LlmProviderEditorScreen({ } } + if (credentialKind === "opencode_oauth" && source === "models_dev" && selectedProviderId !== "openai") { + setSaveError("OpenCode OAuth credentials are only available for the OpenAI catalog provider."); + return; + } + if (source === "custom" && !customConfigText.trim()) { setSaveError("Paste a custom provider config."); return; @@ -297,6 +399,7 @@ export function LlmProviderEditorScreen({ const body: Record = { name: providerName.trim(), source, + credentialKind, memberIds: [...new Set(selectedMemberIds)], teamIds: [...new Set(selectedTeamIds)], }; @@ -308,10 +411,14 @@ export function LlmProviderEditorScreen({ body.customConfigText = customConfigText; } - if (apiKey.trim() || !provider) { + if (credentialKind === "api_key" && (apiKey.trim() || !provider || provider.credentialKind !== "api_key")) { body.apiKey = apiKey.trim(); } + if (credentialKind === "opencode_oauth" && (opencodeAuth.trim() || !provider || provider.credentialKind !== "opencode_oauth")) { + body.opencodeAuth = opencodeAuth.trim(); + } + const path = provider ? `/v1/llm-providers/${encodeURIComponent(provider.id)}` : `/v1/llm-providers`; @@ -607,28 +714,113 @@ export function LlmProviderEditorScreen({ Credential - {provider?.hasApiKey ? ( + {provider?.hasCredential ? ( Existing credential saved ) : null} -