fingerly 0.2.0 → 0.4.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.
@@ -0,0 +1,282 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Named constants for the closed string sets the API sends.
4
+ #
5
+ # Every constant is the frozen wire string itself, so it compares equal to the
6
+ # field it names (+event.suspect_level == Fingerly::SuspectLevel::HIGH+) and
7
+ # the fields stay plain strings. A value the server adds after this SDK was
8
+ # released still arrives unchanged; it is only missing from +ALL+.
9
+ #
10
+ # Each module's +ALL+ is a frozen array of its values, in the order listed.
11
+ module Fingerly
12
+ # Identifiers a trigger's +signal+ (and +group+) can hold.
13
+ #
14
+ # Event reads report each trigger under its signal group, such as +vpn+;
15
+ # +visitor.suspect+ webhooks and the archived document's +risk.triggers+
16
+ # carry the detector, such as +vpn_public+, with its group beside it. Many
17
+ # groups share their detector's name, so each identifier is here once.
18
+ #
19
+ # Inside +module Fingerly+, this constant shadows Ruby's own +::Signal+.
20
+ module Signal
21
+ # Detectors every platform can produce.
22
+ HIGH_ACTIVITY = "high_activity"
23
+ TAMPERING = "tampering"
24
+ DEVICE_FARM = "device_farm"
25
+ DEVELOPER_TOOLS = "developer_tools"
26
+ GEO_MISMATCH = "geo_mismatch"
27
+ DEVICE_INCONSISTENT = "device_inconsistent"
28
+
29
+ # Detectors derived from the address a submission arrived from.
30
+ TOR = "tor"
31
+ PROXY = "proxy"
32
+ RESIDENTIAL_PROXY = "residential_proxy"
33
+ RESIDENTIAL_PROXY_LOW_CONFIDENCE = "residential_proxy_low_confidence"
34
+ RESIDENTIAL_PROXY_MEDIUM_CONFIDENCE = "residential_proxy_medium_confidence"
35
+ RESIDENTIAL_PROXY_HIGH_CONFIDENCE = "residential_proxy_high_confidence"
36
+ VPN_PUBLIC = "vpn_public"
37
+ VPN_TIMEZONE = "vpn_timezone"
38
+ VPN_RELAY = "vpn_relay"
39
+ VPN_MOBILE = "vpn_mobile"
40
+ VPN_OS_MISMATCH = "vpn_os_mismatch"
41
+ VPN_LOW_CONFIDENCE = "vpn_low_confidence"
42
+ VPN_MEDIUM_CONFIDENCE = "vpn_medium_confidence"
43
+ VPN_HIGH_CONFIDENCE = "vpn_high_confidence"
44
+ IP_BLOCKLIST_EMAIL_SPAM = "ip_blocklist_email_spam"
45
+ IP_BLOCKLIST_ATTACK_SOURCE = "ip_blocklist_attack_source"
46
+ IP_ABUSER = "ip_abuser"
47
+ DATACENTER_IP = "datacenter_ip"
48
+ BOGON_IP = "bogon_ip"
49
+ ANYCAST_IP = "anycast_ip"
50
+
51
+ # Detectors only a browser can produce.
52
+ INCOGNITO = "incognito"
53
+ BAD_BOT = "bad_bot"
54
+ AUTOMATION = "automation"
55
+ FETCH_METADATA_MISSING = "fetch_metadata_missing"
56
+ WEB_TICKET_MISSING = "web_ticket_missing"
57
+ WEB_TICKET_INVALID = "web_ticket_invalid"
58
+ ANTIDETECT_BROWSER = "antidetect_browser"
59
+ VIRTUAL_MACHINE = "virtual_machine"
60
+ FINGERPRINT_SUPPRESSED = "fingerprint_suppressed"
61
+ PRIVACY_SETTINGS = "privacy_settings"
62
+ EMBEDDED_WEB_VIEW = "embedded_web_view"
63
+ REMOTE_CONTROL = "remote_control"
64
+
65
+ # Detectors only a native application can produce.
66
+ EMULATOR = "emulator"
67
+ ROOT_APPS = "root_apps"
68
+ APP_CLONER = "app_cloner"
69
+ JAILBREAK = "jailbreak"
70
+ SIMULATOR = "simulator"
71
+ FRIDA = "frida"
72
+ MITM_ATTACK = "mitm_attack"
73
+ ACTIVE_CALL = "active_call"
74
+ ATTESTATION_MISSING = "attestation_missing"
75
+ ATTESTATION_DOWNGRADE = "attestation_downgrade"
76
+ REPEATED_REINSTALL = "repeated_reinstall"
77
+ DEVICE_ACTIVITY_HIGH = "device_activity_high"
78
+ DEVICE_ACTIVITY_VERY_HIGH = "device_activity_very_high"
79
+ PLAY_DEVICE_INTEGRITY_FAILED = "play_device_integrity_failed"
80
+ PLAY_APP_UNRECOGNIZED = "play_app_unrecognized"
81
+ ATTESTATION_FAILED = "attestation_failed"
82
+ REPORT_INCOMPLETE = "report_incomplete"
83
+ PROBE_ERRORS = "probe_errors"
84
+ CUSTOM_ROOT_CA = "custom_root_ca"
85
+ SECONDARY_USER_PROFILE = "secondary_user_profile"
86
+
87
+ # Signal groups whose name is not also a detector's.
88
+ DATACENTER_PROXY = "datacenter_proxy"
89
+ VPN = "vpn"
90
+ IP_BLOCKLIST = "ip_blocklist"
91
+ IP_REPUTATION = "ip_reputation"
92
+ NETWORK_ANOMALY = "network_anomaly"
93
+ LOCATION_SPOOFING = "location_spoofing"
94
+ IOS_SIMULATOR = "ios_simulator"
95
+ ANDROID_EMULATOR = "android_emulator"
96
+ JAILBROKEN_DEVICE = "jailbroken_device"
97
+ ROOTED_DEVICE = "rooted_device"
98
+ CLONED_APP = "cloned_app"
99
+ FRIDA_DETECTED = "frida_detected"
100
+ BROWSER_TAMPERING = "browser_tampering"
101
+ BOT = "bot"
102
+ INCOGNITO_MODE = "incognito_mode"
103
+
104
+ ALL = [
105
+ HIGH_ACTIVITY, TAMPERING, DEVICE_FARM, DEVELOPER_TOOLS, GEO_MISMATCH, DEVICE_INCONSISTENT,
106
+ TOR, PROXY, RESIDENTIAL_PROXY, RESIDENTIAL_PROXY_LOW_CONFIDENCE,
107
+ 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_MEDIUM_CONFIDENCE, VPN_HIGH_CONFIDENCE, IP_BLOCKLIST_EMAIL_SPAM,
110
+ 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,
114
+ FRIDA, MITM_ATTACK, ACTIVE_CALL, ATTESTATION_MISSING, ATTESTATION_DOWNGRADE,
115
+ REPEATED_REINSTALL, DEVICE_ACTIVITY_HIGH, DEVICE_ACTIVITY_VERY_HIGH,
116
+ PLAY_DEVICE_INTEGRITY_FAILED, PLAY_APP_UNRECOGNIZED, ATTESTATION_FAILED, REPORT_INCOMPLETE,
117
+ PROBE_ERRORS, CUSTOM_ROOT_CA, SECONDARY_USER_PROFILE, DATACENTER_PROXY, VPN, IP_BLOCKLIST,
118
+ IP_REPUTATION, NETWORK_ANOMALY, LOCATION_SPOOFING, IOS_SIMULATOR, ANDROID_EMULATOR,
119
+ JAILBROKEN_DEVICE, ROOTED_DEVICE, CLONED_APP, FRIDA_DETECTED, BROWSER_TAMPERING, BOT,
120
+ INCOGNITO_MODE
121
+ ].freeze
122
+ end
123
+
124
+ # An event's +suspect_level+, and the +level+ of identification webhooks:
125
+ # the score, banded.
126
+ module SuspectLevel
127
+ LOW = "low"
128
+ MEDIUM = "medium"
129
+ HIGH = "high"
130
+
131
+ ALL = [LOW, MEDIUM, HIGH].freeze
132
+ end
133
+
134
+ # How sure a detection is: {EventTrigger#confidence}.
135
+ module Confidence
136
+ LOW = "low"
137
+ MEDIUM = "medium"
138
+ HIGH = "high"
139
+
140
+ ALL = [LOW, MEDIUM, HIGH].freeze
141
+ end
142
+
143
+ # The server's verdict on a native event's hardware evidence: the archived
144
+ # document's +attestation.state+.
145
+ module AttestationState
146
+ ATTESTED = "attested"
147
+ NOT_ATTESTED = "not_attested"
148
+ FAILED = "failed"
149
+
150
+ ALL = [ATTESTED, NOT_ATTESTED, FAILED].freeze
151
+ end
152
+
153
+ # The detail behind {AttestationState}: the archived document's
154
+ # +attestation.status+.
155
+ module AttestationStatus
156
+ VERIFIED = "verified"
157
+ INDETERMINATE = "indeterminate"
158
+ INVALID = "invalid"
159
+ ABSENT = "absent"
160
+ UNCONFIGURED = "unconfigured"
161
+
162
+ ALL = [VERIFIED, INDETERMINATE, INVALID, ABSENT, UNCONFIGURED].freeze
163
+ end
164
+
165
+ # Why a native app sent no attestation: the archived document's
166
+ # +attestation.attest_skipped+. Diagnostic only; it never lowers the score.
167
+ module AttestSkippedReason
168
+ NOT_OFFERED = "not_offered"
169
+ UNSUPPORTED = "unsupported"
170
+ CHALLENGE_UNAVAILABLE = "challenge_unavailable"
171
+ KEY_ERROR = "key_error"
172
+ TIMEOUT = "timeout"
173
+ BACKOFF = "backoff"
174
+ INSTALL_UNAVAILABLE = "install_unavailable"
175
+
176
+ ALL = [
177
+ NOT_OFFERED, UNSUPPORTED, CHALLENGE_UNAVAILABLE, KEY_ERROR, TIMEOUT, BACKOFF,
178
+ INSTALL_UNAVAILABLE
179
+ ].freeze
180
+ end
181
+
182
+ # Why +fingerly.events.verify+ refused an event: {EventVerification#reason}.
183
+ # +OK+ is the +""+ of an event that passed; the failures follow in the order
184
+ # the checks run.
185
+ module VerifyReason
186
+ OK = ""
187
+ NOT_FOUND = "not_found"
188
+ TOO_OLD = "too_old"
189
+ TAG_MISMATCH = "tag_mismatch"
190
+ UNIDENTIFIABLE = "unidentifiable"
191
+ UNSCORED = "unscored"
192
+ ALREADY_CONSUMED = "already_consumed"
193
+
194
+ ALL = [OK, NOT_FOUND, TOO_OLD, TAG_MISMATCH, UNIDENTIFIABLE, UNSCORED, ALREADY_CONSUMED].freeze
195
+ end
196
+
197
+ # A webhook delivery's {WebhookEvent#type}. +WEBHOOK_TEST+ is sent to one
198
+ # endpoint on request and cannot be subscribed to.
199
+ module WebhookEventType
200
+ IDENTIFICATION_COMPLETED = "identification.completed"
201
+ IDENTIFICATION_REFUSED = "identification.refused"
202
+ VISITOR_SUSPECT = "visitor.suspect"
203
+ BILLING_STATUS_CHANGED = "billing.status_changed"
204
+ USAGE_DAILY_SETTLED = "usage.daily_settled"
205
+ WEBHOOK_TEST = "webhook.test"
206
+
207
+ ALL = [
208
+ IDENTIFICATION_COMPLETED, IDENTIFICATION_REFUSED, VISITOR_SUSPECT, BILLING_STATUS_CHANGED,
209
+ USAGE_DAILY_SETTLED, WEBHOOK_TEST
210
+ ].freeze
211
+ end
212
+
213
+ # A webhook delivery's {WebhookEvent#environment}.
214
+ module WebhookEnvironment
215
+ LIVE = "live"
216
+ TEST = "test"
217
+
218
+ ALL = [LIVE, TEST].freeze
219
+ end
220
+
221
+ # An event's +state+: enriched, or unavailable when the network lookup
222
+ # could not run. +PENDING+ is accepted and not yet written; an event read
223
+ # answers it as a pending error rather than as an event.
224
+ module EventState
225
+ PENDING = "pending"
226
+ ENRICHED = "enriched"
227
+ UNAVAILABLE = "unavailable"
228
+
229
+ ALL = [PENDING, ENRICHED, UNAVAILABLE].freeze
230
+ end
231
+
232
+ # The environment an event was recorded in: {Event}'s +environment+.
233
+ module Environment
234
+ PRODUCTION = "production"
235
+ STAGING = "staging"
236
+ DEVELOPMENT = "development"
237
+
238
+ ALL = [PRODUCTION, STAGING, DEVELOPMENT].freeze
239
+ end
240
+
241
+ # The scoring profile an event was scored under: {Event}'s +platform+.
242
+ # +sdk_platform+ is what the SDK called itself and is not limited to these.
243
+ module Platform
244
+ WEB = "web"
245
+ ANDROID = "android"
246
+ IOS = "ios"
247
+
248
+ ALL = [WEB, ANDROID, IOS].freeze
249
+ end
250
+
251
+ # The anonymity network an event's address belongs to: {Event}'s
252
+ # +anonymity_network+, nil on an ordinary connection.
253
+ module AnonymityNetwork
254
+ TOR = "tor"
255
+ RELAY = "relay"
256
+ VPN = "vpn"
257
+ PROXY = "proxy"
258
+ HOSTING = "hosting"
259
+
260
+ ALL = [TOR, RELAY, VPN, PROXY, HOSTING].freeze
261
+ end
262
+
263
+ # What the fingerprint was taken on: {Event}'s +device_kind+.
264
+ module DeviceKind
265
+ DESKTOP = "desktop"
266
+ MOBILE = "mobile"
267
+ TABLET = "tablet"
268
+ SERVER = "server"
269
+
270
+ ALL = [DESKTOP, MOBILE, TABLET, SERVER].freeze
271
+ end
272
+
273
+ # What is behind a submission: {Event}'s +visitor_kind+.
274
+ module VisitorKind
275
+ HUMAN = "human"
276
+ AI_BOT = "ai_bot"
277
+ AUTOMATION = "automation"
278
+ SEARCH_CRAWLER = "search_crawler"
279
+
280
+ ALL = [HUMAN, AI_BOT, AUTOMATION, SEARCH_CRAWLER].freeze
281
+ end
282
+ end
@@ -81,6 +81,107 @@ module Fingerly
81
81
  def pending?
