Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
32.9 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import {
	hasStoredAccount,
	hasUsableStoredAccount,
	loadDomainMigrationDiscovery,
	readActiveSessionToken,
	readDomainMigrationDiscovery,
	readDomainMigrationEnvironment,
	readDomainMigrationGateInput,
	startDomainMigrationFromSource,
} from '@app/features/app/domain_migration/DomainMigrationBrowser';
import {
	anonymousRolloutIsOpen,
	buildTargetUrl,
	clearDomainMigrationIntent,
	collectExportableLocalStorage,
	DOMAIN_MIGRATION_CUSTOM_SOUNDS_MAX_BYTES,
	DOMAIN_MIGRATION_DEFAULT_NEXT_PATH,
	DOMAIN_MIGRATION_DEVICE_KEY,
	DOMAIN_MIGRATION_MARKER_KEY,
	DOMAIN_MIGRATION_MAX_FAILED_ATTEMPTS,
	DOMAIN_MIGRATION_NOTIFICATIONS_KEY,
	DOMAIN_MIGRATION_PAYLOAD_VERSION,
	DOMAIN_MIGRATION_PENDING_KEY,
	DOMAIN_MIGRATION_PENDING_MAX_AGE_MS,
	DOMAIN_MIGRATION_THEME_ASSETS_MAX_BYTES,
	type DomainMigrationCustomSound,
	type DomainMigrationMediaDevice,
	type DomainMigrationPayload,
	type DomainMigrationSide,
	type DomainMigrationThemeLibrary,
	deviceIsInAnonymousRollout,
	environmentAllowsDomainMigration,
	environmentMayForward,
	importIsRunning,
	intentConfirmsCompletion,
	isCompletedDomainMigrationMarker,
	isDomainMigrationOneShotRoute,
	isExportableLocalStorageKey,
	isForwardableOneShotRoute,
	keepValidTargetSession,
	markDomainMigrationCompleted,
	markDomainMigrationFailed,
	markDomainMigrationHandedOff,
	parseDomainMigrationMarker,
	parseDomainMigrationPayload,
	readDomainMigrationEnrollment,
	readDomainMigrationImport,
	readDomainMigrationIntent,
	readDomainMigrationMarker,
	resolveDomainMigrationSide,
	type StorageLike,
	sanitizeNextPath,
	shouldForwardCompletedSource,
	shouldStartDomainMigration,
	withoutOptionalPayloadData,
	writeDomainMigrationDeviceMap,
	writeDomainMigrationImport,
	writeDomainMigrationIntent,
} from '@app/features/app/domain_migration/DomainMigrationCore';
import {
	base64UrlToBytes,
	bytesToBase64Url,
	decryptDomainMigrationPayload,
	encryptDomainMigrationPayload,
	randomBase64Url,
	sha256Hex,
} from '@app/features/app/domain_migration/DomainMigrationCrypto';
import {runtimeInstanceKey} from '@app/features/app/state/InstanceSnapshotStore';
import type {RuntimeConfigSnapshot} from '@app/features/app/state/RuntimeConfig';
import {parseAccountStorageKey} from '@app/features/auth/state/AccountStorageKey';
import type {SoundType} from '@app/features/notification/utils/SoundUtils';
import {
	AuthSessionStorageKey,
	parseStoredSessionValue,
	readStoredActiveAccountKey,
	readStoredSessionUserId,
} from '@app/features/platform/state/auth_session/AuthSessionStorage';
import {getProtectedLocalStorage, getProtectedSessionStorage} from '@app/features/platform/state/ProtectedWebStorage';
import {Logger} from '@app/features/platform/utils/AppLogger';
import type {
	ThemeLibraryAsset,
	ThemeLibraryLocalFileReference,
	ThemeLibraryTheme,
} from '@app/features/theme/state/ThemeLibrary';
import {when} from 'mobx';

const logger = new Logger('DomainMigration');

const NONCE_BYTES = 32;
const DEVICE_ID_BYTES = 16;
const BASE64URL_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/u;
const MAX_HANDOFF_PAYLOAD_LENGTH = 8 * 1024 * 1024;
const IMPORT_WAIT_MS = 20_000;
const IMPORT_POLL_MS = 250;
const MEDIA_DEVICES_WAIT_MS = 1500;
const REDEEM_RETRY_MAX_WAIT_MS = 60_000;
const UNLOAD_GRACE_MS = 250;
const MIGRATE_DISCOVERY_TIMEOUTS_MS: ReadonlyArray<number> = [5000, 15_000];

type DomainMigrationLanding = 'target' | 'source';

type DomainMigrationFailureReason =
	| 'disabled'
	| 'no_pending'
	| 'missing_handoff'
	| 'handoff_expired'
	| 'nonce_mismatch'
	| 'redeem_failed'
	| 'invalid_payload'
	| 'import_failed'
	| 'target_error';

