From d4b14c46f929c213573ab27d6e3a5246aa0c2684 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 23 May 2026 18:26:03 +0200 Subject: [PATCH 01/12] feat(den): add provider credential contract base Add the LLM provider credential kind/opencode auth storage contract, migration, and passive credential redaction/flags needed by follow-up provider credential and worker sync PRs. --- .../den-api/src/routes/org/llm-providers.ts | 33 ++++++++++++++++--- .../0019_llm_provider_opencode_oauth.sql | 3 ++ ee/packages/den-db/drizzle/meta/_journal.json | 7 ++++ .../src/schema/sharables/llm-providers.ts | 4 +++ 4 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 ee/packages/den-db/drizzle/0019_llm_provider_opencode_oauth.sql 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 5cc66da166..994b43565e 100644 --- a/ee/apps/den-api/src/routes/org/llm-providers.ts +++ b/ee/apps/den-api/src/routes/org/llm-providers.ts @@ -145,6 +145,24 @@ function isOrganizationAdmin(payload: { currentMember: { isOwner: boolean; role: return payload.currentMember.isOwner || memberHasRole(payload.currentMember.role, "admin") } +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 canManageLlmProvider( payload: { currentMember: { id: MemberId; isOwner: boolean; role: string } }, provider: LlmProviderRow, @@ -464,7 +482,7 @@ async function loadLlmProviders(input: { return providers.map((provider) => ({ ...provider, - hasApiKey: Boolean(provider.apiKey && provider.apiKey.trim().length > 0), + ...getCredentialFlags(provider), models: (modelsByProviderId.get(provider.id) ?? []) .map((model) => ({ id: model.modelId, @@ -607,8 +625,7 @@ export function registerOrgLlmProviderRoutes ({ - ...provider, - apiKey: undefined, + ...redactLlmProviderCredentials(provider), canManage: canManageLlmProvider(payload, provider), })), }) @@ -678,6 +695,8 @@ export function registerOrgLlmProviderRoutes ({ id: model.modelId, @@ -781,10 +800,13 @@ export function registerOrgLlmProviderRoutes>() .notNull(), + credentialKind: mysqlEnum("credential_kind", ["api_key", "opencode_oauth"]) + .notNull() + .default("api_key"), apiKey: encryptedTextColumn("api_key"), + opencodeAuth: encryptedTextColumn("opencode_auth"), createdAt: timestamp("created_at", { fsp: 3 }).notNull().defaultNow(), updatedAt: timestamp("updated_at", { fsp: 3 }) .notNull() From efdefad0d19e62f5bd93cf8b747c47cce587b9fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 23 May 2026 22:54:28 +0200 Subject: [PATCH 02/12] feat(den): handle OAuth provider credentials Add Den API create/update/read/import handling for API-key versus OpenCode OAuth provider credentials on top of the credential contract base. --- .../den-api/src/routes/org/llm-providers.ts | 140 ++++++++++++++++-- .../test/llm-provider-credentials.test.ts | 61 ++++++++ 2 files changed, 190 insertions(+), 11 deletions(-) create mode 100644 ee/apps/den-api/test/llm-provider-credentials.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 994b43565e..e3c4438cca 100644 --- a/ee/apps/den-api/src/routes/org/llm-providers.ts +++ b/ee/apps/den-api/src/routes/org/llm-providers.ts @@ -73,10 +73,12 @@ const customProviderSchema = z.object({ const llmProviderWriteSchema = z.object({ name: z.string().trim().min(1).max(255), source: z.enum(["models_dev", "custom"]), + credentialKind: z.enum(["api_key", "opencode_oauth"]).optional().default("api_key"), providerId: z.string().trim().min(1).max(255).optional(), modelIds: z.array(z.string().trim().min(1).max(255)).min(1).optional(), customConfigText: z.string().trim().min(1).optional(), apiKey: z.string().trim().max(65535).optional(), + opencodeAuth: z.string().trim().max(65535).optional(), memberIds: z.array(denTypeIdSchema("member")).max(500).optional().default([]), teamIds: z.array(denTypeIdSchema("team")).max(500).optional().default([]), }).superRefine((value, ctx) => { @@ -105,6 +107,14 @@ const llmProviderWriteSchema = z.object({ message: "Paste a custom provider config.", }) } + + 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.", + }) + } }) const providerCatalogListResponseSchema = z.object({ @@ -163,6 +173,33 @@ export function redactLlmProviderCredentials).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.") + } +} + +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 canManageLlmProvider( payload: { currentMember: { id: MemberId; isOwner: boolean; role: string } }, provider: LlmProviderRow, @@ -292,6 +329,10 @@ async function resolveTeamIds(input: { } async function normalizeLlmProviderInput(input: z.infer) { + const credentialKind = input.credentialKind + const apiKey = credentialKind === "api_key" ? input.apiKey?.trim() || null : null + const opencodeAuth = credentialKind === "opencode_oauth" ? normalizeOpencodeAuth(input.opencodeAuth) : null + if (input.source === "models_dev") { const provider = await getModelsDevProvider(input.providerId ?? "") if (!provider) { @@ -308,10 +349,9 @@ async function normalizeLlmProviderInput(input: z.infer { + const payload = c.get("organizationContext") + const params = c.req.valid("param") + + let llmProviderId: LlmProviderId + try { + llmProviderId = parseLlmProviderId(params.llmProviderId) + } catch { + return c.json({ error: "llm_provider_not_found" }, 404) + } + + const providerRows = await db + .select() + .from(LlmProviderTable) + .where(and(eq(LlmProviderTable.id, llmProviderId), eq(LlmProviderTable.organizationId, payload.organization.id))) + .limit(1) + + const provider = providerRows[0] + if (!provider) return c.json({ error: "llm_provider_not_found" }, 404) + if (!canImportLlmProviderCredential(payload)) { + return c.json({ error: "forbidden", message: "Only organization admins can import provider credentials." }, 403) + } + + const models = await db + .select() + .from(LlmProviderModelTable) + .where(eq(LlmProviderModelTable.llmProviderId, llmProviderId)) + + return c.json({ + llmProvider: { + ...buildLlmProviderCredentialPayload(provider), + models: models + .map((model) => ({ + id: model.modelId, + name: model.name, + config: model.modelConfig, + createdAt: model.createdAt, + })) + .sort((left, right) => left.name.localeCompare(right.name)), + }, + }) + }, + ) + app.post( "/v1/llm-providers", describeRoute({ @@ -751,10 +855,12 @@ export function registerOrgLlmProviderRoutes { + seedRequiredEnv() + llmProviderModule = await import("../src/routes/org/llm-providers.js") +}) + +test("generic provider payload redaction removes API key and OAuth auth material", () => { + const redacted = llmProviderModule.redactLlmProviderCredentials({ + id: "llmProvider_secret_123", + apiKey: "plain-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: "plain-secret", + opencodeAuth: JSON.stringify({ type: "oauth", access: "access", refresh: "refresh", expires: 1 }), + })).toEqual({ hasApiKey: true, hasOpencodeAuth: true, hasCredential: true }) +}) + +test("credential import permission gate requires 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.canImportLlmProviderCredential(owner)).toBe(true) + expect(llmProviderModule.canImportLlmProviderCredential(admin)).toBe(true) + expect(llmProviderModule.canImportLlmProviderCredential(creatorOnly)).toBe(false) +}) + +test("purpose-specific import endpoint requires authentication", async () => { + const app = new Hono() + llmProviderModule.registerOrgLlmProviderRoutes(app) + + 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" }) +}) From 32b39e7be4a27e509aef75b6de6507ac26fbf383 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Sat, 23 May 2026 22:56:28 +0200 Subject: [PATCH 03/12] feat(app): import OAuth-backed Den providers Allow desktop cloud-provider import to consume OpenCode OAuth-backed organization providers from the Den credential import endpoint. --- apps/app/src/app/lib/den.ts | 8 ++++ .../connections/provider-auth/store.ts | 44 +++++++++++++++++-- 2 files changed, 48 insertions(+), 4 deletions(-) diff --git a/apps/app/src/app/lib/den.ts b/apps/app/src/app/lib/den.ts index d5aebaf2be..0f425a9473 100644 --- a/apps/app/src/app/lib/den.ts +++ b/apps/app/src/app/lib/den.ts @@ -111,10 +111,13 @@ export type DenOrgLlmProviderModel = { export type DenOrgLlmProvider = { id: string; source: "models_dev" | "custom" | "openwork"; + credentialKind: "api_key" | "opencode_oauth"; providerId: string; name: string; providerConfig: Record; hasApiKey: boolean; + hasOpencodeAuth: boolean; + hasCredential: boolean; models: DenOrgLlmProviderModel[]; createdAt: string | null; updatedAt: string | null; @@ -122,6 +125,7 @@ export type DenOrgLlmProvider = { export type DenOrgLlmProviderConnection = DenOrgLlmProvider & { apiKey: string | null; + opencodeAuth: string | null; }; export type DenPluginConfigObjectType = "skill" | "agent" | "command" | "tool" | "mcp" | "hook" | "context" | "custom"; @@ -897,10 +901,13 @@ function parseDenOrgLlmProvider(value: unknown): DenOrgLlmProvider | null { return { id: value.id, source: value.source, + credentialKind: value.credentialKind === "opencode_oauth" ? "opencode_oauth" : "api_key", providerId: value.providerId, name: value.name, providerConfig: isRecord(value.providerConfig) ? value.providerConfig : {}, hasApiKey: value.hasApiKey === true, + hasOpencodeAuth: value.hasOpencodeAuth === true, + hasCredential: value.hasCredential === true || value.hasApiKey === true || value.hasOpencodeAuth === true, models: Array.isArray(value.models) ? value.models.flatMap((model) => { const parsed = parseDenOrgLlmProviderModel(model); @@ -936,6 +943,7 @@ function getDenOrgLlmProviderConnection(payload: unknown): DenOrgLlmProviderConn return { ...provider, apiKey: typeof payload.llmProvider.apiKey === "string" ? payload.llmProvider.apiKey : null, + opencodeAuth: typeof payload.llmProvider.opencodeAuth === "string" ? payload.llmProvider.opencodeAuth : null, }; } diff --git a/apps/app/src/react-app/domains/connections/provider-auth/store.ts b/apps/app/src/react-app/domains/connections/provider-auth/store.ts index b0550da8f8..192c403d36 100644 --- a/apps/app/src/react-app/domains/connections/provider-auth/store.ts +++ b/apps/app/src/react-app/domains/connections/provider-auth/store.ts @@ -163,8 +163,12 @@ export function createProviderAuthStore(options: CreateProviderAuthStoreOptions) a.length === b.length && a.every((value, index) => value === b[index]); const getCloudManagedProviderId = ( - provider: Pick, - ) => provider.source === "openwork" ? "openwork" : provider.id.trim(); + provider: Pick, + ) => { + if (provider.source === "openwork") return "openwork"; + if (provider.credentialKind === "opencode_oauth") return provider.providerId.trim(); + return provider.id.trim(); + }; const getProviderAuthWorkerType = (): "local" | "remote" => options.selectedWorkspaceDisplay().workspaceType === "remote" ? "remote" : "local"; @@ -1327,14 +1331,45 @@ export function createProviderAuthStore(options: CreateProviderAuthStoreOptions) const existingImported = state.importedCloudProviders[cloudProviderId] ?? null; const localProviderId = getCloudManagedProviderId(provider); const apiKey = provider.apiKey?.trim() ?? ""; + const opencodeAuth = provider.opencodeAuth?.trim() ?? ""; const env = getCloudProviderEnv(provider.providerConfig); - if (!apiKey && env.length > 0) { + if (provider.credentialKind === "opencode_oauth" && !opencodeAuth) { + throw new Error(`${provider.name} does not have a stored OpenCode OAuth credential yet.`); + } + if (provider.credentialKind === "api_key" && !apiKey && env.length > 0) { throw new Error(`${provider.name} does not have a stored organization credential yet.`); } await assertCloudProviderImportSafe(provider); - if (apiKey) { + if (provider.credentialKind === "opencode_oauth" && opencodeAuth) { + let parsedAuth: unknown; + try { + parsedAuth = JSON.parse(opencodeAuth); + } catch { + throw new Error(`${provider.name} has invalid OpenCode OAuth JSON.`); + } + if (!parsedAuth || typeof parsedAuth !== "object" || Array.isArray(parsedAuth)) { + throw new Error(`${provider.name} OpenCode OAuth auth must be a JSON object.`); + } + const authRecord = parsedAuth as Record; + if (authRecord.type !== "oauth") { + throw new Error(`${provider.name} OpenCode OAuth auth must include type "oauth".`); + } + if (typeof authRecord.access !== "string" || !authRecord.access.trim()) { + throw new Error(`${provider.name} OpenCode OAuth auth must include an access token.`); + } + if (typeof authRecord.refresh !== "string" || !authRecord.refresh.trim()) { + throw new Error(`${provider.name} OpenCode OAuth auth must include a refresh token.`); + } + if (typeof authRecord.expires !== "number" || !Number.isFinite(authRecord.expires) || authRecord.expires < 0) { + throw new Error(`${provider.name} OpenCode OAuth auth must include a non-negative numeric expires value.`); + } + await c.auth.set({ + providerID: localProviderId, + auth: parsedAuth as Parameters[0]["auth"], + }); + } else if (apiKey) { await c.auth.set({ providerID: localProviderId, auth: { type: "api", key: apiKey }, @@ -1380,6 +1415,7 @@ export function createProviderAuthStore(options: CreateProviderAuthStoreOptions) .filter((id) => id !== localProviderId && id !== existingImported?.providerId); options.setDisabledProviders(nextDisabledProviders); options.markOpencodeConfigReloadRequired(); + await refreshProviders({ dispose: true }).catch(() => null); refreshSnapshot(); emitChange(); return `${t("status.connected")} ${provider.name}`; From 976b68c2119c2d731e491f7776ab83a9775e16ea 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 04/12] 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} -