Skip to content

Open source CapCut alternative.

TypeScript

feat(site): report a promotion's button clicks and credit claims

David Le7f9f292e05f2
diff --git a/docs/guides/backend-apis.md b/docs/guides/backend-apis.md
index d7039c91..fea76f21 100644
--- a/docs/guides/backend-apis.md
+++ b/docs/guides/backend-apis.md
@@ -6,7 +6,8 @@ the site's own client views, signed in with a session cookie.
**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 and Resend webhooks, the
-HMAC-token-verified one-click email unsubscribe, and a plain health check. Ship
+HMAC-token-verified one-click email unsubscribe and promotion button redirect,
+and a plain health check. Ship
a handler without the wrapper and the endpoint is open to anyone.
## Authentication
diff --git a/site/prisma/Email.prisma b/site/prisma/Email.prisma
index f43bbff3..bc479f92 100644
--- a/site/prisma/Email.prisma
+++ b/site/prisma/Email.prisma
@@ -41,6 +41,8 @@ model EmailSend {
// A failed attempt pushes the next one out.
notBefore DateTime @default(now())
sentAt DateTime?
+ // The first time the recipient followed the message's button.
+ clickedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/site/src/app/api/email/click/route.ts b/site/src/app/api/email/click/route.ts
new file mode 100644
index 00000000..67cfc6f1
--- /dev/null
+++ b/site/src/app/api/email/click/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse, type NextRequest } from "next/server";
+import { z } from "zod";
+
+import { unauthorizedResponse } from "@/lib/donkey-api-auth";
+import { recordClick, verifyClick } from "@/lib/email/click";
+
+const querySchema = z.object({
+ s: z.string().min(1).max(64),
+ t: z.string().min(1).max(512),
+ u: z.url({ protocol: /^https?$/ }).max(2000),
+});
+
+// Public exception to withDonkeyAuth (docs/guides/backend-apis.md): the
+// recipient of a promotion follows this link from their mail client, with no
+// session. The signed token in the URL is the authorization; it binds the
+// send row to the destination, and a bad one goes nowhere.
+export async function GET(request: NextRequest) {
+ const parsed = querySchema.safeParse(Object.fromEntries(request.nextUrl.searchParams));
+ if (!parsed.success || !verifyClick(parsed.data.s, parsed.data.u, parsed.data.t)) {
+ return unauthorizedResponse();
+ }
+ await recordClick(parsed.data.s);
+ return NextResponse.redirect(parsed.data.u, 302);
+}
diff --git a/site/src/app/su/promotions/page.tsx b/site/src/app/su/promotions/page.tsx
index dd0408b3..c3984991 100644
--- a/site/src/app/su/promotions/page.tsx
+++ b/site/src/app/su/promotions/page.tsx
@@ -129,7 +129,7 @@ function PromotionRow({
const skipped = p.excludePromotionIds
.map((id) => all.find((other) => other.id === id)?.name ?? "a deleted promotion")
.join(", ");
- const { recipients, sent, failed } = p.counts;
+ const { recipients, sent, failed, clicked, claimed } = p.counts;
return (
<div className="rounded-lg border p-4">
@@ -147,7 +147,9 @@ function PromotionRow({
<p className="mt-1 text-xs text-muted-foreground">
{p.status === "draft"
? `Draft · saved ${when(p.updatedAt)}`
- : `${sent} of ${recipients} sent${failed ? ` · ${failed} failed` : ""}${
+ : `${sent} of ${recipients} sent${failed ? ` · ${failed} failed` : ""} · ${clicked} clicked${
+ p.creditOffer ? ` · ${claimed} claimed` : ""
+ }${
p.startedAt ? ` · started ${when(p.startedAt)}` : ""
}${p.finishedAt ? ` · finished ${when(p.finishedAt)}` : ""}`}
</p>
diff --git a/site/src/lib/credits/offers.ts b/site/src/lib/credits/offers.ts
index 7443dedc..3d4906c8 100644
--- a/site/src/lib/credits/offers.ts
+++ b/site/src/lib/credits/offers.ts
@@ -17,6 +17,8 @@ const TOKEN_DOMAIN = "donkey-credit-offer-v1";
// The kind su makes by hand; a promotion's offers carry the promotion's key.
export const MANUAL_OFFER_KIND = "manual";
+// The kind of an offer a promotion email made; its id is `${promotionId}:${userId}`.
+export const PROMOTION_OFFER_KIND = "promotion_email";
function signature(offerId: string): Buffer {
const secret = process.env.BETTER_AUTH_SECRET;
@@ -137,7 +139,7 @@ export async function landCreditOffer(
// a promotion mails. Every other kind lands from the act it rewards.
export async function claimCreditOffer(offerId: string, userId: string) {
const offer = await prisma.creditOffer.findUnique({ where: { id: offerId } });
- if (!offer || (offer.kind !== MANUAL_OFFER_KIND && offer.kind !== "promotion_email")) return null;
+ if (!offer || (offer.kind !== MANUAL_OFFER_KIND && offer.kind !== PROMOTION_OFFER_KIND)) return null;
if (offer.userId !== userId) throw new CreditOfferNotYoursError();
if (!offer.claimedAt && !creditOfferOpen(offer, new Date())) throw new CreditOfferClosedError();
return landCreditOffer(offer, {
@@ -163,7 +165,7 @@ export async function createPromotionCreditOffer(input: {
create: {
id: offerId,
userId: input.userId,
- kind: "promotion_email",
+ kind: PROMOTION_OFFER_KIND,
amountMicros: BigInt(input.amountDollars) * BigInt(1_000_000),
expiresAfterDays: input.expiresAfterDays,
closesAt: new Date(now.getTime() + input.claimWindowDays * 86_400_000),
diff --git a/site/src/lib/email/click.test.ts b/site/src/lib/email/click.test.ts
new file mode 100644
index 00000000..a9582216
--- /dev/null
+++ b/site/src/lib/email/click.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, test } from "bun:test";
+
+import { clickUrl, verifyClick } from "./click";
+
+process.env.BETTER_AUTH_SECRET ??= "test-secret";
+
+describe("click links", () => {
+ test("a link verifies for its own row and destination", () => {
+ const url = new URL(clickUrl("send_1", "https://donkeycut.com/app?claim=abc"));
+ const s = url.searchParams.get("s")!;
+ const u = url.searchParams.get("u")!;
+ const t = url.searchParams.get("t")!;
+ expect(s).toBe("send_1");
+ expect(u).toBe("https://donkeycut.com/app?claim=abc");
+ expect(verifyClick(s, u, t)).toBe(true);
+ });
+
+ test("a changed row or destination fails", () => {
+ const url = new URL(clickUrl("send_1", "https://donkeycut.com/app"));
+ const t = url.searchParams.get("t")!;
+ expect(verifyClick("send_2", "https://donkeycut.com/app", t)).toBe(false);
+ expect(verifyClick("send_1", "https://evil.example/", t)).toBe(false);
+ expect(verifyClick("send_1", "https://donkeycut.com/app", "nope")).toBe(false);
+ });
+});
diff --git a/site/src/lib/email/click.ts b/site/src/lib/email/click.ts
new file mode 100644
index 00000000..bb62e2fe
--- /dev/null
+++ b/site/src/lib/email/click.ts
@@ -0,0 +1,33 @@
+import { createHmac, timingSafeEqual } from "node:crypto";
+
+import { DONKEYCUT_CANONICAL } from "@/cut/lib/hosts";
+import { prisma } from "@/lib/prisma";
+
+// A button in a promotion goes through this app first, so the send row learns
+// it was followed. The link carries the row id and the destination, signed
+// with an HMAC keyed by a domain-separated derivation of the auth secret, so
+// nobody can mark rows clicked or bounce people to their own address.
+const TOKEN_DOMAIN = "donkey-email-click-v1";
+
+function signature(sendId: string, url: 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(`${sendId}\n${url}`).digest();
+}
+
+export function clickUrl(sendId: string, url: string): string {
+ const params = new URLSearchParams({ s: sendId, u: url, t: signature(sendId, url).toString("base64url") });
+ return `${DONKEYCUT_CANONICAL}/api/email/click?${params}`;
+}
+
+export function verifyClick(sendId: string, url: string, token: string): boolean {
+ const expected = signature(sendId, url);
+ const given = Buffer.from(token, "base64url");
+ return given.length === expected.length && timingSafeEqual(given, expected);
+}
+
+/** Stamps the row's first click; later clicks leave the first stamp. */
+export async function recordClick(sendId: string): Promise<void> {
+ await prisma.emailSend.updateMany({ data: { clickedAt: new Date() }, where: { clickedAt: null, id: sendId } });
+}
diff --git a/site/src/lib/email/kinds.ts b/site/src/lib/email/kinds.ts
index 92f7fd79..2e22b068 100644
--- a/site/src/lib/email/kinds.ts
+++ b/site/src/lib/email/kinds.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { creditOfferClaimUrl, createPromotionCreditOffer } from "@/lib/credits/offers";
+import { clickUrl } from "@/lib/email/click";
import { recordExpiryNoticeSent } from "@/lib/email/credit-expiry-notices";
import type { EmailSendKind } from "@/lib/email/daily-send-limit";
import { PermanentSendError } from "@/lib/email/errors";
@@ -126,8 +127,13 @@ async function abandonPromotion(promotionId: string, error: Error): Promise<void
}
// A promotion with a credit offer mails each person their own claim link,
-// backed by an offer row that the real send and the test send share.
-async function promotionEmailFor(promotion: Awaited<ReturnType<typeof promotionRowOf>>, user: EmailUser) {
+// backed by an offer row that the real send and the test send share. The
+// real send's button is counted when followed.
+async function promotionEmailFor(
+ promotion: Awaited<ReturnType<typeof promotionRowOf>>,
+ user: EmailUser,
+ trackClick?: (url: string) => string,
+) {
const offer = promotionOfferOf(promotion.creditOffer);
const claimUrl = offer
? (
@@ -141,7 +147,7 @@ async function promotionEmailFor(promotion: Awaited<ReturnType<typeof promotionR
})
).claimUrl
: undefined;
- return buildPromotionEmail(promotionCopyOf(promotion), user, claimUrl);
+ return buildPromotionEmail(promotionCopyOf(promotion), user, claimUrl, trackClick);
}
const promotion = define({
@@ -152,7 +158,7 @@ const promotion = define({
// The opt-out is read again right before the send, so someone who
// unsubscribed after the segment was resolved is skipped.
if (!user || (await isMarketingUnsubscribed(user.id))) return null;
- return promotionEmailFor(promotion, user);
+ return promotionEmailFor(promotion, user, (url) => clickUrl(row.id, url));
},
onAbandon: async ({ promotionId }, _row, error) => abandonPromotion(promotionId, error),
});
diff --git a/site/src/lib/marketing/promotionInput.ts b/site/src/lib/marketing/promotionInput.ts
index db5ae035..ed8828fb 100644
--- a/site/src/lib/marketing/promotionInput.ts
+++ b/site/src/lib/marketing/promotionInput.ts
@@ -58,7 +58,9 @@ export type PromotionSummary = {
finishedAt: string | null;
createdAt: string;
updatedAt: string;
- counts: { recipients: number; sent: number; failed: number };
+ // Recipients queued, sent, failed, and what came of it: buttons followed,
+ // credit offers claimed.
+ counts: { recipients: number; sent: number; failed: number; clicked: number; claimed: number };
};
// What a segment resolves to before anything is sent.
diff --git a/site/src/lib/marketing/promotions.ts b/site/src/lib/marketing/promotions.ts
index 7c213d6d..176f5b5a 100644
--- a/site/src/lib/marketing/promotions.ts
+++ b/site/src/lib/marketing/promotions.ts
@@ -17,6 +17,7 @@ import {
type SegmentCount,
} from "@/lib/marketing/promotionInput";
import { prisma } from "@/lib/prisma";
+import { PROMOTION_OFFER_KIND } from "@/lib/credits/offers";
import { promotionOfferOf } from "@/lib/marketing/promotionOfferInput";
// Promotions on the server: which address each sender is, who a segment
@@ -58,10 +59,17 @@ export function promotionAudienceOf(raw: Prisma.JsonValue): Audience {
/** One promotion email for one account. The idempotency key is the row's:
* the outbox keys on the recipient so a retried run cannot mail anyone twice. */
-export function buildPromotionEmail(copy: PromotionCopy, user: EmailUser, claimUrl: string | undefined): EmailMessage {
+export function buildPromotionEmail(
+ copy: PromotionCopy,
+ user: EmailUser,
+ claimUrl: string | undefined,
+ // Wraps the button's link so the follow is counted; the test send has none.
+ trackClick?: (url: string) => string,
+): EmailMessage {
const from = promotionSenders()[copy.sender];
if (!from) throw new PermanentSendError(`The ${copy.sender} sender is not configured.`);
const rendered = renderPromotion(copy, user, claimUrl);
+ const cta = rendered.cta && trackClick ? { ...rendered.cta, url: trackClick(rendered.cta.url) } : rendered.cta;
return {
from,
to: user.email,
@@ -69,7 +77,7 @@ export function buildPromotionEmail(copy: PromotionCopy, user: EmailUser, claimU
subject: rendered.subject,
react: PromotionEmail({
blocks: rendered.blocks,
- cta: rendered.cta,
+ cta,
preview: rendered.preview,
unsubscribeUrl: unsubscribePageUrl(user.id),
}),
@@ -161,10 +169,7 @@ export async function resolvePromotionSegment(
type PromotionRow = NonNullable<Awaited<ReturnType<typeof prisma.promotion.findUnique>>>;
-function summarize(
- row: PromotionRow,
- counts: { recipients: number; sent: number; failed: number },
-): PromotionSummary {
+function summarize(row: PromotionRow, counts: PromotionSummary["counts"]): PromotionSummary {
return {
id: row.id,
creditOffer: promotionOfferOf(row.creditOffer),
@@ -185,9 +190,10 @@ function summarize(
};
}
-/** Every promotion, newest first, with how far its send got. */
+/** Every promotion, newest first, with how far its send got and what came
+ * of it: buttons followed, and credit offers claimed. */
export async function listPromotions(): Promise<PromotionSummary[]> {
- const [rows, all, sent, failed] = await Promise.all([
+ const [rows, all, sent, failed, clicked, claimedOffers] = await Promise.all([
prisma.promotion.findMany({ orderBy: { createdAt: "desc" } }),
prisma.emailSend.groupBy({ _count: true, by: ["promotionId"], where: { promotionId: { not: null } } }),
prisma.emailSend.groupBy({ _count: true, by: ["promotionId"], where: { promotionId: { not: null }, state: "sent" } }),
@@ -196,17 +202,32 @@ export async function listPromotions(): Promise<PromotionSummary[]> {
by: ["promotionId"],
where: { promotionId: { not: null }, state: { in: ["failed", "skipped"] } },
}),
+ prisma.emailSend.groupBy({
+ _count: true,
+ by: ["promotionId"],
+ where: { clickedAt: { not: null }, promotionId: { not: null } },
+ }),
+ // A promotion's offers are keyed `${promotionId}:${userId}`.
+ prisma.creditOffer.findMany({ select: { id: true }, where: { claimedAt: { not: null }, kind: PROMOTION_OFFER_KIND } }),
]);
const countOf = (groups: { promotionId: string | null; _count: number }[]) =>
new Map(groups.flatMap((g) => (g.promotionId ? [[g.promotionId, g._count] as const] : [])));
const recipients = countOf(all);
const sentBy = countOf(sent);
const failedBy = countOf(failed);
+ const clickedBy = countOf(clicked);
+ const claimedBy = new Map<string, number>();
+ for (const offer of claimedOffers) {
+ const promotionId = offer.id.slice(0, offer.id.indexOf(":"));
+ claimedBy.set(promotionId, (claimedBy.get(promotionId) ?? 0) + 1);
+ }
return rows.map((row) =>
summarize(row, {
recipients: recipients.get(row.id) ?? 0,
sent: sentBy.get(row.id) ?? 0,
failed: failedBy.get(row.id) ?? 0,
+ clicked: clickedBy.get(row.id) ?? 0,
+ claimed: claimedBy.get(row.id) ?? 0,
}),
);
}