" on the * consent screen and tie the sign-in to this one site. After sign-in the site * is linked to one Outercite workspace (POST /api/v1/wordpress/sites); from * then on its token only reaches that client. * * Everything is stored in one option, encrypted (see Crypto). * * @package Outercite */ namespace Outercite; defined( 'ABSPATH' ) || exit; /** * The Outercite sign-in and the link to a workspace. */ final class Connection { private const OPTION = 'outercite_connection'; private const STATE_PREFIX = 'outercite_oauth_'; private const REFRESH_LOCK = 'outercite_refresh_lock'; private const SCOPES = 'read:actions write:actions read:recommendations write:recommendations read:citations read:citetrace'; public const SOFTWARE_ID = 'com.outercite.wordpress'; /** * The decrypted connection, read once per request. * * @var array|null */ private static $cache = null; /** * The stored connection, decrypted. * * @return array Empty when not connected. */ public static function get(): array { if ( null === self::$cache ) { $plain = Crypto::decrypt( get_option( self::OPTION, '' ) ); $data = $plain ? json_decode( $plain, true ) : null; self::$cache = is_array( $data ) ? $data : array(); } return self::$cache; } /** * Store the connection, encrypted. * * @param array $data The whole connection. */ private static function save( array $data ): void { self::$cache = $data; update_option( self::OPTION, Crypto::encrypt( (string) wp_json_encode( $data ) ), false ); } /** * Change some fields of the stored connection. * * @param array $fields Fields to change. */ public static function update( array $fields ): void { self::save( array_merge( self::get(), $fields ) ); } /** * Delete the stored connection. */ public static function forget(): void { self::$cache = array(); delete_option( self::OPTION ); } /** * Signed in and linked to a workspace. */ public static function is_linked(): bool { $c = self::get(); return ! empty( $c['access_token'] ) && ! empty( $c['site_host'] ) && empty( $c['revoked'] ); } /** * Signed in, but no workspace picked yet. */ public static function needs_workspace(): bool { $c = self::get(); return ! empty( $c['access_token'] ) && empty( $c['site_host'] ) && empty( $c['revoked'] ); } /** * The sign-in stopped working and an administrator has to reconnect. */ public static function is_revoked(): bool { return ! empty( self::get()['revoked'] ); } /** * Where Outercite sends the administrator back after sign-in. */ public static function redirect_uri(): string { return admin_url( 'admin.php?page=outercite-settings&outercite_oauth=callback' ); } /** * Full Outercite address for an API path. * * @param string $path API path, starting with a slash. */ private static function api_url( string $path ): string { return untrailingslashit( OUTERCITE_API_URL ) . $path; } /** * Base64url encoding without padding, as PKCE uses. * * @param string $bytes Raw bytes. */ private static function base64url( string $bytes ): string { return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode } /** * Register this site as an OAuth client, once per redirect address. A * changed address (the site moved) registers again. * * @return true|\WP_Error */ private static function ensure_client() { $conn = self::get(); if ( ! empty( $conn['client_id'] ) && ( $conn['redirect_uri'] ?? '' ) === self::redirect_uri() ) { return true; } $res = wp_remote_post( self::api_url( '/api/oauth/register' ), array( 'timeout' => 15, 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => wp_json_encode( array( 'client_name' => 'Outercite for WordPress (' . Site::current_host() . ')', 'redirect_uris' => array( self::redirect_uri() ), 'software_id' => self::SOFTWARE_ID, 'software_version' => OUTERCITE_VERSION, 'grant_types' => array( 'authorization_code', 'refresh_token' ), 'token_endpoint_auth_method' => 'client_secret_post', 'scope' => self::SCOPES, ) ), ) ); if ( is_wp_error( $res ) ) { return new \WP_Error( 'outercite_unreachable', __( 'Could not reach Outercite. Check the site can make outgoing requests, then try again.', 'outercite' ) ); } $body = json_decode( wp_remote_retrieve_body( $res ), true ); if ( 201 !== wp_remote_retrieve_response_code( $res ) || empty( $body['client_id'] ) ) { $msg = is_array( $body ) && ! empty( $body['error_description'] ) ? $body['error_description'] : __( 'Outercite did not accept this site.', 'outercite' ); return new \WP_Error( 'outercite_register', $msg ); } self::update( array( 'client_id' => $body['client_id'], 'client_secret' => $body['client_secret'], 'redirect_uri' => self::redirect_uri(), ) ); return true; } /** * Start sign-in: the address to send the administrator to. * * @return string|\WP_Error */ public static function authorize_url() { $ok = self::ensure_client(); if ( is_wp_error( $ok ) ) { return $ok; } $verifier = self::base64url( random_bytes( 32 ) ); $state = self::base64url( random_bytes( 16 ) ); set_transient( self::STATE_PREFIX . $state, array( 'verifier' => $verifier, 'user' => get_current_user_id(), ), 15 * MINUTE_IN_SECONDS ); return add_query_arg( array( 'response_type' => 'code', 'client_id' => rawurlencode( self::get()['client_id'] ), 'redirect_uri' => rawurlencode( self::redirect_uri() ), 'scope' => rawurlencode( self::SCOPES ), 'state' => rawurlencode( $state ), 'code_challenge' => rawurlencode( self::base64url( hash( 'sha256', $verifier, true ) ) ), 'code_challenge_method' => 'S256', ), untrailingslashit( OUTERCITE_APP_URL ) . '/api/oauth/authorize' ); } /** * Finish sign-in: exchange the code. The state must match one this user * started, so a forged callback cannot connect the site to someone else. * * @param string $code Authorization code from the callback. * @param string $state State from the callback. * @return true|\WP_Error */ public static function handle_callback( string $code, string $state ) { $key = self::STATE_PREFIX . $state; $pending = get_transient( $key ); delete_transient( $key ); if ( ! is_array( $pending ) || get_current_user_id() !== (int) $pending['user'] ) { return new \WP_Error( 'outercite_state', __( 'That sign-in link expired or was not started here. Click Connect again.', 'outercite' ) ); } $conn = self::get(); $res = self::token_request( array( 'grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => self::redirect_uri(), 'code_verifier' => $pending['verifier'], 'client_id' => $conn['client_id'] ?? '', 'client_secret' => $conn['client_secret'] ?? '', ) ); if ( is_wp_error( $res ) ) { return $res; } self::store_tokens( $res ); self::update( array( 'revoked' => false, 'connected_by' => get_current_user_id(), 'connected_at' => time(), ) ); return true; } /** * POST to the OAuth token endpoint. * * @param array $form Form fields to post. * @return array|\WP_Error */ private static function token_request( array $form ) { $res = wp_remote_post( self::api_url( '/api/oauth/token' ), array( 'timeout' => 15, 'body' => $form, ) ); if ( is_wp_error( $res ) ) { return new \WP_Error( 'outercite_unreachable', __( 'Could not reach Outercite. Try again in a moment.', 'outercite' ) ); } $body = json_decode( wp_remote_retrieve_body( $res ), true ); if ( 200 !== wp_remote_retrieve_response_code( $res ) || empty( $body['access_token'] ) ) { $code = is_array( $body ) && ! empty( $body['error'] ) ? $body['error'] : 'token_error'; $msg = is_array( $body ) && ! empty( $body['error_description'] ) ? $body['error_description'] : __( 'Outercite refused the sign-in.', 'outercite' ); return new \WP_Error( 'outercite_' . $code, $msg ); } return $body; } /** * Store the tokens from a token response. * * @param array $body Token response. */ private static function store_tokens( array $body ): void { self::update( array( 'access_token' => $body['access_token'], 'refresh_token' => $body['refresh_token'] ?? ( self::get()['refresh_token'] ?? '' ), 'expires_at' => time() + (int) ( $body['expires_in'] ?? 3600 ), ) ); } /** * A usable access token, refreshed when it is about to expire. Null when * there is none, or it expired on a staging copy (which never refreshes). */ public static function access_token(): ?string { $conn = self::get(); if ( empty( $conn['access_token'] ) || ! empty( $conn['revoked'] ) ) { return null; } if ( (int) ( $conn['expires_at'] ?? 0 ) > time() + 60 ) { return $conn['access_token']; } if ( Site::is_staging() ) { return (int) ( $conn['expires_at'] ?? 0 ) > time() ? $conn['access_token'] : null; } return self::refresh() ? self::get()['access_token'] : null; } /** * Re-read the stored connection, bypassing this request's caches, so a * refresh another request just finished is seen. */ private static function reload(): array { self::$cache = null; wp_cache_delete( self::OPTION, 'options' ); return self::get(); } /** * Take the refresh lock atomically. add_option() fails when the row * exists, so only one request at a time spends the refresh token. A lock * older than 30 seconds belongs to a request that died, and is taken over. */ private static function take_refresh_lock(): bool { if ( add_option( self::REFRESH_LOCK, time(), '', false ) ) { return true; } wp_cache_delete( self::REFRESH_LOCK, 'options' ); $since = (int) get_option( self::REFRESH_LOCK, 0 ); if ( $since && $since < time() - 30 ) { delete_option( self::REFRESH_LOCK ); return add_option( self::REFRESH_LOCK, time(), '', false ); } return false; } /** * Use the refresh token. Only a definite refusal (the grant or the client * is no longer valid) marks the sign-in revoked; an outage, a rate limit or * a server error leaves it alone so the next request tries again. */ public static function refresh(): bool { if ( Site::is_staging() ) { return false; } if ( ! self::take_refresh_lock() ) { // Another request is refreshing: wait for its result rather than spend the same refresh token twice. for ( $i = 0; $i < 6; $i++ ) { sleep( 1 ); if ( (int) ( self::reload()['expires_at'] ?? 0 ) > time() + 60 ) { return true; } } return false; } $conn = self::reload(); if ( (int) ( $conn['expires_at'] ?? 0 ) > time() + 60 ) { // Refreshed by another request between our check and the lock. delete_option( self::REFRESH_LOCK ); return true; } $res = self::token_request( array( 'grant_type' => 'refresh_token', 'refresh_token' => $conn['refresh_token'] ?? '', 'client_id' => $conn['client_id'] ?? '', 'client_secret' => $conn['client_secret'] ?? '', ) ); if ( is_wp_error( $res ) ) { if ( in_array( $res->get_error_code(), array( 'outercite_invalid_grant', 'outercite_invalid_client', 'outercite_unauthorized_client' ), true ) ) { self::update( array( 'revoked' => true ) ); } delete_option( self::REFRESH_LOCK ); return false; } self::store_tokens( $res ); delete_option( self::REFRESH_LOCK ); return true; } /** * Mark the sign-in as revoked, after Outercite refused a fresh token. */ public static function mark_revoked(): void { self::update( array( 'revoked' => true ) ); } /** * Revoke the sign-in in Outercite. Best effort: the local copy is deleted either way. */ public static function revoke_remote(): void { $conn = self::get(); foreach ( array( 'refresh_token', 'access_token' ) as $kind ) { if ( empty( $conn[ $kind ] ) ) { continue; } wp_remote_post( self::api_url( '/api/oauth/revoke' ), array( 'timeout' => 10, 'body' => array( 'token' => $conn[ $kind ], 'client_id' => $conn['client_id'] ?? '', 'client_secret' => $conn['client_secret'] ?? '', ), ) ); } } }