class DomainMigrationImportError extends Error {
	constructor(readonly reason: DomainMigrationFailureReason) {
		super(`Domain migration import failed: ${reason}`);
		this.name = 'DomainMigrationImportError';
	}
}

interface PendingHandoff {
	nonce: string;
	next: string;
	at: number;
	handoff?: string;
	key?: string;
	land?: string;
	redeeming?: boolean;
	sealed?: string;
}

function navigate(url: string): true {
	window.location.replace(url);
	return true;
}

async function outliveUnload(): Promise<void> {
	await new Promise((resolve) => setTimeout(resolve, UNLOAD_GRACE_MS));
}

function mountInPlace(next: string): false {
	window.history.replaceState(null, '', next);
	return false;
}

function readCurrentPath(): {pathname: string; search: string; hash: string} {
	return {pathname: window.location.pathname, search: window.location.search, hash: window.location.hash};
}

async function currentInstanceSnapshot(): Promise<RuntimeConfigSnapshot> {
	const {default: RuntimeConfig} = await import('@app/features/app/state/RuntimeConfig');
	const active = RuntimeConfig.getSnapshotOrNull();
	if (active !== null) {
		return active;
	}
	const resolution = await RuntimeConfig.resolveEndpoint({input: window.location.origin, signal: null});
	return resolution.snapshot;
}

function readNotificationPermission(): string {
	return typeof Notification === 'undefined' ? 'unsupported' : Notification.permission;
}

function readOrCreateDeviceId(): string {
	const storage = getProtectedLocalStorage();
	const existing = storage?.getItem(DOMAIN_MIGRATION_DEVICE_KEY);
	if (existing) {
		return existing;
	}
	const deviceId = randomBase64Url(DEVICE_ID_BYTES);
	try {
		storage?.setItem(DOMAIN_MIGRATION_DEVICE_KEY, deviceId);
	} catch {}
	return deviceId;
}

async function collectCustomSounds(): Promise<Array<DomainMigrationCustomSound> | undefined> {
	try {
		const {getAllCustomSounds} = await import('@app/features/notification/utils/CustomSoundDB');
		const sounds = await getAllCustomSounds();
		const totalBytes = sounds.reduce((sum, sound) => sum + sound.blob.size, 0);
		if (totalBytes > DOMAIN_MIGRATION_CUSTOM_SOUNDS_MAX_BYTES) {
			return undefined;
		}
		return await Promise.all(
			sounds.map(async (sound) => ({
				sound_type: sound.soundType,
				file_name: sound.fileName,
				mime_type: sound.blob.type,
				data: bytesToBase64Url(new Uint8Array(await sound.blob.arrayBuffer())),
			})),
		);
	} catch (err) {
		logger.warn('Skipping custom sounds in the domain migration export:', err);
		return undefined;
	}
}

async function restoreCustomSounds(sounds: ReadonlyArray<DomainMigrationCustomSound> | undefined): Promise<void> {
	if (!sounds || sounds.length === 0) {
		return;
	}
	const {saveCustomSound} = await import('@app/features/notification/utils/CustomSoundDB');
	for (const sound of sounds) {
		try {
			const blob = new Blob([base64UrlToBytes(sound.data)], {type: sound.mime_type});
			await saveCustomSound(sound.sound_type as SoundType, blob, sound.file_name);
		} catch (err) {
			logger.warn(`Failed to restore custom sound ${sound.sound_type}:`, err);
		}
	}
}

async function collectMediaDevices(): Promise<Array<DomainMigrationMediaDevice> | undefined> {
	try {
		const devices = await Promise.race([
			navigator.mediaDevices?.enumerateDevices?.() ?? Promise.resolve([]),
			new Promise<Array<MediaDeviceInfo>>((resolve) => setTimeout(() => resolve([]), MEDIA_DEVICES_WAIT_MS)),
		]);
		const labelled = devices.flatMap((device): Array<DomainMigrationMediaDevice> => {
			const deviceId = device.deviceId.trim();
			const label = device.label.trim();
			if (!deviceId || !label || deviceId === 'default' || deviceId === 'communications') {
				return [];
			}
			return [{kind: device.kind, device_id: deviceId, label}];
		});
		return labelled.length > 0 ? labelled : undefined;
	} catch (err) {
		logger.warn('Skipping media devices in the domain migration export:', err);
		return undefined;
	}
}

