A post going around X this week put it in one line: "Vibe coding a website is great until you realize you forgot to add spam protection or rate limiting to your forms." Around the same time, a write-up made the rounds about an AI-built booking app wired to Stripe, OpenAI, Supabase and Resend. None of its keys had spending caps, and it logged 212 unauthorized requests in two weeks.
Neither one surprised me. When we generate marketing sites, the contact form, the waitlist box, or the "book a demo" form is usually the only part with a backend. It's also the part nobody looks at after the first test message shows up in the inbox. The page loads, the form works, ship it.
So I wanted to see what that form actually allows. I wrote the kind of /api/contact handler a coding agent produces when you ask for "a working contact form that emails us and sends the visitor a confirmation". Then I wrote a script that abuses it the way bots and bored people do, hardened the handler, and ran the same script again. Everything runs locally. The email API is a stub that counts what it would have sent, so no real email went anywhere. All the numbers below come from those runs.
It doesn't matter whether the site came from Cursor, Claude Code or an AI website builder. If there's a form that triggers an email, this applies.
The naive handler
This is a fictional invoicing product called Ledgerly, with a Vercel-style serverless function. Generated code tends to come out in roughly this shape:
// What a coding agent typically writes for "add a working contact form that emails us
// and sends the visitor a confirmation". Deliberately naive. Do not ship this.
import { mailer as resend } from "../mailer.mjs";
export const formHtml = `<form method="post" action="/api/contact">
<input name="name" placeholder="Your name" required>
<input name="email" type="email" placeholder="you@company.com" required>
<textarea name="message" required></textarea>
<button>Send</button>
</form>`;
export default async function handler(req, res) {
if (req.method !== "POST") return res.status(405).end();
const { name, email, message } = req.body;
// notify the team
await resend.emails.send({
from: "Ledgerly <hello@ledgerly.example>",
to: "team@ledgerly.example",
replyTo: email,
subject: `New message from ${name}`,
html: `<p><b>${name}</b> (${email}) wrote:</p><p>${message}</p>`,
});
// confirm to the visitor
await resend.emails.send({
from: "Ledgerly <hello@ledgerly.example>",
to: email,
subject: `Thanks for reaching out, ${name}!`,
html: `<p>Hi ${name},</p><p>Thanks for contacting Ledgerly. We'll get back to you within 24 hours.</p>`,
});
return res.status(200).json({ ok: true });
}
It looks harmless. It validates nothing, and every POST sends two emails. One goes to your team. The other goes to whatever address the request claims, with the request's name in the subject and body. That second email is the problem.
The harness
Three small pieces, Node only, no dependencies:
-
mailer.mjsstands in for the email client.emails.send()pushes the message into an in-memory array and returns a fake id. No network. -
server.mjsis a tiny stand-in for the platform. It parses JSON, applies a 5 MB body limit, setsreq.ip, and mounts the handler. It lets the test script fake client IPs through anX-Test-Client-IPheader so one machine can play many clients. A real platform works out the client IP itself. Never trust a client-supplied header for this in production. -
attack.mjsstarts a fresh server for each attack (so rate-limit state doesn't leak between tests), fires requests, then reads the stub's outbox and counts what got through.
The attacks:
| Attack | What it does |
|---|---|
| form-bot | 50 posts from a bot that loads the form, fills every field it finds, and submits instantly |
| fast-bot | 50 posts from a bot that skips hidden fields but still submits in under a second |
| replay | one form token reused for 20 posts |
| burst | 200 posts from one IP in a tight loop |
| autoreply-bomb | 100 posts with victim@example.net as the sender, from 100 different IPs |
| distributed | 300 posts from 300 IPs with 300 different sender addresses (quota drain) |
| crlf |
"Bob\r\nBcc: everyone@list.example" as the name |
| phish-name |
"Account locked! Verify: https://ledgerly-verify.example" as the name, victim's address as sender |
| html-message | an <a href> "invoice overdue, pay here" link in the message |
| oversized | a 1 MB message |
There's also a control: one normal message from a person, to make sure the hardening doesn't break the form.
Note that burst, autoreply-bomb, distributed and replay are run by a careful attacker. It loads the form first, keeps any token it finds, leaves hidden fields empty, and waits a few seconds before firing. I did that on purpose. Bot checks stop lazy scripts, and I wanted to see what's left once someone puts in a little effort.
attack.mjs (about 135 lines)
// Fires realistic abuse at a local contact endpoint and reports what reached the email API.
// Usage: node attack.mjs naive|hardened [--json out.json]
// Everything stays on 127.0.0.1. The "email API" is the in-memory stub in mailer.mjs.
import { spawn } from "node:child_process";
import { writeFileSync } from "node:fs";
const target = process.argv[2];
const jsonOut = process.argv.includes("--json") ? process.argv[process.argv.indexOf("--json") + 1] : null;
const TEAM = "team@ledgerly.example", VICTIM = "victim@example.net";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function withServer(fn) {
const child = spawn(process.execPath, ["server.mjs", target, "0"], {
cwd: new URL(".", import.meta.url).pathname, env: { ...process.env, MIN_FILL_MS: "3000", DAILY_SEND_CAP: "50" },
});
const p = await new Promise((ok, bad) => {
child.stdout.on("data", (d) => { const m = String(d).match(/on :(\d+)/); if (m) ok(m[1]); });
child.on("exit", (c) => bad(new Error(`server exited ${c}`)));
});
const base = `http://127.0.0.1:${p}`;
try { return await fn(base); } finally { child.kill(); }
}
const getForm = async (base) => (await fetch(`${base}/contact`)).text();
const fields = (html) => [...html.matchAll(/<(?:input|textarea)[^>]*name="([^"]+)"(?:[^>]*value="([^"]*)")?/g)].map((m) => [m[1], m[2] || ""]);
async function post(base, body, ip = "203.0.113.7") {
const r = await fetch(`${base}/api/contact`, {
method: "POST", headers: { "content-type": "application/json", "x-test-client-ip": ip }, body: JSON.stringify(body),
});
let j = {}; try { j = await r.json(); } catch {}
return { status: r.status, reason: j.reason || j._dropped || null };
}
// A careful attacker reads the form: keeps any token, leaves unknown hidden fields alone,
// and waits out a minimum fill time once for a whole batch of pre-fetched forms.
async function patientTokens(base, n) {
const toks = [];
for (let i = 0; i < n; i++) { const t = fields(await getForm(base)).find(([k]) => k === "token"); toks.push(t ? t[1] : undefined); }
if (toks.some(Boolean)) await sleep(3100);
return toks;
}
async function run(name, what, fn) {
return withServer(async (base) => {
const results = await fn(base);
const outbox = await (await fetch(`${base}/__outbox`)).json();
const reasons = {};
for (const r of results) if (r.reason) reasons[r.reason] = (reasons[r.reason] || 0) + 1;
const unsafe = outbox.filter((m) =>
/[\r\n]/.test(m.subject) || /https?:\/\//.test(m.subject) ||
(m.to !== TEAM && /https?:\/\//.test(m.html || "")) || /<a\s|<script/i.test(m.html || ""));
return {
name, what, requests: results.length,
accepted: results.filter((r) => r.status >= 200 && r.status < 300).length,
emails: outbox.length,
toOutsiders: outbox.filter((m) => m.to !== TEAM).length,
toVictim: outbox.filter((m) => m.to === VICTIM).length,
unsafe: unsafe.length,
bytesToProvider: outbox.reduce((s, m) => s + (m.html || "").length + (m.text || "").length + (m.subject || "").length, 0),
reasons, sample: (() => { const m = unsafe.find((x) => x.to !== TEAM) || unsafe[0]; return m ? { to: m.to, subject: m.subject, html: (m.html || "").slice(0, 160) } : null; })(),
};
});
}
const attacks = [
["control", "1 normal human submission (should still work)", async (b) => {
const [token] = await patientTokens(b, 1);
return [await post(b, { name: "Dana Ortiz", email: "dana@smallshop.example", message: "Do you support CSV export for my accountant?", token })];
}],
["form-bot", "50 bot posts that fill every field and submit instantly", async (b) => {
const out = [];
for (let i = 0; i < 50; i++) {
const body = {};
for (const [k, v] of fields(await getForm(b)))
body[k] = v || ({ name: "Crypto Bonus", email: `bot${i}@spam.example`, message: "Claim your bonus at https://spam.example" }[k] || "https://spam.example");
out.push(await post(b, body, "198.51.100.23"));
}
return out;
}],
["fast-bot", "50 bot posts that skip hidden fields but submit within 1s", async (b) => {
const out = [];
for (let i = 0; i < 50; i++) {
const tok = fields(await getForm(b)).find(([k]) => k === "token");
out.push(await post(b, { name: "Promo", email: `fast${i}@spam.example`, message: "cheap backlinks, reply now", token: tok && tok[1] }, "198.51.100.24"));
}
return out;
}],
["replay", "1 aged form token reused for 20 posts", async (b) => {
const [token] = await patientTokens(b, 1), out = [];
for (let i = 0; i < 20; i++) out.push(await post(b, { name: "Kim", email: `kim${i}@replay.example`, message: "same token again", token }, `172.16.0.${i + 1}`));
return out;
}],
["burst", "200 posts from one IP in a tight loop", async (b) => {
const toks = await patientTokens(b, 200), out = [];
for (let i = 0; i < 200; i++) out.push(await post(b, { name: "Sam", email: `sam${i}@flood.example`, message: "hello hello", token: toks[i] }));
return out;
}],
["autoreply-bomb", `100 posts with ${VICTIM} as the sender, 100 different IPs`, async (b) => {
const toks = await patientTokens(b, 100), out = [];
for (let i = 0; i < 100; i++) out.push(await post(b, { name: "Alex", email: VICTIM, message: "pls call me back", token: toks[i] }, `192.0.2.${i + 1}`));
return out;
}],
["distributed", "300 posts, 300 IPs, 300 sender addresses (quota drain)", async (b) => {
const toks = await patientTokens(b, 300), out = [];
for (let i = 0; i < 300; i++) out.push(await post(b, { name: "Lee", email: `lee${i}@many.example`, message: "question about pricing", token: toks[i] }, `10.${i >> 8}.${i & 255}.9`));
return out;
}],
["crlf", "CRLF + fake Bcc header in the name field", async (b) => {
const [token] = await patientTokens(b, 1);
return [await post(b, { name: "Bob\r\nBcc: everyone@list.example", email: "bob@example.org", message: "hi there", token })];
}],
["phish-name", "phishing text + URL in name, victim's address as sender", async (b) => {
const [token] = await patientTokens(b, 1);
return [await post(b, { name: "Account locked! Verify: https://ledgerly-verify.example", email: VICTIM, message: "x".repeat(20), token })];
}],
["html-message", "HTML link in message (lands in the team's inbox)", async (b) => {
const [token] = await patientTokens(b, 1);
return [await post(b, { name: "Jo", email: "jo@example.org", message: '<a href="https://evil.example/pay">Invoice #4471 overdue, pay here</a>', token })];
}],
["oversized", "1 MB message", async (b) => {
const [token] = await patientTokens(b, 1);
return [await post(b, { name: "Pat", email: "big@example.org", message: "M".repeat(1_000_000), token })];
}],
];
const report = [];
console.log(`\n=== target: ${target} ===`);
for (const [name, what, fn] of attacks) {
const r = await run(name, what, fn);
report.push(r);
const rs = Object.entries(r.reasons).map(([k, v]) => `${k}×${v}`).join(" ");
console.log(`${name.padEnd(15)} req=${String(r.requests).padStart(3)} 2xx=${String(r.accepted).padStart(3)} emails=${String(r.emails).padStart(3)} to-outsiders=${String(r.toOutsiders).padStart(3)} unsafe=${r.unsafe} bytes=${r.bytesToProvider}${rs ? " [" + rs + "]" : ""}`);
if (r.sample) console.log(`${" ".repeat(15)} e.g. to=${r.sample.to} subject=${JSON.stringify(r.sample.subject).slice(0, 110)}`);
}
const tot = (k) => report.filter((r) => r.name !== "control").reduce((s, r) => s + r[k], 0);
console.log(`TOTAL (attacks only) requests=${tot("requests")} emails=${tot("emails")} to-outsiders=${tot("toOutsiders")} unsafe=${tot("unsafe")} bytes=${tot("bytesToProvider")}`);
if (jsonOut) writeFileSync(jsonOut, JSON.stringify(report, null, 2));
server.mjs and mailer.mjs
// Tiny local stand-in for a serverless platform: parses JSON, sets req.ip, mounts the handler.
// The harness fakes client IPs through X-Test-Client-IP so one machine can play many clients.
// (A real platform derives the IP itself. Never trust a client-supplied header for this.)
import http from "node:http";
import { outbox } from "./mailer.mjs";
const which = process.argv[2]; // "naive" | "hardened"
const port = Number(process.argv[3] || 0); // 0 = let the OS pick a free port
const mod = await import(`./${which}/contact.mjs`);
const BODY_LIMIT = 5 * 1024 * 1024; // platform-style body limit for the harness
const srv = http.createServer(async (req, rq) => {
const res = {
status(c) { rq.statusCode = c; return res; },
json(o) { rq.setHeader("content-type", "application/json"); rq.end(JSON.stringify(o)); },
end(s) { rq.end(s); },
};
if (req.url === "/__outbox") { rq.setHeader("content-type", "application/json"); return rq.end(JSON.stringify(outbox)); }
if (req.url === "/__reset") { outbox.length = 0; return rq.end("ok"); }
if (req.url === "/contact") {
const html = typeof mod.formHtml === "function" ? mod.formHtml(mod.issueToken()) : mod.formHtml;
rq.setHeader("content-type", "text/html"); return rq.end(html);
}
if (req.url !== "/api/contact") return res.status(404).end();
let raw = "", size = 0;
for await (const chunk of req) { size += chunk.length; if (size > BODY_LIMIT) return res.status(413).end(); raw += chunk; }
try { req.body = raw ? JSON.parse(raw) : {}; } catch { return res.status(400).json({ ok: false, reason: "bad-json" }); }
req.ip = req.headers["x-test-client-ip"] || req.socket.remoteAddress;
try { await mod.default(req, res); } catch (e) { res.status(500).json({ ok: false, reason: String(e) }); }
});
srv.listen(port, "127.0.0.1", () => console.log(`${which} on :${srv.address().port}`));
// Stand-in for an email API client (Resend, Postmark, SES...). It never touches the
// network: every "send" is appended to an in-memory outbox the harness can inspect.
export const outbox = [];
export const mailer = {
emails: {
async send(msg) {
outbox.push({ ...msg, at: Date.now() });
return { id: `stub_${outbox.length}` };
},
},
};
Run 1: the naive handler
$ node harness/attack.mjs naive
=== target: naive ===
control req= 1 2xx= 1 emails= 2 to-outsiders= 1 unsafe=0 bytes=268
form-bot req= 50 2xx= 50 emails=100 to-outsiders= 50 unsafe=0 bytes=13390
fast-bot req= 50 2xx= 50 emails=100 to-outsiders= 50 unsafe=0 bytes=11340
replay req= 20 2xx= 20 emails= 40 to-outsiders= 20 unsafe=0 bytes=4190
burst req=200 2xx=200 emails=400 to-outsiders=200 unsafe=0 bytes=40890
autoreply-bomb req=100 2xx=100 emails=200 to-outsiders=100 unsafe=0 bytes=21200
distributed req=300 2xx=300 emails=600 to-outsiders=300 unsafe=0 bytes=64390
crlf req= 1 2xx= 1 emails= 2 to-outsiders= 1 unsafe=2 bytes=309
e.g. to=bob@example.org subject="Thanks for reaching out, Bob\r\nBcc: everyone@list.example!"
phish-name req= 1 2xx= 1 emails= 2 to-outsiders= 1 unsafe=2 bytes=420
e.g. to=victim@example.net subject="Thanks for reaching out, Account locked! Verify: https://ledgerly-verify.example!"
html-message req= 1 2xx= 1 emails= 2 to-outsiders= 1 unsafe=1 bytes=254
e.g. to=team@ledgerly.example subject="New message from Jo"
oversized req= 1 2xx= 1 emails= 2 to-outsiders= 1 unsafe=0 bytes=1000189
TOTAL (attacks only) requests=724 emails=1448 to-outsiders=724 unsafe=5 bytes=1156572
emails counts calls to the email API. to-outsiders counts emails sent to any address other than the team's. unsafe counts emails where a CR/LF or a URL from the request ended up in the subject, a URL ended up in an email to an outside address, or raw HTML from the request ended up in the body.
Here's what that means in practice:
It's an email relay. 724 attack requests turned into 1,448 emails, and 724 of them went to addresses the attacker picked. The autoreply-bomb run sent 100 "Thanks for reaching out" emails to victim@example.net from 100 IPs. Nobody had to compromise anything. That's just what the form does. To the victim it looks like your domain is spamming them. To their mail provider, it looks the same.
It's a phishing kit with your logo on it. In the phish-name run, the victim got an email from your real domain with this subject:
Thanks for reaching out, Account locked! Verify: https://ledgerly-verify.example!
and the same text in the greeting. SPF and DKIM would pass, because you really did send it. That's the most dangerous row in the table, and it only took one request.
User input reaches the subject line untouched. The CRLF test passed Bob\r\nBcc: everyone@list.example into the subject of both emails. What happens next depends on your transport. JSON email APIs take the subject as a field rather than as raw headers, so they may reject or encode it. I didn't test any real provider, so I won't guess which. If your stack builds raw SMTP messages, such as a hand-rolled mail function or custom headers in an SMTP library, this is classic header injection. Either way, there's no good reason for a newline from a form to reach the subject.
Your team's inbox renders attacker HTML. The internal notification puts the message straight into html. So the <a href> "Invoice #4471 overdue, pay here" link shows up as a real, clickable link in the email your team reads, and that's exactly the kind of link people click.
There's no ceiling. A 1 MB message went through, and the run sent just over 1 MB of text to the email API for one request. With no rate limit and no daily cap, anyone can burn through your email plan's quota and your function invocations, then however many more requests they feel like sending. That's the part the booking-app write-up was about: keys with no spending cap behind an endpoint anyone can call.
The hardened handler
Here's the order of checks, cheapest first:
The pieces that matter:
export default async function handler(req, res) {
if (req.method !== "POST") return res.status(405).end();
const now = Date.now();
const ip = req.ip; // set by the platform, not by a client header you parse yourself
const b = req.body || {};
const reject = (status, reason) => res.status(status).json({ ok: false, reason });
// 1. bot checks first, and answer bots with a fake success so they don't adapt
if (b.website) return res.status(200).json({ ok: true, _dropped: "honeypot" });
const tokErr = checkToken(b.token, now);
if (tokErr === "too-fast") return res.status(200).json({ ok: true, _dropped: "too-fast" });
if (tokErr) return reject(400, tokErr);
// 2. shape and size
const bad = validate(b);
if (bad) return reject(400, bad);
// 3. rate limits
if (limited(`ip:${ip}`, PER_IP, now)) return reject(429, "ip-rate-limit");
if (limited(`email:${b.email.toLowerCase()}`, PER_EMAIL, now)) return reject(429, "email-rate-limit");
const today = new Date(now).toISOString().slice(0, 10);
if (today !== day) { day = today; sentToday = 0; }
if (sentToday >= DAILY_SEND_CAP) return reject(503, "daily-cap");
sentToday++;
// 4. one email, to us only. Fixed subject; user text escaped and only in the body.
await resend.emails.send({
from: "Ledgerly <hello@ledgerly.example>",
to: "team@ledgerly.example",
replyTo: b.email,
subject: "New contact form message",
text: `From: ${b.name} <${b.email}>\nIP: ${ip}\n\n${b.message}`,
html: `<p>From: ${esc(b.name)} <${esc(b.email)}></p><pre>${esc(b.message)}</pre>`,
});
// No auto-reply. The page shows "Thanks, we got it". Confirmation emails go out only
// after the address is verified (double opt-in) and never contain user-supplied text.
return res.status(200).json({ ok: true });
}
Some decisions behind it:
- No auto-reply. This is the biggest fix, and it's a product decision, not a code trick. The thank-you message lives on the page. If you really need a confirmation email (a waitlist, say), send it only after the address is verified with double opt-in, and use a fixed template that contains nothing the visitor typed. Not even their name.
-
Fixed subject. User text only in the body, escaped. The team email's subject is always
New contact form message. The name, email and message go into atextpart and an escapedhtmlpart. -
A honeypot and a signed, single-use, minimum-age token. The form gets a hidden
websitefield and a token made oftimestamp.nonce.HMAC. The token is stateless to issue, can't be forged, and is rejected if it's less than 3 seconds old or already used. Bots caught by the honeypot or the too-fast check get a fake200 OK, so they have nothing to adapt to. A missing, forged or reused token gets a plain 400. -
Server-side validation with hard caps. Name 1–80 characters with no control characters, URLs or angle brackets. Email 254 characters max and a sane shape. Message 2–5,000 characters.
maxlengthon the inputs is a courtesy for humans. The server check is the one that counts. - Three rate limits. 5 per IP per 10 minutes, 3 per sender address per day, and a daily cap on total sends. Each one catches a different attack, as you'll see below.
Full hardened/contact.mjs (about 110 lines)
// The same endpoint after a security pass. Stdlib only, no captcha vendor.
import crypto from "node:crypto";
import { mailer as resend } from "../mailer.mjs";
const SECRET = process.env.FORM_SECRET || crypto.randomBytes(32).toString("hex");
const MIN_FILL_MS = Number(process.env.MIN_FILL_MS || 3000); // humans take longer than this
const MAX_TOKEN_AGE_MS = 2 * 60 * 60 * 1000; // form token valid for 2h
const PER_IP = { max: 5, windowMs: 10 * 60 * 1000 }; // 5 per IP per 10 min
const PER_EMAIL = { max: 3, windowMs: 24 * 60 * 60 * 1000 }; // 3 per sender address per day
const DAILY_SEND_CAP = Number(process.env.DAILY_SEND_CAP || 50); // circuit breaker for the whole form
// In-memory state is fine for one long-running server. On serverless, every instance has
// its own memory: put these counters in Redis/KV/your database instead.
const hits = new Map(); // key -> [timestamps]
const usedTokens = new Set(); // single-use form tokens
let day = new Date().toISOString().slice(0, 10), sentToday = 0;
const sign = (s) => crypto.createHmac("sha256", SECRET).update(s).digest("base64url");
export function issueToken(now = Date.now()) {
const nonce = crypto.randomBytes(9).toString("base64url");
return `${now}.${nonce}.${sign(`${now}.${nonce}`)}`;
}
function checkToken(tok, now) {
const [ts, nonce, mac] = String(tok || "").split(".");
if (!ts || !nonce || !mac) return "missing-token";
const good = sign(`${ts}.${nonce}`);
if (mac.length !== good.length || !crypto.timingSafeEqual(Buffer.from(mac), Buffer.from(good))) return "bad-token";
const age = now - Number(ts);
if (age < MIN_FILL_MS) return "too-fast";
if (age > MAX_TOKEN_AGE_MS) return "expired-token";
if (usedTokens.has(nonce)) return "replayed-token";
usedTokens.add(nonce);
return null;
}
function limited(key, { max, windowMs }, now) {
const recent = (hits.get(key) || []).filter((t) => now - t < windowMs);
recent.push(now);
hits.set(key, recent);
return recent.length > max;
}
const EMAIL_RE = /^[^\s@<>()",;:]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/;
const CTRL = /[\r\n\u0000-\u001f\u007f\u2028\u2029]/;
const URLISH = /(https?:\/\/|www\.|\b[a-z0-9-]+\.(com|net|org|io|ru|xyz|top|link|app)\b)/i;
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c]));
export const formHtml = (token) => `<form method="post" action="/api/contact">
<input name="name" placeholder="Your name" required maxlength="80">
<input name="email" type="email" placeholder="you@company.com" required maxlength="254">
<textarea name="message" required maxlength="5000"></textarea>
<!-- honeypot: hidden from people, visible to bots that fill every field -->
<div aria-hidden="true" style="position:absolute;left:-9999px">
<label>Company website <input name="website" tabindex="-1" autocomplete="off"></label>
</div>
<input type="hidden" name="token" value="${token}">
<button>Send</button>
</form>`;
function validate(b) {
if (typeof b !== "object" || b === null) return "bad-body";
const { name, email, message } = b;
if (![name, email, message].every((v) => typeof v === "string")) return "bad-types";
if (name.trim().length < 1 || name.length > 80) return "name-length";
if (CTRL.test(name) || CTRL.test(email)) return "control-chars";
if (URLISH.test(name) || /[<>]/.test(name)) return "name-has-url-or-markup";
if (email.length > 254 || !EMAIL_RE.test(email)) return "bad-email";
if (message.trim().length < 2 || message.length > 5000) return "message-length";
return null;
}
export default async function handler(req, res) {
if (req.method !== "POST") return res.status(405).end();
const now = Date.now();
const ip = req.ip; // set by the platform, not by a client header you parse yourself
const b = req.body || {};
const reject = (status, reason) => res.status(status).json({ ok: false, reason });
// 1. bot checks first, and answer bots with a fake success so they don't adapt
if (b.website) return res.status(200).json({ ok: true, _dropped: "honeypot" });
const tokErr = checkToken(b.token, now);
if (tokErr === "too-fast") return res.status(200).json({ ok: true, _dropped: "too-fast" });
if (tokErr) return reject(400, tokErr);
// 2. shape and size
const bad = validate(b);
if (bad) return reject(400, bad);
// 3. rate limits
if (limited(`ip:${ip}`, PER_IP, now)) return reject(429, "ip-rate-limit");
if (limited(`email:${b.email.toLowerCase()}`, PER_EMAIL, now)) return reject(429, "email-rate-limit");
const today = new Date(now).toISOString().slice(0, 10);
if (today !== day) { day = today; sentToday = 0; }
if (sentToday >= DAILY_SEND_CAP) return reject(503, "daily-cap");
sentToday++;
// 4. one email, to us only. Fixed subject; user text escaped and only in the body.
await resend.emails.send({
from: "Ledgerly <hello@ledgerly.example>",
to: "team@ledgerly.example",
replyTo: b.email,
subject: "New contact form message",
text: `From: ${b.name} <${b.email}>\nIP: ${ip}\n\n${b.message}`,
html: `<p>From: ${esc(b.name)} <${esc(b.email)}></p><pre>${esc(b.message)}</pre>`,
});
// No auto-reply. The page shows "Thanks, we got it". Confirmation emails go out only
// after the address is verified (double opt-in) and never contain user-supplied text.
return res.status(200).json({ ok: true });
}
Run 2: same attacks, hardened handler
$ node harness/attack.mjs hardened
=== target: hardened ===
control req= 1 2xx= 1 emails= 1 to-outsiders= 0 unsafe=0 bytes=236
form-bot req= 50 2xx= 50 emails= 0 to-outsiders= 0 unsafe=0 bytes=0 [honeypot×50]
fast-bot req= 50 2xx= 50 emails= 0 to-outsiders= 0 unsafe=0 bytes=0 [too-fast×50]
replay req= 20 2xx= 1 emails= 1 to-outsiders= 0 unsafe=0 bytes=159 [replayed-token×19]
burst req=200 2xx= 5 emails= 5 to-outsiders= 0 unsafe=0 bytes=740 [ip-rate-limit×195]
autoreply-bomb req=100 2xx= 3 emails= 3 to-outsiders= 0 unsafe=0 bytes=474 [email-rate-limit×97]
distributed req=300 2xx= 50 emails= 50 to-outsiders= 0 unsafe=0 bytes=8370 [daily-cap×250]
crlf req= 1 2xx= 0 emails= 0 to-outsiders= 0 unsafe=0 bytes=0 [control-chars×1]
phish-name req= 1 2xx= 0 emails= 0 to-outsiders= 0 unsafe=0 bytes=0 [name-has-url-or-markup×1]
html-message req= 1 2xx= 1 emails= 1 to-outsiders= 0 unsafe=0 bytes=278
oversized req= 1 2xx= 0 emails= 0 to-outsiders= 0 unsafe=0 bytes=0 [message-length×1]
TOTAL (attacks only) requests=724 emails=60 to-outsiders=0 unsafe=0 bytes=10021
The attacks went from 1,448 emails to 60, and from 724 emails sent to attacker-chosen addresses to zero. The control message still went through.
The results are more interesting row by row than in total:
- The honeypot and the token age check each caught exactly the bot they were built for, and nothing else. form-bot filled the hidden field (honeypot ×50). fast-bot skipped it but posted too fast (too-fast ×50). Both "succeeded" from their own point of view, since they got a 200.
- Bot checks don't stop a careful attacker. Every attack that waited 3 seconds and left the honeypot empty got past them. Rate limits stopped those: 195 of 200 in the burst, 97 of 100 in the autoreply-bomb (by sender address, because the IPs were all different), and 19 of 20 replays (single-use tokens).
- The daily cap is the only thing that stopped the distributed run. 300 IPs and 300 sender addresses slip past both per-key limits, so 50 emails got through before the cap tripped. That's the cap working: it limits the damage, it doesn't filter. Those 50 still land in your team's inbox, and while the cap is tripped, a real customer's message gets a 503 too. Alert yourself when it trips.
- The HTML message got through, as text. That's on purpose. Real people paste links into contact forms. The email shows the markup escaped, so nothing in it is clickable.
What I didn't test, and what I'd add
-
In-memory state doesn't work on serverless. Every function instance has its own memory, so the
Mapof rate-limit hits and theSetof used tokens are reset whenever the platform starts a new instance. On a single long-running server that's fine. On Vercel-style functions, put the counters in Redis, a KV store, or a table in your database. The logic stays the same. - A captcha is the next layer, and I didn't test one. The harness runs offline, so Turnstile or hCaptcha weren't part of it. If the distributed row worries you (it should, for a popular site), add one and verify the token on the server before the rate limits. Don't verify it only in the browser.
- Caps on the provider side. My daily cap lives in code. Also look at what your email provider and every other API key behind the site let you limit: usage alerts, sending limits, separate keys per environment. The booking-app write-up was about keys that had none. How far the platform's own limits go is also worth checking before you build, since AI app builders differ a lot in what happens when credits run out.
-
Not covered here: cross-site request forgery from other origins, abuse of the
replyToheader, and leaked secrets in the front end. That last one is its own post.
The short version
If you're about to ship an AI-built site with a form, check five things:
- Does the form send email to an address the visitor typed? Remove that, or put it behind double opt-in with a fixed template.
- Does any user input reach a subject line or header? Use a fixed subject.
- Is user input escaped in the HTML email your team reads?
- Is there a per-IP limit, a per-sender limit, and a daily cap, all stored somewhere that survives a cold start?
- Do the keys behind the form have a usage cap or an alert set?
Then drop your own handler into a harness like this one, with the mailer stubbed, and run the attack script against it. Don't fire it at a deployment that sends real email. I'd put it on your launch-day checklist, next to the checks you run against production in the hour you go live. On my machine the naive run took under 2 seconds and the hardened one about 30, mostly the attacker waiting out the 3-second token age. It's much nicer to read these numbers in your own terminal than in your provider's billing dashboard.
What does your form backend do when it gets 300 posts in a minute? If you've seen a different abuse pattern on a real site, tell me and I'll add it to the script.



Top comments (1)
Ran your hardened contact.mjs and hit one snag. checkToken marks the nonce used before validate() runs, so a person who types anna@gmail, gets bad-email, fixes it and hits Send again gets replayed-token and no email. Moving usedTokens.add down to right before the send fixed it for me.