mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 00:51:17 -08:00
fix(crypto): restore device verification from an unverified session
This commit is contained in:
10 files changed
+410
-56
No files matched your search
@@ -92,13 +92,23 @@ type VerificationStartProps = {
|
||||
onStart: () => Promise<void>;
|
||||
};
|
||||
function AutoVerificationStart({ onStart }: VerificationStartProps) {
|
||||
const [error, setError] = useState<Error>();
|
||||
|
||||
useEffect(() => {
|
||||
onStart().catch(() => undefined);
|
||||
onStart().catch((reason: unknown) => {
|
||||
const failure = reason instanceof Error ? reason : new Error(String(reason));
|
||||
Sentry.captureException(failure, { tags: { flow: 'device-verification-start' } });
|
||||
setError(failure);
|
||||
});
|
||||
}, [onStart]);
|
||||
|
||||
return (
|
||||
<Box direction="Column" gap="400">
|
||||
<WaitingMessage message="Starting verification using emoji comparison..." />
|
||||
{error ? (
|
||||
<Text size="T200">{error.message}</Text>
|
||||
) : (
|
||||
<WaitingMessage message="Asking your other devices to start emoji comparison..." />
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -719,21 +719,34 @@ export class EngineCrypto
|
||||
});
|
||||
}
|
||||
|
||||
async onIncomingKeyVerificationRequest(sender: string, transactionId: string): Promise<void> {
|
||||
async onIncomingKeyVerificationRequest(sender: string, transactionId: string): Promise<boolean> {
|
||||
const state = (await this.#call('getVerificationRequest', {
|
||||
userId: sender,
|
||||
flowId: transactionId,
|
||||
})) as EngineVerificationState | null;
|
||||
if (!state) return;
|
||||
if (!state) return false;
|
||||
|
||||
const existing = this.#verificationRequests.get(transactionId);
|
||||
if (existing) {
|
||||
existing.apply(state);
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
const request = new EngineVerificationRequest(this.#engineCall, state);
|
||||
this.#verificationRequests.set(transactionId, request);
|
||||
this.emit(CryptoEvent.VerificationRequestReceived, request);
|
||||
return true;
|
||||
}
|
||||
|
||||
async #retryVerificationRequestWithKeys(
|
||||
sender: string,
|
||||
transactionId: string,
|
||||
event: IToDeviceEvent
|
||||
): Promise<void> {
|
||||
await this.#trackUsers([sender]);
|
||||
await this.#sendTracked(await this.#call('queryKeysForUsers', { users: [sender] }));
|
||||
await this.#flushOutgoingRequests();
|
||||
await this.#receiveSyncChanges({ toDeviceEvents: [event] });
|
||||
await this.onIncomingKeyVerificationRequest(sender, transactionId);
|
||||
}
|
||||
|
||||
#flushOutgoingRequests(): Promise<void> {
|
||||
@@ -805,11 +818,20 @@ export class EngineCrypto
|
||||
if (transactionId && message.sender) {
|
||||
if (message.type === EventType.KeyVerificationRequest) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await this.onIncomingKeyVerificationRequest(message.sender, transactionId);
|
||||
const handled = await this.onIncomingKeyVerificationRequest(
|
||||
message.sender,
|
||||
transactionId
|
||||
);
|
||||
if (!handled) {
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await this.#retryVerificationRequestWithKeys(message.sender, transactionId, message);
|
||||
}
|
||||
} else if (message.type === EventType.KeyVerificationDone) {
|
||||
// Rust removes completed requests while consuming the event, so no state snapshot
|
||||
// exists to refresh. Keep the JS request alive long enough to expose Done.
|
||||
this.#verificationRequests.get(transactionId)?.markDone();
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
await this.#queryOwnKeys();
|
||||
} else {
|
||||
// Without this the verifier never learns the SAS digits arrived.
|
||||
// eslint-disable-next-line no-await-in-loop
|
||||
@@ -1562,6 +1584,22 @@ export class EngineCrypto
|
||||
await this.#flushOutgoingRequests();
|
||||
}
|
||||
|
||||
async #signOwnDeviceIfNeeded(): Promise<void> {
|
||||
const status = await this.getDeviceVerificationStatus(
|
||||
this.#identity.userId,
|
||||
this.#identity.deviceId
|
||||
);
|
||||
if (status?.crossSigningVerified) return;
|
||||
|
||||
const request = (await this.#call('device.verify', {
|
||||
userId: this.#identity.userId,
|
||||
deviceId: this.#identity.deviceId,
|
||||
})) as OutgoingRequest | null;
|
||||
if (!request) return;
|
||||
await sendOutgoingRequest(this.#mx, request);
|
||||
await this.#queryOwnKeys();
|
||||
}
|
||||
|
||||
async crossSignDevice(deviceId: string): Promise<void> {
|
||||
await this.#sendTracked(
|
||||
await this.#call('device.verify', { userId: this.#identity.userId, deviceId })
|
||||
@@ -1602,6 +1640,7 @@ export class EngineCrypto
|
||||
if (!stored && (await this.#mx.secretStorage.hasKey())) {
|
||||
await this.#exportCrossSigningKeysToStorage();
|
||||
}
|
||||
await this.#signOwnDeviceIfNeeded();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { CryptoEvent, EventType, type MatrixClient } from '$types/matrix-sdk';
|
||||
import { engineInvoke } from '../olmMachine/engineInvoke';
|
||||
import { EngineCrypto } from './EngineCrypto';
|
||||
|
||||
vi.mock('../olmMachine/engineInvoke', () => ({
|
||||
engineInvoke: vi.fn<(...args: never[]) => Promise<unknown>>(),
|
||||
}));
|
||||
|
||||
const mockInvoke = vi.mocked(engineInvoke);
|
||||
|
||||
const clientSpy = () => {
|
||||
const authedRequest = vi.fn<(...args: never[]) => Promise<string>>(async () => '{}');
|
||||
return { mx: { http: { authedRequest } } as unknown as MatrixClient, authedRequest };
|
||||
};
|
||||
|
||||
const REQUEST_EVENT = {
|
||||
type: EventType.KeyVerificationRequest,
|
||||
sender: '@me:e.org',
|
||||
content: { transaction_id: '$f', from_device: 'OTHER' },
|
||||
};
|
||||
|
||||
const requestState = {
|
||||
flowId: '$f',
|
||||
otherUserId: '@me:e.org',
|
||||
phase: 1,
|
||||
isSelfVerification: true,
|
||||
};
|
||||
|
||||
describe('incoming verification request', () => {
|
||||
beforeEach(() => mockInvoke.mockReset());
|
||||
|
||||
it('fetches the sender keys and replays the event when the device is unknown', async () => {
|
||||
const { mx } = clientSpy();
|
||||
let senderKnown = false;
|
||||
const invoked: string[] = [];
|
||||
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
invoked.push(method as string);
|
||||
if (method === 'receiveSyncChanges') {
|
||||
return [{ type: 3, rawEvent: JSON.stringify(REQUEST_EVENT) }];
|
||||
}
|
||||
if (method === 'queryKeysForUsers') {
|
||||
senderKnown = true;
|
||||
return { id: 'q1', type: 1, className: 'KeysQueryRequest', body: '{}' };
|
||||
}
|
||||
if (method === 'getVerificationRequest') return senderKnown ? requestState : null;
|
||||
return [];
|
||||
});
|
||||
|
||||
const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' });
|
||||
const received = vi.fn();
|
||||
crypto.on(CryptoEvent.VerificationRequestReceived, received);
|
||||
|
||||
await crypto.preprocessToDeviceMessages([REQUEST_EVENT as never]);
|
||||
|
||||
expect(invoked.filter((m) => m === 'queryKeysForUsers')).toHaveLength(1);
|
||||
expect(invoked.filter((m) => m === 'receiveSyncChanges')).toHaveLength(2);
|
||||
expect(received).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not replay when the engine already knows the request', async () => {
|
||||
const { mx } = clientSpy();
|
||||
const invoked: string[] = [];
|
||||
|
||||
mockInvoke.mockImplementation(async (_identity, method) => {
|
||||
invoked.push(method as string);
|
||||
if (method === 'receiveSyncChanges') {
|
||||
return [{ type: 3, rawEvent: JSON.stringify(REQUEST_EVENT) }];
|
||||
}
|
||||
if (method === 'getVerificationRequest') return requestState;
|
||||
return [];
|
||||
});
|
||||
|
||||
const crypto = new EngineCrypto(mx, { userId: '@me:e.org', deviceId: 'D' });
|
||||
const received = vi.fn();
|
||||
crypto.on(CryptoEvent.VerificationRequestReceived, received);
|
||||
|
||||
await crypto.preprocessToDeviceMessages([REQUEST_EVENT as never]);
|
||||
|
||||
expect(invoked).not.toContain('queryKeysForUsers');
|
||||
expect(invoked.filter((m) => m === 'receiveSyncChanges')).toHaveLength(1);
|
||||
expect(received).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -44,6 +44,8 @@ export class EngineVerificationRequest
|
||||
|
||||
#sasAccepted = false;
|
||||
|
||||
#sasWeStarted = false;
|
||||
|
||||
constructor(call: EngineCall, state: EngineVerificationState) {
|
||||
super();
|
||||
this.#call = call;
|
||||
@@ -75,8 +77,14 @@ export class EngineVerificationRequest
|
||||
: undefined;
|
||||
|
||||
const accepted = (verification as SasState).hasBeenAccepted === true;
|
||||
const lostTieBreak = wanted === 'Sas' && current === 'Sas' && this.#sasAccepted && !accepted;
|
||||
const weStarted = (verification as SasState).weStarted === true;
|
||||
const replaced =
|
||||
wanted === 'Sas' &&
|
||||
current === 'Sas' &&
|
||||
((this.#sasAccepted && !accepted) || (this.#sasWeStarted && !weStarted));
|
||||
const lostTieBreak = replaced;
|
||||
this.#sasAccepted = wanted === 'Sas' ? accepted : false;
|
||||
this.#sasWeStarted = wanted === 'Sas' ? weStarted : false;
|
||||
|
||||
if (current !== wanted || lostTieBreak) {
|
||||
if (wanted === 'Sas') {
|
||||
@@ -118,7 +126,15 @@ export class EngineVerificationRequest
|
||||
'verificationRequest.state',
|
||||
this.#flow
|
||||
)) as EngineVerificationState | null;
|
||||
if (!next) return;
|
||||
if (!next) {
|
||||
if (this.#state.phase === EnginePhase.Done || this.#state.phase === EnginePhase.Cancelled) {
|
||||
return;
|
||||
}
|
||||
this.#state = { ...this.#state, phase: EnginePhase.Cancelled, isCancelled: true };
|
||||
this.#syncVerifier();
|
||||
this.emit(VerificationRequestEvent.Change);
|
||||
return;
|
||||
}
|
||||
|
||||
this.#state = next;
|
||||
this.#syncVerifier();
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useDeviceIds, useDeviceList, useSplitCurrentDevice } from '$hooks/useDe
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import {
|
||||
useDeviceVerificationStatus,
|
||||
useVerifiedDeviceCount,
|
||||
useUnverifiedDeviceCount,
|
||||
VerificationStatus,
|
||||
} from '$hooks/useDeviceVerificationStatus';
|
||||
@@ -49,6 +50,7 @@ export function Devices({ requestBack, requestClose }: DevicesProps) {
|
||||
);
|
||||
|
||||
const otherDevicesId = useDeviceIds(otherDevices);
|
||||
const verifiedDeviceCount = useVerifiedDeviceCount(crypto, mx.getSafeUserId(), otherDevicesId);
|
||||
const unverifiedDeviceCount = useUnverifiedDeviceCount(
|
||||
crypto,
|
||||
mx.getSafeUserId(),
|
||||
@@ -111,15 +113,13 @@ export function Devices({ requestBack, requestClose }: DevicesProps) {
|
||||
>
|
||||
{crypto && <DeviceKeyDetails crypto={crypto} />}
|
||||
</DeviceTile>
|
||||
{crossSigningActive &&
|
||||
verificationStatus === VerificationStatus.Unverified &&
|
||||
defaultSecretStorageKeyId &&
|
||||
defaultSecretStorageKeyContent && (
|
||||
<VerifyCurrentDeviceTile
|
||||
secretStorageKeyId={defaultSecretStorageKeyId}
|
||||
secretStorageKeyContent={defaultSecretStorageKeyContent}
|
||||
/>
|
||||
)}
|
||||
{crossSigningActive && verificationStatus === VerificationStatus.Unverified && (
|
||||
<VerifyCurrentDeviceTile
|
||||
secretStorageKeyId={defaultSecretStorageKeyId}
|
||||
secretStorageKeyContent={defaultSecretStorageKeyContent}
|
||||
hasVerifiedOtherDevice={(verifiedDeviceCount ?? 0) > 0}
|
||||
/>
|
||||
)}
|
||||
{crypto && verificationStatus === VerificationStatus.Verified && (
|
||||
<BackupRestoreTile
|
||||
crypto={crypto}
|
||||
@@ -137,9 +137,7 @@ export function Devices({ requestBack, requestClose }: DevicesProps) {
|
||||
<OtherDevices
|
||||
devices={otherDevices}
|
||||
refreshDeviceList={refreshDeviceList}
|
||||
showVerification={
|
||||
crossSigningActive && verificationStatus === VerificationStatus.Verified
|
||||
}
|
||||
showVerification={crossSigningActive}
|
||||
/>
|
||||
)}
|
||||
<LocalBackup />
|
||||
|
||||
@@ -20,10 +20,15 @@ vi.mock('$components/DeviceVerification', () => ({
|
||||
const KEY_ID = 'key-id';
|
||||
const KEY_CONTENT = { algorithm: 'm.secret_storage.v1.aes-hmac-sha2' } as SecretStorageKeyContent;
|
||||
|
||||
const renderTile = () =>
|
||||
const renderTile = (props: Record<string, unknown> = {}) =>
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<VerifyCurrentDeviceTile secretStorageKeyId={KEY_ID} secretStorageKeyContent={KEY_CONTENT} />
|
||||
<VerifyCurrentDeviceTile
|
||||
secretStorageKeyId={KEY_ID}
|
||||
secretStorageKeyContent={KEY_CONTENT}
|
||||
hasVerifiedOtherDevice
|
||||
{...props}
|
||||
/>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
|
||||
@@ -42,6 +47,34 @@ describe('VerifyCurrentDeviceTile', () => {
|
||||
expect(await screen.findByText('device verification dialog')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('offers the device flow when there is no recovery key to fall back on', async () => {
|
||||
renderTile({ secretStorageKeyId: undefined, secretStorageKeyContent: undefined });
|
||||
|
||||
expect(screen.getByRole('button', { name: /Verify with Device/i })).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /Verify Manually/i })).toBeNull();
|
||||
expect(screen.getByText(/Verify with another device\./)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not offer a request nobody can answer when no other device is verified', async () => {
|
||||
renderTile({ hasVerifiedOtherDevice: false });
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Verify with Device/i })).toBeNull();
|
||||
expect(screen.getByRole('button', { name: /Verify Manually/i })).toBeInTheDocument();
|
||||
expect(screen.getByText(/recovery key/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('says to reset when there is neither a verified device nor a recovery key', async () => {
|
||||
renderTile({
|
||||
hasVerifiedOtherDevice: false,
|
||||
secretStorageKeyId: undefined,
|
||||
secretStorageKeyContent: undefined,
|
||||
});
|
||||
|
||||
expect(screen.queryByRole('button', { name: /Verify with Device/i })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /Verify Manually/i })).toBeNull();
|
||||
expect(screen.getByText(/reset device verification/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('reports why the request failed instead of silently doing nothing', async () => {
|
||||
requestOwnUserVerification.mockRejectedValue(new Error('no cross-signing identity'));
|
||||
renderTile();
|
||||
|
||||
@@ -61,7 +61,20 @@ export function VerificationStatusBadge({
|
||||
);
|
||||
}
|
||||
|
||||
function LearnStartVerificationFromOtherDevice() {
|
||||
const describeOptions = (canVerifyWithDevice: boolean, canVerifyManually: boolean): string => {
|
||||
if (canVerifyWithDevice && canVerifyManually) {
|
||||
return 'Verify with another device or verify manually.';
|
||||
}
|
||||
if (canVerifyWithDevice) return 'Verify with another device.';
|
||||
if (canVerifyManually) return 'Verify manually with your recovery key.';
|
||||
return 'No verified device and no recovery key: reset device verification to start over.';
|
||||
};
|
||||
|
||||
function LearnStartVerificationFromOtherDevice({
|
||||
canVerifyManually,
|
||||
}: {
|
||||
canVerifyManually: boolean;
|
||||
}) {
|
||||
return (
|
||||
<Box direction="Column">
|
||||
<Text size="T200">Steps to verify from other device.</Text>
|
||||
@@ -77,20 +90,25 @@ function LearnStartVerificationFromOtherDevice() {
|
||||
<li>Initiate verification.</li>
|
||||
</ul>
|
||||
</Text>
|
||||
<Text size="T200">
|
||||
If you do not have any verified device press the <i>"Verify Manually"</i> button.
|
||||
</Text>
|
||||
{canVerifyManually && (
|
||||
<Text size="T200">
|
||||
If you do not have any verified device press the <i>"Verify Manually"</i>{' '}
|
||||
button.
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
type VerifyCurrentDeviceTileProps = {
|
||||
secretStorageKeyId: string;
|
||||
secretStorageKeyContent: SecretStorageKeyContent;
|
||||
secretStorageKeyId?: string;
|
||||
secretStorageKeyContent?: SecretStorageKeyContent;
|
||||
hasVerifiedOtherDevice?: boolean;
|
||||
};
|
||||
export function VerifyCurrentDeviceTile({
|
||||
secretStorageKeyId,
|
||||
secretStorageKeyContent,
|
||||
hasVerifiedOtherDevice = false,
|
||||
}: VerifyCurrentDeviceTileProps) {
|
||||
const mx = useMatrixClient();
|
||||
const [learnMore, setLearnMore] = useState(false);
|
||||
@@ -113,6 +131,8 @@ export function VerifyCurrentDeviceTile({
|
||||
setRequestState({ status: AsyncStatus.Idle });
|
||||
}, []);
|
||||
const requesting = requestState.status === AsyncStatus.Loading;
|
||||
const canVerifyManually = Boolean(secretStorageKeyId && secretStorageKeyContent);
|
||||
const canVerifyWithDevice = hasVerifiedOtherDevice;
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -121,44 +141,50 @@ export function VerifyCurrentDeviceTile({
|
||||
title="Unverified"
|
||||
description={
|
||||
<>
|
||||
Verify with another device or verify manually.{' '}
|
||||
{describeOptions(canVerifyWithDevice, canVerifyManually)}{' '}
|
||||
<Text as="a" size="T200" onClick={() => setLearnMore(!learnMore)}>
|
||||
<b>{learnMore ? 'View Less' : 'Learn More'}</b>
|
||||
</Text>
|
||||
</>
|
||||
}
|
||||
after={
|
||||
!manualVerification && (
|
||||
!(manualVerification && canVerifyManually) && (
|
||||
<Box gap="200" alignItems="Center">
|
||||
<Button
|
||||
size="300"
|
||||
variant="Critical"
|
||||
radii="300"
|
||||
onClick={requestVerification}
|
||||
before={requesting && <Spinner size="100" variant="Critical" fill="Solid" />}
|
||||
disabled={requesting}
|
||||
>
|
||||
<Text as="span" size="B300">
|
||||
Verify with Device
|
||||
</Text>
|
||||
</Button>
|
||||
<Button
|
||||
size="300"
|
||||
variant="Critical"
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
outlined
|
||||
onClick={() => setManualVerification(true)}
|
||||
>
|
||||
<Text as="span" size="B300">
|
||||
Verify Manually
|
||||
</Text>
|
||||
</Button>
|
||||
{canVerifyWithDevice && (
|
||||
<Button
|
||||
size="300"
|
||||
variant="Critical"
|
||||
radii="300"
|
||||
onClick={requestVerification}
|
||||
before={requesting && <Spinner size="100" variant="Critical" fill="Solid" />}
|
||||
disabled={requesting}
|
||||
>
|
||||
<Text as="span" size="B300">
|
||||
Verify with Device
|
||||
</Text>
|
||||
</Button>
|
||||
)}
|
||||
{canVerifyManually && (
|
||||
<Button
|
||||
size="300"
|
||||
variant="Critical"
|
||||
fill="Soft"
|
||||
radii="300"
|
||||
outlined
|
||||
onClick={() => setManualVerification(true)}
|
||||
>
|
||||
<Text as="span" size="B300">
|
||||
Verify Manually
|
||||
</Text>
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
)
|
||||
}
|
||||
>
|
||||
{learnMore && <LearnStartVerificationFromOtherDevice />}
|
||||
{learnMore && (
|
||||
<LearnStartVerificationFromOtherDevice canVerifyManually={canVerifyManually} />
|
||||
)}
|
||||
{requestState.status === AsyncStatus.Error && (
|
||||
<Text size="T200">{requestState.error.message}</Text>
|
||||
)}
|
||||
@@ -166,7 +192,7 @@ export function VerifyCurrentDeviceTile({
|
||||
<DeviceVerification request={requestState.data} onExit={handleExitVerification} />
|
||||
)}
|
||||
</InfoCard>
|
||||
{manualVerification && (
|
||||
{manualVerification && secretStorageKeyId && secretStorageKeyContent && (
|
||||
<ManualVerificationTile
|
||||
secretStorageKeyId={secretStorageKeyId}
|
||||
secretStorageKeyContent={secretStorageKeyContent}
|
||||
|
||||
@@ -208,6 +208,23 @@ export const useDeviceVerificationStatus = (
|
||||
return status;
|
||||
};
|
||||
|
||||
export const useVerifiedDeviceCount = (
|
||||
crypto: CryptoApi | undefined,
|
||||
userId: string,
|
||||
devices: string[]
|
||||
): number | undefined => {
|
||||
useInvalidateDeviceVerification(crypto);
|
||||
|
||||
return useQueries({
|
||||
queries: devices.map((deviceId) => deviceVerificationQuery(crypto, userId, deviceId)),
|
||||
combine: (results) => {
|
||||
if (!crypto) return 0;
|
||||
if (results.some((result) => result.isPending)) return undefined;
|
||||
return results.filter((result) => result.data === true).length;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export const useUnverifiedDeviceCount = (
|
||||
crypto: CryptoApi | undefined,
|
||||
userId: string,
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { Page } from '@playwright/test';
|
||||
import { test, expect } from './fixtures/test';
|
||||
import { homeserverBaseUrl, PASSWORD, type InjectedSession } from './fixtures/session';
|
||||
import {
|
||||
loginUser,
|
||||
registerUser,
|
||||
setAccountData,
|
||||
type RegisteredUser,
|
||||
} from './fixtures/continuwuity';
|
||||
|
||||
const injectSession = async (page: Page, baseUrl: string, user: RegisteredUser): Promise<void> => {
|
||||
const session: InjectedSession = {
|
||||
baseUrl,
|
||||
userId: user.userId,
|
||||
deviceId: user.deviceId,
|
||||
accessToken: user.accessToken,
|
||||
slidingSyncOptIn: false,
|
||||
};
|
||||
await page.addInitScript((injected: InjectedSession) => {
|
||||
localStorage.setItem('matrixSessions', JSON.stringify([injected]));
|
||||
localStorage.setItem('matrixActiveSession', JSON.stringify(injected.userId));
|
||||
localStorage.setItem('dismissNotice', 'true');
|
||||
}, session);
|
||||
};
|
||||
|
||||
test.describe('device verification entry points', () => {
|
||||
test('an unverified session can still start verification with another session', async ({
|
||||
browser,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(300_000);
|
||||
const storageStatePath = testInfo.project.use.storageState as string;
|
||||
const hsBaseUrl = await homeserverBaseUrl(storageStatePath);
|
||||
const username = `two-device-${testInfo.project.name}-${process.pid}`;
|
||||
|
||||
const first = await registerUser(hsBaseUrl, username, PASSWORD);
|
||||
await setAccountData(hsBaseUrl, first, 'm.cross_signing.master', { encrypted: {} });
|
||||
const second = await loginUser(hsBaseUrl, username, PASSWORD);
|
||||
|
||||
const firstContext = await browser.newContext({ storageState: undefined });
|
||||
const firstPage = await firstContext.newPage();
|
||||
await injectSession(firstPage, hsBaseUrl, first);
|
||||
await firstPage.goto('/settings/devices');
|
||||
await expect(firstPage.getByText(first.deviceId).first()).toBeVisible({ timeout: 120_000 });
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const response = await fetch(`${hsBaseUrl}/_matrix/client/v3/keys/query`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${first.accessToken}` },
|
||||
body: JSON.stringify({ device_keys: { [first.userId]: [] } }),
|
||||
});
|
||||
const body = (await response.json()) as {
|
||||
device_keys?: Record<string, Record<string, unknown>>;
|
||||
};
|
||||
return Object.keys(body.device_keys?.[first.userId] ?? {}).length;
|
||||
},
|
||||
{ timeout: 120_000, intervals: [2_000] }
|
||||
)
|
||||
.toBeGreaterThanOrEqual(1);
|
||||
|
||||
const context = await browser.newContext({ storageState: undefined });
|
||||
const page = await context.newPage();
|
||||
await injectSession(page, hsBaseUrl, second);
|
||||
|
||||
await page.goto('/settings/devices');
|
||||
await expect(page.getByText('Others')).toBeVisible({ timeout: 120_000 });
|
||||
await expect(page.getByText(first.deviceId).first()).toBeVisible({ timeout: 120_000 });
|
||||
|
||||
const otherDeviceTile = page.getByText(
|
||||
'Verify device identity and grant access to encrypted messages.',
|
||||
{ exact: true }
|
||||
);
|
||||
await expect(otherDeviceTile).toBeVisible({ timeout: 120_000 });
|
||||
|
||||
await page
|
||||
.getByRole('button', { name: 'Verify', exact: true })
|
||||
.last()
|
||||
.click({ timeout: 60_000 });
|
||||
|
||||
await expect(
|
||||
firstPage.getByText('Click accept to start the verification process.')
|
||||
).toBeVisible({ timeout: 120_000 });
|
||||
|
||||
await context.close();
|
||||
await firstContext.close();
|
||||
});
|
||||
});
|
||||
@@ -88,6 +88,49 @@ export async function registerUser(
|
||||
return { userId: body.user_id, accessToken: body.access_token, deviceId: body.device_id };
|
||||
}
|
||||
|
||||
export async function loginUser(
|
||||
baseUrl: string,
|
||||
username: string,
|
||||
password: string
|
||||
): Promise<RegisteredUser> {
|
||||
const response = await fetch(`${baseUrl}/_matrix/client/v3/login`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
type: 'm.login.password',
|
||||
identifier: { type: 'm.id.user', user: username },
|
||||
password,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`login failed: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
const body = (await response.json()) as {
|
||||
user_id: string;
|
||||
access_token: string;
|
||||
device_id: string;
|
||||
};
|
||||
return { userId: body.user_id, accessToken: body.access_token, deviceId: body.device_id };
|
||||
}
|
||||
|
||||
export async function setAccountData(
|
||||
baseUrl: string,
|
||||
user: RegisteredUser,
|
||||
type: string,
|
||||
content: Record<string, unknown>
|
||||
): Promise<void> {
|
||||
const response = await fetch(
|
||||
`${baseUrl}/_matrix/client/v3/user/${encodeURIComponent(user.userId)}/account_data/${type}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { Authorization: `Bearer ${user.accessToken}` },
|
||||
body: JSON.stringify(content),
|
||||
}
|
||||
);
|
||||
if (!response.ok) {
|
||||
throw new Error(`account data ${type} failed: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function createRoom(
|
||||
baseUrl: string,
|
||||
token: string,
|
||||
|
||||
Reference in new issue
Block a user