diff --git a/src/app/pages/auth/authFront.test.tsx b/src/app/pages/auth/authFront.test.tsx new file mode 100644 index 00000000..3e6abfd7 --- /dev/null +++ b/src/app/pages/auth/authFront.test.tsx @@ -0,0 +1,113 @@ +import React from 'react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { renderToString } from 'react-dom/server'; +import { MemoryRouter } from 'react-router-dom'; +import { AutoDiscoveryInfoProvider } from '../../hooks/useAutoDiscoveryInfo'; +import { AuthServerProvider } from '../../hooks/useAuthServer'; +import { AuthFlowsProvider } from '../../hooks/useAuthFlows'; +import { ClientConfigProvider } from '../../hooks/useClientConfig'; +import type { ClientConfig } from '../../hooks/useClientConfig'; +import type { AutoDiscoveryInfo } from '../../cs-api'; +import { setSoftLogout } from '../../state/softLogout'; +import { Login } from './login/Login'; +import { ResetPassword } from './reset-password/ResetPassword'; + +vi.mock('../../../client/initMatrix', () => ({ clearLoginData: vi.fn() })); +// folds' Overlay portals into document, which the server renderer has none of. +vi.mock('folds', async (importOriginal) => ({ + ...(await importOriginal()), + Overlay: () => null, +})); +vi.mock('./reset-password/PasswordResetForm', () => ({ + PasswordResetForm: () =>
in-client reset form
, +})); + +const plain: AutoDiscoveryInfo = { 'm.homeserver': { base_url: 'https://hs.example' } }; +const mas: AutoDiscoveryInfo = { + ...plain, + 'org.matrix.msc2965.authentication': { account: 'https://auth.example/account' }, +}; +const entryConfig: ClientConfig = { + registration: { enabled: true, url: 'https://accounts.example/join' }, +}; +const flows = { + loginFlows: { flows: [{ type: 'm.login.password' }] }, + registerFlows: { status: 400 }, +} as never; + +const render = (ui: React.ReactElement, info: AutoDiscoveryInfo, config: ClientConfig = {}) => + renderToString( + + + + + {ui} + + + + + ); + +const store = new Map(); +beforeEach(() => { + store.clear(); + vi.stubGlobal('window', { location: { origin: 'https://app.example', search: '' } }); + vi.stubGlobal('localStorage', { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => store.set(k, v), + removeItem: (k: string) => store.delete(k), + }); +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('Login register entries', () => { + it('non-MAS without an entry: the bare Register link, no notice', () => { + const html = render(, plain); + expect(html).toContain('Register'); + expect(html).not.toContain('managed by your sign-in service'); + }); + it('non-MAS with an entry: the entry and its notice', () => { + const html = render(, plain, entryConfig); + expect(html).toContain('href="https://accounts.example/join"'); + }); + it('MAS without an entry: the account page notice, no bare Register link', () => { + const html = render(, mas); + expect(html).toContain('managed by your sign-in service'); + expect(html).toContain('href="https://auth.example/account"'); + expect(html).not.toContain('Register'); + }); + it('MAS with an entry: the entry stays, no MAS notice', () => { + const html = render(, mas, entryConfig); + expect(html).toContain('href="https://accounts.example/join"'); + expect(html).not.toContain('managed by your sign-in service'); + }); +}); + +describe('PasswordLoginForm through Login', () => { + it('shows Forgot Password only without MAS', () => { + expect(render(, plain)).toContain('Forget Password?'); + expect(render(, mas)).not.toContain('Forget Password?'); + }); + it('fixes the username and offers someone else only with a soft record', () => { + expect(render(, plain)).not.toContain('readOnly'); + expect(render(, plain)).not.toContain('Sign in as someone else'); + setSoftLogout({ userId: '@a:hs.example', deviceId: 'DEV' }); + const html = render(, plain); + expect(html).toContain('value="@a:hs.example"'); + expect(html).toMatch(/readonly/i); + expect(html).toContain('Sign in as someone else'); + }); +}); + +describe('ResetPassword', () => { + it('shows the notice under MAS and the form otherwise', () => { + const under = render(, mas); + expect(under).toContain('href="https://auth.example/account"'); + expect(under).not.toContain('in-client reset form'); + const plainHtml = render(, plain); + expect(plainHtml).toContain('in-client reset form'); + expect(plainHtml).not.toContain('managed by your sign-in service'); + }); +}); diff --git a/src/app/pages/auth/login/loginUtil.ts b/src/app/pages/auth/login/loginUtil.ts index 7a9cfb38..d1cfea82 100644 --- a/src/app/pages/auth/login/loginUtil.ts +++ b/src/app/pages/auth/login/loginUtil.ts @@ -1,6 +1,6 @@ import to from 'await-to-js'; import { LoginRequest, LoginResponse, MatrixError, createClient } from 'matrix-js-sdk'; -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { ClientConfig, clientAllowedServer } from '../../../hooks/useClientConfig'; import { autoDiscovery, specVersions } from '../../../cs-api'; @@ -12,7 +12,7 @@ import { import { getHomePath } from '../../pathUtils'; import { setFallbackSession } from '../../../state/sessions'; import { settleLocalData } from '../../../state/softLogout'; -import { wipeLocalData } from '../../../../client/initMatrix'; +import { wipeLocalData } from '../../../../client/wipeLocalData'; export enum GetBaseUrlError { NotAllow = 'NotAllow', @@ -112,9 +112,11 @@ export const login = async ( export const useLoginComplete = (data?: CustomLoginResponse) => { const navigate = useNavigate(); + const settled = useRef(); useEffect(() => { - if (!data) return; + if (!data || settled.current === data) return; + settled.current = data; const { response: loginRes, baseUrl: loginBaseUrl } = data; const finish = async () => { const afterLoginRedirectUrl = getAfterLoginRedirectPath(); diff --git a/src/app/pages/auth/masAccount.test.ts b/src/app/pages/auth/masAccount.test.ts index f2331365..04bd6340 100644 --- a/src/app/pages/auth/masAccount.test.ts +++ b/src/app/pages/auth/masAccount.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest'; -import { readFileSync } from 'fs'; import { masAccountUrl } from './masAccount'; import type { AutoDiscoveryInfo } from '../../cs-api'; @@ -37,39 +36,3 @@ describe('masAccountUrl', () => { expect(masAccountUrl(info({ account: 'ftp://a.example' }))).toBeUndefined(); }); }); - -const src = (p: string) => readFileSync(`${process.cwd()}/src/app/pages/auth/${p}`, 'utf8'); - -describe('MAS front guards', () => { - it('Login keeps a configured register entry, else MAS notice, else the bare link', () => { - const s = src('login/Login.tsx'); - expect(s).toContain('useMasAccountUrl()'); - expect(s).toContain('{registerEntry && }'); - expect(s).toContain('{!registerEntry && masUrl && { - const s = src('login/PasswordLoginForm.tsx'); - expect(s).toContain('useMasAccountUrl()'); - expect(s).toMatch(/\{!masUrl && \([\s\S]*getResetPasswordPath/); - }); - it('RegisterRoute and ResetPassword show the notice under MAS', () => { - ['register/RegisterRoute.tsx', 'reset-password/ResetPassword.tsx'].forEach((p) => { - const s = src(p); - expect(s).toContain('useMasAccountUrl()'); - expect(s).toContain(' { - expect(src('login/PasswordLoginForm.tsx').match(/withDevice\(\{/g)).toHaveLength(3); - expect(src('login/TokenLogin.tsx')).toContain('withSoftLogoutDevice('); - }); - it('the logout listener and login completion defer to the one wipe', () => { - const root = readFileSync(`${process.cwd()}/src/app/pages/client/ClientRoot.tsx`, 'utf8'); - expect(root).toContain('createLogoutHandler('); - expect(root).toContain('wipeLocalData(mx)'); - expect(root).not.toContain('localStorage.clear'); - expect(src('login/loginUtil.ts')).toContain('settleLocalData(loginRes'); - expect(src('register/registerUtil.ts')).toContain('settleLocalData('); - }); -}); diff --git a/src/app/pages/auth/register/registerUtil.ts b/src/app/pages/auth/register/registerUtil.ts index 9d5afa87..dca4dd17 100644 --- a/src/app/pages/auth/register/registerUtil.ts +++ b/src/app/pages/auth/register/registerUtil.ts @@ -6,7 +6,7 @@ import { RegisterRequest, RegisterResponse, } from 'matrix-js-sdk'; -import { useEffect } from 'react'; +import { useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { LoginPathSearchParams } from '../../paths'; import { ErrorCode } from '../../../cs-errorcode'; @@ -18,7 +18,7 @@ import { getHomePath, getLoginPath, withSearchParam } from '../../pathUtils'; import { getMxIdLocalPart, getMxIdServer } from '../../../utils/matrix'; import { setFallbackSession } from '../../../state/sessions'; import { settleLocalData } from '../../../state/softLogout'; -import { wipeLocalData } from '../../../../client/initMatrix'; +import { wipeLocalData } from '../../../../client/wipeLocalData'; import type { RegisterTrouble } from '../authMessages'; export enum RegisterError { @@ -133,9 +133,11 @@ export const register = async ( export const useRegisterComplete = (data?: CustomRegisterResponse) => { const navigate = useNavigate(); + const settled = useRef(); useEffect(() => { - if (data) { + if (data && settled.current !== data) { + settled.current = data; const { response, baseUrl } = data; const userId = response.user_id; diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx index 2cb69ed5..ba1876ce 100644 --- a/src/app/pages/client/ClientRoot.tsx +++ b/src/app/pages/client/ClientRoot.tsx @@ -19,11 +19,11 @@ import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useState } import { clearCacheAndReload, clearLoginData, - wipeLocalData, initClient, logoutClient, startClient, } from '../../../client/initMatrix'; +import { wipeLocalData } from '../../../client/wipeLocalData'; import { SplashScreen } from '../../components/splash-screen'; import { ServerConfigsLoader } from '../../components/ServerConfigsLoader'; import { CapabilitiesProvider } from '../../hooks/useCapabilities'; diff --git a/src/app/state/softLogout.test.ts b/src/app/state/softLogout.test.ts index 8df1a8f8..2f113dd4 100644 --- a/src/app/state/softLogout.test.ts +++ b/src/app/state/softLogout.test.ts @@ -168,6 +168,13 @@ describe('the logout handler', () => { await handler({ data: {} }); expect(calls).toEqual({ stop: 0, wipe: 0, reload: 0, worker: 0 }); }); + it('soft with no session in storage: one wipe, no record', async () => { + const { storage, calls, handler } = rig(true); + storage.removeItem('cinny_access_token'); + await handler({ data: { soft_logout: true } }); + expect(calls).toEqual({ stop: 1, wipe: 1, reload: 1, worker: 0 }); + expect(getSoftLogout(storage)).toBeUndefined(); + }); it('hard twice: one wipe', async () => { const { calls, handler, err } = rig(false); await handler(err); diff --git a/src/app/state/softLogout.ts b/src/app/state/softLogout.ts index 645d0cc3..bf0c3fd1 100644 --- a/src/app/state/softLogout.ts +++ b/src/app/state/softLogout.ts @@ -98,8 +98,9 @@ export const createLogoutHandler = (ports: LogoutHandlerPorts) => { if (fired || getSoftLogout(ports.storage)) return; fired = true; ports.stop(); - if (classifyLogout(err) === 'soft') { - if (beginSoftLogout(ports.storage)) ports.forgetSessionInWorker(); + // Soft needs a session to remember; without one nothing can vouch for the stores, so wipe. + if (classifyLogout(err) === 'soft' && beginSoftLogout(ports.storage)) { + ports.forgetSessionInWorker(); ports.reload(); return; } diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index b6d22597..a5cc2b35 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -7,6 +7,7 @@ import { SyncState, } from 'matrix-js-sdk'; +import { wipeLocalData } from './wipeLocalData'; import { cryptoCallbacks } from './secretStorageKeys'; import { clearNavToActivePathStore } from '../app/state/navToActivePath'; import { pushSessionToSW } from '../sw-session'; @@ -111,45 +112,6 @@ export const clearCacheAndReload = async (mx: MatrixClient) => { window.location.reload(); }; -// The rust crypto databases the SDK names, for browsers without indexedDB.databases(). -const KNOWN_DATABASES = [ - 'web-sync-store', - 'crypto-store', - 'matrix-js-sdk::matrix-sdk-crypto', - 'matrix-js-sdk::matrix-sdk-crypto-meta', -]; - -const deleteDatabase = (name: string) => - new Promise((resolve) => { - const req = window.indexedDB.deleteDatabase(name); - req.onsuccess = () => resolve(); - req.onerror = () => resolve(); - req.onblocked = () => resolve(); - }); - -/** - * The one wipe of everything this browser holds for the account: client stores, every IndexedDB - * database, localStorage. Hard logout, a soft logout answered by another user or device, and - * "sign in as someone else" all end here. Callers reload afterwards. - */ -export const wipeLocalData = async (mx?: MatrixClient) => { - try { - await mx?.clearStores(); - } catch { - // the databases go below regardless - } - let names: string[]; - try { - names = (await window.indexedDB.databases()) - .map((db) => db.name) - .filter((name): name is string => !!name); - } catch { - names = KNOWN_DATABASES; - } - await Promise.all(names.map(deleteDatabase)); - window.localStorage.clear(); -}; - export const logoutClient = async (mx: MatrixClient) => { pushSessionToSW(); mx.stopClient(); diff --git a/src/client/wipeLocalData.test.ts b/src/client/wipeLocalData.test.ts new file mode 100644 index 00000000..2d3faa0a --- /dev/null +++ b/src/client/wipeLocalData.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest'; +import { KNOWN_DATABASES, wipeLocalData } from './wipeLocalData'; + +type Mode = 'success' | 'blocked' | 'error' | 'throws'; + +const rig = (opts: { databases?: () => Promise<{ name?: string }[]>; mode?: Mode }) => { + const deleted: string[] = []; + let cleared = 0; + const indexedDB = { + databases: opts.databases, + deleteDatabase: (name: string) => { + deleted.push(name); + if (opts.mode === 'throws') throw new Error('sync boom'); + const req: Record void) | undefined> = {}; + setTimeout(() => { + if (opts.mode === 'blocked') req.onblocked?.(); + else if (opts.mode === 'error') req.onerror?.(); + else req.onsuccess?.(); + }, 0); + return req as unknown as IDBOpenDBRequest; + }, + }; + const storage = { + clear: () => { + cleared += 1; + }, + }; + return { deleted, cleared: () => cleared, ports: { indexedDB, storage } }; +}; + +describe('wipeLocalData', () => { + it('deletes every listed database and clears storage', async () => { + const r = rig({ databases: async () => [{ name: 'a' }, { name: 'b' }, {}] }); + await wipeLocalData(undefined, r.ports); + expect(r.deleted).toEqual(['a', 'b']); + expect(r.cleared()).toBe(1); + }); + it('falls back to the known names when databases() is absent or throws', async () => { + const absent = rig({}); + await wipeLocalData(undefined, absent.ports); + expect(absent.deleted).toEqual(KNOWN_DATABASES); + expect(absent.cleared()).toBe(1); + const throws = rig({ + databases: async () => { + throw new Error('nope'); + }, + }); + await wipeLocalData(undefined, throws.ports); + expect(throws.deleted).toEqual(KNOWN_DATABASES); + expect(throws.cleared()).toBe(1); + }); + it('a synchronous deleteDatabase throw does not abort the rest or the storage clear', async () => { + const r = rig({ databases: async () => [{ name: 'a' }, { name: 'b' }], mode: 'throws' }); + await expect(wipeLocalData(undefined, r.ports)).resolves.toBeUndefined(); + expect(r.deleted).toEqual(['a', 'b']); + expect(r.cleared()).toBe(1); + }); + it('blocked and errored deletions settle and still clear storage', async () => { + await Promise.all( + (['blocked', 'error'] as const).map(async (mode) => { + const r = rig({ databases: async () => [{ name: 'a' }], mode }); + await wipeLocalData(undefined, r.ports); + expect(r.cleared()).toBe(1); + }) + ); + }); + it('a throwing clearStores does not stop the wipe', async () => { + const r = rig({ databases: async () => [{ name: 'a' }] }); + const mx = { + clearStores: async () => { + throw new Error('x'); + }, + }; + await wipeLocalData(mx as never, r.ports); + expect(r.deleted).toEqual(['a']); + expect(r.cleared()).toBe(1); + }); +}); diff --git a/src/client/wipeLocalData.ts b/src/client/wipeLocalData.ts new file mode 100644 index 00000000..dc24951c --- /dev/null +++ b/src/client/wipeLocalData.ts @@ -0,0 +1,58 @@ +import type { MatrixClient } from 'matrix-js-sdk'; + +// The rust crypto databases the SDK names, for browsers without indexedDB.databases(). +export const KNOWN_DATABASES = [ + 'web-sync-store', + 'crypto-store', + 'matrix-js-sdk::matrix-sdk-crypto', + 'matrix-js-sdk::matrix-sdk-crypto-meta', +]; + +export type WipePorts = { + indexedDB: Pick & { + databases?: () => Promise<{ name?: string }[]>; + }; + storage: Pick; +}; + +const deleteDatabase = (idb: WipePorts['indexedDB'], name: string) => + new Promise((resolve) => { + try { + const req = idb.deleteDatabase(name); + req.onsuccess = () => resolve(); + req.onerror = () => resolve(); + req.onblocked = () => resolve(); + } catch { + // one database failing must not stop the rest + resolve(); + } + }); + +/** + * The one wipe of everything this browser holds for the account: client stores, every IndexedDB + * database, localStorage. Hard logout, a soft logout answered by another user or device, and + * "sign in as someone else" all end here. It never rejects, and localStorage (the access token + * with it) is cleared whatever the databases do. Callers reload afterwards. + */ +export const wipeLocalData = async ( + mx?: MatrixClient, + ports: WipePorts = { indexedDB: window.indexedDB, storage: window.localStorage } +): Promise => { + try { + try { + await mx?.clearStores(); + } catch { + // the databases go below regardless + } + let names = KNOWN_DATABASES; + try { + const listed = await ports.indexedDB.databases?.(); + if (listed) names = listed.map((db) => db.name).filter((n): n is string => !!n); + } catch { + // keep the known names + } + await Promise.all(names.map((name) => deleteDatabase(ports.indexedDB, name))); + } finally { + ports.storage.clear(); + } +};