Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

1.8 KB
Raw Blame
"use server";

import { sendEmail } from "@cap/database/emails/config";
import { DownloadLink } from "@cap/database/emails/download-link";
import { checkRateLimit } from "@vercel/firewall";
import { headers } from "next/headers";

function sanitizeEmail(raw: string): string | null {
	const stripped = raw
		.replace(/<[^>]*>/g, "")
		.trim()
		.toLowerCase();

	if (stripped.length === 0 || stripped.length > 254) {
		return null;
	}

	if (
		!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(
			stripped,
		)
	) {
		return null;
	}

	return stripped;
}

export async function sendDownloadLink(email: string) {
	const sanitized = sanitizeEmail(email);
	if (!sanitized) {
		return { success: false, error: "Please enter a valid email address." };
	}

	const headersList = await headers();
	const request = new Request("https://cap.so/api/send-download-link", {
		method: "POST",
		headers: headersList,
	});

	let rateLimited = false;
	try {
		const result = await checkRateLimit("rl_send_download_link", {
			request,
		});
		rateLimited = result.rateLimited;
	} catch (error) {
		// Fail closed: this action is unauthenticated and the rate limit is its
		// only outbound-email guard, and a caller can force checkRateLimit to
		// throw with oversized headers (494).
		rateLimited = true;
		console.error(
			'Rate limit check failed for "rl_send_download_link":',
			error,
		);
	}

	if (rateLimited) {
		return {
			success: false,
			error: "You've sent too many requests. Please try again later.",
		};
	}

	try {
		await sendEmail({
			email: sanitized,
			subject: "Your Cap download links",
			react: DownloadLink({ email: sanitized }),
			marketing: true,
		});

		return { success: true };
	} catch {
		return { success: false, error: "Something went wrong. Please try again." };
	}
}