Policy -> Queue -> action hook. * * The Router builds no form data itself. It takes a RequestContext and a * SubmissionData (WP1), asks the Scorer (WP3) for a Verdict, lets the * Policy (WP3) pick the action, stores a copy via Queue (WP6) and fires * the `agentlane_verdict` action. Adapters (WP5) call it and act on * `$verdict->action`. * * It is also the composition root for the scoring pipeline: it wires the * Scorer with Signals callables, the AgentDirectory, a WebBotAuth verifier * (directory fetch only when `verify_signed_agents` is on) and the Queue's * duplicate lookup. Shared helpers for adapters live here too (settings, * hidden field markup, page marking, SubmissionData construction). * * Failure mode is "fail open": if scoring throws for any reason the * submission is allowed and the error is logged under WP_DEBUG. A spam * filter must never take a real person's message down with it. * * @package AgentLane */ namespace AgentLane; if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Class Router */ class Router { /** * Allowed actions. * * @var string[] */ const ACTIONS = array( 'allow', 'queue', 'block' ); /** * Max length of a single field value kept for scoring and preview. */ const MAX_FIELD_LENGTH = 20000; /** * Transient prefix for cached Web Bot Auth key directories. */ const WBA_TRANSIENT_PREFIX = 'agentlane_wba_dir_'; /** * Cache lifetimes for the key directory: success 24h, failure 10 min. */ const WBA_CACHE_OK = 86400; const WBA_CACHE_FAIL = 600; /** * Upper bound for a key directory body we are willing to parse. */ const WBA_MAX_BODY = 65536; /** * Site-wide rate limit for key directory fetches: WBA_FETCH_LIMIT per WBA_FETCH_WINDOW seconds. */ const WBA_RATE_TRANSIENT = 'agentlane_wba_fetches'; const WBA_FETCH_LIMIT = 30; const WBA_FETCH_WINDOW = 600; /** * Transient prefix for seen Web Bot Auth nonces (replay protection). */ const WBA_NONCE_PREFIX = 'agentlane_wba_n_'; /** * Transient prefix for the per-token use counter. */ const TOKEN_USES_PREFIX = 'agentlane_tok_'; /** * Field names that are never scored, stored or emailed (case-insensitive). * Filter: agentlane_sensitive_field_pattern. */ const SENSITIVE_FIELD_PATTERN = '/(password|passwd|cvv|cvc|card[ _-]?number|iban|ssn|passport|national[ _-]?id)/i'; /** * POST keys that are never user fields (form plugin internals). * * @var string[] */ const INTERNAL_KEYS = array( 'action', 'post_id', 'form_id', 'referer_title', 'queried_id', 'referrer', 'wpforms', 'g-recaptcha-response', 'h-captcha-response', 'cf-turnstile-response', 'comment_post_ID', 'comment_parent', 'submit', ); /** * Full pipeline: Scorer -> Policy -> Queue insert -> action -> Verdict. * * Queue::insert is called for every verdict; the Queue itself stores a * light copy (no fields) for `allow` and a full copy for queue/block * (contract 5.10). * * @param RequestContext $ctx Request context built by the adapter. * @param SubmissionData $data Submission built by the adapter. * @return Verdict */ public static function route( RequestContext $ctx, SubmissionData $data ): Verdict { try { $verdict = self::scorer( $ctx, $data )->score( $ctx, $data ); self::apply_blocklist( $verdict, $ctx, $data ); $verdict = self::policy()->decide( $verdict ); } catch ( \Throwable $e ) { self::log( 'scoring failed, allowing submission: ' . $e->getMessage() ); $verdict = self::fallback_verdict( $e->getMessage() ); } if ( ! in_array( $verdict->action, self::ACTIONS, true ) ) { $verdict->action = 'allow'; } // Store a copy. Guarded: WP6 may be absent in tests or partial installs. $queue_id = 0; if ( class_exists( Queue::class ) ) { $queue_id = self::store( $verdict, $ctx, $data, false ); // A held row the table refused (emoji on an old utf8 table, invalid bytes): // try once more with the text made storable. The row then says so. if ( $queue_id <= 0 && 'allow' !== $verdict->action ) { $queue_id = self::store( $verdict, $ctx, $data, true ); if ( $queue_id > 0 ) { $verdict->meta['queue_text_replaced'] = true; } } if ( $queue_id > 0 ) { $verdict->meta['queue_id'] = $queue_id; } } // Holding means "the form plugin drops it, the queue keeps it". When the queue did // not keep it (table missing on a new network site, a row the table cannot store), // holding would lose the message for good, so the submission is delivered instead // (security review 2026-11-18, item 3). Class, score and reasons stay as scored. if ( $queue_id <= 0 && 'allow' !== $verdict->action ) { self::log( 'submission could not be stored in the queue, delivering it instead of "' . $verdict->action . '"' ); $verdict->meta['queue_failed'] = true; $verdict->meta['action_wanted'] = $verdict->action; if ( class_exists( Queue::class ) ) { // Persistent record for the admin notice (Admin::queue_failure_notice()). Queue::record_failure( $verdict->action ); } $verdict->action = 'allow'; } /** * Fires after every scored submission. * * @param Verdict $verdict Final verdict (action already set). * @param RequestContext $ctx Request context. * @param SubmissionData $data Submission data. */ do_action( 'agentlane_verdict', $verdict, $ctx, $data ); return $verdict; } /** * Convenience wrapper for adapters: build context + submission, route. * * Returns null when the core classes are not available or when anything * throws; adapters treat null as "allow" (fail open). * * @param string $form_source 'cf7'|'wpforms'|'gravity'|'elementor'|'comments'. * @param string $form_id Form identifier as the form plugin knows it. * @param array $fields Raw fields name => value (value may be array). * @return Verdict|null */ public static function handle( string $form_source, string $form_id, array $fields ): ?Verdict { if ( ! self::is_ready() ) { return null; } try { $ctx = RequestContext::from_globals(); $data = self::make_submission( $form_source, $form_id, $fields ); return self::route( $ctx, $data ); } catch ( \Throwable $e ) { self::log( 'route failed, allowing submission: ' . $e->getMessage() ); return null; } } /** * True when every class the pipeline needs is loadable. * * @return bool */ public static function is_ready(): bool { // Verdict lives inside class-scorer.php (WP3); loading Scorer first // makes sure the autoloader has defined it. if ( ! class_exists( Scorer::class ) ) { return false; } return class_exists( Verdict::class ) && class_exists( Policy::class ) && class_exists( AgentDirectory::class ) && class_exists( Signals::class ) && class_exists( RequestContext::class ) && class_exists( SubmissionData::class ); } /** * Build a SubmissionData from a raw field list plus our own POST fields. * * Drops internal keys (agentlane_*, honeypot, nonces, captcha tokens, * anything that looks like a password), flattens array values and * joins the text into `text_blob`. Our own fields are read from $_POST * directly because WPForms, Gravity and Elementor keep their fields in * nested arrays while ours stay top-level. * * @param string $form_source Source id. * @param string $form_id Form id. * @param array $fields name => value. * @return SubmissionData */ public static function make_submission( string $form_source, string $form_id, array $fields ): SubmissionData { $honeypot_name = (string) self::setting( 'honeypot_field_name', '' ); $clean = array(); $blob = array(); foreach ( $fields as $name => $value ) { $name = trim( (string) $name ); if ( '' === $name || self::is_internal_field( $name, $honeypot_name ) ) { continue; } $text = self::flatten_value( $value ); $clean[ $name ] = $text; if ( '' !== $text ) { $blob[] = $text; } } return new SubmissionData( array( 'form_source' => $form_source, 'form_id' => substr( $form_id, 0, 100 ), 'fields' => $clean, 'honeypot_value' => '' !== $honeypot_name ? self::post_value( $honeypot_name ) : '', 'token' => substr( self::post_value( SubmissionData::FIELD_TOKEN ), 0, 512 ), 'signals_raw' => substr( self::post_value( SubmissionData::FIELD_SIGNALS ), 0, 8192 ), 'agent_purpose' => substr( self::post_value( SubmissionData::FIELD_AGENT_PURPOSE, true ), 0, 1000 ), 'text_blob' => implode( "\n", $blob ), ) ); } /** * Read one of our own fields from $_POST. * * These are public front-end forms; the form plugin owns the nonce and * our signed token replaces it for our purposes, hence no nonce check. * * @param string $key POST key. * @param bool $multiline Keep line breaks. * @return string */ public static function post_value( string $key, bool $multiline = false ): string { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- public form submission; the signed token (Signals::verify_token) replaces the nonce. if ( ! isset( $_POST[ $key ] ) || ! is_string( $_POST[ $key ] ) ) { return ''; } if ( $multiline ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- see above. return sanitize_textarea_field( wp_unslash( $_POST[ $key ] ) ); } // phpcs:ignore WordPress.Security.NonceVerification.Missing -- see above. return sanitize_text_field( wp_unslash( $_POST[ $key ] ) ); } /** * One setting (contract 5.6) with fallback for environments without WP1. * * @param string $key Setting key. * @param mixed $default Fallback. * @return mixed */ public static function setting( string $key, $default = null ) { if ( class_exists( Settings::class ) ) { return Settings::instance()->get( $key, $default ); } $all = self::settings_array(); return array_key_exists( $key, $all ) ? $all[ $key ] : $default; } /** * All settings as a plain array (what Scorer and Policy take). * * @return array */ public static function settings_array(): array { if ( class_exists( Settings::class ) ) { return Settings::instance()->all(); } $option = get_option( 'agentlane_settings', array() ); return is_array( $option ) ? $option : array(); } /** * Message shown when a submission is blocked. * * @return string */ public static function block_message(): string { $default = __( 'This form does not accept automated submissions. If you are an agent acting for a person, state your purpose in the agent field.', 'agent-lane' ); $message = (string) self::setting( 'block_message', $default ); if ( '' === trim( $message ) ) { $message = $default; } /** * Filter the block message shown to a rejected submission. * * @param string $message Plain text message. */ return wp_strip_all_tags( (string) apply_filters( 'agentlane_block_message', $message ) ); } /** * Message shown when a submission is held in the Automation queue. * Honest wording: nothing is deleted, the owner can release it. * * @return string */ public static function held_message(): string { $message = __( 'Thank you. Your submission has been received and is awaiting review.', 'agent-lane' ); /** * Filter the message shown to a held (queued) submission. * * @param string $message Plain text message. */ return wp_strip_all_tags( (string) apply_filters( 'agentlane_held_message', $message ) ); } /** * Markup for the token, honeypot and agent-purpose fields (WP2). * Returns '' when Signals is unavailable; JS injection then takes over. * * @return string HTML, escaped inside Signals. */ public static function hidden_fields(): string { if ( ! class_exists( Signals::class ) ) { return ''; } try { return Signals::render_hidden_fields(); } catch ( \Throwable $e ) { self::log( 'render_hidden_fields failed: ' . $e->getMessage() ); return ''; } } /** * Tell the core that this page contains a supported form (enqueues JS). * * @return void */ public static function mark_page_has_form(): void { if ( class_exists( Plugin::class ) ) { Plugin::mark_page_has_form(); } } /** * Short reason text for the form plugin's own spam log. * * @param Verdict $verdict Verdict. * @return string */ public static function reason_summary( Verdict $verdict ): string { $codes = array(); foreach ( array_slice( $verdict->reasons, 0, 3 ) as $reason ) { if ( is_array( $reason ) && ! empty( $reason['code'] ) ) { $codes[] = (string) $reason['code']; } } return sprintf( 'Agent Lane: %1$s, score %2$d%3$s', $verdict->class, $verdict->score, $codes ? ' (' . implode( ', ', $codes ) . ')' : '' ); } /** * Fetch a Web Bot Auth key directory (JWK Set) with a transient cache. * * Only ever called when `verify_signed_agents` is on: that is the single * outbound HTTP call the plugin makes (section 2, rule 1). Successful * bodies are cached 24h, failed fetches 10 minutes so a dead host is not * hammered on every submission. Rate limited, then guarded against SSRF * (see is_safe_directory_url()); hosts the guard rejects are not cached. * * @param string $url Directory URL (WebBotAuth::directory_url()). * @return string JSON body or '' on failure. */ public static function fetch_directory( string $url ): string { $key = self::WBA_TRANSIENT_PREFIX . md5( $url ); $cached = get_transient( $key ); if ( is_string( $cached ) ) { return $cached; } // Rate limit first: the safety check below resolves the host name, and the header // that names the host is free text. Counting before the check keeps both the DNS // lookups and the outbound requests under WBA_FETCH_LIMIT per window, whatever // hosts are sent (security review 2026-11-18). The counter is one fixed option; // it is not atomic, so parallel requests can exceed the limit by a few. $count = (int) get_transient( self::WBA_RATE_TRANSIENT ); if ( $count >= self::WBA_FETCH_LIMIT ) { return ''; } set_transient( self::WBA_RATE_TRANSIENT, $count + 1, self::WBA_FETCH_WINDOW ); // SSRF guard: public https host on the default port only, no IP literals, no local // names, no private addresses behind the name (security review 2026-10-12). // A rejected host is not cached: one transient per made-up host name would let a // sender fill the options table. The rate limit above bounds the repeat checks. if ( ! self::is_safe_directory_url( $url ) ) { return ''; } $body = ''; $response = wp_safe_remote_get( $url, array( 'timeout' => 5, 'redirection' => 0, 'reject_unsafe_urls' => true, 'limit_response_size' => self::WBA_MAX_BODY, 'sslverify' => true, 'headers' => array( 'Accept' => 'application/http-message-signatures-directory+json, application/json' ), ) ); if ( ! is_wp_error( $response ) && 200 === (int) wp_remote_retrieve_response_code( $response ) ) { $raw = (string) wp_remote_retrieve_body( $response ); if ( '' !== $raw && strlen( $raw ) <= self::WBA_MAX_BODY && null !== json_decode( $raw, true ) ) { $body = $raw; } } set_transient( $key, $body, '' === $body ? self::WBA_CACHE_FAIL : self::WBA_CACHE_OK ); return $body; } /** * Is a key directory URL safe to fetch from this server? * * Rejects anything but https on port 443, IP literals (v4, bracketed v6), * single-label and reserved local names, and hosts that resolve to a * private, loopback, link-local or CGNAT address. Residual risk: DNS * rebinding between this check and the connect (accepted for v1). * * @param string $url Directory URL. * @return bool */ public static function is_safe_directory_url( string $url ): bool { $parts = wp_parse_url( $url ); if ( ! is_array( $parts ) ) { return false; } $scheme = strtolower( (string) ( $parts['scheme'] ?? '' ) ); $host = strtolower( (string) ( $parts['host'] ?? '' ) ); if ( 'https' !== $scheme || '' === $host ) { return false; } if ( isset( $parts['user'] ) || isset( $parts['pass'] ) ) { return false; } if ( isset( $parts['port'] ) && 443 !== (int) $parts['port'] ) { return false; } if ( '[' === $host[0] || false !== filter_var( $host, FILTER_VALIDATE_IP ) ) { return false; } if ( false === strpos( $host, '.' ) ) { return false; } if ( preg_match( '/\.(localhost|local|internal|intranet|lan|home|corp|arpa|test|invalid|example|onion)$/', $host ) ) { return false; } $ips = gethostbynamel( $host ); if ( empty( $ips ) ) { return false; } foreach ( $ips as $ip ) { if ( class_exists( Signals::class ) && Signals::ip_is_private( (string) $ip ) ) { return false; } } return true; } /** * Records one use of a form token and returns how often it has been used. Kept in * a transient for the lifetime of the token; called by the Scorer only for tokens * this site issued. * * Counted per token and per client (network range + browser family, the same pair * the token is tied to), not per token alone. A page cache may hand one token to * many visitors even though the setting asks sites with a cache to turn the binding * off; with a counter per token alone the fourth visitor of such a page would be * held for the rest of the day. * * @param string $nonce Token nonce (16 hex chars). * @return int */ public static function token_uses( string $nonce ): int { if ( 1 !== preg_match( '/^[a-f0-9]{16}$/', $nonce ) ) { return 0; } $key = self::TOKEN_USES_PREFIX . md5( $nonce . '|' . Signals::client_binding() ); $uses = (int) get_transient( $key ) + 1; set_transient( $key, $uses, max( 600, (int) self::setting( 'token_max_age', 86400 ) ) ); return $uses; } /** * Host[:port] of this site, as a signing agent puts it into @authority (RFC 9421, * section 2.2.3). The port belongs to the authority unless it is the default for the * scheme (WebBotAuth strips that case itself), so a site on :8080 must be compared * with its port or every signature fails with authority_mismatch. * * @param string $url URL to read; empty = home_url( '/' ). * @return string */ public static function site_authority( string $url = '' ): string { $parts = wp_parse_url( '' !== $url ? $url : home_url( '/' ) ); $host = is_array( $parts ) ? strtolower( (string) ( $parts['host'] ?? '' ) ) : ''; if ( '' !== $host && ! empty( $parts['port'] ) ) { $host .= ':' . (int) $parts['port']; } return $host; } /** * Replay check for Web Bot Auth nonces: true when this nonce was seen before. * WebBotAuth calls it only after the signature verified, so unsigned requests * cannot fill the cache. Kept until the signature expires (plus skew). * * @param string $nonce Signature nonce. * @param string|null $agent Signature-Agent origin. * @param int $expires Signature expiry (unix). * @return bool */ public static function wba_nonce_seen( string $nonce, ?string $agent, int $expires ): bool { $key = self::WBA_NONCE_PREFIX . hash( 'sha256', (string) $agent . '|' . $nonce ); if ( get_transient( $key ) ) { return true; } set_transient( $key, 1, max( 60, $expires - time() + WebBotAuth::DEFAULT_SKEW ) ); return false; } /* ------------------------------------------------------------------ */ /* Internals */ /* ------------------------------------------------------------------ */ /** * Scorer wired with Signals, AgentDirectory, WebBotAuth and Queue lookup. * * The Scorer's duplicate check hands us a hash of the text only; the * Queue indexes the fingerprint (ua + ip + text), so the lookup answers * "same sender sent the same text in the last 24h". Narrower than the * contract wording, but it needs no extra column. * * @param RequestContext $ctx Context (for the duplicate lookup). * @param SubmissionData $data Submission (for the duplicate lookup). * @return Scorer */ private static function scorer( RequestContext $ctx, SubmissionData $data ): Scorer { $settings = self::settings_array(); $wba_verify = null; if ( class_exists( WebBotAuth::class ) ) { $fetch = ! empty( $settings['verify_signed_agents'] ) ? array( self::class, 'fetch_directory' ) : null; $wba = new WebBotAuth( $fetch, null, array( 'scheme' => is_ssl() ? 'https' : 'http', // Bind @authority to this site: a signature captured on another host is not valid here. 'authority' => self::site_authority(), // Replay protection: each nonce is accepted once. 'nonce_check' => array( self::class, 'wba_nonce_seen' ), ) ); $wba_verify = array( $wba, 'verify' ); } $recent = null; if ( class_exists( Queue::class ) ) { $recent = static function ( string $text_hash ) use ( $ctx, $data ): bool { unset( $text_hash ); return Queue::instance()->seen_recently( Queue::fingerprint( $ctx, $data ), 86400 ); }; } // Token use limit. Off when tokens are not tied to the visitor: that mode exists for // full-page caches, where every visitor legitimately carries the same token. $token_uses = null; if ( ! empty( $settings['bind_token_to_client'] ) && '' !== Signals::client_binding() ) { $token_uses = array( self::class, 'token_uses' ); /** * How many submissions one page load (one token) may carry. 0 = no limit. * * @param int $max Default 3. */ $settings['token_max_uses'] = max( 0, (int) apply_filters( 'agentlane_token_max_uses', Scorer::DEFAULT_TOKEN_MAX_USES ) ); } return new Scorer( $settings, new AgentDirectory(), array( Signals::class, 'parse_signals' ), array( Signals::class, 'server_signals' ), array( Signals::class, 'verify_token' ), $wba_verify, $recent, $token_uses ); } /** * Policy instance. * * @return Policy */ private static function policy(): Policy { return new Policy( self::settings_array() ); } /** * Owner blocklist (option `agentlane_blocklist`, filled by Queue::mark_bot). * A hit turns the verdict into a certain bot so Policy blocks it. * * @param Verdict $verdict Verdict to adjust in place. * @param RequestContext $ctx Context. * @param SubmissionData $data Submission. * @return void */ private static function apply_blocklist( Verdict $verdict, RequestContext $ctx, SubmissionData $data ): void { if ( ! class_exists( Queue::class ) ) { return; } $fingerprint = Queue::fingerprint( $ctx, $data ); if ( '' === $fingerprint || ! Queue::is_blocklisted( $fingerprint ) ) { return; } $verdict->class = 'bot'; $verdict->score = 100; $verdict->reasons[] = array( 'code' => 'blocklist', 'weight' => 100, 'detail' => __( 'Signature was marked as a bot by the site owner', 'agent-lane' ), ); $verdict->meta['blocklist'] = true; } /** * Verdict used when scoring itself failed: allow, score 0, one reason. * * @param string $error Error text for meta. * @return Verdict */ private static function fallback_verdict( string $error ): Verdict { $verdict = new Verdict(); $verdict->class = 'human'; $verdict->score = 0; $verdict->reasons = array( array( 'code' => 'scorer_error', 'weight' => 0, 'detail' => __( 'Scoring failed, submission allowed', 'agent-lane' ), ), ); $verdict->action = 'allow'; $verdict->meta = array( 'error' => $error ); return $verdict; } /** * Keys that must not be treated as user-entered fields. * * @param string $name Field name. * @param string $honeypot_name Current honeypot field name. * @return bool */ private static function is_internal_field( string $name, string $honeypot_name ): bool { if ( '' !== $honeypot_name && $name === $honeypot_name ) { return true; } if ( 0 === strpos( $name, 'agentlane_' ) || 0 === strpos( $name, '_' ) ) { return true; } if ( in_array( $name, self::INTERNAL_KEYS, true ) ) { return true; } /** * Pattern for field names that must never be scored, stored or emailed. * * @param string $pattern PCRE pattern, matched against the field name. */ $pattern = (string) apply_filters( 'agentlane_sensitive_field_pattern', self::SENSITIVE_FIELD_PATTERN ); return '' !== $pattern && 1 === preg_match( $pattern, $name ); } /** * Turn any posted value into a single trimmed string. * * @param mixed $value Scalar or (nested) array. * @return string */ private static function flatten_value( $value ): string { if ( is_array( $value ) ) { $parts = array(); foreach ( $value as $item ) { $text = self::flatten_value( $item ); if ( '' !== $text ) { $parts[] = $text; } } $text = implode( ', ', $parts ); } elseif ( is_scalar( $value ) ) { $text = trim( (string) $value ); } else { $text = ''; } if ( strlen( $text ) > self::MAX_FIELD_LENGTH ) { $text = substr( $text, 0, self::MAX_FIELD_LENGTH ); } return $text; } /** * One queue insert, guarded. Returns the row id or 0. * * @param Verdict $verdict Verdict. * @param RequestContext $ctx Request context. * @param SubmissionData $data Submission. * @param bool $storable Second try with storable text. * @return int */ private static function store( Verdict $verdict, RequestContext $ctx, SubmissionData $data, bool $storable ): int { try { return (int) Queue::instance()->insert( $verdict, $ctx, $data, $storable ); } catch ( \Throwable $e ) { self::log( 'queue insert failed: ' . $e->getMessage() ); return 0; } } /** * Debug log, only under WP_DEBUG. Local error_log only, no telemetry. * * @param string $message Message. * @return void */ private static function log( string $message ): void { if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) { // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- debug only. error_log( '[agent-lane] ' . $message ); } } }