Compare commits

..

1 Commits

Author SHA1 Message Date
diegosouzapw
17c3a693df fix(dashboard): surface auth-required banner for guest-session database settings (#12709)
/api/settings/database and /api/settings/import-json are intentionally
ALWAYS_PROTECTED (GHSA-mghq-58h3-qcqj, GHSA-v7g9-7f55-5g46) and correctly
401 a guest/anonymous session. SystemStorageTab.tsx silently collapsed
that 401 to null, so the entire database-settings section of Settings ->
General just disappeared with zero explanation ("Failed to load
settings").

Extract the fetch/detection logic into systemStorageAuth.tsx (new module,
keeps SystemStorageTab.tsx within its frozen file-size baseline) and
surface an explicit auth-required banner plus a dedicated JSON-import
error message instead of a blank page.
2026-09-10 15:34:48 -03:00
8 changed files with 162 additions and 155 deletions

View File

@@ -35,24 +35,16 @@ export function resolveOpencodeTarget(opts = {}) {
baseUrl = `http://localhost:${Number(opts.port ?? process.env.PORT ?? 20128) || 20128}`;
}
// Precedence: explicit --api-key flag > OMNIROUTE_API_KEY env var > active
// context's management token. A context's accessToken/apiKey is a CLI
// management credential (oma_live_...) with no /v1/* inference scope — it
// must never silently outrank a real inference key the caller supplied
// either as a flag or via the ambient env var (mirrors the explicit >
// ambient-env > context precedence documented in bin/cli/api.mjs's
// buildHeaders()). Only fall back to the context token when neither an
// explicit flag nor the env var is set.
let apiKey = opts.apiKey ?? opts["api-key"];
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
if (!apiKey) {
try {
const c = resolveActiveContext(opts.context ?? process.env.OMNIROUTE_CONTEXT);
apiKey = c?.accessToken || c?.apiKey || "";
apiKey = c?.accessToken || c?.apiKey;
} catch {
/* no context auth */
}
}
if (!apiKey) apiKey = process.env.OMNIROUTE_API_KEY || "";
return { baseUrl: baseUrl.replace(/\/+$/, ""), apiKey };
}
@@ -185,17 +177,8 @@ export function registerSetupOpencode(program) {
"--allow-container-write",
"Write even when the target is inside a container and not mounted from the host"
)
.action(async (opts, cmd) => {
// Commander parses the ancestor program's own global --api-key option
// (bin/cli/program.mjs, bound to .env("OMNIROUTE_API_KEY")) against any
// occurrence of the flag in argv, so it wins the value even when the
// user typed --api-key AFTER `setup-opencode` — this local option's own
// `opts.apiKey` never sees it. cmd.optsWithGlobals() resolves to the
// correct value either way ("globals overwrite locals" is exactly the
// outcome we want here, since the global option is where the value
// always actually lands).
const resolvedOpts = { ...opts, apiKey: cmd.optsWithGlobals().apiKey ?? opts.apiKey };
const code = await runSetupOpencodeCommand(resolvedOpts);
.action(async (opts) => {
const code = await runSetupOpencodeCommand(opts);
if (code !== 0) process.exit(code);
});
}

View File

@@ -0,0 +1 @@
- fix(dashboard): surface an authentication-required banner instead of silently blanking database settings for a guest session (#12709)

View File

@@ -1 +0,0 @@
- fix(cli): setup-opencode no longer sends an active context's management token to `/v1/models` when `--api-key`/`OMNIROUTE_API_KEY` is supplied — an explicit flag or the env var now always outranks the context's token, and the flag itself is no longer swallowed by the parent program's global `--api-key` option (#12783)

View File

@@ -4,6 +4,11 @@ import { useState, useEffect, useCallback, useRef } from "react";
import { Card, Button, Badge, ConfirmModal } from "@/shared/components";
import { useLocale, useTranslations } from "next-intl";
import DatabaseBackupRetentionCard from "./DatabaseBackupRetentionCard";
import {
fetchDatabaseSettingsData,
isAuthRequiredResponse,
AuthRequiredBanner,
} from "./systemStorageAuth";
// Whitelist mirrored from src/lib/db/cleanup.ts::RESET_USAGE_HISTORY_PERIODS.
const RESET_USAGE_PERIOD_VALUES = [
@@ -29,16 +34,6 @@ async function fetchStorageHealthData() {
}
}
async function fetchDatabaseSettingsData() {
try {
const res = await fetch("/api/settings/database");
if (res.ok) return await res.json();
} catch (err) {
console.error("Failed to load database settings:", err);
}
return null;
}
export default function SystemStorageTab() {
const [backups, setBackups] = useState([]);
const [backupsLoading, setBackupsLoading] = useState(false);
@@ -108,6 +103,7 @@ export default function SystemStorageTab() {
// Database settings state (tasks 23-26)
const [dbSettings, setDbSettings] = useState<any>(null);
const [dbSettingsLoading, setDbSettingsLoading] = useState(true);
const [dbSettingsAuthRequired, setDbSettingsAuthRequired] = useState(false);
const [dbSettingsSaving, setDbSettingsSaving] = useState(false);
const [dbStatsRefreshing, setDbStatsRefreshing] = useState(false);
@@ -137,8 +133,9 @@ export default function SystemStorageTab() {
applyStorageHealth(await fetchStorageHealthData());
};
const applyDatabaseSettings = useCallback((data) => {
if (data) setDbSettings(data);
const applyDatabaseSettings = useCallback((result: { data: any; authRequired: boolean }) => {
if (result.data) setDbSettings(result.data);
setDbSettingsAuthRequired(result.authRequired);
setDbSettingsLoading(false);
}, []);
@@ -589,6 +586,8 @@ export default function SystemStorageTab() {
});
await loadStorageHealth();
if (backupsExpanded) await loadBackups();
} else if (isAuthRequiredResponse(res.status, data)) {
setImportStatus({ type: "error", message: t("jsonImportAuthRequired") });
} else {
setImportStatus({ type: "error", message: data.error || t("jsonImportFailed") });
}
@@ -1290,6 +1289,7 @@ export default function SystemStorageTab() {
</div>
</div>
{dbSettingsAuthRequired && !dbSettingsLoading && <AuthRequiredBanner t={t} />}
{renderDatabaseStatistics()}
<div className="pt-3 border-t border-border/50 mb-4">

View File

@@ -0,0 +1,57 @@
"use client";
// #12709: database-settings requests are ALWAYS_PROTECTED (routeGuard.ts) — a guest/anonymous
// session correctly gets a 401 AUTH_001 from /api/settings/database and /api/settings/import-json
// (GHSA-mghq-58h3-qcqj, GHSA-v7g9-7f55-5g46). Do NOT loosen that gate; this module only makes the
// client surface the failure instead of silently rendering a blank section.
import Link from "next/link";
export interface DatabaseSettingsFetchResult {
data: unknown;
authRequired: boolean;
}
/**
* True when a response represents the intentional auth-required rejection
* (401, optionally carrying the AUTH_001 error code) rather than some other
* transient failure.
*/
export function isAuthRequiredResponse(status: number, data: unknown): boolean {
if (status !== 401) return false;
const code = (data as { error?: { code?: string } } | null)?.error?.code;
return code === undefined || code === "AUTH_001";
}
export async function fetchDatabaseSettingsData(): Promise<DatabaseSettingsFetchResult> {
try {
const res = await fetch("/api/settings/database");
const body = await res.json().catch(() => null);
if (res.ok) return { data: body, authRequired: false };
return { data: null, authRequired: isAuthRequiredResponse(res.status, body) };
} catch (err) {
console.error("Failed to load database settings:", err);
return { data: null, authRequired: false };
}
}
export function AuthRequiredBanner({ t }: { t: (key: string) => string }) {
return (
<div
role="alert"
className="mb-4 rounded-xl border border-amber-200 dark:border-amber-500/30 bg-amber-50 dark:bg-amber-500/10 px-5 py-4"
>
<h2 className="text-sm font-semibold text-amber-900 dark:text-amber-100">
{t("databaseSettingsAuthRequiredTitle")}
</h2>
<p className="mt-1 text-sm text-amber-900/80 dark:text-amber-200/80">
{t("databaseSettingsAuthRequiredBody")}
</p>
<Link
href="/login"
className="mt-3 inline-flex items-center rounded-lg bg-amber-600 px-3.5 py-2 text-sm font-medium text-white hover:bg-amber-700 dark:bg-amber-500 dark:hover:bg-amber-400"
>
{t("databaseSettingsAuthRequiredCta")}
</Link>
</div>
);
}

View File

@@ -7741,6 +7741,10 @@
"legacyJsonImportSuccess": "Legacy JSON imported successfully!",
"jsonImportFailed": "Failed to import JSON",
"jsonImportError": "Error during JSON import",
"jsonImportAuthRequired": "Authentication required to import a legacy JSON configuration. Please sign in or complete setup first.",
"databaseSettingsAuthRequiredTitle": "Authentication required",
"databaseSettingsAuthRequiredBody": "Database settings and JSON import are only available to an authenticated admin. Sign in or complete setup to view and edit them.",
"databaseSettingsAuthRequiredCta": "Sign in",
"storagePurgeData": "Purge Data",
"storagePurgeDataDesc": "Immediately delete all records without applying retention checks. Use with caution.",
"storageRetentionCleanup": "Retention Settings",

View File

@@ -1,121 +0,0 @@
import assert from "node:assert/strict";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { resolveOpencodeTarget } from "../../bin/cli/commands/setup-opencode.mjs";
/** Point OMNIROUTE_CONTEXT config resolution at an isolated, throwaway DATA_DIR. */
function withIsolatedContext(contextConfig, fn) {
const dir = mkdtempSync(join(tmpdir(), "omniroute-setup-opencode-test-"));
const originalDataDir = process.env.DATA_DIR;
process.env.DATA_DIR = dir;
writeFileSync(
join(dir, "config.json"),
JSON.stringify({
version: 1,
currentContext: "remote",
contexts: { remote: contextConfig },
})
);
try {
return fn();
} finally {
if (originalDataDir === undefined) delete process.env.DATA_DIR;
else process.env.DATA_DIR = originalDataDir;
rmSync(dir, { recursive: true, force: true });
}
}
function withEnvApiKey(value, fn) {
const original = process.env.OMNIROUTE_API_KEY;
if (value === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = value;
try {
return fn();
} finally {
if (original === undefined) delete process.env.OMNIROUTE_API_KEY;
else process.env.OMNIROUTE_API_KEY = original;
}
}
test("setup-opencode: --api-key typed AFTER the subcommand name is not stolen by the parent program's global option", async () => {
const { createProgram } = await import("../../bin/cli/program.mjs");
const program = createProgram();
const setupOpencode = program.commands.find((c) => c.name() === "setup-opencode");
assert.ok(setupOpencode, "setup-opencode subcommand must be registered");
let capturedApiKey;
setupOpencode._actionHandler = null; // avoid the real network-calling action
setupOpencode.action((opts, cmd) => {
capturedApiKey = cmd.optsWithGlobals().apiKey ?? opts.apiKey;
});
await program.parseAsync(
[
"node",
"omniroute",
"setup-opencode",
"--remote",
"http://100.64.0.1:20128",
"--api-key",
"sk-TESTKEY123",
],
{ from: "node" }
);
assert.equal(
capturedApiKey,
"sk-TESTKEY123",
"the CLI-supplied --api-key value must reach the setup-opencode action handler"
);
});
test("resolveOpencodeTarget: (a) explicit --api-key flag wins over an active context's management token", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ apiKey: "sk-FLAG", context: "remote" });
assert.equal(apiKey, "sk-FLAG");
}
);
});
});
test("resolveOpencodeTarget: (b) OMNIROUTE_API_KEY env wins over an active context's management token when no flag is passed", () => {
withEnvApiKey("sk-ENVKEY", () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "sk-ENVKEY");
}
);
});
});
test("resolveOpencodeTarget: (c) the context's token is used only when neither a flag nor the env var is set", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext(
{ baseUrl: "http://100.64.0.1:20128", accessToken: "oma_live_CONTEXT_TOKEN" },
() => {
const { apiKey } = resolveOpencodeTarget({ context: "remote" });
assert.equal(apiKey, "oma_live_CONTEXT_TOKEN");
}
);
});
});
test("resolveOpencodeTarget: falls back to '' when neither a flag, env var, nor a resolvable context is present", () => {
withEnvApiKey(undefined, () => {
withIsolatedContext({ baseUrl: "http://100.64.0.1:20128" }, () => {
const { apiKey } = resolveOpencodeTarget({
remote: "http://100.64.0.1:20128",
context: "__no-such-context__",
});
assert.equal(apiKey, "");
});
});
});

