fingerly 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3c77b9ed11a4ea1bb5bf81b5de416a0a2943e32ee9be806b4e531db1d5d64c0b
4
- data.tar.gz: 0e3b9e16f45b9e4c84efcfbc81d50131fdf925f0f5293b64ee0a6246c7f08479
3
+ metadata.gz: b88a73350975aa92bb9841d3fc4f69bb56a57cbe2ac47355e9dfb756cbb39f64
4
+ data.tar.gz: 587553cf25659f1de108734cd561fc76250ec1e18d6fbe20f76c443bec790953
5
5
  SHA512:
6
- metadata.gz: ede4c294f90137cf3c068cdea18e18a391de904d72f02eefc9f6b7ef46d4c9d83539e6c77fdbb3701e20217deeb606c35edc5c25638085741bdbb10a0e906a7f
7
- data.tar.gz: cc1e8ba7c18c8c0d24b0124483a03faeb4b47df20cf1f83ac4b65d5ea7aa91af1d464e3519ab678c9a463d285ee06801d66db261e69ddc7d3397f1f282e401e6
6
+ metadata.gz: 4ceef7c71db61e96650a64bb01068886cd53af092601003d38eba787fc74a38af3ba7916440600b6de8cca7eee3917777a44e23a2449c48503d3a21bc0993bea
7
+ data.tar.gz: 7427d309f6de7e37c479958cf7ca72568dc0998816a905838a58a81d9113ad11218c1c5f320800fda3b9d15a3c1f325225d5b014e1d8beb49208fcd57f3668fb
data/README.md CHANGED
@@ -36,7 +36,7 @@ device behind each session and scores how suspicious it is.
36
36
  2. **Install.** Add it to your `Gemfile`:
37
37
 
38
38
  ```ruby
39
- gem "fingerly", "~> 0.4.1"
39
+ gem "fingerly", "~> 0.5.0"
40
40
  ```
41
41
 
42
42
  3. **Read an event.**
