Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
fix: theme-explorer-host-gate (#2592)
Maximilian Kaskee95f832482d2
diff --git a/apps/status-page/AGENTS.md b/apps/status-page/AGENTS.mdindex c9d0191bc..101768148 100644--- a/apps/status-page/AGENTS.md+++ b/apps/status-page/AGENTS.md@@ -37,3 +37,21 @@ a theme in that package; do not hard-code colours in a component.Status-page impact labels are coloured text only — no dots, no chevrons. Thehover affordance is a dashed muted underline, never one tinted with the impactcolour.++## Theme explorer++`/` renders the theme explorer, and it is also where any request resolving to+no `page` row ends up. The proxy rewrites those to a 404+(`resolveUnresolvedHostAction`) so an unknown slug or a custom domain missing+from the DB never answers with the explorer or its OG image. Only+`themes.openstatus.dev` is indexable — see `lib/theme-explorer-host.ts`.++<!-- BEGIN:nextjs-agent-rules -->++# This is NOT the Next.js you know++This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.++This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.++<!-- END:nextjs-agent-rules -->diff --git a/apps/status-page/src/app/(public)/layout.tsx b/apps/status-page/src/app/(public)/layout.tsxindex 68c079858..6949cc483 100644--- a/apps/status-page/src/app/(public)/layout.tsx+++ b/apps/status-page/src/app/(public)/layout.tsx@@ -4,8 +4,11 @@ import {SidebarProvider,} from "@openstatus/ui/components/ui/sidebar";import { Toaster } from "@openstatus/ui/components/ui/sonner";+import type { Metadata } from "next";import { NextIntlClientProvider } from "next-intl";import PlausibleProvider from "next-plausible";+import { headers } from "next/headers";+import { notFound } from "next/navigation";import { Suspense } from "react";import { Link } from "../../components/common/link";@@ -14,15 +17,39 @@ import {SidebarTrigger,ThemeSidebar,} from "../../components/themes/theme-sidebar";+import {+ isCanonicalThemeExplorerHost,+ isThemeExplorerHost,+} from "../../lib/theme-explorer-host";+import { themeExplorerMetadata } from "../metadata";const SIDEBAR_WIDTH = "20rem";const SIDEBAR_WIDTH_MOBILE = "18rem";+async function requestHost() {+ const headerStore = await headers();+ return headerStore.get("x-forwarded-host") ?? headerStore.get("host");+}++export async function generateMetadata(): Promise<Metadata> {+ const host = await requestHost();+ // Same gate as the layout: metadata is resolved alongside the render, so the+ // explorer's OG image would otherwise ship with the 404.+ if (!isThemeExplorerHost(host)) notFound();+ return themeExplorerMetadata({+ indexable: isCanonicalThemeExplorerHost(host),+ });+}+export default async function Layout({children,}: {children: React.ReactNode;}) {+ // `/` is the fallthrough for every host that resolves to no page, so keep the+ // explorer off unknown slugs and unconfigured custom domains.+ if (!isThemeExplorerHost(await requestHost())) notFound();+const locale = "en";const messages = (await import(`../../../messages/${locale}.json`)).default;diff --git a/apps/status-page/src/app/layout.tsx b/apps/status-page/src/app/layout.tsxindex bc1a2aec1..78cbbff01 100644--- a/apps/status-page/src/app/layout.tsx+++ b/apps/status-page/src/app/layout.tsx@@ -8,7 +8,6 @@ import { NuqsAdapter } from "nuqs/adapters/next/app";import { TailwindIndicator } from "../components/tailwind-indicator";import { TRPCReactProvider } from "../lib/trpc/client";-import { ogMetadata, twitterMetadata } from "./metadata";import { defaultMetadata } from "./metadata";const cal = LocalFont({@@ -52,15 +51,7 @@ const commitMono = LocalFont({variable: "--font-commit-mono",});-export const metadata: Metadata = {- ...defaultMetadata,- twitter: {- ...twitterMetadata,- },- openGraph: {- ...ogMetadata,- },-};+export const metadata: Metadata = defaultMetadata;// export const dynamic = "error";diff --git a/apps/status-page/src/app/metadata.ts b/apps/status-page/src/app/metadata.tsindex d90e4198a..2f2205251 100644--- a/apps/status-page/src/app/metadata.ts+++ b/apps/status-page/src/app/metadata.ts@@ -1,5 +1,7 @@import type { Metadata } from "next";+import { THEME_EXPLORER_URL } from "../lib/theme-explorer-host";+export const TITLE = "Status Page";export const DESCRIPTION ="Status page customization with built-in themes. Explore all themes and contribute your own theme.";@@ -9,6 +11,7 @@ const OG_DESCRIPTION ="Explore all themes for your status page and contribute new ones to the community.";const FOOTER = "themes.openstatus.dev";const IMAGE = "assets/og/theme-explorer.png";+const THEME_EXPLORER_IMAGE = `/api/og?title=${OG_TITLE}&description=${OG_DESCRIPTION}&footer=${FOOTER}&image=${IMAGE}`;export const defaultMetadata: Metadata = {title: {@@ -18,22 +21,38 @@ export const defaultMetadata: Metadata = {icons: "https://www.openstatus.dev/favicon.ico",description: DESCRIPTION,metadataBase: new URL("https://www.openstatus.dev"),+ // Unresolved hosts render the 404 off this layout — keep them out of the+ // index. Status pages and the theme explorer set their own `robots`.+ robots: { index: false, follow: false },};export const twitterMetadata: Metadata["twitter"] = {title: TITLE,description: DESCRIPTION,card: "summary_large_image",- images: [- `/api/og?title=${OG_TITLE}&description=${OG_DESCRIPTION}&footer=${FOOTER}&image=${IMAGE}`,- ],};export const ogMetadata: Metadata["openGraph"] = {title: TITLE,description: DESCRIPTION,type: "website",- images: [- `/api/og?title=${OG_TITLE}&description=${OG_DESCRIPTION}&footer=${FOOTER}&image=${IMAGE}`,- ],};++/**+ * Theme explorer only — the OG image must never be inherited by a status page+ * or by the 404 an unresolved host lands on.+ */+export function themeExplorerMetadata({+ indexable,+}: {+ indexable: boolean;+}): Metadata {+ return {+ alternates: { canonical: THEME_EXPLORER_URL },+ robots: indexable+ ? { index: true, follow: true }+ : { index: false, follow: false },+ twitter: { ...twitterMetadata, images: [THEME_EXPLORER_IMAGE] },+ openGraph: { ...ogMetadata, images: [THEME_EXPLORER_IMAGE] },+ };+}diff --git a/apps/status-page/src/app/robots.ts b/apps/status-page/src/app/robots.tsindex 9b1d57a80..fcc4d1815 100644--- a/apps/status-page/src/app/robots.ts+++ b/apps/status-page/src/app/robots.ts@@ -6,6 +6,7 @@ import { headers } from "next/headers";import { getBaseUrl } from "../lib/base-url";import { stripHostPort } from "../lib/domain";import { resolveRoute } from "../lib/resolve-route";+import { isCanonicalThemeExplorerHost } from "../lib/theme-explorer-host";// trpc/db lookup needs Node, matching the sitemap and other content routes.export const runtime = "nodejs";@@ -51,6 +52,13 @@ export default async function robots(): Promise<MetadataRoute.Robots> {};}+ // No page for this host: `/` falls through to the theme explorer, which only+ // belongs in the index on its own host. Matches the `robots` the explorer+ // itself emits — every other host that renders it is noindex.+ if (!row && !isCanonicalThemeExplorerHost(host)) {+ return { rules: [{ userAgent: "*", disallow: "/" }] };+ }+const sitemap = row? `${getBaseUrl({ slug: row.slug, customDomain: row.customDomain ?? undefined })}/sitemap.xml`: undefined;diff --git a/apps/status-page/src/lib/domain.test.ts b/apps/status-page/src/lib/domain.test.tsnew file mode 100644index 000000000..7483aca24--- /dev/null+++ b/apps/status-page/src/lib/domain.test.ts@@ -0,0 +1,128 @@+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import { getValidSubdomain, stripHostPort } from "./domain";++describe("stripHostPort", () => {+ test("drops the port", () => {+ expect(stripHostPort("status.acme.com:8080")).toBe("status.acme.com");+ expect(stripHostPort("localhost:3000")).toBe("localhost");+ });++ test("leaves a portless host untouched", () => {+ expect(stripHostPort("status.acme.com")).toBe("status.acme.com");+ });++ test("does not normalise case — callers lowercase themselves", () => {+ expect(stripHostPort("Status.Acme.COM")).toBe("Status.Acme.COM");+ });++ test("passes null/undefined through", () => {+ expect(stripHostPort(null)).toBe(null);+ expect(stripHostPort(undefined)).toBe(null);+ expect(stripHostPort("")).toBe("");+ });++ test("a bare IPv6 literal is mangled: the trailing `:1` reads as a port", () => {+ // Hosts arrive bracketed (`[::1]:3000`) from real clients, so this only+ // shows up in hand-built values.+ expect(stripHostPort("::1")).toBe(":");+ });+});++describe("getValidSubdomain", () => {+ describe("openstatus.dev / stpg.dev hosts", () => {+ test("tenant subdomain → the slug", () => {+ expect(getValidSubdomain("acme.openstatus.dev")).toBe("acme");+ expect(getValidSubdomain("acme.stpg.dev")).toBe("acme");+ });++ test("`www.` is not a tenant", () => {+ expect(getValidSubdomain("www.openstatus.dev")).toBe(null);+ expect(getValidSubdomain("www.stpg.dev")).toBe(null);+ });++ test("the theme explorer host resolves like any other subdomain", () => {+ // No `page` row matches "themes", so the proxy passes through to `/`.+ expect(getValidSubdomain("themes.openstatus.dev")).toBe("themes");+ });++ test("apex openstatus.dev reads its own first label as the slug", () => {+ expect(getValidSubdomain("openstatus.dev")).toBe("openstatus");+ });+ });++ describe("localhost", () => {+ test("bare localhost is not a tenant (path routing in dev)", () => {+ expect(getValidSubdomain("localhost")).toBe(null);+ expect(getValidSubdomain("localhost:3000")).toBe(null);+ });++ test("subdomain of localhost → the slug, port stripped", () => {+ expect(getValidSubdomain("acme.localhost:3000")).toBe("acme");+ expect(getValidSubdomain("acme.localhost")).toBe("acme");+ });+ });++ describe("vercel deployments", () => {+ test("*.vercel.app is never a tenant", () => {+ expect(getValidSubdomain("status-page-abc123.vercel.app")).toBe(null);+ expect(getValidSubdomain("status-page-git-main-os.vercel.app")).toBe(+ null,+ );+ });+ });++ describe("custom domains", () => {+ test("the whole host is the lookup key, not its first label", () => {+ expect(getValidSubdomain("status.acme.com")).toBe("status.acme.com");+ expect(getValidSubdomain("acme.com")).toBe("acme.com");+ expect(getValidSubdomain("acme.co.uk")).toBe("acme.co.uk");+ });++ test("`www.` custom domains are kept whole", () => {+ expect(getValidSubdomain("www.acme.com")).toBe("www.acme.com");+ });++ test("no host at all → no tenant", () => {+ expect(getValidSubdomain(null)).toBe(null);+ expect(getValidSubdomain(undefined)).toBe(null);+ expect(getValidSubdomain("")).toBe(null);+ });+ });++ describe("known gaps — pinned so a fix is a deliberate change", () => {+ test("a look-alike host matches by substring and yields the tenant slug", () => {+ // `host.includes("openstatus.dev")` is a substring test, so an attacker+ // domain ending in `.evil.com` still resolves to tenant `acme`. Reaching+ // this needs the domain attached to the deployment, which Vercel refuses+ // without domain verification — hence pinned, not treated as live.+ expect(getValidSubdomain("acme.openstatus.dev.evil.com")).toBe("acme");+ });++ test("an uppercase Host is read as a custom domain", () => {+ // The `.includes()` guards are case-sensitive, so the whole host becomes+ // the lookup key and no `page` row matches → a valid page 404s. Browsers+ // send lowercase hosts, so this needs a hand-built request.+ expect(getValidSubdomain("ACME.OPENSTATUS.DEV")).toBe(+ "ACME.OPENSTATUS.DEV",+ );+ });++ test("a custom domain keeps its port, which never matches page.customDomain", () => {+ // `page.customDomain` is stored without a port and `stripHostPort` is+ // never applied on this path. Only reachable in local dev.+ expect(getValidSubdomain("status.acme.com:8080")).toBe(+ "status.acme.com:8080",+ );+ });++ test("IP hosts are not excluded — the exclusion regex is double-escaped", () => {+ // `/^(localhost|127\\.0\\.0\\.1|...)/` matches literal backslashes, so+ // every alternative but `localhost` is inert and an IP host is treated as+ // a custom domain.+ expect(getValidSubdomain("127.0.0.1:3000")).toBe("127.0.0.1:3000");+ expect(getValidSubdomain("192.168.1.10")).toBe("192.168.1.10");+ });+ });+});diff --git a/apps/status-page/src/lib/proxy/access-predicates.test.ts b/apps/status-page/src/lib/proxy/access-predicates.test.tsnew file mode 100644index 000000000..e5d7bb223--- /dev/null+++ b/apps/status-page/src/lib/proxy/access-predicates.test.ts@@ -0,0 +1,198 @@+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import {+ isEmailDomainAuthorized,+ isIpAuthorized,+ isPasswordAuthorized,+} from "./access-predicates";++describe("isPasswordAuthorized", () => {+ test("matching cookie authorizes", () => {+ expect(+ isPasswordAuthorized({+ stored: "s3cret",+ queryPassword: null,+ cookiePassword: "s3cret",+ }),+ ).toBe(true);+ });++ test("matching query param authorizes", () => {+ expect(+ isPasswordAuthorized({+ stored: "s3cret",+ queryPassword: "s3cret",+ cookiePassword: null,+ }),+ ).toBe(true);+ });++ test("a wrong query param does not fall through to a valid cookie", () => {+ expect(+ isPasswordAuthorized({+ stored: "s3cret",+ queryPassword: "nope",+ cookiePassword: "s3cret",+ }),+ ).toBe(false);+ });++ test("an empty query param counts as submitted and loses", () => {+ expect(+ isPasswordAuthorized({+ stored: "s3cret",+ queryPassword: "",+ cookiePassword: "s3cret",+ }),+ ).toBe(false);+ });++ test("an absent query param defers to the cookie", () => {+ expect(+ isPasswordAuthorized({+ stored: "s3cret",+ queryPassword: undefined,+ cookiePassword: "s3cret",+ }),+ ).toBe(true);+ });++ test("no stored password never authorizes, whatever is submitted", () => {+ for (const stored of [null, undefined, ""]) {+ expect(+ isPasswordAuthorized({+ stored,+ queryPassword: "",+ cookiePassword: "",+ }),+ ).toBe(false);+ expect(+ isPasswordAuthorized({+ stored,+ queryPassword: "anything",+ cookiePassword: null,+ }),+ ).toBe(false);+ }+ });++ test("nothing submitted → denied", () => {+ expect(+ isPasswordAuthorized({+ stored: "s3cret",+ queryPassword: null,+ cookiePassword: undefined,+ }),+ ).toBe(false);+ });++ test("comparison is exact: case, whitespace, prefixes and length all count", () => {+ const deny = (submitted: string) =>+ isPasswordAuthorized({+ stored: "s3cret",+ queryPassword: submitted,+ cookiePassword: null,+ });+ expect(deny("S3CRET")).toBe(false);+ expect(deny(" s3cret")).toBe(false);+ expect(deny("s3cret ")).toBe(false);+ expect(deny("s3cre")).toBe(false);+ expect(deny("s3cretx")).toBe(false);+ expect(deny("")).toBe(false);+ });++ test("non-ASCII passwords compare by code unit", () => {+ expect(+ isPasswordAuthorized({+ stored: "pässwörd✅",+ queryPassword: "pässwörd✅",+ cookiePassword: null,+ }),+ ).toBe(true);+ expect(+ isPasswordAuthorized({+ stored: "pässwörd✅",+ queryPassword: "passwörd✅",+ cookiePassword: null,+ }),+ ).toBe(false);+ });+});++describe("isEmailDomainAuthorized", () => {+ test("domain in the allow-list authorizes", () => {+ expect(isEmailDomainAuthorized("[email protected]", ["acme.com"])).toBe(true);+ });++ test("matching is case-insensitive on both sides", () => {+ expect(isEmailDomainAuthorized("[email protected]", ["acme.com"])).toBe(true);+ expect(isEmailDomainAuthorized("[email protected]", ["ACME.COM"])).toBe(true);+ });++ test("a subdomain of an allowed domain is not allowed", () => {+ expect(isEmailDomainAuthorized("[email protected]", ["acme.com"])).toBe(+ false,+ );+ });++ test("a suffix look-alike is not allowed", () => {+ expect(isEmailDomainAuthorized("[email protected]", ["acme.com"])).toBe(+ false,+ );+ expect(isEmailDomainAuthorized("[email protected]", ["acme.com"])).toBe(+ false,+ );+ });++ test("empty or missing allow-list denies", () => {+ expect(isEmailDomainAuthorized("[email protected]", [])).toBe(false);+ expect(isEmailDomainAuthorized("[email protected]", null)).toBe(false);+ expect(isEmailDomainAuthorized("[email protected]", undefined)).toBe(false);+ });++ test("no session email denies", () => {+ expect(isEmailDomainAuthorized(null, ["acme.com"])).toBe(false);+ expect(isEmailDomainAuthorized(undefined, ["acme.com"])).toBe(false);+ expect(isEmailDomainAuthorized("", ["acme.com"])).toBe(false);+ });++ test("an address without a domain denies", () => {+ expect(isEmailDomainAuthorized("dev", ["acme.com"])).toBe(false);+ expect(isEmailDomainAuthorized("dev@", ["acme.com"])).toBe(false);+ });++ test("only the first domain of a multi-@ address is read", () => {+ // `split("@")[1]` — "a@[email protected]" checks "b", not "acme.com".+ expect(isEmailDomainAuthorized("a@[email protected]", ["acme.com"])).toBe(false);+ expect(isEmailDomainAuthorized("[email protected]@b", ["acme.com"])).toBe(true);+ });+});++describe("isIpAuthorized", () => {+ test("IP inside an allowed range authorizes", () => {+ expect(isIpAuthorized("192.168.1.42", ["192.168.1.0/24"])).toBe(true);+ });++ test("IP outside every range denies", () => {+ expect(isIpAuthorized("10.0.0.1", ["192.168.1.0/24"])).toBe(false);+ });++ test("no ranges configured denies (fail closed)", () => {+ expect(isIpAuthorized("192.168.1.42", [])).toBe(false);+ expect(isIpAuthorized("192.168.1.42", null)).toBe(false);+ expect(isIpAuthorized("192.168.1.42", undefined)).toBe(false);+ });++ test("no client IP denies (fail closed)", () => {+ expect(isIpAuthorized(null, ["0.0.0.0/0"])).toBe(false);+ expect(isIpAuthorized(undefined, ["0.0.0.0/0"])).toBe(false);+ expect(isIpAuthorized("", ["0.0.0.0/0"])).toBe(false);+ });++ test("a malformed range is skipped, the rest still evaluated", () => {+ expect(+ isIpAuthorized("192.168.1.42", ["not-a-cidr", "192.168.1.0/24"]),+ ).toBe(true);+ });+});diff --git a/apps/status-page/src/lib/proxy/proxy-chain.test.ts b/apps/status-page/src/lib/proxy/proxy-chain.test.tsnew file mode 100644index 000000000..8090223c1--- /dev/null+++ b/apps/status-page/src/lib/proxy/proxy-chain.test.ts@@ -0,0 +1,319 @@+import type { Page } from "@openstatus/db/src/schema";+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import { resolveRoute } from "../resolve-route";+import { applyPageLocaleOverride } from "./apply-page-locale-override";+import { applyPageSlugPrefix } from "./apply-page-slug-prefix";+import { composePageAction } from "./compose-page-action";+import type { Action } from "./types";++/**+ * Integration cover for the exact sequence `proxy.ts` runs after its DB lookup:+ * resolveRoute → applyPageLocaleOverride → applyPageSlugPrefix →+ * composePageAction. The stages are unit-tested individually; this pins how+ * they compose for a real host + path + page row.+ */++const ORIGIN = "https://www.stpg.dev";++function buildPage(overrides: Partial<Page> = {}): Page {+ return {+ 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,+ ...overrides,+ } as unknown as Page;+}++/** Mirrors proxy.ts for a request the DB lookup resolved to `page`. */+function runProxy({+ host,+ pathname,+ search = "",+ page = buildPage(),+ isSelfHosted = false,+ cookiePassword,+ queryPassword = null,+ redirectParam = null,+ authEmail = null,+ clientIp = null,+ urlHost = "www.stpg.dev",+}: {+ host: string;+ pathname: string;+ search?: string;+ page?: Page;+ isSelfHosted?: boolean;+ cookiePassword?: string;+ queryPassword?: string | null;+ redirectParam?: string | null;+ authEmail?: string | null;+ clientIp?: string | null;+ urlHost?: string;+}): { action: Action; rewritePath: string } {+ const initialRoute = resolveRoute({ host, urlHost, pathname });+ if (!initialRoute) throw new Error("route did not resolve");++ const route = applyPageSlugPrefix(+ applyPageLocaleOverride(initialRoute, page),+ page,+ );++ const action = composePageAction({+ route,+ page,+ host,+ urlHost,+ pathname,+ search,+ isSelfHosted,+ requestUrl: `${ORIGIN}${pathname}${search}`,+ origin: ORIGIN,+ cookiePassword,+ queryPassword,+ redirectParam,+ authEmail,+ clientIp,+ });++ return { action, rewritePath: route.rewritePath };+}++describe("proxy chain — public pages", () => {+ test("subdomain host rewrites to the slug-prefixed internal path", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/events",+ });+ expect(action.type).toBe("rewrite");+ expect(action.url?.pathname).toBe("/acme/en/events");+ });++ test("custom domain swaps the domain prefix for the slug", () => {+ // resolveRoute keys custom domains by the full host; the `[domain]` segment+ // must still be the slug — the login cookie key is derived from it.+ const { action } = runProxy({+ host: "status.acme.com",+ pathname: "/monitors/1",+ page: buildPage({ customDomain: "status.acme.com" }),+ });+ expect(action.type).toBe("rewrite");+ expect(action.url?.pathname).toBe("/acme/en/monitors/1");+ });++ test("apps/web proxy shape: host repeated as the first path segment", () => {+ const { action } = runProxy({+ host: "status.acme.com",+ pathname: "/status.acme.com/events/report/1",+ page: buildPage({ customDomain: "status.acme.com" }),+ });+ expect(action.type).toBe("rewrite");+ expect(action.url?.pathname).toBe("/acme/en/events/report/1");+ });++ test("path routing (local dev) rewrites in place", () => {+ const { action } = runProxy({+ host: "localhost:3000",+ urlHost: "localhost:3000",+ pathname: "/acme/events",+ });+ expect(action.type).toBe("rewrite");+ expect(action.url?.pathname).toBe("/acme/en/events");+ });++ test("search params survive the rewrite", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/monitors/1",+ search: "?period=7d®ion=ams",+ });+ expect(action.url?.search).toBe("?period=7d®ion=ams");+ });+});++describe("proxy chain — locale", () => {+ test("no locale in the URL adopts the page default", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/events",+ page: buildPage({ defaultLocale: "fr" }),+ });+ expect(action.url?.pathname).toBe("/acme/fr/events");+ });++ test("an explicit locale wins over the page default", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/en/events",+ page: buildPage({ defaultLocale: "fr" }),+ });+ expect(action.url?.pathname).toBe("/acme/en/events");+ });++ test("a locale the page does not publish redirects to its default", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/fr/events",+ page: buildPage({ defaultLocale: "en", locales: ["en", "de"] }),+ });+ expect(action.type).toBe("redirect");+ expect(action.reason).toBe("locale-mismatch-redirect");+ // Hostname routing: the slug is not part of the public URL.+ expect(action.url?.pathname).toBe("/en/events");+ });+});++describe("proxy chain — gates", () => {+ const passwordPage = buildPage({+ accessType: "password",+ passwordProtected: true,+ password: "s3cret",+ customDomain: "status.acme.com",+ });++ test("password page with no credentials redirects to the custom domain login", () => {+ const { action } = runProxy({+ host: "status.acme.com",+ pathname: "/",+ page: passwordPage,+ });+ expect(action.type).toBe("redirect");+ expect(action.reason).toContain("gate-in");+ // The post-auth target is captured on the way in.+ expect(action.url?.toString()).toBe(+ "https://status.acme.com/login?redirect=%2F",+ );+ });++ test("a correct cookie on /login sends the visitor back to the page", () => {+ const { action } = runProxy({+ host: "status.acme.com",+ pathname: "/login",+ page: passwordPage,+ cookiePassword: "s3cret",+ });+ expect(action.type).toBe("redirect");+ expect(action.reason).toContain("gate-out");+ expect(action.url?.toString()).toBe("https://status.acme.com/");+ });++ test("a wrong cookie keeps the visitor on /login", () => {+ const { action } = runProxy({+ host: "status.acme.com",+ pathname: "/login",+ page: passwordPage,+ cookiePassword: "nope",+ });+ expect(action.type).not.toBe("redirect");+ });++ test("a correct password renders the page", () => {+ const { action } = runProxy({+ host: "status.acme.com",+ pathname: "/",+ page: passwordPage,+ cookiePassword: "s3cret",+ });+ expect(action.type).toBe("rewrite");+ expect(action.url?.pathname).toBe("/acme/en");+ });++ test("an email-domain page redirects an unauthenticated visitor", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/",+ page: buildPage({+ accessType: "email-domain",+ authEmailDomains: ["acme.com"],+ }),+ });+ expect(action.type).toBe("redirect");+ expect(action.reason).toContain("gate-in");+ });++ test("an email-domain page renders for an allowed domain", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/",+ page: buildPage({+ accessType: "email-domain",+ authEmailDomains: ["acme.com"],+ }),+ authEmail: "[email protected]",+ });+ expect(action.type).toBe("rewrite");+ expect(action.url?.pathname).toBe("/acme/en");+ });++ test("an ip-restricted page redirects an outside IP to /restricted", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/",+ page: buildPage({+ accessType: "ip-restriction",+ allowedIpRanges: ["192.168.1.0/24"],+ }),+ clientIp: "10.0.0.1",+ });+ expect(action.type).toBe("redirect");+ expect(action.reason).toBe("ip-restriction-gate-in");+ expect(action.url?.pathname).toBe("/restricted");+ });++ test("an ip-restricted page renders for an allowed IP", () => {+ const { action } = runProxy({+ host: "acme.openstatus.dev",+ pathname: "/",+ page: buildPage({+ accessType: "ip-restriction",+ allowedIpRanges: ["192.168.1.0/24"],+ }),+ clientIp: "192.168.1.42",+ });+ expect(action.type).toBe("rewrite");+ expect(action.url?.pathname).toBe("/acme/en");+ });++ test("a gated page never rewrites before the gate resolves", () => {+ // Regression guard: the gate stages must run before the default rewrite,+ // or the internal path would render for an unauthorized visitor.+ for (const page of [+ passwordPage,+ buildPage({ accessType: "email-domain", authEmailDomains: ["acme.com"] }),+ buildPage({+ accessType: "ip-restriction",+ allowedIpRanges: ["192.168.1.0/24"],+ }),+ ]) {+ const { action } = runProxy({+ host: page.customDomain || "acme.openstatus.dev",+ pathname: "/monitors/1",+ page,+ });+ expect(action.type).toBe("redirect");+ }+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-unresolved-host-action.test.ts b/apps/status-page/src/lib/proxy/resolve-unresolved-host-action.test.tsnew file mode 100644index 000000000..67d7a8b9e--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-unresolved-host-action.test.ts@@ -0,0 +1,84 @@+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import {+ NOT_FOUND_PATH,+ resolveUnresolvedHostAction,+} from "./resolve-unresolved-host-action";++const ORIGIN = "https://www.stpg.dev";++function run(host: string | null, urlHost = "www.stpg.dev", path = "/") {+ return resolveUnresolvedHostAction({+ host,+ urlHost,+ requestUrl: `${ORIGIN}${path}`,+ });+}++describe("resolveUnresolvedHostAction", () => {+ describe("hosts that must 404 instead of seeing the theme explorer", () => {+ test("custom domain pointed at the deployment but missing from `page`", () => {+ const action = run("status.mxkaske.dev");+ expect(action.type).toBe("rewrite");+ expect(action.reason).toBe("unresolved-host");+ expect(action.url?.pathname).toBe(NOT_FOUND_PATH);+ });++ test("unknown tenant subdomain", () => {+ expect(run("does-not-exist.openstatus.dev").type).toBe("rewrite");+ expect(run("does-not-exist.stpg.dev").type).toBe("rewrite");+ });++ test("apex and `www.` custom domains", () => {+ expect(run("mxkaske.dev").type).toBe("rewrite");+ expect(run("www.mxkaske.dev").type).toBe("rewrite");+ });++ test("the marketing host", () => {+ expect(run("www.openstatus.dev").type).toBe("rewrite");+ });++ test("the 404 target drops the original path and query", () => {+ const action = run("status.mxkaske.dev", "www.stpg.dev", "/events?a=1");+ expect(action.url?.pathname).toBe(NOT_FOUND_PATH);+ expect(action.url?.search).toBe("");+ });+ });++ describe("hosts that render the explorer", () => {+ test("the canonical theme explorer host", () => {+ const action = run("themes.openstatus.dev");+ expect(action.type).toBe("passthrough");+ expect(action.reason).toBe("theme-explorer-host");+ expect(action.url).toBe(undefined);+ });++ test("the internal origin", () => {+ expect(run("www.stpg.dev").type).toBe("passthrough");+ });++ test("local dev", () => {+ expect(run("localhost:3000", "localhost:3000").type).toBe("passthrough");+ });++ test("preview deployments", () => {+ expect(run("os-abc123.vercel.app", "os-abc123.vercel.app").type).toBe(+ "passthrough",+ );+ });+ });++ describe("host resolution", () => {+ test("falls back to urlHost when x-forwarded-host is absent", () => {+ expect(run(null, "themes.openstatus.dev").type).toBe("passthrough");+ expect(run(null, "status.mxkaske.dev").type).toBe("rewrite");+ });++ test("x-forwarded-host wins over urlHost", () => {+ // The origin every proxied host lands on is allowed; the forwarded+ // tenant host is what must 404.+ expect(run("status.mxkaske.dev", "www.stpg.dev").type).toBe("rewrite");+ });+ });+});diff --git a/apps/status-page/src/lib/proxy/resolve-unresolved-host-action.ts b/apps/status-page/src/lib/proxy/resolve-unresolved-host-action.tsnew file mode 100644index 000000000..1a20b8132--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-unresolved-host-action.ts@@ -0,0 +1,32 @@+import { isThemeExplorerHost } from "../theme-explorer-host";+import { type Action, passthrough } from "./types";++/** Matches no route, so Next renders the app's own 404. */+export const NOT_FOUND_PATH = "/_not-found";++/**+ * Decides what to serve when a request resolves to no page — an unknown slug,+ * or a custom domain pointed at the deployment but missing from the `page`+ * table. Passing those through would serve `/`, which is the theme explorer, so+ * the host would answer with the explorer and its OG image instead of a 404.+ */+export function resolveUnresolvedHostAction({+ host,+ urlHost,+ requestUrl,+}: {+ /** x-forwarded-host header value */+ host: string | null;+ /** req.nextUrl.host */+ urlHost: string;+ requestUrl: string;+}): Action {+ if (isThemeExplorerHost(host ?? urlHost)) {+ return passthrough("theme-explorer-host");+ }+ return {+ type: "rewrite",+ url: new URL(NOT_FOUND_PATH, requestUrl),+ reason: "unresolved-host",+ };+}diff --git a/apps/status-page/src/lib/resolve-route.test.ts b/apps/status-page/src/lib/resolve-route.test.tsindex 0ca871828..78dea75e8 100644--- a/apps/status-page/src/lib/resolve-route.test.ts+++ b/apps/status-page/src/lib/resolve-route.test.ts@@ -519,4 +519,180 @@ describe("resolveRoute", () => {});});});+ describe("host header source", () => {+ test("x-forwarded-host wins over the internal urlHost", () => {+ // Every proxied host is rewritten to the www.stpg.dev origin; only the+ // forwarded header still carries the tenant.+ const result = resolveRoute({+ host: "status.acme.com",+ urlHost: "www.stpg.dev",+ pathname: "/monitors/1",+ });+ expect(result).toEqual({+ type: "hostname",+ prefix: "status.acme.com",+ locale: "en",+ localeExplicit: false,+ rewritePath: "/status.acme.com/en/monitors/1",+ });+ });++ test("no forwarded header falls back to urlHost", () => {+ const result = resolveRoute({+ host: null,+ urlHost: "acme.openstatus.dev",+ pathname: "/events",+ });+ expect(result).toEqual({+ type: "hostname",+ prefix: "acme",+ locale: "en",+ localeExplicit: false,+ rewritePath: "/acme/en/events",+ });+ });++ test("origin host alone resolves no tenant", () => {+ // www.stpg.dev/ reached directly — nothing to look up, so the request+ // falls through to `/`.+ expect(+ resolveRoute({+ host: "www.stpg.dev",+ urlHost: "www.stpg.dev",+ pathname: "/",+ }),+ ).toBeNull();+ });+ });++ describe("vercel preview deployments", () => {+ test("preview root resolves no tenant", () => {+ expect(+ resolveRoute({+ host: "status-page-abc123.vercel.app",+ urlHost: "status-page-abc123.vercel.app",+ pathname: "/",+ }),+ ).toBeNull();+ });++ test("preview uses path routing, not the deployment name", () => {+ const result = resolveRoute({+ host: "status-page-abc123.vercel.app",+ urlHost: "status-page-abc123.vercel.app",+ pathname: "/acme/en",+ });+ expect(result).toEqual({+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/acme/en",+ });+ });++ test("a forwarded preview host with a non-preview urlHost reads the deployment name as a slug", () => {+ // The `.vercel.app` guard tests urlHost only. Harmless — no page matches+ // a deployment name — but pinned so a fix is deliberate.+ const result = resolveRoute({+ host: "status-page-abc123.vercel.app",+ urlHost: "www.stpg.dev",+ pathname: "/",+ });+ expect(result?.prefix).toBe("status-page-abc123");+ });+ });++ describe("path shapes", () => {+ test("trailing slash does not add an empty segment", () => {+ const result = resolveRoute({+ host: "acme.openstatus.dev",+ urlHost: "www.stpg.dev",+ pathname: "/events/",+ });+ expect(result?.rewritePath).toBe("/acme/en/events");+ });++ test("repeated slashes collapse", () => {+ const result = resolveRoute({+ host: "acme.openstatus.dev",+ urlHost: "www.stpg.dev",+ pathname: "//events",+ });+ expect(result?.rewritePath).toBe("/acme/en/events");+ });++ test("an unsupported locale-shaped segment is treated as a path segment", () => {+ const result = resolveRoute({+ host: "acme.openstatus.dev",+ urlHost: "www.stpg.dev",+ pathname: "/de-DE/events",+ });+ expect(result).toEqual({+ type: "hostname",+ prefix: "acme",+ locale: "en",+ localeExplicit: false,+ rewritePath: "/acme/en/de-DE/events",+ });+ });++ test("path routing lowercases the lookup prefix but rewrites the original casing", () => {+ // The `[locale]` layout then rejects "EN" and renders the 404.+ const result = resolveRoute({+ host: "www.stpg.dev",+ urlHost: "www.stpg.dev",+ pathname: "/ACME/EN/events",+ });+ expect(result).toEqual({+ type: "pathname",+ prefix: "acme",+ locale: "en",+ localeExplicit: true,+ rewritePath: "/ACME/EN/events",+ });+ });+ });++ describe("hosts with no tenant — these fall through to `/`", () => {+ // The proxy passes through when the resolved prefix matches no `page` row,+ // and `/` is the theme explorer. `isThemeExplorerHost` is what keeps the+ // explorer off the hosts below; see theme-explorer-host.test.ts.+ test("the theme explorer host resolves as a normal subdomain", () => {+ const result = resolveRoute({+ host: "themes.openstatus.dev",+ urlHost: "www.stpg.dev",+ pathname: "/",+ });+ expect(result?.prefix).toBe("themes");+ });++ test("an unknown subdomain resolves to its own slug", () => {+ const result = resolveRoute({+ host: "does-not-exist.openstatus.dev",+ urlHost: "www.stpg.dev",+ pathname: "/",+ });+ expect(result?.prefix).toBe("does-not-exist");+ });++ test("a custom domain missing from the page table resolves to the full host", () => {+ const result = resolveRoute({+ host: "status.unconfigured.com",+ urlHost: "www.stpg.dev",+ pathname: "/",+ });+ expect(result?.prefix).toBe("status.unconfigured.com");+ });++ test("a look-alike host resolves to the tenant slug it imitates", () => {+ // Substring match in getValidSubdomain — see domain.test.ts.+ const result = resolveRoute({+ host: "acme.openstatus.dev.evil.com",+ urlHost: "www.stpg.dev",+ pathname: "/",+ });+ expect(result?.prefix).toBe("acme");+ });+ });});diff --git a/apps/status-page/src/lib/theme-explorer-host.test.ts b/apps/status-page/src/lib/theme-explorer-host.test.tsnew file mode 100644index 000000000..02d6f5cff--- /dev/null+++ b/apps/status-page/src/lib/theme-explorer-host.test.ts@@ -0,0 +1,43 @@+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import {+ isCanonicalThemeExplorerHost,+ isThemeExplorerHost,+} from "./theme-explorer-host";++describe("isThemeExplorerHost", () => {+ test("allows the canonical host", () => {+ expect(isThemeExplorerHost("themes.openstatus.dev")).toBe(true);+ expect(isThemeExplorerHost("THEMES.OPENSTATUS.DEV")).toBe(true);+ });++ test("allows the internal origin and local/preview hosts", () => {+ expect(isThemeExplorerHost("www.stpg.dev")).toBe(true);+ expect(isThemeExplorerHost("stpg.dev")).toBe(true);+ expect(isThemeExplorerHost("localhost:3000")).toBe(true);+ expect(isThemeExplorerHost("status-page-git-main.vercel.app")).toBe(true);+ });++ test("rejects status page hosts", () => {+ expect(isThemeExplorerHost("acme.openstatus.dev")).toBe(false);+ expect(isThemeExplorerHost("acme.stpg.dev")).toBe(false);+ expect(isThemeExplorerHost("status.acme.com")).toBe(false);+ expect(isThemeExplorerHost("acme.localhost:3000")).toBe(false);+ });++ test("rejects look-alike hosts", () => {+ expect(isThemeExplorerHost("themes.openstatus.dev.evil.com")).toBe(false);+ expect(isThemeExplorerHost("eviltheme.openstatus.dev")).toBe(false);+ expect(isThemeExplorerHost(null)).toBe(false);+ expect(isThemeExplorerHost(undefined)).toBe(false);+ });+});++describe("isCanonicalThemeExplorerHost", () => {+ test("only the published host is indexable", () => {+ expect(isCanonicalThemeExplorerHost("themes.openstatus.dev")).toBe(true);+ expect(isCanonicalThemeExplorerHost("www.stpg.dev")).toBe(false);+ expect(isCanonicalThemeExplorerHost("localhost:3000")).toBe(false);+ });+});diff --git a/apps/status-page/src/lib/theme-explorer-host.ts b/apps/status-page/src/lib/theme-explorer-host.tsnew file mode 100644index 000000000..b43c9734a--- /dev/null+++ b/apps/status-page/src/lib/theme-explorer-host.ts@@ -0,0 +1,28 @@+import { stripHostPort } from "./domain";++/** The only host the theme explorer is published on. */+export const THEME_EXPLORER_HOST = "themes.openstatus.dev";+export const THEME_EXPLORER_URL = `https://${THEME_EXPLORER_HOST}`;++// The explorer lives at `/`, which is also where every unresolved host lands+// (unknown slug, custom domain pointed at us but missing from `page`). Without+// this allowlist those hosts render — and share — the explorer as their 404.+// `stpg.dev` is the internal origin every proxied host is rewritten to; it stays+// allowed so the explorer still renders if the proxy drops `x-forwarded-host`,+// but only the canonical host is indexable.+const ALLOWED_HOSTS = [+ THEME_EXPLORER_HOST,+ "stpg.dev",+ "www.stpg.dev",+ "localhost",+];++export function isThemeExplorerHost(host?: string | null) {+ const hostname = stripHostPort(host)?.toLowerCase();+ if (!hostname) return false;+ return ALLOWED_HOSTS.includes(hostname) || hostname.endsWith(".vercel.app");+}++export function isCanonicalThemeExplorerHost(host?: string | null) {+ return stripHostPort(host)?.toLowerCase() === THEME_EXPLORER_HOST;+}diff --git a/apps/status-page/src/proxy.ts b/apps/status-page/src/proxy.tsindex c57aa35ac..c061682ba 100644--- a/apps/status-page/src/proxy.ts+++ b/apps/status-page/src/proxy.ts@@ -9,6 +9,7 @@ import { applyPageLocaleOverride } from "./lib/proxy/apply-page-locale-override"import { applyPageSlugPrefix } from "./lib/proxy/apply-page-slug-prefix";import { composePageAction } from "./lib/proxy/compose-page-action";import { detectMarkdown } from "./lib/proxy/detect-markdown";+import { resolveUnresolvedHostAction } from "./lib/proxy/resolve-unresolved-host-action";import { sanitizeRedirectParam } from "./lib/proxy/sanitize-redirect-param";import { resolveRoute } from "./lib/resolve-route";@@ -17,11 +18,32 @@ const isSelfHosted = process.env.SELF_HOST === "true";export default auth(async (req) => {const url = req.nextUrl.clone();const passthroughResponse = NextResponse.next();+// HTML and markdown share the same URL (negotiated by Accept) — tell shared// caches to key on it so a markdown variant is never served to a browser.passthroughResponse.headers.set("Vary", "Accept");const host = req.headers.get("x-forwarded-host");+ // HTML served via internal rewrite shares its URL with the markdown variant —+ // carry the same Vary as the passthrough so caches don't cross them.+ const rewriteWithVary = (target: URL) => {+ const response = NextResponse.rewrite(target);+ response.headers.set("Vary", "Accept");+ return response;+ };++ // `/` is the theme explorer, so a host that resolves to no page must 404+ // rather than fall through to it.+ const unresolvedHostResponse = () => {+ const action = resolveUnresolvedHostAction({+ host,+ urlHost: url.host,+ requestUrl: req.url,+ });+ if (action.type !== "rewrite") return passthroughResponse;+ return rewriteWithVary(action.url);+ };+// Strip a `.md` suffix before route resolution so path-based markdown// (`/foo/en/monitors/123.md`) parses slug/locale correctly.const { wantsMarkdown, source, pathname } = detectMarkdown({@@ -36,7 +58,7 @@ export default auth(async (req) => {});if (!initialRoute) {- return passthroughResponse;+ return unresolvedHostResponse();}// Markdown requests bypass the proxy's DB lookup and gate chain: the route is@@ -63,8 +85,9 @@ export default auth(async (req) => {const validation = selectPageSchema.safeParse(query);+ // No page for this host/slug — never fall through to the theme explorer.if (!validation.success) {- return passthroughResponse;+ return unresolvedHostResponse();}const _page = validation.data;@@ -114,13 +137,8 @@ export default auth(async (req) => {switch (action.type) {case "redirect":return NextResponse.redirect(action.url);- case "rewrite": {- // HTML served via internal rewrite shares its URL with the markdown- // variant — carry the same Vary so caches don't cross them.- const rewriteResponse = NextResponse.rewrite(action.url);- rewriteResponse.headers.set("Vary", "Accept");- return rewriteResponse;- }+ case "rewrite":+ return rewriteWithVary(action.url);case "passthrough":return passthroughResponse;}