shopify_api-graphql-request 0.1.1 → 0.2.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 +4 -4
- data/.env.template +4 -0
- data/Changes +6 -0
- data/README.md +146 -28
- data/lib/shopify_api/graphql/request/oauth/access_token.rb +74 -32
- data/lib/shopify_api/graphql/request/oauth/access_token_migrator.rb +3 -4
- data/lib/shopify_api/graphql/request/oauth/client_assertion.rb +111 -0
- data/lib/shopify_api/graphql/request/oauth.rb +11 -0
- data/lib/shopify_api/graphql/request/shop.rb +42 -0
- data/lib/shopify_api/graphql/request/version.rb +1 -1
- data/lib/shopify_api/graphql/request.rb +88 -28
- data/lib/tasks/shopify.rake +41 -0
- metadata +29 -7
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 56926437cb2febbc651d11a9b502c8750ca16593c4a6ea7f72568a09c574ebbf
|
|
4
|
+
data.tar.gz: e353e1d4546d323d8d5b9f15215556400d800c0e9181dcc527ea4180342128e1
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 464d04e4fdb42dc6ec62a9d4e9acdf0f3acef724c9b9e583c90d853ce2ad9eeb3c75920fca5f208a5c68ebb0e25a27c1a33f11e785fb04062279678fbd4d843c
|
|
7
|
+
data.tar.gz: 5914d8d2f813841829b733ad98a8ca2cf70bffbadb340ab128a94b03666caf692ac22e56e85fd765ce78dd07b70d64d22656be80a8fbfc373a7528c034cb9031
|
data/.env.template
CHANGED
|
@@ -16,6 +16,10 @@ SHOPIFY_CLIENT_API_SECRET=
|
|
|
16
16
|
# Refresh token needed to test OAuth::AccessToken#refresh
|
|
17
17
|
SHOPIFY_REFRESH_TOKEN=
|
|
18
18
|
|
|
19
|
+
# Application-only access token tests. SHOPIFY_PRIVATE_KEY is a PEM file path or the PEM itself
|
|
20
|
+
SHOPIFY_KEY_ID=
|
|
21
|
+
SHOPIFY_PRIVATE_KEY=
|
|
22
|
+
|
|
19
23
|
# Will result in the creation of a metadafield on the customer. write_customers permission required
|
|
20
24
|
SHOPIFY_CUSTOMER_ID=
|
|
21
25
|
|
data/Changes
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
+
v0.2.0 2026-11-18
|
|
2
|
+
--------------------
|
|
3
|
+
Add support for application-only expiring tokens
|
|
4
|
+
Fix issues with token refresh when paginating
|
|
5
|
+
Change OAuth::AccessToken signatures to account for application-only access token requirements
|
|
6
|
+
|
|
1
7
|
v0.1.1 2026-11-11
|
|
2
8
|
--------------------
|
|
3
9
|
Improve robustness of token migration task when using a spreadsheet
|
data/README.md
CHANGED
|
@@ -2,8 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[](https://github.com/ScreenStaring/shopify_api-graphql-request/actions/workflows/main.yml)
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
Comes with built-in retry, token refresh, pagination, error handling, and more!
|
|
5
|
+
Simplify GraphQL queries and mutations for the Shopify Admin API. Comes with built-in OAuth token refresh, retry, pagination, error handling, and more!
|
|
7
6
|
|
|
8
7
|
## Usage
|
|
9
8
|
|
|
@@ -92,6 +91,8 @@ class ShopifyProduct < ShopifyAPI::GraphQL::Request
|
|
|
92
91
|
end
|
|
93
92
|
|
|
94
93
|
def list
|
|
94
|
+
return paginate(LIST) unless block_given?
|
|
95
|
+
|
|
95
96
|
paginate(LIST) { |page| yield page.dig(:data, :products, :edges) }
|
|
96
97
|
end
|
|
97
98
|
end
|
|
@@ -176,20 +177,49 @@ class ShopifyProduct < ShopifyAPI::GraphQL::Request
|
|
|
176
177
|
end
|
|
177
178
|
```
|
|
178
179
|
|
|
179
|
-
|
|
180
|
+
## Access Tokens
|
|
181
|
+
|
|
182
|
+
The following types of access tokens are supported:
|
|
183
|
+
|
|
184
|
+
- Expiring offline access tokens
|
|
185
|
+
- Expiring offline application-only access tokens
|
|
186
|
+
- Non-expiring offline access tokens
|
|
187
|
+
|
|
188
|
+
Several Rake tasks are included to assist with token-related processes. See [Rake Tasks](#rake-tasks).
|
|
189
|
+
|
|
190
|
+
Access tokens are managed by the `ShopifyAPI::GraphQL::Request::OAuth::AccessToken` class.
|
|
180
191
|
|
|
181
|
-
`ShopifyAPI::GraphQL::Request` can automatically refresh
|
|
192
|
+
`ShopifyAPI::GraphQL::Request` can automatically refresh expiring offline access tokens before making a request, and automatically retry once on 401 Unauthorized response.
|
|
193
|
+
To enable auto-refresh use the `:refresh` option:
|
|
182
194
|
|
|
183
|
-
|
|
195
|
+
```rb
|
|
196
|
+
ShopifyAPI::GraphQL::Request.new(shop, token, :refresh => { ... })
|
|
197
|
+
```
|
|
198
|
+
The options provided to `:refresh` depend on the token type. See the appropriate token's section below for more information.
|
|
199
|
+
|
|
200
|
+
### Expiring Offline Access Tokens
|
|
201
|
+
|
|
202
|
+
To enable auto-refresh of expiring tokens use the `:refresh` option with the following keys:
|
|
184
203
|
|
|
185
204
|
```rb
|
|
186
205
|
request = ShopifyAPI::GraphQL::Request.new(shop, token, :refresh => {
|
|
187
206
|
:client_id => SHOPIFY_CLIENT_ID,
|
|
188
207
|
:client_secret => SHOPIFY_CLIENT_SECRET,
|
|
189
208
|
:refresh_token => refresh_token,
|
|
190
|
-
:expires_at => expires_at,
|
|
191
|
-
:refresh_expires_at => refresh_expires_at,
|
|
192
|
-
:synchronize => ->(refresh, shopify_domain)
|
|
209
|
+
:expires_at => expires_at, # Absolute Time or Integer Unix epoch timestamp
|
|
210
|
+
:refresh_expires_at => refresh_expires_at, # Absolute Time or Integer Unix epoch timestamp
|
|
211
|
+
:synchronize => ->(refresh, shopify_domain) { } # See :synchronize Callback section
|
|
212
|
+
})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
#### The `:synchronize` Callback
|
|
216
|
+
|
|
217
|
+
Because refreshed tokens must be persisted for future requests a `:synchronize` callback is required. It is passed a `refresh` proc and the shop's Shopify domain:
|
|
218
|
+
|
|
219
|
+
```rb
|
|
220
|
+
ShopifyAPI::GraphQL::Request.new(shop, token, :refresh => {
|
|
221
|
+
# ...
|
|
222
|
+
:synchronize => -> (refresh, shopify_domain) do
|
|
193
223
|
shop = Shop.find_by!(:shopify_domain => shopify_domain)
|
|
194
224
|
|
|
195
225
|
shop.with_lock do
|
|
@@ -207,19 +237,18 @@ request = ShopifyAPI::GraphQL::Request.new(shop, token, :refresh => {
|
|
|
207
237
|
})
|
|
208
238
|
```
|
|
209
239
|
|
|
210
|
-
#### The `:synchronize` Callback
|
|
211
|
-
|
|
212
|
-
Because refreshed tokens must be persisted for future requests, `:synchronize` is required. It is passed a `refresh` proc and the shop's Shopify domain:
|
|
213
|
-
|
|
214
240
|
* `refresh.call` returns a `Hash` with `:access_token`, `:expires_at`, `:refresh_token`, and `:refresh_expires_at`. Note that `:expires_at` and `:refresh_expires_at` are absolute Unix epoch timestamps (in seconds), not relative duration offsets like Shopify's `expires_in`.
|
|
215
241
|
* Calling `refresh.call` without arguments refreshes using the client's **current in-memory token state**. If you're using multiple processes see [Multi-Process Concurrency](#multi-process-concurrency)
|
|
216
242
|
|
|
243
|
+
You can also use a class with a `#call` method.
|
|
244
|
+
|
|
217
245
|
#### Multi-Process Concurrency
|
|
218
246
|
|
|
219
247
|
In multi-process environments multiple processes may attempt to refresh an expired token simultaneously. To prevent duplicate refresh requests and token invalidation
|
|
220
248
|
pass the freshly read storage state to `refresh`:
|
|
221
249
|
|
|
222
250
|
```rb
|
|
251
|
+
# ...
|
|
223
252
|
:synchronize => ->(refresh, shop) do
|
|
224
253
|
shop = Shop.find_by!(:shopify_domain => shopify_domain)
|
|
225
254
|
shop.with_lock do
|
|
@@ -237,21 +266,94 @@ pass the freshly read storage state to `refresh`:
|
|
|
237
266
|
end
|
|
238
267
|
```
|
|
239
268
|
|
|
269
|
+
### Expiring Offline Application-Only Access Tokens
|
|
270
|
+
|
|
271
|
+
Two token types are supported:
|
|
272
|
+
|
|
273
|
+
- Client assertions for public apps
|
|
274
|
+
- Client credentials for stores in your own organization
|
|
275
|
+
|
|
276
|
+
#### Using a Client Assertion
|
|
277
|
+
|
|
278
|
+
This requires a public/private key pair and uploading the public key as a JWK to Shopify.
|
|
279
|
+
See [Shopify's documentation](https://shopify.dev/docs/apps/build/authentication-authorization/application-only-access-tokens).
|
|
280
|
+
|
|
281
|
+
Once you have your keys and have uploaded the JWK to Shopify you can use the private key to create a `ClientAssertion` and pass it to `AccessToken#client_credentials`:
|
|
282
|
+
|
|
283
|
+
```rb
|
|
284
|
+
assertion = ShopifyAPI::GraphQL::Request::OAuth::ClientAssertion.new(
|
|
285
|
+
SHOPIFY_CLIENT_ID,
|
|
286
|
+
File.read("your_private_key.pem"), # PEM String, OpenSSL::PKey::RSA, or OpenSSL::PKey::EC
|
|
287
|
+
KEY_ID # ID of the public key registered with Shopify
|
|
288
|
+
)
|
|
289
|
+
|
|
290
|
+
client = ShopifyAPI::GraphQL::Request::OAuth::AccessToken.new(SHOPIFY_CLIENT_ID)
|
|
291
|
+
result = client.client_credentials(shop, assertion) # => { "access_token" => "...", "scope" => "...", "expires_in" => 3599 }
|
|
292
|
+
|
|
293
|
+
# You can now make a request using result["access_token"]
|
|
294
|
+
request = ShopifyAPI::GraphQL::Request.new(shop, result["access_token"])
|
|
295
|
+
request.execute("query { ... }")
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
Application-only access tokens do not have a refresh token. `#client_credentials` must be called again when the token expires.
|
|
299
|
+
This can be done automatically, see [Refresh](#refresh).
|
|
300
|
+
|
|
301
|
+
#### Refresh
|
|
302
|
+
|
|
303
|
+
Pass the `:refresh` option to `ShopifyAPI::GraphQL::Request` to automatically refresh expiring application-only access tokens:
|
|
304
|
+
|
|
305
|
+
```rb
|
|
306
|
+
request = ShopifyAPI::GraphQL::Request.new(shop, token, :refresh => {
|
|
307
|
+
:client_id => SHOPIFY_CLIENT_ID,
|
|
308
|
+
:assertion => assertion, # Instance of ShopifyAPI::GraphQL::Request::OAuth::ClientAssertion
|
|
309
|
+
:expires_at => expires_at, # From AccessToken#client_credentials, can be an absolute Time or Integer Unix epoch timestamp
|
|
310
|
+
:synchronize => ->(refresh, shopify_domain) do
|
|
311
|
+
shop = Shop.find_by!(:shopify_domain => shopify_domain)
|
|
312
|
+
|
|
313
|
+
shop.with_lock do
|
|
314
|
+
new_state = refresh.call(:access_token => shop.access_token, :expires_at => shop.expires_at)
|
|
315
|
+
shop.update!(:access_token => new_state[:access_token], :expires_at => new_state[:expires_at])
|
|
316
|
+
end
|
|
317
|
+
end
|
|
318
|
+
})
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
See [The `:synchronize` Callback](#the-synchronize-callback) and [Multi-Process Concurrency](#multi-process-concurrency).
|
|
322
|
+
They work the same way here except the state has no `:refresh_token` or `:refresh_expires_at` key.
|
|
323
|
+
|
|
324
|
+
`ArgumentError` is raised for invalid arguments or public, unsupported, or incorrectly sized keys.
|
|
325
|
+
|
|
326
|
+
#### Using Client Credentials
|
|
327
|
+
|
|
328
|
+
This is only applicable for stores in your own organization. See [Shopify's documentation](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant).
|
|
329
|
+
|
|
330
|
+
```rb
|
|
331
|
+
client = ShopifyAPI::GraphQL::Request::OAuth::AccessToken.new(
|
|
332
|
+
SHOPIFY_CLIENT_ID,
|
|
333
|
+
SHOPIFY_CLIENT_SECRET
|
|
334
|
+
)
|
|
335
|
+
|
|
336
|
+
result = client.client_credentials(shop) # => { "access_token" => "...", "scope" => "...", "expires_in" => 86399 }
|
|
337
|
+
|
|
338
|
+
# You can now make a request using result["access_token"]
|
|
339
|
+
request = ShopifyAPI::GraphQL::Request.new(shop, result["access_token"])
|
|
340
|
+
request.execute("query { ... }")
|
|
341
|
+
```
|
|
342
|
+
|
|
240
343
|
### Migrating Non-Expiring Access Tokens
|
|
241
344
|
|
|
242
|
-
To migrate a legacy non-expiring offline access token to an expiring offline access token
|
|
345
|
+
To migrate a legacy non-expiring offline access token to an expiring offline access token call `ShopifyAPI::GraphQL::Request::OAuth::AccessToken#migrate`:
|
|
243
346
|
|
|
244
347
|
```rb
|
|
245
348
|
client = ShopifyAPI::GraphQL::Request::OAuth::AccessToken.new(
|
|
246
349
|
SHOPIFY_CLIENT_ID,
|
|
247
|
-
SHOPIFY_CLIENT_SECRET
|
|
248
|
-
shop
|
|
350
|
+
SHOPIFY_CLIENT_SECRET
|
|
249
351
|
)
|
|
250
352
|
|
|
251
|
-
tokens = client.migrate(non_expiring_token)
|
|
353
|
+
tokens = client.migrate(shop, non_expiring_token)
|
|
252
354
|
```
|
|
253
355
|
|
|
254
|
-
`#migrate` returns Shopify's token exchange response `Hash`:
|
|
356
|
+
`#migrate` returns Shopify's token exchange response as a `Hash`:
|
|
255
357
|
|
|
256
358
|
```rb
|
|
257
359
|
{
|
|
@@ -278,19 +380,31 @@ store.update!(
|
|
|
278
380
|
|
|
279
381
|
If the token is invalid or cannot be migrated, a `ShopifyAPI::GraphQL::Request::OAuth::AccessToken::InvalidTokenError` will be raised.
|
|
280
382
|
|
|
281
|
-
|
|
383
|
+
A Rake task is provided to assist with the migration of 1 or more stores. See [Rake Tasks](#rake-tasks).
|
|
384
|
+
|
|
385
|
+
#### Recovering a Lost Response
|
|
386
|
+
|
|
387
|
+
If a migration request fails or the response is lost, you can safely repeat the `#migrate` call with the original non-expiring token within
|
|
388
|
+
7 days of the initial exchange. Shopify will return the same token pair.
|
|
389
|
+
|
|
390
|
+
## Rake Tasks
|
|
391
|
+
|
|
392
|
+
The gem includes tasks to assist with token-related processes. If you are using Rails the tasks will be automatically loaded.
|
|
393
|
+
|
|
394
|
+
### Migrating Non-Expiring Access Tokens
|
|
282
395
|
|
|
283
|
-
|
|
396
|
+
Migrate a single shop:
|
|
284
397
|
|
|
285
398
|
```sh
|
|
286
|
-
# Migrate a single shop:
|
|
287
399
|
bundle exec rake shopify_api:graphql:request:migrate_access_tokens SHOPIFY_API_KEY=X SHOPIFY_API_SECRET=Y SHOP=my-shop TOKEN=shpat_...
|
|
400
|
+
```
|
|
288
401
|
|
|
289
|
-
|
|
402
|
+
Migrate using a CSV file. The CSV file requires "shop" and "token" columns:
|
|
403
|
+
```
|
|
290
404
|
bundle exec rake shopify_api:graphql:request:migrate_access_tokens SHOPIFY_API_KEY=X SHOPIFY_API_SECRET=Y FILE=tokens.csv HANDLER=update_token.rb
|
|
291
405
|
```
|
|
292
406
|
|
|
293
|
-
A single shop's tokens are always printed. `HANDLER=file.rb` is required with `FILE`
|
|
407
|
+
A single shop's tokens are always printed. `HANDLER=file.rb` is required with `FILE` and optional with `SHOP`. Use it to persist the new tokens.
|
|
294
408
|
The file is `load`ed and must define `update_token(shop, tokens)`, which is called with the shop and the return value of `#migrate`:
|
|
295
409
|
|
|
296
410
|
```rb
|
|
@@ -301,15 +415,19 @@ end
|
|
|
301
415
|
```
|
|
302
416
|
|
|
303
417
|
```sh
|
|
304
|
-
|
|
418
|
+
rake shopify_api:graphql:request:migrate_access_tokens SHOPIFY_API_KEY=X SHOPIFY_API_SECRET=Y FILE=tokens.csv HANDLER=update_token.rb
|
|
305
419
|
```
|
|
306
420
|
|
|
307
421
|
A summary of succeeded and failed shops (with the error for each failure) is printed when done. A failure for one shop does not stop the others; the task exits with status 1 if any shop failed.
|
|
308
422
|
|
|
309
|
-
|
|
423
|
+
### Exporting Your Public Key as a JSON Web Key (JWK)
|
|
310
424
|
|
|
311
|
-
|
|
312
|
-
|
|
425
|
+
To assist with the use [offline application-only access tokens](#expiring-offline-application-only-access-tokens) a task is included to export your public key as a JWK.
|
|
426
|
+
The task reads the PEM file (private or public key) given by `KEY` and outputs a JWK. The `KEY`, `KID`, and `ALG` (`RS256` or `ES256`) argumens are all required:
|
|
427
|
+
|
|
428
|
+
```sh
|
|
429
|
+
rake shopify_api:graphql:request:jwk_export KID=your-key-id ALG=RS256 KEY=private_key.pem
|
|
430
|
+
```
|
|
313
431
|
|
|
314
432
|
### More Info
|
|
315
433
|
|
|
@@ -318,13 +436,13 @@ For more information checkout [the API docs](https://rdoc.info/gems/shopify_api-
|
|
|
318
436
|
## Why Use This Instead of Shopify's API Client?
|
|
319
437
|
|
|
320
438
|
- Easy-to-use
|
|
439
|
+
- Built-in OAuth token refresh
|
|
321
440
|
- Built-in retry
|
|
322
441
|
- Built-in pagination
|
|
323
442
|
- Improved exception handling
|
|
324
443
|
- You can use `:snake_case` hash keys
|
|
325
|
-
- Lightweight
|
|
326
444
|
|
|
327
|
-
Overall, Shopify's API client
|
|
445
|
+
Overall, Shopify's API client has proven itself to be bloated trash that will give you development headaches and long-term maintenance nightmares.
|
|
328
446
|
|
|
329
447
|
We used to use it, staring way back in 2015, but eventually had to pivot away from their Ruby libraries due to developer
|
|
330
448
|
frustration and high maintenance cost (and don't get us started on the ShopifyApp gem!@#).
|
|
@@ -3,7 +3,10 @@ require "json"
|
|
|
3
3
|
require "net/http"
|
|
4
4
|
require "uri"
|
|
5
5
|
|
|
6
|
+
require "shopify_api/graphql/request/oauth"
|
|
7
|
+
require "shopify_api/graphql/request/shop"
|
|
6
8
|
require "shopify_api/graphql/request/version"
|
|
9
|
+
require "shopify_api/graphql/request/oauth/client_assertion"
|
|
7
10
|
|
|
8
11
|
module ShopifyAPI
|
|
9
12
|
module GraphQL
|
|
@@ -19,19 +22,16 @@ module ShopifyAPI
|
|
|
19
22
|
TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"
|
|
20
23
|
OFFLINE_TOKEN_TYPE = "urn:shopify:params:oauth:token-type:offline-access-token"
|
|
21
24
|
REFRESH_TOKEN_GRANT_TYPE = "refresh_token"
|
|
22
|
-
|
|
23
|
-
|
|
25
|
+
CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials"
|
|
26
|
+
CLIENT_ASSERTION_TYPE = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
|
|
24
27
|
|
|
25
28
|
USER_AGENT = "ShopifyAPI::GraphQL::Request v#{VERSION} (Ruby v#{RUBY_VERSION})"
|
|
26
29
|
|
|
27
|
-
SHOPIFY_DOMAIN = ".myshopify.com"
|
|
28
|
-
|
|
29
30
|
##
|
|
30
31
|
# === Arguments
|
|
31
32
|
#
|
|
32
33
|
# [client_id (String)] App's client ID
|
|
33
|
-
# [client_secret (String)] App's client secret
|
|
34
|
-
# [shop (String)] Shopify domain to make requests against
|
|
34
|
+
# [client_secret (String|nil)] App's client secret. Optional if only using +#client_credentials+ with a +ClientAssertion+.
|
|
35
35
|
# [options (Hash)] Client options. Optional.
|
|
36
36
|
#
|
|
37
37
|
# === Options
|
|
@@ -42,16 +42,19 @@ module ShopifyAPI
|
|
|
42
42
|
#
|
|
43
43
|
# === Errors
|
|
44
44
|
#
|
|
45
|
-
# ArgumentError if no +client_id
|
|
45
|
+
# ArgumentError if no +client_id+ is provided.
|
|
46
46
|
#
|
|
47
|
-
def initialize(client_id, client_secret
|
|
47
|
+
def initialize(client_id, client_secret = nil, options = nil)
|
|
48
48
|
raise ArgumentError, "client_id required" if client_id.to_s.strip.empty?
|
|
49
|
-
raise ArgumentError, "client_secret required" if client_secret.to_s.strip.empty?
|
|
50
|
-
raise ArgumentError, "shop required" if shop.to_s.strip.empty?
|
|
51
49
|
|
|
50
|
+
if client_secret.is_a?(Hash) && options.nil?
|
|
51
|
+
options = client_secret
|
|
52
|
+
client_secret = nil
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
client_secret = client_secret.to_s.strip
|
|
52
56
|
@client_id = client_id
|
|
53
|
-
@client_secret = client_secret
|
|
54
|
-
@domain = shopify_domain(shop)
|
|
57
|
+
@client_secret = client_secret.empty? ? nil : client_secret
|
|
55
58
|
|
|
56
59
|
options ||= {}
|
|
57
60
|
|
|
@@ -61,8 +64,6 @@ module ShopifyAPI
|
|
|
61
64
|
if options[:debug]
|
|
62
65
|
@debug = options[:debug].is_a?(IO) ? options[:debug] : $stderr
|
|
63
66
|
end
|
|
64
|
-
|
|
65
|
-
@endpoint = URI(sprintf(TOKEN_ENDPOINT, @domain))
|
|
66
67
|
end
|
|
67
68
|
|
|
68
69
|
##
|
|
@@ -70,6 +71,7 @@ module ShopifyAPI
|
|
|
70
71
|
#
|
|
71
72
|
# === Arguments
|
|
72
73
|
#
|
|
74
|
+
# [shop (String|Shop)] Shopify domain to make the request against
|
|
73
75
|
# [non_expiring_token (String)] Existing non-expiring offline access token to migrate
|
|
74
76
|
#
|
|
75
77
|
# === Returns
|
|
@@ -80,10 +82,12 @@ module ShopifyAPI
|
|
|
80
82
|
#
|
|
81
83
|
# ArgumentError, InvalidTokenError, Error
|
|
82
84
|
#
|
|
83
|
-
def migrate(non_expiring_token)
|
|
85
|
+
def migrate(shop, non_expiring_token)
|
|
86
|
+
raise ArgumentError, "client_secret required" unless @client_secret
|
|
84
87
|
raise ArgumentError, "token required" if non_expiring_token.to_s.strip.empty?
|
|
85
88
|
|
|
86
89
|
request(
|
|
90
|
+
shop,
|
|
87
91
|
:client_id => @client_id,
|
|
88
92
|
:client_secret => @client_secret,
|
|
89
93
|
:grant_type => TOKEN_EXCHANGE_GRANT_TYPE,
|
|
@@ -99,6 +103,7 @@ module ShopifyAPI
|
|
|
99
103
|
#
|
|
100
104
|
# === Arguments
|
|
101
105
|
#
|
|
106
|
+
# [shop (String|Shop)] Shopify domain to make the request against
|
|
102
107
|
# [refresh_token (String)] Refresh token to use
|
|
103
108
|
#
|
|
104
109
|
# === Returns
|
|
@@ -109,10 +114,12 @@ module ShopifyAPI
|
|
|
109
114
|
#
|
|
110
115
|
# ArgumentError, InvalidRefreshTokenError, Error
|
|
111
116
|
#
|
|
112
|
-
def refresh(refresh_token)
|
|
117
|
+
def refresh(shop, refresh_token)
|
|
118
|
+
raise ArgumentError, "client_secret required" unless @client_secret
|
|
113
119
|
raise ArgumentError, "refresh token required" if refresh_token.to_s.strip.empty?
|
|
114
120
|
|
|
115
121
|
request(
|
|
122
|
+
shop,
|
|
116
123
|
:client_id => @client_id,
|
|
117
124
|
:client_secret => @client_secret,
|
|
118
125
|
:grant_type => REFRESH_TOKEN_GRANT_TYPE,
|
|
@@ -120,25 +127,66 @@ module ShopifyAPI
|
|
|
120
127
|
)
|
|
121
128
|
end
|
|
122
129
|
|
|
130
|
+
##
|
|
131
|
+
# Request an access token using the client credentials grant.
|
|
132
|
+
# Uses the given +ClientAssertion+ if provided, otherwise the client secret.
|
|
133
|
+
#
|
|
134
|
+
# === Arguments
|
|
135
|
+
#
|
|
136
|
+
# [shop (String|Shop)] Shopify domain to make the request against
|
|
137
|
+
# [assertion (ClientAssertion)] Optional signed client assertion for public apps
|
|
138
|
+
#
|
|
139
|
+
# === Returns
|
|
140
|
+
#
|
|
141
|
+
# [Hash] The token response. Unmodified.
|
|
142
|
+
#
|
|
143
|
+
# === Errors
|
|
144
|
+
#
|
|
145
|
+
# ArgumentError, Error
|
|
146
|
+
#
|
|
147
|
+
def client_credentials(shop, assertion = nil)
|
|
148
|
+
domain = Shop.new(shop)
|
|
149
|
+
params = {
|
|
150
|
+
:client_id => @client_id,
|
|
151
|
+
:grant_type => CLIENT_CREDENTIALS_GRANT_TYPE
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if assertion
|
|
155
|
+
raise ArgumentError, "assertion must be a ClientAssertion" unless assertion.is_a?(ClientAssertion)
|
|
156
|
+
|
|
157
|
+
params[:client_assertion_type] = CLIENT_ASSERTION_TYPE
|
|
158
|
+
params[:client_assertion] = assertion.to_jwt(domain)
|
|
159
|
+
else
|
|
160
|
+
raise ArgumentError, "client_secret required" unless @client_secret
|
|
161
|
+
|
|
162
|
+
params[:client_secret] = @client_secret
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
request(domain, params)
|
|
166
|
+
end
|
|
167
|
+
|
|
123
168
|
private
|
|
124
169
|
|
|
125
|
-
def request(params)
|
|
126
|
-
|
|
170
|
+
def request(shop, params)
|
|
171
|
+
domain = shop.is_a?(Shop) ? shop : Shop.new(shop)
|
|
172
|
+
endpoint = URI(sprintf(TOKEN_ENDPOINT, domain))
|
|
173
|
+
|
|
174
|
+
response = post(endpoint, params)
|
|
127
175
|
body = parse_body(response)
|
|
128
176
|
|
|
129
|
-
handle_error(response, body) unless response.is_a?(Net::HTTPSuccess)
|
|
177
|
+
handle_error(domain, response, body) unless response.is_a?(Net::HTTPSuccess)
|
|
130
178
|
|
|
131
179
|
body
|
|
132
180
|
end
|
|
133
181
|
|
|
134
|
-
def post(params)
|
|
135
|
-
http = Net::HTTP.new(
|
|
182
|
+
def post(endpoint, params)
|
|
183
|
+
http = Net::HTTP.new(endpoint.host, endpoint.port)
|
|
136
184
|
http.use_ssl = true
|
|
137
185
|
http.open_timeout = @open_timeout if @open_timeout
|
|
138
186
|
http.read_timeout = @read_timeout if @read_timeout
|
|
139
187
|
http.set_debug_output(@debug) if @debug
|
|
140
188
|
|
|
141
|
-
post = Net::HTTP::Post.new(
|
|
189
|
+
post = Net::HTTP::Post.new(endpoint.path)
|
|
142
190
|
post.body = URI.encode_www_form(params)
|
|
143
191
|
post["Content-Type"] = "application/x-www-form-urlencoded"
|
|
144
192
|
post["Accept"] = "application/json"
|
|
@@ -156,18 +204,18 @@ module ShopifyAPI
|
|
|
156
204
|
raise Error, "failed to parse JSON response: #{e.message}"
|
|
157
205
|
end
|
|
158
206
|
|
|
159
|
-
def handle_error(response, body)
|
|
207
|
+
def handle_error(domain, response, body)
|
|
160
208
|
error = body["error"] if body.is_a?(Hash)
|
|
161
209
|
message = error_message(body)
|
|
162
210
|
|
|
163
211
|
if response.code == "400" && (error == "invalid_subject_token" || error == "invalid_requested_token_type")
|
|
164
|
-
raise InvalidTokenError, "failed to migrate access token for #{
|
|
212
|
+
raise InvalidTokenError, "failed to migrate access token for #{domain}: #{message}"
|
|
165
213
|
# RFC 6749 §5.2 specifies HTTP 400 for invalid_grant, but Shopify returns HTTP 401
|
|
166
214
|
# when a refresh token is inactive, expired, or already rotated. Check both to be safe.
|
|
167
215
|
elsif (response.code == "400" || response.code == "401") && error == "invalid_grant"
|
|
168
|
-
raise InvalidRefreshTokenError, "failed to refresh access token for #{
|
|
216
|
+
raise InvalidRefreshTokenError, "failed to refresh access token for #{domain}: #{message}"
|
|
169
217
|
else
|
|
170
|
-
raise Error, "failed to request access token for #{
|
|
218
|
+
raise Error, "failed to request access token for #{domain}: #{message} (HTTP #{response.code})"
|
|
171
219
|
end
|
|
172
220
|
end
|
|
173
221
|
|
|
@@ -176,12 +224,6 @@ module ShopifyAPI
|
|
|
176
224
|
|
|
177
225
|
body["error_description"] || body["error"] || body.to_s
|
|
178
226
|
end
|
|
179
|
-
|
|
180
|
-
def shopify_domain(host)
|
|
181
|
-
domain = host.sub(%r{\Ahttps?://}i, "")
|
|
182
|
-
domain << SHOPIFY_DOMAIN unless domain.end_with?(SHOPIFY_DOMAIN)
|
|
183
|
-
domain
|
|
184
|
-
end
|
|
185
227
|
end
|
|
186
228
|
end
|
|
187
229
|
end
|
|
@@ -39,8 +39,6 @@ module ShopifyAPI
|
|
|
39
39
|
# ArgumentError
|
|
40
40
|
#
|
|
41
41
|
def initialize(client_id, client_secret, options = {})
|
|
42
|
-
@client_id = client_id
|
|
43
|
-
@client_secret = client_secret
|
|
44
42
|
@shop = nil_if_blank(options[:shop])
|
|
45
43
|
@token = nil_if_blank(options[:token])
|
|
46
44
|
@file = nil_if_blank(options[:file])
|
|
@@ -51,6 +49,8 @@ module ShopifyAPI
|
|
|
51
49
|
raise ArgumentError, "client_secret required" if nil_if_blank(client_secret).nil?
|
|
52
50
|
raise ArgumentError, "shop or file required" unless @shop || @file
|
|
53
51
|
raise ArgumentError, "handler required when using file" if !@shop && !@handler
|
|
52
|
+
|
|
53
|
+
@client = AccessToken.new(client_id, client_secret)
|
|
54
54
|
end
|
|
55
55
|
|
|
56
56
|
##
|
|
@@ -108,8 +108,7 @@ module ShopifyAPI
|
|
|
108
108
|
end
|
|
109
109
|
|
|
110
110
|
def migrate(shop, token)
|
|
111
|
-
|
|
112
|
-
result = client.migrate(token)
|
|
111
|
+
result = @client.migrate(shop, token)
|
|
113
112
|
|
|
114
113
|
@out.puts result.pretty_inspect if @shop
|
|
115
114
|
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require "jwt"
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
|
|
6
|
+
require "shopify_api/graphql/request/oauth"
|
|
7
|
+
require "shopify_api/graphql/request/shop"
|
|
8
|
+
|
|
9
|
+
module ShopifyAPI
|
|
10
|
+
module GraphQL
|
|
11
|
+
class Request
|
|
12
|
+
module OAuth
|
|
13
|
+
##
|
|
14
|
+
# Builds signed, single-use JWT client assertions for Shopify application-only access tokens.
|
|
15
|
+
#
|
|
16
|
+
class ClientAssertion
|
|
17
|
+
MAX_STRING_SIZE = 255
|
|
18
|
+
LIFETIME = 60
|
|
19
|
+
# Shopify requires RSA keys to be between 2048 and 8192 bits:
|
|
20
|
+
# keys < 2048 bits are insecure and rejected by Shopify; keys > 8192 bits are unsupported.
|
|
21
|
+
RSA_KEY_SIZES = (2048..8192).freeze
|
|
22
|
+
EC_CURVE = "prime256v1"
|
|
23
|
+
|
|
24
|
+
##
|
|
25
|
+
# === Arguments
|
|
26
|
+
#
|
|
27
|
+
# [client_id (String)] App's client ID
|
|
28
|
+
# [private_key (OpenSSL::PKey::RSA|OpenSSL::PKey::EC|String)] Private key or PEM encoded private key.
|
|
29
|
+
# RSA (2048-8192 bits) or EC (prime256v1).
|
|
30
|
+
# [key_id (String)] ID of the corresponding public key registered with Shopify
|
|
31
|
+
#
|
|
32
|
+
# === Errors
|
|
33
|
+
#
|
|
34
|
+
# ArgumentError if an argument is invalid or the key is not a supported private key.
|
|
35
|
+
#
|
|
36
|
+
def initialize(client_id, private_key, key_id)
|
|
37
|
+
raise ArgumentError, "client_id required" if client_id.to_s.strip.empty?
|
|
38
|
+
raise ArgumentError, "client_id too long" if client_id.to_s.size > MAX_STRING_SIZE
|
|
39
|
+
raise ArgumentError, "key_id required" if key_id.to_s.strip.empty?
|
|
40
|
+
raise ArgumentError, "key_id too long" if key_id.to_s.size > MAX_STRING_SIZE
|
|
41
|
+
raise ArgumentError, "key_id must not have leading or trailing whitespace" if key_id.to_s != key_id.to_s.strip
|
|
42
|
+
|
|
43
|
+
@client_id = client_id
|
|
44
|
+
@key_id = key_id
|
|
45
|
+
@private_key = read_key(private_key)
|
|
46
|
+
@alg = algorithm(@private_key)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
##
|
|
50
|
+
# Build and sign a JWT for the given shop.
|
|
51
|
+
#
|
|
52
|
+
# === Arguments
|
|
53
|
+
#
|
|
54
|
+
# [shop (String|Shop)] Shopify domain the assertion is for
|
|
55
|
+
#
|
|
56
|
+
# === Returns
|
|
57
|
+
#
|
|
58
|
+
# [String] The JWT
|
|
59
|
+
#
|
|
60
|
+
# === Errors
|
|
61
|
+
#
|
|
62
|
+
# ArgumentError if no +shop+ is provided.
|
|
63
|
+
#
|
|
64
|
+
def to_jwt(shop)
|
|
65
|
+
now = Time.now.to_i
|
|
66
|
+
payload = {
|
|
67
|
+
:iss => @client_id,
|
|
68
|
+
:sub => @client_id,
|
|
69
|
+
:aud => sprintf(TOKEN_ENDPOINT, Shop.new(shop)),
|
|
70
|
+
:iat => now,
|
|
71
|
+
:exp => now + LIFETIME,
|
|
72
|
+
:jti => SecureRandom.uuid
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
JWT.encode(payload, @private_key, @alg, :kid => @key_id)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
private
|
|
79
|
+
|
|
80
|
+
def read_key(key)
|
|
81
|
+
key = OpenSSL::PKey.read(key) if key.is_a?(String)
|
|
82
|
+
raise ArgumentError, "private_key required" unless key.is_a?(OpenSSL::PKey::PKey)
|
|
83
|
+
raise ArgumentError, "private_key must be a private key" unless private_key?(key)
|
|
84
|
+
|
|
85
|
+
key
|
|
86
|
+
rescue OpenSSL::PKey::PKeyError => e
|
|
87
|
+
raise ArgumentError, "invalid private_key: #{e.message}"
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
def private_key?(key)
|
|
91
|
+
key.respond_to?(:private?) ? key.private? : key.private_key?
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def algorithm(key)
|
|
95
|
+
if key.is_a?(OpenSSL::PKey::RSA)
|
|
96
|
+
raise ArgumentError, "RSA private_key must be 2048 to 8192 bits" unless RSA_KEY_SIZES.include?(key.n.num_bits)
|
|
97
|
+
|
|
98
|
+
"RS256"
|
|
99
|
+
elsif key.is_a?(OpenSSL::PKey::EC)
|
|
100
|
+
raise ArgumentError, "EC private_key must use the #{EC_CURVE} curve" unless key.group.curve_name == EC_CURVE
|
|
101
|
+
|
|
102
|
+
"ES256"
|
|
103
|
+
else
|
|
104
|
+
raise ArgumentError, "unsupported private_key type: #{key.class}"
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
end
|
|
111
|
+
end
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module ShopifyAPI
|
|
4
|
+
module GraphQL
|
|
5
|
+
class Request
|
|
6
|
+
##
|
|
7
|
+
# A Shopify shop's fully qualified +myshopify.com+ domain.
|
|
8
|
+
#
|
|
9
|
+
# Converts to a +String+ via +#to_s+ and +#to_str+.
|
|
10
|
+
#
|
|
11
|
+
class Shop
|
|
12
|
+
SHOPIFY_DOMAIN = ".myshopify.com"
|
|
13
|
+
|
|
14
|
+
##
|
|
15
|
+
# === Arguments
|
|
16
|
+
#
|
|
17
|
+
# [store (String|Shop)] Shop's handle, e.g. +my-shop+, or its domain, optionally with a scheme.
|
|
18
|
+
#
|
|
19
|
+
# === Errors
|
|
20
|
+
#
|
|
21
|
+
# ArgumentError if +store+ is blank.
|
|
22
|
+
#
|
|
23
|
+
def initialize(store)
|
|
24
|
+
store = store.to_s.strip
|
|
25
|
+
store.sub!(%r{\Ahttps?://}i, "")
|
|
26
|
+
# Strip trailing slashes, paths, and query/fragment parameters if given a URL
|
|
27
|
+
store.sub!(%r{[/?#].*\z}, "")
|
|
28
|
+
store.sub!(/\.?myshopify\.com\z/i, "")
|
|
29
|
+
raise ArgumentError, "shop required" if store.empty?
|
|
30
|
+
|
|
31
|
+
@domain = "#{store}#{SHOPIFY_DOMAIN}"
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def to_s
|
|
35
|
+
@domain.dup
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
alias to_str to_s
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
@@ -20,6 +20,10 @@ module ShopifyAPI
|
|
|
20
20
|
# instead of an absolute point in time.
|
|
21
21
|
MIN_EPOCH_TIMESTAMP = 1_000_000_000
|
|
22
22
|
|
|
23
|
+
# Refresh access tokens slightly before expiration to cover clock skew and avoid
|
|
24
|
+
# unnecessary 401 round-trips on borderline requests.
|
|
25
|
+
TOKEN_EXPIRY_BUFFER = 60
|
|
26
|
+
|
|
23
27
|
class UserError < Error
|
|
24
28
|
attr_reader :errors
|
|
25
29
|
|
|
@@ -66,11 +70,18 @@ module ShopifyAPI
|
|
|
66
70
|
# [:raise_if_not_found (Boolean)] If +true+ raise a NotFoundError if the requested record is not found. Defaults to +true+.
|
|
67
71
|
# [:raise_if_user_errors (Boolean)] If +true+ raise a UserError if the mutation resulted in user errors. Defaults to +true+.
|
|
68
72
|
# [:snake_case (Boolean)] Convert response `Hash` keys to +snake_case+ symbols. Defaults to +true+.
|
|
69
|
-
# [:refresh (Hash)] Auto-refresh expiring access tokens. Requires +:client_id+, +:client_secret
|
|
70
|
-
# +:expires_at+,
|
|
73
|
+
# [:refresh (Hash)] Auto-refresh expiring access tokens. Requires +:client_id+, +:client_secret+ (or +:assertion+),
|
|
74
|
+
# +:expires_at+, and +:synchronize+. For expiring offline tokens, also pass +:refresh_token+
|
|
75
|
+
# (and optionally +:refresh_expires_at+).
|
|
71
76
|
# +:expires_at+ and +:refresh_expires_at+ must be absolute timestamps (+Time+s or Integer Unix epoch timestamps in seconds),
|
|
72
77
|
# not relative duration offsets (e.g. Shopify's +expires_in+).
|
|
73
78
|
#
|
|
79
|
+
# For application-only access tokens, omit +:refresh_token+ (and pass +:assertion+ as an
|
|
80
|
+
# OAuth::ClientAssertion for public apps, or +:client_secret+ for stores in your organization).
|
|
81
|
+
# A new token is obtained with OAuth::AccessToken#client_credentials.
|
|
82
|
+
# To get the first token pass +nil+ for +token+ and omit +:expires_at+; the token is requested
|
|
83
|
+
# on the first query via +:synchronize+. Offline tokens must be obtained via OAuth authorization or token exchange.
|
|
84
|
+
#
|
|
74
85
|
# +:synchronize+ is a Proc called with a refresh Proc and the shop. It should persist the new token
|
|
75
86
|
# state returned by the refresh Proc:
|
|
76
87
|
#
|
|
@@ -92,22 +103,31 @@ module ShopifyAPI
|
|
|
92
103
|
end
|
|
93
104
|
|
|
94
105
|
@shop = shop
|
|
95
|
-
@gql = ShopifyAPI::GraphQL::Tiny.new(shop, token, @options)
|
|
96
|
-
|
|
97
106
|
@gid = TinyGID.new("shopify")
|
|
98
107
|
|
|
99
108
|
refresh = @options[:refresh]
|
|
109
|
+
# Without :refresh a token is required, Tiny will raise if it's missing.
|
|
110
|
+
# With :refresh the first token is obtained, via the :synchronize callback, on the first request.
|
|
111
|
+
@gql = ShopifyAPI::GraphQL::Tiny.new(shop, token, @options) unless refresh && token.nil?
|
|
100
112
|
return unless refresh
|
|
101
113
|
|
|
102
114
|
raise ArgumentError, ":refresh must be a Hash" unless refresh.is_a?(Hash)
|
|
103
115
|
|
|
104
|
-
|
|
116
|
+
@assertion = refresh[:assertion]
|
|
117
|
+
raise ArgumentError, ":assertion must be a ClientAssertion" if @assertion && !@assertion.is_a?(OAuth::ClientAssertion)
|
|
118
|
+
|
|
119
|
+
required = [:client_id]
|
|
120
|
+
required << :expires_at unless token.nil?
|
|
121
|
+
required << :synchronize
|
|
122
|
+
required << :client_secret unless @assertion
|
|
123
|
+
|
|
124
|
+
missing = required.reject { |name| refresh.include?(name) }
|
|
105
125
|
raise ArgumentError, ":refresh requires #{missing.join(", ")}" if missing.any?
|
|
106
126
|
|
|
107
|
-
validate_timestamp(:expires_at, refresh[:expires_at])
|
|
127
|
+
validate_timestamp(:expires_at, refresh[:expires_at]) if refresh[:expires_at] || !token.nil?
|
|
108
128
|
validate_timestamp(:refresh_expires_at, refresh[:refresh_expires_at]) if refresh[:refresh_expires_at]
|
|
109
129
|
|
|
110
|
-
@oauth = OAuth::AccessToken.new(refresh[:client_id], refresh[:client_secret],
|
|
130
|
+
@oauth = OAuth::AccessToken.new(refresh[:client_id], refresh[:client_secret], @options)
|
|
111
131
|
@synchronize = refresh[:synchronize]
|
|
112
132
|
@token_state = {
|
|
113
133
|
:access_token => token,
|
|
@@ -159,6 +179,9 @@ module ShopifyAPI
|
|
|
159
179
|
begin
|
|
160
180
|
data = gql.execute(query, variables)
|
|
161
181
|
rescue ShopifyAPI::GraphQL::Tiny::HTTPError => error
|
|
182
|
+
# TODO: check error message to ensure it's a refreshable error or a legit failure
|
|
183
|
+
warn error
|
|
184
|
+
warn error.code
|
|
162
185
|
raise unless refreshable? && error.code == "401"
|
|
163
186
|
|
|
164
187
|
refresh_after_401
|
|
@@ -194,28 +217,18 @@ module ShopifyAPI
|
|
|
194
217
|
options = @options.merge(options || {})
|
|
195
218
|
|
|
196
219
|
variables = camelize_keys(variables) if options[:snake_case]
|
|
197
|
-
ensure_fresh_token
|
|
198
220
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
pages = pager.execute(query, variables).map do |page|
|
|
203
|
-
raise_if_not_found(page, variables) if options[:raise_if_not_found]
|
|
204
|
-
raise_if_user_errors(page) if options[:raise_if_user_errors]
|
|
205
|
-
|
|
206
|
-
page = snake_case_keys(page) if options[:snake_case]
|
|
207
|
-
page
|
|
208
|
-
end
|
|
221
|
+
pager = RetryPaginator.new(self, query, variables).lazy.map do |page|
|
|
222
|
+
raise_if_not_found(page, variables) if options[:raise_if_not_found]
|
|
223
|
+
raise_if_user_errors(page) if options[:raise_if_user_errors]
|
|
209
224
|
|
|
210
|
-
|
|
225
|
+
page = snake_case_keys(page) if options[:snake_case]
|
|
226
|
+
page
|
|
227
|
+
end
|
|
211
228
|
|
|
212
|
-
|
|
213
|
-
rescue ShopifyAPI::GraphQL::Tiny::HTTPError => error
|
|
214
|
-
raise unless refreshable? && error.code == "401"
|
|
229
|
+
return pager unless block_given?
|
|
215
230
|
|
|
216
|
-
|
|
217
|
-
retry
|
|
218
|
-
end
|
|
231
|
+
pager.each { |page| yield page }
|
|
219
232
|
|
|
220
233
|
nil
|
|
221
234
|
end
|
|
@@ -250,6 +263,40 @@ module ShopifyAPI
|
|
|
250
263
|
|
|
251
264
|
private
|
|
252
265
|
|
|
266
|
+
# Enumerates paginated GraphQL results, refreshing the access token at most once per page on 401
|
|
267
|
+
# and resuming from the pager's current cursor.
|
|
268
|
+
class RetryPaginator < Enumerator # :nodoc:
|
|
269
|
+
def initialize(request, query, variables)
|
|
270
|
+
super() do |y|
|
|
271
|
+
request.send(:ensure_fresh_token)
|
|
272
|
+
|
|
273
|
+
vars = variables ? variables.dup : {}
|
|
274
|
+
refreshed = false
|
|
275
|
+
|
|
276
|
+
begin
|
|
277
|
+
pager = request.send(:gql).paginate
|
|
278
|
+
pager.execute(query, vars) do |page|
|
|
279
|
+
# A page succeeded, so a later 401 may refresh again
|
|
280
|
+
refreshed = false
|
|
281
|
+
# Yielding inside this rescue block means a 401 HTTPError raised by the
|
|
282
|
+
# caller's block will also trigger a refresh and retry of the current page.
|
|
283
|
+
y << page
|
|
284
|
+
end
|
|
285
|
+
rescue ShopifyAPI::GraphQL::Tiny::HTTPError => error
|
|
286
|
+
# Only refresh once per page, otherwise a persistent 401 (e.g., revoked access) would loop forever
|
|
287
|
+
raise unless request.send(:refreshable?) && error.code == "401" && !refreshed
|
|
288
|
+
|
|
289
|
+
request.send(:refresh_after_401)
|
|
290
|
+
refreshed = true
|
|
291
|
+
vars["after"] = pager.cursor if pager.cursor
|
|
292
|
+
retry
|
|
293
|
+
end
|
|
294
|
+
end
|
|
295
|
+
end
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
private_constant :RetryPaginator
|
|
299
|
+
|
|
253
300
|
def ensure_fresh_token
|
|
254
301
|
return unless refreshable?
|
|
255
302
|
return unless token_expired?(@token_state)
|
|
@@ -262,8 +309,10 @@ module ShopifyAPI
|
|
|
262
309
|
end
|
|
263
310
|
|
|
264
311
|
def token_expired?(state)
|
|
312
|
+
return true if state[:access_token].nil?
|
|
313
|
+
|
|
265
314
|
expires_at = state[:expires_at]
|
|
266
|
-
expires_at && to_time(expires_at) <= Time.now
|
|
315
|
+
expires_at && to_time(expires_at) <= Time.now + TOKEN_EXPIRY_BUFFER
|
|
267
316
|
end
|
|
268
317
|
|
|
269
318
|
def to_time(value)
|
|
@@ -291,7 +340,7 @@ module ShopifyAPI
|
|
|
291
340
|
def refresh_tokens(state = @token_state)
|
|
292
341
|
state ||= @token_state
|
|
293
342
|
if token_expired?(state)
|
|
294
|
-
@token_state = normalize_tokens(
|
|
343
|
+
@token_state = normalize_tokens(request_tokens(state))
|
|
295
344
|
else
|
|
296
345
|
@token_state = state
|
|
297
346
|
end
|
|
@@ -300,12 +349,21 @@ module ShopifyAPI
|
|
|
300
349
|
def refresh_stale_tokens(state = @token_state)
|
|
301
350
|
state ||= @token_state
|
|
302
351
|
if state.equal?(@token_state) || state[:access_token] == @token_state[:access_token]
|
|
303
|
-
@token_state = normalize_tokens(
|
|
352
|
+
@token_state = normalize_tokens(request_tokens(state))
|
|
304
353
|
else
|
|
305
354
|
@token_state = state
|
|
306
355
|
end
|
|
307
356
|
end
|
|
308
357
|
|
|
358
|
+
# Application-only access tokens have no refresh token, get a new one with #client_credentials
|
|
359
|
+
def request_tokens(state)
|
|
360
|
+
if state[:refresh_token] && !@assertion
|
|
361
|
+
@oauth.refresh(@shop, state[:refresh_token])
|
|
362
|
+
else
|
|
363
|
+
@oauth.client_credentials(@shop, @assertion)
|
|
364
|
+
end
|
|
365
|
+
end
|
|
366
|
+
|
|
309
367
|
def refresh_after_401
|
|
310
368
|
synchronize(method(:refresh_stale_tokens))
|
|
311
369
|
end
|
|
@@ -352,5 +410,7 @@ module ShopifyAPI
|
|
|
352
410
|
end
|
|
353
411
|
end
|
|
354
412
|
|
|
413
|
+
require "shopify_api/graphql/request/shop"
|
|
414
|
+
require "shopify_api/graphql/request/oauth/client_assertion"
|
|
355
415
|
require "shopify_api/graphql/request/oauth/access_token"
|
|
356
416
|
require "shopify_api/graphql/request/railtie" if defined?(Rails::Railtie)
|
data/lib/tasks/shopify.rake
CHANGED
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require "json"
|
|
4
|
+
require "jwt"
|
|
5
|
+
require "openssl"
|
|
6
|
+
|
|
3
7
|
require "shopify_api/graphql/request"
|
|
4
8
|
require "shopify_api/graphql/request/oauth/access_token_migrator"
|
|
9
|
+
require "shopify_api/graphql/request/oauth/client_assertion"
|
|
5
10
|
|
|
6
11
|
namespace :shopify_api do
|
|
7
12
|
namespace :graphql do
|
|
@@ -37,6 +42,42 @@ namespace :shopify_api do
|
|
|
37
42
|
|
|
38
43
|
exit 1 unless failed.empty?
|
|
39
44
|
end
|
|
45
|
+
|
|
46
|
+
desc "Export a public key as a JWK. Requires KEY (PEM file), KID, and ALG (RS256 or ES256)."
|
|
47
|
+
task :jwk_export do
|
|
48
|
+
path = ENV["KEY"].to_s.strip
|
|
49
|
+
kid = ENV["KID"].to_s.strip
|
|
50
|
+
alg = ENV["ALG"].to_s.strip
|
|
51
|
+
|
|
52
|
+
abort "KEY required" if path.empty?
|
|
53
|
+
abort "KID required" if kid.empty?
|
|
54
|
+
abort "ALG required" if alg.empty?
|
|
55
|
+
|
|
56
|
+
key_types = { "RS256" => OpenSSL::PKey::RSA, "ES256" => OpenSSL::PKey::EC }
|
|
57
|
+
abort "ALG must be one of: #{key_types.keys.join(", ")}" unless key_types.include?(alg)
|
|
58
|
+
|
|
59
|
+
abort "KEY file not found: #{path}" unless File.file?(path)
|
|
60
|
+
|
|
61
|
+
begin
|
|
62
|
+
key = OpenSSL::PKey.read(File.read(path))
|
|
63
|
+
rescue OpenSSL::PKey::PKeyError => e
|
|
64
|
+
abort "invalid key: #{e.message}"
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
abort "key must be an #{key_types[alg].name.split("::").last} key for #{alg}" unless key.is_a?(key_types[alg])
|
|
68
|
+
|
|
69
|
+
client_assertion = ShopifyAPI::GraphQL::Request::OAuth::ClientAssertion
|
|
70
|
+
if key.is_a?(OpenSSL::PKey::RSA)
|
|
71
|
+
# Shopify requires RSA keys to be between 2048 and 8192 bits
|
|
72
|
+
abort "RSA key must be 2048 to 8192 bits" unless client_assertion::RSA_KEY_SIZES.include?(key.n.num_bits)
|
|
73
|
+
elsif key.is_a?(OpenSSL::PKey::EC)
|
|
74
|
+
# Shopify requires ECDSA keys using the prime256v1 (P-256) curve for ES256
|
|
75
|
+
abort "EC key must use the #{client_assertion::EC_CURVE} curve" unless key.group.curve_name == client_assertion::EC_CURVE
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Only the public parameters are exported
|
|
79
|
+
puts JSON.pretty_generate(JWT::JWK.new(key, :kid => kid, :alg => alg, :use => "sig").export)
|
|
80
|
+
end
|
|
40
81
|
end
|
|
41
82
|
end
|
|
42
83
|
end
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: shopify_api-graphql-request
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.2.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Skye Shaw
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: exe
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-11-
|
|
11
|
+
date: 2026-11-18 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: shopify_api-graphql-tiny
|
|
@@ -16,7 +16,7 @@ dependencies:
|
|
|
16
16
|
requirements:
|
|
17
17
|
- - ">="
|
|
18
18
|
- !ruby/object:Gem::Version
|
|
19
|
-
version: 1.
|
|
19
|
+
version: 1.1.1
|
|
20
20
|
- - "<"
|
|
21
21
|
- !ruby/object:Gem::Version
|
|
22
22
|
version: '2'
|
|
@@ -26,7 +26,7 @@ dependencies:
|
|
|
26
26
|
requirements:
|
|
27
27
|
- - ">="
|
|
28
28
|
- !ruby/object:Gem::Version
|
|
29
|
-
version: 1.
|
|
29
|
+
version: 1.1.1
|
|
30
30
|
- - "<"
|
|
31
31
|
- !ruby/object:Gem::Version
|
|
32
32
|
version: '2'
|
|
@@ -78,6 +78,26 @@ dependencies:
|
|
|
78
78
|
- - ">="
|
|
79
79
|
- !ruby/object:Gem::Version
|
|
80
80
|
version: '3.0'
|
|
81
|
+
- !ruby/object:Gem::Dependency
|
|
82
|
+
name: jwt
|
|
83
|
+
requirement: !ruby/object:Gem::Requirement
|
|
84
|
+
requirements:
|
|
85
|
+
- - ">="
|
|
86
|
+
- !ruby/object:Gem::Version
|
|
87
|
+
version: '2.6'
|
|
88
|
+
- - "<"
|
|
89
|
+
- !ruby/object:Gem::Version
|
|
90
|
+
version: '4'
|
|
91
|
+
type: :runtime
|
|
92
|
+
prerelease: false
|
|
93
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
94
|
+
requirements:
|
|
95
|
+
- - ">="
|
|
96
|
+
- !ruby/object:Gem::Version
|
|
97
|
+
version: '2.6'
|
|
98
|
+
- - "<"
|
|
99
|
+
- !ruby/object:Gem::Version
|
|
100
|
+
version: '4'
|
|
81
101
|
- !ruby/object:Gem::Dependency
|
|
82
102
|
name: bundler
|
|
83
103
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -162,9 +182,12 @@ files:
|
|
|
162
182
|
- README.md
|
|
163
183
|
- Rakefile
|
|
164
184
|
- lib/shopify_api/graphql/request.rb
|
|
185
|
+
- lib/shopify_api/graphql/request/oauth.rb
|
|
165
186
|
- lib/shopify_api/graphql/request/oauth/access_token.rb
|
|
166
187
|
- lib/shopify_api/graphql/request/oauth/access_token_migrator.rb
|
|
188
|
+
- lib/shopify_api/graphql/request/oauth/client_assertion.rb
|
|
167
189
|
- lib/shopify_api/graphql/request/railtie.rb
|
|
190
|
+
- lib/shopify_api/graphql/request/shop.rb
|
|
168
191
|
- lib/shopify_api/graphql/request/tasks.rb
|
|
169
192
|
- lib/shopify_api/graphql/request/version.rb
|
|
170
193
|
- lib/tasks/shopify.rake
|
|
@@ -194,7 +217,6 @@ requirements: []
|
|
|
194
217
|
rubygems_version: 3.5.16
|
|
195
218
|
signing_key:
|
|
196
219
|
specification_version: 4
|
|
197
|
-
summary:
|
|
198
|
-
|
|
199
|
-
error handling, and more!
|
|
220
|
+
summary: Simplify GraphQL queries and mutations for the Shopify Admin API. Comes with
|
|
221
|
+
built-in OAuth token refresh, retry, pagination, error handling, and more!
|
|
200
222
|
test_files: []
|