Skip to content

feat: Password Protection (v4) - #3276

Merged
eduardoformiga merged 13 commits into
devfrom
feat/password-protection
Jun 17, 2026
Merged

eduardoformiga merged 13 commits into
devfrom
feat/password-protection

Conversation

@vlaux

@vlaux vlaux commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

FAS-930

What's the purpose of this pull request?

Store deployments frequently expose preview URLs to external audiences during development and testing phases. This creates multiple security and usability concerns:

  • SEO Indexing Issues: Search engines can index preview URLs, leading to duplicate content and rankings degradation
  • Consumer Confusion: Customers may attempt to purchase from preview URLs instead of production stores
  • Information Disclosure: Unreleased products, features, or sensitive configurations may become visible to unintended audiences
  • Operational Friction: Commerce developers currently require manual password protection setup at provider level (e.g., Vercel), creating implementation burden

How it works?

Merchants set up password protection settings to their builds, which can be applied to default domains (*.vtex.app) or custom domains (mystore.com).

How to test it?

Password protection setup on WebOps: https://vtexgame1.myvtex.com/admin/webops/settings
Running store: https://vtexgame1.vtex.app/ (password is 123)

Starters Deploy Preview

References

RFC: https://docs.google.com/document/d/1rOwddxX8V08cY-lhJR6VqQ1g-oznJ1dBuNMTCJtO7FI/edit?tab=t.ftdefyeg4z3l#heading=h.n2j25ht9xpmm

Checklist

You may erase this after checking them all 😉

PR Title and Commit Messages

  • PR title and commit messages follow the Conventional Commits specification
    • Available prefixes: feat, fix, chore, docs, style, refactor, ci and test

PR Description

  • Added a label according to the PR goal - breaking change, bug, contributing, performance, documentation..

Dependencies

  • Committed the pnpm-lock.yaml file when there were changes to the packages

Documentation

  • PR description
  • For documentation changes, ping @Mariana-Caetano to review and update (Or submit a doc request)

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a password-protection login page for gated storefront access.
    • Added a new unlock endpoint to validate passwords, set a secure session cookie, and return a safe redirect URL.
  • Improvements

    • Enhanced request protection behavior in the storefront middleware (including root routing coverage and cookie handling).
    • Simplified CLI dev/build flow by removing localization-based proxy toggling.
  • Testing

    • Expanded automated coverage for URL generation, unlock responses, proxy behavior, and password-protection service scenarios.

@codesandbox-ci

codesandbox-ci Bot commented Apr 15, 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 commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The PR removes the CLI's localization-based proxy filename toggling (toggleProxyByLocalizationFlag) from build and dev commands, then introduces a complete password-protection auth system in packages/core: WebOps endpoint URL helpers, a PasswordProtectionService with RSA JWT verification and renewal, async proxy middleware integration, a /api/fs/password-protection/unlock API route, a login page with styles, an UnlockResponse type guard, and comprehensive Vitest test coverage for all components.

Changes

CLI proxy toggle removal

Layer / File(s) Summary
Remove proxy toggle and CLI references
packages/cli/src/utils/generate.ts, packages/cli/src/commands/build.ts, packages/cli/src/commands/dev.ts
Deletes DISABLED_PROXY_FILENAME constant, moveSync import, and exported toggleProxyByLocalizationFlag function from generate.ts; removes Discovery config lookups and proxy toggle calls from build.ts and dev.ts command runners.

Password-protection auth system in core

Layer / File(s) Summary
Dependencies and WebOps URL helpers
packages/core/package.json, packages/components/package.json, packages/core/src/server/password-protection/webops-api.ts, packages/core/test/server/webops-api.test.ts
Adds jose ^6.2.3 dependency for JWT operations; catalog-aligns @testing-library/jest-dom across packages; introduces webops-api.ts module with environment-based origin construction, four endpoint URL factories (publicKeyUrl, protectionStatusUrl, sessionUrl, renewUrl), and passwordProtectionTimeouts constants; comprehensive Vitest test coverage validates origin normalization, trailing-slash stripping, scheme enforcement, and timeout constants.
UnlockResponse type guard
packages/core/src/utils/unlockResponse.ts, packages/core/test/utils/unlockResponse.test.ts
Adds UnlockResponse interface with optional success, redirectUrl, error fields; implements isUnlockResponse runtime type guard for validating API response shapes; test suite covers invalid types, missing fields, and valid payloads.
PasswordProtectionService implementation and tests
packages/core/src/server/password-protection-service.ts, packages/core/test/server/password-protection-service.test.ts
Implements RSA public-key fetch with 1-hour caching, JWT signature verification against store ID, expired token renewal via WebOps, fallback to protection-status endpoint, domain eligibility logic for default and custom domains, __fs_password_protection cookie helpers, and fail-closed redirects. Test suite validates development bypass, protection status decisions, JWT caching/reuse, expiry renewal flows, scope-based host eligibility, custom-domain environment gating, and error handling.
Proxy middleware password-protection integration
packages/core/src/proxy.ts, packages/core/test/proxy.test.ts
Refactors proxy() to async; constructs PasswordProtectionService and calls checkStoreProtection() with exception handling; short-circuits non-200 protection responses; extracts localizationRewrite() helper; copies protection cookies onto rewritten responses; updates config.matcher to include root '/' and broaden exclusions for password-protection, unlock route, and partytown. Tests verify error responses, redirects, cookie forwarding, and matcher patterns.
Unlock API route
packages/core/src/pages/api/fs/password-protection/unlock.ts, packages/core/test/pages/api/unlock.test.ts
Adds POST handler validating method and password body; calls WebOps session endpoint with timeout; maps upstream 401/403 to 401 Invalid password and other failures to 503; validates JSON payload shape; sets HttpOnly cookie with TTL; sanitizes returnTo parameter; returns 200 with redirect URL on success. Test suite covers HTTP methods, input validation, upstream error mapping, payload validation, cookie/redirect behavior, and unsafe returnTo sanitization.
Password-protection login page and styles
packages/core/src/pages/password-protection/index.tsx, packages/core/src/pages/password-protection/password-protection.module.scss, packages/core/test/pages/password-protection.browser.test.tsx
Adds PasswordProtectionLogin page component with password state, POST to unlock API, isUnlockResponse validation, redirect on success, and noindex meta tag; SCSS module provides flex centering and Faststore UI atom/molecule styles; browser test suite verifies rendering, form submission, error display, returnTo sanitization, fallback messages, and network failure handling.