82
82
  status == 404 && code == "event_pending"
83
83
  end
84
+
85
+ # Whether this is a consume for an event that was already consumed
86
+ # (+409 event_already_consumed+). Such an answer raises
87
+ # {EventAlreadyConsumedError}.
88
+ #
89
+ # @return [Boolean]
90
+ def event_already_consumed?
91
+ status == 409 && code == EventAlreadyConsumedError::CODE
92
+ end
93
+ end
94
+
95
+ # Raised when +fingerly.events.consume+ finds the event already consumed
96
+ # (+409 event_already_consumed+).
97
+ #
98
+ # It is an {APIError}, so +rescue Fingerly::APIError+ still catches it.
99
+ #
100
+ # begin
101
+ # fingerly.events.consume(request_id)
102
+ # rescue Fingerly::EventAlreadyConsumedError => e
103
+ # return "refuse" # another decision already used it, at e.consumed_at
104
+ # end
105
+ class EventAlreadyConsumedError < APIError
106
+ CODE = "event_already_consumed"
107
+
108
+ # @return [String, nil] when the event was first consumed, as the API
109
+ # sent it (RFC 3339), or nil when the answer did not say
110
+ attr_reader :consumed_at
111
+
112
+ # @api private
113
+ def initialize(consumed_at: nil, **)
114
+ super(**)
115
+ @consumed_at = consumed_at
116
+ end
117
+ end
118
+
119
+ # Raised for any non-2xx answer to a DeviceCheck read or write.
120
+ #
121
+ # It is an {APIError}, so +rescue Fingerly::APIError+ still catches it; each
122
+ # documented code has its own predicate.
123
+ #
124
+ # begin
125
+ # bits = fingerly.device_check.query(request_id)
126
+ # rescue Fingerly::DeviceCheckError => e
127
+ # raise unless e.not_held? || e.spent? || e.apple_rejected?
128
+ #
129
+ # bits = nil # no answer, not a verdict: decide without the bits
130
+ # end
131
+ class DeviceCheckError < APIError
132
+ NOT_HELD = "device_check_not_held"
133
+ SPENT = "device_check_spent"
134
+ BUSY = "device_check_busy"
135
+ CREDENTIAL_UNAVAILABLE = "credential_unavailable"
136
+ BITS_REQUIRED = "bits_required"
137
+ APPLE_REJECTED = "apple_rejected"
138
+ UNAVAILABLE = "device_check_unavailable"
139
+
140
+ # @return [Integer, nil] Apple's HTTP status for +apple_rejected+, from
141
+ # the +apple_status+ entry of {#details}; nil for any other code
142
+ attr_reader :apple_status
143
+
144
+ # @api private
145
+ def initialize(**)
146
+ super
147
+ @apple_status = parse_apple_status
148
+ end
149
+
150
+ # +404+: no token is held for that event. Decide without the bits.
151
+ def not_held? = status == 404 && code == NOT_HELD
152
+
153
+ # +409+: the token was already used, or this was a retry that is not the
154
+ # request the token was first used for.
155
+ def spent? = status == 409 && code == SPENT
156
+
157
+ # +409+: another call is using the token right now.
158
+ def busy? = status == 409 && code == BUSY
159
+
160
+ # +409+: the project's Apple key is missing, refused, or has DeviceCheck
161
+ # off. The token is kept: fix the key, then retry the same request.
162
+ def credential_unavailable? = status == 409 && code == CREDENTIAL_UNAVAILABLE
163
+
164
+ # +422+: a write named neither bit.
165
+ def bits_required? = status == 422 && code == BITS_REQUIRED
166
+
167
+ # +422+: Apple rejected the token, which is now used up. See
168
+ # {#apple_status}.
169
+ def apple_rejected? = status == 422 && code == APPLE_REJECTED
170
+
171
+ # +503+: Apple or Fingerly's storage could not answer, after the retries
172
+ # the client already made. The token is kept: retry the same request
173
+ # within the hour.
174
+ def unavailable? = status == 503 && code == UNAVAILABLE
175
+
176
+ private
177
+
178
+ def parse_apple_status
179
+ return nil unless code == APPLE_REJECTED && details.is_a?(Array)
180
+
181
+ entry = details.find { |item| item.is_a?(Hash) && item["field"] == "apple_status" }
182
+ issue = entry && entry["issue"]
183
+ issue.is_a?(String) && issue.match?(/\A\d{3}\z/) ? Integer(issue, 10) : nil
184
+ end
84
185
  end
