Files
errors.bitreport.pt/admin-ui/middleware.ts
Peter Spark 3b175eec86 fix(admin-ui): proxy ingest API through Next.js rewrites (BIT-750)
The single-domain deployment (errors.bitreport.pt) routed all traffic
through the admin-ui, whose auth middleware redirected /v1/ingest/events
and /health to /login — making the ingest API unreachable from outside.

- middleware.ts: pass through /v1/* and /health without auth redirect
- next.config.ts: rewrite /v1/* and /health to ingest-api backend
  (INGEST_API_URL env, default http://127.0.0.1:3041)
- docker-compose.yml: set INGEST_API_URL=http://ingest-api:3041
- env examples: document INGEST_API_URL
- scripts/onboard-project.sh: generate project + ingest key SQL

Paperclip-Agent: peter-spark
Paperclip-Issue: BIT-750
Paperclip-Run: dc5b7949-b24d-4867-a2cd-cf4f47477ef8
2026-04-03 10:01:55 +00:00

66 lines
1.9 KiB
TypeScript

import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
/** Admin session cookie checked by middleware. */
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;
/** Paperclip + CRM contract: JSON with api_key on Fastify; proxy routes must not 307 to /login. */
if (pathname.startsWith("/api/error-monitoring/")) {
return NextResponse.next();
}
/** Ingest API paths — proxied to the ingest-api backend via next.config rewrites. */
if (
pathname === "/health" ||
pathname.startsWith("/v1/")
) {
return NextResponse.next();
}
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)$).*)"],
};