Skip to content

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.

tech(Cloud): Abmelden meldet keinen falschen Erfolg mehr, und 429 heißt nicht immer 'Guthaben leer'

David93498d039d93
diff --git a/src-tauri/src/commands/oauth.rs b/src-tauri/src/commands/oauth.rs
index 296229d1..7d0926b5 100644
--- a/src-tauri/src/commands/oauth.rs
+++ b/src-tauri/src/commands/oauth.rs
@@ -35,7 +35,126 @@ pub struct PendingLogin {
#[derive(Default)]
pub struct OauthPending(pub Mutex<HashMap<u16, PendingLogin>>);
-const CALLBACK_BODY: &str = "<!doctype html><html><body style=\"font-family:-apple-system,system-ui,sans-serif;background:#161616;color:#e5e5e5;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Signed in — you can close this tab and return to LU.</p></body></html>";
+/// The redirect URI handed to Supabase — and registered in its allow-list — is
+/// always exactly this path on the ladder port.
+const CALLBACK_PATH: &str = "/callback";
+
+/// Longest request head this listener will read before giving up on a socket.
+const MAX_HEAD_BYTES: usize = 16 * 1024;
+
+/// What one accepted request turns out to be.
+#[derive(Debug, PartialEq, Eq)]
+enum Verdict {
+ /// A genuine provider callback; the query string goes to the frontend.
+ Callback(String),
+ /// Anything else: 404 it and stay armed for the real redirect.
+ Reject,
+}
+
+/// Decide whether a raw HTTP request is the redirect this attempt is waiting
+/// for.
+///
+/// This listener sits on a loopback port that ANY page in ANY browser can
+/// reach — `<img src="http://127.0.0.1:17872/x?error=…">` is a cross-origin
+/// request the browser sends without asking anyone, and no same-origin policy
+/// stops it being SENT. It used to be enough for such a request to carry
+/// `code=` or `error=` anywhere in its query: it was answered, the pending
+/// sign-in was resolved with the stranger's query, and their attacker-written
+/// `error_description` was displayed in LU's auth panel. Any page could
+/// therefore kill a sign-in in progress and put text of its choosing in front
+/// of the user. So a request now has to look like what Supabase actually
+/// sends:
+///
+/// * `GET` — the redirect is a navigation, never a POST.
+/// * exactly `/callback` — the only path in the redirect allow-list.
+/// * `Host: 127.0.0.1:<port>` (or `localhost:<port>`) — a DNS-rebinding page
+/// reaches this same socket under its own hostname, which is not that.
+/// * no `Origin` header — a cross-site top-level navigation does not send
+/// one, while every `fetch`/XHR (`no-cors` included) does.
+/// * `Sec-Fetch-Mode: navigate` and `Sec-Fetch-Dest: document` whenever the
+/// browser sends those headers. A page cannot forge or drop them, and they
+/// are exactly what separates the redirect from an `<img>`, `<script>` or
+/// `<iframe>` pointed at the same URL. Absent (pre-2023 Safari, a non-
+/// browser client) they simply do not vote.
+///
+/// `state` is deliberately not checked, and this is the one hole left: the
+/// Supabase PKCE redirect carries `code` alone, so the only way to bind a
+/// per-attempt nonce would be to add a query parameter to the redirect URI —
+/// which the server's exact-match `uri_allow_list` would then refuse,
+/// breaking sign-in for everyone. What remains reachable after the checks
+/// above is a top-level navigation the attacker cannot make silently: a
+/// `window.open`/form submit needs a user gesture and opens a visible window.
+/// A code from a stranger is useless in any case — the PKCE verifier never
+/// leaves the app, so the exchange fails.
+fn classify(req: &str, port: u16) -> Verdict {
+ let mut lines = req.lines();
+ let Some(request_line) = lines.next() else {
+ return Verdict::Reject;
+ };
+ let mut parts = request_line.split_whitespace();
+ let (Some(method), Some(target)) = (parts.next(), parts.next()) else {
+ return Verdict::Reject;
+ };
+ if method != "GET" {
+ return Verdict::Reject;
+ }
+ let (path, query) = target.split_once('?').unwrap_or((target, ""));
+ if path != CALLBACK_PATH {
+ return Verdict::Reject;
+ }
+ if !query
+ .split('&')
+ .any(|kv| kv.starts_with("code=") || kv.starts_with("error="))
+ {
+ return Verdict::Reject;
+ }
+ let mut host_ok = false;
+ for line in lines {
+ if line.is_empty() {
+ break; // end of the header block
+ }
+ let Some((name, value)) = line.split_once(':') else {
+ continue;
+ };
+ let value = value.trim();
+ match name.trim().to_ascii_lowercase().as_str() {
+ "host" => {
+ host_ok = value == format!("127.0.0.1:{port}") || value == format!("localhost:{port}")
+ }
+ "origin" => return Verdict::Reject,
+ "sec-fetch-mode" if !value.eq_ignore_ascii_case("navigate") => return Verdict::Reject,
+ "sec-fetch-dest" if !value.eq_ignore_ascii_case("document") => return Verdict::Reject,
+ _ => {}
+ }
+ }
+ if !host_ok {
+ return Verdict::Reject;
+ }
+ Verdict::Callback(query.to_string())
+}
+
+/// Read one request head (up to the blank line). The whole head shares a
+/// single deadline rather than each read having its own: a socket dribbling a
+/// byte at a time must not park the accept loop while the real callback waits
+/// in the backlog.
+async fn read_head(stream: &mut tokio::net::TcpStream) -> String {
+ let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
+ let mut head = Vec::with_capacity(2048);
+ let mut chunk = [0u8; 2048];
+ loop {
+ let n = match tokio::time::timeout_at(deadline, stream.read(&mut chunk)).await {
+ Ok(Ok(n)) if n > 0 => n,
+ _ => break,
+ };
+ head.extend_from_slice(&chunk[..n]);
+ if head.windows(4).any(|w| w == b"\r\n\r\n") || head.len() >= MAX_HEAD_BYTES {
+ break;
+ }
+ }
+ String::from_utf8_lossy(&head).into_owned()
+}
+
+const CALLBACK_BODY: &str ="<!doctype html><html><body style=\"font-family:-apple-system,system-ui,sans-serif;background:#161616;color:#e5e5e5;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Signed in — you can close this tab and return to LU.</p></body></html>";
const DENIED_BODY: &str = "<!doctype html><html><body style=\"font-family:-apple-system,system-ui,sans-serif;background:#161616;color:#e5e5e5;display:flex;align-items:center;justify-content:center;height:100vh;margin:0\"><p>Sign-in didn't complete — you can close this tab and try again in LU.</p></body></html>";
/// Bind the first free ladder port and arm an accept loop that serves exactly
@@ -59,39 +178,18 @@ pub async fn oauth_start(state: tauri::State<'_, OauthPending>) -> Result<u16, S
};
let (tx, rx) = oneshot::channel::<String>();
let task = tauri::async_runtime::spawn(async move {
- // Accept until a request actually carries the callback query
- // (code=… or error=…). Strays — browser preconnects that send no
- // bytes, favicon fetches, localhost port probes — get a 404 and
- // the armed window stays open for the real redirect. oauth_wait's
- // timeout/abort bounds the loop's lifetime; the listener drops
- // with this task. If oauth_wait times out first, tx.send just
- // errs into the void — harmless.
+ // Accept until a request actually IS the provider redirect (see
+ // classify). Everything else — browser preconnects that send no
+ // bytes, favicon fetches, localhost port probes, and any page
+ // trying to plant its own query here — gets a 404 while the armed
+ // window stays open for the real redirect, so a stray can neither
+ // resolve nor cancel the sign-in. oauth_wait's timeout/abort
+ // bounds the loop's lifetime; the listener drops with this task.
+ // If oauth_wait times out first, tx.send just errs into the void.
loop {
let Ok((mut stream, _)) = listener.accept().await else { return };
- let mut buf = vec![0u8; 8192];
- // Short read deadline so an idle preconnect socket can't park
- // the loop while the real callback waits in the backlog.
- let n = match tokio::time::timeout(
- std::time::Duration::from_secs(2),
- stream.read(&mut buf),
- )
- .await
- {
- Ok(Ok(n)) => n,
- _ => 0,
- };
- let req = String::from_utf8_lossy(&buf[..n]);
- // Request line: GET /callback?code=…&state=… HTTP/1.1
- let query = req
- .lines()
- .next()
- .and_then(|l| l.split_whitespace().nth(1))
- .and_then(|path| path.split_once('?').map(|(_, q)| q.to_string()))
- .unwrap_or_default();
- let is_callback = query
- .split('&')
- .any(|kv| kv.starts_with("code=") || kv.starts_with("error="));
- if !is_callback {
+ let req = read_head(&mut stream).await;
+ let Verdict::Callback(query) = classify(&req, port) else {
let _ = stream
.write_all(
b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
@@ -99,7 +197,7 @@ pub async fn oauth_start(state: tauri::State<'_, OauthPending>) -> Result<u16, S
.await;
let _ = stream.shutdown().await;
continue;
- }
+ };
// Provider denial arrives as error=…&error_description=… — be
// honest in the tab; the frontend gets the raw query either way.
let body = if query.split('&').any(|kv| kv.starts_with("error=")) {
@@ -170,3 +268,152 @@ pub async fn oauth_wait(
Err(_) => Err("sign-in timed out — the browser never came back".into()),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::{classify, Verdict};
+
+ const PORT: u16 = 17872;
+
+ /// What Supabase's 302 makes the browser send.
+ fn real_redirect(query: &str) -> String {
+ format!(
+ "GET /callback?{query} HTTP/1.1\r\n\
+ Host: 127.0.0.1:{PORT}\r\n\
+ Upgrade-Insecure-Requests: 1\r\n\
+ Accept: text/html,application/xhtml+xml\r\n\
+ Sec-Fetch-Site: cross-site\r\n\
+ Sec-Fetch-Mode: navigate\r\n\
+ Sec-Fetch-Dest: document\r\n\
+ Connection: close\r\n\r\n"
+ )
+ }
+
+ #[test]
+ fn the_real_redirect_is_accepted() {
+ assert_eq!(
+ classify(&real_redirect("code=abc123"), PORT),
+ Verdict::Callback("code=abc123".into())
+ );
+ }
+
+ #[test]
+ fn a_provider_denial_is_still_a_callback() {
+ let q = "error=access_denied&error_description=The+user+said+no";
+ assert_eq!(classify(&real_redirect(q), PORT), Verdict::Callback(q.into()));
+ }
+
+ #[test]
+ fn a_browser_that_sends_no_sec_fetch_headers_still_gets_in() {
+ // Pre-16.4 Safari. Those headers cannot vote when they are absent.
+ let req = format!(
+ "GET /callback?code=abc HTTP/1.1\r\nHost: localhost:{PORT}\r\nConnection: close\r\n\r\n"
+ );
+ assert_eq!(classify(&req, PORT), Verdict::Callback("code=abc".into()));
+ }
+
+ // ── the attacks the loopback used to serve ──────────────────────────
+
+ #[test]
+ fn an_image_tag_on_any_page_cannot_kill_the_sign_in() {
+ // <img src="http://127.0.0.1:17872/callback?error=…"> — same URL, but
+ // the browser labels it as a subresource fetch, and only a browser can
+ // set these headers.
+ let req = format!(
+ "GET /callback?error=nope&error_description=Your+account+was+closed HTTP/1.1\r\n\
+ Host: 127.0.0.1:{PORT}\r\n\
+ Sec-Fetch-Site: cross-site\r\n\
+ Sec-Fetch-Mode: no-cors\r\n\
+ Sec-Fetch-Dest: image\r\n\r\n"
+ );
+ assert_eq!(classify(&req, PORT), Verdict::Reject);
+ }
+
+ #[test]
+ fn a_scripted_fetch_is_refused_by_its_origin_alone() {
+ // fetch(url, {mode:'no-cors'}) reaches the socket, but always names
+ // the page it came from.
+ let req = format!(
+ "GET /callback?code=attacker HTTP/1.1\r\n\
+ Host: 127.0.0.1:{PORT}\r\n\
+ Origin: https://evil.example\r\n\r\n"
+ );
+ assert_eq!(classify(&req, PORT), Verdict::Reject);
+ }
+
+ #[test]
+ fn an_iframe_navigation_is_not_a_top_level_one() {
+ let req = format!(
+ "GET /callback?code=attacker HTTP/1.1\r\n\
+ Host: 127.0.0.1:{PORT}\r\n\
+ Sec-Fetch-Mode: navigate\r\n\
+ Sec-Fetch-Dest: iframe\r\n\r\n"
+ );
+ assert_eq!(classify(&req, PORT), Verdict::Reject);
+ }
+
+ #[test]
+ fn dns_rebinding_reaches_the_socket_under_the_wrong_host() {
+ let req = "GET /callback?code=abc HTTP/1.1\r\n\
+ Host: rebind.evil.example:17872\r\n\
+ Sec-Fetch-Mode: navigate\r\n\
+ Sec-Fetch-Dest: document\r\n\r\n";
+ assert_eq!(classify(req, PORT), Verdict::Reject);
+ }
+
+ #[test]
+ fn a_host_naming_another_ladder_port_is_not_this_attempt() {
+ let req = "GET /callback?code=abc HTTP/1.1\r\nHost: 127.0.0.1:17873\r\n\r\n";
+ assert_eq!(classify(req, PORT), Verdict::Reject);
+ }
+
+ #[test]
+ fn a_missing_host_header_is_not_trusted() {
+ assert_eq!(
+ classify("GET /callback?code=abc HTTP/1.1\r\n\r\n", PORT),
+ Verdict::Reject
+ );
+ }
+
+ #[test]
+ fn the_query_must_live_on_the_callback_path() {
+ let req = format!("GET /?code=abc HTTP/1.1\r\nHost: 127.0.0.1:{PORT}\r\n\r\n");
+ assert_eq!(classify(&req, PORT), Verdict::Reject);
+ let req = format!("GET /callback/x?code=abc HTTP/1.1\r\nHost: 127.0.0.1:{PORT}\r\n\r\n");
+ assert_eq!(classify(&req, PORT), Verdict::Reject);
+ }
+
+ #[test]
+ fn a_post_is_never_the_redirect() {
+ let req = format!("POST /callback?code=abc HTTP/1.1\r\nHost: 127.0.0.1:{PORT}\r\n\r\n");
+ assert_eq!(classify(&req, PORT), Verdict::Reject);
+ }
+
+ // ── strays that must not end the attempt either ─────────────────────
+
+ #[test]
+ fn preconnects_and_probes_are_rejected_without_a_query() {
+ for req in [
+ "",
+ "GET /favicon.ico HTTP/1.1\r\nHost: 127.0.0.1:17872\r\n\r\n",
+ "GET /callback HTTP/1.1\r\nHost: 127.0.0.1:17872\r\n\r\n",
+ ] {
+ assert_eq!(classify(req, PORT), Verdict::Reject);
+ }
+ }
+
+ #[test]
+ fn a_code_lookalike_parameter_is_not_a_code() {
+ // `?decode=1` used to satisfy the old "contains code=" test.
+ let req = format!("GET /callback?decode=1 HTTP/1.1\r\nHost: 127.0.0.1:{PORT}\r\n\r\n");
+ assert_eq!(classify(&req, PORT), Verdict::Reject);
+ }
+
+ #[test]
+ fn header_names_are_matched_case_insensitively() {
+ let req = format!(
+ "GET /callback?code=abc HTTP/1.1\r\nHOST: 127.0.0.1:{PORT}\r\nSEC-FETCH-DEST: Document\r\n\r\n"
+ );
+ assert_eq!(classify(&req, PORT), Verdict::Callback("code=abc".into()));
+ }
+}
diff --git a/src/api/cloud/__tests__/cloud-client.test.ts b/src/api/cloud/__tests__/cloud-client.test.ts
index eab83c59..dfe7be27 100644
--- a/src/api/cloud/__tests__/cloud-client.test.ts
+++ b/src/api/cloud/__tests__/cloud-client.test.ts
@@ -19,6 +19,21 @@ beforeEach(() => {
getAccessToken.mockResolvedValue('tok-123')
})
+/** A fetch that never answers on its own, and that ends the same way a real
+ * one does when its signal aborts — including a signal that was already
+ * aborted before the call. */
+function hangingFetch(onAbort?: () => void) {
+ return (_url: string, init: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ const stop = () => {
+ onAbort?.()
+ reject(new Error('aborted'))
+ }
+ if (init.signal?.aborted) stop()
+ else init.signal?.addEventListener('abort', stop, { once: true })
+ })
+}
+
function jsonRes(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
status,
@@ -45,6 +60,62 @@ describe('cloudFetch', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
+ it('gives up on a connection that never answers', async () => {
+ // The wedge this bounds: a half-open socket during an upload or a submit.
+ // fetch never settles on its own, every Create run awaits it, so the whole
+ // surface stayed frozen at "Submitting to the render queue…" until the app
+ // was restarted.
+ vi.useFakeTimers()
+ fetchMock.mockImplementation(hangingFetch())
+ const pending = cloudFetch('/api/jobs', { method: 'POST', body: '{"x":1}' })
+ const settled = pending.catch((e: unknown) => e)
+ await vi.advanceTimersByTimeAsync(120_000)
+ const err = await settled
+ expect(err).toBeInstanceOf(CloudJobError)
+ expect((err as CloudJobError).status).toBe(408)
+ vi.useRealTimers()
+ })
+
+ it('an upload gets a deadline that grows with the bytes it has to push', async () => {
+ // A flat ceiling would cut a legitimate large clip off on a slow uplink.
+ vi.useFakeTimers()
+ let aborted = false
+ fetchMock.mockImplementation(hangingFetch(() => { aborted = true }))
+ const big = new ArrayBuffer(40 * 1024 * 1024)
+ const settled = cloudFetch('/api/jobs/upload?role=video', { method: 'POST', body: big }).catch(
+ (e: unknown) => e,
+ )
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(aborted).toBe(false)
+ await vi.advanceTimersByTimeAsync(60 * 60_000)
+ expect(await settled).toBeInstanceOf(CloudJobError)
+ vi.useRealTimers()
+ })
+
+ it("hands the caller's abort signal through to the request", async () => {
+ // pollJob and generate() both hold an AbortController for the run; before
+ // this, cancelling could not reach a request already in flight.
+ const ac = new AbortController()
+ let seen: AbortSignal | undefined
+ fetchMock.mockImplementation((url: string, init: RequestInit) => {
+ seen = init.signal ?? undefined
+ return hangingFetch()(url, init)
+ })
+ const settled = cloudFetch('/api/me', { signal: ac.signal }).catch((e: unknown) => e)
+ ac.abort()
+ const err = await settled
+ expect(seen?.aborted).toBe(true)
+ // A cancelled run is not a timeout — it must not be relabelled as one.
+ expect(err).not.toBeInstanceOf(CloudJobError)
+ })
+
+ it('an already-aborted signal never reaches the network', async () => {
+ fetchMock.mockImplementation(hangingFetch())
+ const ac = new AbortController()
+ ac.abort()
+ await expect(cloudFetch('/api/me', { signal: ac.signal })).rejects.toThrow()
+ })
+
it('preserves method, body and extra headers', async () => {
fetchMock.mockResolvedValue(jsonRes({}))
await cloudFetch('/api/jobs', {
@@ -78,6 +149,37 @@ describe('jsonOrError', () => {
const err = await jsonOrError(res).catch((e: unknown) => e)
expect((err as CloudJobError).message).toBe('request failed (504)')
})
+
+ it('keeps the server code and retry-after, which a bare 429 cannot tell apart', async () => {
+ const res = new Response(JSON.stringify({ error: 'too many requests', code: 'rate_limited' }), {
+ status: 429,
+ headers: { 'content-type': 'application/json', 'retry-after': '30' },
+ })
+ const err = (await jsonOrError(res).catch((e: unknown) => e)) as CloudJobError
+ expect(err.code).toBe('rate_limited')
+ expect(err.retryAfterMs).toBe(30_000)
+ })
+
+ it('a 2xx whose body never finished arriving is an error, not an empty result', async () => {
+ // What a cut-off response looks like once cloudFetch's deadline aborts the
+ // read mid-body. Returning {} here handed submitCloudJob an undefined id
+ // and left the run polling a job that never existed.
+ const torn = new Response(
+ new ReadableStream({
+ start(c) {
+ c.enqueue(new TextEncoder().encode('{"id":"j1"'))
+ c.error(new Error('network closed'))
+ },
+ }),
+ { status: 200 },
+ )
+ await expect(jsonOrError(torn)).rejects.toThrow(/incomplete/)
+ })
+
+ it('but an empty 2xx body still resolves', async () => {
+ // A 204-style answer from a route that returns nothing is not a failure.
+ await expect(jsonOrError(new Response('', { status: 200 }))).resolves.toEqual({})
+ })
})
describe('jobs wrappers', () => {
diff --git a/src/api/cloud/__tests__/keychain-storage.test.ts b/src/api/cloud/__tests__/keychain-storage.test.ts
index e119155f..ed07f0d9 100644
--- a/src/api/cloud/__tests__/keychain-storage.test.ts
+++ b/src/api/cloud/__tests__/keychain-storage.test.ts
@@ -80,7 +80,8 @@ describe('a transient keychain failure must not latch', () => {
secretSet.mockRejectedValueOnce(new Error('user cancelled the unlock prompt'))
await store.setItem(SESSION, 'first')
- expect(localStorage.getItem(SESSION)).toBe('first')
+ expect(localStorage.getItem(SESSION)).not.toBeNull()
+ await expect(store.getItem(SESSION)).resolves.toBe('first')
secretSet.mockResolvedValue(undefined)
await store.setItem(SESSION, 'second')
@@ -97,7 +98,7 @@ describe('a transient keychain failure must not latch', () => {
await store.setItem(SESSION, 'second')
expect(secretSet.mock.calls.length).toBe(callsAfterFirst)
- expect(localStorage.getItem(SESSION)).toBe('second')
+ await expect(store.getItem(SESSION)).resolves.toBe('second')
})
it('prefers a localStorage fallback copy over the older keychain value', async () => {
@@ -153,3 +154,62 @@ describe('sign-out must not leave a resurrectable session', () => {
await expect(store.getItem(SESSION)).resolves.toBe('{"access_token":"abc"}')
})
})
+
+describe('the localStorage fallback is not a plaintext token dump', () => {
+ // Linux and the web build have no OS vault at all, so this IS the store
+ // there — and what it holds is a refresh token, a full account bearer until
+ // it is revoked. providerStore never puts an API key in localStorage in the
+ // clear on those same platforms; this used to.
+ const REFRESH_TOKEN = '{"refresh_token":"v1.MRefr3sh","access_token":"eyJhbGciOiJIUzI1NiJ9.x.y"}'
+
+ it('does not write the token where a reader of the profile can see it', async () => {
+ const store = await freshAdapter()
+ secretSet.mockRejectedValue(new Error('keychain unsupported on this platform'))
+
+ await store.setItem(SESSION, REFRESH_TOKEN)
+
+ const onDisk = localStorage.getItem(SESSION)!
+ expect(onDisk).not.toContain('v1.MRefr3sh')
+ expect(onDisk).not.toContain('refresh_token')
+ expect(onDisk).not.toContain('eyJ')
+ })
+
+ it('and reads it back unchanged, or the fallback would sign the user out', async () => {
+ const store = await freshAdapter()
+ secretSet.mockRejectedValue(new Error('keychain unsupported on this platform'))
+ secretGet.mockRejectedValue(new Error('keychain unsupported on this platform'))
+
+ await store.setItem(SESSION, REFRESH_TOKEN)
+ await expect(store.getItem(SESSION)).resolves.toBe(REFRESH_TOKEN)
+ })
+
+ it('survives non-ASCII in the session (a display name blows up naive base64)', async () => {
+ const store = await freshAdapter()
+ secretSet.mockRejectedValue(new Error('keychain unsupported on this platform'))
+ const withUmlaut = '{"user":{"name":"Jürgen 🦀"},"refresh_token":"abc"}'
+
+ await store.setItem(SESSION, withUmlaut)
+ await expect(store.getItem(SESSION)).resolves.toBe(withUmlaut)
+ })
+
+ it('still reads a session written by an older build', async () => {
+ // Those are plain JSON with no marker. Rejecting them would sign every
+ // Linux user out on update.
+ const store = await freshAdapter()
+ secretGet.mockRejectedValue(new Error('keychain unsupported on this platform'))
+ localStorage.setItem(SESSION, REFRESH_TOKEN)
+
+ await expect(store.getItem(SESSION)).resolves.toBe(REFRESH_TOKEN)
+ })
+
+ it('sign-out still empties the fallback', async () => {
+ const store = await freshAdapter()
+ secretSet.mockRejectedValue(new Error('keychain unsupported on this platform'))
+
+ await store.setItem(SESSION, REFRESH_TOKEN)
+ await store.removeItem(SESSION)
+
+ expect(localStorage.getItem(SESSION)).toBeNull()
+ await expect(store.getItem(SESSION)).resolves.toBeNull()
+ })
+})
diff --git a/src/api/cloud/__tests__/oauth-callback-text.test.ts b/src/api/cloud/__tests__/oauth-callback-text.test.ts
new file mode 100644
index 00000000..70fef7c4
--- /dev/null
+++ b/src/api/cloud/__tests__/oauth-callback-text.test.ts
@@ -0,0 +1,81 @@
+/**
+ * What the OAuth loopback query is allowed to put in front of the user
+ * (src/api/cloud/supabase.ts, loginWithProvider).
+ *
+ * The query comes off a 127.0.0.1 socket. commands/oauth.rs now only serves a
+ * genuine top-level callback navigation, so this text is the provider's — but
+ * `error_description` is still free-form remote input, and it used to be piped
+ * into an error line verbatim, at any length, with any control characters in
+ * it. Defence in depth for the half of the pair that lives in the frontend.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const oauthStart = vi.fn()
+const oauthWait = vi.fn()
+const openExternal = vi.fn()
+
+vi.mock('../../backend', () => ({
+ secretGet: vi.fn(),
+ secretSet: vi.fn(),
+ secretDelete: vi.fn(),
+ oauthStart: (...a: unknown[]) => oauthStart(...a),
+ oauthWait: (...a: unknown[]) => oauthWait(...a),
+ openExternal: (...a: unknown[]) => openExternal(...a),
+}))
+vi.mock('../config', () => ({ SUPABASE_URL: 'https://x.test', SUPABASE_ANON_KEY: 'anon' }))
+
+const exchangeCodeForSession = vi.fn()
+vi.mock('@supabase/supabase-js', () => ({
+ createClient: () => ({
+ auth: {
+ signInWithOAuth: async () => ({ data: { url: 'https://accounts.google.test/o' }, error: null }),
+ exchangeCodeForSession,
+ },
+ }),
+}))
+
+import { loginWithProvider } from '../supabase'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ oauthStart.mockResolvedValue(17872)
+ openExternal.mockResolvedValue(undefined)
+ exchangeCodeForSession.mockResolvedValue({ error: null })
+})
+
+describe('a real callback still works', () => {
+ it('exchanges the code', async () => {
+ oauthWait.mockResolvedValue('code=abc123')
+ await expect(loginWithProvider('google')).resolves.toBeUndefined()
+ expect(exchangeCodeForSession).toHaveBeenCalledWith('abc123')
+ })
+
+ it('shows the provider its own refusal', async () => {
+ oauthWait.mockResolvedValue('error=access_denied&error_description=You+denied+the+request')
+ await expect(loginWithProvider('github')).rejects.toThrow('You denied the request')
+ })
+})
+
+describe('remote text does not get a free hand in the UI', () => {
+ it('cuts a flood down to a line', async () => {
+ oauthWait.mockResolvedValue(`error=x&error_description=${'A'.repeat(5000)}`)
+ const err = await loginWithProvider('google').catch((e: Error) => e)
+ expect((err as Error).message.length).toBeLessThanOrEqual(200)
+ })
+
+ it('strips the control characters that fake a second message', async () => {
+ oauthWait.mockResolvedValue(
+ `error=x&error_description=${encodeURIComponent('Session expired.\n\nEnter your password at evil.example')}`,
+ )
+ const msg = await loginWithProvider('google').catch((e: Error) => e.message)
+ // One line: remote text must not be able to lay itself out as a second
+ // paragraph that reads like it came from LU.
+ expect(msg).not.toContain('\n')
+ expect(msg).not.toContain('\r')
+ })
+
+ it('falls back to a sentence of our own when the query says nothing', async () => {
+ oauthWait.mockResolvedValue('state=abc')
+ await expect(loginWithProvider('google')).rejects.toThrow(/cancelled in the browser/)
+ })
+})
diff --git a/src/api/cloud/client.ts b/src/api/cloud/client.ts
index 036cc3cf..c97b34b4 100644
--- a/src/api/cloud/client.ts
+++ b/src/api/cloud/client.ts
@@ -5,32 +5,128 @@
import { CLOUD_BASE } from './config'
import { getAccessToken } from './supabase'
+import { parseRetryAfter } from '../../lib/http-status'
export class CloudJobError extends Error {
readonly status: number
- constructor(message: string, status: number) {
+ /** The server's machine-readable reason (`code` next to `error` in the
+ * body), when it sent one. The status alone is ambiguous where it matters
+ * most: LU Cloud answers 429 for the per-user burst guard, for an upstream
+ * provider throttle AND for an empty wallet, and only the last of those is
+ * something the user can act on by paying. */
+ readonly code?: string
+ /** What `retry-after` asked for, in ms — the burst guard's window is fixed
+ * and up to a minute long, so the number is worth showing. */
+ readonly retryAfterMs?: number
+ constructor(message: string, status: number, meta?: { code?: string; retryAfterMs?: number }) {
super(message)
this.name = 'CloudJobError'
this.status = status
+ this.code = meta?.code
+ this.retryAfterMs = meta?.retryAfterMs
}
}
export async function jsonOrError<T>(res: Response): Promise<T> {
- const body = await res.json().catch(() => ({}))
+ // Read as text rather than json() so a body that never finished arriving is
+ // distinguishable from one that legitimately has nothing in it. A torn read
+ // used to fall into the same `{}` as a 204, which handed submitCloudJob an
+ // undefined job id and left the run polling a job that never existed.
+ let truncated = false
+ const raw = await res.text().catch(() => {
+ truncated = true
+ return ''
+ })
+ let body: unknown = {}
+ let unparseable = false
+ if (raw.trim()) {
+ try {
+ body = JSON.parse(raw)
+ } catch {
+ unparseable = true
+ }
+ }
if (!res.ok) {
- const msg =
- typeof (body as { error?: unknown }).error === 'string'
- ? (body as { error: string }).error
- : `request failed (${res.status})`
- throw new CloudJobError(msg, res.status)
+ const b = body as { error?: unknown; code?: unknown }
+ const msg = typeof b.error === 'string' ? b.error : `request failed (${res.status})`
+ throw new CloudJobError(msg, res.status, {
+ code: typeof b.code === 'string' ? b.code : undefined,
+ retryAfterMs: parseRetryAfter(res),
+ })
+ }
+ if (truncated || unparseable) {
+ throw new CloudJobError(`the server's answer arrived incomplete (${res.status})`, res.status)
}
return body as T
}
-export async function cloudFetch(path: string, init: RequestInit = {}): Promise<Response> {
+/** Ceiling for one cloud round-trip. Nothing else bounds these: the Create
+ * surface awaits them one after another, and a fetch whose peer disappears
+ * mid-flight never settles on its own — one half-open socket during an
+ * upload or a submit therefore wedged Create until the app was restarted. */
+const REQUEST_TIMEOUT_MS = 60_000
+
+/** Uploads have to survive a slow uplink, so their deadline grows with the
+ * body instead of cutting a legitimate 40 MB clip off at the flat ceiling.
+ * ~64 KB/s is far below any connection that could ever finish the upload. */
+const UPLOAD_BYTES_PER_MS = 64
+
+function deadlineFor(init: RequestInit): number {
+ const body = init.body
+ const bytes =
+ body instanceof ArrayBuffer
+ ? body.byteLength
+ : ArrayBuffer.isView(body)
+ ? body.byteLength
+ : typeof Blob !== 'undefined' && body instanceof Blob
+ ? body.size
+ : typeof body === 'string'
+ ? body.length
+ : 0
+ return REQUEST_TIMEOUT_MS + Math.ceil(bytes / UPLOAD_BYTES_PER_MS)
+}
+
+export interface CloudFetchInit extends RequestInit {
+ /** Overrides the size-derived deadline for this one request. */
+ timeoutMs?: number
+}
+
+export async function cloudFetch(path: string, init: CloudFetchInit = {}): Promise<Response> {
const token = await getAccessToken()
if (!token) throw new CloudJobError('not signed in', 401)
const headers = new Headers(init.headers)
headers.set('authorization', `Bearer ${token}`)
- return fetch(`${CLOUD_BASE}${path}`, { ...init, headers })
+
+ const { timeoutMs, signal, ...rest } = init
+ // Two things must be able to end this request — the caller's signal (a
+ // cancelled run) and the deadline — and fetch takes one. AbortSignal.any
+ // would merge them, but it is newer than the WKWebView LU runs inside on
+ // older macOS, so the relay is wired by hand.
+ const ac = new AbortController()
+ const relay = () => ac.abort(signal?.reason)
+ if (signal) {
+ if (signal.aborted) relay()
+ else signal.addEventListener('abort', relay, { once: true })
+ }
+ let timedOut = false
+ const timer = setTimeout(() => {
+ timedOut = true
+ ac.abort()
+ }, timeoutMs ?? deadlineFor(init))
+ try {
+ return await fetch(`${CLOUD_BASE}${path}`, { ...rest, headers, signal: ac.signal })
+ } catch (err) {
+ // Engines disagree on whether a fetch rejects with the abort *reason*, so
+ // the deadline is remembered here instead of read back off the signal.
+ // 408 keeps pollJob's policy intact — a timeout is worth another try.
+ if (timedOut) throw new CloudJobError('the cloud did not answer in time', 408)
+ throw err
+ } finally {
+ // The deadline covers what this function owns: connect, request body,
+ // response headers — which is where the observed wedge lived (an upload
+ // or a submit that never came back). Reading the response body is the
+ // caller's half; jsonOrError reports a torn read rather than hanging.
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', relay)
+ }
}
diff --git a/src/api/cloud/supabase.ts b/src/api/cloud/supabase.ts
index ee73ecc7..795ab20c 100644
--- a/src/api/cloud/supabase.ts
+++ b/src/api/cloud/supabase.ts
@@ -6,7 +6,9 @@
// Session storage: OS keychain via the existing Rust `secret_*` commands
// (Windows Credential Manager / macOS Keychain) — survives the NSIS-update
// WebView2 wipe and keeps refresh tokens out of localStorage. Linux and the
-// browser dev build fall back to localStorage (same tiering as providerStore).
+// browser dev build have no vault to use (secret.rs is a stub there) and fall
+// back to localStorage under the same obfuscation providerStore gives API
+// keys — see FALLBACK_MARKER for what that is and is not worth.
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
import { secretGet, secretSet, secretDelete, oauthStart, oauthWait, openExternal } from '../backend'
@@ -42,6 +44,51 @@ function keychainAccount(key: string): string {
// physically, but must never sign anyone back in. getItem reports it as absent.
const TOMBSTONE = '__lu_signed_out__'
+// ── localStorage fallback encoding ──────────────────────────────────────
+// Everything the keychain path does not take ends up here: Linux and the
+// browser dev build have no OS vault at all (commands/secret.rs compiles to an
+// "unsupported" stub there), and any keychain write that fails falls back for
+// that one call. What lands is the Supabase session — a refresh token that is
+// a full account bearer until it is revoked — and it used to be written
+// verbatim, so on Linux it sat greppable in WebKitGTK's profile directory
+// while providerStore's API keys on the very same platforms never do (those
+// are stored reversed + base64). This closes that gap: same platforms, same
+// treatment.
+//
+// It is obfuscation, NOT encryption. There is no key this app could hold that
+// a reader of the profile directory could not take as well, so it only stops
+// the token from being legible at a glance — a backup, a synced profile
+// folder, a support screenshot, another process grepping for `eyJ`. The real
+// store remains the OS vault, and a secret store for Linux is a Rust-side
+// change, not one this adapter can make.
+const FALLBACK_MARKER = 'lu.obf.1:'
+
+function packFallback(value: string): string {
+ try {
+ return FALLBACK_MARKER + btoa(encodeURIComponent(value))
+ } catch {
+ // Dropping the session here would sign the user out on the next launch for
+ // no reason at all, which is the worse failure of the two.
+ return value
+ }
+}
+
+function unpackFallback(stored: string): string {
+ // No marker = written by a build before this encoding existed. Those must
+ // keep working, or an update signs every Linux user out.
+ if (!stored.startsWith(FALLBACK_MARKER)) return stored
+ try {
+ return decodeURIComponent(atob(stored.slice(FALLBACK_MARKER.length)))
+ } catch {
+ return stored
+ }
+}
+
+function fallbackGet(key: string): string | null {
+ const raw = localStorage.getItem(key)
+ return raw === null ? null : unpackFallback(raw)
+}
+
/** 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 = {
@@ -55,13 +102,13 @@ export 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.
- value = localStorage.getItem(key) ?? fromKeychain
+ value = fallbackGet(key) ?? fromKeychain
} catch (err) {
if (keychainMissing(err)) keychainBroken = true
- value = localStorage.getItem(key)
+ value = fallbackGet(key)
}
} else {
- value = localStorage.getItem(key)
+ value = fallbackGet(key)
}
return value === TOMBSTONE ? null : value
},
@@ -77,7 +124,7 @@ export const keychainStorage = {
if (keychainMissing(err)) keychainBroken = true
}
}
- localStorage.setItem(key, value)
+ localStorage.setItem(key, packFallback(value))
},
async removeItem(key: string): Promise<void> {
// Always clear the fallback copy too — sign-out must never leave a
@@ -150,6 +197,17 @@ export async function getAccessToken(): Promise<string | null> {
export type OAuthProvider = 'google' | 'github'
+/** The loopback callback is the one place in sign-in where text from outside
+ * the app reaches the UI. commands/oauth.rs now only serves a genuine
+ * top-level callback navigation, so this text comes from the provider — but
+ * `error_description` is still free-form remote input, and an error line is
+ * no place for a screenful of it. Control characters out, 200 chars max. */
+function providerErrorText(params: URLSearchParams): string {
+ const raw = params.get('error_description') || params.get('error') || ''
+ const clean = raw.replace(/\p{C}/gu, ' ').replace(/\s+/g, ' ').trim().slice(0, 200)
+ return clean || 'Sign-in was cancelled in the browser.'
+}
+
/** Google/GitHub sign-in, same identities as lu-labs.ai. Flow: bind a
* 127.0.0.1 loopback port (Rust, fixed ladder registered in the Supabase
* redirect allow-list) → open the provider consent in the SYSTEM browser →
@@ -184,7 +242,7 @@ export async function loginWithProvider(provider: OAuthProvider, signal?: AbortS
const params = new URLSearchParams(query)
const code = params.get('code')
if (!code) {
- throw new Error(params.get('error_description') || params.get('error') || 'Sign-in was cancelled in the browser.')
+ throw new Error(providerErrorText(params))
}
const { error: exchangeError } = await supabaseCloud().auth.exchangeCodeForSession(code)
if (exchangeError) throw new Error(exchangeError.message)
diff --git a/src/hooks/__tests__/a-429-is-not-always-money.test.ts b/src/hooks/__tests__/a-429-is-not-always-money.test.ts
new file mode 100644
index 00000000..c6e71001
--- /dev/null
+++ b/src/hooks/__tests__/a-429-is-not-always-money.test.ts
@@ -0,0 +1,71 @@
+/**
+ * What Create says when the render queue answers 429 (src/hooks/useCloudCreate.ts).
+ *
+ * LU Cloud answers 429 for three different things — the per-user burst guard,
+ * an upstream provider throttle, and an empty wallet (lib/http-status carries
+ * the same policy for the chat path). All three used to reach the user as
+ * "Monthly credit budget exhausted, upgrade your plan", so a subscriber who
+ * had simply clicked twice too fast was told to buy a bigger plan while the
+ * credits meter next to the message still showed a balance. On a billed
+ * product that is a false sales pitch, so the wallet case has to be identified
+ * rather than assumed.
+ */
+import { describe, it, expect } from 'vitest'
+import { throttleMessage } from '../useCloudCreate'
+import { CloudJobError } from '../../api/cloud/client'
+
+const UPGRADE = /upgrade your plan/
+
+describe('the wallet case, and only the wallet case, mentions the plan', () => {
+ it('trusts the server code', () => {
+ const err = new CloudJobError('too many requests', 429, { code: 'credits_exhausted' })
+ expect(throttleMessage(err)).toMatch(UPGRADE)
+ })
+
+ it('and the message the server sends today, in case the code is absent', () => {
+ expect(throttleMessage(new CloudJobError('monthly credit budget exhausted', 429))).toMatch(UPGRADE)
+ })
+})
+
+describe('a throttle is named as a throttle', () => {
+ it('says wait, not pay, for the per-user burst guard', () => {
+ const err = new CloudJobError('too many requests', 429, { retryAfterMs: 42_000 })
+ const msg = throttleMessage(err)
+ expect(msg).not.toMatch(UPGRADE)
+ expect(msg).toMatch(/not your credit balance/)
+ // The burst window is fixed and up to a minute long — retry-after is the
+ // only number that tells the user when it is actually worth clicking.
+ expect(msg).toContain('42s')
+ })
+
+ it('says the same without a retry-after header', () => {
+ const err = new CloudJobError('provider is rate limiting', 429)
+ const msg = throttleMessage(err)
+ expect(msg).not.toMatch(UPGRADE)
+ expect(msg).toMatch(/try again/i)
+ })
+
+ it('does not invent a countdown from a missing or zero wait', () => {
+ for (const meta of [undefined, { retryAfterMs: 0 }]) {
+ expect(throttleMessage(new CloudJobError('slow down', 429, meta))).not.toMatch(/\d+s\b/)
+ }
+ })
+
+ it('rounds a sub-second wait up rather than telling the user 0s', () => {
+ expect(throttleMessage(new CloudJobError('slow down', 429, { retryAfterMs: 250 }))).toContain('1s')
+ })
+})
+
+describe('the metadata the message needs actually survives the client', () => {
+ it('jsonOrError carries code and retry-after off the response', async () => {
+ const { jsonOrError } = await import('../../api/cloud/client')
+ const res = new Response(JSON.stringify({ error: 'too many requests', code: 'rate_limited' }), {
+ status: 429,
+ headers: { 'content-type': 'application/json', 'retry-after': '30' },
+ })
+ const err = (await jsonOrError(res).catch((e: unknown) => e)) as CloudJobError
+ expect(err.code).toBe('rate_limited')
+ expect(err.retryAfterMs).toBe(30_000)
+ expect(throttleMessage(err)).toContain('30s')
+ })
+})
diff --git a/src/hooks/__tests__/signing-out-must-not-lie.test.ts b/src/hooks/__tests__/signing-out-must-not-lie.test.ts
new file mode 100644
index 00000000..cd9f848a
--- /dev/null
+++ b/src/hooks/__tests__/signing-out-must-not-lie.test.ts
@@ -0,0 +1,110 @@
+/**
+ * Sign-out (src/hooks/useCloudAuth.ts).
+ *
+ * The keychain adapter throws on purpose when a delete fails and the stored
+ * session survives (api/cloud/supabase.ts, "Signed out, but the saved session
+ * could not be removed"). That throw was swallowed and the store was flipped
+ * to signed-out regardless, so the app said "signed out" while a valid refresh
+ * token stayed in the OS vault — and the 5-minute probe signed the account
+ * back in. On a shared or handed-over machine that is the whole account.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const signOut = vi.fn()
+const getSession = vi.fn()
+
+vi.mock('../../api/cloud/supabase', () => ({
+ supabaseCloud: () => ({ auth: { signOut, getSession } }),
+}))
+vi.mock('../../api/cloud/jobs', () => ({ getMe: vi.fn(), getQuota: vi.fn() }))
+vi.mock('../../stores/cloudCatalogStore', () => ({ refreshCatalog: vi.fn() }))
+vi.mock('../../stores/providerStore', () => ({
+ useProviderStore: { getState: () => ({ providers: {}, setProviderConfig: vi.fn() }) },
+}))
+vi.mock('../../stores/settingsStore', () => ({
+ useSettingsStore: { getState: () => ({ settings: { appMode: 'local' }, updateSettings: vi.fn() }) },
+}))
+
+import { signOutAccount } from '../useCloudAuth'
+import { useCloudAuthStore } from '../../stores/cloudAuthStore'
+
+const SESSION = { access_token: 'still-valid', refresh_token: 'r' }
+
+function signedIn() {
+ useCloudAuthStore
+ .getState()
+ .setSignedIn({ id: 'u1', email: '[email protected]' }, { licenseActive: true, tier: 'hosted', access: true, quota: null })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal('window', { dispatchEvent: vi.fn(), CustomEvent })
+ signedIn()
+})
+
+describe('a sign-out that worked', () => {
+ it('clears the account state', async () => {
+ signOut.mockResolvedValue({ error: null })
+
+ await expect(signOutAccount()).resolves.toBeUndefined()
+
+ expect(useCloudAuthStore.getState().status).toBe('signed-out')
+ expect(useCloudAuthStore.getState().user).toBeNull()
+ // No reason to interrogate the storage when nothing went wrong.
+ expect(getSession).not.toHaveBeenCalled()
+ })
+})
+
+describe('a sign-out that did not happen', () => {
+ it('reports the keychain failure instead of swallowing it', async () => {
+ // Exactly what keychainStorage.removeItem throws when the OS vault is
+ // there and the delete failed anyway (locked at wake, dismissed prompt).
+ signOut.mockRejectedValue(new Error('Signed out, but the saved session could not be removed from the keychain.'))
+ getSession.mockResolvedValue({ data: { session: SESSION }, error: null })
+
+ await expect(signOutAccount()).rejects.toThrow(/still on this computer/)
+ })
+
+ it('does not claim the account is signed out while the token is still there', async () => {
+ signOut.mockRejectedValue(new Error('The stub received bad data.'))
+ getSession.mockResolvedValue({ data: { session: SESSION }, error: null })
+
+ await signOutAccount().catch(() => {})
+
+ // The panel must keep showing the account, because the account IS still
+ // usable here. Saying "signed out" over a live session is what let the
+ // next person at this machine spend the credits.
+ expect(useCloudAuthStore.getState().status).toBe('signed-in')
+ expect(useCloudAuthStore.getState().user?.id).toBe('u1')
+ })
+
+ it('treats an unreadable session as still there', async () => {
+ signOut.mockRejectedValue(new Error('boom'))
+ getSession.mockRejectedValue(new Error('keychain locked'))
+
+ await expect(signOutAccount()).rejects.toThrow(/still on this computer/)
+ expect(useCloudAuthStore.getState().status).toBe('signed-in')
+ })
+})
+
+describe('a failure that still emptied this machine', () => {
+ it('completes the sign-out when the tombstone landed', async () => {
+ // removeItem could not delete the entry but did overwrite it, so getItem
+ // reports the session as absent — this machine is clean.
+ signOut.mockRejectedValue(new Error('Signed out, but the saved session could not be removed from the keychain.'))
+ getSession.mockResolvedValue({ data: { session: null }, error: null })
+
+ await expect(signOutAccount()).resolves.toBeUndefined()
+ expect(useCloudAuthStore.getState().status).toBe('signed-out')
+ })
+
+ it('completes when only the server-side revoke failed', async () => {
+ // supabase-js clears the local session before returning that error, so
+ // there is nothing left here to sign anyone back in.
+ signOut.mockResolvedValue({ error: { message: 'Failed to fetch' } })
+ getSession.mockResolvedValue({ data: { session: null }, error: null })
+
+ await expect(signOutAccount()).resolves.toBeUndefined()
+ expect(useCloudAuthStore.getState().status).toBe('signed-out')
+ })
+})
diff --git a/src/hooks/useCloudAuth.ts b/src/hooks/useCloudAuth.ts
index a11a6251..93d3fd9e 100644
--- a/src/hooks/useCloudAuth.ts
+++ b/src/hooks/useCloudAuth.ts
@@ -110,6 +110,55 @@ function syncChatProvider(): void {
}
}
+/** Signs out, or throws saying it could not.
+ *
+ * The keychain adapter (api/cloud/supabase.ts) throws on purpose when a
+ * delete fails and the stored session survives — supabase-js does not wrap
+ * storage errors, so that throw comes straight back out of signOut(). It used
+ * to be swallowed by a `.catch(() => {})` and the store was flipped to
+ * signed-out anyway, which is the worst combination available: the user is
+ * told they are signed out, a valid refresh token is still in the system
+ * vault, and the 5-minute probe signs the account back in without a word.
+ * Whoever hands over a shared or company machine on the strength of that
+ * message hands over the account with it.
+ *
+ * Module-level (and exported) so the sign-out contract can be tested without
+ * rendering the hook. */
+export async function signOutAccount(): Promise<void> {
+ // Invalidate any in-flight probe — its request carried the old (still
+ // unexpired) access token and would resurrect the signed-in state.
+ probeGen++
+ const auth = supabaseCloud().auth
+ let failure: string | null = null
+ try {
+ const { error } = await auth.signOut()
+ if (error) failure = error.message
+ } catch (err) {
+ failure = err instanceof Error ? err.message : String(err)
+ }
+ if (failure) {
+ // Ask the storage rather than trusting the failure. A delete that failed
+ // but left the tombstone behind IS a completed sign-out, and so is a failed
+ // server-side revoke (supabase-js clears the local session before it
+ // returns that error). Only a session that still reads back means the
+ // refresh token is still on this machine.
+ const survived = await auth
+ .getSession()
+ .then((r) => Boolean(r.data.session))
+ .catch(() => true)
+ if (survived) {
+ // Leave the store signed in: the account really is still usable here, and
+ // a "signed out" panel over a live session is the dangerous half of this.
+ throw new Error(
+ `Sign-out failed — the saved session is still on this computer, so the account stays signed in here. ${failure}`,
+ )
+ }
+ }
+ useCloudAuthStore.getState().setSignedOut()
+ syncChatProvider()
+ syncAppMode()
+}
+
export function useCloudAuth() {
const status = useCloudAuthStore((s) => s.status)
const user = useCloudAuthStore((s) => s.user)
@@ -139,15 +188,7 @@ export function useCloudAuth() {
await probeAccount()
}, [])
- const logout = useCallback(async (): Promise<void> => {
- // Invalidate any in-flight probe — its request carried the old (still
- // unexpired) access token and would resurrect the signed-in state.
- probeGen++
- await supabaseCloud().auth.signOut().catch(() => {})
- useCloudAuthStore.getState().setSignedOut()
- syncChatProvider()
- syncAppMode()
- }, [])
+ const logout = useCallback((): Promise<void> => signOutAccount(), [])
const refresh = useCallback(async (): Promise<void> => {
await probeAccount()
diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.ts
index 47a668d1..2cfe2859 100644
--- a/src/hooks/useCloudCreate.ts
+++ b/src/hooks/useCloudCreate.ts
@@ -65,6 +65,28 @@ function opProgressVerb(op: string): string {
}
}
+// What a 429 from the render queue actually means.
+//
+// The queue answers 429 for three different things (lib/http-status states the
+// same policy for the chat path): the per-user burst guard, an upstream
+// provider throttle — both transient, both carrying retry-after — and an empty
+// wallet, which is the only one paying more fixes. Every one of them used to
+// read "Monthly credit budget exhausted, upgrade your plan", so a subscriber
+// who was merely clicking too fast, with credits left in the meter next to the
+// message, was told to buy a bigger plan. That is a sales pitch for a refusal
+// the money would not have prevented, so the wallet case has to be positively
+// identified — by the server's own `code`, or failing that by a message that
+// actually talks about credits — and everything else says what it is.
+export function throttleMessage(err: CloudJobError): string {
+ if (err.code === 'credits_exhausted' || /credit/i.test(err.message)) {
+ return 'Monthly credit budget exhausted, upgrade your plan or wait for the next period.'
+ }
+ const secs = err.retryAfterMs && err.retryAfterMs > 0 ? Math.ceil(err.retryAfterMs / 1000) : null
+ return secs
+ ? `Too many requests right now — the render queue is throttling, not your credit balance. Try again in ${secs}s.`
+ : 'Too many requests right now — the render queue is throttling, not your credit balance. Give it a moment and try again.'
+}
+
// Decoded by hand instead of fetch(dataUrl): the webview CSP's connect-src
// (rightly) has no data: entry, so fetching a data URL throws "Load failed"
// and killed every source-needing op before the upload even started.
@@ -380,7 +402,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
} catch (err) {
const st = useCreateStore.getState()
if (err instanceof CloudJobError && err.status === 429) {
- st.setError('Monthly credit budget exhausted, upgrade your plan or wait for the next period.')
+ st.setError(throttleMessage(err))
} else if (err instanceof CloudJobError && err.status === 401) {
st.setError('Sign in to your LU Cloud account to render in the cloud.')
} else if (err instanceof CloudJobError && err.message === 'render timed out') {
@@ -497,7 +519,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
} catch (err) {
const st = useCreateStore.getState()
if (err instanceof CloudJobError && err.status === 429) {
- st.setError('Monthly credit budget exhausted, upgrade your plan or wait for the next period.')
+ st.setError(throttleMessage(err))
} else if (!(err instanceof CloudJobError && err.message === 'polling aborted')) {
st.setError(err instanceof Error ? err.message : String(err))
}
@@ -589,7 +611,7 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {
} catch (err) {
const st = useCreateStore.getState()
if (err instanceof CloudJobError && err.status === 429) {
- st.setError('Monthly credit budget exhausted, upgrade your plan or wait for the next period.')
+ st.setError(throttleMessage(err))
} else if (!(err instanceof CloudJobError && err.message === 'polling aborted')) {
st.setError(err instanceof Error ? err.message : String(err))
}