Korzen
Bot Protection
Nesta documentação

Lovable

Bot Protection num app do Lovable: a tag na página, cadastros e testes checados numa server function ou Supabase Edge Function, e um prompt que adiciona tudo.

Um app do Lovable pergunta ao Bot Protection no próprio servidor antes de criar uma conta ou começar um teste grátis, e carrega a tag nas suas páginas. O Lovable escreve as duas coisas a partir de um prompt. Esta página traz o prompt para cada tipo de projeto do Lovable e depois o que o Lovable escreve a partir dele, para você conseguir ler o diff.

Qual projeto você tem

O Lovable cria os projetos novos em TanStack Start: as páginas são renderizadas no Cloudflare Workers, e o código de servidor são server functions do TanStack Start. Um projeto com src/routes/__root.tsx é um deles: siga TanStack Start. Um projeto com um index.html e sem servidor próprio roda o código de servidor como Supabase Edge Functions: siga Edge Functions do Supabase.

TanStack Start

A server function roda no mesmo Worker que as páginas, no domínio do seu próprio app, então o cookie da tag vai junto com cada chamada: o token não precisa de cabeçalho.

O prompt

Cole no chat do seu projeto. Se você estiver logado, esta página já traz a sua site key. Depois o Lovable pede KORZEN_API_KEY num formulário de secrets: cole ali a sua chave de API secreta, nunca no chat.

Prompt
Add Korzen Bot Protection to this app, in monitor mode, failing open.

1. In the root route (src/routes/__root.tsx), inside the shell's <head>, add exactly:
   <script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>

2. Add the npm package @korzen/bot-protection@3. Create a TanStack Start server function
   checkSignup (createServerFn, method POST) whose handler, on the server alone:
   - reads the secret KORZEN_API_KEY from process.env and makes the client once with
     createClient({ apiKey }).
   - gets the request with getRequest() from @tanstack/react-start/server and builds the
     input with fromRequest(request, { ip: ipFrom.cloudflare, path: "/signup", protectedAction: true }).
   - calls client.decide(input). decide returns null on any error or timeout: then go on.
   - returns { allowed: false } when the action is "block", and otherwise
     { allowed: true, requestId: the decision's request_id, or null }.

3. In the sign-up form, before supabase.auth.signUp: run `await window.korzen?.ready()` (the
   tag's token then rides with the call in its _kz cookie), then call checkSignup. When it
   is not allowed, show "We could not create your account." and do not sign up. Otherwise
   sign up as before, with korzen_request_id (the requestId) in options.data. If the call
   to checkSignup itself fails, sign up as before. Never call /v1/decide from the browser.

4. If the app has a free trial, start it in a server function instead of from the
   browser: with the signed-in user (requireSupabaseAuth), it runs the same check with
   path "/trial" first and starts nothing on "block". Then users can no
   longer start a trial from the browser by themselves.

Do not add a CAPTCHA, change the sign-in, or log the API key. Ask me for KORZEN_API_KEY as
a secret. Show me the diff.

O Lovable não instala nenhuma versão do npm com menos de 24 horas: logo depois de um lançamento, espere um dia ou fixe a versão anterior.

A tag

Em src/routes/__root.tsx, no <head> do shell, para toda página ser renderizada com ela. O seu endereço do Lovable e o seu domínio próprio são aprendidos como domínios do seu site nas primeiras visitas.

<head>
  <HeadContent />
  <script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>
</head>

A server function

O TanStack Start roda a função só no servidor; a página recebe um stub que a chama. Ela lê a chave de API dos secrets do projeto, pergunta ao Bot Protection e responde se o cadastro pode seguir. Qualquer erro, um timeout acima de 200 ms ou uma chave errada não dá decisão, e o cadastro segue.

// src/lib/korzen.server.ts
import { createClient, fromRequest, ipFrom, type Client } from "@korzen/bot-protection";
import { getRequest } from "@tanstack/react-start/server";

let cached: { apiKey: string; client: Client } | undefined;

export async function checkBot(path: "/signup" | "/trial") {
  const apiKey = process.env.KORZEN_API_KEY ?? "";
  // A changed secret reaches the next request without a new build: a new client for it.
  if (cached?.apiKey !== apiKey) cached = { apiKey, client: createClient({ apiKey }) };
  // CF-Connecting-IP is the visitor's; the token comes in the _kz cookie.
  // protectedAction: a script that never loaded your page holds no token.
  const d = await cached.client.decide(fromRequest(getRequest(), { ip: ipFrom.cloudflare, path, protectedAction: true }));
  if (d?.action === "block") return { allowed: false as const };
  return { allowed: true as const, requestId: d?.request_id ?? null };
}

// src/lib/signup.functions.ts
import { createServerFn } from "@tanstack/react-start";
import { checkBot } from "./korzen.server";

export const checkSignup = createServerFn({ method: "POST" }).handler(() => checkBot("/signup"));

O formulário

O formulário pergunta primeiro à server function e depois faz o cadastro no Supabase como antes, guardando o request_id da decisão com a conta. Se a própria chamada falhar, faz o cadastro como antes.

const checkSignupFn = useServerFn(checkSignup);
// in the sign-up's submit:
let data: { korzen_request_id: string | null } | undefined;
try {
  await window.korzen?.ready();
  const verdict = await checkSignupFn();
  if (!verdict.allowed) return toast.error("We could not create your account.");
  data = { korzen_request_id: verdict.requestId };
} catch {
  // no answer from the check: sign up as before
}
const { error } = await supabase.auth.signUp({ email, password, options: { data } });

O teste grátis

O teste grátis começa numa server function com o usuário logado, depois da mesma checagem com o path /trial. O Lovable também tira do navegador o direito de começar um por conta própria, então a checagem não pode ser pulada.

// src/lib/trial.functions.ts
export const startTrial = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const verdict = await checkBot("/trial");
    if (!verdict.allowed) return { started: false };
    const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
    await supabaseAdmin.from("trials").insert({ user_id: context.userId });
    // keep verdict.requestId with the trial
    return { started: true };
  });

