http/proxy.ts

Trusted proxy configuration and middleware.

Resolves the client IP from X-Forwarded-For only when the TCP connection originates from a configured trusted proxy. Without this middleware, get_client_ip returns 'unknown'.

view source

Declarations
#

9 declarations

create_proxy_middleware
#

http/proxy.ts view source

(options: ProxyOptions): MiddlewareHandler import {create_proxy_middleware} from '@fuzdev/fuz_app/http/proxy.js';

Create a Hono middleware that resolves the client IP from trusted proxies.

Sets client_ip on the Hono context for downstream use by get_client_ip. All client IPs are normalized (lowercase, IPv4-mapped IPv6 stripped).

Resolution logic:

  1. No X-Forwarded-For → use connection IP directly.
  2. X-Forwarded-For present but connection is untrusted → ignore header (spoofed by a direct attacker), use connection IP.
  3. X-Forwarded-For present and connection is trusted → walk header right-to-left, strip trusted entries, use first untrusted entry; a malformed entry stops the walk and the connection IP is used.

options

trusted proxy configuration

returns

MiddlewareHandler

throws

  • Error - if any entry in `options.trusted_proxies` is invalid (parsed eagerly via `parse_proxy_entry`)

mutates

  • c.var.client_ip — set to the resolved (or `'unknown'`) client IP per request

create_proxy_middleware_spec
#

http/proxy.ts view source

(options: ProxyOptions): MiddlewareSpec import {create_proxy_middleware_spec} from '@fuzdev/fuz_app/http/proxy.js';

Create a middleware spec for trusted proxy resolution.

Apply before auth middleware so client_ip is available for rate limiting.

options

trusted proxy configuration

returns

MiddlewareSpec

is_trusted_ip
#

http/proxy.ts view source

(ip: string, proxies: ParsedProxy[]): boolean import {is_trusted_ip} from '@fuzdev/fuz_app/http/proxy.js';

Check whether ip matches any entry in the trusted proxy list.

Normalizes ip before matching (lowercase, IPv4-mapped IPv6 stripped). Uses validate_ip_strict to reject malformed input — without strict validation, Hono's lax distinctRemoteAddr would let an entry like '203.0.113.1:8080' (false-positive 'IPv6') reach convertIPv6ToBinary in the CIDR-match branch and throw.

ip

type string

proxies

returns

boolean

normalize_ip
#

http/proxy.ts view source

(ip: string): string import {normalize_ip} from '@fuzdev/fuz_app/http/proxy.js';

Normalize an IP address for consistent matching and storage.

Delegates to canonicalize_ip from http/ip_canonical.ts — collapses RFC 5952-equivalent IPv6 forms (::1, ::0001, 0:0:0:0:0:0:0:1) into a single key, emits IPv4-mapped IPv6 in dotted form, and strips the ::ffff: prefix from dotted IPv4-mapped values so the bucket collapses to plain IPv4.

  • Lowercases for case-insensitive IPv6 comparison.
  • Idempotent: calling twice produces the same result.
  • Safe on non-IP strings: normalize_ip('unknown') returns 'unknown'. Malformed inputs ('attacker:controlled', '::1\n', '203.0.113.1:8080') pass through unchanged so downstream validate_ip_strict can still reject them — canonicalization never erases the malformed-form signal.

ip

type string

returns

string

parse_proxy_entry
#

http/proxy.ts view source

(entry: string): ParsedProxy import {parse_proxy_entry} from '@fuzdev/fuz_app/http/proxy.js';

Parse a trusted proxy entry string into a structured form.

Accepts plain IPs ('127.0.0.1', '::1') and CIDR notation ('10.0.0.0/8', 'fe80::/10'). Plain IPs are normalized (lowercase, IPv4-mapped IPv6 stripped) and validated. CIDR prefixes are validated against address family bounds. A /0 prefix is refused for either family: it trusts every client as a proxy, so the client's own X-Forwarded-For would choose the IP every per-IP limiter keys on.

entry

IP address or CIDR notation

type string

returns

