Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Remove retired onboarding tip cancellation (#1273)

Goldflagda6b5f704044
diff --git a/server/src/api/user/unsubscribeMarketing.test.ts b/server/src/api/user/unsubscribeMarketing.test.ts
new file mode 100644
index 000000000..c1d26559d
--- /dev/null
+++ b/server/src/api/user/unsubscribeMarketing.test.ts
@@ -0,0 +1,182 @@
+import type { FastifyReply, FastifyRequest } from "fastify";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ findUser: vi.fn(),
+ unsubscribeContact: vi.fn(),
+}));
+
+vi.mock("../../db/postgres/postgres.js", () => ({
+ db: {
+ select: () => ({ from: () => ({ where: mocks.findUser }) }),
+ },
+}));
+vi.mock("../../lib/email/email.js", () => ({ unsubscribeContact: mocks.unsubscribeContact }));
+vi.mock("../../lib/const.js", () => ({ SECRET: "test-secret" }));
+
+import { signExpiringPayload, signPayload } from "../../lib/signedToken.js";
+import { oneClickUnsubscribeMarketing, unsubscribeMarketing } from "./unsubscribeMarketing.js";
+
+type UnsubscribeQuery = { email?: string; exp?: string; sig?: string };
+
+function requestStub(method = "POST", query: UnsubscribeQuery = {}, userId?: string) {
+ return {
+ method,
+ query,
+ user: userId ? { id: userId } : undefined,
+ log: { error: vi.fn() },
+ } as unknown as FastifyRequest<{ Querystring: UnsubscribeQuery }>;
+}
+
+function replyStub() {
+ return {
+ status: vi.fn().mockReturnThis(),
+ type: vi.fn().mockReturnThis(),
+ send: vi.fn().mockReturnThis(),
+ } as unknown as FastifyReply;
+}
+
+const email = "[email protected]";
+
+function signedQuery(): UnsubscribeQuery {
+ const { exp, sig } = signExpiringPayload(`unsubscribe:${email}`, 3600);
+ return { email, exp: String(exp), sig };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-09-29T12:00:00Z"));
+ vi.clearAllMocks();
+ mocks.findUser.mockResolvedValue([{ email }]);
+ mocks.unsubscribeContact.mockResolvedValue(undefined);
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("authenticated marketing unsubscribe", () => {
+ it("unsubscribes the authenticated user's contact", async () => {
+ const reply = replyStub();
+ await unsubscribeMarketing(requestStub("POST", {}, "u1"), reply);
+
+ expect(mocks.unsubscribeContact).toHaveBeenCalledWith(email);
+ expect(reply.send).toHaveBeenCalledWith({
+ success: true,
+ message: "Successfully unsubscribed from marketing emails",
+ });
+ });
+
+ it("returns 401 without authentication", async () => {
+ const reply = replyStub();
+ await unsubscribeMarketing(requestStub(), reply);
+
+ expect(reply.status).toHaveBeenCalledWith(401);
+ expect(mocks.findUser).not.toHaveBeenCalled();
+ expect(mocks.unsubscribeContact).not.toHaveBeenCalled();
+ });
+
+ it("returns 404 if the authenticated user no longer exists", async () => {
+ mocks.findUser.mockResolvedValue([]);
+ const reply = replyStub();
+ await unsubscribeMarketing(requestStub("POST", {}, "deleted"), reply);
+
+ expect(reply.status).toHaveBeenCalledWith(404);
+ expect(reply.send).toHaveBeenCalledWith({ error: "User not found" });
+ expect(mocks.unsubscribeContact).not.toHaveBeenCalled();
+ });
+
+ it("returns 500 when unsubscribing fails", async () => {
+ mocks.unsubscribeContact.mockRejectedValue(new Error("Contact update failed"));
+ const reply = replyStub();
+ await unsubscribeMarketing(requestStub("POST", {}, "u1"), reply);
+
+ expect(reply.status).toHaveBeenCalledWith(500);
+ expect(reply.send).toHaveBeenCalledWith({ error: "Failed to unsubscribe" });
+ });
+});
+
+describe("one-click marketing unsubscribe", () => {
+ it("honors signed POST requests even without a matching database user", async () => {
+ mocks.findUser.mockResolvedValue([]);
+ const reply = replyStub();
+ await oneClickUnsubscribeMarketing(requestStub("POST", signedQuery()), reply);
+
+ expect(mocks.unsubscribeContact).toHaveBeenCalledWith(email);
+ expect(reply.status).toHaveBeenCalledWith(200);
+ expect(reply.send).toHaveBeenCalledWith();
+ });
+
+ it("shows the confirmation page for signed GET links", async () => {
+ const reply = replyStub();
+ await oneClickUnsubscribeMarketing(requestStub("GET", signedQuery()), reply);
+
+ expect(mocks.unsubscribeContact).toHaveBeenCalledWith(email);
+ expect(reply.status).toHaveBeenCalledWith(200);
+ expect(reply.type).toHaveBeenCalledWith("text/html");
+ expect(reply.send).toHaveBeenCalledWith(expect.stringContaining("<h1>Unsubscribed</h1>"));
+ });
+
+ it("honors unsigned links only before the legacy cutoff", async () => {
+ const before = replyStub();
+ await oneClickUnsubscribeMarketing(requestStub("POST", { email }), before);
+ expect(mocks.unsubscribeContact).toHaveBeenCalledWith(email);
+ expect(before.status).toHaveBeenCalledWith(200);
+
+ mocks.unsubscribeContact.mockClear();
+ vi.setSystemTime(new Date("2026-12-01T00:00:00Z"));
+ const atCutoff = replyStub();
+ await oneClickUnsubscribeMarketing(requestStub("POST", { email }), atCutoff);
+ expect(atCutoff.status).toHaveBeenCalledWith(400);
+ expect(mocks.unsubscribeContact).not.toHaveBeenCalled();
+ });
+
+ it("keeps valid signed links working after the legacy cutoff", async () => {
+ vi.setSystemTime(new Date("2026-12-02T00:00:00Z"));
+ const reply = replyStub();
+ await oneClickUnsubscribeMarketing(requestStub("POST", signedQuery()), reply);
+
+ expect(mocks.unsubscribeContact).toHaveBeenCalledWith(email);
+ expect(reply.status).toHaveBeenCalledWith(200);
+ });
+
+ it.each(["tampered", "expired", "partial"])("rejects a %s signed link during the legacy window", async kind => {
+ let query = signedQuery();
+ if (kind === "tampered") query = { ...query, email: "[email protected]" };
+ if (kind === "partial") query = { email, exp: query.exp };
+ if (kind === "expired") {
+ const exp = Math.floor(Date.now() / 1000) - 1;
+ query = { email, exp: String(exp), sig: signPayload(`unsubscribe:${email}:${exp}`) };
+ }
+ const reply = replyStub();
+ await oneClickUnsubscribeMarketing(requestStub("POST", query), reply);
+
+ expect(reply.status).toHaveBeenCalledWith(400);
+ expect(reply.send).toHaveBeenCalledWith({ error: "Invalid or expired unsubscribe link" });
+ expect(mocks.unsubscribeContact).not.toHaveBeenCalled();
+ });
+
+ it.each(["GET", "POST"])("returns 400 for a %s request without an email", async method => {
+ const reply = replyStub();
+ await oneClickUnsubscribeMarketing(requestStub(method), reply);
+
+ expect(reply.status).toHaveBeenCalledWith(400);
+ expect(mocks.unsubscribeContact).not.toHaveBeenCalled();
+ if (method === "GET") {
+ expect(reply.type).toHaveBeenCalledWith("text/html");
+ } else {
+ expect(reply.send).toHaveBeenCalledWith({ error: "Email is required" });
+ }
+ });
+
+ it("keeps the 200 response for email clients when unsubscribing fails", async () => {
+ mocks.unsubscribeContact.mockRejectedValue(new Error("Contact update failed"));
+ const request = requestStub("POST", signedQuery());
+ const reply = replyStub();
+ await oneClickUnsubscribeMarketing(request, reply);
+
+ expect(request.log.error).toHaveBeenCalled();
+ expect(reply.status).toHaveBeenCalledWith(200);
+ expect(reply.send).toHaveBeenCalledWith();
+ });
+});
diff --git a/server/src/api/user/unsubscribeMarketing.ts b/server/src/api/user/unsubscribeMarketing.ts
index 6742f1545..332103f10 100644
--- a/server/src/api/user/unsubscribeMarketing.ts
+++ b/server/src/api/user/unsubscribeMarketing.ts
@@ -3,17 +3,9 @@ import { eq } from "drizzle-orm";
import { DateTime } from "luxon";
import { db } from "../../db/postgres/postgres.js";
import { user } from "../../db/postgres/schema.js";
-import { cancelScheduledEmail, unsubscribeContact } from "../../lib/email/email.js";
+import { unsubscribeContact } from "../../lib/email/email.js";
import { verifyExpiringPayload } from "../../lib/signedToken.js";
-// Cancel tip emails pre-scheduled in Resend for users who signed up before the
-// lifecycle email system replaced the fixed drip. Remove once those have aged out.
-const cancelLegacyScheduledTips = async (emailIds: string[]): Promise<void> => {
- for (const emailId of emailIds) {
- await cancelScheduledEmail(emailId);
- }
-};
-
// Authenticated user unsubscribe
export const unsubscribeMarketing = async (request: FastifyRequest, reply: FastifyReply) => {
try {
@@ -26,7 +18,6 @@ export const unsubscribeMarketing = async (request: FastifyRequest, reply: Fasti
const [userData] = await db
.select({
email: user.email,
- scheduledTipEmailIds: user.scheduledTipEmailIds,
})
.from(user)
.where(eq(user.id, userId));
@@ -35,19 +26,6 @@ export const unsubscribeMarketing = async (request: FastifyRequest, reply: Fasti
return reply.status(404).send({ error: "User not found" });
}
- // Cancel scheduled tip emails
- const emailIds = (userData.scheduledTipEmailIds as string[]) || [];
- await cancelLegacyScheduledTips(emailIds);
-
- // Clear the scheduled email IDs
- await db
- .update(user)
- .set({
- scheduledTipEmailIds: [],
- updatedAt: DateTime.now().toISO(),
- })
- .where(eq(user.id, userId));
-
// Mark contact as unsubscribed in Resend
await unsubscribeContact(userData.email);
@@ -99,30 +77,6 @@ export const oneClickUnsubscribeMarketing = async (
return reply.status(400).send({ error: "Email is required" });
}
- // Find user by email
- const [userData] = await db
- .select({
- id: user.id,
- scheduledTipEmailIds: user.scheduledTipEmailIds,
- })
- .from(user)
- .where(eq(user.email, email));
-
- if (userData) {
- // Cancel scheduled tip emails
- const emailIds = (userData.scheduledTipEmailIds as string[]) || [];
- await cancelLegacyScheduledTips(emailIds);
-
- // Clear the scheduled email IDs
- await db
- .update(user)
- .set({
- scheduledTipEmailIds: [],
- updatedAt: DateTime.now().toISO(),
- })
- .where(eq(user.id, userData.id));
- }
-
// Mark contact as unsubscribed in Resend (even if user not found in our DB)
await unsubscribeContact(email);
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index 68bb2d2a6..af39e7a17 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -43,9 +43,8 @@ export const user = pgTable(
// deprecated
monthlyEventCount: integer().default(0),
sendAutoEmailReports: boolean().default(true),
- // deprecated - Resend email IDs from the retired pre-scheduled tip sequence; kept so
- // unsubscribe can still cancel tips already scheduled for users who signed up before
- // the lifecycle email system replaced it
+ // deprecated - Resend IDs from the retired tip sequence; retained until the
+ // separate contract migration audits and drops the legacy data
scheduledTipEmailIds: jsonb("scheduled_tip_email_ids").$type<string[]>().default([]),
},
table => [unique("user_username_unique").on(table.username), unique("user_email_unique").on(table.email)]
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index fe57c5083..99e712c47 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -289,11 +289,6 @@ export const auth = betterAuth({
defaultValue: true,
input: true,
},
- // scheduledTipEmailIds: {
- // type: "string[]",
- // required: false,
- // defaultValue: [],
- // },
},
deleteUser: {
enabled: true,
diff --git a/server/src/lib/email/email.ts b/server/src/lib/email/email.ts
index 5d96bbc54..dca9496e6 100644
--- a/server/src/lib/email/email.ts
+++ b/server/src/lib/email/email.ts
@@ -242,16 +242,6 @@ Bill`;
}
};
-// Cancel a scheduled email
-export const cancelScheduledEmail = async (emailId: string): Promise<void> => {
- if (!resend) return;
- try {
- await resend.emails.cancel(emailId);
- } catch (error) {
- console.error("Failed to cancel scheduled email:", error);
- }
-};
-
/**
* Signed one-click marketing unsubscribe URL used by all lifecycle emails.
* Unsubscribe links must keep working from old emails, so the TTL is long
diff --git a/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts b/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts
index 2a9313426..576ac4413 100644
--- a/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts
+++ b/server/src/services/lifecycleEmails/lifecycleEmailService.test.ts
@@ -14,7 +14,6 @@ const daysAgo = (d: number) => now().minus({ days: d }).toSQL({ includeOffset: f
const state = vi.hoisted(() => ({
users: [] as Array<{ id: string; email: string; name: string; createdAt: string }>,
- legacyTipUsers: [] as Array<{ id: string; scheduledTipEmailIds: string[] }>,
memberships: [] as Array<{ userId: string; organizationId: string; role: string }>,
sites: [] as Array<{
siteId: number;
@@ -44,13 +43,11 @@ const state = vi.hoisted(() => ({
establishedSites: [] as Array<{ site_id: number; total: number }>,
/** unique-key guard mirroring the DB constraint */
sentKeys: new Set<string>(),
- clearedTipUsers: [] as string[],
}));
const mocks = vi.hoisted(() => ({
sendLifecycleEmail: vi.fn(async (_email: string, _subject: string, _text: string, _idempotencyKey?: string) => true),
isContactUnsubscribed: vi.fn(async (_email: string) => false),
- cancelScheduledEmail: vi.fn(async (_id: string) => undefined),
detectPlatform: vi.fn(async () => null),
}));
@@ -73,7 +70,6 @@ vi.mock("../../db/postgres/postgres.js", () => {
// Reads are told apart by the columns each one selects.
select: (fields: Record<string, unknown>) =>
chain(() => {
- if ("scheduledTipEmailIds" in fields) return state.legacyTipUsers;
if ("siteId" in fields && "userId" in fields && "sentAt" in fields) return state.recentQuietLogs;
if ("emailKey" in fields && "userId" in fields) return state.logs;
if ("role" in fields) return state.memberships;
@@ -105,10 +101,8 @@ vi.mock("../../db/postgres/postgres.js", () => {
}),
}),
update: () => ({
- set: (values: Record<string, unknown>) => ({
- where: async () => {
- if ("scheduledTipEmailIds" in values) state.clearedTipUsers.push("cleared");
- },
+ set: () => ({
+ where: async () => {},
}),
}),
// The service only deletes the rows it just inserted (send-failure
@@ -151,7 +145,6 @@ vi.mock("../../db/clickhouse/clickhouse.js", () => ({
vi.mock("../../lib/email/email.js", () => ({
sendLifecycleEmail: mocks.sendLifecycleEmail,
isContactUnsubscribed: mocks.isContactUnsubscribed,
- cancelScheduledEmail: mocks.cancelScheduledEmail,
}));
vi.mock("../../lib/const.js", () => ({ IS_CLOUD: true, SECRET: "test-secret" }));
@@ -193,7 +186,6 @@ beforeEach(() => {
insertedStack.length = 0;
// Reset singleton run-state between tests
(lifecycleEmailService as any).lastWentQuietAt = null;
- (lifecycleEmailService as any).legacyTipsCancelled = true;
(lifecycleEmailService as any).negativeCache.clear();
});
@@ -609,14 +601,3 @@ describe("multi-site owners", () => {
expect(mocks.sendLifecycleEmail.mock.calls[0][3]).toBe("lifecycle:u1:no_site_1");
});
});
-
-describe("rollout", () => {
- it("cancels tips the retired drip already scheduled in Resend", async () => {
- (lifecycleEmailService as any).legacyTipsCancelled = false;
- state.legacyTipUsers.push({ id: "u9", scheduledTipEmailIds: ["re_1", "re_2", "re_3"] });
- await run();
- expect(mocks.cancelScheduledEmail).toHaveBeenCalledTimes(3);
- expect(mocks.cancelScheduledEmail).toHaveBeenCalledWith("re_1");
- expect(state.clearedTipUsers.length).toBe(1);
- });
-});
diff --git a/server/src/services/lifecycleEmails/lifecycleEmailService.ts b/server/src/services/lifecycleEmails/lifecycleEmailService.ts
index b134cd5c7..1aa6ccdfe 100644
--- a/server/src/services/lifecycleEmails/lifecycleEmailService.ts
+++ b/server/src/services/lifecycleEmails/lifecycleEmailService.ts
@@ -5,7 +5,7 @@ import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { db } from "../../db/postgres/postgres.js";
import { goals, lifecycleEmailLog, member, sites, user } from "../../db/postgres/schema.js";
import { IS_CLOUD } from "../../lib/const.js";
-import { cancelScheduledEmail, isContactUnsubscribed, sendLifecycleEmail } from "../../lib/email/email.js";
+import { isContactUnsubscribed, sendLifecycleEmail } from "../../lib/email/email.js";
import { createServiceLogger } from "../../lib/logger/logger.js";
import { signExpiringPayload } from "../../lib/signedToken.js";
import * as content from "./lifecycleContent.js";
@@ -85,7 +85,6 @@ class LifecycleEmailService {
private cronTask: cron.ScheduledTask | null = null;
private logger = createServiceLogger("lifecycle-emails");
private running = false;
- private legacyTipsCancelled = false;
private lastWentQuietAt: DateTime | null = null;
/** cacheKey -> epoch ms until which a known-negative ClickHouse probe is not repeated */
private negativeCache = new Map<string, number>();
@@ -316,38 +315,6 @@ class LifecycleEmailService {
return this.sendBundle(userId, email, [{ key: emailKey, siteId }], `lifecycle:${userId}:${emailKey}`, build);
}
- // -------------------------------------------------------------------------
- // Rollout: cancel tips the retired drip already scheduled in Resend
- // -------------------------------------------------------------------------
-
- private async cancelLegacyScheduledTips(): Promise<void> {
- if (this.legacyTipsCancelled) return;
- this.legacyTipsCancelled = true;
-
- try {
- // The old drip scheduled at most 5 days out, so only recent signups can
- // still have pending sends worth cancelling.
- const cutoff = DateTime.utc().minus({ days: 10 }).toSQL({ includeOffset: false })!;
- const users = await db
- .select({ id: user.id, scheduledTipEmailIds: user.scheduledTipEmailIds })
- .from(user)
- .where(gt(user.createdAt, cutoff));
-
- for (const u of users) {
- const ids = (u.scheduledTipEmailIds as string[]) || [];
- if (ids.length === 0) continue;
- for (const emailId of ids) {
- await cancelScheduledEmail(emailId);
- }
- await db.update(user).set({ scheduledTipEmailIds: [] }).where(eq(user.id, u.id));
- this.logger.info({ userId: u.id, cancelled: ids.length }, "Cancelled legacy scheduled tip emails");
- }
- } catch (error) {
- this.legacyTipsCancelled = false; // retry next run
- this.logger.error({ err: error }, "Error cancelling legacy scheduled tips");
- }
- }
-
// -------------------------------------------------------------------------
// Onboarding pass: users in their first COHORT_DAYS
// -------------------------------------------------------------------------
@@ -768,7 +735,6 @@ class LifecycleEmailService {
this.emailedThisRun = new Set();
const now = DateTime.utc();
try {
- await this.cancelLegacyScheduledTips();
await this.processOnboarding(now);
// The went-quiet scan covers the whole events table (bounded to 7 days);
// hourly is plenty for a 48h-silence alert.