diff --git a/web/src/lib/player/clientId.test.ts b/web/src/lib/player/clientId.test.ts index ca0e934e..5c3a3309 100644 --- a/web/src/lib/player/clientId.test.ts +++ b/web/src/lib/player/clientId.test.ts @@ -1,13 +1,18 @@ -import { afterEach, beforeEach, describe, expect, test } from 'vitest'; -import { getOrCreateClientId } from './clientId'; +import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'; +import { getOrCreateClientId, randomUUID } from './clientId'; + +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}$/; beforeEach(() => sessionStorage.clear()); -afterEach(() => sessionStorage.clear()); +afterEach(() => { + sessionStorage.clear(); + vi.unstubAllGlobals(); +}); describe('getOrCreateClientId', () => { test('generates a UUID on first call and persists it in sessionStorage', () => { const id = getOrCreateClientId(); - expect(id).toMatch(/^[0-9a-f-]{36}$/); + expect(id).toMatch(UUID_V4); expect(sessionStorage.getItem('minstrel.client_id')).toBe(id); }); @@ -17,3 +22,15 @@ describe('getOrCreateClientId', () => { expect(a).toBe(b); }); }); + +describe('randomUUID', () => { + test('still makes an id on a plain-HTTP page, where crypto.randomUUID is missing', () => { + const real = globalThis.crypto; + vi.stubGlobal('crypto', { getRandomValues: real.getRandomValues.bind(real) }); + const a = randomUUID(); + const b = randomUUID(); + expect(a).toMatch(UUID_V4); + expect(b).toMatch(UUID_V4); + expect(a).not.toBe(b); + }); +}); diff --git a/web/src/lib/player/clientId.ts b/web/src/lib/player/clientId.ts index 84c73809..0f7667d3 100644 --- a/web/src/lib/player/clientId.ts +++ b/web/src/lib/player/clientId.ts @@ -7,7 +7,22 @@ export function getOrCreateClientId(): string { } catch { // sessionStorage unavailable (non-browser env). Generate ephemerally. } - const id = crypto.randomUUID(); + const id = randomUUID(); try { sessionStorage.setItem(KEY, id); } catch { /* ignore */ } return id; } + +/** + * A version 4 UUID. Browsers offer crypto.randomUUID only on HTTPS pages and + * localhost, and Minstrel is often opened over plain HTTP on a home network + * (http://minstrel.lan:4533), so this falls back to crypto.getRandomValues, + * which every page has. + */ +export function randomUUID(): string { + if (typeof crypto.randomUUID === 'function') return crypto.randomUUID(); + const b = crypto.getRandomValues(new Uint8Array(16)); + b[6] = (b[6] & 0x0f) | 0x40; // version 4 + b[8] = (b[8] & 0x3f) | 0x80; // RFC 4122 variant + const hex = Array.from(b, (x) => x.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)}`; +}