ParsedProxy

throws

  • Error - on invalid IP, invalid CIDR network, NaN/negative/over-range prefix, or a `/0` prefix

ParsedProxy
#

http/proxy.ts view source

ParsedProxy

type { type: "ip"; address: string; } | { type: "cidr"; network: bigint; prefix: number; address_type: "IPv4" | "IPv6"; }

import type {ParsedProxy} from '@fuzdev/fuz_app/http/proxy.js';

A parsed proxy entry — either an exact IP or a CIDR range.

ProxyOptions
#

http/proxy.ts view source

ProxyOptions import type {ProxyOptions} from '@fuzdev/fuz_app/http/proxy.js';

Configuration for trusted proxy resolution.

trusted_proxies

Trusted proxy IPs or CIDR ranges (e.g. '127.0.0.1', '10.0.0.0/8', '::1').

type string[]

get_connection_ip

Extract the raw TCP connection IP from the Hono context.

type (c: Context<any, any, {}>): string | undefined

c

type Context<any, any, {}>
returns string | undefined

log?

Optional logger for proxy resolution diagnostics.

type Logger

resolve_client_ip
#

http/proxy.ts view source

(forwarded_for: string, proxies: ParsedProxy[]): string | undefined import {resolve_client_ip} from '@fuzdev/fuz_app/http/proxy.js';

Resolve the real client IP from an X-Forwarded-For header value.

Walks right-to-left, skipping trusted proxy entries. The first untrusted entry is the client IP. The walk stops at the first entry that fails strict IP validation (validate_ip_strict) and returns undefined, so the middleware falls back to the connection IP: an entry is only as trustworthy as the hop that wrote it, and everything left of a malformed one was written before any trusted hop vouched for it. If every entry is trusted, returns the leftmost one (likely-misconfigured all-trusted case). Empty entries are dropped before the walk. All entries are normalized before matching and in the returned value.

Stopping, not skipping, is the rate-limit-key rule. Returning a malformed entry would let an attacker rotate arbitrary strings (incl. 'attacker:controlled', which Hono's lax distinctRemoteAddr misclassifies as IPv6) into fresh per-IP rate-limit buckets; skipping it and walking on would hand the key to the entry the client wrote whenever a trusted hop appends a non-bare-IP token (ip:port, [v6]:port, unknown, unix:). Tradeoff: behind such a proxy every client collapses to the proxy's connection IP in rate limiting (one bucket for everyone behind it). Standard proxies (nginx's $remote_addr, cloud LBs) append bare IPs.

forwarded_for

the X-Forwarded-For header value

type string

proxies

parsed trusted proxy entries

returns

string | undefined

the normalized client IP, or undefined if the header is empty or the walk met a malformed entry

validate_ip_strict
#

http/proxy.ts view source

(ip: string): "IPv4" | "IPv6" | undefined import {validate_ip_strict} from '@fuzdev/fuz_app/http/proxy.js';

Strict IP validity check.

Defense in depth around Hono's hono/utils/ipaddr helpers, which are lax in two ways:

  1. distinctRemoteAddr classifies anything-with-a-colon as 'IPv6', including 'host:port', 'attacker:controlled', '203.0.113.1:8080'.
  2. convertIPv6ToBinary silently accepts malformed forms like '[::1]:8080' and '::1\n', parsing them as inconsistent binary values that would still serve as distinct rate-limit keys for an attacker rotating the suffix.

Strict validation here is two-layered: a character-set pre-filter (IP_LITERAL_CHARS), then a round-trip through convertIPv*ToBinary to confirm the input parses cleanly. Either layer alone has holes; together they reject every input form we've seen Hono mis-handle.

Used as the security primitive for any code path that takes an IP string from an untrusted source (XFF, query params) and uses it as a key (rate limiting, audit subject) or compares it against trusted proxies via CIDR (where the latent throw would otherwise bubble out).

ip

type string

returns

"IPv4" | "IPv6" | undefined

the address family on success, undefined if the string is not a strictly-valid IP

Depends on
#

Imported by
#