leverprice 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9d0113802761dfde970aa7c9661c7007940ccfd3707732996ba8be5fb573473a
4
- data.tar.gz: 65d47dd2b8ba72a0cefab2a7457bf66ac51d42730b1b4f06316bc659c2aeec54
3
+ metadata.gz: e1d5b60ccb0ffc4f980dbaf026f4b907c39804c99a747517eb6333bfeaa2f2eb
4
+ data.tar.gz: a4b4a768b233c52ca9d1e37f428105241bbedb3a0f462e554dde2629a28f987e
5
5
  SHA512:
6
- metadata.gz: c6ce9cc753fe57ee58abb94edf20202e291ff6edc3fc9ff36feee0eeb10d9690e2e325d1eef7c676da03378bea44e0c2ce75420483ff81161a3cca44b335c5d2
7
- data.tar.gz: e8989fda08a04fe92fc78cd3c50962b5247ebfae144f55f9bbe6bd1e0c640bb3f135b10c7a15fe7fb32197efde4a002df3e9ce36ffe10226cd59da392239d5ad
6
+ metadata.gz: f93af949733ce4cb49531f918aea2129178b082637b87c86157d5a41ff43f35ca3480ba4087e82c4514f67a37f7a83d1bca204c514617e1a92caae8d8bdc63bd
7
+ data.tar.gz: 67e8955e08d03b82ca4930d5aa754f596a04440f30aae35b07feb052a27dc5c7bcfa20d912141e9e0eb9271871bf68ce6de93a56483c4741b21d3d82c148fd44
data/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.1 (2026-11-18)
4
+
5
+ - VPN guard: a visitor keeps the price of a country that pays more, where they were seen in the last 7 days, so a VPN
6
+ to a cheaper country no longer lowers the price. A visitor who moves to a dearer country pays its price from then
7
+ on. The held country is `quote.country` and lives in the signed `__pp` cookie, which a regional product now sets
8
+ even without a test. Turned on by the signed config; older SDKs ignore it.
9
+ - A visitor who refuses cookies keeps one price and counts once: without a cookie, the visitor is keyed by an HMAC of
10
+ their IP address (IPv6 by its /64), browser and languages, made with the project's secret. Neither leaves your
11
+ server.
12
+ - `country_header:` naming a header every browser sends (`Accept-Language`, `X-Forwarded-For`…) is ignored and
13
+ reported to `on_error`, and such a header in the project settings is never read: visitors can no longer pick their
14
+ own country.
15
+ - Every config request says which products your code prices (`Leverprice-Products`) and why the last config was
16
+ refused, if it was (`Leverprice-Config-Error`), so the dashboard's Setup page turns green only when visitors get
17
+ real prices and otherwise says what to fix. A refused config reaches `on_error` as `Leverprice::ConfigError`, whose
18
+ `code` says why.
19
+ - A cold start no longer gives up early: each request waits its own `timeout_ms:` for the first config, even when
20
+ `preload` in another thread or another request started the fetch earlier. Before, a busy server answered the first
21
+ visitors with the fallback early, said nothing, and pinned them to it for 30 minutes. A request that does give up
22
+ now reports `Leverprice config: still loading after 500 ms (timeout_ms); …` to `on_error`, once per fetch.
23
+
3
24
  ## 0.4.0 (2026-11-18)
4
25
 
5
26
  - Settings live in Leverprice, not in code: the product's price range and the header that carries the visitor's
data/README.md CHANGED
@@ -195,6 +195,8 @@ Pass whatever request object you have: a Rack env Hash, a `Rack::Request` or `Ac
195
195
 
196
196
  Pricing several products on one page? Pass the **same request** to each `get_price` call. The quotes share one visitor cookie, and the last quote's cookie carries every assignment.
197
197
 
198
+ A visitor who refuses cookies still keeps one price and counts once: without a cookie, the SDK keys the visitor by an HMAC of their IP address (an IPv6 address by its /64 network), browser and languages, made with your project's secret on your server. Neither the address nor the browser leaves your server. The address comes from `CF-Connecting-IP`, `True-Client-IP`, `Fastly-Client-IP`, `Fly-Client-IP`, `X-Real-IP`, `X-Forwarded-For` or the Rack env's `REMOTE_ADDR`.
199
+
198
200
  `user_id:` accepts a String or an Integer. Convert other id types (UUID objects, `BSON::ObjectId`) with `to_s`.
199
201
 
200
202
  ## Regional prices
@@ -213,7 +215,8 @@ quote.regional? # true
213
215
  quote = LEVERPRICE.get_price("pro", request: request, country: lookup_country(request.ip))
214
216
  ```
215
217
 
216
- - **The country.** Name only a header your host or CDN sets and overwrites: a header a visitor can send themselves would let them pick their own price. To decide in code instead, pass `country_header:` to `Leverprice::Client.new` (it replaces the project setting) or `country:` to `get_price` (it wins over both). Give the HTTP header name, not the Rack key: the SDK finds `HTTP_CF_IPCOUNTRY` in a Rack env by itself. `CF_IPCountry` and `CF-IPCountry` share that key, so keep header names with underscores dropped in front of the app (the nginx default).
218
+ - **The country.** Name only a header your host or CDN sets and overwrites: a header a visitor can send themselves would let them pick their own price. Headers every browser sends (`Accept-Language`, `X-Forwarded-For`, `User-Agent`…) are never read as the country: as `country_header:` they are ignored and reported to `on_error`. To decide in code instead, pass `country_header:` to `Leverprice::Client.new` (it replaces the project setting) or `country:` to `get_price` (it wins over both). Give the HTTP header name, not the Rack key: the SDK finds `HTTP_CF_IPCOUNTRY` in a Rack env by itself. `CF_IPCountry` and `CF-IPCountry` share that key, so keep header names with underscores dropped in front of the app (the nginx default).
219
+ - **VPNs.** A visitor keeps the price of a dearer country they were seen in during the last 7 days, so turning on a VPN to a cheaper country doesn't lower it. That country is `quote.country`, and it travels in the signed `__pp` cookie, which a regional product now sets even without a test.
217
220
  - **Local currencies.** Regional prices in your product's currency ($12 in India instead of $29) need nothing in code. Prices in the visitor's own currency (₹999) are served only with `local_currencies: true`, which you set when your checkout charges `quote.price` in `quote.currency`; without it those visitors get the standard price, so a checkout with a fixed currency can never charge 99900 in dollars.
218
221
  - **Tests.** Each visitor still gets one sticky variant, at that variant's price for their country. A test can run in selected countries only, and countries can get their own share of traffic per price: both are set in the dashboard and need nothing from your code but the visitor's country.
219
222
  - **Checkout.** Always pass `quote.currency` with `quote.price`, also before you turn regional prices on: then they need no code change later. `checkout_url` is `nil` for a regional price: hosted checkout links are made for standard prices.
@@ -266,7 +269,7 @@ The config is revalidated every 30 seconds with an ETag, driven by traffic. When
266
269
  | `product_key` | The key you asked for |
267
270
  | `price` | Minor units; use it for display and as the checkout amount |
268
271
  | `currency` | Lowercase ISO 4217: your product's currency, or the region's for a regional price |
269
- | `country` | The visitor's country (ISO 3166-1 alpha-2) when known, else `nil` |
272
+ | `country` | The country whose price applies (ISO 3166-1 alpha-2): the visitor's, or a dearer one they hold (see VPNs); `nil` when unknown |
270
273
  | `regional`, `regional?` | `true` when `price` is the regional price of `country` |
271
274
  | `is_fallback`, `fallback?` | `true` when `price` is your `fallback_price` |
272
275
  | `reason` | See below |
@@ -313,7 +316,7 @@ The config is revalidated every 30 seconds with an ETag, driven by traffic. When
313
316
  | `cookie_max_age_seconds` | `15552000` | 180 days |
314
317
  | `cookie_secure` | `true` | Set `false` only for plain-HTTP development |
315
318
  | `cookie_domain` | `nil` | |
316
- | `country_header` | `nil` | Request header your CDN or host sets to the visitor's country, such as `cf-ipcountry`. Overrides the project's country setting in Leverprice. Name only a header visitors cannot set |
319
+ | `country_header` | `nil` | Request header your CDN or host sets to the visitor's country, such as `cf-ipcountry`. Overrides the project's country setting in Leverprice. A header every browser sends (`accept-language`, `x-forwarded-for`…) is ignored and reported to `on_error` |
317
320
  | `local_currencies` | `false` | Serve regional prices in the visitor's currency, not only in each product's own. Set it only when your checkout charges `quote.price` in `quote.currency` |
318
321
  | `flush_interval_ms` | `2000` | Longest exposures wait before being sent |
319
322
  | `trusted_root_keys` | `ROOT_PUBLIC_KEYS` | For staging and local development |
@@ -24,20 +24,28 @@ module Leverprice
24
24
  CATCH_UP_GAP_MS = 5_000
25
25
  MAX_DEDUPE = 10_000
26
26
  IDLE_WAIT_SECONDS = 60
27
+ PRODUCTS_HEADER = "Leverprice-Products"
28
+ CONFIG_ERROR_HEADER = "Leverprice-Config-Error"
29
+ MAX_REPORTED_PRODUCTS = 50
30
+ UNRESERVED_RE = /\A[A-Za-z0-9._~-]\z/
27
31
 
28
32
  Guard = Struct.new(:currency, :fallback_price)
29
33
  Region = Struct.new(:index, :currency, :price)
30
34
  Scope = Struct.new(:mutex, :cookie, :pinned)
31
35
  ScopeCookie = Struct.new(:input, :user_id, :assignment_key, :state)
32
36
  Context = Struct.new(:cookie, :user_agent, :user_id, :exposure, :bot, :country, keyword_init: true)
33
- private_constant :Guard, :Region, :Scope, :ScopeCookie, :Context
37
+ # `changed`: the state differs from the request's cookie, so a new one is sent.
38
+ Visitor = Struct.new(:key, :user_id, :state, :changed)
39
+ private_constant :Guard, :Region, :Scope, :ScopeCookie, :Context, :Visitor
34
40
 
35
41
  # @api private
36
42
  class Flight
37
43
  attr_reader :started_at
44
+ attr_accessor :slow_reported
38
45
 
39
46
  def initialize(started_at)
40
47
  @started_at = started_at
48
+ @slow_reported = false
41
49
  @mutex = Mutex.new
42
50
  @finished = ConditionVariable.new
43
51
  @done = false
@@ -69,7 +77,8 @@ module Leverprice
69
77
  # `max_price:` are deprecated and ignored since 0.4: the price range is set in Leverprice
70
78
  # @param secret_key [String, nil] `pp_sk_live_…` or `pp_sk_test_…`; missing or malformed turns the SDK off
71
79
  # @param country_header [String, nil] request header your CDN or host sets to the visitor's country, such as
