ipscope 1.0.0 → 1.1.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.
@@ -1,510 +1,698 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module IpScope
4
- # Geographic location intelligence block.
4
+ # Lenient JSON value casting shared by the response models.
5
+ # @api private
6
+ module ModelCast
7
+ module_function
8
+
9
+ def as_hash(raw)
10
+ raw.is_a?(Hash) ? raw : {}
11
+ end
12
+
13
+ def obj(raw, key)
14
+ v = raw[key]
15
+ v.is_a?(Hash) ? v : nil
16
+ end
17
+
18
+ def str(raw, key)
19
+ v = raw[key]
20
+ return nil if v.nil? || v.is_a?(Hash) || v.is_a?(Array)
21
+
22
+ v.to_s.freeze
23
+ end
24
+
25
+ def int(raw, key)
26
+ v = raw[key]
27
+ v.is_a?(Numeric) ? v.to_i : nil
28
+ end
29
+
30
+ def float(raw, key)
31
+ v = raw[key]
32
+ v.is_a?(Numeric) ? v.to_f : nil
33
+ end
34
+
35
+ # Numeric value kept as sent: an Integer stays Integer, a fraction stays Float.
36
+ def number(raw, key)
37
+ v = raw[key]
38
+ v.is_a?(Numeric) ? v : nil
39
+ end
40
+
41
+ # Tri-state boolean: true, false, or nil when the API abstains or omits the field.
42
+ def bool(raw, key)
43
+ v = raw[key]
44
+ v == true || v == false ? v : nil
45
+ end
46
+
47
+ def str_list(raw, key)
48
+ v = raw[key]
49
+ return [].freeze unless v.is_a?(Array)
50
+
51
+ v.reject { |item| item.is_a?(Hash) || item.is_a?(Array) || item.nil? }.map { |item| item.to_s.freeze }.freeze
52
+ end
53
+
54
+ # Prints a deprecation warning pointing at the caller (silenced by `ruby -W0`, i.e. `$VERBOSE = nil`).
55
+ def deprecated(klass, old, new_name)
56
+ return if $VERBOSE.nil?
57
+
58
+ warn("[ipscope] #{klass}##{old} is deprecated since 1.1.0; use ##{new_name}.", uplevel: 2)
59
+ end
60
+ end
61
+
62
+ # Geographic block (`geo`) of a lookup response.
5
63
  class GeoBlock
6
- attr_reader :country_code, :country_name, :region_code, :region_name,
7
- :city, :postal_code, :latitude, :longitude, :timezone,
8
- :accuracy_radius_km
64
+ attr_reader :country_code, :subdivision, :city, :postal_code, :latitude, :longitude,
65
+ :timezone, :location_type, :confidence, :accuracy_radius_km,
66
+ :declared_country_code, :physical_country_code, :is_virtual_location
9
67
 
10
68
  def initialize(
11
69
  country_code: nil,
12
- country_name: nil,
13
- region_code: nil,
14
- region_name: nil,
70
+ subdivision: nil,
15
71
  city: nil,
16
72
  postal_code: nil,
17
73
  latitude: nil,
18
74
  longitude: nil,
19
75
  timezone: nil,
20
- accuracy_radius_km: nil
76
+ location_type: "unknown",
77
+ confidence: 0.0,
78
+ accuracy_radius_km: nil,
79
+ declared_country_code: nil,
80
+ physical_country_code: nil,
81
+ is_virtual_location: nil
21
82
  )
22
- @country_code = country_code&.to_s&.freeze
23
- @country_name = country_name&.to_s&.freeze
24
- @region_code = region_code&.to_s&.freeze
25
- @region_name = region_name&.to_s&.freeze
26
- @city = city&.to_s&.freeze
27
- @postal_code = postal_code&.to_s&.freeze
28
- @latitude = latitude.nil? ? nil : latitude.to_f
29
- @longitude = longitude.nil? ? nil : longitude.to_f
30
- @timezone = timezone&.to_s&.freeze
31
- @accuracy_radius_km = accuracy_radius_km.nil? ? nil : accuracy_radius_km.to_i
83
+ @country_code = country_code
84
+ @subdivision = subdivision
85
+ @city = city
86
+ @postal_code = postal_code
87
+ @latitude = latitude
88
+ @longitude = longitude
89
+ @timezone = timezone
90
+ @location_type = location_type
91
+ @confidence = confidence
92
+ @accuracy_radius_km = accuracy_radius_km
93
+ @declared_country_code = declared_country_code
94
+ @physical_country_code = physical_country_code
95
+ @is_virtual_location = is_virtual_location
32
96
  freeze
33
97
  end
34
98
 
35
99
  def self.from_h(raw)
36
- h = raw.is_a?(Hash) ? raw : {}
100
+ h = ModelCast.as_hash(raw)
37
101
  new(
38
- country_code: h["country_code"],
39
- country_name: h["country_name"],
40
- region_code: h["region_code"],
41
- region_name: h["region_name"],
42
- city: h["city"],
43
- postal_code: h["postal_code"],
44
- latitude: h["latitude"],
45
- longitude: h["longitude"],
46
- timezone: h["timezone"],
47
- accuracy_radius_km: h["accuracy_radius_km"]
102
+ country_code: ModelCast.str(h, "country_code"),
103
+ subdivision: ModelCast.str(h, "subdivision"),
104
+ city: ModelCast.str(h, "city"),
105
+ postal_code: ModelCast.str(h, "postal_code"),
106
+ latitude: ModelCast.float(h, "latitude"),
107
+ longitude: ModelCast.float(h, "longitude"),
108
+ timezone: ModelCast.str(h, "timezone"),
109
+ location_type: ModelCast.str(h, "location_type") || "unknown",
110
+ confidence: ModelCast.float(h, "confidence") || 0.0,
111
+ accuracy_radius_km: ModelCast.float(h, "accuracy_radius_km"),
112
+ declared_country_code: ModelCast.str(h, "declared_country_code"),
113
+ physical_country_code: ModelCast.str(h, "physical_country_code"),
114
+ is_virtual_location: ModelCast.bool(h, "is_virtual_location")
48
115
  )