Sequence Diagram

sequenceDiagram
  actor User
  participant LoginPage as PasswordProtectionLogin
  participant UnlockAPI as POST /api/fs/password-protection/unlock
  participant WebOps as WebOps Session Endpoint
  participant ProxyMW as proxy() middleware
  participant PPS as PasswordProtectionService

  User->>LoginPage: Enter password
  LoginPage->>UnlockAPI: POST { password } with returnTo query
  UnlockAPI->>WebOps: POST sessionUrl() with storeId, timeout
  alt 401/403 from WebOps
    WebOps-->>UnlockAPI: 401 Unauthorized
    UnlockAPI-->>LoginPage: 401 Invalid password
  else non-ok upstream
    WebOps-->>UnlockAPI: 5xx or other
    UnlockAPI-->>LoginPage: 503 Service temporarily unavailable
  else success
    WebOps-->>UnlockAPI: { valid: true, token }
    UnlockAPI->>UnlockAPI: Set __fs_password_protection cookie
    UnlockAPI-->>LoginPage: 200 { success: true, redirectUrl }
    LoginPage->>User: location.href = redirectUrl
  end

  Note over ProxyMW,PPS: On subsequent requests to protected store
  ProxyMW->>PPS: new PasswordProtectionService()
  ProxyMW->>PPS: checkStoreProtection(request)
  alt Valid JWT in cookie
    PPS->>PPS: jwtVerify with cached RSA public key
    PPS-->>ProxyMW: NextResponse.next() + cookie
    ProxyMW->>ProxyMW: localizationRewrite + copy cookies
  else No/invalid/expired JWT
    PPS-->>ProxyMW: 307 redirect to /password-protection
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Suggested reviewers

  • lemagnetic
  • hellofanny

Poem

🔐 The proxy no longer shuffles its name,
A new JWT guard joins the game—
WebOps hands keys, RSA locks tight,
Cookies and redirects working right.
Password-protection, scoped and secure,
Your store's front door is now pure! 🛡️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.34% 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 'feat: Password Protection (v4)' clearly identifies the main feature being added—password protection for VTEX FastStore deployments. It accurately summarizes the primary changeset objective.
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 feat/password-protection

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.

@vlaux vlaux changed the title Password Protected stores feat: password protected stores Apr 15, 2026
@vlaux
vlaux force-pushed the feat/password-protection branch from e24ed72 to d4400ee Compare April 15, 2026 17:33

@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: 11

