Second Soul pass: soft event without a session wipes, wipe never rejects, rendered MAS tests
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
Some checks failed
Build pull request / Build pull request (pull_request) Has been cancelled
wipeLocalData moves to its own module with injectable ports: per-database failures are contained and localStorage clears in a finally. A soft logout with no session to remember is treated as hard. Login/PasswordLoginForm/ResetPassword MAS behavior is now tested by rendering. Login and register completion settle once per response. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
3a5258c3ef
commit
31d58075db
10 changed files with 271 additions and 85 deletions
113
src/app/pages/auth/authFront.test.tsx
Normal file
113
src/app/pages/auth/authFront.test.tsx
Normal file
|
|
@ -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<typeof import('folds')>()),
|
||||
Overlay: () => null,
|
||||
}));
|
||||
vi.mock('./reset-password/PasswordResetForm', () => ({
|
||||
PasswordResetForm: () => <div>in-client reset form</div>,
|
||||
}));
|
||||
|
||||
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(
|
||||
<MemoryRouter>
|
||||
<AutoDiscoveryInfoProvider value={info}>
|
||||
<AuthServerProvider value="hs.example">
|
||||
<AuthFlowsProvider value={flows}>
|
||||
<ClientConfigProvider value={config}>{ui}</ClientConfigProvider>
|
||||
</AuthFlowsProvider>
|
||||
</AuthServerProvider>
|
||||
</AutoDiscoveryInfoProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
const store = new Map<string, string>();
|
||||
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(<Login />, plain);
|
||||
expect(html).toContain('Register</a>');
|
||||
expect(html).not.toContain('managed by your sign-in service');
|
||||
});
|
||||
it('non-MAS with an entry: the entry and its notice', () => {
|
||||
const html = render(<Login />, 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(<Login />, mas);
|
||||
expect(html).toContain('managed by your sign-in service');
|
||||
expect(html).toContain('href="https://auth.example/account"');
|
||||
expect(html).not.toContain('Register</a>');
|
||||
});
|
||||
it('MAS with an entry: the entry stays, no MAS notice', () => {
|
||||
const html = render(<Login />, 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(<Login />, plain)).toContain('Forget Password?');
|
||||
expect(render(<Login />, mas)).not.toContain('Forget Password?');
|
||||
});
|
||||
it('fixes the username and offers someone else only with a soft record', () => {
|
||||
expect(render(<Login />, plain)).not.toContain('readOnly');
|
||||
expect(render(<Login />, plain)).not.toContain('Sign in as someone else');
|
||||
setSoftLogout({ userId: '@a:hs.example', deviceId: 'DEV' });
|
||||
const html = render(<Login />, 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(<ResetPassword />, mas);
|
||||
expect(under).toContain('href="https://auth.example/account"');
|
||||
expect(under).not.toContain('in-client reset form');
|
||||
const plainHtml = render(<ResetPassword />, plain);
|
||||
expect(plainHtml).toContain('in-client reset form');
|
||||
expect(plainHtml).not.toContain('managed by your sign-in service');
|
||||
});
|
||||
});
|
||||
|
|
@ -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<CustomLoginResponse>();
|
||||
|
||||
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();
|
||||
|
|
|
|||
|
|
@ -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 && <RegisterEntry />}');
|
||||
expect(s).toContain('{!registerEntry && masUrl && <MasAccountNotice');
|
||||
expect(s).toContain('{!registerEntry && !masUrl && (');
|
||||
});
|
||||
it('PasswordLoginForm hides the forgot link behind the MAS predicate', () => {
|
||||
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('<MasAccountNotice');
|
||||
});
|
||||
});
|
||||
it('every login request path carries the soft-logout device', () => {
|
||||
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(');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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<CustomRegisterResponse>();
|
||||
|
||||
useEffect(() => {
|
||||
if (data) {
|
||||
if (data && settled.current !== data) {
|
||||
settled.current = data;
|
||||
const { response, baseUrl } = data;
|
||||
|
||||
const userId = response.user_id;
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<void>((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();
|
||||
|
|
|
|||
78
src/client/wipeLocalData.test.ts
Normal file
78
src/client/wipeLocalData.test.ts
Normal file
|
|
@ -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<string, (() => 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);
|
||||
});
|
||||
});
|
||||
58
src/client/wipeLocalData.ts
Normal file
58
src/client/wipeLocalData.ts
Normal file
|
|
@ -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<IDBFactory, 'deleteDatabase'> & {
|
||||
databases?: () => Promise<{ name?: string }[]>;
|
||||
};
|
||||
storage: Pick<Storage, 'clear'>;
|
||||
};
|
||||
|
||||
const deleteDatabase = (idb: WipePorts['indexedDB'], name: string) =>
|
||||
new Promise<void>((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<void> => {
|
||||
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();
|
||||
}
|
||||
};
|
||||
Loading…
Reference in a new issue