Skip to content

armgit / spree

Public Imported from GitHub
0

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

Added the pre-registered consumer clients

Damian Legawiecfa88dfc1755a
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 0ea934a4bb..7449473a36 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -484,6 +484,10 @@ import type {
MediaUpdateParams,
MediaUsageReference,
MeUpdateParams,
+ OauthApplication,
+ OauthAuthorizationParams,
+ OauthAuthorizationRequest,
+ OauthRedirect,
OptionTypeCreateParams,
OptionTypeUpdateParams,
OrderCancelParams,
@@ -5932,6 +5936,49 @@ export class AdminClient {
// API Keys (publishable + secret)
// ============================================
+ /**
+ * OAuth 2.1 consent, for the screen a merchant approves when an agent or an
+ * app asks for access to the store.
+ *
+ * `authorization` describes what is being asked for; `approve` and `deny`
+ * both answer with the `redirect_uri` the browser should then be sent to.
+ * These require a signed-in admin: a secret key authenticates but is not a
+ * person, so it can never grant authority on someone's behalf.
+ */
+ readonly oauth = {
+ authorization: (
+ params: OauthAuthorizationParams,
+ options?: RequestOptions,
+ ): Promise<OauthAuthorizationRequest> =>
+ this.request<OauthAuthorizationRequest>('GET', '/oauth/authorize', {
+ ...options,
+ // The authorization request is a flat set of strings by construction,
+ // so it travels as query params untouched — no Ransack wrapping, and
+ // nothing re-derived on the way.
+ params: { ...params } as Record<string, string | undefined>,
+ }),
+
+ approve: (params: OauthAuthorizationParams, options?: RequestOptions): Promise<OauthRedirect> =>
+ this.request<OauthRedirect>('POST', '/oauth/authorize', { ...options, body: params }),
+
+ 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. */
+ applications: {
+ list: (options?: RequestOptions): Promise<OauthApplication[]> =>
+ this.request<OauthApplication[]>('GET', '/oauth/applications', 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.
+ */
+ revoke: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/oauth/applications/${id}`, options ?? {}),
+ },
+ }
+
readonly apiKeys = {
list: (
params?: ListParams<ApiKeyFilters, ApiKeySort>,
diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
new file mode 100644
index 0000000000..8d332acbb6
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/applications_controller.rb
@@ -0,0 +1,60 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Oauth
+ # Connected applications, so a merchant can see which agents and
+ # apps hold access to the store and take it away.
+ #
+ # Revoking is the off switch and has to be immediate: it revokes
+ # 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
+ # Listing and revoking connected apps is store configuration.
+ scoped_resource :settings
+
+ def index
+ applications = current_store.oauth_applications.
+ where(id: connected_application_ids).
+ order(:name)
+
+ render json: applications.map { |application| serialize(application) }
+ end
+
+ def destroy
+ application = current_store.oauth_applications.find_by_prefix_id!(params[:id])
+
+ authorize! :update, Spree::Store
+
+ 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
+
+ private
+
+ # 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
+
+ def serialize(application)
+ {
+ id: application.prefixed_id,
+ name: application.name,
+ scopes: application.scopes.to_a.sort,
+ last_used_at: application.last_used_at,
+ created_at: application.created_at
+ }
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb
new file mode 100644
index 0000000000..72bca87dfb
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/oauth/authorizations_controller.rb
@@ -0,0 +1,116 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ module Oauth
+ # The consent step, as JSON for the dashboard to render.
+ #
+ # `show` describes what a client is asking for so the dashboard can
+ # draw a consent screen in its own design system, with the admin
+ # already signed in. `create` grants it and answers with the
+ # redirect the browser should follow; `destroy` denies it.
+ #
+ # 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)
+
+ before_action :require_signed_in_admin!
+ before_action :load_pre_authorization
+
+ def show
+ render json: {
+ client_name: client_name,
+ scopes: requested_permissions,
+ resource: requested_resource,
+ redirect_uri: @pre_auth.redirect_uri
+ }
+ end
+
+ def create
+ authorization = ::Doorkeeper::OAuth::Authorization::Code.new(@pre_auth, current_actor)
+ authorization.issue_token!
+
+ render json: { redirect_uri: authorization.callback.redirect_uri }
+ end
+
+ def destroy
+ render json: { redirect_uri: denied_redirect_uri }
+ end
+
+ private
+
+ # A secret key authenticates but is not a person; `current_actor`
+ # returns the key in that case, and a grant must belong to a user.
+ def require_signed_in_admin!
+ return if current_actor.is_a?(Spree.admin_user_class)
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:access_denied],
+ message: 'Only a signed-in admin user can authorize an application.',
+ status: :forbidden
+ )
+ end
+
+ def load_pre_authorization
+ @pre_auth = ::Doorkeeper::OAuth::PreAuthorization.new(
+ ::Doorkeeper.config,
+ pre_authorization_params,
+ current_actor
+ )
+
+ return if @pre_auth.authorizable?
+
+ render_error(
+ code: Spree::Api::V3::ErrorHandler::ERROR_CODES[:resource_invalid],
+ message: @pre_auth.error_response.body[:error_description].to_s,
+ status: :unprocessable_content
+ )
+ end
+
+ # Symbol keys: PreAuthorization reads them that way, and a hash of
+ # strings silently produces an unauthorizable request.
+ def pre_authorization_params
+ params.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
+ end
+
+ def requested_resource
+ resource = @pre_auth.try(:resource)
+ Array(resource).first
+ end
+
+ # Every capability the requested scopes imply, so a merchant sees
+ # what they are actually granting rather than only the shorthand
+ # the client named.
+ def requested_permissions
+ Spree.permissions.expand_keys(@pre_auth.scopes.to_a).sort
+ end
+
+ def client_name
+ @pre_auth.client&.application&.name.presence || 'An application'
+ end
+
+ def denied_redirect_uri
+ uri = URI.parse(@pre_auth.redirect_uri.to_s)
+ query = Rack::Utils.parse_nested_query(uri.query.to_s)
+ query['error'] = 'access_denied'
+ query['state'] = params[:state] if params[:state].present?
+ uri.query = query.to_query
+ uri.to_s
+ end
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/seeds/oauth_applications.rb b/spree/core/app/services/spree/seeds/oauth_applications.rb
new file mode 100644
index 0000000000..c6e688e63e
--- /dev/null
+++ b/spree/core/app/services/spree/seeds/oauth_applications.rb
@@ -0,0 +1,49 @@
+module Spree
+ module Seeds
+ # Pre-registers the consumer MCP clients.
+ #
+ # Hosted connectors cannot register themselves: dynamic client
+ # registration is deprecated in the current MCP revision, and client ID
+ # metadata documents are not yet supported by the authorization server.
+ # Pre-registration is the first option in the spec's own priority order,
+ # and it means a merchant pastes their store URL into the client and signs
+ # in — nothing to create first.
+ class OauthApplications
+ prepend Spree::ServiceModule::Base
+ include StoreScoped
+
+ # Each client's own documented callback. A redirect URI is the one thing
+ # that cannot be guessed at runtime, so it is registered rather than
+ # accepted from the request.
+ CLIENTS = [
+ {
+ name: 'Claude',
+ redirect_uri: 'https://claude.ai/api/mcp/auth_callback'
+ },
+ {
+ name: 'ChatGPT',
+ redirect_uri: 'https://chatgpt.com/connector_platform_oauth_redirect'
+ }
+ ].freeze
+
+ private
+
+ def seed(store)
+ CLIENTS.each do |client|
+ next if store.oauth_applications.exists?(name: client[:name])
+
+ store.oauth_applications.create!(
+ name: client[:name],
+ redirect_uri: client[:redirect_uri],
+ # Public: a hosted connector runs on the vendor's servers and
+ # cannot keep a secret, which is why PKCE is mandatory.
+ confidential: false,
+ # Granted at consent, not at registration — the merchant decides
+ # what a client may do, and may re-consent to change it.
+ scopes: ''
+ )
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/services/spree/seeds/store_resources.rb b/spree/core/app/services/spree/seeds/store_resources.rb
index 2a843cbbe6..62c3e2dd27 100644
--- a/spree/core/app/services/spree/seeds/store_resources.rb
+++ b/spree/core/app/services/spree/seeds/store_resources.rb
@@ -31,6 +31,7 @@ module Spree
SellerRequirements.call(store: store)
# Binds to the wholesale channel that Channels creates above.
ApiKeys.call(store: store)
+ OauthApplications.call(store: store)
SavedReports.call(store: store)
AllowedOrigins.call(store: store)
end