app_manager 2.7.1 → 2.8.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.
@@ -2,6 +2,8 @@ require_dependency "app_manager/application_controller"
2
2
  require 'kaminari'
3
3
  module AppManager
4
4
  class PlansController < ApplicationController
5
+ prepend_before_action :authorize_request, :only => [:users, :burst_cache, :fail_safe_backup, :rebuild_failsafe]
6
+ prepend_before_action :authorize_session_or_api_token, :only => [:index, :plans, :active_without_plan]
5
7
  cache_response_for :plans
6
8
  cache_response_for :index
7
9
  cache_response_for :users
@@ -48,7 +50,7 @@ module AppManager
48
50
  global_plan_obj = AppManager::Client.new
49
51
  plan = global_plan_obj.get_bundle_plan(active_plan_id_or_name)
50
52
  end
51
- if active_charge && active_charge.any? && active_charge['active_charge'].nil? && active_charge['cancelled_charge'].nil? && !trial_activated_at && !plan
53
+ if choose_later_offered?(plan, active_charge, trial_activated_at)
52
54
  choose_later = true
53
55
  end
54
56
 
@@ -62,20 +64,7 @@ module AppManager
62
64
 
63
65
 
64
66
  plans = plan_obj.get_plans(params[:shop_domain]) if plans && plans.blank?
65
- default_plan_data = plans.select { |x| x['choose_later_plan'] == true }
66
- if default_plan_data.any?
67
- if default_plan_data.select { |x| x['store_base_plan'] == true }.size > 0
68
- shopify_plans = plans.select { |x| x['interval'] == 'EVERY_30_DAYS' }
69
- shopify_plans.each do |shp|
70
- if shp && shp["shopify_plans"].include?(shopify_plan)
71
- default_plan_id = shp["id"]
72
- break
73
- end
74
- end
75
- else
76
- default_plan_id = default_plan_data.map { |e| e['id'] }.first if default_plan_data.any? rescue nil
77
- end
78
- end
67
+ default_plan_id = choose_later_plan_id(plans, shopify_plan)
79
68
 
80
69
  promotional_discount = []
81
70
  if params[:discount_code].present? && !params[:discount_code].nil? && @shop
@@ -202,12 +191,32 @@ module AppManager
202
191
  def active_without_plan
203
192
  if params[:shop_domain].present? && params[:plan_id].present? && model
204
193
  @shop = shop_data
194
+ return render(json: {'status' => false, 'error' => 'Shop not found or missing shop'}, status: 422) if @shop.nil?
205
195
  @trial_activated_field = AppManager.configuration.field_names['trial_activated_at']
206
196
  plan_obj = AppManager::Client.new
207
197
  plan_data = plan_obj.get_plan(params[:plan_id], params[:shop_domain]) rescue nil
208
198
  # Only stamp the trial start the first time; re-assigning a no-charge plan must
209
199
  # not restart the trial clock (that would hand back trial days already consumed).
210
200
  existing_trial_activated_at = @shop[@trial_activated_field] rescue nil
201
+
202
+ # Same rule as the choose-later link in plans.
203
+ active_plan_id_or_name = @shop[@plan_field] rescue nil
204
+ shopify_plan = @shop[@field_names['shopify_plan']] rescue nil
205
+ plans = plan_obj.get_plans(params[:shop_domain], active_plan_id_or_name)
206
+ plans = [] unless plans.is_a?(Array)
207
+ current_plan = active_plan_id_or_name.nil? ? nil : plans.find { |x| x["id"] == active_plan_id_or_name }
208
+ active_charge = plan_obj.get_charge(params[:shop_domain])
209
+ if current_plan.nil? && active_charge.present? && active_charge.any? && !active_charge['bundle_charge'].nil?
210
+ current_plan = AppManager::Client.new.get_bundle_plan(active_plan_id_or_name)
211
+ end
212
+ default_plan_id = choose_later_plan_id(plans, shopify_plan)
213
+ charge_known = active_charge.is_a?(Hash) && active_charge.key?('active_charge')
214
+ if AppManager.configuration.plan_features.nil? || !@field_names.has_key?('shopify_plan') ||
215
+ default_plan_id.nil? || default_plan_id.to_s != params[:plan_id].to_s ||
216
+ !charge_known || !choose_later_offered?(current_plan, active_charge, existing_trial_activated_at)
217
+ return render json: {'status' => false, 'error' => 'Choose later is not available for this shop'}, status: 422
218
+ end
219
+
211
220
  update_info = {@plan_field => params[:plan_id]}