🤖 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/middleware.ts`:
- Around line 45-55: The redirect branch in middleware.ts drops cookies set
during authentication (from authenticateRequest() / authResult.response), so
when a token is renewed the new Set-Cookie is not forwarded; modify the redirect
handling to detect authResult.response (or any response returned by
authenticateRequest()) and copy its Set-Cookie header(s) into the redirect
response before returning it—e.g., read
authResult.response.headers.getAll('set-cookie') or the single 'set-cookie'
value and append each to the NextResponse.redirect() result (or use
response.cookies.set if available) so the renewed auth cookie is carried over
with the redirect.
- Around line 34-62: Move the authentication call (new
AuthenticationService().authenticateRequest(request)) out of the outer try/catch
so auth errors are not swallowed; if authenticateRequest throws, return a
failing auth response (do not return NextResponse.next()) or let the error
propagate to produce a non-public response. Wrap only the redirect lookup
(redirectsClient.get(path) and subsequent URL/NextResponse.redirect logic) in a
try/catch and on redirect lookup failure fall back to returning
authResult.response; keep references to AuthenticationService,
authenticateRequest, redirectsClient.get, NextResponse.redirect, and
NextResponse.next() to locate the code to change.

In `@packages/core/src/pages/api/fs/auth/login.ts`:
- Around line 43-49: The current login handler treats any non-2xx webopsResponse
as "Invalid password"; update the error handling in the block that checks
webopsResponse (the variable webopsResponse used in the login function) to
inspect webopsResponse.status and only return 401 (or 403 if you prefer) for
explicit auth failures (status === 401 or status === 403) with the existing
invalid-credentials payload, while returning a 503 Service Unavailable (and a
generic upstream error payload) for all other 5xx/non-auth statuses so upstream
outages are not misclassified as bad credentials.
- Around line 53-69: The handler currently echoes the user-supplied returnTo
query into the JSON redirectUrl (variable returnTo) which permits
open-redirects; validate and sanitize returnTo before reflecting it by allowing
only same-site absolute paths (e.g. non-empty string that starts with a single
'/' but not '//' and contains no scheme or host), otherwise fallback to '/';
perform validation where returnTo is computed and use the sanitized value in
response.status(200).json({ redirectUrl: sanitizedReturnTo }), keeping the
existing cookie logic (COOKIE_NAME, TOKEN_TTL_SECONDS,
isSecureAuthCookieForPagesApi, response.setHeader) unchanged.

In `@packages/core/src/pages/fs-auth-login/index.tsx`:
- Around line 1-3: The login page must be marked non-indexable by search
engines; update the FS auth page component in this file to include a robots meta
tag. Import Head from 'next/head' and add <meta name="robots"
content="noindex,nofollow" /> inside the page component's returned JSX (the
default exported component in this module that renders the Button/InputField
form), ensuring the meta tag appears alongside other head elements so crawlers
see it for this public route.

In `@packages/core/src/server/authentication-service.ts`:
- Around line 94-97: The code currently treats a valid token with
verification.payload.protected === false as a long-lived negative cache and
immediately returns NextResponse.next(), which allows visitors to bypass
newly-enabled protection for TOKEN_TTL_SECONDS; modify the logic in
authentication-service.ts (the block handling verification.valid &&
verification.payload) to recheck current protection state instead of trusting a
false protected flag—call the same protection-check routine used for new
requests (or fetch latest merchant protection setting) and only return
NextResponse.next() when both the token is valid and the current protection is
disabled, otherwise proceed to enforce protection (e.g., clear the cookie or
redirect to login). Ensure references to verification.payload.protected,
TOKEN_TTL_SECONDS, and the NextResponse.next() return path are updated
accordingly.
- Around line 114-127: Normalize the Host header before checking for the default
domain: in shouldCheckProtection(request: NextRequest) (and likewise in
shouldProtectDomain(request: NextRequest)) read request.headers.get('host') into
a variable, lower-case it and strip any port portion (e.g.
host.split(':')[0].trim().toLowerCase()), then use that
normalizedHost.endsWith('.vtex.app') instead of the raw header; update both
methods to use the same normalization logic to ensure hosts like
"preview.vtex.app:443" or mixed-case values are handled correctly.
- Around line 268-270: The redirectToLogin method currently sets returnTo to
only request.nextUrl.pathname, losing query parameters; update redirectToLogin
(the method named redirectToLogin in authentication-service.ts) to include the
full path+query by appending request.nextUrl.search (e.g., use
request.nextUrl.pathname + request.nextUrl.search or otherwise serialize the
original nextUrl) when setting loginUrl.searchParams.set('returnTo', ...), so
requests like /search?term=chair&page=2 preserve their query string through the
/fs-auth-login redirect.

In `@packages/core/src/server/password-protection/auth-cookie.ts`:
- Around line 4-9: The isLocalHost function misparses bracketed IPv6 addresses
like "[::1]:3000" because splitting on ':' yields '['; update isLocalHost to
detect and handle bracketed IPv6 first: if host starts with '[' extract the
substring between '[' and ']' as the hostname, otherwise split on ':' and take
the first segment; normalize to lower-case and then check against 'localhost',
'127.0.0.1', '::1' and '[::1]' (or simply strip brackets before comparison) so
IPv6 loopback is correctly recognized and Secure cookies are disabled on
localhost IPv6.

In `@packages/core/src/server/password-protection/webops-api.ts`:
- Around line 16-19: The protectionStatusUrl is built by interpolating
discoveryConfig.api.storeId into the query string which can break for reserved
characters; update the construction of protectionStatusUrl to create the base
URL with origin and pathname, then set the storeId using URL.searchParams (e.g.,
call protectionStatusUrl.searchParams.set('storeId',
discoveryConfig.api.storeId)) so the storeId is properly URL-encoded; locate the
symbol protectionStatusUrl and the referenced discoveryConfig.api.storeId and
replace the current template-string-based URL construction with creation +
searchParams.set.
- Around line 5-9: The code currently assigns origin using the
nullish-coalescing operator which lets an all-whitespace WEBOPS_API_URL become
an empty string and produce an invalid URL; update the logic that computes
origin (the variable named origin and the env var WEBOPS_API_URL) to treat a
trimmed empty string as unset by checking for a non-empty trimmed value (e.g.,
compute a trimmed value into a temp like raw =
process.env.WEBOPS_API_URL?.trim().replaceAll(/\/+$/g, '') and then use origin =
raw && raw.length ? raw : DEFAULT_WEBOPS_ORIGIN) and keep the existing
origin.startsWith('http') normalization to prepend https:// when needed.
🪄 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: 37f3a60c-d19f-41d9-b5df-37e31de47d69

📥 Commits

Reviewing files that changed from the base of the PR and between ea8071b and d4400ee.

⛔ Files ignored due to path filters (2)
  • .gitignore is excluded by none and included by none
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (12)
  • packages/cli/src/utils/generate.ts
  • packages/core/package.json
  • packages/core/src/middleware.ts
  • packages/core/src/middleware__DISABLED.ts
  • packages/core/src/pages/api/fs/auth/login.ts
  • packages/core/src/pages/fs-auth-login/fs-auth-login.module.scss
  • packages/core/src/pages/fs-auth-login/index.tsx
  • packages/core/src/server/authentication-service.ts
  • packages/core/src/server/password-protection/auth-cookie.ts
  • packages/core/src/server/password-protection/webops-api.ts
  • packages/core/test/server/authentication-service.test.ts
  • packages/core/test/server/password-protection/auth-cookie.test.ts
💤 Files with no reviewable changes (2)
  • packages/cli/src/utils/generate.ts
  • packages/core/src/middleware__DISABLED.ts

Comment thread packages/core/src/middleware.ts Resolved
Comment thread packages/core/src/middleware.ts Resolved
@vlaux
vlaux force-pushed the feat/password-protection branch 2 times, most recently from fa49b7b to 9c7f6de Compare April 17, 2026 19:06
@vlaux vlaux added enhancement New feature or request contributing Pull request submitted by the community labels Apr 17, 2026
@vlaux
vlaux force-pushed the feat/password-protection branch from 2f70225 to 4850045 Compare April 22, 2026 18:57
@vlaux
vlaux marked this pull request as ready for review April 23, 2026 11:04
@vlaux
vlaux requested a review from a team as a code owner April 23, 2026 11:04
@vlaux
vlaux requested review from ommeirelles and renatamottam and removed request for a team April 23, 2026 11:04

@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

🧹 Nitpick comments (2)
packages/core/src/server/authentication-service.ts (2)

96-114: Flatten the valid-token branch — three NextResponse.next() paths collapse into one.

Once a token is verified for this store, every sub-branch (unprotected payload, out-of-scope domain, in-scope protected) returns NextResponse.next(). The intermediate conditionals are dead logic and add cognitive load. As per coding guidelines ("Prefer flat conditionals over nested ifs"), this reads better as an early return.

♻️ Proposed refactor
     if (token) {
       const verification = await this.verifyToken(token)
 
       if (verification.valid && verification.payload) {
-        if (!verification.payload.protected) {
-          return { response: NextResponse.next() }
-        }
-
-        if (!this.shouldProtectDomain(request, verification.payload.scope)) {
-          return { response: NextResponse.next() }
-        }
-
         return { response: NextResponse.next() }
       }
 
       if (verification.expired && verification.payload) {
         return await this.tryRenewSession(request, token, verification.payload)
       }
     }

If those intermediate checks were meant to trigger cookie cleanup or a different response path, the intent isn't visible in the current code — worth either wiring that in or removing the branches.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/server/authentication-service.ts` around lines 96 - 114, In
verifyToken handling inside the authentication flow, collapse the nested
valid-token branches: when verification.valid && verification.payload is true,
immediately return NextResponse.next() instead of checking
verification.payload.protected and shouldProtectDomain(request,
verification.payload.scope) since all three branches currently return the same
value; remove the dead conditionals in the valid branch in
authentication-service.ts (around the verifyToken usage) so the code reads an
early return, and keep the expired-path logic that calls
tryRenewSession(request, token, verification.payload) intact.

161-188: Double as unknown as TokenPayload coerces without validating.

