-
Notifications
You must be signed in to change notification settings - Fork 78
feat: password protected stores #3276
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vlaux
wants to merge
17
commits into
dev
Choose a base branch
from
feat/password-protection
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
361a415
feat(core): add AuthenticationService for password protection
vlaux f247d80
feat(core): enable middleware always, add password protection and con…
vlaux b087d22
feat(password-protection) retrieve public key from webops
vlaux 7d9eef2
refactor(core): centralize WebOps password-protection API URLs and ti…
vlaux cfe7d95
feat(core): secure auth cookie rules and test password protection flow
vlaux cdd81e1
fix(password-protection): always fail close if webops not available
vlaux d1c12a3
feat(core): protection login page using internal styles
vlaux d4400ee
test(password-protection): fix and add more tests
vlaux f79a573
chore: properly encode search param values
vlaux 77fe5fd
fix: keep query params on returnTo
vlaux 1f0f960
chore: do not allow indexing of auth page
vlaux 3cfaa4e
fix: cookies being dropped during authentication
vlaux bc89347
fix: sanitize return url
vlaux 5e7f321
fix: do not return invalid password when webops unavailable
vlaux 9c7f6de
refactor: update WebOps API URL handling to use dynamic functions
vlaux 5fad874
chore: normalize host before checking .vtex.app.
vlaux 4850045
fix: isLocalHost misparses bracketed IPv6 hosts
vlaux File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| .turbo | ||
| .next | ||
| *.tsbuildinfo | ||
|
|
||
| # Logs | ||
| logs | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| /* | ||
| * Middleware is always active. It runs: | ||
| * 1. Password protection (AuthenticationService) — when applicable (default/custom domains per env). | ||
| * 2. Redirects — only when ENABLE_REDIRECTS_MIDDLEWARE is set at runtime. | ||
| */ | ||
|
|
||
| import { NextResponse } from 'next/server' | ||
| import type { NextRequest } from 'next/server' | ||
| import storeConfig from 'discovery.config' | ||
|
|
||
| import { AuthenticationService } from './server/authentication-service' | ||
|
|
||
| type Redirect = { | ||
| from: string | ||
| to: string | ||
| type: 'permanent' | 'temporary' | ||
| } | ||
| interface RedirectsClient { | ||
| get(from: string): Promise<Redirect | null> | ||
| } | ||
|
|
||
| class DynamoRedirectsClient implements RedirectsClient { | ||
| async get(_from: string): Promise<Redirect | null> { | ||
| // TODO: Implement DynamoDB client. Ensure that the cluster has access to DynamoDB first. | ||
| return null | ||
| } | ||
| } | ||
|
|
||
| const redirectsClient = new DynamoRedirectsClient() | ||
|
|
||
| export async function middleware(request: NextRequest) { | ||
| const path = request.nextUrl.pathname | ||
|
|
||
| try { | ||
| const authService = new AuthenticationService() | ||
| const authResult = await authService.authenticateRequest(request) | ||
|
|
||
| if (authResult.response.status !== 200) { | ||
| return authResult.response | ||
| } | ||
|
|
||
| if (process.env.ENABLE_REDIRECTS_MIDDLEWARE === 'true') { | ||
| const redirect = await redirectsClient.get(path) | ||
|
|
||
| if (redirect) { | ||
| const redirectUrl = new URL(redirect.to, storeConfig.storeUrl) | ||
| const redirectStatusCode = redirect.type === 'permanent' ? 301 : 302 | ||
| const response = NextResponse.redirect(redirectUrl, redirectStatusCode) | ||
|
|
||
| for (const cookie of authResult.response.cookies.getAll()) { | ||
| response.cookies.set(cookie) | ||
| } | ||
|
|
||
| response.headers.set( | ||
| 'Cache-Control', | ||
| 'public, max-age=300, stale-while-revalidate=31536000' | ||
| ) | ||
|
|
||
| return response | ||
| } | ||
| } | ||
|
|
||
| return authResult.response | ||
| } catch { | ||
| return NextResponse.next() | ||
| } | ||
| } | ||
|
|
||
| export const config = { | ||
| matcher: [ | ||
| /* | ||
| * Match all paths including `/` | ||
| * Exclude: | ||
| * - api (e.g. api/fs/auth/login) | ||
| * - _next/static, _next/image | ||
| * - favicon.ico | ||
| * - fs-auth-login (login page) | ||
| * - ~partytown (partytown scripts) | ||
| */ | ||
| '/', | ||
| '/((?!api|_next/static|_next/image|favicon.ico|fs-auth-login|~partytown).*)', | ||
| ], | ||
| } | ||
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next' | ||
|
|
||
| import storeConfig from 'discovery.config' | ||
|
|
||
| import { isSecureAuthCookieForPagesApi } from '../../../../server/password-protection/auth-cookie' | ||
| import { | ||
| sessionUrl, | ||
| passwordProtectionTimeouts, | ||
| } from '../../../../server/password-protection/webops-api' | ||
|
|
||
| const COOKIE_NAME = '__fs_auth_token' | ||
| const TOKEN_TTL_SECONDS = 10 * 60 | ||
|
|
||
| const isSafeReturnToPath = (value: string): boolean => { | ||
| return value.startsWith('/') && !value.startsWith('//') | ||
| } | ||
|
|
||
| const handler: NextApiHandler = async ( | ||
| request: NextApiRequest, | ||
| response: NextApiResponse | ||
| ) => { | ||
| if (request.method !== 'POST') { | ||
| response.status(405).end() | ||
| return | ||
| } | ||
|
|
||
| const storeId = storeConfig.api.storeId | ||
|
|
||
| try { | ||
| const { password } = request.body ?? {} | ||
|
|
||
| if (!password || typeof password !== 'string') { | ||
| response.status(400).json({ | ||
| success: false, | ||
| error: 'Password is required', | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| const webopsResponse = await fetch(sessionUrl(), { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json' }, | ||
| body: JSON.stringify({ storeId, password }), | ||
| signal: AbortSignal.timeout(passwordProtectionTimeouts.defaultMs), | ||
| }) | ||
|
|
||
| if (!webopsResponse.ok) { | ||
| if (webopsResponse.status === 401 || webopsResponse.status === 403) { | ||
| response.status(401).json({ | ||
| success: false, | ||
| error: 'Invalid password', | ||
| }) | ||
| return | ||
| } | ||
|
|
||
| response.status(503).json({ | ||
| success: false, | ||
| error: 'Service temporarily unavailable', | ||
| }) | ||
| return | ||
| } | ||
|
vlaux marked this conversation as resolved.
|
||
|
|
||
| const data = await webopsResponse.json() | ||
|
|
||
| if (data.valid && data.token) { | ||
| const returnTo = | ||
| typeof request.query.returnTo === 'string' | ||
| ? request.query.returnTo | ||
| : '/' | ||
| const sanitizedReturnTo = isSafeReturnToPath(returnTo) ? returnTo : '/' | ||
|
|
||
| const securePart = isSecureAuthCookieForPagesApi(request) | ||
| ? '; Secure' | ||
| : '' | ||
|
|
||
| response.setHeader('Set-Cookie', [ | ||
| `${COOKIE_NAME}=${data.token}; HttpOnly${securePart}; SameSite=Lax; Path=/; Max-Age=${TOKEN_TTL_SECONDS}`, | ||
| ]) | ||
|
|
||
| response.status(200).json({ | ||
| success: true, | ||
| redirectUrl: sanitizedReturnTo, | ||
| }) | ||
| } else { | ||
| response.status(401).json({ | ||
| success: false, | ||
| error: 'Invalid password', | ||
| }) | ||
| } | ||
| } catch { | ||
| response.status(503).json({ | ||
| success: false, | ||
| error: 'Service temporarily unavailable', | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| export default handler | ||
41 changes: 41 additions & 0 deletions
41
packages/core/src/pages/fs-auth-login/fs-auth-login.module.scss
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| @layer components { | ||
| .fsAuthLogin { | ||
| @import "@faststore/ui/src/components/atoms/Button/styles.scss"; | ||
| @import "@faststore/ui/src/components/atoms/Input/styles.scss"; | ||
| @import "@faststore/ui/src/components/atoms/Loader/styles.scss"; | ||
| @import "@faststore/ui/src/components/molecules/InputField/styles.scss"; | ||
| } | ||
| } | ||
|
|
||
| .page { | ||
| display: flex; | ||
| flex-direction: column; | ||
| align-items: center; | ||
| justify-content: center; | ||
| min-height: 100vh; | ||
| padding: var(--fs-spacing-3); | ||
| } | ||
|
|
||
| .title { | ||
| margin: 0 0 var(--fs-spacing-6) 0; | ||
| font-size: var(--fs-text-size-title-section); | ||
| font-weight: var(--fs-text-weight-bold); | ||
| } | ||
|
|
||
| .subtitle { | ||
| margin: 0 0 var(--fs-spacing-3) 0; | ||
| font-size: var(--fs-text-size-body); | ||
| } | ||
|
|
||
| .form { | ||
| display: flex; | ||
| flex-direction: column; | ||
| gap: var(--fs-spacing-2); | ||
| align-items: stretch; | ||
| width: 100%; | ||
| max-width: 20rem; | ||
|
|
||
| button { | ||
| align-self: center; | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Don't fail open when auth throws.
The outer
catchturns any unexpected auth error intoNextResponse.next(), which exposes protected previews instead of keeping the request behind the gate. Keep the auth path outside that fail-open branch, and only soften redirect lookup failures if needed.🩹 Proposed fix
export async function middleware(request: NextRequest) { const path = request.nextUrl.pathname + const authService = new AuthenticationService() + const authResult = await authService.authenticateRequest(request) - try { - const authService = new AuthenticationService() - const authResult = await authService.authenticateRequest(request) - - if (authResult.response.status !== 200) { - return authResult.response - } + if (authResult.response.status !== 200) { + return authResult.response + } - if (process.env.ENABLE_REDIRECTS_MIDDLEWARE === 'true') { + if (process.env.ENABLE_REDIRECTS_MIDDLEWARE === 'true') { + try { const redirect = await redirectsClient.get(path) if (redirect) { const redirectUrl = new URL(redirect.to, storeConfig.storeUrl) const redirectStatusCode = redirect.type === 'permanent' ? 301 : 302 @@ return response } + } catch { + return authResult.response } - - return authResult.response - } catch { - return NextResponse.next() } + + return authResult.response }📝 Committable suggestion
🤖 Prompt for AI Agents