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
Serve the seller panel at /sellers, like the dashboard
Damian Legawiecb79e3f04a9f8
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4803ac357d..c7ec56f3e4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -135,6 +135,7 @@ One-time machine setup: Homebrew `postgresql@18` running on :5432 (with a `postg| E2E prerequisites | Once per worktree: `cd spree/api && bundle install && bundle exec rake test_app` (then `pnpm wt:e2e`) || Meilisearch search provider | Optional: `brew install meilisearch`, run it, set `MEILISEARCH_URL` in `server/.env`, `bin/rails spree:search:reindex` || Hosted dashboard at `/dashboard` (single-node test) | `pnpm server:dashboard` to build `packages/dashboard-starter/dist`, set `SPREE_DASHBOARD_DIST_PATH=<monorepo>/packages/dashboard-starter/dist` in `server/.env` |+| Hosted seller panel at `/sellers` (single-node test) | `pnpm server:seller` to build `packages/seller-dashboard-starter/dist`, set `SPREE_SELLER_PANEL_DIST_PATH=<monorepo>/packages/seller-dashboard-starter/dist` in `server/.env` || Broken beyond repair | `wt remove` and recreate — or `dropdb spree_dev_<branch>`, delete `server/`, re-run `pnpm wt:setup` |**The legacy Docker compose flow (`pnpm server:setup` / `server:dev` / `server:stop` etc.) is deprecated — never use it.** It exists only for spree-starter parity; it fights the worktree stack for ports and its teardown scripts wipe shared state.diff --git a/docs/developer/customization/configuration.mdx b/docs/developer/customization/configuration.mdxindex c4f6091546..e2855cb724 100644--- a/docs/developer/customization/configuration.mdx+++ b/docs/developer/customization/configuration.mdx@@ -23,7 +23,7 @@ Settings that describe the deployment rather than commerce behavior can be set w| 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`. |-| `seller_panel_url` | `SPREE_SELLER_PANEL_URL` | Origin where the marketplace seller panel is hosted (e.g. `https://sellers.my-shop.com`). Used for links sent to sellers, today the invitation email. Leave it unset on a marketplace with no seller panel — those links then open the dashboard. |+| `seller_panel_url` | `SPREE_SELLER_PANEL_URL` | Origin where the marketplace seller panel is hosted, when you serve it somewhere other than this app's own `/sellers` mount. Used for links sent to sellers, today the invitation email. Leave it unset to use `/sellers`; with no panel deployed at all, those links open the dashboard. |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.diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex 5969e4b20f..c3e4bbb6ca 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -737,6 +737,7 @@ Even before this lands, work touching adjacent areas should:- **The shared catalog ships as variant attributes plus one selection service** (RESOLVED 2026-08-16, shipped — Decision 11's Phase 1b). `spree_variants.seller_id` and `spree_variants.delivery_profile_id`, both nullable, and **two modes that never mix**: on an *owned* product (`products.seller_id` set) every variant is that seller's and ships as the product does — no other seller can create a variant there, so the variant's own columns carry no meaning and are kept blank by a normalizer; on a *master* product (`products.seller_id` nil, the shared catalog) each seller's row names its own seller and how it ships, falling back to the master's profile. The resolved answer is a plain read on the model (`resolved_seller`, `resolved_delivery_profile` — product's if owned, else the row's; no memo, no inheritance chain), and the API carries **one field each** (`seller_id`, `delivery_profile_id`), read resolved and written to the column, so a storefront never learns which mode it is in and a read-then-write round trip on an owned product changes nothing (the write is a no-op there). This deliberately departs from `Variant#tax_category`'s override-the-reader shape, and supersedes an earlier cut that modelled the seller as an inheritance-with-override and grew a second `own_*` name on the API to keep the round-trip safe — the domain has no override to model, so it needed neither. `Variant#digital?` moved onto the variant's own profile with it, which is what lets a download and its printed edition sit on one product. Condition is an `OptionType` shipped as **sample data, not a seed** (`db/sample_data/options.rb`, beside color; values new/refurbished/used): nothing in core keys on the word — the buy box groups by whatever option values it is given — so it is a merchant's choice, not an install prerequisite, and a store that sells only new goods never finds it on a fresh install, so it splits a product the way any axis does and the buy box keys on the option combination — a new buy box and a used one, at no extra cost. **The buy box is `Spree::Products::SelectBuyBox`** behind `Spree.product_buy_box_service`: computed on every read and never stored (it turns on price, stock and who is selling today, none of which hold still), ranking first-party ahead of sellers then cheapest, refusing to feature a seller who is suspended, onboarding or away, and still naming a variant when nothing is buyable so the page has a price to render. `purchasable?`/`in_stock?`/`backorderable?` now answer through the winner rather than `variants.any?` — a product is not purchasable because a suspended seller happens to hold stock — and `default_variant` prefers a first-party listing, since the headline price, SKU and the Omnibus `prior_price` are compliance claims about the operator's own pricing. **SKU uniqueness is scoped to the resolved seller** via a hand-written validation rather than a `scope:` option, because Rails' uniqueness validator reads the raw column and would have merged two sellers who each own a whole product into the nil scope. Cross-store binding is refused on the model (`seller`/`delivery_profile` must belong to the product's store), matching the pair already on Product. **Three pre-existing faults were fixed with it, each with a regression spec proven against the old code:** `Product#variants=`'s full-replacement delete was left as-is on the operator's path — the operator writes every seller's variants on a master — and the guard against a seller wiping a rival's rows lives at the seller branch, not the model (see "Writes never destroy another seller's variants" above), `Stock::Splitter::DeliveryProfile` and `Stock::Coordinator` re-keyed their memoisation off `product_id`, and `with_option_value_ids` now requires **one variant** to satisfy every axis (a `HAVING COUNT(DISTINCT option_type_id)` over one grouped subquery) instead of asking the product about each axis separately — "Blue AND XL" had matched a product selling a blue small beside a red XL, a live storefront bug independent of marketplaces. **Both search providers were fixed together**, since a filter's meaning is part of the provider contract and fixing one would have made results change when an operator installs the search gem: the Meilisearch document is per product, so its option values are a union across variants that cannot answer a per-variant question — the presenter now also emits `option_value_combination_ids` (one token per *combination* of values seen on the same variant) and a multi-axis filter asks for a whole combination, with single-axis filters and the disjunctive-facet queries unchanged. Whole combinations rather than pairs, because every pair holding on *some* variant is not the same as one variant holding them all — three variants (blue, XL, used), (blue, S, new) and (red, XL, new) satisfy each pair of "blue AND XL AND new" while none carries all three. Token count is exponential in the axis count, so it is capped (`MAX_COMBINATION_AXES`) and filters naming more axes fall back to the pairwise approximation. **The upgrade needs a reindex** — existing documents lack the field, so a multi-axis filter matches nothing until then; `search_reindex` is in the 5.6→6.0 manifest for exactly this and is a no-op on the database provider.- **Seller lifecycle → four workflows, never a writable `status`** (RESOLVED 2026-08-16, shipped). `Spree::Sellers::Invite` / `Approve` / `Suspend` / `Reject` (seams `seller_invite_workflow` and siblings), each with `validate` + `after_*` hooks and its own `seller.*` event. The Admin API exposes them as member actions (`POST invite`, `PATCH approve|suspend|reject`) and deliberately omits `status` from `permitted_params` — a PATCH that moved a seller would skip the mail, the payout provisioning and the extension hooks, which is exactly what `6.0-service-workflows.md` keeps out of a column write. Guards admit more than the linear path: `Approve` also lifts a suspension (clearing holiday mode with it) and revives a rejected applicant; `Suspend` is for a seller already on the marketplace while `Reject` is for one that never traded, so rejecting an approved seller is refused. Suspension and rejection reasons live in `metadata` rather than columns — each is a note about one event, and the next one has its own. Creation stays plain CRUD (it is not a lifecycle transition), so the default status is applied in an `after_initialize` on the model, as on `Spree::Fulfillment`.- **Lifecycle emails are seller-facing, event-driven, and skip the invitation** (RESOLVED 2026-08-16, shipped). `Spree::SellerMailer` (approved/suspended/rejected) in `spree_emails`, fired by `Spree::SellerEmailSubscriber` off the `seller.*` events the workflows already publish — nothing mails from a workflow step, so mail is one listener among several rather than something a transition waits on. Three departures from the legacy module: **no `seller.invited` email** (inviting creates an `Invitation`, which already mails the invitee — a second message would be the same news to the same address), **no marketplace-staff copies** (the legacy module mailed every store admin on approval and onboarding; staff read status in the dashboard, and per-admin fan-out across many sellers is the kind of noise merchants switch off — staff notifications ride the event/webhook surface), and **suspension/rejection reasons never appear in the email** (the operator's note is an internal record; the seller is asked to get in touch). Gated on a new `send_seller_transactional_emails` Store preference rather than the consumer one — sellers are a different audience, and silencing customer receipts must not silence seller mail. Onboarding started/completed emails wait for the onboarding task registry.+- **The seller panel is a path, not a subdomain** (RESOLVED 2026-08-18). Served at `/sellers` by `spree_dashboard`, exactly as the operator's dashboard is served at `/dashboard` — same engine, same SPA controller (generalised to `Spree::Dashboard::SpaController`, which a subclass points at a bundle), `SPREE_SELLER_PANEL_DIST_PATH` beside `SPREE_DASHBOARD_DIST_PATH`. Nothing forced a second hostname: the two panels' refresh cookies are already isolated by name and path (`/api/v3/admin/auth` vs `/api/v3/seller/auth`), so sharing an origin costs nothing in isolation and saves every deployment a hostname, a certificate and a CORS allowlist entry. `SPREE_SELLER_PANEL_URL` remains for marketplaces that do want sellers on their own domain, and `Sellers::PanelUrl` now resolves the `/sellers` mount before falling back to the dashboard. The dev-time `sellers.<branch>` host stays — two Vite servers cannot share an origin root, which is why `admin.<branch>` exists too. **Constraint:** a link the panel builds from a path must resolve against `BASE_URL`, never `window.location.origin` alone, or it misses the mount.- **Team management mirrors the operator's staff page** (RESOLVED 2026-08-18). Members in a table, pending offers in their own card, one invite dialog — the same layout, components and row actions as Settings → Staff, because it is the same job seen from the other side. Pending invitations were the gap that made the first cut feel broken: inviting someone changed nothing visible, since `team#index` lists accepted members only. A seller now gets `/seller/invitations` (index/destroy + `PATCH resend`), matching the admin surface, and the seller invitation serializer carries `acceptance_url` so a colleague who never got the email can be handed the link. Deliberately a separate controller from `team`: sending an invitation is hiring, chasing or withdrawing one is bookkeeping on the offer. **Roles stay single** — everyone holds the seller's seeded role, so inviting asks only for an address; narrower seller roles need seller-scoped role management first and are a design of their own. One framework lesson: the panel must extend `@spree/dashboard-core/lib/i18n` rather than call `init()` itself, or shared components render raw keys (`admin.row_actions.menu_label`) — a second `init()` wins the race and drops the framework's own copy.- **An invitation opens the app it is an invitation to** (RESOLVED 2026-08-17). The `admin_invitation_acceptance` route branches on `invitation.resource`: onto a `Spree::Seller` it resolves `Spree::Sellers::PanelUrl` (the `seller_panel_url` preference / SPREE_SELLER_PANEL_URL), everything else keeps the dashboard origin. Not cosmetic — the dashboard's acceptance page authenticates through the Admin API, which no seller may call, so a seller sent there could read the invitation and never accept it. The panel gets its own acceptance page and the seller API its own `auth/invitations/:id/{lookup,accept}`, parallel to the admin pair rather than subclassing it: what differs is the audience issued and the invitations it will touch, and both are the point — accepting a *staff* invitation here is refused as `not_found`, since it carries no seller membership and would mint a seller token for someone who runs no seller. With no panel deployed the link falls back to the dashboard; a marketplace that never onboards sellers by email need configure nothing.- **The seller panel is its own app and its own SDK** (RESOLVED 2026-08-17). `@spree/seller-sdk` beside `@spree/sdk` and `@spree/admin-sdk`, and `packages/seller-dashboard` (shell) + `packages/seller-dashboard-starter` (host) beside their dashboard counterparts — not a mode of the admin app. The credentials differ in kind, not degree: a seller JWT only (no secret-key equivalent exists), `X-Spree-Seller-Id` rather than `X-Spree-Store-Id` (the store is derived from the seller), and a refresh cookie whose name and path are deliberately not shared. Typing those as optional-but-meaningless on one client is how a panel ends up able to call the wrong API.diff --git a/package.json b/package.jsonindex e77011bb6c..030ff8d42e 100644--- a/package.json+++ b/package.json@@ -14,6 +14,7 @@"server:create": "git clone --depth 1 --branch 6-0-dev https://github.com/spree/spree-starter.git server && rm -rf server/.git server/.gitignore && printf 'SPREE_PATH=..\\nSECRET_KEY_BASE=%s\\n' \"$(openssl rand -hex 64)\" > server/.env","server:setup": "bash scripts/server-setup.sh","server:dashboard": "turbo build --filter=@spree/dashboard && VITE_BASE_PATH=/dashboard/ pnpm --dir packages/dashboard-starter build",+ "server:seller": "turbo build --filter=@spree/seller-dashboard && VITE_BASE_PATH=/sellers/ pnpm --dir packages/seller-dashboard-starter build","server:dev": "SPREE_PATH=$PWD docker compose -f server/docker-compose.dev.yml -f scripts/docker-compose.edge.yml ${SPREE_MEILISEARCH:+-f scripts/docker-compose.meilisearch.yml} up --force-recreate --remove-orphans web","server:build": "bash scripts/server-build.sh","server:restart": "SPREE_PATH=$PWD docker compose -f server/docker-compose.dev.yml -f scripts/docker-compose.edge.yml restart web",diff --git a/packages/seller-dashboard/package.json b/packages/seller-dashboard/package.jsonindex 594c701e93..ec94020f2d 100644--- a/packages/seller-dashboard/package.json+++ b/packages/seller-dashboard/package.json@@ -35,10 +35,10 @@"@tanstack/react-router": "^1.133.32","@tanstack/router-plugin": "^1.167.35","@tanstack/virtual-file-routes": "^1.162.0",- "i18next": "^25.6.0",+ "i18next": "^26.2.0","lucide-react": "^0.545.0","react-hook-form": "^7.65.0",- "react-i18next": "^16.0.0",+ "react-i18next": "^17.0.8","sonner": "^2.0.7","zod": "^4.4.3"},diff --git a/packages/seller-dashboard/src/i18n.ts b/packages/seller-dashboard/src/i18n.tsindex 7d19dfd6ee..0f7a2f52a5 100644--- a/packages/seller-dashboard/src/i18n.ts+++ b/packages/seller-dashboard/src/i18n.ts@@ -1,12 +1,16 @@// Extends the framework's i18n rather than standing up a second instance.//-// `@spree/dashboard-core/lib/i18n` initialises i18next and registers the-// framework's own copy — the strings baked into shared components like-// `RowActions` and the confirm dialog. A panel that called `init()` itself-// would win the race and leave those components rendering raw keys-// (`admin.row_actions.menu_label`) wherever they appear.+// The side-effect import initialises i18next and registers the framework's+// own copy — the strings baked into shared components like `RowActions` and+// the confirm dialog. A panel that called `init()` itself would win the race+// and leave those components rendering raw keys+// (`admin.row_actions.menu_label`) wherever they appear. It must come first:+// side-effect imports are ordering barriers.import '@spree/dashboard-core/lib/i18n'-import i18n from 'i18next'+// The instance comes from core too, not a bare `i18next` import: a bundled+// build can resolve a second copy of the package, and `addResourceBundle` on+// that one throws. Core re-exports the object it initialised for exactly this.+import { i18n } from '@spree/dashboard-core'import en from './locales/en.json'/**diff --git a/packages/seller-dashboard/src/index.ts b/packages/seller-dashboard/src/index.tsindex 9c46d0ba32..b41a5b7403 100644--- a/packages/seller-dashboard/src/index.ts+++ b/packages/seller-dashboard/src/index.ts@@ -1,3 +1,9 @@+// The i18n bootstrap runs on import and must come first: route modules and+// table definitions call `i18n.t(...)` at module load, so a bundler that+// evaluated them before this would bake raw keys into the UI. Side-effect+// imports are ordering barriers, which is exactly what this relies on.+import './i18n'+export {createSellerApiClient,rememberedSeller,diff --git a/packages/seller-dashboard/src/pages/team.tsx b/packages/seller-dashboard/src/pages/team.tsxindex 95681b467d..7c6edd8044 100644--- a/packages/seller-dashboard/src/pages/team.tsx+++ b/packages/seller-dashboard/src/pages/team.tsx@@ -288,10 +288,15 @@ function InvitationRow({ invitation }: { invitation: Invitation }) {})async function handleCopyLink() {- // Path-only when no panel origin is configured; resolve against this- // panel's own origin, which is where the link would land anyway.+ // Path-only when no panel origin is configured; resolve against wherever+ // this panel is actually mounted. `BASE_URL` matters: served at /sellers+ // (the single-node topology), origin alone would produce a link that+ // misses the mount and 404s.const url = invitation.acceptance_url.startsWith('/')- ? `${window.location.origin}${invitation.acceptance_url}`+ ? new URL(+ `.${invitation.acceptance_url}`,+ `${window.location.origin}${import.meta.env.BASE_URL}`,+ ).toString(): invitation.acceptance_urlawait copy(url)diff --git a/packages/seller-dashboard/src/seller-dashboard.tsx b/packages/seller-dashboard/src/seller-dashboard.tsxindex 74613a60b5..83ffb598e6 100644--- a/packages/seller-dashboard/src/seller-dashboard.tsx+++ b/packages/seller-dashboard/src/seller-dashboard.tsx@@ -4,7 +4,6 @@ import { QueryClientProvider } from '@tanstack/react-query'import type { AnyRouter } from '@tanstack/react-router'import { RouterProvider } from '@tanstack/react-router'import { StrictMode } from 'react'-import './i18n'/*** The seller panel shell.diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f80050fc62..cefdae0157 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -675,8 +675,8 @@ importers:specifier: ^1.162.0version: 1.162.0i18next:- specifier: ^25.6.0- version: 25.10.10([email protected])+ specifier: ^26.2.0+ version: 26.2.0([email protected])lucide-react:specifier: ^0.545.0version: 0.545.0([email protected])@@ -684,8 +684,8 @@ importers:specifier: ^7.65.0version: 7.75.0([email protected])react-i18next:- specifier: ^16.0.0- version: 16.6.6([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])+ specifier: ^17.0.8+ version: 17.0.8([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected])sonner:specifier: ^2.0.7@@ -3251,14 +3251,6 @@ packages:resolution: {integrity: sha512-eKCa6bwnJhvxj14kZk5NCPc6Hb6BdsU9DZcOnmQKSnO1VKrfV0zCvtttPZUsBvjmNDn8rpcJfpwSYnHBjc95MQ==}engines: {node: '>=18.18.0'}- resolution: {integrity: sha512-cqUW2Z3EkRx7NqSyywjkgCLK7KLCL6IFVFcONG7nVYIJ3ekZ1/N5jUsihHV6Bq37NfhgtczxJcxduELtjTwkuQ==}- peerDependencies:- typescript: ^5 || ^6- peerDependenciesMeta:- typescript:- optional: true-resolution: {integrity: sha512-zwBHldHdTmwN7r6UNc7lC6GWNN+YYg3DrRSeHR5PRRBf5QnJZcYHrQc0uaU26qZeYxR7iFZD+Y315dPnKP47wA==}peerDependencies:@@ -4008,22 +4000,6 @@ packages:peerDependencies:react: ^16.8.0 || ^17 || ^18 || ^19- resolution: {integrity: sha512-ZgL2HUoW34UKUkOV7uSQFE1CDnRPD+tCR3ywSuWH7u2iapnz86U8Bi3Vrs620qNDzCf1F47NxglCEkchCTDOHw==}- peerDependencies:- i18next: '>= 25.10.9'- react: '>= 16.8.0'- react-dom: '*'- react-native: '*'- typescript: ^5 || ^6- peerDependenciesMeta:- react-dom:- optional: true- react-native:- optional: true- typescript:- optional: true-resolution: {integrity: sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw==}peerDependencies:@@ -7084,12 +7060,6 @@ snapshots:- dependencies:- '@babel/runtime': 7.29.2- optionalDependencies:- typescript: 6.0.3-optionalDependencies:typescript: 6.0.3@@ -7741,17 +7711,6 @@ snapshots:dependencies:react: 19.2.6- [email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):- dependencies:- '@babel/runtime': 7.29.2- html-parse-stringify: 3.0.1- i18next: 25.10.10([email protected])- react: 19.2.6- use-sync-external-store: 1.6.0([email protected])- optionalDependencies:- react-dom: 19.2.6([email protected])- typescript: 6.0.3-[email protected]([email protected]([email protected]))([email protected]([email protected]))([email protected])([email protected]):dependencies:'@babel/runtime': 7.29.2diff --git a/spree/core/app/finders/spree/sellers/panel_url.rb b/spree/core/app/finders/spree/sellers/panel_url.rbindex b8c5b8485f..c428fcf868 100644--- a/spree/core/app/finders/spree/sellers/panel_url.rb+++ b/spree/core/app/finders/spree/sellers/panel_url.rb@@ -12,12 +12,12 @@ module Spree# Resolution order, most authoritative first:## 1. the `seller_panel_url` preference / SPREE_SELLER_PANEL_URL- # 2. the dashboard origin, as a last resort+ # 2. the `/sellers` mount this app serves, when a bundle is configured+ # 3. the dashboard origin, as a last resort#- # The fallback is deliberate. A marketplace that has not deployed a panel- # still has to send a working invitation, and the staff dashboard at least- # exists; sending nowhere would be worse. Configure- # SPREE_SELLER_PANEL_URL and sellers land on their own app.+ # The last fallback is deliberate. A marketplace that has not deployed a+ # panel still has to send a working invitation, and the staff dashboard at+ # least exists; sending nowhere would be worse.class PanelUrl# @param store [Spree::Store, nil] store whose URL ends the fallback chain# @return [String] origin without a trailing slash, e.g. +https://sellers.shop.com+@@ -26,8 +26,22 @@ module Spreereturn configured.to_s.chomp('/') if configured- Spree::Stores::DashboardUrl.call(store: store)+ mounted_panel_url(store) || Spree::Stores::DashboardUrl.call(store: store)end++ # The `/sellers` mount this app serves, when `spree_dashboard` is+ # installed AND pointed at a seller-panel build. Without a bundle the+ # route 404s, so linking there would be worse than the dashboard.+ # @return [String, nil]+ def self.mounted_panel_url(store)+ return unless defined?(Spree::SellerPanel) && Spree::SellerPanel.dist_path.present?++ host = Spree::Stores::DashboardUrl.app_host(store)+ return if host.blank?++ "#{host.chomp('/')}/sellers"+ end+ private_class_method :mounted_panel_urlendendenddiff --git a/spree/core/app/finders/spree/stores/dashboard_url.rb b/spree/core/app/finders/spree/stores/dashboard_url.rbindex 54f7933cb9..c1f1b9fa1b 100644--- a/spree/core/app/finders/spree/stores/dashboard_url.rb+++ b/spree/core/app/finders/spree/stores/dashboard_url.rb@@ -58,6 +58,9 @@ module Spree# 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.+ #+ # Public because the seller panel resolves its own `/sellers` mount+ # against the same host — both are asking where this app serves.# @return [String, nil]def self.app_host(store)options = Rails.application.routes.default_url_options@@ -68,7 +71,6 @@ module Spreehost = "#{protocol}://#{options[:host]}"port.present? ? "#{host}:#{port}" : hostend- private_class_method :app_hostendendenddiff --git a/spree/core/spec/finders/spree/sellers/panel_url_spec.rb b/spree/core/spec/finders/spree/sellers/panel_url_spec.rbnew file mode 100644index 0000000000..f7e4aff677--- /dev/null+++ b/spree/core/spec/finders/spree/sellers/panel_url_spec.rb@@ -0,0 +1,43 @@+require 'spec_helper'++RSpec.describe Spree::Sellers::PanelUrl do+ let(:store) { @default_store }++ after do+ Spree::Config[:seller_panel_url] = nil+ Spree::Config[:dashboard_url] = nil+ end++ it 'prefers an explicitly configured panel origin' do+ Spree::Config[:seller_panel_url] = 'https://sellers.example.com/'+ Spree::Config[:dashboard_url] = 'https://admin.example.com'++ expect(described_class.call(store: store)).to eq('https://sellers.example.com')+ end++ # The single-node topology: Spree serves the panel itself at /sellers, so a+ # link there works without any hostname of its own. `Spree::SellerPanel`+ # ships in the optional spree_dashboard gem, which core's suite does not+ # load — hence the resolver's `defined?` guard, and this stand-in.+ context 'when this app serves a seller panel bundle' do+ before do+ stub_const('Spree::SellerPanel', Module.new do+ def self.dist_path = '/tmp/panel-dist'+ end)+ end++ it 'points at the mount rather than the dashboard' do+ Spree::Config[:dashboard_url] = 'https://admin.example.com'++ expect(described_class.call(store: store)).to end_with('/sellers')+ end+ end++ # A marketplace that has not deployed a panel still has to send a working+ # invitation, and the dashboard at least exists.+ it 'falls back to the dashboard origin when nothing else resolves' do+ Spree::Config[:dashboard_url] = 'https://admin.example.com'++ expect(described_class.call(store: store)).to eq('https://admin.example.com')+ end+enddiff --git a/spree/dashboard/app/controllers/spree/dashboard/app_controller.rb b/spree/dashboard/app/controllers/spree/dashboard/app_controller.rbindex 59dd0e5858..15e3585c3c 100644--- a/spree/dashboard/app/controllers/spree/dashboard/app_controller.rb+++ b/spree/dashboard/app/controllers/spree/dashboard/app_controller.rb@@ -1,77 +1,16 @@module Spreemodule Dashboard- # Serves a built React Dashboard (`vite build` output) at /dashboard — the- # single-node topology: the SPA and the Admin API share one origin, so no- # CORS entries and Lax cookies. The dist directory comes from- # `Spree::Dashboard.dist_path` (the official Docker image sets it via- # SPREE_DASHBOARD_DIST_PATH); when unset, /dashboard 404s.+ # Serves the built React Dashboard at /dashboard. Everything about how a+ # bundle is served lives in SpaController; this names which bundle.#- # SPA semantics: real files are served with long-lived caching (Vite's- # `assets/` are content-hashed, so they're immutable); every other path- # falls back to index.html with no-cache so deploys take effect on the- # next navigation. No authentication — the bundle is public client code;- # the SPA authenticates its API calls itself.- class AppController < ActionController::Base- # GET-only file serving mutates nothing, but enable forgery protection- # anyway so the controller stays safe if an action is ever added.- protect_from_forgery with: :exception- # `verify_same_origin_request` blocks JavaScript responses to plain GET- # requests — protection against JSONP-style data leaks from dynamically- # generated JS. The Vite bundle is static public code that the SPA's own- # <script> tags must load, which is exactly that request shape.- skip_after_action :verify_same_origin_request-- def show- root = dist_root- return head :not_found unless root-- if (file = resolve_file(root, params[:path].to_s))- response.headers['Cache-Control'] = cache_control_for(params[:path].to_s)- send_file file, disposition: 'inline'- elsif (index = root.join('index.html')).file?- response.headers['Cache-Control'] = 'no-cache'- send_file index, type: 'text/html', disposition: 'inline'- else- head :not_found- end- end-+ # The dist directory comes from `Spree::Dashboard.dist_path` (the official+ # Docker image sets it via SPREE_DASHBOARD_DIST_PATH); when unset,+ # /dashboard 404s.+ class AppController < SpaControllerprivate- def dist_root- path = Spree::Dashboard.dist_path- return if path.blank?-- root = Pathname.new(path).expand_path- root if root.directory?- end-- # Resolve a request path to a real file inside the dist directory.- # Defense in depth against traversal: reject null bytes, absolute- # paths, and any `.`/`..` segment before touching the filesystem, then- # verify the expanded path still lives under the dist root (which also- # covers symlinks pointing outside it).- def resolve_file(root, relative_path)- return if relative_path.blank? || relative_path.include?("\0")-- relative = Pathname.new(relative_path)- return if relative.absolute?-- segments = relative.each_filename.to_a- return if segments.empty? || segments.any? { |segment| segment == '.' || segment == '..' }-- candidate = root.join(*segments).expand_path- return unless candidate.to_s.start_with?("#{root}#{File::SEPARATOR}")-- candidate if candidate.file?- end-- def cache_control_for(relative_path)- if relative_path.start_with?('assets/')- 'public, max-age=31536000, immutable'- else- 'public, max-age=3600'- end+ def dist_path+ Spree::Dashboard.dist_pathendendenddiff --git a/spree/dashboard/app/controllers/spree/dashboard/spa_controller.rb b/spree/dashboard/app/controllers/spree/dashboard/spa_controller.rbnew file mode 100644index 0000000000..f7d6c5c9db--- /dev/null+++ b/spree/dashboard/app/controllers/spree/dashboard/spa_controller.rb@@ -0,0 +1,86 @@+module Spree+ module Dashboard+ # Serves a built Vite SPA from a directory on disk — the single-node+ # topology, where the SPA and the API it calls share one origin, so no+ # CORS entries and Lax cookies.+ #+ # Abstract: a subclass names the directory by implementing `dist_path`.+ # Two panels ride on this — the operator's dashboard at /dashboard and the+ # marketplace seller panel at /sellers — and they differ in nothing but+ # that directory and their mount point.+ #+ # SPA semantics: real files are served with long-lived caching (Vite's+ # `assets/` are content-hashed, so they're immutable); every other path+ # falls back to index.html with no-cache so deploys take effect on the+ # next navigation. No authentication — the bundle is public client code;+ # the SPA authenticates its API calls itself.+ class SpaController < ActionController::Base+ # GET-only file serving mutates nothing, but enable forgery protection+ # anyway so the controller stays safe if an action is ever added.+ protect_from_forgery with: :exception+ # `verify_same_origin_request` blocks JavaScript responses to plain GET+ # requests — protection against JSONP-style data leaks from dynamically+ # generated JS. The Vite bundle is static public code that the SPA's own+ # <script> tags must load, which is exactly that request shape.+ skip_after_action :verify_same_origin_request++ def show+ root = dist_root+ return head :not_found unless root++ if (file = resolve_file(root, params[:path].to_s))+ response.headers['Cache-Control'] = cache_control_for(params[:path].to_s)+ send_file file, disposition: 'inline'+ elsif (index = root.join('index.html')).file?+ response.headers['Cache-Control'] = 'no-cache'+ send_file index, type: 'text/html', disposition: 'inline'+ else+ head :not_found+ end+ end++ private++ # @return [String, nil] directory holding the built bundle+ def dist_path+ raise NotImplementedError, "#{self.class} must implement #dist_path"+ end++ def dist_root+ path = dist_path+ return if path.blank?++ root = Pathname.new(path).expand_path+ root if root.directory?+ end++ # Resolve a request path to a real file inside the dist directory.+ # Defense in depth against traversal: reject null bytes, absolute+ # paths, and any `.`/`..` segment before touching the filesystem, then+ # verify the expanded path still lives under the dist root (which also+ # covers symlinks pointing outside it).+ def resolve_file(root, relative_path)+ return if relative_path.blank? || relative_path.include?("\0")++ relative = Pathname.new(relative_path)+ return if relative.absolute?++ segments = relative.each_filename.to_a+ return if segments.empty? || segments.any? { |segment| segment == '.' || segment == '..' }++ candidate = root.join(*segments).expand_path+ return unless candidate.to_s.start_with?("#{root}#{File::SEPARATOR}")++ candidate if candidate.file?+ end++ def cache_control_for(relative_path)+ if relative_path.start_with?('assets/')+ 'public, max-age=31536000, immutable'+ else+ 'public, max-age=3600'+ end+ end+ end+ end+enddiff --git a/spree/dashboard/app/controllers/spree/seller_panel/app_controller.rb b/spree/dashboard/app/controllers/spree/seller_panel/app_controller.rbnew file mode 100644index 0000000000..08b7e56d71--- /dev/null+++ b/spree/dashboard/app/controllers/spree/seller_panel/app_controller.rb@@ -0,0 +1,23 @@+module Spree+ module SellerPanel+ # Serves the built marketplace seller panel at /sellers.+ #+ # Same origin as the dashboard and the API on purpose: the two panels'+ # refresh cookies are already isolated by name and path+ # (`/api/v3/admin/auth` vs `/api/v3/seller/auth`), so sharing a host costs+ # nothing in isolation and saves every deployment a second hostname and+ # certificate. A marketplace that wants sellers on their own domain+ # deploys the bundle there and points SPREE_SELLER_PANEL_URL at it.+ #+ # The dist directory comes from `Spree::SellerPanel.dist_path`; when+ # unset, /sellers 404s — a marketplace that runs no seller panel serves+ # nothing rather than an empty shell.+ class AppController < Spree::Dashboard::SpaController+ private++ def dist_path+ Spree::SellerPanel.dist_path+ end+ end+ end+enddiff --git a/spree/dashboard/config/routes.rb b/spree/dashboard/config/routes.rbindex 98b31d5226..0c554bed5e 100644--- a/spree/dashboard/config/routes.rb+++ b/spree/dashboard/config/routes.rb@@ -5,4 +5,10 @@ Spree::Core::Engine.add_routes do# being parsed as a response format.get '/dashboard', to: 'dashboard/app#show', as: :dashboard_appget '/dashboard/*path', to: 'dashboard/app#show', format: false++ # Hosted seller panel, same topology as the dashboard above. Its own mount+ # rather than a nested route: it is a separate app with its own bundle, and+ # a marketplace that runs no seller panel leaves it unconfigured.+ get '/sellers', to: 'seller_panel/app#show', as: :seller_panel_app+ get '/sellers/*path', to: 'seller_panel/app#show', format: falseenddiff --git a/spree/dashboard/lib/spree/dashboard.rb b/spree/dashboard/lib/spree/dashboard.rbindex 273094e336..21bbfa5006 100644--- a/spree/dashboard/lib/spree/dashboard.rb+++ b/spree/dashboard/lib/spree/dashboard.rb@@ -16,4 +16,7 @@ module Spreeendend+# The seller panel rides in this gem: same engine, same SPA-serving+# controller, a different bundle at a different mount.+require 'spree/seller_panel'require 'spree/dashboard/engine'diff --git a/spree/dashboard/lib/spree/seller_panel.rb b/spree/dashboard/lib/spree/seller_panel.rbnew file mode 100644index 0000000000..058e088bc5--- /dev/null+++ b/spree/dashboard/lib/spree/seller_panel.rb@@ -0,0 +1,17 @@+require 'spree'++module Spree+ module SellerPanel+ class << self+ # Directory holding a built seller panel (`vite build` output), served+ # at /sellers. Set from an initializer, or via the+ # SPREE_SELLER_PANEL_DIST_PATH env var. Unset, /sellers responds 404 —+ # a marketplace that runs no seller panel serves nothing.+ attr_writer :dist_path++ def dist_path+ @dist_path.presence || ENV.fetch('SPREE_SELLER_PANEL_DIST_PATH', nil)+ end+ end+ end+enddiff --git a/spree/dashboard/spec/requests/spree/seller_panel/app_spec.rb b/spree/dashboard/spec/requests/spree/seller_panel/app_spec.rbnew file mode 100644index 0000000000..3b1fd60138--- /dev/null+++ b/spree/dashboard/spec/requests/spree/seller_panel/app_spec.rb@@ -0,0 +1,73 @@+require 'spec_helper'++RSpec.describe 'Hosted seller panel', type: :request do+ let(:dist) { Dir.mktmpdir }++ before do+ File.write(File.join(dist, 'index.html'), '<html>seller panel shell</html>')+ FileUtils.mkdir_p(File.join(dist, 'assets'))+ File.write(File.join(dist, 'assets', 'panel-abc123.js'), 'console.log("panel")')+ end++ after do+ FileUtils.remove_entry(dist)+ Spree::SellerPanel.dist_path = nil+ Spree::Dashboard.dist_path = nil+ end++ # A marketplace that runs no seller panel serves nothing, rather than an+ # empty shell that looks broken.+ context 'when no bundle is configured' do+ it 'returns 404' do+ get '/sellers'+ expect(response).to have_http_status(:not_found)+ end+ end++ context 'when a bundle is configured' do+ before { Spree::SellerPanel.dist_path = dist }++ it 'serves the shell at the mount root' do+ get '/sellers'++ expect(response).to have_http_status(:ok)+ expect(response.body).to include('seller panel shell')+ expect(response.headers['Cache-Control']).to eq('no-cache')+ end++ # Deep links are the point: an invitation lands on+ # /sellers/accept-invitation/... and the SPA routes it client-side.+ it 'falls back to the shell for client-side routes' do+ get '/sellers/accept-invitation/inv_abc'++ expect(response).to have_http_status(:ok)+ expect(response.body).to include('seller panel shell')+ end++ it 'serves hashed assets as immutable' do+ get '/sellers/assets/panel-abc123.js'++ expect(response).to have_http_status(:ok)+ expect(response.headers['Cache-Control']).to include('immutable')+ end++ it 'refuses to escape the bundle directory' do+ get '/sellers/assets/%2e%2e/%2e%2e/config/database.yml'++ # Either refused outright or answered with the SPA shell — never the file.+ expect(response.body).not_to include('adapter:')+ end++ # The two panels are separate apps: configuring one must not serve the+ # other, or a marketplace with no seller panel would hand sellers the+ # operator's dashboard.+ it 'does not serve the dashboard bundle' do+ Spree::SellerPanel.dist_path = nil+ Spree::Dashboard.dist_path = dist++ get '/sellers'++ expect(response).to have_http_status(:not_found)+ end+ end+end