From ee0b79af1f8937811a160fcb6d8b5dc9cb9a5828 Mon Sep 17 00:00:00 2001 From: Jon de Andres Frias Date: Mon, 16 Nov 2026 22:55:55 -0800 Subject: [PATCH] Add forgot password A "Forgot password?" link on the sign-in form leads to /forgot-password, which asks the backend for a reset link with client: "desktop", so the emailed link is a nodea:///reset-password/ deep link back into the app. /reset-password/:token checks the link, sets the new password, and lands on sign in with the email filled in and a notice. The reset signs the account out everywhere, so a signed-in app signs out locally too. The password rule SignupPage checked moves to src/lib/validation.ts so both forms share it. Needs nodea-sh/nodea#343 (the /v1/password-reset endpoints). --- src/App.tsx | 4 + src/components/DeepLinkListener.tsx | 18 ++-- src/lib/api.ts | 21 +++++ src/lib/mockApi.ts | 18 ++++ src/lib/validation.ts | 14 +++ src/pages/ForgotPasswordPage.tsx | 81 ++++++++++++++++ src/pages/LoginPage.tsx | 17 +++- src/pages/ResetPasswordPage.tsx | 140 ++++++++++++++++++++++++++++ src/pages/SignupPage.tsx | 14 +-- tests/forgot-password.spec.ts | 89 ++++++++++++++++++ 10 files changed, 393 insertions(+), 23 deletions(-) create mode 100644 src/lib/validation.ts create mode 100644 src/pages/ForgotPasswordPage.tsx create mode 100644 src/pages/ResetPasswordPage.tsx create mode 100644 tests/forgot-password.spec.ts diff --git a/src/App.tsx b/src/App.tsx index 01d33cc..b2db234 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -5,6 +5,8 @@ import { ProtectedRoute } from './components/ProtectedRoute' import { DeepLinkListener } from './components/DeepLinkListener' import { AppLayout } from './components/layout/AppLayout' import { LoginPage } from './pages/LoginPage' +import { ForgotPasswordPage } from './pages/ForgotPasswordPage' +import { ResetPasswordPage } from './pages/ResetPasswordPage' import { SignupPage } from './pages/SignupPage' import { ConfirmEmailPage } from './pages/ConfirmEmailPage' import { AcceptInvitationPage } from './pages/AcceptInvitationPage' @@ -30,6 +32,8 @@ function App() { } /> + } /> + } /> } /> } /> } /> diff --git a/src/components/DeepLinkListener.tsx b/src/components/DeepLinkListener.tsx index 20f3b34..1e855db 100644 --- a/src/components/DeepLinkListener.tsx +++ b/src/components/DeepLinkListener.tsx @@ -4,15 +4,17 @@ import { listen } from '@tauri-apps/api/event' import { isTauriApp } from '@/lib/platform' /** - * Bridges nodea:// deep links (opened from invitation/confirm-email - * emails) into the React Router. The Rust side (src-tauri/src/main.rs) - * registers the OS-level scheme handler and forwards incoming links here - * via the "scheme-request-received" event. + * Bridges nodea:// deep links (opened from emails) into the React Router. + * The Rust side (src-tauri/src/main.rs) registers the OS-level scheme + * handler and forwards incoming links here via the + * "scheme-request-received" event. * - * FRONTEND_BASE_URL is "nodea://" in production, so a link built as - * `${FRONTEND_BASE_URL}/confirm-email/${token}` becomes - * "nodea:///confirm-email/" - an empty host with the app route as - * the URL's pathname, which is what we navigate to below. + * The backend builds the password reset links this app asks for from + * DESKTOP_FRONTEND_BASE_URL, "nodea://" in production, so + * `${DESKTOP_FRONTEND_BASE_URL}/reset-password/${token}` becomes + * "nodea:///reset-password/" - an empty host with the app route as + * the URL's pathname, which is what we navigate to below. Its other links + * (FRONTEND_BASE_URL) open the web console. */ export function DeepLinkListener() { const navigate = useNavigate() diff --git a/src/lib/api.ts b/src/lib/api.ts index 90d316d..9c74a44 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -563,6 +563,27 @@ class ApiClient { body: JSON.stringify({ email }), }) } + + // Forgot password - public, the user cannot sign in. The emailed link is a + // nodea:// deep link back into this app (client: 'desktop'). + async requestPasswordReset(email: string): Promise<{ message: string }> { + return this.fetch<{ message: string }>('/v1/password-reset', { + method: 'POST', + body: JSON.stringify({ email, client: 'desktop' }), + }) + } + + // Answers 410 for a link that is unknown, used, replaced or expired. + async checkPasswordReset(token: string): Promise<{ email: string }> { + return this.fetch<{ email: string }>(`/v1/password-reset/${encodeURIComponent(token)}`) + } + + async resetPassword(token: string, password: string): Promise<{ message: string; email: string }> { + return this.fetch<{ message: string; email: string }>(`/v1/password-reset/${encodeURIComponent(token)}`, { + method: 'POST', + body: JSON.stringify({ password }), + }) + } } diff --git a/src/lib/mockApi.ts b/src/lib/mockApi.ts index 9be202b..6bbfbb7 100644 --- a/src/lib/mockApi.ts +++ b/src/lib/mockApi.ts @@ -688,6 +688,24 @@ export class MockApiClient { return { message: 'Confirmation email resent' } } + // Forgot password + async requestPasswordReset(_email: string): Promise<{ message: string }> { + await delay(300) + console.log('Mock: Password reset email sent') + return { message: 'If an account exists for this email, a reset link is on its way' } + } + + async checkPasswordReset(_token: string): Promise<{ email: string }> { + await delay(200) + return { email: 'demo@getnodea.com' } + } + + async resetPassword(_token: string, _password: string): Promise<{ message: string; email: string }> { + await delay(300) + console.log('Mock: Password reset') + return { message: 'Password updated', email: 'demo@getnodea.com' } + } + // Onboarding async createOrganizationOnboarding(): Promise<{ organization: Organization }> { await delay(500) diff --git a/src/lib/validation.ts b/src/lib/validation.ts new file mode 100644 index 0000000..af46d3e --- /dev/null +++ b/src/lib/validation.ts @@ -0,0 +1,14 @@ +// Mirrors the backend's validation.validate_password, so the form can say what +// is wrong before submitting. +export function validatePassword(password: string): string | null { + if (password.length < 8) { + return 'Password must be at least 8 characters long' + } + if (!/[A-Za-z]/.test(password)) { + return 'Password must contain at least 1 letter' + } + if (!/\d/.test(password)) { + return 'Password must contain at least 1 digit' + } + return null +} diff --git a/src/pages/ForgotPasswordPage.tsx b/src/pages/ForgotPasswordPage.tsx new file mode 100644 index 0000000..3abe8d8 --- /dev/null +++ b/src/pages/ForgotPasswordPage.tsx @@ -0,0 +1,81 @@ +import { useState } from 'react' +import { Link, useLocation } from 'react-router-dom' +import { apiClient } from '@/lib/api' + +/* Same layout as LoginPage, which links here with the email typed there. */ +export function ForgotPasswordPage() { + const location = useLocation() + const [email, setEmail] = useState((location.state as { email?: string } | null)?.email ?? '') + const [sending, setSending] = useState(false) + const [sent, setSent] = useState(false) + const [error, setError] = useState('') + + const submit = async (e: React.FormEvent) => { + e.preventDefault() + setError('') + setSending(true) + try { + await apiClient.requestPasswordReset(email) + setSent(true) + } catch (err) { + setError(err instanceof Error ? err.message : 'Could not send a reset link') + } finally { + setSending(false) + } + } + + return ( +
+
+ + + N + + +

+ Reset your password +

+ + {sent ? ( + <> + {/* The backend answers the same for any address, so neither can we. */} +

+ If an account exists for {email}, a link to + reset its password is on its way. Open it on this computer to come back to the app. It works for + one hour. +

+ + Back to sign in + + + ) : ( + <> +

+ Enter the email of your account and we'll send you a link to choose a new password. +

+ +
+ {error &&

{error}

} + + setEmail(e.target.value)} + required autoFocus + placeholder="you@company.com" + className="rounded-[8px] border border-[var(--n-border)] bg-[var(--n-sidebar)] px-3 py-2.5 text-[15px] leading-[1.2] text-[var(--n-text)] outline-none placeholder:text-[var(--n-text-4)] focus:border-[var(--n-accent-800)]" /> + + + +

+ + Back to sign in + +

+
+ + )} +
+ ) +} diff --git a/src/pages/LoginPage.tsx b/src/pages/LoginPage.tsx index 607d620..ac1e64e 100644 --- a/src/pages/LoginPage.tsx +++ b/src/pages/LoginPage.tsx @@ -1,7 +1,8 @@ import { useState, useEffect } from 'react' -import { Link, useNavigate, useSearchParams } from 'react-router-dom' +import { Link, useLocation, useNavigate, useSearchParams } from 'react-router-dom' import { useAuth } from '@/contexts/AuthContext' import { apiClient } from '@/lib/api' +import type { PasswordResetLoginState } from './ResetPasswordPage' // Only accounts created before signups could log in unconfirmed still get // this from Supabase; confirming (or resending) the link unblocks them. @@ -12,7 +13,9 @@ function isEmailNotConfirmedError(message: string): boolean { /* Keeps the existing auth calls (invitation sign-up, unconfirmed-email * resend, post-login redirect) — only the presentation changes. */ export function LoginPage() { - const [email, setEmail] = useState('') + // Set when arriving from a finished password reset. + const resetState = useLocation().state as PasswordResetLoginState | null + const [email, setEmail] = useState(resetState?.email ?? '') const [password, setPassword] = useState('') const [error, setError] = useState('') const [loading, setLoading] = useState(false) @@ -129,6 +132,11 @@ export function LoginPage() { This account was deleted. This device stopped sharing compute.

)} + {resetState?.passwordReset && ( +

+ Your password was changed. Sign in with your new password. +

+ )}

