diff --git a/src/app/pages/auth/login/Login.tsx b/src/app/pages/auth/login/Login.tsx
index 05204779..3606a9a4 100644
--- a/src/app/pages/auth/login/Login.tsx
+++ b/src/app/pages/auth/login/Login.tsx
@@ -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() {
>
)}
- {masUrl && }
- {!masUrl && registrationEntry(config) && }
- {!masUrl && !registrationEntry(config) && (
+ {registerEntry && }
+ {!registerEntry && masUrl && }
+ {!registerEntry && !masUrl && (
Do not have an account? Register
diff --git a/src/app/pages/auth/login/loginUtil.ts b/src/app/pages/auth/login/loginUtil.ts
index f4124db7..7a9cfb38 100644
--- a/src/app/pages/auth/login/loginUtil.ts
+++ b/src/app/pages/auth/login/loginUtil.ts
@@ -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 });
diff --git a/src/app/pages/auth/masAccount.test.ts b/src/app/pages/auth/masAccount.test.ts
index c45497f3..f2331365 100644
--- a/src/app/pages/auth/masAccount.test.ts
+++ b/src/app/pages/auth/masAccount.test.ts
@@ -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 && }');
- expect(s).toContain('{!masUrl && !registrationEntry(config) && (');
+ expect(s).toContain('{registerEntry && }');
+ expect(s).toContain('{!registerEntry && masUrl && {
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(');
});
});
diff --git a/src/app/pages/auth/masAccount.ts b/src/app/pages/auth/masAccount.ts
index b131a916..6e65b2a4 100644
--- a/src/app/pages/auth/masAccount.ts
+++ b/src/app/pages/auth/masAccount.ts
@@ -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
diff --git a/src/app/pages/auth/register/RegisterRoute.test.tsx b/src/app/pages/auth/register/RegisterRoute.test.tsx
index 1fde64cd..47ea7179 100644
--- a/src/app/pages/auth/register/RegisterRoute.test.tsx
+++ b/src/app/pages/auth/register/RegisterRoute.test.tsx
@@ -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');
});
});
diff --git a/src/app/pages/auth/register/RegisterRoute.tsx b/src/app/pages/auth/register/RegisterRoute.tsx
index fa56527a..ee68dd45 100644
--- a/src/app/pages/auth/register/RegisterRoute.tsx
+++ b/src/app/pages/auth/register/RegisterRoute.tsx
@@ -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 (
diff --git a/src/app/pages/auth/register/registerUtil.ts b/src/app/pages/auth/register/registerUtil.ts
index 02f530fb..9d5afa87 100644
--- a/src/app/pages/auth/register/registerUtil.ts
+++ b/src/app/pages/auth/register/registerUtil.ts
@@ -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);
diff --git a/src/app/pages/auth/registrationEntry.ts b/src/app/pages/auth/registrationEntry.ts
index 6c65732e..2aa0e34d 100644
--- a/src/app/pages/auth/registrationEntry.ts
+++ b/src/app/pages/auth/registrationEntry.ts
@@ -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),
diff --git a/src/app/pages/client/ClientRoot.tsx b/src/app/pages/client/ClientRoot.tsx
index dd63226a..2cb69ed5 100644
--- a/src/app/pages/client/ClientRoot.tsx
+++ b/src/app/pages/client/ClientRoot.tsx
@@ -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 () => {
diff --git a/src/app/state/softLogout.test.ts b/src/app/state/softLogout.test.ts
index e529288d..8df1a8f8 100644
--- a/src/app/state/softLogout.test.ts
+++ b/src/app/state/softLogout.test.ts
@@ -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);
+ });
+});
diff --git a/src/app/state/softLogout.ts b/src/app/state/softLogout.ts
index d7ea1180..645d0cc3 100644
--- a/src/app/state/softLogout.ts
+++ b/src/app/state/softLogout.ts
@@ -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;
- 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;
+ 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;
+ 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 => {
+ 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,
+ storage: Storage = localStorage
+): Promise => {
+ const outcome = decideLoginOutcome(getSoftLogout(storage), response);
+ if (outcome === 'wipe') await wipe();
+ clearSoftLogout(storage);
+ return outcome;
+};
diff --git a/src/app/utils/secureUrl.ts b/src/app/utils/secureUrl.ts
new file mode 100644
index 00000000..f1dacd9c
--- /dev/null
+++ b/src/app/utils/secureUrl.ts
@@ -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;
+ }
+};