Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix: approving consent crashed before the merchant reached the client

Damian Legawiec3ecb460cf6fa
diff --git a/packages/admin-sdk/src/types/generated/OauthApplication.ts b/packages/admin-sdk/src/types/generated/OauthApplication.ts
index d6af68d6ea..98dc340931 100644
--- a/packages/admin-sdk/src/types/generated/OauthApplication.ts
+++ b/packages/admin-sdk/src/types/generated/OauthApplication.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 8c2fb32a386af3dcd58e8300c3882d44
+// Typelizer digest 563d9fb82d6fd499c593eb219262f5a3
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -8,6 +8,7 @@ interface OauthApplication {
redirect_uri: string | null;
created_at: string;
updated_at: string;
+ client_id: string;
scopes: Array<string>;
last_used_at: string | null;
authorized_at: string | null;
diff --git a/packages/admin-sdk/src/zod/generated/OauthApplication.ts b/packages/admin-sdk/src/zod/generated/OauthApplication.ts
index 47ac87cc1e..e9c6813195 100644
--- a/packages/admin-sdk/src/zod/generated/OauthApplication.ts
+++ b/packages/admin-sdk/src/zod/generated/OauthApplication.ts
@@ -7,6 +7,7 @@ export const OauthApplicationSchema = z.object({
redirect_uri: z.string().nullable(),
created_at: z.string(),
updated_at: z.string(),
+ client_id: z.string(),
scopes: z.array(z.string()),
last_used_at: z.string().nullable(),
authorized_at: z.string().nullable(),
diff --git a/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx
index 5d170d1425..7ea1bbe0ee 100644
--- a/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx
+++ b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx
@@ -19,7 +19,7 @@ import {
import { useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useCreateApiKey } from '../../hooks/use-api-keys'
-import { useStoreSettings } from '../../hooks/use-store-settings'
+import { useOauthApplications } from '../../hooks/use-oauth'
type McpConnectSheetProps = {
open: boolean
@@ -34,7 +34,7 @@ type McpConnectSheetProps = {
*/
export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {
const { t } = useTranslation()
- const { data: store } = useStoreSettings()
+ const { data: applications } = useOauthApplications()
const createKey = useCreateApiKey()
const { permissions } = usePermissions()
const [minted, setMinted] = useState<ApiKey | null>(null)
@@ -42,7 +42,16 @@ export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {
const [mintError, setMintError] = useState<string | null>(null)
const writableId = useId()
- const endpoint = store ? `${store.api_url}/v3/admin/mcp` : ''
+ // Where this dashboard's own API calls go — either a configured origin or
+ // the page's own, which is what a proxied or multi-hostname deployment
+ // actually answers on. The store record's URL describes the storefront and
+ // is frequently neither.
+ const apiOrigin = import.meta.env.VITE_SPREE_API_URL || window.location.origin
+ const endpoint = `${apiOrigin}/api/v3/admin/mcp`
+ const clientIds = (applications?.data ?? []).map((application) => ({
+ name: application.name,
+ clientId: application.client_id,
+ }))
const token = minted?.plaintext_token ?? 'YOUR_SECRET_KEY'
const canMint = permissions.can('create', Subject.ApiKey)
@@ -189,6 +198,30 @@ export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {
value={endpoint}
/>
</div>
+ {/* A connector that asks for a client id needs this store's own:
+ the id is issued per store, so it cannot be published in
+ documentation. */}
+ {clientIds.length > 0 ? (
+ <div className="flex flex-col gap-1">
+ <p className="text-muted-foreground text-xs">
+ {t('admin.mcp_connect.client_id_help')}
+ </p>
+ {clientIds.map(({ name, clientId }) => (
+ <div key={clientId} className="relative">
+ <pre className="overflow-x-auto rounded-md bg-muted p-3 pr-12 text-xs">
+ <code>
+ {name}: {clientId}
+ </code>
+ </pre>
+ <CopyToClipboardButton
+ aria-label={t('admin.actions.copy')}
+ className="absolute top-1.5 right-2"
+ value={clientId}
+ />
+ </div>
+ ))}
+ </div>
+ ) : null}
</div>
</div>
</SheetContent>
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 3df97dab14..3dd35f7b54 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -4197,7 +4197,8 @@
"revoke_hint": "يمكنك إلغاء ذلك في أي وقت من الإعدادات ← التطبيقات المتصلة.",
"approve": "السماح بالوصول",
"deny": "إلغاء",
- "invalid_request": "طلب الترخيص هذا غير صالح. ابدأ من جديد من التطبيق الذي أرسلك إلى هنا."
+ "invalid_request": "طلب الترخيص هذا غير صالح. ابدأ من جديد من التطبيق الذي أرسلك إلى هنا.",
+ "decision_failed": "تعذّر تسجيل القرار. حاول مرة أخرى."
}
}
},
@@ -6385,7 +6386,8 @@
"allow_writes": "السماح لهذا الوكيل بإجراء تغييرات",
"allow_writes_help": "اتركه مُعطّلاً للوكيل الذي يقرأ فقط. فالمفتاح القادر على التغيير يستطيع أيضًا إلغاء الطلبات وإصدار المبالغ المستردة.",
"mint_failed": "تعذّر إنشاء المفتاح.",
- "consumer_title": "Claude Desktop وclaude.ai وChatGPT"
+ "consumer_title": "Claude Desktop وclaude.ai وChatGPT",
+ "client_id_help": "إذا طلب الموصّل معرّف عميل، فاستخدم المعرّف الخاص بعميلك — فهي تُصدر لكل متجر على حدة."
}
}
}
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 789d70ca5d..6f639af84a 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -4169,7 +4169,8 @@
"revoke_hint": "Sie können dies jederzeit unter Einstellungen → Verbundene Apps widerrufen.",
"approve": "Zugriff erlauben",
"deny": "Abbrechen",
- "invalid_request": "Diese Autorisierungsanfrage ist ungültig. Beginnen Sie erneut in der Anwendung, die Sie hierher geschickt hat."
+ "invalid_request": "Diese Autorisierungsanfrage ist ungültig. Beginnen Sie erneut in der Anwendung, die Sie hierher geschickt hat.",
+ "decision_failed": "Die Entscheidung konnte nicht gespeichert werden. Versuchen Sie es erneut."
}
}
},
@@ -6345,7 +6346,8 @@
"allow_writes": "Diesem Agenten Änderungen erlauben",
"allow_writes_help": "Für einen Agenten, der nur liest, ausgeschaltet lassen. Ein Schlüssel mit Schreibrechten kann auch Bestellungen stornieren und Rückerstattungen auslösen.",
"mint_failed": "Der Schlüssel konnte nicht erstellt werden.",
- "consumer_title": "Claude Desktop, claude.ai und ChatGPT"
+ "consumer_title": "Claude Desktop, claude.ai und ChatGPT",
+ "client_id_help": "Falls der Connector eine Client-ID verlangt, verwenden Sie die für Ihren Client — diese werden pro Shop vergeben."
}
}
}
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index 8be4d298e2..5cdfe555f6 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -4169,7 +4169,8 @@
"revoke_hint": "You can revoke this at any time under Settings → Connected apps.",
"approve": "Allow access",
"deny": "Cancel",
- "invalid_request": "This authorization request is not valid. Start again from the application that sent you here."
+ "invalid_request": "This authorization request is not valid. Start again from the application that sent you here.",
+ "decision_failed": "The decision could not be recorded. Try again."
}
}
},
@@ -6345,7 +6346,8 @@
"allow_writes": "Let this agent make changes",
"allow_writes_help": "Leave off for an agent that only reads. A key that can change things can also cancel orders and issue refunds.",
"mint_failed": "The key could not be created.",
- "consumer_title": "Claude Desktop, claude.ai and ChatGPT"
+ "consumer_title": "Claude Desktop, claude.ai and ChatGPT",
+ "client_id_help": "If the connector asks for a client ID, use the one for your client — these are issued per store."
}
}
}
diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.json
index 84a6f64892..0e259640d5 100644
--- a/packages/dashboard/src/locales/es.json
+++ b/packages/dashboard/src/locales/es.json
@@ -1061,7 +1061,8 @@
"revoke_hint": "Puede revocarlo en cualquier momento en Configuración → Aplicaciones conectadas.",
"approve": "Permitir acceso",
"deny": "Cancelar",
- "invalid_request": "Esta solicitud de autorización no es válida. Vuelva a empezar desde la aplicación que le envió aquí."
+ "invalid_request": "Esta solicitud de autorización no es válida. Vuelva a empezar desde la aplicación que le envió aquí.",
+ "decision_failed": "No se pudo registrar la decisión. Inténtelo de nuevo."
}
}
},
@@ -6345,7 +6346,8 @@
"allow_writes": "Permitir que este agente haga cambios",
"allow_writes_help": "Déjelo desactivado para un agente que solo lee. Una clave que puede cambiar cosas también puede cancelar pedidos y emitir reembolsos.",
"mint_failed": "No se pudo crear la clave.",
- "consumer_title": "Claude Desktop, claude.ai y ChatGPT"
+ "consumer_title": "Claude Desktop, claude.ai y ChatGPT",
+ "client_id_help": "Si el conector pide un ID de cliente, use el de su cliente: se emiten por tienda."
}
}
}
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 9f88cb120c..9decc2fb82 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -4169,7 +4169,8 @@
"revoke_hint": "Vous pouvez révoquer cet accès à tout moment dans Paramètres → Applications connectées.",
"approve": "Autoriser l’accès",
"deny": "Annuler",
- "invalid_request": "Cette demande d’autorisation n’est pas valide. Recommencez depuis l’application qui vous a envoyé ici."
+ "invalid_request": "Cette demande d’autorisation n’est pas valide. Recommencez depuis l’application qui vous a envoyé ici.",
+ "decision_failed": "La décision n’a pas pu être enregistrée. Réessayez."
}
}
},
@@ -6345,7 +6346,8 @@
"allow_writes": "Autoriser cet agent à apporter des modifications",
"allow_writes_help": "Laissez désactivé pour un agent qui ne fait que lire. Une clé qui peut modifier peut aussi annuler des commandes et émettre des remboursements.",
"mint_failed": "La clé n’a pas pu être créée.",
- "consumer_title": "Claude Desktop, claude.ai et ChatGPT"
+ "consumer_title": "Claude Desktop, claude.ai et ChatGPT",
+ "client_id_help": "Si le connecteur demande un identifiant client, utilisez celui de votre client — ils sont émis par boutique."
}
}
}
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 61fcda05cb..44411a960d 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -4223,7 +4223,8 @@
"revoke_hint": "Możesz odebrać dostęp w dowolnym momencie w Ustawienia → Połączone aplikacje.",
"approve": "Zezwól na dostęp",
"deny": "Anuluj",
- "invalid_request": "To żądanie autoryzacji jest nieprawidłowe. Zacznij ponownie z aplikacji, która Cię tu skierowała."
+ "invalid_request": "To żądanie autoryzacji jest nieprawidłowe. Zacznij ponownie z aplikacji, która Cię tu skierowała.",
+ "decision_failed": "Nie udało się zapisać decyzji. Spróbuj ponownie."
}
}
},
@@ -6413,7 +6414,8 @@
"allow_writes": "Pozwól temu agentowi wprowadzać zmiany",
"allow_writes_help": "Zostaw wyłączone dla agenta, który tylko czyta. Klucz, który może zmieniać dane, może też anulować zamówienia i wystawiać zwroty.",
"mint_failed": "Nie udało się utworzyć klucza.",
- "consumer_title": "Claude Desktop, claude.ai i ChatGPT"
+ "consumer_title": "Claude Desktop, claude.ai i ChatGPT",
+ "client_id_help": "Jeśli konektor poprosi o identyfikator klienta, użyj tego dla swojego klienta — są wydawane osobno dla każdego sklepu."
}
}
}
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 43c6d73eec..70b8f12a20 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -4159,7 +4159,8 @@
"revoke_hint": "您可以随时在“设置 → 已连接的应用”中撤销。",
"approve": "允许访问",
"deny": "取消",
- "invalid_request": "此授权请求无效。请从引导您来此的应用重新开始。"
+ "invalid_request": "此授权请求无效。请从引导您来此的应用重新开始。",
+ "decision_failed": "无法记录此决定,请重试。"
}
}
},
@@ -6332,7 +6333,8 @@
"allow_writes": "允许此代理进行更改",
"allow_writes_help": "仅读取的代理请保持关闭。可更改数据的密钥同样可以取消订单和发起退款。",
"mint_failed": "无法创建密钥。",
- "consumer_title": "Claude Desktop、claude.ai 和 ChatGPT"
+ "consumer_title": "Claude Desktop、claude.ai 和 ChatGPT",
+ "client_id_help": "如果连接器需要客户端 ID,请使用对应客户端的 ID——它们按店铺分别签发。"
}
}
}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx
index ddde66abdb..ca345f01e8 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx
@@ -2,6 +2,7 @@ import { PageHeader } from '@spree/dashboard-core'
import { Alert, AlertDescription, Button, Card, CardContent, Skeleton } from '@spree/dashboard-ui'
import { CheckIcon, ShieldIcon } from '@spree/dashboard-ui/icons'
import { createFileRoute } from '@tanstack/react-router'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { z } from 'zod'
import { permissionKeyLabel } from '../../../../components/spree/permission-picker'
@@ -36,14 +37,29 @@ function OauthAuthorizePage() {
const search = Route.useSearch()
const { data, isLoading, error } = useOauthAuthorization(search)
const errorDetail = error instanceof Error ? error.message : undefined
+ const [decisionError, setDecisionError] = useState<string | null>(null)
const { data: catalog } = usePermissionCatalog()
const approve = useApproveOauthAuthorization()
const deny = useDenyOauthAuthorization()
// The decision ends the flow by handing the browser back to the client, so
// a full navigation rather than a router push.
- const leaveTo = (redirectUri: string) => {
- window.location.href = redirectUri
+ //
+ // A rejected decision leaves the merchant here, and without the catch they
+ // would sit on an unchanged screen with no sign the click did anything.
+ async function decide(mutation: typeof approve | typeof deny) {
+ setDecisionError(null)
+
+ try {
+ const result = await mutation.mutateAsync(search)
+ window.location.href = result.redirect_uri
+ } catch (failure) {
+ setDecisionError(
+ failure instanceof Error
+ ? failure.message
+ : t('admin.pages.oauth.authorize.decision_failed'),
+ )
+ }
}
const pending = approve.isPending || deny.isPending
@@ -111,24 +127,17 @@ function OauthAuthorizePage() {
</AlertDescription>
</Alert>
+ {decisionError ? (
+ <Alert variant="destructive">
+ <AlertDescription>{decisionError}</AlertDescription>
+ </Alert>
+ ) : null}
+
<div className="flex gap-3">
- <Button
- disabled={pending}
- onClick={async () => {
- const result = await approve.mutateAsync(search)
- leaveTo(result.redirect_uri)
- }}
- >
+ <Button disabled={pending} onClick={() => decide(approve)}>
{t('admin.pages.oauth.authorize.approve')}
</Button>
- <Button
- variant="outline"
- disabled={pending}
- onClick={async () => {
- const result = await deny.mutateAsync(search)
- leaveTo(result.redirect_uri)
- }}
- >
+ <Button variant="outline" disabled={pending} onClick={() => decide(deny)}>
{t('admin.pages.oauth.authorize.deny')}
</Button>
</div>
diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
index 722fb9964e..9e1f574945 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
@@ -52,8 +52,8 @@ module Spree
# Applications holding a live token, as a subquery so nothing is
# loaded just to be counted.
def connected_application_ids
- Spree::OauthAccessToken.
- where(revoked_at: nil, resource_owner_type: Spree.admin_user_class.name).
+ Spree::OauthAccessToken.not_expired.
+ where(resource_owner_type: Spree.admin_user_class.name).
where(application_id: current_store.oauth_applications.select(:id)).
select(:application_id)
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb
index 302a0ddbf6..4a87ecfcb8 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb
@@ -36,14 +36,11 @@ module Spree
end
def create
- authorization = ::Doorkeeper::OAuth::Authorization::Code.new(@pre_auth, current_actor)
- authorization.issue_token!
-
- render json: { redirect_uri: authorization.callback.redirect_uri }
+ render json: { redirect_uri: code_request.authorize.redirect_uri }
end
def destroy
- render json: { redirect_uri: denied_redirect_uri }
+ render json: { redirect_uri: code_request.deny.redirect_uri }
end
private
@@ -118,13 +115,12 @@ module Spree
@pre_auth.client&.application&.name.presence || 'An application'
end
- def denied_redirect_uri
- uri = URI.parse(@pre_auth.redirect_uri.to_s)
- query = Rack::Utils.parse_nested_query(uri.query.to_s)
- query['error'] = 'access_denied'
- query['state'] = params[:state] if params[:state].present?
- uri.query = query.to_query
- uri.to_s
+ # Doorkeeper's own request object builds both redirects. Hand-
+ # rolling them means getting out-of-band clients, fragment
+ # response mode and the RFC 9207 issuer parameter right by hand,
+ # which is exactly the work the gem is here to do.
+ def code_request
+ @code_request ||= ::Doorkeeper::OAuth::CodeRequest.new(@pre_auth, current_actor)
end
end
end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/oauth_application_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/oauth_application_serializer.rb
index 70c7a93ba0..ef2ae5c53f 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/oauth_application_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/oauth_application_serializer.rb
@@ -4,15 +4,17 @@ module Spree
module Admin
# Admin API serializer for {Spree::OauthApplication}.
#
- # Never exposes `secret` or `uid`: a client is pre-registered, and the
- # screen this feeds is about taking access away rather than
- # reconfiguring it.
+ # Exposes `client_id` but never `secret`. The id is public by
+ # design — it is what a merchant pastes into a connector — while the
+ # secret is null here anyway, because every MCP client is a public
+ # client that proves itself with PKCE instead.
#
# `scopes` and `last_used_at` come from the live tokens rather than
# the registration — a client is registered once and granted per
# consent, so what the merchant approved lives on the token.
class OauthApplicationSerializer < V3::BaseSerializer
typelize name: :string,
+ client_id: :string,
scopes: [:string, multi: true],
last_used_at: [:string, nullable: true],
authorized_at: [:string, nullable: true],
@@ -21,6 +23,8 @@ module Spree
attributes :name, :redirect_uri, created_at: :iso8601, updated_at: :iso8601
+ attribute :client_id, &:uid
+
attribute :scopes do |application|
application.live_token_scopes
end
diff --git a/spree/core/app/models/spree/oauth_application.rb b/spree/core/app/models/spree/oauth_application.rb
index 441f0133b4..d2ecbd37c8 100644
--- a/spree/core/app/models/spree/oauth_application.rb
+++ b/spree/core/app/models/spree/oauth_application.rb
@@ -21,11 +21,12 @@ module Spree
foreign_key: :application_id,
dependent: :destroy
- # Tokens that still work. A revoked or expired one says nothing about
- # what a merchant has granted, and showing its scopes after a revoke
- # reads as if the revoke did not take.
+ # Tokens that still work. Doorkeeper's own scope, so expiry counts as
+ # well as revocation: an application whose tokens have all run out can no
+ # longer call the store, and listing it as connected with its old scopes
+ # intact misstates what has access.
has_many :live_access_tokens,
- -> { where(revoked_at: nil) },
+ -> { not_expired },
class_name: 'Spree::OauthAccessToken',
foreign_key: :application_id,
inverse_of: :application,