72
- # `cf-ipcountry`; overrides the project's setting. Name only a header visitors cannot set
80
+ # `cf-ipcountry`; overrides the project's setting. A header every browser sends itself (`accept-language`,
81
+ # `x-forwarded-for`…) is ignored and reported to `on_error`
73
82
  # @param local_currencies [Boolean] serve regional prices in the visitor's currency, not only in each product's
74
83
  # own; set it only when your checkout charges `quote.price` in `quote.currency`
75
84
  # @raise [ArgumentError] for invalid products, cookie_name or country_header
@@ -92,7 +101,9 @@ module Leverprice
92
101
  @cookie_max_age = Util.safe_int(cookie_max_age_seconds) || cookie_max_age_seconds || 15_552_000
93
102
  @cookie_secure = cookie_secure != false
94
103
  @cookie_domain = cookie_domain
95
- @country_header = normalize_country_header(country_header)
104
+ named = normalize_country_header(country_header)
105
+ # A header the visitor sends would let them pick their own price: the project's setting is used.
106
+ @country_header = named && Request.visitor_set_header?(named) ? nil : named
96
107
  @local_currencies = local_currencies == true
97
108
  @flush_interval_ms = flush_interval_ms || 2_000
98
109
  @transport = transport || NetHTTPTransport.new
@@ -114,12 +125,21 @@ module Leverprice
114
125
  @server_version = 0
115
126
  @catch_up_at = 0
116
127
  @hmac_cache = nil
128
+ @config_error = nil
129
+ @products_header = products_header(@guards)
117
130
  @closed = false
118
131
  reset_runtime
119
132
  @scope_ivar = :"@__leverprice_scope_#{ForkTracker.register(self)}"
120
- return if key.empty? || @secret_key || @disabled || Leverprice.env_disabled?
133
+ return if @disabled || Leverprice.env_disabled?
121
134
 
122
- emit(Error.new("Leverprice: secret_key is not a pp_sk_live_… / pp_sk_test_… key; serving fallback prices."))
135
+ unless key.empty? || @secret_key
136
+ emit(Error.new("Leverprice: secret_key is not a pp_sk_live_… / pp_sk_test_… key; serving fallback prices."))
137
+ end
138
+ return unless named && @country_header.nil?
139
+
140
+ emit(Error.new(%(Leverprice: country_header "#{named}" is sent by visitors' browsers, so it would let them ) \
141
+ "pick their own price; it is ignored. Name the header your CDN or host sets, such as " \
142
+ "cf-ipcountry."))
123
143
  end
124
144
 
125
145
  # Returns the price to show and charge. Raises only for a product key missing from `products`.
@@ -387,14 +407,19 @@ module Leverprice
387
407
  return fallback_quote(key, guard, "unknown_product") unless product
388
408
  return fallback_quote(key, guard, "currency_mismatch") unless product.currency == guard.currency
389
409
 
390
- experiment = experiment_for(product, info.country)
391
- return base_quote(key, guard, product, info.country) unless experiment
410
+ # The country a visitor holds lives in the cookie, so it is read before the test is chosen.
411
+ guarded = config.country_hold.positive? && !product.regions.empty?
412
+ held = guarded ? visitor_for(request, context, info, scope, config) : nil
413
+ country = held ? held_country(held, guard, product, info.country, config.country_hold) : info.country
414
+ experiment = experiment_for(product, country)
415
+ return base_quote(key, guard, product, country, held, scope, info, config) unless experiment
392
416
  if experiment.variants.empty? || !experiment.variants.all? { |v| in_bounds?(product, v.price) }
393
417
  return fallback_quote(key, guard, "out_of_bounds")
394
418
  end
395
419
 
396
- region = region_for(guard, product, info.country)
397
- experiment_quote(key, guard, context, info, scope, config, product, experiment, region)
420
+ visitor = held || visitor_for(request, context, info, scope, config)
421
+ region = region_for(guard, product, country)
422
+ experiment_quote(key, guard, context, info, scope, config, product, experiment, region, country, visitor)
398
423
  rescue StandardError => e
399
424
  report(e)
400
425
  bot ? fallback_quote(key, guard, "bot") : no_config(key, guard, scope)
@@ -409,7 +434,7 @@ module Leverprice
409
434
  experiment.scope.include?(country) ? experiment : nil
410
435
  end
411
436
 
412
- def base_quote(key, guard, product, country)
437
+ def base_quote(key, guard, product, country, held, scope, info, config)
413
438
  return fallback_quote(key, guard, "out_of_bounds") unless in_bounds?(product, product.price)
414
439
 
415
440
  region = region_for(guard, product, country)
@@ -419,6 +444,11 @@ module Leverprice
419
444
  price_quote(key, guard, product.price, "base_price", product.checkout_url)
420
445
  end
421
446
  quote.country = country
447
+ if held
448
+ cookies = keep(held, scope, info, config)
449
+ # Outside a test the cookie only carries the held country: none held, none sent.
450
+ quote.set_cookie = held.state.c ? cookies : []
451
+ end
422
452
  quote
423
453
  end
424
454
 
@@ -444,38 +474,34 @@ module Leverprice
444
474
  fallback_quote(key, guard, "bot")
445
475
  end
446
476
 
447
- def experiment_quote(key, guard, context, info, scope, config, product, experiment, region)
448
- hmac_key = hmac_key_for(config.assignment_key)
449
- user_id = normalize_user_id(context.user_id)
450
- state = prior_state(scope, info, user_id, config) || verified_state(hmac_key, info)
451
- changed = state.nil?
452
- state ||= Cookie.new_state(Util.random_hex(16))
453
-
454
- visitor_key = user_id ? "u:#{user_id}" : "a:#{state.v}"
477
+ def experiment_quote(key, guard, context, info, scope, config, product, experiment, region, country, visitor)
478
+ hmac_key = visitor.key
479
+ state = visitor.state
480
+ visitor_key = visitor.user_id ? "u:#{visitor.user_id}" : "a:#{state.v}"
455
481
  visitor_id = Util.hmac_hex(hmac_key, "pp:visitor:v1:#{visitor_key}", 32)
456
482
  assigned = state.a[experiment.id]
457
483
  sticky = assigned && experiment.variants.find { |v| v.id == assigned }
458
484
  variant = sticky || Util.pick_variant(experiment.variants, Util.bucket_for(experiment.salt, visitor_id),
459
- experiment.split_of[info.country])
485
+ experiment.split_of[country])
460
486
  unless sticky
