Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(codex): close Claude/review-pr gaps Claude called optional
Alfredo Lopez0f3515432c5b
diff --git a/codex-llm-proxy/package-lock.json b/codex-llm-proxy/package-lock.jsonindex 76fa8ff7f..335de08e4 100644--- a/codex-llm-proxy/package-lock.json+++ b/codex-llm-proxy/package-lock.json@@ -11,6 +11,7 @@"dependencies": {"@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract","express": "^4.21.2",+ "express-rate-limit": "^8.6.2","jsonwebtoken": "^9.0.2","pino": "^10.3.1","prom-client": "^15.1.3",@@ -1132,6 +1133,48 @@"url": "https://opencollective.com/express"}},+ "node_modules/express-rate-limit": {+ "version": "8.6.2",+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.6.2.tgz",+ "integrity": "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A==",+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3",+ "ip-address": "^10.2.0"+ },+ "engines": {+ "node": ">= 16"+ },+ "funding": {+ "url": "https://github.com/sponsors/express-rate-limit"+ },+ "peerDependencies": {+ "express": ">= 4.11"+ }+ },+ "node_modules/express-rate-limit/node_modules/debug": {+ "version": "4.4.3",+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/express-rate-limit/node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "license": "MIT"+ },"node_modules/fast-safe-stringify": {"version": "2.1.1","resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",@@ -1379,6 +1422,15 @@"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==","license": "ISC"},+ "node_modules/ip-address": {+ "version": "10.5.0",+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",+ "integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==",+ "license": "MIT",+ "engines": {+ "node": ">= 12"+ }+ },"node_modules/ipaddr.js": {"version": "1.9.1","resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",diff --git a/codex-llm-proxy/package.json b/codex-llm-proxy/package.jsonindex 2651b2c2d..03eaa4074 100644--- a/codex-llm-proxy/package.json+++ b/codex-llm-proxy/package.json@@ -17,6 +17,7 @@"dependencies": {"@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract","express": "^4.21.2",+ "express-rate-limit": "^8.6.2","jsonwebtoken": "^9.0.2","pino": "^10.3.1","prom-client": "^15.1.3",diff --git a/codex-llm-proxy/src/logger.ts b/codex-llm-proxy/src/logger.tsindex 2b50e4035..0191fd1be 100644--- a/codex-llm-proxy/src/logger.ts+++ b/codex-llm-proxy/src/logger.ts@@ -1,6 +1,6 @@-import pino from 'pino'+import pino, { type DestinationStream } from 'pino'-const REDACT_PATHS = [+export const REDACT_PATHS = ['accessToken','refreshToken','executionTicket',@@ -10,9 +10,18 @@ const REDACT_PATHS = ['attemptReceipt',]-export const logger = pino({- level: process.env.LOG_LEVEL ?? (process.env.NODE_ENV === 'test' ? 'silent' : 'info'),- base: { svc: 'codex-llm-proxy' },- timestamp: pino.stdTimeFunctions.isoTime,- redact: { paths: REDACT_PATHS, remove: true },-})+export function createProxyLogger(destination?: DestinationStream) {+ return pino(+ {+ level: destination+ ? 'info'+ : (process.env.LOG_LEVEL ?? (process.env.NODE_ENV === 'test' ? 'silent' : 'info')),+ base: { svc: 'codex-llm-proxy' },+ timestamp: pino.stdTimeFunctions.isoTime,+ redact: { paths: REDACT_PATHS, remove: true },+ },+ destination+ )+}++export const logger = createProxyLogger()diff --git a/codex-llm-proxy/src/originPolicy.ts b/codex-llm-proxy/src/originPolicy.tsindex c53de137b..aeb735990 100644--- a/codex-llm-proxy/src/originPolicy.ts+++ b/codex-llm-proxy/src/originPolicy.ts@@ -46,11 +46,18 @@ export function assertAllowedUpstreamUrl(raw: string, kind: UpstreamKind): URL {return parsed}+export async function defaultAddressLookup(+ hostname: string+): Promise<Array<{ address: string; family: number }>> {+ const { lookup } = await import('node:dns/promises')+ const records = await lookup(hostname, { all: true })+ return records.map(record => ({ address: record.address, family: record.family }))+}+export async function assertResolvedUpstream(url: URL,- lookup: OriginPolicyOptions['lookup']+ lookup: OriginPolicyOptions['lookup'] = defaultAddressLookup): Promise<void> {- if (!lookup) returnconst records = await lookup(url.hostname)if (!records.length) throw new OriginDeniedError('origin_denied')for (const record of records) {@@ -68,7 +75,7 @@ export async function fetchFrozenOrigin(input: {fetchFn: typeof fetchlookup?: OriginPolicyOptions['lookup']}): Promise<Response> {- await assertResolvedUpstream(input.url, input.lookup)+ await assertResolvedUpstream(input.url, input.lookup ?? defaultAddressLookup)const init: RequestInit = { ...input.init, redirect: 'manual' }const first = await input.fetchFn(input.url.href, init)if (first.status < 300 || first.status >= 400) return firstdiff --git a/codex-llm-proxy/src/server.ts b/codex-llm-proxy/src/server.tsindex ecb39611e..ecdabaa5d 100644--- a/codex-llm-proxy/src/server.ts+++ b/codex-llm-proxy/src/server.ts@@ -1,4 +1,5 @@import express, { type Express, type Request, type Response } from 'express'+import { rateLimit } from 'express-rate-limit'import { createServer, type Server } from 'node:http'import { Registry, collectDefaultMetrics } from 'prom-client'import { z } from 'zod'@@ -15,7 +16,7 @@ import type { CodexLlmProxyConfig } from './config.js'import { ControlApiClient, ControlApiClientError } from './controlApiClient.js'import { logger } from './logger.js'import { createProxyMetrics } from './metrics.js'-import { OriginDeniedError } from './originPolicy.js'+import { defaultAddressLookup, OriginDeniedError } from './originPolicy.js'import { RequestLimitError, streamGate } from './requestLimits.js'const COMPLETION_KEYS = new Set(['executionTicket', 'requestHash', 'request', 'deadlineMs'])@@ -84,10 +85,23 @@ export function createProxyApps(config: CodexLlmProxyConfig, deps: ProxyRuntimeDserviceToken: config.controlApiServiceToken,})const fetchFn = deps.fetchFn ?? fetch+ const lookup = defaultAddressLookup+ const runtimeRateLimit = rateLimit({+ windowMs: 60_000,+ limit: 60,+ standardHeaders: 'draft-7',+ legacyHeaders: false,+ })+ const adminRateLimit = rateLimit({+ windowMs: 60_000,+ limit: 30,+ standardHeaders: 'draft-7',+ legacyHeaders: false,+ })const runtimeApp = express()runtimeApp.use(express.json({ limit: config.maxBodyBytes }))- runtimeApp.post('/internal/runtime/v1/codex/completions', (req, res) => {+ runtimeApp.post('/internal/runtime/v1/codex/completions', runtimeRateLimit, (req, res) => {if (!req.is('application/json')) {reject(res, 415, 'unsupported_media_type')return@@ -159,6 +173,7 @@ export function createProxyApps(config: CodexLlmProxyConfig, deps: ProxyRuntimeDredeem: input => client.redeem(input),finalize: input => client.finalize(input),fetchFn,+ lookup,onFrame: frame => {res.write(`data: ${JSON.stringify(frame)}\n\n`)},@@ -218,11 +233,19 @@ export function createProxyApps(config: CodexLlmProxyConfig, deps: ProxyRuntimeDvoid (async () => {try {if (kind === 'models') {- const listed = await listCodexModels({ accessToken: parsed.data.accessToken, fetchFn })+ const listed = await listCodexModels({+ accessToken: parsed.data.accessToken,+ fetchFn,+ lookup,+ })res.status(200).json(listed)return}- const tested = await testCodexConnection({ accessToken: parsed.data.accessToken, fetchFn })+ const tested = await testCodexConnection({+ accessToken: parsed.data.accessToken,+ fetchFn,+ lookup,+ })res.status(200).json(tested)} catch (err) {const mapped = mapError(err)@@ -230,8 +253,8 @@ export function createProxyApps(config: CodexLlmProxyConfig, deps: ProxyRuntimeD}})()}- adminApp.post('/internal/admin/v1/codex/models', adminHandler('models'))- adminApp.post('/internal/admin/v1/codex/test', adminHandler('test'))+ adminApp.post('/internal/admin/v1/codex/models', adminRateLimit, adminHandler('models'))+ adminApp.post('/internal/admin/v1/codex/test', adminRateLimit, adminHandler('test'))adminApp.use((_req, res) => reject(res, 404, 'not_found'))adminApp.use(boundedErrorHandler)diff --git a/codex-llm-proxy/test/originPolicy.test.ts b/codex-llm-proxy/test/originPolicy.test.tsindex e3bcff3e5..a0f3307e2 100644--- a/codex-llm-proxy/test/originPolicy.test.ts+++ b/codex-llm-proxy/test/originPolicy.test.ts@@ -66,6 +66,7 @@ describe('originPolicy', () => {const allowed = await fetchFrozenOrigin({url: new URL(CODEX_COMPLETIONS_ORIGIN),init: { method: 'POST' },+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],fetchFn: (async () => {hops += 1if (hops === 1) {@@ -84,6 +85,7 @@ describe('originPolicy', () => {fetchFrozenOrigin({url: new URL(CODEX_COMPLETIONS_ORIGIN),init: { method: 'POST' },+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],fetchFn: (async () =>new Response(null, {status: 302,diff --git a/codex-llm-proxy/test/redaction.test.ts b/codex-llm-proxy/test/redaction.test.tsindex ea80a8725..a01b1c114 100644--- a/codex-llm-proxy/test/redaction.test.ts+++ b/codex-llm-proxy/test/redaction.test.ts@@ -1,6 +1,5 @@-import pino from 'pino'import { describe, expect, it } from 'vitest'-import { logger } from '../src/logger.js'+import { createProxyLogger, logger } from '../src/logger.js'describe('proxy redaction', () => {it('strips access tokens, tickets, receipts, and authorization headers', () => {@@ -10,24 +9,8 @@ describe('proxy redaction', () => {messages.push(chunk)},}- const child = pino(- {- level: 'info',- redact: {- paths: [- 'accessToken',- 'refreshToken',- 'executionTicket',- 'authorization',- 'headers.authorization',- 'attemptReceipt',- ],- remove: true,- },- },- stream- )- child.info({+ const probe = createProxyLogger(stream)+ probe.info({accessToken: 'sk-live-secret',refreshToken: 'rt-secret',executionTicket: 'ticket-secret',diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c1b47509b..94cfb9c8d 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.494",+ "version": "0.1.495","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.494",+ "version": "0.1.495","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex f04ad5945..99acf8119 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.494",+ "version": "0.1.495","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex f87df8e7b..0d6d7d974 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -36,6 +36,10 @@ import {isPublicCodexCliClient,resolveCodexControlUiBaseUrl,} from '../../services/codexSubscriptionRedirectUri.js'+import {+ adminCodexReadRateLimits,+ adminCodexWriteRateLimits,+} from '../workflows/shared/rateLimit.js'const log = rootLogger.child({ module: 'admin-codex-subscription' })const BASE = '/admin/llm/providers/codex-subscription'@@ -266,23 +270,40 @@ export function createAdminCodexSubscriptionRouter(}})- router.get(`${BASE}/connection`, getConnectionHandler)- router.post(`${BASE}/browser/start`, browserStartHandler)- router.post(`${BASE}/device/start`, deviceStartHandler)- router.get(`${BASE}/device/poll`, devicePollHandler)- router.post(`${BASE}/refresh`, refreshHandler)- router.post(`${BASE}/catalog/sync`, catalogSyncHandler)- router.post(`${BASE}/revoke`, revokeHandler)- router.get(`${BASE}/connections/:key`, getConnectionHandler)- router.post(`${BASE}/connections/:key/browser/start`, browserStartHandler)- router.post(`${BASE}/connections/:key/device/start`, deviceStartHandler)- router.get(`${BASE}/connections/:key/device/poll`, devicePollHandler)- router.post(`${BASE}/connections/:key/refresh`, refreshHandler)- router.post(`${BASE}/connections/:key/catalog/sync`, catalogSyncHandler)- router.post(`${BASE}/connections/:key/revoke`, revokeHandler)+ router.get(`${BASE}/connection`, ...adminCodexReadRateLimits(), getConnectionHandler)+ router.post(`${BASE}/browser/start`, ...adminCodexWriteRateLimits(), browserStartHandler)+ router.post(`${BASE}/device/start`, ...adminCodexWriteRateLimits(), deviceStartHandler)+ router.get(`${BASE}/device/poll`, ...adminCodexReadRateLimits(), devicePollHandler)+ router.post(`${BASE}/refresh`, ...adminCodexWriteRateLimits(), refreshHandler)+ router.post(`${BASE}/catalog/sync`, ...adminCodexWriteRateLimits(), catalogSyncHandler)+ router.post(`${BASE}/revoke`, ...adminCodexWriteRateLimits(), revokeHandler)+ router.get(`${BASE}/connections/:key`, ...adminCodexReadRateLimits(), getConnectionHandler)+ router.post(+ `${BASE}/connections/:key/browser/start`,+ ...adminCodexWriteRateLimits(),+ browserStartHandler+ )+ router.post(+ `${BASE}/connections/:key/device/start`,+ ...adminCodexWriteRateLimits(),+ deviceStartHandler+ )+ router.get(+ `${BASE}/connections/:key/device/poll`,+ ...adminCodexReadRateLimits(),+ devicePollHandler+ )+ router.post(`${BASE}/connections/:key/refresh`, ...adminCodexWriteRateLimits(), refreshHandler)+ router.post(+ `${BASE}/connections/:key/catalog/sync`,+ ...adminCodexWriteRateLimits(),+ catalogSyncHandler+ )+ router.post(`${BASE}/connections/:key/revoke`, ...adminCodexWriteRateLimits(), revokeHandler)router.get(`${BASE}/connections`,+ ...adminCodexReadRateLimits(),asyncHandler(async (_req, res) => {if (!config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })@@ -300,6 +321,7 @@ export function createAdminCodexSubscriptionRouter(router.post(`${BASE}/connections`,+ ...adminCodexWriteRateLimits(),asyncHandler(async (req, res) => {if (!config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })@@ -336,6 +358,7 @@ export function createAdminCodexSubscriptionRouter(router.get(`${BASE}/connections/:key/models`,+ ...adminCodexReadRateLimits(),asyncHandler(async (req, res) => {if (!config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })diff --git a/control-api/src/routes/auth/codexSubscription.ts b/control-api/src/routes/auth/codexSubscription.tsindex 2d6fe645e..b08ef039d 100644--- a/control-api/src/routes/auth/codexSubscription.ts+++ b/control-api/src/routes/auth/codexSubscription.ts@@ -14,6 +14,7 @@ import {buildCodexBrowserReturnLocation,resolveCodexCallbackControlUiBaseUrl,} from '../../services/codexSubscriptionRedirectUri.js'+import { codexOAuthCallbackRateLimits } from '../workflows/shared/rateLimit.js'const log = rootLogger.child({ module: 'auth-codex-subscription' })@@ -53,6 +54,7 @@ export function createAuthCodexSubscriptionRouter(): Router {router.get('/auth/codex-subscription/callback',+ ...codexOAuthCallbackRateLimits(),asyncHandler(async (req, res) => {const code = typeof req.query.code === 'string' ? req.query.code : ''const state = typeof req.query.state === 'string' ? req.query.state : ''diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.tsindex ce5cbea39..3c658fd89 100644--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts@@ -12,6 +12,7 @@ import {LlmProviderAttemptAuthorizeError,authorizeLlmProviderAttempt,} from '../../services/llmProviderAttemptAuthorizer.js'+import { llmProviderAttemptAuthorizeRateLimits } from '../workflows/shared/rateLimit.js'const log = rootLogger.child({ module: 'mcp-host-llm-provider-attempts' })@@ -65,6 +66,7 @@ export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Routrouter.post('/mcp-host/llm/provider-attempts/authorize',requireMcpHostJwt,+ ...llmProviderAttemptAuthorizeRateLimits(),asyncHandler(async (req: Request, res: Response) => {const claims = req.mcpHostJwtif (!claims) {diff --git a/control-api/src/routes/workflows/shared/rateLimit.ts b/control-api/src/routes/workflows/shared/rateLimit.tsindex 56474616a..2345a574f 100644--- a/control-api/src/routes/workflows/shared/rateLimit.ts+++ b/control-api/src/routes/workflows/shared/rateLimit.ts@@ -11,6 +11,10 @@ const WORKFLOW_GRANT_WRITE_PER_MINUTE = 20const WORKFLOW_ADMIN_READ_PER_MINUTE = 60const ADMIN_OUTPUTS_READ_PER_MINUTE = 30const WORKFLOW_TRIGGER_PER_MINUTE = 10+const ADMIN_CODEX_READ_PER_MINUTE = 30+const ADMIN_CODEX_WRITE_PER_MINUTE = 20+const CODEX_OAUTH_CALLBACK_PER_MINUTE = 20+const LLM_PROVIDER_ATTEMPT_AUTHORIZE_PER_MINUTE = 60/*** Credential surface matched by requireAdminWorkflowCaller: bearer for automation,@@ -130,6 +134,85 @@ export function adminOutputsReadRateLimits() {return [adminOutputsReadEdgeRateLimit(), adminOutputsReadRateLimit()] as const}+function adminCodexReadEdgeRateLimit() {+ return createWorkflowEdgeRateLimit('admin_codex_read_edge', ADMIN_CODEX_READ_PER_MINUTE)+}++function adminCodexWriteEdgeRateLimit() {+ return createWorkflowEdgeRateLimit('admin_codex_write_edge', ADMIN_CODEX_WRITE_PER_MINUTE)+}++function adminCodexReadRateLimit() {+ return rateLimitMiddleware({+ bucketType: 'admin_codex_read',+ maxPerMinute: ADMIN_CODEX_READ_PER_MINUTE,+ getBucketKey: hashedAdminWorkflowCredentialBucket('admin_codex_read'),+ })+}++function adminCodexWriteRateLimit() {+ return rateLimitMiddleware({+ bucketType: 'admin_codex_write',+ maxPerMinute: ADMIN_CODEX_WRITE_PER_MINUTE,+ getBucketKey: hashedAdminWorkflowCredentialBucket('admin_codex_write'),+ })+}++export function adminCodexReadRateLimits() {+ return [adminCodexReadEdgeRateLimit(), adminCodexReadRateLimit()] as const+}++export function adminCodexWriteRateLimits() {+ return [adminCodexWriteEdgeRateLimit(), adminCodexWriteRateLimit()] as const+}++export function codexOAuthCallbackRateLimits() {+ return [+ rateLimit({+ windowMs: 60_000,+ limit: CODEX_OAUTH_CALLBACK_PER_MINUTE,+ standardHeaders: 'draft-7',+ legacyHeaders: false,+ keyGenerator: (req: Request) =>+ `codex_oauth_callback:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`,+ handler: workflowGrantEdgeRateLimitHandler,+ }),+ rateLimitMiddleware({+ bucketType: 'codex_oauth_callback',+ maxPerMinute: CODEX_OAUTH_CALLBACK_PER_MINUTE,+ getBucketKey: (req: Request) =>+ `codex_oauth_callback:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`,+ }),+ ] as const+}++export function llmProviderAttemptAuthorizeRateLimits() {+ return [+ rateLimit({+ windowMs: 60_000,+ limit: LLM_PROVIDER_ATTEMPT_AUTHORIZE_PER_MINUTE,+ standardHeaders: 'draft-7',+ legacyHeaders: false,+ skip: (req: Request) => !req.mcpHostJwt,+ keyGenerator: (req: Request) => {+ const claims = req.mcpHostJwt+ if (!claims) return `llm_provider_attempt:anon:${ipKeyGenerator(req.ip ?? 'unknown')}`+ return `llm_provider_attempt:${claims.sub}`+ },+ handler: workflowGrantEdgeRateLimitHandler,+ }),+ rateLimitMiddleware({+ bucketType: 'llm_provider_attempt_authorize',+ maxPerMinute: LLM_PROVIDER_ATTEMPT_AUTHORIZE_PER_MINUTE,+ getBucketKey: (req: Request) => {+ const claims = req.mcpHostJwt+ if (!claims) return null+ return `llm_provider_attempt:${claims.sub}`+ },+ }),+ ] as const+}+function adminWorkflowTriggerRateLimitKey(req: Request): string | null {const value = adminWorkflowRateLimitCredential(req)if (!value) return nulldiff --git a/control-api/src/services/codexSubscriptionRedirectUri.ts b/control-api/src/services/codexSubscriptionRedirectUri.tsindex 1a8ac88be..cc3c4b3b3 100644--- a/control-api/src/services/codexSubscriptionRedirectUri.ts+++ b/control-api/src/services/codexSubscriptionRedirectUri.ts@@ -79,16 +79,21 @@ export function resolveCodexCallbackControlUiBaseUrl(input: {forwardedProto?: string | nulloriginHeader?: string | null}): string {+ const configured = resolveCodexControlUiBaseUrl(+ input.configuredBaseUrl,+ input.originHeader ?? undefined+ )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.- }+ if (!forwardedHost || !forwardedProto) return configured+ try {+ const forwarded = normalizeControlUiOrigin(`${forwardedProto}://${forwardedHost}`)+ if (forwarded === configured) return forwarded+ if (isLoopbackHttpOrigin(configured) && isLoopbackHttpOrigin(forwarded)) return forwarded+ } catch {+ return configured}- return resolveCodexControlUiBaseUrl(input.configuredBaseUrl, input.originHeader ?? undefined)+ return configured}export function buildCodexBrowserReturnLocation(outcome: string): string {diff --git a/control-api/test/codexSubscriptionRedirectUri.test.ts b/control-api/test/codexSubscriptionRedirectUri.test.tsindex 5651b96dd..b26eb3dbc 100644--- a/control-api/test/codexSubscriptionRedirectUri.test.ts+++ b/control-api/test/codexSubscriptionRedirectUri.test.ts@@ -49,6 +49,16 @@ describe('codex subscription redirect URI', () => {).toBe('http://127.0.0.1:36148')})+ it('ignores a non-loopback forwarded host that does not match the configured origin', () => {+ expect(+ resolveCodexCallbackControlUiBaseUrl({+ configuredBaseUrl: 'https://control.example.com',+ forwardedHost: 'evil.example.com',+ forwardedProto: 'https',+ })+ ).toBe('https://control.example.com')+ })+it('identifies the public Codex CLI client id', () => {expect(isPublicCodexCliClient(PUBLIC_CODEX_CLI_CLIENT_ID)).toBe(true)expect(isPublicCodexCliClient('app_evenfire_custom')).toBe(false)diff --git a/control-api/test/routes.auth.codexSubscriptionCallback.test.ts b/control-api/test/routes.auth.codexSubscriptionCallback.test.tsindex 9ef6aef03..e1afdf150 100644--- a/control-api/test/routes.auth.codexSubscriptionCallback.test.ts+++ b/control-api/test/routes.auth.codexSubscriptionCallback.test.ts@@ -19,6 +19,20 @@ vi.mock('../src/db.js', () => ({pool: { query: vi.fn() },}))+vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ remaining: 19,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))++vi.mock('../src/observability/metrics.js', () => ({+ rateLimitHitsTotal: { inc: vi.fn() },+}))+const { config } = await import('../src/config.js')const { createAuthCodexSubscriptionRouter } =await import('../src/routes/auth/codexSubscription.js')diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.tsindex e45d05f04..85e22f514 100644--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts@@ -9,6 +9,24 @@ import { LlmProviderAttemptAuthorizeError } from '../src/services/llmProviderAttimport * as authorizer from '../src/services/llmProviderAttemptAuthorizer.js'import * as mcpHostJwt from '../src/utils/auth/mcpHostJwtToken.js'+vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))++vi.mock('../src/observability/metrics.js', async importOriginal => {+ const actual = await importOriginal<typeof import('../src/observability/metrics.js')>()+ return {+ ...actual,+ rateLimitHitsTotal: { inc: vi.fn() },+ }+})+vi.mock('../src/services/llmProviderAttemptAuthorizer.js', async () => {const actual = await vi.importActual<typeof import('../src/services/llmProviderAttemptAuthorizer.js')diff --git a/control-api/test/workflows.shared.rateLimit.test.ts b/control-api/test/workflows.shared.rateLimit.test.tsindex be5b422f8..07e616f0b 100644--- a/control-api/test/workflows.shared.rateLimit.test.ts+++ b/control-api/test/workflows.shared.rateLimit.test.ts@@ -2,9 +2,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import request from 'supertest'import {+ adminCodexReadRateLimits,+ adminCodexWriteRateLimits,adminOutputsReadRateLimits,adminWorkflowRateLimitCredential,adminWorkflowTriggerRateLimit,+ codexOAuthCallbackRateLimits,+ llmProviderAttemptAuthorizeRateLimits,shouldSkipWorkflowGrantEdgeRateLimit,verifiedAdminRateLimitSubject,workflowAdminReadRateLimits,@@ -73,6 +77,10 @@ describe('routes/workflows/shared/rateLimit', () => {expect(workflowGrantWriteRateLimits()).toHaveLength(2)expect(workflowAdminReadRateLimits()).toHaveLength(2)expect(adminOutputsReadRateLimits()).toHaveLength(2)+ expect(adminCodexReadRateLimits()).toHaveLength(2)+ expect(adminCodexWriteRateLimits()).toHaveLength(2)+ expect(codexOAuthCallbackRateLimits()).toHaveLength(2)+ expect(llmProviderAttemptAuthorizeRateLimits()).toHaveLength(2)})it('shouldSkipWorkflowGrantEdgeRateLimit skips anonymous callers', () => {diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex b7c88f719..b218b47cc 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -76,7 +76,7 @@ export default function HostDetailsPage() {const params = useParams<{ name: string; tab?: string }>()const router = useRouter()const { showToast } = useToast()- const { confirm, confirmDialog } = useConfirmDialog()+ const { confirmDialog } = useConfirmDialog()const routeName = decodeURIComponent(params.name || '')const mountedRef = useRef(true)diff --git a/control-ui/components/CodexSubscriptionConnection/index.tsx b/control-ui/components/CodexSubscriptionConnection/index.tsxdeleted file mode 100644index 1bb810302..000000000--- a/control-ui/components/CodexSubscriptionConnection/index.tsx+++ /dev/null@@ -1,472 +0,0 @@-'use client'--import React, { useEffect, useMemo, useState } from 'react'-import { useRouter, useSearchParams } from 'next/navigation'-import { useConfirmDialog } from '@components/ConfirmDialog'-import { CreateFlowPanel } from '@components/CreateFlowPanel'-import { CreatePageHeader } from '@components/CreatePageHeader'-import { LlmModelsTabBar } from '@components/LlmModelsSurface/LlmModelsTabBar'-import { LlmProviderIcon } from '@components/LlmProviderIcon'-import { useToast } from '@components/Toast'-import { Button, FormSection } from '@components/ui'-import { CONTROL_ROUTES } from '@constants/routes'-import { type LlmAllowedModel, getLlmModels, isSilentApiError } from '@lib/api'-import {- type CodexOAuthIntent,- type CodexSubscriptionConnectionView,- getCodexSubscriptionConnection,- pollCodexDevice,- readCodexOAuthQueryParam,- refreshCodexSubscriptionConnection,- revokeCodexSubscription,- startCodexDeviceConnect,- syncCodexSubscriptionCatalog,-} from '@lib/codexSubscription'-import {- isCodexSubscriptionUiEnabled,- loadCodexSubscriptionCapability,-} from '@lib/codexSubscriptionFeature'-import {- type CodexSubscriptionUiStatus,- mapConnectionStatus,- statusLabel,- statusTagClass,-} from './types'--function failureClass(error: unknown): string {- if (- error &&- typeof error === 'object' &&- typeof (error as { code?: unknown }).code === 'string'- ) {- return (error as { code: string }).code- }- if (error instanceof Error && error.message.trim()) return 'request_failed'- return 'unavailable'-}--function CodexHeaderIcon() {- return <LlmProviderIcon provider="codex-subscription" label="Codex subscription" />-}--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)- const [enabled, setEnabled] = useState(false)- const [uiStatus, setUiStatus] = useState<CodexSubscriptionUiStatus>('disconnected')- const [connection, setConnection] = useState<CodexSubscriptionConnectionView | null>(null)- const [deviceUserCode, setDeviceUserCode] = useState<string | null>(null)- const [deviceVerificationUri, setDeviceVerificationUri] = useState<string | null>(null)- const [deviceState, setDeviceState] = useState<string | null>(null)- 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)- const [tabModels, setTabModels] = useState<LlmAllowedModel[]>([])-- const discoveryReviewCount = useMemo(- () =>- tabModels.filter(model => model.source === 'discovery' && !model.enabled && !model.stale)- .length,- [tabModels]- )-- function applyConnection(next: CodexSubscriptionConnectionView) {- setConnection(next)- setUiStatus(mapConnectionStatus(next.status))- setErrorClass(null)- }-- async function loadConnection() {- try {- applyConnection(await getCodexSubscriptionConnection())- } catch (error) {- if (isSilentApiError(error)) return- setConnection(null)- setUiStatus('unavailable')- setErrorClass(failureClass(error))- }- }-- useEffect(() => {- if (!enabled) {- setTabModels([])- return- }- let cancelled = false- void getLlmModels()- .then(result => {- if (!cancelled) setTabModels(result.rows ?? [])- })- .catch(error => {- if (!cancelled && !isSilentApiError(error)) setTabModels([])- })- return () => {- cancelled = true- }- }, [enabled])-- function renderSectionTabs() {- if (!enabled) return null- return (- <LlmModelsTabBar- activeTab="catalog"- catalogCount={tabModels.length}- discoveryReviewCount={discoveryReviewCount}- />- )- }-- useEffect(() => {- let cancelled = false- void loadCodexSubscriptionCapability().then(capability => {- if (cancelled) return- const on = isCodexSubscriptionUiEnabled(capability)- setEnabled(on)- setCapabilityReady(true)- if (on) void loadConnection()- })- return () => {- cancelled = true- }- }, [])-- useEffect(() => {- const outcome = readCodexOAuthQueryParam(searchParams)- if (!outcome) return- router.replace(CONTROL_ROUTES.agents.root)- 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 undefined- const timer = window.setInterval(() => {- void pollCodexDevice(deviceState)- .then(result => {- if (result.status === 'connected') {- setDeviceState(null)- setDeviceUserCode(null)- setDeviceVerificationUri(null)- applyConnection(result.connection)- showToast('Codex subscription connected.', { tone: 'success' })- return- }- if (result.status === 'expired' || result.status === 'denied') {- setDeviceState(null)- setDeviceUserCode(null)- setDeviceVerificationUri(null)- setUiStatus('disconnected')- setErrorClass(result.status)- return- }- if (result.status === 'pending' || result.status === 'slow_down') {- setPollMs(result.intervalSeconds * 1000)- }- })- .catch(error => {- if (isSilentApiError(error)) return- setErrorClass(failureClass(error))- })- }, pollMs)- return () => window.clearInterval(timer)- }, [deviceState, pollMs, showToast, uiStatus])-- const fingerprint = useMemo(- () => connection?.accountFingerprint ?? 'none',- [connection?.accountFingerprint]- )-- async function startDevice(intent: CodexOAuthIntent) {- setBusy(true)- setErrorClass(null)- try {- const started = await startCodexDeviceConnect(intent)- setDeviceUserCode(started.userCode)- setDeviceVerificationUri(started.verificationUri)- setDeviceState(started.state)- setPollMs(started.intervalSeconds * 1000)- setUiStatus('device-pending')- if (started.verificationUri) {- window.open(started.verificationUri, '_blank', 'noopener,noreferrer')- }- } catch (error) {- if (isSilentApiError(error)) return- setUiStatus('unavailable')- setErrorClass(failureClass(error))- } finally {- setBusy(false)- }- }-- async function handleReplace() {- const approved = await confirm({- title: 'Replace Codex account',- message:- 'This replaces the current Codex grant. Hosts and recipes using Codex subscription lose the current grant and must use the new account after replacement.',- confirmLabel: 'Replace account',- tone: 'danger',- })- if (!approved) return- await startDevice('replace')- }-- async function handleRevoke() {- const approved = await confirm({- title: 'Revoke Codex subscription',- message:- 'Revoke the deployment Codex grant? Catalog models stay visible but become unusable until a new connection.',- confirmLabel: 'Revoke',- tone: 'danger',- })- if (!approved) return- setBusy(true)- setUiStatus('revoking')- try {- applyConnection(await revokeCodexSubscription())- showToast('Codex subscription revoked.', { tone: 'success' })- } catch (error) {- if (isSilentApiError(error)) return- setUiStatus('unavailable')- setErrorClass(failureClass(error))- } finally {- setBusy(false)- }- }-- async function handleSync() {- setBusy(true)- try {- const synced = await syncCodexSubscriptionCatalog()- applyConnection(synced.connection)- setSyncSummary(- `Catalog ${synced.outcome}: ${synced.added} added, ${synced.refreshed} refreshed, ${synced.staled} stale. New models stay disabled until enabled.`- )- showToast('Codex catalog synchronized.', { tone: 'success' })- } catch (error) {- if (isSilentApiError(error)) return- setErrorClass(failureClass(error))- } finally {- setBusy(false)- }- }-- async function handleTest() {- setBusy(true)- try {- applyConnection(await refreshCodexSubscriptionConnection())- showToast('Codex connection test succeeded.', { tone: 'success' })- } catch (error) {- if (isSilentApiError(error)) return- setErrorClass(failureClass(error))- if (connection) setUiStatus(mapConnectionStatus(connection.status))- } finally {- setBusy(false)- }- }-- if (!capabilityReady) {- return <p className="cu-subtitle">Checking Codex subscription availability.</p>- }-- if (!enabled) {- return (- <CreateFlowPanel- header={- <CreatePageHeader- icon={<CodexHeaderIcon />}- title="Codex subscription"- subtitle="This provider is not enabled on the control plane."- backLabel="Back to models"- onBack={() => router.push(CONTROL_ROUTES.llmModels.root)}- />- }- >- <div className="cu-banner" role="status">- Codex subscription is unavailable.- </div>- </CreateFlowPanel>- )- }-- return (- <CreateFlowPanel- header={- <>- <CreatePageHeader- icon={<CodexHeaderIcon />}- title="Codex subscription"- subtitle="Sign in with ChatGPT to use included Codex usage. Tokens stay on the control plane."- />- {renderSectionTabs()}- </>- }- >- <div className="cu-create-content cu-px-form cu-codex-subscription-panel">- <FormSection- title="Connection"- description="Sign in with ChatGPT once for this deployment. This uses your ChatGPT account, not a platform API key."- >- <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>- ) : null}-- {deviceUserCode ? (- <div- className="cu-banner cu-banner--info"- role="status"- data-testid="codex-device-code"- >- Sign in with ChatGPT using code <strong>{deviceUserCode}</strong>- {deviceVerificationUri ? (- <>- {' '}- at{' '}- <a href={deviceVerificationUri} target="_blank" rel="noopener noreferrer">- {deviceVerificationUri}- </a>- </>- ) : null}- </div>- ) : null}-- {syncSummary ? (- <div className="cu-banner cu-banner--ok" role="status" data-testid="codex-sync-summary">- {syncSummary}- </div>- ) : null}-- {errorClass ? (- <div className="cu-banner cu-banner--error" role="alert">- Connection failed ({errorClass}).- </div>- ) : null}-- {browserOAuthBlocked ? (- <div- className="cu-banner cu-banner--info"- role="status"- data-testid="codex-browser-oauth-blocked"- >- Browser redirect sign-in is not registered for this cluster. Use Sign in with ChatGPT- — the same account login path used by Codex, Pi, and OpenCode.- </div>- ) : null}-- <div className="cu-form-inline">- <Button- variant="primary"- size="sm"- disabled={busy}- onClick={() => void startDevice('connect')}- >- Sign in with ChatGPT- </Button>- <Button- size="sm"- variant="ghost"- disabled={busy || !connection}- onClick={() => void startDevice('reconnect')}- >- Reconnect- </Button>- <Button- size="sm"- variant="ghost"- disabled={busy || !connection}- onClick={() => void handleReplace()}- >- Replace account- </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/LlmModelsSurface/LlmModelsTabBar.tsx b/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsxindex 8f3e5879f..483353cb2 100644--- a/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx+++ b/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx@@ -14,8 +14,8 @@ export type LlmModelsTabBarProps = {}/**- * Shared LLM Models section tabs. Subscriptions are broker-backed OAuth flows,- * not API-key catalog rows, so Codex appears as its own tab beside Catalog.+ * Shared LLM Models section tabs. Codex assignment lives on the agent model+ * tab, so this bar is Catalog and Discovery review only.*/export function LlmModelsTabBar({activeTab,diff --git a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsxdeleted file mode 100644index fb6b786df..000000000--- a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx+++ /dev/null@@ -1,274 +0,0 @@-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 {- isCodexBrowserOAuthUnavailableError,- readCodexOAuthQueryParam,- sanitizeCodexConnection,-} from '@lib/codexSubscription'-import type { CodexSubscriptionConnectionView } from '@lib/codexSubscription'-import {- getCodexSubscriptionConnection,- refreshCodexSubscriptionConnection,- revokeCodexSubscription,- startCodexBrowserConnect,- startCodexDeviceConnect,- syncCodexSubscriptionCatalog,-} from '@lib/codexSubscription'-import { loadCodexSubscriptionCapability } from '@lib/codexSubscriptionFeature'-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(), replace: replaceMock }),- useSearchParams: () => searchParams,-}))--vi.mock('@components/ConfirmDialog', () => ({- useConfirmDialog: () => ({- confirm: confirmMock,- confirmDialog: null,- }),-}))--vi.mock('@lib/codexSubscriptionFeature', () => ({- loadCodexSubscriptionCapability: vi.fn(),- isCodexSubscriptionUiEnabled: (capability: { enabled?: boolean } | null) =>- capability?.enabled === true,-}))--vi.mock('@lib/codexSubscription', async importOriginal => {- const actual = await importOriginal<typeof import('@lib/codexSubscription')>()- return {- ...actual,- getCodexSubscriptionConnection: vi.fn(),- startCodexBrowserConnect: vi.fn(),- startCodexDeviceConnect: vi.fn(),- pollCodexDevice: vi.fn(),- refreshCodexSubscriptionConnection: vi.fn(),- syncCodexSubscriptionCatalog: vi.fn(),- revokeCodexSubscription: vi.fn(),- }-})--const connected: CodexSubscriptionConnectionView = {- connectionKey: 'deployment-default',- status: 'connected',- credentialRevision: 2,- catalogRevision: 4,- accountFingerprint: 'fp-safe',- catalogStatus: 'ready',- catalogSyncedAt: '2026-08-20T00:00:00.000Z',- lastRefreshAt: '2026-08-20T00:00:00.000Z',- lastAuthAt: '2026-08-20T00:00:00.000Z',- refreshLockHeld: false,-}--function renderSurface() {- return render(- <ToastProvider>- <CodexSubscriptionConnection />- </ToastProvider>- )-}--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('location', { assign: assignMock })- })-- afterEach(() => {- cleanup()- vi.clearAllMocks()- vi.unstubAllGlobals()- })-- it('strips tokens from a leaked connection fixture', () => {- expect(() =>- sanitizeCodexConnection({- ...connected,- accessToken: 'sk-leaked',- })- ).toThrow(/accessToken/)- })-- it('hides the surface when Control API capability is disabled', async () => {- vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: false })- renderSurface()- expect(await screen.findByText('Codex subscription is unavailable.')).toBeInTheDocument()- expect(screen.queryByRole('button', { name: 'Sign in with ChatGPT' })).not.toBeInTheDocument()- })-- it('renders connected status without tokens or account ids', async () => {- renderSurface()- expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Connected')- expect(screen.getByTestId('codex-fingerprint')).toHaveTextContent('fp-safe')- expect(document.body.textContent).not.toMatch(/sk-|accessToken|acct_raw|Authorization/i)- })-- it.each([- ['disconnected', 'Disconnected'],- ['connecting', 'Connecting'],- ['reauth_required', 'Reauthorization required'],- ] as const)('maps backend status %s to %s', async (status, label) => {- vi.mocked(getCodexSubscriptionConnection).mockResolvedValue({ ...connected, status })- renderSurface()- expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent(label)- })-- it('starts Sign in with ChatGPT through the device flow without rendering secrets', async () => {- const openMock = vi.fn()- vi.stubGlobal('open', openMock)- vi.mocked(startCodexDeviceConnect).mockResolvedValue({- userCode: 'ABCD-EFGH',- verificationUri: 'https://auth.openai.com/codex/device',- intervalSeconds: 5,- state: 'dev',- intent: 'connect',- })- renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Sign in with ChatGPT' }))- await waitFor(() => {- expect(startCodexDeviceConnect).toHaveBeenCalledWith('connect')- })- expect(openMock).toHaveBeenCalledWith(- 'https://auth.openai.com/codex/device',- '_blank',- 'noopener,noreferrer'- )- expect(assignMock).not.toHaveBeenCalled()- expect(document.body.textContent).not.toMatch(/sk-|deviceCode|accessToken/i)- })-- it('shows the ChatGPT sign-in banner when a leftover browser callback is unregistered', async () => {- searchParams = new URLSearchParams('codex_oauth=browser_oauth_unregistered')- renderSurface()- expect(await screen.findByTestId('codex-browser-oauth-blocked')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Sign in with ChatGPT' })).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(expect.stringMatching(/\/(hosts|agents)/))- })- 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',- verificationUri: 'https://auth.openai.com/codex/device',- intervalSeconds: 5,- state: 'dev',- intent: 'connect',- })- renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Sign in with ChatGPT' }))- expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent(- 'Device code pending'- )- expect(screen.getByTestId('codex-device-code')).toHaveTextContent('ABCD-EFGH')- expect(document.body.textContent).not.toContain('device_secret')- })-- it('confirms replacement impact before starting a replace flow', async () => {- vi.mocked(startCodexDeviceConnect).mockResolvedValue({- userCode: 'REPL-CODE',- verificationUri: 'https://auth.openai.com/codex/device',- intervalSeconds: 5,- state: 'rep',- intent: 'replace',- })- renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Replace account' }))- await waitFor(() => {- expect(confirmMock).toHaveBeenCalled()- })- expect(String(confirmMock.mock.calls[0]?.[0]?.message)).toMatch(/lose the current grant/i)- await waitFor(() => {- expect(startCodexDeviceConnect).toHaveBeenCalledWith('replace')- })- })-- it('syncs catalog and keeps newly discovered models disabled in the summary', async () => {- vi.mocked(syncCodexSubscriptionCatalog).mockResolvedValue({- outcome: 'ready',- added: 2,- refreshed: 1,- staled: 1,- connection: connected,- })- renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Sync catalog' }))- expect(await screen.findByTestId('codex-sync-summary')).toHaveTextContent(- 'New models stay disabled until enabled'- )- expect(syncCodexSubscriptionCatalog).toHaveBeenCalled()- })-- it('tests and revokes the connection', async () => {- vi.mocked(refreshCodexSubscriptionConnection).mockResolvedValue(connected)- vi.mocked(revokeCodexSubscription).mockResolvedValue({- ...connected,- status: 'revoked',- })- renderSurface()- fireEvent.click(await screen.findByRole('button', { name: 'Test connection' }))- await waitFor(() => {- expect(refreshCodexSubscriptionConnection).toHaveBeenCalled()- })- fireEvent.click(screen.getByRole('button', { name: 'Revoke' }))- await waitFor(() => {- expect(revokeCodexSubscription).toHaveBeenCalled()- })- expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Revoked')- })-- it('anti-false-positive: a leaked accessToken never reaches the DOM', async () => {- vi.mocked(getCodexSubscriptionConnection).mockImplementation(async () =>- sanitizeCodexConnection({- ...connected,- accessToken: 'sk-should-not-render',- })- )- renderSurface()- expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Unavailable')- expect(document.body.textContent).not.toContain('sk-should-not-render')- 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/package-lock.json b/control-ui/package-lock.jsonindex accdf57c0..2c6910463 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.451",+ "version": "0.1.452","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.451",+ "version": "0.1.452","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 1efd79c00..24b4ddf96 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.451",+ "version": "0.1.452","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/docs/how-to/codeql-js-missing-rate-limiting.md b/docs/how-to/codeql-js-missing-rate-limiting.mdindex 610df3038..fcd12632b 100644--- a/docs/how-to/codeql-js-missing-rate-limiting.md+++ b/docs/how-to/codeql-js-missing-rate-limiting.md@@ -59,6 +59,9 @@ Additional tiers shipped in PR #428:| Admin workflow read | 60 | `workflowAdminReadRateLimits` || Admin outputs read | 30 | `adminOutputsReadRateLimits` || Admin workflow trigger | 10 | `adminWorkflowTriggerRateLimit` |+| Admin Codex read / write | 30 / 20 | `adminCodexReadRateLimits` / `adminCodexWriteRateLimits` |+| Codex OAuth callback | 20 | `codexOAuthCallbackRateLimits` (IP) |+| mcp-host attempt authorize | 60 | `llmProviderAttemptAuthorizeRateLimits` |## Out-of-scope dispositions (Layer 3)diff --git a/tests/e2e/integration/codex-subscription-contract-freeze.test.ts b/tests/e2e/integration/codex-subscription-contract-freeze.test.tsindex b0470fe93..09c2658bf 100644--- a/tests/e2e/integration/codex-subscription-contract-freeze.test.ts+++ b/tests/e2e/integration/codex-subscription-contract-freeze.test.ts@@ -124,7 +124,7 @@ describe('codex-subscription contract freeze', () => {expect(isHttpsOrigin(origins?.[key]), `origins.${key} must be an exact https origin`).toBe(true)- expect(String(origins?.[key])).not.toMatch(/api\.openai\.com\/v1\/(?!responses\b)/)+ expect(String(origins?.[key])).not.toMatch(/^https:\/\/api\.openai\.com\/v1\/(?!responses\b)/)}expect(Array.isArray(contract.forbiddenOrigins), 'forbiddenOrigins must be listed').toBe(true)expect(contract.forbiddenOrigins as unknown[]).toEqual(diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.jsonindex 2b05ec0ef..5d46fa2b3 100644--- a/tests/e2e/package-lock.json+++ b/tests/e2e/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-e2e-tests",- "version": "0.1.69",+ "version": "0.1.70","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-e2e-tests",- "version": "0.1.69",+ "version": "0.1.70","devDependencies": {"@types/jsonwebtoken": "^9.0.10","@types/node": "^22.0.0",diff --git a/tests/e2e/package.json b/tests/e2e/package.jsonindex 9f389a828..ba921241d 100644--- a/tests/e2e/package.json+++ b/tests/e2e/package.json@@ -1,6 +1,6 @@{"name": "clerum-e2e-tests",- "version": "0.1.69",+ "version": "0.1.70","private": true,"type": "module","scripts": {