212
221
  update_info[@trial_activated_field] = DateTime.now if existing_trial_activated_at.blank?
213
222
  if !config_trial_days.nil? && !plan_data.nil?
@@ -300,6 +309,29 @@ module AppManager
300
309
  params.permit!
301
310
  end
302
311
 
312
+ def choose_later_offered?(plan, active_charge, trial_activated_at)
313
+ active_charge && active_charge.any? && active_charge['active_charge'].nil? && active_charge['cancelled_charge'].nil? && !trial_activated_at && !plan
314
+ end
315
+
316
+ def choose_later_plan_id(plans, shopify_plan)
317
+ default_plan_id = nil
318
+ default_plan_data = plans.select { |x| x['choose_later_plan'] == true }
319
+ if default_plan_data.any?
320
+ if default_plan_data.select { |x| x['store_base_plan'] == true }.size > 0
321
+ shopify_plans = plans.select { |x| x['interval'] == 'EVERY_30_DAYS' }
322
+ shopify_plans.each do |shp|
323
+ if shp && shp["shopify_plans"].include?(shopify_plan)
324
+ default_plan_id = shp["id"]
325
+ break
326
+ end
327
+ end
328
+ else
329
+ default_plan_id = default_plan_data.map { |e| e['id'] }.first if default_plan_data.any? rescue nil
330
+ end
331
+ end
332
+ default_plan_id
333
+ end
334
+
303
335
  def model
304
336
  @models = ActiveRecord::Base.connection.tables
305
337
  @config_table = AppManager.configuration.shopify_table_name
@@ -2,9 +2,11 @@ module AppManager
2
2
  module Authenticate
3
3
  extend ActiveSupport::Concern
4
4
 
5
+ # Each controller declares which actions need which check, with
6
+ # prepend_before_action so it runs before the response cache.
5
7
  included do
6
8
  include AppManager::Protection
7
- before_action :authorize_request, :only => [:users]
9
+ include AppManager::SessionToken
8
10
  end
9
11
  end
