The official Rails middleware for the VPNDetection API: it checks each visitor's IP for VPN, Tor and proxy use, and can block them with a 403.
It classifies the visitor behind each request as VPN, residential proxy, Tor, hosting, CDN or relay, and hands the answer to your controllers. Blocking is opt-in.
It is Rack middleware, so it works in Sinatra, Hanami, Roda or a bare Rack app too; the Railtie is only what saves a Rails user from inserting it by hand.
Getting Started
bundle add vpndetection-railsRequires Ruby 3.3 or newer, and libcurl at runtime, which the curl package brings on Debian and Alpine. The Dockerfile Rails generates already installs it.
Lookups need no API key to try: the free plan answers each address's first lookups of the day without one, with VPN, Tor and relay detection. A free API key answers your organization's first lookups each day with every field, and the basics with no cap. The Data plan answers every field on every lookup: the hosting, CDN and proxy flags, is_bot (whether an automated client such as a search engine's crawler uses the address), the AS's type, the provider behind each flag, and bot, whose bot it is and whether its operator vouches for the address. Create a key in the console.
# config/application.rb
config.vpndetection = { api_key: ENV["VPNDETECTION_API_KEY"] }class HomeController < ApplicationController
def index
lookup = VPNDetection::Rails.lookup(request)
render plain: lookup&.result&.vpn? ? "Hello, VPN user" : "Hello"
end
endIn a non-Rails Rack app, insert it yourself:
use VPNDetection::Rails::Middleware, api_key: ENV["VPNDETECTION_API_KEY"]By default nothing is blocked. Every request gets an answer and your own code decides what to do with it, since whether a VPN visitor is a problem depends on what they're doing.
Blocking
Set a block_condition and a matching request is answered with 403 and never reaches your controllers.
config.vpndetection = { api_key: ENV["VPNDETECTION_API_KEY"], block_condition: { is_vpn: true } }A condition is written in the shape of an answer, and only the members you name are considered. That lets it reach the evidence, not just the flags:
{ is_vpn: true, vpn: { provider: "nordvpn" } } # one provider
{ is_resproxy: true, resproxy: { hits: { gte: 5 } } } # a numeric threshold
{ vpn: { confidence: %w[high medium] } } # any of these
{ bot: { identity: "spoofed" } } # a client claiming a bot it is not
[{ is_tor: true }, { is_resproxy: true }] # a list is ORSymbol and string keys both work. Values are matched by equality, strings without regard to case. An Array means any-of. A term on a member the answer holds as a list, such as pubproxy: { protocols: "socks5" } or web: { port: 443 }, matches when any element matches it, and an object term must match one element whole. A Hash of gte/gt/lte/lt compares numbers, and every bound you give must hold, so two of them are a range. Members set to false or nil are ignored, so a condition states the signals you act on; one that constrains nothing would match every request, and is refused when the middleware is built rather than silently blocking all your traffic.
Replace the refusal with on_blocked, which returns a Rack triplet:
on_blocked: ->(request, lookup) { [303, { "location" => "/no-vpn" }, []] }Let verified crawlers through
With allow_bots: true, the request's own User-Agent goes with its lookup when it names a crawler, and a request whose answer says its crawler is verified, the agent's operator vouching for the address, is never refused, whatever your block_condition matches. The answer is still on the request. It is off by default. Any other agent, or none, is not sent, since its verdict could only be not_bot. One address is looked up with at most four crawler agents an hour: past those its lookup sends none, and a request passes as a crawler only where the answer's bot.verified is true. The verdict, and bot, are a paid plan's, so an app without a key, or on a free key past its organization's full answers for the day, lets no crawler through, and the middleware warns once.
# config/application.rb
config.vpndetection = {
api_key: ENV["VPNDETECTION_API_KEY"],
block_condition: { is_hosting: true },
allow_bots: true,
}# config.ru, or any Rack app
use VPNDetection::Rails::Middleware, api_key: ENV["VPNDETECTION_API_KEY"],
block_condition: { is_hosting: true }, allow_bots: trueThe verdict is on lookup.result.user_agent: verified, spoofed where the operator does not vouch for the address, unverifiable for a bot nothing published can confirm, or not_bot. Only an answer with every field carries one, a paid plan's or a free key's within its organization's full answers for the day: without a key, or past those, no answer carries user_agent, so nothing is let through, and the middleware warns once. With it on, a condition can name the verdict, refusing a client that claims a crawler it is not:
block_condition: { user_agent: { verdict: "spoofed" } }An answer with an agent is cached apart from the address's plain answer and from another agent's, so a cache that held one entry per visitor holds one per visitor and agent.
Where the client address comes from
Get this setting right, or none of the above works.
In Rails, the default reads env["action_dispatch.remote_ip"], the answer ActionDispatch::RemoteIp computed from X-Forwarded-For minus your config.action_dispatch.trusted_proxies. That is the right fix behind a load balancer: tell Rails which proxies are yours and it resolves the visitor for you. Rack::Request#ip does not read that entry, so reading Rails' own is what makes your trusted_proxies mean anything here. With nothing in front of the app server, that default can be forged: RemoteIp believes X-Forwarded-For without checking that the connection came from a proxy, so any visitor picks the address that gets looked up. There, pass ip_selector: ->(request) { request.ip }. The middleware warns once when it sees that setup: a request carrying X-Forwarded-For, Client-IP or Forwarded from a public address outside trusted_proxies.
In a bare Rack app there is no such entry and the default falls back to Rack::Request#ip. Rack's ip returns the connecting address, REMOTE_ADDR, unless that is a trusted proxy, which by default means a loopback or private address. Only then does it read the forwarding headers, and it takes the right-most entry that is not a trusted proxy. The test suite pins both. Behind an edge on a public address, or one that appends rather than overwrites, name your edge's header instead:
ip_selector: VPNDetection::Rails.header_ip_selector("CF-Connecting-IP")VPNDetection::Rails.xff_ip_selector reads X-Forwarded-For directly, and xff_ip_selector(1) counts one trusted hop from the right. Anything else, pass your own callable: it receives the Rack request and returns an address.
Behind a proxy that writes only X-Forwarded-For, a visitor's own Forwarded header names the address. Rack 3 reads Forwarded first, for Rack::Request#ip and Rails' remote_ip alike, and nginx passes a visitor's copy through untouched, so a request sending Forwarded: for=1.1.1.1 is looked up as 1.1.1.1. Clear the header at the proxy, proxy_set_header Forwarded ""; in nginx, or tell Rack to read X-Forwarded-For alone at the top of config.ru:
Rack::Request.forwarded_priority = [:x_forwarded]The middleware warns once when a request through a proxy carries both headers. From Rails 8.1.4.1, RemoteIp itself refuses a request whose Forwarded and X-Forwarded-For name different visitors, raising ActionDispatch::RemoteIp::IpSpoofAttackError, and the middleware leaves that to Rails, as your own remote_ip call would. Puma answers it with a 500, not a 400: the address is first read above ShowExceptions, in this middleware or else in Rails' own request logging, so nothing maps the error. Clearing the header at the proxy avoids it.
If the address resolves to a private one, the middleware says so once. That is expected locally and is the signal to fix your configuration anywhere else.
When a lookup fails
The request is let through, and the reason is on lookup.error. Our outage should not become yours, so a network failure, an exhausted quota or a rejected key all fail open. Pass fail_closed: true to block instead. Private addresses are answered locally and never fail, so this will not lock you out in development.
An answer with cap_reached true is a failed lookup too, from 3.0.0. Your organization's lookups with every field are used, so the client raises :quota_exceeded and the request is let through with nothing attached but the error, and no block_condition is evaluated: the answer has only the basics, and a condition on a flag it lacks would pass every visitor. fail_closed: true refuses it, as it refuses any failed lookup. It is logged at error level, naming quota_exceeded, at most once a minute however many requests are capped, to Rails.logger, or to the logger: you pass, and to standard error in a Rack app with neither. A request that is not capped logs nothing.
Cost and latency
Answers are cached for an hour, so a returning visitor costs nothing, and private addresses never leave the process. A cache miss is one request to our API, bounded at 2.5 seconds by default and not retried: on a request path, failing open fast beats holding a visitor while we retry.
Files in public/, compiled assets included, never reach the middleware: ActionDispatch::Static answers them first, so they cost no lookup. Skip the routes you do not care about:
skip: ->(request) { request.path == "/up" || request.path.start_with?("/webhooks") }Beyond a few million distinct visitors a day, stop calling the API per request: download the dataset and look addresses up locally instead.
Absent is not false
A lookup with no key leaves out is_hosting, is_cdn, is_bot, the four proxy flags and the AS's type, and of the detail behind each flag answers only Tor's and relay's. A capped answer leaves out those and is_vpn too, but the client raises it, so it never reaches lookup.result. A member the answer does not carry is nil, which means "not in this answer" rather than "checked, and no", and a false from vpn? on an answer without is_vpn is the same: never "not a VPN". Ruby makes that easy to lose, since nil and false are both falsy.
lookup.result.hosting? # true or false, never nil
lookup.result.is_hosting # nil when your plan does not include it
lookup.result.included?(:is_hosting)A block_condition naming a member your plan does not serve can never match, so the middleware warns once instead of failing silently: a condition on is_bot, or on asn: { type: ... }, which it names as asn.type, is reported that way without a paid plan. Pass on_missing_field: :raise to make it an error.
Other Libraries
There are official VPNDetection client libraries available for many languages including PHP, Python, Go, Java, Ruby, and many popular frameworks such as Django, Rails, and Laravel. See our GitHub at https://github.com/vpndetection-io for more.
About VPNDetection
VPN Detection API: Accurate anonymity detection identifying VPNs, residential proxies, hosting servers, Tor nodes, CDNs, relays and more.
License
This project is licensed under the MIT License.