Lines: 90.91%
| Line | Hits | Source |
|---|---|---|
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Drupal\visitors\Service; | |
| 6 | ||
| 7 | use Drupal\visitors\VisitorsAiAgentInterface; | |
| 8 | use Symfony\Component\HttpFoundation\Request; | |
| 9 | ||
| 10 | /** | |
| 11 | * Detects visits opened by an AI agent browser. | |
| 12 | */ | |
| 13 | final class AiAgentDetector implements VisitorsAiAgentInterface { | |
| 14 | ||
| 15 | /** | |
| 16 | * ChatGPT Signature-Agent value, including the quotes. | |
| 17 | */ | |
| 18 | private const CHATGPT_AGENT = '"https://chatgpt.com"'; | |
| 19 | ||
| 20 | /** | |
| 21 | * Nova Act user agent token, including the leading space. | |
| 22 | */ | |
| 23 | private const NOVA_ACT = ' Agent-NovaAct/'; | |
| 24 | ||
| 25 | /** | |
| 26 | * {@inheritdoc} | |
| 27 | */ | |
| 28 | public function isAgent(Request $request): bool { | |
| 29 | 11 | return $this->isChatGpt($request) || $this->isNovaAct($request); |
| 30 | } | |
| 31 | ||
| 32 | /** | |
| 33 | * Whether the request carries a ChatGPT agent signature. | |
| 34 | * | |
| 35 | * Signature and Signature-Input must be present. Signature-Agent | |
| 36 | * must be the quoted ChatGPT agent URL. | |
| 37 | */ | |
| 38 | private function isChatGpt(Request $request): bool { | |
| 39 | 11 | $signature = trim((string) $request->headers->get('Signature', '')); |
| 40 | 11 | $agent = trim((string) $request->headers->get('Signature-Agent', '')); |
| 41 | 11 | $input = trim((string) $request->headers->get('Signature-Input', '')); |
| 42 | 11 | return $signature !== '' |
| 43 | 11 | && $input !== '' |
| 44 | 11 | && $agent === self::CHATGPT_AGENT; |
| 45 | } | |
| 46 | ||
| 47 | /** | |
| 48 | * Whether the user agent is Amazon Nova Act. | |
| 49 | */ | |
| 50 | private function isNovaAct(Request $request): bool { | |
| 51 | 10 | $user_agent = (string) $request->headers->get('User-Agent', ''); |
| 52 | 10 | if ($user_agent === '') { |
| 53 | 0 | $user_agent = (string) $request->server->get('HTTP_USER_AGENT', ''); |
| 54 | } | |
| 55 | 10 | return stripos($user_agent, self::NOVA_ACT) !== FALSE; |
| 56 | } | |
| 57 | ||
| 58 | } |