settings = Plugin::get_settings( 'security' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); add_action( 'adminease_settings_saved', [ $this, 'adminease_settings_saved' ] ); add_filter( 'adminease_validate_settings', [ $this, 'validate_origins' ] ); if( !empty( $this->settings['cors_header'] ) ) { add_filter( 'rest_pre_serve_request', [ $this, 'rest_pre_serve_request' ], 20 ); if( !Utils::is_apache_compatible() ) { add_action( 'send_headers', [ $this, 'send_headers' ] ); } } } /** * Adds security-related fields, including the CORS header switch, to the settings fields array. * * @param array $fields An array of existing settings fields. * * @return array An updated array including CORS header field settings. */ public function adminease_settings_fields( array $fields ): array { $mode = Utils::is_apache_compatible() ? __( 'The headers are written to your .htaccess file.', 'adminease' ) : __( 'Your server does not read .htaccess files, so the headers are sent from PHP.', 'adminease' ); $fields['security']['fields'][] = [ 'type' => 'switch', 'id' => 'cors-header', 'name' => 'adminease[security][cors_header]', 'value' => $this->settings['cors_header'] ?? false, 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'CORS Header', 'adminease' ), 'description' => __( "Allow Cross-Origin Resource Sharing. Add the 'Access-Control-Allow-Origin:' header to responses.", 'adminease' ) . ' ' . $mode, 'child_fields' => [ [ 'type' => 'textarea', 'id' => 'cors-header-origins', 'name' => 'adminease[security][cors_header_origins]', 'value' => $this->settings['cors_header_origins'] ?? '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Allowed origins', 'adminease' ), 'field_description' => __( 'One site per line, for example https://app.example.com. Leave empty to allow every origin (*) without credentials.', 'adminease' ), 'attributes' => [ 'data-parent' => 'cors-header', ], ], ], ]; return $fields; } /** * Turns the saved textarea value into a clean list of origins. * * @param mixed $value The saved text. * * @return array Origins without a trailing slash, no empty lines, no duplicates. */ public static function parse_origins( $value ): array { if( !is_string( $value ) ) { return []; } $origins = []; foreach( preg_split( '/[\r\n]+/', $value ) as $line ) { $line = strtolower( rtrim( trim( $line ), '/' ) ); $line = preg_replace( '#^(https://[^/:]+):443$#', '$1', $line ); $line = preg_replace( '#^(http://[^/:]+):80$#', '$1', $line ); if( '' !== $line ) { $origins[] = $line; } } return array_values( array_unique( $origins ) ); } /** * Whether one origin is a scheme, host and optional port with nothing else. * * @param string $origin The origin to check. * * @return bool True when it is a valid origin. */ private static function is_valid_origin( string $origin ): bool { return 1 === preg_match( '#^https?://[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]{1,5})?$#i', $origin ); } /** * Refuses an origins list with an invalid or too many entries. * * @param array|\WP_Error $settings The settings about to be saved. * * @return array|\WP_Error The settings, or an error. */ public function validate_origins( $settings ) { if( !is_array( $settings ) || empty( $settings['security']['cors_header'] ) ) { return $settings; } $origins = self::parse_origins( $settings['security']['cors_header_origins'] ?? '' ); if( count( $origins ) > self::MAX_ORIGINS ) { return new \WP_Error( 'cors_header_origins', esc_html__( 'CORS allowed origins: at most 50 origins.', 'adminease' ) ); } foreach( $origins as $origin ) { if( !self::is_valid_origin( $origin ) ) { /* translators: %s: the refused origin. */ return new \WP_Error( 'cors_header_origins', sprintf( esc_html__( 'CORS allowed origins: %s is not valid. Use the form https://example.com, one per line, with no path.', 'adminease' ), esc_html( $origin ) ) ); } } return $settings; } /** * Returns the origins allowed by the saved list, keeping only valid ones. * * @return array The allowed origins, empty when every origin is allowed. */ private function get_allowed_origins(): array { return array_values( array_filter( self::parse_origins( $this->settings['cors_header_origins'] ?? '' ), [ self::class, 'is_valid_origin' ] ) ); } /** * Builds the CORS headers for a request. * * @param string $request_origin The Origin header of the request, empty when none. * * @return array Header name => value. Empty when the origin is not allowed. */ public function get_headers( string $request_origin ): array { $allowed = $this->get_allowed_origins(); if( empty( $allowed ) ) { $headers = [ 'Access-Control-Allow-Origin' => '*' ]; } elseif( '' !== $request_origin && in_array( strtolower( rtrim( $request_origin, '/' ) ), $allowed, true ) ) { $headers = [ 'Access-Control-Allow-Origin' => strtolower( rtrim( $request_origin, '/' ) ), 'Access-Control-Allow-Credentials' => 'true', 'Vary' => 'Origin', ]; } else { return [ 'Vary' => 'Origin' ]; } $headers['Access-Control-Allow-Methods'] = self::METHODS; $headers['Access-Control-Allow-Headers'] = self::HEADERS; $headers['Access-Control-Max-Age'] = '3600'; return $headers; } /** * Sends the CORS headers from PHP, for servers that ignore .htaccess. * * @return void */ public function send_headers(): void { $origin = isset( $_SERVER['HTTP_ORIGIN'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) ) : ''; foreach( $this->get_headers( $origin ) as $name => $value ) { header( $name . ': ' . $value, 'Vary' !== $name ); } } /** * Removes the REST API's own CORS headers, which copy back any origin, and sends ours on servers without .htaccess. * * @param bool $served Whether the request was already served. * * @return bool The unchanged value. */ public function rest_pre_serve_request( $served ) { foreach( [ 'Access-Control-Allow-Origin', 'Access-Control-Allow-Credentials', 'Access-Control-Allow-Methods', 'Access-Control-Expose-Headers' ] as $name ) { header_remove( $name ); } if( !Utils::is_apache_compatible() ) { $this->send_headers(); } return $served; } /** * Handles the settings saved for CORS configuration and updates the .htaccess rules. * * @param array $sanitized_settings An array of settings containing CORS configurations. * * @return void */ public function adminease_settings_saved( array $sanitized_settings ): void { $code = ''; if( !empty( $sanitized_settings['security']['cors_header'] ) && Utils::is_apache_compatible() ) { $origins = array_values( array_filter( self::parse_origins( $sanitized_settings['security']['cors_header_origins'] ?? '' ), [ self::class, 'is_valid_origin' ] ) ); $code = "# CORS Headers - Allow Cross-Origin Resource Sharing\n"; $code .= "\n"; if( empty( $origins ) ) { $code .= "\tHeader always set Access-Control-Allow-Origin \"*\"\n"; } else { $pattern = implode( '|', array_map( 'preg_quote', $origins ) ); $code .= "\tSetEnvIf Origin \"^(" . $pattern . ")$\" CORS_ORIGIN=$0\n"; $code .= "\tHeader always set Access-Control-Allow-Origin \"%{CORS_ORIGIN}e\" env=CORS_ORIGIN\n"; $code .= "\tHeader always set Access-Control-Allow-Credentials \"true\" env=CORS_ORIGIN\n"; $code .= "\tHeader always merge Vary \"Origin\"\n"; } $code .= "\tHeader always set Access-Control-Allow-Methods \"" . self::METHODS . "\"\n"; $code .= "\tHeader always set Access-Control-Allow-Headers \"" . self::HEADERS . "\"\n"; $code .= "\tHeader always set Access-Control-Max-Age \"3600\"\n"; $code .= "\n\n"; } FileHandler::get_instance()->stack_htaccess_rule( 'CORS_HEADERS', $code ); } }