Skip to content

armgit / spree

Public Imported from GitHub
0

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

Simplify: shared authed-download helper, hoisted origin gate

Damian Legawiec473289e13d86
diff --git a/packages/dashboard-core/src/components/import-button.tsx b/packages/dashboard-core/src/components/import-button.tsx
index b7fad4b119..60d6276a88 100644
--- a/packages/dashboard-core/src/components/import-button.tsx
+++ b/packages/dashboard-core/src/components/import-button.tsx
@@ -137,7 +137,6 @@ export function ImportButton({ type, subject, onCreated, label }: ImportButtonPr
variant="file"
icon={<FileSpreadsheetIcon />}
dropLabel={t('admin.components.import_button.drop_label')}
- browseLabel={t('admin.components.import_button.browse')}
// Windows browsers report `.csv` as `application/vnd.ms-excel`,
// which the server's content-type validation rejects.
transformFile={(picked) => new File([picked], picked.name, { type: 'text/csv' })}
diff --git a/packages/dashboard-core/src/hooks/use-export.ts b/packages/dashboard-core/src/hooks/use-export.ts
index 3a739ec75d..ae0c3a4cd8 100644
--- a/packages/dashboard-core/src/hooks/use-export.ts
+++ b/packages/dashboard-core/src/hooks/use-export.ts
@@ -2,13 +2,12 @@ import type { Export, ExportCreateParams } from '@spree/admin-sdk'
import { useMutation } from '@tanstack/react-query'
import { toast } from 'sonner'
import { adminClient } from '../client'
+import { downloadFromApi } from '../lib/download'
import { i18n } from '../lib/i18n'
import { useAuth } from './use-auth'
const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 5 * 60 * 1000
-const API_BASE_URL = import.meta.env.VITE_SPREE_API_URL || ''
-const API_ORIGIN = API_BASE_URL ? new URL(API_BASE_URL).origin : window.location.origin
class ExportTimeoutError extends Error {
constructor() {
@@ -17,18 +16,6 @@ class ExportTimeoutError extends Error {
}
}
-/**
- * Resolve `download_url` (a path or absolute URL) against the API base.
- * Returns both the resolved URL and whether it points at the trusted API
- * origin — only same-origin requests get the `Authorization` header so we
- * can't accidentally leak a JWT to a third-party host.
- */
-function resolveDownload(downloadUrl: string): { url: string; sameOrigin: boolean } {
- const url = /^https?:\/\//.test(downloadUrl) ? downloadUrl : `${API_BASE_URL}${downloadUrl}`
- const sameOrigin = new URL(url, window.location.origin).origin === API_ORIGIN
- return { url, sameOrigin }
-}
-
async function pollUntilDone(id: string): Promise<Export> {
const deadline = Date.now() + POLL_TIMEOUT_MS
@@ -41,31 +28,10 @@ async function pollUntilDone(id: string): Promise<Export> {
throw new ExportTimeoutError()
}
-// `window.location` won't carry the in-memory JWT, so we fetch the file
-// ourselves and drive the download via a Blob URL.
async function downloadExportFile(exp: Export, token: string | null): Promise<void> {
if (!exp.download_url) throw new Error('Export has no download_url')
- const { url, sameOrigin } = resolveDownload(exp.download_url)
- const headers: Record<string, string> = {}
- if (sameOrigin && token) headers.Authorization = `Bearer ${token}`
-
- const response = await fetch(url, {
- headers,
- credentials: sameOrigin ? 'include' : 'omit',
- })
-
- if (!response.ok) throw new Error(`Download failed: ${response.status}`)
-
- const blob = await response.blob()
- const objectUrl = URL.createObjectURL(blob)
- const anchor = document.createElement('a')
- anchor.href = objectUrl
- anchor.download = exp.filename ?? 'export.csv'
- document.body.appendChild(anchor)
- anchor.click()
- anchor.remove()
- URL.revokeObjectURL(objectUrl)
+ await downloadFromApi(token, exp.download_url, exp.filename ?? 'export.csv')
}
/**
diff --git a/packages/dashboard-core/src/hooks/use-import.ts b/packages/dashboard-core/src/hooks/use-import.ts
index a5efe729c1..46dafb87f4 100644
--- a/packages/dashboard-core/src/hooks/use-import.ts
+++ b/packages/dashboard-core/src/hooks/use-import.ts
@@ -1,11 +1,10 @@
import type { Import, ImportCreateParams, ImportType } from '@spree/admin-sdk'
import { useMutation } from '@tanstack/react-query'
import { adminClient } from '../client'
+import { downloadFromApi } from '../lib/download'
import { useStore } from '../providers/store-provider'
import { useAuth } from './use-auth'
-const API_BASE_URL = import.meta.env.VITE_SPREE_API_URL || ''
-
export interface CreateImportInput {
type: ImportType
/** Signed blob id of the already direct-uploaded CSV (see `FileUploadField`). */
@@ -34,31 +33,6 @@ export function useCreateImport() {
})
}
-/**
- * Authed fetch → Blob URL download. The endpoints are JWT-protected, so a
- * top-level navigation (which cannot carry the in-memory token) does not work.
- */
-async function downloadFromApi(token: string | null, path: string, fallbackName: string) {
- const headers: Record<string, string> = {}
- if (token) headers.Authorization = `Bearer ${token}`
-
- const response = await fetch(`${API_BASE_URL}${path}`, { headers, credentials: 'include' })
- if (!response.ok) throw new Error(`Download failed: ${response.status}`)
-
- const disposition = response.headers.get('Content-Disposition')
- const filename = disposition?.match(/filename="?([^";]+)"?/)?.[1] ?? fallbackName
-
- const blob = await response.blob()
- const objectUrl = URL.createObjectURL(blob)
- const anchor = document.createElement('a')
- anchor.href = objectUrl
- anchor.download = filename
- document.body.appendChild(anchor)
- anchor.click()
- anchor.remove()
- URL.revokeObjectURL(objectUrl)
-}
-
/** Downloads the CSV template for an import type. */
export function useDownloadImportTemplate() {
const { token } = useAuth()
diff --git a/packages/dashboard-core/src/lib/download.ts b/packages/dashboard-core/src/lib/download.ts
new file mode 100644
index 0000000000..e91c281445
--- /dev/null
+++ b/packages/dashboard-core/src/lib/download.ts
@@ -0,0 +1,49 @@
+const API_BASE_URL = import.meta.env.VITE_SPREE_API_URL || ''
+
+/**
+ * Resolve `urlOrPath` (a path or absolute URL) against the API base and
+ * report whether it targets the trusted API origin. Origins are computed
+ * lazily so importing this module never touches `window` (node test envs).
+ */
+function resolveApiUrl(urlOrPath: string): { url: string; sameOrigin: boolean } {
+ const url = /^https?:\/\//.test(urlOrPath) ? urlOrPath : `${API_BASE_URL}${urlOrPath}`
+ const apiOrigin = API_BASE_URL ? new URL(API_BASE_URL).origin : window.location.origin
+ const sameOrigin = new URL(url, window.location.origin).origin === apiOrigin
+ return { url, sameOrigin }
+}
+
+/**
+ * Authed fetch → Blob URL download for JWT-protected endpoints — a top-level
+ * navigation cannot carry the in-memory token. Only requests to the API
+ * origin get the `Authorization` header and cookies, so the token can't leak
+ * to a third-party host (e.g. a URL echoed back by the server). The filename
+ * comes from `Content-Disposition` when present, else `fallbackName`.
+ */
+export async function downloadFromApi(
+ token: string | null,
+ urlOrPath: string,
+ fallbackName: string,
+): Promise<void> {
+ const { url, sameOrigin } = resolveApiUrl(urlOrPath)
+ const headers: Record<string, string> = {}
+ if (sameOrigin && token) headers.Authorization = `Bearer ${token}`
+
+ const response = await fetch(url, {
+ headers,
+ credentials: sameOrigin ? 'include' : 'omit',
+ })
+ if (!response.ok) throw new Error(`Download failed: ${response.status}`)
+
+ const disposition = response.headers.get('Content-Disposition')
+ const filename = disposition?.match(/filename="?([^";]+)"?/)?.[1] ?? fallbackName
+
+ const blob = await response.blob()
+ const objectUrl = URL.createObjectURL(blob)
+ const anchor = document.createElement('a')
+ anchor.href = objectUrl
+ anchor.download = filename
+ document.body.appendChild(anchor)
+ anchor.click()
+ anchor.remove()
+ URL.revokeObjectURL(objectUrl)
+}
diff --git a/packages/dashboard-core/src/locales/ar.json b/packages/dashboard-core/src/locales/ar.json
index 2aa4c72e60..04a9efd27b 100644
--- a/packages/dashboard-core/src/locales/ar.json
+++ b/packages/dashboard-core/src/locales/ar.json
@@ -481,7 +481,6 @@
"title": "استيراد من CSV",
"description": "قم برفع ملف CSV. ستقوم بمطابقة أعمدته مع الحقول في الخطوة التالية.",
"drop_label": "أسقط ملف CSV هنا، أو انقر للاستعراض",
- "browse": "استعراض الملفات",
"delimiter_label": "فاصل الأعمدة",
"delimiters": {
"comma": "فاصلة (,)",
diff --git a/packages/dashboard-core/src/locales/de.json b/packages/dashboard-core/src/locales/de.json
index 78e00754ff..ba84e15b11 100644
--- a/packages/dashboard-core/src/locales/de.json
+++ b/packages/dashboard-core/src/locales/de.json
@@ -481,7 +481,6 @@
"title": "Aus CSV importieren",
"description": "Laden Sie eine CSV-Datei hoch. Im nächsten Schritt ordnen Sie ihre Spalten den Feldern zu.",
"drop_label": "CSV-Datei hier ablegen oder klicken zum Auswählen",
- "browse": "Dateien durchsuchen",
"delimiter_label": "Spaltentrennzeichen",
"delimiters": {
"comma": "Komma (,)",
diff --git a/packages/dashboard-core/src/locales/en.json b/packages/dashboard-core/src/locales/en.json
index 06dea3dab0..fb037f95e0 100644
--- a/packages/dashboard-core/src/locales/en.json
+++ b/packages/dashboard-core/src/locales/en.json
@@ -481,7 +481,6 @@
"title": "Import from CSV",
"description": "Upload a CSV file. You'll match its columns to fields in the next step.",
"drop_label": "Drop a CSV file here, or click to browse",
- "browse": "Browse files",
"delimiter_label": "Column separator",
"delimiters": {
"comma": "Comma (,)",
diff --git a/packages/dashboard-core/src/locales/fr.json b/packages/dashboard-core/src/locales/fr.json
index 88ee17e264..e71c51be04 100644
--- a/packages/dashboard-core/src/locales/fr.json
+++ b/packages/dashboard-core/src/locales/fr.json
@@ -481,7 +481,6 @@
"title": "Importer depuis un CSV",
"description": "Téléversez un fichier CSV. Vous associerez ses colonnes aux champs à l'étape suivante.",
"drop_label": "Déposez un fichier CSV ici ou cliquez pour parcourir",
- "browse": "Parcourir les fichiers",
"delimiter_label": "Séparateur de colonnes",
"delimiters": {
"comma": "Virgule (,)",
diff --git a/packages/dashboard-core/src/locales/pl.json b/packages/dashboard-core/src/locales/pl.json
index 35fe6d3d45..75573506c4 100644
--- a/packages/dashboard-core/src/locales/pl.json
+++ b/packages/dashboard-core/src/locales/pl.json
@@ -481,7 +481,6 @@
"title": "Importuj z pliku CSV",
"description": "Prześlij plik CSV. W następnym kroku dopasujesz jego kolumny do pól.",
"drop_label": "Upuść plik CSV tutaj lub kliknij, aby przeglądać",
- "browse": "Przeglądaj pliki",
"delimiter_label": "Separator kolumn",
"delimiters": {
"comma": "Przecinek (,)",
diff --git a/packages/dashboard-core/src/locales/zh-CN.json b/packages/dashboard-core/src/locales/zh-CN.json
index 8cab4b8eeb..fcdca58a12 100644
--- a/packages/dashboard-core/src/locales/zh-CN.json
+++ b/packages/dashboard-core/src/locales/zh-CN.json
@@ -481,7 +481,6 @@
"title": "从 CSV 导入",
"description": "上传 CSV 文件。下一步将文件列与字段进行匹配。",
"drop_label": "将 CSV 文件拖放到此处,或点击浏览",
- "browse": "浏览文件",
"delimiter_label": "列分隔符",
"delimiters": {
"comma": "逗号 (,)",
diff --git a/packages/dashboard/src/components/spree/imports/import-wizard-dialog.tsx b/packages/dashboard/src/components/spree/imports/import-wizard-dialog.tsx
index 70de92404d..dcafe60196 100644
--- a/packages/dashboard/src/components/spree/imports/import-wizard-dialog.tsx
+++ b/packages/dashboard/src/components/spree/imports/import-wizard-dialog.tsx
@@ -234,7 +234,7 @@ function MappingStep({ imp }: { imp: Import }) {
}
const headerOptions = (current: string | null) => [
- { value: NOT_MAPPED, label: t('admin.imports.mapping.not_mapped') },
+ { value: NOT_MAPPED, label: t('admin.imports.mapping.not_mapped'), disabled: false },
...imp.csv_headers.map((header) => ({
value: header,
label: header,
@@ -297,7 +297,7 @@ function MappingStep({ imp }: { imp: Import }) {
<SelectItem
key={option.value}
value={option.value}
- disabled={'disabled' in option ? option.disabled : false}
+ disabled={option.disabled}
>
{option.label}
</SelectItem>
diff --git a/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb
index dbc0f419ba..2ad1341788 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/exports_controller.rb
@@ -87,7 +87,8 @@ module Spree
store: current_store,
user: try_spree_current_user
)
- attrs[:results_url] = validated_results_url(attrs[:results_url])
+ # The done email's download button target — allowed origins only.
+ attrs[:results_url] = validated_allowed_origin_url(attrs[:results_url])
klass.new(attrs)
end
@@ -103,17 +104,6 @@ module Spree
attrs
end
- # The export-done email links to this URL (typically the caller's
- # own exports view). Only honored when it matches a configured
- # allowed origin — otherwise silently dropped and the email renders
- # no download button. Mirrors ImportsController#validated_results_url.
- def validated_results_url(url)
- return if url.blank?
- return unless current_store.allowed_origins.exists? && current_store.allowed_origin?(url)
-
- url
- end
-
# Returns the registered Export subclass matching `name`, or nil.
#
# The constantize target comes from `available_types` (a trusted
diff --git a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
index f6fe6f5d89..3b9ef6e406 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/imports_controller.rb
@@ -204,7 +204,8 @@ module Spree
owner: current_store,
user: acting_admin_user
)
- attrs[:results_url] = validated_results_url(attrs[:results_url])
+ # The done email links back to results_url — allowed origins only.
+ attrs[:results_url] = validated_allowed_origin_url(attrs[:results_url])
klass.new(attrs)
end
@@ -212,17 +213,6 @@ module Spree
params.permit(:type, :attachment, :preferred_delimiter, :results_url)
end
- # The dashboard's results URL (the import-done email links back to
- # it) is only honored when it matches a configured allowed origin —
- # otherwise it is silently dropped and the done email renders no
- # link. Mirrors PasswordResetsController#redirect_url.
- def validated_results_url(url)
- return if url.blank?
- return unless current_store.allowed_origins.exists? && current_store.allowed_origin?(url)
-
- url
- end
-
# Returns the registered Import subclass matching `name`, or nil.
#
# The constantize target comes from `available_types` (a trusted
diff --git a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
index 7b2730e8a2..95c7d390e3 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/resource_controller.rb
@@ -40,6 +40,20 @@ module Spree
end
end
+ # Returns +url+ only when it matches one of the store's configured
+ # allowed origins — the gate for caller-provided URLs that later
+ # surface outside the request (e.g. the results_url the import/export
+ # done emails link back to). Anything else is silently dropped,
+ # mirroring the password-reset redirect_url behavior: no configured
+ # origins means no caller URLs are honored.
+ # @return [String, nil]
+ def validated_allowed_origin_url(url)
+ return if url.blank?
+ return unless current_store.allowed_origin?(url)
+
+ url
+ end
+
# Parses a strictly-integer param, returning nil for missing/blank/
# non-integer values (so callers can reject rather than coerce to 0).
# @return [Integer, nil]