Open source CapCut alternative.
TypeScript
feat(site): cap signup credits per network
David Le6d21b66610d3
diff --git a/site/prisma/Onboarding.prisma b/site/prisma/Onboarding.prismaindex c78706c7..d0e0f6e6 100644--- a/site/prisma/Onboarding.prisma+++ b/site/prisma/Onboarding.prisma@@ -34,3 +34,15 @@ model DeletedAccount {grantedMicros BigInt @default(0)chargedMicros BigInt @default(0)}++// How many signup credit grants one network has taken in its current window.+// Signup claims one before granting; a network at the+// signupCreditsPerNetwork limit gives later accounts none until the window+// lapses.+model SignupNetwork {+ // HMAC of the network address (an IPv6 address collapsed to its /64), so+ // the table holds no address.+ networkKey String @id+ windowStart DateTime+ claims Int @default(0)+}diff --git a/site/prisma/migrations/20261016104230/migration.sql b/site/prisma/migrations/20261016104230/migration.sqlnew file mode 100644index 00000000..d890ff2e--- /dev/null+++ b/site/prisma/migrations/20261016104230/migration.sql@@ -0,0 +1,8 @@+-- CreateTable+CREATE TABLE "SignupNetwork" (+ "networkKey" TEXT NOT NULL,+ "windowStart" TIMESTAMP(3) NOT NULL,+ "claims" INTEGER NOT NULL DEFAULT 0,++ CONSTRAINT "SignupNetwork_pkey" PRIMARY KEY ("networkKey")+);diff --git a/site/src/lib/auth.ts b/site/src/lib/auth.tsindex 182fd4ea..5e611949 100644--- a/site/src/lib/auth.ts+++ b/site/src/lib/auth.ts@@ -66,13 +66,17 @@ export const auth = betterAuth({// Every new account is provisioned with its signup credit grant, its// starter project, the welcome email, and its Resend contact.// provisionSignupGrants is idempotent and- // swallows its own errors, so it never blocks user creation.- after: async (user) => {- await provisionSignupGrants({- email: user.email,- id: user.id,- name: user.name,- });+ // swallows its own errors, so it never blocks user creation. The+ // request's headers carry the network the signup came from.+ after: async (user, context) => {+ await provisionSignupGrants(+ {+ email: user.email,+ id: user.id,+ name: user.name,+ },+ context?.headers ?? context?.request?.headers,+ );},},},diff --git a/site/src/lib/config/registry.ts b/site/src/lib/config/registry.tsindex 01be573c..2d925a8b 100644--- a/site/src/lib/config/registry.ts+++ b/site/src/lib/config/registry.ts@@ -556,6 +556,21 @@ export const SETTINGS = defineSettings({title: "Signup credits",description: "USD a new account is granted at signup, shown as 1,000 credits per dollar, and how many days the grant lives.",},+ signupCreditsPerNetwork: {+ schema: z+ .object({+ // Signup grants one network takes per window; later accounts from it+ // start with no credits.+ limit: z.number().int().min(1).max(1000),+ // Days a network's window runs from its first grant.+ windowDays: z.number().int().min(1).max(365),+ })+ .strict(),+ default: { limit: 3, windowDays: 7 },+ public: false,+ title: "Signup credits per network",+ description: "How many new accounts from one network get the signup credits within the window; later accounts from it start with none.",+ },emailSendBudget: {schema: z.object({diff --git a/site/src/lib/onboarding/signup-grants.ts b/site/src/lib/onboarding/signup-grants.tsindex 08645d39..7ef10b73 100644--- a/site/src/lib/onboarding/signup-grants.ts+++ b/site/src/lib/onboarding/signup-grants.ts@@ -8,13 +8,15 @@ import { type EmailUser } from "@/lib/email/resend";import { deliverEmail } from "@/lib/email/outbox";import { welcomeIdempotencyKey } from "@/lib/email/send-welcome";import { isDeletedAddress } from "@/lib/onboarding/deleted-account";+import { claimSignupGrant, signupNetworkKey } from "@/lib/onboarding/signup-network";// Single source of truth for what a new account starts with. All steps are// idempotent and keyed to the user, so provisioning can run more than once// (e.g. a retried signup) without double-granting, double-seeding, or// double-sending. The grant amount and its lifetime are the signupCredits-// setting; the welcome email names the amount that landed.-export async function provisionSignupGrants(user: EmailUser): Promise<void> {+// setting; the welcome email names the amount that landed. `headers` are the+// signup request's, which name the network the account came from.+export async function provisionSignupGrants(user: EmailUser, headers: Headers | undefined): Promise<void> {const setting = await getGlobalSetting("signupCredits");// An address that was deleted already had its signup credits once. The// starter project, fonts and welcome still land; the credits do not, and@@ -25,7 +27,8 @@ export async function provisionSignupGrants(user: EmailUser): Promise<void> {userId: user.id,});}- const credits = returning || setting.dollars <= 0 ? null : String(setting.dollars);+ const eligible = !returning && setting.dollars > 0;+ const credits = eligible && (await networkHasGrant(user.id, headers)) ? String(setting.dollars) : null;const expiresAt = creditGrantExpiry(setting.expiresAfterDays) ?? null;// Settle the steps independently: one failing must not block the others,// and signup itself must never fail because a bonus grant hiccupped.@@ -48,6 +51,30 @@ export async function provisionSignupGrants(user: EmailUser): Promise<void> {}}+// Whether the network this signup came from still has a grant to give, under+// the signupCreditsPerNetwork limit; asking takes one. One person cycling+// accounts from one connection gets the first few grants and no more. A+// signup whose address can't be read, or whose claim fails, gets none, so+// the limit always holds.+async function networkHasGrant(userId: string, headers: Headers | undefined): Promise<boolean> {+ try {+ const key = headers ? signupNetworkKey(headers) : null;+ if (!key) {+ console.error("[signup-grants] signup carried no network address; signup credits withheld", { userId });+ return false;+ }++ const open = await claimSignupGrant(key, await getGlobalSetting("signupCreditsPerNetwork"));+ if (!open) {+ console.info("[signup-grants] network reached its signup grant limit; signup credits withheld", { userId });+ }+ return open;+ } catch (reason) {+ console.error("[signup-grants] failed to claim a network signup grant; signup credits withheld", { reason, userId });+ return false;+ }+}+export async function grantSignupAppCredits(userId: string,credits: string,diff --git a/site/src/lib/onboarding/signup-network.test.ts b/site/src/lib/onboarding/signup-network.test.tsnew file mode 100644index 00000000..195237f0--- /dev/null+++ b/site/src/lib/onboarding/signup-network.test.ts@@ -0,0 +1,93 @@+import { beforeEach, expect, test } from "bun:test";+import { stubModule } from "@/lib/testing/stubModule";++// One network gets `limit` signup grants per window. The fake table applies+// each guarded write the way Postgres does: the where clause decides whether+// the row changes, and the count says whether it did.+type Row = { networkKey: string; windowStart: Date; claims: number };+type Where = { networkKey: string; windowStart?: { lt: Date }; claims?: { lt: number } };+const rows = new Map<string, Row>();++function matches(row: Row | undefined, where: Where): row is Row {+ if (!row) {+ return false;+ }+ if (where.windowStart && !(row.windowStart < where.windowStart.lt)) {+ return false;+ }+ return !where.claims || row.claims < where.claims.lt;+}++const prisma = {+ signupNetwork: {+ createMany: async ({ data }: { data: Row[] }) => {+ const fresh = data.filter((row) => !rows.has(row.networkKey));+ for (const row of fresh) {+ rows.set(row.networkKey, { ...row });+ }+ return { count: fresh.length };+ },+ updateMany: async ({ where, data }: { where: Where; data: { windowStart?: Date; claims: number | { increment: number } } }) => {+ const row = rows.get(where.networkKey);+ if (!matches(row, where)) {+ return { count: 0 };+ }+ row.claims = typeof data.claims === "number" ? data.claims : row.claims + data.claims.increment;+ row.windowStart = data.windowStart ?? row.windowStart;+ return { count: 1 };+ },+ },+};+await stubModule<typeof import("@/lib/prisma")>("@/lib/prisma", import.meta.url, { prisma: prisma as never });+process.env.BETTER_AUTH_SECRET ??= "test-secret";++const { claimSignupGrant, signupNetworkKey } = await import("./signup-network");++const CAP = { limit: 3, windowDays: 7 };+const DAY_MS = 24 * 60 * 60 * 1000;+const start = new Date("2026-10-12T11:00:00Z");++function from(ip: string): Headers {+ return new Headers({ "x-forwarded-for": `${ip}, 10.0.0.1` });+}++beforeEach(() => {+ rows.clear();+});++test("a network past its limit gets no more grants inside the window", async () => {+ const key = signupNetworkKey(from("2804:14c:4e7:85e6:6499:71e4:d97d:a236"));+ if (!key) {+ throw new Error("no key");+ }+ const granted = [];+ for (let i = 0; i < 14; i++) {+ granted.push(await claimSignupGrant(key, CAP, new Date(start.getTime() + i * 60_000)));+ }+ expect(granted.filter(Boolean)).toHaveLength(3);+ expect(granted.slice(0, 3)).toEqual([true, true, true]);+});++test("the window starts over once it lapses", async () => {+ const key = "network";+ for (let i = 0; i < 4; i++) {+ await claimSignupGrant(key, CAP, start);+ }+ expect(await claimSignupGrant(key, CAP, new Date(start.getTime() + 6 * DAY_MS))).toBe(false);+ expect(await claimSignupGrant(key, CAP, new Date(start.getTime() + 8 * DAY_MS))).toBe(true);+});++test("addresses inside one IPv6 /64 share a key, and the key hides the address", () => {+ const a = signupNetworkKey(from("2804:14c:4e7:85e6:6499:71e4:d97d:a236"));+ const b = signupNetworkKey(from("2804:14c:4e7:85e6::1"));+ const other = signupNetworkKey(from("2804:14c:4e7:85e7::1"));+ expect(a).toBe(b);+ expect(a).not.toBe(other);+ expect(a).not.toContain("2804");+ expect(signupNetworkKey(from("203.0.113.7"))).not.toBe(signupNetworkKey(from("203.0.113.8")));+});++test("a request without a readable address has no key", () => {+ expect(signupNetworkKey(new Headers())).toBeNull();+ expect(signupNetworkKey(from("not-an-ip"))).toBeNull();+});diff --git a/site/src/lib/onboarding/signup-network.ts b/site/src/lib/onboarding/signup-network.tsnew file mode 100644index 00000000..57fc5604--- /dev/null+++ b/site/src/lib/onboarding/signup-network.ts@@ -0,0 +1,68 @@+import { createHmac } from "node:crypto";++import { isValidIP, normalizeIP } from "@better-auth/core/utils/ip";++import { prisma } from "@/lib/prisma";++// The header the host puts the caller's address in, first entry first. Vercel+// sets it on every request, and better-auth reads the same one.+const FORWARDED_FOR = "x-forwarded-for";++// The block of IPv6 addresses one household or device is handed. Cycling+// addresses inside it still counts as one network.+const IPV6_NETWORK_PREFIX = 64;++const DAY_MS = 24 * 60 * 60 * 1000;++type NetworkLimit = { limit: number; windowDays: number };++/**+ * The network a signup came from, as a keyed hash so the table holds no+ * address. Null when the request carries no readable address.+ */+export function signupNetworkKey(headers: Headers): string | null {+ const ip = headers.get(FORWARDED_FOR)?.split(",")[0]?.trim();+ if (!ip || !isValidIP(ip)) {+ return null;+ }++ const secret = process.env.BETTER_AUTH_SECRET;+ if (!secret) {+ throw new Error("BETTER_AUTH_SECRET is not set");+ }+ const network = normalizeIP(ip, { ipv6Subnet: IPV6_NETWORK_PREFIX });+ return createHmac("sha256", secret).update(network).digest("hex");+}++/**+ * Takes one of the network's signup grants, and says whether one was left. A+ * window opens at the network's first claim and runs `windowDays`; once it+ * holds `limit` claims, signups from that network get none until it lapses.+ * Each step is a guarded write, so two signups racing on one network can't+ * both take its last claim.+ */+export async function claimSignupGrant(+ networkKey: string,+ cap: NetworkLimit,+ now: Date = new Date(),+): Promise<boolean> {+ // The network's first signup opens its window.+ await prisma.signupNetwork.createMany({+ data: [{ networkKey, windowStart: now, claims: 0 }],+ skipDuplicates: true,+ });++ // A window older than `windowDays` starts over at this signup.+ const lapsedBefore = new Date(now.getTime() - cap.windowDays * DAY_MS);+ await prisma.signupNetwork.updateMany({+ where: { networkKey, windowStart: { lt: lapsedBefore } },+ data: { windowStart: now, claims: 0 },+ });++ // Take a claim while the window has room.+ const { count } = await prisma.signupNetwork.updateMany({+ where: { networkKey, claims: { lt: cap.limit } },+ data: { claims: { increment: 1 } },+ });+ return count === 1;+}