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.
@@ -0,0 +1,172 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "openssl"
5
+ require "securerandom"
6
+
7
+ module Leverprice
8
+ # @api private
9
+ module Util
10
+ MAX_SAFE_INTEGER = 9_007_199_254_740_991
11
+ ID_RE = /\A[A-Za-z0-9_-]{1,64}\z/
12
+ B64URL_RE = /\A[A-Za-z0-9_-]*\z/
13
+ JS_SPACE = '\s   - 

   '
14
+ TRIM_RE = Regexp.new("\\A[#{JS_SPACE}]+|[#{JS_SPACE}]+\\z")
15
+ ED25519_SPKI_PREFIX = ["302a300506032b6570032100"].pack("H*").freeze
16
+ UTF_8 = Encoding::UTF_8
17
+ JSON_OPTIONS =
18
+ if Gem::Version.new(JSON::VERSION) >= Gem::Version.new("2.13.0")
19
+ { allow_duplicate_key: true }.freeze
20
+ else
21
+ {}.freeze
22
+ end
23
+
24
+ module_function
25
+
26
+ def utf8(value)
27
+ str = value.is_a?(String) ? value : value.to_s
28
+ encoding = str.encoding
29
+ return str if encoding == UTF_8 && str.valid_encoding?
30
+
31
+ if str.valid_encoding? && ![UTF_8, Encoding::BINARY, Encoding::US_ASCII].include?(encoding)
32
+ begin
33
+ return str.encode(UTF_8)
34
+ rescue EncodingError
35
+ nil
36
+ end
37
+ end
38
+ forced = str.dup.force_encoding(UTF_8)
39
+ forced.valid_encoding? ? forced : str.dup.force_encoding(Encoding::ISO_8859_1).encode(UTF_8)
40
+ end
41
+
42
+ def trim(value)
43
+ utf8(value).gsub(TRIM_RE, "")
44
+ end
45
+
46
+ def js_length(str)
47
+ str = utf8(str)
48
+ str.ascii_only? ? str.bytesize : str.encode(Encoding::UTF_16LE).bytesize / 2
49
+ end
50
+
51
+ def text(bytes)
52
+ str = bytes.to_s.dup.force_encoding(UTF_8)
53
+ str = str.scrub("�") unless str.valid_encoding?
54
+ str.delete_prefix("")
55
+ end
56
+
57
+ def str_match?(regexp, value)
58
+ value.is_a?(String) && regexp.match?(value)
59
+ rescue ArgumentError, EncodingError
60
+ false
61
+ end
62
+
63
+ def id?(value)
64
+ str_match?(ID_RE, value)
65
+ end
66
+
67
+ def number?(value)
68
+ value.is_a?(Integer) || value.is_a?(Float)
69
+ end
70
+
71
+ def finite_number?(value)
72
+ number?(value) && value.to_f.finite?
73
+ end
74
+
75
+ def safe_int(value)
76
+ case value
77
+ when Integer
78
+ value.abs <= MAX_SAFE_INTEGER ? value : nil
79
+ when Float
80
+ value.finite? && value == value.floor && value.abs <= MAX_SAFE_INTEGER ? value.to_i : nil
81
+ end
82
+ end
83
+
84
+ def js_round(value)
85
+ floor = value.floor
86
+ value - floor >= 0.5 ? floor + 1 : floor
87
+ end
88
+
89
+ def parse_json(text)
90
+ JSON.parse(text, **JSON_OPTIONS)
91
+ end
92
+
93
+ def b64url_encode(bytes)
94
+ [bytes].pack("m0").tr("+/", "-_").delete("=")
95
+ end
96
+
97
+ def b64url_decode(str)
98
+ raise ArgumentError, "invalid base64url" unless str_match?(B64URL_RE, str) && str.length % 4 != 1
99
+
100
+ standard = str.tr("-_", "+/")
101
+ standard << ("=" * ((4 - (standard.length % 4)) % 4))
102
+ standard.unpack1("m")
103
+ end
104
+
105
+ def decode_json_b64(str)
106
+ parse_json(text(b64url_decode(str)))
107
+ end
108
+
109
+ def hex(bytes)
110
+ bytes.unpack1("H*")
111
+ end
112
+
113
+ def sha256(bytes)
114
+ OpenSSL::Digest::SHA256.digest(bytes)
115
+ end
116
+
117
+ def hmac(key, data)
118
+ OpenSSL::HMAC.digest("SHA256", key, utf8(data).b)
119
+ end
120
+
121
+ def hmac_hex(key, data, chars)
122
+ hex(hmac(key, data))[0, chars]
123
+ end
124
+
125
+ def secure_equal?(left, right)
126
+ left.bytesize == right.bytesize && OpenSSL.fixed_length_secure_compare(left, right)
127
+ end
128
+
129
+ def random_hex(bytes)
130
+ SecureRandom.hex(bytes)
131
+ end
132
+
133
+ def bucket_for(salt, visitor_id)
134
+ sha256(utf8(salt).b + ":".b + utf8(visitor_id).b).unpack1("N") % 10_000
135
+ end
136
+
137
+ def pick_variant(variants, bucket)
138
+ accumulated = 0
139
+ variants.each do |variant|
140
+ accumulated += variant.weight
141
+ return variant if bucket < accumulated
142
+ end
143
+ variants.last
144
+ end
145
+
146
+ def ed25519_verify(public_key, signature, data)
147
+ return false unless public_key.is_a?(String) && signature.is_a?(String) && data.is_a?(String)
148
+
149
+ raw = b64url_decode(public_key)
150
+ sig = b64url_decode(signature)
151
+ return false unless raw.bytesize == 32 && sig.bytesize == 64
152
+
153
+ OpenSSL::PKey.read(ED25519_SPKI_PREFIX + raw).verify(nil, sig, utf8(data).b) == true
154
+ rescue StandardError
155
+ false
156
+ end
157
+
158
+ def iso_time(millis)
159
+ Time.at(millis.to_r / 1000).utc.strftime("%Y-%m-%dT%H:%M:%S.%LZ")
160
+ rescue StandardError
161
+ millis.to_s
162
+ end
163
+
164
+ def monotonic
165
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
166
+ end
167
+
168
+ def wall_millis
169
+ Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
170
+ end
171
+ end
172
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leverprice
4
+ VERSION = "0.3.0"
5
+ end
@@ -0,0 +1,197 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Leverprice
4
+ # @api private
5
+ module Wire
6
+ PROTOCOL_VERSION = 2
7
+ CONFIG_VERSION_HEADER = "Leverprice-Config-Version"
8
+ MAX_EVENTS_PER_REQUEST = 500
9
+ MAX_MINOR_UNITS = 10_000_000_000
10
+ PROVIDERS = %w[stripe polar lemonsqueezy dodo other].freeze
11
+ FINGERPRINT_RE = /\A[0-9a-f]{16}\z/
12
+ SIGNATURE_RE = /\A[0-9a-f]{16}\z/
13
+ CURRENCY_RE = /\A[A-Za-z]{3}\z/
14
+ WIRE_CURRENCY_RE = /\A[a-z]{3}\z/
15
+ URL_BODY_RE = Regexp.new("\\A[^#{Util::JS_SPACE}]+\\z")
16
+
17
+ Variant = Struct.new(:id, :price, :weight, :checkout_url, keyword_init: true)
18
+ Experiment = Struct.new(:id, :salt, :variants, keyword_init: true)
19
+ Product = Struct.new(:id, :currency, :price, :min_price, :max_price, :checkout_url, :experiment,
20
+ keyword_init: true)
21
+ Config = Struct.new(:project_id, :version, :issued_at, :expires_at, :assignment_key, :key_fingerprints,
22
+ :products, keyword_init: true)
23
+
24
+ module_function
25
+
26
+ def parse_config(payload)
27
+ raw = decode(payload, "Leverprice config: payload is not base64url JSON")
28
+ raise Error, "Leverprice config: payload is not an object" unless raw.is_a?(Hash)
29
+
30
+ schema = raw["schema"]
31
+ unless schema == PROTOCOL_VERSION
32
+ raise Error, "Leverprice config: unsupported schema #{schema.inspect} " \
33
+ "(this SDK speaks schema #{PROTOCOL_VERSION})"
34
+ end
35
+
36
+ fingerprints = raw["keyFingerprints"]
37
+ unless fingerprints.is_a?(Array) && fingerprints.all? { |f| Util.str_match?(FINGERPRINT_RE, f) }
38
+ raise Error, "Leverprice config: bad keyFingerprints"
39
+ end
40
+
41
+ project_id = raw["projectId"]
42
+ raise Error, "Leverprice config: no projectId" unless project_id.is_a?(String) && !project_id.empty?
43
+
44
+ version = Util.safe_int(raw["version"])
45
+ raise Error, "Leverprice config: bad version" unless version && version >= 0
46
+
47
+ expires_at = raw["expiresAt"]
48
+ raise Error, "Leverprice config: bad expiresAt" unless Util.finite_number?(expires_at)
49
+
50
+ assignment_key = raw["assignmentKey"]
51
+ unless assignment_key.is_a?(String) && key_length(assignment_key) >= 32
52
+ raise Error, "Leverprice config: assignmentKey must be at least 32 bytes of base64url"
53
+ end
54
+
55
+ products = raw["products"]
56
+ raise Error, "Leverprice config: no products" unless products.is_a?(Hash)
57
+
58
+ parsed = {}
59
+ dropped = []
60
+ products.each do |key, value|
61
+ product = parse_product(value)
62
+ product ? parsed[key] = product : dropped << key
63
+ end
64
+
65
+ config = Config.new(
66
+ project_id: project_id,
67
+ version: version,
68
+ issued_at: Util.number?(raw["issuedAt"]) ? raw["issuedAt"] : 0,
69
+ expires_at: expires_at,
70
+ assignment_key: assignment_key,
71
+ key_fingerprints: fingerprints,
72
+ products: parsed
73
+ )
74
+ [config, dropped]
75
+ end
76
+
77
+ def parse_product(raw)
78
+ return nil unless raw.is_a?(Hash)
79
+
80
+ currency = raw["currency"]
81
+ return nil unless Util.str_match?(CURRENCY_RE, currency)
82
+
83
+ price = Util.safe_int(raw["price"])
84
+ min_price = Util.safe_int(raw["minPrice"])
85
+ max_price = Util.safe_int(raw["maxPrice"])
86
+ return nil if price.nil? || min_price.nil? || max_price.nil?
87
+
88
+ experiment = nil
89
+ unless raw["experiment"].nil?
90
+ experiment = parse_experiment(raw["experiment"])
91
+ return nil unless experiment
92
+ end
93
+
94
+ Product.new(
95
+ id: raw["id"].is_a?(String) ? raw["id"] : "",
96
+ currency: currency.downcase,
97
+ price: price,
98
+ min_price: min_price,
99
+ max_price: max_price,
100
+ checkout_url: https_url(raw["checkoutUrl"]),
101
+ experiment: experiment
102
+ )
103
+ end
104
+
105
+ def parse_experiment(raw)
106
+ return nil unless raw.is_a?(Hash) && Util.id?(raw["id"]) && raw["salt"].is_a?(String) &&
107
+ raw["variants"].is_a?(Array)
108
+
109
+ variants = raw["variants"].map do |variant|
110
+ return nil unless variant.is_a?(Hash) && Util.id?(variant["id"])
111
+
112
+ price = Util.safe_int(variant["price"])
113
+ weight = Util.safe_int(variant["weight"])
114
+ return nil if price.nil? || weight.nil? || weight.negative?
115
+
116
+ Variant.new(id: variant["id"], price: price, weight: weight, checkout_url: https_url(variant["checkoutUrl"]))
117
+ end
118
+ Experiment.new(id: raw["id"], salt: raw["salt"], variants: variants)
119
+ end
120
+
121
+ def https_url(value)
122
+ return nil unless value.is_a?(String)
123
+
124
+ url = Util.utf8(value)
125
+ return nil unless url.length > 8 && url[0, 8].downcase(:ascii) == "https://"
126
+
127
+ URL_BODY_RE.match?(url[8..]) ? url : nil
128
+ end
129
+
130
+ def key_length(str)
131
+ Util.b64url_decode(str).bytesize
132
+ rescue ArgumentError
133
+ 0
134
+ end
135
+
136
+ def decode(payload, message)
137
+ Util.decode_json_b64(payload)
138
+ rescue StandardError
139
+ raise Error, message
140
+ end
141
+
142
+ def event_problem(event)
143
+ timestamp = Util.safe_int(event["timestamp"])
144
+ return "timestamp must be a positive integer (ms)" unless timestamp&.positive?
145
+
146
+ if event["type"] == "exposure"
147
+ valid = Util.id?(event["experimentId"]) && Util.id?(event["variantId"]) && Util.id?(event["visitorId"])
148
+ return valid ? nil : "invalid experiment/variant/visitor id"
149
+ end
150
+ return %(unknown provider "#{event["provider"]}") unless PROVIDERS.include?(event["provider"])
151
+ return "orderId must be a string of 1–255 characters" unless text?(event["orderId"])
152
+ return "currency must be a 3-letter ISO 4217 code" unless Util.str_match?(WIRE_CURRENCY_RE, event["currency"])
153
+
154
+ event["type"] == "purchase" ? purchase_problem(event) : refund_problem(event)
155
+ end
156
+
157
+ def purchase_problem(event)
158
+ return "amount must be a non-negative integer in minor units" unless minor_units?(event["amount"])
159
+
160
+ attribution = event["attribution"]
161
+ return nil if attribution.nil? || attribution == false
162
+
163
+ attribution_valid?(attribution) ? nil : "invalid attribution"
164
+ end
165
+
166
+ def attribution_valid?(attribution)
167
+ return false unless attribution.is_a?(Hash)
168
+ return false unless Util.id?(attribution["experimentId"]) && Util.id?(attribution["variantId"]) &&
169
+ Util.id?(attribution["visitorId"])
170
+
171
+ signature = attribution["signature"]
172
+ (signature.nil? && attribution.key?("signature")) || Util.str_match?(SIGNATURE_RE, signature)
173
+ end
174
+
175
+ def refund_problem(event)
176
+ return "refundId must be a string of 1–255 characters" if event.key?("refundId") && !text?(event["refundId"])
177
+ return "amount must be a non-negative integer" if event.key?("amount") && !minor_units?(event["amount"])
178
+ if event.key?("refundedTotal") && !minor_units?(event["refundedTotal"])
179
+ return "refundedTotal must be a non-negative integer"
180
+ end
181
+ unless (event.key?("refundId") && event.key?("amount")) || event.key?("refundedTotal")
182
+ return "refund needs refundId + amount, or refundedTotal"
183
+ end
184
+
185
+ nil
186
+ end
187
+
188
+ def minor_units?(value)
189
+ amount = Util.safe_int(value)
190
+ !amount.nil? && amount >= 0 && amount <= MAX_MINOR_UNITS
191
+ end
192
+
193
+ def text?(value)
194
+ value.is_a?(String) && Util.js_length(value).between?(1, 255)
195
+ end
196
+ end
197
+ end
data/lib/leverprice.rb ADDED
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "leverprice/version"
4
+
5
+ # Server-side SDK for Leverprice price experiments.
6
+ module Leverprice
7
+ # Raised for invalid options; also the class of every error passed to `on_error`.
8
+ class Error < StandardError; end
9
+
10
+ # Leverprice's offline root public keys (raw Ed25519, base64url) by id.
11
+ ROOT_PUBLIC_KEYS = { "r1" => "5FmNzXvPMPZEuDnFT_fFd_VVNsUrWwWTKLerMWbSdcg" }.freeze
12
+
13
+ # Keysets below this version are refused even by a fresh process.
14
+ MIN_KEYSET_VERSION = 1
15
+
16
+ class << self
17
+ # @param user_agent [String, nil]
18
+ # @return [Boolean] true for crawlers, link previewers, headless browsers, monitors and HTTP tools
19
+ def bot?(user_agent)
20
+ Bots.bot?(user_agent)
21
+ end
22
+
23
+ # Appends a quote's `Set-Cookie` values to a Rails, Sinatra or Rack response, or to a Rack headers Hash.
24
+ # Works with Rack 2 (newline-joined) and Rack 3 (array) headers.
25
+ # @param target [#headers, Hash]
26
+ # @param quote [Quote, Array<String>]
27
+ # @return [Object] target
28
+ def write_cookies(target, quote)
29
+ ResponseCookies.write(target, quote)
30
+ end
31
+
32
+ # @return [Boolean] true when the environment variable LEVERPRICE_DISABLED is "1" or "true"
33
+ def env_disabled?
34
+ value = ENV.fetch("LEVERPRICE_DISABLED", nil)
35
+ !value.nil? && %w[1 true].include?(Util.trim(value).downcase)
36
+ rescue StandardError
37
+ false
38
+ end
39
+ end
40
+ end
41
+
42
+ require_relative "leverprice/util"
43
+ require_relative "leverprice/bots"
44
+ require_relative "leverprice/wire"
45
+ require_relative "leverprice/trust"
46
+ require_relative "leverprice/cookie"
47
+ require_relative "leverprice/request"
48
+ require_relative "leverprice/transport"
49
+ require_relative "leverprice/quote"
50
+ require_relative "leverprice/process"
51
+ require_relative "leverprice/client"
52
+ require_relative "leverprice/rack"
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: leverprice
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
5
+ platform: ruby
6
+ authors:
7
+ - Leverprice
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: 'Signed, fail-safe price experiments for SaaS checkouts: verified configs,
13
+ sticky assignments, exposure logging and purchase attribution. Zero runtime dependencies.'
14
+ executables: []
15
+ extensions: []
16
+ extra_rdoc_files: []
17
+ files:
18
+ - CHANGELOG.md
19
+ - LICENSE
20
+ - README.md
21
+ - lib/leverprice.rb
22
+ - lib/leverprice/bots.rb
23
+ - lib/leverprice/client.rb
24
+ - lib/leverprice/cookie.rb
25
+ - lib/leverprice/process.rb
26
+ - lib/leverprice/quote.rb
27
+ - lib/leverprice/rack.rb
28
+ - lib/leverprice/request.rb
29
+ - lib/leverprice/transport.rb
30
+ - lib/leverprice/trust.rb
31
+ - lib/leverprice/util.rb
32
+ - lib/leverprice/version.rb
33
+ - lib/leverprice/wire.rb
34
+ homepage: https://leverprice.com
35
+ licenses:
36
+ - MIT
37
+ metadata:
38
+ homepage_uri: https://leverprice.com
39
+ source_code_uri: https://github.com/leverprice/leverprice-ruby
40
+ documentation_uri: https://leverprice.com/docs
41
+ changelog_uri: https://github.com/leverprice/leverprice-ruby/blob/main/CHANGELOG.md
42
+ bug_tracker_uri: https://github.com/leverprice/leverprice-ruby/issues
43
+ rubygems_mfa_required: 'true'
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '3.1'
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubygems_version: 4.0.20
59
+ specification_version: 4
60
+ summary: Server-side SDK for Leverprice price experiments
61
+ test_files: []