app_manager 2.7.0 → 2.7.2

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: b07aa041091f2f5c6acc9fc85b9ffbf6c73d7d97f0694981fb3ee261fd4d167c
4
- data.tar.gz: 3ef460faa396f6dbb9df6cb66010045975cd76b28a29e97d00b4542bb846a0c2
3
+ metadata.gz: 25bbca315f9442380053af33b5cefc075b98201beedca082258e7b18a88814fd
4
+ data.tar.gz: 5a8a74e68f0004e1ff78853600855e2c5a0128fb91d7581d20076b6da5c99de9
5
5
  SHA512:
6
- metadata.gz: 22f3bb93b50b5064d8db803023882e48539e9c212703b922379378e3cff63d017020b96c7cf3d2bdf3402768e4011f1ffbbd7ba823d513c3d81c9881a6f91a69
7
- data.tar.gz: 423fbd2cea4724aaeeacfc86fc6f90d15df211fc8a74a23c8e6ac2c93ff3744d27c502873d55b3beb03d3783db3492d74b26c63f2d0d940209668715bccbc8d1
6
+ metadata.gz: 4697954ffef80046805ce553050318270a85ddc62603f87a17d42673ec33af80073424a3176e58ea85468b13dacc25796497e7bb6a624b6763702f0673c564df
7
+ data.tar.gz: '059d1cade8f2f14756ff443a0c9bab78c28c22979e2a050aeb2b51178158d4bb5f3848c6e92721bdd31a57ce9db98379cbc03ad2c4b6644e005e260156c083e9'
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- app_manager (2.7.0)
4
+ app_manager (2.7.2)
5
5
  activerecord-import (~> 1.4)
6
6
  httparty
7
7
  kaminari (>= 0.16.3)
@@ -103,7 +103,7 @@ GEM
103
103
  diff-lcs (1.6.2)
104
104
  dotenv (2.1.2)
105
105
  drb (2.2.3)
106
- erb (6.0.6)
106
+ erb (6.0.7)
107
107
  erubi (1.13.1)
108
108
  globalid (1.4.0)
109
109
  activesupport (>= 6.1)
@@ -146,25 +146,21 @@ GEM
146
146
  marcel (1.2.1)
147
147
  method_source (1.1.0)
148
148
  mini_mime (1.1.5)
149
- mini_portile2 (2.8.9)
150
149
  minitest (6.0.6)
151
150
  drb (~> 2.0)
152
151
  prism (~> 1.5)
153
152
  multi_xml (0.9.1)
154
153
  bigdecimal (>= 3.1, < 5)
155
- net-imap (0.6.4.1)
154
+ net-imap (0.6.7)
156
155
  date
157
156
  net-protocol
158
157
  net-pop (0.1.2)
159
158
  net-protocol
160
- net-protocol (0.2.2)
159
+ net-protocol (0.4.0)
161
160
  timeout
162
- net-smtp (0.5.1)
161
+ net-smtp (0.5.2)
163
162
  net-protocol
164
163
  nio4r (2.7.5)
165
- nokogiri (1.19.4)
166
- mini_portile2 (~> 2.8.2)
167
- racc (~> 1.4)
168
164
  nokogiri (1.19.4-x86_64-linux-gnu)
169
165
  racc (~> 1.4)
170
166
  pp (0.6.4)
@@ -216,11 +212,11 @@ GEM
216
212
  tsort (>= 0.2)
217
213
  zeitwerk (~> 2.6)
218
214
  rake (13.3.1)
219
- rbs (4.0.3)
215
+ rbs (4.2.0)
220
216
  logger
221
217
  prism (>= 1.6.0)
222
218
  tsort
223
- rdoc (8.0.0)
219
+ rdoc (8.1.0)
224
220
  erb
225
221
  prism (>= 1.6.0)
226
222
  rbs (>= 4.0.0)
@@ -259,7 +255,7 @@ GEM
259
255
  base64
260
256
  websocket-extensions (>= 0.1.0)
261
257
  websocket-extensions (0.1.5)
262
- zeitwerk (2.8.2)
258
+ zeitwerk (2.8.3)
263
259
 
264
260
  PLATFORMS
265
261
  ruby
data/README.md CHANGED
@@ -50,7 +50,8 @@ AppManager.configure do |config|
50
50
  config.enable_caching = false # Optional, True to enable app-manager api response caching, default is enabled from gem
51
51
  config.expires_in = 1.days # Optional, Example: 30.seconds, 5.minutes or 2.days Default caching is for 1.days from gem
52
52
  config.app_url = '' # App URL like https://volumediscount.hulkapps.dev/ or #https://5044-2409-4052-209a-69da-9d7-925a-9418-a9c3.ngrok.io
