%s` * conditional update): the OAuth/API-key work package appends that as a new * method once this class exists, so the atomic claim and this package's * plain insert/read/prune never conflict in the same method body. * * Fails closed exactly like {@see ConnectionStore}. * * @phpstan-type McpOAuthCodeRow array{ * code_hash: string, * client_id_hash: string, * user_id: int, * redirect_uri: string, * code_challenge: string, * code_challenge_method: string, * permission_level: string, * resource: string, * expires_at: string, * used_at: string|null, * connection_id: int|null, * created_at: string * } * * @since 2.8.2 */ final class OAuthCodeStore { /** How long a code row is kept after it expired, used or not. */ private const RETENTION_AFTER_EXPIRY_SECONDS = DAY_IN_SECONDS; /** @var \wpdb */ private $wpdb; /** @var string */ private $table; /** * @param \wpdb|null $wpdb Defaults to the global $wpdb. */ public function __construct( ?\wpdb $wpdb = null ) { $this->wpdb = $wpdb instanceof \wpdb ? $wpdb : $GLOBALS['wpdb']; $this->table = $this->wpdb->prefix . 'aipt_mcp_oauth_codes'; } /** * Fully-qualified table name. * * @return string */ public function table(): string { return $this->table; } /** * Insert a newly minted authorization code row. * * @param array{code_hash:string,client_id_hash:string,user_id:int,redirect_uri:string,code_challenge:string,code_challenge_method?:string,permission_level:string,resource?:string,expires_at:string,now?:string} $data Code fields. * @return bool */ public function insert( array $data ): bool { $wpdb = $this->wpdb; $code_hash = isset( $data['code_hash'] ) ? (string) $data['code_hash'] : ''; $client_id_hash = isset( $data['client_id_hash'] ) ? (string) $data['client_id_hash'] : ''; $user_id = isset( $data['user_id'] ) ? (int) $data['user_id'] : 0; $expires_at = isset( $data['expires_at'] ) ? (string) $data['expires_at'] : ''; if ( '' === $code_hash || '' === $client_id_hash || $user_id <= 0 || '' === $expires_at ) { return false; } $now = isset( $data['now'] ) ? (string) $data['now'] : gmdate( 'Y-m-d H:i:s' ); $result = $wpdb->insert( $this->table, array( 'code_hash' => $code_hash, 'client_id_hash' => $client_id_hash, 'user_id' => $user_id, 'redirect_uri' => isset( $data['redirect_uri'] ) ? (string) $data['redirect_uri'] : '', 'code_challenge' => isset( $data['code_challenge'] ) ? (string) $data['code_challenge'] : '', 'code_challenge_method' => isset( $data['code_challenge_method'] ) ? (string) $data['code_challenge_method'] : 'S256', 'permission_level' => isset( $data['permission_level'] ) ? (string) $data['permission_level'] : '', 'resource' => isset( $data['resource'] ) ? (string) $data['resource'] : '', 'expires_at' => $expires_at, 'created_at' => $now, ), array( '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); return false; } return true; } /** * Read a code row by its hash. * * @param string $code_hash sha256(code). * @return array|null * @phpstan-return McpOAuthCodeRow|null */ public function findByHash( string $code_hash ): ?array { $wpdb = $this->wpdb; if ( '' === $code_hash ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table} WHERE code_hash = %s", $code_hash ), ARRAY_A ); if ( is_array( $row ) ) { return $this->mapRow( $row ); } if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); } return null; } /** * Atomically redeem an authorization code: exactly one statement claims * the row, so two concurrent redemptions of the same code can never both * succeed. Zero rows affected means either the code does not exist, is * already used (a replay), or has expired; the caller cannot tell those * apart from this return value alone and must treat all three as "not * redeemable" (a replay additionally revokes the connection minted from * this code, per the caller's own policy). * * @param string $code_hash sha256(code) — the row to claim. * @param string $now UTC datetime stamped as `used_at` and compared against `expires_at`. * @return bool True only when this call claimed exactly one row. */ public function claim( string $code_hash, string $now ): bool { $wpdb = $this->wpdb; if ( '' === $code_hash ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET used_at = %s WHERE code_hash = %s AND used_at IS NULL AND expires_at > %s", $now, $code_hash, $now ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return false; } return (int) $affected > 0; } /** * Same atomic single-statement claim as {@see claim()}, but reports a * database error distinctly from a genuine lost race, instead of * collapsing both into `false`. A caller that cannot tell them apart * ends up treating a transient write failure as a detected replay (see * the OAuth/API-key work package's caller), which punitively revokes a * connection that never actually redeemed anything twice. * * @param string $code_hash sha256(code) — the row to claim. * @param string $now UTC datetime stamped as `used_at` and compared against `expires_at`. * @return bool|null True when this call claimed exactly one row; false when * the row was already used/expired/missing (zero rows * matched, no database error); null on a database error. */ public function claimResult( string $code_hash, string $now ): ?bool { $wpdb = $this->wpdb; if ( '' === $code_hash ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET used_at = %s WHERE code_hash = %s AND used_at IS NULL AND expires_at > %s", $now, $code_hash, $now ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return null; } return (int) $affected > 0; } /** * Record the connection a redeemed code's tokens were issued on, so a * later replay of the code revokes exactly that connection. * * @param string $code_hash sha256(code). * @param int $connection_id The connection the code minted or reused. * @return bool False on invalid input or a database error, the cases a * caller must not hand out credentials for. */ public function recordConnection( string $code_hash, int $connection_id ): bool { $wpdb = $this->wpdb; if ( '' === $code_hash || $connection_id <= 0 ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET connection_id = %d WHERE code_hash = %s", $connection_id, $code_hash ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return false; } return true; } /** * Delete codes that expired more than {@see RETENTION_AFTER_EXPIRY_SECONDS} * before $now, used or not, chunked with LIMIT. A used code stays until * then, so presenting it again is still recognised as a replay and * revokes the connection it minted (RFC 6749 section 4.1.2), whenever * the daily cleanup happens to run. * * @param string $now Current UTC datetime. * @param int $limit Max rows deleted by this call. * @return int Number of rows deleted; 0 on a database error. */ public function deleteExpired( string $now, int $limit ): int { $wpdb = $this->wpdb; $now_ts = strtotime( $now ); $now_ts = false !== $now_ts ? $now_ts : time(); $cutoff = gmdate( 'Y-m-d H:i:s', $now_ts - self::RETENTION_AFTER_EXPIRY_SECONDS ); $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table} WHERE expires_at < %s LIMIT %d", $cutoff, max( 1, $limit ) ) ); if ( false === $deleted ) { $this->logError( __FUNCTION__ ); return 0; } return (int) $deleted; } /** * Normalize a raw row. * * @param array $row Raw row from $wpdb. * @return array * @phpstan-return McpOAuthCodeRow */ private function mapRow( array $row ): array { return array( 'code_hash' => (string) ( $row['code_hash'] ?? '' ), 'client_id_hash' => (string) ( $row['client_id_hash'] ?? '' ), 'user_id' => (int) ( $row['user_id'] ?? 0 ), 'redirect_uri' => (string) ( $row['redirect_uri'] ?? '' ), 'code_challenge' => (string) ( $row['code_challenge'] ?? '' ), 'code_challenge_method' => (string) ( $row['code_challenge_method'] ?? 'S256' ), 'permission_level' => (string) ( $row['permission_level'] ?? '' ), 'resource' => (string) ( $row['resource'] ?? '' ), 'expires_at' => (string) ( $row['expires_at'] ?? '' ), 'used_at' => isset( $row['used_at'] ) ? (string) $row['used_at'] : null, 'connection_id' => isset( $row['connection_id'] ) && (int) $row['connection_id'] > 0 ? (int) $row['connection_id'] : null, 'created_at' => (string) ( $row['created_at'] ?? '' ), ); } /** * @param string $method Calling method name, for the log line. * @return void */ private function logError( string $method ): void { $wpdb = $this->wpdb; } }