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.
@@ -34,7 +34,6 @@ module Fingerly
34
34
  RESIDENTIAL_PROXY_MEDIUM_CONFIDENCE = "residential_proxy_medium_confidence"
35
35
  RESIDENTIAL_PROXY_HIGH_CONFIDENCE = "residential_proxy_high_confidence"
36
36
  VPN_PUBLIC = "vpn_public"
37
- VPN_TIMEZONE = "vpn_timezone"
38
37
  VPN_RELAY = "vpn_relay"
39
38
  VPN_MOBILE = "vpn_mobile"
40
39
  VPN_OS_MISMATCH = "vpn_os_mismatch"
@@ -51,6 +50,7 @@ module Fingerly
51
50
  # Detectors only a browser can produce.
52
51
  INCOGNITO = "incognito"
53
52
  BAD_BOT = "bad_bot"
53
+ AI_SPOOFED = "ai_spoofed"
54
54
  AUTOMATION = "automation"
55
55
  FETCH_METADATA_MISSING = "fetch_metadata_missing"
56
56
  WEB_TICKET_MISSING = "web_ticket_missing"
@@ -58,6 +58,7 @@ module Fingerly
58
58
  ANTIDETECT_BROWSER = "antidetect_browser"
59
59
  VIRTUAL_MACHINE = "virtual_machine"
60
60
  FINGERPRINT_SUPPRESSED = "fingerprint_suppressed"
61
+ IDENTITY_OBFUSCATED = "identity_obfuscated"
61
62
  PRIVACY_SETTINGS = "privacy_settings"
62
63
  EMBEDDED_WEB_VIEW = "embedded_web_view"
63
64
  REMOTE_CONTROL = "remote_control"
@@ -105,12 +106,13 @@ module Fingerly
105
106
  HIGH_ACTIVITY, TAMPERING, DEVICE_FARM, DEVELOPER_TOOLS, GEO_MISMATCH, DEVICE_INCONSISTENT,
106
107
  TOR, PROXY, RESIDENTIAL_PROXY, RESIDENTIAL_PROXY_LOW_CONFIDENCE,
107
108
  RESIDENTIAL_PROXY_MEDIUM_CONFIDENCE, RESIDENTIAL_PROXY_HIGH_CONFIDENCE, VPN_PUBLIC,
108
- VPN_TIMEZONE, VPN_RELAY, VPN_MOBILE, VPN_OS_MISMATCH, VPN_LOW_CONFIDENCE,
109
+ VPN_RELAY, VPN_MOBILE, VPN_OS_MISMATCH, VPN_LOW_CONFIDENCE,
109
110
  VPN_MEDIUM_CONFIDENCE, VPN_HIGH_CONFIDENCE, IP_BLOCKLIST_EMAIL_SPAM,
110
111
  IP_BLOCKLIST_ATTACK_SOURCE, IP_ABUSER, DATACENTER_IP, BOGON_IP, ANYCAST_IP, INCOGNITO,
111
- BAD_BOT, AUTOMATION, FETCH_METADATA_MISSING, WEB_TICKET_MISSING, WEB_TICKET_INVALID,
112
- ANTIDETECT_BROWSER, VIRTUAL_MACHINE, FINGERPRINT_SUPPRESSED, PRIVACY_SETTINGS,
113
- EMBEDDED_WEB_VIEW, REMOTE_CONTROL, EMULATOR, ROOT_APPS, APP_CLONER, JAILBREAK, SIMULATOR,
112
+ BAD_BOT, AI_SPOOFED, AUTOMATION, FETCH_METADATA_MISSING, WEB_TICKET_MISSING,
113
+ WEB_TICKET_INVALID, ANTIDETECT_BROWSER, VIRTUAL_MACHINE, FINGERPRINT_SUPPRESSED,
114
+ IDENTITY_OBFUSCATED, PRIVACY_SETTINGS, EMBEDDED_WEB_VIEW, REMOTE_CONTROL, EMULATOR,
115
+ ROOT_APPS, APP_CLONER, JAILBREAK, SIMULATOR,
114
116
  FRIDA, MITM_ATTACK, ACTIVE_CALL, ATTESTATION_MISSING, ATTESTATION_DOWNGRADE,
115
117
  REPEATED_REINSTALL, DEVICE_ACTIVITY_HIGH, DEVICE_ACTIVITY_VERY_HIGH,
