The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(cloud): sign-out reported success while the session survived in the keychain
David14ffa2cbf65b
diff --git a/src/api/cloud/__tests__/keychain-storage.test.ts b/src/api/cloud/__tests__/keychain-storage.test.tsnew file mode 100644index 00000000..e119155f--- /dev/null+++ b/src/api/cloud/__tests__/keychain-storage.test.ts@@ -0,0 +1,155 @@+/**+ * The keychain-backed session storage adapter (src/api/cloud/supabase.ts).+ *+ * This adapter holds the LU Cloud refresh token. It was completely untested,+ * and the invariants it relies on are all written as prose in the comments —+ * so this file asserts them instead.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++const secretGet = vi.fn()+const secretSet = vi.fn()+const secretDelete = vi.fn()++vi.mock('../../backend', () => ({+ secretGet: (...a: unknown[]) => secretGet(...a),+ secretSet: (...a: unknown[]) => secretSet(...a),+ secretDelete: (...a: unknown[]) => secretDelete(...a),+ oauthStart: vi.fn(),+ oauthWait: vi.fn(),+ openExternal: vi.fn(),+}))+vi.mock('@supabase/supabase-js', () => ({ createClient: vi.fn() }))+vi.mock('../config', () => ({ SUPABASE_URL: 'https://x.test', SUPABASE_ANON_KEY: 'anon' }))++// vitest runs in the node environment here, so the adapter's localStorage+// fallback needs a stand-in.+const memory = new Map<string, string>()+vi.stubGlobal('localStorage', {+ getItem: (k: string) => memory.get(k) ?? null,+ setItem: (k: string, v: string) => void memory.set(k, String(v)),+ removeItem: (k: string) => void memory.delete(k),+ clear: () => memory.clear(),+})++const SESSION = 'lu-cloud-session'+const VERIFIER = 'lu-cloud-session-code-verifier'++async function freshAdapter() {+ vi.resetModules()+ localStorage.clear()+ secretGet.mockReset()+ secretSet.mockReset()+ secretDelete.mockReset()+ secretGet.mockResolvedValue(null)+ secretSet.mockResolvedValue(undefined)+ secretDelete.mockResolvedValue(undefined)+ const mod = await import('../supabase')+ return mod.keychainStorage+}++beforeEach(() => {+ localStorage.clear()+})++describe('a healthy keychain keeps the token out of localStorage', () => {+ it('writes to the keychain and drops any stale localStorage copy', async () => {+ const store = await freshAdapter()+ localStorage.setItem(SESSION, 'stale-from-an-earlier-fallback')++ await store.setItem(SESSION, 'fresh')++ expect(secretSet).toHaveBeenCalledWith(SESSION, 'fresh')+ expect(localStorage.getItem(SESSION)).toBeNull()+ })++ it('gives the PKCE verifier its own account so it cannot clobber the session', async () => {+ const store = await freshAdapter()+ await store.setItem(SESSION, 'session-value')+ await store.setItem(VERIFIER, 'verifier-value')++ const accounts = secretSet.mock.calls.map((c) => c[0])+ expect(new Set(accounts).size).toBe(2)+ expect(accounts).toContain(SESSION)+ })+})++describe('a transient keychain failure must not latch', () => {+ it('falls back for that call only and retries the keychain next time', async () => {+ const store = await freshAdapter()+ secretSet.mockRejectedValueOnce(new Error('user cancelled the unlock prompt'))++ await store.setItem(SESSION, 'first')+ expect(localStorage.getItem(SESSION)).toBe('first')++ secretSet.mockResolvedValue(undefined)+ await store.setItem(SESSION, 'second')+ expect(secretSet).toHaveBeenLastCalledWith(SESSION, 'second')+ expect(localStorage.getItem(SESSION)).toBeNull()+ })++ it('a permanent absence latches so later calls skip the keychain entirely', async () => {+ const store = await freshAdapter()+ secretSet.mockRejectedValue(new Error('keychain unsupported on this platform'))++ await store.setItem(SESSION, 'first')+ const callsAfterFirst = secretSet.mock.calls.length+ await store.setItem(SESSION, 'second')++ expect(secretSet.mock.calls.length).toBe(callsAfterFirst)+ expect(localStorage.getItem(SESSION)).toBe('second')+ })++ it('prefers a localStorage fallback copy over the older keychain value', async () => {+ const store = await freshAdapter()+ secretGet.mockResolvedValue('older-keychain-value')+ localStorage.setItem(SESSION, 'newer-fallback-value')++ await expect(store.getItem(SESSION)).resolves.toBe('newer-fallback-value')+ })+})++describe('sign-out must not leave a resurrectable session', () => {+ it('clears both stores on a healthy keychain', async () => {+ const store = await freshAdapter()+ localStorage.setItem(SESSION, 'fallback-copy')++ await store.removeItem(SESSION)++ expect(secretDelete).toHaveBeenCalledWith(SESSION)+ expect(localStorage.getItem(SESSION)).toBeNull()+ })++ it('does not report success when the keychain entry survived', async () => {+ const store = await freshAdapter()+ // Not "keychain unavailable"/"unsupported" — the keychain is THERE and the+ // delete failed anyway (locked at wake, dismissed prompt, CredMan hiccup).+ // The refresh token is still in it, so the next launch signs the user back+ // in. Silently resolving here reports a sign-out that did not happen.+ secretDelete.mockRejectedValue(new Error('The stub received bad data.'))++ await expect(store.removeItem(SESSION)).rejects.toThrow()+ expect(localStorage.getItem(SESSION)).toBeNull()+ })++ it('neutralises the surviving entry so the next launch cannot restore it', async () => {+ const store = await freshAdapter()+ secretDelete.mockRejectedValue(new Error('The stub received bad data.'))++ await store.removeItem(SESSION).catch(() => {})++ // Best effort: a write may succeed where the delete did not.+ expect(secretSet).toHaveBeenCalledWith(SESSION, expect.any(String))+ const tombstone = secretSet.mock.calls[0][1]++ // Next launch: the entry is physically there, but must read as signed out.+ secretGet.mockResolvedValue(tombstone)+ await expect(store.getItem(SESSION)).resolves.toBeNull()+ })++ it('a real session still reads back normally', async () => {+ const store = await freshAdapter()+ secretGet.mockResolvedValue('{"access_token":"abc"}')+ await expect(store.getItem(SESSION)).resolves.toBe('{"access_token":"abc"}')+ })+})diff --git a/src/api/cloud/supabase.ts b/src/api/cloud/supabase.tsindex db92c8a7..ee73ecc7 100644--- a/src/api/cloud/supabase.ts+++ b/src/api/cloud/supabase.ts@@ -38,8 +38,15 @@ function keychainAccount(key: string): string {return key.startsWith(LOCAL_KEY) ? SESSION_ACCOUNT + key.slice(LOCAL_KEY.length) : key}-const keychainStorage = {+// Written over a keychain entry whose delete failed: the entry survives+// physically, but must never sign anyone back in. getItem reports it as absent.+const TOMBSTONE = '__lu_signed_out__'++/** Exported for its unit tests — this adapter holds the refresh token, and the+ * invariants in the comments above are worth asserting rather than trusting. */+export const keychainStorage = {async getItem(key: string): Promise<string | null> {+ let value: string | null = nullif (!keychainBroken) {try {const fromKeychain = await secretGet(keychainAccount(key))@@ -48,12 +55,15 @@ const keychainStorage = {// stores hold the key, localStorage is the newer one. A clean// keychain miss must also consult it, or a fallback-written session// is invisible on the next launch and the user is signed out.- return localStorage.getItem(key) ?? fromKeychain+ value = localStorage.getItem(key) ?? fromKeychain} catch (err) {if (keychainMissing(err)) keychainBroken = true+ value = localStorage.getItem(key)}+ } else {+ value = localStorage.getItem(key)}- return localStorage.getItem(key)+ return value === TOMBSTONE ? null : value},async setItem(key: string, value: string): Promise<void> {if (!keychainBroken) {@@ -70,16 +80,35 @@ const keychainStorage = {localStorage.setItem(key, value)},async removeItem(key: string): Promise<void> {- if (!keychainBroken) {- try {- await secretDelete(keychainAccount(key))- } catch (err) {- if (keychainMissing(err)) keychainBroken = true- }- }// Always clear the fallback copy too — sign-out must never leave a// resurrectable session (or plaintext refresh token) in localStorage.localStorage.removeItem(key)+ if (keychainBroken) return++ const account = keychainAccount(key)+ try {+ await secretDelete(account)+ return+ } catch (err) {+ if (keychainMissing(err)) {+ keychainBroken = true+ return+ }+ }+ // The keychain is THERE and the delete failed anyway (locked at wake, a+ // dismissed unlock prompt, a Credential Manager hiccup) — so the refresh+ // token is still in it and the next launch would sign the user back in+ // after they explicitly signed out. This used to resolve silently, which+ // reported a sign-out that had not happened.+ //+ // Neutralise the surviving entry (best effort: a write may succeed where+ // the delete did not), then report the failure instead of swallowing it.+ try {+ await secretSet(account, TOMBSTONE)+ } catch {+ // Nothing left to try — the throw below is the only honest outcome.+ }+ throw new Error('Signed out, but the saved session could not be removed from the keychain.')},}