Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
28.72% covered (danger)
28.72%
218 / 759
48.98% covered (danger)
48.98%
24 / 49
CRAP
0.00% covered (danger)
0.00%
0 / 1
SSO
28.72% covered (danger)
28.72%
218 / 759
48.98% covered (danger)
48.98%
24 / 49
15573.42
0.00% covered (danger)
0.00%
0 / 1
 __construct
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
6.04
 get_instance
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 init_standalone
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 maybe_start_standalone
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
6
 add_standalone_module
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sync_sso_callables
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 sso_reminder_logout_wpcom
93.75% covered (success)
93.75%
15 / 16
0.00% covered (danger)
0.00%
0 / 1
3.00
 maybe_logout_user
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 xmlrpc_methods
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 xmlrpc_user_disconnect
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 login_enqueue_scripts
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 login_body_class
75.00% covered (warning)
75.00%
12 / 16
0.00% covered (danger)
0.00%
0 / 1
14.25
 print_inline_admin_css
n/a
0 / 0
n/a
0 / 0
1
 enqueue_login_styles
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 register_settings
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
2
 render_require_two_step
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 validate_jetpack_sso_require_two_step
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 render_match_by_email
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
2
 validate_jetpack_sso_match_by_email
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 wants_to_login
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 login_init
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
156
 display_sso_login_form
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 save_cookies
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
90
 login_form
77.27% covered (warning)
77.27%
51 / 66
0.00% covered (danger)
0.00%
0 / 1
12.42
 clear_cookies_after_login
0.00% covered (danger)
0.00%
0 / 51
0.00% covered (danger)
0.00%
0 / 1
42
 disconnect
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 request_initial_nonce
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
56
 validate_broker_url
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
6.10
 is_broker_authorized
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 is_referrer_wpcom
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_live_referrer_wpcom
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
 get_broker_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_broker_auth_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 handle_login
