Skip to content

Log in again when auth-server rejects the refresh token - #300

Merged
kevin-ip merged 4 commits into
mainfrom
kevin/sdk-relogin-on-refresh-rejection
Nov 10, 2026
Merged

kevin-ip merged 4 commits into
mainfrom
kevin/sdk-relogin-on-refresh-rejection

Conversation

@kevin-ip

@kevin-ip kevin-ip commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

When auth-server rejects a refresh token with a 401, a client that never called initialize() (like the market-making-bots TS bots) now drops it and does a full wallet login once, shared across concurrent calls, instead of retrying the dead token on every call; a connected client logs out at once instead of retrying for about 30 s, so the browser never gets an unprompted wallet signing request. Refresh and login failures now log only the HTTP status and the server's message, because logging the whole AxiosError wrote the request body, including the 30-day refresh token, to client logs. A 403, network error or 5xx on refresh still rethrows and keeps the refresh token, and yarn test adds node:test coverage for these paths, which CI does not run yet.

🤖 Generated with Claude Code

A 401 or 403 on /auth/token/refresh means the refresh token will never
work again (expired, revoked, or signed by a signing key auth-server no
longer trusts). login() now drops it and falls through to the full
wallet login instead of rethrowing, so clients that skip initialize()
no longer retry the dead token on every API call. Network errors still
rethrow and keep the token.

Refresh and login failures log the HTTP status and server message only;
logging the AxiosError printed the request body, including the refresh
token.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kevin-ip
kevin-ip marked this pull request as ready for review November 6, 2026 23:25
@kevin-ip
kevin-ip requested review from a team and lucasfronza as code owners November 6, 2026 23:25
Comment thread ts/sdk/src/sdk.ts Outdated
console.warn(
`Refresh token rejected (${describeError(e)}), logging in again`,
);
this.tokenResponse = null;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In connected mode, clearing tokenResponse before the fallback login means any failure of that login (even a transient network error or 5xx) causes an immediate logout with no retries.

Connected browser client: refresh returns 401, tokenResponse is set to null, and POST /auth/v2/token then hits a one-off 'Network Error'. In performTokenRefresh, the next retry finds isRefreshTokenValid() false (tokenResponse is null) and calls logout() at line 983. A 5xx hits !isNetworkError && !this.tokenResponse and logs out at line 1025. Before this change the same blip got 5 backoff retries. Fix: let performTokenRefresh retry the full login when tokenResponse is null instead of treating it as a permanent failure.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 4e0e4fa by the wallet-prompt fix: connected clients no longer fall back to a full login, so a failure there can't skip the retries. A rejected refresh logs out at once, without the 5 retries against a dead token.

Comment thread ts/sdk/src/sdk.ts Outdated
console.warn(
`Refresh token rejected (${describeError(e)}), logging in again`,
);
this.tokenResponse = null;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

login() is not single-flight outside refreshToken(), so concurrent getAccessToken() calls each send the dead refresh token, each do their own wallet login, and a late 401 can clear a fresh token pair that another call just stored.

A bot (no initialize()) starts with a stale refresh token and fires 10 parallel API calls. Each one goes through getAccessToken -> login(), gets a 401, and does its own full login: 10 signatures, 10 token issuances, and a possible rate limit. If call A's full login finishes first and stores a new pair, call B's later 401 then runs this.tokenResponse = null and drops A's valid pair, so anyone arriving in that window starts yet another login. Fix: share one in-flight login promise, and clear tokenResponse only if it still holds the rejected refresh token.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4e0e4fa: login() shares one in-flight promise, and a rejection clears tokenResponse only if it still holds the refresh token that was rejected. Test: 'logs in once for concurrent calls' (10 parallel calls, 1 refresh, 1 signature, 1 login).

Comment thread ts/sdk/src/sdk.ts
}
console.warn(
`Refresh token rejected (${describeError(e)}), logging in again`,
);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On a 401/403, background refreshes (timer, visibilitychange, online) now call bfSigner.signLoginRequest with no user gesture, and disableLoginPromptOnLogout is never checked.

Browser app using a wallet-adapter signer: the session is revoked server-side, and when the tab becomes visible handleVisible -> refreshToken -> login gets a 401, falls through to signLoginRequest, and opens a wallet signing popup the user didn't ask for. If the user rejects it or the popup is blocked, this is a non-network failure with tokenResponse null, so it logs out anyway. Before, it logged out without the popup. Fix: gate the fallback behind an option, or skip it when disableLoginPromptOnLogout is set or the signer needs user interaction.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4e0e4fa: the full-login fallback now runs only when the client is not connected (no initialize(), as bots run). A connected client clears the rejected token and throws, so performTokenRefresh logs out at once without calling signLoginRequest. Test: 'logs out without asking the wallet to sign when connected'.

Comment thread ts/sdk/src/sdk.ts Outdated

