Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Add List-Unsubscribe headers and tokenized per-poll unsubscribe (#3148)
Luke Vellaa3ec09443015
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 7db7cec4f..676c9973f 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -514,6 +514,12 @@"moreOptions": "More options","moreParticipants": "{count, plural, other {# more…}}","muteNotifications": "Mute notifications",+ "mutePollConfirmDescription": "You will stop receiving emails about new responses and comments on <b>{pollTitle}</b>. Your other polls are not affected.",+ "mutePollConfirmTitle": "Mute this poll?",+ "mutePollDoneDescription": "You will no longer receive emails about <b>{pollTitle}</b>. You can unmute it from the poll page.",+ "mutePollDoneTitle": "Poll muted",+ "mutePollGoToPoll": "Go to poll",+ "mutePollManageSettings": "Manage notification settings","name": "Name","namePlaceholder": "Jessie Smith","neverUsed": "Never used",@@ -839,6 +845,9 @@"unexpectedError": "Unexpected error","unlicensed": "Unlicensed","unmuteNotifications": "Unmute notifications",+ "unsubscribeInvalidLinkDescription": "The item it pointed to may have been deleted. You can manage all your email notifications from your <a>notification settings</a>.",+ "unsubscribeInvalidTitle": "This link is no longer valid",+ "unsubscribeTitle": "Unsubscribe","upcoming": "Upcoming","upcomingEventCount": "{count, plural, other {# upcoming}}","upcomingEventsEmptyStateDescription": "When you schedule events, they will appear here.",diff --git a/apps/web/src/app/[locale]/unsubscribe/[token]/components/mute-poll-form.tsx b/apps/web/src/app/[locale]/unsubscribe/[token]/components/mute-poll-form.tsxnew file mode 100644index 000000000..bf6b7a531--- /dev/null+++ b/apps/web/src/app/[locale]/unsubscribe/[token]/components/mute-poll-form.tsx@@ -0,0 +1,101 @@+"use client";++import { buttonVariants } from "@rallly/ui";+import { Button } from "@rallly/ui/button";+import { BellOffIcon } from "lucide-react";+import Link from "next/link";+import React from "react";+import { unsubscribeWithTokenAction } from "@/features/notifications/actions";+import { Trans } from "@/i18n/client";+import { useSafeAction } from "@/lib/safe-action/client";++export function MutePollForm({+ token,+ pollId,+ pollTitle,+ initialMuted,+}: {+ token: string;+ pollId: string;+ pollTitle: string;+ initialMuted: boolean;+}) {+ const [muted, setMuted] = React.useState(initialMuted);+ const unsubscribe = useSafeAction(unsubscribeWithTokenAction, {+ onSuccess: ({ data }) => {+ if (data?.ok) {+ setMuted(true);+ }+ },+ });++ if (muted) {+ return (+ <>+ <div className="mx-auto flex size-10 items-center justify-center rounded-full bg-muted">+ <BellOffIcon className="size-5 text-muted-foreground" />+ </div>+ <div className="space-y-2">+ <h1 className="font-bold text-lg">+ <Trans i18nKey="mutePollDoneTitle" defaults="Poll muted" />+ </h1>+ <p className="text-muted-foreground text-sm">+ <Trans+ i18nKey="mutePollDoneDescription"+ defaults="You will no longer receive emails about <b>{pollTitle}</b>. You can unmute it from the poll page."+ values={{ pollTitle }}+ components={{ b: <strong className="text-foreground" /> }}+ />+ </p>+ </div>+ <div className="flex flex-col gap-2">+ <Link+ href={`/poll/${pollId}`}+ className={buttonVariants({ variant: "primary" })}+ >+ <Trans i18nKey="mutePollGoToPoll" defaults="Go to poll" />+ </Link>+ <Link href="/settings/notifications" className={buttonVariants()}>+ <Trans+ i18nKey="mutePollManageSettings"+ defaults="Manage notification settings"+ />+ </Link>+ </div>+ </>+ );+ }++ return (+ <>+ <div className="space-y-2">+ <h1 className="font-bold text-lg">+ <Trans i18nKey="mutePollConfirmTitle" defaults="Mute this poll?" />+ </h1>+ <p className="text-muted-foreground text-sm">+ <Trans+ i18nKey="mutePollConfirmDescription"+ defaults="You will stop receiving emails about new responses and comments on <b>{pollTitle}</b>. Your other polls are not affected."+ values={{ pollTitle }}+ components={{ b: <strong className="text-foreground" /> }}+ />+ </p>+ </div>+ <div className="flex flex-col gap-2">+ <Button+ variant="primary"+ loading={unsubscribe.isExecuting}+ onClick={() => unsubscribe.execute({ token })}+ >+ <Trans i18nKey="muteNotifications" defaults="Mute notifications" />+ </Button>+ <Link href="/settings/notifications" className={buttonVariants()}>+ <Trans+ i18nKey="mutePollManageSettings"+ defaults="Manage notification settings"+ />+ </Link>+ </div>+ </>+ );+}diff --git a/apps/web/src/app/[locale]/unsubscribe/[token]/page.tsx b/apps/web/src/app/[locale]/unsubscribe/[token]/page.tsxnew file mode 100644index 000000000..465ee6c0f--- /dev/null+++ b/apps/web/src/app/[locale]/unsubscribe/[token]/page.tsx@@ -0,0 +1,68 @@+import { Card } from "@rallly/ui/card";+import type { Metadata } from "next";+import { Trans } from "react-i18next/TransWithoutContext";+import { Logo } from "@/features/branding/components/logo";+import { loadUnsubscribeTarget } from "@/features/notifications/loaders";+import { getTranslation } from "@/i18n/server";+import { MutePollForm } from "./components/mute-poll-form";++export default async function UnsubscribePage({+ params,+}: {+ params: Promise<{ token: string }>;+}) {+ const { token } = await params;+ const { t, i18n } = await getTranslation();+ const target = await loadUnsubscribeTarget(token);++ return (+ <div className="flex min-h-dvh flex-col items-center gap-12 py-12">+ <Logo />+ <main id="main-content" tabIndex={-1} className="w-full max-w-sm px-4">+ <Card className="flex w-full flex-col gap-6 p-8 text-center">+ {target?.kind === "poll" ? (+ <MutePollForm+ token={token}+ pollId={target.poll.id}+ pollTitle={target.poll.title}+ initialMuted={target.poll.muted}+ />+ ) : (+ <>+ <h1 className="font-bold text-lg">+ <Trans+ t={t}+ i18n={i18n}+ ns="app"+ i18nKey="unsubscribeInvalidTitle"+ defaults="This link is no longer valid"+ />+ </h1>+ <p className="text-muted-foreground text-sm">+ <Trans+ t={t}+ i18n={i18n}+ ns="app"+ i18nKey="unsubscribeInvalidLinkDescription"+ defaults="The item it pointed to may have been deleted. You can manage all your email notifications from your <a>notification settings</a>."+ components={{+ a: (+ <a className="text-link" href="/settings/notifications" />+ ),+ }}+ />+ </p>+ </>+ )}+ </Card>+ </main>+ </div>+ );+}++export async function generateMetadata(): Promise<Metadata> {+ const { t } = await getTranslation();+ return {+ title: t("unsubscribeTitle", { defaultValue: "Unsubscribe" }),+ };+}diff --git a/apps/web/src/app/api/unsubscribe/[token]/route.ts b/apps/web/src/app/api/unsubscribe/[token]/route.tsnew file mode 100644index 000000000..21c1146ce--- /dev/null+++ b/apps/web/src/app/api/unsubscribe/[token]/route.ts@@ -0,0 +1,33 @@+import { NextResponse } from "next/server";+import { unsubscribeWithToken } from "@/features/notifications/mutations";++type Context = { params: Promise<{ token: string }> };++/**+ * RFC 8058 one-click unsubscribe target. Mail clients POST here straight from+ * the `List-Unsubscribe` header with no session, so the signed token in the+ * path is the only credential.+ */+export async function POST(_request: Request, { params }: Context) {+ const { token } = await params;+ const result = await unsubscribeWithToken({ token });++ if (!result.ok && result.reason === "invalidToken") {+ return NextResponse.json({ error: "Invalid token" }, { status: 400 });+ }++ // An item that no longer exists (or changed owner) has nothing left to+ // mute; the client's intent is satisfied either way.+ return NextResponse.json({ ok: true });+}++// Clients that open the header link in a browser instead of posting land on+// the confirmation page. Nothing is muted on GET so link prefetchers can't+// trigger it.+export async function GET(request: Request, { params }: Context) {+ const { token } = await params;+ return NextResponse.redirect(+ new URL(`/unsubscribe/${encodeURIComponent(token)}`, request.url),+ 303,+ );+}diff --git a/apps/web/src/features/notifications/actions.ts b/apps/web/src/features/notifications/actions.tsindex 5edf111ee..575a2267e 100644--- a/apps/web/src/features/notifications/actions.ts+++ b/apps/web/src/features/notifications/actions.ts@@ -1,9 +1,15 @@"use server";-import { updateNotificationPreference } from "@/features/notifications/mutations";-import { updateNotificationPreferenceSchema } from "@/features/notifications/schema";+import {+ unsubscribeWithToken,+ updateNotificationPreference,+} from "@/features/notifications/mutations";+import {+ unsubscribeWithTokenSchema,+ updateNotificationPreferenceSchema,+} from "@/features/notifications/schema";import { track } from "@/lib/posthog";-import { authActionClient } from "@/lib/safe-action/server";+import { actionClient, authActionClient } from "@/lib/safe-action/server";export const updateNotificationPreferenceAction = authActionClient.metadata({ actionName: "update_notification_preference" })@@ -23,3 +29,11 @@ export const updateNotificationPreferenceAction = authActionClient},});});++// Public: the signed token is the credential, verified in the mutation.+export const unsubscribeWithTokenAction = actionClient+ .metadata({ actionName: "unsubscribe_with_token" })+ .inputSchema(unsubscribeWithTokenSchema)+ .action(async ({ parsedInput }) => {+ return unsubscribeWithToken({ token: parsedInput.token });+ });diff --git a/apps/web/src/features/notifications/data.ts b/apps/web/src/features/notifications/data.tsindex 10d0c5290..01888aa0a 100644--- a/apps/web/src/features/notifications/data.ts+++ b/apps/web/src/features/notifications/data.ts@@ -87,3 +87,20 @@ export async function getNotificationRecipient({locale: creator.locale,};}++/**+ * The poll an unsubscribe token points at, scoped to the owner the token was+ * issued for so a token can't reveal anything about a poll that changed hands.+ */+export async function getPollMuteTarget({+ pollId,+ userId,+}: {+ pollId: string;+ userId: string;+}) {+ return prisma.poll.findFirst({+ where: { id: pollId, userId, deleted: false },+ select: { id: true, title: true, muted: true },+ });+}diff --git a/apps/web/src/features/notifications/loaders.ts b/apps/web/src/features/notifications/loaders.tsindex b44514391..d1af28cd6 100644--- a/apps/web/src/features/notifications/loaders.ts+++ b/apps/web/src/features/notifications/loaders.ts@@ -1,10 +1,37 @@import "server-only";import { cache } from "react";-import { getNotificationPreferences } from "@/features/notifications/data";+import { env } from "@/env";+import {+ getNotificationPreferences,+ getPollMuteTarget,+} from "@/features/notifications/data";+import { parseUnsubscribeToken } from "@/features/notifications/utils";import { requireUser } from "@/features/user/loaders";export const loadNotificationPreferences = cache(async () => {const user = await requireUser();return getNotificationPreferences(user.id);});++/**+ * Resolves the actor from the unsubscribe token instead of the session: the+ * page is reached from an email and must work without login.+ */+export const loadUnsubscribeTarget = cache(async (token: string) => {+ const target = parseUnsubscribeToken({+ token,+ secret: env.SECRET_PASSWORD,+ });++ if (!target) {+ return null;+ }++ switch (target.kind) {+ case "poll": {+ const poll = await getPollMuteTarget(target);+ return poll ? { kind: "poll" as const, poll } : null;+ }+ }+});diff --git a/apps/web/src/features/notifications/mutations.ts b/apps/web/src/features/notifications/mutations.tsindex b3469bc8b..ce36d7547 100644--- a/apps/web/src/features/notifications/mutations.ts+++ b/apps/web/src/features/notifications/mutations.ts@@ -1,9 +1,12 @@import "server-only";import { Prisma, prisma } from "@rallly/database";+import { env } from "@/env";+import { setPollMuted } from "@/features/poll/mutations";import { defaultNotificationPreferences } from "./constants";import type { ActivityEventType } from "./schema";+import { parseUnsubscribeToken } from "./utils";export async function updateNotificationPreference({userId,@@ -49,3 +52,31 @@ export async function updateNotificationPreference({throw e;}}++/**+ * Mutes whatever a signed unsubscribe token points at. The token is the+ * credential (there is no session on either caller: the one-click POST from a+ * mail client or the confirmation page), so it is verified here rather than+ * in an action gate.+ */+export async function unsubscribeWithToken({ token }: { token: string }) {+ const target = parseUnsubscribeToken({+ token,+ secret: env.SECRET_PASSWORD,+ });++ if (!target) {+ return { ok: false as const, reason: "invalidToken" as const };+ }++ switch (target.kind) {+ case "poll": {+ const result = await setPollMuted({+ pollId: target.pollId,+ userId: target.userId,+ muted: true,+ });+ return result.ok ? { ok: true as const, target } : result;+ }+ }+}diff --git a/apps/web/src/features/notifications/schema.ts b/apps/web/src/features/notifications/schema.tsindex 94608d5d2..4c633f434 100644--- a/apps/web/src/features/notifications/schema.ts+++ b/apps/web/src/features/notifications/schema.ts@@ -21,3 +21,7 @@ export const updateNotificationPreferenceSchema = z.object({});export type NotificationPreferences = Record<ActivityEventType, boolean>;++export const unsubscribeWithTokenSchema = z.object({+ token: z.string().min(1),+});diff --git a/apps/web/src/features/notifications/utils.test.ts b/apps/web/src/features/notifications/utils.test.tsnew file mode 100644index 000000000..8c64de571--- /dev/null+++ b/apps/web/src/features/notifications/utils.test.ts@@ -0,0 +1,62 @@+import { describe, expect, it } from "vitest";+import { createSignature } from "@/lib/signature";+import type { UnsubscribeTarget } from "./utils";+import { createUnsubscribeToken, parseUnsubscribeToken } from "./utils";++const secret = "0123456789abcdef0123456789abcdef";+const target: UnsubscribeTarget = {+ kind: "poll",+ pollId: "poll_123",+ userId: "user_456",+};++function forge(payload: object, signature: string) {+ return `${Buffer.from(JSON.stringify(payload)).toString("base64url")}~${signature}`;+}++describe("unsubscribe token", () => {+ it("round-trips the target", () => {+ const token = createUnsubscribeToken({ target, secret });+ expect(parseUnsubscribeToken({ token, secret })).toEqual(target);+ });++ it("is URL safe and contains no dot", () => {+ const token = createUnsubscribeToken({ target, secret });+ expect(encodeURIComponent(token)).toBe(token);+ expect(token).not.toContain(".");+ });++ it("rejects a token signed with another secret", () => {+ const token = createUnsubscribeToken({ target, secret: "other-secret" });+ expect(parseUnsubscribeToken({ token, secret })).toBeNull();+ });++ it("rejects a tampered payload", () => {+ const [, signature] = createUnsubscribeToken({ target, secret }).split("~");+ const token = forge(+ { k: "poll", p: "poll_other", u: "user_456" },+ signature,+ );+ expect(parseUnsubscribeToken({ token, secret })).toBeNull();+ });++ it("rejects an unknown kind even when correctly signed", () => {+ const payload = Buffer.from(+ JSON.stringify({ k: "sheet", p: "poll_123", u: "user_456" }),+ ).toString("base64url");+ const signature = createSignature({+ context: "unsubscribe",+ payload,+ secret,+ });+ expect(+ parseUnsubscribeToken({ token: `${payload}~${signature}`, secret }),+ ).toBeNull();+ });++ it("rejects malformed tokens", () => {+ for (const token of ["", "abc", "a~b~c", "!!!~???", "bm90LWpzb24~sig"]) {+ expect(parseUnsubscribeToken({ token, secret })).toBeNull();+ }+ });+});diff --git a/apps/web/src/features/notifications/utils.ts b/apps/web/src/features/notifications/utils.tsnew file mode 100644index 000000000..14e7bbd20--- /dev/null+++ b/apps/web/src/features/notifications/utils.ts@@ -0,0 +1,80 @@+import { createSignature, verifySignature } from "@/lib/signature";++const SIGNING_CONTEXT = "unsubscribe";++// Not "." — the proxy matcher treats any dotted path as a static asset and+// skips the locale rewrite, which 404s the confirmation page.+const SEPARATOR = "~";++/**+ * What an unsubscribe token acts on. New notifying entities (sign-up sheets)+ * add a member here; the route and page stay the same.+ */+export type UnsubscribeTarget = {+ kind: "poll";+ pollId: string;+ userId: string;+};++/**+ * A bearer token that lets the recipient mute one item without logging in.+ * It never expires: the email it ships in can sit in an inbox for months, and+ * the worst a leaked token can do is mute something its owner can unmute in+ * the UI.+ */+export function createUnsubscribeToken({+ target,+ secret,+}: {+ target: UnsubscribeTarget;+ secret: string;+}) {+ const payload = Buffer.from(+ JSON.stringify({ k: target.kind, p: target.pollId, u: target.userId }),+ ).toString("base64url");+ const signature = createSignature({+ context: SIGNING_CONTEXT,+ payload,+ secret,+ });+ return `${payload}${SEPARATOR}${signature}`;+}++export function parseUnsubscribeToken({+ token,+ secret,+}: {+ token: string;+ secret: string;+}): UnsubscribeTarget | null {+ const [payload, signature, ...rest] = token.split(SEPARATOR);+ if (+ !payload ||+ !signature ||+ rest.length > 0 ||+ !verifySignature({ context: SIGNING_CONTEXT, payload, secret, signature })+ ) {+ return null;+ }++ try {+ const parsed: unknown = JSON.parse(+ Buffer.from(payload, "base64url").toString(),+ );+ if (+ typeof parsed === "object" &&+ parsed !== null &&+ "k" in parsed &&+ parsed.k === "poll" &&+ "p" in parsed &&+ "u" in parsed &&+ typeof parsed.p === "string" &&+ typeof parsed.u === "string"+ ) {+ return { kind: "poll", pollId: parsed.p, userId: parsed.u };+ }+ } catch {+ // Malformed payload: fall through+ }+ return null;+}diff --git a/apps/web/src/lib/signature.test.ts b/apps/web/src/lib/signature.test.tsnew file mode 100644index 000000000..248a133cd--- /dev/null+++ b/apps/web/src/lib/signature.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from "vitest";+import { createSignature, verifySignature } from "./signature";++const secret = "0123456789abcdef0123456789abcdef";+const input = { context: "test", payload: "hello", secret };++describe("signature", () => {+ it("verifies its own output", () => {+ const signature = createSignature(input);+ expect(verifySignature({ ...input, signature })).toBe(true);+ });++ it("is URL safe", () => {+ const signature = createSignature(input);+ expect(encodeURIComponent(signature)).toBe(signature);+ expect(signature).not.toContain(".");+ });++ it("rejects a different context, payload, or secret", () => {+ const signature = createSignature(input);+ expect(verifySignature({ ...input, signature, context: "other" })).toBe(+ false,+ );+ expect(verifySignature({ ...input, signature, payload: "hellp" })).toBe(+ false,+ );+ expect(+ verifySignature({ ...input, signature, secret: "x".repeat(32) }),+ ).toBe(false);+ });++ it("rejects malformed signatures without throwing", () => {+ for (const signature of ["", "abc", "!!!"]) {+ expect(verifySignature({ ...input, signature })).toBe(false);+ }+ });+});diff --git a/apps/web/src/lib/signature.ts b/apps/web/src/lib/signature.tsnew file mode 100644index 000000000..2f13cb4aa--- /dev/null+++ b/apps/web/src/lib/signature.ts@@ -0,0 +1,40 @@+import crypto from "node:crypto";++/**+ * HMAC-SHA256 over a payload, base64url encoded. `context` is mixed into the+ * signed input so tokens minted for one purpose never verify for another even+ * though every caller shares the same secret.+ */+export function createSignature({+ context,+ payload,+ secret,+}: {+ context: string;+ payload: string;+ secret: string;+}) {+ return crypto+ .createHmac("sha256", secret)+ .update(`${context}:${payload}`)+ .digest("base64url");+}++export function verifySignature({+ context,+ payload,+ secret,+ signature,+}: {+ context: string;+ payload: string;+ secret: string;+ signature: string;+}) {+ const expected = Buffer.from(createSignature({ context, payload, secret }));+ const actual = Buffer.from(signature);+ return (+ expected.length === actual.length &&+ crypto.timingSafeEqual(expected, actual)+ );+}diff --git a/apps/web/src/lib/storage/asset-upload.ts b/apps/web/src/lib/storage/asset-upload.tsindex 3134ca38d..7ed966f27 100644--- a/apps/web/src/lib/storage/asset-upload.ts+++ b/apps/web/src/lib/storage/asset-upload.ts@@ -1,28 +1,26 @@import "server-only";-import crypto from "node:crypto";import { DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";import { getSignedUrl } from "@aws-sdk/s3-request-presigner";import { after } from "next/server";import { env } from "@/env";import { isSelfHosted } from "@/lib/constants";import { AppError } from "@/lib/errors/app-error";+import { createSignature, verifySignature } from "@/lib/signature";import type { AssetProfile } from "./asset-profile";import { extensionByMimeType, parseAssetKey } from "./asset-profile";import { isStorageKey } from "./resolve-storage-url";import { getS3Client } from "./s3";const UPLOAD_TOKEN_TTL_SECONDS = 3600;--function computeSignature(payload: string) {- return crypto- .createHmac("sha256", env.SECRET_PASSWORD)- .update(payload)- .digest("hex");-}+const SIGNING_CONTEXT = "asset-upload";export function signUploadKey(key: string) {const expiry = Math.floor(Date.now() / 1000) + UPLOAD_TOKEN_TTL_SECONDS;- const signature = computeSignature(`${key}:${expiry}`);+ const signature = createSignature({+ context: SIGNING_CONTEXT,+ payload: `${key}:${expiry}`,+ secret: env.SECRET_PASSWORD,+ });return `${expiry}.${signature}`;}@@ -34,13 +32,12 @@ export function verifyUploadToken(key: string, token: string) {if (!Number.isInteger(expiry)) return false;if (expiry <= Math.floor(Date.now() / 1000)) return false;- const expected = computeSignature(`${key}:${expiry}`);- const expectedBuf = Buffer.from(expected, "hex");- const tokenBuf = Buffer.from(signature, "hex");- if (expectedBuf.length === 0 || expectedBuf.length !== tokenBuf.length) {- return false;- }- return crypto.timingSafeEqual(expectedBuf, tokenBuf);+ return verifySignature({+ context: SIGNING_CONTEXT,+ payload: `${key}:${expiry}`,+ secret: env.SECRET_PASSWORD,+ signature,+ });}export async function createAssetUploadUrl({diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.tsindex f3bff56cd..095fa7f65 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -6,7 +6,9 @@ import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";import { getInstanceBranding } from "@/emails/branding";+import { env } from "@/env";import { getNotificationRecipient } from "@/features/notifications/data";+import { createUnsubscribeToken } from "@/features/notifications/utils";import { hasPollAdminAccess } from "@/features/poll/data";import {MAX_COMMENT_AUTHOR_NAME_LENGTH,@@ -154,15 +156,23 @@ export const comments = router({});if (recipient) {+ const unsubscribeToken = createUnsubscribeToken({+ target: { kind: "poll", pollId, userId: recipient.id },+ secret: env.SECRET_PASSWORD,+ });after(async () =>sendNewCommentEmail({to: recipient.email,locale: recipient.locale ?? undefined,branding: await getInstanceBranding(),+ listUnsubscribeUrl: absoluteUrl(+ `/api/unsubscribe/${unsubscribeToken}`,+ ),props: {authorName,content: newComment.content,pollUrl: absoluteUrl(`/poll/${poll.id}`),+ unsubscribeUrl: absoluteUrl(`/unsubscribe/${unsubscribeToken}`),disableNotificationsUrl: absoluteUrl("/settings/notifications"),title: poll.title,},diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.tsindex 0e17471a2..cf8a92191 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -8,7 +8,9 @@ import { TRPCError } from "@trpc/server";import { after } from "next/server";import * as z from "zod";import { getInstanceBranding, getSpaceBranding } from "@/emails/branding";+import { env } from "@/env";import { getNotificationRecipient } from "@/features/notifications/data";+import { createUnsubscribeToken } from "@/features/notifications/utils";import { recordPollActivities } from "@/features/poll/activity/mutations";import { hasPollAdminAccess } from "@/features/poll/data";import { AppError } from "@/lib/errors/app-error";@@ -95,16 +97,23 @@ async function sendNewResponseNotificationEmail({return;}+ const unsubscribeToken = createUnsubscribeToken({+ target: { kind: "poll", pollId, userId: recipient.id },+ secret: env.SECRET_PASSWORD,+ });+await sendNewParticipantEmail({to: recipient.email,locale: recipient.locale ?? undefined,branding: await getInstanceBranding(),replyTo: participantEmail ?? undefined,+ listUnsubscribeUrl: absoluteUrl(`/api/unsubscribe/${unsubscribeToken}`),props: {participantName,note: note ?? undefined,canReply: !!participantEmail,pollUrl: absoluteUrl(`/poll/${pollId}`),+ unsubscribeUrl: absoluteUrl(`/unsubscribe/${unsubscribeToken}`),disableNotificationsUrl: absoluteUrl("/settings/notifications"),title: pollTitle,},diff --git a/apps/web/tests/list-unsubscribe.spec.ts b/apps/web/tests/list-unsubscribe.spec.tsnew file mode 100644index 000000000..5c4f15762--- /dev/null+++ b/apps/web/tests/list-unsubscribe.spec.ts@@ -0,0 +1,143 @@+import type { Browser } from "@playwright/test";+import { expect, test } from "@playwright/test";+import { prisma } from "@rallly/database";+import {+ captureOne,+ deleteAllMessages,+ getMessageHeaders,+} from "@rallly/test-helpers";+import { load } from "cheerio";+import { InvitePage } from "./invite-page";+import { NewPollPage } from "./new-poll-page";+import { createUserInDb, loginWithEmail } from "./test-utils";++/**+ * Owner notification mail carries RFC 8058 one-click unsubscribe headers and+ * a tokenized link. Both mute the poll for the owner without a session.+ */++const OWNER_EMAIL = "[email protected]";+const POLL_TITLE = "List Unsubscribe Poll";++test.describe.configure({ mode: "serial" });++async function cleanup() {+ await prisma.user.deleteMany({ where: { email: OWNER_EMAIL } });+}++async function voteAsGuest(browser: Browser, inviteUrl: string, name: string) {+ const context = await browser.newContext();+ const page = await context.newPage();+ await page.goto(inviteUrl);+ await new InvitePage(page).addParticipant(name);+ await context.close();+}++async function isMuted(pollId: string) {+ const poll = await prisma.poll.findUniqueOrThrow({+ where: { id: pollId },+ select: { muted: true },+ });+ return poll.muted;+}++test.describe("List-Unsubscribe", () => {+ let pollId: string;+ let inviteUrl: string;+ let oneClickUrl: string;+ let pageUrl: string;++ test.beforeAll(async ({ browser }) => {+ await cleanup();+ await deleteAllMessages();+ await createUserInDb({ email: OWNER_EMAIL, name: "Unsubscribe Owner" });++ const page = await browser.newPage();+ await loginWithEmail(page, { email: OWNER_EMAIL });++ const newPollPage = new NewPollPage(page);+ await newPollPage.goto();+ const dialog = await newPollPage.create({ name: POLL_TITLE });+ const pollPage = await dialog.goToPollPage();++ const match = page.url().match(/\/poll\/([a-zA-Z0-9]+)/);+ pollId = match?.[1] ?? "";+ expect(pollId).not.toBe("");++ inviteUrl = await pollPage.copyInviteLink();+ await pollPage.closeDialog();+ await page.close();++ // Drop the login OTP so the first capture is the notification.+ await deleteAllMessages();+ });++ test.afterAll(async () => {+ await cleanup();+ });++ test("notification mail carries one-click headers and a body link", async ({+ browser,+ }) => {+ await voteAsGuest(browser, inviteUrl, "First Voter");++ const { email } = await captureOne(OWNER_EMAIL);+ expect(email.Subject).toBe(`First Voter has responded to ${POLL_TITLE}`);++ const headers = await getMessageHeaders(email.ID);+ const listUnsubscribe = headers["List-Unsubscribe"]?.[0] ?? "";+ expect(listUnsubscribe).toMatch(/^<https?:\/\/.+\/api\/unsubscribe\/.+>$/);+ // The test server is plain http, and RFC 8058 one-click requires https,+ // so the flag must be withheld here. Its emission over https is covered+ // by the send unit test in packages/emails.+ expect(headers["List-Unsubscribe-Post"]).toBeUndefined();+ oneClickUrl = listUnsubscribe.slice(1, -1);++ const $ = load(email.HTML);+ pageUrl = $('a[href*="/unsubscribe/"]').attr("href") ?? "";+ expect(pageUrl).toMatch(/\/unsubscribe\/.+/);+ expect($('a[href*="/settings/notifications"]').length).toBe(1);+ });++ test("confirmation page mutes the poll without a session", async ({+ browser,+ }) => {+ const context = await browser.newContext();+ const page = await context.newPage();+ await page.goto(pageUrl);++ await expect(+ page.getByRole("heading", { name: "Mute this poll?" }),+ ).toBeVisible();+ await page.getByRole("button", { name: "Mute notifications" }).click();+ await expect(+ page.getByRole("heading", { name: "Poll muted" }),+ ).toBeVisible();+ await context.close();++ expect(await isMuted(pollId)).toBe(true);++ // A muted poll sends nothing, so the next test starts from unmuted.+ await prisma.poll.update({ where: { id: pollId }, data: { muted: false } });+ });++ test("one-click POST mutes the poll and stops further mail", async ({+ browser,+ request,+ }) => {+ const response = await request.post(oneClickUrl, {+ form: { "List-Unsubscribe": "One-Click" },+ });+ expect(response.status()).toBe(200);+ expect(await isMuted(pollId)).toBe(true);++ await deleteAllMessages();+ await voteAsGuest(browser, inviteUrl, "Second Voter");+ await expect(captureOne(OWNER_EMAIL, { wait: 3000 })).rejects.toThrow();+ });++ test("a tampered token is rejected", async ({ request }) => {+ const response = await request.post(`${oneClickUrl}x`);+ expect(response.status()).toBe(400);+ });+});diff --git a/packages/emails/locales/en/emails.json b/packages/emails/locales/en/emails.jsonindex 38095d30a..781ba7293 100644--- a/packages/emails/locales/en/emails.json+++ b/packages/emails/locales/en/emails.json@@ -13,7 +13,7 @@"changeEmail_preview": "Your 6-digit code is: {code}","changeEmail_subject": "Verify your new email address","changeEmail_text": "Please use the following 6-digit verification code to confirm your new email address",- "common_disableNotifications": "You can <a>manage your notification settings</a> to stop receiving these emails.",+ "common_notificationFooter": "You can <0>mute this poll</0> or <1>manage your notification settings</1>.","common_poweredBy": "Powered by <a>{domain}</a>","common_viewOn": "View on {domain}","eventCanceledContent": "<b>{hostName}</b> has canceled <b>{title}</b> that was scheduled for:",diff --git a/packages/emails/src/send.test.tsx b/packages/emails/src/send.test.tsxnew file mode 100644index 000000000..9967b9986--- /dev/null+++ b/packages/emails/src/send.test.tsx@@ -0,0 +1,75 @@+import { afterEach, beforeEach, expect, test, vi } from "vitest";++const sendMail = vi.fn(async (_options: unknown) => ({}));++vi.mock("./transport", () => ({+ getTransport: () => ({ sendMail }),+}));++vi.mock("@rallly/logger", () => ({+ createLogger: () => ({ info: vi.fn(), error: vi.fn() }),+}));++const { sendRawEmail } = await import("./send");++const savedSupportEmail = process.env.SUPPORT_EMAIL;++beforeEach(() => {+ sendMail.mockClear();+ process.env.SUPPORT_EMAIL = "[email protected]";+});++afterEach(() => {+ if (savedSupportEmail === undefined) {+ delete process.env.SUPPORT_EMAIL;+ } else {+ process.env.SUPPORT_EMAIL = savedSupportEmail;+ }+});++test("emits one-click unsubscribe headers when a URL is given", async () => {+ await sendRawEmail({+ to: "[email protected]",+ subject: "Hello",+ text: "Hi",+ listUnsubscribeUrl: "https://rallly.co/api/unsubscribe/token",+ });++ expect(sendMail).toHaveBeenCalledTimes(1);+ expect(sendMail.mock.calls[0][0]).toMatchObject({+ headers: {+ "List-Unsubscribe": "<https://rallly.co/api/unsubscribe/token>",+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",+ },+ });+});++test("omits the one-click flag for a non-https URL", async () => {+ await sendRawEmail({+ to: "[email protected]",+ subject: "Hello",+ text: "Hi",+ listUnsubscribeUrl: "http://localhost:3000/api/unsubscribe/token",+ });++ expect(sendMail).toHaveBeenCalledTimes(1);+ expect(sendMail.mock.calls[0][0]).toMatchObject({+ headers: {+ "List-Unsubscribe": "<http://localhost:3000/api/unsubscribe/token>",+ },+ });+ expect(sendMail.mock.calls[0][0]).not.toHaveProperty(+ "headers.List-Unsubscribe-Post",+ );+});++test("omits unsubscribe headers when no URL is given", async () => {+ await sendRawEmail({+ to: "[email protected]",+ subject: "Hello",+ text: "Hi",+ });++ expect(sendMail).toHaveBeenCalledTimes(1);+ expect(sendMail.mock.calls[0][0]).toMatchObject({ headers: undefined });+});diff --git a/packages/emails/src/send.tsx b/packages/emails/src/send.tsxindex 7903c0402..9bd1b36fa 100644--- a/packages/emails/src/send.tsx+++ b/packages/emails/src/send.tsx@@ -21,6 +21,13 @@ export type SendArgs<P> = {replyTo?: string;attachments?: EmailAttachments;icalEvent?: IcalEvent;+ /**+ * HTTPS URL that mutes this kind of mail for the recipient. Emitted as+ * `List-Unsubscribe` + `List-Unsubscribe-Post` (RFC 8058 one-click), which+ * Gmail and Yahoo expect on recurring notification mail. The URL must+ * accept an unauthenticated POST.+ */+ listUnsubscribeUrl?: string;};function resolveFrom(from?: From): From {@@ -41,9 +48,28 @@ type DispatchOptions = {text?: string;attachments?: EmailAttachments;icalEvent?: IcalEvent;+ listUnsubscribeUrl?: string;errorLabel: string;};+function buildHeaders(+ listUnsubscribeUrl?: string,+): Record<string, string> | undefined {+ if (!listUnsubscribeUrl) {+ return undefined;+ }+ // RFC 8058 one-click requires an https URI. A plain-http instance (local+ // dev, self-hosted on a LAN) still gets the mailto-style link header, just+ // not the one-click flag.+ if (!listUnsubscribeUrl.startsWith("https://")) {+ return { "List-Unsubscribe": `<${listUnsubscribeUrl}>` };+ }+ return {+ "List-Unsubscribe": `<${listUnsubscribeUrl}>`,+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",+ };+}+async function dispatch(options: DispatchOptions) {if (!process.env.SUPPORT_EMAIL) {logger.info("SUPPORT_EMAIL not configured - skipping email send");@@ -60,6 +86,7 @@ async function dispatch(options: DispatchOptions) {text: options.text,attachments: options.attachments,icalEvent: options.icalEvent,+ headers: buildHeaders(options.listUnsubscribeUrl),});} catch (e) {// Operational (SMTP/transport) failures are logged, not thrown — sending is@@ -84,6 +111,7 @@ export async function sendRenderedEmail(options: {replyTo?: string;attachments?: EmailAttachments;icalEvent?: IcalEvent;+ listUnsubscribeUrl?: string;}) {const [html, text] = await Promise.all([render(options.element),@@ -99,6 +127,7 @@ export async function sendRenderedEmail(options: {text,attachments: options.attachments,icalEvent: options.icalEvent,+ listUnsubscribeUrl: options.listUnsubscribeUrl,errorLabel: options.subject,});}@@ -112,6 +141,7 @@ export type SendRawEmailOptions = {replyTo?: string;attachments?: EmailAttachments;icalEvent?: IcalEvent;+ listUnsubscribeUrl?: string;};/**diff --git a/packages/emails/src/templates/new-comment.tsx b/packages/emails/src/templates/new-comment.tsxindex 4ec5d4461..5b0f00ca5 100644--- a/packages/emails/src/templates/new-comment.tsx+++ b/packages/emails/src/templates/new-comment.tsx@@ -26,6 +26,7 @@ type NewCommentEmailProps = {authorName: string;content: string;pollUrl: string;+ unsubscribeUrl: string;disableNotificationsUrl: string;};@@ -36,6 +37,7 @@ async function NewCommentEmail({authorName,content,pollUrl,+ unsubscribeUrl,disableNotificationsUrl,locale = "en",chrome,@@ -111,17 +113,22 @@ async function NewCommentEmail({t={t}i18n={i18n}ns="emails"- i18nKey="common_disableNotifications"- defaults="You can <a>manage your notification settings</a> to stop receiving these emails."- components={{- a: (- <Link- color={chrome.primaryColor}- style={{ whiteSpace: "nowrap" }}- href={disableNotificationsUrl}- />- ),- }}+ i18nKey="common_notificationFooter"+ defaults="You can <0>mute this poll</0> or <1>manage your notification settings</1>."+ components={[+ <Link+ key="unsubscribe"+ color={chrome.primaryColor}+ style={{ whiteSpace: "nowrap" }}+ href={unsubscribeUrl}+ />,+ <Link+ key="settings"+ color={chrome.primaryColor}+ style={{ whiteSpace: "nowrap" }}+ href={disableNotificationsUrl}+ />,+ ]}/></Text><PoweredBy chrome={chrome} locale={locale} />@@ -137,6 +144,7 @@ NewCommentEmail.PreviewProps = {content:"Hi everyone! I can make most of these times work, but Tuesday afternoon would be best for me.\nLooking forward to it!",pollUrl: "https://rallly.co",+ unsubscribeUrl: "https://rallly.co",disableNotificationsUrl: "https://rallly.co",locale: "en",chrome: previewChrome,diff --git a/packages/emails/src/templates/new-participant.test.tsx b/packages/emails/src/templates/new-participant.test.tsxindex 471076f21..d80bec3b1 100644--- a/packages/emails/src/templates/new-participant.test.tsx+++ b/packages/emails/src/templates/new-participant.test.tsx@@ -7,6 +7,7 @@ const baseProps = {title: "Team Meeting",participantName: "Jane Doe",pollUrl: "https://rallly.co/poll/abc",+ unsubscribeUrl: "https://rallly.co/unsubscribe/token",disableNotificationsUrl: "https://rallly.co/settings",chrome: previewChrome,};@@ -35,6 +36,12 @@ describe("NewParticipantEmail", () => {expect(html).not.toContain("border-left");});+ it("links both footer actions", async () => {+ const html = await renderEmail();+ expect(html).toContain('href="https://rallly.co/unsubscribe/token"');+ expect(html).toContain('href="https://rallly.co/settings"');+ });+it("shows reply guidance only when a reply address exists", async () => {const withReply = await renderEmail({ note: "A note", canReply: true });expect(withReply).toContain("You can reply to this email");diff --git a/packages/emails/src/templates/new-participant.tsx b/packages/emails/src/templates/new-participant.tsxindex 2383b773b..c4e55f241 100644--- a/packages/emails/src/templates/new-participant.tsx+++ b/packages/emails/src/templates/new-participant.tsx@@ -27,6 +27,7 @@ type NewParticipantEmailProps = {note?: string;canReply?: boolean;pollUrl: string;+ unsubscribeUrl: string;disableNotificationsUrl: string;};@@ -38,6 +39,7 @@ async function NewParticipantEmail({note,canReply,pollUrl,+ unsubscribeUrl,disableNotificationsUrl,locale = "en",chrome,@@ -129,17 +131,22 @@ async function NewParticipantEmail({t={t}i18n={i18n}ns="emails"- i18nKey="common_disableNotifications"- defaults="You can <a>manage your notification settings</a> to stop receiving these emails."- components={{- a: (- <Link- color={chrome.primaryColor}- style={{ whiteSpace: "nowrap" }}- href={disableNotificationsUrl}- />- ),- }}+ i18nKey="common_notificationFooter"+ defaults="You can <0>mute this poll</0> or <1>manage your notification settings</1>."+ components={[+ <Link+ key="unsubscribe"+ color={chrome.primaryColor}+ style={{ whiteSpace: "nowrap" }}+ href={unsubscribeUrl}+ />,+ <Link+ key="settings"+ color={chrome.primaryColor}+ style={{ whiteSpace: "nowrap" }}+ href={disableNotificationsUrl}+ />,+ ]}/></Text><PoweredBy chrome={chrome} locale={locale} />@@ -155,6 +162,7 @@ NewParticipantEmail.PreviewProps = {canReply: true,title: "Untitled Poll",pollUrl: "https://rallly.co",+ unsubscribeUrl: "https://rallly.co",disableNotificationsUrl: "https://rallly.co",locale: "en",chrome: previewChrome,diff --git a/packages/test-helpers/src/index.ts b/packages/test-helpers/src/index.tsindex 925783487..a68aeec3b 100644--- a/packages/test-helpers/src/index.ts+++ b/packages/test-helpers/src/index.ts@@ -6,6 +6,7 @@ export {deleteAllMessages,getAttachmentText,getMessage,+ getMessageHeaders,getMessages,type MailpitAttachment,type MailpitEmailAddress,diff --git a/packages/test-helpers/src/mailpit.ts b/packages/test-helpers/src/mailpit.tsindex 6979da87c..627b020e1 100644--- a/packages/test-helpers/src/mailpit.ts+++ b/packages/test-helpers/src/mailpit.ts@@ -108,6 +108,15 @@ export async function captureOne(throw new Error(`No email received for ${to} within ${timeout}ms`);}+export async function getMessageHeaders(+ messageId: string,+): Promise<Record<string, string[]>> {+ const response = await fetch(+ `${MAILPIT_API_URL}/v1/message/${messageId}/headers`,+ );+ return (await response.json()) as Record<string, string[]>;+}+export async function getAttachmentText(messageId: string,partId: string,