10
- end
12
+ end
@@ -0,0 +1,121 @@
1
+ # Commit and PR message standards
2
+
3
+ These rules apply to every repository whose merges to production are tracked in
4
+ Atlas. They are written for the AI tools that write most of our commit and PR
5
+ messages (Cursor, Claude Code, Copilot) and for the people reviewing them.
6
+
7
+ **Let your AI tool write the commit message and the PR title and description.** It
8
+ has the diff in front of it and, with this file in the repo, it knows the format.
9
+ Review what it writes rather than typing it by hand.
10
+
11
+ ## Why it matters
12
+
13
+ Every merge into production becomes a deployment record in Atlas. The PR title and
14
+ description are all that record has to go on. They feed:
15
+
16
+ - the classifier behind our KPIs (what kind of change it was, and whether it
17
+ shipped an AI feature),
18
+ - the changelog and the daily deployment digest in `#production-deployments`,
19
+ - the Data AI Agent, when someone asks what shipped.
20
+
21
+ A merge described as `WIP` or `staging-v2` shows up as nothing in all of them.
22
+ A better model cannot fix an empty input.
23
+
24
+ ## 1. The PR title is the one that counts
25
+
26
+ Most repos squash-merge, so **the PR title becomes the commit on `main`**. The
27
+ individual commit messages disappear, so put your care into the PR title and
28
+ description.
29
+
30
+ **Format:** `<JIRA-KEY>: <what changed, in plain words>`
31
+
32
+ - Say what changed **for the user or the system**, not which branch it came from.
33
+ - Use the imperative mood and keep it under about 72 characters.
34
+ - Put the Jira key first when there is one.
35
+ - Never use a branch name (`staging-v2`, `develop`, `testing to main`), `WIP`, `fix`,
36
+ `update` or `changes` as a title.
37
+
38
+ **Release / promotion PRs** (`develop` → `main`, `staging` → `master`,
39
+ `staging-v2` → `master-v2`):
40
+ `Release: <the two or three main things it carries>`
41
+
42
+ | Seen in production | How it should read |
43
+ |---|---|
44
+ | `WIP` | `PRODOPS-612: Add per-option inventory limits` |
45
+ | `staging-v2` | `Release: billing link fix, upgrade button visibility (OP-3612)` |
46
+ | `testing to main` | `Release: shared options UI, sales-channel filter` |
47
+ | `Pull last app_kit version` | `Bump app_kit to 4.2.0 (brings the new billing banner)` |
48
+
49
+ ## 2. End the PR description with this block
50
+
51
+ Atlas reads this block directly, so a merge described this way is classified
52
+ correctly without an AI having to guess.
53
+
54
+ ```
55
+ Change type: New Feature
56
+ Feature scope: Minor
57
+ Short description: Merchants can cap how many of each option value can be sold.
58
+ Notes: Behind the inventory_limits flag until the 1 Oct rollout.
59
+ ```
60
+
61
+ **Change type**, exactly one of:
62
+
63
+ | Type | Use it for |
64
+ |---|---|
65
+ | `New Feature` | User-facing functionality that didn't exist before: new screens, flows, capabilities. |
66
+ | `Improvement` | Making something that already exists better: performance, UX polish, copy, more options. |
67
+ | `Bug Fix` | A targeted fix for a defect shipped in an earlier release. |
68
+ | `Refactor` | Restructuring code with **no change in behaviour**. |
69
+ | `Security` | Anything motivated by security: patched vulnerability, auth check, rotated secret. |
70
+ | `Maintenance` | Dependency bumps, infra, CI/build changes, version bumps. |
71
+
72
+ **Feature scope:** `Major` or `Minor`.
73
+ - **Major** means a significant surface-area change: a new tab, a new API endpoint, a
74
+ migration, a behaviour change users will notice across many flows.
75
+ - **Minor** means a small, contained change: one bug fix, a copy tweak, one new option.
76
+
77
+ When in doubt, choose **Minor**.
78
+
79
+ **Short description:** one sentence a product manager would understand.
80
+ **Notes:** optional.
81
+
82
+ **Several changes in one PR?** Repeat the block once per change, starting each
83
+ block with a `Task:` line:
84
+
85
+ ```
86
+ Task: Inventory limits
87
+ Change type: New Feature
88
+ Feature scope: Major
89
+ Short description: Merchants can cap how many of each option value can be sold.
90
+
91
+ Task: Checkout crash
92
+ Change type: Bug Fix
93
+ Feature scope: Minor
94
+ Short description: Fixed a crash when an option set had no values.
95
+ ```
96
+
97
+ ## 3. Never merge a template unfilled
98
+
99
+ A PR template left with its headings, HTML comments, empty checkboxes and
100
+ `[Short description here]` placeholders looks like a long description to a machine
101
+ and says nothing to a person. Either fill it in or delete it.
102
+
103
+ ## 4. Commits
104
+
105
+ With squash-merge, commit messages matter less, but they are still what a release
106
+ falls back on when nothing else describes it. So:
107
+
108
+ - Write one line that says what changed: `Handle error on charges`, not `fix`.
109
+ - Put the Jira key in the branch name or the commit (`OP-3612-upgrade-button`).
110
+ - Don't push work straight to `staging` / `develop` without a PR. A release built
111
+ from direct pushes leaves only commit messages to describe it.
112
+
113
+ ## Where these rules are wired in
114
+
115
+ This repository contains the same rules for each AI tool:
116
+
117
+ - **Claude Code** reads `CLAUDE.md`, which imports this file.
118
+ - **Cursor** reads `.cursor/rules/commit-and-pr.mdc` (always applied).
119
+ - **Copilot** reads `.github/copilot-instructions.md`.
120
+
121
+ If you change the rules, change them here and keep the other three files in step.
@@ -7,6 +7,7 @@ module AppManager
7
7
  attr_accessor :plan_features