{isInvitedSignup ? <>Joining {invitationDetails?.organizationName} as {invitationDetails?.role}. @@ -174,6 +182,11 @@ export function LoginPage() { Sign up + {' · '} + + Forgot password? +

)} diff --git a/src/pages/ResetPasswordPage.tsx b/src/pages/ResetPasswordPage.tsx new file mode 100644 index 0000000..fab34ac --- /dev/null +++ b/src/pages/ResetPasswordPage.tsx @@ -0,0 +1,140 @@ +import { useEffect, useState } from 'react' +import { Link, useNavigate, useParams } from 'react-router-dom' +import { apiClient } from '@/lib/api' +import { useAuth } from '@/contexts/AuthContext' +import { validatePassword } from '@/lib/validation' + +type LinkState = 'checking' | 'valid' | 'invalid' + +// Read by LoginPage to say the password changed and prefill the email. +export interface PasswordResetLoginState { + passwordReset: true + email: string +} + +const inputClass = + 'rounded-[8px] border border-[var(--n-border)] bg-[var(--n-sidebar)] px-3 py-2.5 text-[15px] leading-[1.2] text-[var(--n-text)] outline-none placeholder:text-[var(--n-text-4)] focus:border-[var(--n-accent-800)]' + +/* Opened from the emailed nodea:///reset-password/ link (see + * DeepLinkListener). Same layout as LoginPage. */ +export function ResetPasswordPage() { + const { token } = useParams<{ token: string }>() + const navigate = useNavigate() + const { isAuthenticated, logout } = useAuth() + + const [linkState, setLinkState] = useState('checking') + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [confirm, setConfirm] = useState('') + const [saving, setSaving] = useState(false) + const [error, setError] = useState('') + + // Checking does not use the link up, so a second call (StrictMode) is harmless. + useEffect(() => { + if (!token) { + setLinkState('invalid') + return + } + + let cancelled = false + apiClient + .checkPasswordReset(token) + .then(({ email }) => { + if (cancelled) return + setEmail(email) + setLinkState('valid') + }) + .catch(() => { + if (!cancelled) setLinkState('invalid') + }) + return () => { + cancelled = true + } + }, [token]) + + const submit = async (e: React.FormEvent) => { + e.preventDefault() + setError('') + + const passwordError = validatePassword(password) + if (passwordError) { + setError(passwordError) + return + } + if (password !== confirm) { + setError('Passwords do not match') + return + } + + setSaving(true) + try { + const result = await apiClient.resetPassword(token!, password) + // The reset signed the account out everywhere, this app included. + if (isAuthenticated) await logout().catch(() => {}) + const state: PasswordResetLoginState = { passwordReset: true, email: result.email } + navigate('/login', { replace: true, state }) + } catch (err) { + setError(err instanceof Error ? err.message : 'Could not reset your password') + setSaving(false) + } + } + + return ( +
+
+ + + N + + +

+ {linkState === 'invalid' ? 'Link expired or invalid' : 'Choose a new password'} +

+ + {linkState === 'checking' && ( +

Checking your link…

+ )} + + {linkState === 'invalid' && ( + <> +

+ This reset link has expired, was already used, or a newer one was sent. +

+ + Send a new link + + + )} + + {linkState === 'valid' && ( + <> +

+ For {email}. You'll be signed out everywhere + and can sign in with it straight away. +

+ +
+ {error &&

{error}

} + + setPassword(e.target.value)} + required autoFocus autoComplete="new-password" + placeholder="New password" + className={inputClass} /> + setConfirm(e.target.value)} + required autoComplete="new-password" + placeholder="Confirm new password" + className={inputClass} /> +

At least 8 characters, with a letter and a digit.

