Un'app Lovable chiede a Bot Protection sul proprio server prima di creare un account o avviare una prova gratuita, e carica il tag nelle sue pagine. Lovable scrive entrambe le cose da un prompt. Questa pagina dà il prompt per ogni tipo di progetto Lovable, poi quello che Lovable ne scrive, così puoi leggere il diff.
Che progetto hai
Lovable crea i nuovi progetti su TanStack Start: le loro pagine sono renderizzate su Cloudflare Workers, e il loro codice server sono server function di TanStack Start. Un progetto con src/routes/__root.tsx è uno di questi: segui TanStack Start. Un progetto con un index.html e senza un server suo esegue il codice server come Supabase Edge Function: segui Edge Function di Supabase.
TanStack Start
La server function gira nello stesso Worker delle pagine, sul dominio della tua app, quindi il cookie del tag viaggia con ogni chiamata: il token non ha bisogno di un header.
Il prompt
Incollalo nella chat del tuo progetto. Se hai fatto l'accesso, questa pagina inserisce la tua site key. Lovable poi chiede KORZEN_API_KEY in un modulo dei secret: incolla lì la tua chiave API segreta, mai nella 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 non installa nessuna versione npm più giovane di 24 ore: subito dopo un rilascio, aspetta un giorno o fissa la versione precedente.
Il tag
In src/routes/__root.tsx, nel <head> della shell, così ogni pagina viene renderizzata con il tag. Il tuo indirizzo Lovable e il tuo dominio vengono entrambi appresi come domini del tuo sito alle prime visite.
<head> <HeadContent /> <script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script> </head>
La server function
TanStack Start la esegue solo sul server; la pagina riceve uno stub che la chiama. Legge la chiave API dai secret del progetto, chiede a Bot Protection e risponde se la registrazione può proseguire. Qualsiasi errore, un timeout oltre i 200 ms o una chiave sbagliata non danno alcuna decisione, e la registrazione prosegue.
// 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"));
Il form
Il form chiede prima alla server function, poi registra su Supabase come prima, tenendo il request_id della decisione con l'account. Se la chiamata stessa fallisce, registra come prima.
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 } });
La prova gratuita
La prova gratuita parte in una server function con l'utente che ha fatto l'accesso, dopo lo stesso controllo con il path /trial. Lovable toglie anche al browser il diritto di avviarne una da solo, così il controllo non si può saltare.
// 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;
L'IP del visitatore
Lovable serve le app TanStack Start da Cloudflare Workers, dove CF-Connecting-IP è l'indirizzo del visitatore: lo scrive Cloudflare, e rifiuta una richiesta che manda il proprio. ipFrom.cloudflare lo legge. Non leggere mai lì X-Forwarded-For: Lovable lascia passare quello che il visitatore ci manda.
Edge Function di Supabase
Qui l'app è una pagina nel browser con un progetto Supabase dietro, senza un server suo. Il controllo gira in una Edge Function di Supabase che crea l'account, sul dominio di Supabase, quindi il token va in un header.
Il prompt
Incollalo nella chat del tuo progetto. Se hai fatto l'accesso, questa pagina inserisce la tua site key. Poi aggiungi la tua chiave API segreta ai secret delle Edge Function del progetto come KORZEN_API_KEY quando Lovable la chiede, mai nella 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.
Il tag
In index.html, nel <head>. Il tag osserva la pagina e passa il suo token alla funzione a ogni registrazione. Il tuo indirizzo Lovable e il tuo dominio vengono entrambi appresi come domini del tuo sito alle prime visite.
<script src="https://eu.korzen.dev/v1/tag.js" data-site-key="YOUR_SITE_KEY" async></script>
La Edge Function
Supabase esegue le Edge Function su Deno, che esegue l'SDK Node così com'è, importato da npm. La funzione chiede a Bot Protection, poi crea l'account con la tua anon key, come faceva prima il form. Qualsiasi errore, un timeout oltre i 200 ms o una chiave sbagliata non danno alcuna decisione, e la registrazione prosegue.
// 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 }); });
Fai il deploy con verify_jwt = false per questa funzione in supabase/config.toml: un visitatore che si registra non ha ancora una sessione. Lovable fa entrambe le cose quando scrive la funzione.
Il form
Il form chiama la funzione al posto di supabase.auth.signUp, con il token del tag in un header: la pagina e la funzione sono su domini diversi, quindi il cookie non viaggia.
const token = (await window.korzen?.ready()) ?? ""; const { data, error } = await supabase.functions.invoke("signup", { body: { email, password }, headers: { "x-korzen-token": token }, });
La prova gratuita
Dove l'app avvia una prova gratuita in una Edge Function, la stessa chiamata viene prima, con il path /trial. Lì il visitatore ha già fatto l'accesso, quindi lascia attivo il controllo JWT di Supabase e invia il token dalla pagina allo stesso modo.
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
L'IP del visitatore
In una Edge Function l'indirizzo del visitatore è la prima voce di X-Forwarded-For, come la leggono gli esempi di Supabase stessi; ipFrom.vercel legge proprio quella. Verificalo una volta: invia una registrazione con un X-Forwarded-For scelto da te e guarda l'IP della decisione nella dashboard. Se mostra l'indirizzo che hai scritto, scrivici prima di attivare la modalità blocco.
Chiudi la strada che la aggira
La anon key è nella pagina, quindi un bot può ancora chiamare direttamente la registrazione di Supabase, in entrambi i tipi di progetto. L'hook Before User Created della guida Supabase Auth rifiuta le registrazioni che non sono passate dal tuo controllo: la tua funzione crea il lasciapassare che crea la server action di quella guida. Una server function riceve l'email e restituisce il lasciapassare con il suo verdetto, e il form lo mette in options.data; una Edge Function lo crea con la Web Crypto API al posto di node:crypto. Aggiungilo quando la modalità monitor mostra le decisioni che ti aspetti.
Provalo
- Apri l'anteprima della tua app e la sua pagina di registrazione. Negli strumenti per sviluppatori del browser, il cookie
_kzcompare dopo qualche secondo. - Registrati. La decisione compare nella pagina Decisioni della dashboard, sotto
/signup. - Verifica il fail-open: imposta una
KORZEN_API_KEYsbagliata e registrati di nuovo. La chiamata risponde401, e la registrazione va a buon fine.
L'account parte in modalità monitor, dove action è sempre allow: per i visitatori non cambia niente finché non attivi la modalità blocco.
Errori comuni
- La chiave API nella pagina o nella chat. Va solo nei secret del progetto; la pagina ha soltanto la site key.
- Una registrazione o una prova gratuita che salta ancora il controllo: il form che chiama
supabase.auth.signUpprima del controllo, o la prova ancora scritta dal browser. Cerca entrambe le cose nel codice dopo la modifica di Lovable. - Con TanStack Start,
X-Forwarded-Forletto come IP del visitatore. Qualsiasi visitatore può scriverci quello che vuole; leggiCF-Connecting-IP. - In una Edge Function, manca
x-korzen-tokennegli header CORS. Allora il browser rifiuta la chiamata prima che parta. - Un errore della chiamata che blocca la registrazione. Nessuna decisione significa: lascia passare il visitatore.