53
- config.shopify_api_key = '' # Shopify api key of app
53
+ config.shopify_api_key = '' # Required, Shopify api key of app
54
+ config.shopify_api_secret = ENV['SHOPIFY_API_SECRET'] # Required, Shopify api secret of app. Verifies the billing page's session tokens; use your own env name if it differs
54
55
  config.shopify_api_version = '' # Must be 2022-04 or latest
55
56
  config.shopify_table_name = 'shops' # Table name which is generated by shopify mostly it is 'shops'
56
57
  config.shopify_domain_field = 'shopify_domain' #shopify domain field
@@ -137,6 +138,18 @@ end
137
138
  APP_MANAGER_API_URL: 'https://XXXXXXXX.com'
138
139
  ```
139
140
 
141
+ * **Required: `config.shopify_api_key` and `config.shopify_api_secret`.** The `/api/app-manager/*` routes are authenticated:
142
+
143
+ | Routes | Caller | Required |
144
+ |---|---|---|
145
+ | `users`, `burst-cache`, `fail-safe-backup`, `fail-safe-backup-full`, `cancel-charge`, `plan/activate-global`, `plan/cancel-global` | App Manager | `token` header = `APP_MANAGER_ACCESS_TOKEN` (App Manager already sends it) |
146
+ | `plans`, `plan-features`, `marketing-banners`, `plan/process/:plan_id`, `active-without-plan` | Embedded billing page | Shopify session token in `Authorization: Bearer …`, verified with `shopify_api_key` and `shopify_api_secret` |
147
+ | `plan/callback` | Shopify's redirect after charge approval | — |
148
+
149
+ Point both settings at the env variables that hold your app's Shopify API key and secret, using your own names if they differ, for example `ENV['SHOPIFY_PRIVATE_KEY']`. A `shop` / `shop_domain` param that doesn't match the session token's shop gets a 403. Nothing throws if a setting is missing or wrong: every billing-page request returns 401. A missing secret is reported to your error tracker, and a wrong secret or key logs a warning; each message starts with `App Manager:`.
150
+
151
+ The billing page must send the session token: `@shopcircle/app-manager-web-components` 1.4.0+ does this through App Bridge. A frontend calling these routes with axios needs a request interceptor that adds `Authorization: Bearer ${await shopify.idToken()}`.
152
+
140
153
  * App Manager provides a rake task that must needs to include in your existing app cron for every 10 minutes. Like if you are using [whenever](https://github.com/javan/whenever) gem then you MUST need to include following rake take in your 'schedule.rb' (created by whenever gem)
141
154
 
142
155
  ```
@@ -2,6 +2,7 @@ require_dependency "app_manager/application_controller"
2
2
 
3
3
  module AppManager
4
4
  class BannersController < ApplicationController
5
+ prepend_before_action :authorize_session_or_api_token, :only => [:marketing_banner]
5
6
  cache_response_for :marketing_banner
6
7
  def marketing_banner
7
8
  begin
@@ -2,6 +2,9 @@ require_dependency "app_manager/application_controller"
2
2
  module AppManager
3
3
  class ChargesController < ApplicationController
4
4
  include HTTParty
5
+ prepend_before_action :authorize_request, :only => [:cancel_charge, :activate_global, :cancel_global]
6
+ # callback stays open: Shopify redirects the merchant there after approving a charge.
7
+ prepend_before_action :authorize_session_or_api_token, :only => [:process_plan]
5
8
  skip_before_action :verify_authenticity_token, :only => [:process_plan,:activate_global,:cancel_charge,:cancel_global]
6
9
  before_action :params_permit
7
10
  require 'time'
@@ -51,6 +54,13 @@ module AppManager
51
54
  rescue Exception => e
52
55
  Rollbar.error("APP MANAGER Error in Process Plan #{e.inspect}-#{e.backtrace}")
53
56
  end
57
+ unless [true, 1, '1'].include?(plan_data['public'])
58
+ begin
59
+ plan_obj.mark_custom_plan_used(params[:shop], params[:plan_id])
60
+ rescue Exception => e
61
+ Rollbar.error("APP MANAGER Error marking custom plan used #{e.inspect}-#{e.backtrace}")
62
+ end
63
+ end
54
64
  AppManager.clear_cache
55
65
  # render json: {'redirect_url' => "#{app_url}?shop=#{params[:shop]}"} and return true
56
66
  render json: {'status' => true,'plan_type' => 'free_plan'} and return true
@@ -103,25 +113,35 @@ module AppManager
103
113
  if !@shop.nil?
104
114
  old_plan_id = @shop[@plan_field]
105
115
  old_plan_data = nil
116
+ raise Error, "Invalid charge" unless params[:charge_id].to_s.match?(/\A\d+\z/)
106
117
  headers = {"X-Shopify-Access-Token" => @shop[shopify_token]}
107
118
  charges = HTTParty.get('https://' + @shop[shopify_domain] + '/admin/api/' + @api_version + '/recurring_application_charges/' + params[:charge_id] + '.json', :headers => headers)
108
119
 
109
120
  if charges.parsed_response && charges.parsed_response.is_a?(Hash) && charges.parsed_response.has_key?('recurring_application_charge')
110
121
 
122
+ charge = charges.parsed_response['recurring_application_charge']
123
+ return redirect_to_app if charge['status'].to_s.downcase != 'active'
124
+
125
+ # Read the plan from Shopify's stored return_url: the query string can be edited.
126
+ bound = Rack::Utils.parse_query(URI.parse(charge['return_url'].to_s).query.to_s) rescue {}
127
+ raise Error, "Invalid charge" if bound['plan'].blank? || bound['shop'] != params[:shop]
128
+ plan_id = bound['plan']
129
+ discount_id = bound['discount']
130
+
111
131
  plan_obj = AppManager::Client.new
112
- plan_data = plan_obj.get_plan(params[:plan], params[:shop])
132
+ # TODO: an empty plan or failed store_charge leaves a paying merchant without the plan; report and retry.
133
+ plan_data = plan_obj.get_plan(plan_id, params[:shop])
113
134
 
114
- charge = charges.parsed_response['recurring_application_charge']
115
135
  charge['charge_id'] = charge['id']
116
136
  charge['type'] = 'recurring'
117
- charge['plan_id'] = params[:plan]
137
+ charge['plan_id'] = plan_id
118
138
  charge['shop_domain'] = params[:shop]
119
139
  charge['interval'] = plan_data['interval']['value']
120
140
 
121
141
  ['api_client_id', 'return_url', 'decorated_return_url','id','id','currency'].each { |k| charge.delete k }
122
142
 
123
143
  # Merge the discount snapshot captured at charge creation onto the charge row.
124
- snapshot_key = AppManager.charge_snapshot_cache_key(params[:shop], params[:timestamp])
144
+ snapshot_key = AppManager.charge_snapshot_cache_key(params[:shop], bound['timestamp'])
125
145
  discount_snapshot = Rails.cache.read(snapshot_key) rescue nil
126
146
  if discount_snapshot.is_a?(Hash)
127
147
  discount_snapshot.each { |field, value| charge[field] = value unless value.nil? || value == '' }
@@ -134,7 +154,7 @@ module AppManager
134
154
  if response['message'] == "success"
135
155
  AppManager.clear_cache
136
156
 
137
- update_info = {@plan_field => params[:plan],grandfathered_field => 0}
157
+ update_info = {@plan_field => plan_id,grandfathered_field => 0}
138
158
  if !config_trial_days.nil? && !plan_data.nil?
139
159
  trial_days = plan_data['trial_days'] || 0
140
160
  update_info[config_trial_days] = trial_days
@@ -157,10 +177,10 @@ module AppManager
157
177
 
158
178
  begin
159
179
  plan_obj = AppManager::Client.new
160
- if params[:discount].present? && !params[:discount].nil? && params[:discount] != '0' && plan_data['is_global'] == 0
161
- discounted_plans = plan_obj.get_related_discounted_plans(params[:discount])
162
- if discounted_plans.empty? || discounted_plans.include?(params[:plan].to_i)
163
- plan_obj.discount_used(@shop[shopify_domain], params[:discount])
180
+ if discount_id.present? && discount_id != '0' && plan_data['is_global'] == 0
181
+ discounted_plans = plan_obj.get_related_discounted_plans(discount_id)
182
+ if discounted_plans.empty? || discounted_plans.include?(plan_id.to_i)
183
+ plan_obj.discount_used(@shop[shopify_domain], discount_id)
164
184
  end
165
185
  end
166
186
  rescue Exception => e
@@ -299,6 +319,15 @@ module AppManager
299
319
  end
300
320
  end
301
321
 
322
+ def redirect_to_app
323
+ embed_host = Base64.encode64(params[:shop] + "/admin")
324
+ if app_slug.present?
325
+ redirect_to "https://#{params[:shop]}/admin/apps/#{app_slug}", :allow_other_host => true
326
+ else
327
+ redirect_to "#{app_url}?host=#{embed_host}&shop=#{params[:shop]}", :allow_other_host => true, :status => 301
328
+ end
329
+ end
330
+
302
331
  def app_url
303
332
  AppManager.configuration.app_url
304
333
  end
@@ -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
@@ -121,6 +121,8 @@ module AppManager
121
121
  return @fs.store_local_charge(params,options)
122
122
  when 'cancel-charge'
123
123
  return @fs.store_cancel_charge(params,options)
124
+ when 'mark-custom-plan-used'
125
+ return @fs.mark_custom_plan_used_helper(params,options)
124
126
  when 'get-remaining-days'
125
127
  return @fs.get_local_remaining_days(params,options)
126
128
  when 'get-charge'
@@ -23,6 +23,10 @@ module AppManager
23
23
  post("/cancel-charge", {shop_domain: shop_domain, plan_id: plan_id})
24
24
  end
25
25
 
26
+ def mark_custom_plan_used(shop_domain, plan_id)
27
+ post("/mark-custom-plan-used", {shop_domain: shop_domain, plan_id: plan_id})
28
+ end
29
+
26
30
  def update_charge(shop_domain, plan_id)
27
31
  post("/update-charge", {shop_domain: shop_domain, plan_id: plan_id})
28
32
  end
@@ -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
@@ -23,6 +24,7 @@ module AppManager
23
24
  @enable_caching = true
24
25
  @app_url = nil
25
26
  @shopify_api_key = nil
27
+ @shopify_api_secret = ENV['SHOPIFY_API_SECRET']
26
28
  @shopify_api_version = nil
27
29
  @shopify_table_name = 'shops'
28
30
  @shopify_domain_field = 'shopify_domain'
@@ -64,6 +66,10 @@ module AppManager
64
66
  @shopify_api_key
65
67
  end
66
68
 
69
+ def shopify_api_secret
70
+ @shopify_api_secret
71
+ end
72
+
67
73
  def shopify_api_version
68
74
  @shopify_api_version
69
75
  end
@@ -886,6 +886,17 @@ module AppManager
886
886
  return message
887
887
  end
888
888
 
889
+ def mark_custom_plan_used_helper(params, options)
890
+ shop_domain = options[:shop_domain] || params['shop_domain'] rescue nil
891
+ plan_id = options[:plan_id] || params['plan_id'] rescue nil
892
+ return {"message" => 'fail'} if shop_domain.blank? || plan_id.blank?
893
+ return {"message" => 'success', 'updated' => false} unless AppManager::PlanUser.column_names.include?('used')
894
+
895
+ updated = AppManager::PlanUser.where(shop_domain: shop_domain, plan_id: plan_id, used: false)
896
+ .update_all(used: true, updated_at: Time.current)
897
+ {"message" => 'success', 'updated' => updated > 0}
898
+ end
899
+
889
900
  def store_discount_used(params,options)
890
901
  if options && options[:shop_domain].present? && options[:discount_id].present?
891
902
  app_id = AppManager::Discount.where(discount_id: options[:discount_id])
@@ -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
@@ -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
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module AppManager
4
- VERSION = "2.7.0"
4
+ VERSION = "2.7.2"
5
5
  end
data/lib/app_manager.rb CHANGED
@@ -12,6 +12,7 @@ require "app_manager/graphql_helper"
12
12
  require "app_manager/response_cache"
13
13
  require "app_manager/config"
14
14
  require "app_manager/protection"
15
+ require "app_manager/session_token"
15
16
  require "app_manager/model"
16
17
  require "app_manager/fail_safe"
17
18
  require 'app_manager/railtie' if defined?(Rails)
@@ -2,7 +2,8 @@ AppManager.configure do |config|
2
2
  config.enable_caching = false # Optional, True to enable app-manager api response caching, default is enabled from gem
3
3
  config.expires_in = 1.days # Optional, Example: 30.seconds, 5.minutes or 2.days Default caching is for 1.days from gem
4
4
  config.app_url = '' # App URL like https://volumediscount.hulkapps.dev/ or #https://5044-2409-4052-209a-69da-9d7-925a-9418-a9c3.ngrok.io
5
- config.shopify_api_key = '' # Shopify api key of app
5
+ config.shopify_api_key = '' # Required, Shopify api key of app
6
+ config.shopify_api_secret = ENV['SHOPIFY_API_SECRET'] # Required, Shopify api secret of app. Verifies the billing page's session tokens; use your own env name if it differs
6
7
  config.shopify_api_version = '' # Must be 2022-04 or latest
7
8
  config.shopify_table_name = 'shops' # Table name which is generated by shopify mostly it is 'shops'
8
9
  config.shopify_domain_field = 'shopify_domain' #shopify domain field
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: app_manager
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.7.0
4
+ version: 2.7.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rahul Tiwari @ Hulkapps
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2026-07-23 00:00:00.000000000 Z
11
+ date: 2026-11-03 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: httparty
@@ -121,6 +121,7 @@ files:
121
121
  - lib/app_manager/protection.rb
122
122
  - lib/app_manager/railtie.rb
123
123
  - lib/app_manager/response_cache.rb
124
+ - lib/app_manager/session_token.rb
124
125
  - lib/app_manager/set_local_storage.rb
125
126
  - lib/app_manager/tasks/sync/local_app_manager.rake
126
127
  - lib/app_manager/version.rb