wpdb = $wpdb instanceof \wpdb ? $wpdb : $GLOBALS['wpdb']; $this->table = $this->wpdb->prefix . 'aipt_mcp_tokens'; } /** * Fully-qualified table name. * * @return string */ public function table(): string { return $this->table; } /** * Insert a newly minted token row. * * @param array{connection_id:int,token_hash:string,token_type:string,paired_token_id?:int,permission_level?:string,expires_at?:string|null,now?:string} $data Token fields. * @return int|null New row id, or null when the input is invalid or the insert failed. */ public function insert( array $data ): ?int { $wpdb = $this->wpdb; $connection_id = isset( $data['connection_id'] ) ? (int) $data['connection_id'] : 0; $token_hash = isset( $data['token_hash'] ) ? (string) $data['token_hash'] : ''; $token_type = isset( $data['token_type'] ) ? (string) $data['token_type'] : ''; if ( $connection_id <= 0 || '' === $token_hash ) { return null; } if ( ! in_array( $token_type, array( self::TOKEN_TYPE_API_KEY, self::TOKEN_TYPE_OAUTH_ACCESS, self::TOKEN_TYPE_OAUTH_REFRESH ), true ) ) { return null; } $now = isset( $data['now'] ) ? (string) $data['now'] : gmdate( 'Y-m-d H:i:s' ); $expires_at = array_key_exists( 'expires_at', $data ) && null !== $data['expires_at'] ? (string) $data['expires_at'] : null; $result = $wpdb->insert( $this->table, array( 'connection_id' => $connection_id, 'token_hash' => $token_hash, 'token_type' => $token_type, 'paired_token_id' => isset( $data['paired_token_id'] ) ? (int) $data['paired_token_id'] : 0, 'permission_level' => isset( $data['permission_level'] ) ? (string) $data['permission_level'] : '', 'expires_at' => $expires_at, 'created_at' => $now, ), array( '%d', '%s', '%s', '%d', '%s', '%s', '%s' ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); return null; } return (int) $wpdb->insert_id; } /** * Read a token row by id. * * @param int $id Row id. * @return array|null * @phpstan-return McpTokenRow|null */ public function find( int $id ): ?array { $wpdb = $this->wpdb; if ( $id <= 0 ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table} WHERE id = %d", $id ), ARRAY_A ); if ( is_array( $row ) ) { return $this->mapRow( $row ); } if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); } return null; } /** * Read a token row by its hash. * * @param string $token_hash Hash of the raw token. * @return array|null * @phpstan-return McpTokenRow|null */ public function findByHash( string $token_hash ): ?array { $wpdb = $this->wpdb; if ( '' === $token_hash ) { return null; } $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$this->table} WHERE token_hash = %s", $token_hash ), ARRAY_A ); if ( is_array( $row ) ) { return $this->mapRow( $row ); } if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); } return null; } /** * List every token (any type, any state) belonging to a connection. * * @param int $connection_id Connection id. * @return array> * @phpstan-return array */ public function listForConnection( int $connection_id ): array { $wpdb = $this->wpdb; if ( $connection_id <= 0 ) { return array(); } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$this->table} WHERE connection_id = %d ORDER BY created_at DESC, id DESC", $connection_id ), ARRAY_A ); if ( '' !== $wpdb->last_error ) { $this->logError( __FUNCTION__ ); return array(); } return array_map( array( $this, 'mapRow' ), is_array( $rows ) ? $rows : array() ); } /** * Revoke one token. No-op (returns false) when it is already revoked. * * @param int $id Row id. * @param string $reason One of the REVOKE_REASON_* constants. * @param string $now UTC datetime to stamp as revoked_at. * @return bool True when this call actually revoked the row. */ public function revoke( int $id, string $reason, string $now ): bool { $wpdb = $this->wpdb; if ( $id <= 0 ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET revoked_at = %s, revoke_reason = %s WHERE id = %d AND revoked_at IS NULL", $now, $reason, $id ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return false; } return (int) $affected > 0; } /** * Revoke every not-yet-revoked token belonging to a connection in one * statement (used when the connection itself is revoked). * * @param int $connection_id Connection id. * @param string $reason One of the REVOKE_REASON_* constants. * @param string $now UTC datetime to stamp as revoked_at. * @return int Number of rows revoked by this call; 0 on a database error. */ public function revokeForConnection( int $connection_id, string $reason, string $now ): int { $wpdb = $this->wpdb; if ( $connection_id <= 0 ) { return 0; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET revoked_at = %s, revoke_reason = %s WHERE connection_id = %d AND revoked_at IS NULL", $now, $reason, $connection_id ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return 0; } return (int) $affected; } /** * Atomically rotate a refresh token: exactly one statement revokes it * with reason 'rotated', so two concurrent rotations of the same token * can never both succeed. The caller mints the replacement pair only * after this returns true; zero rows affected means the token was * already revoked (by a prior rotation, or directly) and the caller must * not mint anything. * * @param int $token_id Row id of the refresh token being rotated. * @param string $now UTC datetime stamped as `revoked_at`. * @return bool True only when this call rotated exactly one row. */ public function rotate( int $token_id, string $now ): bool { $wpdb = $this->wpdb; if ( $token_id <= 0 ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET revoked_at = %s, revoke_reason = %s WHERE id = %d AND revoked_at IS NULL", $now, self::REVOKE_REASON_ROTATED, $token_id ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return false; } return (int) $affected > 0; } /** * Same atomic single-statement rotation as {@see rotate()}, 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 refresh-token * reuse (see the OAuth/API-key work package's caller), which punitively * revokes a connection that was never actually reused. * * @param int $token_id Row id of the refresh token being rotated. * @param string $now UTC datetime stamped as `revoked_at`. * @return bool|null True when this call rotated exactly one row; false * when the row was already revoked/rotated/missing * (zero rows matched, no database error); null on a * database error. */ public function rotateResult( int $token_id, string $now ): ?bool { $wpdb = $this->wpdb; if ( $token_id <= 0 ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET revoked_at = %s, revoke_reason = %s WHERE id = %d AND revoked_at IS NULL", $now, self::REVOKE_REASON_ROTATED, $token_id ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return null; } return (int) $affected > 0; } /** * Claim the one compensating reissue a rotated refresh token is allowed * during its reuse-detection grace window. One statement marks * `grace_reused_at` only when it is still NULL, so of any number of * concurrent or sequential presentations of the same rotated token, * exactly one can ever claim it; every other presentation must be * treated as genuine reuse instead of minting another independent token * pair. * * @param int $token_id Row id of the already-rotated refresh token. * @param string $now UTC datetime stamped as `grace_reused_at`. * @return bool|null True when this call claimed the grace reissue; false * when it was already claimed (no database error); * null on a database error. */ public function claimGraceReuse( int $token_id, string $now ): ?bool { $wpdb = $this->wpdb; if ( $token_id <= 0 ) { return false; } $affected = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET grace_reused_at = %s WHERE id = %d AND revoke_reason = %s AND grace_reused_at IS NULL", $now, $token_id, self::REVOKE_REASON_ROTATED ) ); if ( false === $affected ) { $this->logError( __FUNCTION__ ); return null; } return (int) $affected > 0; } /** * Link an access/refresh token pair after both rows exist: each one's id * is only known once it has been inserted, so pairing is a follow-up * update rather than part of {@see insert()}. Called once per side (the * caller links both directions). * * @param int $id Row id to update. * @param int $pairedTokenId The other token's row id. * @return bool */ public function setPairedTokenId( int $id, int $pairedTokenId ): bool { $wpdb = $this->wpdb; if ( $id <= 0 || $pairedTokenId <= 0 ) { return false; } $result = $wpdb->update( $this->table, array( 'paired_token_id' => $pairedTokenId ), array( 'id' => $id ), array( '%d' ), array( '%d' ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); return false; } return true; } /** * Record that a token was just used, throttled to at most one write per * 60 seconds for the same row. * * @param int $id Row id. * @param string $now Current UTC datetime. * @return void */ public function touchLastUsed( int $id, string $now ): void { $wpdb = $this->wpdb; if ( $id <= 0 ) { return; } $cutoff_ts = strtotime( $now ) - self::TOUCH_THROTTLE_SECONDS; $cutoff = false !== $cutoff_ts ? gmdate( 'Y-m-d H:i:s', $cutoff_ts ) : $now; $result = $wpdb->query( $wpdb->prepare( "UPDATE {$this->table} SET last_used_at = %s WHERE id = %d AND (last_used_at IS NULL OR last_used_at < %s)", $now, $id, $cutoff ) ); if ( false === $result ) { $this->logError( __FUNCTION__ ); } } /** * Delete stale token rows, chunked with LIMIT. A row is stale when ANY * of these hold: * * - `expires_at` is more than 1 day in the past (any token_type, * any revoke_reason, including never revoked); * - revoked with reason 'revoked' or 'connection_revoked' more than 7 * days ago; * - revoked with reason 'rotated' AND its own `expires_at` has passed * by more than 1 day (kept alive past revocation so refresh-token * reuse can still be detected during its natural lifetime, then for * the same 1-day grace every token gets past expiry). * * A non-revoked api_key (expires_at NULL, revoked_at NULL) can never * match any branch and is never deleted. * * @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 deleteStale( string $now, int $limit ): int { $wpdb = $this->wpdb; $now_ts = strtotime( $now ); $now_ts = false !== $now_ts ? $now_ts : time(); $expired_cutoff = gmdate( 'Y-m-d H:i:s', $now_ts - self::EXPIRED_GRACE_SECONDS ); $revoked_cutoff = gmdate( 'Y-m-d H:i:s', $now_ts - self::REVOKED_GRACE_SECONDS ); $rotated_cutoff = gmdate( 'Y-m-d H:i:s', $now_ts - self::ROTATED_GRACE_SECONDS ); $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM {$this->table} WHERE (expires_at IS NOT NULL AND expires_at < %s) OR (revoke_reason IN (%s, %s) AND revoked_at IS NOT NULL AND revoked_at < %s) OR (revoke_reason = %s AND expires_at IS NOT NULL AND expires_at < %s) LIMIT %d", $expired_cutoff, self::REVOKE_REASON_REVOKED, self::REVOKE_REASON_CONNECTION_REVOKED, $revoked_cutoff, self::REVOKE_REASON_ROTATED, $rotated_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 McpTokenRow */ private function mapRow( array $row ): array { return array( 'id' => (int) ( $row['id'] ?? 0 ), 'connection_id' => (int) ( $row['connection_id'] ?? 0 ), 'token_hash' => (string) ( $row['token_hash'] ?? '' ), 'token_type' => (string) ( $row['token_type'] ?? '' ), 'paired_token_id' => (int) ( $row['paired_token_id'] ?? 0 ), 'permission_level' => (string) ( $row['permission_level'] ?? '' ), 'expires_at' => isset( $row['expires_at'] ) ? (string) $row['expires_at'] : null, 'last_used_at' => isset( $row['last_used_at'] ) ? (string) $row['last_used_at'] : null, 'revoked_at' => isset( $row['revoked_at'] ) ? (string) $row['revoked_at'] : null, 'revoke_reason' => (string) ( $row['revoke_reason'] ?? '' ), 'grace_reused_at' => isset( $row['grace_reused_at'] ) ? (string) $row['grace_reused_at'] : 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; } }