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 { NextResponse } from "next/server";
import path from "path";
import fs from "fs";
import os from "os";
import { getDbInstance, SQLITE_FILE } from "@/lib/db/core";
import {
  CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
  requireOperatorCredential,
} from "@/lib/api/operatorCredential";
import { sanitizeErrorMessage } from "@omniroute/open-sse/utils/error";

/**
 * GET /api/db-backups/export — Download the current database as a .sqlite file.
 *
 * Uses SQLite's native backup API to create a consistent snapshot,
 * then streams it as a downloadable attachment.
 *
 * 🔒 Operator-only: dashboard session, local CLI, or login disabled. API keys (any scope)
 *    and `oma_` access tokens get 403 — the file carries every stored credential.
 */
export async function GET(request: Request) {
  // Hands out every stored credential: operator only (dashboard session, local CLI, or login
  // disabled). API keys of any scope and `oma_` access tokens get 403.
  const operatorVerdict = await requireOperatorCredential(request, {
    forbiddenMessage: CREDENTIAL_EXPORT_FORBIDDEN_MESSAGE,
  });
  if (operatorVerdict.ok === false) return operatorVerdict.response;
  try {
    if (!SQLITE_FILE || !fs.existsSync(SQLITE_FILE)) {
      return NextResponse.json({ error: "Database file not found" }, { status: 404 });
    }

    const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
    const exportFilename = `omniroute-backup-${timestamp}.sqlite`;
    // Use mkdtempSync (exclusive creation, random suffix) instead of a
    // deterministic timestamp path — a predictable path lets a local
    // attacker pre-place a symlink and redirect the write (TOCTOU).
    const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-backup-"));
    const tmpPath = path.join(tmpDir, "backup.sqlite");

    // Use native SQLite backup API for a consistent snapshot
    const db = getDbInstance();
    try {
      await db.backup(tmpPath);
    } catch (backupError) {
      fs.rmSync(tmpDir, { recursive: true, force: true });
      throw backupError;
    }

    const { size: fileSize } = fs.statSync(tmpPath);
    const readStream = fs.createReadStream(tmpPath);

    // Cleanup temp dir (and everything in it) on completion, error, or client abort
    const cleanup = () => {
      readStream.destroy();
      fs.rm(tmpDir, { recursive: true, force: true }, () => {});
    };
    request.signal.addEventListener("abort", cleanup, { once: true });

    const webStream = new ReadableStream({
      start(controller) {
        readStream.on("data", (chunk) => controller.enqueue(chunk));
        readStream.on("end", () => {
          controller.close();
          cleanup();
        });
        readStream.on("error", (err) => {
          controller.error(err);
          cleanup();
        });
      },
      cancel() {
        cleanup();
      },
    });

    return new Response(webStream, {
      status: 200,
      headers: {
        "Content-Type": "application/octet-stream",
        "Content-Disposition": `attachment; filename="${exportFilename}"`,
        "Content-Length": String(fileSize),
        "Cache-Control": "no-cache, no-store",
      },
    });
  } catch (error) {
    console.error("[API] Error exporting database:", error);
    return NextResponse.json({ error: sanitizeErrorMessage(error) }, { status: 500 });
  }
}