Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
feat(emails): transactional email primitives and redesigned templates (#2741)
Maximilian Kaske6d8507f92d3f
diff --git a/apps/dashboard/src/lib/auth/index.ts b/apps/dashboard/src/lib/auth/index.tsindex 1782fc1d6..b987e844c 100644--- a/apps/dashboard/src/lib/auth/index.ts+++ b/apps/dashboard/src/lib/auth/index.ts@@ -157,8 +157,8 @@ const {if (params.user.tenantId) return;await sendEmail({- from: "Thibault from OpenStatus <[email protected]>",- subject: "Welcome to OpenStatus.",+ from: "Thibault from openstatus <[email protected]>",+ subject: "Welcome to openstatus.",to: [params.user.email],react: WelcomeEmail(),});diff --git a/apps/server/src/routes/v1/pageSubscribers/post.test.ts b/apps/server/src/routes/v1/pageSubscribers/post.test.tsindex 80de79fa9..1aad898fc 100644--- a/apps/server/src/routes/v1/pageSubscribers/post.test.ts+++ b/apps/server/src/routes/v1/pageSubscribers/post.test.ts@@ -1,7 +1,9 @@import { and, db, eq, isNull } from "@openstatus/db";import { pageSubscriber } from "@openstatus/db/src/schema";+import { delivery, resend } from "@openstatus/emails/src/send";import { expect } from "@std/expect";import { test } from "@std/testing/bdd";+import { assertSpyCalls, stub } from "@std/testing/mock";import { app } from "@/index";@@ -30,6 +32,45 @@ test("create a page subscription", async () => {}});+test("sends the same redesigned verification email as the status page form", async () => {+ const enabled = stub(delivery, "enabled", () => true);+ const send = stub(resend.emails, "send", () =>+ Promise.resolve({ data: { id: "email_1" }, error: null } as never),+ );++ const email = "[email protected]";+ const cleanup = () =>+ db.delete(pageSubscriber).where(eq(pageSubscriber.email, email));++ try {+ await cleanup();+ const res = await app.request("/v1/page_subscriber/1/update", {+ method: "POST",+ headers: {+ "x-openstatus-key": "1",+ "content-type": "application/json",+ },+ body: JSON.stringify({ email }),+ });+ expect(res.status).toBe(200);++ assertSpyCalls(send, 1);+ const payload = send.calls[0].args[0];+ expect(payload.to).toEqual([email]);+ expect(payload.from).toBe(+ "Status Page <[email protected]>",+ );+ expect(payload.subject).toMatch(/^Confirm your subscription to /);+ // the route calls the template as a function, so this is its <Layout>+ expect(payload.react.props.brand.name).toMatch(/Status$/);+ expect(payload.react.props.pill.label).toBe("Confirm");+ } finally {+ await cleanup();+ send.restore();+ enabled.restore();+ }+});+test("create a scubscriber with invalid email should return a 400", async () => {const res = await app.request("/v1/page_subscriber/1/update", {method: "POST",diff --git a/apps/server/src/routes/v1/pageSubscribers/post.ts b/apps/server/src/routes/v1/pageSubscribers/post.tsindex b9ae75ed2..2b47d53cf 100644--- a/apps/server/src/routes/v1/pageSubscribers/post.ts+++ b/apps/server/src/routes/v1/pageSubscribers/post.ts@@ -3,7 +3,7 @@ import { Events } from "@openstatus/analytics";import { and, eq, isNull, sql } from "@openstatus/db";import { db } from "@openstatus/db/src/db";import { page, pageSubscriber } from "@openstatus/db/src/schema";-import { SubscribeEmail, sendEmail } from "@openstatus/emails";+import { PageSubscriptionEmail, sendEmail } from "@openstatus/emails";import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";import { trackMiddleware } from "@/libs/middlewares";@@ -108,13 +108,13 @@ export function registerPostPageSubscriber(api: typeof pageSubscribersApi) {const link = `https://${_page.slug}.openstatus.dev/verify/${token}`;await sendEmail({- react: SubscribeEmail({+ react: PageSubscriptionEmail({link,page: _page.title,}),- from: "OpenStatus <[email protected]>",+ from: "Status Page <[email protected]>",to: [normalizedEmail],- subject: "Verify your subscription",+ subject: `Confirm your subscription to ${_page.title}`,});const data = PageSubscriberSchema.parse(_statusReportSubscriberUpdate);diff --git a/apps/web/src/app/api/internal/email/feedback/route.ts b/apps/web/src/app/api/internal/email/feedback/route.tsindex 07712e900..9bf7c375f 100644--- a/apps/web/src/app/api/internal/email/feedback/route.ts+++ b/apps/web/src/app/api/internal/email/feedback/route.ts@@ -26,7 +26,7 @@ export async function GET(request: NextRequest) {if (!u.email || u.email.trim() === "") continue;await sendEmail({- from: "Thibault from OpenStatus <[email protected]>",+ from: "Thibault from openstatus <[email protected]>",subject: "One quick question",to: [u.email],react: FeedbackEmail(),diff --git a/apps/web/src/app/api/internal/email/route.ts b/apps/web/src/app/api/internal/email/route.tsdeleted file mode 100644index 5ceefd5e1..000000000--- a/apps/web/src/app/api/internal/email/route.ts+++ /dev/null@@ -1,78 +0,0 @@-import { and, eq, gte, inArray, lte } from "@openstatus/db";-import { db } from "@openstatus/db/src/db";-import {- integration,- user,- usersToWorkspaces,-} from "@openstatus/db/src/schema";-import {- FollowUpEmail,- SlackFeedbackEmail,- sendEmail,-} from "@openstatus/emails";-import type { NextRequest } from "next/server";--export async function GET(request: NextRequest) {- const authHeader = request.headers.get("authorization");- console.log(authHeader);- if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {- return new Response("Unauthorized", {- status: 401,- });- }-- const date1 = new Date();- date1.setDate(date1.getDate() - 2);- const date2 = new Date();- date2.setDate(date2.getDate() - 1);-- const users = await db- .select({- email: user.email,- workspaceId: usersToWorkspaces.workspaceId,- })- .from(user)- .innerJoin(usersToWorkspaces, eq(user.id, usersToWorkspaces.userId))- .where(and(gte(user.createdAt, date1), lte(user.createdAt, date2)))- .all();-- const workspaceIds = [- ...new Set(users.map((u) => u.workspaceId).filter(Boolean)),- ];-- const slackWorkspaceIds = new Set<number>();- if (workspaceIds.length > 0) {- const slackIntegrations = await db- .select({ workspaceId: integration.workspaceId })- .from(integration)- .where(- and(- eq(integration.name, "slack-agent"),- inArray(integration.workspaceId, workspaceIds),- ),- )- .all();- for (const row of slackIntegrations) {- if (row.workspaceId) {- slackWorkspaceIds.add(row.workspaceId);- }- }- }-- for (const u of users) {- if (!u.email) continue;- const hasSlack = u.workspaceId- ? slackWorkspaceIds.has(u.workspaceId)- : false;-- await sendEmail({- from: "Thibault from OpenStatus <[email protected]>",- subject: hasSlack- ? "How's the Slack app working for you?"- : "Manage incidents from Slack",- to: [u.email],- react: hasSlack ? SlackFeedbackEmail() : FollowUpEmail(),- });- }- return Response.json({ success: true });-}diff --git a/apps/web/src/app/api/internal/email/team-invite/route.ts b/apps/web/src/app/api/internal/email/team-invite/route.tsdeleted file mode 100644index db8571a2a..000000000--- a/apps/web/src/app/api/internal/email/team-invite/route.ts+++ /dev/null@@ -1,79 +0,0 @@-import { and, count, eq, gte, inArray, lte } from "@openstatus/db";-import { db } from "@openstatus/db/src/db";-import { invitation, user, usersToWorkspaces } from "@openstatus/db/src/schema";-import { TeamInviteReminderEmail, sendEmail } from "@openstatus/emails";-import type { NextRequest } from "next/server";--export async function GET(request: NextRequest) {- const authHeader = request.headers.get("authorization");- if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {- return new Response("Unauthorized", { status: 401 });- }-- const date1 = new Date();- date1.setDate(date1.getDate() - 6);- const date2 = new Date();- date2.setDate(date2.getDate() - 5);-- const users = await db- .select({- email: user.email,- workspaceId: usersToWorkspaces.workspaceId,- })- .from(user)- .innerJoin(usersToWorkspaces, eq(user.id, usersToWorkspaces.userId))- .where(and(gte(user.createdAt, date1), lte(user.createdAt, date2)))- .all();-- const workspaceIds = [- ...new Set(users.map((u) => u.workspaceId).filter(Boolean)),- ];-- if (workspaceIds.length === 0) {- return Response.json({ success: true, sent: 0 });- }-- const workspaceMemberCounts = await db- .select({- workspaceId: usersToWorkspaces.workspaceId,- memberCount: count(usersToWorkspaces.userId),- })- .from(usersToWorkspaces)- .where(inArray(usersToWorkspaces.workspaceId, workspaceIds))- .groupBy(usersToWorkspaces.workspaceId)- .all();-- const workspacesWithInvitations = await db- .select({ workspaceId: invitation.workspaceId })- .from(invitation)- .where(inArray(invitation.workspaceId, workspaceIds))- .groupBy(invitation.workspaceId)- .all();-- const hasTeamActivity = new Set<number>();-- for (const row of workspaceMemberCounts) {- if (row.memberCount > 1) {- hasTeamActivity.add(row.workspaceId);- }- }- for (const row of workspacesWithInvitations) {- hasTeamActivity.add(row.workspaceId);- }-- let sent = 0;- for (const u of users) {- if (!u.email) continue;- if (u.workspaceId && hasTeamActivity.has(u.workspaceId)) continue;-- await sendEmail({- from: "Thibault from OpenStatus <[email protected]>",- subject: "Incidents are a team sport",- to: [u.email],- react: TeamInviteReminderEmail(),- });- sent++;- }-- return Response.json({ success: true, sent });-}diff --git a/apps/workflows/src/cron/monitor.ts b/apps/workflows/src/cron/monitor.tsindex 0e3b1e399..7142b9a09 100644--- a/apps/workflows/src/cron/monitor.ts+++ b/apps/workflows/src/cron/monitor.ts@@ -29,6 +29,10 @@ import { env } from "../env";const redis = Redis.fromEnv();+const PAUSE_FROM =+ "Thibault from openstatus <[email protected]>";+const PAUSE_REPLY_TO = "[email protected]";+// Check if GCP is properly configured (not empty and not placeholder values)const isGcpConfigured = () => {const gcpProjectId = env().GCP_PROJECT_ID;@@ -250,20 +254,19 @@ export async function Step14Days(userId: number, workFlowRunTimestamp: number) {const user = await getUser(userId);if (user.email) {+ const email = await monitorDeactivationEmail({+ deactivateAt: new Date(new Date().setDate(new Date().getDate() + 14)),+ ...(await getPauseContext(userId)),+ });await sendWorkflowEmail({userId,step: "14days",initialRun: workFlowRunTimestamp,email: {to: user.email,- subject: "Your OpenStatus monitors will be paused in 14 days",- from: "Thibault From OpenStatus <[email protected]>",- reply_to: "[email protected]",- html: monitorDeactivationEmail({- date: new Date(- new Date().setDate(new Date().getDate() + 14),- ).toDateString(),- }),+ from: PAUSE_FROM,+ reply_to: PAUSE_REPLY_TO,+ ...email,},});}@@ -298,20 +301,19 @@ export async function Step3Days(userId: number, workFlowRunTimestamp: number) {const user = await getUser(userId);if (user.email) {+ const email = await monitorDeactivationEmail({+ deactivateAt: new Date(new Date().setDate(new Date().getDate() + 3)),+ ...(await getPauseContext(userId)),+ });await sendWorkflowEmail({userId,step: "3days",initialRun: workFlowRunTimestamp,email: {to: user.email,- subject: "Your OpenStatus monitors will be paused in 3 days",- from: "Thibault From OpenStatus <[email protected]>",- reply_to: "[email protected]",- html: monitorDeactivationEmail({- date: new Date(- new Date().setDate(new Date().getDate() + 3),- ).toDateString(),- }),+ from: PAUSE_FROM,+ reply_to: PAUSE_REPLY_TO,+ ...email,},});}@@ -344,6 +346,7 @@ export async function StepPaused(userId: number, workFlowRunTimestamp: number) {}const workspace = await getUserWorkspace(userId);+ let pausedCount = 0;if (workspace) {const activeMonitors = await db.select({ id: schema.monitor.id })@@ -356,6 +359,7 @@ export async function StepPaused(userId: number, workFlowRunTimestamp: number) {),).all();+ pausedCount = activeMonitors.length;if (activeMonitors.length > 0) {await bulkUpdateMonitors({ctx: {@@ -369,16 +373,19 @@ export async function StepPaused(userId: number, workFlowRunTimestamp: number) {const currentUser = await getUser(userId);if (currentUser.email) {+ const email = await monitorPausedEmail({+ monitorCount: pausedCount || undefined,+ workspaceSlug: workspace?.slug,+ });await sendWorkflowEmail({userId,step: "paused",initialRun: workFlowRunTimestamp,email: {to: currentUser.email,- subject: "Your monitors have been paused",- from: "Thibault From OpenStatus <[email protected]>",- reply_to: "[email protected]",- html: monitorPausedEmail(),+ from: PAUSE_FROM,+ reply_to: PAUSE_REPLY_TO,+ ...email,},});}@@ -508,6 +515,23 @@ async function sendWorkflowEmail({await redis.set(key, 1, { ex: 30 * 86400 });}+async function getPauseContext(userId: number) {+ const workspace = await getUserWorkspace(userId);+ if (!workspace) return {};+ const monitorCount = await db.$count(+ schema.monitor,+ and(+ eq(schema.monitor.workspaceId, workspace.id),+ eq(schema.monitor.active, true),+ isNull(schema.monitor.deletedAt),+ ),+ );+ return {+ monitorCount: monitorCount || undefined,+ workspaceSlug: workspace.slug,+ };+}+async function getUserWorkspace(userId: number) {const row = await db.select({ workspace: schema.workspace })diff --git a/apps/workflows/src/cron/private-location-health.test.ts b/apps/workflows/src/cron/private-location-health.test.tsindex 701a14999..d717b51b5 100644--- a/apps/workflows/src/cron/private-location-health.test.ts+++ b/apps/workflows/src/cron/private-location-health.test.ts@@ -1,6 +1,14 @@import { db, eq } from "@openstatus/db";-import { auditLog, privateLocation } from "@openstatus/db/src/schema";-import { createTestWorkspace } from "@openstatus/db/src/test/factories";+import {+ auditLog,+ monitor,+ privateLocation,+ privateLocationToMonitors,+} from "@openstatus/db/src/schema";+import {+ createMonitor,+ createTestWorkspace,+} from "@openstatus/db/src/test/factories";import {afterEach,assertSpyCalls,@@ -91,6 +99,35 @@ describe("runPrivateLocationHealth", () => {expect(mockEmail.calls[0].args[0].locationName).toBe("health-test-location",);+ expect(mockEmail.calls[0].args[0].monitorCount).toBe(0);+ });++ test("passes the number of monitors scheduled on the location", async () => {+ await seedLocation("active", STALE);+ const linked = await createMonitor(TEST_WORKSPACE_ID, { active: true });+ const unlinked = await createMonitor(TEST_WORKSPACE_ID, { active: true });+ const paused = await createMonitor(TEST_WORKSPACE_ID, { active: false });+ await db+ .insert(privateLocationToMonitors)+ .values([+ { privateLocationId: TEST_LOCATION_ID, monitorId: linked.id },+ { privateLocationId: TEST_LOCATION_ID, monitorId: paused.id },+ {+ privateLocationId: TEST_LOCATION_ID,+ monitorId: unlinked.id,+ deletedAt: new Date(),+ },+ ])+ .run();++ try {+ await runPrivateLocationHealth(NOW);+ expect(mockEmail.calls[0].args[0].monitorCount).toBe(1);+ } finally {+ await db.delete(monitor).where(eq(monitor.id, linked.id));+ await db.delete(monitor).where(eq(monitor.id, unlinked.id));+ await db.delete(monitor).where(eq(monitor.id, paused.id));+ }});test("error + fresh → active + email", async () => {diff --git a/apps/workflows/src/cron/private-location-health.ts b/apps/workflows/src/cron/private-location-health.tsindex b6a56fa22..54462db81 100644--- a/apps/workflows/src/cron/private-location-health.ts+++ b/apps/workflows/src/cron/private-location-health.ts@@ -1,7 +1,9 @@import { getLogger } from "@logtape/logtape";-import { db, eq, isNotNull } from "@openstatus/db";+import { and, db, eq, isNotNull, isNull } from "@openstatus/db";import {+ monitor,privateLocation,+ privateLocationToMonitors,selectWorkspaceSchema,user,usersToWorkspaces,@@ -80,8 +82,24 @@ export async function runPrivateLocationHealth(if (nextStatus === "error") summary.toError++;else summary.toActive++;+ const scheduled = await db+ .select({ id: monitor.id })+ .from(privateLocationToMonitors)+ .innerJoin(monitor, eq(privateLocationToMonitors.monitorId, monitor.id))+ .where(+ and(+ eq(privateLocationToMonitors.privateLocationId, location.id),+ isNull(privateLocationToMonitors.deletedAt),+ eq(monitor.active, true),+ isNull(monitor.deletedAt),+ ),+ )+ .all();+ const monitorCount = scheduled.length;+await notifyMembers({workspaceId: location.workspaceId,+ monitorCount,locationName: location.name,status: nextStatus === "error" ? "error" : "recovered",lastSeenAt: location.lastSeenAt,@@ -96,6 +114,7 @@ async function notifyMembers(args: {locationName: string;status: "error" | "recovered";lastSeenAt: Date;+ monitorCount: number;}) {const members = await db.select({ email: user.email })@@ -116,6 +135,7 @@ async function notifyMembers(args: {locationName: args.locationName,status: args.status,lastSeenAt: args.lastSeenAt,+ monitorCount: args.monitorCount,});} catch (error) {logger.error("Failed to send private location alert", {diff --git a/deno.lock b/deno.lockindex 58ec016ae..1fc5ffecc 100644--- a/deno.lock+++ b/deno.lock@@ -112,7 +112,8 @@"packageJson": {"dependencies": ["npm:@jsr/std__expect@^1.0.19",- "npm:@jsr/std__testing@^1.0.19"+ "npm:@jsr/std__testing@^1.0.19",+ "npm:[email protected]"]}},diff --git a/packages/api/src/router/email/index.ts b/packages/api/src/router/email/index.tsindex 3dea10a39..f68ef6673 100644--- a/packages/api/src/router/email/index.ts+++ b/packages/api/src/router/email/index.ts@@ -138,7 +138,7 @@ export const emailRouter = createTRPCRouter({to: _invitation.email,token: _invitation.token,invitedBy: `${opts.ctx.user.email}`,- workspaceName: opts.ctx.workspace.name || "OpenStatus",+ workspaceName: opts.ctx.workspace.name || "openstatus",baseUrl: opts.input.baseUrl,});}diff --git a/packages/api/src/router/stripe/webhook.ts b/packages/api/src/router/stripe/webhook.tsindex 67031cec2..faacd48a2 100644--- a/packages/api/src/router/stripe/webhook.ts+++ b/packages/api/src/router/stripe/webhook.ts@@ -295,7 +295,7 @@ export const webhookRouter = createTRPCRouter({if (to.length > 0) {await sendEmail({- from: "Thibault from OpenStatus <[email protected]>",+ from: "Thibault from openstatus <[email protected]>",subject: "SSO has been disabled for your workspace",to,react: SsoDisabledEmail(),diff --git a/packages/emails/emails/_components/actions.tsx b/packages/emails/emails/_components/actions.tsxnew file mode 100644index 000000000..4144f25dd--- /dev/null+++ b/packages/emails/emails/_components/actions.tsx@@ -0,0 +1,58 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Button, Link } from "react-email";++import { colors, styles } from "./styles";++interface Action {+ label: string;+ href: string;+}++export function Actions({+ primary,+ secondary,+}: {+ primary: Action;+ secondary?: Action;+}) {+ return (+ <table+ role="presentation"+ cellPadding={0}+ cellSpacing={0}+ style={{ margin: "4px 0 0" }}+ >+ <tbody>+ <tr>+ <td>+ <Button+ href={primary.href}+ style={{+ padding: "13px 20px",+ borderRadius: "8px",+ backgroundColor: colors.foreground,+ color: "#ffffff",+ fontSize: "15px",+ lineHeight: "20px",+ fontWeight: 600,+ }}+ >+ {primary.label}+ </Button>+ </td>+ {secondary ? (+ <td style={{ paddingLeft: "18px" }}>+ <Link+ href={secondary.href}+ style={{ ...styles.link, fontSize: "15px" }}+ >+ {secondary.label}+ </Link>+ </td>+ ) : null}+ </tr>+ </tbody>+ </table>+ );+}diff --git a/packages/emails/emails/_components/callout.tsx b/packages/emails/emails/_components/callout.tsxnew file mode 100644index 000000000..460318db0--- /dev/null+++ b/packages/emails/emails/_components/callout.tsx@@ -0,0 +1,47 @@+/** @jsxRuntime automatic @jsxImportSource react */++import type * as React from "react";+import { Section, Text } from "react-email";++import { colors, tones } from "./styles";++export function Callout({+ tone = "neutral",+ title,+ children,+}: {+ tone?: "neutral" | "success";+ title: string;+ children: React.ReactNode;+}) {+ const success = tone === "success";+ const text = success ? tones.success.text : colors.body;+ return (+ <Section+ style={{+ margin: "8px 0 24px",+ padding: "18px 20px",+ borderRadius: "10px",+ border: `1px solid ${success ? tones.success.border : colors.subtle}`,+ backgroundColor: success ? tones.success.bg : colors.subtle,+ }}+ >+ <Text+ style={{+ margin: "0 0 4px",+ fontSize: "15px",+ lineHeight: "22px",+ fontWeight: 600,+ color: success ? tones.success.text : colors.foreground,+ }}+ >+ {title}+ </Text>+ <Text+ style={{ margin: 0, fontSize: "15px", lineHeight: "24px", color: text }}+ >+ {children}+ </Text>+ </Section>+ );+}diff --git a/packages/emails/emails/_components/code-block.tsx b/packages/emails/emails/_components/code-block.tsxnew file mode 100644index 000000000..fb390f059--- /dev/null+++ b/packages/emails/emails/_components/code-block.tsx@@ -0,0 +1,27 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Text } from "react-email";++import { colors, fonts } from "./styles";++export function CodeBlock({ children }: { children: string }) {+ return (+ <Text+ style={{+ margin: "0 0 24px",+ padding: "14px 16px",+ borderLeft: `3px solid ${colors.border}`,+ borderRadius: "0 8px 8px 0",+ backgroundColor: colors.subtle,+ fontFamily: fonts.mono,+ fontSize: "13px",+ lineHeight: "20px",+ color: colors.body,+ wordBreak: "break-word",+ whiteSpace: "pre-wrap",+ }}+ >+ {children}+ </Text>+ );+}diff --git a/packages/emails/emails/_components/eyebrow.tsx b/packages/emails/emails/_components/eyebrow.tsxnew file mode 100644index 000000000..2d84a0e29--- /dev/null+++ b/packages/emails/emails/_components/eyebrow.tsx@@ -0,0 +1,15 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Text } from "react-email";++import { styles } from "./styles";++export function Eyebrow({ items }: { items: Array<string | undefined> }) {+ const shown = items.filter(Boolean);+ if (shown.length === 0) return null;+ return (+ <Text style={{ ...styles.label, margin: "0 0 10px" }}>+ {shown.join(" · ")}+ </Text>+ );+}diff --git a/packages/emails/emails/_components/footer.tsx b/packages/emails/emails/_components/footer.tsxindex 087d9894b..84625bea2 100644--- a/packages/emails/emails/_components/footer.tsx+++ b/packages/emails/emails/_components/footer.tsx@@ -1,23 +1,67 @@/** @jsxRuntime automatic @jsxImportSource react */+import type * as React from "react";import { Link, Section, Text } from "react-email";-import { styles } from "./styles";+import { colors, styles } from "./styles";-export function Footer() {+export const POSTAL_ADDRESS = "122 Rue Amelot, 75011 Paris, France";++interface FooterLink {+ label: string;+ href: string;+}++const line = {+ margin: "0 0 6px",+ fontSize: "13px",+ lineHeight: "20px",+ color: colors.muted,+} satisfies React.CSSProperties;++const link = { color: colors.muted, textDecoration: "underline" };++export function Footer({+ reason,+ rule,+ links = [],+}: {+ /** Why the reader got this email. */+ reason?: string;+ /** Alert-rule variant, e.g. "latency > 250ms × 3". */+ rule?: string;+ /** Only pass a link where the page behind it exists. */+ links?: FooterLink[];+}) {return (- <Section style={{ textAlign: "center" }}>- <Text>- <Link style={styles.link} href="https://openstatus.dev">- Home Page- </Link>{" "}- ・{" "}- <Link style={styles.link} href="mailto:[email protected]">- Contact Support+ <Section style={{ padding: "24px 16px 0", textAlign: "center" }}>+ {rule ? (+ <Text style={line}>+ Alert rule: <span style={styles.mono}>{rule}</span>+ </Text>+ ) : null}+ {reason ? <Text style={line}>{reason}</Text> : null}+ {links.length > 0 ? (+ <Text style={line}>+ {links.map((l, i) => (+ <span key={l.href}>+ {i > 0 ? " · " : null}+ <Link href={l.href} style={link}>+ {l.label}+ </Link>+ </span>+ ))}+ </Text>+ ) : null}+ <Text style={{ ...line, margin: 0, color: colors.faint }}>+ openstatus · {POSTAL_ADDRESS} ·{" "}+ <Link+ href="mailto:[email protected]"+ style={{ ...link, color: colors.faint }}+ >+ Support</Link></Text>-- <Text>OpenStatus ・ 122 Rue Amelot ・ 75011 Paris, France</Text></Section>);}diff --git a/packages/emails/emails/_components/format.ts b/packages/emails/emails/_components/format.tsnew file mode 100644index 000000000..bdec6ce3d--- /dev/null+++ b/packages/emails/emails/_components/format.ts@@ -0,0 +1,78 @@+// en-US for "Sep" — en-GB abbreviates September as "Sept".+const time = new Intl.DateTimeFormat("en-US", {+ day: "numeric",+ month: "short",+ hour: "2-digit",+ minute: "2-digit",+ hourCycle: "h23",+ timeZone: "UTC",+});++const longDay = new Intl.DateTimeFormat("en-US", {+ weekday: "long",+ day: "numeric",+ month: "long",+ timeZone: "UTC",+});++const day = new Intl.DateTimeFormat("en-US", {+ weekday: "short",+ day: "numeric",+ month: "short",+ year: "numeric",+ timeZone: "UTC",+});++function parts(format: Intl.DateTimeFormat, date: Date) {+ const map = new Map(format.formatToParts(date).map((p) => [p.type, p.value]));+ return (type: Intl.DateTimeFormatPartTypes) => map.get(type) ?? "";+}++/** "18 Sep, 12:37 UTC" — no per-user timezone exists, so always UTC. */+export function formatDateTime(input: Date | string | number): string {+ const date = new Date(input);+ if (Number.isNaN(date.getTime())) return String(input);+ const p = parts(time, date);+ return `${p("day")} ${p("month")}, ${p("hour")}:${p("minute")} UTC`;+}++/** "Fri 25 Sep 2026" — day-only dates carry no timezone suffix. */+export function formatDay(input: Date | string | number): string {+ const date = new Date(input);+ if (Number.isNaN(date.getTime())) return String(input);+ const p = parts(day, date);+ return `${p("weekday")} ${p("day")} ${p("month")} ${p("year")}`;+}++/** "Friday 25 September" — for titles. */+export function formatLongDay(input: Date | string | number): string {+ const date = new Date(input);+ if (Number.isNaN(date.getTime())) return String(input);+ const p = parts(longDay, date);+ return `${p("weekday")} ${p("day")} ${p("month")}`;+}++/** "25 Sep" — for subjects. */+export function formatShortDay(input: Date | string | number): string {+ const date = new Date(input);+ if (Number.isNaN(date.getTime())) return String(input);+ const p = parts(time, date);+ return `${p("day")} ${p("month")}`;+}++/** "2h 14m" between two instants; minutes only under an hour. */+export function formatElapsed(from: Date | string, to: Date | string): string {+ const minutes = Math.max(+ 0,+ Math.floor((new Date(to).getTime() - new Date(from).getTime()) / 60_000),+ );+ const h = Math.floor(minutes / 60);+ const m = minutes % 60;+ if (h === 0) return `${m}m`;+ if (h < 24) return `${h}h ${m}m`;+ return `${Math.floor(h / 24)}d ${h % 24}h`;+}++export function plural(count: number, word: string): string {+ return `${count} ${word}${count === 1 ? "" : "s"}`;+}diff --git a/packages/emails/emails/_components/heading.tsx b/packages/emails/emails/_components/heading.tsxnew file mode 100644index 000000000..8d4af65f3--- /dev/null+++ b/packages/emails/emails/_components/heading.tsx@@ -0,0 +1,41 @@+/** @jsxRuntime automatic @jsxImportSource react */++import type * as React from "react";+import { Heading as EmailHeading, Text } from "react-email";++import { colors, styles } from "./styles";++export function Mono({ children }: { children: React.ReactNode }) {+ return <span style={styles.mono}>{children}</span>;+}++export function Heading({+ title,+ children,+}: {+ title: React.ReactNode;+ children?: React.ReactNode;+}) {+ return (+ <>+ <EmailHeading+ as="h1"+ style={{+ margin: children ? "0 0 12px" : "0 0 20px",+ fontSize: "24px",+ lineHeight: "30px",+ fontWeight: 600,+ letterSpacing: "-0.02em",+ color: colors.foreground,+ }}+ >+ {title}+ </EmailHeading>+ {children ? (+ <Text style={{ ...styles.text, fontSize: "16px", lineHeight: "26px" }}>+ {children}+ </Text>+ ) : null}+ </>+ );+}diff --git a/packages/emails/emails/_components/key-value.tsx b/packages/emails/emails/_components/key-value.tsxnew file mode 100644index 000000000..77ed10b00--- /dev/null+++ b/packages/emails/emails/_components/key-value.tsx@@ -0,0 +1,102 @@+/** @jsxRuntime automatic @jsxImportSource react */++import type * as React from "react";++import { colors, fonts, type Tone, tones } from "./styles";++export interface KeyValueRow {+ label: string;+ value: React.ReactNode;+ /** Muted text after the value, e.g. "threshold 250 ms". */+ hint?: string;+ mono?: boolean;+ bold?: boolean;+ tone?: Tone;+ dot?: boolean;+}++const cell = {+ padding: "14px 18px",+ fontSize: "15px",+ lineHeight: "22px",+} satisfies React.CSSProperties;++export function KeyValue({ rows }: { rows: KeyValueRow[] }) {+ return (+ <table+ role="presentation"+ width="100%"+ cellPadding={0}+ cellSpacing={0}+ style={{+ margin: "8px 0 24px",+ border: `1px solid ${colors.border}`,+ borderRadius: "10px",+ borderCollapse: "separate",+ borderSpacing: 0,+ overflow: "hidden",+ }}+ >+ <tbody>+ {rows.map((row, i) => {+ const tone = row.tone ? tones[row.tone] : undefined;+ const borderTop = i === 0 ? undefined : `1px solid ${colors.border}`;+ const hasValue = row.value !== null && row.value !== undefined;+ return (+ <tr+ key={row.label}+ style={{+ backgroundColor: i % 2 === 0 ? colors.subtle : colors.card,+ }}+ >+ <td+ colSpan={hasValue ? undefined : 2}+ style={{ ...cell, borderTop, color: colors.muted }}+ >+ {row.label}+ </td>+ {hasValue ? (+ <td+ align="right"+ style={{+ ...cell,+ borderTop,+ textAlign: "right",+ wordBreak: "break-word",+ color: tone?.text ?? colors.foreground,+ fontWeight: row.bold || (tone && row.hint) ? 600 : 400,+ fontFamily: row.mono ? fonts.mono : undefined,+ }}+ >+ {row.dot ? (+ <span+ style={{+ color: (tone ?? tones.neutral).dot,+ fontFamily: fonts.sans,+ }}+ >+ ● + </span>+ ) : null}+ {row.value}+ {row.hint ? (+ <span+ style={{+ color: colors.muted,+ fontWeight: 400,+ fontFamily: fonts.sans,+ }}+ >+ {" · "}+ {row.hint}+ </span>+ ) : null}+ </td>+ ) : null}+ </tr>+ );+ })}+ </tbody>+ </table>+ );+}diff --git a/packages/emails/emails/_components/layout.tsx b/packages/emails/emails/_components/layout.tsxindex f3a4815a9..8dabdbd61 100644--- a/packages/emails/emails/_components/layout.tsx+++ b/packages/emails/emails/_components/layout.tsx@@ -1,34 +1,124 @@/** @jsxRuntime automatic @jsxImportSource react */import type * as React from "react";-import { Container, Img, Link, Section } from "react-email";+import {+ Body,+ Container,+ Head,+ Html,+ Img,+ Link,+ Preview,+ Section,+} from "react-email";import { Footer } from "./footer";-import { styles } from "./styles";+import { Pill } from "./pill";+import { colors, styles, type Tone } from "./styles";++export interface Brand {+ name: string;+ href: string;+ /** Hosted PNG; inline SVG data URIs are stripped by Gmail. */+ logo?: string;+}++const openstatus = {+ name: "openstatus",+ href: "https://www.openstatus.dev",+ logo: "https://www.openstatus.dev/assets/logos/OpenStatus.png",+} satisfies Brand;++// Tokenized links (verify, magic link) are one-time: a mail scanner following+// the header link would consume them, so the brand points at the page origin.+function origin(href: string) {+ try {+ return new URL(href).origin;+ } catch {+ return href;+ }+}++export function statusPageBrand(page: string, href: string, logo?: string) {+ return {+ name: /\bstatus$/i.test(page) ? page : `${page} Status`,+ href: origin(href),+ logo,+ } satisfies Brand;+}interface LayoutProps {+ preview: string;+ pill?: { tone: Tone; label: string };+ brand?: Brand;+ footer?: React.ReactNode;children?: React.ReactNode;- img?: {- src: string;- alt: string;- href: string;- };}-const defaultImg = {- src: "https://openstatus.dev/assets/logos/OpenStatus.png",- alt: "OpenStatus",- href: "https://openstatus.dev",-};--export function Layout({ children, img = defaultImg }: LayoutProps) {+export function Layout({+ preview,+ pill,+ brand = openstatus,+ footer = <Footer />,+ children,+}: LayoutProps) {return (- <Container style={styles.container}>- <Link href={img.href}>- <Img src={img.src} width="36" height="36" alt={img.alt} />- </Link>- <Section style={styles.section}>{children}</Section>- <Footer />- </Container>+ <Html lang="en">+ <Head>+ <meta name="color-scheme" content="light only" />+ <meta name="supported-color-schemes" content="light only" />+ </Head>+ <Preview>{preview}</Preview>+ <Body style={styles.main}>+ <Container style={styles.container}>+ <Section style={styles.card}>+ <Section style={styles.header}>+ <table+ role="presentation"+ width="100%"+ cellPadding={0}+ cellSpacing={0}+ >+ <tbody>+ <tr>+ {brand.logo ? (+ <td width={40} valign="middle">+ <Img+ src={brand.logo}+ width="28"+ height="28"+ alt=""+ style={{ display: "block", borderRadius: "999px" }}+ />+ </td>+ ) : null}+ <td valign="middle">+ <Link+ href={brand.href}+ style={{+ color: colors.foreground,+ fontSize: "15px",+ fontWeight: 600,+ textDecoration: "none",+ }}+ >+ {brand.name}+ </Link>+ </td>+ {pill ? (+ <td align="right" valign="middle">+ <Pill tone={pill.tone}>{pill.label}</Pill>+ </td>+ ) : null}+ </tr>+ </tbody>+ </table>+ </Section>+ <Section style={styles.content}>{children}</Section>+ </Section>+ {footer}+ </Container>+ </Body>+ </Html>);}diff --git a/packages/emails/emails/_components/markdown.tsx b/packages/emails/emails/_components/markdown.tsxnew file mode 100644index 000000000..c4ed6602b--- /dev/null+++ b/packages/emails/emails/_components/markdown.tsx@@ -0,0 +1,89 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Marked, Renderer } from "marked";++import { colors, fonts } from "./styles";++// double quotes would end the style attribute these strings are written into+const mono = fonts.mono.replace(/"/g, "'");++const text = `margin:0 0 16px;font-size:15px;line-height:24px;color:${colors.body}`;+const heading = `margin:20px 0 8px;padding:0;font-family:${mono};font-size:12px;line-height:16px;font-weight:400;letter-spacing:0.12em;text-transform:uppercase;color:${colors.faint}`;+const code = `font-family:${mono};font-size:13px;background-color:${colors.subtle}`;++const tagStyles: Record<string, string> = {+ p: text,+ li: `margin:0 0 6px;font-size:15px;line-height:24px;color:${colors.body}`,+ ul: "margin:0 0 16px;padding-left:20px;list-style-type:disc",+ ol: "margin:0 0 16px;padding-left:20px;list-style-type:decimal",+ h1: heading,+ h2: heading,+ h3: heading,+ h4: heading,+ h5: heading,+ h6: heading,+ strong: `font-weight:600;color:${colors.foreground}`,+ hr: `margin:20px 0;border:none;border-top:1px solid ${colors.border}`,+ code,+ pre: `margin:0 0 16px;padding:12px 14px;border-radius:8px;white-space:pre-wrap;word-break:break-word;${code}`,+ table: `width:100%;table-layout:fixed;word-break:break-word;margin:0 0 16px;border-collapse:collapse;font-size:14px;line-height:22px;color:${colors.body}`,+ th: `padding:6px 10px;border:1px solid ${colors.border};background-color:${colors.subtle};font-weight:600;color:${colors.foreground}`,+ td: `padding:6px 10px;border:1px solid ${colors.border}`,+ blockquote: `margin:0 0 16px;padding:0 0 0 14px;border-left:3px solid ${colors.border}`,+};++function escapeHtml(value: string) {+ return value+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'");+}++// Allowlist, not a blocklist: entity- or case-obfuscated schemes never match.+const SAFE_URL = /^(https?:\/\/|mailto:)/i;++const renderer = new Renderer();+// Subscribers must never receive author-controlled markup.+renderer.html = ({ text, block }) =>+ block ? `<p>${escapeHtml(text.trim())}</p>\n` : escapeHtml(text);+// mail clients strip <input>+renderer.checkbox = ({ checked }) => (checked ? "☑" : "☐");+renderer.link = function ({ href, tokens }) {+ const label = this.parser.parseInline(tokens);+ if (!SAFE_URL.test(href.trim())) return label;+ return `<a href="${escapeHtml(href.trim())}" target="_blank" style="color:${colors.body};text-decoration:underline">${label}</a>`;+};+renderer.image = ({ href, text }) =>+ /^https:\/\//i.test(href.trim())+ ? `<img src="${escapeHtml(href.trim())}" alt="${escapeHtml(text)}" style="max-width:100%;height:auto" />`+ : escapeHtml(text);++const marked = new Marked({ renderer, gfm: true, async: false });++// Safe because every author-written "<" is escaped above: any tag left in the+// output was produced by marked itself.+const STYLED_TAG = new RegExp(+ `<(${Object.keys(tagStyles).join("|")})(\\s[^>]*)?>`,+ "g",+);++export function renderMarkdown(source: string): string {+ const html = marked.parse(source) as string;+ return html.replace(+ STYLED_TAG,+ (_, tag: string, attrs = "") =>+ `<${tag}${attrs} style="${tagStyles[tag]}">`,+ );+}++export function Markdown({ children }: { children: string }) {+ return (+ <div+ style={{ margin: "0 0 24px" }}+ // oxlint-disable-next-line react/no-danger -- renderMarkdown escapes all author HTML+ dangerouslySetInnerHTML={{ __html: renderMarkdown(children) }}+ />+ );+}diff --git a/packages/emails/emails/_components/pill.tsx b/packages/emails/emails/_components/pill.tsxnew file mode 100644index 000000000..0cb210bc4--- /dev/null+++ b/packages/emails/emails/_components/pill.tsx@@ -0,0 +1,33 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { fonts, type Tone, tones } from "./styles";++export function Pill({+ tone = "neutral",+ children,+}: {+ tone?: Tone;+ children: string;+}) {+ const t = tones[tone];+ return (+ <span+ style={{+ display: "inline-block",+ padding: "5px 12px",+ border: `1px solid ${t.border}`,+ borderRadius: "999px",+ backgroundColor: t.bg,+ color: t.text,+ fontFamily: fonts.mono,+ fontSize: "11px",+ lineHeight: "14px",+ letterSpacing: "0.14em",+ textTransform: "uppercase",+ whiteSpace: "nowrap",+ }}+ >+ {children.toUpperCase()}+ </span>+ );+}diff --git a/packages/emails/emails/_components/signature.tsx b/packages/emails/emails/_components/signature.tsxnew file mode 100644index 000000000..5332fb6db--- /dev/null+++ b/packages/emails/emails/_components/signature.tsx@@ -0,0 +1,39 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { Hr, Text } from "react-email";++import { colors } from "./styles";++export function Signature({+ name = "Thibault",+ role = "Co-founder, openstatus",+}: {+ name?: string;+ role?: string;+}) {+ return (+ <>+ <Hr style={{ margin: "28px 0 20px", borderColor: colors.border }} />+ <Text+ style={{+ margin: 0,+ fontSize: "15px",+ lineHeight: "22px",+ color: colors.body,+ }}+ >+ {name}+ </Text>+ <Text+ style={{+ margin: 0,+ fontSize: "13px",+ lineHeight: "20px",+ color: colors.faint,+ }}+ >+ {role}+ </Text>+ </>+ );+}diff --git a/packages/emails/emails/_components/steps.tsx b/packages/emails/emails/_components/steps.tsxnew file mode 100644index 000000000..51510884c--- /dev/null+++ b/packages/emails/emails/_components/steps.tsx@@ -0,0 +1,57 @@+/** @jsxRuntime automatic @jsxImportSource react */++import type * as React from "react";+import { Text } from "react-email";++import { colors, styles } from "./styles";++export function Steps({+ label,+ variant = "ordered",+ items,+}: {+ label: string;+ variant?: "ordered" | "dashed";+ items: React.ReactNode[];+}) {+ return (+ <>+ <Text style={styles.label}>{label}</Text>+ <table+ role="presentation"+ cellPadding={0}+ cellSpacing={0}+ style={{ margin: "0 0 24px" }}+ >+ <tbody>+ {items.map((item, i) => (+ <tr key={i}>+ <td+ width={28}+ valign="top"+ style={{+ padding: "0 0 10px",+ fontSize: "15px",+ lineHeight: "24px",+ color: colors.faint,+ }}+ >+ {variant === "ordered" ? `${i + 1}.` : "—"}+ </td>+ <td+ style={{+ padding: "0 0 10px",+ fontSize: "15px",+ lineHeight: "24px",+ color: colors.body,+ }}+ >+ {item}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </>+ );+}diff --git a/packages/emails/emails/_components/styles.ts b/packages/emails/emails/_components/styles.tsindex fc8ca0597..b75aeab32 100644--- a/packages/emails/emails/_components/styles.ts+++ b/packages/emails/emails/_components/styles.ts@@ -1,43 +1,94 @@+import type * as React from "react";++export type Tone = "danger" | "warning" | "info" | "success" | "neutral";++export const fonts = {+ sans: '-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',+ mono: 'ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace',+};+export const colors = {- success: "#51b363",- danger: "#ec6041",- warning: "#ffd60a",- info: "#3d9eff",- border: "#dedede",+ page: "#f4f4f4",+ card: "#ffffff",+ border: "#e5e5e5",+ subtle: "#fafafa",+ foreground: "#171717",+ body: "#3f3f46",+ muted: "#525252",+ // 4.5:1 on both the card and the page background+ faint: "#6e6e6e",};+// The only colour axis: pill, breached value, status dot.+export const tones = {+ danger: { text: "#b42318", bg: "#fdf1f0", border: "#f6d5d2", dot: "#e5484d" },+ warning: {+ text: "#a0460a",+ bg: "#fffaeb",+ border: "#f5dfa0",+ dot: "#f08c2e",+ },+ info: { text: "#1d4ed8", bg: "#eff6ff", border: "#cfe0fb", dot: "#3b82f6" },+ success: {+ text: "#1f6b3a",+ bg: "#f3fbf5",+ border: "#cfe9d8",+ dot: "#46a758",+ },+ neutral: {+ text: "#3f3f46",+ bg: "#f4f4f4",+ border: "#e0e0e0",+ dot: "#a3a3a3",+ },+} satisfies Record<Tone, Record<string, string>>;+export const styles = {main: {- backgroundColor: "#ffffff",- color: "#24292e",- fontFamily:- '-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"',+ backgroundColor: colors.page,+ color: colors.foreground,+ fontFamily: fonts.sans,+ margin: 0,+ padding: "32px 12px",},container: {- maxWidth: "480px",+ maxWidth: "600px",margin: "0 auto",- padding: "20px 0 48px",},- section: {- padding: "24px",- margin: "24px 0",- border: "solid 1px #dedede",- borderRadius: "5px",+ card: {+ backgroundColor: colors.card,+ border: `1px solid ${colors.border}`,+ borderRadius: "12px",},- button: {- backgroundColor: "#24292e",- color: "#ffffff",- padding: "8px 16px",- borderRadius: "6px",+ header: {+ padding: "20px 28px",+ borderBottom: `1px solid ${colors.border}`,},- link: {- textDecoration: "underline",- color: colors.info,+ content: {+ padding: "32px 28px 28px",+ },+ text: {+ margin: "0 0 16px",+ fontSize: "15px",+ lineHeight: "24px",+ color: colors.body,},- bold: {- fontWeight: "bold",+ mono: {+ fontFamily: fonts.mono,+ fontSize: "0.94em",+ letterSpacing: "-0.01em",},- row: {- borderTop: "1px solid #dedede",+ label: {+ margin: "0 0 12px",+ fontFamily: fonts.mono,+ fontSize: "12px",+ lineHeight: "16px",+ letterSpacing: "0.12em",+ textTransform: "uppercase",+ color: colors.faint,+ },+ link: {+ color: colors.body,+ textDecoration: "underline",},} satisfies Record<string, React.CSSProperties>;diff --git a/packages/emails/emails/feedback.tsx b/packages/emails/emails/feedback.tsxindex f9918938e..433bbd116 100644--- a/packages/emails/emails/feedback.tsx+++ b/packages/emails/emails/feedback.tsx@@ -8,22 +8,22 @@ const FeedbackEmail = () => {<Head><title>One quick question</title></Head>- <Preview>What's the one thing you'd change about OpenStatus?</Preview>+ <Preview>What's the one thing you'd change about openstatus?</Preview><Body>Hey<br /><br />- You've been on OpenStatus for about two weeks now. One quick question:+ You've been on openstatus for about two weeks now. One quick question:<br /><br />- What's the one thing you wish OpenStatus did differently?+ What's the one thing you wish openstatus did differently?<br /><br />No survey, no form — just hit reply. I read every response and itgenuinely shapes what we build next.<br /><br />- Thibault Le Ouay Ducasse, co-founder of OpenStatus+ Thibault Le Ouay Ducasse, co-founder of openstatus<br /></Body></Html>diff --git a/packages/emails/emails/followup.tsx b/packages/emails/emails/followup.tsxindex 01640afce..d80bd14ac 100644--- a/packages/emails/emails/followup.tsx+++ b/packages/emails/emails/followup.tsx@@ -13,7 +13,7 @@ const FollowUpEmail = () => {Hey<br /><br />- Quick tip: connect the OpenStatus Slack app and manage incident updates+ Quick tip: connect the openstatus Slack app and manage incident updatesfor your status page directly from Slack — no need to switch tabs duringan outage.<br />@@ -30,7 +30,7 @@ const FollowUpEmail = () => {Hit reply if you have questions — happy to help.<br /><br />- Thibault Le Ouay Ducasse, co-founder of OpenStatus+ Thibault Le Ouay Ducasse, co-founder of openstatus<br /></Body></Html>diff --git a/packages/emails/emails/monitor-alert.tsx b/packages/emails/emails/monitor-alert.tsxindex d271c6874..a0aea9780 100644--- a/packages/emails/emails/monitor-alert.tsx+++ b/packages/emails/emails/monitor-alert.tsx@@ -1,169 +1,223 @@/** @jsxRuntime automatic @jsxImportSource react */-import {- Body,- CodeInline,- Column,- Head,- Heading,- Html,- Link,- Preview,- Row,- Text,-} from "react-email";import { z } from "zod";+import { Actions } from "./_components/actions";+import { CodeBlock } from "./_components/code-block";+import { Footer } from "./_components/footer";+import { formatDateTime } from "./_components/format";+import { Heading } from "./_components/heading";+import { KeyValue, type KeyValueRow } from "./_components/key-value";import { Layout } from "./_components/layout";-import { colors, styles } from "./_components/styles";+import type { Tone } from "./_components/styles";const MonitorAlertSchema = z.object({type: z.enum(["degraded", "alert", "recovery"]),+ monitorId: z.union([z.string(), z.number()]).optional(),name: z.string().optional(),url: z.string().optional(),method: z.string().optional(),status: z.string().optional(),latency: z.string().optional(),region: z.string().optional(),+ /** Regions in this state / regions the monitor runs in. */+ affectedRegions: z.number().optional(),+ totalRegions: z.number().optional(),timestamp: z.string().optional(),message: z.string().optional(),+ /** Latency threshold in ms (`monitor.degradedAfter`). */+ degradedAfter: z.number().optional(),+ /** Incident `startedAt`, ISO string. */+ firstSeen: z.string().optional(),});export type MonitorAlertProps = z.infer<typeof MonitorAlertSchema>;-function getIcon(type: MonitorAlertProps["type"]): {- src: string;- color: string;-} {- switch (type) {+const APP_URL = "https://app.openstatus.dev";++const states = {+ alert: { tone: "danger", pill: "Down" },+ degraded: { tone: "warning", pill: "Degraded" },+ recovery: { tone: "success", pill: "Recovered" },+} satisfies Record<MonitorAlertProps["type"], { tone: Tone; pill: string }>;++function hasValue(value?: string): value is string {+ return Boolean(value) && value !== "N/A";+}++function regionCount(props: MonitorAlertProps) {+ return props.affectedRegions && props.totalRegions+ ? `${props.affectedRegions}/${props.totalRegions}`+ : undefined;+}++function from(props: MonitorAlertProps) {+ const count = regionCount(props);+ if (count && props.affectedRegions !== 1) return ` from ${count} regions`;+ return hasValue(props.region) ? ` from ${props.region}` : "";+}++export function monitorAlertSubject(props: MonitorAlertProps): string {+ const name = props.name ?? "Your monitor";+ const latency = hasValue(props.latency) ? props.latency : undefined;+ switch (props.type) {+ case "alert":+ return `${name} is down — ${+ props.status ? `status ${props.status}` : "check failed"+ }${from(props)}`;+ case "degraded":+ return `${name} is slow — ${latency ?? "degraded"}${from(props)}`;case "recovery":- return {- src: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJsdWNpZGUgbHVjaWRlLWNoZWNrIj48cGF0aCBkPSJNMjAgNiA5IDE3bC01LTUiLz48L3N2Zz4=",- color: colors.success,- };+ return `${name} recovered — ${latency ?? "passing"}${from(props)}`;+ }+}++export function monitorAlertPreheader(props: MonitorAlertProps): string {+ switch (props.type) {case "alert":- return {- src: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJsdWNpZGUgbHVjaWRlLXgiPjxwYXRoIGQ9Ik0xOCA2IDYgMTgiLz48cGF0aCBkPSJtNiA2IDEyIDEyIi8+PC9zdmc+",- color: colors.danger,- };+ return "Open the monitor for the full response.";case "degraded":- return {- src: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJsdWNpZGUgbHVjaWRlLXRyaWFuZ2xlLWFsZXJ0Ij48cGF0aCBkPSJtMjEuNzMgMTgtOC0xNGEyIDIgMCAwIDAtMy40OCAwbC04IDE0QTIgMiAwIDAgMCA0IDIxaDE2YTIgMiAwIDAgMCAxLjczLTMiLz48cGF0aCBkPSJNMTIgOXY0Ii8+PHBhdGggZD0iTTEyIDE3aC4wMSIvPjwvc3ZnPg==",- color: colors.warning,- };+ return props.degradedAfter+ ? `Above your ${props.degradedAfter} ms threshold.`+ : "Response time is above your threshold.";+ case "recovery":+ return "Checks are passing again. No action needed.";}}-const MonitorAlertEmail = (props: MonitorAlertProps) => (- <Html>- <Head />- <Preview>Your monitor's status is: {props.type}</Preview>- <Body style={styles.main}>- <Layout>- <Row>- <Column>- <Heading as="h4">{props.name}</Heading>- </Column>- <Column style={{ textAlign: "right" }}>- <Text- style={{- color: getIcon(props.type).color,- textTransform: "uppercase",- }}- >- {props.type}- </Text>- </Column>- </Row>- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Request</Text>- </Column>- <Column- style={{- textAlign: "right",- flexWrap: "wrap",- wordWrap: "break-word",- maxWidth: "300px",- }}- >- <Text>- <CodeInline>{props.method}</CodeInline> {props.url}- </Text>- </Column>- </Row>- {/* REMINDER: no status code for TCP monitors */}- {props.status ? (- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Status</Text>- </Column>- <Column style={{ textAlign: "right" }}>- <Text>{props.status}</Text>- </Column>- </Row>- ) : null}- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Region</Text>- </Column>- <Column style={{ textAlign: "right" }}>- <Text>{props.region}</Text>- </Column>- </Row>- {props.latency ? (- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Latency</Text>- </Column>- <Column style={{ textAlign: "right" }}>- <Text>{props.latency}</Text>- </Column>- </Row>- ) : null}- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Timestamp</Text>- </Column>- <Column style={{ textAlign: "right" }}>- <Text>{props.timestamp}</Text>- </Column>- </Row>- {props.message ? (- <Row style={styles.row}>- <Column>- <Text>- {props.message?.slice(0, 200)}- {props.message?.length > 200 ? "..." : ""}- </Text>- </Column>- </Row>- ) : null}- <Row style={styles.row}>- <Column>- <Text style={{ textAlign: "center" }}>- <Link style={styles.link} href="https://openstatus.dev/app">- View details- </Link>- </Text>- </Column>- </Row>- </Layout>- </Body>- </Html>-);+function title(props: MonitorAlertProps) {+ const name = props.name ?? "Your monitor";+ if (props.type === "alert") return `${name} is down`;+ if (props.type === "degraded") return `${name} is answering slowly`;+ return `${name} is back up`;+}++function lede(props: MonitorAlertProps) {+ if (props.type === "alert") {+ return `A check${from(props)} failed${+ props.status ? ` with status ${props.status}` : ""+ }.`;+ }+ if (props.type === "degraded") {+ return `Latency crossed your ${+ props.degradedAfter ? `${props.degradedAfter} ms ` : ""+ }threshold${from(props)}.${+ props.status ? ` The endpoint is still returning ${props.status}.` : ""+ }`;+ }+ return `Checks${from(props)} are passing again. No action needed.`;+}++const MonitorAlertEmail = (props: MonitorAlertProps) => {+ const state = states[props.type];+ const monitorUrl = props.monitorId+ ? `${APP_URL}/monitors/${props.monitorId}`+ : `${APP_URL}/monitors`;++ const rows: KeyValueRow[] = [];+ if (hasValue(props.latency)) {+ rows.push({+ label: "Latency",+ value: props.latency,+ tone: props.type === "degraded" ? "warning" : undefined,+ hint:+ props.type === "degraded" && props.degradedAfter+ ? `threshold ${props.degradedAfter} ms`+ : undefined,+ });+ }+ // no status code for TCP / DNS monitors+ if (props.status) {+ rows.push({+ label: "Response",+ value: props.status,+ mono: true,+ tone: props.type === "alert" ? "danger" : undefined,+ });+ }+ if (props.url) {+ rows.push({+ label: "Request",+ value: [props.method, props.url].filter(Boolean).join(" "),+ mono: true,+ });+ }+ const count = regionCount(props);+ if (count) {+ rows.push({+ label: "Regions",+ value: count,+ hint:+ props.affectedRegions === 1 && hasValue(props.region)+ ? props.region+ : undefined,+ });+ } else if (hasValue(props.region)) {+ rows.push({ label: "Region", value: props.region });+ }+ if (props.firstSeen) {+ rows.push({ label: "First seen", value: formatDateTime(props.firstSeen) });+ }+ if (props.timestamp) {+ rows.push({ label: "Checked at", value: formatDateTime(props.timestamp) });+ }++ return (+ <Layout+ preview={monitorAlertPreheader(props)}+ pill={{ tone: state.tone, label: state.pill }}+ footer={+ <Footer+ rule={+ props.type === "degraded" && props.degradedAfter+ ? `latency > ${props.degradedAfter}ms`+ : undefined+ }+ reason="You get this because this address is a notification channel for the monitor."+ links={+ props.monitorId && props.type === "degraded" && props.degradedAfter+ ? [{ label: "Edit rule", href: `${monitorUrl}/edit` }]+ : []+ }+ />+ }+ >+ <Heading title={title(props)}>{lede(props)}</Heading>+ <KeyValue rows={rows} />+ {props.message ? (+ <CodeBlock>+ {props.message.length > 400+ ? `${props.message.slice(0, 400)}…`+ : props.message}+ </CodeBlock>+ ) : null}+ <Actions+ primary={{ label: "Open monitor", href: monitorUrl }}+ secondary={+ props.monitorId+ ? { label: "Edit notifications", href: `${monitorUrl}/edit` }+ : undefined+ }+ />+ </Layout>+ );+};MonitorAlertEmail.PreviewProps = {- type: "alert",+ type: "degraded",+ monitorId: 1,name: "Ping Pong",url: "https://openstatus.dev/ping",method: "GET",status: "200",- latency: "300ms",+ latency: "300 ms",region: "Amsterdam, Netherlands",- timestamp: "2021-10-13T17:29:00Z",- message:- "This is a very long test message that will be truncated. Just testing it for the preview. Veryy veryy long message.",+ affectedRegions: 5,+ totalRegions: 6,+ timestamp: "2026-10-13T17:32:00Z",+ firstSeen: "2026-10-13T17:29:00Z",+ degradedAfter: 250,+ message: "upstream response time 0.302s, cache: MISS",} satisfies MonitorAlertProps;export default MonitorAlertEmail;diff --git a/packages/emails/emails/monitor-deactivation.tsx b/packages/emails/emails/monitor-deactivation.tsxindex fd977ba15..4061c976b 100644--- a/packages/emails/emails/monitor-deactivation.tsx+++ b/packages/emails/emails/monitor-deactivation.tsx@@ -1,70 +1,93 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Button, Head, Html, Preview, Text } from "react-email";import { z } from "zod";+import { Actions } from "./_components/actions";+import { Callout } from "./_components/callout";+import { Footer } from "./_components/footer";+import {+ formatDay,+ formatLongDay,+ formatShortDay,+ plural,+} from "./_components/format";+import { Heading } from "./_components/heading";+import { KeyValue, type KeyValueRow } from "./_components/key-value";import { Layout } from "./_components/layout";-import { styles } from "./_components/styles";+import { Signature } from "./_components/signature";export const MonitorDeactivationSchema = z.object({- // lastLogin: z.coerce.date(),deactivateAt: z.coerce.date(),+ monitorCount: z.number().optional(),+ workspaceSlug: z.string().optional(),+ lastSignIn: z.coerce.date().optional(),});export type MonitorDeactivationProps = z.infer<typeof MonitorDeactivationSchema>;+export function monitorDeactivationSubject(+ props: Pick<MonitorDeactivationProps, "deactivateAt">,+): string {+ return `Your monitors pause on ${formatShortDay(props.deactivateAt)} — one sign-in stops it`;+}+const MonitorDeactivationEmail = ({- // lastLogin,deactivateAt,+ monitorCount,+ workspaceSlug,+ lastSignIn,}: MonitorDeactivationProps) => {+ const rows: KeyValueRow[] = [];+ if (workspaceSlug) {+ rows.push({ label: "Workspace", value: workspaceSlug, mono: true });+ }+ if (lastSignIn)+ rows.push({ label: "Last sign-in", value: formatDay(lastSignIn) });+ rows.push({ label: "Pauses on", value: formatDay(deactivateAt), bold: true });+return (- <Html>- <Head />- <Preview>- Login to your OpenStatus account to keep your monitors active.- </Preview>- <Body style={styles.main}>- <Layout>- <Text>Hello 👋</Text>- {/* <Heading as="h3">Deactivation of the your monitor(s)</Heading> */}- <Text>- To save on cloud resources and avoid having stale monitors. We are- deactivating monitors for free account if you have not logged in for- the last 2 months.- </Text>- {/* <Text>Your last login was {lastLogin.toDateString()}.</Text> */}- <Text>- Your monitor(s) will be deactivated on {deactivateAt.toDateString()}- .- </Text>- <Text>- If you would like to keep your monitor(s) active, please login to- your account or upgrade to a paid plan.- </Text>- <Text style={{ textAlign: "center" }}>- <Button style={styles.button} href="https://www.openstatus.dev/app">- Login- </Button>- </Text>- <Text>If you have any questions, please reply to this email.</Text>- <Text>Thibault </Text>- <Text>- Check out our latest update{" "}- <a href="https://www.openstatus.dev/changelog?ref=paused-email">- here- </a>- </Text>- </Layout>- </Body>- </Html>+ <Layout+ preview="Nothing is deleted. History and status pages stay."+ pill={{ tone: "neutral", label: "Action needed" }}+ footer={+ <Footer reason="You get this because you own a free workspace with active monitors." />+ }+ >+ <Heading+ title={`${+ monitorCount ? plural(monitorCount, "monitor") : "Your monitors"+ } will pause on ${formatLongDay(deactivateAt)}`}+ >+ Nobody has signed in to this free workspace for two months, so we pause+ its monitors to keep capacity for active accounts.+ </Heading>+ <Callout title="Nothing gets deleted">+ Monitors, check history and status pages stay exactly as they are. If+ they do pause, you can switch them back on at any time.+ </Callout>+ <KeyValue rows={rows} />+ <Actions+ primary={{+ label: "Sign in to keep them running",+ href: "https://app.openstatus.dev",+ }}+ secondary={{+ label: "Upgrade instead",+ href: "https://app.openstatus.dev/settings/billing",+ }}+ />+ <Signature />+ </Layout>);};MonitorDeactivationEmail.PreviewProps = {- // lastLogin: new Date(new Date().setDate(new Date().getDate() - 100)),- deactivateAt: new Date(new Date().setDate(new Date().getDate() + 7)),+ deactivateAt: new Date("2026-09-25T00:00:00Z"),+ monitorCount: 3,+ workspaceSlug: "acme-dev",+ lastSignIn: new Date("2026-07-21T00:00:00Z"),} satisfies MonitorDeactivationProps;export default MonitorDeactivationEmail;diff --git a/packages/emails/emails/monitor-paused.tsx b/packages/emails/emails/monitor-paused.tsxindex 528261b4d..2d4e33b75 100644--- a/packages/emails/emails/monitor-paused.tsx+++ b/packages/emails/emails/monitor-paused.tsx@@ -1,45 +1,73 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Button, Head, Html, Preview, Text } from "react-email";+import { z } from "zod";+import { Actions } from "./_components/actions";+import { Callout } from "./_components/callout";+import { Footer } from "./_components/footer";+import { plural } from "./_components/format";+import { Heading } from "./_components/heading";+import { KeyValue } from "./_components/key-value";import { Layout } from "./_components/layout";-import { styles } from "./_components/styles";+import { Signature } from "./_components/signature";-const MonitorPausedEmail = () => {+export const MonitorPausedSchema = z.object({+ monitorCount: z.number().optional(),+ workspaceSlug: z.string().optional(),+});++export type MonitorPausedProps = z.infer<typeof MonitorPausedSchema>;++export const MONITOR_PAUSED_SUBJECT =+ "Your monitors are paused — sign in to switch them back on";++const MonitorPausedEmail = ({+ monitorCount,+ workspaceSlug,+}: MonitorPausedProps) => {return (- <Html>- <Head />- <Preview>Your monitors have been paused</Preview>- <Body style={styles.main}>- <Layout>- <Text>Hello 👋</Text>- {/* <Heading as="h3">Deactivation of the your monitor(s)</Heading> */}- <Text>- To save on cloud resources, your monitor(s) has been paused due to- inactivity.- </Text>- <Text>- If you would like to unpause your monitor(s), please login to your- account or upgrade to a paid plan.- </Text>- <Text style={{ textAlign: "center" }}>- <Button style={styles.button} href="https://www.openstatus.dev/app">- Login- </Button>- </Text>-- <Text>If you have any questions, please reply to this email.</Text>- <Text>Thibault</Text>- <Text>- Check out our latest update{" "}- <a href="https://www.openstatus.dev/changelog?ref=paused-email">- here- </a>- </Text>- </Layout>- </Body>- </Html>+ <Layout+ preview="Nothing was deleted. History and status pages stay."+ pill={{ tone: "neutral", label: "Account change" }}+ footer={+ <Footer reason="You get this because you own a free workspace whose monitors were paused." />+ }+ >+ <Heading+ title={`${+ monitorCount ? plural(monitorCount, "monitor") : "Your monitors"+ } ${monitorCount === 1 ? "has" : "have"} been paused`}+ >+ Nobody has signed in to this free workspace for over two months, so its+ monitors are paused. No checks run and no alerts are sent until you+ switch them back on.+ </Heading>+ <Callout title="Nothing was deleted">+ Monitors, check history and status pages are exactly as you left them.+ </Callout>+ {workspaceSlug ? (+ <KeyValue+ rows={[{ label: "Workspace", value: workspaceSlug, mono: true }]}+ />+ ) : null}+ <Actions+ primary={{+ label: "Sign in to resume",+ href: "https://app.openstatus.dev/monitors",+ }}+ secondary={{+ label: "Upgrade instead",+ href: "https://app.openstatus.dev/settings/billing",+ }}+ />+ <Signature />+ </Layout>);};+MonitorPausedEmail.PreviewProps = {+ monitorCount: 3,+ workspaceSlug: "acme-dev",+} satisfies MonitorPausedProps;+export default MonitorPausedEmail;diff --git a/packages/emails/emails/page-subscription.tsx b/packages/emails/emails/page-subscription.tsxindex 9741d8a87..cf42c4134 100644--- a/packages/emails/emails/page-subscription.tsx+++ b/packages/emails/emails/page-subscription.tsx@@ -1,10 +1,11 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Head, Heading, Html, Link, Preview, Text } from "react-email";import { z } from "zod";-import { Layout } from "./_components/layout";-import { styles } from "./_components/styles";+import { Actions } from "./_components/actions";+import { Footer } from "./_components/footer";+import { Heading } from "./_components/heading";+import { Layout, statusPageBrand } from "./_components/layout";export const PageSubscriptionSchema = z.object({page: z.string(),@@ -22,37 +23,28 @@ export type PageSubscriptionProps = z.infer<typeof PageSubscriptionSchema>;const PageSubscriptionEmail = ({ page, link, img }: PageSubscriptionProps) => {return (- <Html>- <Head />- <Preview>Confirm your subscription to "{page}" Status Page</Preview>- <Body style={styles.main}>- <Layout img={img}>- <Heading as="h3">- Confirm your subscription to "{page}" Status Page- </Heading>- <Text>- You are receiving this email because you subscribed to receive- updates from "{page}" Status Page.- </Text>- <Text>- To confirm your subscription, please click the link below. The link- is valid for 7 days. If you believe this is a mistake, please ignore- this email.- </Text>- <Text>- <Link style={styles.link} href={link}>- Confirm subscription- </Link>- </Text>- </Layout>- </Body>- </Html>+ <Layout+ preview="One click to confirm. The link is valid for 7 days."+ brand={statusPageBrand(page, img?.href ?? link, img?.src)}+ pill={{ tone: "neutral", label: "Confirm" }}+ footer={+ <Footer+ reason={`You get this because this address was subscribed to updates from ${page}. If that wasn’t you, ignore this email.`}+ />+ }+ >+ <Heading title={`Confirm your subscription to ${page}`}>+ Once confirmed, you get email updates from this status page. The link is+ valid for 7 days.+ </Heading>+ <Actions primary={{ label: "Confirm subscription", href: link }} />+ </Layout>);};PageSubscriptionEmail.PreviewProps = {link: "https://slug.openstatus.dev/verify/token",- page: "OpenStatus",+ page: "Acme",} satisfies PageSubscriptionProps;export default PageSubscriptionEmail;diff --git a/packages/emails/emails/private-location-alert.tsx b/packages/emails/emails/private-location-alert.tsxindex 37e4eee7a..4cd4924f9 100644--- a/packages/emails/emails/private-location-alert.tsx+++ b/packages/emails/emails/private-location-alert.tsx@@ -1,76 +1,104 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Button, Head, Heading, Html, Preview, Text } from "react-email";import { z } from "zod";+import { Actions } from "./_components/actions";+import { Footer } from "./_components/footer";+import { formatDateTime, plural } from "./_components/format";+import { Heading, Mono } from "./_components/heading";+import { KeyValue, type KeyValueRow } from "./_components/key-value";import { Layout } from "./_components/layout";-import { colors, styles } from "./_components/styles";+import { Steps } from "./_components/steps";const PrivateLocationAlertSchema = z.object({locationName: z.string(),status: z.enum(["error", "recovered"]),lastSeenAt: z.string(),+ /** Monitors scheduled on this location. */+ monitorCount: z.number().optional(),});export type PrivateLocationAlertProps = z.infer<typeof PrivateLocationAlertSchema>;+const LOCATIONS_URL = "https://app.openstatus.dev/settings/private-locations";++export function privateLocationAlertSubject(+ props: Pick<PrivateLocationAlertProps, "locationName" | "status">,+): string {+ return props.status === "error"+ ? `Checks paused — "${props.locationName}" stopped reporting`+ : `Checks resumed — "${props.locationName}" is reporting again`;+}+const PrivateLocationAlertEmail = (props: PrivateLocationAlertProps) => {const isError = props.status === "error";- const preview = isError- ? `Your private location "${props.locationName}" is unhealthy`- : `Your private location "${props.locationName}" is healthy again`;+ const rows: KeyValueRow[] = [+ { label: "Location", value: props.locationName, mono: true },+ { label: "Last result", value: formatDateTime(props.lastSeenAt) },+ ];+ if (props.monitorCount) {+ rows.push({+ label: isError ? "Checks skipped" : "Checks resumed",+ value: plural(props.monitorCount, "monitor"),+ });+ }return (- <Html>- <Head />- <Preview>{preview}</Preview>- <Body style={styles.main}>- <Layout>- <Heading- as="h4"- style={{ color: isError ? colors.danger : colors.success }}- >- {preview}- </Heading>- {isError ? (- <Text>- The agent for <strong>{props.locationName}</strong> has not- reported a result in over 15 minutes, so checks scheduled on this- location are not running. It was last seen at {props.lastSeenAt}.- </Text>- ) : (- <Text>- The agent for <strong>{props.locationName}</strong> is reporting- again and checks on this location have resumed. It was last seen- at {props.lastSeenAt}.- </Text>- )}- <Text>- {isError- ? "Check that the agent is running and can reach OpenStatus, then verify its token and network access."- : "No action is needed."}- </Text>- <Text style={{ textAlign: "center" }}>- <Button- style={styles.button}- href="https://www.openstatus.dev/app/settings/private-locations"- >- View private locations- </Button>- </Text>- <Text>If you have any questions, please reply to this email.</Text>- </Layout>- </Body>- </Html>+ <Layout+ preview={+ isError+ ? `Last result ${formatDateTime(props.lastSeenAt)}. Three things to check.`+ : "Checks on this private location are running again."+ }+ pill={+ isError+ ? { tone: "danger", label: "Unhealthy" }+ : { tone: "success", label: "Recovered" }+ }+ footer={+ <Footer reason="You get this because you are a member of this workspace." />+ }+ >+ <Heading+ title={+ <>+ Checks on <Mono>{props.locationName}</Mono>{" "}+ {isError ? "are paused" : "are running again"}+ </>+ }+ >+ {isError+ ? "This private location hasn’t sent a result for over 15 minutes. Until it reconnects, every check scheduled on it is skipped — no data, no alerts."+ : "This private location is reporting again and every check scheduled on it has resumed. No action needed."}+ </Heading>+ <KeyValue rows={rows} />+ {isError ? (+ <Steps+ label="Check, in this order"+ items={[+ "The private location container is still running.",+ <>+ It can reach openstatus outbound over HTTPS (port <Mono>443</Mono>+ ).+ </>,+ "Its token hasn’t been rotated or revoked.",+ ]}+ />+ ) : null}+ <Actions+ primary={{ label: "View private location", href: LOCATIONS_URL }}+ />+ </Layout>);};PrivateLocationAlertEmail.PreviewProps = {- locationName: "eu-west-agent",+ locationName: "eu-west-private",status: "error",lastSeenAt: "2026-07-23T10:00:00Z",+ monitorCount: 4,} satisfies PrivateLocationAlertProps;export default PrivateLocationAlertEmail;diff --git a/packages/emails/emails/slack-feedback.tsx b/packages/emails/emails/slack-feedback.tsxindex 630848237..721bb268a 100644--- a/packages/emails/emails/slack-feedback.tsx+++ b/packages/emails/emails/slack-feedback.tsx@@ -8,11 +8,11 @@ const SlackFeedbackEmail = () => {<Head><title>How's the Slack app working for you?</title></Head>- <Preview>We'd love your feedback on the OpenStatus Slack app</Preview>+ <Preview>We'd love your feedback on the openstatus Slack app</Preview><Body>Hey<br />- <br />I saw you installed the OpenStatus Slack app — thanks for trying+ <br />I saw you installed the openstatus Slack app — thanks for tryingit out!<br /><br />@@ -26,7 +26,7 @@ const SlackFeedbackEmail = () => {Just hit reply — I read every response.<br /><br />- Thibault Le Ouay Ducasse, co-founder of OpenStatus+ Thibault Le Ouay Ducasse, co-founder of openstatus<br /></Body></Html>diff --git a/packages/emails/emails/sso-disabled.tsx b/packages/emails/emails/sso-disabled.tsxindex a47d64845..05471021b 100644--- a/packages/emails/emails/sso-disabled.tsx+++ b/packages/emails/emails/sso-disabled.tsx@@ -1,40 +1,46 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Button, Head, Html, Preview, Text } from "react-email";-+import { Actions } from "./_components/actions";+import { Callout } from "./_components/callout";+import { Footer } from "./_components/footer";+import { Heading } from "./_components/heading";+import { KeyValue } from "./_components/key-value";import { Layout } from "./_components/layout";-import { styles } from "./_components/styles";+import { Signature } from "./_components/signature";const SsoDisabledEmail = () => {return (- <Html>- <Head />- <Preview>Single sign-on has been turned off for your workspace</Preview>- <Body style={styles.main}>- <Layout>- <Text>Hello 👋</Text>- <Text>- Your subscription ended, so SAML single sign-on has been turned off- for your workspace. SSO is part of the Scale plan.- </Text>- <Text>- Nobody has lost access — everyone can still sign in with GitHub or- Google. Your identity provider configuration has been kept, so- re-subscribing to Scale restores SSO without reconnecting it.- </Text>- <Text style={{ textAlign: "center" }}>- <Button- style={styles.button}- href="https://app.openstatus.dev/settings/billing"- >- View billing- </Button>- </Text>- <Text>If you have any questions, please reply to this email.</Text>- <Text>Thibault</Text>- </Layout>- </Body>- </Html>+ <Layout+ preview="Owners can still sign in with GitHub or Google. Re-subscribing restores SSO."+ pill={{ tone: "neutral", label: "Account change" }}+ footer={<Footer reason="Sent to workspace owners." />}+ >+ <Heading title="SAML single sign-on has been turned off">+ Your subscription ended, and SSO is a paid add-on.+ </Heading>+ <Callout title="Your setup is kept">+ You can still sign in with GitHub or Google. Your identity provider+ configuration is kept, so re-subscribing restores SSO without+ reconnecting anything.+ </Callout>+ <KeyValue+ rows={[+ { label: "Sign-in methods left", value: "GitHub, Google" },+ { label: "IdP configuration", value: "Kept", tone: "success" },+ ]}+ />+ <Actions+ primary={{+ label: "View billing",+ href: "https://app.openstatus.dev/settings/billing",+ }}+ secondary={{+ label: "Compare plans",+ href: "https://www.openstatus.dev/pricing",+ }}+ />+ <Signature />+ </Layout>);};diff --git a/packages/emails/emails/status-page-magic-link.tsx b/packages/emails/emails/status-page-magic-link.tsxindex 9fb083cff..406bf0be1 100644--- a/packages/emails/emails/status-page-magic-link.tsx+++ b/packages/emails/emails/status-page-magic-link.tsx@@ -1,9 +1,9 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Head, Heading, Html, Link, Preview, Text } from "react-email";--import { Layout } from "./_components/layout";-import { styles } from "./_components/styles";+import { Actions } from "./_components/actions";+import { Footer } from "./_components/footer";+import { Heading } from "./_components/heading";+import { Layout, statusPageBrand } from "./_components/layout";export interface StatusPageMagicLinkProps {page: string;@@ -12,36 +12,27 @@ export interface StatusPageMagicLinkProps {const StatusPageMagicLinkEmail = ({ page, link }: StatusPageMagicLinkProps) => {return (- <Html>- <Head>- <title>Authenticate to "{page}" Status Page</title>- </Head>- <Preview>Authenticate to "{page}" Status Page</Preview>- <Body>- <Layout>- <Heading as="h3">Access to "{page}" Status Page</Heading>- <Text>- You are receiving this email because you have requested access to- the "{page}" Status Page.- </Text>- <Text>- To authenticate, please click the link below. The link is valid for- 24 hours. If you believe this is a mistake, please ignore this- email.- </Text>- <Text>- <Link style={styles.link} href={link}>- Authenticate- </Link>- </Text>- </Layout>- </Body>- </Html>+ <Layout+ preview="One click to sign in. The link is valid for 24 hours."+ brand={statusPageBrand(page, link)}+ pill={{ tone: "neutral", label: "Sign in" }}+ footer={+ <Footer+ reason={`You get this because access to ${page} was requested for this address. If that wasn’t you, ignore this email.`}+ />+ }+ >+ <Heading title={`Sign in to ${page}`}>+ This status page is private. The link below signs you in and is valid+ for 24 hours.+ </Heading>+ <Actions primary={{ label: "Open status page", href: link }} />+ </Layout>);};StatusPageMagicLinkEmail.PreviewProps = {- page: "OpenStatus",+ page: "Acme",link: "https://slug.openstatus.dev/verify/token-xyz",} satisfies StatusPageMagicLinkProps;diff --git a/packages/emails/emails/status-report.tsx b/packages/emails/emails/status-report.tsxindex 91b8a2893..d106c32dd 100644--- a/packages/emails/emails/status-report.tsx+++ b/packages/emails/emails/status-report.tsx@@ -1,23 +1,16 @@/** @jsxRuntime automatic @jsxImportSource react */-import { statusLabel } from "@openstatus/utils";-import {- Body,- Column,- Head,- Heading,- Html,- Link,- Markdown,- Preview,- Row,- Section,- Text,-} from "react-email";import { z } from "zod";-import { Layout } from "./_components/layout";-import { colors, styles } from "./_components/styles";+import { Actions } from "./_components/actions";+import { Eyebrow } from "./_components/eyebrow";+import { Footer } from "./_components/footer";+import { formatDateTime, formatElapsed } from "./_components/format";+import { Heading } from "./_components/heading";+import { KeyValue } from "./_components/key-value";+import { Layout, statusPageBrand } from "./_components/layout";+import { Markdown } from "./_components/markdown";+import type { Tone } from "./_components/styles";export const StatusReportSchema = z.object({pageTitle: z.string(),@@ -33,27 +26,71 @@ export const StatusReportSchema = z.object({message: z.string(),reportTitle: z.string(),pageComponents: z.array(z.string()),+ // pageComponentImpact from db; absent for maintenance and legacy reports+ componentImpacts: z+ .array(+ z.object({+ name: z.string(),+ impact: z.enum([+ "operational",+ "degraded_performance",+ "partial_outage",+ "major_outage",+ ]),+ }),+ )+ .optional(),unsubscribeUrl: z.url(),manageUrl: z.url(),+ statusPageUrl: z.url().optional(),+ /** 1-based position of this update within the report. */+ updateIndex: z.number().optional(),+ reportStartedAt: z.string().optional(),});export type StatusReportProps = z.infer<typeof StatusReportSchema>;-function getStatusColor(status: string) {- switch (status) {- case "investigating":- return colors.danger;- case "identified":- return colors.warning;- case "resolved":- return colors.success;- case "monitoring":- return colors.info;- case "maintenance":- return colors.info;- default:- return colors.success;- }+const statusTone = {+ investigating: "danger",+ identified: "warning",+ monitoring: "info",+ resolved: "success",+ maintenance: "info",+} satisfies Record<StatusReportProps["status"], Tone>;++type Impact = NonNullable<+ StatusReportProps["componentImpacts"]+>[number]["impact"];++const impactRow = {+ operational: { label: "Operational", tone: "success" },+ degraded_performance: { label: "Degraded performance", tone: "warning" },+ partial_outage: { label: "Partial outage", tone: "warning" },+ major_outage: { label: "Major outage", tone: "danger" },+} satisfies Record<Impact, { label: string; tone: Tone }>;++const componentLabel = {+ investigating: "Affected",+ identified: "Affected",+ monitoring: "Monitoring",+ resolved: "Resolved",+ maintenance: "Maintenance",+} satisfies Record<StatusReportProps["status"], string>;++function isDate(value: string) {+ return !Number.isNaN(new Date(value).getTime());+}++export function statusReportPreheader(+ props: Pick<StatusReportProps, "status" | "pageTitle" | "pageComponents">,+): string {+ const components =+ props.pageComponents.length > 0+ ? props.pageComponents.slice(0, 3).join(", ")+ : props.pageTitle;+ if (props.status === "resolved") return `Resolved for ${components}.`;+ if (props.status === "maintenance") return `Planned work on ${components}.`;+ return `${componentLabel[props.status]}: ${components}.`;}function StatusReportEmail({@@ -63,113 +100,97 @@ function StatusReportEmail({reportTitle,pageTitle,pageComponents,+ componentImpacts,unsubscribeUrl,manageUrl,+ statusPageUrl,+ updateIndex,+ reportStartedAt,}: StatusReportProps) {+ const tone = statusTone[status];+ const dated = isDate(date);+ const elapsed =+ dated && reportStartedAt && isDate(reportStartedAt)+ ? formatElapsed(reportStartedAt, date)+ : undefined;++ const links = [];+ if (unsubscribeUrl)+ links.push({ label: "Unsubscribe", href: unsubscribeUrl });+ if (manageUrl) links.push({ label: "Manage notifications", href: manageUrl });+return (- <Html>- <Head />- <Preview>There are new updates on "{pageTitle}" page</Preview>- <Body style={styles.main}>- <Layout>- <Row>- <Column>- <Heading as="h3">{pageTitle}</Heading>- </Column>- <Column style={{ textAlign: "right" }}>- <Text style={{ color: getStatusColor(status) }}>- {statusLabel(status)}- </Text>- </Column>- </Row>- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Title</Text>- </Column>- <Column style={{ textAlign: "right" }}>- <Text>{reportTitle}</Text>- </Column>- </Row>- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Date</Text>- </Column>- <Column style={{ textAlign: "right" }}>- <Text>{date}</Text>- </Column>- </Row>- <Row style={styles.row}>- <Column>- <Text style={styles.bold}>Affected</Text>- </Column>- <Column style={{ textAlign: "right" }}>- <Text style={{ flexWrap: "wrap", wordWrap: "break-word" }}>- {pageComponents.length > 0 ? pageComponents.join(", ") : "N/A"}- </Text>- </Column>- </Row>- <Row style={styles.row}>- <Column>- <Markdown>{message}</Markdown>- </Column>- </Row>- {unsubscribeUrl && (- <Section style={{ marginTop: "24px", textAlign: "center" }}>- <Text style={{ fontSize: "12px", color: "#6b7280" }}>- <Link- href={unsubscribeUrl}- style={{ color: "#6b7280", textDecoration: "underline" }}- >- Unsubscribe- </Link>{" "}- ・{" "}- <Link- href={manageUrl}- style={{ color: "#6b7280", textDecoration: "underline" }}- >- Manage notifications- </Link>- </Text>- </Section>- )}- </Layout>- </Body>- </Html>+ <Layout+ preview={statusReportPreheader({ status, pageTitle, pageComponents })}+ brand={statusPageBrand(pageTitle, statusPageUrl ?? manageUrl)}+ pill={{ tone, label: status }}+ footer={+ <Footer+ reason={`You get this because you subscribed to updates from ${pageTitle}.`}+ links={links}+ />+ }+ >+ <Eyebrow+ items={[+ updateIndex ? `Update ${updateIndex}` : undefined,+ dated ? formatDateTime(date) : undefined,+ elapsed && elapsed !== "0m" ? `${elapsed} in` : undefined,+ ]}+ />+ <Heading title={reportTitle} />+ {!dated ? <KeyValue rows={[{ label: "Window", value: date }]} /> : null}+ {pageComponents.length > 0 ? (+ <KeyValue+ rows={pageComponents.map((name) => {+ const impact = componentImpacts?.find((c) => c.name === name);+ return {+ label: name,+ value: impact ? impactRow[impact.impact].label : null,+ tone: impact ? impactRow[impact.impact].tone : undefined,+ };+ })}+ />+ ) : null}+ <Markdown>{message}</Markdown>+ {statusPageUrl ? (+ <Actions+ primary={{ label: "Follow on the status page", href: statusPageUrl }}+ />+ ) : null}+ </Layout>);}StatusReportEmail.PreviewProps = {- pageTitle: "OpenStatus Status",- reportTitle: "API Unavaible",- status: "investigating",- date: new Date().toISOString(),- message: `-**Status**: Partial Service Restored--**GitHub Runners**: Operational--**Cache Action**: Degraded-------### What's Changed--- All queued workflows are now being picked up and completed successfully.-- Jobs are running normally on our GitHub App. ### Current Issue: Cache Action Unavailable Attempts to re-publish our action to GitHub Marketplace are returning 500 Internal Server Errors. This prevents the updated versions from going live.+ pageTitle: "openstatus",+ reportTitle: "API unavailable — service partially restored",+ status: "monitoring",+ date: "2026-09-18T12:37:00Z",+ reportStartedAt: "2026-09-18T10:23:00Z",+ updateIndex: 3,+ message: `Queued workflows have drained and jobs are running normally again. One piece is still broken: publishing our GitHub Action returns 500s upstream, so new versions can't go live.-### Mitigation In Progress+### What we're doing-- Collaborating with GitHub Support to resolve any upstream issues.+- Working with GitHub Support on the Marketplace 500s.+- Retrying the publish job every 15 minutes.-### Next Update+### What you need to do-We'll post another update by **19:00 UTC** today or sooner if critical developments occur. We apologize for the inconvenience and appreciate your patience as we restore full cache functionality.+Nothing. Pin the previous action version if your pipeline is blocked — next update by **14:00 UTC**.`,- pageComponents: ["OpenStatus API", "OpenStatus Webhook"],+ pageComponents: ["openstatus API", "GitHub Runners", "Cache Action"],+ componentImpacts: [+ { name: "openstatus API", impact: "operational" },+ { name: "GitHub Runners", impact: "degraded_performance" },+ { name: "Cache Action", impact: "partial_outage" },+ ],+ statusPageUrl: "https://status.openstatus.dev",unsubscribeUrl:"https://status.openstatus.dev/unsubscribe/550e8400-e29b-41d4-a716-446655440000",manageUrl:"https://status.openstatus.dev/manage/550e8400-e29b-41d4-a716-446655440000",-};+} satisfies StatusReportProps;export default StatusReportEmail;diff --git a/packages/emails/emails/subscribe.tsx b/packages/emails/emails/subscribe.tsxdeleted file mode 100644index b55492302..000000000--- a/packages/emails/emails/subscribe.tsx+++ /dev/null@@ -1,42 +0,0 @@-/** @jsxRuntime automatic @jsxImportSource react */--import { Body, Head, Html, Link, Preview } from "react-email";--interface SubscribeProps {- page: string;- link: string;-}--const SubscribeEmail = ({ page, link }: SubscribeProps) => {- return (- <Html>- <Head>- <title>Confirm your subscription to "{page}" Status Page</title>- </Head>- <Preview>Confirm your subscription to "{page}" Status Page</Preview>- <Body>- <p>Confirm your subscription to "{page}" Status Page</p>- <p>- You are receiving this email because you subscribed to receive updates- from {page} Status Page.- </p>- <p>- To confirm your subscription, please click the link below. If you- believe this is a mistake, please ignore this email.- </p>- <p>- <a href={link}>Confirm subscription</a>- </p>- <br />🚀 Powered by{" "}- <Link href="https://www.openstatus.dev">OpenStatus.dev</Link>- </Body>- </Html>- );-};--SubscribeEmail.PreviewProps = {- page: "OpenStatus",- link: "https://slug.openstatus.dev/verify/token-xyz",-} satisfies SubscribeProps;--export default SubscribeEmail;diff --git a/packages/emails/emails/team-invitation.tsx b/packages/emails/emails/team-invitation.tsxindex 11ebd7919..865109cb5 100644--- a/packages/emails/emails/team-invitation.tsx+++ b/packages/emails/emails/team-invitation.tsx@@ -1,10 +1,12 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Head, Heading, Html, Link, Preview, Text } from "react-email";import { z } from "zod";+import { Actions } from "./_components/actions";+import { Footer } from "./_components/footer";+import { Heading } from "./_components/heading";+import { KeyValue } from "./_components/key-value";import { Layout } from "./_components/layout";-import { styles } from "./_components/styles";const BASE_URL = "https://app.openstatus.dev/invite";@@ -24,34 +26,45 @@ const TeamInvitationEmail = ({baseUrl = BASE_URL,}: TeamInvitationProps) => {return (- <Html>- <Head />- <Preview>You have been invited to join OpenStatus.dev</Preview>- <Body style={styles.main}>- <Layout>- <Heading as="h3">- You have been invited to join{" "}- {workspaceName ? `"${workspaceName}" workspace` : "OpenStatus.dev"}{" "}- by {invitedBy}- </Heading>- <Text>- Click here to access the workspace:{" "}- <Link style={styles.link} href={`${baseUrl}?token=${token}`}>- accept invitation- </Link>- </Text>- <Text>- If you don't have an account yet, it will require you to create one.- </Text>- </Layout>- </Body>- </Html>+ <Layout+ preview={`${invitedBy} invited you. The link is valid for 7 days.`}+ pill={{ tone: "neutral", label: "Invitation" }}+ footer={+ <Footer reason="You get this because a workspace member invited this address. If that is a mistake, ignore this email." />+ }+ >+ <Heading+ title={+ workspaceName+ ? `Join ${workspaceName} on openstatus`+ : "Join openstatus"+ }+ >+ {invitedBy} invited you to their workspace. If you don’t have an account+ yet, accepting creates one.+ </Heading>+ <KeyValue+ rows={[+ ...(workspaceName+ ? [{ label: "Workspace", value: workspaceName }]+ : []),+ { label: "Invited by", value: invitedBy },+ { label: "Expires", value: "In 7 days" },+ ]}+ />+ <Actions+ primary={{+ label: "Accept invitation",+ href: `${baseUrl}?token=${token}`,+ }}+ />+ </Layout>);};TeamInvitationEmail.PreviewProps = {token: "token",- workspaceName: "OpenStatus",+ workspaceName: "acme",invitedBy: "[email protected]",} satisfies TeamInvitationProps;diff --git a/packages/emails/emails/team-invite-reminder.tsx b/packages/emails/emails/team-invite-reminder.tsxindex 8bb767727..e05d0cccb 100644--- a/packages/emails/emails/team-invite-reminder.tsx+++ b/packages/emails/emails/team-invite-reminder.tsx@@ -29,7 +29,7 @@ const TeamInviteReminderEmail = () => {Hit reply if you have questions — happy to help.<br /><br />- Thibault Le Ouay Ducasse, co-founder of OpenStatus+ Thibault Le Ouay Ducasse, co-founder of openstatus<br /></Body></Html>diff --git a/packages/emails/emails/welcome.tsx b/packages/emails/emails/welcome.tsxindex 836489e54..b65a88107 100644--- a/packages/emails/emails/welcome.tsx+++ b/packages/emails/emails/welcome.tsx@@ -1,46 +1,71 @@/** @jsxRuntime automatic @jsxImportSource react */-import { Body, Head, Html, Preview } from "react-email";+import { Link, Text } from "react-email";++import { Footer } from "./_components/footer";+import { Heading } from "./_components/heading";+import { Layout } from "./_components/layout";+import { Signature } from "./_components/signature";+import { Steps } from "./_components/steps";+import { styles } from "./_components/styles";++const REF = "ref=email-onboarding";++const links = [+ {+ label: "Agents",+ href: `https://app.openstatus.dev/agents?${REF}`,+ description:+ "manage incidents from Slack, your editor via MCP, or the CLI.",+ },+ {+ label: "Docs",+ href: `https://www.openstatus.dev/docs?${REF}`,+ description: "tutorials, guides and the full reference.",+ },+ {+ label: "Discord",+ href: `https://www.openstatus.dev/discord?${REF}`,+ description: "ask questions and talk to us and other users.",+ },+ {+ label: "Changelog",+ href: `https://www.openstatus.dev/changelog?${REF}`,+ description: "what we shipped recently.",+ },+];const WelcomeEmail = () => {return (- <Html>- <Head>- <title>Welcome to OpenStatus</title>- </Head>- <Preview>Set up your status page in under 5 minutes</Preview>-- <Body>- Hey 👋- <br />- <br />- Thanks for signing up for OpenStatus.- <br />- <br />- The fastest way to get started: create your status page. It takes under- 5 minutes and your users will have a single place to check if your- services are up.- <br />- <br />👉{" "}- <a href="https://app.openstatus.dev/status-pages/create?ref=email-onboarding">- Create your status page- </a>- <br />- <br />- Want full control? Use our{" "}- <a href="https://www.openstatus.dev/registry?ref=email-onboarding">- open source- </a>{" "}- to build your own status page and host it anywhere.- <br />- <br />- Hit reply if you get stuck — I read every response.- <br />- <br />- Thibault Le Ouay Ducasse, co-founder of OpenStatus- <br />- </Body>- </Html>+ <Layout+ preview="Agents, docs and where to find us"+ pill={{ tone: "neutral", label: "Welcome" }}+ footer={+ <Footer reason="You get this because you signed up for openstatus." />+ }+ >+ <Heading title="Welcome to openstatus">+ Thanks for signing up. A few places worth knowing about while you get+ set up.+ </Heading>+ <Steps+ label="Links"+ variant="dashed"+ items={links.map((l) => (+ <>+ <Link href={l.href} style={styles.link}>+ {l.label}+ </Link>+ {": "}+ {l.description}+ </>+ ))}+ />+ <Text style={{ ...styles.text, margin: 0 }}>+ Hit reply if you get stuck. I read every response.+ </Text>+ <Signature />+ </Layout>);};diff --git a/packages/emails/hotfix/monitor-alert.ts b/packages/emails/hotfix/monitor-alert.tsdeleted file mode 100644index fe5ddb5d0..000000000--- a/packages/emails/hotfix/monitor-alert.ts+++ /dev/null@@ -1,27 +0,0 @@-interface MonitorAlertEmailProps {- name?: string;- type: "alert" | "degraded" | "recovery";- url?: string;- status?: string;- latency?: string;- region?: string;- timestamp?: string;- message?: string;-}--export function monitorAlertEmail(props: MonitorAlertEmailProps) {- return `- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">-<html dir="ltr" lang="en">- <body>- <p>Your monitor is ${props.type}</p>- <ul>- <li>URL: ${props.url || "N/A"}</li>- <li>Status: ${props.status || "N/A"}</li>- <li>Timestamp: ${props.timestamp || "N/A"}</li>- <li>Message: ${props.message || "N/A"}</li>- </ul>- </body>-</html>-`;-}diff --git a/packages/emails/hotfix/monitor-deactivation.ts b/packages/emails/hotfix/monitor-deactivation.tsdeleted file mode 100644index 4b6bd6e4e..000000000--- a/packages/emails/hotfix/monitor-deactivation.ts+++ /dev/null@@ -1,26 +0,0 @@-interface MonitorDeactivationEmailProps {- date: string;-}--export const monitorDeactivationEmail = (- props: MonitorDeactivationEmailProps,-) => {- return `- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">- <html xmlns="http://www.w3.org/1999/xhtml">- <head>- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />- <title>Login to your OpenStatus account to keep your monitors active.</title>- <style>- body {- font-family: Arial, sans-serif;- }- </style>- </head>- <body>- <p>Hello, </p><p>To save on cloud resources and avoid having stale monitors. We are deactivating monitors for free account if you have not logged in for the last 2 months.</p><p>Your monitor(s) will be deactivated on ${props.date}</p><p>If you would like to keep your monitor(s) active, please login to your account or upgrade to a paid plan.</p><p>If you have any questions, please reply to this email.</p><p>Merci,</p><p>Thibault</p>- </body>- </html>-`;-};diff --git a/packages/emails/hotfix/monitor-paused.ts b/packages/emails/hotfix/monitor-paused.tsdeleted file mode 100644index b902930ba..000000000--- a/packages/emails/hotfix/monitor-paused.ts+++ /dev/null@@ -1,21 +0,0 @@-export const monitorPausedEmail = () => {- return `- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">- <html xmlns="http://www.w3.org/1999/xhtml">- <head>- <meta name="viewport" content="width=device-width, initial-scale=1.0" />- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />- <title>Your monitors have been paused</title>- <style>- body {- font-family: Arial, sans-serif;- }- </style>- </head>- <body>- <p>Hello, </p><p>To save on cloud resources, your monitor(s) has been paused due to inactivity.</p><p>If you would like to unpause your monitor(s), please login to your account or upgrade to a paid plan.</p><p>If you have any questions, please reply to this email.</p><p>Merci,</p><p>Thibault</p>- </body>- </html>--`;-};diff --git a/packages/emails/package.json b/packages/emails/package.jsonindex fa7798ea9..ef0eb0375 100644--- a/packages/emails/package.json+++ b/packages/emails/package.json@@ -20,6 +20,7 @@"@openstatus/utils": "workspace:*","@t3-oss/env-core": "catalog:","effect": "catalog:",+ "marked": "catalog:","react": "catalog:","react-email": "catalog:","resend": "catalog:",diff --git a/packages/emails/src/client.integration.test.tsx b/packages/emails/src/client.integration.test.tsxindex 6fed64ef2..47b3ec682 100644--- a/packages/emails/src/client.integration.test.tsx+++ b/packages/emails/src/client.integration.test.tsx@@ -1,7 +1,6 @@/** @jsxRuntime automatic @jsxImportSource react */import "./test-preload.ts";-import { statusLabel } from "@openstatus/utils";import { expect } from "@std/expect";import { describe, test } from "@std/testing/bdd";import { render } from "react-email";@@ -47,7 +46,7 @@ describe("Status Report Email - Unsubscribe Link in Body", () => {);// Should not contain the unsubscribe text when no URL provided- expect(html).not.toContain("from these notifications");+ expect(html).not.toContain("Unsubscribe");});test("should render unsubscribe link as clickable", async () => {@@ -68,7 +67,7 @@ describe("Status Report Email - Unsubscribe Link in Body", () => {expect(html).toContain(`href="${unsubscribeUrl}"`);});- test("should display unsubscribe link with proper styling", async () => {+ test("should render the unsubscribe link in the footer, outside the card", async () => {const html = await render(<StatusReportEmailpageTitle="Test Page"@@ -82,8 +81,10 @@ describe("Status Report Email - Unsubscribe Link in Body", () => {/>,);- // Check for muted styling (gray color for footer)- expect(html).toContain("#6b7280");+ expect(html.indexOf("Test message")).toBeLessThan(+ html.indexOf(unsubscribeUrl),+ );+ expect(html).toContain("Manage notifications");});});@@ -116,7 +117,7 @@ describe("Status Report Email - Subject Line", () => {describe("Status Report Email - Email Content Validation", () => {test("should include all required email fields", async () => {const props = {- pageTitle: "OpenStatus",+ pageTitle: "openstatus",reportTitle: "API Outage",status: "investigating" as const,date: "2024-01-15T10:00:00.000Z",@@ -159,7 +160,7 @@ describe("Status Report Email - Email Content Validation", () => {/>,);- expect(html).toContain(statusLabel(status));+ expect(html).toContain(status.toUpperCase());}});});diff --git a/packages/emails/src/client.test.ts b/packages/emails/src/client.test.tsindex 1e710bd17..bde1c6345 100644--- a/packages/emails/src/client.test.ts+++ b/packages/emails/src/client.test.ts@@ -134,3 +134,108 @@ describe("EmailClient.sendStatusReportUpdate - idempotency & chunking", () => {assertSpyCalls(batchSend, 1);});});++describe("EmailClient.sendMonitorAlert", () => {+ let client: EmailClient;+ // biome-ignore lint/suspicious/noExplicitAny: stub over the Resend send method+ let send: Stub<any>;++ beforeEach(() => {+ client = new EmailClient({ apiKey: "re_test_123" });+ send = stub(client.client.emails, "send", () => Promise.resolve(ok));+ });++ afterEach(() => {+ send.restore();+ });++ const req = {+ to: "[email protected]",+ type: "degraded" as const,+ monitorId: 42,+ name: "Ping Pong",+ url: "https://openstatus.dev/ping",+ status: "200",+ latency: "300 ms",+ region: "Amsterdam, Netherlands",+ degradedAfter: 250,+ };++ test("sends the rendered template from the system sender", async () => {+ await client.sendMonitorAlert(req);++ assertSpyCalls(send, 1);+ const payload = send.calls[0].args[0];+ expect(payload.to).toBe("[email protected]");+ expect(payload.from).toBe(+ "openstatus <[email protected]>",+ );+ expect(payload.replyTo).toBe("[email protected]");+ expect(payload.subject).toBe(+ "Ping Pong is slow — 300 ms from Amsterdam, Netherlands",+ );+ expect(payload.html).toContain("Ping Pong is answering slowly");+ expect(payload.html).toContain("threshold 250 ms");+ expect(payload.html).toContain("https://app.openstatus.dev/monitors/42");+ });++ test("rethrows a Resend error so the outbox can retry", async () => {+ send.restore();+ send = stub(client.client.emails, "send", () => Promise.resolve(fail));++ await expect(client.sendMonitorAlert(req)).rejects.toEqual({+ name: "application_error",+ });+ });+});++describe("EmailClient.sendPrivateLocationAlert", () => {+ let client: EmailClient;+ // biome-ignore lint/suspicious/noExplicitAny: stub over the Resend batch method+ let batchSend: Stub<any>;++ beforeEach(() => {+ client = new EmailClient({ apiKey: "re_test_123" });+ batchSend = stub(client.client.batch, "send", () => Promise.resolve(ok));+ });++ afterEach(() => {+ batchSend.restore();+ });++ const req = {+ to: ["[email protected]", "[email protected]"],+ locationName: "eu-west-private",+ status: "error" as const,+ lastSeenAt: new Date("2026-07-23T10:00:00Z"),+ monitorCount: 4,+ };++ test("sends one mail per member with subject, sender and body", async () => {+ await client.sendPrivateLocationAlert(req);++ assertSpyCalls(batchSend, 1);+ const emails = batchSend.calls[0].args[0];+ expect(emails.map((e: { to: string }) => e.to)).toEqual(req.to);+ expect(emails[0].from).toBe(+ "openstatus <[email protected]>",+ );+ expect(emails[0].subject).toBe(+ 'Checks paused — "eu-west-private" stopped reporting',+ );+ expect(emails[0].html).toContain("4 monitors");+ expect(emails[0].html).toContain("23 Jul, 10:00 UTC");+ });++ test("does nothing without recipients", async () => {+ await client.sendPrivateLocationAlert({ ...req, to: [] });+ assertSpyCalls(batchSend, 0);+ });++ test("swallows a non rate-limit failure", async () => {+ batchSend.restore();+ batchSend = stub(client.client.batch, "send", () => Promise.resolve(fail));+ await client.sendPrivateLocationAlert(req);+ assertSpyCalls(batchSend, 1);+ });+});diff --git a/packages/emails/src/client.tsx b/packages/emails/src/client.tsxindex 4f1a6870f..32e753ebe 100644--- a/packages/emails/src/client.tsx+++ b/packages/emails/src/client.tsx@@ -6,10 +6,15 @@ import { render } from "react-email";import { Resend } from "resend";import FollowUpEmail from "../emails/followup";+import MonitorAlertEmail, {+ monitorAlertSubject,+} from "../emails/monitor-alert";import type { MonitorAlertProps } from "../emails/monitor-alert";import PageSubscriptionEmail from "../emails/page-subscription";import type { PageSubscriptionProps } from "../emails/page-subscription";-import PrivateLocationAlertEmail from "../emails/private-location-alert";+import PrivateLocationAlertEmail, {+ privateLocationAlertSubject,+} from "../emails/private-location-alert";import type { PrivateLocationAlertProps } from "../emails/private-location-alert";import SlackFeedbackEmail from "../emails/slack-feedback";import StatusPageMagicLinkEmail from "../emails/status-page-magic-link";@@ -18,7 +23,6 @@ import StatusReportEmail from "../emails/status-report";import type { StatusReportProps } from "../emails/status-report";import TeamInvitationEmail from "../emails/team-invitation";import type { TeamInvitationProps } from "../emails/team-invitation";-import { monitorAlertEmail } from "../hotfix/monitor-alert";import { env } from "./env";export function statusReportSubject(req: {@@ -31,6 +35,9 @@ export function statusReportSubject(req: {return req.reportTitle;}+const SYSTEM_FROM = "openstatus <[email protected]>";+const SUPPORT_EMAIL = "[email protected]";+// Deterministic Resend rejections: retrying the identical request can never// succeed (e.g. 409 invalid_idempotent_request when a key is reused with a// different body), it only burns the backoff and re-logs the error.@@ -75,7 +82,7 @@ export class EmailClient {const result = await this.client.emails.send({from: "Thibault Le Ouay Ducasse <[email protected]>",replyTo: "Thibault Le Ouay Ducasse <[email protected]>",- subject: "How's it going with OpenStatus?",+ subject: "How's it going with openstatus?",to: req.to,html,});@@ -101,7 +108,7 @@ export class EmailClient {const result = await this.client.batch.send(req.to.map((subscriber) => ({from: "Thibault Le Ouay Ducasse <[email protected]>",- subject: "How's it going with OpenStatus?",+ subject: "How's it going with openstatus?",to: subscriber,html,})),@@ -179,7 +186,10 @@ export class EmailClient {}public async sendStatusReportUpdate(- req: Omit<StatusReportProps, "unsubscribeUrl" | "manageUrl"> & {+ req: Omit<+ StatusReportProps,+ "unsubscribeUrl" | "manageUrl" | "statusPageUrl"+ > & {subscribers: Array<{ email: string; token: string }>;pageSlug: string;customDomain?: string | null;@@ -223,6 +233,7 @@ export class EmailClient {react: (<StatusReportEmail{...req}+ statusPageUrl={statusPageBaseUrl}unsubscribeUrl={unsubscribeUrl}manageUrl={manageUrl}/>@@ -265,10 +276,11 @@ export class EmailClient {const html = await render(<TeamInvitationEmail {...req} />);const result = await this.client.emails.send({from: `${- req.workspaceName ?? "OpenStatus"+ req.workspaceName || "openstatus"} <[email protected]>`,+ replyTo: SUPPORT_EMAIL,subject: `You've been invited to join ${- req.workspaceName ?? "OpenStatus"+ req.workspaceName || "openstatus"}`,to: req.to,html,@@ -292,11 +304,12 @@ export class EmailClient {}try {- // const html = await render(<MonitorAlertEmail {...req} />);- const html = monitorAlertEmail(req);+ const { to: _to, ...props } = req;+ const html = await render(<MonitorAlertEmail {...props} />);const result = await this.client.emails.send({- from: "OpenStatus <[email protected]>",- subject: `${req.name}: ${req.type.toUpperCase()}`,+ from: SYSTEM_FROM,+ replyTo: SUPPORT_EMAIL,+ subject: monitorAlertSubject(props),to: req.to,html,});@@ -419,6 +432,7 @@ export class EmailClient {date={`${req.from} - ${req.to}`}message={req.message}pageComponents={req.pageComponents}+ statusPageUrl={statusPageBaseUrl}unsubscribeUrl={unsubscribeUrl}manageUrl={manageUrl}/>@@ -459,10 +473,7 @@ export class EmailClient {) {if (req.to.length === 0) return;- const subject =- req.status === "error"- ? `Your private location "${req.locationName}" is unhealthy`- : `Your private location "${req.locationName}" is healthy again`;+ const subject = privateLocationAlertSubject(req);if (env.NODE_ENV === "development") {console.log(@@ -477,11 +488,13 @@ export class EmailClient {locationName={req.locationName}status={req.status}lastSeenAt={req.lastSeenAt.toISOString()}+ monitorCount={req.monitorCount}/>,);const result = await this.client.batch.send(req.to.map((to) => ({- from: "OpenStatus <[email protected]>",+ from: SYSTEM_FROM,+ replyTo: SUPPORT_EMAIL,subject,to,html,diff --git a/packages/emails/src/format.test.ts b/packages/emails/src/format.test.tsnew file mode 100644index 000000000..534797338--- /dev/null+++ b/packages/emails/src/format.test.ts@@ -0,0 +1,58 @@+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";++import {+ formatDateTime,+ formatDay,+ formatElapsed,+ formatLongDay,+ formatShortDay,+ plural,+} from "../emails/_components/format";++describe("email date formatting", () => {+ test("timestamps carry an explicit UTC suffix", () => {+ expect(formatDateTime("2026-09-18T12:37:00Z")).toBe("18 Sep, 12:37 UTC");+ expect(formatDateTime(new Date("2026-10-13T00:05:00Z"))).toBe(+ "13 Oct, 00:05 UTC",+ );+ });++ test("timestamps are rendered in UTC regardless of the offset given", () => {+ expect(formatDateTime("2026-09-18T23:30:00-02:00")).toBe(+ "19 Sep, 01:30 UTC",+ );+ });++ test("day-only dates drop the suffix", () => {+ expect(formatDay("2026-09-25T00:00:00Z")).toBe("Fri 25 Sep 2026");+ expect(formatDay("2026-09-25T00:00:00Z")).not.toContain("UTC");+ expect(formatLongDay("2026-09-25T00:00:00Z")).toBe("Friday 25 September");+ expect(formatShortDay("2026-09-25T00:00:00Z")).toBe("25 Sep");+ });++ test("unparseable input is returned as-is", () => {+ expect(formatDateTime("Mon - Tue")).toBe("Mon - Tue");+ expect(formatDay("soon")).toBe("soon");+ });++ test("elapsed time", () => {+ expect(formatElapsed("2026-09-18T10:23:00Z", "2026-09-18T12:37:00Z")).toBe(+ "2h 14m",+ );+ expect(formatElapsed("2026-09-18T10:23:00Z", "2026-09-18T10:50:00Z")).toBe(+ "27m",+ );+ expect(formatElapsed("2026-09-18T10:00:00Z", "2026-09-20T13:00:00Z")).toBe(+ "2d 3h",+ );+ expect(formatElapsed("2026-09-18T12:00:00Z", "2026-09-18T10:00:00Z")).toBe(+ "0m",+ );+ });++ test("plural", () => {+ expect(plural(1, "monitor")).toBe("1 monitor");+ expect(plural(3, "monitor")).toBe("3 monitors");+ });+});diff --git a/packages/emails/src/index.ts b/packages/emails/src/index.tsindex 9573f28a7..c37ac682f 100644--- a/packages/emails/src/index.ts+++ b/packages/emails/src/index.ts@@ -1,7 +1,7 @@export { default as FeedbackEmail } from "../emails/feedback";export { default as FollowUpEmail } from "../emails/followup";export { default as SlackFeedbackEmail } from "../emails/slack-feedback";-export { default as SubscribeEmail } from "../emails/subscribe";+export { default as PageSubscriptionEmail } from "../emails/page-subscription";export { default as TeamInviteReminderEmail } from "../emails/team-invite-reminder";export { default as WelcomeEmail } from "../emails/welcome";export { default as TeamInvitationEmail } from "../emails/team-invitation";@@ -11,8 +11,7 @@ export { default as PrivateLocationAlertEmail } from "../emails/private-locationexport { default as StatusPageMagicLinkEmail } from "../emails/status-page-magic-link";export { default as SsoDisabledEmail } from "../emails/sso-disabled";-export { monitorDeactivationEmail } from "../hotfix/monitor-deactivation";-export { monitorPausedEmail } from "../hotfix/monitor-paused";+export { monitorDeactivationEmail, monitorPausedEmail } from "./render";export { sendEmail, sendEmailHtml, sendBatchEmailHtml } from "./send";export { EmailClient } from "./client";diff --git a/packages/emails/src/render.tsx b/packages/emails/src/render.tsxnew file mode 100644index 000000000..190a73921--- /dev/null+++ b/packages/emails/src/render.tsx@@ -0,0 +1,28 @@+/** @jsxRuntime automatic @jsxImportSource react */++import { render } from "react-email";++import MonitorDeactivationEmail, {+ type MonitorDeactivationProps,+ monitorDeactivationSubject,+} from "../emails/monitor-deactivation";+import MonitorPausedEmail, {+ MONITOR_PAUSED_SUBJECT,+ type MonitorPausedProps,+} from "../emails/monitor-paused";++export async function monitorDeactivationEmail(+ props: MonitorDeactivationProps,+) {+ return {+ subject: monitorDeactivationSubject(props),+ html: await render(<MonitorDeactivationEmail {...props} />),+ };+}++export async function monitorPausedEmail(props: MonitorPausedProps = {}) {+ return {+ subject: MONITOR_PAUSED_SUBJECT,+ html: await render(<MonitorPausedEmail {...props} />),+ };+}diff --git a/packages/emails/src/send.ts b/packages/emails/src/send.tsindex a51c1e4d5..e63f1c422 100644--- a/packages/emails/src/send.ts+++ b/packages/emails/src/send.ts@@ -21,19 +21,24 @@ export type EmailHtml = {from: string;reply_to?: string;};+// Indirection so tests can enable delivery against a stubbed Resend client.+export const delivery = {+ enabled: () => env.NODE_ENV === "production",+};+export const sendEmail = async (email: Emails) => {- if (env.NODE_ENV !== "production") return;+ if (!delivery.enabled()) return;await resend.emails.send(email);};export const sendBatchEmailHtml = async (emails: EmailHtml[]) => {- if (env.NODE_ENV !== "production") return;+ if (!delivery.enabled()) return;await resend.batch.send(emails);};// TODO: delete in favor of sendBatchEmailHtmlexport const sendEmailHtml = async (emails: EmailHtml[]) => {- if (env.NODE_ENV !== "production") return;+ if (!delivery.enabled()) return;await fetch("https://api.resend.com/emails/batch", {method: "POST",@@ -46,7 +51,7 @@ export const sendEmailHtml = async (emails: EmailHtml[]) => {};export const sendWithRender = async (email: Emails) => {- if (env.NODE_ENV !== "production") return;+ if (!delivery.enabled()) return;const html = await render(email.react);await resend.emails.send({...email,diff --git a/packages/emails/src/templates.test.tsx b/packages/emails/src/templates.test.tsxnew file mode 100644index 000000000..7610b6e94--- /dev/null+++ b/packages/emails/src/templates.test.tsx@@ -0,0 +1,704 @@+/** @jsxRuntime automatic @jsxImportSource react */++import "./test-preload.ts";+import { expect } from "@std/expect";+import { describe, test } from "@std/testing/bdd";+import { render } from "react-email";++import { Callout } from "../emails/_components/callout";+import { Footer, POSTAL_ADDRESS } from "../emails/_components/footer";+import { KeyValue } from "../emails/_components/key-value";+import { Layout, statusPageBrand } from "../emails/_components/layout";+import { renderMarkdown } from "../emails/_components/markdown";+import { Pill } from "../emails/_components/pill";+import { Steps } from "../emails/_components/steps";+import { tones } from "../emails/_components/styles";+import MonitorAlertEmail, {+ type MonitorAlertProps,+ monitorAlertPreheader,+ monitorAlertSubject,+} from "../emails/monitor-alert";+import MonitorDeactivationEmail, {+ monitorDeactivationSubject,+} from "../emails/monitor-deactivation";+import MonitorPausedEmail from "../emails/monitor-paused";+import PageSubscriptionEmail from "../emails/page-subscription";+import PrivateLocationAlertEmail, {+ privateLocationAlertSubject,+} from "../emails/private-location-alert";+import SsoDisabledEmail from "../emails/sso-disabled";+import StatusPageMagicLinkEmail from "../emails/status-page-magic-link";+import StatusReportEmail, {+ type StatusReportProps,+ statusReportPreheader,+} from "../emails/status-report";+import TeamInvitationEmail from "../emails/team-invitation";++const alert = {+ type: "alert",+ monitorId: 42,+ name: "Ping Pong",+ url: "https://openstatus.dev/ping",+ method: "GET",+ status: "503",+ latency: "300 ms",+ region: "Amsterdam, Netherlands",+ timestamp: "2026-10-13T17:32:00Z",+ firstSeen: "2026-10-13T17:29:00Z",+ degradedAfter: 250,+ message: "upstream response time 0.302s",+} satisfies MonitorAlertProps;++const report = {+ pageTitle: "Acme",+ reportTitle: "API unavailable",+ status: "monitoring",+ date: "2026-09-18T12:37:00Z",+ reportStartedAt: "2026-09-18T10:23:00Z",+ updateIndex: 3,+ message: "We are on it.",+ pageComponents: ["API", "Runners"],+ componentImpacts: [+ { name: "API", impact: "partial_outage" },+ { name: "Runners", impact: "operational" },+ ],+ statusPageUrl: "https://acme.openstatus.dev",+ unsubscribeUrl: "https://acme.openstatus.dev/unsubscribe/t",+ manageUrl: "https://acme.openstatus.dev/manage/t",+} satisfies StatusReportProps;++describe("primitives", () => {+ test("pill maps tone to colour and uppercases its label", async () => {+ for (const tone of ["danger", "warning", "success", "neutral"] as const) {+ const html = await render(<Pill tone={tone}>down</Pill>);+ expect(html).toContain(tones[tone].text);+ expect(html).toContain(tones[tone].bg);+ expect(html).toContain("DOWN");+ }+ });++ test("key-value renders mono, tone, dot and hint", async () => {+ const html = await render(+ <KeyValue+ rows={[+ { label: "Request", value: "GET /ping", mono: true },+ {+ label: "Latency",+ value: "300 ms",+ tone: "warning",+ hint: "threshold 250 ms",+ },+ { label: "API", value: "Degraded", tone: "warning", dot: true },+ ]}+ />,+ );+ expect(html).toContain("ui-monospace");+ expect(html).toContain(tones.warning.text);+ expect(html).toContain(tones.warning.dot);+ expect(html).toContain("●");+ expect(html).toContain("threshold 250 ms");+ });++ test("key-value drops the value cell for null and undefined", async () => {+ for (const value of [null, undefined]) {+ const html = await render(<KeyValue rows={[{ label: "API", value }]} />);+ expect(html).toContain('colSpan="2"');+ expect(html).not.toContain('align="right"');+ }+ const html = await render(<KeyValue rows={[{ label: "API", value: 0 }]} />);+ expect(html).toContain('align="right"');+ });++ test("footer renders the reason, links only when given, and the address", async () => {+ const bare = await render(<Footer reason="Sent to workspace owners." />);+ expect(bare).toContain("Sent to workspace owners.");+ expect(bare).toContain(POSTAL_ADDRESS);+ expect(bare).not.toContain("Notification settings");+ expect(bare).not.toContain("Alert rule");++ const linked = await render(+ <Footer+ reason="Why."+ links={[{ label: "Unsubscribe", href: "https://x.dev/u" }]}+ />,+ );+ expect(linked).toContain('href="https://x.dev/u"');+ });++ test("footer alert-rule variant", async () => {+ const html = await render(<Footer rule="latency > 250ms" />);+ expect(html).toContain("Alert rule:");+ expect(html).toContain("latency > 250ms");+ });++ test("callout tones", async () => {+ const success = await render(+ <Callout tone="success" title="Kept">+ body+ </Callout>,+ );+ expect(success).toContain(tones.success.bg);+ const neutral = await render(<Callout title="Kept">body</Callout>);+ expect(neutral).not.toContain(tones.success.bg);+ });++ test("steps render ordered numbers or dashes", async () => {+ const ordered = await render(<Steps label="Check" items={["a", "b"]} />);+ expect(ordered).toContain(">1.<");+ expect(ordered).toContain(">2.<");+ const dashed = await render(+ <Steps label="Doing" variant="dashed" items={["a"]} />,+ );+ expect(dashed).toContain("—");+ expect(dashed).not.toContain(">1.<");+ });++ test("layout sets the preheader, hosted logo and light colour scheme", async () => {+ const html = await render(<Layout preview="Second detail.">hi</Layout>);+ expect(html).toContain("Second detail.");+ expect(html).toContain("https://www.openstatus.dev/assets/logos/");+ expect(html).toContain('name="color-scheme"');+ });++ test("status page brand appends Status once", () => {+ expect(statusPageBrand("Acme", "https://a.dev").name).toBe("Acme Status");+ expect(statusPageBrand("Acme Status", "https://a.dev").name).toBe(+ "Acme Status",+ );+ });+});++describe("markdown", () => {+ test("tables are styled, task lists render without inputs", () => {+ const html = renderMarkdown("| a |\n|--|\n| 1 |\n\n- [x] done");+ expect(html).toContain("<td style=");+ expect(html).toContain("<th style=");+ expect(html).toContain("width:100%;table-layout:fixed");+ expect(html).toContain("☑ done");+ expect(html).not.toContain("<input");+ });++ test("raw HTML is escaped, block and inline", () => {+ const html = renderMarkdown(+ '<script>alert(1)</script>\n\ntext <img src=x onerror=alert(1)> <p style="position:fixed">x</p>',+ );+ expect(html).not.toMatch(/<(script|img|p style="position)/);+ expect(html).toContain("<script>");+ expect(html).toContain("<img src=x onerror=alert(1)>");+ });++ test("quotes in a link destination cannot break out of href", () => {+ for (const source of [+ '<https://evil.com/x"onmouseover=alert(1)>',+ '[x](https://evil.com/x"onmouseover="alert(1))',+ ')',+ ]) {+ const html = renderMarkdown(source);+ expect(html).not.toMatch(/\son\w+=/);+ expect(html).toContain(""");+ }+ });++ test("only http(s) and mailto links survive; the label stays as text", () => {+ for (const source of [+ "[label](javascript:alert(1))",+ "[label](JaVaScRiPt:alert(1))",+ "[label](javascript:alert(1))",+ "[label](data:text/html,x)",+ "[label](vbscript:x)",+ "[label]: javascript:alert(1)\n\n[label]",+ ]) {+ const html = renderMarkdown(source);+ expect(html).not.toContain("<a ");+ expect(html).toContain("label");+ }+ expect(renderMarkdown("<https://a.dev/x>")).toContain(+ 'href="https://a.dev/x"',+ );+ expect(renderMarkdown("<mailto:[email protected]>")).toContain(+ 'href="mailto:[email protected]"',+ );+ });++ test("backslash-escaped backticks do not smuggle HTML", () => {+ const html = renderMarkdown("\\`<img src=x onerror=alert(1)>\\`");+ expect(html).not.toContain("<img");+ });++ test("code keeps its content readable and is escaped once", () => {+ const html = renderMarkdown('`<div class="a">` and R&D');+ expect(html).toContain("<div class="a">");+ expect(html).not.toContain("&lt;");+ expect(html).toContain("R&D");+ expect(html).not.toContain("&amp;");+ });++ test("generated tags get inline styles with a well-formed style attribute", () => {+ const html = renderMarkdown(+ "### Doing\n\n3. third\n\n- **bold**\n\n`code`",+ );+ expect(html).toMatch(/<h3 style="[^"]*text-transform:uppercase[^"]*">/);+ expect(html).toMatch(/<ol start="3" style="[^"]+">/);+ expect(html).toMatch(/<li style="[^"]+">/);+ expect(html).toMatch(/<strong style="[^"]+">bold/);+ expect(html).toMatch(/<code style="[^"]+">code<\/code>/);+ });++ test("images need https", () => {+ expect(renderMarkdown("")).toContain(+ 'src="https://a.dev/i.png"',+ );+ expect(renderMarkdown("")).not.toContain("<img");+ });+});++describe("monitor alert", () => {+ test("region count replaces the single region", async () => {+ const many = { ...alert, affectedRegions: 5, totalRegions: 6 };+ const html = await render(<MonitorAlertEmail {...many} />);+ expect(html).toContain("5/6");+ expect(html).toContain("from 5/6 regions");+ expect(monitorAlertSubject(many)).toContain("from 5/6 regions");++ const one = await render(+ <MonitorAlertEmail {...alert} affectedRegions={1} totalRegions={6} />,+ );+ expect(one).toContain("1/6");+ expect(one).toContain(`from ${alert.region}`);+ });++ test("alert", async () => {+ const html = await render(<MonitorAlertEmail {...alert} />);+ expect(html).toContain("Ping Pong is down");+ expect(html).toContain("DOWN");+ expect(html).not.toContain("retries");+ expect(html).toContain("503");+ expect(html).toContain("GET https://openstatus.dev/ping");+ expect(html).toContain("Amsterdam, Netherlands");+ expect(html).toContain("13 Oct, 17:29 UTC");+ expect(html).toContain("13 Oct, 17:32 UTC");+ expect(html).toContain("upstream response time 0.302s");+ expect(html).toContain('href="https://app.openstatus.dev/monitors/42"');+ expect(html).toContain(+ 'href="https://app.openstatus.dev/monitors/42/edit"',+ );+ expect(html).not.toContain("Alert rule");+ });++ test("degraded shows the threshold and the rule footer", async () => {+ const html = await render(+ <MonitorAlertEmail {...alert} type="degraded" status="200" />,+ );+ expect(html).toContain("Ping Pong is answering slowly");+ expect(html).toContain("DEGRADED");+ expect(html).toContain("threshold 250 ms");+ expect(html).toContain("latency > 250ms");+ expect(html).toContain("Edit rule");+ expect(html).toContain("still returning 200");+ });++ test("recovery", async () => {+ const html = await render(+ <MonitorAlertEmail {...alert} type="recovery" message={undefined} />,+ );+ expect(html).toContain("Ping Pong is back up");+ expect(html).toContain("RECOVERED");+ expect(html).not.toContain("upstream response time");+ });++ test("optional rows disappear (TCP monitor, no incident)", async () => {+ const html = await render(+ <MonitorAlertEmail type="alert" name="TCP" latency="N/A" region="N/A" />,+ );+ expect(html).not.toContain("Response");+ expect(html).not.toContain("Latency");+ expect(html).not.toContain("First seen");+ expect(html).not.toContain("Edit notifications");+ expect(html).toContain('href="https://app.openstatus.dev/monitors"');+ });++ test("long messages are truncated", async () => {+ const html = await render(+ <MonitorAlertEmail {...alert} message={"x".repeat(600)} />,+ );+ expect(html).toContain(`${"x".repeat(400)}…`);+ expect(html).not.toContain("x".repeat(401));+ });++ test("subject and preheader", () => {+ expect(monitorAlertSubject(alert)).toBe(+ "Ping Pong is down — status 503 from Amsterdam, Netherlands",+ );+ expect(monitorAlertSubject({ ...alert, type: "degraded" })).toBe(+ "Ping Pong is slow — 300 ms from Amsterdam, Netherlands",+ );+ expect(monitorAlertSubject({ ...alert, type: "recovery" })).toBe(+ "Ping Pong recovered — 300 ms from Amsterdam, Netherlands",+ );+ expect(monitorAlertSubject({ type: "alert", region: "N/A" })).toBe(+ "Your monitor is down — check failed",+ );+ expect(monitorAlertPreheader({ ...alert, type: "degraded" })).toBe(+ "Above your 250 ms threshold.",+ );+ for (const type of ["alert", "degraded", "recovery"] as const) {+ const props = { ...alert, type };+ expect(monitorAlertPreheader(props)).not.toBe(monitorAlertSubject(props));+ }+ });+});++describe("private location alert", () => {+ const base = {+ locationName: "eu-west-private",+ lastSeenAt: "2026-07-23T10:00:00Z",+ };++ test("error shows the checklist and skipped monitors", async () => {+ const html = await render(+ <PrivateLocationAlertEmail {...base} status="error" monitorCount={4} />,+ );+ expect(html).toContain("UNHEALTHY");+ expect(html).toContain("eu-west-private");+ expect(html).toContain("are paused");+ expect(html).toContain("23 Jul, 10:00 UTC");+ expect(html).toContain("Checks skipped");+ expect(html).toContain("4 monitors");+ expect(html).toContain("Check, in this order");+ expect(html).toContain("you are a member of this workspace");+ expect(html).toContain("/settings/private-locations");+ });++ test("recovered drops the checklist; no monitors drops the row", async () => {+ const html = await render(+ <PrivateLocationAlertEmail {...base} status="recovered" />,+ );+ expect(html).toContain("RECOVERED");+ expect(html).toContain("are running again");+ expect(html).not.toContain("Check, in this order");+ expect(html).not.toContain("Checks resumed");+ });++ test("subject", () => {+ expect(privateLocationAlertSubject({ ...base, status: "error" })).toBe(+ 'Checks paused — "eu-west-private" stopped reporting',+ );+ expect(privateLocationAlertSubject({ ...base, status: "recovered" })).toBe(+ 'Checks resumed — "eu-west-private" is reporting again',+ );+ });+});++describe("status report", () => {+ test("eyebrow, components, markdown, links", async () => {+ const html = await render(<StatusReportEmail {...report} />);+ expect(html).toContain("Acme Status");+ expect(html).toContain("MONITORING");+ expect(html).toContain("Update 3 · 18 Sep, 12:37 UTC · 2h 14m in");+ expect(html).toContain("API unavailable");+ expect(html).toContain("Runners");+ expect(html).toContain("Partial outage");+ expect(html).toContain("Operational");+ expect(html).not.toContain("●");+ expect(html).toContain("We are on it.");+ expect(html).toContain('href="https://acme.openstatus.dev"');+ expect(html).toContain(`href="${report.unsubscribeUrl}"`);+ expect(html).toContain(`href="${report.manageUrl}"`);+ expect(html).not.toContain("openstatus.dev/assets/logos");+ });++ test("pill uses the status enum verbatim, one tone per status", async () => {+ const expected = {+ investigating: tones.danger,+ identified: tones.warning,+ monitoring: tones.info,+ resolved: tones.success,+ maintenance: tones.info,+ };+ for (const [status, tone] of Object.entries(expected)) {+ const html = await render(+ <StatusReportEmail+ {...report}+ status={status as StatusReportProps["status"]}+ />,+ );+ expect(html).toContain(status.toUpperCase());+ expect(html).toContain(tone.bg);+ }+ });++ test("unknown impact drops the value cell", async () => {+ const html = await render(+ <StatusReportEmail {...report} componentImpacts={undefined} />,+ );+ expect(html).toContain("Runners");+ expect(html).toContain('colSpan="2"');+ expect(html).not.toContain("Operational");+ expect(html).not.toContain("Partial outage");+ });++ test("optional blocks disappear", async () => {+ const html = await render(+ <StatusReportEmail+ {...report}+ pageComponents={[]}+ statusPageUrl={undefined}+ updateIndex={undefined}+ reportStartedAt={undefined}+ />,+ );+ expect(html).not.toContain("Update 3");+ expect(html).not.toContain("2h 14m in");+ expect(html).not.toContain("Follow on the status page");+ expect(html).not.toContain("●");+ });++ test("maintenance renders its window instead of a timestamp", async () => {+ const html = await render(+ <StatusReportEmail+ {...report}+ status="maintenance"+ date="Mon 21 Sep, 10:00 - 12:00"+ />,+ );+ expect(html).toContain("MAINTENANCE");+ expect(html).toContain("Window");+ expect(html).toContain("Mon 21 Sep, 10:00 - 12:00");+ });++ test("markdown headings and lists are styled, raw HTML is escaped", async () => {+ const html = await render(+ <StatusReportEmail+ {...report}+ message={+ "### What we're doing\n\n- Retrying\n\n<script>alert(1)</script><img src=x onerror=alert(1)>"+ }+ />,+ );+ expect(html).toMatch(/<h3 style="[^"]*text-transform:\s?uppercase/);+ expect(html).toMatch(/<li style="/);+ expect(html).not.toContain("<script>");+ expect(html).not.toContain("<img src=x");+ expect(html).toContain("<script>");+ });++ test("a crafted autolink cannot inject an attribute into the email", async () => {+ const html = await render(+ <StatusReportEmail+ {...report}+ message={+ '<https://evil.com/x"onmouseover=alert(1)> [x](javascript:alert(1))'+ }+ />,+ );+ expect(html).not.toMatch(/\sonmouseover=/);+ expect(html).not.toContain("javascript:");+ expect(html).toContain(+ 'href="https://evil.com/x"onmouseover=alert(1)"',+ );+ });++ test("autolinks and entities in the message survive escaping", async () => {+ const html = await render(+ <StatusReportEmail+ {...report}+ message="See <https://status.acme.dev/x> — R&D"+ />,+ );+ expect(html).toContain('href="https://status.acme.dev/x"');+ expect(html).toContain("R&D");+ expect(html).not.toContain("&amp;");+ });++ test("maintenance without eyebrow items renders no empty eyebrow", async () => {+ const html = await render(+ <StatusReportEmail+ {...report}+ status="maintenance"+ date="Mon 21 Sep, 10:00 - 12:00"+ updateIndex={undefined}+ reportStartedAt={undefined}+ />,+ );+ expect(html).not.toMatch(/<p[^>]*letter-spacing:0\.12em[^>]*><\/p>/);+ });++ test("preheader never repeats the subject", () => {+ expect(statusReportPreheader(report)).toBe("Monitoring: API, Runners.");+ expect(statusReportPreheader({ ...report, status: "resolved" })).toBe(+ "Resolved for API, Runners.",+ );+ expect(+ statusReportPreheader({ ...report, pageComponents: [] }),+ ).not.toContain(report.reportTitle);+ });+});++describe("inactivity pause", () => {+ test("warning carries count, workspace, last sign-in, pause date and signature", async () => {+ const html = await render(+ <MonitorDeactivationEmail+ deactivateAt={new Date("2026-09-25T00:00:00Z")}+ monitorCount={3}+ workspaceSlug="acme-dev"+ lastSignIn={new Date("2026-07-21T00:00:00Z")}+ />,+ );+ expect(html).toContain("ACTION NEEDED");+ expect(html).toContain("3 monitors will pause on Friday 25 September");+ expect(html).toContain("Nothing gets deleted");+ expect(html).toContain("acme-dev");+ expect(html).toContain("Tue 21 Jul 2026");+ expect(html).toContain("Fri 25 Sep 2026");+ expect(html).toContain("Thibault");+ expect(html).toContain("Co-founder, openstatus");+ });++ test("warning without context falls back and drops the rows", async () => {+ const html = await render(+ <MonitorDeactivationEmail+ deactivateAt={new Date("2026-09-25T00:00:00Z")}+ />,+ );+ expect(html).toContain("Your monitors will pause on");+ expect(html).not.toContain("Workspace");+ expect(html).not.toContain("Last sign-in");+ });++ test("singular monitor", async () => {+ const html = await render(<MonitorPausedEmail monitorCount={1} />);+ expect(html).toContain("1 monitor has been paused");+ });++ test("paused", async () => {+ const html = await render(+ <MonitorPausedEmail monitorCount={3} workspaceSlug="acme-dev" />,+ );+ expect(html).toContain("3 monitors have been paused");+ expect(html).toContain("Nothing was deleted");+ expect(html).toContain("acme-dev");+ const bare = await render(<MonitorPausedEmail />);+ expect(bare).toContain("Your monitors have been paused");+ expect(bare).not.toContain("Workspace");+ });++ test("subject", () => {+ expect(+ monitorDeactivationSubject({+ deactivateAt: new Date("2026-09-25T00:00:00Z"),+ }),+ ).toBe("Your monitors pause on 25 Sep — one sign-in stops it");+ });+});++describe("account and status page mail", () => {+ test("sso disabled never claims nobody lost access", async () => {+ const html = await render(<SsoDisabledEmail />);+ expect(html).toContain("ACCOUNT CHANGE");+ expect(html).toContain("IdP configuration");+ expect(html).not.toContain("Nobody lost access");+ expect(html).not.toContain("Nobody has lost access");+ });++ test("team invitation", async () => {+ const html = await render(+ <TeamInvitationEmail+ token="tok"+ workspaceName="acme"+ invitedBy="[email protected]"+ />,+ );+ expect(html).toContain("Join acme on openstatus");+ expect(html).toContain("[email protected]");+ expect(html).toContain(+ 'href="https://app.openstatus.dev/invite?token=tok"',+ );+ });++ test("page subscription uses the page brand and logo", async () => {+ const html = await render(+ <PageSubscriptionEmail+ page="Acme"+ link="https://acme.openstatus.dev/verify/t"+ img={{+ src: "https://acme.dev/logo.png",+ alt: "",+ href: "https://acme.dev",+ }}+ />,+ );+ expect(html).toContain("Acme Status");+ expect(html).toContain("https://acme.dev/logo.png");+ expect(html).toContain('href="https://acme.openstatus.dev/verify/t"');+ expect(html).not.toContain("every status report");+ });++ test("one-time links appear once, on the CTA only", async () => {+ const link = "https://acme.openstatus.dev/verify/t";+ for (const el of [+ <PageSubscriptionEmail key="s" page="Acme" link={link} />,+ <StatusPageMagicLinkEmail key="m" page="Acme" link={link} />,+ ]) {+ const html = await render(el);+ expect(html.split(`href="${link}"`).length - 1).toBe(1);+ expect(html).toContain('href="https://acme.openstatus.dev"');+ }+ });++ test("team invitation falls back on an empty workspace name", async () => {+ const html = await render(+ <TeamInvitationEmail token="t" workspaceName="" invitedBy="[email protected]" />,+ );+ expect(html).toContain("Join openstatus");+ expect(html).not.toContain("on openstatus");+ expect(html).not.toContain("Workspace");+ });++ test("magic link", async () => {+ const html = await render(+ <StatusPageMagicLinkEmail+ page="Acme"+ link="https://acme.openstatus.dev/verify/t"+ />,+ );+ expect(html).toContain("Sign in to Acme");+ expect(html).toContain("24 hours");+ expect(html).toContain('href="https://acme.openstatus.dev/verify/t"');+ });+});++describe("every transactional template", () => {+ const all = {+ alert: <MonitorAlertEmail {...alert} />,+ degraded: <MonitorAlertEmail {...alert} type="degraded" />,+ recovery: <MonitorAlertEmail {...alert} type="recovery" />,+ privateLocation: (+ <PrivateLocationAlertEmail+ locationName="a"+ status="error"+ lastSeenAt="2026-07-23T10:00:00Z"+ />+ ),+ statusReport: <StatusReportEmail {...report} />,+ deactivation: (+ <MonitorDeactivationEmail deactivateAt={new Date("2026-09-25")} />+ ),+ paused: <MonitorPausedEmail />,+ sso: <SsoDisabledEmail />,+ invitation: <TeamInvitationEmail token="t" invitedBy="[email protected]" />,+ subscription: <PageSubscriptionEmail page="Acme" link="https://a.dev" />,+ magicLink: <StatusPageMagicLinkEmail page="Acme" link="https://a.dev" />,+ };++ for (const [name, element] of Object.entries(all)) {+ test(`${name}: brand casing, no SVG data URIs, no flex/grid, 600px`, async () => {+ const html = await render(element);+ expect(html).not.toContain("OpenStatus<");+ expect(html).not.toMatch(/>[^<]*OpenStatus[^<]*</);+ expect(html).not.toContain("data:image/svg");+ expect(html).not.toMatch(/display:\s?(-webkit-)?(inline-)?(flex|grid)/);+ expect(html).toContain("max-width:600px");+ expect(html).toContain(POSTAL_ADDRESS);+ });+ }+});diff --git a/packages/notifications/email/src/index.test.ts b/packages/notifications/email/src/index.test.tsindex 7ea2c2a0d..d567dc17e 100644--- a/packages/notifications/email/src/index.test.ts+++ b/packages/notifications/email/src/index.test.ts@@ -74,7 +74,8 @@ describe("Email Notifications", () => {expect(callArgs.to).toBe("[email protected]");expect(callArgs.url).toBe("https://api.example.com/health");expect(callArgs.status).toBe("500");- expect(callArgs.latency).toBe("1500ms");+ expect(callArgs.latency).toBe("1500 ms");+ expect(callArgs.monitorId).toBe("monitor-1");expect(callArgs.region).toBe("Ashburn, Virginia, USA");expect(callArgs.message).toBe("Something went wrong");expect(callArgs.timestamp).toBeDefined();@@ -122,7 +123,7 @@ describe("Email Notifications", () => {expect(callArgs.name).toBe("API Health Check");expect(callArgs.to).toBe("[email protected]");expect(callArgs.status).toBe("200");- expect(callArgs.latency).toBe("100ms");+ expect(callArgs.latency).toBe("100 ms");expect(callArgs.region).toBe("Amsterdam, Netherlands");});@@ -147,10 +148,34 @@ describe("Email Notifications", () => {expect(callArgs.type).toBe("degraded");expect(callArgs.name).toBe("API Health Check");expect(callArgs.status).toBe("503");- expect(callArgs.latency).toBe("2000ms");+ expect(callArgs.latency).toBe("2000 ms");expect(callArgs.region).toBe("Los Angeles, California, USA");});+ test("Send Degraded passes the threshold and incident start", async () => {+ const monitor = { ...createMockMonitor(), degradedAfter: 250 };+ const notification = selectNotificationSchema.parse(+ createMockNotification(),+ );+ const startedAt = new Date("2026-10-13T17:29:00Z");++ await sendDegraded({+ // @ts-expect-error+ monitor,+ notification,+ latency: 300,+ regions: ["ams"],+ cronTimestamp: Date.now(),+ // @ts-expect-error+ incident: { startedAt },+ });++ assertSpyCalls(sendMonitorAlertMock, 1);+ const callArgs = sendMonitorAlertMock.calls[0].args[0];+ expect(callArgs.degradedAfter).toBe(250);+ expect(callArgs.firstSeen).toBe(startedAt.toISOString());+ });+test("Handles invalid notification data gracefully", async () => {const monitor = createMockMonitor();const invalidNotification = selectNotificationSchema.parse({diff --git a/packages/notifications/email/src/index.ts b/packages/notifications/email/src/index.tsindex 8e6a78fa4..6c978698e 100644--- a/packages/notifications/email/src/index.ts+++ b/packages/notifications/email/src/index.ts@@ -14,6 +14,7 @@ export const sendAlert = async ({cronTimestamp,latency,regions,+ incident,}: NotificationContext) => {// Convert regions array to single region for backwards compatibilityconst region = regions?.[0] as Region | undefined;@@ -24,13 +25,20 @@ export const sendAlert = async ({if (!config.success) return;await emailClient.sendMonitorAlert({+ monitorId: monitor.id,name: monitor.name,type: "alert",+ method:+ monitor.jobType === "http" ? (monitor.method ?? undefined) : undefined,+ degradedAfter: monitor.degradedAfter ?? undefined,+ firstSeen: incident?.startedAt?.toISOString(),to: config.data.email,url: monitor.url,status: statusCode?.toString(),- latency: latency ? `${latency}ms` : "N/A",+ latency: latency ? `${latency} ms` : "N/A",region: region ? regionDict[region].location : "N/A",+ affectedRegions: regions?.length,+ totalRegions: monitor.regions?.length,timestamp: new Date(cronTimestamp).toISOString(),message,});@@ -43,6 +51,7 @@ export const sendRecovery = async ({cronTimestamp,regions,latency,+ incident,}: NotificationContext) => {// Convert regions array to single region for backwards compatibilityconst region = regions?.[0] as Region | undefined;@@ -53,13 +62,20 @@ export const sendRecovery = async ({if (!config.success) return;await emailClient.sendMonitorAlert({+ monitorId: monitor.id,name: monitor.name,type: "recovery",+ method:+ monitor.jobType === "http" ? (monitor.method ?? undefined) : undefined,+ degradedAfter: monitor.degradedAfter ?? undefined,+ firstSeen: incident?.startedAt?.toISOString(),to: config.data.email,url: monitor.url,status: statusCode?.toString(),- latency: latency ? `${latency}ms` : "N/A",+ latency: latency ? `${latency} ms` : "N/A",region: region ? regionDict[region].location : "N/A",+ affectedRegions: regions?.length,+ totalRegions: monitor.regions?.length,timestamp: new Date(cronTimestamp).toISOString(),});};@@ -71,6 +87,7 @@ export const sendDegraded = async ({cronTimestamp,regions,latency,+ incident,}: NotificationContext) => {// Convert regions array to single region for backwards compatibilityconst region = regions?.[0] as Region | undefined;@@ -81,13 +98,20 @@ export const sendDegraded = async ({if (!config.success) return;await emailClient.sendMonitorAlert({+ monitorId: monitor.id,name: monitor.name,type: "degraded",+ method:+ monitor.jobType === "http" ? (monitor.method ?? undefined) : undefined,+ degradedAfter: monitor.degradedAfter ?? undefined,+ firstSeen: incident?.startedAt?.toISOString(),to: config.data.email,url: monitor.url,status: statusCode?.toString(),- latency: latency ? `${latency}ms` : "N/A",+ latency: latency ? `${latency} ms` : "N/A",region: region ? regionDict[region].location : "N/A",+ affectedRegions: regions?.length,+ totalRegions: monitor.regions?.length,timestamp: new Date(cronTimestamp).toISOString(),});};diff --git a/packages/subscriptions/src/channels/email.ts b/packages/subscriptions/src/channels/email.tsindex 79510a97b..ae4dfeecb 100644--- a/packages/subscriptions/src/channels/email.ts+++ b/packages/subscriptions/src/channels/email.ts@@ -95,6 +95,7 @@ export async function sendEmailNotifications(pageUpdate.message,pageUpdate.date,pageUpdate.pageComponents,+ pageUpdate.componentsWithImpact?.map((c) => c.impact),]),);@@ -112,6 +113,7 @@ export async function sendEmailNotifications(message: pageUpdate.message,date: pageUpdate.date,pageComponents: pageUpdate.pageComponents,+ componentImpacts: pageUpdate.componentsWithImpact,idempotencyKey: `${idempotencyKeyFor(pageUpdate)}:${payloadHash}`,});}diff --git a/packages/subscriptions/src/dispatcher.test.ts b/packages/subscriptions/src/dispatcher.test.tsindex 999fa835f..1da6e3ee3 100644--- a/packages/subscriptions/src/dispatcher.test.ts+++ b/packages/subscriptions/src/dispatcher.test.ts@@ -3,6 +3,10 @@ import { db, eq } from "@openstatus/db";import {pageSubscriber,pageSubscriberToPageComponent,+ statusReport,+ statusReportUpdate,+ statusReportUpdateToPageComponents,+ statusReportsToPageComponents,} from "@openstatus/db/src/schema";import {createPage,@@ -21,7 +25,7 @@ import {} from "@std/testing/bdd";import { assertSpyCalls, type Stub, stub } from "@std/testing/mock";-import { dispatchPageUpdate } from "./dispatcher";+import { dispatchPageUpdate, dispatchStatusReportUpdate } from "./dispatcher";import type { PageUpdate } from "./types";// RESEND_API_KEY is set in test-preload.ts (see bunfig.toml) so @openstatus/emails@@ -226,3 +230,65 @@ describe("dispatchPageUpdate - edge cases", () => {).resolves.toBeUndefined();});});++// ─── dispatchStatusReportUpdate - impacts ─────────────────────────────────────++describe("dispatchStatusReportUpdate - impacts", () => {+ test("an earlier update is sent with the impacts as of that update", async () => {+ const report = await db+ .insert(statusReport)+ .values({+ status: "investigating",+ title: "Late dispatch",+ pageId: PAGE_ID,+ })+ .returning()+ .get();+ await db+ .insert(statusReportsToPageComponents)+ .values({ statusReportId: report.id, pageComponentId: COMPONENT_1 })+ .run();++ const insertUpdate = async (+ date: Date,+ impact: "major_outage" | "operational",+ ) => {+ const update = await db+ .insert(statusReportUpdate)+ .values({+ status: "investigating",+ date,+ message: "msg",+ statusReportId: report.id,+ })+ .returning()+ .get();+ await db+ .insert(statusReportUpdateToPageComponents)+ .values({+ statusReportUpdateId: update.id,+ pageComponentId: COMPONENT_1,+ impact,+ })+ .run();+ return update;+ };++ const earlier = await insertUpdate(+ new Date("2026-01-01T10:00:00Z"),+ "major_outage",+ );+ await insertUpdate(new Date("2026-01-01T11:00:00Z"), "operational");++ try {+ await dispatchStatusReportUpdate(earlier.id);+ assertSpyCalls(sendStatusReportUpdateMock, 1);+ const args = sendStatusReportUpdateMock.calls[0].args[0];+ expect(+ args.componentImpacts.map((c: { impact: string }) => c.impact),+ ).toEqual(["major_outage"]);+ } finally {+ await db.delete(statusReport).where(eq(statusReport.id, report.id));+ }+ });+});diff --git a/packages/subscriptions/src/dispatcher.ts b/packages/subscriptions/src/dispatcher.tsindex 4186c8be7..f50f806a6 100644--- a/packages/subscriptions/src/dispatcher.ts+++ b/packages/subscriptions/src/dispatcher.ts@@ -47,18 +47,25 @@ export async function dispatchStatusReportUpdate(statusReportUpdateId: number) {(i) => i.pageComponent,);+ // impacts as of this update: a late dispatch must not show later updatesconst currentImpacts = currentImpactsFromUpdates(- update.statusReport.statusReportUpdates.map((u) => ({- id: u.id,- date: u.date,- componentImpacts: u.statusReportUpdateToPageComponents,- })),+ update.statusReport.statusReportUpdates+ .filter((u) => u.date.getTime() <= update.date.getTime())+ .map((u) => ({+ id: u.id,+ date: u.date,+ componentImpacts: u.statusReportUpdateToPageComponents,+ })),);- const componentsWithImpact = pageComponents.map((c) => ({- id: c.id,- name: c.name,- impact: currentImpacts.get(c.id) ?? "operational",- }));+ // legacy report (no impact rows): channels fall back to bare names+ const componentsWithImpact =+ currentImpacts.size > 0+ ? pageComponents.map((c) => ({+ id: c.id,+ name: c.name,+ impact: currentImpacts.get(c.id) ?? ("operational" as const),+ }))+ : undefined;await dispatchPageUpdate({id: update.statusReport.id,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 88d09c676..acaf9c0f7 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -494,6 +494,9 @@ catalogs:lucide-react:specifier: 0.525.0version: 0.525.0+ marked:+ specifier: 15.0.12+ version: 15.0.12nanoid:specifier: 5.1.11version: 5.1.11@@ -2220,6 +2223,9 @@ importers:effect:specifier: 'catalog:'version: 4.0.0-rc.112+ marked:+ specifier: 'catalog:'+ version: 15.0.12react:specifier: 'catalog:'version: 19.2.6diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex ab5572376..c13fa6ff4 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -176,6 +176,7 @@ catalog:knip: 5.88.1limiter: 3.0.0lucide-react: 0.525.0+ marked: 15.0.12nanoid: 5.1.11nanoid-dictionary: 5.0.0next: 16.3.0