Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
route every localStorage/sessionStorage access through lib/safeStorage (#5689)
[._.]/ Adam Eivyb2db2890a666
diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsxindex d6bd60377a..72db313adb 100644--- a/client/src/components/music/MusicDesigner.jsx+++ b/client/src/components/music/MusicDesigner.jsx@@ -34,6 +34,7 @@ import TabPills from '../ui/TabPills';import toast from '../ui/Toast';import useMounted from '../../hooks/useMounted';import useProviderModels from '../../hooks/useProviderModels';+import { safeReadStorage, safeRemoveStorage, safeWriteStorage } from '../../lib/safeStorage.js';import {createTrack, describeMusic, generateLyrics, getSettings, getTrack, updateSettings, updateTrack,} from '../../services/api';@@ -66,7 +67,7 @@ export default function MusicDesigner() {const [searchParams] = useSearchParams();const mountedRef = useMounted();const requestedTrackId = searchParams.get('trackId') || '';- const storedDraftId = requestedTrackId || window.localStorage.getItem(ACTIVE_DRAFT_KEY) || '';+ const storedDraftId = requestedTrackId || safeReadStorage(ACTIVE_DRAFT_KEY) || '';// Wizard text — lifted here so MusicGenPanel (which never writes back to// prompt/lyrics) can be re-hosted under step 4 unchanged, and so edits@@ -100,8 +101,8 @@ export default function MusicDesigner() {const hydrateDraft = (track) => {setTrackId(track.id);- if (track.title === DRAFT_TITLE) window.localStorage.setItem(ACTIVE_DRAFT_KEY, track.id);- else if (window.localStorage.getItem(ACTIVE_DRAFT_KEY) === track.id) window.localStorage.removeItem(ACTIVE_DRAFT_KEY);+ if (track.title === DRAFT_TITLE) safeWriteStorage(ACTIVE_DRAFT_KEY, track.id);+ else if (safeReadStorage(ACTIVE_DRAFT_KEY) === track.id) safeRemoveStorage(ACTIVE_DRAFT_KEY);setConcept(track.concept || '');setDescription(track.prompt || '');setLyrics(track.lyrics || '');@@ -561,8 +562,8 @@ export default function MusicDesigner() {onChange={(event) => setTitle(event.target.value)}onBlur={() => {const nextTitle = title.trim() || DRAFT_TITLE;- if (title.trim()) window.localStorage.removeItem(ACTIVE_DRAFT_KEY);- else window.localStorage.setItem(ACTIVE_DRAFT_KEY, trackId);+ if (title.trim()) safeRemoveStorage(ACTIVE_DRAFT_KEY);+ else safeWriteStorage(ACTIVE_DRAFT_KEY, trackId);saveDraft({ title: nextTitle });}}disabled={!draftReady}diff --git a/client/src/components/music/MusicDesigner.test.jsx b/client/src/components/music/MusicDesigner.test.jsxindex 8202213663..98ce7af81a 100644--- a/client/src/components/music/MusicDesigner.test.jsx+++ b/client/src/components/music/MusicDesigner.test.jsx@@ -321,6 +321,31 @@ describe('<MusicDesigner>', () => {});});+ // A blocked localStorage (Safari private mode, disabled cookies) throws from+ // the accessor. The draft-id read happens in the component RENDER BODY, so+ // before #5689 that throw was a render-phase exception and the whole Music+ // Designer route unmounted — the user lost the page, not a preference.+ describe('blocked storage', () => {+ // `vi.stubGlobal`, not `vi.spyOn`: a method assigned onto jsdom's Storage+ // proxy is swallowed as a stored key, so a spy never installs and the test+ // would pass against the unguarded component it is meant to fail.+ afterEach(() => { vi.unstubAllGlobals(); });++ it('still renders the designer when every storage access throws', async () => {+ const boom = () => { throw new DOMException('The operation is insecure.', 'SecurityError'); };+ vi.stubGlobal('localStorage', {+ getItem: boom, setItem: boom, removeItem: boom, clear: () => {},+ });++ renderAt('/music/generate');++ // The route renders, and the draft is still created — storage only ever+ // held the resume hint, so losing it costs the hint and nothing else.+ expect(await screen.findByLabelText(/what do you want to hear/i)).toBeInTheDocument();+ await waitFor(() => expect(api.createTrack).toHaveBeenCalled());+ });+ });+describe('meta-prompt overrides', () => {it('sends a saved override as the template, and stops sending it once reset', async () => {api.getSettings.mockResolvedValue({ music: { designer: { describeTemplate: 'Be terse.' } } });diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex 49b65e6a15..2b26600541 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -1,6 +1,7 @@import { useState, useCallback, useRef, useEffect } from 'react';import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingRun } from '../services/api';import toast from '../components/ui/Toast';+import { safeReadJsonSession, safeRemoveSession, safeWriteJsonSession } from '../lib/safeStorage.js';import { uuidv4 } from '../lib/uuid.js';import {LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN, countLlmCorrect,@@ -23,11 +24,9 @@ const RESTORABLE_STATES = new Set(['drilling', 'between-drills', 'complete']);const newRunId = () => uuidv4();function loadRunSnapshot() {- if (typeof sessionStorage === 'undefined') return null;- const raw = sessionStorage.getItem(RUN_STORAGE_KEY);- if (!raw) return null;- let snap;- try { snap = JSON.parse(raw); } catch { return null; } // corrupt storage → start fresh+ // Missing, inaccessible (Safari private mode) and corrupt all collapse to the+ // fallback here, which the checks below already treat as "start fresh".+ const snap = safeReadJsonSession(RUN_STORAGE_KEY, null);if (!snap || typeof snap !== 'object') return null;if (snap.state === 'saving') {// Both scored and training saves use stable client run/attempt ids, so an@@ -39,7 +38,7 @@ function loadRunSnapshot() {}function clearRunSnapshot() {- if (typeof sessionStorage !== 'undefined') sessionStorage.removeItem(RUN_STORAGE_KEY);+ safeRemoveSession(RUN_STORAGE_KEY);}function computeSessionScoreFromResults(results) {@@ -219,8 +218,9 @@ export function usePostSession() {// refresh during generation. Keeping the last good snapshot lets a refresh// resume at the between-drills screen instead of dropping the whole run.if (state === STATES.LOADING) return;- if (typeof sessionStorage === 'undefined') return;- sessionStorage.setItem(RUN_STORAGE_KEY, JSON.stringify({+ // Best-effort: this effect fires on every drill-state change, and a private-mode+ // QuotaExceededError here used to take the whole training run down (#5689).+ safeWriteJsonSession(RUN_STORAGE_KEY, {runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex,answers, drillResults, sessionScore, isTraining, conditions, legacyTags, sessionPlan,benchmark,@@ -231,7 +231,7 @@ export function usePostSession() {drillStartedAt: drillStartRef.current,runStartedAt: runStartedAtRef.current,runCompletedAt: runCompletedAtRef.current,- }));+ });}, [runId, state, drills, currentDrillIndex, currentDrill, currentQuestionIndex, answers, drillResults, sessionScore, isTraining, conditions, legacyTags, sessionPlan, benchmark]);const startSession = useCallback(async (drillConfigs, training = false, sessionConditions = {}, plan = null, benchmarkMetadata = null) => {diff --git a/client/src/hooks/usePostSession.test.js b/client/src/hooks/usePostSession.test.jsindex b9c0c5ac67..4a7d9d70cc 100644--- a/client/src/hooks/usePostSession.test.js+++ b/client/src/hooks/usePostSession.test.js@@ -839,6 +839,9 @@ describe('usePostSession — LLM training-log per-question breakdown (issue #211describe('usePostSession — refresh-safe run + idempotent submit (issue #2098)', () => {beforeEach(() => {vi.clearAllMocks();+ // Unstub FIRST: one case below replaces sessionStorage with a throwing stub,+ // and a failure there would otherwise leave it installed for every test after.+ vi.unstubAllGlobals();sessionStorage.clear();});@@ -914,6 +917,37 @@ describe('usePostSession — refresh-safe run + idempotent submit (issue #2098)'expect(snap.drillResults).toHaveLength(1);});+ it('keeps a training run alive when sessionStorage.setItem throws (private mode)', async () => {+ // Safari private browsing: `sessionStorage` EXISTS, so the old+ // `typeof sessionStorage === 'undefined'` half-guard passed and the very+ // next setItem threw. That write runs in an effect on every drill-state+ // change, so the throw killed the run mid-session (#5689).+ const store = new Map();+ vi.stubGlobal('sessionStorage', {+ getItem: (k) => (store.has(k) ? store.get(k) : null),+ setItem: () => { throw new DOMException('QuotaExceededError', 'QuotaExceededError'); },+ removeItem: (k) => store.delete(k),+ // The shared afterEach clears storage before this stub is removed.+ clear: () => store.clear(),+ });+ generatePostDrill.mockResolvedValue({+ type: 'doubling-chain', config: { startValue: 2, steps: 2 },+ questions: [{ prompt: '2 x 2', expected: 4 }, { prompt: '4 x 2', expected: 8 }],+ });++ const { result } = renderHook(() => usePostSession());+ await act(async () => {+ await result.current.startSession([{ type: 'doubling-chain', config: {}, timeLimitSec: 60 }]);+ });+ act(() => { result.current.submitAnswer('4'); });+ act(() => { result.current.submitAnswer('8'); });++ // The run advanced to the end despite every snapshot write failing; only+ // refresh-resume is lost, which is exactly what an unwritable storage costs.+ expect(result.current.state).toBe('complete');+ expect(result.current.answers).toHaveLength(2);+ });+it('restores a training run persisted mid-save for an idempotent retry', () => {sessionStorage.setItem('post.activeRun', JSON.stringify({runId: '11111111-1111-4111-8111-111111111111', state: 'saving', isTraining: true,diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 85791e1259..8e585e7c37 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -141,7 +141,7 @@ grep -i "what you want to do" client/src/lib/README.md| `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. || `rapidReaderPosition.js` | Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text. || `registerServiceWorker.js` | `registerServiceWorker()` / `unregisterServiceWorkers()` — wires up the offline app-shell + low-bandwidth asset-caching service worker (`public/sw.js`). Registers only in a production secure context (HTTPS or localhost); no-ops over plain-HTTP Tailnet and tears down any stale SW in dev. Called once from `main.jsx`. |-| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useOpenWorldSettings`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). |+| `safeStorage.js` | `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / `safeWriteJsonStorage` / `safeRemoveStorage` — guarded `localStorage` access that swallows throws (Safari private mode, blocked storage), with fallback-safe JSON parsing for structured entries. Use instead of touching `localStorage` inline so a storage failure never crashes init or a write path (#2387). Consumed by `useTheme`, `useOpenWorldSettings`, `useNavWorkingSet`, and the command palette. Also `safeReadJsonSession` / `safeWriteJsonSession` / `safeRemoveSession` — the same guarantees over `sessionStorage`, for tab-scoped crash-recovery buffers of edits the server has not accepted yet (QuotaBurn's unsaved-patch stash). `safeReadSession` / `safeWriteSession` are the raw-string session pair, for a plain flag (the stale-chunk build-id marker) that must not be JSON-quoted. || `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. || `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). || `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |diff --git a/client/src/lib/safeStorage.js b/client/src/lib/safeStorage.jsindex 23521a34bb..9a46aae3a0 100644--- a/client/src/lib/safeStorage.js+++ b/client/src/lib/safeStorage.js@@ -57,15 +57,36 @@ export const safeRemoveStorage = (key) => {}};-// `sessionStorage` variants, same guarantees. Session scope is for state that-// should survive a navigation or a reload but must NOT outlive the tab —-// crash-recovery buffers for edits the server has not accepted yet. Persisting-// those to `localStorage` would resurrect them weeks later, on top of whatever-// the record holds by then.+// `sessionStorage` variants, same guarantees, and mirroring the `localStorage`+// pair above: a raw-string read/write plus JSON helpers layered on top. Session+// scope is for state that should survive a navigation or a reload but must NOT+// outlive the tab — crash-recovery buffers for edits the server has not accepted+// yet, and per-tab markers. Persisting those to `localStorage` would resurrect+// them weeks later, on top of whatever the record holds by then.++// Returns the stored string, or null on any failure / missing storage. Use this+// rather than the JSON pair for a plain string flag (a build id, a marker):+// JSON-quoting the value would change the bytes every already-open tab holds.+export const safeReadSession = (key) => {+ try {+ return globalThis.sessionStorage?.getItem(key) ?? null;+ } catch {+ return null;+ }+};++export const safeWriteSession = (key, value) => {+ try {+ globalThis.sessionStorage?.setItem(key, value);+ } catch {+ // Ignore — the value stays in memory when persistence is unavailable.+ }+};+export const safeReadJsonSession = (key, fallback = null) => {+ const raw = safeReadSession(key);+ if (raw === null) return fallback;try {- const raw = globalThis.sessionStorage?.getItem(key) ?? null;- if (raw === null) return fallback;return JSON.parse(raw);} catch {return fallback;diff --git a/client/src/lib/safeStorage.test.js b/client/src/lib/safeStorage.test.jsindex 0f944dfec5..b48125dbab 100644--- a/client/src/lib/safeStorage.test.js+++ b/client/src/lib/safeStorage.test.js@@ -2,9 +2,19 @@ import { describe, it, expect, afterEach, vi } from 'vitest';import {safeReadStorage, safeReadJsonStorage, safeWriteStorage, safeWriteJsonStorage, safeRemoveStorage,safeReadJsonSession, safeWriteJsonSession, safeRemoveSession,+ safeReadSession, safeWriteSession,} from './safeStorage.js';+// Blocked storage is simulated with `vi.stubGlobal`, not `vi.spyOn`: assigning+// a method onto jsdom's Storage proxy is swallowed as a stored key, so a spy+// never installs and the test passes on a storage that never threw.+const throwingStorage = () => {+ const boom = () => { throw new DOMException('The operation is insecure.', 'SecurityError'); };+ return { getItem: boom, setItem: boom, removeItem: boom, clear: () => {} };+};+afterEach(() => {+ vi.unstubAllGlobals();vi.restoreAllMocks();window.localStorage.clear();window.sessionStorage.clear();@@ -25,10 +35,12 @@ describe('safeStorage', () => {});it('returns null instead of throwing when getItem throws', () => {- vi.spyOn(window.localStorage, 'getItem').mockImplementation(() => {- throw new DOMException('The operation is insecure.', 'SecurityError');- });+ window.localStorage.setItem('k', 'v');+ vi.stubGlobal('localStorage', throwingStorage());+ // Asserting on a key that IS set: a null from a missing key would pass on a+ // storage that never threw at all.expect(safeReadStorage('k')).toBeNull();+ expect(safeReadJsonStorage('k', 'fallback')).toBe('fallback');});it('reads JSON and returns the supplied fallback for missing or corrupt values', () => {@@ -51,13 +63,9 @@ describe('safeStorage', () => {});it('swallows setItem / removeItem throws', () => {- vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => {- throw new DOMException('QuotaExceededError', 'QuotaExceededError');- });- vi.spyOn(window.localStorage, 'removeItem').mockImplementation(() => {- throw new DOMException('QuotaExceededError', 'QuotaExceededError');- });+ vi.stubGlobal('localStorage', throwingStorage());expect(() => safeWriteStorage('k', 'v')).not.toThrow();+ expect(() => safeWriteJsonStorage('k', { a: 1 })).not.toThrow();expect(() => safeRemoveStorage('k')).not.toThrow();});@@ -77,15 +85,26 @@ describe('safeStorage', () => {expect(safeReadJsonSession('missing', 'fallback')).toBe('fallback');});+ it('stores a session string verbatim, with no JSON quoting', () => {+ safeWriteSession('flag', 'build-abc');+ // The raw bytes are the contract: the stale-chunk flag is compared against+ // values already written by tabs open across an upgrade, so a JSON-quoted+ // `"build-abc"` would silently never match and the anti-loop guard would+ // stop working the day the helper was adopted.+ expect(window.sessionStorage.getItem('flag')).toBe('build-abc');+ expect(safeReadSession('flag')).toBe('build-abc');+ expect(safeReadSession('missing')).toBeNull();+ });+it('swallows a session storage that throws on every access', () => {// Blocked storage (Safari private mode, a sandboxed iframe) throws from the// accessor itself, so the whole call has to be inside the guard.- const boom = () => { throw new DOMException('The operation is insecure.', 'SecurityError'); };- vi.stubGlobal('sessionStorage', { getItem: boom, setItem: boom, removeItem: boom });+ vi.stubGlobal('sessionStorage', throwingStorage());expect(() => safeWriteJsonSession('k', { a: 1 })).not.toThrow();expect(safeReadJsonSession('k', 'fallback')).toBe('fallback');expect(() => safeRemoveSession('k')).not.toThrow();- vi.unstubAllGlobals();+ expect(() => safeWriteSession('k', 'v')).not.toThrow();+ expect(safeReadSession('k')).toBeNull();});});diff --git a/client/src/pages/OpenWorld.jsx b/client/src/pages/OpenWorld.jsxindex 5c11f92069..47ac11c415 100644--- a/client/src/pages/OpenWorld.jsx+++ b/client/src/pages/OpenWorld.jsx@@ -8,6 +8,7 @@ import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';import useKeyCapture from '../hooks/useKeyCapture';import { useAutoRefetch } from '../hooks/useAutoRefetch';import { mergeFrameIntoOpenWorldProps } from '../lib/openWorldPlaybackFrame';+import { safeReadJsonSession, safeWriteJsonSession } from '../lib/safeStorage.js';import * as api from '../services/api';import OpenWorldScene from '../components/openworld/OpenWorldScene';import OpenWorldHud from '../components/openworld/OpenWorldHud';@@ -30,6 +31,9 @@ import { useThemeContext } from '../components/ThemeContext';import { useInstanceFeatures } from '../hooks/useInstanceFeatures';import { recommendOpenWorldStartTier } from '../utils/openWorldRenderBudget';+// Tab-scoped: the app filter should survive a reload but not outlive the tab.+const FILTER_STORAGE_KEY = 'openworld.filter';+// Internal render budgets only. These tiers are selected from sustained frame time and are// deliberately not persisted or exposed as player settings; art direction stays coherent while// the renderer sheds work on slower hardware.@@ -151,33 +155,23 @@ function OpenWorldInner() {}, [settings, effectiveTier, openWorldTimeOfDay.presetKey, worldStyle]);const [filter, setFilter] = useState(() => {- // try/catch is necessary because sessionStorage values are external state- // a corrupted/older-schema entry would throw and crash the page render.- try {- const raw = sessionStorage.getItem('openworld.filter');- if (raw) {- const parsed = JSON.parse(raw);- if (parsed && typeof parsed.status === 'string') {- return {- status: parsed.status,- search: typeof parsed.search === 'string' ? parsed.search : '',- };- }- }- } catch {- // fall through to default+ // A guarded read is necessary because sessionStorage values are external+ // state: an inaccessible storage or a corrupted/older-schema entry would+ // otherwise throw and crash the page render.+ const parsed = safeReadJsonSession(FILTER_STORAGE_KEY, null);+ if (parsed && typeof parsed.status === 'string') {+ return {+ status: parsed.status,+ search: typeof parsed.search === 'string' ? parsed.search : '',+ };}return { status: 'all', search: '' };});useEffect(() => {- // setItem can throw (Safari private mode, storage quota); ignore — this- // is a UX nicety, not load-bearing state.- try {- sessionStorage.setItem('openworld.filter', JSON.stringify(filter));- } catch {- // intentionally swallow- }+ // Best-effort — the persisted filter is a UX nicety, not load-bearing state,+ // and setItem throws in Safari private mode / at quota.+ safeWriteJsonSession(FILTER_STORAGE_KEY, filter);}, [filter]);const filterResult = useMemo(diff --git a/client/src/storageConventions.test.js b/client/src/storageConventions.test.jsnew file mode 100644index 0000000000..89094b5531--- /dev/null+++ b/client/src/storageConventions.test.js@@ -0,0 +1,168 @@+// @vitest-environment node++/**+ * Repo-wide guard: `lib/safeStorage.js` is the only place that touches Web Storage.+ *+ * `localStorage`/`sessionStorage` are not ordinary objects. They throw — not+ * return null — in Safari private browsing, with cookies disabled, in a+ * sandboxed iframe, and at quota; and in some of those the object still EXISTS,+ * so a `typeof sessionStorage === 'undefined'` half-guard passes and the very+ * next `setItem` throws anyway. `lib/safeStorage.js` exists to make every access+ * best-effort, and its header already said "use these instead of touching+ * `localStorage` inline". Three modules still did, and each one turned a lost+ * preference into something worse (#5689):+ *+ * - `MusicDesigner.jsx` read storage in the COMPONENT RENDER BODY, so a throw+ * was a render-phase exception that unmounted the whole Music Designer route.+ * - `staleChunkReload.js` read/wrote its anti-loop flag unguarded inside the+ * stale-bundle recovery path — a storage failure broke the mechanism whose+ * entire job is recovering a user from a broken page.+ * - `usePostSession.js` carried the `typeof`-only half-guard on a write that+ * runs on every drill-state change, so a POST training run died mid-session.+ *+ * The rule is therefore structural rather than per-site: any raw member access+ * fails this suite, and the fix is always the corresponding `safe*` helper.+ *+ * ## Allowlist+ *+ * - `src/lib/safeStorage.js` — it IS the guarded wrapper.+ * - `src/test/**` — the storage polyfill and test helpers deliberately install+ * and probe raw Storage objects; a guard must not trip over its own harness.+ * - `src/utils/timeWindow.js` — enumerates keys via `.length` / `.key(i)` to+ * prune stale per-day entries. `safeStorage` deliberately exposes no+ * enumeration API (it would have to invent an iteration contract for a+ * single caller), so this file keeps its own try/catch — which it already has+ * on every access. Move it off the allowlist the day a second caller needs+ * enumeration and the helper is worth adding.+ *+ * ## What this guard CANNOT see+ *+ * It is a source grep, not an AST pass. Comments are stripped (both forms, with+ * a `:` lookbehind so a `https://` URL is not read as a line comment) because+ * prose like "persisted to localStorage." otherwise reads as a member access+ * spanning the newline; string literals are NOT stripped, so a storage call+ * spelled inside a string would be flagged, and a real call sharing a line with+ * a `//` inside a string would be missed. Aliasing (`const s = localStorage`),+ * a computed base (`globalThis['localStorage']`), or a call funneled through a+ * helper in another file all slip through. Those are unusual enough here that+ * the grep earns its keep; closing them means moving to an AST pass.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';+import { trackedSourceFiles } from './test/trackedFiles.js';++const CLIENT_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++const WRAPPER_FILE = 'src/lib/safeStorage.js';+const ALLOWED = [+ WRAPPER_FILE,+ 'src/utils/timeWindow.js',+];+const ALLOWED_PREFIXES = ['src/test/'];++const isAllowed = (file) =>+ ALLOWED.includes(file) || ALLOWED_PREFIXES.some((p) => file.startsWith(p));++/**+ * Block and line comments removed. Without this, a docblock sentence ending in+ * "localStorage." followed by a line starting with a letter matches the member+ * pattern and reports a file that never touches storage at all. The `[^:]`+ * before `//` keeps `https://…` inside a comment or string from eating the rest+ * of the line.+ */+const stripComments = (src) => src+ .replace(/\/\*[\s\S]*?\*\//g, ' ')+ .replace(/(^|[^:\\])\/\/[^\n]*/g, '$1');++/**+ * `localStorage.foo`, `window.sessionStorage.foo`, `globalThis.localStorage[…]`.+ * A member name (or a bracket) is required so prose and bare identifiers are not+ * matches; the lookbehind keeps an unrelated identifier ending in `…Storage`+ * from counting. Optional chaining counts as an access: `?.` only guards a+ * null/undefined base, not a `getItem` that throws — which is the whole failure+ * mode here — so `sessionStorage?.setItem(…)` is exactly as unsafe as the plain+ * form and must not read as already-guarded.+ */+const RAW_STORAGE = /(?<![\w$])(?:(?:window|globalThis|self)\s*\??\.\s*)?(?:local|session)Storage\s*\??(?:\.\s*[A-Za-z_$]|\[)/g;++/** Raw Web Storage accesses in `src`, as matched snippets. */+export function findRawStorageAccess(src) {+ return [...stripComments(src).matchAll(RAW_STORAGE)].map((m) => m[0].trim());+}++describe('Web Storage access goes through lib/safeStorage', () => {+ it('has no raw localStorage/sessionStorage access outside the wrapper', () => {+ const files = trackedSourceFiles(CLIENT_ROOT);+ // A broken `git ls-files` (wrong cwd, detached checkout) would otherwise make+ // this guard pass by scanning nothing at all.+ expect(files.length).toBeGreaterThan(100);++ const violations = [];+ for (const file of files) {+ if (isAllowed(file)) continue;+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');+ for (const hit of findRawStorageAccess(src)) violations.push(`${file}: ${hit}`);+ }++ expect(+ violations,+ 'These files touch `localStorage`/`sessionStorage` directly. Storage throws '+ + '(Safari private mode, blocked storage, disabled cookies, quota) — in a render '+ + 'body that unmounts the route, and in an effect it kills the flow mid-session.\n'+ + 'Fix: use `safeReadStorage` / `safeReadJsonStorage` / `safeWriteStorage` / '+ + '`safeWriteJsonStorage` / `safeRemoveStorage`, or the session variants '+ + '`safeReadSession` / `safeWriteSession` / `safeReadJsonSession` / '+ + '`safeWriteJsonSession` / `safeRemoveSession`, from `client/src/lib/safeStorage.js`.\n'+ + `Offenders:\n ${violations.join('\n ')}`,+ ).toEqual([]);+ });++ // Guards the guard: if the detector stops recognizing a raw access, the scan+ // above goes vacuously green and the bug class walks straight back in.+ it('flags every raw spelling and accepts the safe helpers', () => {+ expect(findRawStorageAccess("localStorage.getItem('x')")).toEqual(['localStorage.g']);+ expect(findRawStorageAccess("window.localStorage.setItem('x', '1')")).toEqual(['window.localStorage.s']);+ expect(findRawStorageAccess('globalThis.sessionStorage?.removeItem(k)')).toEqual(['globalThis.sessionStorage?.r']);+ expect(findRawStorageAccess("sessionStorage['x']")).toEqual(['sessionStorage[']);+ expect(findRawStorageAccess('for (let i = 0; i < localStorage.length; i += 1) {}')).toEqual(['localStorage.l']);++ expect(findRawStorageAccess("safeReadStorage('x')")).toEqual([]);+ expect(findRawStorageAccess("safeWriteJsonSession('x', v)")).toEqual([]);+ // A `typeof` presence check alone is the half-guard #5689 was about, but it+ // is not itself an access — only the member call that follows is.+ expect(findRawStorageAccess("if (typeof sessionStorage === 'undefined') return;")).toEqual([]);+ });++ it('does not flag prose that merely names the API', () => {+ // The exact shapes present in the tree when this guard was written: a+ // sentence-final "localStorage." whose next line starts with a letter.+ expect(findRawStorageAccess(+ '// nothing in this module reads or writes localStorage.\nconst TIERS = {};',+ )).toEqual([]);+ expect(findRawStorageAccess(+ ' * Sidebar working-set state, persisted to localStorage.\n */\nexport const x = 1;',+ )).toEqual([]);+ // A URL inside a comment must not swallow the rest of the file and hide a+ // real access on a later line.+ expect(findRawStorageAccess(+ "// see https://example.com/storage\nlocalStorage.getItem('x');",+ )).toEqual(['localStorage.g']);+ });++ // The allowlist must keep naming files that really exist and really carry the+ // shape — otherwise a rename turns an exemption into silent dead config.+ it('allowlists only files that exist and still touch storage directly', () => {+ const tracked = trackedSourceFiles(CLIENT_ROOT);+ for (const file of ALLOWED) {+ expect(tracked, `${file} is allowlisted but no longer tracked`).toContain(file);+ const src = readFileSync(join(CLIENT_ROOT, file), 'utf8');+ expect(+ findRawStorageAccess(src).length,+ `${file} no longer touches storage directly — drop it from the allowlist`,+ ).toBeGreaterThan(0);+ }+ });+});diff --git a/client/src/utils/openWorldCollectibles.js b/client/src/utils/openWorldCollectibles.jsindex b4116c33f7..c35d2ac423 100644--- a/client/src/utils/openWorldCollectibles.js+++ b/client/src/utils/openWorldCollectibles.js@@ -4,6 +4,7 @@// increments the session score, and unlocks discovery recognition.// No three.js / React imports — pure, testable in node.+import { safeReadJsonSession, safeWriteJsonSession } from '../lib/safeStorage.js';import { WORLD } from './openWorldPlan';export const SHARD_COLLECTION_RADIUS = 2.4;@@ -97,23 +98,10 @@ export function getCollectionStats(collectedSet = new Set(), totalCount = TOTAL_const STORAGE_KEY = 'openworld.shards';export function loadCollectedShardIds() {- try {- if (typeof sessionStorage === 'undefined') return new Set();- const raw = sessionStorage.getItem(STORAGE_KEY);- if (!raw) return new Set();- const parsed = JSON.parse(raw);- return Array.isArray(parsed) ? new Set(parsed) : new Set();- } catch {- return new Set();- }+ const parsed = safeReadJsonSession(STORAGE_KEY, null);+ return Array.isArray(parsed) ? new Set(parsed) : new Set();}export function saveCollectedShardIds(set) {- try {- if (typeof sessionStorage === 'undefined') return;- const list = Array.from(set || []);- sessionStorage.setItem(STORAGE_KEY, JSON.stringify(list));- } catch {- // Swallow storage exceptions safely- }+ safeWriteJsonSession(STORAGE_KEY, Array.from(set || []));}diff --git a/client/src/utils/staleChunkReload.js b/client/src/utils/staleChunkReload.jsindex 61747f3adf..0c18e1c854 100644--- a/client/src/utils/staleChunkReload.js+++ b/client/src/utils/staleChunkReload.js@@ -1,3 +1,4 @@+import { safeReadSession, safeWriteSession } from '../lib/safeStorage.js';import { sleep } from './sleep.js';// Cross-browser detection for stale dynamic-import chunk errors that happen@@ -98,8 +99,19 @@ export const fetchServerBuildId = async () => {export const reloadOnceForStaleChunk = () => {const buildId = getCurrentBuildId();const flag = buildId ? `${buildId}` : '1';- if (sessionStorage.getItem(RELOAD_FLAG) === flag) return false;- sessionStorage.setItem(RELOAD_FLAG, flag);+ // The stored flag IS the anti-loop guard, so it gets the sentinel treatment+ // (root AGENTS.md): a storage that cannot persist must not read back as+ // `no reload attempted yet`, which would reload on every stale-chunk error+ // forever. Write, then read back — a mismatch means storage is unavailable+ // (Safari private mode, blocked storage, disabled cookies) and the page stays+ // put. The guarded helpers also keep the throw itself from taking out the very+ // recovery path a stale bundle needs (#5689).+ if (safeReadSession(RELOAD_FLAG) === flag) return false;+ safeWriteSession(RELOAD_FLAG, flag);+ if (safeReadSession(RELOAD_FLAG) !== flag) {+ console.warn('🔄 Stale chunk detected but sessionStorage is unavailable — skipping reload to avoid a reload loop');+ return false;+ }console.warn(`🔄 Stale chunk detected (build ${buildId || 'unknown'}) — reloading to pick up new bundle`);// Purge the offline caches BEFORE reloading so the reload can't be handed the// stale shell/chunks back — but only when the server confirms a differentdiff --git a/client/src/utils/staleChunkReload.test.js b/client/src/utils/staleChunkReload.test.jsindex 1c1355d396..ad85513bad 100644--- a/client/src/utils/staleChunkReload.test.js+++ b/client/src/utils/staleChunkReload.test.js@@ -212,6 +212,23 @@ describe('reloadOnceForStaleChunk', () => {expect(reload).toHaveBeenCalledTimes(1);});+ it('does not reload at all when sessionStorage is unavailable (no reload loop)', async () => {+ // Safari private mode / blocked storage: the accessor itself throws. The+ // stored flag IS the anti-loop guard, so a storage that cannot persist it+ // must not read back as "no reload attempted yet" — that would reload on+ // every stale-chunk error, forever (#5689).+ const boom = () => { throw new DOMException('The operation is insecure.', 'SecurityError'); };+ vi.stubGlobal('sessionStorage', { getItem: boom, setItem: boom, removeItem: boom });+ stubFetch();+ const reload = stubReload();+ vi.stubGlobal('caches', undefined);++ expect(reloadOnceForStaleChunk()).toBe(false);+ expect(reloadOnceForStaleChunk()).toBe(false);+ await Promise.resolve();+ expect(reload).not.toHaveBeenCalled();+ });+it('reloads again after a new build ships (guard is build-scoped)', async () => {stubSessionStorage();stubFetch();