$token, 'nonce' => $parts[0] ?? '', 'ts' => $parts[1] ?? '', 'tokenField' => self::FIELD_TOKEN, 'signalsField' => self::FIELD_SIGNALS, 'purposeField' => self::FIELD_PURPOSE, 'honeypot' => self::honeypot_name(), 'purposeLabel' => self::purpose_label(), // Inject into every POST form on the page, not only forms that carry our marker. 'injectAll' => self::filter( 'agentlane_inject_all_forms', true ) ? '1' : '0', // Same-site address that swaps a cached page token for a fresh one (TokenEndpoint). 'refreshUrl' => self::ajax_url(), 'refreshAfter' => (string) self::refresh_after(), ); $cfg = self::filter( 'agentlane_signals_cfg', $cfg ); wp_localize_script( self::SCRIPT_HANDLE, 'agentlaneCfg', $cfg ); wp_enqueue_script( self::SCRIPT_HANDLE ); } /** * HTML for the hidden fields. Adapters inject this into form markup when their plugin * offers a filter; otherwise signals.js injects the same fields on the client. * * @return string */ public static function render_hidden_fields(): string { self::$instance++; $id_suffix = (string) self::$instance; $token = self::current_token(); $hp_name = self::honeypot_name(); $label = self::purpose_label(); $hidden = 'position:absolute!important;clip:rect(0 0 0 0);clip-path:inset(50%);width:1px;height:1px;overflow:hidden;white-space:nowrap;margin:-1px;'; $html = ''; $html .= ''; // Visually hidden but present in the accessibility tree on purpose: honest agents can read it. $html .= '
'; $html .= ''; $html .= ''; $html .= '
'; $html .= ''; return $html; } /** * Verify a render token. * * @param string $token Value of agentlane_t. * `issued` the token was rendered by this site (it may have travelled to another client); * `nonce_ok` the whole signature is intact: issued by this site for this client; * `valid` nonce_ok and the age is inside token_min_age .. token_max_age. * `refreshed` the first half carries the "refresh|" label: the token was minted by * TokenEndpoint for the client that asked, not rendered into a page. * It goes through exactly the same checks as a page token. * * @return array{valid: bool, age_seconds: int, nonce_ok: bool, issued: bool, refreshed: bool} */ public static function verify_token( string $token ): array { $result = array( 'valid' => false, 'age_seconds' => 0, 'nonce_ok' => false, 'issued' => false, 'refreshed' => false, ); $parts = self::parse_token( $token ); if ( null === $parts ) { return $result; } list( $nonce, $ts, $sig ) = $parts; $first = substr( $sig, 0, 32 ); $page = hash_equals( self::sign_issued( $nonce, $ts ), $first ); $refreshed = ! $page && hash_equals( self::sign_refresh( $nonce, $ts ), $first ); $issued = $page || $refreshed; $nonce_ok = $issued && hash_equals( self::sign_bound( $nonce, $ts ), substr( $sig, 32 ) ); $age = self::now() - $ts; $result['age_seconds'] = $age; $result['issued'] = $issued; $result['refreshed'] = $refreshed; $result['nonce_ok'] = $nonce_ok; $result['valid'] = $nonce_ok && $age >= self::token_min_age() && $age <= self::token_max_age(); return $result; } /** * Is this token good as a ticket for a refreshed token (TokenEndpoint)? * * Only the "issued" half is checked: a cached page was rendered for somebody else, * so the bound half cannot match the caller, and that is the case this exists for. * Accepted: a page token (label "issued|") this site signed, dated no more than * ticket_max_age() seconds ago and no more than TICKET_FUTURE_SKEW seconds ahead. * Refused: anything else, including a refreshed token (label "refresh|"), so one page * load cannot be turned into an endless chain of tokens. * * @param string $token The token embedded in the page. * @return array{ok: bool, reason: string, age_seconds: int} reason: ok, malformed, * not_issued, refreshed, expired or future. */ public static function verify_ticket( string $token ): array { $result = array( 'ok' => false, 'reason' => 'malformed', 'age_seconds' => 0, ); $parts = self::parse_token( $token ); if ( null === $parts ) { return $result; } list( $nonce, $ts, $sig ) = $parts; $first = substr( $sig, 0, 32 ); if ( ! hash_equals( self::sign_issued( $nonce, $ts ), $first ) ) { $result['reason'] = hash_equals( self::sign_refresh( $nonce, $ts ), $first ) ? 'refreshed' : 'not_issued'; return $result; } $age = self::now() - $ts; $result['age_seconds'] = $age; if ( $age < -self::TICKET_FUTURE_SKEW ) { $result['reason'] = 'future'; return $result; } if ( $age > self::ticket_max_age() ) { $result['reason'] = 'expired'; return $result; } $result['ok'] = true; $result['reason'] = 'ok'; return $result; } /** * Oldest page token (seconds) still accepted as a ticket by verify_ticket(). * Filter agentlane_ticket_max_age over DEFAULT_TICKET_MAX_AGE (30 days); never below 60. * * @return int */ public static function ticket_max_age(): int { return max( 60, (int) self::filter( 'agentlane_ticket_max_age', self::DEFAULT_TICKET_MAX_AGE ) ); } /** * Mint a refreshed token for the current client: same nonce.timestamp.signature shape * as create_token(), first half labelled "refresh|", second half bound to the caller. * * @param int|null $ts Unix timestamp; null = now. * @return string */ public static function create_refresh_token( ?int $ts = null ): string { $ts = null === $ts ? self::now() : $ts; $nonce = self::random_hex( 16 ); return $nonce . '.' . $ts . '.' . self::sign_refresh( $nonce, $ts ) . self::sign_bound( $nonce, $ts ); } /** * Seconds after which signals.js swaps the embedded page token for a fresh one. * Filter agentlane_token_refresh_after; 0 switches the whole feature off (the page * script never asks and TokenEndpoint answers 404). * * @return int */ public static function refresh_after(): int { return max( 0, (int) self::filter( 'agentlane_token_refresh_after', self::DEFAULT_REFRESH_AFTER ) ); } /** * Decode and normalize the client-side signals blob. * * The blob must carry the same token as agentlane_t (key "t" or "token"), otherwise it is * treated as missing (a replayed blob glued to a fresh token). Counters may use the short * wire keys written by signals.js or the long contract names. On success the array has * exactly the keys listed in contract 5.4; `ms_to_first_input` is -1 when the user never * typed or tapped. * * @param string $signals_raw Value of agentlane_s (base64 JSON). * @param string $token Value of agentlane_t. * @return array Normalized counters, or ['missing' => true, 'reason' => string]. */ public static function parse_signals( string $signals_raw, string $token ): array { $signals_raw = trim( $signals_raw ); if ( '' === $signals_raw ) { return array( 'missing' => true, 'reason' => 'empty' ); } if ( strlen( $signals_raw ) > self::MAX_SIGNALS_BYTES ) { return array( 'missing' => true, 'reason' => 'too_large' ); } // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- the browser blob is base64(JSON), not obfuscated code. $json = base64_decode( strtr( $signals_raw, '-_', '+/' ), true ); if ( false === $json || '' === $json ) { return array( 'missing' => true, 'reason' => 'decode' ); } $data = json_decode( $json, true ); if ( ! is_array( $data ) ) { return array( 'missing' => true, 'reason' => 'decode' ); } // signals.js writes short keys ("t", "pm", ...); long contract names are accepted too. $data = self::expand_keys( $data ); $blob_token = isset( $data['token'] ) && is_scalar( $data['token'] ) ? (string) $data['token'] : ''; if ( ! hash_equals( trim( $token ), $blob_token ) ) { return array( 'missing' => true, 'reason' => 'token_mismatch' ); } return array( 'pointer_moves' => self::int_val( $data, 'pointer_moves', 0, 1000000 ), 'touch_events' => self::int_val( $data, 'touch_events', 0, 1000000 ), 'key_events' => self::int_val( $data, 'key_events', 0, 1000000 ), 'focus_changes' => self::int_val( $data, 'focus_changes', 0, 1000000 ), 'focus_order_ok' => self::bool_val( $data, 'focus_order_ok' ), 'ms_to_first_input' => self::int_val( $data, 'ms_to_first_input', -1, 864000000 ), 'ms_to_submit' => self::int_val( $data, 'ms_to_submit', 0, 864000000 ), 'webdriver' => self::bool_val( $data, 'webdriver' ), 'headless_ua' => self::bool_val( $data, 'headless_ua' ), 'screen_w' => self::int_val( $data, 'screen_w', 0, 100000 ), 'screen_h' => self::int_val( $data, 'screen_h', 0, 100000 ), 'dpr' => self::float_val( $data, 'dpr', 0.0, 100.0 ), 'plugins_count' => self::int_val( $data, 'plugins_count', 0, 1000 ), 'languages_count' => self::int_val( $data, 'languages_count', 0, 1000 ), 'visibility_changes' => self::int_val( $data, 'visibility_changes', 0, 1000000 ), ); } /** * Map of short wire keys (signals.js) to contract names. * * @var array */ const SHORT_KEYS = array( 't' => 'token', 'pm' => 'pointer_moves', 'te' => 'touch_events', 'ke' => 'key_events', 'fc' => 'focus_changes', 'fo' => 'focus_order_ok', 'fi' => 'ms_to_first_input', 'su' => 'ms_to_submit', 'wd' => 'webdriver', 'hu' => 'headless_ua', 'sw' => 'screen_w', 'sh' => 'screen_h', 'dp' => 'dpr', 'pc' => 'plugins_count', 'lc' => 'languages_count', 'vc' => 'visibility_changes', ); /** * Copy short keys onto their long names (long names win when both are present). * * @param array $data Decoded JSON. * @return array */ protected static function expand_keys( array $data ): array { foreach ( self::SHORT_KEYS as $short => $long ) { if ( array_key_exists( $short, $data ) && ! array_key_exists( $long, $data ) ) { $data[ $long ] = $data[ $short ]; } } return $data; } /** * Server-side request signals. * * Notes: * - `direct_post`: POST without Sec-Fetch-Site, or with Sec-Fetch-Site: none. Old browsers * (Safari before 16.4) never send Sec-Fetch headers, so this stays a weak signal. * - `missing_sec_ch_ua`: Chrome only sends Sec-CH-UA over HTTPS, so the flag is false on * plain HTTP sites. `ua_chromium` (extra key) tells the scorer whether the UA claims Chrome. * - `ip_is_datacenter`: IPv4 only; the bundled list is a best-effort aggregate. * * @param RequestContext $ctx Request context built by WP1. * @return array */ public static function server_signals( RequestContext $ctx ): array { $method = strtoupper( (string) ( $ctx->method ?? '' ) ); $ua = (string) ( $ctx->ua ?? '' ); $sec_fetch_site = isset( $ctx->sec_fetch_site ) ? strtolower( trim( (string) $ctx->sec_fetch_site ) ) : ''; $sec_ch_ua = isset( $ctx->sec_ch_ua ) ? trim( (string) $ctx->sec_ch_ua ) : ''; $accept_language = isset( $ctx->accept_language ) ? trim( (string) $ctx->accept_language ) : ''; $ip_full = (string) ( $ctx->ip_full ?? '' ); $ip = '' !== $ip_full ? $ip_full : (string) ( $ctx->ip ?? '' ); return array( 'direct_post' => ( 'POST' === $method ) && ( '' === $sec_fetch_site || 'none' === $sec_fetch_site ), 'missing_sec_ch_ua' => ( '' === $sec_ch_ua ) && self::is_https( $ctx ), 'missing_accept_language' => '' === $accept_language, 'ua_is_known_bot' => self::ua_is_known_bot( $ua ), 'ua_headless' => self::ua_headless( $ua ), 'ua_chromium' => (bool) preg_match( '/\bChrome\/\d|\bChromium\/\d|\bCriOS\/\d/', $ua ), 'no_cookies' => empty( $ctx->has_cookies ), 'origin_mismatch' => self::origin_mismatch( $ctx ), 'ip_is_datacenter' => self::ip_is_datacenter( $ip ), 'ip_is_private' => self::ip_is_private( $ip ), ); } /* --------------------------------------------------------------------- * Public helpers (not in the contract, useful for adapters and tests) * ------------------------------------------------------------------ */ /** * Create a fresh token for the current time (or a given timestamp). * * @param int|null $ts Unix timestamp; null = now. * @return string */ public static function create_token( ?int $ts = null ): string { $ts = null === $ts ? self::now() : $ts; $nonce = self::random_hex( 16 ); return $nonce . '.' . $ts . '.' . self::sign( $nonce, $ts ); } /** * Field names the adapters read from $_POST. * * @return array{token: string, signals: string, purpose: string, honeypot: string} */ public static function field_names(): array { return array( 'token' => self::FIELD_TOKEN, 'signals' => self::FIELD_SIGNALS, 'purpose' => self::FIELD_PURPOSE, 'honeypot' => self::honeypot_name(), ); } /** * Is the IPv4/IPv6 address inside the bundled datacenter list? * * @param string $ip IP address (full or truncated). * @return bool */ public static function ip_is_datacenter( string $ip ): bool { $long = self::ipv4_to_long( $ip ); if ( null === $long ) { return false; // IPv6 or malformed: no IPv6 ranges bundled in v1. } $index = self::cidr_index(); $octet = $long >> 24; if ( empty( $index[ $octet ] ) ) { return false; } foreach ( $index[ $octet ] as $range ) { if ( ( $long & $range[1] ) === $range[0] ) { return true; } } return false; } /** * Is the address private, loopback, link-local or CGNAT? * * @param string $ip IP address. * @return bool */ public static function ip_is_private( string $ip ): bool { $ip = trim( $ip ); if ( '' === $ip ) { return false; } $long = self::ipv4_to_long( $ip ); if ( null !== $long ) { foreach ( self::PRIVATE_CIDRS as $cidr ) { $range = self::parse_cidr( $cidr ); if ( null !== $range && ( $long & $range[1] ) === $range[0] ) { return true; } } return false; } if ( false === strpos( $ip, ':' ) || false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) { return false; } $bin = inet_pton( $ip ); if ( false === $bin || 16 !== strlen( $bin ) ) { return false; } // ::1 loopback, :: unspecified. if ( str_repeat( "\0", 15 ) . "\x01" === $bin || str_repeat( "\0", 16 ) === $bin ) { return true; } // ::ffff:a.b.c.d (IPv4-mapped): check the IPv4 part. if ( str_repeat( "\0", 10 ) . "\xff\xff" === substr( $bin, 0, 12 ) ) { $mapped = unpack( 'N', substr( $bin, 12, 4 ) ); return self::ip_is_private( long2ip( (int) $mapped[1] ) ); } $b0 = ord( $bin[0] ); $b1 = ord( $bin[1] ); if ( 0xfc === ( $b0 & 0xfe ) ) { return true; // fc00::/7 unique local. } if ( 0xfe === $b0 && 0x80 === ( $b1 & 0xc0 ) ) { return true; // fe80::/10 link local. } return false; } /* --------------------------------------------------------------------- * Token internals * ------------------------------------------------------------------ */ /** * Token signature: the "issued by this site" half followed by the "for this client" half. * * @param string $nonce 16 hex chars. * @param int $ts Unix timestamp. * @return string 64 hex chars. */ protected static function sign( string $nonce, int $ts ): string { return self::sign_issued( $nonce, $ts ) . self::sign_bound( $nonce, $ts ); } /** * First half: HMAC-SHA256 over "issued|" nonce|timestamp|site_salt, cut to 32 hex chars. * It does not depend on the client, so it still verifies when the visitor's address * changed between page load and submit, and it never verifies for a made-up token. * * @param string $nonce 16 hex chars. * @param int $ts Unix timestamp. * @return string 32 hex chars. */ protected static function sign_issued( string $nonce, int $ts ): string { return substr( hash_hmac( 'sha256', 'issued|' . $nonce . '|' . $ts . '|' . self::site_salt(), self::salt() ), 0, 32 ); } /** * First half of a refreshed token: like sign_issued() with the label "refresh|", so * the server can tell a token it minted for a caller from one rendered into a page. * * @param string $nonce 16 hex chars. * @param int $ts Unix timestamp. * @return string 32 hex chars. */ protected static function sign_refresh( string $nonce, int $ts ): string { return substr( hash_hmac( 'sha256', 'refresh|' . $nonce . '|' . $ts . '|' . self::site_salt(), self::salt() ), 0, 32 ); } /** * Split a token into [nonce, timestamp, signature] when it has the wire format. * * @param string $token Token. * @return array{0: string, 1: int, 2: string}|null */ protected static function parse_token( string $token ): ?array { $token = trim( $token ); if ( '' === $token || strlen( $token ) > 120 ) { return null; } $parts = explode( '.', $token ); if ( 3 !== count( $parts ) ) { return null; } list( $nonce, $ts, $sig ) = $parts; if ( ! preg_match( '/^[a-f0-9]{16}$/', $nonce ) || ! preg_match( '/^[0-9]{9,11}$/', $ts ) || ! preg_match( '/^[a-f0-9]{64}$/', $sig ) ) { return null; } return array( $nonce, (int) $ts, $sig ); } /** * Second half: HMAC-SHA256 over nonce|timestamp|binding|site_salt, cut to 32 hex chars. * * `binding` is the coarse client fingerprint from client_binding() ('' when the * setting bind_token_to_client is off or the filter agentlane_token_binding * empties it), so a token rendered for one visitor does not fully verify for another. * * @param string $nonce 16 hex chars. * @param int $ts Unix timestamp. * @return string 32 hex chars. */ protected static function sign_bound( string $nonce, int $ts ): string { return substr( hash_hmac( 'sha256', $nonce . '|' . $ts . '|' . self::client_binding() . '|' . self::site_salt(), self::salt() ), 0, 32 ); } /** * Coarse fingerprint of the client a token is tied to: the first two octets of the * IPv4 address (first 32 bits for IPv6) plus the browser family. Coarse on purpose: * it survives address changes inside a provider and minor browser updates, but a * token copied to another network or another browser family stops verifying. * * Empty when the setting bind_token_to_client is off. The filter * agentlane_token_binding lets a site behind a full-page cache return '' (a cached * page hands the same token to every visitor). * * @param RequestContext|null $ctx Request to bind to; null = the current request. * @return string '' or "prefix|family". */ public static function client_binding( ?RequestContext $ctx = null ): string { $binding = ''; if ( (bool) self::setting( 'bind_token_to_client', true ) ) { if ( null === $ctx && class_exists( __NAMESPACE__ . '\\RequestContext' ) ) { $ctx = RequestContext::from_globals(); } if ( null !== $ctx ) { $binding = self::ip_prefix( (string) $ctx->ip ) . '|' . self::ua_family( (string) $ctx->ua ); } } return (string) self::filter( 'agentlane_token_binding', $binding ); } /** * First two octets of an IPv4 address ("81.2") or the first 32 bits of IPv6 as hex. * * @param string $ip IP address (truncated or full). * @return string '' when the address is not valid. */ public static function ip_prefix( string $ip ): string { if ( false !== filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { $parts = explode( '.', $ip ); return $parts[0] . '.' . $parts[1]; } if ( false !== filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) { $bin = inet_pton( $ip ); return ( false === $bin || 16 !== strlen( $bin ) ) ? '' : bin2hex( substr( $bin, 0, 4 ) ); } return ''; } /** * Browser family from the User-Agent: edge, opera, firefox, chrome, safari, ie, * none (empty UA) or other. Order matters: Edge and Opera carry "Chrome", Chrome * carries "Safari". * * @param string $ua User-Agent header. * @return string */ public static function ua_family( string $ua ): string { $ua = strtolower( trim( $ua ) ); if ( '' === $ua ) { return 'none'; } if ( preg_match( '/\\bedg(?:e|a|ios)?\\//', $ua ) ) { return 'edge'; } if ( false !== strpos( $ua, 'opr/' ) || false !== strpos( $ua, 'opera' ) ) { return 'opera'; } if ( false !== strpos( $ua, 'firefox' ) || false !== strpos( $ua, 'fxios' ) ) { return 'firefox'; } if ( false !== strpos( $ua, 'chrome' ) || false !== strpos( $ua, 'crios' ) || false !== strpos( $ua, 'chromium' ) ) { return 'chrome'; } if ( false !== strpos( $ua, 'safari' ) ) { return 'safari'; } if ( false !== strpos( $ua, 'msie' ) || false !== strpos( $ua, 'trident' ) ) { return 'ie'; } return 'other'; } /** * Token shared by all fields rendered in this request. * * @return string */ protected static function current_token(): string { if ( null === self::$current_token ) { self::$current_token = self::create_token(); } return self::$current_token; } /** * Random lowercase hex string. * * @param int $length Number of hex chars (even). * @return string */ protected static function random_hex( int $length ): string { try { return substr( bin2hex( random_bytes( (int) ceil( $length / 2 ) ) ), 0, $length ); } catch ( \Exception $e ) { // No system CSPRNG (does not happen on a normal PHP 7.4+ build): fall back to // WordPress' own generator, or to the clock when the class runs without WordPress. $seed = function_exists( 'wp_rand' ) ? (string) wp_rand() : (string) microtime( true ); return substr( hash( 'sha256', uniqid( $seed, true ) ), 0, $length ); } } /* --------------------------------------------------------------------- * Server signal internals * ------------------------------------------------------------------ */ /** * Generic bot / HTTP-library markers in the User-Agent (the detailed agent directory * lives in WP3; this is only the coarse flag from contract 5.4). Empty UA counts as bot. * * @param string $ua User-Agent. * @return bool */ protected static function ua_is_known_bot( string $ua ): bool { $ua = trim( $ua ); if ( '' === $ua ) { return true; } $pattern = '/bot|crawl|spider|slurp|scrap|fetch|curl\/|wget|python|java\/|go-http-client|libwww|httpclient|okhttp|axios|node-fetch|undici|postman|insomnia|guzzle|php\/|perl|lwp-|httpie|aiohttp|headless|phantom|puppeteer|playwright|selenium|chatgpt|claude|perplexity|anthropic|openai/i'; return (bool) preg_match( $pattern, $ua ); } /** * Headless browser markers in the User-Agent. * * @param string $ua User-Agent. * @return bool */ protected static function ua_headless( string $ua ): bool { return (bool) preg_match( '/HeadlessChrome|PhantomJS|Puppeteer|Playwright|Selenium|SlimerJS|CasperJS|HtmlUnit/i', $ua ); } /** * Origin (or Referer when Origin is absent) points to another host than this site. * * @param RequestContext $ctx Request context. * @return bool */ protected static function origin_mismatch( RequestContext $ctx ): bool { $candidate = isset( $ctx->origin ) ? trim( (string) $ctx->origin ) : ''; if ( '' === $candidate ) { $candidate = isset( $ctx->referer ) ? trim( (string) $ctx->referer ) : ''; } if ( '' === $candidate ) { return false; // Nothing to compare; direct_post covers this case. } if ( 'null' === strtolower( $candidate ) ) { return true; } $site_host = self::site_host( $ctx ); if ( '' === $site_host ) { return false; } // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- pure PHP class, unit-tested without WordPress. $host = parse_url( $candidate, PHP_URL_HOST ); if ( ! is_string( $host ) || '' === $host ) { return true; } return self::norm_host( $host ) !== self::norm_host( $site_host ); } /** * Host of this site: home_url() when WordPress is loaded, else the Host header. * * @param RequestContext $ctx Request context. * @return string */ protected static function site_host( RequestContext $ctx ): string { if ( function_exists( 'home_url' ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- pure PHP class, unit-tested without WordPress. $host = parse_url( (string) home_url( '/' ), PHP_URL_HOST ); if ( is_string( $host ) && '' !== $host ) { return $host; } } $headers = isset( $ctx->headers ) && is_array( $ctx->headers ) ? $ctx->headers : array(); if ( isset( $headers['host'] ) && is_string( $headers['host'] ) ) { return $headers['host']; } if ( defined( 'AGENTLANE_TEST_HOST' ) ) { return (string) AGENTLANE_TEST_HOST; } return ''; } /** * Lowercase host without port and without a leading "www.". * * @param string $host Host name. * @return string */ protected static function norm_host( string $host ): string { $host = strtolower( trim( $host ) ); $host = (string) preg_replace( '/:\d+$/', '', $host ); if ( 0 === strpos( $host, 'www.' ) ) { $host = (string) substr( $host, 4 ); } return $host; } /** * Was the request made over HTTPS? Uses is_ssl() under WordPress; otherwise the * X-Forwarded-Proto header from the context; when nothing says otherwise (CLI tests) * assumes HTTPS so the Sec-CH-UA signal is observable in tests. * * @param RequestContext $ctx Request context. * @return bool */ protected static function is_https( RequestContext $ctx ): bool { if ( function_exists( 'is_ssl' ) ) { return (bool) is_ssl(); } if ( isset( $ctx->headers['x-forwarded-proto'] ) ) { return 'https' === strtolower( (string) $ctx->headers['x-forwarded-proto'] ); } return true; } /* --------------------------------------------------------------------- * CIDR internals (64-bit PHP assumed; ip2long is positive there) * ------------------------------------------------------------------ */ /** * Dotted IPv4 to unsigned int; null for anything else. * * @param string $ip IP address. * @return int|null */ protected static function ipv4_to_long( string $ip ): ?int { $ip = trim( $ip ); if ( '' === $ip || ! filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ) { return null; } $long = ip2long( $ip ); if ( false === $long ) { return null; } return $long & 0xFFFFFFFF; } /** * "a.b.c.d/n" to [network, mask]; null when malformed. * * @param string $cidr CIDR notation. * @return array{0:int,1:int}|null */ protected static function parse_cidr( string $cidr ): ?array { $pos = strpos( $cidr, '/' ); if ( false === $pos ) { return null; } $net = substr( $cidr, 0, $pos ); $bits = (int) substr( $cidr, $pos + 1 ); $long = self::ipv4_to_long( $net ); if ( null === $long || $bits < 0 || $bits > 32 ) { return null; } $mask = 0 === $bits ? 0 : ( ( 0xFFFFFFFF << ( 32 - $bits ) ) & 0xFFFFFFFF ); return array( $long & $mask, $mask ); } /** * Datacenter list pre-parsed and bucketed by first octet (built once per request). * * @return array> */ protected static function cidr_index(): array { static $index = null; if ( null !== $index ) { return $index; } $index = array(); foreach ( self::DATACENTER_CIDRS as $cidr ) { $range = self::parse_cidr( $cidr ); if ( null === $range ) { continue; } $start = $range[0]; $end = $range[0] | ( ~$range[1] & 0xFFFFFFFF ); for ( $octet = $start >> 24; $octet <= ( $end >> 24 ); $octet++ ) { $index[ $octet ][] = $range; } } return $index; } /* --------------------------------------------------------------------- * Normalization helpers * ------------------------------------------------------------------ */ /** * Clamped integer from the decoded blob. * * @param array $data Decoded JSON. * @param string $key Short key. * @param int $min Lower bound. * @param int $max Upper bound. * @return int */ protected static function int_val( array $data, string $key, int $min, int $max ): int { if ( ! isset( $data[ $key ] ) || ! is_numeric( $data[ $key ] ) ) { return $min < 0 ? -1 : 0; } $v = (int) $data[ $key ]; return max( $min, min( $max, $v ) ); } /** * Clamped float from the decoded blob. * * @param array $data Decoded JSON. * @param string $key Short key. * @param float $min Lower bound. * @param float $max Upper bound. * @return float */ protected static function float_val( array $data, string $key, float $min, float $max ): float { if ( ! isset( $data[ $key ] ) || ! is_numeric( $data[ $key ] ) ) { return 0.0; } $v = (float) $data[ $key ]; return max( $min, min( $max, $v ) ); } /** * Boolean from the decoded blob (accepts 1/0, true/false, "1"/"0"). * * @param array $data Decoded JSON. * @param string $key Short key. * @return bool */ protected static function bool_val( array $data, string $key ): bool { if ( ! isset( $data[ $key ] ) ) { return false; } $v = $data[ $key ]; if ( is_bool( $v ) ) { return $v; } if ( is_numeric( $v ) ) { return 0 !== (int) $v; } return 'true' === strtolower( (string) $v ); } /* --------------------------------------------------------------------- * WordPress wrappers with plain-PHP fallbacks (tests run without WP) * ------------------------------------------------------------------ */ /** * HMAC key: wp_salt('nonce'), or a test constant, or a random secret of this process. * The last fallback is unreachable under WordPress; it is random so that no code path * can ever sign with a public string (a token from it only verifies in this process). * * @return string */ protected static function salt(): string { static $process_secret = ''; if ( function_exists( 'wp_salt' ) ) { return (string) wp_salt( 'nonce' ); } if ( defined( 'AGENTLANE_TEST_SALT' ) ) { return (string) AGENTLANE_TEST_SALT; } if ( '' === $process_secret ) { $process_secret = bin2hex( random_bytes( 32 ) ); } return $process_secret; } /** * Site salt inside the signed message. Contract 5.4 says "nonce|timestamp|site_salt" with * wp_salt('nonce') as the key; the site salt is that same wp_salt('nonce') value (this is * also what tests/bootstrap.php assumes). Kept as a separate method so a later version can * bind tokens to one site of a multisite network without touching sign(). * * @return string */ protected static function site_salt(): string { return self::salt(); } /** * Current unix time (overridable via self::$now in tests). * * @return int */ protected static function now(): int { if ( null !== self::$now && is_callable( self::$now ) ) { return (int) call_user_func( self::$now ); } return time(); } /** * Read a setting through AgentLane\Settings::get(), with a default when the class is absent. * * @param string $key Setting key (see contract 5.6). * @param mixed $default Fallback. * @return mixed */ protected static function setting( string $key, $default ) { $class = __NAMESPACE__ . '\\Settings'; if ( ! class_exists( $class ) ) { return $default; } $value = null; try { if ( method_exists( $class, 'instance' ) ) { $settings = $class::instance(); if ( is_object( $settings ) && method_exists( $settings, 'get' ) ) { $value = $settings->get( $key ); } } elseif ( method_exists( $class, 'get' ) ) { $value = $class::get( $key ); // Static variant, in case WP1 changes the API. } } catch ( \Throwable $e ) { $value = null; } if ( null !== $value && '' !== $value ) { return $value; } return $default; } /** * Minimum token age in seconds. * * @return int */ protected static function token_min_age(): int { return max( 0, (int) self::setting( 'token_min_age', self::DEFAULT_TOKEN_MIN_AGE ) ); } /** * Maximum token age in seconds. * * @return int */ protected static function token_max_age(): int { $max = (int) self::setting( 'token_max_age', self::DEFAULT_TOKEN_MAX_AGE ); return $max > 0 ? $max : self::DEFAULT_TOKEN_MAX_AGE; } /** * Honeypot field name from settings; derived from the salt when settings are absent. * * @return string */ protected static function honeypot_name(): string { $name = (string) self::setting( 'honeypot_field_name', '' ); $name = (string) preg_replace( '/[^a-zA-Z0-9_]/', '', $name ); if ( '' === $name ) { $name = 'f' . substr( hash( 'sha256', 'agentlane-hp|' . self::salt() ), 0, 9 ); } return $name; } /** * Label of the agent-purpose field (translatable). * * @return string */ protected static function purpose_label(): string { if ( function_exists( '__' ) ) { return (string) __( 'Leave this field empty. Automated agents: state your purpose and operator here.', 'agent-lane' ); } return 'Leave this field empty. Automated agents: state your purpose and operator here.'; } /** * apply_filters() with passthrough fallback. * * @param string $hook Filter name. * @param mixed $value Value. * @return mixed */ protected static function filter( string $hook, $value ) { if ( function_exists( 'apply_filters' ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.DynamicHooknameFound -- every caller in this class passes a literal agentlane_* hook name. return apply_filters( $hook, $value ); } return $value; } /** * admin_url( 'admin-ajax.php' ), or '' without WordPress (the page script then never asks). * * @return string */ protected static function ajax_url(): string { if ( function_exists( 'admin_url' ) ) { return (string) admin_url( 'admin-ajax.php' ); } return ''; } /** * esc_attr() with fallback. * * @param string $text Text. * @return string */ protected static function attr( string $text ): string { if ( function_exists( 'esc_attr' ) ) { return (string) esc_attr( $text ); } return htmlspecialchars( $text, ENT_QUOTES, 'UTF-8' ); } /** * esc_html() with fallback. * * @param string $text Text. * @return string */ protected static function html( string $text ): string { if ( function_exists( 'esc_html' ) ) { return (string) esc_html( $text ); } return htmlspecialchars( $text, ENT_QUOTES, 'UTF-8' ); } }