Skip to content

Open source CapCut alternative.

TypeScript

feat(site): add email unsubscribe endpoints and a preferences toggle

David Led6dd82498800
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index 47b255d2..82c66c1b 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -6,8 +6,9 @@ third-party Vision API developers, who authenticate with an API key.
**The one rule:** every route handler is wrapped in `withDonkeyAuth`. A public
endpoint is a deliberate exception with a product reason — today only Better
-Auth's own routes, the signature-verified Stripe webhook, and a plain health
-check. Ship a handler without the wrapper and the endpoint is open to anyone.
+Auth's own routes, the signature-verified Stripe and Resend webhooks, the
+HMAC-token-verified one-click email unsubscribe, and a plain health check. Ship
+a handler without the wrapper and the endpoint is open to anyone.
## Authentication
diff --git a/site/src/app/api/account/email-preferences/route.ts b/site/src/app/api/account/email-preferences/route.ts
new file mode 100644
index 00000000..bf326e6d
--- /dev/null
+++ b/site/src/app/api/account/email-preferences/route.ts
@@ -0,0 +1,39 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+
+import {
+ withDonkeyAuth,
+ type DonkeyAuthenticatedRequest,
+} from "@/lib/donkey-api-auth";
+import {
+ isMarketingUnsubscribed,
+ setMarketingUnsubscribed,
+} from "@/lib/email/unsubscribe";
+
+export const dynamic = "force-dynamic";
+
+export const GET = withDonkeyAuth(
+ async (request: DonkeyAuthenticatedRequest) => {
+ return NextResponse.json({
+ marketingEmails: !(await isMarketingUnsubscribed(request.donkey.userId)),
+ });
+ },
+);
+
+const updateSchema = z.object({ marketingEmails: z.boolean() });
+
+export const PUT = withDonkeyAuth(
+ async (request: DonkeyAuthenticatedRequest) => {
+ const parsed = updateSchema.safeParse(
+ await request.json().catch(() => null),
+ );
+ if (!parsed.success) {
+ return NextResponse.json({ error: "Invalid request." }, { status: 400 });
+ }
+ await setMarketingUnsubscribed(
+ request.donkey.userId,
+ !parsed.data.marketingEmails,
+ );
+ return NextResponse.json({ marketingEmails: parsed.data.marketingEmails });
+ },
+);
diff --git a/site/src/app/api/email/resend-webhook/route.ts b/site/src/app/api/email/resend-webhook/route.ts
new file mode 100644
index 00000000..34dfed6b
--- /dev/null
+++ b/site/src/app/api/email/resend-webhook/route.ts
@@ -0,0 +1,59 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { Webhook } from "svix";
+import { z } from "zod";
+
+import { unauthorizedResponse } from "@/lib/donkey-api-auth";
+import { setMarketingUnsubscribed } from "@/lib/email/unsubscribe";
+import { prisma } from "@/lib/prisma";
+
+export const dynamic = "force-dynamic";
+
+// The one event this app consumes: an unsubscribe (or resubscribe) made on
+// Resend's side — a broadcast footer link or a dashboard edit — flows back
+// into the account's own preference row. Everything else acknowledges as a
+// no-op so enabling more events in the dashboard never errors.
+const contactUpdatedSchema = z.object({
+ data: z.object({
+ email: z.string().email(),
+ unsubscribed: z.boolean(),
+ }),
+ type: z.literal("contact.updated"),
+});
+
+// Public exception to withDonkeyAuth (docs/guides/backend-apis.md): Resend
+// calls this endpoint directly. Every request is Svix-signature-verified
+// against RESEND_WEBHOOK_SECRET before it is read.
+export async function POST(request: NextRequest) {
+ const secret = process.env.RESEND_WEBHOOK_SECRET;
+ if (!secret) {
+ return unauthorizedResponse();
+ }
+
+ const payload = await request.text();
+ let event: unknown;
+ try {
+ event = new Webhook(secret).verify(payload, {
+ "svix-id": request.headers.get("svix-id") ?? "",
+ "svix-signature": request.headers.get("svix-signature") ?? "",
+ "svix-timestamp": request.headers.get("svix-timestamp") ?? "",
+ });
+ } catch {
+ return unauthorizedResponse();
+ }
+
+ const parsed = contactUpdatedSchema.safeParse(event);
+ if (!parsed.success) {
+ return NextResponse.json({ ok: true });
+ }
+
+ const user = await prisma.user.findUnique({
+ select: { id: true },
+ where: { email: parsed.data.data.email },
+ });
+ if (user) {
+ await setMarketingUnsubscribed(user.id, parsed.data.data.unsubscribed, {
+ mirrorToResend: false,
+ });
+ }
+ return NextResponse.json({ ok: true });
+}
diff --git a/site/src/app/api/email/unsubscribe/route.ts b/site/src/app/api/email/unsubscribe/route.ts
new file mode 100644
index 00000000..0729daf8
--- /dev/null
+++ b/site/src/app/api/email/unsubscribe/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { z } from "zod";
+
+import { unauthorizedResponse } from "@/lib/donkey-api-auth";
+import {
+ setMarketingUnsubscribed,
+ verifyUnsubscribeToken,
+} from "@/lib/email/unsubscribe";
+
+export const dynamic = "force-dynamic";
+
+const querySchema = z.object({ token: z.string().min(1).max(512) });
+
+// Public exception to withDonkeyAuth (docs/guides/backend-apis.md): RFC 8058
+// one-click unsubscribe arrives as a bare POST from the recipient's mail
+// provider, with no session. The signed token in the URL is the authorization,
+// and the /unsubscribe page posts here too.
+export async function POST(request: NextRequest) {
+ const parsed = querySchema.safeParse(
+ Object.fromEntries(request.nextUrl.searchParams),
+ );
+ if (!parsed.success) {
+ return unauthorizedResponse();
+ }
+ const userId = verifyUnsubscribeToken(parsed.data.token);
+ if (!userId) {
+ return unauthorizedResponse();
+ }
+ await setMarketingUnsubscribed(userId, true);
+ return NextResponse.json({ ok: true });
+}
diff --git a/site/src/app/cut/app/(home)/settings/profile/EmailSection.tsx b/site/src/app/cut/app/(home)/settings/profile/EmailSection.tsx
new file mode 100644
index 00000000..fa2c7c72
--- /dev/null
+++ b/site/src/app/cut/app/(home)/settings/profile/EmailSection.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { Switch } from "@/components/ui/switch";
+import {
+ useEmailPreferences,
+ useSetEmailPreferences,
+} from "@/queries/emailPreferences";
+
+// The account's email choice: product news on or off. Transactional email
+// (billing, security) is unaffected. This is also the way back in after an
+// unsubscribe from an email footer.
+export function EmailSection() {
+ const { data: prefs } = useEmailPreferences();
+ const set = useSetEmailPreferences();
+
+ if (!prefs) return null;
+
+ return (
+ <div className="rounded-xl border bg-card p-5">
+ <div className="text-sm font-medium">Email preferences</div>
+ <div className="mt-4 border-t pt-4">
+ <div className="flex items-start justify-between gap-6">
+ <span className="min-w-0">
+ <span className="block text-sm font-medium">Product emails</span>
+ <span className="mt-0.5 block text-sm text-muted-foreground">
+ News and announcements about Donkey Cut.
+ </span>
+ </span>
+ <Switch
+ aria-label="Product emails"
+ checked={prefs.marketingEmails}
+ onCheckedChange={(v) => set.mutate({ marketingEmails: v === true })}
+ />
+ </div>
+ {set.isError && (
+ <p className="mt-3 text-sm text-red-600">
+ Couldn&apos;t save that change — try again.
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/site/src/app/cut/app/(home)/settings/profile/page.tsx b/site/src/app/cut/app/(home)/settings/profile/page.tsx
index d624d4b0..23c14a40 100644
--- a/site/src/app/cut/app/(home)/settings/profile/page.tsx
+++ b/site/src/app/cut/app/(home)/settings/profile/page.tsx
@@ -4,6 +4,7 @@ import { useState } from "react";
import { Pencil } from "lucide-react";
import { AvatarDialog } from "@/app/cut/app/(home)/settings/profile/AvatarDialog";
+import { EmailSection } from "@/app/cut/app/(home)/settings/profile/EmailSection";
import { FeatureFlagsSection } from "@/app/cut/app/(home)/settings/profile/FeatureFlagsSection";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -98,6 +99,8 @@ export default function CutProfilePage() {
</div>
</div>
+ <EmailSection />
+
<FeatureFlagsSection />
<AvatarDialog
diff --git a/site/src/app/unsubscribe/UnsubscribeConfirm.tsx b/site/src/app/unsubscribe/UnsubscribeConfirm.tsx
new file mode 100644
index 00000000..fc9bf036
--- /dev/null
+++ b/site/src/app/unsubscribe/UnsubscribeConfirm.tsx
@@ -0,0 +1,49 @@
+"use client";
+
+import { useState } from "react";
+
+// One button between the email link and the unsubscribe, posting to the same
+// endpoint mail providers use for one-click.
+export function UnsubscribeConfirm({ token }: { token: string }) {
+ const [state, setState] = useState<"idle" | "pending" | "done" | "error">(
+ "idle",
+ );
+
+ const unsubscribe = async () => {
+ setState("pending");
+ const response = await fetch(
+ `/api/email/unsubscribe?token=${encodeURIComponent(token)}`,
+ { method: "POST" },
+ );
+ setState(response.ok ? "done" : "error");
+ };
+
+ if (state === "done") {
+ return (
+ <p>
+ You&apos;re unsubscribed from product emails. You can turn them back on
+ any time from Settings in the app.
+ </p>
+ );
+ }
+
+ return (
+ <>
+ <p>
+ Stop receiving product news and announcements from Donkey Cut? Emails
+ about your account, like billing and security, keep arriving either way.
+ </p>
+ <button
+ type="button"
+ onClick={unsubscribe}
+ disabled={state === "pending"}
+ className="cursor-pointer rounded-lg bg-[#0F0E0D] px-6 py-3 text-sm font-semibold text-[#F5EFE0] disabled:opacity-60"
+ >
+ Unsubscribe
+ </button>
+ {state === "error" && (
+ <p className="text-red-600">That didn&apos;t go through — try again.</p>
+ )}
+ </>
+ );
+}
diff --git a/site/src/app/unsubscribe/page.tsx b/site/src/app/unsubscribe/page.tsx
new file mode 100644
index 00000000..1a7c8704
--- /dev/null
+++ b/site/src/app/unsubscribe/page.tsx
@@ -0,0 +1,30 @@
+import { LegalPageShell } from "@/app/legal/LegalPageShell";
+import { UnsubscribeConfirm } from "@/app/unsubscribe/UnsubscribeConfirm";
+import { verifyUnsubscribeToken } from "@/lib/email/unsubscribe";
+
+// Where the unsubscribe link in an email footer lands. The token is verified
+// here, but the actual unsubscribe waits for a button press: link-prefetching
+// mail scanners open URLs on the recipient's behalf, and a GET that
+// unsubscribed on load would let them opt people out.
+export default async function UnsubscribePage({
+ searchParams,
+}: {
+ searchParams: Promise<{ token?: string }>;
+}) {
+ const { token } = await searchParams;
+ const userId = token ? verifyUnsubscribeToken(token) : null;
+
+ return (
+ <LegalPageShell>
+ <h1>Email preferences</h1>
+ {userId && token ? (
+ <UnsubscribeConfirm token={token} />
+ ) : (
+ <p>
+ This link is no longer valid. You can manage product emails from
+ Settings in the app.
+ </p>
+ )}
+ </LegalPageShell>
+ );
+}
diff --git a/site/src/proxy.ts b/site/src/proxy.ts
index dee35474..070d02a7 100644
--- a/site/src/proxy.ts
+++ b/site/src/proxy.ts
@@ -64,6 +64,8 @@ const PASSTHROUGH = [
"/sign-in",
"/sign-up",
"/donkeyvision",
+ // Email-footer unsubscribe page.
+ "/unsubscribe",
];
// Whole-segment prefix match, so "/cut" covers "/cut/…" but not "/cut-app".
diff --git a/site/src/queries/emailPreferences.ts b/site/src/queries/emailPreferences.ts
new file mode 100644
index 00000000..a5090833
--- /dev/null
+++ b/site/src/queries/emailPreferences.ts
@@ -0,0 +1,33 @@
+"use client";
+
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+
+import { apiFetch } from "@/queries/apiClient";
+
+export const emailPreferencesQueryKey = ["account-email-preferences"] as const;
+
+export type EmailPreferences = {
+ marketingEmails: boolean;
+};
+
+export function useEmailPreferences() {
+ return useQuery({
+ queryFn: () =>
+ apiFetch<EmailPreferences>("/api/account/email-preferences"),
+ queryKey: emailPreferencesQueryKey,
+ });
+}
+
+export function useSetEmailPreferences() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (update: EmailPreferences) =>
+ apiFetch<EmailPreferences>("/api/account/email-preferences", {
+ body: JSON.stringify(update),
+ method: "PUT",
+ }),
+ onSuccess: (prefs) => {
+ queryClient.setQueryData(emailPreferencesQueryKey, prefs);
+ },
+ });
+}