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