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
Added registering and editing OAuth clients from the dashboard
Damian Legawiec53a0bdb2c585
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex aa7813ddb5..eea9505519 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -5964,20 +5964,8 @@ export class AdminClient {deny: (params: OauthAuthorizationParams, options?: RequestOptions): Promise<OauthRedirect> =>this.request<OauthRedirect>('DELETE', '/oauth/authorize', { ...options, body: params }),- /** Applications a merchant has connected, for the revoke screen. */+ /** The OAuth clients registered against this store. */applications: {- /**- * Every client registered for this store, connected or not. A merchant- * needs the id of one they have not connected yet, which is exactly- * what `list` leaves out.- */- registrations: (options?: RequestOptions): Promise<{ data: OauthApplication[] }> =>- this.request<{ data: OauthApplication[] }>(- 'GET',- '/oauth/applications/registrations',- options ?? {},- ),-list: (params?: ListParams & Record<string, unknown>,options?: RequestOptions,@@ -5987,13 +5975,38 @@ export class AdminClient {params: params ? transformListParams(params) : undefined,}),+ get: (id: string, options?: RequestOptions): Promise<OauthApplication> =>+ this.request<OauthApplication>('GET', `/oauth/applications/${id}`, options ?? {}),++ create: (+ params: { name: string; redirect_uri: string },+ options?: RequestOptions,+ ): Promise<OauthApplication> =>+ this.request<OauthApplication>('POST', '/oauth/applications', {+ ...options,+ body: params,+ }),++ update: (+ id: string,+ params: Partial<{ name: string; redirect_uri: string }>,+ options?: RequestOptions,+ ): Promise<OauthApplication> =>+ this.request<OauthApplication>('PATCH', `/oauth/applications/${id}`, {+ ...options,+ body: params,+ }),++ /** Removes the registration, and every grant and token with it. */+ delete: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/oauth/applications/${id}`, options ?? {}),+/**- * Revokes every live token and grant an application holds. The- * registration itself is kept, so a merchant can reconnect without the- * client being re-registered.+ * Revokes every live token and grant an application holds, keeping the+ * registration so a merchant can connect the same client again.*/revoke: (id: string, options?: RequestOptions): Promise<void> =>- this.request<void>('DELETE', `/oauth/applications/${id}`, options ?? {}),+ this.request<void>('DELETE', `/oauth/applications/${id}/tokens`, options ?? {}),},}diff --git a/packages/dashboard/src/components/spree/oauth-application-sheet.tsx b/packages/dashboard/src/components/spree/oauth-application-sheet.tsxnew file mode 100644index 0000000000..5b3079c5d8--- /dev/null+++ b/packages/dashboard/src/components/spree/oauth-application-sheet.tsx@@ -0,0 +1,137 @@+import type { OauthApplication } from '@spree/admin-sdk'+import { adminClient, mapSpreeErrorsToForm } from '@spree/dashboard-core'+import {+ Button,+ Field,+ FieldError,+ Input,+ Label,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle,+} from '@spree/dashboard-ui'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { useEffect } from 'react'+import { useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'++interface FormValues {+ name: string+ redirect_uri: string+}++/**+ * Registers an OAuth client, or edits one already registered.+ *+ * The callback comes from the client's own documentation — it is where+ * authorization codes are delivered, so a wrong one sends them to whoever+ * controls that host. The field says as much rather than leaving a merchant+ * to guess, and the server refuses anything that is not https.+ */+export function OauthApplicationSheet({+ application,+ open,+ onOpenChange,+}: {+ application?: OauthApplication+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const form = useForm<FormValues>({ defaultValues: { name: '', redirect_uri: '' } })++ useEffect(() => {+ if (!open) return+ form.reset({+ name: application?.name ?? '',+ redirect_uri: application?.redirect_uri ?? '',+ })+ }, [open, application, form])++ const save = useMutation({+ mutationFn: (values: FormValues) =>+ application+ ? adminClient.oauth.applications.update(application.id, values)+ : adminClient.oauth.applications.create(values),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['oauth-applications'] })+ onOpenChange(false)+ },+ })++ async function onSubmit(values: FormValues) {+ try {+ await save.mutateAsync(values)+ } catch (error) {+ if (!mapSpreeErrorsToForm(error, form.setError)) throw error+ }+ }++ return (+ <Sheet open={open} onOpenChange={onOpenChange}>+ <SheetContent>+ <SheetHeader>+ <SheetTitle>+ {application+ ? t('admin.pages.settings.connected_apps.form.edit_title')+ : t('admin.pages.settings.connected_apps.form.create_title')}+ </SheetTitle>+ <SheetDescription>+ {t('admin.pages.settings.connected_apps.form.description')}+ </SheetDescription>+ </SheetHeader>++ <form+ className="flex flex-1 flex-col gap-4 overflow-y-auto px-4"+ onSubmit={form.handleSubmit(onSubmit)}+ >+ {form.formState.errors.root && (+ <p className="text-destructive text-sm">{form.formState.errors.root.message}</p>+ )}++ <Field>+ <Label htmlFor="oauth-application-name">+ {t('admin.fields.oauth_application.name.label')}+ </Label>+ <Input+ id="oauth-application-name"+ {...form.register('name', { required: true })}+ aria-invalid={Boolean(form.formState.errors.name)}+ placeholder={t('admin.fields.oauth_application.name.placeholder')}+ />+ <FieldError>{form.formState.errors.name?.message}</FieldError>+ </Field>++ <Field>+ <Label htmlFor="oauth-application-redirect-uri">+ {t('admin.fields.oauth_application.redirect_uri.label')}+ </Label>+ <Input+ id="oauth-application-redirect-uri"+ {...form.register('redirect_uri', { required: true })}+ aria-invalid={Boolean(form.formState.errors.redirect_uri)}+ placeholder="https://example.com/oauth/callback"+ />+ <p className="text-muted-foreground text-xs">+ {t('admin.fields.oauth_application.redirect_uri.help')}+ </p>+ <FieldError>{form.formState.errors.redirect_uri?.message}</FieldError>+ </Field>++ <SheetFooter className="px-0">+ <Button type="submit" disabled={save.isPending}>+ {t('admin.common.save')}+ </Button>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.common.cancel')}+ </Button>+ </SheetFooter>+ </form>+ </SheetContent>+ </Sheet>+ )+}diff --git a/packages/dashboard/src/hooks/use-oauth.ts b/packages/dashboard/src/hooks/use-oauth.tsindex cf0680da54..241b04a14d 100644--- a/packages/dashboard/src/hooks/use-oauth.ts+++ b/packages/dashboard/src/hooks/use-oauth.ts@@ -40,21 +40,30 @@ export function useDenyOauthAuthorization() {}/**- * Every registered client, for the setup panel — unlike the connected list,- * which answers what to revoke.+ * Every client registered against this store. The connected ones are those+ * carrying live scopes, which the row renders from.*/-export function useOauthRegistrations() {+export function useOauthApplications() {return useQuery({- queryKey: useResourceKey('oauth-registrations'),- queryFn: () => adminClient.oauth.applications.registrations(),- staleTime: 30 * 60 * 1000,+ queryKey: useResourceKey('oauth-applications'),+ queryFn: () => adminClient.oauth.applications.list(),})}-export function useOauthApplications() {+/** Kept for the connect panel, which only needs the client ids. */+export function useOauthRegistrations() {return useQuery({queryKey: useResourceKey('oauth-applications'),queryFn: () => adminClient.oauth.applications.list(),+ staleTime: 30 * 60 * 1000,+ })+}++/** Removes the registration, and every grant and token with it. */+export function useDeleteOauthApplication() {+ return useResourceMutation<void, Error, string>({+ mutationFn: (id) => adminClient.oauth.applications.delete(id),+ invalidate: [['oauth-applications']],})}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex fa456ba62f..c328d0922d 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -2416,6 +2416,16 @@"label": "العلبة الافتراضية","help": "العلبة التي تُحسب على أساسها أسعار شحن طرودك. علبة افتراضية واحدة في كل مرة."}+ },+ "oauth_application": {+ "name": {+ "label": "الاسم",+ "placeholder": "Cursor"+ },+ "redirect_uri": {+ "label": "عنوان الاستدعاء",+ "help": "من وثائق العميل نفسه. تُسلَّم رموز التفويض هنا، لذا يجب أن يكون العنوان الذي ينشره العميل."+ }}},"gift_cards": {@@ -4136,6 +4146,16 @@"revoke_confirm": {"title": "إلغاء الوصول؟","message": "سيتوقف {{name}} عن العمل فورًا. وسيحتاج أي شخص يستخدمه إلى الاتصال من جديد."+ },+ "register": "تسجيل عميل",+ "form": {+ "create_title": "تسجيل عميل",+ "edit_title": "تعديل العميل",+ "description": "سجّل عميل OAuth حتى يمكن ربطه بهذا المتجر."+ },+ "delete_confirm": {+ "title": "حذف هذا العميل؟",+ "message": "سيتوقف {{name}} عن العمل فورًا وسيُحذف تسجيله."}}},diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 639f4451f3..568ad409fe 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -2398,6 +2398,16 @@"label": "Standardverpackung","help": "Die Verpackung, auf der Ihre Paketangebote basieren. Nur eine Standardverpackung gleichzeitig."}+ },+ "oauth_application": {+ "name": {+ "label": "Name",+ "placeholder": "Cursor"+ },+ "redirect_uri": {+ "label": "Callback-URL",+ "help": "Aus der Dokumentation des Clients. Autorisierungscodes werden hierhin geliefert, daher muss es die vom Client veröffentlichte Adresse sein."+ }}},"gift_cards": {@@ -4108,6 +4118,16 @@"revoke_confirm": {"title": "Zugriff widerrufen?","message": "{{name}} funktioniert ab sofort nicht mehr. Wer es nutzt, muss sich erneut verbinden."+ },+ "register": "Client registrieren",+ "form": {+ "create_title": "Client registrieren",+ "edit_title": "Client bearbeiten",+ "description": "Registrieren Sie einen OAuth-Client, damit er mit diesem Shop verbunden werden kann."+ },+ "delete_confirm": {+ "title": "Diesen Client löschen?",+ "message": "{{name}} funktioniert sofort nicht mehr und die Registrierung wird entfernt."}}},diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 76ee5c0972..fbeec39ec0 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -2398,6 +2398,16 @@"label": "Default box","help": "The packaging your parcel quotes are built on. One default at a time."}+ },+ "oauth_application": {+ "name": {+ "label": "Name",+ "placeholder": "Cursor"+ },+ "redirect_uri": {+ "label": "Callback URL",+ "help": "From the client’s own documentation. Authorization codes are delivered here, so it must be the address the client publishes."+ }}},"gift_cards": {@@ -4108,6 +4118,16 @@"revoke_confirm": {"title": "Revoke access?","message": "{{name}} will stop working immediately. Anyone using it will need to connect again."+ },+ "register": "Register a client",+ "form": {+ "create_title": "Register a client",+ "edit_title": "Edit client",+ "description": "Register an OAuth client so it can be connected to this store."+ },+ "delete_confirm": {+ "title": "Delete this client?",+ "message": "{{name}} will stop working immediately and its registration will be removed."}}},diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 98084dd37a..8452feb485 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -734,6 +734,16 @@"revoke_confirm": {"title": "¿Revocar el acceso?","message": "{{name}} dejará de funcionar de inmediato. Quien lo use tendrá que conectarse de nuevo."+ },+ "register": "Registrar un cliente",+ "form": {+ "create_title": "Registrar un cliente",+ "edit_title": "Editar cliente",+ "description": "Registre un cliente OAuth para poder conectarlo a esta tienda."+ },+ "delete_confirm": {+ "title": "¿Eliminar este cliente?",+ "message": "{{name}} dejará de funcionar de inmediato y se eliminará su registro."}}},@@ -2467,6 +2477,16 @@"label": "Caja predeterminada","help": "El empaque sobre el que se calculan tus cotizaciones de paquetería. Solo una predeterminada a la vez."}+ },+ "oauth_application": {+ "name": {+ "label": "Nombre",+ "placeholder": "Cursor"+ },+ "redirect_uri": {+ "label": "URL de retorno",+ "help": "De la documentación del propio cliente. Los códigos de autorización se entregan aquí, así que debe ser la dirección que el cliente publica."+ }}},"orders": {diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex a16524e14c..4ee1f28fb6 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -2398,6 +2398,16 @@"label": "Emballage par défaut","help": "L'emballage sur lequel vos tarifs de colis sont calculés. Un seul par défaut à la fois."}+ },+ "oauth_application": {+ "name": {+ "label": "Nom",+ "placeholder": "Cursor"+ },+ "redirect_uri": {+ "label": "URL de rappel",+ "help": "Issue de la documentation du client. Les codes d'autorisation y sont livrés : ce doit être l'adresse publiée par le client."+ }}},"gift_cards": {@@ -4108,6 +4118,16 @@"revoke_confirm": {"title": "Révoquer l’accès ?","message": "{{name}} cessera de fonctionner immédiatement. Toute personne qui l’utilise devra se connecter à nouveau."+ },+ "register": "Enregistrer un client",+ "form": {+ "create_title": "Enregistrer un client",+ "edit_title": "Modifier le client",+ "description": "Enregistrez un client OAuth pour pouvoir le connecter à cette boutique."+ },+ "delete_confirm": {+ "title": "Supprimer ce client ?",+ "message": "{{name}} cessera de fonctionner immédiatement et son enregistrement sera supprimé."}}},diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 4f5d77d7a3..d73392055c 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -2416,6 +2416,16 @@"label": "Domyślne opakowanie","help": "Opakowanie, na którym opierają się wyceny Twoich przesyłek. Tylko jedno domyślne naraz."}+ },+ "oauth_application": {+ "name": {+ "label": "Nazwa",+ "placeholder": "Cursor"+ },+ "redirect_uri": {+ "label": "Adres zwrotny",+ "help": "Z dokumentacji samego klienta. Tu trafiają kody autoryzacyjne, więc musi to być adres publikowany przez klienta."+ }}},"gift_cards": {@@ -4162,6 +4172,16 @@"revoke_confirm": {"title": "Odebrać dostęp?","message": "{{name}} przestanie działać natychmiast. Każdy, kto z niej korzysta, będzie musiał połączyć się ponownie."+ },+ "register": "Zarejestruj klienta",+ "form": {+ "create_title": "Zarejestruj klienta",+ "edit_title": "Edytuj klienta",+ "description": "Zarejestruj klienta OAuth, aby można go było połączyć z tym sklepem."+ },+ "delete_confirm": {+ "title": "Usunąć tego klienta?",+ "message": "{{name}} przestanie działać natychmiast, a jego rejestracja zostanie usunięta."}}},diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 6aaf70588a..0ef955d19a 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -2393,6 +2393,16 @@"label": "默认包装","help": "您的包裹报价所依据的包装。同一时间只能有一个默认包装。"}+ },+ "oauth_application": {+ "name": {+ "label": "名称",+ "placeholder": "Cursor"+ },+ "redirect_uri": {+ "label": "回调地址",+ "help": "来自客户端自己的文档。授权码会发送到这里,因此必须是客户端公布的地址。"+ }}},"gift_cards": {@@ -4098,6 +4108,16 @@"revoke_confirm": {"title": "撤销访问权限?","message": "{{name}} 将立即停止工作。使用它的人需要重新连接。"+ },+ "register": "注册客户端",+ "form": {+ "create_title": "注册客户端",+ "edit_title": "编辑客户端",+ "description": "注册 OAuth 客户端后即可将其连接到此店铺。"+ },+ "delete_confirm": {+ "title": "删除此客户端?",+ "message": "{{name}} 将立即停止工作,其注册记录也会被删除。"}}},diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsxindex 52c262527f..fe04af0a63 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx@@ -12,7 +12,8 @@ import { createFileRoute } from '@tanstack/react-router'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { McpConnectSheet } from '../../../../components/spree/mcp-connect-sheet'-import { useRevokeOauthApplication } from '../../../../hooks/use-oauth'+import { OauthApplicationSheet } from '../../../../components/spree/oauth-application-sheet'+import { useDeleteOauthApplication, useRevokeOauthApplication } from '../../../../hooks/use-oauth'import '../../../../tables/oauth-applications'export const Route = createFileRoute('/_authenticated/$storeId/settings/connected-apps')({@@ -27,6 +28,28 @@ function ConnectedAppsSettingsPage() {const revoke = useRevokeOauthApplication()const { permissions } = usePermissions()const [connectOpen, setConnectOpen] = useState(false)+ const [editing, setEditing] = useState<OauthApplication | undefined>()+ const [formOpen, setFormOpen] = useState(false)+ const remove = useDeleteOauthApplication()++ function openForm(application?: OauthApplication) {+ setEditing(application)+ setFormOpen(true)+ }++ async function handleDelete(application: OauthApplication) {+ const ok = await confirm({+ title: t('admin.pages.settings.connected_apps.delete_confirm.title'),+ message: t('admin.pages.settings.connected_apps.delete_confirm.message', {+ name: application.name,+ }),+ variant: 'destructive',+ confirmLabel: t('admin.common.delete'),+ })+ if (!ok) return++ await remove.mutateAsync(application.id).catch(() => undefined)+ }async function handleRevoke(application: OauthApplication) {const ok = await confirm({@@ -48,13 +71,28 @@ function ConnectedAppsSettingsPage() {title={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>+ <div className="flex gap-2">+ {permissions.can('update', Subject.OauthApplication) && (+ <Button size="sm" variant="outline" onClick={() => openForm()}>+ {t('admin.pages.settings.connected_apps.register')}+ </Button>+ )}+ <Button size="sm" onClick={() => setConnectOpen(true)}>+ {t('admin.mcp_connect.open_cta')}+ </Button>+ </div>}/><McpConnectSheet open={connectOpen} onOpenChange={setConnectOpen} />+ <OauthApplicationSheet+ application={editing}+ open={formOpen}+ onOpenChange={(next) => {+ setFormOpen(next)+ if (!next) setEditing(undefined)+ }}+ /><ResourceTable<OauthApplication>tableKey="oauth-applications"@@ -65,6 +103,12 @@ function ConnectedAppsSettingsPage() {rowActions={(application) => (<RowActionsactions={[+ {+ key: 'edit',+ label: t('admin.common.edit'),+ visible: permissions.can('update', Subject.OauthApplication),+ onSelect: () => openForm(application),+ },{key: 'revoke',label: t('admin.pages.settings.connected_apps.revoke'),@@ -73,6 +117,14 @@ function ConnectedAppsSettingsPage() {disabled: revoke.isPending,onSelect: () => handleRevoke(application),},+ {+ key: 'delete',+ label: t('admin.common.delete'),+ destructive: true,+ visible: permissions.can('destroy', Subject.OauthApplication),+ disabled: remove.isPending,+ onSelect: () => handleDelete(application),+ },]}/>)}diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/application_tokens_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/application_tokens_controller.rbnew file mode 100644index 0000000000..131345fdcf--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/application_tokens_controller.rb@@ -0,0 +1,29 @@+module Spree+ module Api+ module V3+ module Admin+ module Oauth+ # A connected client's live credentials.+ #+ # Revoking is deleting these, not deleting the application: the+ # registration stays so the merchant can connect the same client+ # again, while anything still holding a token stops working on its+ # next call.+ class ApplicationTokensController < Spree::Api::V3::Admin::BaseController+ scoped_resource :agents++ def destroy+ application = current_store.oauth_applications.find_by_prefix_id!(params[:application_id])+ authorize! :update, application++ application.access_tokens.where(revoked_at: nil).update_all(revoked_at: Time.current)+ application.access_grants.where(revoked_at: nil).update_all(revoked_at: Time.current)++ head :no_content+ end+ end+ end+ end+ end+ end+enddiff --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 bb4e5242ed..bd87688387 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@@ -10,72 +10,38 @@ module Spree# every live token and grant rather than deleting the registration,# so a client that still holds a token stops working on its next# call.- class ApplicationsController < Spree::Api::V3::Admin::BaseController+ class ApplicationsController < Spree::Api::V3::Admin::ResourceController# Its own permission rather than store configuration: a standing# credential to the back office is not the same kind of thing as# a delivery zone.scoped_resource :agents- def index- # Only applications somebody actually authorized — a registered- # client nobody connected is not a connection. Tokens and their- # owners are preloaded because the serializer reads each- # application's scopes, last use and who approved it from them.- scope = current_store.oauth_applications.- where(id: connected_application_ids).- includes(live_access_tokens: :resource_owner).- order(:name)+ protected- @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- }- }+ def model_class+ Spree::OauthApplicationend- # Every client registered for this store, connected or not — a- # merchant needs the id of one they have not connected yet, which- # is precisely what `index` leaves out.- def registrations- applications = current_store.oauth_applications.- includes(live_access_tokens: :resource_owner).- order(:name)-- render json: {- data: Spree.api.admin_oauth_application_serializer.new(applications).serializable_hash- }+ def serializer_class+ Spree.api.admin_oauth_application_serializerend- def destroy- application = current_store.oauth_applications.find_by_prefix_id!(params[:id])-- authorize! :update, Spree::OauthApplication-- application.access_tokens.where(revoked_at: nil).update_all(revoked_at: Time.current)- application.access_grants.where(revoked_at: nil).update_all(revoked_at: Time.current)-- head :no_content+ def scope+ super.order(:name)end- private+ # The serializer reads each application's scopes, last+ # authorization and who approved it from the live tokens.+ def collection_includes+ { live_access_tokens: :resource_owner }+ end- # Applications that can still reach the store, as a subquery so- # nothing is loaded just to be counted.- #- # Revocation, not expiry, is the test: a refresh token outlives- # the access token beside it, so an application whose access has- # lapsed can mint more. Hiding it here would leave a merchant- # unable to revoke something that still works.- 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)).- select(:application_id)+ # `confidential` is not writable: these are hosted connectors that+ # cannot keep a secret, which is why PKCE is mandatory. `scopes`+ # is not writable either — what a client may do is granted by the+ # merchant at consent, not fixed at registration.+ def resource_permitted_attributes+ %i[name redirect_uri]endendenddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex ce3af7bb45..b3d8aae7ad 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -246,8 +246,11 @@ Spree::Core::Engine.add_routes dopost 'authorize', to: 'authorizations#create'delete 'authorize', to: 'authorizations#destroy'- resources :applications, only: %i[index destroy] do- get :registrations, on: :collection+ # The OAuth clients registered against this store. Deleting one+ # removes the registration; revoking a connection is the nested+ # `tokens` resource, because that is what revoking deletes.+ resources :applications do+ resource :tokens, only: :destroy, controller: 'application_tokens'endenddiff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rbindex 250442d9fe..2d2626f442 100644--- a/spree/api/lib/spree/api/oauth.rb+++ b/spree/api/lib/spree/api/oauth.rb@@ -145,6 +145,12 @@ module Spree# nothing against an intercepted code.pkce_code_challenge_methods %w[S256]+ # A redirect URI is where authorization codes are delivered, so a+ # plain-http one hands them to anyone on the path. Off in+ # development, where a local client has no certificate and the+ # traffic never leaves the machine.+ force_ssl_in_redirect_uri !Rails.env.development?+# 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.diff --git a/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb b/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rbindex 044bf2f83e..2d10f633f8 100644--- a/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb+++ b/spree/api/spec/requests/spree/api/v3/admin/oauth/applications_spec.rb@@ -56,19 +56,23 @@ RSpec.describe 'Admin connected applications', type: :request doexpect(list['data'].map { |row| row['name'] }).to include('Claude')end- it 'drops it once revoked' do- token_for(admin).update!(revoked_at: Time.current)-- expect(list['data']).to be_empty- end-- it 'lists only applications somebody actually connected' do+ # The listing is every registered client, connected or not — a merchant+ # needs the one they have not connected yet as much as the one they have.+ # Whether a row is connected is what its live scopes say.+ it 'lists a registration nobody has connected' dostore.oauth_applications.create!(name: 'Never connected', redirect_uri: 'https://example.test/cb', confidential: false)token_for(admin)- expect(list['data'].map { |row| row['name'] }).to contain_exactly('Claude')+ expect(list['data'].map { |row| row['name'] }).to include('Claude', 'Never connected')+ end++ it 'reports no scopes for one whose access was revoked' do+ token_for(admin).update!(revoked_at: Time.current)++ row = list['data'].find { |candidate| candidate['name'] == 'Claude' }+ expect(row['scopes']).to be_emptyendit 'reports what the live tokens grant, not the registration' do@@ -83,11 +87,14 @@ RSpec.describe 'Admin connected applications', type: :request doexpect(list['meta']).to include('page', 'count', 'pages')end+ # Revoking and deleting are different operations on different things, which+ # is why revoking is the nested tokens resource: it deletes the credentials,+ # not the client.describe 'revoking' doit 'stops the application working without deleting its registration' doraw = token_for(admin).plaintext_token- delete "/api/v3/admin/oauth/applications/#{application.prefixed_id}",+ delete "/api/v3/admin/oauth/applications/#{application.prefixed_id}/tokens",headers: { 'X-Spree-API-Key' => api_key.plaintext_token }expect(response).to have_http_status(:no_content)@@ -95,4 +102,24 @@ RSpec.describe 'Admin connected applications', type: :request doexpect(store.oauth_applications.find_by(name: 'Claude')).to be_presentendend++ describe 'registering a client' do+ it 'creates one from a name and a callback' do+ post '/api/v3/admin/oauth/applications',+ params: { name: 'Cursor', redirect_uri: 'https://cursor.com/oauth/callback' },+ headers: { 'X-Spree-API-Key' => api_key.plaintext_token }++ expect(response).to have_http_status(:created)+ expect(store.oauth_applications.find_by(name: 'Cursor')).to be_present+ end++ # Deleting the client takes its credentials with it, unlike revoking.+ it 'deletes the registration itself' do+ delete "/api/v3/admin/oauth/applications/#{application.prefixed_id}",+ headers: { 'X-Spree-API-Key' => api_key.plaintext_token }++ expect(response).to have_http_status(:no_content)+ expect(store.oauth_applications.find_by(name: 'Claude')).to be_nil+ end+ endenddiff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 2dd06e6541..e5741705c9 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -613,8 +613,10 @@ en:messages:already_confirmed: was already confirmedforbidden_reporting_member: references data you are not allowed to read+ fragment_present: cannot contain a fragmentinvalid_document_number_affix: 'can only contain uppercase letters, digits, dashes and #'invalid_system_key: can only contain lowercase letters, digits and underscores+ invalid_uri: must be a valid URLlocked_after_first_number: cannot change once numbering has startednot_a_number: is not a numbernot_found: not found@@ -622,7 +624,10 @@ en:not_saved:one: '1 error prohibited this %{resource} from being saved:'other: "%{count} errors prohibited this %{resource} from being saved:"+ relative_uri: must be an absolute URL+ secured_uri: must start with https, because authorization codes are delivered to itseeded_report_read_only: is a built-in report and cannot be changed — save a copy instead+ unspecified_scheme: must include a scheme, such as httpsnumber:currency:format: