Files
errors.bitreport.pt/admin-ui/middleware.ts
T
1sonhador 83308b465b fix(admin-ui): middleware login gate; add admin API systemd unit
- Middleware: require development+demo or SKIP_LOGIN for unauthenticated access.
- Document SKIP_LOGIN and stricter demo in .env.example.
- Ship bitreport-error-reporting-api.service (PORT via ExecStart env; shared env has PORT for ingest).
2026-03-29 18:32:05 +01:00

53 lines
1.5 KiB
TypeScript

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 when demo mode is explicitly enabled in development.
* Edge middleware often sees `NODE_ENV` unset; treating "not production" as dev would open the shell publicly if DEMO=1.
* Opt-in escape hatch: ERROR_REPORTING_UI_SKIP_LOGIN=1 (local/staging only; never in public prod).
*/
function _allowWithoutSession(): boolean {
if (process.env.ERROR_REPORTING_UI_SKIP_LOGIN === "1") {
return true;
}
return (
process.env.NODE_ENV === "development" &&
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)$).*)"],
};