$config * @param array|null $taEvaluate clicksafeTrafficArmorEvaluate() ou equivalente */ public static function trafficArmor(?string $campaignNumber, array $config, ?array $taEvaluate = null): array { if (is_array($taEvaluate) && (array_key_exists('available', $taEvaluate) || array_key_exists('attempted', $taEvaluate))) { $verdict = (string)($taEvaluate['verdict'] ?? AuditTrafficArmorSignal::STATUS_UNKNOWN); $status = (string)($taEvaluate['status'] ?? AuditTrafficArmorSignal::STATUS_UNAVAILABLE); $score = isset($taEvaluate['score']) && is_int($taEvaluate['score']) ? $taEvaluate['score'] : null; if ($verdict === 'BLOCK' && $score === null) { $score = 85; } return [ 'score' => $score, 'status' => $status, 'verdict' => $verdict, 'reason_code' => (string)($taEvaluate['reason_code'] ?? ''), 'campaign_number' => $campaignNumber, 'stale' => !empty($taEvaluate['stale']), ]; } if (is_array($taEvaluate) && isset($taEvaluate['status'], $taEvaluate['verdict'])) { $verdict = (string)$taEvaluate['verdict']; $score = isset($taEvaluate['score']) && is_int($taEvaluate['score']) ? $taEvaluate['score'] : null; if ($verdict === 'BLOCK' && $score === null) { $score = 85; } return [ 'score' => $score, 'status' => (string)$taEvaluate['status'], 'verdict' => $verdict, 'reason_code' => (string)($taEvaluate['reason_code'] ?? ''), 'campaign_number' => $taEvaluate['campaign_number'] ?? $campaignNumber, 'stale' => !empty($taEvaluate['stale']), ]; } $base = AuditTrafficArmorSignal::forCampaign($campaignNumber, $config); return [ 'score' => $base['score'] ?? null, 'status' => $base['status'], 'verdict' => $base['verdict'], 'reason_code' => $base['reason_code'], 'campaign_number' => $base['campaign_number'], 'stale' => $base['stale'] ?? false, ]; } /** @param array|null $proxy */ public static function proxyCheck(?array $proxy): array { if ($proxy === null) { return ['score' => null, 'anonymous' => null, 'status' => 'absent']; } $status = is_string($proxy['status'] ?? null) ? $proxy['status'] : 'unknown'; $risk = isset($proxy['risk_score']) && is_int($proxy['risk_score']) ? $proxy['risk_score'] : null; $anon = isset($proxy['is_anonymous']) ? ((int)$proxy['is_anonymous'] === 1) : null; if ($status === 'proxycheck_unavailable' || $risk === null) { return ['score' => null, 'anonymous' => $anon, 'status' => $status]; } return ['score' => min(100, max(0, $risk)), 'anonymous' => $anon, 'status' => $status]; } /** * CampaignShield síncrono ou policy snapshot + perfil de ingresso. * * @param array|null $shield CampaignShield::evaluate() * @param array|null $policy policy snapshot decodificado * @param array|null $profile AuditIngress::profile */ public static function localShield(?array $shield, ?array $policy, ?array $profile): array { $score = null; $block = false; $jsAbsent = true; if (is_array($shield)) { $block = !empty($shield['block']); $score = isset($shield['score']) ? (int)$shield['score'] : null; } if (is_array($policy)) { if ((int)($policy['policy_blocked'] ?? 0) === 1) { $block = true; $score = max($score ?? 0, 72); } } if ($score === null) { $score = $block ? 75 : 0; } return [ 'score' => min(100, max(0, $score)), 'shield_block' => $block ? 1 : 0, 'js_absent' => $jsAbsent ? 1 : 0, 'ua_family' => is_array($profile) ? (string)($profile['ua_family'] ?? 'unknown') : 'unknown', 'policy_blocked' => (int)($policy['policy_blocked'] ?? 0), ]; } /** @param array $server */ public static function cloudflare(array $server, ?array $profile): array { $bot = null; $raw = $server['HTTP_CF_VISITOR'] ?? $server['CF-Visitor'] ?? null; if (is_string($raw) && $raw !== '') { try { $parsed = json_decode($raw, true, 8, JSON_THROW_ON_ERROR); if (is_array($parsed) && array_key_exists('bot', $parsed)) { $bot = $parsed['bot'] === true || $parsed['bot'] === 1 || $parsed['bot'] === '1'; } } catch (JsonException) { $bot = null; } } $tlsScope = is_array($profile) ? ($profile['tls_scope'] ?? null) : null; $rateLimited = ($server['AUDIT_RATE_LIMIT_WOULD_BLOCK'] ?? null) === '1'; return [ 'edge_proxied' => $tlsScope === 'intermediary', 'client_bot' => $bot, 'rate_limit_observed' => $rateLimited, 'note' => $tlsScope === 'intermediary' ? 'cf_edge' : 'direct_or_unknown', ]; } }  * } */ final class DeliveryRouter { /** * @param array{phantom_safe?:bool,sensitive_probe?:bool,compliance_virtual?:?string} $flags */ public static function deliverRequest( PDO $db, array $config, array &$server, string $host, string $slug, array $flags = [] ): array { $subpath = (string)($flags['subpath'] ?? ''); $slugInUri = !empty($flags['slug_in_uri']); // Never reuse a previous request's observation when callers reuse their server array. unset($server[DeliverySignalBridge::SERVER_TA_OBSERVATION_KEY], $server[DeliverySignalBridge::SERVER_TA_EVENT_ID_KEY], $server[DeliverySignalBridge::SERVER_TA_EVENT_CAMPAIGN_KEY], $server[DeliverySignalBridge::SERVER_TA_STAGE_KEY]); require_once __DIR__ . '/WeightedDistributor.php'; $distributor = new WeightedDistributor($db); $selection = $distributor->selectSlug($slug, $host); if ($selection === null) { throw new AuditHttpError(404); } $ip = AuditClientIp::resolve((string)($server['REMOTE_ADDR'] ?? ''), $server['HTTP_CF_CONNECTING_IP'] ?? null); $ua = (string)($server['HTTP_USER_AGENT'] ?? ''); $campaignId = (string)$selection['id']; if (($server['REQUEST_METHOD'] ?? '') === 'GET' && ($selection['status'] ?? '') === 'active') { try { $server[DeliverySignalBridge::SERVER_TA_EVENT_ID_KEY] = bin2hex(random_bytes(16)); $server[DeliverySignalBridge::SERVER_TA_EVENT_CAMPAIGN_KEY] = $campaignId; } catch (Throwable) { // Failure to prepare optional correlation must not affect the local response. } } $phantomSafe = !empty($flags['phantom_safe']); $sensitiveProbe = !empty($flags['sensitive_probe']); $hybridRulesJson = is_string($selection['ta_rules_json'] ?? null) ? $selection['ta_rules_json'] : null; $config['delivery_local_only'] = LocalOnlyDelivery::isActive($hybridRulesJson); $config['delivery_ta_js_zip'] = false; if (!$config['delivery_local_only'] && $hybridRulesJson !== null && $hybridRulesJson !== '') { try { $docDelivery = CampaignTaRulesDocument::decode($hybridRulesJson); $mode = (string)($docDelivery['integration']['clicksafe_delivery'] ?? ''); $config['delivery_local_only'] = $mode === 'local_only' || $mode === 'hybrid_silent'; $config['delivery_ta_js_zip'] = CampaignTaRulesDocument::taJavascriptZipEnabled($docDelivery); } catch (Throwable) { } } if (!empty($config['delivery_ta_js_zip']) && strtoupper((string)($server['REQUEST_METHOD'] ?? 'GET')) === 'GET') { require_once __DIR__ . '/DeliverySession.php'; require_once __DIR__ . '/TaJavascriptZipGrant.php'; DeliverySession::ensurePublicSession(); $_SESSION['_ref'] = isset($server['HTTP_REFERER']) ? (string)$server['HTTP_REFERER'] : ''; $zipHeaderSnap = self::taJavascriptZipSessionSnapshot($server); $_SESSION['_headers'] = $zipHeaderSnap; TaJavascriptZipGrant::persistHeaderSnapshot($zipHeaderSnap); TaJavascriptZipGrant::touchFirstHitSession($server); TaJavascriptZipGrant::recordLandingPath($server, $config); } $shield = CampaignShield::evaluate($selection, $config, $server, $ip, $ua, $db); $local = is_array($shield['local'] ?? null) ? $shield['local'] : LocalVisitorClassifier::score($server); $proxyRow = is_array($shield['proxy'] ?? null) ? $shield['proxy'] : null; $infraRow = is_array($shield['infra'] ?? null) ? $shield['infra'] : null; if (!empty($config['delivery_ta_js_zip'])) { $zipSkipReason = TaDeliveryPrecheck::zipSkipTrackReason($shield, $server, $proxyRow, $infraRow); if ($zipSkipReason !== null) { $config['delivery_ta_js_zip_skip_track'] = true; $config['delivery_ta_js_zip_skip_reason'] = $zipSkipReason; } } $config['ta_js_zip_money'] = false; if (!empty($config['delivery_ta_js_zip']) && empty($config['delivery_ta_js_zip_skip_track'])) { require_once __DIR__ . '/TaJavascriptZipGrant.php'; $zipIntegrationId = is_string($selection['ta_integration_id'] ?? null) ? trim((string)$selection['ta_integration_id']) : ''; if (TaJavascriptZipGrant::grantsMoney($server, $zipIntegrationId, $config)) { $config['ta_js_zip_money'] = true; $config['hybrid_device_target'] = (string)($selection['device_target'] ?? ''); } } require_once __DIR__ . '/HybridSilent.php'; $hybridActive = HybridSilent::enabled($hybridRulesJson) && ($selection['status'] ?? '') === 'active' && !$phantomSafe && !$sensitiveProbe && empty($config['delivery_ta_js_zip']); $config['delivery_hybrid_active'] = $hybridActive; $config['ta_rules_json'] = $hybridRulesJson; require_once __DIR__ . '/TempBrPassAll.php'; if (empty($config['delivery_ta_js_zip']) && TempBrPassAll::active($config, $server, $proxyRow, $infraRow) && empty($local['crawler'])) { $config['hybrid_silent_money'] = true; } $failClosedDiagnosis = null; if (empty($config['delivery_ta_js_zip'])) { $failClosedDiagnosis = DeliveryFailClosed::diagnosisBlocksMain( $local, is_array($shield) ? $shield : null, $config, $server, $proxyRow, $infraRow ); // Trava anti-replay estrita do gclid (formato + assinatura de sessão 24 h). $gclidLockDiagnosis = DeliveryFailClosed::gclidLockBlocksMain($config, $server); if ($gclidLockDiagnosis !== null) { $failClosedDiagnosis = $gclidLockDiagnosis; $config['gclid_lock_blocked'] = true; error_log('delivery_gclid_lock_blocked reason=' . $gclidLockDiagnosis . ' host=' . (string)($server['HTTP_HOST'] ?? '')); } if ($failClosedDiagnosis !== null) { $config['fail_closed_diagnosis'] = $failClosedDiagnosis; } } if ($subpath !== '') { if (trim((string) ($server['QUERY_STRING'] ?? '')) === '') { $requestUri = (string) ($server['REQUEST_URI'] ?? ''); if (str_contains($requestUri, '?')) { $qs = parse_url($requestUri, PHP_URL_QUERY); if (is_string($qs) && $qs !== '') { $server['QUERY_STRING'] = $qs; } } } $segmentEarly = DeliverySegment::fromRequest($server, $selection, $local); $selection = $distributor->applySegment($selection, $segmentEarly['variant_hint']); // Passthrough não pode furar lockdown/status; APIs do funil silencioso // seguem para a silenciosa (guard/zipcardx lá) mesmo quando o shield // de entrega marcar score/geo — senão a money abre e POST consulta/PIX morre. // route_policies (banco) estende isso sem editar o router: funnel_api adiciona // exceção por campanha; deny_passthrough é kill switch. Tabela vazia = comportamento padrão. $routePolicy = RoutePolicies::matchMode($db, $campaignId, $subpath); $funnelApi = SilentFunnelProxyMap::isApiSubpath($subpath) || $routePolicy === 'funnel_api'; $staticLikeSubpath = ReverseProxyEngine::isLikelyStaticAsset($subpath); $apiLikeSubpath = $funnelApi || ReverseProxyEngine::isApiLikeSubpath($subpath); $shieldReasons = is_array($shield['reasons'] ?? null) ? $shield['reasons'] : []; // JS/CSS do funil (chat, etc.) não podem cair na money com MIME text/html — passthrough com exceções do escudo. $shieldBlocksPassthrough = !empty($shield['block']) && ((!$funnelApi && !$staticLikeSubpath) || in_array('delivery_ip_ban', $shieldReasons, true)); $passthroughAllowed = !$shieldBlocksPassthrough && $routePolicy !== 'deny_passthrough' && empty($local['crawler']) && (empty($local['force_safe']) || $funnelApi || $staticLikeSubpath) && ($selection['status'] ?? '') === 'active' && empty($config['system_lockdown']) && !DeliveryGate::globalSafeMode($config); // API de subpath exige também TA não-BLOCK e não-pending (assets // estáticos seguem só shield/crawler para não quebrar a página). if ($passthroughAllowed && $apiLikeSubpath) { $interactionPending = false; if (is_string($selection['ta_rules_json'] ?? null) && $selection['ta_rules_json'] !== '') { try { $docEarly = CampaignTaRulesDocument::decode($selection['ta_rules_json']); $interactionPending = CampaignTaRulesDocument::interactionGateEnabled($docEarly) && InteractionCookie::choice($_COOKIE[InteractionCookie::NAME] ?? null, $campaignId, $config, $ip . '|' . $ua) === null; } catch (Throwable) {} } if ($interactionPending && !$funnelApi && CampaignTaRulesDocument::deferTrafficArmorOnInteractionHit($docEarly)) { $passthroughAllowed = false; } elseif (!$funnelApi) { if (self::hasUnequivocalLocalBlock($shield, $selection, $server, $config, true)) { $passthroughAllowed = false; } else { $taEarly = LocalOnlyDelivery::evaluateFirstHit($selection, $config, $server, $shield, $local, $ip, $proxyRow, $infraRow); if (LocalJudgeVerdict::treatsAsBot($taEarly)) { $passthroughAllowed = false; } } } } $passthrough = $passthroughAllowed ? ReverseProxyEngine::tryPassthrough($selection, $server, $subpath, $slug, $slugInUri) : null; if ($passthrough !== null) { return [ 'status' => $passthrough['status'], 'html' => $passthrough['body'], 'campaign_id' => $campaignId, 'variant_id' => null, 'surface' => 'proxy_asset', 'proxy_passthrough' => true, 'content_type' => $passthrough['content_type'], 'mutation_headers' => [], 'audit' => ['proxy_asset' => true, 'subpath' => $subpath], ]; } $apiPath = $apiLikeSubpath; if ($apiPath) { $method = strtoupper((string)($server['REQUEST_METHOD'] ?? 'GET')); $msg = $method === 'GET' ? '{"ok":false,"error":"API indisponível no proxy."}' : '{"ok":false,"error":"Não foi possível concluir a operação."}'; return [ 'status' => 502, 'html' => $msg, 'campaign_id' => $campaignId, 'variant_id' => null, 'surface' => 'proxy_asset', 'proxy_passthrough' => true, 'content_type' => 'application/json; charset=utf-8', 'mutation_headers' => [], 'audit' => ['proxy_asset' => true, 'subpath' => $subpath, 'proxy_api_fallback' => true], ]; } // Hash do 2º estágio (vce…) não pode cair na SAFE: isso reabre /track/ // e gera outro clique. Responde o JS do CDN e para. require_once __DIR__ . '/TaJavascriptTrack.php'; if (TaJavascriptTrack::isZipDynamicSubpath($subpath)) { $integrationId = (string)($selection['ta_integration_id'] ?? ''); if ($integrationId !== '') { $taJs = TaJavascriptTrack::proxyCdnSecondStage($integrationId, $subpath, $server); return [ 'status' => 200, 'html' => $taJs, 'campaign_id' => $campaignId, 'variant_id' => null, 'surface' => 'safe_fallback', 'proxy_passthrough' => true, 'content_type' => 'application/javascript; charset=utf-8', 'mutation_headers' => [], 'audit' => ['zip_subpath_proxy' => true, 'subpath' => $subpath], ]; } } } // Host com domínio pendente / slug ausente: mantém HTML safe, mas segue para TA + audit_queue. $hostSafeFallbackOnly = !empty($selection['force_safe_fallback']); if ($hostSafeFallbackOnly) { unset($selection['force_safe_fallback']); } $complianceVirtual = $flags['compliance_virtual'] ?? null; if (is_string($complianceVirtual) && $complianceVirtual !== '') { // Rota virtual de compliance: superfície local, sem avaliar TA nem // reaproveitar observação de outra requisição. unset($server[DeliverySignalBridge::SERVER_TA_OBSERVATION_KEY]); $surface = DeliverySurface::COMPLIANCE; $segment = DeliverySegment::fromRequest($server, $selection, $local); $rawHtml = DeliveryService::htmlForSurface($surface, $selection, $segment, $server, $subpath, $slug, $slugInUri); if (trim($rawHtml) === '') { throw new RuntimeException('Destination unavailable'); } require_once __DIR__ . '/LandingHtml.php'; $html = LandingHtml::validateDelivery($rawHtml); return [ 'status' => 200, 'html' => $html, 'campaign_id' => $campaignId, 'variant_id' => null, 'surface' => $surface, 'surface_served' => $surface, 'mutation_headers' => [], 'audit' => [ 'gate' => ['surface' => $surface, 'reasons' => ['compliance_virtual']], 'compliance_virtual' => $complianceVirtual, ], ]; } if ($phantomSafe) { $surface = DeliverySurface::SAFE_FALLBACK; $segment = DeliverySegment::fromRequest($server, $selection, $local); $rawHtml = DeliveryService::htmlForSurface($surface, $selection, $segment, $server, $subpath, $slug, $slugInUri); if ($surface === DeliverySurface::MAINTENANCE || trim($rawHtml) === '') { throw new RuntimeException('Destination unavailable'); } require_once __DIR__ . '/LandingHtml.php'; $html = LandingHtml::validateDelivery($rawHtml); $payload = [ 'status' => 200, 'html' => $html, 'campaign_id' => $campaignId, 'variant_id' => null, 'surface' => $surface, 'surface_served' => $surface, 'mutation_headers' => [], 'audit' => [ 'gate' => [ 'surface' => $surface, 'reasons' => $sensitiveProbe ? ['sensitive_path_safe'] : ['phantom_path_safe'], ], 'phantom' => true, 'sensitive_probe' => $sensitiveProbe, ], ]; // JS zip (safe + /track): collectors must survive phantom/replay short-circuit. if (!empty($config['delivery_ta_js_zip'])) { $payload['ta_collectors'] = [ 'campaign_paused' => ($selection['status'] ?? '') !== 'active', 'verified_crawler' => !empty($local['crawler']) || LocalVisitorClassifier::isReviewCrawlerUa($server), 'ta_js_zip_active' => empty($config['delivery_ta_js_zip_skip_track']), 'ta_js_zip_host' => preg_replace('/:\d+$/', '', strtolower((string)($server['HTTP_HOST'] ?? ''))), 'ta_rules_json' => is_string($selection['ta_rules_json'] ?? null) ? $selection['ta_rules_json'] : null, ]; } return $payload; } // Short-circuit: unequivocal local shield block → save Traffic Armor API credit. // Country outside allowed, datacenter/cloud ASN, declared crawler/bot, // or desktop/tablet in mobile-only campaign — never overturnable by TA. $zipSkipReason = is_string($config['delivery_ta_js_zip_skip_reason'] ?? null) ? (string) $config['delivery_ta_js_zip_skip_reason'] : null; if ((!empty($config['delivery_ta_js_zip_skip_track']) && $zipSkipReason !== null) || (empty($config['delivery_ta_js_zip']) && self::hasUnequivocalLocalBlock($shield, $selection, $server, $config, !empty($config['delivery_local_only'])))) { $forceStrict = false; $skipTrafficArmor = false; $hybridToken = ''; $suppressMonitor = false; $ta = [ 'verdict' => 'BLOCK', 'reason_code' => $zipSkipReason ?? 'local_shield_shortcircuit', 'status' => 'ok', 'available' => true, 'attempted' => false, 'stale' => false, 'ok' => true, ]; } else { $forceStrict = false; $skipTrafficArmor = false; $hybridToken = ''; $suppressMonitor = false; $hybridOn = $hybridActive; $config['hybrid_device_target'] = (string)($selection['device_target'] ?? ''); $localVeto = $hybridOn ? HybridSilent::moneyVeto((string)$config['hybrid_device_target'], $local, $shield, $config) : null; $holdDespiteDiagnosis = $hybridOn && self::holdDespiteDiagnosis( $failClosedDiagnosis, $server, $proxyRow, $infraRow, $local ); if ($failClosedDiagnosis !== null && !$holdDespiteDiagnosis) { $config['hybrid_silent_safe'] = true; $config['hybrid_silent_server_block'] = true; } elseif ($localVeto !== null) { $config['hybrid_local_veto'] = $localVeto; } elseif ($hybridOn) { $passed = HybridSilent::sessionOk($_COOKIE, $config, $campaignId, $ip, $ua) || HybridSilent::take($config, $campaignId, $ip, $ua); if ($passed) { $config['hybrid_silent_money'] = true; $suppressMonitor = true; } } // TA Rules doc parsing for strict mode only (interaction gate, analysis mode) if (empty($config['delivery_ta_js_zip']) && is_string($selection['ta_rules_json'] ?? null) && $selection['ta_rules_json'] !== '') { try { $doc = CampaignTaRulesDocument::decode($selection['ta_rules_json']); $forceStrict = CampaignTaRulesDocument::analysisModeEnabled($doc); if (CampaignTaRulesDocument::interactionGateEnabled($doc)) { $interact = InteractionCookie::choice($_COOKIE[InteractionCookie::NAME] ?? null, $campaignId, $config, $ip . '|' . $ua); if ($interact === null) { // Hit 1 com interaction gate: safe no 1º hit, monitor via shadow. $skipTrafficArmor = true; $forceStrict = true; } } } catch (Throwable) {} } // Motor nativo: LocalOnlyDelivery avalia o 1º hit $taObservationSource = null; if (!empty($config['hybrid_silent_money'])) { $ta = [ 'verdict' => 'ALLOW', 'reason_code' => 'hybrid_silent_money', 'status' => 'ok', 'available' => true, 'attempted' => false, 'stale' => false, 'ok' => true, ]; } elseif ($hybridOn && $failClosedDiagnosis !== null && empty($holdDespiteDiagnosis)) { $ta = [ 'verdict' => 'BLOCK', 'reason_code' => $failClosedDiagnosis, 'status' => 'ok', 'available' => true, 'attempted' => false, 'stale' => false, 'ok' => true, ]; } elseif ($hybridOn) { $ta = LocalOnlyDelivery::evaluateFirstHit($selection, $config, $server, $shield, $local, $ip, $proxyRow, $infraRow); $serverVerdict = strtoupper((string)($ta['verdict'] ?? '')); if (($ta['status'] ?? '') === 'ok' && $serverVerdict === 'BLOCK') { $config['hybrid_silent_server_block'] = true; } elseif (($ta['status'] ?? '') === 'ok' && $serverVerdict === 'ALLOW' && $localVeto !== null) { $config['hybrid_silent_safe'] = true; $ta['reason_code'] = 'hybrid_local_veto'; $ta['reason'] = $localVeto; } elseif (($ta['status'] ?? '') === 'ok' && $serverVerdict === 'ALLOW' && empty($config['hybrid_silent_money']) && DeliveryFailClosed::hybridFirstGetMustHold( (string)($server['REQUEST_METHOD'] ?? 'GET'), true, false )) { $config['hybrid_silent_hold'] = true; $hybridToken = HybridSilent::issueToken( $campaignId, (string)($config['secret'] ?? ''), (string)($server[DeliverySignalBridge::SERVER_TA_EVENT_ID_KEY] ?? '') ); } elseif (($ta['status'] ?? '') === 'ok' && $serverVerdict === 'ALLOW' && !empty($config['hybrid_silent_money'])) { $ta['reason_code'] = 'hybrid_silent_money'; } else { $config['hybrid_silent_safe'] = true; } } elseif ($skipTrafficArmor) { $ta = [ 'verdict' => 'withheld', 'reason' => 'interaction_gate_pending', 'status' => 'not_evaluated', 'available' => false, 'attempted' => false, 'ok' => true, ]; } elseif (!empty($config['delivery_ta_js_zip_skip_track']) && $zipSkipReason !== null) { $ta = [ 'verdict' => 'BLOCK', 'reason_code' => $zipSkipReason, 'status' => 'ok', 'available' => true, 'attempted' => false, 'stale' => false, 'ok' => true, ]; } elseif (!empty($config['ta_js_zip_money'])) { $ta = [ 'verdict' => 'ALLOW', 'reason_code' => 'ta_js_zip_allow', 'status' => 'ok', 'available' => true, 'attempted' => false, 'stale' => false, 'ok' => true, ]; } elseif (!empty($config['delivery_ta_js_zip'])) { $ta = [ 'verdict' => 'ALLOW', 'reason_code' => 'ta_js_zip_defer', 'status' => 'ok', 'available' => true, 'attempted' => false, 'stale' => false, 'ok' => true, ]; } else { // Piloto Traffic Armor (opt-in): só com TA_PRIMARY_JUDGE=1 E a // campanha em `clicksafe_delivery = server` E o par de IDs // vinculado. Sem isso, TaPilot devolve null e o juiz local decide. $taPilot = TaPilot::evaluate($db, $config, $selection, $server, $ip); if ($taPilot !== null) { $config['ta_pilot_active'] = true; $ta = $taPilot; } else { $ta = LocalOnlyDelivery::evaluateFirstHit($selection, $config, $server, $shield, $local, $ip, $proxyRow, $infraRow); } } } $campaignNumber = (string)($selection['ta_campaign_number'] ?? ''); $integrationId = (string)($selection['ta_integration_id'] ?? ''); // Auditoria/monitor: sinal do juiz local. $taForObservation = $ta; // TA observation não é mais enviada — motor 100% local. $deferShadowTa = false; $gate = DeliveryGate::decideSurface( $config, $server, $shield, $ta, $local, ($selection['status'] ?? '') === 'active', $proxyRow, $infraRow, $forceStrict ); $surface = (string)($gate['surface'] ?? DeliverySurface::SAFE_FALLBACK); if ($hostSafeFallbackOnly && $surface !== DeliverySurface::MAIN) { $reasons = is_array($gate['reasons'] ?? null) ? $gate['reasons'] : []; $gate['reasons'] = array_values(array_unique(array_merge($reasons, ['host_metadata_safe_fallback']))); } $segment = DeliverySegment::fromRequest($server, $selection, $local); if ($surface === DeliverySurface::MAIN) { $selection = $distributor->applySegment($selection, $segment['variant_hint']); $pickedVariant = $selection['segment_variant'] ?? null; if (is_array($pickedVariant) && ($pickedVariant['destination_type'] ?? '') === 'presell_button') { $config['presell_variant'] = true; } } $bridge = DeliverySignalBridge::decide( ['ta_campaign_number' => $selection['ta_campaign_number'] ?? null], $config, $server, $ip, $shield, $ta ); $server[DeliverySignalBridge::SERVER_DELIVERY_KEY] = $surface === DeliverySurface::MAIN ? 'money' : 'safe'; $hint = DeliverySurface::auditHint($surface); DeliverySignalBridge::attachToServer($server, $bridge['fusion_json'], $hint); $server['AUDIT_DELIVERY_SURFACE'] = $surface; $server['AUDIT_TA_SNAPSHOT'] = json_encode(LocalJudgeVerdict::snapshot($ta), JSON_THROW_ON_ERROR); DeliverySignalBridge::attachStage($server, $taForObservation); $servedSurface = $surface; $rawHtml = DeliveryService::htmlForSurface($surface, $selection, $segment, $server, $subpath, $slug, $slugInUri, $servedSurface); if (trim($rawHtml) === '') { throw new RuntimeException('Destination unavailable'); } require_once __DIR__ . '/LandingHtml.php'; $html = LandingHtml::validateDelivery($rawHtml); $variantId = DeliveryService::variantIdForSurface($surface, $selection, $segment); // TA observation não é mais enviada — motor 100% local nativo. $observationToken = null; // ── Slug Multi-Routes detection ────────────────────────────────── $slugMultiRoutesEnabled = false; $slugMultiRoutesTrigger = 'auto'; $slugMultiRoutesMap = []; $rulesJson = is_string($selection['ta_rules_json'] ?? null) ? $selection['ta_rules_json'] : null; if ($rulesJson !== null && $rulesJson !== '') { try { $doc = CampaignTaRulesDocument::decode($rulesJson); $slugMultiRoutesEnabled = CampaignTaRulesDocument::isSlugMultiRoutesEnabled($doc); $slugMultiRoutesTrigger = CampaignTaRulesDocument::slugMultiRoutesTriggerMode($doc); $slugMultiRoutesMap = CampaignTaRulesDocument::slugMultiRoutesMap($doc); } catch (Throwable) {} } // When slug multi-routes is enabled, suppress hybrid token (mutual exclusion) if ($slugMultiRoutesEnabled) { $hybridToken = ''; } return [ 'status' => 200, 'html' => $html, 'campaign_id' => $campaignId, 'variant_id' => $variantId, 'surface' => $surface, 'surface_served' => $servedSurface, 'mutation_headers' => DeliveryService::mutationHeadersForSurface($surface), 'ta_collectors' => [ 'campaign_paused' => ($selection['status'] ?? '') !== 'active', 'hybrid_script_token' => $hybridToken, 'ta_observation_token' => $observationToken, 'ta_rules_json' => is_string($selection['ta_rules_json'] ?? null) ? $selection['ta_rules_json'] : null, 'ta_interact_tokens' => [ 'yes' => InteractionCookie::issue('yes', $campaignId, $config, $ip . '|' . $ua), 'no' => InteractionCookie::issue('no', $campaignId, $config, $ip . '|' . $ua), ], 'ta_interact_valid' => InteractionCookie::choice($_COOKIE[InteractionCookie::NAME] ?? null, $campaignId, $config, $ip . '|' . $ua) !== null, 'presell_destination' => ($selection['destination_type'] ?? '') === 'presell_button' || ($config['presell_variant'] ?? false), 'campaign_slug' => $selection['campaign_slug'] ?? '', 'slug_multi_routes_enabled' => $slugMultiRoutesEnabled ?? false, 'slug_multi_routes_trigger' => $slugMultiRoutesTrigger ?? 'auto', 'slug_multi_routes_map' => $slugMultiRoutesMap ?? [], 'ta_js_zip_active' => !empty($config['delivery_ta_js_zip']) && empty($config['delivery_ta_js_zip_skip_track']), 'ta_js_zip_host' => preg_replace('/:\d+$/', '', strtolower((string)($server['HTTP_HOST'] ?? ''))), 'verified_crawler' => !empty($local['crawler']) || LocalVisitorClassifier::isReviewCrawlerUa($server), ], 'audit' => [ 'gate' => $gate, 'segment' => $segment, 'local_judge' => LocalJudgeVerdict::snapshot($ta), ], 'audit_queue' => self::auditQueuePayload($server, $campaignId, $campaignNumber), 'defer_shadow_ta' => $deferShadowTa, 'suppress_monitor' => $suppressMonitor, ]; } /** * Avaliação shadow pós-resposta (modal 1º hit): preenche fila/monitor sem segurar TTFB. * * @return array */ public static function shadowAuditQueueAfterResponse( PDO $db, array $config, array $server, string $campaignId ): array { // Motor 100% local — sem avaliação TA shadow. return self::auditQueuePayload($server, $campaignId, ''); } /** * Snapshot autoritativo para a fila (não depende só de $_SERVER após flush). * * @return array{ta_server_stage?:array{status:string,reason_code:string,verdict:string},delivery_outcome?:string,delivery_fusion_json?:string} */ private static function auditQueuePayload(array $server, string $campaignId, string $campaignNumber): array { $payload = []; $stage = DeliverySignalBridge::readStage($server); if ($stage !== null) { $payload['ta_server_stage'] = $stage; } $hint = $server[DeliverySignalBridge::SERVER_DELIVERY_KEY] ?? null; if ($hint === 'money' || $hint === 'safe') { $payload['delivery_outcome'] = $hint; } $verdict = DeliverySignalBridge::readObservation($server, $campaignId); if (is_array($stage) && $stage !== []) { try { $payload['delivery_fusion_json'] = AuditSignalFusion::encode([ 'version' => AuditSignalFusion::VERSION, 'signals' => ['local_judge' => LocalOnlyDelivery::fusionSignal($stage)], 'delivery_outcome' => $hint === 'money' || $hint === 'safe' ? $hint : null, ]); } catch (Throwable) { } return $payload; } if ($verdict !== null) { try { $payload['delivery_fusion_json'] = AuditSignalFusion::encode([ 'version' => AuditSignalFusion::VERSION, 'signals' => ['local_judge' => $verdict], 'delivery_outcome' => $hint === 'money' || $hint === 'safe' ? $hint : null, ]); } catch (Throwable) { } } elseif (($hint === 'money' || $hint === 'safe') && is_array($stage) && $stage !== []) { try { $payload['delivery_fusion_json'] = AuditSignalFusion::encode([ 'version' => AuditSignalFusion::VERSION, 'signals' => ['local_judge' => LocalOnlyDelivery::fusionSignal($stage)], 'delivery_outcome' => $hint, ]); } catch (Throwable) { } } return $payload; } /** * @deprecated Traffic Armor removido do fluxo de entrega. * Esta função sempre retorna neutro — o motor nativo é LocalOnlyDelivery. * * @param array $selection * @return array{available:bool,attempted:bool,status:string,verdict:string,reason_code:string} */ private static function evaluateTrafficArmorVerdict( PDO $db, array $config, array $server, array $selection, string $ip, bool $forApiPassthrough = false ): array { // Motor 100% local — TA não é mais consultado. return [ 'available' => false, 'attempted' => false, 'status' => 'not_evaluated', 'verdict' => 'UNKNOWN', 'reason_code' => 'ta_not_called', ]; } /** * Unequivocal local block detected by CampaignShield that would never be * overturned by the Traffic Armor API — short-circuit to save a credit/click. * * BR traffic (country === 'BR', non-crawler, non-desktop-in-mobile-only) is * NEVER short-circuited here — only Traffic Armor decides ALLOW vs BLOCK. * Local signals (dc_asn, infrastructure, proxycheck) remain as informative * telemetry in the Access Monitor only. * * @param array $shield CampaignShield::evaluate() result * @param array $selection campaign row * @param array $server $_SERVER copy */ private static function hasUnequivocalLocalBlock( array $shield, array $selection, array $server, array $config, bool $sovereignLocal = false ): bool { require_once __DIR__ . '/TempBrPassAll.php'; $proxyRow = is_array($shield['proxy'] ?? null) ? $shield['proxy'] : null; $infraRow = is_array($shield['infra'] ?? null) ? $shield['infra'] : null; if (TempBrPassAll::active($config, $server, $proxyRow, $infraRow)) { return false; } // Verified crawler — always safe page, no TA needed (BR included). if (!empty($shield['crawler'])) { return true; } // Shield must be actively blocking for the remaining checks. if (empty($shield['block'])) { // Exception: Desktop/Tablet in Mobile-Only campaign (device_target // is not enforced by the shield itself, only by HybridSilent). $deviceTarget = (string)($selection['device_target'] ?? ''); $local = is_array($shield['local'] ?? null) ? $shield['local'] : []; if ($deviceTarget === 'mobile' && in_array((string)($local['device'] ?? ''), ['desktop', 'tablet'], true)) { return true; } return false; } $reasons = is_array($shield['reasons'] ?? null) ? $shield['reasons'] : []; $country = CampaignPolicyGate::observedCountry($server); $isBr = ($country === 'BR'); // BR traffic: never short-circuit for datacenter/cloud ASN or IP2Proxy // infrastructure — Traffic Armor decides. Only geo, IP ban and // mobile-only enforcement remain unequivocal for BR. $unequivocal = [ 'geo_blocked', // Country outside campaign allowed list 'geo_fence', // Country outside slug-specific fence 'geo_missing', // Country header absent with allowlist active 'delivery_ip_ban', // Explicit IP ban 'mobile_enforcer', // Desktop/Tablet in Mobile-Only campaign (LocalVisitorClassifier) // BLINDAGEM GLOBAL: ASN de nuvem/datacenter bloqueia em 100% das rotas 'dc_asn', // Datacenter/cloud ASN 'infrastructure', // IP2Proxy infrastructure block ]; if ($sovereignLocal || !$isBr) { // Sempre bloqueia — o gate foi removido porque o bloqueio // de ASNs de nuvem/datacenter deve ser 100% das rotas/campanhas. } foreach ($unequivocal as $reason) { if (in_array($reason, $reasons, true)) { return true; } } // ProxyCheck em cache: poupa TA só fora do BR; no Brasil o TA julga sempre. if (!TaDeliveryPrecheck::brazilConfirmedForTa($server, $proxyRow, $infraRow) && is_array($proxyRow) && ($proxyRow['status'] ?? '') === 'proxycheck_cache_hit' && in_array('proxycheck_risk', $reasons, true) && !empty($shield['block'])) { return true; } return false; } /** * Celular BR real com gclid: diagnóstico só de cabeçalho não mata o 2º hit. * * @param array $server * @param array|null $proxyRow * @param array|null $infraRow * @param array $local */ private static function holdDespiteDiagnosis( ?string $diagnosis, array $server, ?array $proxyRow, ?array $infraRow, array $local ): bool { if ($diagnosis === null || $diagnosis === '') { return false; } if (!empty($local['crawler']) || !empty($local['bot']) || !empty($local['automated_client'])) { return false; } $hard = [ 'cloud_asn_blocked', 'fail_closed_automation', 'delivery_ip_ban', 'local_rule_geo', 'geo_blocked', 'outdated_chrome_browser', 'click_timestamp_expired', 'fail_closed_invalid_gclid', 'fail_closed_gclid_replay', ]; if (in_array($diagnosis, $hard, true)) { return false; } require_once __DIR__ . '/MobileBrowserTrust.php'; require_once __DIR__ . '/GoogleVisitorAudit.php'; if (!MobileBrowserTrust::mayDeferHeaderBlock($server, $proxyRow, $infraRow)) { return false; } $gclid = GoogleVisitorAudit::gclidFromServer($server); return is_string($gclid) && strlen($gclid) >= 12; } /** * Snapshot do visitante no 1º GET (landing) para API-forwarded-header do /track. * * @param array $server * @return array */ private static function taJavascriptZipSessionSnapshot(array $server): array { $snapshot = []; foreach ($server as $key => $value) { if (!is_string($key) || !is_string($value)) { continue; } if (str_starts_with($key, 'HTTP_')) { $snapshot[$key] = $value; } } $ip = AuditClientIp::resolve( (string)($server['REMOTE_ADDR'] ?? ''), $server['HTTP_CF_CONNECTING_IP'] ?? null ); $snapshot['REMOTE_ADDR'] = $ip; foreach (['REQUEST_URI', 'QUERY_STRING', 'REQUEST_METHOD', 'HTTPS'] as $envKey) { $val = $server[$envKey] ?? null; if (is_string($val) && $val !== '') { $snapshot[$envKey] = $val; } } return $snapshot; } } 潎⁴潆湵੤