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
Point the setup link at a dashboard that is actually running
Damian Legawiec941742949e37
diff --git a/CLAUDE.md b/CLAUDE.mdindex 753e5a6c41..22375d298f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -25,7 +25,7 @@ Active plans (6.0 target, work pending):- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15):** diverging parcels are split fulfillments; a `spree_fulfillment_trackings` model is 6.1 work and must absorb the entire carrier axis (per-row status/`delivered_at`, webhook matching by row) — never split the axis across fulfillment and tracking rows- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, `StoreCreditCategory.default_refund_category` (alias kept). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)-- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — never a hardcoded port). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. creates the first admin and adopts/renames the seeded store. No general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction; new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly.+- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — resolving `dashboard_url` pref/`SPREE_DASHBOARD_URL` → deprecated `admin_url` → this app's own `/dashboard` mount when `spree_dashboard` serves a build → dev Vite → store URL; never a hardcoded port, and the CLI rebuilds the link host-side since the seed runs before any dashboard is up). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. creates the first admin and adopts/renames the seeded store. No general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction; new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly.- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`); reference provider: Avalara (decisions.md 2026-07-30)- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod; monorepo ships one reference multi-carrier provider (**EasyPost** — decisions.md 2026-08-06 reversal: BYOCA fit for larger merchants + only maintained official Ruby SDK; Shippo's ruby gem dead since 2020); method rows stay regional (no cross-market method entity). **Dynamic carrier rates (2026-08-09):** a carrier method is the carrier connection — `estimates(package)` returns one Estimate per service, each becoming its own named DeliveryRate (unique (fulfillment, method) rate index dropped; `DeliveryRate#name` falls back to the method name); `Spree::DeliveryMethodService` rows narrow/rename/mark-up services (no rows = all, method-level markup columns as default); selection + EasyPost label buy key off the selected rate's carrier/service; seeds/sample data reshaped Shopify-style (Domestic + International zones with basic methods)- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)diff --git a/docs/plans/6.0-store-context-and-first-run-setup.md b/docs/plans/6.0-store-context-and-first-run-setup.mdindex 35273b5071..10e21a69a8 100644--- a/docs/plans/6.0-store-context-and-first-run-setup.md+++ b/docs/plans/6.0-store-context-and-first-run-setup.md@@ -57,7 +57,9 @@ A `StoreContext` concern in the v3 Admin base controller resolves `current_store- `GET /api/v3/admin/auth/setup` → `{ "setup_required": true | false }`. True only while zero admin users exist. Safe to expose: it leaks one boolean that is also self-evident from a fresh install.- `POST /api/v3/admin/auth/setup` → params: `setup_token`, `email`, `password`, `first_name`, `last_name`, `store_name`, optional `currency`/`country_iso`. Guards, in order: admin count is zero; token digest matches. Effects, in one transaction: create the admin user, `add_user` with the `admin` role on the default store, rename/configure the store, delete the setup-token row. Then issue the refresh cookie + JWT exactly like `InvitationAcceptancesController` and return the admin-user payload. Any later call 404s (setup no longer required).-**Setup token mechanics.** The token is a `has_secure_token :setup_token` on `Spree::Store` — generated when the seed creates the default store, so a repeated `db:seed` reprints the same URL. `Store#setup_url` builds it on top of `Spree::Stores::DashboardUrl`, the single resolver for "where is the dashboard" now shared by the setup link, invitation emails and the SSO callback: `Spree::Config[:dashboard_url]` (env-backed, see below) → the deprecated `admin_url` → the Vite dev server in development → the store's own URL.+**Setup token mechanics.** The token is a `has_secure_token :setup_token` on `Spree::Store` — generated when the seed creates the default store, so a repeated `db:seed` reprints the same URL. `Store#setup_url` builds it on top of `Spree::Stores::DashboardUrl`, the single resolver for "where is the dashboard" now shared by the setup link, invitation emails and the SSO callback: `Spree::Config[:dashboard_url]` (env-backed, see below) → the deprecated `admin_url` → **this app's own `/dashboard` mount** when `spree_dashboard` is installed with a build to serve → the Vite dev server in development → the store's own URL.++**The chicken-and-egg problem the mount solves (2026-08-13).** The setup link is printed by `db:seed`, which runs *before* anything is serving the dashboard — and under `create-spree-app` it runs inside a container, where the host's Vite port is unknowable. Two answers, one per install path. A plain Rails app (`spree:install`, `template.rb`) links at its own `/dashboard`, which the app serves itself the moment it boots — no second process, which is why the mount outranks the Vite guess: it is a fact about the deployment rather than an assumption about the developer's setup. The CLI keeps only the **token** from the seed output and rebuilds the URL against the dashboard it is about to launch (dev server if runnable, else the API's bundled mount), since it alone knows the host-side ports.**App configuration reads the environment (2026-08-13).** `RuntimeConfiguration.preference` takes an `env:` option, so an app-level setting can be configured from the deployment environment instead of Ruby, with precedence explicit value → env var → coded default. `dashboard_url` is the first adopter (`SPREE_DASHBOARD_URL`) because the setup link is printed by `db:seed`, before anyone can reach a console to set a preference, and every worktree and container has a different dashboard origin (worktree provisioning writes it into `server/.env`). `admin_url` is deprecated in its favour — both named the same origin, and the split was a legacy-admin artifact. The option is deliberately limited to `Spree::Config`; per-store behavior belongs in Store preferences, which one global env var cannot express. `bin/rails spree:setup:token` prints the current link (generating one for stores predating the column; `ROTATE=1` rotates). The setup endpoint compares with `secure_compare` behind the zero-admins gate and clears the token when setup completes, so the flow is dead on every install that seeds credentials explicitly. Plaintext at rest, deliberately — the same posture as invitation tokens, and the token only works while the database contains nothing but seed data.diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex a331ebf4ca..d88b2674bf 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -93,7 +93,10 @@ export async function runFirstRunSetup(flags: {? { ADMIN_EMAIL: adminEmail, ADMIN_PASSWORD: adminPassword }: undefined,)- const setupUrl = seedOutput.match(/https?:\/\/\S+\/setup\?token=\S+/)?.[0]+ // Only the token travels: the seed resolves the URL inside the container,+ // where the dashboard's host and port are unknowable. The card rebuilds the+ // link against whichever dashboard it is about to point the user at.+ const setupToken = seedOutput.match(/\/setup\?token=(\S+)/)?.[1]s.stop('Database seeded.')if (adminEmail) writeAdminEmail(ctx.projectDir, adminEmail)@@ -144,13 +147,23 @@ export async function runFirstRunSetup(flags: {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.+ // the browser through the seed's one-time setup link. Built against the+ // dashboard this card is advertising (the dev server `spree dev` starts, or+ // the bundled dashboard the API serves when there is no dev server), since+ // the URL the seed printed used the container's own idea of the host.+ const setupBase = dashboardRunnable+ ? `http://localhost:${DASHBOARD_PORT}`+ : `http://localhost:${ctx.port}/dashboard`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')}`,+ ` ${pc.cyan(+ setupToken+ ? `${setupBase}/setup?token=${setupToken}`+ : 'run `spree run bin/rails spree:setup:token` for the setup link',+ )}`,]const adminBlock = dashboardRunnablediff --git a/spree/core/app/finders/spree/stores/dashboard_url.rb b/spree/core/app/finders/spree/stores/dashboard_url.rbindex e03251d809..54f7933cb9 100644--- a/spree/core/app/finders/spree/stores/dashboard_url.rb+++ b/spree/core/app/finders/spree/stores/dashboard_url.rb@@ -4,17 +4,28 @@ module Spree# someone into it: invitation emails, the SSO callback, the first-run# setup link.#- # Configure it with the SPREE_DASHBOARD_URL environment variable (read- # through the `dashboard_url` preference). The fallbacks exist so links- # still work in dev and on installs that never set it — the Vite dev- # server in development, then the store's own URL — but neither is a- # substitute for configuring the real origin in production.+ # Resolution order, most authoritative first:+ #+ # 1. the `dashboard_url` preference / SPREE_DASHBOARD_URL — an explicit+ # answer always wins+ # 2. the deprecated `admin_url` preference+ # 3. the dashboard this app serves itself, when `spree_dashboard` is+ # installed and has a build to serve (`/dashboard` on the app's own+ # host) — a fact about this deployment, so it beats the guess below+ # 4. the Vite dev server in development, for the monorepo/CLI workflow+ # where the dashboard runs as a separate process+ # 5. the store's own URL+ #+ # Steps 3-5 keep links working on installs that never configured an+ # origin; none is a substitute for setting SPREE_DASHBOARD_URL in+ # production, where the app's own host is rarely where admins go.class DashboardUrl# @param store [Spree::Store, nil] store whose URL ends the fallback chain# @return [String] origin without a trailing slash, e.g. +https://admin.shop.com+def self.call(store: nil)base = Spree::Config[:dashboard_url].presence ||legacy_admin_url ||+ mounted_dashboard_url(store) ||(Rails.env.development? ? 'http://localhost:5173' : nil) ||store&.formatted_url@@ -29,6 +40,35 @@ module SpreeSpree::Config.admin_url.presenceendprivate_class_method :legacy_admin_url++ # The `/dashboard` mount served by this app, when `spree_dashboard` is+ # installed AND pointed at a build. Without a build the route 404s, so+ # linking there would be worse than the dev-server guess.+ # @return [String, nil]+ def self.mounted_dashboard_url(store)+ return unless defined?(Spree::Dashboard) && Spree::Dashboard.dist_path.present?++ host = app_host(store)+ return if host.blank?++ "#{host.chomp('/')}/dashboard"+ end+ private_class_method :mounted_dashboard_url++ # Where this Rails app answers. `default_url_options` is what mailers+ # already rely on, so a deployment that gets email links right gets this+ # right too; the store URL is the last resort.+ # @return [String, nil]+ def self.app_host(store)+ options = Rails.application.routes.default_url_options+ return store&.formatted_url if options[:host].blank?++ protocol = options[:protocol].presence || 'http'+ port = options[:port]+ host = "#{protocol}://#{options[:host]}"+ port.present? ? "#{host}:#{port}" : host+ end+ private_class_method :app_hostendendenddiff --git a/spree/core/app/services/spree/seeds/admin_user.rb b/spree/core/app/services/spree/seeds/admin_user.rbindex 77cdbcd338..74af310ca5 100644--- a/spree/core/app/services/spree/seeds/admin_user.rb+++ b/spree/core/app/services/spree/seeds/admin_user.rb@@ -46,10 +46,12 @@ module Spreemessage = <<~MSG- ==> No admin account yet. Finish setup in the dashboard:+ ==> No admin account yet. Start your app, then open this link to+ create the first admin account:+#{store.setup_url}- (Run `bin/rails spree:setup:token` to print this link again.)+ (Run `bin/rails spree:setup:token` to print it again.)MSGdiff --git a/spree/core/lib/tasks/setup.rake b/spree/core/lib/tasks/setup.rakeindex 8f97f965b1..6bd2b9ec9f 100644--- a/spree/core/lib/tasks/setup.rake+++ b/spree/core/lib/tasks/setup.rake@@ -11,7 +11,7 @@ namespace :spree dostore.regenerate_setup_token if store.setup_token.blank? || ENV['ROTATE'].present?- puts 'Finish setup in the dashboard:'+ puts 'Open this link (with your app running) to create the first admin account:'puts " #{store.setup_url}"endenddiff --git a/spree/core/spec/finders/spree/stores/dashboard_url_spec.rb b/spree/core/spec/finders/spree/stores/dashboard_url_spec.rbindex 548a15e594..6422235f02 100644--- a/spree/core/spec/finders/spree/stores/dashboard_url_spec.rb+++ b/spree/core/spec/finders/spree/stores/dashboard_url_spec.rb@@ -36,4 +36,49 @@ RSpec.describe Spree::Stores::DashboardUrl doexpect(subject).not_to include('localhost:5173')endend++ # The bundled dashboard is a fact about the deployment, so it outranks the+ # Vite guess: an app serving /dashboard itself needs no second process for+ # the setup link to work.+ context 'when this app serves the bundled dashboard' do+ before do+ stub_const('ENV', ENV.to_h.except('SPREE_DASHBOARD_URL'))+ stub_const('Spree::Dashboard', Class.new { def self.dist_path = '/srv/dashboard' })+ allow(Rails.application.routes).to receive(:default_url_options).+ and_return(host: 'shop.example.com', protocol: 'https')+ end++ it 'points at the app’s own /dashboard mount, even in development' do+ allow(Rails.env).to receive(:development?).and_return(true)++ expect(subject).to eq('https://shop.example.com/dashboard')+ end++ it 'still yields to an explicitly configured origin' do+ Spree::Config.dashboard_url = 'https://admin.example.com'++ expect(subject).to eq('https://admin.example.com')+ ensure+ Spree::Config.dashboard_url = nil+ end++ it 'includes the port when the app runs on one' do+ allow(Rails.application.routes).to receive(:default_url_options).+ and_return(host: 'localhost', port: 3000)++ expect(subject).to eq('http://localhost:3000/dashboard')+ end+ end++ context 'when spree_dashboard is installed but has no build to serve' do+ before do+ stub_const('ENV', ENV.to_h.except('SPREE_DASHBOARD_URL'))+ stub_const('Spree::Dashboard', Class.new { def self.dist_path = nil })+ allow(Rails.env).to receive(:development?).and_return(true)+ end++ it 'skips the mount, which would 404, and uses the dev server' do+ expect(subject).to eq('http://localhost:5173')+ end+ endend