async function collectThemeLibrary(): Promise<DomainMigrationThemeLibrary | undefined> {
	try {
		const db = await import('@app/features/theme/utils/ThemeLibraryDb');
		const [themes, assets, localFiles, enabledThemeIds] = await Promise.all([
			db.listThemeLibraryThemes(),
			db.listThemeLibraryAssets(),
			db.listThemeLibraryLocalFiles(),
			db.getEnabledThemeIds(),
		]);
		const assetBytes = assets.reduce((sum, asset) => sum + (asset.data?.size ?? 0), 0);
		const portableAssets = assetBytes > DOMAIN_MIGRATION_THEME_ASSETS_MAX_BYTES ? [] : assets;
		return {
			themes: themes.map((theme) => ({...theme})),
			assets: await Promise.all(
				portableAssets.map(async (asset) => ({
					id: asset.id,
					name: asset.name,
					mime_type: asset.mimeType,
					size: asset.size,
					data: asset.data ? bytesToBase64Url(new Uint8Array(await asset.data.arrayBuffer())) : undefined,
					desktop_path: asset.desktopPath,
					created_at: asset.createdAt,
					updated_at: asset.updatedAt,
				})),
			),
			local_files: localFiles.map((file) => ({...file})),
			enabled_theme_ids: enabledThemeIds,
		};
	} catch (err) {
		logger.warn('Skipping the theme library in the domain migration export:', err);
		return undefined;
	}
}

async function restoreThemeLibrary(library: DomainMigrationThemeLibrary | undefined): Promise<void> {
	if (!library) {
		return;
	}
	try {
		const db = await import('@app/features/theme/utils/ThemeLibraryDb');
		for (const theme of library.themes) {
			await db.saveThemeLibraryTheme(theme as unknown as ThemeLibraryTheme);
		}
		for (const asset of library.assets) {
			const restored: ThemeLibraryAsset = {
				id: asset.id,
				name: asset.name,
				mimeType: asset.mime_type,
				size: asset.size,
				data: asset.data === undefined ? undefined : new Blob([base64UrlToBytes(asset.data)], {type: asset.mime_type}),
				desktopPath: asset.desktop_path,
				createdAt: asset.created_at,
				updatedAt: asset.updated_at,
			};
			await db.saveThemeLibraryAsset(restored);
		}
		for (const file of library.local_files) {
			await db.saveThemeLibraryLocalFile(file as unknown as ThemeLibraryLocalFileReference);
		}
		if (library.enabled_theme_ids.length > 0) {
			await db.setEnabledThemeIds(library.enabled_theme_ids);
		}
	} catch (err) {
		logger.warn('Failed to restore the theme library:', err);
	}
}

async function createHandoff(apiEndpoint: string, token: string, nonceHash: string, payload: string): Promise<string> {
	const response = await fetch(`${apiEndpoint}/v1/auth/origin-handoff`, {
		method: 'POST',
		credentials: 'omit',
		headers: {'Content-Type': 'application/json', Authorization: token},
		body: JSON.stringify({nonce_hash: nonceHash, payload}),
	});
	if (!response.ok) {
		throw new Error(`Origin handoff was rejected with status ${response.status}`);
	}
	const body = (await response.json()) as {handoff_id?: unknown};
	if (typeof body.handoff_id !== 'string' || !BASE64URL_TOKEN_PATTERN.test(body.handoff_id)) {
		throw new Error('Origin handoff response is malformed');
	}
	return body.handoff_id;
}

async function rateLimitRetryMs(response: Response): Promise<number | null> {
	try {
		const body = (await response.json()) as {retry_after?: unknown};
		return typeof body.retry_after === 'number' && body.retry_after >= 0 ? Math.ceil(body.retry_after * 1000) : null;
	} catch {
		return null;
	}
}

async function postRedeem(target: string, handoffId: string, nonce: string): Promise<Response> {
	const deadline = Date.now() + REDEEM_RETRY_MAX_WAIT_MS;
	for (;;) {
		let response: Response;
		try {
			response = await fetch(`${target}/api/v1/auth/origin-handoff/redeem`, {
				method: 'POST',
				credentials: 'omit',
				headers: {'Content-Type': 'application/json'},
				body: JSON.stringify({handoff_id: handoffId, nonce}),
			});
		} catch {
			throw new DomainMigrationImportError('redeem_failed');
		}
		if (response.status !== 429) {
			return response;
		}
		const waitMs = await rateLimitRetryMs(response);
		if (waitMs === null || Date.now() + waitMs > deadline) {
			return response;
		}
		logger.warn(`Origin handoff redeem was rate limited, retrying in ${waitMs}ms`);
		await new Promise((resolve) => setTimeout(resolve, waitMs));
	}
}

async function redeemHandoff(target: string, handoffId: string, nonce: string): Promise<string> {
	const response = await postRedeem(target, handoffId, nonce);
	if (response.status === 404) {
		throw new DomainMigrationImportError('handoff_expired');
	}
	if (response.status === 400) {
		throw new DomainMigrationImportError('nonce_mismatch');
	}
	if (!response.ok) {
		throw new DomainMigrationImportError('redeem_failed');
	}
	const body = (await response.json()) as {payload?: unknown};
	if (typeof body.payload !== 'string') {
		throw new DomainMigrationImportError('redeem_failed');
	}
	return body.payload;
}

