'U+0460-052F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F', 'vietnamese' => 'U+0102-0103,U+0110-0111,U+0128-0129,U+0168-0169,U+01A0-01A1,U+01AF-01B0,U+0300-0301,U+0303-0304,U+0308-0309,U+0323,U+0329,U+1EA0-1EF9,U+20AB', 'latin-ext' => 'U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF', 'latin' => 'U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD', ); /** * Registered URL schemes with browser-defined script-executing or * document-loading semantics. A scheme-only CSP source is meant to allow * a native app's own custom handler (e.g. `cursor:`); it must never allow * one of these, since a browser treats them specially in a form-action * or navigation context regardless of what the scheme owner intended. * * @var string[] */ private const DANGEROUS_CSP_SCHEMES = array( 'javascript', 'data', 'vbscript', 'file', 'blob', ); /** * Pending-request fields that round-trip through the forms as hidden * inputs. Only fields present in the view-model's `pending` array are * rendered; this list also keeps the set of possible hidden field names * fixed regardless of what the view-model array happens to contain. * * @var string[] */ private const PENDING_FIELDS = array( 'client_id', 'redirect_uri', 'response_type', 'code_challenge', 'code_challenge_method', 'state', 'resource', 'scope', ); /** * Builds the nonce action string for one pending authorization request. * * The permission level the merchant picks lives inside the form the * nonce protects, so it is deliberately not part of this action string: * changing which radio button is checked does not need a different * nonce, only the identity of the pending request (who is asking, where * the result goes, and which PKCE challenge it is bound to) does. * * @param string $clientId Requesting client's identifier. * @param string $redirectUri Exact redirect URI the request will return to. * @param string $codeChallenge PKCE code challenge of the pending request. * @return string */ public static function nonceAction( string $clientId, string $redirectUri, string $codeChallenge ): string { return 'aipt_mcp_consent_' . substr( hash( 'sha256', $clientId . "\n" . $redirectUri . "\n" . $codeChallenge ), 0, 32 ); } /** * Computes the security headers this screen always sends, as a plain * name => value map. Split out from sendHeaders() so the header values * themselves (in particular the computed CSP string) can be asserted * directly without the test needing to intercept the real header() * call. * * @param array $viewModel Controller-validated view-model. * @return array */ public static function securityHeaders( array $viewModel ): array { $style_hash = 'sha256-' . base64_encode( hash( 'sha256', self::styleBlockCss(), true ) ); $form_action = "'self'"; $raw_origin = isset( $viewModel['redirect_origin_for_csp'] ) ? (string) $viewModel['redirect_origin_for_csp'] : ''; $valid_origin = self::sanitizeCspOrigin( $raw_origin ); if ( '' !== $valid_origin ) { $form_action .= ' ' . $valid_origin; } $csp = "default-src 'none'; style-src '" . $style_hash . "'; font-src 'self'; img-src 'self' data:; form-action " . $form_action . "; base-uri 'none'; frame-ancestors 'none'"; return array( 'Content-Security-Policy' => $csp, 'X-Frame-Options' => 'DENY', 'Referrer-Policy' => 'no-referrer', 'Cache-Control' => 'no-store', 'Pragma' => 'no-cache', 'X-Content-Type-Options' => 'nosniff', 'Content-Type' => 'text/html; charset=utf-8', ); } /** * Sends the consent screen's response headers, unless the caller has * already sent output (in which case headers can no longer be changed * and attempting it would only raise a PHP warning). * * @param array $viewModel Controller-validated view-model. * @return void */ public static function sendHeaders( array $viewModel ): void { if ( headers_sent() ) { return; } foreach ( self::securityHeaders( $viewModel ) as $name => $value ) { header( $name . ': ' . $value ); } } /** * Renders the full consent screen document. * * @param array $viewModel Controller-validated view-model. See the class docblock * and the work package contract for the full key list. * @return string Complete HTML document. The caller echoes it and exits. */ public static function render( array $viewModel ): string { $error_message = isset( $viewModel['error_message'] ) ? trim( (string) $viewModel['error_message'] ) : ''; $site_name = isset( $viewModel['site_name'] ) ? (string) $viewModel['site_name'] : ''; $title = sprintf( /* translators: %s: site name. */ esc_html__( 'Connect an app to %s', 'ai-product-tools' ), esc_html( $site_name ) ); $body = '' !== $error_message ? self::renderErrorBody( $error_message ) : self::renderConsentBody( $viewModel ); return self::documentShell( $title, $body ); } /** * Builds the error state: a short explanation and no forms. * * @param string $errorMessage Already-trimmed, non-empty error message. * @return string */ private static function renderErrorBody( string $errorMessage ): string { return '
'; } /** * Builds the normal consent state: the requesting app, the plain-text * trust facts, the permission levels, and the Approve/Deny forms. * * @param array $viewModel Controller-validated view-model. * @return string */ private static function renderConsentBody( array $viewModel ): string { $site_name = isset( $viewModel['site_name'] ) ? (string) $viewModel['site_name'] : ''; $user_display_name = isset( $viewModel['user_display_name'] ) ? (string) $viewModel['user_display_name'] : ''; $client_name = isset( $viewModel['client_name'] ) ? (string) $viewModel['client_name'] : ''; $client_id_host = isset( $viewModel['client_id_host'] ) ? (string) $viewModel['client_id_host'] : ''; $client_registration = isset( $viewModel['client_registration'] ) ? (string) $viewModel['client_registration'] : ''; $redirect_host = isset( $viewModel['redirect_host'] ) ? (string) $viewModel['redirect_host'] : ''; $cap_reached = ! empty( $viewModel['cap_reached'] ); $upgrade_url = isset( $viewModel['upgrade_url'] ) ? (string) $viewModel['upgrade_url'] : ''; $intro = ''; $signed_in_as = ''; $facts = ''; $forms = $cap_reached ? self::renderCapReachedNotice( $upgrade_url ) . self::renderDenyForm( $viewModel ) : self::renderApproveForm( $viewModel ) . self::renderDenyForm( $viewModel ); return '
'; } /** * Optional third fact row naming how the requesting client registered, * when the controller supplied a recognized value. Unrecognized or * missing values render no row rather than guessing. * * @param string $clientRegistration 'dcr', 'cimd', or anything else. * @return string */ private static function registrationFactRow( string $clientRegistration ): string { if ( 'dcr' === $clientRegistration ) { $label = esc_html__( 'Registered by', 'ai-product-tools' ); $value = esc_html__( 'self-registration (Dynamic Client Registration)', 'ai-product-tools' ); } elseif ( 'cimd' === $clientRegistration ) { $label = esc_html__( 'Registered by', 'ai-product-tools' ); $value = esc_html__( 'a client identity document it published', 'ai-product-tools' ); } else { return ''; } return '
' . $label . '
' . $value . '
'; } /** * The free-plan connection cap notice, shown instead of the Approve * form when the view-model reports the cap is reached. * * @param string $upgradeUrl Where the upgrade link points. * @return string */ private static function renderCapReachedNotice( string $upgradeUrl ): string { $new_tab = self::isOffSiteUrl( $upgradeUrl ) ? ' target="_blank" rel="noopener noreferrer"' : ''; $message = ''; return $message; } /** * Whether a URL points away from this site, so its link opens in a new * tab. A relative URL stays on the site. * * @param string $url URL to check. * @return bool */ private static function isOffSiteUrl( string $url ): bool { $host = wp_parse_url( $url, PHP_URL_HOST ); if ( ! is_string( $host ) || '' === $host ) { return false; } return strtolower( $host ) !== strtolower( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ); } /** * The Approve form: the permission-level choice plus the pending * request fields, protected by the request-bound nonce. * * @param array $viewModel Controller-validated view-model. * @return string */ private static function renderApproveForm( array $viewModel ): string { $levels = isset( $viewModel['levels'] ) && is_array( $viewModel['levels'] ) ? $viewModel['levels'] : array(); $default_level = isset( $viewModel['default_level'] ) ? (string) $viewModel['default_level'] : ''; $level_fields = ''; foreach ( $levels as $index => $level ) { $level_fields .= self::renderLevelOption( $level, $default_level, (int) $index ); } $hidden_fields = self::renderHiddenPendingFields( $viewModel ) . ''; return ''; } /** * The Deny form: the same pending fields and nonce as Approve, no * permission level since nothing is being granted. * * @param array $viewModel Controller-validated view-model. * @return string */ private static function renderDenyForm( array $viewModel ): string { $hidden_fields = self::renderHiddenPendingFields( $viewModel ) . ''; return ''; } /** * One radio option in the permission-level group. * * @param mixed $level Expected shape: array{value:string,label:string,description:string}. * @param string $defaultLevel The value that should start checked. * @param int $index Position in the list, used only to build a stable element id. * @return string */ private static function renderLevelOption( $level, string $defaultLevel, int $index ): string { $level = is_array( $level ) ? $level : array(); $value = isset( $level['value'] ) ? (string) $level['value'] : ''; $label = isset( $level['label'] ) ? (string) $level['label'] : ''; $desc = isset( $level['description'] ) ? (string) $level['description'] : ''; $id = 'aipt-consent-level-' . $index; $checked = $value === $defaultLevel ? ' checked="checked"' : ''; return ''; } /** * Hidden inputs that round-trip the pending authorization request's * fields through whichever form the merchant submits. Only the fixed, * known field names in self::PENDING_FIELDS are ever emitted. * * @param array $viewModel Controller-validated view-model. * @return string */ private static function renderHiddenPendingFields( array $viewModel ): string { $pending = isset( $viewModel['pending'] ) && is_array( $viewModel['pending'] ) ? $viewModel['pending'] : array(); $fields = ''; foreach ( self::PENDING_FIELDS as $field ) { if ( ! array_key_exists( $field, $pending ) ) { continue; } $fields .= ''; } return $fields; } /** * The nonce field shared by both forms, bound to the pending request's * client_id, redirect_uri and code_challenge (Amendment A3). * * @param array $viewModel Controller-validated view-model. * @return string */ private static function nonceField( array $viewModel ): string { $pending = isset( $viewModel['pending'] ) && is_array( $viewModel['pending'] ) ? $viewModel['pending'] : array(); $client_id = isset( $pending['client_id'] ) ? (string) $pending['client_id'] : ''; $redirect_uri = isset( $pending['redirect_uri'] ) ? (string) $pending['redirect_uri'] : ''; $code_challenge = isset( $pending['code_challenge'] ) ? (string) $pending['code_challenge'] : ''; $action = self::nonceAction( $client_id, $redirect_uri, $code_challenge ); return (string) wp_nonce_field( $action, '_wpnonce', true, false ); } /** * @param array $viewModel Controller-validated view-model. * @return string */ private static function formActionUrl( array $viewModel ): string { return isset( $viewModel['form_action_url'] ) ? (string) $viewModel['form_action_url'] : ''; } /** * Restricts a client-redirect origin to a well-formed https origin, a * loopback http origin, or a scheme-only private-use source, so it is * safe to splice into the form-action CSP directive. Anything else * (whitespace, quotes, semicolons, a wildcard, a path, a bare * http/https scheme, or one of the script-executing or document-loading * schemes in self::DANGEROUS_CSP_SCHEMES) is dropped rather than * emitted. The scheme-only branch is meant for a native app's own * custom handler (e.g. `cursor:`), never for a scheme a browser gives * special script-executing or navigation semantics. * * @param string $origin Candidate redirect_origin_for_csp value. * @return string The validated origin, or '' if it was not well-formed. */ private static function sanitizeCspOrigin( string $origin ): string { if ( '' === $origin ) { return ''; } if ( 1 === preg_match( '/^https:\/\/[A-Za-z0-9.-]+(:[0-9]{1,5})?$/', $origin ) ) { return $origin; } if ( 1 === preg_match( '/^http:\/\/(127\.0\.0\.1|\[::1\]|localhost)(:[0-9]{1,5})?$/', $origin ) ) { return $origin; } if ( 1 === preg_match( '/^([A-Za-z][A-Za-z0-9+.-]*):$/', $origin, $schemeMatch ) ) { $scheme = strtolower( $schemeMatch[1] ); if ( 'http' !== $scheme && 'https' !== $scheme && ! in_array( $scheme, self::DANGEROUS_CSP_SCHEMES, true ) ) { return $origin; } } return ''; } /** * The one inline style block, shared verbatim by render() (where it is * printed) and securityHeaders() (where its hash authorizes it). The * rules live in a single literal string; the only computed part is the * plugin font's faces from {@see fontFaceCss()}. * * @return string */ private static function styleBlockCss(): string { return self::fontFaceCss() . <<<'CSS' :root{color-scheme:light} *{box-sizing:border-box} body{margin:0;padding:24px 16px;background:#f0f0f1;font-family:"Plus Jakarta Sans",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;color:#1d2327;line-height:1.5} .aipt-consent{display:flex;justify-content:center} .aipt-consent__card{width:100%;max-width:420px;background:#fff;border:1px solid #c3c4c7;border-radius:4px;padding:32px 24px;box-shadow:0 1px 3px rgba(0,0,0,.1)} .aipt-consent__card h1{margin:0 0 16px;font-size:20px;line-height:1.3} .aipt-consent__intro,.aipt-consent__signed-in,.aipt-consent__error,.aipt-consent__cap-notice{margin:0 0 16px;font-size:14px} .aipt-consent__signed-in{color:#50575e} .aipt-consent__facts{margin:0 0 20px;padding:12px 16px;background:#f6f7f7;border-radius:4px;font-size:13px} .aipt-consent__facts dt{font-weight:600;color:#50575e} .aipt-consent__facts dd{margin:0 0 10px;word-break:break-all} .aipt-consent__facts dd:last-child{margin-bottom:0} .aipt-consent__levels{border:1px solid #dcdcde;border-radius:4px;margin:0 0 20px;padding:12px} .aipt-consent__levels legend{padding:0 4px;font-size:13px;font-weight:600} .aipt-consent__level{display:flex;align-items:flex-start;gap:10px;padding:8px 4px;cursor:pointer} .aipt-consent__level-label{font-weight:600;font-size:14px} .aipt-consent__level-desc{display:block;font-size:12px;color:#50575e;font-weight:400} .aipt-consent__actions{display:flex;flex-direction:column;gap:10px} .aipt-consent__form{margin:0} .aipt-consent__button{width:100%;padding:10px 16px;font-size:14px;font-weight:600;border-radius:3px;border:1px solid transparent;cursor:pointer} .aipt-consent__button--primary{background:#2271b1;border-color:#2271b1;color:#fff} .aipt-consent__button--secondary{background:#fff;border-color:#c3c4c7;color:#1d2327} a{color:#2271b1} input:focus,a:focus,button:focus{outline:2px solid #2271b1;outline-offset:2px} @media (max-width:480px){body{padding:12px 8px}.aipt-consent__card{padding:24px 16px}} CSS; } /** * The plugin font's faces, loaded from the plugin's own files (the CSP * allows fonts from this site only). Empty when the plugin URL is unknown * or holds a character outside plain URL characters, which could end the * CSS url() early; the system fonts in the stack are used then. * * @return string */ private static function fontFaceCss(): string { $base = defined( 'AIPT_PLUGIN_URL' ) ? (string) AIPT_PLUGIN_URL : ''; if ( '' === $base || 1 === preg_match( '#[^A-Za-z0-9:/._~%+-]#', $base ) ) { return ''; } $css = ''; foreach ( self::FONT_SUBSETS as $subset => $range ) { $css .= "@font-face{font-family:'Plus Jakarta Sans';font-style:normal;font-weight:400 700;font-display:swap;src:url('" . $base . 'dist/webfonts/plus-jakarta-sans-400-normal-' . $subset . ".woff2') format('woff2');unicode-range:" . $range . '}'; } return $css; } /** * Wraps a rendered body in the zero-JavaScript HTML document shell. * * @param string $escapedTitle Already-escaped content. * @param string $body Already-escaped body markup. * @return string */ private static function documentShell( string $escapedTitle, string $body ): string { return '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" />' . '<meta name="viewport" content="width=device-width, initial-scale=1" />' . '<title>' . $escapedTitle . '' . '' . '' . $body . ''; } }