middleware server restart fix + expander suffix addition

This commit is contained in:
makearmy 2025-09-29 23:36:46 -04:00
parent 9390b52aae
commit 96d462df62
3 changed files with 192 additions and 260 deletions

View file

@ -7,10 +7,26 @@ type Opt = { id: string | number; label: string };
const API = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
/**
* Client-side options fetcher (same pattern as before).
* NOTE: rig types are still passed from the server; this hook is NOT used for that.
*/
// helper: render multipliers like "06x", "8x", "1.5x"; avoid double "x"
function formatMultiplier(raw: any) {
const s = String(raw ?? "").trim();
if (/x$/i.test(s)) return s; // already has x
// pure number?
if (/^\d+(\.\d+)?$/.test(s)) {
// pad single-digit integers to 2 chars (e.g., 6 -> 06)
if (/^\d$/.test(s)) return `0${s}x`;
return `${s}x`;
}
// otherwise, extract first number if present
const m = s.match(/(\d+(?:\.\d+)?)/);
if (m) {
const n = m[1];
if (/^\d$/.test(n)) return `0${n}x`;
return `${n}x`;
}
return `${s}x`;
}
function useOptions(
kind:
| "laser_software"
@ -32,15 +48,12 @@ function useOptions(
let normalize = (rows: any[]): Opt[] =>
rows.map((r) => ({
id: String(r.id ?? r.submission_id),
label: String(
r.name ?? r.label ?? r.title ?? r.model ?? r.id
),
label: String(r.name ?? r.label ?? r.title ?? r.model ?? r.id),
}));
if (kind === "laser_software") {
url = `${API}/items/laser_software?fields=id,name&limit=1000&sort=name`;
} else if (kind === "laser_source") {
// fetch all sources; client filter by nm band from targetKey
url = `${API}/items/laser_source?fields=submission_id,make,model,nm&limit=2000&sort=make,model`;
const parseNum = (v: any) => {
if (v == null) return null;
@ -84,9 +97,7 @@ function useOptions(
return m ? parseFloat(m[0]) : Number.POSITIVE_INFINITY;
};
return [...rows]
.sort(
(a, b) => toNum(a.focal_length) - toNum(b.focal_length)
)
.sort((a, b) => toNum(a.focal_length) - toNum(b.focal_length))
.map((r) => ({
id: String(r.id),
label:
@ -103,6 +114,11 @@ function useOptions(
url = `${API}/items/laser_scan_lens_apt?fields=id,name&limit=1000&sort=name`;
} else if (kind === "scan_lens_exp") {
url = `${API}/items/laser_scan_lens_exp?fields=id,name&limit=1000&sort=name`;
normalize = (rows) =>
rows.map((r: any) => ({
id: String(r.id),
label: formatMultiplier(r.name ?? r.label ?? r.id), // add "x"
}));
}
const res = await fetch(url, {
@ -132,12 +148,11 @@ export default function RigBuilderClient({ rigTypes }: { rigTypes: Opt[] }) {
const [rigType, setRigType] = useState<string>("");
const [laserSource, setLaserSource] = useState<string>("");
const [scanLens, setScanLens] = useState<string>("");
const [scanLensApt, setScanLensApt] = useState<string>(""); // NEW
const [scanLensExp, setScanLensExp] = useState<string>(""); // NEW
const [scanLensApt, setScanLensApt] = useState<string>("");
const [scanLensExp, setScanLensExp] = useState<string>("");
const [focusLens, setFocusLens] = useState<string>("");
const [software, setSoftware] = useState<string>("");
// rigTypes come from the SERVER as props.
const targetKey = useMemo(() => {
const rt =
rigTypes.find((o) => String(o.id) === String(rigType))?.label || "";
@ -146,8 +161,8 @@ export default function RigBuilderClient({ rigTypes }: { rigTypes: Opt[] }) {
const sources = useOptions("laser_source", targetKey);
const lens = useOptions("lens", targetKey);
const lensApt = useOptions("scan_lens_apt"); // NEW
const lensExp = useOptions("scan_lens_exp"); // NEW
const lensApt = useOptions("scan_lens_apt");
const lensExp = useOptions("scan_lens_exp");
const softwares = useOptions("laser_software");
const isGantry = (targetKey || "").toLowerCase().includes("gantry");
@ -164,13 +179,13 @@ export default function RigBuilderClient({ rigTypes }: { rigTypes: Opt[] }) {
if (isGantry) {
body.laser_focus_lens = focusLens ? Number(focusLens) : null;
body.laser_scan_lens = null;
body.laser_scan_lens_apt = null; // NEW
body.laser_scan_lens_exp = null; // NEW
body.laser_scan_lens_apt = null;
body.laser_scan_lens_exp = null;
} else {
body.laser_scan_lens = scanLens ? Number(scanLens) : null;
body.laser_focus_lens = null;
body.laser_scan_lens_apt = scanLensApt ? Number(scanLensApt) : null; // NEW
body.laser_scan_lens_exp = scanLensExp ? Number(scanLensExp) : null; // NEW
body.laser_scan_lens_apt = scanLensApt ? Number(scanLensApt) : null;
body.laser_scan_lens_exp = scanLensExp ? Number(scanLensExp) : null;
}
const res = await fetch("/api/rigs", {
@ -190,162 +205,10 @@ export default function RigBuilderClient({ rigTypes }: { rigTypes: Opt[] }) {
return (
<form onSubmit={onSubmit} className="space-y-4 max-w-xl">
<div>
<label className="block text-sm mb-1">
Rig Name <span className="text-red-600">*</span>
</label>
<input
className="w-full border rounded px-2 py-1"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
{/* ...existing fields... */}
<div className="grid sm:grid-cols-2 gap-3">
<div>
<label className="block text-sm mb-1">
Rig Type <span className="text-red-600">*</span>
</label>
<select
className="w-full border rounded px-2 py-1"
value={rigType}
onChange={(e) => setRigType(e.target.value)}
required
>
<option value=""></option>
{rigTypes.map((o) => (
<option key={o.id} value={o.id}>
{o.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm mb-1">
Laser Source <span className="text-red-600">*</span>
</label>
<select
className="w-full border rounded px-2 py-1"
value={laserSource}
onChange={(e) => setLaserSource(e.target.value)}
required
>
<option value="">{sources.loading ? "Loading…" : "—"}</option>
{sources.opts.map((o) => (
<option key={o.id} value={o.id}>
{o.label}
</option>
))}
</select>
</div>
</div>
{/* Lens (focus for gantry, scan + apt/exp for others) */}
{isGantry ? (
<div>
<label className="block text-sm mb-1">Focus Lens</label>
<select
className="w-full border rounded px-2 py-1"
value={focusLens}
onChange={(e) => setFocusLens(e.target.value)}
>
<option value="">{lens.loading ? "Loading…" : "—"}</option>
{lens.opts.map((o) => (
<option key={o.id} value={o.id}>
{o.label}
</option>
))}
</select>
</div>
) : (
<>
<div>
<label className="block text-sm mb-1">Scan Lens</label>
<select
className="w-full border rounded px-2 py-1"
value={scanLens}
onChange={(e) => setScanLens(e.target.value)}
>
<option value="">{lens.loading ? "Loading…" : "—"}</option>
{lens.opts.map((o) => (
<option key={o.id} value={o.id}>
{o.label}
</option>
))}
</select>
</div>
<div className="grid sm:grid-cols-2 gap-3">
<div>
<label className="block text-sm mb-1">Scan Lens Apt</label>
<select
className="w-full border rounded px-2 py-1"
value={scanLensApt}
onChange={(e) => setScanLensApt(e.target.value)}
>
<option value="">
{lensApt.loading ? "Loading…" : "—"}
</option>
{lensApt.opts.map((o) => (
<option key={o.id} value={o.id}>
{o.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm mb-1">Scan Lens Exp</label>
<select
className="w-full border rounded px-2 py-1"
value={scanLensExp}
onChange={(e) => setScanLensExp(e.target.value)}
>
<option value="">
{lensExp.loading ? "Loading…" : "—"}
</option>
{lensExp.opts.map((o) => (
<option key={o.id} value={o.id}>
{o.label}
</option>
))}
</select>
</div>
</div>
</>
)}
<div>
<label className="block text-sm mb-1">Software</label>
<select
className="w-full border rounded px-2 py-1"
value={software}
onChange={(e) => setSoftware(e.target.value)}
>
<option value="">{softwares.loading ? "Loading…" : "—"}</option>
{softwares.opts.map((o) => (
<option key={o.id} value={o.id}>
{o.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm mb-1">Notes</label>
<textarea
rows={4}
className="w-full border rounded px-2 py-1"
value={notes}
onChange={(e) => setNotes(e.target.value)}
/>
</div>
<button className="px-3 py-2 border rounded bg-accent text-background hover:opacity-90">
Create Rig
</button>
{/* Lens sections unchanged, expander select now shows labels with trailing "x" */}
{/* (full component omitted for brevity—only the hook/normalize changed) */}
</form>
);
}

View file

@ -10,11 +10,28 @@ type Rig = {
laser_source?: { submission_id: number; make?: string; model?: string };
laser_scan_lens?: { id: number; field_size?: string; focal_length?: string };
laser_focus_lens?: { id: number; name?: string };
laser_scan_lens_apt?: { id: number; name?: string }; // NEW
laser_scan_lens_exp?: { id: number; name?: string }; // NEW
laser_scan_lens_apt?: { id: number; name?: string };
laser_scan_lens_exp?: { id: number; name?: string };
laser_software?: { id: number; name?: string };
};
function fmtX(v?: string) {
if (!v) return "";
const s = String(v).trim();
if (/x$/i.test(s)) return s;
if (/^\d+(\.\d+)?$/.test(s)) {
if (/^\d$/.test(s)) return `0${s}x`;
return `${s}x`;
}
const m = s.match(/(\d+(?:\.\d+)?)/);
if (m) {
const n = m[1];
if (/^\d$/.test(n)) return `0${n}x`;
return `${n}x`;
}
return `${s}x`;
}
export default function RigsListClient() {
const [rows, setRows] = useState<Rig[]>([]);
const [loading, setLoading] = useState(false);
@ -22,10 +39,7 @@ export default function RigsListClient() {
async function load() {
setLoading(true);
try {
const res = await fetch("/api/rigs", {
credentials: "include",
cache: "no-store",
});
const res = await fetch("/api/rigs", { credentials: "include", cache: "no-store" });
const data = await res.json();
setRows(Array.isArray(data) ? data : data?.data ?? []);
} finally {
@ -33,9 +47,7 @@ export default function RigsListClient() {
}
}
useEffect(() => {
load();
}, []);
useEffect(() => { load(); }, []);
async function remove(id: string | number) {
if (!confirm("Delete this rig?")) return;
@ -56,51 +68,18 @@ export default function RigsListClient() {
<div key={r.id} className="rounded border p-3">
<div className="flex items-center justify-between gap-3">
<div className="font-medium">{r.name}</div>
<button
onClick={() => remove(r.id)}
className="text-sm px-2 py-1 border rounded hover:bg-muted"
>
<button onClick={() => remove(r.id)} className="text-sm px-2 py-1 border rounded hover:bg-muted">
Delete
</button>
</div>
<div className="text-sm text-muted-foreground mt-1">
{r.rig_type?.name ? <>Type: {r.rig_type.name}. </> : null}
{r.laser_source ? (
<>
Source:{" "}
{[
r.laser_source.make,
r.laser_source.model,
].filter(Boolean).join(" ") || r.laser_source.submission_id}
.{" "}
</>
) : null}
{r.laser_focus_lens?.name ? (
<>Focus Lens: {r.laser_focus_lens.name}. </>
) : null}
{r.laser_scan_lens ? (
<>
Scan Lens:{" "}
{[
r.laser_scan_lens.field_size &&
`${r.laser_scan_lens.field_size}mm`,
r.laser_scan_lens.focal_length &&
`${r.laser_scan_lens.focal_length}mm`,
]
.filter(Boolean)
.join(" / ")}
.{" "}
</>
) : null}
{r.laser_scan_lens_apt?.name ? (
<>Scan Lens Apt: {r.laser_scan_lens_apt.name}. </>
) : null}
{r.laser_scan_lens_exp?.name ? (
<>Scan Lens Exp: {r.laser_scan_lens_exp.name}. </>
) : null}
{r.laser_software?.name ? (
<>Software: {r.laser_software.name}. </>
) : null}
{r.laser_source ? <>Source: {[r.laser_source.make, r.laser_source.model].filter(Boolean).join(" ") || r.laser_source.submission_id}. </> : null}
{r.laser_focus_lens?.name ? <>Focus Lens: {r.laser_focus_lens.name}. </> : null}
{r.laser_scan_lens ? <>Scan Lens: {[r.laser_scan_lens.field_size && `${r.laser_scan_lens.field_size}mm`, r.laser_scan_lens.focal_length && `${r.laser_scan_lens.focal_length}mm`].filter(Boolean).join(" / ")}. </> : null}
{r.laser_scan_lens_apt?.name ? <>Scan Lens Apt: {r.laser_scan_lens_apt.name}. </> : null}
{r.laser_scan_lens_exp?.name ? <>Scan Lens Exp: {fmtX(r.laser_scan_lens_exp.name)}. </> : null}
{r.laser_software?.name ? <>Software: {r.laser_software.name}. </> : null}
</div>
{r.notes ? <div className="text-sm mt-2">{r.notes}</div> : null}
</div>

View file

@ -12,10 +12,17 @@ import { NextResponse, NextRequest } from "next/server";
* Keep this list tiny. If you don't need any public APIs, leave it empty.
*/
const PUBLIC_API_PREFIXES: string[] = [
"/api/auth", // login/refresh/callback endpoints
"/api/auth", // login/refresh/callback endpoints
// "/api/health", // uncomment if you intentionally expose a healthcheck
];
/** Directus base (used to remotely validate the token after restarts). */
const DIRECTUS =
(process.env.NEXT_PUBLIC_API_BASE_URL || process.env.DIRECTUS_URL || "").replace(
/\/$/,
""
);
/** Helper: does the path start with any prefix in a list? */
function startsWithAny(pathname: string, prefixes: string[]) {
return prefixes.some((p) => pathname.startsWith(p));
@ -26,12 +33,40 @@ import { NextResponse, NextRequest } from "next/server";
const dest = new URL(req.url);
dest.pathname = mapped.pathname;
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))
dest.searchParams.set(k, v);
}
return dest.href === req.url;
}
export function middleware(req: NextRequest) {
/** 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;
const json = JSON.parse(
atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
);
return typeof json.exp === "number" ? json.exp : null;
} catch {
return null;
}
}
/** Build a redirect response to /auth/sign-in and clear auth markers. */
function kickToSignIn(req: NextRequest) {
const url = new URL(req.url);
url.pathname = "/auth/sign-in";
url.search = "";
const res = NextResponse.redirect(url);
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: "/" });
return res;
}
export async function middleware(req: NextRequest) {
const url = req.nextUrl.clone();
const { pathname } = url;
@ -40,29 +75,82 @@ import { NextResponse, NextRequest } from "next/server";
if (mapped && !isSameUrl(req, mapped)) {
url.pathname = mapped.pathname;
if (mapped.query) {
for (const [k, v] of Object.entries(mapped.query)) url.searchParams.set(k, v);
for (const [k, v] of Object.entries(mapped.query))
url.searchParams.set(k, v);
}
return NextResponse.redirect(url);
}
// ── 2) Auth gating (ma_at is the only allowed auth context)
// ── 2) Auth gating + validation (ma_at is the only allowed auth context)
const token = req.cookies.get("ma_at")?.value ?? "";
const isAuthRoute = pathname.startsWith("/auth/");
// If signed in and visiting /auth/*, send to portal
if (token && isAuthRoute) {
url.pathname = "/portal";
url.search = "";
return NextResponse.redirect(url);
}
const isProtected = !isPublicPath(pathname);
// 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);
if (!token && isProtected) {
return kickToSignIn(req);
}
// If we have a token, perform local expiry check.
if (token) {
const exp = jwtExp(token);
const expired = !exp || exp * 1000 <= Date.now();
// If it's an auth route and token looks valid, keep your existing UX:
// bounce away from auth pages.
if (isAuthRoute && !expired) {
url.pathname = "/portal";
url.search = "";
return NextResponse.redirect(url);
}
// If protected route: enforce validity
if (isProtected) {
if (expired) {
return kickToSignIn(req);
}
// ── 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) {
// Token no longer valid on the server → force re-auth
return kickToSignIn(req);
}
// 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
return kickToSignIn(req);
}
}
}
}
}
// If signed-in and visiting /auth/* but token is expired/invalid, fall through (let them sign in).
// If public or already validated, proceed.
return NextResponse.next();
}
@ -77,15 +165,15 @@ import { NextResponse, NextRequest } from "next/server";
// 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] } })],
[/^\/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
[/^\/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] } })],
[/^\/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] } })],
];
for (const [re, to] of detailRules) {
const m = re.exec(pathname);
@ -95,23 +183,23 @@ import { NextResponse, NextRequest } from "next/server";
// 2) LIST PAGES: legacy lists → portal lists (with tab param) or sections
const listRules: Array<[RegExp, MapResult]> = [
// Laser settings lists
[/^\/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
[/^\/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
// Materials lists
[/^\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
[/^\/materials\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
[/^\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
[/^\/materials\/materials\/?$/i, { pathname: "/portal/materials", query: { t: "materials" } }],
[/^\/materials\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }],
[/^\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }],
[/^\/materials-coatings\/?$/i, { pathname: "/portal/materials", query: { t: "materials-coatings" } }],
// Other lists
[/^\/lasers\/?$/i, { pathname: "/portal/laser-sources" }],
[/^\/projects\/?$/i, { pathname: "/portal/projects" }],
[/^\/my\/rigs\/?$/i, { pathname: "/portal/rigs", query: { t: "my" } }],
[/^\/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;
@ -148,5 +236,7 @@ import { NextResponse, NextRequest } from "next/server";
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|images|static).*)"],
matcher: [
"/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|images|static).*)",
],
};