Repository navigation
fix: Refactor token refresh logic in GraphQL API handler - SFS-3104 - #3263
Conversation
- Simplified conditions for refreshing tokens by consolidating checks for expired tokens and the presence of refresh tokens. - Removed redundant checks to streamline the authentication flow.
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
WalkthroughCentralizes ValidateSession refresh decision into a new helper, moves refresh-token handling to a dedicated flow that logs out and clears session on refresh failure, updates account hook to call logout on failure, and adds unit tests for the new helper. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Client
participant AccountHook as "Account Hook\n(useRefreshToken)"
participant SDK as "Session SDK\n(validateSession / handleRefreshToken)"
participant GraphQL as "API\n/pages/api/graphql"
participant Logout as "API\n/api/fs/logout"
Client->>AccountHook: trigger refresh flow
AccountHook->>SDK: call validateSession / refreshTokenRequest
SDK->>GraphQL: ValidateSession request
alt GraphQL indicates forced refresh
GraphQL-->>SDK: 401 (force refresh)
SDK->>SDK: handleRefreshToken -> refreshTokenRequest()
alt refresh succeeds
SDK-->>AccountHook: updated session (refreshAfter set)
AccountHook-->>Client: navigate with _refresh
else refresh fails
SDK->>Logout: POST /api/fs/logout
Logout-->>SDK: 200 OK
SDK-->>AccountHook: cleared session (person,b2b,refreshAfter=null)
AccountHook-->>Client: set shouldShow403 = true
end
else No forced refresh
GraphQL-->>SDK: 200 OK
SDK-->>AccountHook: session valid
AccountHook-->>Client: continue
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/core/src/pages/api/graphql.ts (1)
182-188: Remove the redundant refresh predicate.Line 183 never changes the outcome:
tokenExpiredalready impliesjwtexists, sotokenExpired && !refreshAfterExistis fully covered by Line 180's!!jwt && !refreshAfterExist. Also, perpackages/core/src/utils/getCookie.ts:26-38, a cleared auth cookie becomesjwt = null, so the "after browser clears the cookie" note is not accurate for this branch.♻️ Proposed simplification
- // token expired with no refreshAfter: covers jwt expired before first refresh and after browser clears the cookie - const tokenExpiredWithNoRefreshAfter = tokenExpired && !refreshAfterExist - const shouldRefreshToken = tokenExistAndIsFirstRefreshTokenRequest || - tokenExpiredWithNoRefreshAfter || refreshAfterExpiredIf you apply this,
tokenExpiredabove becomes unused and can be removed too.As per coding guidelines, "Prefer flat conditionals over nested ifs: combine conditions with && or use early returns to avoid deep nesting and improve readability."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/pages/api/graphql.ts` around lines 182 - 188, Remove the redundant tokenExpiredWithNoRefreshAfter predicate and any now-unused tokenExpired variable; simplify the shouldRefreshToken logic to rely on the existing jwt/refresAfter checks (use the existing tokenExistAndIsFirstRefreshTokenRequest or the !!jwt && !refreshAfterExist branch and refreshAfterExpired) so the condition no longer duplicates jwt presence via tokenExpired, and update usage of shouldRefreshToken accordingly (referencing tokenExpired, refreshAfterExist, tokenExistAndIsFirstRefreshTokenRequest, refreshAfterExpired, and jwt to locate and update the expressions).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/core/src/pages/api/graphql.ts`:
- Around line 182-188: Remove the redundant tokenExpiredWithNoRefreshAfter
predicate and any now-unused tokenExpired variable; simplify the
shouldRefreshToken logic to rely on the existing jwt/refresAfter checks (use the
existing tokenExistAndIsFirstRefreshTokenRequest or the !!jwt &&
!refreshAfterExist branch and refreshAfterExpired) so the condition no longer
duplicates jwt presence via tokenExpired, and update usage of shouldRefreshToken
accordingly (referencing tokenExpired, refreshAfterExist,
tokenExistAndIsFirstRefreshTokenRequest, refreshAfterExpired, and jwt to locate
and update the expressions).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 94c47872-d3ca-4d2f-a552-5c992cbece3e
📒 Files selected for processing (1)
packages/core/src/pages/api/graphql.ts
- Added logic to clear server-side cookies and reset the session to an anonymous state when refresh token fails. - Removed unnecessary session properties to prevent retry loops.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/sdk/session/index.ts`:
- Around line 138-147: The logout fetch call (fetch('/api/fs/logout')) inside
the refresh-token catch block should be wrapped in its own try-catch so network
errors don't propagate and prevent cleanup; call fetch('/api/fs/logout', {
method: 'POST' }) inside a try and swallow or log any error (e.g., using
console.error or processLogger) in the catch, then always call
sessionStore.set({ ...session, person: null, b2b: null, refreshAfter: null })
after the try-catch to guarantee the session is reset even if the logout request
fails.
- Around line 138-147: When refresh token handling in
packages/core/src/sdk/session/index.ts fails, don’t immediately clear the
session via the fetch('/api/fs/logout') + sessionStore.set({...person: null,
b2b: null}) path; instead align with useRefreshToken.ts retry behavior by
deferring logout — set session.refreshAfter to Date.now() + 3600_000 (or reuse
the same retry helper) and leave person and b2b intact so the hourly retry
window is honored; alternatively, if you prefer immediate logout, replace the
deferred retry in useRefreshToken.ts with the same logout path to keep behavior
consistent across both flows.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 75357123-0a25-4afa-8f4d-2b435b0df65b
📒 Files selected for processing (1)
packages/core/src/sdk/session/index.ts
… management - Introduced `logoutAndClearSession` function to centralize session clearing logic. - Updated `useRefreshToken` and `validateSession` to utilize the new function for handling refresh token failures, enhancing error handling and reducing code duplication.
- Replaced inline token refresh conditions with a dedicated `shouldForceRefreshTokenForValidateSession` function for improved readability and maintainability. - Introduced new utility function to handle refresh token validation based on JWT and session refresh criteria. - Added unit tests for the new refresh token validation logic to ensure correctness.
- Introduced `handleRefreshToken` function to centralize token refresh logic, improving readability and maintainability. - Added `isRefreshAfterExpired` function to check for expired refresh tokens. - Updated `validateSession` to utilize the new functions, streamlining the session validation process and reducing code duplication.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
packages/core/src/sdk/session/index.ts (1)
80-93: Minor: redundant optional chaining after the success guard.Inside the
isRefreshTokenSuccessful(result)branch,result(and itsrefreshAfter) are guaranteed by the type guard, soresult?.refreshAftercan drop the?.. Also, a malformedrefreshAfterwould silently stringify to"NaN"and quietly poison futureNumber(sessionRefreshAfter)comparisons. Worth a small sanity check if the upstream contract isn't fully trusted.✨ Suggested tightening
- if (isRefreshTokenSuccessful(result)) { - sessionStore.set({ - ...session, - refreshAfter: String( - Math.floor(new Date(result?.refreshAfter).getTime() / 1000) - ), - }) - } else { + if (isRefreshTokenSuccessful(result)) { + const refreshAfterSeconds = Math.floor( + new Date(result.refreshAfter).getTime() / 1000 + ) + if (Number.isFinite(refreshAfterSeconds)) { + sessionStore.set({ + ...session, + refreshAfter: String(refreshAfterSeconds), + }) + } + } else { await logoutAndClearSession(session) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/session/index.ts` around lines 80 - 93, The success branch in handleRefreshToken uses redundant optional chaining and doesn't validate the parsed timestamp; inside the isRefreshTokenSuccessful(result) block, remove the `?.` from `result.refreshAfter`, parse the date and verify that `Number.isFinite(new Date(result.refreshAfter).getTime())` (or otherwise check for NaN) before calling sessionStore.set, and if the timestamp is invalid call logoutAndClearSession(session) (or set a safe fallback) to avoid storing "NaN" as refreshAfter; reference functions: handleRefreshToken, isRefreshTokenSuccessful, sessionStore.set, and logoutAndClearSession.packages/core/src/sdk/account/useRefreshToken.ts (1)
11-51: Consistent behavior withvalidateSession— both paths now logout+clear. 👍Small optional hardening: the effect fires
setShouldShow403(true)after awaited work, so a fast unmount (e.g., user navigates) could schedule a state update on an unmounted component. React warns rather than breaks, but a simpleisMountedref orAbortControllerwould silence it.🧹 Optional cleanup pattern
useEffect(() => { + let cancelled = false const handleRefreshTokenAndUpdateSession = async () => { if (!needsRefreshToken) return @@ } else { await logoutAndClearSession(currentSession) - setShouldShow403(true) + if (!cancelled) setShouldShow403(true) } } catch (error) { console.error('Error during refresh token process:', error) await logoutAndClearSession(currentSession) - setShouldShow403(true) + if (!cancelled) setShouldShow403(true) } } handleRefreshTokenAndUpdateSession() + return () => { + cancelled = true + } }, [needsRefreshToken, fromPage])🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/account/useRefreshToken.ts` around lines 11 - 51, The effect can schedule state updates after unmount (setShouldShow403 and logoutAndClearSession) — add an isMounted ref in useRefreshToken and set it to false in the effect cleanup, then guard any post-await state calls inside handleRefreshTokenAndUpdateSession (e.g., before calling logoutAndClearSession(currentSession) and before setShouldShow403(true), and before window.location.href if you want) with if (isMounted.current) to avoid setting state on unmounted components; alternatively you can use an AbortController to cancel the async work and check abortController.signal.aborted inside the async flow. Ensure you reference the isMounted ref from within handleRefreshTokenAndUpdateSession and add the cleanup return that flips it to false.packages/core/test/utils/validateSessionRefreshToken.test.ts (1)
38-68: Good coverage — consider one extra boundary case.The strict
>in the helper meansnowSeconds === Number(sessionRefreshAfter)returnsfalse(not expired). A tiny test pinning that boundary would lock the contract in place and prevent a future off-by-one regression from sneaking in silently.🧪 Suggested addition
it('returns true if refreshAfter is past even without JWT', () => { expect( shouldForceRefreshTokenForValidateSession({ jwt: null, sessionRefreshAfter: String(now - 1), nowSeconds: now, }) ).toBe(true) }) + + it('returns false when refreshAfter equals nowSeconds (boundary)', () => { + expect( + shouldForceRefreshTokenForValidateSession({ + jwt: { exp: now + 3600 }, + sessionRefreshAfter: String(now), + nowSeconds: now, + }) + ).toBe(false) + }) })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/test/utils/validateSessionRefreshToken.test.ts` around lines 38 - 68, Add a boundary test for shouldForceRefreshTokenForValidateSession that verifies when sessionRefreshAfter exactly equals nowSeconds the function returns false (i.e., not expired); create a new it block in the existing "when session.refreshAfter is set" describe and call shouldForceRefreshTokenForValidateSession with sessionRefreshAfter: String(now) (and the same jwt/nowSeconds setup used elsewhere) then assert the result is false to lock the current strict '>' behavior.packages/core/src/utils/validateSessionRefreshToken.ts (1)
1-29: Clean, testable helper — nice work flattening the decision logic. 🎯The two-flag decomposition is tidy and the JSDoc explains the triggers well. One tiny observation:
jwt.expis only used for truthiness of the object, not theexpvalue itself. If that is intentional (presence of JWT cookie suffices), the type could be narrowed to e.g.object | null | undefinedto communicate intent — but keeping the structural type documents the caller's shape fromgetJWTAutCookie, so this is purely a taste call.Also:
Number(sessionRefreshAfter)yieldsNaNfor non-numeric strings, which harmlessly makes the expired checkfalse. Given the value comes from a trusted GraphQL variable, no action needed; just flagging in case the contract ever loosens.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/utils/validateSessionRefreshToken.ts` around lines 1 - 29, The code currently treats jwt only for presence and casts sessionRefreshAfter with Number which can produce NaN; update the types and guards to reflect intent: change ShouldForceRefreshParams.jwt from `{ exp: number } | null | undefined` to `object | null | undefined` (or keep the existing type but use a presence check `jwt != null`) and replace `Number(sessionRefreshAfter)` with a safe numeric parse/guard in shouldForceRefreshTokenForValidateSession (e.g. parseInt/Number + Number.isFinite or `const refreshAfterSeconds = Number(sessionRefreshAfter); const refreshAfterExpired = refreshAfterExists && Number.isFinite(refreshAfterSeconds) && nowSeconds > refreshAfterSeconds`) so non-numeric strings don't produce NaN-driven behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/sdk/session/index.ts`:
- Around line 103-116: The early returns after clearing stale refreshAfter and
after handleRefreshToken cause the function to skip the downstream
ValidateSession GraphQL call and postalCode flow (affecting callers like
useRegion.setRegion and useGeolocation); either document this as intentional or
stop returning null on success. Change the cleanup branch (where
session.refreshAfter && !session.person) to set refreshAfter to null but
continue into the validation flow (remove the unconditional return null), and
change the refresh token branch (isRefreshAfterExpired + handleRefreshToken) to
only return null on refresh failure—on success continue to the
validation/deliveryPromise and request(mutation, ...) so validatedSession is
populated (refer to session.refreshAfter, session.person, sessionStore.set,
isRefreshAfterExpired, handleRefreshToken, deliveryPromise, and request).
---
Nitpick comments:
In `@packages/core/src/sdk/account/useRefreshToken.ts`:
- Around line 11-51: The effect can schedule state updates after unmount
(setShouldShow403 and logoutAndClearSession) — add an isMounted ref in
useRefreshToken and set it to false in the effect cleanup, then guard any
post-await state calls inside handleRefreshTokenAndUpdateSession (e.g., before
calling logoutAndClearSession(currentSession) and before setShouldShow403(true),
and before window.location.href if you want) with if (isMounted.current) to
avoid setting state on unmounted components; alternatively you can use an
AbortController to cancel the async work and check
abortController.signal.aborted inside the async flow. Ensure you reference the
isMounted ref from within handleRefreshTokenAndUpdateSession and add the cleanup
return that flips it to false.
In `@packages/core/src/sdk/session/index.ts`:
- Around line 80-93: The success branch in handleRefreshToken uses redundant
optional chaining and doesn't validate the parsed timestamp; inside the
isRefreshTokenSuccessful(result) block, remove the `?.` from
`result.refreshAfter`, parse the date and verify that `Number.isFinite(new
Date(result.refreshAfter).getTime())` (or otherwise check for NaN) before
calling sessionStore.set, and if the timestamp is invalid call
logoutAndClearSession(session) (or set a safe fallback) to avoid storing "NaN"
as refreshAfter; reference functions: handleRefreshToken,
isRefreshTokenSuccessful, sessionStore.set, and logoutAndClearSession.
In `@packages/core/src/utils/validateSessionRefreshToken.ts`:
- Around line 1-29: The code currently treats jwt only for presence and casts
sessionRefreshAfter with Number which can produce NaN; update the types and
guards to reflect intent: change ShouldForceRefreshParams.jwt from `{ exp:
number } | null | undefined` to `object | null | undefined` (or keep the
existing type but use a presence check `jwt != null`) and replace
`Number(sessionRefreshAfter)` with a safe numeric parse/guard in
shouldForceRefreshTokenForValidateSession (e.g. parseInt/Number +
Number.isFinite or `const refreshAfterSeconds = Number(sessionRefreshAfter);
const refreshAfterExpired = refreshAfterExists &&
Number.isFinite(refreshAfterSeconds) && nowSeconds > refreshAfterSeconds`) so
non-numeric strings don't produce NaN-driven behavior.
In `@packages/core/test/utils/validateSessionRefreshToken.test.ts`:
- Around line 38-68: Add a boundary test for
shouldForceRefreshTokenForValidateSession that verifies when sessionRefreshAfter
exactly equals nowSeconds the function returns false (i.e., not expired); create
a new it block in the existing "when session.refreshAfter is set" describe and
call shouldForceRefreshTokenForValidateSession with sessionRefreshAfter:
String(now) (and the same jwt/nowSeconds setup used elsewhere) then assert the
result is false to lock the current strict '>' behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 6f69a927-05fd-4d2b-9874-68db26fb296e
📒 Files selected for processing (5)
packages/core/src/pages/api/graphql.tspackages/core/src/sdk/account/useRefreshToken.tspackages/core/src/sdk/session/index.tspackages/core/src/utils/validateSessionRefreshToken.tspackages/core/test/utils/validateSessionRefreshToken.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/pages/api/graphql.ts
- Updated `handleRefreshToken` to return the refreshed session or null, improving clarity in session management. - Enhanced `validateSession` to handle the refreshed session appropriately, ensuring the session state is correctly updated or cleared. - Streamlined comments for better understanding of session validation flow and token refresh logic.
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/graphql-utils
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
- Eliminated the logic that cleared the stale refreshAfter when no person is associated with the session, streamlining the session validation process. - This change focuses on improving clarity and maintaining the flow of session validation without unnecessary state modifications.
What's the purpose of this pull request?
How it works?
How to test it?
Starters Deploy Preview
References
Checklist
You may erase this after checking them all 😉
PR Title and Commit Messages
feat,fix,chore,docs,style,refactor,ciandtestPR Description
breaking change,bug,contributing,performance,documentation..Dependencies
pnpm-lock.yamlfile when there were changes to the packagesDocumentation
@Mariana-Caetanoto review and update (Or submit a doc request)Summary by CodeRabbit
Refactor
Bug Fixes / Behavior Change
New Features
Tests