49
116
  end
50
117
  end
51
118
 
52
- # Autonomous System (ASN) and BGP prefix block.
119
+ # Autonomous System block (`network`) of a lookup response.
53
120
  class NetworkBlock
54
- attr_reader :asn, :asn_name, :org, :isp, :connection_type, :bgp_prefix, :rir
121
+ attr_reader :asn, :organization
55
122
 
56
- def initialize(
57
- asn: nil,
58
- asn_name: nil,
59
- org: nil,
60
- isp: nil,
61
- connection_type: nil,
62
- bgp_prefix: nil,
63
- rir: nil
64
- )
65
- @asn = asn.nil? ? nil : asn.to_i
66
- @asn_name = asn_name&.to_s&.freeze
67
- @org = org&.to_s&.freeze
68
- @isp = isp&.to_s&.freeze
69
- @connection_type = connection_type&.to_s&.freeze
70
- @bgp_prefix = bgp_prefix&.to_s&.freeze
71
- @rir = rir&.to_s&.freeze
123
+ def initialize(asn: nil, organization: nil)
124
+ @asn = asn
125
+ @organization = organization
72
126
  freeze
73
127
  end
74
128
 
129
+ # @deprecated since 1.1.0; use {#organization}.
130
+ def org
131
+ ModelCast.deprecated(self.class, "org", "organization")
132
+ @organization
133
+ end
134
+
75
135
  def self.from_h(raw)
76
- h = raw.is_a?(Hash) ? raw : {}
77
- new(
78
- asn: h["asn"],
79
- asn_name: h["asn_name"],
80
- org: h["org"],
81
- isp: h["isp"],
82
- connection_type: h["connection_type"],
83
- bgp_prefix: h["bgp_prefix"],
84
- rir: h["rir"]
85
- )
136
+ h = ModelCast.as_hash(raw)
137
+ new(asn: ModelCast.int(h, "asn"), organization: ModelCast.str(h, "organization"))
86
138
  end
87
139
  end
88
140
 
89
- # Anonymity, proxy, VPN, Tor, and threat intelligence block.
141
+ # Security and anonymity block (`security`) of a lookup response.
142
+ # Booleans are nil when the API has insufficient evidence (never a silent false).
90
143
  class SecurityBlock
91
- attr_reader :is_vpn, :is_proxy, :is_tor, :is_datacenter, :is_relay,
92
- :threat_level, :threat_types
144
+ attr_reader :is_vpn, :is_hosting, :is_tor_exit, :is_proxy, :is_relay,
145
+ :anonymizer_type, :confidence, :reason_codes
93
146
 
94
147
  def initialize(
95
- is_vpn: false,
96
- is_proxy: false,
97
- is_tor: false,
98
- is_datacenter: false,
99
- is_relay: false,
100
- threat_level: "low",
101
- threat_types: []
148
+ is_vpn: nil,
149
+ is_hosting: nil,
150
+ is_tor_exit: nil,
151
+ is_proxy: nil,
152
+ is_relay: nil,
153
+ anonymizer_type: "unknown",
154
+ confidence: 0.0,
155
+ reason_codes: []
102
156
  )
103
- @is_vpn = !!is_vpn
104
- @is_proxy = !!is_proxy
105
- @is_tor = !!is_tor
106
- @is_datacenter = !!is_datacenter
107
- @is_relay = !!is_relay
108
- @threat_level = (threat_level || "low").to_s.freeze
109
- @threat_types = Array(threat_types).map { |t| t.to_s.freeze }.freeze
157
+ @is_vpn = is_vpn
158
+ @is_hosting = is_hosting
159
+ @is_tor_exit = is_tor_exit
160
+ @is_proxy = is_proxy
161
+ @is_relay = is_relay
162
+ @anonymizer_type = anonymizer_type
163
+ @confidence = confidence
164
+ @reason_codes = Array(reason_codes).freeze
110
165
  freeze
111
166
  end
112
167
 
168
+ # @deprecated since 1.1.0; use {#is_tor_exit}.
169
+ def is_tor
170
+ ModelCast.deprecated(self.class, "is_tor", "is_tor_exit")
171
+ @is_tor_exit
172
+ end
173
+
174
+ # @deprecated since 1.1.0; use {#is_hosting}.
175
+ def is_datacenter
176
+ ModelCast.deprecated(self.class, "is_datacenter", "is_hosting")
177
+ @is_hosting
178
+ end
179
+
113
180
  def self.from_h(raw)
114
- h = raw.is_a?(Hash) ? raw : {}
181
+ h = ModelCast.as_hash(raw)
115
182
  new(
116
- is_vpn: h["is_vpn"],
117
- is_proxy: h["is_proxy"],
118
- is_tor: h["is_tor"],
119
- is_datacenter: h["is_datacenter"],
120
- is_relay: h["is_relay"],
121
- threat_level: h["threat_level"] || "low",
122
- threat_types: h["threat_types"].is_a?(Array) ? h["threat_types"] : []
183
+ is_vpn: ModelCast.bool(h, "is_vpn"),
184
+ is_hosting: ModelCast.bool(h, "is_hosting"),
185
+ is_tor_exit: ModelCast.bool(h, "is_tor_exit"),
186
+ is_proxy: ModelCast.bool(h, "is_proxy"),
187
+ is_relay: ModelCast.bool(h, "is_relay"),
188
+ anonymizer_type: ModelCast.str(h, "anonymizer_type") || "unknown",
189
+ confidence: ModelCast.float(h, "confidence") || 0.0,
190
+ reason_codes: ModelCast.str_list(h, "reason_codes")
123
191
  )
124
192
  end
125
193
  end
126
194
 
127
- # Detailed connection and carrier classification block.
195
+ # Connection context block (`connection`), present only when the `connection` field family is licensed.
128
196
  class ConnectionBlock