function isAuthRejection(e: unknown): boolean {
const status = globalAxios.isAxiosError(e) ? e.response?.status : undefined;
return status === 401 || status === 403;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Treating any 403 as 'refresh token rejected' throws away a possibly valid refresh token when the 403 comes from somewhere else, such as a WAF, geo-block, or account restriction.

A CDN/WAF or geo-block returns 403 for the auth host. The SDK drops the 30-day refresh token, tries a wallet login that also gets 403, and in connected mode logs out right away at line 1025 because tokenResponse is null. A token that would have worked after the block cleared is now lost. Fix: limit the fallback to 401, or match on the auth-server's specific error code or body.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4e0e4fa: only a 401 counts as a rejection. A 403 rethrows and keeps the refresh token. Test: 'keeps the refresh token and rethrows on a 403'.

Comment thread ts/sdk/src/sdk.ts Outdated
console.warn(
`Refresh token rejected (${describeError(e)}), logging in again`,
);
this.tokenResponse = null;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix only half-applies the new policy: performTokenRefresh still logs out (line 983) when the SDK's own clock says the refresh token has expired, instead of falling back to a full login like the server-rejection path now does.

A connected client that keeps running past refreshTokenValidForSeconds minus 60 s gets logout() and onLogout from line 983. A client whose token the server rejects is silently logged in again. Two policies for the same condition, 'the refresh token is no good', live in two places. Fix: decide in one place. Have login() handle both 'no valid refresh token' and 'refresh rejected' by doing a full login, and drop the isRefreshTokenValid() logout check in performTokenRefresh, or the reverse.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 4e0e4fa by the wallet-prompt fix: each mode now has one policy for a bad refresh token. Connected clients log out whether it expired locally or the server rejected it; clients that are not connected log in again in both cases.

Comment thread ts/sdk/src/sdk.ts
if (globalAxios.isAxiosError(e)) {
const serverMessage = (e.response?.data as { message?: unknown } | undefined)
?.message;
return [e.response?.status ?? e.code, serverMessage ?? e.message]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

describeError uses response.data.message whatever its type, so an object or array message logs as '[object Object]', and a plain-string response body is ignored.

The auth-server or a proxy returns {message: {code: 'X'}} and the log reads '401 [object Object]'. A text/plain 502 body such as 'upstream timeout' is dropped and replaced by the generic axios message. Fix: use message only when typeof === 'string', and fall back to data when data itself is a string.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly fixed in 63cdb61: describeError now uses response.data.message only when it is a string, so objects no longer log as [object Object]. Not falling back to a plain-string body, because a proxy's HTML error page would then be dumped into the log in full.

Comment thread ts/sdk/src/sdk.ts Outdated
console.error(`Full login failed: ${describeError(e)}`);

// If this fails and we're in a mode where logout should be disabled, don't logout
if (this.disableLoginPromptOnLogout) {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both branches of the disableLoginPromptOnLogout check in the touched catch block throw the same Error, so the branch does nothing.

The flag looks like it changes the behavior of a failed full login but doesn't, which misleads readers (see the wallet-prompt finding above). Fix: replace both with a single throw new Error(...), or make the flag actually change what happens.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 63cdb61: collapsed the two identical branches into one throw.

}
});

it('keeps the refresh token and rethrows on a network error', async () => {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test 'keeps the refresh token and rethrows on a network error' never checks that the refresh token was kept.

If a regression cleared tokenResponse on network errors too, the test would still pass, because it only checks that authV2TokenPost was not called. Add assert.equal(sdk.getTokenResponse()?.refreshToken, DEAD_REFRESH_TOKEN).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4e0e4fa: the test now asserts getTokenResponse()?.refreshToken is still the original token.

Comment thread ts/sdk/package.json Outdated
"build:esm": "tsc -p tsconfig.esm.json",
"build:example": "tsc -p tsconfig.example.json",
"build:types": "tsc -p tsconfig.esm.json --noEmit",
"test": "node --import tsx --test --test-force-exit tests/*.test.ts",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

--test-force-exit hides leaked handles, such as the scheduled refresh timer or HTTP/2 sessions, instead of failing on them.

If dispose() stops clearing updateTokenTimeout, or a test forgets to call dispose(), the 240 s refresh timer leaks and the suite still exits 0. The leak only shows up later as hangs in consumers. Fix: drop the flag and clean up handles explicitly in afterEach.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4e0e4fa: dropped --test-force-exit. Every SDK a test creates is disposed in afterEach, and the suite exits on its own.

kevin-ip and others added 2 commits November 6, 2026 17:51
- describeError logs response.data.message only when it is a string
- collapse the identical disableLoginPromptOnLogout branches in login()

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- connected clients log out on a rejected refresh token instead of prompting the wallet to sign in the background
- login() is single-flight, and a rejection clears the token only if it still holds the rejected refresh token
- only a 401 counts as a refresh rejection, so a 403 from a WAF or geo-block keeps the refresh token
- the network-error and 403 tests check that the refresh token is kept
- tests dispose every SDK in afterEach instead of forcing the process to exit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
nikita-seedlabs
nikita-seedlabs previously approved these changes Nov 9, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@kevin-ip
kevin-ip merged commit d2fcd75 into main Nov 10, 2026
5 checks passed
@kevin-ip
kevin-ip deleted the kevin/sdk-relogin-on-refresh-rejection branch November 10, 2026 21:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants