Open-source status page, incident response and uptime monitoring
TypeScript alertingincident-managementmcpmcp-servermonitoringmonitoring-as-codeobservabilityon-callopen-sourcesrestatus-pagestatuspagesynthetic-monitoringterraformtinybirdtursouptimeuptime-checkeruptime-monitor
/** @jsxRuntime automatic @jsxImportSource react */
import "./test-preload.ts";
import { render } from "react-email";
import {
afterEach,
beforeEach,
describe,
expect,
test,
vi,
type MockInstance,
} from "vitest";
import type { PlanLoss } from "../emails/_components/plan-loss";
import CancellationScheduledEmail from "../emails/cancellation-scheduled";
import MemberAccessEndingEmail, {
memberAccessEndingSubject,
} from "../emails/member-access-ending";
import MemberRemovedEmail from "../emails/member-removed";
import OwnershipTransferredEmail from "../emails/ownership-transferred";
import PlanDowngradedEmail, {
planDowngradedSubject,
} from "../emails/plan-downgraded";
import PlanEndingSoonEmail, {
planEndingSoonSubject,
} from "../emails/plan-ending-soon";
import TrialEndingEmail, { trialEndingSubject } from "../emails/trial-ending";
import {
billingRecipients,
planLossLines,
reminderScheduledAt,
scheduleMemberAccessEnding,
schedulePlanEndingSoon,
sendCancellationScheduled,
sendMemberRemoved,
sendOwnershipTransferred,
sendPlanDowngraded,
sendTrialEnding,
} from "./billing";
import { cancelScheduledEmail, delivery, resend, sendEmail } from "./send";
const loss = {
monitorsDeactivated: 11,
pagesDeleted: ["Acme API", "Acme EU"],
keptPageTitle: "Acme",
notificationsDeleted: 3,
invitationsDeleted: 1,
membersRemoved: 4,
customDomains: ["status.acme.dev"],
sso: true,
} satisfies PlanLoss;
const nothing = {
monitorsDeactivated: 0,
pagesDeleted: [],
keptPageTitle: null,
notificationsDeleted: 0,
invitationsDeleted: 0,
membersRemoved: 0,
customDomains: [],
sso: false,
} satisfies PlanLoss;
const endsAt = new Date("2026-09-25T00:00:00Z");
describe("billing templates", () => {
test("plan-downgraded names deleted pages and counts everything else", async () => {
const props = { workspaceSlug: "acme-dev", previousPlan: "team", loss };
const html = await render(<PlanDowngradedEmail {...props} />);
expect(html).toContain("ACCOUNT CHANGE");
expect(html).toContain("acme-dev");
expect(html).toContain("team → free");
expect(html).toContain("Acme API, Acme EU");
expect(html).toContain("Deleted status pages cannot be restored");
expect(html).toContain("11 monitors, oldest stays active");
expect(html).toContain("4 members");
expect(html).toContain("status.acme.dev");
expect(html).toContain("Off, IdP configuration kept");
expect(html).toContain("workspace owners and the billing contact");
expect(html).toContain("Co-founder, openstatus");
expect(html).toContain(
'href="https://app.openstatus.dev/settings/billing"',
);
expect(planDowngradedSubject(props)).toBe(
"Your workspace is on the free plan — 2 status pages deleted",
);
});
test("plan-downgraded with nothing trimmed drops every loss row", async () => {
const props = {
workspaceSlug: "acme-dev",
previousPlan: "starter",
loss: nothing,
};
const html = await render(<PlanDowngradedEmail {...props} />);
expect(html).toContain("No status page was deleted");
expect(html).not.toContain("Status pages deleted");
expect(html).not.toContain("Members removed");
expect(html).not.toContain("SAML SSO");
expect(planDowngradedSubject(props)).toBe(
"Your workspace is on the free plan — here is what changed",
);
});
test("plan-downgraded after a trial says trial and offers upgrade", async () => {
const props = {
workspaceSlug: "acme-dev",
previousPlan: "team",
loss,
reason: "trial_ended" as const,
};
const html = await render(<PlanDowngradedEmail {...props} />);
expect(html).toContain("TRIAL");
expect(html).toContain("team trial ended without a payment method");
expect(html).toContain("team trial → free");
expect(html).toContain("Upgrade");
expect(html).not.toContain("subscription ended");
expect(html).not.toContain("Re-subscribe");
expect(planDowngradedSubject(props)).toBe(
"Your trial ended — 2 status pages deleted",
);
const cancelled = await render(
<PlanDowngradedEmail {...props} reason="trial_cancelled" />,
);
expect(cancelled).toContain("You cancelled your team trial");
});
test("plan-ending-soon is dated and in the future tense", async () => {
const props = { workspaceSlug: "acme-dev", plan: "team", endsAt, loss };
const html = await render(<PlanEndingSoonEmail {...props} />);
expect(html).toContain("ACTION NEEDED");
expect(html).toContain("Your team plan ends on Friday 25 September");
expect(html).toContain("Fri 25 Sep 2026");
expect(html).toContain("Status pages that get deleted");
expect(html).toContain("Resume subscription");
expect(planEndingSoonSubject(props)).toBe(
"Your team plan ends on 25 Sep — resume to keep everything",
);
});
test("member-access-ending: dated, names owners, trial vs cancellation", async () => {
const props = {
workspaceName: "Acme",
plan: "team",
endsAt,
reason: "cancellation" as const,
owners: ["[email protected]", "[email protected]"],
};
const html = await render(<MemberAccessEndingEmail {...props} />);
expect(html).toContain("HEADS UP");
expect(html).toContain("You lose access to Acme on Friday 25 September");
expect(html).toContain("team subscription is cancelled");
expect(html).toContain("Fri 25 Sep 2026");
expect(html).toContain("[email protected], [email protected]");
expect(html).toContain("you are a member of this workspace");
expect(memberAccessEndingSubject(props)).toBe(
"Your access to Acme on openstatus ends on 25 Sep",
);
const trial = await render(
<MemberAccessEndingEmail {...props} reason="trial" owners={[]} />,
);
expect(trial).toContain("team trial ends without a payment method");
expect(trial).toContain("Ask a workspace owner");
expect(trial).not.toContain("Ask to keep it");
});
test("member-removed: one line, who to ask, no CTA", async () => {
const html = await render(
<MemberRemovedEmail
workspaceName="Acme"
reason="downgrade"
owners={["[email protected]"]}
/>,
);
expect(html).toContain("You were removed from Acme");
expect(html).toContain("subscription ended");
expect(html).toContain("[email protected]");
expect(html).not.toContain("app.openstatus.dev");
const manual = await render(
<MemberRemovedEmail workspaceName="Acme" reason="manual" owners={[]} />,
);
expect(manual).toContain("A workspace owner removed you");
expect(manual).not.toContain("Ask for access");
});
test("ownership-transferred: copy per recipient", async () => {
const props = {
workspaceName: "Acme",
newOwner: "[email protected]",
formerOwner: "[email protected]",
};
const toNew = await render(
<OwnershipTransferredEmail {...props} recipient="new" />,
);
expect(toNew).toContain("You are now the owner of Acme");
expect(toNew).toContain("Transferred by");
expect(toNew).toContain("[email protected]");
const toFormer = await render(
<OwnershipTransferredEmail {...props} recipient="former" />,
);
expect(toFormer).toContain("You transferred ownership of Acme");
expect(toFormer).toContain("you are a member");
expect(toFormer).toContain("[email protected]");
});
test("cancellation-scheduled is raw: no layout, date, losses, resume link", async () => {
const html = await render(
<CancellationScheduledEmail
plan="team"
endsAt={endsAt}
losses={planLossLines(loss)}
/>,
);
expect(html).toContain("Fri 25 Sep 2026");
expect(html).toContain("2 status pages get deleted (Acme API, Acme EU)");
expect(html).toContain("4 members lose access");
expect(html).toContain("what made you cancel?");
expect(html).toContain(
'href="https://app.openstatus.dev/settings/billing"',
);
expect(html).not.toContain("max-width:600px");
const bare = await render(
<CancellationScheduledEmail plan="team" endsAt={endsAt} losses={[]} />,
);
expect(bare).not.toContain("moves to the free plan");
});
test("trial-ending without a card lists what gets removed", async () => {
const props = {
workspaceSlug: "acme-dev",
plan: "starter",
trialEnd: endsAt,
hasPaymentMethod: false,
loss,
};
const html = await render(<TrialEndingEmail {...props} />);
expect(trialEndingSubject(props)).toBe(
"Your trial ends on 25 Sep — add a payment method to keep starter",
);
expect(html).toContain("ACTION NEEDED");
expect(html).toContain("Your trial ends on Friday 25 September");
expect(html).toContain("acme-dev");
expect(html).toContain("starter → free");
expect(html).toContain("Acme API, Acme EU");
expect(html).toContain("Add payment method");
expect(html).not.toContain("on file, so");
});
test("trial-ending with a card says the plan continues", async () => {
const props = {
workspaceSlug: "acme-dev",
plan: "starter",
trialEnd: endsAt,
hasPaymentMethod: true,
loss,
};
const html = await render(<TrialEndingEmail {...props} />);
expect(trialEndingSubject(props)).toBe(
"Your trial ends on 25 Sep — your starter plan continues",
);
expect(html).toContain("Nothing to do");
expect(html).toContain("starter, continues");
expect(html).toContain("Manage subscription");
expect(html).not.toContain("Acme API, Acme EU");
expect(html).not.toContain("Add payment method");
});
test("trial-ending without a card and nothing to trim", async () => {
const html = await render(
<TrialEndingEmail
workspaceSlug="acme-dev"
plan="starter"
trialEnd={endsAt}
hasPaymentMethod={false}
loss={nothing}
/>,
);
expect(html).toContain("free plan on that day.");
expect(html).not.toContain("trimmed");
});
test("loss lines use singular forms", () => {
expect(
planLossLines({
...nothing,
pagesDeleted: ["A"],
monitorsDeactivated: 1,
membersRemoved: 1,
}),
).toEqual([
"1 status page gets deleted (A)",
"1 monitor gets paused",
"1 member loses access",
]);
});
test("loss lines cover every destructive change", () => {
expect(
planLossLines({
...nothing,
invitationsDeleted: 2,
notificationsDeleted: 1,
customDomains: ["a.dev", "b.dev"],
sso: true,
}),
).toEqual([
"2 pending invitations get deleted",
"1 notification channel gets removed",
"the custom domains a.dev, b.dev are released",
"SAML SSO turns off",
]);
});
test("custom domain label follows the count", async () => {
const one = await render(
<PlanDowngradedEmail
workspaceSlug="a"
previousPlan="team"
loss={{ ...nothing, customDomains: ["a.dev"] }}
/>,
);
expect(one).toContain("Custom domain released");
const two = await render(
<PlanDowngradedEmail
workspaceSlug="a"
previousPlan="team"
loss={{ ...nothing, customDomains: ["a.dev", "b.dev"] }}
/>,
);
expect(two).toContain("Custom domains released");
});
});
describe("billingRecipients", () => {
test("owners + customer, case-insensitive dedupe, empties dropped", () => {
expect(
billingRecipients(
["[email protected]", "", null, " ", "[email protected]"],
"[email protected]",
),
).toEqual(["[email protected]", "[email protected]"]);
expect(billingRecipients([], "[email protected]")).toEqual([
"[email protected]",
]);
expect(billingRecipients([undefined], null)).toEqual([]);
});
});
describe("reminderScheduledAt", () => {
const now = new Date("2026-09-01T00:00:00Z");
test("period end minus 3 days", () => {
expect(reminderScheduledAt(endsAt, now)?.toISOString()).toBe(
"2026-09-22T00:00:00.000Z",
);
});
test("null inside the lead window and beyond Resend's 30 days", () => {
expect(reminderScheduledAt(new Date("2026-09-03T00:00:00Z"), now)).toBe(
null,
);
expect(reminderScheduledAt(new Date("2027-03-01T00:00:00Z"), now)).toBe(
null,
);
});
});
describe("send plumbing", () => {
let send: MockInstance,
batch: MockInstance,
cancel: MockInstance,
enabled: MockInstance;
// safe because the verbs only read `data.id` and `error.name`
const result = (value: unknown) => Promise.resolve(value as never);
const ok = { data: { id: "email_123" }, error: null };
beforeEach(() => {
enabled = vi.spyOn(delivery, "enabled").mockImplementation(() => true);
send = vi.spyOn(resend.emails, "send").mockImplementation(() => result(ok));
batch = vi.spyOn(resend.batch, "send").mockImplementation(() => result(ok));
cancel = vi
.spyOn(resend.emails, "cancel")
.mockImplementation(() => result(ok));
});
afterEach(() => {
for (const s of [enabled, send, batch, cancel]) s.mockRestore();
});
const email = {
from: "a <[email protected]>",
to: ["[email protected]"],
subject: "s",
react: (
<TrialEndingEmail
workspaceSlug="acme-dev"
plan="starter"
trialEnd={endsAt}
hasPaymentMethod={false}
/>
),
};
test("sendEmail forwards idempotencyKey and scheduledAt, returns the id", async () => {
const id = await sendEmail(
{ ...email, reply_to: "[email protected]" },
{ idempotencyKey: "k", scheduledAt: "2026-09-22T00:00:00.000Z" },
);
expect(id).toBe("email_123");
expect(send.mock.calls[0][0].scheduledAt).toBe("2026-09-22T00:00:00.000Z");
expect(send.mock.calls[0][0].replyTo).toBe("[email protected]");
expect(send.mock.calls[0][1]).toEqual({ idempotencyKey: "k" });
});
test("sendEmail omits both when not given", async () => {
await sendEmail(email);
expect("scheduledAt" in send.mock.calls[0][0]).toBe(false);
expect(send.mock.calls[0][1]).toBeUndefined();
});
test("sendEmail does nothing outside production", async () => {
enabled.mockRestore();
enabled = vi.spyOn(delivery, "enabled").mockImplementation(() => false);
expect(await sendEmail(email)).toBeUndefined();
expect(send).toHaveBeenCalledTimes(0);
});
test("an idempotency conflict or Resend error never throws", async () => {
for (const name of ["invalid_idempotent_request", "application_error"]) {
send.mockRestore();
send = vi
.spyOn(resend.emails, "send")
.mockImplementation(() => result({ data: null, error: { name } }));
expect(await sendEmail(email, { idempotencyKey: "k" })).toBeUndefined();
expect(send).toHaveBeenCalledTimes(1);
}
});
test("cancelScheduledEmail wraps emails.cancel and reports success", async () => {
expect(await cancelScheduledEmail("email_123")).toBe(true);
expect(cancel.mock.calls[0][0]).toBe("email_123");
cancel.mockRestore();
cancel = vi
.spyOn(resend.emails, "cancel")
.mockImplementation(() =>
result({ data: null, error: { name: "application_error" } }),
);
expect(await cancelScheduledEmail("email_123")).toBe(false);
});
test("scheduleMemberAccessEnding: 3 days ahead, 50 recipients per email", async () => {
const now = new Date(endsAt.getTime() - 10 * 86_400_000);
const ids = await scheduleMemberAccessEnding({
to: Array.from({ length: 60 }, (_, i) => `m${i}@acme.dev`),
eventId: "evt_1",
workspaceName: "Acme",
plan: "team",
endsAt,
reason: "cancellation",
owners: ["[email protected]"],
now,
});
expect(send).toHaveBeenCalledTimes(2);
expect(send.mock.calls.map((c) => c[0].to.length)).toEqual([50, 10]);
expect(send.mock.calls[0][0].scheduledAt).toBe("2026-09-22T00:00:00.000Z");
expect(send.mock.calls[1][1]).toEqual({
idempotencyKey: "stripe:evt_1:member-access-ending:1",
});
expect(ids.length).toBe(2);
});
test("scheduleMemberAccessEnding chunks a stable order across redeliveries", async () => {
const req = {
eventId: "evt_1",
workspaceName: "Acme",
plan: "team",
endsAt,
reason: "trial" as const,
owners: [],
};
await scheduleMemberAccessEnding({
...req,
to: ["[email protected]", "[email protected]"],
});
await scheduleMemberAccessEnding({
...req,
to: ["[email protected]", "[email protected]"],
});
expect(send.mock.calls[0][0].to).toEqual(send.mock.calls[1][0].to);
});
test("scheduleMemberAccessEnding inside the lead window sends now, no ids", async () => {
const ids = await scheduleMemberAccessEnding({
to: ["[email protected]"],
eventId: "evt_1",
workspaceName: "Acme",
plan: "team",
endsAt,
reason: "trial",
owners: [],
now: new Date(endsAt.getTime() - 86_400_000),
});
expect(send).toHaveBeenCalledTimes(1);
expect("scheduledAt" in send.mock.calls[0][0]).toBe(false);
expect(ids).toEqual([]);
const unscheduled = await scheduleMemberAccessEnding({
to: ["[email protected]"],
eventId: "evt_3",
workspaceName: "Acme",
plan: "team",
endsAt,
reason: "cancellation",
owners: [],
schedule: false,
now: new Date(endsAt.getTime() - 10 * 86_400_000),
});
expect(send).toHaveBeenCalledTimes(2);
expect("scheduledAt" in send.mock.calls[1][0]).toBe(false);
expect(unscheduled).toEqual([]);
expect(
await scheduleMemberAccessEnding({
to: [],
eventId: "evt_2",
workspaceName: "Acme",
plan: "team",
endsAt,
reason: "trial",
owners: [],
}),
).toEqual([]);
expect(send).toHaveBeenCalledTimes(2);
});
test("sendMemberRemoved chunks at Resend's 100-email batch limit", async () => {
await sendMemberRemoved({
to: Array.from({ length: 250 }, (_, i) => `m${i}@acme.dev`),
idempotencyKey: "stripe:evt_1:member-removed",
workspaceName: "Acme",
reason: "downgrade",
owners: [],
});
expect(batch).toHaveBeenCalledTimes(3);
expect(batch.mock.calls.map((c) => c[0].length)).toEqual([100, 100, 50]);
expect(batch.mock.calls.map((c) => c[1].idempotencyKey)).toEqual([
"stripe:evt_1:member-removed:0",
"stripe:evt_1:member-removed:1",
"stripe:evt_1:member-removed:2",
]);
});
test("a batch error is swallowed, not thrown", async () => {
batch.mockRestore();
batch = vi
.spyOn(resend.batch, "send")
.mockImplementation(() =>
result({ data: null, error: { name: "application_error" } }),
);
await sendMemberRemoved({
to: ["[email protected]"],
workspaceName: "Acme",
reason: "downgrade",
owners: [],
});
expect(batch).toHaveBeenCalledTimes(1);
});
test("sendPlanDowngraded", async () => {
await sendPlanDowngraded({
to: ["[email protected]"],
eventId: "evt_1",
workspaceSlug: "acme-dev",
previousPlan: "team",
loss,
});
const [payload, options] = send.mock.calls[0];
expect(payload.to).toEqual(["[email protected]"]);
expect(payload.from).toBe(
"Thibault from openstatus <[email protected]>",
);
expect(payload.replyTo).toBe("[email protected]");
expect(payload.subject).toBe(
"Your workspace is on the free plan — 2 status pages deleted",
);
expect(options).toEqual({ idempotencyKey: "stripe:evt_1:plan-downgraded" });
});
test("sendMemberRemoved batches one mail per member under one key", async () => {
await sendMemberRemoved({
to: ["[email protected]", "[email protected]"],
idempotencyKey: "stripe:evt_1:member-removed",
workspaceName: "Acme",
reason: "downgrade",
owners: ["[email protected]"],
});
const [emails, options] = batch.mock.calls[0];
expect(emails.map((e: { to: string }) => e.to)).toEqual([
"[email protected]",
"[email protected]",
]);
expect(emails[0].from).toBe(
"openstatus <[email protected]>",
);
expect(emails[0].replyTo).toBe("[email protected]");
expect(emails[0].subject).toBe(
"You no longer have access to Acme on openstatus",
);
expect(emails[0].html).toContain("[email protected]");
expect(options).toEqual({
idempotencyKey: "stripe:evt_1:member-removed:0",
});
});
test("sendOwnershipTransferred sends one mail per person, keyed by recipient", async () => {
await sendOwnershipTransferred({
idempotencyKey: "ownership:1:42",
workspaceName: "Acme",
newOwner: "[email protected]",
formerOwner: "[email protected]",
to: { new: "[email protected]", former: "[email protected]" },
});
expect(send).toHaveBeenCalledTimes(2);
const [toNew, newOptions] = send.mock.calls[0];
const [toFormer, formerOptions] = send.mock.calls[1];
expect(toNew.to).toEqual(["[email protected]"]);
expect(toNew.subject).toBe("You are now the owner of Acme on openstatus");
expect(toNew.replyTo).toBe("[email protected]");
expect(newOptions).toEqual({ idempotencyKey: "ownership:1:42:new" });
expect(toFormer.to).toEqual(["[email protected]"]);
expect(toFormer.subject).toBe(
"You transferred ownership of Acme on openstatus",
);
expect(formerOptions).toEqual({ idempotencyKey: "ownership:1:42:former" });
});
test("sendOwnershipTransferred skips a person without an address", async () => {
await sendOwnershipTransferred({
idempotencyKey: "ownership:1:43",
workspaceName: "Acme",
newOwner: "[email protected]",
formerOwner: "Max",
to: { new: "[email protected]", former: null },
});
expect(send).toHaveBeenCalledTimes(1);
const [toNew] = send.mock.calls[0];
expect(toNew.to).toEqual(["[email protected]"]);
expect(toNew.react.props.formerOwner).toBe("Max");
});
test("sendCancellationScheduled is raw, from the root domain", async () => {
await sendCancellationScheduled({
to: ["[email protected]"],
eventId: "evt_2",
plan: "team",
endsAt,
loss,
});
const [payload, options] = send.mock.calls[0];
expect(payload.from).toBe(
"Thibault from openstatus <[email protected]>",
);
expect(payload.subject).toBe("Your openstatus cancellation");
expect(options).toEqual({
idempotencyKey: "stripe:evt_2:cancellation-scheduled",
});
});
test("schedulePlanEndingSoon schedules 3 days before and returns the id", async () => {
const id = await schedulePlanEndingSoon({
to: ["[email protected]"],
eventId: "evt_2",
workspaceSlug: "acme-dev",
plan: "team",
endsAt,
loss,
now: new Date("2026-09-01T00:00:00Z"),
});
expect(id).toBe("email_123");
const [payload, options] = send.mock.calls[0];
expect(payload.from).toBe("openstatus <[email protected]>");
expect(payload.replyTo).toBe("[email protected]");
expect(payload.scheduledAt).toBe("2026-09-22T00:00:00.000Z");
expect(options).toEqual({
idempotencyKey: "stripe:evt_2:plan-ending-soon",
});
});
test("schedulePlanEndingSoon skips a period end beyond 30 days", async () => {
const id = await schedulePlanEndingSoon({
to: ["[email protected]"],
eventId: "evt_2",
workspaceSlug: "acme-dev",
plan: "team",
endsAt: new Date("2027-03-01T00:00:00Z"),
loss,
now: new Date("2026-09-01T00:00:00Z"),
});
expect(id).toBeUndefined();
expect(send).toHaveBeenCalledTimes(0);
});
test("sendTrialEnding", async () => {
await sendTrialEnding({
to: ["[email protected]"],
eventId: "evt_3",
workspaceSlug: "acme-dev",
trialEnd: endsAt,
plan: "starter",
hasPaymentMethod: false,
loss,
});
const [payload, options] = send.mock.calls[0];
expect(payload.from).toBe("openstatus <[email protected]>");
expect(payload.replyTo).toBe("[email protected]");
expect(payload.subject).toBe(
"Your trial ends on 25 Sep — add a payment method to keep starter",
);
expect(options).toEqual({ idempotencyKey: "stripe:evt_3:trial-ending" });
});
test("no verb sends without recipients", async () => {
await sendPlanDowngraded({
to: [],
eventId: "e",
workspaceSlug: "a",
previousPlan: "team",
loss,
});
await sendMemberRemoved({
to: [],
workspaceName: "A",
reason: "downgrade",
owners: [],
});
await sendTrialEnding({
to: [],
eventId: "e",
workspaceSlug: "a",
trialEnd: endsAt,
plan: "starter",
hasPaymentMethod: false,
});
expect(send).toHaveBeenCalledTimes(0);
expect(batch).toHaveBeenCalledTimes(0);
});
});