Repository navigation
feat: Password Protection (v4) - #3276
Conversation
|
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. |
WalkthroughThe PR removes the CLI's localization-based proxy filename toggling ( ChangesCLI proxy toggle removal
Password-protection auth system in core
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes 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 |
e24ed72 to
d4400ee
Compare
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (2)
.gitignoreis excluded by none and included by nonepnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (12)
packages/cli/src/utils/generate.tspackages/core/package.jsonpackages/core/src/middleware.tspackages/core/src/middleware__DISABLED.tspackages/core/src/pages/api/fs/auth/login.tspackages/core/src/pages/fs-auth-login/fs-auth-login.module.scsspackages/core/src/pages/fs-auth-login/index.tsxpackages/core/src/server/authentication-service.tspackages/core/src/server/password-protection/auth-cookie.tspackages/core/src/server/password-protection/webops-api.tspackages/core/test/server/authentication-service.test.tspackages/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
fa49b7b to
9c7f6de
Compare
2f70225 to
4850045
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/core/src/server/authentication-service.ts (2)
96-114: Flatten the valid-token branch — threeNextResponse.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: Doubleas unknown as TokenPayloadcoerces without validating.
jwtVerifyreturnsJWTPayload, anddecodeJwteven more so — nothing guaranteesstoreId/protected/scopeare the expected types at runtime. A malformed token could slip pastpayloadMatchesStore(e.g.storeIdas a number coerced, orprotectedas 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 bothverifyTokensuccess and expired paths and fail closed when it returnsnull.🤖 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
📒 Files selected for processing (6)
packages/core/src/middleware.tspackages/core/src/pages/api/fs/auth/login.tspackages/core/src/pages/fs-auth-login/index.tsxpackages/core/src/server/authentication-service.tspackages/core/src/server/password-protection/auth-cookie.tspackages/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
6c7ef8e to
4d4ac3a
Compare
|
hey @vlaux
In V4, edge handling moved from Could you rebase/merge dev and reimplement password protection in proxy, so it works alongside the localization proxy? Thanks! |
4850045 to
a0ffc70
Compare
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
cf94ad3 to
bcc30c5
Compare
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (2)
.gitignoreis excluded by none and included by nonepnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (15)
packages/cli/src/commands/build.tspackages/cli/src/commands/dev.tspackages/cli/src/utils/generate.tspackages/core/package.jsonpackages/core/src/pages/api/fs/auth/login.tspackages/core/src/pages/fs-auth-login/fs-auth-login.module.scsspackages/core/src/pages/fs-auth-login/index.tsxpackages/core/src/proxy.tspackages/core/src/server/authentication-service.tspackages/core/src/server/password-protection/webops-api.tspackages/core/src/utils/loginResponse.tspackages/core/test/pages/api/fs-auth-login.test.tspackages/core/test/server/authentication-service.test.tspackages/core/test/server/webops-api.test.tspackages/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
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/core/test/pages/fs-auth-login.test.tsx (1)
102-109: ⚡ Quick winPrefer
.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
📒 Files selected for processing (4)
packages/core/test/pages/api/fs-auth-login.test.tspackages/core/test/pages/fs-auth-login.test.tsxpackages/core/test/proxy.test.tspackages/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
left a comment
There was a problem hiding this comment.
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? |
There was a problem hiding this comment.
♻️ Duplicate comments (1)
packages/core/src/server/password-protection-service.ts (1)
83-86:⚠️ Potential issue | 🟠 Major | ⚡ Quick winIPv6 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: UseuserEvent.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 addinguserEventto 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 valueInconsistent 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
⛔ Files ignored due to path filters (2)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by nonepnpm-workspace.yamlis excluded by none and included by none
📒 Files selected for processing (13)
packages/components/package.jsonpackages/core/package.jsonpackages/core/src/pages/api/fs/password-protection/unlock.tspackages/core/src/pages/password-protection/index.tsxpackages/core/src/pages/password-protection/password-protection.module.scsspackages/core/src/proxy.tspackages/core/src/server/password-protection-service.tspackages/core/src/utils/unlockResponse.tspackages/core/test/pages/api/unlock.test.tspackages/core/test/pages/password-protection.browser.test.tsxpackages/core/test/proxy.test.tspackages/core/test/server/password-protection-service.test.tspackages/core/test/utils/unlockResponse.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/package.json
eduardoformiga
left a comment
There was a problem hiding this comment.
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.
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]>
Co-authored-by: Leandro Rodrigues <[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.
1305e33 to
a6eb010
Compare
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (3)
.gitignoreis excluded by none and included by nonepnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by nonepnpm-workspace.yamlis excluded by none and included by none
📒 Files selected for processing (18)
packages/cli/src/commands/build.tspackages/cli/src/commands/dev.tspackages/cli/src/utils/generate.tspackages/components/package.jsonpackages/core/package.jsonpackages/core/src/pages/api/fs/password-protection/unlock.tspackages/core/src/pages/password-protection/index.tsxpackages/core/src/pages/password-protection/password-protection.module.scsspackages/core/src/proxy.tspackages/core/src/server/password-protection-service.tspackages/core/src/server/password-protection/webops-api.tspackages/core/src/utils/unlockResponse.tspackages/core/test/pages/api/unlock.test.tspackages/core/test/pages/password-protection.browser.test.tsxpackages/core/test/proxy.test.tspackages/core/test/server/password-protection-service.test.tspackages/core/test/server/webops-api.test.tspackages/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
## 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]>
…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]>

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:
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
feat,fix,chore,docs,style,refactor,ciandtestPR Description
breaking change,bug,contributing,performance,documentation..Dependencies
pnpm-lock.yamlfile when there were changes to the packagesDocumentation
@Mariana-Caetanoto review and update (Or submit a doc request)Summary by CodeRabbit
Release Notes
New Features
Improvements
Testing