Skip to content

The only tool you need to know what is happening and how to fix it.

feat: status pages with proxy+CNAME setup (non iframe approach)

narrow-adventurec71465cbbd6a
diff --git a/CLAUDE.md b/CLAUDE.md
index c268cf92..6548f2b9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -609,7 +609,7 @@ backend/
| Synthetic runner API | `UseRunnerAuth` only (shared SYNTHETICS_RUNNER_SECRET bearer + self-registration by X-Traceway-Runner-Name; no Transactional — poll holds the request up to 25s) |
| Public status page | `RateLimitPerIP` only |
-**Global middleware** (registered in `cmd/run.go` ahead of the routes): `middleware.GuardBodyReads` (every request body gets the progress guard, 30s idle / 10 min total / 1 KB/s floor after 20s, answering through `middleware.BodyReadError` as 408; routes with their own budget call `GuardBodyRead` again, which re-arms the same guard rather than wrapping twice, so uploads get 30s/30 min, `/api/report` 20s/10 min and OTLP 20s/2 min. The guard clears the socket read deadline the moment the body is complete: Go's background connection read would otherwise time out and cancel the request context of any handler that outlives the idle window. The `http.Server` `ReadTimeout` is a 1h backstop that only applies while a body is still arriving (the guard lifts it for bodiless requests too, so a long-lived handler such as the MCP `GET /mcp` stream is not cancelled after an hour), `ReadHeaderTimeout` is 15s), `configureClientIP` (gin's trusted proxies from `Cfg.TrustedProxyList`, plus `TrustedPlatform` from `TRUSTED_PROXY_HEADER`; a malformed list panics), `warnOnUntrustedForwardedFor` (list mode only: one-time log when a forwarding header arrives from a peer outside `TRUSTED_PROXIES`), and `middleware.SecurityHeaders` (`X-Frame-Options: DENY`, CSP `frame-ancestors 'none'; base-uri 'self'; form-action 'self'`, `Referrer-Policy`, `nosniff`). The two frame headers are skipped for any `/status/*` or `/api/status/*` path so public status pages stay embeddable in an iframe. A status page served at the root of a custom domain is not exempt: the same root serves the logged-in dashboard on every hostname the backend answers on, so it must not be frameable there.
+**Global middleware** (registered in `cmd/run.go` ahead of the routes): `middleware.GuardBodyReads` (every request body gets the progress guard, 30s idle / 10 min total / 1 KB/s floor after 20s, answering through `middleware.BodyReadError` as 408; routes with their own budget call `GuardBodyRead` again, which re-arms the same guard rather than wrapping twice, so uploads get 30s/30 min, `/api/report` 20s/10 min and OTLP 20s/2 min. The guard clears the socket read deadline the moment the body is complete: Go's background connection read would otherwise time out and cancel the request context of any handler that outlives the idle window. The `http.Server` `ReadTimeout` is a 1h backstop that only applies while a body is still arriving (the guard lifts it for bodiless requests too, so a long-lived handler such as the MCP `GET /mcp` stream is not cancelled after an hour), `ReadHeaderTimeout` is 15s), `configureClientIP` (gin's trusted proxies from `Cfg.TrustedProxyList`, plus `TrustedPlatform` from `TRUSTED_PROXY_HEADER`; a malformed list panics), `warnOnUntrustedForwardedFor` (list mode only: one-time log when a forwarding header arrives from a peer outside `TRUSTED_PROXIES`), and `middleware.SecurityHeaders` (`X-Frame-Options: DENY`, CSP `frame-ancestors 'none'; base-uri 'self'; form-action 'self'`, `Referrer-Policy`, `nosniff`). The two frame headers are skipped for any `/status/*` or `/api/status/*` path so public status pages stay embeddable in an iframe. A custom-domain status host is exempt as a whole: the SPA handler serves nothing but that status page there, so it drops the two headers itself (see the status domains row below).
### API Endpoints
@@ -851,7 +851,7 @@ Checks (`synthetic_checks`, main DB) are http/tcp/browser probes with per-check
| GET/POST/PUT/DELETE | `/api/organizations/:organizationId/status-pages(/:id)` | Member / Admin | Status page CRUD (slug `[a-z0-9-]{3,60}` unique, checkIds validated against the org; branding fields `description`, `customDomain` unique hostname) |
| POST | `/api/organizations/:organizationId/status-pages/:id/logo` | Admin | Upload a PNG/JPEG logo (raw body, 1MB cap, sniffed content type; SVG rejected as scriptable) stored via storage.Store under `statuspages/<id>/logo` |
| GET | `/api/status/:slug/logo` | None (rate-limited) | Streams a public page's logo |
-| GET | `/api/status-domains/resolve` | None (rate-limited) | Maps the request Host header to a public status page slug — backs CNAMEd vanity domains (TLS terminates at the operator's proxy); the SPA calls it for anonymous visits to `/` |
+| GET | `/` on a custom domain | None | Status domains (CNAMEd vanity hosts, TLS at the operator's proxy). The SPA handler in `cmd/run.go` looks the Host up with `controllers.StatusPageForHost` (public pages only, never the `APP_BASE_URL` host) and, on a match, serves `index.html` with a `traceway-status-slug` meta tag plus the page's title and description. The frontend reads it in `$lib/status-domain.ts` and the root layout renders only `StatusPageView` at `/`, whatever the auth state. Every other page path on that host 302s to `/`, so the dashboard never loads on a customer's domain; static assets and `/api` still work. Saving a custom domain equal to `APP_BASE_URL`'s host or the admin's current host answers 422 |
| GET | `/api/status/:slug` | None (rate-limited) | Public status payload: per-check status + 90 daily uptime buckets + incidents + `pastIncidents` (date-grouped titles with timeline updates); cached ~30s per slug; private/unknown slugs are both 404; latency values and internal error messages stripped. Frontend page: `/status/[slug]` (in `isPublicPath`) |
| GET | `/api/organizations/:organizationId/incidents` | Member | Org incidents (90d, joined check/status-page names, updatesCount, postMortemId) |
| GET | `/api/organizations/:organizationId/incidents/:incidentId/updates` | Member | One incident + its timeline updates |
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 9c27c1bc..0c91f539 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -324,9 +324,6 @@ func RegisterControllers(router *gin.RouterGroup) {
// reads main DB + telemetry through its own short transactions).
router.GET("/status/:slug", middleware.RateLimitPerIP(30, time.Minute), StatusPageController.Public)
router.GET("/status/:slug/logo", middleware.RateLimitPerIP(60, time.Minute), StatusPageController.PublicLogo)
- // Maps a CNAMEd vanity host to its status page slug (called by the SPA
- // when an anonymous visitor lands on / of an unrecognized host).
- router.GET("/status-domains/resolve", middleware.RateLimitPerIP(60, time.Minute), StatusPageController.ResolveHost)
router.GET("/organizations/:organizationId/teams", middleware.UseAppAuth, middleware.RequireOrganizationAccess, middleware.Transactional, TeamController.List)
router.POST("/organizations/:organizationId/teams", middleware.UseAppAuth, middleware.RequireAdminAccess, middleware.Transactional, TeamController.Create)
diff --git a/backend/app/controllers/status_page.controller.go b/backend/app/controllers/status_page.controller.go
index 7e16bc68..aaee2e0d 100644
--- a/backend/app/controllers/status_page.controller.go
+++ b/backend/app/controllers/status_page.controller.go
@@ -7,6 +7,7 @@ import (
"io"
"net"
"net/http"
+ "net/url"
"regexp"
"sort"
"strconv"
@@ -15,6 +16,7 @@ import (
"time"
"github.com/gin-gonic/gin"
+ "github.com/tracewayapp/traceway/backend/app/config"
"github.com/tracewayapp/traceway/backend/app/db"
"github.com/tracewayapp/traceway/backend/app/middleware"
"github.com/tracewayapp/traceway/backend/app/models"
@@ -57,7 +59,7 @@ type statusPageRequest struct {
var customDomainPattern = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)+$`)
-func validateStatusPageRequest(tx *sql.Tx, organizationId int, req *statusPageRequest) (string, error) {
+func validateStatusPageRequest(tx *sql.Tx, organizationId int, requestHost string, req *statusPageRequest) (string, error) {
req.Name = strings.TrimSpace(req.Name)
req.Slug = strings.ToLower(strings.TrimSpace(req.Slug))
if req.Name == "" {
@@ -83,6 +85,9 @@ func validateStatusPageRequest(tx *sql.Tx, organizationId int, req *statusPageRe
if req.CustomDomain != "" && !customDomainPattern.MatchString(req.CustomDomain) {
return "Custom domain must be a bare hostname like status.example.com (no scheme or path).", nil
}
+ if req.CustomDomain != "" && isDashboardHost(req.CustomDomain, requestHost) {
+ return "Custom domain must not be the host Traceway itself is served on.", nil
+ }
for _, checkId := range req.CheckIds {
check, err := transactional.SyntheticCheckRepository.FindByIdInOrganization(tx, checkId, organizationId)
if err != nil {
@@ -123,7 +128,7 @@ func (ctrl *statusPageController) Create(ctx *gin.Context) {
return
}
tx := db.GetTx(ctx)
- if message, err := validateStatusPageRequest(tx, organizationId, &req); err != nil {
+ if message, err := validateStatusPageRequest(tx, organizationId, ctx.Request.Host, &req); err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to validate status page: %w", err))
return
} else if message != "" {
@@ -194,7 +199,7 @@ func (ctrl *statusPageController) Update(ctx *gin.Context) {
ctx.JSON(http.StatusNotFound, gin.H{"error": "Status page not found"})
return
}
- if message, err := validateStatusPageRequest(tx, organizationId, &req); err != nil {
+ if message, err := validateStatusPageRequest(tx, organizationId, ctx.Request.Host, &req); err != nil {
ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to validate status page: %w", err))
return
} else if message != "" {
@@ -597,29 +602,30 @@ func (ctrl *statusPageController) PublicLogo(ctx *gin.Context) {
ctx.Data(http.StatusOK, http.DetectContentType(data), data)
}
-// ResolveHost maps the request's Host header to a public status page slug,
-// so a CNAMEd vanity domain (status.example.com -> this instance) can land
-// on its status page. TLS for the vanity host terminates at the operator's
-// proxy; this endpoint only does the host-to-slug mapping.
-func (ctrl *statusPageController) ResolveHost(ctx *gin.Context) {
- host := strings.ToLower(ctx.Request.Host)
+func normalizeHost(host string) string {
+ host = strings.ToLower(strings.TrimSpace(host))
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
- if host == "" || !customDomainPattern.MatchString(host) {
- ctx.JSON(http.StatusNotFound, gin.H{"error": "Not found"})
- return
+ return host
+}
+
+func isDashboardHost(host, requestHost string) bool {
+ if host == normalizeHost(requestHost) {
+ return true
}
- page, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.StatusPage, error) {
- return transactional.StatusPageRepository.FindPublicByCustomDomain(tx, host)
- })
- if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to resolve status host: %w", err))
- return
+ if base, err := url.Parse(config.Config.PublicBaseURL()); err == nil && base.Hostname() != "" {
+ return host == normalizeHost(base.Hostname())
}
- if page == nil {
- ctx.JSON(http.StatusNotFound, gin.H{"error": "Not found"})
- return
+ return false
+}
+
+func StatusPageForHost(requestHost string) (*models.StatusPage, error) {
+ host := normalizeHost(requestHost)
+ if host == "" || !customDomainPattern.MatchString(host) || isDashboardHost(host, "") {
+ return nil, nil
}
- ctx.JSON(http.StatusOK, gin.H{"slug": page.Slug})
+ return db.ExecuteTransaction(func(tx *sql.Tx) (*models.StatusPage, error) {
+ return transactional.StatusPageRepository.FindPublicByCustomDomain(tx, host)
+ })
}
diff --git a/backend/cmd/run.go b/backend/cmd/run.go
index f3058733..5789ea94 100644
--- a/backend/cmd/run.go
+++ b/backend/cmd/run.go
@@ -1,8 +1,10 @@
package cmd
import (
+ "bytes"
"context"
"fmt"
+ "html"
"io/fs"
"net"
"net/http"
@@ -558,19 +560,51 @@ func createSPAHandler(staticFS fs.FS) gin.HandlerFunc {
}
cleanPath := strings.TrimPrefix(path, "/")
- if cleanPath != "" {
+ isPage := cleanPath == "" || strings.HasSuffix(cleanPath, ".html")
+ if !isPage {
if data, err := fs.ReadFile(staticFS, cleanPath); err == nil {
- contentType := detectContentType(cleanPath)
- c.Data(200, contentType, data)
+ c.Data(200, detectContentType(cleanPath), data)
return
}
}
+ statusPage, err := controllers.StatusPageForHost(c.Request.Host)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to resolve status page host: %w", err))
+ return
+ }
+
+ if statusPage == nil && cleanPath != "" && isPage {
+ if data, err := fs.ReadFile(staticFS, cleanPath); err == nil {
+ c.Data(200, detectContentType(cleanPath), data)
+ return
+ }
+ }
+
+ if statusPage != nil && path != "/" {
+ c.Redirect(http.StatusFound, "/")
+ return
+ }
+
indexData, err := fs.ReadFile(staticFS, "index.html")
if err != nil {
c.JSON(404, gin.H{"error": "Not found"})
return
}
+ if statusPage != nil {
+ title := html.EscapeString(statusPage.Name + " status")
+ head := `<meta name="traceway-status-slug" content="` + html.EscapeString(statusPage.Slug) + `">` +
+ `<meta property="og:title" content="` + title + `">`
+ if statusPage.Description != "" {
+ description := html.EscapeString(statusPage.Description)
+ head += `<meta name="description" content="` + description + `">` +
+ `<meta property="og:description" content="` + description + `">`
+ }
+ indexData = bytes.Replace(indexData, []byte("<title>Traceway</title>"), []byte("<title>"+title+"</title>"), 1)
+ indexData = bytes.Replace(indexData, []byte("</head>"), []byte(head+"</head>"), 1)
+ c.Header("Content-Security-Policy", "base-uri 'self'; form-action 'self'")
+ c.Writer.Header().Del("X-Frame-Options")
+ }
c.Data(200, "text/html; charset=utf-8", indexData)
}
}
diff --git a/docs/pages/learn/monitors.mdx b/docs/pages/learn/monitors.mdx
index ad367f03..96ff1c04 100644
--- a/docs/pages/learn/monitors.mdx
+++ b/docs/pages/learn/monitors.mdx
@@ -31,15 +31,76 @@ Add a notification rule of type **Monitor Down** on the Alerts page. It fires wh
A status page publishes the uptime of selected monitors at `/status/<slug>`: a branded light page with 90 days of per-day uptime bars (green operational, amber partial outage, red major outage, gray no data), incident history, and no login required. Create one under the **Status Pages** tab on the Monitors page (organization admins only), pick the monitors, choose a slug, and toggle it public. Branding: a title, an optional description, and an uploaded PNG/JPEG logo. Latency numbers stay internal; the public payload only carries availability.
-### Custom domains
-
-Each status page can carry a custom domain (for example `status.acme.com`):
-
-1. Set the domain on the status page.
-2. Create a DNS CNAME from that hostname to your Traceway instance's hostname.
-3. Terminate TLS for the vanity hostname at your reverse proxy (Caddy and Traefik can issue certificates for it automatically; with nginx use certbot).
+### Serving a status page on your own domain
+
+Every public status page is always available at `/status/<slug>` on your Traceway instance. On Traceway Cloud that is `https://cloud.tracewayapp.com/status/<slug>`. To show it on a domain of your own, such as `status.acme.com`, there are two paths:
+
+| | Path 1: CNAME | Path 2: iframe |
+|---|---|---|
+| Works on | Self-hosted Traceway | Traceway Cloud and self-hosted |
+| What you host | Nothing, DNS points at Traceway | One static HTML file |
+| Who provides HTTPS for `status.acme.com` | A reverse proxy with SSL in front of Traceway, such as Cloudflare | Whatever hosts the HTML file |
+| Custom domain field on the status page | Set to `status.acme.com` | Left empty |
+
+Both paths need the status page to be public.
+
+#### Path 1: CNAME to your Traceway instance
+
+Use this when you run Traceway yourself. Traceway does not handle HTTPS itself, so this path needs a reverse proxy with SSL in front of it. That proxy holds the certificate for `status.acme.com` and forwards requests to Traceway. Traceway Cloud does not issue certificates for your hostnames, so on Cloud use path 2.
+
+Any of these proxies works:
+
+- **Cloudflare.** Put `status.acme.com` on Cloudflare and turn the proxy on for the record (the orange cloud). Cloudflare serves the certificate to visitors. Your server still has to answer HTTPS for Cloudflare's connection: with SSL/TLS set to **Full** any certificate is accepted, and with **Full (strict)** install a Cloudflare Origin CA certificate that covers `status.acme.com`.
+- **Caddy or Traefik** on your server. Both issue a Let's Encrypt certificate for the new hostname automatically.
+- **nginx** on your server, with a certificate from certbot.
+
+Then:
+
+1. Set **Custom domain** on the status page to `status.acme.com`.
+2. Create a DNS CNAME record from `status.acme.com` to your Traceway instance's hostname.
+3. Add `status.acme.com` to your reverse proxy with its certificate. The proxy must pass the original `Host` header through, since that is how Traceway recognizes the domain. Cloudflare, Caddy and Traefik do this by default. With nginx, set `proxy_set_header Host $host;`.
+
+Anyone who opens `https://status.acme.com` sees the status page at `/`, whether or not they are logged in to Traceway. The dashboard is never served on a status domain, and every other path redirects to `/`. The custom domain can't be the hostname Traceway itself runs on.
+
+#### Path 2: embed the page in an iframe
+
+Use this on Traceway Cloud, or on a self-hosted instance when you would rather not touch the proxy. Status pages are allowed to be framed by any site, so you host one small HTML file that fills the whole window with the status page.
+
+1. Leave **Custom domain** empty on the status page and note its slug.
+2. Save the file below as `index.html` and replace `acme` with your slug. On a self-hosted instance, also replace `https://cloud.tracewayapp.com` with your own Traceway URL.
+3. Host it at `status.acme.com` on any static host with HTTPS, such as Cloudflare Pages, Netlify, GitHub Pages, or an S3 bucket behind CloudFront.
+
+```html filename="index.html"
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Acme status</title>
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ }
+ iframe {
+ display: block;
+ width: 100%;
+ height: 100%;
+ border: 0;
+ }
+ </style>
+ </head>
+ <body>
+ <iframe src="https://cloud.tracewayapp.com/status/acme" title="Acme status"></iframe>
+ </body>
+</html>
+```
-Anonymous visitors hitting the instance under that Host are routed to the status page automatically (the backend maps the Host header to the page via `/api/status-domains/resolve`).
+The iframe takes the full window with no padding or border, and the status page scrolls inside it. The page keeps refreshing on its own, so the file never needs to change. Search engines and link previews see only this file, so set its `<title>` to something meaningful.
## Incidents and post-mortems
diff --git a/frontend/src/lib/components/traceway/status-page-view.svelte b/frontend/src/lib/components/traceway/status-page-view.svelte
new file mode 100644
index 00000000..c853a88f
--- /dev/null
+++ b/frontend/src/lib/components/traceway/status-page-view.svelte
@@ -0,0 +1,755 @@
+<script lang="ts">
+ import { onMount, onDestroy } from 'svelte';
+ import { SvelteDate, SvelteMap } from 'svelte/reactivity';
+
+ interface StatusDay {
+ bucket: string;
+ total: number;
+ up: number;
+ missed: number;
+ }
+
+ interface StatusIncident {
+ startedAt: string;
+ resolvedAt: string | null;
+ }
+
+ interface StatusCheck {
+ name: string;
+ checkType: string;
+ status: 'up' | 'down' | 'unknown';
+ uptimePct: number | null;
+ days: StatusDay[];
+ incidents: StatusIncident[];
+ }
+
+ interface PastIncidentUpdate {
+ status: string;
+ message: string;
+ createdAt: string;
+ }
+
+ interface PastIncident {
+ title: string;
+ startedAt: string;
+ resolvedAt: string | null;
+ updates: PastIncidentUpdate[];
+ }
+
+ interface StatusView {
+ name: string;
+ description: string;
+ hasLogo: boolean;
+ checks: StatusCheck[];
+ pastIncidents: PastIncident[];
+ generatedAt: string;
+ }
+
+ let { slug }: { slug: string } = $props();
+
+ type LoadState = 'loading' | 'ready' | 'notFound' | 'error';
+ let loadState = $state<LoadState>('loading');
+ let view = $state<StatusView | null>(null);
+ let refreshTimer: ReturnType<typeof setInterval> | null = null;
+
+ const DAYS = 90;
+
+ type DayCell = {
+ date: Date;
+ state: 'operational' | 'degraded' | 'down' | 'empty';
+ uptimePct: number | null;
+ };
+
+ // Deliberately a raw fetch: the api client's 401 handling would bounce
+ // anonymous visitors to /login, and this page must work logged out.
+ async function loadStatus() {
+ try {
+ const response = await fetch(`/api/status/${encodeURIComponent(slug)}`);
+ if (response.status === 404) {
+ loadState = 'notFound';
+ return;
+ }
+ if (!response.ok) {
+ throw new Error(`status ${response.status}`);
+ }
+ view = await response.json();
+ loadState = 'ready';
+ } catch {
+ if (loadState !== 'ready') {
+ loadState = 'error';
+ }
+ }
+ }
+
+ const allUp = $derived(view !== null && view.checks.every((c) => c.status !== 'down'));
+
+ function dayKey(date: Date): string {
+ return `${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`;
+ }
+
+ // A fixed 90-cell grid: days without data render as empty cells instead of
+ // the bar silently shrinking.
+ function buildCells(check: StatusCheck): DayCell[] {
+ const byDay = new SvelteMap<string, StatusDay>();
+ for (const day of check.days) {
+ byDay.set(dayKey(new Date(day.bucket)), day);
+ }
+ const cells: DayCell[] = [];
+ const now = new Date();
+ for (let i = DAYS - 1; i >= 0; i--) {
+ const date = new SvelteDate(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
+ );
+ date.setUTCDate(date.getUTCDate() - i);
+ const day = byDay.get(dayKey(date));
+ const measured = day ? day.total - day.missed : 0;
+ if (!day || measured === 0) {
+ cells.push({ date, state: 'empty', uptimePct: null });
+ continue;
+ }
+ const pct = (day.up / measured) * 100;
+ cells.push({
+ date,
+ state: pct >= 99.5 ? 'operational' : day.up === 0 ? 'down' : 'degraded',
+ uptimePct: pct
+ });
+ }
+ return cells;
+ }
+
+ const cellColors: Record<DayCell['state'], string> = {
+ operational: '#22c55e',
+ degraded: '#f5a623',
+ down: '#e5484d',
+ empty: '#e4e7ec'
+ };
+
+ const stateDescriptions: Record<DayCell['state'], string> = {
+ operational: 'Operational',
+ degraded: 'Partial outage',
+ down: 'Major outage',
+ empty: 'No data'
+ };
+
+ function cellTitle(cell: DayCell): string {
+ const date = cell.date.toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric'
+ });
+ if (cell.state === 'empty') return `${date} — no data`;
+ return `${date} — ${stateDescriptions[cell.state]} (${cell.uptimePct?.toFixed(2)}% uptime)`;
+ }
+
+ function checkStatusLabel(check: StatusCheck): { label: string; color: string } {
+ if (check.status === 'up') return { label: 'Operational', color: '#16a34a' };
+ if (check.status === 'down') return { label: 'Major outage', color: '#e5484d' };
+ return { label: 'No recent data', color: '#98a2b3' };
+ }
+
+ function formatIncident(incident: StatusIncident): string {
+ const started = new Date(incident.startedAt).toLocaleString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ hour: '2-digit',
+ minute: '2-digit'
+ });
+ if (!incident.resolvedAt) return `${started} — ongoing`;
+ const minutes = Math.max(
+ 1,
+ Math.round(
+ (new Date(incident.resolvedAt).getTime() - new Date(incident.startedAt).getTime()) / 60000
+ )
+ );
+ return `${started} — resolved after ${minutes} min`;
+ }
+
+ const INCIDENTS_PER_PAGE = 5;
+ let incidentPage = $state(1);
+
+ const totalIncidentPages = $derived(
+ Math.ceil((view?.pastIncidents.length ?? 0) / INCIDENTS_PER_PAGE)
+ );
+
+ const currentIncidentPage = $derived(
+ Math.min(Math.max(incidentPage, 1), Math.max(totalIncidentPages, 1))
+ );
+
+ const pagedIncidents = $derived(
+ (view?.pastIncidents ?? []).slice(
+ (currentIncidentPage - 1) * INCIDENTS_PER_PAGE,
+ currentIncidentPage * INCIDENTS_PER_PAGE
+ )
+ );
+
+ const incidentGroups = $derived.by(() => {
+ const groups: { label: string; incidents: PastIncident[] }[] = [];
+ for (const incident of pagedIncidents) {
+ const label = new Date(incident.startedAt).toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ year: 'numeric',
+ timeZone: 'UTC'
+ });
+ const group = groups[groups.length - 1];
+ if (group && group.label === label) {
+ group.incidents.push(incident);
+ } else {
+ groups.push({ label, incidents: [incident] });
+ }
+ }
+ return groups;
+ });
+
+ function updateStatusLabel(status: string): string {
+ return status.charAt(0).toUpperCase() + status.slice(1);
+ }
+
+ function formatUpdateTime(iso: string): string {
+ const date = new Date(iso);
+ const day = date.toLocaleDateString(undefined, {
+ month: 'short',
+ day: 'numeric',
+ timeZone: 'UTC'
+ });
+ const time = date.toLocaleTimeString(undefined, {
+ hour: '2-digit',
+ minute: '2-digit',
+ hour12: false,
+ timeZone: 'UTC'
+ });
+ return `${day}, ${time} UTC`;
+ }
+
+ // The status page is a standalone light design; anonymous visitors default
+ // to the app's dark theme class, which would restyle headings underneath
+ // the scoped styles. Force light here and restore on leave.
+ let hadDarkClass = false;
+ onMount(() => {
+ hadDarkClass = document.documentElement.classList.contains('dark');
+ document.documentElement.classList.remove('dark');
+ document.documentElement.style.colorScheme = 'light';
+ loadStatus();
+ refreshTimer = setInterval(loadStatus, 60000);
+ });
+
+ onDestroy(() => {
+ if (refreshTimer) clearInterval(refreshTimer);
+ if (hadDarkClass) {
+ document.documentElement.classList.add('dark');
+ document.documentElement.style.colorScheme = 'dark';
+ }
+ });
+</script>
+
+<svelte:head>
+ <title>{view ? `${view.name} status` : 'Status'}</title>
+</svelte:head>
+
+<!-- Deliberately a standalone light design, independent of the app theme. -->
+<div class="status-page">
+ <div class="status-container">
+ {#if loadState === 'loading'}
+ <div class="status-center">
+ <div class="status-spinner"></div>
+ </div>
+ {:else if loadState === 'notFound'}
+ <div class="status-center">
+ <h1>Status page not found</h1>
+ <p>This status page does not exist or is not public.</p>
+ </div>
+ {:else if loadState === 'error'}
+ <div class="status-center">
+ <h1>Something went wrong</h1>
+ <p>Could not load the status page. Try again shortly.</p>
+ </div>
+ {:else if view}
+ <header class="status-header">
+ <div class="status-brand">
+ {#if view.hasLogo}
+ <img src={`/api/status/${encodeURIComponent(slug)}/logo`} alt="" />
+ {/if}
+ <div>
+ <h1>{view.name}</h1>
+ {#if view.description}
+ <p>{view.description}</p>
+ {/if}
+ </div>
+ </div>
+ </header>
+
+ <div class="status-banner" class:degraded={!allUp}>
+ {allUp ? 'All systems operational' : 'Some systems are experiencing issues'}
+ </div>
+
+ <div class="status-cards">
+ {#each view.checks as check, __index (__index)}
+ {@const cells = buildCells(check)}
+ {@const chip = checkStatusLabel(check)}
+ <section class="status-card">
+ <div class="status-card-head">
+ <span class="status-card-name">{check.name}</span>
+ <span class="status-chip" style="color: {chip.color}">
+ <span class="status-dot" style="background: {chip.color}"></span>
+ {chip.label}
+ </span>
+ </div>
+ <div class="status-uptime-row">
+ <span
+ >{check.uptimePct === null
+ ? 'No data yet'
+ : `${check.uptimePct.toFixed(2)}% uptime in the last 90 days`}</span
+ >
+ </div>
+ <div class="status-bars">
+ {#each cells as cell, i (i)}
+ <span
+ class="status-bar {i < 30 ? 'band-oldest' : i < 60 ? 'band-mid' : ''}"
+ style="background: {cellColors[cell.state]}"
+ title={cellTitle(cell)}
+ ></span>
+ {/each}
+ </div>
+ <div class="status-bar-labels">
+ <span class="label-90">90 days ago</span>
+ <span class="label-60">60 days ago</span>
+ <span class="label-30">30 days ago</span>
+ <span>Today</span>
+ </div>
+ {#if check.incidents.length > 0}
+ <details class="status-incidents">
+ <summary>
+ {check.incidents.length} incident{check.incidents.length === 1 ? '' : 's'} in the last
+ 90 days
+ </summary>
+ <ul>
+ {#each check.incidents as incident, __index (__index)}
+ <li>{formatIncident(incident)}</li>
+ {/each}
+ </ul>
+ </details>
+ {/if}
+ </section>
+ {/each}
+ </div>
+
+ {#if view.pastIncidents.length > 0}
+ <section class="past-incidents">
+ <h2>Past Incidents</h2>
+ {#each incidentGroups as group, __index (__index)}
+ <div class="past-day">
+ <h3>{group.label}</h3>
+ {#each group.incidents as incident, __index (__index)}
+ <article class="past-incident">
+ <h4>{incident.title}</h4>
+ {#if incident.updates.length > 0}
+ {#each incident.updates as update, __index (__index)}
+ <div class="past-update">
+ <p>
+ <b>{updateStatusLabel(update.status)}</b>{update.message
+ ? ` - ${update.message}`
+ : ''}
+ </p>
+ <time>{formatUpdateTime(update.createdAt)}</time>
+ </div>
+ {/each}
+ {:else}
+ <div class="past-update">
+ <p><b>{incident.resolvedAt ? 'Resolved' : 'Investigating'}</b></p>
+ <time>{formatUpdateTime(incident.resolvedAt ?? incident.startedAt)}</time>
+ </div>
+ {/if}
+ </article>
+ {/each}
+ </div>
+ {/each}
+ {#if totalIncidentPages > 1}
+ <nav class="past-pager" aria-label="Past incidents pages">
+ <button
+ type="button"
+ onclick={() => (incidentPage = currentIncidentPage - 1)}
+ disabled={currentIncidentPage <= 1}
+ >
+ Newer
+ </button>
+ <span>Page {currentIncidentPage} of {totalIncidentPages}</span>
+ <button
+ type="button"
+ onclick={() => (incidentPage = currentIncidentPage + 1)}
+ disabled={currentIncidentPage >= totalIncidentPages}
+ >
+ Older
+ </button>
+ </nav>
+ {/if}
+ </section>
+ {/if}
+
+ <div class="status-legend">
+ <span><i style="background: #22c55e"></i> Operational</span>
+ <span><i style="background: #f5a623"></i> Partial outage</span>
+ <span><i style="background: #e5484d"></i> Major outage</span>
+ <span><i style="background: #e4e7ec"></i> No data</span>
+ </div>
+
+ <footer class="status-footer">
+ Updated {new Date(view.generatedAt).toLocaleTimeString()} · Powered by Traceway
+ </footer>
+ {/if}
+ </div>
+</div>
+
+<style>
+ .status-page {
+ min-height: 100vh;
+ background: #f7f8fa;
+ color: #101828;
+ font-family:
+ -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
+ }
+
+ .status-container {
+ max-width: 880px;
+ margin: 0 auto;
+ padding: 56px 24px 40px;
+ }
+
+ .status-center {
+ padding: 120px 0;
+ text-align: center;
+ }
+
+ .status-center h1 {
+ font-size: 24px;
+ font-weight: 600;
+ margin: 0 0 8px;
+ color: #101828;
+ }
+
+ .status-center p {
+ color: #667085;
+ margin: 0;
+ }
+
+ .status-spinner {
+ width: 28px;
+ height: 28px;
+ margin: 0 auto;
+ border: 3px solid #e4e7ec;
+ border-top-color: #16a34a;
+ border-radius: 50%;
+ animation: spin 0.8s linear infinite;
+ }
+
+ @keyframes spin {
+ to {
+ transform: rotate(360deg);
+ }
+ }
+
+ .status-header {
+ margin-bottom: 20px;
+ }
+
+ .status-brand {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ }
+
+ .status-brand img {
+ width: 48px;
+ height: 48px;
+ border-radius: 10px;
+ object-fit: contain;
+ background: #fff;
+ border: 1px solid #e4e7ec;
+ padding: 4px;
+ }
+
+ .status-brand h1 {
+ font-size: 26px;
+ font-weight: 700;
+ margin: 0;
+ letter-spacing: -0.02em;
+ color: #101828;
+ }
+
+ .status-brand p {
+ margin: 2px 0 0;
+ color: #667085;
+ font-size: 14px;
+ }
+
+ .status-banner {
+ background: #16a34a;
+ color: #fff;
+ font-size: 16px;
+ font-weight: 600;
+ padding: 16px 20px;
+ border-radius: 10px;
+ margin-bottom: 24px;
+ }
+
+ .status-banner.degraded {
+ background: #e5484d;
+ }
+
+ .status-cards {
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ }
+
+ .status-card {
+ background: #fff;
+ border: 1px solid #e4e7ec;
+ border-radius: 12px;
+ padding: 20px;
+ box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
+ }
+
+ .status-card-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ }
+
+ .status-card-name {
+ font-size: 15px;
+ font-weight: 600;
+ }
+
+ .status-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ font-weight: 600;
+ }
+
+ .status-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ }
+
+ .status-uptime-row {
+ margin-top: 2px;
+ font-size: 12px;
+ color: #667085;
+ }
+
+ .status-bars {
+ display: flex;
+ gap: 3px;
+ margin-top: 12px;
+ }
+
+ .status-bar {
+ flex: 1;
+ height: 34px;
+ min-width: 3px;
+ border-radius: 3px;
+ transition: transform 0.1s ease;
+ }
+
+ .status-bar:hover {
+ transform: scaleY(1.15);
+ }
+
+ .status-bar-labels {
+ display: flex;
+ justify-content: space-between;
+ margin-top: 6px;
+ font-size: 11px;
+ color: #98a2b3;
+ }
+
+ .label-60,
+ .label-30 {
+ display: none;
+ }
+
+ /* Narrow screens can't fit 90 bars (3px bar + 3px gap each), so show a
+ shorter recent window instead of overflowing the viewport. */
+ @media (max-width: 760px) {
+ .status-bar.band-oldest {
+ display: none;
+ }
+
+ .label-90 {
+ display: none;
+ }
+
+ .label-60 {
+ display: inline;
+ }
+ }
+
+ @media (max-width: 520px) {
+ .status-bar.band-mid {
+ display: none;
+ }
+
+ .label-60 {
+ display: none;
+ }
+
+ .label-30 {
+ display: inline;
+ }
+ }
+
+ @media (max-width: 640px) {
+ .status-container {
+ padding: 32px 16px 32px;
+ }
+
+ .status-brand h1 {
+ font-size: 22px;
+ }
+
+ .status-banner {
+ font-size: 14px;
+ padding: 14px 16px;
+ }
+
+ .status-card {
+ padding: 16px;
+ }
+
+ .status-card-head {
+ flex-wrap: wrap;
+ }
+ }
+
+ .status-incidents {
+ margin-top: 12px;
+ font-size: 12px;
+ color: #667085;
+ }
+
+ .status-incidents summary {
+ cursor: pointer;
+ }
+
+ .status-incidents ul {
+ margin: 8px 0 0;
+ padding-left: 18px;
+ }
+
+ .status-incidents li {
+ margin-top: 4px;
+ }
+
+ .past-incidents {
+ margin-top: 44px;
+ }
+
+ .past-incidents h2 {
+ font-size: 22px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin: 0;
+ color: #101828;
+ }
+
+ .past-day {
+ margin-top: 24px;
+ }
+
+ .past-day h3 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0;
+ padding-bottom: 10px;
+ border-bottom: 1px solid #e4e7ec;
+ color: #101828;
+ }
+
+ .past-incident {
+ margin-top: 16px;
+ }
+
+ .past-incident h4 {
+ font-size: 16px;
+ font-weight: 600;
+ margin: 0 0 10px;
+ color: #d97706;
+ }
+
+ .past-update {
+ margin-top: 10px;
+ }
+
+ .past-update p {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.5;
+ color: #101828;
+ }
+
+ .past-update time {
+ display: block;
+ margin-top: 2px;
+ font-size: 12px;
+ color: #98a2b3;
+ }
+
+ .past-pager {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 14px;
+ margin-top: 24px;
+ font-size: 13px;
+ color: #667085;
+ }
+
+ .past-pager button {
+ background: #fff;
+ border: 1px solid #d0d5dd;
+ border-radius: 8px;
+ padding: 6px 14px;
+ font-size: 13px;
+ font-weight: 600;
+ color: #344054;
+ cursor: pointer;
+ }
+
+ .past-pager button:hover:not(:disabled) {
+ background: #f7f8fa;
+ }
+
+ .past-pager button:disabled {
+ opacity: 0.45;
+ cursor: default;
+ }
+
+ .status-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 16px;
+ justify-content: center;
+ margin-top: 28px;
+ font-size: 12px;
+ color: #667085;
+ }
+
+ .status-legend i {
+ display: inline-block;
+ width: 10px;
+ height: 10px;
+ border-radius: 2px;
+ margin-right: 5px;
+ }
+
+ .status-footer {
+ margin-top: 28px;
+ text-align: center;
+ font-size: 12px;
+ color: #98a2b3;
+ }
+</style>
diff --git a/frontend/src/lib/status-domain.ts b/frontend/src/lib/status-domain.ts
new file mode 100644
index 00000000..0df71ab1
--- /dev/null
+++ b/frontend/src/lib/status-domain.ts
@@ -0,0 +1,7 @@
+// Set by the backend on index.html when the request's Host is a status page's
+// custom domain: the app then renders only that status page, at /.
+export const statusDomainSlug: string | null =
+ typeof document === 'undefined'
+ ? null
+ : (document.querySelector('meta[name="traceway-status-slug"]')?.getAttribute('content') ??
+ null);
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index b46ead66..6bf80a48 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -26,6 +26,8 @@
import { captureException } from '@tracewayapp/frontend';
import * as Tooltip from '$lib/components/ui/tooltip';
import type { Component } from 'svelte';
+ import StatusPageView from '$lib/components/traceway/status-page-view.svelte';
+ import { statusDomainSlug } from '$lib/status-domain';
if (__TRACEWAY_URL__) {
setupTraceway({
@@ -98,6 +100,7 @@
function isPublicPath(pathname: string): boolean {
return (
+ statusDomainSlug !== null ||
PUBLIC_PATHS.has(pathname) ||
pathname.startsWith('/accept-invitation') ||
pathname.startsWith('/ack/') ||
@@ -111,28 +114,6 @@
$effect(() => {
if (!authState.isAuthenticated && !isPublicPath(page.url.pathname)) {
const returnTo = page.url.pathname + page.url.search;
- if (page.url.pathname === '/') {
- // A CNAMEd status-page vanity domain lands here anonymously; ask
- // the backend whether this Host maps to a status page before
- // falling back to the login redirect.
- fetch('/api/status-domains/resolve')
- .then((response) => (response.ok ? response.json() : null))
- .then((resolved) => {
- if (resolved?.slug) {
- goto(resolve(`/status/${resolved.slug}` as '/'), { replaceState: true });
- } else {
- gotoHref(`/login?returnTo=${encodeURIComponent(returnTo)}`, {
- replaceState: true
- });
- }
- })
- .catch(() => {
- gotoHref(`/login?returnTo=${encodeURIComponent(returnTo)}`, {
- replaceState: true
- });
- });
- return;
- }
gotoHref(`/login?returnTo=${encodeURIComponent(returnTo)}`, {
replaceState: true
});
@@ -161,6 +142,7 @@
$effect(() => {
if (
+ statusDomainSlug ||
!authState.isAuthenticated ||
page.url.pathname !== '/' ||
page.url.searchParams.has('projectId') ||
@@ -222,7 +204,7 @@
initTheme();
window.captureException = captureException;
- if (authState.isAuthenticated) {
+ if (authState.isAuthenticated && !statusDomainSlug) {
projectsState.loadProjects();
}
@@ -316,7 +298,11 @@
<Tooltip.Provider delayDuration={0}>
<!-- This is not ideal, but because our layout is a top level route it can end up showing sidebar on the login page (after the login before the transition). -->
<!-- We could consider moving this to a lower level layout for the actual app, for now it's just a path check -->
- {#if authState.isAuthenticated && !isPublicPath(page.url.pathname) && inSetupFlow}
+ {#if statusDomainSlug}
+ <main class="h-screen w-screen">
+ <StatusPageView slug={statusDomainSlug} />
+ </main>
+ {:else if authState.isAuthenticated && !isPublicPath(page.url.pathname) && inSetupFlow}
<div class="flex min-h-screen flex-col">
<header class="flex h-14 shrink-0 items-center justify-between px-4">
{#if themeState.isDark}
diff --git a/frontend/src/routes/+page.ts b/frontend/src/routes/+page.ts
index 9f2ce0c4..aeca390a 100644
--- a/frontend/src/routes/+page.ts
+++ b/frontend/src/routes/+page.ts
@@ -1,9 +1,10 @@
import { redirect } from '@sveltejs/kit';
import { authState } from '$lib/state/auth.svelte';
+import { statusDomainSlug } from '$lib/status-domain';
import type { PageLoad } from './$types';
export const load: PageLoad = () => {
- if (!authState.isAuthenticated) {
+ if (!authState.isAuthenticated && !statusDomainSlug) {
throw redirect(302, '/login');
}
};
diff --git a/frontend/src/routes/status/[slug]/+page.svelte b/frontend/src/routes/status/[slug]/+page.svelte
index 01cec29c..cf2b7382 100644
--- a/frontend/src/routes/status/[slug]/+page.svelte
+++ b/frontend/src/routes/status/[slug]/+page.svelte
@@ -1,755 +1,7 @@
<script lang="ts">
- import { onMount, onDestroy } from 'svelte';
- import { SvelteDate, SvelteMap } from 'svelte/reactivity';
-
- interface StatusDay {
- bucket: string;
- total: number;
- up: number;
- missed: number;
- }
-
- interface StatusIncident {
- startedAt: string;
- resolvedAt: string | null;
- }
-
- interface StatusCheck {
- name: string;
- checkType: string;
- status: 'up' | 'down' | 'unknown';
- uptimePct: number | null;
- days: StatusDay[];
- incidents: StatusIncident[];
- }
-
- interface PastIncidentUpdate {
- status: string;
- message: string;
- createdAt: string;
- }
-
- interface PastIncident {
- title: string;
- startedAt: string;
- resolvedAt: string | null;
- updates: PastIncidentUpdate[];
- }
-
- interface StatusView {
- name: string;
- description: string;
- hasLogo: boolean;
- checks: StatusCheck[];
- pastIncidents: PastIncident[];
- generatedAt: string;
- }
+ import StatusPageView from '$lib/components/traceway/status-page-view.svelte';
let { data }: { data: { slug: string } } = $props();
-
- type LoadState = 'loading' | 'ready' | 'notFound' | 'error';
- let loadState = $state<LoadState>('loading');
- let view = $state<StatusView | null>(null);
- let refreshTimer: ReturnType<typeof setInterval> | null = null;
-
- const DAYS = 90;
-
- type DayCell = {
- date: Date;
- state: 'operational' | 'degraded' | 'down' | 'empty';
- uptimePct: number | null;
- };
-
- // Deliberately a raw fetch: the api client's 401 handling would bounce
- // anonymous visitors to /login, and this page must work logged out.
- async function loadStatus() {
- try {
- const response = await fetch(`/api/status/${encodeURIComponent(data.slug)}`);
- if (response.status === 404) {
- loadState = 'notFound';
- return;
- }
- if (!response.ok) {
- throw new Error(`status ${response.status}`);
- }
- view = await response.json();
- loadState = 'ready';
- } catch {
- if (loadState !== 'ready') {
- loadState = 'error';
- }
- }
- }
-
- const allUp = $derived(view !== null && view.checks.every((c) => c.status !== 'down'));
-
- function dayKey(date: Date): string {
- return `${date.getUTCFullYear()}-${date.getUTCMonth()}-${date.getUTCDate()}`;
- }
-
- // A fixed 90-cell grid: days without data render as empty cells instead of
- // the bar silently shrinking.
- function buildCells(check: StatusCheck): DayCell[] {
- const byDay = new SvelteMap<string, StatusDay>();
- for (const day of check.days) {
- byDay.set(dayKey(new Date(day.bucket)), day);
- }
- const cells: DayCell[] = [];
- const now = new Date();
- for (let i = DAYS - 1; i >= 0; i--) {
- const date = new SvelteDate(
- Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
- );
- date.setUTCDate(date.getUTCDate() - i);
- const day = byDay.get(dayKey(date));
- const measured = day ? day.total - day.missed : 0;
- if (!day || measured === 0) {
- cells.push({ date, state: 'empty', uptimePct: null });
- continue;
- }
- const pct = (day.up / measured) * 100;
- cells.push({
- date,
- state: pct >= 99.5 ? 'operational' : day.up === 0 ? 'down' : 'degraded',
- uptimePct: pct
- });
- }
- return cells;
- }
-
- const cellColors: Record<DayCell['state'], string> = {
- operational: '#22c55e',
- degraded: '#f5a623',
- down: '#e5484d',
- empty: '#e4e7ec'
- };
-
- const stateDescriptions: Record<DayCell['state'], string> = {
- operational: 'Operational',
- degraded: 'Partial outage',
- down: 'Major outage',
- empty: 'No data'
- };
-
- function cellTitle(cell: DayCell): string {
- const date = cell.date.toLocaleDateString(undefined, {
- month: 'short',
- day: 'numeric',
- year: 'numeric'
- });
- if (cell.state === 'empty') return `${date} — no data`;
- return `${date} — ${stateDescriptions[cell.state]} (${cell.uptimePct?.toFixed(2)}% uptime)`;
- }
-
- function checkStatusLabel(check: StatusCheck): { label: string; color: string } {
- if (check.status === 'up') return { label: 'Operational', color: '#16a34a' };
- if (check.status === 'down') return { label: 'Major outage', color: '#e5484d' };
- return { label: 'No recent data', color: '#98a2b3' };
- }
-
- function formatIncident(incident: StatusIncident): string {
- const started = new Date(incident.startedAt).toLocaleString(undefined, {
- month: 'short',
- day: 'numeric',
- hour: '2-digit',
- minute: '2-digit'
- });
- if (!incident.resolvedAt) return `${started} — ongoing`;
- const minutes = Math.max(
- 1,
- Math.round(
- (new Date(incident.resolvedAt).getTime() - new Date(incident.startedAt).getTime()) / 60000
- )
- );
- return `${started} — resolved after ${minutes} min`;
- }
-
- const INCIDENTS_PER_PAGE = 5;
- let incidentPage = $state(1);
-
- const totalIncidentPages = $derived(
- Math.ceil((view?.pastIncidents.length ?? 0) / INCIDENTS_PER_PAGE)
- );
-
- const currentIncidentPage = $derived(
- Math.min(Math.max(incidentPage, 1), Math.max(totalIncidentPages, 1))
- );
-
- const pagedIncidents = $derived(
- (view?.pastIncidents ?? []).slice(
- (currentIncidentPage - 1) * INCIDENTS_PER_PAGE,
- currentIncidentPage * INCIDENTS_PER_PAGE
- )
- );
-
- const incidentGroups = $derived.by(() => {
- const groups: { label: string; incidents: PastIncident[] }[] = [];
- for (const incident of pagedIncidents) {
- const label = new Date(incident.startedAt).toLocaleDateString(undefined, {
- month: 'short',
- day: 'numeric',
- year: 'numeric',
- timeZone: 'UTC'
- });
- const group = groups[groups.length - 1];
- if (group && group.label === label) {
- group.incidents.push(incident);
- } else {
- groups.push({ label, incidents: [incident] });
- }
- }
- return groups;
- });
-
- function updateStatusLabel(status: string): string {
- return status.charAt(0).toUpperCase() + status.slice(1);
- }
-
- function formatUpdateTime(iso: string): string {
- const date = new Date(iso);
- const day = date.toLocaleDateString(undefined, {
- month: 'short',
- day: 'numeric',
- timeZone: 'UTC'
- });
- const time = date.toLocaleTimeString(undefined, {
- hour: '2-digit',
- minute: '2-digit',
- hour12: false,
- timeZone: 'UTC'
- });
- return `${day}, ${time} UTC`;
- }
-
- // The status page is a standalone light design; anonymous visitors default
- // to the app's dark theme class, which would restyle headings underneath
- // the scoped styles. Force light here and restore on leave.
- let hadDarkClass = false;
- onMount(() => {
- hadDarkClass = document.documentElement.classList.contains('dark');
- document.documentElement.classList.remove('dark');
- document.documentElement.style.colorScheme = 'light';
- loadStatus();
- refreshTimer = setInterval(loadStatus, 60000);
- });
-
- onDestroy(() => {
- if (refreshTimer) clearInterval(refreshTimer);
- if (hadDarkClass) {
- document.documentElement.classList.add('dark');
- document.documentElement.style.colorScheme = 'dark';
- }
- });
</script>
-<svelte:head>
- <title>{view ? `${view.name} status` : 'Status'}</title>
-</svelte:head>
-
-<!-- Deliberately a standalone light design, independent of the app theme. -->
-<div class="status-page">
- <div class="status-container">
- {#if loadState === 'loading'}
- <div class="status-center">
- <div class="status-spinner"></div>
- </div>
- {:else if loadState === 'notFound'}
- <div class="status-center">
- <h1>Status page not found</h1>
- <p>This status page does not exist or is not public.</p>
- </div>
- {:else if loadState === 'error'}
- <div class="status-center">
- <h1>Something went wrong</h1>
- <p>Could not load the status page. Try again shortly.</p>
- </div>
- {:else if view}
- <header class="status-header">
- <div class="status-brand">
- {#if view.hasLogo}
- <img src={`/api/status/${encodeURIComponent(data.slug)}/logo`} alt="" />
- {/if}
- <div>
- <h1>{view.name}</h1>
- {#if view.description}
- <p>{view.description}</p>
- {/if}
- </div>
- </div>
- </header>
-
- <div class="status-banner" class:degraded={!allUp}>
- {allUp ? 'All systems operational' : 'Some systems are experiencing issues'}
- </div>
-
- <div class="status-cards">
- {#each view.checks as check, __index (__index)}
- {@const cells = buildCells(check)}
- {@const chip = checkStatusLabel(check)}
- <section class="status-card">
- <div class="status-card-head">
- <span class="status-card-name">{check.name}</span>
- <span class="status-chip" style="color: {chip.color}">
- <span class="status-dot" style="background: {chip.color}"></span>
- {chip.label}
- </span>
- </div>
- <div class="status-uptime-row">
- <span
- >{check.uptimePct === null
- ? 'No data yet'
- : `${check.uptimePct.toFixed(2)}% uptime in the last 90 days`}</span
- >
- </div>
- <div class="status-bars">
- {#each cells as cell, i (i)}
- <span
- class="status-bar {i < 30 ? 'band-oldest' : i < 60 ? 'band-mid' : ''}"
- style="background: {cellColors[cell.state]}"
- title={cellTitle(cell)}
- ></span>
- {/each}
- </div>
- <div class="status-bar-labels">
- <span class="label-90">90 days ago</span>
- <span class="label-60">60 days ago</span>
- <span class="label-30">30 days ago</span>
- <span>Today</span>
- </div>
- {#if check.incidents.length > 0}
- <details class="status-incidents">
- <summary>
- {check.incidents.length} incident{check.incidents.length === 1 ? '' : 's'} in the last
- 90 days
- </summary>
- <ul>
- {#each check.incidents as incident, __index (__index)}
- <li>{formatIncident(incident)}</li>
- {/each}
- </ul>
- </details>
- {/if}
- </section>
- {/each}
- </div>
-
- {#if view.pastIncidents.length > 0}
- <section class="past-incidents">
- <h2>Past Incidents</h2>
- {#each incidentGroups as group, __index (__index)}
- <div class="past-day">
- <h3>{group.label}</h3>
- {#each group.incidents as incident, __index (__index)}
- <article class="past-incident">
- <h4>{incident.title}</h4>
- {#if incident.updates.length > 0}
- {#each incident.updates as update, __index (__index)}
- <div class="past-update">
- <p>
- <b>{updateStatusLabel(update.status)}</b>{update.message
- ? ` - ${update.message}`
- : ''}
- </p>
- <time>{formatUpdateTime(update.createdAt)}</time>
- </div>
- {/each}
- {:else}
- <div class="past-update">
- <p><b>{incident.resolvedAt ? 'Resolved' : 'Investigating'}</b></p>
- <time>{formatUpdateTime(incident.resolvedAt ?? incident.startedAt)}</time>
- </div>
- {/if}
- </article>
- {/each}
- </div>
- {/each}
- {#if totalIncidentPages > 1}
- <nav class="past-pager" aria-label="Past incidents pages">
- <button
- type="button"
- onclick={() => (incidentPage = currentIncidentPage - 1)}
- disabled={currentIncidentPage <= 1}
- >
- Newer
- </button>
- <span>Page {currentIncidentPage} of {totalIncidentPages}</span>
- <button
- type="button"
- onclick={() => (incidentPage = currentIncidentPage + 1)}
- disabled={currentIncidentPage >= totalIncidentPages}
- >
- Older
- </button>
- </nav>
- {/if}
- </section>
- {/if}
-
- <div class="status-legend">
- <span><i style="background: #22c55e"></i> Operational</span>
- <span><i style="background: #f5a623"></i> Partial outage</span>
- <span><i style="background: #e5484d"></i> Major outage</span>
- <span><i style="background: #e4e7ec"></i> No data</span>
- </div>
-
- <footer class="status-footer">
- Updated {new Date(view.generatedAt).toLocaleTimeString()} · Powered by Traceway
- </footer>
- {/if}
- </div>
-</div>
-
-<style>
- .status-page {
- min-height: 100vh;
- background: #f7f8fa;
- color: #101828;
- font-family:
- -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
- }
-
- .status-container {
- max-width: 880px;
- margin: 0 auto;
- padding: 56px 24px 40px;
- }
-
- .status-center {
- padding: 120px 0;
- text-align: center;
- }
-
- .status-center h1 {
- font-size: 24px;
- font-weight: 600;
- margin: 0 0 8px;
- color: #101828;
- }
-
- .status-center p {
- color: #667085;
- margin: 0;
- }
-
- .status-spinner {
- width: 28px;
- height: 28px;
- margin: 0 auto;
- border: 3px solid #e4e7ec;
- border-top-color: #16a34a;
- border-radius: 50%;
- animation: spin 0.8s linear infinite;
- }
-
- @keyframes spin {
- to {
- transform: rotate(360deg);
- }
- }
-
- .status-header {
- margin-bottom: 20px;
- }
-
- .status-brand {
- display: flex;
- align-items: center;
- gap: 16px;
- }
-
- .status-brand img {
- width: 48px;
- height: 48px;
- border-radius: 10px;
- object-fit: contain;
- background: #fff;
- border: 1px solid #e4e7ec;
- padding: 4px;
- }
-
- .status-brand h1 {
- font-size: 26px;
- font-weight: 700;
- margin: 0;
- letter-spacing: -0.02em;
- color: #101828;
- }
-
- .status-brand p {
- margin: 2px 0 0;
- color: #667085;
- font-size: 14px;
- }
-
- .status-banner {
- background: #16a34a;
- color: #fff;
- font-size: 16px;
- font-weight: 600;
- padding: 16px 20px;
- border-radius: 10px;
- margin-bottom: 24px;
- }
-
- .status-banner.degraded {
- background: #e5484d;
- }
-
- .status-cards {
- display: flex;
- flex-direction: column;
- gap: 16px;
- }
-
- .status-card {
- background: #fff;
- border: 1px solid #e4e7ec;
- border-radius: 12px;
- padding: 20px;
- box-shadow: 0 1px 2px rgba(16, 24, 40, 0.04);
- }
-
- .status-card-head {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- }
-
- .status-card-name {
- font-size: 15px;
- font-weight: 600;
- }
-
- .status-chip {
- display: inline-flex;
- align-items: center;
- gap: 6px;
- font-size: 13px;
- font-weight: 600;
- }
-
- .status-dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- }
-
- .status-uptime-row {
- margin-top: 2px;
- font-size: 12px;
- color: #667085;
- }
-
- .status-bars {
- display: flex;
- gap: 3px;
- margin-top: 12px;
- }
-
- .status-bar {
- flex: 1;
- height: 34px;
- min-width: 3px;
- border-radius: 3px;
- transition: transform 0.1s ease;
- }
-
- .status-bar:hover {
- transform: scaleY(1.15);
- }
-
- .status-bar-labels {
- display: flex;
- justify-content: space-between;
- margin-top: 6px;
- font-size: 11px;
- color: #98a2b3;
- }
-
- .label-60,
- .label-30 {
- display: none;
- }
-
- /* Narrow screens can't fit 90 bars (3px bar + 3px gap each), so show a
- shorter recent window instead of overflowing the viewport. */
- @media (max-width: 760px) {
- .status-bar.band-oldest {
- display: none;
- }
-
- .label-90 {
- display: none;
- }
-
- .label-60 {
- display: inline;
- }
- }
-
- @media (max-width: 520px) {
- .status-bar.band-mid {
- display: none;
- }
-
- .label-60 {
- display: none;
- }
-
- .label-30 {
- display: inline;
- }
- }
-
- @media (max-width: 640px) {
- .status-container {
- padding: 32px 16px 32px;
- }
-
- .status-brand h1 {
- font-size: 22px;
- }
-
- .status-banner {
- font-size: 14px;
- padding: 14px 16px;
- }
-
- .status-card {
- padding: 16px;
- }
-
- .status-card-head {
- flex-wrap: wrap;
- }
- }
-
- .status-incidents {
- margin-top: 12px;
- font-size: 12px;
- color: #667085;
- }
-
- .status-incidents summary {
- cursor: pointer;
- }
-
- .status-incidents ul {
- margin: 8px 0 0;
- padding-left: 18px;
- }
-
- .status-incidents li {
- margin-top: 4px;
- }
-
- .past-incidents {
- margin-top: 44px;
- }
-
- .past-incidents h2 {
- font-size: 22px;
- font-weight: 700;
- letter-spacing: -0.02em;
- margin: 0;
- color: #101828;
- }
-
- .past-day {
- margin-top: 24px;
- }
-
- .past-day h3 {
- font-size: 15px;
- font-weight: 600;
- margin: 0;
- padding-bottom: 10px;
- border-bottom: 1px solid #e4e7ec;
- color: #101828;
- }
-
- .past-incident {
- margin-top: 16px;
- }
-
- .past-incident h4 {
- font-size: 16px;
- font-weight: 600;
- margin: 0 0 10px;
- color: #d97706;
- }
-
- .past-update {
- margin-top: 10px;
- }
-
- .past-update p {
- margin: 0;
- font-size: 14px;
- line-height: 1.5;
- color: #101828;
- }
-
- .past-update time {
- display: block;
- margin-top: 2px;
- font-size: 12px;
- color: #98a2b3;
- }
-
- .past-pager {
- display: flex;
- align-items: center;
- justify-content: center;
- gap: 14px;
- margin-top: 24px;
- font-size: 13px;
- color: #667085;
- }
-
- .past-pager button {
- background: #fff;
- border: 1px solid #d0d5dd;
- border-radius: 8px;
- padding: 6px 14px;
- font-size: 13px;
- font-weight: 600;
- color: #344054;
- cursor: pointer;
- }
-
- .past-pager button:hover:not(:disabled) {
- background: #f7f8fa;
- }
-
- .past-pager button:disabled {
- opacity: 0.45;
- cursor: default;
- }
-
- .status-legend {
- display: flex;
- flex-wrap: wrap;
- gap: 16px;
- justify-content: center;
- margin-top: 28px;
- font-size: 12px;
- color: #667085;
- }
-
- .status-legend i {
- display: inline-block;
- width: 10px;
- height: 10px;
- border-radius: 2px;
- margin-right: 5px;
- }
-
- .status-footer {
- margin-top: 28px;
- text-align: center;
- font-size: 12px;
- color: #98a2b3;
- }
-</style>
+<StatusPageView slug={data.slug} />