Admins can now create, edit, toggle and delete redirects from /admin/redirects without a rebuild. Rules support exact or prefix (/old/* -> /new/*) matching, 301/302, internal paths or external URLs, optional query-string passthrough, notes and a hit counter. - Redirect model + migration; grants redirects.manage to admin - /api/redirects CRUD (redirects.manage) plus public /active and /:id/hit - Server validation rejects reserved paths (/api, /_next, /admin, /media, /.well-known), the homepage, loops, duplicates and non-http(s) targets - frontend/middleware.ts caches active rules for 30s, serves stale rules while refreshing, and fails open so a backend outage never blocks pages Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
159 lines
5.0 KiB
TypeScript
159 lines
5.0 KiB
TypeScript
import { NextResponse, type NextFetchEvent, type NextRequest } from "next/server";
|
|
import { apiUrl } from "@/lib/api-base";
|
|
|
|
/**
|
|
* Admin-managed redirects (/admin/redirects). Rules are fetched from the backend
|
|
* and cached in memory; edits go live within REFRESH_MS. This must never take
|
|
* the site down: any failure keeps the last known rules (or none) and lets the
|
|
* request through untouched.
|
|
*/
|
|
|
|
interface Rule {
|
|
id: string;
|
|
source: string;
|
|
destination: string;
|
|
matchType: "exact" | "prefix";
|
|
permanent: boolean;
|
|
preserveQuery: boolean;
|
|
}
|
|
|
|
interface RuleSet {
|
|
exact: Map<string, Rule>;
|
|
/** Longest source first so the most specific prefix wins. */
|
|
prefix: Rule[];
|
|
}
|
|
|
|
const REFRESH_MS = 30_000;
|
|
const RETRY_MS = 10_000;
|
|
const FETCH_TIMEOUT_MS = 1_500;
|
|
|
|
let rules: RuleSet | null = null;
|
|
let nextRefreshAt = 0;
|
|
let inflight: Promise<void> | null = null;
|
|
|
|
function buildRuleSet(list: Rule[]): RuleSet {
|
|
const exact = new Map<string, Rule>();
|
|
const prefix: Rule[] = [];
|
|
for (const r of list) {
|
|
if (r.matchType === "prefix") prefix.push(r);
|
|
else exact.set(r.source, r);
|
|
}
|
|
prefix.sort((a, b) => b.source.length - a.source.length);
|
|
return { exact, prefix };
|
|
}
|
|
|
|
async function refresh(): Promise<void> {
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
try {
|
|
const res = await fetch(apiUrl("/redirects/active"), { signal: controller.signal, cache: "no-store" });
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
const list = (await res.json()) as Rule[];
|
|
if (!Array.isArray(list)) throw new Error("Unexpected response");
|
|
rules = buildRuleSet(list);
|
|
nextRefreshAt = Date.now() + REFRESH_MS;
|
|
} catch {
|
|
nextRefreshAt = Date.now() + RETRY_MS;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
function ensureFresh(event: NextFetchEvent): Promise<void> | null {
|
|
if (Date.now() < nextRefreshAt) return null;
|
|
if (!inflight) {
|
|
inflight = refresh().finally(() => {
|
|
inflight = null;
|
|
});
|
|
}
|
|
// Stale rules are served while refreshing in the background; only the very
|
|
// first request after a cold start waits for them.
|
|
if (rules) {
|
|
event.waitUntil(inflight);
|
|
return null;
|
|
}
|
|
return inflight;
|
|
}
|
|
|
|
/** Decoded path with duplicate and trailing slashes removed (case kept). */
|
|
function cleanPath(pathname: string): string {
|
|
let path = pathname;
|
|
try {
|
|
path = decodeURIComponent(pathname);
|
|
} catch {
|
|
// Malformed escape: match on the raw path.
|
|
}
|
|
return path.replace(/\/{2,}/g, "/").replace(/\/+$/, "") || "/";
|
|
}
|
|
|
|
/** Matches case-insensitively; the remainder of a prefix match keeps its case. */
|
|
function findRule(set: RuleSet, path: string): { rule: Rule; rest: string } | null {
|
|
const lower = path.toLowerCase();
|
|
const exact = set.exact.get(lower);
|
|
if (exact) return { rule: exact, rest: "" };
|
|
for (const rule of set.prefix) {
|
|
if (lower === rule.source) return { rule, rest: "" };
|
|
if (lower.startsWith(`${rule.source}/`)) {
|
|
const source = lower.length === path.length ? path : lower;
|
|
return { rule, rest: source.slice(rule.source.length) };
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Public origin of the request; nginx passes Host and X-Forwarded-Proto. */
|
|
function publicOrigin(req: NextRequest): string {
|
|
const forwarded = req.headers.get("x-forwarded-proto")?.split(",")[0].trim();
|
|
const proto = forwarded === "https" || forwarded === "http" ? forwarded : req.nextUrl.protocol.replace(/:$/, "");
|
|
const host = req.headers.get("host") || req.nextUrl.host;
|
|
return `${proto}://${host}`;
|
|
}
|
|
|
|
function buildLocation(rule: Rule, rest: string, search: URLSearchParams, origin: string): string {
|
|
// Next requires an absolute Location; internal paths resolve against the
|
|
// host the visitor came in on.
|
|
const url = new URL(rule.destination, origin);
|
|
|
|
if (rest) url.pathname = `${url.pathname.replace(/\/+$/, "")}${rest}`;
|
|
|
|
if (rule.preserveQuery) {
|
|
search.forEach((value, key) => {
|
|
if (!url.searchParams.has(key)) url.searchParams.append(key, value);
|
|
});
|
|
}
|
|
|
|
return url.toString();
|
|
}
|
|
|
|
export async function middleware(req: NextRequest, event: NextFetchEvent) {
|
|
try {
|
|
const pending = ensureFresh(event);
|
|
if (pending) await pending;
|
|
if (!rules || (rules.exact.size === 0 && rules.prefix.length === 0)) return NextResponse.next();
|
|
|
|
const match = findRule(rules, cleanPath(req.nextUrl.pathname));
|
|
if (!match) return NextResponse.next();
|
|
|
|
const { rule, rest } = match;
|
|
const location = buildLocation(rule, rest, req.nextUrl.searchParams, publicOrigin(req));
|
|
|
|
event.waitUntil(
|
|
fetch(apiUrl(`/redirects/${encodeURIComponent(rule.id)}/hit`), { method: "POST" })
|
|
.then(() => undefined)
|
|
.catch(() => undefined)
|
|
);
|
|
|
|
return new NextResponse(null, {
|
|
status: rule.permanent ? 301 : 302,
|
|
headers: { Location: location, "Cache-Control": "no-store" },
|
|
});
|
|
} catch {
|
|
return NextResponse.next();
|
|
}
|
|
}
|
|
|
|
export const config = {
|
|
// Never run for the API, build assets, uploaded media or ACME/lnurlp paths.
|
|
matcher: ["/((?!api/|_next/|media/|\\.well-known/|favicon\\.ico).*)"],
|
|
};
|