85
186
 
86
187
  # Raised when a request does not finish within its time limit.
@@ -4,17 +4,51 @@ require "time"
4
4
 
5
5
  module Fingerly
6
6
  # One signal group that contributed to an event's suspect score.
7
+ #
8
+ # The +SIGNAL_*+ constants are the same strings as {Signal}'s.
7
9
  class EventTrigger
8
- # @return [String, nil] the signal group, such as +vpn+ or +bot+
10
+ SIGNAL_ATTESTATION_FAILED = Signal::ATTESTATION_FAILED
11
+ SIGNAL_ATTESTATION_MISSING = Signal::ATTESTATION_MISSING
12
+ SIGNAL_ATTESTATION_DOWNGRADE = Signal::ATTESTATION_DOWNGRADE
13
+ SIGNAL_DEVICE_INCONSISTENT = Signal::DEVICE_INCONSISTENT
14
+ SIGNAL_REPORT_INCOMPLETE = Signal::REPORT_INCOMPLETE
15
+ SIGNAL_PROBE_ERRORS = Signal::PROBE_ERRORS
16
+ SIGNAL_FETCH_METADATA_MISSING = Signal::FETCH_METADATA_MISSING
17
+ SIGNAL_WEB_TICKET_MISSING = Signal::WEB_TICKET_MISSING
18
+ SIGNAL_WEB_TICKET_INVALID = Signal::WEB_TICKET_INVALID
19
+ SIGNAL_TAMPERING = Signal::TAMPERING
20
+ SIGNAL_BROWSER_TAMPERING = Signal::BROWSER_TAMPERING
21
+ SIGNAL_CUSTOM_ROOT_CA = Signal::CUSTOM_ROOT_CA
22
+ SIGNAL_SECONDARY_USER_PROFILE = Signal::SECONDARY_USER_PROFILE
23
+
24
+ V3_SIGNALS = [
25
+ SIGNAL_ATTESTATION_FAILED,
26
+ SIGNAL_ATTESTATION_DOWNGRADE,
27
+ SIGNAL_DEVICE_INCONSISTENT,
28
+ SIGNAL_REPORT_INCOMPLETE,
29
+ SIGNAL_PROBE_ERRORS,
30
+ SIGNAL_FETCH_METADATA_MISSING,
31
+ SIGNAL_WEB_TICKET_MISSING,
32
+ SIGNAL_WEB_TICKET_INVALID,
33
+ SIGNAL_TAMPERING,
34
+ SIGNAL_CUSTOM_ROOT_CA,
35
+ SIGNAL_SECONDARY_USER_PROFILE
36
+ ].freeze
37
+
38
+ # @return [String, nil] the signal or signal group, such as +vpn+ or
39
+ # +attestation_failed+; see {Signal}
9
40
  attr_reader :signal