function sourceUrl(side: DomainMigrationSide, next: unknown): string {
	return `${side.source}${sanitizeNextPath(next)}`;
}

function discoveryAllowsMigration(): boolean {
	return (
		readDomainMigrationDiscovery()?.enabled === true &&
		environmentAllowsDomainMigration(readDomainMigrationEnvironment())
	);
}

function revokeCompletedMarker(storage: StorageLike | null): void {
	if (isCompletedDomainMigrationMarker(readDomainMigrationMarker(storage))) {
		markDomainMigrationFailed(storage, Date.now());
	}
}

async function exportFromSource(side: DomainMigrationSide, nonce: string | null): Promise<boolean> {
	const storage = getProtectedLocalStorage();
	const sessionStorage = getProtectedSessionStorage();
	const intent = readDomainMigrationIntent(sessionStorage, Date.now());
	if (intent === null || (intent.handoff_id !== undefined && intent.nonce !== nonce)) {
		clearDomainMigrationIntent(sessionStorage);
		return navigate(sourceUrl(side, DOMAIN_MIGRATION_DEFAULT_NEXT_PATH));
	}
	try {
		if (nonce === null || !BASE64URL_TOKEN_PATTERN.test(nonce)) {
			throw new Error('Missing or malformed nonce');
		}
		const previous = readDomainMigrationMarker(storage);
		const attempts = previous?.state === 'handed-off' ? previous.attempts + 1 : Math.max(previous?.attempts ?? 0, 1);
		if (attempts > DOMAIN_MIGRATION_MAX_FAILED_ATTEMPTS) {
			throw new Error('Too many domain migration attempts');
		}
		const [{default: accountStorage}, {runtimeConfigSnapshotsAreSameInstance}, instance] = await Promise.all([
			import('@app/features/auth/state/AccountStorage'),
			import('@app/features/app/state/RuntimeConfig'),
			currentInstanceSnapshot(),
		]);
		const accounts = (await accountStorage.getAllAccounts()).records.filter(
			(account) => Boolean(account.token) && runtimeConfigSnapshotsAreSameInstance(account.instance, instance),
		);
		const token = readActiveSessionToken() ?? accounts.find((account) => account.isValid !== false)?.token ?? null;
		if (!token) {
			throw new Error('No stored account to export');
		}
		const [{collectExportableAppStorage}, {getPersistentStorageBackend}] = await Promise.all([
			import('@app/features/app/domain_migration/DomainMigrationAppStorage'),
			import('@app/features/platform/state/PersistentStorageBackend'),
		]);
		const storedState = await collectExportableAppStorage(
			getPersistentStorageBackend(),
			collectExportableLocalStorage(storage),
			accounts,
			storage ? readStoredSessionUserId(storage) : null,
		);
		const payload: DomainMigrationPayload = {
			version: DOMAIN_MIGRATION_PAYLOAD_VERSION,
			source_origin: side.source,
			exported_at: Date.now(),
			local_storage: storedState.local_storage,
			app_storage: storedState.app_storage,
			accounts,
			custom_sounds: await collectCustomSounds(),
			theme_library: await collectThemeLibrary(),
			media_devices: await collectMediaDevices(),
			notification_permission: readNotificationPermission(),
		};
		let sealed = await encryptDomainMigrationPayload(payload);
		if (sealed.payload.length > MAX_HANDOFF_PAYLOAD_LENGTH) {
			sealed = await encryptDomainMigrationPayload(withoutOptionalPayloadData(payload));
		}
		const handoffId = await createHandoff(instance.apiEndpoint, token, sha256Hex(nonce), sealed.payload);
		writeDomainMigrationIntent(sessionStorage, {at: intent.at, handoff_id: handoffId, nonce});
		markDomainMigrationHandedOff(storage, side.target, Date.now(), attempts);
		const landing: DomainMigrationLanding = environmentMayForward(
			readDomainMigrationEnvironment(),
			readDomainMigrationDiscovery(),
		)
			? 'target'
			: 'source';
		return navigate(`${side.target}/migrate/complete#h=${handoffId}&k=${sealed.key}&land=${landing}`);
	} catch (err) {
		logger.warn('Domain migration export failed:', err);
		await outliveUnload();
		clearDomainMigrationIntent(sessionStorage);
		revokeCompletedMarker(storage);
		return navigate(sourceUrl(side, DOMAIN_MIGRATION_DEFAULT_NEXT_PATH));
	}
}

