From e17acc983c1ec12862db31bd7d8909218930e2a8 Mon Sep 17 00:00:00 2001 From: 1sonhador <1sonhador@gmail.com> Date: Mon, 23 Mar 2026 23:00:20 +0000 Subject: [PATCH] fix(admin-ui): require session for dashboard in production (BIT-403) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add middleware redirecting unauthenticated users to /login unless dev+demo - Disable demo incident data when NODE_ENV=production - Forward __Host-access cookie on SSR fetches to admin API - Document NPM /admin/ proxy to Fastify api (§14.2.2) Co-Authored-By: Paperclip --- admin-ui/.env.example | 9 +- admin-ui/app/login/page.tsx | 136 ++++++++++++++++++ admin-ui/lib/incidents-data.ts | 30 +++- admin-ui/middleware.ts | 47 ++++++ .../bitreport-error-reporting-lxc-proxmox.md | 18 +++ 5 files changed, 236 insertions(+), 4 deletions(-) create mode 100644 admin-ui/app/login/page.tsx create mode 100644 admin-ui/middleware.ts diff --git a/admin-ui/.env.example b/admin-ui/.env.example index 6ee5939..fd7d69d 100644 --- a/admin-ui/.env.example +++ b/admin-ui/.env.example @@ -1,5 +1,10 @@ # Base URL da API admin (Fastify) quando existir (BIT-179). Sem trailing slash. -# ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3050 +# Usada pelo servidor Next para SSR (pode ser http://127.0.0.1:3200 no LXC). +# ERROR_REPORTING_ADMIN_API_BASE=http://127.0.0.1:3200 -# Apenas desenvolvimento: carrega dados fictícios para validar layout sem API. +# Origem que o *browser* usa para POST /admin/auth/login (mesmo hostname que a UI +# quando o proxy encaminha /admin/* para a API). Opcional: omite para usar window.location.origin. +# NEXT_PUBLIC_ERROR_REPORTING_AUTH_ORIGIN=https://errors.bitreport.pt + +# Apenas desenvolvimento (NODE_ENV!==production): dados fictícios sem API. # ERROR_REPORTING_UI_DEMO=1 diff --git a/admin-ui/app/login/page.tsx b/admin-ui/app/login/page.tsx new file mode 100644 index 0000000..f4f083b --- /dev/null +++ b/admin-ui/app/login/page.tsx @@ -0,0 +1,136 @@ +"use client"; + +import { useSearchParams } from "next/navigation"; +import { type FormEvent, Suspense, useState } from "react"; + +/** + * Public origin for admin auth API (browser). Prefer same host as this UI so + * `__Host-access` cookies apply (NPM should proxy `/admin/*` to Fastify `api/`). + * Fallback: current origin. + */ +function _authBase(): string { + const _env = process.env.NEXT_PUBLIC_ERROR_REPORTING_AUTH_ORIGIN?.trim(); + if (_env) { + return _env.replace(/\/$/, ""); + } + if (typeof window !== "undefined") { + return window.location.origin; + } + return ""; +} + +function LoginForm() { + const _search = useSearchParams(); + const _next = _search.get("next")?.trim() || "/"; + + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [error, setError] = useState(null); + const [loading, setLoading] = useState(false); + + async function handleSubmit(e: FormEvent) { + e.preventDefault(); + setError(null); + setLoading(true); + + try { + const _base = _authBase(); + const _res = await fetch(`${_base}/admin/auth/login`, { + method: "POST", + credentials: "include", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ email: email.trim(), password }), + }); + + if (_res.ok) { + window.location.assign(_next.startsWith("/") ? _next : "/"); + return; + } + + const _data = (await _res.json().catch(() => ({}))) as { error?: string; message?: string }; + setError(_data?.message ?? _data?.error ?? "Credenciais inválidas."); + } catch { + setError("Não foi possível contactar o servidor. Verifique a rede e o proxy `/admin/*`."); + } finally { + setLoading(false); + } + } + + return ( +
+
+
+
+

BitReport — Error reporting

+

Inicie sessão para aceder ao painel.

+ + {error ? ( +
+ {error} +
+ ) : null} + +
+
+ + setEmail(e.target.value)} + required + disabled={loading} + /> +
+
+ + setPassword(e.target.value)} + required + disabled={loading} + /> +
+ +
+ +