41
+ # @return [String, nil] optional group identifier when returned alongside a raw signal
42
+ attr_reader :group
10
43
  # @return [Integer] the group's combined weight in this score
11
44
  attr_reader :weight
12
- # @return [String, nil] +low+, +medium+ or +high+
45
+ # @return [String, nil] +low+, +medium+ or +high+; see {Confidence}
13
46
  attr_reader :confidence
14
47
 
15
48
  # @api private
16
49
  def initialize(payload)
17
50
  @signal = payload["signal"]
51
+ @group = payload["group"]
18
52
  @weight = payload["weight"] || 0
19
53
  @confidence = payload["confidence"]
20
54
  freeze
@@ -33,11 +67,12 @@ module Fingerly
33
67
  # the distinction at the call site.
34
68
  class Event
35
69
  # Fields copied straight from the response, in the order the API documents
36
- # them. Anything not listed stays reachable through {#raw}. +project_id+
37
- # is the UUID string of the Fingerly project the event belongs to, and nil
38
- # when an older server does not send it.
70
+ # them. Anything not listed stays reachable through {#raw}. +visitor_id+ is
71
+ # +""+ when the submission was unidentifiable, +reason+ explains why
72
+ # enrichment did not happen when unavailable, and +project_id+ is the UUID
73
+ # string of the Fingerly project the event belongs to (nil on older servers).
39
74
  STRING_FIELDS = %w[
40
- request_id project_id visitor_id state environment platform sdk_platform
75
+ request_id project_id visitor_id state reason environment platform sdk_platform
41
76
  sdk_version origin url_host url_path tag ip_network country_code
42
77
  country_name asn asn_name anonymity_network agent agent_version os
43
78
  device_kind visitor_kind suspect_level
@@ -62,10 +97,17 @@ module Fingerly
62
97
  # API adds after this SDK was released needs no upgrade
63
98
  attr_reader :raw
64
99
 
100
+ # @param lenient_time [Boolean] keeps a missing or malformed
101
+ # +occurred_at+ as nil rather than raising, for +events.verify+, which
102
+ # answers +too_old+ for it
65
103
  # @api private
66
- def initialize(payload)
104
+ def initialize(payload, lenient_time: false)
67
105
  STRING_FIELDS.each { |name| instance_variable_set(:"@#{name}", payload[name]) }
68
- @occurred_at = Models.parse_instant(payload["occurred_at"])
106
+ @occurred_at = if lenient_time
107
+ Models.rfc3339(payload["occurred_at"])
108
+ else
109
+ Models.parse_instant(payload["occurred_at"])
110
+ end
69
111
  @suspect_score = payload["suspect_score"]
70
112
  @has_document = payload["has_document"] ? true : false
71
113
  @triggers = Array(payload["triggers"]).map { |item| EventTrigger.new(item) }.freeze
@@ -125,6 +167,129 @@ module Fingerly
125
167
  end
126
168
  end
127
169
 
170
+ # The first consumption of an event, from +fingerly.events.consume+.
171
+ class EventConsumption
172
+ # @return [String, nil] the consumed event's request id
173
+ attr_reader :request_id
174
+ # @return [String, nil] when it was consumed, as the API sent it (RFC 3339)
175
+ attr_reader :consumed_at
176
+ # @return [Boolean] true for the call that consumed the event
177
+ attr_reader :first
178
+ # @return [Hash] the response body exactly as it arrived
179
+ attr_reader :raw
180
+
181
+ # @api private
182
+ def initialize(payload)
183
+ @request_id = payload["request_id"].is_a?(String) ? payload["request_id"] : nil
184
+ @consumed_at = payload["consumed_at"].is_a?(String) ? payload["consumed_at"] : nil
185
+ @first = payload["first"] == true
186
+ @raw = payload
187
+ freeze
188
+ end
189
+
190
+ def first? = first
191
+
192
+ def inspect
193
+ "#<Fingerly::EventConsumption request_id=#{request_id.inspect} first=#{first}>"
194
+ end
195
+ end
196
+
197
+ # The answer of +fingerly.events.verify+.
198
+ #
199
+ # {#reason} is +""+ when {#ok?}, and otherwise the first check that failed,
200
+ # as one of the {VerifyReason} strings. The score is not checked: apply your own
201
+ # policy to {#event} after {#ok?}.
202
+ class EventVerification
203
+ NOT_FOUND = VerifyReason::NOT_FOUND
204
+ TOO_OLD = VerifyReason::TOO_OLD
205
+ TAG_MISMATCH = VerifyReason::TAG_MISMATCH
206
+ UNIDENTIFIABLE = VerifyReason::UNIDENTIFIABLE
207
+ UNSCORED = VerifyReason::UNSCORED
208
+ ALREADY_CONSUMED = VerifyReason::ALREADY_CONSUMED
209
+
210
+ # Every failure reason, in the order the checks run.
211
+ REASONS = [NOT_FOUND, TOO_OLD, TAG_MISMATCH, UNIDENTIFIABLE, UNSCORED, ALREADY_CONSUMED].freeze
212
+
213
+ # @return [Boolean] whether every check passed
214
+ attr_reader :ok
215
+ # @return [String] the failed check, or +""+ when {#ok}
216
+ attr_reader :reason
217
+ # @return [Event, nil] the event read; nil only for +not_found+
218
+ attr_reader :event
219
+
220
+ # @api private
221
+ def initialize(reason:, event:)
222
+ @ok = reason.empty?
223
+ @reason = reason
224
+ @event = event
225
+ freeze
226
+ end
227
+
228
+ def ok? = ok
229
+
230
+ def inspect
231
+ "#<Fingerly::EventVerification ok=#{ok} reason=#{reason.inspect}>"
232
+ end
233
+ end
234
+
235
+ # What Apple holds for the device behind an event, from
236
+ # +fingerly.device_check.query+. The bits mean what you decide; Fingerly
237
+ # never reads them.
238
+ class DeviceCheckBits
239
+ # @return [Boolean] false when Apple holds no bits for the device yet;
240
+ # both bits are then false
241
+ attr_reader :found
242
+ # @return [Boolean] the first bit
243
+ attr_reader :bit0
244
+ # @return [Boolean] the second bit
245
+ attr_reader :bit1
246
+ # @return [String, nil] when the bits last changed, as +YYYY-MM+; nil when
247
+ # Apple holds no bits
248
+ attr_reader :last_update
249
+ # @return [Hash] the response body exactly as it arrived
250
+ attr_reader :raw
251
+
252
+ # @api private
253
+ def initialize(payload)
254
+ @found = payload["found"] == true
255
+ @bit0 = payload["bit0"] == true
256
+ @bit1 = payload["bit1"] == true
257
+ @last_update = payload["last_update"].is_a?(String) ? payload["last_update"] : nil
258
+ @raw = payload
259
+ freeze
260
+ end
261
+
262
+ def found? = found
263
+
264
+ def inspect
265
+ "#<Fingerly::DeviceCheckBits found=#{found} bit0=#{bit0} bit1=#{bit1}>"
266
+ end
267
+ end
268
+
269
+ # The bits Apple accepted, from +fingerly.device_check.write+.
270
+ class DeviceCheckWrite
271
+ # @return [Boolean, nil] the value set for the first bit; nil when the
272
+ # write left it out
273
+ attr_reader :bit0
274
+ # @return [Boolean, nil] the value set for the second bit; nil when the
275
+ # write left it out
276
+ attr_reader :bit1
277
+ # @return [Hash] the response body exactly as it arrived
278
+ attr_reader :raw
279
+
280
+ # @api private
281
+ def initialize(payload)
282
+ @bit0 = [true, false].include?(payload["bit0"]) ? payload["bit0"] : nil
283
+ @bit1 = [true, false].include?(payload["bit1"]) ? payload["bit1"] : nil
284
+ @raw = payload
285
+ freeze
286
+ end
287
+
288
+ def inspect
289
+ "#<Fingerly::DeviceCheckWrite bit0=#{bit0.inspect} bit1=#{bit1.inspect}>"
290
+ end
291
+ end
292
+
128
293
  # The envelope every webhook delivery shares.
129
294
  #
130
295
  # {#data} is left as a plain Hash, so a new event type needs no SDK upgrade.
@@ -179,5 +344,17 @@ module Fingerly
179
344
  rescue ArgumentError, TypeError
180
345
  raise Error, "Fingerly API returned a timestamp that is not RFC 3339"
181
346
  end
347
+
348
+ RFC3339 = /\A\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})\z/
349
+
350
+ # A strict RFC 3339 date-time, or nil for anything else, a date alone
351
+ # included.
352
+ def rfc3339(value)
353
+ return nil unless value.is_a?(String) && value.match?(RFC3339)
354
+
355
+ Time.iso8601(value.upcase)
356
+ rescue ArgumentError
357
+ nil
358
+ end
182
359
  end
183
360
  end