Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
refactor(status-page): extract proxy middleware into tested pure stages (#2086)
Maximilian Kaskebd270838aa1a
diff --git a/apps/status-page/package.json b/apps/status-page/package.jsonindex 45e64fec4..e44a96913 100644--- a/apps/status-page/package.json+++ b/apps/status-page/package.json@@ -8,6 +8,7 @@"build": "next build","start": "next start","lint": "next lint",+ "test": "bun test","tsc": "tsc --noEmit"},"dependencies": {diff --git a/apps/status-page/src/lib/proxy/apply-page-locale-override.test.ts b/apps/status-page/src/lib/proxy/apply-page-locale-override.test.tsnew file mode 100644index 000000000..6db39ba2e--- /dev/null+++ b/apps/status-page/src/lib/proxy/apply-page-locale-override.test.ts@@ -0,0 +1,69 @@+import { describe, expect, test } from "bun:test";+import type { ResolvedRoute } from "../resolve-route";+import { applyPageLocaleOverride } from "./apply-page-locale-override";++const baseRoute: ResolvedRoute = {+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: false,+ rewritePath: "/acme/en",+};++describe("applyPageLocaleOverride", () => {+ test("localeExplicit: returns input unchanged", () => {+ const route = { ...baseRoute, localeExplicit: true };+ expect(applyPageLocaleOverride(route, { defaultLocale: "fr" })).toBe(route);+ });++ test("page default equals current locale: returns input unchanged", () => {+ expect(applyPageLocaleOverride(baseRoute, { defaultLocale: "en" })).toBe(+ baseRoute,+ );+ });++ test("page default differs: returns new route with swapped locale and rewritePath", () => {+ const result = applyPageLocaleOverride(baseRoute, { defaultLocale: "fr" });+ expect(result).not.toBe(baseRoute);+ expect(result).toEqual({+ type: "pathname",+ prefix: "acme",+ locale: "fr",+ localeExplicit: false,+ rewritePath: "/acme/fr",+ });+ });++ test("swaps locale within a deeper rewritePath", () => {+ const route: ResolvedRoute = {+ ...baseRoute,+ rewritePath: "/acme/en/events",+ };+ const result = applyPageLocaleOverride(route, { defaultLocale: "fr" });+ expect(result.rewritePath).toBe("/acme/fr/events");+ });++ test("hostname routing: swaps locale in rewritePath", () => {+ const route: ResolvedRoute = {+ type: "hostname",+ prefix: "acme",+ locale: "en",+ localeExplicit: false,+ rewritePath: "/acme/en/monitors/1",+ };+ const result = applyPageLocaleOverride(route, { defaultLocale: "fr" });+ expect(result).toEqual({+ type: "hostname",+ prefix: "acme",+ locale: "fr",+ localeExplicit: false,+ rewritePath: "/acme/fr/monitors/1",+ });+ });++ test("does not mutate input", () => {+ const route = { ...baseRoute };+ applyPageLocaleOverride(route, { defaultLocale: "fr" });+ expect(route).toEqual(baseRoute);+ });+});diff --git a/apps/status-page/src/lib/proxy/apply-page-locale-override.ts b/apps/status-page/src/lib/proxy/apply-page-locale-override.tsnew file mode 100644index 000000000..b856010d7--- /dev/null+++ b/apps/status-page/src/lib/proxy/apply-page-locale-override.ts@@ -0,0 +1,28 @@+import type { Page } from "@openstatus/db/src/schema";+import type { ResolvedRoute } from "../resolve-route";++/**+ * If the URL had no explicit locale segment, swap in the page's configured+ * default locale (when it differs from the route's fallback default).+ *+ * Pure function — returns a new ResolvedRoute rather than mutating the input.+ * Runs once in proxy.ts after the DB query, before the composer, so every+ * downstream stage sees a locale-normalised route.+ */+export function applyPageLocaleOverride(+ route: ResolvedRoute,+ page: Pick<Page, "defaultLocale">,+): ResolvedRoute {+ if (route.localeExplicit) return route;+ if (!page.defaultLocale) return route;+ if (page.defaultLocale === route.locale) return route;++ return {+ ...route,+ locale: page.defaultLocale,+ rewritePath: route.rewritePath.replace(+ `/${route.prefix}/${route.locale}`,+ `/${route.prefix}/${page.defaultLocale}`,+ ),+ };+}diff --git a/apps/status-page/src/lib/proxy/build-external-path.test.ts b/apps/status-page/src/lib/proxy/build-external-path.test.tsnew file mode 100644index 000000000..06bb1f962--- /dev/null+++ b/apps/status-page/src/lib/proxy/build-external-path.test.ts@@ -0,0 +1,43 @@+import { describe, expect, test } from "bun:test";+import { buildExternalPath } from "./build-external-path";++describe("buildExternalPath", () => {+ test("hostname routing: suffix stands alone", () => {+ expect(+ buildExternalPath({ type: "hostname", prefix: "acme" }, "/login"),+ ).toBe("/login");+ });++ test("hostname routing: empty suffix → page root", () => {+ expect(buildExternalPath({ type: "hostname", prefix: "acme" }, "")).toBe(+ "",+ );+ });++ test("pathname routing: prefix prepended to suffix", () => {+ expect(+ buildExternalPath({ type: "pathname", prefix: "acme" }, "/login"),+ ).toBe("/acme/login");+ });++ test("pathname routing: empty suffix → page root with prefix", () => {+ expect(buildExternalPath({ type: "pathname", prefix: "acme" }, "")).toBe(+ "/acme",+ );+ });++ test("pathname routing: /restricted suffix", () => {+ expect(+ buildExternalPath({ type: "pathname", prefix: "status" }, "/restricted"),+ ).toBe("/status/restricted");+ });++ test("hostname routing: custom-domain prefix", () => {+ expect(+ buildExternalPath(+ { type: "hostname", prefix: "status.acme.com" },+ "/login",+ ),+ ).toBe("/login");+ });+});diff --git a/apps/status-page/src/lib/proxy/build-external-path.ts b/apps/status-page/src/lib/proxy/build-external-path.tsnew file mode 100644index 000000000..00addbe10--- /dev/null+++ b/apps/status-page/src/lib/proxy/build-external-path.ts@@ -0,0 +1,16 @@+import type { ResolvedRoute } from "../resolve-route";++/**+ * Builds the external-facing path for a page, accounting for routing mode.+ * - hostname routing: the slug is implicit in the host, so the suffix stands alone.+ * - pathname routing: the slug is prepended, e.g. `/acme/login`.+ *+ * Pass `suffix` as a leading-slash path segment (e.g. "/login") or "" for the page root.+ */+export function buildExternalPath(+ route: Pick<ResolvedRoute, "type" | "prefix">,+ suffix: string,+): string {+ if (route.type === "hostname") return suffix;+ return `/${route.prefix}${suffix}`;+}diff --git a/apps/status-page/src/lib/proxy/compose-page-action.test.ts b/apps/status-page/src/lib/proxy/compose-page-action.test.tsnew file mode 100644index 000000000..8faf69687--- /dev/null+++ b/apps/status-page/src/lib/proxy/compose-page-action.test.ts@@ -0,0 +1,154 @@+import { describe, expect, test } from "bun:test";+import type { Page } from "@openstatus/db/src/schema";+import type { ResolvedRoute } from "../resolve-route";+import { type ComposeInput, composePageAction } from "./compose-page-action";++const route: ResolvedRoute = {+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++const basePage: Page = {+ id: 1,+ workspaceId: 1,+ title: "Acme",+ description: "",+ slug: "acme",+ customDomain: "",+ icon: "",+ forceTheme: null,+ footerHtml: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ published: true,+ passwordProtected: false,+ password: "",+ accessType: "public",+ authEmailDomains: [],+ allowedIpRanges: [],+ defaultLocale: "en",+ locales: null,+ favicon: null,+ logo: null,+ contactUrl: null,+ statusReportSchedule: null,+ showMonitorValues: null,+ showMonitorUptime: null,+} as unknown as Page;++function buildInput(overrides: Partial<ComposeInput> = {}): ComposeInput {+ return {+ route,+ page: basePage,+ host: "localhost:3000",+ urlHost: "localhost:3000",+ pathname: "/acme/en",+ search: "",+ isSelfHosted: false,+ requestUrl: "http://localhost:3000/acme/en",+ origin: "http://localhost:3000",+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ authEmail: null,+ clientIp: null,+ ...overrides,+ };+}++describe("composePageAction — priority ordering", () => {+ test("all stages pass → passthrough with reason 'no-match'", () => {+ const action = composePageAction(buildInput());+ expect(action.type).toBe("passthrough");+ expect(action.reason).toBe("no-match");+ expect(action.url).toBeUndefined();+ });++ test("locale rejection fires before password gate", () => {+ const action = composePageAction(+ buildInput({+ route: { ...route, locale: "fr", rewritePath: "/acme/fr" },+ page: {+ ...basePage,+ locales: ["en"],+ accessType: "password",+ password: "secret",+ } as Page,+ }),+ );+ expect(action.reason).toBe("locale-mismatch-redirect");+ });++ test("password gate fires before ip-restriction (when accessType matches password)", () => {+ const action = composePageAction(+ buildInput({+ page: {+ ...basePage,+ accessType: "password",+ password: "secret",+ } as Page,+ // ip-restriction would also block if it were checked, but password wins+ clientIp: "1.2.3.4",+ }),+ );+ expect(action.reason).toBe("password-gate-in");+ });++ test("ip-restriction gate fires (no other stage matches)", () => {+ const action = composePageAction(+ buildInput({+ page: {+ ...basePage,+ accessType: "ip-restriction",+ allowedIpRanges: ["10.0.0.0/24"],+ } as Page,+ clientIp: "1.2.3.4",+ }),+ );+ expect(action.reason).toBe("ip-restriction-gate-in");+ });++ test("custom-domain rewrite fires before default rewrite", () => {+ const action = composePageAction(+ buildInput({+ page: {+ ...basePage,+ customDomain: "status.acme.com",+ } as Page,+ host: "status.acme.com",+ urlHost: "localhost:3000",+ pathname: "/status.acme.com/en/events",+ }),+ );+ expect(action.reason).toBe("custom-domain-rewrite-path-strip");+ });++ test("default rewrite fires when paths differ and no other stage matches", () => {+ const action = composePageAction(+ buildInput({+ route: { ...route, rewritePath: "/acme/en" },+ pathname: "/acme",+ }),+ );+ expect(action.reason).toBe("default-rewrite");+ });++ test("email-domain gate fires before ip-restriction when both would match", () => {+ // Only one accessType is set on a page, so they are exclusive. This test+ // documents ordering: email-domain comes before ip-restriction in the chain.+ const action = composePageAction(+ buildInput({+ page: {+ ...basePage,+ accessType: "email-domain",+ authEmailDomains: ["acme.com"],+ } as Page,+ authEmail: null,+ }),+ );+ expect(action.reason).toBe("email-domain-gate-in");+ });+});diff --git a/apps/status-page/src/lib/proxy/compose-page-action.ts b/apps/status-page/src/lib/proxy/compose-page-action.tsnew file mode 100644index 000000000..be5b44fdd--- /dev/null+++ b/apps/status-page/src/lib/proxy/compose-page-action.ts@@ -0,0 +1,47 @@+import { resolveCustomDomainRewrite } from "./resolve-custom-domain-rewrite";+import { resolveDefaultRewrite } from "./resolve-default-rewrite";+import { resolveEmailDomainAction } from "./resolve-email-domain-action";+import { resolveIpRestrictionAction } from "./resolve-ip-restriction-action";+import { resolveLocaleAction } from "./resolve-locale-action";+import { resolvePasswordAction } from "./resolve-password-action";+import { type Action, type ComposeInput, passthrough } from "./types";++export type { ComposeInput };++/**+ * Runs the proxy stages in priority order and returns the first non-null+ * Action. If every stage passes, returns a `passthrough` action.+ *+ * Priority ordering (top wins):+ * 1. locale-mismatch redirect+ * 2. password gate (in/out)+ * 3. email-domain gate (in/out)+ * 4. ip-restriction gate (in/out)+ * 5. custom-domain rewrite (stpg.dev hosted)+ * 6. default rewrite (openstatus.dev OR rewritePath differs)+ *+ * Note on locale-first: a user on a mis-localed URL for a gated page gets+ * two redirects (locale → gate) instead of one. We accept the extra hop so+ * the gate and its `?redirect=` capture operate on the canonical localed+ * URL — gating first would capture the mis-localed path as the post-auth+ * target, forcing a third redirect after auth. Revisit if measured UX cost+ * outweighs the ambiguity.+ */+export function composePageAction(input: ComposeInput): Action {+ return (+ resolveLocaleAction(input) ??+ resolvePasswordAction(input) ??+ resolveEmailDomainAction(input) ??+ resolveIpRestrictionAction(input) ??+ resolveCustomDomainRewrite(input) ??+ resolveDefaultRewrite(input) ??+ // Reached whenever resolveDefaultRewrite declines: host is not an+ // openstatus.dev host AND route.rewritePath === pathname. In hosted+ // deployments this is rare because one of those conditions almost always+ // triggers. In self-hosted mode (no openstatus.dev host) it fires for any+ // request whose resolved route already matches the URL — expect to see+ // `reason: "no-match"` in those logs. The dispatcher turns it into+ // NextResponse.next() (passthrough).+ passthrough("no-match")+ );+}diff --git a/apps/status-page/src/lib/proxy/is-ip-allowed.test.ts b/apps/status-page/src/lib/proxy/is-ip-allowed.test.tsnew file mode 100644index 000000000..8a424dc1f--- /dev/null+++ b/apps/status-page/src/lib/proxy/is-ip-allowed.test.ts@@ -0,0 +1,45 @@+import { describe, expect, test } from "bun:test";+import { isIpAllowed } from "./is-ip-allowed";++describe("isIpAllowed", () => {+ test("empty allowed ranges → denies all", () => {+ expect(isIpAllowed("1.2.3.4", [])).toBe(false);+ });++ test("IP inside single range → allowed", () => {+ expect(isIpAllowed("10.0.0.5", ["10.0.0.0/24"])).toBe(true);+ });++ test("IP outside single range → denied", () => {+ expect(isIpAllowed("10.0.1.5", ["10.0.0.0/24"])).toBe(false);+ });++ test("IP matches one of multiple ranges → allowed", () => {+ expect(isIpAllowed("192.168.1.10", ["10.0.0.0/24", "192.168.1.0/24"])).toBe(+ true,+ );+ });++ test("IP matches none of multiple ranges → denied", () => {+ expect(isIpAllowed("172.16.0.1", ["10.0.0.0/24", "192.168.1.0/24"])).toBe(+ false,+ );+ });++ test("exact /32 single-host range", () => {+ expect(isIpAllowed("1.2.3.4", ["1.2.3.4/32"])).toBe(true);+ expect(isIpAllowed("1.2.3.5", ["1.2.3.4/32"])).toBe(false);+ });++ test("malformed range is skipped, other ranges still evaluated", () => {+ expect(isIpAllowed("10.0.0.1", ["not-a-cidr", "10.0.0.0/24"])).toBe(true);+ });++ test("all malformed ranges → denied", () => {+ expect(isIpAllowed("10.0.0.1", ["not-a-cidr", "also-bad"])).toBe(false);+ });++ test("IPv6 range match", () => {+ expect(isIpAllowed("2001:db8::1", ["2001:db8::/32"])).toBe(true);+ });+});diff --git a/apps/status-page/src/lib/proxy/is-ip-allowed.ts b/apps/status-page/src/lib/proxy/is-ip-allowed.tsnew file mode 100644index 000000000..a4fdcb8be--- /dev/null+++ b/apps/status-page/src/lib/proxy/is-ip-allowed.ts@@ -0,0 +1,19 @@+import IPCIDR from "ip-cidr";++/**+ * Checks whether a client IP falls within any of the allowed CIDR ranges.+ * Pure function — no side effects.+ */+export function isIpAllowed(ip: string, allowedRanges: string[]): boolean {+ // No ranges configured — deny all (defensive: form validation prevents this)+ if (allowedRanges.length === 0) return false;+ return allowedRanges.some((range) => {+ try {+ const cidr = new IPCIDR(range);+ return cidr.contains(ip);+ } catch {+ // Skip malformed ranges rather than crashing the middleware+ return false;+ }+ });+}diff --git a/apps/status-page/src/lib/proxy/resolve-custom-domain-rewrite.test.ts b/apps/status-page/src/lib/proxy/resolve-custom-domain-rewrite.test.tsnew file mode 100644index 000000000..c6bb0e6dc--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-custom-domain-rewrite.test.ts@@ -0,0 +1,167 @@+import { describe, expect, test } from "bun:test";+import { resolveCustomDomainRewrite } from "./resolve-custom-domain-rewrite";++const page = {+ slug: "acme",+ customDomain: "status.acme.com",+};++describe("resolveCustomDomainRewrite", () => {+ test("self-hosted: passes (null)", () => {+ expect(+ resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "localhost:3000",+ pathname: "/en/events",+ search: "",+ isSelfHosted: true,+ requestUrl: "http://localhost:3000/en/events",+ }),+ ).toBeNull();+ });++ test("no customDomain configured: passes (null)", () => {+ expect(+ resolveCustomDomainRewrite({+ page: { slug: "acme", customDomain: "" },+ host: "acme.stpg.dev",+ urlHost: "localhost:3000",+ pathname: "/en",+ search: "",+ isSelfHosted: false,+ requestUrl: "http://acme.stpg.dev/en",+ }),+ ).toBeNull();+ });++ test("host === {slug}.stpg.dev: passes (null)", () => {+ expect(+ resolveCustomDomainRewrite({+ page,+ host: "acme.stpg.dev",+ urlHost: "localhost:3000",+ pathname: "/en",+ search: "",+ isSelfHosted: false,+ requestUrl: "http://acme.stpg.dev/en",+ }),+ ).toBeNull();+ });++ // Branch 1: no subdomain detected on urlHost, deep path.+ test("branch 1 (path-strip): no subdomain, deep path → /{slug}/<rest>", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "localhost:3000",+ pathname: "/status.acme.com/en/events",+ search: "",+ isSelfHosted: false,+ requestUrl: "http://localhost:3000/status.acme.com/en/events",+ });+ expect(action?.reason).toBe("custom-domain-rewrite-path-strip");+ expect(action?.url?.pathname).toBe("/acme/en/events");+ });++ test("branch 1: trailing-slash-only path → /{slug} without trailing slash", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "localhost:3000",+ pathname: "/status.acme.com/",+ search: "",+ isSelfHosted: false,+ requestUrl: "http://localhost:3000/status.acme.com/",+ });+ expect(action?.reason).toBe("custom-domain-rewrite-path-strip");+ expect(action?.url?.pathname).toBe("/acme");+ });++ test("branch 1 preserves search", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "localhost:3000",+ pathname: "/status.acme.com/en",+ search: "?foo=bar",+ isSelfHosted: false,+ requestUrl: "http://localhost:3000/status.acme.com/en",+ });+ expect(action?.url?.search).toBe("?foo=bar");+ });++ // Branch 2: subdomain on urlHost, deep path.+ test("branch 2 (subdomain-subpath): subdomain + deep path → https://{slug}.stpg.dev/<rest>", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "acme.stpg.dev",+ pathname: "/path/to/events",+ search: "",+ isSelfHosted: false,+ requestUrl: "https://acme.stpg.dev/path/to/events",+ });+ expect(action?.reason).toBe("custom-domain-rewrite-subdomain-subpath");+ expect(action?.url?.host).toBe("acme.stpg.dev");+ expect(action?.url?.pathname).toBe("/path/to/events");+ });++ // Branch 3: subdomain on urlHost, shallow path.+ test("branch 3 (subdomain-root): subdomain + shallow path → https://{slug}.stpg.dev{pathname}", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "acme.stpg.dev",+ pathname: "/en",+ search: "",+ isSelfHosted: false,+ requestUrl: "https://acme.stpg.dev/en",+ });+ expect(action?.reason).toBe("custom-domain-rewrite-subdomain-root");+ expect(action?.url?.host).toBe("acme.stpg.dev");+ expect(action?.url?.pathname).toBe("/en");+ });++ test("branch 3: root path", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "acme.stpg.dev",+ pathname: "/",+ search: "",+ isSelfHosted: false,+ requestUrl: "https://acme.stpg.dev/",+ });+ expect(action?.reason).toBe("custom-domain-rewrite-subdomain-root");+ expect(action?.url?.pathname).toBe("/");+ });++ // Branch 4: no subdomain, shallow path → fallback.+ test("branch 4 (fallback): no subdomain, shallow path → /{slug}", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "localhost:3000",+ pathname: "/",+ search: "",+ isSelfHosted: false,+ requestUrl: "http://localhost:3000/",+ });+ expect(action?.reason).toBe("custom-domain-rewrite-fallback");+ expect(action?.url?.pathname).toBe("/acme");+ });++ test("branch 4 preserves search", () => {+ const action = resolveCustomDomainRewrite({+ page,+ host: "status.acme.com",+ urlHost: "localhost:3000",+ pathname: "/",+ search: "?x=1",+ isSelfHosted: false,+ requestUrl: "http://localhost:3000/",+ });+ expect(action?.url?.search).toBe("?x=1");+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-custom-domain-rewrite.ts b/apps/status-page/src/lib/proxy/resolve-custom-domain-rewrite.tsnew file mode 100644index 000000000..37482ed5d--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-custom-domain-rewrite.ts@@ -0,0 +1,86 @@+import type { Page } from "@openstatus/db/src/schema";+import { getValidSubdomain } from "../domain";+import type { Action, ComposeInput } from "./types";++type Input = Pick<+ ComposeInput,+ "host" | "urlHost" | "pathname" | "search" | "isSelfHosted" | "requestUrl"+> & {+ page: Pick<Page, "slug" | "customDomain">;+};++/**+ * stpg.dev ↔ custom-domain rewrite. Runs only when the request reaches us on a+ * host other than `{slug}.stpg.dev` for a page that has a configured custom+ * domain (and we are not in self-hosted mode).+ *+ * Four branches:+ * 1. subdomain absent, deep path → rewrite to `/{slug}/<rest>` (path-strip).+ * 2. subdomain present, deep path → rewrite to `https://{slug}.stpg.dev/<rest>` (subdomain-subpath).+ * 3. subdomain present, shallow path → rewrite to `https://{slug}.stpg.dev{pathname}` (subdomain-root).+ * 4. Otherwise → rewrite to `/{slug}` (fallback).+ *+ * All branches preserve the incoming search string.+ */+export function resolveCustomDomainRewrite({+ page,+ host,+ urlHost,+ pathname,+ search,+ isSelfHosted,+ requestUrl,+}: Input): Action | null {+ if (isSelfHosted) return null;+ if (!page.customDomain) return null;+ if (host === `${page.slug}.stpg.dev`) return null;++ const pathnames = pathname.split("/");+ const subdomain = getValidSubdomain(urlHost);++ // Branch 1: no subdomain, pathname has >1 segment → strip leading segment.+ if (pathnames.length > 2 && !subdomain) {+ const rest = pathnames.slice(2).join("/");+ // Trailing-slash only (e.g. "/status.acme.com/") yields empty `rest` —+ // emit `/{slug}` without a trailing slash to match Branch 4's semantics+ // and avoid a redundant 308 from Next.js trailing-slash handling.+ const path = rest ? `/${page.slug}/${rest}` : `/${page.slug}`;+ const url = new URL(path, requestUrl);+ url.search = search;+ return {+ type: "rewrite",+ url,+ reason: "custom-domain-rewrite-path-strip",+ };+ }++ // Branch 2 & 3: subdomain present — rewrite to the stpg.dev host.+ if (subdomain) {+ if (pathnames.length > 2) {+ const rest = pathnames.slice(1).join("/");+ const url = new URL(rest, `https://${page.slug}.stpg.dev`);+ url.search = search;+ return {+ type: "rewrite",+ url,+ reason: "custom-domain-rewrite-subdomain-subpath",+ };+ }+ const url = new URL(pathname, `https://${page.slug}.stpg.dev`);+ url.search = search;+ return {+ type: "rewrite",+ url,+ reason: "custom-domain-rewrite-subdomain-root",+ };+ }++ // Branch 4: fallback — rewrite to the bare slug.+ const url = new URL(`/${page.slug}`, requestUrl);+ url.search = search;+ return {+ type: "rewrite",+ url,+ reason: "custom-domain-rewrite-fallback",+ };+}diff --git a/apps/status-page/src/lib/proxy/resolve-default-rewrite.test.ts b/apps/status-page/src/lib/proxy/resolve-default-rewrite.test.tsnew file mode 100644index 000000000..7a5ea1eb8--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-default-rewrite.test.ts@@ -0,0 +1,103 @@+import { describe, expect, test } from "bun:test";+import type { ResolvedRoute } from "../resolve-route";+import { resolveDefaultRewrite } from "./resolve-default-rewrite";++const hostnameRoute: ResolvedRoute = {+ type: "hostname",+ prefix: "acme",+ locale: "en",+ localeExplicit: false,+ rewritePath: "/acme/en",+};++const pathnameRoute: ResolvedRoute = {+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++describe("resolveDefaultRewrite", () => {+ test("rewritePath matches pathname (non-openstatus host): passes (null)", () => {+ expect(+ resolveDefaultRewrite({+ route: pathnameRoute,+ host: "localhost:3000",+ pathname: "/acme/en",+ search: "",+ requestUrl: "http://localhost:3000/acme/en",+ }),+ ).toBeNull();+ });++ test("rewritePath differs from pathname: rewrite to rewritePath", () => {+ const action = resolveDefaultRewrite({+ route: hostnameRoute,+ host: "acme.localhost:3000",+ pathname: "/",+ search: "",+ requestUrl: "http://acme.localhost:3000/",+ });+ expect(action?.type).toBe("rewrite");+ expect(action?.reason).toBe("default-rewrite");+ expect(action?.url?.pathname).toBe("/acme/en");+ });++ test("openstatus.dev host always rewrites (even if paths match)", () => {+ const action = resolveDefaultRewrite({+ route: pathnameRoute,+ host: "openstatus.dev",+ pathname: "/acme/en",+ search: "",+ requestUrl: "https://openstatus.dev/acme/en",+ });+ expect(action?.reason).toBe("default-rewrite");+ expect(action?.url?.pathname).toBe("/acme/en");+ });++ test("openstatus.dev host rewrites when paths differ", () => {+ const action = resolveDefaultRewrite({+ route: hostnameRoute,+ host: "openstatus.dev",+ pathname: "/",+ search: "",+ requestUrl: "https://openstatus.dev/",+ });+ expect(action?.url?.pathname).toBe("/acme/en");+ });++ test("preserves search params", () => {+ const action = resolveDefaultRewrite({+ route: hostnameRoute,+ host: "acme.localhost:3000",+ pathname: "/",+ search: "?foo=bar",+ requestUrl: "http://acme.localhost:3000/",+ });+ expect(action?.url?.search).toBe("?foo=bar");+ });++ test("null host, paths match: passes (null)", () => {+ expect(+ resolveDefaultRewrite({+ route: pathnameRoute,+ host: null,+ pathname: "/acme/en",+ search: "",+ requestUrl: "http://localhost:3000/acme/en",+ }),+ ).toBeNull();+ });++ test("host with openstatus.dev substring (e.g. docs.openstatus.dev): triggers rewrite", () => {+ const action = resolveDefaultRewrite({+ route: pathnameRoute,+ host: "docs.openstatus.dev",+ pathname: "/acme/en",+ search: "",+ requestUrl: "https://docs.openstatus.dev/acme/en",+ });+ expect(action?.reason).toBe("default-rewrite");+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-default-rewrite.ts b/apps/status-page/src/lib/proxy/resolve-default-rewrite.tsnew file mode 100644index 000000000..d8a2fce2f--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-default-rewrite.ts@@ -0,0 +1,35 @@+import type { Action, ComposeInput } from "./types";++type Input = Pick<+ ComposeInput,+ "route" | "host" | "pathname" | "search" | "requestUrl"+>;++/**+ * Fallback rewrite: target is the route's internal `rewritePath`. Fires when+ * either:+ * - the request is on an openstatus.dev host (preserved from original —+ * unclear if this no-op rewrite is load-bearing when rewritePath ===+ * pathname; kept as-is), OR+ * - the resolved rewritePath differs from the incoming pathname.+ */+export function resolveDefaultRewrite({+ route,+ host,+ pathname,+ search,+ requestUrl,+}: Input): Action | null {+ const isOpenstatusDevHost = !!host?.includes("openstatus.dev");+ const pathDiffers = route.rewritePath !== pathname;++ if (!isOpenstatusDevHost && !pathDiffers) return null;++ const url = new URL(route.rewritePath, requestUrl);+ url.search = search;+ return {+ type: "rewrite",+ url,+ reason: "default-rewrite",+ };+}diff --git a/apps/status-page/src/lib/proxy/resolve-email-domain-action.test.ts b/apps/status-page/src/lib/proxy/resolve-email-domain-action.test.tsnew file mode 100644index 000000000..67687ce0e--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-email-domain-action.test.ts@@ -0,0 +1,163 @@+import { describe, expect, test } from "bun:test";+import type { ResolvedRoute } from "../resolve-route";+import { resolveEmailDomainAction } from "./resolve-email-domain-action";++const pathnameRoute: ResolvedRoute = {+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++const hostnameRoute: ResolvedRoute = {+ type: "hostname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++const page = {+ accessType: "email-domain" as const,+ authEmailDomains: ["acme.com"],+};++describe("resolveEmailDomainAction", () => {+ test("non-email-domain page: passes (null)", () => {+ expect(+ resolveEmailDomainAction({+ route: pathnameRoute,+ page: { ...page, accessType: "public" as const },+ pathname: "/acme/en",+ authEmail: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ }),+ ).toBeNull();+ });++ test("gate-in pathname: no email → redirect to /acme/login", () => {+ const action = resolveEmailDomainAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/en",+ authEmail: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("email-domain-gate-in");+ expect(action?.url?.pathname).toBe("/acme/login");+ });++ test("gate-in pathname: email domain mismatch → redirect", () => {+ const action = resolveEmailDomainAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/en",+ authEmail: "[email protected]",+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("email-domain-gate-in");+ });++ test("gate-in hostname: redirect to /login (no prefix)", () => {+ const action = resolveEmailDomainAction({+ route: hostnameRoute,+ page,+ pathname: "/en",+ authEmail: null,+ redirectParam: null,+ origin: "http://acme.localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/login");+ });++ test("gate-out pathname: authorised email on /login → /acme", () => {+ const action = resolveEmailDomainAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/login",+ authEmail: "[email protected]",+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("email-domain-gate-out");+ expect(action?.url?.pathname).toBe("/acme");+ });++ test("gate-out hostname: authorised email on /login → /", () => {+ const action = resolveEmailDomainAction({+ route: hostnameRoute,+ page,+ pathname: "/login",+ authEmail: "[email protected]",+ redirectParam: null,+ origin: "http://acme.localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/");+ });++ test("gate-out pathname with redirectParam: honours the redirect target", () => {+ const action = resolveEmailDomainAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/login",+ authEmail: "[email protected]",+ redirectParam: "/acme/en/events",+ origin: "http://localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/acme/en/events");+ });++ test("gate-out hostname with redirectParam: honours the redirect target", () => {+ const action = resolveEmailDomainAction({+ route: hostnameRoute,+ page,+ pathname: "/login",+ authEmail: "[email protected]",+ redirectParam: "/en/events",+ origin: "http://acme.localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/en/events");+ });++ test("authorised email off /login: passes (null)", () => {+ expect(+ resolveEmailDomainAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/en",+ authEmail: "[email protected]",+ redirectParam: null,+ origin: "http://localhost:3000",+ }),+ ).toBeNull();+ });++ test("unauthorised email on /login: passes (null — user already on gate)", () => {+ expect(+ resolveEmailDomainAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/login",+ authEmail: "[email protected]",+ redirectParam: null,+ origin: "http://localhost:3000",+ }),+ ).toBeNull();+ });++ test("email without @ → treated as unauthorised", () => {+ const action = resolveEmailDomainAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/en",+ authEmail: "malformed",+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("email-domain-gate-in");+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-email-domain-action.ts b/apps/status-page/src/lib/proxy/resolve-email-domain-action.tsnew file mode 100644index 000000000..26ba7c817--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-email-domain-action.ts@@ -0,0 +1,57 @@+import type { Page } from "@openstatus/db/src/schema";+import { buildExternalPath } from "./build-external-path";+import type { Action, ComposeInput } from "./types";++type Input = Pick<+ ComposeInput,+ "route" | "pathname" | "authEmail" | "redirectParam" | "origin"+> & {+ page: Pick<Page, "accessType" | "authEmailDomains">;+};++/**+ * Email-domain-gated page access control. Handles both gate-in+ * (missing/unauthorised email → /login) and gate-out (authorised email on+ * /login → page root).+ *+ * Note on `endsWith("/login")`: deliberately loose; preserved from the+ * original middleware.+ */+export function resolveEmailDomainAction({+ route,+ page,+ pathname,+ authEmail,+ redirectParam,+ origin,+}: Input): Action | null {+ if (page.accessType !== "email-domain") return null;++ const emailDomain = authEmail?.split("@")[1];+ const isAuthorised = !!(+ emailDomain && page.authEmailDomains.includes(emailDomain)+ );+ const isOnLogin = pathname.endsWith("/login");++ // Gate-in: not authorised and not on /login → send to login+ if (!isOnLogin && !isAuthorised) {+ return {+ type: "redirect",+ url: new URL(`${origin}${buildExternalPath(route, "/login")}`),+ reason: "email-domain-gate-in",+ };+ }++ // Gate-out: authorised and on /login → send to the originally-requested path+ // (if provided) or page root. Mirrors password-gate-out's redirect-honouring.+ if (isOnLogin && isAuthorised) {+ const target = redirectParam ?? buildExternalPath(route, "");+ return {+ type: "redirect",+ url: new URL(`${origin}${target}`),+ reason: "email-domain-gate-out",+ };+ }++ return null;+}diff --git a/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.test.ts b/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.test.tsnew file mode 100644index 000000000..9c5f7863c--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.test.ts@@ -0,0 +1,119 @@+import { describe, expect, test } from "bun:test";+import type { ResolvedRoute } from "../resolve-route";+import { resolveIpRestrictionAction } from "./resolve-ip-restriction-action";++const pathnameRoute: ResolvedRoute = {+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++const hostnameRoute: ResolvedRoute = {+ type: "hostname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++const page = {+ accessType: "ip-restriction" as const,+ allowedIpRanges: ["10.0.0.0/24"],+};++describe("resolveIpRestrictionAction", () => {+ test("non-ip-restriction page: passes (null)", () => {+ expect(+ resolveIpRestrictionAction({+ route: pathnameRoute,+ page: { ...page, accessType: "public" as const },+ pathname: "/acme/en",+ clientIp: "1.1.1.1",+ origin: "http://localhost:3000",+ }),+ ).toBeNull();+ });++ test("gate-in pathname: disallowed IP → redirect to /acme/restricted", () => {+ const action = resolveIpRestrictionAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/en",+ clientIp: "1.2.3.4",+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("ip-restriction-gate-in");+ expect(action?.url?.pathname).toBe("/acme/restricted");+ });++ test("gate-in hostname: disallowed IP → redirect to /restricted (no prefix)", () => {+ const action = resolveIpRestrictionAction({+ route: hostnameRoute,+ page,+ pathname: "/en",+ clientIp: "1.2.3.4",+ origin: "http://acme.localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/restricted");+ });++ test("gate-in: missing clientIp treated as disallowed", () => {+ const action = resolveIpRestrictionAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/en",+ clientIp: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("ip-restriction-gate-in");+ });++ test("gate-out pathname: allowed IP on /restricted → /acme", () => {+ const action = resolveIpRestrictionAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/restricted",+ clientIp: "10.0.0.5",+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("ip-restriction-gate-out");+ expect(action?.url?.pathname).toBe("/acme");+ });++ test("gate-out hostname: allowed IP on /restricted → /", () => {+ const action = resolveIpRestrictionAction({+ route: hostnameRoute,+ page,+ pathname: "/restricted",+ clientIp: "10.0.0.5",+ origin: "http://acme.localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/");+ });++ test("allowed IP off /restricted: passes (null)", () => {+ expect(+ resolveIpRestrictionAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/en",+ clientIp: "10.0.0.5",+ origin: "http://localhost:3000",+ }),+ ).toBeNull();+ });++ test("disallowed IP on /restricted: passes (null — user already on gate)", () => {+ expect(+ resolveIpRestrictionAction({+ route: pathnameRoute,+ page,+ pathname: "/acme/restricted",+ clientIp: "1.2.3.4",+ origin: "http://localhost:3000",+ }),+ ).toBeNull();+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.ts b/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.tsnew file mode 100644index 000000000..ce24ca6ba--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.ts@@ -0,0 +1,51 @@+import type { Page } from "@openstatus/db/src/schema";+import { buildExternalPath } from "./build-external-path";+import { isIpAllowed } from "./is-ip-allowed";+import type { Action, ComposeInput } from "./types";++type Input = Pick<+ ComposeInput,+ "route" | "pathname" | "clientIp" | "origin"+> & {+ page: Pick<Page, "accessType" | "allowedIpRanges">;+};++/**+ * IP-restriction access control. Handles both gate-in (disallowed IP →+ * /restricted) and gate-out (allowed IP on /restricted → page root).+ *+ * Note on `endsWith("/restricted")`: deliberately loose; preserved from the+ * original middleware.+ */+export function resolveIpRestrictionAction({+ route,+ page,+ pathname,+ clientIp,+ origin,+}: Input): Action | null {+ if (page.accessType !== "ip-restriction") return null;++ const allowed = !!(clientIp && isIpAllowed(clientIp, page.allowedIpRanges));+ const isOnRestricted = pathname.endsWith("/restricted");++ // Gate-in: disallowed and not already on /restricted → send to /restricted+ if (!isOnRestricted && !allowed) {+ return {+ type: "redirect",+ url: new URL(`${origin}${buildExternalPath(route, "/restricted")}`),+ reason: "ip-restriction-gate-in",+ };+ }++ // Gate-out: allowed and on /restricted → send to page root+ if (isOnRestricted && allowed) {+ return {+ type: "redirect",+ url: new URL(`${origin}${buildExternalPath(route, "")}`),+ reason: "ip-restriction-gate-out",+ };+ }++ return null;+}diff --git a/apps/status-page/src/lib/proxy/resolve-locale-action.test.ts b/apps/status-page/src/lib/proxy/resolve-locale-action.test.tsnew file mode 100644index 000000000..582acf91e--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-locale-action.test.ts@@ -0,0 +1,128 @@+import { describe, expect, test } from "bun:test";+import type { ResolvedRoute } from "../resolve-route";+import { resolveLocaleAction } from "./resolve-locale-action";++const baseRoute: ResolvedRoute = {+ type: "pathname",+ prefix: "acme",+ locale: "fr",+ localeExplicit: true,+ rewritePath: "/acme/fr",+};++describe("resolveLocaleAction", () => {+ test("page has no locales list: passes (null)", () => {+ expect(+ resolveLocaleAction({+ route: baseRoute,+ page: { locales: null, defaultLocale: "en" },+ requestUrl: "http://localhost:3000/acme/fr",+ }),+ ).toBeNull();+ });++ test("page has empty locales list: passes (null)", () => {+ expect(+ resolveLocaleAction({+ route: baseRoute,+ page: { locales: [], defaultLocale: "en" },+ requestUrl: "http://localhost:3000/acme/fr",+ }),+ ).toBeNull();+ });++ test("route locale is in page's allowed list: passes (null)", () => {+ expect(+ resolveLocaleAction({+ route: baseRoute,+ page: { locales: ["en", "fr"], defaultLocale: "en" },+ requestUrl: "http://localhost:3000/acme/fr",+ }),+ ).toBeNull();+ });++ test("pathname routing: rejected locale → redirect to page default", () => {+ const action = resolveLocaleAction({+ route: baseRoute,+ page: { locales: ["en", "de"], defaultLocale: "en" },+ requestUrl: "http://localhost:3000/acme/fr",+ });+ expect(action).toEqual({+ type: "redirect",+ url: new URL("http://localhost:3000/acme/en"),+ reason: "locale-mismatch-redirect",+ });+ });++ test("pathname routing: rejected locale with sub-path → redirect preserves path", () => {+ const action = resolveLocaleAction({+ route: { ...baseRoute, rewritePath: "/acme/fr/events" },+ page: { locales: ["en"], defaultLocale: "en" },+ requestUrl: "http://localhost:3000/acme/fr/events",+ });+ expect(action?.url?.pathname).toBe("/acme/en/events");+ });++ test("hostname routing: rejected locale → redirect strips prefix", () => {+ const route: ResolvedRoute = {+ type: "hostname",+ prefix: "acme",+ locale: "fr",+ localeExplicit: true,+ rewritePath: "/acme/fr/events",+ };+ const action = resolveLocaleAction({+ route,+ page: { locales: ["en"], defaultLocale: "en" },+ requestUrl: "https://acme.localhost:3000/fr/events",+ });+ expect(action?.type).toBe("redirect");+ expect(action?.url?.pathname).toBe("/en/events");+ });++ test("missing page defaultLocale falls back to 'en'", () => {+ const action = resolveLocaleAction({+ route: baseRoute,+ page: { locales: ["en", "de"], defaultLocale: null as unknown as "en" },+ requestUrl: "http://localhost:3000/acme/fr",+ });+ expect(action?.url?.pathname).toBe("/acme/en");+ });++ test("hostname routing at root: rejected locale → redirect to '/'", () => {+ const route: ResolvedRoute = {+ type: "hostname",+ prefix: "acme",+ locale: "fr",+ localeExplicit: true,+ rewritePath: "/acme/fr",+ };+ const action = resolveLocaleAction({+ route,+ page: { locales: ["en"], defaultLocale: "en" },+ requestUrl: "https://acme.localhost:3000/fr",+ });+ expect(action?.reason).toBe("locale-mismatch-redirect");+ expect(action?.url?.pathname).toBe("/en");+ });++ test("reason is stable kebab-case", () => {+ const action = resolveLocaleAction({+ route: baseRoute,+ page: { locales: ["en"], defaultLocale: "en" },+ requestUrl: "http://localhost:3000/acme/fr",+ });+ expect(action?.reason).toBe("locale-mismatch-redirect");+ });++ test("rewritePath without expected /{prefix}/{locale} segment: passes (null)", () => {+ // Guards the invariant that `rewritePath` embeds the route's locale. If+ // it doesn't, `.replace()` would no-op and we'd redirect to the same URL.+ const action = resolveLocaleAction({+ route: { ...baseRoute, rewritePath: "/some/other/shape" },+ page: { locales: ["en"], defaultLocale: "en" },+ requestUrl: "http://localhost:3000/some/other/shape",+ });+ expect(action).toBeNull();+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-locale-action.ts b/apps/status-page/src/lib/proxy/resolve-locale-action.tsnew file mode 100644index 000000000..c22c92345--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-locale-action.ts@@ -0,0 +1,42 @@+import type { Page } from "@openstatus/db/src/schema";+import { stripPrefixForExternal } from "./strip-prefix-for-external";+import type { Action, ComposeInput } from "./types";++type Input = Pick<ComposeInput, "route" | "requestUrl"> & {+ page: Pick<Page, "locales" | "defaultLocale">;+};++/**+ * If the page restricts locales and the current route's locale isn't in that+ * list, redirect to the page's default locale. Assumes `route` has already been+ * normalised via applyPageLocaleOverride.+ */+export function resolveLocaleAction({+ route,+ page,+ requestUrl,+}: Input): Action | null {+ if (!page.locales || page.locales.length === 0) return null;+ if (page.locales.includes(route.locale)) return null;++ const pageDefault = page.defaultLocale || "en";+ const expectedSegment = `/${route.prefix}/${route.locale}`;+ // Invariant: `rewritePath` is constructed by `resolveRoute` with the+ // `/${prefix}/${locale}` segment. If that ever changes (e.g. a new route+ // shape that doesn't embed the locale), `.replace()` would no-op and we'd+ // redirect to the same URL — so bail out here rather than emit a redirect+ // that could loop.+ if (!route.rewritePath.includes(expectedSegment)) return null;+ const redirectPath = route.rewritePath.replace(+ expectedSegment,+ `/${route.prefix}/${pageDefault}`,+ );+ // For pathname routing, use the rewrite path directly;+ // for hostname routing, strip the prefix from the redirect URL+ const externalPath = stripPrefixForExternal(route, redirectPath);+ return {+ type: "redirect",+ url: new URL(externalPath || "/", requestUrl),+ reason: "locale-mismatch-redirect",+ };+}diff --git a/apps/status-page/src/lib/proxy/resolve-password-action.test.ts b/apps/status-page/src/lib/proxy/resolve-password-action.test.tsnew file mode 100644index 000000000..bfabf41a1--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-password-action.test.ts@@ -0,0 +1,303 @@+import { describe, expect, test } from "bun:test";+import type { ResolvedRoute } from "../resolve-route";+import { resolvePasswordAction } from "./resolve-password-action";++const pathnameRoute: ResolvedRoute = {+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++const hostnameRoute: ResolvedRoute = {+ type: "hostname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+};++const passwordPage = {+ slug: "acme",+ customDomain: "",+ password: "secret",+ accessType: "password" as const,+};++const customDomainPage = {+ slug: "acme",+ customDomain: "status.acme.com",+ password: "secret",+ accessType: "password" as const,+};++describe("resolvePasswordAction", () => {+ test("non-password page: passes (null)", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: { ...passwordPage, accessType: "public" as const },+ pathname: "/acme/en",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action).toBeNull();+ });++ test("gate-in pathname: wrong password, not on /login → redirect to /acme/login", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: passwordPage,+ pathname: "/acme/en",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.type).toBe("redirect");+ expect(action?.reason).toBe("password-gate-in");+ expect(action?.url?.pathname).toBe("/acme/login");+ expect(action?.url?.searchParams.get("redirect")).toBe("/acme/en");+ });++ test("gate-in hostname: wrong password, not on /login → redirect to /login (no prefix)", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: passwordPage,+ pathname: "/en",+ host: "acme.localhost:3000",+ isSelfHosted: false,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "http://acme.localhost:3000",+ });+ expect(action?.reason).toBe("password-gate-in");+ expect(action?.url?.pathname).toBe("/login");+ });++ test("gate-in custom-domain: redirects to https://{customDomain}/login", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: customDomainPage,+ pathname: "/status.acme.com/en",+ host: "status.acme.com",+ isSelfHosted: false,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("password-gate-in-custom-domain");+ expect(action?.url?.toString()).toBe(+ "https://status.acme.com/login?redirect=%2Fen",+ );+ });++ test("gate-in custom-domain: only leading customDomain segment is stripped", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: customDomainPage,+ pathname: "/status.acme.com/en/status.acme.com/nested",+ host: "status.acme.com",+ isSelfHosted: false,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.url?.searchParams.get("redirect")).toBe(+ "/en/status.acme.com/nested",+ );+ });++ test("gate-in custom-domain skipped in self-hosted", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: customDomainPage,+ pathname: "/acme/en",+ host: "status.acme.com",+ isSelfHosted: true,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "http://self.hosted",+ });+ expect(action?.reason).toBe("password-gate-in");+ expect(action?.url?.host).toBe("self.hosted");+ });++ test("gate-in custom-domain skipped when host is {slug}.stpg.dev", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: customDomainPage,+ pathname: "/en",+ host: "acme.stpg.dev",+ isSelfHosted: false,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "https://acme.stpg.dev",+ });+ expect(action?.reason).toBe("password-gate-in");+ expect(action?.url?.host).toBe("acme.stpg.dev");+ });++ test("cookie password matches: on /login → gate-out", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: passwordPage,+ pathname: "/acme/login",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("password-gate-out");+ expect(action?.type).toBe("redirect");+ });++ test("query password overrides cookie", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: passwordPage,+ pathname: "/acme/login",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: "wrong-cookie",+ queryPassword: "secret",+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("password-gate-out");+ });++ test("gate-out custom-domain: redirects to https://{customDomain}/", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: customDomainPage,+ pathname: "/status.acme.com/login",+ host: "status.acme.com",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.reason).toBe("password-gate-out-custom-domain");+ expect(action?.url?.toString()).toBe("https://status.acme.com/");+ });++ test("gate-out custom-domain: honours redirectParam", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: customDomainPage,+ pathname: "/status.acme.com/login",+ host: "status.acme.com",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: "/events",+ origin: "http://localhost:3000",+ });+ expect(action?.url?.toString()).toBe("https://status.acme.com/events");+ });++ test("gate-out pathname with redirectParam: honours the redirect target", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: passwordPage,+ pathname: "/acme/login",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: "/acme/en/events",+ origin: "http://localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/acme/en/events");+ });++ test("gate-out hostname with redirectParam: honours the redirect target", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: passwordPage,+ pathname: "/login",+ host: "acme.localhost:3000",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: "/en/events",+ origin: "http://acme.localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/en/events");+ });++ test("gate-out pathname, no redirectParam: → /acme", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: passwordPage,+ pathname: "/acme/login",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/acme");+ });++ test("gate-out hostname, no redirectParam: → /", () => {+ const action = resolvePasswordAction({+ route: hostnameRoute,+ page: passwordPage,+ pathname: "/login",+ host: "acme.localhost:3000",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: null,+ origin: "http://acme.localhost:3000",+ });+ expect(action?.url?.pathname).toBe("/");+ });++ test("wrong password on /login: passes (null) — user already on gate", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: passwordPage,+ pathname: "/acme/login",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: undefined,+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action).toBeNull();+ });++ test("correct password off /login: passes (null) — nothing to gate", () => {+ const action = resolvePasswordAction({+ route: pathnameRoute,+ page: passwordPage,+ pathname: "/acme/en",+ host: "localhost:3000",+ isSelfHosted: false,+ cookiePassword: "secret",+ queryPassword: null,+ redirectParam: null,+ origin: "http://localhost:3000",+ });+ expect(action).toBeNull();+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-password-action.ts b/apps/status-page/src/lib/proxy/resolve-password-action.tsnew file mode 100644index 000000000..b3812728f--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-password-action.ts@@ -0,0 +1,101 @@+import type { Page } from "@openstatus/db/src/schema";+import { buildExternalPath } from "./build-external-path";+import type { Action, ComposeInput } from "./types";++type Input = Pick<+ ComposeInput,+ | "route"+ | "pathname"+ | "host"+ | "isSelfHosted"+ | "cookiePassword"+ | "queryPassword"+ | "redirectParam"+ | "origin"+> & {+ page: Pick<Page, "slug" | "customDomain" | "password" | "accessType">;+};++/**+ * Password-protected page access control. Handles both gate-in (wrong password+ * → /login) and gate-out (correct password + on /login → page root), including+ * the custom-domain variants that redirect to `https://{customDomain}` instead+ * of the current host.+ *+ * Returns null if the page is not password-protected, or if the request is+ * already in the right state (authorised elsewhere, not on /login).+ *+ * Note on `endsWith("/login")`: deliberately loose — also matches+ * `/some-login`. Preserved from the original middleware; tighten to+ * last-segment equality in a follow-up if needed.+ */+export function resolvePasswordAction({+ route,+ page,+ pathname,+ host,+ isSelfHosted,+ cookiePassword,+ queryPassword,+ redirectParam,+ origin,+}: Input): Action | null {+ if (page.accessType !== "password") return null;++ // ?? rather than ||: an empty-string `?pw=` shouldn't silently fall through+ // to the cookie (the query param is "present, empty" — not absent).+ const password = queryPassword ?? cookiePassword;+ const isOnLogin = pathname.endsWith("/login");+ const needsCustomDomainRedirect =+ !isSelfHosted && !!page.customDomain && host !== `${page.slug}.stpg.dev`;++ // Gate-in: wrong password and not already on /login → send to login+ if (password !== page.password && !isOnLogin) {+ if (needsCustomDomainRedirect) {+ const leading = `/${page.customDomain}`;+ const redirect = pathname.startsWith(leading)+ ? pathname.slice(leading.length)+ : pathname;+ return {+ type: "redirect",+ url: new URL(+ `https://${page.customDomain}/login?redirect=${encodeURIComponent(redirect)}`,+ ),+ reason: "password-gate-in-custom-domain",+ };+ }+ return {+ type: "redirect",+ url: new URL(+ `${origin}${buildExternalPath(route, "/login")}?redirect=${encodeURIComponent(pathname)}`,+ ),+ reason: "password-gate-in",+ };+ }++ // Gate-out: correct password and on /login → send to page root+ if (password === page.password && isOnLogin) {+ if (needsCustomDomainRedirect) {+ return {+ type: "redirect",+ url: new URL(`https://${page.customDomain}${redirectParam ?? "/"}`),+ reason: "password-gate-out-custom-domain",+ };+ }+ // Parentheses matter: without them, `redirectParam ?? route.type === "pathname"`+ // binds first, making the ternary condition always truthy when `redirectParam`+ // is a non-null string — so the redirect param would be ignored.+ return {+ type: "redirect",+ url: new URL(+ `${origin}${+ redirectParam ??+ (route.type === "pathname" ? `/${route.prefix}` : "/")+ }`,+ ),+ reason: "password-gate-out",+ };+ }++ return null;+}diff --git a/apps/status-page/src/lib/proxy/sanitize-redirect-param.test.ts b/apps/status-page/src/lib/proxy/sanitize-redirect-param.test.tsnew file mode 100644index 000000000..c61ace1e2--- /dev/null+++ b/apps/status-page/src/lib/proxy/sanitize-redirect-param.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from "bun:test";+import { sanitizeRedirectParam } from "./sanitize-redirect-param";++describe("sanitizeRedirectParam", () => {+ test("null / empty → null", () => {+ expect(sanitizeRedirectParam(null)).toBeNull();+ expect(sanitizeRedirectParam("")).toBeNull();+ });++ test("absolute path → returned unchanged", () => {+ expect(sanitizeRedirectParam("/acme/en/events")).toBe("/acme/en/events");+ expect(sanitizeRedirectParam("/")).toBe("/");+ expect(sanitizeRedirectParam("/events?tab=open")).toBe("/events?tab=open");+ });++ test("non-path values → null (would throw in new URL)", () => {+ expect(sanitizeRedirectParam("http://evil.com")).toBeNull();+ expect(sanitizeRedirectParam("https://evil.com/path")).toBeNull();+ expect(sanitizeRedirectParam(":")).toBeNull();+ expect(sanitizeRedirectParam("events")).toBeNull();+ });++ test("protocol-relative paths → null", () => {+ expect(sanitizeRedirectParam("//evil.com")).toBeNull();+ expect(sanitizeRedirectParam("/\\evil.com")).toBeNull();+ });++ test("whitespace and control characters → null", () => {+ expect(sanitizeRedirectParam("/foo bar")).toBeNull();+ expect(sanitizeRedirectParam("/foo\nbar")).toBeNull();+ expect(sanitizeRedirectParam("/foo\tbar")).toBeNull();+ expect(sanitizeRedirectParam("/foo\x00bar")).toBeNull();+ });+});diff --git a/apps/status-page/src/lib/proxy/sanitize-redirect-param.ts b/apps/status-page/src/lib/proxy/sanitize-redirect-param.tsnew file mode 100644index 000000000..ca7e39649--- /dev/null+++ b/apps/status-page/src/lib/proxy/sanitize-redirect-param.ts@@ -0,0 +1,23 @@+/**+ * Validates a `?redirect=...` query value for use as a safe path suffix when+ * concatenated with an origin. Returns the value unchanged if it's a normal+ * absolute path, or null otherwise. Applied at the proxy input boundary so+ * every downstream resolver can trust the value.+ *+ * Rejects:+ * - missing/empty values+ * - values that don't start with `/` (e.g. `http://evil.com` — concatenating+ * these with an origin produces strings that throw in `new URL(...)` and+ * 500 the request)+ * - protocol-relative paths (`//…` or `/\…`, which URL parsers normalise to+ * a scheme-less authority and can escape the host)+ * - whitespace / control characters (which cause `new URL(...)` to throw or+ * get silently mangled across parsers)+ */+export function sanitizeRedirectParam(value: string | null): string | null {+ if (!value) return null;+ if (!value.startsWith("/")) return null;+ if (value.startsWith("//") || value.startsWith("/\\")) return null;+ if (/[\s\x00-\x1f]/.test(value)) return null;+ return value;+}diff --git a/apps/status-page/src/lib/proxy/strip-prefix-for-external.test.ts b/apps/status-page/src/lib/proxy/strip-prefix-for-external.test.tsnew file mode 100644index 000000000..0205e2f0c--- /dev/null+++ b/apps/status-page/src/lib/proxy/strip-prefix-for-external.test.ts@@ -0,0 +1,55 @@+import { describe, expect, test } from "bun:test";+import { stripPrefixForExternal } from "./strip-prefix-for-external";++describe("stripPrefixForExternal", () => {+ test("pathname routing: path unchanged", () => {+ expect(+ stripPrefixForExternal(+ { type: "pathname", prefix: "acme" },+ "/acme/en/events",+ ),+ ).toBe("/acme/en/events");+ });++ test("hostname routing: strips first occurrence of /prefix", () => {+ expect(+ stripPrefixForExternal(+ { type: "hostname", prefix: "acme" },+ "/acme/en/events",+ ),+ ).toBe("/en/events");+ });++ test("hostname routing: strips at root (no trailing segments)", () => {+ expect(+ stripPrefixForExternal({ type: "hostname", prefix: "acme" }, "/acme/en"),+ ).toBe("/en");+ });++ test("hostname routing: custom-domain prefix", () => {+ expect(+ stripPrefixForExternal(+ { type: "hostname", prefix: "status.acme.com" },+ "/status.acme.com/en",+ ),+ ).toBe("/en");+ });++ test("hostname routing: prefix recurs in deeper path — only the leading occurrence is stripped", () => {+ expect(+ stripPrefixForExternal(+ { type: "hostname", prefix: "acme" },+ "/acme/en/acme/more",+ ),+ ).toBe("/en/acme/more");+ });++ test("hostname routing: path does not start with /prefix → returned unchanged", () => {+ expect(+ stripPrefixForExternal(+ { type: "hostname", prefix: "acme" },+ "/other/en/acme",+ ),+ ).toBe("/other/en/acme");+ });+});diff --git a/apps/status-page/src/lib/proxy/strip-prefix-for-external.ts b/apps/status-page/src/lib/proxy/strip-prefix-for-external.tsnew file mode 100644index 000000000..14fce9366--- /dev/null+++ b/apps/status-page/src/lib/proxy/strip-prefix-for-external.ts@@ -0,0 +1,18 @@+import type { ResolvedRoute } from "../resolve-route";++/**+ * Inverse of buildExternalPath: strips the page prefix from an already-built+ * internal path when the page uses hostname routing. Used by the locale-mismatch+ * redirect, which starts from the internal rewrite path and needs to hand back+ * an external URL.+ */+export function stripPrefixForExternal(+ route: Pick<ResolvedRoute, "type" | "prefix">,+ internalPath: string,+): string {+ if (route.type !== "hostname") return internalPath;+ const leading = `/${route.prefix}`;+ return internalPath.startsWith(leading)+ ? internalPath.slice(leading.length)+ : internalPath;+}diff --git a/apps/status-page/src/lib/proxy/types.ts b/apps/status-page/src/lib/proxy/types.tsnew file mode 100644index 000000000..31931ce9f--- /dev/null+++ b/apps/status-page/src/lib/proxy/types.ts@@ -0,0 +1,64 @@+/**+ * Shared types for the proxy stage pipeline.+ *+ * Each stage is a pure function that inspects its inputs and returns an Action+ * (terminal decision for the middleware) or null (pass — let the next stage try).+ * The composer runs stages in priority order and returns the first non-null+ * Action, or a passthrough Action if all stages decline.+ */++import type { Page } from "@openstatus/db/src/schema";+import type { ResolvedRoute } from "../resolve-route";++export type ActionType = "rewrite" | "redirect" | "passthrough";++interface ActionBase {+ /** Kebab-case identifier of which branch produced this action. Used in logs and tests. */+ reason: string;+}++/**+ * Discriminated union: a `rewrite` or `redirect` is guaranteed to carry a URL;+ * a `passthrough` never does. Stages and callers rely on TypeScript narrowing+ * from the `type` tag — no runtime URL-presence checks needed in the+ * dispatcher. `rewrite` and `redirect` are kept as distinct variants so+ * narrowing stays precise when the two diverge (e.g. status codes, headers).+ */+export type Action =+ | (ActionBase & { type: "rewrite"; url: URL })+ | (ActionBase & { type: "redirect"; url: URL })+ | (ActionBase & { type: "passthrough"; url?: never });++/** Passthrough action shorthand. */+export const passthrough = (reason: string): Action => ({+ type: "passthrough",+ reason,+});++/**+ * Superset of every field read by any stage. proxy.ts assembles this once per+ * request; the composer passes it through to each stage. Individual stages+ * declare narrower input types and rely on structural subtyping.+ */+export interface ComposeInput {+ route: ResolvedRoute;+ page: Page;+ host: string | null;+ urlHost: string;+ pathname: string;+ search: string;+ isSelfHosted: boolean;+ requestUrl: string;+ origin: string;+ cookiePassword: string | undefined;+ queryPassword: string | null;+ /**+ * Pre-sanitized by `sanitizeRedirectParam` at the proxy boundary: either+ * `null`, or an absolute path starting with `/` (never `//` or `/\`) with+ * no whitespace/control chars. Downstream stages can concatenate it with+ * an origin without validating again.+ */+ redirectParam: string | null;+ authEmail: string | null | undefined;+ clientIp: string | null | undefined;+}diff --git a/apps/status-page/src/proxy.ts b/apps/status-page/src/proxy.tsindex ae1a10dbc..44bf9493e 100644--- a/apps/status-page/src/proxy.ts+++ b/apps/status-page/src/proxy.ts@@ -1,278 +1,98 @@-import IPCIDR from "ip-cidr";import { NextResponse } from "next/server";import { auth } from "@/lib/auth";import { db, sql } from "@openstatus/db";import { page, selectPageSchema } from "@openstatus/db/src/schema";-import { getValidSubdomain } from "./lib/domain";import { createProtectedCookieKey } from "./lib/protected";+import { applyPageLocaleOverride } from "./lib/proxy/apply-page-locale-override";+import { composePageAction } from "./lib/proxy/compose-page-action";+import { sanitizeRedirectParam } from "./lib/proxy/sanitize-redirect-param";import { resolveRoute } from "./lib/resolve-route";const isSelfHosted = process.env.SELF_HOST === "true";-function isIpAllowed(ip: string, allowedRanges: string[]): boolean {- // No ranges configured — deny all (defensive: form validation prevents this)- if (allowedRanges.length === 0) return false;- return allowedRanges.some((range) => {- try {- const cidr = new IPCIDR(range);- return cidr.contains(ip);- } catch {- // Skip malformed ranges rather than crashing the middleware- return false;- }- });-}-export default auth(async (req) => {const url = req.nextUrl.clone();- const response = NextResponse.next();- const cookies = req.cookies;- const headers = req.headers;- const host = headers.get("x-forwarded-host");+ const passthroughResponse = NextResponse.next();+ const host = req.headers.get("x-forwarded-host");- const route = resolveRoute({+ const initialRoute = resolveRoute({host,urlHost: url.host,pathname: url.pathname,});- if (!route) {- return response;+ if (!initialRoute) {+ return passthroughResponse;}- const { type, prefix } = route;-const query = await db.select().from(page).where(- sql`lower(${page.slug}) = ${prefix} OR lower(${page.customDomain}) = ${prefix}`,+ sql`lower(${page.slug}) = ${initialRoute.prefix} OR lower(${page.customDomain}) = ${initialRoute.prefix}`,).get();const validation = selectPageSchema.safeParse(query);if (!validation.success) {- return response;+ return passthroughResponse;}const _page = validation.data;+ const route = applyPageLocaleOverride(initialRoute, _page);- // Override locale with the page's default when no explicit locale was in the URL- if (- !route.localeExplicit &&- _page.defaultLocale &&- _page.defaultLocale !== route.locale- ) {- const oldLocale = route.locale;- route.locale = _page.defaultLocale;- route.rewritePath = route.rewritePath.replace(- `/${route.prefix}/${oldLocale}`,- `/${route.prefix}/${_page.defaultLocale}`,- );- }-- // Reject locales not in the page's allowed list — redirect to the page's default locale- if (- _page.locales &&- _page.locales.length > 0 &&- !_page.locales.includes(route.locale)- ) {- const pageDefault = _page.defaultLocale || "en";- const redirectPath = route.rewritePath.replace(- `/${route.prefix}/${route.locale}`,- `/${route.prefix}/${pageDefault}`,- );- // For pathname routing, redirect to the rewrite path directly;- // for hostname routing, strip the prefix from the redirect URL- const externalPath =- route.type === "hostname"- ? redirectPath.replace(`/${route.prefix}`, "")- : redirectPath;- return NextResponse.redirect(new URL(externalPath || "/", req.url));- }-- console.log({ slug: _page?.slug, customDomain: _page?.customDomain });-- if (_page?.accessType === "password") {- const protectedCookie = cookies.get(createProtectedCookieKey(_page.slug));- const cookiePassword = protectedCookie ? protectedCookie.value : undefined;- const queryPassword = url.searchParams.get("pw");- const password = queryPassword || cookiePassword;-- if (password !== _page.password && !url.pathname.endsWith("/login")) {- const { pathname, origin } = req.nextUrl;-- // custom domain redirect- if (- !isSelfHosted &&- _page.customDomain &&- host !== `${_page.slug}.stpg.dev`- ) {- const redirect = pathname.replace(`/${_page.customDomain}`, "");- const url = new URL(- `https://${_page.customDomain}/login?redirect=${encodeURIComponent(- redirect,- )}`,- );- console.log("redirect to /login", url.toString());- return NextResponse.redirect(url);- }-- const url = new URL(- `${origin}${- type === "pathname" ? `/${prefix}` : ""- }/login?redirect=${encodeURIComponent(pathname)}`,- );- return NextResponse.redirect(url);- }- if (password === _page.password && url.pathname.endsWith("/login")) {- const redirect = url.searchParams.get("redirect");-- // custom domain redirect- if (- !isSelfHosted &&- _page.customDomain &&- host !== `${_page.slug}.stpg.dev`- ) {- const url = new URL(`https://${_page.customDomain}${redirect ?? "/"}`);- console.log("redirect to /", url.toString());- return NextResponse.redirect(url);- }-- return NextResponse.redirect(- new URL(- `${req.nextUrl.origin}${- redirect ?? type === "pathname" ? `/${prefix}` : "/"- }`,- ),- );- }- }-- if (_page.accessType === "email-domain") {- const { origin, pathname } = req.nextUrl;- const email = req.auth?.user?.email;- const emailDomain = email?.split("@")[1];- if (- !pathname.endsWith("/login") &&- (!emailDomain || !_page.authEmailDomains.includes(emailDomain))- ) {- const url = new URL(- `${origin}${type === "pathname" ? `/${prefix}` : ""}/login`,- );- return NextResponse.redirect(url);- }- if (- pathname.endsWith("/login") &&- emailDomain &&- _page.authEmailDomains.includes(emailDomain)- ) {- const url = new URL(- `${origin}${type === "pathname" ? `/${prefix}` : ""}`,- );- return NextResponse.redirect(url);- }- }-- if (_page.accessType === "ip-restriction") {- // Vercel overwrites x-forwarded-for with the verified client IP — not spoofable.- // https://vercel.com/docs/headers/request-headers#x-forwarded-for- const xff = req.headers.get("x-forwarded-for");- const clientIp = xff?.split(",")[0]?.trim() ?? req.headers.get("x-real-ip");-- const allowed = clientIp && isIpAllowed(clientIp, _page.allowedIpRanges);-- if (!url.pathname.endsWith("/restricted") && !allowed) {- const { origin } = req.nextUrl;- const redirectUrl = new URL(- `${origin}${type === "pathname" ? `/${prefix}` : ""}/restricted`,- );- return NextResponse.redirect(redirectUrl);- }-- // Redirect allowed IPs away from /restricted- if (url.pathname.endsWith("/restricted") && allowed) {- const { origin } = req.nextUrl;- const redirectUrl = new URL(- `${origin}${type === "pathname" ? `/${prefix}` : ""}`,- );- return NextResponse.redirect(redirectUrl);- }- }-- const proxy = req.headers.get("x-proxy");- console.log({ proxy });+ // Vercel overwrites x-forwarded-for with the verified client IP — not spoofable.+ // https://vercel.com/docs/headers/request-headers#x-forwarded-for+ const xff = req.headers.get("x-forwarded-for");+ const clientIp = xff?.split(",")[0]?.trim() ?? req.headers.get("x-real-ip");- if (proxy) {- const rewriteUrl = new URL(`/${prefix}${url.pathname}`, req.url);- // Preserve search params from original request- rewriteUrl.search = url.search;- return NextResponse.rewrite(rewriteUrl);- }+ console.log("[proxy] request", {+ host,+ pathname: url.pathname,+ slug: _page.slug,+ customDomain: _page.customDomain || null,+ accessType: _page.accessType,+ route,+ authEmailPresent: !!req.auth?.user?.email,+ clientIp: clientIp ?? null,+ isSelfHosted,+ });- console.log({- customDomain: _page.customDomain,+ const action = composePageAction({+ route,+ page: _page,host,- expectedHost: isSelfHosted- ? "(self-hosted mode)"- : `${_page.slug}.stpg.dev`,+ urlHost: url.host,+ pathname: url.pathname,+ search: url.search,+ isSelfHosted,+ requestUrl: req.url,+ origin: req.nextUrl.origin,+ cookiePassword: req.cookies.get(createProtectedCookieKey(_page.slug))+ ?.value,+ queryPassword: url.searchParams.get("pw"),+ redirectParam: sanitizeRedirectParam(url.searchParams.get("redirect")),+ authEmail: req.auth?.user?.email,+ clientIp,});- // stpg.dev-specific rewrite — skipped in self-hosted deployments- if (- !isSelfHosted &&- _page.customDomain &&- host !== `${_page.slug}.stpg.dev`- ) {- const pathnames = url.pathname.split("/");- const subdomain = getValidSubdomain(url.host);- if (pathnames.length > 2 && !subdomain) {- const pathname = pathnames.slice(2).join("/");- const rewriteUrl = new URL(`/${_page.slug}/${pathname}`, req.url);- rewriteUrl.search = url.search;- return NextResponse.rewrite(rewriteUrl);- }- if (_page.customDomain && subdomain) {- console.log({ url: req.url });- if (pathnames.length > 2) {- const pathname = pathnames.slice(1).join("/");- const rewriteUrl = new URL(- `${pathname}`,- `https://${_page.slug}.stpg.dev`,- );- rewriteUrl.search = url.search;- return NextResponse.rewrite(rewriteUrl);- }- const rewriteUrl = new URL(- `${url.pathname}`,- `https://${_page.slug}.stpg.dev`,- );- rewriteUrl.search = url.search;- return NextResponse.rewrite(rewriteUrl);- }- const rewriteUrl = new URL(`/${_page.slug}`, req.url);- rewriteUrl.search = url.search;- return NextResponse.rewrite(rewriteUrl);- }- if (host?.includes("openstatus.dev")) {- const rewriteUrl = new URL(route.rewritePath, req.url);- // Preserve search params from original request- rewriteUrl.search = url.search;- return NextResponse.rewrite(rewriteUrl);- }+ console.log("[proxy] action", {+ type: action.type,+ reason: action.reason,+ url: action.url?.toString() ?? null,+ });- // Rewrite to the resolved path when it differs from the incoming pathname- // (e.g. hostname routing or pathname routing without a locale segment)- if (route.rewritePath !== url.pathname) {- const rewriteUrl = new URL(route.rewritePath, req.url);- rewriteUrl.search = url.search;- return NextResponse.rewrite(rewriteUrl);+ switch (action.type) {+ case "redirect":+ return NextResponse.redirect(action.url);+ case "rewrite":+ return NextResponse.rewrite(action.url);+ case "passthrough":+ return passthroughResponse;}-- return response;});export const config = {