agentleFS
FavoritchannelFavoritchannel/claude-code-skills/skills/lead-form-hardening/SKILL.md

lead-form-hardening

Skill0 starsChanged 5 months agoMITView on GitHub

Production-grade hardening for agency client lead forms (quote requests, booking forms, contact forms). Layered server-side anti-spam (honeypot + min-fill-time + payload validation + Turnstile feature-flag), URL prefill pattern, and the conditional-field pattern for tiered offerings. Use when wiring or auditing any public form that posts to an internal API. Triggers on phrases like "booking form", "quote form", "contact form", "/api/booking", "spam protection", "anti-spam", "honeypot", "Turnstile", "Cloudflare Turnstile", "form validation", "lead capture".

  • Reads credentials
  • Sends data out

The file

We split this skill into the rules it gives an agent

9 rules. About 0 are common, 7 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈7

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Silent succeed for detected bots: When a guard trips (honeypot filled, submission too fast, validation fails), return HTTP 200 OK and …

    line 25
  2. Distinctive:

    Don't fail closed without the captcha: If Turnstile env vars are unset, skip Turnstile verification (not "reject all").

    line 27
  3. Very specific:

    Use a name that sounds tempting to bots (company, website, url) but isn't in the visible form.

    line 45
  4. Distinctive:

    Use Cloudflare Turnstile in production unless you have a specific reason for hCaptcha or reCAPTCHA.

    line 143
  5. Distinctive:

    If the form receives >100 submissions/day or the client is a known target, add Upstash Redis-based rate-limiting on the API route.

    line 147
  6. Distinctive:

    When a CTA button on a service page links to the booking form, prefill the form via query string.

    line 153
  7. Very specific:

    If the form has a service dropdown and each service has different size/scope options, render the second field conditionally:

    line 162
  8. Distinctive:

    Before declaring a hardened form done, run these curl tests against the dev server:

    line 191
  9. Distinctive:

    Add to hosting env vars (Vercel / Netlify / Cloudflare Pages):

    line 225

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Lead form hardening

When to use

Trigger when:

  • Wiring a new client lead form (booking, quote, contact, demo request)
  • Auditing an existing form before public launch
  • Investigating spam after a form has been live
  • Adding Cloudflare Turnstile to an existing form
  • Building any <form> that posts to an internal API endpoint and triggers a notification (Telegram bot, email, Slack)

Core philosophy

  1. Layer defenses; never rely on one. A single defense (Turnstile alone, captcha alone) has a single failure mode. Layered defenses (honeypot + timing + payload validation + external challenge) each catch a different bot tier and degrade gracefully.
  2. Defenses must be server-side authoritative. Client guards are advisory only — a bot bypasses the client entirely with curl -X POST. Every guard MUST also be enforced on the server.
  3. Feature-flag the external slow path. Turnstile / hCaptcha / reCAPTCHA require external account setup. Feature-flag them so the form works on day one with cheap built-in guards, then upgrade when the client provisions the external service.
  4. Silent succeed for detected bots. When a guard trips (honeypot filled, submission too fast, validation fails), return HTTP 200 OK and pretend success. Bots learn what trips your guards if you return 400 with diagnostic errors. Logs separately record the rejection.
  5. Don't fail closed without the captcha. If Turnstile env vars are unset, skip Turnstile verification (not "reject all"). Form must be usable during the rollout window.

The 5-layer pattern (in order of defense depth)

Layer 1 — Honeypot field

A hidden form field that humans don't see (off-screen via absolute positioning, NOT display: none which screen readers may also skip oddly). Naive bots fill every visible-on-DOM field.

<div
  aria-hidden
  style={{ position: "absolute", left: "-10000px", width: "1px", height: "1px", overflow: "hidden" }}
>
  <label htmlFor="company">Company (leave blank)</label>
  <input id="company" name="company" type="text" tabIndex={-1} autoComplete="off" />
</div>

Use a name that sounds tempting to bots (company, website, url) but isn't in the visible form. Client-side: if filled at submit, silent-succeed without sending. Server-side: reject 200-OK (silent) on any non-empty value.