View File

@@ -0,0 +1,84 @@
// @vitest-environment jsdom
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import SystemStorageTab from "@/app/(dashboard)/dashboard/settings/components/SystemStorageTab";
vi.mock("next-intl", () => ({
useTranslations: () => (key: string) => key,
useLocale: () => "en",
}));
const roots: Array<{ root: Root; el: HTMLDivElement }> = [];
async function render(): Promise<HTMLDivElement> {
const el = document.createElement("div");
document.body.appendChild(el);
const root = createRoot(el);
await act(async () => {
root.render(<SystemStorageTab />);
});
roots.push({ root, el });
return el;
}
async function flush() {
await act(async () => {
await new Promise((resolve) => setTimeout(resolve, 10));
});
}
describe("#12709 - SystemStorageTab guest-session 401 on /api/settings/database", () => {
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/api/settings/database")) {
return new Response(
JSON.stringify({ error: { code: "AUTH_001", message: "Authentication required" } }),
{ status: 401, headers: { "Content-Type": "application/json" } }
);
}
if (url.includes("/api/storage/health")) {
return new Response(
JSON.stringify({
driver: "sqlite",
dbPath: "~/.omniroute/storage.sqlite",
sizeBytes: 0,
retentionDays: { app: 7, call: 7 },
tableMaxRows: { callLogs: 100000, proxyLogs: 100000 },
backupCount: 0,
backupRetention: { maxFiles: 20, days: 0 },
lastBackupAt: null,
}),
{ status: 200, headers: { "Content-Type": "application/json" } }
);
}
return new Response("{}", { status: 200 });
});
(globalThis as any).fetch = fetchMock;
});
afterEach(() => {
for (const { root, el } of roots.splice(0)) {
act(() => root.unmount());
el.remove();
}
vi.restoreAllMocks();
});
it("surfaces an authentication-required message instead of silently hiding Settings", async () => {
const container = await render();
await flush();
await flush();
const dbCall = fetchMock.mock.calls.find((c) => String(c[0]).includes("/api/settings/database"));
expect(dbCall).toBeTruthy();
const text = container.textContent || "";
const mentionsAuth = /auth|sign in|log in|login|401|unauthorized/i.test(text);
expect(mentionsAuth).toBe(true);
});
});