Storage::store(), 'site' => array( 'id' => self::site(), 'name' => '' !== $name ? $name : (string) wp_parse_url( home_url(), PHP_URL_HOST ), 'hostnames' => self::hostnames(), 'timezone' => self::timezone(), ), 'secret' => self::secret(), // The plugin works out the visitor's address itself (Visitor) and hands it over with each request, so no header is believed here. 'trustProxy' => false, 'fetcher' => new Fetcher(), // Rate counts and the site's icon go in WordPress's cache, never in files of Runlight's own. 'cache' => new Cache(), // No SMTP, whose client opens connections of its own: WordPress's mailer and the mail services cover it. 'mailServices' => array_values( array_diff( array_column( \Runlight\Mail\Transports::SERVICES, 'id' ), array( 'smtp' ) ) ), 'linkPath' => self::runlight_link_path(), ); if ( Settings::get()['locations'] ) { $lookup = self::locations()->lookup(); if ( null !== $lookup ) { $options['geo'] = $lookup; } } // With an SMTP or mail plugin set up, reports go through WordPress, until the dashboard names another service. $mailer = Mailer::option(); if ( null !== $mailer ) { $options['mail'] = $mailer; } self::$runlight = new Runlight( $options ); return self::$runlight; } /** Runlight's routes, signed in through WordPress: those who can manage options own it. */ private static function routes(): Routes { if ( null !== self::$routes ) { return self::$routes; } self::$routes = self::runlight()->routes( array( 'basePath' => self::base(), 'token' => null, // Given here, so Runlight never reads them from the environment: WordPress's cron runs the upkeep, and no // other site reports AI agents to this one. 'cronSecret' => '', 'observeKey' => '', // Only an admin, and a change only with this site's nonce, from this site's own pages. 'authorize' => static fn ( Request $request ): bool => current_user_can( 'manage_options' ) && self::nonced( $request ) && self::same_site( $request ), 'csrf' => static fn (): string => wp_create_nonce( self::NONCE ), 'signIn' => self::base() . '/login', 'origin' => home_url(), 'geoCredit' => Settings::get()['locations'], 'cms' => 'WordPress', ) ); return self::$routes; } /** * Only the server fields Runlight uses, unslashed and sanitized before * they enter the library. URLs keep percent escapes; text does not carry * markup, and addresses, methods, hosts, and lengths are validated. * * @return array */ private static function server(): array { $server = array(); foreach ( array( 'REQUEST_METHOD', 'HTTPS', 'HTTP_HOST', 'SERVER_NAME', 'REMOTE_ADDR', 'CONTENT_TYPE', 'CONTENT_LENGTH', 'REDIRECT_HTTP_AUTHORIZATION', 'HTTP_AUTHORIZATION', 'HTTP_COOKIE', 'HTTP_USER_AGENT', 'HTTP_ACCEPT_LANGUAGE', 'HTTP_IF_NONE_MATCH', 'HTTP_SEC_CH_UA', 'HTTP_SEC_CH_UA_MOBILE', 'HTTP_SEC_CH_UA_PLATFORM', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED_PROTO', 'HTTP_CF_CONNECTING_IP', 'HTTP_CF_IPCOUNTRY', 'HTTP_CF_REGION_CODE', 'HTTP_X_RUNLIGHT_SHARE', 'HTTP_X_RUNLIGHT_EMBED', 'HTTP_X_RUNLIGHT_CSRF', 'HTTP_SEC_FETCH_SITE', 'HTTP_SEC_FETCH_MODE', ) as $key ) { if ( isset( $_SERVER[ $key ] ) && is_string( $_SERVER[ $key ] ) ) { $server[ $key ] = sanitize_text_field( wp_unslash( $_SERVER[ $key ] ) ); } } foreach ( array( 'REQUEST_URI', 'HTTP_ORIGIN', 'HTTP_REFERER' ) as $key ) { if ( isset( $_SERVER[ $key ] ) && is_string( $_SERVER[ $key ] ) ) { $server[ $key ] = esc_url_raw( wp_unslash( $_SERVER[ $key ] ), array( 'http', 'https' ) ); } } // Cloudflare encodes city names, so sanitize the text without losing spaces or accented letters. if ( isset( $_SERVER['HTTP_CF_IPCITY'] ) && is_string( $_SERVER['HTTP_CF_IPCITY'] ) ) { $server['HTTP_CF_IPCITY'] = rawurlencode( sanitize_text_field( rawurldecode( wp_strip_all_tags( wp_unslash( $_SERVER['HTTP_CF_IPCITY'] ) ) ) ) ); } $uri = $server['REQUEST_URI'] ?? '/'; $server['REQUEST_URI'] = str_starts_with( $uri, '/' ) && ! str_starts_with( $uri, '//' ) ? $uri : '/'; foreach ( array( 'HTTP_HOST', 'SERVER_NAME' ) as $key ) { if ( isset( $server[ $key ] ) && ! preg_match( '/^(?:[a-z0-9.-]+|\[[a-f0-9:]+\])(?::[0-9]{1,5})?$/iD', $server[ $key ] ) ) { unset( $server[ $key ] ); } } if ( ! preg_match( '/^[A-Z]+$/D', $server['REQUEST_METHOD'] ?? '' ) ) { $server['REQUEST_METHOD'] = 'GET'; } if ( isset( $server['CONTENT_LENGTH'] ) && ! ctype_digit( $server['CONTENT_LENGTH'] ) ) { unset( $server['CONTENT_LENGTH'] ); } if ( ! filter_var( $server['REMOTE_ADDR'] ?? '', FILTER_VALIDATE_IP ) ) { $server['REMOTE_ADDR'] = ''; } return $server; } /** * The sanitized request, with its body read up to the library's limit. * * @throws \Runlight\Http\BodyTooLarge When the body is past its limit. */ public static function request(): Request { Library::load(); return Request::fromServer( self::server() ); } /** The path of the request being served, without its query. */ private static function path(): string { return (string) wp_parse_url( self::server()['REQUEST_URI'], PHP_URL_PATH ); } /** * Answers requests for Runlight: the dashboard and its API under * /runlight, and short links under /go, which WordPress answers itself * when no link has the name. Everything else is WordPress's. */ public static function serve(): void { if ( ! self::active() ) { return; } $path = self::path(); $base = self::base(); $link = str_starts_with( $path, self::runlight_link_path() . '/' ); if ( $path !== $base && ! str_starts_with( $path, $base . '/' ) && ! $link ) { return; } // A short link's page is left to page caches until Runlight knows the link, since another plugin may answer there. if ( ! $link ) { self::uncached(); } if ( $base . '/login' === $path ) { self::sign_in(); } try { $request = self::request(); } catch ( \Runlight\Http\BodyTooLarge $too_large ) { Request::tooLarge()->emit( true ); exit; } self::load(); $server = self::server(); $context = array( 'ip' => Visitor::address( $server ) ); // Cloudflare's location headers are believed only for a connection from Cloudflare, as its CF-Connecting-IP is. if ( Visitor::from_cloudflare( $server ) ) { $request = $request->with( platformHeaders: true ); } try { if ( $link ) { $response = ( self::runlight()->linkHandler() )( $request, $context ); // No link by that name: the page is WordPress's to answer. if ( 404 === $response->status ) { return; } self::uncached(); } else { $response = self::routes()->handle( $request, $context ); } } catch ( \Throwable $error ) { \Runlight\Log::write( 'Runlight: ' . $error->getMessage() ); // A short link Runlight could not look up is left to WordPress, which may have a page there. if ( $link ) { return; } $response = new \Runlight\Http\Response( '{"error":"Internal error","code":"internal"}', 500, array( 'content-type' => 'application/json; charset=utf-8', 'cache-control' => 'no-store', 'x-content-type-options' => 'nosniff' ) ); } $response->emit( 'HEAD' !== $request->method ); // The visitor has the answer; whatever is left runs without keeping them waiting. if ( function_exists( 'fastcgi_finish_request' ) ) { fastcgi_finish_request(); } elseif ( function_exists( 'litespeed_finish_request' ) ) { litespeed_finish_request(); } self::runlight()->idle(); exit; } /** * Whether a request reads, or else carries this site's nonce for Runlight: the dashboard sends the one it was * given in an x-runlight-csrf header with every change, and the OAuth consent form in its csrf field. * * @param Request $request The request. */ private static function nonced( Request $request ): bool { if ( in_array( $request->method, array( 'GET', 'HEAD', 'OPTIONS' ), true ) ) { return true; } $nonce = (string) $request->headers->get( 'x-runlight-csrf' ); if ( '' === $nonce && str_starts_with( strtolower( (string) $request->headers->get( 'content-type' ) ), 'application/x-www-form-urlencoded' ) ) { parse_str( $request->text(), $form ); $nonce = is_string( $form['csrf'] ?? null ) ? $form['csrf'] : ''; } return '' !== $nonce && false !== wp_verify_nonce( sanitize_key( $nonce ), self::NONCE ); } /** * Whether a request comes from a page on this site, as the browser says where a request comes from, beside * the nonce. A change must say it does. A read from a page on another site is refused too, as one could * run the upkeep, unless it is a visit, such as an app sending an admin to the OAuth consent page. * * @param Request $request The request. */ private static function same_site( Request $request ): bool { $fetch = strtolower( (string) $request->headers->get( 'sec-fetch-site' ) ); if ( in_array( $request->method, array( 'GET', 'HEAD', 'OPTIONS' ), true ) ) { return 'cross-site' !== $fetch || 'navigate' === strtolower( (string) $request->headers->get( 'sec-fetch-mode' ) ); } if ( '' !== $fetch ) { return 'same-origin' === $fetch || 'none' === $fetch; } $origin = (string) $request->headers->get( 'origin' ); return '' !== $origin && strtolower( (string) wp_parse_url( $origin, PHP_URL_HOST ) ) === strtolower( (string) wp_parse_url( $request->url, PHP_URL_HOST ) ); } /** Tells page caches to leave this answer alone. */ private static function uncached(): void { if ( ! defined( 'DONOTCACHEPAGE' ) ) { define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- the constant page caches look for. } } /** Where short links live, before Runlight is made. */ private static function runlight_link_path(): string { return self::home_path() . '/go'; } /** * Runlight sends people who are signed out here, naming the page to come * back to, which is always one of its own. */ private static function sign_in(): void { $next = isset( $_GET['next'] ) ? sanitize_text_field( wp_unslash( $_GET['next'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- only names a page of Runlight's to go back to. $back = str_starts_with( $next, self::base() . '/' ) || self::base() === $next ? $next : self::base() . '/'; $home = wp_parse_url( home_url() ); $to = ( $home['scheme'] ?? 'https' ) . '://' . ( $home['host'] ?? '' ) . ( isset( $home['port'] ) ? ':' . $home['port'] : '' ) . $back; wp_safe_redirect( wp_login_url( $to ) ); exit; } /** The upkeep, scheduled hourly while Runlight runs here. */ public static function schedule(): void { $scheduled = wp_next_scheduled( self::CRON ); if ( self::active() && ! $scheduled ) { wp_schedule_event( time(), 'hourly', self::CRON ); // Due from now, so the settings page can tell when it has not run for a day. if ( false === get_option( self::CHECKED ) ) { update_option( self::CHECKED, time(), false ); } } elseif ( ! self::active() && $scheduled ) { wp_clear_scheduled_hook( self::CRON ); } } /** * Runs the upkeep. A failure is logged rather than thrown, so the other * events WordPress's cron runs in the same request still run. */ public static function check(): void { if ( ! self::active() ) { return; } try { if ( Settings::get()['locations'] ) { self::locations()->refresh( (int) floor( microtime( true ) * 1000 ) ); } self::runlight()->check(); Cache::sweep(); update_option( self::CHECKED, time(), false ); } catch ( \Throwable $error ) { \Runlight\Log::write( 'Runlight: the hourly check failed: ' . $error->getMessage() ); } } /** * Whether the upkeep has not finished for over a day: WordPress's cron is * off, or nothing has visited the site to run it, or it keeps failing. */ public static function overdue(): bool { $checked = get_option( self::CHECKED ); return self::active() && is_numeric( $checked ) && time() - (int) $checked > DAY_IN_SECONDS + HOUR_IN_SECONDS; } /** * Records a page served to an AI agent, once the page has been sent. * * @param string $url The page the agent fetched. * @param string $agent The agent's user agent. * @param string $ip The agent's address, checked against its company's list and then dropped. */ public static function observe( string $url, string $agent, string $ip = '' ): void { Library::load(); self::runlight()->observe( new Request( $url, 'GET', array( 'user-agent' => $agent ) ), null, array( 'ip' => $ip ) ); } }