fingerly 0.1.1 → 0.3.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.
data/README.md CHANGED
@@ -1,90 +1,235 @@
1
- # fingerly-ruby
1
+ <p align="center">
2
+ <a href="https://fingerly.io">
3
+ <picture>
4
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/logo-dark.svg">
5
+ <img src="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/logo-light.svg" alt="Fingerly" height="44">
6
+ </picture>
7
+ </a>
8
+ </p>
9
+
10
+ <p align="center"><b>Fingerly for Ruby</b><br>Read device intelligence events, verify webhooks and serve the browser SDK from your own domain.</p>
11
+
12
+ <p align="center">
13
+ <a href="https://rubygems.org/gems/fingerly"><img src="https://img.shields.io/gem/v/fingerly?style=flat-square" alt="Gem version"></a>
14
+ <a href="https://github.com/fingerly-io/sdk-ruby/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/fingerly-io/sdk-ruby/ci.yml?style=flat-square&label=ci" alt="CI status"></a>
15
+ <a href="https://github.com/fingerly-io/sdk-ruby/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue?style=flat-square" alt="License: Apache-2.0"></a>
16
+ <img src="https://img.shields.io/badge/ruby-%E2%89%A5%203.2-CC342D?style=flat-square" alt="Ruby 3.2 or newer">
17
+ <a href="https://docs.fingerly.io/docs/sdks/ruby"><img src="https://img.shields.io/badge/docs-docs.fingerly.io-111827?style=flat-square" alt="Documentation"></a>
18
+ </p>
19
+
20
+ <p align="center"><img src="https://raw.githubusercontent.com/fingerly-io/.github/main/assets/banner.webp" alt="Fingerly" width="100%"></p>
21
+
22
+ ## What is this
23
+
24
+ The `fingerly` gem is the server-side SDK for Ruby. It reads Fingerly events
25
+ with a secret key, verifies webhook signatures and relays the browser SDK's
26
+ traffic through your own domain with a same-origin Rack proxy. It has no
27
+ runtime dependencies and is for backends that protect signups, logins and
28
+ payments from fraud and abuse. [Fingerly](https://fingerly.io) identifies the
29
+ device behind each session and scores how suspicious it is.
30
+
31
+ ## Getting started
32
+
33
+ 1. **Prerequisites.** A Fingerly account and a secret key (`fly_sk_...`). See
34
+ [API keys and environments](https://docs.fingerly.io/docs/api-keys). Ruby
35
+ 3.2+.
36
+ 2. **Install.** Add it to your `Gemfile`:
37
+
38
+ ```ruby
39
+ gem "fingerly", "~> 0.3.0"
40
+ ```
41
+
42
+ 3. **Read an event.**
43
+
44
+ ```ruby
45
+ require "fingerly"
46
+
47
+ fingerly = Fingerly::Client.new(secret_key: ENV.fetch("FINGERLY_SECRET_KEY"))
48
+
49
+ request_id = ARGV.fetch(0) # the requestId the browser SDK's identify() returned
50
+ event = fingerly.events.get(request_id)
51
+ page = fingerly.events.list(level: "high", limit: 50)
52
+ page.each { |row| puts "#{row.request_id} #{row.suspect_level}" }
53
+ ```
54
+
55
+ 4. **Verify a webhook.**
56
+
57
+ ```ruby
58
+ class FingerlyWebhooksController < ActionController::API
59
+ def create
60
+ payload = request.raw_post
61
+
62
+ valid = Fingerly::Webhooks.verify(
63
+ secret: ENV.fetch("FINGERLY_WEBHOOK_SECRET"),
64
+ payload: payload,
65
+ timestamp: request.headers["x-fingerly-timestamp"],
66
+ signature: request.headers["x-fingerly-signature"]
67
+ )
68
+ return head :bad_request unless valid
69
+
70
+ event = Fingerly::Webhooks.parse(payload)
71
+ # Hand the work to your own job queue here, deduplicating on event.id.
72
+ Rails.logger.info("Fingerly webhook #{event.id} (#{event.type})")
73
+ head :no_content
74
+ end
75
+ end
76
+ ```
77
+
78
+ ```ruby
79
+ # config/routes.rb
80
+ post "/webhooks/fingerly", to: "fingerly_webhooks#create"
81
+ ```
82
+
83
+ Full guide: [docs.fingerly.io/docs/sdks/ruby](https://docs.fingerly.io/docs/sdks/ruby).
84
+
85
+ ## Choose what you need
86
+
87
+ | I want to | Use | Read |
88
+ | --- | --- | --- |
89
+ | Read an event after the browser identified a visitor | `Fingerly::Client` and `events.get` / `events.list` | [Read events](#read-events) |
90
+ | Let one event back one backend action | `events.verify` and `events.consume` | [Verify a backend action](#verify-a-backend-action) |
91
+ | Read or write an iOS device's DeviceCheck bits | `device_check.query` / `device_check.write` | [DeviceCheck bits](#devicecheck-bits) |
92
+ | Check a webhook delivery is genuine | `Fingerly::Webhooks.verify` and `.parse` | [Verify webhooks](#verify-webhooks) |
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
+
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
+
97
+ ## Read events
2
98
 
3
- Server-side event reads, webhook verification and a same-origin proxy for
4
- Ruby.
99
+ Event reads require `fly_sk_{production|staging|development}_` keys. Requests
100
+ go to `https://api.fingerly.io`; `endpoint:` overrides that with a bare
101
+ `https` origin, scheme, host and an optional port. A path, query, fragment,
102
+ credentials, whitespace, a control character or plain `http` is a
103
+ `ConfigurationError`, and the message never repeats the value. For a local
104
+ test API, `allow_insecure_loopback: true` accepts `http://127.0.0.1`,
105
+ `http://localhost` and `http://[::1]` (with any port); leave it off in
106
+ production. Public, proxy, management, malformed and unsupported keys are rejected
107
+ before network access, by the constructor rather than by the first call.
108
+ Requests do not follow redirects. `get` and `list` each perform one request
109
+ and never retry.
5
110
 
6
- ```ruby
7
- gem "fingerly", "~> 0.1"
8
- ```
111
+ ### Unscored events
9
112
 
10
- ```ruby
11
- require "fingerly"
12
-
13
- fingerly = Fingerly::Client.new(secret_key: ENV.fetch("FINGERLY_SECRET_KEY"))
113
+ `event.suspect_score` is `nil` when the request was not scored. Never read nil
114
+ as zero: a visitor about whom nothing fired scores 0, while a submission that
115
+ was never enriched has no score at all. `scored?` states the distinction at
116
+ the call site.
14
117
 
15
- request_id = ARGV.fetch(0) # the requestId the browser SDK's identify() returned
16
- event = fingerly.events.get(request_id)
17
- page = fingerly.events.list(level: "high", limit: 50)
18
- page.each { |row| puts "#{row.request_id} #{row.suspect_level}" }
118
+ ```ruby
119
+ unless event.scored?
120
+ # Decide on something else; do not treat it as clean.
121
+ end
19
122
  ```
20
123
 
21
- Event reads require `fly_sk_{production|staging|development}_` keys. Requests
22
- go to `https://api.fingerly.io`; `endpoint:` overrides that for a local
23
- API. Public, proxy, management, malformed and unsupported keys are rejected
24
- before network access, by the constructor rather than by the first call.
25
- Requests do not follow redirects. `get` and `list` each perform one request
26
- and never retry.
124
+ `event.raw` keeps the response body exactly as it arrived, so a field the API
125
+ adds later is reachable without a gem upgrade.
27
126
 
28
- Requires Ruby 3.2+, which is what the gemspec declares, and fiber-scheduler
29
- support below needs nothing newer. No runtime dependencies: everything it
30
- needs is in the standard library. Rack is a contract rather than a
31
- dependency, so the proxy speaks it without loading it and cannot pin a version
32
- against your own.
127
+ `event.project_id` is the UUID string of the Fingerly project the event
128
+ belongs to, on both `events.get` and `events.list` rows; it is `nil` when an
129
+ older server does not send it.
33
130
 
34
- ## There is no asynchronous client, and none is needed
131
+ ### Read an event you just identified
35
132
 
36
- The Python SDK ships two clients because ASGI and WSGI are two live server
37
- standards, and a blocking call inside FastAPI stalls its event loop. Ruby has
38
- one server interface, Rack, and every framework on it calls your application
39
- synchronously.
133
+ An event is usually readable as soon as identification answers. If it is
134
+ still being recorded, the read raises a `Fingerly::APIError` whose `pending?`
135
+ is true and whose `retry_after` says when to read again:
40
136
 
41
- The stack that is not thread-per-request is covered anyway. On Ruby 3.2+,
42
- the floor this gem requires, `Net::HTTP` yields to a fiber scheduler, so under
43
- Falcon or the `async` gem the blocking reads in this SDK hand the thread back
44
- to the scheduler rather than holding it. Concurrent calls overlap without a
45
- second API to choose between, and there are tests asserting exactly that under
46
- both a fiber scheduler and plain threads.
137
+ ```ruby
138
+ # Returns the event, or nil while it is still being recorded.
139
+ def read_event(fingerly, request_id)
140
+ fingerly.events.get(request_id)
141
+ rescue Fingerly::APIError => e
142
+ raise unless e.pending?
47
143
 
48
- Where there is no fiber scheduler, a call holds its thread until it answers,
49
- for at most `timeout:`. That is what Puma and Unicorn expect. Do not call the
50
- client from an event loop that is not a fiber scheduler, such as an
51
- EventMachine reactor: there it would stall every connection the loop serves.
144
+ # Not recorded yet, so nothing is decided: read again after e.retry_after
145
+ # seconds (2 when nil), or verify asynchronously.
146
+ nil
147
+ end
148
+ ```
52
149
 
53
- Size the thread pool for the slow case, not the average one: while Fingerly is
54
- slow, every proxied request holds its thread for the whole `timeout:`. At 100
55
- proxied requests a second with 1% of them running into a 5 second timeout, that
56
- is 5 threads busy on average, before any fast request is served. Run more
57
- threads than that across your Puma or Unicorn workers, lower `timeout:` for the
58
- proxy, or serve with Falcon, where a waiting call holds no thread.
150
+ Retry a pending read a bounded number of times, for example from a background
151
+ job. `event_not_found?` means a request id that was never issued, or one past
152
+ retention, and is never pending.
59
153
 
60
- ## Deadlines
154
+ The archived document arrives moments after the event itself, so check
155
+ `has_document?` rather than assuming it is there, and read `event.document`
156
+ (`Hash` or `nil`, holding allow-listed `risk`, `attestation`, `ip_network` and
157
+ `velocity` fields without raw signals, user agent or address). When a submission
158
+ is unidentifiable (`identifiable == false`, such as insufficient entropy, a
159
+ genuine embedded WebView, or an unmatched high-risk Web payload),
160
+ `event.visitor_id` is `""`; there are no `deferred_token`, `deferred_signals` or
161
+ `supplements` fields in `v: 3`.
162
+
163
+ `Fingerly::EventTrigger::V3_SIGNALS` groups the `v: 3` anti-spoofing and
164
+ integrity signal constants on `Fingerly::EventTrigger`:
165
+ `SIGNAL_ATTESTATION_FAILED` (`"attestation_failed"`),
166
+ `SIGNAL_ATTESTATION_DOWNGRADE` (`"attestation_downgrade"`),
167
+ `SIGNAL_DEVICE_INCONSISTENT` (`"device_inconsistent"`),
168
+ `SIGNAL_REPORT_INCOMPLETE` (`"report_incomplete"`),
169
+ `SIGNAL_PROBE_ERRORS` (`"probe_errors"`),
170
+ `SIGNAL_FETCH_METADATA_MISSING` (`"fetch_metadata_missing"`),
171
+ `SIGNAL_WEB_TICKET_MISSING` (`"web_ticket_missing"`),
172
+ `SIGNAL_WEB_TICKET_INVALID` (`"web_ticket_invalid"`),
173
+ `SIGNAL_TAMPERING` (`"tampering"`),
174
+ `SIGNAL_CUSTOM_ROOT_CA` (`"custom_root_ca"`) and
175
+ `SIGNAL_SECONDARY_USER_PROFILE` (`"secondary_user_profile"`).
176
+
177
+ ### Verify a backend action
178
+
179
+ `fingerly.events.verify` reads the event with the server-only key, checks
180
+ that it can back the action, and consumes it, so one event backs one
181
+ decision:
61
182
 
62
- `timeout:` bounds the whole exchange: connecting, sending, the response
63
- headers and the body.
183
+ ```ruby
184
+ def authorize_checkout(fingerly, request_id)
185
+ result = fingerly.events.verify(request_id, tag: "checkout") # max_age_seconds: 300, consume: true
186
+ return "refuse" unless result.ok? # result.reason names the failed check
64
187
 
65
- That takes care on this platform. `Net::HTTP` has `open_timeout`,
66
- `read_timeout` and `write_timeout`, but each bounds a single operation: a
67
- server that answers and then sends one byte a second would satisfy all three
68
- forever, and so would one that sends a header line a second, because each
69
- header line gets the full read timeout. The client shrinks the socket's own
70
- timeouts to whatever is left of the deadline before each step, and one
71
- `Timeout` around the whole exchange covers the header lines, so the bound is
72
- tight rather than a multiple of the timeout. Under a fiber scheduler that
73
- `Timeout` is the scheduler's own.
188
+ # The score policy is yours: verify never judges the score.
189
+ result.event.suspect_level == "low" ? "allow" : "review"
190
+ rescue Fingerly::APIError => e
191
+ return "retry later" if e.pending? # not decided yet: read again after e.retry_after
74
192
 
75
- Idle connections are kept in one pool per process and destination, shared by
76
- every client and proxy in it. `Net::HTTP` cannot be used by two threads or
77
- fibers at once, so each exchange checks a connection out and hands it back
78
- when it is done: a burst of a few hundred concurrent requests reuses its
79
- sockets rather than opening one each, and a fiber that ends (Falcon runs one
80
- per client connection) returns its socket instead of stranding it. At most
81
- 256 idle connections are kept per destination. A connection is reopened after
82
- 60 seconds, so DNS is asked again, and dropped after 15 seconds idle. One the
83
- other end closed while it was idle is reopened and the request sent again,
84
- but only for `GET`, because a `POST` that may already have arrived must never
85
- be sent twice. A forked worker starts with an empty pool.
193
+ raise
194
+ end
195
+ ```
86
196
 
87
- ## Errors
197
+ The checks run in this order and stop at the first failure, whose wire string
198
+ is `result.reason` (`""` when `result.ok?`), with a constant on
199
+ `Fingerly::EventVerification`:
200
+
201
+ 1. `not_found` (`NOT_FOUND`): the request id was never issued, or the event is
202
+ past retention. `result.event` is `nil` for this reason only.
203
+ 2. `too_old` (`TOO_OLD`): the event occurred more than `max_age_seconds`
204
+ ago (300 by default), or carries no readable `occurred_at`.
205
+ 3. `tag_mismatch` (`TAG_MISMATCH`): `tag:` was given and the event's tag is not
206
+ exactly it. Without `tag:` nothing is compared; an empty tag raises
207
+ `Fingerly::ConfigurationError`.
208
+ 4. `unidentifiable` (`UNIDENTIFIABLE`): `event.visitor_id` is empty.
209
+ 5. `unscored` (`UNSCORED`): the event has no suspect score.
210
+ 6. `already_consumed` (`ALREADY_CONSUMED`): another call consumed the event
211
+ first.
212
+
213
+ The consume runs last, only when every other check passed, so a failed check
214
+ leaves the event unused. Pass `consume: false` to check without consuming. An
215
+ invalid option raises `Fingerly::ConfigurationError` before anything is sent.
216
+ Any other failure raises as it does for `events.get`. A pending event
217
+ (`pending?`) is not a verdict: retry after `retry_after` seconds or verify
218
+ asynchronously, rather than refusing the action.
219
+
220
+ `fingerly.events.consume(request_id)` is the consume on its own. It returns a
221
+ `Fingerly::EventConsumption` (`request_id`, `consumed_at`, `first?`) the first
222
+ time, is never retried, and raises `Fingerly::EventAlreadyConsumedError`, a
223
+ `Fingerly::APIError` with `event_already_consumed?` true and the first
224
+ `consumed_at`, every time after.
225
+
226
+ Do not authorize an action using scores or visitor identifiers supplied by the
227
+ browser. Tags correlate events; they do not replace your application's
228
+ authentication. A tag must never hold a personal identifier, such as a user
229
+ ID, email, install ID or advertising ID, because the server keeps tags in
230
+ long-lived rollups.
231
+
232
+ ### Errors
88
233
 
89
234
  Every runtime failure derives from `Fingerly::Error`. A bad option raises
90
235
  `Fingerly::ConfigurationError`, which is an `ArgumentError`: a key that was
@@ -94,7 +239,10 @@ call site can help with.
94
239
  ```ruby
95
240
  def decide(fingerly, request_id)
96
241
  event = fingerly.events.get(request_id)
97
- event.scored? && event.suspect_level == "low" ? "allow" : "review"
242
+ return "review" if event.visitor_id.empty? || !event.scored?
243
+ return "refuse" if event.triggers.any? { |t| t.signal == Fingerly::EventTrigger::SIGNAL_ATTESTATION_FAILED }
244
+
245
+ event.suspect_level == "low" ? "allow" : "review"
98
246
  rescue Fingerly::APIError => e
99
247
  return "retry later" if e.pending? # not decided yet: read again after e.retry_after
100
248
  return "refuse" if e.event_not_found?
@@ -104,126 +252,132 @@ rescue Fingerly::APIError => e
104
252
  end
105
253
  ```
106
254
 
107
- Every response outside 2xx, a redirect included, raises `Fingerly::APIError`.
108
- It carries `status`, and optional `code`, `details`, `request_id` and
109
- `retry_after`. The secret key is stripped from the first three, and the
110
- response body is never echoed. `request_id` falls back to the `x-request-id`
111
- header when the body is not an error envelope. `retry_after` is the
112
- `Retry-After` header in whole seconds, from either of its forms, or `nil`
255
+ | Error | Raised when |
256
+ | --- | --- |
257
+ | `Fingerly::ConfigurationError` (an `ArgumentError`) | A bad option, such as a key that was never valid. |
258
+ | `Fingerly::APIError` | Every response outside 2xx, a redirect included. Carries `status`, and optional `code`, `details`, `request_id` and `retry_after`. |
259
+ | `Fingerly::TimeoutError` | The deadline (`timeout:`) passed. |
260
+ | `Fingerly::ConnectionError` | The API is unreachable. |
261
+
262
+ On `APIError`, the secret key is stripped from the first three of those
263
+ fields, and the response body is never echoed. `request_id` falls back to the
264
+ `x-request-id` header when the body is not an error envelope. `retry_after` is
265
+ the `Retry-After` header in whole seconds, from either of its forms, or `nil`
113
266
  when there was none: on a `429` or a pending event, wait that long before
114
267
  reading again.
115
268
 
116
269
  A read answers `404` with one of two codes, each with its own predicate:
117
270
 
118
- - `pending?`: `event_pending`, the request id was accepted and the event is
119
- still being recorded. Nothing is decided yet: read again after
120
- `retry_after` seconds (the API sends `Retry-After: 2`), or verify
121
- asynchronously. Do not treat it as fraud.
122
- - `event_not_found?`: `event_not_found`, the request id was never issued, or
123
- the event is past retention.
271
+ | Predicate | Code | Meaning |
272
+ | --- | --- | --- |
273
+ | `pending?` | `event_pending` | The request id was accepted and the event is still being recorded. Nothing is decided yet: read again after `retry_after` seconds (the API sends `Retry-After: 2`), or verify asynchronously. Do not treat it as fraud. |
274
+ | `event_not_found?` | `event_not_found` | The request id was never issued, or the event is past retention. |
124
275
 
125
- The client never retries by itself. A deadline raises
126
- `Fingerly::TimeoutError`; an unreachable API raises
127
- `Fingerly::ConnectionError`.
276
+ The client never retries an event read by itself; only a
277
+ [DeviceCheck](#devicecheck-bits) call retries, and only the same request.
128
278
 
129
279
  No object in the SDK shows a credential. A client or proxy printed with
130
280
  `inspect`, `to_s`, `pp`, `to_json` or YAML shows `[redacted]` in place of its
131
281
  key, and `Marshal.dump` refuses it. The request handed to `client_ip` hides the
132
282
  visitor's cookies and authorization header the same way.
133
283
 
134
- ## Unscored events
135
-
136
- `event.suspect_score` is `nil` when the request was not scored. Never read nil
137
- as zero: a visitor about whom nothing fired scores 0, while a submission that
138
- was never enriched has no score at all. `scored?` states the distinction at
139
- the call site.
140
-
141
- ```ruby
142
- unless event.scored?
143
- # Decide on something else; do not treat it as clean.
144
- end
145
- ```
146
-
147
- `event.raw` keeps the response body exactly as it arrived, so a field the API
148
- adds later is reachable without a gem upgrade.
284
+ ## DeviceCheck bits
149
285
 
150
- ## Read an event you just identified
151
-
152
- An event is usually readable as soon as identification answers. If it is
153
- still being recorded, the read raises a `Fingerly::APIError` whose `pending?`
154
- is true and whose `retry_after` says when to read again:
286
+ On iOS, Apple keeps two DeviceCheck bits per device for your developer team,
287
+ and they survive a reinstall. When DeviceCheck is on for the project's Apple
288
+ key, Fingerly holds the DeviceCheck token that came with an identification for
289
+ one hour, and your backend spends it once:
155
290
 
156
291
  ```ruby
157
- # Returns the event, or nil while it is still being recorded.
158
- def read_event(fingerly, request_id)
159
- fingerly.events.get(request_id)
160
- rescue Fingerly::APIError => e
161
- raise unless e.pending?
292
+ bits = fingerly.device_check.query(request_id) # Fingerly::DeviceCheckBits
293
+ bits.found # false when Apple holds no bits for the device yet
294
+ bits.bit0 # true or false
295
+ bits.last_update # "YYYY-MM", or nil when Apple holds no bits
162
296
 
163
- # Not recorded yet, so nothing is decided: read again after e.retry_after
164
- # seconds (2 when nil), or verify asynchronously.
165
- nil
166
- end
297
+ written = fingerly.device_check.write(request_id, bit0: true) # Fingerly::DeviceCheckWrite
298
+ written.bit0 # true; a bit left out is nil, and keeps its value at Apple
167
299
  ```
168
300
 
169
- Retry a pending read a bounded number of times, for example from a background
170
- job. `event_not_found?` means a request id that was never issued, or one past
171
- retention, and is never pending.
172
-
173
- The archived document arrives moments after the event itself, so check
174
- `has_document?` rather than assuming it is there.
175
-
176
- ## Verify a backend action
301
+ Apple treats each DeviceCheck token as single-use, so one event pays for one
302
+ call: a read or a write, never both. A flow that checks and then marks a
303
+ device, such as a once-per-device free trial, takes two identifications:
177
304
 
178
- Read the event with a server-only key. Check that its tag matches your action,
179
- that it is recent, that its environment is correct, and that it was scored.
180
- Apply your own policy to the server's verdict. A pending event (`pending?`)
181
- is not a verdict: retry after `retry_after` seconds or verify asynchronously,
182
- rather than refusing the action. Do not authorize an action using scores or
183
- visitor identifiers supplied by the browser. Tags correlate events; they do
184
- not replace your application's authentication or replay protection.
185
-
186
- ## Webhooks
305
+ 1. Query on the identification that asks for the trial. If the bits say the
306
+ device already had one, refuse it.
307
+ 2. Otherwise grant the trial and record the grant in your own data.
308
+ 3. Write the bit on the next identification from that install, such as one
309
+ the app makes right after the grant. Until the write lands, your own record
310
+ of the grant is what stops a second trial.
187
311
 
188
312
  ```ruby
189
- class FingerlyWebhooksController < ActionController::API
190
- def create
191
- payload = request.raw_post
192
-
193
- valid = Fingerly::Webhooks.verify(
194
- secret: ENV.fetch("FINGERLY_WEBHOOK_SECRET"),
195
- payload: payload,
196
- timestamp: request.headers["x-fingerly-timestamp"],
197
- signature: request.headers["x-fingerly-signature"]
198
- )
199
- return head :bad_request unless valid
200
-
201
- event = Fingerly::Webhooks.parse(payload)
202
- # Hand the work to your own job queue here, deduplicating on event.id.
203
- Rails.logger.info("Fingerly webhook #{event.id} (#{event.type})")
204
- head :no_content
313
+ # bit0 means "this device has had a free trial". The meaning is yours.
314
+ def start_trial(fingerly, account, request_id)
315
+ bits = begin
316
+ fingerly.device_check.query(request_id)
317
+ rescue Fingerly::DeviceCheckError => e
318
+ raise unless e.not_held? || e.spent? || e.apple_rejected?
319
+
320
+ nil # no answer, not a verdict: decide without the bits
205
321
  end
322
+ return "offer-paid-plan" if bits&.bit0
323
+
324
+ Trial.grant(account, device_marked: false)
325
+ "granted"
206
326
  end
207
- ```
208
327
 
209
- ```ruby
210
- # config/routes.rb
211
- post "/webhooks/fingerly", to: "fingerly_webhooks#create"
328
+ def mark_trial(fingerly, account, request_id)
329
+ fingerly.device_check.write(request_id, bit0: true)
330
+ Trial.update(account, device_marked: true)
331
+ rescue Fingerly::DeviceCheckError => e
332
+ raise unless e.not_held? || e.spent?
333
+ # Keep device_marked false and write at the install's next identification.
334
+ end
212
335
  ```
213
336
 
214
- Verify the exact raw bytes before parsing them. `request.raw_post` is those
215
- bytes; a body reconstructed from parsed parameters is not. Signatures cover
216
- the timestamp and body. The default replay tolerance is five minutes; persist
217
- processed `id` values to deduplicate deliveries. During signing-secret
218
- rotation, any matching signature in the comma-separated header is accepted;
219
- only the first 32 are read.
220
- Malformed or missing input is a false result, never an exception, and a body
221
- that is not valid UTF-8 verifies rather than raising on concatenation.
337
+ A failure raises `Fingerly::DeviceCheckError`, a `Fingerly::APIError` with a
338
+ predicate per code:
339
+
340
+ | Status | Code | Predicate |
341
+ |---|---|---|
342
+ | 404 | `device_check_not_held` | `not_held?` |
343
+ | 409 | `device_check_spent` | `spent?` |
344
+ | 409 | `device_check_busy` | `busy?` |
345
+ | 409 | `credential_unavailable` | `credential_unavailable?` |
346
+ | 422 | `bits_required` | `bits_required?` |
347
+ | 422 | `apple_rejected` | `apple_rejected?`, with Apple's HTTP status in `apple_status` |
348
+ | 503 | `device_check_unavailable` | `unavailable?` |
349
+
350
+ A write that names neither bit raises `Fingerly::ConfigurationError` before
351
+ anything is sent.
352
+
353
+ The token may be retried only with the same request. After a `503` or a
354
+ transport failure the token is kept, so the client sends the identical request
355
+ again, up to three attempts in all; it retries nothing else. If you retry
356
+ later yourself, repeat the same call with the same bits: a read after a failed
357
+ write, or a write with other bits, answers `409 device_check_spent`. Apple asks
358
+ that DeviceCheck is never the only fraud check, and that users have a way to
359
+ have the bits reset.
360
+
361
+ ## Verify webhooks
362
+
363
+ The controller and route are in [Getting started](#getting-started). Verify the
364
+ exact raw bytes before parsing them. `request.raw_post` is those bytes; a body
365
+ reconstructed from parsed parameters is not.
366
+
367
+ | Behaviour | Detail |
368
+ | --- | --- |
369
+ | What a signature covers | the timestamp and the body |
370
+ | Replay tolerance | five minutes by default |
371
+ | Secret rotation | any matching signature in the comma-separated header is accepted; only the first 32 are read |
372
+ | Malformed or missing input | a false result, never an exception; a body that is not valid UTF-8 verifies rather than raising on concatenation |
373
+ | Deduplication | persist processed `id` values to deduplicate deliveries |
222
374
 
223
375
  `WebhookEvent#data` stays a plain `Hash`, so a new event type needs no gem
224
- upgrade.
376
+ upgrade. `identification.completed` and `visitor.suspect` deliveries carry the
377
+ event's project as `data["project_id"]`; `identification.refused` carries it
378
+ only when the refused request named a known key.
225
379
 
226
- ## Same-origin proxy
380
+ ## First-party proxy (same-origin)
227
381
 
228
382
  Content blockers refuse browser requests to third-party APIs, and a refused
229
383
  identification is a visitor never identified. Mount the proxy on a path of
@@ -267,8 +421,21 @@ Put it first, ahead of authentication: the browser SDK sends no cookies and
267
421
  carries no user, and a filter that redirected it to a sign-in page would break
268
422
  identification for every signed-out visitor.
269
423
 
270
- Then point the browser SDK at the same path. Both of its calls go there, with
271
- nothing appended:
424
+ > **`client_ip` is the one thing you must get right.** Resolve it from a
425
+ > header your own infrastructure sets, such as your load balancer's or CDN's,
426
+ > and fall back to `request.peer_host`, the TCP peer, when it is absent, as in
427
+ > local development. Trust that header only when traffic can reach your
428
+ > application through that CDN alone; otherwise a visitor can set it. Never read
429
+ > the left-most `X-Forwarded-For` value: the visitor writes it.
430
+
431
+ `client_ip` must return exactly one IPv4 or IPv6 address. Anything else, `nil`
432
+ or an empty string, a list, a port, a prefix length, or an exception, is a
433
+ configuration mistake: the proxy sends nothing upstream, answers `500` with
434
+ "The client IP callback returned no valid address", and logs it once per
435
+ process rather than once per visitor.
436
+
437
+ Then point the client SDK at the same path. Browser and proxied native SDKs post
438
+ a single `v: 3` identification envelope there, with nothing appended:
272
439
 
273
440
  ```ts
274
441
  import { load } from '@fingerly/web-js'
@@ -276,65 +443,52 @@ import { load } from '@fingerly/web-js'
276
443
  const fingerly = await load({ apiKey: 'fly_pk_…', endpoints: '/k7x2qm4a' })
277
444
  ```
278
445
 
279
- `path` is optional where the framework already routes the path to the proxy,
280
- as a Rails `mount` or a `Rack::URLMap` entry does. Omit it there: the mount has
281
- already moved the path into `SCRIPT_NAME`. A mount matches a prefix, but the
282
- proxy still answers only the mount's exact path: `/k7x2qm4a/admin` or
283
- `/k7x2qm4a/` routed to it get `404`. Rails hands a mount the same `PATH_INFO`
284
- with and without a trailing slash, so the proxy tells them apart by the raw
285
- request line in `REQUEST_URI`, which Puma and Falcon provide.
286
-
287
- ```ruby
288
- # config/routes.rb
289
- mount Fingerly::Proxy.new(
290
- proxy_key: ENV.fetch("FINGERLY_PROXY_KEY"),
291
- client_ip: ->(request) { request.header("CF-Connecting-IP") || request.peer_host }
292
- ) => "/k7x2qm4a"
293
- ```
294
-
295
- As middleware it sees every request in the stack, so there `path` is required
296
- and its absence is a `ConfigurationError` at start-up.
446
+ `proxy_key` and `path` are required. A proxy key that is not
447
+ `fly_px_<environment>_...` for `production`, `staging` or `development`, or a
448
+ missing `path`, is a `ConfigurationError` at start-up. The proxy matches it
449
+ exactly against `PATH_INFO`, so use it as middleware, as above, or run it as
450
+ the whole application. Do not put it behind a Rails `mount` or a
451
+ `Rack::URLMap` entry: those move the path into `SCRIPT_NAME`, and the proxy
452
+ then sees a path that is not its own and answers `404`.
297
453
 
298
454
  ### What the proxy does
299
455
 
300
- It answers only the configured path, matched exactly and case-sensitively:
301
- `/k7x2qm4a/`, `//k7x2qm4a`, `/k7x2qm4a/.`, `/k7x2qm4a%2F` and `/k7x2qm4a/admin`
302
- are not its own. Anything else is passed along to
303
- your application, or answered `404` when the proxy has no application behind
304
- it. On its own path, anything but `POST` gets `405`. Every request it accepts
305
- goes to one URL, `https://api.fingerly.io/api/v1/ingest`, which tells the
306
- identification from the report that follows it by the body. Nothing else is
307
- reachable through it, event reads included: they need a secret key and stay
308
- unreachable from a browser by construction. `api_version:` changes only the
309
- version in that URL.
310
-
311
- The browser must present a public key from the same environment as the proxy
312
- key, or the request gets `401`. Bodies over 1 MiB get `413`,
313
- enforced while reading rather than after buffering. That bounds what the proxy
314
- holds. A server that buffers the whole request before calling the application,
315
- as Puma does, has already read it by then, so bound request bodies there with
316
- the server's or the load balancer's own limit as well. Falcon streams the body,
317
- so there the proxy stops reading at the limit. Only the content type, the
318
- visitor metadata Fingerly needs, and an `Idempotency-Key` are forwarded;
319
- customer cookies and authorization headers never are. The proxy reports itself
320
- upstream as `ruby/0.1.1` in `x-fingerly-proxy-version`, which the dashboard
321
- shows per proxy.
322
-
323
- When Fingerly cannot be reached, the visitor gets a gateway error rather than
324
- your application's `500`: `504 Gateway timeout` when `timeout:` (5 seconds by
325
- default) passes, and `502 Bad gateway` for anything else, whether the
326
- connection was refused or reset, the name did not resolve, or the answer was
327
- malformed, cut short or over 4 MiB. The whole answer is read before anything
328
- is written back, so a truncated response is never relayed as a success. Each
329
- failure logs one line, without a stack trace, to `logger:` when you pass one,
330
- to `rack.logger` when your server provides it, and to standard error
331
- otherwise.
332
-
333
- Only `content-type`, `x-request-id`, `ratelimit-limit`, `ratelimit-remaining`
334
- and `retry-after` are relayed back, plus `cache-control: no-store` set by the
335
- proxy. A content blocker can match a response header by name, and an
336
- allowlist keeps anything that names Fingerly off the response, whatever the
337
- API adds later.
456
+ | Rule | Behaviour |
457
+ | --- | --- |
458
+ | Path match | Only the configured path, matched exactly and case-sensitively: `/k7x2qm4a/`, `//k7x2qm4a`, `/k7x2qm4a/.`, `/k7x2qm4a%2F`, `/k7x2qm4a/admin` and retired `/supplement` paths are not its own. Anything else is passed along to your application, or answered `404` when the proxy has no application behind it. |
459
+ | Other methods | On its own path, anything but `POST` (plus `OPTIONS` when `allowed_origins:` is configured) gets `405`. Methods are compared exactly, so `post` gets `405` too. |
460
+ | Own answers | Every answer the proxy writes itself carries `cache-control: no-store`. |
461
+ | Upstream | Every request it accepts goes verbatim as raw bytes to one URL, `https://api.fingerly.io/api/v1/ingest`. `api_version:` changes only the version in that URL. |
462
+ | Event reads | Nothing else is reachable through it, event reads included: they need a secret key and stay unreachable from a browser by construction. |
463
+ | Public key | The caller must present a public key (`fly_pk_...`) from the same environment as the proxy key, or the request gets `401` and nothing is forwarded; a secret key is refused the same way. |
464
+ | 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. |
465
+ | 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. |
466
+ | Body size | Bodies over 1 MiB get `413`, enforced while reading rather than after buffering. |
467
+ | 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-*`. |
468
+ | Proxy identity | The proxy reports itself upstream as `ruby/0.3.0` in `x-fingerly-proxy-version`, which the dashboard shows per proxy. |
469
+ | Fingerly unreachable | The visitor gets a gateway error rather than your application's `500`. |
470
+ | Deadline passes | `504 Gateway timeout` when `timeout:` (5 seconds by default) passes. |
471
+ | 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. |
472
+ | Truncated answers | The whole answer is read before anything is written back, so a truncated response is never relayed as a success. |
473
+ | Failure logging | Each failure logs one line, without a stack trace, to `logger:` when you pass one, to `rack.logger` when your server provides it, and to standard error otherwise. The line names the kind of failure only, never the upstream address or a key. |
474
+ | Relayed back | Only `content-type`, `x-request-id`, `ratelimit-limit`, `ratelimit-remaining` and `retry-after`, plus `cache-control: no-store` set by the proxy. A content blocker can match a response header by name, and an allowlist keeps anything that names Fingerly off the response, whatever the API adds later. |
475
+ | Header shape | Relayed headers are lowercase and repeats joined with `", "`, which is the one shape Rack 2 and Rack 3 both accept: Rack 3 refuses an uppercase name outright, and Rack 2 refuses the array Rack 3 would rather have. |
476
+
477
+ The 1 MiB limit bounds what the proxy holds. A server that buffers the whole
478
+ request before calling the application, as Puma does, has already read it by
479
+ then, so bound request bodies there with the server's or the load balancer's own
480
+ limit as well. Falcon streams the body, so there the proxy stops reading at the
481
+ limit.
482
+
483
+ `upstream:` takes a bare origin, scheme, host and an optional port, such as
484
+ `https://api.fingerly.io`. A path, query, fragment, credentials, whitespace or
485
+ a control character is a `ConfigurationError`, and so is plain `http`. For a
486
+ local test API, `allow_insecure_loopback: true` accepts `http://127.0.0.1`,
487
+ `http://localhost` and `http://[::1]` (with any port), and nothing else; leave
488
+ it off in production.
489
+
490
+ <details>
491
+ <summary>Why the middleware decides from the path alone, and what <code>path</code> means</summary>
338
492
 
339
493
  The middleware decides from the path alone before it reads anything. It sees
340
494
  every request in the stack, and reading the body to find out whether one
@@ -348,25 +502,81 @@ means the same thing wherever the application is deployed. Use the one the
348
502
  dashboard issued rather than inventing one: blockers look for words such as
349
503
  `fingerprint`, `tracking` and `analytics` in a path.
350
504
 
351
- Relayed headers are lowercase and repeats joined with `", "`, which is the
352
- one shape Rack 2 and Rack 3 both accept: Rack 3 refuses an uppercase name
353
- outright, and Rack 2 refuses the array Rack 3 would rather have.
505
+ </details>
354
506
 
355
- > **`client_ip` is the one thing you must get right.** Resolve it from a
356
- > header your own infrastructure sets, such as your load balancer's or CDN's,
357
- > and fall back to `request.peer_host`, the TCP peer, when it is absent, as in
358
- > local development. Trust that header only when traffic can reach your
359
- > application through that CDN alone; otherwise a visitor can set it. Never read
360
- > the left-most `X-Forwarded-For` value: the visitor writes it.
507
+ ## Threads, fibers and deadlines
361
508
 
362
- `client_ip` must return exactly one IPv4 or IPv6 address. Anything else, `nil`
363
- or an empty string, a list, a port, a prefix length, or an exception, is a
364
- configuration mistake: the proxy sends nothing upstream, answers `500` with
365
- "The client IP callback returned no valid address", and logs it once per
366
- process rather than once per visitor.
509
+ There is no asynchronous client, and none is needed.
510
+
511
+ The Python SDK ships two clients because ASGI and WSGI are two live server
512
+ standards, and a blocking call inside FastAPI stalls its event loop. Ruby has
513
+ one server interface, Rack, and every framework on it calls your application
514
+ synchronously.
515
+
516
+ The stack that is not thread-per-request is covered anyway. On Ruby 3.2+,
517
+ the floor this gem requires, `Net::HTTP` yields to a fiber scheduler, so under
518
+ Falcon or the `async` gem the blocking reads in this SDK hand the thread back
519
+ to the scheduler rather than holding it. Concurrent calls overlap without a
520
+ second API to choose between, and there are tests asserting exactly that under
521
+ both a fiber scheduler and plain threads.
522
+
523
+ Where there is no fiber scheduler, a call holds its thread until it answers,
524
+ for at most `timeout:`. That is what Puma and Unicorn expect. Do not call the
525
+ client from an event loop that is not a fiber scheduler, such as an
526
+ EventMachine reactor: there it would stall every connection the loop serves.
527
+
528
+ Size the thread pool for the slow case, not the average one: while Fingerly is
529
+ slow, every proxied request holds its thread for the whole `timeout:`. At 100
530
+ proxied requests a second with 1% of them running into a 5 second timeout, that
531
+ is 5 threads busy on average, before any fast request is served. Run more
532
+ threads than that across your Puma or Unicorn workers, lower `timeout:` for the
533
+ proxy, or serve with Falcon, where a waiting call holds no thread.
534
+
535
+ ### Deadlines
536
+
537
+ `timeout:` bounds the whole exchange: connecting, sending, the response
538
+ headers and the body.
539
+
540
+ That takes care on this platform. `Net::HTTP` has `open_timeout`,
541
+ `read_timeout` and `write_timeout`, but each bounds a single operation: a
542
+ server that answers and then sends one byte a second would satisfy all three
543
+ forever, and so would one that sends a header line a second, because each
544
+ header line gets the full read timeout. The client shrinks the socket's own
545
+ timeouts to whatever is left of the deadline before each step, and one
546
+ `Timeout` around the whole exchange covers the header lines, so the bound is
547
+ tight rather than a multiple of the timeout. Under a fiber scheduler that
548
+ `Timeout` is the scheduler's own.
549
+
550
+ ### Connection pool
551
+
552
+ Idle connections are kept in one pool per process and destination, shared by
553
+ every client and proxy in it. `Net::HTTP` cannot be used by two threads or
554
+ fibers at once, so each exchange checks a connection out and hands it back
555
+ when it is done: a burst of a few hundred concurrent requests reuses its
556
+ sockets rather than opening one each, and a fiber that ends (Falcon runs one
557
+ per client connection) returns its socket instead of stranding it.
558
+
559
+ | Pool rule | Value |
560
+ | --- | --- |
561
+ | Idle connections kept | at most 256 per destination |
562
+ | Reopened after | 60 seconds, so DNS is asked again |
563
+ | Dropped after | 15 seconds idle |
564
+ | Closed while idle by the other end | reopened and the request sent again, but only for `GET`, because a `POST` that may already have arrived must never be sent twice |
565
+ | Forked worker | starts with an empty pool |
566
+
567
+ ## Requirements
568
+
569
+ Ruby 3.2+, which is what the gemspec declares (`required_ruby_version >= 3.2.0`),
570
+ and fiber-scheduler support needs nothing newer. CI runs Ruby 3.2, 3.3 and 3.4.
571
+ No runtime dependencies: everything it needs is in the standard library. Rack is
572
+ a contract rather than a dependency, so the proxy speaks it without loading it
573
+ and cannot pin a version against your own.
367
574
 
368
575
  ## Development and release preparation
369
576
 
577
+ <details>
578
+ <summary>Tests, signatures, contract snapshot, release, source structure</summary>
579
+
370
580
  ```sh
371
581
  bundle install
372
582
  bundle exec rake # tests, RuboCop and the RBS signatures
@@ -392,7 +602,7 @@ separate check step. Never put production secrets in fixtures.
392
602
  The gemspec sets `allowed_push_host` to RubyGems, so a push to any other host
393
603
  is refused.
394
604
 
395
- ## Source structure
605
+ ### Source structure
396
606
 
397
607
  `Client` holds the connection and the options; `Events` owns the reads and the
398
608
  list filters, and `Event`, `EventPage` and `EventTrigger` are what they speak
@@ -400,3 +610,22 @@ in. `Webhooks` verifies signatures. `Proxy` holds every proxy decision, with
400
610
  `ProxyRequest` as the shape `client_ip` is given. `Config` validates every
401
611
  caller-supplied option before any network access, and `Transport` is the one
402
612
  place that knows how to bound an exchange and reuse a socket.
613
+
614
+ </details>
615
+
616
+ ## Documentation
617
+
618
+ - [Ruby SDK guide](https://docs.fingerly.io/docs/sdks/ruby)
619
+ - [Webhooks](https://docs.fingerly.io/docs/webhooks)
620
+ - [Proxy integrations](https://docs.fingerly.io/docs/proxy-integrations)
621
+ - [API reference](https://docs.fingerly.io/reference/overview)
622
+
623
+ ## Help
624
+
625
+ Open an issue on [this repository](https://github.com/fingerly-io/sdk-ruby/issues), or write to
626
+ [support@fingerly.io](mailto:support@fingerly.io). Report security issues to
627
+ [security@fingerly.io](mailto:security@fingerly.io).
628
+
629
+ ## Licence
630
+
631
+ Apache-2.0. See [LICENSE](https://github.com/fingerly-io/sdk-ruby/blob/main/LICENSE).