461
487
  Cookie.assign(state, experiment.id, variant.id)
462
- changed = true
488
+ visitor.changed = true
463
489
  end
464
490
 
465
491
  logged = state.x.include?(experiment.id) || exposed?(experiment.id, visitor_id)
466
492
  if !logged && auto_exposure?(context.exposure) && !info.prefetch
467
- record_exposure(experiment.id, variant.id, visitor_id, info.country)
493
+ record_exposure(experiment.id, variant.id, visitor_id, country)
468
494
  logged = true
469
495
  end
470
- changed = true if logged && Cookie.mark_exposed(state, experiment.id)
471
- scope.cookie = ScopeCookie.new(info.cookie_input, user_id, config.assignment_key, state) if scope
496
+ visitor.changed = true if logged && Cookie.mark_exposed(state, experiment.id)
497
+ set_cookie = keep(visitor, scope, info, config)
472
498
 
473
499
  signature = Util.hmac_hex(hmac_key, "pp:attr:v1:#{experiment.id}:#{variant.id}:#{visitor_id}", 16)
474
500
  Quote.new(
475
501
  product_key: key,
476
502
  price: region ? variant.regional[region.index] : variant.price,
477
503
  currency: region ? region.currency : guard.currency,
478
- country: info.country,
504
+ country: country,
479
505
  regional: !region.nil?,
480
506
  is_fallback: false,
481
507
  reason: "experiment",
@@ -483,12 +509,64 @@ module Leverprice
483
509
  variant_id: variant.id,
484
510
  visitor_id: visitor_id,
485
511
  metadata: { "pp_exp" => experiment.id, "pp_var" => variant.id, "pp_vid" => visitor_id, "pp_sig" => signature },
486
- set_cookie: changed ? [assignment_cookie(hmac_key, state)] : [],
512
+ set_cookie: set_cookie,
487
513
  checkout_url: region ? nil : (variant.checkout_url || product.checkout_url),
488
514
  exposure_logged: logged
489
515
  )
490
516
  end
491
517
 
518
+ # The visitor behind the request: the state an earlier quote of the same request left, else the first valid
519
+ # assignment cookie, else a new visitor.
520
+ def visitor_for(request, context, info, scope, config)
521
+ hmac_key = hmac_key_for(config.assignment_key)
522
+ user_id = normalize_user_id(context.user_id)
523
+ state = prior_state(scope, info, user_id, config) || verified_state(hmac_key, info)
524
+ return Visitor.new(hmac_key, user_id, state, false) if state
525
+
526
+ Visitor.new(hmac_key, user_id, Cookie.new_state(new_visitor_key(hmac_key, request, info)), true)
527
+ end
528
+
529
+ # A browser without a cookie comes back as a new visitor every time, so its key comes from what stays the same
530
+ # between its requests (address, browser, languages), keyed by the project's secret: a visitor who refuses
531
+ # cookies keeps one price and counts once. Neither the address nor the browser leaves the server.
532
+ def new_visitor_key(hmac_key, request, info)
533
+ address = Request.client_address(request)
534
+ return Util.random_hex(16) unless address
535
+
536
+ language = Request.header(request, "accept-language") || ""
537
+ Util.hmac_hex(hmac_key, "pp:anon:v1:#{address}\n#{info.user_agent}\n#{language}", 32)
538
+ end
539
+
540
+ # Leverprice's VPN guard: a visitor seen lately in a country that pays more keeps that country's price, so
541
+ # switching a VPN to a cheaper country changes nothing until the hold runs out. Anywhere else, the visitor is
542
+ # priced where they are and that country is held from now on.
543
+ def held_country(visitor, guard, product, country, hold_seconds)
544
+ seconds = (now / 1000).floor
545
+ state = visitor.state
546
+ held = state.c && state.t && seconds - state.t < hold_seconds ? state.c : nil
547
+ return held if held && held != country && level_of(guard, product, held) > level_of(guard, product, country)
548
+
549
+ if country && held != country
550
+ state.c = country
551
+ state.t = seconds
552
+ visitor.changed = true
553
+ end
554
+ country
555
+ end
556
+
557
+ # What a visitor from `country` pays, as basis points of the standard price.
558
+ def level_of(guard, product, country)
559
+ region = region_for(guard, product, country)
560
+ region ? product.regions[region.index].level : Wire::STANDARD_LEVEL
561
+ end
562
+
563
+ # Remembers the visitor for the request's next quote; the Set-Cookie values when its state changed.
564
+ def keep(visitor, scope, info, config)
565
+ state = visitor.state
566
+ scope.cookie = ScopeCookie.new(info.cookie_input, visitor.user_id, config.assignment_key, state) if scope
567
+ visitor.changed ? [assignment_cookie(visitor.key, state)] : []
568
+ end
569
+
492
570
  def prior_state(scope, info, user_id, config)