0.00% covered (danger)
0.00%
0 / 176
0.00% covered (danger)
0.00%
0 / 1
1190
 profile_page_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 build_sso_button
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 build_sso_button_url
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 get_sso_url_or_die
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
20
 get_sso_base_url
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 build_sso_url
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 build_reauth_and_sso_url
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
20
 set_wpcom_user_id_meta
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_user_by_wpcom_id
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 get_signed_user_token_for_wpcom_id
47.37% covered (danger)
47.37%
9 / 19
0.00% covered (danger)
0.00%
0 / 1
8.64
 verify_user_token
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 maybe_authorize_user_after_sso
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 store_wpcom_profile_cookies_on_logout
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
12
 is_user_connected
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_user_data
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 add_two_factor_session_meta
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * SSO feature. Entry point.
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack\Connection;
9
10use Automattic\Jetpack\Assets;
11use Automattic\Jetpack\Connection\SSO\Force_2FA;
12use Automattic\Jetpack\Connection\SSO\Helpers;
13use Automattic\Jetpack\Connection\SSO\Notices;
14use Automattic\Jetpack\Connection\SSO\User_Admin;
15use Automattic\Jetpack\Connection\Webhooks\Authorize_Redirect;
16use Automattic\Jetpack\Constants;
17use Automattic\Jetpack\Modules;
18use Automattic\Jetpack\Redirect;
19use Automattic\Jetpack\Roles;
20use Automattic\Jetpack\Status;
21use Automattic\Jetpack\Status\Host;
22use Automattic\Jetpack\Tracking;
23use Jetpack_IXR_Client;
24use WP_Error;
25use WP_User;
26use WP_User_Query;
27
28/**
29 * SSO feature main class.
30 */
31class SSO {
32    /**
33     * WordPress.com User information.
34     *
35     * @var false|object
36     */
37    private $user_data;
38
39    /**
40     * Whether the SSO attempt failed because the site requires two-step authentication and the WordPress.com account lacks it.
41     *
42     * @var bool
43     */
44    private $two_step_required = false;
45
46    /**
47     * Automattic\Jetpack\Connection\SSO instance.
48     *
49     * @var \Automattic\Jetpack\Connection\SSO|null
50     */
51    public static $instance = null;
52
53    /**
54     * Stores the WP_User being authenticated via SSO so the
55     * attach_session_information callback can tag the session.
56     *
57     * @var WP_User|null
58     */
59    private static $sso_user_for_2fa = null;
60
61    /**
62     * Cookie name for the SSO broker authorization signal.
63     *
64     * Set when WP.com signals that a broker should be used for SSO. The cookie
65     * value is the SSO nonce, tying the signal to a specific authentication flow.
66     *
67     * @var string
68     */
69    const BROKER_COOKIE = 'jetpack_sso_broker';
70
71    /**
72     * Automattic\Jetpack\Connection\SSO constructor.
73     */
74    private function __construct() {
75
76        self::$instance = $this;
77
78        add_action( 'admin_init', array( $this, 'maybe_authorize_user_after_sso' ), 1 );
79        add_action( 'admin_init', array( $this, 'register_settings' ) );
80        add_action( 'login_init', array( $this, 'login_init' ) );
81        add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
82        add_action( 'init', array( $this, 'maybe_logout_user' ), 5 );
83        add_action( 'login_form_logout', array( $this, 'store_wpcom_profile_cookies_on_logout' ) );
84        add_action( 'jetpack_unlinked_user', array( Helpers::class, 'delete_connection_for_user' ) );
85
86        add_action( 'jetpack_site_before_disconnected', array( static::class, 'disconnect' ) );
87        add_action( 'wp_login', array( static::class, 'clear_cookies_after_login' ) );
88
89        // Adding this action so that on login_init, the action won't be sanitized out of the $action global.
90        add_action( 'login_form_jetpack-sso', '__return_true' );
91
92        add_filter( 'wp_login_errors', array( $this, 'sso_reminder_logout_wpcom' ) );
93
94        // Synchronize SSO options with WordPress.com.
95        add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'sync_sso_callables' ), 10, 1 );
96
97        /**
98         * Filter to include Force 2FA feature.
99         *
100         * By default, `manage_options` users are forced when enable. The capability can be modified
101         * with the `jetpack_force_2fa_cap` filter.
102         *
103         * To enable the feature, add the following code:
104         * add_filter( 'jetpack_force_2fa', '__return_true' );
105         *
106         * @param bool $force_2fa Whether to force 2FA or not.
107         *
108         * @todo Provide a UI to enable/disable the feature.
109         *
110         * @since jetpack-12.7
111         * @module SSO
112         * @return bool
113         */
114        if (
115            ! class_exists( 'Automattic\Jetpack\Connection\SSO\Force_2FA', false )
116            && apply_filters( 'jetpack_force_2fa', false )
117        ) {
118            new Force_2FA();
119        }
120
121        /*
122         * Allow admins to invite new users to create a WordPress.com account
123         * as they are added to the site.
124         *
125         * This is a feature that is only available when the admin is connected to WordPress.com.
126         */
127        if (
128            ( new Manager() )->is_user_connected() &&
129            ! is_multisite() &&
130            /**
131             * Toggle the ability to invite new users to create a WordPress.com account.
132             *
133             * @module sso
134             *
135             * @since 2.7.2
136             *
137             * @param bool true Whether to allow admins to invite new users to create a WordPress.com account.
138             */
139            apply_filters( 'jetpack_sso_invite_new_users_wpcom', true )
140        ) {
141            new User_Admin();
142        }
143    }
144
145    /**
146     * Returns the single instance of the Automattic\Jetpack\Connection\SSO object
147     *
148     * @since jetpack-2.8
149     * @return \Automattic\Jetpack\Connection\SSO
150     */
151    public static function get_instance() {
152        if ( self::$instance !== null ) {
153            return self::$instance;
154        }
155
156        self::$instance = new SSO();
157        return self::$instance;
158    }
159
160    /**
161     * Let a plugin other than Jetpack offer SSO: make the `sso` module available, and start SSO while it is on.
162     *
163     * Call it before `after_setup_theme`, when the Jetpack plugin loads its modules; that plugin's own loader starts SSO.
164     *
165     * @since 9.18.0
166     *
167     * @return void
168     */
169    public static function init_standalone() {
170        add_filter( 'jetpack_get_available_standalone_modules', array( __CLASS__, 'add_standalone_module' ) );
171
172        // Not sooner: the constructor resolves the current user, before other plugins have added their auth filters.
173        if ( did_action( 'after_setup_theme' ) ) {
174            self::maybe_start_standalone();
175        } else {
176            add_action( 'after_setup_theme', array( __CLASS__, 'maybe_start_standalone' ), -2 );
177        }
178    }
179
180    /**
181     * Start SSO for a standalone plugin, under the conditions the Jetpack plugin's module loader would.
182     *
183     * @internal Public only so init_standalone() can hook it; call init_standalone() instead.
184     *
185     * @since 9.18.0
186     *
187     * @return void
188     */
189    public static function maybe_start_standalone() {
190        if ( class_exists( 'Jetpack', false ) || ( new Status() )->is_offline_mode() ) {
191            return;
192        }
193
194        $connection = new Manager();
195        if ( ! $connection->is_connected() || ! $connection->has_connected_owner() ) {
196            return;
197        }
198
199        if ( ( new Modules() )->is_active( 'sso' ) ) {
200            self::get_instance();
201        }
202    }
203
204    /**
205     * Add `sso` to the modules a standalone plugin can switch on.
206     *
207     * @internal Public only so init_standalone() can hook it; call init_standalone() instead.
208     *
209     * @since 9.18.0
210     *
211     * @param string[] $modules Module slugs.
212     * @return string[]
213     */
214    public static function add_standalone_module( $modules ) {
215        return array_unique( array_merge( (array) $modules, array( 'sso' ) ) );
216    }
217
218    /**
219     * Add SSO callables to the sync whitelist.
220     *
221     * @since 2.8.1
222     *
223     * @param array $callables list of callables.
224     *
225     * @return array list of callables.
226     */
227    public function sync_sso_callables( $callables ) {
228        $sso_callables = array(
229            'sso_is_two_step_required'      => array( Helpers::class, 'is_two_step_required' ),
230            'sso_should_hide_login_form'    => array( Helpers::class, 'should_hide_login_form' ),
231            'sso_match_by_email'            => array( Helpers::class, 'match_by_email' ),
232            'sso_new_user_override'         => array( Helpers::class, 'new_user_override' ),
233            'sso_bypass_default_login_form' => array( Helpers::class, 'bypass_login_forward_wpcom' ),
234        );
235
236        return array_merge( $callables, $sso_callables );
237    }
238
239    /**
240     * Safety heads-up added to the logout messages when SSO is enabled.
241     * Some folks on a shared computer don't know that they need to log out of WordPress.com as well.
242     *
243     * @param WP_Error $errors WP_Error object.
244     */
245    public function sso_reminder_logout_wpcom( $errors ) {
246        if ( ( new Host() )->is_wpcom_platform() ) {
247            return $errors;
248        }
249
250        if ( ! empty( $errors->errors['loggedout'] ) ) {
251            $logout_message = wp_kses(
252                sprintf(
253                /* translators: %1$s is a link to the WordPress.com account settings page. */
254                    __( 'If you are on a shared computer, remember to also <a href="%1$s">log out of WordPress.com</a>.', 'jetpack-connection' ),
255                    'https://wordpress.com/me'
256                ),
257                array(
258                    'a' => array(
259                        'href' => array(),
260                    ),
261                )
262            );
263            $errors->add( 'jetpack-sso-show-logout', $logout_message, 'message' );
264        }
265        return $errors;
266    }
267
268    /**
269     * If jetpack_force_logout == 1 in current user meta the user will be forced
270     * to logout and reauthenticate with the site.
271     **/
272    public function maybe_logout_user() {
273        global $current_user;
274
275        if ( 1 === (int) $current_user->jetpack_force_logout ) {
276            delete_user_meta( $current_user->ID, 'jetpack_force_logout' );
277            Helpers::delete_connection_for_user( $current_user->ID );
278            wp_logout();
279            wp_safe_redirect( wp_login_url() );
280            exit( 0 );
281        }
282    }
283
284    /**
285     * Adds additional methods the WordPress xmlrpc API for handling SSO specific features
286     *
287     * @param array $methods API methods.
288     * @return array
289     **/
290    public function xmlrpc_methods( $methods ) {
291        $methods['jetpack.userDisconnect'] = array( $this, 'xmlrpc_user_disconnect' );
292        return $methods;
293    }
294
295    /**
296     * Marks a user's profile for disconnect from WordPress.com and forces a logout
297     * the next time the user visits the site.
298     *
299     * @param int $user_id User to disconnect from the site.
300     **/
301    public function xmlrpc_user_disconnect( $user_id ) {
302        $user = self::get_user_by_wpcom_id( $user_id );
303
304        if ( $user instanceof WP_User ) {
305            $user = wp_set_current_user( $user->ID );
306            update_user_meta( $user->ID, 'jetpack_force_logout', '1' );
307            Helpers::delete_connection_for_user( $user->ID );
308            return true;
309        }
310        return false;
311    }
312
313    /**
314     * Enqueues scripts and styles necessary for SSO login.
315     */
316    public function login_enqueue_scripts() {
317        global $action;
318
319        if ( ! Helpers::display_sso_form_for_action( $action ) ) {
320            return;
321        }
322
323        Assets::register_script(
324            'jetpack-sso-login',
325            '../../dist/jetpack-sso-login.js',
326            __FILE__,
327            array(
328                'enqueue' => true,
329                'version' => Package_Version::PACKAGE_VERSION,
330            )
331        );
332    }
333
334    /**
335     * Adds Jetpack SSO classes to login body
336     *
337     * @param  array $classes Array of classes to add to body tag.
338     * @return array          Array of classes to add to body tag.
339     */
340    public function login_body_class( $classes ) {
341        global $action;
342
343        if ( ! Helpers::display_sso_form_for_action( $action ) ) {
344            return $classes;
345        }
346
347        // Always add the jetpack-sso class so that we can add SSO specific styling even when the SSO form isn't being displayed.
348        $classes[] = 'jetpack-sso';
349
350        if ( ! ( new Status() )->in_safe_mode() ) {
351            /**
352             * Should we show the SSO login form?
353             *
354             * $_GET['jetpack-sso-show-default-form'] is used to provide a fallback in case JavaScript is not enabled.
355             *
356             * The default_to_sso_login() method allows us to dynamically decide whether we show the SSO login form or not.
357             * The SSO module uses the method to display the default login form if we cannot find a user to log in via SSO.
358             * But, the method could be filtered by a site admin to always show the default login form if that is preferred.
359             */
360            $default_form_preference = isset( $_GET['jetpack-sso-show-default-form'] ) ? sanitize_text_field( wp_unslash( $_GET['jetpack-sso-show-default-form'] ) ) : null; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
361            $show_sso_form           = empty( $default_form_preference ) && Helpers::show_sso_login();
362
363            if ( 'entered_recovery_mode' === $action ) {
364                if ( '0' === $default_form_preference ) {
365                    // Explicit user opt-in via the no-JS toggle; honor it regardless of show_sso_login() so the toggle always works.
366                    $show_sso_form = true;
367                } elseif ( null === $default_form_preference && ! Helpers::should_hide_login_form() ) {
368                    // Recovery is the break-glass fallback, so default to the wp-admin password form. Skip when that form is hidden, otherwise no login path would work.
369                    $show_sso_form = false;
370                }
371            }
372
373            if ( $this->two_step_required && '1' !== $default_form_preference ) {
374                // The two-step screen only follows an SSO attempt, so show the SSO form regardless of the site default.
375                $show_sso_form = true;
376            }
377
378            if ( $show_sso_form ) {
379                $classes[] = 'jetpack-sso-form-display';
380            }
381        }
382
383        return $classes;
384    }
385
386    /**
387     * Print the SSO styles for the login screen.
388     *
389     * @deprecated 8.12.0 Use enqueue_login_styles().
390     */
391    public function print_inline_admin_css() {
392        _deprecated_function( __METHOD__, 'connection-8.12.0', __CLASS__ . '::enqueue_login_styles' );
393        $this->enqueue_login_styles();
394    }
395
396    /**
397     * Enqueue the SSO styles for the login screen.
398     */
399    public function enqueue_login_styles() {
400        $handle = 'jetpack-sso-login-styles';
401
402        // No src: the handle only carries the inline CSS below. Core enqueues `login` before `login_enqueue_scripts` fires,
403        // so these rules already print after the core login stylesheet, which sets `.message` margins at the same
404        // specificity. No dependency on `login`: plugins that replace the login screen deregister that handle, and a
405        // missing dependency would drop this one from the queue.
406        wp_register_style( $handle, false, array(), Package_Version::PACKAGE_VERSION );
407        wp_enqueue_style( $handle );
408
409        $css = <<<'CSS'
410.jetpack-sso .message {
411    margin-top: 20px;
412}
413
414.jetpack-sso #login .message:first-child,
415.jetpack-sso #login h1 + .message {
416    margin-top: 0;
417}
418CSS;
419
420        wp_add_inline_style( $handle, $css );
421    }
422
423    /**
424     * Adds settings fields to Settings > General > WordPress.com login that allows users to
425     * turn off the login form on wp-login.php
426     *
427     * @since jetpack-2.7
428     **/
429    public function register_settings() {
430
431        add_settings_section(
432            'jetpack_sso_settings',
433            __( 'WordPress.com login', 'jetpack-connection' ),
434            '__return_false',
435            'jetpack-sso'
436        );
437
438        /*
439         * Settings > General > WordPress.com login
440         * Require two step authentication
441         */
442        register_setting(
443            'jetpack-sso',
444            'jetpack_sso_require_two_step',
445            array( $this, 'validate_jetpack_sso_require_two_step' )
446        );
447
448        add_settings_field(
449            'jetpack_sso_require_two_step',
450            '', // Output done in render $callback: __( 'Require Two-Step Authentication' , 'jetpack-connection' ).
451            array( $this, 'render_require_two_step' ),
452            'jetpack-sso',
453            'jetpack_sso_settings'
454        );
455
456        /*
457         * Settings > General > WordPress.com login
458         */
459        register_setting(
460            'jetpack-sso',
461            'jetpack_sso_match_by_email',
462            array( $this, 'validate_jetpack_sso_match_by_email' )
463        );
464
465        add_settings_field(
466            'jetpack_sso_match_by_email',
467            '', // Output done in render $callback: __( 'Match by Email' , 'jetpack-connection' ).
468            array( $this, 'render_match_by_email' ),
469            'jetpack-sso',
470            'jetpack_sso_settings'
471        );
472    }
473
474    /**
475     * Builds the display for the checkbox allowing user to require two step
476     * auth be enabled on WordPress.com accounts before login. Displays in Settings > General
477     *
478     * @since jetpack-2.7
479     **/
480    public function render_require_two_step() {
481        ?>
482        <label>
483            <input
484                type="checkbox"
485                name="jetpack_sso_require_two_step"
486        <?php checked( Helpers::is_two_step_required() ); ?>
487        <?php disabled( Helpers::is_require_two_step_checkbox_disabled() ); ?>
488            >
489        <?php esc_html_e( 'Require Two-Step Authentication', 'jetpack-connection' ); ?>
490        </label>
491        <?php
492    }
493
494    /**
495     * Validate the require  two step checkbox in Settings > General.
496     *
497     * @param bool $input The jetpack_sso_require_two_step option setting.
498     *
499     * @since jetpack-2.7
500     * @return int
501     **/
502    public function validate_jetpack_sso_require_two_step( $input ) {
503        return ( ! empty( $input ) ) ? 1 : 0;
504    }
505
506    /**
507     * Builds the display for the checkbox allowing the user to allow matching logins by email
508     * Displays in Settings > General
509     *
510     * @since jetpack-2.9
511     **/
512    public function render_match_by_email() {
513        ?>
514            <label>
515                <input
516                    type="checkbox"
517                    name="jetpack_sso_match_by_email"
518            <?php checked( Helpers::match_by_email() ); ?>
519            <?php disabled( Helpers::is_match_by_email_checkbox_disabled() ); ?>
520                >
521        <?php esc_html_e( 'Match by Email', 'jetpack-connection' ); ?>
522            </label>
523        <?php
524    }
525
526    /**
527     * Validate the match by email check in Settings > General.
528     *
529     * @param bool $input The jetpack_sso_match_by_email option setting.
530     *
531     * @since jetpack-2.9
532     * @return int
533     **/
534    public function validate_jetpack_sso_match_by_email( $input ) {
535        return ( ! empty( $input ) ) ? 1 : 0;
536    }
537
538    /**
539     * Checks to determine if the user wants to login on wp-login
540     *
541     * This function mostly exists to cover the exceptions to login
542     * that may exist as other parameters to $_GET[action] as $_GET[action]
543     * does not have to exist. By default WordPress assumes login if an action
544     * is not set, however this may not be true, as in the case of logout
545     * where $_GET[loggedout] is instead set
546     *
547     * @return boolean
548     **/
549    private function wants_to_login() {
550        $wants_to_login = false;
551
552        // Cover default WordPress behavior.
553        $action = isset( $_REQUEST['action'] ) ? filter_var( wp_unslash( $_REQUEST['action'] ) ) : 'login'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
554
555        // And now the exceptions.
556        $action = isset( $_GET['loggedout'] ) ? 'loggedout' : $action; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
557
558        // Recovery mode must complete on the local site (token validation, cookie, recovery notice). Skip the bypass-redirect so SSO doesn't carry the user off-site mid-recovery.
559        if ( 'entered_recovery_mode' === $action ) {
560            return false;
561        }
562
563        if ( Helpers::display_sso_form_for_action( $action ) ) {
564            $wants_to_login = true;
565        }
566
567        return $wants_to_login;
568    }
569
570    /**
571     * Initialization for a SSO request.
572     */
573    public function login_init() {
574        global $action;
575
576        $tracking = new Tracking();
577
578        if ( Helpers::should_hide_login_form() ) {
579            /**
580             * Since the default authenticate filters fire at priority 20 for checking username and password,
581             * let's fire at priority 30. wp_authenticate_spam_check is fired at priority 99, but since we return a
582             * WP_Error in disable_default_login_form, then we won't trigger spam processing logic.
583             */
584            add_filter( 'authenticate', array( Notices::class, 'disable_default_login_form' ), 30 );
585
586            /**
587             * Filter the display of the disclaimer message appearing when default WordPress login form is disabled.
588             *
589             * @module sso
590             *
591             * @since jetpack-2.8.0
592             *
593             * @param bool true Should the disclaimer be displayed. Default to true.
594             */
595            $display_sso_disclaimer = apply_filters( 'jetpack_sso_display_disclaimer', true );
596            if ( $display_sso_disclaimer ) {
597                add_filter( 'login_message', array( Notices::class, 'msg_login_by_jetpack' ) );
598            }
599        }
600
601        if ( 'jetpack-sso' === $action ) {
602            if ( isset( $_GET['result'] ) && isset( $_GET['user_id'] ) && isset( $_GET['sso_nonce'] ) && 'success' === $_GET['result'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
603                $this->handle_login();
604                $this->display_sso_login_form();
605            } elseif ( ( new Status() )->in_safe_mode() ) {
606                add_filter( 'login_message', array( Notices::class, 'sso_not_allowed_in_safe_mode' ) );
607            } else {
608                // Is it wiser to just use wp_redirect than do this runaround to wp_safe_redirect?
609                add_filter( 'allowed_redirect_hosts', array( Helpers::class, 'allowed_redirect_hosts' ) );
610                $reauth  = ! empty( $_GET['force_reauth'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
611                $sso_url = $this->get_sso_url_or_die( $reauth );
612
613                $tracking->record_user_event( 'sso_login_redirect_success' );
614                wp_safe_redirect( $sso_url );
615                exit( 0 );
616            }
617        } elseif ( Helpers::display_sso_form_for_action( $action ) ) {
618
619            // Save cookies so we can handle redirects after SSO.
620            static::save_cookies();
621
622            /**
623             * Check to see if the site admin wants to automagically forward the user
624             * to the WordPress.com login page AND  that the request to wp-login.php
625             * is not something other than login (Like logout!)
626             */
627            if ( Helpers::bypass_login_forward_wpcom() && $this->wants_to_login() ) {
628                add_filter( 'allowed_redirect_hosts', array( Helpers::class, 'allowed_redirect_hosts' ) );
629                $reauth  = ! empty( $_GET['force_reauth'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
630                $sso_url = $this->get_sso_url_or_die( $reauth );
631                $tracking->record_user_event( 'sso_login_redirect_bypass_success' );
632                wp_safe_redirect( $sso_url );
633                exit( 0 );
634            }
635
636            $this->display_sso_login_form();
637        }
638    }
639
640    /**
641     * Ensures that we can get a nonce from WordPress.com via XML-RPC before setting
642     * up the hooks required to display the SSO form.
643     */
644    public function display_sso_login_form() {
645        add_filter( 'login_body_class', array( $this, 'login_body_class' ) );
646        add_action( 'login_enqueue_scripts', array( $this, 'enqueue_login_styles' ) );
647
648        if ( ( new Status() )->in_safe_mode() ) {
649            add_filter( 'login_message', array( Notices::class, 'sso_not_allowed_in_safe_mode' ) );
650            return;
651        }
652
653        $sso_nonce = self::request_initial_nonce();
654        if ( is_wp_error( $sso_nonce ) ) {
655            return;
656        }
657
658        add_action( 'login_form', array( $this, 'login_form' ) );
659        add_action( 'login_enqueue_scripts', array( $this, 'login_enqueue_scripts' ) );
660    }
661
662    /**
663     * Conditionally save the redirect_to url as a cookie.
664     *
665     * @since jetpack-4.6.0 Renamed to save_cookies from maybe_save_redirect_cookies
666     */
667    public static function save_cookies() {
668        if ( headers_sent() ) {
669            return new WP_Error( 'headers_sent', __( 'Cannot deal with cookie redirects, as headers are already sent.', 'jetpack-connection' ) );
670        }
671
672        setcookie(
673            'jetpack_sso_original_request',
674        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sniff misses the wrapping esc_url_raw().
675            esc_url_raw( set_url_scheme( ( isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : '' ) . ( isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : '' ) ) ),
676            time() + HOUR_IN_SECONDS,
677            COOKIEPATH,
678            COOKIE_DOMAIN,
679            is_ssl(),
680            true
681        );
682
683        // Persist the WordPress.com referrer signal so it survives the SSO button
684        // click, which changes the HTTP Referer to the site's own login page.
685        // Uses the live-only check to avoid a self-reinforcing cookie loop.
686        if ( self::is_live_referrer_wpcom() ) {
687            setcookie( 'jetpack_sso_wpcom_referrer', '1', time() + ( 10 * MINUTE_IN_SECONDS ), COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
688            $_COOKIE['jetpack_sso_wpcom_referrer'] = '1';
689        } elseif ( ! empty( $_COOKIE['jetpack_sso_wpcom_referrer'] ) ) {
690            setcookie( 'jetpack_sso_wpcom_referrer', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
691            unset( $_COOKIE['jetpack_sso_wpcom_referrer'] );
692        }
693
694        if ( ! empty( $_GET['redirect_to'] ) && is_string( $_GET['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
695            // If we have something to redirect to.
696            $url = esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
697            setcookie( 'jetpack_sso_redirect_to', $url, time() + HOUR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
698        } elseif ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
699            // Otherwise, if it's already set, purge it.
700            setcookie( 'jetpack_sso_redirect_to', ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
701        }
702    }
703
704    /**
705     * Outputs the Jetpack SSO button and description as well as the toggle link
706     * for switching between Jetpack SSO and default login.
707     */
708    public function login_form() {
709        $site_name = get_bloginfo( 'name' );
710        if ( ! $site_name ) {
711            $site_name = get_bloginfo( 'url' );
712        }
713
714        $display_name = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] )
715        ? sanitize_text_field( wp_unslash( $_COOKIE[ 'jetpack_sso_wpcom_name_' . COOKIEHASH ] ) )
716        : false;
717        $gravatar     = ! empty( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] )
718        ? esc_url_raw( wp_unslash( $_COOKIE[ 'jetpack_sso_wpcom_gravatar_' . COOKIEHASH ] ) )
719        : false;
720
721        ?>
722        <div id="jetpack-sso-wrap">
723        <?php
724        /**
725         * Allow extension above Jetpack's SSO form.
726         *
727         * @module sso
728         *
729         * @since jetpack-8.6.0
730         */
731        do_action( 'jetpack_sso_login_form_above_wpcom' );
732
733        if ( $display_name && $gravatar && ! $this->two_step_required ) :
734            ?>
735                <div id="jetpack-sso-wrap__user">
736                    <img width="72" height="72" src="<?php echo esc_html( $gravatar ); ?>" />
737
738                    <h2>
739                <?php
740                echo wp_kses(
741                    /* translators: %s a user display name. */
742                    sprintf( __( 'Log in as <span>%s</span>', 'jetpack-connection' ), esc_html( $display_name ) ),
743                    array( 'span' => true )
744                );
745                ?>
746                    </h2>
747                </div>
748
749                <?php endif; ?>
750
751
752            <div id="jetpack-sso-wrap__action">
753                <?php if ( $this->two_step_required ) : ?>
754                    <?php // Opens in a new tab so this tab keeps the button to log in again after setup. ?>
755                    <a rel="noopener noreferrer" target="_blank" class="button button-primary" href="<?php echo esc_url( Redirect::get_url( 'calypso-me-security-two-step' ) ); ?>">
756                        <?php esc_html_e( 'Set up two-step authentication', 'jetpack-connection' ); ?>
757                    </a>
758                    <div class="jetpack-sso-then">
759                        <span><?php esc_html_e( 'Then', 'jetpack-connection' ); ?></span>
760                    </div>
761                    <?php echo $this->build_sso_button(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping done in build_sso_button() ?>
762                <?php else : ?>
763                    <?php echo $this->build_sso_button( array(), true ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaping done in build_sso_button() ?>
764
765                    <?php if ( $display_name && $gravatar ) : ?>
766                    <a rel="nofollow" class="jetpack-sso-wrap__reauth" href="<?php echo esc_url( $this->build_sso_button_url( array( 'force_reauth' => '1' ) ) ); ?>">
767                        <?php esc_html_e( 'Log in with another WordPress.com account', 'jetpack-connection' ); ?>
768                    </a>
769                <?php else : ?>
770                    <p>
771                        <?php
772                            /**
773                             * Filter the messeage displayed below the SSO button.
774                             *
775                             * @module sso
776                             *
777                             * @since jetpack-10.3.0
778                             *
779                             * @param string $sso_explanation Message displayed below the SSO button.
780                             */
781                            $sso_explanation = apply_filters(
782                                'jetpack_sso_login_form_explanation_text',
783                                sprintf(
784                                    /* Translators: %s is the name of the site. */
785                                    __( 'You can now save time spent logging in by connecting your WordPress.com account to %s.', 'jetpack-connection' ),
786                                    esc_html( $site_name )
787                                )
788                            );
789                            echo esc_html( $sso_explanation );
790                        ?>
791                    </p>
792                    <?php endif; ?>
793                <?php endif; ?>
794            </div>
795
796                    <?php
797                    /**
798                     * Allow extension below Jetpack's SSO form.
799                     *
800                     * @module sso
801                     *
802                     * @since jetpack-8.6.0
803                     */
804                    do_action( 'jetpack_sso_login_form_below_wpcom' );
805
806                    if ( ! Helpers::should_hide_login_form() ) :
807                        ?>
808                    <div class="jetpack-sso-or">
809                        <span><?php esc_html_e( 'Or', 'jetpack-connection' ); ?></span>
810                    </div>
811
812                    <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '1' ) ); ?>" class="jetpack-sso-toggle wpcom">
813                        <?php
814                        esc_html_e( 'Log in with username and password', 'jetpack-connection' )
815                        ?>
816                    </a>
817
818                    <a href="<?php echo esc_url( add_query_arg( 'jetpack-sso-show-default-form', '0' ) ); ?>" class="jetpack-sso-toggle default">
819                        <?php
820                        esc_html_e( 'Log in with WordPress.com', 'jetpack-connection' )
821                        ?>
822                    </a>
823                    <?php endif; ?>
824        </div>
825                <?php
826    }
827
828    /**
829     * Clear cookies that are no longer needed once the user has logged in.
830     *
831     * @since jetpack-4.8.0
832     */
833    public static function clear_cookies_after_login() {
834        Helpers::clear_wpcom_profile_cookies();
835        if ( isset( $_COOKIE['jetpack_sso_nonce'] ) ) {
836            setcookie(
837                'jetpack_sso_nonce',
838                ' ',
839                time() - YEAR_IN_SECONDS,
840                COOKIEPATH,
841                COOKIE_DOMAIN,
842                is_ssl(),
843                true
844            );
845        }
846
847        if ( isset( $_COOKIE['jetpack_sso_original_request'] ) ) {
848            setcookie(
849                'jetpack_sso_original_request',
850                ' ',
851                time() - YEAR_IN_SECONDS,
852                COOKIEPATH,
853                COOKIE_DOMAIN,
854                is_ssl(),
855                true
856            );
857        }
858
859        if ( isset( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
860            setcookie(
861                'jetpack_sso_redirect_to',
862                ' ',
863                time() - YEAR_IN_SECONDS,
864                COOKIEPATH,
865                COOKIE_DOMAIN,
866                is_ssl(),
867                true
868            );
869        }
870
871        if ( isset( $_COOKIE[ self::BROKER_COOKIE ] ) ) {
872            setcookie(
873                self::BROKER_COOKIE,
874                ' ',
875                time() - YEAR_IN_SECONDS,
876                COOKIEPATH,
877                COOKIE_DOMAIN,
878                is_ssl(),
879                true
880            );
881        }
882
883        if ( isset( $_COOKIE['jetpack_sso_wpcom_referrer'] ) ) {
884            setcookie(
885                'jetpack_sso_wpcom_referrer',
886                ' ',
887                time() - YEAR_IN_SECONDS,
888                COOKIEPATH,
889                COOKIE_DOMAIN,
890                is_ssl(),
891                true
892            );
893        }
894    }
895
896    /**
897     * Clean up after Jetpack gets disconnected.
898     *
899     * @since jetpack-10.7
900     */
901    public static function disconnect() {
902        if ( ( new Manager() )->is_user_connected() ) {
903            Helpers::delete_connection_for_user( get_current_user_id() );
904        }
905    }
906
907    /**
908     * Retrieves nonce used for SSO form.
909     *
910     * @return string|WP_Error
911     */
912    public static function request_initial_nonce() {
913        $nonce = ! empty( $_COOKIE['jetpack_sso_nonce'] )
914        ? sanitize_key( wp_unslash( $_COOKIE['jetpack_sso_nonce'] ) )
915        : false;
916
917        if ( ! $nonce ) {
918            $xml = new Jetpack_IXR_Client();
919            $xml->query( 'jetpack.sso.requestNonce' );
920
921            if ( $xml->isError() ) {
922                return new WP_Error( $xml->getErrorCode(), $xml->getErrorMessage() );
923            }
924
925            $response = $xml->getResponse();
926
927            // The response may be a plain nonce string (default) or an associative
928            // array containing 'nonce' and a 'use_sso_broker' signal for sites that
929            // use an external SSO broker (e.g. CIAB stores via the MSD).
930            if ( is_array( $response ) ) {
931                if ( empty( $response['nonce'] ) ) {
932                    return new WP_Error( 'invalid_response', __( 'Invalid nonce response from WordPress.com.', 'jetpack-connection' ) );
933                }
934
935                $nonce      = sanitize_key( $response['nonce'] );
936                $use_broker = ! empty( $response['use_sso_broker'] );
937            } else {
938                $nonce      = sanitize_key( $response );
939                $use_broker = false;
940            }
941
942            $cookie_expiry = time() + ( 10 * MINUTE_IN_SECONDS );
943
944            setcookie(
945                'jetpack_sso_nonce',
946                $nonce,
947                $cookie_expiry,
948                COOKIEPATH,
949                COOKIE_DOMAIN,
950                is_ssl(),
951                true
952            );
953            // Ensure this request can use the nonce immediately after setcookie().
954            $_COOKIE['jetpack_sso_nonce'] = $nonce;
955
956            if ( $use_broker ) {
957                setcookie(
958                    self::BROKER_COOKIE,
959                    $nonce,
960                    $cookie_expiry,
961                    COOKIEPATH,
962                    COOKIE_DOMAIN,
963                    is_ssl(),
964                    true
965                );
966                // Mirror the broker signal in-memory for this request.
967                $_COOKIE[ self::BROKER_COOKIE ] = $nonce;
968            } else {
969                setcookie( self::BROKER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true );
970                unset( $_COOKIE[ self::BROKER_COOKIE ] );
971            }
972        }
973
974        return $nonce;
975    }
976
977    /**
978     * Validates a broker URL string.
979     *
980     * @param string $url The URL to validate.
981     * @return string|false The URL if valid HTTPS with a host, or false.
982     */
983    private static function validate_broker_url( $url ) {
984        if ( empty( $url ) || ! is_string( $url ) ) {
985            return false;
986        }
987
988        $sanitized = esc_url_raw( $url );
989        $url_parts = wp_parse_url( $sanitized );
990
991        if ( $url_parts && 'https' === ( $url_parts['scheme'] ?? '' ) && ! empty( $url_parts['host'] ) ) {
992            return $sanitized;
993        }
994
995        return false;
996    }
997
998    /**
999     * Checks whether WP.com has authorized broker mode for the current SSO flow.
1000     *
1001     * The broker cookie is set during the nonce request when WP.com signals
1002     * that broker SSO should be used. Its value matches the SSO nonce to tie
1003     * the authorization to a specific flow.
1004     *
1005     * @return bool True if WP.com authorized broker mode for this nonce.
1006     */
1007    private static function is_broker_authorized() {
1008        $broker_signal = ! empty( $_COOKIE[ self::BROKER_COOKIE ] )
1009            ? sanitize_key( wp_unslash( $_COOKIE[ self::BROKER_COOKIE ] ) )
1010            : false;
1011        $current_nonce = ! empty( $_COOKIE['jetpack_sso_nonce'] )
1012            ? sanitize_key( wp_unslash( $_COOKIE['jetpack_sso_nonce'] ) )
1013            : false;
1014
1015        return $broker_signal && $current_nonce && $broker_signal === $current_nonce;
1016    }
1017
1018    /**
1019     * Checks whether the current request's referrer is a WordPress.com domain.
1020     *
1021     * Used to skip the broker URL when the user navigated from Calypso or
1022     * another WordPress.com interface, so they stay within the expected
1023     * wordpress.com SSO flow.
1024     *
1025     * @return bool True if the referrer is a WordPress.com domain.
1026     */
1027    private static function is_referrer_wpcom() {
1028        // Check the cookie persisted by save_cookies() on the initial login page
1029        // load. The live HTTP Referer changes to the site's own wp-login.php when
1030        // the user clicks the SSO button, so the cookie carries the original signal.
1031        if ( ! empty( $_COOKIE['jetpack_sso_wpcom_referrer'] ) ) {
1032            return true;
1033        }
1034
1035        return self::is_live_referrer_wpcom();
1036    }
1037
1038    /**
1039     * Checks the live HTTP Referer header against WordPress.com domains.
1040     *
1041     * Unlike is_referrer_wpcom(), this does NOT consult the persisted cookie,
1042     * so it is safe to call from save_cookies() without creating a
1043     * self-reinforcing loop.
1044     *
1045     * @return bool True if the live referrer is a WordPress.com domain.
1046     */
1047    private static function is_live_referrer_wpcom() {
1048        $referer = wp_get_raw_referer();
1049        if ( ! $referer ) {
1050            return false;
1051        }
1052
1053        $wpcom_hosts = array(
1054            'wordpress.com',
1055            'horizon.wordpress.com',
1056            'wpcalypso.wordpress.com',
1057        );
1058
1059        $referer_host = wp_parse_url( $referer, PHP_URL_HOST );
1060        return $referer_host && in_array( $referer_host, $wpcom_hosts, true );
1061    }
1062
1063    /**
1064     * Retrieves the SSO broker URL if authorized by WP.com and defined by the MU plugin.
1065     *
1066     * The broker URL is read from the JETPACK_SSO_BROKER_URL constant, which
1067     * is expected to be defined by a garden MU plugin (e.g. for CIAB stores).
1068     * It is only used when WP.com has signaled broker mode via the nonce response.
1069     *
1070     * @return string|false The broker URL, or false if not available.
1071     */
1072    public static function get_broker_url() {
1073        if ( ! self::is_broker_authorized() ) {
1074            return false;
1075        }
1076        $url = Constants::get_constant( 'JETPACK_SSO_BROKER_URL' );
1077        return $url ? self::validate_broker_url( $url ) : false;
1078    }
1079
1080    /**
1081     * Retrieves the SSO broker authorization URL if authorized by WP.com.
1082     *
1083     * For broker sites, this URL replaces the Jetpack authorization endpoint
1084     * for establishing user connections. Read from the JETPACK_SSO_BROKER_AUTH_URL
1085     * constant defined by the garden MU plugin.
1086     *
1087     * @return string|false The broker authorization URL, or false if not available.
1088     */
1089    public static function get_broker_auth_url() {
1090        if ( ! self::is_broker_authorized() ) {
1091            return false;
1092        }
1093        $url = Constants::get_constant( 'JETPACK_SSO_BROKER_AUTH_URL' );
1094        return $url ? self::validate_broker_url( $url ) : false;
1095    }
1096
1097    /**
1098     * The function that actually handles the login!
1099     */
1100    public function handle_login() {
1101        $wpcom_nonce   = isset( $_GET['sso_nonce'] ) ? sanitize_key( $_GET['sso_nonce'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1102        $wpcom_user_id = isset( $_GET['user_id'] ) ? (int) $_GET['user_id'] : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1103
1104        $token_lookup             = $this->get_signed_user_token_for_wpcom_id( $wpcom_user_id );
1105        $signed_user_token        = $token_lookup['signed_token'];
1106        $token_validated_for_user = $token_lookup['local_user_id'];
1107
1108        $xml = new Jetpack_IXR_Client();
1109        if ( $signed_user_token ) {
1110            $xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id, $signed_user_token );
1111        } else {
1112            $xml->query( 'jetpack.sso.validateResult', $wpcom_nonce, $wpcom_user_id );
1113        }
1114
1115        $user_data = $xml->isError() ? false : $xml->getResponse();
1116        if ( empty( $user_data ) ) {
1117            add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
1118            add_filter( 'login_message', array( Notices::class, 'error_invalid_response_data' ) );
1119            return;
1120        }
1121
1122        $user_data = (object) $user_data;
1123        $user      = null;
1124
1125        /**
1126         * Fires before Jetpack's SSO modifies the log in form.
1127         *
1128         * @module sso
1129         *
1130         * @since jetpack-2.6.0
1131         *
1132         * @param object $user_data WordPress.com User information.
1133         */
1134        do_action( 'jetpack_sso_pre_handle_login', $user_data );
1135
1136        $tracking = new Tracking();
1137
1138        if ( Helpers::is_two_step_required() && 0 === (int) $user_data->two_step_enabled ) {
1139            $this->user_data         = $user_data;
1140            $this->two_step_required = true;
1141
1142            $tracking->record_user_event(
1143                'sso_login_failed',
1144                array(
1145                    'error_message' => 'error_msg_enable_two_step',
1146                )
1147            );
1148
1149            $error = new WP_Error( 'two_step_required', __( 'You must have Two-Step Authentication enabled on your WordPress.com account.', 'jetpack-connection' ) );
1150
1151            /** This filter is documented in core/src/wp-includes/pluggable.php */
1152            do_action( 'wp_login_failed', $user_data->login, $error );
1153            add_filter(
1154                'login_message',
1155                function ( $message ) use ( $user_data ) {
1156                    return Notices::error_msg_enable_two_step( $message, $user_data );
1157                }
1158            );
1159            return;
1160        }
1161
1162        $user_found_with = '';
1163        if ( isset( $user_data->external_user_id ) ) {
1164            $user_found_with = 'external_user_id';
1165            $user            = get_user_by( 'id', (int) $user_data->external_user_id );
1166            if ( $user ) {
1167                $expected_id = Utils::get_wpcom_user_id( $user->ID );
1168                if ( $expected_id && $expected_id !== (int) $user_data->ID ) {
1169                    $error = new WP_Error( 'expected_wpcom_user', __( 'Something got a little mixed up and an unexpected WordPress.com user logged in.', 'jetpack-connection' ) );
1170
1171                    $tracking->record_user_event(
1172                        'sso_login_failed',
1173                        array(
1174                            'error_message' => 'error_unexpected_wpcom_user',
1175                        )
1176                    );
1177
1178                    /** This filter is documented in core/src/wp-includes/pluggable.php */
1179                    do_action( 'wp_login_failed', $user_data->login, $error );
1180                    add_filter( 'login_message', array( Notices::class, 'error_invalid_response_data' ) ); // @todo Need to have a better notice. This is only for the sake of testing the validation.
1181                    return;
1182                }
1183                self::set_wpcom_user_id_meta( $user->ID, $user_data->ID );
1184            }
1185        }
1186
1187        // If we don't have one by wpcom_user_id, try by the email?
1188        if ( empty( $user ) && Helpers::match_by_email() ) {
1189            $user_found_with = 'match_by_email';
1190            $user            = get_user_by( 'email', $user_data->email );
1191            if ( $user ) {
1192                self::set_wpcom_user_id_meta( $user->ID, $user_data->ID );
1193            }
1194        }
1195
1196        // If we've still got nothing, create the user.
1197        $new_user_override_role = Helpers::new_user_override( $user_data );
1198        if ( empty( $user ) && ( get_option( 'users_can_register' ) || $new_user_override_role ) ) {
1199            /**
1200             * If not matching by email we still need to verify the email does not exist
1201             * or this blows up
1202             *
1203             * If match_by_email is true, we know the email doesn't exist, as it would have
1204             * been found in the first pass.  If get_user_by( 'email' ) doesn't find the
1205             * user, then we know that email is unused, so it's safe to add.
1206             */
1207            if ( Helpers::match_by_email() || ! get_user_by( 'email', $user_data->email ) ) {
1208
1209                if ( $new_user_override_role ) {
1210                    $user_data->role = $new_user_override_role;
1211                }
1212
1213                $user = Utils::generate_user( $user_data );
1214                if ( ! $user ) {
1215                    $tracking->record_user_event(
1216                        'sso_login_failed',
1217                        array(
1218                            'error_message' => 'could_not_create_username',
1219                        )
1220                    );
1221                    add_filter( 'login_message', array( Notices::class, 'error_unable_to_create_user' ) );
1222                    return;
1223                }
1224
1225                $user_found_with = $new_user_override_role
1226                ? 'user_created_new_user_override'
1227                : 'user_created_users_can_register';
1228            } else {
1229                $tracking->record_user_event(
1230                    'sso_login_failed',
1231                    array(
1232                        'error_message' => 'error_msg_email_already_exists',
1233                    )
1234                );
1235
1236                $this->user_data = $user_data;
1237                add_action( 'login_message', array( Notices::class, 'error_msg_email_already_exists' ) );
1238                return;
1239            }
1240        }
1241
1242        /**
1243         * Fires after we got login information from WordPress.com.
1244         *
1245         * @module sso
1246         *
1247         * @since jetpack-2.6.0
1248         *
1249         * @param WP_User|false|null $user      Local User information.
1250         * @param object             $user_data WordPress.com User Login information.
1251         */
1252        do_action( 'jetpack_sso_handle_login', $user, $user_data );
1253
1254        if ( $user ) {
1255            // Cache the user's details, so we can present it back to them on their user screen.
1256            update_user_meta( $user->ID, 'wpcom_user_data', $user_data );
1257
1258            /*
1259             * Two-Factor plugin 0.15.0+ unconditionally hooks wp_login at PHP_INT_MAX,
1260             * which destroys the auth session and prompts for local 2FA â€” even for SSO
1261             * logins that already completed 2FA on WordPress.com.
1262             *
1263             * When WP.com confirms the user has 2FA active, remove Two-Factor's wp_login
1264             * hook so SSO can complete without a redundant local 2FA prompt.
1265             *
1266             * When WP.com 2FA is NOT active, the hook stays and Two-Factor can enforce
1267             * local 2FA as a safety net.
1268             *
1269             * @see https://github.com/WordPress/two-factor/issues/811
1270             */
1271            /**
1272             * Filter whether to accept WordPress.com 2FA in place of a local
1273             * Two-Factor prompt during SSO login.
1274             *
1275             * Return false to always require the local Two-Factor prompt,
1276             * even when the user has completed 2FA on WordPress.com.
1277             *
1278             * @since 8.1.0
1279             * @module sso
1280             *
1281             * @param bool    $accept    Whether to accept WP.com 2FA. Default true.
1282             * @param object  $user_data WordPress.com user data from SSO validation.
1283             * @param WP_User $user      The local WordPress user.
1284             */
1285            $accept_wpcom_2fa = apply_filters( 'jetpack_sso_accept_wpcom_2fa', true, $user_data, $user );
1286
1287            if (
1288                ! empty( $user_data->two_step_enabled )
1289                && class_exists( 'Two_Factor_Core' )
1290                && $accept_wpcom_2fa
1291            ) {
1292                self::$sso_user_for_2fa = $user;
1293                add_filter( 'attach_session_information', array( static::class, 'add_two_factor_session_meta' ), 10, 2 );
1294
1295                remove_action( 'wp_login', array( 'Two_Factor_Core', 'wp_login' ), PHP_INT_MAX );
1296            }
1297
1298            add_filter( 'auth_cookie_expiration', array( Helpers::class, 'extend_auth_cookie_expiration_for_sso' ) );
1299            wp_set_auth_cookie( $user->ID, true );
1300            remove_filter( 'auth_cookie_expiration', array( Helpers::class, 'extend_auth_cookie_expiration_for_sso' ) );
1301            remove_filter( 'attach_session_information', array( static::class, 'add_two_factor_session_meta' ), 10 );
1302
1303            /** This filter is documented in core/src/wp-includes/user.php */
1304            do_action( 'wp_login', $user->user_login, $user );
1305
1306            wp_set_current_user( $user->ID );
1307
1308            $json_api_auth_environment = Helpers::get_json_api_auth_environment();
1309
1310            $is_json_api_auth  = ! empty( $json_api_auth_environment );
1311            $manager           = new Manager();
1312            $is_user_connected = $manager->is_user_connected( $user->ID );
1313
1314            if ( $is_user_connected ) {
1315                $is_user_connected = $this->verify_user_token(
1316                    $user->ID,
1317                    $user_data,
1318                    $manager->get_tokens(),
1319                    $token_validated_for_user
1320                );
1321            }
1322
1323            $roles = new Roles();
1324            $tracking->record_user_event(
1325                'sso_user_logged_in',
1326                array(
1327                    'user_found_with'  => $user_found_with,
1328                    'user_connected'   => (bool) $is_user_connected,
1329                    'user_role'        => $roles->translate_current_user_to_role(),
1330                    'is_json_api_auth' => $is_json_api_auth,
1331                )
1332            );
1333
1334            $_request_redirect_to = isset( $_REQUEST['redirect_to'] ) ? esc_url_raw( wp_unslash( $_REQUEST['redirect_to'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1335            $redirect_to          = user_can( $user, 'edit_posts' ) ? admin_url() : self::profile_page_url();
1336
1337            // If we have a saved redirect to request in a cookie.
1338            if ( ! empty( $_COOKIE['jetpack_sso_redirect_to'] ) ) {
1339                // Set that as the requested redirect to.
1340                $redirect_to          = esc_url_raw( wp_unslash( $_COOKIE['jetpack_sso_redirect_to'] ) );
1341                $_request_redirect_to = $redirect_to;
1342            }
1343
1344            if ( $is_json_api_auth ) {
1345                $authorize_json_api = new Authorize_Json_Api();
1346                $authorize_json_api->verify_json_api_authorization_request( $json_api_auth_environment );
1347                $authorize_json_api->store_json_api_authorization_token( $user->user_login, $user );
1348
1349            } elseif ( ! $is_user_connected ) {
1350                $broker_auth_url = self::get_broker_auth_url();
1351                if ( $broker_auth_url ) {
1352                    add_filter( 'allowed_redirect_hosts', array( Helpers::class, 'allowed_redirect_hosts' ) );
1353                    wp_safe_redirect(
1354                        add_query_arg(
1355                            array(
1356                                'action'                   => 'jetpack-sso',
1357                                'site_id'                  => Manager::get_site_id( true ),
1358                                'redirect_to'              => $redirect_to,
1359                                'request_redirect_to'      => $_request_redirect_to,
1360                                'broker-sso-auth-redirect' => '1',
1361                            ),
1362                            $broker_auth_url
1363                        )
1364                    );
1365                    exit( 0 );
1366                }
1367
1368                wp_safe_redirect(
1369                    add_query_arg(
1370                        array(
1371                            'redirect_to'               => $redirect_to,
1372                            'request_redirect_to'       => $_request_redirect_to,
1373                            'calypso_env'               => ( new Host() )->get_calypso_env(),
1374                            'jetpack-sso-auth-redirect' => '1',
1375                        ),
1376                        admin_url()
1377                    )
1378                );
1379                exit( 0 );
1380            }
1381
1382            add_filter( 'allowed_redirect_hosts', array( Helpers::class, 'allowed_redirect_hosts' ) );
1383            wp_safe_redirect(
1384            /** This filter is documented in core/src/wp-login.php */
1385                apply_filters( 'login_redirect', $redirect_to, $_request_redirect_to, $user )
1386            );
1387            exit( 0 );
1388        }
1389
1390        add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
1391
1392        $tracking->record_user_event(
1393            'sso_login_failed',
1394            array(
1395                'error_message' => 'cant_find_user',
1396            )
1397        );
1398
1399        $this->user_data = $user_data;
1400
1401        $error = new WP_Error( 'account_not_found', __( 'Account not found. If you already have an account, make sure you have connected to WordPress.com.', 'jetpack-connection' ) );
1402
1403        /** This filter is documented in core/src/wp-includes/pluggable.php */
1404        do_action( 'wp_login_failed', $user_data->login, $error );
1405        add_filter( 'login_message', array( Notices::class, 'cant_find_user' ) );
1406    }
1407
1408    /**
1409     * Retrieve the admin profile page URL.
1410     */
1411    public static function profile_page_url() {
1412        return admin_url( 'profile.php' );
1413    }
1414
1415    /**
1416     * Builds the "Login to WordPress.com" button that is displayed on the login page as well as user profile page.
1417     *
1418     * @param  array   $args       An array of arguments to add to the SSO URL.
1419     * @param  boolean $is_primary If the button have the `button-primary` class.
1420     * @return string              Returns the HTML markup for the button.
1421     */
1422    public function build_sso_button( $args = array(), $is_primary = false ) {
1423        $url     = $this->build_sso_button_url( $args );
1424        $classes = $is_primary
1425        ? 'jetpack-sso button button-primary'
1426        : 'jetpack-sso button';
1427
1428        return sprintf(
1429            '<a rel="nofollow" href="%1$s" class="%2$s">%3$s %4$s</a>',
1430            esc_url( $url ),
1431            $classes,
1432            '<span class="genericon genericon-wordpress"></span>',
1433            esc_html__( 'Log in with WordPress.com', 'jetpack-connection' )
1434        );
1435    }
1436
1437    /**
1438     * Builds a URL with `jetpack-sso` action and option args which is used to setup SSO.
1439     *
1440     * @param  array $args An array of arguments to add to the SSO URL.
1441     * @return string       The URL used for SSO.
1442     */
1443    public function build_sso_button_url( $args = array() ) {
1444        $defaults = array(
1445            'action' => 'jetpack-sso',
1446        );
1447
1448        $args = wp_parse_args( $args, $defaults );
1449
1450        if ( ! empty( $_GET['redirect_to'] ) && is_string( $_GET['redirect_to'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1451            $args['redirect_to'] = rawurlencode( esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1452        }
1453
1454        return add_query_arg( $args, wp_login_url() );
1455    }
1456
1457    /**
1458     * Retrieves a WordPress.com SSO URL with appropriate query parameters or dies.
1459     *
1460     * @param  boolean $reauth  If the user be forced to reauthenticate on WordPress.com.
1461     * @param  array   $args    Optional query parameters.
1462     * @return string            The WordPress.com SSO URL.
1463     */
1464    public function get_sso_url_or_die( $reauth = false, $args = array() ) {
1465        $custom_login_url = Helpers::get_custom_login_url();
1466        if ( $custom_login_url ) {
1467            $args['login_url'] = rawurlencode( $custom_login_url );
1468        }
1469
1470        if ( empty( $reauth ) ) {
1471            $sso_redirect = $this->build_sso_url( $args );
1472        } else {
1473            Helpers::clear_wpcom_profile_cookies();
1474            $sso_redirect = $this->build_reauth_and_sso_url( $args );
1475        }
1476
1477        // If there was an error retrieving the SSO URL, then error.
1478        if ( is_wp_error( $sso_redirect ) ) {
1479            $error_message = sanitize_text_field(
1480                sprintf( '%s: %s', $sso_redirect->get_error_code(), $sso_redirect->get_error_message() )
1481            );
1482            $tracking      = new Tracking();
1483            $tracking->record_user_event(
1484                'sso_login_redirect_failed',
1485                array(
1486                    'error_message' => $error_message,
1487                )
1488            );
1489            wp_die( esc_html( $error_message ) );
1490        }
1491
1492        return $sso_redirect;
1493    }
1494
1495    /**
1496     * Returns the base URL for SSO authentication.
1497     *
1498     * If a broker URL is available (authorized by WP.com and defined by the
1499     * garden MU plugin), that URL is used unless the user navigated from a
1500     * WordPress.com domain. Otherwise falls back to the default WordPress.com
1501     * login URL.
1502     *
1503     * @return string The base SSO URL.
1504     */
1505    public static function get_sso_base_url() {
1506        $broker_url = self::get_broker_url();
1507        if ( $broker_url && ! self::is_referrer_wpcom() ) {
1508            return $broker_url;
1509        }
1510        return 'https://wordpress.com/wp-login.php';
1511    }
1512
1513    /**
1514     * Build SSO URL with appropriate query parameters.
1515     *
1516     * The base URL can be WordPress.com or an authorized broker URL.
1517     *
1518     * @param array $args Optional query parameters.
1519     * @return string|WP_Error Redirect URL for SSO authentication.
1520     */
1521    public function build_sso_url( $args = array() ) {
1522        $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
1523        $defaults  = array(
1524            'action'       => 'jetpack-sso',
1525            'site_id'      => Manager::get_site_id( true ),
1526            'sso_nonce'    => $sso_nonce,
1527            'calypso_auth' => '1',
1528        );
1529
1530        $args = wp_parse_args( $args, $defaults );
1531
1532        if ( is_wp_error( $sso_nonce ) ) {
1533            return $sso_nonce;
1534        }
1535
1536        return add_query_arg( $args, self::get_sso_base_url() );
1537    }
1538
1539    /**
1540     * Build SSO URL with appropriate query parameters, including the
1541     * parameters necessary to force the user to reauthenticate.
1542     *
1543     * @param array $args Optional query parameters.
1544     * @return string|WP_Error Redirect URL for SSO authentication.
1545     */
1546    public function build_reauth_and_sso_url( $args = array() ) {
1547        $sso_nonce = ! empty( $args['sso_nonce'] ) ? $args['sso_nonce'] : self::request_initial_nonce();
1548        $redirect  = $this->build_sso_url(
1549            array(
1550                'force_auth' => '1',
1551                'sso_nonce'  => $sso_nonce,
1552            )
1553        );
1554
1555        if ( is_wp_error( $redirect ) ) {
1556            return $redirect;
1557        }
1558
1559        $defaults = array(
1560            'action'       => 'jetpack-sso',
1561            'site_id'      => Manager::get_site_id( true ),
1562            'sso_nonce'    => $sso_nonce,
1563            'reauth'       => '1',
1564            'redirect_to'  => rawurlencode( $redirect ),
1565            'calypso_auth' => '1',
1566        );
1567
1568        $args = wp_parse_args( $args, $defaults );
1569
1570        if ( is_wp_error( $args['sso_nonce'] ) ) {
1571            return $args['sso_nonce'];
1572        }
1573
1574        return add_query_arg( $args, self::get_sso_base_url() );
1575    }
1576
1577    /**
1578     * Sets the wpcom_user_id meta on a local user.
1579     *
1580     * @since 8.6.0
1581     *
1582     * @param int $user_id       The local WordPress user ID to set the meta on.
1583     * @param int $wpcom_user_id The WordPress.com user ID.
1584     */
1585    private static function set_wpcom_user_id_meta( $user_id, $wpcom_user_id ) {
1586        Utils::set_wpcom_user_id( $user_id, $wpcom_user_id );
1587    }
1588
1589    /**
1590     * Determines local user associated with a given WordPress.com user ID.
1591     *
1592     * @since jetpack-2.6.0
1593     *
1594     * @param int $wpcom_user_id User ID from WordPress.com.
1595     * @return null|object Local user object if found, null if not.
1596     */
1597    public static function get_user_by_wpcom_id( $wpcom_user_id ) {
1598        $user_query = new WP_User_Query(
1599            array(
1600                'meta_key'   => 'wpcom_user_id',
1601                'meta_value' => (int) $wpcom_user_id,
1602                'number'     => 1,
1603            )
1604        );
1605
1606        $users = $user_query->get_results();
1607        return $users ? array_shift( $users ) : null;
1608    }
1609
1610    /**
1611     * Retrieves the signed user token for a given WP.com user ID, if one exists locally.
1612     *
1613     * Looks up the local WordPress user associated with the WP.com user ID and returns
1614     * a signed representation of their user token along with the local user ID.
1615     * The signed token is sent to WP.com during SSO validation so WP.com can verify
1616     * the token is still valid on its side.
1617     *
1618     * @since 8.6.0
1619     *
1620     * @param int $wpcom_user_id The WordPress.com user ID.
1621     * @return array{signed_token: string, local_user_id: int} The signed token and local user ID.
1622     *               Both values are 0/empty when no valid token exists.
1623     */
1624    private function get_signed_user_token_for_wpcom_id( $wpcom_user_id ) {
1625        $result = array(
1626            'signed_token'  => '',
1627            'local_user_id' => 0,
1628        );
1629
1630        if ( ! $wpcom_user_id ) {
1631            return $result;
1632        }
1633
1634        $local_user = self::get_user_by_wpcom_id( $wpcom_user_id );
1635        if ( ! $local_user ) {
1636            return $result;
1637        }
1638
1639        $tokens     = new Tokens();
1640        $user_token = $tokens->get_access_token( $local_user->ID );
1641        if ( ! $user_token ) {
1642            return $result;
1643        }
1644
1645        $signed = $tokens->get_signed_token( $user_token );
1646        if ( is_wp_error( $signed ) ) {
1647            return $result;
1648        }
1649
1650        $result['signed_token']  = $signed;
1651        $result['local_user_id'] = $local_user->ID;
1652        return $result;
1653    }
1654
1655    /**
1656     * Verifies that a locally-stored user token is still valid on WP.com.
1657     *
1658     * Uses the `user_token_valid` field from the SSO validate response when the
1659     * signed token was sent for the same user that was resolved during login.
1660     *
1661     * When the validate response can't be trusted for this user (a different user
1662     * was resolved, or no signed token was sent), login proceeds without an extra
1663     * verification call. In that case `set_wpcom_user_id_meta()` records the
1664     * mapping during this login, so the fast path validates the token on the next
1665     * SSO login. This avoids an extra HTTP request on every first-SSO login and
1666     * keeps the Error_Handler from being triggered for users whose token state can
1667     * only be resolved by a direct token-health check.
1668     *
1669     * If the token is found to be invalid, it is removed locally so the user will be
1670     * prompted to re-authorize and obtain a fresh token.
1671     *
1672     * @since 8.6.0
1673     *
1674     * @param int    $user_id                  The local WordPress user ID (the resolved user).
1675     * @param object $user_data                The WP.com user data from jetpack.sso.validateResult.
1676     * @param Tokens $tokens                   The Tokens instance.
1677     * @param int    $token_validated_for_user  The local user ID whose token was sent to WP.com, or 0 if none.
1678     * @return bool True if the user token is valid (or could not be verified), false if invalid and removed.
1679     */
1680    private function verify_user_token( $user_id, $user_data, Tokens $tokens, $token_validated_for_user ) {
1681        // Only trust the validateResult response if the signed token was for this same user.
1682        if ( $token_validated_for_user === $user_id && isset( $user_data->user_token_valid ) ) {
1683            if ( false === $user_data->user_token_valid ) {
1684                $tokens->disconnect_user( $user_id );
1685                return false;
1686            }
1687            return true;
1688        }
1689
1690        // The signed token was for a different user (or wasn't sent at all), so the
1691        // validateResult response can't be trusted for this user. Let login proceed;
1692        // the wpcom_user_id meta set during this login means the next SSO login will
1693        // validate the token via the fast path.
1694        return true;
1695    }
1696
1697    /**
1698     * When jetpack-sso-auth-redirect query parameter is set, will redirect user to
1699     * WordPress.com authorization flow.
1700     *
1701     * We redirect here instead of in handle_login() because Jetpack::init()->build_connect_url
1702     * calls menu_page_url() which doesn't work properly until admin menus are registered.
1703     */
1704    public function maybe_authorize_user_after_sso() {
1705        if ( empty( $_GET['jetpack-sso-auth-redirect'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1706            return;
1707        }
1708
1709        $redirect_to         = ! empty( $_GET['redirect_to'] ) && is_string( $_GET['redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['redirect_to'] ) ) : admin_url(); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1710        $request_redirect_to = ! empty( $_GET['request_redirect_to'] ) && is_string( $_GET['request_redirect_to'] ) ? esc_url_raw( wp_unslash( $_GET['request_redirect_to'] ) ) : $redirect_to; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
1711
1712        /** This filter is documented in core/src/wp-login.php */
1713        $redirect_after_auth = apply_filters( 'login_redirect', $redirect_to, $request_redirect_to, wp_get_current_user() );
1714
1715        /**
1716         * Since we are passing this redirect to WordPress.com and therefore cannot use wp_safe_redirect(),
1717         * let's sanitize it here to make sure it's safe. If the redirect is not safe, then use admin_url().
1718         */
1719        $redirect_after_auth = wp_sanitize_redirect( $redirect_after_auth );
1720        $redirect_after_auth = wp_validate_redirect( $redirect_after_auth, admin_url() );
1721
1722        /**
1723         * Return the raw connect URL with our redirect and attribute connection to SSO.
1724         * We remove any other filters that may be turning on the in-place connection
1725         * since we will be redirecting the user as opposed to iFraming.
1726         */
1727        remove_all_filters( 'jetpack_use_iframe_authorization_flow' );
1728        add_filter( 'jetpack_use_iframe_authorization_flow', '__return_false' );
1729
1730        $connection  = new Manager( 'jetpack-connection' );
1731        $connect_url = ( new Authorize_Redirect( $connection ) )->build_authorize_url( $redirect_after_auth, 'sso', true );
1732
1733        add_filter( 'allowed_redirect_hosts', array( Helpers::class, 'allowed_redirect_hosts' ) );
1734        wp_safe_redirect( $connect_url );
1735        exit( 0 );
1736    }
1737
1738    /**
1739     * Cache user's display name and Gravatar so it can be displayed on the login screen. These cookies are
1740     * stored when the user logs out, and then deleted when the user logs in.
1741     */
1742    public function store_wpcom_profile_cookies_on_logout() {
1743        $user_id = get_current_user_id();
1744        if ( ! ( new Manager() )->is_user_connected( $user_id ) ) {
1745            return;
1746        }
1747
1748        $user_data = $this->get_user_data( $user_id );
1749        if ( ! $user_data ) {
1750            return;
1751        }
1752
1753        setcookie(
1754            'jetpack_sso_wpcom_name_' . COOKIEHASH,
1755            $user_data->display_name,
1756            time() + WEEK_IN_SECONDS,
1757            COOKIEPATH,
1758            COOKIE_DOMAIN,
1759            is_ssl(),
1760            true
1761        );
1762
1763        setcookie(
1764            'jetpack_sso_wpcom_gravatar_' . COOKIEHASH,
1765            get_avatar_url(
1766                $user_data->email,
1767                array(
1768                    'size'    => 144,
1769                    'default' => 'mystery',
1770                )
1771            ),
1772            time() + WEEK_IN_SECONDS,
1773            COOKIEPATH,
1774            COOKIE_DOMAIN,
1775            is_ssl(),
1776            true
1777        );
1778    }
1779
1780    /**
1781     * Determines if a local user is connected to WordPress.com
1782     *
1783     * @since jetpack-2.8
1784     * @param integer $user_id - Local user id.
1785     * @return boolean
1786     **/
1787    public function is_user_connected( $user_id ) {
1788        return $this->get_user_data( $user_id );
1789    }
1790
1791    /**
1792     * Retrieves a user's WordPress.com data
1793     *
1794     * @since jetpack-2.8
1795     * @param integer $user_id - Local user id.
1796     * @return mixed null or stdClass
1797     **/
1798    public function get_user_data( $user_id ) {
1799        return get_user_meta( $user_id, 'wpcom_user_data', true );
1800    }
1801
1802    /**
1803     * Marks a session as two-factor-authenticated when SSO handled 2FA via WP.com.
1804     *
1805     * @param array $session Session information array.
1806     * @param int   $user_id User ID for the session being created.
1807     * @return array Modified session information.
1808     */
1809    public static function add_two_factor_session_meta( $session, $user_id ) {
1810        if ( self::$sso_user_for_2fa && self::$sso_user_for_2fa->ID === $user_id ) {
1811            $session['two-factor-login'] = time();
1812            self::$sso_user_for_2fa      = null;
1813        }
1814        return $session;
1815    }
1816}