Skip to content

Open source CapCut alternative.

TypeScript

refactor(site): the accounts table is the only marketing list

David Le1832981a56ef
diff --git a/site/.env.example b/site/.env.example
index 7fcb2f32..24697856 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -39,18 +39,15 @@ STRIPE_WEBHOOK_SECRET="replace-with-stripe-webhook-signing-secret"
STRIPE_PRO_PRICE_ID="replace-with-stripe-pro-price-id"
STRIPE_PORTAL_CONFIGURATION_ID="replace-with-stripe-portal-configuration-id"
-# Resend (transactional email + contact sync). Unset in dev skips email work:
-# signups log the skip and provision everything else. The from address is code
-# (src/lib/email/resend.ts). RESEND_WEBHOOK_SECRET signs the contact.updated
-# webhook at /api/email/resend-webhook, from the endpoint's page in the Resend
-# dashboard. RESEND_REGISTERED_USERS_SEGMENT_ID is the segment signups join
-# (Segments → "Registered Users" — the id in the segment page's URL).
+# Resend (email sending). Unset in dev skips email work: signups log the skip
+# and provision everything else. RESEND_WEBHOOK_SECRET signs the
+# email.received webhook at /api/email/resend-webhook, from the endpoint's
+# page in the Resend dashboard.
RESEND_API_KEY="replace-with-resend-api-key"
RESEND_WEBHOOK_SECRET="replace-with-resend-webhook-signing-secret"
-RESEND_REGISTERED_USERS_SEGMENT_ID="replace-with-resend-segment-id"
# The sending identity, on the Resend-verified domain.
RESEND_FROM_EMAIL="Sender Name <[email protected]>"
-# The sender for list mail — the welcome email and dashboard broadcasts — on a
+# The sender for list mail — the welcome email and promotions — on a
# Resend-verified subdomain. A mail provider keeps one reputation record per
# signing domain, so bulk sends get their own and the apex above stays the
# address a person writes from. Unset falls back to RESEND_FROM_EMAIL.
diff --git a/site/scripts/backfill-resend-contacts.ts b/site/scripts/backfill-resend-contacts.ts
deleted file mode 100644
index 94f8f014..00000000
--- a/site/scripts/backfill-resend-contacts.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-#!/usr/bin/env bun
-/**
- * One-off: push every existing account into Resend as a contact (new signups
- * sync on creation). Accounts that already opted out are created unsubscribed.
- * Idempotent — an existing contact is left as-is — so the script can re-run.
- *
- * Run from site/ with production credentials in the environment:
- * bun run scripts/backfill-resend-contacts.ts
- */
-
-import { syncResendContact } from "../src/lib/email/sync-contact";
-import { prisma } from "../src/lib/prisma";
-
-const PAGE_SIZE = 100;
-
-let synced = 0;
-let failed = 0;
-let cursor: string | undefined;
-
-for (;;) {
- const users = await prisma.user.findMany({
- ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
- orderBy: { id: "asc" },
- select: {
- email: true,
- emailSettings: { select: { marketingUnsubscribedAt: true } },
- id: true,
- name: true,
- },
- take: PAGE_SIZE,
- });
- if (users.length === 0) break;
- cursor = users[users.length - 1].id;
-
- for (const user of users) {
- try {
- await syncResendContact(user, {
- unsubscribed: user.emailSettings?.marketingUnsubscribedAt != null,
- });
- synced += 1;
- } catch (error) {
- failed += 1;
- console.error("[backfill] contact sync failed", { error, userId: user.id });
- }
- }
- console.log(`[backfill] ${synced} synced, ${failed} failed…`);
-}
-
-console.log(`[backfill] done: ${synced} synced, ${failed} failed`);
-await prisma.$disconnect();
diff --git a/site/src/app/api/email/resend-webhook/route.ts b/site/src/app/api/email/resend-webhook/route.ts
index a71d0bdc..c71947ff 100644
--- a/site/src/app/api/email/resend-webhook/route.ts
+++ b/site/src/app/api/email/resend-webhook/route.ts
@@ -3,24 +3,12 @@ import { Webhook } from "svix";
import { z } from "zod";
import { unauthorizedResponse } from "@/lib/donkey-api-auth";
-import { setMarketingUnsubscribed } from "@/lib/email/unsubscribe";
import { forwardOutreachReply } from "@/lib/marketing/forward-reply";
-import { prisma } from "@/lib/prisma";
-
-// Two events 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. A received email is a reply to an
-// outreach note, which files itself against its row and forwards on.
-// 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"),
-});
+// One event this app consumes: a received email is a reply to an outreach
+// note, which files itself against its row and forwards on. Everything else
+// acknowledges as a no-op so enabling more events in the dashboard never
+// errors.
const emailReceivedSchema = z.object({
data: z.object({
email_id: z.string(),
@@ -56,22 +44,6 @@ export async function POST(request: NextRequest) {
const received = emailReceivedSchema.safeParse(event);
if (received.success) {
await forwardOutreachReply(received.data.data);
- return NextResponse.json({ ok: true });
- }
-
- 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/lib/email/resend.ts b/site/src/lib/email/resend.ts
index e555d5d3..5b1ea66e 100644
--- a/site/src/lib/email/resend.ts
+++ b/site/src/lib/email/resend.ts
@@ -6,22 +6,15 @@ export function emailFrom(): string {
return process.env.RESEND_FROM_EMAIL ?? "";
}
-// Who list mail comes from: the welcome email, and the broadcasts sent from
-// the Resend dashboard. A mail provider keeps one reputation record per
-// signing domain, so bulk sends get a subdomain of their own and the apex in
-// RESEND_FROM_EMAIL stays the address a person writes from. Unset falls back
-// to that shared sender, which puts both streams on one domain.
+// Who list mail comes from: the welcome email and promotions. A mail
+// provider keeps one reputation record per signing domain, so bulk sends get
+// a subdomain of their own and the apex in RESEND_FROM_EMAIL stays the
+// address a person writes from. Unset falls back to that shared sender, which
+// puts both streams on one domain.
export function bulkFrom(): string {
return process.env.RESEND_BULK_FROM_EMAIL || emailFrom();
}
-// The Resend segment every account joins at signup, so broadcasts have one
-// list to target: Segments → "Registered Users" in the dashboard. Empty skips
-// the segment step — contacts are still created.
-export function registeredUsersSegmentId(): string {
- return process.env.RESEND_REGISTERED_USERS_SEGMENT_ID ?? "";
-}
-
// What every email path needs to know about an account.
/** One message as the provider takes it. */
export type EmailMessage = Parameters<Resend["emails"]["send"]>[0];
diff --git a/site/src/lib/email/sync-contact.ts b/site/src/lib/email/sync-contact.ts
deleted file mode 100644
index 4c77750b..00000000
--- a/site/src/lib/email/sync-contact.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import {
- getResend,
- isResendConfigured,
- registeredUsersSegmentId,
- type EmailUser,
-} from "@/lib/email/resend";
-
-// Projects an account into Resend: a global contact, added to the segment
-// broadcasts target. Postgres stays the source of truth — this copy exists so
-// announcements can be sent as Resend Broadcasts, which handle per-recipient
-// unsubscribe links and suppression on their own. Idempotent: an existing
-// contact is left as-is and re-adding to a segment is a no-op, so signup
-// retries and the backfill script can both re-run it.
-export async function syncResendContact(
- user: EmailUser,
- { unsubscribed = false }: { unsubscribed?: boolean } = {},
-): Promise<void> {
- if (!isResendConfigured()) {
- console.log("[email] RESEND_API_KEY not set; skipping contact sync", {
- userId: user.id,
- });
- return;
- }
-
- const resend = getResend();
- const [firstName, ...rest] = user.name.trim().split(/\s+/);
- const created = await resend.contacts.create({
- email: user.email,
- firstName: firstName || undefined,
- lastName: rest.join(" ") || undefined,
- unsubscribed,
- });
- // An already-existing contact fails creation but must still reach the
- // segment; a real failure (bad key, outage) repeats on the segment call
- // below and throws there.
- if (created.error) {
- console.log("[email] contact create skipped", {
- error: created.error.name,
- userId: user.id,
- });
- }
-
- const segmentId = registeredUsersSegmentId();
- if (!segmentId) {
- console.warn(
- "[email] RESEND_REGISTERED_USERS_SEGMENT_ID is unset; contact not added to a segment",
- { userId: user.id },
- );
- return;
- }
- const added = await resend.contacts.segments.add({
- email: user.email,
- segmentId,
- });
- if (added.error) {
- throw new Error(
- `Resend segment add failed: ${added.error.name}: ${added.error.message}`,
- );
- }
-}
diff --git a/site/src/lib/email/unsubscribe.ts b/site/src/lib/email/unsubscribe.ts
index aa8a33c0..6f6a6d44 100644
--- a/site/src/lib/email/unsubscribe.ts
+++ b/site/src/lib/email/unsubscribe.ts
@@ -1,7 +1,6 @@
import { createHmac, timingSafeEqual } from "node:crypto";
import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
-import { getResend, isResendConfigured } from "@/lib/email/resend";
import { prisma } from "@/lib/prisma";
// Unsubscribe links authenticate with an HMAC over the userId, keyed by a
@@ -48,23 +47,12 @@ export function unsubscribeActionUrl(userId: string): string {
return `${DONKEYCUT_CANONICAL}/api/email/unsubscribe?token=${unsubscribeToken(userId)}`;
}
-type SetUnsubscribedOptions = {
- // The Resend webhook passes false: the change came from Resend, so echoing
- // it back would loop.
- mirrorToResend?: boolean;
-};
-
-// The database row is authoritative; the Resend contact mirror is best-effort,
-// so a Resend outage can never block the user's choice. A missing user (deleted
-// account, dev-bypass caller) is a quiet no-op — unsubscribing is idempotent by
-// contract.
-export async function setMarketingUnsubscribed(
- userId: string,
- unsubscribed: boolean,
- { mirrorToResend = true }: SetUnsubscribedOptions = {},
-): Promise<void> {
+// The database row is the record every marketing send reads. A missing user
+// (deleted account, dev-bypass caller) is a quiet no-op — unsubscribing is
+// idempotent by contract.
+export async function setMarketingUnsubscribed(userId: string, unsubscribed: boolean): Promise<void> {
const user = await prisma.user.findUnique({
- select: { email: true },
+ select: { id: true },
where: { id: userId },
});
if (!user) {
@@ -77,20 +65,6 @@ export async function setMarketingUnsubscribed(
update: { marketingUnsubscribedAt },
where: { userId },
});
-
- if (!mirrorToResend || !isResendConfigured()) {
- return;
- }
- const { error } = await getResend().contacts.update({
- email: user.email,
- unsubscribed,
- });
- if (error) {
- console.error("[email] failed to mirror unsubscribe state to Resend", {
- error,
- userId,
- });
- }
}
// Gate for non-essential sends. Transactional and security email skips it;
diff --git a/site/src/lib/jobs/delete-user.ts b/site/src/lib/jobs/delete-user.ts
index 65b59595..3d4ccb5d 100644
--- a/site/src/lib/jobs/delete-user.ts
+++ b/site/src/lib/jobs/delete-user.ts
@@ -5,15 +5,14 @@ import { deleteLibraryAssetCascade } from "@/cut/server/cloud/library";
import { deleteProjectCascade } from "@/cut/server/cloud/projects";
import { deletePrefix, INFERENCE_PREFIX, R2NotConfiguredError } from "@/cut/server/cloud/r2";
import { getStripe, StripeNotConfiguredError } from "@/lib/billing/stripe";
-import { getResend, isResendConfigured } from "@/lib/email/resend";
import { defineJob, JobFailure } from "@/lib/jobs/registry";
import { deletedAccountKey } from "@/lib/onboarding/deleted-account";
import { prisma } from "@/lib/prisma";
// Deletes an account and everything it owns. Order matters: the Stripe
// customer goes first (deleting it cancels any live subscription, so a crash
-// mid-job can never leave a paying customer with no account), then the Resend
-// contact, then the Cut cloud content — per-project and per-asset cascades,
+// mid-job can never leave a paying customer with no account), then the Cut
+// cloud content — per-project and per-asset cascades,
// which also clear R2 objects and HLS ladder records — then the user-keyed
// rows that carry no foreign key, an R2 sweep of anything left under the
// user's prefixes, then the record the address leaves behind so a second
@@ -38,15 +37,6 @@ export const deleteUserJob = defineJob(
}
}
- if (isResendConfigured()) {
- const removed = await getResend().contacts.remove({ email: user.email });
- if (removed.error && removed.error.name !== "not_found") {
- throw new Error(
- `Resend contact remove failed: ${removed.error.name}: ${removed.error.message}`,
- );
- }
- }
-
const projects = await prisma.cutProject.findMany({
where: { userId: user.id },
select: { id: true },
diff --git a/site/src/lib/onboarding/signup-grants.ts b/site/src/lib/onboarding/signup-grants.ts
index 0b32477d..5f71a0cf 100644
--- a/site/src/lib/onboarding/signup-grants.ts
+++ b/site/src/lib/onboarding/signup-grants.ts
@@ -7,7 +7,6 @@ import { creditGrantExpiry } from "@/lib/credits/top-up";
import { type EmailUser } from "@/lib/email/resend";
import { deliverEmail } from "@/lib/email/outbox";
import { welcomeIdempotencyKey } from "@/lib/email/send-welcome";
-import { syncResendContact } from "@/lib/email/sync-contact";
import { isDeletedAddress } from "@/lib/onboarding/deleted-account";
// Single source of truth for what a new account starts with. All steps are
@@ -37,7 +36,6 @@ export async function provisionSignupGrants(user: EmailUser): Promise<void> {
seedStarterProject(user.id),
seedFontsFolder(user.id),
deliverEmail({ idempotencyKey: welcomeIdempotencyKey(user.id), kind: "welcome", payload: { credits }, userId: user.id }),
- syncResendContact(user),
]);
for (const result of results) {