+ + +
+ + )} +
+ ) +} diff --git a/src/pages/SignupPage.tsx b/src/pages/SignupPage.tsx index b6c0d6c..fd6f0e2 100644 --- a/src/pages/SignupPage.tsx +++ b/src/pages/SignupPage.tsx @@ -6,19 +6,7 @@ import { Input } from '@/components/ui/input' import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' import { Alert, AlertDescription } from '@/components/ui/alert' import { useAuth } from '@/contexts/AuthContext' - -function validatePassword(password: string): string | null { - if (password.length < 8) { - return 'Password must be at least 8 characters long' - } - if (!/[A-Za-z]/.test(password)) { - return 'Password must contain at least 1 letter' - } - if (!/\d/.test(password)) { - return 'Password must contain at least 1 digit' - } - return null -} +import { validatePassword } from '@/lib/validation' export function SignupPage() { const [email, setEmail] = useState('') diff --git a/tests/forgot-password.spec.ts b/tests/forgot-password.spec.ts new file mode 100644 index 0000000..95a7f7d --- /dev/null +++ b/tests/forgot-password.spec.ts @@ -0,0 +1,89 @@ +import { test, expect, type Page, type Request } from '@playwright/test' + +/** + * Forgot password, with the backend's three /v1/password-reset routes stubbed. + * Not demo mode: these go through the real src/lib/api.ts, so the request each + * page sends is checked as well. + */ + +const GOOD_TOKEN = 'good-token' + +async function stubPasswordReset(page: Page) { + const requests: Request[] = [] + await page.route( + (url) => url.pathname.startsWith('/site/v1/password-reset'), + (route) => { + const request = route.request() + requests.push(request) + const token = new URL(request.url()).pathname.split('/')[4] + + if (!token) { + return route.fulfill({ status: 202, json: { message: 'If an account exists for this email, a reset link is on its way' } }) + } + if (token !== GOOD_TOKEN) { + return route.fulfill({ status: 410, json: { error: 'Invalid or expired password reset link' } }) + } + return request.method() === 'GET' + ? route.fulfill({ json: { email: 'person@getnodea.com' } }) + : route.fulfill({ json: { message: 'Password updated', email: 'person@getnodea.com' } }) + } + ) + return requests +} + +test.describe('Forgot password', () => { + test('asks for a link that opens this app, keeping the email typed on the login form', async ({ page }) => { + const requests = await stubPasswordReset(page) + + await page.goto('/login') + await page.fill('#email', 'person@getnodea.com') + await page.getByRole('link', { name: /forgot password/i }).click() + + await expect(page).toHaveURL(/\/forgot-password$/) + await expect(page.locator('#email')).toHaveValue('person@getnodea.com') + await page.getByRole('button', { name: /send reset link/i }).click() + + await expect(page.getByRole('status')).toContainText(/if an account exists for/i) + expect(requests).toHaveLength(1) + expect(requests[0].method()).toBe('POST') + expect(requests[0].postDataJSON()).toEqual({ email: 'person@getnodea.com', client: 'desktop' }) + }) + + test('sets a new password and lands on sign in with the email filled in', async ({ page }) => { + const requests = await stubPasswordReset(page) + + await page.goto(`/reset-password/${GOOD_TOKEN}`) + await expect(page.getByText('person@getnodea.com')).toBeVisible() + + // Refused before anything is sent, so the link is not spent. + await page.getByLabel('New password', { exact: true }).fill('short') + await page.getByLabel('Confirm new password').fill('short') + await page.getByRole('button', { name: /set new password/i }).click() + await expect(page.getByRole('alert')).toContainText(/at least 8 characters/i) + + await page.getByLabel('New password', { exact: true }).fill('newpass123') + await page.getByLabel('Confirm new password').fill('newpass124') + await page.getByRole('button', { name: /set new password/i }).click() + await expect(page.getByRole('alert')).toContainText(/do not match/i) + expect(requests.filter((r) => r.method() === 'POST')).toHaveLength(0) + + await page.getByLabel('Confirm new password').fill('newpass123') + await page.getByRole('button', { name: /set new password/i }).click() + + await expect(page).toHaveURL(/\/login$/) + await expect(page.getByRole('status')).toContainText(/your password was changed/i) + await expect(page.locator('#email')).toHaveValue('person@getnodea.com') + const reset = requests.find((r) => r.method() === 'POST')! + expect(reset.postDataJSON()).toEqual({ password: 'newpass123' }) + }) + + test('a link that no longer works offers a new one', async ({ page }) => { + await stubPasswordReset(page) + + await page.goto('/reset-password/spent-token') + + await expect(page.getByText(/link expired or invalid/i)).toBeVisible() + await page.getByRole('link', { name: /send a new link/i }).click() + await expect(page).toHaveURL(/\/forgot-password$/) + }) +})