jwtVerify returns JWTPayload, and decodeJwt even more so — nothing guarantees storeId/protected/scope are the expected types at runtime. A malformed token could slip past payloadMatchesStore (e.g. storeId as a number coerced, or protected as a truthy string). Per coding guidelines, prefer runtime validation over type assertions for untrusted inputs.

♻️ Sketch
function toTokenPayload(payload: JWTPayload): TokenPayload | null {
  if (typeof payload.storeId !== 'string') return null
  if (typeof payload.protected !== 'boolean') return null
  if (payload.scope !== undefined && typeof payload.scope !== 'string') return null
  return payload as TokenPayload
}

Then use toTokenPayload(...) in both verifyToken success and expired paths and fail closed when it returns null.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/core/src/server/authentication-service.ts` around lines 161 - 188,
The code currently coerces untrusted JWT payloads with "as unknown as
TokenPayload"; add a runtime validator (e.g., toTokenPayload(payload:
JWTPayload): TokenPayload | null) that checks typeof payload.storeId ===
'string', typeof payload.protected === 'boolean', and payload.scope is undefined
or a string, then use that validator in both the jwtVerify success path and the
decodeJwt expired path (replace the double casts) and return failure (valid:
false) when the validator returns null; reference jwtVerify, decodeJwt,
isJwtExpiredError, and payloadMatchesStore to locate where to plug the validator
and to keep the existing store-matching logic.
🤖 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/server/authentication-service.ts`:
- Around line 84-87: getNormalizedHost currently splits the host on ':' which
breaks for bracketed IPv6 like "[::1]:8080"; update
getNormalizedHost(NextRequest) to handle bracketed IPv6 by detecting if hostname
startsWith('[') and, in that case, extract the text between the first '[' and
the matching ']' (dropping any trailing :port), otherwise strip the port by
cutting at the last ':' (use lastIndexOf) to avoid splitting hostnames with
colons; then trim and toLowerCase the result so downstream checks (e.g.,
endsWith('.vtex.app')) work correctly.

---

Nitpick comments:
In `@packages/core/src/server/authentication-service.ts`:
- Around line 96-114: In verifyToken handling inside the authentication flow,
collapse the nested valid-token branches: when verification.valid &&
verification.payload is true, immediately return NextResponse.next() instead of
checking verification.payload.protected and shouldProtectDomain(request,
verification.payload.scope) since all three branches currently return the same
value; remove the dead conditionals in the valid branch in
authentication-service.ts (around the verifyToken usage) so the code reads an
early return, and keep the expired-path logic that calls
tryRenewSession(request, token, verification.payload) intact.
- Around line 161-188: The code currently coerces untrusted JWT payloads with
"as unknown as TokenPayload"; add a runtime validator (e.g.,
toTokenPayload(payload: JWTPayload): TokenPayload | null) that checks typeof
payload.storeId === 'string', typeof payload.protected === 'boolean', and
payload.scope is undefined or a string, then use that validator in both the
jwtVerify success path and the decodeJwt expired path (replace the double casts)
and return failure (valid: false) when the validator returns null; reference
jwtVerify, decodeJwt, isJwtExpiredError, and payloadMatchesStore to locate where
to plug the validator and to keep the existing store-matching logic.
🪄 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: 74cf2e96-ce7f-4ae5-8e30-91aab1c3c32f

📥 Commits

Reviewing files that changed from the base of the PR and between d4400ee and 4850045.

📒 Files selected for processing (6)
  • packages/core/src/middleware.ts
  • packages/core/src/pages/api/fs/auth/login.ts
  • packages/core/src/pages/fs-auth-login/index.tsx
  • packages/core/src/server/authentication-service.ts
  • packages/core/src/server/password-protection/auth-cookie.ts
  • packages/core/src/server/password-protection/webops-api.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/core/src/middleware.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/core/src/pages/fs-auth-login/index.tsx
  • packages/core/src/server/password-protection/auth-cookie.ts
  • packages/core/src/server/password-protection/webops-api.ts

@eduardoformiga
eduardoformiga force-pushed the dev branch 2 times, most recently from 6c7ef8e to 4d4ac3a Compare May 7, 2026 15:18
@renatamottam
renatamottam removed their request for review May 13, 2026 13:13
@lemagnetic

Copy link
Copy Markdown
Contributor

hey @vlaux

dev already has V4, so this branch needs an update with dev, there’s a conflict in packages/cli/src/utils/generate.ts.

In V4, edge handling moved from middleware to proxy.ts. Localization rewrites run there, and the CLI toggles it on/off (proxy.ts <> proxy__DISABLED.ts via toggleProxyByLocalizationFlag in generate). This PR still uses middleware.ts, which no longer matches dev.

Could you rebase/merge dev and reimplement password protection in proxy, so it works alongside the localization proxy? Thanks!

@vlaux
vlaux force-pushed the feat/password-protection branch from 4850045 to a0ffc70 Compare May 27, 2026 15:33
@vlaux vlaux changed the title feat: password protected stores feat: Password Protection (v4) May 27, 2026
@pkg-pr-new

pkg-pr-new Bot commented May 27, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

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

@faststore/cli

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

@faststore/components

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

@faststore/core

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

@faststore/diagnostics

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

@faststore/lighthouse

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

@faststore/sdk

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

@faststore/ui

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

commit: a6eb010

@vlaux
vlaux force-pushed the feat/password-protection branch from cf94ad3 to bcc30c5 Compare June 11, 2026 19:38