493
571
  prior = scope&.cookie
494
572
  return nil unless prior && prior.input == info.cookie_input && prior.user_id == user_id &&
@@ -618,6 +696,20 @@ module Leverprice
618
696
  raise ArgumentError, "Leverprice: country_header is not a valid header name"
619
697
  end
620
698
 
699
+ # `key=currency` per product, sorted by the percent-encoded key, at most 50: tells the dashboard what the code
700
+ # prices.
701
+ def products_header(guards)
702
+ guards.map { |key, guard| [encode_key(key), guard.currency] }
703
+ .sort_by(&:first)
704
+ .first(MAX_REPORTED_PRODUCTS)
705
+ .map { |key, currency| "#{key}=#{currency}" }
706
+ .join(", ")
707
+ end
708
+
709
+ def encode_key(key)
710
+ Util.utf8(key).b.each_char.map { |char| UNRESERVED_RE.match?(char) ? char : format("%%%02X", char.ord) }.join
711
+ end
712
+
621
713
  def option(hash, *names)
622
714
  return nil unless hash.is_a?(Hash)
623
715
 
@@ -648,9 +740,20 @@ module Leverprice
648
740
  end
649
741
  return nil unless flight
650
742
 
651
- remaining = @timeout_ms - (started - flight.started_at)
652
- flight.wait(remaining / 1000.0) if remaining.positive?
653
- @lock.synchronize { usable(now) }
743
+ # Each request waits its own timeout_ms: a fetch started earlier (preload, another request) must not
744
+ # shorten it.
745
+ finished = @timeout_ms.positive? ? flight.wait(@timeout_ms / 1000.0) : true
746
+ config, slow = @lock.synchronize do
747
+ ready = usable(now)
748
+ slow = ready.nil? && !finished && @inflight.equal?(flight) && !flight.slow_reported
749
+ flight.slow_reported = true if slow
750
+ [ready, slow]
751
+ end
752
+ if slow
753
+ report(Error.new("Leverprice config: still loading after #{@timeout_ms} ms (timeout_ms); " \
754
+ "serving fallback prices until it arrives"))
755
+ end
756
+ config
654
757
  end
655
758
 
656
759
  def usable(at)
@@ -711,13 +814,19 @@ module Leverprice
711
814
  end
712
815
 
713
816
  def load_config(unconditional)
714
- headers = {}
715
- @lock.synchronize { headers["If-None-Match"] = @etag if !unconditional && @etag && usable(now) }
817
+ # Tells the dashboard whether visitors get real prices: the products in code, and why the last config was
818
+ # refused.
819
+ headers = { PRODUCTS_HEADER => @products_header }
820
+ @lock.synchronize do
821
+ headers[CONFIG_ERROR_HEADER] = @config_error if @config_error
822
+ headers["If-None-Match"] = @etag if !unconditional && @etag && usable(now)
823
+ end
716
824
  response = http("GET", "/v1/config", headers)
717
825
  warning = @lock.synchronize { apply_config(response, headers.key?("If-None-Match")) }
718
826
  report(Error.new(warning)) if warning
719
827
  rescue StandardError => e
720
828
  @lock.synchronize do
829
+ @config_error = e.code if e.is_a?(ConfigError)
721
830
  @failures += 1
722
831
  @retry_at = now + [MAX_BACKOFF_MS, 500 * (2**[@failures, 16].min)].min
723
832
  end
@@ -732,6 +841,7 @@ module Leverprice
732
841
  end
733
842
 
734
843
  warning = @acceptance.accept(parse_envelope(response.body), now).warning
844
+ @config_error = nil
735
845
  @etag = response.header("ETag")
736
846
  end
737
847
  @fetched_at = now
@@ -744,7 +854,7 @@ module Leverprice
744
854
  def parse_envelope(body)
745
855
  Util.parse_json(body)
746
856
  rescue StandardError
747
- raise Error, "Leverprice config: response is not JSON"
857
+ raise ConfigError.new("malformed", "Leverprice config: response is not JSON")
748
858
  end
749
859
 
750
860
  def note_server_version(response)
@@ -8,8 +8,10 @@ module Leverprice
8
8
  VISITOR_KEY_RE = /\A[0-9a-f]{32}\z/
9
9
  BODY_RE = /\A[A-Za-z0-9_-]+\z/
10
10
  SIG_RE = /\A[A-Za-z0-9_-]{22}\z/
11
+ COUNTRY_RE = /\A[A-Z]{2}\z/
11
12
 
12
- State = Struct.new(:v, :a, :x)
13
+ # `c` and `t`: the country whose price the visitor holds, and since when (seconds since the epoch).
14
+ State = Struct.new(:v, :a, :x, :c, :t)
13
15
 
14
16
  module_function
15
17
 
@@ -18,7 +20,7 @@ module Leverprice
18
20
  end
19
21
 
20
22
  def clone_state(state)
21
- State.new(state.v, state.a.dup, state.x.dup)
23
+ State.new(state.v, state.a.dup, state.x.dup, state.c, state.t)
22
24
  end
23
25
 
24
26
  def assign(state, experiment_id, variant_id)
@@ -35,7 +37,9 @@ module Leverprice
35
37
  end
36
38
 
37
39
  def serialize(state)
