, * component_unavailable:, invalid_signature_length, * no_ed25519_backend, signature_mismatch, nonce_reused, authority_mismatch, * lifetime_too_long. */ class WebBotAuth { /** Allowed clock skew for created/expires, in seconds. */ const DEFAULT_SKEW = 300; /** Well-known path of the JWKS directory relative to the agent origin. */ const DIRECTORY_PATH = '/.well-known/http-message-signatures-directory'; /** Tag value required by the Web Bot Auth protocol draft. */ const EXPECTED_TAG = 'web-bot-auth'; /** Upper bound for header values we are willing to parse. */ const MAX_HEADER_LENGTH = 8192; /** Longest accepted created..expires window, in seconds (draft examples use one hour). */ const MAX_LIFETIME = 86400; /** * Fetches the JWKS body for a directory URL. Signature: fn( string $url ): ?string. * * @var callable|null */ private $fetch_directory; /** * Clock provider. Signature: fn(): int (unix seconds). * * @var callable */ private $now; /** * Options (see constructor). * * @var array */ private $options; /** * @param callable|null $fetch_directory fn( string $url ): ?string returning the JWKS JSON body, or null when fetching is disabled. * @param callable|null $now fn(): int returning the current unix time; defaults to time(). * @param array $options Optional keys: * 'skew' int allowed clock skew in seconds (default 300); * 'scheme' string 'https'|'http' of the incoming request (default: x-forwarded-proto, then https); * 'authority' string this site's host; when set, @authority must equal it (error authority_mismatch); * 'label' string signature label to verify (default: first label tagged web-bot-auth, else first common label); * 'jwks' array|string static JWK Set used instead of fetching (tests, pinned keys); * 'require_tag' bool reject signatures without tag="web-bot-auth" (default false); * 'allow_http_agent' bool accept http:// Signature-Agent origins (default false); * 'nonce_check' callable fn( string $nonce, ?string $agent, int $expires ): bool, true = nonce already seen. */ public function __construct( ?callable $fetch_directory = null, ?callable $now = null, array $options = array() ) { $this->fetch_directory = $fetch_directory; $this->now = $now ? $now : static function (): int { return time(); }; $this->options = array_merge( array( 'skew' => self::DEFAULT_SKEW, 'scheme' => null, 'authority' => null, 'label' => null, 'jwks' => null, 'require_tag' => false, 'allow_http_agent' => false, 'nonce_check' => null, ), $options ); } /* ------------------------------------------------------------------ */ /* Public API (contract 5.9) */ /* ------------------------------------------------------------------ */ /** * True when both Signature-Input and Signature headers are present. */ public function has_signature( RequestContext $ctx ): bool { return self::non_empty( $ctx->sig_input ) && self::non_empty( $ctx->signature ); } /** * Verify the request signature. * * @return array{verified: bool, agent: ?string, keyid: ?string, error: ?string} * 'agent' is the Signature-Agent origin (e.g. "https://chatgpt.com") whenever it * could be parsed, even if verification failed later. */ public function verify( RequestContext $ctx ): array { $agent = null; $keyid = null; if ( ! $this->has_signature( $ctx ) ) { return self::result( false, null, null, 'no_signature' ); } if ( strlen( (string) $ctx->sig_input ) > self::MAX_HEADER_LENGTH || strlen( (string) $ctx->signature ) > self::MAX_HEADER_LENGTH ) { return self::result( false, null, null, 'header_too_long' ); } // Signature-Agent first: its origin is useful to the scorer even when verification fails. $sig_agent_raw = self::non_empty( $ctx->sig_agent ) ? (string) $ctx->sig_agent : self::header_from_ctx( $ctx, 'signature-agent' ); if ( self::non_empty( $sig_agent_raw ) ) { if ( strlen( $sig_agent_raw ) > 2048 ) { return self::result( false, null, null, 'invalid_signature_agent' ); } $agent = self::parse_signature_agent( $sig_agent_raw, (bool) $this->options['allow_http_agent'] ); if ( null === $agent ) { return self::result( false, null, null, 'invalid_signature_agent' ); } } $inputs = self::sf_parse_dictionary( (string) $ctx->sig_input ); if ( null === $inputs || empty( $inputs ) ) { return self::result( false, $agent, null, 'invalid_signature_input' ); } $sigs = self::sf_parse_dictionary( (string) $ctx->signature ); if ( null === $sigs || empty( $sigs ) ) { return self::result( false, $agent, null, 'invalid_signature_header' ); } $label = $this->pick_label( $inputs, $sigs ); if ( null === $label ) { return self::result( false, $agent, null, 'label_mismatch' ); } $input = $inputs[ $label ]; if ( 'list' !== $input['type'] ) { return self::result( false, $agent, null, 'invalid_signature_input' ); } if ( 'bytes' !== $sigs[ $label ]['type'] ) { return self::result( false, $agent, null, 'invalid_signature_header' ); } $sig_bytes = $sigs[ $label ]['value']; $components = $input['value']; $params = $input['params']; // Signature parameters. $error = self::validate_params( $params, (bool) $this->options['require_tag'] ); if ( null !== $error ) { return self::result( false, $agent, null, $error ); } $keyid = (string) $params['keyid']['value']; $created = (int) $params['created']['value']; $expires = (int) $params['expires']['value']; // Time window. $now = (int) call_user_func( $this->now ); $skew = max( 0, (int) $this->options['skew'] ); if ( $created > $now + $skew ) { return self::result( false, $agent, $keyid, 'created_in_future' ); } if ( $expires <= $created ) { return self::result( false, $agent, $keyid, 'expires_before_created' ); } if ( $now > $expires + $skew ) { return self::result( false, $agent, $keyid, 'expired' ); } if ( $expires - $created > self::MAX_LIFETIME ) { return self::result( false, $agent, $keyid, 'lifetime_too_long' ); } // Covered components. $names = array(); foreach ( $components as $component ) { if ( 'string' !== $component['type'] ) { return self::result( false, $agent, $keyid, 'invalid_signature_input' ); } if ( ! empty( $component['params'] ) ) { // ;sf ;bs ;key ;req ;tr transforms are not implemented. return self::result( false, $agent, $keyid, 'unsupported_component_parameter' ); } $name = (string) $component['value']; if ( in_array( $name, $names, true ) ) { return self::result( false, $agent, $keyid, 'duplicate_component' ); } $names[] = $name; } if ( ! in_array( '@authority', $names, true ) ) { return self::result( false, $agent, $keyid, 'missing_required_component' ); } if ( null !== $agent && ! in_array( 'signature-agent', $names, true ) ) { return self::result( false, $agent, $keyid, 'missing_required_component' ); } if ( null === $agent && null === $this->options['jwks'] ) { return self::result( false, null, $keyid, 'missing_signature_agent' ); } // Public key. list( $keys, $error ) = $this->load_keys( $agent ); if ( null !== $error ) { return self::result( false, $agent, $keyid, $error ); } list( $public_key, $error ) = self::select_key( $keys, $keyid, $now, $skew ); if ( null !== $error ) { return self::result( false, $agent, $keyid, $error ); } // Signature base. $view = $this->view_from_ctx( $ctx ); $expected_authority = $this->options['authority']; if ( is_string( $expected_authority ) && '' !== $expected_authority ) { $expected_authority = self::normalize_authority( $expected_authority, (string) $view['scheme'] ); if ( null === $view['authority'] || $view['authority'] !== $expected_authority ) { return self::result( false, $agent, $keyid, 'authority_mismatch' ); } } list( $base, $error ) = self::build_signature_base( $view, $components, $params ); if ( null !== $error ) { return self::result( false, $agent, $keyid, $error ); } if ( 64 !== strlen( $sig_bytes ) ) { return self::result( false, $agent, $keyid, 'invalid_signature_length' ); } $ok = self::ed25519_verify( $sig_bytes, $base, $public_key ); if ( null === $ok ) { return self::result( false, $agent, $keyid, 'no_ed25519_backend' ); } if ( ! $ok ) { return self::result( false, $agent, $keyid, 'signature_mismatch' ); } // Optional replay protection, only after the signature proved genuine. if ( isset( $params['nonce'] ) && is_callable( $this->options['nonce_check'] ) ) { $seen = call_user_func( $this->options['nonce_check'], (string) $params['nonce']['value'], $agent, $expires ); if ( $seen ) { return self::result( false, $agent, $keyid, 'nonce_reused' ); } } return self::result( true, $agent, $keyid, null ); } /** * JWKS directory URL for an agent origin, e.g. https://chatgpt.com. */ public static function directory_url( string $agent_origin ): string { return rtrim( $agent_origin, '/' ) . self::DIRECTORY_PATH; } /** * RFC 7638 thumbprint of a raw 32-byte Ed25519 public key (base64url, no padding). */ public static function jwk_thumbprint( string $public_key ): string { return self::thumbprint_from_x( self::b64url_encode( $public_key ) ); } /* ------------------------------------------------------------------ */ /* Verification helpers */ /* ------------------------------------------------------------------ */ private static function result( bool $verified, ?string $agent, ?string $keyid, ?string $error ): array { return array( 'verified' => $verified, 'agent' => $agent, 'keyid' => $keyid, 'error' => $error, ); } private static function non_empty( $value ): bool { return is_string( $value ) && '' !== trim( $value ); } /** * Choose which signature label to verify when several are present. */ private function pick_label( array $inputs, array $sigs ): ?string { $wanted = $this->options['label']; if ( is_string( $wanted ) && '' !== $wanted ) { return ( isset( $inputs[ $wanted ], $sigs[ $wanted ] ) ) ? $wanted : null; } $first = null; foreach ( $inputs as $label => $member ) { $label = (string) $label; if ( ! isset( $sigs[ $label ] ) || 'list' !== $member['type'] ) { continue; } $tag = isset( $member['params']['tag']['value'] ) ? $member['params']['tag']['value'] : null; if ( self::EXPECTED_TAG === $tag ) { return $label; } if ( null === $first ) { $first = $label; } } return $first; } /** * Validate signature parameters. Returns an error string or null. */ private static function validate_params( array $params, bool $require_tag ): ?string { foreach ( array( 'created', 'expires' ) as $key ) { if ( ! isset( $params[ $key ] ) ) { return 'missing_' . $key; } if ( 'integer' !== $params[ $key ]['type'] || $params[ $key ]['value'] < 0 ) { return 'invalid_' . $key; } } if ( ! isset( $params['keyid'] ) ) { return 'missing_keyid'; } if ( 'string' !== $params['keyid']['type'] || '' === $params['keyid']['value'] ) { return 'invalid_keyid'; } foreach ( array( 'alg', 'nonce', 'tag' ) as $key ) { if ( isset( $params[ $key ] ) && 'string' !== $params[ $key ]['type'] ) { return 'invalid_' . $key; } } if ( isset( $params['alg'] ) && 'ed25519' !== $params['alg']['value'] ) { return 'unsupported_alg'; } if ( isset( $params['tag'] ) ) { if ( self::EXPECTED_TAG !== $params['tag']['value'] ) { return 'unexpected_tag'; } } elseif ( $require_tag ) { return 'missing_tag'; } return null; } /** * Parse the Signature-Agent header value into an origin ("https://host[:port]"). * Accepts the sf-string form ("https://chatgpt.com"), a bare token, or a bare host. */ private static function parse_signature_agent( string $raw, bool $allow_http ): ?string { $raw = trim( $raw ); $pos = 0; $item = self::sf_parse_item( $raw, $pos ); if ( null === $item || $pos !== strlen( $raw ) ) { return null; } if ( 'string' !== $item['type'] && 'token' !== $item['type'] ) { return null; } $value = trim( (string) $item['value'] ); if ( '' === $value ) { return null; } if ( false === strpos( $value, '://' ) && preg_match( '/^[A-Za-z0-9.-]+(:[0-9]{1,5})?$/', $value ) ) { $value = 'https://' . $value; } // phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- pure PHP class, unit-tested without WordPress. $parts = parse_url( $value ); if ( ! is_array( $parts ) || empty( $parts['scheme'] ) || empty( $parts['host'] ) ) { return null; } $scheme = strtolower( (string) $parts['scheme'] ); if ( 'https' !== $scheme && ( 'http' !== $scheme || ! $allow_http ) ) { return null; } if ( isset( $parts['user'] ) || isset( $parts['pass'] ) || isset( $parts['query'] ) || isset( $parts['fragment'] ) ) { return null; } if ( isset( $parts['path'] ) && '' !== $parts['path'] && '/' !== $parts['path'] ) { return null; } $host = strtolower( (string) $parts['host'] ); // No IP literals, no bracketed IPv6, no explicit port: the site fetches a URL derived // from this origin, so it must name a public host (security review 2026-10-12). if ( isset( $parts['port'] ) || '[' === $host[0] || false !== filter_var( $host, FILTER_VALIDATE_IP ) ) { return null; } $origin = $scheme . '://' . $host; return $origin; } /** * Load the JWK Set: static option first, otherwise the injected fetcher. * * @return array{0: ?array, 1: ?string} [keys, error] */ private function load_keys( ?string $agent ): array { $jwks = null; if ( null !== $this->options['jwks'] ) { $jwks = is_string( $this->options['jwks'] ) ? json_decode( $this->options['jwks'], true ) : $this->options['jwks']; } else { if ( null === $agent ) { return array( null, 'missing_signature_agent' ); } if ( null === $this->fetch_directory ) { return array( null, 'directory_fetch_disabled' ); } $body = call_user_func( $this->fetch_directory, self::directory_url( $agent ) ); if ( ! is_string( $body ) || '' === trim( $body ) ) { return array( null, 'directory_unavailable' ); } $jwks = json_decode( $body, true ); } if ( ! is_array( $jwks ) ) { return array( null, 'directory_invalid' ); } if ( isset( $jwks['keys'] ) && is_array( $jwks['keys'] ) ) { $keys = $jwks['keys']; } elseif ( isset( $jwks['kty'] ) ) { $keys = array( $jwks ); } else { $keys = array(); } $keys = array_values( array_filter( $keys, 'is_array' ) ); if ( empty( $keys ) ) { return array( null, 'directory_invalid' ); } return array( $keys, null ); } /** * Pick the key matching keyid (kid, then RFC 7638 thumbprint, then single-key fallback) * and return the raw 32-byte public key. * * @return array{0: ?string, 1: ?string} [public_key, error] */ private static function select_key( array $keys, string $keyid, int $now, int $skew ): array { $match = null; foreach ( $keys as $key ) { if ( isset( $key['kid'] ) && is_scalar( $key['kid'] ) && (string) $key['kid'] === $keyid ) { $match = $key; break; } } if ( null === $match ) { foreach ( $keys as $key ) { if ( ! self::is_ed25519_jwk( $key ) ) { continue; } $x = (string) $key['x']; if ( self::thumbprint_from_x( $x ) === $keyid ) { $match = $key; break; } $raw = self::b64url_decode( $x ); if ( null !== $raw && self::jwk_thumbprint( $raw ) === $keyid ) { $match = $key; break; } } } if ( null === $match && 1 === count( $keys ) ) { $match = $keys[0]; } if ( null === $match ) { return array( null, 'key_not_found' ); } if ( ! self::is_ed25519_jwk( $match ) ) { return array( null, 'unsupported_key' ); } $public_key = self::b64url_decode( (string) $match['x'] ); if ( null === $public_key || 32 !== strlen( $public_key ) ) { return array( null, 'invalid_key' ); } if ( isset( $match['exp'] ) && is_numeric( $match['exp'] ) && $now > (int) $match['exp'] + $skew ) { return array( null, 'key_expired' ); } if ( isset( $match['nbf'] ) && is_numeric( $match['nbf'] ) && (int) $match['nbf'] > $now + $skew ) { return array( null, 'key_not_yet_valid' ); } return array( $public_key, null ); } private static function is_ed25519_jwk( array $key ): bool { return isset( $key['kty'], $key['crv'], $key['x'] ) && 'OKP' === $key['kty'] && 'Ed25519' === $key['crv'] && is_string( $key['x'] ) && '' !== $key['x']; } private static function thumbprint_from_x( string $x ): string { $json = '{"crv":"Ed25519","kty":"OKP","x":"' . $x . '"}'; return self::b64url_encode( hash( 'sha256', $json, true ) ); } /** * Build the request "view" (method, scheme, authority, path, query, headers) * from a RequestContext (contract 5.1). */ private function view_from_ctx( RequestContext $ctx ): array { $headers = array(); foreach ( (array) $ctx->headers as $name => $value ) { $name = strtolower( (string) $name ); if ( is_array( $value ) ) { $parts = array(); foreach ( $value as $part ) { $parts[] = trim( is_scalar( $part ) ? (string) $part : '' ); } $value = implode( ', ', $parts ); } elseif ( ! is_string( $value ) ) { $value = is_scalar( $value ) ? (string) $value : ''; } $headers[ $name ] = trim( $value ); } if ( ! isset( $headers['signature-agent'] ) && self::non_empty( $ctx->sig_agent ) ) { $headers['signature-agent'] = trim( (string) $ctx->sig_agent ); } $scheme = $this->resolve_scheme( $headers ); $authority = isset( $headers['host'] ) && '' !== $headers['host'] ? self::normalize_authority( $headers['host'], $scheme ) : null; $path = (string) $ctx->path; $query = null; $q = strpos( $path, '?' ); if ( false !== $q ) { $query = substr( $path, $q + 1 ); $path = substr( $path, 0, $q ); } if ( '' === $path ) { $path = '/'; } return array( 'method' => (string) $ctx->method, 'scheme' => $scheme, 'authority' => $authority, 'path' => $path, 'query' => $query, 'headers' => $headers, ); } private function resolve_scheme( array $headers ): string { $opt = $this->options['scheme']; if ( is_string( $opt ) ) { $opt = strtolower( $opt ); if ( 'http' === $opt || 'https' === $opt ) { return $opt; } } if ( isset( $headers['x-forwarded-proto'] ) ) { $first = strtolower( trim( explode( ',', $headers['x-forwarded-proto'] )[0] ) ); if ( 'http' === $first || 'https' === $first ) { return $first; } } return 'https'; } /** * Lowercase host and drop the default port (RFC 9421 2.2.3 / RFC 9110 4.2.3). */ private static function normalize_authority( string $host, string $scheme ): string { $host = strtolower( trim( $host ) ); if ( 'https' === $scheme && ':443' === substr( $host, -4 ) ) { $host = substr( $host, 0, -4 ); } elseif ( 'http' === $scheme && ':80' === substr( $host, -3 ) ) { $host = substr( $host, 0, -3 ); } return $host; } private static function header_from_ctx( RequestContext $ctx, string $name ): ?string { $headers = (array) $ctx->headers; if ( ! isset( $headers[ $name ] ) ) { $lower = array_change_key_case( $headers, CASE_LOWER ); if ( ! isset( $lower[ $name ] ) ) { return null; } $headers = $lower; } $value = $headers[ $name ]; if ( is_array( $value ) ) { $value = implode( ', ', array_map( 'trim', array_map( 'strval', $value ) ) ); } return is_scalar( $value ) ? trim( (string) $value ) : null; } /** * Build the RFC 9421 signature base from a request view. * * @param array $view See view_from_ctx(). * @param array $components Parsed inner-list items (type string, no params). * @param array $params Parsed signature parameters (ordered). * @return array{0: ?string, 1: ?string} [base, error] */ private static function build_signature_base( array $view, array $components, array $params ): array { $lines = array(); foreach ( $components as $component ) { $name = (string) $component['value']; list( $value, $error ) = self::component_value( $view, $name ); if ( null !== $error ) { return array( null, $error ); } $lines[] = self::sf_serialize_item( $component ) . ': ' . $value; } $lines[] = '"@signature-params": ' . self::sf_serialize_inner_list( $components, $params ); return array( implode( "\n", $lines ), null ); } /** * Component value for the signature base. * * @return array{0: ?string, 1: ?string} [value, error] */ private static function component_value( array $view, string $name ): array { if ( '' !== $name && '@' === $name[0] ) { switch ( $name ) { case '@method': $method = strtoupper( (string) $view['method'] ); return '' === $method ? array( null, 'component_unavailable:@method' ) : array( $method, null ); case '@authority': $authority = $view['authority']; return ( null === $authority || '' === $authority ) ? array( null, 'component_unavailable:@authority' ) : array( $authority, null ); case '@scheme': return array( (string) $view['scheme'], null ); case '@path': return array( (string) $view['path'], null ); case '@query': return array( '?' . (string) ( $view['query'] ?? '' ), null ); case '@target-uri': $authority = $view['authority']; if ( null === $authority || '' === $authority ) { return array( null, 'component_unavailable:@target-uri' ); } $uri = (string) $view['scheme'] . '://' . $authority . (string) $view['path']; if ( null !== $view['query'] ) { $uri .= '?' . (string) $view['query']; } return array( $uri, null ); default: return array( null, 'unsupported_component:' . $name ); } } if ( ! preg_match( '/^[a-z0-9!#$%&\'*+.^_`|~-]+$/', $name ) ) { return array( null, 'unsupported_component:' . $name ); } if ( ! isset( $view['headers'][ $name ] ) || '' === $view['headers'][ $name ] ) { return array( null, 'component_unavailable:' . $name ); } return array( (string) $view['headers'][ $name ], null ); } /* ------------------------------------------------------------------ */ /* Ed25519 backends */ /* ------------------------------------------------------------------ */ /** * @return bool|null True/false for the verification result, null when no backend exists. */ private static function ed25519_verify( string $signature, string $message, string $public_key ): ?bool { if ( function_exists( 'sodium_crypto_sign_verify_detached' ) ) { try { return (bool) \sodium_crypto_sign_verify_detached( $signature, $message, $public_key ); } catch ( \Throwable $e ) { return false; } } if ( class_exists( '\ParagonIE_Sodium_Compat' ) ) { try { return (bool) \ParagonIE_Sodium_Compat::crypto_sign_verify_detached( $signature, $message, $public_key ); } catch ( \Throwable $e ) { return false; } } return null; } /* ------------------------------------------------------------------ */ /* base64url */ /* ------------------------------------------------------------------ */ private static function b64url_encode( string $bytes ): string { // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- base64url JWK member / RFC 8941 byte sequence, not obfuscation. return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' ); } private static function b64url_decode( string $text ): ?string { $text = strtr( trim( $text ), '-_', '+/' ); if ( '' === $text || ! preg_match( '/^[A-Za-z0-9+\/]+=*$/', $text ) ) { return null; } $text = rtrim( $text, '=' ); $pad = strlen( $text ) % 4; if ( 1 === $pad ) { return null; } if ( 0 !== $pad ) { $text .= str_repeat( '=', 4 - $pad ); } // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- base64url JWK member / RFC 8941 byte sequence, not obfuscation. $bytes = base64_decode( $text, true ); return ( false === $bytes ) ? null : $bytes; } /* ------------------------------------------------------------------ */ /* Minimal RFC 8941 structured-field parser */ /* */ /* Parsed values are arrays: ['type' => string|token|integer|decimal| */ /* bytes|boolean|list, 'value' => mixed, 'params' => [key => bare]]. */ /* Every parse function returns null on a syntax error. */ /* ------------------------------------------------------------------ */ private static function sf_parse_dictionary( string $input ): ?array { $pos = 0; $len = strlen( $input ); $dict = array(); self::sf_skip_ows( $input, $pos ); while ( $pos < $len ) { $key = self::sf_parse_key( $input, $pos ); if ( null === $key ) { return null; } if ( $pos < $len && '=' === $input[ $pos ] ) { $pos++; $member = self::sf_parse_item_or_inner_list( $input, $pos ); } else { $params = self::sf_parse_parameters( $input, $pos ); $member = ( null === $params ) ? null : array( 'type' => 'boolean', 'value' => true, 'params' => $params, ); } if ( null === $member ) { return null; } $dict[ $key ] = $member; self::sf_skip_ows( $input, $pos ); if ( $pos >= $len ) { return $dict; } if ( ',' !== $input[ $pos ] ) { return null; } $pos++; self::sf_skip_ows( $input, $pos ); if ( $pos >= $len ) { return null; // Trailing comma. } } return $dict; } private static function sf_parse_item_or_inner_list( string $input, int &$pos ): ?array { if ( $pos < strlen( $input ) && '(' === $input[ $pos ] ) { return self::sf_parse_inner_list( $input, $pos ); } return self::sf_parse_item( $input, $pos ); } private static function sf_parse_inner_list( string $input, int &$pos ): ?array { $len = strlen( $input ); if ( $pos >= $len || '(' !== $input[ $pos ] ) { return null; } $pos++; $items = array(); while ( $pos < $len ) { self::sf_skip_sp( $input, $pos ); if ( $pos >= $len ) { return null; } if ( ')' === $input[ $pos ] ) { $pos++; $params = self::sf_parse_parameters( $input, $pos ); if ( null === $params ) { return null; } return array( 'type' => 'list', 'value' => $items, 'params' => $params, ); } $item = self::sf_parse_item( $input, $pos ); if ( null === $item ) { return null; } $items[] = $item; if ( $pos >= $len || ( ' ' !== $input[ $pos ] && ')' !== $input[ $pos ] ) ) { return null; } } return null; } private static function sf_parse_item( string $input, int &$pos ): ?array { $bare = self::sf_parse_bare_item( $input, $pos ); if ( null === $bare ) { return null; } $params = self::sf_parse_parameters( $input, $pos ); if ( null === $params ) { return null; } $bare['params'] = $params; return $bare; } private static function sf_parse_bare_item( string $input, int &$pos ): ?array { if ( $pos >= strlen( $input ) ) { return null; } $c = $input[ $pos ]; $o = ord( $c ); if ( '"' === $c ) { return self::sf_parse_string( $input, $pos ); } if ( ':' === $c ) { return self::sf_parse_bytes( $input, $pos ); } if ( '?' === $c ) { return self::sf_parse_boolean( $input, $pos ); } if ( '-' === $c || ( $o >= 0x30 && $o <= 0x39 ) ) { return self::sf_parse_number( $input, $pos ); } if ( '*' === $c || ( $o >= 0x41 && $o <= 0x5A ) || ( $o >= 0x61 && $o <= 0x7A ) ) { return self::sf_parse_token( $input, $pos ); } return null; } private static function sf_parse_parameters( string $input, int &$pos ): ?array { $len = strlen( $input ); $params = array(); while ( $pos < $len && ';' === $input[ $pos ] ) { $pos++; self::sf_skip_sp( $input, $pos ); $key = self::sf_parse_key( $input, $pos ); if ( null === $key ) { return null; } if ( $pos < $len && '=' === $input[ $pos ] ) { $pos++; $value = self::sf_parse_bare_item( $input, $pos ); if ( null === $value ) { return null; } } else { $value = array( 'type' => 'boolean', 'value' => true, ); } $params[ $key ] = $value; } return $params; } private static function sf_parse_key( string $input, int &$pos ): ?string { if ( $pos >= strlen( $input ) ) { return null; } $o = ord( $input[ $pos ] ); if ( '*' !== $input[ $pos ] && ( $o < 0x61 || $o > 0x7A ) ) { return null; } $n = strspn( $input, 'abcdefghijklmnopqrstuvwxyz0123456789_-.*', $pos ); $key = substr( $input, $pos, $n ); $pos += $n; return $key; } private static function sf_parse_string( string $input, int &$pos ): ?array { $len = strlen( $input ); $pos++; // Opening quote. $out = ''; while ( $pos < $len ) { $c = $input[ $pos ]; if ( '\\' === $c ) { $pos++; if ( $pos >= $len ) { return null; } $n = $input[ $pos ]; if ( '"' !== $n && '\\' !== $n ) { return null; } $out .= $n; $pos++; continue; } if ( '"' === $c ) { $pos++; return array( 'type' => 'string', 'value' => $out, ); } $o = ord( $c ); if ( $o < 0x20 || $o > 0x7E ) { return null; } $out .= $c; $pos++; } return null; // Unterminated string. } private static function sf_parse_token( string $input, int &$pos ): ?array { $n = strspn( $input, 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&\'*+-.^_`|~:/', $pos ); $token = substr( $input, $pos, $n ); $pos += $n; return array( 'type' => 'token', 'value' => $token, ); } private static function sf_parse_bytes( string $input, int &$pos ): ?array { $pos++; // Opening colon. $end = strpos( $input, ':', $pos ); if ( false === $end ) { return null; } $b64 = substr( $input, $pos, $end - $pos ); $pos = $end + 1; if ( '' !== $b64 && ! preg_match( '/^[A-Za-z0-9+\/]+=*$/', $b64 ) ) { return null; } $b64 = rtrim( $b64, '=' ); $pad = strlen( $b64 ) % 4; if ( 1 === $pad ) { return null; } if ( 0 !== $pad ) { $b64 .= str_repeat( '=', 4 - $pad ); } // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- base64url JWK member / RFC 8941 byte sequence, not obfuscation. $bytes = ( '' === $b64 ) ? '' : base64_decode( $b64, true ); if ( false === $bytes ) { return null; } return array( 'type' => 'bytes', 'value' => $bytes, ); } private static function sf_parse_boolean( string $input, int &$pos ): ?array { $pos++; // Question mark. if ( $pos >= strlen( $input ) ) { return null; } $c = $input[ $pos ]; if ( '1' !== $c && '0' !== $c ) { return null; } $pos++; return array( 'type' => 'boolean', 'value' => ( '1' === $c ), ); } private static function sf_parse_number( string $input, int &$pos ): ?array { $len = strlen( $input ); $start = $pos; if ( '-' === $input[ $pos ] ) { $pos++; } $digits = strspn( $input, '0123456789', $pos ); if ( 0 === $digits ) { return null; } $pos += $digits; if ( $pos < $len && '.' === $input[ $pos ] ) { if ( $digits > 12 ) { return null; } $pos++; $frac = strspn( $input, '0123456789', $pos ); if ( $frac < 1 || $frac > 3 ) { return null; } $pos += $frac; return array( 'type' => 'decimal', 'value' => (float) substr( $input, $start, $pos - $start ), ); } if ( $digits > 15 ) { return null; } return array( 'type' => 'integer', 'value' => (int) substr( $input, $start, $pos - $start ), ); } private static function sf_skip_sp( string $input, int &$pos ): void { $len = strlen( $input ); while ( $pos < $len && ' ' === $input[ $pos ] ) { $pos++; } } private static function sf_skip_ows( string $input, int &$pos ): void { $len = strlen( $input ); while ( $pos < $len && ( ' ' === $input[ $pos ] || "\t" === $input[ $pos ] ) ) { $pos++; } } /* ------------------------------------------------------------------ */ /* Minimal RFC 8941 serializer (used for @signature-params and tests) */ /* ------------------------------------------------------------------ */ private static function sf_serialize_inner_list( array $items, array $params ): string { $parts = array(); foreach ( $items as $item ) { $parts[] = self::sf_serialize_item( $item ); } return '(' . implode( ' ', $parts ) . ')' . self::sf_serialize_params( $params ); } private static function sf_serialize_item( array $item ): string { $params = isset( $item['params'] ) && is_array( $item['params'] ) ? $item['params'] : array(); return self::sf_serialize_bare( $item ) . self::sf_serialize_params( $params ); } private static function sf_serialize_params( array $params ): string { $out = ''; foreach ( $params as $key => $value ) { $out .= ';' . (string) $key; if ( 'boolean' === $value['type'] && true === $value['value'] ) { continue; } $out .= '=' . self::sf_serialize_bare( $value ); } return $out; } private static function sf_serialize_bare( array $item ): string { switch ( $item['type'] ) { case 'string': return '"' . str_replace( array( '\\', '"' ), array( '\\\\', '\\"' ), (string) $item['value'] ) . '"'; case 'token': return (string) $item['value']; case 'integer': return (string) (int) $item['value']; case 'decimal': $text = rtrim( number_format( (float) $item['value'], 3, '.', '' ), '0' ); if ( '.' === substr( $text, -1 ) ) { $text .= '0'; } return $text; case 'bytes': // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- base64url JWK member / RFC 8941 byte sequence, not obfuscation. return ':' . base64_encode( (string) $item['value'] ) . ':'; case 'boolean': return $item['value'] ? '?1' : '?0'; } return ''; } }