Korzen
Bot Protection
In these docs

Supabase Auth

Bot Protection with Supabase Auth: sign-ups through your server, and a Before User Created hook that refuses the ones that skipped it.

With Supabase Auth, the browser can create an account by calling Supabase directly, so your server never sees the sign-up. Two parts close that: your server signs the visitor up, after asking Bot Protection, and a Before User Created hook refuses sign-ups that did not come through it. This guide uses Next.js with @supabase/ssr; any server works the same way.

The tag

As in the Next.js guide, in the root layout. The decide function is that guide's too.

The call

The server action that signs the visitor up. It asks Bot Protection, then hands Supabase a pass: the email and the time, signed with SIGNUP_PASS_SECRET, a random secret you make and give to both sides.

// app/signup/actions.js
"use server";
import { createHmac } from "node:crypto";
import { decide } from "@/lib/korzen"; // from the Next.js guide
import { createClient } from "@/utils/supabase/server";

export async function signUp(prevState, formData) {
  const email = String(formData.get("email")).toLowerCase();
  const d = await decide("/signup"); // the Next.js guide's: it sends protected_action
  if (d?.action === "block") return { error: "We could not create your account." };
  const supabase = await createClient();
  const { error } = await supabase.auth.signUp({
    email,
    password: String(formData.get("password")),
    options: { data: { korzen_pass: pass(email), korzen_request_id: d?.request_id ?? null } },
  });
  // ...
}

// pass tells the hook this sign-up came through your server: the email and the time,
// signed with a secret only your server and the hook know.
function pass(email) {
  const ts = Date.now();
  const mac = createHmac("sha256", process.env.SIGNUP_PASS_SECRET).update(`${email}.${ts}`).digest("hex");
  return `${ts}.${mac}`;
}

The hook, as an Edge Function. Supabase calls it before it creates any user, with the user's email and metadata, and waits up to 5 seconds. It refuses an email sign-up without a valid pass made in the last 5 minutes; it never calls Bot Protection, so Bot Protection being slow or down cannot stop it. It asks for no token either: the server action's call already did, and the tag's cookie never reaches Supabase's servers.

// supabase/functions/before-user-created/index.ts
import { Webhook } from "https://esm.sh/standardwebhooks@1.0.0";

const hookSecret = Deno.env.get("BEFORE_USER_CREATED_HOOK_SECRET")!.replace("v1,whsec_", "");
const passSecret = new TextEncoder().encode(Deno.env.get("SIGNUP_PASS_SECRET")!);

Deno.serve(async (req) => {
  const payload = await req.text();
  let user;
  try {
    ({ user } = new Webhook(hookSecret).verify(payload, Object.fromEntries(req.headers)));
  } catch {
    return new Response("{}", { status: 401 });
  }
  // Sign-ups with Google, GitHub and the like never pass through your form.
  if (user.app_metadata?.provider !== "email" || (await passOK(user.email, user.user_metadata?.korzen_pass))) {
    return Response.json({});
  }
  return Response.json({ error: { http_code: 403, message: "Please sign up on our site." } }, { status: 403 });
});

// passOK checks the server's signature, made in the last 5 minutes for this email.
async function passOK(email: string, pass: unknown): Promise<boolean> {
  const [ts, mac] = String(pass ?? "").split(".");
  if (!ts || !mac || Date.now() - Number(ts) > 5 * 60_000) return false;
  const key = await crypto.subtle.importKey("raw", passSecret, { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
  const sig = Uint8Array.from(mac.match(/../g) ?? [], (h) => parseInt(h, 16));
  return crypto.subtle.verify("HMAC", key, sig, new TextEncoder().encode(`${email.toLowerCase()}.${ts}`));
}

Deploy it with supabase functions deploy before-user-created --no-verify-jwt (Supabase calls hooks without a user's token), set SIGNUP_PASS_SECRET on it, and turn it on in the Supabase dashboard under Authentication, Hooks, as an HTTP hook pointing at the function. Keep the secret Supabase shows there as BEFORE_USER_CREATED_HOOK_SECRET.

The visitor's IP

The decision runs in your server action, so the IP is what the Next.js guide says: x-forwarded-for on Vercel, your edge's own header elsewhere.

Apply the action

Read only action. On block, answer with the same error the action shows when it fails for any other reason, so a bot learns nothing. The account starts in monitor mode, where action is always allow: nothing changes for visitors until you turn on block mode.

Keep the answer's request_id with what the action created, such as the account or the order: it names that decision when you ask us about it. The answer

Test it on your machine

Run supabase start and next dev. Turn on the hook locally in supabase/config.toml, and serve the function:

# supabase/config.toml
[auth.hook.before_user_created]
enabled = true
uri = "http://host.docker.internal:54321/functions/v1/before-user-created"
secrets = "env(BEFORE_USER_CREATED_HOOK_SECRET)"

# then: supabase functions serve before-user-created --no-verify-jwt

Then open http://localhost:3000. Pages on localhost always accept the tag and are never listed as a domain. Locally the IP is 127.0.0.1 or ::1, and that is fine. In Docker on your machine, the app sees the bridge's address instead, such as 172.17.0.1, and that is fine too.

  1. Set KORZEN_API_KEY in .env.local (and SIGNUP_PASS_SECRET in supabase/functions/.env) and open the sign-up page. In the browser's developer tools, the _kz cookie appears after a few seconds.
  2. Sign up. The decision shows on the dashboard's Decisions page, under the path you sent.
  3. Check fail open: set a wrong key and sign up again. The call answers 401, and the sign-up goes through.

Common mistakes

  • Only the server action, without the hook. A bot then signs up with your public anon key, straight to Supabase.
  • The hook refusing every sign-up without a pass. Sign-ups with Google or GitHub never go through your form: the code above lets them through.
  • A different secret on each side, or an email compared in different case. Every sign-up is then refused: the action lowercases the email, and the hook too.
  • Calling /v1/decide from the browser. The API key would reach every visitor; the call belongs on your server.
  • No timeout, or an error that stops the sign-up. Any answer other than 200, and no answer in time, means: let the visitor through.