Repository navigation
fix(desktop): prevent sidebar localStorage state loss and token-swap remounts #6089
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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
103 changes: 103 additions & 0 deletions
103
...erer/routes/_authenticated/providers/CollectionsProvider/localCollectionLifecycle.test.ts
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,103 @@ | ||
| import { describe, expect, it } from "bun:test"; | ||
| import { | ||
| createCollection, | ||
| localStorageCollectionOptions, | ||
| } from "@tanstack/react-db"; | ||
| import { z } from "zod"; | ||
|
|
||
| /** | ||
| * Pins the @tanstack/db lifecycle semantics `hardenLocalCollection` relies on | ||
| * (collections.ts): a localStorage collection only hydrates when sync starts, | ||
| * and a mutation on a never-synced (`idle`) collection re-serializes the whole | ||
| * storage key from empty memory — erasing every persisted row. `startSync: | ||
| * true` makes that state unrepresentable. If a library upgrade changes either | ||
| * behavior, these tests flag that the hardening needs a fresh look. | ||
| */ | ||
|
|
||
| const rowSchema = z.object({ id: z.string(), label: z.string() }); | ||
| type Row = z.infer<typeof rowSchema>; | ||
|
|
||
| function makeMapStorage() { | ||
| const map = new Map<string, string>(); | ||
| return { | ||
| store: map, | ||
| api: { | ||
| getItem: (key: string) => map.get(key) ?? null, | ||
| setItem: (key: string, value: string) => { | ||
| map.set(key, value); | ||
| }, | ||
| removeItem: (key: string) => { | ||
| map.delete(key); | ||
| }, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| const noopEvents = { | ||
| addEventListener: () => {}, | ||
| removeEventListener: () => {}, | ||
| }; | ||
|
|
||
| function seedRow( | ||
| storage: { setItem(k: string, v: string): void }, | ||
| key: string, | ||
| ) { | ||
| storage.setItem( | ||
| key, | ||
| JSON.stringify({ | ||
| "s:existing": { | ||
| versionKey: "v0", | ||
| data: { id: "existing", label: "old" }, | ||
| }, | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| function makeCollection( | ||
| storage: ReturnType<typeof makeMapStorage>["api"], | ||
| key: string, | ||
| options: { startSync?: boolean } = {}, | ||
| ) { | ||
| return createCollection( | ||
| localStorageCollectionOptions({ | ||
| id: key, | ||
| storageKey: key, | ||
| schema: rowSchema, | ||
| getKey: (item: Row) => item.id, | ||
| storage, | ||
| storageEventApi: noopEvents, | ||
| gcTime: 0, | ||
| ...options, | ||
| }), | ||
| ); | ||
| } | ||
|
|
||
| describe("localStorage collection lifecycle", () => { | ||
| it("startSync: true — insert on a fresh collection preserves existing rows", () => { | ||
| const { store, api: storage } = makeMapStorage(); | ||
| seedRow(storage, "test-live"); | ||
|
|
||
| const collection = makeCollection(storage, "test-live", { | ||
| startSync: true, | ||
| }); | ||
| collection.insert({ id: "new", label: "new" }); | ||
|
|
||
| expect(collection.get("existing")?.label).toBe("old"); | ||
| const persisted = store.get("test-live") ?? ""; | ||
| expect(persisted).toContain('"id":"existing"'); | ||
| expect(persisted).toContain('"id":"new"'); | ||
| }); | ||
|
|
||
| it("without startSync — the same insert wipes the store (the hazard being defended against)", () => { | ||
| const { store, api: storage } = makeMapStorage(); | ||
| seedRow(storage, "test-idle"); | ||
|
|
||
| const collection = makeCollection(storage, "test-idle"); | ||
| collection.insert({ id: "new", label: "new" }); | ||
|
|
||
| // Library behavior pin, not desired behavior: the idle collection never | ||
| // hydrated, so the whole-store rewrite drops the pre-existing row. If | ||
| // this starts passing rows through, startSync may no longer be needed. | ||
| expect(store.get("test-idle") ?? "").not.toContain('"id":"existing"'); | ||
| }); | ||
| }); |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P2: The atomic swap now sets a fresh authToken while immediately nulling the JWT (
setJwt(null)) and then awaitingrefetchSession()to re-mint a new JWT via the 401-refresh path. This new null-the-JWT-then-refetch sequence has two unguarded edges: (1) if twoonTokenChangedevents arrive in quick succession, the overlapping asyncrefetchSession()calls are not serialized/versioned, so a stale refresh result can apply to the newer swap — the same stale-refresh-overwrites-newer-state race that a generation guard is meant to prevent; and (2) ifrefetchSession()rejects, the state is left authenticated (setAuthToken(data.token)succeeded) but withjwt === nulland no restore path, i.e. a session credential was permanently cleared. Consider versioning the swap (a generation counter captured around the swap, and only applying the refetch result if the generation is still current), and ensure the failure path restores a usable JWT or treats the null-JWT state as signed-out rather than leaving an inconsistent authenticated-without-credential state.Prompt for AI agents
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Assessed as non-blocking, leaving as-is:
(1) Overlapping
onTokenChangedevents: better-auth's session atom aborts an in-flight get-session when a new fetch starts, and every request reads the bearer viagetAuthToken()at send time — so the last swap's refetch always resolves against the newest token. Rotation events are also rare (OAuth deep-link saves only; the subscription does not fire on boot or refresh).(2)
jwt === nullafter a failed refetch is the designed lazy state, not a stranded one: Electric's 401 handler (refreshJwtAfterUnauthorized) and the 50-minute interval in this same provider both re-mint it, andensureFreshJwtfetches on demand. The bearer token — the actual session credential — is never cleared on this path. The pre-fix code left the stale JWT in place, which was strictly worse.