129
- attr_reader :usage_type, :company_type, :carrier_name, :mcc, :mnc,
130
- :domain, :route, :allocated_date, :registry_status
131
-
132
- def initialize(
133
- usage_type: nil,
134
- company_type: nil,
135
- carrier_name: nil,
136
- mcc: nil,
137
- mnc: nil,
138
- domain: nil,
139
- route: nil,
140
- allocated_date: nil,
141
- registry_status: nil
142
- )
143
- @usage_type = usage_type&.to_s&.freeze
144
- @company_type = company_type&.to_s&.freeze
145
- @carrier_name = carrier_name&.to_s&.freeze
146
- @mcc = mcc&.to_s&.freeze
147
- @mnc = mnc&.to_s&.freeze
148
- @domain = domain&.to_s&.freeze
149
- @route = route&.to_s&.freeze
150
- @allocated_date = allocated_date&.to_s&.freeze
151
- @registry_status = registry_status&.to_s&.freeze
197
+ attr_reader :connection_type, :is_residential, :is_mobile, :is_business, :is_hosting
198
+
199
+ def initialize(connection_type: "unknown", is_residential: nil, is_mobile: nil, is_business: nil, is_hosting: nil)
200
+ @connection_type = connection_type
201
+ @is_residential = is_residential
202
+ @is_mobile = is_mobile
203
+ @is_business = is_business
204
+ @is_hosting = is_hosting
152
205
  freeze
153
206
  end
154
207
 
155
208
  def self.from_h(raw)
156
- h = raw.is_a?(Hash) ? raw : {}
209
+ h = ModelCast.as_hash(raw)
157
210
  new(
158
- usage_type: h["usage_type"],
159
- company_type: h["company_type"],
160
- carrier_name: h["carrier_name"],
161
- mcc: h["mcc"],
162
- mnc: h["mnc"],
163
- domain: h["domain"],
164
- route: h["route"],
165
- allocated_date: h["allocated_date"],
166
- registry_status: h["registry_status"]
211
+ connection_type: ModelCast.str(h, "connection_type") || "unknown",
212
+ is_residential: ModelCast.bool(h, "is_residential"),
213
+ is_mobile: ModelCast.bool(h, "is_mobile"),
214
+ is_business: ModelCast.bool(h, "is_business"),
215
+ is_hosting: ModelCast.bool(h, "is_hosting")
167
216
  )
168
217
  end
169
218
  end
170
219
 
171
- # Extended threat scoring and provider attribution block.
220
+ # Security extensions block (`security_extensions`), present only when that field family is licensed.
172
221
  class SecurityExtensionsBlock
173
- attr_reader :vpn_provider, :proxy_type, :threat_score, :is_abuser, :is_bot, :is_bogon
174
-
175
- def initialize(
176
- vpn_provider: nil,
177
- proxy_type: nil,
178
- threat_score: nil,
179
- is_abuser: false,
180
- is_bot: false,
181
- is_bogon: false
182
- )
183
- @vpn_provider = vpn_provider&.to_s&.freeze
184
- @proxy_type = proxy_type&.to_s&.freeze
185
- @threat_score = threat_score.nil? ? nil : threat_score.to_i
186
- @is_abuser = !!is_abuser
187
- @is_bot = !!is_bot
188
- @is_bogon = !!is_bogon
222
+ # Abuse reputation / velocity score, or nil. The API contract defines an Integer 0..100
223
+ # (higher is worse); API releases before that change serve a Float in 0.0..1.0. The value
224
+ # is passed through unchanged, so check which form you got.
225
+ attr_reader :abuse_velocity_score
226
+ attr_reader :is_known_scanner, :observation_recency_hours
227
+
228
+ def initialize(abuse_velocity_score: nil, is_known_scanner: nil, observation_recency_hours: nil)
229
+ @abuse_velocity_score = abuse_velocity_score
230
+ @is_known_scanner = is_known_scanner
231
+ @observation_recency_hours = observation_recency_hours
189
232
  freeze
190
233
  end
191
234
 
192
235
  def self.from_h(raw)
193
- h = raw.is_a?(Hash) ? raw : {}
236
+ h = ModelCast.as_hash(raw)
194
237
  new(
195
- vpn_provider: h["vpn_provider"],
196
- proxy_type: h["proxy_type"],
197
- threat_score: h["threat_score"],
198
- is_abuser: h["is_abuser"],
199
- is_bot: h["is_bot"],
200
- is_bogon: h["is_bogon"]
238
+ abuse_velocity_score: ModelCast.number(h, "abuse_velocity_score"),
239
+ is_known_scanner: ModelCast.bool(h, "is_known_scanner"),
240
+ observation_recency_hours: ModelCast.float(h, "observation_recency_hours")
201
241
  )
202
242
  end
203
243
  end
204
244
 
205
- # Canonical IP intelligence response returned by `/v1/ip` and `/v1/ip/{ip}`.
245
+ # Canonical IP lookup response (`GET /v1/ip/{ip}`, `GET /v1/ip/me`).
206
246
  class IpLookupResponse
207
- attr_reader :ip, :version, :is_bogon, :bogon_type, :geo, :network,
208
- :security, :connection, :security_extensions, :updated_at
247
+ attr_reader :ip, :ip_version, :matched_network, :geo, :network, :security,
248
+ :connection, :security_extensions, :dataset_version, :updated_at
209
249
 
210
250
  def initialize(
211
251
  ip:,
212
- version:,
213
- is_bogon:,
214
- bogon_type:,
252
+ ip_version:,
215
253
  geo:,
216
254
  network:,
217
255
  security:,
256
+ matched_network: nil,
218
257
  connection: nil,
219
258
  security_extensions: nil,
220
- updated_at: ""
259
+ dataset_version: "",
260
+ updated_at: nil
221
261
  )
222
262
  @ip = ip.to_s.freeze