Catch rate: 40–60% of low-effort bots.

Layer 2 — Min-fill-time guard

Record mount timestamp; reject submissions under 1500ms. Humans rarely fill even a short form that fast; bots routinely submit in <300ms.

const mountedAt = useRef<number>(Date.now());

async function onSubmit(e) {
  e.preventDefault();
  if (Date.now() - mountedAt.current < 1500) {
    setStatus("success"); // silent
    return;
  }
  // ... real submit
}

1500ms is a generous threshold; fast typers won't hit it. Catches 70–80% of remaining naive bots.

Layer 3 — Payload validation (server-side authoritative)

This is the highest-leverage layer. Every field gets:

  • Type check (string, not array or object)
  • Length cap (name ≤ 80, phone ≤ 30, email ≤ 254, notes ≤ 2000)
  • Enum reject for known-domain fields (service, tier, country) — bot submissions usually fail enum checks
  • Normalization (trim, lowercase email, strip non-digit-friendly chars from phone)
// src/lib/booking-validation.ts
export const FIELD_LIMITS = { name: 80, phone: 30, email: 254, notes: 2000 } as const;

export function isValidServiceKey(v: unknown): v is ServiceKey {
  return typeof v === "string" && SERVICE_KEYS.has(v as ServiceKey);
}

export function isValidTierForService(svc: ServiceItem, v: unknown): boolean {
  if (typeof v !== "string") return false;
  if (svc.pricingMode === "quote") return true; // free text allowed
  return v === "" || svc.tiers.some((t) => t.key === v);
}

export function normalizePhone(v: unknown): string {
  if (typeof v !== "string") return "";
  return v.replace(/[^\d+()\s.-]/g, "").trim().slice(0, FIELD_LIMITS.phone);
}

On the route:

if (!isValidServiceKey(raw.service)) {
  return NextResponse.json({ ok: false, error: "unknown-service" }, { status: 400 });
}

For known-enum fields, 400 with unknown-X is fine — bots get nothing useful, but if a future legit submission fails here it tells you the form is sending garbage. Honeypot stays silent because that's specifically a bot signal; enum mismatch is more often a code bug.

Catches 90%+ of remaining bots that get past Layers 1 + 2.

Layer 4 — Cloudflare Turnstile (or equivalent), feature-flagged

// BookingForm.tsx
const TURNSTILE_SITE_KEY = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;

{TURNSTILE_SITE_KEY && (
  <Turnstile
    siteKey={TURNSTILE_SITE_KEY}
    onSuccess={setTurnstileToken}
    options={{ theme: "light", size: "flexible" }}
  />
)}
// /api/booking route.ts
const TURNSTILE_SECRET = process.env.TURNSTILE_SECRET_KEY;

async function verifyTurnstile(token: string | undefined, ip: string | null) {
  if (!TURNSTILE_SECRET) return { ok: true, skipped: "no-secret" as const };
  if (!token) return { ok: false, error: "missing-token" as const };
  const body = new URLSearchParams({ secret: TURNSTILE_SECRET, response: token });
  if (ip) body.set("remoteip", ip);
  const r = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body,
  });
  const json = await r.json();
  return { ok: !!json.success };
}

Without env vars, the form falls back to Layers 1–3 (still 95%+ effective for typical scrape-style bot traffic). With env vars, sophisticated headless-Chromium bots also get caught.

Use Cloudflare Turnstile in production unless you have a specific reason for hCaptcha or reCAPTCHA. Turnstile is free, privacy-friendly, doesn't degrade UX with image puzzles.

Layer 5 — IP rate-limit (optional, for high-traffic sites)

If the form receives >100 submissions/day or the client is a known target, add Upstash Redis-based rate-limiting on the API route. Skip for typical small-business forms — Layers 1–4 cover them.

Form UX patterns that pair with hardening

URL prefill (query before hash)

When a CTA button on a service page links to the booking form, prefill the form via query string. Important: Query goes BEFORE the hash, not after.

✅ Correct: /?service=standard&tier=1bd1ba#cta ❌ Wrong: /#cta?service=standard&tier=1bd1ba (browser ignores query after hash)

Form reads via useSearchParams(). Don't forget the Suspense boundary at the form's mount site (see tnova-seo-geo/references/nextjs-app-router-gotchas.md §2 for the Next.js App Router specifics).

Conditional fields by selected service

If the form has a service dropdown and each service has different size/scope options, render the second field conditionally:

{selected && selected.pricingMode === "tiered" ? (
  <select id="size" name="size" required>
    {selected.tiers.map((tier) => (
      <option key={tier.key} value={tier.key}>
        {tierLabel(selected.key, tier.key)}
      </option>
    ))}
  </select>
) : (
  <input id="size" name="size" type="text" placeholder="Describe the project" />
)}

This pairs with Layer 3 validation: the server knows which tier keys are valid for which service, so unknown tier → 400.

Anti-patterns (never do)

  • ❌ Email-link confirmation as the only verification. Confirmation emails just delay the bot's submission by an hour; they don't reject.
  • ❌ CAPTCHA on every page load (image puzzles for normal users). UX-hostile and not necessary if Layers 1–3 are working. Turnstile is invisible to humans.
  • ❌ Returning structured 400 errors with the failing field. Reveals the validation logic to bots. Use opaque error: "captcha-failed" codes if you return 400 at all.
  • ❌ Skipping server-side validation because the client validates. Curl-able. Always validate server-side.
  • ❌ Hardcoding the Turnstile site key in source. Use NEXT_PUBLIC_TURNSTILE_SITE_KEY; secret key (server-side only) goes in TURNSTILE_SECRET_KEY.
  • ❌ Logging full payload to public logs. Sanitize first — phone numbers and emails are PII.

Smoke tests for verification

Before declaring a hardened form done, run these curl tests against the dev server:

# Valid payload — should 200 OK
curl -X POST http://localhost:3000/api/booking \
  -H "Content-Type: application/json" \
  -d '{"name":"Test","phone":"5870000000","service":"standard","size":"1bd1ba"}'
# Expected: {"ok":true}

# Unknown service — should 400
curl -X POST http://localhost:3000/api/booking \
  -H "Content-Type: application/json" \
  -d '{"name":"Test","phone":"5870000000","service":"NOT_REAL","size":""}'
# Expected: {"ok":false,"error":"unknown-service"}

# Honeypot filled — should 200 OK (silent), but NOT actually deliver
curl -X POST http://localhost:3000/api/booking \
  -H "Content-Type: application/json" \
  -d '{"name":"Bot","phone":"5870000000","service":"standard","size":"","company":"spam"}'
# Expected: {"ok":true}, check Telegram — no message arrived

# Build with dummy Turnstile keys — should not crash
NEXT_PUBLIC_TURNSTILE_SITE_KEY="0x000" pnpm build
# Expected: clean build, dummy widget renders

# Build with no env vars — should also not crash
pnpm build
# Expected: clean build, no Turnstile widget renders

Manual user steps for Turnstile rollout (after code ships)

  1. https://dash.cloudflare.com → Turnstile → Add site → domain → widget type Invisible or Managed (Invisible preferred for booking forms)
  2. Copy Site Key + Secret Key
  3. Add to hosting env vars (Vercel / Netlify / Cloudflare Pages):
    • NEXT_PUBLIC_TURNSTILE_SITE_KEY = site key (client-side)
    • TURNSTILE_SECRET_KEY = secret key (server-side only)
  4. Redeploy
  5. Submit a test booking from the live site to confirm widget loads + form submits successfully

Files to reference

Per-project, the canonical implementation lives in:

  • src/components/BookingForm.tsx — client-side guards + Turnstile widget + URL prefill
  • src/app/api/booking/route.ts — server-side payload validation + Turnstile verify
  • src/lib/booking-validation.ts — pure validation helpers (no I/O)

The Ukrainian Elite Cleaning project (cleaning vertical) is the working reference implementation. Mirror the patterns there for new clients.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.