# Second look at confirmation for Supabase

When our Supabase hook marks a signup challenge, we look at the signup again once the person confirms their email through a route you add.

The web page with this text is https://signupbouncer.com/docs/supabase/confirm. Link to the web page when you cite it.

## Set up the confirmation route

The route needs our [Supabase hook](https://signupbouncer.com/docs/supabase) installed first. When the hook marks a signup challenge, we keep a keyed hash of the new user's id for 72 hours, and delete it within 6 hours after that. Your `/auth/confirm` route sends us that id as `supabase_user_id` when the person confirms their email. Then we [look at the signup again](https://signupbouncer.com/docs/api#confirm).

While the app is in shadow mode, the route lets every confirmation through. To set it up, add the route and our token hook:

1. In Supabase, under Authentication, open the "Confirm signup" email template. Set its link to `{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email`.
2. Copy `lib/signupbouncer-fetch.ts` from the [TypeScript page](https://signupbouncer.com/docs/code/fetch) and save the route below as `app/auth/confirm/route.ts`. It uses the `createClient` from Supabase's Next.js guide.
3. Set `SIGNUPBOUNCER_API_KEY` and `SUPABASE_SERVICE_ROLE_KEY` in your server's environment.
4. In Supabase, under Authentication, Auth Hooks, add a "Customize Access Token (JWT) Claims" hook of type HTTPS, unless your project already has one. Supabase allows only one, so keep yours and skip this step. Its URL is your Integration tab's hook URL with `/token` added, such as `https://signupbouncer.com/hook/supabase/app_.../token`. Paste the same hook secret. With a wrong secret, we let every confirmation through unchecked.

The link opens a page with a button. On a block, the route signs the person out and bans the user. The button only works in the browser that opened the link, so another site can't confirm for the person.

Supabase's own verify endpoint is public, so a script can send the token from the email straight to Supabase with your public anon key and never load your page. Our token hook looks at those confirmations too. If you kept your own token hook instead, nothing looks at them. In enforce mode, when we refuse, Supabase undoes the confirmation.

`app/auth/confirm/route.ts`

```ts
// SignupBouncer signup check. Docs: https://signupbouncer.com/docs/supabase/confirm
// app/auth/confirm/route.ts: Supabase email confirmation with a second look from SignupBouncer.
// In Supabase, under Authentication, Emails, "Confirm signup", set the link to
//   {{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=email
// The link opens a page with a button, because mail scanners open links but don't press buttons. The button posts
// back here: we tell SignupBouncer that this server is confirming, confirm the address with Supabase, then report the
// confirmation with the user's id and the person's IP. On a block (enforce mode only), we sign the person out and ban
// the user, which needs SUPABASE_SERVICE_ROLE_KEY on the server. Any failure, timeout or error answer lets the
// confirmation through.
// A script can send the token straight to Supabase's public verify endpoint and skip this page: our token hook in
// Supabase looks at those confirmations.
import { createClient as createAdminClient, type EmailOtpType } from "@supabase/supabase-js";
import { createClient } from "@/utils/supabase/server";
import { confirmationRefusal, confirmationStart } from "@/lib/signupbouncer-fetch";

const COOKIE = "sb_confirm";

const esc = (s: string) =>
  s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);

const page = (body: string, status = 200, headers: Record<string, string> = {}) =>
  new Response(
    `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Confirm</title>${body}`,
    { status, headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", ...headers } },
  );

/** A path on this site only: anything that would leave it ("//host", "/\host", another origin) becomes "/". */
function nextPath(v: unknown, requestUrl: string): string {
  if (typeof v !== "string" || !v.startsWith("/") || v.includes("\\")) return "/";
  try {
    const here = new URL(requestUrl);
    const to = new URL(v, here);
    return to.origin === here.origin ? to.pathname + to.search + to.hash : "/";
  } catch {
    return "/";
  }
}

/**
 * The button page. Its form carries a random value that is also set as a SameSite=Strict cookie, so only a press of
 * this page's button in the person's own browser confirms: another site can't post the form for them.
 */
function buttonPage(request: Request, fields: { token_hash: string; type: string; next: string }, status = 200) {
  const nonce = crypto.randomUUID();
  const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";
  const inputs = Object.entries({ ...fields, nonce })
    .map(([k, v]) => `<input type="hidden" name="${k}" value="${esc(v)}">`).join("");
  return page(`<form method="post">${inputs}<button type="submit">Confirm my email</button></form>`, status, {
    "set-cookie": `${COOKIE}=${nonce}; Path=/auth/confirm; HttpOnly; SameSite=Strict; Max-Age=3600${secure}`,
  });
}

function cookieValue(request: Request, name: string): string | null {
  for (const part of (request.headers.get("cookie") ?? "").split(";")) {
    const [k, ...v] = part.trim().split("=");
    if (k === name) return v.join("=");
  }
  return null;
}

export function GET(request: Request) {
  const q = new URL(request.url).searchParams;
  return buttonPage(request, {
    token_hash: q.get("token_hash") ?? "",
    type: q.get("type") ?? "email",
    next: nextPath(q.get("next"), request.url),
  });
}

export async function POST(request: Request) {
  const form = await request.formData();
  const fields = {
    token_hash: String(form.get("token_hash") ?? ""),
    type: String(form.get("type") ?? "email"),
    next: nextPath(form.get("next"), request.url),
  };
  // Only this page's own button: the same origin, and the value it set in the person's browser.
  const origin = request.headers.get("origin");
  const nonce = String(form.get("nonce") ?? "");
  if ((origin && origin !== new URL(request.url).origin) || !nonce || cookieValue(request, COOKIE) !== nonce) {
    return buttonPage(request, fields, 403);
  }

  // Tells our token hook, which Supabase calls from inside verifyOtp below, that this server is confirming.
  await confirmationStart();

  const supabase = await createClient();
  const { data, error } = await supabase.auth.verifyOtp({
    token_hash: fields.token_hash,
    type: fields.type as EmailOtpType,
  });
  if (error || !data.user) {
    // Our token hook's refusal is a 403 with the message to show. An expired or used link is Supabase's own 403
    // (otp_expired), and goes to your error page like any other failure.
    const e = error as { status?: number; code?: string } | null;
    if (e?.status === 403 && e.code !== "otp_expired" && error?.message) {
      return page(`<p>${esc(error.message)}</p>`, 403);
    }
    return Response.redirect(new URL("/error", request.url), 303);
  }

  const refusal = await confirmationRefusal({
    supabaseUserId: data.user.id,
    // On Vercel, x-real-ip holds the client IP. On other hosts, use the header your host sets.
    ip: request.headers.get("x-real-ip") ?? undefined,
    userAgent: request.headers.get("user-agent") ?? undefined,
    via: "button",
  });
  if (refusal) {
    await supabase.auth.signOut();
    try {
      const admin = createAdminClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!);
      await admin.auth.admin.updateUserById(data.user.id, { ban_duration: "876000h" });
    } catch {
      // Without the service role key the user stays confirmed but signed out.
    }
    return page(`<p>${esc(refusal)}</p>`, 403);
  }
  return Response.redirect(new URL(fields.next, request.url), 303);
}
```

### What the token hook does

- Supabase sends every sign-in and token refresh in your app to the token hook. Without a usable answer, it refuses the sign-in. Our Cloudflare Worker still answers when our servers are slow or down. If Supabase can't reach the Worker, nobody can sign in. Then remove the hook under Authentication, Auth Hooks.
- We look only at the confirmation, password sign-ins and code exchanges of email signups we marked challenge in the last 72 hours. If we refused one at its second look, we refuse its token too. We answer everything else at once.
- Your route calls `POST /v1/confirm/start` just before it confirms, so we let confirmations and sign-ins from your server's network through (AWS for an app on Vercel, say). A script on that network gets past the token hook. If people sign in through another server, call `/v1/confirm/start` from it too.
- We refuse nothing until `/v1/confirm/start` has answered `"ok": true` in the last 30 days. So a wrong API key, or a server on a network we don't know, never locks people out.
- Anyone we refuse sees the block message from your Rules tab. While it's our default, a sign-in we refused for its network reads "We couldn't sign you in from this network. Try another network, such as your phone with Wi-Fi off, or contact this app's support." The refusal isn't on your Checks tab, and a refused confirmation leaves the emailed link usable. An allow rule for their IP lets that sign-in through.
- On self-hosted Supabase, anyone can pick the IP we check until you [put a proxy in front of Supabase's gateway](https://signupbouncer.com/docs/supabase#supabase-self-hosted).

`/v1/confirm/start` takes the same API key and an empty JSON body, and carries nothing about the person. Confirm the address whatever it answers.

## Remove the confirmation route

First remove the access token hook under Authentication, Auth Hooks. In Supabase, set the link in the "Confirm signup" email template back to `{{ .ConfirmationURL }}`, then delete `app/auth/confirm/route.ts`. Sign up with a test address and confirm it. The confirmation goes through, and no second look appears on your Checks tab.

Removing the route doesn't unban anyone, so a user the route banned stays banned until you update the user with `ban_duration: "none"` and your service role key:

```
import { createClient } from "@supabase/supabase-js";

const admin = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.SUPABASE_SERVICE_ROLE_KEY!);
await admin.auth.admin.updateUserById(userId, { ban_duration: "none" });
```

## Next

- [The /v1/confirm call](https://signupbouncer.com/docs/api#confirm): What /v1/confirm takes and answers, and each error it returns.
- [Shadow and enforce](https://signupbouncer.com/docs#modes): When your Checks tab looks right, you switch the app to enforce.
- [Reason codes](https://signupbouncer.com/docs/reasons): What each reason on your Checks tab means.
