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
Stop the install paths from minting a well-known admin
Damian Legawiec94629f0fe6ef
diff --git a/docs/v6/developer/customization/configuration.mdx b/docs/v6/developer/customization/configuration.mdxindex 1f7c7acf03..830d509cae 100644--- a/docs/v6/developer/customization/configuration.mdx+++ b/docs/v6/developer/customization/configuration.mdx@@ -16,6 +16,14 @@ endRestart your Rails server after editing the initializer.</Note>+## Deployment settings read the environment++Settings that describe the deployment rather than commerce behavior can be set with an environment variable — no Ruby, no code change, no restart-after-edit dance. An explicitly configured value always wins over the environment.++| Setting | Environment variable | What it configures |+|---|---|---|+| `dashboard_url` | `SPREE_DASHBOARD_URL` | Origin where the admin dashboard is hosted (e.g. `https://admin.my-shop.com`). Used for every link that sends someone into the dashboard: invitation emails, SSO redirects, and the first-run setup link printed by `db:seed`. |+This page lists only settings Spree 6 actually reads. Settings that exist for backwards compatibility are listed under [Deprecated settings](#deprecated-settings) rather than mixed in with the rest.## Settings that belong to a storediff --git a/packages/admin-sdk/src/client.ts b/packages/admin-sdk/src/client.tsindex f53364ff00..d37f1ff341 100644--- a/packages/admin-sdk/src/client.ts+++ b/packages/admin-sdk/src/client.ts@@ -59,7 +59,11 @@ export function createAdminClient(config: AdminClientConfig): Client {options: InternalRequestOptions = {},): Promise<T> => {const extraHeaders: Record<string, string> = {}- if (currentStoreId) {+ // Auth endpoints are store-agnostic by design (login, refresh, setup,+ // invitation acceptance run before or between store selections), and a+ // stale store id from a previous session must never be able to 404 the+ // way back in.+ if (currentStoreId && !path.startsWith('/auth/')) {extraHeaders['X-Spree-Store-Id'] = currentStoreId}diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 5310cbeba5..a331ebf4ca 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -112,9 +112,17 @@ export async function runFirstRunSetup(flags: {ensureDashboardDevEnv(ctx.projectDir, ctx.port)if (sampleData) {- s.start('Loading sample data...')- await rakeTask('spree:load_sample_data', ctx.projectDir)- s.stop('Sample data loaded.')+ // Sample-data imports need an admin as their owner; without credentials+ // the seed minted none and the loader would raise mid-init.+ if (adminEmail && adminPassword) {+ s.start('Loading sample data...')+ await rakeTask('spree:load_sample_data', ctx.projectDir)+ s.stop('Sample data loaded.')+ } else {+ p.log.warn(+ 'Skipping sample data — it needs an admin account. Finish setup, then run `spree sample-data`.',+ )+ }}s.start('Indexing products for search...')diff --git a/packages/dashboard-core/src/providers/auth-provider.tsx b/packages/dashboard-core/src/providers/auth-provider.tsxindex 51c7af4a01..af14470f76 100644--- a/packages/dashboard-core/src/providers/auth-provider.tsx+++ b/packages/dashboard-core/src/providers/auth-provider.tsx@@ -81,6 +81,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {const clearSession = useCallback(() => {adminClient.setToken('')+ // The store header is session state too — left set, it would ride into+ // the next admin's first requests (permissions, the index redirect) and+ // 403 them against a store they may hold no role on.+ adminClient.setStore('')setToken(null)setUser(null)clearRefreshTimer()diff --git a/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb b/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rbindex 01dd3aa9a3..f6c392e8e3 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/admin/store_context.rb@@ -22,6 +22,9 @@ module Spree# lookups) reads it. The store-presence guard 404s an unknown# header ID right after this runs.prepend_before_action :set_current_store_context++ # Once-per-process latch for the missing-header notice.+ class_attribute :missing_store_header_warned, default: false, instance_accessor: falseend# Resolution order: the secret key's bound store, then the header,@@ -72,12 +75,19 @@ module Spreerequest.headers[STORE_HEADER].presenceend+ # A plain once-per-process log line, deliberately NOT+ # Spree::Deprecation: some endpoints structurally cannot carry the+ # header (`/me` runs before any store is selected — it is how the+ # dashboard discovers the user's stores), so a per-request+ # deprecation would be pure noise and would 500 every login+ # bootstrap for apps running deprecations-as-errors.def warn_missing_store_header- return unless defined?(Spree::Deprecation)+ return if self.class.missing_store_header_warned+ self.class.missing_store_header_warned = true- Spree::Deprecation.warn(+ Rails.logger&.info("Admin API v3 requests without an #{STORE_HEADER} header fall back to the default store. " \- 'The header becomes required for JWT requests in Spree 6.1.'+ 'Multi-store clients should send the header; store-agnostic endpoints (/me, auth) are exempt.')endenddiff --git a/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rbindex bd5f4eaf35..be8f2d5b2e 100644--- a/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/setup_controller.rb@@ -96,12 +96,19 @@ module Spree# `store_name` is optional: an API client may claim the installation# without renaming the seeded store (the dashboard's form requires- # it, but the endpoint is the documented surface).+ # it, but the endpoint is the documented surface). `currency` and+ # `country_iso` are applied only when they resolve to something real+ # — the token is spent in the same request, so persisting a typo+ # here would be unrecoverable in-band.def store_params@store_params ||= beginpermitted = {}permitted[:name] = params[:store_name] if params[:store_name].present?- permitted[:default_currency] = params[:currency] if params[:currency].present?++ if params[:currency].present?+ currency = ::Money::Currency.find(params[:currency].to_s.strip)+ permitted[:default_currency] = currency.iso_code if currency+ endif params[:country_iso].present?country = Spree::Country.find_by(iso: params[:country_iso].to_s.upcase)diff --git a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb b/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rbindex 7fbf7a7e30..b657141bec 100644--- a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb@@ -27,10 +27,14 @@ module Spree# The download token is the request's credential and selects the# store (tokens are globally unique via has_secure_token) — no# publishable key accompanies emailed download links, so there is- # no other credential to derive store context from.+ # no other credential to derive store context from. Assigned, not+ # memoized-into: earlier prepended callbacks resolve current_store+ # before the resource exists (to the key's store, when one is+ # sent), and the link's own store must overwrite that.def set_resource@resource = digital_link_scope.find_by!(token: params[:token])- Spree::Current.store = current_store+ @current_store = @resource.order.store+ Spree::Current.store = @current_storeenddef digital_link_scope@@ -38,7 +42,7 @@ module Spreeenddef current_store- @current_store ||= @resource&.order&.store || super+ @current_store ||= superendendenddiff --git a/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rbindex c911a78c3b..c48d9dae85 100644--- a/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb+++ b/spree/api/spec/controllers/concerns/spree/api/v3/admin/store_context_spec.rb@@ -56,8 +56,12 @@ RSpec.describe Spree::Api::V3::Admin::TaxCategoriesController, type: :controllerendcontext 'without the header' do- it 'falls back to the default store with a deprecation warning' do- expect(Spree::Deprecation).to receive(:warn).with(/X-Spree-Store-Id/)+ # No Spree::Deprecation here by design: /me and the auth endpoints+ # structurally cannot send the header, and deprecations-as-errors would+ # turn every login bootstrap into a 500. A once-per-process log line+ # covers the multi-store-client nudge instead.+ it 'falls back to the default store without raising deprecations' do+ expect(Spree::Deprecation).not_to receive(:warn)get :index, as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rbindex 26448cb1ce..2ca50e1f15 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/setup_controller_spec.rb@@ -61,13 +61,25 @@ RSpec.describe Spree::Api::V3::Admin::SetupController, type: :controller doit 'applies optional currency and country' docreate(:country_us) unless Spree::Country.find_by(iso: 'US')- post :create, params: valid_params.merge(currency: 'EUR', country_iso: 'us'), as: :json+ post :create, params: valid_params.merge(currency: 'eur', country_iso: 'us'), as: :jsonexpect(response).to have_http_status(:ok)expect(@default_store.reload.default_currency).to eq('EUR')expect(@default_store.default_country&.iso).to eq('US')end+ # The token is spent in the same request, so persisting garbage here+ # would be unrecoverable in-band — unknown codes are ignored, mirroring+ # country_iso.+ it 'ignores an unknown currency' do+ original_currency = @default_store.default_currency++ post :create, params: valid_params.merge(currency: 'NOTACURRENCY'), as: :json++ expect(response).to have_http_status(:ok)+ expect(@default_store.reload.default_currency).to eq(original_currency)+ end+it 'returns 422 with field errors on invalid input' dopost :create, params: valid_params.merge(password_confirmation: 'nope'), as: :jsondiff --git a/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rbindex 98ec481c34..3d9d50ca44 100644--- a/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/digitals_controller_spec.rb@@ -77,10 +77,14 @@ RSpec.describe Spree::Api::V3::Store::DigitalsController, type: :controller do# The globally unique token is the credential and selects the store —# download links arrive by email with no API key, so there is no other# credential to scope by (see KeyStoreContext).- it 'downloads the file' do+ it "downloads the file under the link's own store context" doget :show, params: { token: other_digital_link.token }expect(response).to have_http_status(:ok)+ # Even when a publishable key of another store accompanies the+ # request, the link's store wins for the download context. Asserted+ # via the ivar because the shared context stubs current_store itself.+ expect(controller.instance_variable_get(:@current_store)).to eq(other_store)endenddiff --git a/spree/core/app/services/spree/seeds/admin_user.rb b/spree/core/app/services/spree/seeds/admin_user.rbindex a4967c65e6..77cdbcd338 100644--- a/spree/core/app/services/spree/seeds/admin_user.rb+++ b/spree/core/app/services/spree/seeds/admin_user.rb@@ -53,8 +53,11 @@ module SpreeMSG+ # The URL goes to stdout only — the token is a claim-this-installation+ # credential, and Rails.logger typically feeds a log aggregator with a+ # far wider audience than the person running the seed.puts message unless Rails.env.test?- Rails.logger&.info(message)+ Rails.logger&.info('No admin account yet — run `bin/rails spree:setup:token` to print the setup link.')endendenddiff --git a/spree/core/lib/tasks/cli.rake b/spree/core/lib/tasks/cli.rakeindex 662fd7b07c..8d0b1a6689 100644--- a/spree/core/lib/tasks/cli.rake+++ b/spree/core/lib/tasks/cli.rake@@ -44,10 +44,18 @@ namespace :spree do# freshly migrated app that has not been seeded.admin_role = Spree::Role.default_admin_role- admin = Spree.admin_user_class.find_or_create_by!(email: email) do |user|- user.password = password- user.password_confirmation = password+ # Never silently ignore the supplied password: an operator rerunning+ # this to "reset" a password would otherwise get a success exit while+ # nothing changed.+ if Spree.admin_user_class.exists?(email: email)+ abort "An admin with email #{email} already exists — password NOT changed. Use a password reset to change it."end++ admin = Spree.admin_user_class.create!(+ email: email,+ password: password,+ password_confirmation: password+ )admin.add_role(admin_role.name, Spree::Store.default)print admin.emailenddiff --git a/spree/lib/generators/spree/install/install_generator.rb b/spree/lib/generators/spree/install/install_generator.rbindex 2d23557c54..b86c6ac99e 100644--- a/spree/lib/generators/spree/install/install_generator.rb+++ b/spree/lib/generators/spree/install/install_generator.rb@@ -110,8 +110,15 @@ module Spreereturn unless Spree::Core::Engine.sample_available?if @load_sample_data- say_status :loading, 'sample data'- rake 'spree_sample:load'+ # Sample-data imports need an admin as their owner. Without explicit+ # credentials the seed mints none (first-run setup does), so loading+ # now would raise mid-install.+ if admin_account_available?+ say_status :loading, 'sample data'+ rake 'spree_sample:load'+ else+ say_status :skipping, 'sample data (needs an admin account — finish setup, then run bin/rails spree:load_sample_data)'+ endelsesay_status :skipping, 'sample data (you can always run rake spree_sample:load)'end@@ -145,6 +152,11 @@ module Spreeunless options[:quiet]puts '*' * 50puts "Spree has been installed successfully. You're all ready to go!"+ unless admin_account_available?+ puts ' '+ puts 'No admin account was created — finish setup in the dashboard using the'+ puts 'link printed by the seed (reprint it with: bin/rails spree:setup:token).'+ endputs ' 'puts 'Enjoy!'end@@ -152,6 +164,19 @@ module Spreeprivate+ # Whether this install ends up with an admin account: explicit credentials+ # were passed to the seed, or one already exists (re-install into a+ # configured app). Drives the sample-data guard and the completion notes.+ def admin_account_available?+ credentials = (options[:admin_email].presence || ENV['ADMIN_EMAIL'].presence) &&+ (options[:admin_password].presence || ENV['ADMIN_PASSWORD'].presence)+ return true if credentials++ Spree.admin_user_class.present? && Spree.admin_user_class.exists?+ rescue StandardError+ false+ end+def silence_stream(stream)old_stream = stream.dupstream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')diff --git a/spree/template.rb b/spree/template.rbindex b6fada5e17..32657eded3 100644--- a/spree/template.rb+++ b/spree/template.rb@@ -10,8 +10,12 @@ USE_LOCAL_SPREE = ENV['USE_LOCAL_SPREE'] == 'true'# gemspec (spree, spree_core, spree_api, spree_emails, …) via Bundler's default# glob, resolving the whole stack locally.SPREE_LOCAL_PATH = ENV['SPREE_LOCAL_PATH'] || '.'-ADMIN_EMAIL = ENV['ADMIN_EMAIL'] || '[email protected]'-ADMIN_PASSWORD = ENV['ADMIN_PASSWORD'] || 'spree123'+# No defaults: without explicit credentials the seed mints no admin and+# prints a one-time setup link instead — the dashboard's first-run screen+# creates the account. This keeps well-known credentials out of every app+# scaffolded from this template.+ADMIN_EMAIL = ENV['ADMIN_EMAIL']+ADMIN_PASSWORD = ENV['ADMIN_PASSWORD']SPREE_VERSION = ENV['SPREE_VERSION'] || '>= 5.4.2'def add_gems@@ -62,13 +66,22 @@ enddef seed_databasesay 'Loading seed data...', :blue- rails_command "db:seed AUTO_ACCEPT=1 ADMIN_EMAIL=#{ADMIN_EMAIL} ADMIN_PASSWORD=#{ADMIN_PASSWORD}"+ if ADMIN_EMAIL.present? && ADMIN_PASSWORD.present?+ rails_command "db:seed AUTO_ACCEPT=1 ADMIN_EMAIL=#{ADMIN_EMAIL} ADMIN_PASSWORD=#{ADMIN_PASSWORD}"+ else+ rails_command 'db:seed AUTO_ACCEPT=1'+ endenddef load_sample_dataif LOAD_SAMPLE_DATA- say 'Loading sample data...', :blue- rails_command 'spree:load_sample_data'+ if ADMIN_EMAIL.present? && ADMIN_PASSWORD.present?+ say 'Loading sample data...', :blue+ rails_command 'spree:load_sample_data'+ else+ # Sample-data imports need an admin as their owner, and none was seeded.+ say 'Skipping sample data — it needs an admin account. Load it after first-run setup with: bin/rails spree:load_sample_data', :yellow+ endendend@@ -85,9 +98,15 @@ def show_success_messagesay ' Store API: http://localhost:3000/api/v3/store', :boldsay ' Admin API: http://localhost:3000/api/v3/admin', :boldsay- say 'Admin account (sign in via the Admin API / React dashboard):', :yellow- say " Email: #{ADMIN_EMAIL}", :bold- say " Password: #{ADMIN_PASSWORD}", :bold+ if ADMIN_EMAIL.present? && ADMIN_PASSWORD.present?+ say 'Admin account (sign in via the Admin API / React dashboard):', :yellow+ say " Email: #{ADMIN_EMAIL}", :bold+ say " Password: #{ADMIN_PASSWORD}", :bold+ else+ say 'Admin account:', :yellow+ say ' Use the setup link printed by the seed above to create it.', :bold+ say ' (Reprint it any time with: bin/rails spree:setup:token)'+ endsaysay 'Useful commands:', :yellowsay ' bin/rails console # Rails console'