Sign-up protection with protectSignup()
How to protect a sign-up form with protectSignup() and the Hazeloft Security proof-of-work challenge, step by step, with working code examples.
Last updated:
protectSignup() gathers the account form checks into a single call. challenge() adds the only check where the client has to produce something: the solution to a computation.
protectSignup()
import { protectSignup, createConfigClient } from "@hazeloft/security";
const configClient = createConfigClient(); // reads HAZELOFT_SECURITY_API_KEY
export async function POST(request: Request) {
const body = await request.json();
const verdict = await protectSignup({
headers: request.headers,
body, // { email, name }
config: await configClient.get(), // the configuration from the console
client: cloudClient, // optional: enables rateLimitEmail and verifyDomain
});
if (verdict.conclusion === "deny") {
return new Response("Sign-up rejected.", { status: 403 });
}
// create the account
}
What it checks
In order, each with its own mode from the console:
| Check | What it rejects | Needs the decision service |
|---|---|---|
| Honeypot field | Forms in which the invisible field was filled in. | no |
detectBot |
Automated clients, by User-Agent. A missing header is not rejected here. | no |
validateEmail |
Addresses that are too long, invalid, disposable or, optionally, free. | no |
validateName |
Names that are too short, too long or made of random strings. | no |
rateLimitEmail |
Too many attempts on the same canonical address. | yes |
verifyDomain |
Email domains that do not exist in DNS. | yes |
The verdict
verdict.conclusion // "allow" or "deny"
verdict.canonicalEmail // the key for uniqueness and for limits
verdict.events // the events for the console charts
verdict.skipped // checks that could not run
The two checks that need the decision service let the request through when the service does not answer or when client is missing, but the failure stays visible: they appear in verdict.skipped. Log it, so you know when a protection did not run.
The honeypot field
You put a field in the form that is invisible to a person. The form sends the SIGNUP_HONEYPOT_HEADER header only if that field was filled in:
import { SIGNUP_HONEYPOT_HEADER } from "@hazeloft/security";
const headers: Record<string, string> = { "content-type": "application/json" };
if (honeypotValue) headers[SIGNUP_HONEYPOT_HEADER] = honeypotValue;
The limit on the canonical address
rateLimitEmail counts attempts on the canonical address: j.doe+1@gmail.com and jdoe@gmail.com hit the same counter. It catches accounts made in series on a single mailbox. A bot with genuinely distinct addresses walks past it; that one is taxed by the challenge and caught by verifyDomain, when its domains are invented.
Domain verification
verifyDomain asks DNS. A domain that does not exist is rejected. A domain that exists but has no MX record is rejected only with blockNoMx on.
The canonical form, on every path
canonicalizeAuthEmail(email) is exported separately. Apply it on every path that looks up a user by email (sign-in, password reset, verification), not just at sign-up. Otherwise, someone who types their Gmail address with dots can no longer sign in to the account created without them.
import { canonicalizeAuthEmail } from "@hazeloft/security";
record.email = canonicalizeAuthEmail(record.email);
Challenge
The other rules read headers, and a header is a claim: a script that sends a POST straight to the route sends the same bytes as a browser. With the challenge, the client has to solve a proof-of-work computation bound to a nonce issued and signed by your server.
Verification is local (one HMAC and one SHA-256), with no network round trip.
Three pieces of code, two requests
The rule covers verification only. Issuing the token is code you write, on the server, and solving is done by @hazeloft/security-client, in the browser. Without both, the rule rejects everything.
1. The issuing route (server). Keep the nonce; you need it in step 3.
import { issueChallenge } from "@hazeloft/security";
export async function GET() {
const { token, nonce, exp } = await issueChallenge({
secret: challengeSecret, // stays on the server ONLY
action: "sign-up", // defaults: difficulty 13, validity 120 seconds
});
await recordNonce(nonce, exp);
return Response.json({ token });
}
2. The browser. fetchAndSolveChallenge fetches the token, solves the computation in a Worker (falling back to the main thread) and returns the value for the header. Start it when the person begins filling in the form, not when they press the button.
import { CHALLENGE_HEADER, fetchAndSolveChallenge } from "@hazeloft/security-client";
const header = await fetchAndSolveChallenge({ endpoint: "/api/challenge" });
await fetch("/api/sign-up", {
method: "POST",
headers: { "content-type": "application/json", [CHALLENGE_HEADER]: header },
body: JSON.stringify(form),
});
3. The protected route (server). The same action and the same secret as at issuing.
import { HazeloftSecurity, challenge } from "@hazeloft/security";
const security = new HazeloftSecurity({
apiKey: process.env.HAZELOFT_SECURITY_API_KEY,
rules: [challenge({ secret: challengeSecret, action: "sign-up", isFresh: consumeNonce })],
});
isFresh(nonce) must return false if the nonce has been seen before and, in the same operation, mark it as seen. An isFresh that only reads lets a valid token be reused until it expires. If isFresh throws, the request is rejected.
What it proves
That the token was issued by you, for this route’s action, inside its validity window, that someone did the required computation and that the nonce had not been used. That is all.
What it does not prove
- It does not prove the request comes from a browser. An automated browser runs the client and passes. So does any script that implements the same steps: the format is public.
- It does not prove there is a person on the other side. There is no interaction, no gesture and no device check. Do not present it to your users as a check that they are people: it raises the price of automation, it does not detect it.
- The cost is not symmetric. In native code, the computation is much faster than in a browser. The real value is that the token has to be requested, and that request can be counted and limited: put a
rateLimiton the issuing route. - Signals are not protection. The client can send three informative values: the reported core count, the solve duration and whether a Worker was used. They are not signed and do not influence the verdict. The client does no device fingerprinting.
Mount it only on routes where your own client actually runs the SDK (sign-up, sign-in, password reset), never on an API called by other servers: any request without a valid header is rejected.
Dry run first
Straight on Live, the challenge rejects every client that is not yet sending the header: cached pages, mobile apps that have not been updated, an intermediary that strips unknown headers. Run in Dry run first and watch detail.code in decision.results:
detail.code |
What it means |
|---|---|
missing |
The header is absent: the client is not running the SDK, or an intermediary strips it. It has to reach zero before Live. |
malformed |
Header present but in another format: old client version, truncated token. |
bad_signature |
The signature does not verify: usually a different secret between issuing and verifying. |
expired |
Outside the validity window. |
action_mismatch |
Token issued for a different action than the route’s. |
insufficient_work |
The solution does not meet the difficulty in the token. |
replayed |
isFresh said the nonce had been seen, or your nonce store threw. |
The code is for you, not for the client: the default adapter answers with a plain 403.