async function forwardCompletedSource(side: DomainMigrationSide): Promise<true> {
	const {pathname, search, hash} = readCurrentPath();
	if (!(await hasStoredAccount())) {
		return navigate(buildTargetUrl(side.target, pathname, search, hash));
	}
	writeDomainMigrationIntent(getProtectedSessionStorage(), {at: Date.now()});
	const next = sanitizeNextPath(`${pathname}${search}${hash}`);
	const imported = readDomainMigrationMarker(getProtectedLocalStorage())?.state === 'completed' ? '&imported=1' : '';
	return navigate(`${side.target}/migrate/begin?resume=1${imported}&next=${encodeURIComponent(next)}`);
}

async function startEnrolledSource(side: DomainMigrationSide): Promise<boolean> {
	if (
		!readDomainMigrationEnrollment(getProtectedLocalStorage()) ||
		!shouldStartDomainMigration(readDomainMigrationGateInput(true, false))
	) {
		return false;
	}
	if (!(await hasStoredAccount())) {
		return false;
	}
	return startDomainMigrationFromSource(side);
}

async function forwardFromSource(side: DomainMigrationSide): Promise<boolean> {
	const {pathname, search, hash} = readCurrentPath();
	const oneShotRoute = isDomainMigrationOneShotRoute(pathname);
	if (oneShotRoute && !isForwardableOneShotRoute(pathname)) {
		return false;
	}
	if (!oneShotRoute && (await startEnrolledSource(side))) {
		return true;
	}
	const environment = readDomainMigrationEnvironment();
	const discovery = readDomainMigrationDiscovery();
	if (!environmentMayForward(environment, discovery)) {
		return false;
	}
	if (shouldForwardCompletedSource(discovery, readDomainMigrationMarker(getProtectedLocalStorage()), environment)) {
		return forwardCompletedSource(side);
	}
	if (oneShotRoute) {
		return (await hasUsableStoredAccount()) ? false : navigate(buildTargetUrl(side.target, pathname, search, hash));
	}
	if (
		discovery !== null &&
		anonymousRolloutIsOpen(discovery) &&
		!(await hasStoredAccount()) &&
		deviceIsInAnonymousRollout(discovery, readOrCreateDeviceId())
	) {
		return navigate(buildTargetUrl(side.target, pathname, search, hash));
	}
	return false;
}

async function forwardWhenIdle(side: DomainMigrationSide): Promise<void> {
	const {default: MediaEngine} = await import('@app/features/voice/engine/MediaEngineFacade');
	await when(() => !MediaEngine.connected && !MediaEngine.connecting);
	if (
		isDomainMigrationOneShotRoute(window.location.pathname) ||
		!shouldForwardCompletedSource(
			readDomainMigrationDiscovery(),
			readDomainMigrationMarker(getProtectedLocalStorage()),
			readDomainMigrationEnvironment(),
		)
	) {
		return;
	}
	await forwardCompletedSource(side);
}

function installSourceMarkerListener(side: DomainMigrationSide): void {
	let waiting = false;
	window.addEventListener('storage', (event) => {
		if (event.key !== DOMAIN_MIGRATION_MARKER_KEY || waiting) {
			return;
		}
		if (
			!shouldForwardCompletedSource(
				readDomainMigrationDiscovery(),
				parseDomainMigrationMarker(event.newValue),
				readDomainMigrationEnvironment(),
			)
		) {
			return;
		}
		waiting = true;
		forwardWhenIdle(side)
			.catch((err) => {
				logger.warn('Failed to forward a migrated source tab:', err);
			})
			.finally(() => {
				waiting = false;
			});
	});
}

function completeOnSource(side: DomainMigrationSide, params: URLSearchParams): boolean {
	const sessionStorage = getProtectedSessionStorage();
	const intent = readDomainMigrationIntent(sessionStorage, Date.now());
	clearDomainMigrationIntent(sessionStorage);
	if (!intentConfirmsCompletion(intent, params.get('h'))) {
		return navigate(sourceUrl(side, params.get('next')));
	}
	markDomainMigrationCompleted(getProtectedLocalStorage(), side.target, Date.now());
	if (!environmentMayForward(readDomainMigrationEnvironment(), readDomainMigrationDiscovery())) {
		return navigate(sourceUrl(side, params.get('next')));
	}
	return navigate(`${side.target}${sanitizeNextPath(params.get('next'))}`);
}

function startOnSource(side: DomainMigrationSide, params: URLSearchParams): boolean {
	writeDomainMigrationIntent(getProtectedSessionStorage(), {at: Date.now()});
	return navigate(`${side.target}/migrate/begin?next=${encodeURIComponent(sanitizeNextPath(params.get('next')))}`);
}

function failOnSource(side: DomainMigrationSide, params: URLSearchParams): boolean {
	const sessionStorage = getProtectedSessionStorage();
	const intent = readDomainMigrationIntent(sessionStorage, Date.now());
	clearDomainMigrationIntent(sessionStorage);
	if (intent !== null) {
		logger.warn(`Domain migration failed on ${side.target}: ${params.get('reason') ?? 'unknown'}`);
		revokeCompletedMarker(getProtectedLocalStorage());
	}
	return navigate(sourceUrl(side, params.get('next')));
}

async function handleSource(side: DomainMigrationSide): Promise<boolean> {
	const params = new URLSearchParams(window.location.search);
	const {pathname} = window.location;
	if (pathname.startsWith('/migrate/') && !discoveryAllowsMigration()) {
		clearDomainMigrationIntent(getProtectedSessionStorage());
		return navigate(sourceUrl(side, params.get('next')));
	}
	switch (pathname) {
		case '/migrate/export':
			return exportFromSource(side, params.get('n'));
		case '/migrate/start':
			return startOnSource(side, params);
		case '/migrate/done':
			return completeOnSource(side, params);
		case '/migrate/failed':
			return failOnSource(side, params);
	}
	if (await forwardFromSource(side)) {
		return true;
	}
	installSourceMarkerListener(side);
	return false;
}

function optionalString(value: unknown): string | undefined {
	return typeof value === 'string' ? value : undefined;
}

function readPendingHandoff(): PendingHandoff | null {
	try {
		const raw = getProtectedSessionStorage()?.getItem(DOMAIN_MIGRATION_PENDING_KEY) ?? null;
		if (!raw) {
			return null;
		}
		const value = JSON.parse(raw) as Partial<PendingHandoff>;
		if (typeof value.nonce !== 'string' || typeof value.next !== 'string' || typeof value.at !== 'number') {
			return null;
		}
		return {
			nonce: value.nonce,
			next: value.next,
			at: value.at,
			handoff: optionalString(value.handoff),
			key: optionalString(value.key),
			land: optionalString(value.land),
			redeeming: value.redeeming === true,
			sealed: optionalString(value.sealed),
		};
	} catch {
		return null;
	}
}

function writePendingHandoff(pending: PendingHandoff | null): void {
	const storage = getProtectedSessionStorage();
	try {
		if (pending === null) {
			storage?.removeItem(DOMAIN_MIGRATION_PENDING_KEY);
		} else {
			storage?.setItem(DOMAIN_MIGRATION_PENDING_KEY, JSON.stringify(pending));
		}
	} catch {}
}

async function importHandoff(side: DomainMigrationSide, pending: PendingHandoff): Promise<void> {
	const {handoff: handoffId, key} = pending;
	if (!handoffId || !key || !BASE64URL_TOKEN_PATTERN.test(handoffId)) {
		throw new DomainMigrationImportError('missing_handoff');
	}
	let sealed = pending.sealed;
	if (sealed === undefined) {
		writePendingHandoff({...pending, redeeming: true});
		sealed = await redeemHandoff(side.target, handoffId, pending.nonce);
		writePendingHandoff({...pending, redeeming: true, sealed});
	}
	let payload: DomainMigrationPayload | null;
	try {
		payload = parseDomainMigrationPayload(await decryptDomainMigrationPayload(sealed, key), side.source);
	} catch {
		payload = null;
	}
	if (payload === null) {
		throw new DomainMigrationImportError('invalid_payload');
	}
	const storage = getProtectedLocalStorage();
	const previousImport = readDomainMigrationImport(storage);
	writeDomainMigrationImport(storage, {state: 'running', at: Date.now()});
	const [appStorage, {getPersistentStorageBackend}] = await Promise.all([
		import('@app/features/app/domain_migration/DomainMigrationAppStorage'),
		import('@app/features/platform/state/PersistentStorageBackend'),
	]);
	let instance: RuntimeConfigSnapshot;
	try {
		const [{default: accountStorage}, {runtimeConfigSnapshotsAreSameInstance}, snapshot] = await Promise.all([
			import('@app/features/auth/state/AccountStorage'),
			import('@app/features/app/state/RuntimeConfig'),
			currentInstanceSnapshot(),
		]);
		instance = snapshot;
		const activeToken = readActiveSessionToken();
		const activeUserId = storage ? readStoredSessionUserId(storage) : null;
		const incomingToken = parseStoredSessionValue(payload.local_storage[AuthSessionStorageKey.Token] ?? null);
		const incomingUserId = parseStoredSessionValue(payload.local_storage[AuthSessionStorageKey.UserId] ?? null);
		const existing = new Map(
			(await accountStorage.getAllAccounts()).records
				.filter((account) => runtimeConfigSnapshotsAreSameInstance(account.instance, instance))
				.map((account) => [account.userId, account]),
		);
		await accountStorage.importAccounts(
			payload.accounts.map((account) =>
				keepValidTargetSession(appStorage.rewriteImportedAccount(account, instance), existing.get(account.userId)),
			),
		);
		if (activeToken !== null && activeUserId !== null && incomingToken !== null && incomingUserId !== activeUserId) {
			await accountStorage.stashAccountData(activeUserId, activeToken, undefined, instance).catch((err: unknown) => {
				logger.warn('Failed to keep the replaced target session:', err);
			});
		}
	} catch (err) {
		writeDomainMigrationImport(storage, previousImport);
		logger.warn('Failed to import migrated accounts:', err);
		throw new DomainMigrationImportError('import_failed');
	}
	for (const [storageKey, value] of Object.entries(payload.local_storage)) {
		if (!isExportableLocalStorageKey(storageKey)) {
			continue;
		}
		try {
			storage?.setItem(storageKey, value);
		} catch (err) {
			logger.warn(`Failed to import localStorage key ${storageKey}:`, err);
		}
	}
	if (payload.app_storage) {
		try {
			await appStorage.writeImportedAppStorage(
				getPersistentStorageBackend(),
				payload.app_storage,
				payload.accounts,
				instance,
			);
		} catch (err) {
			logger.warn('Failed to import scoped app storage:', err);
		}
	}
	try {
		await appStorage.retargetAccountKeys(
			getPersistentStorageBackend(),
			storage,
			appStorage.importedAccountKeyMoves(payload.accounts, instance),
		);
	} catch (err) {
		logger.warn('Failed to point imported state at the new account keys:', err);
	}
	if (payload.media_devices) {
		writeDomainMigrationDeviceMap(storage, {at: Date.now(), devices: payload.media_devices, resolved: []});
	}
	if (payload.notification_permission === 'granted') {
		try {
			storage?.setItem(DOMAIN_MIGRATION_NOTIFICATIONS_KEY, 'granted');
		} catch {}
	}
	writeDomainMigrationImport(storage, {state: 'done', at: Date.now()});
	await restoreCustomSounds(payload.custom_sounds);
	await restoreThemeLibrary(payload.theme_library);
}

