Skip to content

feat: Password Protection (v3) - #3347

Merged
vlaux merged 26 commits into
3.xfrom
feat/3.x/password-protection
Jun 2, 2026
Merged

vlaux merged 26 commits into
3.xfrom
feat/3.x/password-protection

Conversation

@vlaux

@vlaux vlaux commented May 26, 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). 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

  • 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

  • New Features

    • Password protection for storefronts with automatic enforcement via middleware.
    • User-facing password login page that posts credentials and redirects back after successful login.
    • API endpoint for password authentication that sets an HttpOnly auth cookie on success.
  • Bug Fixes / Improvements

    • Improved session handling and token renewal to reduce unexpected logouts.

@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

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

Changes

Password Protection System

Layer / File(s) Summary
CLI: Remove old middleware enablement
packages/cli/src/utils/generate.ts
Deletes ENABLE_REDIRECTS_MIDDLEWARE constant and enableRedirectsMiddleware() and removes its call from generate() orchestration.
WebOps API: Endpoints and timeout configuration
packages/core/src/server/password-protection/webops-api.ts, packages/core/package.json
Exports URL builders for public key, protection status (includes storeId), session, and renew endpoints; sanitizes WEBOPS_API_URL; adds jose dependency.
Login response validation helper
packages/core/src/utils/loginResponse.ts
Defines LoginResponse interface and isLoginResponse type guard for API/UI response validation.
Authentication service: Token verification and renewal
packages/core/src/server/authentication-service.ts
Adds AuthenticationService with WebOps public-key fetch & cache, jwt verification, expired-token decode+renewal, protection-status checks, scope-to-host enforcement, auth cookie writing, and login redirect logic.
Request middleware: Auth enforcement and optional redirects
packages/core/src/middleware.ts
Middleware invokes AuthenticationService, returns auth responses or errors, and optionally resolves path redirects via a RedirectsClient (stubbed) when enabled; exports config.matcher.
Login API endpoint: Password validation and token issuance
packages/core/src/pages/api/fs/auth/login.ts
POST handler validating password, calling WebOps session endpoint with timeout, mapping errors, validating shape, setting __fs_auth_token cookie (HttpOnly, Secure, SameSite=Lax, TTL), and returning { success, redirectUrl } or error.
Login page: UI component and styles
packages/core/src/pages/fs-auth-login/index.tsx, packages/core/src/pages/fs-auth-login/fs-auth-login.module.scss
PasswordProtectionLogin posts password to login API with returnTo, validates response, redirects on success, shows loading/errors; SCSS adds layout and form styles and noindex,nofollow.
Tests: Authentication service behavior and token handling
packages/core/test/server/authentication-service.test.ts
Comprehensive Jest suite covering development bypass, WebOps status handling, JWT verify/renew flows, scope matching, fail-closed redirects, and cookie expectations across env configurations.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • vtex/faststore#3185: Modifies packages/cli/src/utils/generate.ts related to middleware enablement/renaming.

Suggested labels

enhancement

Suggested reviewers

  • emersonlaurentino
  • hellofanny
  • renatomaurovtex

Poem

🔐 Tokens hum, the middleware wakes,
Cookies set for guarded takes.
WebOps checks and renews the night,
Login form guides the safe-flight.
Tests assure the path is tight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% 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 (v3)' clearly summarizes the main change—adding password protection for FastStore 3.x—and aligns with the changeset's primary objective of protecting preview deployments.
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/3.x/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 base branch from dev to 3.x May 26, 2026 14:43
@codesandbox-ci

codesandbox-ci Bot commented May 26, 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.

vlaux added 16 commits May 26, 2026 11:52
…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.
@vlaux
vlaux force-pushed the feat/3.x/password-protection branch from 424e521 to 9e369ff Compare May 26, 2026 15:22
@vlaux
vlaux marked this pull request as ready for review May 26, 2026 15:46
@vlaux
vlaux requested a review from a team as a code owner May 26, 2026 15:46
@vlaux
vlaux requested review from lariciamota and ommeirelles and removed request for a team May 26, 2026 15:46
@vlaux
vlaux marked this pull request as draft May 26, 2026 15:46
@vlaux
vlaux requested review from lemagnetic and removed request for lariciamota and ommeirelles May 26, 2026 15:47
@vlaux vlaux self-assigned this May 26, 2026

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

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

99-108: 💤 Low value

Simplify 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 win

Consider 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 return false
  • x-forwarded-proto as 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

📥 Commits

Reviewing files that changed from the base of the PR and between 5636f4f and 9e369ff.

⛔ Files ignored due to path filters (1)
  • .gitignore is excluded by none and included by none
📒 Files selected for processing (11)
  • packages/cli/src/utils/generate.ts
  • 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/core/src/middleware__DISABLED.ts
  • packages/cli/src/utils/generate.ts

Comment thread packages/core/src/middleware.ts Resolved
@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/cli

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/components

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/core

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/graphql-utils

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/lighthouse

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/sdk

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

@faststore/ui

yarn add https://pkg.pr.new/vtex/faststore/@faststore/[email protected]

commit: 1a948f3

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9e369ff and 309b98f.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (6)
  • packages/core/package.json
  • 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/password-protection/auth-cookie.ts
  • packages/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

@vlaux
vlaux marked this pull request as ready for review May 27, 2026 12:39

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

🧹 Nitpick comments (1)
packages/core/src/pages/api/fs/auth/login.ts (1)

11-12: 💤 Low value

Consider extracting shared auth constants.

COOKIE_NAME and TOKEN_TTL_SECONDS are duplicated here and in authentication-service.ts (see context snippet 2: maxAge: TOKEN_TTL_SECONDS). Extracting these to a shared module (e.g., webops-api.ts or a dedicated auth-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

📥 Commits

Reviewing files that changed from the base of the PR and between 9e369ff and 139b8ba.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (7)
  • packages/core/package.json
  • 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/utils/loginResponse.ts
  • packages/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

@vlaux
vlaux requested a review from lemagnetic June 2, 2026 13:18

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

🧹 Nitpick comments (1)
packages/core/src/pages/api/fs/auth/login.ts (1)

101-103: 💤 Low value

Potential header injection if token contains special characters.

The token is interpolated directly into the Set-Cookie header 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 encodeURIComponent on the token value, or leverage the res.setHeader with 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

📥 Commits

Reviewing files that changed from the base of the PR and between 139b8ba and 1a948f3.

📒 Files selected for processing (2)
  • packages/core/src/pages/api/fs/auth/login.ts
  • packages/core/src/server/authentication-service.ts

@vlaux
vlaux merged commit e215c72 into 3.x Jun 2, 2026
5 checks passed
@vlaux
vlaux deleted the feat/3.x/password-protection branch June 2, 2026 19:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants