Soul fixes: idempotent logout handler, keep register consent entry under MAS, settle stores on register
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
First SessionLoggedOut decides; later events are ignored so a second soft event cannot fall into the wipe. Under MAS a configured registrationEntry (with its training notice) is kept; the MAS notice replaces only the in-client form and bare link. Registration goes through the same keep-or-wipe settle as login. Soft record drops its unused baseUrl. One shared https-or-localhost predicate. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
4fd83fb4c4
commit
3a5258c3ef
12 changed files with 214 additions and 85 deletions
|
|
@ -62,6 +62,7 @@ export function Login() {
|
|||
|
||||
const parsedFlows = useParsedLoginFlows(loginFlows.flows);
|
||||
const masUrl = useMasAccountUrl();
|
||||
const registerEntry = registrationEntry(config);
|
||||
const softLogout = useSoftLogout();
|
||||
|
||||
return (
|
||||
|
|
@ -100,9 +101,9 @@ export function Login() {
|
|||
<span data-spacing-node />
|
||||
</>
|
||||
)}
|
||||
{masUrl && <MasAccountNotice url={masUrl} />}
|
||||
{!masUrl && registrationEntry(config) && <RegisterEntry />}
|
||||
{!masUrl && !registrationEntry(config) && (
|
||||
{registerEntry && <RegisterEntry />}
|
||||
{!registerEntry && masUrl && <MasAccountNotice url={masUrl} />}
|
||||
{!registerEntry && !masUrl && (
|
||||
<Text align="Center">
|
||||
Do not have an account? <Link to={getRegisterPath(server)}>Register</Link>
|
||||
</Text>
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import {
|
|||
} from '../../afterLoginRedirectPath';
|
||||
import { getHomePath } from '../../pathUtils';
|
||||
import { setFallbackSession } from '../../../state/sessions';
|
||||
import { clearSoftLogout, decideLoginOutcome, getSoftLogout } from '../../../state/softLogout';
|
||||
import { settleLocalData } from '../../../state/softLogout';
|
||||
import { wipeLocalData } from '../../../../client/initMatrix';
|
||||
|
||||
export enum GetBaseUrlError {
|
||||
|
|
@ -119,9 +119,7 @@ export const useLoginComplete = (data?: CustomLoginResponse) => {
|
|||
const finish = async () => {
|
||||
const afterLoginRedirectUrl = getAfterLoginRedirectPath();
|
||||
// A soft logout left stores behind; they stay only for the same user on the same device.
|
||||
const outcome = decideLoginOutcome(getSoftLogout(), loginRes);
|
||||
if (outcome === 'wipe') await wipeLocalData();
|
||||
clearSoftLogout();
|
||||
await settleLocalData(loginRes, () => wipeLocalData());
|
||||
setFallbackSession(loginRes.access_token, loginRes.device_id, loginRes.user_id, loginBaseUrl);
|
||||
deleteAfterLoginRedirectPath();
|
||||
navigate(afterLoginRedirectUrl ?? getHomePath(), { replace: true });
|
||||
|
|
|
|||
|
|
@ -41,12 +41,12 @@ describe('masAccountUrl', () => {
|
|||
const src = (p: string) => readFileSync(`${process.cwd()}/src/app/pages/auth/${p}`, 'utf8');
|
||||
|
||||
describe('MAS front guards', () => {
|
||||
it('Login hides both register entries behind the MAS predicate', () => {
|
||||
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('{masUrl && <MasAccountNotice');
|
||||
expect(s).toContain('{!masUrl && registrationEntry(config) && <RegisterEntry />}');
|
||||
expect(s).toContain('{!masUrl && !registrationEntry(config) && (');
|
||||
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');
|
||||
|
|
@ -66,9 +66,10 @@ describe('MAS front guards', () => {
|
|||
});
|
||||
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('classifyLogout(err)');
|
||||
expect(root).toContain('createLogoutHandler(');
|
||||
expect(root).toContain('wipeLocalData(mx)');
|
||||
expect(root).not.toContain('localStorage.clear');
|
||||
expect(src('login/loginUtil.ts')).toContain('wipeLocalData()');
|
||||
expect(src('login/loginUtil.ts')).toContain('settleLocalData(loginRes');
|
||||
expect(src('register/registerUtil.ts')).toContain('settleLocalData(');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,23 +1,9 @@
|
|||
import { useAutoDiscoveryInfo } from '../../hooks/useAutoDiscoveryInfo';
|
||||
import { isSecureOrLocalUrl } from '../../utils/secureUrl';
|
||||
import type { AutoDiscoveryInfo } from '../../cs-api';
|
||||
|
||||
// Plain http is for a developer's own machine only.
|
||||
const isLocalHost = (hostname: string): boolean =>
|
||||
hostname === 'localhost' ||
|
||||
hostname.endsWith('.localhost') ||
|
||||
hostname === '127.0.0.1' ||
|
||||
hostname === '[::1]';
|
||||
|
||||
const usable = (value: unknown): string | undefined => {
|
||||
if (typeof value !== 'string') return undefined;
|
||||
try {
|
||||
const { protocol, hostname } = new URL(value);
|
||||
if (protocol === 'https:' || (protocol === 'http:' && isLocalHost(hostname))) return value;
|
||||
} catch {
|
||||
// not a url
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const usable = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' && isSecureOrLocalUrl(value) ? value : undefined;
|
||||
|
||||
/**
|
||||
* The account page of the sign-in service fronting this homeserver (MAS), when discovery
|
||||
|
|
|
|||
|
|
@ -45,14 +45,19 @@ describe('the /register route', () => {
|
|||
).toContain('in-client register form');
|
||||
});
|
||||
|
||||
it('under MAS shows the account page notice, not the form, with the switch on or off', () => {
|
||||
[{}, { registration: { enabled: true, url: 'https://accounts.example/join' } }].forEach(
|
||||
(config) => {
|
||||
const html = render(config, mas);
|
||||
expect(html).toContain('href="https://auth.example/account"');
|
||||
expect(html).not.toContain('in-client register form');
|
||||
expect(html).not.toContain('Continue to sign up');
|
||||
}
|
||||
it('under MAS with no configured entry shows the account page notice, not the form', () => {
|
||||
const html = render({}, mas);
|
||||
expect(html).toContain('href="https://auth.example/account"');
|
||||
expect(html).not.toContain('in-client register form');
|
||||
});
|
||||
|
||||
it('under MAS a configured entry keeps its own page, not the notice or the form', () => {
|
||||
const html = render(
|
||||
{ registration: { enabled: true, url: 'https://accounts.example/join' } },
|
||||
mas
|
||||
);
|
||||
expect(html).toContain('href="https://accounts.example/join"');
|
||||
expect(html).not.toContain('auth.example/account');
|
||||
expect(html).not.toContain('in-client register form');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -13,10 +13,11 @@ export function RegisterRoute() {
|
|||
const entry = registrationEntry(useClientConfig());
|
||||
const masUrl = useMasAccountUrl();
|
||||
useEffect(() => {
|
||||
if (entry && !masUrl) window.location.replace(entry.url);
|
||||
}, [entry, masUrl]);
|
||||
// Under MAS the in-client sign-up (UIA) cannot work; the account page is the only way.
|
||||
if (masUrl) {
|
||||
if (entry) window.location.replace(entry.url);
|
||||
}, [entry]);
|
||||
// Under MAS the in-client sign-up (UIA) cannot work; with no configured entry the account page
|
||||
// is the only way. A configured entry keeps its own page and its training notice.
|
||||
if (!entry && masUrl) {
|
||||
return (
|
||||
<Box direction="Column" gap="300">
|
||||
<Text size="H2" priority="400">
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ import {
|
|||
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 type { RegisterTrouble } from '../authMessages';
|
||||
|
||||
export enum RegisterError {
|
||||
|
|
@ -141,10 +143,15 @@ export const useRegisterComplete = (data?: CustomRegisterResponse) => {
|
|||
const deviceId = response.device_id;
|
||||
|
||||
if (accessToken && deviceId) {
|
||||
setFallbackSession(accessToken, deviceId, userId, baseUrl);
|
||||
const afterLoginRedirectPath = getAfterLoginRedirectPath();
|
||||
deleteAfterLoginRedirectPath();
|
||||
navigate(afterLoginRedirectPath ?? getHomePath(), { replace: true });
|
||||
// A new account never boots on a soft-logged-out user's stores.
|
||||
settleLocalData({ user_id: userId, device_id: deviceId }, () => wipeLocalData()).then(
|
||||
() => {
|
||||
setFallbackSession(accessToken, deviceId, userId, baseUrl);
|
||||
deleteAfterLoginRedirectPath();
|
||||
navigate(afterLoginRedirectPath ?? getHomePath(), { replace: true });
|
||||
}
|
||||
);
|
||||
} else {
|
||||
const username = getMxIdLocalPart(userId);
|
||||
const userServer = getMxIdServer(userId);
|
||||
|
|
|
|||
|
|
@ -1,15 +1,9 @@
|
|||
import type { ClientConfig } from '../../hooks/useClientConfig';
|
||||
import { isSecureOrLocalUrl } from '../../utils/secureUrl';
|
||||
import { TRAINING_NOTICE_VERSION, trainingNoticeText } from '../../utils/trainingNotice';
|
||||
|
||||
export type RegistrationEntry = { url: string; notice: string; noticeVersion: number };
|
||||
|
||||
// Plain http is for a developer's own machine only; a stranger's sign-up page is https.
|
||||
const isLocalHost = (hostname: string): boolean =>
|
||||
hostname === 'localhost' ||
|
||||
hostname.endsWith('.localhost') ||
|
||||
hostname === '127.0.0.1' ||
|
||||
hostname === '[::1]';
|
||||
|
||||
/**
|
||||
* The sign-up entry the sign-in page may show: the account service's registration page, when the
|
||||
* switch is on and the configured url is an https address (http only for localhost). Anything else is no entry. The
|
||||
|
|
@ -18,12 +12,7 @@ const isLocalHost = (hostname: string): boolean =>
|
|||
export const registrationEntry = (config: ClientConfig): RegistrationEntry | undefined => {
|
||||
const { enabled, url } = config.registration ?? {};
|
||||
if (enabled !== true || typeof url !== 'string') return undefined;
|
||||
try {
|
||||
const { protocol, hostname } = new URL(url);
|
||||
if (protocol !== 'https:' && !(protocol === 'http:' && isLocalHost(hostname))) return undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
if (!isSecureOrLocalUrl(url)) return undefined;
|
||||
return {
|
||||
url,
|
||||
notice: trainingNoticeText(config.previewDemo),
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ import { stopPropagation } from '../../utils/keyboard';
|
|||
import { SyncStatus } from './SyncStatus';
|
||||
import { AuthMetadataProvider } from '../../hooks/useAuthMetadata';
|
||||
import { getFallbackSession } from '../../state/sessions';
|
||||
import { beginSoftLogout, classifyLogout } from '../../state/softLogout';
|
||||
import { createLogoutHandler } from '../../state/softLogout';
|
||||
import { pushSessionToSW } from '../../../sw-session';
|
||||
import { AutoDiscovery } from './AutoDiscovery';
|
||||
import { PhoneHit } from '../../styles/PhoneHit.css';
|
||||
|
|
@ -130,17 +130,15 @@ function ClientRootOptions({ mx }: { mx?: MatrixClient }) {
|
|||
|
||||
const useLogoutListener = (mx?: MatrixClient) => {
|
||||
useEffect(() => {
|
||||
const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = async (err) => {
|
||||
mx?.stopClient();
|
||||
// Soft: the token is dead, the device is not. Keep the stores and ask for a sign-in.
|
||||
if (classifyLogout(err) === 'soft' && beginSoftLogout()) {
|
||||
pushSessionToSW();
|
||||
window.location.reload();
|
||||
return;
|
||||
const handleLogout: HttpApiEventHandlerMap[HttpApiEvent.SessionLoggedOut] = createLogoutHandler(
|
||||
{
|
||||
storage: window.localStorage,
|
||||
stop: () => mx?.stopClient(),
|
||||
wipe: () => wipeLocalData(mx),
|
||||
reload: () => window.location.reload(),
|
||||
forgetSessionInWorker: () => pushSessionToSW(),
|
||||
}
|
||||
await wipeLocalData(mx);
|
||||
window.location.reload();
|
||||
};
|
||||
);
|
||||
|
||||
mx?.on(HttpApiEvent.SessionLoggedOut, handleLogout);
|
||||
return () => {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ import {
|
|||
beginSoftLogout,
|
||||
classifyLogout,
|
||||
clearSoftLogout,
|
||||
createLogoutHandler,
|
||||
settleLocalData,
|
||||
decideLoginOutcome,
|
||||
getSoftLogout,
|
||||
setSoftLogout,
|
||||
|
|
@ -29,7 +31,7 @@ const memoryStorage = (): Storage => {
|
|||
};
|
||||
};
|
||||
|
||||
const record = { userId: '@a:hs', deviceId: 'DEV', baseUrl: 'https://hs.example' };
|
||||
const record = { userId: '@a:hs', deviceId: 'DEV' };
|
||||
|
||||
describe('classifyLogout', () => {
|
||||
it('is soft only for soft_logout === true', () => {
|
||||
|
|
@ -118,3 +120,95 @@ describe('decideLoginOutcome', () => {
|
|||
expect(decideLoginOutcome(record, { user_id: '@a:hs', device_id: 'NEW' })).toBe('wipe');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the logout handler', () => {
|
||||
const rig = (soft: boolean) => {
|
||||
const storage = memoryStorage();
|
||||
storage.setItem('cinny_access_token', 'tok');
|
||||
storage.setItem('cinny_device_id', 'DEV');
|
||||
storage.setItem('cinny_user_id', '@a:hs');
|
||||
storage.setItem('cinny_hs_base_url', 'https://hs.example');
|
||||
const calls = { stop: 0, wipe: 0, reload: 0, worker: 0 };
|
||||
const handler = createLogoutHandler({
|
||||
storage,
|
||||
stop: () => {
|
||||
calls.stop += 1;
|
||||
},
|
||||
wipe: async () => {
|
||||
calls.wipe += 1;
|
||||
},
|
||||
reload: () => {
|
||||
calls.reload += 1;
|
||||
},
|
||||
forgetSessionInWorker: () => {
|
||||
calls.worker += 1;
|
||||
},
|
||||
});
|
||||
const err = { data: { soft_logout: soft } };
|
||||
return { storage, calls, handler, err };
|
||||
};
|
||||
|
||||
it('soft twice: one begin, no wipe, record kept', async () => {
|
||||
const { storage, calls, handler, err } = rig(true);
|
||||
await handler(err);
|
||||
await handler(err);
|
||||
expect(calls).toEqual({ stop: 1, wipe: 0, reload: 1, worker: 1 });
|
||||
expect(getSoftLogout(storage)).toEqual(record);
|
||||
expect(storage.getItem('cinny_device_id')).toBe('DEV');
|
||||
});
|
||||
it('soft then hard: the later event does not wipe', async () => {
|
||||
const { calls, handler } = rig(true);
|
||||
await handler({ data: { soft_logout: true } });
|
||||
await handler({ data: {} });
|
||||
expect(calls.wipe).toBe(0);
|
||||
});
|
||||
it('a record already standing swallows a fresh handler too', async () => {
|
||||
const { storage, calls, handler } = rig(false);
|
||||
setSoftLogout(record, storage);
|
||||
await handler({ data: {} });
|
||||
expect(calls).toEqual({ stop: 0, wipe: 0, reload: 0, worker: 0 });
|
||||
});
|
||||
it('hard twice: one wipe', async () => {
|
||||
const { calls, handler, err } = rig(false);
|
||||
await handler(err);
|
||||
await handler(err);
|
||||
expect(calls).toEqual({ stop: 1, wipe: 1, reload: 1, worker: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('settleLocalData', () => {
|
||||
const run = async (
|
||||
rec: typeof record | undefined,
|
||||
res: { user_id: string; device_id: string }
|
||||
) => {
|
||||
const s = memoryStorage();
|
||||
if (rec) setSoftLogout(rec, s);
|
||||
let wipes = 0;
|
||||
const outcome = await settleLocalData(
|
||||
res,
|
||||
async () => {
|
||||
wipes += 1;
|
||||
},
|
||||
s
|
||||
);
|
||||
return { outcome, wipes, left: getSoftLogout(s) };
|
||||
};
|
||||
it('same user and device: keep stores, retire the record', async () => {
|
||||
expect(await run(record, { user_id: '@a:hs', device_id: 'DEV' })).toEqual({
|
||||
outcome: 'keep',
|
||||
wipes: 0,
|
||||
left: undefined,
|
||||
});
|
||||
});
|
||||
it('another user or device (a new account too): wipe once, retire the record', async () => {
|
||||
expect(await run(record, { user_id: '@new:hs', device_id: 'X' })).toEqual({
|
||||
outcome: 'wipe',
|
||||
wipes: 1,
|
||||
left: undefined,
|
||||
});
|
||||
expect((await run(record, { user_id: '@a:hs', device_id: 'OTHER' })).wipes).toBe(1);
|
||||
});
|
||||
it('no record: plain, no wipe', async () => {
|
||||
expect((await run(undefined, { user_id: '@a:hs', device_id: 'D' })).wipes).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -10,23 +10,15 @@ const ACCESS_TOKEN_KEY = 'cinny_access_token';
|
|||
export type SoftLogoutRecord = {
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
baseUrl: string;
|
||||
};
|
||||
|
||||
export const getSoftLogout = (storage: Storage = localStorage): SoftLogoutRecord | undefined => {
|
||||
const raw = storage.getItem(SOFT_LOGOUT_KEY);
|
||||
if (!raw) return undefined;
|
||||
try {
|
||||
const { userId, deviceId, baseUrl } = JSON.parse(raw) as Partial<SoftLogoutRecord>;
|
||||
if (
|
||||
typeof userId === 'string' &&
|
||||
typeof deviceId === 'string' &&
|
||||
typeof baseUrl === 'string' &&
|
||||
userId &&
|
||||
deviceId &&
|
||||
baseUrl
|
||||
) {
|
||||
return { userId, deviceId, baseUrl };
|
||||
const { userId, deviceId } = JSON.parse(raw) as Partial<SoftLogoutRecord>;
|
||||
if (typeof userId === 'string' && typeof deviceId === 'string' && userId && deviceId) {
|
||||
return { userId, deviceId };
|
||||
}
|
||||
} catch {
|
||||
// an unreadable record is no record
|
||||
|
|
@ -57,10 +49,7 @@ export const classifyLogout = (err: unknown): LogoutKind => {
|
|||
export const beginSoftLogout = (storage: Storage = localStorage): boolean => {
|
||||
const session = getFallbackSession(storage);
|
||||
if (!session) return false;
|
||||
setSoftLogout(
|
||||
{ userId: session.userId, deviceId: session.deviceId, baseUrl: session.baseUrl },
|
||||
storage
|
||||
);
|
||||
setSoftLogout({ userId: session.userId, deviceId: session.deviceId }, storage);
|
||||
storage.removeItem(ACCESS_TOKEN_KEY);
|
||||
return true;
|
||||
};
|
||||
|
|
@ -89,3 +78,47 @@ export const decideLoginOutcome = (
|
|||
};
|
||||
|
||||
export const useSoftLogout = (): SoftLogoutRecord | undefined => useState(() => getSoftLogout())[0];
|
||||
|
||||
export type LogoutHandlerPorts = {
|
||||
storage: Storage;
|
||||
stop: () => void;
|
||||
wipe: () => Promise<void>;
|
||||
reload: () => void;
|
||||
forgetSessionInWorker: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The SessionLoggedOut handler. The SDK emits once per failing request and in-flight requests
|
||||
* outlive stopClient, so the first event decides and every later one is ignored: a second soft
|
||||
* event must never find the token already gone and fall into the wipe.
|
||||
*/
|
||||
export const createLogoutHandler = (ports: LogoutHandlerPorts) => {
|
||||
let fired = false;
|
||||
return async (err: unknown): Promise<void> => {
|
||||
if (fired || getSoftLogout(ports.storage)) return;
|
||||
fired = true;
|
||||
ports.stop();
|
||||
if (classifyLogout(err) === 'soft') {
|
||||
if (beginSoftLogout(ports.storage)) ports.forgetSessionInWorker();
|
||||
ports.reload();
|
||||
return;
|
||||
}
|
||||
await ports.wipe();
|
||||
ports.reload();
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Settle local data when a login or registration hands back a session: wipe first when a soft
|
||||
* logout left stores that belong to someone else, then retire the record.
|
||||
*/
|
||||
export const settleLocalData = async (
|
||||
response: { user_id: string; device_id: string },
|
||||
wipe: () => Promise<void>,
|
||||
storage: Storage = localStorage
|
||||
): Promise<LoginOutcome> => {
|
||||
const outcome = decideLoginOutcome(getSoftLogout(storage), response);
|
||||
if (outcome === 'wipe') await wipe();
|
||||
clearSoftLogout(storage);
|
||||
return outcome;
|
||||
};
|
||||
|
|
|
|||
16
src/app/utils/secureUrl.ts
Normal file
16
src/app/utils/secureUrl.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
// Plain http is for a developer's own machine only; a stranger's page is https.
|
||||
const isLocalHost = (hostname: string): boolean =>
|
||||
hostname === 'localhost' ||
|
||||
hostname.endsWith('.localhost') ||
|
||||
hostname === '127.0.0.1' ||
|
||||
hostname === '[::1]';
|
||||
|
||||
/** True for an https url, or an http url on localhost. Anything else, including non-urls, is false. */
|
||||
export const isSecureOrLocalUrl = (value: string): boolean => {
|
||||
try {
|
||||
const { protocol, hostname } = new URL(value);
|
||||
return protocol === 'https:' || (protocol === 'http:' && isLocalHost(hostname));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
Loading…
Reference in a new issue