function doneUrl(side: DomainMigrationSide, next: string, handoffId: string | null): string {
	const handoff = handoffId === null ? '' : `h=${encodeURIComponent(handoffId)}&`;
	return `${side.source}/migrate/done?${handoff}next=${encodeURIComponent(next)}`;
}

function landOnTarget(
	side: DomainMigrationSide,
	land: string | undefined,
	handoffId: string | null,
	next: string,
): boolean {
	switch (land) {
		case 'target':
			return mountInPlace(next);
		case 'source':
			return navigate(sourceUrl(side, next));
	}
	return navigate(doneUrl(side, next, handoffId));
}

function failedUrl(side: DomainMigrationSide, reason: DomainMigrationFailureReason, next: string): string {
	return `${side.source}/migrate/failed?reason=${reason}&next=${encodeURIComponent(next)}`;
}

async function waitForRunningImport(): Promise<void> {
	const deadline = Date.now() + IMPORT_WAIT_MS;
	while (importIsRunning(readDomainMigrationImport(getProtectedLocalStorage()), Date.now()) && Date.now() < deadline) {
		await new Promise((resolve) => setTimeout(resolve, IMPORT_POLL_MS));
	}
}

async function beginOnTarget(side: DomainMigrationSide, params: URLSearchParams): Promise<boolean> {
	const next = sanitizeNextPath(params.get('next'));
	if (readDomainMigrationDiscovery()?.enabled !== true) {
		return navigate(failedUrl(side, 'disabled', next));
	}
	const storage = getProtectedLocalStorage();
	const started = params.get('start') === '1';
	const resumed = params.get('resume') === '1';
	if (resumed) {
		await waitForRunningImport();
	}
	const imported = readDomainMigrationImport(storage)?.state === 'done' || (resumed && params.get('imported') === '1');
	if ((resumed || started) && (imported || (started && (await hasStoredAccount())))) {
		return mountInPlace(next);
	}
	if (started) {
		return navigate(`${side.source}/migrate/start?next=${encodeURIComponent(next)}`);
	}
	if (imported) {
		return navigate(doneUrl(side, next, null));
	}
	writeDomainMigrationImport(storage, {state: 'running', at: Date.now()});
	const nonce = randomBase64Url(NONCE_BYTES);
	const pending: PendingHandoff = {nonce, next, at: Date.now()};
	getProtectedSessionStorage()?.setItem(DOMAIN_MIGRATION_PENDING_KEY, JSON.stringify(pending));
	return navigate(`${side.source}/migrate/export?n=${nonce}`);
}

