Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): add Grok device OAuth adapter
Jose Gabriel Ramirez Encinas090825030920
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 7744eb931..c9035a7d4 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,14 +1,15 @@{"name": "clerum-control-api",- "version": "0.1.556",+ "version": "0.1.557","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.556",+ "version": "0.1.557","dependencies": {"@clerum/display-field": "file:../packages/display-field",+ "@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract","@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract","@clerum/llm-providers": "file:../packages/llm-providers",@@ -48,6 +49,11 @@"version": "0.1.0","license": "MIT"},+ "../packages/grok-provider-attempt-contract": {+ "name": "@clerum/grok-provider-attempt-contract",+ "version": "0.1.0",+ "license": "MIT"+ },"../packages/image-policy": {"name": "@clerum/image-policy","version": "0.1.0",@@ -88,6 +94,10 @@"resolved": "../packages/display-field","link": true},+ "node_modules/@clerum/grok-provider-attempt-contract": {+ "resolved": "../packages/grok-provider-attempt-contract",+ "link": true+ },"node_modules/@clerum/image-policy": {"resolved": "../packages/image-policy","link": truediff --git a/control-api/package.json b/control-api/package.jsonindex c27919fdd..40ee6816b 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.556",+ "version": "0.1.557","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {@@ -17,6 +17,7 @@},"dependencies": {"@clerum/display-field": "file:../packages/display-field",+ "@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract","@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-provider-attempt-contract": "file:../packages/llm-provider-attempt-contract","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/src/config.ts b/control-api/src/config.tsindex 4e1fcefb3..bcb8002c7 100644--- a/control-api/src/config.ts+++ b/control-api/src/config.ts@@ -123,6 +123,12 @@ type Config = {// Public Codex CLI OAuth client id. Not a secret; PKCE/device flow protect the// grant. Override only to pin a documented registration.codexOAuthClientId: string+ // Default OFF. Grok SuperGrok/coding-plan management stays dark until+ // CONTROL_API_GROK_SUBSCRIPTION_ENABLED=true.+ grokSubscriptionEnabled: boolean+ // Public Grok CLI OAuth client id. Not a secret; device-code flow protects+ // the grant. Override only to pin a documented registration.+ grokOAuthClientId: stringllmCatalogSyncIntervalMs: number// §4.5 sanity guard, layer 3: absolute plausibility floor. If a LIVE run's// TOTAL mapped model count is below this, the whole run SKIPS stale-marking@@ -797,6 +803,9 @@ export const config: Config = {// client id; the default CLI client supports device-code connect only.codexOAuthClientId:process.env.CONTROL_API_CODEX_OAUTH_CLIENT_ID || 'app_EMoamEEZ73f0CkXaXp7hrann',+ grokSubscriptionEnabled: process.env.CONTROL_API_GROK_SUBSCRIPTION_ENABLED === 'true',+ grokOAuthClientId:+ process.env.CONTROL_API_GROK_OAUTH_CLIENT_ID || 'b1a00492-073a-47ea-816f-4c329264a828',// Default 24h. Validated (not merely parsed): the value goes straight into// setInterval and each tick opens a Postgres transaction + advisory lock. A// 60s floor is orders of magnitude below the default and far above a hot loop.diff --git a/control-api/src/services/grokSubscriptionCatalog.ts b/control-api/src/services/grokSubscriptionCatalog.tsnew file mode 100644index 000000000..14dbda8d0--- /dev/null+++ b/control-api/src/services/grokSubscriptionCatalog.ts@@ -0,0 +1,455 @@+import jwt from 'jsonwebtoken'+import { CATALOG_ORIGIN } from '@clerum/grok-provider-attempt-contract'+import { config } from '../config.js'+import type { DbClient } from '../db.js'+import { rootLogger } from '../observability/logger.js'+import {+ type GrokSubscriptionCatalogStatus,+ type GrokSubscriptionConnectionStatus,+ type GrokSubscriptionSafeConnection,+ getSafeGrokSubscriptionConnection,+ isGrokUnassignedConnectionKey,+ readHostGrokConnectionRef,+ recordGrokCatalogOutcome,+} from './grokSubscriptionConnection.js'++const log = rootLogger.child({ module: 'grok-subscription-catalog' })+const PROVIDER = 'grok-subscription'++export const GROK_CATALOG_ORIGIN = CATALOG_ORIGIN++export type GrokCatalogOutcome = 'ready' | 'auth-rejected' | 'unavailable'++export type GrokDiscoveredModel = {+ model: string+ displayName?: string+ contextWindowTokens?: number+}++export type GrokCatalogTransportResult =+ | { outcome: 'ready'; models: GrokDiscoveredModel[] }+ | { outcome: 'auth-rejected' }+ | { outcome: 'unavailable' }++export type GrokCatalogTransport = {+ listModels(input: { accessToken: string }): Promise<GrokCatalogTransportResult>+}++export type GrokCatalogRow = {+ model: string+ source: 'manual' | 'discovery'+ enabled: boolean+ stale: boolean+}++export type GrokCatalogPlan = {+ inserts: GrokDiscoveredModel[]+ refresh: string[]+ stale: string[]+ catalogStatus: GrokCatalogOutcome+ connectionStatus?: Extract<GrokSubscriptionConnectionStatus, 'reauth_required'>+ mutateRows: boolean+}++export function planGrokCatalogReconcile(+ existing: GrokCatalogRow[],+ result: GrokCatalogTransportResult+): GrokCatalogPlan {+ if (result.outcome === 'auth-rejected') {+ return {+ inserts: [],+ refresh: [],+ stale: [],+ catalogStatus: 'auth-rejected',+ connectionStatus: 'reauth_required',+ mutateRows: false,+ }+ }+ if (result.outcome === 'unavailable') {+ return {+ inserts: [],+ refresh: [],+ stale: [],+ catalogStatus: 'unavailable',+ mutateRows: false,+ }+ }++ const discovered = new Map(result.models.map(model => [model.model, model]))+ const inserts: GrokDiscoveredModel[] = []+ const refresh: string[] = []+ const stale: string[] = []+ for (const model of discovered.values()) {+ const row = existing.find(candidate => candidate.model === model.model)+ if (!row) {+ inserts.push(model)+ continue+ }+ if (row.source === 'manual') continue+ refresh.push(row.model)+ }+ for (const row of existing) {+ if (row.source !== 'discovery') continue+ if (!discovered.has(row.model)) stale.push(row.model)+ }+ return {+ inserts,+ refresh,+ stale,+ catalogStatus: 'ready',+ mutateRows: true,+ }+}++export async function getGrokCatalogModelState(+ db: DbClient,+ connectionId: string,+ model: string+): Promise<{ enabled: boolean; stale: boolean } | null> {+ const result = await db.query(+ `SELECT enabled, stale+ FROM grok_catalog_models+ WHERE connection_id = $1+ AND model = $2+ LIMIT 1`,+ [connectionId, model]+ )+ const row = result.rows[0] as { enabled?: boolean; stale?: boolean } | undefined+ if (!row) return null+ return { enabled: row.enabled === true, stale: row.stale === true }+}++export async function isGrokAssignmentAllowed(+ db: DbClient,+ connectionRef: string,+ model: string+): Promise<boolean> {+ const key = readHostGrokConnectionRef(connectionRef)+ if (isGrokUnassignedConnectionKey(key)) return false+ const connection = await getSafeGrokSubscriptionConnection(db, key)+ if (+ !connection ||+ connection.status !== 'connected' ||+ connection.revokedAt ||+ connection.catalogStatus !== 'ready'+ ) {+ return false+ }+ const state = await getGrokCatalogModelState(db, connection.id, model)+ return Boolean(state?.enabled && !state.stale)+}++export function pickGrokGrantModel(+ current: string,+ offered: string[],+ grantDefault?: string | null+): string {+ const trimmed = current.trim()+ if (trimmed && offered.includes(trimmed)) return trimmed+ const fallback = grantDefault?.trim() ?? ''+ if (fallback && offered.includes(fallback)) return fallback+ return offered[0] ?? ''+}++export async function listOfferedGrokModelsForAssignment(+ db: DbClient,+ connectionKey: string+): Promise<string[]> {+ const result = await db.query(+ `SELECT m.model+ FROM grok_catalog_models m+ JOIN grok_subscription_connections c ON c.id = m.connection_id+ WHERE c.connection_key = $1+ AND c.revoked_at IS NULL+ AND c.status = 'connected'+ AND c.catalog_status = 'ready'+ AND m.enabled+ AND m.stale = false+ ORDER BY m.model ASC`,+ [connectionKey]+ )+ return (result.rows as Array<{ model: string }>).map(row => String(row.model))+}++export async function listGrokCatalogModels(+ db: DbClient,+ connectionId: string+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {+ const result = await db.query(+ `SELECT model, enabled, stale+ FROM grok_catalog_models+ WHERE connection_id = $1+ ORDER BY model ASC`,+ [connectionId]+ )+ return (result.rows as Array<Record<string, unknown>>).map(row => ({+ model: String(row.model),+ enabled: row.enabled === true,+ stale: row.stale === true,+ }))+}++export async function setGrokCatalogModelEnabled(+ db: DbClient,+ connectionId: string,+ model: string,+ enabled: boolean+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }> | null> {+ const updated = await db.query(+ `UPDATE grok_catalog_models+ SET enabled = $3,+ updated_at = now()+ WHERE connection_id = $1+ AND model = $2+ RETURNING model`,+ [connectionId, model, enabled]+ )+ if (updated.rowCount === 0) return null+ if (!enabled) {+ await db.query(+ `UPDATE grok_subscription_connections+ SET default_model = NULL,+ updated_at = now()+ WHERE id = $1+ AND default_model = $2+ AND revoked_at IS NULL`,+ [connectionId, model]+ )+ }+ await rebuildLiveGrokUnionAllowlist(db)+ return listGrokCatalogModels(db, connectionId)+}++export async function rebuildLiveGrokUnionAllowlist(db: DbClient): Promise<void> {+ await db.query(+ `INSERT INTO llm_allowed_models+ (provider, model, enabled, source, stale, display_name, context_window_tokens, vendor, last_seen_at)+ SELECT $1, m.model, true, 'discovery', false,+ MIN(m.display_name), MAX(m.context_window_tokens), 'xAI', NOW()+ FROM grok_catalog_models m+ JOIN grok_subscription_connections c ON c.id = m.connection_id+ WHERE c.revoked_at IS NULL+ AND m.enabled+ AND m.stale = false+ GROUP BY m.model+ ON CONFLICT (provider, model) DO UPDATE+ SET enabled = true,+ stale = false,+ last_seen_at = NOW()`,+ [PROVIDER]+ )+ await db.query(+ `UPDATE llm_allowed_models+ SET enabled = false,+ stale = true+ WHERE provider = $1+ AND model NOT IN (+ SELECT DISTINCT m.model+ FROM grok_catalog_models m+ JOIN grok_subscription_connections c ON c.id = m.connection_id+ WHERE c.revoked_at IS NULL+ AND m.enabled+ AND m.stale = false+ )`,+ [PROVIDER]+ )+}++export async function syncGrokSubscriptionCatalog(+ db: DbClient,+ transport: GrokCatalogTransport,+ accessToken: string,+ expected: { credentialRevision?: number; catalogRevision?: number; connectionKey: string }+): Promise<{+ outcome: GrokCatalogOutcome+ connection: GrokSubscriptionSafeConnection | null+ added: number+ refreshed: number+ staled: number+}> {+ const connection = await getSafeGrokSubscriptionConnection(db, expected.connectionKey)+ if (!connection || connection.status === 'revoked' || connection.status === 'disconnected') {+ throw new Error('grok_subscription_not_connected')+ }+ const expectedCredentialRevision = expected.credentialRevision ?? connection.credentialRevision+ const expectedCatalogRevision = expected.catalogRevision ?? connection.catalogRevision+ const result = await transport.listModels({ accessToken })+ const existing = await loadGrokRows(db, connection.id)+ const plan = planGrokCatalogReconcile(existing, result)+ const recorded = await recordGrokCatalogOutcome(db, {+ catalogStatus: plan.catalogStatus as GrokSubscriptionCatalogStatus,+ connectionStatus: plan.connectionStatus,+ expectedCredentialRevision,+ expectedCatalogRevision,+ connectionKey: expected.connectionKey,+ })+ let added = 0+ let refreshed = 0+ let staled = 0+ if (recorded && plan.mutateRows) {+ added = await insertDiscovered(db, connection.id, plan.inserts)+ refreshed = await refreshDiscovered(db, connection.id, plan.refresh)+ staled = await staleMissing(db, connection.id, plan.stale)+ await rebuildLiveGrokUnionAllowlist(db)+ }+ if (!recorded) {+ log.warn(+ { event: 'grok_catalog_stale_writer' },+ 'catalog outcome lost the connection revision race'+ )+ } else {+ log.info(+ {+ event: 'grok_catalog_reconciled',+ outcome: plan.catalogStatus,+ added,+ refreshed,+ staled,+ },+ 'Grok catalog reconciled'+ )+ }+ return {+ outcome: plan.catalogStatus,+ connection: recorded,+ added,+ refreshed,+ staled,+ }+}++export function createUnavailableGrokCatalogTransport(): GrokCatalogTransport {+ return {+ async listModels() {+ return { outcome: 'unavailable' }+ },+ }+}++export function signGrokAdminPermit(operation: 'catalog_list' | 'connection_test'): string {+ return jwt.sign(+ { sub: 'control-api', typ: 'grok-admin-permit', operation },+ config.adminJwtPrivateKey,+ {+ algorithm: 'RS256',+ issuer: config.adminJwtIssuer,+ audience: 'grok-llm-proxy-admin',+ expiresIn: 60,+ }+ )+}++export function createGrokProxyCatalogTransport(deps: {+ adminBaseUrl: string+ fetchFn?: typeof fetch+ signPermit?: (operation: 'catalog_list' | 'connection_test') => string+}): GrokCatalogTransport {+ const fetchFn = deps.fetchFn ?? fetch+ const signPermit = deps.signPermit ?? signGrokAdminPermit+ return {+ async listModels(input: { accessToken: string }): Promise<GrokCatalogTransportResult> {+ const base = deps.adminBaseUrl.replace(/\/+$/, '')+ let response: Response+ try {+ response = await fetchFn(`${base}/internal/admin/v1/grok/models`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ authorization: `Bearer ${signPermit('catalog_list')}`,+ },+ body: JSON.stringify({ accessToken: input.accessToken }),+ })+ } catch (err) {+ log.warn({ event: 'grok_catalog_proxy_unreachable', err }, 'Grok catalog proxy unreachable')+ return { outcome: 'unavailable' }+ }+ if (!response.ok) {+ if (response.status === 401 || response.status === 403) return { outcome: 'auth-rejected' }+ return { outcome: 'unavailable' }+ }+ const body = (await response.json()) as {+ outcome?: GrokCatalogOutcome+ models?: GrokDiscoveredModel[]+ }+ if (body.outcome === 'auth-rejected' || body.outcome === 'unavailable') {+ return { outcome: body.outcome }+ }+ return { outcome: 'ready', models: Array.isArray(body.models) ? body.models : [] }+ },+ }+}++export function createGrokCatalogTransportFromEnv(+ env: NodeJS.ProcessEnv = process.env+): GrokCatalogTransport {+ const adminBaseUrl = env.GROK_LLM_PROXY_ADMIN_URL?.trim() ?? ''+ if (!adminBaseUrl) return createUnavailableGrokCatalogTransport()+ return createGrokProxyCatalogTransport({ adminBaseUrl })+}++async function loadGrokRows(db: DbClient, connectionId: string): Promise<GrokCatalogRow[]> {+ const result = await db.query(+ `SELECT model, source, enabled, stale+ FROM grok_catalog_models+ WHERE connection_id = $1`,+ [connectionId]+ )+ return (result.rows as Array<Record<string, unknown>>).map(row => ({+ model: String(row.model),+ source: row.source === 'manual' ? 'manual' : 'discovery',+ enabled: row.enabled === true,+ stale: row.stale === true,+ }))+}++async function insertDiscovered(+ db: DbClient,+ connectionId: string,+ models: GrokDiscoveredModel[]+): Promise<number> {+ let added = 0+ for (const model of models) {+ const result = await db.query(+ `INSERT INTO grok_catalog_models+ (connection_id, model, enabled, source, discovered_at, last_seen_at, stale, display_name, context_window_tokens)+ VALUES ($1, $2, true, 'discovery', NOW(), NOW(), false, $3, $4)+ ON CONFLICT (connection_id, model) DO NOTHING`,+ [connectionId, model.model, model.displayName ?? null, model.contextWindowTokens ?? null]+ )+ added += result.rowCount ?? 0+ }+ return added+}++async function refreshDiscovered(+ db: DbClient,+ connectionId: string,+ models: string[]+): Promise<number> {+ if (models.length === 0) return 0+ const result = await db.query(+ `UPDATE grok_catalog_models+ SET last_seen_at = NOW(),+ stale = false,+ updated_at = NOW()+ WHERE connection_id = $1+ AND source = 'discovery'+ AND model = ANY($2::text[])`,+ [connectionId, models]+ )+ return result.rowCount ?? 0+}++async function staleMissing(db: DbClient, connectionId: string, models: string[]): Promise<number> {+ if (models.length === 0) return 0+ const result = await db.query(+ `UPDATE grok_catalog_models+ SET stale = true,+ updated_at = NOW()+ WHERE connection_id = $1+ AND source = 'discovery'+ AND model = ANY($2::text[])`,+ [connectionId, models]+ )+ return result.rowCount ?? 0+}diff --git a/control-api/src/services/grokSubscriptionConnection.ts b/control-api/src/services/grokSubscriptionConnection.tsnew file mode 100644index 000000000..d84a2d4b6--- /dev/null+++ b/control-api/src/services/grokSubscriptionConnection.ts@@ -0,0 +1,644 @@+import type { DbClient } from '../db.js'+import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'+import {+ generateGrokConnectionKey,+ assertGrokConnectionKey as parseGrokConnectionKey,+} from './grokSubscriptionSchema.js'++export { generateGrokConnectionKey }++/** Fail-closed Host sentinel. Not a grant row; never maps to deployment-default. */+export const GROK_UNASSIGNED_CONNECTION_KEY = 'unassigned' as const+export const GROK_RESERVED_DEPLOYMENT_DEFAULT_KEY = 'deployment-default' as const++export const GROK_CONNECTION_REF_ANNOTATION = 'clerum.io/subscription-connection-ref' as const++export function isGrokUnassignedConnectionKey(value?: string | null): boolean {+ return typeof value === 'string' && value.trim() === GROK_UNASSIGNED_CONNECTION_KEY+}++/**+ * Host spec reader. Empty/missing is `unassigned`. Grok never aliases empty+ * to `deployment-default`.+ */+export function readHostGrokConnectionRef(value?: string | null): string {+ const trimmed = typeof value === 'string' ? value.trim() : ''+ if (!trimmed) return GROK_UNASSIGNED_CONNECTION_KEY+ return trimmed+}++export class GrokSubscriptionInvalidConnectionKeyError extends Error {+ readonly code = 'invalid_connection_key'++ constructor(key: string) {+ super(`Grok subscription connection key is invalid: ${key}`)+ this.name = 'GrokSubscriptionInvalidConnectionKeyError'+ }+}++export function assertGrokConnectionKey(value: string): string {+ try {+ return parseGrokConnectionKey(value)+ } catch {+ throw new GrokSubscriptionInvalidConnectionKeyError(value.trim())+ }+}++export class GrokSubscriptionFingerprintConflictError extends Error {+ readonly code = 'fingerprint_in_use'++ constructor() {+ super('A live Grok subscription already uses this account')+ this.name = 'GrokSubscriptionFingerprintConflictError'+ }+}++export class GrokSubscriptionStaleRevisionError extends Error {+ readonly code = 'grok_subscription_stale_revision'++ constructor() {+ super('Grok subscription credential revision is stale')+ this.name = 'GrokSubscriptionStaleRevisionError'+ }+}++export type GrokSubscriptionConnectionStatus =+ | 'disconnected'+ | 'connecting'+ | 'connected'+ | 'reauth_required'+ | 'revoked'++export type GrokSubscriptionCatalogStatus =+ | 'never_synced'+ | 'ready'+ | 'auth-rejected'+ | 'unavailable'++export type GrokSubscriptionSafeConnection = {+ id: string+ connectionKey: string+ displayName: string+ defaultModel: string | null+ createdBy: string | null+ status: GrokSubscriptionConnectionStatus+ credentialRevision: number+ catalogRevision: number+ accountFingerprint: string | null+ catalogStatus: GrokSubscriptionCatalogStatus+ catalogSyncedAt: Date | null+ lastRefreshAt: Date | null+ lastAuthAt: Date | null+ refreshLockHeld: boolean+ revokedAt: Date | null+ createdAt: Date+ updatedAt: Date+}++export type GrokSubscriptionCredentialWrite = {+ refreshToken: string+ accessToken?: string | null+ accessTokenExpiresAt?: Date | null+ accountFingerprint: string+ status?: Extract<GrokSubscriptionConnectionStatus, 'connected' | 'reauth_required'>+}++export type GrokSubscriptionSecrets = {+ refreshToken: string+ accessToken: string | null+ accessTokenExpiresAt: Date | null+ credentialRevision: number+}++type SafeConnectionRow = {+ id: string+ connection_key: string+ display_name: string | null+ default_model: string | null+ created_by: string | null+ status: GrokSubscriptionConnectionStatus+ credential_revision: string | number+ catalog_revision: string | number+ account_fingerprint: string | null+ catalog_status: GrokSubscriptionCatalogStatus+ catalog_synced_at: Date | string | null+ last_refresh_at: Date | string | null+ last_auth_at: Date | string | null+ refresh_lock_token: string | null+ refresh_lock_expires_at: Date | string | null+ revoked_at: Date | string | null+ created_at: Date | string+ updated_at: Date | string+}++const SAFE_CONNECTION_COLUMNS = `+ id,+ connection_key,+ display_name,+ default_model,+ created_by,+ status,+ credential_revision,+ catalog_revision,+ account_fingerprint,+ catalog_status,+ catalog_synced_at,+ last_refresh_at,+ last_auth_at,+ refresh_lock_token,+ refresh_lock_expires_at,+ revoked_at,+ created_at,+ updated_at+`++export async function getSafeGrokSubscriptionConnection(+ db: DbClient,+ connectionKey: string+): Promise<GrokSubscriptionSafeConnection | null> {+ const key = assertGrokConnectionKey(connectionKey)+ const result = await db.query(+ `SELECT ${SAFE_CONNECTION_COLUMNS}+ FROM grok_subscription_connections+ WHERE connection_key = $1+ AND revoked_at IS NULL`,+ [key]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ return row ? toSafeConnection(row) : null+}++export async function getSafeGrokSubscriptionConnectionById(+ db: DbClient,+ connectionId: string+): Promise<GrokSubscriptionSafeConnection | null> {+ const result = await db.query(+ `SELECT ${SAFE_CONNECTION_COLUMNS}+ FROM grok_subscription_connections+ WHERE id = $1`,+ [connectionId]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ return row ? toSafeConnection(row) : null+}++export async function listSafeGrokSubscriptionConnections(+ db: DbClient+): Promise<GrokSubscriptionSafeConnection[]> {+ const result = await db.query(+ `SELECT ${SAFE_CONNECTION_COLUMNS}+ FROM grok_subscription_connections+ ORDER BY created_at ASC, connection_key ASC`+ )+ return (result.rows as SafeConnectionRow[]).map(toSafeConnection)+}++export async function listLiveGrokSubscriptionConnections(+ db: DbClient+): Promise<GrokSubscriptionSafeConnection[]> {+ const result = await db.query(+ `SELECT ${SAFE_CONNECTION_COLUMNS}+ FROM grok_subscription_connections+ WHERE revoked_at IS NULL+ ORDER BY created_at ASC, connection_key ASC`+ )+ return (result.rows as SafeConnectionRow[]).map(toSafeConnection)+}++export async function createNamedGrokSubscriptionConnection(+ db: DbClient,+ input: { connectionKey: string; displayName: string; createdBy?: string | null }+): Promise<GrokSubscriptionSafeConnection> {+ const connectionKey = assertGrokConnectionKey(input.connectionKey)+ const displayName = input.displayName.trim() || connectionKey+ const result = await db.query(+ `INSERT INTO grok_subscription_connections (+ connection_key,+ display_name,+ created_by,+ status,+ credential_revision,+ catalog_revision,+ catalog_status+ ) VALUES ($1, $2, $3, 'disconnected', 1, 0, 'never_synced')+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [connectionKey, displayName, input.createdBy ?? null]+ )+ return toSafeConnection(result.rows[0] as SafeConnectionRow)+}++export async function insertInitialGrokSubscriptionConnection(+ db: DbClient,+ encryptionKey: Buffer,+ input: GrokSubscriptionCredentialWrite,+ connectionKey: string+): Promise<GrokSubscriptionSafeConnection> {+ const key = assertGrokConnectionKey(connectionKey)+ const refreshTokenEncrypted = encryptOAuthSecret(encryptionKey, input.refreshToken)+ const accessTokenEncrypted =+ input.accessToken == null || input.accessToken === ''+ ? null+ : encryptOAuthSecret(encryptionKey, input.accessToken)+ try {+ const result = await db.query(+ `INSERT INTO grok_subscription_connections (+ connection_key,+ display_name,+ status,+ refresh_token_encrypted,+ access_token_encrypted,+ access_token_expires_at,+ credential_revision,+ catalog_revision,+ account_fingerprint,+ catalog_status,+ last_auth_at+ ) VALUES ($1, $2, $3, $4, $5, $6, 1, 0, $7, 'never_synced', now())+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [+ key,+ key,+ input.status ?? 'connected',+ refreshTokenEncrypted,+ accessTokenEncrypted,+ input.accessTokenExpiresAt ?? null,+ input.accountFingerprint,+ ]+ )+ return toSafeConnection(result.rows[0] as SafeConnectionRow)+ } catch (err) {+ throw remapFingerprintConflict(err)+ }+}++export async function rotateGrokSubscriptionCredentials(+ db: DbClient,+ encryptionKey: Buffer,+ expectedRevision: number,+ input: GrokSubscriptionCredentialWrite,+ connectionKey: string+): Promise<GrokSubscriptionSafeConnection> {+ const key = assertGrokConnectionKey(connectionKey)+ const refreshTokenEncrypted = encryptOAuthSecret(encryptionKey, input.refreshToken)+ const accessTokenEncrypted =+ input.accessToken == null || input.accessToken === ''+ ? null+ : encryptOAuthSecret(encryptionKey, input.accessToken)+ try {+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET refresh_token_encrypted = $1,+ access_token_encrypted = $2,+ access_token_expires_at = $3,+ account_fingerprint = $4,+ status = $5,+ credential_revision = credential_revision + 1,+ last_refresh_at = now(),+ last_auth_at = now(),+ updated_at = now()+ WHERE connection_key = $6+ AND credential_revision = $7+ AND revoked_at IS NULL+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [+ refreshTokenEncrypted,+ accessTokenEncrypted,+ input.accessTokenExpiresAt ?? null,+ input.accountFingerprint,+ input.status ?? 'connected',+ key,+ expectedRevision,+ ]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ if (!row) throw new GrokSubscriptionStaleRevisionError()+ return toSafeConnection(row)+ } catch (err) {+ throw remapFingerprintConflict(err)+ }+}++/**+ * Persist a rotated refresh ciphertext before any fallible post-processing.+ * Fenced on the live refresh lock and credential_revision; does not bump+ * revision (issued tickets bind that integer).+ */+export async function persistGrokRefreshCiphertextFirst(+ db: DbClient,+ encryptionKey: Buffer,+ input: {+ connectionKey: string+ expectedRevision: number+ lockToken: string+ refreshToken: string+ }+): Promise<GrokSubscriptionSafeConnection> {+ const key = assertGrokConnectionKey(input.connectionKey)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET refresh_token_encrypted = $1,+ last_refresh_at = now(),+ updated_at = now()+ WHERE connection_key = $2+ AND credential_revision = $3+ AND refresh_lock_token = $4+ AND refresh_lock_expires_at IS NOT NULL+ AND refresh_lock_expires_at > now()+ AND revoked_at IS NULL+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [+ encryptOAuthSecret(encryptionKey, input.refreshToken),+ key,+ input.expectedRevision,+ input.lockToken,+ ]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ if (!row) throw new GrokSubscriptionStaleRevisionError()+ return toSafeConnection(row)+}++export async function markGrokRefreshSubjectMismatch(+ db: DbClient,+ connectionKey: string,+ expectedRevision: number+): Promise<GrokSubscriptionSafeConnection | null> {+ const key = assertGrokConnectionKey(connectionKey)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET status = 'reauth_required',+ updated_at = now()+ WHERE connection_key = $1+ AND credential_revision = $2+ AND revoked_at IS NULL+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [key, expectedRevision]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ return row ? toSafeConnection(row) : null+}++export async function revokeGrokSubscriptionConnection(+ db: DbClient,+ connectionKey: string+): Promise<GrokSubscriptionSafeConnection | null> {+ const key = assertGrokConnectionKey(connectionKey)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET status = 'revoked',+ refresh_token_encrypted = NULL,+ access_token_encrypted = NULL,+ access_token_expires_at = NULL,+ catalog_status = 'never_synced',+ credential_revision = credential_revision + 1,+ refresh_lock_token = NULL,+ refresh_lock_expires_at = NULL,+ revoked_at = now(),+ updated_at = now()+ WHERE connection_key = $1+ AND revoked_at IS NULL+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [key]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ if (!row) return getSafeGrokSubscriptionConnection(db, key)+ await db.query(+ `UPDATE grok_catalog_models+ SET enabled = false,+ stale = true+ WHERE connection_id = $1`,+ [row.id]+ )+ return toSafeConnection(row)+}++export async function acquireGrokSubscriptionRefreshLock(+ db: DbClient,+ lockToken: string,+ ttlMs: number,+ connectionKey: string+): Promise<boolean> {+ const key = assertGrokConnectionKey(connectionKey)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET refresh_lock_token = $1,+ refresh_lock_expires_at = now() + ($2 * interval '1 millisecond'),+ updated_at = now()+ WHERE connection_key = $3+ AND revoked_at IS NULL+ AND (+ refresh_lock_token IS NULL+ OR refresh_lock_expires_at IS NULL+ OR refresh_lock_expires_at <= now()+ )+ RETURNING refresh_lock_token`,+ [lockToken, ttlMs, key]+ )+ return (result.rowCount ?? 0) > 0+}++export async function releaseGrokSubscriptionRefreshLock(+ db: DbClient,+ lockToken: string,+ connectionKey: string+): Promise<boolean> {+ const key = assertGrokConnectionKey(connectionKey)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET refresh_lock_token = NULL,+ refresh_lock_expires_at = NULL,+ updated_at = now()+ WHERE connection_key = $1+ AND refresh_lock_token = $2`,+ [key, lockToken]+ )+ return (result.rowCount ?? 0) > 0+}++export async function loadGrokSubscriptionSecrets(+ db: DbClient,+ encryptionKey: Buffer,+ connectionKey: string+): Promise<GrokSubscriptionSecrets | null> {+ const key = assertGrokConnectionKey(connectionKey)+ const result = await db.query(+ `SELECT refresh_token_encrypted,+ access_token_encrypted,+ access_token_expires_at,+ credential_revision+ FROM grok_subscription_connections+ WHERE connection_key = $1+ AND revoked_at IS NULL`,+ [key]+ )+ const row = result.rows[0] as+ | {+ refresh_token_encrypted: string | null+ access_token_encrypted: string | null+ access_token_expires_at: Date | string | null+ credential_revision: string | number+ }+ | undefined+ if (!row?.refresh_token_encrypted) return null+ return {+ refreshToken: decryptOAuthSecret(encryptionKey, row.refresh_token_encrypted),+ accessToken: row.access_token_encrypted+ ? decryptOAuthSecret(encryptionKey, row.access_token_encrypted)+ : null,+ accessTokenExpiresAt: asDate(row.access_token_expires_at),+ credentialRevision: Number(row.credential_revision),+ }+}++export async function updateGrokAccessTokenInPlace(+ db: DbClient,+ encryptionKey: Buffer,+ expectedRevision: number,+ input: {+ accessToken: string+ accessTokenExpiresAt?: Date | null+ },+ connectionKey: string,+ lockToken?: string+): Promise<GrokSubscriptionSafeConnection> {+ const key = assertGrokConnectionKey(connectionKey)+ const params: unknown[] = [+ encryptOAuthSecret(encryptionKey, input.accessToken),+ input.accessTokenExpiresAt ?? null,+ key,+ expectedRevision,+ ]+ const lockFence = lockToken+ ? `AND refresh_lock_token = $5+ AND refresh_lock_expires_at IS NOT NULL+ AND refresh_lock_expires_at > now()`+ : ''+ if (lockToken) params.push(lockToken)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET access_token_encrypted = $1,+ access_token_expires_at = $2,+ last_refresh_at = now(),+ updated_at = now()+ WHERE connection_key = $3+ AND credential_revision = $4+ AND revoked_at IS NULL+ ${lockFence}+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ params+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ if (!row) throw new GrokSubscriptionStaleRevisionError()+ return toSafeConnection(row)+}++export async function recordGrokCatalogOutcome(+ db: DbClient,+ input: {+ catalogStatus: GrokSubscriptionCatalogStatus+ connectionStatus?: GrokSubscriptionConnectionStatus+ expectedCredentialRevision: number+ expectedCatalogRevision: number+ connectionKey: string+ }+): Promise<GrokSubscriptionSafeConnection | null> {+ const key = assertGrokConnectionKey(input.connectionKey)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET catalog_status = $1,+ status = COALESCE($2, status),+ catalog_revision = catalog_revision + 1,+ catalog_synced_at = now(),+ updated_at = now()+ WHERE connection_key = $3+ AND credential_revision = $4+ AND catalog_revision = $5+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ [+ input.catalogStatus,+ input.connectionStatus ?? null,+ key,+ input.expectedCredentialRevision,+ input.expectedCatalogRevision,+ ]+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ return row ? toSafeConnection(row) : null+}++export async function updateGrokSubscriptionConnectionMetadata(+ db: DbClient,+ connectionKey: string,+ patch: { displayName?: string; defaultModel?: string | null }+): Promise<GrokSubscriptionSafeConnection | null> {+ const key = assertGrokConnectionKey(connectionKey)+ const sets: string[] = ['updated_at = now()']+ const values: unknown[] = []+ if (typeof patch.displayName === 'string') {+ values.push(patch.displayName.trim() || key)+ sets.push(`display_name = $${values.length}`)+ }+ if (patch.defaultModel !== undefined) {+ const next = typeof patch.defaultModel === 'string' ? patch.defaultModel.trim() : ''+ values.push(next || null)+ sets.push(`default_model = $${values.length}`)+ }+ if (values.length === 0) {+ return getSafeGrokSubscriptionConnection(db, key)+ }+ values.push(key)+ const result = await db.query(+ `UPDATE grok_subscription_connections+ SET ${sets.join(', ')}+ WHERE connection_key = $${values.length}+ AND revoked_at IS NULL+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,+ values+ )+ const row = result.rows[0] as SafeConnectionRow | undefined+ return row ? toSafeConnection(row) : null+}++function remapFingerprintConflict(err: unknown): never | Error {+ const conflict = err as { code?: string; constraint?: string } | null+ if (+ conflict?.code === '23505' &&+ conflict.constraint === 'grok_subscription_connections_active_fingerprint'+ ) {+ return new GrokSubscriptionFingerprintConflictError()+ }+ throw err+}++function toSafeConnection(row: SafeConnectionRow): GrokSubscriptionSafeConnection {+ return {+ id: String(row.id),+ connectionKey: row.connection_key,+ displayName: row.display_name?.trim() || row.connection_key,+ defaultModel: row.default_model?.trim() || null,+ createdBy: row.created_by,+ status: row.status,+ credentialRevision: Number(row.credential_revision),+ catalogRevision: Number(row.catalog_revision),+ accountFingerprint: row.account_fingerprint,+ catalogStatus: row.catalog_status,+ catalogSyncedAt: asDate(row.catalog_synced_at),+ lastRefreshAt: asDate(row.last_refresh_at),+ lastAuthAt: asDate(row.last_auth_at),+ refreshLockHeld: isLockHeld(row.refresh_lock_token, row.refresh_lock_expires_at),+ revokedAt: asDate(row.revoked_at),+ createdAt: asDate(row.created_at) ?? new Date(0),+ updatedAt: asDate(row.updated_at) ?? new Date(0),+ }+}++function isLockHeld(token: string | null, expiresAt: Date | string | null): boolean {+ if (!token) return false+ const expires = asDate(expiresAt)+ return expires !== null && expires.getTime() > Date.now()+}++function asDate(value: Date | string | null | undefined): Date | null {+ if (value == null) return null+ return value instanceof Date ? value : new Date(value)+}diff --git a/control-api/src/services/grokSubscriptionOAuth.ts b/control-api/src/services/grokSubscriptionOAuth.tsnew file mode 100644index 000000000..606a0ca97--- /dev/null+++ b/control-api/src/services/grokSubscriptionOAuth.ts@@ -0,0 +1,757 @@+import { createHash, randomBytes } from 'node:crypto'+import type { DbClient } from '../db.js'+import { rootLogger } from '../observability/logger.js'+import {+ type GrokCatalogOutcome,+ type GrokCatalogTransport,+ rebuildLiveGrokUnionAllowlist,+ syncGrokSubscriptionCatalog,+} from './grokSubscriptionCatalog.js'+import {+ GrokSubscriptionFingerprintConflictError,+ type GrokSubscriptionSafeConnection,+ GrokSubscriptionStaleRevisionError,+ acquireGrokSubscriptionRefreshLock,+ assertGrokConnectionKey,+ getSafeGrokSubscriptionConnection,+ insertInitialGrokSubscriptionConnection,+ loadGrokSubscriptionSecrets,+ markGrokRefreshSubjectMismatch,+ persistGrokRefreshCiphertextFirst,+ releaseGrokSubscriptionRefreshLock,+ revokeGrokSubscriptionConnection,+ rotateGrokSubscriptionCredentials,+ updateGrokAccessTokenInPlace,+} from './grokSubscriptionConnection.js'+import {+ type GrokSubscriptionOAuthIntent,+ type GrokSubscriptionOAuthSafeState,+ cancelGrokSubscriptionOAuthState,+ consumeGrokSubscriptionOAuthState,+ expireGrokSubscriptionOAuthState,+ insertGrokSubscriptionOAuthState,+ peekPendingGrokSubscriptionOAuthState,+} from './grokSubscriptionOAuthState.js'++const log = rootLogger.child({ module: 'grok-subscription-oauth' })++export const GROK_OAUTH_DEVICE_URL = 'https://auth.x.ai/oauth2/device/code'+export const GROK_OAUTH_TOKEN_URL = 'https://auth.x.ai/oauth2/token'+export const GROK_OAUTH_REVOKE_URL = 'https://auth.x.ai/oauth2/revoke'+export const GROK_OAUTH_DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code'+export const GROK_OAUTH_SCOPES = [+ 'openid',+ 'profile',+ 'email',+ 'offline_access',+ 'grok-cli:access',+ 'api:access',+ 'conversations:read',+ 'conversations:write',+] as const+export const GROK_OAUTH_DEFAULT_CLIENT_ID = 'b1a00492-073a-47ea-816f-4c329264a828'++const DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60+const TOKEN_TIMEOUT_MS = 15_000+const REFRESH_LOCK_TTL_MS = 30_000+const REFRESH_LOCK_POLL_MS = 200+const ACCESS_TOKEN_REFRESH_SKEW_MS = 5 * 60_000++function accessTokenIsUsable(secrets: {+ accessToken?: string | null+ accessTokenExpiresAt?: Date | null+}): boolean {+ if (!secrets.accessToken) return false+ return secrets.accessTokenExpiresAt == null || secrets.accessTokenExpiresAt.getTime() > Date.now()+}++function sleep(ms: number): Promise<void> {+ return new Promise(resolve => setTimeout(resolve, ms))+}++export type GrokOAuthErrorCode =+ | 'disabled'+ | 'not_connected'+ | 'state_replayed'+ | 'state_expired'+ | 'state_cancelled'+ | 'replacement_required'+ | 'stale_revision'+ | 'refresh_in_flight'+ | 'provider_unavailable'+ | 'no_grant'+ | 'invalid_callback'+ | 'fingerprint_in_use'+ | 'connection_mismatch'+ | 'reauth_required'++const GROK_OAUTH_ERROR_CODES: ReadonlySet<GrokOAuthErrorCode> = new Set([+ 'disabled',+ 'not_connected',+ 'state_replayed',+ 'state_expired',+ 'state_cancelled',+ 'replacement_required',+ 'stale_revision',+ 'refresh_in_flight',+ 'provider_unavailable',+ 'no_grant',+ 'invalid_callback',+ 'fingerprint_in_use',+ 'connection_mismatch',+ 'reauth_required',+])++export function isGrokOAuthErrorCode(value: string): value is GrokOAuthErrorCode {+ return GROK_OAUTH_ERROR_CODES.has(value as GrokOAuthErrorCode)+}++export class GrokSubscriptionOAuthError extends Error {+ readonly code: GrokOAuthErrorCode++ constructor(code: GrokOAuthErrorCode, message: string) {+ super(message)+ this.name = 'GrokSubscriptionOAuthError'+ this.code = code+ }+}++export type GrokOAuthDeps = {+ db: DbClient+ encryptionKey: Buffer+ fetchFn: typeof fetch+ clientId: string+ enabled: boolean+ connectionKey: string+}++function connectionKeyOf(deps: GrokOAuthDeps): string {+ return assertGrokConnectionKey(deps.connectionKey)+}++function completionConnectionKey(deps: GrokOAuthDeps, stateKey: string): string {+ const target = assertGrokConnectionKey(stateKey)+ const requested = connectionKeyOf(deps)+ if (requested !== target) {+ log.warn(+ { event: 'grok_oauth_connection_mismatch', requested, target },+ 'OAuth completion key does not match the state'+ )+ throw new GrokSubscriptionOAuthError(+ 'connection_mismatch',+ 'OAuth state is bound to a different connection'+ )+ }+ return target+}++function requireEnabled(deps: GrokOAuthDeps): void {+ if (!deps.enabled) {+ throw new GrokSubscriptionOAuthError('disabled', 'Grok subscription is disabled')+ }+}++export type GrokDeviceStartResult = {+ userCode: string+ verificationUri: string+ verificationUriComplete: string | null+ intervalSeconds: number+ expiresAt: Date+ state: string+ intent: GrokSubscriptionOAuthIntent+}++export type GrokDevicePollResult =+ | {+ status: 'pending' | 'slow_down'+ intervalSeconds: number+ state: GrokSubscriptionOAuthSafeState+ }+ | { status: 'expired' | 'denied' }+ | { status: 'connected'; connection: GrokSubscriptionSafeConnection }++export type GrokCatalogSyncResult = {+ ok: boolean+ catalogStatus: GrokCatalogOutcome | 'never_synced'+ reason?: GrokOAuthErrorCode | 'catalog_sync_failed' | 'stale_revision' | 'no_grant'+}++export async function getGrokSubscriptionConnection(+ deps: GrokOAuthDeps+): Promise<GrokSubscriptionSafeConnection | { connectionKey: string; status: 'disconnected' }> {+ requireEnabled(deps)+ const row = await getSafeGrokSubscriptionConnection(deps.db, connectionKeyOf(deps))+ return row ?? { connectionKey: connectionKeyOf(deps), status: 'disconnected' }+}++export async function startGrokDeviceConnect(+ deps: GrokOAuthDeps,+ intent: GrokSubscriptionOAuthIntent = 'connect'+): Promise<GrokDeviceStartResult> {+ requireEnabled(deps)+ const connectionKey = connectionKeyOf(deps)+ const started = await postForm(deps, GROK_OAUTH_DEVICE_URL, {+ client_id: deps.clientId,+ scope: GROK_OAUTH_SCOPES.join(' '),+ })+ if (!started.ok) {+ throw new GrokSubscriptionOAuthError('provider_unavailable', 'device authorization failed')+ }+ const body = started.body+ const deviceCode = requiredString(body.device_code, 'device_code')+ const userCode = requiredString(body.user_code, 'user_code')+ const verificationUri = assertVerificationUri(+ typeof body.verification_uri === 'string' ? body.verification_uri : ''+ )+ const verificationUriComplete =+ typeof body.verification_uri_complete === 'string' && body.verification_uri_complete+ ? assertVerificationUri(body.verification_uri_complete)+ : null+ const intervalSeconds = parsePositiveNumber(body.interval, 5)+ const expiresAt = parseDeviceExpiry(body)+ const state = randomBytes(24).toString('base64url')+ const safe = await insertGrokSubscriptionOAuthState(deps.db, deps.encryptionKey, {+ state,+ intent,+ deviceCode,+ expiresAt,+ connectionKey,+ })+ log.info({ event: 'grok_oauth_device_start', intent: safe.intent }, 'device OAuth start')+ return {+ userCode,+ verificationUri,+ verificationUriComplete,+ intervalSeconds,+ expiresAt: safe.expiresAt,+ state,+ intent: safe.intent,+ }+}++export async function pollGrokDevice(+ deps: GrokOAuthDeps,+ state: string+): Promise<GrokDevicePollResult> {+ requireEnabled(deps)+ const pending = await peekPendingGrokSubscriptionOAuthState(deps.db, deps.encryptionKey, state)+ if (!pending) {+ throw new GrokSubscriptionOAuthError('state_replayed', 'device state is not pending')+ }+ completionConnectionKey(deps, pending.safe.connectionKey)+ if (pending.safe.expiresAt.getTime() <= Date.now()) {+ await expireGrokSubscriptionOAuthState(deps.db, state)+ return { status: 'expired' }+ }+ if (!pending.deviceCode) {+ throw new GrokSubscriptionOAuthError(+ 'invalid_callback',+ 'device state is missing a device code'+ )+ }+ const tokenResult = await pollDeviceAuthorization(deps, pending.deviceCode)+ if (tokenResult.kind === 'pending') {+ return { status: 'pending', intervalSeconds: tokenResult.intervalSeconds, state: pending.safe }+ }+ if (tokenResult.kind === 'slow_down') {+ return {+ status: 'slow_down',+ intervalSeconds: tokenResult.intervalSeconds,+ state: pending.safe,+ }+ }+ if (tokenResult.kind === 'expired') {+ await expireGrokSubscriptionOAuthState(deps.db, state)+ return { status: 'expired' }+ }+ if (tokenResult.kind === 'denied') {+ await cancelGrokSubscriptionOAuthState(deps.db, state)+ return { status: 'denied' }+ }+ const consumed = await consumeGrokSubscriptionOAuthState(deps.db, deps.encryptionKey, state)+ if (!consumed) {+ throw new GrokSubscriptionOAuthError('state_replayed', 'device state was consumed concurrently')+ }+ const connection = await persistGrantedTokens(+ deps,+ consumed.safe.intent,+ tokenResult.parsed,+ completionConnectionKey(deps, consumed.safe.connectionKey)+ )+ return { status: 'connected', connection }+}++export async function refreshGrokSubscriptionConnection(+ deps: GrokOAuthDeps+): Promise<GrokSubscriptionSafeConnection> {+ requireEnabled(deps)+ const key = connectionKeyOf(deps)+ const current = await getSafeGrokSubscriptionConnection(deps.db, key)+ if (!current || current.status === 'revoked' || current.status === 'disconnected') {+ throw new GrokSubscriptionOAuthError('not_connected', 'no active Grok subscription')+ }+ const lockToken = randomBytes(16).toString('hex')+ const locked = await acquireGrokSubscriptionRefreshLock(+ deps.db,+ lockToken,+ REFRESH_LOCK_TTL_MS,+ key+ )+ if (!locked) {+ throw new GrokSubscriptionOAuthError('refresh_in_flight', 'another refresh holds the lock')+ }+ try {+ return await rotateLockedRefresh(deps, key, lockToken)+ } finally {+ await releaseGrokSubscriptionRefreshLock(deps.db, lockToken, key)+ }+}++export async function revokeGrokSubscription(+ deps: GrokOAuthDeps+): Promise<GrokSubscriptionSafeConnection | { connectionKey: string; status: 'disconnected' }> {+ requireEnabled(deps)+ const key = connectionKeyOf(deps)+ const secrets = await loadGrokSubscriptionSecrets(deps.db, deps.encryptionKey, key)+ const local = await revokeGrokSubscriptionConnection(deps.db, key)+ await rebuildLiveGrokUnionAllowlist(deps.db)+ if (secrets?.refreshToken) {+ try {+ await postForm(deps, GROK_OAUTH_REVOKE_URL, {+ token_type_hint: 'refresh_token',+ client_id: deps.clientId,+ token: secrets.refreshToken,+ })+ } catch (err) {+ log.warn({ event: 'grok_oauth_upstream_revoke_failed', err }, 'upstream revoke failed')+ }+ }+ log.info({ event: 'grok_oauth_revoked_local' }, 'local Grok subscription revoked')+ return local ?? { connectionKey: key, status: 'disconnected' }+}++export async function ensureFreshGrokAccessToken(deps: GrokOAuthDeps): Promise<void> {+ requireEnabled(deps)+ const key = connectionKeyOf(deps)+ const secrets = await loadGrokSubscriptionSecrets(deps.db, deps.encryptionKey, key)+ if (!secrets) {+ throw new GrokSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')+ }+ const expiring =+ secrets.accessTokenExpiresAt != null &&+ secrets.accessTokenExpiresAt.getTime() - Date.now() < ACCESS_TOKEN_REFRESH_SKEW_MS+ if (secrets.accessToken && !expiring) return++ let lockToken = randomBytes(16).toString('hex')+ let locked = await acquireGrokSubscriptionRefreshLock(+ deps.db,+ lockToken,+ REFRESH_LOCK_TTL_MS,+ key+ )+ if (!locked) {+ const deadline = Date.now() + REFRESH_LOCK_TTL_MS+ while (true) {+ await sleep(REFRESH_LOCK_POLL_MS)+ const latest = await loadGrokSubscriptionSecrets(deps.db, deps.encryptionKey, key)+ if (!latest) {+ throw new GrokSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')+ }+ if (accessTokenIsUsable(latest)) return+ if (Date.now() >= deadline) {+ throw new GrokSubscriptionOAuthError('refresh_in_flight', 'another refresh holds the lock')+ }+ lockToken = randomBytes(16).toString('hex')+ locked = await acquireGrokSubscriptionRefreshLock(+ deps.db,+ lockToken,+ REFRESH_LOCK_TTL_MS,+ key+ )+ if (locked) break+ }+ }+ try {+ await rotateLockedRefresh(deps, key, lockToken)+ } finally {+ await releaseGrokSubscriptionRefreshLock(deps.db, lockToken, key)+ }+}++export async function runGrokCatalogSync(+ deps: GrokOAuthDeps,+ connectionKey: string,+ transport: GrokCatalogTransport+): Promise<GrokCatalogSyncResult> {+ const key = assertGrokConnectionKey(connectionKey)+ try {+ const keyed = { ...deps, connectionKey: key }+ await ensureFreshGrokAccessToken(keyed)+ const secrets = await loadGrokSubscriptionSecrets(deps.db, deps.encryptionKey, key)+ if (!secrets?.accessToken) {+ return { ok: false, catalogStatus: 'never_synced', reason: 'no_grant' }+ }+ const synced = await syncGrokSubscriptionCatalog(deps.db, transport, secrets.accessToken, {+ connectionKey: key,+ })+ if (!synced.connection) {+ return { ok: false, catalogStatus: 'never_synced', reason: 'stale_revision' }+ }+ if (synced.outcome !== 'ready') {+ return { ok: false, catalogStatus: synced.outcome }+ }+ return { ok: true, catalogStatus: 'ready' }+ } catch (err) {+ log.warn(+ { err, event: 'grok_catalog_auto_sync_failed', connectionKey: key },+ 'automatic catalog sync after grant failed'+ )+ const reason: GrokOAuthErrorCode | 'catalog_sync_failed' =+ err instanceof GrokSubscriptionOAuthError ? err.code : 'catalog_sync_failed'+ return { ok: false, catalogStatus: 'never_synced', reason }+ }+}++async function rotateLockedRefresh(+ deps: GrokOAuthDeps,+ key: string,+ lockToken: string+): Promise<GrokSubscriptionSafeConnection> {+ const secrets = await loadGrokSubscriptionSecrets(deps.db, deps.encryptionKey, key)+ if (!secrets) {+ throw new GrokSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')+ }+ const current = await getSafeGrokSubscriptionConnection(deps.db, key)+ const observedRevision = secrets.credentialRevision+ const token = await exchangeRefreshToken(deps, secrets.refreshToken, {+ expectedRevision: observedRevision,+ lockToken,+ connectionKey: key,+ })+ try {+ const persisted = await persistGrokRefreshCiphertextFirst(deps.db, deps.encryptionKey, {+ connectionKey: key,+ expectedRevision: observedRevision,+ lockToken,+ refreshToken: token.refreshToken,+ })+ const updated = await updateGrokAccessTokenInPlace(+ deps.db,+ deps.encryptionKey,+ persisted.credentialRevision,+ {+ accessToken: token.accessToken,+ accessTokenExpiresAt: token.expiresAt,+ },+ key,+ lockToken+ )+ if (+ current?.accountFingerprint &&+ token.accountFingerprint &&+ current.accountFingerprint !== token.accountFingerprint+ ) {+ const marked = await markGrokRefreshSubjectMismatch(deps.db, key, updated.credentialRevision)+ return marked ?? { ...updated, status: 'reauth_required' }+ }+ return updated+ } catch (err) {+ if (err instanceof GrokSubscriptionStaleRevisionError) {+ throw new GrokSubscriptionOAuthError('stale_revision', 'refresh lost the credential race')+ }+ throw err+ }+}++async function persistGrantedTokens(+ deps: GrokOAuthDeps,+ intent: GrokSubscriptionOAuthIntent,+ parsed: ParsedGrokToken,+ connectionKey: string+): Promise<GrokSubscriptionSafeConnection> {+ const key = assertGrokConnectionKey(connectionKey)+ const existing = await getSafeGrokSubscriptionConnection(deps.db, key)+ if (existing?.revokedAt || existing?.status === 'revoked') {+ throw new GrokSubscriptionOAuthError(+ 'not_connected',+ 'revoked grant cannot be reused; create a new connection'+ )+ }+ if (+ existing?.accountFingerprint &&+ existing.accountFingerprint !== parsed.accountFingerprint &&+ intent !== 'replace'+ ) {+ throw new GrokSubscriptionOAuthError(+ 'replacement_required',+ 'different account requires an explicit replace intent'+ )+ }+ const write = {+ refreshToken: parsed.refreshToken,+ accessToken: parsed.accessToken,+ accessTokenExpiresAt: parsed.expiresAt,+ accountFingerprint: parsed.accountFingerprint,+ status: 'connected' as const,+ }+ if (!existing) {+ const created = await insertInitialGrokSubscriptionConnection(+ deps.db,+ deps.encryptionKey,+ write,+ key+ )+ log.info({ event: 'grok_oauth_persisted', connectionKey: key }, 'Grok grant persisted')+ return created+ }+ try {+ const rotated = await rotateGrokSubscriptionCredentials(+ deps.db,+ deps.encryptionKey,+ existing.credentialRevision,+ write,+ key+ )+ log.info({ event: 'grok_oauth_persisted', connectionKey: key }, 'Grok grant persisted')+ return rotated+ } catch (err) {+ if (err instanceof GrokSubscriptionStaleRevisionError) {+ throw new GrokSubscriptionOAuthError('stale_revision', 'connection was replaced concurrently')+ }+ if (err instanceof GrokSubscriptionFingerprintConflictError) {+ throw new GrokSubscriptionOAuthError(+ 'fingerprint_in_use',+ 'a live Grok subscription already uses this account'+ )+ }+ throw err+ }+}++type ParsedGrokToken = {+ accessToken: string+ refreshToken: string+ expiresAt: Date | null+ accountFingerprint: string+}++async function pollDeviceAuthorization(+ deps: GrokOAuthDeps,+ deviceCode: string+): Promise<+ | { kind: 'ok'; parsed: ParsedGrokToken }+ | { kind: 'pending'; intervalSeconds: number }+ | { kind: 'slow_down'; intervalSeconds: number }+ | { kind: 'expired' }+ | { kind: 'denied' }+> {+ const result = await postForm(deps, GROK_OAUTH_TOKEN_URL, {+ grant_type: GROK_OAUTH_DEVICE_GRANT,+ device_code: deviceCode,+ client_id: deps.clientId,+ })+ if (result.ok) {+ return { kind: 'ok', parsed: parseTokenResponse(result.body, { requireRefresh: true }) }+ }+ const error = readUpstreamErrorCode(result.body)+ if (error === 'authorization_pending') {+ return { kind: 'pending', intervalSeconds: parsePositiveNumber(result.body.interval, 5) }+ }+ if (error === 'slow_down') {+ return { kind: 'slow_down', intervalSeconds: parsePositiveNumber(result.body.interval, 10) }+ }+ if (error === 'expired_token') return { kind: 'expired' }+ if (error === 'access_denied') return { kind: 'denied' }+ if (result.status === 403) {+ throw new GrokSubscriptionOAuthError(+ 'provider_unavailable',+ 'device token poll was entitlement-denied'+ )+ }+ throw new GrokSubscriptionOAuthError('provider_unavailable', 'device token poll failed')+}++async function exchangeRefreshToken(+ deps: GrokOAuthDeps,+ refreshToken: string,+ fence: { expectedRevision: number; lockToken: string; connectionKey: string }+): Promise<ParsedGrokToken> {+ const result = await postForm(deps, GROK_OAUTH_TOKEN_URL, {+ grant_type: 'refresh_token',+ refresh_token: refreshToken,+ client_id: deps.clientId,+ })+ if (result.status === 403) {+ throw new GrokSubscriptionOAuthError('provider_unavailable', 'refresh was entitlement-denied')+ }+ if (!result.ok) {+ const error = readUpstreamErrorCode(result.body)+ if ((result.status === 400 || result.status === 401) && error === 'invalid_grant') {+ const latest = await loadGrokSubscriptionSecrets(+ deps.db,+ deps.encryptionKey,+ fence.connectionKey+ )+ const current = await getSafeGrokSubscriptionConnection(deps.db, fence.connectionKey)+ const lockChanged = !current?.refreshLockHeld+ const revisionChanged = latest?.credentialRevision !== fence.expectedRevision+ if (lockChanged || revisionChanged) {+ throw new GrokSubscriptionOAuthError(+ 'stale_revision',+ 'invalid_grant observed after a lost refresh race'+ )+ }+ throw new GrokSubscriptionOAuthError('reauth_required', 'refresh token was rejected')+ }+ throw new GrokSubscriptionOAuthError('provider_unavailable', 'refresh token exchange failed')+ }+ return parseTokenResponse(result.body, { requireRefresh: true })+}++function parseTokenResponse(+ body: Record<string, unknown>,+ opts: { requireRefresh: boolean }+): ParsedGrokToken {+ const accessToken = requiredString(body.access_token, 'access_token')+ const refreshToken = typeof body.refresh_token === 'string' ? body.refresh_token : ''+ if (opts.requireRefresh && !refreshToken) {+ throw new GrokSubscriptionOAuthError(+ 'provider_unavailable',+ 'token response omitted refresh_token'+ )+ }+ const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : null+ const idToken = typeof body.id_token === 'string' ? body.id_token : null+ const subject = subjectFromTokens(idToken, accessToken)+ return {+ accessToken,+ refreshToken,+ expiresAt: expiresIn ? new Date(Date.now() + expiresIn * 1000) : null,+ accountFingerprint: fingerprintAccount(subject),+ }+}++function subjectFromTokens(idToken: string | null, accessToken: string): string {+ const fromId = subjectFromJwt(idToken)+ if (fromId) return fromId+ const fromAccess = subjectFromJwt(accessToken)+ if (fromAccess) return fromAccess+ throw new GrokSubscriptionOAuthError('invalid_callback', 'token response omitted a subject')+}++function subjectFromJwt(token: string | null): string | null {+ if (!token) return null+ const parts = token.split('.')+ if (parts.length < 2) return null+ try {+ const payload = JSON.parse(Buffer.from(parts[1]!, 'base64url').toString('utf8')) as {+ sub?: unknown+ }+ if (typeof payload.sub === 'string' && payload.sub.length > 0) return payload.sub+ } catch {+ return null+ }+ return null+}++function fingerprintAccount(subject: string): string {+ return createHash('sha256').update(subject, 'utf8').digest('hex')+}++function assertVerificationUri(value: string): string {+ let parsed: URL+ try {+ parsed = new URL(value)+ } catch {+ throw new GrokSubscriptionOAuthError(+ 'provider_unavailable',+ 'device verification URI is invalid'+ )+ }+ if (parsed.protocol !== 'https:' || parsed.hostname !== 'auth.x.ai') {+ throw new GrokSubscriptionOAuthError(+ 'provider_unavailable',+ 'device verification URI origin is not frozen'+ )+ }+ return parsed.toString()+}++async function postForm(+ deps: GrokOAuthDeps,+ url: string,+ params: Record<string, string>+): Promise<{ ok: boolean; status: number; body: Record<string, unknown> }> {+ return post(deps, url, new URLSearchParams(params).toString())+}++async function post(+ deps: GrokOAuthDeps,+ url: string,+ body: string+): Promise<{ ok: boolean; status: number; body: Record<string, unknown> }> {+ let response: Response+ try {+ response = await deps.fetchFn(url, {+ method: 'POST',+ headers: {+ 'content-type': 'application/x-www-form-urlencoded',+ accept: 'application/json',+ },+ body,+ redirect: 'manual',+ signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS),+ })+ } catch (err) {+ log.warn({ event: 'grok_oauth_upstream_unreachable', err }, 'Grok OAuth upstream unreachable')+ throw new GrokSubscriptionOAuthError('provider_unavailable', 'Grok OAuth upstream unreachable')+ }+ if (response.status >= 300 && response.status < 400) {+ log.warn(+ { event: 'grok_oauth_redirect_denied', status: response.status },+ 'Grok OAuth upstream returned a redirect'+ )+ throw new GrokSubscriptionOAuthError(+ 'provider_unavailable',+ 'Grok OAuth upstream returned a redirect'+ )+ }+ const json = (await response.json().catch(() => ({}))) as Record<string, unknown>+ return { ok: response.ok, status: response.status, body: json }+}++function requiredString(value: unknown, field: string): string {+ if (typeof value === 'string' && value.length > 0) return value+ throw new GrokSubscriptionOAuthError('provider_unavailable', `upstream omitted ${field}`)+}++function readUpstreamErrorCode(body: Record<string, unknown>): string {+ const error = body.error+ if (typeof error === 'string') return error+ if (+ error &&+ typeof error === 'object' &&+ typeof (error as { code?: unknown }).code === 'string'+ ) {+ return (error as { code: string }).code+ }+ return ''+}++function parsePositiveNumber(value: unknown, fallback: number): number {+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value+ if (typeof value === 'string') {+ const parsed = Number(value.trim())+ if (Number.isFinite(parsed) && parsed > 0) return parsed+ }+ return fallback+}++function parseDeviceExpiry(body: Record<string, unknown>): Date {+ if (typeof body.expires_at === 'string') {+ const parsed = new Date(body.expires_at)+ if (!Number.isNaN(parsed.getTime())) return parsed+ }+ const expiresIn = parsePositiveNumber(body.expires_in, DEVICE_CODE_TIMEOUT_SECONDS)+ return new Date(Date.now() + expiresIn * 1000)+}diff --git a/control-api/src/services/grokSubscriptionOAuthState.ts b/control-api/src/services/grokSubscriptionOAuthState.tsnew file mode 100644index 000000000..d1a34f341--- /dev/null+++ b/control-api/src/services/grokSubscriptionOAuthState.ts@@ -0,0 +1,191 @@+import type { DbClient } from '../db.js'+import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'+import { assertGrokConnectionKey } from './grokSubscriptionConnection.js'++export type GrokSubscriptionOAuthFlow = 'device'+export type GrokSubscriptionOAuthIntent = 'connect' | 'reconnect' | 'replace'+export type GrokSubscriptionOAuthStateStatus = 'pending' | 'consumed' | 'expired' | 'cancelled'++export type GrokSubscriptionOAuthSafeState = {+ state: string+ flow: GrokSubscriptionOAuthFlow+ intent: GrokSubscriptionOAuthIntent+ status: GrokSubscriptionOAuthStateStatus+ connectionKey: string+ expiresAt: Date+ consumedAt: Date | null+ cancelledAt: Date | null+ createdAt: Date+}++export type GrokSubscriptionOAuthStateWrite = {+ state: string+ intent: GrokSubscriptionOAuthIntent+ deviceCode: string+ expiresAt: Date+ connectionKey: string+}++export type GrokSubscriptionConsumedOAuthState = {+ safe: GrokSubscriptionOAuthSafeState+ deviceCode?: string+}++type SafeOAuthStateRow = {+ state: string+ flow: GrokSubscriptionOAuthFlow+ intent: GrokSubscriptionOAuthIntent+ status: GrokSubscriptionOAuthStateStatus+ connection_key: string+ expires_at: Date | string+ consumed_at: Date | string | null+ cancelled_at: Date | string | null+ created_at: Date | string+}++type ConsumedOAuthStateRow = SafeOAuthStateRow & {+ device_code_encrypted: string | null+}++const SAFE_OAUTH_STATE_COLUMNS = `+ state,+ flow,+ intent,+ status,+ connection_key,+ expires_at,+ consumed_at,+ cancelled_at,+ created_at+`++export async function insertGrokSubscriptionOAuthState(+ db: DbClient,+ encryptionKey: Buffer,+ input: GrokSubscriptionOAuthStateWrite+): Promise<GrokSubscriptionOAuthSafeState> {+ if (!input.deviceCode) {+ throw new Error('device OAuth state requires a device code')+ }+ const connectionKey = assertGrokConnectionKey(input.connectionKey)+ const result = await db.query(+ `INSERT INTO grok_subscription_oauth_states (+ state,+ flow,+ intent,+ device_code_encrypted,+ status,+ expires_at,+ connection_key+ ) VALUES ($1, 'device', $2, $3, 'pending', $4, $5)+ RETURNING ${SAFE_OAUTH_STATE_COLUMNS}`,+ [+ input.state,+ input.intent,+ encryptOAuthSecret(encryptionKey, input.deviceCode),+ input.expiresAt,+ connectionKey,+ ]+ )+ return toSafeOAuthState(result.rows[0] as SafeOAuthStateRow)+}++export async function peekPendingGrokSubscriptionOAuthState(+ db: DbClient,+ encryptionKey: Buffer,+ state: string+): Promise<GrokSubscriptionConsumedOAuthState | null> {+ const result = await db.query(+ `SELECT ${SAFE_OAUTH_STATE_COLUMNS},+ device_code_encrypted+ FROM grok_subscription_oauth_states+ WHERE state = $1+ AND status = 'pending'+ AND expires_at > now()`,+ [state]+ )+ const row = result.rows[0] as ConsumedOAuthStateRow | undefined+ if (!row) return null+ return toConsumedOAuthState(row, encryptionKey)+}++export async function expireGrokSubscriptionOAuthState(+ db: DbClient,+ state: string+): Promise<boolean> {+ const result = await db.query(+ `UPDATE grok_subscription_oauth_states+ SET status = 'expired'+ WHERE state = $1+ AND status = 'pending'`,+ [state]+ )+ return (result.rowCount ?? 0) > 0+}++export async function consumeGrokSubscriptionOAuthState(+ db: DbClient,+ encryptionKey: Buffer,+ state: string+): Promise<GrokSubscriptionConsumedOAuthState | null> {+ const result = await db.query(+ `UPDATE grok_subscription_oauth_states+ SET status = 'consumed',+ consumed_at = now()+ WHERE state = $1+ AND status = 'pending'+ AND expires_at > now()+ RETURNING ${SAFE_OAUTH_STATE_COLUMNS},+ device_code_encrypted`,+ [state]+ )+ const row = result.rows[0] as ConsumedOAuthStateRow | undefined+ if (!row) return null+ return toConsumedOAuthState(row, encryptionKey)+}++export async function cancelGrokSubscriptionOAuthState(+ db: DbClient,+ state: string+): Promise<boolean> {+ const result = await db.query(+ `UPDATE grok_subscription_oauth_states+ SET status = 'cancelled',+ cancelled_at = now()+ WHERE state = $1+ AND status = 'pending'`,+ [state]+ )+ return (result.rowCount ?? 0) > 0+}++function toConsumedOAuthState(+ row: ConsumedOAuthStateRow,+ encryptionKey: Buffer+): GrokSubscriptionConsumedOAuthState {+ return {+ safe: toSafeOAuthState(row),+ deviceCode: row.device_code_encrypted+ ? decryptOAuthSecret(encryptionKey, row.device_code_encrypted)+ : undefined,+ }+}++function toSafeOAuthState(row: SafeOAuthStateRow): GrokSubscriptionOAuthSafeState {+ return {+ state: row.state,+ flow: row.flow,+ intent: row.intent,+ status: row.status,+ connectionKey: assertGrokConnectionKey(row.connection_key),+ expiresAt: asDate(row.expires_at) ?? new Date(0),+ consumedAt: asDate(row.consumed_at),+ cancelledAt: asDate(row.cancelled_at),+ createdAt: asDate(row.created_at) ?? new Date(0),+ }+}++function asDate(value: Date | string | null | undefined): Date | null {+ if (value == null) return null+ return value instanceof Date ? value : new Date(value)+}diff --git a/control-api/src/utils/log/redact.ts b/control-api/src/utils/log/redact.tsindex c00e374ce..40befb711 100644--- a/control-api/src/utils/log/redact.ts+++ b/control-api/src/utils/log/redact.ts@@ -27,6 +27,15 @@ export const TOKEN_LEAK_REDACT_PATHS: readonly string[] = ['idToken','pkceVerifier','refresh_token',+ 'deviceCode',+ 'device_code',+ 'userCode',+ 'user_code',+ 'accountSubject',+ 'account_subject',+ '*.access_token',+ '*.refresh_token',+ '*.id_token',]/** Asserted by unit tests so redactions can grow but never shrink. */@@ -50,4 +59,13 @@ export const REQUIRED_REDACT_PATHS: readonly string[] = ['idToken','pkceVerifier','refresh_token',+ 'deviceCode',+ 'device_code',+ 'userCode',+ 'user_code',+ 'accountSubject',+ 'account_subject',+ '*.access_token',+ '*.refresh_token',+ '*.id_token',]diff --git a/control-api/test/services.grokSubscriptionCatalog.test.ts b/control-api/test/services.grokSubscriptionCatalog.test.tsnew file mode 100644index 000000000..8819f6997--- /dev/null+++ b/control-api/test/services.grokSubscriptionCatalog.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from 'vitest'+import { CATALOG_ORIGIN } from '@clerum/grok-provider-attempt-contract'+import {+ GROK_CATALOG_ORIGIN,+ pickGrokGrantModel,+ planGrokCatalogReconcile,+} from '../src/services/grokSubscriptionCatalog.js'+import {+ isGrokUnassignedConnectionKey,+ readHostGrokConnectionRef,+} from '../src/services/grokSubscriptionConnection.js'++describe('grok subscription catalog', () => {+ it('uses the frozen catalog origin from the Grok attempt contract', () => {+ expect(GROK_CATALOG_ORIGIN).toBe(CATALOG_ORIGIN)+ expect(GROK_CATALOG_ORIGIN).toBe('https://cli-chat-proxy.grok.com/v1/models')+ expect(GROK_CATALOG_ORIGIN).not.toContain('api.x.ai')+ })++ it('auto-enables new discovery rows and never invents a static default model', () => {+ const plan = planGrokCatalogReconcile([], {+ outcome: 'ready',+ models: [{ model: 'grok-4.6' }, { model: 'grok-4.5' }],+ })+ expect(plan.catalogStatus).toBe('ready')+ expect(plan.inserts.map(row => row.model)).toEqual(['grok-4.6', 'grok-4.5'])+ expect(pickGrokGrantModel('', ['grok-4.6', 'grok-4.5'], 'grok-4.6')).toBe('grok-4.6')+ expect(pickGrokGrantModel('missing', ['grok-4.6'], null)).toBe('grok-4.6')+ })++ it('rejects unassigned Host refs for assignment', () => {+ expect(isGrokUnassignedConnectionKey(readHostGrokConnectionRef(''))).toBe(true)+ expect(isGrokUnassignedConnectionKey(readHostGrokConnectionRef('team-grok'))).toBe(false)+ })+})diff --git a/control-api/test/services.grokSubscriptionConnection.test.ts b/control-api/test/services.grokSubscriptionConnection.test.tsnew file mode 100644index 000000000..27dcaea89--- /dev/null+++ b/control-api/test/services.grokSubscriptionConnection.test.ts@@ -0,0 +1,175 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'+import {+ GrokSubscriptionFingerprintConflictError,+ GrokSubscriptionInvalidConnectionKeyError,+ GrokSubscriptionStaleRevisionError,+ assertGrokConnectionKey,+ generateGrokConnectionKey,+ getSafeGrokSubscriptionConnection,+ insertInitialGrokSubscriptionConnection,+ persistGrokRefreshCiphertextFirst,+ readHostGrokConnectionRef,+} from '../src/services/grokSubscriptionConnection.js'++const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))++function queryMock() {+ return vi.fn()+}++describe('grok subscription connection repository', () => {+ const query = queryMock()++ beforeEach(() => {+ query.mockReset()+ })++ it('generates grok-<16 hex> keys and rejects reserved names', () => {+ expect(generateGrokConnectionKey()).toMatch(/^grok-[0-9a-f]{16}$/)+ expect(assertGrokConnectionKey('team-grok')).toBe('team-grok')+ expect(() => assertGrokConnectionKey('unassigned')).toThrow(+ GrokSubscriptionInvalidConnectionKeyError+ )+ expect(() => assertGrokConnectionKey('deployment-default')).toThrow(+ GrokSubscriptionInvalidConnectionKeyError+ )+ expect(() => assertGrokConnectionKey('')).toThrow(GrokSubscriptionInvalidConnectionKeyError)+ })++ it('maps empty Host connectionRef to unassigned, never deployment-default', () => {+ expect(readHostGrokConnectionRef(undefined)).toBe('unassigned')+ expect(readHostGrokConnectionRef('')).toBe('unassigned')+ expect(readHostGrokConnectionRef(' ')).toBe('unassigned')+ expect(readHostGrokConnectionRef('team-grok')).toBe('team-grok')+ })++ it('returns safe metadata without ciphertext or token fields', async () => {+ const ciphertext = encryptOAuthSecret(KEY, 'refresh-secret')+ query.mockResolvedValueOnce({+ rows: [+ {+ id: '11111111-1111-1111-1111-111111111111',+ connection_key: 'team-grok',+ display_name: 'Team Grok',+ created_by: null,+ status: 'connected',+ refresh_token_encrypted: ciphertext,+ access_token_encrypted: encryptOAuthSecret(KEY, 'access-secret'),+ access_token_expires_at: new Date('2026-09-16T12:00:00.000Z'),+ credential_revision: '3',+ catalog_revision: '1',+ account_fingerprint: 'fp_abc',+ catalog_status: 'ready',+ catalog_synced_at: new Date('2026-09-16T11:00:00.000Z'),+ last_refresh_at: new Date('2026-09-16T11:30:00.000Z'),+ last_auth_at: new Date('2026-09-16T10:00:00.000Z'),+ refresh_lock_token: 'lock',+ refresh_lock_expires_at: new Date('2026-09-16T12:00:00.000Z'),+ revoked_at: null,+ created_at: new Date('2026-09-16T09:00:00.000Z'),+ updated_at: new Date('2026-09-16T11:30:00.000Z'),+ },+ ],+ rowCount: 1,+ })++ const metadata = await getSafeGrokSubscriptionConnection({ query }, 'team-grok')+ expect(metadata).toMatchObject({+ connectionKey: 'team-grok',+ status: 'connected',+ credentialRevision: 3,+ catalogRevision: 1,+ accountFingerprint: 'fp_abc',+ catalogStatus: 'ready',+ })+ const serialized = JSON.stringify(metadata)+ expect(serialized).not.toContain(ciphertext)+ expect(serialized).not.toContain('refresh-secret')+ expect(serialized).not.toContain('access-secret')+ expect(metadata).not.toHaveProperty('refreshToken')+ expect(metadata).not.toHaveProperty('accessToken')+ expect(String(query.mock.calls[0]?.[0])).not.toContain('chatgpt')+ })++ it('inserts encrypted credentials without ChatGPT columns', async () => {+ query.mockResolvedValueOnce({+ rows: [+ {+ id: '11111111-1111-1111-1111-111111111111',+ connection_key: 'team-grok',+ display_name: 'team-grok',+ created_by: null,+ status: 'connected',+ credential_revision: '1',+ catalog_revision: '0',+ account_fingerprint: 'fp_new',+ catalog_status: 'never_synced',+ catalog_synced_at: null,+ last_refresh_at: null,+ last_auth_at: new Date(),+ refresh_lock_token: null,+ refresh_lock_expires_at: null,+ revoked_at: null,+ created_at: new Date(),+ updated_at: new Date(),+ },+ ],+ rowCount: 1,+ })++ const metadata = await insertInitialGrokSubscriptionConnection(+ { query },+ KEY,+ {+ refreshToken: 'plain-refresh',+ accessToken: 'plain-access',+ accountFingerprint: 'fp_new',+ },+ 'team-grok'+ )+ expect(metadata.connectionKey).toBe('team-grok')+ const sql = String(query.mock.calls[0]?.[0])+ expect(sql).not.toContain('chatgpt')+ const [, params] = query.mock.calls[0] as [string, unknown[]]+ expect(params).not.toContain('plain-refresh')+ expect(params).not.toContain('plain-access')+ expect(String(params[3])).toMatch(/^v1\./)+ })++ it('maps a unique active fingerprint violation to fingerprint_in_use', async () => {+ query.mockRejectedValueOnce(+ Object.assign(new Error('duplicate'), {+ code: '23505',+ constraint: 'grok_subscription_connections_active_fingerprint',+ })+ )+ await expect(+ insertInitialGrokSubscriptionConnection(+ { query },+ KEY,+ { refreshToken: 'plain-refresh', accountFingerprint: 'fp_dup' },+ 'team-grok'+ )+ ).rejects.toBeInstanceOf(GrokSubscriptionFingerprintConflictError)+ })++ it('fences persist-first refresh on lock token, revision, and live lease', async () => {+ query.mockResolvedValueOnce({ rows: [], rowCount: 0 })+ await expect(+ persistGrokRefreshCiphertextFirst({ query }, KEY, {+ connectionKey: 'team-grok',+ expectedRevision: 4,+ lockToken: 'lease-1',+ refreshToken: 'rotated-refresh',+ })+ ).rejects.toBeInstanceOf(GrokSubscriptionStaleRevisionError)+ const sql = String(query.mock.calls[0]?.[0])+ expect(sql).toContain('refresh_lock_token = $4')+ expect(sql).toContain('credential_revision = $3')+ expect(sql).toContain('refresh_lock_expires_at > now()')+ expect(sql).not.toContain('credential_revision + 1')+ const [, params] = query.mock.calls[0] as [string, unknown[]]+ expect(params).not.toContain('rotated-refresh')+ })+})diff --git a/control-api/test/services.grokSubscriptionOAuth.test.ts b/control-api/test/services.grokSubscriptionOAuth.test.tsnew file mode 100644index 000000000..cfbfeb9b0--- /dev/null+++ b/control-api/test/services.grokSubscriptionOAuth.test.ts@@ -0,0 +1,497 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { createHash } from 'node:crypto'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { GrokSubscriptionStaleRevisionError } from '../src/services/grokSubscriptionConnection.js'++const repos = vi.hoisted(() => ({+ insertState: vi.fn(),+ consumeState: vi.fn(),+ peekState: vi.fn(),+ expireState: vi.fn(),+ cancelState: vi.fn(),+ getSafe: vi.fn(),+ insertInitial: vi.fn(),+ rotate: vi.fn(),+ acquireLock: vi.fn(),+ releaseLock: vi.fn(),+ loadSecrets: vi.fn(),+ revokeConnection: vi.fn(),+ updateInPlace: vi.fn(),+ persistRefresh: vi.fn(),+ markMismatch: vi.fn(),+}))++vi.mock('../src/services/grokSubscriptionOAuthState.js', async () => {+ const actual = await vi.importActual('../src/services/grokSubscriptionOAuthState.js')+ return {+ ...actual,+ insertGrokSubscriptionOAuthState: repos.insertState,+ consumeGrokSubscriptionOAuthState: repos.consumeState,+ peekPendingGrokSubscriptionOAuthState: repos.peekState,+ expireGrokSubscriptionOAuthState: repos.expireState,+ cancelGrokSubscriptionOAuthState: repos.cancelState,+ }+})++vi.mock('../src/services/grokSubscriptionConnection.js', async () => {+ const actual = await vi.importActual('../src/services/grokSubscriptionConnection.js')+ return {+ ...actual,+ getSafeGrokSubscriptionConnection: repos.getSafe,+ insertInitialGrokSubscriptionConnection: repos.insertInitial,+ rotateGrokSubscriptionCredentials: repos.rotate,+ acquireGrokSubscriptionRefreshLock: repos.acquireLock,+ releaseGrokSubscriptionRefreshLock: repos.releaseLock,+ loadGrokSubscriptionSecrets: repos.loadSecrets,+ revokeGrokSubscriptionConnection: repos.revokeConnection,+ updateGrokAccessTokenInPlace: repos.updateInPlace,+ persistGrokRefreshCiphertextFirst: repos.persistRefresh,+ markGrokRefreshSubjectMismatch: repos.markMismatch,+ }+})++vi.mock('../src/services/grokSubscriptionCatalog.js', async () => {+ const actual = await vi.importActual('../src/services/grokSubscriptionCatalog.js')+ return {+ ...actual,+ syncGrokSubscriptionCatalog: vi.fn(),+ rebuildLiveGrokUnionAllowlist: vi.fn(),+ }+})++const {+ GROK_OAUTH_DEVICE_GRANT,+ GROK_OAUTH_DEVICE_URL,+ GROK_OAUTH_SCOPES,+ GROK_OAUTH_TOKEN_URL,+ ensureFreshGrokAccessToken,+ pollGrokDevice,+ refreshGrokSubscriptionConnection,+ startGrokDeviceConnect,+} = await import('../src/services/grokSubscriptionOAuth.js')++const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))+const CONNECTION_KEY = 'team-grok'++function idTokenFor(subject: string): string {+ const payload = Buffer.from(JSON.stringify({ sub: subject })).toString('base64url')+ return `hdr.${payload}.sig`+}++function fingerprint(subject: string): string {+ return createHash('sha256').update(subject, 'utf8').digest('hex')+}++function assertNoLeak(value: unknown): void {+ const serialized = JSON.stringify(value)+ expect(serialized).not.toMatch(+ /sk-|Bearer |eyJ[A-Za-z0-9_-]+\.|refresh-secret|access-secret|device-secret|cookie/i+ )+ expect(serialized).not.toContain('acct_raw_123')+}++function deps(fetchFn: typeof fetch) {+ return {+ db: { query: vi.fn() },+ encryptionKey: KEY,+ fetchFn,+ clientId: 'b1a00492-073a-47ea-816f-4c329264a828',+ enabled: true,+ connectionKey: CONNECTION_KEY,+ }+}++describe('grok subscription OAuth device broker', () => {+ beforeEach(() => {+ for (const fn of Object.values(repos)) fn.mockReset()+ })++ it('starts RFC 8628 device authorization without leaking the device code', async () => {+ repos.insertState.mockImplementation(+ async (+ _db: unknown,+ _key: Buffer,+ input: { state: string; intent: string; expiresAt: Date; deviceCode: string }+ ) => ({+ state: input.state,+ flow: 'device',+ intent: input.intent,+ status: 'pending',+ connectionKey: CONNECTION_KEY,+ expiresAt: input.expiresAt,+ consumedAt: null,+ cancelledAt: null,+ createdAt: new Date(),+ })+ )+ const fetchFn = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ device_code: 'device-secret',+ user_code: 'ABCD-EFGH',+ verification_uri: 'https://auth.x.ai/activate',+ expires_in: 900,+ interval: 5,+ }),+ })+ const result = await startGrokDeviceConnect(deps(fetchFn), 'connect')+ expect(fetchFn).toHaveBeenCalledWith(+ GROK_OAUTH_DEVICE_URL,+ expect.objectContaining({+ redirect: 'manual',+ headers: expect.objectContaining({+ 'content-type': 'application/x-www-form-urlencoded',+ accept: 'application/json',+ }),+ })+ )+ const body = String(fetchFn.mock.calls[0]?.[1]?.body)+ const form = new URLSearchParams(body)+ expect(form.get('client_id')).toBe('b1a00492-073a-47ea-816f-4c329264a828')+ expect(form.get('scope')).toBe(GROK_OAUTH_SCOPES.join(' '))+ expect(result.userCode).toBe('ABCD-EFGH')+ expect(result.verificationUri).toContain('https://auth.x.ai/')+ expect(repos.insertState.mock.calls[0]?.[2]).toMatchObject({+ intent: 'connect',+ deviceCode: 'device-secret',+ connectionKey: CONNECTION_KEY,+ })+ assertNoLeak(result)+ expect(JSON.stringify(result)).not.toContain('device-secret')+ })++ it('does not follow OAuth token redirects and treats 3xx as provider_unavailable', async () => {+ repos.peekState.mockResolvedValue({+ safe: {+ state: 'dev-redir',+ flow: 'device',+ intent: 'connect',+ status: 'pending',+ connectionKey: CONNECTION_KEY,+ expiresAt: new Date(Date.now() + 60_000),+ consumedAt: null,+ cancelledAt: null,+ createdAt: new Date(),+ },+ deviceCode: 'device-secret',+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: false,+ status: 307,+ json: async () => ({}),+ })+ await expect(pollGrokDevice(deps(fetchFn), 'dev-redir')).rejects.toMatchObject({+ code: 'provider_unavailable',+ })+ expect(fetchFn).toHaveBeenCalledWith(+ GROK_OAUTH_TOKEN_URL,+ expect.objectContaining({ redirect: 'manual' })+ )+ })++ it('exchanges a completed device poll for access and refresh tokens', async () => {+ repos.peekState.mockResolvedValue({+ safe: {+ state: 'dev-ok',+ flow: 'device',+ intent: 'connect',+ status: 'pending',+ connectionKey: CONNECTION_KEY,+ expiresAt: new Date(Date.now() + 60_000),+ consumedAt: null,+ cancelledAt: null,+ createdAt: new Date(),+ },+ deviceCode: 'device-secret',+ })+ repos.consumeState.mockResolvedValue({+ safe: {+ state: 'dev-ok',+ flow: 'device',+ intent: 'connect',+ status: 'consumed',+ connectionKey: CONNECTION_KEY,+ expiresAt: new Date(Date.now() + 60_000),+ consumedAt: new Date(),+ cancelledAt: null,+ createdAt: new Date(),+ },+ deviceCode: 'device-secret',+ })+ repos.getSafe.mockResolvedValue(null)+ repos.insertInitial.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 1,+ accountFingerprint: fingerprint('acct_raw_123'),+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'access-secret',+ refresh_token: 'refresh-secret',+ expires_in: 60,+ id_token: idTokenFor('acct_raw_123'),+ }),+ })+ const connected = await pollGrokDevice(deps(fetchFn), 'dev-ok')+ expect(connected.status).toBe('connected')+ const body = String(fetchFn.mock.calls[0]?.[1]?.body)+ expect(body).toContain(`grant_type=${encodeURIComponent(GROK_OAUTH_DEVICE_GRANT)}`)+ expect(repos.insertInitial.mock.calls[0]?.[2]).toMatchObject({+ refreshToken: 'refresh-secret',+ accessToken: 'access-secret',+ })+ assertNoLeak(connected)+ })++ it('rejects a refresh 200 that omits refresh_token', 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: true,+ status: 200,+ json: async () => ({+ access_token: 'access-secret',+ id_token: idTokenFor('acct_raw_123'),+ }),+ })+ await expect(refreshGrokSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({+ code: 'provider_unavailable',+ })+ expect(repos.persistRefresh).not.toHaveBeenCalled()+ expect(repos.releaseLock).toHaveBeenCalled()+ })++ it('maps refresh 403 to provider_unavailable', 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: 403,+ json: async () => ({ error: 'access_denied' }),+ })+ await expect(refreshGrokSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({+ code: 'provider_unavailable',+ })+ expect(repos.persistRefresh).not.toHaveBeenCalled()+ })++ it('maps invalid_grant with unchanged lock and revision to reauth_required', 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' }),+ })+ await expect(refreshGrokSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({+ code: 'reauth_required',+ })+ })++ it('maps invalid_grant after a lock/revision change to a lost race', async () => {+ const before = {+ connectionKey: CONNECTION_KEY,+ status: 'connected' as const,+ credentialRevision: 3,+ refreshLockHeld: true,+ }+ repos.getSafe+ .mockResolvedValueOnce(before)+ .mockResolvedValueOnce(before)+ .mockResolvedValueOnce({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 4,+ refreshLockHeld: false,+ })+ repos.acquireLock.mockResolvedValue(true)+ repos.loadSecrets+ .mockResolvedValueOnce({+ refreshToken: 'old-refresh',+ accessToken: null,+ accessTokenExpiresAt: null,+ credentialRevision: 3,+ })+ .mockResolvedValueOnce({+ refreshToken: 'winner-refresh',+ accessToken: 'access-secret',+ accessTokenExpiresAt: new Date(Date.now() + 60_000),+ credentialRevision: 4,+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: false,+ status: 401,+ json: async () => ({ error: 'invalid_grant' }),+ })+ await expect(refreshGrokSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({+ code: 'stale_revision',+ })+ })++ it('persists the rotated refresh ciphertext before later processing', async () => {+ repos.getSafe.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 7,+ accountFingerprint: fingerprint('acct_raw_123'),+ refreshLockHeld: true,+ })+ repos.acquireLock.mockResolvedValue(true)+ repos.loadSecrets.mockResolvedValue({+ refreshToken: 'old-refresh',+ accessToken: null,+ accessTokenExpiresAt: null,+ credentialRevision: 7,+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'access-secret',+ refresh_token: 'rotated-refresh',+ id_token: idTokenFor('acct_raw_123'),+ }),+ })+ repos.persistRefresh.mockRejectedValueOnce(new GrokSubscriptionStaleRevisionError())+ await expect(refreshGrokSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({+ code: 'stale_revision',+ })+ expect(repos.persistRefresh).toHaveBeenCalledWith(+ expect.anything(),+ KEY,+ expect.objectContaining({+ refreshToken: 'rotated-refresh',+ expectedRevision: 7,+ connectionKey: CONNECTION_KEY,+ })+ )+ expect(repos.updateInPlace).not.toHaveBeenCalled()+ expect(repos.releaseLock).toHaveBeenCalled()+ })++ it('keeps the stored fingerprint and marks reauth_required when the subject differs', async () => {+ repos.getSafe.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 2,+ accountFingerprint: fingerprint('acct_raw_123'),+ refreshLockHeld: true,+ })+ repos.acquireLock.mockResolvedValue(true)+ repos.loadSecrets.mockResolvedValue({+ refreshToken: 'old-refresh',+ accessToken: null,+ accessTokenExpiresAt: null,+ credentialRevision: 2,+ })+ repos.persistRefresh.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 2,+ accountFingerprint: fingerprint('acct_raw_123'),+ })+ repos.updateInPlace.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 2,+ accountFingerprint: fingerprint('acct_raw_123'),+ })+ repos.markMismatch.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'reauth_required',+ credentialRevision: 2,+ accountFingerprint: fingerprint('acct_raw_123'),+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'access-secret',+ refresh_token: 'rotated-refresh',+ id_token: idTokenFor('other-subject'),+ }),+ })+ const refreshed = await refreshGrokSubscriptionConnection(deps(fetchFn))+ expect(refreshed.status).toBe('reauth_required')+ expect(repos.persistRefresh).toHaveBeenCalled()+ expect(repos.markMismatch).toHaveBeenCalled()+ expect(repos.rotate).not.toHaveBeenCalled()+ })++ it('refreshes an expiring access token through persist-first', async () => {+ repos.loadSecrets.mockResolvedValue({+ refreshToken: 'refresh-secret',+ accessToken: 'stale-access',+ accessTokenExpiresAt: new Date(Date.now() + 30_000),+ credentialRevision: 3,+ })+ repos.getSafe.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 3,+ accountFingerprint: fingerprint('acct_raw_123'),+ refreshLockHeld: true,+ })+ repos.acquireLock.mockResolvedValue(true)+ repos.persistRefresh.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 3,+ })+ repos.updateInPlace.mockResolvedValue({+ connectionKey: CONNECTION_KEY,+ status: 'connected',+ credentialRevision: 3,+ })+ const fetchFn = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'access-secret',+ refresh_token: 'rotated-refresh',+ id_token: idTokenFor('acct_raw_123'),+ }),+ })+ await ensureFreshGrokAccessToken(deps(fetchFn))+ expect(repos.persistRefresh).toHaveBeenCalled()+ expect(repos.updateInPlace).toHaveBeenCalled()+ expect(repos.releaseLock).toHaveBeenCalled()+ })+})diff --git a/control-api/test/utils.log.redact.test.ts b/control-api/test/utils.log.redact.test.tsindex 192d7ac89..3260ea0d9 100644--- a/control-api/test/utils.log.redact.test.ts+++ b/control-api/test/utils.log.redact.test.ts@@ -46,4 +46,21 @@ describe('token-leak redaction', () => {expect(REQUIRED_REDACT_PATHS).toContain(p)}})++ it('redacts Grok device-code and nested token fields', () => {+ for (const p of [+ 'deviceCode',+ 'device_code',+ 'userCode',+ 'user_code',+ 'accountSubject',+ 'account_subject',+ '*.access_token',+ '*.refresh_token',+ '*.id_token',+ ]) {+ expect(TOKEN_LEAK_REDACT_PATHS).toContain(p)+ expect(REQUIRED_REDACT_PATHS).toContain(p)+ }+ })})