Skip to content

Open-source status page, incident response and uptime monitoring

fix: bug api email subscriber (#2097)

Thibault Le Ouay2c7a38bd3fc8
diff --git a/apps/server/src/libs/test/preload.ts b/apps/server/src/libs/test/preload.ts
index 1ee432e14..304600f80 100644
--- a/apps/server/src/libs/test/preload.ts
+++ b/apps/server/src/libs/test/preload.ts
@@ -1,17 +1,34 @@
import { mock } from "bun:test";
+import * as realSubscriptions from "@openstatus/subscriptions";
// Subscription dispatch spies — accessible in tests via globalThis.__subscriptionSpies
const dispatchStatusReportUpdateSpy = mock((_id: number) => Promise.resolve());
const dispatchMaintenanceUpdateSpy = mock((_id: number) => Promise.resolve());
+const sendVerificationSpy = mock(
+ (_subscription: realSubscriptions.Subscription, _verifyUrl: string) =>
+ Promise.resolve(),
+);
+
+const getChannelMock = {
+ id: "email",
+ sendVerification: sendVerificationSpy,
+ sendNotifications: mock(() => Promise.resolve()),
+ validateConfig: mock(() => Promise.resolve({ valid: true })),
+};
+
(globalThis as Record<string, unknown>).__subscriptionSpies = {
dispatchStatusReportUpdate: dispatchStatusReportUpdateSpy,
dispatchMaintenanceUpdate: dispatchMaintenanceUpdateSpy,
+ sendVerification: sendVerificationSpy,
+ getChannel: getChannelMock,
};
mock.module("@openstatus/subscriptions", () => ({
+ ...realSubscriptions,
dispatchStatusReportUpdate: dispatchStatusReportUpdateSpy,
dispatchMaintenanceUpdate: dispatchMaintenanceUpdateSpy,
+ getChannel: () => getChannelMock,
}));
const testRedisStore = new Map<string, string>();
diff --git a/apps/server/src/routes/rpc/services/status-page/__tests__/status-page.test.ts b/apps/server/src/routes/rpc/services/status-page/__tests__/status-page.test.ts
index f8f7cd068..d8a6d0ae1 100644
--- a/apps/server/src/routes/rpc/services/status-page/__tests__/status-page.test.ts
+++ b/apps/server/src/routes/rpc/services/status-page/__tests__/status-page.test.ts
@@ -61,6 +61,9 @@ beforeAll(async () => {
await db.run(
sql`UPDATE workspace SET limits = json_set(COALESCE(limits, '{}'), '$."no-index"', json('true')) WHERE id = 1`,
);
+ await db.run(
+ sql`UPDATE workspace SET limits = json_set(COALESCE(limits, '{}'), '$."status-subscribers"', json('true')) WHERE id = 1`,
+ );
// Clean up any existing test data
await db
@@ -1663,8 +1666,15 @@ describe("StatusPageService.UpdateComponentGroup", () => {
// Subscribers
// ==========================================================================
+const subscriptionSpies = (globalThis as Record<string, unknown>)
+ .__subscriptionSpies as {
+ sendVerification: ReturnType<typeof import("bun:test").mock>;
+};
+
describe("StatusPageService.SubscribeToPage", () => {
test("subscribes new user to page", async () => {
+ subscriptionSpies.sendVerification.mockClear();
+
const res = await connectRequest(
"SubscribeToPage",
{
@@ -1680,6 +1690,7 @@ describe("StatusPageService.SubscribeToPage", () => {
expect(data).toHaveProperty("subscriber");
expect(data.subscriber.email).toBe(`${TEST_PREFIX}[email protected]`);
expect(data.subscriber.pageId).toBe(String(testPageId));
+ expect(subscriptionSpies.sendVerification).toHaveBeenCalledTimes(1);
// Clean up
await db
@@ -1688,11 +1699,13 @@ describe("StatusPageService.SubscribeToPage", () => {
});
test("returns existing subscriber when already subscribed", async () => {
+ subscriptionSpies.sendVerification.mockClear();
+
const res = await connectRequest(
"SubscribeToPage",
{
pageId: String(testPageId),
- email: `${TEST_PREFIX}@example.com`, // Already exists
+ email: `${TEST_PREFIX}@example.com`, // Already exists and verified
},
{ "x-openstatus-key": "1" },
);
@@ -1702,6 +1715,7 @@ describe("StatusPageService.SubscribeToPage", () => {
const data = await res.json();
expect(data).toHaveProperty("subscriber");
expect(data.subscriber.id).toBe(String(testSubscriberId));
+ expect(subscriptionSpies.sendVerification).not.toHaveBeenCalled();
});
test("returns 401 when no auth key provided", async () => {
@@ -1725,6 +1739,78 @@ describe("StatusPageService.SubscribeToPage", () => {
expect(res.status).toBe(404);
});
+
+ test("returns 403 when status-subscribers limit is disabled", async () => {
+ const res = await connectRequest(
+ "SubscribeToPage",
+ {
+ pageId: "1",
+ email: "[email protected]",
+ },
+ { "x-openstatus-key": "2" },
+ );
+
+ expect(res.status).toBe(403);
+ });
+
+ test("returns subscriber even if email sending fails", async () => {
+ subscriptionSpies.sendVerification.mockImplementationOnce(() => {
+ throw new Error("Resend API failure");
+ });
+
+ const res = await connectRequest(
+ "SubscribeToPage",
+ {
+ pageId: String(testPageId),
+ email: `${TEST_PREFIX}[email protected]`,
+ },
+ { "x-openstatus-key": "1" },
+ );
+
+ expect(res.status).toBe(200);
+
+ const data = await res.json();
+ expect(data).toHaveProperty("subscriber");
+ expect(data.subscriber.email).toBe(`${TEST_PREFIX}[email protected]`);
+
+ // Clean up
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.id, Number(data.subscriber.id)));
+ });
+
+ test("re-subscribing a pending subscriber re-sends verification email", async () => {
+ // First subscribe
+ const res1 = await connectRequest(
+ "SubscribeToPage",
+ {
+ pageId: String(testPageId),
+ email: `${TEST_PREFIX}[email protected]`,
+ },
+ { "x-openstatus-key": "1" },
+ );
+ expect(res1.status).toBe(200);
+
+ subscriptionSpies.sendVerification.mockClear();
+
+ // Subscribe again with the same email
+ const res2 = await connectRequest(
+ "SubscribeToPage",
+ {
+ pageId: String(testPageId),
+ email: `${TEST_PREFIX}[email protected]`,
+ },
+ { "x-openstatus-key": "1" },
+ );
+ expect(res2.status).toBe(200);
+ expect(subscriptionSpies.sendVerification).toHaveBeenCalledTimes(1);
+
+ // Clean up
+ const data = await res2.json();
+ await db
+ .delete(pageSubscriber)
+ .where(eq(pageSubscriber.id, Number(data.subscriber.id)));
+ });
});
describe("StatusPageService.UnsubscribeFromPage", () => {
diff --git a/apps/server/src/routes/rpc/services/status-page/index.ts b/apps/server/src/routes/rpc/services/status-page/index.ts
index 6d29d024c..d2cbb692f 100644
--- a/apps/server/src/routes/rpc/services/status-page/index.ts
+++ b/apps/server/src/routes/rpc/services/status-page/index.ts
@@ -27,7 +27,7 @@ import {
OverallStatus,
PageAccessType,
} from "@openstatus/proto/status_page/v1";
-import { nanoid } from "nanoid";
+import { getChannel, upsertEmailSubscription } from "@openstatus/subscriptions";
import { getRpcContext } from "../../interceptors";
import {
@@ -71,6 +71,7 @@ import {
checkPageComponentLimits,
checkPasswordProtectionLimit,
checkStatusPageLimits,
+ checkStatusSubscribersLimit,
} from "./limits";
/**
@@ -897,75 +898,60 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
async subscribeToPage(req, ctx) {
const rpcCtx = getRpcContext(ctx);
const workspaceId = rpcCtx.workspace.id;
+ const limits = rpcCtx.workspace.limits;
+
+ checkStatusSubscribersLimit(limits);
- // Verify page exists and belongs to workspace
const pageData = await getPageById(Number(req.pageId), workspaceId);
if (!pageData) {
throw statusPageNotFoundError(req.pageId);
}
- // Check if already subscribed
- const existingSubscriber = await db
+ const result = await upsertEmailSubscription({
+ email: req.email,
+ pageId: pageData.id,
+ });
+
+ const row = await db
.select()
.from(pageSubscriber)
- .where(
- and(
- eq(pageSubscriber.pageId, pageData.id),
- eq(pageSubscriber.email, req.email),
- ),
- )
+ .where(eq(pageSubscriber.id, result.id))
.get();
- if (existingSubscriber) {
- // If unsubscribed, resubscribe within a transaction to ensure atomicity
- if (existingSubscriber.unsubscribedAt) {
- const updatedSubscriber = await db.transaction(async (tx) => {
- const result = await tx
- .update(pageSubscriber)
- .set({
- unsubscribedAt: null,
- updatedAt: new Date(),
- token: nanoid(),
- })
- .where(eq(pageSubscriber.id, existingSubscriber.id))
- .returning()
- .get();
-
- if (!result) {
- throw subscriberCreateFailedError();
- }
-
- return result;
- });
-
- return {
- subscriber: dbSubscriberToProto(updatedSubscriber),
- };
- }
-
- // Already subscribed, return existing
- return {
- subscriber: dbSubscriberToProto(existingSubscriber),
- };
+ if (!row) {
+ throw subscriberCreateFailedError();
}
- // Create new subscriber
- const newSubscriber = await db
- .insert(pageSubscriber)
- .values({
- pageId: pageData.id,
- email: req.email,
- token: nanoid(),
- })
- .returning()
- .get();
-
- if (!newSubscriber) {
- throw subscriberCreateFailedError();
+ if (!result.acceptedAt) {
+ const verifyUrl = pageData.customDomain
+ ? `https://${pageData.customDomain}/verify/${result.token}`
+ : `https://${pageData.slug}.openstatus.dev/verify/${result.token}`;
+
+ const channel = getChannel("email");
+ if (channel?.sendVerification) {
+ try {
+ await channel.sendVerification(
+ {
+ id: result.id,
+ pageId: pageData.id,
+ pageName: pageData.title,
+ pageSlug: pageData.slug,
+ customDomain: pageData.customDomain,
+ componentIds: [],
+ channelType: "email",
+ email: result.email,
+ token: result.token ?? undefined,
+ },
+ verifyUrl,
+ );
+ } catch (err) {
+ console.error("Failed to send verification email:", err);
+ }
+ }
}
return {
- subscriber: dbSubscriberToProto(newSubscriber),
+ subscriber: dbSubscriberToProto(row),
};
},
diff --git a/apps/server/src/routes/rpc/services/status-page/limits.ts b/apps/server/src/routes/rpc/services/status-page/limits.ts
index cbcf97b0b..2ff3b2628 100644
--- a/apps/server/src/routes/rpc/services/status-page/limits.ts
+++ b/apps/server/src/routes/rpc/services/status-page/limits.ts
@@ -86,6 +86,15 @@ export function checkNoIndexLimit(limits: Limits): void {
}
}
+export function checkStatusSubscribersLimit(limits: Limits): void {
+ if (!limits["status-subscribers"]) {
+ throw new ConnectError(
+ "Upgrade to use status subscribers",
+ Code.PermissionDenied,
+ );
+ }
+}
+
/**
* Check workspace limits for creating a new page component.
* Throws ConnectError with PermissionDenied if limit is exceeded.