Skip to content

Open-source status page, incident response and uptime monitoring

fix(subscribers): query active subscriber for subscribe/unsubscribe (#2099)

Maximilian Kaskee220d1adbc81
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 d8a6d0ae1..531389437 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
@@ -1,5 +1,5 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
-import { db, eq, sql } from "@openstatus/db";
+import { and, db, eq, isNull, sql } from "@openstatus/db";
import {
monitor,
page,
@@ -1921,6 +1921,74 @@ describe("StatusPageService.UnsubscribeFromPage", () => {
expect(res.status).toBe(400);
});
+
+ test("unsubscribes the ACTIVE subscriber when a prior unsubscribed row exists", async () => {
+ const email = `${TEST_PREFIX}[email protected]`;
+
+ // Seed an old unsubscribed row (simulates a user who subscribed, verified,
+ // and unsubscribed in the past).
+ const oldRow = await db
+ .insert(pageSubscriber)
+ .values({
+ pageId: testPageId,
+ email,
+ channelType: "email",
+ token: crypto.randomUUID(),
+ acceptedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 30),
+ unsubscribedAt: new Date(Date.now() - 1000 * 60 * 60 * 24 * 7),
+ })
+ .returning()
+ .get();
+
+ // Create a new ACTIVE subscription for the same email.
+ const activeRow = await db
+ .insert(pageSubscriber)
+ .values({
+ pageId: testPageId,
+ email,
+ channelType: "email",
+ token: crypto.randomUUID(),
+ acceptedAt: new Date(),
+ })
+ .returning()
+ .get();
+
+ // Unsubscribe by email — must target the ACTIVE row.
+ const res = await connectRequest(
+ "UnsubscribeFromPage",
+ {
+ pageId: String(testPageId),
+ email,
+ },
+ { "x-openstatus-key": "1" },
+ );
+ expect(res.status).toBe(200);
+
+ const refreshedActive = await db
+ .select()
+ .from(pageSubscriber)
+ .where(eq(pageSubscriber.id, activeRow.id))
+ .get();
+ expect(refreshedActive?.unsubscribedAt).not.toBeNull();
+
+ // No remaining active rows for this email on this page.
+ const stillActive = await db
+ .select()
+ .from(pageSubscriber)
+ .where(
+ and(
+ eq(pageSubscriber.pageId, testPageId),
+ eq(pageSubscriber.email, email),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ )
+ .all();
+ expect(stillActive.length).toBe(0);
+
+ // Cleanup
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.id, oldRow.id));
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.id, activeRow.id));
+ });
});
describe("StatusPageService.ListSubscribers", () => {
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 d2cbb692f..0514703ec 100644
--- a/apps/server/src/routes/rpc/services/status-page/index.ts
+++ b/apps/server/src/routes/rpc/services/status-page/index.ts
@@ -9,6 +9,7 @@ import {
inArray,
isNull,
lte,
+ sql,
} from "@openstatus/db";
import {
maintenance,
@@ -973,7 +974,9 @@ export const statusPageServiceImpl: ServiceImpl<typeof StatusPageService> = {
.where(
and(
eq(pageSubscriber.pageId, pageData.id),
- eq(pageSubscriber.email, req.identifier.value),
+ sql`LOWER(${pageSubscriber.email}) = ${req.identifier.value.toLowerCase()}`,
+ eq(pageSubscriber.channelType, "email"),
+ isNull(pageSubscriber.unsubscribedAt),
),
)
.get();
diff --git a/apps/server/src/routes/v1/pageSubscribers/post.test.ts b/apps/server/src/routes/v1/pageSubscribers/post.test.ts
index 4343a94ed..92111b759 100644
--- a/apps/server/src/routes/v1/pageSubscribers/post.test.ts
+++ b/apps/server/src/routes/v1/pageSubscribers/post.test.ts
@@ -1,7 +1,7 @@
import { expect, test } from "bun:test";
import { app } from "@/index";
-import { db, eq } from "@openstatus/db";
+import { and, db, eq, isNull } from "@openstatus/db";
import { pageSubscriber } from "@openstatus/db/src/schema";
import { PageSubscriberSchema } from "./schema";
@@ -51,3 +51,130 @@ test("no auth key should return 401", async () => {
expect(res.status).toBe(401);
});
+
+test("re-subscribing after unsubscribe succeeds and does not leave duplicate active rows", async () => {
+ const email = "[email protected]";
+
+ // Clean any pre-existing rows from a previous run
+ await db
+ .delete(pageSubscriber)
+ .where(and(eq(pageSubscriber.email, email), eq(pageSubscriber.pageId, 1)));
+
+ // 1. Subscribe
+ const firstRes = await app.request("/v1/page_subscriber/1/update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ email }),
+ });
+ expect(firstRes.status).toBe(200);
+ const first = PageSubscriberSchema.parse(await firstRes.json());
+
+ // 2. Mark the subscriber as accepted + unsubscribed (simulates the
+ // user verifying, then later unsubscribing via one-click).
+ await db
+ .update(pageSubscriber)
+ .set({ acceptedAt: new Date(), unsubscribedAt: new Date() })
+ .where(eq(pageSubscriber.id, first.id));
+
+ // 3. Subscribe the same email again — should succeed.
+ const secondRes = await app.request("/v1/page_subscriber/1/update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ email }),
+ });
+ expect(secondRes.status).toBe(200);
+
+ // There must be exactly one ACTIVE row (unsubscribedAt IS NULL) for the email.
+ const active = await db
+ .select()
+ .from(pageSubscriber)
+ .where(
+ and(
+ eq(pageSubscriber.email, email),
+ eq(pageSubscriber.pageId, 1),
+ isNull(pageSubscriber.unsubscribedAt),
+ ),
+ )
+ .all();
+ expect(active.length).toBe(1);
+
+ // Cleanup
+ await db
+ .delete(pageSubscriber)
+ .where(and(eq(pageSubscriber.email, email), eq(pageSubscriber.pageId, 1)));
+});
+
+test("subscribing when an active subscription already exists returns 409", async () => {
+ const email = "[email protected]";
+
+ await db
+ .delete(pageSubscriber)
+ .where(and(eq(pageSubscriber.email, email), eq(pageSubscriber.pageId, 1)));
+
+ const firstRes = await app.request("/v1/page_subscriber/1/update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ email }),
+ });
+ expect(firstRes.status).toBe(200);
+ const first = PageSubscriberSchema.parse(await firstRes.json());
+
+ // Second subscribe with an already-active (but pending) entry should conflict.
+ const secondRes = await app.request("/v1/page_subscriber/1/update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ email }),
+ });
+ expect(secondRes.status).toBe(409);
+
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.id, first.id));
+});
+
+test("subscribing is case-insensitive on email", async () => {
+ const email = "[email protected]";
+
+ await db
+ .delete(pageSubscriber)
+ .where(
+ and(
+ eq(pageSubscriber.email, email.toLowerCase()),
+ eq(pageSubscriber.pageId, 1),
+ ),
+ );
+
+ const firstRes = await app.request("/v1/page_subscriber/1/update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ email }),
+ });
+ expect(firstRes.status).toBe(200);
+ const first = PageSubscriberSchema.parse(await firstRes.json());
+
+ // Same email in different case — should conflict.
+ const secondRes = await app.request("/v1/page_subscriber/1/update", {
+ method: "POST",
+ headers: {
+ "x-openstatus-key": "1",
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({ email: email.toUpperCase() }),
+ });
+ expect(secondRes.status).toBe(409);
+
+ await db.delete(pageSubscriber).where(eq(pageSubscriber.id, first.id));
+});
diff --git a/apps/server/src/routes/v1/pageSubscribers/post.ts b/apps/server/src/routes/v1/pageSubscribers/post.ts
index 1ba27607c..bec3fb7fd 100644
--- a/apps/server/src/routes/v1/pageSubscribers/post.ts
+++ b/apps/server/src/routes/v1/pageSubscribers/post.ts
@@ -3,7 +3,7 @@ import { createRoute } from "@hono/zod-openapi";
import { OpenStatusApiError, openApiErrorResponses } from "@/libs/errors";
import { trackMiddleware } from "@/libs/middlewares";
import { Events } from "@openstatus/analytics";
-import { and, eq, isNotNull } from "@openstatus/db";
+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";
@@ -68,15 +68,17 @@ export function registerPostPageSubscriber(api: typeof pageSubscribersApi) {
});
}
+ const normalizedEmail = input.email.toLowerCase();
+
const alreadySubscribed = await db
.select()
.from(pageSubscriber)
.where(
and(
- eq(pageSubscriber.email, input.email),
+ sql`LOWER(${pageSubscriber.email}) = ${normalizedEmail}`,
eq(pageSubscriber.pageId, Number(id)),
- isNotNull(pageSubscriber.acceptedAt),
- isNotNull(pageSubscriber.unsubscribedAt),
+ eq(pageSubscriber.channelType, "email"),
+ isNull(pageSubscriber.unsubscribedAt),
),
)
.get();
@@ -95,7 +97,7 @@ export function registerPostPageSubscriber(api: typeof pageSubscribersApi) {
.insert(pageSubscriber)
.values({
pageId: _page.id,
- email: input.email,
+ email: normalizedEmail,
token,
expiresAt,
})
@@ -110,7 +112,7 @@ export function registerPostPageSubscriber(api: typeof pageSubscribersApi) {
page: _page.title,
}),
from: "OpenStatus <[email protected]>",
- to: [input.email],
+ to: [normalizedEmail],
subject: "Verify your subscription",
});