223
- @version = version.to_i
224
- @is_bogon = !!is_bogon
225
- @bogon_type = bogon_type&.to_s&.freeze
263
+ @ip_version = ip_version.to_i
264
+ @matched_network = matched_network
226
265
  @geo = geo
227
266
  @network = network
228
267
  @security = security
229
268
  @connection = connection
230
269
  @security_extensions = security_extensions
231
- @updated_at = updated_at.to_s.freeze
270
+ @dataset_version = dataset_version.to_s.freeze
271
+ @updated_at = updated_at
232
272
  freeze
233
273
  end
234
274
 
275
+ # @deprecated since 1.1.0; use {#ip_version}.
276
+ def version
277
+ ModelCast.deprecated(self.class, "version", "ip_version")
278
+ @ip_version
279
+ end
280
+
235
281
  def self.from_h(raw)
236
- h = raw.is_a?(Hash) ? raw : {}
282
+ h = ModelCast.as_hash(raw)
283
+ ip = ModelCast.str(h, "ip") || ""
284
+ connection = ModelCast.obj(h, "connection")
285
+ extensions = ModelCast.obj(h, "security_extensions")
237
286
  new(
238
- ip: h["ip"] || "",
239
- version: h["version"] || 4,
240
- is_bogon: h["is_bogon"] || false,
241
- bogon_type: h["bogon_type"],
287
+ ip: ip,
288
+ ip_version: ModelCast.int(h, "ip_version") || (ip.include?(":") ? 6 : 4),
289
+ matched_network: ModelCast.str(h, "matched_network"),
242
290
  geo: GeoBlock.from_h(h["geo"]),
243
291
  network: NetworkBlock.from_h(h["network"]),
244
292
  security: SecurityBlock.from_h(h["security"]),
245
- connection: h["connection"].is_a?(Hash) ? ConnectionBlock.from_h(h["connection"]) : nil,
246
- security_extensions: h["security_extensions"].is_a?(Hash) ? SecurityExtensionsBlock.from_h(h["security_extensions"]) : nil,
247
- updated_at: h["updated_at"] || ""
293
+ connection: connection ? ConnectionBlock.from_h(connection) : nil,
294
+ security_extensions: extensions ? SecurityExtensionsBlock.from_h(extensions) : nil,
295
+ dataset_version: ModelCast.str(h, "dataset_version") || "",
296
+ updated_at: ModelCast.str(h, "updated_at")
248
297
  )
249
298
  end
250
299
  end
251
300
 
252
- # Batch IP lookup response returned by `POST /v1/ip/batch`.
301
+ # Batch IP lookup response (`POST /v1/ip/batch`).
253
302
  class BatchLookupResponse
254
- attr_reader :count, :results
303
+ attr_reader :count, :results, :dataset_version
255
304
 
256
- def initialize(count:, results:)
305
+ def initialize(count:, results:, dataset_version: "")
257
306
  @results = Array(results).freeze
258
307
  @count = count ? count.to_i : @results.length
308
+ @dataset_version = dataset_version.to_s.freeze
259
309
  freeze
260
310
  end
261
311
 
262
312
  def self.from_h(raw)
263
- h = raw.is_a?(Hash) ? raw : {}
313
+ h = ModelCast.as_hash(raw)
264
314
  raw_list = h["results"].is_a?(Array) ? h["results"] : []
265
315
  records = raw_list.select { |item| item.is_a?(Hash) }.map { |item| IpLookupResponse.from_h(item) }
266
316
  new(
267
- count: h["count"] || records.length,
268
- results: records
317
+ count: ModelCast.int(h, "count") || records.length,
318
+ results: records,
319
+ dataset_version: ModelCast.str(h, "dataset_version") || ""
269
320
  )
270
321
  end
271
322
  end
272
323
 
273
- # Canonical BGP/CIDR prefix intelligence record.
274
- class CanonicalNetworkPrefixRecord
275
- attr_reader :network_cidr, :ip_version, :geo, :network, :security,
276
- :connection, :security_extensions, :updated_at
324
+ # A structured geographic assertion inside a canonical network record (camelCase on the wire).
325
+ class LocationAssertion
326
+ attr_reader :country_code, :country_name, :subdivision, :city, :latitude, :longitude,
327
+ :accuracy_radius_km, :timezone
328
+
329
+ def initialize(country_code: nil, country_name: nil, subdivision: nil, city: nil, latitude: nil,
330
+ longitude: nil, accuracy_radius_km: nil, timezone: nil)
331
+ @country_code = country_code
332
+ @country_name = country_name
333
+ @subdivision = subdivision
334
+ @city = city
335
+ @latitude = latitude
336
+ @longitude = longitude
337
+ @accuracy_radius_km = accuracy_radius_km
338
+ @timezone = timezone
339
+ freeze
340
+ end
277
341
 
278
- def initialize(
279
- network_cidr:,
280
- ip_version:,
281
- geo:,
282
- network:,
283
- security:,
284
- connection: nil,
285
- security_extensions: nil,
286
- updated_at: ""
287
- )
288
- @network_cidr = network_cidr.to_s.freeze
289
- @ip_version = ip_version.to_i
290
- @geo = geo
291
- @network = network
292
- @security = security
293
- @connection = connection
294
- @security_extensions = security_extensions
295
- @updated_at = updated_at.to_s.freeze
342
+ def self.from_h(raw)
343
+ return nil unless raw.is_a?(Hash)
344
+
345
+ new(
346
+ country_code: ModelCast.str(raw, "countryCode"),
347
+ country_name: ModelCast.str(raw, "countryName"),
348
+ subdivision: ModelCast.str(raw, "subdivision"),
349
+ city: ModelCast.str(raw, "city"),
350
+ latitude: ModelCast.float(raw, "latitude"),
351
+ longitude: ModelCast.float(raw, "longitude"),
352
+ accuracy_radius_km: ModelCast.float(raw, "accuracyRadiusKm"),
353
+ timezone: ModelCast.str(raw, "timezone")
354
+ )
355
+ end
356
+ end
357
+
358
+ # Declared, inferred-physical, and client locations kept separate in a canonical record.
359
+ class SeparatedLocations
360
+ attr_reader :declared_location, :inferred_physical_location, :client_location
361
+
362
+ def initialize(declared_location: nil, inferred_physical_location: nil, client_location: nil)
363
+ @declared_location = declared_location
364
+ @inferred_physical_location = inferred_physical_location
365
+ @client_location = client_location
296
366
  freeze
297
367
  end
298
368
 
299
369
  def self.from_h(raw)
300
- h = raw.is_a?(Hash) ? raw : {}
370
+ h = ModelCast.as_hash(raw)
301
371
  new(
302
- network_cidr: h["network_cidr"] || "",
303
- ip_version: h["ip_version"] || 4,
304
- geo: GeoBlock.from_h(h["geo"]),
305
- network: NetworkBlock.from_h(h["network"]),
306
- security: SecurityBlock.from_h(h["security"]),
307
- connection: h["connection"].is_a?(Hash) ? ConnectionBlock.from_h(h["connection"]) : nil,
308
- security_extensions: h["security_extensions"].is_a?(Hash) ? SecurityExtensionsBlock.from_h(h["security_extensions"]) : nil,
309
- updated_at: h["updated_at"] || ""
372
+ declared_location: LocationAssertion.from_h(h["declaredLocation"]),
373
+ inferred_physical_location: LocationAssertion.from_h(h["inferredPhysicalLocation"]),
374
+ client_location: LocationAssertion.from_h(h["clientLocation"])
310
375
  )
311
376
  end
312
377
  end
313
378
 
314
- # Network CIDR lookup response returned by `GET /v1/network/{address}/{prefixLength}`.
315
- class NetworkPrefixLookupResponse
316
- attr_reader :requested_cidr, :exact_match, :enclosing_prefix,
317
- :overlapping_prefixes, :total_matches
379
+ # Canonical network record stored in the serving snapshot (`record` of a network lookup).
380
+ # The API serves this object with camelCase keys; attributes here are snake_case.
381
+ class CanonicalNetworkPrefixRecord
382
+ FIELDS = {
383
+ family: ["family", :int],
384
+ prefix: ["prefix", :str],
385
+ asn: ["asn", :int],
386
+ organization: ["organization", :str],
387
+ country_code: ["countryCode", :str],
388
+ subdivision: ["subdivision", :str],
389
+ city: ["city", :str],
390
+ postal_code: ["postalCode", :str],
391
+ latitude: ["latitude", :float],
392
+ longitude: ["longitude", :float],
393
+ timezone: ["timezone", :str],
394
+ location_type: ["locationType", :str],
395
+ geo_confidence: ["geoConfidence", :float],
396
+ accuracy_radius_km: ["accuracyRadiusKm", :float],
397
+ is_virtual_location: ["isVirtualLocation", :bool],
398
+ connection_type: ["connectionType", :str],
399
+ is_hosting: ["isHosting", :bool],
400
+ is_vpn: ["isVpn", :bool],
401
+ is_tor_exit: ["isTorExit", :bool],
402
+ is_proxy: ["isProxy", :bool],
403
+ anonymizer_type: ["anonymizerType", :str],
404
+ security_confidence: ["securityConfidence", :float],
405
+ abuse_velocity_score: ["abuseVelocityScore", :number],
406
+ is_known_scanner: ["isKnownScanner", :bool],
407
+ reason_codes: ["reasonCodes", :str_list],
408
+ source_ids: ["sourceIds", :str_list],
409
+ license_policy_ids: ["licensePolicyIds", :str_list],
410
+ updated_at: ["updatedAt", :str]
411
+ }.freeze
412
+
413
+ attr_reader(*FIELDS.keys)
414
+ attr_reader :locations
415
+
416
+ def initialize(locations: SeparatedLocations.new, **attrs)
417
+ unknown = attrs.keys - FIELDS.keys
418
+ raise ArgumentError, "unknown keywords: #{unknown.join(', ')}" unless unknown.empty?
419
+
420
+ FIELDS.each_key { |name| instance_variable_set("@#{name}", attrs[name]) }
421
+ @prefix ||= ""
422
+ @family ||= @prefix.include?(":") ? 6 : 4
423
+ @location_type ||= "unknown"
424
+ @anonymizer_type ||= "unknown"
425
+ @geo_confidence ||= 0.0
426
+ @security_confidence ||= 0.0
427
+ @reason_codes ||= [].freeze
428
+ @source_ids ||= [].freeze
429
+ @license_policy_ids ||= [].freeze
430
+ @locations = locations
431
+ freeze
432
+ end
318
433
 
319
- def initialize(
320
- requested_cidr:,
321
- exact_match:,
322
- enclosing_prefix:,
323
- overlapping_prefixes:,
324
- total_matches:
325
- )
326
- @requested_cidr = requested_cidr.to_s.freeze
327
- @exact_match = exact_match
328
- @enclosing_prefix = enclosing_prefix
329
- @overlapping_prefixes = Array(overlapping_prefixes).freeze
330
- @total_matches = total_matches.to_i
434
+ def self.from_h(raw)
435
+ h = ModelCast.as_hash(raw)
436
+ attrs = FIELDS.each_with_object({}) do |(name, (key, type)), acc|
437
+ acc[name] = ModelCast.public_send(type, h, key)
438
+ end
439
+ new(locations: SeparatedLocations.from_h(h["locations"]), **attrs)
440
+ end
441
+ end
442
+
443
+ # Network CIDR lookup response (`GET /v1/networks/{address}/{prefixLength}`).
444
+ class NetworkPrefixLookupResponse
445
+ attr_reader :queried_cidr, :matched_network, :family, :bgp_prefix_length,
446
+ :dataset_version, :record, :lookup
447
+
448
+ def initialize(queried_cidr:, matched_network:, family:, bgp_prefix_length:, dataset_version:,
449
+ record: nil, lookup: nil)
450
+ @queried_cidr = queried_cidr.to_s.freeze
451
+ @matched_network = matched_network.to_s.freeze
452
+ @family = family.to_i
453
+ @bgp_prefix_length = bgp_prefix_length.to_i
454
+ @dataset_version = dataset_version.to_s.freeze
455
+ @record = record
456
+ @lookup = lookup
331
457
  freeze
