Repository navigation
fix: Enhance session validation logic to skip token refresh in local … - #3285
Conversation
…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.
|
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)
WalkthroughThe GraphQL API handler and session validator now detect local requests by parsing the Host header for Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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. Review rate limit: 0/1 reviews remaining, refill in 60 minutes.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.
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
📒 Files selected for processing (2)
packages/core/src/pages/api/graphql.tspackages/core/src/sdk/session/index.ts
- 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.
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/graphql-utils
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
…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 --> [](https://app.coderabbit.ai/change-stack/vtex/faststore/pull/3325) <!-- review_stack_entry_end --> <!-- end of auto-generated comment: release notes by coderabbit.ai -->
…environments
Summary by CodeRabbit
New Features
Bug Fixes