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
Simplified the OAuth layer after review
Damian Legawiecbcd9878b90ae
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 7449473a36..ad53848065 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -5966,8 +5966,8 @@ export class AdminClient {/** Applications a merchant has connected, for the revoke screen. */applications: {- list: (options?: RequestOptions): Promise<OauthApplication[]> =>- this.request<OauthApplication[]>('GET', '/oauth/applications', options ?? {}),+ list: (options?: RequestOptions): Promise<{ data: OauthApplication[] }> =>+ this.request<{ data: OauthApplication[] }>('GET', '/oauth/applications', options ?? {}),/*** Revokes every live token and grant an application holds. Thediff --git a/packages/dashboard/src/hooks/use-oauth.ts b/packages/dashboard/src/hooks/use-oauth.tsindex f2b44dab76..a019f54fb1 100644--- a/packages/dashboard/src/hooks/use-oauth.ts+++ b/packages/dashboard/src/hooks/use-oauth.ts@@ -1,5 +1,4 @@import type {- OauthApplication,OauthAuthorizationParams,OauthAuthorizationRequest,OauthRedirect,@@ -41,7 +40,7 @@ export function useDenyOauthAuthorization() {}export function useOauthApplications() {- return useQuery<OauthApplication[]>({+ return useQuery({queryKey: useResourceKey('oauth-applications'),queryFn: () => adminClient.oauth.applications.list(),})@@ -52,6 +51,7 @@ export function useRevokeOauthApplication() {mutationFn: (id) => adminClient.oauth.applications.revoke(id),invalidate: [['oauth-applications']],successMessage: false,- errorMessage: false,+ // A failed revoke has no inline form to report into, and the row simply+ // staying put reads as success — so this one does toast.})}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsxindex 741641ce09..bba91d88fe 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/oauth/authorize.tsx@@ -4,6 +4,7 @@ import { CheckIcon, ShieldIcon } from '@spree/dashboard-ui/icons'import { createFileRoute } from '@tanstack/react-router'import { useTranslation } from 'react-i18next'import { z } from 'zod'+import { permissionKeyLabel } from '../../../../components/spree/permission-picker'import {useApproveOauthAuthorization,useDenyOauthAuthorization,@@ -44,7 +45,6 @@ function OauthAuthorizePage() {window.location.href = redirectUri}- const describe = (key: string) => catalog?.data.find((permission) => permission.key === key)const pending = approve.isPending || deny.isPendingreturn (@@ -82,23 +82,15 @@ function OauthAuthorizePage() {{t('admin.pages.oauth.authorize.permissions_heading')}</h2><ul className="flex flex-col gap-2">- {data.scopes.map((key) => {- const permission = describe(key)-- return (- <li key={key} className="flex items-start gap-2 text-sm">- <CheckIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />- <span>- {permission?.label ?? key}- {permission?.description ? (- <span className="block text-muted-foreground text-xs">- {permission.description}- </span>- ) : null}- </span>- </li>- )- })}+ {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+ merchant what they are granting follows their own+ language, not the server's. */}+ <span>{permissionKeyLabel(t, catalog?.data, key)}</span>+ </li>+ ))}</ul></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 5dd795a5c5..b9d424d087 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/connected-apps.tsx@@ -2,9 +2,10 @@ import type { OauthApplication } from '@spree/admin-sdk'import { PageHeader, Subject, usePermissions } from '@spree/dashboard-core'import {Badge,- Button,Card,CardContent,+ RelativeTime,+ RowActions,Skeleton,Table,TableBody,@@ -23,18 +24,15 @@ export const Route = createFileRoute('/_authenticated/$storeId/settings/connecte})function ConnectedAppsSettingsPage() {- const { t, i18n } = useTranslation()+ const { t } = useTranslation()const confirm = useConfirm()const { data, isLoading } = useOauthApplications()const revoke = useRevokeOauthApplication()const { permissions } = usePermissions()- const applications = data ?? []+ const applications = data?.data ?? []const canRevoke = permissions.can('update', Subject.Store)- const formatDate = (value: string | null) =>- value ? new Date(value).toLocaleDateString(i18n.language) : '—'-async function handleRevoke(application: OauthApplication) {const ok = await confirm({title: t('admin.pages.settings.connected_apps.revoke_confirm.title'),@@ -95,19 +93,21 @@ function ConnectedAppsSettingsPage() {</div></TableCell><TableCell className="text-muted-foreground">- {formatDate(application.last_used_at)}+ <RelativeTime iso={application.last_used_at} /></TableCell><TableCell className="text-right">- {canRevoke ? (- <Button- variant="ghost"- size="sm"- disabled={revoke.isPending}- onClick={() => handleRevoke(application)}- >- {t('admin.pages.settings.connected_apps.revoke')}- </Button>- ) : null}+ <RowActions+ actions={[+ {+ key: 'revoke',+ label: t('admin.pages.settings.connected_apps.revoke'),+ destructive: true,+ visible: canRevoke,+ disabled: revoke.isPending,+ onSelect: () => handleRevoke(application),+ },+ ]}+ /></TableCell></TableRow>))}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 8968ea2342..1b5268890c 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@@ -16,10 +16,10 @@ module Spreedef indexapplications = current_store.oauth_applications.- where(id: connected_application_ids).+ where(id: live_tokens_by_application.keys).order(:name)- render json: applications.map { |application| serialize(application) }+ render json: { data: applications.map { |application| serialize(application) } }enddef destroy@@ -35,14 +35,6 @@ module Spreeprivate- # Only applications somebody actually authorized — a registered- # client nobody connected is not a connection.- def connected_application_ids- Spree::OauthAccessToken.where(revoked_at: nil).- where(resource_owner_type: Spree.admin_user_class.name).- select(:application_id)- end-# 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@@ -59,10 +51,15 @@ module Spree}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.where(revoked_at: nil).- where(resource_owner_type: Spree.admin_user_class.name).+ 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)endenddiff --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 51211fa117..24ccb8e746 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@@ -92,17 +92,15 @@ module Spreedef pre_authorization_paramsparams.permit(:client_id, :redirect_uri, :response_type, :state, :scope,- :code_challenge, :code_challenge_method, :response_mode,- resource: []- ).to_h.symbolize_keys.tap do |permitted|- scalar = params[:resource]- permitted[:resource] = scalar if scalar.is_a?(String) && scalar.present?- end+ :code_challenge, :code_challenge_method, :response_mode+ ).to_h.symbolize_keys.+ # Carried through raw: RFC 8707 allows one value or several,+ # and Doorkeeper's own validator normalizes both shapes.+ merge(resource: params[:resource])enddef requested_resource- resource = @pre_auth.try(:resource)- Array(resource).first+ @pre_auth.resource_indicators&.firstend# Every capability the requested scopes imply, so a merchant seesdiff --git a/spree/api/lib/spree/api/engine.rb b/spree/api/lib/spree/api/engine.rbindex 32c8e0f170..d0ea5eaf81 100644--- a/spree/api/lib/spree/api/engine.rb+++ b/spree/api/lib/spree/api/engine.rb@@ -28,6 +28,13 @@ module SpreeSpree::Api::Oauth.configure!end+ # Extensions register their permission scopes from config initializers,+ # which run after the configuration above — so the grantable list is+ # re-read once they have.+ config.after_initialize do+ Spree::Api::Oauth.refresh_scopes!+ end+initializer 'spree.api.request_size_limit' do |app|require_relative 'middleware/request_size_limit'app.middleware.insert_before Rack::Runtime, Spree::Api::Middleware::RequestSizeLimitdiff --git a/spree/api/lib/spree/api/oauth.rb b/spree/api/lib/spree/api/oauth.rbindex 4f45504e03..127098de95 100644--- a/spree/api/lib/spree/api/oauth.rb+++ b/spree/api/lib/spree/api/oauth.rb@@ -48,6 +48,46 @@ module Spreeresources[key.to_sym]&.call(store)end+ # The grantable scope list, re-read after host and extension+ # initializers have run.+ #+ # `optional_scopes` builds its value eagerly, and an extension+ # registers its scopes from a config initializer — which runs after+ # {.configure!}, because a host's own `doorkeeper.rb` has to be able+ # to win. Without this second pass the vocabulary would be whatever+ # core shipped, and an extension's keys could never be granted.+ def refresh_scopes!+ ::Doorkeeper.config.instance_variable_set(+ :@optional_scopes,+ ::Doorkeeper::OAuth::Scopes.from_array(staff_scope_keys)+ )+ end++ # @return [Array<String>]+ def staff_scope_keys+ Spree.permissions.grantable_keys(Spree::PermissionConfiguration::STAFF_AUDIENCE)+ end++ # Whether every requested audience belongs to the client's own store.+ #+ # 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.+ #+ # @param requested [Array<String>] the `resource` values asked for+ # @param client [Object] Doorkeeper's client wrapper+ # @return [Boolean]+ def indicators_valid?(requested, client)+ 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) }+ end+def configure!::Doorkeeper.configure doorm :active_record@@ -81,21 +121,15 @@ 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|- allowed = Spree::Store.all.flat_map do |store|- Spree::Api::Oauth.resource_identifiers(store)- end- requested.any? && requested.all? { |indicator| allowed.include?(indicator) }+ resource_indicator_validator(lambda do |requested, client|+ Spree::Api::Oauth.indicators_valid?(requested, client)end)# Spree's own permission catalog is the scope vocabulary, so a# grant carries the same keys an API key would and the tool- # registry needs no translation. Resolved at configuration time- # from the catalog rather than hardcoded, so a scope an extension- # registers is grantable without touching this.- optional_scopes(*Spree.permissions.grantable_keys(- Spree::PermissionConfiguration::STAFF_AUDIENCE- ))+ # registry needs no translation. Seeded here and re-read in+ # `refresh_scopes!` once extensions have registered theirs.+ optional_scopes(*Spree::Api::Oauth.staff_scope_keys)use_refresh_token# One live token per authorization, so re-consenting does notdiff --git a/spree/core/app/models/spree/oauth_application.rb b/spree/core/app/models/spree/oauth_application.rbindex a27e2ae4bb..2703d7a147 100644--- a/spree/core/app/models/spree/oauth_application.rb+++ b/spree/core/app/models/spree/oauth_application.rb@@ -21,14 +21,5 @@ module Spreeforeign_key: :application_id,dependent: :destroy- # When this application was last granted a token that is still live.- # Revoked and expired tokens are excluded, so a merchant who has just- # revoked an app does not see a recent timestamp suggesting it still- # works.- #- # @return [ActiveSupport::TimeWithZone, nil]- def last_used_at- access_tokens.where(revoked_at: nil).maximum(:created_at)- endendenddiff --git a/spree/core/lib/spree/agent_tools/context.rb b/spree/core/lib/spree/agent_tools/context.rbindex a6d7ab5e44..60d5a625c9 100644--- a/spree/core/lib/spree/agent_tools/context.rb+++ b/spree/core/lib/spree/agent_tools/context.rb@@ -116,10 +116,10 @@ module Spreescope = Spree.permissions.scope_for_resource(record.is_a?(Class) ? record : record.class)return true if scope.nil?- write = !%i[read show index].include?(action.to_sym)- key = "#{write ? 'write' : 'read'}_#{scope.name}"- permission_keys.include?(key) ||- (!write && permission_keys.include?("write_#{scope.name}"))+ # A write key always expands to its read key, so checking the one the+ # action needs is the whole answer.+ kind = %i[read show index].include?(action.to_sym) ? 'read' : 'write'+ permission_keys.include?("#{kind}_#{scope.name}")end# Whether the caller holds a permission a tool *declares*.diff --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 c11d6416e4..c57f51f41a 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@@ -47,7 +47,7 @@ module Spree# confirmed it was issued for this store's endpoint, which is the# same assurance `require_store_membership!` gives a JWT.def authenticate_admin!- return super if oauth_token.blank?+ return super if current_oauth_token.blank?owner = oauth_resource_ownerreturn false if owner.nil?@@ -95,11 +95,11 @@ module Spree# is its scopes; a token's is the admin user's own permissions,# resolved fresh here rather than frozen when the token was issued.def agent_context- if oauth_token.present?+ if current_oauth_token.present?Spree::AgentTools::Context.new(store: current_store,user: oauth_resource_owner,- granted_scopes: oauth_token.scopes.to_a+ granted_scopes: current_oauth_token.scopes.to_a)elseSpree::AgentTools::Context.new(store: current_store, api_key: current_api_key)@@ -109,35 +109,25 @@ module Spree# RFC 6750: the challenge names where to discover the authorization# server, which is how a consumer client starts its own sign-in.#- # The metadata URL is derived from the resource identifier rather- # than from route helpers, so both carry the same scheme and host.- # A client compares them, and http-versus-https is enough for it to- # decide the document describes a different resource and stop.+ # 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.## No `scope`: it is a SHOULD, and listing every grantable key makes# a header several kilobytes long. A client reads the real list from# the metadata document.def oauth_challenge- resource = Spree::Api::Oauth.resource_identifier(:mcp, current_store)- base = resource.sub(%r{/api/v3/admin/mcp\z}, '')-format('Bearer realm="%<realm>s", resource_metadata="%<metadata>s"',- realm: resource,- metadata: "#{base}/api/v3/oauth/protected-resource/mcp"+ realm: Spree::Api::Oauth.resource_identifier(:mcp, current_store),+ metadata: "#{current_store.formatted_url}/api/v3/oauth/protected-resource/mcp")end# A token issued for another resource must not work here, whatever# its scopes say. Doorkeeper binds the audience at issue; this is# the check that it matches.- # The hook ScopedAuthorization reads, so a grant narrows this- # request's authority through the same path every admin endpoint- # uses rather than only here.- def current_oauth_token- oauth_token- end-# A token selects its own store, the way a secret key does.## An MCP client sends a URL and a bearer token and nothing else — it@@ -146,28 +136,34 @@ module Spree# would be measured against the default store's resource identifier# and always fail its audience check.def resolve_admin_store- application_store || super- end-- def application_store- return if bearer_value.blank?- return if bearer_value.start_with?(Spree::ApiKey::PREFIXES['secret'])-- Spree::OauthAccessToken.by_token(bearer_value)&.application&.store+ bearer_access_token&.application&.store || superend- def oauth_token- return @oauth_token if defined?(@oauth_token)+ # The token the bearer header names, before any check of whether it+ # may be used here. Resolving the store needs it, and the audience+ # check needs the store, so the lookup has to come first — and it is+ # memoized because three callers want the same row.+ def bearer_access_token+ return @bearer_access_token if defined?(@bearer_access_token)- @oauth_token = begin- raw = bearer_value+ raw = bearer_value+ @bearer_access_token =if raw.blank? || raw.start_with?(Spree::ApiKey::PREFIXES['secret'])nilelse- token = Spree::OauthAccessToken.by_token(raw)- token if token&.accessible? && audience_matches?(token)+ Spree::OauthAccessToken.by_token(raw)end- end+ end++ # The token this request may actually act on: live, and issued for+ # this endpoint. Named for the hook ScopedAuthorization reads, so a+ # grant narrows authority through the same path every admin+ # endpoint uses rather than only here.+ def current_oauth_token+ return @current_oauth_token if defined?(@current_oauth_token)++ token = bearer_access_token+ @current_oauth_token = token if token&.accessible? && audience_matches?(token)end# Deliberately stricter than Doorkeeper's own@@ -184,7 +180,7 @@ module Spreeenddef oauth_resource_owner- owner = oauth_token.resource_owner+ owner = current_oauth_token.resource_ownerowner if owner.is_a?(Spree.admin_user_class)end@@ -196,7 +192,7 @@ module Spree# a consumer client that arrives with nothing discovers how to sign# in rather than simply failing.def require_agent_credential!- return if secret_api_key.present? || oauth_token.present?+ return if secret_api_key.present? || current_oauth_token.present?response.headers['WWW-Authenticate'] = oauth_challenge