# Node.js Better Auth

The official Better Auth plugin for the VPNDetection API: it checks the address behind each sign-up for VPN, Tor, proxy and hosting use, and refuses the ones you choose with a 403.

## Getting Started

```bash
npm install vpndetection-better-auth
```

Requires Node.js 22 or newer and Better Auth 1.7 or newer. TypeScript types are included.

**Start with a free API key**, no card needed: create one in the [console](https://app.vpndetection.io). A free key checks VPN, Tor and relays on its organization's quota. Hosting networks and the proxy flags are the Data plan's ([pricing](https://vpndetection.io/pricing)). Past the quota, each lookup raises `quota_exceeded` until the quota resets, and the plugin lets the sign-up through and logs it ([When a lookup fails](#when-a-lookup-fails)).

```ts
import { betterAuth } from 'better-auth';
import { vpndetection } from 'vpndetection-better-auth';

export const auth = betterAuth({
    emailAndPassword: { enabled: true },
    plugins: [
        vpndetection({
            apiKey: process.env.VPNDETECTION_API_KEY,
            blockCondition: [{ isVpn: true }, { isTor: true }],
        }),
    ],
});
```

A refused sign-up gets a `403` with the code `VPNDETECTION_BLOCKED` and the message `Access from this network is not allowed.`, which `message` replaces. No user is created. The same check runs when your server calls `auth.api.signUpEmail` with the request's headers.

## What it checks

By default only `/sign-up/email`. `paths` takes Better Auth's endpoint paths, and one ending in `*` matches every path that starts with it:

```ts
vpndetection({
    apiKey: process.env.VPNDETECTION_API_KEY,
    blockCondition: { isVpn: true },
    paths: ['/sign-up/email', '/sign-in/*'],
})
```

A sign-in through a social provider is checked at `/sign-in/social`, before Better Auth knows whether the account is new, so adding it checks sign-ins as well as sign-ups.

## Blocking

A condition is written in the shape of a result, and only the members you name count:

```ts
blockCondition: { isVpn: true }                                       // any VPN
blockCondition: [{ isVpn: true }, { isTor: true }, { isRelay: true }] // a list is OR
blockCondition: { isVpn: true, vpn: { provider: 'nordvpn' } }         // one provider, on the Data plan
blockCondition: { isHosting: true }                                   // a datacenter, on the Data plan
blockCondition: { isIspproxy: true }                                  // an ISP proxy, on the Data plan
blockCondition: { isResproxy: true, resproxy: { hits: { gte: 5 } } }  // a numeric threshold, on the Data plan
```

Values match by equality, strings without regard to case, and an array means any of them. `{ gte, gt, lte, lt }` compares numbers. A member set to `false` or `null` is ignored, and a condition that constrains nothing is refused when the plugin is built, since it would refuse every sign-up.

Without a `blockCondition` nobody is refused, and `onLookup` gets each answer to record or act on:

```ts
vpndetection({
    apiKey: process.env.VPNDETECTION_API_KEY,
    onLookup: (lookup, request) => {
        console.log(request.path, lookup.ip, lookup.result?.isVpn);
    },
})
```

## Where the client address comes from

By default the plugin reads the address Better Auth itself resolves, as its rate limiter does, so it follows your `advanced.ipAddress` settings. Better Auth reads `X-Forwarded-For` and takes it only when it holds one address, unless you list your proxies in `trustedProxies`, when it walks the chain from the right past them:

```ts
betterAuth({
    advanced: {
        ipAddress: {
            trustedProxies: ['10.0.0.0/8'],              // your load balancer
            // ipAddressHeaders: ['cf-connecting-ip'],   // or the header your edge writes
        },
    },
    plugins: [vpndetection({ apiKey: process.env.VPNDETECTION_API_KEY, blockCondition: { isVpn: true } })],
});
```

When Better Auth resolves no address, the plugin looks nothing up, lets the sign-up through and warns once. Outside production Better Auth falls back to `127.0.0.1`, which is a private address and is answered locally without a lookup.

`ipSelector` replaces Better Auth's address with your own choice:

```ts
import { headerIpSelector, xffIpSelector } from 'vpndetection-better-auth';

vpndetection({ ipSelector: headerIpSelector('CF-Connecting-IP') })  // behind Cloudflare
vpndetection({ ipSelector: xffIpSelector({ depth: 1 }) })          // the address your nearest proxy saw
```

The left-most `X-Forwarded-For` entry is whatever the visitor sent, so `xffIpSelector()` without a `depth` is only safe when an edge you control overwrites the header.

## When a lookup fails

A lookup that fails (a network error, a timeout, a spent quota, an outage of ours) lets the sign-up through and logs it through Better Auth's logger, a spent quota at error level and at most once a minute, however many sign-ups it fails. `failClosed: true` refuses the sign-up instead. A lookup holds the request for at most 2.5 seconds (`timeoutMs`) and is not retried (`retries`).

Each answer is cached per address for the client's default time, so a burst of sign-ups from one address makes one lookup. Pass `client` to share an existing `VPNDetection` client and its cache.

## Absent is not false

A free key's answers leave out the hosting flag, the five proxy flags (`isIspproxy` among them) and the AS's `type`, and `isVpn` can be absent from an answer too. A field the answer leaves out is `undefined`, never `false`, and a condition on it never matches: the plugin warns once (`onMissingField`, `'throw'` to make it an error, `'ignore'` to say nothing).
