Een Lovable-app raadpleegt Bot Protection op zijn server voordat hij een account aanmaakt of een proefperiode start, en laadt de tag in zijn pagina's. Lovable schrijft allebei vanuit een prompt. Deze pagina geeft de prompt voor elk soort Lovable-project, en daarna wat Lovable ervan schrijft, zodat je de diff kunt lezen.
Welk project je hebt
Lovable maakt nieuwe projecten op TanStack Start: hun pagina's worden gerenderd op Cloudflare Workers, en hun servercode bestaat uit TanStack Start server functions. Een project met src/routes/__root.tsx is er een: volg TanStack Start. Een project met een index.html en zonder eigen server draait zijn servercode als Supabase Edge Functions: volg Edge Functions van Supabase.
TanStack Start
De server function draait in dezelfde Worker als de pagina's, op het eigen domein van je app, dus de cookie van de tag gaat met elke call mee: het token heeft geen header nodig.
De prompt
Plak hem in de chat van je project. Als je bent ingelogd, vult deze pagina je eigen site key in. Lovable vraagt daarna om KORZEN_API_KEY in een formulier voor secrets: plak je geheime API-sleutel daar, nooit in de chat.
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.
Lovable installeert geen npm-release die jonger is dan 24 uur: wacht vlak na een release een dag of pin de versie ervoor.
De tag
In src/routes/__root.tsx, in de <head> van de shell, zodat elke pagina ermee wordt gerenderd. Je Lovable-adres en je eigen domein worden bij de eerste bezoeken allebei geleerd als domeinen van je site.
<head> <HeadContent /> <script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script> </head>
De server function
TanStack Start draait hem alleen op de server; de pagina krijgt een stub die hem aanroept. Hij leest de API-sleutel uit de secrets van het project, raadpleegt Bot Protection en antwoordt of de registratie door mag gaan. Elke fout, een timeout van meer dan 200 ms of een verkeerde sleutel geeft geen beslissing, en de registratie gaat door.
// 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"));
Het formulier
Het formulier vraagt eerst de server function en registreert daarna bij Supabase zoals voorheen, met de request_id van de beslissing bij het account. Als de call zelf mislukt, registreert het zoals voorheen.
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 } });
De proefperiode
De proefperiode start in een server function met de ingelogde gebruiker, na dezelfde controle met het pad /trial. Lovable neemt de browser ook het recht af om er zelf een te starten, zodat de controle niet over te slaan is.
// 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;
Het IP-adres van de bezoeker
Lovable serveert TanStack Start-apps vanaf Cloudflare Workers, waar CF-Connecting-IP het adres van de bezoeker is: Cloudflare schrijft hem, en weigert een verzoek dat er zelf een meestuurt. ipFrom.cloudflare leest hem. Lees daar nooit X-Forwarded-For: Lovable geeft door wat de bezoeker erin stuurt.
Edge Functions van Supabase
Hier is de app een pagina in de browser met een Supabase-project erachter, zonder eigen server. De controle draait in een Supabase Edge Function die het account aanmaakt, op het domein van Supabase, dus het token gaat in een header mee.
De prompt
Plak hem in de chat van je project. Als je bent ingelogd, vult deze pagina je eigen site key in. Voeg daarna je geheime API-sleutel toe aan de Edge Function-secrets van het project als KORZEN_API_KEY wanneer Lovable erom vraagt, nooit in de chat.
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.
De tag
In index.html, in de <head>. De tag bekijkt de pagina en geeft zijn token bij elke registratie mee aan de function. Je Lovable-adres en je eigen domein worden bij de eerste bezoeken allebei geleerd als domeinen van je site.
<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>
De Edge Function
Supabase draait Edge Functions op Deno, dat de Node-SDK draait zoals hij is, geïmporteerd uit npm. De function raadpleegt Bot Protection en maakt daarna het account aan met je anon key, zoals het formulier eerder deed. Elke fout, een timeout van meer dan 200 ms of een verkeerde sleutel geeft geen beslissing, en de registratie gaat door.
// 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 }); });
Deploy hem met verify_jwt = false voor deze function in supabase/config.toml: een bezoeker die zich registreert, heeft nog geen sessie. Lovable doet allebei wanneer het de function schrijft.
Het formulier
Het formulier roept de function aan in plaats van supabase.auth.signUp, met het token van de tag in een header: de pagina en de function staan op verschillende domeinen, dus de cookie reist niet mee.
const token = (await window.korzen?.ready()) ?? ""; const { data, error } = await supabase.functions.invoke("signup", { body: { email, password }, headers: { "x-korzen-token": token }, });
De proefperiode
Waar de app een gratis proefperiode start in een Edge Function, gaat dezelfde call eerst, met het pad /trial. De bezoeker is daar ingelogd, dus laat de JWT-controle van Supabase aanstaan, en stuur het token vanaf de pagina op dezelfde manier.
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
Het IP-adres van de bezoeker
In een Edge Function is het adres van de bezoeker de eerste vermelding in X-Forwarded-For, zoals de eigen voorbeelden van Supabase het lezen; ipFrom.vercel leest precies die. Controleer het één keer: stuur een registratie met een eigen X-Forwarded-For en bekijk het IP-adres van de beslissing op het dashboard. Toont het het adres dat je zelf schreef, schrijf ons dan voordat je de blokkeermodus aanzet.
Sluit de weg eromheen af
De anon key staat in de pagina, dus een bot kan de registratie van Supabase nog steeds rechtstreeks aanroepen, in beide soorten project. De Before User Created hook uit de Supabase Auth-gids weigert registraties die niet via je controle kwamen: je function maakt de pas die de server action uit die gids maakt. Een server function krijgt het e-mailadres en geeft de pas terug met zijn oordeel, en het formulier zet hem in options.data; een Edge Function maakt hem met de Web Crypto API in plaats van node:crypto. Voeg hem toe zodra de monitormodus de beslissingen laat zien die je verwacht.
Test het
- Open de preview van je app en de registratiepagina. In de developer tools van de browser verschijnt na een paar seconden de
_kz-cookie. - Registreer je. De beslissing verschijnt op de pagina Beslissingen van het dashboard, onder
/signup. - Controleer fail-open: zet een verkeerde
KORZEN_API_KEYen registreer je opnieuw. De call antwoordt met401, en de registratie gaat door.
Het account begint in monitormodus, waar action altijd allow is: voor bezoekers verandert er niets tot je de blokkeermodus aanzet.
Veelgemaakte fouten
- De API-sleutel in de pagina of in de chat. Die hoort alleen in de secrets van het project; de pagina heeft alleen de site key.
- Een registratie of proefperiode die de controle nog overslaat: het formulier dat
supabase.auth.signUpvóór de controle aanroept, of de proefperiode die nog vanuit de browser wordt geschreven. Zoek naar allebei in de code na de wijziging van Lovable. - In TanStack Start
X-Forwarded-Forgelezen als het IP-adres van de bezoeker. Elke bezoeker kan daar invullen wat hij wil; leesCF-Connecting-IP. - In een Edge Function geen
x-korzen-tokenin de CORS-headers. De browser weigert de call dan voordat hij vertrekt. - Een fout van de call die de registratie tegenhoudt. Geen beslissing betekent: laat de bezoeker door.