Skip to content

Open source CapCut alternative.

TypeScript

feat(site): outreach replies file themselves and forward to an inbox

David Le4765e105014e
diff --git a/site/.env.example b/site/.env.example
index f95b0f08..dbfcc1c6 100644
--- a/site/.env.example
+++ b/site/.env.example
@@ -51,6 +51,12 @@ 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]>"
+# Where a reply to an outreach note is forwarded so it can be answered from a
+# normal inbox, with the user's own address as the reply-to. A bare address —
+# it is a recipient, not a sending identity. Unset skips the forward; the row
+# is still marked replied. Needs the reply subdomain set up as a Resend
+# receiving domain and email.received enabled on the webhook.
+RESEND_INBOX_EMAIL="[email protected]"
# PostHog analytics (client-side project key; public by design, inlined at build).
# Leave unset to disable tracking (e.g. local dev).
diff --git a/site/src/app/api/email/resend-webhook/route.ts b/site/src/app/api/email/resend-webhook/route.ts
index 263db7d0..a71d0bdc 100644
--- a/site/src/app/api/email/resend-webhook/route.ts
+++ b/site/src/app/api/email/resend-webhook/route.ts
@@ -4,12 +4,15 @@ 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";
-// The one event this app consumes: an unsubscribe (or resubscribe) made on
+// 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. Everything else acknowledges as a
-// no-op so enabling more events in the dashboard never errors.
+// 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(),
@@ -18,6 +21,17 @@ const contactUpdatedSchema = z.object({
type: z.literal("contact.updated"),
});
+const emailReceivedSchema = z.object({
+ data: z.object({
+ email_id: z.string(),
+ from: z.string(),
+ received_for: z.array(z.string()).default([]),
+ subject: z.string().default(""),
+ to: z.array(z.string()).default([]),
+ }),
+ type: z.literal("email.received"),
+});
+
// 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.
@@ -39,6 +53,12 @@ export async function POST(request: NextRequest) {
return unauthorizedResponse();
}
+ 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 });
diff --git a/site/src/lib/marketing/forward-reply.ts b/site/src/lib/marketing/forward-reply.ts
new file mode 100644
index 00000000..0efe3bd6
--- /dev/null
+++ b/site/src/lib/marketing/forward-reply.ts
@@ -0,0 +1,116 @@
+import { emailFrom, getResend, isResendConfigured } from "@/lib/email/resend";
+import { outreachIdFromRecipients } from "@/lib/marketing/replyAddress";
+import { prisma } from "@/lib/prisma";
+
+// Where a reply is forwarded so it can be answered from a normal inbox. Env
+// rather than code for the same reason RESEND_FROM_EMAIL is: the open-source
+// repo carries no personal address.
+function outreachInbox(): string {
+ return process.env.RESEND_INBOX_EMAIL ?? "";
+}
+
+// The banner names the account, and an account's display name is whatever
+// Google handed us — it reaches the operator's inbox as markup otherwise.
+function escapeHtml(value: string): string {
+ return value
+ .replace(/&/g, "&amp;")
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
+ .replace(/"/g, "&quot;");
+}
+
+type ReceivedEmail = {
+ email_id: string;
+ from: string;
+ to: string[];
+ received_for: string[];
+ subject: string;
+};
+
+// Handles an inbound reply to an outreach note: flips the row to replied and
+// forwards the message on so it can be answered from a normal inbox. The
+// forward goes out as a fresh send rather than Resend's own forward call
+// because only a send takes a reply-to — that is what makes hitting reply in
+// the inbox address the user instead of looping back into the reply domain.
+//
+// Nothing about the message is written down. Body, subject, and attachments
+// travel from Resend through this function to the inbox and stop there.
+export async function forwardOutreachReply(email: ReceivedEmail): Promise<boolean> {
+ const outreachId = outreachIdFromRecipients(email.received_for, email.to);
+ if (!outreachId) {
+ return false;
+ }
+ const outreach = await prisma.userOutreach.findUnique({
+ select: { id: true, repliedAt: true, user: { select: { email: true, name: true } } },
+ where: { id: outreachId },
+ });
+ if (!outreach) {
+ return false;
+ }
+
+ // Keep the first reply's timestamp; a later one in the same thread only
+ // confirms the status.
+ await prisma.userOutreach.update({
+ data: { repliedAt: outreach.repliedAt ?? new Date(), status: "replied" },
+ where: { id: outreach.id },
+ });
+
+ const inbox = outreachInbox();
+ const from = emailFrom();
+ if (!isResendConfigured() || !inbox || !from) {
+ console.warn("[outreach] reply not forwarded; inbox or sender unconfigured", {
+ outreachId: outreach.id,
+ });
+ return true;
+ }
+
+ const resend = getResend();
+ const received = await resend.emails.receiving.get(email.email_id);
+ if (received.error || !received.data) {
+ throw new Error(
+ `Resend inbound fetch failed: ${received.error?.name}: ${received.error?.message}`,
+ );
+ }
+
+ const attachments = await Promise.all(
+ received.data.attachments.map(async (attachment) => {
+ const file = await resend.emails.receiving.attachments.get({
+ emailId: email.email_id,
+ id: attachment.id,
+ });
+ if (file.error || !file.data) {
+ throw new Error(
+ `Resend attachment fetch failed: ${file.error?.name}: ${file.error?.message}`,
+ );
+ }
+ return {
+ contentType: file.data.content_type,
+ filename: file.data.filename ?? attachment.filename ?? attachment.id,
+ path: file.data.download_url,
+ };
+ }),
+ );
+
+ const banner = `${outreach.user.name} <${outreach.user.email}> replied to your outreach note.`;
+ const bannerHtml = escapeHtml(banner);
+ const { error } = await resend.emails.send(
+ {
+ from,
+ to: inbox,
+ replyTo: outreach.user.email,
+ subject: received.data.subject || "Re: What are you making?",
+ attachments: attachments.length > 0 ? attachments : undefined,
+ html: received.data.html
+ ? `<p><strong>${bannerHtml}</strong></p>${received.data.html}`
+ : undefined,
+ text: received.data.text ? `${banner}\n\n${received.data.text}` : banner,
+ },
+ // Resend's own dedupe is what keeps a redelivered webhook from forwarding
+ // the same reply twice, so nothing has to be written down to track it.
+ { idempotencyKey: `outreach-reply:${email.email_id}` },
+ );
+ if (error) {
+ throw new Error(`Resend forward failed: ${error.name}: ${error.message}`);
+ }
+ return true;
+}