relay = $relay; $this->sourceRepo = $sourceRepo; $this->encryption = $encryption; $this->logger = $logger; } /** * Registers the admin-post action hook — for logged-in users only. The * callback is a top-level GET redirect from the relay, so the browser sends * the WordPress auth cookies (SameSite=Lax); a logged-out request never * reaches the handler. */ public function register(): void { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores add_action( 'admin_post_feednetic_oauth_callback', [ $this, 'handle' ] ); } /** * Entry point for admin-post.php: reads state and code from the query * string and hands them to handleCallback(). The one-time state (bound to * the admin who started the connect attempt) stands in for a nonce. */ public function handle(): void { // phpcs:disable WordPress.Security.NonceVerification.Recommended -- verified by the one-time state in processCallback() $state = isset( $_GET['state'] ) ? sanitize_text_field( wp_unslash( $_GET['state'] ) ) : ''; $code = isset( $_GET['code'] ) ? sanitize_text_field( wp_unslash( $_GET['code'] ) ) : ''; // phpcs:enable WordPress.Security.NonceVerification.Recommended $this->handleCallback( (string) $state, (string) $code ); } /** * Verifies the callback and redirects to the admin app. Delegates to * processCallback(), which only accepts the logged-in admin who started * the connect attempt. * * Calls exit() after every redirect to stop further execution. * * @param string $state The one-time state from the relay redirect (sanitized). * @param string $code The short-lived relay code (sanitized). */ public function handleCallback( string $state, string $code ): void { if ( '' === $state || '' === $code ) { $this->redirectWithError( 'invalid_request' ); exit; } try { $source = $this->processCallback( $state, $code ); } catch ( OauthUnauthorizedException $e ) { $this->redirectWithError( 'unauthorized' ); exit; } catch ( \Exception $e ) { $this->logger->error( 'OAuth callback failed: ' . $e->getMessage() ); $this->redirectWithError( 'callback_failed' ); exit; } $outcome = $this->resolve( $source ); if ( isset( $outcome['error'] ) ) { $this->redirectWithError( $outcome['error'] ); } else { $this->redirectSuccess( $source->network, $outcome['params'] ); } exit; } /** * Decides what a verified connection leads to (no redirect, no exit). * * - Facebook with Pages: they are parked under a one-time pages token for the picker. * - Facebook with zero Pages: error "no_pages" — nothing is stored (a Facebook * user is never a feed source; Pages managed only in Meta Business Suite * are not returned by Meta until the person is added to the Page directly). * - Otherwise the account is stored. * * @return array{error:string}|array{params:array} */ public function resolve( ConnectedSource $source ): array { if ( ! empty( $source->availablePages ) ) { return [ 'params' => [ 'pages_token' => $this->storePagesTransient( get_current_user_id(), $source->availablePages ) ] ]; } if ( 'facebook' === $source->network ) { return [ 'error' => 'no_pages' ]; } $this->storeSource( $source ); return [ 'params' => [] ]; } /** * Verifies the state transient (including user ID binding), consumes it, and * delegates the code exchange to the relay provider. * * Kept separate from handle() so it can be tested without exit(). * * @param string $state OAuth state parameter from the callback URL. * @param string $code Short-lived code from the relay redirect. * @return ConnectedSource Parsed source from the relay exchange response. * @throws OauthUnauthorizedException Not a logged-in admin, or not the admin who started the flow (nothing consumed). * @throws \RuntimeException On invalid state or exchange failure. */ public function processCallback( string $state, string $code ): ConnectedSource { // Only a logged-in admin, from their own session cookies — never a user // derived from request data. if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) { throw new OauthUnauthorizedException( 'OAuth callback requires a logged-in administrator.' ); } $transientKey = 'feednetic_oauth_state_' . $state; $stored = get_transient( $transientKey ); if ( false === $stored ) { throw new \RuntimeException( 'Invalid or expired OAuth state.' ); } $data = json_decode( (string) $stored, true ); if ( ! is_array( $data ) || ! isset( $data['network'], $data['user_id'] ) ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped throw new \RuntimeException( 'Invalid or expired OAuth state.' ); } // Bind the callback to the admin who started the flow. Checked before // consuming anything, so another user cannot burn someone's attempt. if ( get_current_user_id() !== (int) $data['user_id'] ) { throw new OauthUnauthorizedException( 'OAuth state user mismatch.' ); } // Consume immediately to prevent replay attacks. delete_transient( $transientKey ); return $this->relay->handleCallback( [ 'code' => $code, 'network' => (string) $data['network'], 'code_verifier' => (string) ( $data['code_verifier'] ?? '' ), ] ); } /** * Encrypts the available Facebook pages and stores them in a short-lived transient. * * Returns the token the admin UI must pass back to claimFacebookPages() to retrieve them. * * @param int $userId The admin user ID. * @param ConnectedSource[] $pages Available pages from the relay payload. * @return string One-time token for claiming the stored pages. */ public function storePagesTransient( int $userId, array $pages ): string { $token = bin2hex( random_bytes( 16 ) ); $pageMaps = []; foreach ( $pages as $page ) { $pageMaps[] = [ 'network' => $page->network, 'external_id' => $page->externalId, 'name' => $page->name, 'username' => $page->username, 'avatar_url' => $page->avatarUrl, 'auth_type' => $page->authType, 'access_token' => $page->getAccessToken(), 'meta' => $page->meta, ]; } $encrypted = $this->encryption->encrypt( (string) wp_json_encode( $pageMaps ) ); set_transient( "feednetic_fb_pages_{$userId}_{$token}", $encrypted, 600 ); return $token; } /** * Claims (and consumes) the Facebook pages stored by storePagesTransient(). * * @param int $userId The admin user ID. * @param string $token The one-time token returned by storePagesTransient(). * @return ConnectedSource[] The available pages ready for storage. * @throws \RuntimeException If the transient is missing, expired, or corrupted. */ public function claimFacebookPages( int $userId, string $token ): array { $transientKey = "feednetic_fb_pages_{$userId}_{$token}"; $stored = get_transient( $transientKey ); if ( false === $stored ) { // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped throw new \RuntimeException( 'Facebook pages token invalid or expired.' ); } // Consume immediately. delete_transient( $transientKey ); $decrypted = $this->encryption->decrypt( (string) $stored ); if ( null === $decrypted ) { throw new \RuntimeException( 'Facebook pages transient decryption failed.' ); } $pageMaps = json_decode( $decrypted, true ); if ( ! is_array( $pageMaps ) ) { throw new \RuntimeException( 'Facebook pages transient contains invalid data.' ); } $sources = []; foreach ( $pageMaps as $page ) { if ( ! is_array( $page ) ) { continue; } $expiresAt = null; if ( ! empty( $page['token_expires_at'] ) ) { try { $expiresAt = new \DateTimeImmutable( (string) $page['token_expires_at'], new \DateTimeZone( 'UTC' ) ); } catch ( \Exception $e ) { unset( $e ); } } $sources[] = new ConnectedSource( (string) ( $page['network'] ?? '' ), (string) ( $page['external_id'] ?? '' ), (string) ( $page['name'] ?? '' ), (string) ( $page['username'] ?? '' ), isset( $page['avatar_url'] ) ? (string) $page['avatar_url'] : null, (string) ( $page['auth_type'] ?? 'relay' ), (string) ( $page['access_token'] ?? '' ), $expiresAt, isset( $page['meta'] ) && is_array( $page['meta'] ) ? $page['meta'] : [] ); } return $sources; } /** * Upserts the ConnectedSource into the database. * * @param ConnectedSource $source The verified source to persist. * @return int The database row ID. */ private function storeSource( ConnectedSource $source ): int { // A source without its own token (e.g. the Facebook user, who only owns // the Pages) is never stored. if ( '' === $source->getAccessToken() ) { throw new \RuntimeException( 'Refusing to store a connection without an access token.' ); } $existing = $this->sourceRepo->findByNetworkAndExternalId( $source->network, $source->externalId ); $data = [ 'network' => $source->network, 'external_id' => $source->externalId, 'name' => $source->name, 'username' => $source->username, 'avatar_url' => $source->avatarUrl, 'auth_type' => $source->authType, 'token_encrypted' => $this->encryption->encrypt( $source->getAccessToken() ), 'status' => 'active', 'last_error' => null, ]; if ( null !== $source->tokenExpiresAt ) { $data['token_expires_at'] = $source->tokenExpiresAt->format( 'Y-m-d H:i:s' ); } if ( null !== $existing ) { $id = (int) $existing['id']; $this->sourceRepo->update( $id, $data ); } else { // insert() fires feednetic/source_connected itself. $id = $this->sourceRepo->insert( $data ); } // e.g. relay_app_id: the Meta app that issued this token. if ( ! empty( $source->meta ) ) { $this->sourceRepo->updateMeta( $id, $source->meta ); } // A reconnect is a new token too: restart fetching and reschedule the // token refresh (the Facebook Pages claim path does the same). if ( null !== $existing ) { // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores do_action( 'feednetic/source_connected', $id ); } return $id; } /** * Redirects the admin to the success page. * * @param string $network The connected network slug. * @param array $extra Additional query parameters. */ private function redirectSuccess( string $network, array $extra = [] ): void { wp_safe_redirect( add_query_arg( array_merge( [ 'page' => 'feednetic', 'action' => 'connected', 'network' => $network, ], $extra ), $this->adminPageUrl() ) ); } /** * Redirects the admin to the error page. * * @param string $error The error slug, e.g. 'invalid_request'. */ private function redirectWithError( string $error ): void { wp_safe_redirect( add_query_arg( [ 'page' => 'feednetic', // Not "error": WordPress strips that from admin URLs // (wp_removable_query_args) before the admin app can read it. 'fn_error' => $error, ], $this->adminPageUrl() ) ); } /** * Returns the admin.php base URL for post-OAuth redirects. Always the * site's own admin URL — never built from request headers (Host / * X-Forwarded-Proto), which a client controls. */ private function adminPageUrl(): string { return admin_url( 'admin.php' ); } }