'POST', 'callback' => 'vasp_handle_verify_bootstrap', 'permission_callback' => '__return_true', ]); register_rest_route('valuespace/v1', '/event-session', [ 'methods' => WP_REST_Server::READABLE, 'callback' => 'vasp_handle_event_session_identity', 'permission_callback' => 'vasp_event_is_same_origin_identity_request', ]); } /** Return a private, non-cacheable response from the event-session resolver. */ function vasp_event_session_identity_response($data, $status = 200) { $response = new WP_REST_Response($data, (int) $status); $response->header('Cache-Control', 'private, no-store, no-cache, max-age=0, must-revalidate'); $response->header('Pragma', 'no-cache'); $response->header('Expires', 'Wed, 11 Jan 1984 05:00:00 GMT'); $response->header('Vary', 'Cookie, Origin'); return $response; } /** Accept modern exact-origin fetches, with the existing URL check as fallback. */ function vasp_event_is_same_origin_identity_request() { if (isset($_SERVER['HTTP_SEC_FETCH_SITE'])) { return is_string($_SERVER['HTTP_SEC_FETCH_SITE']) && strtolower(sanitize_text_field(wp_unslash($_SERVER['HTTP_SEC_FETCH_SITE']))) === 'same-origin'; } return vasp_event_is_same_site_browser_request(); } /** Resolve the signed per-browser event session without exposing it in page HTML. */ function vasp_handle_event_session_identity() { if (!vasp_event_is_same_origin_identity_request()) { return vasp_event_session_identity_response(null, 403); } $session_id = vasp_event_get_bound_session_id(true); if (!is_string($session_id) || !wp_is_uuid($session_id, 4)) { return vasp_event_session_identity_response(null, 503); } // The widget resolves this same-origin identity while initializing the // current page. Preserve that fact locally so direct commerce requests // without a preceding page load cannot enter the delivery outbox. if (!vasp_event_mark_session_page_view($session_id)) { vasp_log('Event page-view evidence could not be recorded', 'warning'); return vasp_event_session_identity_response(null, 503); } return vasp_event_session_identity_response([ 'origin' => 'wordpress', 'externalId' => substr($session_id, 0, 36), ]); } /** * Verify and consume an SSO nonce for Dashboard origin and administrator checks. */ function vasp_handle_verify_bootstrap(WP_REST_Request $request) { $nonce = $request->get_param('nonce'); $nonce = is_string($nonce) ? sanitize_text_field($nonce) : ''; if (!wp_is_uuid($nonce, 4)) { return new WP_REST_Response(null, 404); } $proof = empty($nonce) ? false : get_transient(VASP_TRANSIENT_BOOTSTRAP_NONCE_PREFIX . $nonce); if (!is_array($proof)) { vasp_log('SSO verification failed: nonce not found', 'warning'); return new WP_REST_Response(null, 404); } vasp_delete_dynamic_transient(VASP_TRANSIENT_BOOTSTRAP_NONCE_PREFIX . $nonce); vasp_log('SSO verification succeeded', 'info'); return new WP_REST_Response([ 'verified' => true, 'siteUrl' => $proof['site_url'], 'email' => $proof['email'], 'manageOptions' => !empty($proof['manage_options']), 'locale' => isset($proof['locale']) ? (string) $proof['locale'] : 'en_US', 'wooCommerceActive' => class_exists('WooCommerce'), ], 200); } /** * Handle event tracking AJAX requests * * Flow: * 1. Validate request (event type, nonce) * 2. Parse event data * 3. Record event via VASP_Event_Recorder * 4. Log result * 5. Return JSON response */ function vasp_ajax_track_event() { $is_batch = isset($_POST['events']); if ($is_batch) { $events_json = is_string($_POST['events']) ? wp_unslash($_POST['events']) : ''; $outer_url = isset($_POST['url']) && is_string($_POST['url']) ? vasp_event_normalize_page_url(wp_unslash($_POST['url'])) : null; if ($outer_url === false) { wp_send_json_error(__('Event not recorded', 'valuespace')); return; } $events = vasp_ajax_parse_event_batch($events_json, $outer_url); if ($events === false) { wp_send_json_error(__('Event not recorded', 'valuespace')); return; } $validated_session_id = null; $validation_error = vasp_ajax_validate_request($events[0]['event_type'], count($events), $validated_session_id); if ($validation_error) { wp_send_json_error($validation_error); return; } if (!class_exists('VASP_Event_Recorder')) { require_once VASP_PLUGIN_DIR . 'includes/events/recorder.php'; } $accepted = 0; $recorder = new VASP_Event_Recorder(); foreach ($events as $event) { $trusted_context = vasp_event_browser_trusted_context($validated_session_id); if (!empty($event['source_event_id'])) { $trusted_context['source_event_id'] = $event['source_event_id']; } $result = $recorder->record_event( $event['event_type'], $event['event_data'], $event['url'], $trusted_context ); if (!empty($result['success']) && empty($result['ignored'])) { $accepted++; } } wp_send_json_success([ 'accepted' => $accepted, 'rejected' => count($events) - $accepted, ]); return; } // STEP 1: Validate request $event_type = isset($_POST['event_type']) && is_string($_POST['event_type']) ? sanitize_text_field(wp_unslash($_POST['event_type'])) : ''; $validated_session_id = null; $validation_error = vasp_ajax_validate_request($event_type, 1, $validated_session_id); if ($validation_error) { wp_send_json_error($validation_error); return; } // STEP 2: Parse event data $event_data_json = isset($_POST['event_data']) && is_string($_POST['event_data']) ? wp_unslash($_POST['event_data']) : '{}'; if (strlen($event_data_json) > 16384) { wp_send_json_error(__('Event data is too large', 'valuespace')); return; } $event_data = vasp_ajax_parse_event_data($event_data_json); $event_url = isset($_POST['url']) && is_string($_POST['url']) ? vasp_event_normalize_page_url(wp_unslash($_POST['url'])) : null; if ($event_url === false || !vasp_event_validate_payload($event_type, $event_data, $event_url)) { wp_send_json_error(__('Event not recorded', 'valuespace')); return; } // STEP 3: Record event (all logging happens inside event recorder) if (!class_exists('VASP_Event_Recorder')) { require_once VASP_PLUGIN_DIR . 'includes/events/recorder.php'; } $recorder = new VASP_Event_Recorder(); $result = $recorder->record_event( $event_type, $event_data, $event_url, vasp_event_browser_trusted_context($validated_session_id) ); // STEP 4: Send response if (!empty($result['ignored'])) { wp_send_json_success(__('Event not recorded', 'valuespace')); } elseif ($result['success']) { wp_send_json_success(__('Event recorded', 'valuespace')); } else { wp_send_json_error(__('Event not recorded', 'valuespace')); } } /** * Validate AJAX request */ function vasp_ajax_validate_request($event_type, $event_count = 1, &$validated_session_id = null) { $validated_session_id = null; if (empty($event_type)) { return __('Missing event type', 'valuespace'); } $user_agent = isset($_SERVER['HTTP_USER_AGENT']) && is_string($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : ''; $is_bot = $user_agent !== '' && vasp_event_is_bot_user_agent($user_agent); if ($is_bot && function_exists('vasp_event_increment_bot_excluded')) { vasp_event_increment_bot_excluded(); } if ($user_agent === '' || $is_bot || !vasp_event_is_same_site_browser_request()) { return __('Event not recorded', 'valuespace'); } if (function_exists('vasp_is_client_event_context') && !vasp_is_client_event_context()) { return __('Event not recorded', 'valuespace'); } $nonce_value = isset($_POST['nonce']) && is_string($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : ''; if (!wp_verify_nonce($nonce_value, 'valuespace_tracker')) { return __('Security check failed', 'valuespace'); } $session_id = vasp_event_get_bound_session_id(true); if (!$session_id) { return __('Invalid event session', 'valuespace'); } $remote_address = isset($_SERVER['REMOTE_ADDR']) && is_string($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : ''; if (!filter_var($remote_address, FILTER_VALIDATE_IP)) { $remote_address = 'unknown'; } if (vasp_event_request_rate_limited($session_id, $remote_address, $event_count)) { return __('Too many event requests', 'valuespace'); } $validated_session_id = $session_id; return null; } /** Pass only the exact server-validated browser session into the recorder. */ function vasp_event_browser_trusted_context($validated_session_id) { return wp_is_uuid($validated_session_id, 4) ? ['session_id' => (string) $validated_session_id] : []; } /** Charge the session gate before the shared IP gate. */ function vasp_event_request_rate_limited($session_id, $remote_address, $charge = 1) { $session_limit = max(1, (int) apply_filters('vasp_event_session_rate_limit_per_minute', 30)); $session_key = 'vasp_event_rate_session_' . hash('sha256', (string) $session_id); if (vasp_event_rate_limit_exceeded($session_key, $session_limit, $charge)) { return true; } $ip_limit = max(1, (int) apply_filters('vasp_event_ip_rate_limit_per_minute', 60)); $ip_key = 'vasp_event_rate_ip_' . hash_hmac('sha256', (string) $remote_address, wp_salt('nonce')); return vasp_event_rate_limit_exceeded($ip_key, $ip_limit, $charge); } /** Atomically increment one ephemeral minute-bucket counter. */ function vasp_event_rate_limit_exceeded($rate_key, $limit, $charge = 1) { $rate_key = substr(sanitize_key((string) $rate_key), 0, 172); $lock_key = 'vasp_event_rate_lock_' . md5($rate_key); if (!vasp_event_acquire_option_lock($lock_key)) { return true; } $charge = max(1, (int) $charge); try { $rate = get_transient($rate_key); $count = is_array($rate) && isset($rate['count']) ? (int) $rate['count'] : 0; if ($count + $charge > max(1, (int) $limit)) { return true; } return !set_transient($rate_key, ['count' => $count + $charge], MINUTE_IN_SECONDS); } finally { delete_option($lock_key); } } /** Acquire a short-lived non-autoloaded option lock without visitor residue. */ function vasp_event_acquire_option_lock($lock_key, $attempts = 3) { $attempts = max(1, min(5, (int) $attempts)); for ($attempt = 0; $attempt < $attempts; $attempt++) { if (add_option($lock_key, time(), '', 'no')) { return $lock_key; } $created_at = (int) get_option($lock_key, 0); if ($created_at > 0 && time() - $created_at >= 15) { delete_option($lock_key); continue; } if ($attempt + 1 < $attempts) { usleep(25000); } } return false; } /** * Parse and validate a bounded batch submitted through the existing endpoint. * * @param string $events_json JSON array of event objects. * @return array|false Normalized events, or false for malformed input. */ function vasp_ajax_parse_event_batch($events_json, $fallback_url = null) { if (!is_string($events_json) || $events_json === '' || strlen($events_json) > 360448) { return false; } $items = json_decode($events_json, true, 10); if (json_last_error() !== JSON_ERROR_NONE || !is_array($items) || count($items) < 1 || count($items) > 20 || array_keys($items) !== range(0, count($items) - 1)) { return false; } if ($fallback_url !== null) { $fallback_url = vasp_event_normalize_page_url($fallback_url); if ($fallback_url === false) { return false; } } $events = []; foreach ($items as $item) { if (!is_array($item) || !isset($item['event_type']) || !is_string($item['event_type'])) { return false; } $source_event_id = isset($item['source_event_id']) && is_string($item['source_event_id']) ? strtolower(trim($item['source_event_id'])) : ''; if ($source_event_id !== '' && !wp_is_uuid($source_event_id)) { return false; } $event_type = sanitize_text_field($item['event_type']); if ($event_type === '') { return false; } $data_value = array_key_exists('event_data', $item) ? $item['event_data'] : []; if (is_string($data_value)) { $event_data_json = $data_value; if (strlen($event_data_json) > 16384) { return false; } $event_data = json_decode($event_data_json, true, 8); if (json_last_error() !== JSON_ERROR_NONE || !is_array($event_data)) { return false; } } elseif (is_array($data_value)) { $event_data_json = wp_json_encode($data_value); if (!is_string($event_data_json) || strlen($event_data_json) > 16384) { return false; } $event_data = $data_value; } else { return false; } if (isset($item['url']) && !is_string($item['url'])) { return false; } $item_url = isset($item['url']) ? vasp_event_normalize_page_url($item['url']) : $fallback_url; if ($item_url === false || !vasp_event_validate_payload($event_type, $event_data, $item_url)) { return false; } $events[] = [ 'event_type' => $event_type, 'event_data' => $event_data, 'url' => $item_url, 'source_event_id' => $source_event_id, ]; } return $events; } /** * Parse event data from JSON */ function vasp_ajax_parse_event_data($event_data_json) { $event_data = json_decode($event_data_json, true, 8); if (json_last_error() !== JSON_ERROR_NONE || !is_array($event_data)) { return []; } return $event_data; } // Register AJAX handlers /** * Handle retention days save AJAX request */ function vasp_ajax_save_retention() { // Verify nonce $nonce_value = isset($_POST['nonce']) && is_string($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : ''; if (!wp_verify_nonce($nonce_value, 'vasp_events_admin_nonce')) { wp_send_json_error(__('Security check failed', 'valuespace')); return; } // Check permissions if (!current_user_can('manage_options')) { wp_send_json_error(__('Insufficient permissions', 'valuespace')); return; } // Validate retention days $retention_days = isset($_POST['retention_days']) ? (is_string($_POST['retention_days']) ? intval(wp_unslash($_POST['retention_days'])) : 0) : 30; if ($retention_days < 1 || $retention_days > 365) { wp_send_json_error(__('Retention days must be between 1 and 365', 'valuespace')); return; } // Update settings $settings = get_option(VASP_EVENT_SETTINGS_OPTION, []); $settings['event_retention_days'] = $retention_days; update_option(VASP_EVENT_SETTINGS_OPTION, $settings, false); wp_send_json_success(__('Retention days updated', 'valuespace')); }