116
118
  PLAY_DEVICE_INTEGRITY_FAILED, PLAY_APP_UNRECOGNIZED, ATTESTATION_FAILED, REPORT_INCOMPLETE,
@@ -286,13 +288,72 @@ module Fingerly
286
288
  ALL = [DESKTOP, MOBILE, TABLET, SERVER].freeze
287
289
  end
288
290
 
289
- # What is behind a submission: {Event}'s +visitor_kind+.
291
+ # What is behind a submission: {Event}'s and {AgentSighting}'s +visitor_kind+.
290
292
  module VisitorKind
291
293
  HUMAN = "human"
292
294
  AI_BOT = "ai_bot"
293
295
  AUTOMATION = "automation"
294
296
  SEARCH_CRAWLER = "search_crawler"
297
+ # Only in an agent sightings answer: a request the server could not use;
298
+ # ttl 0, never remembered.
299
+ UNKNOWN = "unknown"
295
300
 
296
- ALL = [HUMAN, AI_BOT, AUTOMATION, SEARCH_CRAWLER].freeze
301
+ ALL = [HUMAN, AI_BOT, AUTOMATION, SEARCH_CRAWLER, UNKNOWN].freeze
302
+ end
303
+
304
+ # What an AI agent's operator says its traffic is for: {AiAgent}'s
305
+ # +purpose+. The API can add values, so keep an +else+ branch.
306
+ module AiPurpose
307
+ # Collecting content to train models.
308
+ TRAINING = "training"
309
+ # Indexing for an AI answer or search product.
310
+ SEARCH = "search"
311
+ # Reading a page a person asked an assistant to read.
312
+ USER_FETCH = "user_fetch"
313
+ # Driving a browser on a person's behalf.
314
+ AGENT = "agent"
315
+
316
+ ALL = [TRAINING, SEARCH, USER_FETCH, AGENT].freeze
317
+ end
318
+
319
+ # Where an AI agent runs: {AiAgent}'s +runtime+. The API can add values, so
320
+ # keep an +else+ branch.
321
+ module AiRuntime
322
+ # The operator's own infrastructure.
323
+ PROVIDER_CLOUD = "provider_cloud"
324
+ # A third party's cloud browser.
325
+ HOSTED_BROWSER = "hosted_browser"
326
+ # A person's own browser.
327
+ USER_DEVICE = "user_device"
328
+
329
+ ALL = [PROVIDER_CLOUD, HOSTED_BROWSER, USER_DEVICE].freeze
330
+ end
331
+
332
+ # How an AI agent's claimed identity was checked: {AiVerification}'s
333
+ # +method+. The API can add values, so keep an +else+ branch.
334
+ module AiVerificationMethod
335
+ # A signed request.
336
+ SIGNATURE = "signature"
337
+ # The operator's published address ranges.
338
+ IP_LIST = "ip_list"
339
+ # A reverse lookup confirmed forward.
340
+ REVERSE_DNS = "reverse_dns"
341
+ # No check was made.
342
+ NONE = "none"
343
+
344
+ ALL = [SIGNATURE, IP_LIST, REVERSE_DNS, NONE].freeze
345
+ end
346
+
347
+ # What checking an AI agent's identity found: {AiVerification}'s +result+.
348
+ # The API can add values, so keep an +else+ branch.
349
+ module AiVerificationResult
350
+ # The claim held.
351
+ PASS = "pass"
352
+ # The claim was checked and did not hold.
353
+ FAIL = "fail"
354
+ # No check was made.
355
+ NOT_ATTEMPTED = "not_attempted"
356
+
357
+ ALL = [PASS, FAIL, NOT_ATTEMPTED].freeze
297
358
  end
298
359
  end
@@ -49,13 +49,24 @@ module Fingerly
49
49
  # itself.
50
50
  attr_reader :retry_after
51
51
 
52
+ # @return [String, nil] which limit refused the call, from the
53
+ # +Fingerly-RateLimit-Scope+ header of a 429, such as +daily+ for an
54
+ # organization's daily allowance; see {RATE_LIMIT_SCOPE_DAILY}
55
+ attr_reader :rate_limit_scope
56
+
57
+ # The +Fingerly-RateLimit-Scope+ of a daily allowance: it resets at the
58
+ # next UTC day.
59
+ RATE_LIMIT_SCOPE_DAILY = "daily"
60
+
52
61
  # @api private
