Coverage index

src/Service/AiAgentDetector.php

Lines: 90.91%

LineHitsSource
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 {
2911
    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 {
3911
    $signature = trim((string) $request->headers->get('Signature', ''));
4011
    $agent = trim((string) $request->headers->get('Signature-Agent', ''));
4111
    $input = trim((string) $request->headers->get('Signature-Input', ''));
4211
    return $signature !== ''
4311
      && $input !== ''
4411
      && $agent === self::CHATGPT_AGENT;
45
  }
46
47
  /**
48
   * Whether the user agent is Amazon Nova Act.
49
   */
50
  private function isNovaAct(Request $request): bool {
5110
    $user_agent = (string) $request->headers->get('User-Agent', '');
5210
    if ($user_agent === '') {
530
      $user_agent = (string) $request->server->get('HTTP_USER_AGENT', '');
54
    }
5510
    return stripos($user_agent, self::NOVA_ACT) !== FALSE;
56
  }
57
58
}