38
- JSON.generate({ "v" => state.v, "a" => state.a, "x" => state.x })
40
+ body = { "v" => state.v, "a" => state.a, "x" => state.x }
41
+ body.merge!("c" => state.c, "t" => state.t) if state.c && state.t
42
+ JSON.generate(body)
39
43
  end
40
44
 
41
45
  def sign(key, state)
@@ -70,7 +74,13 @@ module Leverprice
70
74
  assignments[experiment_id] = variant_id if Util.id?(experiment_id) && Util.id?(variant_id)
71
75
  end
72
76
  exposed = raw["x"].is_a?(Array) ? raw["x"].select { |id| id.is_a?(String) && assignments.key?(id) } : []
73
- State.new(raw["v"], assignments, exposed.first(MAX_EXPERIMENTS))
77
+ state = State.new(raw["v"], assignments, exposed.first(MAX_EXPERIMENTS))
78
+ since = Util.safe_int(raw["t"])
79
+ if Util.str_match?(COUNTRY_RE, raw["c"]) && since && since >= 0
80
+ state.c = raw["c"]
81
+ state.t = since
82
+ end
83
+ state
74
84
  end
75
85
 
76
86
  def header(name, value, max_age, secure:, domain:)
@@ -4,8 +4,9 @@ module Leverprice
4
4
  # The price to show and charge, and why.
5
5
  #
6
6
  # `reason` is one of "experiment", "base_price", "bot", "disabled", "no_config", "pinned_fallback",
7
- # "unknown_product", "currency_mismatch" or "out_of_bounds". `country` is the visitor's country (ISO 3166-1
8
- # alpha-2) when known; with a regional price, `currency` is the region's currency.
7
+ # "unknown_product", "currency_mismatch" or "out_of_bounds". `country` is the country whose price applies (ISO
8
+ # 3166-1 alpha-2) when known: the visitor's, or a dearer one they were seen in lately (Leverprice's VPN guard).
9
+ # With a regional price, `currency` is the region's currency.
9
10
  Quote = Struct.new(
10
11
  :product_key, :price, :currency, :is_fallback, :reason, :experiment_id, :variant_id,
11
12
  :visitor_id, :metadata, :set_cookie, :checkout_url, :exposure_logged, :country, :regional,
@@ -10,6 +10,21 @@ module Leverprice
10
10
  RACK_ENV_MARKERS = %w[REQUEST_METHOD rack.version SERVER_NAME].freeze
11
11
  NOT_A_COUNTRY = %w[XX ZZ T1 A1 A2 AP EU].freeze
12
12
  COUNTRY_INPUT_RE = /\A[ \t\n\x0B\x0C\r]*([A-Za-z]{2})[ \t\n\x0B\x0C\r]*\z/
13
+ # Headers every browser or client sends itself: never a source for the visitor's country.
14
+ VISITOR_SET_PREFIX_RE = /\A(?:sec-|accept|content-|if-|x-forwarded-|proxy-)/
15
+ VISITOR_SET_HEADERS = %w[
16
+ authorization cache-control connection cookie dnt forwarded host origin pragma priority purpose range referer
17
+ te upgrade-insecure-requests user-agent via x-real-ip x-requested-with
18
+ ].freeze
19
+ # Headers proxies and hosts set to the visitor's address, in the order they are read.
20
+ ADDRESS_HEADERS = %w[
21
+ cf-connecting-ip true-client-ip fastly-client-ip fly-client-ip x-real-ip x-forwarded-for
22
+ ].freeze
23
+ IPV4_RE = /\A(0|[1-9][0-9]{0,2})\.(0|[1-9][0-9]{0,2})\.(0|[1-9][0-9]{0,2})\.(0|[1-9][0-9]{0,2})\z/
24
+ HEX_GROUP_RE = /\A[0-9A-Fa-f]{1,4}\z/
25
+ ADDRESS_BLANKS_RE = /\A[ \t]+|[ \t]+\z/
26
+ BRACKET_PORT_RE = /\A:[0-9]{1,5}\z/
27
+ IPV4_PORT_RE = /\A[0-9.]+:[0-9]{1,5}\z/
13
28
 
14
29
  Info = Struct.new(:cookie_input, :assignment_cookies, :pinned, :user_agent, :prefetch, :country,
15
30
  keyword_init: true)
@@ -55,6 +70,103 @@ module Leverprice
55
70
  NOT_A_COUNTRY.include?(code) ? nil : code
56
71
  end
57
72
 
73
+ def visitor_set_header?(name)
74
+ return false unless name.is_a?(String)
75
+
76
+ lower = name.b.downcase
77
+ VISITOR_SET_PREFIX_RE.match?(lower) || VISITOR_SET_HEADERS.include?(lower)
78
+ end
79
+
80
+ # The visitor's address: the first address header that holds one, else the connection's.
81
+ def client_address(request)
82
+ return nil if request.nil?
83
+
84
+ ADDRESS_HEADERS.each do |name|
85
+ value = header(request, name)
86
+ next if value.nil?
87
+
88
+ address = normalize_address(value.split(",", 2).first)
89
+ return address if address
90
+ end
91
+ normalize_address(connection_address(request))
92
+ end
93
+
94
+ # `REMOTE_ADDR` of a Rack env, or of the env behind a Rack or ActionDispatch request.
95
+ def connection_address(request)
96
+ env = request.is_a?(Hash) ? request : rack_env(request)
97
+ if env
98
+ return nil unless RACK_ENV_MARKERS.any? { |marker| env.key?(marker) }
99
+
100
+ return env["REMOTE_ADDR"]
101
+ end
102
+ request.respond_to?(:get_header) ? request.get_header("REMOTE_ADDR") : nil
103
+ rescue StandardError
104
+ nil
105
+ end
106
+
107
+ # IPv4 in decimal, IPv6 cut to its /64 network as four lowercase hex groups, IPv4-mapped IPv6 as IPv4;
108
+ # brackets, a port and a zone are dropped. nil for anything else.
109
+ def normalize_address(value)
110
+ return nil unless value.is_a?(String)
111
+
112
+ text = Util.utf8(value).b.gsub(ADDRESS_BLANKS_RE, "")
113
+ if text.start_with?("[")
114
+ close = text.index("]")
115
+ return nil if close.nil?
116
+
117
+ rest = text[(close + 1)..]
118
+ return nil unless rest.empty? || BRACKET_PORT_RE.match?(rest)
119
+
120
+ text = text[1...close]
121
+ elsif IPV4_PORT_RE.match?(text)
122
+ text = text[0, text.index(":")]
123
+ end
124
+ zone = text.index("%")
125
+ text = text[0, zone] if zone
126
+ v4 = ipv4(text)
127
+ return v4.join(".") if v4
128
+
129
+ groups = ipv6(text)
130
+ return nil unless groups
131
+ if groups[0, 5].all?(&:zero?) && groups[5] == 0xffff
132
+ return [groups[6] >> 8, groups[6] & 255, groups[7] >> 8, groups[7] & 255].join(".")
133
+ end
134
+
135
+ groups[0, 4].map { |group| group.to_s(16) }.join(":")
136
+ end
137
+
138
+ def ipv4(text)
139
+ match = IPV4_RE.match(text)
140
+ return nil unless match
141
+
142
+ parts = match.captures.map(&:to_i)
143
+ parts.all? { |part| part <= 255 } ? parts : nil
144
+ end
145
+
146
+ def ipv6(text)
147
+ if text.include?(".")
148
+ colon = text.rindex(":")
149
+ v4 = colon && ipv4(text[(colon + 1)..])
150
+ return nil unless v4
151
+
152
+ text = "#{text[0..colon]}#{((v4[0] << 8) | v4[1]).to_s(16)}:#{((v4[2] << 8) | v4[3]).to_s(16)}"
153
+ end
154
+ halves = text.split("::", -1)
155
+ return nil if halves.empty? || halves.size > 2
156
+
157
+ head = halves[0].split(":", -1)
158
+ tail = halves[1]&.split(":", -1)
159
+ groups = head + (tail || [])
160
+ return nil unless groups.all? { |group| HEX_GROUP_RE.match?(group) }
161
+
162
+ values = groups.map { |group| group.to_i(16) }
163
+ return values.size == 8 ? values : nil if tail.nil?
164
+ return nil if groups.size > 7
165
+
166
+ head_values = values.first(head.size)
167
+ head_values + ([0] * (8 - groups.size)) + values.drop(head.size)
168
+ end
169
+
58
170
  def header(request, name)
59
171
  value = lookup(request, name)
60
172
  case value
@@ -29,20 +29,24 @@ module Leverprice
29
29
  def verify(envelope, now)
30
30
  unless envelope.is_a?(Hash) && envelope["payload"].is_a?(String) && envelope["signature"].is_a?(String) &&
31
31
  envelope["keyId"].is_a?(String)
32
- raise Error, "Leverprice config: response is not a signed config"
32
+ raise ConfigError.new("malformed", "Leverprice config: response is not a signed config")
33
33
  end
34
34
 
35
- keyset = verify_keyset(envelope["keyset"], now)
35
+ keyset = coded("untrusted") { verify_keyset(envelope["keyset"], now) }
36
36
  key_id = envelope["keyId"]
37
37
  key = keyset.keys.find { |k| k.id == key_id }
38
- raise Error, %(Leverprice config: signing key "#{key_id}" is not in keyset v#{keyset.version}) unless key
38
+ unless key
39
+ raise ConfigError.new("bad_signature",
40
+ %(Leverprice config: signing key "#{key_id}" is not in keyset v#{keyset.version}))
41
+ end
39
42
  unless Util.ed25519_verify(key.public_key, envelope["signature"], envelope["payload"])
40
- raise Error, %(Leverprice config: bad signature (key "#{key_id}"))
43
+ raise ConfigError.new("bad_signature", %(Leverprice config: bad signature (key "#{key_id}")))
41
44
  end
42
45
 
43
- config, dropped = Wire.parse_config(envelope["payload"])
46
+ config, dropped = coded("malformed") { Wire.parse_config(envelope["payload"]) }
44
47
  if now >= config.expires_at
45
- raise Error, "Leverprice config v#{config.version}: expired at #{Util.iso_time(config.expires_at)}"
48
+ raise ConfigError.new("expired",
49
+ "Leverprice config v#{config.version}: expired at #{Util.iso_time(config.expires_at)}")
46
50
  end
47
51
 
48
52
  Verified.new(config, SigningKey.new(key.id, key.public_key), dropped)
@@ -50,6 +54,14 @@ module Leverprice
50
54
 
51
55
  private
52
56
 
57
+ def coded(code)
58
+ yield
59
+ rescue ConfigError
60
+ raise
61
+ rescue StandardError => e
62
+ raise ConfigError.new(code, e.message)
63
+ end
64
+
53
65
  def verify_keyset(signed, now)
54
66
  unless signed.is_a?(Hash) && signed["payload"].is_a?(String) && signed["signature"].is_a?(String) &&
55
67
  signed["rootKeyId"].is_a?(String)
@@ -140,15 +152,17 @@ module Leverprice
140
152
  config = verified.config
141
153
  # A validly signed config of another project (e.g. from a compromised cache) is refused even on first load.
142
154
  unless config.key_fingerprints.include?(@fingerprint)
143
- raise Error, "Leverprice config: not issued for this API key; refusing"
155
+ raise ConfigError.new("wrong_key", "Leverprice config: not issued for this API key; refusing")
144
156
  end
145
157
 
146
158
  current = self.config
147
159
  if current && config.project_id != current.project_id
148
- raise Error, "Leverprice config: project changed from #{current.project_id} to #{config.project_id}; refusing"
160
+ raise ConfigError.new("wrong_project", "Leverprice config: project changed from #{current.project_id} " \
161
+ "to #{config.project_id}; refusing")
149
162
  end
150
163
  if current && config.version < current.version
151
- raise Error, "Leverprice config: refusing to roll back from version #{current.version} to #{config.version}"
164
+ raise ConfigError.new("rollback", "Leverprice config: refusing to roll back from version " \
165
+ "#{current.version} to #{config.version}")
152
166
  end
153
167
 
154
168
  warning = nil
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Leverprice
4
- VERSION = "0.4.0"
4
+ VERSION = "0.4.1"
5
5
  end
@@ -3,6 +3,17 @@
3
3
  require "set"
4
4
 
5
5
  module Leverprice
6
+ # A refused config. `code` says why ("malformed", "untrusted", "bad_signature", "expired", "wrong_key",
7
+ # "wrong_project" or "rollback") and is reported to Leverprice with the next config request.
8
+ class ConfigError < Error
9
+ attr_reader :code
10
+
11
+ def initialize(code, message)
12
+ super(message)
13
+ @code = code
14
+ end
15
+ end
16
+
6
17
  # @api private
7
18
  module Wire
8
19
  PROTOCOL_VERSION = 2
@@ -12,6 +23,9 @@ module Leverprice
12
23
  MAX_REGIONS = 300
13
24
  MAX_SPLITS = 300
14
25
  MAX_SCOPE = 300
26
+ # The level of a country without a regional price: the standard price.
27
+ STANDARD_LEVEL = 10_000
28
+ MAX_COUNTRY_HOLD = 90 * 86_400
15
29
  PROVIDERS = %w[stripe polar lemonsqueezy dodo paddle creem other].freeze
16
30
  FINGERPRINT_RE = /\A[0-9a-f]{16}\z/
17
31
  SIGNATURE_RE = /\A[0-9a-f]{16}\z/
@@ -23,11 +37,13 @@ module Leverprice
23
37
 
24
38
  Variant = Struct.new(:id, :price, :weight, :checkout_url, :regional, keyword_init: true)
25
39
  Experiment = Struct.new(:id, :salt, :variants, :scope, :split_of, keyword_init: true)
26
- Region = Struct.new(:countries, :currency, :price, keyword_init: true)
40
+ # `level`: the price as basis points of the standard price (10000 = the same), to compare countries.
41
+ Region = Struct.new(:countries, :currency, :price, :level, keyword_init: true)
27
42
  Product = Struct.new(:id, :currency, :price, :min_price, :max_price, :checkout_url, :regions, :region_of,
28
43
  :experiment, keyword_init: true)
44
+ # `country_hold`: seconds a visitor keeps the price of a dearer country they were seen in; 0 is off.
29
45
  Config = Struct.new(:project_id, :version, :issued_at, :expires_at, :assignment_key, :key_fingerprints,
30
- :country_header, :products, keyword_init: true)
46
+ :country_header, :country_hold, :products, keyword_init: true)
31
47
 
32
48
  module_function
33
49
 
@@ -78,13 +94,22 @@ module Leverprice
78
94
  assignment_key: assignment_key,
79
95
  key_fingerprints: fingerprints,
80
96
  country_header: header_name(raw["countryHeader"]),
97
+ country_hold: country_hold(raw["countryHold"]),
81
98
  products: parsed
82
99
  )
83
100
  [config, dropped]
84
101
  end
85
102
 
103
+ # A header visitors send themselves would let them pick their own price: never read.
86
104
  def header_name(value)
87
- Util.str_match?(HEADER_NAME_RE, value) ? value.downcase(:ascii) : nil
105
+ return nil unless Util.str_match?(HEADER_NAME_RE, value) && !Request.visitor_set_header?(value)
106
+
107
+ value.downcase(:ascii)
108
+ end
109
+
110
+ def country_hold(value)
111
+ seconds = Util.safe_int(value)
112
+ seconds&.positive? && seconds <= MAX_COUNTRY_HOLD ? seconds : 0
88
113
  end
89
114
 
90
115
  def parse_product(raw)
@@ -137,7 +162,10 @@ module Leverprice
137
162
  price = Util.safe_int(region["price"])
138
163
  return nil unless Util.str_match?(CURRENCY_RE, currency) && price&.positive?
139
164
 
140
- Region.new(countries: region["countries"], currency: currency.downcase, price: price)
165
+ # A level this SDK can't read compares as the standard price: it never holds a price.
166
+ level = Util.safe_int(region["level"])
167
+ Region.new(countries: region["countries"], currency: currency.downcase, price: price,
168
+ level: level&.positive? ? level : STANDARD_LEVEL)
141
169
  end
142
170
  end
143
171
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: leverprice
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.4.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Leverprice