# CyberFence — full reference for LLMs and coding agents Source: https://cyberfence.dev · SDK: @cyberfence/node · API: https://api.cyberfence.dev # Integrating CyberFence: instructions for AI coding agents You are adding CyberFence sign-up protection to an existing app. Follow these steps in order. Read the app's code first; don't guess its structure. Keep every change small, typed and consistent with the app's existing patterns. CyberFence returns one decision per sign-up: - `allow`: create the user normally. - `review`: **held back**. Create the user, but without the trial, credits or paid features, and let them appeal. - `deny`: refuse the sign-up and show the message CyberFence returns. Package: `@cyberfence/node` (Node 18+, no dependencies). API: `https://api.cyberfence.dev`. --- ## 0. Ground rules (never break these) 1. **Server-side only.** The API key (`CYBERFENCE_KEY`) is a secret. Never import the SDK in client or browser code, never put the key in a `NEXT_PUBLIC_*` / `VITE_*` variable, and never commit it. Add it to `.env.example` with an empty value. 2. **Every sign-up path.** Protect email/password sign-up **and** every OAuth or SSO path that creates a new user (Google, Microsoft, GitHub, magic link…). Returning logins are not sign-ups; don't call `protect()` for them. 3. **Call before creating the user**, so CyberFence's velocity counts don't include the new account yet. 4. **`review` is not `deny`.** Never refuse a `review` sign-up. Create the account in a held-back state. 5. **Fail open is intended.** If CyberFence is unreachable, `protect()` returns `decision: 'allow'` with `failedOpen: true`. Don't add your own retries or turn that into an error. 6. **Use `verdict.normalizedEmail`** as the stored email, or at least for uniqueness checks. It strips `+tags` and Gmail dots so one inbox can't create many accounts. 7. **Webhooks need the raw body.** Verify signatures against the exact bytes received, before any JSON body parser runs. 8. Don't change existing auth semantics beyond what's described here. Ask the user before changing the trial or credit logic if it's unclear. --- ## 1. Discover Find and note the following before writing code: - framework and router (Express, Fastify, Hono, Next.js App or Pages Router, Remix, NestJS, …) - the auth library (NextAuth/Auth.js, Better Auth, Lucia, Clerk/Supabase webhooks, custom…) - every place a **new user is created**: grep for `users.create`, `createUser`, `insert into users`, `signUp`, `register`, and the OAuth adapter's `createUser` - where the verification email is built and sent, and the verify-email route - the user model or schema, and the migration tool - how trial, credits or plan access are granted on sign-up - billing success hooks (Stripe `invoice.paid` / `checkout.session.completed`, …) - how the app reads env vars and where it keeps server-only config ## 2. Install and configure ```bash npm install @cyberfence/node # or pnpm add / yarn add / bun add, matching the repo's lockfile ``` Env vars, all server-side; add them to `.env.example` with empty values: ``` CYBERFENCE_KEY= # cf_test_… in development, cf_live_… in production CYBERFENCE_WEBHOOK_SECRET= # whsec_… from Dashboard → Webhooks # CYBERFENCE_URL= # only when self-hosting ``` Create **one** shared client module in a server-only location (for example `src/lib/cyberfence.ts`; in Next.js add `import 'server-only'` if the project uses it): ```ts import { CyberFence } from '@cyberfence/node'; export const fence = new CyberFence({ apiKey: process.env.CYBERFENCE_KEY! }); ``` ## 3. Store the decision on the user Add these fields to the user model, with a migration in the project's own tool: | field | type | purpose | |---|---|---| | `cyberfenceId` | string, nullable | the evaluation id (`verdict.id`); needed for verify-click, appeal, report | | `signupStatus` | enum `active` \| `held_back` \| `disabled` (or the app's equivalent) | gates the trial, credits and paid features | If the app already has a status or approval field, reuse it instead of adding a duplicate. ## 4. Protect email/password sign-up ```ts import { requestContext } from '@cyberfence/node'; import { fence } from '@/lib/cyberfence'; const verdict = await fence.protect({ email: body.email, // EXACTLY as typed (don't normalize first) name: body.name, provider: 'credentials', timeZone: body.timeZone, // from the browser, see step 5 timeToSubmitMs: body.timeToSubmitMs, // optional, see step 5 honeypot: body.website, // optional hidden field, see step 5 captchaToken: body.captchaToken, // only if the app already uses Turnstile / hCaptcha / reCAPTCHA ...requestContext(req.headers, req.socket?.remoteAddress), // ip, userAgent, country, language }); if (verdict.decision === 'deny') { return error(403, verdict.message); // verdict.message is safe to show the user } const user = await createUser({ email: verdict.normalizedEmail, signupStatus: verdict.decision === 'review' ? 'held_back' : 'active', cyberfenceId: verdict.id || null, // '' when it failed open }); if (verdict.id) await fence.report(verdict.id, { outcome: 'created', externalUserId: String(user.id) }); // Grant the trial / credits ONLY when signupStatus === 'active'. // Pass verdict.emailOpenPixelUrl to the verification email (step 6). // For held-back users, show verdict.message and the appeal form (step 8). ``` **Framework notes:** - **Next.js App Router:** use `requestContext(req.headers)`. There is no socket, so the IP comes from `x-forwarded-for` / `cf-connecting-ip`. - **Behind Cloudflare or a load balancer:** `requestContext` prefers `CF-Connecting-IP`, then `X-Real-IP`, then the first `X-Forwarded-For` entry. If the app has no proxy, pass the socket address. - **Server actions:** read headers with `headers()` from `next/headers`. ## 5. Small additions to the sign-up form (client side) These are hidden fields only; there are no visible UI changes. ```ts // when the form mounts const startedAt = Date.now(); // on submit, add to the payload: timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, timeToSubmitMs: Date.now() - startedAt, ``` Honeypot: add a visually hidden input that humans won't fill. ```html ``` Pass its value as `honeypot`. Skip the honeypot if the form already has one. ## 6. Verification email: add the pixel (rule 10) In the verification email template, add CyberFence's signed open pixel, so a verification email opened on a temp-mail site holds the account back: ```html ``` Use `verdict.emailOpenPixelUrl`. Store it with the pending verification, or regenerate it by keeping `cyberfenceId`. If the app doesn't send verification emails, skip this step and step 7. ## 7. Verify-email route: report the click (rule 10) The verify page should send `document.referrer` to the server. If verification is a plain GET link, use the request's `Referer` / `Origin` only. ```ts import { verifyClickContext } from '@cyberfence/node'; if (user.cyberfenceId) { const { heldBack } = await fence.verifyClick(user.cyberfenceId, verifyClickContext(req.headers, body.pageReferrer)); if (heldBack) await setSignupStatus(user.id, 'held_back'); // also arrives as the signup.held_back webhook } // Still mark the email as verified: held back ≠ unverified. ``` `verifyClick` never throws on outages; it returns `{ heldBack: false }`. ## 8. Appeal form for held-back users When `signupStatus === 'held_back'`, show a short form: **company website or LinkedIn** and **what you want to do** (at least 10 characters). Send it from a server route: ```ts import { CyberFenceError } from '@cyberfence/node'; try { const r = await fence.appeal(user.cyberfenceId, { website: body.website, useCase: body.useCase }); if (r.status === 'approved') await activateUser(user.id); // grant the trial now return ok({ status: r.status }); // 'pending_review': a person will decide } catch (e) { if (e instanceof CyberFenceError && (e.status === 400 || e.status === 409)) return error(e.status, e.message); throw e; } ``` The appeal can be sent once. Show a "we'll get back to you" state after that. ## 9. OAuth / SSO sign-ups Run `protect()` where a **new** user is created, with `provider` set to the provider's name and the request headers: - **NextAuth / Auth.js:** wrap the adapter's `createUser`. Don't use `events.createUser`, because it runs after the insert. Keep the original adapter and override only `createUser`: ```ts const base = PrismaAdapter(prisma); export const adapter = { ...base, async createUser(data) { const h = await headers(); // next/headers (or the request in Pages Router) const verdict = await fence.protect({ email: data.email, name: data.name, provider: 'oauth', ...requestContext(h) }); if (verdict.decision === 'deny') throw new Error(verdict.message || 'Sign-up not available'); return base.createUser!({ ...data, email: verdict.normalizedEmail, signupStatus: verdict.decision === 'review' ? 'held_back' : 'active', cyberfenceId: verdict.id || null }); }, }; ``` - **Better Auth / Lucia / custom:** call it in the hook or route that runs right before the user insert. - **Hosted auth (Clerk, Supabase Auth, Firebase Auth, …):** run `protect()` in the user-created webhook or trigger. If it's `deny`, disable or delete the user; if it's `review`, set your app's held-back flag. Use the real provider id where you have it (`google`, `github`, `microsoft`…). Rules 3, 6 and 9 only apply to `credentials`. ## 10. Webhook endpoint Create `POST /webhooks/cyberfence` and register its URL in Dashboard → Webhooks. Subscribe to `signup.approved`, `signup.rejected`, `signup.held_back` and `signup.appealed`. ```ts import { verifyWebhook } from '@cyberfence/node'; // Express: app.post('/webhooks/cyberfence', express.raw({ type: 'application/json' }), handler) // Next.js App Router: const raw = await req.text(); const event = verifyWebhook(rawBody, signatureHeader /* 'cyberfence-signature' */, process.env.CYBERFENCE_WEBHOOK_SECRET!); const ev = event.data.evaluation!; switch (event.type) { case 'signup.approved': await activateUser(ev.externalUserId!); break; // grant the trial case 'signup.rejected': await setSignupStatus(ev.externalUserId!, 'disabled'); break; case 'signup.held_back': await setSignupStatus(ev.externalUserId!, 'held_back'); break; case 'signup.appealed': /* optional: notify your team */ break; } return 200; ``` - Return 400 on `WebhookVerificationError`, and 2xx quickly otherwise. Deliveries are retried for about 45 hours and can arrive more than once, so make the handlers idempotent. - If `externalUserId` is missing, look the user up by `cyberfenceId === ev.id`. ## 11. Report paying customers In the billing success handler (first successful payment): ```ts if (user.cyberfenceId) await fence.report(user.cyberfenceId, { outcome: 'customer', externalUserId: String(user.id) }); ``` This makes the customer's company domain known-good, so colleagues signing up later aren't held back by the domain or network rules. When an account turns out to be abuse, report `{ outcome: 'fraud' }`. ## 12. Verify the integration Use a **test key** (`cf_test_…`): it runs the full pipeline and isn't billed. Then check: - [ ] A normal sign-up returns `allow` and the user gets the trial. - [ ] `x@mailinator.com` returns `deny` with a user-visible message. - [ ] A sign-up with user agent `curl/8` returns `deny` (`reason: 'bot'`). - [ ] Forcing a held-back case creates the user without a trial and shows the appeal form. Either set a domain to "block" in the dashboard rules, or hold back with `blockedCountries` and pass `country`. - [ ] Submitting the appeal returns `approved` or `pending_review`. Approving it in Dashboard → Review queue fires `signup.approved` and the app activates the user. - [ ] The webhook endpoint returns 400 on a bad signature (Dashboard → Webhooks → "Send test" sends a valid `ping`). - [ ] With `CYBERFENCE_URL=http://127.0.0.1:9` (unreachable), sign-up still works (`failedOpen: true`). - [ ] `git grep CYBERFENCE_KEY` shows no hard-coded keys and no client-side usage. - [ ] Existing tests still pass. If they hit sign-up, mock `fence.protect` to return `{ decision: 'allow', id: '', normalizedEmail: email, emailOpenPixelUrl: '' }`. ## Reference | `verdict` field | meaning | |---|---| | `decision` | `allow` / `review` / `deny`; act on this | | `reason` | code, e.g. `ok`, `disposable_email`, `rule1_throwaway_domain`, `rule13_agent_sure` | | `message` | end-user-safe text (empty for `allow`) | | `normalizedEmail` | canonical email to store | | `id` | evaluation id; keep it as `cyberfenceId` | | `ai` | Agent's opinion `{ verdict: 'real' \| 'suspicious', confidence, signal }` | | `emailOpenPixelUrl` | pixel for the verification email | | `livemode` | `false` with test keys | | `failedOpen` | `true` when CyberFence was unreachable | Full API docs: https://cyberfence.dev/docs --- # SDK reference: @cyberfence/node Stop fake signups before they reach your database. One call returns **allow**, **review** or **deny** for each signup, based on three things: - **Sign-up trust rules** proven in production: throwaway and burst domains, name/email mismatch, temp-Gmail dot patterns, network bursts, and more. - **Agent** (`typesafe/jev-1.13`), a structured-decision model that judges every signup and holds it back only when it is sure. - Hard abuse checks: disposable and dead email domains, bots, Tor, honeypots and IP floods. Suspicious signups aren't lost. They're **held back** and can appeal. ```bash npm install @cyberfence/node ``` Requires Node 18+. No dependencies. ## Quick start 1. Create a workspace and an API key at cyberfence.dev. Use test keys (`cf_test_…`) while developing. 2. Put the key on your **server**. It is a secret, so never ship it to the browser. ```bash CYBERFENCE_KEY=cf_live_... ``` 3. Call `protect()` before you create the user: ```ts import { CyberFence, requestContext } from '@cyberfence/node'; const fence = new CyberFence({ apiKey: process.env.CYBERFENCE_KEY! }); app.post('/signup', async (req, res) => { const verdict = await fence.protect({ email: req.body.email, // exactly as typed name: req.body.name, provider: 'credentials', // or 'google', 'microsoft', … for OAuth sign-ups timeZone: req.body.timeZone, // from the browser: Intl.DateTimeFormat().resolvedOptions().timeZone captchaToken: req.body.captchaToken, // optional: Turnstile / hCaptcha / reCAPTCHA timeToSubmitMs: req.body.timeToSubmitMs, // optional: ms between form render and submit honeypot: req.body.website, // optional: hidden field humans leave empty ...requestContext(req.headers, req.socket.remoteAddress), // ip, userAgent, country, language }); if (verdict.decision === 'deny') { return res.status(403).json({ error: verdict.message }); // safe to show to users } const user = await db.users.create({ email: verdict.normalizedEmail, // canonical: strips +aliases and Gmail dots status: verdict.decision === 'review' ? 'held_back' : 'active', cyberfenceId: verdict.id, }); await fence.report(verdict.id, { outcome: 'created', externalUserId: user.id }); // Put verdict.emailOpenPixelUrl as a 1x1 in the verification email you send (rule 10). await sendVerificationEmail(user, { pixelUrl: verdict.emailOpenPixelUrl }); res.json({ ok: true, heldBack: verdict.decision === 'review', message: verdict.message }); }); ``` | `decision` | meaning | do this | |---|---|---| | `allow` | looks legitimate | create the user normally | | `review` | held back by a trust rule or by Agent | create the user without the trial or credits; let them appeal; activate on `signup.approved` | | `deny` | clear abuse | refuse and show `verdict.message` | `verdict.reason` says why, for example `rule1_throwaway_domain`, `rule13_agent_sure` or `disposable_email`. `verdict.ai` holds Agent's opinion: `{ verdict: 'real' | 'suspicious', confidence, signal }`. ## After sign-up: temp-mail detection (rule 10) Temp-mail sites show your verification email inside their own page. CyberFence detects that in two ways and holds back a signup it had allowed. When that happens, it fires the `signup.held_back` webhook. **1. The email-open pixel.** Put the URL from `verdict.emailOpenPixelUrl` in your verification email: ```html ``` **2. The verify-link click.** Send it from your verify-email handler. The verify page posts `document.referrer`: ```ts import { verifyClickContext } from '@cyberfence/node'; app.post('/verify-email', async (req, res) => { const user = await verifyToken(req.body.token); const { heldBack } = await fence.verifyClick(user.cyberfenceId, verifyClickContext(req.headers, req.body.pageReferrer)); if (heldBack) await db.users.holdBack(user.id); res.json({ ok: true }); }); ``` ## Appeals A held-back user can tell you who they are. Agent runs a second check: clear cases are approved straight away, and everything else waits for a person in your review queue. ```ts const r = await fence.appeal(user.cyberfenceId, { website: 'https://acme.com', // company website or LinkedIn useCase: 'We sell payroll software and want to reach HR directors in the US.', }); if (r.status === 'approved') await db.users.activate(user.id); // signup.approved also fires // r.status === 'pending_review': a reviewer decides; you'll get signup.approved / signup.rejected ``` Throws `CyberFenceError` with status 400 (answers too short) or 409 (not held back, or already appealed). ## Webhooks ```ts import express from 'express'; import { verifyWebhook } from '@cyberfence/node'; app.post('/webhooks/cyberfence', express.raw({ type: 'application/json' }), async (req, res) => { let event; try { event = verifyWebhook(req.body, req.headers['cyberfence-signature'], process.env.CYBERFENCE_WEBHOOK_SECRET!); } catch { return res.sendStatus(400); } const ev = event.data.evaluation!; if (event.type === 'signup.approved') await db.users.activate(ev.externalUserId!); if (event.type === 'signup.rejected') await db.users.disable(ev.externalUserId!); if (event.type === 'signup.held_back') await db.users.holdBack(ev.externalUserId!); res.sendStatus(200); }); ``` Events: | Event | Fires when | |---|---| | `signup.allowed` | a signup is allowed | | `signup.denied` | a signup is refused | | `signup.review_required` | a signup is held back at signup time | | `signup.held_back` | an allowed signup is held back later, by rule 10 | | `signup.appealed` | a held-back user appealed and it needs a human | | `signup.approved` / `signup.rejected` | a review or appeal is decided | The signature is HMAC-SHA256 over `"."`. Timestamps more than 5 minutes off are rejected, and failed deliveries are retried for about 45 hours. ## API ### `new CyberFence(options)` | option | default | | |---|---|---| | `apiKey` | — | `cf_live_…` or `cf_test_…` (required) | | `baseUrl` | `CYBERFENCE_URL` env, then `https://api.cyberfence.dev` | set it when self-hosting | | `timeoutMs` | `10000` | per request (the Agent step can take a few seconds) | | `failOpen` | `true` | if CyberFence is unreachable (network error, 5xx, or 429 when the quota is used up), `protect()` returns `allow` with `failedOpen: true`, so an outage never blocks real users. Invalid keys or input still throw. | | `fetch` | global `fetch` | custom fetch implementation | ### `fence.protect(input)` → `ProtectResponse` - **Input:** `email` (required, as typed), `name`, `ip`, `userAgent`, `provider`, `isPasswordSignup`, `country`, `timeZone`, `language`, `captchaToken`, `timeToSubmitMs`, `honeypot`, `externalUserId`, `metadata` (up to 4KB, echoed in webhooks), `debug` (adds the full signal vector and decision trace to the response). - **Response:** `id`, `decision`, `modelDecision` (differs only in dry-run mode), `reason`, `score`, `message`, `normalizedEmail`, `status`, `dryRun`, `livemode`, `latencyMs`, `ai` (Agent's opinion), `emailOpenPixelUrl`, `failedOpen?`. ### `fence.report(id, { outcome, externalUserId?, note? })` | `outcome` | Effect | |---|---| | `created` | links the evaluation to your user | | `customer` | the user pays, so their company domain becomes known-good (exempt from the domain and network rules) | | `fraud` | marks a signup you let through as abuse; it then counts against its network and domain | ### `fence.verifyClick(id, { pageReferrer?, origin?, referer?, appHost? })` → `{ tempMailHost, heldBack }` Fails open: returns `{ heldBack: false }` if CyberFence is unreachable. ### `fence.appeal(id, { website, useCase })` → `{ status: 'approved' | 'pending_review', evaluation }` ### `fence.review(id, { action: 'approve' | 'reject', note? })` Resolves a held-back signup from your own admin tooling. The matching webhook still fires. ### `fence.getEvaluation(id)` ### Helpers - `verifyWebhook(rawBody, signatureHeader, secret, toleranceSeconds = 300)` → `WebhookEvent` - `getClientIp(headers, remoteAddress?)` reads `CF-Connecting-IP`, then `X-Real-IP`, then the first `X-Forwarded-For` entry, then the socket address. Only trust these headers if your app actually sits behind such a proxy. - `requestContext(headers, remoteAddress?)` → `{ ip, userAgent, country, language }` - `verifyClickContext(headers, pageReferrer?)` → the input for `verifyClick()` They work with Node `IncomingHttpHeaders` and the Fetch `Headers` object. ## Test mode Test keys run the full pipeline but don't count toward your quota. They also keep separate velocity counters, so local testing can't trip rate limits on live traffic. Responses carry `livemode: false`. ## License MIT