@@ -91,8 +91,9 @@ Full guide: [docs.fingerly.io/docs/sdks/ruby](https://docs.fingerly.io/docs/sdks
91
91
  | Read or write an iOS device's DeviceCheck bits | `device_check.query` / `device_check.write` | [DeviceCheck bits](#devicecheck-bits) |
92
92
  | Check a webhook delivery is genuine | `Fingerly::Webhooks.verify` and `.parse` | [Verify webhooks](#verify-webhooks) |
93
93
  | Keep the browser SDK first-party, away from content blockers | `Fingerly::Proxy`, a Rack middleware | [First-party proxy](#first-party-proxy-same-origin) |
94
+ | See AI crawlers that never run your pages' JavaScript, and tell them apart | `Fingerly::AgentSightings` and its Rack middleware | [Agent sightings](#agent-sightings) |
94
95
 
95
- On this page: [Read events](#read-events) · [DeviceCheck bits](#devicecheck-bits) · [Verify webhooks](#verify-webhooks) · [First-party proxy](#first-party-proxy-same-origin) · [Threads, fibers and deadlines](#threads-fibers-and-deadlines) · [Requirements](#requirements) · [Development](#development-and-release-preparation) · [Documentation](#documentation) · [Help](#help) · [Licence](#licence)
96
+ On this page: [Read events](#read-events) · [DeviceCheck bits](#devicecheck-bits) · [Verify webhooks](#verify-webhooks) · [First-party proxy](#first-party-proxy-same-origin) · [Agent sightings](#agent-sightings) · [Threads, fibers and deadlines](#threads-fibers-and-deadlines) · [Requirements](#requirements) · [Development](#development-and-release-preparation) · [Documentation](#documentation) · [Help](#help) · [Licence](#licence)
96
97
 
97
98
  ## Read events
98
99
 
@@ -128,6 +129,33 @@ adds later is reachable without a gem upgrade.
128
129
  belongs to, on both `events.get` and `events.list` rows; it is `nil` when an
129
130
  older server does not send it.
130
131
 
132
+ `event.ai` is set only when `event.visitor_kind` is
133
+ `Fingerly::VisitorKind::AI_BOT`, and `nil` otherwise: a `Fingerly::AiAgent`
134
+ with the agent's `name`, `provider`, `purpose`, `runtime`, `declared?` and
135
+ `verification` (`method`, `result`). The agent is named by a Web Bot Auth
136
+ signature when the request carried one, otherwise by its user agent.
137
+ `verification` says how far that was checked:
138
+ `Fingerly::AiVerificationMethod::SIGNATURE` (the operator's published key
139
+ signed the request) or `Fingerly::AiVerificationMethod::IP_LIST` (the address
140
+ is inside the operator's published ranges), with result
141
+ `Fingerly::AiVerificationResult::PASS`, `Fingerly::AiVerificationResult::FAIL`
142
+ (the name was borrowed), or `Fingerly::AiVerificationResult::NOT_ATTEMPTED`
143
+ with method `Fingerly::AiVerificationMethod::NONE` (the operator publishes
144
+ nothing to check against, or it could not be checked; the name is then only
145
+ the client's claim). Every field of `event.ai` is always set, `verification`
146
+ included, so `event.ai.verification.result` needs no nil check once
147
+ `event.ai` is there; an answer whose `ai` lacks one raises `Fingerly::Error`
148
+ when it is read. Only clients that run the Fingerly SDK produce events, so
149
+ crawlers that do not run JavaScript never appear. `events.list` filters on `kind:`,
150
+ `ai_provider:` (exact and case-sensitive, such as `"OpenAI"`) and `ai_purpose:`.
151
+
152
+ ```ruby
153
+ fetches = fingerly.events.list(
154
+ kind: Fingerly::VisitorKind::AI_BOT,
155
+ ai_purpose: Fingerly::AiPurpose::USER_FETCH
156
+ )
157
+ ```
158
+
131
159
  ### Read an event you just identified
132
160
 
133
161
  An event is usually readable as soon as identification answers. If it is
@@ -176,7 +204,11 @@ missing from the module's frozen `ALL` array.
176
204
  | `Fingerly::Platform` | `Event#platform` | `WEB`, `ANDROID`, `IOS` |
177
205
  | `Fingerly::AnonymityNetwork` | `Event#anonymity_network` | `TOR`, `RELAY`, `VPN`, `PROXY`, `HOSTING` |
178
206
  | `Fingerly::DeviceKind` | `Event#device_kind` | `DESKTOP`, `MOBILE`, `TABLET`, `SERVER` |
179
- | `Fingerly::VisitorKind` | `Event#visitor_kind` | `HUMAN`, `AI_BOT`, `AUTOMATION`, `SEARCH_CRAWLER` |
207
+ | `Fingerly::VisitorKind` | `Event#visitor_kind`, `events.list(kind:)`, `AgentSighting#visitor_kind` | `HUMAN`, `AI_BOT`, `AUTOMATION`, `SEARCH_CRAWLER`, and `UNKNOWN` (only in an agent sightings answer: a request the server could not use) |
208
+ | `Fingerly::AiPurpose` | `AiAgent#purpose`, `events.list(ai_purpose:)` | `TRAINING`, `SEARCH`, `USER_FETCH`, `AGENT` |
209
+ | `Fingerly::AiRuntime` | `AiAgent#runtime` | `PROVIDER_CLOUD`, `HOSTED_BROWSER`, `USER_DEVICE` |
210
+ | `Fingerly::AiVerificationMethod` | `AiVerification#method` | `SIGNATURE`, `IP_LIST`, `REVERSE_DNS`, `NONE` |
211
+ | `Fingerly::AiVerificationResult` | `AiVerification#result` | `PASS`, `FAIL`, `NOT_ATTEMPTED` |
180
212
  | `Fingerly::AttestationState` | `event.document["attestation"]["state"]` | `ATTESTED`, `NOT_ATTESTED`, `FAILED` |
181
213
  | `Fingerly::AttestationStatus` | `event.document["attestation"]["status"]` | `VERIFIED`, `INDETERMINATE`, `INVALID`, `ABSENT`, `UNCONFIGURED` |
182
214
  | `Fingerly::AttestSkippedReason` | `event.document["attestation"]["attest_skipped"]` | `NOT_OFFERED`, `UNSUPPORTED`, `CHALLENGE_UNAVAILABLE`, `KEY_ERROR`, `TIMEOUT`, `BACKOFF`, `INSTALL_UNAVAILABLE` |
@@ -303,8 +335,9 @@ visitor's cookies and authorization header the same way.
303
335
 
304
336
  On iOS, Apple keeps two DeviceCheck bits per device for your developer team,
305
337
  and they survive a reinstall. When DeviceCheck is on for the project's Apple
306
- key, Fingerly holds the DeviceCheck token that came with an identification for
307
- one hour, and your backend spends it once:
338
+ key, Fingerly holds the two DeviceCheck tokens that came with an
339
+ identification for one hour, a read token and a write token, and your backend
340
+ spends each once:
308
341
 
309
342
  ```ruby
310
343
  bits = fingerly.device_check.query(request_id) # Fingerly::DeviceCheckBits
@@ -316,16 +349,16 @@ written = fingerly.device_check.write(request_id, bit0: true) # Fingerly::Device
316
349
  written.bit0 # true; a bit left out is nil, and keeps its value at Apple
317
350
  ```
318
351
 
319
- Apple treats each DeviceCheck token as single-use, so one event pays for one
320
- call: a read or a write, never both. A flow that checks and then marks a
321
- device, such as a once-per-device free trial, takes two identifications:
352
+ Apple treats each DeviceCheck token as single-use, so one event supports one
353
+ read and one write: a read spends the read token, a write the write token,
354
+ and each pays for one Apple call. A flow that checks and then marks a device,
355
+ such as a once-per-device free trial, does both on the identification that
356
+ asks for the trial:
322
357
 
323
- 1. Query on the identification that asks for the trial. If the bits say the
324
- device already had one, refuse it.
358
+ 1. Query the bits. If they say the device already had one, refuse it.
325
359
  2. Otherwise grant the trial and record the grant in your own data.
326
- 3. Write the bit on the next identification from that install, such as one
327
- the app makes right after the grant. Until the write lands, your own record
328
- of the grant is what stops a second trial.
360
+ 3. Write the bit with the same request ID. Until the write lands, your own
361
+ record of the grant is what stops a second trial.
329
362
 
330
363
  ```ruby
331
364
  # bit0 means "this device has had a free trial". The meaning is yours.
@@ -340,6 +373,7 @@ def start_trial(fingerly, account, request_id)
340
373
  return "offer-paid-plan" if bits&.bit0
341
374
 
342
375
  Trial.grant(account, device_marked: false)
376
+ mark_trial(fingerly, account, request_id)
343
377
  "granted"
344
378
  end
345
379
 
@@ -348,7 +382,8 @@ def mark_trial(fingerly, account, request_id)
348
382
  Trial.update(account, device_marked: true)
349
383
  rescue Fingerly::DeviceCheckError => e
350
384
  raise unless e.not_held? || e.spent?
351
- # Keep device_marked false and write at the install's next identification.
385
+ # Keep device_marked false and write at a later identification from that
386
+ # install.
352
387
  end
353
388
  ```
354
389
 
@@ -371,8 +406,8 @@ anything is sent.
371
406
  The token may be retried only with the same request. After a `503` or a
372
407
  transport failure the token is kept, so the client sends the identical request
373
408
  again, up to three attempts in all; it retries nothing else. If you retry
374
- later yourself, repeat the same call with the same bits: a read after a failed
375
- write, or a write with other bits, answers `409 device_check_spent`. Apple asks
409
+ later yourself, repeat the same call with the same bits: a second read, or a
410
+ write with other bits, answers `409 device_check_spent`. Apple asks
376
411
  that DeviceCheck is never the only fraud check, and that users have a way to
377
412
  have the bits reset.
378
413
 
@@ -497,8 +532,8 @@ then sees a path that is not its own and answers `404`.
497
532
  | Credentials upstream | Every request carries the proxy key as `X-Fingerly-Proxy-Key` and the caller's public key as `X-API-Key`, never a secret key. |
498
533
  | 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. A request is forwarded on one channel only: with an `Origin` the proxy sends `x-fingerly-origin` and drops the platform header, and without one it sends the validated platform. |
499
534
  | Body size | Bodies over 1 MiB get `413`, enforced while reading rather than after buffering. |
500
- | Forwarded headers | All incoming `x-fingerly-*`, `cookie` and `authorization` headers are stripped, restoring only a validated `x-fingerly-sdk-platform` (when there is no `Origin`) alongside `x-fingerly-host`, `idempotency-key`, `sec-fetch-*` and `sec-ch-ua-*`. |
501
- | Proxy identity | The proxy reports itself upstream as `ruby/0.4.1` in `x-fingerly-proxy-version`, which the dashboard shows per proxy. |
535
+ | Forwarded headers | All incoming `x-fingerly-*`, `cookie` and `authorization` headers are stripped, restoring only a validated `x-fingerly-sdk-platform` (when there is no `Origin`) alongside `x-fingerly-host`, `idempotency-key`, `sec-fetch-*`, `sec-ch-ua-*` and the Web Bot Auth `signature`, `signature-input` and `signature-agent` (each dropped when over 4096 bytes). |
536
+ | Proxy identity | The proxy reports itself upstream as `ruby/0.5.0` in `x-fingerly-proxy-version`, which the dashboard shows per proxy. |
502
537
  | Fingerly unreachable | The visitor gets a gateway error rather than your application's `500`. |
503
538
  | Deadline passes | `504 Gateway timeout` when `timeout:` (5 seconds by default) passes. |
504
539
  | Any other upstream failure | `502 Bad gateway`, whether the connection was refused or reset, the name did not resolve, or the answer was malformed, cut short or over 4 MiB. Redirects are never followed, and an upstream redirect or a status outside `200` to `599` is answered `502` as well. |
@@ -537,6 +572,150 @@ dashboard issued rather than inventing one: blockers look for words such as
537
572
 
538
573
  </details>
539
574
 
575
+ ## Agent sightings
576
+
577
+ Most AI crawlers and fetchers, such as GPTBot or ClaudeBot, read your pages
578
+ without running their JavaScript, so the browser SDK never sees them.
579
+ `Fingerly::AgentSightings` reports the requests your server served to
580
+ Fingerly, which answers what sent each one: a person's browser, an AI agent,
581
+ other automation or a search crawler. The requests are then counted in the
582
+ dashboard, and your code can ask for the answer.
583
+
584
+ The SDK forwards raw input and remembers the answers; it never judges a user
585
+ agent or an address itself. An AI agent's identity starts from what the
586
+ request claims, and `answer.ai.verification` says how far that claim was
587
+ checked: `PASS` means the operator's key or published ranges confirmed it,
588
+ `FAIL` means the name was borrowed, and `NOT_ATTEMPTED` leaves it the
589
+ client's claim.
590
+
591
+ Build one per process at start-up with a secret key and the same kind of
592
+ `client_ip` callback the [proxy](#first-party-proxy-same-origin) takes, then
593
+ mount its middleware first in the stack, so it also sees `/robots.txt` and the
594
+ other files your server answers itself:
595
+
596
+ ```ruby
597
+ # config/initializers/fingerly.rb
598
+ FINGERLY_SIGHTINGS = Fingerly::AgentSightings.new(
599
+ secret_key: ENV.fetch("FINGERLY_SECRET_KEY"),
600
+ client_ip: ->(request) { request.header("CF-Connecting-IP") || request.peer_host }
601
+ )
602
+
603
+ Rails.application.config.middleware.insert_before 0,
604
+ Fingerly::AgentSightings::Middleware,
605
+ FINGERLY_SIGHTINGS
606
+ ```
607
+
608
+ ```ruby
609
+ # config.ru, for Sinatra, Hanami or a bare Rack app
610
+ require "fingerly"
611
+ require_relative "app" # defines MyApp, your Sinatra or Rack application
612
+
613
+ SIGHTINGS = Fingerly::AgentSightings.new(
614
+ secret_key: ENV.fetch("FINGERLY_SECRET_KEY"),
615
+ client_ip: ->(request) { request.header("CF-Connecting-IP") || request.peer_host }
616
+ )
617
+
618
+ use Fingerly::AgentSightings::Middleware, SIGHTINGS
619
+ run MyApp
620
+ ```
621
+
622
+ `lookup` answers from memory what the server said about this exact request
623
+ before, and `Fingerly::AgentSightings::UNKNOWN` when it has not said anything
624
+ yet. It never waits on the network and never raises. Treat `UNKNOWN` as
625
+ "serve as usual":
626
+
627
+ ```ruby
628
+ class ArticlesController < ApplicationController
629
+ def show
630
+ @article = Article.find(params[:id])
631
+ answer = FINGERLY_SIGHTINGS.lookup(request)
632
+ return if answer == Fingerly::AgentSightings::UNKNOWN
633
+
634
+ # Your policy: here, a crawler collecting training data gets the summary.
635
+ @summary_only = answer.visitor_kind == Fingerly::VisitorKind::AI_BOT &&
636
+ answer.ai&.purpose == Fingerly::AiPurpose::TRAINING
637
+ end
638
+ end
639
+ ```
640
+
641
+ An answer is an `AgentSighting` with `visitor_kind` (see `VisitorKind`),
642
+ `agent` (such as `GPTBot` or `Googlebot`, when the server knows it) and, for
643
+ an AI agent, `ai` with `name`, `provider`, `purpose` (`AiPurpose`), `runtime`
644
+ (`AiRuntime`) and `verification` (`AiVerificationMethod`,
645
+ `AiVerificationResult`). The first request from a new visitor is answered
646
+ `UNKNOWN`: the server is asked after the response, and later requests get its
647
+ answer.
648
+
649
+ ### What is reported
650
+
651
+ By default the middleware reports every response with a `Content-Type` of
652
+ `text/html` or `application/xhtml+xml`, and every request for `/robots.txt`,
653
+ `/llms.txt` and `/llms-full.txt`, whatever the status. Static assets, API
654
+ routes and health checks are left out. What is reported is decided by your
655
+ own response and path, never by the visitor's user agent, address or headers.
656
+
657
+ ```ruby
658
+ use Fingerly::AgentSightings::Middleware, SIGHTINGS,
659
+ content_types: %w[text/html application/xhtml+xml text/markdown], # replaces the default
660
+ include_path_prefixes: ["/feed"], # reported whatever their content type
661
+ exclude_path_prefixes: ["/admin"] # never reported; wins over everything
662
+ ```
663
+
664
+ Paths are matched against `PATH_INFO`, as the proxy does. The middleware
665
+ reports after your application answered, in memory, so it never delays a
666
+ response, and nothing it does can fail one. A framework that does not run
667
+ Rack middleware can call `SIGHTINGS.report(env)` itself after its response.
668
+
669
+ | Sent for each request | Never sent, never logged |
670
+ | --- | --- |
671
+ | `User-Agent` as received (a value over 4096 bytes is not reported at all, and stays `UNKNOWN`), the address `client_ip` returned (a request without one is not reported), `Host` (left out when over 4096 bytes), the method (a request whose method is over 4096 bytes is not reported), the Web Bot Auth `Signature`, `Signature-Input` and `Signature-Agent` headers (each left out when over 4096 bytes), and how many times the same request was seen since the last report, at most 1,000,000. Values go as UTF-8, an invalid byte sequence as U+FFFD, and the limits count the bytes sent | The path, the query string, cookies, `Authorization`, any other header, the request body and your response |
672
+
673
+ ### Memory, flushing and failures
674
+
675
+ | Rule | Behaviour |
676
+ | --- | --- |
677
+ | Answers remembered | At most `capacity:` (4096 by default; a larger value than 65536 is read as 65536), least recently used dropped first. A few hundred bytes each: about 1.5 MB at the default. Each expires after the `ttl` the server gave it; a signed request is never remembered, and a new `rules_version` drops them all. |
678
+ | Pending reports | At most 1000, the batch being sent included. Repeats of one request fold into one item with a count, signed requests excepted. When full, a new request is not reported and stays `UNKNOWN`; `dropped_count` counts them. |
679
+ | Flushing | One background thread per process sends up to 200 items when 200 are pending, when their fields reach 64 KiB, or 2 seconds after the oldest, one flush at a time, each within 5 seconds. A forked worker starts its own thread and reports only its own requests. |
680
+ | `429` | The batch is kept and nothing is sent until `Retry-After` has passed, or the next UTC day for the daily allowance: at least 1 second and at most 24 hours, whatever `Retry-After` said. |
681
+ | `401` / `403` | The batch is dropped, nothing is sent for 60 seconds, and the refused key is logged at most once a minute. |
682
+ | `503`, or no answer at all | The batch is kept, as old as when it was first seen, and sent again after 1, 2, 4 and up to 60 seconds. |
683
+ | Timed out after sending | The batch is dropped, because the server may already have counted it. |
684
+ | An item the server could not use | Answered `VisitorKind::UNKNOWN` with a `ttl` of 0, so it is never remembered and that request stays `UNKNOWN`; the rest of the batch is answered as usual, and nothing is logged. |
685
+ | `422` | No item in the batch was usable. The batch is dropped and logged at most once a minute. |
686
+ | Any other status, `500`, `502` and `504` included | The batch is dropped and logged at most once a minute. |
687
+
688
+ In every case requests are served as usual and `lookup` keeps answering from
689
+ memory or `UNKNOWN`. Log lines go to `logger:` when you pass one and to
690
+ standard error otherwise, and never carry a request's fields.
691
+
692
+ `flush` sends what is pending now and waits for it, for runtimes that end
693
+ between invocations. `close` makes one last flush and stops the thread, for a
694
+ clean shutdown:
695
+
696
+ ```ruby
697
+ at_exit { SIGHTINGS.close }
698
+ ```
699
+
700
+ Register it next to where you build the instance. Under Puma, clustered or
701
+ not, and Unicorn with `preload_app`, every forked worker inherits the hook and
702
+ sends its own pending reports when it stops gracefully, and a worker never
703
+ sends what its parent holds. Unicorn stops gracefully on `QUIT`; on `TERM` or
704
+ `INT` it ends its workers at once, without running exit hooks, so what they
705
+ held is lost. `close` waits up to 6 seconds for a batch already in flight,
706
+ then sends what is left one batch at a time, each within 5 seconds, and stops
707
+ at the first that fails. `close` and `flush` never raise, may be called more
708
+ than once or from several threads at once, and also work inside a signal
709
+ handler such as `trap("TERM")`, which they hold up 12 seconds at most.
710
+
711
+ `fingerly.agents.report_sightings(items)` is the call underneath, for building
712
+ your own batching: it takes up to 200 `Fingerly::AgentSightingInput` values
713
+ and returns an `AgentSightingsReport` with `rules_version` and one
714
+ `AgentSighting` per item, in order; an item of another shape than the API
715
+ documents is `Fingerly::AgentSightings::UNKNOWN`. A `429` raises an `APIError` with
716
+ `retry_after` and `rate_limit_scope` (`APIError::RATE_LIMIT_SCOPE_DAILY` for
717
+ the daily allowance).
718
+
540
719
  ## Threads, fibers and deadlines
541
720
 
542
721
  There is no asynchronous client, and none is needed.
@@ -640,7 +819,9 @@ is refused.
640
819
  `Client` holds the connection and the options; `Events` owns the reads and the
641
820
  list filters, and `Event`, `EventPage` and `EventTrigger` are what they speak
642
821
  in. `Webhooks` verifies signatures. `Proxy` holds every proxy decision, with
643
- `ProxyRequest` as the shape `client_ip` is given. `Config` validates every
822
+ `ProxyRequest` as the shape `client_ip` is given. `AgentSightings` holds the
823
+ answer cache, the pending buffer and the background flusher, and its
824
+ `Middleware` decides which responses are reported. `Config` validates every
644
825
  caller-supplied option before any network access, and `Transport` is the one
645
826
  place that knows how to bound an exchange and reuse a socket.
646
827