'76/p0XVbiQKeh8aRrp9T0Ld4ViKGDtLizMw6h2ElTa8=', ]; } function affgsc_trusted_feed_key_id(string $encoded_key): string { $decoded = base64_decode($encoded_key, true); if (!is_string($decoded) || !defined('SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES') || strlen($decoded) !== SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES ) { return ''; } $key_id = substr(hash('sha256', $decoded), 0, 32); $trusted = affgsc_trusted_feed_public_keys(); return isset($trusted[$key_id]) && hash_equals((string)$trusted[$key_id], $encoded_key) ? $key_id : ''; } function affgsc_feed_public_key(): string { $key = (string)get_option('affgsc_feed_public_key', ''); return affgsc_trusted_feed_key_id($key) !== '' ? $key : ''; } function affgsc_auth_canonical(string $action, string $install_id, int $timestamp, string $nonce, string $body_hash): string { return implode("\n", [ 'affgate-request-v1', sanitize_key($action), strtolower($install_id), (string)$timestamp, strtolower($nonce), strtolower($body_hash), ]); } function affgsc_register_installation_proof_route(): void { register_rest_route('affgsc/v1', '/installation-proof', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'affgsc_rest_installation_proof', 'permission_callback' => '__return_true', 'args' => [], ]); } function affgsc_rest_installation_proof(WP_REST_Request $request): WP_REST_Response { $install_id = sanitize_text_field((string)$request->get_param('install_id')); $challenge = strtolower(sanitize_text_field((string)$request->get_param('challenge'))); if (!hash_equals(strtolower(affgsc_install_id()), strtolower($install_id)) || !preg_match('/^[a-f0-9]{64}$/', $challenge)) { return new WP_REST_Response(['error' => 'Invalid proof request'], 400); } $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash((string)$_SERVER['REMOTE_ADDR'])) : ''; $rate_key = 'affgsc_proof_rate_' . md5($ip); $count = (int)get_transient($rate_key); if ($count >= 60) return new WP_REST_Response(['error' => 'Rate limit exceeded'], 429); set_transient($rate_key, $count + 1, HOUR_IN_SECONDS); $proof = hash_hmac( 'sha256', 'affgate-registration-v1|' . strtolower($install_id) . '|' . $challenge, affgsc_install_proof_secret() ); return new WP_REST_Response([ 'install_id' => $install_id, 'challenge' => $challenge, 'proof' => $proof, ], 200); } function affgsc_register_installation(): array { if (!function_exists('sodium_crypto_sign_verify_detached')) { return ['ok' => false, 'message' => 'The PHP Sodium extension is required for secure AffGate feeds.']; } $endpoint = affgsc_sanitize_https_url((string)affgsc_setting( 'registration_endpoint', 'https://affgate.com/wp-json/affgate-games/v1/installations/register' )); $site_url = home_url('/'); $proof_url = rest_url('affgsc/v1/installation-proof'); if ($endpoint === '' || strtolower((string)wp_parse_url($site_url, PHP_URL_SCHEME)) !== 'https' || strtolower((string)wp_parse_url($proof_url, PHP_URL_SCHEME)) !== 'https' ) { return ['ok' => false, 'message' => 'A public HTTPS WordPress site is required to connect securely to AffGate.']; } $payload = [ 'install_id' => affgsc_install_id(), 'site_url' => esc_url_raw($site_url), 'site_host' => strtolower((string)(wp_parse_url($site_url, PHP_URL_HOST) ?: '')), 'installed_at' => (string)get_option('affgsc_installed_at', ''), 'active_games' => affgsc_active_game_count(), 'plugin_version' => AFFGSC_VERSION, 'proof_url' => esc_url_raw($proof_url), 'proof_secret' => affgsc_auth_base64url_encode(affgsc_install_proof_secret()), ]; $body = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); $res = wp_safe_remote_post($endpoint, [ 'timeout' => 20, 'redirection' => 0, 'limit_response_size' => 65536, 'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'], 'body' => $body, ]); if (is_wp_error($res)) return ['ok' => false, 'message' => $res->get_error_message()]; $code = (int)wp_remote_retrieve_response_code($res); $data = json_decode((string)wp_remote_retrieve_body($res), true); if ($code < 200 || $code >= 300 || !is_array($data)) { $message = is_array($data) ? sanitize_text_field((string)($data['error'] ?? '')) : ''; return ['ok' => false, 'message' => $message !== '' ? $message : 'AffGate registration failed with HTTP ' . $code]; } $api_secret = sanitize_text_field((string)($data['api_secret'] ?? '')); $feed_public_key = sanitize_text_field((string)($data['feed_public_key'] ?? '')); $decoded_secret = affgsc_auth_base64url_decode($api_secret); $trusted_key_id = affgsc_trusted_feed_key_id($feed_public_key); if (strlen($decoded_secret) !== 32 || $trusted_key_id === '') { return ['ok' => false, 'message' => 'AffGate returned invalid security credentials.']; } $returned_key_id = strtolower(sanitize_text_field((string)($data['feed_key_id'] ?? ''))); if ($returned_key_id !== '' && !hash_equals($trusted_key_id, $returned_key_id)) { return ['ok' => false, 'message' => 'AffGate returned an invalid feed signing key identifier.']; } if (!affgsc_store_install_api_secret($api_secret)) { return ['ok' => false, 'message' => 'The installation secret could not be stored securely.']; } update_option('affgsc_feed_public_key', $feed_public_key, false); update_option('affgsc_feed_key_id', $trusted_key_id, false); update_option('affgsc_connected_at', affgsc_now(), false); affgsc_schedule_installation_heartbeat(); return ['ok' => true, 'message' => 'Connected securely to AffGate.']; } function affgsc_ensure_installation_secret(): array { if (affgsc_install_api_secret() !== '' && affgsc_feed_public_key() !== '') { return ['ok' => true, 'message' => 'AffGate connection is ready.']; } return affgsc_register_installation(); } function affgsc_signed_remote_post(string $endpoint, string $action, array $payload, array $args = []) { $secret_encoded = affgsc_install_api_secret(); $secret = affgsc_auth_base64url_decode($secret_encoded); if (strlen($secret) !== 32) return new WP_Error('affgsc_not_registered', 'This site is not securely registered with AffGate.'); $body = wp_json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if (!is_string($body)) return new WP_Error('affgsc_json', 'Could not encode the AffGate request.'); $timestamp = time(); $nonce = bin2hex(random_bytes(24)); $body_hash = hash('sha256', $body); $canonical = affgsc_auth_canonical($action, affgsc_install_id(), $timestamp, $nonce, $body_hash); $headers = [ 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'X-AffGate-Install-ID' => affgsc_install_id(), 'X-AffGate-Timestamp' => (string)$timestamp, 'X-AffGate-Nonce' => $nonce, 'X-AffGate-Content-SHA256' => $body_hash, 'X-AffGate-Signature' => hash_hmac('sha256', $canonical, $secret_encoded), ]; return wp_safe_remote_post($endpoint, array_replace([ 'timeout' => 20, 'redirection' => 0, 'limit_response_size' => 65536, 'headers' => $headers, 'body' => $body, ], $args)); }