8
8
  attr_accessor :app_url
9
9
  attr_accessor :shopify_api_key
10
+ attr_accessor :shopify_api_secret
10
11
  attr_accessor :shopify_api_version
11
12
  attr_accessor :shopify_table_name
12
13
  attr_accessor :shopify_domain_field
@@ -16,6 +17,9 @@ module AppManager
16
17
  attr_accessor :shopify_app_slug
17
18
  attr_accessor :most_popular_plan_ids
18
19
  attr_accessor :plan_page_route
20
+ # Object/class/class-name responding to #token(shop_domain) and #refresh(shop_domain),
21
+ # e.g. AppManager::ModelTokenResolver. nil keeps the old behaviour: read the token column.
22
+ attr_accessor :shopify_token_resolver
19
23
 
20
24
  def initialize
21
25
  @refresh_by_request_params = true
@@ -23,6 +27,7 @@ module AppManager
23
27
  @enable_caching = true
24
28
  @app_url = nil
25
29
  @shopify_api_key = nil
30
+ @shopify_api_secret = ENV['SHOPIFY_API_SECRET']
26
31
  @shopify_api_version = nil
27
32
  @shopify_table_name = 'shops'
28
33
  @shopify_domain_field = 'shopify_domain'
@@ -64,6 +69,10 @@ module AppManager
64
69
  @shopify_api_key
65
70
  end
66
71
 
72
+ def shopify_api_secret
73
+ @shopify_api_secret
74
+ end
75
+
67
76
  def shopify_api_version
68
77
  @shopify_api_version
69
78
  end
@@ -5,7 +5,9 @@ module AppManager
5
5
  # charge callback can persist it (value/type/duration/source) on the charge row.
6
6
  attr_reader :discount_snapshot
7
7
 
8
- def initialize(shopify_domain,shopify_token)
8
+ # shopify_token is only a fallback for when the resolver has none; billing
9
+ # calls get their token from AppManager::ShopifyApi (the app's resolver).
10
+ def initialize(shopify_domain, shopify_token = nil)
9
11
  @api_key = AppManager.configuration.shopify_api_key || nil
10
12
  @api_version = AppManager.configuration.shopify_api_version || nil
11
13
  @shopify_domain = shopify_domain
@@ -17,27 +19,29 @@ module AppManager
17
19
  end
18
20
 
19
21
  def api_call(query,is_json=false)
20
- require 'uri'
21
- require 'net/http'
22
- if !@api_key.nil? && !@api_version.nil? && !@shopify_domain.nil? && !@shopify_token.nil?
23
- url = URI("https://#{@api_key}:#{@shopify_token}@#{@shopify_domain}/admin/api/#{@api_version}/graphql.json")
24
- http = Net::HTTP.new(url.host, url.port)
25
- http.use_ssl = true
26
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
27
- request = Net::HTTP::Post.new(url)
28
- request["X-Shopify-Access-Token"] = @shopify_token
29
- request.body = query
30
- request["Accept"] = 'application/json'
31
- if is_json.present?
32
- request["Content-Type"] = 'application/json'
33
- else
34
- request["Content-Type"] = 'application/graphql'
22
+ if !@api_key.nil? && !@api_version.nil? && !@shopify_domain.nil?
23
+ url = URI("https://#{@shopify_domain}/admin/api/#{@api_version}/graphql.json")
24
+ content_type = is_json.present? ? 'application/json' : 'application/graphql'
25
+ begin
26
+ response = AppManager::ShopifyApi.with_token(@shopify_domain, @shopify_token) do |token|
27
+ http = Net::HTTP.new(url.host, url.port)
28
+ http.use_ssl = true
29
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
30
+ request = Net::HTTP::Post.new(url)
31
+ request["X-Shopify-Access-Token"] = token
32
+ request.body = query
33
+ request["Accept"] = 'application/json'
34
+ request["Content-Type"] = content_type
35
+ http.request(request)
36
+ end
37
+ rescue AppManager::MissingTokenError
38
+ Rollbar.error("=== no Shopify access token available for shopify_domain=#{@shopify_domain} ===")
39
+ return []
35
40
  end