@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: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/src/proxy.ts`:
- Around line 176-196: The matcher in the exported config (config.matcher)
currently excludes all /api/* routes; narrow that negative lookahead so only the
intended public endpoint(s) are bypassed (e.g., /api/fs/auth/login) instead of
"api". Update the matcher array entry
'/((?!api|_next/static|_next/image|favicon.ico|fs-auth-login|~partytown|.*[.][^/]+$).*)'
to exclude the specific API path(s) you want public (for example replace "api"
with "api/fs/auth/login" or add a separate explicit allowance for
'/api/fs/auth/login') so other API routes remain covered by the password
protection.

In `@packages/core/test/pages/api/fs-auth-login.test.ts`:
- Line 1: The test file name doesn't match the source basename; rename
packages/core/test/pages/api/fs-auth-login.test.ts to match the source file
login.ts (e.g., packages/core/test/pages/api/login.test.ts) so the test filename
tracks the source basename and follows the packages/**/*.test.{ts,tsx} naming
rule; update any imports or test runner references that point to
fs-auth-login.test.ts to the new filename (check package test scripts or CI
configs) and ensure the test folder structure remains the same.

In `@packages/core/test/server/authentication-service.test.ts`:
- Around line 88-91: The teardown in afterAll restores
process.env.CUSTOM_DOMAINS_PROTECTION_ENABLED by assigning originalCustomDomains
directly which can set the string "undefined" into env; change the afterAll
cleanup to restore safely: if originalCustomDomains is undefined/null then
delete process.env.CUSTOM_DOMAINS_PROTECTION_ENABLED, otherwise set it to
originalCustomDomains, and keep the existing setNodeEnv(originalNodeEnv) call;
locate the afterAll block in authentication-service.test.ts and update the logic
around process.env.CUSTOM_DOMAINS_PROTECTION_ENABLED accordingly.

In `@packages/core/test/utils/loginResponse.test.ts`:
- Around line 22-24: The tests in packages/core/test/utils/loginResponse.test.ts
incorrectly treat empty objects and objects with only undefined fields as valid;
update the tests (the cases at Line 22 and the block around 48-56) to expect
false for {} and for payloads where every expected field is undefined, and
modify the isLoginResponse function to enforce that at least one of the expected
properties (e.g., accessToken, refreshToken, user or whatever keys
isLoginResponse checks) is non-null/undefined before returning true so
malformed/empty payloads are rejected.
🪄 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: 86a0c23c-afaa-42c4-b3d1-047264eed479

📥 Commits

Reviewing files that changed from the base of the PR and between cf94ad3 and bcc30c5.

⛔ Files ignored due to path filters (2)
  • .gitignore is excluded by none and included by none
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (15)
  • packages/cli/src/commands/build.ts
  • packages/cli/src/commands/dev.ts
  • packages/cli/src/utils/generate.ts
  • packages/core/package.json
  • packages/core/src/pages/api/fs/auth/login.ts
  • packages/core/src/pages/fs-auth-login/fs-auth-login.module.scss
  • packages/core/src/pages/fs-auth-login/index.tsx
  • packages/core/src/proxy.ts
  • packages/core/src/server/authentication-service.ts
  • packages/core/src/server/password-protection/webops-api.ts
  • packages/core/src/utils/loginResponse.ts
  • packages/core/test/pages/api/fs-auth-login.test.ts
  • packages/core/test/server/authentication-service.test.ts
  • packages/core/test/server/webops-api.test.ts
  • packages/core/test/utils/loginResponse.test.ts
💤 Files with no reviewable changes (1)
  • packages/cli/src/commands/build.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/core/package.json
  • packages/core/src/utils/loginResponse.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/core/src/server/password-protection/webops-api.ts
  • packages/core/src/pages/fs-auth-login/index.tsx
  • packages/cli/src/utils/generate.ts

Comment thread packages/core/src/proxy.ts Resolved

@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

🧹 Nitpick comments (1)
packages/core/test/pages/fs-auth-login.test.tsx (1)

102-109: ⚡ Quick win

Prefer .toBeInTheDocument() for DOM assertions.

Use Testing Library's .toBeInTheDocument() matcher instead of .not.toBeNull() for clearer intent.

♻️ Suggested refactor
-    expect(
-      screen.queryByText('This store is password protected')
-    ).not.toBeNull()
-    expect(
-      screen.queryByText('Enter the password to access the store')
-    ).not.toBeNull()
-    expect(screen.queryByLabelText('Password')).not.toBeNull()
-    expect(screen.queryByRole('button', { name: 'Login' })).not.toBeNull()
+    expect(
+      screen.getByText('This store is password protected')
+    ).toBeInTheDocument()
+    expect(
+      screen.getByText('Enter the password to access the store')
+    ).toBeInTheDocument()
+    expect(screen.getByLabelText('Password')).toBeInTheDocument()
+    expect(screen.getByRole('button', { name: 'Login' })).toBeInTheDocument()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/pages/fs-auth-login.test.tsx` around lines 102 - 109,
Replace assertions using .not.toBeNull() with the clearer Testing Library
matcher .toBeInTheDocument() for the queries in fs-auth-login.test.tsx: update
the expectations that call screen.queryByText('This store is password
protected'), screen.queryByText('Enter the password to access the store'),
screen.queryByLabelText('Password'), and screen.queryByRole('button', { name:
'Login' }) so they use .toBeInTheDocument() (e.g.,
expect(screen.queryByText(...)).toBeInTheDocument()); keep the same query calls
and intent, only change the matcher for clearer DOM assertion semantics.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/core/test/pages/fs-auth-login.test.tsx`:
- Around line 1-3: This test file is a browser (jsdom) test but uses the wrong
extension; rename the test from fs-auth-login.test.tsx to
fs-auth-login.browser.test.tsx and update any references/imports to that
filename so the test runner picks up the browser test convention; ensure the
file header remains "// `@vitest-environment` jsdom" in the renamed file.

---

Nitpick comments:
In `@packages/core/test/pages/fs-auth-login.test.tsx`:
- Around line 102-109: Replace assertions using .not.toBeNull() with the clearer
Testing Library matcher .toBeInTheDocument() for the queries in
fs-auth-login.test.tsx: update the expectations that call
screen.queryByText('This store is password protected'),
screen.queryByText('Enter the password to access the store'),
screen.queryByLabelText('Password'), and screen.queryByRole('button', { name:
'Login' }) so they use .toBeInTheDocument() (e.g.,
expect(screen.queryByText(...)).toBeInTheDocument()); keep the same query calls
and intent, only change the matcher for clearer DOM assertion semantics.
🪄 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: df41e909-eec3-4973-88f0-a3621deaed0f

📥 Commits

Reviewing files that changed from the base of the PR and between bcc30c5 and c569ca3.

📒 Files selected for processing (4)
  • packages/core/test/pages/api/fs-auth-login.test.ts
  • packages/core/test/pages/fs-auth-login.test.tsx
  • packages/core/test/proxy.test.ts
  • packages/core/test/server/authentication-service.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/test/pages/api/fs-auth-login.test.ts
  • packages/core/test/server/authentication-service.test.ts

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

Sobre a nomenclatura: vários nomes usam auth/login (AuthenticationService, /api/fs/auth/login, página fs-auth-login, cookie __fs_auth_token, LoginResponse), mas esse vocabulário no FastStore já é da autenticação do cliente (useAuth, ProfileChallenge, sdk/session, My Account/VTEX ID).

Aqui é outra coisa: um gate do site com senha compartilhada para acessar uma loja ainda não pública — sem usuário, perfil ou "minha conta". Reusar "login/auth" confunde.

Como o PR já usa server/password-protection/, sugiro alinhar tudo a esse domínio e trocar "login" por "unlock": PasswordProtectionService, /api/fs/password-protection/unlock, página fs-password-protection, cookie __fs_password_protection, UnlockResponse/isUnlockResponse.

A rota e o cookie são internos da store (só as URLs da WebOps são contrato fixo), então o rename é seguro e só mexe no nosso código e nos testes. Não é bloqueante, mas acho que vale fazer agora pra evitar confusão com o login do cliente. O que acham?

@vlaux

vlaux commented Jun 16, 2026

Copy link
Copy Markdown
Contributor Author

Sobre a nomenclatura: vários nomes usam auth/login (AuthenticationService, /api/fs/auth/login, página fs-auth-login, cookie __fs_auth_token, LoginResponse), mas esse vocabulário no FastStore já é da autenticação do cliente (useAuth, ProfileChallenge, sdk/session, My Account/VTEX ID).

Aqui é outra coisa: um gate do site com senha compartilhada para acessar uma loja ainda não pública — sem usuário, perfil ou "minha conta". Reusar "login/auth" confunde.

Como o PR já usa server/password-protection/, sugiro alinhar tudo a esse domínio e trocar "login" por "unlock": PasswordProtectionService, /api/fs/password-protection/unlock, página fs-password-protection, cookie __fs_password_protection, UnlockResponse/isUnlockResponse.

A rota e o cookie são internos da store (só as URLs da WebOps são contrato fixo), então o rename é seguro e só mexe no nosso código e nos testes. Não é bloqueante, mas acho que vale fazer agora pra evitar confusão com o login do cliente. O que acham?

De acordo. Refatorei a nomenclatura aqui. O que acham?
cc @eduardoformiga

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

♻️ Duplicate comments (1)
packages/core/src/server/password-protection-service.ts (1)

83-86: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

IPv6 host normalization still breaks on bracketed literals.

The current implementation host.split(':')[0] returns "[" for IPv6 hosts like "[::1]:8080", causing incorrect .endsWith('.vtex.app') checks. The past review flagged this and it appears unresolved.

🩹 Suggested fix
   private getNormalizedHost(request: NextRequest): string {
-    const host = request.headers.get('host') || ''
-    return host.split(':')[0].toLowerCase()
+    const host = (request.headers.get('host') || '').trim().toLowerCase()
+
+    // Bracketed IPv6: "[::1]:8080" -> "[::1]"
+    if (host.startsWith('[')) {
+      const end = host.indexOf(']')
+      return end === -1 ? host : host.slice(0, end + 1)
+    }
+
+    // IPv4 / regular hostnames: strip ":port"
+    return host.split(':')[0]
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/server/password-protection-service.ts` around lines 83 -
86, The getNormalizedHost method fails to properly normalize IPv6 addresses
wrapped in brackets like "[::1]:8080" because splitting by colon returns only
"[" as the first element. Fix this by detecting when the host starts with a
bracket (indicating IPv6 format), and if present, extract the portion between
the brackets first before performing any port removal logic. This ensures the
method correctly handles both IPv4 addresses and IPv6 bracketed literals,
allowing the subsequent endsWith check to work as intended.
🧹 Nitpick comments (2)
packages/core/test/pages/password-protection.browser.test.tsx (1)

77-82: Use userEvent.click() for more realistic form submission testing.

The current fireEvent.submit() on a button doesn't accurately simulate user interaction. Per React Testing Library best practices, userEvent.click() on the submit button properly triggers the full event sequence (visibility checks, focus, mouse events), making the test more representative of actual user behavior. This requires adding userEvent to imports and making the helper async with await.

Suggested improvement
 import {
   cleanup,
+  fireEvent,
-  fireEvent,
   render,
   screen,
   waitFor,
-} from '`@testing-library/react`'
+  userEvent,
+} from '`@testing-library/react`'

