Korzen
Bot Protection
このドキュメントの目次

Lovable

Lovable アプリでの Bot Protection。ページのタグ、server function か Supabase の Edge Function での新規登録と無料トライアルのチェック、両方を追加するプロンプト。

Lovable アプリは、アカウントを作成したり無料トライアルを開始したりする前に自分のサーバーで Bot Protection に問い合わせ、ページにタグを読み込みます。Lovable はその両方をプロンプトから書きます。このページでは Lovable プロジェクトの種類ごとにプロンプトを示し、続いて Lovable がそこから書く内容を示すので、diff を読むときに使えます。

どちらのプロジェクトか

Lovable は新しいプロジェクトを TanStack Start で作成します。ページは Cloudflare Workers でレンダリングされ、サーバーのコードは TanStack Start の server function です。src/routes/__root.tsx があるプロジェクトはこちらです。TanStack Start に進んでください。index.html があり独自のサーバーを持たないプロジェクトは、サーバーのコードを Supabase の Edge Function として動かします。Supabase の Edge Function に進んでください。

TanStack Start

server function はページと同じ Worker で、アプリ自身のドメイン上で動くため、タグの Cookie は呼び出しのたびに一緒に送られます。トークンにヘッダーは必要ありません。

プロンプト

プロジェクトのチャットに貼り付けてください。サインインしていれば、このページにあなたのサイトキーが入ります。その後 Lovable がシークレットのフォームで KORZEN_API_KEY を求めるので、シークレット API キーはそこに貼り付けます。チャットには決して書かないでください。

プロンプト
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 は公開から 24 時間未満の npm リリースをインストールしません。リリース直後は 1 日待つか、1 つ前のバージョンに固定してください。

タグ

src/routes/__root.tsx のシェルの <head> に置き、すべてのページがタグ付きでレンダリングされるようにします。Lovable のアドレスと独自ドメインは、どちらも最初の訪問でサイトのドメインとして学習されます。

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

server function

TanStack Start はこれをサーバーだけで動かし、ページにはそれを呼び出すスタブが渡されます。プロジェクトのシークレットから API キーを読み、Bot Protection に問い合わせ、新規登録を進めてよいかを返します。エラー、200 ms を超えるタイムアウト、誤ったキーのいずれでも判定は返らず、新規登録はそのまま進みます。

// 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"));

フォーム

フォームはまず server function に問い合わせ、その後は以前と同じように Supabase で新規登録し、判定の request_id をアカウントと一緒に保存します。呼び出しそのものが失敗したときは、以前と同じように新規登録します。

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 } });

無料トライアル

無料トライアルは、サインイン済みのユーザーで server function の中で開始され、その前にパス /trial で同じチェックを行います。Lovable はブラウザが自分でトライアルを開始する権限も取り除くため、チェックを飛ばすことはできません。

// 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;

訪問者の IP

Lovable は TanStack Start のアプリを Cloudflare Workers から配信しており、そこでは CF-Connecting-IP が訪問者のアドレスです。Cloudflare がこれを書き込み、自分で送ってきたリクエストは拒否します。ipFrom.cloudflare がこれを読みます。そこでは決して X-Forwarded-For を読まないでください。Lovable は訪問者が送ってきた値をそのまま渡します。

Supabase の Edge Function

こちらのアプリは、ブラウザ上のページとその背後の Supabase プロジェクトでできており、独自のサーバーはありません。チェックはアカウントを作成する Supabase の Edge Function の中で、Supabase のドメイン上で行われるため、トークンはヘッダーで送ります。

プロンプト

プロジェクトのチャットに貼り付けてください。サインインしていれば、このページにあなたのサイトキーが入ります。その後、Lovable に求められたら、シークレット API キーをプロジェクトの Edge Function のシークレットに KORZEN_API_KEY として追加します。チャットには決して書かないでください。

プロンプト
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.

タグ

index.html の <head> に置きます。タグはページを見守り、新規登録のたびにトークンを関数に渡します。Lovable のアドレスと独自ドメインは、どちらも最初の訪問でサイトのドメインとして学習されます。

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

Edge Function

Supabase は Edge Function を Deno で動かし、Deno は npm からインポートした Node SDK をそのまま動かします。関数は Bot Protection に問い合わせてから、以前フォームがしていたように anon キーでアカウントを作成します。エラー、200 ms を超えるタイムアウト、誤ったキーのいずれでも判定は返らず、新規登録はそのまま進みます。

// 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 });
});

supabase/config.toml でこの関数に verify_jwt = false を設定して deploy します。新規登録する訪問者にはまだセッションがないためです。Lovable は関数を書くときに両方を行います。

フォーム

フォームは supabase.auth.signUp の代わりに関数を呼び出し、タグのトークンをヘッダーに入れて送ります。ページと関数は別のドメインにあるため、Cookie は届きません。

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

無料トライアル

アプリが Edge Function で無料トライアルを開始する場合は、パス /trial で同じ呼び出しを先に行います。そこでは訪問者はサインイン済みなので、Supabase の JWT チェックはオンのままにし、ページからのトークンも同じ方法で送ります。

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

訪問者の IP

Edge Function では、Supabase 自身の例と同じく、訪問者のアドレスは X-Forwarded-For の最初のエントリです。ipFrom.vercel はそのエントリを読みます。一度確認してください。自分で書いた X-Forwarded-For を付けて新規登録を送り、ダッシュボードで判定の IP を見ます。書いたアドレスが表示された場合は、ブロックモードをオンにする前にご連絡ください。

迂回経路を塞ぐ

anon キーはページに含まれているため、どちらの種類のプロジェクトでも、ボットは Supabase の新規登録を直接呼び出せてしまいます。Supabase Auth ガイドの Before User Created フックは、あなたのチェックを経由しなかった新規登録を拒否します。そのガイドの server action が作る通行証を、あなたの関数に作らせてください。server function ならメールアドレスを受け取って判定と一緒に通行証を返し、フォームがそれを options.data に入れます。Edge Function なら node:crypto の代わりに Web Crypto API で作ります。モニターモードで期待どおりの判定が出るのを確認してから追加します。

テストする

  1. アプリのプレビューを開き、新規登録ページを開きます。数秒後、ブラウザの開発者ツールに _kz Cookie が表示されます。
  2. 新規登録します。判定がダッシュボードの判定ページに、/signup で表示されます。
  3. fail-open を確認します。誤った KORZEN_API_KEY を設定してもう一度新規登録すると、呼び出しは 401 を返し、新規登録はそのまま完了します。

アカウントはモニターモードで始まり、その間 action は常に allow です。ブロックモードをオンにするまで、訪問者にとっては何も変わりません。

よくある間違い

  • API キーをページやチャットに書いている。API キーはプロジェクトのシークレットにだけ置き、ページにはサイトキーだけを置きます。
  • 新規登録や無料トライアルがまだチェックを飛ばしている。チェックより前に supabase.auth.signUp を呼び出すフォームや、まだブラウザから書き込まれるトライアルです。Lovable の変更後に、コードで両方を検索してください。
  • TanStack Start で X-Forwarded-For を訪問者の IP として読んでいる。そこにはどの訪問者でも好きな値を書けます。CF-Connecting-IP を読んでください。
  • Edge Function で、CORS のヘッダーに x-korzen-token がない。その場合、ブラウザは呼び出しを送信前に拒否します。
  • 呼び出しのエラーで新規登録が止まる。判定がないということは、訪問者を通すという意味です。