leverprice 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 753711f844bb0ef50ab286ca7abe669c66b78c850fb895e3f01480f3cdf6a69d
4
+ data.tar.gz: 4c166ab47c428b40c4504e8d3065a88d7198e8159b805b68e58d748738291ee7
5
+ SHA512:
6
+ metadata.gz: f0279eeb2183781d6dd8cd359343d572fe1570c3aa97edb54574b79dbbe3ada36a1c28f45b99285e526b59ef669a440d056e67b4136af191e81e0cfce921408c
7
+ data.tar.gz: 3d4786181bb23e7fd60e4a663d8f1c5eceabff85d950b13e12d187071e52fbbd04c195d78e225d006a49dea5c0ccfdd123769f98204401721f5377e1334403c7
data/CHANGELOG.md ADDED
@@ -0,0 +1,18 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0 (2026-11-17)
4
+
5
+ First release of the Ruby SDK, implementing protocol v2 of the Leverprice server SDK.
6
+
7
+ - `Leverprice::Client` with `get_price`, `log_exposure`, `track_purchase`, `track_refund`, `flush`, `refresh`,
8
+ `preload` and `close`.
9
+ - Configs verified through the root, keyset and config signature chain (Ed25519 via OpenSSL), with key revocation,
10
+ rollback protection and expiry.
11
+ - Signed, sticky assignment cookie shared by every quote of one request, and an outage pin cookie.
12
+ - Automatic or manual exposure logging with prefetch detection, and `Leverprice.bot?`.
13
+ - Batched event delivery with retries and a background flush thread. Thread-safe and fork-safe (Puma, Unicorn,
14
+ Passenger).
15
+ - Reads Rack envs, Rack and ActionDispatch requests, header objects and plain Hashes. `Leverprice.write_cookies` for
16
+ Rack 2 and Rack 3 responses.
17
+ - Kill switch through `disabled: true` or `LEVERPRICE_DISABLED`.
18
+ - No runtime dependencies.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Leverprice
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,271 @@
1
+ # Leverprice Ruby SDK
2
+
3
+ Server-side SDK for [Leverprice](https://leverprice.com) price experiments. Ruby 3.1 or later, no runtime dependencies (OpenSSL, Net::HTTP and JSON from the standard library). Thread-safe and fork-safe, so it works under Puma, Unicorn, Passenger, Sidekiq and plain Rack.
4
+
5
+ **Your payments stay yours.** The SDK gives your server a number. Your own code creates the checkout with your own provider keys. Leverprice never sees card data or provider API keys.
6
+
7
+ ```sh
8
+ bundle add leverprice
9
+ ```
10
+
11
+ ## Quick start
12
+
13
+ ### Rails
14
+
15
+ ```ruby
16
+ # config/initializers/leverprice.rb
17
+ LEVERPRICE = Leverprice::Client.new(
18
+ secret_key: ENV["LEVERPRICE_SECRET_KEY"], # server-only
19
+ products: {
20
+ # Local guardrails: prices outside these bounds are never returned.
21
+ "pro" => { currency: "usd", fallback_price: 1900, min_price: 1500, max_price: 3900 },
22
+ },
23
+ logger: Rails.logger,
24
+ )
25
+ LEVERPRICE.preload # optional: fetch the config at boot instead of on the first request
26
+ at_exit { LEVERPRICE.close }
27
+ ```
28
+
29
+ Show the price, then charge the same price at checkout. Never trust a price sent by the browser.
30
+
31
+ ```ruby
32
+ class PricingController < ApplicationController
33
+ def show
34
+ @quote = LEVERPRICE.get_price("pro", request: request, user_id: current_user&.id)
35
+ Leverprice.write_cookies(response, @quote)
36
+ # @quote.price is in minor units (1900 = $19.00)
37
+ end
38
+ end
39
+
40
+ class CheckoutsController < ApplicationController
41
+ def create
42
+ quote = LEVERPRICE.get_price("pro", request: request, user_id: current_user&.id)
43
+ Leverprice.write_cookies(response, quote)
44
+ session = Stripe::Checkout::Session.create(
45
+ mode: "payment",
46
+ line_items: [{
47
+ quantity: 1,
48
+ price_data: { currency: quote.currency, unit_amount: quote.price, product_data: { name: "Pro" } },
49
+ }],
50
+ metadata: quote.metadata, # signed attribution: pass it whole
51
+ payment_intent_data: { metadata: quote.metadata },
52
+ success_url: root_url,
53
+ cancel_url: pricing_url,
54
+ )
55
+ redirect_to session.url, allow_other_host: true, status: :see_other
56
+ end
57
+ end
58
+ ```
59
+
60
+ Report the purchase from your webhook (or connect your provider's webhooks to Leverprice directly):
61
+
62
+ ```ruby
63
+ class StripeWebhooksController < ActionController::API
64
+ def create
65
+ event = Stripe::Webhook.construct_event(
66
+ request.raw_post, request.headers["Stripe-Signature"], ENV.fetch("STRIPE_WEBHOOK_SECRET"),
67
+ )
68
+ if event.type == "checkout.session.completed"
69
+ session = event.data.object
70
+ LEVERPRICE.track_purchase(
71
+ provider: "stripe",
72
+ order_id: session.payment_intent,
73
+ amount: session.amount_total - (session.total_details&.amount_tax || 0),
74
+ currency: session.currency,
75
+ metadata: session.metadata.to_h,
76
+ timestamp: event.created, # Unix seconds are converted
77
+ )
78
+ end
79
+ head :ok
80
+ end
81
+ end
82
+ ```
83
+
84
+ `Leverprice.write_cookies` appends the quote's `Set-Cookie` values correctly on Rack 2 and Rack 3. On Rack 3 (Rails 7.1+ with Rack 3, Sinatra 4) you can also write them yourself with `quote.set_cookie.each { |c| response.add_header("set-cookie", c) }`; on Rack 2, join them with `"\n"` into one `Set-Cookie` header.
85
+
86
+ ### Sinatra
87
+
88
+ ```ruby
89
+ require "sinatra"
90
+ require "leverprice"
91
+
92
+ LEVERPRICE = Leverprice::Client.new(
93
+ secret_key: ENV["LEVERPRICE_SECRET_KEY"],
94
+ products: { "pro" => { currency: "usd", fallback_price: 1900, min_price: 1500, max_price: 3900 } },
95
+ )
96
+
97
+ get "/pricing" do
98
+ quote = LEVERPRICE.get_price("pro", request: request, user_id: session[:user_id])
99
+ Leverprice.write_cookies(response, quote)
100
+ erb :pricing, locals: { quote: quote }
101
+ end
102
+
103
+ post "/checkout" do
104
+ quote = LEVERPRICE.get_price("pro", request: request, user_id: session[:user_id])
105
+ Leverprice.write_cookies(response, quote)
106
+ checkout = Stripe::Checkout::Session.create(
107
+ mode: "payment",
108
+ line_items: [{ quantity: 1, price_data: { currency: quote.currency, unit_amount: quote.price,
109
+ product_data: { name: "Pro" } } }],
110
+ metadata: quote.metadata,
111
+ payment_intent_data: { metadata: quote.metadata },
112
+ success_url: url("/thanks"), cancel_url: url("/pricing"),
113
+ )
114
+ redirect checkout.url, 303
115
+ end
116
+
117
+ post "/webhooks/stripe" do
118
+ event = Stripe::Webhook.construct_event(request.body.read, env["HTTP_STRIPE_SIGNATURE"], ENV["STRIPE_WEBHOOK_SECRET"])
119
+ if event.type == "checkout.session.completed"
120
+ s = event.data.object
121
+ LEVERPRICE.track_purchase(provider: "stripe", order_id: s.payment_intent,
122
+ amount: s.amount_total - (s.total_details&.amount_tax || 0),
123
+ currency: s.currency, metadata: s.metadata.to_h, timestamp: event.created)
124
+ end
125
+ 200
126
+ end
127
+ ```
128
+
129
+ ### Rack
130
+
131
+ ```ruby
132
+ # config.ru
133
+ require "leverprice"
134
+
135
+ LEVERPRICE = Leverprice::Client.new(
136
+ secret_key: ENV["LEVERPRICE_SECRET_KEY"],
137
+ products: { "pro" => { currency: "usd", fallback_price: 1900, min_price: 1500, max_price: 3900 } },
138
+ )
139
+
140
+ run lambda { |env|
141
+ quote = LEVERPRICE.get_price("pro", request: env)
142
+ headers = { "content-type" => "text/plain" }
143
+ Leverprice.write_cookies(headers, quote)
144
+ [200, headers, ["Pro: #{format('%.2f', quote.price / 100.0)} #{quote.currency.upcase}"]]
145
+ }
146
+ ```
147
+
148
+ ## Guarantees
149
+
150
+ - **Fails safe.** If Leverprice is off, slow (no config within 500 ms), down, misconfigured or returns anything unexpected, `get_price` returns your `fallback_price`. It raises only for a product key missing from `products`, which is a bug in the calling code. `track_purchase`, `track_refund`, `log_exposure`, `flush`, `refresh`, `preload` and `close` never raise.
151
+ - **Verified config.** Root key, keyset and config signatures are checked in a chain. Versions only move forward (no rollback, no revoked keys) and configs expire.
152
+ - **Bounded.** Every price is checked against your local `min_price`, `max_price` and `currency`.
153
+ - **Sticky and tamper-proof.** Visitors keep their price. The assignment cookie is HMAC-signed with your project's assignment key, delivered in the signed config, so rotating your API key does not reshuffle visitors.
154
+ - **Private.** Visitor and user ids are HMAC-hashed on your server. Leverprice only sees the hash.
155
+ - **No price flips.** A visitor who got the fallback during an outage keeps it for the rest of their session.
156
+ - **Search engines see the standard price.** Crawlers and link previews are never put into experiments.
157
+ - **Never in the way.** Background threads never keep your process alive, and events are sent off the request path.
158
+
159
+ ## Requests and cookies
160
+
161
+ Pass whatever request object you have: a Rack env Hash, a `Rack::Request` or `ActionDispatch::Request`, anything with `#headers`, or a plain Hash of header names (case-insensitive, Symbol keys and Array values allowed). The SDK reads the `Cookie` header, the `User-Agent` and prefetch hints. `cookie:` and `user_agent:` override what is read from the request.
162
+
163
+ `quote.set_cookie` is an Array of `Set-Cookie` header values: usually empty, one value when the assignment cookie (`__pp`) changes, or the outage pin (`__pp_f`). Write every value to your response.
164
+
165
+ 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.
166
+
167
+ `user_id:` accepts a String or an Integer. Convert other id types (UUID objects, `BSON::ObjectId`) with `to_s`.
168
+
169
+ ## Exposures
170
+
171
+ An exposure is one person seeing an experiment price. With `exposure: :auto` (the default) the SDK logs it the first time a visitor gets a price from an experiment, once per visitor and experiment. Prefetch and prerender requests (`Sec-Purpose`, `Purpose`, `X-Purpose`, `X-Moz`, `Next-Router-Prefetch`) are priced but not counted.
172
+
173
+ If you compute the price before it is visible, use manual mode:
174
+
175
+ ```ruby
176
+ quote = LEVERPRICE.get_price("pro", request: request, exposure: :manual)
177
+ # later, once the price is on screen:
178
+ LEVERPRICE.log_exposure(quote)
179
+ ```
180
+
181
+ Exposures are sent in batches within 2 seconds. Purchases and refunds are sent immediately.
182
+
183
+ ## Bots
184
+
185
+ Crawlers, link previewers (Slack, WhatsApp, iMessage), headless browsers, uptime monitors and command-line clients get the product's standard price (or your fallback when no config is available) with reason `"bot"`: no assignment, no cookie, no exposure. An empty user agent counts as a person. Pass `bot: true` or `bot: false` to use your own detection. The built-in check is `Leverprice.bot?(user_agent)`.
186
+
187
+ ## Kill switch
188
+
189
+ Set `LEVERPRICE_DISABLED=1` (or `true`), or pass `disabled: true`. The variable is read on every call. `get_price` then returns your fallback price with reason `"disabled"`, sets no cookies, makes no network calls and logs nothing, and `track_purchase`, `track_refund` and `log_exposure` do nothing. A missing or malformed `secret_key` behaves the same way; a malformed key is reported once through `on_error`.
190
+
191
+ ## Outages
192
+
193
+ When no usable config is available (reason `"no_config"`), the quote also sets `__pp_f=1` for 30 minutes. While a browser sends it, it gets the fallback price with reason `"pinned_fallback"` and is not enrolled. Each pinned request extends the pin, so the price changes only after 30 minutes of inactivity. The pin is unsigned on purpose: it can only select your own fallback price.
194
+
195
+ Failed config fetches back off exponentially up to 30 seconds. Purchases and refunds that cannot be delivered stay queued and are retried with the next flush.
196
+
197
+ ## Forking servers
198
+
199
+ Create the client once at boot. With `preload_app!` (Puma) or `preload_app true` (Unicorn), calling `preload` at boot means every worker starts with a verified config. The SDK detects forks and gives each worker its own threads, locks and event queue; a worker never re-sends events queued in the parent. Call `close` at shutdown (`at_exit`, or Puma's `on_worker_shutdown`) to send pending exposures.
200
+
201
+ ## Trust chain and updates
202
+
203
+ The SDK embeds only Leverprice's offline root public keys (`Leverprice::ROOT_PUBLIC_KEYS`). Each config carries a keyset of online signing keys, signed by a root key, and must itself be signed by one of those keys. Keyset versions only move forward within a process, so a revoked key cannot come back with an older keyset and a config it signed stops being trusted. `Leverprice::MIN_KEYSET_VERSION` sets the floor for fresh processes. Config versions only move forward and configs expire. For local development pass `trusted_root_keys: { "r1" => "<your dev root public key>" }`.
204
+
205
+ The config is revalidated every 30 seconds with an ETag, driven by traffic. When any Leverprice response announces a newer version in `Leverprice-Config-Version`, the SDK fetches it right away.
206
+
207
+ ## Reference
208
+
209
+ `get_price(product_key, request:, cookie:, user_agent:, user_id:, exposure:, bot:)` returns a `Leverprice::Quote`.
210
+
211
+ | Quote | |
212
+ |---|---|
213
+ | `product_key` | The key you asked for |
214
+ | `price` | Minor units; use it for display and as the checkout amount |
215
+ | `currency` | Lowercase ISO 4217, from your product guard |
216
+ | `is_fallback`, `fallback?` | `true` when `price` is your `fallback_price` |
217
+ | `reason` | See below |
218
+ | `experiment_id`, `variant_id` | Set when `reason` is `"experiment"`, else `nil` |
219
+ | `visitor_id` | Hashed visitor id Leverprice sees; `nil` unless `reason` is `"experiment"` |
220
+ | `metadata` | `{ "pp_exp", "pp_var", "pp_vid", "pp_sig" }` for the checkout (signed); `{}` otherwise |
221
+ | `set_cookie` | `Set-Cookie` values to write (zero or more) |
222
+ | `checkout_url` | Hosted checkout link for this price, or `nil` |
223
+ | `exposure_logged`, `exposure_logged?` | An exposure for this visitor and experiment has been logged |
224
+
225
+ | `reason` | Price |
226
+ |---|---|
227
+ | `experiment` | The visitor's sticky variant |
228
+ | `base_price` | Standard price (no experiment running) |
229
+ | `bot` | Standard price, or fallback if unavailable; never enrolled |
230
+ | `disabled` | Fallback: kill switch, or no valid secret key |
231
+ | `no_config` | Fallback: no usable signed config (timeout, outage, rejected or expired); sets the pin |
232
+ | `pinned_fallback` | Fallback: this browser got a fallback during an outage in this session |
233
+ | `unknown_product` | Fallback: the config has no such product |
234
+ | `currency_mismatch` | Fallback: the config's currency differs from your guard |
235
+ | `out_of_bounds` | Fallback: a price is outside your (or Leverprice's) min/max |
236
+
237
+ | Method | |
238
+ |---|---|
239
+ | `log_exposure(quote)` | Logs a manual-mode exposure; returns `true` if one was queued |
240
+ | `track_purchase(provider:, order_id:, amount:, currency:, metadata: nil, timestamp: nil)` | Reads `pp_exp`, `pp_var`, `pp_vid` and `pp_sig` from `metadata`. Providers: `stripe`, `polar`, `lemonsqueezy`, `dodo`, `other` |
241
+ | `track_refund(provider:, order_id:, currency:, refund_id:, amount:)` or `(…, refunded_total:)` | One refund, or the order's cumulative refunded total |
242
+ | `flush` | Sends queued events now (up to 500 per request, retried; purchases and refunds are kept on failure) |
243
+ | `refresh` / `preload` | Fetch the config now / only if none is usable |
244
+ | `close` | Flushes and stops the background flush thread |
245
+ | `Leverprice.write_cookies(response, quote)` | Writes `quote.set_cookie` to a Rails, Sinatra or Rack response, or a headers Hash |
246
+ | `Leverprice.bot?(user_agent)` | The built-in bot check |
247
+
248
+ | Option | Default | |
249
+ |---|---|---|
250
+ | `secret_key` | | `pp_sk_live_…` or `pp_sk_test_…` |
251
+ | `products` | | Product key to `{ currency:, fallback_price:, min_price: 1, max_price: 2**53 - 1 }` |
252
+ | `disabled` | `false` | Kill switch |
253
+ | `api_url` | `https://api.leverprice.com` | |
254
+ | `timeout_ms` | `500` | Longest a request waits for a config when none is usable |
255
+ | `refresh_interval_ms` | `30000` | Config revalidation period |
256
+ | `max_stale_ms` | `86400000` | Stop using a config this long after the server last confirmed it |
257
+ | `cookie_name` | `"__pp"` | The outage pin is `<cookie_name>_f` |
258
+ | `cookie_max_age_seconds` | `15552000` | 180 days |
259
+ | `cookie_secure` | `true` | Set `false` only for plain-HTTP development |
260
+ | `cookie_domain` | `nil` | |
261
+ | `flush_interval_ms` | `2000` | Longest exposures wait before being sent |
262
+ | `trusted_root_keys` | `ROOT_PUBLIC_KEYS` | For staging and local development |
263
+ | `on_error` | `nil` | Callable that receives every SDK error (`Leverprice::Error`) |
264
+ | `logger` | `nil` | Used for warnings when `on_error` is not set (default: `Kernel#warn`) |
265
+ | `transport` | Net::HTTP | Object with `call(method:, url:, headers:, body:, timeout:)` returning a `Leverprice::Response` or `[status, headers, body]` |
266
+
267
+ In tests, pass `disabled: true`, or a `transport` that returns canned responses.
268
+
269
+ ## License
270
+
271
+ MIT
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leverprice
4
+ # User-agent detection of crawlers, link previewers, headless browsers, monitors and HTTP tools.
5
+ module Bots
6
+ PATTERNS = [
7
+ "(?<!cu)bot(?![a-z])",
8
+ "crawl",
9
+ "spider",
10
+ "scrap",
11
+ "slurp",
12
+ "archiver",
13
+ "fetcher",
14
+ "\\+https?:",
15
+ "facebookexternalhit",
16
+ "facebookcatalog",
17
+ "meta-external",
18
+ "whatsapp/",
19
+ "skypeuripreview",
20
+ "bingpreview",
21
+ "microsoftpreview",
22
+ "link ?preview",
23
+ "url preview",
24
+ "web preview",
25
+ "slack-imgproxy",
26
+ "vkshare",
27
+ "embedly",
28
+ "iframely",
29
+ "cardyb",
30
+ "outbrain",
31
+ "flipboardproxy",
32
+ "mediapartners-google",
33
+ "apis-google",
34
+ "duplexweb-google",
35
+ "google-(?:inspectiontool|site-verification|read-aloud|pagerenderer|structured-data|safety)",
36
+ "googleother",
37
+ "googleproducer",
38
+ "google favicon",
39
+ "chatgpt-user",
40
+ "claude-user",
41
+ "perplexity-user",
42
+ "mistralai-user",
43
+ "anthropic-ai",
44
+ "cohere-ai",
45
+ "daumoa",
46
+ "ahrefs",
47
+ "sitebulb",
48
+ "siteimprove",
49
+ "barkrowler",
50
+ "botify",
51
+ "seokicks",
52
+ "validator",
53
+ "checklink",
54
+ "heritrix",
55
+ "headless",
56
+ "phantomjs",
57
+ "slimerjs",
58
+ "htmlunit",
59
+ "jsdom",
60
+ "cypress",
61
+ "lighthouse",
62
+ "page ?speed",
63
+ "gtmetrix",
64
+ "ptst/",
65
+ "pingdom",
66
+ "uptime",
67
+ "statuscake",
68
+ "site24x7",
69
+ "newrelicpinger",
70
+ "synthetic",
71
+ "checkly",
72
+ "health-?check",
73
+ "googlehc",
74
+ "kube-probe",
75
+ "nagios",
76
+ "zabbix",
77
+ "catchpoint",
78
+ "freshping",
79
+ "hetrixtools",
80
+ "ohdear",
81
+ "monitoring",
82
+ "curl",
83
+ "wget",
84
+ "httpie",
85
+ "python-requests",
86
+ "python-urllib",
87
+ "python-httpx",
88
+ "aiohttp",
89
+ "go-http-client",
90
+ "\\Ajava/",
91
+ "apache-httpclient",
92
+ "libwww-perl",
93
+ "lwp::",
94
+ "guzzlehttp",
95
+ "postmanruntime",
96
+ "insomnia",
97
+ "axios/",
98
+ "node-fetch",
99
+ "undici"
100
+ ].freeze
101
+
102
+ # Matched against the ASCII-lowercased user agent: case folding is ASCII-only on every platform.
103
+ PATTERN = Regexp.new(PATTERNS.join("|"))
104
+
105
+ module_function
106
+
107
+ # @param user_agent [String, nil]
108
+ # @return [Boolean] true for known bots; an empty or missing user agent is a person.
109
+ def bot?(user_agent)
110
+ return false unless user_agent.is_a?(String)
111
+
112
+ agent = Util.trim(user_agent)
113
+ !agent.empty? && PATTERN.match?(agent.downcase(:ascii))
114
+ end
115
+ end
116
+ end