Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(ui): brand subscription sanitizer failures by the broker that answered
Alfredo Lopezac01b07b9d59
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 343c05cc9..f7a852a71 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.596",+ "version": "0.1.597","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.596",+ "version": "0.1.597","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 15acddefd..82574c3bb 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.596",+ "version": "0.1.597","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/test/services.grokSubscriptionOAuth.test.ts b/control-api/test/services.grokSubscriptionOAuth.test.tsindex e028eb4ad..937f3e249 100644--- a/control-api/test/services.grokSubscriptionOAuth.test.ts+++ b/control-api/test/services.grokSubscriptionOAuth.test.ts@@ -74,6 +74,7 @@ const {pollGrokDevice,refreshGrokSubscriptionConnection,revokeGrokSubscription,+ runGrokCatalogSync,startGrokDeviceConnect,} = await import('../src/services/grokSubscriptionOAuth.js')@@ -397,13 +398,63 @@ describe('grok subscription OAuth device broker', () => {status: 400,json: async () => ({ error: 'invalid_grant' }),})+ // `persistedConnectionStatus` is named explicitly because `toMatchObject` is a+ // partial match: an assertion that omits it passes whether the flag is true,+ // false or absent. That flag is what makes the cron republish the allowlist+ // after this rejection, so leaving it unnamed lets the whole mechanism be+ // severed with the suite still green. `markMismatch` below is the liveness+ // witness that the row really was written before the throw.await expect(refreshGrokSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({code: 'reauth_required',+ persistedConnectionStatus: true,})expect(repos.markMismatch).toHaveBeenCalled()expect(repos.persistRefresh).not.toHaveBeenCalled()})+ // The other half of the same wiring. The assertion above pins the flag on the+ // error; this pins that `runGrokCatalogSync` carries it out to its caller,+ // which is what makes the reconciliation cron republish the runtime allowlist+ // for a grant the control plane has just marked broken. Both ends have to be+ // asserted: severing either one on its own left the whole control-api suite+ // green.+ it('carries persisted out of a rejected refresh so the caller can republish', async () => {+ repos.getSafe.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 3,+ refreshLockHeld: true,+ })+ repos.acquireLock.mockResolvedValue(true)+ repos.loadSecrets.mockResolvedValue({+ refreshToken: 'old-refresh',+ accessToken: null,+ accessTokenExpiresAt: null,+ credentialRevision: 3,+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: false,+ status: 400,+ json: async () => ({ error: 'invalid_grant' }),+ })+ const transport = { listModels: vi.fn() }++ const result = await runGrokCatalogSync(deps(fetchFn), CONNECTION_KEY, transport)++ expect(result).toMatchObject({+ ok: false,+ catalogStatus: 'never_synced',+ reason: 'reauth_required',+ persisted: true,+ })+ // Liveness witnesses for the negative below: the refresh really was+ // attempted and the row really was written, so `listModels` not being+ // called is the catalog being skipped, not the test never running.+ expect(fetchFn).toHaveBeenCalledTimes(1)+ expect(repos.markMismatch).toHaveBeenCalled()+ expect(transport.listModels).not.toHaveBeenCalled()+ })+it('maps invalid_grant after a lock/revision change to a lost race', async () => {const before = {connectionKey: CONNECTION_KEY,diff --git a/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts b/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.tsindex 418b0b2fa..1b194f9e6 100644--- a/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts+++ b/control-api/test/services.subscriptionCatalogSyncCron.realPostgres.integration.test.ts@@ -77,10 +77,13 @@ function jsonResponse(status: number, body: Record<string, unknown>): Response {const GRANT_SUBJECT = 'subject-cron-grok'/**- * Simulated xAI device-authorization provider. The cron's tick finds an- * access token past its expiry and rotates the refresh token through this- * before it may read the catalog, so the rotation path is exercised, not- * bypassed.+ * Simulated xAI device-authorization provider for the healthy cases. Its grant+ * is valid for an hour, well outside `ACCESS_TOKEN_REFRESH_SKEW_MS`, so a tick+ * using it finds a fresh access token and goes straight to the catalog:+ * `ensureFreshGrokAccessToken` returns before `rotateLockedRefresh`, and this+ * token endpoint is never called a second time. That is the ordinary steady+ * state, and it is deliberately NOT the rotation path — see+ * `rejectingRefreshGrokProvider` for the tick that does rotate.*/function simulatedGrokProvider(): typeof fetch {let issued = 0@@ -109,6 +112,50 @@ function simulatedGrokProvider(): typeof fetch {}) as typeof fetch}+/**+ * Simulated xAI provider whose grant expires inside the refresh skew and whose+ * refresh exchange is then rejected with `invalid_grant` — the state a real+ * deployment reaches when the operator revokes the app at xAI.+ *+ * The device grant and the refresh share one endpoint, so the first token call+ * is the grant and every later one is the rotation this suite's other provider+ * never reaches. `expires_in` of 60 seconds sits inside+ * `ACCESS_TOKEN_REFRESH_SKEW_MS` (5 minutes), which is what makes+ * `ensureFreshGrokAccessToken` rotate instead of returning early.+ *+ * This is the same HTTP seam the healthy cases use, not a new double: xAI's+ * endpoints are the boundary, so a rejected refresh needs no real subscription.+ */+function rejectingRefreshGrokProvider(): typeof fetch {+ let tokenCalls = 0+ return (async (url: string | URL) => {+ const target = String(url)+ if (target === GROK_OAUTH_DEVICE_URL) {+ return jsonResponse(200, {+ device_code: `device-code-reject-${randomBytes(4).toString('hex')}`,+ user_code: 'IJKL-MNOP',+ verification_uri: 'https://auth.x.ai/activate',+ expires_in: 900,+ interval: 5,+ })+ }+ if (target === GROK_OAUTH_TOKEN_URL) {+ tokenCalls += 1+ if (tokenCalls === 1) {+ return jsonResponse(200, {+ access_token: `access-${randomBytes(4).toString('hex')}`,+ refresh_token: `refresh-${randomBytes(4).toString('hex')}`,+ expires_in: 60,+ id_token: idTokenFor(GRANT_SUBJECT),+ })+ }+ return jsonResponse(400, { error: 'invalid_grant' })+ }+ if (target === GROK_OAUTH_REVOKE_URL) return jsonResponse(200, {})+ return jsonResponse(404, {})+ }) as typeof fetch+}+function readyTransport(models: Array<{ model: string; contextWindowTokens?: number }>): {transport: GrokCatalogTransportcalls: number[]@@ -158,11 +205,19 @@ describeRealPostgres('Subscription catalog sync cron on real PostgreSQL', () =>}}- function oauthDeps(connectionKey: string, db: DbClient = pool): GrokOAuthDeps {+ // `fetchFn` is a parameter because a provider that counts its own calls has to+ // be the SAME instance across the device grant and the later tick; a helper+ // that built a fresh one per call would reset that counter and hand the tick+ // a second successful grant instead of the rejection under test.+ function oauthDeps(+ connectionKey: string,+ db: DbClient = pool,+ fetchFn: typeof fetch = simulatedGrokProvider()+ ): GrokOAuthDeps {return {db,encryptionKey: KEY,- fetchFn: simulatedGrokProvider(),+ fetchFn,clientId: 'b1a00492-073a-47ea-816f-4c329264a828',enabled: true,connectionKey,@@ -176,7 +231,8 @@ describeRealPostgres('Subscription catalog sync cron on real PostgreSQL', () =>*/function grokPort(transport: GrokCatalogTransport,- syncedKeys: string[] = []+ syncedKeys: string[] = [],+ fetchFn?: typeof fetch): SubscriptionBrokerPort {return {broker: 'grok-subscription',@@ -185,7 +241,7 @@ describeRealPostgres('Subscription catalog sync cron on real PostgreSQL', () =>filterAddressableGrokConnections(await listLiveGrokSubscriptionConnections(pool)),syncCatalog: key => {syncedKeys.push(key)- return runGrokCatalogSync(oauthDeps(key), key, transport)+ return runGrokCatalogSync(oauthDeps(key, pool, fetchFn), key, transport)},}}@@ -375,4 +431,46 @@ describeRealPostgres('Subscription catalog sync cron on real PostgreSQL', () =>catalogStatus: 'never_synced',})})++ it('a rejected refresh marks the row and still counts as a recorded outcome', async () => {+ const rejected = 'cron-grok-rejected'+ // One provider instance for the grant AND the tick: the rejection is its+ // second token call, so a fresh instance per call would hand the tick+ // another successful grant.+ const provider = rejectingRefreshGrokProvider()+ const started = await startGrokDeviceConnect(oauthDeps(rejected, pool, provider), 'connect')+ const polled = await pollGrokDevice(oauthDeps(rejected, pool, provider), started.state)+ expect(polled.status).toBe('connected')+ const { transport, calls } = readyTransport([{ model: 'grok-4' }])+ const syncedKeys: string[] = []+ const { materializer, calls: published } = recordingMaterializer()++ const result = await reconcileSubscriptionCatalogs({+ brokers: [grokPort(transport, syncedKeys, provider)],+ materializer,+ })++ // `degraded` is the load-bearing count, not a detail of the tally. A+ // rejected refresh returns `catalogStatus: 'never_synced'`, so the only+ // thing that keeps it out of `failed` is `persisted: true` travelling from+ // the error, through `runGrokCatalogSync`, into `syncOutcomeChangedTheRow`.+ // Sever any link in that chain and this line reads `degraded: 0, failed: 1`+ // — which is the whole mechanism this feature exists for, observed at the+ // level where it runs rather than asserted on a hand-built outcome.+ expect(result).toMatchObject({ synced: 1, degraded: 1, failed: 0, raced: 0 })+ // The business witness in Postgres: the connection really was written+ // before the throw, which is what makes the stale ConfigMap a problem.+ expect(await getSafeGrokSubscriptionConnection(pool, rejected)).toMatchObject({+ status: 'reauth_required',+ catalogStatus: 'never_synced',+ })+ // Liveness witnesses for the negative: the healthy grant in the same+ // listing was synced and its catalog really was read, so `calls` holding a+ // single entry means the rejected grant never reached the transport — not+ // that the tick did nothing.+ expect(syncedKeys).toContain(rejected)+ expect(syncedKeys).toContain('cron-grok-primary')+ expect(calls).toEqual([1])+ expect(published).toHaveLength(1)+ })})diff --git a/control-ui/components/CodexSubscriptionHub/index.tsx b/control-ui/components/CodexSubscriptionHub/index.tsxindex f8ee9a0d5..c37750a47 100644--- a/control-ui/components/CodexSubscriptionHub/index.tsx+++ b/control-ui/components/CodexSubscriptionHub/index.tsx@@ -107,6 +107,16 @@ function catalogSyncErrorMessage(err: unknown, brand: string): string {case 'no_grant':case 'not_connected':return `This subscription no longer authorizes with ${brand}. Sign in again, then sync the catalog.`+ // The one code that is both actionable and already recorded: the refresh+ // token was rejected, so control-api has ALREADY moved this row to+ // `reauth_required` before answering. Leaving it on the default arm gave+ // the most common recoverable failure the least usable message, while+ // `not_connected` — the same situation, reached differently — got the+ // instruction that resolves it.+ case 'reauth_required':+ return `${brand} rejected this subscription's saved credentials. Sign in again to restore it, then sync the catalog.`+ case 'provider_unavailable':+ return `${brand} did not answer the credential refresh. The stored models are unchanged; try again in a moment.`case 'stale_revision':return `The subscription changed while this sync ran. Reopen it to see the current catalog, then sync again.`case 'refresh_in_flight':diff --git a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsxindex 616c32d7a..e51bc31a9 100644--- a/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx+++ b/control-ui/components/__tests__/CodexSubscriptionHub.test.tsx@@ -958,13 +958,18 @@ describe('CodexSubscriptionHub catalog re-sync', () => {expect(await screen.findByText(/could not be refreshed/)).toBeInTheDocument()})- it('reports a non-ready outcome the endpoint returns with 200 instead of claiming success', async () => {+ // The route cannot emit this today: 200 is returned only on the `ok` branch,+ // and that branch's type pins `catalogStatus: 'ready'`. The guard still earns+ // its place, because the client reads the SANITIZED view and+ // `sanitizeCodexCatalogSync` resolves a missing `outcome` to `'unknown'`+ // without throwing. So a 200 whose body lost its outcome — a contract drift,+ // a truncated response — lands here, and the operator sees the failure rather+ // than a "Catalog synced" toast over a sync that never happened. This test+ // defends that guard; it does not claim the backend produces this shape.+ it('refuses to claim success for a 200 whose outcome is not ready', async () => {fetchMock.mockResolvedValueOnce(makeResponse(200, {outcome: 'auth-rejected',- added: 0,- refreshed: 0,- staled: 0,connection: connection({connectionKey: 'grok-aaa',displayName: 'Team Grok',@@ -1052,6 +1057,40 @@ describe('CodexSubscriptionHub catalog re-sync', () => {expect(fetchMock).toHaveBeenCalledTimes(1)})+ // control-api answers a rejected refresh token with 400 `reauth_required`+ // AFTER writing that status to the row. Unmapped codes keep the API's raw+ // message by design, and for this one that produced `400 Bad Request -+ // reauth_required` — the least readable message on the most common+ // recoverable failure.+ it('tells the operator to sign in again when the saved credentials are rejected', async () => {+ fetchMock.mockResolvedValueOnce(makeResponse(400, { error: 'reauth_required' }))++ const dialog = await openGrokDialog()+ await within(dialog).findByLabelText('grok-4.6')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))++ const banner = await within(dialog).findByText(/rejected this subscription's saved/i)+ expect(banner).toHaveTextContent('Sign in again')+ // The raw fall-through is what this case replaces, so its absence is the+ // point. The banner assertion above is its liveness witness: a component+ // that rendered no error at all would satisfy the absence for free.+ expect(within(dialog).queryByText(/400 Bad Request/)).not.toBeInTheDocument()+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it('says the provider did not answer when the credential refresh is unavailable', async () => {+ fetchMock.mockResolvedValueOnce(makeResponse(400, { error: 'provider_unavailable' }))++ const dialog = await openGrokDialog()+ await within(dialog).findByLabelText('grok-4.6')+ fireEvent.click(within(dialog).getByRole('button', { name: 'Sync catalog' }))++ const banner = await within(dialog).findByText(/did not answer the credential refresh/i)+ expect(banner).toHaveTextContent('stored models are unchanged')+ expect(within(dialog).queryByText(/400 Bad Request/)).not.toBeInTheDocument()+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })+// The setup form is the one state where the models block renders while the// grant is still disconnected, so it is the only place the sync action's own// status guard decides anything. Fixtures where the block is hidden anywaydiff --git a/control-ui/components/__tests__/LlmModelTable.test.tsx b/control-ui/components/__tests__/LlmModelTable.test.tsxindex 07531124d..9db58c33c 100644--- a/control-ui/components/__tests__/LlmModelTable.test.tsx+++ b/control-ui/components/__tests__/LlmModelTable.test.tsx@@ -226,6 +226,45 @@ describe('LlmModelTable catalog-lifecycle columns', () => {expect(onEdit).not.toHaveBeenCalledWith('xai-key')})+ it('labels a model only the API key serves without implying a subscription', () => {+ renderTable([+ {+ ...baseModel,+ id: 'xai-key',+ provider: 'xai',+ model: 'grok-4.6',+ vendor: 'xAI',+ display_name: 'Grok 4.6',+ },+ {+ ...baseModel,+ id: 'xai-sub',+ provider: 'grok-subscription',+ model: 'grok-4.6',+ vendor: 'xAI',+ display_name: 'Grok 4.6',+ },+ {+ ...baseModel,+ id: 'xai-key-only',+ provider: 'xai',+ model: 'grok-4.6-heavy',+ vendor: 'xAI',+ display_name: 'Grok 4.6 Heavy',+ },+ ])+ fireEvent.click(screen.getByRole('button', { name: 'Expand xAI (Grok) models' }))+ // The mirror of the subscription-only row the suite already covers. The+ // badge is per model, not per family: a family that holds a broker must not+ // make every one of its models look reachable through the subscription.+ const apiKeyOnly = screen.getByText('grok-4.6-heavy').closest('tr')+ expect(apiKeyOnly).toHaveTextContent('API key')+ expect(apiKeyOnly).not.toHaveTextContent('Subscription')+ // Liveness witness: the collapse really ran on this family, so the negative+ // above is about a rendered badge and not about an unrendered table.+ expect(screen.getByText('grok-4.6').closest('tr')).toHaveTextContent('API key · Subscription')+ })+it('leaves a single-provider family uncollapsed and unlabelled', () => {renderTable([{ ...baseModel, id: 'cl-1', model: 'claude-sonnet-4-6' },diff --git a/control-ui/lib/__tests__/grokSubscription.sync.test.ts b/control-ui/lib/__tests__/grokSubscription.sync.test.tsindex 54488a155..57ac80107 100644--- a/control-ui/lib/__tests__/grokSubscription.sync.test.ts+++ b/control-ui/lib/__tests__/grokSubscription.sync.test.ts@@ -34,13 +34,15 @@ beforeEach(() => {afterEach(() => vi.unstubAllGlobals())describe('Grok subscription catalog sync client', () => {+ // The fixture carries exactly what the Grok branch of the route sends —+ // `{ outcome, connection }`, no counters. That is what `GrokCatalogSyncView`+ // omits them for. A fixture that invented counters would assert a producer+ // behaviour that does not exist, and would keep passing if the real response+ // ever drifted.it('POSTs to the connection-scoped catalog sync endpoint on the Grok base', async () => {fetchMock.mockResolvedValueOnce(makeResponse(200, {outcome: 'ready',- added: 2,- refreshed: 5,- staled: 1,connection: readyConnection,}))@@ -57,11 +59,11 @@ describe('Grok subscription catalog sync client', () => {expect(init.method).toBe('POST')expect(init.body).toBeUndefined()+ // `toEqual` is exact, so this also pins the absence of the counters: if the+ // sanitizer ever puts `added`/`refreshed`/`staled` back into the Grok view,+ // this line fails instead of silently handing a caller three zeros.expect(view).toEqual({outcome: 'ready',- added: 2,- refreshed: 5,- staled: 1,connection: expect.objectContaining({ connectionKey, catalogStatus: 'ready' }),})})diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.tsindex 5fb0cdff7..5faf226d6 100644--- a/control-ui/lib/codexSubscription.ts+++ b/control-ui/lib/codexSubscription.ts@@ -90,17 +90,26 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === 'object' && !Array.isArray(value)}-function assertNoForbiddenKeys(value: unknown, path = 'root'): void {+/**+ * The two subscription brokers share this module's shape validation but not+ * their identity. An operator reading "Codex subscription connection status is+ * invalid" in a Grok dialog is being told the wrong thing about which vendor+ * answered, so every message the user can reach is parameterized by the brand+ * of the endpoint that produced the payload.+ */+export type SubscriptionBrand = 'Codex' | 'Grok'++function assertNoForbiddenKeys(value: unknown, brand: SubscriptionBrand, path = 'root'): void {if (Array.isArray(value)) {- value.forEach((entry, index) => assertNoForbiddenKeys(entry, `${path}[${index}]`))+ value.forEach((entry, index) => assertNoForbiddenKeys(entry, brand, `${path}[${index}]`))return}if (!isPlainObject(value)) returnfor (const [key, nested] of Object.entries(value)) {if (FORBIDDEN_KEY.test(key)) {- throw new Error(`Codex subscription payload leaked forbidden field "${key}" at ${path}`)+ throw new Error(`${brand} subscription payload leaked forbidden field "${key}" at ${path}`)}- assertNoForbiddenKeys(nested, `${path}.${key}`)+ assertNoForbiddenKeys(nested, brand, `${path}.${key}`)}}@@ -117,9 +126,16 @@ function pickBool(value: unknown): boolean {}export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnectionView {- assertNoForbiddenKeys(raw)+ return sanitizeSubscriptionConnection(raw, 'Codex')+}++export function sanitizeSubscriptionConnection(+ raw: unknown,+ brand: SubscriptionBrand+): CodexSubscriptionConnectionView {+ assertNoForbiddenKeys(raw, brand)if (!isPlainObject(raw)) {- throw new Error('Codex subscription connection is not an object')+ throw new Error(`${brand} subscription connection is not an object`)}const status = raw.statusif (@@ -129,7 +145,7 @@ export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnectistatus !== 'reauth_required' &&status !== 'revoked') {- throw new Error('Codex subscription connection status is invalid')+ throw new Error(`${brand} subscription connection status is invalid`)}const catalogStatus = raw.catalogStatusconst safeCatalog: CodexCatalogStatus =@@ -141,7 +157,7 @@ export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnecti: 'never_synced'const connectionKey = typeof raw.connectionKey === 'string' ? raw.connectionKey.trim() : ''if (!connectionKey || connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {- throw new Error('Codex subscription connection key is invalid')+ throw new Error(`${brand} subscription connection key is invalid`)}return {connectionKey,@@ -169,7 +185,7 @@ export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnecti}export function sanitizeCodexBrowserStart(raw: unknown): CodexBrowserStartView {- assertNoForbiddenKeys(raw)+ assertNoForbiddenKeys(raw, 'Codex')if (!isPlainObject(raw)) throw new Error('Codex browser start is not an object')const authorizeUrl = pickString(raw.authorizeUrl)const state = pickString(raw.state)@@ -190,7 +206,7 @@ export function sanitizeCodexBrowserStart(raw: unknown): CodexBrowserStartView {}export function sanitizeCodexDeviceStart(raw: unknown): CodexDeviceStartView {- assertNoForbiddenKeys(raw)+ assertNoForbiddenKeys(raw, 'Codex')if (!isPlainObject(raw)) throw new Error('Codex device start is not an object')const userCode = pickString(raw.userCode)const verificationUri = pickString(raw.verificationUri)@@ -212,7 +228,7 @@ export function sanitizeCodexDeviceStart(raw: unknown): CodexDeviceStartView {}export function sanitizeCodexDevicePoll(raw: unknown): CodexDevicePollView {- assertNoForbiddenKeys(raw)+ assertNoForbiddenKeys(raw, 'Codex')if (!isPlainObject(raw)) throw new Error('Codex device poll is not an object')if (raw.status === 'connected') {return { status: 'connected', connection: sanitizeCodexConnection(raw.connection) }@@ -231,14 +247,22 @@ export function sanitizeCodexDevicePoll(raw: unknown): CodexDevicePollView {}export function sanitizeCodexCatalogSync(raw: unknown): CodexCatalogSyncView {- assertNoForbiddenKeys(raw)- if (!isPlainObject(raw)) throw new Error('Codex catalog sync is not an object')+ return sanitizeSubscriptionCatalogSync(raw, 'Codex')+}++export function sanitizeSubscriptionCatalogSync(+ raw: unknown,+ brand: SubscriptionBrand+): CodexCatalogSyncView {+ assertNoForbiddenKeys(raw, brand)+ if (!isPlainObject(raw)) throw new Error(`${brand} catalog sync is not an object`)return {outcome: pickString(raw.outcome) ?? 'unknown',added: pickNumber(raw.added),refreshed: pickNumber(raw.refreshed),staled: pickNumber(raw.staled),- connection: raw.connection == null ? null : sanitizeCodexConnection(raw.connection),+ connection:+ raw.connection == null ? null : sanitizeSubscriptionConnection(raw.connection, brand),}}diff --git a/control-ui/lib/grokSubscription.ts b/control-ui/lib/grokSubscription.tsindex 95f4c6e17..f2e45aca1 100644--- a/control-ui/lib/grokSubscription.ts+++ b/control-ui/lib/grokSubscription.ts@@ -8,8 +8,8 @@ import {type CodexDevicePollView,type CodexOAuthIntent,type CodexSubscriptionConnectionView,- sanitizeCodexCatalogSync,- sanitizeCodexConnection,+ sanitizeSubscriptionCatalogSync,+ sanitizeSubscriptionConnection,} from './codexSubscription'export const GROK_SUBSCRIPTION_API_BASE = '/api/v1/admin/llm/providers/grok-subscription'@@ -26,7 +26,7 @@ export type GrokDevicePollView = CodexDevicePollView/*** Narrower than the Codex view on purpose. The Grok `catalog/sync` endpoint* answers `{ outcome, connection }` and sends no `added`/`refreshed`/`staled`- * counters, so `sanitizeCodexCatalogSync` fills them with zeros that mean "the+ * counters, so the shared sanitizer fills them with zeros that mean "the* endpoint said nothing", not "nothing changed". Promising the fields would* invite a caller to render those zeros as a result.*/@@ -110,6 +110,28 @@ function sanitizeGrokDeviceStart(raw: unknown): GrokDeviceStartView {}}+/**+ * The shape validation is shared with Codex; the brand is not. Routing the Grok+ * endpoints through `sanitizeCodexConnection` made a malformed xAI payload+ * report itself as a Codex failure, which sends the operator to the wrong+ * vendor's dashboard.+ */+function sanitizeGrokConnection(raw: unknown): GrokSubscriptionConnectionView {+ return sanitizeSubscriptionConnection(raw, 'Grok')+}++/**+ * The shared sanitizer resolves the three counters to zero when the payload+ * omits them, which is every Grok response. Narrowing the type alone left the+ * zeros in the returned object, so a caller reading them through a cast — or a+ * test asserting the whole view — still saw counters the endpoint never sent.+ * Dropping them here makes the value match the type it is declared with.+ */+function sanitizeGrokCatalogSync(raw: unknown): GrokCatalogSyncView {+ const view = sanitizeSubscriptionCatalogSync(raw, 'Grok')+ return { outcome: view.outcome, connection: view.connection }+}+function keyedPath(connectionKey: string, action?: string): string {const base = `${GROK_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}`return action ? `${base}/${action}` : base@@ -119,14 +141,16 @@ export async function listGrokSubscriptionConnections(): Promise<GrokSubscriptioconst raw = (await apiGet(`${GROK_SUBSCRIPTION_API_BASE}/connections`)) as {connections?: unknown}- return Array.isArray(raw.connections) ? raw.connections.map(sanitizeCodexConnection) : []+ return Array.isArray(raw.connections)+ ? raw.connections.map(row => sanitizeGrokConnection(row))+ : []}export async function createGrokSubscriptionConnection(input: {displayName: stringconnectionKey?: string}): Promise<GrokSubscriptionConnectionView> {- return sanitizeCodexConnection(+ return sanitizeGrokConnection(await apiSend('POST', `${GROK_SUBSCRIPTION_API_BASE}/connections`, input))}@@ -167,7 +191,7 @@ export async function pollGrokDevice(>assertNoForbiddenKeys(raw)if (raw.status === 'connected') {- return { status: 'connected', connection: sanitizeCodexConnection(raw.connection) }+ return { status: 'connected', connection: sanitizeGrokConnection(raw.connection) }}if (raw.status === 'expired' || raw.status === 'denied') {return { status: raw.status }@@ -185,20 +209,20 @@ export async function pollGrokDevice(export async function syncGrokSubscriptionCatalog(connectionKey: string): Promise<GrokCatalogSyncView> {- return sanitizeCodexCatalogSync(await apiSend('POST', keyedPath(connectionKey, 'catalog/sync')))+ return sanitizeGrokCatalogSync(await apiSend('POST', keyedPath(connectionKey, 'catalog/sync')))}export async function revokeGrokSubscription(connectionKey: string): Promise<GrokSubscriptionConnectionView> {- return sanitizeCodexConnection(await apiSend('POST', keyedPath(connectionKey, 'revoke')))+ return sanitizeGrokConnection(await apiSend('POST', keyedPath(connectionKey, 'revoke')))}export async function patchGrokSubscriptionConnection(connectionKey: string,patch: { displayName?: string; defaultModel?: string | null }): Promise<GrokSubscriptionConnectionView> {- return sanitizeCodexConnection(await apiSend('PATCH', keyedPath(connectionKey), patch))+ return sanitizeGrokConnection(await apiSend('PATCH', keyedPath(connectionKey), patch))}export async function patchGrokCatalogModel(diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 7118ebe17..f00f3900c 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.607",+ "version": "0.1.608","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.607",+ "version": "0.1.608","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/control-ui/package.json b/control-ui/package.jsonindex d4848f328..fb19480cd 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.607",+ "version": "0.1.608","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/packages/llm-providers/index.test.cjs b/packages/llm-providers/index.test.cjsindex 9e4026b5e..83744b5f1 100644--- a/packages/llm-providers/index.test.cjs+++ b/packages/llm-providers/index.test.cjs@@ -99,4 +99,30 @@ describe('provider families', () => {assert.equal(providers.providerDescriptor('codex-subscription').family, 'openai')assert.equal(providers.providerDescriptor('claude').family, 'claude')})++ it('gives each family at most one provider per auth mode', () => {+ // The credential badge control-ui renders per family row+ // (`collapseFamilyRows`) names an auth mode once — `API key`,+ // `Subscription`, or both. Two members sharing an auth mode would make that+ // badge ambiguous about which credential the row refers to, and the UI has+ // no way to disambiguate it. The invariant lives here because this package+ // owns the family map; the consumer cannot enforce it.+ let checkedFamilies = 0+ for (const family of new Set(Object.values(providers.PROVIDER_FAMILY))) {+ const seen = new Map()+ for (const id of providers.familyProviderIds(family)) {+ const { authMode } = providers.providerDescriptor(id)+ assert.equal(+ seen.has(authMode),+ false,+ `family '${family}' has two '${authMode}' providers: '${seen.get(authMode)}' and '${id}'`+ )+ seen.set(authMode, id)+ }+ checkedFamilies += 1+ }+ // Liveness witness: the loop above is satisfied by zero iterations, so a+ // PROVIDER_FAMILY that stopped enumerating anything would read as green.+ assert.equal(checkedFamilies, 22)+ })})