# knownprint in the backend: PHP (Laravel, Symfony, plain PHP)

Part of the knownprint quickstart for AI coding agents, Step 6. Read
https://knownprint.com/quickstart.md first: it holds the rules that apply here (never read or print
secrets, ask before touching a live server, an unknown result is never a pass). This file covers the
module that reads the event, runs the six checks and decides, and how to call it from a handler. The
checks and rules it implements are written out in https://knownprint.com/quickstart/other.md.

Use the module as written. It takes the values of `KNOWNPRINT_API`, `KNOWNPRINT_SECRET_KEY` and
`KNOWNPRINT_SITE_ORIGINS` in its constructor, never logs a request id, an address or a secret, and turns every failure
into an "unknown" result that takes the challenge path.

## The module

PHP 8.1 or later with the curl extension. The class takes its settings in the constructor, so it
works in any namespace and under PHP-FPM, whose workers do not see the shell's environment:

```php
<?php
// Knownprint.php (in Laravel: app/Services/Knownprint.php, with namespace App\Services;)

final class Knownprint
{
    private const MAX_AGE = 10.0;
    private const CLOCK_SKEW = 60.0;

    /**
     * @param string[] $siteOrigins every origin whose pages run the script
     * @param callable(string): bool $useOnce true only the first time an id is seen
     */
    public function __construct(
        private string $api,
        private string $secretKey,
        private array $siteOrigins,
        private $useOnce,
    ) {}

    public static function canonicalIp(?string $text): ?string
    {
        $packed = $text === null ? false : @inet_pton(trim($text));
        if ($packed === false) {
            return null;
        }
        if (strlen($packed) === 16 && str_starts_with($packed, str_repeat("\0", 10) . "\xff\xff")) {
            $packed = substr($packed, 12);
        }
        return inet_ntop($packed);
    }

    /**
     * The visitor's address. Under fastcgi_pass, REMOTE_ADDR is already the visitor. Behind an HTTP
     * proxy on the same host, the last X-Forwarded-For entry, which that proxy appended.
     */
    public static function clientIp(?string $remoteAddr, ?string $forwardedFor): ?string
    {
        $peer = self::canonicalIp($remoteAddr);
        if ($peer === '127.0.0.1' || $peer === '::1') {
            $entries = array_values(array_filter(array_map('trim', explode(',', $forwardedFor ?? ''))));
            if ($entries !== []) {
                return self::canonicalIp(end($entries));
            }
        }
        return $peer;
    }

    private function call(string $method, string $path, ?array $body = null): mixed
    {
        $curl = curl_init($this->api . $path);
        $headers = ['Authorization: Bearer ' . $this->secretKey, 'Accept: application/json'];
        if ($body !== null) {
            $headers[] = 'Content-Type: application/json';
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body));
        }
        curl_setopt_array($curl, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 5,
        ]);
        $raw = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        curl_close($curl);
        if ($raw === false) {
            throw new \RuntimeException('knownprint unreachable');
        }
        if ($status === 404 || $status === 409) {
            return null;
        }
        if ($status < 200 || $status >= 300) {
            throw new \RuntimeException("knownprint answered $status");
        }
        return $raw === '' ? true : json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
    }

    /** @return array{ok: bool, reason?: string, event?: array} never throws */
    public function verifyRequestId(mixed $requestId, ?string $ip): array
    {
        try {
            if (!is_string($requestId) || !preg_match('/^evt_[a-z2-7]{26}\z/', $requestId)) {
                return ['ok' => false, 'reason' => 'missing'];
            }
            if (!($this->useOnce)($requestId)) {
                return ['ok' => false, 'reason' => 'used'];
            }
            $event = $this->call('GET', '/v1/events/' . $requestId);
            if ($event === null) {
                return ['ok' => false, 'reason' => 'not_found'];
            }
            $received = (float) (new \DateTimeImmutable($event['received_at']))->format('U.u');
            $age = microtime(true) - $received;
            if ($age > self::MAX_AGE || $age < -self::CLOCK_SKEW) {
                return ['ok' => false, 'reason' => 'stale'];
            }
            if ($event['integrity']['replayed']) {
                return ['ok' => false, 'reason' => 'replayed'];
            }
            if (!in_array($event['integrity']['origin'], $this->siteOrigins, true)) {
                return ['ok' => false, 'reason' => 'origin'];
            }
            if ($event['network']['ip'] === null || $event['network']['ip'] !== self::canonicalIp($ip)) {
                return ['ok' => false, 'reason' => 'address'];
            }
            return ['ok' => true, 'event' => $event];
        } catch (\Throwable $error) {
            error_log('knownprint: ' . get_class($error)); // never the request id or the address
            return ['ok' => false, 'reason' => 'error'];
        }
    }

    /** 'allow' | 'challenge' | 'review' | 'block'. Example thresholds: tune them. */
    public static function decide(array $result): string
    {
        if (!$result['ok']) {
            return 'challenge'; // unknown: never allow, never block on this alone
        }
        $signals = $result['event']['signals'];
        $score = $signals['suspect_score']['value'] ?? null;
        if (($signals['bot']['value'] ?? null) === 'bad') {
            return 'block';
        }
        if ($score === null) {
            return 'challenge';
        }
        if (($signals['tampering']['value'] ?? null) === true || $score >= 60) {
            return 'review';
        }
        return $score >= 30 ? 'challenge' : 'allow';
    }

    /** Attach your account id to the event once the account exists. Never throws. */
    public function linkAccount(string $requestId, string|int $accountId): void
    {
        try {
            $this->call('PATCH', '/v1/events/' . $requestId, ['linked_id' => (string) $accountId]);
        } catch (\Throwable $error) {
            error_log('knownprint link: ' . get_class($error));
        }
    }
}
```

In Laravel, put the settings in `config/services.php` (`'knownprint' => ['api' =>
env('KNOWNPRINT_API'), 'secret_key' => env('KNOWNPRINT_SECRET_KEY'), 'site_origins' =>
env('KNOWNPRINT_SITE_ORIGINS')]`) so they survive `config:cache`, and build the class from them:

```php
$kp = new Knownprint(
    config('services.knownprint.api'),
    config('services.knownprint.secret_key'),
    array_map('trim', explode(',', (string) config('services.knownprint.site_origins'))),
    fn (string $id): bool => Cache::add("kp:used:$id", 1, 70),
);
$ip = Knownprint::clientIp($request->server('REMOTE_ADDR'), $request->header('X-Forwarded-For'));
$result = $kp->verifyRequestId($request->input('kp_request_id'), $ip);
$decision = Knownprint::decide($result);
```

Without a framework, read the values from the PHP-FPM pool (`env[KNOWNPRINT_API] =` lines) or a
configuration file outside the web root, and use a shared cache (APCu with `apcu_add`, or Redis
with `SET key 1 PX 70000 NX`) for single use.

Next: https://knownprint.com/quickstart.md, the end of Step 6.