-function fillAndSubmit(password = 'secret') {
+async function fillAndSubmit(password = 'secret') {
   fireEvent.change(screen.getByLabelText('Password'), {
     target: { value: password },
   })
-  fireEvent.submit(screen.getByRole('button', { name: 'Unlock' }))
+  await userEvent.click(screen.getByRole('button', { name: 'Unlock' }))
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/test/pages/password-protection.browser.test.tsx` around lines
77 - 82, In the fillAndSubmit helper function, replace the fireEvent.submit()
call with userEvent.click() to provide more realistic form submission testing.
First, add userEvent to the imports at the top of the test file. Then, make the
fillAndSubmit function async and replace the
fireEvent.submit(screen.getByRole('button', { name: 'Unlock' })) line with await
userEvent.click(screen.getByRole('button', { name: 'Unlock' })) to properly
simulate the complete user interaction sequence including visibility checks,
focus, and mouse events.
packages/core/src/pages/api/fs/password-protection/unlock.ts (1)

5-13: 💤 Low value

Inconsistent import style between relative and path alias.

Lines 5-9 use relative imports (../../../../utils/..., ../../../../server/...) while lines 10-13 use a path alias (src/server/...). Consider aligning to one style for consistency.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/core/src/pages/api/fs/password-protection/unlock.ts` around lines 5
- 13, The imports in the unlock.ts file mix relative path imports
(../../../../utils/unlockResponse and
../../../../server/password-protection/webops-api) with path alias imports
(src/server/password-protection-service). Convert all the relative imports at
the top of the file to use the consistent path alias style by replacing the
relative paths (../../../../) with the src/ alias prefix, so that all imports
follow the same pattern and improve readability and maintainability.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@packages/core/src/server/password-protection-service.ts`:
- Around line 83-86: The getNormalizedHost method fails to properly normalize
IPv6 addresses wrapped in brackets like "[::1]:8080" because splitting by colon
returns only "[" as the first element. Fix this by detecting when the host
starts with a bracket (indicating IPv6 format), and if present, extract the
portion between the brackets first before performing any port removal logic.
This ensures the method correctly handles both IPv4 addresses and IPv6 bracketed
literals, allowing the subsequent endsWith check to work as intended.

---

Nitpick comments:
In `@packages/core/src/pages/api/fs/password-protection/unlock.ts`:
- Around line 5-13: The imports in the unlock.ts file mix relative path imports
(../../../../utils/unlockResponse and
../../../../server/password-protection/webops-api) with path alias imports
(src/server/password-protection-service). Convert all the relative imports at
the top of the file to use the consistent path alias style by replacing the
relative paths (../../../../) with the src/ alias prefix, so that all imports
follow the same pattern and improve readability and maintainability.

In `@packages/core/test/pages/password-protection.browser.test.tsx`:
- Around line 77-82: In the fillAndSubmit helper function, replace the
fireEvent.submit() call with userEvent.click() to provide more realistic form
submission testing. First, add userEvent to the imports at the top of the test
file. Then, make the fillAndSubmit function async and replace the
fireEvent.submit(screen.getByRole('button', { name: 'Unlock' })) line with await
userEvent.click(screen.getByRole('button', { name: 'Unlock' })) to properly
simulate the complete user interaction sequence including visibility checks,
focus, and mouse events.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 415fa39d-a3bd-40ec-aec7-3eef96c0ca0c

📥 Commits

Reviewing files that changed from the base of the PR and between bcc30c5 and 0d8b698.

⛔ Files ignored due to path filters (2)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
  • pnpm-workspace.yaml is excluded by none and included by none
📒 Files selected for processing (13)
  • packages/components/package.json
  • packages/core/package.json
  • packages/core/src/pages/api/fs/password-protection/unlock.ts
  • packages/core/src/pages/password-protection/index.tsx
  • packages/core/src/pages/password-protection/password-protection.module.scss
  • packages/core/src/proxy.ts
  • packages/core/src/server/password-protection-service.ts
  • packages/core/src/utils/unlockResponse.ts
  • packages/core/test/pages/api/unlock.test.ts
  • packages/core/test/pages/password-protection.browser.test.tsx
  • packages/core/test/proxy.test.ts
  • packages/core/test/server/password-protection-service.test.ts
  • packages/core/test/utils/unlockResponse.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/core/package.json

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

Nice! I'll let it pre-approved.

  • sonarqube is failing but there is no approve option in its panel.
  • we also need to regenerate the pnpm lock file that is conflicting.

vlaux and others added 13 commits June 17, 2026 15:10
Next.js' negative-lookahead matcher does not catch `/` on its own, so
the homepage was bypassing password protection. Restore the explicit
`/` entry that the 3.x middleware had.

Co-authored-by: Cursor <[email protected]>
Add unit tests for the login API route, webops-api URL builders and
loginResponse type guard. Fix String.raw code smell in proxy matcher.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Biome's lint:fix rewrote the regex with `\.` into a `String.raw` tagged
template literal, which Next.js refuses to statically analyze in
`config.matcher`, breaking the production build. Use the equivalent
regex character class `[.]` so the string has no escapes for Biome to
"fix" and stays a plain string literal Next.js can parse.

Co-authored-by: Cursor <[email protected]>
- Updated the proxy matcher to explicitly exclude the password-protection login endpoint from being matched.
- Improved the `isLoginResponse` type guard to ensure it correctly identifies valid login response structures, returning false for empty objects and when all fields are undefined.
- Removed the now-redundant test file for the password-protection login API route, streamlining the test suite.
…n login tests

- Added '@testing-library/jest-dom' version 6.9.1 to pnpm-lock.yaml and pnpm-workspace.yaml.
- Updated package.json files in components and core to reference '@testing-library/jest-dom' as 'catalog:'.
- Introduced a new test file for the PasswordProtectionLogin component, enhancing test coverage for login functionality and error handling.
…ection tests

- Added '@testing-library/user-event' version 14.5.2 to pnpm-lock.yaml and pnpm-workspace.yaml.
- Updated package.json in core to reference '@testing-library/user-event' as 'catalog:'.
- Refactored password protection tests to use userEvent for better interaction simulation.
@vlaux
vlaux force-pushed the feat/password-protection branch from 1305e33 to a6eb010 Compare June 17, 2026 18:10
@sonar-workflows

Copy link
Copy Markdown

Failed Quality Gate failed

  • 0.00% Security Hotspots Reviewed on New Code (is less than 100.00%)

Project ID: vtex_faststore_f0a862d5-9557-49f9-8d09-de40caa76622

View in SonarQube

@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 current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/components/package.json`:
- Line 39: In the `packages/components/package.json` file, the
`@testing-library/jest-dom` dependency is incorrectly using the `catalog:`
reference. Since this dependency is only used locally within the
packages/components package (via packages/components/vitest.setup.ts) and not
shared across multiple packages, it should not reference the catalog. Replace
the `"catalog:"` value with an inline-pinned version string (e.g., `"^6.9.1"`)
to properly reflect that this is a single-package dependency per the coding
guidelines.
🪄 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: 0734c9cf-3d6b-4436-a0a4-7c6d9cfcc88d

📥 Commits

Reviewing files that changed from the base of the PR and between 1305e33 and a6eb010.

⛔ Files ignored due to path filters (3)
  • .gitignore is excluded by none and included by none
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
  • pnpm-workspace.yaml is excluded by none and included by none
📒 Files selected for processing (18)
  • packages/cli/src/commands/build.ts
  • packages/cli/src/commands/dev.ts
  • packages/cli/src/utils/generate.ts
  • packages/components/package.json
  • packages/core/package.json
  • packages/core/src/pages/api/fs/password-protection/unlock.ts
  • packages/core/src/pages/password-protection/index.tsx
  • packages/core/src/pages/password-protection/password-protection.module.scss
  • packages/core/src/proxy.ts
  • packages/core/src/server/password-protection-service.ts
  • packages/core/src/server/password-protection/webops-api.ts
  • packages/core/src/utils/unlockResponse.ts
  • packages/core/test/pages/api/unlock.test.ts
  • packages/core/test/pages/password-protection.browser.test.tsx
  • packages/core/test/proxy.test.ts
  • packages/core/test/server/password-protection-service.test.ts
  • packages/core/test/server/webops-api.test.ts
  • packages/core/test/utils/unlockResponse.test.ts
💤 Files with no reviewable changes (2)
  • packages/cli/src/commands/build.ts
  • packages/cli/src/utils/generate.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/core/test/utils/unlockResponse.test.ts
  • packages/core/package.json
🚧 Files skipped from review as they are similar to previous changes (11)
  • packages/cli/src/commands/dev.ts
  • packages/core/src/utils/unlockResponse.ts
  • packages/core/src/server/password-protection/webops-api.ts
  • packages/core/test/pages/password-protection.browser.test.tsx
  • packages/core/src/pages/password-protection/index.tsx
  • packages/core/src/proxy.ts
  • packages/core/src/pages/api/fs/password-protection/unlock.ts
  • packages/core/test/server/password-protection-service.test.ts
  • packages/core/test/pages/api/unlock.test.ts
  • packages/core/test/server/webops-api.test.ts
  • packages/core/src/server/password-protection-service.ts

Comment thread packages/components/package.json Resolved
@eduardoformiga
eduardoformiga merged commit 575f162 into dev Jun 17, 2026
9 of 10 checks passed
@eduardoformiga
eduardoformiga deleted the feat/password-protection branch June 17, 2026 21:14
@eduardoformiga eduardoformiga mentioned this pull request Jun 17, 2026
2 tasks
eduardoformiga added a commit that referenced this pull request Jun 17, 2026
## Summary

Graduate the `4.3.0-dev.8` prerelease cycle to the stable `4.3.0`
release on `latest`.

Merging this PR triggers CD on `main`, which runs `lerna version
--conventional-graduate` and publishes all `@faststore/*` packages to
the `latest` dist-tag.

### Features
- Password Protection (v4) (#3276)
- File upload via Order Entry Service (OES) (#3334)
- Add sitemap to CMS Landing Page content-type (#3386)

### Bug Fixes
- **core:** use authenticator route for setpassword (#3380)
- migrate partytown `@builder.io` → `@[email protected]` (#3394)
- **api:** use account-scoped cookie in orderEntry headers (#3395)
- forward auth token only via account-scoped cookie (#3381)
- **core:** propagate upstream error status instead of always 500
(#3379)

## Pre-flight (faststore-release skill)
- Working tree clean; `release.yml` has `fetch-depth: 0`
- All 8 packages have `repository.url`
- No breaking changes since `v4.2.0`
- `dev → main` merges cleanly (no CHANGELOG/codegen conflicts)
- No unmerged hotfixes on `main` (accidental `4.2.1` was fully reverted
in #3375)

## Test plan
- [ ] CI green on this PR
- [ ] After merge, confirm CD publishes all 8 packages at `4.3.0` under
`latest`

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

---------

Co-authored-by: Matheus P. Silva <[email protected]>
Co-authored-by: vtexgithubbot <[email protected]>
Co-authored-by: Lucas Feijó <[email protected]>
Co-authored-by: Luiz Falcão <[email protected]>
Co-authored-by: Artur Santiago <[email protected]>
Co-authored-by: Larícia Mota <[email protected]>
Co-authored-by: Sahan Jayawardana <[email protected]>
Co-authored-by: Mateus Pontes <[email protected]>
Co-authored-by: Matheus Martins <[email protected]>
Co-authored-by: renatomaurovtex <[email protected]>
Co-authored-by: Leandro Rodrigues <[email protected]>
Co-authored-by: Fanny Chien <[email protected]>
Co-authored-by: Arthur Andrade <[email protected]>
Co-authored-by: Leandro Rodrigues <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Thiago Pereira <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Giuliana Rigaud <[email protected]>
Co-authored-by: renato <[email protected]>
Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: BrunaCubos <[email protected]>
Co-authored-by: Ícaro Oliveira <[email protected]>
Co-authored-by: Bruna Santos <[email protected]>
Co-authored-by: Everton Ataide <[email protected]>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
Co-authored-by: Otavio Moreira Meirelles <[email protected]>
Co-authored-by: Marco Cardoso <[email protected]>
Co-authored-by: Gabriel Paladino <[email protected]>
Co-authored-by: CodeRabbit <[email protected]>
Co-authored-by: dk-portal[bot] <134092483+dk-portal[bot]@users.noreply.github.com>
Co-authored-by: Rodrigo Tavares <[email protected]>
Co-authored-by: vitorflg <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Co-authored-by: Válber Laux <[email protected]>
eduardoformiga pushed a commit that referenced this pull request Jun 30, 2026
…3404)

[FAS-1151](https://vtex-dev.atlassian.net/browse/FAS-1151)

## Summary

- Ports vocabulary changes from v4 (f4ed151 / #3276) to v3 to fix a
cookie name inconsistency with an external application
- Renames `__fs_auth_token` → `__fs_password_protection` (the critical
fix)
- Aligns all related file names, class/method names, URLs, and UI copy
to the `unlock` domain

## Changes

| Old (v3) | New |
|---|---|
| `__fs_auth_token` (cookie) | `__fs_password_protection` |
| `AuthenticationService` | `PasswordProtectionService` |
| `authenticateRequest()` | `checkStoreProtection()` |
| `authentication-service.ts` | `password-protection-service.ts` |
| `loginResponse.ts` | `unlockResponse.ts` |
| `LoginResponse` / `isLoginResponse` | `UnlockResponse` /
`isUnlockResponse` |
| `pages/api/fs/auth/login` | `pages/api/fs/password-protection/unlock`
|
| `pages/fs-auth-login/` | `pages/password-protection/` |
| Button label: `Login` | `Unlock` |
| Input id: `fs-auth-password` | `password-protection-input` |

## Context

The vocabulary inconsistency between v3 and v4 was causing issues in
another application reading the auth cookie by name. This PR brings v3
in sync with the v4 refactor that was already merged (#3276).

## Test plan

- [ ] Unit tests pass (`pnpm test` in `packages/core`)
- [ ] Middleware correctly redirects to `/password-protection` when
store is protected
- [ ] Unlock page posts to `/api/fs/password-protection/unlock` and sets
`__fs_password_protection` cookie on success
- [ ] External application consuming the cookie reads it correctly with
the new name

🤖 Generated with [Claude Code](https://claude.com/claude-code)

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

## Summary by CodeRabbit

## Release Notes

* **Refactor**
* Switched store access checks from authentication-based protection to
password-protection-based validation.
* Updated the session protection service, including cookie name and
renewal behavior.
* Updated the unlock flow terminology and payload validation to use an
unlock-specific response.
* Adjusted middleware redirect behavior and cookie propagation to match
the new protection flow.
* **New Features**
* Added the password-protection unlock page flow (Unlock submission +
unlock API).
* **Tests**
* Updated password-protection service tests to match new cookies,
redirects, and fail-close behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

[FAS-1151]:
https://vtex-dev.atlassian.net/browse/FAS-1151?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

---------

Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributing Pull request submitted by the community enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants