jns-cloudflare
v1.0.1
Published
Cloudflare proxy support for JNS.
Maintainers
Readme
jns-cloudflare
Cloudflare proxy support for @jnode/server.
Installation
npm i jns-cloudflareQuick start
Import
const { createServer, routerConstructors: r, handlerConstructors: h } = require('@jnode/server');
const { routerConstructors: cf } = require('jns-cloudflare');Trusting Cloudflare proxies
const server = createServer(
// The CloudflareProxy router verifies if the request comes from Cloudflare
cf.CloudflareProxy(
// Match: The request is from Cloudflare.
// ctx.identity.address is now the real client IP.
r.Path(h.Text('Hello real user!')),
// Fail: The request is NOT from Cloudflare.
// We might want to block direct access or handle it differently.
h.Text('Direct access not allowed', { statusCode: 403 })
)
);
server.listen(8080);How it works?
Cloudflare acts as a reverse proxy, meaning your server sees Cloudflare's IP addresses instead of the actual visitor's IP.
jns-cloudflare solves this by:
- Fetching Trusted IPs: Automatically fetches the latest list of official Cloudflare IP ranges (IPv4 and IPv6) on startup.
- Verification: Compares the incoming request's remote address against these trusted ranges.
- Identity Restoration: If the IP is verified, it extracts the real visitor's IP from the
CF-Connecting-IPheader and updatesctx.identity.address. - Geo-data Enrichment: It also populates
ctx.identity.countryandctx.identity.continentbased on Cloudflare's headers.
Reference
Router: CloudflareProxy(next, fail)
nextrouter | handler-extended The next step to execute if the request is confirmed to be routed through Cloudflare.failrouter | handler-extended The step to execute if the request remote address does not match Cloudflare's IP ranges.
Identity Enrichment
When a request passes through the next path, the following properties are guaranteed/updated in ctx.identity:
address<string>: Updated to the value of theCF-Connecting-IPheader.country<string>: Two-letter country code (ISO 3166-1 alpha-2) fromCF-IPCountry.continent<string>: Continent code fromCF-IPContinent.
Automatic Updates
The router automatically initiates an asynchronous fetch of Cloudflare's IP list upon initialization. If the network request fails, it falls back to a built-in list of known Cloudflare IP ranges to ensure the server remains functional.
