Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🗄️ fix: Fall Back to In-Memory Storage When Web Storage Is Denied (#16431)

Marco Berettadc85985040cf
diff --git a/client/index.html b/client/index.html
index dc96c252d3..9fe3086ed9 100644
--- a/client/index.html
+++ b/client/index.html
@@ -28,7 +28,12 @@
}
</style>
<script>
- const theme = localStorage.getItem('color-theme');
+ let theme = null;
+ try {
+ theme = localStorage.getItem('color-theme');
+ } catch (e) {
+ /* Web Storage denied by browser policy: the shell falls back to the system theme. */
+ }
const loadingContainerStyle = document.createElement('style');
let backgroundColor;
diff --git a/client/src/main.jsx b/client/src/main.jsx
index f0f196e720..945b89f166 100644
--- a/client/src/main.jsx
+++ b/client/src/main.jsx
@@ -1,3 +1,4 @@
+import './polyfills/storage';
import './polyfills/regeneratorRuntime';
import { createRoot } from 'react-dom/client';
import { initializeI18n } from './locales/i18n';
diff --git a/client/src/polyfills/__tests__/storage.test.ts b/client/src/polyfills/__tests__/storage.test.ts
new file mode 100644
index 0000000000..74945433b7
--- /dev/null
+++ b/client/src/polyfills/__tests__/storage.test.ts
@@ -0,0 +1,74 @@
+import { createMemoryStorage, installStorageFallback } from '../storage';
+
+function deniedWindow(): Pick<Window, 'localStorage' | 'sessionStorage'> {
+ const target = {} as Pick<Window, 'localStorage' | 'sessionStorage'>;
+ for (const name of ['localStorage', 'sessionStorage']) {
+ Object.defineProperty(target, name, {
+ configurable: true,
+ get() {
+ throw new DOMException('denied', 'SecurityError');
+ },
+ });
+ }
+ return target;
+}
+
+describe('installStorageFallback', () => {
+ it('leaves accessible storage untouched', () => {
+ const storage = createMemoryStorage();
+ const target = { localStorage: storage, sessionStorage: storage };
+ expect(installStorageFallback(target)).toEqual([]);
+ expect(target.localStorage).toBe(storage);
+ });
+
+ it('replaces a throwing getter with a working in-memory storage', () => {
+ const target = deniedWindow();
+ expect(() => target.localStorage).toThrow('denied');
+
+ expect(installStorageFallback(target)).toEqual(['localStorage', 'sessionStorage']);
+
+ target.localStorage.setItem('color-theme', 'dark');
+ expect(target.localStorage.getItem('color-theme')).toBe('dark');
+ target.sessionStorage.setItem('lc-rum-queue', '[]');
+ expect(target.sessionStorage.getItem('lc-rum-queue')).toBe('[]');
+ expect(target.localStorage.getItem('lc-rum-queue')).toBeNull();
+ expect(target.localStorage).toBe(target.localStorage);
+ });
+});
+
+describe('createMemoryStorage', () => {
+ it('implements the Storage methods', () => {
+ const storage = createMemoryStorage();
+ expect(storage.getItem('missing')).toBeNull();
+ storage.setItem('a', '1');
+ storage.setItem('b', '2');
+ expect(storage).toHaveLength(2);
+ expect(storage.key(1)).toBe('b');
+ expect(storage.key(5)).toBeNull();
+ storage.removeItem('a');
+ expect(storage.getItem('a')).toBeNull();
+ storage.clear();
+ expect(storage).toHaveLength(0);
+ });
+
+ it('reports stored keys as own properties, as key-scanning readers expect', () => {
+ const storage = createMemoryStorage();
+ storage.setItem('textDraft_1', 'hello');
+ storage.setItem('getItem', 'shadow');
+ expect(Object.keys(storage)).toEqual(['textDraft_1', 'getItem']);
+ expect(storage.textDraft_1).toBe('hello');
+ expect(typeof storage.getItem).toBe('function');
+ expect(storage.getItem('getItem')).toBe('shadow');
+ });
+
+ it('routes named-property writes and deletes through the stored items', () => {
+ const storage = createMemoryStorage();
+ storage.lastModel = 'gpt';
+ expect(storage.getItem('lastModel')).toBe('gpt');
+ expect(storage).toHaveLength(1);
+ expect(Object.keys(storage)).toEqual(['lastModel']);
+ delete storage.lastModel;
+ expect(storage.getItem('lastModel')).toBeNull();
+ expect(storage).toHaveLength(0);
+ });
+});
diff --git a/client/src/polyfills/storage.ts b/client/src/polyfills/storage.ts
new file mode 100644
index 0000000000..181b776572
--- /dev/null
+++ b/client/src/polyfills/storage.ts
@@ -0,0 +1,87 @@
+type StorageName = 'localStorage' | 'sessionStorage';
+type StorageHost = Pick<Window, StorageName>;
+
+const STORAGE_NAMES: StorageName[] = ['localStorage', 'sessionStorage'];
+
+/** A session-lived stand-in for Web Storage. Stored keys are reported as own enumerable
+ * properties, as on a real `Storage`, so `Object.keys(localStorage)` keeps working. */
+export function createMemoryStorage(): Storage {
+ const items = new Map<string, string>();
+ const storage: Storage = {
+ get length() {
+ return items.size;
+ },
+ key: (index: number) => Array.from(items.keys())[index] ?? null,
+ getItem: (key: string) => items.get(String(key)) ?? null,
+ setItem: (key: string, value: string) => {
+ items.set(String(key), String(value));
+ },
+ removeItem: (key: string) => {
+ items.delete(String(key));
+ },
+ clear: () => items.clear(),
+ };
+
+ return new Proxy(storage, {
+ get: (target, property, receiver) => {
+ if (typeof property !== 'string' || property in target) {
+ return Reflect.get(target, property, receiver);
+ }
+ return items.get(property);
+ },
+ set: (target, property, value, receiver) => {
+ if (typeof property !== 'string' || property in target) {
+ return Reflect.set(target, property, value, receiver);
+ }
+ items.set(property, String(value));
+ return true;
+ },
+ deleteProperty: (target, property) => {
+ if (typeof property !== 'string' || property in target) {
+ return Reflect.deleteProperty(target, property);
+ }
+ items.delete(property);
+ return true;
+ },
+ ownKeys: () => Array.from(items.keys()),
+ getOwnPropertyDescriptor: (_target, property) => {
+ if (typeof property !== 'string' || !items.has(property)) {
+ return undefined;
+ }
+ return { value: items.get(property), writable: true, enumerable: true, configurable: true };
+ },
+ });
+}
+
+function isAccessible(target: StorageHost, name: StorageName): boolean {
+ try {
+ return target[name] != null;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * A browser that denies Web Storage by policy throws a `SecurityError` from the
+ * `localStorage`/`sessionStorage` getter itself, which would take down every reader in the
+ * app. Where the getter throws, it is replaced with an in-memory storage for the page's
+ * lifetime, so the app runs on defaults and remembers nothing across reloads.
+ */
+export function installStorageFallback(target: StorageHost): StorageName[] {
+ return STORAGE_NAMES.filter((name) => {
+ if (isAccessible(target, name)) {
+ return false;
+ }
+ const fallback = createMemoryStorage();
+ Object.defineProperty(target, name, {
+ configurable: true,
+ enumerable: true,
+ get: () => fallback,
+ });
+ return true;
+ });
+}
+
+if (typeof window !== 'undefined') {
+ installStorageFallback(window);
+}
diff --git a/e2e/specs/mock/scenarios/denied-web-storage.spec.ts b/e2e/specs/mock/scenarios/denied-web-storage.spec.ts
new file mode 100644
index 0000000000..995f3b0510
--- /dev/null
+++ b/e2e/specs/mock/scenarios/denied-web-storage.spec.ts
@@ -0,0 +1,92 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { NEW_CHAT_PATH, messagesView, replyPrompt, replyText, sendMessage } from '../helpers';
+
+/**
+ * A browser that denies Web Storage by policy throws a `SecurityError` from the
+ * `localStorage` and `sessionStorage` getters themselves. The denial is in place
+ * before the document's first script, as it is in a real browser, and the app has
+ * to run on defaults instead of handing the page to the error boundary.
+ */
+
+declare global {
+ interface Window {
+ /** Set by the init script when the getters were denied before the app loaded. */
+ __storageDenied?: boolean;
+ }
+}
+
+async function denyWebStorage(page: Page) {
+ await page.addInitScript(() => {
+ for (const name of ['localStorage', 'sessionStorage']) {
+ Object.defineProperty(window, name, {
+ configurable: true,
+ get() {
+ throw new DOMException('denied', 'SecurityError');
+ },
+ });
+ }
+ window.__storageDenied = true;
+ });
+}
+
+function collectPageErrors(page: Page): string[] {
+ const errors: string[] = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ return errors;
+}
+
+async function expectNoErrorBoundary(page: Page, errors: string[]) {
+ await expect(page.getByText('Oops! Something Unexpected Occurred')).toHaveCount(0);
+ expect(errors, `Unexpected runtime errors: ${errors.join(', ')}`).toEqual([]);
+}
+
+test.describe('denied web storage', () => {
+ test('the chat shell loads when the browser denies Web Storage @scenario:denied-web-storage-loads-the-chat', async ({
+ page,
+ }) => {
+ const errors = collectPageErrors(page);
+ await denyWebStorage(page);
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();
+ await expect(page.getByRole('main')).toBeVisible();
+ const storage = await page.evaluate(() => {
+ window.localStorage.setItem('probe', 'kept');
+ return {
+ denied: window.__storageDenied === true,
+ probe: window.localStorage.getItem('probe'),
+ session: typeof window.sessionStorage.getItem,
+ };
+ });
+ expect(storage).toEqual({ denied: true, probe: 'kept', session: 'function' });
+ await expectNoErrorBoundary(page, errors);
+ });
+
+ test('a user can chat and start a new chat when the browser denies Web Storage @scenario:denied-web-storage-chats-and-starts-a-new-chat', async ({
+ page,
+ }) => {
+ const errors = collectPageErrors(page);
+ await denyWebStorage(page);
+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });
+
+ await sendMessage(page, replyPrompt('denied-storage'));
+ await expect(messagesView(page).getByText(replyText('denied-storage'))).toBeVisible({
+ timeout: 30000,
+ });
+ await expect(page).toHaveURL(/\/c\/(?!new$)[^/]+$/);
+
+ await page
+ .getByRole('link', { name: 'New chat', exact: true })
+ .or(page.getByRole('button', { name: 'New chat', exact: true }))
+ .filter({ visible: true })
+ .first()
+ .click();
+
+ await expect(page).toHaveURL(/\/c\/new$/);
+ await expect(page.getByRole('textbox', { name: 'Message input' })).toBeVisible();
+ await expect(messagesView(page).getByText(replyText('denied-storage'))).toHaveCount(0);
+ await expectNoErrorBoundary(page, errors);
+ });
+});