enforce user token auth, remove public api blanket allow

This commit is contained in:
makearmy 2025-09-29 12:04:42 -04:00
parent 756efbf948
commit 7b465c16c3

View file

@ -1,134 +1,152 @@
// middleware.ts // middleware.ts
import { NextResponse, NextRequest } from "next/server"; import { NextResponse, NextRequest } from "next/server";
const PUBLIC_PATHS = new Set<string>(["/auth/sign-in", "/auth/sign-up"]); /**
* Public pages that should remain reachable without being signed in.
* Everything else is considered protected (including most /api/*).
*/
const PUBLIC_PAGES = new Set<string>(["/auth/sign-in", "/auth/sign-up"]);
/** Helper: are we about to redirect to the same URL? */ /**
function isSameUrl(req: NextRequest, mapped: MapResult) { * API paths that are explicitly allowed without auth.
const dest = new URL(req.url); * Keep this list tiny. If you don't need any public APIs, leave it empty.
dest.pathname = mapped.pathname; */
if (mapped.query) { const PUBLIC_API_PREFIXES: string[] = [
// start from existing params so we preserve any others "/api/auth", // login/refresh/callback endpoints
for (const [k, v] of Object.entries(mapped.query)) dest.searchParams.set(k, v); // "/api/health", // uncomment if you intentionally expose a healthcheck
} ];
return dest.href === req.url;
}
export function middleware(req: NextRequest) { /** Helper: does the path start with any prefix in a list? */
const url = req.nextUrl.clone(); function startsWithAny(pathname: string, prefixes: string[]) {
const { pathname } = url; return prefixes.some((p) => pathname.startsWith(p));
}
// ── 1) Legacy → Portal / Canonical mapping (runs before auth gating) /** Helper: are we about to redirect to the same URL? */
const mapped = legacyMap(pathname); function isSameUrl(req: NextRequest, mapped: MapResult) {
if (mapped && !isSameUrl(req, mapped)) { const dest = new URL(req.url);
// Build destination on the same URL object to keep host/proto dest.pathname = mapped.pathname;
url.pathname = mapped.pathname; if (mapped.query) {
if (mapped.query) { for (const [k, v] of Object.entries(mapped.query)) dest.searchParams.set(k, v);
for (const [k, v] of Object.entries(mapped.query)) { }
url.searchParams.set(k, v); return dest.href === req.url;
} }
}
return NextResponse.redirect(url);
}
// ── 2) Auth gating export function middleware(req: NextRequest) {
const token = req.cookies.get("ma_at")?.value ?? ""; const url = req.nextUrl.clone();
const isAuthRoute = pathname.startsWith("/auth/"); const { pathname } = url;
// Authed users on any /auth/* route → /portal // ── 1) Legacy → Portal / Canonical mapping (runs before auth gating)
if (token && isAuthRoute) { const mapped = legacyMap(pathname);
url.pathname = "/portal"; if (mapped && !isSameUrl(req, mapped)) {
url.search = ""; url.pathname = mapped.pathname;
return NextResponse.redirect(url); if (mapped.query) {
} for (const [k, v] of Object.entries(mapped.query)) url.searchParams.set(k, v);
}
return NextResponse.redirect(url);
}
// Unauthed users on protected paths → sign-in (no ?next=) // ── 2) Auth gating (ma_at is the only allowed auth context)
if (!token && !isPublicPath(pathname)) { const token = req.cookies.get("ma_at")?.value ?? "";
url.pathname = "/auth/sign-in"; const isAuthRoute = pathname.startsWith("/auth/");
url.search = "";
return NextResponse.redirect(url);
}
return NextResponse.next(); // If signed in and visiting /auth/*, send to portal
} if (token && isAuthRoute) {
url.pathname = "/portal";
url.search = "";
return NextResponse.redirect(url);
}
type MapResult = { pathname: string; query?: Record<string, string> }; // If unauthenticated and the route is protected, send to sign-in
if (!token && !isPublicPath(pathname)) {
url.pathname = "/auth/sign-in";
url.search = "";
return NextResponse.redirect(url);
}
function legacyMap(pathname: string): MapResult | null { return NextResponse.next();
// If were already inside the portal, dont try to remap again. }
if (pathname.startsWith("/portal")) return null;
// 1) DETAIL PAGES: map legacy detail URLs straight into the portal with ?id= type MapResult = { pathname: string; query?: Record<string, string> };
// NOTE: We intentionally DO NOT remap `/lasers/:id` and `/projects/:id`
// so the portal iframes can load those canonical pages without recursion.
const detailRules: Array<[RegExp, (m: RegExpExecArray) => MapResult]> = [
// Laser settings
[/^\/fiber-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "fiber", id: m[1] } })],
[/^\/uv-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "uv", id: m[1] } })],
[/^\/co2-galvo-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "co2-galvo", id: m[1] } })],
[/^\/co2-gantry-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "co2-gantry", id: m[1] } })],
[/^\/co2gantry-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "co2-gantry", id: m[1] } })],
// Materials function legacyMap(pathname: string): MapResult | null {
[/^\/materials\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/materials", query: { t: "materials", id: m[1] } })], // If were already inside the portal, dont try to remap again.
[/^\/materials-coatings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/materials", query: { t: "materials-coatings", id: m[1] } })], if (pathname.startsWith("/portal")) return null;
// (no lasers/projects detail remap here on purpose) // 1) DETAIL PAGES: map legacy detail URLs straight into the portal with ?id=
]; // NOTE: We intentionally DO NOT remap `/lasers/:id` and `/projects/:id`
for (const [re, to] of detailRules) { // so the portal iframes can load those canonical pages without recursion.
const m = re.exec(pathname); const detailRules: Array<[RegExp, (m: RegExpExecArray) => MapResult]> = [
if (m) return to(m); // Laser settings
} [/^\/fiber-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "fiber", id: m[1] } })],
[/^\/uv-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "uv", id: m[1] } })],
[/^\/co2-galvo-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "co2-galvo", id: m[1] } })],
[/^\/co2-gantry-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "co2-gantry", id: m[1] } })],
[/^\/co2gantry-settings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/laser-settings", query: { t: "co2-gantry", id: m[1] } })],
// 2) LIST PAGES: legacy lists → portal lists (with tab param) or sections // Materials
const listRules: Array<[RegExp, MapResult]> = [ [/^\/materials\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/materials", query: { t: "materials", id: m[1] } })],
// Laser settings lists [/^\/materials-coatings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/materials", query: { t: "materials-coatings", id: m[1] } })],
[/^\/fiber-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "fiber" } }], ];
[/^\/uv-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "uv" } }], for (const [re, to] of detailRules) {
[/^\/co2-galvo-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-galvo" } }], const m = re.exec(pathname);
[/^\/co2-ganry-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-gantry" } }], // typo catch if (m) return to(m);
[/^\/co2-gantry-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-gantry" } }], }
[/^\/co2gantry-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-gantry" } }], // old alias
// Materials lists // 2) LIST PAGES: legacy lists → portal lists (with tab param) or sections
[/^\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }], const listRules: Array<[RegExp, MapResult]> = [
[/^\/materials\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }], // Laser settings lists
[/^\/materials\/materials-coatings\/?$/i, [/^\/fiber-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "fiber" } }],
{ pathname: "/portal/materials", query: { t: "materials-coatings" } }], [/^\/uv-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "uv" } }],
[/^\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }], [/^\/co2-galvo-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-galvo" } }],
[/^\/co2-ganry-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-gantry" } }], // typo catch
[/^\/co2-gantry-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-gantry" } }],
[/^\/co2gantry-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "co2-gantry" } }], // old alias
// Other lists // Materials lists
[/^\/lasers\/?$/i, { pathname: "/portal/laser-sources" }], [/^\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
[/^\/projects\/?$/i, { pathname: "/portal/projects" }], [/^\/materials\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
[/^\/my\/rigs\/?$/i, { pathname: "/portal/rigs", query: { t: "my" } }], [/^\/materials\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }],
]; [/^\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }],
for (const [re, dest] of listRules) {
if (re.test(pathname)) return dest;
}
return null; // Other lists
} [/^\/lasers\/?$/i, { pathname: "/portal/laser-sources" }],
[/^\/projects\/?$/i, { pathname: "/portal/projects" }],
[/^\/my\/rigs\/?$/i, { pathname: "/portal/rigs", query: { t: "my" } }],
];
for (const [re, dest] of listRules) {
if (re.test(pathname)) return dest;
}
function isPublicPath(pathname: string): boolean { return null;
if (PUBLIC_PATHS.has(pathname)) return true; }
// Static assets / internals function isPublicPath(pathname: string): boolean {
if ( // 1) Public pages (auth screens)
pathname.startsWith("/_next/") || if (PUBLIC_PAGES.has(pathname)) return true;
pathname.startsWith("/static/") ||
pathname.startsWith("/images/") ||
pathname === "/favicon.ico" ||
pathname === "/robots.txt" ||
pathname === "/sitemap.xml"
) return true;
// API routes arent gated here; each route should enforce auth as needed // 2) Static assets / internals
if (pathname.startsWith("/api/")) return true; if (
pathname.startsWith("/_next/") ||
pathname.startsWith("/static/") ||
pathname.startsWith("/images/") ||
pathname === "/favicon.ico" ||
pathname === "/robots.txt" ||
pathname === "/sitemap.xml"
) {
return true;
}
// Everything else is protected // 3) APIs:
return false; // By default, /api/* is PROTECTED.
} // Only allow specific public API prefixes listed above.
if (pathname.startsWith("/api/")) {
return startsWithAny(pathname, PUBLIC_API_PREFIXES);
}
export const config = { // 4) Everything else is protected
matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|images|static).*)"], return false;
}; }
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|images|static).*)"],
};