async function completeOnTarget(side: DomainMigrationSide): Promise<boolean> {
	const fragment = new URLSearchParams(window.location.hash.slice(1));
	window.history.replaceState(window.history.state, '', `${window.location.pathname}${window.location.search}`);
	const stored = readPendingHandoff();
	const lastImport = readDomainMigrationImport(getProtectedLocalStorage());
	if (stored === null || Date.now() - stored.at > DOMAIN_MIGRATION_PENDING_MAX_AGE_MS) {
		writePendingHandoff(null);
		if (lastImport?.state === 'done' && Date.now() - lastImport.at < DOMAIN_MIGRATION_PENDING_MAX_AGE_MS) {
			const land = fragment.get('land') === 'source' ? 'source' : 'target';
			return landOnTarget(side, land, null, DOMAIN_MIGRATION_DEFAULT_NEXT_PATH);
		}
		return navigate(failedUrl(side, 'no_pending', DOMAIN_MIGRATION_DEFAULT_NEXT_PATH));
	}
	const pending: PendingHandoff = {
		...stored,
		handoff: fragment.get('h') ?? stored.handoff,
		key: fragment.get('k') ?? stored.key,
		land: fragment.get('land') ?? stored.land,
	};
	writePendingHandoff(pending);
	const next = sanitizeNextPath(pending.next);
	if (lastImport?.state === 'done' && lastImport.at >= pending.at) {
		writePendingHandoff(null);
		return landOnTarget(side, pending.land, pending.handoff ?? null, next);
	}
	try {
		await importHandoff(side, pending);
	} catch (err) {
		const reason = err instanceof DomainMigrationImportError ? err.reason : 'import_failed';
		logger.warn('Domain migration import failed:', err);
		await outliveUnload();
		writePendingHandoff(null);
		const storage = getProtectedLocalStorage();
		if (readDomainMigrationImport(storage)?.state === 'running') {
			writeDomainMigrationImport(storage, null);
		}
		if (reason === 'handoff_expired' && pending.redeeming === true) {
			return navigate(`${side.source}/migrate/start?next=${encodeURIComponent(next)}`);
		}
		return navigate(failedUrl(side, reason, next));
	}
	writePendingHandoff(null);
	return landOnTarget(side, pending.land, pending.handoff ?? null, next);
}

async function repairMovedAccounts(): Promise<void> {
	const storage = getProtectedLocalStorage();
	if (storage === null || readDomainMigrationImport(storage)?.state !== 'done') {
		return;
	}
	const instance = await currentInstanceSnapshot();
	const pointer = parseAccountStorageKey(readStoredActiveAccountKey(storage));
	if (pointer === null || pointer.instanceKey === runtimeInstanceKey(instance)) {
		return;
	}
	const [{default: accountStorage}, {retargetAccountKeys}, {getPersistentStorageBackend}] = await Promise.all([
		import('@app/features/auth/state/AccountStorage'),
		import('@app/features/app/domain_migration/DomainMigrationAppStorage'),
		import('@app/features/platform/state/PersistentStorageBackend'),
	]);
	const moves = await accountStorage.rekeyAccountsOnInstance(instance);
	await retargetAccountKeys(getPersistentStorageBackend(), storage, moves);
}

async function handleTarget(side: DomainMigrationSide): Promise<boolean> {
	if (window.location.pathname !== '/migrate/complete') {
		await repairMovedAccounts().catch((err: unknown) => {
			logger.warn('Failed to repair accounts moved by an earlier import:', err);
		});
	}
	switch (window.location.pathname) {
		case '/migrate/begin':
			return beginOnTarget(side, new URLSearchParams(window.location.search));
		case '/migrate/complete':
			return completeOnTarget(side);
	}
	return false;
}

async function loadDiscovery(): Promise<void> {
	const timeouts: ReadonlyArray<number | undefined> = window.location.pathname.startsWith('/migrate/')
		? MIGRATE_DISCOVERY_TIMEOUTS_MS
		: [undefined];
	for (const [index, timeoutMs] of timeouts.entries()) {
		try {
			await loadDomainMigrationDiscovery(timeoutMs);
			return;
		} catch (err) {
			logger.warn(`Domain migration discovery is unavailable (attempt ${index + 1} of ${timeouts.length}):`, err);
		}
	}
}

export async function runDomainMigrationPreMount(): Promise<boolean> {
	if (typeof window === 'undefined') {
		return false;
	}
	const side = resolveDomainMigrationSide(window.location.origin);
	if (side === null) {
		return false;
	}
	await loadDiscovery();
	try {
		return side.role === 'source' ? await handleSource(side) : await handleTarget(side);
	} catch (err) {
		logger.error('Domain migration pre-mount step failed:', err);
		if (side.role === 'target' && window.location.pathname.startsWith('/migrate/')) {
			return navigate(failedUrl(side, 'target_error', DOMAIN_MIGRATION_DEFAULT_NEXT_PATH));
		}
		return false;
	}
}