+ O proxy público deve encaminhar /admin/* para a API Fastify (porta do + serviço api/) no mesmo hostname, para as cookies HTTP-only funcionarem. +

+
+
+
+
+ ); +} + +export default function LoginPage() { + return ( + + A carregar… + + } + > + + + ); +} diff --git a/admin-ui/lib/incidents-data.ts b/admin-ui/lib/incidents-data.ts index 379bd18..3167afe 100644 --- a/admin-ui/lib/incidents-data.ts +++ b/admin-ui/lib/incidents-data.ts @@ -1,10 +1,28 @@ +import { cookies } from "next/headers"; import { getDemoIncidentDetail, getDemoIncidentSummaries } from "./demo-incidents"; import type { DetailResult, IncidentState, IncidentSummary, ListResult, Severity } from "./types"; function _isDemoEnabled(): boolean { + if (process.env.NODE_ENV === "production") { + return false; + } return process.env.ERROR_REPORTING_UI_DEMO === "1"; } +/** Forward session cookie to internal admin API (SSR fetch). */ +async function _sessionCookieHeader(): Promise { + try { + const _jar = await cookies(); + const _access = _jar.get("__Host-access")?.value; + if (!_access) { + return undefined; + } + return `__Host-access=${_access}`; + } catch { + return undefined; + } +} + function _apiBase(): string | null { const _raw = process.env.ERROR_REPORTING_ADMIN_API_BASE?.trim(); if (!_raw) { @@ -19,9 +37,13 @@ async function _fetchJson(_path: string): Promise { throw new Error("API base not configured"); } const _url = `${_base}${_path.startsWith("/") ? _path : `/${_path}`}`; + const _cookie = await _sessionCookieHeader(); const _res = await fetch(_url, { next: { revalidate: 0 }, - headers: { Accept: "application/json" }, + headers: { + Accept: "application/json", + ...(_cookie ? { Cookie: _cookie } : {}), + }, }); if (!_res.ok) { throw new Error(`HTTP ${_res.status}`); @@ -137,9 +159,13 @@ export async function fetchIncidentDetail(id: string): Promise { throw new Error("unreachable"); } const _url = `${_base}/v1/incidents/${encodeURIComponent(id)}`; + const _cookie = await _sessionCookieHeader(); const _res = await fetch(_url, { next: { revalidate: 0 }, - headers: { Accept: "application/json" }, + headers: { + Accept: "application/json", + ...(_cookie ? { Cookie: _cookie } : {}), + }, }); if (_res.status === 404) { return { diff --git a/admin-ui/middleware.ts b/admin-ui/middleware.ts new file mode 100644 index 0000000..efe313c --- /dev/null +++ b/admin-ui/middleware.ts @@ -0,0 +1,47 @@ +import type { NextRequest } from "next/server"; +import { NextResponse } from "next/server"; + +/** Matches Fastify admin auth cookie name (`api/src/plugins/auth.ts`). */ +const ACCESS_COOKIE = "__Host-access"; + +/** + * Unauthenticated access is only allowed in non-production when demo mode is on. + * In production, demo data is disabled in `lib/incidents-data.ts` and routes require a session. + */ +function _allowWithoutSession(): boolean { + return ( + process.env.NODE_ENV !== "production" && process.env.ERROR_REPORTING_UI_DEMO === "1" + ); +} + +export function middleware(request: NextRequest) { + const { pathname } = request.nextUrl; + + if (_allowWithoutSession()) { + return NextResponse.next(); + } + + if ( + pathname.startsWith("/login") || + pathname.startsWith("/_next") || + pathname === "/favicon.ico" + ) { + return NextResponse.next(); + } + + if (!request.cookies.get(ACCESS_COOKIE)?.value) { + const _url = request.nextUrl.clone(); + _url.pathname = "/login"; + const _next = pathname + request.nextUrl.search; + if (_next && _next !== "/login") { + _url.searchParams.set("next", _next); + } + return NextResponse.redirect(_url); + } + + return NextResponse.next(); +} + +export const config = { + matcher: ["/((?!_next/static|_next/image|.*\\.(?:ico|png|jpg|jpeg|svg|webp)$).*)"], +}; diff --git a/docs/deployment/bitreport-error-reporting-lxc-proxmox.md b/docs/deployment/bitreport-error-reporting-lxc-proxmox.md index d45e53e..3408978 100644 --- a/docs/deployment/bitreport-error-reporting-lxc-proxmox.md +++ b/docs/deployment/bitreport-error-reporting-lxc-proxmox.md @@ -202,6 +202,24 @@ proxy_set_header X-Forwarded-Port $server_port; **Evitar** colar directivas `map` ou segundo `location /` completos no *Custom* — o NPM valida o snippet no contexto do `server{}`; blocos inválidos impedem o reload. +#### 14.2.2 Autenticação admin (`/admin/*` → API Fastify) + +A **admin-ui** (Next em **3040**) exige sessão em produção e envia o login para **`/admin/auth/login`** no **mesmo hostname** público (`errors.bitreport.pt`), para as cookies `__Host-access` / `__Host-refresh` serem válidas. + +Se o *Proxy Host* do NPM enviar **todo** o tráfego só para **3040**, o login falha. No *Advanced* → **Custom Nginx Configuration**, acrescentar um `location` **antes** do bloco genérico que o NPM gera (ou usar *Custom Locations* se disponível) para encaminhar **`/admin/`** para o serviço **`api/`** (porta interna por omissão **3200** no LXC, conforme `ERROR_REPORTING_ADMIN_API_BASE`): + +```nginx +location /admin/ { + proxy_pass http://:3200; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; +} +``` + +Em **produção**, definir **`ERROR_REPORTING_UI_DEMO=0`** (ou omitir). O modo demo **não** é usado com `NODE_ENV=production` no código da admin-ui. + **Collector-worker no LXC:** manter `INGEST_BASE_URL` para `http://127.0.0.1:3041` (ou hostname interno do próprio guest). Clientes e colectores externos usam o FQDN público da ingest. ### 14.3 Cloudflare