332
458
  end
333
459
 
334
460
  def self.from_h(raw)
335
- h = raw.is_a?(Hash) ? raw : {}
336
- overlaps = (h["overlapping_prefixes"].is_a?(Array) ? h["overlapping_prefixes"] : [])
337
- .select { |item| item.is_a?(Hash) }
338
- .map { |item| CanonicalNetworkPrefixRecord.from_h(item) }
461
+ h = ModelCast.as_hash(raw)
462
+ queried = ModelCast.str(h, "queried_cidr") || ""
463
+ matched = ModelCast.str(h, "matched_network") || queried
464
+ record = ModelCast.obj(h, "record")
465
+ lookup = ModelCast.obj(h, "lookup")
339
466
  new(
340
- requested_cidr: h["requested_cidr"] || "",
341
- exact_match: h["exact_match"].is_a?(Hash) ? CanonicalNetworkPrefixRecord.from_h(h["exact_match"]) : nil,
342
- enclosing_prefix: h["enclosing_prefix"].is_a?(Hash) ? CanonicalNetworkPrefixRecord.from_h(h["enclosing_prefix"]) : nil,
343
- overlapping_prefixes: overlaps,
344
- total_matches: h["total_matches"] || overlaps.length
467
+ queried_cidr: queried,
468
+ matched_network: matched,
469
+ family: ModelCast.int(h, "family") || (queried.include?(":") ? 6 : 4),
470
+ bgp_prefix_length: ModelCast.int(h, "bgp_prefix_length") || matched.split("/")[1].to_i,
471
+ dataset_version: ModelCast.str(h, "dataset_version") || "",
472
+ record: record ? CanonicalNetworkPrefixRecord.from_h(record) : nil,
473
+ lookup: lookup ? IpLookupResponse.from_h(lookup) : nil
345
474
  )
346
475
  end
347
476
  end
348
477
 
349
- # Snapshot metadata for a single IP intelligence dataset source.
478
+ # Summary of one loaded dataset snapshot.
350
479
  class DatasetSnapshotSummary
351
- attr_reader :source, :version_tag, :checksum_sha256, :record_count,
352
- :activated_at, :created_at
353
-
354
- def initialize(
355
- source:,
356
- version_tag:,
357
- checksum_sha256:,
358
- record_count:,
359
- activated_at:,
360
- created_at:
361
- )
362
- @source = source.to_s.freeze
363
- @version_tag = version_tag.to_s.freeze
364
- @checksum_sha256 = checksum_sha256.to_s.freeze
365
- @record_count = record_count.to_i
366
- @activated_at = activated_at&.to_s&.freeze
367
- @created_at = created_at.to_s.freeze
480
+ attr_reader :snapshot_version, :digest, :ruleset_version, :published_at,
481
+ :ipv4_prefix_count, :ipv6_prefix_count
482
+
483
+ def initialize(snapshot_version:, digest:, ruleset_version:, published_at:,
484
+ ipv4_prefix_count:, ipv6_prefix_count:)
485
+ @snapshot_version = snapshot_version.to_s.freeze
486
+ @digest = digest.to_s.freeze
487
+ @ruleset_version = ruleset_version.to_s.freeze
488
+ @published_at = published_at.to_s.freeze
489
+ @ipv4_prefix_count = ipv4_prefix_count.to_i
490
+ @ipv6_prefix_count = ipv6_prefix_count.to_i
368
491
  freeze
369
492
  end
370
493
 
371
494
  def self.from_h(raw)
372
- h = raw.is_a?(Hash) ? raw : {}
495
+ h = ModelCast.as_hash(raw)
373
496
  new(
374
- source: h["source"] || "",
375
- version_tag: h["version_tag"] || "",
376
- checksum_sha256: h["checksum_sha256"] || "",
377
- record_count: h["record_count"] || 0,
378
- activated_at: h["activated_at"],
379
- created_at: h["created_at"] || ""
497
+ snapshot_version: ModelCast.str(h, "snapshot_version") || "",
498
+ digest: ModelCast.str(h, "digest") || "",
499
+ ruleset_version: ModelCast.str(h, "ruleset_version") || "",
500
+ published_at: ModelCast.str(h, "published_at") || "",
501
+ ipv4_prefix_count: ModelCast.int(h, "ipv4_prefix_count") || 0,
502
+ ipv6_prefix_count: ModelCast.int(h, "ipv6_prefix_count") || 0
380
503
  )
381
504
  end
382
505
  end
383
506
 
384
- # Active dataset snapshots metadata returned by `GET /v1/datasets/metadata`.
507
+ # Dataset snapshots metadata (`GET /v1/metadata/datasets`).
385
508
  class DatasetsMetadataResponse
386
- attr_reader :count, :active_datasets
509
+ attr_reader :active_version, :previous_version, :snapshots
387
510
 
388
- def initialize(count:, active_datasets:)
389
- @active_datasets = Array(active_datasets).freeze
390
- @count = count ? count.to_i : @active_datasets.length
511
+ def initialize(active_version:, previous_version:, snapshots:)
512
+ @active_version = active_version.to_s.freeze
513
+ @previous_version = previous_version
514
+ @snapshots = Array(snapshots).freeze
391
515
  freeze
392
516
  end
393
517
 
394
518
  def self.from_h(raw)
