http = $http; $this->relayUrl = $relayUrl; $this->environmentType = $environmentType; } public function type(): string { return 'relay'; } /** * Creates a one-time state transient (including current user ID) and returns the relay connect URL. * * @throws \RuntimeException When the relay URL is missing or not https://. */ public function getConnectUrl( string $network, string $returnUrl ): string { $this->assertSecureRelayUrl(); $state = wp_generate_uuid4(); // PKCE (RFC 7636, S256): the verifier stays on this site (in the state // transient); only its hash goes to the relay. /exchange needs the // verifier, so a relay code is useless to anyone who intercepts it. $verifier = self::base64Url( random_bytes( 32 ) ); $challenge = self::base64Url( hash( 'sha256', $verifier, true ) ); set_transient( 'feednetic_oauth_state_' . $state, wp_json_encode( [ 'network' => $network, 'user_id' => get_current_user_id(), 'code_verifier' => $verifier, ] ), self::STATE_TTL ); return add_query_arg( [ 'site' => rawurlencode( home_url() ), 'return' => rawurlencode( $returnUrl ), 'state' => $state, 'code_challenge' => $challenge, 'code_challenge_method' => 'S256', ], trailingslashit( $this->relayUrl ) . rawurlencode( $network ) . '/start' ); } /** * Exchanges a code (received from the relay redirect) for a ConnectedSource. * * State verification (CSRF) is handled upstream by OauthCallbackHandler before this * method is called. This method performs the server-to-server code exchange with the * relay over verified HTTPS and validates the returned payload. * * @param array $params Must contain 'code', 'network' and 'code_verifier'. * @throws \RuntimeException On missing params, an insecure relay URL, exchange failure, or a malformed payload. */ public function handleCallback( array $params ): ConnectedSource { $code = $params['code'] ?? ''; $network = $params['network'] ?? ''; $verifier = $params['code_verifier'] ?? ''; if ( '' === $code || '' === $network ) { throw new \RuntimeException( 'handleCallback requires both code and network parameters.' ); } if ( '' === $verifier ) { throw new \RuntimeException( 'handleCallback requires the PKCE code_verifier from the connect attempt.' ); } $this->assertSecureRelayUrl(); return $this->parsePayload( $network, $this->exchangeCode( $code, $network, $verifier ) ); } /** * The relay has no refresh endpoint: tokens are refreshed directly with the * network (RefreshTokenJob → adapter::refreshToken(); Instagram needs no app * secret, Facebook Page tokens do not expire). Never called in practice. * * @throws \RuntimeException Always. */ public function refreshToken( SourceConfig $config ): Token { throw new \RuntimeException( 'The relay does not refresh tokens; they are refreshed directly with the network.' ); } /** * The relay is trusted because HTTPS authenticates it, so its URL must be * https://. A plain http:// URL (e.g. a FEEDNETIC_RELAY_URL override pointing * at a dev relay) is accepted only on local/development sites. * * @throws \RuntimeException When the URL is empty, has no host, or is not https:// outside local/development. */ private function assertSecureRelayUrl(): void { if ( '' === $this->relayUrl ) { throw new \RuntimeException( 'Relay URL is not configured.' ); } $scheme = strtolower( (string) wp_parse_url( $this->relayUrl, PHP_URL_SCHEME ) ); $host = (string) wp_parse_url( $this->relayUrl, PHP_URL_HOST ); if ( '' !== $host && ( 'https' === $scheme || ( 'http' === $scheme && $this->isDevEnvironment() ) ) ) { return; } throw new \RuntimeException( 'Relay URL must use https:// (FEEDNETIC_RELAY_URL may use http:// only on local or development sites).' ); } private function isDevEnvironment(): bool { $env = '' === $this->environmentType ? (string) wp_get_environment_type() : $this->environmentType; return 'local' === $env || 'development' === $env; } /** * Performs a server-to-server POST to the relay /exchange endpoint, exchanging * the short-lived code for the payload containing the token(s) and account info. * * The request goes through wp_safe_remote_post() (WpHttpClient) with TLS * certificate verification forced on for this URL, even if another plugin * disables it through http_request_args or https_ssl_verify. * * @param string $code Short-lived code from the relay redirect. * @param string $network Network slug, e.g. 'instagram'. * @param string $verifier PKCE code_verifier stored when the flow started. * @return array The decoded payload object. * @throws \RuntimeException On HTTP failure, a non-200 status, or a response that is not a JSON object. */ private function exchangeCode( string $code, string $network, string $verifier ): array { $endpoint = trailingslashit( $this->relayUrl ) . 'exchange'; $forceArgs = static function ( $args, $url ) use ( $endpoint ) { if ( $url === $endpoint && is_array( $args ) ) { $args['sslverify'] = true; } return $args; }; $forceVerify = static function ( $verify, $url ) use ( $endpoint ) { // Never let a filter turn verification off for the relay. return ( $url === $endpoint && false === $verify ) ? ABSPATH . 'wp-includes/certificates/ca-bundle.crt' : $verify; }; add_filter( 'http_request_args', $forceArgs, PHP_INT_MAX, 2 ); add_filter( 'https_ssl_verify', $forceVerify, PHP_INT_MAX, 2 ); try { $response = $this->http->post( $endpoint, [ 'Content-Type' => 'application/json' ], [ 'code' => $code, 'network' => $network, 'site' => home_url(), 'code_verifier' => $verifier, ] ); } finally { remove_filter( 'http_request_args', $forceArgs, PHP_INT_MAX ); remove_filter( 'https_ssl_verify', $forceVerify, PHP_INT_MAX ); } if ( 200 !== $response->statusCode ) { // The relay answers errors with { "error": "" }; keep only a safe code. $error = json_decode( $response->body, true ); $detail = is_array( $error ) && isset( $error['error'] ) && is_string( $error['error'] ) && 1 === preg_match( '/^[a-z_]{1,64}$/', $error['error'] ) ? ' (' . $error['error'] . ')' : ''; // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- exception messages are not HTML output. throw new \RuntimeException( sprintf( 'Relay code exchange failed with HTTP %d%s.', $response->statusCode, $detail ) ); } $contentType = ''; foreach ( $response->headers as $name => $value ) { if ( 'content-type' === strtolower( (string) $name ) ) { $contentType = strtolower( (string) $value ); } } if ( '' !== $contentType && false === strpos( $contentType, 'json' ) ) { throw new \RuntimeException( 'Relay exchange response is not JSON.' ); } $data = json_decode( $response->body, true ); // An object, not a list or a scalar. if ( ! is_array( $data ) || 0 !== strpos( ltrim( $response->body ), '{' ) ) { throw new \RuntimeException( 'Relay exchange response is not a JSON object.' ); } return $data; } /** * Parses the relay payload into a ConnectedSource. * * Instagram: the account itself is the source, so a top-level access_token * is required. * * Facebook: only Page tokens are used. The relay sends the Facebook user's * identity (external_id, name, username) and pages[], each Page with its own * access_token; there is no user token (least privilege), and if one were * sent it is ignored — never kept or stored. pages[] is required; an empty * list is valid and ends in the "No Pages found" message. Each Page becomes * an element of ConnectedSource::$availablePages for the Page picker. * * @param string $network Network slug. * @param array $payload Decoded exchange payload object. * @throws \RuntimeException On missing required fields. */ private function parsePayload( string $network, array $payload ): ConnectedSource { $isFacebook = 'facebook' === $network; $required = $isFacebook ? [ 'external_id', 'name', 'username' ] : [ 'external_id', 'name', 'username', 'access_token' ]; foreach ( $required as $field ) { if ( empty( $payload[ $field ] ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped throw new \RuntimeException( "Relay callback is missing required field: {$field}" ); } } if ( $isFacebook && ( ! isset( $payload['pages'] ) || ! is_array( $payload['pages'] ) ) ) { throw new \RuntimeException( 'Relay callback is missing required field: pages' ); } $expiresAt = null; if ( ! $isFacebook && ! empty( $payload['token_expires_at'] ) ) { try { $expiresAt = new \DateTimeImmutable( (string) $payload['token_expires_at'], new \DateTimeZone( 'UTC' ) ); } catch ( \Exception $e ) { unset( $e ); } } // Which of the relay's Meta apps issued these tokens (load balancing). // Stored per source so later relay calls use the same app. $meta = []; if ( ! empty( $payload['app_id'] ) && is_scalar( $payload['app_id'] ) ) { $meta['relay_app_id'] = (string) $payload['app_id']; } $availablePages = []; if ( $isFacebook ) { foreach ( $payload['pages'] as $page ) { if ( ! is_array( $page ) || empty( $page['external_id'] ) || empty( $page['access_token'] ) ) { continue; // A Page without its own token cannot be shown. } // Facebook Page tokens obtained this way do not expire (no token_expires_at). $availablePages[] = new ConnectedSource( $network, (string) $page['external_id'], (string) ( $page['name'] ?? '' ), (string) ( $page['username'] ?? '' ), isset( $page['avatar_url'] ) ? (string) $page['avatar_url'] : null, 'relay', (string) $page['access_token'], null, $meta ); } } return new ConnectedSource( $network, (string) $payload['external_id'], (string) $payload['name'], (string) $payload['username'], isset( $payload['avatar_url'] ) ? (string) $payload['avatar_url'] : null, 'relay', // Facebook: the user is only the owner of the Pages — no token, ever. $isFacebook ? '' : (string) $payload['access_token'], $expiresAt, $meta, $availablePages ); } /** base64url without padding (RFC 4648 §5). */ private static function base64Url( string $bytes ): string { return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- PKCE encoding, not obfuscation } }