Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(codex): derive OAuth redirect from cluster Control UI URL
Alfredo Lopez69339edae6ed
diff --git a/Makefile b/Makefileindex 94120c12f..ed9004687 100644--- a/Makefile+++ b/Makefile@@ -523,6 +523,10 @@ minikube-sync-auth-key-if-present: ## Sync JWT public key only when minikube aut$(MAKE) --no-print-directory minikube-sync-auth-key; \fi+.PHONY: minikube-sync-codex-subscription-url+minikube-sync-codex-subscription-url: ## Resolve branch Control UI URL and sync CONTROL_API_CONTROL_UI_BASE_URL for Codex OAuth+ @bash scripts/minikube/sync-codex-subscription-control-ui-url.sh --context=$(MINIKUBE_PROFILE)+# ── Minikube Port Forwards ──────────────────────────────────────────.PHONY: minikube-pf-control-uiminikube-pf-control-ui: ## Port-forward Control UI → localhost:3000diff --git a/control-api/src/config.ts b/control-api/src/config.tsindex 3e06ee943..2e8998387 100644--- a/control-api/src/config.ts+++ b/control-api/src/config.ts@@ -783,7 +783,8 @@ export const config: Config = {// Codex subscription management and admission dark.codexSubscriptionEnabled: process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED === 'true',// Public native client used by the Codex CLI ChatGPT login. This is not a- // confidential client secret.+ // confidential client secret. Browser OAuth requires a deployment-registered+ // client id; the default CLI client supports device-code connect only.codexOAuthClientId:process.env.CONTROL_API_CODEX_OAUTH_CLIENT_ID || 'app_EMoamEEZ73f0CkXaXp7hrann',// Default 24h. Validated (not merely parsed): the value goes straight intodiff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex b1bb6af4d..df5a1206e 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -21,6 +21,11 @@ import {startCodexDeviceConnect,} from '../../services/codexSubscriptionOAuth.js'import type { CodexSubscriptionOAuthIntent } from '../../services/codexSubscriptionOAuthState.js'+import {+ buildCodexBrowserRedirectUri,+ isPublicCodexCliClient,+ resolveCodexControlUiBaseUrl,+} from '../../services/codexSubscriptionRedirectUri.js'const log = rootLogger.child({ module: 'admin-codex-subscription' })const BASE = '/admin/llm/providers/codex-subscription'@@ -29,27 +34,23 @@ function dbClient() {return { query: (text: string, values?: unknown[]) => pool.query(text, values) }}-function buildRedirectUri(req: {- protocol: string- get: (h: string) => string | undefined-}): string {- const origin =- config.oauthCallbackBaseUrl && config.oauthCallbackBaseUrl.length > 0- ? config.oauthCallbackBaseUrl.replace(/\/+$/, '')- : `${req.protocol}://${req.get('host') ?? 'localhost'}`- return `${origin}/api/v1/auth/codex-subscription/callback`+function resolveBrowserRedirectUri(req: { get: (h: string) => string | undefined }): string {+ const controlUiOrigin = resolveCodexControlUiBaseUrl(config.controlUiBaseUrl, req.get('origin'))+ return buildCodexBrowserRedirectUri(controlUiOrigin)}-function oauthDeps(req: {- protocol: string- get: (h: string) => string | undefined-}): CodexOAuthDeps {+function oauthDeps(+ req: {+ get: (h: string) => string | undefined+ },+ redirectUri = resolveBrowserRedirectUri(req)+): CodexOAuthDeps {return {db: dbClient(),encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),fetchFn: fetch,clientId: config.codexOAuthClientId,- redirectUri: buildRedirectUri(req),+ redirectUri,enabled: config.codexSubscriptionEnabled,}}@@ -104,8 +105,15 @@ export function createAdminCodexSubscriptionRouter(`${BASE}/browser/start`,asyncHandler(async (req, res) => {try {+ const redirectUri = resolveBrowserRedirectUri(req)+ if (isPublicCodexCliClient(config.codexOAuthClientId)) {+ throw new CodexSubscriptionOAuthError(+ 'browser_oauth_unregistered',+ 'browser OAuth requires a deployment-registered OpenAI client'+ )+ }const started = await startCodexBrowserConnect(- oauthDeps(req),+ oauthDeps(req, redirectUri),parseIntent(req.body?.intent))res.status(200).json(started)diff --git a/control-api/src/routes/auth/codexSubscription.ts b/control-api/src/routes/auth/codexSubscription.tsindex 1259c5bfd..2d6fe645e 100644--- a/control-api/src/routes/auth/codexSubscription.ts+++ b/control-api/src/routes/auth/codexSubscription.ts@@ -9,6 +9,11 @@ import {CodexSubscriptionOAuthError,handleCodexBrowserCallback,} from '../../services/codexSubscriptionOAuth.js'+import {+ buildCodexBrowserRedirectUri,+ buildCodexBrowserReturnLocation,+ resolveCodexCallbackControlUiBaseUrl,+} from '../../services/codexSubscriptionRedirectUri.js'const log = rootLogger.child({ module: 'auth-codex-subscription' })@@ -20,20 +25,29 @@ function oauthDeps(req: {protocol: stringget: (h: string) => string | undefined}): CodexOAuthDeps {- const origin =- config.oauthCallbackBaseUrl && config.oauthCallbackBaseUrl.length > 0- ? config.oauthCallbackBaseUrl.replace(/\/+$/, '')- : `${req.protocol}://${req.get('host') ?? 'localhost'}`+ const controlUiOrigin = resolveCodexCallbackControlUiBaseUrl({+ configuredBaseUrl: config.controlUiBaseUrl,+ forwardedHost: req.get('x-forwarded-host'),+ forwardedProto: req.get('x-forwarded-proto'),+ originHeader: req.get('origin'),+ })return {db: dbClient(),encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),fetchFn: fetch,clientId: config.codexOAuthClientId,- redirectUri: `${origin}/api/v1/auth/codex-subscription/callback`,+ redirectUri: buildCodexBrowserRedirectUri(controlUiOrigin),enabled: config.codexSubscriptionEnabled,}}+function redirectToCodexSurface(+ res: { redirect: (status: number, location: string) => void },+ outcome: string+) {+ res.redirect(303, buildCodexBrowserReturnLocation(outcome))+}+export function createAuthCodexSubscriptionRouter(): Router {const router = Router()@@ -43,17 +57,16 @@ export function createAuthCodexSubscriptionRouter(): Router {const code = typeof req.query.code === 'string' ? req.query.code : ''const state = typeof req.query.state === 'string' ? req.query.state : ''try {- const connection = await handleCodexBrowserCallback(oauthDeps(req), { code, state })- res.status(200).json({- status: connection.status,- accountFingerprint: connection.accountFingerprint,- credentialRevision: connection.credentialRevision,- })+ await handleCodexBrowserCallback(oauthDeps(req), { code, state })+ redirectToCodexSurface(res, 'connected')} catch (err) {if (err instanceof CodexSubscriptionOAuthError) {- const status = err.code === 'disabled' ? 404 : 400log.warn({ event: 'codex_oauth_callback_denied', code: err.code }, 'callback denied')- res.status(status).json({ error: err.code })+ if (err.code === 'disabled') {+ res.status(404).json({ error: err.code })+ return+ }+ redirectToCodexSurface(res, err.code)return}throw errdiff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.tsindex de96a16bc..2cdc3478c 100644--- a/control-api/src/services/codexSubscriptionOAuth.ts+++ b/control-api/src/services/codexSubscriptionOAuth.ts@@ -46,6 +46,7 @@ export type CodexOAuthErrorCode =| 'provider_unavailable'| 'no_grant'| 'invalid_callback'+ | 'browser_oauth_unregistered'export class CodexSubscriptionOAuthError extends Error {readonly code: CodexOAuthErrorCodediff --git a/control-api/src/services/codexSubscriptionRedirectUri.ts b/control-api/src/services/codexSubscriptionRedirectUri.tsnew file mode 100644index 000000000..1a8ac88be--- /dev/null+++ b/control-api/src/services/codexSubscriptionRedirectUri.ts@@ -0,0 +1,96 @@+/** Public OAuth client shipped with the Codex CLI — device-code only for Evenfire. */+export const PUBLIC_CODEX_CLI_CLIENT_ID = 'app_EMoamEEZ73f0CkXaXp7hrann'++/** Same-origin proxy path control-ui uses before forwarding to control-api. */+export const CODEX_BROWSER_CALLBACK_PROXY_PATH =+ '/control-api/api/v1/auth/codex-subscription/callback'++export const CODEX_BROWSER_RETURN_PATH = '/llm-models/providers/codex-subscription'++export function isPublicCodexCliClient(clientId: string): boolean {+ return clientId === PUBLIC_CODEX_CLI_CLIENT_ID+}++export function normalizeControlUiOrigin(value: string): string {+ let url: URL+ try {+ url = new URL(value)+ } catch {+ throw new Error('control-ui base URL is not a valid URL')+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ throw new Error('control-ui base URL must use http or https')+ }+ if (!url.hostname) {+ throw new Error('control-ui base URL is missing a host')+ }+ const path = url.pathname.replace(/\/+$/, '')+ if (path.length > 0) {+ throw new Error('control-ui base URL must not include a path')+ }+ return `${url.protocol}//${url.host}`+}++export function isLoopbackHttpOrigin(origin: string): boolean {+ try {+ const url = new URL(origin)+ return (+ url.protocol === 'http:' && (url.hostname === 'localhost' || url.hostname === '127.0.0.1')+ )+ } catch {+ return false+ }+}++/**+ * Resolve the deployment control-ui origin. In local loopback profiles the live+ * browser Origin may differ from the declared ConfigMap port; accept it only+ * when both sides are loopback HTTP.+ */+export function resolveCodexControlUiBaseUrl(+ configuredBaseUrl: string,+ originHeader: string | undefined+): string {+ const configured = normalizeControlUiOrigin(configuredBaseUrl)+ if (!originHeader) return configured+ try {+ const requestOrigin = normalizeControlUiOrigin(originHeader)+ if (isLoopbackHttpOrigin(configured) && isLoopbackHttpOrigin(requestOrigin)) {+ return requestOrigin+ }+ } catch {+ return configured+ }+ return configured+}++/**+ * Derive the OAuth callback from the public control-ui origin. OpenAI must see+ * this exact value in authorize and token exchange.+ */+export function buildCodexBrowserRedirectUri(controlUiBaseUrl: string): string {+ return `${normalizeControlUiOrigin(controlUiBaseUrl)}${CODEX_BROWSER_CALLBACK_PROXY_PATH}`+}++/** Public host seen by the browser after the control-ui proxy forwards the callback. */+export function resolveCodexCallbackControlUiBaseUrl(input: {+ configuredBaseUrl: string+ forwardedHost?: string | null+ forwardedProto?: string | null+ originHeader?: string | null+}): string {+ const forwardedHost = input.forwardedHost?.split(',')[0]?.trim()+ const forwardedProto = input.forwardedProto?.split(',')[0]?.trim()+ if (forwardedHost && forwardedProto) {+ try {+ return normalizeControlUiOrigin(`${forwardedProto}://${forwardedHost}`)+ } catch {+ // Fall through to configured / Origin resolution.+ }+ }+ return resolveCodexControlUiBaseUrl(input.configuredBaseUrl, input.originHeader ?? undefined)+}++export function buildCodexBrowserReturnLocation(outcome: string): string {+ return `${CODEX_BROWSER_RETURN_PATH}?codex_oauth=${encodeURIComponent(outcome)}`+}diff --git a/control-api/test/codexSubscriptionRedirectUri.test.ts b/control-api/test/codexSubscriptionRedirectUri.test.tsnew file mode 100644index 000000000..5651b96dd--- /dev/null+++ b/control-api/test/codexSubscriptionRedirectUri.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from 'vitest'+import {+ PUBLIC_CODEX_CLI_CLIENT_ID,+ buildCodexBrowserRedirectUri,+ buildCodexBrowserReturnLocation,+ isPublicCodexCliClient,+ resolveCodexCallbackControlUiBaseUrl,+ resolveCodexControlUiBaseUrl,+} from '../src/services/codexSubscriptionRedirectUri.js'++describe('codex subscription redirect URI', () => {+ it('builds the control-ui proxied callback from the cluster public origin', () => {+ expect(buildCodexBrowserRedirectUri('https://control.example.com')).toBe(+ 'https://control.example.com/control-api/api/v1/auth/codex-subscription/callback'+ )+ expect(buildCodexBrowserRedirectUri('http://127.0.0.1:36148/')).toBe(+ 'http://127.0.0.1:36148/control-api/api/v1/auth/codex-subscription/callback'+ )+ })++ it('never emits the Codex CLI loopback redirect', () => {+ const redirect = buildCodexBrowserRedirectUri('http://127.0.0.1:36148')+ expect(redirect).not.toContain(':1455')+ expect(redirect).not.toMatch(/\/auth\/callback$/)+ })++ it('rejects invalid control-ui base URLs', () => {+ expect(() => buildCodexBrowserRedirectUri('')).toThrow()+ expect(() => buildCodexBrowserRedirectUri('not-a-url')).toThrow()+ expect(() => buildCodexBrowserRedirectUri('https://control.example.com/extra')).toThrow()+ })++ it('accepts loopback Origin overrides only for local profiles', () => {+ expect(resolveCodexControlUiBaseUrl('http://127.0.0.1:3000', 'http://127.0.0.1:36148')).toBe(+ 'http://127.0.0.1:36148'+ )+ expect(+ resolveCodexControlUiBaseUrl('https://control.example.com', 'https://evil.example.com')+ ).toBe('https://control.example.com')+ })++ it('prefers forwarded host on OAuth callback requests', () => {+ expect(+ resolveCodexCallbackControlUiBaseUrl({+ configuredBaseUrl: 'http://127.0.0.1:3000',+ forwardedHost: '127.0.0.1:36148',+ forwardedProto: 'http',+ })+ ).toBe('http://127.0.0.1:36148')+ })++ it('identifies the public Codex CLI client id', () => {+ expect(isPublicCodexCliClient(PUBLIC_CODEX_CLI_CLIENT_ID)).toBe(true)+ expect(isPublicCodexCliClient('app_evenfire_custom')).toBe(false)+ })++ it('builds a relative browser return location', () => {+ expect(buildCodexBrowserReturnLocation('connected')).toBe(+ '/llm-models/providers/codex-subscription?codex_oauth=connected'+ )+ })+})diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.tsindex 679435baa..e527c6143 100644--- a/control-api/test/routes.admin.codexSubscription.test.ts+++ b/control-api/test/routes.admin.codexSubscription.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import express, { type NextFunction, type Request, type Response } from 'express'import request from 'supertest'import { CodexSubscriptionOAuthError } from '../src/services/codexSubscriptionOAuth.js'+import { PUBLIC_CODEX_CLI_CLIENT_ID } from '../src/services/codexSubscriptionRedirectUri.js'const oauth = vi.hoisted(() => ({getConnection: vi.fn(),@@ -53,10 +54,14 @@ function assertNoLeak(body: unknown): void {describe('admin Codex subscription routes', () => {let app: ReturnType<typeof makeAuthedApp>+ const originalClientId = config.codexOAuthClientId+ const originalControlUiBaseUrl = config.controlUiBaseUrlbeforeEach(() => {app = makeAuthedApp()config.codexSubscriptionEnabled = true+ config.codexOAuthClientId = originalClientId+ config.controlUiBaseUrl = originalControlUiBaseUrlfor (const fn of Object.values(oauth)) fn.mockReset()})@@ -81,13 +86,44 @@ describe('admin Codex subscription routes', () => {assertNoLeak(res.body)})- it('starts browser and device flows without tokens or cookies', async () => {+ it('blocks browser start for the public Codex CLI client', async () => {+ config.codexOAuthClientId = PUBLIC_CODEX_CLI_CLIENT_ID+ const res = await request(app)+ .post('/admin/llm/providers/codex-subscription/browser/start')+ .set('Origin', 'http://127.0.0.1:36148')+ .send({ intent: 'connect' })+ expect(res.status).toBe(400)+ expect(res.body).toEqual({ error: 'browser_oauth_unregistered' })+ expect(oauth.startBrowser).not.toHaveBeenCalled()+ assertNoLeak(res.body)+ })++ it('starts browser OAuth with a control-ui derived redirect for custom clients', async () => {+ config.codexOAuthClientId = 'app_evenfire_custom'+ config.controlUiBaseUrl = 'http://127.0.0.1:3000'oauth.startBrowser.mockResolvedValue({authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=abc',state: 'abc',intent: 'connect',expiresAt: new Date().toISOString(),})+ const res = await request(app)+ .post('/admin/llm/providers/codex-subscription/browser/start')+ .set('Host', 'control-api.control-plane.svc.cluster.local:8090')+ .set('Origin', 'http://127.0.0.1:36148')+ .send({ intent: 'connect' })+ expect(res.status).toBe(200)+ expect(oauth.startBrowser).toHaveBeenCalledWith(+ expect.objectContaining({+ redirectUri: 'http://127.0.0.1:36148/control-api/api/v1/auth/codex-subscription/callback',+ }),+ 'connect'+ )+ assertNoLeak(res.body)+ })++ it('starts device flow without tokens or cookies even with the public client', async () => {+ config.codexOAuthClientId = PUBLIC_CODEX_CLI_CLIENT_IDoauth.startDevice.mockResolvedValue({userCode: 'ABCD-EFGH',verificationUri: 'https://auth.openai.com/codex/device',@@ -95,14 +131,6 @@ describe('admin Codex subscription routes', () => {state: 'dev',intent: 'connect',})- const browser = await request(app)- .post('/admin/llm/providers/codex-subscription/browser/start')- .send({ intent: 'connect' })- expect(browser.status).toBe(200)- expect(browser.body.authorizeUrl).toContain('https://auth.openai.com/oauth/authorize')- expect(browser.headers['set-cookie']).toBeUndefined()- assertNoLeak(browser.body)-const device = await request(app).post('/admin/llm/providers/codex-subscription/device/start').send({ intent: 'replace' })@@ -113,6 +141,7 @@ describe('admin Codex subscription routes', () => {})it('maps replacement and refresh races to 409 without leaking tokens', async () => {+ config.codexOAuthClientId = 'app_evenfire_custom'oauth.startBrowser.mockRejectedValue(new CodexSubscriptionOAuthError('replacement_required', 'replace'))diff --git a/control-api/test/routes.auth.codexSubscriptionCallback.test.ts b/control-api/test/routes.auth.codexSubscriptionCallback.test.tsindex 470d106c7..9ef6aef03 100644--- a/control-api/test/routes.auth.codexSubscriptionCallback.test.ts+++ b/control-api/test/routes.auth.codexSubscriptionCallback.test.ts@@ -19,6 +19,7 @@ vi.mock('../src/db.js', () => ({pool: { query: vi.fn() },}))+const { config } = await import('../src/config.js')const { createAuthCodexSubscriptionRouter } =await import('../src/routes/auth/codexSubscription.js')@@ -28,8 +29,8 @@ function makeApp() {return app}-function assertNoLeak(body: unknown): void {- const serialized = JSON.stringify(body)+function assertNoLeak(value: unknown): void {+ const serialized = typeof value === 'string' ? value : JSON.stringify(value)expect(serialized).not.toMatch(/sk-|Bearer |eyJ[A-Za-z0-9_-]+\.|refresh-secret|access-secret/i)expect(serialized).not.toMatch(/cookie|set-cookie|authorization/i)expect(serialized).not.toContain('acct_raw_123')@@ -41,27 +42,10 @@ describe('GET /auth/codex-subscription/callback', () => {beforeEach(() => {app = makeApp()oauth.callback.mockReset()+ config.controlUiBaseUrl = 'http://127.0.0.1:3000'})- it('rejects a missing code or state', async () => {- oauth.callback.mockRejectedValue(new CodexSubscriptionOAuthError('invalid_callback', 'missing'))- const res = await request(app).get('/auth/codex-subscription/callback')- expect(res.status).toBe(400)- expect(res.body).toEqual({ error: 'invalid_callback' })- assertNoLeak(res.body)- })-- it('rejects callback replay', async () => {- oauth.callback.mockRejectedValue(new CodexSubscriptionOAuthError('state_replayed', 'replay'))- const res = await request(app)- .get('/auth/codex-subscription/callback')- .query({ code: 'code-1', state: 'state-1' })- expect(res.status).toBe(400)- expect(res.body).toEqual({ error: 'state_replayed' })- assertNoLeak(res.body)- })-- it('returns only safe connection fields on success', async () => {+ it('redirects back to the Codex surface on success without tokens', async () => {oauth.callback.mockResolvedValue({status: 'connected',accountFingerprint: 'fp',@@ -71,14 +55,40 @@ describe('GET /auth/codex-subscription/callback', () => {})const res = await request(app).get('/auth/codex-subscription/callback')+ .set('x-forwarded-host', '127.0.0.1:36148')+ .set('x-forwarded-proto', 'http').query({ code: 'code-1', state: 'state-1' })- expect(res.status).toBe(200)- expect(res.body).toEqual({- status: 'connected',- accountFingerprint: 'fp',- credentialRevision: 1,- })+ expect(res.status).toBe(303)+ expect(res.headers.location).toBe(+ '/llm-models/providers/codex-subscription?codex_oauth=connected'+ )+ expect(oauth.callback).toHaveBeenCalledWith(+ expect.objectContaining({+ redirectUri: 'http://127.0.0.1:36148/control-api/api/v1/auth/codex-subscription/callback',+ }),+ { code: 'code-1', state: 'state-1' }+ )expect(res.headers['set-cookie']).toBeUndefined()+ assertNoLeak(res.text)+ })++ it('redirects callback replay errors back to the Codex surface', async () => {+ oauth.callback.mockRejectedValue(new CodexSubscriptionOAuthError('state_replayed', 'replay'))+ const res = await request(app)+ .get('/auth/codex-subscription/callback')+ .query({ code: 'code-1', state: 'state-1' })+ expect(res.status).toBe(303)+ expect(res.headers.location).toBe(+ '/llm-models/providers/codex-subscription?codex_oauth=state_replayed'+ )+ assertNoLeak(res.headers.location)+ })++ it('returns 404 JSON when the feature is disabled', async () => {+ oauth.callback.mockRejectedValue(new CodexSubscriptionOAuthError('disabled', 'off'))+ const res = await request(app).get('/auth/codex-subscription/callback')+ expect(res.status).toBe(404)+ expect(res.body).toEqual({ error: 'disabled' })assertNoLeak(res.body)})})diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.tsindex 7002615b3..3eec7da5d 100644--- a/control-api/test/services.codexSubscriptionOAuth.test.ts+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts@@ -80,7 +80,7 @@ function deps(fetchFn: typeof fetch) {encryptionKey: KEY,fetchFn,clientId: 'app_test_client',- redirectUri: 'https://control.example/api/v1/auth/codex-subscription/callback',+ redirectUri: 'https://control.example.com/control-api/api/v1/auth/codex-subscription/callback',enabled: true,}}@@ -107,10 +107,12 @@ describe('codex subscription OAuth broker', () => {createdAt: new Date(),}))- const result = await startCodexBrowserConnect(deps(vi.fn()), 'connect')+ const oauthDeps = deps(vi.fn())+ const result = await startCodexBrowserConnect(oauthDeps, 'connect')expect(result.authorizeUrl.startsWith(CODEX_OAUTH_AUTHORIZE_URL)).toBe(true)expect(result.authorizeUrl).toContain('code_challenge_method=S256')expect(result.authorizeUrl).toContain('state=')+ expect(result.authorizeUrl).toContain(encodeURIComponent(oauthDeps.redirectUri))expect(repos.insertState.mock.calls[0]?.[2]).toMatchObject({flow: 'browser',intent: 'connect',diff --git a/control-ui/app/control-api/[...path]/route.ts b/control-ui/app/control-api/[...path]/route.tsindex 52b647a5a..2462db76a 100644--- a/control-ui/app/control-api/[...path]/route.ts+++ b/control-ui/app/control-api/[...path]/route.ts@@ -147,6 +147,11 @@ function copyRequestHeaders(req: NextRequest): Headers {headers.set(key, value)}})+ const host = req.headers.get('host') ?? req.nextUrl.host+ if (host) {+ headers.set('x-forwarded-host', host)+ headers.set('x-forwarded-proto', req.nextUrl.protocol.replace(':', ''))+ }return headers}diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 0d9b4fadd..03ba7d836 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -7785,6 +7785,16 @@ textarea.cu-input {color: var(--cu-text-muted);}+.cu-llm-config__block-tag--warning {+ border-color: rgba(var(--cu-warning-rgb), 0.4);+ color: var(--cu-warning);+}++.cu-llm-config__block-tag--danger {+ border-color: rgba(var(--cu-danger-rgb), 0.4);+ color: var(--cu-danger);+}+.cu-llm-config__model-row {display: grid;grid-template-columns: repeat(auto-fit, minmax(12rem, 1fr));@@ -7842,9 +7852,11 @@ textarea.cu-input {.cu-filter-select__copy,.cu-filter-select__icon,.cu-chip,- .cu-px-provider+ .cu-px-provider,+ .cu-codex-subscription-entry,+ .cu-codex-subscription-header-icon)- .cu-llm-provider-icon[data-provider='openai']+ .cu-llm-provider-icon:is([data-provider='openai'], [data-provider='codex-subscription'])img {filter: brightness(0);}@@ -10397,6 +10409,92 @@ textarea.cu-input {flex: 0 0 auto;}+.cu-codex-subscription-entry {+ display: flex;+ align-items: center;+ gap: var(--cu-space-3);+ padding: var(--cu-space-3) var(--cu-space-4);+ border: 1px solid var(--cu-border);+ border-radius: var(--cu-radius-sm);+ background: var(--cu-bg-elevated);+ color: inherit;+ text-decoration: none;+ transition:+ border-color 0.15s ease,+ background 0.15s ease;+}++.cu-codex-subscription-entry:hover {+ border-color: var(--cu-border-strong);+ background: var(--cu-bg-panel);+}++.cu-codex-subscription-entry:focus-visible {+ outline: 2px solid rgba(var(--cu-focus-rgb), 0.8);+ outline-offset: 2px;+}++.cu-codex-subscription-entry__brand {+ display: inline-flex;+ align-items: center;+ gap: var(--cu-space-2);+ flex: none;+}++.cu-codex-subscription-entry__brand .cu-llm-provider-icon {+ width: 2rem;+ height: 2rem;+ flex: 0 0 2rem;+}++.cu-codex-subscription-entry__copy {+ display: grid;+ gap: 0.15rem;+ flex: 1;+ min-width: 0;+}++.cu-codex-subscription-entry__title {+ color: var(--cu-text);+ font-weight: 600;+}++.cu-codex-subscription-entry__subtitle {+ color: var(--cu-text-soft);+ font-size: 0.8125rem;+ line-height: 1.45;+}++.cu-codex-subscription-entry__chevron {+ flex: none;+ color: var(--cu-text-muted);+}++.cu-codex-subscription-header-icon {+ display: inline-flex;+ align-items: center;+ gap: 0.2rem;+}++.cu-codex-subscription-header-icon .cu-llm-provider-icon {+ width: 1.35rem;+ height: 1.35rem;+ flex: 0 0 1.35rem;+}++.cu-codex-subscription-panel {+ display: grid;+ gap: var(--cu-space-4);+}++.cu-codex-subscription-panel__status-row {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: var(--cu-space-2);+}+.cu-agent-select.cu-llm-provider-filter {width: 12rem;flex: 0 0 12rem;diff --git a/control-ui/components/CodexSubscriptionConnection/index.tsx b/control-ui/components/CodexSubscriptionConnection/index.tsxindex 2d3e8369f..cd0eb9d43 100644--- a/control-ui/components/CodexSubscriptionConnection/index.tsx+++ b/control-ui/components/CodexSubscriptionConnection/index.tsx@@ -1,19 +1,22 @@'use client'import React, { useEffect, useMemo, useState } from 'react'-import { useRouter } from 'next/navigation'+import { useRouter, useSearchParams } from 'next/navigation'import { useConfirmDialog } from '@components/ConfirmDialog'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'-import { IconModels } from '@components/Sidebar/icons'+import { LlmProviderIcon } from '@components/LlmProviderIcon'import { useToast } from '@components/Toast'+import { Button, FormSection } from '@components/ui'import { CONTROL_ROUTES } from '@constants/routes'import { isSilentApiError } from '@lib/api'import {type CodexOAuthIntent,type CodexSubscriptionConnectionView,getCodexSubscriptionConnection,+ isCodexBrowserOAuthUnavailableError,pollCodexDevice,+ readCodexOAuthQueryParam,refreshCodexSubscriptionConnection,revokeCodexSubscription,startCodexBrowserConnect,@@ -24,7 +27,12 @@ import {isCodexSubscriptionUiEnabled,loadCodexSubscriptionCapability,} from '@lib/codexSubscriptionFeature'-import { type CodexSubscriptionUiStatus, mapConnectionStatus } from './types'+import {+ type CodexSubscriptionUiStatus,+ mapConnectionStatus,+ statusLabel,+ statusTagClass,+} from './types'function failureClass(error: unknown): string {if (@@ -38,27 +46,39 @@ function failureClass(error: unknown): string {return 'unavailable'}-function statusLabel(status: CodexSubscriptionUiStatus): string {- switch (status) {- case 'connected':- return 'Connected'- case 'connecting':- return 'Connecting'- case 'device-pending':- return 'Device code pending'- case 'reauth-required':- return 'Reauthorization required'- case 'revoking':- return 'Revoking'- case 'unavailable':- return 'Unavailable'- default:- return 'Disconnected'- }+function CodexHeaderIcon() {+ return (+ <span className="cu-codex-subscription-header-icon" aria-hidden="true">+ <LlmProviderIcon provider="openai" label="OpenAI" />+ <LlmProviderIcon provider="codex-subscription" label="Codex subscription" />+ </span>+ )+}++function ConnectionDetailRow({+ label,+ value,+ testId,+}: {+ label: string+ value: React.ReactNode+ testId?: string+}) {+ return (+ <div className="cu-settings-row">+ <div className="cu-settings-row__main">+ <span className="cu-settings-row__label">{label}</span>+ <span className="cu-settings-row__value" {...(testId ? { 'data-testid': testId } : {})}>+ {value}+ </span>+ </div>+ </div>+ )}export function CodexSubscriptionConnection() {const router = useRouter()+ const searchParams = useSearchParams()const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()const [capabilityReady, setCapabilityReady] = useState(false)@@ -71,6 +91,7 @@ export function CodexSubscriptionConnection() {const [pollMs, setPollMs] = useState(5000)const [syncSummary, setSyncSummary] = useState<string | null>(null)const [errorClass, setErrorClass] = useState<string | null>(null)+ const [browserOAuthBlocked, setBrowserOAuthBlocked] = useState(false)const [busy, setBusy] = useState(false)function applyConnection(next: CodexSubscriptionConnectionView) {@@ -104,6 +125,23 @@ export function CodexSubscriptionConnection() {}}, [])+ useEffect(() => {+ const outcome = readCodexOAuthQueryParam(searchParams)+ if (!outcome) return+ router.replace(CONTROL_ROUTES.llmModels.codexSubscription)+ if (outcome === 'connected') {+ void loadConnection().then(() => {+ showToast('Codex subscription connected.', { tone: 'success' })+ })+ return+ }+ setErrorClass(outcome)+ if (outcome === 'browser_oauth_unregistered') {+ setBrowserOAuthBlocked(true)+ }+ setUiStatus('disconnected')+ }, [router, searchParams, showToast])+useEffect(() => {if (!deviceState || uiStatus !== 'device-pending') return undefinedconst timer = window.setInterval(() => {@@ -145,14 +183,19 @@ export function CodexSubscriptionConnection() {async function startBrowser(intent: CodexOAuthIntent) {setBusy(true)setErrorClass(null)+ setBrowserOAuthBlocked(false)setUiStatus('connecting')try {const started = await startCodexBrowserConnect(intent)- window.open(started.authorizeUrl, '_blank', 'noopener,noreferrer')- showToast('Complete Codex sign-in in the browser window.', { tone: 'info' })- await loadConnection()+ window.location.assign(started.authorizeUrl)} catch (error) {if (isSilentApiError(error)) return+ if (isCodexBrowserOAuthUnavailableError(error)) {+ setBrowserOAuthBlocked(true)+ setErrorClass('browser_oauth_unregistered')+ setUiStatus(connection ? mapConnectionStatus(connection.status) : 'disconnected')+ return+ }if (error &&typeof error === 'object' &&@@ -267,7 +310,7 @@ export function CodexSubscriptionConnection() {<CreateFlowPanelheader={<CreatePageHeader- icon={<IconModels />}+ icon={<CodexHeaderIcon />}title="Codex subscription"subtitle="This provider is not enabled on the control plane."backLabel="Back to models"@@ -286,107 +329,153 @@ export function CodexSubscriptionConnection() {<CreateFlowPanelheader={<CreatePageHeader- icon={<IconModels />}+ icon={<CodexHeaderIcon />}title="Codex subscription"- subtitle="Connect a broker-backed Codex catalog without storing tokens in the browser."+ subtitle="Connect OpenAI Codex through the OAuth broker without storing tokens in the browser."backLabel="Back to models"onBack={backToModels}backDisabled={busy}/>}>- <div className="cu-llm-models-layout">- <p data-testid="codex-connection-status">Status: {statusLabel(uiStatus)}</p>- {connection ? (- <dl>- <div>- <dt>Fingerprint</dt>- <dd data-testid="codex-fingerprint">{fingerprint}</dd>+ <div className="cu-create-content cu-px-form cu-codex-subscription-panel">+ <FormSection+ title="Connection"+ description="Authorize OpenAI Codex once for this deployment. Tokens stay on the control plane."+ >+ <div className="cu-codex-subscription-panel__status-row">+ <span className="cu-settings-row__label">Status</span>+ <span className={statusTagClass(uiStatus)} data-testid="codex-connection-status">+ {statusLabel(uiStatus)}+ </span>+ </div>++ {connection ? (+ <div className="cu-settings-list">+ <ConnectionDetailRow+ label="Account fingerprint"+ value={fingerprint}+ testId="codex-fingerprint"+ />+ <ConnectionDetailRow+ label="Credential revision"+ value={connection.credentialRevision}+ />+ <ConnectionDetailRow label="Catalog revision" value={connection.catalogRevision} />+ <ConnectionDetailRow label="Catalog status" value={connection.catalogStatus} /></div>- <div>- <dt>Credential revision</dt>- <dd>{connection.credentialRevision}</dd>+ ) : null}++ {deviceUserCode ? (+ <div+ className="cu-banner cu-banner--info"+ role="status"+ data-testid="codex-device-code"+ >+ Enter device code <strong>{deviceUserCode}</strong>+ {deviceVerificationUri ? (+ <>+ {' '}+ at{' '}+ <a href={deviceVerificationUri} target="_blank" rel="noopener noreferrer">+ {deviceVerificationUri}+ </a>+ </>+ ) : null}</div>- <div>- <dt>Catalog revision</dt>- <dd>{connection.catalogRevision}</dd>+ ) : null}++ {syncSummary ? (+ <div className="cu-banner cu-banner--ok" role="status" data-testid="codex-sync-summary">+ {syncSummary}</div>- <div>- <dt>Catalog</dt>- <dd>{connection.catalogStatus}</dd>+ ) : null}++ {errorClass ? (+ <div className="cu-banner cu-banner--error" role="alert">+ Connection failed ({errorClass}).</div>- </dl>- ) : null}- {deviceUserCode ? (- <p data-testid="codex-device-code">- Enter device code {deviceUserCode}- {deviceVerificationUri ? ` at ${deviceVerificationUri}` : ''}- </p>- ) : null}- {syncSummary ? <p data-testid="codex-sync-summary">{syncSummary}</p> : null}- {errorClass ? (- <div className="cu-banner cu-banner--error" role="alert">- Connection failed ({errorClass}).+ ) : null}++ {browserOAuthBlocked ? (+ <div+ className="cu-banner cu-banner--info"+ role="status"+ data-testid="codex-browser-oauth-blocked"+ >+ Browser sign-in needs a deployment-registered OpenAI OAuth client for this+ cluster's control-ui callback URL. Use device code to connect with the default+ Codex client.+ </div>+ ) : null}++ <div className="cu-form-inline">+ <Button+ variant="primary"+ size="sm"+ disabled={busy}+ onClick={() => void startBrowser('connect')}+ >+ Connect in browser+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy}+ onClick={() => void startDevice('connect')}+ >+ Use device code+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || !connection}+ onClick={() => void startBrowser('reconnect')}+ >+ Reconnect+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || !connection}+ onClick={() => void handleReplace()}+ >+ Replace account+ </Button></div>- ) : null}- <div>- <button- type="button"- className="cu-btn cu-btn--primary cu-btn--sm"- disabled={busy}- onClick={() => void startBrowser('connect')}- >- Connect in browser- </button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- disabled={busy}- onClick={() => void startDevice('connect')}- >- Use device code- </button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- disabled={busy || !connection}- onClick={() => void startBrowser('reconnect')}- >- Reconnect- </button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- disabled={busy || !connection}- onClick={() => void handleReplace()}- >- Replace account- </button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- disabled={busy || uiStatus !== 'connected'}- onClick={() => void handleSync()}- >- Sync catalog- </button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- disabled={busy || uiStatus !== 'connected'}- onClick={() => void handleTest()}- >- Test connection- </button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- disabled={busy || uiStatus === 'disconnected'}- onClick={() => void handleRevoke()}- >- Revoke- </button>- </div>+ </FormSection>++ <FormSection+ title="Catalog and health"+ description="Sync discovered models into the allowlist and verify the broker grant."+ >+ <div className="cu-form-inline">+ <Button+ size="sm"+ variant="primary"+ disabled={busy || uiStatus !== 'connected'}+ onClick={() => void handleSync()}+ >+ Sync catalog+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || uiStatus !== 'connected'}+ onClick={() => void handleTest()}+ >+ Test connection+ </Button>+ <Button+ size="sm"+ variant="danger"+ disabled={busy || uiStatus === 'disconnected'}+ onClick={() => void handleRevoke()}+ >+ Revoke+ </Button>+ </div>+ </FormSection></div>{confirmDialog}</CreateFlowPanel>diff --git a/control-ui/components/CodexSubscriptionConnection/types.ts b/control-ui/components/CodexSubscriptionConnection/types.tsindex d46ced913..05ffc1424 100644--- a/control-ui/components/CodexSubscriptionConnection/types.ts+++ b/control-ui/components/CodexSubscriptionConnection/types.ts@@ -33,3 +33,37 @@ export function mapConnectionStatus(status: CodexConnectionStatus): CodexSubscriif (status === 'revoked') return 'disconnected'return 'disconnected'}++export function statusLabel(status: CodexSubscriptionUiStatus): string {+ switch (status) {+ case 'connected':+ return 'Connected'+ case 'connecting':+ return 'Connecting'+ case 'device-pending':+ return 'Device code pending'+ case 'reauth-required':+ return 'Reauthorization required'+ case 'revoking':+ return 'Revoking'+ case 'unavailable':+ return 'Unavailable'+ default:+ return 'Disconnected'+ }+}++export function statusTagClass(status: CodexSubscriptionUiStatus): string {+ switch (status) {+ case 'connected':+ return 'cu-llm-config__block-tag'+ case 'connecting':+ case 'device-pending':+ return 'cu-llm-config__block-tag cu-llm-config__block-tag--warning'+ case 'reauth-required':+ case 'unavailable':+ return 'cu-llm-config__block-tag cu-llm-config__block-tag--danger'+ default:+ return 'cu-llm-config__block-tag cu-llm-config__block-tag--muted'+ }+}diff --git a/control-ui/components/LlmModelsSurface/CodexSubscriptionCatalogLink.tsx b/control-ui/components/LlmModelsSurface/CodexSubscriptionCatalogLink.tsxnew file mode 100644index 000000000..4f99101ad--- /dev/null+++ b/control-ui/components/LlmModelsSurface/CodexSubscriptionCatalogLink.tsx@@ -0,0 +1,38 @@+'use client'++import React from 'react'+import { LlmProviderIcon } from '@components/LlmProviderIcon'+import { IconChevronRight } from '@components/icons'+import { CONTROL_ROUTES } from '@constants/routes'++/**+ * Catalog entry for the broker-backed Codex subscription provider. Shown on the+ * LLM Models catalog tab only after Control API proves the feature flag.+ */+export function CodexSubscriptionCatalogLink() {+ return (+ <a+ href={CONTROL_ROUTES.llmModels.codexSubscription}+ className="cu-codex-subscription-entry"+ aria-label="Codex subscription"+ data-testid="codex-subscription-catalog-link"+ >+ <span className="cu-codex-subscription-entry__brand" aria-hidden="true">+ <LlmProviderIcon provider="openai" label="OpenAI" />+ <LlmProviderIcon provider="codex-subscription" label="Codex subscription" />+ </span>+ <span className="cu-codex-subscription-entry__copy">+ <span className="cu-codex-subscription-entry__title">Codex subscription</span>+ <span className="cu-codex-subscription-entry__subtitle">+ Connect OpenAI Codex through the OAuth broker — no API keys in the browser.+ </span>+ </span>+ <IconChevronRight+ className="cu-codex-subscription-entry__chevron"+ width={18}+ height={18}+ aria-hidden+ />+ </a>+ )+}diff --git a/control-ui/components/LlmModelsSurface/index.tsx b/control-ui/components/LlmModelsSurface/index.tsxindex 4e2cad86e..d9f15af83 100644--- a/control-ui/components/LlmModelsSurface/index.tsx+++ b/control-ui/components/LlmModelsSurface/index.tsx@@ -29,6 +29,7 @@ import {import { getProviderDisplayLabel } from '@lib/llm'import { buildUnpricedKeys } from '@lib/llmModelUnpriced'import { CatalogAttentionBanner } from './CatalogAttentionBanner'+import { CodexSubscriptionCatalogLink } from './CodexSubscriptionCatalogLink'import type { LlmModelsSurfaceProps, LlmModelsTab } from './types'const CONFIGMAP_DEFERRED_WARNING =@@ -185,11 +186,7 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {{activeTab === 'catalog' ? (<CatalogAttentionBanner refreshSignal={attentionRefreshKey} />) : null}- {activeTab === 'catalog' && codexEnabled ? (- <p>- <a href={CONTROL_ROUTES.llmModels.codexSubscription}>Codex subscription</a>- </p>- ) : null}+ {activeTab === 'catalog' && codexEnabled ? <CodexSubscriptionCatalogLink /> : null}{activeTab === 'catalog' ? (<LlmModelTableitems={models}diff --git a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsxindex f703b18c5..fbcb2c871 100644--- a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx+++ b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx@@ -1,7 +1,11 @@import type { ReactNode } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { sanitizeCodexConnection } from '@lib/codexSubscription'+import {+ isCodexBrowserOAuthUnavailableError,+ readCodexOAuthQueryParam,+ sanitizeCodexConnection,+} from '@lib/codexSubscription'import type { CodexSubscriptionConnectionView } from '@lib/codexSubscription'import {getCodexSubscriptionConnection,@@ -16,9 +20,13 @@ import { CodexSubscriptionConnection } from '../CodexSubscriptionConnection'import { ToastProvider } from '../Toast'const confirmMock = vi.fn()+const replaceMock = vi.fn()+let searchParams = new URLSearchParams()+const assignMock = vi.fn()vi.mock('next/navigation', () => ({- useRouter: () => ({ push: vi.fn() }),+ useRouter: () => ({ push: vi.fn(), replace: replaceMock }),+ useSearchParams: () => searchParams,}))vi.mock('@components/ConfirmDialog', () => ({@@ -69,13 +77,26 @@ function renderSurface() {)}+function browserOAuthUnavailableError() {+ const error = new Error('400 Bad Request - browser_oauth_unregistered') as Error & {+ code?: string+ status?: number+ }+ error.code = 'browser_oauth_unregistered'+ error.status = 400+ return error+}+describe('CodexSubscriptionConnection', () => {beforeEach(() => {confirmMock.mockReset()+ replaceMock.mockReset()+ assignMock.mockReset()+ searchParams = new URLSearchParams()confirmMock.mockResolvedValue(true)vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: true })vi.mocked(getCodexSubscriptionConnection).mockResolvedValue(connected)- vi.stubGlobal('open', vi.fn())+ vi.stubGlobal('location', { assign: assignMock })})afterEach(() => {@@ -117,7 +138,7 @@ describe('CodexSubscriptionConnection', () => {expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent(label)})- it('starts a browser connect without rendering secrets', async () => {+ it('starts a browser connect in the same tab without rendering secrets', async () => {vi.mocked(startCodexBrowserConnect).mockResolvedValue({authorizeUrl: 'https://auth.openai.com/oauth/authorize?state=abc',state: 'abc',@@ -129,14 +150,28 @@ describe('CodexSubscriptionConnection', () => {await waitFor(() => {expect(startCodexBrowserConnect).toHaveBeenCalledWith('connect')})- expect(window.open).toHaveBeenCalledWith(- 'https://auth.openai.com/oauth/authorize?state=abc',- '_blank',- 'noopener,noreferrer'- )+ expect(assignMock).toHaveBeenCalledWith('https://auth.openai.com/oauth/authorize?state=abc')expect(document.body.textContent).not.toMatch(/sk-|deviceCode|accessToken/i)})+ it('shows a device-code fallback banner when browser OAuth is unregistered', async () => {+ vi.mocked(startCodexBrowserConnect).mockRejectedValue(browserOAuthUnavailableError())+ renderSurface()+ fireEvent.click(await screen.findByRole('button', { name: 'Connect in browser' }))+ expect(await screen.findByTestId('codex-browser-oauth-blocked')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Use device code' })).toBeVisible()+ expect(assignMock).not.toHaveBeenCalled()+ })++ it('reloads connection after a successful browser callback query param', async () => {+ searchParams = new URLSearchParams('codex_oauth=connected')+ renderSurface()+ await waitFor(() => {+ expect(replaceMock).toHaveBeenCalledWith('/llm-models/providers/codex-subscription')+ })+ expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Connected')+ })+it('shows device-code progress without the secret device code', async () => {vi.mocked(startCodexDeviceConnect).mockResolvedValue({userCode: 'ABCD-EFGH',@@ -219,3 +254,13 @@ describe('CodexSubscriptionConnection', () => {expect(document.body.textContent).not.toContain('accessToken')})})++describe('codex subscription query helpers', () => {+ it('reads the oauth callback query param', () => {+ expect(readCodexOAuthQueryParam(new URLSearchParams('codex_oauth=connected'))).toBe('connected')+ })++ it('detects browser oauth unregistered API errors', () => {+ expect(isCodexBrowserOAuthUnavailableError(browserOAuthUnavailableError())).toBe(true)+ })+})diff --git a/control-ui/components/__tests__/LlmModelsSurface.test.tsx b/control-ui/components/__tests__/LlmModelsSurface.test.tsxindex d85299092..d4e5190b3 100644--- a/control-ui/components/__tests__/LlmModelsSurface.test.tsx+++ b/control-ui/components/__tests__/LlmModelsSurface.test.tsx@@ -97,9 +97,8 @@ describe('LlmModelsSurface', () => {</ToastProvider>)- expect(await screen.findByRole('link', { name: 'Codex subscription' })).toHaveAttribute(- 'href',- '/llm-models/providers/codex-subscription'- )+ const link = await screen.findByRole('link', { name: 'Codex subscription' })+ expect(link).toHaveAttribute('href', '/llm-models/providers/codex-subscription')+ expect(screen.getByTestId('codex-subscription-catalog-link')).toBeInTheDocument()})})diff --git a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts b/control-ui/lib/__tests__/controlApiProxyRoute.test.tsindex 592a1ad4b..14ddb8e63 100644--- a/control-ui/lib/__tests__/controlApiProxyRoute.test.ts+++ b/control-ui/lib/__tests__/controlApiProxyRoute.test.ts@@ -35,6 +35,8 @@ describe('control-ui control-api proxy route', () => {expect(init.method).toBe('POST')expect(init.headers.get('authorization')).toBe('Bearer test-token')expect(init.headers.get('x-trace')).toBe('abc123')+ expect(init.headers.get('x-forwarded-host')).toBe('localhost:3000')+ expect(init.headers.get('x-forwarded-proto')).toBe('http')expect(init.headers.has('host')).toBe(false)expect(init.headers.has('content-length')).toBe(false)expect(init.signal).toBeDefined()diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.tsindex c6e0d6251..78991d813 100644--- a/control-ui/lib/codexSubscription.ts+++ b/control-ui/lib/codexSubscription.ts@@ -234,3 +234,21 @@ export async function syncCodexSubscriptionCatalog(): Promise<CodexCatalogSyncViexport async function revokeCodexSubscription(): Promise<CodexSubscriptionConnectionView> {return sanitizeCodexConnection(await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/revoke`))}++const CODEX_OAUTH_QUERY_PARAM = 'codex_oauth'++export function readCodexOAuthQueryParam(+ searchParams: URLSearchParams | null | undefined+): string | null {+ if (!searchParams) return null+ const value = searchParams.get(CODEX_OAUTH_QUERY_PARAM)+ return value && value.trim() ? value.trim() : null+}++export function isCodexBrowserOAuthUnavailableError(error: unknown): boolean {+ return (+ Boolean(error) &&+ typeof error === 'object' &&+ (error as { code?: unknown }).code === 'browser_oauth_unregistered'+ )+}diff --git a/control-ui/public/provider-icons/codex-subscription.svg b/control-ui/public/provider-icons/codex-subscription.svgnew file mode 100644index 000000000..aa82b3bd0--- /dev/null+++ b/control-ui/public/provider-icons/codex-subscription.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img" aria-hidden="true">+ <path+ fill="#ffffff"+ d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9106 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.747-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3748v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3656-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"+ />+</svg>diff --git a/control-ui/public/provider-icons/openai.svg b/control-ui/public/provider-icons/openai.svgindex 67e79e275..aa82b3bd0 100644--- a/control-ui/public/provider-icons/openai.svg+++ b/control-ui/public/provider-icons/openai.svg@@ -1 +1,6 @@-<svg xmlns="http://www.w3.org/2000/svg" width="800" height="800" fill="#fff" viewBox="0 0 24 24"><path fill="#ffffff000" d="M22.282 9.821a6 6 0 0 0-.516-4.91 6.05 6.05 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a6 6 0 0 0-3.998 2.9 6.05 6.05 0 0 0 .743 7.097 5.98 5.98 0 0 0 .51 4.911 6.05 6.05 0 0 0 6.515 2.9A6 6 0 0 0 13.26 24a6.06 6.06 0 0 0 5.772-4.206 6 6 0 0 0 3.997-2.9 6.06 6.06 0 0 0-.747-7.073M13.26 22.43a4.48 4.48 0 0 1-2.876-1.04l.141-.081 4.779-2.758a.8.8 0 0 0 .392-.681v-6.737l2.02 1.168a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085 4.783 2.759a.77.77 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646M2.34 7.896a4.5 4.5 0 0 1 2.366-1.973V11.6a.77.77 0 0 0 .388.677l5.815 3.354-2.02 1.168a.08.08 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855-5.833-3.387L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667m2.01-3.023-.141-.085-4.774-2.782a.78.78 0 0 0-.785 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.8.8 0 0 0-.393.681zm1.097-2.365 2.602-1.5 2.607 1.5v2.999l-2.597 1.5-2.607-1.5Z"/></svg>\ No newline at end of file+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="img" aria-hidden="true">+ <path+ fill="#ffffff"+ d="M22.2819 9.8211a5.9847 5.9847 0 0 0-.5157-4.9106 6.0462 6.0462 0 0 0-6.5098-2.9A6.0651 6.0651 0 0 0 4.9807 4.1818a5.9847 5.9847 0 0 0-3.9977 2.9 6.0462 6.0462 0 0 0 .7427 7.0966 5.98 5.98 0 0 0 .511 4.9107 6.051 6.051 0 0 0 6.5146 2.9001A5.9847 5.9847 0 0 0 13.2599 24a6.0557 6.0557 0 0 0 5.7718-4.2058 5.9894 5.9894 0 0 0 3.9977-2.9001 6.0557 6.0557 0 0 0-.747-7.0729zm-9.022 12.6081a4.4755 4.4755 0 0 1-2.8764-1.0408l.1419-.0804 4.7783-2.7582a.7948.7948 0 0 0 .3927-.6813v-6.7369l2.02 1.1686a.071.071 0 0 1 .038.052v5.5826a4.504 4.504 0 0 1-4.4945 4.4944zm-9.6607-4.1254a4.4708 4.4708 0 0 1-.5346-3.0137l.142.0852 4.783 2.7582a.7712.7712 0 0 0 .7806 0l5.8428-3.3748v2.3324a.0804.0804 0 0 1-.0332.0615L9.74 19.9502a4.4992 4.4992 0 0 1-6.1408-1.6464zM2.3408 7.8956a4.485 4.485 0 0 1 2.3656-1.9728V11.6a.7664.7664 0 0 0 .3879.6765l5.8144 3.3543-2.0201 1.1685a.0757.0757 0 0 1-.071 0l-4.8303-2.7865A4.504 4.504 0 0 1 2.3408 7.872zm16.5963 3.8558L13.1038 8.364 15.1192 7.2a.0757.0757 0 0 1 .071 0l4.8303 2.7913a4.4944 4.4944 0 0 1-.6765 8.1042v-5.6772a.79.79 0 0 0-.407-.667zm2.0107-3.0231l-.142-.0852-4.7735-2.7818a.7759.7759 0 0 0-.7854 0L9.409 9.2297V6.8974a.0662.0662 0 0 1 .0284-.0615l4.8303-2.7866a4.4992 4.4992 0 0 1 6.6802 4.66zM8.3065 12.863l-2.02-1.1638a.0804.0804 0 0 1-.038-.0567V6.0742a4.4992 4.4992 0 0 1 7.3757-3.4537l-.142.0805L8.704 5.459a.7948.7948 0 0 0-.3927.6813zm1.0976-2.3654l2.602-1.4998 2.6069 1.4998v2.9994l-2.5974 1.4997-2.6067-1.4997Z"+ />+</svg>diff --git a/deploy/overlays/minikube/configmaps/control-api-config.yaml b/deploy/overlays/minikube/configmaps/control-api-config.yamlindex e9b7c1b47..7668ecdae 100644--- a/deploy/overlays/minikube/configmaps/control-api-config.yaml+++ b/deploy/overlays/minikube/configmaps/control-api-config.yaml@@ -35,6 +35,9 @@ data:# Self-hosted-only GFS operator parity. Managed/base deployments remain# fail-closed because this narrow elevation flag is absent there.CONTROL_API_DESKTOP_GFS_OPERATOR_LINKING_ENABLED: 'true'+ # Branch profiles use profile-owned random port-forwards; run+ # `make minikube-sync-codex-subscription-url` after pf-all-stack to align+ # Codex subscription browser OAuth redirect_uri with the live Control UI origin.CONTROL_API_CONTROL_UI_BASE_URL: 'http://127.0.0.1:3000'CONTROL_API_CONTROL_UI_APP_NAME: 'Evenfire'CONTROL_API_POLICY_AUTH_AUDIENCE: 'control-api'@@ -101,3 +104,8 @@ data:CLERUM_ATTACHMENT_MAX_BYTES: '52428800'CONTROL_API_CODEX_SUBSCRIPTION_ENABLED: 'true'CODEX_LLM_PROXY_EXECUTION_ENABLED: 'true'+ # Codex browser OAuth redirect_uri derives from this control-ui origin plus+ # /control-api/api/v1/auth/codex-subscription/callback. Loopback profiles may+ # override via the browser Origin header when both sides are 127.0.0.1/localhost.+ # Browser connect requires CONTROL_API_CODEX_OAUTH_CLIENT_ID registered with OpenAI+ # for that exact callback URL; the default CLI client supports device code only.diff --git a/scripts/e2e/e2e-codex-subscription-playwright.sh b/scripts/e2e/e2e-codex-subscription-playwright.shindex 7a485a567..dc693e7e8 100755--- a/scripts/e2e/e2e-codex-subscription-playwright.sh+++ b/scripts/e2e/e2e-codex-subscription-playwright.sh@@ -63,6 +63,9 @@ load_branch_profile_ports() {urls_preconfigured=truefiif [[ "${ctx}" =~ ^clerum-(codex|detached)- ]] || [[ "${ctx}" =~ ^clerum-.+-[0-9a-f]{7,8}$ ]]; then+ if [[ -z "${ports_env}" ]]; then+ ports_env="${HOME}/.cache/clerum/minikube-profiles/${ctx}/ports.env"+ fiif [[ -z "${ports_env}" && "${urls_preconfigured}" != "true" ]]; thendie "branch-owned context ${ctx} requires ports.env from branch-profile preflight, or explicit CONTROL_UI_URL and CONTROL_API_URL"fi@@ -72,6 +75,9 @@ load_branch_profile_ports() {if [[ -n "${ports_env}" && -f "${ports_env}" ]]; thendotenv_load_file "${ports_env}"fi+ if [[ -n "${ports_env}" ]]; then+ export CLERUM_PROFILE_PORTS_ENV="${ports_env}"+ fi}require_random_local_port_for_branch_context() {@@ -121,6 +127,14 @@ export CONTROL_API_BASE_URL="${CONTROL_API_BASE_URL:-${CONTROL_API_URL}}"require_random_local_port_for_branch_context "CONTROL_UI_URL" "${CONTROL_UI_URL}" "3000"require_random_local_port_for_branch_context "CONTROL_API_URL" "${CONTROL_API_URL}" "8090"+log "Syncing Codex subscription Control UI origin into control-api"+sync_args=(--context "${PROFILE}")+if [[ -n "${CLERUM_PROFILE_PORTS_ENV:-}" ]]; then+ sync_args+=(--ports-env "${CLERUM_PROFILE_PORTS_ENV}")+fi+"${ROOT}/scripts/minikube/sync-codex-subscription-control-ui-url.sh" "${sync_args[@]}" \+ || die "failed to sync Codex subscription Control UI URL"+if [[ "${E2E_USE_EXISTING_PORT_FORWARDS:-false}" != "true" ]]; thenlog "Starting held port-forwards (log: ${PF_LOG})""${ROOT}/scripts/minikube/pf-all-stack.sh" --hold >"${PF_LOG}" 2>&1 &diff --git a/scripts/minikube/sync-codex-subscription-control-ui-url.sh b/scripts/minikube/sync-codex-subscription-control-ui-url.shnew file mode 100755index 000000000..a414b177d--- /dev/null+++ b/scripts/minikube/sync-codex-subscription-control-ui-url.sh@@ -0,0 +1,205 @@+#!/usr/bin/env bash+# Resolve the branch-owned Control UI URL for a Minikube profile and sync+# CONTROL_API_CONTROL_UI_BASE_URL on control-api so Codex subscription browser+# OAuth builds the correct cluster-local redirect_uri.+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+ROOT="$(cd "${HERE}/../.." && pwd)"++# shellcheck source=scripts/e2e/load-dotenv.sh+source "${ROOT}/scripts/e2e/load-dotenv.sh"++PROFILE="${MINIKUBE_PROFILE:-${KUBECONTEXT:-}}"+PORTS_ENV="${CLERUM_PROFILE_PORTS_ENV:-${E2E_PROFILE_PORTS_ENV:-}}"+DRY_RUN=false+EVIDENCE_DIR="${ROOT}/.local-notes/infra/runs"+CONFIGMAP="control-api-config"+NAMESPACE="control-plane"+DEPLOYMENT="control-api"+TARGET_KEY="CONTROL_API_CONTROL_UI_BASE_URL"+CALLBACK_SUFFIX="/control-api/api/v1/auth/codex-subscription/callback"++log() {+ printf '[codex-subscription-url] %s\n' "$*"+}++die() {+ log "ERROR: $*" >&2+ exit 1+}++usage() {+ cat <<'EOF'+Usage: scripts/minikube/sync-codex-subscription-control-ui-url.sh [options]++Options:+ --context <name> Kubernetes context / Minikube profile (default: MINIKUBE_PROFILE)+ --ports-env <path> Branch profile ports.env (default: CLERUM_PROFILE_PORTS_ENV or profile cache)+ --dry-run Print the resolved URL and redirect_uri without patching the cluster+ -h, --help Show this help++Resolution order for the Control UI origin:+ 1. CONTROL_UI_URL or CONTROL_UI_BASE_URL already exported in the environment+ 2. CONTROL_UI_URL / CONTROL_UI_BASE_URL from the profile ports.env+ 3. http://127.0.0.1:${CONTROL_UI_PORT} when the port variable is present++The script patches control-api-config and restarts control-api when the value drifts.+EOF+}++while [[ $# -gt 0 ]]; do+ case "$1" in+ --context)+ PROFILE="${2:-}"+ shift 2+ ;;+ --context=*)+ PROFILE="${1#--context=}"+ shift+ ;;+ --ports-env)+ PORTS_ENV="${2:-}"+ shift 2+ ;;+ --ports-env=*)+ PORTS_ENV="${1#--ports-env=}"+ shift+ ;;+ --dry-run)+ DRY_RUN=true+ shift+ ;;+ -h|--help)+ usage+ exit 0+ ;;+ *)+ die "unknown argument: $1"+ ;;+ esac+done++[[ -n "${PROFILE}" ]] || die "MINIKUBE_PROFILE or --context is required"++if [[ -z "${PORTS_ENV}" ]]; then+ PORTS_ENV="${HOME}/.cache/clerum/minikube-profiles/${PROFILE}/ports.env"+fi++normalize_url() {+ local value="${1%/}"+ printf '%s' "${value}"+}++read_ports_env_value() {+ local key="$1"+ awk -F= -v expected_key="${key}" '$1 == expected_key { sub(/^[^=]*=/, ""); print; exit }' "${PORTS_ENV}"+}++resolve_control_ui_url() {+ local from_env="${CONTROL_UI_URL:-${CONTROL_UI_BASE_URL:-}}"+ if [[ -n "${from_env}" ]]; then+ normalize_url "${from_env}"+ return 0+ fi++ if [[ -f "${PORTS_ENV}" ]]; then+ dotenv_load_file "${PORTS_ENV}"+ from_env="${CONTROL_UI_URL:-${CONTROL_UI_BASE_URL:-}}"+ if [[ -n "${from_env}" ]]; then+ normalize_url "${from_env}"+ return 0+ fi+ if [[ -n "${CONTROL_UI_PORT:-}" ]]; then+ printf 'http://127.0.0.1:%s' "${CONTROL_UI_PORT}"+ return 0+ fi+ fi++ if [[ -n "${CONTROL_UI_PORT:-}" ]]; then+ printf 'http://127.0.0.1:%s' "${CONTROL_UI_PORT}"+ return 0+ fi++ return 1+}++validate_control_ui_url() {+ local url="$1"+ case "${url}" in+ http://127.0.0.1:[0-9]*|http://localhost:[0-9]*|https://*)+ ;;+ *)+ die "refusing non-loopback/non-https Control UI URL for Codex OAuth sync: ${url}"+ ;;+ esac+}++make_config_patch() {+ CONTROL_UI_ORIGIN="$1" TARGET_KEY="$2" python3 - <<'PY'+import json+import os++print(json.dumps({"data": {os.environ["TARGET_KEY"]: os.environ["CONTROL_UI_ORIGIN"]}}))+PY+}++write_local_env_file() {+ local control_ui_url="$1"+ local redirect_uri="$2"+ local safe_profile="${PROFILE//[^A-Za-z0-9_.-]/_}"+ local env_file="${EVIDENCE_DIR}/codex-subscription-${safe_profile}.env"++ mkdir -p "${EVIDENCE_DIR}"+ cat >"${env_file}" <<EOF+# Generated by scripts/minikube/sync-codex-subscription-control-ui-url.sh+# Profile: ${PROFILE}+CONTROL_UI_URL=${control_ui_url}+CONTROL_UI_BASE_URL=${control_ui_url}+CONTROL_API_CONTROL_UI_BASE_URL=${control_ui_url}+CODEX_BROWSER_REDIRECT_URI=${redirect_uri}+EOF+ log "Wrote local env evidence: ${env_file}"+}++if ! CONTROL_UI_URL="$(resolve_control_ui_url)"; then+ die "could not resolve Control UI URL; export CONTROL_UI_URL or provide ${PORTS_ENV}"+fi++validate_control_ui_url "${CONTROL_UI_URL}"+CODEX_BROWSER_REDIRECT_URI="${CONTROL_UI_URL}${CALLBACK_SUFFIX}"++log "Profile: ${PROFILE}"+log "Control UI origin: ${CONTROL_UI_URL}"+log "Codex browser redirect_uri: ${CODEX_BROWSER_REDIRECT_URI}"++write_local_env_file "${CONTROL_UI_URL}" "${CODEX_BROWSER_REDIRECT_URI}"++if [[ "${DRY_RUN}" == "true" ]]; then+ log "Dry run complete; cluster unchanged"+ exit 0+fi++KCTL=(kubectl --context="${PROFILE}")++if ! "${KCTL[@]}" get configmap "${CONFIGMAP}" -n "${NAMESPACE}" >/dev/null 2>&1; then+ die "missing ${NAMESPACE}/${CONFIGMAP}; deploy the minikube overlay first"+fi++current_value="$("${KCTL[@]}" get configmap "${CONFIGMAP}" -n "${NAMESPACE}" -o "jsonpath={.data.${TARGET_KEY}}" 2>/dev/null || true)"+if [[ "${current_value}" == "${CONTROL_UI_URL}" ]]; then+ log "${CONFIGMAP}.${TARGET_KEY} already matches ${CONTROL_UI_URL}"+ exit 0+fi++log "Patching ${NAMESPACE}/${CONFIGMAP}.${TARGET_KEY}"+"${KCTL[@]}" patch configmap "${CONFIGMAP}" -n "${NAMESPACE}" --type=merge \+ -p "$(make_config_patch "${CONTROL_UI_URL}" "${TARGET_KEY}")" >/dev/null++if "${KCTL[@]}" get "deployment/${DEPLOYMENT}" -n "${NAMESPACE}" >/dev/null 2>&1; then+ log "Restarting ${NAMESPACE}/${DEPLOYMENT} to pick up Codex OAuth callback origin"+ "${KCTL[@]}" rollout restart "deployment/${DEPLOYMENT}" -n "${NAMESPACE}" >/dev/null+ "${KCTL[@]}" rollout status "deployment/${DEPLOYMENT}" -n "${NAMESPACE}" --timeout=180s+fi++log "Codex subscription Control UI origin synced"diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.shindex c8b1194a8..bdd90aa1b 100755--- a/scripts/tests/test-codex-subscription-t0.sh+++ b/scripts/tests/test-codex-subscription-t0.sh@@ -153,6 +153,9 @@ require_ci_matrix_entry "packages/llm-provider-attempt-contract"run_group "shared-contract" "packages/llm-provider-attempt-contract" "index.test.cjs"run_group "control-api" "control-api" \+ "test/codexSubscriptionRedirectUri.test.ts" \+ "test/routes.admin.codexSubscription.test.ts" \+ "test/routes.auth.codexSubscriptionCallback.test.ts" \"test/llmProviders.test.ts" \"test/services.codexSubscriptionOAuth.test.ts" \"test/services.codexSubscriptionCatalog.test.ts" \diff --git a/scripts/tests/test-minikube-makefile.sh b/scripts/tests/test-minikube-makefile.shindex 3bd772e6c..610d644a0 100755--- a/scripts/tests/test-minikube-makefile.sh+++ b/scripts/tests/test-minikube-makefile.sh@@ -87,6 +87,8 @@ assert_contains minikube-deploy-all-body "minikube-sync-auth-key"assert_contains minikube-sync-auth-key "with-t2-mutation-lock.sh"assert_contains minikube-sync-auth-key-body "--context=clerum-test"assert_contains minikube-sync-auth-key-body "scripts/minikube/sync-auth-key.sh"+assert_succeeds_dry minikube-sync-codex-subscription-url+assert_contains minikube-sync-codex-subscription-url "scripts/minikube/sync-codex-subscription-control-ui-url.sh"assert_contains minikube-verify-networkpolicies "verify-networkpolicies.sh --overlay minikube"assert_contains minikube-sync-auth-key-if-present "rpc-proxy-secrets"assert_file_contains Makefile "T2_MUTATION_LOCK_WRAPPED"diff --git a/scripts/tests/test-minikube-sync-codex-subscription-control-ui-url.sh b/scripts/tests/test-minikube-sync-codex-subscription-control-ui-url.shnew file mode 100755index 000000000..ab59fdbed--- /dev/null+++ b/scripts/tests/test-minikube-sync-codex-subscription-control-ui-url.sh@@ -0,0 +1,133 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/../.." && pwd)"+TMP_DIR="$(mktemp -d)"+trap 'rm -rf "${TMP_DIR}"' EXIT++STATE_DIR="${TMP_DIR}/state"+LOG_FILE="${TMP_DIR}/kubectl.log"+OUT_FILE="${TMP_DIR}/sync.out"+mkdir -p "${STATE_DIR}"++cat >"${TMP_DIR}/kubectl" <<'SH'+#!/usr/bin/env bash+set -euo pipefail++while [[ "${1:-}" == --context* ]]; do+ if [[ "${1}" == "--context" ]]; then+ shift 2+ else+ shift+ fi+done++printf '%s\n' "$*" >>"${TEST_KUBECTL_LOG}"++if [[ "${1:-}" == "get" && "${2:-}" == "configmap" && "${3:-}" == "control-api-config" ]]; then+ if printf '%s\n' "$@" | grep -q 'jsonpath='; then+ printf '%s' "${TEST_CURRENT_CONTROL_UI_URL:-http://127.0.0.1:3000}"+ fi+ exit 0+fi++if [[ "${1:-}" == "patch" && "${2:-}" == "configmap" && "${3:-}" == "control-api-config" ]]; then+ next_is_patch=false+ for arg in "$@"; do+ if [[ "${next_is_patch}" == "true" ]]; then+ printf '%s' "${arg}" >"${TEST_STATE_DIR}/last-patch.json"+ exit 0+ fi+ if [[ "${arg}" == "-p" ]]; then+ next_is_patch=true+ elif [[ "${arg}" == -p=* ]]; then+ printf '%s' "${arg#-p=}" >"${TEST_STATE_DIR}/last-patch.json"+ exit 0+ fi+ done+ exit 0+fi++if [[ "${1:-}" == "get" && "${2:-}" == "deployment/control-api" ]]; then+ exit 0+fi++if [[ "${1:-}" == "rollout" && "${2:-}" == "restart" && "${3:-}" == "deployment/control-api" ]]; then+ printf '1' >"${TEST_STATE_DIR}/restarted"+ exit 0+fi++if [[ "${1:-}" == "rollout" && "${2:-}" == "status" ]]; then+ exit 0+fi++echo "unexpected kubectl: $*" >&2+exit 99+SH+chmod +x "${TMP_DIR}/kubectl"++PORTS_ENV="${TMP_DIR}/ports.env"+cat >"${PORTS_ENV}" <<'EOF'+CONTROL_UI_URL=http://127.0.0.1:36148+CONTROL_API_URL=http://127.0.0.1:36238+EOF++export TEST_KUBECTL_LOG="${LOG_FILE}"+export TEST_STATE_DIR="${STATE_DIR}"+export TEST_CURRENT_CONTROL_UI_URL='http://127.0.0.1:3000'+export PATH="${TMP_DIR}:${PATH}"++if ! PATH="${TMP_DIR}:${PATH}" bash "${ROOT}/scripts/minikube/sync-codex-subscription-control-ui-url.sh" \+ --context 'clerum-feat-codex-deadbeef' \+ --ports-env "${PORTS_ENV}" >"${OUT_FILE}" 2>&1; then+ echo 'FAIL: sync script exited non-zero' >&2+ cat "${OUT_FILE}" >&2+ exit 1+fi++grep -Fq 'Control UI origin: http://127.0.0.1:36148' "${OUT_FILE}" || {+ echo 'FAIL: resolved URL missing from output' >&2+ cat "${OUT_FILE}" >&2+ exit 1+}++grep -Fq '/control-api/api/v1/auth/codex-subscription/callback' "${OUT_FILE}" || {+ echo 'FAIL: redirect_uri missing from output' >&2+ cat "${OUT_FILE}" >&2+ exit 1+}++[[ -f "${STATE_DIR}/last-patch.json" ]] || {+ echo 'FAIL: expected configmap patch' >&2+ exit 1+}++grep -Fq 'CONTROL_API_CONTROL_UI_BASE_URL' "${STATE_DIR}/last-patch.json" || {+ echo 'FAIL: patch missing target key' >&2+ cat "${STATE_DIR}/last-patch.json" >&2+ exit 1+}++[[ -f "${STATE_DIR}/restarted" ]] || {+ echo 'FAIL: expected control-api rollout restart' >&2+ exit 1+}++if PATH="${TMP_DIR}:${PATH}" bash "${ROOT}/scripts/minikube/sync-codex-subscription-control-ui-url.sh" \+ --context 'clerum-feat-codex-deadbeef' \+ --ports-env "${PORTS_ENV}" \+ --dry-run >"${TMP_DIR}/dry-run.out" 2>&1; then+ :+else+ echo 'FAIL: dry-run exited non-zero' >&2+ cat "${TMP_DIR}/dry-run.out" >&2+ exit 1+fi++grep -Fq 'Dry run complete' "${TMP_DIR}/dry-run.out" || {+ echo 'FAIL: dry-run banner missing' >&2+ cat "${TMP_DIR}/dry-run.out" >&2+ exit 1+}++echo 'PASS: sync-codex-subscription-control-ui-url resolves profile URL and patches control-api'diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.tsindex 686f835d1..cf0e796f8 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts@@ -39,4 +39,28 @@ test.describe('Codex subscription connection', () => {await expect(page.getByRole('button', { name: 'Use device code' })).toBeVisible()await expect(page.getByText(/sk-|access token|account id/i)).toHaveCount(0)})++ test('browser connect fails loud with the default CLI client and keeps device code available', async ({+ page,+ }) => {+ await page.goto('/')+ await loginControlUiVisible(page)+ await page.getByRole('link', { name: 'LLM Models' }).click()+ await page.getByRole('link', { name: 'Codex subscription' }).click()+ await expect(page).toHaveURL(/\/llm-models\/providers\/codex-subscription/)++ const browserStart = page.waitForResponse(+ response =>+ response.url().includes('/api/v1/admin/llm/providers/codex-subscription/browser/start') &&+ response.request().method() === 'POST'+ )+ await page.getByRole('button', { name: 'Connect in browser' }).click()+ const response = await browserStart+ expect(response.status(), 'default CLI client must not open browser OAuth').toBe(400)+ const body = (await response.json()) as { error?: string }+ expect(body.error).toBe('browser_oauth_unregistered')+ await expect(page.getByTestId('codex-browser-oauth-blocked')).toBeVisible()+ await expect(page.getByRole('button', { name: 'Use device code' })).toBeVisible()+ await expect(page).not.toHaveURL(/auth\.openai\.com/)+ })})diff --git a/tests/e2e/playwright/control-ui/codex-subscription-workflow-recipe.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-workflow-recipe.spec.tsindex 5abf81c19..3438c6a12 100644--- a/tests/e2e/playwright/control-ui/codex-subscription-workflow-recipe.spec.ts+++ b/tests/e2e/playwright/control-ui/codex-subscription-workflow-recipe.spec.ts@@ -85,15 +85,19 @@ test.describe('Codex subscription workflow recipe authoring', () => {await page.goto('/')await loginControlUiVisible(page)- await page.getByRole('link', { name: 'Installed plugins' }).click()- await expect(page).toHaveURL(/\/plugins/)-const listRecipes = page.waitForResponse(response =>- response.url().includes('/api/v1/admin/recipes') && response.request().method() === 'GET'+ response.url().includes('/api/v1/admin/recipes') && response.request().method() === 'GET',+ { timeout: 20_000 })+ await page.getByRole('link', { name: 'Installed plugins' }).click()+ await expect(page).toHaveURL(/\/plugins/)+ const recipesResponse = await listRecipes+ expect(+ recipesResponse.ok(),+ `recipe list must succeed, got ${recipesResponse.status()}`+ ).toBe(true)await expect(page.getByLabel('Search plugins')).toBeVisible({ timeout: 20_000 })- await listRecipesawait page.getByLabel('Search plugins').fill(recipeName)const recipeLink = page.getByRole('link', { name: new RegExp(`Open ${recipeName}`, 'i') })diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.jsonindex fe1b86930..7dfdb1655 100644--- a/tests/e2e/playwright/package-lock.json+++ b/tests/e2e/playwright/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-playwright-tests",- "version": "0.1.25",+ "version": "0.1.26","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.25",+ "version": "0.1.26","devDependencies": {"@playwright/test": "^1.50.0","@types/node": "^22.0.0"diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.jsonindex c818479fa..cf4da438d 100644--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@ -1,6 +1,6 @@{"name": "clerum-playwright-tests",- "version": "0.1.25",+ "version": "0.1.26","private": true,"description": "Playwright E2E tests for Control UI and Desktop App","scripts": {