395
- h = raw.is_a?(Hash) ? raw : {}
396
- datasets = (h["active_datasets"].is_a?(Array) ? h["active_datasets"] : [])
397
- .select { |item| item.is_a?(Hash) }
398
- .map { |item| DatasetSnapshotSummary.from_h(item) }
519
+ h = ModelCast.as_hash(raw)
520
+ snapshots = (h["snapshots"].is_a?(Array) ? h["snapshots"] : [])
521
+ .select { |item| item.is_a?(Hash) }
522
+ .map { |item| DatasetSnapshotSummary.from_h(item) }
399
523
  new(
400
- count: h["count"] || datasets.length,
401
- active_datasets: datasets
524
+ active_version: ModelCast.str(h, "active_version") || "",
525
+ previous_version: ModelCast.str(h, "previous_version"),
526
+ snapshots: snapshots
402
527
  )
403
528
  end
404
529
  end
405
530
 
406
- # Payload for submitting an IP geolocation or anonymity correction (`POST /v1/feedback`).
531
+ # Correction report for `POST /v1/feedback`.
407
532
  class FeedbackSubmissionInput
408
- attr_reader :ip_or_cidr, :suggested_country_code, :suggested_region_name,
409
- :suggested_city, :suggested_is_vpn, :notes, :contact_email
410
-
411
- def initialize(
412
- ip_or_cidr:,
413
- suggested_country_code: nil,
414
- suggested_region_name: nil,
415
- suggested_city: nil,
416
- suggested_is_vpn: nil,
417
- notes: nil,
418
- contact_email: nil
419
- )
420
- @ip_or_cidr = ip_or_cidr.to_s.freeze
421
- @suggested_country_code = suggested_country_code&.to_s&.freeze
422
- @suggested_region_name = suggested_region_name&.to_s&.freeze
423
- @suggested_city = suggested_city&.to_s&.freeze
424
- @suggested_is_vpn = suggested_is_vpn.nil? ? nil : !!suggested_is_vpn
425
- @notes = notes&.to_s&.freeze
533
+ ROLES = %w[network_owner user researcher].freeze
534
+ ISSUE_TYPES = %w[
535
+ wrong_country
536
+ wrong_city
537
+ false_positive_vpn
538
+ false_positive_hosting
539
+ false_positive_tor
540
+ virtual_location_mismatch
541
+ other
542
+ ].freeze
543
+
544
+ attr_reader :prefix_or_ip, :role, :issue_type, :requested_correction,
545
+ :evidence_url, :contact_consent, :contact_email
546
+
547
+ # @param prefix_or_ip [String] target IP address or CIDR prefix
548
+ # @param role [String] one of {ROLES}
549
+ # @param issue_type [String] one of {ISSUE_TYPES}
550
+ # @param requested_correction [Hash] requested corrected attributes, e.g. `{ "country_code" => "DE" }`
551
+ # @param evidence_url [String, nil] public URL to geofeed / RDAP / traceroute evidence
552
+ def initialize(prefix_or_ip:, role:, issue_type:, requested_correction: {}, evidence_url: nil,
553
+ contact_consent: false, contact_email: nil)
554
+ @prefix_or_ip = prefix_or_ip.to_s.freeze
555
+ @role = role.to_s.freeze
556
+ @issue_type = issue_type.to_s.freeze
557
+ @requested_correction = (requested_correction || {}).each_with_object({}) { |(k, v), acc| acc[k.to_s] = v }.freeze
558
+ @evidence_url = evidence_url&.to_s&.freeze
559
+ @contact_consent = contact_consent ? true : false
426
560
  @contact_email = contact_email&.to_s&.freeze
427
561
  freeze
428
562
  end
429
563
 
430
564
  def to_h
431
- payload = { "ip_or_cidr" => @ip_or_cidr }
432
- payload["suggested_country_code"] = @suggested_country_code unless @suggested_country_code.nil?
433
- payload["suggested_region_name"] = @suggested_region_name unless @suggested_region_name.nil?
434
- payload["suggested_city"] = @suggested_city unless @suggested_city.nil?
435
- payload["suggested_is_vpn"] = @suggested_is_vpn unless @suggested_is_vpn.nil?
436
- payload["notes"] = @notes unless @notes.nil?
565
+ payload = {
566
+ "prefix_or_ip" => @prefix_or_ip,
567
+ "role" => @role,
568
+ "issue_type" => @issue_type,
569
+ "requested_correction" => @requested_correction,
570
+ "contact_consent" => @contact_consent
571
+ }
572
+ payload["evidence_url"] = @evidence_url unless @evidence_url.nil?
437
573
  payload["contact_email"] = @contact_email unless @contact_email.nil?
438
574
  payload
439
575
  end
440
576
  end
441
577
 
442
- # Feedback submission acknowledgment returned by `POST /v1/feedback`.
578
+ # Feedback acknowledgment returned by `POST /v1/feedback`.
443
579
  class FeedbackSubmissionResponse
444
- attr_reader :id, :ip_or_cidr, :status, :created_at
580
+ attr_reader :id, :prefix_or_ip, :role, :issue_type, :requested_correction,
581
+ :evidence_url, :contact_consent, :contact_email, :status, :created_at
445
582
 
446
- def initialize(id:, ip_or_cidr:, status:, created_at:)
583
+ def initialize(id:, status:, created_at:, prefix_or_ip: "", role: "", issue_type: "",
584
+ requested_correction: {}, evidence_url: nil, contact_consent: nil, contact_email: nil)
447
585
  @id = id.to_s.freeze
448
- @ip_or_cidr = ip_or_cidr.to_s.freeze
586
+ @prefix_or_ip = prefix_or_ip.to_s.freeze
587
+ @role = role.to_s.freeze
588
+ @issue_type = issue_type.to_s.freeze
589
+ @requested_correction = requested_correction.freeze
590
+ @evidence_url = evidence_url
591
+ @contact_consent = contact_consent
592
+ @contact_email = contact_email
449
593
  @status = status.to_s.freeze
450
594
  @created_at = created_at.to_s.freeze
451
595
  freeze
452
596
  end
453
597
 
454
598
  def self.from_h(raw)