53
- def initialize(status:, code: nil, details: nil, request_id: nil, retry_after: nil)
62
+ def initialize(status:, code: nil, details: nil, request_id: nil, retry_after: nil,
63
+ rate_limit_scope: nil)
54
64
  @status = status
55
65
  @code = code
56
66
  @details = details
57
67
  @request_id = request_id
58
68
  @retry_after = retry_after
69
+ @rate_limit_scope = rate_limit_scope
59
70
  described = "Fingerly API returned HTTP #{status}"
60
71
  super(code ? "#{described} (#{code})" : described)
61
72
  end
@@ -147,11 +158,12 @@ module Fingerly
147
158
  @apple_status = parse_apple_status
148
159
  end
149
160
 
150
- # +404+: no token is held for that event. Decide without the bits.
161
+ # +404+: no token is held for that call. Decide without the bits.
151
162
  def not_held? = status == 404 && code == NOT_HELD
152
163
 
153
- # +409+: the token was already used, or this was a retry that is not the
154
- # request the token was first used for.
164
+ # +409+: the call's token was already used, a read's by a read or a
165
+ # write's by a write, or this was a retry that is not the request the
166
+ # token was first used for.
155
167
  def spent? = status == 409 && code == SPENT
156
168
 
157
169
  # +409+: another call is using the token right now.
@@ -187,10 +199,37 @@ module Fingerly
187
199
  # Raised when a request does not finish within its time limit.
188
200
  #
189
201
  # The deadline covers reading the response body, not only the headers.
190
- class TimeoutError < Error; end
202
+ class TimeoutError < Error
203
+ # @api private
204
+ def initialize(message = "The Fingerly request timed out", connected: true)
205
+ super(message)
206
+ @connected = connected
207
+ end
208
+
209
+ # Whether a connection to the API was open when the time ran out. When it
210
+ # was, the request may have reached the server, so sending it again could
211
+ # do its work twice; when it was not, nothing was sent.
212
+ #
213
+ # @return [Boolean]
214
+ def connected? = @connected
215
+ end
191
216
 
192
217
  # Raised when the Fingerly API could not be reached at all.
193
218
  #
194
- # A DNS failure, a refused connection or a TLS error arrives here.
195
- class ConnectionError < Error; end
219
+ # A DNS failure, a refused connection or a TLS error arrives here, and so
220
+ # does a connection lost or a response cut short once the request was sent.
221
+ class ConnectionError < Error
222
+ # @api private
223
+ def initialize(message = "Could not reach the Fingerly API", sent: false)
224
+ super(message)
225
+ @sent = sent
226
+ end
227
+
228
+ # Whether the whole request had been written when the connection failed.
229
+ # When it had, the server may have acted on it, so sending it again could
230
+ # do its work twice; when it had not, the server never saw all of it.
231
+ #
232
+ # @return [Boolean]
233
+ def sent? = @sent
234
+ end
196
235
  end
@@ -47,10 +47,10 @@ module Fingerly
47
47
 
48
48
  # @api private
49
49
  def initialize(payload)
50
- @signal = payload["signal"]
51
- @group = payload["group"]
52
- @weight = payload["weight"] || 0
53
- @confidence = payload["confidence"]
50
+ @signal = Models.string(payload["signal"])
51
+ @group = Models.string(payload["group"])
52
+ @weight = payload["weight"].is_a?(Integer) ? payload["weight"] : 0
53
+ @confidence = Models.string(payload["confidence"])
54
54
  freeze
55
55
  end
56
56
 
@@ -59,6 +59,109 @@ module Fingerly
59
59
  end
60
60
  end
61
61
 
