import { ClaudeProviderAccountAuthoritySnapshotV1, type ConnectionMetadata, } from "@opengeni/contracts"; import { directModelConnectionSpec, isDirectModelId } from "@opengeni/contracts"; import { organizationCompatibleConnectionIdOf, VERCEL_AI_GATEWAY_CONNECTION_DOMAIN, WORKSPACE_OPENROUTER_CONNECTION_DOMAIN, WORKSPACE_OPPER_CONNECTION_DOMAIN, } from "@opengeni/config"; import { and, eq, isNull, sql } from "drizzle-orm"; import { connections } from "./schema"; import { rawRows, withWorkspaceSubjectRls, type Database } from "./database"; import { connectionModelAllowed } from "./model-connection-access"; export type ConnectionModelRestrictions = Record; /** Claude's model restrictions per id form, as its core route projects them (one answer). */ export type ClaudeCoreModelRestrictions = { readonly "claude/": readonly string[] | null; readonly "organization-claude-subscription/": readonly string[] | null; readonly "workspace-claude-subscription/": readonly string[] | null; }; /** A mutable copy of one core restriction (the core's answers may be frozen). */ const copied = (restriction: readonly string[] | null) => restriction === null ? null : [...restriction]; /** Metadata-only read under the caller's workspace and subject RLS scope. */ async function listDirectModelConnections(db: Database, workspaceId: string, subjectId: string) { return await withWorkspaceSubjectRls(db, workspaceId, subjectId, async (tx) => tx .select({ id: connections.id, version: connections.version, subjectId: connections.subjectId, kind: connections.kind, status: connections.status, providerDomain: connections.providerDomain, metadata: connections.metadata, }) .from(connections) .where( and( eq(connections.workspaceId, workspaceId), isNull(connections.subjectId), eq(connections.kind, "api_key"), eq(connections.status, "active"), sql`${connections.metadata}->>'credentialRole' IN ('direct_openai', 'direct_azure_openai', 'direct_openai_compatible')`, ), ), ); } /** * Public model-id restrictions only. Never returns connection or private owner * identifiers. `supergrok/` is closed here: SuperGrok runs only on the shared * core, whose readiness projection replaces it (`withCoreRoutedXaiRestriction`). */ export async function getWorkspaceConnectionModelRestrictions( db: Database, workspaceId: string, subjectId: string, codex: ReadonlyArray<{ status: string; allocatorEnabled: boolean; allowedModelIds?: string[] | null; }>, claudeAuthoritySnapshot?: ClaudeProviderAccountAuthoritySnapshotV1, /** * Claude's restrictions on its core route (design 5.3, C2a): when given, * no legacy Claude pool or v1 snapshot is read and these are used. */ claudeCoreRestrictions?: ClaudeCoreModelRestrictions, /** * An already authorized public-workspace metadata read from this invocation. * Its owner still observes the original failure; unavailable metadata keeps * the independent scoped read and its original error behavior. */ workspaceConnections?: Promise, ): Promise { const sharedMetadata = workspaceConnections?.catch(() => undefined); const union = (rows: Array<{ allowedModelIds?: string[] | null }>) => rows.some((row) => row.allowedModelIds == null) ? null : [...new Set(rows.flatMap((row) => row.allowedModelIds ?? []))]; const restrictions: ConnectionModelRestrictions = { "codex/": union(codex.filter((row) => row.status === "active" && row.allocatorEnabled)), "supergrok/": [], "workspace-gateway/": [], "workspace-openrouter/": [], "workspace-opper/": [], "workspace-anthropic/": [], "claude/": claudeCoreRestrictions ? copied(claudeCoreRestrictions["claude/"]) : [], "workspace-claude-subscription/": claudeCoreRestrictions ? copied(claudeCoreRestrictions["workspace-claude-subscription/"]) : [], "organization-gateway/": [], "organization-openrouter/": [], "organization-opper/": [], "organization-openai/": [], "organization-azure-openai/": [], "organization-anthropic/": [], "organization-claude-subscription/": claudeCoreRestrictions ? copied(claudeCoreRestrictions["organization-claude-subscription/"]) : [], }; await withWorkspaceSubjectRls(db, workspaceId, subjectId, async (tx) => { const rows = await rawRows<{ prefix: string; allowedModelIds: string[] | null; }>( tx, sql` SELECT CASE provider_kind WHEN 'vercel_gateway' THEN 'organization-gateway/' WHEN 'anthropic' THEN 'organization-anthropic/' WHEN 'claude_subscription' THEN 'organization-claude-subscription/' WHEN 'opper' THEN 'organization-opper/' WHEN 'openai' THEN 'organization-openai/' WHEN 'azure_openai' THEN 'organization-azure-openai/' WHEN 'openrouter' THEN 'organization-openrouter/' END AS prefix, allowed_model_ids AS "allowedModelIds" FROM organization_model_provider_connections WHERE status = 'active' AND provider_kind IN ('vercel_gateway', 'openrouter', 'anthropic', 'opper', 'openai', 'azure_openai') UNION ALL SELECT 'organization-compatible-' || id::text || '/', allowed_model_ids FROM organization_model_provider_connections WHERE status = 'active' AND provider_kind = 'openai_compatible' UNION ALL SELECT CASE metadata->>'credentialRole' WHEN 'vercel_ai_gateway' THEN 'workspace-gateway/' WHEN 'anthropic' THEN 'workspace-anthropic/' WHEN 'claude_subscription' THEN 'workspace-claude-subscription/' WHEN 'opper' THEN 'workspace-opper/' ELSE 'workspace-openrouter/' END, allowed_model_ids FROM ( SELECT DISTINCT ON (metadata->>'credentialRole') * FROM connections WHERE workspace_id = ${workspaceId}::uuid AND subject_id IS NULL AND kind = 'api_key' AND status = 'active' AND ((metadata->>'credentialRole' = 'vercel_ai_gateway' AND lower(provider_domain) = ${VERCEL_AI_GATEWAY_CONNECTION_DOMAIN}) OR (metadata->>'credentialRole' = 'openrouter' AND lower(provider_domain) = ${WORKSPACE_OPENROUTER_CONNECTION_DOMAIN}) OR (metadata->>'credentialRole' = 'opper' AND lower(provider_domain) = ${WORKSPACE_OPPER_CONNECTION_DOMAIN}) OR (metadata->>'credentialRole' = 'anthropic' AND lower(provider_domain) = 'api.anthropic.com')) ORDER BY metadata->>'credentialRole', created_at DESC, id DESC ) selected`, ); for (const row of rows) restrictions[row.prefix] = row.allowedModelIds; }); const metadata = await sharedMetadata; const directConnections = metadata === undefined ? await listDirectModelConnections(db, workspaceId, subjectId) : metadata.filter((connection) => connection.workspaceId === workspaceId); for (const connection of directConnections) { const spec = directModelConnectionSpec(connection); if (spec) restrictions[`${spec.providerId}/`] = [spec.modelId]; } return restrictions; } export function modelAllowedByConnections( restrictions: ConnectionModelRestrictions, modelId: string, ): boolean { const prefix = Object.keys(restrictions).find((candidate) => modelId.startsWith(candidate)); return prefix === undefined || connectionModelAllowed(restrictions[prefix], modelId); } /** Authoritative turn gate after allocation, including pins and recovered leases. */ export async function assertModelConnectionAllowsTurn( db: Database, input: { workspaceId: string; subjectId: string; modelId: string; codexCredentialId?: string | null; workspaceProviderConnectionId?: string; }, ): Promise { const model = input.modelId; let query; if (isDirectModelId(model)) { const connection = ( await listDirectModelConnections(db, input.workspaceId, input.subjectId) ).find( (candidate) => directModelConnectionSpec(candidate)?.modelId === model && (!input.workspaceProviderConnectionId || candidate.id === input.workspaceProviderConnectionId), ); if (!connection) throw new Error( "This model connection is no longer available; reconnect and select its model", ); return; } const compatibleConnectionId = organizationCompatibleConnectionIdOf(model); if (compatibleConnectionId) { // One of the organization's own OpenAI-compatible endpoints: that exact // endpoint must still be active and reach this workspace. query = sql`SELECT allowed_model_ids AS models FROM organization_model_provider_connections WHERE provider_kind = 'openai_compatible' AND id = ${compatibleConnectionId}::uuid AND status = 'active'`; } else if ( model.startsWith("claude/") || model.startsWith("workspace-claude-subscription/") || model.startsWith("organization-claude-subscription/") || model.startsWith("codex/") || model.startsWith("supergrok/") ) { // Subscription requests require the exact core placement and lease; // this API-key helper cannot authorize a subscription dispatch. throw new Error("Subscription model access requires shared-core placement"); } else if ( model.startsWith("organization-gateway/") || model.startsWith("organization-openrouter/") || model.startsWith("organization-opper/") || model.startsWith("organization-openai/") || model.startsWith("organization-azure-openai/") || model.startsWith("organization-anthropic/") ) { query = sql`SELECT allowed_model_ids AS models FROM organization_model_provider_connections WHERE provider_kind = ${model.startsWith("organization-gateway/") ? "vercel_gateway" : model.startsWith("organization-anthropic/") ? "anthropic" : model.startsWith("organization-claude-subscription/") ? "claude_subscription" : model.startsWith("organization-opper/") ? "opper" : model.startsWith("organization-openai/") ? "openai" : model.startsWith("organization-azure-openai/") ? "azure_openai" : "openrouter"} AND status = 'active'`; } else if ( model.startsWith("workspace-gateway/") || model.startsWith("workspace-openrouter/") || model.startsWith("workspace-opper/") || model.startsWith("workspace-anthropic/") ) { const claude = model.startsWith("workspace-anthropic/") || model.startsWith("workspace-claude-subscription/"); query = sql`SELECT allowed_model_ids AS models FROM connections WHERE workspace_id = ${input.workspaceId}::uuid AND subject_id IS NULL AND kind = 'api_key' AND status = 'active' AND metadata->>'credentialRole' = ${model.startsWith("workspace-gateway/") ? "vercel_ai_gateway" : model.startsWith("workspace-anthropic/") ? "anthropic" : model.startsWith("workspace-claude-subscription/") ? "claude_subscription" : model.startsWith("workspace-opper/") ? "opper" : "openrouter"} AND lower(provider_domain) = ${claude ? "api.anthropic.com" : model.startsWith("workspace-gateway/") ? VERCEL_AI_GATEWAY_CONNECTION_DOMAIN : model.startsWith("workspace-opper/") ? WORKSPACE_OPPER_CONNECTION_DOMAIN : WORKSPACE_OPENROUTER_CONNECTION_DOMAIN} ${input.workspaceProviderConnectionId ? sql`AND id = ${input.workspaceProviderConnectionId}::uuid` : sql``} ORDER BY created_at DESC, id DESC LIMIT 1`; } else return; const rows = await withWorkspaceSubjectRls(db, input.workspaceId, input.subjectId, (tx) => rawRows<{ models: string[] | null }>(tx, query), ); if (!rows.some((row) => connectionModelAllowed(row.models, model))) throw new Error("This model is disabled for the selected connection or workspace"); }