455
- h = raw.is_a?(Hash) ? raw : {}
599
+ h = ModelCast.as_hash(raw)
600
+ new(
601
+ id: ModelCast.str(h, "id") || "",
602
+ prefix_or_ip: ModelCast.str(h, "prefix_or_ip") || "",
603
+ role: ModelCast.str(h, "role") || "",
604
+ issue_type: ModelCast.str(h, "issue_type") || "",
605
+ requested_correction: ModelCast.obj(h, "requested_correction") || {},
606
+ evidence_url: ModelCast.str(h, "evidence_url"),
607
+ contact_consent: ModelCast.bool(h, "contact_consent"),
608
+ contact_email: ModelCast.str(h, "contact_email"),
609
+ status: ModelCast.str(h, "status") || "",
610
+ # The API returns camelCase `createdAt`; accept snake_case too.
611
+ created_at: ModelCast.str(h, "createdAt") || ModelCast.str(h, "created_at") || ""
612
+ )
613
+ end
614
+ end
615
+
616
+ # Serving and previous dataset versions reported by `GET /v1/status`.
617
+ class ServiceSnapshotInfo
618
+ attr_reader :current_version, :previous_version
619
+
620
+ def initialize(current_version: nil, previous_version: nil)
621
+ @current_version = current_version
622
+ @previous_version = previous_version
623
+ freeze
624
+ end
625
+
626
+ def self.from_h(raw)
627
+ h = ModelCast.as_hash(raw)
456
628
  new(
457
- id: h["id"] || "",
458
- ip_or_cidr: h["ip_or_cidr"] || "",
459
- status: h["status"] || "",
460
- created_at: h["created_at"] || ""
629
+ current_version: ModelCast.str(h, "currentVersion"),
630
+ previous_version: ModelCast.str(h, "previousVersion")
461
631
  )
462
632
  end
463
633
  end
464
634
 
465
- # Service health status returned by `GET /v1/status`.
635
+ # Service health returned by `GET /v1/status`.
466
636
  class ServiceStatusResponse
467
- attr_reader :status, :service, :version, :uptime_seconds, :timestamp
637
+ attr_reader :status, :snapshot
468
638
 
469
- def initialize(status:, service:, version:, uptime_seconds:, timestamp:)
639
+ def initialize(status:, snapshot: nil)
470
640
  @status = status.to_s.freeze
471
- @service = service.to_s.freeze
472
- @version = version.to_s.freeze
473
- @uptime_seconds = uptime_seconds.to_f
474
- @timestamp = timestamp.to_s.freeze
641
+ @snapshot = snapshot
475
642
  freeze
476
643
  end
477
644
 
645
+ # Dataset version currently served (the `dataset_version` lookups return).
646
+ def current_version
647
+ @snapshot&.current_version
648
+ end
649
+
650
+ def previous_version
651
+ @snapshot&.previous_version
652
+ end
653
+
478
654
  def self.from_h(raw)
479
- h = raw.is_a?(Hash) ? raw : {}
655
+ h = ModelCast.as_hash(raw)
656
+ snapshot = ModelCast.obj(h, "snapshot")
480
657
  new(
481
- status: h["status"] || "",
482
- service: h["service"] || "",
483
- version: h["version"] || "",
484
- uptime_seconds: h["uptime_seconds"] || 0.0,
485
- timestamp: h["timestamp"] || ""
658
+ status: ModelCast.str(h, "status") || "",
659
+ snapshot: snapshot ? ServiceSnapshotInfo.from_h(snapshot) : nil
486
660
  )
487
661
  end
488
662
  end
489
663
 
490
- # Rate-limit and quota metadata extracted from `x-ratelimit-*` HTTP response headers.
664
+ # Rate-limit metadata from the `X-RateLimit-*` response headers. Limits apply per user, not per key.
491
665
  class RateLimitMetadata
492
- attr_reader :limit, :remaining, :reset_epoch_seconds, :credits_remaining, :plan_tier
493
-
494
- def initialize(
495
- limit: nil,
496
- remaining: nil,
497
- reset_epoch_seconds: nil,
498
- credits_remaining: nil,
499
- plan_tier: nil
500
- )
666
+ # limit: requests allowed per window; remaining: left in this window;
667
+ # reset_after_seconds: seconds until the window resets; scope: e.g. "user".
668
+ attr_reader :limit, :remaining, :reset_after_seconds, :scope
669
+
670
+ # `reset_epoch_seconds:` is accepted as a deprecated 1.0 alias of `reset_after_seconds:`.
671
+ def initialize(limit: nil, remaining: nil, reset_after_seconds: nil, scope: nil,
672
+ reset_epoch_seconds: nil, credits_remaining: nil, plan_tier: nil)
673
+ reset = reset_after_seconds.nil? ? reset_epoch_seconds : reset_after_seconds
501
674
  @limit = limit.nil? ? nil : limit.to_i
502
675
  @remaining = remaining.nil? ? nil : remaining.to_i
503
- @reset_epoch_seconds = reset_epoch_seconds.nil? ? nil : reset_epoch_seconds.to_i
504
- @credits_remaining = credits_remaining.nil? ? nil : credits_remaining.to_i
505
- @plan_tier = plan_tier&.to_s&.freeze
676
+ @reset_after_seconds = reset.nil? ? nil : reset.to_i
677
+ @scope = scope&.to_s&.freeze
506
678
  freeze
507
679
  end
680
+
681
+ # @deprecated since 1.1.0. Misnamed in 1.0: the API sends seconds until the window
682
+ # resets, not an epoch timestamp. Returns the same value as {#reset_after_seconds}.
683
+ def reset_epoch_seconds
684
+ @reset_after_seconds
685
+ end
686
+
687
+ # @deprecated since 1.1.0. The API never sends a credits header; always nil.
688
+ def credits_remaining
689
+ nil
690
+ end
691
+
692
+ # @deprecated since 1.1.0. The API never sends a tier header; always nil.
693
+ def plan_tier
694
+ nil
695
+ end
508
696
  end
509
697
 
510
698
  # Wrapper pairing a response payload with rate-limit metadata and cache hit status.