62
+ # How an {AiAgent}'s claimed identity was checked, and what that found.
63
+ #
64
+ # The API always sends both values, so neither is ever nil.
65
+ class AiVerification
66
+ # @return [String] +signature+, +ip_list+, +reverse_dns+ or +none+;
67
+ # see {AiVerificationMethod}. Named for the wire field, so it hides
68
+ # +Object#method+ on this one class.
69
+ attr_reader :method
70
+ # @return [String] +pass+, +fail+ or +not_attempted+; see
71
+ # {AiVerificationResult}
72
+ attr_reader :result
73
+
74
+ # @api private
75
+ # @raise [Error] if either value is missing or not a string
76
+ def initialize(payload)
77
+ @method = Models.required_string(payload, "method", "AI agent verification")
78
+ @result = Models.required_string(payload, "result", "AI agent verification")
79
+ freeze
80
+ end
81
+
82
+ def inspect
83
+ "#<Fingerly::AiVerification method=#{@method.inspect} result=#{@result.inspect}>"
84
+ end
85
+ end
86
+
87
+ # The AI agent behind an event whose +visitor_kind+ is
88
+ # {VisitorKind::AI_BOT}.
89
+ #
90
+ # The agent is named by a Web Bot Auth signature when the request carried
91
+ # one, otherwise by its user agent. {#verification} says how far that was
92
+ # checked: {AiVerificationMethod::SIGNATURE} (the operator's published key
93
+ # signed the request) or {AiVerificationMethod::IP_LIST} (the address is
94
+ # inside the operator's published ranges), with result
95
+ # {AiVerificationResult::PASS}, {AiVerificationResult::FAIL} (the name was
96
+ # borrowed), or {AiVerificationResult::NOT_ATTEMPTED} with method
97
+ # {AiVerificationMethod::NONE} (the operator publishes nothing to check
98
+ # against, or it could not be checked; the name is then only the client's
99
+ # claim). {#purpose}, {#runtime} and the verification values are plain
100
+ # strings, so a value the API adds later still reads.
101
+ #
102
+ # The API sends every field of it, so none is ever nil: an answer without
103
+ # one raises {Error} when it is read, never later in your code.
104
+ class AiAgent
105
+ # @return [String] the agent as its operator names it, such as
106
+ # +ChatGPT-User+ or +Claude-User+
107
+ attr_reader :name
108
+ # @return [String] the company that operates it, such as +OpenAI+,
109
+ # +Anthropic+ or +Google+
110
+ attr_reader :provider
111
+ # @return [String] +training+, +search+, +user_fetch+ or +agent+; see
112
+ # {AiPurpose}
113
+ attr_reader :purpose
114
+ # @return [String] +provider_cloud+, +hosted_browser+ or +user_device+;
115
+ # see {AiRuntime}
116
+ attr_reader :runtime
117
+ # @return [Boolean] true when the agent named itself, in its user agent or
118
+ # a signature
119
+ attr_reader :declared
120
+ # @return [AiVerification] how the claimed identity was checked
121
+ attr_reader :verification
122
+
123
+ # The +ai+ object of an answer, or nil when the answer has none.
124
+ #
125
+ # @api private
126
+ # @raise [Error] if it is present but not an AI agent of the documented
127
+ # shape
128
+ def self.from(value)
129
+ return nil if value.nil?
130
+ return new(value) if value.is_a?(Hash)
131
+
132
+ raise Error, "Fingerly API returned an AI agent that is not an object"
133
+ end
134
+
135
+ # @api private
136
+ # @raise [Error] if a field is missing or of another type
137
+ def initialize(payload)
138
+ @name = Models.required_string(payload, "name", "AI agent")
139
+ @provider = Models.required_string(payload, "provider", "AI agent")
140
+ @purpose = Models.required_string(payload, "purpose", "AI agent")
141
+ @runtime = Models.required_string(payload, "runtime", "AI agent")
142
+ declared = payload["declared"]
143
+ unless [true, false].include?(declared)
144
+ raise Error, "Fingerly API returned an AI agent without a boolean declared"
145
+ end
146
+
147
+ @declared = declared
148
+ verification = payload["verification"]
149
+ unless verification.is_a?(Hash)
150
+ raise Error, "Fingerly API returned an AI agent without its verification"
151
+ end
152
+
153
+ @verification = AiVerification.new(verification)
154
+ freeze
155
+ end
156
+
157
+ def declared? = declared
158
+
159
+ def inspect
160
+ "#<Fingerly::AiAgent name=#{name.inspect} provider=#{provider.inspect} " \
161
+ "purpose=#{purpose.inspect}>"
162
+ end
163
+ end
164
+
62
165
  # A stored identification event.
63
166
  #
64
167
  # {#suspect_score} is +nil+ when the request was not scored, which must not
@@ -87,6 +190,11 @@ module Fingerly
87
190
  # @return [Array<EventTrigger>] the signal groups behind the score; never
88
191
  # nil, and empty when nothing fired
89
192
  attr_reader :triggers
