Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat: status page markdown content (#2291)
Maximilian Kaske52f483487ad0
diff --git a/apps/status-page/package.json b/apps/status-page/package.jsonindex deb6110b4..cd3368276 100644--- a/apps/status-page/package.json+++ b/apps/status-page/package.json@@ -83,6 +83,7 @@"@types/node": "catalog:","@types/react": "catalog:","@types/react-dom": "catalog:",+ "bun-types": "catalog:","shadcn": "catalog:","tailwindcss": "catalog:","tw-animate-css": "catalog:",diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(list)/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(list)/layout.tsxnew file mode 100644index 000000000..32ea5a797--- /dev/null+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(list)/layout.tsx@@ -0,0 +1,16 @@+import type { Metadata } from "next";++import { statusPageAlternatesMetadata } from "@/lib/alternates-metadata";++export async function generateMetadata({+ params,+}: {+ params: Promise<{ domain: string }>;+}): Promise<Metadata> {+ const { domain } = await params;+ return statusPageAlternatesMetadata({ domain, markdownPath: "/events.md" });+}++export default function Layout({ children }: { children: React.ReactNode }) {+ return children;+}diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/maintenance/[id]/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/maintenance/[id]/layout.tsxindex 8ebac902a..140e18c53 100644--- a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/maintenance/[id]/layout.tsx+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/maintenance/[id]/layout.tsx@@ -1,7 +1,23 @@+import type { Metadata } from "next";import { notFound } from "next/navigation";+import { statusPageAlternatesMetadata } from "@/lib/alternates-metadata";import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";+export async function generateMetadata({+ params,+}: {+ params: Promise<{ id: string; domain: string }>;+}): Promise<Metadata> {+ const { id, domain } = await params;+ const numericId = Number(id);+ if (Number.isNaN(numericId)) return {};+ return statusPageAlternatesMetadata({+ domain,+ markdownPath: `/events/maintenance/${numericId}.md`,+ });+}+export default async function Layout({children,params,diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/report/[id]/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/report/[id]/layout.tsxindex 5711e11c4..124f989ec 100644--- a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/report/[id]/layout.tsx+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/events/(view)/report/[id]/layout.tsx@@ -1,7 +1,23 @@+import type { Metadata } from "next";import { notFound } from "next/navigation";+import { statusPageAlternatesMetadata } from "@/lib/alternates-metadata";import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";+export async function generateMetadata({+ params,+}: {+ params: Promise<{ id: string; domain: string }>;+}): Promise<Metadata> {+ const { id, domain } = await params;+ const numericId = Number(id);+ if (Number.isNaN(numericId)) return {};+ return statusPageAlternatesMetadata({+ domain,+ markdownPath: `/events/report/${numericId}.md`,+ });+}+export default async function Layout({children,params,diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/[type]/route.ts b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/[type]/route.tsindex ad5ee407f..a3fbb4637 100644--- a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/[type]/route.ts+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/[type]/route.ts@@ -32,9 +32,13 @@ export async function GET(if (_page.accessType === "password") {const url = new URL(_request.url);- const password = url.searchParams.get("pw");- console.log({ url, _page, password });- if (password !== _page.password) return unauthorized();+ const authorized = await queryClient.fetchQuery(+ trpc.statusPage.isPasswordAuthorized.queryOptions({+ slug: _page.slug,+ queryPassword: url.searchParams.get("pw"),+ }),+ );+ if (!authorized) return unauthorized();}if (_page.accessType === "email-domain") {diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/json/route.ts b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/json/route.tsindex 3c3a851b0..885246ea0 100644--- a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/json/route.ts+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/feed/json/route.ts@@ -21,9 +21,13 @@ export async function GET(if (_page.accessType === "password") {const url = new URL(_request.url);- const password = url.searchParams.get("pw");- console.log({ url, _page, password });- if (password !== _page.password) return unauthorized();+ const authorized = await queryClient.fetchQuery(+ trpc.statusPage.isPasswordAuthorized.queryOptions({+ slug: _page.slug,+ queryPassword: url.searchParams.get("pw"),+ }),+ );+ if (!authorized) return unauthorized();}if (_page.accessType === "email-domain") {diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/llms.txt/route.ts b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/llms.txt/route.tsnew file mode 100644index 000000000..060d94fc2--- /dev/null+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/llms.txt/route.ts@@ -0,0 +1,122 @@+import { db, sql } from "@openstatus/db";+import { page } from "@openstatus/db/src/schema";+import { NextResponse } from "next/server";++import { escapeLinkLabel, type OverviewPage } from "@/content/markdown";+import { getBaseUrl } from "@/lib/base-url";+import { getQueryClient, trpc } from "@/lib/trpc/server";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";++function notFound() {+ return new NextResponse("Not Found", {+ status: 404,+ headers: { "Content-Type": "text/plain; charset=utf-8" },+ });+}++function render({+ data,+ baseUrl,+}: {+ data: OverviewPage;+ baseUrl: string;+}): string {+ const now = Date.now();+ const sections = [+ `# ${data.title}`,+ "",+ `> ${data.description || "Operational status."} Agent-readable markdown, JSON, and feeds are linked below.`,+ "",+ "## Status",+ `- [Overview](${baseUrl}/.md): overall status, components, active incidents`,+ `- [Monitors](${baseUrl}/monitors.md): per-service status`,+ `- [Events](${baseUrl}/events.md): incident & maintenance history`,+ ];++ if (data.monitors.length > 0) {+ sections.push("", "## Monitors");+ for (const monitor of data.monitors) {+ sections.push(+ `- [${escapeLinkLabel(monitor.name)}](${baseUrl}/monitors/${monitor.id}.md)`,+ );+ }+ }++ const activeReports = data.statusReports.filter(+ (r) => r.status !== "resolved",+ );+ const activeMaintenance = data.maintenances.filter(+ (m) => m.to && new Date(m.to).getTime() >= now,+ );+ if (activeReports.length > 0 || activeMaintenance.length > 0) {+ sections.push("", "## Active incidents & maintenance");+ for (const report of activeReports) {+ sections.push(+ `- [${escapeLinkLabel(report.title)}](${baseUrl}/events/report/${report.id}.md)`,+ );+ }+ for (const maintenance of activeMaintenance) {+ sections.push(+ `- [${escapeLinkLabel(maintenance.title)}](${baseUrl}/events/maintenance/${maintenance.id}.md)`,+ );+ }+ }++ sections.push(+ "",+ "## Data",+ `- [summary.json](${baseUrl}/api/status/summary.json): machine summary, Statuspage-compatible`,+ `- [current.json](${baseUrl}/api/status/current.json): single overall indicator — cheapest "is it up?"`,+ `- [Unresolved incidents](${baseUrl}/api/status/incidents.json)`,+ `- [RSS](${baseUrl}/feed/rss) · [Atom](${baseUrl}/feed/atom) · [JSON feed](${baseUrl}/feed/json)`,+ "",+ "## Notes",+ "- Any page URL also serves markdown via a `.md` suffix or `Accept: text/markdown`.",+ "",+ );++ return sections.join("\n");+}++export async function GET(+ _request: Request,+ props: { params: Promise<{ domain: string }> },+) {+ const { domain } = await props.params;+ const prefix = domain.toLowerCase();++ const row = await db+ .select({+ slug: page.slug,+ accessType: page.accessType,+ })+ .from(page)+ .where(+ sql`lower(${page.slug}) = ${prefix} OR lower(${page.customDomain}) = ${prefix}`,+ )+ .get();+ if (!row) return notFound();+ // Only public pages get a discovery doc — don't leak title/description of+ // password/email/IP-gated pages. Gate on the cheap row before the full fetch.+ if (row.accessType !== "public") return notFound();++ const data = await getQueryClient().fetchQuery(+ trpc.statusPage.get.queryOptions({ slug: row.slug }),+ );+ if (!data) return notFound();++ const baseUrl = getBaseUrl({+ slug: data.slug,+ customDomain: data.customDomain ?? undefined,+ });++ return new NextResponse(render({ data, baseUrl }), {+ status: 200,+ headers: {+ "Content-Type": "text/plain; charset=utf-8",+ "Cache-Control": "public, max-age=300, stale-while-revalidate=600",+ },+ });+}diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/monitors/[id]/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/monitors/[id]/layout.tsxindex a9bf09737..5a45b9601 100644--- a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/monitors/[id]/layout.tsx+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/monitors/[id]/layout.tsx@@ -1,5 +1,22 @@+import type { Metadata } from "next";import { notFound } from "next/navigation";+import { statusPageAlternatesMetadata } from "@/lib/alternates-metadata";++export async function generateMetadata({+ params,+}: {+ params: Promise<{ id: string; domain: string }>;+}): Promise<Metadata> {+ const { id, domain } = await params;+ const numericId = Number(id);+ if (Number.isNaN(numericId)) return {};+ return statusPageAlternatesMetadata({+ domain,+ markdownPath: `/monitors/${numericId}.md`,+ });+}+export default async function Layout({children,params,diff --git a/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/monitors/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/monitors/layout.tsxnew file mode 100644index 000000000..61d968111--- /dev/null+++ b/apps/status-page/src/app/(status-page)/[domain]/[locale]/(public)/monitors/layout.tsx@@ -0,0 +1,16 @@+import type { Metadata } from "next";++import { statusPageAlternatesMetadata } from "@/lib/alternates-metadata";++export async function generateMetadata({+ params,+}: {+ params: Promise<{ domain: string }>;+}): Promise<Metadata> {+ const { domain } = await params;+ return statusPageAlternatesMetadata({ domain, markdownPath: "/monitors.md" });+}++export default function Layout({ children }: { children: React.ReactNode }) {+ return children;+}diff --git a/apps/status-page/src/app/(status-page)/[domain]/layout.tsx b/apps/status-page/src/app/(status-page)/[domain]/layout.tsxindex dc3edf0d9..79acbe4c5 100644--- a/apps/status-page/src/app/(status-page)/[domain]/layout.tsx+++ b/apps/status-page/src/app/(status-page)/[domain]/layout.tsx@@ -12,7 +12,8 @@ import {} from "@/components/status-page/floating-button";import { FloatingTheme } from "@/components/status-page/floating-theme";import { ThemeProvider } from "@/components/themes/theme-provider";-import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";+import { statusPageAlternates } from "@/lib/alternates";+import { getQueryClient, HydrateClient, trpc } from "@/lib/trpc/server";// Canonical schema — guarantees concrete enum output (never null/undefined).@@ -110,11 +111,10 @@ export async function generateMetadata({icons: page?.icon?.toLowerCase().endsWith(".svg")? { icon: { url: page.icon, type: "image/svg+xml" } }: page?.icon,- alternates: {- canonical: page?.customDomain- ? `https://${page.customDomain}`- : `https://${page.slug}.openstatus.dev`,- },+ alternates: statusPageAlternates({+ slug: page.slug,+ customDomain: page.customDomain,+ }),twitter: {...twitterMetadata,images: [`/api/og/page?slug=${page?.slug}`],diff --git a/apps/status-page/src/app/api/markdown/[[...path]]/route.ts b/apps/status-page/src/app/api/markdown/[[...path]]/route.tsnew file mode 100644index 000000000..43a151d45--- /dev/null+++ b/apps/status-page/src/app/api/markdown/[[...path]]/route.ts@@ -0,0 +1,213 @@+import { cookies, headers } from "next/headers";+import { type NextRequest, NextResponse } from "next/server";++import {+ generateEventsList,+ generateMaintenance,+ generateMonitor,+ generateMonitorsList,+ generateOverview,+ generateReport,+ matchMarkdownRoute,+ parseMarkdownPath,+} from "@/content/markdown";+import { getBaseUrl } from "@/lib/base-url";+import { resolveClientIp } from "@/lib/http/client-ip";+import { resolveMarkdownResponse } from "@/lib/http/markdown-response";+import { type GatePage, resolveGate } from "@/lib/proxy/resolve-gate";+import { getQueryClient, trpc } from "@/lib/trpc/server";++// Match the feed route: getQueryClient/httpBatchLink needs Node, not Edge.+export const runtime = "nodejs";++const PLAIN = "text/plain; charset=utf-8";++function textResponse(body: string, status: number) {+ return new NextResponse(body, {+ status,+ headers: { "Content-Type": PLAIN, "Cache-Control": "no-store" },+ });+}++function markdownResponse(+ request: NextRequest,+ body: string,+ source: string | null,+ whiteLabel: boolean,+ accessType: string | null | undefined,+) {+ const {+ status,+ body: finalBody,+ headers,+ } = resolveMarkdownResponse(request, {+ body,+ source,+ whiteLabel,+ accessType,+ });+ return new NextResponse(finalBody, { status, headers });+}++export async function GET(+ request: NextRequest,+ { params }: { params: Promise<{ path?: string[] }> },+) {+ try {+ const { path = [] } = await params;+ const parsed = parseMarkdownPath(path);+ if (!parsed) return textResponse("Not Found", 404);+ const { slug, rest } = parsed;++ const target = matchMarkdownRoute(rest);+ if (!target) return textResponse("Not Found", 404);++ const source = request.headers.get("x-md-source");+ const queryClient = getQueryClient();+ const url = new URL(request.url);+ const cookieStore = await cookies();+ const headerStore = await headers();+ const clientIp = resolveClientIp(headerStore);++ // Returns a response when the gate denies, null when it passes.+ async function denyResponse(gatePage: GatePage) {+ const gate = await resolveGate({+ page: gatePage,+ queryClient,+ url,+ cookieStore,+ clientIp,+ });+ return gate.ok ? null : textResponse(gate.body, gate.status);+ }++ switch (target.kind) {+ // List pages render from `get`, which also carries the access fields — so+ // we gate off the same payload instead of a second full-graph getLight.+ case "overview":+ case "monitors":+ case "events": {+ const page = await queryClient.fetchQuery(+ trpc.statusPage.get.queryOptions({ slug }),+ );+ if (!page) return textResponse("Not Found", 404);+ const denied = await denyResponse(page);+ if (denied) return denied;++ const baseUrl = getBaseUrl({+ slug: page.slug,+ customDomain: page.customDomain,+ });++ if (target.kind === "monitors") {+ return markdownResponse(+ request,+ generateMonitorsList(page, baseUrl),+ source,+ page.whiteLabel,+ page.accessType,+ );+ }+ if (target.kind === "events") {+ return markdownResponse(+ request,+ generateEventsList(page, baseUrl),+ source,+ page.whiteLabel,+ page.accessType,+ );+ }+ // Mirror what the live page renders: bar/card type and the uptime+ // toggle come from the page configuration, not hardcoded defaults.+ const cardType = page.configuration?.value ?? "requests";+ const barType = page.configuration?.type ?? "absolute";+ const showUptime = page.configuration?.uptime ?? true;+ // Per-day uptime series (Tinybird) — only after the gate passes.+ const uptime =+ (await queryClient.fetchQuery(+ trpc.statusPage.getUptime.queryOptions({+ slug,+ pageComponentIds: page.pageComponents.map((c) => c.id.toString()),+ cardType,+ barType,+ }),+ )) ?? [];+ return markdownResponse(+ request,+ generateOverview(page, uptime, baseUrl, showUptime),+ source,+ page.whiteLabel,+ page.accessType,+ );+ }+ // Detail pages: the detail queries don't carry access fields, so gate via+ // getGate — a narrow access-only query — before fetching the (heavier)+ // detail payload.+ case "monitor":+ case "report":+ case "maintenance": {+ const light = await queryClient.fetchQuery(+ trpc.statusPage.getGate.queryOptions({ slug }),+ );+ if (!light) return textResponse("Not Found", 404);+ const denied = await denyResponse(light);+ if (denied) return denied;++ const baseUrl = getBaseUrl({+ slug: light.slug,+ customDomain: light.customDomain,+ });++ if (target.kind === "monitor") {+ const monitor = await queryClient.fetchQuery(+ trpc.statusPage.getMonitor.queryOptions({ slug, id: target.id }),+ );+ if (!monitor) return textResponse("Not Found", 404);+ return markdownResponse(+ request,+ generateMonitor(monitor, baseUrl, {+ homepageUrl: light.homepageUrl,+ contactUrl: light.contactUrl,+ }),+ source,+ light.whiteLabel,+ light.accessType,+ );+ }+ if (target.kind === "report") {+ const report = await queryClient.fetchQuery(+ trpc.statusPage.getReport.queryOptions({ slug, id: target.id }),+ );+ if (!report) return textResponse("Not Found", 404);+ return markdownResponse(+ request,+ generateReport(report, baseUrl, {+ homepageUrl: light.homepageUrl,+ contactUrl: light.contactUrl,+ }),+ source,+ light.whiteLabel,+ light.accessType,+ );+ }+ const maintenance = await queryClient.fetchQuery(+ trpc.statusPage.getMaintenance.queryOptions({ slug, id: target.id }),+ );+ if (!maintenance) return textResponse("Not Found", 404);+ return markdownResponse(+ request,+ generateMaintenance(maintenance, baseUrl, {+ homepageUrl: light.homepageUrl,+ contactUrl: light.contactUrl,+ }),+ source,+ light.whiteLabel,+ light.accessType,+ );+ }+ }+ } catch (error) {+ console.error("Error serving status-page markdown:", error);+ return textResponse("Internal Server Error", 500);+ }+}diff --git a/apps/status-page/src/app/api/status/[[...path]]/route.ts b/apps/status-page/src/app/api/status/[[...path]]/route.tsnew file mode 100644index 000000000..37255f800--- /dev/null+++ b/apps/status-page/src/app/api/status/[[...path]]/route.ts@@ -0,0 +1,127 @@+import { db, sql } from "@openstatus/db";+import { page } from "@openstatus/db/src/schema";+import { cookies, headers } from "next/headers";+import { type NextRequest, NextResponse } from "next/server";++import {+ matchEndpoint,+ toStatus,+ toSummary,+ toUnresolvedIncidents,+} from "@/content/status-json";+import { getBaseUrl } from "@/lib/base-url";+import { stripHostPort } from "@/lib/domain";+import { resolveClientIp } from "@/lib/http/client-ip";+import { computeETag, isNotModified } from "@/lib/http/etag";+import { resolveGate } from "@/lib/proxy/resolve-gate";+import { resolveRoute } from "@/lib/resolve-route";+import { getQueryClient, trpc } from "@/lib/trpc/server";++// trpc httpBatchLink needs Node, matching the markdown route.+export const runtime = "nodejs";+export const dynamic = "force-dynamic";++function json(body: unknown, status: number, extraHeaders?: HeadersInit) {+ return new NextResponse(JSON.stringify(body), {+ status,+ headers: {+ "Content-Type": "application/json; charset=utf-8",+ ...extraHeaders,+ },+ });+}++export async function GET(+ request: NextRequest,+ { params }: { params: Promise<{ path?: string[] }> },+) {+ try {+ const { path = [] } = await params;+ const matched = matchEndpoint(path);+ if (!matched) return json({ error: "Not Found" }, 404);+ const { endpoint, slug: pathSlug } = matched;++ const url = new URL(request.url);+ // Strip the port: custom-domain lookups exact-match the port-less+ // page.customDomain (parity with sitemap.ts / robots.ts).+ const host = stripHostPort(request.headers.get("x-forwarded-host"));+ // Host-keyed deploys (subdomain/custom domain) resolve from the host; a+ // path-based deploy carries the slug in the URL (`{slug}/summary.json`),+ // so feed it through resolveRoute as the pathname prefix.+ const route = resolveRoute({+ host,+ urlHost: host ?? url.host,+ pathname: pathSlug ? `/${pathSlug}` : "/",+ });+ if (!route) return json({ error: "Not Found" }, 404);++ const row = await db+ .select({ slug: page.slug })+ .from(page)+ .where(+ sql`lower(${page.slug}) = ${route.prefix} OR lower(${page.customDomain}) = ${route.prefix}`,+ )+ .get();+ if (!row) return json({ error: "Not Found" }, 404);++ const queryClient = getQueryClient();+ const data = await queryClient.fetchQuery(+ trpc.statusPage.get.queryOptions({ slug: row.slug }),+ );+ if (!data) return json({ error: "Not Found" }, 404);++ const headerStore = await headers();+ const cookieStore = await cookies();+ const clientIp = resolveClientIp(headerStore);+ const gate = await resolveGate({+ page: data,+ queryClient,+ url,+ cookieStore,+ clientIp,+ });+ if (!gate.ok) return json({ error: gate.body }, gate.status);++ const baseUrl = getBaseUrl({+ slug: data.slug,+ customDomain: data.customDomain ?? undefined,+ });++ const payload =+ endpoint === "status"+ ? toStatus(data, baseUrl)+ : endpoint === "incidents"+ ? toUnresolvedIncidents(data, baseUrl)+ : toSummary(data, baseUrl);++ const body = JSON.stringify(payload);+ const etag = computeETag(body);+ const cacheControl =+ data.accessType === "public"+ ? "public, max-age=30, stale-while-revalidate=60"+ : "private, no-store";++ if (isNotModified(request, etag)) {+ return new NextResponse(null, {+ status: 304,+ headers: {+ ETag: etag,+ "Cache-Control": cacheControl,+ "Content-Type": "application/json; charset=utf-8",+ },+ });+ }++ return new NextResponse(body, {+ status: 200,+ headers: {+ "Content-Type": "application/json; charset=utf-8",+ "Cache-Control": cacheControl,+ ETag: etag,+ },+ });+ } catch (error) {+ console.error("Error serving status-page status JSON:", error);+ return json({ error: "Internal Server Error" }, 500);+ }+}diff --git a/apps/status-page/src/app/robots.ts b/apps/status-page/src/app/robots.tsindex c7828a99c..4df99d6d6 100644--- a/apps/status-page/src/app/robots.ts+++ b/apps/status-page/src/app/robots.ts@@ -1,6 +1,42 @@+import { db, sql } from "@openstatus/db";+import { page } from "@openstatus/db/src/schema";import type { MetadataRoute } from "next";+import { headers } from "next/headers";++import { getBaseUrl } from "@/lib/base-url";+import { stripHostPort } from "@/lib/domain";+import { resolveRoute } from "@/lib/resolve-route";++// trpc/db lookup needs Node, matching the sitemap and other content routes.+export const runtime = "nodejs";+export const dynamic = "force-dynamic";++export default async function robots(): Promise<MetadataRoute.Robots> {+ const headerStore = await headers();+ const host = stripHostPort(+ headerStore.get("x-forwarded-host") ?? headerStore.get("host"),+ );++ // Only advertise a sitemap when the host resolves to a real page; the host+ // header is attacker-controlled, so resolve the page and build the sitemap URL+ // from its canonical base — never reflect the raw host (validating the slug+ // prefix alone lets a forged host like `acme.openstatus.dev.evil.com` through).+ const route = host+ ? resolveRoute({ host, urlHost: host, pathname: "/" })+ : null;+ const row = route+ ? await db+ .select({ slug: page.slug, customDomain: page.customDomain })+ .from(page)+ .where(+ sql`lower(${page.slug}) = ${route.prefix} OR lower(${page.customDomain}) = ${route.prefix}`,+ )+ .get()+ : undefined;+ const sitemap = row+ ? `${getBaseUrl({ slug: row.slug, customDomain: row.customDomain ?? undefined })}/sitemap.xml`+ : undefined;-export default function robots(): MetadataRoute.Robots {return {rules: [{@@ -8,5 +44,6 @@ export default function robots(): MetadataRoute.Robots {allow: "/",},],+ ...(sitemap ? { sitemap } : {}),};}diff --git a/apps/status-page/src/app/sitemap.ts b/apps/status-page/src/app/sitemap.tsindex 57e967552..b6e31bef2 100644--- a/apps/status-page/src/app/sitemap.ts+++ b/apps/status-page/src/app/sitemap.ts@@ -1,24 +1,77 @@-import { db, eq } from "@openstatus/db";+import { db, sql } from "@openstatus/db";import { page } from "@openstatus/db/src/schema";import type { MetadataRoute } from "next";+import { headers } from "next/headers";+import { getBaseUrl } from "@/lib/base-url";+import { stripHostPort } from "@/lib/domain";+import { resolveRoute } from "@/lib/resolve-route";+import { getQueryClient, trpc } from "@/lib/trpc/server";++// One sitemap per host: a custom domain must never enumerate other tenants'+// pages. trpc httpBatchLink needs Node, matching the other content routes.+export const runtime = "nodejs";export const dynamic = "force-dynamic";export default async function sitemap(): Promise<MetadataRoute.Sitemap> {- const pages = await db+ const headerStore = await headers();+ const host = stripHostPort(+ headerStore.get("x-forwarded-host") ?? headerStore.get("host"),+ );+ const route = resolveRoute({ host, urlHost: host ?? "", pathname: "/" });+ if (!route) return [];++ const row = await db.select({slug: page.slug,customDomain: page.customDomain,- updatedAt: page.updatedAt,+ allowIndex: page.allowIndex,+ accessType: page.accessType,}).from(page)- .where(eq(page.allowIndex, true))- .all();-- return pages.map((p) => {- const url = p.customDomain- ? `https://${p.customDomain}`- : `https://${p.slug}.openstatus.dev`;- return { url, lastModified: p.updatedAt ?? undefined };+ .where(+ sql`lower(${page.slug}) = ${route.prefix} OR lower(${page.customDomain}) = ${route.prefix}`,+ )+ .get();+ // Only public, indexable pages belong in a sitemap — gated content must not+ // be advertised to crawlers.+ if (!row || !row.allowIndex || row.accessType !== "public") return [];++ const data = await getQueryClient().fetchQuery(+ trpc.statusPage.get.queryOptions({ slug: row.slug }),+ );+ if (!data) return [];++ const baseUrl = getBaseUrl({+ slug: data.slug,+ customDomain: data.customDomain ?? undefined,});+ const lastModified = data.updatedAt ?? undefined;++ const entries: MetadataRoute.Sitemap = [+ { url: baseUrl, lastModified },+ { url: `${baseUrl}/events`, lastModified },+ ];++ if (data.monitors.length > 0) {+ entries.push({ url: `${baseUrl}/monitors`, lastModified });+ }++ for (const monitor of data.monitors) {+ entries.push({ url: `${baseUrl}/monitors/${monitor.id}`, lastModified });+ }+ for (const report of data.statusReports) {+ entries.push({+ url: `${baseUrl}/events/report/${report.id}`,+ lastModified,+ });+ }+ for (const maintenance of data.maintenances) {+ entries.push({+ url: `${baseUrl}/events/maintenance/${maintenance.id}`,+ lastModified,+ });+ }++ return entries;}diff --git a/apps/status-page/src/components/status-page/status-updates.tsx b/apps/status-page/src/components/status-page/status-updates.tsxindex a344e1ab2..f1a38198b 100644--- a/apps/status-page/src/components/status-page/status-updates.tsx+++ b/apps/status-page/src/components/status-page/status-updates.tsx@@ -19,9 +19,11 @@ import {TabsList,TabsTrigger,} from "@openstatus/ui/components/ui/tabs";+import { useCookieState } from "@openstatus/ui/hooks/use-cookie-state";import { cn } from "@openstatus/ui/lib/utils";import { Inbox } from "lucide-react";import { useExtracted } from "next-intl";+import { useParams } from "next/navigation";import { useState } from "react";import {@@ -29,19 +31,26 @@ import {type FormValues,} from "@/components/forms/form-subscribe-email";import { getBaseUrl } from "@/lib/base-url";+import { createProtectedCookieKey } from "@/lib/protected";export type StatusUpdateType = "email" | "rss" | "ssh" | "json" | "slack";type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;-function getUpdateLink(type: "rss" | "json" | "atom", page?: Page | null) {+function getUpdateLink(+ type: "rss" | "json" | "atom",+ page?: Page | null,+ password?: string,+) {const baseUrl = getBaseUrl({slug: page?.slug,customDomain: page?.customDomain,});return `${baseUrl}/feed/${type}${- page?.accessType === "password" ? `?pw=${page?.password}` : ""+ page?.accessType === "password" && password+ ? `?pw=${encodeURIComponent(password)}`+ : ""}`;}@@ -60,12 +69,17 @@ export function StatusUpdates({}: StatusUpdatesProps) {const t = useExtracted();const [success, setSuccess] = useState(false);+ const params = useParams();+ const domain = typeof params.domain === "string" ? params.domain : "";+ // The password lives in the cookie this browser set at login — not in the+ // page payload, which intentionally omits it.+ const [password] = useCookieState(createProtectedCookieKey(domain));if (types.length === 0) return null;- const rssUrl = getUpdateLink("rss", page);- const atomUrl = getUpdateLink("atom", page);- const jsonUrl = getUpdateLink("json", page);+ const rssUrl = getUpdateLink("rss", page, password);+ const atomUrl = getUpdateLink("atom", page, password);+ const jsonUrl = getUpdateLink("json", page, password);const sshCommand = `ssh ${page?.slug}@ssh.openstatus.dev`;return (diff --git a/apps/status-page/src/content/markdown/generators.test.ts b/apps/status-page/src/content/markdown/generators.test.tsnew file mode 100644index 000000000..05c074d54--- /dev/null+++ b/apps/status-page/src/content/markdown/generators.test.ts@@ -0,0 +1,699 @@+import { describe, expect, test } from "bun:test";++import {+ escapeCell,+ escapeLinkLabel,+ eventLog,+ frontmatter,+ navLine,+ statusLabel,+ withPoweredBy,+} from "./helpers";+import {+ generateEventsList,+ generateMaintenance,+ generateMonitor,+ generateMonitorsList,+ generateOverview,+ generateReport,+ type MaintenanceDetail,+ type MonitorDetail,+ type OverviewPage,+ type ReportDetail,+ type UptimeComponent,+} from "./index";++const BASE = "https://acme.openstatus.dev";++// Fixtures are partial — generators only read the fields asserted below.+const overview = {+ title: "Acme Status",+ description: "Acme service status",+ status: "degraded",+ statusReports: [+ {+ id: 1,+ title: "API latency",+ status: "investigating",+ createdAt: new Date("2026-06-18T10:00:00.000Z"),+ statusReportsToPageComponents: [+ { pageComponentId: 100, pageComponent: { name: "API" } },+ ],+ statusReportUpdates: [+ {+ status: "investigating",+ message: "Looking into it.",+ date: new Date("2026-06-18T10:00:00.000Z"),+ statusReportUpdateToPageComponents: [+ { pageComponentId: 100, impact: "major_outage" },+ ],+ },+ ],+ },+ {+ id: 2,+ title: "Old outage",+ status: "resolved",+ createdAt: new Date("2026-05-01T10:00:00.000Z"),+ statusReportsToPageComponents: [],+ statusReportUpdates: [+ {+ status: "resolved",+ message: "Fixed.",+ date: new Date("2026-05-02T10:00:00.000Z"),+ },+ {+ status: "investigating",+ message: "Down.",+ date: new Date("2026-05-01T10:00:00.000Z"),+ },+ ],+ },+ ],+ maintenances: [+ {+ id: 5,+ title: "DB upgrade",+ message: "Brief downtime.",+ from: new Date("2026-06-20T00:00:00.000Z"),+ to: new Date("2099-06-20T01:00:00.000Z"),+ maintenancesToPageComponents: [{ pageComponent: { name: "Database" } }],+ },+ ],+ monitors: [{ id: 9, name: "API monitor", status: "success" }],+ trackers: [],+ homepageUrl: "https://acme.com",+ contactUrl: "mailto:[email protected]",+} as unknown as OverviewPage;++const components = [+ {+ name: "laser pointer tracker",+ pageComponentId: 100,+ uptime: "97.8%",+ data: [+ { bar: [{ status: "success", height: 100 }] },+ { bar: [{ status: "error", height: 100 }] },+ { bar: [{ status: "info", height: 100 }] },+ ],+ },+] as unknown as UptimeComponent[];++describe("generateOverview", () => {+ const md = generateOverview(overview, components, BASE);++ test("frontmatter + no generated-at", () => {+ expect(md).toContain('title: "Acme Status"');+ expect(md).toContain(`base_url: "${BASE}"`);+ expect(md).toContain(`canonical: "${BASE}"`);+ expect(md).not.toContain("generated-at");+ });++ test("frontmatter carries page homepage + contact urls", () => {+ expect(md).toContain('homepage_url: "https://acme.com"');+ expect(md).toContain('contact_url: "mailto:[email protected]"');+ });++ test("peer nav links to monitors + events docs", () => {+ expect(md).toContain(+ `**Status** · [Monitors](/monitors.md) · [Events](/events.md)`,+ );+ });++ test("overall status line with glyph + timestamp", () => {+ expect(md).toContain("`~` **Degraded** · ");+ expect(md).toMatch(/\(GMT\+0\)/);+ });++ test("active incident with affected components (resolved excluded)", () => {+ expect(md).toContain("**API latency**");+ expect(md).toContain("affects: API");+ expect(md).toContain("Looking into it.");+ expect(md).not.toContain("Old outage");+ });++ test("active & upcoming maintenance with affected components", () => {+ expect(md).toContain("## Active & upcoming maintenance");+ expect(md).toContain("= **DB upgrade**");+ expect(md).toContain("affects: Database");+ });++ test("per-component ascii uptime bar in a code span", () => {+ expect(md).toContain("**laser pointer tracker** — 97.8%");+ expect(md).toContain("`3d ago → today`");+ expect(md).toContain("`+x=`");+ });++ test("per-component event links to affecting reports", () => {+ expect(md).toContain(`Events: [API latency](/events/report/1.md)`);+ });++ test("showUptime=false renders current status instead of percentage", () => {+ const off = generateOverview(overview, components, BASE, false);+ // last fixture day is "info" → Maintenance; percentage must not appear+ expect(off).toContain("**laser pointer tracker** — Maintenance");+ expect(off).not.toContain("97.8%");+ });++ test("legend lists every status in severity order", () => {+ expect(md).toContain(+ "Legend: `+` Operational · `~` Degraded · `x` Outage · `=` Maintenance · `.` No data",+ );+ });+});++describe("generateOverview machine-readable pointer", () => {+ test("public page points to json endpoints + llms.txt", () => {+ const pub = {+ ...overview,+ trackers: [],+ accessType: "public",+ } as unknown as OverviewPage;+ expect(generateOverview(pub, components, BASE)).toContain(+ "Machine-readable: [current.json](/api/status/current.json) · [summary.json](/api/status/summary.json) · [more](/llms.txt)",+ );+ });++ test("gated page omits the pointer", () => {+ const gated = {+ ...overview,+ trackers: [],+ accessType: "password",+ } as unknown as OverviewPage;+ expect(generateOverview(gated, components, BASE)).not.toContain(+ "Machine-readable:",+ );+ });+});++describe("generateOverview live frontmatter", () => {+ const page = {+ title: "Acme",+ description: "",+ status: "degraded",+ updatedAt: new Date("2026-06-18T14:03:00.000Z"),+ statusReports: [+ {+ id: 1,+ title: "x",+ status: "investigating",+ createdAt: new Date("2026-06-18T10:00:00.000Z"),+ statusReportsToPageComponents: [],+ statusReportUpdates: [],+ },+ ],+ maintenances: [],+ monitors: [],+ trackers: [+ {+ type: "component",+ component: { name: "API", status: "error" },+ order: 0,+ },+ {+ type: "component",+ component: { name: "Web", status: "success" },+ order: 1,+ },+ {+ type: "group",+ groupName: "g",+ components: [{ name: "DB", status: "success" }],+ status: "success",+ order: 2,+ },+ ],+ } as unknown as OverviewPage;+ const comps = [+ {+ name: "API",+ pageComponentId: 1,+ uptime: "99.0%",+ data: [{ bar: [{ status: "success", height: 100 }] }],+ },+ ] as unknown as UptimeComponent[];++ const count = (s: string, sub: string) => s.split(sub).length - 1;++ test("frontmatter carries live machine state", () => {+ const md = generateOverview(page, comps, BASE);+ expect(md).toContain('status: "degraded"');+ expect(md).toContain("active_reports: 1");+ expect(md).toContain("active_maintenance: 0");+ expect(md).toContain("components_operational: 2");+ expect(md).toContain("components_total: 3");+ expect(md).toContain('worst_component: "API"');+ // fetched_at is the generation time, minute-granular ISO; no misleading+ // page-mtime updated_at, no cryptic Statuspage indicator.+ expect(md).toMatch(/fetched_at: "\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:00\.000Z"/);+ expect(md).not.toContain("indicator:");+ expect(md).not.toContain("updated_at:");+ });++ test("always renders the ascii uptime bar + legend", () => {+ const md = generateOverview(page, comps, BASE);+ // The `+` bar is a code span (`` `+` ``); `(GMT+0)` has a bare `+`, so match+ // the wrapped form to isolate the bar.+ expect(count(md, "`+`")).toBeGreaterThan(0);+ expect(md).toContain("Legend:");+ });+});++describe("generateOverview component ordering + grouping", () => {+ const page = {+ title: "Acme",+ description: "",+ status: "success",+ statusReports: [],+ maintenances: [],+ monitors: [],+ trackers: [+ {+ type: "component",+ component: { id: 1, name: "API", status: "success" },+ order: 0,+ },+ {+ type: "component",+ component: { id: 2, name: "Web", status: "success" },+ order: 1,+ },+ {+ type: "group",+ groupName: "Databases",+ components: [+ { id: 3, name: "Primary DB", status: "success" },+ { id: 4, name: "Replica DB", status: "success" },+ ],+ status: "success",+ order: 2,+ },+ ],+ } as unknown as OverviewPage;++ // Uptime arrives in a different (DB-arbitrary) order than trackers.+ const day = { bar: [{ status: "success", height: 100 }] };+ const comps = [+ { name: "Replica DB", pageComponentId: 4, uptime: "99%", data: [day] },+ { name: "API", pageComponentId: 1, uptime: "100%", data: [day] },+ { name: "Primary DB", pageComponentId: 3, uptime: "98%", data: [day] },+ { name: "Web", pageComponentId: 2, uptime: "100%", data: [day] },+ ] as unknown as UptimeComponent[];++ const md = generateOverview(page, comps, BASE);++ test("renders components in tracker order, not uptime-array order", () => {+ const order = ["API", "Web", "Primary DB", "Replica DB"].map((n) =>+ md.indexOf(`**${n}**`),+ );+ expect(order.every((i) => i >= 0)).toBe(true);+ expect(order).toEqual([...order].sort((a, b) => a - b));+ });++ test("emits a heading for grouped components, not for ungrouped", () => {+ expect(md).toContain("### Databases");+ expect(md.indexOf("### Databases")).toBeLessThan(+ md.indexOf("**Primary DB**"),+ );+ expect(md).not.toContain("### API");+ });+});++describe("generateOverview empty components", () => {+ const empty = {+ title: "Empty",+ description: "",+ status: "success",+ statusReports: [],+ maintenances: [],+ monitors: [],+ trackers: [],+ } as unknown as OverviewPage;+ const md = generateOverview(empty, [], BASE);++ test("no components copy + operational", () => {+ expect(md).toContain("`+` **Operational**");+ expect(md).toContain("No components.");+ });+});++describe("generateMonitorsList", () => {+ test("monitor row with status glyph + .md link", () => {+ const md = generateMonitorsList(overview, BASE);+ expect(md).toContain(`| + API monitor | Operational | /monitors/9.md |`);+ });+});++describe("generateEventsList", () => {+ const md = generateEventsList(overview, BASE);++ test("report heading is a link, no glyph", () => {+ expect(md).toContain(`### [Old outage](/events/report/2.md)`);+ expect(md).toContain(`### [API latency](/events/report/1.md)`);+ expect(md).not.toContain("### x");+ });++ test("affects includes per-component impact; bullets have no bold", () => {+ expect(md).toContain("affects: API (major outage)");+ expect(md).toContain("- x Investigating —");+ expect(md).toContain("- + Resolved —");+ expect(md).not.toContain("**Investigating**");+ });++ test("update bullet carries its own per-component impact, no body", () => {+ expect(md).toContain("· API (major outage)");+ expect(md).not.toContain("Looking into it.");+ });++ test("greppable event log: fenced, sortable stamp, ref, trailing glyph", () => {+ expect(md).toContain("## Event log");+ expect(md).toContain("```text");+ expect(md).toContain("# timestamp");+ expect(md).toMatch(+ /2026-06-18 10:00 {2}INVESTIGATING {2}report\/1 +x API latency/,+ );+ expect(md).toMatch(+ /2026-05-02 10:00 {2}RESOLVED {2,}report\/2 +\+ Old outage/,+ );+ // newest update sorts above older ones+ expect(md.indexOf("2026-06-18 10:00")).toBeLessThan(+ md.indexOf("2026-05-02 10:00"),+ );+ });++ test("maintenance heading is a link, no glyph", () => {+ expect(md).toContain("## Maintenance");+ expect(md).toContain(`### [DB upgrade](/events/maintenance/5.md)`);+ });+});++describe("generateEventsList open-ended maintenance", () => {+ // Regression: `m.to` is nullable; the old `new Date(m.to)` resolved to the+ // epoch and produced a phantom 1970 "COMPLETED" row + a ~56-year duration.+ const page = {+ title: "X",+ description: "",+ monitors: [],+ statusReports: [],+ maintenances: [+ {+ id: 7,+ title: "Rolling upgrade",+ from: new Date("2026-06-18T00:00:00.000Z"),+ to: null,+ maintenancesToPageComponents: [],+ },+ ],+ } as unknown as OverviewPage;+ const md = generateEventsList(page, BASE);++ test("no phantom COMPLETED row, no 1970 timestamp", () => {+ expect(md).not.toContain("COMPLETED");+ expect(md).not.toContain("1970");+ });+});++describe("escapeCell", () => {+ test("escapes backslash before pipe (CodeQL: incomplete escaping)", () => {+ // input: backslash, pipe → both must end up escaped+ expect(escapeCell(String.raw`\|`)).toBe(String.raw`\\\|`);+ expect(escapeCell("plain")).toBe("plain");+ });+});++describe("withPoweredBy", () => {+ test("appends attribution footer when not white-labeled", () => {+ const out = withPoweredBy("# Title\n", false);+ expect(out).toContain(+ "_Powered by [openstatus.dev](https://openstatus.dev)_",+ );+ });++ test("omits footer when white-labeled", () => {+ expect(withPoweredBy("# Title\n", true)).toBe("# Title\n");+ });+});++describe("statusLabel mapping", () => {+ test("component + report statuses", () => {+ expect(statusLabel("success")).toBe("Operational");+ expect(statusLabel("error")).toBe("Outage");+ expect(statusLabel("investigating")).toBe("Investigating");+ expect(statusLabel("resolved")).toBe("Resolved");+ });+});++describe("generateReport", () => {+ const report = {+ id: 1,+ title: "API latency",+ status: "monitoring",+ createdAt: new Date("2026-06-18T10:00:00.000Z"),+ statusReportsToPageComponents: [+ { pageComponentId: 100, pageComponent: { name: "API" } },+ ],+ statusReportUpdates: [+ {+ status: "resolved",+ message: "All good.",+ date: new Date("2026-06-18T13:00:00.000Z"),+ statusReportUpdateToPageComponents: [+ { pageComponentId: 100, impact: "operational" },+ ],+ },+ {+ status: "monitoring",+ message: "Recovering.",+ date: new Date("2026-06-18T12:00:00.000Z"),+ statusReportUpdateToPageComponents: [+ { pageComponentId: 100, impact: "degraded_performance" },+ ],+ },+ {+ status: "investigating",+ message: "Started.",+ date: new Date("2026-06-18T10:00:00.000Z"),+ statusReportUpdateToPageComponents: [+ { pageComponentId: 100, impact: "major_outage" },+ ],+ },+ ],+ } as unknown as ReportDetail;+ const md = generateReport(report, BASE);++ test("breadcrumb roots back to Status › Events", () => {+ expect(md).toContain(`[Status](/.md) › [Events](/events.md) › API latency`);+ });++ test("lifecycle heading, affects, timeline", () => {+ expect(md).toContain("# API latency");+ expect(md).toContain("affects: API");+ expect(md).toContain("### x Monitoring — Jun 18, 12:00 PM");+ expect(md).toContain("Recovering.");+ expect(md).toContain("### x Investigating — Jun 18, 10:00 AM");+ });++ test("each update lists its own impact, operational shown explicitly", () => {+ expect(md).toContain("affects: API (degraded performance)");+ expect(md).toContain("affects: API (major outage)");+ expect(md).toContain("affects: API (operational)");+ });++ test("frontmatter carries page homepage + contact urls", () => {+ const withUrls = generateReport(report, BASE, {+ homepageUrl: "https://acme.com",+ contactUrl: "mailto:[email protected]",+ });+ expect(withUrls).toContain('homepage_url: "https://acme.com"');+ expect(withUrls).toContain('contact_url: "mailto:[email protected]"');+ });+});++describe("generateMaintenance", () => {+ const maintenance = {+ id: 5,+ title: "DB upgrade",+ message: "Brief downtime.",+ from: new Date("2026-06-20T00:00:00.000Z"),+ to: new Date("2026-06-20T01:00:00.000Z"),+ maintenancesToPageComponents: [{ pageComponent: { name: "Database" } }],+ } as unknown as MaintenanceDetail;+ const md = generateMaintenance(maintenance, BASE);++ test("heading, window, components", () => {+ expect(md).toContain("# DB upgrade");+ expect(md).toContain(+ "**Window:** Jun 20, 12:00 AM → Jun 20, 1:00 AM · 1 hour",+ );+ expect(md).toContain("**Affected components:** Database");+ expect(md).toContain("Brief downtime.");+ });++ test("frontmatter carries page homepage + contact urls", () => {+ const withUrls = generateMaintenance(maintenance, BASE, {+ homepageUrl: "https://acme.com",+ contactUrl: "mailto:[email protected]",+ });+ expect(withUrls).toContain('homepage_url: "https://acme.com"');+ expect(withUrls).toContain('contact_url: "mailto:[email protected]"');+ });++ test("null `to` renders 'ongoing', not a bogus duration", () => {+ const openEnded = {+ ...maintenance,+ to: null,+ } as unknown as MaintenanceDetail;+ const out = generateMaintenance(openEnded, BASE);+ expect(out).toContain("**Window:** Jun 20, 12:00 AM → — · ongoing");+ expect(out).not.toContain("1970");+ });+});++describe("generateMonitor", () => {+ const monitor = {+ id: 9,+ name: "API monitor",+ description: "Main API",+ url: "https://api.acme.com",+ data: {+ latency: {+ data: [+ {+ timestamp: 1_717_372_800_000,+ p50Latency: 100,+ p75Latency: 200,+ p95Latency: 300,+ p99Latency: 400,+ },+ {+ timestamp: 1_717_459_200_000,+ p50Latency: 200,+ p75Latency: 300,+ p95Latency: 400,+ p99Latency: 500,+ },+ ],+ },+ regions: {+ data: [+ { region: "ams", p75Latency: 200 },+ { region: "ams", p75Latency: 400 },+ { region: "iad", p75Latency: 100 },+ ],+ },+ uptime: {+ data: [+ { interval: new Date(), success: 90, degraded: 5, error: 5 },+ { interval: new Date(), success: 100, degraded: 0, error: 0 },+ ],+ },+ },+ } as unknown as MonitorDetail;+ const md = generateMonitor(monitor, BASE);++ test("KPI table", () => {+ expect(md).toContain("| Global latency (p75) | 200ms – 300ms |");+ expect(md).toContain("| Region latency | 2 regions · fastest: iad |");+ expect(md).toContain("| Uptime (last 7 days) | 97.50% · 200 checks |");+ });++ test("percentile table", () => {+ expect(md).toContain("| p50 | 150ms |");+ expect(md).toContain("| p99 | 450ms |");+ });++ test("breadcrumb roots back to Status › Monitors", () => {+ expect(md).toContain(+ `[Status](/.md) › [Monitors](/monitors.md) › API monitor`,+ );+ });++ test("per-region p75, slowest first", () => {+ expect(md).toContain("| ams | 300ms |");+ expect(md).toContain("| iad | 100ms |");+ expect(md.indexOf("| ams |")).toBeLessThan(md.indexOf("| iad |"));+ });++ test("no generated-at", () => {+ expect(md).not.toContain("generated-at");+ });++ test("frontmatter carries page homepage + contact urls", () => {+ const withUrls = generateMonitor(monitor, BASE, {+ homepageUrl: "https://acme.com",+ contactUrl: "mailto:[email protected]",+ });+ expect(withUrls).toContain('homepage_url: "https://acme.com"');+ expect(withUrls).toContain('contact_url: "mailto:[email protected]"');+ });+});++describe("frontmatter YAML escaping", () => {+ test("escapes newlines so a title cannot break out of its scalar", () => {+ const md = frontmatter({+ title: 'Acme\nstatus" page\r\nv2',+ description: "line1\nline2",+ baseUrl: BASE,+ canonical: BASE,+ });+ expect(md).toContain('title: "Acme\\nstatus\\" page\\r\\nv2"');+ expect(md).toContain('description: "line1\\nline2"');+ // The title value must stay on a single physical line.+ const titleLine = md.split("\n").find((l) => l.startsWith("title:"));+ expect(titleLine).toBe('title: "Acme\\nstatus\\" page\\r\\nv2"');+ });++ test("escapes tabs and other C0 control characters", () => {+ const md = frontmatter({+ title: "a\tbc",+ description: "",+ baseUrl: BASE,+ canonical: BASE,+ });+ expect(md).toContain('title: "a\\tb\\x01c"');+ });+});++describe("escapeLinkLabel", () => {+ test("escapes brackets so a title cannot break a link label", () => {+ expect(escapeLinkLabel("[API] is down")).toBe("\\[API\\] is down");+ });++ test("leaves bracket-free labels untouched", () => {+ expect(escapeLinkLabel("API latency")).toBe("API latency");+ });+});++describe("navLine", () => {+ test("escapes the label of a linked item", () => {+ expect(navLine([{ label: "[x](evil)", url: "/safe" }])).toBe(+ "[\\[x\\](evil)](/safe)",+ );+ });++ test("leaves plain (unlinked) items untouched", () => {+ expect(+ navLine([{ label: "Status" }, { label: "Events", url: "/e.md" }]),+ ).toBe("Status › [Events](/e.md)");+ });+});++describe("eventLog", () => {+ test("strips a lone CR so a title cannot close the code fence", () => {+ const out = eventLog([+ {+ timestamp: new Date("2026-06-18T14:50:00.000Z"),+ label: "Outage",+ glyph: "x",+ ref: "R-1",+ title: "down\r```\n# injected",+ },+ ]);+ // CommonMark treats a lone CR as a line ending; if it survived, the trailing+ // ``` would start a new line and close the fence early.+ expect(out).not.toContain("\r");+ expect(out.startsWith("```text\n")).toBe(true);+ expect(out.endsWith("\n```")).toBe(true);+ expect(out).toContain("down ``` # injected");+ });+});diff --git a/apps/status-page/src/content/markdown/generators.ts b/apps/status-page/src/content/markdown/generators.tsnew file mode 100644index 000000000..101c3e838--- /dev/null+++ b/apps/status-page/src/content/markdown/generators.ts@@ -0,0 +1,681 @@+import type { RouterOutputs } from "@openstatus/api";++import { flattenComponents, worstComponent } from "../status-vocab";+import {+ canonicalUrl,+ componentImpact,+ componentImpactExplicit,+ dominantDayStatus,+ escapeLinkLabel,+ type EventLogRow,+ eventLog,+ formatDay,+ formatDayTime,+ formatMs,+ formatPercent,+ formatStamp,+ frontmatter,+ humanDuration,+ legend,+ machineReadable,+ mdUrl,+ navLine,+ relativeTime,+ reportStatusGlyph,+ statusGlyph,+ statusLabel,+ table,+ uptimeBar,+ worstImpact,+} from "./helpers";++export type OverviewPage = NonNullable<RouterOutputs["statusPage"]["get"]>;+export type UptimeComponent = NonNullable<+ RouterOutputs["statusPage"]["getUptime"]+>[number];+export type MonitorDetail = NonNullable<+ RouterOutputs["statusPage"]["getMonitor"]+>;+export type ReportDetail = NonNullable<+ RouterOutputs["statusPage"]["getReport"]+>;+export type MaintenanceDetail = NonNullable<+ RouterOutputs["statusPage"]["getMaintenance"]+>;++// Detail payloads don't carry the page's homepage/contact URLs — thread them in+// from getLight so a directly-fetched detail page has those nav anchors.+type PageUrls = { homepageUrl?: string | null; contactUrl?: string | null };++function avg(values: number[]): number | null {+ if (values.length === 0) return null;+ return values.reduce((a, b) => a + b, 0) / values.length;+}++export function generateOverview(+ page: OverviewPage,+ components: UptimeComponent[],+ baseUrl: string,+ showUptime = true,+): string {+ const now = Date.now();+ const out: string[] = [];++ const activeReports = page.statusReports.filter(+ (r) => r.status !== "resolved",+ );+ const activeMaintenance = page.maintenances.filter(+ (m) => m.to && new Date(m.to).getTime() >= now,+ );+ const flatComponents = flattenComponents(page.trackers);++ out.push(+ frontmatter({+ title: page.title,+ description: page.description,+ baseUrl,+ canonical: canonicalUrl(baseUrl),+ homepageUrl: page.homepageUrl,+ contactUrl: page.contactUrl,+ live: {+ status: page.status,+ // Minute-granular so the body (and its ETag) stays stable within the+ // minute, matching the visible timestamp — full precision would bust+ // the conditional-GET window on every request.+ fetchedAt: Math.floor(now / 60_000) * 60_000,+ activeReports: activeReports.length,+ activeMaintenance: activeMaintenance.length,+ componentsOperational: flatComponents.filter(+ (c) => c.status === "success",+ ).length,+ componentsTotal: flatComponents.length,+ worstComponent: worstComponent(flatComponents),+ },+ }),+ );+ out.push(`# ${page.title}\n`);+ out.push(+ `${navLine(+ [+ { label: "**Status**" },+ ...(page.monitors.length > 0+ ? [{ label: "Monitors", url: mdUrl("monitors") }]+ : []),+ { label: "Events", url: mdUrl("events") },+ ],+ " · ",+ )}\n`,+ );+ if (page.description) out.push(`> ${page.description}\n`);+ out.push(+ `\`${statusGlyph(page.status)}\` **${statusLabel(page.status)}** · ${formatStamp(now)}\n`,+ );++ const componentNames = (+ links: { pageComponent?: { name?: string | null } | null }[],+ ) =>+ links+ .map((l) => l.pageComponent?.name)+ .filter((name): name is string => Boolean(name));++ if (activeReports.length > 0) {+ out.push("## Active incidents\n");+ for (const report of activeReports) {+ const latest = report.statusReportUpdates[0];+ const affects = componentNames(report.statusReportsToPageComponents);+ const head = [+ `- ${reportStatusGlyph(report.status)} **${report.title}** — ${statusLabel(report.status)}`,+ affects.length ? `affects: ${affects.join(", ")}` : null,+ mdUrl(`events/report/${report.id}`),+ ].filter(Boolean);+ out.push(head.join(" · "));+ if (latest) out.push(` ${latest.message}`);+ }+ out.push("");+ }++ if (activeMaintenance.length > 0) {+ out.push("## Active & upcoming maintenance\n");+ for (const m of activeMaintenance) {+ const affects = componentNames(m.maintenancesToPageComponents);+ const head = [+ `- ${statusGlyph("info")} **${m.title}** — ${formatDay(m.from)} → ${formatDay(m.to)}`,+ affects.length ? `affects: ${affects.join(", ")}` : null,+ mdUrl(`events/maintenance/${m.id}`),+ ].filter(Boolean);+ out.push(head.join(" · "));+ if (m.message) out.push(` ${m.message}`);+ }+ out.push("");+ }++ out.push("## Components\n");++ // `components` (uptime data) has no stable order and is flat. Drive+ // iteration from `page.trackers` instead — the same ordered, grouped+ // structure the HTML page renders — and join uptime data by id.+ const uptimeById = new Map(components.map((c) => [c.pageComponentId, c]));+ const rows: { groupName: string | null; component: UptimeComponent }[] = [];+ for (const tracker of page.trackers) {+ if (tracker.type === "component") {+ const u = uptimeById.get(tracker.component.id);+ if (u) rows.push({ groupName: null, component: u });+ } else {+ for (const comp of tracker.components) {+ const u = uptimeById.get(comp.id);+ if (u) rows.push({ groupName: tracker.groupName, component: u });+ }+ }+ }+ // Defensive fallback: if trackers and uptime diverge, don't drop components.+ if (rows.length === 0 && components.length > 0) {+ for (const c of components) rows.push({ groupName: null, component: c });+ }++ if (rows.length === 0) {+ out.push("No components.\n");+ } else {+ out.push(`${legend()}\n`);++ const lastActivity = (r: OverviewPage["statusReports"][number]) => {+ const dates = r.statusReportUpdates.map((u) =>+ new Date(u.date).getTime(),+ );+ return dates.length+ ? Math.max(...dates)+ : r.createdAt+ ? new Date(r.createdAt).getTime()+ : 0;+ };++ let currentGroup: string | null = null;+ for (const { groupName, component: c } of rows) {+ if (groupName && groupName !== currentGroup)+ out.push(`### ${groupName}\n`);+ currentGroup = groupName;+ const days = c.data.length;+ const metric = showUptime+ ? c.uptime+ : statusLabel(dominantDayStatus(c.data[c.data.length - 1]?.bar ?? []));+ out.push(`**${c.name}** — ${metric} · \`${days}d ago → today\``);+ out.push(uptimeBar(c.data));++ // Only events within the chart window (c.data is oldest → newest); older+ // ones fall off the bar and live on the /events page.+ const windowStart = c.data[0]?.day+ ? new Date(c.data[0].day).getTime()+ : 0;++ // Link the reports/maintenances that explain this component's colored days.+ const events = [+ ...page.statusReports+ .filter((r) =>+ r.statusReportsToPageComponents.some(+ (x) => x.pageComponentId === c.pageComponentId,+ ),+ )+ .map((r) => ({+ sort: lastActivity(r),+ link: `[${escapeLinkLabel(r.title)}](${mdUrl(`events/report/${r.id}`)})`,+ })),+ ...page.maintenances+ .filter((m) =>+ m.maintenancesToPageComponents.some(+ (x) => x.pageComponentId === c.pageComponentId,+ ),+ )+ .map((m) => ({+ sort: new Date(m.from).getTime(),+ link: `[${escapeLinkLabel(m.title)}](${mdUrl(`events/maintenance/${m.id}`)})`,+ })),+ ]+ .filter((e) => e.sort >= windowStart)+ .sort((a, b) => b.sort - a.sort);++ if (events.length > 0) {+ const shown = events.slice(0, 5).map((e) => e.link);+ const extra = events.length - shown.length;+ const more = extra > 0 ? ` · [+${extra} more](${mdUrl("events")})` : "";+ out.push(`Events: ${shown.join(" · ")}${more}`);+ }+ out.push("");+ }+ }++ if (page.accessType === "public") out.push(machineReadable());++ return `${out.join("\n").trimEnd()}\n`;+}++export function generateMonitorsList(+ page: OverviewPage,+ baseUrl: string,+): string {+ const out: string[] = [];+ out.push(+ frontmatter({+ title: `${page.title} — Monitors`,+ description: `Monitors for ${page.title}`,+ baseUrl,+ canonical: canonicalUrl(baseUrl, "monitors"),+ homepageUrl: page.homepageUrl,+ contactUrl: page.contactUrl,+ }),+ );+ out.push(`# ${page.title} — Monitors\n`);+ out.push(+ `${navLine(+ [+ { label: "Status", url: mdUrl() },+ { label: "**Monitors**" },+ { label: "Events", url: mdUrl("events") },+ ],+ " · ",+ )}\n`,+ );++ if (page.monitors.length === 0) {+ out.push("No public monitors.\n");+ } else {+ const rows = page.monitors.map((m) => [+ `${statusGlyph(m.status)} ${m.name}`,+ statusLabel(m.status),+ mdUrl(`monitors/${m.id}`),+ ]);+ out.push(table(["Monitor", "Status", "Details"], rows));+ out.push("");+ }++ return `${out.join("\n").trimEnd()}\n`;+}++export function generateEventsList(+ page: OverviewPage,+ baseUrl: string,+): string {+ const now = Date.now();+ const out: string[] = [];+ out.push(+ frontmatter({+ title: `${page.title} — Events`,+ description: `Incident history and maintenance for ${page.title}`,+ baseUrl,+ canonical: canonicalUrl(baseUrl, "events"),+ homepageUrl: page.homepageUrl,+ contactUrl: page.contactUrl,+ }),+ );+ out.push(`# ${page.title} — Events · Reports\n`);+ out.push(+ `${navLine(+ [+ { label: "Status", url: mdUrl() },+ ...(page.monitors.length > 0+ ? [{ label: "Monitors", url: mdUrl("monitors") }]+ : []),+ { label: "**Events**" },+ ],+ " · ",+ )}\n`,+ );++ const logRows: EventLogRow[] = [];+ for (const report of page.statusReports) {+ for (const update of report.statusReportUpdates) {+ logRows.push({+ timestamp: update.date,+ label: statusLabel(update.status).toUpperCase(),+ glyph: reportStatusGlyph(update.status),+ ref: `report/${report.id}`,+ title: report.title,+ });+ }+ }+ for (const m of page.maintenances) {+ logRows.push({+ timestamp: m.from,+ label: "MAINTENANCE",+ glyph: statusGlyph("info"),+ ref: `maintenance/${m.id}`,+ title: m.title,+ });+ // Only log a COMPLETED entry once the window has actually ended. (`m.to`+ // is non-null per schema; the truthy check is just defensive.)+ if (m.to && new Date(m.to).getTime() <= now) {+ logRows.push({+ timestamp: m.to,+ label: "COMPLETED",+ glyph: statusGlyph("success"),+ ref: `maintenance/${m.id}`,+ title: m.title,+ });+ }+ }+ if (logRows.length > 0) {+ out.push("## Event log\n");+ out.push(`${eventLog(logRows)}\n`);+ }++ if (page.statusReports.length === 0) {+ out.push("No status reports.\n");+ } else {+ for (const report of page.statusReports) {+ const updates = report.statusReportUpdates;+ const oldest = updates[updates.length - 1];+ const start = oldest?.date ?? report.createdAt;++ const componentName = new Map<number, string>();+ for (const c of report.statusReportsToPageComponents) {+ if (c.pageComponent?.name)+ componentName.set(c.pageComponentId, c.pageComponent.name);+ }++ // Worst impact each component reached over the report's lifetime.+ const impactByComponent = new Map<number, string>();+ for (const u of updates) {+ for (const ci of u.statusReportUpdateToPageComponents ?? []) {+ const prev = impactByComponent.get(ci.pageComponentId);+ impactByComponent.set(+ ci.pageComponentId,+ prev ? (worstImpact([prev, ci.impact]) ?? ci.impact) : ci.impact,+ );+ }+ }+ const affects = report.statusReportsToPageComponents+ .map((c) => {+ const name = c.pageComponent?.name;+ if (!name) return null;+ return componentImpact(+ name,+ impactByComponent.get(c.pageComponentId),+ );+ })+ .filter((v): v is string => Boolean(v));++ const meta = [+ start ? formatDay(start) : null,+ start ? relativeTime(start, now) : null,+ affects.length ? `affects: ${affects.join(", ")}` : null,+ oldest && updates[0]+ ? humanDuration(oldest.date, updates[0].date)+ : null,+ ].filter(Boolean);++ out.push(+ `### [${escapeLinkLabel(report.title)}](${mdUrl(`events/report/${report.id}`)})`,+ );+ if (meta.length) out.push(`${meta.join(" · ")}`);+ for (const update of updates) {+ const updateAffects = (update.statusReportUpdateToPageComponents ?? [])+ .map((ci) => {+ const name = componentName.get(ci.pageComponentId);+ return name ? componentImpactExplicit(name, ci.impact) : null;+ })+ .filter((v): v is string => Boolean(v));+ const head = `- ${reportStatusGlyph(update.status)} ${statusLabel(update.status)} — ${formatDayTime(update.date)}`;+ out.push(+ updateAffects.length ? `${head} · ${updateAffects.join(", ")}` : head,+ );+ }+ out.push("");+ }+ }++ if (page.maintenances.length > 0) {+ out.push("## Maintenance\n");+ for (const m of page.maintenances) {+ const affects = m.maintenancesToPageComponents+ .map((c) => c.pageComponent?.name)+ .filter((name): name is string => Boolean(name));+ const meta = [+ formatDay(m.from),+ m.to ? humanDuration(m.from, m.to) : null,+ affects.length ? `affects: ${affects.join(", ")}` : null,+ ].filter(Boolean);+ out.push(+ `### [${escapeLinkLabel(m.title)}](${mdUrl(`events/maintenance/${m.id}`)})`,+ );+ out.push(meta.join(" · "));+ out.push("");+ }+ }++ return `${out.join("\n").trimEnd()}\n`;+}++export function generateReport(+ report: ReportDetail,+ baseUrl: string,+ page?: PageUrls,+): string {+ const now = Date.now();+ const updates = report.statusReportUpdates;+ const oldest = updates[updates.length - 1];+ const latest = updates[0];++ const componentName = new Map<number, string>();+ for (const c of report.statusReportsToPageComponents) {+ if (c.pageComponent?.name)+ componentName.set(c.pageComponentId, c.pageComponent.name);+ }+ const components = report.statusReportsToPageComponents+ .map((c) => c.pageComponent?.name)+ .filter((name): name is string => Boolean(name));++ const description =+ [+ latest ? statusLabel(latest.status) : null,+ components.length ? `affects ${components.join(", ")}` : null,+ oldest ? formatDay(oldest.date) : null,+ ]+ .filter(Boolean)+ .join(" · ") || `Status report: ${report.title}`;++ const out: string[] = [];+ out.push(+ frontmatter({+ title: report.title,+ description,+ baseUrl,+ canonical: canonicalUrl(baseUrl, `events/report/${report.id}`),+ homepageUrl: page?.homepageUrl,+ contactUrl: page?.contactUrl,+ }),+ );+ out.push(`# ${report.title}\n`);+ out.push(+ `${navLine([+ { label: "Status", url: mdUrl() },+ { label: "Events", url: mdUrl("events") },+ { label: report.title },+ ])}\n`,+ );+ const meta = [+ oldest+ ? `${formatDay(oldest.date)} · ${relativeTime(oldest.date, now)}`+ : null,+ components.length ? `affects: ${components.join(", ")}` : null,+ oldest && updates[0] ? humanDuration(oldest.date, updates[0].date) : null,+ ].filter(Boolean);+ if (meta.length) out.push(`${meta.join(" · ")}\n`);++ out.push("## Updates\n");+ if (updates.length === 0) {+ out.push("No updates.\n");+ } else {+ for (const update of updates) {+ const updateAffects = (update.statusReportUpdateToPageComponents ?? [])+ .map((ci) => {+ const name = componentName.get(ci.pageComponentId);+ return name ? componentImpactExplicit(name, ci.impact) : null;+ })+ .filter((v): v is string => Boolean(v));+ out.push(+ `### ${reportStatusGlyph(update.status)} ${statusLabel(update.status)} — ${formatDayTime(update.date)}\n`,+ );+ if (updateAffects.length)+ out.push(`affects: ${updateAffects.join(", ")}\n`);+ out.push(`${update.message}\n`);+ }+ }++ return `${out.join("\n").trimEnd()}\n`;+}++export function generateMaintenance(+ maintenance: MaintenanceDetail,+ baseUrl: string,+ page?: PageUrls,+): string {+ const out: string[] = [];+ out.push(+ frontmatter({+ title: maintenance.title,+ description: `Maintenance: ${maintenance.title}`,+ baseUrl,+ canonical: canonicalUrl(baseUrl, `events/maintenance/${maintenance.id}`),+ homepageUrl: page?.homepageUrl,+ contactUrl: page?.contactUrl,+ }),+ );+ out.push(`# ${maintenance.title}\n`);+ out.push(+ `${navLine([+ { label: "Status", url: mdUrl() },+ { label: "Events", url: mdUrl("events") },+ { label: maintenance.title },+ ])}\n`,+ );+ const windowLine = [+ `${formatDayTime(maintenance.from)} → ${formatDayTime(maintenance.to)}`,+ maintenance.to+ ? humanDuration(maintenance.from, maintenance.to)+ : "ongoing",+ ].join(" · ");+ out.push(`**Window:** ${windowLine}\n`);++ const components = maintenance.maintenancesToPageComponents+ .map((c) => c.pageComponent?.name)+ .filter((name): name is string => Boolean(name));+ if (components.length > 0) {+ out.push(`**Affected components:** ${components.join(", ")}\n`);+ }++ out.push("## Details\n");+ out.push(`${maintenance.message}\n`);++ return `${out.join("\n").trimEnd()}\n`;+}++export function generateMonitor(+ monitor: MonitorDetail,+ baseUrl: string,+ page?: PageUrls,+): string {+ const out: string[] = [];+ out.push(+ frontmatter({+ title: monitor.name,+ description: `Monitor metrics for ${monitor.name} (last 7 days)`,+ baseUrl,+ canonical: canonicalUrl(baseUrl, `monitors/${monitor.id}`),+ homepageUrl: page?.homepageUrl,+ contactUrl: page?.contactUrl,+ }),+ );+ out.push(`# ${monitor.name}\n`);+ out.push(+ `${navLine([+ { label: "Status", url: mdUrl() },+ { label: "Monitors", url: mdUrl("monitors") },+ { label: monitor.name },+ ])}\n`,+ );+ if (monitor.description) out.push(`> ${monitor.description}\n`);++ const latencyData = [...(monitor.data.latency?.data ?? [])].sort(+ (a, b) => a.timestamp - b.timestamp,+ );+ const p75Series = latencyData.map((d) => d.p75Latency);++ // Uptime over the hardcoded 7-day window.+ const uptimeData = monitor.data.uptime?.data ?? [];+ const totals = uptimeData.reduce(+ (acc, d) => ({+ success: acc.success + d.success,+ degraded: acc.degraded + d.degraded,+ error: acc.error + d.error,+ }),+ { success: 0, degraded: 0, error: 0 },+ );+ const totalChecks = totals.success + totals.degraded + totals.error;+ const uptime =+ totalChecks > 0+ ? formatPercent((totals.success + totals.degraded) / totalChecks)+ : "N/A";++ // Per-region p75 (mean across the window).+ const regionData = monitor.data.regions?.data ?? [];+ const byRegion = new Map<string, number[]>();+ for (const d of regionData) {+ const list = byRegion.get(d.region) ?? [];+ if (d.p75Latency !== null && d.p75Latency !== undefined) {+ list.push(d.p75Latency);+ }+ byRegion.set(d.region, list);+ }+ const regionAverages = Array.from(byRegion.entries())+ .map(([region, values]) => ({ region, p75: avg(values) }))+ .sort((a, b) => (a.p75 ?? Infinity) - (b.p75 ?? Infinity));+ const fastest = regionAverages[0]?.region;++ const p75Min = p75Series.length ? Math.min(...p75Series) : null;+ const p75Max = p75Series.length ? Math.max(...p75Series) : null;++ out.push(+ table(+ ["Metric", "Value"],+ [+ [+ "Global latency (p75)",+ p75Min !== null ? `${formatMs(p75Min)} – ${formatMs(p75Max)}` : "—",+ ],+ [+ "Region latency",+ byRegion.size+ ? `${byRegion.size} regions · fastest: ${fastest}`+ : "—",+ ],+ ["Uptime (last 7 days)", `${uptime} · ${totalChecks} checks`],+ ],+ ),+ );+ out.push("");++ out.push("## Latency percentiles (last 7 days)\n");+ out.push(+ table(+ ["Quantile", "Latency"],+ [+ ["p50", formatMs(avg(latencyData.map((d) => d.p50Latency)))],+ ["p75", formatMs(avg(p75Series))],+ ["p95", formatMs(avg(latencyData.map((d) => d.p95Latency)))],+ ["p99", formatMs(avg(latencyData.map((d) => d.p99Latency)))],+ ],+ ),+ );+ out.push("");++ out.push("## Latency by region — p75 (last 7 days)\n");+ if (regionAverages.length === 0) {+ out.push("No regional data.\n");+ } else {+ const rows = [...regionAverages]+ .sort((a, b) => (b.p75 ?? 0) - (a.p75 ?? 0))+ .map((r) => [r.region, formatMs(r.p75)]);+ out.push(table(["Region", "p75"], rows));+ out.push("");+ }++ return `${out.join("\n").trimEnd()}\n`;+}diff --git a/apps/status-page/src/content/markdown/helpers.ts b/apps/status-page/src/content/markdown/helpers.tsnew file mode 100644index 000000000..ce00d1ddc--- /dev/null+++ b/apps/status-page/src/content/markdown/helpers.ts@@ -0,0 +1,467 @@+import { isoOrNull } from "../status-vocab";++export type ComponentStatus = "success" | "degraded" | "error" | "info";++export type ReportStatus =+ | "investigating"+ | "identified"+ | "monitoring"+ | "resolved"+ | "maintenance";++const COMPONENT_STATUS_LABELS: Record<ComponentStatus, string> = {+ success: "Operational",+ degraded: "Degraded",+ error: "Outage",+ info: "Maintenance",+};++const REPORT_STATUS_LABELS: Record<ReportStatus, string> = {+ investigating: "Investigating",+ identified: "Identified",+ monitoring: "Monitoring",+ resolved: "Resolved",+ maintenance: "Maintenance",+};++export function statusLabel(status: string): string {+ if (status in COMPONENT_STATUS_LABELS) {+ return COMPONENT_STATUS_LABELS[status as ComponentStatus];+ }+ if (status in REPORT_STATUS_LABELS) {+ return REPORT_STATUS_LABELS[status as ReportStatus];+ }+ return status;+}++/** Quote a value as a double-quoted YAML scalar. Every C0 control char must be+ * escaped — a literal newline/tab splits or corrupts the scalar and parsers+ * disagree on the result. */+function escapeYaml(value: string): string {+ let out = '"';+ for (const ch of value) {+ const code = ch.charCodeAt(0);+ if (ch === "\\") out += "\\\\";+ else if (ch === '"') out += '\\"';+ else if (ch === "\n") out += "\\n";+ else if (ch === "\r") out += "\\r";+ else if (ch === "\t") out += "\\t";+ else if (code < 0x20) out += `\\x${code.toString(16).padStart(2, "0")}`;+ else out += ch;+ }+ return `${out}"`;+}++/**+ * Live page state carried in frontmatter so an agent gets the answer from the+ * top ~10 lines without tokenizing the body. `fetched_at` is the snapshot's+ * generation time (truthful freshness signal); HTTP ETag/Cache-Control carry+ * the rest.+ */+export interface FrontmatterLive {+ status: string;+ fetchedAt: Date | string | number | null | undefined;+ activeReports: number;+ activeMaintenance: number;+ componentsOperational: number;+ componentsTotal: number;+ worstComponent?: string | null;+}++export function frontmatter(fields: {+ title: string;+ description: string;+ baseUrl: string;+ canonical: string;+ homepageUrl?: string | null;+ contactUrl?: string | null;+ live?: FrontmatterLive;+}): string {+ const lines = [+ "---",+ `title: ${escapeYaml(fields.title)}`,+ `description: ${escapeYaml(fields.description)}`,+ // Origin the root-relative in-body links resolve against.+ `base_url: ${escapeYaml(fields.baseUrl)}`,+ `canonical: ${escapeYaml(fields.canonical)}`,+ ];+ if (fields.homepageUrl)+ lines.push(`homepage_url: ${escapeYaml(fields.homepageUrl)}`);+ if (fields.contactUrl)+ lines.push(`contact_url: ${escapeYaml(fields.contactUrl)}`);+ if (fields.live) {+ const fetched = isoOrNull(fields.live.fetchedAt);+ lines.push(`status: ${escapeYaml(fields.live.status)}`);+ if (fetched) lines.push(`fetched_at: ${escapeYaml(fetched)}`);+ lines.push(`active_reports: ${fields.live.activeReports}`);+ lines.push(`active_maintenance: ${fields.live.activeMaintenance}`);+ lines.push(`components_operational: ${fields.live.componentsOperational}`);+ lines.push(`components_total: ${fields.live.componentsTotal}`);+ if (fields.live.worstComponent)+ lines.push(`worst_component: ${escapeYaml(fields.live.worstComponent)}`);+ }+ lines.push("---");+ return `${lines.join("\n")}\n`;+}++/** Escape a markdown table cell — pipes and newlines would break the row. */+export function escapeCell(value: string): string {+ // Escape backslash first so the pipe-escaping we add isn't re-escaped.+ return value+ .replace(/\\/g, "\\\\")+ .replace(/\|/g, "\\|")+ .replace(/[\r\n]+/g, " ")+ .trim();+}++/** Escape a value used as a markdown link label — `[`/`]` would break `[text](url)`. */+export function escapeLinkLabel(value: string): string {+ return value.replace(/\\/g, "\\\\").replace(/[[\]]/g, "\\$&");+}++export function table(headers: string[], rows: string[][]): string {+ const head = `| ${headers.map((cell) => escapeCell(cell)).join(" | ")} |`;+ const divider = `| ${headers.map(() => "---").join(" | ")} |`;+ const body = rows+ .map((row) => `| ${row.map((cell) => escapeCell(cell)).join(" | ")} |`)+ .join("\n");+ return body ? `${head}\n${divider}\n${body}` : `${head}\n${divider}`;+}++export function formatDate(+ date: Date | string | number | null | undefined,+): string {+ if (date === null || date === undefined) return "—";+ const d = date instanceof Date ? date : new Date(date);+ if (Number.isNaN(d.getTime())) return "—";+ return d.toISOString();+}++export function formatMs(value: number | null | undefined): string {+ if (value === null || value === undefined || Number.isNaN(value)) return "—";+ return `${Math.round(value)}ms`;+}++export function formatPercent(ratio: number): string {+ return `${(ratio * 100).toFixed(2)}%`;+}++/** Build the public-facing canonical (HTML) URL for a path under a page. */+export function canonicalUrl(baseUrl: string, path = ""): string {+ return path ? `${baseUrl}/${path.replace(/^\//, "")}` : baseUrl;+}++/**+ * Root-relative `.md` link for a path under a page (root → `/.md`). Relative on+ * purpose: the frontmatter `canonical` carries the absolute base, so in-body+ * links need not repeat the host.+ */+export function mdUrl(path = ""): string {+ const clean = path.replace(/^\//, "");+ return clean ? `/${clean}.md` : "/.md";+}++/**+ * A breadcrumb / peer-nav line. Items with a `url` render as links; the current+ * item (no `url`) renders as plain text. Use ` › ` for hierarchy, ` · ` for peers.+ */+export function navLine(+ items: { label: string; url?: string }[],+ separator = " › ",+): string {+ return items+ .map((i) =>+ i.url+ ? `[${escapeLinkLabel(i.label)}](${i.url})`+ : escapeLinkLabel(i.label),+ )+ .join(separator);+}++export type DayStatus = "success" | "degraded" | "error" | "info" | "empty";++// ASCII status markers: 1 column, monospace-stable, markdown-inert. Markdown has+// no color, so shape carries the meaning — `x` reads as down/outage.+const STATUS_GLYPH: Record<DayStatus, string> = {+ success: "+",+ degraded: "~",+ error: "x",+ info: "=",+ empty: ".",+};++const DAY_PRIORITY: Record<DayStatus, number> = {+ error: 3,+ degraded: 2,+ info: 1,+ success: 0,+ empty: -1,+};++export function statusGlyph(status: string): string {+ return STATUS_GLYPH[status as DayStatus] ?? STATUS_GLYPH.empty;+}++const LEGEND_LABELS: Record<DayStatus, string> = {+ success: "Operational",+ degraded: "Degraded",+ error: "Outage",+ info: "Maintenance",+ empty: "No data",+};++const LEGEND_ORDER: DayStatus[] = [+ "success",+ "degraded",+ "error",+ "info",+ "empty",+];++/** Legend line covering every status, in severity order. */+export function legend(): string {+ // Glyphs in code spans so they render in the same monospace as the bar they+ // explain — a bare `.` / `~` is otherwise easy to miss or misread.+ const parts = LEGEND_ORDER.map(+ (s) => `\`${STATUS_GLYPH[s]}\` ${LEGEND_LABELS[s]}`,+ );+ return `Legend: ${parts.join(" · ")}`;+}++// Severity order mirrors `pageComponentImpact` in @openstatus/db; kept local so+// the generators stay types-only against the API and don't value-import the schema.+const IMPACT_ORDER = [+ "operational",+ "degraded_performance",+ "partial_outage",+ "major_outage",+];++const IMPACT_LABELS: Record<string, string> = {+ operational: "operational",+ degraded_performance: "degraded performance",+ partial_outage: "partial outage",+ major_outage: "major outage",+};++export function impactLabel(impact: string): string {+ return IMPACT_LABELS[impact] ?? impact;+}++/** "name (impact label)", dropping the impact when operational/absent. */+export function componentImpact(name: string, impact?: string | null): string {+ return impact && impact !== "operational"+ ? `${name} (${impactLabel(impact)})`+ : name;+}++/**+ * Like `componentImpact` but always shows the impact label, even operational —+ * for a single update's affects line, where every component has a declared+ * impact and dropping operational would read as inconsistent against siblings.+ */+export function componentImpactExplicit(+ name: string,+ impact?: string | null,+): string {+ return impact ? `${name} (${impactLabel(impact)})` : name;+}++/** Most severe impact among the given values, or null if empty. */+export function worstImpact(impacts: string[]): string | null {+ let worst: string | null = null;+ for (const i of impacts) {+ if (+ worst === null ||+ IMPACT_ORDER.indexOf(i) > IMPACT_ORDER.indexOf(worst)+ ) {+ worst = i;+ }+ }+ return worst;+}++/** Status glyph for a report/update lifecycle status (resolved → `+`, etc.). */+export function reportStatusGlyph(status: string): string {+ if (status === "resolved") return STATUS_GLYPH.success;+ if (status === "maintenance") return STATUS_GLYPH.info;+ return STATUS_GLYPH.error;+}++/** Collapse a day's stacked bar segments to the single worst (most severe) status. */+export function dominantDayStatus(+ bar: { status: string; height: number }[],+): DayStatus {+ let best: DayStatus = "empty";+ for (const seg of bar) {+ const status = seg.status as DayStatus;+ if (seg.height > 0 && (DAY_PRIORITY[status] ?? -1) > DAY_PRIORITY[best]) {+ best = status;+ }+ }+ return best;+}++/**+ * One ASCII cell per day, oldest → newest, in a code span. The code span pins+ * the bar to monospace (cells stay aligned) and keeps it markdown-inert — a run+ * of `~~` days would otherwise parse as strikethrough.+ */+export function uptimeBar(+ days: { bar: { status: string; height: number }[] }[],+): string {+ if (days.length === 0) return "";+ return `\`${days.map((d) => statusGlyph(dominantDayStatus(d.bar))).join("")}\``;+}++const MONTHS = [+ "Jan",+ "Feb",+ "Mar",+ "Apr",+ "May",+ "Jun",+ "Jul",+ "Aug",+ "Sep",+ "Oct",+ "Nov",+ "Dec",+];++function toDate(date: Date | string | number): Date {+ return date instanceof Date ? date : new Date(date);+}++/** "Jan 25, 2026" (UTC, deterministic). */+export function formatDay(date: Date | string | number): string {+ const d = toDate(date);+ return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;+}++/** "Feb 3, 1:42 PM" (UTC, deterministic). Null/invalid → "—". */+export function formatDayTime(+ date: Date | string | number | null | undefined,+): string {+ if (date === null || date === undefined) return "—";+ const d = toDate(date);+ if (Number.isNaN(d.getTime())) return "—";+ const h = d.getUTCHours();+ const period = h < 12 ? "AM" : "PM";+ const hour12 = h % 12 === 0 ? 12 : h % 12;+ const minutes = String(d.getUTCMinutes()).padStart(2, "0");+ return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${hour12}:${minutes} ${period}`;+}++/** "2026-06-18 14:50" (UTC, sortable, fixed-width). */+export function formatLogStamp(date: Date | string | number): string {+ const d = toDate(date);+ const yyyy = d.getUTCFullYear();+ const mm = String(d.getUTCMonth() + 1).padStart(2, "0");+ const dd = String(d.getUTCDate()).padStart(2, "0");+ const hh = String(d.getUTCHours()).padStart(2, "0");+ const min = String(d.getUTCMinutes()).padStart(2, "0");+ return `${yyyy}-${mm}-${dd} ${hh}:${min}`;+}++export type EventLogRow = {+ timestamp: Date | string | number;+ label: string;+ glyph: string;+ ref: string;+ title: string;+};++/**+ * Greppable event log: one update per line, sortable stamp first, newest first.+ * Structured columns (stamp/status/ref/glyph) precede the user-authored title,+ * which trails as free text. Newlines are stripped from the title so it can't+ * inject a line that closes the fenced block.+ */+export function eventLog(rows: EventLogRow[]): string {+ if (rows.length === 0) return "";+ const sorted = [...rows].sort(+ (a, b) => toDate(b.timestamp).getTime() - toDate(a.timestamp).getTime(),+ );+ const statusW = Math.max(6, ...sorted.map((r) => r.label.length));+ const refW = Math.max(5, ...sorted.map((r) => r.ref.length));+ const header = `# ${"timestamp".padEnd(16)} ${"status".padEnd(statusW)} event`;+ const lines = sorted.map(+ (r) =>+ `${formatLogStamp(r.timestamp)} ${r.label.padEnd(statusW)} ${r.ref.padEnd(refW)} ${r.glyph} ${r.title.replace(/[\r\n]+/g, " ")}`,+ );+ return ["```text", header, ...lines, "```"].join("\n");+}++/** "Jun 18, 2026 14:50 (GMT+0)" (UTC, deterministic). */+export function formatStamp(date: Date | string | number): string {+ const d = toDate(date);+ const hh = String(d.getUTCHours()).padStart(2, "0");+ const mm = String(d.getUTCMinutes()).padStart(2, "0");+ return `${MONTHS[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()} ${hh}:${mm} (GMT+0)`;+}++const MINUTE = 60_000;+const HOUR = 60 * MINUTE;+const DAY = 24 * HOUR;+const MONTH = 30 * DAY;+const YEAR = 365 * DAY;++function coarseSpan(ms: number): string {+ if (ms < HOUR) {+ const m = Math.max(1, Math.round(ms / MINUTE));+ return `${m} ${m === 1 ? "minute" : "minutes"}`;+ }+ if (ms < DAY) {+ const h = Math.round(ms / HOUR);+ return `${h} ${h === 1 ? "hour" : "hours"}`;+ }+ if (ms < MONTH) {+ const d = Math.round(ms / DAY);+ return `${d} ${d === 1 ? "day" : "days"}`;+ }+ if (ms < YEAR) {+ const m = Math.round(ms / MONTH);+ return `${m} ${m === 1 ? "month" : "months"}`;+ }+ const y = Math.round(ms / YEAR);+ return `${y} ${y === 1 ? "year" : "years"}`;+}++/** "4 months ago" relative to `now`. */+export function relativeTime(+ date: Date | string | number,+ now: number,+): string {+ const ms = now - toDate(date).getTime();+ if (ms < MINUTE) return "just now";+ return `${coarseSpan(ms)} ago`;+}++/** Human duration between two instants: "9 days", "23 hours". */+export function humanDuration(+ from: Date | string | number,+ to: Date | string | number,+): string {+ return coarseSpan(Math.max(0, toDate(to).getTime() - toDate(from).getTime()));+}++/**+ * Pointer to machine-readable formats, for agents that enter via a `.md` link+ * and never see `llms.txt`. Public pages only — a gated page must not advertise+ * JSON endpoints that may not honor its access gate.+ */+export function machineReadable(): string {+ return "Machine-readable: [current.json](/api/status/current.json) · [summary.json](/api/status/summary.json) · [more](/llms.txt)";+}++/** Attribution footer appended to every doc unless the page is white-labeled. */+export function poweredByFooter(): string {+ return "---\n\n_Powered by [openstatus.dev](https://openstatus.dev)_\n";+}++/** Append the attribution footer to rendered markdown unless white-labeled. */+export function withPoweredBy(markdown: string, whiteLabel: boolean): string {+ if (whiteLabel) return markdown;+ return `${markdown}\n${poweredByFooter()}`;+}diff --git a/apps/status-page/src/content/markdown/index.ts b/apps/status-page/src/content/markdown/index.tsnew file mode 100644index 000000000..b31795097--- /dev/null+++ b/apps/status-page/src/content/markdown/index.ts@@ -0,0 +1,18 @@+export { matchMarkdownRoute, parseMarkdownPath } from "./match-route";+export type { MarkdownTarget } from "./match-route";+export { escapeLinkLabel, poweredByFooter, withPoweredBy } from "./helpers";+export {+ generateEventsList,+ generateMaintenance,+ generateMonitor,+ generateMonitorsList,+ generateOverview,+ generateReport,+} from "./generators";+export type {+ MaintenanceDetail,+ MonitorDetail,+ OverviewPage,+ ReportDetail,+ UptimeComponent,+} from "./generators";diff --git a/apps/status-page/src/content/markdown/match-route.test.ts b/apps/status-page/src/content/markdown/match-route.test.tsnew file mode 100644index 000000000..7000f38d9--- /dev/null+++ b/apps/status-page/src/content/markdown/match-route.test.ts@@ -0,0 +1,93 @@+import { describe, expect, test } from "bun:test";++import { matchMarkdownRoute, parseMarkdownPath } from "./match-route";++describe("parseMarkdownPath", () => {+ test("missing slug → null", () => {+ expect(parseMarkdownPath([])).toBeNull();+ });++ test("slug only → overview rest", () => {+ expect(parseMarkdownPath(["acme"])).toEqual({ slug: "acme", rest: [] });+ });++ test("drops a present locale segment", () => {+ expect(parseMarkdownPath(["acme", "de", "monitors", "123"])).toEqual({+ slug: "acme",+ rest: ["monitors", "123"],+ });+ });++ test("keeps a non-locale second segment (locale-less request)", () => {+ expect(parseMarkdownPath(["acme", "monitors", "123"])).toEqual({+ slug: "acme",+ rest: ["monitors", "123"],+ });+ });++ test("locale only, no rest", () => {+ expect(parseMarkdownPath(["acme", "fr"])).toEqual({+ slug: "acme",+ rest: [],+ });+ });+});++describe("matchMarkdownRoute", () => {+ test("empty → overview", () => {+ expect(matchMarkdownRoute([])).toEqual({ kind: "overview" });+ });++ test("monitors list", () => {+ expect(matchMarkdownRoute(["monitors"])).toEqual({ kind: "monitors" });+ });++ test("monitor detail with numeric id", () => {+ expect(matchMarkdownRoute(["monitors", "123"])).toEqual({+ kind: "monitor",+ id: 123,+ });+ });++ test("events list", () => {+ expect(matchMarkdownRoute(["events"])).toEqual({ kind: "events" });+ });++ test("report detail", () => {+ expect(matchMarkdownRoute(["events", "report", "7"])).toEqual({+ kind: "report",+ id: 7,+ });+ });++ test("maintenance detail", () => {+ expect(matchMarkdownRoute(["events", "maintenance", "42"])).toEqual({+ kind: "maintenance",+ id: 42,+ });+ });++ test("non-numeric monitor id → null", () => {+ expect(matchMarkdownRoute(["monitors", "abc"])).toBeNull();+ });++ test("report missing id → null", () => {+ expect(matchMarkdownRoute(["events", "report"])).toBeNull();+ });++ test("report with trailing extra segment → null", () => {+ expect(matchMarkdownRoute(["events", "report", "1", "extra"])).toBeNull();+ });++ test("unknown tail → null", () => {+ expect(matchMarkdownRoute(["foo"])).toBeNull();+ });++ test("monitor id zero → null", () => {+ expect(matchMarkdownRoute(["monitors", "0"])).toBeNull();+ });++ test("unknown event subtype → null", () => {+ expect(matchMarkdownRoute(["events", "incident", "1"])).toBeNull();+ });+});diff --git a/apps/status-page/src/content/markdown/match-route.ts b/apps/status-page/src/content/markdown/match-route.tsnew file mode 100644index 000000000..2f9b1b0aa--- /dev/null+++ b/apps/status-page/src/content/markdown/match-route.ts@@ -0,0 +1,61 @@+import { locales } from "@openstatus/locales";++export type MarkdownTarget =+ | { kind: "overview" | "monitors" | "events" }+ | { kind: "monitor" | "report" | "maintenance"; id: number };++/**+ * Split the catch-all path into the page slug and rest-segments. Markdown is+ * locale-agnostic, so a locale segment is dropped — but only when actually+ * present, otherwise a real path segment would be consumed. Returns null when+ * the slug is missing.+ */+export function parseMarkdownPath(+ path: string[],+): { slug: string; rest: string[] } | null {+ const [slug, second, ...tail] = path;+ if (!slug) return null;+ const isLocale = (locales as readonly string[]).includes(second);+ const rest = isLocale ? tail : [second, ...tail].filter(Boolean);+ return { slug, rest };+}++function parseId(value: string | undefined): number | null {+ if (!value || !/^\d+$/.test(value)) return null;+ const id = Number(value);+ return Number.isSafeInteger(id) && id > 0 ? id : null;+}++/**+ * Pure dispatch over the catch-all rest-segments (everything after slug/locale).+ * Returns null for unknown shapes so the handler can 404.+ */+export function matchMarkdownRoute(rest: string[]): MarkdownTarget | null {+ const [first, second, third] = rest;++ if (rest.length === 0) return { kind: "overview" };++ if (first === "monitors") {+ if (rest.length === 1) return { kind: "monitors" };+ if (rest.length === 2) {+ const id = parseId(second);+ return id === null ? null : { kind: "monitor", id };+ }+ return null;+ }++ if (first === "events") {+ if (rest.length === 1) return { kind: "events" };+ if (+ rest.length === 3 &&+ (second === "report" || second === "maintenance")+ ) {+ const id = parseId(third);+ if (id === null) return null;+ return { kind: second === "report" ? "report" : "maintenance", id };+ }+ return null;+ }++ return null;+}diff --git a/apps/status-page/src/content/status-json.test.ts b/apps/status-page/src/content/status-json.test.tsnew file mode 100644index 000000000..70e450c20--- /dev/null+++ b/apps/status-page/src/content/status-json.test.ts@@ -0,0 +1,154 @@+import { describe, expect, test } from "bun:test";++import type { RouterOutputs } from "@openstatus/api";++import {+ matchEndpoint,+ toStatus,+ toSummary,+ toUnresolvedIncidents,+} from "./status-json";++describe("matchEndpoint", () => {+ test("single endpoint segment, no slug", () => {+ expect(matchEndpoint(["summary.json"])).toEqual({+ endpoint: "summary",+ slug: null,+ });+ expect(matchEndpoint(["current.json"])).toEqual({+ endpoint: "status",+ slug: null,+ });+ expect(matchEndpoint(["incidents.json"])).toEqual({+ endpoint: "incidents",+ slug: null,+ });+ });++ test("path-based slug + endpoint", () => {+ expect(matchEndpoint(["acme", "summary.json"])).toEqual({+ endpoint: "summary",+ slug: "acme",+ });+ });++ test("unknown endpoint → null", () => {+ expect(matchEndpoint(["acme", "unknown.json"])).toBeNull();+ expect(matchEndpoint(["summary"])).toBeNull();+ });++ test("empty or too-long paths → null", () => {+ expect(matchEndpoint([])).toBeNull();+ expect(matchEndpoint(["a", "b", "summary.json"])).toBeNull();+ });+});++type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;++const BASE = "https://acme.openstatus.dev";+const NOW = new Date("2026-06-19T12:00:00.000Z").getTime();++const page = {+ title: "Acme Status",+ status: "degraded",+ slug: "acme",+ customDomain: null,+ updatedAt: new Date("2026-06-19T11:00:00.000Z"),+ trackers: [+ {+ type: "component",+ component: { name: "API", status: "error" },+ order: 0,+ },+ {+ type: "group",+ groupName: "Edge",+ components: [{ name: "CDN", status: "success" }],+ status: "success",+ order: 1,+ },+ ],+ statusReports: [+ {+ id: 1,+ title: "API latency",+ status: "investigating",+ createdAt: new Date("2026-06-19T10:00:00.000Z"),+ statusReportUpdates: [+ {+ status: "investigating",+ message: "Looking into it.",+ date: new Date("2026-06-19T10:30:00.000Z"),+ },+ ],+ },+ {+ id: 2,+ title: "Old",+ status: "resolved",+ createdAt: new Date("2026-06-01T10:00:00.000Z"),+ statusReportUpdates: [],+ },+ ],+ maintenances: [+ {+ id: 5,+ title: "DB upgrade",+ from: new Date("2026-06-20T00:00:00.000Z"),+ to: new Date("2026-06-20T01:00:00.000Z"),+ },+ ],+} as unknown as Page;++describe("toStatus", () => {+ test("page block + Statuspage indicator", () => {+ expect(toStatus(page, BASE)).toEqual({+ page: {+ name: "Acme Status",+ url: BASE,+ updated_at: "2026-06-19T11:00:00.000Z",+ },+ status: { indicator: "minor", description: "Degraded Performance" },+ });+ });+});++describe("toSummary", () => {+ const summary = toSummary(page, BASE, NOW);++ test("components carry Statuspage statuses", () => {+ expect(summary.components).toEqual([+ { name: "API", status: "major_outage" },+ { name: "CDN", status: "operational" },+ ]);+ });++ test("only unresolved incidents, with updates", () => {+ expect(summary.incidents).toHaveLength(1);+ expect(summary.incidents[0]).toMatchObject({+ id: "1",+ name: "API latency",+ status: "investigating",+ updated_at: "2026-06-19T10:30:00.000Z",+ });+ expect(summary.incidents[0].incident_updates[0].body).toBe(+ "Looking into it.",+ );+ });++ test("upcoming maintenance scheduled", () => {+ expect(summary.scheduled_maintenances).toHaveLength(1);+ expect(summary.scheduled_maintenances[0]).toMatchObject({+ id: "5",+ status: "scheduled",+ scheduled_for: "2026-06-20T00:00:00.000Z",+ });+ });+});++describe("toUnresolvedIncidents", () => {+ test("excludes resolved", () => {+ const out = toUnresolvedIncidents(page, BASE);+ expect(out.incidents.map((i) => i.id)).toEqual(["1"]);+ });+});diff --git a/apps/status-page/src/content/status-json.ts b/apps/status-page/src/content/status-json.tsnew file mode 100644index 000000000..62f325cbb--- /dev/null+++ b/apps/status-page/src/content/status-json.ts@@ -0,0 +1,111 @@+import type { RouterOutputs } from "@openstatus/api";++import {+ componentStatus,+ flattenComponents,+ isoOrNull,+ pageIndicator,+} from "./status-vocab";++type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;++export type StatusEndpoint = "summary" | "status" | "incidents";++const ENDPOINTS: Record<string, StatusEndpoint> = {+ "summary.json": "summary",+ "current.json": "status",+ "incidents.json": "incidents",+};++/**+ * The endpoint is always the last path segment; an optional leading segment is a+ * path-based slug (`/{slug}/summary.json`), mirroring the markdown route. Returns+ * null for unknown shapes so the handler can 404.+ */+export function matchEndpoint(+ path: string[],+): { endpoint: StatusEndpoint; slug: string | null } | null {+ if (path.length === 0 || path.length > 2) return null;+ const endpoint = ENDPOINTS[path[path.length - 1]];+ if (!endpoint) return null;+ return { endpoint, slug: path.length === 2 ? path[0] : null };+}++function pageBlock(page: Page, baseUrl: string) {+ return {+ name: page.title,+ url: baseUrl,+ updated_at: isoOrNull(page.updatedAt),+ };+}++/** `current.json` (Statuspage `status.json` shape) — the cheapest "is it up?" payload. */+export function toStatus(page: Page, baseUrl: string) {+ return {+ page: pageBlock(page, baseUrl),+ status: pageIndicator(page.status),+ };+}++function unresolvedIncidents(page: Page) {+ return page.statusReports+ .filter((report) => report.status !== "resolved")+ .map((report) => ({+ id: String(report.id),+ name: report.title,+ // openstatus report statuses already match Statuspage's incident enum.+ status: report.status,+ updated_at: isoOrNull(+ report.statusReportUpdates[0]?.date ?? report.createdAt,+ ),+ incident_updates: report.statusReportUpdates.map((update) => ({+ status: update.status,+ body: update.message,+ created_at: isoOrNull(update.date),+ })),+ }));+}++// `completed` is intentionally absent: scheduledMaintenances only feeds windows+// with `to >= now`, so a window is always either upcoming or live.+function maintenanceState(+ from: Date | string | number,+ now: number,+): "scheduled" | "in_progress" {+ return now < new Date(from).getTime() ? "scheduled" : "in_progress";+}++function scheduledMaintenances(page: Page, now: number) {+ return page.maintenances+ .filter((m) => m.to && new Date(m.to).getTime() >= now)+ .map((m) => ({+ id: String(m.id),+ name: m.title,+ status: maintenanceState(m.from, now),+ scheduled_for: isoOrNull(m.from),+ scheduled_until: isoOrNull(m.to),+ }));+}++/** Statuspage `summary.json` — page status, components, active incidents/maintenance. */+export function toSummary(page: Page, baseUrl: string, now = Date.now()) {+ const components = flattenComponents(page.trackers).map((c) => ({+ name: c.name,+ status: componentStatus(c.status),+ }));+ return {+ page: pageBlock(page, baseUrl),+ status: pageIndicator(page.status),+ components,+ incidents: unresolvedIncidents(page),+ scheduled_maintenances: scheduledMaintenances(page, now),+ };+}++/** `incidents.json` (Statuspage `incidents/unresolved.json` shape). */+export function toUnresolvedIncidents(page: Page, baseUrl: string) {+ return {+ page: pageBlock(page, baseUrl),+ incidents: unresolvedIncidents(page),+ };+}diff --git a/apps/status-page/src/content/status-vocab.test.ts b/apps/status-page/src/content/status-vocab.test.tsnew file mode 100644index 000000000..5769f458e--- /dev/null+++ b/apps/status-page/src/content/status-vocab.test.ts@@ -0,0 +1,92 @@+import { describe, expect, test } from "bun:test";++import {+ componentStatus,+ flattenComponents,+ isoOrNull,+ pageIndicator,+ worstComponent,+} from "./status-vocab";++describe("pageIndicator", () => {+ test("maps live status to Statuspage indicator + description", () => {+ expect(pageIndicator("success")).toEqual({+ indicator: "none",+ description: "All Systems Operational",+ });+ expect(pageIndicator("degraded").indicator).toBe("minor");+ expect(pageIndicator("error").indicator).toBe("major");+ expect(pageIndicator("info").indicator).toBe("maintenance");+ });++ test("unknown falls back to operational", () => {+ expect(pageIndicator("???").indicator).toBe("none");+ });+});++describe("componentStatus", () => {+ test("maps to Statuspage component vocabulary", () => {+ expect(componentStatus("success")).toBe("operational");+ expect(componentStatus("degraded")).toBe("degraded_performance");+ expect(componentStatus("error")).toBe("major_outage");+ expect(componentStatus("info")).toBe("under_maintenance");+ expect(componentStatus("???")).toBe("operational");+ });+});++describe("flattenComponents", () => {+ test("flattens components and grouped components", () => {+ const flat = flattenComponents([+ { type: "component", component: { name: "API", status: "error" } },+ {+ type: "group",+ components: [+ { name: "DB", status: "success" },+ { name: "Cache", status: "degraded" },+ ],+ },+ ]);+ expect(flat).toEqual([+ { name: "API", status: "error" },+ { name: "DB", status: "success" },+ { name: "Cache", status: "degraded" },+ ]);+ });++ test("tolerates null/undefined", () => {+ expect(flattenComponents(null)).toEqual([]);+ expect(flattenComponents(undefined)).toEqual([]);+ });+});++describe("worstComponent", () => {+ test("returns the most severely impacted name", () => {+ expect(+ worstComponent([+ { name: "API", status: "degraded" },+ { name: "Web", status: "error" },+ { name: "DB", status: "success" },+ ]),+ ).toBe("Web");+ });++ test("null when all operational", () => {+ expect(+ worstComponent([+ { name: "API", status: "success" },+ { name: "Web", status: "success" },+ ]),+ ).toBeNull();+ });+});++describe("isoOrNull", () => {+ test("ISO for valid dates, null otherwise", () => {+ expect(isoOrNull(new Date("2026-06-18T14:03:00.000Z"))).toBe(+ "2026-06-18T14:03:00.000Z",+ );+ expect(isoOrNull(null)).toBeNull();+ expect(isoOrNull(undefined)).toBeNull();+ expect(isoOrNull("not a date")).toBeNull();+ });+});diff --git a/apps/status-page/src/content/status-vocab.ts b/apps/status-page/src/content/status-vocab.tsnew file mode 100644index 000000000..67c7091db--- /dev/null+++ b/apps/status-page/src/content/status-vocab.ts@@ -0,0 +1,90 @@+/**+ * Maps openstatus's internal status vocabulary onto Atlassian Statuspage's+ * de-facto public schema, so agents and tooling that already know that shape+ * work against an openstatus page zero-shot. `page.status` and component+ * `status` are both `success|degraded|error|info` in @openstatus/db; the+ * component-impact enum (`operational|degraded_performance|…`) already matches+ * Statuspage, so only the live rollup needs translating.+ */++export type PageStatus = "success" | "degraded" | "error" | "info";++const PAGE_INDICATOR: Record<+ PageStatus,+ { indicator: string; description: string }+> = {+ success: { indicator: "none", description: "All Systems Operational" },+ degraded: { indicator: "minor", description: "Degraded Performance" },+ error: { indicator: "major", description: "Major Outage" },+ info: { indicator: "maintenance", description: "Under Maintenance" },+};++const COMPONENT_STATUS: Record<PageStatus, string> = {+ success: "operational",+ degraded: "degraded_performance",+ error: "major_outage",+ info: "under_maintenance",+};++const SEVERITY: Record<PageStatus, number> = {+ error: 3,+ degraded: 2,+ info: 1,+ success: 0,+};++/** Statuspage page-level indicator + human description for a live page status. */+export function pageIndicator(status: string): {+ indicator: string;+ description: string;+} {+ return PAGE_INDICATOR[status as PageStatus] ?? PAGE_INDICATOR.success;+}++/** Statuspage component status for a live component status. */+export function componentStatus(status: string): string {+ return COMPONENT_STATUS[status as PageStatus] ?? "operational";+}++type TrackerLike =+ | { type: "component"; component: { name: string; status: string } }+ | { type: "group"; components: { name: string; status: string }[] };++/** Flatten the tracker tree (components + grouped components) to a flat list. */+export function flattenComponents(+ trackers: TrackerLike[] | null | undefined,+): { name: string; status: string }[] {+ const out: { name: string; status: string }[] = [];+ for (const t of trackers ?? []) {+ if (t.type === "component") {+ out.push({ name: t.component.name, status: t.component.status });+ } else {+ for (const c of t.components)+ out.push({ name: c.name, status: c.status });+ }+ }+ return out;+}++/** Name of the most severely impacted component, or null if all operational. */+export function worstComponent(+ components: { name: string; status: string }[],+): string | null {+ let worst: { name: string; rank: number } | null = null;+ for (const c of components) {+ const rank = SEVERITY[c.status as PageStatus] ?? 0;+ if (rank > 0 && (worst === null || rank > worst.rank)) {+ worst = { name: c.name, rank };+ }+ }+ return worst?.name ?? null;+}++/** ISO-8601 (RFC3339) timestamp, or null — for machine-facing JSON. */+export function isoOrNull(+ date: Date | string | number | null | undefined,+): string | null {+ if (date === null || date === undefined) return null;+ const d = date instanceof Date ? date : new Date(date);+ return Number.isNaN(d.getTime()) ? null : d.toISOString();+}diff --git a/apps/status-page/src/lib/alternates-metadata.ts b/apps/status-page/src/lib/alternates-metadata.tsnew file mode 100644index 000000000..ae4d66550--- /dev/null+++ b/apps/status-page/src/lib/alternates-metadata.ts@@ -0,0 +1,24 @@+import type { Metadata } from "next";++import { statusPageAlternates } from "@/lib/alternates";+import { getQueryClient, trpc } from "@/lib/trpc/server";++export async function statusPageAlternatesMetadata({+ domain,+ markdownPath,+}: {+ domain: string;+ markdownPath?: string;+}): Promise<Metadata> {+ const page = await getQueryClient().fetchQuery(+ trpc.statusPage.get.queryOptions({ slug: domain }),+ );+ if (!page) return {};+ return {+ alternates: statusPageAlternates({+ slug: page.slug,+ customDomain: page.customDomain,+ markdownPath,+ }),+ };+}diff --git a/apps/status-page/src/lib/alternates.test.ts b/apps/status-page/src/lib/alternates.test.tsnew file mode 100644index 000000000..900502ee4--- /dev/null+++ b/apps/status-page/src/lib/alternates.test.ts@@ -0,0 +1,64 @@+import { describe, expect, test } from "bun:test";++import { statusPageAlternates } from "./alternates";++describe("statusPageAlternates", () => {+ test("subdomain, default markdown path → overview", () => {+ expect(statusPageAlternates({ slug: "acme" })).toEqual({+ canonical: "https://acme.openstatus.dev",+ types: {+ "text/markdown": "https://acme.openstatus.dev/.md",+ "application/json":+ "https://acme.openstatus.dev/api/status/summary.json",+ },+ });+ });++ test("custom domain wins over subdomain", () => {+ expect(+ statusPageAlternates({ slug: "acme", customDomain: "status.acme.com" }),+ ).toEqual({+ canonical: "https://status.acme.com",+ types: {+ "text/markdown": "https://status.acme.com/.md",+ "application/json": "https://status.acme.com/api/status/summary.json",+ },+ });+ });++ test("null customDomain falls back to subdomain", () => {+ expect(statusPageAlternates({ slug: "acme", customDomain: null })).toEqual({+ canonical: "https://acme.openstatus.dev",+ types: {+ "text/markdown": "https://acme.openstatus.dev/.md",+ "application/json":+ "https://acme.openstatus.dev/api/status/summary.json",+ },+ });+ });++ test("per-page markdown path, subdomain", () => {+ const result = statusPageAlternates({+ slug: "acme",+ markdownPath: "/monitors/123.md",+ });+ expect(result?.types?.["text/markdown"]).toBe(+ "https://acme.openstatus.dev/monitors/123.md",+ );+ // canonical and json alternate stay at the page root regardless of md path+ expect(result?.canonical).toBe("https://acme.openstatus.dev");+ expect(result?.types?.["application/json"]).toBe(+ "https://acme.openstatus.dev/api/status/summary.json",+ );+ });++ test("per-page markdown path, custom domain", () => {+ expect(+ statusPageAlternates({+ slug: "acme",+ customDomain: "status.acme.com",+ markdownPath: "/events/report/7.md",+ })?.types?.["text/markdown"],+ ).toBe("https://status.acme.com/events/report/7.md");+ });+});diff --git a/apps/status-page/src/lib/alternates.ts b/apps/status-page/src/lib/alternates.tsnew file mode 100644index 000000000..6d679daba--- /dev/null+++ b/apps/status-page/src/lib/alternates.ts@@ -0,0 +1,34 @@+import type { Metadata } from "next";++function host({+ slug,+ customDomain,+}: {+ slug: string;+ customDomain?: string | null;+}) {+ return customDomain+ ? `https://${customDomain}`+ : `https://${slug}.openstatus.dev`;+}++// Next.js merges `alternates` shallowly, so a deeper segment that sets it+// replaces the parent's entirely — always return the full object.+export function statusPageAlternates({+ slug,+ customDomain,+ markdownPath = "/.md",+}: {+ slug: string;+ customDomain?: string | null;+ markdownPath?: string;+}): Metadata["alternates"] {+ const base = host({ slug, customDomain });+ return {+ canonical: base,+ types: {+ "text/markdown": `${base}${markdownPath}`,+ "application/json": `${base}/api/status/summary.json`,+ },+ };+}diff --git a/apps/status-page/src/lib/domain.ts b/apps/status-page/src/lib/domain.tsindex 6dbc9351c..7d3fa2e3c 100644--- a/apps/status-page/src/lib/domain.ts+++ b/apps/status-page/src/lib/domain.ts@@ -1,5 +1,10 @@import type { NextRequest } from "next/server";+// Custom-domain lookups exact-match page.customDomain, which is stored without a+// port; an inbound host like "status.acme.com:8080" must be normalized first.+export const stripHostPort = (host?: string | null) =>+ host ? host.replace(/:\d+$/, "") : (host ?? null);+export const getValidSubdomain = (host?: string | null) => {let subdomain: string | null = null;if (!host && typeof window !== "undefined") {diff --git a/apps/status-page/src/lib/http/client-ip.test.ts b/apps/status-page/src/lib/http/client-ip.test.tsnew file mode 100644index 000000000..684c07a58--- /dev/null+++ b/apps/status-page/src/lib/http/client-ip.test.ts@@ -0,0 +1,39 @@+import { describe, expect, test } from "bun:test";++import { resolveClientIp } from "./client-ip";++function h(map: Record<string, string>) {+ return { get: (name: string) => map[name] ?? null };+}++describe("resolveClientIp", () => {+ test("prefers x-real-ip over x-forwarded-for", () => {+ expect(+ resolveClientIp(+ h({ "x-real-ip": "9.9.9.9", "x-forwarded-for": "1.2.3.4" }),+ ),+ ).toBe("9.9.9.9");+ });++ test("ignores a spoofed leftmost x-forwarded-for when x-real-ip is present", () => {+ // Attacker injects an allowed IP at the head of the chain; x-real-ip wins.+ expect(+ resolveClientIp(+ h({+ "x-real-ip": "203.0.113.7",+ "x-forwarded-for": "10.0.0.1, 203.0.113.7",+ }),+ ),+ ).toBe("203.0.113.7");+ });++ test("falls back to leftmost x-forwarded-for when x-real-ip is absent", () => {+ expect(resolveClientIp(h({ "x-forwarded-for": "1.2.3.4, 5.6.7.8" }))).toBe(+ "1.2.3.4",+ );+ });++ test("returns null when neither header is present", () => {+ expect(resolveClientIp(h({}))).toBeNull();+ });+});diff --git a/apps/status-page/src/lib/http/client-ip.ts b/apps/status-page/src/lib/http/client-ip.tsnew file mode 100644index 000000000..2f346c074--- /dev/null+++ b/apps/status-page/src/lib/http/client-ip.ts@@ -0,0 +1,15 @@+/**+ * Client IP for access-gate checks. Prefer `x-real-ip`: Vercel's edge sets it to+ * the single verified client IP, with no comma-chain to parse. `x-forwarded-for`'s+ * leftmost entry is the classic spoof vector on paths that reach a route directly+ * — `/api/*` bypasses the proxy middleware — so only fall back to it when+ * `x-real-ip` is absent (e.g. local dev). A null result denies ip-restricted pages.+ */+export function resolveClientIp(headers: {+ get(name: string): string | null;+}): string | null {+ const real = headers.get("x-real-ip");+ if (real) return real.trim();+ const xff = headers.get("x-forwarded-for");+ return xff?.split(",")[0]?.trim() ?? null;+}diff --git a/apps/status-page/src/lib/http/etag.test.ts b/apps/status-page/src/lib/http/etag.test.tsnew file mode 100644index 000000000..66e86bd8b--- /dev/null+++ b/apps/status-page/src/lib/http/etag.test.ts@@ -0,0 +1,50 @@+import { describe, expect, test } from "bun:test";++import { computeETag, isNotModified } from "./etag";++function withINM(value: string | null): Request {+ return new Request("https://acme.openstatus.dev/.md", {+ headers: value ? { "if-none-match": value } : {},+ });+}++describe("computeETag", () => {+ test("quoted, stable for the same body", () => {+ const etag = computeETag("# Status");+ expect(etag).toMatch(/^"[0-9a-f]{64}"$/);+ expect(computeETag("# Status")).toBe(etag);+ });++ test("differs when the body differs", () => {+ expect(computeETag("a")).not.toBe(computeETag("b"));+ });+});++describe("isNotModified", () => {+ test("no If-None-Match → false", () => {+ expect(isNotModified(withINM(null), computeETag("x"))).toBe(false);+ });++ test("exact match → true", () => {+ const etag = computeETag("x");+ expect(isNotModified(withINM(etag), etag)).toBe(true);+ });++ test("non-matching tag → false", () => {+ expect(isNotModified(withINM(computeETag("x")), computeETag("y"))).toBe(+ false,+ );+ });++ test("matches one tag in a comma-separated list with whitespace", () => {+ const etag = computeETag("x");+ expect(isNotModified(withINM(`"deadbeef", ${etag} , "cafe"`), etag)).toBe(+ true,+ );+ });++ test("wildcard `*` matches any current ETag", () => {+ expect(isNotModified(withINM("*"), computeETag("x"))).toBe(true);+ expect(isNotModified(withINM(" * "), computeETag("x"))).toBe(true);+ });+});diff --git a/apps/status-page/src/lib/http/etag.ts b/apps/status-page/src/lib/http/etag.tsnew file mode 100644index 000000000..b7c4b3962--- /dev/null+++ b/apps/status-page/src/lib/http/etag.ts@@ -0,0 +1,15 @@+import { createHash } from "node:crypto";++/** Strong ETag from a content hash. Node runtime only (uses node:crypto). */+export function computeETag(body: string): string {+ return `"${createHash("sha256").update(body).digest("hex")}"`;+}++/** Whether the request's If-None-Match matches the ETag — i.e. serve a 304. */+export function isNotModified(request: Request, etag: string): boolean {+ const header = request.headers.get("if-none-match");+ if (!header) return false;+ // RFC 7232 §3.2: `*` matches any current representation.+ if (header.trim() === "*") return true;+ return header.split(",").some((tag) => tag.trim() === etag);+}diff --git a/apps/status-page/src/lib/http/markdown-response.test.ts b/apps/status-page/src/lib/http/markdown-response.test.tsnew file mode 100644index 000000000..c519398eb--- /dev/null+++ b/apps/status-page/src/lib/http/markdown-response.test.ts@@ -0,0 +1,108 @@+import { describe, expect, test } from "bun:test";++import { withPoweredBy } from "@/content/markdown";+import { computeETag } from "@/lib/http/etag";+import { resolveMarkdownResponse } from "@/lib/http/markdown-response";++const PUBLIC_CACHE =+ "public, max-age=60, s-maxage=60, stale-while-revalidate=300";+const NO_STORE = "private, no-store";++function req(ifNoneMatch?: string): Request {+ return new Request("https://acme.openstatus.dev/.md", {+ headers: ifNoneMatch ? { "if-none-match": ifNoneMatch } : {},+ });+}++describe("resolveMarkdownResponse", () => {+ test("200: appends powered-by footer, markdown content-type, Vary: Accept", () => {+ const res = resolveMarkdownResponse(req(), {+ body: "# Status",+ source: "suffix",+ whiteLabel: false,+ accessType: "public",+ });+ expect(res.status).toBe(200);+ expect(res.body).toBe(withPoweredBy("# Status", false));+ expect(res.body).toContain("Powered by");+ expect(res.headers["Content-Type"]).toBe("text/markdown; charset=utf-8");+ expect(res.headers.Vary).toBe("Accept");+ expect(res.headers.ETag).toMatch(/^"[0-9a-f]{64}"$/);+ });++ test("ETag is hashed over the footer-appended body, not the raw body", () => {+ const res = resolveMarkdownResponse(req(), {+ body: "# Status",+ source: "suffix",+ whiteLabel: false,+ accessType: "public",+ });+ expect(res.headers.ETag).toBe(+ computeETag(withPoweredBy("# Status", false)),+ );+ });++ test("white-labeled: no footer, and a different ETag", () => {+ const plain = resolveMarkdownResponse(req(), {+ body: "# Status",+ source: "suffix",+ whiteLabel: false,+ accessType: "public",+ });+ const wl = resolveMarkdownResponse(req(), {+ body: "# Status",+ source: "suffix",+ whiteLabel: true,+ accessType: "public",+ });+ expect(wl.body).toBe("# Status");+ expect(wl.body).not.toContain("Powered by");+ expect(wl.headers.ETag).not.toBe(plain.headers.ETag);+ });++ test("304 when If-None-Match matches the footer-appended ETag, body null", () => {+ const etag = computeETag(withPoweredBy("# Status", false));+ const res = resolveMarkdownResponse(req(etag), {+ body: "# Status",+ source: "suffix",+ whiteLabel: false,+ accessType: "public",+ });+ expect(res.status).toBe(304);+ expect(res.body).toBeNull();+ // Cache + ETag + Vary still ride along on the 304.+ expect(res.headers.ETag).toBe(etag);+ expect(res.headers.Vary).toBe("Accept");+ expect(res.headers["Cache-Control"]).toBe(PUBLIC_CACHE);+ });++ test("public .md suffix is edge-cacheable", () => {+ const res = resolveMarkdownResponse(req(), {+ body: "x",+ source: "suffix",+ whiteLabel: false,+ accessType: "public",+ });+ expect(res.headers["Cache-Control"]).toBe(PUBLIC_CACHE);+ });++ test("gated page is never edge-cacheable, even via .md suffix", () => {+ const res = resolveMarkdownResponse(req(), {+ body: "x",+ source: "suffix",+ whiteLabel: false,+ accessType: "password",+ });+ expect(res.headers["Cache-Control"]).toBe(NO_STORE);+ });++ test("header-negotiated public page is not edge-cached", () => {+ const res = resolveMarkdownResponse(req(), {+ body: "x",+ source: "header",+ whiteLabel: false,+ accessType: "public",+ });+ expect(res.headers["Cache-Control"]).toBe(NO_STORE);+ });+});diff --git a/apps/status-page/src/lib/http/markdown-response.ts b/apps/status-page/src/lib/http/markdown-response.tsnew file mode 100644index 000000000..ae27ed3ec--- /dev/null+++ b/apps/status-page/src/lib/http/markdown-response.ts@@ -0,0 +1,39 @@+import { withPoweredBy } from "@/content/markdown";+import { computeETag, isNotModified } from "@/lib/http/etag";+import { markdownCacheControl } from "@/lib/proxy/markdown-cache-control";++const MARKDOWN = "text/markdown; charset=utf-8";++export interface MarkdownResponseInit {+ body: string;+ source: string | null;+ whiteLabel: boolean;+ accessType: string | null | undefined;+}++export interface ResolvedMarkdownResponse {+ status: number;+ body: string | null;+ headers: Record<string, string>;+}++// Pure response shaping: append the powered-by footer, hash a strong ETag, and+// return a 304 (null body) when If-None-Match matches. `Vary: Accept` always —+// the same URL serves HTML or markdown by negotiation, so caches must split.+export function resolveMarkdownResponse(+ request: Request,+ { body, source, whiteLabel, accessType }: MarkdownResponseInit,+): ResolvedMarkdownResponse {+ const finalBody = withPoweredBy(body, whiteLabel);+ const etag = computeETag(finalBody);+ const headers = {+ "Content-Type": MARKDOWN,+ "Cache-Control": markdownCacheControl(source, accessType),+ ETag: etag,+ Vary: "Accept",+ };+ if (isNotModified(request, etag)) {+ return { status: 304, body: null, headers };+ }+ return { status: 200, body: finalBody, headers };+}diff --git a/apps/status-page/src/lib/proxy/access-predicates.ts b/apps/status-page/src/lib/proxy/access-predicates.tsnew file mode 100644index 000000000..a73c70cc6--- /dev/null+++ b/apps/status-page/src/lib/proxy/access-predicates.ts@@ -0,0 +1,62 @@+import { isIpAllowed } from "./is-ip-allowed";++/**+ * Pure allow/deny predicates shared by the proxy gate chain (which wraps them in+ * redirects) and the markdown route gate (which wraps them in status codes).+ * Keeping the authorization core here is the guarantee that the two surfaces+ * cannot drift — only their wrapping behaviour differs.+ */++// Length-independent comparison so a wrong guess can't be timed by length or+// character. Pure JS (no node:crypto): must be Edge-safe for the proxy, so it+// can't import the twin in packages/api (not in the middleware bundle) — hence+// the duplication; keep both implementations in sync.+function constantTimeEqual(+ a: string | null | undefined,+ b: string | null | undefined,+): boolean {+ if (a == null || b == null) return false;+ // Iterate over the max length and fold the length delta into the accumulator+ // so we never early-return or branch on length.+ const max = Math.max(a.length, b.length);+ let mismatch = a.length ^ b.length;+ for (let i = 0; i < max; i++) {+ // out-of-range indices read as 0; mismatch already non-zero on length diff.+ mismatch |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);+ }+ return mismatch === 0;+}++/**+ * Stored page password vs submitted. The query param wins over the cookie (a+ * present-but-wrong `?pw=` must not fall through to a valid cookie), matching+ * the proxy's established behaviour. Empty/absent stored never authorizes.+ */+export function isPasswordAuthorized(input: {+ stored: string | null | undefined;+ queryPassword: string | null | undefined;+ cookiePassword: string | null | undefined;+}): boolean {+ if (!input.stored) return false;+ const submitted = input.queryPassword ?? input.cookiePassword;+ return constantTimeEqual(submitted, input.stored);+}++/** Authenticated email's domain is in the page's allow-list. */+export function isEmailDomainAuthorized(+ authEmail: string | null | undefined,+ authEmailDomains: string[] | null | undefined,+): boolean {+ // DNS domains are case-insensitive — normalise both sides before matching.+ const domain = authEmail?.split("@")[1]?.toLowerCase();+ const allowed = (authEmailDomains ?? []).map((d) => d.toLowerCase());+ return !!(domain && allowed.includes(domain));+}++/** Client IP falls within one of the page's allowed CIDR ranges. */+export function isIpAuthorized(+ clientIp: string | null | undefined,+ allowedIpRanges: string[] | null | undefined,+): boolean {+ return !!(clientIp && isIpAllowed(clientIp, allowedIpRanges ?? []));+}diff --git a/apps/status-page/src/lib/proxy/detect-markdown.test.ts b/apps/status-page/src/lib/proxy/detect-markdown.test.tsnew file mode 100644index 000000000..10dbc1f91--- /dev/null+++ b/apps/status-page/src/lib/proxy/detect-markdown.test.ts@@ -0,0 +1,68 @@+import { describe, expect, test } from "bun:test";++import { detectMarkdown } from "./detect-markdown";++describe("detectMarkdown", () => {+ test(".md suffix stripped, source suffix", () => {+ expect(+ detectMarkdown({ pathname: "/monitors/123.md", accept: null }),+ ).toEqual({+ wantsMarkdown: true,+ source: "suffix",+ pathname: "/monitors/123",+ });+ });++ test("root /.md → /", () => {+ expect(detectMarkdown({ pathname: "/.md", accept: null })).toEqual({+ wantsMarkdown: true,+ source: "suffix",+ pathname: "/",+ });+ });++ test("Accept: text/markdown → source header, pathname untouched", () => {+ expect(+ detectMarkdown({ pathname: "/monitors", accept: "text/markdown" }),+ ).toEqual({ wantsMarkdown: true, source: "header", pathname: "/monitors" });+ });++ test("case-insensitive + multi-type Accept", () => {+ expect(+ detectMarkdown({+ pathname: "/",+ accept: "text/html, text/Markdown;q=0.9",+ }),+ ).toEqual({ wantsMarkdown: true, source: "header", pathname: "/" });+ });++ test("plain HTML accept → not markdown", () => {+ expect(+ detectMarkdown({ pathname: "/monitors", accept: "text/html" }),+ ).toEqual({ wantsMarkdown: false, source: null, pathname: "/monitors" });+ });++ test("no accept header → not markdown", () => {+ expect(detectMarkdown({ pathname: "/events", accept: null })).toEqual({+ wantsMarkdown: false,+ source: null,+ pathname: "/events",+ });+ });++ test(".md that also matches Accept resolves to suffix", () => {+ expect(+ detectMarkdown({ pathname: "/monitors/1.md", accept: "text/markdown" }),+ ).toEqual({+ wantsMarkdown: true,+ source: "suffix",+ pathname: "/monitors/1",+ });+ });++ test("partial token (text/markdownish) does not match", () => {+ expect(+ detectMarkdown({ pathname: "/", accept: "text/markdownish" }),+ ).toEqual({ wantsMarkdown: false, source: null, pathname: "/" });+ });+});diff --git a/apps/status-page/src/lib/proxy/detect-markdown.ts b/apps/status-page/src/lib/proxy/detect-markdown.tsnew file mode 100644index 000000000..27e649b0a--- /dev/null+++ b/apps/status-page/src/lib/proxy/detect-markdown.ts@@ -0,0 +1,42 @@+export interface DetectMarkdownResult {+ wantsMarkdown: boolean;+ source: "suffix" | "header" | null;+ /** Pathname with a trailing `.md` stripped, so `resolveRoute` runs unchanged. */+ pathname: string;+}++function acceptsMarkdown(accept: string | null): boolean {+ if (!accept) return false;+ // Match the media type as a whole token, tolerating params/q-values and casing.+ return accept+ .toLowerCase()+ .split(",")+ .some((part) => part.trim().split(";")[0].trim() === "text/markdown");+}++/**+ * Proxy-side detection of a markdown request. The `.md` suffix wins over the+ * Accept header so a `.md` URL keeps the cache-safe suffix policy.+ */+export function detectMarkdown(input: {+ pathname: string;+ accept: string | null;+}): DetectMarkdownResult {+ const { pathname, accept } = input;++ if (pathname.endsWith(".md")) {+ const stripped = pathname.slice(0, -".md".length);+ // `/.md` (root) → `/`; otherwise keep the stripped path.+ return {+ wantsMarkdown: true,+ source: "suffix",+ pathname: stripped === "" ? "/" : stripped,+ };+ }++ if (acceptsMarkdown(accept)) {+ return { wantsMarkdown: true, source: "header", pathname };+ }++ return { wantsMarkdown: false, source: null, pathname };+}diff --git a/apps/status-page/src/lib/proxy/evaluate-markdown-gate.test.ts b/apps/status-page/src/lib/proxy/evaluate-markdown-gate.test.tsnew file mode 100644index 000000000..02c7f46ba--- /dev/null+++ b/apps/status-page/src/lib/proxy/evaluate-markdown-gate.test.ts@@ -0,0 +1,120 @@+import { describe, expect, test } from "bun:test";++import { evaluateMarkdownGate } from "./evaluate-markdown-gate";++const base = {+ passwordAuthorized: false,+ authEmail: null,+ authEmailDomains: null,+ clientIp: null,+ allowedIpRanges: null,+} as const;++describe("evaluateMarkdownGate", () => {+ test("public → ok", () => {+ expect(evaluateMarkdownGate({ ...base, accessType: "public" })).toEqual({+ ok: true,+ });+ });++ describe("password", () => {+ test("authorized → ok", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "password",+ passwordAuthorized: true,+ }),+ ).toEqual({ ok: true });+ });++ test("not authorized → 401", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "password",+ passwordAuthorized: false,+ }),+ ).toMatchObject({ ok: false, status: 401 });+ });+ });++ describe("email-domain", () => {+ test("allowed domain → ok", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "email-domain",+ authEmail: "[email protected]",+ authEmailDomains: ["acme.com"],+ }),+ ).toEqual({ ok: true });+ });++ test("no session → 403", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "email-domain",+ authEmailDomains: ["acme.com"],+ }),+ ).toMatchObject({ ok: false, status: 403 });+ });++ test("wrong domain → 403", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "email-domain",+ authEmail: "[email protected]",+ authEmailDomains: ["acme.com"],+ }),+ ).toMatchObject({ ok: false, status: 403 });+ });++ test("empty authEmailDomains → 403", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "email-domain",+ authEmail: "[email protected]",+ authEmailDomains: [],+ }),+ ).toMatchObject({ ok: false, status: 403 });+ });+ });++ describe("ip-restriction", () => {+ test("allowed IP → ok", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "ip-restriction",+ clientIp: "10.0.0.5",+ allowedIpRanges: ["10.0.0.0/24"],+ }),+ ).toEqual({ ok: true });+ });++ test("disallowed IP → 403", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "ip-restriction",+ clientIp: "192.168.1.1",+ allowedIpRanges: ["10.0.0.0/24"],+ }),+ ).toMatchObject({ ok: false, status: 403 });+ });++ test("missing IP → 403 (gap the feed route has, asserted closed)", () => {+ expect(+ evaluateMarkdownGate({+ ...base,+ accessType: "ip-restriction",+ allowedIpRanges: ["10.0.0.0/24"],+ }),+ ).toMatchObject({ ok: false, status: 403 });+ });+ });+});diff --git a/apps/status-page/src/lib/proxy/evaluate-markdown-gate.ts b/apps/status-page/src/lib/proxy/evaluate-markdown-gate.tsnew file mode 100644index 000000000..8847e9eda--- /dev/null+++ b/apps/status-page/src/lib/proxy/evaluate-markdown-gate.ts@@ -0,0 +1,48 @@+import type { Page } from "@openstatus/db/src/schema";++import { isEmailDomainAuthorized, isIpAuthorized } from "./access-predicates";++export type MarkdownGateResult =+ | { ok: true }+ | { ok: false; status: 401 | 403; body: string };++/**+ * Pure access-control decision for a markdown request, mirroring the proxy gate+ * chain. Security-critical: the markdown route is reachable directly via `/api`,+ * which bypasses the proxy, so this is the only enforcement on that path.+ *+ * `passwordAuthorized` is resolved server-side (via `statusPage.isPasswordAuthorized`)+ * so the stored password never reaches this surface.+ */+export function evaluateMarkdownGate(input: {+ accessType: Page["accessType"];+ passwordAuthorized: boolean;+ authEmail: string | null | undefined;+ authEmailDomains: string[] | null;+ clientIp: string | null | undefined;+ allowedIpRanges: string[] | null;+}): MarkdownGateResult {+ switch (input.accessType) {+ case "public":+ return { ok: true };++ case "password":+ return input.passwordAuthorized+ ? { ok: true }+ : { ok: false, status: 401, body: "Unauthorized" };++ case "email-domain":+ return isEmailDomainAuthorized(input.authEmail, input.authEmailDomains)+ ? { ok: true }+ : { ok: false, status: 403, body: "Forbidden" };++ case "ip-restriction":+ return isIpAuthorized(input.clientIp, input.allowedIpRanges)+ ? { ok: true }+ : { ok: false, status: 403, body: "Forbidden" };++ default:+ // Unknown access type → deny.+ return { ok: false, status: 403, body: "Forbidden" };+ }+}diff --git a/apps/status-page/src/lib/proxy/markdown-cache-control.test.ts b/apps/status-page/src/lib/proxy/markdown-cache-control.test.tsnew file mode 100644index 000000000..9b6f90532--- /dev/null+++ b/apps/status-page/src/lib/proxy/markdown-cache-control.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test } from "bun:test";++import { markdownCacheControl } from "./markdown-cache-control";++const PUBLIC_CACHE =+ "public, max-age=60, s-maxage=60, stale-while-revalidate=300";+const NO_STORE = "private, no-store";++describe("markdownCacheControl", () => {+ test("public page via .md suffix is edge-cacheable", () => {+ expect(markdownCacheControl("suffix", "public")).toBe(PUBLIC_CACHE);+ });++ test("gated pages are never cacheable, even via .md suffix", () => {+ for (const accessType of [+ "password",+ "email-domain",+ "ip-restriction",+ ] as const) {+ expect(markdownCacheControl("suffix", accessType)).toBe(NO_STORE);+ }+ });++ test("header-negotiated requests are never edge-cached", () => {+ expect(markdownCacheControl("header", "public")).toBe(NO_STORE);+ });++ test("unknown/absent access type is not cacheable", () => {+ expect(markdownCacheControl("suffix", null)).toBe(NO_STORE);+ expect(markdownCacheControl("suffix", undefined)).toBe(NO_STORE);+ });+});diff --git a/apps/status-page/src/lib/proxy/markdown-cache-control.ts b/apps/status-page/src/lib/proxy/markdown-cache-control.tsnew file mode 100644index 000000000..43bf49a9d--- /dev/null+++ b/apps/status-page/src/lib/proxy/markdown-cache-control.ts@@ -0,0 +1,14 @@+/**+ * Cache-Control for a markdown response. Only PUBLIC pages served via the `.md`+ * suffix are edge-cacheable; gated pages (password/email-domain/ip-restriction)+ * must always be `private, no-store` — a `.md` suffix is not a license to cache+ * authorized content where the CDN could serve it to an unauthorized request.+ */+export function markdownCacheControl(+ source: string | null,+ accessType: string | null | undefined,+): string {+ return source === "suffix" && accessType === "public"+ ? "public, max-age=60, s-maxage=60, stale-while-revalidate=300"+ : "private, no-store";+}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.tsindex 8ee116d91..99c8b60ba 100644--- a/apps/status-page/src/lib/proxy/resolve-email-domain-action.ts+++ b/apps/status-page/src/lib/proxy/resolve-email-domain-action.ts@@ -1,5 +1,6 @@import type { Page } from "@openstatus/db/src/schema";+import { isEmailDomainAuthorized } from "./access-predicates";import { buildExternalPath } from "./build-external-path";import type { Action, ComposeInput } from "./types";@@ -28,9 +29,9 @@ export function resolveEmailDomainAction({}: Input): Action | null {if (page.accessType !== "email-domain") return null;- const emailDomain = authEmail?.split("@")[1];- const isAuthorised = !!(- emailDomain && page.authEmailDomains.includes(emailDomain)+ const isAuthorised = isEmailDomainAuthorized(+ authEmail,+ page.authEmailDomains,);const isOnLogin = pathname.endsWith("/login");diff --git a/apps/status-page/src/lib/proxy/resolve-gate.ts b/apps/status-page/src/lib/proxy/resolve-gate.tsnew file mode 100644index 000000000..7e56564e5--- /dev/null+++ b/apps/status-page/src/lib/proxy/resolve-gate.ts@@ -0,0 +1,54 @@+import type { Page } from "@openstatus/db/src/schema";++import { auth } from "@/lib/auth";+import { createProtectedCookieKey } from "@/lib/protected";+import type { getQueryClient } from "@/lib/trpc/server";+import { trpc } from "@/lib/trpc/server";++import {+ evaluateMarkdownGate,+ type MarkdownGateResult,+} from "./evaluate-markdown-gate";++export type GatePage = {+ accessType: Page["accessType"];+ authEmailDomains: string[] | null;+ allowedIpRanges: string[] | null;+ slug: string;+};++/**+ * Server-side orchestration around `evaluateMarkdownGate`: resolves the session+ * (email-domain pages) and password authorization (password pages) before+ * delegating to the pure decision. Shared by the markdown and status JSON API+ * routes, both reachable directly via `/api` — bypassing the proxy gate.+ */+export async function resolveGate(args: {+ page: GatePage;+ queryClient: ReturnType<typeof getQueryClient>;+ url: URL;+ cookieStore: { get(name: string): { value: string } | undefined };+ clientIp: string | null | undefined;+}): Promise<MarkdownGateResult> {+ const { page, queryClient, url, cookieStore, clientIp } = args;+ const session = page.accessType === "email-domain" ? await auth() : null;+ const passwordAuthorized =+ page.accessType === "password"+ ? await queryClient.fetchQuery(+ trpc.statusPage.isPasswordAuthorized.queryOptions({+ slug: page.slug,+ queryPassword: url.searchParams.get("pw"),+ cookiePassword: cookieStore.get(createProtectedCookieKey(page.slug))+ ?.value,+ }),+ )+ : false;+ return evaluateMarkdownGate({+ accessType: page.accessType,+ passwordAuthorized,+ authEmail: session?.user?.email,+ authEmailDomains: page.authEmailDomains,+ clientIp,+ allowedIpRanges: page.allowedIpRanges,+ });+}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.tsindex 59ffa5b1d..494e27b13 100644--- a/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.ts+++ b/apps/status-page/src/lib/proxy/resolve-ip-restriction-action.ts@@ -1,7 +1,7 @@import type { Page } from "@openstatus/db/src/schema";+import { isIpAuthorized } from "./access-predicates";import { buildExternalPath } from "./build-external-path";-import { isIpAllowed } from "./is-ip-allowed";import type { Action, ComposeInput } from "./types";type Input = Pick<@@ -27,7 +27,7 @@ export function resolveIpRestrictionAction({}: Input): Action | null {if (page.accessType !== "ip-restriction") return null;- const allowed = !!(clientIp && isIpAllowed(clientIp, page.allowedIpRanges));+ const allowed = isIpAuthorized(clientIp, page.allowedIpRanges);const isOnRestricted = pathname.endsWith("/restricted");// Gate-in: disallowed and not already on /restricted → send to /restricteddiff --git a/apps/status-page/src/lib/proxy/resolve-password-action.ts b/apps/status-page/src/lib/proxy/resolve-password-action.tsindex f8357a71f..07f46ce82 100644--- a/apps/status-page/src/lib/proxy/resolve-password-action.ts+++ b/apps/status-page/src/lib/proxy/resolve-password-action.ts@@ -1,5 +1,6 @@import type { Page } from "@openstatus/db/src/schema";+import { isPasswordAuthorized } from "./access-predicates";import { buildExternalPath } from "./build-external-path";import type { Action, ComposeInput } from "./types";@@ -43,15 +44,17 @@ export function resolvePasswordAction({}: 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 authorized = isPasswordAuthorized({+ stored: page.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 (!authorized && !isOnLogin) {if (needsCustomDomainRedirect) {const leading = `/${page.customDomain}`;const redirect = pathname.startsWith(leading)@@ -75,7 +78,7 @@ export function resolvePasswordAction({}// Gate-out: correct password and on /login → send to page root- if (password === page.password && isOnLogin) {+ if (authorized && isOnLogin) {if (needsCustomDomainRedirect) {return {type: "redirect",diff --git a/apps/status-page/src/proxy.ts b/apps/status-page/src/proxy.tsindex cddbab15c..ab8511f2b 100644--- a/apps/status-page/src/proxy.ts+++ b/apps/status-page/src/proxy.ts@@ -3,10 +3,12 @@ import { page, selectPageSchema } from "@openstatus/db/src/schema";import { NextResponse } from "next/server";import { auth } from "@/lib/auth";+import { resolveClientIp } from "@/lib/http/client-ip";import { createProtectedCookieKey } from "./lib/protected";import { applyPageLocaleOverride } from "./lib/proxy/apply-page-locale-override";import { composePageAction } from "./lib/proxy/compose-page-action";+import { detectMarkdown } from "./lib/proxy/detect-markdown";import { sanitizeRedirectParam } from "./lib/proxy/sanitize-redirect-param";import { resolveRoute } from "./lib/resolve-route";@@ -15,18 +17,42 @@ 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");+ // 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({+ pathname: url.pathname,+ accept: req.headers.get("accept"),+ });+const initialRoute = resolveRoute({host,urlHost: url.host,- pathname: url.pathname,+ pathname,});if (!initialRoute) {return passthroughResponse;}+ // Markdown requests bypass the proxy's DB lookup and gate chain: the route is+ // reachable directly via `/api` anyway, so it re-validates every gate itself.+ // Short-circuiting before the gates avoids 307-redirecting a gated `.md` to+ // /login (it would never reach the route).+ if (wantsMarkdown) {+ const rewriteUrl = url.clone();+ rewriteUrl.pathname = `/api/markdown${initialRoute.rewritePath}`;+ const requestHeaders = new Headers(req.headers);+ requestHeaders.set("x-md-source", source ?? "header");+ return NextResponse.rewrite(rewriteUrl, {+ request: { headers: requestHeaders },+ });+ }+const query = await db.select().from(page)@@ -44,10 +70,7 @@ export default auth(async (req) => {const _page = validation.data;const route = applyPageLocaleOverride(initialRoute, _page);- // 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 clientIp = resolveClientIp(req.headers);console.log("[proxy] request", {host,@@ -88,8 +111,13 @@ export default auth(async (req) => {switch (action.type) {case "redirect":return NextResponse.redirect(action.url);- case "rewrite":- return NextResponse.rewrite(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 "passthrough":return passthroughResponse;}diff --git a/apps/web/public/assets/posts/status-page-markdown-for-agents/status-page-markdown-for-agents.png b/apps/web/public/assets/posts/status-page-markdown-for-agents/status-page-markdown-for-agents.pngnew file mode 100644index 000000000..564e63524Binary files /dev/null and b/apps/web/public/assets/posts/status-page-markdown-for-agents/status-page-markdown-for-agents.png differdiff --git a/apps/web/src/content/pages/blog/status-page-markdown-for-agents.mdx b/apps/web/src/content/pages/blog/status-page-markdown-for-agents.mdxnew file mode 100644index 000000000..4f61e4131--- /dev/null+++ b/apps/web/src/content/pages/blog/status-page-markdown-for-agents.mdx@@ -0,0 +1,119 @@+---+title: "Tokenminning: a status page your agents can actually read"+description: "The same status page URL now serves a React page to humans and clean markdown to agents - chosen by Accept: text/markdown or a .md suffix. The page drops from ~60k tokens of HTML to ~1.2k of markdown, with the answer in the frontmatter. Here's how and why."+image: "/assets/posts/status-page-markdown-for-agents/status-page-markdown-for-agents.png"+author: "Maximilian Kaske"+publishedAt: "2026-06-22"+category: "engineering"+---++> everyone is tokenmaxxing, we are tokenminning++An agent asking "is acme.com up?" should not have to render React, hunt for the right `<div>`, and guess what green means.++But that's all we ever gave it: a status page built for eyeballs. Color, animation, a 60,000-token DOM. Great for a human at 2am. Useless for the LLM that human just asked.++So we gave the status page a second reader. Same URL. The human gets the page. The agent gets markdown.++## One URL, two readers++You don't get a new API. You get the page you already share, in the format the caller asks for:++```bash+curl https://acme.openstatus.dev/monitors # HTML, for humans+curl -H "Accept: text/markdown" https://acme.openstatus.dev/monitors # markdown+curl https://acme.openstatus.dev/monitors.md # markdown (byte-identical)+```++Two ways in - the `Accept` header for agents that set it, the `.md` suffix for everything that can't (a link in a doc, a crawler, you in a terminal at 2am). The suffix wins over the header on purpose: a `.md` URL is a stable cache key, so it keeps the cache-safe path even when a client also sends `Accept`. Everything else carries `Vary: Accept` so a shared cache never hands an agent the human page or a human the agent page.++We didn't invent this. `Accept: text/markdown` is quietly becoming the handshake - Cloudflare now does [the same negotiation at the edge](https://developers.cloudflare.com/fundamentals/reference/markdown-for-agents/) for any site behind it, and calls markdown "the lingua franca for agents." The difference is *where the markdown comes from*. Edge conversion turns your **HTML** into markdown - generic, best-effort, working from whatever DOM it happens to see. We generate markdown from the **data**, which is the whole reason the next part works.++## The numbers (or: why we bother)++Same status page, fetched both ways, then tokenized:++| Request | What you get | Bytes | Tokens |+| --- | --- | --- | --- |+| `GET /status` | HTML | ~166 KB | ~59,500 |+| `GET /status.md` *(or `Accept: text/markdown`)* | markdown | ~4.7 KB | ~1,225 |+| **Shrinks by** | | **~36×** | **~49×** |++That's a status page going from ~59,500 tokens to ~1,225 - roughly **49× lighter**. The `.md` suffix and the `Accept` header return byte-identical markdown; how you ask doesn't change what you get. The homepage tells the same story: ~181 KB / ~60,000 tokens of HTML collapse to ~8.8 KB / ~2,100 tokens as `/index.md`, about **28× lighter**.++Either way it's not an optimization, it's a threshold. At ~60k tokens a status page is a real bite out of a context window and an agent will skip it. At ~1k it's basically free to read - and since the answer lives in the frontmatter, the agent often never reads the body at all.++And notice tokens shrink *more* than bytes do. The status page is a ~36× byte cut (166 KB → 4.7 KB) but a ~49× token cut - because HTML spends tokens on class soup, escaped entities, and inline `<script>` blobs an agent pays for and immediately throws in the bin. Bytes are what you transfer; tokens are what you're billed to *think* about. That's the tokenmaxxing tax. We'd rather not pay it.++**How we measured.** No magic - fetch the bytes, count the tokens:++```js+// count.mjs — `node count.mjs`+import { encode } from "gpt-tokenizer/encoding/o200k_base";++const urls = [+ "https://status.openstatus.dev", // HTML+ "https://status.openstatus.dev/.md", // markdown (root → `/.md`)+];+for (const url of urls) {+ const res = await fetch(url);+ const buf = Buffer.from(await res.arrayBuffer());+ console.log(buf.length, "bytes", encode(buf.toString("utf8")).length, "tokens", url);+}+```++We counted with OpenAI's `o200k_base` (the GPT-4o encoding) and cross-checked against `cl100k_base` - the two agree within ~5%. Claude's tokenizer draws its boundaries in slightly different places, but the order of magnitude - ~60k vs ~1k - doesn't budge. The `~` is on purpose: the claim is "~50×," not a leaderboard score.++## The refresh button is a `while` loop now++People used to *subscribe* to a status page. Type in your email, wait for the "we're back" message, get on with your day. Increasingly they don't. They point an agent at the page and put it on a loop - literally `/loop check if acme is back every 2 minutes` - and walk away while it polls.++That flips the economics. An email subscription is *one* notification when something changes. A polling loop is a fetch every couple of minutes, forever, until the service recovers - and an outage is precisely when *everyone's* loop is hammering the page at the same time. At ~60k tokens a pull, a handful of people asking "is it back yet?" every two minutes burns more context - and more money - than the incident itself. At 1.2k, with a `304` whenever nothing changed, it's a rounding error.++That's the real reason tokenminning matters. We're not shaving tokens for a leaderboard. The dominant reader of a status page is becoming a loop, not a person, and a loop checks far more often than the page ever changes. Build for the reader you're actually getting.++## The answer lives in the frontmatter++The point isn't prettier text. It's that "is it up?" should cost almost nothing to read. So every page opens with a live snapshot in YAML frontmatter:++```yaml+---+title: "Acme Status"+status: "operational"+fetched_at: "2026-06-20T14:50:00.000Z"+active_reports: 0+active_maintenance: 0+components_operational: 5+components_total: 5+worst_component: null+---+```++The agent gets its answer from the top ten lines, no body required. `fetched_at` is the snapshot's real generation time - an honest freshness signal - floored to the minute. That's not cosmetic: a minute-granular timestamp keeps the body (and its ETag) stable inside the cache window, so a polling agent gets a `304 Not Modified` instead of re-billing the read every few seconds. (Cloudflare returns an `x-markdown-tokens` header in the same spirit - tell the caller the cost up front.)++## Markdown has no color, so shape carries the meaning++The uptime bar is the fun part. On the web it's pretty colored bars. In markdown there is no color, so we encode status as *shape* - one ASCII column per day:++```text+`+` operational · `~` degraded · `x` outage · `=` maintenance · `.` no data+`+++++~++x+++++++++++++++++++++++`+```++`x` reads as "down" with zero rendering.++Our first instinct was emoji - 🟩🟩🟧🟩🟥🟩🟩 - which a human skims instantly. Then we tokenized it. A 45-day emoji bar costs **134 tokens**; the same bar in ASCII costs **8**. Every emoji is its own ~3-token unit that never compresses, while a run of `+` collapses into a single multi-character token. So we picked ASCII, and we'll be honest about why: it's *not* about human readability - nobody's curling a status page for the vibes. It saves ~17× the tokens. And, fine, ASCII is just nerdier, and a monospace `+++x++` bar in a terminal is the kind of thing this audience likes. Two birds.++Two things bit us getting here. The glyphs live in a code span so they stay monospace and *aligned* - and so markdown leaves them alone, because a bare run of `~~` would otherwise turn into ~~strikethrough~~ and ruin the whole bar. Incident timelines get the same treatment: a fenced, greppable log, sortable timestamp first, user-written titles stripped of newlines so nobody can sneak in a line that closes the fence.++## Gated pages stay gated++A status page can be password-, email-, or IP-gated. The markdown path honors the same gate - and is paranoid about it. Public pages get an edge cache and advertise their machine-readable cousins (`summary.json`, `current.json`, an `llms.txt` index). Gated pages get `private, no-store` and advertise *nothing* - the discovery doc 404s before it can leak so much as the title of a page you weren't allowed to see. A ~50× token win is not worth one accidental data leak.++## The docs and marketing site have done this since February++None of this is new to `openstatus.dev` - we shipped the same `Accept` / `.md` negotiation for the docs, guides, and blog back in mid-February, months before the status page. This very post is served the same way - don't take the numbers on faith, `curl -sL https://www.openstatus.dev/blog/status-page-markdown-for-agents.md` and count the tokens yourself. It's also how our own MCP server feeds the docs back to an agent. And for callers that don't even want prose, there's a JSON tier: `current.json` is the cheapest possible "is it up?", and `summary.json` is Statuspage-compatible so existing tooling just works.++The web didn't get more machine-readable by accident. We took the pages we already had, gave them a second reader, and handed that reader the answer first.++Tokenmaxx less. Tokenmin more.diff --git a/packages/api/src/router/statusPage.ts b/packages/api/src/router/statusPage.tsindex 2692108c6..cceff91e2 100644--- a/packages/api/src/router/statusPage.ts+++ b/packages/api/src/router/statusPage.ts@@ -7,6 +7,7 @@ import {pageConfigurationSchema,selectMaintenancePageSchema,selectPageComponentWithMonitorRelation,+ selectPageSchema,selectPublicMonitorSchema,selectPublicPageLightSchemaWithRelation,selectPublicPageSchemaWithRelation,@@ -61,6 +62,36 @@ import {const WORKSPACES =process.env.WORKSPACES_LOOKBACK_30?.split(",").map(Number) || [];+// Length-independent comparison so a wrong guess can't be timed by length or+// character. Pure JS (no node:crypto) keeps it usable from the Edge runtime.+function constantTimeEqual(+ a: string | null | undefined,+ b: string | null | undefined,+): boolean {+ if (a == null || b == null) return false;+ // constant-time: iterate over the max length and fold the length delta into+ // the accumulator so we never early-return or branch on length.+ const max = Math.max(a.length, b.length);+ let mismatch = a.length ^ b.length;+ for (let i = 0; i < max; i++) {+ // out-of-range indices read as 0; mismatch already non-zero on length diff.+ mismatch |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);+ }+ return mismatch === 0;+}++// Gate fields for getGate, reusing selectPageSchema's stringToArray transforms+// so authEmailDomains / allowedIpRanges come back as arrays like getLight.+const gateFieldsSchema = selectPageSchema.pick({+ slug: true,+ customDomain: true,+ accessType: true,+ authEmailDomains: true,+ allowedIpRanges: true,+ homepageUrl: true,+ contactUrl: true,+});+export const statusPageRouter = createTRPCRouter({get: publicProcedure.input(@@ -480,6 +511,9 @@ export const statusPageRouter = createTRPCRouter({(c) => c.monitor?.incidents ?? [],);+ const ws = selectWorkspaceSchema.safeParse(_page.workspace);+ const whiteLabel = ws.data?.limits["white-label"] ?? false;+return selectPublicPageLightSchemaWithRelation.parse({..._page,monitors,@@ -489,9 +523,42 @@ export const statusPageRouter = createTRPCRouter({pageComponents: _page.pageComponents,pageComponentGroups: _page.pageComponentGroups,workspacePlan: _page.workspace.plan,+ whiteLabel,});}),+ // Narrow access-check query for the markdown detail routes: returns only the+ // gate + chrome fields, skipping the full reports/maintenances/components graph+ // that getLight loads.+ getGate: publicProcedure+ .input(z.object({ slug: z.string().toLowerCase() }))+ .query(async (opts) => {+ if (!opts.input.slug) return null;++ const _page = await opts.ctx.db.query.page.findFirst({+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ columns: {+ slug: true,+ customDomain: true,+ accessType: true,+ authEmailDomains: true,+ allowedIpRanges: true,+ homepageUrl: true,+ contactUrl: true,+ },+ with: { workspace: true },+ });++ if (!_page) return null;++ const ws = selectWorkspaceSchema.safeParse(_page.workspace);+ const whiteLabel = ws.data?.limits["white-label"] ?? false;++ const { workspace: _workspace, ...rest } = _page;+ const gate = gateFieldsSchema.parse(rest);+ return { ...gate, whiteLabel };+ }),+getMaintenance: publicProcedure.input(z.object({ slug: z.string().toLowerCase(), id: z.number() })).query(async (opts) => {@@ -501,7 +568,7 @@ export const statusPageRouter = createTRPCRouter({.select().from(page).where(- sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,).get();@@ -543,7 +610,7 @@ export const statusPageRouter = createTRPCRouter({if (!input.slug) return null;const _page = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${input.slug} OR lower(${page.customDomain}) = ${input.slug}`,+ where: sql`lower(${page.slug}) = ${input.slug} OR lower(${page.customDomain}) = ${input.slug}`,with: {maintenances: {with: {@@ -736,7 +803,7 @@ export const statusPageRouter = createTRPCRouter({.select().from(page).where(- sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,).get();@@ -853,7 +920,7 @@ export const statusPageRouter = createTRPCRouter({// NOTE: revalidate the public monitors firstconst _page = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,with: {pageComponents: {with: {@@ -953,7 +1020,7 @@ export const statusPageRouter = createTRPCRouter({if (!opts.input.slug) return null;const _page = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,with: {pageComponents: {where: eq(pageComponent.monitorId, opts.input.id),@@ -1046,7 +1113,7 @@ export const statusPageRouter = createTRPCRouter({if (!opts.input.slug) return null;const _page = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,with: {workspace: true,},@@ -1169,7 +1236,7 @@ export const statusPageRouter = createTRPCRouter({if (!opts.input.slug) return null;const _page = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,});if (!_page) {@@ -1237,7 +1304,7 @@ export const statusPageRouter = createTRPCRouter({if (!opts.input.slug) return null;const _page = await opts.ctx.db.query.page.findFirst({- where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,});if (!_page) {@@ -1254,7 +1321,7 @@ export const statusPageRouter = createTRPCRouter({});}- if (_page.password !== opts.input.password) {+ if (!constantTimeEqual(_page.password, opts.input.password)) {throw new TRPCError({code: "BAD_REQUEST",message: "Invalid password",@@ -1264,6 +1331,29 @@ export const statusPageRouter = createTRPCRouter({return true;}),+ // Server-side password gate for the public `/api/*` routes. Returns a boolean+ // so the stored password never leaves the server (the `get` output omits it).+ isPasswordAuthorized: publicProcedure+ .input(+ z.object({+ slug: z.string().toLowerCase(),+ queryPassword: z.string().nullish(),+ cookiePassword: z.string().nullish(),+ }),+ )+ .query(async (opts) => {+ const _page = await opts.ctx.db.query.page.findFirst({+ where: sql`lower(${page.slug}) = ${opts.input.slug} OR lower(${page.customDomain}) = ${opts.input.slug}`,+ columns: { password: true, accessType: true },+ });+ if (!_page || _page.accessType !== "password") return false;+ // TODO: rate-limit — an unauthenticated caller can brute-force guesses here.+ // Query param wins over cookie: a present-but-wrong `?pw=` must not fall+ // through to a valid cookie. Mirrors isPasswordAuthorized on the proxy.+ const submitted = opts.input.queryPassword ?? opts.input.cookiePassword;+ return constantTimeEqual(_page.password, submitted);+ }),+getSubscriberByToken: publicProcedure.input(z.object({ token: z.uuid(), domain: z.string().toLowerCase() })).query(async (opts) => {diff --git a/packages/db/src/schema/shared.ts b/packages/db/src/schema/shared.tsindex eba7cf99a..d6c23baf1 100644--- a/packages/db/src/schema/shared.ts+++ b/packages/db/src/schema/shared.ts@@ -179,30 +179,38 @@ export const selectPublicPageLightSchemaWithRelation = selectPageSchema// NEW: Include pageComponents for modern consumerspageComponents: selectPageComponentWithMonitorRelation.array().prefault([]),pageComponentGroups: selectPageComponentGroupSchema.array().prefault([]),+ whiteLabel: z.boolean().prefault(false),})+ // `password` is access-control state, never client-facing — gates read it+ // server-side from the DB. See status-page markdown/feed routes..omit({id: true,+ password: true,});-export const selectPublicPageSchemaWithRelation = selectPageSchema.extend({- monitorGroups: selectMonitorGroupSchema.array().prefault([]),- // TODO: include status of the monitor- monitors: selectPublicMonitorWithStatusSchema.array(),- pageComponents: selectPageComponentWithMonitorRelation.array().prefault([]),- pageComponentGroups: selectPageComponentGroupSchema.array().prefault([]),- trackers: trackersSchema,- lastEvents: z.array(statusPageEventSchema),- openEvents: z.array(statusPageEventSchema),- statusReports: z.array(selectStatusReportPageSchema),- incidents: z.array(selectIncidentSchema),- maintenances: z.array(selectMaintenancePageSchema),- status: z.enum(["success", "degraded", "error", "info"]).prefault("success"),- workspacePlan: workspacePlanSchema- .nullable()- .prefault("free")- .transform((val) => val ?? "free"),- whiteLabel: z.boolean().prefault(false),-});+export const selectPublicPageSchemaWithRelation = selectPageSchema+ .extend({+ monitorGroups: selectMonitorGroupSchema.array().prefault([]),+ // TODO: include status of the monitor+ monitors: selectPublicMonitorWithStatusSchema.array(),+ pageComponents: selectPageComponentWithMonitorRelation.array().prefault([]),+ pageComponentGroups: selectPageComponentGroupSchema.array().prefault([]),+ trackers: trackersSchema,+ lastEvents: z.array(statusPageEventSchema),+ openEvents: z.array(statusPageEventSchema),+ statusReports: z.array(selectStatusReportPageSchema),+ incidents: z.array(selectIncidentSchema),+ maintenances: z.array(selectMaintenancePageSchema),+ status: z+ .enum(["success", "degraded", "error", "info"])+ .prefault("success"),+ workspacePlan: workspacePlanSchema+ .nullable()+ .prefault("free")+ .transform((val) => val ?? "free"),+ whiteLabel: z.boolean().prefault(false),+ })+ .omit({ password: true });export type StatusReportWithUpdates = z.infer<typeof selectStatusReportPageSchemadiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 976e7d002..8c362b6d1 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -757,7 +757,7 @@ importers:version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: 'catalog:'- version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])next-themes:specifier: 'catalog:'@@ -1192,10 +1192,10 @@ importers:version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: 'catalog:'- version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])next-intl:specifier: 'catalog:'- version: 4.12.0([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])+ version: 4.12.0([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])next-plausible:specifier: 'catalog:'version: 3.12.5([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])@@ -1269,6 +1269,9 @@ importers:'@types/react-dom':specifier: 'catalog:'version: 19.2.3(@types/[email protected])+ bun-types:+ specifier: 'catalog:'+ version: 1.3.14shadcn:specifier: 'catalog:'@@ -1454,7 +1457,7 @@ importers:version: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])next-auth:specifier: 'catalog:'- version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])next-mdx-remote:specifier: 'catalog:'version: 6.0.0(@types/[email protected])([email protected])@@ -1910,7 +1913,7 @@ importers:version: 0.31.10next-auth:specifier: 'catalog:'- version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected])+ version: 5.0.0-beta.31([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])typescript:specifier: 'catalog:'version: 5.9.3@@ -14732,7 +14735,7 @@ snapshots:'@slack/[email protected]':dependencies:- '@types/node': 24.10.1+ '@types/node': 24.12.4'@slack/[email protected]': {}@@ -15120,7 +15123,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 24.10.1+ '@types/node': 24.12.4'@types/[email protected]':dependencies:@@ -15177,7 +15180,7 @@ snapshots:'@types/[email protected]':dependencies:'@types/minimatch': 6.0.0- '@types/node': 24.10.1+ '@types/node': 24.12.4'@types/[email protected]':dependencies:@@ -15214,7 +15217,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 24.10.1+ '@types/node': 24.12.4'@types/[email protected]':dependencies:@@ -15232,7 +15235,7 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 24.10.1+ '@types/node': 24.12.4pg-protocol: 1.10.3pg-types: 2.2.0@@ -15261,11 +15264,11 @@ snapshots:'@types/[email protected]':dependencies:- '@types/node': 24.10.1+ '@types/node': 24.12.4'@types/[email protected]':dependencies:- '@types/node': 24.10.1+ '@types/node': 24.12.4'@types/[email protected]': {}@@ -15638,7 +15641,7 @@ snapshots:dependencies:- '@types/node': 24.10.1+ '@types/node': 24.12.4dependencies:@@ -18045,7 +18048,7 @@ snapshots:- [email protected]([email protected](@opentelemetry/[email protected])([email protected]([email protected]))([email protected]))([email protected]):+ [email protected]([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]):dependencies:'@auth/core': 0.41.2next: 16.2.6(@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected])@@ -18053,7 +18056,7 @@ snapshots:- [email protected]([email protected](@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):+ [email protected]([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected]):dependencies:'@formatjs/intl-localematcher': 0.8.1'@parcel/watcher': 2.5.1