Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
electronTrpc.auth.onTokenChanged.useSubscription(undefined, {
onData: async (data) => {
if (data?.token && data?.expiresAt) {
setAuthToken(null);
await authClient.signOut({ fetchOptions: { throw: false } });
// Swap atomically: a null-token + awaited sign-out gap let a
// concurrent get-session read "no session" and unmount the whole
// authenticated tree. The stale JWT re-mints on the next 401.
setAuthToken(data.token);
setJwt(null);

Copy link
Copy Markdown
Contributor

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 awaiting refetchSession() 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 two onTokenChanged events arrive in quick succession, the overlapping async refetchSession() 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) if refetchSession() rejects, the state is left authenticated (setAuthToken(data.token) succeeded) but with jwt === null and 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
Check if this issue is valid — if so, understand the root cause and fix it. At apps/desktop/src/renderer/providers/AuthProvider/AuthProvider.tsx, line 82:

<comment>The atomic swap now sets a fresh authToken while immediately nulling the JWT (`setJwt(null)`) and then awaiting `refetchSession()` 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 two `onTokenChanged` events arrive in quick succession, the overlapping async `refetchSession()` 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) if `refetchSession()` rejects, the state is left authenticated (`setAuthToken(data.token)` succeeded) but with `jwt === null` and 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.</comment>

<file context>
@@ -75,9 +75,11 @@ export function AuthProvider({ children }: { children: ReactNode }) {
+				// concurrent get-session read "no session" and unmount the whole
+				// authenticated tree. The stale JWT re-mints on the next 401.
 				setAuthToken(data.token);
+				setJwt(null);
 				try {
 					await refetchSession();
</file context>

Copy link
Copy Markdown
Member Author

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 onTokenChanged events: better-auth's session atom aborts an in-flight get-session when a new fetch starts, and every request reads the bearer via getAuthToken() 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 === null after 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, and ensureFreshJwt fetches 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.

try {
await refetchSession();
} catch (err) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,19 +112,31 @@ const createIndexedCollection = ((
createCollection({ ...config, ...indexDefaults })) as typeof createCollection;

/**
* Applied to every localStorage-backed collection so an exhausted store drops
* the write instead of throwing, which is what stops the rollback/retry loop
* that freezes the renderer.
* Applied to every localStorage-backed collection:
* - `startSync: true` + `gcTime: 0`: hydrate at construction, never GC. The
* sidebar mutation helpers read `.state` non-reactively, and a write into a
* not-yet-hydrated (or GC'd) collection rewrites the whole storage key from
* empty memory — erasing every persisted row for the org.
* - `withReadHeal`: per-row tolerant reads — one malformed entry escaping to
* the library's hydration catch-all would blank the entire store.
* - `withQuotaGuard`: an exhausted store drops the write instead of throwing,
* which is what stops the rollback/retry loop that freezes the renderer.
*/
const guardQuota = <T>(options: T): T =>
withQuotaGuard(options, {
// Oldest-first by the terminal GC's persisted-at index (24h pressure TTL)
// — survives relaunches, unlike registry membership.
reclaim: () => reclaimTerminalStateForQuota(),
// Not passed by reference: the guard's second argument is the error, which
// would land in the notice's optional `mode` slot.
onPersistFailed: (storageKey) => notifyQuotaExhausted(storageKey),
});
const hardenLocalCollection = <T>(
options: T,
heal?: (raw: unknown) => unknown,
): T =>
withQuotaGuard(
withReadHeal({ ...options, startSync: true, gcTime: 0 } as T, heal),
{
// Oldest-first by the terminal GC's persisted-at index (24h pressure TTL)
// — survives relaunches, unlike registry membership.
reclaim: () => reclaimTerminalStateForQuota(),
// Not passed by reference: the guard's second argument is the error, which
// would land in the notice's optional `mode` slot.
onPersistFailed: (storageKey) => notifyQuotaExhausted(storageKey),
},
);

type ElectricSyncConfig = ReturnType<typeof electricCollectionOptions>;
const createPersistedElectricCollection = ((config: ElectricSyncConfig) => {
Expand Down Expand Up @@ -764,7 +776,7 @@ function createOrgCollections(organizationId: string): OrgCollections {

const v2SidebarProjects = createIndexedCollection(
localStorageCollectionOptions(
guardQuota({
hardenLocalCollection({
id: `v2_sidebar_projects-${organizationId}`,
storageKey: `v2-sidebar-projects-${organizationId}`,
schema: dashboardSidebarProjectSchema,
Expand All @@ -782,18 +794,16 @@ function createOrgCollections(organizationId: string): OrgCollections {

const v2WorkspaceLocalState = createIndexedCollection(
localStorageCollectionOptions(
guardQuota(
withReadHeal(
{
id: `v2_workspace_local_state-${organizationId}`,
storageKey: `v2-workspace-local-state-${organizationId}`,
schema: workspaceLocalStateSchema,
// Explicit type so `withReadHeal`'s passthrough generic keeps the
// linkage between schema and getKey for downstream inference.
getKey: (item: WorkspaceLocalStateRow) => item.workspaceId,
},
healWorkspaceLocalState,
),
hardenLocalCollection(
{
id: `v2_workspace_local_state-${organizationId}`,
storageKey: `v2-workspace-local-state-${organizationId}`,
schema: workspaceLocalStateSchema,
// Explicit type so `withReadHeal`'s passthrough generic keeps the
// linkage between schema and getKey for downstream inference.
getKey: (item: WorkspaceLocalStateRow) => item.workspaceId,
},
healWorkspaceLocalState,
),
),
);
Expand All @@ -812,7 +822,7 @@ function createOrgCollections(organizationId: string): OrgCollections {

const v2SidebarSections = createIndexedCollection(
localStorageCollectionOptions(
guardQuota({
hardenLocalCollection({
id: `v2_sidebar_sections-${organizationId}`,
storageKey: `v2-sidebar-sections-${organizationId}`,
schema: dashboardSidebarSectionSchema,
Expand All @@ -831,7 +841,7 @@ function createOrgCollections(organizationId: string): OrgCollections {

const v2TerminalPresets = createIndexedCollection(
localStorageCollectionOptions(
guardQuota({
hardenLocalCollection({
id: `v2_terminal_presets-${organizationId}`,
storageKey: `v2-terminal-presets-${organizationId}`,
schema: v2TerminalPresetSchema,
Expand All @@ -842,27 +852,25 @@ function createOrgCollections(organizationId: string): OrgCollections {

const v2UserPreferences = createCollection(
localStorageCollectionOptions(
guardQuota(
withReadHeal(
{
id: `v2_user_preferences-${organizationId}`,
storageKey: `v2-user-preferences-${organizationId}`,
schema: v2UserPreferencesSchema,
// Cast widens the inferred literal "preferences" key to string so
// the collection slots into the shared OrgCollections.{...<TKey=string>}
// shape alongside the other v2 collections. Explicit `item` type so
// `withReadHeal`'s passthrough generic keeps schema/getKey linkage.
getKey: (item: V2UserPreferencesRow) => item.id as string,
},
healV2UserPreferences,
),
hardenLocalCollection(
{
id: `v2_user_preferences-${organizationId}`,
storageKey: `v2-user-preferences-${organizationId}`,
schema: v2UserPreferencesSchema,
// Cast widens the inferred literal "preferences" key to string so
// the collection slots into the shared OrgCollections.{...<TKey=string>}
// shape alongside the other v2 collections. Explicit `item` type so
// `withReadHeal`'s passthrough generic keeps schema/getKey linkage.
getKey: (item: V2UserPreferencesRow) => item.id as string,
},
healV2UserPreferences,
),
),
);

const failedWorkspaceCreates = createIndexedCollection(
localStorageCollectionOptions(
guardQuota({
hardenLocalCollection({
id: `failed_workspace_creates-${organizationId}`,
storageKey: `failed-workspace-creates-${organizationId}`,
schema: failedWorkspaceCreateSchema,
Expand Down
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"');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,54 @@ describe("withReadHeal parser", () => {
expect(parsed["s:bar"]?.data).toEqual({ b: 2, healed: true });
});

it("passes non-envelope values through unchanged", () => {
const heal = () => {
throw new Error("should not be called for non-envelope values");
it("drops non-envelope entries so they never reach the library's hydration", () => {
// A non-envelope value passed through would make the library throw
// InvalidStorageDataFormatError inside its whole-store try/catch,
// hydrating EVERY row as lost.
const opts = withReadHeal(
{} as {
parser?: { parse: (s: string) => unknown };
},
);
const raw = JSON.stringify({
"s:foo": "string-not-an-envelope",
"s:bar": { versionKey: "v1", data: { b: 2 } },
});
const parsed = opts.parser?.parse(raw) as Record<string, unknown>;
expect(parsed["s:foo"]).toBeUndefined();
expect(parsed["s:bar"]).toEqual({ versionKey: "v1", data: { b: 2 } });
});

it("drops only the entry whose heal throws, keeping the rest", () => {
const heal = (raw: unknown) => {
const data = raw as { poison?: boolean };
if (data.poison) throw new Error("unhealable");
return data;
};
const opts = withReadHeal(
{} as { parser?: { parse: (s: string) => unknown } },
heal,
);
const raw = JSON.stringify({ "s:foo": "string-not-an-envelope" });
const raw = JSON.stringify({
"s:bad": { versionKey: "v1", data: { poison: true } },
"s:good": { versionKey: "v2", data: { a: 1 } },
});
const parsed = opts.parser?.parse(raw) as Record<string, unknown>;
expect(parsed["s:foo"]).toBe("string-not-an-envelope");
expect(parsed["s:bad"]).toBeUndefined();
expect(parsed["s:good"]).toEqual({ versionKey: "v2", data: { a: 1 } });
});

it("defaults to an identity heal when none is provided", () => {
const opts = withReadHeal(
{} as {
parser?: { parse: (s: string) => unknown };
},
);
const raw = JSON.stringify({
"s:foo": { versionKey: "v1", data: { a: 1 } },
});
const parsed = opts.parser?.parse(raw) as Record<string, unknown>;
expect(parsed["s:foo"]).toEqual({ versionKey: "v1", data: { a: 1 } });
});
});

Expand Down Expand Up @@ -156,6 +193,50 @@ describe("withReadHeal end-to-end via real localStorageCollectionOptions", () =>
expect(row?.sidebarFileLinks).toBeUndefined();
});

it("hydrates surviving rows when the store holds one corrupt entry", async () => {
const { api: storage } = makeMapStorage();
const workspaceId = "11111111-1111-1111-1111-111111111111";
const projectId = "22222222-2222-2222-2222-222222222222";
storage.setItem(
"test-corrupt",
JSON.stringify({
// Not a {versionKey, data} envelope: without the per-row drop the
// library throws mid-hydration and treats the WHOLE store as empty,
// and the next mutation persists that emptiness.
"s:corrupt": 42,
[`s:${workspaceId}`]: {
versionKey: "v0",
data: {
workspaceId,
createdAt: "2026-01-01T00:00:00.000Z",
paneLayout: { version: 1, tabs: [], activeTabId: null },
sidebarState: { projectId },
},
},
}),
);

const collection = createCollection(
localStorageCollectionOptions(
withReadHeal(
{
id: "test-corrupt",
storageKey: "test-corrupt",
schema: workspaceLocalStateSchema,
getKey: (item: WorkspaceLocalStateRow) => item.workspaceId,
storage,
storageEventApi: noopEvents,
},
healWorkspaceLocalState,
),
),
);
await collection.preload();

expect(collection.get(workspaceId)?.sidebarState.projectId).toBe(projectId);
expect(collection.size).toBe(1);
});

it("heals a workspaceLocalState row missing optional + nested fields", async () => {
const { api: storage } = makeMapStorage();
const workspaceId = "11111111-1111-1111-1111-111111111111";
Expand Down
Loading
Loading