// the migration Lovable adds: only the server function starts a trial
// REVOKE INSERT ON public.trials FROM authenticated;

O IP do visitante

O Lovable serve os apps TanStack Start a partir do Cloudflare Workers, onde CF-Connecting-IP é o endereço do visitante: o Cloudflare escreve esse cabeçalho e recusa uma requisição que mande o seu próprio. ipFrom.cloudflare lê esse. Nunca leia X-Forwarded-For ali: o Lovable repassa o que o visitante mandar nele.

Edge Functions do Supabase

Aqui o app é uma página no navegador com um projeto Supabase por trás, sem servidor próprio. A checagem roda numa Edge Function do Supabase que cria a conta, no domínio do Supabase, então o token vai num cabeçalho.

O prompt

Cole no chat do seu projeto. Se você estiver logado, esta página já traz a sua site key. Depois adicione a sua chave de API secreta aos secrets de Edge Function do projeto como KORZEN_API_KEY quando o Lovable pedir, nunca no chat.

Prompt
Add Korzen Bot Protection to this app, in monitor mode, failing open.

1. In index.html, inside <head>, add exactly:
   <script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>

2. Create a Supabase Edge Function "signup" (verify_jwt = false) that the sign-up form
   calls instead of supabase.auth.signUp. It imports
   npm:@korzen/bot-protection@3 and npm:@supabase/supabase-js@2, reads the secret
   KORZEN_API_KEY, and for each POST {email, password}:
   - builds the input with
     fromRequest(req, { ip: ipFrom.vercel, path: "/signup", protectedAction: true }) and
     calls client.decide(input). decide returns null on any error or timeout: then go on.
   - if the action is "block", answers 403 with
     {"error": "We could not create your account."} and creates nothing.
   - otherwise calls supabase.auth.signUp with the anon key, passing
     korzen_request_id (the decision's request_id) in options.data, and answers
     what Supabase answered.
   - answers OPTIONS for CORS and allows the headers authorization, x-client-info,
     apikey, content-type and x-korzen-token.

3. In the sign-up form, before calling the function, get the token with
   `await window.korzen?.ready()` and send it as the x-korzen-token header of
   supabase.functions.invoke("signup", ...). Show the function's error as the form's
   error. Never call /v1/decide from the browser.

4. If the app has a free trial, call the same check with path "/trial" in the Edge
   Function that starts it, before the trial is written.

Do not add a CAPTCHA, change the sign-in, or log the API key. Show me the diff.

A tag

Em index.html, no <head>. A tag observa a página e entrega o token dela para a função a cada cadastro. O seu endereço do Lovable e o seu domínio próprio são aprendidos como domínios do seu site nas primeiras visitas.

<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>

A Edge Function

O Supabase roda as Edge Functions no Deno, que roda o SDK de Node como ele é, importado do npm. A função pergunta ao Bot Protection e depois cria a conta com a sua anon key, como o formulário fazia antes. Qualquer erro, um timeout acima de 200 ms ou uma chave errada não dá decisão, e o cadastro segue.

// supabase/functions/signup/index.ts
import { createClient as korzen, fromRequest, ipFrom } from "npm:@korzen/bot-protection@3";
import { createClient } from "npm:@supabase/supabase-js@2";

const bp = korzen({ apiKey: Deno.env.get("KORZEN_API_KEY") ?? "" });
const cors = {
  "access-control-allow-origin": "*",
  "access-control-allow-headers": "authorization, x-client-info, apikey, content-type, x-korzen-token",
};

Deno.serve(async (req) => {
  if (req.method === "OPTIONS") return new Response("ok", { headers: cors });
  const { email, password } = await req.json();
  // The token comes in x-korzen-token; the first X-Forwarded-For entry is the visitor's.
  // protectedAction: a script that never loaded your page holds no token.
  const d = await bp.decide(fromRequest(req, { ip: ipFrom.vercel, path: "/signup", protectedAction: true }));
  if (d?.action === "block") {
    return Response.json({ error: "We could not create your account." }, { status: 403, headers: cors });
  }
  const supabase = createClient(Deno.env.get("SUPABASE_URL")!, Deno.env.get("SUPABASE_ANON_KEY")!);
  const { data, error } = await supabase.auth.signUp({
    email,
    password,
    options: { data: { korzen_request_id: d?.request_id ?? null } },
  });
  return Response.json(error ? { error: error.message } : data, { status: error ? 400 : 200, headers: cors });
});

Faça o deploy com verify_jwt = false para esta função em supabase/config.toml: um visitante que se cadastra ainda não tem sessão. O Lovable faz as duas coisas quando escreve a função.

O formulário

O formulário chama a função no lugar de supabase.auth.signUp, com o token da tag num cabeçalho: a página e a função ficam em domínios diferentes, então o cookie não viaja.

const token = (await window.korzen?.ready()) ?? "";
const { data, error } = await supabase.functions.invoke("signup", {
  body: { email, password },
  headers: { "x-korzen-token": token },
});

O teste grátis

Onde o app começa um teste grátis numa Edge Function, a mesma chamada vem primeiro, com o path /trial. Ali o visitante já está logado, então mantenha a verificação de JWT do Supabase ligada, e envie o token da página do mesmo jeito.

const d = await bp.decide(fromRequest(req, { ip: ipFrom.vercel, path: "/trial", protectedAction: true }));
if (d?.action === "block") {
  return Response.json({ error: "We could not start your trial." }, { status: 403, headers: cors });
}
// start the trial as before, keeping d?.request_id with it

O IP do visitante

Numa Edge Function, o endereço do visitante é a primeira entrada do X-Forwarded-For, como os próprios exemplos do Supabase o leem; ipFrom.vercel lê essa entrada. Confira uma vez: envie um cadastro com um X-Forwarded-For seu e veja o IP da decisão no painel. Se aparecer o endereço que você escreveu, escreva para nós antes de ligar o modo bloqueio.

Feche o caminho por fora

A anon key está na página, então um bot ainda consegue chamar o cadastro do Supabase direto, nos dois tipos de projeto. O hook Before User Created do guia do Supabase Auth recusa cadastros que não passaram pela sua checagem: a sua função gera o passe que a server action daquele guia gera. Uma server function recebe o email e devolve o passe com o veredito, e o formulário coloca o passe em options.data; uma Edge Function gera o passe com a Web Crypto API no lugar de node:crypto. Adicione o hook quando o modo monitor mostrar as decisões que você espera.

Teste

  1. Abra a prévia do seu app e a página de cadastro. Nas ferramentas de desenvolvedor do navegador, o cookie _kz aparece depois de alguns segundos.
  2. Cadastre-se. A decisão aparece na página Decisões do painel, em /signup.
  3. Confira o fail open: coloque uma KORZEN_API_KEY errada e cadastre-se de novo. A chamada responde 401, e o cadastro passa.

A conta começa no modo monitor, em que a action é sempre allow: nada muda para os visitantes até você ligar o modo bloqueio.

Erros comuns

  • A chave de API na página ou no chat. Ela fica só nos secrets do projeto; a página tem apenas a site key.
  • Um cadastro ou um teste grátis que ainda pula a checagem: o formulário chamando supabase.auth.signUp antes da checagem, ou o teste ainda gravado pelo navegador. Procure os dois no código depois da mudança do Lovable.
  • No TanStack Start, X-Forwarded-For lido como o IP do visitante. Qualquer visitante escreve o que quiser ali; leia CF-Connecting-IP.
  • Numa Edge Function, sem x-korzen-token nos cabeçalhos de CORS. Aí o navegador recusa a chamada antes de ela sair.
  • Um erro da chamada que trava o cadastro. Sem decisão quer dizer: deixe o visitante passar.