Repository navigation
feat: Password Protection (v3) - #3347
Conversation
WalkthroughAdds password-protection: WebOps endpoint builders, AuthenticationService (JWT verify/renew + cookie management), middleware enforcement, login API and UI, tests, and removes old CLI redirects-middleware enablement. ChangesPassword Protection System
Sequence DiagramsequenceDiagram
participant Request as NextRequest
participant Service as AuthenticationService
participant JwtVerify as jose.jwtVerify
participant WebOps as WebOps API
Request->>Service: authenticateRequest(request)
activate Service
alt Has __fs_auth_token cookie
Service->>JwtVerify: verify token
alt Token valid
JwtVerify-->>Service: verified payload
Service-->>Request: NextResponse.next()
else Token expired
Service->>WebOps: renewUrl()
WebOps-->>Service: new token
Service->>Service: setAuthCookie(newToken)
Service-->>Request: NextResponse.next()
else JWT error
Service->>WebOps: protectionStatusUrl()
WebOps-->>Service: {protected, scope, token?}
alt Protected and scope applies
Service-->>Request: redirectToLogin()
else Protection off or scope doesn't apply
Service->>Service: setAuthCookie(optionalToken)
Service-->>Request: NextResponse.next()
end
end
else No token
Service->>WebOps: protectionStatusUrl()
WebOps-->>Service: {protected, scope, token?}
alt Protected and scope applies
Service-->>Request: redirectToLogin()
else Protection off or scope doesn't apply
Service->>Service: setAuthCookie(optionalToken)
Service-->>Request: NextResponse.next()
end
end
deactivate Service
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
…ditional redirects - Rename middleware__DISABLED.ts to middleware.ts (middleware always active) - Integrate AuthenticationService for password protection flow - Run redirects only when ENABLE_REDIRECTS_MIDDLEWARE is set at runtime - Remove middleware renaming logic from CLI generate.ts Made-with: Cursor
…meouts Add webops-api helpers for public-key, status, session, and renew endpoints. Use them from AuthenticationService and the fs auth login route; normalize WEBOPS_API_URL and encode storeId on status queries. Improve login page a11y.
424e521 to
9e369ff
Compare
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (2)
packages/core/src/server/authentication-service.ts (1)
99-108: 💤 Low valueSimplify consecutive pass-through conditions.
Three separate conditions all return
NextResponse.next(). Per coding guidelines, prefer flat conditionals.♻️ Proposed refactor
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() } + const needsProtection = + verification.payload.protected && + this.shouldProtectDomain(request, verification.payload.scope) + + if (!needsProtection) { + return { response: NextResponse.next() } + } + + // Token valid and domain is protected — allow through + return { response: NextResponse.next() } }🤖 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/authentication-service.ts` around lines 99 - 108, The three consecutive checks that all return NextResponse.next() can be collapsed: replace the separate branches that test verification.valid && verification.payload, verification.payload.protected, and this.shouldProtectDomain(...) with a single conditional that returns { response: NextResponse.next() } when verification.valid && verification.payload && ( !verification.payload.protected || !this.shouldProtectDomain(request, verification.payload.scope) ); keep the remaining logic untouched so only the redundant early-return branches are removed; refer to verification.valid, verification.payload.protected, shouldProtectDomain(request, verification.payload.scope), and NextResponse.next() when applying the change.packages/core/test/server/password-protection/auth-cookie.test.ts (1)
66-109: ⚡ Quick winConsider adding edge-case coverage for header variations.
The current tests cover the main paths, but a few additional cases would strengthen robustness:
x-forwarded-proto: 'http'should returnfalsex-forwarded-protoas an array (implementation handles this per line 57 of auth-cookie.ts)- IPv6 localhost like
[::1]- Comma-separated proto values
These would catch potential bugs in header parsing logic without much effort.
🤖 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/server/password-protection/auth-cookie.test.ts` around lines 66 - 109, Add four edge-case tests to the existing isSecureAuthCookieForPagesApi suite in auth-cookie.test.ts: (1) a production request with header 'x-forwarded-proto' set to 'http' expecting false, (2) a production request where 'x-forwarded-proto' is an array (e.g., ['https'] and ['http']) asserting the correct boolean, (3) a production request with host '[::1]' (IPv6 localhost) expecting false, and (4) a production request with comma-separated proto values (e.g., 'https, http' and 'http, https') asserting correct parsing behavior; ensure each test uses setNodeEnv('production') and constructs a NextApiRequest-like object with headers to call isSecureAuthCookieForPagesApi.
🤖 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/middleware.ts`:
- Around line 64-66: The catch block currently returns NextResponse.next(),
letting requests through on any error; change it to fail-closed for protected
domains by redirecting to your login flow instead: when AuthenticationService
construction or authenticateRequest throws, call the same redirect logic used
for unauthenticated users (e.g., the AuthenticationService redirect-to-login
helper or the existing redirect target used elsewhere) and return that
NextResponse.redirect; ensure you still allow NextResponse.next() only for
explicitly unprotected domains or after a successful allow decision from
AuthenticationService.
In `@packages/core/src/pages/api/fs/auth/login.ts`:
- Around line 63-66: After reading webopsResponse.json() in the login handler,
replace the untyped use of data with a properly typed payload and runtime guard:
define an interface (e.g., WebOpsSessionPayload) matching expected fields
(valid: boolean, token?: string, ...), implement a type guard (e.g.,
isWebOpsSessionPayload(data)) that checks those fields exist and have correct
types, call that guard right after const data = await webopsResponse.json(), and
return a 400/unauthorized error if the guard fails; then continue to use
data.valid and data.token safely when issuing the token in this handler.
In `@packages/core/src/pages/fs-auth-login/fs-auth-login.module.scss`:
- Around line 1-8: The SCSS `@import` rules are nested inside the `@layer` block and
include the .scss extension, which violates stylelint; move the four `@import`
lines so they are top-level (before the `@layer` components { ... } block) and
remove the .scss extension from each import path (e.g., change
"`@faststore/ui/src/components/atoms/Button/styles.scss`" to
"`@faststore/ui/src/components/atoms/Button/styles`"), keeping the existing
.fsAuthLogin selector intact.
In `@packages/core/src/pages/fs-auth-login/index.tsx`:
- Around line 32-37: The login handler currently reads response.json() into an
untyped data variable and then accesses
data.success/data.redirectUrl/data.error; add a proper typed response or runtime
guard before branching: define a LoginResponse shape (or validate the unknown
from response.json()) and assert it matches { success?: boolean; redirectUrl?:
string; error?: string } using a small type guard, then only access
data.success, data.redirectUrl and call setError when the guard passes (fall
back to a safe error message if validation fails) so that the usages in this
file (response.json, data.success, data.redirectUrl, data.error, setError) are
type-safe.
In `@packages/core/src/server/authentication-service.ts`:
- Around line 3-4: The package is missing the 'jose' dependency used by
authentication-service.ts (imports jwtVerify, decodeJwt, importSPKI, errors), so
add 'jose' to packages/core/package.json dependencies with an appropriate semver
(e.g., a stable ^ version) and run install; ensure TypeScript types are
available (either via included types in the package or `@types` if required) so
the imports in authentication-service.ts resolve.
- Around line 84-87: getNormalizedHost currently splits the Host header on ':'
which breaks bracketed IPv6 like "[::1]:3000"; update getNormalizedHost to use
the same bracket-aware parsing logic used by isLocalHost in auth-cookie.ts:
detect if hostname starts with '[' then extract the substring between '[' and
']' as the host, otherwise strip any port by splitting on ':' from the right or
using lastIndexOf, then trim() and toLowerCase(); reference getNormalizedHost
and isLocalHost to copy the bracket-aware behavior.
In `@packages/core/src/server/password-protection/auth-cookie.ts`:
- Around line 4-12: The regex in isLocalHost wrongly uses [^\\] (not-backslash)
inside the character class when extracting an IPv6 address from “[ipv6]:port”;
replace the character class with [^\]] so the pattern becomes
/^\[([^\]]+)\](?::\d+)?$/ (or construct the same via RegExp) to correctly match
everything except the closing bracket, update the new RegExp(...) call in
isLocalHost accordingly.
In `@packages/core/test/server/password-protection/auth-cookie.test.ts`:
- Around line 1-110: The build is failing due to deprecated tsconfig
compilerOptions (moduleResolution: node10, baseUrl, target: es5); update the
root tsconfig.json and packages/core/tsconfig.json compilerOptions to supported
values (e.g., moduleResolution: "node", remove or correct deprecated
baseUrl/target to a modern target like "es2019") or add "ignoreDeprecations":
"6.0" to suppress the deprecation errors, then re-run TypeScript typechecking
(npx tsc -p ...) and confirm the auth-cookie typings pass for
isSecureAuthCookieForMiddleware and isSecureAuthCookieForPagesApi in
packages/core/src/server/password-protection/auth-cookie.ts and its test file.
---
Nitpick comments:
In `@packages/core/src/server/authentication-service.ts`:
- Around line 99-108: The three consecutive checks that all return
NextResponse.next() can be collapsed: replace the separate branches that test
verification.valid && verification.payload, verification.payload.protected, and
this.shouldProtectDomain(...) with a single conditional that returns { response:
NextResponse.next() } when verification.valid && verification.payload && (
!verification.payload.protected || !this.shouldProtectDomain(request,
verification.payload.scope) ); keep the remaining logic untouched so only the
redundant early-return branches are removed; refer to verification.valid,
verification.payload.protected, shouldProtectDomain(request,
verification.payload.scope), and NextResponse.next() when applying the change.
In `@packages/core/test/server/password-protection/auth-cookie.test.ts`:
- Around line 66-109: Add four edge-case tests to the existing
isSecureAuthCookieForPagesApi suite in auth-cookie.test.ts: (1) a production
request with header 'x-forwarded-proto' set to 'http' expecting false, (2) a
production request where 'x-forwarded-proto' is an array (e.g., ['https'] and
['http']) asserting the correct boolean, (3) a production request with host
'[::1]' (IPv6 localhost) expecting false, and (4) a production request with
comma-separated proto values (e.g., 'https, http' and 'http, https') asserting
correct parsing behavior; ensure each test uses setNodeEnv('production') and
constructs a NextApiRequest-like object with headers to call
isSecureAuthCookieForPagesApi.
🪄 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: 39e0a32b-1d08-4a35-8779-e5869bc512ce
⛔ Files ignored due to path filters (1)
.gitignoreis excluded by none and included by none
📒 Files selected for processing (11)
packages/cli/src/utils/generate.tspackages/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/core/src/middleware__DISABLED.ts
- packages/cli/src/utils/generate.ts
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/graphql-utils
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
… authentication service
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/core/src/server/password-protection/login-response.ts`:
- Around line 1-20: Move the shared LoginResponse contract out of the
server-only folder and rename the file to camelCase (e.g., loginResponse.ts) so
it's under packages/core/src/ (or another non-server src directory); update the
exported interface LoginResponse and type-guard isLoginResponse in that new file
and update all imports that reference the old src/server/login-response.ts to
the new path/name; ensure the new module keeps the same exports (LoginResponse,
isLoginResponse) so both the API route and client page work without further
changes.
🪄 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: 4905aef1-6ff3-4ebd-8005-734bde9b734b
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (6)
packages/core/package.jsonpackages/core/src/middleware.tspackages/core/src/pages/api/fs/auth/login.tspackages/core/src/pages/fs-auth-login/index.tsxpackages/core/src/server/password-protection/auth-cookie.tspackages/core/src/server/password-protection/login-response.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/core/src/middleware.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/core/src/pages/api/fs/auth/login.ts (1)
11-12: 💤 Low valueConsider extracting shared auth constants.
COOKIE_NAMEandTOKEN_TTL_SECONDSare duplicated here and inauthentication-service.ts(see context snippet 2:maxAge: TOKEN_TTL_SECONDS). Extracting these to a shared module (e.g.,webops-api.tsor a dedicatedauth-constants.ts) would prevent drift if values change.🤖 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/auth/login.ts` around lines 11 - 12, COOKIE_NAME and TOKEN_TTL_SECONDS are duplicated between this file and authentication-service.ts, which can drift; extract these constants into a shared module (e.g., auth-constants.ts or webops-api.ts) and import them in both places so both the login handler (COOKIE_NAME, TOKEN_TTL_SECONDS) and authentication-service (where maxAge: TOKEN_TTL_SECONDS is used) reference the same exported symbols, update imports, and remove the local definitions.
🤖 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.
Nitpick comments:
In `@packages/core/src/pages/api/fs/auth/login.ts`:
- Around line 11-12: COOKIE_NAME and TOKEN_TTL_SECONDS are duplicated between
this file and authentication-service.ts, which can drift; extract these
constants into a shared module (e.g., auth-constants.ts or webops-api.ts) and
import them in both places so both the login handler (COOKIE_NAME,
TOKEN_TTL_SECONDS) and authentication-service (where maxAge: TOKEN_TTL_SECONDS
is used) reference the same exported symbols, update imports, and remove the
local definitions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 61456542-bedb-4097-a530-08b09ab75f1f
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (7)
packages/core/package.jsonpackages/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/utils/loginResponse.tspackages/core/test/server/authentication-service.test.ts
💤 Files with no reviewable changes (1)
- packages/core/test/server/authentication-service.test.ts
✅ Files skipped from review due to trivial changes (2)
- packages/core/src/utils/loginResponse.ts
- packages/core/package.json
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/core/src/server/authentication-service.ts
- packages/core/src/pages/fs-auth-login/index.tsx
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/core/src/pages/api/fs/auth/login.ts (1)
101-103: 💤 Low valuePotential header injection if token contains special characters.
The token is interpolated directly into the
Set-Cookieheader string. If WebOps ever returns a token containing semicolons, newlines, or other special characters, this could cause cookie parsing issues or header injection.Consider using
encodeURIComponenton the token value, or leverage theres.setHeaderwith proper cookie serialization.♻️ Defensive encoding
response.setHeader('Set-Cookie', [ - `${COOKIE_NAME}=${data.token}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${TOKEN_TTL_SECONDS}`, + `${COOKIE_NAME}=${encodeURIComponent(data.token)}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${TOKEN_TTL_SECONDS}`, ])🤖 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/auth/login.ts` around lines 101 - 103, The Set-Cookie header construction in response.setHeader is vulnerable to header injection because the token is interpolated raw; update the login response to safely serialize/encode the cookie value (e.g., use encodeURIComponent or a cookie serializer) before inserting it into the header so characters like semicolons or newlines cannot break the header. Locate the response.setHeader call that builds `${COOKIE_NAME}=${data.token}; ... Max-Age=${TOKEN_TTL_SECONDS}` and replace it with a properly encoded/serialized cookie value for COOKIE_NAME while preserving attributes (HttpOnly, Secure, SameSite, Path, Max-Age).
🤖 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.
Nitpick comments:
In `@packages/core/src/pages/api/fs/auth/login.ts`:
- Around line 101-103: The Set-Cookie header construction in response.setHeader
is vulnerable to header injection because the token is interpolated raw; update
the login response to safely serialize/encode the cookie value (e.g., use
encodeURIComponent or a cookie serializer) before inserting it into the header
so characters like semicolons or newlines cannot break the header. Locate the
response.setHeader call that builds `${COOKIE_NAME}=${data.token}; ...
Max-Age=${TOKEN_TTL_SECONDS}` and replace it with a properly encoded/serialized
cookie value for COOKIE_NAME while preserving attributes (HttpOnly, Secure,
SameSite, Path, Max-Age).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3f6c1c58-a62f-4bfc-819a-41fb86ff62bd
📒 Files selected for processing (2)
packages/core/src/pages/api/fs/auth/login.tspackages/core/src/server/authentication-service.ts
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). This version applies to version 3.x of FastStore.
How to test it?
Password protection setup on WebOps: https://faststoreplatform3.myvtex.com/admin/webops/deployments
Running store: https://sfj-ba4d8c7--faststoreplatform3.preview.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
New Features
Bug Fixes / Improvements