193
+ # @return [AiAgent, nil] the AI agent behind the event, present only when
194
+ # +visitor_kind+ is {VisitorKind::AI_BOT}. The agent is named by a Web
195
+ # Bot Auth signature when the request carried one, otherwise by its user
196
+ # agent; see {AiAgent#verification} for how far that was checked.
197
+ attr_reader :ai
90
198
  # @return [Hash, nil] an allow-listed view of the archived request, when
91
199
  # one was kept: schema, request id, time, SDK, network, IP
92
200
  # classification and city-level location, risk, attestation and
@@ -101,17 +209,25 @@ module Fingerly
101
209
  # +occurred_at+ as nil rather than raising, for +events.verify+, which
102
210
  # answers +too_old+ for it
103
211
  # @api private
212
+ # @raise [Error] if the event is not an object, or its +ai+ is not an AI
213
+ # agent of the documented shape
104
214
  def initialize(payload, lenient_time: false)
105
- STRING_FIELDS.each { |name| instance_variable_set(:"@#{name}", payload[name]) }
215
+ raise Error, "Fingerly API returned an event that is not an object" unless payload.is_a?(Hash)
216
+
217
+ # A value of another JSON type reads as absent, so every reader returns
218
+ # the type it documents.
219
+ STRING_FIELDS.each { |name| instance_variable_set(:"@#{name}", Models.string(payload[name])) }
106
220
  @occurred_at = if lenient_time
107
221
  Models.rfc3339(payload["occurred_at"])
108
222
  else
109
223
  Models.parse_instant(payload["occurred_at"])
110
224
  end
111
- @suspect_score = payload["suspect_score"]
112
- @has_document = payload["has_document"] ? true : false
113
- @triggers = Array(payload["triggers"]).map { |item| EventTrigger.new(item) }.freeze
114
- @document = payload["document"]
225
+ @suspect_score = payload["suspect_score"].is_a?(Integer) ? payload["suspect_score"] : nil
226
+ @has_document = payload["has_document"] == true
227
+ triggers = payload["triggers"].is_a?(Array) ? payload["triggers"].grep(Hash) : []
228
+ @triggers = triggers.map { |item| EventTrigger.new(item) }.freeze
229
+ @ai = AiAgent.from(payload["ai"])
230
+ @document = payload["document"].is_a?(Hash) ? payload["document"] : nil
115
231
  @raw = payload
116
232
  freeze
117
233
  end
@@ -149,10 +265,16 @@ module Fingerly
149
265
  attr_reader :raw
150
266
 
151
267
  # @api private
268
+ # @raise [Error] if +rows+ is not a list of events
152
269
  def initialize(payload)
153
- @rows = Array(payload["rows"]).map { |item| Event.new(item) }.freeze
154
- @page = payload["page"] || 0
155
- @page_size = payload["page_size"] || 0
270
+ rows = payload["rows"]
271
+ unless rows.nil? || rows.is_a?(Array)
272
+ raise Error, "Fingerly API returned an event page whose rows are not a list"
273
+ end
274
+
275
+ @rows = Array(rows).map { |item| Event.new(item) }.freeze
276
+ @page = payload["page"].is_a?(Integer) ? payload["page"] : 0
277
+ @page_size = payload["page_size"].is_a?(Integer) ? payload["page_size"] : 0
156
278
  @raw = payload
157
279
  freeze
158
280
  end
@@ -314,13 +436,13 @@ module Fingerly
314
436
 
315
437
  # @api private
316
438
  def initialize(payload)
317
- @id = payload["id"]
318
- @type = payload["type"]
319
- @version = payload["version"]
320
- @organization_id = payload["organization_id"]
321
- @environment = payload["environment"]
439
+ @id = Models.string(payload["id"])
440
+ @type = Models.string(payload["type"])
441
+ @version = payload["version"].is_a?(Integer) ? payload["version"] : nil
442
+ @organization_id = Models.string(payload["organization_id"])
443
+ @environment = Models.string(payload["environment"])
322
444
  @created_at = payload["created_at"] ? Models.parse_instant(payload["created_at"]) : nil
323
- @data = payload["data"] || {}
445
+ @data = payload["data"].is_a?(Hash) ? payload["data"] : {}
324
446
  @raw = payload
325
447
  freeze
326
448
  end
@@ -330,12 +452,162 @@ module Fingerly
330
452
  end
331
453
  end
332
454
 
455
+ # One request your server served, as raw input for
456
+ # +fingerly.agents.report_sightings+. Nothing here is judged by the SDK: the
457
+ # server decides what sent it.
458
+ class AgentSightingInput
459
+ # @return [String] the +User-Agent+ header as received, or +""+
460
+ attr_reader :user_agent
461
+ # @return [String] the client's one IP literal, from a trusted source
462
+ attr_reader :client_ip
463
+ # @return [String, nil] the +Host+ the request was sent to
464
+ attr_reader :host
465
+ # @return [String, nil] the request method, sent as +method+
466
+ attr_reader :request_method
467
+ # @return [String, nil] the +Signature+ header
468
+ attr_reader :signature
469
+ # @return [String, nil] the +Signature-Input+ header
470
+ attr_reader :signature_input
471
+ # @return [String, nil] the +Signature-Agent+ header
472
+ attr_reader :signature_agent
473
+ # @return [Integer, nil] how many times this request was served since it
474
+ # was last reported, this one included
475
+ attr_reader :count
476
+
477
+ def initialize(user_agent:, client_ip:, host: nil, request_method: nil, signature: nil,
478
+ signature_input: nil, signature_agent: nil, count: nil)
479
+ @user_agent = user_agent
480
+ @client_ip = client_ip
481
+ @host = host
482
+ @request_method = request_method
483
+ @signature = signature
484
+ @signature_input = signature_input
485
+ @signature_agent = signature_agent
486
+ @count = count
487
+ freeze
488
+ end
489
+
490
+ # @return [Hash{String=>Object}] the item as the API reads it
491
+ def to_h
492
+ {
493
+ "user_agent" => user_agent, "client_ip" => client_ip, "host" => host,
494
+ "method" => request_method, "signature" => signature,
495
+ "signature_input" => signature_input, "signature_agent" => signature_agent,
496
+ "count" => count
497
+ }.compact
498
+ end
499
+
500
+ # The fields are a visitor's request; none of them is printed.
501
+ def inspect
502
+ "#<Fingerly::AgentSightingInput count=#{count.inspect}>"
503
+ end
504
+ end
505
+
506
+ # What the server said sent one reported request.
507
+ #
508
+ # {AgentSightings::UNKNOWN} is the one answer that did not come from the
509
+ # server: nothing is known yet, so serve the request as usual.
510
+ class AgentSighting
511
+ # @return [Integer] seconds this answer may be reused for the same user
512
+ # agent, address and +Signature-Agent+; 0 for a signed request
513
+ attr_reader :ttl
514
+ # @return [String] +human+, +ai_bot+, +automation+ or +search_crawler+;
515
+ # see {VisitorKind}. {VisitorKind::UNKNOWN}, with a ttl of 0, marks a
516
+ # request the server could not use; it is never remembered. The API can
517
+ # add values, so keep an +else+ branch.
518
+ attr_reader :visitor_kind
519
+ # @return [String, nil] the agent's name where the server knows it, such
520
+ # as +GPTBot+ or +Googlebot+
521
+ attr_reader :agent
522
+ # @return [AiAgent, nil] present when {#visitor_kind} is
523
+ # {VisitorKind::AI_BOT}
524
+ attr_reader :ai
525
+
526
+ # @api private
527
+ # @raise [Error] if +ai+ is present but not an AI agent of the documented
528
+ # shape
529
+ def initialize(payload)
530
+ ttl = payload["ttl"]
531
+ @ttl = ttl.is_a?(Integer) && ttl.positive? ? ttl : 0
532
+ kind = payload["visitor_kind"]
533
+ @visitor_kind = kind.is_a?(String) ? kind : ""
534
+ @agent = payload["agent"].is_a?(String) ? payload["agent"] : nil
535
+ @ai = AiAgent.from(payload["ai"])
536
+ freeze
537
+ end
538
+
539
+ def inspect
540
+ "#<Fingerly::AgentSighting visitor_kind=#{visitor_kind.inspect} agent=#{agent.inspect} " \
541
+ "ttl=#{ttl}>"
542
+ end
543
+ end
544
+
545
+ # The server's answer to +fingerly.agents.report_sightings+.
546
+ class AgentSightingsReport
547
+ # @return [String] names the classification rules; when it changes, every
548
+ # remembered answer is stale
549
+ attr_reader :rules_version
550
+ # @return [Array<AgentSighting>] one answer per reported request, in the
551
+ # same order. An item that is not an answer of the documented shape,
552
+ # such as one whose +ai+ lacks its verification, is
553
+ # {AgentSightings::UNKNOWN}: the others still count.
554
+ attr_reader :items
555
+ # @return [Hash] the response body exactly as it arrived
556
+ attr_reader :raw
557
+
558
+ # @api private
559
+ # @raise [Error] if the body is not an answer of this shape
560
+ def initialize(payload)
561
+ items = payload["items"]
562
+ version = payload["rules_version"]
563
+ unless items.is_a?(Array) && version.is_a?(String)
564
+ raise Error, "Fingerly API returned an agent sightings answer of another shape"
565
+ end
566
+
567
+ @rules_version = version
568
+ @items = items.map { |item| AgentSightingsReport.answer(item) }.freeze
569
+ @raw = payload
570
+ freeze
571
+ end
572
+
573
+ # One item as an answer, or {AgentSightings::UNKNOWN} when it is not one.
574
+ #
575
+ # @api private
576
+ def self.answer(item)
577
+ return AgentSightings::UNKNOWN unless item.is_a?(Hash)
578
+
579
+ AgentSighting.new(item)
580
+ rescue Error
581
+ AgentSightings::UNKNOWN
582
+ end
583
+
584
+ def inspect
585
+ "#<Fingerly::AgentSightingsReport rules_version=#{rules_version.inspect} " \
586
+ "items=#{items.size}>"
587
+ end
588
+ end
589
+
333
590
  # Shared decoding helpers.
334
591
  #
335
592
  # @api private
336
593
  module Models
337
594
  module_function
338
595
 
596
+ # @return [String, nil] the value when it is a string, otherwise nil
597
+ def string(value)
598
+ value.is_a?(String) ? value : nil
599
+ end
600
+
601
+ # A string field the contract requires.
602
+ #
603
+ # @raise [Error] if it is missing or not a string
604
+ def required_string(payload, name, what)
605
+ value = payload[name]
606
+ return value if value.is_a?(String)
607
+
608
+ raise Error, "Fingerly API returned an #{what} without a string #{name}"
609
+ end
610
+
339
611
  # Reads an RFC 3339 timestamp into a Time.
340
612
  #
341
613
  # @raise [Error] if the API sent something that is not one
@@ -117,6 +117,15 @@ module Fingerly
117
117
  sec-ch-ua sec-ch-ua-mobile sec-ch-ua-platform
118
118
  ].freeze
119
119
 
120
+ # Web Bot Auth headers an AI agent's browser signs the request with,
121
+ # forwarded when present, header-safe and at most
122
+ # +MAX_SIGNATURE_HEADER_BYTES+. The API ignores a longer one, so it is
123
+ # dropped here rather than refused.
124
+ SIGNATURE_HEADERS = %w[signature signature-input signature-agent].freeze
125
+
126
+ # The longest Web Bot Auth header value forwarded, in bytes.
127
+ MAX_SIGNATURE_HEADER_BYTES = 4096
128
+
120
129
  # Upstream statuses that can be relayed; 3xx inside this range is not.
121
130
  RELAYABLE_STATUS = (200..599)
122
131
 
@@ -324,7 +333,7 @@ module Fingerly
324
333
  def client_address(env, request)
325
334
  address = begin
326
335
  @client_ip.call(request)
327
- rescue StandardError => e
336
+ rescue *Config::CALLBACK_ERRORS => e
328
337
  e
329
338
  end
330
339
  return address if Config.ip_literal?(address)
@@ -360,7 +369,7 @@ module Fingerly
360
369
  def log(env, line)
361
370
  logger = @logger || env["rack.logger"]
362
371
  logger ? logger.warn(line) : warn(line)
363
- rescue StandardError
372
+ rescue *Config::CALLBACK_ERRORS
364
373
  # A broken logger must not turn a gateway error into a crash.
365
374
  nil
366
375
  end
@@ -412,6 +421,10 @@ module Fingerly
412
421
  value = non_blank(safe(request.header(name)))
413
422
  headers[name] = value if value
414
423
  end
424
+ SIGNATURE_HEADERS.each do |name|
425
+ value = non_blank(safe(request.header(name)))
426
+ headers[name] = value if value && value.bytesize <= MAX_SIGNATURE_HEADER_BYTES
427
+ end
415
428
  headers
416
429
  end
417
430