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.5 KB
Raw Blame
/**
 * Shared helpers for /api/services/dario/admin/* route handlers.
 *
 * These routes are a thin, SERVER-SIDE proxy in front of the running Dario
 * instance's headless `/admin/*` control plane. The real DARIO_ADMIN_TOKEN
 * (stored encrypted in version_manager.api_key, generated by getOrCreateApiKey)
 * must NEVER reach the browser — the webUI calls these OmniRoute routes, which
 * attach the bearer token here and forward to Dario on loopback.
 *
 * Auth gating mirrors the CLIProxyAPI OAuth import route
 * (src/app/api/oauth/cliproxy-import/route.ts): when auth is required and the
 * caller isn't authenticated, 401. The routes live under /api/services/ which
 * routeGuard.ts already classifies LOCAL_ONLY.
 */

import { NextResponse } from "next/server";
import { getServiceRow } from "@/lib/db/versionManager";
import { decrypt } from "@/lib/db/encryption";
import { isAuthRequired, isAuthenticated } from "@/shared/utils/apiAuth";
import { DARIO_DEFAULT_PORT } from "@/lib/services/installers/dario";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";

export function darioBaseUrl(): string {
  const host = process.env.DARIO_HOST || "127.0.0.1";
  const port = parseInt(process.env.DARIO_PORT || String(DARIO_DEFAULT_PORT), 10);
  return `http://${host}:${port}`;
}

/** 401 response when auth is required and the caller isn't authenticated; else null. */
export async function requireAdminAuth(request: Request): Promise<Response | null> {
  if (!(await isAuthRequired(request))) return null;
  if (await isAuthenticated(request)) return null;
  return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

/** Read the stored (decrypted) DARIO_ADMIN_TOKEN, or null if unavailable. */
export async function getDarioAdminToken(): Promise<string | null> {
  const row = await getServiceRow("dario");
  if (!row?.apiKey) return null;
  const decrypted = decrypt(row.apiKey);
  return decrypted || null;
}

type ForwardOptions = {
  method: "GET" | "POST" | "DELETE";
  path: string; // e.g. "/admin/login/start"
  body?: unknown; // JSON body for POST
};

/**
 * Forward a call to the running Dario instance's /admin/* endpoint with the
 * stored admin bearer token attached. Returns a NextResponse mirroring Dario's
 * status + JSON body, or a friendly error when Dario is unreachable / the token
 * is missing.
 */
export async function forwardToDarioAdmin(opts: ForwardOptions): Promise<Response> {
  const token = await getDarioAdminToken();
  if (!token) {
    return NextResponse.json(
      { error: "Dario admin token unavailable — is Dario installed and started?" },
      { status: 409 }
    );
  }

  const url = `${darioBaseUrl()}${opts.path}`;
  try {
    const res = await fetch(url, {
      method: opts.method,
      headers: {
        Authorization: `Bearer ${token}`,
        ...(opts.body !== undefined ? { "Content-Type": "application/json" } : {}),
      },
      ...(opts.body !== undefined ? { body: JSON.stringify(opts.body) } : {}),
      signal: AbortSignal.timeout(15_000),
    });

    // Pass through Dario's JSON body + status verbatim (never the token).
    const text = await res.text();
    let payload: unknown;
    try {
      payload = text ? JSON.parse(text) : {};
    } catch {
      payload = { error: text };
    }
    return NextResponse.json(payload, { status: res.status });
  } catch (err) {
    return NextResponse.json(
      {
        error: `Could not reach Dario admin API at ${url}: ${sanitizeErrorMessage(
          err instanceof Error ? err.message : String(err)
        )}`,
      },
      { status: 502 }
    );
  }
}