string, 'weight' => int, 'detail' => string]. * * @var array */ public array $reasons = array(); /** * One of the ACTION_* constants. Empty until Policy::decide() runs. * * @var string */ public string $action = ''; /** * Display name from the agent directory or the Signature-Agent host. * * @var string|null */ public ?string $agent_name = null; /** * Free-form extra data (agent_id, raw_score, text_hash, wba result ...). * * @var array */ public array $meta = array(); /** * All valid class names. * * @return string[] */ public static function classes(): array { return array( self::CLASS_HUMAN, self::CLASS_AGENT_DECLARED, self::CLASS_AGENT_VERIFIED, self::CLASS_AGENT_SUSPECTED, self::CLASS_BOT, ); } /** * All valid actions. * * @return string[] */ public static function actions(): array { return array( self::ACTION_ALLOW, self::ACTION_QUEUE, self::ACTION_BLOCK ); } /** * Append a reason. * * @param string $code Machine code, e.g. 'honeypot_filled'. * @param int $weight Points added to the score (0 for informational). * @param string $detail Human-readable explanation. */ public function add_reason( string $code, int $weight, string $detail ): void { $this->reasons[] = array( 'code' => $code, 'weight' => $weight, 'detail' => $detail, ); } /** * Whether a reason with this code was recorded. * * @param string $code Reason code. * @return bool */ public function has_reason( string $code ): bool { foreach ( $this->reasons as $reason ) { if ( isset( $reason['code'] ) && $reason['code'] === $code ) { return true; } } return false; } /** * Sum of all reason weights, uncapped. * * @return int */ public function weight_sum(): int { $sum = 0; foreach ( $this->reasons as $reason ) { $sum += isset( $reason['weight'] ) ? (int) $reason['weight'] : 0; } return $sum; } /** * Sort reasons by weight, heaviest first. Stable for equal weights. */ public function sort_reasons(): void { $indexed = array(); foreach ( $this->reasons as $i => $reason ) { $indexed[] = array( $i, $reason ); } usort( $indexed, static function ( array $a, array $b ): int { $wa = isset( $a[1]['weight'] ) ? (int) $a[1]['weight'] : 0; $wb = isset( $b[1]['weight'] ) ? (int) $b[1]['weight'] : 0; if ( $wa === $wb ) { return $a[0] <=> $b[0]; } return $wb <=> $wa; } ); $sorted = array(); foreach ( $indexed as $pair ) { $sorted[] = $pair[1]; } $this->reasons = $sorted; } /** * Heaviest N reasons (for the admin list "top 3 reasons"). * * @param int $limit How many. * @return array */ public function top_reasons( int $limit = 3 ): array { $copy = clone $this; $copy->sort_reasons(); return array_slice( $copy->reasons, 0, max( 0, $limit ) ); } /** * True for the three agent classes. * * @return bool */ public function is_agent(): bool { return in_array( $this->class, array( self::CLASS_AGENT_DECLARED, self::CLASS_AGENT_VERIFIED, self::CLASS_AGENT_SUSPECTED ), true ); } /** * Plain array (for JSON storage in the queue table). * * @return array */ public function to_array(): array { return array( 'class' => $this->class, 'score' => $this->score, 'reasons' => $this->reasons, 'action' => $this->action, 'agent_name' => $this->agent_name, 'meta' => $this->meta, ); } } /** * Combines request signals into a Verdict. Weighted additive model, cap 100. * * Section 5.7. Weights are class constants so they can be tuned in one place. */ class Scorer { // Weights (section 5.7). const W_HONEYPOT_FILLED = 60; const W_TOKEN_MISSING = 35; const W_TOKEN_INVALID = 35; // Same weight as missing: a forged or stale token is no better. const W_TOKEN_TOO_YOUNG = 30; const W_SIGNALS_MISSING = 25; const W_NO_POINTER_BEFORE_TYPING = 25; const W_NO_INTERACTION = 20; // Addition: script ran but zero pointer, touch and key events. const W_WEBDRIVER = 40; const W_HEADLESS_UA = 40; const W_DIRECT_POST = 20; const W_MISSING_SEC_CH_UA = 15; const W_MISSING_ACCEPT_LANGUAGE = 10; const W_NO_COOKIES = 5; const W_DATACENTER_IP = 15; const W_KNOWN_AGENT_UA = 50; const W_MANY_URLS = 15; const W_DUPLICATE_TEXT = 20; const W_TOO_FAST = 30; const W_SIGNALS_INCONSISTENT = 20; // Addition: browser counters contradict the server-side token facts. const W_TOKEN_REUSED = 35; // Addition (0.2.0): one page load used for more submissions than allowed. // Fixed scores for honest agents. const SCORE_AGENT_VERIFIED = 50; const SCORE_AGENT_DECLARED = 50; const SCORE_CAP = 100; const FAST_SUBMIT_MS = 2000; const MANY_URLS_MIN = 3; // Seconds of slack between the browser's time-on-page and the token age (page load // starts before the server renders the token; clocks are both server-side). const SIGNALS_AGE_TOLERANCE_S = 15; // Defaults used when a settings key is absent (section 5.6). const DEFAULT_QUEUE_THRESHOLD = 55; const DEFAULT_BLOCK_THRESHOLD = 90; const DEFAULT_TOKEN_MIN_AGE = 3; // Submissions one page load (one token) may carry before the token stops counting. // A person who sends a second or third message from the same page stays below it. const DEFAULT_TOKEN_MAX_USES = 3; /** * Settings array (keys from section 5.6). * * @var array */ private array $settings; /** * Known agents. * * @var AgentDirectory */ private AgentDirectory $directory; /** * callable( string $signals_raw, string $token ): array (Signals::parse_signals) * * @var callable */ private $parse_signals; /** * callable( RequestContext $ctx ): array (Signals::server_signals) * * @var callable */ private $server_signals; /** * callable( string $token ): array (Signals::verify_token) * * @var callable */ private $verify_token; /** * callable( RequestContext $ctx ): array (WebBotAuth::verify) or null. * * @var callable|null */ private $wba_verify; /** * callable( string $sha256_hash ): bool (Queue duplicate lookup) or null. * * @var callable|null */ private $recent_hash_exists; /** * callable( string $nonce ): int (counts this use and returns the total) or null. * * @var callable|null */ private $token_uses; /** * @param array $settings Settings as array (Settings::all() or test array). * @param AgentDirectory $directory Agent directory. * @param callable $parse_signals fn( string $signals_raw, string $token ): array. * @param callable $server_signals fn( RequestContext $ctx ): array. * @param callable $verify_token fn( string $token ): array{valid:bool,age_seconds:int,nonce_ok:bool}. * @param callable|null $wba_verify fn( RequestContext $ctx ): array{verified:bool,agent:?string,keyid:?string,error:?string}. * @param callable|null $recent_hash_exists fn( string $hash ): bool, true if same text was seen in the last 24h. * @param callable|null $token_uses fn( string $nonce ): int, records one use of a token and returns how often it was used. */ public function __construct( array $settings, AgentDirectory $directory, callable $parse_signals, callable $server_signals, callable $verify_token, ?callable $wba_verify = null, ?callable $recent_hash_exists = null, ?callable $token_uses = null ) { $this->settings = $settings; $this->directory = $directory; $this->parse_signals = $parse_signals; $this->server_signals = $server_signals; $this->verify_token = $verify_token; $this->wba_verify = $wba_verify; $this->recent_hash_exists = $recent_hash_exists; $this->token_uses = $token_uses; } /** * Score one submission. * * @param RequestContext $ctx Request context (section 5.1). * @param SubmissionData $data Submission data (section 5.2). * @return Verdict Verdict with class, score, reasons, agent_name, meta. Action is left for Policy. */ public function score( RequestContext $ctx, SubmissionData $data ): Verdict { $verdict = new Verdict(); // Working state shared by the checks below. $state = array( 'verified' => false, // Web Bot Auth signature verified AND its origin is in the agent directory. 'signed' => false, // Signature is cryptographically valid (origin may be unknown). 'agent' => null, // Directory record for a known agent (not headless). 'agent_flag' => false, // UA or signature points at a known agent or generic bot. 'headless' => false, // Headless browser or scripted HTTP client. 'headless_name' => '', 'honeypot' => false, 'purpose' => '', 'token_valid' => false, 'token_nonce_ok' => false, // HMAC intact (age may still be out of range). 'token_issued' => false, // Token was rendered by this site (maybe for another client). 'token_too_young' => false, ); $this->check_honeypot( $data, $verdict, $state ); if ( ! $state['honeypot'] ) { // A filled honeypot is a bot whatever else is true; skip the (possibly outbound) signature check. $this->check_web_bot_auth( $ctx, $verdict, $state ); } $this->check_directory( $ctx, $verdict, $state ); $this->check_token( $data, $verdict, $state ); $this->check_signals( $data, $verdict, $state ); $this->check_server_signals( $ctx, $verdict, $state ); $this->check_text( $data, $verdict ); $this->check_purpose( $data, $verdict, $state ); $this->check_headless( $verdict, $state ); $raw = $verdict->weight_sum(); $capped = min( self::SCORE_CAP, max( 0, $raw ) ); $verdict->meta['raw_score'] = $raw; $verdict->meta['queue_threshold'] = $this->queue_threshold(); $this->assign_class( $verdict, $state, $capped ); $verdict->sort_reasons(); return $verdict; } /** * Final class mapping (section 5.7). * * Order matters: * 1. Verified signature from an origin listed in the agent directory wins: it is * cryptographic proof of a known operator. A valid signature from any other * origin proves only that domain; it sets agent_flag (step 4), not this class. * 2. Honeypot filled is always a bot, even if the purpose field is filled * (dumb bots fill every field they find). * 3. Declared purpose without honeypot: honest agent, unless the additive * score already reaches block_threshold (then it is a bot that found the field). * 4. Known agent UA or signature without declaration: suspected agent. * 5. Otherwise threshold decides human vs bot. * * @param Verdict $verdict Verdict to fill. * @param array $state Working state. * @param int $capped Capped additive score. */ private function assign_class( Verdict $verdict, array $state, int $capped ): void { if ( $state['verified'] ) { $verdict->class = Verdict::CLASS_AGENT_VERIFIED; $verdict->score = self::SCORE_AGENT_VERIFIED; return; } if ( $state['honeypot'] ) { $verdict->class = Verdict::CLASS_BOT; $verdict->score = $capped; return; } if ( '' !== $state['purpose'] ) { if ( $capped >= $this->block_threshold() ) { // Purpose text plus a request that already looks scripted (webdriver, // headless, no token, direct POST): a claim does not outweigh evidence. $verdict->add_reason( 'purpose_not_trusted', 0, __( 'Agent purpose was stated, but the request itself looks scripted; treated as a bot', 'agent-lane' ) ); $verdict->class = Verdict::CLASS_BOT; $verdict->score = $capped; return; } $verdict->class = Verdict::CLASS_AGENT_DECLARED; $verdict->score = max( self::SCORE_AGENT_DECLARED, $capped ); return; } if ( $state['agent_flag'] ) { $verdict->class = Verdict::CLASS_AGENT_SUSPECTED; $verdict->score = $capped; return; } if ( $capped >= $this->queue_threshold() ) { $verdict->class = Verdict::CLASS_BOT; $verdict->score = $capped; return; } $verdict->class = Verdict::CLASS_HUMAN; $verdict->score = $capped; } /** * Honeypot field: +60 when anything non-blank is in it. */ private function check_honeypot( SubmissionData $data, Verdict $verdict, array &$state ): void { if ( '' === trim( (string) $data->honeypot_value ) ) { return; } $state['honeypot'] = true; $verdict->add_reason( 'honeypot_filled', self::W_HONEYPOT_FILLED, __( 'Hidden honeypot field was filled in', 'agent-lane' ) ); } /** * Web Bot Auth: only when the request carries signature headers. * Verification runs only if the owner opted in (verify_signed_agents) * and a verifier was injected; otherwise the signature is noted only. */ private function check_web_bot_auth( RequestContext $ctx, Verdict $verdict, array &$state ): void { $sig_agent = is_string( $ctx->sig_agent ) ? trim( $ctx->sig_agent ) : ''; $signature = is_string( $ctx->signature ) ? trim( $ctx->signature ) : ''; if ( '' === $sig_agent && '' === $signature ) { return; } $verdict->meta['signature_agent'] = AgentDirectory::normalize_agent_host( $sig_agent ); if ( ! $this->setting_bool( 'verify_signed_agents', false ) || null === $this->wba_verify ) { $verdict->add_reason( 'wba_unverified', 0, __( 'Request carries a Web Bot Auth signature; signature verification is off in settings or unavailable', 'agent-lane' ) ); return; } $result = call_user_func( $this->wba_verify, $ctx ); if ( ! is_array( $result ) ) { $result = array(); } $verdict->meta['wba'] = $result; if ( empty( $result['verified'] ) ) { $error = isset( $result['error'] ) && '' !== (string) $result['error'] ? (string) $result['error'] : __( 'unknown error', 'agent-lane' ); $verdict->add_reason( 'wba_failed', 0, sprintf( /* translators: %s: error text from the signature verifier */ __( 'Web Bot Auth signature could not be verified (%s)', 'agent-lane' ), $error ) ); return; } // The signature is valid, so the identity of this request is the signing origin and // nothing else: from here on the User-Agent may add reasons, never an agent id // (check_directory). Anyone can publish keys on a domain of their own, so a valid // signature alone proves a domain, not a known operator. $state['signed'] = true; $agent_value = ! empty( $result['agent'] ) ? (string) $result['agent'] : $sig_agent; $record = $this->directory->match_signature_agent( $agent_value ); if ( ! empty( $result['keyid'] ) ) { $verdict->meta['wba_keyid'] = (string) $result['keyid']; } if ( null === $record ) { // Signed by an origin the directory does not list: not agent_verified, and no // per-agent rule can apply. It is still automation by its own statement, so it // is held as a suspected agent under the name of the domain that signed. $host = AgentDirectory::normalize_agent_host( $agent_value ); $verdict->agent_name = '' !== $host ? $host : null; $verdict->meta['agent_matched_by'] = 'signature_agent'; $state['agent_flag'] = true; $verdict->add_reason( 'wba_unlisted', 0, sprintf( /* translators: %s: host name that signed the request */ __( 'Valid Web Bot Auth signature from %s, which is not in the agent directory; not treated as a verified agent', 'agent-lane' ), '' !== $host ? $host : __( 'unknown operator', 'agent-lane' ) ) ); return; } $state['verified'] = true; $this->remember_agent( $verdict, $record ); $verdict->add_reason( 'wba_verified', 0, sprintf( /* translators: %s: agent name or Signature-Agent host */ __( 'Valid Web Bot Auth signature from %s', 'agent-lane' ), (string) $verdict->agent_name ) ); } /** * Known agents from the bundled directory. Headless / scripted-client * records count as headless, not as agents. */ private function check_directory( RequestContext $ctx, Verdict $verdict, array &$state ): void { $record = $this->directory->match( $ctx ); if ( null === $record ) { return; } $category = isset( $record['category'] ) ? (string) $record['category'] : ''; if ( AgentDirectory::is_automation_category( $category ) ) { $state['headless'] = true; $state['headless_name'] = isset( $record['name'] ) ? (string) $record['name'] : ''; return; } $state['agent'] = $record; $state['agent_flag'] = true; if ( ! $state['signed'] ) { // With a valid signature the identity is the signing origin (check_web_bot_auth). // A User-Agent is free text: letting it overwrite agent_id here would hand the // owner's per-agent rule for, say, ChatGPT to anyone who signs with a domain of // their own and copies the ChatGPT User-Agent (security review 2026-11-18). $this->remember_agent( $verdict, $record ); } $name = isset( $record['name'] ) ? (string) $record['name'] : (string) $record['id']; $operator = isset( $record['operator'] ) && '' !== (string) $record['operator'] ? (string) $record['operator'] : __( 'unknown operator', 'agent-lane' ); $by = isset( $record['matched_by'] ) ? (string) $record['matched_by'] : 'ua'; $label = self::agent_label( $name, $operator ); if ( 'signature_agent' === $by ) { $verdict->add_reason( 'known_agent_signature', self::W_KNOWN_AGENT_UA, sprintf( /* translators: %s: agent name with its operator, e.g. "GPTBot (OpenAI)" */ __( 'Signature-Agent header names %s', 'agent-lane' ), $label ) ); return; } $verdict->add_reason( 'known_agent_ua', self::W_KNOWN_AGENT_UA, sprintf( /* translators: %s: agent name with its operator, e.g. "GPTBot (OpenAI)" */ __( 'User agent matches %s', 'agent-lane' ), $label ) ); } /** * "Name (Operator)" for a directory record. Most bundled names already carry the * operator ("GPTBot (OpenAI)"); it is appended only when the name does not. * * @param string $name Agent name from the directory. * @param string $operator Operator name. * @return string */ public static function agent_label( string $name, string $operator ): string { if ( '' === $operator || false !== stripos( $name, $operator ) ) { return $name; } return $name . ' (' . $operator . ')'; } /** * Form token: missing +35, invalid +35, younger than token_min_age +30. */ private function check_token( SubmissionData $data, Verdict $verdict, array &$state ): void { $token = trim( (string) $data->token ); if ( '' === $token ) { $verdict->add_reason( 'token_missing', self::W_TOKEN_MISSING, __( 'Form token is missing: the page script did not run or the form was posted directly', 'agent-lane' ) ); return; } $result = call_user_func( $this->verify_token, $token ); if ( ! is_array( $result ) ) { $result = array(); } $valid = ! empty( $result['valid'] ); $nonce_ok = ! empty( $result['nonce_ok'] ); $age = isset( $result['age_seconds'] ) ? (int) $result['age_seconds'] : -1; $min_age = $this->setting_int( 'token_min_age', self::DEFAULT_TOKEN_MIN_AGE ); $verdict->meta['token_age_seconds'] = $age; $state['token_valid'] = $valid; $state['token_nonce_ok'] = $nonce_ok; // Verifiers without the `issued` key (tests, older callables) fall back to the full signature. $state['token_issued'] = array_key_exists( 'issued', $result ) ? ! empty( $result['issued'] ) : $nonce_ok; // One page load is good for a few submissions, not for a day of them. Past the limit // the token no longer vouches for anything: it costs like an invalid token and the // counters that came with it are not counted (check_signals), so a script that // replays one token is held. Only tokens this site issued are counted, so made-up // tokens cannot fill the counter store. if ( $state['token_issued'] && null !== $this->token_uses ) { $max = $this->setting_int( 'token_max_uses', self::DEFAULT_TOKEN_MAX_USES ); $uses = (int) call_user_func( $this->token_uses, (string) strtok( $token, '.' ) ); $verdict->meta['token_uses'] = $uses; if ( $max > 0 && $uses > $max ) { $state['token_issued'] = false; $verdict->add_reason( 'token_reused', self::W_TOKEN_REUSED, sprintf( /* translators: 1: how many times the token was used, 2: allowed number of uses */ __( 'Form token was used %1$d times; one page load is accepted for %2$d submissions', 'agent-lane' ), $uses, $max ) ); return; } } // Signals::verify_token() reports an intact token younger than // token_min_age as not valid (contract 5.4). Keep the two cases apart: // intact but too young is "too fast" (+30), forged or stale is invalid // (+35). Otherwise a fast submit would collect both weights. if ( $nonce_ok && $age >= 0 && $age < $min_age ) { $state['token_valid'] = true; $state['token_too_young'] = true; $verdict->add_reason( 'token_too_young', self::W_TOKEN_TOO_YOUNG, sprintf( /* translators: 1: seconds since render, 2: minimum seconds */ __( 'Form was submitted %1$d seconds after it was rendered, below the minimum of %2$d seconds', 'agent-lane' ), $age, $min_age ) ); return; } if ( ! $valid ) { $verdict->add_reason( 'token_invalid', self::W_TOKEN_INVALID, __( 'Form token is invalid or expired', 'agent-lane' ) ); } } /** * Client-side behavior signals (agentlane_s). */ private function check_signals( SubmissionData $data, Verdict $verdict, array &$state ): void { $signals = call_user_func( $this->parse_signals, (string) $data->signals_raw, (string) $data->token ); if ( ! is_array( $signals ) || empty( $signals ) || ! empty( $signals['missing'] ) ) { $verdict->meta['signals_present'] = false; $verdict->add_reason( 'signals_missing', self::W_SIGNALS_MISSING, __( 'No behavior signals were received from the page script', 'agent-lane' ) ); return; } // Counters are only as good as the token they are tied to. The browser copies the // token into the blob and the server compares the two, so a blob that arrives with // no token, or with one this site never issued, is a claim anyone can write without // loading the page. Not counting it keeps "made-up token plus made-up counters" // from scoring better than no token at all. if ( ! $state['token_issued'] ) { $verdict->meta['signals_present'] = false; $verdict->add_reason( 'signals_untrusted', self::W_SIGNALS_MISSING, __( 'Behavior signals came without a form token issued by this site, so they were not counted', 'agent-lane' ) ); return; } $verdict->meta['signals_present'] = true; $pointer = isset( $signals['pointer_moves'] ) ? (int) $signals['pointer_moves'] : 0; $touch = isset( $signals['touch_events'] ) ? (int) $signals['touch_events'] : 0; $keys = isset( $signals['key_events'] ) ? (int) $signals['key_events'] : 0; if ( ! empty( $signals['webdriver'] ) ) { $verdict->add_reason( 'webdriver', self::W_WEBDRIVER, __( 'Browser reports that it is under automation control (navigator.webdriver)', 'agent-lane' ) ); } if ( ! empty( $signals['headless_ua'] ) ) { $state['headless'] = true; } if ( 0 === $pointer && 0 === $touch && $keys > 0 ) { $verdict->add_reason( 'no_pointer_before_typing', self::W_NO_POINTER_BEFORE_TYPING, __( 'No mouse or touch movement before typing', 'agent-lane' ) ); } elseif ( 0 === $pointer && 0 === $touch && 0 === $keys ) { $verdict->add_reason( 'no_interaction', self::W_NO_INTERACTION, __( 'Page script ran but saw no mouse, touch or keyboard activity at all', 'agent-lane' ) ); } $ms_to_submit = isset( $signals['ms_to_submit'] ) ? (int) $signals['ms_to_submit'] : -1; $verdict->meta['ms_to_submit'] = $ms_to_submit; // Token too young already covers the same fact from the server side; // do not count it twice. if ( $ms_to_submit >= 0 && $ms_to_submit < self::FAST_SUBMIT_MS && ! $state['token_too_young'] ) { $verdict->add_reason( 'too_fast', self::W_TOO_FAST, sprintf( /* translators: %s: seconds with one decimal */ __( 'Submitted %s seconds after the form was rendered', 'agent-lane' ), number_format( $ms_to_submit / 1000, 1, '.', '' ) ) ); } // Cross-check the counters against server facts (security review 2026-10-12, // medium 4). The token timestamp is server time at render, so a blob that claims // more time on the page than the token has existed, or an input order that cannot // happen in a browser, was written by hand. A page served from cache makes the // token older than the page, never younger, so that case stays clean. $age = isset( $verdict->meta['token_age_seconds'] ) ? (int) $verdict->meta['token_age_seconds'] : -1; $first_input = isset( $signals['ms_to_first_input'] ) ? (int) $signals['ms_to_first_input'] : -1; $detail = ''; if ( $state['token_nonce_ok'] && $age >= 0 && $ms_to_submit > ( $age + self::SIGNALS_AGE_TOLERANCE_S ) * 1000 ) { $detail = __( 'Browser counters claim more time on the page than the form token has existed', 'agent-lane' ); } elseif ( $first_input >= 0 && $ms_to_submit >= 0 && $first_input > $ms_to_submit ) { $detail = __( 'Browser counters put the first input after the submit', 'agent-lane' ); } elseif ( $first_input < 0 && ( $keys > 0 || $touch > 0 ) ) { $detail = __( 'Browser counters report typing or touches but no first-input time', 'agent-lane' ); } if ( '' !== $detail ) { $verdict->add_reason( 'signals_inconsistent', self::W_SIGNALS_INCONSISTENT, $detail ); } } /** * Server-side request signals (Signals::server_signals). */ private function check_server_signals( RequestContext $ctx, Verdict $verdict, array &$state ): void { $srv = call_user_func( $this->server_signals, $ctx ); if ( ! is_array( $srv ) ) { $srv = array(); } if ( ! empty( $srv['ua_headless'] ) ) { $state['headless'] = true; } if ( ! empty( $srv['direct_post'] ) ) { $verdict->add_reason( 'direct_post', self::W_DIRECT_POST, __( 'Request was posted directly, not from a page in a browser (no Sec-Fetch-Site)', 'agent-lane' ) ); } if ( ! empty( $srv['missing_sec_ch_ua'] ) && self::ua_is_chromium( (string) $ctx->ua ) && self::context_is_secure( $ctx ) ) { $verdict->add_reason( 'missing_sec_ch_ua', self::W_MISSING_SEC_CH_UA, __( 'Chrome user agent without the Sec-CH-UA client hints that real Chrome sends', 'agent-lane' ) ); } if ( ! empty( $srv['missing_accept_language'] ) ) { $verdict->add_reason( 'missing_accept_language', self::W_MISSING_ACCEPT_LANGUAGE, __( 'No Accept-Language header', 'agent-lane' ) ); } if ( ! empty( $srv['no_cookies'] ) ) { $verdict->add_reason( 'no_cookies', self::W_NO_COOKIES, __( 'No cookies were sent with the request', 'agent-lane' ) ); } if ( ! empty( $srv['ip_is_datacenter'] ) ) { $verdict->add_reason( 'datacenter_ip', self::W_DATACENTER_IP, __( 'IP address belongs to a hosting or cloud provider', 'agent-lane' ) ); } // Generic bot marker from Signals when the directory did not match. if ( ! empty( $srv['ua_is_known_bot'] ) && null === $state['agent'] && ! $state['headless'] ) { $state['agent_flag'] = true; $verdict->add_reason( 'ua_known_bot', self::W_KNOWN_AGENT_UA, __( 'User agent identifies itself as a bot or crawler', 'agent-lane' ) ); } } /** * Content heuristics on the joined text fields. */ private function check_text( SubmissionData $data, Verdict $verdict ): void { $text = trim( (string) $data->text_blob ); if ( '' === $text ) { return; } $url_count = preg_match_all( '~(?:https?://|www\.)[^\s<>"\']+~i', $text ); $url_count = false === $url_count ? 0 : (int) $url_count; $verdict->meta['url_count'] = $url_count; if ( $url_count >= self::MANY_URLS_MIN ) { $verdict->add_reason( 'many_urls', self::W_MANY_URLS, sprintf( /* translators: %d: number of links */ __( 'Message contains %d links', 'agent-lane' ), $url_count ) ); } $hash = self::text_hash( $text ); $verdict->meta['text_hash'] = $hash; if ( null !== $this->recent_hash_exists && true === (bool) call_user_func( $this->recent_hash_exists, $hash ) ) { $verdict->add_reason( 'duplicate_text', self::W_DUPLICATE_TEXT, __( 'Identical text was submitted in the last 24 hours', 'agent-lane' ) ); } } /** * The hidden "agent purpose" field. Informational reasons only; the * class mapping uses $state['purpose'] and $state['honeypot']. */ private function check_purpose( SubmissionData $data, Verdict $verdict, array &$state ): void { $purpose = trim( (string) $data->agent_purpose ); if ( '' === $purpose ) { return; } $state['purpose'] = $purpose; $verdict->meta['agent_purpose'] = self::truncate( $purpose, 200 ); if ( $state['honeypot'] ) { $verdict->add_reason( 'purpose_ignored', 0, __( 'Agent purpose field was filled, but so was the honeypot; treated as a bot', 'agent-lane' ) ); return; } $verdict->add_reason( 'agent_declared', 0, sprintf( /* translators: %s: text the agent typed into the purpose field */ __( 'Agent declared its purpose: %s', 'agent-lane' ), self::truncate( $purpose, 120 ) ) ); } /** * One headless reason regardless of how many sources flagged it * (client signals, server signals, directory). */ private function check_headless( Verdict $verdict, array $state ): void { if ( ! $state['headless'] ) { return; } if ( '' !== $state['headless_name'] ) { $detail = sprintf( /* translators: %s: marker name, e.g. HeadlessChrome */ __( 'User agent belongs to a headless browser or scripted client (%s)', 'agent-lane' ), $state['headless_name'] ); } else { $detail = __( 'User agent belongs to a headless browser or scripted HTTP client', 'agent-lane' ); } $verdict->add_reason( 'headless_ua', self::W_HEADLESS_UA, $detail ); } /** * Copy identity fields from a directory record into the verdict. */ private function remember_agent( Verdict $verdict, array $record ): void { $verdict->agent_name = isset( $record['name'] ) ? (string) $record['name'] : (string) $record['id']; $verdict->meta['agent_id'] = (string) $record['id']; $verdict->meta['agent_operator'] = isset( $record['operator'] ) ? $record['operator'] : null; $verdict->meta['agent_category'] = isset( $record['category'] ) ? $record['category'] : null; $verdict->meta['agent_default_policy'] = isset( $record['default_policy'] ) ? $record['default_policy'] : null; $verdict->meta['agent_matched_by'] = isset( $record['matched_by'] ) ? $record['matched_by'] : null; $verdict->meta['agent_matched_value'] = isset( $record['matched_value'] ) ? $record['matched_value'] : null; } /** * Normalized SHA-256 of a text blob (lowercase, whitespace collapsed). * Public so Queue / Router can compute the same hash when storing. * * @param string $text Raw text. * @return string 64 hex chars. */ public static function text_hash( string $text ): string { $norm = preg_replace( '/\s+/u', ' ', trim( $text ) ); if ( null === $norm ) { $norm = preg_replace( '/\s+/', ' ', trim( $text ) ); } if ( null === $norm ) { $norm = $text; } $norm = function_exists( 'mb_strtolower' ) ? mb_strtolower( $norm, 'UTF-8' ) : strtolower( $norm ); return hash( 'sha256', $norm ); } /** * Chromium-based desktop/Android UA (sends Sec-CH-UA on secure origins). * Chrome on iOS (CriOS) is WebKit and never sends client hints. * * @param string $ua User agent. * @return bool */ public static function ua_is_chromium( string $ua ): bool { if ( false !== stripos( $ua, 'CriOS/' ) ) { return false; } return false !== stripos( $ua, 'Chrome/' ) || false !== stripos( $ua, 'Chromium/' ); } /** * Client hints are only sent on HTTPS. If Origin / Referer say the page * was plain HTTP, missing Sec-CH-UA means nothing. Unknown counts as secure. * * @param RequestContext $ctx Request. * @return bool */ private static function context_is_secure( RequestContext $ctx ): bool { $hints = array(); if ( is_string( $ctx->origin ) && '' !== $ctx->origin ) { $hints[] = $ctx->origin; } if ( is_string( $ctx->referer ) && '' !== $ctx->referer ) { $hints[] = $ctx->referer; } if ( isset( $ctx->headers['x-forwarded-proto'] ) && is_string( $ctx->headers['x-forwarded-proto'] ) ) { $hints[] = strtolower( trim( $ctx->headers['x-forwarded-proto'] ) ) . '://'; } if ( empty( $hints ) ) { return true; } foreach ( $hints as $hint ) { if ( 0 === stripos( $hint, 'https://' ) || 0 === stripos( $hint, 'https:' ) ) { return true; } } return false; } /** * Cut a string to N characters, multibyte-safe when mbstring exists. */ private static function truncate( string $text, int $max ): string { if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) { if ( mb_strlen( $text, 'UTF-8' ) <= $max ) { return $text; } return mb_substr( $text, 0, $max, 'UTF-8' ) . '...'; } if ( strlen( $text ) <= $max ) { return $text; } return substr( $text, 0, $max ) . '...'; } /** * Queue threshold from settings. */ private function queue_threshold(): int { return $this->setting_int( 'queue_threshold', self::DEFAULT_QUEUE_THRESHOLD ); } /** * Block threshold from settings. */ private function block_threshold(): int { return $this->setting_int( 'block_threshold', self::DEFAULT_BLOCK_THRESHOLD ); } /** * Integer setting with default. */ private function setting_int( string $key, int $default ): int { if ( ! isset( $this->settings[ $key ] ) || ! is_numeric( $this->settings[ $key ] ) ) { return $default; } return (int) $this->settings[ $key ]; } /** * Boolean setting with default. Accepts '1', 'true', 'yes', 'on'. */ private function setting_bool( string $key, bool $default ): bool { if ( ! isset( $this->settings[ $key ] ) ) { return $default; } $value = $this->settings[ $key ]; if ( is_bool( $value ) ) { return $value; } if ( is_numeric( $value ) ) { return 0 !== (int) $value; } if ( is_string( $value ) ) { return in_array( strtolower( trim( $value ) ), array( '1', 'true', 'yes', 'on' ), true ); } return (bool) $value; } }