2025-09-26 15:19:19 -04:00
|
|
|
|
// middleware.ts
|
2025-09-27 14:30:16 -04:00
|
|
|
|
import { NextResponse, NextRequest } from "next/server";
|
2025-09-26 14:18:24 -04:00
|
|
|
|
|
2025-09-29 12:04:42 -04:00
|
|
|
|
/**
|
|
|
|
|
|
* Public pages that should remain reachable without being signed in.
|
|
|
|
|
|
* Everything else is considered protected (including most /api/*).
|
|
|
|
|
|
*/
|
2025-09-30 22:38:25 -04:00
|
|
|
|
const PUBLIC_PAGES = new Set<string>([
|
|
|
|
|
|
"/", // ← splash page is public
|
|
|
|
|
|
"/auth/sign-in",
|
|
|
|
|
|
"/auth/sign-up",
|
|
|
|
|
|
]);
|
2025-09-29 12:04:42 -04:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* API paths that are explicitly allowed without auth.
|
|
|
|
|
|
* Keep this list tiny. If you don't need any public APIs, leave it empty.
|
|
|
|
|
|
*/
|
|
|
|
|
|
const PUBLIC_API_PREFIXES: string[] = [
|
2025-09-29 23:36:46 -04:00
|
|
|
|
"/api/auth", // login/refresh/callback endpoints
|
2025-09-29 12:04:42 -04:00
|
|
|
|
// "/api/health", // uncomment if you intentionally expose a healthcheck
|
|
|
|
|
|
];
|
|
|
|
|
|
|
2025-09-29 23:36:46 -04:00
|
|
|
|
/** Directus base (used to remotely validate the token after restarts). */
|
2025-09-30 22:38:25 -04:00
|
|
|
|
const DIRECTUS = (process.env.NEXT_PUBLIC_API_BASE_URL || process.env.DIRECTUS_URL || "").replace(/\/$/, "");
|
2025-09-29 23:36:46 -04:00
|
|
|
|
|
2025-09-29 12:04:42 -04:00
|
|
|
|
/** Helper: does the path start with any prefix in a list? */
|
|
|
|
|
|
function startsWithAny(pathname: string, prefixes: string[]) {
|
|
|
|
|
|
return prefixes.some((p) => pathname.startsWith(p));
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/** Helper: are we about to redirect to the same URL? */
|
|
|
|
|
|
function isSameUrl(req: NextRequest, mapped: MapResult) {
|
|
|
|
|
|
const dest = new URL(req.url);
|
|
|
|
|
|
dest.pathname = mapped.pathname;
|
|
|
|
|
|
if (mapped.query) {
|
2025-09-30 19:35:27 -04:00
|
|
|
|
for (const [k, v] of Object.entries(mapped.query)) dest.searchParams.set(k, v);
|
2025-09-29 12:04:42 -04:00
|
|
|
|
}
|
|
|
|
|
|
return dest.href === req.url;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-29 23:36:46 -04:00
|
|
|
|
/** Decode JWT exp (seconds since epoch). We don't verify signature here. */
|
|
|
|
|
|
function jwtExp(token: string): number | null {
|
|
|
|
|
|
try {
|
|
|
|
|
|
const [, payload] = token.split(".");
|
|
|
|
|
|
if (!payload) return null;
|
2025-09-30 19:35:27 -04:00
|
|
|
|
const json = JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
|
2025-09-29 23:36:46 -04:00
|
|
|
|
return typeof json.exp === "number" ? json.exp : null;
|
|
|
|
|
|
} catch {
|
|
|
|
|
|
return null;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-30 22:38:25 -04:00
|
|
|
|
/**
|
|
|
|
|
|
* Build redirect to /auth/sign-in?next=<original>.
|
|
|
|
|
|
* Only set reauth=1 (and clear cookies) when opts.reauth === true.
|
|
|
|
|
|
*/
|
|
|
|
|
|
function kickToSignIn(req: NextRequest, opts?: { reauth?: boolean }) {
|
|
|
|
|
|
const wantReauth = !!opts?.reauth;
|
|
|
|
|
|
|
2025-09-30 10:36:40 -04:00
|
|
|
|
const orig = new URL(req.url);
|
|
|
|
|
|
const next = orig.pathname + (orig.search || "");
|
2025-09-30 22:38:25 -04:00
|
|
|
|
|
2025-09-29 23:36:46 -04:00
|
|
|
|
const url = new URL(req.url);
|
|
|
|
|
|
url.pathname = "/auth/sign-in";
|
|
|
|
|
|
url.search = "";
|
2025-09-30 22:38:25 -04:00
|
|
|
|
if (wantReauth) url.searchParams.set("reauth", "1");
|
2025-09-30 10:36:40 -04:00
|
|
|
|
url.searchParams.set("next", next);
|
|
|
|
|
|
|
2025-09-29 23:36:46 -04:00
|
|
|
|
const res = NextResponse.redirect(url);
|
2025-09-30 22:38:25 -04:00
|
|
|
|
|
|
|
|
|
|
// Only clear auth markers in true re-auth scenarios
|
|
|
|
|
|
if (wantReauth) {
|
|
|
|
|
|
res.cookies.set("ma_at", "", { maxAge: 0, path: "/" });
|
|
|
|
|
|
res.cookies.set("ma_v", "", { maxAge: 0, path: "/" }); // throttle marker
|
|
|
|
|
|
// If you also use a refresh token, clear it here too:
|
|
|
|
|
|
// res.cookies.set("ma_rt", "", { maxAge: 0, path: "/" });
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-29 23:36:46 -04:00
|
|
|
|
return res;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export async function middleware(req: NextRequest) {
|
2025-09-29 12:04:42 -04:00
|
|
|
|
const url = req.nextUrl.clone();
|
|
|
|
|
|
const { pathname } = url;
|
|
|
|
|
|
|
2025-10-02 14:21:12 -04:00
|
|
|
|
// ── 0) Absolute rule: the homepage must never redirect (no mapping, no gating).
|
|
|
|
|
|
if (pathname === "/") {
|
|
|
|
|
|
return NextResponse.next();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-29 12:04:42 -04:00
|
|
|
|
// ── 1) Legacy → Portal / Canonical mapping (runs before auth gating)
|
|
|
|
|
|
const mapped = legacyMap(pathname);
|
|
|
|
|
|
if (mapped && !isSameUrl(req, mapped)) {
|
|
|
|
|
|
url.pathname = mapped.pathname;
|
|
|
|
|
|
if (mapped.query) {
|
2025-09-30 19:35:27 -04:00
|
|
|
|
for (const [k, v] of Object.entries(mapped.query)) url.searchParams.set(k, v);
|
2025-09-29 12:04:42 -04:00
|
|
|
|
}
|
|
|
|
|
|
return NextResponse.redirect(url);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-29 23:36:46 -04:00
|
|
|
|
// ── 2) Auth gating + validation (ma_at is the only allowed auth context)
|
2025-09-29 12:04:42 -04:00
|
|
|
|
const token = req.cookies.get("ma_at")?.value ?? "";
|
|
|
|
|
|
const isAuthRoute = pathname.startsWith("/auth/");
|
2025-09-29 23:36:46 -04:00
|
|
|
|
const isProtected = !isPublicPath(pathname);
|
2025-09-29 12:04:42 -04:00
|
|
|
|
|
2025-09-30 10:36:40 -04:00
|
|
|
|
// Allow explicit reauth flow even if a (possibly stale) token cookie exists
|
2025-09-30 10:24:20 -04:00
|
|
|
|
const forceAuth =
|
|
|
|
|
|
isAuthRoute &&
|
2025-09-30 19:35:27 -04:00
|
|
|
|
(url.searchParams.get("reauth") === "1" || url.searchParams.get("force") === "1");
|
2025-09-30 10:24:20 -04:00
|
|
|
|
|
2025-09-30 22:38:25 -04:00
|
|
|
|
// If unauthenticated and the route is protected, send to sign-in WITHOUT reauth
|
2025-09-29 23:36:46 -04:00
|
|
|
|
if (!token && isProtected) {
|
2025-09-30 22:38:25 -04:00
|
|
|
|
return kickToSignIn(req, { reauth: false });
|
2025-09-29 12:04:42 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-29 23:36:46 -04:00
|
|
|
|
// If we have a token, perform local expiry check.
|
|
|
|
|
|
if (token) {
|
|
|
|
|
|
const exp = jwtExp(token);
|
|
|
|
|
|
const expired = !exp || exp * 1000 <= Date.now();
|
|
|
|
|
|
|
2025-09-30 22:38:25 -04:00
|
|
|
|
// If it's an auth route and token looks valid, bounce away from auth pages — unless this is a forced reauth.
|
2025-09-30 10:24:20 -04:00
|
|
|
|
if (isAuthRoute && !expired && !forceAuth) {
|
2025-09-29 23:36:46 -04:00
|
|
|
|
url.pathname = "/portal";
|
|
|
|
|
|
url.search = "";
|
|
|
|
|
|
return NextResponse.redirect(url);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// If protected route: enforce validity
|
|
|
|
|
|
if (isProtected) {
|
|
|
|
|
|
if (expired) {
|
2025-09-30 22:38:25 -04:00
|
|
|
|
// True reauth
|
|
|
|
|
|
return kickToSignIn(req, { reauth: true });
|
2025-09-29 23:36:46 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// ── Throttled remote validation (catches server restarts / revoked tokens)
|
|
|
|
|
|
// Only if we have a Directus URL configured.
|
|
|
|
|
|
if (DIRECTUS) {
|
|
|
|
|
|
const nowMinute = Math.floor(Date.now() / 60000).toString();
|
|
|
|
|
|
const lastValidated = req.cookies.get("ma_v")?.value;
|
|
|
|
|
|
|
|
|
|
|
|
if (lastValidated !== nowMinute) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
const r = await fetch(`${DIRECTUS}/users/me?fields=id`, {
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
Authorization: `Bearer ${token}`,
|
|
|
|
|
|
Accept: "application/json",
|
|
|
|
|
|
},
|
|
|
|
|
|
cache: "no-store",
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
if (!r.ok) {
|
2025-09-30 22:38:25 -04:00
|
|
|
|
// Token no longer valid on the server → true reauth, carry next
|
|
|
|
|
|
return kickToSignIn(req, { reauth: true });
|
2025-09-29 23:36:46 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Cache the success for ~1 minute to avoid hammering Directus
|
|
|
|
|
|
const res = NextResponse.next();
|
|
|
|
|
|
res.cookies.set("ma_v", nowMinute, {
|
|
|
|
|
|
path: "/",
|
|
|
|
|
|
httpOnly: false,
|
|
|
|
|
|
sameSite: "lax",
|
|
|
|
|
|
maxAge: 90, // seconds
|
|
|
|
|
|
});
|
|
|
|
|
|
return res;
|
|
|
|
|
|
} catch {
|
|
|
|
|
|
// If Directus is unreachable, be conservative and require re-auth
|
2025-09-30 22:38:25 -04:00
|
|
|
|
return kickToSignIn(req, { reauth: true });
|
2025-09-29 23:36:46 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-09-29 12:04:42 -04:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-30 10:24:20 -04:00
|
|
|
|
// If signed-in and visiting /auth/* but token is expired/invalid or reauth was requested, fall through (let them sign in).
|
2025-09-29 23:36:46 -04:00
|
|
|
|
// If public or already validated, proceed.
|
2025-09-29 12:04:42 -04:00
|
|
|
|
return NextResponse.next();
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type MapResult = { pathname: string; query?: Record<string, string> };
|
|
|
|
|
|
|
|
|
|
|
|
function legacyMap(pathname: string): MapResult | null {
|
2025-10-02 14:21:12 -04:00
|
|
|
|
// Never map the homepage, and if we’re already inside the portal, don’t remap again.
|
|
|
|
|
|
if (pathname === "/" || pathname.startsWith("/portal")) return null;
|
2025-09-29 12:04:42 -04:00
|
|
|
|
|
|
|
|
|
|
// 1) DETAIL PAGES: map legacy detail URLs straight into the portal with ?id=
|
|
|
|
|
|
// 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
|
2025-09-29 23:36:46 -04:00
|
|
|
|
[/^\/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] } })],
|
2025-09-29 12:04:42 -04:00
|
|
|
|
|
|
|
|
|
|
// Materials
|
2025-09-29 23:36:46 -04:00
|
|
|
|
[/^\/materials\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/materials", query: { t: "materials", id: m[1] } })],
|
|
|
|
|
|
[/^\/materials-coatings\/([^/]+)\/?$/i, (m) => ({ pathname: "/portal/materials", query: { t: "materials-coatings", id: m[1] } })],
|
2025-09-29 12:04:42 -04:00
|
|
|
|
];
|
|
|
|
|
|
for (const [re, to] of detailRules) {
|
|
|
|
|
|
const m = re.exec(pathname);
|
|
|
|
|
|
if (m) return to(m);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 2) LIST PAGES: legacy lists → portal lists (with tab param) or sections
|
|
|
|
|
|
const listRules: Array<[RegExp, MapResult]> = [
|
|
|
|
|
|
// Laser settings lists
|
2025-09-29 23:36:46 -04:00
|
|
|
|
[/^\/fiber-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "fiber" } }],
|
|
|
|
|
|
[/^\/uv-settings\/?$/i, { pathname: "/portal/laser-settings", query: { t: "uv" } }],
|
|
|
|
|
|
[/^\/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
|
2025-09-29 12:04:42 -04:00
|
|
|
|
|
|
|
|
|
|
// Materials lists
|
2025-09-29 23:36:46 -04:00
|
|
|
|
[/^\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
|
|
|
|
|
|
[/^\/materials\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
|
2025-09-29 12:04:42 -04:00
|
|
|
|
[/^\/materials\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }],
|
2025-09-29 23:36:46 -04:00
|
|
|
|
[/^\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }],
|
2025-09-29 12:04:42 -04:00
|
|
|
|
|
|
|
|
|
|
// Other lists
|
2025-09-29 23:36:46 -04:00
|
|
|
|
[/^\/lasers\/?$/i, { pathname: "/portal/laser-sources" }],
|
|
|
|
|
|
[/^\/projects\/?$/i, { pathname: "/portal/projects" }],
|
|
|
|
|
|
[/^\/my\/rigs\/?$/i, { pathname: "/portal/rigs", query: { t: "my" } }],
|
2025-09-29 12:04:42 -04:00
|
|
|
|
];
|
|
|
|
|
|
for (const [re, dest] of listRules) {
|
|
|
|
|
|
if (re.test(pathname)) return dest;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return null;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
function isPublicPath(pathname: string): boolean {
|
2025-09-30 22:38:25 -04:00
|
|
|
|
// 1) Public pages (root splash & auth screens)
|
2025-09-29 12:04:42 -04:00
|
|
|
|
if (PUBLIC_PAGES.has(pathname)) return true;
|
|
|
|
|
|
|
|
|
|
|
|
// 2) Static assets / internals
|
|
|
|
|
|
if (
|
|
|
|
|
|
pathname.startsWith("/_next/") ||
|
|
|
|
|
|
pathname.startsWith("/static/") ||
|
|
|
|
|
|
pathname.startsWith("/images/") ||
|
|
|
|
|
|
pathname === "/favicon.ico" ||
|
|
|
|
|
|
pathname === "/robots.txt" ||
|
|
|
|
|
|
pathname === "/sitemap.xml"
|
|
|
|
|
|
) {
|
|
|
|
|
|
return true;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 3) APIs:
|
|
|
|
|
|
// By default, /api/* is PROTECTED.
|
|
|
|
|
|
// Only allow specific public API prefixes listed above.
|
|
|
|
|
|
if (pathname.startsWith("/api/")) {
|
|
|
|
|
|
return startsWithAny(pathname, PUBLIC_API_PREFIXES);
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 4) Everything else is protected
|
|
|
|
|
|
return false;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
export const config = {
|
2025-09-30 19:35:27 -04:00
|
|
|
|
matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|images|static).*)"],
|
2025-09-29 12:04:42 -04:00
|
|
|
|
};
|