mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 09:54:14 +00:00
Merge PR #3300: Native Cloud trials and password recovery
This commit is contained in:
@@ -1,5 +1,11 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isNewCloudPlan, opensSoon, planForUnclaimedPurchase, refundedBeforeOpening } from './cloudOrders';
|
||||
import {
|
||||
isNewCloudPlan,
|
||||
matchesPurchaseAgreement,
|
||||
opensSoon,
|
||||
planForUnclaimedPurchase,
|
||||
refundedBeforeOpening,
|
||||
} from './cloudOrders';
|
||||
|
||||
describe('opensSoon', () => {
|
||||
const base = { available: true, closed: true, sandbox: false, onPlay: false };
|
||||
@@ -35,6 +41,15 @@ describe('refundedBeforeOpening', () => {
|
||||
});
|
||||
|
||||
describe('Cloud catalog and purchase recovery', () => {
|
||||
it('only carries the accepted agreement into a new purchase if the current version and text still match', () => {
|
||||
const accepted = { version: '2026-12-01', text: 'Agreed changes' };
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted })).toBe(true);
|
||||
expect(matchesPurchaseAgreement(accepted, null)).toBe(false);
|
||||
expect(matchesPurchaseAgreement(null, accepted)).toBe(false);
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted, version: '2026-12-02' })).toBe(false);
|
||||
expect(matchesPurchaseAgreement(accepted, { ...accepted, text: 'Changed conditions' })).toBe(false);
|
||||
});
|
||||
|
||||
it('only offers Start and Plus even when the server still lists retired plans', () => {
|
||||
expect(['start', 'basis', 'plus', 'pro'].filter(isNewCloudPlan)).toEqual(['start', 'plus']);
|
||||
});
|
||||
|
||||
@@ -29,6 +29,21 @@ export function isNewCloudPlan(id: string): boolean {
|
||||
return id === 'start' || id === 'plus';
|
||||
}
|
||||
|
||||
export interface CloudPurchaseAgreement {
|
||||
version: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** Recheck the agreement before opening the store sheet. No agreement means no new purchase. */
|
||||
export function matchesPurchaseAgreement(
|
||||
accepted: CloudPurchaseAgreement | null,
|
||||
current: CloudPurchaseAgreement | null
|
||||
): boolean {
|
||||
return (
|
||||
accepted !== null && current !== null && accepted.version === current.version && accepted.text === current.text
|
||||
);
|
||||
}
|
||||
|
||||
const PLAN_NAMES: Record<string, string> = { start: 'Start', basis: 'Basis', plus: 'Plus', pro: 'Pro' };
|
||||
|
||||
/** A verified purchase can predate the current offer and still need its instance set up. */
|
||||
|
||||
@@ -84,15 +84,22 @@ describe('native client', () => {
|
||||
expect(await fakeIapClient.isSandbox()).toBe(true);
|
||||
});
|
||||
|
||||
it('maps the store price strings by product', async () => {
|
||||
shell.storeProducts.mockResolvedValue({ products: [{ id: 'cloud.plus.monthly', displayPrice: '9,99 €' }] });
|
||||
const prices = await nativeIapClient.prices(['cloud.plus.monthly', 'cloud.pro.monthly']);
|
||||
expect(shell.storeProducts).toHaveBeenCalledWith({ ids: ['cloud.plus.monthly', 'cloud.pro.monthly'] });
|
||||
expect(prices.get('cloud.plus.monthly')).toBe('9,99 €');
|
||||
expect(prices.has('cloud.pro.monthly')).toBe(false);
|
||||
it('maps the regular price and explicitly confirmed trial by product', async () => {
|
||||
shell.storeProducts.mockResolvedValue({
|
||||
products: [
|
||||
{ id: 'cloud.plus.monthly', displayPrice: '9,99 €', freeTrial: true },
|
||||
{ id: 'cloud.start.monthly', displayPrice: '4,99 €' },
|
||||
],
|
||||
});
|
||||
const ids = ['cloud.plus.monthly', 'cloud.start.monthly', 'cloud.plus.yearly'];
|
||||
const products = await nativeIapClient.products(ids);
|
||||
expect(shell.storeProducts).toHaveBeenCalledWith({ ids });
|
||||
expect(products.get('cloud.plus.monthly')).toEqual({ displayPrice: '9,99 €', freeTrial: true });
|
||||
expect(products.get('cloud.start.monthly')).toEqual({ displayPrice: '4,99 €', freeTrial: false });
|
||||
expect(products.has('cloud.plus.yearly')).toBe(false);
|
||||
|
||||
shell.storeProducts.mockRejectedValue(new Error('down'));
|
||||
expect((await nativeIapClient.prices(['cloud.plus.monthly'])).size).toBe(0);
|
||||
expect((await nativeIapClient.products(['cloud.plus.monthly'])).size).toBe(0);
|
||||
});
|
||||
|
||||
it('turns a bought transaction into a receipt', async () => {
|
||||
@@ -124,6 +131,15 @@ describe('native client', () => {
|
||||
expect(await nativeIapClient.held()).toBe(false);
|
||||
});
|
||||
|
||||
it('asks the store to preserve an advertised trial and reports a changed offer without retrying as paid', async () => {
|
||||
shell.storePurchase.mockResolvedValue({ kind: 'offer-changed' });
|
||||
expect(await nativeIapClient.purchase('cloud.plus.monthly', '9,99 €')).toEqual({ kind: 'offer-changed' });
|
||||
expect(shell.storePurchase).toHaveBeenCalledExactlyOnceWith({
|
||||
productId: 'cloud.plus.monthly',
|
||||
trialRenewalPrice: '9,99 €',
|
||||
});
|
||||
});
|
||||
|
||||
it('a build without storeHeld counts as holding nothing; the purchase still guards', async () => {
|
||||
shell.storeHeld.mockRejectedValue(new Error('not implemented'));
|
||||
expect(await nativeIapClient.held()).toBe(false);
|
||||
|
||||
+22
-11
@@ -38,17 +38,23 @@ type PurchaseOutcome =
|
||||
| { kind: 'cancelled' }
|
||||
| { kind: 'pending' }
|
||||
| { kind: 'failed' }
|
||||
| { kind: 'offer-changed' }
|
||||
| { kind: 'subscribed' };
|
||||
|
||||
export interface IapProduct {
|
||||
displayPrice: string;
|
||||
/** The store confirms an eligible first week at no charge. */
|
||||
freeTrial: boolean;
|
||||
}
|
||||
|
||||
export interface IapClient {
|
||||
/** Whether this build can take a payment. */
|
||||
isAvailable(): Promise<boolean>;
|
||||
/**
|
||||
* The store's own price strings by product id, in the buyer's currency. A
|
||||
* product missing from the map cannot be bought here. Empty for the fake, whose
|
||||
* prices come from the plan list.
|
||||
* Store pricing and offer eligibility by product id. A missing product cannot
|
||||
* be bought. Empty for the fake, whose prices come from the plan list.
|
||||
*/
|
||||
prices(productIds: string[]): Promise<Map<string, string>>;
|
||||
products(productIds: string[]): Promise<Map<string, IapProduct>>;
|
||||
/** A test build (TestFlight, App Review), whose purchases cost nothing and may go ahead before the opening. */
|
||||
isSandbox(): Promise<boolean>;
|
||||
/**
|
||||
@@ -58,7 +64,7 @@ export interface IapClient {
|
||||
*/
|
||||
held(): Promise<boolean>;
|
||||
/** Runs the platform's purchase sheet for a product and resolves with what became of it. */
|
||||
purchase(productId: string): Promise<PurchaseOutcome>;
|
||||
purchase(productId: string, trialRenewalPrice?: string): Promise<PurchaseOutcome>;
|
||||
/** Tells the store a purchase was delivered, once its instance exists. */
|
||||
finish(purchase: Purchase): Promise<void>;
|
||||
/** The subscription this store account already holds, for a reinstall or a new device. */
|
||||
@@ -94,7 +100,7 @@ export const fakeIapClient: IapClient = {
|
||||
async isAvailable() {
|
||||
return true;
|
||||
},
|
||||
async prices() {
|
||||
async products() {
|
||||
return new Map();
|
||||
},
|
||||
async isSandbox() {
|
||||
@@ -151,10 +157,10 @@ export const nativeIapClient: IapClient = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async prices(productIds) {
|
||||
async products(productIds) {
|
||||
try {
|
||||
const { products } = await TrekShell.storeProducts({ ids: productIds });
|
||||
return new Map(products.map((p) => [p.id, p.displayPrice]));
|
||||
return new Map(products.map((p) => [p.id, { displayPrice: p.displayPrice, freeTrial: p.freeTrial === true }]));
|
||||
} catch {
|
||||
return new Map();
|
||||
}
|
||||
@@ -166,9 +172,9 @@ export const nativeIapClient: IapClient = {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async purchase(productId) {
|
||||
async purchase(productId, trialRenewalPrice) {
|
||||
try {
|
||||
const result = await TrekShell.storePurchase({ productId });
|
||||
const result = await TrekShell.storePurchase({ productId, ...(trialRenewalPrice ? { trialRenewalPrice } : {}) });
|
||||
const receipt = result.jws ?? result.purchaseToken;
|
||||
if (result.kind === 'bought' && receipt && result.transactionId) {
|
||||
return {
|
||||
@@ -181,7 +187,12 @@ export const nativeIapClient: IapClient = {
|
||||
},
|
||||
};
|
||||
}
|
||||
if (result.kind === 'cancelled' || result.kind === 'pending' || result.kind === 'subscribed') {
|
||||
if (
|
||||
result.kind === 'cancelled' ||
|
||||
result.kind === 'pending' ||
|
||||
result.kind === 'subscribed' ||
|
||||
result.kind === 'offer-changed'
|
||||
) {
|
||||
return { kind: result.kind };
|
||||
}
|
||||
return { kind: 'failed' };
|
||||
|
||||
@@ -128,14 +128,14 @@ export interface TrekShellPlugin {
|
||||
/** Feature storeKit (iOS) or playBilling (Android): the store's price strings for the products it knows. */
|
||||
storeProducts(options: {
|
||||
ids: string[];
|
||||
}): Promise<{ products: { id: string; displayPrice: string }[]; sandbox?: boolean }>;
|
||||
}): Promise<{ products: { id: string; displayPrice: string; freeTrial?: boolean }[]; sandbox?: boolean }>;
|
||||
/**
|
||||
* The purchase sheet. Set when bought: on iOS `jws`, the signed transaction; on
|
||||
* Android `purchaseToken`, which the control plane verifies with Google Play.
|
||||
*/
|
||||
storePurchase(options: { productId: string }): Promise<{
|
||||
storePurchase(options: { productId: string; trialRenewalPrice?: string }): Promise<{
|
||||
/** `subscribed`: this store account already holds a delivered subscription, so nothing was bought. */
|
||||
kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed';
|
||||
kind: 'bought' | 'cancelled' | 'pending' | 'failed' | 'subscribed' | 'offer-changed';
|
||||
jws?: string;
|
||||
purchaseToken?: string;
|
||||
productId?: string;
|
||||
|
||||
@@ -9,9 +9,14 @@ import ForgotPasswordPage from './ForgotPasswordPage'
|
||||
// forgotPassword/useForgotPassword.test.ts). The hook is mocked so the form,
|
||||
// the sent screen and the SMTP hint can each be rendered on demand.
|
||||
|
||||
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown> }))
|
||||
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown>, native: false }))
|
||||
|
||||
vi.mock('./forgotPassword/useForgotPassword', () => ({ useForgotPassword: () => mocks.forgot }))
|
||||
vi.mock('../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../native/platform')>()),
|
||||
isNativeApp: () => mocks.native,
|
||||
}))
|
||||
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
|
||||
|
||||
const navigate = vi.fn((_to: string) => {})
|
||||
const setEmail = vi.fn((_v: string) => {})
|
||||
@@ -32,6 +37,7 @@ function setForgot(over: Record<string, unknown> = {}) {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.native = false
|
||||
setForgot()
|
||||
})
|
||||
|
||||
@@ -124,4 +130,28 @@ describe('ForgotPasswordPage', () => {
|
||||
expect(screen.getByRole('heading', { name: 'Check your email' })).toBeInTheDocument()
|
||||
expect(screen.getByText(/console/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the SMTP warning visible throughout native password recovery', () => {
|
||||
mocks.native = true
|
||||
setForgot({ smtpConfigured: false })
|
||||
const { rerender } = render(<ForgotPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('main')).toHaveClass('al-body')
|
||||
expect(screen.getByRole('textbox', { name: 'Email' })).toHaveAttribute('autocomplete', 'email')
|
||||
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
|
||||
|
||||
setForgot({ smtpConfigured: false, submitted: true })
|
||||
rerender(<ForgotPasswordPage />)
|
||||
expect(screen.getByText(/hasn't configured SMTP/i)).toBeVisible()
|
||||
expect(screen.queryByRole('heading', { name: 'Check your email' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('lets a native user try again after a requester-wide rate limit', () => {
|
||||
mocks.native = true
|
||||
setForgot({ submitted: true, deliveryIssue: 'rateLimit' })
|
||||
render(<ForgotPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Too many attempts')
|
||||
expect(screen.getByRole('button', { name: 'Send reset link' })).toBeEnabled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Mail, ArrowLeft, CheckCircle2, Terminal } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { isNativeApp } from '../native/platform'
|
||||
import AppForgotPassword from './forgotPassword/AppForgotPassword'
|
||||
import { useForgotPassword } from './forgotPassword/useForgotPassword'
|
||||
|
||||
const inputBase: React.CSSProperties = {
|
||||
@@ -13,7 +15,9 @@ const inputBase: React.CSSProperties = {
|
||||
function ForgotPasswordPage() {
|
||||
const { t } = useTranslation()
|
||||
// Page = wiring container: form state, the SMTP probe and submit live in the hook.
|
||||
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = useForgotPassword()
|
||||
const forgot = useForgotPassword()
|
||||
const { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit } = forgot
|
||||
if (isNativeApp()) return <AppForgotPassword forgot={forgot} />
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
|
||||
@@ -9,9 +9,14 @@ import ResetPasswordPage from './ResetPasswordPage'
|
||||
// resetPassword/useResetPassword.test.ts). The hook is mocked so the success,
|
||||
// broken-link, password and MFA screens can each be rendered directly.
|
||||
|
||||
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown> }))
|
||||
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown>, native: false }))
|
||||
|
||||
vi.mock('./resetPassword/useResetPassword', () => ({ useResetPassword: () => mocks.reset }))
|
||||
vi.mock('../native/platform', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../native/platform')>()),
|
||||
isNativeApp: () => mocks.native,
|
||||
}))
|
||||
vi.mock('../../native-shell/scenery', () => ({ startScenery: vi.fn(), cameraForPlan: () => [0, 0] }))
|
||||
|
||||
const navigate = vi.fn((_to: string) => {})
|
||||
const setPw = vi.fn((_v: string) => {})
|
||||
@@ -43,10 +48,35 @@ function setReset(over: Record<string, unknown> = {}) {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.native = false
|
||||
setReset()
|
||||
})
|
||||
|
||||
describe('ResetPasswordPage', () => {
|
||||
it('announces reset errors and supports backup codes on the native screen', () => {
|
||||
mocks.native = true
|
||||
setReset({ mfaRequired: true, error: 'The security code was rejected' })
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('main')).toHaveClass('al-body')
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('The security code was rejected')
|
||||
const code = screen.getByRole('textbox', { name: '2FA code' })
|
||||
expect(code).toHaveAttribute('autocomplete', 'one-time-code')
|
||||
fireEvent.change(code, { target: { value: 'ABCD-EFGH' } })
|
||||
expect(setMfaCode).toHaveBeenCalledWith('ABCD-EFGH')
|
||||
})
|
||||
|
||||
it('lets the native user request another link when the server rejects the current one', () => {
|
||||
mocks.native = true
|
||||
setReset({ linkInvalid: true })
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
expect(screen.getByRole('heading', { name: 'Invalid reset link' })).toBeVisible()
|
||||
expect(screen.queryByLabelText('New password')).not.toBeInTheDocument()
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Send reset link' }))
|
||||
expect(navigate).toHaveBeenCalledWith('/forgot-password')
|
||||
})
|
||||
|
||||
it('FE-PAGE-RESETUI-001: renders the password form for a valid token', () => {
|
||||
setReset()
|
||||
render(<ResetPasswordPage />)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import React, { ChangeEvent } from 'react'
|
||||
import { Lock, KeyRound, CheckCircle2, AlertTriangle, Eye, EyeOff } from 'lucide-react'
|
||||
import { useTranslation } from '../i18n'
|
||||
import { isNativeApp } from '../native/platform'
|
||||
import AppResetPassword from './resetPassword/AppResetPassword'
|
||||
import { useResetPassword } from './resetPassword/useResetPassword'
|
||||
import PasswordChecklist from '../components/shared/PasswordChecklist'
|
||||
|
||||
@@ -14,12 +16,14 @@ const inputBase: React.CSSProperties = {
|
||||
function ResetPasswordPage() {
|
||||
const { t } = useTranslation()
|
||||
// Page = wiring container: token, form state, validation + submit live in the hook.
|
||||
const reset = useResetPassword()
|
||||
const {
|
||||
navigate, token,
|
||||
navigate, token, linkInvalid,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
} = useResetPassword()
|
||||
} = reset
|
||||
if (isNativeApp()) return <AppResetPassword reset={reset} />
|
||||
|
||||
const shell = (inner: React.ReactNode) => (
|
||||
<div style={{
|
||||
@@ -57,7 +61,7 @@ function ResetPasswordPage() {
|
||||
)
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
if (!token || linkInvalid) {
|
||||
return shell(
|
||||
<div style={{ textAlign: 'center', padding: '12px 0' }}>
|
||||
<div style={{
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { CheckCircle2 } from 'lucide-react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
|
||||
import type { useForgotPassword } from './useForgotPassword';
|
||||
|
||||
export default function AppForgotPassword({ forgot }: { forgot: ReturnType<typeof useForgotPassword> }) {
|
||||
const { t } = useTranslation();
|
||||
const back = () => void forgot.navigate('/login');
|
||||
const smtpOff = forgot.smtpConfigured === false;
|
||||
const smtpNotice = smtpOff && <Notice tone="warn">{t('login.forgotPasswordSmtpHintOff')}</Notice>;
|
||||
|
||||
return (
|
||||
<AppAuthScreen>
|
||||
{forgot.submitted && !forgot.deliveryIssue ? (
|
||||
<div className="al-form">
|
||||
<div className="al-recovery-feedback" role="status">
|
||||
{!smtpOff && <CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />}
|
||||
<h1 className="al-title">{t(smtpOff ? 'login.forgotPasswordTitle' : 'login.forgotPasswordSentTitle')}</h1>
|
||||
{!smtpOff && <p className="al-sub">{t('login.forgotPasswordSentBody')}</p>}
|
||||
</div>
|
||||
{smtpNotice}
|
||||
<button type="button" className="al-cta" onClick={back}>
|
||||
{t('login.backToLogin')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<form className="al-form" onSubmit={(event) => void forgot.handleSubmit(event)}>
|
||||
<h1 className="al-title">{t('login.forgotPasswordTitle')}</h1>
|
||||
<p className="al-sub">{t('login.forgotPasswordBody')}</p>
|
||||
{smtpNotice}
|
||||
{forgot.deliveryIssue && (
|
||||
<Notice>
|
||||
{t(forgot.deliveryIssue === 'rateLimit' ? 'common.tooManyAttempts' : 'native.connect.errorUnreachable')}
|
||||
</Notice>
|
||||
)}
|
||||
<Field
|
||||
label={t('common.email')}
|
||||
name="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
autoCapitalize="none"
|
||||
enterKeyHint="send"
|
||||
value={forgot.email}
|
||||
onChange={(event) => forgot.setEmail(event.target.value)}
|
||||
placeholder={t('login.emailPlaceholder')}
|
||||
required
|
||||
/>
|
||||
<button type="submit" className="al-cta" disabled={forgot.isLoading}>
|
||||
{forgot.isLoading && <span className="al-spin" aria-hidden="true" />}
|
||||
{forgot.isLoading ? t('common.loading') : t('login.forgotPasswordSubmit')}
|
||||
</button>
|
||||
</form>
|
||||
<button type="button" className="al-forgot" onClick={back}>
|
||||
{t('login.backToLogin')}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// FE-PAGE-FORGOT-001 to FE-PAGE-FORGOT-008
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { AxiosError } from 'axios';
|
||||
import type { FormEvent } from 'react';
|
||||
import { authApi } from '../../api/client';
|
||||
import { useForgotPassword } from './useForgotPassword';
|
||||
@@ -72,6 +73,18 @@ describe('useForgotPassword', () => {
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
|
||||
expect(result.current.submitted).toBe(true);
|
||||
expect(result.current.deliveryIssue).toBeNull();
|
||||
});
|
||||
|
||||
it('distinguishes a lost connection without revealing information about the address', async () => {
|
||||
vi.mocked(authApi.forgotPassword).mockRejectedValueOnce(new AxiosError('Lost connection', 'ERR_NETWORK'));
|
||||
const { result } = renderHook(() => useForgotPassword());
|
||||
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(result.current.deliveryIssue).toBe('connection');
|
||||
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(result.current.deliveryIssue).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-PAGE-FORGOT-007: ignores a second submit while the first is in flight', async () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useEffect, type FormEvent } from 'react'
|
||||
import { useNavigate } from 'react-router'
|
||||
import { isAxiosError } from 'axios'
|
||||
import { authApi } from '../../api/client'
|
||||
|
||||
/**
|
||||
@@ -14,6 +15,7 @@ export function useForgotPassword() {
|
||||
const [submitted, setSubmitted] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [smtpConfigured, setSmtpConfigured] = useState<boolean | null>(null)
|
||||
const [deliveryIssue, setDeliveryIssue] = useState<'connection' | 'rateLimit' | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
// Probe whether SMTP is configured so we can warn the user up-front that the
|
||||
@@ -29,15 +31,21 @@ export function useForgotPassword() {
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setDeliveryIssue(null)
|
||||
setIsLoading(true)
|
||||
try {
|
||||
await authApi.forgotPassword({ email: email.trim() })
|
||||
} catch {
|
||||
// Enumeration-safe: success UX regardless of server outcome.
|
||||
} catch (error) {
|
||||
// These errors apply to the connection or requester, not to the mailbox.
|
||||
// Keep every other outcome indistinguishable from an accepted request.
|
||||
if (isAxiosError(error)) {
|
||||
if (error.response?.status === 429) setDeliveryIssue('rateLimit')
|
||||
else if (!error.response) setDeliveryIssue('connection')
|
||||
}
|
||||
}
|
||||
setSubmitted(true)
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, handleSubmit }
|
||||
return { navigate, email, setEmail, submitted, isLoading, smtpConfigured, deliveryIssue, handleSubmit }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { AlertCircle, Globe, Lock } from 'lucide-react';
|
||||
import { useEffect, useRef, type InputHTMLAttributes, type ReactNode } from 'react';
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { lightStatusBarIcons } from '../../native/appBoot';
|
||||
import { reportNativeFailure } from '../../native/reportFailure';
|
||||
import './appLogin.css';
|
||||
|
||||
export function AppAuthScreen({ children, leaving }: { children: ReactNode; leaving?: boolean }) {
|
||||
useEffect(() => lightStatusBarIcons(), []);
|
||||
return (
|
||||
<div className={leaving ? 'app-login al-leaving' : 'app-login'}>
|
||||
<AppAuthHero />
|
||||
<main className="al-body">{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AppAuthHero() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
const hero = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const box = hero.current;
|
||||
if (!box) return;
|
||||
let cancelled = false;
|
||||
// Keep the landscape in the position where the address screen leaves it.
|
||||
void import('../../../native-shell/scenery')
|
||||
.then(({ startScenery, cameraForPlan }) => {
|
||||
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
|
||||
})
|
||||
.catch(reportNativeFailure);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
box.querySelector('canvas.scenery')?.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="al-hero" ref={hero}>
|
||||
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
|
||||
{host && (
|
||||
<div className="al-card">
|
||||
<div className="al-card-text">
|
||||
<small>
|
||||
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
|
||||
{t('native.connect.yourTrek')}
|
||||
</small>
|
||||
<div className="al-host" dir="ltr">
|
||||
<Globe size={17} aria-hidden="true" />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
|
||||
{t('common.change')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Notice({ tone, children }: { tone?: 'warn'; children: ReactNode }) {
|
||||
return (
|
||||
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? 'status' : 'alert'}>
|
||||
<AlertCircle size={18} aria-hidden="true" />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Field({
|
||||
label,
|
||||
after,
|
||||
...input
|
||||
}: { label: string; after?: ReactNode } & InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
|
||||
<label className="al-fld">
|
||||
<span className="al-lab">{label}</span>
|
||||
<input {...input} />
|
||||
</label>
|
||||
{after && <span className="al-after">{after}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,8 @@
|
||||
import { AlertCircle, Eye, EyeOff, Fingerprint, Globe, Lock, Shield } from 'lucide-react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { Eye, EyeOff, Fingerprint, Shield } from 'lucide-react';
|
||||
import ToggleSwitch from '../../components/Settings/ToggleSwitch';
|
||||
import { useNativeServer } from '../../components/Settings/useNativeServer';
|
||||
import PasswordChecklist from '../../components/shared/PasswordChecklist';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { lightStatusBarIcons } from '../../native/appBoot';
|
||||
import { reportNativeFailure } from '../../native/reportFailure';
|
||||
import './appLogin.css';
|
||||
import { AppAuthScreen, Field, Notice } from './AppAuthScreen';
|
||||
import { heading as headingOf, oidcLoginHref, oidcOnlyHref, submitLabel, type LoginStep } from './loginModel';
|
||||
import { mfaCodeInputProps } from './mfaCodeInput';
|
||||
import { IDP_LOGIN_URL, type useLogin } from './useLogin';
|
||||
@@ -22,14 +18,10 @@ type Login = ReturnType<typeof useLogin>;
|
||||
* (the device decides, see useLogin) differ.
|
||||
*/
|
||||
export default function AppLogin({ login }: { login: Login }) {
|
||||
useEffect(() => lightStatusBarIcons(), []);
|
||||
return (
|
||||
<div className={login.showTakeoff ? 'app-login al-leaving' : 'app-login'}>
|
||||
<AppLoginHero />
|
||||
<main className="al-body">
|
||||
<AppLoginContent login={login} />
|
||||
</main>
|
||||
</div>
|
||||
<AppAuthScreen leaving={login.showTakeoff}>
|
||||
<AppLoginContent login={login} />
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -59,85 +51,6 @@ function AppLoginContent({ login }: { login: Login }) {
|
||||
return <Credentials login={login} />;
|
||||
}
|
||||
|
||||
/** The landscape of the address screen, with the server this screen signs in to. */
|
||||
function AppLoginHero() {
|
||||
const { t } = useTranslation();
|
||||
const { host, changeServer } = useNativeServer();
|
||||
const hero = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const box = hero.current;
|
||||
if (!box) return;
|
||||
let cancelled = false;
|
||||
// The same camera the address screen ends on, so the picture holds still
|
||||
// across the change of screens. The scene stops drawing once its canvas
|
||||
// has left the page.
|
||||
void import('../../../native-shell/scenery')
|
||||
.then(({ startScenery, cameraForPlan }) => {
|
||||
if (!cancelled) startScenery(box, { frame: 320, camera: cameraForPlan(1), haze: false });
|
||||
})
|
||||
// Without the landscape the box keeps its plain sea colour.
|
||||
.catch(reportNativeFailure);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
box.querySelector('canvas.scenery')?.remove();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="al-hero" ref={hero}>
|
||||
<img className="al-logo" src="/logo-light.svg" alt="TREK" />
|
||||
{host && (
|
||||
<div className="al-card">
|
||||
<div className="al-card-text">
|
||||
<small>
|
||||
<Lock size={12} strokeWidth={2.6} aria-hidden="true" />
|
||||
{t('native.connect.yourTrek')}
|
||||
</small>
|
||||
<div className="al-host" dir="ltr">
|
||||
<Globe size={17} aria-hidden="true" />
|
||||
<span>{host}</span>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="al-change" onClick={changeServer} aria-label={t('native.changeServer')}>
|
||||
{t('common.change')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Notice({ tone, children }: { tone?: 'warn'; children: React.ReactNode }) {
|
||||
return (
|
||||
<div className={tone ? `al-notice ${tone}` : 'al-notice'} role={tone ? undefined : 'alert'}>
|
||||
<AlertCircle size={18} aria-hidden="true" />
|
||||
<div>{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A field on a white card, the label above the input, as on the address screen.
|
||||
* A control beside the input (the password's eye) sits outside the label, so
|
||||
* the label names the input alone.
|
||||
*/
|
||||
function Field({
|
||||
label,
|
||||
after,
|
||||
...input
|
||||
}: { label: string; after?: React.ReactNode } & React.InputHTMLAttributes<HTMLInputElement>) {
|
||||
return (
|
||||
<div className={after ? 'al-fld-wrap with-after' : 'al-fld-wrap'}>
|
||||
<label className="al-fld">
|
||||
<span className="al-lab">{label}</span>
|
||||
<input {...input} />
|
||||
</label>
|
||||
{after && <span className="al-after">{after}</span>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OidcOnly({ login }: { login: Login }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* The sign-in screen inside the iOS and Android app (AppLogin.tsx). It is the
|
||||
* The sign-in and password recovery screens inside the iOS and Android app. The sign-in is the
|
||||
* next screen after the app's own address screen (native-shell/), so it wears
|
||||
* that screen's look: the same landscape on top, the same glass card with the
|
||||
* server on it, the same type, fields and buttons on the same warm page. The
|
||||
@@ -295,6 +295,14 @@
|
||||
line-height: 1.5;
|
||||
color: var(--al-text);
|
||||
}
|
||||
.al-recovery-feedback {
|
||||
display: grid;
|
||||
gap: 8px;
|
||||
justify-items: start;
|
||||
}
|
||||
.al-recovery-icon {
|
||||
color: var(--al-good);
|
||||
}
|
||||
|
||||
/* A field on a white card: the label above, the input below it. */
|
||||
.al-fld {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { CheckCircle2, Eye, EyeOff } from 'lucide-react';
|
||||
import PasswordChecklist from '../../components/shared/PasswordChecklist';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { AppAuthScreen, Field, Notice } from '../login/AppAuthScreen';
|
||||
import { mfaCodeInputProps } from '../login/mfaCodeInput';
|
||||
import type { useResetPassword } from './useResetPassword';
|
||||
|
||||
type Reset = ReturnType<typeof useResetPassword>;
|
||||
|
||||
export default function AppResetPassword({ reset }: { reset: Reset }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<AppAuthScreen>
|
||||
{reset.success ? (
|
||||
<div className="al-form">
|
||||
<div className="al-recovery-feedback" role="status">
|
||||
<CheckCircle2 className="al-recovery-icon" size={28} aria-hidden="true" />
|
||||
<h1 className="al-title">{t('login.resetPasswordSuccessTitle')}</h1>
|
||||
<p className="al-sub">{t('login.resetPasswordSuccessBody')}</p>
|
||||
</div>
|
||||
<button type="button" className="al-cta" onClick={() => void reset.navigate('/login')}>
|
||||
{t('login.signIn')}
|
||||
</button>
|
||||
</div>
|
||||
) : !reset.token || reset.linkInvalid ? (
|
||||
<div className="al-form">
|
||||
<h1 className="al-title">{t('login.resetPasswordInvalidLink')}</h1>
|
||||
<Notice>{t('login.resetPasswordInvalidLinkBody')}</Notice>
|
||||
<button type="button" className="al-cta" onClick={() => void reset.navigate('/forgot-password')}>
|
||||
{t('login.forgotPasswordSubmit')}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<ResetForm reset={reset} />
|
||||
)}
|
||||
</AppAuthScreen>
|
||||
);
|
||||
}
|
||||
|
||||
function ResetForm({ reset }: { reset: Reset }) {
|
||||
const { t } = useTranslation();
|
||||
const inputType = reset.showPw ? 'text' : 'password';
|
||||
const title = reset.mfaRequired ? t('login.mfaTitle') : t('login.resetPasswordTitle');
|
||||
const action = reset.mfaRequired ? t('login.resetPasswordVerify') : t('login.resetPasswordSubmit');
|
||||
return (
|
||||
<form className="al-form" onSubmit={(event) => void reset.handleSubmit(event)}>
|
||||
<h1 className="al-title">{title}</h1>
|
||||
<p className="al-sub">{t(reset.mfaRequired ? 'login.resetPasswordMfaBody' : 'login.resetPasswordBody')}</p>
|
||||
{reset.error && <Notice>{reset.error}</Notice>}
|
||||
{reset.mfaRequired ? (
|
||||
<Field
|
||||
label={t('login.mfaCode')}
|
||||
{...mfaCodeInputProps(reset.mfaCode, reset.setMfaCode, t('login.mfaPlaceholder'))}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<Field
|
||||
label={t('login.newPassword')}
|
||||
type={inputType}
|
||||
name="new-password"
|
||||
autoComplete="new-password"
|
||||
value={reset.pw}
|
||||
onChange={(event) => reset.setPw(event.target.value)}
|
||||
required
|
||||
after={
|
||||
<button
|
||||
type="button"
|
||||
className="al-eye"
|
||||
aria-label={t('native.claim.showPassword')}
|
||||
aria-pressed={reset.showPw}
|
||||
onClick={() => reset.setShowPw((visible) => !visible)}
|
||||
>
|
||||
{reset.showPw ? <EyeOff size={18} aria-hidden="true" /> : <Eye size={18} aria-hidden="true" />}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<PasswordChecklist password={reset.pw} className="al-check" tone="light" />
|
||||
<Field
|
||||
label={t('login.confirmPassword')}
|
||||
type={inputType}
|
||||
name="confirm-password"
|
||||
autoComplete="new-password"
|
||||
value={reset.pw2}
|
||||
onChange={(event) => reset.setPw2(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<button type="submit" className="al-cta" disabled={reset.isLoading}>
|
||||
{reset.isLoading && <span className="al-spin" aria-hidden="true" />}
|
||||
{reset.isLoading ? t('common.loading') : action}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -132,6 +132,32 @@ describe('useResetPassword', () => {
|
||||
expect(result.current.success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'Invalid or expired reset link',
|
||||
'This reset link has already been used',
|
||||
'Reset link has expired. Please request a new one.',
|
||||
])('stops retrying a link refused by the server (%s)', async (error) => {
|
||||
vi.mocked(authApi.resetPassword).mockResolvedValueOnce({ mfa_required: true } as never);
|
||||
vi.mocked(authApi.resetPassword).mockRejectedValueOnce({ response: { data: { error } } });
|
||||
const { result, rerender } = renderHook(() => useResetPassword());
|
||||
|
||||
await submit(result, 'Longenough1!');
|
||||
act(() => result.current.setMfaCode('123456'));
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
|
||||
expect(result.current.linkInvalid).toBe(true);
|
||||
expect(result.current.pw).toBe('');
|
||||
expect(result.current.pw2).toBe('');
|
||||
expect(result.current.mfaCode).toBe('');
|
||||
expect(result.current.mfaRequired).toBe(false);
|
||||
await act(() => result.current.handleSubmit(submitEvent()));
|
||||
expect(authApi.resetPassword).toHaveBeenCalledTimes(2);
|
||||
|
||||
search = new URLSearchParams('token=fresh-link');
|
||||
rerender();
|
||||
expect(result.current.linkInvalid).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-PAGE-RESET-011: surfaces a plain Error message as-is', async () => {
|
||||
vi.mocked(authApi.resetPassword).mockRejectedValueOnce(new Error('Network Error'));
|
||||
const { result } = renderHook(() => useResetPassword());
|
||||
|
||||
@@ -5,11 +5,17 @@ import { getApiErrorMessage } from '../../types'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { passwordErrorKey } from '../../utils/passwordError'
|
||||
|
||||
// Published TREK servers report these refusals as messages, without an error code.
|
||||
const unusableLinkErrors = new Set([
|
||||
'Invalid or expired reset link',
|
||||
'This reset link has already been used',
|
||||
'Reset link has expired. Please request a new one.',
|
||||
])
|
||||
|
||||
/**
|
||||
* Reset-password data hook — owns the token lookup, the form state, the
|
||||
* client-side validation and the submit (incl. the MFA step-up branch).
|
||||
* ResetPasswordPage is a pure wiring container. Behaviour is identical to the
|
||||
* previous in-component logic.
|
||||
* ResetPasswordPage is a pure wiring container.
|
||||
*/
|
||||
export function useResetPassword() {
|
||||
const { t } = useTranslation()
|
||||
@@ -23,8 +29,10 @@ export function useResetPassword() {
|
||||
const [mfaCode, setMfaCode] = useState('')
|
||||
const [mfaRequired, setMfaRequired] = useState(false)
|
||||
const [error, setError] = useState('')
|
||||
const [unusableToken, setUnusableToken] = useState<string | null>(null)
|
||||
const [success, setSuccess] = useState(false)
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const linkInvalid = unusableToken === token
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) setError(t('login.resetPasswordInvalidLink'))
|
||||
@@ -34,7 +42,7 @@ export function useResetPassword() {
|
||||
e.preventDefault()
|
||||
if (isLoading) return
|
||||
setError('')
|
||||
if (!token) return
|
||||
if (!token || linkInvalid) return
|
||||
const weak = passwordErrorKey(pw)
|
||||
if (weak) { setError(t(weak)); return }
|
||||
if (pw !== pw2) { setError(t('login.passwordsDontMatch')); return }
|
||||
@@ -54,13 +62,23 @@ export function useResetPassword() {
|
||||
setSuccess(true)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(getApiErrorMessage(err, t('login.resetPasswordFailed')))
|
||||
const message = getApiErrorMessage(err, t('login.resetPasswordFailed'))
|
||||
if (unusableLinkErrors.has(message)) {
|
||||
setUnusableToken(token)
|
||||
setPw('')
|
||||
setPw2('')
|
||||
setShowPw(false)
|
||||
setMfaCode('')
|
||||
setMfaRequired(false)
|
||||
} else {
|
||||
setError(message)
|
||||
}
|
||||
}
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
||||
return {
|
||||
navigate, token,
|
||||
navigate, token, linkInvalid,
|
||||
pw, setPw, pw2, setPw2, showPw, setShowPw,
|
||||
mfaCode, setMfaCode, mfaRequired, error, success, isLoading,
|
||||
handleSubmit,
|
||||
|
||||
Vendored
+3
@@ -4,6 +4,9 @@
|
||||
/** The version this bundle was built as (client/package.json), set by `define` in vite.config.js. */
|
||||
declare const __TREK_UI_VERSION__: string;
|
||||
|
||||
/** Defined only for the native store-sandbox build. */
|
||||
declare const __TREK_STORE_SANDBOX_ORIGIN__: string | undefined;
|
||||
|
||||
/**
|
||||
* Big Shoulders Display's weights, imported for their stylesheets alone
|
||||
* (components/Studio/bookFontFaces.ts). Its package maps `./*` to `./*.css`
|
||||
|
||||
Reference in New Issue
Block a user