Skip to content

fix: Refactor token refresh logic in GraphQL API handler - SFS-3104 - #3263

Merged
eduardoformiga merged 10 commits into
devfrom
chore/refresh-token-adjusts
Apr 28, 2026
Merged

eduardoformiga merged 10 commits into
devfrom
chore/refresh-token-adjusts

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Apr 8, 2026 •

Copy link
Copy Markdown
Member
  • 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.

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

  • PR title and commit messages follow the Conventional Commits specification
    • Available prefixes: feat, fix, chore, docs, style, refactor, ci and test

PR Description

  • Added a label according to the PR goal - breaking change, bug, contributing, performance, documentation..

Dependencies

  • Committed the pnpm-lock.yaml file when there were changes to the packages

Documentation

  • PR description
  • For documentation changes, ping @Mariana-Caetano to review and update (Or submit a doc request)

Summary by CodeRabbit

  • Refactor

    • Centralized and simplified session validation/refresh decision logic for more consistent token handling.
  • Bug Fixes / Behavior Change

    • On refresh failure, users are immediately logged out and session data cleared; the app now surfaces a 403 state instead of silently postponing refresh attempts.
  • New Features

    • Added a shared logout-and-clear-session action and a helper to decide when validation must force a token refresh.
  • Tests

    • New unit tests cover the refresh-decision helper across expected scenarios.

- 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.
@eduardoformiga
eduardoformiga requested a review from a team as a code owner April 8, 2026 17:05
@eduardoformiga
eduardoformiga requested review from gabpaladino and lariciamota and removed request for a team April 8, 2026 17:05
@coderabbitai

coderabbitai Bot commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: fce06579-e9c8-488d-b251-51a9b1d153ff

📥 Commits

Reviewing files that changed from the base of the PR and between 4318ab2 and 456d579.

📒 Files selected for processing (1)
  • packages/core/src/sdk/session/index.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/src/sdk/session/index.ts

Walkthrough

Centralizes 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

Cohort / File(s) Summary
GraphQL API refresh decision
packages/core/src/pages/api/graphql.ts
Replaced inline JWT/refresh-after expiration checks with shouldForceRefreshTokenForValidateSession(...); removed isExpired import and inline booleans.
Session SDK behavior
packages/core/src/sdk/session/index.ts
Introduced handleRefreshToken usage; added exported logoutAndClearSession(session) which POSTs /api/fs/logout and clears person, b2b, refreshAfter; on refresh failure now logs out and clears session instead of postponing refresh.
Account hook refresh flow
packages/core/src/sdk/account/useRefreshToken.ts
On refresh failure calls logoutAndClearSession(currentSession) and sets shouldShow403 = true (removed postpone-refresh path); success still updates refreshAfter and navigates with _refresh.
New helper & tests
packages/core/src/utils/validateSessionRefreshToken.ts, packages/core/test/utils/validateSessionRefreshToken.test.ts
Added shouldForceRefreshTokenForValidateSession(...) to decide when ValidateSession should force a 401 refresh; added tests covering initial-refresh and expired-refresh scenarios.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • gabpaladino
  • lariciamota

Poem

Tokens hush, a helper stands in line,
One decision now, concise and fine.
If refresh stumbles, logout clears the slate,
Sessions tidy, flows coordinate. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: refactoring token refresh logic in the GraphQL API handler, which is the central focus across all modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/refresh-token-adjusts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codesandbox-ci

codesandbox-ci Bot commented Apr 8, 2026 •

Copy link
Copy Markdown

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
packages/core/src/pages/api/graphql.ts (1)

182-188: Remove the redundant refresh predicate.

Line 183 never changes the outcome: tokenExpired already implies jwt exists, so tokenExpired && !refreshAfterExist is fully covered by Line 180's !!jwt && !refreshAfterExist. Also, per packages/core/src/utils/getCookie.ts:26-38, a cleared auth cookie becomes jwt = 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 ||
         refreshAfterExpired

If you apply this, tokenExpired above 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9495157 and 2d6b225.

📒 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d6b225 and 5aebad1.

📒 Files selected for processing (1)
  • packages/core/src/sdk/session/index.ts

Comment thread packages/core/src/sdk/session/index.ts Resolved
@eduardoformiga eduardoformiga changed the title fix: Refactor token refresh logic in GraphQL API handler fix: Refactor token refresh logic in GraphQL API handler - SFS-3104 Apr 10, 2026
Comment thread packages/core/src/pages/api/graphql.ts Resolved
Comment thread packages/core/src/sdk/session/index.ts Resolved
Comment thread packages/core/src/pages/api/graphql.ts Resolved
… 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 its refreshAfter) are guaranteed by the type guard, so result?.refreshAfter can drop the ?.. Also, a malformed refreshAfter would silently stringify to "NaN" and quietly poison future Number(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 with validateSession — 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 simple isMounted ref or AbortController would 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 means nowSeconds === Number(sessionRefreshAfter) returns false (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.exp is only used for truthiness of the object, not the exp value itself. If that is intentional (presence of JWT cookie suffices), the type could be narrowed to e.g. object | null | undefined to communicate intent — but keeping the structural type documents the caller's shape from getJWTAutCookie, so this is purely a taste call.

Also: Number(sessionRefreshAfter) yields NaN for non-numeric strings, which harmlessly makes the expired check false. 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

📥 Commits

Reviewing files that changed from the base of the PR and between d4c0fa3 and 4318ab2.

📒 Files selected for processing (5)
  • packages/core/src/pages/api/graphql.ts
  • packages/core/src/sdk/account/useRefreshToken.ts
  • packages/core/src/sdk/session/index.ts
  • packages/core/src/utils/validateSessionRefreshToken.ts
  • packages/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

Comment thread packages/core/src/sdk/session/index.ts Resolved
- 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.
@pkg-pr-new

pkg-pr-new Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/cli

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/components

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/core

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/graphql-utils

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/lighthouse

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/sdk

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/ui

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

commit: 456d579

- 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.
@eduardoformiga
eduardoformiga merged commit 695ab6a into dev Apr 28, 2026
5 checks passed
@eduardoformiga
eduardoformiga deleted the chore/refresh-token-adjusts branch April 28, 2026 18:15
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