Sub topic 7
Keeping bots off your list
This chapter assumes you can read basic HTML and a small amount of server-side Python. It also assumes you know that an email service provider (ESP) stores subscribers and sends campaigns. You will learn which bots attack sign-up forms, which defenses stop them, and which defenses cause new problems.
What bots do to a sign-up form
A public form that accepts an email address and triggers an email is an open endpoint. Automated clients abuse it in three main ways.
- Junk sign-ups. Scripts submit random or scraped addresses. These inflate your subscriber count, hurt your open rate, and can raise your ESP bill.
- Spam-trap and bounce damage. Some addresses on your list will bounce or belong to mailbox providers that use them to catch careless senders. Mailing them lowers your sender reputation.
- Subscription bombing. An attacker submits a victim's address to thousands of forms. The victim receives a flood of confirmation emails. Your domain becomes one of the senders, and you can be blamed.
The third case matters because double opt-in, covered in a later chapter, is the strongest filter against fake addresses. Without limits, it also lets an attacker make you send mail to a stranger.
Layer the defenses
No single check stops every bot. Combine cheap checks that cost real users nothing, and add stronger ones only if abuse continues.
<br>
The honeypot field
A honeypot is a field that real visitors never see or fill in, but simple bots fill in because they complete every input they find. The form from the HTML chapter already includes one:
<div style="position:absolute;left:-9999px" aria-hidden="true">
<label for="website">Leave this field empty</label>
<input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
</div>Each attribute has a job:
position:absolute;left:-9999pxhides the field visually. Usingdisplay:nonealso works, but some bots skip fields they can tell are not rendered, so off-screen placement catches more of them.aria-hidden="true"andtabindex="-1"keep screen reader users and keyboard users from landing in the field.autocomplete="off"reduces the chance that a browser or password manager fills the field for a real person.- The field name should look attractive to a bot, such as
websiteorurl. Avoid names likehoneypotortrap.
On the server, a non-empty honeypot means "bot". The important detail is what you do next. Return the same success message a real visitor sees, and do not add the address. A visible error tells the bot author what to change.
Honeypot gotchas
- Browser autofill can still fill a hidden field named
addressorphone. Pick a name that autofill does not recognize, and test in at least Chrome and Safari. - Honeypots stop generic form-filling scripts. They do not stop a targeted script written for your form, or a human who is paid to submit it.
- A visible label such as "Leave this field empty" matters. It is the only thing a user of an assistive technology could encounter if the hiding fails.
Timing checks
A person needs a few seconds to type an address. A script can post in milliseconds. If you record when the form was rendered, you can reject submissions that arrive too fast.
Do not store the render time in a plain hidden field, because a bot can simply set it to an old value. Sign it on the server so that it cannot be forged. The example below puts the honeypot, signed timing, rate limit, and email check together.
import re
import time
from collections import defaultdict, deque
from flask import Flask, request
from itsdangerous import BadSignature, URLSafeSerializer
app = Flask(__name__)
signer = URLSafeSerializer("replace-with-a-long-random-secret")
MIN_SECONDS = 3
MAX_SECONDS = 24 * 60 * 60
LIMIT = 5 # submissions allowed per IP
WINDOW = 60 * 60 # per hour
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
hits = defaultdict(deque)
OK = "Thanks. Check your inbox to confirm your subscription."
@app.get("/form")
def form():
token = signer.dumps(int(time.time()))
return f"""
<form action="/subscribe" method="post">
<label for="email">Email address</label>
<input type="email" id="email" name="email" autocomplete="email" required>
<div style="position:absolute;left:-9999px" aria-hidden="true">
<label for="website">Leave this field empty</label>
<input type="text" id="website" name="website" tabindex="-1" autocomplete="off">
</div>
<input type="hidden" name="token" value="{token}">
<button type="submit">Subscribe</button>
</form>"""
def too_many(ip):
now = time.time()
q = hits[ip]
while q and now - q[0] > WINDOW:
q.popleft()
if len(q) >= LIMIT:
return True
q.append(now)
return False
@app.post("/subscribe")
def subscribe():
if request.form.get("website"):
return OK # honeypot filled: pretend success
try:
rendered = signer.loads(request.form.get("token", ""))
except BadSignature:
return OK # forged or missing token
age = time.time() - rendered
if age < MIN_SECONDS or age > MAX_SECONDS:
return OK # too fast, or stale form
if too_many(request.remote_addr):
return "Too many attempts. Try again later.", 429
email = request.form.get("email", "").strip()
if not EMAIL_RE.match(email):
return "Please enter a valid email address.", 400
# Here you would call your ESP to send the confirmation email.
return OKTo run it, install Flask (pip install flask), save the file as app.py, and start it with flask run.
Points to notice:
- Silent discards return the same text as real success. Only the rate limit and syntax errors are visible, since a real person can trigger both.
- A stale-token rule (
MAX_SECONDS) matters for cached pages. If your page is cached for days, the token will expire and real users will be dropped. Either keep the maximum long, or fetch the token with a small request when the form loads. - The in-memory rate limiter resets when the process restarts and does not share state across servers. Production setups usually use Redis or the rate-limiting feature of a CDN or ESP.
- Behind a proxy,
request.remote_addris the proxy's address. Read the client address from a trusted forwarding header, or every visitor will share one limit.
Rate limiting and subscription bombing
Limit by IP address, and also by target email address. The per-IP limit slows a single machine. The per-address limit protects victims when an attacker spreads requests over many IPs. A reasonable rule is to send at most one confirmation email per address per hour, and to ignore repeat requests during that time without telling the requester.
Keep the response identical whether or not the address is already subscribed. Different messages let an attacker test which addresses are on your list.
CAPTCHAs and challenge services
A CAPTCHA asks the client to prove it is human. Common services include Google reCAPTCHA, hCaptcha, and Cloudflare Turnstile. Most now run in the background and only show a puzzle when a visitor looks suspicious.
Add a CAPTCHA only when the cheaper layers fail, and weigh these costs first:
| Concern | What to check |
|---|---|
| Conversion | Any challenge can lose real subscribers. Measure the sign-up rate before and after. |
| Accessibility | Image and audio puzzles are hard for many users. Prefer invisible or low-friction challenges. |
| Privacy | The provider loads a third-party script and may set cookies. This can require disclosure or consent under privacy rules. |
| Server check | The token the browser receives must be verified on your server against the provider's API. A client-side widget alone proves nothing. |
Common mistakes
- Validating only in the browser. The
requiredandtype="email"attributes help users, but a bot posts directly to your endpoint. Repeat every check on the server. - Revealing why a submission failed. Detailed errors for honeypot or timing failures teach the attacker how to adapt.
- Blocking the form for assistive technology. A honeypot that can receive focus, or a CAPTCHA without an alternative, locks out real people.
- Skipping double opt-in to avoid friction. Without confirmation, every fake address reaches your list. With it, you still need the limits above so the confirmation email is not weaponized.
- Trusting a count of "new subscribers" as success. A sudden spike with a low confirmation rate or high bounce rate usually means bots, not growth.
Exercise
A bot fills in the hidden "website" field. Your server returns "Please remove the value from the website field." Name two problems with this response and describe a better one.
Show answer
The message tells the bot author which field is the trap, so they can update the script to leave it empty, and it confirms the honeypot exists. A better response discards the submission silently and returns the same success message a real subscriber sees, without adding the address to the list.
Exercise
Your sign-up page is cached by a CDN for a week, and you add the signed timestamp check with a 24-hour maximum age. Real visitors start being dropped. Why does this happen, and what are two ways to fix it?
Show answer
The signed token was generated when the page was cached, so after 24 hours every visitor receives an expired token. One fix is to raise the maximum age above the cache lifetime. The other is to fetch a fresh token from the server with a small request when the form loads, so the page itself can stay cached.