Skip to content

fix: bypass refresh-token flow on localhost in 403 page and useRefreshToken hook - #3325

Merged
lemagnetic merged 1 commit into
devfrom
fix/refresh-token-localhost-bypass
May 19, 2026
Merged

lemagnetic merged 1 commit into
devfrom
fix/refresh-token-localhost-bypass

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented May 14, 2026 •

Copy link
Copy Markdown
Member

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

Made with Cursor

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 Change Stack

…hToken hook

When `experimental.refreshToken` is enabled, manually injecting a
`VtexIdclientAutCookie_<account>` on localhost was unusable: any SSR query
in `/pvt/account/*` that returned 401/403 redirected to `/pvt/account/403`,
which then fired `useRefreshToken`. That hook POSTs cross-origin to the
production refresh endpoint without the `vid_rt` cookie, so the request
always failed and `logoutAndClearSession` wiped the injected auth cookie.

Centralizes the `localhost`/`127.0.0.1` check in a new `isLocalHost` util
(consolidating the inline copies in `sdk/session` and `api/graphql`) and
extends the bypass to both `useRefreshToken` and the `403.tsx` SSR
`needsRefreshToken` decision so developers can drive logged-in flows from
localhost regardless of the flag.
@eduardoformiga
eduardoformiga requested a review from a team as a code owner May 14, 2026 18:50
@eduardoformiga
eduardoformiga requested review from lariciamota and ommeirelles and removed request for a team May 14, 2026 18:50
@coderabbitai

coderabbitai Bot commented May 14, 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: 496e8c3a-6bc5-48c0-9deb-210996fbe8a1

📥 Commits

Reviewing files that changed from the base of the PR and between 813003e and 4923de5.

📒 Files selected for processing (7)
  • packages/core/src/pages/api/graphql.ts
  • packages/core/src/pages/pvt/account/403.tsx
  • packages/core/src/sdk/account/useRefreshToken.ts
  • packages/core/src/sdk/session/index.ts
  • packages/core/src/utils/isLocalHost.ts
  • packages/core/test/utils/isLocalHost.browser.test.ts
  • packages/core/test/utils/isLocalHost.test.ts

Walkthrough

This PR introduces a centralized isLocalHost utility for localhost hostname detection and refactors refresh-token flow gating across the GraphQL API, SSR pages, and browser session hooks to use the shared utility instead of duplicated inline logic.

Changes

Localhost Detection Centralization

Layer / File(s) Summary
Localhost detection utility
packages/core/src/utils/isLocalHost.ts
New utility exports isLocalHost(hostname) for case-insensitive bare-hostname matching against localhost / 127.0.0.1, and isLocalHostBrowser() wrapper that reads window.location.hostname safely (returns false during SSR/Node).
Utility test coverage
packages/core/test/utils/isLocalHost.test.ts, packages/core/test/utils/isLocalHost.browser.test.ts
Server test suite verifies bare-hostname matching, case-insensitivity, port/IPv6/production/nullish rejection. Browser test suite stubs window.location.hostname and asserts localhost detection and fallback behavior.
API GraphQL endpoint
packages/core/src/pages/api/graphql.ts
ValidateSession operation replaces inline request.headers.host parsing with isLocalHost(getRequestHostname(...)) to gate server-side token-refresh for local requests.
SSR 403 page
packages/core/src/pages/pvt/account/403.tsx
SSR logic imports isLocalHost, computes isLocal from request headers, and gates needsRefreshToken with !isLocal so developers always see the static 403 view on localhost.
Browser session hooks
packages/core/src/sdk/session/index.ts, packages/core/src/sdk/account/useRefreshToken.ts
Session validation and error-handling replace the removed isLocalEnvironment() inline check with the shared isLocalHostBrowser() utility, skipping token refresh for local-browser contexts in both main flow and 401-catch paths.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • vtex/faststore#3285: Both PRs modify GraphQL API and session validation to detect localhost and skip refresh-token logic, though this PR centralizes detection via the new isLocalHost utility.
  • vtex/faststore#3263: Overlaps on refresh-token handling logic (validateSession / error paths) that both PRs refactor, though this PR adds localhost-based gating while the other refactors the core decision/failure behavior.

Suggested labels

hotfix

Suggested reviewers

  • ommeirelles
  • lariciamota

Poem

A localhost helper stands tall and true,
127.0.0.1 skips the token queue,
No more parsing sprawled across the codebase wide—
One utility module, clean and centralized. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 and specifically describes the main change: bypassing the refresh-token flow on localhost in two key locations (403 page and useRefreshToken hook).
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-bypass

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

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.

eduardoformiga added a commit that referenced this pull request May 14, 2026
…hToken hook

When `experimental.refreshToken` is enabled, manually injecting a
`VtexIdclientAutCookie_<account>` on localhost was unusable: any SSR query
in `/pvt/account/*` that returned 401/403 redirected to `/pvt/account/403`,
which then fired `useRefreshToken`. That hook POSTs cross-origin to the
production refresh endpoint without the `vid_rt` cookie, so the request
always failed and `logoutAndClearSession` wiped the injected auth cookie.

Centralizes the `localhost`/`127.0.0.1` check in a new `isLocalHost` util
(consolidating the inline copies in `sdk/session` and `api/graphql`) and
extends the bypass to both `useRefreshToken` and the `403.tsx` SSR
`needsRefreshToken` decision so developers can drive logged-in flows from
localhost regardless of the flag.

Backport of the fix targeting `dev` (PR #3325) to the `3.x` release line.
@lemagnetic
lemagnetic merged commit d48571a into dev May 19, 2026
5 checks passed
@lemagnetic
lemagnetic deleted the fix/refresh-token-localhost-bypass branch May 19, 2026 17:37
lemagnetic pushed a commit that referenced this pull request May 19, 2026
…hToken hook (#3326)

Backport of #3325 (targeting `dev`) to the `3.x` release line.

## 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 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**. Part of the bypass was already in
place for `ValidateSession` in the SDK and `/api/graphql`; this PR
extends it to the only two remaining 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) — callers strip the port with `host?.split(':')[0]`.
- `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` — uses
`isLocalHost(request.headers.host?.split(':')[0])`.
- 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.

## Diff vs the `dev` PR

The only adaptations needed for the 3.x port:
- 3.x has no standalone `src/utils/getRequestHostname.ts`, so the
API/SSR call sites strip the port inline with `host?.split(':')[0]` (the
`isLocalHost` helper already lowercases the input).
- Tests use Jest (instead of Vitest on `dev`): no `import { describe,
it, expect } from 'vitest'`, and the browser test uses the `/**
@jest-environment jsdom */` pragma.

## 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` (jsdom, 3 cases): stubs
`window.location.hostname` to validate `isLocalHostBrowser` for
`localhost`, `127.0.0.1` and a production hostname.
- Existing `test/utils/validateSessionRefreshToken.test.ts` continues to
pass.

## 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

- Companion PR targeting `dev`: #3325

Made with [Cursor](https://cursor.com)
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