Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
✨ Wire the nonprofit application pipeline and checkout coupon (RAL-1627, RAL-1624) (#3281)
Luke Vellae669578ca919
diff --git a/apps/web/src/features/billing/actions.ts b/apps/web/src/features/billing/actions.tsindex c8f716a9d..94bc781ee 100644--- a/apps/web/src/features/billing/actions.ts+++ b/apps/web/src/features/billing/actions.ts@@ -5,6 +5,9 @@ import { absoluteUrl } from "@rallly/utils/absolute-url";import { redirect } from "next/navigation";import * as z from "zod";import { createStripePortalSession } from "@/features/billing/mutations";+import { getNonprofitStatus } from "@/features/billing/nonprofit/data";+import { ensureNonprofitCoupon } from "@/features/billing/nonprofit/mutations";+import { buildCheckoutDiscountParams } from "@/features/billing/nonprofit/utils";import type {CustomerMetadata,SubscriptionCheckoutMetadata,@@ -97,7 +100,13 @@ export const upgradeToProAction = authActionClientcustomerId = customer.id;}- const proPricingData = await getProPricing({ stripe });+ const [proPricingData, nonprofit] = await Promise.all([+ getProPricing({ stripe }),+ getNonprofitStatus(space.id),+ ]);+ const discount = buildCheckoutDiscountParams(+ nonprofit.grantedAt ? await ensureNonprofitCoupon() : null,+ );const checkoutSession = await stripe.checkout.sessions.create({success_url: absoluteUrl(@@ -118,7 +127,7 @@ export const upgradeToProAction = authActionClientcurrency && currency in proPricingData.currencies? currency: undefined,- allow_promotion_codes: true,+ ...discount.session,billing_address_collection: "auto",tax_id_collection: {enabled: true,@@ -149,7 +158,7 @@ export const upgradeToProAction = authActionClientafter_expiration: {recovery: {enabled: true,- allow_promotion_codes: true,+ ...discount.recovery,},},});@@ -166,6 +175,7 @@ export const upgradeToProAction = authActionClientproperties: {interval: period === "yearly" ? "year" : "month",currency,+ nonprofit_discount: Boolean(nonprofit.grantedAt),},groups: {space: space.id,diff --git a/apps/web/src/features/billing/mutations.ts b/apps/web/src/features/billing/mutations.tsindex 8f70b0177..bb0b29760 100644--- a/apps/web/src/features/billing/mutations.ts+++ b/apps/web/src/features/billing/mutations.ts@@ -10,6 +10,7 @@ import { prisma } from "@rallly/database";import { absoluteUrl } from "@rallly/utils/absolute-url";import { isBillingEnabled } from "@/features/billing/constants";import { getStripe } from "@/features/billing/service";+import { isStripeResourceMissingError } from "@/features/billing/utils";export async function createStripePortalSession({customerId,@@ -158,15 +159,6 @@ export async function createStripeSubscriptionUpdateConfirmation({return portalSession.url;}-function isStripeResourceMissingError(error: unknown) {- return (- typeof error === "object" &&- error !== null &&- "code" in error &&- (error as { code?: unknown }).code === "resource_missing"- );-}-// Scheduling an account deletion must guarantee no further charges without// destroying anything: cancel_at_period_end stops the renewal while keeping// the paid-for time, and is reversible if the deletion is cancelled.diff --git a/apps/web/src/features/billing/nonprofit/actions.ts b/apps/web/src/features/billing/nonprofit/actions.tsindex 9ef37a1c8..c870da78c 100644--- a/apps/web/src/features/billing/nonprofit/actions.ts+++ b/apps/web/src/features/billing/nonprofit/actions.ts@@ -1,8 +1,18 @@"use server";+import * as Sentry from "@sentry/nextjs";+import { after } from "next/server";import { createMiddleware } from "next-safe-action";import { nonprofitDocumentAssetProfile } from "@/features/billing/nonprofit/constants";-import { signNonprofitDocumentUploadSchema } from "@/features/billing/nonprofit/schema";+import {+ applyForNonprofitDiscount,+ deleteNonprofitDocuments,+} from "@/features/billing/nonprofit/mutations";+import {+ applyForNonprofitDiscountSchema,+ signNonprofitDocumentUploadSchema,+} from "@/features/billing/nonprofit/schema";+import type { NonprofitApplicationStatus } from "@/features/billing/nonprofit/types";import { getActiveSpaceForUser } from "@/features/space/data";import { defineAbilityForMember } from "@/features/space/member/ability";import { AppError } from "@/lib/errors/app-error";@@ -11,7 +21,10 @@ import {authActionClient,createRateLimitMiddleware,} from "@/lib/safe-action/server";-import { createAssetUploadUrl } from "@/lib/storage/asset-upload";+import {+ assertAssetKey,+ createAssetUploadUrl,+} from "@/lib/storage/asset-upload";// Same gate as the billing settings page: the actor's active space, and// only its owner may act. Injects the space into ctx.@@ -59,3 +72,71 @@ export const signNonprofitDocumentUploadAction = authActionClientfileSize: parsedInput.fileSize,});});++/**+ * Resolves to the outcome as a value so the dialog can render it; only the+ * gates (auth, flag, ownership, rate limit, key ownership) throw.+ */+export const applyForNonprofitDiscountAction = authActionClient+ .metadata({ actionName: "apply_for_nonprofit_discount" })+ .use(createRateLimitMiddleware(3, "1 d"))+ .use(billingManageMiddleware)+ .inputSchema(applyForNonprofitDiscountSchema)+ .action(+ async ({+ ctx,+ parsedInput,+ }): Promise<{+ outcome: NonprofitApplicationStatus;+ reason: string | null;+ }> => {+ // Keys are proven before anything else can fail, so a gate that stops+ // the application here still deletes what the applicant uploaded. The+ // mutation deletes on its own paths; nothing reaches it from here.+ const documentKeys: string[] = [];+ for (const key of parsedInput.documentKeys) {+ try {+ assertAssetKey(key, {+ profile: nonprofitDocumentAssetProfile,+ entityId: ctx.space.id,+ });+ } catch (error) {+ after(() => deleteNonprofitDocuments(documentKeys));+ throw error;+ }+ documentKeys.push(key);+ }++ // ctx.user is the database row, so this is not the session snapshot.+ if (!ctx.user.emailVerified) {+ after(() => deleteNonprofitDocuments(documentKeys));+ throw new AppError({+ code: "FORBIDDEN",+ message: "Verify your email address before applying",+ });+ }++ try {+ const result = await applyForNonprofitDiscount({+ spaceId: ctx.space.id,+ userId: ctx.user.id,+ userEmail: ctx.user.email,+ organizationName: parsedInput.organizationName,+ website: parsedInput.website,+ documentKeys,+ });++ if (result.outcome === "already_granted") {+ return { outcome: "approved", reason: null };+ }++ return result;+ } catch (error) {+ Sentry.captureException(error, {+ tags: { errorHandler: "safe-action" },+ extra: { actionName: "apply_for_nonprofit_discount" },+ });+ return { outcome: "failed", reason: null };+ }+ },+ );diff --git a/apps/web/src/features/billing/nonprofit/mutations.ts b/apps/web/src/features/billing/nonprofit/mutations.tsindex 8c2b5a379..2675be044 100644--- a/apps/web/src/features/billing/nonprofit/mutations.ts+++ b/apps/web/src/features/billing/nonprofit/mutations.ts@@ -1,6 +1,42 @@import "server-only";+import { GetObjectCommand } from "@aws-sdk/client-s3";+import { prisma } from "@rallly/database";+import { sendRawEmail } from "@rallly/emails";+import { createLogger } from "@rallly/logger";+import { after } from "next/server";+import { env } from "@/env";+import {+ NONPROFIT_COUPON_ID,+ NONPROFIT_DISCOUNT_PERCENT,+ nonprofitDocumentAssetProfile,+} from "@/features/billing/nonprofit/constants";+import {+ fetchWebsiteText,+ getNonprofitVerifierModelId,+ verifyNonprofit,+} from "@/features/billing/nonprofit/service";+import type {+ NonprofitApplicationStatus,+ NonprofitReasonCode,+} from "@/features/billing/nonprofit/types";+import {+ domainsMatch,+ isFreemailDomain,+ normalizeWebsite,+} from "@/features/billing/nonprofit/utils";+import { getStripe } from "@/features/billing/service";+import {+ isStripeErrorCode,+ isStripeResourceMissingError,+} from "@/features/billing/utils";+import { AppError } from "@/lib/errors/app-error";+import { track } from "@/lib/posthog";+import { parseAssetKey } from "@/lib/storage/asset-profile";import { deleteStoredAsset } from "@/lib/storage/asset-upload";+import { getS3Client } from "@/lib/storage/s3";++const logger = createLogger("nonprofit");/*** Zero retention: the apply step calls this in `finally` via `after()` so@@ -9,3 +45,321 @@ import { deleteStoredAsset } from "@/lib/storage/asset-upload";export async function deleteNonprofitDocuments(keys: readonly string[]) {await Promise.all(keys.map((key) => deleteStoredAsset(key)));}++let couponPromise: Promise<string> | undefined;++/**+ * The Stripe coupon behind the discount, created on first use so there is+ * no dashboard step and test and live mode behave the same. Memoised per+ * process; a failed attempt is forgotten so the next call retries.+ */+export function ensureNonprofitCoupon() {+ couponPromise ??= (async () => {+ const stripe = getStripe();+ try {+ await stripe.coupons.retrieve(NONPROFIT_COUPON_ID);+ } catch (error) {+ if (!isStripeResourceMissingError(error)) throw error;+ try {+ await stripe.coupons.create({+ id: NONPROFIT_COUPON_ID,+ percent_off: NONPROFIT_DISCOUNT_PERCENT,+ duration: "forever",+ name: "Nonprofit discount",+ });+ } catch (createError) {+ // Two processes racing on first use: the other one won.+ if (!isStripeErrorCode(createError, "resource_already_exists")) {+ throw createError;+ }+ }+ }+ return NONPROFIT_COUPON_ID;+ })().catch((error) => {+ couponPromise = undefined;+ throw error;+ });++ return couponPromise;+}++/**+ * The pinned API version takes `coupon`, not `discounts`. The existing+ * customer.subscription.updated webhook records the discount on our row.+ */+export async function applyNonprofitCouponToSubscription({+ subscriptionId,+}: {+ subscriptionId: string;+}) {+ const coupon = await ensureNonprofitCoupon();+ await getStripe().subscriptions.update(subscriptionId, { coupon });+}++async function readDocument(key: string) {+ const parsed = parseAssetKey(key, [nonprofitDocumentAssetProfile]);+ if (!parsed) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Not a nonprofit document key",+ });+ }++ const s3Client = getS3Client();+ if (!s3Client) {+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "S3 storage has not been configured",+ });+ }++ const object = await s3Client.send(+ new GetObjectCommand({ Bucket: env.S3_BUCKET_NAME, Key: key }),+ );+ const data = await object.Body?.transformToByteArray();+ if (!data || data.byteLength === 0) {+ throw new Error("Uploaded document is empty");+ }++ return { mediaType: parsed.mimeType, data };+}++const DETERMINISTIC_REASONS = {+ invalid_website: "The website must be a public https address.",+ freemail_domain:+ "Applications must come from an email address on the organization's own domain, not a personal mailbox provider.",+ domain_mismatch:+ "The email address must be on the same domain as the organization's website.",+} satisfies Partial<Record<NonprofitReasonCode, string>>;++function checkDeterministic({+ emailDomain,+ websiteHost,+}: {+ emailDomain: string;+ websiteHost: string | null;+}): keyof typeof DETERMINISTIC_REASONS | null {+ if (!websiteHost) return "invalid_website";+ if (isFreemailDomain(emailDomain)) return "freemail_domain";+ if (!domainsMatch(emailDomain, websiteHost)) return "domain_mismatch";+ return null;+}++type Decision = {+ status: NonprofitApplicationStatus;+ reasonCode: NonprofitReasonCode;+ reason: string | null;+ model: string | null;+ organizationNameInDocuments: string | null;+};++export type ApplyForNonprofitDiscountResult =+ | { outcome: "already_granted" }+ | { outcome: NonprofitApplicationStatus; reason: string | null };++/**+ * The whole application, from the deterministic checks to the coupon. Every+ * application writes one row and one support email whatever the outcome:+ * that email is the only view of who is applying, so an approved-only or+ * rejected-only notification would hide abuse patterns.+ *+ * Runs inside a request: the documents are deleted with `after()`.+ */+export async function applyForNonprofitDiscount({+ spaceId,+ userId,+ userEmail,+ organizationName,+ website,+ documentKeys,+}: {+ spaceId: string;+ userId: string;+ userEmail: string;+ organizationName: string;+ website: string;+ documentKeys: readonly string[];+}): Promise<ApplyForNonprofitDiscountResult> {+ // Registered before any early return or throw: the documents never+ // outlive the request, whatever happens to the application.+ after(() => deleteNonprofitDocuments(documentKeys));++ const space = await prisma.space.findUnique({+ where: { id: spaceId },+ select: {+ nonprofitDiscountGrantedAt: true,+ subscriptions: {+ where: { active: true },+ select: { id: true },+ take: 1,+ },+ },+ });++ if (!space) {+ throw new AppError({ code: "NOT_FOUND", message: "Space not found" });+ }++ if (space.nonprofitDiscountGrantedAt) {+ return { outcome: "already_granted" };+ }++ const emailDomain = userEmail.slice(userEmail.lastIndexOf("@") + 1);+ const websiteOrigin = normalizeWebsite(website);+ const websiteHost = websiteOrigin ? new URL(websiteOrigin).hostname : null;++ // Writes the row and fires the side effects. With `grant`, the grant is+ // claimed conditionally so two concurrent approvals cannot both record+ // one; the loser returns false and skips the side effects.+ const record = async (decision: Decision, { grant = false } = {}) => {+ const application = {+ spaceId,+ userId,+ organizationName,+ website,+ emailDomain,+ status: decision.status,+ reason: decision.reason,+ model: decision.model,+ };++ if (grant) {+ const claimed = await prisma.$transaction(async (tx) => {+ const { count } = await tx.space.updateMany({+ where: { id: spaceId, nonprofitDiscountGrantedAt: null },+ data: { nonprofitDiscountGrantedAt: new Date() },+ });+ if (count === 0) return false;+ await tx.nonprofitApplication.create({ data: application });+ return true;+ });+ if (!claimed) return false;+ } else {+ await prisma.nonprofitApplication.create({ data: application });+ }++ const actor = { id: userId, isGuest: false };+ const groups = { space: spaceId };+ track(actor, {+ event: "billing:nonprofit_application_submit",+ properties: {+ outcome: decision.status,+ reason_code: decision.reasonCode,+ },+ groups,+ });+ if (decision.status !== "failed") {+ track(actor, {+ event: `billing:nonprofit_application_${decision.status === "approved" ? "approve" : "reject"}`,+ properties: { reason_code: decision.reasonCode },+ groups,+ });+ }++ try {+ await sendRawEmail({+ to: env.SUPPORT_EMAIL,+ subject: `Nonprofit application ${decision.status}: ${organizationName}`,+ text: [+ `Space: ${spaceId}`,+ `Organization: ${organizationName}`,+ `Website: ${website}`,+ `Email domain: ${emailDomain}`,+ `Outcome: ${decision.status} (${decision.reasonCode})`,+ `Reason: ${decision.reason ?? "-"}`,+ `Model: ${decision.model ?? "none (deterministic)"}`,+ `Organization name in documents: ${decision.organizationNameInDocuments ?? "-"}`,+ ].join("\n"),+ });+ } catch (error) {+ logger.error(+ { error, spaceId, status: decision.status },+ "Failed to send nonprofit application notification",+ );+ }+ return true;+ };++ let model: string | null = null;++ try {+ const deterministic = checkDeterministic({ emailDomain, websiteHost });+ if (deterministic) {+ const reason = DETERMINISTIC_REASONS[deterministic];+ await record({+ status: "rejected",+ reasonCode: deterministic,+ reason,+ model: null,+ organizationNameInDocuments: null,+ });+ return { outcome: "rejected", reason };+ }++ const [siteText, documents] = await Promise.all([+ fetchWebsiteText(websiteOrigin as string),+ Promise.all(documentKeys.map(readDocument)),+ ]);++ model = getNonprofitVerifierModelId();+ const { verdict, modelId } = await verifyNonprofit({+ organizationName,+ website: websiteOrigin as string,+ emailDomain,+ siteText,+ documents,+ });+ model = modelId;++ if (verdict.verdict === "approved") {+ // Stripe first so a failure leaves nothing granted; the coupon call is+ // idempotent and the subscription update is safe to repeat.+ const subscription = space.subscriptions[0];+ if (subscription) {+ await applyNonprofitCouponToSubscription({+ subscriptionId: subscription.id,+ });+ } else {+ await ensureNonprofitCoupon();+ }+ }++ const recorded = await record(+ {+ status: verdict.verdict,+ reasonCode:+ verdict.verdict === "approved"+ ? "verifier_approved"+ : "verifier_rejected",+ reason: verdict.reason,+ model,+ organizationNameInDocuments: verdict.organizationNameInDocuments,+ },+ { grant: verdict.verdict === "approved" },+ );+ if (!recorded) return { outcome: "already_granted" };++ return { outcome: verdict.verdict, reason: verdict.reason };+ } catch (error) {+ logger.error({ error, spaceId }, "Nonprofit application failed");+ try {+ await record({+ status: "failed",+ reasonCode: "verifier_error",+ reason: null,+ model,+ organizationNameInDocuments: null,+ });+ } catch (recordError) {+ logger.error(+ { error: recordError, spaceId },+ "Failed to record the failed nonprofit application",+ );+ }+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Nonprofit verification failed",+ cause: error,+ });+ }+}diff --git a/apps/web/src/features/billing/nonprofit/schema.ts b/apps/web/src/features/billing/nonprofit/schema.tsindex 55f008c88..3710dcb11 100644--- a/apps/web/src/features/billing/nonprofit/schema.ts+++ b/apps/web/src/features/billing/nonprofit/schema.ts@@ -1,5 +1,9 @@import * as z from "zod";-import { nonprofitDocumentAssetProfile } from "@/features/billing/nonprofit/constants";+import {+ MAX_DOCUMENTS,+ nonprofitDocumentAssetProfile,+} from "@/features/billing/nonprofit/constants";+import { normalizeWebsite } from "@/features/billing/nonprofit/utils";export const signNonprofitDocumentUploadSchema = z.object({fileType: z.enum(nonprofitDocumentAssetProfile.accept),@@ -17,3 +21,19 @@ export const nonprofitVerdictSchema = z.object({});export type NonprofitVerdict = z.infer<typeof nonprofitVerdictSchema>;++export const applyForNonprofitDiscountSchema = z.object({+ organizationName: z.string().trim().min(1).max(200),+ website: z+ .string()+ .trim()+ .max(2048)+ .refine((value) => normalizeWebsite(value) !== null, {+ message: "Enter the organization's https website",+ }),+ documentKeys: z.array(z.string().min(1)).min(1).max(MAX_DOCUMENTS),+});++export type ApplyForNonprofitDiscountInput = z.infer<+ typeof applyForNonprofitDiscountSchema+>;diff --git a/apps/web/src/features/billing/nonprofit/service.ts b/apps/web/src/features/billing/nonprofit/service.tsindex 37ffd5c1b..6f7db5133 100644--- a/apps/web/src/features/billing/nonprofit/service.ts+++ b/apps/web/src/features/billing/nonprofit/service.ts@@ -1,5 +1,7 @@import "server-only";+import { lookup } from "node:dns/promises";+import { request as httpsRequest } from "node:https";import { createOpenAI } from "@ai-sdk/openai";import { generateObject } from "ai";import { env } from "@/env";@@ -7,6 +9,7 @@ import { NONPROFIT_VERIFIER_DEFAULT_MODEL } from "@/features/billing/nonprofit/cimport type { NonprofitVerdict } from "@/features/billing/nonprofit/schema";import { nonprofitVerdictSchema } from "@/features/billing/nonprofit/schema";import { htmlToText } from "@/features/billing/nonprofit/utils";+import { isPublicAddress } from "@/lib/public-address";const FETCH_TIMEOUT_MS = 5_000;const FETCH_MAX_REDIRECTS = 3;@@ -14,22 +17,93 @@ const FETCH_MAX_BYTES = 200 * 1024;const VERIFY_TIMEOUT_MS = 45_000;-async function readCapped(response: Response) {- const reader = response.body?.getReader();- if (!reader) return "";-- const chunks: Uint8Array[] = [];- let received = 0;- while (received < FETCH_MAX_BYTES) {- const { done, value } = await reader.read();- if (done) break;- chunks.push(value);- received += value.byteLength;- }- await reader.cancel().catch(() => {});+type ResolvedAddress = { address: string; family: number };- const buffer = Buffer.concat(chunks).subarray(0, FETCH_MAX_BYTES);- return new TextDecoder("utf-8", { fatal: false }).decode(buffer);+/**+ * The hostname is applicant supplied, so it must not resolve to anything+ * inside our network. The address returned here is the one the connection+ * is pinned to, so a DNS answer that changes between the check and the+ * connect cannot redirect the request.+ */+async function resolvePublicAddress(+ hostname: string,+): Promise<ResolvedAddress | null> {+ // dns.lookup has no abort signal; the race gives it the fetch deadline+ // and the caller's catch turns a timeout into null.+ const addresses = await Promise.race([+ lookup(hostname, { all: true, verbatim: true }),+ new Promise<never>((_, reject) =>+ setTimeout(+ () => reject(new Error("DNS lookup timed out")),+ FETCH_TIMEOUT_MS,+ ).unref(),+ ),+ ]);+ if (addresses.length === 0) return null;+ if (!addresses.every(({ address }) => isPublicAddress(address))) return null;+ return addresses[0];+}++type CappedResponse = {+ status: number;+ location: string | null;+ contentType: string;+ body: string;+};++/**+ * One GET pinned to `pinned` for the socket while TLS and the Host header+ * keep the hostname. Reads at most FETCH_MAX_BYTES of the body.+ */+function getPinned(url: URL, pinned: ResolvedAddress) {+ return new Promise<CappedResponse>((resolve, reject) => {+ const request = httpsRequest(+ url,+ {+ method: "GET",+ timeout: FETCH_TIMEOUT_MS,+ headers: {+ accept: "text/html",+ "user-agent": "Rallly nonprofit verifier (+https://rallly.co)",+ },+ // net calls this with `all` when it wants every address; either way+ // it only ever gets the one we checked.+ lookup: (_hostname, options, callback) => {+ if (options.all) {+ callback(null, [pinned]);+ } else {+ callback(null, pinned.address, pinned.family);+ }+ },+ },+ (response) => {+ const chunks: Buffer[] = [];+ let received = 0;+ const finish = () => {+ const buffer = Buffer.concat(chunks).subarray(0, FETCH_MAX_BYTES);+ resolve({+ status: response.statusCode ?? 0,+ location: response.headers.location ?? null,+ contentType: response.headers["content-type"] ?? "",+ body: new TextDecoder("utf-8", { fatal: false }).decode(buffer),+ });+ };+ response.on("data", (chunk: Buffer) => {+ chunks.push(chunk);+ received += chunk.byteLength;+ if (received >= FETCH_MAX_BYTES) {+ response.destroy();+ finish();+ }+ });+ response.on("end", finish);+ response.on("error", reject);+ },+ );+ request.on("timeout", () => request.destroy(new Error("Fetch timed out")));+ request.on("error", reject);+ request.end();+ });}/**@@ -44,21 +118,14 @@ export async function fetchWebsiteText(url: string) {let current = origin;for (let hop = 0; hop <= FETCH_MAX_REDIRECTS; hop++) {- const response = await fetch(current, {- redirect: "manual",- cache: "no-store",- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),- headers: {- accept: "text/html",- "user-agent": "Rallly nonprofit verifier (+https://rallly.co)",- },- });+ const pinned = await resolvePublicAddress(current.hostname);+ if (!pinned) return null;++ const response = await getPinned(current, pinned);if (response.status >= 300 && response.status < 400) {- const location = response.headers.get("location");- await response.body?.cancel().catch(() => {});- if (!location) return null;- const next = new URL(location, current);+ if (!response.location) return null;+ const next = new URL(response.location, current);if (next.protocol !== "https:" || next.hostname !== origin.hostname) {return null;}@@ -66,12 +133,10 @@ export async function fetchWebsiteText(url: string) {continue;}- if (!response.ok) return null;+ if (response.status !== 200) return null;+ if (!response.contentType.includes("text/html")) return null;- const contentType = response.headers.get("content-type") ?? "";- if (!contentType.includes("text/html")) return null;-- const text = htmlToText(await readCapped(response));+ const text = htmlToText(response.body);return text || null;}@@ -94,6 +159,10 @@ Reject when any criterion fails or when you are not sure. Reject screenshots orWrite "reason" for the applicant: one or two plain sentences saying what was accepted or what was missing, without naming these criteria by number. Set "organizationNameInDocuments" to the organization name exactly as it appears in the documents, or null if no document names an organization.`;+export function getNonprofitVerifierModelId() {+ return env.NONPROFIT_VERIFIER_MODEL || NONPROFIT_VERIFIER_DEFAULT_MODEL;+}+function resolveModel(modelId: string) {// `provider/model` is a Vercel AI Gateway id, handled by the ai package's// default provider. A bare id goes to OpenAI directly.@@ -118,8 +187,7 @@ export async function verifyNonprofit({siteText: string | null;documents: { mediaType: string; data: Uint8Array }[];}): Promise<{ verdict: NonprofitVerdict; modelId: string }> {- const modelId =- env.NONPROFIT_VERIFIER_MODEL || NONPROFIT_VERIFIER_DEFAULT_MODEL;+ const modelId = getNonprofitVerifierModelId();const result = await generateObject({model: resolveModel(modelId),diff --git a/apps/web/src/features/billing/nonprofit/types.ts b/apps/web/src/features/billing/nonprofit/types.tsindex d792a06cd..f66262e6d 100644--- a/apps/web/src/features/billing/nonprofit/types.ts+++ b/apps/web/src/features/billing/nonprofit/types.ts@@ -1,5 +1,15 @@export type NonprofitApplicationStatus = "approved" | "rejected" | "failed";+// Why an application ended the way it did, for analytics. The deterministic+// codes never reach the model; the verifier codes always did.+export type NonprofitReasonCode =+ | "invalid_website"+ | "freemail_domain"+ | "domain_mismatch"+ | "verifier_approved"+ | "verifier_rejected"+ | "verifier_error";+export type NonprofitStatus = {grantedAt: Date | null;latestApplication: {diff --git a/apps/web/src/features/billing/nonprofit/utils.test.ts b/apps/web/src/features/billing/nonprofit/utils.test.tsindex e45ad2805..bd1b49d3e 100644--- a/apps/web/src/features/billing/nonprofit/utils.test.ts+++ b/apps/web/src/features/billing/nonprofit/utils.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";import { NONPROFIT_SITE_TEXT_MAX_CHARS } from "./constants";import {+ buildCheckoutDiscountParams,domainsMatch,htmlToText,isFreemailDomain,@@ -93,3 +94,19 @@ describe("htmlToText", () => {expect(htmlToText(html)).toHaveLength(NONPROFIT_SITE_TEXT_MAX_CHARS);});});++describe("buildCheckoutDiscountParams", () => {+ it("attaches the coupon and drops promotion codes for an entitled space", () => {+ expect(buildCheckoutDiscountParams("nonprofit-20")).toEqual({+ session: { discounts: [{ coupon: "nonprofit-20" }] },+ recovery: { allow_promotion_codes: false },+ });+ });++ it("keeps promotion codes and no discount otherwise", () => {+ const params = buildCheckoutDiscountParams(null);+ expect(params.session).toEqual({ allow_promotion_codes: true });+ expect(params.session).not.toHaveProperty("discounts");+ expect(params.recovery).toEqual({ allow_promotion_codes: true });+ });+});diff --git a/apps/web/src/features/billing/nonprofit/utils.ts b/apps/web/src/features/billing/nonprofit/utils.tsindex 0e2fff331..cdef6692c 100644--- a/apps/web/src/features/billing/nonprofit/utils.ts+++ b/apps/web/src/features/billing/nonprofit/utils.ts@@ -1,3 +1,4 @@+import type { Stripe } from "@rallly/billing";import {FREEMAIL_DOMAINS,NONPROFIT_SITE_TEXT_MAX_CHARS,@@ -76,3 +77,31 @@ export function htmlToText(html: string) {? text.slice(0, NONPROFIT_SITE_TEXT_MAX_CHARS): text;}++/**+ * Checkout params for the discount. Stripe rejects `discounts` together+ * with `allow_promotion_codes`, so an entitled space gets the coupon and+ * loses the promotion code field, on the session and on the recovery email+ * alike; everyone else keeps the field.+ */+export function buildCheckoutDiscountParams(coupon: string | null): {+ session: Pick<+ Stripe.Checkout.SessionCreateParams,+ "discounts" | "allow_promotion_codes"+ >;+ recovery: Pick<+ Stripe.Checkout.SessionCreateParams.AfterExpiration.Recovery,+ "allow_promotion_codes"+ >;+} {+ if (coupon) {+ return {+ session: { discounts: [{ coupon }] },+ recovery: { allow_promotion_codes: false },+ };+ }+ return {+ session: { allow_promotion_codes: true },+ recovery: { allow_promotion_codes: true },+ };+}diff --git a/apps/web/src/features/billing/utils.ts b/apps/web/src/features/billing/utils.tsindex 23a638793..560f33f78 100644--- a/apps/web/src/features/billing/utils.ts+++ b/apps/web/src/features/billing/utils.ts@@ -9,3 +9,16 @@ import type { SpaceTier } from "@/features/space/schema";export function resolveSpaceTier(storedTier: SpaceTier): SpaceTier {return isBillingEnabled ? storedTier : "pro";}++export function isStripeErrorCode(error: unknown, code: string) {+ return (+ typeof error === "object" &&+ error !== null &&+ "code" in error &&+ (error as { code?: unknown }).code === code+ );+}++export function isStripeResourceMissingError(error: unknown) {+ return isStripeErrorCode(error, "resource_missing");+}diff --git a/apps/web/src/features/user/data.ts b/apps/web/src/features/user/data.tsindex 2be167573..92a4aa0f2 100644--- a/apps/web/src/features/user/data.ts+++ b/apps/web/src/features/user/data.ts@@ -18,6 +18,7 @@ export const createUserDTO = (user: User): UserDTO => ({customerId: user.customerId ?? undefined,isGuest: user.isAnonymous,deletedAt: user.deletedAt ?? undefined,+ emailVerified: user.emailVerified ?? false,});export const getUser = async (userId: string) => {diff --git a/apps/web/src/features/user/schema.ts b/apps/web/src/features/user/schema.tsindex 94a59578b..9dca5cea6 100644--- a/apps/web/src/features/user/schema.ts+++ b/apps/web/src/features/user/schema.ts@@ -41,7 +41,8 @@ export type UserDTO = {locale?: string;weekStart?: number;customerId?: string;- // Only populated on database-derived DTOs (createUserDTO); deletedAt is- // deliberately not part of the session user object.+ // Only populated on database-derived DTOs (createUserDTO); deletedAt and+ // emailVerified are deliberately not part of the session user object.deletedAt?: Date;+ emailVerified?: boolean;};diff --git a/apps/web/src/lib/public-address.test.ts b/apps/web/src/lib/public-address.test.tsnew file mode 100644index 000000000..1db0b905e--- /dev/null+++ b/apps/web/src/lib/public-address.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from "vitest";+import { isPublicAddress } from "./public-address";++describe("isPublicAddress", () => {+ it.each([+ "8.8.8.8",+ "93.184.216.34",+ "2606:4700::6810:84e5",+ "::ffff:93.184.216.34",+ ])("accepts %s", (address) => {+ expect(isPublicAddress(address)).toBe(true);+ });++ it.each([+ "127.0.0.1",+ "10.1.2.3",+ "172.16.0.1",+ "192.168.1.1",+ "169.254.169.254",+ "100.64.0.1",+ "0.0.0.0",+ "224.0.0.1",+ "::1",+ "::",+ "fd00::1",+ "fe80::1",+ "::ffff:127.0.0.1",+ "64:ff9b::7f00:1",+ "64:ff9b:1::c0a8:1",+ "not-an-ip",+ ])("rejects %s", (address) => {+ expect(isPublicAddress(address)).toBe(false);+ });+});diff --git a/apps/web/src/lib/public-address.ts b/apps/web/src/lib/public-address.tsnew file mode 100644index 000000000..9ff8ad73d--- /dev/null+++ b/apps/web/src/lib/public-address.ts@@ -0,0 +1,47 @@+import "server-only";++import { BlockList, isIP } from "node:net";++// Loopback, link local (cloud metadata lives there), private, carrier grade+// NAT, benchmarking, multicast, reserved and unspecified. Anything an+// applicant's hostname resolves to must fall outside these before we fetch.+const nonPublicAddresses = new BlockList();+for (const [subnet, prefix] of [+ ["0.0.0.0", 8],+ ["10.0.0.0", 8],+ ["100.64.0.0", 10],+ ["127.0.0.0", 8],+ ["169.254.0.0", 16],+ ["172.16.0.0", 12],+ ["192.0.0.0", 24],+ ["192.0.2.0", 24],+ ["192.168.0.0", 16],+ ["198.18.0.0", 15],+ ["198.51.100.0", 24],+ ["203.0.113.0", 24],+ ["224.0.0.0", 3],+] as const) {+ nonPublicAddresses.addSubnet(subnet, prefix, "ipv4");+}+for (const [subnet, prefix] of [+ ["::", 128],+ ["::1", 128],+ ["64:ff9b::", 96],+ ["64:ff9b:1::", 48],+ ["100::", 64],+ ["2001:db8::", 32],+ ["fc00::", 7],+ ["fe80::", 10],+ ["ff00::", 8],+] as const) {+ nonPublicAddresses.addSubnet(subnet, prefix, "ipv6");+}++export function isPublicAddress(address: string) {+ // IPv4 mapped IPv6 (`::ffff:10.0.0.1`) is checked as the IPv4 it wraps.+ const mapped = address.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);+ const candidate = mapped ? mapped[1] : address;+ const family = isIP(candidate);+ if (family === 0) return false;+ return !nonPublicAddresses.check(candidate, family === 4 ? "ipv4" : "ipv6");+}