You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
auth: coordinate OAuth token renewal in AccountsStore [4/10] - #22939
Adds safe renewal of short-lived tokens. Each renewal gives a new access token and a new single-use refresh token, so two renewals at once, or a lost result, would sign the user out. Nothing creates refreshable credentials yet, so existing accounts behave as before.
New CredentialSessions class (used by AccountsStore):
renews a token that expires within ten minutes, or whose expiry is unknown. Concurrent callers share one exchange;
saves both new tokens in one secure-store item, through a per-endpoint write queue, before handing out the new access token;
uses a generation counter so a late renewal or write can't bring back a signed-out or replaced account;
maps old access tokens to their session, so long-lived API clients get the current token without switching identity;
signs the account out once when the refresh is rejected or the response is malformed, and keeps the credential on temporary failures;
revokes credentials that are no longer used, with a timeout.
AccountsStore:
exposes resolveToken, getAccountWithFreshToken, isRefreshable, getTokenExpiration and revokeUnusedToken;
addAccount accepts the full credential;
removeAccount retires the session before any await, then returns the removed account, so AppStore revokes the credential current at sign-out;
ignores 401s for tokens that were already rotated, and waits for a renewal in flight before deciding.
API:
resolves the token per request through API.setTokenProvider, installed in index.tsx;
reports the token actually sent on 401;
the anonymous public-repository fallback opts out.
request and deleteToken accept an AbortSignal.
revokeUnusedToken is only used by tests until the sign-in PR.
Stack
Merge in order, starting with 1. Each PR builds, passes tests, and keeps production behavior on its own.
Add tests for refresh concurrency and stale response handling
app/src/lib/stores/accounts-store.ts:258
No test exercises AccountsStore.refresh, so the two new concurrency guarantees here are unprotected. Please add deferred-request tests showing that a profile response completed after removal/replacement is ignored, and that a token rotated while the profile request is pending remains the installed token.
sergiou87
changed the title
auth: coordinate OAuth token renewal in AccountsStore [4/9]
auth: coordinate OAuth token renewal in AccountsStore [4/10]
Oct 2, 2026
The reason will be displayed to describe this comment to others. Learn more.
The core renewal design is careful: concurrent refreshes are deduplicated, secure-store operations are ordered per endpoint, stale 401s are handled correctly, and retirement prevents late renewal work from resurrecting a session.
I found one overlapping-sign-in persistence race that I think needs addressing before this central coordination layer lands. If sign-in A is blocked in setItem, sign-in B advances the generation, A then completes its write and is correctly not installed, and B’s queued write subsequently fails, the original session remains active in memory while secure storage contains A. For the same login, restarting Desktop loads a credential from a sign-in that was reported as unsuccessful; with #22943’s unpublished-token cleanup that persisted credential may also have been revoked. For different logins, A can remain as an orphaned keychain entry.
The UI normally has one active sign-in state, but resetting or restarting a flow cannot cancel an addAccount operation that has already entered secure storage. A blocked keychain write makes two in-flight additions possible, and the generation logic explicitly treats overlapping additions as supported.
Suggested approach: after setItem succeeds, if isLatest() is now false, reconcile secure storage inside the same per-endpoint write-queue action before returning null. Restore the currently installed credential when the superseded write used the same login; otherwise delete the superseded login’s keychain entry. The sign-in layer can then revoke the unpublished credential as planned. If rollback fails, fail closed by retiring the in-memory session after leaving the write action rather than retaining a known disk/memory mismatch.
Please add a gated-write regression test: install O, block A’s write, start B, allow A to persist, fail B, then assert memory, secure storage, and a restarted AccountsStore all retain O. A different-login variant should verify that A’s orphaned keychain entry is removed.
Base automatically changed from
short-lived-tokens-3-storage to
developmentOctober 2, 2026 12:18
Short-lived GitHub tokens expire after eight hours and are renewed with
a single-use refresh token. Every renewal returns a new access token
and a new refresh token, and invalidates the old refresh token. If two
callers renew at once, or a renewal result is lost, the account is
signed out. This commit adds the machinery that renews safely. Nothing
creates refreshable credentials yet, so every existing account keeps
its plain token and behaves as before.
CredentialSessions (new, app/src/lib/credential-sessions.ts) owns the
token lifecycle for AccountsStore:
- one session per endpoint, restored from secure storage on load and
replaced when an account is added;
- renewal before authenticated work when the access token expires
within ten minutes (inclusive) or its expiry is unknown. Concurrent
callers share one exchange, and callers asking for a shorter
validity still wait for an exchange in flight instead of getting
the token it is about to invalidate;
- both tokens of a renewed pair are saved in one secure-store item,
through a per-endpoint write queue, before the new access token is
published. If saving fails, the new token isn't handed out;
- a generation counter, so a late renewal or write can't bring back
an account that was signed out or replaced;
- lookups from old access tokens to their session, so a long-lived
API client holding a token snapshot gets the current token without
switching identity;
- classification of renewal failures: a rejected or malformed
refresh response signs the account out (once) and emits
`token-invalidated`; temporary failures keep the credential and
let the next caller retry;
- remote revocation of credentials that are no longer used, bounded
by a timeout so a stalled request can't block sign-out.
AccountsStore delegates to it and exposes what consumers need:
`resolveToken`, `getAccountWithFreshToken`, `isRefreshable`,
`getTokenExpiration` and `revokeUnusedToken`. `addAccount` accepts the
full credential (defaulting to the account's plain token), and the
constructor accepts renewal, clock and revocation functions for tests.
`removeAccount` now retires the session synchronously, before any
await, so a renewal can't publish a token in between. It then deletes
secure storage and returns the removed account (or null if it wasn't
installed), so AppStore revokes the credential that was current at
sign-out rather than a stale snapshot. If deleting from secure storage
fails, the account is still signed out and the returned credential can
still be revoked.
`invalidateToken` now ignores 401s for tokens that were already
rotated, and waits for a renewal in flight before deciding whether the
rejected token is still current.
`tryUpdateAccount` refreshes profile data with a fresh token and keeps
whatever token is current when the response arrives, instead of
overwriting a token that rotated during the request.
The API class resolves its token through a provider that index.tsx
installs from AccountsStore (`API.setTokenProvider`, which returns a
cleanup function). Each request resolves the current token, and a 401
reports the token that was actually sent. The anonymous
public-repository fallback account (`id === -1`) opts out, so it never
picks up another account's credentials or signs anyone out.
`request` and `deleteToken` accept an optional AbortSignal, used to
bound revocation.
Tests cover renewal timing, shared exchanges, persistence failures,
sign-out racing renewal and persistence, stale 401s during rotation,
revocation timeouts and failures, token provider behavior in API, and
an HTML gateway error during renewal being treated as temporary.
Co-authored-by: Copilot <[email protected]>
`CredentialSessions.add` retired the endpoint's current session before
writing the new credential to secure storage. If that write failed,
`AccountsStore.addAccount` reported the error and kept the existing
account in its list, but the account's session was already retired:
every later request for the still-visible account threw
`AccountRequiresSignInError` until the app was restarted. On
`development`, a failed re-sign-in left the existing account fully
usable, so this was a regression introduced by the credential
sessions refactor.
The fix makes replacement follow a simple rule: try to save the new
credential; if the save succeeds, swap it in; if it fails, keep the
old one untouched.
- `add` no longer retires anything up front. It only bumps the
endpoint's generation so a sign-out or a newer sign-in started while
storage is pending still supersedes it, exactly as before.
- The swap (retire the previous session, install the new one) happens
inside the queued write, right after `setItem` resolves and only if
this sign-in is still the latest. Doing it inside the write matters:
a renewal of the replaced session whose own write is queued behind
this one then sees `retired` and revokes its unused token instead of
overwriting the new credential. A renewal already in flight when the
swap happens is handled by the existing post-exchange `retired`
checks in `rotate`.
- `retireSession` is split into `retirePrevious` (drop the session)
and `nextGeneration` (bump the counter). Sign-out and sign-in
required still do both through `retire`; `add` uses them separately.
- The `sessionGenerations` comment now says what bumps it: a sign-in
starting or a session being removed.
Renewal concurrency is unchanged: a session still shares one
in-flight `refreshing` promise, so there is never more than one
refresh request per session at a time.
One trade-off: because the old session stays live while the new
credential is being written, a rejected renewal of that old session
landing in that short window signs it out and, through the generation
bump, also drops the pending sign-in. Before, the early retirement
made the old session's failure a no-op. The window is the duration of
one secure-storage write and the user can simply sign in again.
Tests (`account-token-lifecycle-test.ts`):
- New: "keeps the current account usable when saving a replacement
fails". Adds a rotating account, makes `setItem` throw, signs in a
different user on the same endpoint, and checks the old account is
still listed, still refreshable, still hands out its token, and its
stored credential is unchanged. Fails without the source change.
- New: "a renewal finishing after a replacement cannot overwrite it".
Starts a renewal, replaces the account while the exchange is
pending, then finishes the exchange: the renewed token is revoked,
the caller gets `AccountRequiresSignInError`, and secure storage and
the account list hold the replacement.
- Fix: "stays signed out if secure deletion fails after renewal
rejection" had been pasted inside the body of "does not return a new
token when persistence fails or downgrade storage" during the stack
split. As a nested `it` it was never awaited by its parent, so
`node:test` could cancel it and its coverage depended on timing. It
is now a sibling test with the same body.
Addresses review feedback on #22939.
Co-authored-by: Copilot <[email protected]>
Review feedback on #22939 found that overlapping sign-ins could leave memory,
secure storage, and the next launch disagreeing about which account is signed
in. With account O signed in:
1. Sign-in A starts and its keychain write stalls.
2. Sign-in B starts and bumps the endpoint's sign-in generation, marking A as
superseded.
3. A's write lands, but A is not installed because it is no longer the latest
sign-in, so addAccount returns null.
4. B's write fails, so B is not installed either.
Memory still held O while the keychain held A. On the next launch A loaded
from storage, even though the sign-in flow had already revoked A's token as
unpublished, and a different-login A left O's entry orphaned.
The generation counter tried to guess which concurrent sign-in "should" win
before knowing which saves would succeed. This replaces it with a simpler
rule: secure-storage writes are serialized per endpoint, and every sign-in
whose save succeeds is installed immediately, inside that same write step. The
installed session therefore always matches the last successful save, which is
also what the next launch loads. A failed save leaves the current session
untouched, and only then does addAccount return null, so the sign-in flow
revokes a token only when it was never installed.
Consequences:
- CredentialSessions.add no longer returns null; it resolves with the
installed account or throws when secure storage fails. The
sessionGenerations map, nextGeneration, retirePrevious and isLatest helpers
are removed.
- Signing out (retire) no longer cancels a pending sign-in either. A sign-in
saved after the previous account was signed out stays signed in, matching
what the user just did, and an automatic sign-out of the old account cannot
silently drop the new one.
- delete() now skips removing the keychain item when a later sign-in with the
same login has been installed since the sign-out, because that item already
holds the new sign-in's credential. Different logins use different items, so
the old account's item is still deleted.
Second race found while re-checking the fix: CredentialSessions swapped the
session inside the write, but AccountsStore only updated its account list a few
microtasks later, after add() returned. A sign-out resuming in that window
found the old account still listed, so it retired the endpoint's session,
which was already the new sign-in's. Depending on the login, the new account
then stayed listed but unusable, or lost its keychain item and reloaded with
an empty token. The account list update now happens through a new
ICredentialSessionsDelegate.onSignedIn callback that runs synchronously with
the session swap, so a sign-out always sees the old pair or the new pair,
never a mix.
Tests:
- credential-sessions-test: "drops a sign-in superseded..." becomes "installs
overlapping sign-ins in the order they are saved". Both sign-ins resolve, the
first token stops resolving, and storage holds the second credential.
- account-token-lifecycle-test, three new tests:
- "keeps memory, storage, and restart in sync when overlapping sign-ins
race" reproduces the review scenario (first write stalls, second write
fails) and checks memory, the token, storage, and a restarted store all
agree on the first sign-in.
- "a sign-in saved after signing out the previous account stays signed in"
covers same-login and different-login replacements gated behind a
sign-out.
- "a sign-out resuming as a sign-in is installed sees one consistent
account" sweeps a sign-out across the microtasks after the keychain save
resolves.
Each new or updated test fails against the previous implementation. The full
suite passes apart from the four known git push/rev-parse failures that also
fail on development in this environment.
Co-authored-by: Copilot <[email protected]>
Review feedback on #22939 pointed out that CredentialSessions.restore
replaced the endpoint's entry in sessionsByEndpoint without retiring the
session it replaced. add() already retires the previous session before
installing a new one, but restore() is also called directly by the
AccountsStore load path, once per persisted account.
AccountsStore.addAccount never persists two accounts for the same endpoint,
but the persisted users list can still contain duplicates. For example,
after downgrading to a version without the GHE endpoint migration and
signing in to the same *.ghe.com host there, the old /api/v3 entry and the
new api. entry both migrate to the same endpoint on the next launch. In that
case the earlier entry's session stayed live but hidden: sessionsByEndpoint
pointed at the later one, yet sessionsByToken still mapped the earlier token
to a non-retired session. A long-lived client holding that token could
resolve it, renew it and overwrite that account's keychain item, breaking
the one-session-per-endpoint invariant the rest of the class relies on.
restore() now retires any existing session for the endpoint before
installing the restored one, matching add(). The later entry wins, like an
overlapping sign-in, and the earlier token stops resolving with
AccountRequiresSignInError instead of renewing.
Test: 'loading duplicate entries for an endpoint keeps only the last
session live' persists two accounts for the same endpoint, the first with an
expired rotating credential, and checks that resolving the first token
rejects without renewing while the second still resolves. It fails without
this change.
Co-authored-by: Copilot <[email protected]>
Register gateway-failure test as an awaited sibling
app/test/unit/oauth-token-test.ts:334
This test is still nested inside sanitizes malformed JSON responses and is not awaited. Once the parent completes, node:test can cancel the child, so this gateway-failure coverage is timing-dependent. Close the parent before registering this as a sibling test.
Follow-up review feedback on #22939. The previous commit made
CredentialSessions.restore retire the earlier session when the persisted
users list contains two entries for the same endpoint, so only the last
entry's credential stays live. AccountsStore's load path still appended both
entries to its account list, though, leaving the list and the sessions
disagreeing about which account is signed in:
- getAll() and the UI listed two accounts for the same host, one of them
backed by a retired session.
- retireAccount and getAccountWithFreshToken look the account up with
find() by endpoint, so they could match the dead entry. When the two
entries had different ids, the id check failed and removeAccount returned
null, leaving the user unable to sign out of the live account.
The load path now collects accounts in a Map keyed by endpoint, so the last
entry wins exactly as it does in CredentialSessions.restore, before sorting.
When the duplicates come from the GHE endpoint migration, the migration
already triggers save(), so the deduplicated list is persisted too.
development keeps both entries in this case, but it has no per-endpoint
sessions for the list to disagree with, so the mismatch is specific to this
stack.
Test: 'loading duplicate entries for an endpoint keeps only the last
session live' now also asserts that getAll() returns only the last entry and
that removing it succeeds and empties the list. It fails without this change.
Co-authored-by: Copilot <[email protected]>
Review feedback on #22939. The test 'treats an HTML gateway failure as
temporary rather than a malformed replacement pair' was declared inside the
body of 'sanitizes malformed JSON responses' instead of after it. node:test
then registers it as an un-awaited subtest of that test, which can be
cancelled once the parent finishes, so whether the gateway-failure coverage
actually ran depended on timing.
Close the parent test first and declare the gateway-failure test as a
sibling in the 'OAuth token requests' suite. The test body is unchanged
apart from indentation.
Co-authored-by: Copilot <[email protected]>
After chatting a bit with Copilot, it came up with what seems to be a simpler fix (already implemented, with a regression test). Let me copy & paste the explanation:
I went a slightly different way than the suggested rollback. Instead of making a superseded save undo itself, I removed superseding entirely. Fixed in 19244cc.
What changed
Keychain saves for an endpoint are still serialized. Every sign-in whose save succeeds is now installed right away, inside the same write-queue action.
The generation counter (sessionGenerations, nextGeneration, isLatest) is gone. CredentialSessions.add no longer returns null: it resolves with the installed account or throws if secure storage fails.
So memory always matches the last successful save, which is also what a restarted AccountsStore loads.
In your scenario (O installed, A's write blocked, B starts, A persists, B fails), the result is now A in memory, in the keychain and after restart. A's token is not revoked, because A's addAccount succeeded.
Why not roll back to O
A was a sign-in the user completed, and its save succeeded. Undoing it means rolling back secure storage after the fact.
That rollback can fail too, which needs another fail-closed path.
The generation counter was guessing which concurrent sign-in "should" win before knowing which saves would succeed. "Last successful save wins" needs no reconciliation and no extra failure mode.
Related changes in the same commit
Signing out no longer cancels a pending sign-in. A sign-in saved after the previous account was signed out stays signed in, including after an automatic sign-out.
delete() skips removing the keychain item if a same-login sign-in was installed after the sign-out, because that item now holds the new credential.
While re-checking this I found a related gap. The session was swapped inside the write, but AccountsStore only updated its account list a few microtasks later. A sign-out resuming in that window could retire the new session while the old account was still listed. The list is now updated through a new onSignedIn delegate callback that runs synchronously with the swap.
Tests
Your gated-write scenario: O installed, A blocked, B started, A persists, B fails. It asserts memory, the resolved token, secure storage and a restarted store all agree, on A rather than O, given the approach above.
Same-login and different-login replacements saved after a sign-out of the previous account.
A sign-out swept across the microtasks after a sign-in's save resolves.
Each test fails against the previous implementation.
One caveat
In the different-login case, replacing O with A leaves O's keychain entry behind. That's the same as account replacement on development today, so I left it out of this PR.
docs/technical/oauth.md (#22919) now describes how overlapping sign-ins resolve.
After that fix I had to deal with other stuff caught by Copilot 😂 Hopefully it's in a much better shape now 💪
The reason will be displayed to describe this comment to others. Learn more.
The revised serialized “last successful save wins” model resolves the requested disk/memory inconsistency. Successful writes install and publish synchronously, failed writes leave the current session untouched, sign-out/write ordering is explicitly handled, duplicate endpoint restoration is consistent, and the new gated regression tests cover the original O/A/B race plus adjacent sign-out interleavings.
Three fresh remediation reviews confirmed the original finding is resolved. The remaining post-install localStorage/listener-exception path is a low-probability hardening concern already accepted elsewhere in the stack and does not block this fix.
Brings in short-lived token support (#22917, #22937, #22938, #22939) and
adapts it to multiple accounts per endpoint:
- Credential sessions are keyed per account (endpoint + login) instead of
per endpoint, so renewal, invalidation and storage writes are isolated.
- AccountsStore lookups, retirement and refresh match the exact account.
- The invalidated token dialog names the signed-out login and offers a
targeted sign-in for that account.
Co-authored-by: Copilot App <[email protected]>
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
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.
Description
Adds safe renewal of short-lived tokens. Each renewal gives a new access token and a new single-use refresh token, so two renewals at once, or a lost result, would sign the user out. Nothing creates refreshable credentials yet, so existing accounts behave as before.
New
CredentialSessionsclass (used by AccountsStore):AccountsStore:
resolveToken,getAccountWithFreshToken,isRefreshable,getTokenExpirationandrevokeUnusedToken;addAccountaccepts the full credential;removeAccountretires the session before any await, then returns the removed account, so AppStore revokes the credential current at sign-out;API:
API.setTokenProvider, installed in index.tsx;requestanddeleteTokenaccept an AbortSignal.revokeUnusedTokenis only used by tests until the sign-in PR.Stack
Merge in order, starting with 1. Each PR builds, passes tests, and keeps production behavior on its own.
Validation
Release notes
Notes: no-notes