From 4b093a13faabb027656b8f67871c428ff4bc7bea Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 20:54:45 -0400 Subject: [PATCH 1/5] Renew app credentials and report missing Shopify scopes --- README.md | 20 ++++- src/Http/Controllers/ActionsController.php | 29 +++++-- src/Http/Controllers/PagesController.php | 3 +- src/Shopify/AccessTokens.php | 74 +++++++++++++++++ src/Shopify/ClientFactory.php | 11 +-- src/Shopify/HttpShopifyClient.php | 1 + src/Shopify/Queries.php | 1 + src/Shopify/ShopifyClient.php | 2 +- src/Shopify/ShopifyConnectionTester.php | 18 ++++ src/Shopify/SyncPolicy.php | 5 ++ src/ShopifyPlugin.php | 2 + tests/Fakes/FakeShopifyClient.php | 2 +- tests/Feature/ClientCredentialsTest.php | 97 ++++++++++++++++++++++ tests/Feature/HttpClientTest.php | 2 +- ui/src/components/ConnectionForm.vue | 19 ++++- ui/src/locales/en.json | 9 +- ui/src/pages/Overview.vue | 2 +- 17 files changed, 272 insertions(+), 25 deletions(-) create mode 100644 src/Shopify/AccessTokens.php create mode 100644 tests/Feature/ClientCredentialsTest.php diff --git a/README.md b/README.md index ff1aea7..518da15 100644 --- a/README.md +++ b/README.md @@ -60,7 +60,7 @@ The plugin needs the Inventoros **queue worker** and **scheduler** running (`sho ## Set up a store -In short: create a custom app in the Shopify admin with the scopes `read_products`, `write_products`, `read_inventory`, `write_inventory`, `read_locations` and `read_orders`, install it, then paste its Admin API access token and API secret key under **Shopify > Connect a store**. Map locations to warehouses, run a full sync and confirm the SKU suggestions. +Install a Shopify app with the scopes `read_products`, `write_products`, `read_inventory`, `write_inventory`, `read_locations` and `read_orders`, then connect under **Shopify > Connect a store** using client credentials for an app and store in your own Shopify organization, or an existing Admin API access token and API secret key. Map locations to warehouses, run a full sync and confirm the SKU suggestions. The step-by-step guide, with what each status means: **[docs/setup.md](docs/setup.md)**. How orders, stock, products, webhooks and retries behave: **[docs/sync.md](docs/sync.md)**. @@ -143,3 +143,21 @@ queue retry policy. Mutations keep their existing idempotency and queue retries. Query shapes are bounded below Shopify's default 1,000-point single-query limit. Shopify can assign field costs, so response throttle metadata remains authoritative. + +### Client credentials and missing scopes + +Choose **App client credentials** for apps and stores in the same Shopify +organization. Enter the app client ID and API secret key (its client secret). +The server exchanges these for an expiring token, keeps it encrypted alongside +its expiry, and renews it two minutes before expiration when a client is built. +A connection-row lock prevents concurrent workers from minting duplicate tokens. +Manual tokens remain supported; they are never replaced automatically. + +Connection tests name missing scopes for the enabled sync directions. Updating +app permissions may require reinstalling/reauthorizing the app before testing +again. Secrets and client IDs are write-only and excluded from validation-session +old input. Failed token exchanges report sanitized errors without provider bodies. +No OAuth redirect/authorization-code flow is provided by this option. + +See [Shopify client credentials](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant) +and [token lifetimes](https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens). diff --git a/src/Http/Controllers/ActionsController.php b/src/Http/Controllers/ActionsController.php index 93b196f..ee3a3f9 100644 --- a/src/Http/Controllers/ActionsController.php +++ b/src/Http/Controllers/ActionsController.php @@ -4,11 +4,13 @@ namespace Inventoros\Plugins\Shopify\Http\Controllers; +use App\Models\User; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Controller; use Illuminate\Validation\Rule; use Illuminate\Validation\ValidationException; +use InvalidArgumentException; use Inventoros\Plugins\Shopify\Jobs\ImportOrder; use Inventoros\Plugins\Shopify\Jobs\PushInventory; use Inventoros\Plugins\Shopify\Jobs\RunSync; @@ -29,7 +31,7 @@ use Inventoros\Plugins\Shopify\Sync\InventoryPush; use Inventoros\Plugins\Shopify\Sync\Locations; use Inventoros\Plugins\Shopify\Sync\OrderImporter; -use InvalidArgumentException; +use Inventoros\Plugins\Shopify\Sync\SkuMatcher; /** * Every write the pages make, under /p/shopify/actions (web group: session, @@ -55,7 +57,7 @@ public function storeConnection(Request $request): RedirectResponse 'acting_user_id' => $user->id, 'name' => $data['name'], 'shop_domain' => $data['shop_domain'], - 'credentials' => ['access_token' => $data['access_token'], 'webhook_secret' => $data['webhook_secret']], + 'credentials' => array_filter(['access_token' => $data['access_token'] ?? null, 'webhook_secret' => $data['webhook_secret'], 'client_id' => $data['client_id'] ?? null]), 'status' => Connection::PENDING, 'settings' => SyncPolicy::sanitize($data + ['orders_since' => $data['orders_since'] ?? now()->toDateString()]), ]); @@ -74,13 +76,23 @@ public function updateConnection(Request $request, int $connection): RedirectRes $credentials = $record->credentials ?? []; $retest = false; - foreach (['access_token', 'webhook_secret'] as $key) { + foreach (['access_token', 'webhook_secret', 'client_id'] as $key) { if (($data[$key] ?? '') !== '') { $credentials[$key] = $data[$key]; $retest = true; } } + if ($data['auth_mode'] !== $record->setting('auth_mode', 'token')) { + $retest = true; + } + if ($data['auth_mode'] === 'client_credentials' && $retest) { + unset($credentials['access_token'], $credentials['token_expires_at']); + } + if ($data['auth_mode'] === 'token') { + unset($credentials['client_id'], $credentials['token_expires_at']); + } + $record->forceFill([ 'name' => $data['name'], 'acting_user_id' => $user->id, @@ -221,7 +233,7 @@ public function linkMapping(Request $request, int $mapping): RedirectResponse } $data = $request->validate(['sku' => ['required', 'string', 'max:191']]); - $candidates = \Inventoros\Plugins\Shopify\Sync\SkuMatcher::candidates($organizationId, $data['sku']); + $candidates = SkuMatcher::candidates($organizationId, $data['sku']); if (count($candidates) !== 1) { throw ValidationException::withMessages(['sku' => count($candidates) === 0 @@ -369,12 +381,17 @@ private function validateConnection(Request $request, ?Connection $existing): ar $request->merge(['shop_domain' => ShopDomain::normalize((string) $request->input('shop_domain', ''))]); } + $request->merge(['auth_mode' => $request->input('auth_mode', $existing?->setting('auth_mode', 'token') ?? 'token')]); + $clientMode = $request->input('auth_mode') === 'client_credentials'; $secret = $existing === null ? 'required' : 'nullable'; + $tokenRequired = ! $clientMode && ($existing === null || $existing->setting('auth_mode', 'token') !== 'token'); $data = $request->validate([ 'name' => ['required', 'string', 'max:120'], 'shop_domain' => $existing === null ? ['required', 'string', 'max:191'] : ['exclude'], - 'access_token' => [$secret, 'string', 'max:255'], + 'auth_mode' => ['required', Rule::in(['token', 'client_credentials'])], + 'client_id' => [$clientMode && ! $existing?->hasCredential('client_id') ? 'required' : 'nullable', 'string', 'max:255'], + 'access_token' => [$tokenRequired ? 'required' : 'nullable', 'string', 'max:255'], 'webhook_secret' => [$secret, 'string', 'max:255'], 'stock_source' => ['required', Rule::in(SyncPolicy::STOCK_SOURCES)], 'product_source' => ['required', Rule::in(SyncPolicy::PRODUCT_SOURCES)], @@ -390,7 +407,7 @@ private function validateConnection(Request $request, ?Connection $existing): ar return $data; } - private function authorizeManage(Request $request): \App\Models\User + private function authorizeManage(Request $request): User { $user = $request->user(); diff --git a/src/Http/Controllers/PagesController.php b/src/Http/Controllers/PagesController.php index d1e8ca6..a424696 100644 --- a/src/Http/Controllers/PagesController.php +++ b/src/Http/Controllers/PagesController.php @@ -18,8 +18,8 @@ use Inventoros\Plugins\Shopify\Kit\Models\SyncLog; use Inventoros\Plugins\Shopify\Kit\Models\SyncRun; use Inventoros\Plugins\Shopify\Shopify\ShopifyClient; -use Inventoros\Plugins\Shopify\ShopifyPlugin; use Inventoros\Plugins\Shopify\Shopify\SyncPolicy; +use Inventoros\Plugins\Shopify\ShopifyPlugin; use Inventoros\Plugins\Shopify\Support\Core; use Inventoros\Plugins\Shopify\Support\Permissions; use Inventoros\Plugins\Shopify\Sync\Catalog; @@ -202,6 +202,7 @@ public static function connection(Connection $connection): array 'currency' => ($connection->remote ?? [])['currency'] ?? null, 'webhooks_registered_at' => ($connection->remote ?? [])['webhooks_registered_at'] ?? null, 'has_access_token' => $connection->hasCredential('access_token'), + 'has_client_id' => $connection->hasCredential('client_id'), 'has_webhook_secret' => $connection->hasCredential('webhook_secret'), 'last_tested_at' => $connection->last_tested_at?->toIso8601String(), 'webhook_url' => RegisterWebhooks::callbackUrl($connection), diff --git a/src/Shopify/AccessTokens.php b/src/Shopify/AccessTokens.php new file mode 100644 index 0000000..6888ebc --- /dev/null +++ b/src/Shopify/AccessTokens.php @@ -0,0 +1,74 @@ +shop_domain)) { + throw new PermanentError('The shop domain is not a myshopify.com address.'); + } + if ($connection->setting('auth_mode', 'token') !== 'client_credentials') { + return $connection->credential('access_token') + ?? throw new PermanentError('This connection has no access token. Add one in the connection settings.', authentication: true); + } + + $token = DB::transaction(function () use ($connection) { + $locked = Connection::forOrganization($connection->organization_id)->whereKey($connection->id)->lockForUpdate()->firstOrFail(); + $credentials = $locked->credentials ?? []; + $expires = $credentials['token_expires_at'] ?? null; + if (is_string($expires) && $locked->hasCredential('access_token') && Carbon::parse($expires)->gt(now()->addMinutes(2))) { + return $locked->credential('access_token'); + } + if (! $locked->hasCredential('client_id') || ! $locked->hasCredential('webhook_secret')) { + throw new PermanentError('Add the app client ID and API secret key for client-credentials authentication.', authentication: true); + } + try { + $response = Http::asForm()->acceptJson()->timeout(30)->connectTimeout(10) + ->withOptions(['allow_redirects' => false]) + ->post('https://'.$locked->shop_domain.'/admin/oauth/access_token', [ + 'grant_type' => 'client_credentials', 'client_id' => $locked->credential('client_id'), + 'client_secret' => $locked->credential('webhook_secret'), + ]); + } catch (ConnectionException) { + throw new TransientError('Could not reach Shopify to renew the access token.'); + } + if ($response->status() === 429) { + throw new RateLimited('Shopify limited token requests.', RetryAfter::seconds($response->header('Retry-After'), 5)); + } + if ($response->serverError()) { + throw new TransientError('Shopify could not renew the access token. Retry later.'); + } + if (! $response->successful()) { + throw new PermanentError('Shopify refused the app credentials. Check the client ID/secret, app installation and that the app and store belong to the same Shopify organization.', authentication: true); + } + $body = $response->json(); + if (! is_array($body) || ! is_string($body['access_token'] ?? null) || $body['access_token'] === '' + || ! is_numeric($body['expires_in'] ?? null) || (int) $body['expires_in'] <= 120) { + throw new TransientError('Shopify returned an invalid token response. Retry the connection test.'); + } + $locked->forceFill(['credentials' => array_replace($credentials, [ + 'access_token' => $body['access_token'], 'token_expires_at' => now()->addSeconds((int) $body['expires_in'])->toIso8601String(), + ])])->save(); + + return $body['access_token']; + }); + $connection->refresh(); // Error/log scrubbing sees the newly minted secret. + + return $token; + } +} diff --git a/src/Shopify/ClientFactory.php b/src/Shopify/ClientFactory.php index 85aea11..ba2f6de 100644 --- a/src/Shopify/ClientFactory.php +++ b/src/Shopify/ClientFactory.php @@ -4,7 +4,6 @@ namespace Inventoros\Plugins\Shopify\Shopify; -use Inventoros\Plugins\Shopify\Kit\Exceptions\PermanentError; use Inventoros\Plugins\Shopify\Kit\Models\Connection; use Inventoros\Plugins\Shopify\Kit\Support\CostBudget; @@ -16,15 +15,7 @@ class ClientFactory { public function make(Connection $connection): ShopifyClient { - $token = $connection->credential('access_token'); - - if ($token === null) { - throw new PermanentError('This connection has no access token. Add one in the connection settings.', authentication: true); - } - - if (! ShopDomain::valid($connection->shop_domain)) { - throw new PermanentError('The shop domain is not a myshopify.com address.'); - } + $token = app(AccessTokens::class)->token($connection); return new HttpShopifyClient($connection->shop_domain, $token, CostBudget::for($connection->id)); } diff --git a/src/Shopify/HttpShopifyClient.php b/src/Shopify/HttpShopifyClient.php index 03cef4a..b57fd07 100644 --- a/src/Shopify/HttpShopifyClient.php +++ b/src/Shopify/HttpShopifyClient.php @@ -52,6 +52,7 @@ public function shop(): array 'domain' => (string) ($shop['myshopifyDomain'] ?? $this->shopDomain), 'currency' => (string) ($shop['currencyCode'] ?? ''), 'plan' => $shop['plan']['displayName'] ?? null, + 'scopes' => array_column($data['currentAppInstallation']['accessScopes'] ?? [], 'handle'), ]; } diff --git a/src/Shopify/Queries.php b/src/Shopify/Queries.php index 05037dc..d58dc77 100644 --- a/src/Shopify/Queries.php +++ b/src/Shopify/Queries.php @@ -15,6 +15,7 @@ final class Queries public const SHOP = <<<'GQL' query Shop { shop { id name myshopifyDomain currencyCode plan { displayName } } + currentAppInstallation { accessScopes { handle } } } GQL; diff --git a/src/Shopify/ShopifyClient.php b/src/Shopify/ShopifyClient.php index 3993fd0..bcd1f79 100644 --- a/src/Shopify/ShopifyClient.php +++ b/src/Shopify/ShopifyClient.php @@ -31,7 +31,7 @@ interface ShopifyClient public const API_VERSION = '2026-07'; /** - * @return array{id: string, name: string, domain: string, currency: string, plan: string|null} + * @return array{id: string, name: string, domain: string, currency: string, plan: string|null, scopes: array} */ public function shop(): array; diff --git a/src/Shopify/ShopifyConnectionTester.php b/src/Shopify/ShopifyConnectionTester.php index 12f7127..7193d74 100644 --- a/src/Shopify/ShopifyConnectionTester.php +++ b/src/Shopify/ShopifyConnectionTester.php @@ -26,6 +26,24 @@ public function test(Connection $connection): TestResult return TestResult::failed($error->getMessage()); } + $policy = SyncPolicy::for($connection); + $required = ['read_products', 'read_inventory', 'read_locations']; + if ($policy->pushesStock()) { + $required[] = 'write_inventory'; + } + if ($policy->pushesProducts()) { + $required[] = 'write_products'; + } + if ($policy->importsOrders()) { + $required[] = 'read_orders'; + } + $granted = $shop['scopes'] ?? []; + $missing = array_values(array_filter($required, fn ($scope) => ! in_array($scope, $granted, true) + && ! (str_starts_with($scope, 'read_') && in_array('write_'.substr($scope, 5), $granted, true)))); + if ($missing !== []) { + return TestResult::failed('Missing Shopify access scopes: '.implode(', ', $missing).'. Update the app permissions and reinstall or reauthorize it, then test again.'); + } + if (! $connection->hasCredential('webhook_secret')) { return TestResult::failed('The access token works, but the API secret key is missing: webhooks cannot be verified without it.'); } diff --git a/src/Shopify/SyncPolicy.php b/src/Shopify/SyncPolicy.php index d0d32fd..a5cecf9 100644 --- a/src/Shopify/SyncPolicy.php +++ b/src/Shopify/SyncPolicy.php @@ -29,6 +29,7 @@ final class SyncPolicy public const PRODUCT_SOURCES = ['shopify', 'inventoros']; public const DEFAULTS = [ + 'auth_mode' => 'token', 'stock_source' => 'inventoros', 'product_source' => 'shopify', 'import_orders' => true, @@ -52,6 +53,10 @@ public static function sanitize(array $input, array $current = []): array { $settings = array_merge(self::DEFAULTS, array_intersect_key($current, self::DEFAULTS)); + if (in_array($input['auth_mode'] ?? null, ['token', 'client_credentials'], true)) { + $settings['auth_mode'] = $input['auth_mode']; + } + if (in_array($input['stock_source'] ?? null, self::STOCK_SOURCES, true)) { $settings['stock_source'] = $input['stock_source']; } diff --git a/src/ShopifyPlugin.php b/src/ShopifyPlugin.php index 93c096a..b22beb2 100644 --- a/src/ShopifyPlugin.php +++ b/src/ShopifyPlugin.php @@ -6,6 +6,7 @@ use Illuminate\Console\Application as Artisan; use Illuminate\Console\Scheduling\Schedule; +use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Support\Facades\Route; use Inventoros\Plugins\Shopify\Console\PruneCommand; use Inventoros\Plugins\Shopify\Console\SyncCommand; @@ -56,6 +57,7 @@ public function __construct( public function register(): void { + app(ExceptionHandler::class)->dontFlash(['access_token', 'webhook_secret', 'client_id']); $this->registerServices(); $this->registerTranslations(); $this->registerPermissions(); diff --git a/tests/Fakes/FakeShopifyClient.php b/tests/Fakes/FakeShopifyClient.php index f4abe81..7c33e03 100644 --- a/tests/Fakes/FakeShopifyClient.php +++ b/tests/Fakes/FakeShopifyClient.php @@ -46,7 +46,7 @@ final class FakeShopifyClient implements ShopifyClient public function __construct() { $shop = self::fixture('shop')['data']['shop']; - $this->shop = ['id' => '77001', 'name' => $shop['name'], 'domain' => $shop['myshopifyDomain'], 'currency' => $shop['currencyCode'], 'plan' => $shop['plan']['displayName']]; + $this->shop = ['id' => '77001', 'name' => $shop['name'], 'domain' => $shop['myshopifyDomain'], 'currency' => $shop['currencyCode'], 'plan' => $shop['plan']['displayName'], 'scopes' => ['read_products', 'write_products', 'read_inventory', 'write_inventory', 'read_locations', 'read_orders']]; foreach (self::fixture('locations')['data']['locations']['nodes'] as $node) { $this->locations[] = ['id' => substr($node['id'], strrpos($node['id'], '/') + 1), 'name' => $node['name'], 'active' => $node['isActive']]; diff --git a/tests/Feature/ClientCredentialsTest.php b/tests/Feature/ClientCredentialsTest.php new file mode 100644 index 0000000..3671cdd --- /dev/null +++ b/tests/Feature/ClientCredentialsTest.php @@ -0,0 +1,97 @@ +setUpWorld(); + } + + public function test_tokens_are_encrypted_reused_and_renewed_before_expiry(): void + { + $this->store->forceFill(['settings' => ['auth_mode' => 'client_credentials'], + 'credentials' => ['client_id' => 'app-client-123', 'webhook_secret' => self::SECRET]])->save(); + Http::fake(['*' => Http::sequence() + ->push(['access_token' => 'minted-token-one', 'expires_in' => 86399]) + ->push(['access_token' => 'minted-token-two', 'expires_in' => 86399])]); + $tokens = app(AccessTokens::class); + $this->assertSame('minted-token-one', $tokens->token($this->store)); + $this->assertSame('minted-token-one', $tokens->token($this->store->fresh())); + Http::assertSentCount(1); + $raw = DB::table('plg_shopify_connections')->where('id', $this->store->id)->value('credentials'); + $this->assertStringNotContainsString('minted-token-one', $raw); + $this->assertStringNotContainsString(self::SECRET, $raw); + $this->travel(24)->hours(); + $this->assertSame('minted-token-two', $tokens->token($this->store->fresh())); + Http::assertSentCount(2); + Http::assertSent(fn ($request) => $request->url() === 'https://acme-store.myshopify.com/admin/oauth/access_token' + && $request['grant_type'] === 'client_credentials' && $request['client_secret'] === self::SECRET); + } + + public function test_manual_tokens_make_no_exchange_and_bad_app_credentials_are_sanitized(): void + { + $this->assertSame(self::TOKEN, app(AccessTokens::class)->token($this->store)); + Http::assertNothingSent(); + $this->store->forceFill(['settings' => ['auth_mode' => 'client_credentials'], + 'credentials' => ['client_id' => 'app-id', 'webhook_secret' => self::SECRET]])->save(); + Http::fake(['*' => Http::response(['error_description' => self::SECRET], 400)]); + try { + app(AccessTokens::class)->token($this->store); + $this->fail('Expected credential rejection.'); + } catch (PermanentError $error) { + $this->assertStringContainsString('same Shopify organization', $error->getMessage()); + $this->assertStringNotContainsString(self::SECRET, $error->getMessage()); + } + } + + public function test_client_mode_saves_without_a_manual_token_and_keeps_blank_secrets(): void + { + Queue::fake(); + $this->actingAs($this->admin)->post(route('plg.shopify.actions.connections.update', $this->store->id), [ + 'name' => 'Own app', 'auth_mode' => 'client_credentials', 'client_id' => 'app-123', + 'webhook_secret' => '', 'stock_source' => 'inventoros', 'product_source' => 'shopify', 'import_orders' => true, + ])->assertRedirect()->assertSessionHasNoErrors(); + $this->assertNull($this->store->fresh()->credential('access_token')); + $this->assertSame('app-123', $this->store->fresh()->credential('client_id')); + $this->assertSame(self::SECRET, $this->store->fresh()->credential('webhook_secret')); + $this->assertSame('client_credentials', $this->store->fresh()->setting('auth_mode')); + } + + public function test_validation_never_flashes_credentials_or_client_ids(): void + { + $this->actingAs($this->admin)->post(route('plg.shopify.actions.connections.store'), [ + 'name' => '', 'access_token' => self::TOKEN, 'webhook_secret' => self::SECRET, 'client_id' => 'private-client-id', + ])->assertRedirect()->assertSessionHasErrors('name'); + foreach (['access_token', 'webhook_secret', 'client_id'] as $field) { + $this->assertNull(session()->getOldInput($field)); + } + } + + public function test_connection_tests_name_missing_scopes_for_enabled_directions(): void + { + $this->shopify->shop['scopes'] = ['read_products', 'read_inventory', 'read_locations']; + $result = app(ShopifyConnectionTester::class)->test($this->store); + $this->assertFalse($result->ok); + $this->assertStringContainsString('write_inventory', $result->message); + $this->assertStringContainsString('read_orders', $result->message); + $this->assertStringNotContainsString('write_products', $result->message); + $this->store->forceFill(['settings' => ['stock_source' => 'shopify', 'product_source' => 'shopify', 'import_orders' => false]])->save(); + $this->assertTrue(app(ShopifyConnectionTester::class)->test($this->store)->ok); + } +} diff --git a/tests/Feature/HttpClientTest.php b/tests/Feature/HttpClientTest.php index eddaa5e..d640a63 100644 --- a/tests/Feature/HttpClientTest.php +++ b/tests/Feature/HttpClientTest.php @@ -45,7 +45,7 @@ public function test_it_sends_the_token_header_to_the_pinned_version_and_reads_t $shop = $this->client()->shop(); - $this->assertSame(['id' => '77001', 'name' => 'Acme Store', 'domain' => 'acme-store.myshopify.com', 'currency' => 'USD', 'plan' => 'Basic'], $shop); + $this->assertSame(['id' => '77001', 'name' => 'Acme Store', 'domain' => 'acme-store.myshopify.com', 'currency' => 'USD', 'plan' => 'Basic', 'scopes' => []], $shop); Http::assertSent(fn (Request $request) => $request->url() === self::ENDPOINT && $request->hasHeader('X-Shopify-Access-Token', self::TOKEN) && ! $request->hasHeader('Authorization')); diff --git a/ui/src/components/ConnectionForm.vue b/ui/src/components/ConnectionForm.vue index f7aa2e1..66a5c6a 100644 --- a/ui/src/components/ConnectionForm.vue +++ b/ui/src/components/ConnectionForm.vue @@ -22,6 +22,8 @@ const prefix = editing ? `shopify-conn-${props.connection.id}` : 'shopify-new'; const form = useForm({ name: props.connection?.name ?? '', shop_domain: props.connection?.shop_domain ?? '', + auth_mode: settings.auth_mode ?? 'token', + client_id: '', access_token: '', webhook_secret: '', stock_source: settings.stock_source ?? 'inventoros', @@ -35,7 +37,7 @@ const submit = () => { form.post(props.action, { preserveScroll: true, onSuccess: () => { - form.reset('access_token', 'webhook_secret'); + form.reset('access_token', 'webhook_secret', 'client_id'); emit('done'); }, }); @@ -68,6 +70,21 @@ const submit = () => {
+ + +

{{ t('form.authHint') }}

+

{{ form.errors.auth_mode }}

+
+
+ + +

{{ t('form.keepSecret') }}

+

{{ form.errors.client_id }}

+
+

{{ editing ? t('form.keepSecret') : t('form.accessTokenHint') }}

diff --git a/ui/src/locales/en.json b/ui/src/locales/en.json index c13b871..3238aa4 100644 --- a/ui/src/locales/en.json +++ b/ui/src/locales/en.json @@ -12,10 +12,15 @@ "emptyReadOnly": "No store is connected yet. Ask someone who can manage Shopify to connect one.", "connect": "Connect a store", "connectAnother": "Connect another store", - "setupHint": "Create a custom app in your Shopify admin, give it the scopes listed in the setup guide, install it, then paste its Admin API access token and API secret key here.", + "setupHint": "Install your Shopify app with the scopes in the setup guide. Connect using app client credentials for stores in your own Shopify organization, or an existing Admin API token.", "apiVersion": "Admin API {version}" }, "form": { + "authMode": "Authentication", + "authToken": "Saved Admin API token", + "authClient": "App client credentials (automatic renewal)", + "authHint": "Client credentials work when the app and store belong to the same Shopify organization. The API secret key is also the app client secret. Tokens renew automatically before expiry.", + "clientId": "App client ID", "name": "Name", "namePlaceholder": "Main store", "shopDomain": "Shop domain", @@ -50,7 +55,7 @@ "webhooksRegistered": "Webhooks registered", "webhooksMissing": "Webhooks not registered yet: the scheduled sync still runs every 15 minutes.", "credentials": "Credentials", - "credentialsSet": "Token and secret saved", + "credentialsSet": "Credentials saved", "credentialsMissing": "Credentials missing", "sync": "Sync", "initialSync": "Run full sync", diff --git a/ui/src/pages/Overview.vue b/ui/src/pages/Overview.vue index c5b46f8..51f781d 100644 --- a/ui/src/pages/Overview.vue +++ b/ui/src/pages/Overview.vue @@ -120,7 +120,7 @@ const disconnect = (connection) => {
{{ t('connection.credentials') }} - {{ connection.has_access_token && connection.has_webhook_secret ? t('connection.credentialsSet') : t('connection.credentialsMissing') }} + {{ (connection.settings.auth_mode === 'client_credentials' ? connection.has_client_id : connection.has_access_token) && connection.has_webhook_secret ? t('connection.credentialsSet') : t('connection.credentialsMissing') }}
From a2c023fd06b2f0b89f2313ecfd4dd59dfdc33fe0 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:21:16 -0400 Subject: [PATCH 2/5] Version the authentication settings bundle --- CHANGELOG.md | 7 +++++++ plugin.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 30e3275..b765a3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ All notable changes to this plugin are documented here. The format follows [Keep ## [Unreleased] +## [1.1.0] - Unreleased + +### Added + +- Optional client-credentials authentication for apps and stores in the same Shopify organization, with encrypted expiring tokens and automatic renewal. +- Connection tests identify missing scopes for the enabled sync directions. Validation errors never flash credentials or client IDs. + ## [1.0.3] - Unreleased ### Fixed diff --git a/plugin.json b/plugin.json index eb80763..e3d9939 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "Shopify", "description": "Connect Inventoros with Shopify for asynchronous two-way product, inventory and order sync, with webhooks, retries, mappings and sync health checks.", - "version": "1.0.3", + "version": "1.1.0", "author": "Inventoros", "author_url": "https://inventoros.com", "license": "AGPL-3.0-or-later", From 3e3d1715ef3f093c320c7116e8a93cfa45dfa900 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:27:11 -0400 Subject: [PATCH 3/5] Refresh tokens during long-running syncs --- README.md | 2 +- src/Shopify/AccessTokens.php | 5 +++++ src/Shopify/ClientFactory.php | 3 ++- src/Shopify/HttpShopifyClient.php | 7 ++++++- tests/Feature/ClientCredentialsTest.php | 21 +++++++++++++++++++++ 5 files changed, 35 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 518da15..f7683cb 100644 --- a/README.md +++ b/README.md @@ -149,7 +149,7 @@ Shopify can assign field costs, so response throttle metadata remains authoritat Choose **App client credentials** for apps and stores in the same Shopify organization. Enter the app client ID and API secret key (its client secret). The server exchanges these for an expiring token, keeps it encrypted alongside -its expiry, and renews it two minutes before expiration when a client is built. +its expiry, and renews it two minutes before expiration before each API request, including later pages of an already-running client. A connection-row lock prevents concurrent workers from minting duplicate tokens. Manual tokens remain supported; they are never replaced automatically. diff --git a/src/Shopify/AccessTokens.php b/src/Shopify/AccessTokens.php index 6888ebc..3cf38ef 100644 --- a/src/Shopify/AccessTokens.php +++ b/src/Shopify/AccessTokens.php @@ -19,6 +19,7 @@ final class AccessTokens { public function token(Connection $connection): string { + $connection->refresh(); if (! ShopDomain::valid($connection->shop_domain)) { throw new PermanentError('The shop domain is not a myshopify.com address.'); } @@ -29,6 +30,10 @@ public function token(Connection $connection): string $token = DB::transaction(function () use ($connection) { $locked = Connection::forOrganization($connection->organization_id)->whereKey($connection->id)->lockForUpdate()->firstOrFail(); + if ($locked->setting('auth_mode', 'token') !== 'client_credentials') { + return $locked->credential('access_token') + ?? throw new PermanentError('The connection has no saved access token.', authentication: true); + } $credentials = $locked->credentials ?? []; $expires = $credentials['token_expires_at'] ?? null; if (is_string($expires) && $locked->hasCredential('access_token') && Carbon::parse($expires)->gt(now()->addMinutes(2))) { diff --git a/src/Shopify/ClientFactory.php b/src/Shopify/ClientFactory.php index ba2f6de..23c01ff 100644 --- a/src/Shopify/ClientFactory.php +++ b/src/Shopify/ClientFactory.php @@ -17,6 +17,7 @@ public function make(Connection $connection): ShopifyClient { $token = app(AccessTokens::class)->token($connection); - return new HttpShopifyClient($connection->shop_domain, $token, CostBudget::for($connection->id)); + return new HttpShopifyClient($connection->shop_domain, $token, CostBudget::for($connection->id), + tokenResolver: fn () => app(AccessTokens::class)->token($connection)); } } diff --git a/src/Shopify/HttpShopifyClient.php b/src/Shopify/HttpShopifyClient.php index b57fd07..ee5bd9b 100644 --- a/src/Shopify/HttpShopifyClient.php +++ b/src/Shopify/HttpShopifyClient.php @@ -36,9 +36,10 @@ final class HttpShopifyClient implements ShopifyClient public function __construct( private readonly string $shopDomain, - private readonly string $accessToken, + private string $accessToken, private readonly CostBudget $budget, private readonly string $apiVersion = self::API_VERSION, + private readonly ?\Closure $tokenResolver = null, ) {} public function shop(): array @@ -223,6 +224,9 @@ public function subscribeWebhook(string $topic, string $callbackUrl): void */ private function query(string $query, array $variables, int $expectedCost): array { + if ($this->tokenResolver !== null) { + $this->accessToken = ($this->tokenResolver)(); + } $this->budget->reserve($expectedCost); try { @@ -232,6 +236,7 @@ private function query(string $query, array $variables, int $expectedCost): arra ]) ->timeout(30) ->connectTimeout(10) + ->withOptions(['allow_redirects' => false]) ->post($this->endpoint(), ['query' => $query, 'variables' => (object) array_filter($variables, fn ($v) => $v !== null)]); } catch (ConnectionException $error) { throw new TransientError('Could not reach Shopify: '.$this->clean($error->getMessage())); diff --git a/tests/Feature/ClientCredentialsTest.php b/tests/Feature/ClientCredentialsTest.php index 3671cdd..aee8129 100644 --- a/tests/Feature/ClientCredentialsTest.php +++ b/tests/Feature/ClientCredentialsTest.php @@ -9,8 +9,10 @@ use Illuminate\Support\Facades\Queue; use Inventoros\Plugins\Shopify\Kit\Exceptions\PermanentError; use Inventoros\Plugins\Shopify\Shopify\AccessTokens; +use Inventoros\Plugins\Shopify\Shopify\ClientFactory; use Inventoros\Plugins\Shopify\Shopify\ShopifyConnectionTester; use Inventoros\Plugins\Shopify\Tests\Concerns\ShopifyWorld; +use Inventoros\Plugins\Shopify\Tests\Fakes\FakeShopifyClient; use Inventoros\Plugins\Shopify\Tests\TestCase; final class ClientCredentialsTest extends TestCase @@ -60,6 +62,25 @@ public function test_manual_tokens_make_no_exchange_and_bad_app_credentials_are_ } } + public function test_a_long_running_client_uses_the_renewed_token_on_its_next_page(): void + { + $this->store->forceFill(['settings' => ['auth_mode' => 'client_credentials'], + 'credentials' => ['client_id' => 'app-client-123', 'webhook_secret' => self::SECRET]])->save(); + Http::fake([ + '*/admin/oauth/access_token' => Http::sequence() + ->push(['access_token' => 'token-before-expiry', 'expires_in' => 86399]) + ->push(['access_token' => 'token-after-expiry', 'expires_in' => 86399]), + '*/graphql.json' => Http::response(FakeShopifyClient::fixture('shop')), + ]); + $client = (new ClientFactory)->make($this->store); + $client->shop(); + $this->travel(24)->hours(); + $client->shop(); + $headers = Http::recorded(fn ($request) => str_ends_with($request->url(), 'graphql.json')) + ->map(fn ($pair) => $pair[0]->header('X-Shopify-Access-Token')[0])->all(); + $this->assertSame(['token-before-expiry', 'token-after-expiry'], $headers); + } + public function test_client_mode_saves_without_a_manual_token_and_keeps_blank_secrets(): void { Queue::fake(); From a20e6e7097d5cb1a733a13a60011d1c3ec51e8a2 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:28:45 -0400 Subject: [PATCH 4/5] Compare renewed request headers in request order --- tests/Feature/ClientCredentialsTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Feature/ClientCredentialsTest.php b/tests/Feature/ClientCredentialsTest.php index aee8129..67ad738 100644 --- a/tests/Feature/ClientCredentialsTest.php +++ b/tests/Feature/ClientCredentialsTest.php @@ -77,7 +77,7 @@ public function test_a_long_running_client_uses_the_renewed_token_on_its_next_pa $this->travel(24)->hours(); $client->shop(); $headers = Http::recorded(fn ($request) => str_ends_with($request->url(), 'graphql.json')) - ->map(fn ($pair) => $pair[0]->header('X-Shopify-Access-Token')[0])->all(); + ->map(fn ($pair) => $pair[0]->header('X-Shopify-Access-Token')[0])->values()->all(); $this->assertSame(['token-before-expiry', 'token-after-expiry'], $headers); } From b45d3da1c849f4472495a443c4cea87166824612 Mon Sep 17 00:00:00 2001 From: Matt Gros Date: Thu, 22 Oct 2026 21:41:26 -0400 Subject: [PATCH 5/5] Support console exception handler decorators on activation --- src/ShopifyPlugin.php | 7 ++++- .../ConsoleActivationCompatibilityTest.php | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 tests/Feature/ConsoleActivationCompatibilityTest.php diff --git a/src/ShopifyPlugin.php b/src/ShopifyPlugin.php index b22beb2..5bfe83a 100644 --- a/src/ShopifyPlugin.php +++ b/src/ShopifyPlugin.php @@ -57,7 +57,12 @@ public function __construct( public function register(): void { - app(ExceptionHandler::class)->dontFlash(['access_token', 'webhook_secret', 'client_id']); + $handler = app(ExceptionHandler::class); + // Console renderers can decorate the HTTP handler without exposing + // its validation-input configuration (for example Collision). + if (method_exists($handler, 'dontFlash')) { + $handler->dontFlash(['access_token', 'webhook_secret', 'client_id']); + } $this->registerServices(); $this->registerTranslations(); $this->registerPermissions(); diff --git a/tests/Feature/ConsoleActivationCompatibilityTest.php b/tests/Feature/ConsoleActivationCompatibilityTest.php new file mode 100644 index 0000000..3228424 --- /dev/null +++ b/tests/Feature/ConsoleActivationCompatibilityTest.php @@ -0,0 +1,29 @@ +instance(ExceptionHandler::class, Mockery::mock(ExceptionHandler::class)->shouldIgnoreMissing()); + try { + app(PluginService::class)->activatePlugin('shopify'); + $this->assertTrue((bool) Plugin::where('slug', 'shopify')->value('is_active')); + } finally { + app(PluginService::class)->deactivatePlugin('shopify'); + } + } +}