fix(admin-ui): require session for dashboard in production (BIT-403)

- 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 <[email protected]>
This commit is contained in:
1sonhadorandPaperclip committed 2026-03-23 23:00:20 +00:00
1 parent e3a7efc1a3
commit e17acc983c
5 files changed
+236 -4

No files matched your search

+7 -2
View File
@@ -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
+136
View File
@@ -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<string | null>(null);
const [loading, setLoading] = useState(false);
async function handleSubmit(e: FormEvent<HTMLFormElement>) {
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 (
<div className="min-vh-100 d-flex align-items-center justify-content-center bg-body-secondary px-3">
<div className="w-100" style={{ maxWidth: "420px" }}>
<div className="card shadow-sm">
<div className="card-body p-4">
<h1 className="h5 mb-1">BitReport — Error reporting</h1>
<p className="text-muted small mb-4">Inicie sessão para aceder ao painel.</p>
{error ? (
<div className="alert alert-danger py-2 small" role="alert">
{error}
</div>
) : null}
<form onSubmit={handleSubmit} noValidate>
<div className="mb-3">
<label htmlFor="er-email" className="form-label">
Email
</label>
<input
id="er-email"
type="email"
className="form-control"
autoComplete="username"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
disabled={loading}
/>
</div>
<div className="mb-3">
<label htmlFor="er-password" className="form-label">
Palavra-passe
</label>
<input
id="er-password"
type="password"
className="form-control"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
disabled={loading}
/>
</div>
<button
type="submit"
className="btn btn-primary w-100"
disabled={loading || !email || !password}
>
{loading ? "A entrar…" : "Entrar"}
</button>
</form>
<p className="text-muted small mt-3 mb-0">
O proxy público deve encaminhar <code>/admin/*</code> para a API Fastify (porta do
serviço <code>api/</code>) no mesmo hostname, para as cookies HTTP-only funcionarem.
</p>
</div>
</div>
</div>
</div>
);
}
export default function LoginPage() {
return (
<Suspense
fallback={
<div className="min-vh-100 d-flex align-items-center justify-content-center">
<span className="text-muted small">A carregar…</span>
</div>
}
>
<LoginForm />
</Suspense>
);
}
+28 -2
View File
@@ -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<string | undefined> {
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<T>(_path: string): Promise<T> {
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<DetailResult> {
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 {
+47
View File
@@ -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)$).*)"],
};