diff --git a/backend/src/auth/__tests__/auth-copy-capability.spec.ts b/backend/src/auth/__tests__/auth-copy-capability.spec.ts new file mode 100644 index 00000000..fe83669e --- /dev/null +++ b/backend/src/auth/__tests__/auth-copy-capability.spec.ts @@ -0,0 +1,27 @@ +import { AuthResolver } from '../auth.resolver'; +import { AuthService } from '../auth.service'; + +// No password operations are under test. Avoid requiring a native bcrypt +// binary just to read a deployment-wide boolean. +jest.mock('bcrypt', () => ({ hash: jest.fn(), compare: jest.fn() })); +jest.mock('sqlite3', () => ({ Database: jest.fn() })); + +describe('password reset email availability', () => { + it.each([false, true])( + 'reports only the global mail flag (%s)', + (enabled) => { + // Exercise the real service getter and resolver without an account, mail + // server, or database. This capability must never look up an address. + const service = Object.create(AuthService.prototype) as AuthService; + Object.defineProperty(service, 'isMailEnabled', { value: enabled }); + Object.defineProperty(service, 'userRepository', { + get: () => { + throw new Error('A global capability must not inspect any account'); + }, + }); + expect(new AuthResolver(service).passwordResetEmailAvailable()).toBe( + enabled, + ); + }, + ); +}); diff --git a/backend/src/auth/auth.resolver.ts b/backend/src/auth/auth.resolver.ts index 85de8c35..fdbf2dfb 100644 --- a/backend/src/auth/auth.resolver.ts +++ b/backend/src/auth/auth.resolver.ts @@ -53,6 +53,13 @@ export class AuthResolver { return process.env.MAIL_ENABLED?.toLowerCase() === 'true'; } + /** Never offer email recovery when this deployment cannot send it. */ + @Query(() => Boolean) + @Public() + passwordResetEmailAvailable(): boolean { + return this.authService.passwordResetEmailAvailable; + } + /** * Whether "Continue with Google" can actually work. The strategy boots on * placeholder credentials when unconfigured, so the button used to send @@ -116,7 +123,11 @@ export class AuthResolver { @Args('currentPassword') currentPassword: string, @Args('newPassword') newPassword: string, ): Promise { - return this.authService.changePassword(userId, currentPassword, newPassword); + return this.authService.changePassword( + userId, + currentPassword, + newPassword, + ); } /** diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 56adf10d..84d1b800 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -54,6 +54,11 @@ export class AuthService { this.isMailEnabled = this.configService.isMailEnabled; } + /** Deployment-wide mail capability, independent of any account or address. */ + get passwordResetEmailAvailable(): boolean { + return this.isMailEnabled; + } + async confirmEmail(token: string): Promise { try { const payload = await this.jwtService.verifyAsync(token); @@ -181,7 +186,7 @@ export class AuthService { ): Promise { const same = { message: - 'If that address has an account, a reset link is on its way. Check your inbox.', + 'If this account can receive password reset email, check your inbox for a reset link.', success: true, }; diff --git a/frontend/jest.auth-copy.config.js b/frontend/jest.auth-copy.config.js new file mode 100644 index 00000000..b11ef567 --- /dev/null +++ b/frontend/jest.auth-copy.config.js @@ -0,0 +1,19 @@ +module.exports = { + rootDir: '.', + testEnvironment: 'jsdom', + testMatch: ['/src/**/__tests__/auth-copy*.spec.ts?(x)'], + moduleNameMapper: { '^@/(.*)$': '/src/$1' }, + setupFilesAfterEnv: ['@testing-library/jest-dom'], + transform: { + '^.+\\.tsx?$': [ + 'ts-jest', + { + tsconfig: { + jsx: 'react-jsx', + module: 'commonjs', + moduleResolution: 'node', + }, + }, + ], + }, +}; diff --git a/frontend/src/app/auth/confirm/page.tsx b/frontend/src/app/auth/confirm/page.tsx index 0bc89b4d..93b5b045 100644 --- a/frontend/src/app/auth/confirm/page.tsx +++ b/frontend/src/app/auth/confirm/page.tsx @@ -12,6 +12,7 @@ import { } from '@/components/ui/texture-card'; import { AlertCircle, CheckCircle } from 'lucide-react'; import { Button } from '@/components/ui/button'; +import { getVerificationFailureMessage } from '@/lib/auth-copy'; export default function ConfirmEmailPage() { const searchParams = useSearchParams(); @@ -25,21 +26,19 @@ export default function ConfirmEmailPage() { onCompleted: (data) => { if (data.confirmEmail.success) { setStatus('success'); - setMessage(data.confirmEmail.message || 'Email verified successfully!'); + setMessage('Email verified. You can sign in now.'); // Redirect to home page after a short delay setTimeout(() => { router.push('/'); }, 3000); } else { setStatus('error'); - setMessage(data.confirmEmail.message || 'Failed to verify email.'); + setMessage(getVerificationFailureMessage(data.confirmEmail.message)); } }, - onError: (error) => { + onError: () => { setStatus('error'); - setMessage( - error.message || 'An error occurred while verifying your email.' - ); + setMessage('We couldn’t verify your email. Try opening the link again.'); }, }); @@ -48,7 +47,9 @@ export default function ConfirmEmailPage() { if (!token) { setStatus('error'); - setMessage('Invalid verification link. No token provided.'); + setMessage( + 'This verification link is incomplete. Open the full link from your CodeFox email.' + ); return; } @@ -65,7 +66,7 @@ export default function ConfirmEmailPage() { - Email Verification + Verify your email
@@ -86,13 +87,13 @@ export default function ConfirmEmailPage() { {status === 'success' && (

- You will be redirected to the home page shortly... + Returning to CodeFox…

)} {status === 'error' && ( )} diff --git a/frontend/src/app/auth/oauth-callback/page.tsx b/frontend/src/app/auth/oauth-callback/page.tsx index aa9bafcd..ea9101dd 100644 --- a/frontend/src/app/auth/oauth-callback/page.tsx +++ b/frontend/src/app/auth/oauth-callback/page.tsx @@ -23,7 +23,9 @@ export default function OAuthCallbackPage() { // Handle error cases if (error) { console.error('Authentication error:', error); - toast.error('Authentication failed'); + toast.error( + 'Google sign-in didn’t finish. Return to CodeFox and try again.' + ); router.push('/'); return; } @@ -31,7 +33,9 @@ export default function OAuthCallbackPage() { // Check if tokens exist if (!accessToken || !refreshToken) { console.error('Missing tokens in callback'); - toast.error('Authentication failed: Missing tokens'); + toast.error( + 'Google sign-in didn’t finish. Return to CodeFox and try again.' + ); router.push('/'); return; } @@ -40,13 +44,15 @@ export default function OAuthCallbackPage() { login(accessToken, refreshToken); // Show success message - toast.success('Logged in successfully!'); + toast.success('Signed in'); // Redirect to home or dashboard router.push('/'); } catch (error) { console.error('Error processing authentication:', error); - toast.error('Authentication processing failed'); + toast.error( + 'Google sign-in didn’t finish. Return to CodeFox and try again.' + ); router.push('/'); } }; @@ -57,9 +63,7 @@ export default function OAuthCallbackPage() { return (
-

- Completing authentication... -

+

Signing you in…

Please wait while we sign you in.

diff --git a/frontend/src/app/reset-password/page.tsx b/frontend/src/app/reset-password/page.tsx index 6c03694e..8ba7bd2f 100644 --- a/frontend/src/app/reset-password/page.tsx +++ b/frontend/src/app/reset-password/page.tsx @@ -41,7 +41,7 @@ function ResetPasswordForm() { setError(data.resetPassword.message); } }, - onError: () => setError('Could not reach the server. Try again.'), + onError: () => setError('We couldn’t update your password. Try again.'), }); const submit = (e: React.FormEvent) => { @@ -78,15 +78,18 @@ function ResetPasswordForm() { {!token ? (

- This link is missing its token. Open the link from your email - again, or request a new one. + This reset link is incomplete. Open the full link from your + email, or go to Sign in → Forgot your password to request + another.

- +
) : done ? (

Password updated. You can sign in now.

-

Taking you home…

+

+ Returning to CodeFox… +

) : (
diff --git a/frontend/src/components/__tests__/auth-copy-components.spec.tsx b/frontend/src/components/__tests__/auth-copy-components.spec.tsx new file mode 100644 index 00000000..eb445d61 --- /dev/null +++ b/frontend/src/components/__tests__/auth-copy-components.spec.tsx @@ -0,0 +1,200 @@ +import React from 'react'; +import '@testing-library/jest-dom'; +import { act, fireEvent, render, screen } from '@testing-library/react'; +import { useMutation, useQuery } from '@apollo/client'; +import { SignInModal } from '../sign-in-modal'; +import { SignUpModal } from '../sign-up-modal'; + +jest.mock('@apollo/client', () => ({ + ...jest.requireActual('@apollo/client'), + useMutation: jest.fn(), + useQuery: jest.fn(), +})); +jest.mock('@/providers/AuthProvider', () => ({ + useAuthContext: () => ({ login: jest.fn() }), +})); +jest.mock('@/app/log/logger', () => ({ logger: { error: jest.fn() } })); +jest.mock('sonner', () => ({ toast: { success: jest.fn() } })); + +const mutationOptions: Record = {}; +const mutations: Record = {}; +let resetQuery: any; + +beforeEach(() => { + jest.clearAllMocks(); + for (const key of Object.keys(mutations)) delete mutations[key]; + resetQuery = { data: { passwordResetEmailAvailable: true }, loading: false }; + (useQuery as jest.Mock).mockImplementation((document) => { + const name = document.definitions[0].name.value; + if (name === 'PasswordResetEmailAvailable') return resetQuery; + if (name === 'EmailVerificationRequired') + return { data: { emailVerificationRequired: true } }; + return { data: { googleAuthAvailable: false } }; + }); + (useMutation as jest.Mock).mockImplementation((document, options) => { + const name = document.definitions[0].name.value; + mutationOptions[name] = options; + mutations[name] ??= jest.fn().mockResolvedValue({}); + return [mutations[name], { loading: false }]; + }); +}); + +afterEach(() => jest.useRealTimers()); + +describe('sign-in and recovery copy in the actual dialog', () => { + it('updates the accessible title when opening and leaving password recovery', () => { + render( {}} />); + expect(screen.getByRole('dialog', { name: 'Sign in' })).toBeInTheDocument(); + fireEvent.click( + screen.getByRole('button', { name: 'Forgot your password?' }) + ); + expect( + screen.getByRole('dialog', { name: 'Reset your password' }) + ).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Back to sign in' })); + expect(screen.getByRole('dialog', { name: 'Sign in' })).toBeInTheDocument(); + }); + + it.each([ + { data: { passwordResetEmailAvailable: false }, loading: false }, + { loading: true }, + { data: { passwordResetEmailAvailable: true }, loading: true }, + { + data: { passwordResetEmailAvailable: true }, + error: new Error('offline'), + }, + ])( + 'does not submit reset email when unavailable, unknown, or stale: %p', + (query) => { + resetQuery = query; + render( {}} />); + fireEvent.click( + screen.getByRole('button', { name: 'Forgot your password?' }) + ); + fireEvent.change(screen.getByLabelText('Email'), { + target: { value: 'person@example.com' }, + }); + const submit = screen.getByRole('button', { name: 'Send reset link' }); + expect(submit).toBeDisabled(); + // Even a submit event bypassing the disabled button must be guarded. + fireEvent.submit(submit.closest('form')!); + expect(mutations.RequestPasswordReset).not.toHaveBeenCalled(); + } + ); + + it('requests a reset only when the global capability is confirmed', () => { + render( {}} />); + fireEvent.click( + screen.getByRole('button', { name: 'Forgot your password?' }) + ); + fireEvent.change(screen.getByLabelText('Email'), { + target: { value: 'person@example.com' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Send reset link' })); + expect(mutations.RequestPasswordReset).toHaveBeenCalledWith({ + variables: { email: 'person@example.com' }, + }); + }); + + it('renders actionable verification and network errors without raw diagnostics', () => { + render( {}} />); + act(() => + mutationOptions.Login.onError({ + graphQLErrors: [ + { message: 'Email not confirmed. Please check your inbox.' }, + ], + }) + ); + expect( + screen.getByText('Check your email to verify your account, then sign in.') + ).toBeInTheDocument(); + act(() => + mutationOptions.Login.onError({ + networkError: new Error('internal diagnostic'), + }) + ); + expect( + screen.getByText( + 'CodeFox couldn’t complete sign-in. Try again in a moment.' + ) + ).toBeInTheDocument(); + expect( + screen.queryByText(/internal diagnostic|Incorrect email or password/) + ).not.toBeInTheDocument(); + }); +}); + +describe('signup copy and resend state', () => { + it('shows truthful requirements before typing and retains the old acceptance rules', () => { + render( {}} />); + expect(screen.getByLabelText('Password')).toHaveAccessibleDescription( + /at least 6 characters and at least two/ + ); + expect(screen.getByLabelText('Display name')).toHaveAccessibleDescription( + /public projects/ + ); + fireEvent.change(screen.getByLabelText('Display name'), { + target: { value: 'Example' }, + }); + fireEvent.change(screen.getByLabelText('Email'), { + target: { value: 'person@example.com' }, + }); + fireEvent.change(screen.getByLabelText('Password'), { + target: { value: 'abcde1' }, + }); + fireEvent.change(screen.getByLabelText('Confirm Password'), { + target: { value: 'abcde1' }, + }); + fireEvent.click(screen.getByRole('button', { name: 'Sign up' })); + expect(mutations.RegisterUser).toHaveBeenCalledWith({ + variables: { + input: { + username: 'Example', + email: 'person@example.com', + password: 'abcde1', + confirmPassword: 'abcde1', + }, + }, + }); + }); + + it('keeps resend success styling and expiry independent of the rewritten words', () => { + jest.useFakeTimers(); + render( {}} />); + act(() => mutationOptions.RegisterUser.onCompleted()); + fireEvent.click( + screen.getByRole('button', { name: 'Resend verification email' }) + ); + act(() => + mutationOptions.ResendConfirmationEmail.onCompleted({ + resendConfirmationEmail: { success: true }, + }) + ); + expect(screen.getByRole('status')).toHaveTextContent( + 'Verification email sent again. Check your inbox.' + ); + expect(screen.getByRole('status').className).toContain('bg-green-50'); + expect( + screen.getByRole('button', { name: 'Resend available in 60s' }) + ).toBeDisabled(); + for (let second = 0; second < 60; second++) + act(() => jest.advanceTimersByTime(1000)); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + expect( + screen.getByRole('button', { name: 'Resend verification email' }) + ).toBeEnabled(); + fireEvent.click( + screen.getByRole('button', { name: 'Resend verification email' }) + ); + act(() => + mutationOptions.ResendConfirmationEmail.onCompleted({ + resendConfirmationEmail: { + success: false, + message: 'Try again later.', + }, + }) + ); + expect(screen.getByRole('status')).toHaveTextContent('Try again later.'); + expect(screen.getByRole('status').className).not.toContain('bg-green-50'); + }); +}); diff --git a/frontend/src/components/settings/settings.tsx b/frontend/src/components/settings/settings.tsx index ca01d162..97ca137b 100644 --- a/frontend/src/components/settings/settings.tsx +++ b/frontend/src/components/settings/settings.tsx @@ -7,6 +7,7 @@ import { useAuthContext } from '@/providers/AuthProvider'; import { gql, useMutation, useQuery } from '@apollo/client'; import { toast } from 'sonner'; import { CHANGE_PASSWORD, HAS_PASSWORD } from '@/graphql/mutations/auth'; +import { getDisplayNameErrorMessage } from '@/lib/auth-copy'; /** * Section shell shared by every block on this page, matching the rule-and-label @@ -89,11 +90,10 @@ function UsernameField({ current }: { current?: string | null }) { try { await update({ variables: { username: next } }); await refreshUserInfo(); - toast.success('Username updated'); + toast.success('Display name updated'); } catch (error: any) { - // The server owns the rules (length, characters, already taken), so - // show what it said rather than guessing at a second copy of them. - toast.error(error?.message ?? 'Could not update your username'); + // Explain existing server outcomes using the same field name as the UI. + toast.error(getDisplayNameErrorMessage(error?.message)); setValue(current ?? ''); } finally { setSaving(false); @@ -114,7 +114,7 @@ function UsernameField({ current }: { current?: string | null }) { } }} maxLength={32} - aria-label="Username" + aria-label="Display name" className="w-56 rounded-md border border-border bg-background px-3 py-1.5 font-mono text-sm text-foreground transition-colors hover:border-primary/60 focus:border-primary focus:outline-none disabled:opacity-60" /> ); @@ -233,7 +233,7 @@ function PasswordField() { disabled={loading || !current || !next || !confirm} className="rounded-md border border-primary bg-primary px-3 py-1.5 font-mono text-sm text-primary-foreground transition-opacity disabled:opacity-50" > - {loading ? 'Saving…' : 'Save'} + {loading ? 'Updating…' : 'Update password'}
@@ -177,7 +204,7 @@ export function SignInModal({ isOpen, onClose }: SignInModalProps) { @@ -282,7 +309,7 @@ export function SignInModal({ isOpen, onClose }: SignInModalProps) { alt="Google" className="w-5 h-5" /> - Google + Continue with Google
diff --git a/frontend/src/components/sign-up-modal.tsx b/frontend/src/components/sign-up-modal.tsx index 5ea0a9f6..e85d1b1b 100644 --- a/frontend/src/components/sign-up-modal.tsx +++ b/frontend/src/components/sign-up-modal.tsx @@ -24,12 +24,11 @@ import { REGISTER_USER, RESEND_CONFIRMATION_EMAIL_MUTATION, } from '@/graphql/mutations/auth'; -import { useRouter } from 'next/navigation'; import { VisuallyHidden } from '@radix-ui/react-visually-hidden'; import { AlertCircle, CheckCircle, Mail, Clock } from 'lucide-react'; -import { toast } from 'sonner'; import { useEffect } from 'react'; import { logger } from '@/app/log/logger'; +import { getSignupPasswordState, SIGNUP_PASSWORD_HELP } from '@/lib/auth-copy'; export function SignUpModal({ isOpen, @@ -38,7 +37,6 @@ export function SignUpModal({ isOpen: boolean; onClose: () => void; }) { - const router = useRouter(); // When the deployment sends no verification mail, saying one was sent is a // lie that strands the user at their inbox. Default to the strict copy // until the backend answers. @@ -55,6 +53,9 @@ export function SignUpModal({ const [registrationSuccess, setRegistrationSuccess] = useState(false); const [resendCooldown, setResendCooldown] = useState(0); const [resendMessage, setResendMessage] = useState(null); + const [resendStatus, setResendStatus] = useState<'success' | 'error' | null>( + null + ); const [passwordConfirm, setPasswordConfirm] = useState(''); const [passwordError, setPasswordError] = useState(null); const [passwordStrength, setPasswordStrength] = useState< @@ -62,40 +63,10 @@ export function SignUpModal({ >(null); const validatePassword = (value: string) => { - // Reset errors - setPasswordError(null); - - // Check minimum length - if (value.length < 6) { - setPasswordError('Password must be at least 6 characters long'); - setPasswordStrength('weak'); - return false; - } - - // Check for complexity - const hasUppercase = /[A-Z]/.test(value); - const hasLowercase = /[a-z]/.test(value); - const hasNumbers = /\d/.test(value); - const hasSpecialChar = /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(value); - - const strengthScore = [ - hasUppercase, - hasLowercase, - hasNumbers, - hasSpecialChar, - ].filter(Boolean).length; - - if (strengthScore < 2) { - setPasswordStrength('weak'); - setPasswordError('Password is too weak'); - return false; - } else if (strengthScore < 4) { - setPasswordStrength('medium'); - return true; - } else { - setPasswordStrength('strong'); - return true; - } + const result = getSignupPasswordState(value); + setPasswordError(result.error); + setPasswordStrength(result.strength); + return result.error === null; }; const [registerUser, { loading }] = useMutation(REGISTER_USER, { @@ -150,19 +121,22 @@ export function SignUpModal({ { onCompleted: (data) => { if (data.resendConfirmationEmail.success) { - setResendMessage( - 'Verification email has been resent. Please check your inbox.' - ); + setResendStatus('success'); + setResendMessage('Verification email sent again. Check your inbox.'); setResendCooldown(60); // Start 60 second cooldown } else { + setResendStatus('error'); setResendMessage( data.resendConfirmationEmail.message || 'Failed to resend. Please try again later.' ); } }, - onError: (error) => { - setResendMessage(`Error: ${error.message}`); + onError: () => { + setResendStatus('error'); + setResendMessage( + 'We couldn’t resend the verification email. Try again.' + ); }, } ); @@ -175,17 +149,19 @@ export function SignUpModal({ }, 1000); } else if (resendCooldown === 0) { // Clear the resend message once cooldown is complete - if (resendMessage && resendMessage.includes('has been resent')) { + if (resendStatus === 'success') { setResendMessage(null); + setResendStatus(null); } } return () => clearTimeout(timer); - }, [resendCooldown, resendMessage]); + }, [resendCooldown, resendStatus]); const handleResendConfirmation = () => { if (resendCooldown > 0) return; setResendMessage(null); + setResendStatus(null); resendConfirmationEmail({ variables: { input: { @@ -250,13 +226,14 @@ export function SignUpModal({ {resendMessage && (
- {resendMessage.includes('has been resent') ? ( + {resendStatus === 'success' ? ( ) : ( @@ -336,9 +313,10 @@ export function SignUpModal({
- + +

+ Shown next to your public projects. You can change it in + Settings. +

@@ -370,6 +355,7 @@ export function SignUpModal({ { @@ -380,6 +366,12 @@ export function SignUpModal({ required className={`w-full ${passwordError ? 'border-red-500' : ''}`} /> +

+ {SIGNUP_PASSWORD_HELP} +

{password && (
@@ -403,44 +395,6 @@ export function SignUpModal({ : 'Strong'}
- -
- Password must: -
    -
  • = 6 ? 'text-green-500' : '' - } - > - Be at least 6 characters long -
  • -
  • - Include at least one uppercase letter -
  • -
  • - Include at least one number -
  • -
  • /?]/.test( - password - ) - ? 'text-green-500' - : '' - } - > - Include at least one special character -
  • -
-
)} diff --git a/frontend/src/graphql/mutations/auth.ts b/frontend/src/graphql/mutations/auth.ts index b0d6b771..eaa0ca7b 100644 --- a/frontend/src/graphql/mutations/auth.ts +++ b/frontend/src/graphql/mutations/auth.ts @@ -66,6 +66,12 @@ export const GOOGLE_AUTH_AVAILABLE = gql` } `; +export const PASSWORD_RESET_EMAIL_AVAILABLE = gql` + query PasswordResetEmailAvailable { + passwordResetEmailAvailable + } +`; + export const REQUEST_PASSWORD_RESET = gql` mutation RequestPasswordReset($email: String!) { requestPasswordReset(email: $email) { diff --git a/frontend/src/graphql/schema.gql b/frontend/src/graphql/schema.gql index ad62c228..e42bd4dd 100644 --- a/frontend/src/graphql/schema.gql +++ b/frontend/src/graphql/schema.gql @@ -48,6 +48,7 @@ type AdminRuntime { model: String! nodeEnv: String! provider: String! + passwordResetEmailAvailable: Boolean! registrationOpen: Boolean! sandbox: String! uptime: Int! @@ -276,6 +277,7 @@ type Query { logout: Boolean! me: User! myRoles: [String!]! + passwordResetEmailAvailable: Boolean! registrationOpen: Boolean! scenarios: [ScenarioChoice!]! } @@ -353,4 +355,4 @@ type User { subscribedProjects: [Project!] @deprecated(reason: "Use projects with forkedFromId instead") updatedAt: Date! username: String! -} \ No newline at end of file +} diff --git a/frontend/src/lib/__tests__/auth-copy.spec.ts b/frontend/src/lib/__tests__/auth-copy.spec.ts new file mode 100644 index 00000000..c7b459d3 --- /dev/null +++ b/frontend/src/lib/__tests__/auth-copy.spec.ts @@ -0,0 +1,134 @@ +import { + classifySignInError, + getSignInErrorMessage, + getSignupPasswordState, + getVerificationFailureMessage, + getDisplayNameErrorMessage, + SIGNUP_PASSWORD_HELP, +} from '../auth-copy'; + +describe('auth outcome copy', () => { + it('uses display-name terminology for existing server validation outcomes', () => { + expect( + getDisplayNameErrorMessage('A username is between 3 and 32 characters.') + ).toMatch(/3 and 32 characters.*display name/); + expect(getDisplayNameErrorMessage('That username is taken.')).toMatch( + /display name is already in use/ + ); + expect(getDisplayNameErrorMessage('private diagnostic')).toBe( + 'We couldn’t update your display name. Try again.' + ); + }); + + it('does not blame credentials for a network or unknown failure', () => { + expect(classifySignInError({ networkError: new Error('offline') })).toBe( + 'network' + ); + expect( + getSignInErrorMessage({ networkError: new Error('offline') }) + ).toMatch(/complete sign-in/); + expect( + classifySignInError({ + graphQLErrors: [{ message: 'Database unavailable' }], + }) + ).toBe('unknown'); + expect( + getSignInErrorMessage({ + graphQLErrors: [{ message: 'Database unavailable' }], + }) + ).not.toMatch(/password|Database/); + }); + + it('only explains verification when the existing backend explicitly reports it', () => { + expect( + classifySignInError({ + graphQLErrors: [ + { message: 'Email not confirmed. Please check your inbox.' }, + ], + }) + ).toBe('verification'); + expect( + getSignInErrorMessage({ + graphQLErrors: [ + { message: 'Email not confirmed. Please check your inbox.' }, + ], + }) + ).toMatch(/verify your account/); + expect( + classifySignInError({ + graphQLErrors: [{ message: 'Invalid credentials' }], + }) + ).toBe('credentials'); + // Unknown, inactive, deleted, and wrong-password accounts all use this one + // server response. Never branch on or reveal a more specific account state. + expect( + getSignInErrorMessage({ + graphQLErrors: [{ message: 'Invalid credentials' }], + }) + ).toBe('Email or password is incorrect. Check your details and try again.'); + expect( + classifySignInError({ graphQLErrors: [{ message: 'User inactive' }] }) + ).toBe('unknown'); + }); + + it('removes implementation jargon from verification failures', () => { + for (const message of [ + 'Invalid token format', + 'Invalid or expired token', + 'Email already confirmed or user not found.', + 'private diagnostic', + ]) { + expect(getVerificationFailureMessage(message)).not.toMatch( + /token|private diagnostic|user not found/ + ); + } + expect(getVerificationFailureMessage('Invalid or expired token')).toMatch( + /latest verification email/ + ); + }); +}); + +describe('signup password help preserves existing policy', () => { + it('describes six characters and any two character types', () => { + expect(SIGNUP_PASSWORD_HELP).toMatch( + /at least 6 characters and at least two/ + ); + for (const value of [ + 'abcdef1', + 'ABCDEF1', + 'abcDEF', + 'abcde!', + '12345!', + 'ABCDE!', + ]) { + expect(getSignupPasswordState(value).error).toBeNull(); + } + for (const value of ['', 'Ab1!', 'abcdef', 'ABCDEF', '123456', '!!!!!!']) { + expect(getSignupPasswordState(value).error).not.toBeNull(); + } + }); + + it('matches the old validator over every character-class combination and length boundary', () => { + const old = (value: string) => + value.length >= 6 && + [ + /[A-Z]/.test(value), + /[a-z]/.test(value), + /\d/.test(value), + /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(value), + ].filter(Boolean).length >= 2; + for (let mask = 0; mask < 16; mask++) { + const seed = + ['A', 'a', '1', '!'] + .filter((_, index) => mask & (1 << index)) + .join('') || ' '; + for (let length = 0; length < 12; length++) { + const value = seed.repeat(12).slice(0, length); + expect(getSignupPasswordState(value).error === null).toBe(old(value)); + } + } + for (const symbol of '!@#$%^&*()_+-=[]{};\':"\\|,.<>/?') { + expect(getSignupPasswordState(`aaaaa${symbol}`).error).toBeNull(); + } + }); +}); diff --git a/frontend/src/lib/auth-copy.ts b/frontend/src/lib/auth-copy.ts new file mode 100644 index 00000000..aea9515f --- /dev/null +++ b/frontend/src/lib/auth-copy.ts @@ -0,0 +1,87 @@ +/** Only classify outcomes the server already distinguishes. Never infer account status. */ +export interface AuthError { + networkError?: unknown; + graphQLErrors?: ReadonlyArray<{ message: string }>; +} + +export type SignInFailure = + | 'credentials' + | 'verification' + | 'network' + | 'unknown'; + +export function classifySignInError(error: AuthError): SignInFailure { + if (error.networkError) return 'network'; + const messages = error.graphQLErrors?.map((item) => item.message) ?? []; + if (messages.includes('Invalid credentials')) return 'credentials'; + if (messages.includes('Email not confirmed. Please check your inbox.')) { + return 'verification'; + } + return 'unknown'; +} + +export function getSignInErrorMessage(error: AuthError): string { + switch (classifySignInError(error)) { + case 'credentials': + return 'Email or password is incorrect. Check your details and try again.'; + case 'verification': + return 'Check your email to verify your account, then sign in.'; + case 'network': + return 'CodeFox couldn’t complete sign-in. Try again in a moment.'; + default: + return 'We couldn’t sign you in. Try again.'; + } +} + +export function getDisplayNameErrorMessage(message?: string): string { + switch (message) { + case 'A username is between 3 and 32 characters.': + return 'Use between 3 and 32 characters for your display name.'; + case 'A username cannot contain < > / \\ @ or quotes.': + return 'Your display name can’t include < > / \\ @ or quotes.'; + case 'That username is taken.': + return 'That display name is already in use. Try another.'; + default: + return 'We couldn’t update your display name. Try again.'; + } +} + +export const SIGNUP_PASSWORD_HELP = + 'Use at least 6 characters and at least two of these: lowercase letters, uppercase letters, numbers, or symbols.'; + +/** Mirrors the existing signup rules; this does not set a new password policy. */ +export function getSignupPasswordState(value: string): { + error: string | null; + strength: 'weak' | 'medium' | 'strong'; +} { + if (value.length < 6) { + return { error: 'Use at least 6 characters.', strength: 'weak' }; + } + const characterTypes = [ + /[A-Z]/.test(value), + /[a-z]/.test(value), + /\d/.test(value), + /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(value), + ].filter(Boolean).length; + if (characterTypes < 2) { + return { + error: + 'Add another character type: lowercase, uppercase, number, or symbol.', + strength: 'weak', + }; + } + return { error: null, strength: characterTypes < 4 ? 'medium' : 'strong' }; +} + +export function getVerificationFailureMessage(message?: string): string { + if ( + message === 'Invalid token format' || + message === 'Invalid or expired token' + ) { + return 'This verification link is invalid or has expired. Open the latest verification email and try again.'; + } + if (message === 'Email already confirmed or user not found.') { + return 'We couldn’t verify this email. If you’ve already verified it, try signing in. Otherwise, open the latest verification email and try again.'; + } + return 'We couldn’t verify your email. Try opening the link again.'; +} diff --git a/frontend/src/lib/client.ts b/frontend/src/lib/client.ts index e9469b30..0033d030 100644 --- a/frontend/src/lib/client.ts +++ b/frontend/src/lib/client.ts @@ -214,9 +214,14 @@ const tokenRefreshLink = onError( localStorage.removeItem(LocalStore.refreshToken); logger.warn( - 'Network error during authentication, redirecting to home' + 'Network error during authentication, clearing stored tokens' ); - window.location.href = '/'; + // Login owns an inline recovery message. Reloading here would erase + // it and the user's input before they can retry. Token cleanup above + // and redirect behavior for refresh/validation stay unchanged. + if (networkErrorOperation !== 'Login') { + window.location.href = '/'; + } } } } diff --git a/scripts/check-auth-copy.mjs b/scripts/check-auth-copy.mjs new file mode 100644 index 00000000..d8b2e212 --- /dev/null +++ b/scripts/check-auth-copy.mjs @@ -0,0 +1,97 @@ +#!/usr/bin/env node +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; + +const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8'); +const signup = read('frontend/src/components/sign-up-modal.tsx'); +const signin = read('frontend/src/components/sign-in-modal.tsx'); +const settings = read('frontend/src/components/settings/settings.tsx'); +const reset = read('frontend/src/app/reset-password/page.tsx'); +const confirm = read('frontend/src/app/auth/confirm/page.tsx'); +const oauth = read('frontend/src/app/auth/oauth-callback/page.tsx'); +const resolver = read('backend/src/auth/auth.resolver.ts'); +const service = read('backend/src/auth/auth.service.ts'); +const client = read('frontend/src/lib/client.ts'); + +assert.match( + client, + /if \(networkErrorOperation !== 'Login'\) \{\s+window\.location\.href = '\/';/, + 'a Login transport failure must not reload away its inline recovery message' +); +const networkCleanup = client.slice( + client.indexOf('const networkErrorOperation') +); +assert.match( + networkCleanup, + /localStorage\.removeItem\(LocalStore\.accessToken\)/ +); +assert.match( + networkCleanup, + /localStorage\.removeItem\(LocalStore\.refreshToken\)/ +); + +assert.match( + read('frontend/src/lib/auth-copy.ts'), + /at least two of these/, + 'signup must explain the actual two-character-type rule' +); +assert.doesNotMatch( + signup, + /Include at least one uppercase letter|Include at least one number|Include at least one special character/ +); +assert.match(signup, /aria-describedby="signup-password-help"/); +assert.match(signup, /resendStatus === 'success'/); +assert.doesNotMatch( + signup, + /includes\('has been resent'\)/, + 'resend state must not depend on English wording' +); +assert.match(signup, /Display name/); +assert.match(signup, /Shown next to your public projects/); +assert.match( + signin, + /getSignInErrorMessage\(error\)/, + 'sign-in must classify errors rather than blame all on credentials' +); +assert.match( + signin, + /forgot \? 'Reset your password' : 'Sign in'/, + 'the accessible dialog title must follow its state' +); +assert.match(signin, /PASSWORD_RESET_EMAIL_AVAILABLE/); +assert.match(signin, /passwordResetEmailAvailable === true/); +assert.match( + signin, + /if \(!resetEmailAvailable\) return;/, + 'the reset submit handler must refuse unavailable or unknown capability' +); +assert.match(signin, /sending \|\| !email \|\| !resetEmailAvailable/); +assert.match( + resolver, + /@Public\(\)\s+passwordResetEmailAvailable\(\)/, + 'reset capability must be global and public' +); +assert.match( + service, + /get passwordResetEmailAvailable\(\): boolean \{\s+return this\.isMailEnabled;/ +); +assert.match(settings, /title="Display name"/); +assert.match(settings, /Press Enter or leave this field to save/); +assert.doesNotMatch( + reset + confirm + oauth, + /missing its token|No token provided|Authentication failed: Missing tokens/ +); +assert.match(reset, /This reset link is incomplete/); +assert.match(confirm, /This verification link is incomplete/); + +// Copy changes must not silently change password requirements or session rules. +assert.match( + read('backend/src/user/dto/register-user.input.ts'), + /@MinLength\(6\)/ +); +assert.match(service, /newPassword\.length < 8/); +assert.match(service, /await this\.endAllSessions\(user\.id\)/); +assert.match(service, /if \(!user \|\| !user\.password\) return same;/); +console.log( + 'ok — auth copy matches state, recovery availability, and unchanged security rules' +);