This repository was archived by the owner on Aug 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
refactor(web): route browser persistence through one validated seam #3651
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,148 @@ | ||
| import type { z } from "zod"; | ||
|
|
||
| // The single seam for the web host's browser persistence. Every per-device | ||
| // store routes its reads and writes through here so the | ||
| // getItem -> JSON.parse -> guard -> JSON.stringify -> setItem boilerplate lives | ||
| // in exactly one place instead of being hand-rolled in each store. | ||
| // | ||
| // localStorage is the web host's one persistence layer. IndexedDB is used in | ||
| // exactly one place (web-auth-adapters.ts) and is deliberately NOT routed | ||
| // through here: it holds the non-extractable AES-GCM cipher key, which | ||
| // localStorage physically cannot store without exposing its raw bytes as a | ||
| // string — the very property that keeps a stolen token dump undecryptable | ||
| // offline. That is a key vault, not app state, so it stays separate. | ||
| // | ||
| // Versioning: every store here is a discardable per-device cache that rebuilds | ||
| // from the server or re-derives, so "drop what no longer fits and rebuild" IS | ||
| // the migration strategy. The validated readers below (readValidated, | ||
| // createRecordStore) parse persisted data against a Zod schema on load and shed | ||
| // anything that fails — a shape change needs only a schema edit, never a | ||
| // hand-written localStorage migration. | ||
| // | ||
| // Two write tiers. The best-effort helpers (writeJson/removeKey) swallow storage | ||
| // failures because for a rebuildable cache a dropped write only costs persistence | ||
| // across reloads, never correctness. The *Strict variants propagate the failure | ||
| // and MUST be used where a silently-dropped write would be a correctness or | ||
| // security bug — the auth session/preferences, where a clear() that looked like | ||
| // it succeeded but didn't would leave a stale session recoverable on reload. | ||
|
|
||
| export function readJson<T>(key: string, fallback: () => T): T { | ||
| try { | ||
| const raw = window.localStorage.getItem(key); | ||
| return raw ? (JSON.parse(raw) as T) : fallback(); | ||
| } catch { | ||
| // Absent, corrupt, or unparseable: fall back rather than throw. Callers | ||
| // treat missing state as empty. | ||
| return fallback(); | ||
| } | ||
| } | ||
|
|
||
| export function writeJson<T>(key: string, value: T): void { | ||
| try { | ||
| window.localStorage.setItem(key, JSON.stringify(value)); | ||
| } catch { | ||
| // Best-effort: a storage failure (quota, privacy mode) only costs | ||
| // persistence across reloads, never correctness — the in-memory value is | ||
| // still authoritative for this session. Use writeJsonStrict where a dropped | ||
| // write must surface. | ||
| } | ||
| } | ||
|
|
||
| export function removeKey(key: string): void { | ||
| try { | ||
| window.localStorage.removeItem(key); | ||
| } catch { | ||
| // Best-effort, same rationale as writeJson. Use removeKeyStrict where a | ||
| // dropped removal must surface (e.g. clearing an auth session on logout). | ||
| } | ||
| } | ||
|
gantoine marked this conversation as resolved.
|
||
|
|
||
| // Strict write/remove: let storage failures propagate so the caller can react | ||
| // instead of treating a dropped write as success. For auth state (see the two- | ||
| // tier note above), not the rebuildable caches. | ||
| export function writeJsonStrict<T>(key: string, value: T): void { | ||
| window.localStorage.setItem(key, JSON.stringify(value)); | ||
| } | ||
|
|
||
| export function removeKeyStrict(key: string): void { | ||
| window.localStorage.removeItem(key); | ||
| } | ||
|
|
||
| // Schema-validated read of a single persisted object. Parses the JSON, checks it | ||
| // against `schema`, and returns the fallback on any failure (absent, corrupt, or | ||
| // a shape that no longer matches — see the versioning note above). | ||
| export function readValidated<S extends z.ZodType>( | ||
| key: string, | ||
| schema: S, | ||
| fallback: () => z.infer<S>, | ||
| ): z.infer<S> { | ||
| let raw: string | null; | ||
| try { | ||
| raw = window.localStorage.getItem(key); | ||
| } catch { | ||
| return fallback(); | ||
| } | ||
| if (!raw) return fallback(); | ||
| try { | ||
| const result = schema.safeParse(JSON.parse(raw)); | ||
| return result.success ? result.data : fallback(); | ||
| } catch { | ||
| // Invalid JSON. | ||
| return fallback(); | ||
| } | ||
| } | ||
|
|
||
| export interface JsonStore<T> { | ||
| get(): T; | ||
| set(value: T): void; | ||
| clear(): void; | ||
| } | ||
|
|
||
| // A cached live store for the per-device registries (workspaces, archive, task | ||
| // metadata), which are all `Record<string, Entry>`: load once at construction, | ||
| // keep the value in memory, write through on every set. Each entry is validated | ||
| // against `entrySchema` on load and invalid entries are dropped individually, so | ||
| // a shape change sheds only the stale rows instead of nuking the whole map. | ||
| export function createRecordStore<S extends z.ZodType>( | ||
| key: string, | ||
| entrySchema: S, | ||
| ): JsonStore<Record<string, z.infer<S>>> { | ||
| const load = (): Record<string, z.infer<S>> => { | ||
| const rawRecord = readJson<unknown>(key, () => ({})); | ||
| if (typeof rawRecord !== "object" || rawRecord === null) return {}; | ||
| const valid: Record<string, z.infer<S>> = {}; | ||
| for (const [id, value] of Object.entries(rawRecord)) { | ||
| const result = entrySchema.safeParse(value); | ||
| if (result.success) valid[id] = result.data; | ||
| } | ||
| return valid; | ||
| }; | ||
|
|
||
| let cache = load(); | ||
| return { | ||
| get: () => cache, | ||
| set: (value) => { | ||
| cache = value; | ||
| writeJson(key, value); | ||
| }, | ||
| clear: () => { | ||
| cache = {}; | ||
| removeKey(key); | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| // StateStorage backend for @posthog/ui's zustand persist (web-storage.ts). | ||
| // Zustand already serializes, so this passes raw strings straight through. It | ||
| // also lets storage errors propagate: the renderer persistence layer awaits and | ||
| // logs failed writes, so swallowing here would report a dropped draft/setting/ | ||
| // layout write as a success that vanishes on reload. | ||
| export const rawLocalStorage = { | ||
| getItem: (name: string): string | null => window.localStorage.getItem(name), | ||
| setItem: (name: string, value: string): void => { | ||
| window.localStorage.setItem(name, value); | ||
| }, | ||
|
gantoine marked this conversation as resolved.
|
||
| removeItem: (name: string): void => { | ||
| window.localStorage.removeItem(name); | ||
| }, | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,7 @@ | ||
| import { registerRendererStateStorage } from "@posthog/ui/shell/rendererStorage"; | ||
| import { rawLocalStorage } from "./web-local-store"; | ||
|
|
||
| // Web persistence backend for @posthog/ui stores (drafts, settings, layout). | ||
| // Desktop persists through the host; web uses origin-scoped localStorage. | ||
| registerRendererStateStorage({ | ||
| getItem: (name) => window.localStorage.getItem(name), | ||
| setItem: (name, value) => { | ||
| window.localStorage.setItem(name, value); | ||
| }, | ||
| removeItem: (name) => { | ||
| window.localStorage.removeItem(name); | ||
| }, | ||
| }); | ||
| // Desktop persists through the host; web uses origin-scoped localStorage via the | ||
| // shared seam (web-local-store). | ||
| registerRendererStateStorage(rawLocalStorage); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.