Skip to content

Open source CapCut alternative.

TypeScript

feat(site): outreach notes send with signed reply addresses

David Le96f6030de5b9
diff --git a/site/src/cut/lib/hosts.ts b/site/src/cut/lib/hosts.ts
index 50dcd83f..7fa8ad33 100644
--- a/site/src/cut/lib/hosts.ts
+++ b/site/src/cut/lib/hosts.ts
@@ -16,6 +16,12 @@ export const DONKEYCUT_CANONICAL = "https://donkeycut.com";
export const CUT_MEDIA_HOST = "media.donkeycut.com";
export const CUT_MEDIA_ORIGIN = `https://${CUT_MEDIA_HOST}`;
+// Founder outreach replies land here: Resend receives mail for this subdomain
+// and posts it to /api/email/resend-webhook. It is deliberately a subdomain —
+// the MX record belongs to Resend, and the apex keeps whatever routes its mail
+// today (src/lib/marketing/replyAddress.ts).
+export const OUTREACH_REPLY_HOST = "reply.donkeycut.com";
+
// The Cut Worker's control plane — the /wake the hosted API posts to when it
// queues a render. Its own custom domain, claimed in wrangler.jsonc beside the
// media route, so it cannot be revoked by a deploy default the way the
diff --git a/site/src/emails/outreach.tsx b/site/src/emails/outreach.tsx
new file mode 100644
index 00000000..9e589e56
--- /dev/null
+++ b/site/src/emails/outreach.tsx
@@ -0,0 +1,90 @@
+import {
+ Body,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Link,
+ Preview,
+ Tailwind,
+ Text,
+ pixelBasedPreset,
+} from "react-email";
+import { Fragment } from "react";
+
+import { CommunityPs } from "./_components/CommunityPs";
+import { DonkeyMark } from "./_components/DonkeyMark";
+
+// The shell every outreach note is written into: the mark, the operator's text
+// as paragraphs, the community P.S., and the unsubscribe footer. The words
+// themselves come from a template in src/lib/marketing/templates/ or straight
+// from the send dialog, already filled for this recipient. Preview with
+// `npm run email:dev`. This module stays pure — the react-email preview server
+// bundles it on its own, so everything it needs comes in as props and
+// asset/link URLs are absolute.
+
+type OutreachEmailProps = {
+ /** Plain text. A blank line starts a paragraph, a single newline breaks a
+ * line. */
+ body: string;
+ unsubscribeUrl: string;
+};
+
+function paragraphs(body: string): string[] {
+ return body
+ .split(/\n\s*\n/)
+ .map((block) => block.trim())
+ .filter((block) => block.length > 0);
+}
+
+export default function OutreachEmail({ body, unsubscribeUrl }: OutreachEmailProps) {
+ const blocks = paragraphs(body);
+ return (
+ <Html>
+ <Head />
+ <Preview>{blocks[0] ?? ""}</Preview>
+ <Tailwind config={{ presets: [pixelBasedPreset] }}>
+ <Body className="bg-white font-sans text-[#0F0E0D]">
+ <Container className="mx-auto max-w-[520px] px-6 py-12">
+ <DonkeyMark />
+ {blocks.map((block, index) => (
+ <Text key={index} className="text-[15px] leading-relaxed">
+ {block.split("\n").map((line, lineIndex) => (
+ <Fragment key={lineIndex}>
+ {lineIndex > 0 ? <br /> : null}
+ {line}
+ </Fragment>
+ ))}
+ </Text>
+ ))}
+ <CommunityPs />
+ <Hr className="mt-6 border-[#0F0E0D]/15" />
+ <Text className="text-[12px] leading-relaxed text-[#0F0E0D]/60">
+ You&apos;re receiving this because you created a Donkey Cut
+ account.{" "}
+ <Link
+ href={unsubscribeUrl}
+ className="text-[#0F0E0D]/60 underline"
+ >
+ Unsubscribe
+ </Link>{" "}
+ from product emails.
+ </Text>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+}
+
+OutreachEmail.PreviewProps = {
+ body: `Hey Ada,
+
+I'm David — I build Donkey Cut. I saw you've been using the AI features.
+
+What are you making?
+
+Thanks,
+David`,
+ unsubscribeUrl: "https://donkeycut.com/unsubscribe?token=preview",
+} satisfies OutreachEmailProps;
diff --git a/site/src/lib/marketing/placeholders.test.ts b/site/src/lib/marketing/placeholders.test.ts
new file mode 100644
index 00000000..9c0d159f
--- /dev/null
+++ b/site/src/lib/marketing/placeholders.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, test } from "bun:test";
+
+import { fillOutreachText, UnknownPlaceholderError } from "./placeholders";
+
+const vars = {
+ balance: "0",
+ email: "[email protected]",
+ firstName: "Ada",
+ name: "Ada Lovelace",
+ spent: "2.4",
+};
+
+function refusedPlaceholder(text: string): boolean {
+ try {
+ fillOutreachText(text, vars);
+ return false;
+ } catch (e) {
+ return e instanceof UnknownPlaceholderError;
+ }
+}
+
+describe("fillOutreachText", () => {
+ test("a placeholder becomes the recipient's value", () => {
+ expect(fillOutreachText("Hey {{firstName}}, you spent ${{spent}}.", vars)).toBe(
+ "Hey Ada, you spent $2.4.",
+ );
+ });
+
+ test("spacing inside the braces is allowed", () => {
+ expect(fillOutreachText("{{ name }}", vars)).toBe("Ada Lovelace");
+ });
+
+ test("text with no placeholders is untouched", () => {
+ expect(fillOutreachText("Plain words.", vars)).toBe("Plain words.");
+ });
+
+ test("a misspelled placeholder throws instead of mailing the braces", () => {
+ expect(refusedPlaceholder("Hey {{frstName}}")).toBe(true);
+ });
+});
+
diff --git a/site/src/lib/marketing/placeholders.ts b/site/src/lib/marketing/placeholders.ts
new file mode 100644
index 00000000..36c90636
--- /dev/null
+++ b/site/src/lib/marketing/placeholders.ts
@@ -0,0 +1,44 @@
+// What a subject or body may name, and where each value comes from. Saved
+// templates and hand-typed notes go through the same fill, so a placeholder
+// means the same thing either way.
+
+/** The values a placeholder resolves to, for one recipient. */
+export type OutreachVars = {
+ /** First word of the account name. */
+ firstName: string;
+ /** The account name as Google gave it. */
+ name: string;
+ email: string;
+ /** USD spent on model work so far, as a plain number string. */
+ spent: string;
+ /** USD left on the account. */
+ balance: string;
+};
+
+export const OUTREACH_PLACEHOLDERS = [
+ "firstName",
+ "name",
+ "email",
+ "spent",
+ "balance",
+] as const satisfies readonly (keyof OutreachVars)[];
+
+const PLACEHOLDER = /\{\{\s*([a-zA-Z]+)\s*\}\}/g;
+
+export class UnknownPlaceholderError extends Error {
+ public constructor(public readonly placeholder: string) {
+ super(`Unknown placeholder {{${placeholder}}}.`);
+ this.name = "UnknownPlaceholderError";
+ }
+}
+
+/** Fills a subject or body for one recipient. An unknown placeholder throws
+ * rather than mailing the braces out, so a typo is caught before the send. */
+export function fillOutreachText(text: string, vars: OutreachVars): string {
+ return text.replace(PLACEHOLDER, (_match, key: string) => {
+ if (!(OUTREACH_PLACEHOLDERS as readonly string[]).includes(key)) {
+ throw new UnknownPlaceholderError(key);
+ }
+ return vars[key as keyof OutreachVars];
+ });
+}
diff --git a/site/src/lib/marketing/replyAddress.test.ts b/site/src/lib/marketing/replyAddress.test.ts
new file mode 100644
index 00000000..1d08aea9
--- /dev/null
+++ b/site/src/lib/marketing/replyAddress.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, test } from "bun:test";
+
+process.env.BETTER_AUTH_SECRET ??= "test-secret";
+
+import {
+ outreachIdFromReplyAddress,
+ outreachIdFromRecipients,
+ outreachReplyAddress,
+} from "./replyAddress";
+
+const id = "cmf0z8k9x0000abcdefghijkl";
+
+describe("outreachReplyAddress", () => {
+ test("an address it signed reads back as its row id", () => {
+ expect(outreachIdFromReplyAddress(outreachReplyAddress(id))).toBe(id);
+ });
+
+ test("the local part stays inside the 64-octet limit", () => {
+ const local = outreachReplyAddress(id).split("@")[0];
+ expect(local.length).toBeLessThanOrEqual(64);
+ });
+
+ test("a guessed row id without a signature is refused", () => {
+ expect(outreachIdFromReplyAddress(`outreach+${id}[email protected]`)).toBeNull();
+ });
+
+ test("another row's signature does not carry over", () => {
+ const sig = outreachReplyAddress("other-row").split("@")[0].split(".")[1];
+ expect(outreachIdFromReplyAddress(`outreach+${id}.${sig}@reply.donkeycut.com`)).toBeNull();
+ });
+
+ test("an address on another host is not ours", () => {
+ const local = outreachReplyAddress(id).split("@")[0];
+ expect(outreachIdFromReplyAddress(`${local}@donkeycut.com`)).toBeNull();
+ });
+
+ test("recipients are searched past unrelated addresses and display names", () => {
+ expect(
+ outreachIdFromRecipients(
+ [`Donkey <${outreachReplyAddress(id)}>`],
+ ),
+ ).toBe(id);
+ });
+
+ test("mail addressed to nobody we know reads as no row", () => {
+ expect(outreachIdFromRecipients(["[email protected]"], [])).toBeNull();
+ });
+});
diff --git a/site/src/lib/marketing/replyAddress.ts b/site/src/lib/marketing/replyAddress.ts
new file mode 100644
index 00000000..cc9a0fdd
--- /dev/null
+++ b/site/src/lib/marketing/replyAddress.ts
@@ -0,0 +1,71 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+import { OUTREACH_REPLY_HOST } from "@/cut/lib/hosts";
+
+// Every outreach email replies to its own address, so an inbound message finds
+// its row without matching on the sender — people answer from aliases, and
+// forwarded mail arrives from somewhere else entirely. The row id is signed the
+// same way unsubscribe tokens are (src/lib/email/unsubscribe.ts), under its own
+// domain string, so a stranger cannot post into a thread by guessing an id.
+const TOKEN_DOMAIN = "donkey-outreach-reply-v1";
+
+// Local-part shape: `outreach+${outreachId}.${signature}`. The signature is
+// truncated because a local part may be no longer than 64 octets and some
+// servers enforce it; 96 bits is far more than a forger gets attempts at.
+const LOCAL_PART = /^outreach\+([^.@]+)\.([A-Za-z0-9_-]+)$/;
+const SIGNATURE_BYTES = 12;
+
+function signature(outreachId: string): Buffer {
+ const secret = process.env.BETTER_AUTH_SECRET;
+ if (!secret) {
+ throw new Error("BETTER_AUTH_SECRET is not set.");
+ }
+ const key = createHmac("sha256", secret).update(TOKEN_DOMAIN).digest();
+ return createHmac("sha256", key).update(outreachId).digest().subarray(0, SIGNATURE_BYTES);
+}
+
+export function outreachReplyAddress(outreachId: string): string {
+ const sig = signature(outreachId).toString("base64url");
+ return `outreach+${outreachId}.${sig}@${OUTREACH_REPLY_HOST}`;
+}
+
+/** The row id an inbound address names, or null when it is not one of ours. */
+export function outreachIdFromReplyAddress(address: string): string | null {
+ const at = address.lastIndexOf("@");
+ if (at <= 0) {
+ return null;
+ }
+ const host = address.slice(at + 1).toLowerCase();
+ if (host !== OUTREACH_REPLY_HOST) {
+ return null;
+ }
+ const match = LOCAL_PART.exec(address.slice(0, at));
+ if (!match) {
+ return null;
+ }
+ const [, outreachId, given] = match;
+ const expected = signature(outreachId);
+ const supplied = Buffer.from(given, "base64url");
+ if (supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) {
+ return null;
+ }
+ return outreachId;
+}
+
+// Mail arrives addressed in more than one field: `received_for` carries the
+// envelope recipient, `to` what the sender typed. Take the first that verifies.
+export function outreachIdFromRecipients(
+ ...groups: (string[] | null | undefined)[]
+): string | null {
+ for (const group of groups) {
+ for (const entry of group ?? []) {
+ // Headers arrive as "Name <addr@host>" as often as a bare address.
+ const angled = /<([^>]+)>/.exec(entry);
+ const id = outreachIdFromReplyAddress((angled?.[1] ?? entry).trim());
+ if (id) {
+ return id;
+ }
+ }
+ }
+ return null;
+}
diff --git a/site/src/lib/marketing/send-outreach.ts b/site/src/lib/marketing/send-outreach.ts
new file mode 100644
index 00000000..3ba0f883
--- /dev/null
+++ b/site/src/lib/marketing/send-outreach.ts
@@ -0,0 +1,113 @@
+import {
+ DONKEY_LOGO_CID,
+ DONKEY_LOGO_PNG_BASE64,
+} from "@/emails/_components/logo";
+import OutreachEmail from "@/emails/outreach";
+import {
+ emailFrom,
+ getResend,
+ isResendConfigured,
+ type EmailUser,
+} from "@/lib/email/resend";
+import {
+ isMarketingUnsubscribed,
+ unsubscribeActionUrl,
+ unsubscribePageUrl,
+} from "@/lib/email/unsubscribe";
+import { outreachReplyAddress } from "@/lib/marketing/replyAddress";
+import {
+ fillOutreachText,
+ UnknownPlaceholderError,
+ type OutreachVars,
+} from "@/lib/marketing/placeholders";
+
+export class OutreachNotSendableError extends Error {
+ public constructor(message: string) {
+ super(message);
+ this.name = "OutreachNotSendableError";
+ }
+}
+
+type SendOutreachInput = {
+ user: EmailUser;
+ outreachId: string;
+ // Which send this is for the row, so a retried click cannot double-send and
+ // a deliberate second note still goes out.
+ attempt: number;
+ // The final words, from a template or typed in the dialog. Placeholders are
+ // filled here so the operator edits `{{firstName}}` and the recipient reads
+ // their name.
+ subject: string;
+ body: string;
+ vars: OutreachVars;
+};
+
+// Sends one outreach note. Promotional mail, so it checks the opt-out first
+// and carries the one-click unsubscribe headers. The reply-to is the row's own
+// address: a reply comes back through Resend Inbound and finds its row without
+// matching on the sender.
+export async function sendOutreachEmail({
+ attempt,
+ body,
+ outreachId,
+ subject,
+ user,
+ vars,
+}: SendOutreachInput): Promise<void> {
+ if (!isResendConfigured()) {
+ throw new OutreachNotSendableError("RESEND_API_KEY is not configured.");
+ }
+ const from = emailFrom();
+ if (!from) {
+ throw new OutreachNotSendableError("RESEND_FROM_EMAIL is not configured.");
+ }
+ if (await isMarketingUnsubscribed(user.id)) {
+ throw new OutreachNotSendableError("That account is unsubscribed.");
+ }
+
+ let filledSubject: string;
+ let filledBody: string;
+ try {
+ filledSubject = fillOutreachText(subject, vars);
+ filledBody = fillOutreachText(body, vars);
+ } catch (error) {
+ if (error instanceof UnknownPlaceholderError) {
+ throw new OutreachNotSendableError(error.message);
+ }
+ throw error;
+ }
+
+ const { error } = await getResend().emails.send(
+ {
+ from,
+ to: user.email,
+ replyTo: outreachReplyAddress(outreachId),
+ subject: filledSubject,
+ react: OutreachEmail({
+ body: filledBody,
+ unsubscribeUrl: unsubscribePageUrl(user.id),
+ }),
+ // The mark rides inside the message (Content-ID embed) so no client
+ // fetches anything external; Gmail strips data URIs, so cid is the only
+ // fetch-free form that renders everywhere.
+ attachments: [
+ {
+ content: DONKEY_LOGO_PNG_BASE64,
+ contentId: DONKEY_LOGO_CID,
+ contentType: "image/png",
+ filename: "donkey-cut.png",
+ },
+ ],
+ // RFC 8058 one-click: mail providers POST here with no session; the
+ // signed token in the URL is the authorization.
+ headers: {
+ "List-Unsubscribe": `<${unsubscribeActionUrl(user.id)}>`,
+ "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
+ },
+ },
+ { idempotencyKey: `outreach:${outreachId}:${attempt}` },
+ );
+ if (error) {
+ throw new Error(`Resend send failed: ${error.name}: ${error.message}`);
+ }
+}