Files
OmniRoute/src/shared/utils/apiAuth.ts
Diego Rodrigues de Sa e Souza a25d5f1ef6 Release v3.8.13 (#3327)
* chore(release): open v3.8.13 development cycle

Bump 3.8.12 → 3.8.13 across package.json, lockfile, electron/, open-sse/, and
docs/reference/openapi.yaml; add the [3.8.13] cycle placeholder to the root
CHANGELOG and the 41 i18n mirrors. Integration branch for the v3.8.13 cycle —
fixes/features land here via per-issue PRs and it merges to main at release time.

* fix(ci): skip auto-deploy when VPS host is unreachable from the runner (#3299)

Integrated into release/v3.8.13

* fix(dev): auto-rebuild better-sqlite3 on Node ABI mismatch at dev startup (#3301)

Integrated into release/v3.8.13

* feat(api): accept path-scoped API keys on client API routes (#3300)

Integrated into release/v3.8.13

* fix(sse): harden against empty responses causing Copilot Chat failures (#3297)

Integrated into release/v3.8.13

* fix(api): remove Completions.me rickroll provider (discussion #3293) (#3302)

Integrated into release/v3.8.13

* fix(opencode-provider): extract contextLength from live model catalog (#3298)

Integrated into release/v3.8.13

* feat(web-cookie): self-service login infrastructure + auto-refresh daemon (#3292)

Integrated into release/v3.8.13

* docs(changelog): record the v3.8.13 PRs merged this round (#3292/#3300/#3297/#3298/#3301/#3302/#3299)

* fix(auth): harden URL token extraction — drop query-string fallback, gate to client routes (security follow-up to #3300) (#3309)

Security follow-up to #3300 — integrated into release/v3.8.13

* docs: rename resolve-issues → review-issues skill references

* fix(dashboard): keep no-auth providers visible under 'Show configured only' (#3290) (#3312)

no-auth providers (opencode, duckduckgo-web, theoldllm, veoaifree-web) never
create a DB connection row so stats.total stays 0, which the configured-only
filter treated as 'unconfigured' and hid them — even though they are always
usable and appear unconditionally in /v1/models. filterConfiguredProviderEntries
now treats displayAuthType === 'no-auth' as configured.

Co-authored-by: uniQta <uniQta@users.noreply.github.com>

* fix(cli): resolve update paths relative to script + recursive backup (#3295) (#3313)

omniroute update always failed on a global install:
- getCurrentVersion() read package.json from process.cwd(), which on a global
  npm/brew install is the user's working dir, not the package root → null →
  'Could not determine current version'.
- createBackup() resolved bin/ from cwd too, and passed the 'cli' directory to
  copyFileSync → EISDIR, swallowed by the catch → 'Failed to create backup'.

Both now resolve package.json/bin relative to the script via import.meta.url,
and the backup uses cpSync({recursive:true}) so the cli/ directory is copied.

Co-authored-by: uniQta <uniQta@users.noreply.github.com>

* fix(theoldllm): read upstream body once to avoid [502] body-already-read (#3296) (#3314)

On the cached-token path the executor never enters the refresh branch, so the
same upstream Response was read with .text() twice (token-rejection check +
final body). A Response body is single-use, so the second read threw
'Body is unusable: Body has already been read', caught and surfaced as [502].

Read the body once into finalBody and only re-read after a token-rejection
refetch.

Co-authored-by: onizukashonan14-png <onizukashonan14-png@users.noreply.github.com>

* fix(sse): strip leaked internal tool envelopes from streaming output (#3311)

Integrated into release/v3.8.13

* fix(sse): expose Claude + Gemini budget tiers in the antigravity catalog (#3184) (#3303)

Integrated into release/v3.8.13 (#3184)

* fix(catalog): compute combo context_length from known targets only (#3304)

Integrated into release/v3.8.13 — live contextLength + known-targets combo context (#3298 follow-up)

* chore(i18n): add message keys for proxy UI + vscode/ollama endpoint (#3307)

Integrated into release/v3.8.13 — i18n message keys for proxy UI + vscode/ollama

* feat(dashboard): i18n the proxy settings UI (#3310)

Integrated into release/v3.8.13 — i18n the proxy settings UI

* feat(api): model catalog enrichment + MCP model-catalog tools (#3306)

Integrated into release/v3.8.13 — model catalog enrichment + MCP model-catalog tools, reconciled with #3309 URL-token hardening

* test(catalog): align Antigravity preview-alias test with #3303 budget tiers

#3303 added the Gemini `-high`/`-low` budget tiers to ANTIGRAVITY_PUBLIC_MODELS
(user-callable on the Antigravity OAuth backend, verified via #3184), but did
not update the catalog-route test that asserted `antigravity/gemini-3.1-pro-high`
must NOT be exposed. The assertion now reflects the intended behavior — the
client-visible budget alias IS surfaced — while keeping the legacy
`gemini-claude-*` alias keys unexposed. Caught running the full catalog suite
on the merged release HEAD (the #3303 round only ran the antigravity-aliases
and usage-hardening files).

* docs(changelog): record the 6 PRs merged this review round into v3.8.13

#3306/#3307/#3310 (New Features — VS Code split: catalog+MCP, i18n keys, proxy
UI i18n), #3311/#3303/#3304 (Bug Fixes — SSE envelope sanitizer, antigravity
budget tiers, combo known-targets context_length).

* chore(release): finalize v3.8.13 changelog and cleanup

Finalize the v3.8.13 changelog with release date, maintenance notes,
and contributor credits. Update MCP docs to reference the correct tool
inventory diagram, exclude nested .claude worktrees from ESLint scans,
and tighten a response sanitizer type guard.

* fix(dashboard): refresh connections after provider auth import (#3320)

Integrated into release/v3.8.13 — refresh connections after provider auth import

* fix(codex): strip client-only params on native /responses passthrough (#3317) (#3325)

A /v1/responses request against the built-in codex/ provider does an
openai-responses -> openai-responses passthrough (CodexExecutor.transformRequest
returns the body early for _nativeCodexPassthrough). It forwarded client-only
fields verbatim and the Codex upstream rejected them with 400 Unsupported
parameter: prompt_cache_retention / safety_identifier / user — breaking Factory
Droid (which injects all three). The chat-completions path already strips these
(base.ts #1884, openai-responses translator #2770) but the passthrough skips
translation. Strip the three fields in the shared block before the passthrough
return; user is removed unconditionally since Codex /responses always rejects it.

Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com>

* fix(dashboard): normalize agent-bridge /state response to stop page crash (#3318) (#3326)

The Agent Bridge page seeded a well-shaped initialData default then replaced it
wholesale with the raw /api/tools/agent-bridge/state response. The route returns
{ server, agents } but the UI reads { serverState, agentStates, bypassPatterns,
mappings }, so serverState became undefined and AgentBridgeServerCard crashed on
serverState.running — surfaced as the full-page 'Internal Server Error' boundary
(client render error, not a real 5xx).

Add a shared normalizeAgentBridgeState() that maps the route shape into the page
contract (server.running/certExists -> serverState) and always returns safe
defaults (never undefined serverState). Wired into both the SSR loader (page.tsx)
and the polling hook. The legacy 'agents' entry shape differs from AgentStateEntry
so it is not coerced; full route<->page contract reconciliation (port, upstreamCa,
bypassPatterns, mappings, agentStates) is a follow-up.

Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com>

* docs: VS Code/Ollama endpoints + env & i18n tooling (#3319)

Integrated into release/v3.8.13 — VS Code/Ollama docs + env & i18n tooling

* feat(provider): test-all endpoint, rate-limit overrides, visibility f… (#3267)

Integrated into release/v3.8.13 — provider test-all endpoint, rate-limit overrides, model visibility

* feat: auto-combo optimization, playground model dropdown, only-configured toggle (#3322)

Integrated into release/v3.8.13 — auto-combo candidate expansion + playground dropdown + only-configured toggle

* feat(api): VS Code Copilot Ollama-compatible BYOK endpoint (#3316)

Integrated into release/v3.8.13 — VS Code Copilot Ollama-compatible BYOK endpoint (reconciled with #3306/#3309 auth hardening)

* chore(release): document #3320 in the v3.8.13 changelog + contributor credits

---------

Co-authored-by: Felipe Almeman <4226997+zhiru@users.noreply.github.com>
Co-authored-by: Wilson <pedbookmed@gmail.com>
Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: uniQta <uniQta@users.noreply.github.com>
Co-authored-by: onizukashonan14-png <onizukashonan14-png@users.noreply.github.com>
Co-authored-by: tycronk20 <tycronk20@users.noreply.github.com>
Co-authored-by: Vinayrnani <vinayrnani@gmail.com>
2026-06-06 19:13:11 -03:00

355 lines
11 KiB
TypeScript

/**
* API Authentication Guard — Shared utility for protecting API routes.
*
* Management APIs require a dashboard session, while client-facing APIs may still
* accept Bearer API keys. Route scope is inferred from the request pathname.
*
* @module shared/utils/apiAuth
*/
import { jwtVerify } from "jose";
import { cookies } from "next/headers";
import { getSettings } from "@/lib/localDb";
import { isPublicApiRoute } from "@/shared/constants/publicApiRoutes";
import { extractApiKey } from "@/sse/services/auth";
type RequestLike = {
cookies?: {
get?: (name: string) => { value?: string } | undefined;
};
headers?: Headers;
method?: string;
nextUrl?: { hostname?: string | null; pathname?: string | null } | null;
url?: string;
};
const LOOPBACK_HOSTNAMES = new Set(["localhost", "::1"]);
function hasConfiguredPassword(settings: Record<string, unknown>): boolean {
return typeof settings.password === "string" && settings.password.length > 0;
}
function getRequestPathname(request: RequestLike | Request | null | undefined): string | null {
const nextPathname =
request &&
typeof request === "object" &&
"nextUrl" in request &&
request.nextUrl &&
typeof request.nextUrl.pathname === "string"
? request.nextUrl.pathname
: null;
if (nextPathname) return nextPathname;
const rawUrl =
request && typeof request === "object" && "url" in request && typeof request.url === "string"
? request.url
: "";
if (!rawUrl) return null;
try {
return new URL(rawUrl, "http://localhost").pathname;
} catch {
return null;
}
}
function isOnboardingBootstrapPath(pathname: string | null): boolean {
return pathname === "/dashboard/onboarding";
}
function isRequireLoginBootstrapWritePath(pathname: string | null, method: string): boolean {
return pathname === "/api/settings/require-login" && method.toUpperCase() === "POST";
}
function getRequestMethod(request: RequestLike | Request | null | undefined): string {
if (
request &&
typeof request === "object" &&
"method" in request &&
typeof request.method === "string"
) {
return request.method.toUpperCase();
}
return "GET";
}
function getRequestHostname(request: RequestLike | Request | null | undefined): string | null {
const nextHostname =
request &&
typeof request === "object" &&
"nextUrl" in request &&
request.nextUrl &&
typeof request.nextUrl.hostname === "string"
? request.nextUrl.hostname
: null;
if (nextHostname) return nextHostname;
const rawUrl =
request && typeof request === "object" && "url" in request && typeof request.url === "string"
? request.url
: "";
if (rawUrl) {
try {
return new URL(rawUrl, "http://localhost").hostname;
} catch {
// Fall through to Host header parsing.
}
}
const requestHeaders =
request && typeof request === "object" && "headers" in request ? request.headers : undefined;
const host = requestHeaders?.get("host") || requestHeaders?.get("Host") || null;
if (!host) return null;
try {
return new URL(`http://${host}`).hostname;
} catch {
return host.split(":")[0] || null;
}
}
export function isLoopbackRequest(request: RequestLike | Request | null | undefined): boolean {
const hostname = getRequestHostname(request);
if (!hostname) return false;
const normalized = hostname
.trim()
.toLowerCase()
.replace(/^\[(.*)\]$/, "$1");
if (LOOPBACK_HOSTNAMES.has(normalized)) return true;
if (/^127(?:\.\d{1,3}){3}$/.test(normalized)) return true;
return false;
}
function getCookieValueFromHeader(headers: Headers | undefined, name: string): string | null {
const cookieHeader = headers?.get("cookie") || headers?.get("Cookie");
if (!cookieHeader) return null;
for (const segment of cookieHeader.split(";")) {
const [rawKey, ...rawValue] = segment.split("=");
if (!rawKey || rawValue.length === 0) continue;
if (rawKey.trim() !== name) continue;
return rawValue.join("=").trim();
}
return null;
}
function getRequestApiKey(
request: RequestLike | Request | null | undefined,
opts?: { allowUrl?: boolean }
): string | null {
if (!request || typeof request !== "object") return null;
const headers = "headers" in request ? request.headers : undefined;
const rawUrl = "url" in request && typeof request.url === "string" ? request.url : null;
const pathname = getRequestPathname(request);
const syntheticUrl = rawUrl || (pathname ? `http://localhost${pathname}` : null);
// Management auth never honours a URL-borne credential (defence-in-depth: the
// path-scoped token is a client-API affordance only — a credential in the URL
// must not authenticate a management route). See the #3300 security follow-up.
const allowUrl = opts?.allowUrl !== false;
return extractApiKey({ headers, url: allowUrl ? syntheticUrl : null }, { allowUrl });
}
async function validateBearerApiKey(apiKey: string | null): Promise<boolean> {
if (!apiKey) return false;
try {
const { validateApiKey } = await import("@/lib/db/apiKeys");
return await validateApiKey(apiKey);
} catch {
return false;
}
}
/**
* Check whether a Bearer API key is valid AND carries a scope that authorizes
* it on management API routes (`/api/*` excluding `/api/v1/*` and the public
* allowlist). Returns `false` for unscoped keys so that the existing
* default-deny posture on management routes is preserved.
*
* Scope set is sourced from `@/shared/constants/managementScopes` so this
* helper stays in lockstep with `requireManagementAuth.hasManageScope`.
*/
async function validateBearerApiKeyForManagement(apiKey: string | null): Promise<boolean> {
if (!apiKey) return false;
try {
const [{ validateApiKey, getApiKeyMetadata }, { hasManageScope }] = await Promise.all([
import("@/lib/db/apiKeys"),
import("@/shared/constants/managementScopes"),
]);
const valid = await validateApiKey(apiKey);
if (!valid) return false;
const metadata = await getApiKeyMetadata(apiKey);
if (!metadata) return false;
return hasManageScope(metadata.scopes);
} catch {
return false;
}
}
export function isManagementApiRequest(request: RequestLike | Request): boolean {
const pathname = getRequestPathname(request);
if (!pathname?.startsWith("/api/")) return false;
if (pathname.startsWith("/api/v1/")) return false;
return !isPublicApiRoute(pathname, getRequestMethod(request));
}
export async function isDashboardSessionAuthenticated(
request?: RequestLike | Request | null
): Promise<boolean> {
if (!process.env.JWT_SECRET) return false;
let token =
request &&
typeof request === "object" &&
"cookies" in request &&
request.cookies?.get?.("auth_token")?.value
? request.cookies.get("auth_token")?.value || null
: null;
const requestHeaders =
request && typeof request === "object" && "headers" in request ? request.headers : undefined;
if (!token) {
token = getCookieValueFromHeader(requestHeaders, "auth_token");
}
if (!token) {
try {
const cookieStore = await cookies();
token = cookieStore.get("auth_token")?.value || null;
} catch {
token = null;
}
}
if (!token) return false;
try {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
await jwtVerify(token, secret);
return true;
} catch {
return false;
}
}
// ──────────────── Auth Verification ────────────────
/**
* Check if a request is authenticated.
*
* @returns null if authenticated, error message string if not
*/
export async function verifyAuth(request: any): Promise<string | null> {
if (await isDashboardSessionAuthenticated(request)) {
return null;
}
const isManagement = isManagementApiRequest(request);
const apiKey = getRequestApiKey(request, { allowUrl: !isManagement });
if (isManagement) {
if (await validateBearerApiKeyForManagement(apiKey)) {
return null;
}
return apiKey ? "Invalid management token" : "Authentication required";
}
if (await validateBearerApiKey(apiKey)) {
return null;
}
return "Authentication required";
}
/**
* Check if a request is authenticated — boolean convenience wrapper for route handlers.
*
* Uses `cookies()` from next/headers (App Router compatible) and Bearer API key.
* Returns true if authenticated, false otherwise.
*
* Unlike `verifyAuth`, this does NOT check `isAuthRequired()` — callers that
* need to conditionally skip auth should check that separately.
*/
export async function isAuthenticated(request: Request): Promise<boolean> {
// If settings say login/auth is disabled, treat all requests as authenticated
if (!(await isAuthRequired(request))) {
return true;
}
if (await isDashboardSessionAuthenticated(request)) {
return true;
}
const isManagement = isManagementApiRequest(request);
const apiKey = getRequestApiKey(request, { allowUrl: !isManagement });
if (isManagement) {
return validateBearerApiKeyForManagement(apiKey);
}
return validateBearerApiKey(apiKey);
}
/**
* Check if a route is in the public (no-auth) allowlist.
*/
export function isPublicRoute(pathname: string, method = "GET"): boolean {
return isPublicApiRoute(pathname, method);
}
/**
* Check if authentication is required based on settings.
* If requireLogin is explicitly false, auth is skipped. Fresh installs without
* a password keep their unauthenticated bootstrap path only on loopback
* requests; exposed network requests must configure INITIAL_PASSWORD or log in.
*/
export async function isAuthRequired(
request?: RequestLike | Request | null | undefined
): Promise<boolean> {
try {
const settings = await getSettings();
if (settings.requireLogin === false) return false;
if (!hasConfiguredPassword(settings) && !process.env.INITIAL_PASSWORD) {
if (!request) return false;
const pathname = getRequestPathname(request);
const method = getRequestMethod(request);
if (isOnboardingBootstrapPath(pathname)) {
return false;
}
if (pathname && isPublicApiRoute(pathname, method)) {
return false;
}
if (isRequireLoginBootstrapWritePath(pathname, method)) {
return false;
}
return settings.setupComplete === true || !isLoopbackRequest(request);
}
return true;
} catch (error: any) {
// On error, require auth (secure by default)
// Log the error so failures (e.g., SQLITE_BUSY) aren't silent 401s
console.error(
"[API_AUTH_GUARD] isAuthRequired failed, defaulting to true:",
error?.message || error
);
return true;
}
}