Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

3.3 KB
Raw Blame
import { getDbInstance } from "../core";

export const PROXY_ALIVE_PREDICATE =
  "(p.status IS NULL OR LOWER(p.status) NOT IN ('inactive','error','disabled','dead','down'))";

const PROXY_UNAVAILABLE_STATUSES = new Set(["inactive", "error", "disabled", "dead", "down"]);

/** Keep by-id account proxy resolution aligned with the pool alive predicate above. */
export function isProxyRegistryStatusAlive(status: unknown): boolean {
  return status == null || !PROXY_UNAVAILABLE_STATUSES.has(String(status).toLowerCase());
}

export function isGlobalProxyEnabled(db: ReturnType<typeof getDbInstance>): boolean {
  try {
    const row = db
      .prepare("SELECT value FROM key_value WHERE namespace = 'settings' AND key = 'proxyEnabled'")
      .get() as { value?: string } | undefined;
    if (!row?.value) return true;
    try {
      return JSON.parse(row.value) !== false;
    } catch {
      return true;
    }
  } catch {
    return true;
  }
}

/**
 * #6246 fail-closed guard for a connection with an assigned dead proxy pool.
 * Explicitly disabling proxying globally or for the connection allows direct egress.
 */
export function hasBlockingProxyAssignment(
  connectionId: string,
  providerId?: string,
  comboName?: string | null
): boolean {
  try {
    const db = getDbInstance();
    if (!isGlobalProxyEnabled(db)) return false;

    const conn = db
      .prepare("SELECT provider, proxy_enabled FROM provider_connections WHERE id = ?")
      .get(connectionId) as { provider?: string | null; proxy_enabled?: number } | undefined;
    if (conn && conn.proxy_enabled === 0) return false;
    const provider = conn?.provider ?? providerId ?? null;
    // #13469: include combo scope — a fully dead combo-scoped pool must not
    // fall through to direct egress.
    const dead = db
      .prepare(
        `SELECT 1 FROM proxy_assignments a JOIN proxy_registry p ON p.id = a.proxy_id
           WHERE ((a.scope = 'account' AND a.scope_id = ?)
               OR (a.scope = 'provider' AND a.scope_id = ?)
               OR (a.scope = 'global')
               OR (a.scope = 'combo' AND a.scope_id = ?))
             AND NOT ${PROXY_ALIVE_PREDICATE}
           LIMIT 1`
      )
      .get(connectionId, provider, comboName ?? null);
    return !!dead;
  } catch {
    return false;
  }
}

/**
 * #7380 fail-closed guard for providers without a connection row. Returns true
 * when a provider/global proxy assignment exists but all assigned proxies are known dead.
 */
export function hasBlockingProxyAssignmentForProvider(providerId: string): boolean {
  try {
    const db = getDbInstance();
    if (!isGlobalProxyEnabled(db)) return false;

    const assignments = db
      .prepare(
        `SELECT
           EXISTS(
             SELECT 1 FROM proxy_assignments a
             WHERE ((a.scope = 'provider' AND a.scope_id = ?)
                 OR a.scope = 'global')
           ) AS assigned,
           EXISTS(
             SELECT 1 FROM proxy_assignments a JOIN proxy_registry p ON p.id = a.proxy_id
             WHERE ((a.scope = 'provider' AND a.scope_id = ?)
                 OR a.scope = 'global')
               AND ${PROXY_ALIVE_PREDICATE}
           ) AS alive`
      )
      .get(providerId, providerId) as { assigned?: number; alive?: number } | undefined;
    return assignments?.assigned === 1 && assignments.alive === 0;
  } catch {
    return false;
  }
}