fingerly / fingerly-php
Server-side Fingerly SDK: event reads, webhook verification and a same-origin proxy for the browser SDK.
Requires
- php: ^8.2
- ext-curl: *
- ext-json: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- illuminate/http: ^10.0 || ^11.0 || ^12.0 || ^13.0
- nyholm/psr7: ^1.8
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
- psr/http-server-middleware: ^1.0
- symfony/http-kernel: ^6.4 || ^7.0 || ^8.0
- symfony/var-dumper: ^6.4 || ^7.0 || ^8.0
Suggests
- illuminate/http: To mount the same-origin proxy as Laravel middleware.
- psr/http-client: To send API requests through your own PSR-18 client instead of ext-curl.
- psr/http-factory: Required alongside psr/http-client when supplying your own client.
- psr/http-server-middleware: To mount the same-origin proxy as PSR-15 middleware (Slim, Mezzio).
- symfony/http-kernel: To mount the same-origin proxy as a Symfony kernel listener.
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-17 14:26:55 UTC
README
Fingerly for PHP
Read device intelligence events, verify webhooks and serve the browser SDK from your own domain.
What is this
fingerly/fingerly-php is the server-side SDK for PHP. It reads Fingerly events
with a secret key, verifies webhook signatures and relays the browser SDK's
traffic through your own domain with a same-origin proxy, with adapters for
Laravel, Symfony and PSR-15. It needs nothing outside ext-curl and ext-json
and is for backends that protect signups, logins and payments from fraud and
abuse. Fingerly identifies the device behind each session
and scores how suspicious it is.
Getting started
-
Prerequisites. A Fingerly account and a secret key (
fly_sk_...). See API keys and environments. PHP 8.2 or newer, and nothing outsideext-curlandext-json. Run a PHP release with the October 2026 security fixes (see Requirements). -
Install.
composer require fingerly/fingerly-php:^0.4.1
-
Read an event.
$fingerly = new \Fingerly\Client(getenv('FINGERLY_SECRET_KEY')); $event = $fingerly->events->get($requestId); $page = $fingerly->events->list(['level' => \Fingerly\SuspectLevel::HIGH, 'limit' => 50]);
-
Verify a webhook.
$valid = \Fingerly\Webhook::verify( secret: getenv('FINGERLY_WEBHOOK_SECRET'), payload: $request->getContent(), // the exact bytes, before any parsing timestamp: $request->header('x-fingerly-timestamp'), signature: $request->header('x-fingerly-signature'), ); abort_unless($valid, 400); $event = \Fingerly\Webhook::parse($request->getContent()); ProcessFingerlyEvent::dispatch($event->id); // deduplicate on the ID
Full guide: docs.fingerly.io/docs/sdks/php.
Choose what you need
| I want to | Use | Read |
|---|---|---|
| Read an event after the browser identified a visitor | \Fingerly\Client and events->get / events->list |
Read events |
| Verify a request id before a backend action, once | events->verify / events->consume |
Verify a backend action |
| Read or write an iOS device's Apple DeviceCheck bits | deviceCheck->query / deviceCheck->write |
Apple DeviceCheck bits |
| Check a webhook delivery is genuine | \Fingerly\Webhook::verify and ::parse |
Verify webhooks |
| Keep the browser SDK first-party, away from content blockers | \Fingerly\Proxy with a Laravel, Symfony or PSR-15 adapter |
First-party proxy |
On this page: Dependencies · Read events · DeviceCheck bits · Verify webhooks · First-party proxy · Requirements · Development · Documentation · Help · Licence
No dependencies
ext-curl is the only HTTP client PHP ships, so it is what the package uses
and there is nothing to install. CI asserts the package installs with zero
Composer packages and that the client, the proxy and webhook verification all
work in that state.
Everything else is a suggest, pulled in only if you use it:
| Package | Use it to |
|---|---|
psr/http-client |
route event reads through your own HTTP stack |
psr/http-server-middleware |
mount the proxy as PSR-15 middleware |
illuminate/http |
mount the proxy as Laravel middleware |
symfony/http-kernel |
mount the proxy as a Symfony kernel listener |
A supplied client takes a PSR-17 request_factory, plus a stream_factory
wherever a body is sent. With Guzzle (composer require guzzlehttp/guzzle),
one object is both factories:
// Redirects off and a deadline set: a supplied client owns both (see below). $http = new \GuzzleHttp\Client(['allow_redirects' => false, 'timeout' => 5]); $factory = new \GuzzleHttp\Psr7\HttpFactory(); $fingerly = new \Fingerly\Client(getenv('FINGERLY_SECRET_KEY'), [ 'http_client' => $http, 'request_factory' => $factory, 'stream_factory' => $factory, ]);
PSR-18 has no way to express "do not follow redirects" or a deadline, so a supplied client owns both. The ext-curl path enforces them itself. If you supply a client, disable redirects on it: an authenticated request that follows one replays your secret key to another host.
The
Proxytakes no HTTP client. It always sends over ext-curl with redirects off, because a client that followed a redirect would replay the proxy key before any answer came back.
Read events
Event reads require fly_sk_{production|staging|development}_… keys. Requests
go to https://api.fingerly.io; the endpoint option overrides that. The
secret key travels with every read, so endpoint must be a bare HTTPS origin,
https://host or https://host:port, with no credentials, path, query,
fragment, space or control character. Plain HTTP is accepted only for
127.0.0.1, localhost or [::1], and only with
'allow_insecure_loopback' => true, for a local API or test harness. Public,
proxy, management, malformed and unsupported keys are rejected before network
access. Requests do not follow redirects. get and list each perform one
request and never retry.
Construct the client once and reuse it. Every option is validated in the
constructor, so an invalid key or endpoint throws before anything is sent. An
option this build does not know is refused rather than ignored, because a
silently dropped timeout or endpoint is exactly the kind of thing nobody
notices until it matters.
Unscored events
$event->suspectScore is null when the request was not scored. Never read
null as zero: a visitor about whom nothing fired scores 0, while a submission
that was never enriched has no score at all. $event->isScored() states the
distinction at the call site.
if (!$event->isScored()) { // Unscored. Decide on something else; do not treat it as clean. }
$event->raw and $page->raw keep the response body exactly as it arrived, so
a field the API adds later is reachable without an upgrade.
Read an event you just identified
An event is usually readable as soon as identification answers. If it is
still being recorded, the read throws an ApiException whose isPending() is
true and whose getRetryAfter() says when to read again:
try { $event = $fingerly->events->get($requestId); } catch (\Fingerly\ApiException $e) { if (!$e->isPending()) { throw $e; } // Not recorded yet, so nothing is decided: read again after // $e->getRetryAfter() seconds (2 when null), or verify asynchronously. $event = null; }
Retry a pending read a bounded number of times, for example from a queued job.
isEventNotFound() means a request id that was never issued, or one past
retention, and is never pending.
The archived document arrives moments after the event itself, so check
hasDocument rather than assuming it is there, and read $event->document
(?array, holding allow-listed risk, attestation, ip_network and
velocity fields without raw signals, user agent or address). When a submission
is unidentifiable (identifiable == false, such as insufficient entropy, a
genuine embedded WebView, or an unmatched high-risk Web payload),
$event->visitorId is ''; there are no deferred_token, deferred_signals
or supplements fields in v: 3.
Compare fields against the named constants rather than raw strings. Each is a
final class of public const wire strings, so
\Fingerly\SuspectLevel::HIGH === $event->suspectLevel is an ordinary string
comparison, and every field stays a string: a value the server adds later
arrives unchanged, and is only missing from the class's ALL list. They are
deliberately not backed enums: an enum case is an object, so comparing it with
=== to a string field is always false, and from() throws on a value this
release has not heard of.
| Class | Field | Values |
|---|---|---|
Signal |
EventTrigger::$signal, $group |
every signal group and detector, such as VPN, VPN_PUBLIC and FINGERPRINT_SUPPRESSED |
SuspectLevel |
Event::$suspectLevel, webhook $data['level'] |
LOW, MEDIUM, HIGH |
Confidence |
EventTrigger::$confidence |
LOW, MEDIUM, HIGH |
EventState |
Event::$state |
ENRICHED, UNAVAILABLE, and PENDING, which a read throws as isPending() |
Environment |
Event::$environment |
PRODUCTION, STAGING, DEVELOPMENT |
Platform |
Event::$platform |
WEB, ANDROID, IOS |
AnonymityNetwork |
Event::$anonymityNetwork |
TOR, RELAY, VPN, PROXY, HOSTING |
DeviceKind |
Event::$deviceKind |
DESKTOP, MOBILE, TABLET, SERVER |
VisitorKind |
Event::$visitorKind |
HUMAN, AI_BOT, AUTOMATION, SEARCH_CRAWLER |
AttestationState |
$event->document['attestation']['state'] |
ATTESTED, NOT_ATTESTED, FAILED |
AttestationStatus |
$event->document['attestation']['status'] |
VERIFIED, INDETERMINATE, INVALID, ABSENT, UNCONFIGURED |
AttestSkippedReason |
$event->document['attestation']['attest_skipped'] |
NOT_OFFERED, UNSUPPORTED, CHALLENGE_UNAVAILABLE, KEY_ERROR, TIMEOUT, BACKOFF, INSTALL_UNAVAILABLE |
VerifyReason |
EventVerification::$reason |
OK ('') and the failures in Verify a backend action |
WebhookEventType |
WebhookEvent::$type |
see Verify webhooks |
WebhookEnvironment |
WebhookEvent::$environment |
LIVE, TEST |
All live in the Fingerly namespace. A constant's name is its value
upper-cased, with . as _ (VerifyReason::OK is ''). Event reads report
each trigger under its signal group (Signal::VPN), while visitor.suspect
webhooks and the archived document's risk.triggers carry the detector
(Signal::VPN_PUBLIC) with its group beside it. The SIGNAL_* constants on
EventTrigger, its V3_SIGNALS list and the REASON_* constants on
EventVerification are the same strings.
Event::$projectId names the Fingerly project the event belongs to, as a UUID
string. It is null when the server is older than projects.
Verify a backend action
Send the request id from the browser or app to your backend, and verify it there with a server-only key. Do not authorize an action using scores or visitor identifiers supplied by the browser.
$fingerly->events->verify() reads the event and runs these checks in order,
stopping at the first that fails. $result->reason names it, as one of the
\Fingerly\VerifyReason constants:
not_found: there is no such event.$result->eventis null only here.too_old: it happened more thanmax_age_secondsago (300 by default), or its time cannot be read.tag_mismatch: you passedtagand the event's tag is not exactly it. An untagged event never matches.unidentifiable: the event'svisitorIdis''.unscored: the event has no suspect score.already_consumed: another call already consumed the event.
When every other check passes, verify consumes the event last, so one event
backs one decision: a replayed request id answers already_consumed. Pass
'consume' => false to check without consuming. Then $result->ok is true
and $result->reason is ''.
verify never judges the score, the level or the triggers. Your policy
decides what they mean for the action, after ok:
$result = $fingerly->events->verify($requestId, [ 'tag' => 'checkout', 'max_age_seconds' => 300, ]); if (!$result->ok) { return 'refuse'; // $result->reason says why } $event = $result->event; if (\Fingerly\SuspectLevel::HIGH === $event->suspectLevel) { return 'review'; } foreach ($event->triggers as $trigger) { if (\Fingerly\Signal::ATTESTATION_FAILED === $trigger->signal) { return 'refuse'; } }
A pending event (isPending()) is not a verdict, so verify throws it as an
ApiException, along with every other error: retry after getRetryAfter()
seconds or verify asynchronously, rather than refusing the action. An unknown
option, a max_age_seconds that is not a positive integer, an empty tag or a
consume that is not a boolean throws ConfigurationException before anything
is sent.
$fingerly->events->consume($requestId) consumes an event on its own. The
first call returns an EventConsumption whose first is true; any later call
throws \Fingerly\EventAlreadyConsumedException, an ApiException
(409 event_already_consumed, isAlreadyConsumed()) whose getConsumedAt()
says when. It is never retried.
Tags correlate events; they do not replace your application's authentication or replay protection. Never put a personal identifier (user ID, email, install ID, advertising ID) in a tag: the server keeps tags in long-lived rollups.
Errors
Everything thrown implements \Fingerly\FingerlyException, so one catch
handles the lot, and the concrete classes tell them apart:
| Class | When |
|---|---|
ConfigurationException |
An option was rejected. Nothing was sent. It is an InvalidArgumentException, because a key that was never valid will not become valid on a retry. |
ApiException |
The API answered with a non-2xx status, a redirect included. |
EventAlreadyConsumedException |
An ApiException for 409 event_already_consumed: the event was already consumed, at getConsumedAt(). |
TimeoutException |
The request deadline elapsed. |
ConnectionException |
The API could not be reached, the connection failed mid-response, or the response body was over 4 MiB. |
ApiException carries getStatus(), and optional getErrorCode(),
getDetails(), getRequestId() and getRetryAfter(), the seconds the API's
Retry-After asked you to wait (null when it sent none). The secret key is
stripped from all of them, and the response body is never echoed into a
message. getCode() is the HTTP status too, so a handler that only logs the
code still logs something useful. Reads never retry on their own; after a
429 ($e->isRateLimited()), wait getRetryAfter() seconds before your own
retry.
A read answers 404 with one of two codes, each with its own predicate:
| Predicate | Code | Meaning |
|---|---|---|
$e->isPending() |
event_pending |
The request id was accepted and the event is still being recorded. Nothing is decided yet: read again after getRetryAfter() seconds (the API sends Retry-After: 2), or verify asynchronously. Do not treat it as fraud. |
$e->isEventNotFound() |
event_not_found |
The request id was never issued, or the event is past retention. |
try { $event = $fingerly->events->get($requestId); } catch (\Fingerly\ApiException $e) { if ($e->isPending()) { // Not decided yet: read again after $e->getRetryAfter() seconds. } elseif ($e->isEventNotFound()) { // Never issued, or past retention. } else { throw $e; } }
Deadlines and connections
timeout bounds the whole exchange, including receiving the body, so a server
that answers and then stalls, or sends a byte at a time, times out like one
that never answered. It defaults to 5 seconds, for reads and for the proxy.
cURL's CURLOPT_TIMEOUT_MS covers the transfer end to end. A response body
over 4 MiB is refused rather than buffered.
A client or proxy keeps one cURL handle and reuses its connection, so a long-running worker (Octane, FrankenPHP, RoadRunner) opens one connection to Fingerly and keeps it. On PHP 8.5 and later the connection, DNS and TLS session caches are also shared across the requests a PHP-FPM worker serves, so a client built per request reuses them too. On PHP 8.2 to 8.4 under PHP-FPM each request that builds a new client opens a new connection; at a few hundred proxied requests a second per host, run PHP 8.5 or a worker runtime. No cookies are kept, and redirects are never followed.
Apple DeviceCheck bits
For an iOS identification whose App Attest evidence carried a DeviceCheck token, Fingerly holds the token for one hour, and your backend spends it once to read or to write the device's two Apple DeviceCheck bits. The bits mean what you decide; Fingerly never reads them.
Apple treats each token as single-use, so one identification pays for one call: a read or a write, never both. A "check, then mark" flow such as a once-per-device free trial therefore spends two identifications:
- Query on the identification that asks for the trial. If the bits say the device already had one, refuse it.
- Otherwise record the grant in your own data, then write the bit on the next identification from that install. Until the write lands, your own record is what stops a second trial.
// 1. The identification that asks for the trial. try { $bits = $fingerly->deviceCheck->query($requestId); $usedOnDevice = $bits->found && $bits->bit0; } catch (\Fingerly\ApiException $e) { if (!$e->isDeviceCheckNotHeld() && !$e->isDeviceCheckSpent()) { throw $e; } $usedOnDevice = false; // no answer, not a verdict } // 2. The next identification, once the trial is granted in your own data. $fingerly->deviceCheck->write($nextRequestId, ['bit0' => true]);
A bit left out of a write keeps its value; a write must name bit0, bit1 or
both, or it throws ConfigurationException before anything is sent.
A 503 device_check_unavailable, a timeout or a connection failure keeps the
token, and the SDK sends the identical request again, twice at most. Nothing
else is retried. Apple allows a token to be retried only for the same request,
so if you retry yourself, repeat the same call with the same bits: another
operation or other bits on that event answer 409 device_check_spent.
ApiException tells the answers apart: isDeviceCheckNotHeld() (404),
isDeviceCheckSpent(), isDeviceCheckBusy() and isCredentialUnavailable()
(409), isBitsRequired() and isAppleRejected() (422, with Apple's status
in getAppleStatus()), and isDeviceCheckUnavailable() (503). Apple asks
that DeviceCheck is never the only fraud check, and that users have a way to
have the bits reset.
Verify webhooks
The call is in Getting started. Verify the exact raw bytes before decoding them: re-serialising them changes the digest.
| Behaviour | Detail |
|---|---|
| What a signature covers | the timestamp and the body |
| Replay tolerance | five minutes by default, changed with the tolerance argument |
| Secret rotation | any matching signature in the comma-separated header is accepted |
| Malformed or missing input | a false result, never an exception |
| Deduplication | verification proves authenticity and freshness only; persist processed WebhookEvent::$id values as well |
| Bad payload | Webhook::parse() throws WebhookException, which names the field at fault and never its value |
Webhook::parse() decodes the envelope every delivery shares and leaves $data
an array, so a new event type needs no upgrade. Dispatch on $event->type with
\Fingerly\WebhookEventType:
use Fingerly\WebhookEventType; match ($event->type) { WebhookEventType::VISITOR_SUSPECT => ReviewVisitor::dispatch($event->data['request_id']), // high level only WebhookEventType::IDENTIFICATION_COMPLETED, WebhookEventType::IDENTIFICATION_REFUSED => RecordIdentification::dispatch($event->id), WebhookEventType::WEBHOOK_TEST => null, // sent to one endpoint on request; nobody subscribes to it default => null, // BILLING_STATUS_CHANGED, USAGE_DAILY_SETTLED, or a type added later };
The other types are BILLING_STATUS_CHANGED (billing.status_changed) and
USAGE_DAILY_SETTLED (usage.daily_settled). identification.completed and
visitor.suspect carry $data['project_id']; identification.refused carries
it only when the refused request named a known key.
Webhook verification touches neither the network nor ext-curl, so a receiver that does nothing else pulls in nothing else.
First-party proxy (same-origin)
Content blockers refuse browser requests to third-party APIs, and a refused
identification is a visitor never identified. Serving the browser SDK from a
path on your own site makes those requests first-party. Create a proxy in the
dashboard (Integration > Proxy keys) and mount the proxy at the path it
issued, here /k7x2qm4a. The proxy key is what lets that hop declare the
visitor's real address, origin and user agent; a public key alone never can, so
nobody can spoof them.
$proxy = new \Fingerly\Proxy([ 'proxy_key' => getenv('FINGERLY_PROXY_KEY'), 'path' => '/k7x2qm4a', // Your CDN's visitor header when present, otherwise the TCP peer. 'client_ip' => fn (\Fingerly\Proxy\ProxyRequest $r) => $r->header('cf-connecting-ip') ?: (string) $r->remoteAddress, ]);
PHP has three live server request shapes, so there are three adapters over one
core. Build the Proxy once per process and share it: it holds no per-request
state, and sharing it is what lets its connection be reused.
| Framework | Adapter | Install |
|---|---|---|
| Slim, Mezzio, anything PSR-15 | \Fingerly\Proxy\Psr15Middleware |
psr/http-server-middleware |
| Laravel | \Fingerly\Proxy\LaravelMiddleware |
illuminate/http |
| Symfony | \Fingerly\Proxy\SymfonyListener |
symfony/http-kernel |
| Anything else | $proxy->handle() |
nothing |
Every adapter shares the same Proxy and the same client_ip rule below. Pick
yours:
Slim, Mezzio, anything PSR-15
$app = \Slim\Factory\AppFactory::create(); // ... your routes and other middleware ... // Added last, so it runs first. $app->add(new \Fingerly\Proxy\Psr15Middleware($proxy, $app->getResponseFactory()));
Laravel
The middleware receives the Proxy from the container, which cannot build it
on its own (client_ip is a callable), so bind it once. Without the binding
every request to the application fails with a BindingResolutionException.
// config/services.php 'fingerly' => [ 'proxy_key' => env('FINGERLY_PROXY_KEY'), 'proxy_path' => env('FINGERLY_PROXY_PATH'), 'secret_key' => env('FINGERLY_SECRET_KEY'), ],
// app/Providers/AppServiceProvider.php, in register() $this->app->singleton(\Fingerly\Proxy::class, fn () => new \Fingerly\Proxy([ 'proxy_key' => config('services.fingerly.proxy_key'), 'path' => config('services.fingerly.proxy_path'), 'client_ip' => fn (\Fingerly\Proxy\ProxyRequest $r) => $r->header('cf-connecting-ip') ?: (string) $r->remoteAddress, 'on_error' => fn (string $line) => \Illuminate\Support\Facades\Log::warning($line), ])); $this->app->singleton(\Fingerly\Client::class, fn () => new \Fingerly\Client( config('services.fingerly.secret_key'), ));
// bootstrap/app.php (Laravel 11 and later) ->withMiddleware(function (\Illuminate\Foundation\Configuration\Middleware $middleware): void { $middleware->append(\Fingerly\Proxy\LaravelMiddleware::class); }) // app/Http/Kernel.php (Laravel 10): add it to $middleware \Fingerly\Proxy\LaravelMiddleware::class,
Under Octane, also add both classes to warm in config/octane.php. Octane
gives every request a fresh copy of the container, so a singleton that is not
warmed is built again on each request, with a new cURL handle, and on PHP 8.2
to 8.4 a new connection to Fingerly per proxied request:
// config/octane.php 'warm' => [ ...Octane::defaultServicesToWarm(), \Fingerly\Proxy::class, \Fingerly\Client::class, ],
Laravel reads and decodes a JSON body when it builds the request, before any
middleware runs, so under Laravel the 1 MiB limit refuses an oversized body but
cannot stop it being read into memory first. Cap the body size in the web
server as well: client_max_body_size in nginx, request_body { max_size } in
Caddy and FrankenPHP.
Symfony
The listener runs before the router. Define the Proxy as a service, with an
invokable class for client_ip, because a closure cannot be written in YAML.
With the skeleton's autoconfigure: true, the listener is registered as an
event subscriber on its own.
# config/services.yaml, below the skeleton's _defaults and App\ entries fingerly.proxy: class: Fingerly\Proxy arguments: - proxy_key: '%env(FINGERLY_PROXY_KEY)%' path: '%env(FINGERLY_PROXY_PATH)%' client_ip: ['@App\Fingerly\ClientIp', '__invoke'] on_error: ['@logger', 'warning'] Fingerly\Proxy\SymfonyListener: arguments: ['@fingerly.proxy'] Fingerly\Client: arguments: ['%env(FINGERLY_SECRET_KEY)%']
// src/Fingerly/ClientIp.php namespace App\Fingerly; use Fingerly\Proxy\ProxyRequest; final class ClientIp { public function __invoke(ProxyRequest $request): string { return $request->header('cf-connecting-ip') ?: (string) $request->remoteAddress; } }
Any other framework
The adapters are conveniences; handle() is the interface. Phalcon,
CodeIgniter, CakePHP, Yii, a queue worker or a bare index.php all need about
ten lines:
// Phalcon $response = $proxy->handle(new \Fingerly\Proxy\ProxyRequest( method: $this->request->getMethod(), path: $this->request->getURI(true), headers: $this->request->getHeaders(), body: $this->request->getRawBody(), remoteAddress: $this->request->getClientAddress(), )); // or, with no framework at all $proxy->handle(\Fingerly\Proxy\ProxyRequest::fromGlobals())->send();
fromGlobals() reads $_SERVER and php://input, so it is for PHP-FPM, CGI
and the built-in server only. In a long-running worker those globals belong to
the worker, not the request: build the ProxyRequest from the runtime's own
request object instead, and let client_ip read remoteAddress rather than
$_SERVER['REMOTE_ADDR'].
Then point the browser SDK at the same path:
const fingerly = await load({ apiKey: 'fly_pk_…', endpoints: '/k7x2qm4a' })
Client SDKs post a single identification envelope to exactly that path, with nothing appended.
client_ipis the one thing you must get right. Resolve it from a header your own infrastructure sets, such as your load balancer's or CDN's, and fall back on$r->remoteAddress, the TCP peer the adapter passes in. Only trust that header when traffic can reach your server through that CDN or load balancer alone; otherwise a visitor can send it themselves. Never read the left-mostX-Forwarded-Forvalue: the visitor writes it.The callback must return exactly one IPv4 or IPv6 address. Anything else (null, an empty string, a list, a port, padding) is a configuration error: nothing is forwarded, the browser gets
500with "The client IP callback returned no valid address", and the first occurrence in the process is reported throughon_error(orerror_log()without one).
Event loops and worker sizing
The proxy and the client are synchronous: each call holds the calling thread
for up to timeout while Fingerly answers. That is right for PHP-FPM, Octane,
FrankenPHP and RoadRunner, where a worker serves one request at a time. Never
call them from an event loop (ReactPHP, AMPHP, Revolt, or Swoole and
OpenSwoole coroutines): one slow answer would stall every request that loop is
serving. Hand the call to a worker process or a thread pool instead.
Size the worker pool for the slow case, not the average one: while Fingerly is
slow, every proxied request holds its worker for the whole timeout. At 100
proxied requests a second with 1% of them running into a 5 second timeout, that
is 5 workers busy on average, before any fast request is served. Run more
workers than that, or lower timeout for the proxy.
$proxy->handles($request) answers whether a request is the one the proxy
owns, so everything else goes to your application untouched rather than getting
a 404 of ours. $proxy->maxBodyBytes() is there so glue code can read no
further than the limit.
The path
path is optional in the core. Given one, the proxy answers that path and
nothing else, matched byte for byte: /k7x2qm4a/admin, /k7x2qm4a/,
//k7x2qm4a, /k7x2qm4a/., /k7x2qm4a%2F and /K7X2QM4A are not the
proxy's. A query string is ignored. Left out, it answers whatever your
framework routed to it, which suits a route that already names the path. It
must be slash-separated segments of letters, digits and -._~, with no
trailing slash and no . or .. segment; anything else is a
ConfigurationException.
The three adapters see every request, so each one refuses a Proxy without a
path rather than answer them all, and there is no default to fall back on.
The path is matched against the application-relative path: getPathInfo()
under Laravel and Symfony, and the PSR-7 URI path under PSR-15. It is never the
whole request URI, because a deployment under a sub-URI carries a prefix the
configuration knows nothing about, and a spelled-out front controller such as
/index.php/k7x2qm4a is not the path. Add the PSR-15 middleware to the whole
application or to that one route, not under a path your router strips.
Use the path the dashboard issued. Blockers look for words such as
fingerprint, tracking, analytics, collect, identify and fingerly.
What the proxy does
| Rule | Behaviour |
|---|---|
| Methods and paths | It forwards only POST (plus OPTIONS when allowed_origins is configured), matched exactly: any other method, post included, gets 405, and a path that is not the proxy's (including /supplement subpaths) gets 404 first. |
| Upstream | Every accepted request goes verbatim as raw bytes to one URL, https://api.fingerly.io/api/v1/ingest. api_version changes the version in that URL and nothing else, and upstream its origin. |
| Upstream origin | upstream must be a bare HTTPS origin, https://host or https://host:port, with no credentials, path, query, fragment, space or control character. Plain HTTP is accepted only for 127.0.0.1, localhost or [::1], and only with 'allow_insecure_loopback' => true, for a local test harness. The proxy key travels with every forwarded request, so anything else is refused when the Proxy is constructed. |
| Event reads | Need a secret key and stay unreachable from a browser by construction. |
| Public key | The caller must present a public key from the same environment as the proxy key, or the request gets 401. |
| Origin or platform | Requests without either Origin or a validated native X-Fingerly-SDK-Platform header (ios, android, react-native, react-native-ios, react-native-android, flutter, flutter-ios, flutter-android, lynx-ios, lynx-android, capacitor, kotlin-multiplatform) are rejected locally with 400 (missing_origin), and x-fingerly-origin is never synthesized from Host, Referer or the request URL. |
| Body size | Bodies over 1 MiB get 413. |
| Deadline | One 5 second deadline covers the whole exchange, so an upstream that never answers, or answers a byte at a time, gets 504 Gateway timeout rather than holding the browser's connection open. |
| Upstream failures | An upstream that cannot be reached, drops the connection, answers a redirect or a status outside 200 to 599, or answers a success that is not JSON gets 502 Bad gateway; a redirect is never followed and its Location never relayed. |
| Error answers | 504 and 502 are short text/plain answers marked no-store, and the proxy never throws, so the framework never renders its own error page in their place. |
| Forwarded upstream | All incoming x-fingerly-*, cookie and authorization headers are stripped. x-fingerly-host, idempotency-key, sec-fetch-* and sec-ch-ua-* are forwarded, and one channel header: x-fingerly-origin when the request has an Origin, otherwise the validated x-fingerly-sdk-platform. A request with both is a browser request, as it is when sent to the API directly. |
| Proxy identity | The proxy reports itself upstream as php/0.4.1, which the dashboard shows per proxy. |
| Relayed back | Only Content-Type, X-Request-Id, RateLimit-Limit, RateLimit-Remaining and Retry-After, plus Cache-Control: no-store set by the proxy. It is an allowlist, so nothing on the response names Fingerly, whatever the API adds in future. |
| Laravel and Symfony | The relayed Cache-Control: no-store arrives as no-store, private, because ResponseHeaderBag appends a visibility directive to any Cache-Control without one. That is a narrowing rather than a weakening, so it is left alone. |
Pass on_error to hear about 504 and 502 answers, one line each. A line
names the kind of failure (connect, dns, tls, ...), never the upstream
host, the URL or a key:
'on_error' => fn (string $line) => \Illuminate\Support\Facades\Log::warning($line),
Requirements
- PHP 8.2 or newer, and nothing outside
ext-curlandext-json. - Run a PHP release that has the October 2026 security fixes for CVE-2026-109618 and CVE-2026-109619: 8.5.12, 8.4.27, 8.3.36, 8.2.35 or later. Those flaws are in PHP itself and let an unauthenticated request run code on the server, so an unpatched runtime puts everything on it at risk, this SDK's secret key included.
- CI runs PHP 8.2, 8.3, 8.4 and 8.5, and tests the adapters against Laravel 10 to 13 and Symfony 6.4 to 8.
Development and release preparation
Commands, tests, source structure
composer install composer test # phpunit composer stan # phpstan, level 8, checked against the 8.2 floor composer fmt:check # php-cs-fixer composer contract:sync # refresh the vendored contract snapshot
The tests drive PHP's own built-in server on a real socket rather than a stub
of the transport, and the three adapters are exercised against the real
Laravel, Symfony and PSR-7 types they exist for. The vendored synthetic
contract snapshot in contract/ makes them independent of sibling
repositories; to update it from the integration workspace, set
FINGERLY_CONTRACT_DIR to its contract directory. The snapshot's hashes are
checked by composer test, so there is no separate check step. Never put
production secrets in fixtures.
Source structure
Client.php holds the client and its options. Transport.php performs one
HTTP exchange over a reused cURL handle or a supplied PSR-18 client, caps the
response body, and maps failures to ApiException. Secret.php holds a key
so that no dump or serialisation can show it. Events.php owns the event reads, the list filters, verification and
consumption, decoding into EventVerification.php and EventConsumption.php
and throwing EventAlreadyConsumedException.php, and DeviceCheck.php
the DeviceCheck reads and writes, decoding into DeviceCheckBits.php and
DeviceCheckWrite.php;
Event.php, EventPage.php, EventTrigger.php and
WebhookEvent.php are what they decode into, and Signal.php,
SuspectLevel.php and the other constant classes name the closed string sets
their fields hold. Json.php reads those
bodies without trusting their shape. Webhook.php verifies signatures and
needs nothing else in the package; WebhookException.php is what parse()
throws for a payload it cannot read. Proxy.php is the same-origin core, with
Proxy/ holding its request and response types and the three adapters.
Config.php validates every caller-supplied option: keys, origins, API
versions, the proxy path, durations and sizes, all before any network access.
Documentation
Help
Open an issue on this repository, or write to support@fingerly.io. Report security issues to security@fingerly.io.
Licence
Apache-2.0. See LICENSE.
