Repository navigation
Unsloth Studio: keep tabs signed in on plain-HTTP origins when two refresh at once - #16755
Conversation
… once Web Locks only exist in secure contexts, so on http://<lan-ip>:<port> two tabs can spend the same single-use refresh token. The loser's 401 used to clear the shared tokens (every tab signed out) or, if the winner had already stored its pair, redirect to /login and bounce back to a new chat. Without locks, a 401 now waits briefly for a peer's rotation to land before treating the session as rejected.
A sign-in or account switch in another tab during the wait also replaces the refresh token; it must end the refresh, not be retried as this session.
Two plain-HTTP tabs refreshing a session that had no mark can each mint one; the tab whose write lost would read the peer's rotation as a session switch.
|
Codex on the fork mirror: Didn't find any major issues at |
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: fed622193e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| const currentMark = getAuthSessionMark(); | ||
| mark ??= currentMark; |
There was a problem hiding this comment.
Preserve the logout boundary for legacy refreshes
Without Web Locks, if a legacy session starts with no mark and another tab logs out and signs back in before the refresh's 401 arrives, peerSessionMark is null and this assignment adopts the new sign-in's mark. Its refresh token also differs, so peerRotated returns true and authFetch replays the pre-logout request, including mutations such as saveChatSettingsPatch, under the new session. Same-account sign-ins do not set the account-switch fence or reload peer tabs, so accountTransitionPending() does not prevent this. Preserve a boundary from refresh start that distinguishes initial marker backfill from a completed logout/sign-in.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 43bf2b3: the peer wait now runs only when a session mark existed at refresh start, so a logout and sign-in can never be taken for a peer's rotation; a session with no mark keeps the old reject path until its first refresh backfills one.
…refresh start [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…tores window (#17055) ## Summary Since #16755 merged, every `Frontend CI` run fails on both `Frontend build + bundle sanity` and `Frontend unit tests (Windows)`, with the same file. On PRs this includes #17010 and the cosmos3, images and voice PRs, and the main push runs are red too: ``` # Error: Test "without Web Locks a session with no mark does not take a later sign-in for a peer's rotation" at tests/auth-refresh-transient.test.ts:453:1 generated asynchronous activity after the test ended. This activity created the error "TypeError: Cannot read properties of undefined (reading 'location')" and would have caused the test to fail, but instead triggered an unhandledRejection event. not ok 140 - tests/auth-refresh-transient.test.ts ``` The product code is correct; the test does not wait for it. In the new test, `authFetch` returns the 401, and the rejected-refresh path then sends the tab to `/login` through `window.location` on a later turn. The test ends right after the returned response. The fixture's `t.after` then restores the real `globalThis.window`, which is `undefined` under Node, so the deferred redirect throws. The sibling tests that take a 401 already `await f.settle()` before they finish. This one does not. The failure depends on the Node version. CI pins Node 22 (`22.23.4`), which fails the file every time. Node 24 does not, which is why the PR was green where it was written. ## Change `studio/frontend/tests/auth-refresh-transient.test.ts`, tests only: - The fixture's `t.after` drains five turns before it restores `window`, `fetch`, `setTimeout`, `clearTimeout` and `Date.now`. That is the same drain as `f.settle()`. Deferred work from any test in the file now runs against the fixture's window, not after it is gone. - The new test settles and asserts what the rejected path does, `location.href == "/login"`. It also keeps its existing checks: the other sign-in's tokens stay and nothing is cleared. ## Testing | | Node 22.23.4 (CI) | Node 24.22.1 | |---|---|---| | main | file fails (`# pass 23`, `# fail 1`, the error above) | 23 pass | | this branch | 23 pass | 23 pass | | this branch, fixture drain alone (new assertion removed) | 23 pass | |
…thai#18353) Every open Unsloth Studio tab could still sign out at once when the answer to a successful session refresh never reached the browser. With this change the session survives that. ## What was wrong Refresh tokens are single-use. When `/api/auth/refresh` rotates a token, the server deletes the old one and returns a new pair. If that answer is lost on the way back, the browser keeps the old token, which is already gone on the server: - a tab is closed or reloaded while the refresh is in flight - a reverse proxy times out the request after the server committed - a phone or tablet suspends the page mid-request The next refresh sends the spent token, gets a 401, and the client clears the tokens in shared storage. That signs out every tab on that browser. unslothai#16468 (Web Locks) and unslothai#16755 (plain-HTTP peer wait) fixed the two-tab race reported on Discord. This lost-answer case is the one path that still ends the session. ## The fix A token rotated by `/api/auth/refresh` stays exchangeable for 60 seconds (`REFRESH_REUSE_GRACE_SECONDS`). Presenting it again in that window rotates once more and returns a fresh pair instead of a 401. This makes a retried refresh idempotent, the same idea as Supabase's refresh token reuse interval and Okta's grace period. - **Revocation is unchanged.** Logout, password changes, account revokes and renames delete the grace rows in the same transaction as the live tokens. All five call sites go through one helper, `_delete_refresh_rows`. A password change is also caught by the existing credential generation check. - **Downgrade safe.** The grace rows live in a new `refresh_token_reuse` table, and the spent token is still deleted from `refresh_tokens`. An older build never reads the new table, so it cannot revive a spent token. - **Bounded.** One spent token mints at most `REFRESH_REUSE_MAX` (8) pairs inside the window; later replays get a 401, which the client already answers from a peer's stored pair. - **Only stamped tokens get the window.** A token without a credential generation stamp (legacy rows from before that column existed) stays strictly single-use, so every reuse row is voided by any credential change, including the CLI password reset that rotates the secret with its own SQL. - **Scope.** Only the rotation path opts in. `consume_refresh_token` stays strictly single-use, and expired rows and rows older than the window are purged on every rotation. - **Frontend.** Without Web Locks (plain HTTP), two tabs racing on one token now both get a 200. A tab whose own 200 lands after a peer already stored a pair now reuses the peer's pair through the existing `peerRotated` check, as the 401 path already did, instead of handing its caller the original 401. No new UI: the only visible change is that the tabs stay signed in. Desktop, which runs on a secure origin with Web Locks, follows the same path as before. ## Tests | check | merge base | this PR | |---|---|---| | retry after a lost rotation answer | `401 Invalid or expired refresh token` | `200`, new pair works | | two tabs racing on one token | first 200, second 401 | both 200 | | spent token after the window ends | 401 | 401 | | logout, password change or CLI reset inside the window | 401 | 401 | | legacy unstamped token reused | 401 | 401 | | one spent token replayed 10 times in the window | 401 | 8 pairs, then 401 | | `tests/test_refresh_reuse_grace.py` (11) | 3 fail, 8 pass | 11 pass | | `tests/auth-refresh-transient.test.ts` | 23 pass, 2 fail | 25 pass | | backend auth suites (11 files, 387 tests) | 1 fail | same 1 fail | | full frontend `node --test` (16,708 tests) | same 2 new tests fail | 0 fail | | frontend typecheck | | pass | - The one backend failure on both sides, `test_health_response_reports_desktop_capability_fields`, already fails on main. - The two tests in `test_auth_db_lock_contention.py` that pinned "immediate reuse is a 401" now assert the 401 after the window instead. - Mutation checks: dropping the grace-row delete from the revoke helper fails `test_logout_inside_the_window_still_ends_the_session`; recording unstamped tokens fails `test_a_legacy_unstamped_token_gets_no_window`. - Staging on Linux, macOS (Apple Silicon) and Windows ran the PR's backend and node tests at the final code: 32 backend tests passed and the node refresh suite 25 pass / 0 fail on each OS. - Studio regression journeys (auth, settings, route crawl, full access) base vs head: no regression, 43 of 43 steps unchanged. ## Before and after in Studio Two isolated Studio installs (merge base `daf25ce59` vs this branch). Two tabs are signed in; page JS posts the stored refresh token to `/api/auth/refresh` and drops the 200, so the server has rotated the token while the browser still holds the spent one. The access token is then invalidated and both tabs reload. Before, the spent token gets a 401 and both tabs land on the login page; after, both tabs stay signed in on the chat page. 
Several Unsloth Studio tabs open on a plain-HTTP address (for example
http://<lan-ip>:8888) could all sign out at once, or jump back to a new chat, in the middle of a running chat. It was reported in the Discord help thread on Firefox, Safari, Chromium and Brave, and happened more often with several tasks running. With this change, the tabs stay signed in.What was wrong
Refresh tokens are single-use. #16468 makes tabs take turns refreshing through Web Locks, but browsers only expose Web Locks in secure contexts (HTTPS or localhost). On a plain-HTTP LAN address, every tab still refreshes on its own. All tabs share one access token, so they hit its expiry together:
sequenceDiagram participant A as Tab A participant B as Tab B participant S as Server A->>S: refresh(token R) B->>S: refresh(token R) S-->>A: 200, new pair R2 S-->>B: 401, R already used Note over B: before: clears the shared tokens<br/>or redirects to /login, which bounces to /chat Note over B: after: waits for R2 to land in storage, then retries/login, and the login route bounces it to/chat. That's the "reset to New Chat".The fix
The fix is in
features/auth/api.tsand only applies when Web Locks is unavailable. A 401 from/api/auth/refreshwaits up to 3 seconds for another tab's rotated tokens to appear in shared storage:Secure origins, the backend and the token rules are unchanged.
How it was tested
All runs were on a MacBook Pro (Apple M5, macOS 26).
a17bfe91ab46f7853c1fisSecureContextfalse), 4 forced expiries/logintests/auth-refresh-transient.test.ts, 4 new teststsc -b,tsc -p tsconfig.test.json, backend auth suites (85)The other two new tests cover a session replaced during the wait and a peer tab winning the first mark write. Each fails on the commit before its fix (
e9114afc29,17b0e6f2c0).How the browser run worked: two isolated installs, both bound to
0.0.0.0. Four tabs started on Hub, Train, Export and Library. The token lifetime is a fixed 60 minutes, so each round broke the shared access token's signature instead, which takes the same 401 path as a real expiry. The successful refresh response was also held back 1.5 s, the way a slow remote link would delay it. The server log shows the same collision on both sides, onePOST /api/auth/refresh200 and three 401s within about 5 ms. On base, the losing tabs sign out. With this PR, they pick up the winner's tokens.Not tested
Independent before/after check
Two isolated Studio installs (merge base
a17bfe91abvs this PR), headless Chromium, 4 tabs on/hub,/studio,/export,/libraryserved from a non-localhost name (isSecureContextfalse, nonavigator.locks). Each round breaks the shared access token's signature and fires a request from every tab; the winning refresh is held back 1.5 s.[200, 401][401, 200]/[200, 401]/login, tokens clearedHub tab after round 4: base shows the login page, this PR keeps the tab on Model hub.