Skip to content

fix: Enhance session validation logic to skip token refresh in local … - #3285

Merged
eduardoformiga merged 2 commits into
devfrom
fix/refresh-token-localhost
May 4, 2026
Merged

eduardoformiga merged 2 commits into
devfrom
fix/refresh-token-localhost

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Apr 28, 2026 •

Copy link
Copy Markdown
Member

…environments

  • Introduced a check to bypass token refresh logic when running in local environments (localhost or 127.0.0.1).
  • Updated GraphQL API handler and session validation functions to ensure consistent behavior across environments.
  • This change prevents unnecessary refresh attempts during local development, improving the developer experience.

Summary by CodeRabbit

  • New Features

    • Session validation now detects local development environments (localhost/127.0.0.1) and adapts behavior to simplify local authentication handling and improve developer workflow.
  • Bug Fixes

    • Refined token refresh logic to skip refresh enforcement when running locally, preventing unnecessary 401-driven refresh flows during development.

…environments

- Introduced a check to bypass token refresh logic when running in local environments (localhost or 127.0.0.1).
- Updated GraphQL API handler and session validation functions to ensure consistent behavior across environments.
- This change prevents unnecessary refresh attempts during local development, improving the developer experience.
@eduardoformiga
eduardoformiga requested a review from a team as a code owner April 28, 2026 19:58
@eduardoformiga
eduardoformiga requested review from ommeirelles and renatomaurovtex and removed request for a team April 28, 2026 19:58
@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

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: a8b9711e-58ba-4760-b803-2a6340e31b64

📥 Commits

Reviewing files that changed from the base of the PR and between c16cebb and 6eefc18.

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

Walkthrough

The GraphQL API handler and session validator now detect local requests by parsing the Host header for localhost or 127.0.0.1 and disable refresh-token enforcement/refresh-at-expiration logic for those local requests; non-local behavior remains unchanged.

Changes

Cohort / File(s) Summary
Localhost refresh-token gating
packages/core/src/pages/api/graphql.ts, packages/core/src/sdk/session/index.ts
Added Host header detection for localhost/127.0.0.1 to conditionally skip refresh-token validation and refresh-at-expiration logic when requests are local.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Suggested reviewers

  • gabpaladino
  • lariciamota

Poem

🔐 On localhost the token sleeps,
Guards step back where dev light peeps.
Flow stays intact beyond this gate,
Faster checks for local state. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 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: skipping token refresh in local environments. It directly relates to the core modifications in both the GraphQL handler and session validation logic.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 fix/refresh-token-localhost

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

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

@codesandbox-ci

codesandbox-ci Bot commented Apr 28, 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.

Actionable comments posted: 1

🤖 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/pages/api/graphql.ts`:
- Around line 164-170: The local-host detection using startsWith is too
permissive; change the isLocal check to compare the host portion exactly (strip
any port by splitting request.headers.host on ':' and compare the hostname ===
'localhost' or === '127.0.0.1') instead of using startsWith so requests like
'localhost.example.com:3000' won’t be treated as local; update the isLocal
computation that precedes the operation.__meta__.operationName ===
'ValidateSession' guard to use the exact hostname comparison.
🪄 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: 11810290-a11d-4122-af87-d934ab92cd21

📥 Commits

Reviewing files that changed from the base of the PR and between 3069a16 and c16cebb.

📒 Files selected for processing (2)
  • packages/core/src/pages/api/graphql.ts
  • packages/core/src/sdk/session/index.ts

Comment thread packages/core/src/pages/api/graphql.ts Resolved
- Updated the logic for determining local environment by extracting the hostname from the request headers.
- This change enhances readability and maintains consistent behavior for local development checks.
@pkg-pr-new

pkg-pr-new Bot commented Apr 29, 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: 6eefc18

@eduardoformiga
eduardoformiga merged commit 41a330a into dev May 4, 2026
5 checks passed
@eduardoformiga
eduardoformiga deleted the fix/refresh-token-localhost branch May 4, 2026 14:21
lemagnetic pushed a commit that referenced this pull request May 19, 2026
…hToken hook (#3325)

## What

When `experimental.refreshToken` is enabled in `discovery.config`,
developers could not test logged-in flows on localhost by manually
injecting the `VtexIdclientAutCookie_<account>` cookie. Any SSR query in
`/pvt/account/*` that returned 401/403 redirected to `/pvt/account/403`,
which then fired the `useRefreshToken` hook. That hook POSTs
cross-origin to `${storeUrl}/api/vtexid/refreshtoken/webstore` — and
from `localhost` the `vid_rt` cookie is not sent, so the request always
fails and `logoutAndClearSession` wipes the manually injected auth
cookie.

## Why

The expected behavior — and what was already partially implemented for
`ValidateSession` in #3285 — is that on localhost the refresh-token flow
should be a no-op so developers can drive logged-in flows with an
injected `VtexIdclientAutCookie_<account>` cookie, **regardless of the
`experimental.refreshToken` flag**. The bypass was missing in two paths:

- `useRefreshToken` (client hook called from `/pvt/account/403.tsx`)
- The `needsRefreshToken` decision in `/pvt/account/403.tsx`
`getServerSideProps`

## How

- Adds a shared `isLocalHost` util
(`packages/core/src/utils/isLocalHost.ts`) exposing:
- `isLocalHost(hostname)`: pure helper, `true` for
`localhost`/`127.0.0.1` (case-insensitive). Expects a normalized
hostname (no port) — pairs with the existing `getRequestHostname`
helper.
- `isLocalHostBrowser()`: client-side wrapper that reads
`window.location.hostname`.
- Refactors existing inline copies to use the shared util (no behavior
change):
- `src/sdk/session/index.ts` — drops the local `isLocalEnvironment`
helper.
- `src/pages/api/graphql.ts` — replaces the ad-hoc `host?.split(':')[0]`
with `isLocalHost(getRequestHostname(...))`, picking up
case/whitespace/port normalization for free.
- Closes the remaining gaps (real bug fix):
- `src/sdk/account/useRefreshToken.ts` — bails out and shows the static
403 view on localhost instead of attempting the cross-origin refresh
that would wipe the injected cookie.
- `src/pages/pvt/account/403.tsx` — `getServerSideProps` now also
requires `!isLocal` to set `needsRefreshToken: true`, providing defense
in depth from SSR.

## Tests

- `test/utils/isLocalHost.test.ts` (node, 7 cases): `localhost`,
`127.0.0.1`, case-insensitive, production hostnames, IPv6 loopback (out
of scope), input still carrying a port (contract: caller must
normalize), `null`/`undefined`/`''`.
- `test/utils/isLocalHost.browser.test.ts` (browser, 3 cases): stubs
`window.location.hostname` to validate `isLocalHostBrowser` for
`localhost`, `127.0.0.1` and a production hostname.
- Existing tests in `test/utils/validateSessionRefreshToken.test.ts` and
`test/utils/getRequestHostname.test.ts` continue to pass.

```
 ✓ |node| test/utils/validateSessionRefreshToken.test.ts (6 tests)
 ✓ |node| test/utils/isLocalHost.test.ts (7 tests)
 ✓ |node| test/utils/getRequestHostname.test.ts (12 tests)
 ✓ |browser| test/utils/isLocalHost.browser.test.ts (3 tests)
```

## Test plan

- [ ] In a store with `experimental.refreshToken: true`, run `pnpm dev`
and open `localhost:3000` with a valid `VtexIdclientAutCookie_<account>`
cookie injected via DevTools.
- [ ] Navigate to `/pvt/account/profile`: page should load with the user
data (cookie is honored, no redirect to `/403`).
- [ ] Manually expire/tamper with the cookie to force a 401 on the SSR
profile query: the user lands on `/pvt/account/403` (static view) and
the injected cookie remains in the browser (no `logoutAndClearSession`
round-trip).
- [ ] Repeat with `experimental.refreshToken: false`: behavior on
localhost must be identical (the flag is now a no-op on localhost).
- [ ] On a non-local hostname (e.g. CodeSandbox preview): the existing
refresh-token flow must still trigger as before.

## Related

- Builds on #3285 (which bypassed refresh-token logic for
`ValidateSession` in the SDK and `/api/graphql`) by extending the bypass
to the only two remaining paths.

Made with [Cursor](https://cursor.com)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Introduced a dedicated utility for detecting local development
environments, consolidating localhost identification logic and improving
consistency in how authentication is handled during local development
across the application.

* **Tests**
* Added comprehensive test coverage for localhost detection
functionality in both server-side and browser-side contexts.

<!-- review_stack_entry_start -->

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/vtex/faststore/pull/3325)

<!-- review_stack_entry_end -->

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

3 participants