36
- response = http.request(request)
37
41
  response = ActiveSupport::JSON.decode(response.read_body) rescue nil
38
42
  return response
39
43
  else
40
- Rollbar.error("=== params missing from any of these api_key=#{@api_key}, api_version=#{@api_version}, shopify_domain=#{@shopify_domain}, shopify_token ===#{@shopify_token}")
44
+ Rollbar.error("=== params missing from any of these api_key=#{@api_key}, api_version=#{@api_version}, shopify_domain=#{@shopify_domain} ===")
41
45
  return []
42
46
  end
43
47
  end
@@ -39,6 +39,7 @@ module AppManager
39
39
  end
40
40
 
41
41
 
42
+ # TODO: checks plan_id only, not trial or charge; features stay after an unpaid trial. Apps should also check has_plan.
42
43
  def plan_features
43
44
  plan_id = self[AppManager.configuration.plan_id_or_name_field]
44
45
  if !plan_id
@@ -157,7 +158,7 @@ module AppManager
157
158
  @field_names = AppManager.configuration.field_names
158
159
  shopify_active_charge_id = self.active_shopify_charge_id
159
160
  if shopify_active_charge_id.present?
160
- gq_obj = AppManager::GraphqlHelper.new(self.shopify_domain, self.shopify_token)
161
+ gq_obj = AppManager::GraphqlHelper.new(self.shopify_domain)
161
162
  rec_cancel_data = gq_obj.recurring_charge_cancel_api_call(shopify_active_charge_id, self)
162
163
  if !rec_cancel_data["errors"].present? && (rec_cancel_data["data"].present? && rec_cancel_data["data"]["appSubscriptionCancel"].present? && !rec_cancel_data["data"]["appSubscriptionCancel"]["userErrors"].any? && (rec_cancel_data["data"]["appSubscriptionCancel"]["appSubscription"]["status"] == 'CANCELLED'))
163
164
  cancelled_charge_id = rec_cancel_data["data"]["appSubscriptionCancel"]["appSubscription"]["id"].split('/')[-1]
@@ -176,7 +177,7 @@ module AppManager
176
177
 
177
178
  def get_current_shopify_charge
178
179
  begin
179
- gq_obj = AppManager::GraphqlHelper.new(self.shopify_domain, self.shopify_token)
180
+ gq_obj = AppManager::GraphqlHelper.new(self.shopify_domain)
180
181
  data = gq_obj.recurring_charge_current_api_call(self)
181
182
  if !data["errors"].present? && (data["data"].present? && data["data"]["currentAppInstallation"].present? && data["data"]["currentAppInstallation"]["activeSubscriptions"].present?)
182
183
  return data["data"]["currentAppInstallation"]["activeSubscriptions"].first
@@ -273,7 +274,6 @@ module AppManager
273
274
  # begin
274
275
  @shop = shop
275
276
  @field_names = AppManager.configuration.field_names
276
- shopify_token = @field_names['shopify_token']
277
277
  shopify_domain = @field_names['name']
278
278
  grandfathered_field = @field_names['grandfathered']
279
279
  shop_domain = @shop[AppManager.configuration.shopify_domain_field]
@@ -281,9 +281,9 @@ module AppManager
281
281
  if charge_obj.present? && !charge_obj.nil?
282
282
  shopify_charge_obj = charge_obj
283
283
  else
284
- headers = {"X-Shopify-Access-Token" => @shop[shopify_token]}
285
- charges = HTTParty.get('https://' + shop_domain + '/admin/api/' + AppManager.configuration.shopify_api_version + '/recurring_application_charges/' + current_charge_id + '.json', :headers => headers)
286
- shopify_charge_obj = charges.parsed_response && charges.parsed_response.is_a?(Hash) && charges.parsed_response.has_key?('recurring_application_charge') ? charges.parsed_response['recurring_application_charge'] : {}
284
+ charges = AppManager::ShopifyApi.rest(shop_domain, :get, "recurring_application_charges/#{current_charge_id}.json")
285
+ charges_body = (JSON.parse(charges.body.to_s) rescue nil)
286
+ shopify_charge_obj = charges_body.is_a?(Hash) && charges_body.has_key?('recurring_application_charge') ? charges_body['recurring_application_charge'] : {}
287
287
  end
288
288
 
289
289
  if shopify_charge_obj.present?
@@ -338,7 +338,7 @@ module AppManager
338
338
  def active_shopfiy_charge_full
339
339
  active_charge_id = self.active_shopify_charge_id
340
340
  if active_charge_id.present?
341
- gq_obj = AppManager::GraphqlHelper.new(self.shopify_domain, self.shopify_token)
341
+ gq_obj = AppManager::GraphqlHelper.new(self.shopify_domain)
342
342
  rac_data = gq_obj.current_rc_charge_gql(active_charge_id)
343
343
  return rac_data
344
344
  else
@@ -347,7 +347,7 @@ module AppManager
347
347
  end
348
348
 
349
349
  def usage_charge_call(amount, description = '', shopify_charge_id = nil)
350
- gq_obj = AppManager::GraphqlHelper.new(shopify_domain, shopify_token)
350
+ gq_obj = AppManager::GraphqlHelper.new(shopify_domain)
351
351
 
352
352
  # Validate amount is present and is a valid number
353
353
  return 'Amount must be present and a positive float' if amount.blank? || !amount.is_a?(Numeric) || amount.to_f <= 0
@@ -2,9 +2,10 @@ module AppManager
2
2
  module Protection
3
3
  extend ActiveSupport::Concern
4
4
  def authorize_request
5
- if request.headers['token'].present? && ENV['APP_MANAGER_ACCESS_TOKEN']
6
- if request.headers['token'] === ENV['APP_MANAGER_ACCESS_TOKEN']
7
- else
5
+ expected = ENV['APP_MANAGER_ACCESS_TOKEN'].to_s
6
+ given = request.headers['token'].to_s
7
+ if given.present?
8
+ unless expected.present? && ActiveSupport::SecurityUtils.secure_compare(expected, given)
8
9
  render json: {
9
10
  error: "Invalid Token ",
10
11
  status: 401
@@ -18,4 +19,4 @@ module AppManager
18
19
  end
19
20
  end
20
21
  end
21
- end
22
+ end
@@ -0,0 +1,121 @@
1
+ require 'base64'
2
+ require 'json'
3
+ require 'openssl'
4
+ require 'uri'
5
+
6
+ module AppManager
7
+ # Lets through App Manager (the `token` header) or an embedded admin page
8
+ # (a Shopify session token). A `shop` / `shop_domain` param naming another
9
+ # shop is rejected rather than overwritten, because responses are cached by URL.
10
+ module SessionToken
11
+ extend ActiveSupport::Concern
12
+
13
+ SESSION_TOKEN_LEEWAY_SECONDS = 10
14
+ SESSION_TOKEN_SHOP_PARAMS = %w[shop shop_domain].freeze
15
+
16
+ def authorize_session_or_api_token
17
+ return if valid_app_manager_token?
18
+
19
+ shop = shop_from_session_token(request.authorization.to_s[/\ABearer (.+)\z/, 1].to_s)
20
+ return render(json: { message: 'Unauthenticated' }, status: 401) if shop.nil?
21
+
22
+ SESSION_TOKEN_SHOP_PARAMS.each do |key|
23
+ value = params[key]
24
+ next if value.blank?
25
+ return render(json: { message: 'Shop does not match the session token' }, status: 403) if value.to_s.downcase != shop
26
+ end
27
+ end
28
+
29
+ private
30
+
31
+ def valid_app_manager_token?
32
+ expected = ENV['APP_MANAGER_ACCESS_TOKEN'].to_s
33
+ given = request.headers['token'].to_s
34
+ expected.present? && given.present? && ActiveSupport::SecurityUtils.secure_compare(expected, given)
35
+ end
36
+
37
+ def shop_from_session_token(jwt)
38
+ parts = jwt.split('.')
39
+ return nil unless parts.length == 3
40
+ encoded_header, encoded_payload, encoded_signature = parts
41
+
42
+ header = decode_session_token_json(encoded_header)
43
+ return nil unless header.is_a?(Hash) && header['alg'] == 'HS256'
44
+
45
+ secret = AppManager.configuration.shopify_api_secret.to_s
46
+ if secret.empty?
47
+ report_missing_shopify_api_secret
48
+ return nil
49
+ end
50
+
51
+ payload = decode_session_token_json(encoded_payload)
52
+ return nil unless payload.is_a?(Hash)
53
+
54
+ api_key = AppManager.configuration.shopify_api_key.to_s
55
+ expected = OpenSSL::HMAC.digest('SHA256', secret, "#{encoded_header}.#{encoded_payload}")
56
+ unless ActiveSupport::SecurityUtils.secure_compare(expected, base64url_decode(encoded_signature))
57
+ if api_key.present? && payload['aud'] == api_key
58
+ Rails.logger.warn("App Manager: a session token for this app failed signature verification. Check that AppManager.configuration.shopify_api_secret holds this app's current Shopify API secret.")
59
+ end
60
+ return nil
61
+ end
62
+
63
+ now = Time.now.to_i
64
+ exp = session_token_number(payload['exp'])
65
+ return nil unless exp && exp >= now - SESSION_TOKEN_LEEWAY_SECONDS
66
+ if payload.key?('nbf')
67
+ nbf = session_token_number(payload['nbf'])
68
+ return nil unless nbf && nbf <= now + SESSION_TOKEN_LEEWAY_SECONDS
69
+ end
70
+
71
+ if api_key.present? && payload['aud'] != api_key
72
+ # Only a token signed with this app's secret gets here, so the configured key is wrong.
73
+ Rails.logger.warn("App Manager: a session token signed with this app's secret has a different API key. Check that AppManager.configuration.shopify_api_key holds this app's Shopify API key.")
74
+ return nil
75
+ end
76
+
77
+ shop = session_token_host(payload['dest'])
78
+ return nil if shop.nil? || shop != session_token_host(payload['iss'])
79
+ return nil unless shop =~ /\A[a-z0-9][a-z0-9\-]*\.myshopify\.com\z/i
80
+
81
+ shop.downcase
82
+ end
83
+
84
+ def report_missing_shopify_api_secret
85
+ message = 'App Manager: AppManager.configuration.shopify_api_secret is empty, so session tokens cannot be verified. Set it to your Shopify API secret.'
86
+ error = RuntimeError.new(message)
87
+ # Reported, not just logged, so the app's error tracker alerts: every billing-page request fails until this is set.
88
+ if Rails.respond_to?(:error) && Rails.error.respond_to?(:report)
89
+ Rails.error.report(error, handled: true)
90
+ elsif defined?(Rollbar)
91
+ Rollbar.error(error)
92
+ end
93
+ Rails.logger.error(message)
94
+ end
95
+
96
+ # Same as PHP's is_numeric, so both SDKs accept the same claims.
97
+ def session_token_number(value)
98
+ return value if value.is_a?(Numeric)
99
+ return nil unless value.is_a?(String) && value =~ /\A\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*\z/
100
+ Float(value.strip)
101
+ end
102
+
103
+ def session_token_host(url)
104
+ URI.parse(url.to_s).host
105
+ rescue URI::InvalidURIError
106
+ nil
107
+ end
108
+
109
+ def decode_session_token_json(value)
110
+ JSON.parse(base64url_decode(value))
111
+ rescue JSON::ParserError
112
+ nil
113
+ end
114
+
115
+ def base64url_decode(value)
116
+ Base64.urlsafe_decode64(value + '=' * ((4 - value.length % 4) % 4))
117
+ rescue ArgumentError
118
+ ''
119
+ end
120
+ end
121
+ end