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.

Fix: Fixed "crypto.randomUUID is not a function" on plain-HTTP dashboards (#15087)

Damian Legawiec5de307469335
diff --git a/.changeset/random-uuid-insecure-context.md b/.changeset/random-uuid-insecure-context.md
new file mode 100644
index 0000000000..dcff430ac9
--- /dev/null
+++ b/.changeset/random-uuid-insecure-context.md
@@ -0,0 +1,10 @@
+---
+"@spree/core": patch
+"@spree/sdk": patch
+"@spree/admin-sdk": patch
+"@spree/seller-sdk": patch
+"@spree/dashboard": patch
+"@spree/dashboard-core": patch
+---
+
+Fixed "crypto.randomUUID is not a function" when the dashboard is opened over plain HTTP at an address other than `localhost`, for example a server's IP address. Browsers only provide `crypto.randomUUID` on secure pages, and every request that saves data needs one, starting with the store setup page. `@spree/core` now exports a `randomUUID()` that falls back to `crypto.getRandomValues`, and the SDKs and dashboards use it.
diff --git a/packages/core/README.md b/packages/core/README.md
index 47053fd468..00429bc206 100644
--- a/packages/core/README.md
+++ b/packages/core/README.md
@@ -19,6 +19,7 @@ npm install @spree/core
- [Money](#money) — exact arithmetic, percentages and formatting for decimal-string amounts
- [Reading typed amounts](#reading-typed-amounts) — turning "1.234,56" into "1234.56"
- [Filters](#filters) — types for the queries Spree list endpoints accept
+- [Random IDs](#random-ids) — UUIDs that also work on plain-HTTP pages
- [Compatibility](#compatibility)
## Code lists
@@ -260,11 +261,22 @@ const query: ProductQuery = {
Amounts in `RangeFilters` are decimal strings, like everywhere else in Spree. `FILTER_PREDICATES` lists the conditions for each kind of value, if you need them at runtime, for example to build a filter editor, and `FilterPredicate` is the type of any one of them.
+## Random IDs
+
+`randomUUID()` returns a version 4 UUID. Browsers only provide `crypto.randomUUID` on secure pages (HTTPS or `localhost`), so code that runs on a page served over plain HTTP, for example at a server's IP address, should use this instead. It falls back to `crypto.getRandomValues`, which every browser provides.
+
+```typescript
+import { randomUUID } from '@spree/core';
+
+randomUUID(); // '3b241101-e2bb-4255-8caf-4136c566a962'
+```
+
## Compatibility
- ES modules and CommonJS, with TypeScript types included.
- Node.js 18 or later, and every current browser.
- `formatMoney` uses the built-in `Intl.NumberFormat`.
+- `randomUUID` needs the Web Crypto API as the global `crypto`: built into browsers and Node.js 19 or later. Node.js 18 needs the `--experimental-global-webcrypto` flag, and React Native needs a polyfill.
## Links
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 3466607ee5..52400a7e39 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -56,6 +56,8 @@ export {
export { currencyParts, normalizeMoneyInput } from './money-input'
// Units
export { UNIT_SYSTEM_WEIGHT_UNITS } from './unit-systems'
+// Identifiers
+export { randomUUID } from './uuid'
// Webhooks
export {
isWebhookEventPattern,
diff --git a/packages/core/src/uuid.ts b/packages/core/src/uuid.ts
new file mode 100644
index 0000000000..0c32e205b0
--- /dev/null
+++ b/packages/core/src/uuid.ts
@@ -0,0 +1,14 @@
+/**
+ * A version 4 UUID. Browsers expose `crypto.randomUUID` only on secure pages
+ * (HTTPS or localhost), so a dashboard opened over plain HTTP at an IP address
+ * or hostname falls back to `crypto.getRandomValues`, which works everywhere.
+ */
+export function randomUUID(): string {
+ if (typeof crypto.randomUUID === 'function') return crypto.randomUUID()
+
+ const bytes = crypto.getRandomValues(new Uint8Array(16))
+ bytes[6] = (bytes[6] & 0x0f) | 0x40
+ bytes[8] = (bytes[8] & 0x3f) | 0x80
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
+}
diff --git a/packages/core/tests/uuid.test.ts b/packages/core/tests/uuid.test.ts
new file mode 100644
index 0000000000..71faac9799
--- /dev/null
+++ b/packages/core/tests/uuid.test.ts
@@ -0,0 +1,21 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { randomUUID } from '../src'
+
+const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
+
+describe('randomUUID', () => {
+ afterEach(() => vi.unstubAllGlobals())
+
+ it('returns a version 4 UUID', () => {
+ expect(randomUUID()).toMatch(UUID_V4)
+ })
+
+ it('falls back to getRandomValues when randomUUID is missing, as on plain-HTTP pages', () => {
+ vi.stubGlobal('crypto', { getRandomValues: crypto.getRandomValues.bind(crypto) })
+
+ const ids = new Set(Array.from({ length: 100 }, () => randomUUID()))
+
+ expect(ids.size).toBe(100)
+ for (const id of ids) expect(id).toMatch(UUID_V4)
+ })
+})
diff --git a/packages/dashboard-core/src/components/table-toolbar.tsx b/packages/dashboard-core/src/components/table-toolbar.tsx
index 5a9b5bf5ce..6d9fc80a39 100644
--- a/packages/dashboard-core/src/components/table-toolbar.tsx
+++ b/packages/dashboard-core/src/components/table-toolbar.tsx
@@ -1,4 +1,4 @@
-import type { FilterPredicate } from '@spree/core'
+import { type FilterPredicate, randomUUID } from '@spree/core'
import {
Button,
Checkbox,
@@ -865,7 +865,7 @@ function QuickEnumFilter({
onFiltersChange([
...others,
{
- id: existing?.id ?? crypto.randomUUID(),
+ id: existing?.id ?? randomUUID(),
field: column.key,
operator: 'in',
value: values.join(','),
@@ -956,7 +956,7 @@ function QuickResourceFilter({
onFiltersChange([
...others,
{
- id: existing?.id ?? crypto.randomUUID(),
+ id: existing?.id ?? randomUUID(),
field: column.key,
operator: 'in',
value: values.join(','),
@@ -1039,14 +1039,14 @@ function QuickDateFilter({
const next: FilterRule[] = [...others]
if (rangeFrom) {
next.push({
- id: crypto.randomUUID(),
+ id: randomUUID(),
field: column.key,
operator: 'gteq',
value: rangeFrom,
})
}
if (rangeTo) {
- next.push({ id: crypto.randomUUID(), field: column.key, operator: 'lteq', value: rangeTo })
+ next.push({ id: randomUUID(), field: column.key, operator: 'lteq', value: rangeTo })
}
onFiltersChange(next)
},
@@ -1626,10 +1626,7 @@ function FilterPanel({
const others = filters.filter(
(f) => !(f.field === field && f.operator === nextOperator) && f.id !== editing,
)
- onApply([
- ...others,
- { id: crypto.randomUUID(), field, operator: nextOperator, value: nextValue },
- ])
+ onApply([...others, { id: randomUUID(), field, operator: nextOperator, value: nextValue }])
}
/** Replace this field's bounds with a preset's, and close. */
@@ -1641,10 +1638,10 @@ function FilterPanel({
)
const next = [...others]
if (range.from) {
- next.push({ id: crypto.randomUUID(), field, operator: 'gteq', value: range.from })
+ next.push({ id: randomUUID(), field, operator: 'gteq', value: range.from })
}
if (range.to) {
- next.push({ id: crypto.randomUUID(), field, operator: 'lteq', value: range.to })
+ next.push({ id: randomUUID(), field, operator: 'lteq', value: range.to })
}
onApply(next)
}
@@ -1672,7 +1669,7 @@ function FilterPanel({
onChange(
next.length === 0
? others
- : [...others, { id: crypto.randomUUID(), field, operator: 'in', value: next.join(',') }],
+ : [...others, { id: randomUUID(), field, operator: 'in', value: next.join(',') }],
)
}
@@ -1911,7 +1908,7 @@ function FilterPanel({
const next = [...others]
if (customRange.from) {
next.push({
- id: crypto.randomUUID(),
+ id: randomUUID(),
field,
operator: 'gteq',
value: customRange.from,
@@ -1919,7 +1916,7 @@ function FilterPanel({
}
if (customRange.to) {
next.push({
- id: crypto.randomUUID(),
+ id: randomUUID(),
field,
operator: 'lteq',
value: customRange.to,
diff --git a/packages/dashboard-core/src/products/product-form-cards.tsx b/packages/dashboard-core/src/products/product-form-cards.tsx
index 441027a0d5..f82dad4557 100644
--- a/packages/dashboard-core/src/products/product-form-cards.tsx
+++ b/packages/dashboard-core/src/products/product-form-cards.tsx
@@ -13,7 +13,7 @@ import {
useSortable,
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
-import type { CurrencyCode } from '@spree/core'
+import { type CurrencyCode, randomUUID } from '@spree/core'
import type { MediaType, ProductFormValues } from '@spree/dashboard-core'
import {
getApiClient,
@@ -368,7 +368,7 @@ export function MediaCard({
async (files: FileList | File[]) => {
const fileArray = Array.from(files)
for (const file of fileArray) {
- const uploadId = crypto.randomUUID()
+ const uploadId = randomUUID()
const preview = URL.createObjectURL(file)
setPending((prev) => [...prev, { id: uploadId, file, preview, progress: 'uploading' }])
try {
@@ -445,7 +445,7 @@ export function MediaCard({
...entries.map((entry, index) => ({
...entry,
position: current.length + index + 1,
- uploadId: crypto.randomUUID(),
+ uploadId: randomUUID(),
})),
],
{ shouldDirty: true },
diff --git a/packages/dashboard/e2e/first-run/setup.spec.ts b/packages/dashboard/e2e/first-run/setup.spec.ts
index e59c4f0840..2a1bb88898 100644
--- a/packages/dashboard/e2e/first-run/setup.spec.ts
+++ b/packages/dashboard/e2e/first-run/setup.spec.ts
@@ -72,6 +72,11 @@ test.describe
test('creates the admin account, sets up the store and signs the merchant in', async ({
page,
}) => {
+ // Browsers leave out crypto.randomUUID on plain-HTTP pages, such as a
+ // dashboard opened at a server's IP address. Setup must still work there.
+ await page.addInitScript(() => {
+ delete (Crypto.prototype as { randomUUID?: unknown }).randomUUID
+ })
await page.goto(setupUrl)
await fillSetupForm(page)
await page.getByRole('button', { name: 'Complete setup' }).click()
diff --git a/packages/dashboard/src/components/spree/products/digital-files-form-card.tsx b/packages/dashboard/src/components/spree/products/digital-files-form-card.tsx
index 8f06728eb1..9415dc6c2f 100644
--- a/packages/dashboard/src/components/spree/products/digital-files-form-card.tsx
+++ b/packages/dashboard/src/components/spree/products/digital-files-form-card.tsx
@@ -1,3 +1,4 @@
+import { randomUUID } from '@spree/core'
import { formatFileSize, type ProductFormValues, useFileUpload } from '@spree/dashboard-core'
import {
Button,
@@ -53,7 +54,7 @@ export function DigitalFilesFormCard({
async (files: FileList | File[]) => {
const fileArray = Array.from(files)
for (const file of fileArray) {
- const uploadId = crypto.randomUUID()
+ const uploadId = randomUUID()
setPending((prev) => [...prev, { id: uploadId, name: file.name }])
try {
const { signedId } = await fileUpload.mutateAsync(file)
diff --git a/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsx b/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsx
index 6356bbe0e1..68293a59e3 100644
--- a/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsx
+++ b/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsx
@@ -1,5 +1,5 @@
import type { DeliveryZone } from '@spree/admin-sdk'
-import type { CountryCode } from '@spree/core'
+import { type CountryCode, randomUUID } from '@spree/core'
import { useCountryDisplayName, useSortByCountryName, useStore } from '@spree/dashboard-core'
import {
Button,
@@ -386,7 +386,7 @@ function PostalRulesSection({
// must not gain one, so React keys are minted here and kept out of the value.
const keys = useRef<string[]>([])
while (keys.current.length < rules.length) {
- keys.current = [...keys.current, `postal-rule-${crypto.randomUUID()}`]
+ keys.current = [...keys.current, `postal-rule-${randomUUID()}`]
}
const countryOptions = countries
diff --git a/packages/sdk-core/src/request.ts b/packages/sdk-core/src/request.ts
index 709feb9e54..6b8fe208bd 100644
--- a/packages/sdk-core/src/request.ts
+++ b/packages/sdk-core/src/request.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from '@spree/core'
import type { ErrorResponse, LocaleDefaults, ValidationErrorDetail } from './types'
export interface RetryConfig {
@@ -68,7 +69,7 @@ function sleep(ms: number): Promise<void> {
}
function generateIdempotencyKey(): string {
- return `spree-sdk-retry-${crypto.randomUUID()}`
+ return `spree-sdk-retry-${randomUUID()}`
}
function shouldRetryOnStatus(