Repository navigation
fix: bypass refresh-token flow on localhost in 403 page and useRefreshToken hook - #3325
Conversation
…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.
|
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 (7)
WalkthroughThis PR introduces a centralized ChangesLocalhost Detection Centralization
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Possibly related PRs
Suggested labels
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. |
…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.
…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)
What
When
experimental.refreshTokenis enabled indiscovery.config, developers could not test logged-in flows on localhost by manually injecting theVtexIdclientAutCookie_<account>cookie. Any SSR query in/pvt/account/*that returned 401/403 redirected to/pvt/account/403, which then fired theuseRefreshTokenhook. That hook POSTs cross-origin to${storeUrl}/api/vtexid/refreshtoken/webstore— and fromlocalhostthevid_rtcookie is not sent, so the request always fails andlogoutAndClearSessionwipes the manually injected auth cookie.Why
The expected behavior — and what was already partially implemented for
ValidateSessionin #3285 — is that on localhost the refresh-token flow should be a no-op so developers can drive logged-in flows with an injectedVtexIdclientAutCookie_<account>cookie, regardless of theexperimental.refreshTokenflag. The bypass was missing in two paths:useRefreshToken(client hook called from/pvt/account/403.tsx)needsRefreshTokendecision in/pvt/account/403.tsxgetServerSidePropsHow
isLocalHostutil (packages/core/src/utils/isLocalHost.ts) exposing:isLocalHost(hostname): pure helper,trueforlocalhost/127.0.0.1(case-insensitive). Expects a normalized hostname (no port) — pairs with the existinggetRequestHostnamehelper.isLocalHostBrowser(): client-side wrapper that readswindow.location.hostname.src/sdk/session/index.ts— drops the localisLocalEnvironmenthelper.src/pages/api/graphql.ts— replaces the ad-hochost?.split(':')[0]withisLocalHost(getRequestHostname(...)), picking up case/whitespace/port normalization for free.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—getServerSidePropsnow also requires!isLocalto setneedsRefreshToken: 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): stubswindow.location.hostnameto validateisLocalHostBrowserforlocalhost,127.0.0.1and a production hostname.test/utils/validateSessionRefreshToken.test.tsandtest/utils/getRequestHostname.test.tscontinue to pass.Test plan
experimental.refreshToken: true, runpnpm devand openlocalhost:3000with a validVtexIdclientAutCookie_<account>cookie injected via DevTools./pvt/account/profile: page should load with the user data (cookie is honored, no redirect to/403)./pvt/account/403(static view) and the injected cookie remains in the browser (nologoutAndClearSessionround-trip).experimental.refreshToken: false: behavior on localhost must be identical (the flag is now a no-op on localhost).Related
ValidateSessionin the SDK and/api/graphql) by extending the bypass to the only two remaining paths.Made with Cursor
Summary by CodeRabbit
Refactor
Tests