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
Close gaps in store context and first-run setup found in review
Damian Legawiec995990679353
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex 0352e57da2..5310cbeba5 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -83,12 +83,19 @@ export async function runFirstRunSetup(flags: {s.stop('Spree is ready.')s.start('Seeding database...')- await rakeTask('db:seed', ctx.projectDir, {- ADMIN_EMAIL: adminEmail,- ADMIN_PASSWORD: adminPassword,- })+ // Omitted entirely when unresolved — the seed treats blank values as "no+ // admin" and prints a setup link instead, which we surface on the card+ // below (rakeTask captures stdout rather than streaming it).+ const seedOutput = await rakeTask(+ 'db:seed',+ ctx.projectDir,+ adminEmail && adminPassword+ ? { ADMIN_EMAIL: adminEmail, ADMIN_PASSWORD: adminPassword }+ : undefined,+ )+ const setupUrl = seedOutput.match(/https?:\/\/\S+\/setup\?token=\S+/)?.[0]s.stop('Database seeded.')- writeAdminEmail(ctx.projectDir, adminEmail)+ if (adminEmail) writeAdminEmail(ctx.projectDir, adminEmail)s.start('Configuring API keys...')// Sequential, not Promise.all: finish the publishable key (and its@@ -128,19 +135,27 @@ export async function runFirstRunSetup(flags: {if (hasDashboardApp(ctx.projectDir) && !dashboardRunnable) {warnDashboardNotRunnable(ctx.projectDir)}+ // No credentials means no admin was seeded — the operator creates one in+ // the browser through the seed's one-time setup link.+ const credentialLines =+ adminEmail && adminPassword+ ? [` Email: ${adminEmail}`, ` Password: ${adminPassword}`]+ : [+ ` ${pc.dim('Create your admin account:')}`,+ ` ${pc.cyan(setupUrl ?? 'run `spree run bin/rails spree:setup:token` for the setup link')}`,+ ]+const adminBlock = dashboardRunnable? [pc.bold('Admin Dashboard (React, Developer Preview)'),` ${pc.cyan(`http://localhost:${DASHBOARD_PORT}`)}`,- ` Email: ${adminEmail}`,- ` Password: ${adminPassword}`,+ ...credentialLines,` ${pc.dim('Live-reloading from apps/dashboard/')}`,]: [pc.bold('Admin Dashboard'),` ${pc.dim(`Not installed — add it with ${pc.bold('spree add dashboard')}`)}`,- ` Email: ${adminEmail}`,- ` Password: ${adminPassword}`,+ ...credentialLines,]// The wholesale demo needs both the storefront env opt-in and the seeded@@ -294,15 +309,15 @@ export function updateStorefrontEnv(projectDir: string, apiKey: string): void {}/**- * Flags win; otherwise an interactive terminal prompts (Medusa-style), and a- * non-interactive run falls back to the historical dev credentials — passed- * explicitly to the seed either way, since the server no longer ships dummy- * defaults.+ * Flags win; otherwise an interactive terminal prompts (Medusa-style). A+ * non-interactive run with no flags seeds no admin at all — the setup link+ * printed by the seed claims the installation instead, so an automated+ * install never mints a well-known password.*/async function resolveAdminCredentials(flags: {adminEmail?: stringadminPassword?: string-}): Promise<{ adminEmail: string; adminPassword: string }> {+}): Promise<{ adminEmail?: string; adminPassword?: string }> {let adminEmail = flags.adminEmaillet adminPassword = flags.adminPassword@@ -335,10 +350,7 @@ async function resolveAdminCredentials(flags: {}}- return {- adminEmail: adminEmail || '[email protected]',- adminPassword: adminPassword || 'spree123',- }+ return { adminEmail, adminPassword }}async function openBrowser(url: string): Promise<void> {diff --git a/packages/dashboard/src/routes/_authenticated/index.tsx b/packages/dashboard/src/routes/_authenticated/index.tsxindex 79dc7de052..1e109b89ee 100644--- a/packages/dashboard/src/routes/_authenticated/index.tsx+++ b/packages/dashboard/src/routes/_authenticated/index.tsx@@ -22,9 +22,17 @@ function IndexRedirect() {}let cancelled = false- adminClient.store.get().then((store) => {- if (!cancelled) navigate({ to: '/$storeId', params: { storeId: store.id }, replace: true })- })+ adminClient.store+ .get()+ .then((store) => {+ if (!cancelled) navigate({ to: '/$storeId', params: { storeId: store.id }, replace: true })+ })+ .catch(() => {+ // Nothing resolved a store — send them to login rather than leaving+ // them on a blank page with no way out. A live session that merely hit+ // a network blip lands back here after the redirect.+ if (!cancelled) navigate({ to: '/login', replace: true })+ })return () => {cancelled = true}diff --git a/packages/dashboard/src/routes/login.tsx b/packages/dashboard/src/routes/login.tsxindex 1d615dfb47..cc5b9c241d 100644--- a/packages/dashboard/src/routes/login.tsx+++ b/packages/dashboard/src/routes/login.tsx@@ -65,6 +65,10 @@ function SetupRequiredNotice() {queryKey: ['setup-status'],queryFn: () => adminClient.auth.setupStatus(),retry: false,+ // See the /setup route: never offer setup from a cached `true`.+ gcTime: 0,+ staleTime: 0,+ refetchOnMount: 'always',})if (!status.data?.setup_required) return nulldiff --git a/packages/dashboard/src/routes/setup.tsx b/packages/dashboard/src/routes/setup.tsxindex 1036cd94f6..3431c707b0 100644--- a/packages/dashboard/src/routes/setup.tsx+++ b/packages/dashboard/src/routes/setup.tsx@@ -50,6 +50,12 @@ function SetupLoader({ token }: { token: string }) {queryKey: ['setup-status'],queryFn: () => adminClient.auth.setupStatus(),retry: false,+ // Availability flips exactly once, and a cached `true` would re-render+ // the form after setup completed (browser back, or the login page's+ // link) — a form that can no longer succeed. Always ask.+ gcTime: 0,+ staleTime: 0,+ refetchOnMount: 'always',})if (status.isPending) {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 cbcea0a953..01dd3aa9a3 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@@ -47,7 +47,11 @@ module Spreereturnend- Spree::Current.store = current_store if current_store+ # Assigned even when nil: an unknown store id renders 404 further+ # down the chain, and leaving Spree::Current.store holding the+ # previous request's value on this thread would expose another+ # store to anything reading it before that 404 lands.+ Spree::Current.store = current_storeenddef resolve_admin_storediff --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 804a023a6e..bd5f4eaf35 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@@ -34,9 +34,17 @@ module Spreereturn render_setup_unavailable unless setup_token_usable?user = nil- ApplicationRecord.transaction do+ store = Spree::Store.default++ # The token is one-time, so the guard above must not be a bare+ # check-then-act: two requests carrying the same token can both+ # pass it and each create an admin. Re-checking under a row lock+ # on the store serializes them — the loser sees a spent token.+ store.with_lock do+ return render_setup_unavailable unless setup_token_usable?(store.reload)+user = Spree.admin_user_class.create!(admin_user_params)- adopt_default_store(user)+ adopt_default_store(user, store)endrefresh_token = Spree::RefreshToken.create_for(user, request_env: request_env_for_token)@@ -54,11 +62,11 @@ module Spree# The token lives on the default store (has_secure_token) and only# authorizes setup while no admin user exists.- def setup_token_usable?+ def setup_token_usable?(store = Spree::Store.default)return false unless setup_required?provided = params[:setup_token].to_s- stored = Spree::Store.default&.setup_token+ stored = store&.setup_tokenprovided.present? && stored.present? &&ActiveSupport::SecurityUtils.secure_compare(stored, provided)@@ -81,12 +89,14 @@ module Spree# The seed already created the default store (every downstream seed# depends on it existing) — setup claims and renames it rather than# creating a second one, and spends the token.- def adopt_default_store(user)- store = Spree::Store.default+ def adopt_default_store(user, store)store.update!(store_params.merge(setup_token: nil))store.add_user(user)end+ # `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).def store_params@store_params ||= beginpermitted = {}diff --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 83a1bb0f45..26448cb1ce 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@@ -105,6 +105,23 @@ RSpec.describe Spree::Api::V3::Admin::SetupController, type: :controller doendend+ context 'when the token is spent between the guard and the write' do+ # Simulates the concurrent-submit race: the pre-lock check passes, then+ # another request completes setup before this one takes the lock.+ it 'returns 404 and creates no second admin' do+ call_count = 0+ allow_any_instance_of(described_class).to receive(:setup_token_usable?).and_wrap_original do |original, *args|+ call_count += 1+ call_count == 1 ? original.call(*args) : false+ end++ post :create, params: valid_params, as: :json++ expect(response).to have_http_status(:not_found)+ expect(Spree.admin_user_class.count).to eq(0)+ end+ end+context 'when the store has no token' dobefore { @default_store.update_column(:setup_token, nil) }diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 7d24fdc864..83bfcc4222 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -220,6 +220,22 @@ module Spree# database holds nothing but seed data.has_secure_token :setup_token+ # Link that claims this installation: the dashboard's first-run setup+ # screen with the store's token. Resolves the dashboard origin the same+ # way the SSO callback does — configured origin, the Vite dev server in+ # development, then the store's own URL — so a production install without+ # `dashboard_url` set never advertises a localhost port.+ # @return [String, nil] nil when no token is outstanding+ def setup_url+ return if setup_token.blank?++ base = Spree::Config[:dashboard_url].presence ||+ (Rails.env.development? ? 'http://localhost:5173' : nil) ||+ formatted_url++ "#{base.to_s.chomp('/')}/setup?token=#{setup_token}"+ end+## Callbacksbefore_validation :set_default_code, on: :creatediff --git a/spree/core/app/services/spree/seeds/admin_user.rb b/spree/core/app/services/spree/seeds/admin_user.rbindex 625a5dc478..a4967c65e6 100644--- a/spree/core/app/services/spree/seeds/admin_user.rb+++ b/spree/core/app/services/spree/seeds/admin_user.rb@@ -47,7 +47,7 @@ module Spreemessage = <<~MSG==> No admin account yet. Finish setup in the dashboard:- #{setup_url(store.setup_token)}+ #{store.setup_url}(Run `bin/rails spree:setup:token` to print this link again.)@@ -56,11 +56,6 @@ module Spreeputs message unless Rails.env.test?Rails.logger&.info(message)end-- def setup_url(token)- base = Spree::Config[:admin_url].presence || 'http://localhost:5173'- "#{base.chomp('/')}/setup?token=#{token}"- endendendenddiff --git a/spree/core/lib/tasks/cli.rake b/spree/core/lib/tasks/cli.rakeindex a1113cbf59..662fd7b07c 100644--- a/spree/core/lib/tasks/cli.rake+++ b/spree/core/lib/tasks/cli.rake@@ -40,8 +40,9 @@ namespace :spree doemail = ENV.fetch('EMAIL')password = ENV.fetch('PASSWORD')+ # Creates the role row if the database predates it, so this works on a+ # freshly migrated app that has not been seeded.admin_role = Spree::Role.default_admin_role- abort "The 'admin' role does not exist — run `bin/rails db:seed` first." if admin_role.nil?admin = Spree.admin_user_class.find_or_create_by!(email: email) do |user|user.password = passworddiff --git a/spree/core/lib/tasks/setup.rake b/spree/core/lib/tasks/setup.rakeindex ade6712e02..8f97f965b1 100644--- a/spree/core/lib/tasks/setup.rake+++ b/spree/core/lib/tasks/setup.rake@@ -10,10 +10,9 @@ namespace :spree doabort 'No store yet — run `bin/rails db:seed` first.' if store.nil?store.regenerate_setup_token if store.setup_token.blank? || ENV['ROTATE'].present?- base = Spree::Config[:admin_url].presence || 'http://localhost:5173'puts 'Finish setup in the dashboard:'- puts " #{base.chomp('/')}/setup?token=#{store.setup_token}"+ puts " #{store.setup_url}"endendenddiff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rbindex 8cdc7def83..70df660c11 100644--- a/spree/core/spec/models/spree/store_spec.rb+++ b/spree/core/spec/models/spree/store_spec.rb@@ -306,6 +306,30 @@ describe Spree::Store, type: :model, without_global_store: true doend+ describe '#setup_url' do+ let(:store) { create(:store, url: 'shop.example.com') }++ it 'points at the configured dashboard origin' do+ allow(Spree::Config).to receive(:[]).with(:dashboard_url).and_return('https://admin.example.com')++ expect(store.setup_url).to eq("https://admin.example.com/setup?token=#{store.setup_token}")+ end++ it "falls back to the store's own URL rather than a dev port" do+ allow(Spree::Config).to receive(:[]).with(:dashboard_url).and_return(nil)+ allow(Rails.env).to receive(:development?).and_return(false)++ expect(store.setup_url).to start_with(store.formatted_url)+ expect(store.setup_url).not_to include('localhost:5173')+ end++ it 'is nil once the token is spent' do+ store.update!(setup_token: nil)++ expect(store.setup_url).to be_nil+ end+ end+context 'Validations' dodescribe '#code' doit 'generates a code when blank' do