Skip to content

fix(core): bypass refresh-token flow on WebOps preview hosts - #3533

Merged
eduardoformiga merged 6 commits into
devfrom
fix/bypass-refresh-token-on-preview
Oct 28, 2026
Merged

eduardoformiga merged 6 commits into
devfrom
fix/bypass-refresh-token-on-preview

Conversation

@lariciamota

@lariciamota lariciamota commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What's the purpose of this pull request?

Pasting a VtexIdclientAutCookie_<account> into a WebOps preview to test logged-in areas should work with just the paste.

Right now, with experimental.refreshToken on, the first ValidateSession after the paste fails: there is a JWT and no refreshAfter, so /api/graphql answers 401. The client then calls /api/vtexid/refreshtoken/webstore. Previews do not proxy VTEX ID, so that call answers 405, the refresh fails, and logoutAndClearSession calls /api/fs/logout, which deletes the pasted cookie. The current workarounds are setting refreshAfter by hand in IndexedDB or blocking /api/fs/logout in devtools.

Localhost already skips this flow (#3325). This PR extends the same bypass to *.preview.vtex.app.

How it works?

  • New src/utils/shouldBypassRefreshToken.ts with shouldBypassRefreshToken(hostname) and shouldBypassRefreshTokenBrowser(). They return true for localhost / 127.0.0.1 (via isLocalHost) and for hosts ending in .preview.vtex.app.
  • On the server, shouldBypassRefreshTokenForRequest(headers) checks the Host header and a single x-forwarded-host, because the preview ingress sends the browser host in x-forwarded-host.
  • {account}.vtex.app does not match. It is a production default domain and keeps the refresh flow.
  • The helper replaces isLocalHost / isLocalHostBrowser at the five places that skip the refresh flow:
    • src/pages/api/graphql.ts: forced 401 on ValidateSession
    • src/sdk/session/index.ts: refresh when refreshAfter expired, and refresh after a 401
    • src/sdk/account/useRefreshToken.ts
    • src/pages/pvt/account/403.tsx: needsRefreshToken
  • isLocalHost stays as it is for other uses.

Security notes

  • On the server the host comes from the Host header or a single x-forwarded-host, and a client controls both. Sending Host: x.preview.vtex.app (or that x-forwarded-host) to a production store only skips the forced 401 on ValidateSession. That is already possible today with Host: localhost, and it grants nothing: the JWT is still validated upstream.
  • On previews an expired auth cookie is no longer refreshed. The refresh can't work there anyway, since VTEX ID isn't proxied.

How to test it?

  1. Open a WebOps preview of a store with experimental.refreshToken: true.
  2. Paste a valid VtexIdclientAutCookie_<account> and reload.
  3. The session stays logged in. No call to /api/vtexid/refreshtoken/webstore and no /api/fs/logout.
  4. On the production domain (custom domain or {account}.vtex.app) the refresh flow behaves as before.

Unit tests:

  • test/utils/shouldBypassRefreshToken{,.browser}.test.ts: localhost, 127.0.0.1, preview host, {account}.vtex.app → false, custom domain → false, lookalike suffixes → false
  • test/pages/api/graphql.test.ts: ValidateSession is not forced to 401 on local/preview hosts and still is on production hosts
  • test/sdk/session/validateSession.browser.test.ts: both refresh paths skip on local/preview hosts and still run on production hosts
  • test/sdk/account/useRefreshToken.browser.test.ts (new): no refresh or logout on local/preview hosts
  • test/pages/pvt/account/403.test.ts (new): needsRefreshToken is false on local/preview hosts

Approval

This touches the authentication flow. Per AGENTS.md (Security & Data Handling), this change was explicitly approved by Larícia Mota on 2026-10-21.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved refresh-token handling across local development and WebOps preview environments.
    • Prevented unnecessary refresh attempts and session clearing where refresh endpoints cannot be proxied.
    • Preserved refresh-token enforcement for production environments.
  • Tests

    • Added coverage for refresh behavior across local, preview, production, browser, and server-side scenarios.

WebOps previews (`*.preview.vtex.app`) do not proxy VTEX ID, so
`/api/vtexid/refreshtoken/webstore` answers 405 there. With
`experimental.refreshToken` on, the first ValidateSession after pasting a
`VtexIdclientAutCookie_<account>` forced a refresh, the refresh failed and
`logoutAndClearSession` wiped the pasted cookie.

Add `shouldBypassRefreshToken` (plus a browser variant) that matches
localhost/127.0.0.1 and `*.preview.vtex.app`, and use it wherever the
refresh flow was skipped only for localhost: the ValidateSession guard in
`/api/graphql`, both refresh paths in `validateSession`, `useRefreshToken`
and the 403 page. `{account}.vtex.app` stays out of the bypass because it is
a production default domain.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lariciamota
lariciamota requested a review from a team as a code owner October 21, 2026 14:01
@lariciamota
lariciamota requested review from ommeirelles and renatamottam and removed request for a team October 21, 2026 14:01
@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: vtex/faststore/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Essentials
  • Run ID: 6c3b5be0-cbcb-4ea8-be5f-15f56269cf75
📥 Commits

Reviewing files that changed from the base of the PR and between 3f09177 and 0c8db36.

📒 Files selected for processing: 12
  • 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/src/utils/shouldBypassRefreshToken.ts
  • packages/core/test/pages/api/graphql.test.ts
  • packages/core/test/pages/pvt/account/403.test.ts
  • packages/core/test/sdk/account/useRefreshToken.browser.test.ts
  • packages/core/test/sdk/session/validateSession.browser.test.ts
  • packages/core/test/utils/shouldBypassRefreshToken.browser.test.ts
  • packages/core/test/utils/shouldBypassRefreshToken.test.ts

Included review availability: This review used your included allowance. 4 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour.

Walkthrough

Refresh-token bypass checks now include local and WebOps preview hosts. Server-side validation and browser refresh flows use the shared hostname rules, with tests covering preview and production behavior.

Changes

Refresh-token bypass

Layer / File(s) Summary
Hostname bypass rules
packages/core/src/utils/shouldBypassRefreshToken.ts, packages/core/src/utils/isLocalHost.ts, packages/core/test/utils/*
The new helpers bypass refresh-token handling for local and case-insensitive .preview.vtex.app hosts. They return false for nullish inputs and during server-side rendering. Tests cover preview, production, custom, and malformed hostnames.
Server-side validation
packages/core/src/pages/api/graphql.ts, packages/core/src/pages/pvt/account/403.tsx, packages/core/test/pages/api/graphql.test.ts, packages/core/test/pages/pvt/account/403.test.ts
GraphQL ValidateSession enforcement and the account 403 page use the hostname bypass rule. Tests verify bypass on local and preview hosts and refresh enforcement on production hosts.
Browser refresh flows
packages/core/src/sdk/account/useRefreshToken.ts, packages/core/src/sdk/session/index.ts, packages/core/test/sdk/account/useRefreshToken.browser.test.ts, packages/core/test/sdk/session/validateSession.browser.test.ts
Account refresh and session validation use the browser bypass helper. Tests verify that local and preview hosts skip refresh, while production hosts retain refresh behavior.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related issues

  • vtex/faststore-ai-native#1085 — The issue proposes mock shopper sessions for authenticated previews. This PR does not add mock sessions, but it bypasses refresh attempts on preview hosts.
Merge Risk: ⚪ Minimal · up to 0c8db

No actionable merge-blocking issue was established. The preview bypass can proceed through normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed 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 clearly summarizes the main change: extending the refresh-token bypass to WebOps preview hosts.
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.
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

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

@dk-pr-review

dk-pr-review Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

DK Review — Audit Summary

Verdict: ❌ BLOCKED

Severity Count
BLOCK 1
RESTRICT 1
SUGGEST 1

Only BLOCK and RESTRICT findings anchored to a changed line are commented inline on the diff. The other finding below opens no review thread.

Scenarios evaluated: feature-flags, general-review, quality-ratchet
Scenarios skipped: dependency-governance (no matching files), pipeline-config (no matching files), agent-skills-review (no matching files)

⚠️ Governance warnings: Large PR detected (13 files) — review coverage may be incomplete


📋 Findings (3)

BLOCK

  1. [Functional.Check] packages/core/test/utils/shouldBypassRefreshToken.test.ts:68 — The new refresh-token/401 bypass logic trusts the client-supplied x-forwarded-host header to decide whether a request is 'behind the preview ingress' (see the 'returns true when the preview host arrives in x-forwarded-host' test), but no test exercises the case where an untrusted caller sends an arbitrary host (not the internal ingress hostname) together with a spoofed x-forwarded-host: *.preview.vtex.app. If the implementation does not independently verify the request actually came through the trusted ingress (e.g. by checking host against a known internal value or a signed/allow-listed proxy), an external attacker can forge this header to bypass the forced 401 / refresh-token enforcement on a production store.
    → Add a test asserting that shouldBypassRefreshTokenForRequest returns false when x-forwarded-host is a preview/local host but the raw host is NOT the trusted internal ingress hostname, and confirm the implementation validates the caller is the trusted proxy before honoring x-forwarded-host for this security decision.

RESTRICT

  1. [Functional.Support] packages/core/test/pages/api/graphql.test.ts:242 — This PR changes session/authentication enforcement behavior (when a 401 is forced for ValidateSession, and when refresh-token requests are triggered based on host). Root AGENTS.md states: 'Modifications to authentication, CSRF, or CSP mechanisms require explicit human approval recorded in the PR description.' There is no indication in the provided diff that such approval was recorded.
    → Confirm the PR description records explicit human approval for this change to the session-validation/refresh-token bypass mechanism, per the repo's Security & Data Handling policy.

SUGGEST

  1. [Evolvability.Organizational] packages/core/test/sdk/account/useRefreshToken.browser.test.ts:21 — The stubHostname helper (with its jsdom window.location workaround and identical comment) is duplicated verbatim across at least three test files: useRefreshToken.browser.test.ts, shouldBypassRefreshToken.browser.test.ts, and validateSession.browser.test.ts.
    → Extract stubHostname into a shared test utility (e.g. test/utils/stubHostname.ts) and import it from each browser test file.

DK Review v1.0.0 | To dismiss a finding: reply /dk-review dismiss [reason] under its comment

…Session

Sonar flagged the cognitive complexity of the `/api/graphql` handler (26)
and `validateSession` (20). Move the ValidateSession refresh-token guard
and the success cache-control into their own functions in the handler, and
the refresh-token condition and deliveryPromise postal-code sync into their
own functions in the session SDK. The guard now checks the operation and
the flag before parsing the hostname.

Also read `globalThis.window` in the browser bypass helper, normalize the
hostname once, and drop `isLocalHostBrowser`, which has no callers left.
Add tests for the success cache-control paths that moved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@pkg-pr-new

pkg-pr-new Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@c45bf44

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@c45bf44

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@c45bf44

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@c45bf44

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@c45bf44

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@c45bf44

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@c45bf44

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@c45bf44

commit: c45bf44

Behind the WebOps preview ingress the browser host arrives in
`x-forwarded-host`, not `Host`, so the server-side checks in
`/api/graphql` and the account 403 page could miss a preview and still
force the refresh. `shouldBypassRefreshTokenForRequest` checks both
headers (a multi-value `x-forwarded-host` is ignored).

The hostname check now reuses `isHostAllowed` and ignores a trailing dot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each beforeEach waited for a request call that only earlier tests or the
module load had made. A top-level beforeAll now waits for the initial
validation once, and each test resets the request mock explicitly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
lariciamota added a commit that referenced this pull request Oct 26, 2026
#3525 adds `isB2BSession` to `src/sdk/account/refreshToken`, which the
#3533 tests mock without it. Whichever of the two merges second needs
the same mock change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sonar-workflows

Copy link
Copy Markdown

@eduardoformiga eduardoformiga left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@eduardoformiga
eduardoformiga merged commit a298a71 into dev Oct 28, 2026
14 of 16 checks passed
@eduardoformiga
eduardoformiga deleted the fix/bypass-refresh-token-on-preview branch October 28, 2026 21:09
@eduardoformiga eduardoformiga mentioned this pull request Oct 29, 2026
2 of 7 tasks
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