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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: use real forgery protection on the public OAuth endpoints
Damian Legawiec5c9d4e30c486
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9fea94bb5f..1d86a7ebca 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -652,6 +652,8 @@ The starter is the canonical host — the same app `spree add dashboard` scaffolState the count for bulk (`{{count}}`, pluralized in every locale) and the record name for a single row. **When the write is immediate but the surrounding page is a dirty-tracked form, say so** — e.g. the products panel on a category/collection persists each add/remove/reorder on click while the rest of the page waits for Save, so its confirm copy reads "This takes effect immediately." Without that, merchants reasonably assume Save-or-Discard applies.+**A listing page renders `<ResourceTable>`, never a hand-built table.** Any page whose job is to list records — a settings resource, a top-level index — goes through `ResourceTable` with a `defineTable` definition in `packages/dashboard/src/tables/`. It carries column visibility, sorting, search, pagination, row selection, bulk actions, empty and loading states, and the drag-reorder contract; a `<Table>` assembled by hand gets none of them and drifts from every other page the moment one of those is added. The endpoint it reads must return `{ data, meta }` — add Pagy to the controller rather than returning a bare array, or the table cannot page. Reference: `routes/_authenticated/$storeId/settings/policies.tsx`. A hand-built `<Table>` is for the panels *inside* a record (a product's variants, an order's line items), which are not listing pages.+**Nested collection panels must paginate, never cap.** A panel listing records that belong to the parent (a category's or collection's products, and anything comparable) has to page through the nested endpoint and render `<Pagination meta={meta} onPageChange={...}>`. A bare `limit: 100` silently hides the remainder on a parent with thousands of children, and "select all" then quietly means "all 100 I happened to load". Two consequences to get right: show the parent's real total from `meta.count` rather than the loaded page length, and offset drag-reorder positions by `meta.from - 1`, since the reposition endpoints want an index across the whole set rather than within the page.**Forms.** Raw React Hook Form with `<Field>` / `<Input>` / `<FieldError>` blocks. Drive each input explicitly with `form.register(...)` or a `<Controller>` for custom widgets so the form reads top-to-bottom. Wrap RHF's `handleSubmit` with a try/catch that calls `mapSpreeErrorsToForm` (`@/lib/form-errors`) to route 422 responses onto `form.formState.errors`: flat attribute keys become field errors with `aria-invalid` + `<FieldError>`; `:base` and nested keys land on `errors.root.message` so render a destructive banner at the top of the form.diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex ad53848065..436fc9e6dd 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -484,7 +484,6 @@ import type {MediaUpdateParams,MediaUsageReference,MeUpdateParams,- OauthApplication,OauthAuthorizationParams,OauthAuthorizationRequest,OauthRedirect,@@ -658,6 +657,7 @@ import type {Locale,Market,Media,+ OauthApplication,OptionType,Order,OrderCancellationReason,@@ -5966,8 +5966,14 @@ export class AdminClient {/** Applications a merchant has connected, for the revoke screen. */applications: {- list: (options?: RequestOptions): Promise<{ data: OauthApplication[] }> =>- this.request<{ data: OauthApplication[] }>('GET', '/oauth/applications', options ?? {}),+ list: (+ params?: ListParams & Record<string, unknown>,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<OauthApplication>> =>+ this.request<PaginatedResponse<OauthApplication>>('GET', '/oauth/applications', {+ ...options,+ params: params ? transformListParams(params) : undefined,+ }),/*** Revokes every live token and grant an application holds. Thediff --git a/packages/admin-sdk/src/types/generated/OauthApplication.ts b/packages/admin-sdk/src/types/generated/OauthApplication.tsnew file mode 100644index 0000000000..024029dbbc--- /dev/null+++ b/packages/admin-sdk/src/types/generated/OauthApplication.ts@@ -0,0 +1,15 @@+// Typelizer digest cbcc75348711134a8d4fd2380ad60943+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface OauthApplication {+ id: string;+ name: string;+ redirect_uri: string | null;+ created_at: string;+ updated_at: string;+ scopes: Array<string>;+ last_used_at: string | null;+}++export default OauthApplication;diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex 512eb820b2..1779a2353c 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -131,6 +131,7 @@ export type { default as LineItem } from './generated/LineItem'export type { default as Locale } from './generated/Locale'export type { default as Market } from './generated/Market'export type { default as Media } from './generated/Media'+export type { default as OauthApplication } from './generated/OauthApplication'export type { default as OptionType } from './generated/OptionType'export type { default as OptionValue } from './generated/OptionValue'export type { default as Order } from './generated/Order'diff --git a/packages/admin-sdk/src/zod/generated/OauthApplication.ts b/packages/admin-sdk/src/zod/generated/OauthApplication.tsnew file mode 100644index 0000000000..d4e9d20406--- /dev/null+++ b/packages/admin-sdk/src/zod/generated/OauthApplication.ts@@ -0,0 +1,14 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';++export const OauthApplicationSchema = z.object({+ id: z.string(),+ name: z.string(),+ redirect_uri: z.string().nullable(),+ created_at: z.string(),+ updated_at: z.string(),+ scopes: z.array(z.string()),+ last_used_at: z.string().nullable(),+});++export type OauthApplication = z.infer<typeof OauthApplicationSchema>;diff --git a/packages/admin-sdk/src/zod/generated/index.ts b/packages/admin-sdk/src/zod/generated/index.tsindex 9d88c5ef3b..d91dde2fb4 100644--- a/packages/admin-sdk/src/zod/generated/index.ts+++ b/packages/admin-sdk/src/zod/generated/index.ts@@ -78,6 +78,7 @@ export { MarketSchema, type Market } from './Market';export { MediaSchema, type Media } from './Media';export { MembershipProductSchema, type MembershipProduct } from './MembershipProduct';export { NewsletterSubscriberSchema, type NewsletterSubscriber } from './NewsletterSubscriber';+export { OauthApplicationSchema, type OauthApplication } from './OauthApplication';export { OptionTypeSchema, type OptionType } from './OptionType';export { OptionValueSchema, type OptionValue } from './OptionValue';export { OrderSchema, type Order } from './Order';diff --git a/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsxindex 444e10442e..81f9953a26 100644--- a/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx+++ b/packages/dashboard/src/components/spree/api-keys/api-key-table.tsx@@ -316,7 +316,7 @@ function ApiKeyRow({// usual table widths.const SCOPE_PREVIEW_COUNT = 3-function ScopeList({ scopes }: { scopes: string[] }) {+export function ScopeList({ scopes }: { scopes: string[] }) {const { t } = useTranslation()if (scopes.includes('write_all')) {return <Badge>{t('admin.pages.settings.api_keys.scope_badge.full_access')}</Badge>diff --git a/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsxnew file mode 100644index 0000000000..5d170d1425--- /dev/null+++ b/packages/dashboard/src/components/spree/mcp-connect-sheet.tsx@@ -0,0 +1,197 @@+import type { ApiKey } from '@spree/admin-sdk'+import { Subject, usePermissions } from '@spree/dashboard-core'+import {+ Alert,+ AlertDescription,+ Button,+ Checkbox,+ CopyToClipboardButton,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetHeader,+ SheetTitle,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from '@spree/dashboard-ui'+import { useId, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { useCreateApiKey } from '../../hooks/use-api-keys'+import { useStoreSettings } from '../../hooks/use-store-settings'++type McpConnectSheetProps = {+ open: boolean+ onOpenChange: (open: boolean) => void+}++/**+ * Connects an agent to this store without anyone hand-building a config+ * file. A key is minted on demand with read-only scopes, and each client's+ * snippet is rendered ready to paste — the token appears here once, because+ * that is the only moment the API returns it.+ */+export function McpConnectSheet({ open, onOpenChange }: McpConnectSheetProps) {+ const { t } = useTranslation()+ const { data: store } = useStoreSettings()+ const createKey = useCreateApiKey()+ const { permissions } = usePermissions()+ const [minted, setMinted] = useState<ApiKey | null>(null)+ const [writable, setWritable] = useState(false)+ const [mintError, setMintError] = useState<string | null>(null)+ const writableId = useId()++ const endpoint = store ? `${store.api_url}/v3/admin/mcp` : ''+ const token = minted?.plaintext_token ?? 'YOUR_SECRET_KEY'+ const canMint = permissions.can('create', Subject.ApiKey)++ async function mint() {+ setMintError(null)++ try {+ // Named with a timestamp because a key's name is unique within the+ // store while it is live — a second agent connected on the same day+ // would otherwise collide with the first.+ const key = await createKey.mutateAsync({+ name: `MCP agent ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`,+ key_type: 'secret',+ scopes: writable ? ['write_all'] : ['read_all'],+ })+ setMinted(key)+ } catch (error) {+ setMintError(error instanceof Error ? error.message : t('admin.mcp_connect.mint_failed'))+ }+ }++ const snippets = {+ claude: `claude mcp add --transport http spree ${endpoint} \\+ --header "X-Spree-API-Key: ${token}"`,+ cursor: JSON.stringify(+ { mcpServers: { spree: { url: endpoint, headers: { 'X-Spree-API-Key': token } } } },+ null,+ 2,+ ),+ vscode: JSON.stringify(+ {+ servers: {+ spree: { type: 'http', url: endpoint, headers: { 'X-Spree-API-Key': token } },+ },+ },+ null,+ 2,+ ),+ curl: `curl ${endpoint} \\+ -H "Content-Type: application/json" \\+ -H "X-Spree-API-Key: ${token}" \\+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`,+ }++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent className="w-full overflow-y-auto sm:max-w-2xl">+ <SheetHeader>+ <SheetTitle>{t('admin.mcp_connect.title')}</SheetTitle>+ <SheetDescription>{t('admin.mcp_connect.subtitle')}</SheetDescription>+ </SheetHeader>++ <div className="flex flex-col gap-6 px-4 pb-8">+ {minted ? (+ <Alert>+ <AlertDescription>{t('admin.mcp_connect.token_shown_once')}</AlertDescription>+ </Alert>+ ) : (+ <div className="flex flex-col gap-3">+ <p className="text-muted-foreground text-sm">{t('admin.mcp_connect.mint_help')}</p>+ {canMint ? (+ <>+ <label+ htmlFor={writableId}+ className="flex cursor-pointer items-start gap-2 text-sm"+ >+ <Checkbox+ id={writableId}+ checked={writable}+ onCheckedChange={(checked) => setWritable(checked === true)}+ />+ <span>+ {t('admin.mcp_connect.allow_writes')}+ <span className="block text-muted-foreground text-xs">+ {t('admin.mcp_connect.allow_writes_help')}+ </span>+ </span>+ </label>+ {mintError ? (+ <Alert variant="destructive">+ <AlertDescription>{mintError}</AlertDescription>+ </Alert>+ ) : null}+ <Button className="self-start" disabled={createKey.isPending} onClick={mint}>+ {t('admin.mcp_connect.mint_cta')}+ </Button>+ </>+ ) : (+ <Alert variant="destructive">+ <AlertDescription>{t('admin.mcp_connect.mint_denied')}</AlertDescription>+ </Alert>+ )}+ </div>+ )}++ <Tabs defaultValue="claude">+ <TabsList>+ <TabsTrigger value="claude">Claude Code</TabsTrigger>+ <TabsTrigger value="cursor">Cursor</TabsTrigger>+ <TabsTrigger value="vscode">VS Code</TabsTrigger>+ <TabsTrigger value="curl">{t('admin.mcp_connect.tab_other')}</TabsTrigger>+ </TabsList>++ {(['claude', 'cursor', 'vscode', 'curl'] as const).map((client) => (+ <TabsContent key={client} value={client}>+ <div className="relative">+ <pre className="overflow-x-auto rounded-md bg-muted p-4 pr-12 text-xs leading-relaxed">+ <code>{snippets[client]}</code>+ </pre>+ <CopyToClipboardButton+ aria-label={t('admin.actions.copy')}+ className="absolute top-2 right-2"+ value={snippets[client]}+ />+ </div>+ {client === 'cursor' ? (+ <p className="mt-2 text-muted-foreground text-xs">+ {t('admin.mcp_connect.cursor_path')}+ </p>+ ) : null}+ {client === 'vscode' ? (+ <p className="mt-2 text-muted-foreground text-xs">+ {t('admin.mcp_connect.vscode_path')}+ </p>+ ) : null}+ </TabsContent>+ ))}+ </Tabs>++ {/* A consumer connector takes a URL, not a key — it signs in. There+ is no deep link that would open one of these apps on a given+ server, so the useful thing is the URL itself, ready to paste+ into the connector dialog. */}+ <div className="flex flex-col gap-2 border-t pt-4">+ <p className="font-medium text-sm">{t('admin.mcp_connect.consumer_title')}</p>+ <p className="text-muted-foreground text-xs">{t('admin.mcp_connect.consumer_note')}</p>+ <div className="relative">+ <pre className="overflow-x-auto rounded-md bg-muted p-3 pr-12 text-xs">+ <code>{endpoint}</code>+ </pre>+ <CopyToClipboardButton+ aria-label={t('admin.actions.copy')}+ className="absolute top-1.5 right-2"+ value={endpoint}+ />+ </div>+ </div>+ </div>+ </SheetContent>+ </Sheet>+ )+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex 4cf2d3ebcd..a7fc6f8d9c 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -6368,6 +6368,23 @@"empty": "لا توجد إشعارات جديدة.","view_on_github": "عرض على GitHub","release_notes_unavailable": "تعذر تحميل ملاحظات الإصدار. اقرأها على GitHub بدلاً من ذلك."+ },+ "mcp_connect": {+ "open_cta": "ربط وكيل",+ "title": "ربط وكيل",+ "subtitle": "امنح مساعد الذكاء الاصطناعي حق الوصول إلى هذا المتجر. انسخ الإعداد الخاص بعميلك والصقه.",+ "mint_help": "يتم إنشاء مفتاح للقراءة فقط للوكيل. وللسماح له بإجراء تغييرات، أنشئ بدلاً من ذلك مفتاحًا بالصلاحيات التي تريدها من صفحة مفاتيح API.",+ "mint_cta": "إنشاء مفتاح",+ "mint_denied": "ليست لديك صلاحية إنشاء مفاتيح API.",+ "token_shown_once": "انسخ الإعداد الآن — يُعرض المفتاح هذه المرة فقط.",+ "tab_other": "شيء آخر",+ "cursor_path": "احفظه باسم .cursor/mcp.json في مشروعك، أو ~/.cursor/mcp.json لك وحدك.",+ "vscode_path": "احفظه باسم .vscode/mcp.json في مشروعك.",+ "consumer_note": "تتصل هذه عبر تسجيل الدخول بدلاً من استخدام مفتاح. أضف موصّلاً في العميل، والصق هذا العنوان، ثم وافق على الطلب هنا.",+ "allow_writes": "السماح لهذا الوكيل بإجراء تغييرات",+ "allow_writes_help": "اتركه مُعطّلاً للوكيل الذي يقرأ فقط. فالمفتاح القادر على التغيير يستطيع أيضًا إلغاء الطلبات وإصدار المبالغ المستردة.",+ "mint_failed": "تعذّر إنشاء المفتاح.",+ "consumer_title": "Claude Desktop وclaude.ai وChatGPT"}}}diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex a1bf17f9fb..12e8bfe7c8 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -6328,6 +6328,23 @@"empty": "Sie sind auf dem neuesten Stand.","view_on_github": "Auf GitHub ansehen","release_notes_unavailable": "Die Versionshinweise konnten nicht geladen werden. Lesen Sie sie stattdessen auf GitHub."+ },+ "mcp_connect": {+ "open_cta": "Agent verbinden",+ "title": "Agent verbinden",+ "subtitle": "Geben Sie einem KI-Assistenten Zugriff auf diesen Shop. Kopieren Sie die Einrichtung für Ihren Client und fügen Sie sie ein.",+ "mint_help": "Für den Agenten wird ein Schlüssel nur zum Lesen erstellt. Damit er Änderungen vornehmen darf, erstellen Sie stattdessen auf der Seite API-Schlüssel einen Schlüssel mit den gewünschten Berechtigungen.",+ "mint_cta": "Schlüssel erstellen",+ "mint_denied": "Sie haben keine Berechtigung, API-Schlüssel zu erstellen.",+ "token_shown_once": "Kopieren Sie die Einrichtung jetzt — der Schlüssel wird nur dieses eine Mal angezeigt.",+ "tab_other": "Etwas anderes",+ "cursor_path": "Als .cursor/mcp.json im Projekt speichern oder als ~/.cursor/mcp.json für Sie persönlich.",+ "vscode_path": "Als .vscode/mcp.json im Projekt speichern.",+ "consumer_note": "Diese verbinden sich per Anmeldung statt mit einem Schlüssel. Fügen Sie im Client einen Connector hinzu, fügen Sie diese URL ein und bestätigen Sie die Anfrage hier.",+ "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"}}}diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 856846652d..8d040e7479 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -6328,6 +6328,23 @@"empty": "You're all caught up.","view_on_github": "View on GitHub","release_notes_unavailable": "The release notes could not be loaded. Read them on GitHub instead."+ },+ "mcp_connect": {+ "open_cta": "Connect an agent",+ "title": "Connect an agent",+ "subtitle": "Give an AI assistant access to this store. Copy the setup for your client and paste it in.",+ "mint_help": "A read-only key is created for the agent. To let it make changes, create a key with the scopes you want on the API keys page instead.",+ "mint_cta": "Create a key",+ "mint_denied": "You do not have permission to create API keys.",+ "token_shown_once": "Copy the setup below now — the key is shown only this once.",+ "tab_other": "Anything else",+ "cursor_path": "Save as .cursor/mcp.json in your project, or ~/.cursor/mcp.json for yourself.",+ "vscode_path": "Save as .vscode/mcp.json in your project.",+ "consumer_note": "These connect by signing in rather than with a key. Add a connector in the client, paste this URL, and approve the request here.",+ "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"}}}diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex b3c967e53c..76f9d340cc 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -6328,6 +6328,23 @@"empty": "Estás al día.","view_on_github": "Ver en GitHub","release_notes_unavailable": "No se pudieron cargar las notas de la versión. Léelas en GitHub."+ },+ "mcp_connect": {+ "open_cta": "Conectar un agente",+ "title": "Conectar un agente",+ "subtitle": "Dé a un asistente de IA acceso a esta tienda. Copie la configuración de su cliente y péguela.",+ "mint_help": "Se crea una clave de solo lectura para el agente. Para que pueda hacer cambios, cree una clave con los permisos que desee en la página de Claves API.",+ "mint_cta": "Crear una clave",+ "mint_denied": "No tiene permiso para crear claves API.",+ "token_shown_once": "Copie la configuración ahora: la clave se muestra solo esta vez.",+ "tab_other": "Otra cosa",+ "cursor_path": "Guárdelo como .cursor/mcp.json en su proyecto, o ~/.cursor/mcp.json para usted.",+ "vscode_path": "Guárdelo como .vscode/mcp.json en su proyecto.",+ "consumer_note": "Estos se conectan iniciando sesión en lugar de con una clave. Añada un conector en el cliente, pegue esta URL y apruebe la solicitud aquí.",+ "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"}}}diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex cd47aa3fc8..fef75fbbe7 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -6328,6 +6328,23 @@"empty": "Vous êtes à jour.","view_on_github": "Voir sur GitHub","release_notes_unavailable": "Impossible de charger les notes de version. Consultez-les sur GitHub."+ },+ "mcp_connect": {+ "open_cta": "Connecter un agent",+ "title": "Connecter un agent",+ "subtitle": "Donnez à un assistant IA accès à cette boutique. Copiez la configuration de votre client et collez-la.",+ "mint_help": "Une clé en lecture seule est créée pour l’agent. Pour qu’il puisse apporter des modifications, créez plutôt une clé avec les autorisations voulues sur la page Clés API.",+ "mint_cta": "Créer une clé",+ "mint_denied": "Vous n’avez pas l’autorisation de créer des clés API.",+ "token_shown_once": "Copiez la configuration maintenant — la clé n’est affichée qu’une seule fois.",+ "tab_other": "Autre chose",+ "cursor_path": "Enregistrez sous .cursor/mcp.json dans votre projet, ou ~/.cursor/mcp.json pour vous.",+ "vscode_path": "Enregistrez sous .vscode/mcp.json dans votre projet.",+ "consumer_note": "Ceux-ci se connectent en se connectant à votre compte plutôt qu’avec une clé. Ajoutez un connecteur dans le client, collez cette URL et approuvez la demande ici.",+ "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"}}}diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 72e2999ef5..c4c4652e5a 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -6396,6 +6396,23 @@"empty": "Wszystko przeczytane.","view_on_github": "Zobacz na GitHubie","release_notes_unavailable": "Nie udało się wczytać informacji o wydaniu. Przeczytaj je na GitHubie."+ },+ "mcp_connect": {+ "open_cta": "Połącz agenta",+ "title": "Połącz agenta",+ "subtitle": "Daj asystentowi AI dostęp do tego sklepu. Skopiuj konfigurację dla swojego klienta i wklej ją.",+ "mint_help": "Dla agenta tworzony jest klucz tylko do odczytu. Aby mógł wprowadzać zmiany, utwórz klucz z wybranymi uprawnieniami na stronie Klucze API.",+ "mint_cta": "Utwórz klucz",+ "mint_denied": "Nie masz uprawnień do tworzenia kluczy API.",+ "token_shown_once": "Skopiuj konfigurację teraz — klucz jest pokazywany tylko ten jeden raz.",+ "tab_other": "Coś innego",+ "cursor_path": "Zapisz jako .cursor/mcp.json w projekcie lub ~/.cursor/mcp.json dla siebie.",+ "vscode_path": "Zapisz jako .vscode/mcp.json w projekcie.",+ "consumer_note": "Łączą się przez zalogowanie, a nie kluczem. Dodaj konektor w kliencie, wklej ten adres i zatwierdź prośbę tutaj.",+ "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"}}}diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 8f85817699..870712c5ec 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -6315,6 +6315,23 @@"empty": "暂无新通知。","view_on_github": "在 GitHub 上查看","release_notes_unavailable": "无法加载版本说明,请前往 GitHub 查看。"+ },+ "mcp_connect": {+ "open_cta": "连接代理",+ "title": "连接代理",+ "subtitle": "让 AI 助手访问此店铺。复制适用于您客户端的设置并粘贴。",+ "mint_help": "系统会为代理创建一个只读密钥。若要允许其进行更改,请改在“API 密钥”页面创建具有所需权限的密钥。",+ "mint_cta": "创建密钥",+ "mint_denied": "您没有创建 API 密钥的权限。",+ "token_shown_once": "请立即复制下面的设置——密钥仅显示这一次。",+ "tab_other": "其他",+ "cursor_path": "保存为项目中的 .cursor/mcp.json,或保存为您个人的 ~/.cursor/mcp.json。",+ "vscode_path": "保存为项目中的 .vscode/mcp.json。",+ "consumer_note": "它们通过登录而非密钥连接。在客户端中添加连接器,粘贴此网址,然后在此处批准请求。",+ "allow_writes": "允许此代理进行更改",+ "allow_writes_help": "仅读取的代理请保持关闭。可更改数据的密钥同样可以取消订单和发起退款。",+ "mint_failed": "无法创建密钥。",+ "consumer_title": "Claude Desktop、claude.ai 和 ChatGPT"}}}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsxindex bba91d88fe..ddde66abdb 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx@@ -35,6 +35,7 @@ function OauthAuthorizePage() {const { t } = useTranslation()const search = Route.useSearch()const { data, isLoading, error } = useOauthAuthorization(search)+ const errorDetail = error instanceof Error ? error.message : undefinedconst { data: catalog } = usePermissionCatalog()const approve = useApproveOauthAuthorization()const deny = useDenyOauthAuthorization()@@ -54,75 +55,88 @@ function OauthAuthorizePage() {description={t('admin.pages.oauth.authorize.subtitle')}/>+ {/* The server says what is actually wrong — a missing code challenge,+ an unknown client, a redirect that does not match. Showing only+ "not valid" leaves a merchant with nothing to act on, and the card+ below would skeleton forever behind it. */}{error ? (<Alert variant="destructive">- <AlertDescription>{t('admin.pages.oauth.authorize.invalid_request')}</AlertDescription>+ <AlertDescription>+ {t('admin.pages.oauth.authorize.invalid_request')}+ {errorDetail ? (+ <span className="mt-1 block text-xs opacity-80">{errorDetail}</span>+ ) : null}+ </AlertDescription></Alert>) : null}- <Card>- <CardContent className="flex flex-col gap-6 pt-6">- {isLoading || !data ? (- <div className="flex flex-col gap-3">- <Skeleton className="h-5 w-48" />- <Skeleton className="h-4 w-full" />- <Skeleton className="h-4 w-2/3" />- </div>- ) : (- <>- <div className="flex items-start gap-3">- <ShieldIcon className="mt-0.5 size-5 shrink-0 text-muted-foreground" />- <p className="text-sm">- {t('admin.pages.oauth.authorize.intro', { client: data.client_name })}- </p>+ {error ? null : (+ <Card>+ <CardContent className="flex flex-col gap-6 pt-6">+ {isLoading || !data ? (+ <div className="flex flex-col gap-3">+ <Skeleton className="h-5 w-48" />+ <Skeleton className="h-4 w-full" />+ <Skeleton className="h-4 w-2/3" /></div>+ ) : (+ <>+ <div className="flex items-start gap-3">+ <ShieldIcon className="mt-0.5 size-5 shrink-0 text-muted-foreground" />+ <p className="text-sm">+ {t('admin.pages.oauth.authorize.intro', { client: data.client_name })}+ </p>+ </div>- <div className="flex flex-col gap-3">- <h2 className="font-medium text-sm">- {t('admin.pages.oauth.authorize.permissions_heading')}- </h2>- <ul className="flex flex-col gap-2">- {data.scopes.map((key) => (- <li key={key} className="flex items-start gap-2 text-sm">- <CheckIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />- {/* Labelled client-side so the one screen that tells a+ <div className="flex flex-col gap-3">+ <h2 className="font-medium text-sm">+ {t('admin.pages.oauth.authorize.permissions_heading')}+ </h2>+ <ul className="flex flex-col gap-2">+ {data.scopes.map((key) => (+ <li key={key} className="flex items-start gap-2 text-sm">+ <CheckIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />+ {/* Labelled client-side so the one screen that tells amerchant what they are granting follows their ownlanguage, not the server's. */}- <span>{permissionKeyLabel(t, catalog?.data, key)}</span>- </li>- ))}- </ul>- </div>+ <span>{permissionKeyLabel(t, catalog?.data, key)}</span>+ </li>+ ))}+ </ul>+ </div>- <Alert>- <AlertDescription>{t('admin.pages.oauth.authorize.revoke_hint')}</AlertDescription>- </Alert>+ <Alert>+ <AlertDescription>+ {t('admin.pages.oauth.authorize.revoke_hint')}+ </AlertDescription>+ </Alert>- <div className="flex gap-3">- <Button- disabled={pending}- onClick={async () => {- const result = await approve.mutateAsync(search)- leaveTo(result.redirect_uri)- }}- >- {t('admin.pages.oauth.authorize.approve')}- </Button>- <Button- variant="outline"- disabled={pending}- onClick={async () => {- const result = await deny.mutateAsync(search)- leaveTo(result.redirect_uri)- }}- >- {t('admin.pages.oauth.authorize.deny')}- </Button>- </div>- </>- )}- </CardContent>- </Card>+ <div className="flex gap-3">+ <Button+ disabled={pending}+ onClick={async () => {+ const result = await approve.mutateAsync(search)+ leaveTo(result.redirect_uri)+ }}+ >+ {t('admin.pages.oauth.authorize.approve')}+ </Button>+ <Button+ variant="outline"+ disabled={pending}+ onClick={async () => {+ const result = await deny.mutateAsync(search)+ leaveTo(result.redirect_uri)+ }}+ >+ {t('admin.pages.oauth.authorize.deny')}+ </Button>+ </div>+ </>+ )}+ </CardContent>+ </Card>+ )}</div>)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsxindex b9d424d087..de5421a50c 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx@@ -1,37 +1,32 @@import type { OauthApplication } from '@spree/admin-sdk'-import { PageHeader, Subject, usePermissions } from '@spree/dashboard-core'import {- Badge,- Card,- CardContent,- RelativeTime,- RowActions,- Skeleton,- Table,- TableBody,- TableCell,- TableHead,- TableHeader,- TableRow,- useConfirm,-} from '@spree/dashboard-ui'+ adminClient,+ PageHeader,+ ResourceTable,+ resourceSearchSchema,+ Subject,+ usePermissions,+} from '@spree/dashboard-core'+import { Button, RowActions, useConfirm } from '@spree/dashboard-ui'import { createFileRoute } from '@tanstack/react-router'+import { useState } from 'react'import { useTranslation } from 'react-i18next'-import { useOauthApplications, useRevokeOauthApplication } from '../../../../hooks/use-oauth'+import { McpConnectSheet } from '../../../../components/spree/mcp-connect-sheet'+import { useRevokeOauthApplication } from '../../../../hooks/use-oauth'+import '../../../../tables/oauth-applications'export const Route = createFileRoute('/_authenticated/$storeId/settings/connected-apps')({+ validateSearch: resourceSearchSchema,component: ConnectedAppsSettingsPage,})function ConnectedAppsSettingsPage() {const { t } = useTranslation()+ const search = Route.useSearch()const confirm = useConfirm()- const { data, isLoading } = useOauthApplications()const revoke = useRevokeOauthApplication()const { permissions } = usePermissions()-- const applications = data?.data ?? []- const canRevoke = permissions.can('update', Subject.Store)+ const [connectOpen, setConnectOpen] = useState(false)async function handleRevoke(application: OauthApplication) {const ok = await confirm({@@ -52,70 +47,36 @@ function ConnectedAppsSettingsPage() {<PageHeadertitle={t('admin.pages.settings.connected_apps.title')}description={t('admin.pages.settings.connected_apps.subtitle')}+ actions={+ <Button size="sm" onClick={() => setConnectOpen(true)}>+ {t('admin.mcp_connect.open_cta')}+ </Button>+ }/>- <Card>- <CardContent className="p-0">- {isLoading ? (- <div className="flex flex-col gap-3 p-6">- <Skeleton className="h-4 w-full" />- <Skeleton className="h-4 w-2/3" />- </div>- ) : applications.length === 0 ? (- <p className="p-6 text-muted-foreground text-sm">- {t('admin.pages.settings.connected_apps.empty')}- </p>- ) : (- <Table>- <TableHeader>- <TableRow>- <TableHead>{t('admin.pages.settings.connected_apps.table.name')}</TableHead>- <TableHead>{t('admin.pages.settings.connected_apps.table.access')}</TableHead>- <TableHead>{t('admin.pages.settings.connected_apps.table.last_used')}</TableHead>- <TableHead />- </TableRow>- </TableHeader>- <TableBody>- {applications.map((application) => (- <TableRow key={application.id}>- <TableCell className="font-medium">{application.name}</TableCell>- <TableCell>- <div className="flex flex-wrap gap-1">- {application.scopes.length === 0 ? (- <span className="text-muted-foreground text-sm">—</span>- ) : (- application.scopes.map((scope) => (- <Badge key={scope} variant="secondary">- {scope}- </Badge>- ))- )}- </div>- </TableCell>- <TableCell className="text-muted-foreground">- <RelativeTime iso={application.last_used_at} />- </TableCell>- <TableCell className="text-right">- <RowActions- actions={[- {- key: 'revoke',- label: t('admin.pages.settings.connected_apps.revoke'),- destructive: true,- visible: canRevoke,- disabled: revoke.isPending,- onSelect: () => handleRevoke(application),- },- ]}- />- </TableCell>- </TableRow>- ))}- </TableBody>- </Table>- )}- </CardContent>- </Card>+ <McpConnectSheet open={connectOpen} onOpenChange={setConnectOpen} />++ <ResourceTable<OauthApplication>+ tableKey="oauth-applications"+ queryKey="oauth-applications"+ hideHeader+ queryFn={(params) => adminClient.oauth.applications.list(params)}+ searchParams={search}+ rowActions={(application) => (+ <RowActions+ actions={[+ {+ key: 'revoke',+ label: t('admin.pages.settings.connected_apps.revoke'),+ destructive: true,+ visible: permissions.can('update', Subject.Store),+ disabled: revoke.isPending,+ onSelect: () => handleRevoke(application),+ },+ ]}+ />+ )}+ /></div>)}diff --git a/packages/dashboard/src/tables/oauth-applications.tsx b/packages/dashboard/src/tables/oauth-applications.tsxnew file mode 100644index 0000000000..7e18bb7b50--- /dev/null+++ b/packages/dashboard/src/tables/oauth-applications.tsx@@ -0,0 +1,33 @@+import type { OauthApplication } from '@spree/admin-sdk'+import { defineTable } from '@spree/dashboard-core'+import { RelativeTime, ResourceNameCell } from '@spree/dashboard-ui'+import { PlugIcon } from '@spree/dashboard-ui/icons'+import i18n from 'i18next'+import { ScopeList } from '../components/spree/api-keys/api-key-table'++defineTable<OauthApplication>('oauth-applications', {+ title: i18n.t('admin.settings_nav.items.connected_apps'),+ description: i18n.t('admin.pages.settings.connected_apps.subtitle'),+ emptyIcon: <PlugIcon className="size-8 text-muted-foreground" />,+ emptyMessage: i18n.t('admin.pages.settings.connected_apps.empty'),+ columns: [+ {+ key: 'name',+ label: i18n.t('admin.pages.settings.connected_apps.table.name'),+ default: true,+ render: (application) => <ResourceNameCell id={application.id} name={application.name} />,+ },+ {+ key: 'scopes',+ label: i18n.t('admin.pages.settings.connected_apps.table.access'),+ default: true,+ render: (application) => <ScopeList scopes={application.scopes} />,+ },+ {+ key: 'last_used_at',+ label: i18n.t('admin.pages.settings.connected_apps.table.last_used'),+ default: true,+ render: (application) => <RelativeTime iso={application.last_used_at} />,+ },+ ],+})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.rbindex 1b5268890c..a1a607b127 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@@ -15,11 +15,25 @@ module Spreescoped_resource :settingsdef index- applications = current_store.oauth_applications.- where(id: live_tokens_by_application.keys).- order(:name)+ # Only applications somebody actually authorized — a registered+ # client nobody connected is not a connection. Tokens are+ # preloaded because the serializer reads each application's+ # scopes and last use from them.+ scope = current_store.oauth_applications.+ where(id: connected_application_ids).+ includes(:live_access_tokens).+ order(:name)- render json: { data: applications.map { |application| serialize(application) } }+ @pagy, applications = pagy(scope, limit: params[:limit] || 25)++ render json: {+ data: Spree.api.admin_oauth_application_serializer.new(applications).serializable_hash,+ meta: {+ page: @pagy.page, limit: @pagy.limit, count: @pagy.count,+ pages: @pagy.pages, from: @pagy.from, to: @pagy.to,+ in: @pagy.in, previous: @pagy.previous, next: @pagy.next+ }+ }enddef destroy@@ -35,32 +49,13 @@ module Spreeprivate- # Scopes come from the live tokens, not the registration: a- # client is registered once and granted per consent, so the- # registration's own `scopes` column stays empty and what the- # merchant actually approved lives on the tokens.- def serialize(application)- tokens = live_tokens_by_application[application.id].to_a-- {- id: application.prefixed_id,- name: application.name,- scopes: tokens.flat_map { |token| token.scopes.to_a }.uniq.sort,- last_used_at: tokens.map(&:created_at).max,- created_at: application.created_at- }- end-- # The live tokens for this store's applications, which answer both- # which clients are connected and what each was granted. Scoped to- # the store so a multi-store installation does not load every- # token it holds to render one page.- def live_tokens_by_application- @live_tokens_by_application ||=- Spree::OauthAccessToken.+ # 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).where(application_id: current_store.oauth_applications.select(:id)).- group_by(&:application_id)+ select(:application_id)endendenddiff --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.rbindex 24ccb8e746..302a0ddbf6 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@@ -13,10 +13,14 @@ module Spree# Doorkeeper's own controller is not used: it renders HTML and runs# its own login, and the dashboard already knows who is signed in.class AuthorizationsController < Spree::Api::V3::Admin::BaseController- # Consent is a person's decision about their own authority, so it- # is JWT-only by construction: a secret key has no human behind- # it and must never be able to mint a token for one.- skip_scope_check!(jwt_only: true)+ # Consent is a person's decision about their own authority, and a+ # secret key has no human behind it, so there is no scope that+ # could make this callable with one — `require_signed_in_admin!`+ # refuses a key outright. Skipped for every principal rather than+ # JWT-only, because leaving the key path in the scope machinery+ # asks this controller for a `scoped_resource` it cannot+ # meaningfully name.+ skip_scope_check!before_action :require_signed_in_admin!before_action :require_client_of_this_store!diff --git a/spree/api/app/controllers/spree/api/v3/oauth/authorizations_controller.rb b/spree/api/app/controllers/spree/api/v3/oauth/authorizations_controller.rbindex e663e7adbb..afed62207b 100644--- a/spree/api/app/controllers/spree/api/v3/oauth/authorizations_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/oauth/authorizations_controller.rb@@ -18,11 +18,12 @@ module Spreeinclude Spree::Core::ControllerHelpers::Store# The authorization endpoint is reached by a cross-site GET on- # purpose — a client sends the browser here — so a forgery token- # cannot be required. It is safe to leave open because the action- # only redirects: nothing is granted until the merchant submits- # consent to the Admin API, which does carry its own session.- protect_from_forgery with: :null_session+ # purpose — a client sends the browser here — and forgery+ # protection never applies to a GET, so `:exception` costs nothing+ # while leaving the endpoint reachable. Nothing is granted here+ # either way: the action only redirects, and consent is submitted+ # to the Admin API under the merchant's own session.+ protect_from_forgery with: :exception# Carried across to the dashboard. Everything else is dropped, so a# crafted link cannot smuggle extra parameters into the consent page.diff --git a/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb b/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rbindex 69853efa46..78978b8bea 100644--- a/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/oauth/metadata_controller.rb@@ -10,21 +10,20 @@ module Spree# resource. It is deliberately unauthenticated: a client has no# credential at the point it asks.class MetadataController < ActionController::API- include Spree::Core::ControllerHelpers::Store# A public discovery document, read before any credential exists.# The module has to be included because `ActionController::API`- # carries no forgery protection at all — declaring `:null_session`- # states that this endpoint changes nothing, rather than leaving- # that true only by accident of the base class.+ # carries none of it; `:exception` is free here because the only+ # action is a GET, which forgery protection never applies to.include ActionController::RequestForgeryProtection- protect_from_forgery with: :null_session+ protect_from_forgery with: :exception# The `resource` value must equal the URL the client was pointed at,# path and all, or a consumer client refuses to continue — so it is- # echoed from the registered identifier rather than rebuilt here.+ # built from this request's own origin rather than from anything+ # configured elsewhere.def show- resource = Spree::Api::Oauth.resource_identifier(params[:resource_key], current_store)+ resource = Spree::Api::Oauth.resource_identifier(params[:resource_key], request.base_url)return head :not_found if resource.blank?render json: {@@ -42,8 +41,10 @@ module Spreeprivate+ # The authorization server's own origin. This request reached it, so+ # the origin it arrived on is the one a client can use.def issuer- ::Doorkeeper.config.issuer.presence || current_store.formatted_url+ ::Doorkeeper.config.issuer.presence || request.base_urlendendenddiff --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.rbnew file mode 100644index 0000000000..ac28fb4073--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/oauth_application_serializer.rb@@ -0,0 +1,33 @@+module Spree+ module Api+ module V3+ 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.+ #+ # `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,+ scopes: [:string, multi: true],+ last_used_at: [:string, nullable: true],+ redirect_uri: [:string, nullable: true]++ attributes :name, :redirect_uri, created_at: :iso8601, updated_at: :iso8601++ attribute :scopes do |application|+ application.live_token_scopes+ end++ attribute :last_used_at do |application|+ application.last_used_at&.iso8601+ end+ end+ end+ end+ end+enddiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 7eebb78552..c653f7f7f4 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -38,7 +38,7 @@ module Spreechannel order_routing_rule product_publication market delivery_method delivery_method_servicestock_location stock_reservation delivery_rate freight_summary freight_summary_line payment_methodcredit_card store_credit store_credit_event customer_group payment_source digital_asset digital_link- store setup_task update_status api_key allowed_origin webhook_endpoint webhook_event webhook_delivery invitation+ store setup_task update_status api_key oauth_application allowed_origin webhook_endpoint webhook_event webhook_delivery invitationinvitation_acceptance_link role permission export saved_report import import_row import_mapping promotionpromotion_action promotion_rule coupon_code price_adjustment_tier price_list price_ruleresource_translations email_template email_template_draft email_template_revision email_template_previewdiff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rbindex 127098de95..394f4d8c95 100644--- a/spree/api/lib/spree/api/oauth.rb+++ b/spree/api/lib/spree/api/oauth.rb@@ -15,37 +15,55 @@ module Spree# which is why this lives in `spree_api` rather than in any one gem that# happens to need it.module Oauth- # Protected resources, each registered by the surface that owns it.+ # Protected resources, each registered by the surface that owns it as a+ # path relative to this application's own origin.#- # A resource identifier must equal the URL the client was pointed at,- # path included, or a consumer client refuses the connection — so the- # owning surface supplies it rather than this module guessing.+ # Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp')#- # Spree.api.oauth.register_resource(:mcp) do |store|- # "#{store.formatted_url}/api/v3/admin/mcp"- # end+ # A path rather than a full URL because the identifier must equal the+ # URL the client was actually pointed at: the origin comes from the+ # request where there is one, and from the application's configured+ # URL options otherwise. A store's own `url` column is deliberately not+ # consulted — it describes the storefront, which is frequently neither+ # the host nor the scheme the Admin API answers on.mattr_accessor :resources, default: {}class << self# @param key [Symbol]- # @yieldparam store [Spree::Store]- # @yieldreturn [String] the resource identifier for that store- def register_resource(key, &identifier)- resources[key.to_sym] = identifier+ # @param path [String] absolute path this resource answers on+ def register_resource(key, path)+ resources[key.to_sym] = pathend- # @param store [Spree::Store]+ # @param origin [String, nil] scheme and host the client used# @return [Array<String>] every resource identifier this installation- # serves for the store- def resource_identifiers(store)- resources.values.map { |identifier| identifier.call(store) }+ # serves+ def resource_identifiers(origin = nil)+ base = origin.presence || application_origin+ resources.values.map { |path| "#{base}#{path}" }end# @param key [Symbol]- # @param store [Spree::Store]+ # @param origin [String, nil] scheme and host the client used# @return [String, nil]- def resource_identifier(key, store)- resources[key.to_sym]&.call(store)+ def resource_identifier(key, origin = nil)+ path = resources[key.to_sym]+ return if path.nil?++ "#{origin.presence || application_origin}#{path}"+ end++ # Where this application answers, from the URL options a deployment+ # already has to set for mailer links to work.+ #+ # @return [String]+ def application_origin+ options = Rails.application.routes.default_url_options+ host = options[:host]+ return '' if host.blank?++ origin = "#{options[:protocol].presence || 'https'}://#{host}"+ options[:port].present? ? "#{origin}:#{options[:port]}" : originend# The grantable scope list, re-read after host and extension@@ -68,24 +86,26 @@ module SpreeSpree.permissions.grantable_keys(Spree::PermissionConfiguration::STAFF_AUDIENCE)end- # Whether every requested audience belongs to the client's own store.+ # Whether every requested audience names a resource this application+ # actually serves.#- # Asked of the client rather than of every store: a client is- # registered to one store, so that store's resources are the only ones- # a grant for it could legitimately name, and the application is- # already loaded to validate the client id.+ # Compared by path rather than by full URL: the origin a client used+ # is whatever it was pointed at, and a deployment behind a proxy or+ # reachable at several hostnames would otherwise refuse its own+ # tokens.## @param requested [Array<String>] the `resource` values asked for- # @param client [Object] Doorkeeper's client wrapper# @return [Boolean]- def indicators_valid?(requested, client)+ def indicators_valid?(requested, _client = nil)return false if requested.blank?- store = client.try(:application)&.store- return false if store.nil?-- allowed = resource_identifiers(store)- requested.all? { |indicator| allowed.include?(indicator) }+ paths = resources.values+ requested.all? do |indicator|+ path = URI.parse(indicator.to_s).path+ paths.include?(path)+ rescue URI::InvalidURIError+ false+ endenddef configure!@@ -121,8 +141,8 @@ module Spree# RFC 8707. Registering the validator is what binds an audience# into the token; left nil, the `resource` parameter is ignored# and a token minted for another service would be accepted.- resource_indicator_validator(lambda do |requested, client|- Spree::Api::Oauth.indicators_valid?(requested, client)+ resource_indicator_validator(lambda do |requested, _client|+ Spree::Api::Oauth.indicators_valid?(requested)end)# Spree's own permission catalog is the scope vocabulary, so adiff --git a/spree/api/spec/requests/spree/api/v3/oauth/discovery_spec.rb b/spree/api/spec/requests/spree/api/v3/oauth/discovery_spec.rbindex 1194c76701..efdf7975fe 100644--- a/spree/api/spec/requests/spree/api/v3/oauth/discovery_spec.rb+++ b/spree/api/spec/requests/spree/api/v3/oauth/discovery_spec.rb@@ -7,11 +7,7 @@ require 'spec_helper'RSpec.describe 'OAuth discovery', type: :request dolet(:store) { @default_store }- before do- Spree::Api::Oauth.register_resource(:mcp) do |registered_store|- "#{registered_store.formatted_url}/api/v3/admin/mcp"- end- end+ before { Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp') }describe 'GET /.well-known/oauth-authorization-server' dosubject(:document) do@@ -50,7 +46,11 @@ RSpec.describe 'OAuth discovery', type: :request doexpect(response).to have_http_status(:ok)body = JSON.parse(response.body)- expect(body['resource']).to eq(Spree::Api::Oauth.resource_identifier(:mcp, store))+ # Built from the request rather than from anything configured, so a+ # deployment behind a proxy or reachable at several hostnames still+ # hands a client an identifier matching the URL it used.+ expect(body['resource']).to end_with('/api/v3/admin/mcp')+ expect(URI.parse(body['resource']).origin).to eq(URI.parse(response.request.base_url).origin)expect(body['authorization_servers']).to be_presentexpect(body['bearer_methods_supported']).to eq(['header'])enddiff --git a/spree/core/app/models/spree/oauth_application.rb b/spree/core/app/models/spree/oauth_application.rbindex 2703d7a147..5586ba6ae1 100644--- a/spree/core/app/models/spree/oauth_application.rb+++ b/spree/core/app/models/spree/oauth_application.rb@@ -21,5 +21,32 @@ module Spreeforeign_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.+ has_many :live_access_tokens,+ -> { where(revoked_at: nil) },+ class_name: 'Spree::OauthAccessToken',+ foreign_key: :application_id,+ inverse_of: :application,+ dependent: nil++ # What this application may currently do, as permission keys.+ #+ # Read from the tokens rather than the registration: a client is+ # registered once and granted per consent, so the registration's own+ # `scopes` column stays empty.+ #+ # @return [Array<String>]+ def live_token_scopes+ live_access_tokens.flat_map { |token| token.scopes.to_a }.uniq.sort+ end++ # When this application was last granted a token that still works.+ #+ # @return [ActiveSupport::TimeWithZone, nil]+ def last_used_at+ live_access_tokens.map(&:created_at).max+ endendenddiff --git a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rbindex c57f51f41a..449b288735 100644--- a/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb+++ b/spree/mcp/app/controllers/spree/api/v3/admin/mcp_controller.rb@@ -109,10 +109,10 @@ module Spree# RFC 6750: the challenge names where to discover the authorization# server, which is how a consumer client starts its own sign-in.#- # Both URLs are built from the store, so they carry the same scheme- # and host by construction. A client compares their origins, and- # http-versus-https is enough for it to decide the document- # describes a different resource and stop.+ # Both URLs are built from the origin this request arrived on, so+ # they match what the client used and each other. A client compares+ # them, and a different scheme or host is enough for it to decide+ # the document describes another resource and stop.## No `scope`: it is a SHOULD, and listing every grantable key makes# a header several kilobytes long. A client reads the real list from@@ -120,8 +120,8 @@ module Spreedef oauth_challengeformat('Bearer realm="%<realm>s", resource_metadata="%<metadata>s"',- realm: Spree::Api::Oauth.resource_identifier(:mcp, current_store),- metadata: "#{current_store.formatted_url}/api/v3/oauth/protected-resource/mcp"+ realm: Spree::Api::Oauth.resource_identifier(:mcp, request.base_url),+ metadata: "#{request.base_url}/api/v3/oauth/protected-resource/mcp")end@@ -172,11 +172,18 @@ module Spree# whole point of the audience is that a token minted for another# resource cannot be replayed against this one, and a token with no# audience cannot be shown to have been issued for this endpoint.+ # Compared by path: a token minted through one hostname must keep+ # working through another the same deployment answers on, while a+ # token naming a different resource entirely is still refused.def audience_matches?(token)- expected = Spree::Api::Oauth.resource_identifier(:mcp, current_store)+ expected = Spree::Api::Oauth.resources[:mcp]return false if expected.blank?- token.resource.to_s.split.include?(expected)+ token.resource.to_s.split.any? do |indicator|+ URI.parse(indicator).path == expected+ rescue URI::InvalidURIError+ false+ endenddef oauth_resource_ownerdiff --git a/spree/mcp/lib/spree/mcp/engine.rb b/spree/mcp/lib/spree/mcp/engine.rbindex 205ee7949c..8e7c496320 100644--- a/spree/mcp/lib/spree/mcp/engine.rb+++ b/spree/mcp/lib/spree/mcp/engine.rb@@ -6,12 +6,9 @@ module Spree# Declares this endpoint as an OAuth protected resource, so a token can# be audience-bound to it and a client can discover the authorization- # server from a 401 here. The identifier must be the URL a client was- # pointed at, path included, or a consumer client refuses to continue.+ # server from a 401 here.initializer 'spree.mcp.oauth_resource' do- Spree::Api::Oauth.register_resource(:mcp) do |store|- "#{store.formatted_url}/api/v3/admin/mcp"- end+ Spree::Api::Oauth.register_resource(:mcp, '/api/v3/admin/mcp')endendenddiff --git a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rbindex 12737b47fc..5af5af4fa1 100644--- a/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb+++ b/spree/mcp/spec/requests/spree/api/v3/admin/mcp_spec.rb@@ -114,7 +114,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do# do, and a token issued for some other resource cannot be replayed here.describe 'OAuth authentication' dolet(:admin) { create(:admin_user) }- let(:resource) { Spree::Api::Oauth.resource_identifier(:mcp, store) }+ let(:resource) { Spree::Api::Oauth.resource_identifier(:mcp) }let(:application) dostore.oauth_applications.create!(name: 'Probe', redirect_uri: 'https://example.test/callback', confidential: false@@ -181,9 +181,8 @@ RSpec.describe 'Admin MCP endpoint', type: :request doend# An MCP client sends a URL and a bearer token and nothing else, so the- # token has to select its own store: measured against the default store's- # resource identifier, every other store's token would fail its audience- # check and the endpoint would be single-store in practice.+ # token has to select its own store — otherwise the endpoint would serve+ # the default store whatever the grant said.it 'serves the store its application belongs to, with no store header' doother = create(:store, code: "other-#{SecureRandom.hex(4)}")application = other.oauth_applications.create!(@@ -191,7 +190,7 @@ RSpec.describe 'Admin MCP endpoint', type: :request do)raw = Spree::OauthAccessToken.create!(application: application, resource_owner: admin, scopes: 'read_products',- expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.resource_identifier(:mcp, other)+ expires_in: 2.hours.to_i, resource: Spree::Api::Oauth.resource_identifier(:mcp)).tokenbody = post_with_token(raw)