mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-20 09:01:17 -08:00
fix: retry the m.oauth stage after the cross-signing reset is approved (#1685)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Fixes # #### Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [ ] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
4 files changed
+148
-17
No files matched your search
@@ -7,12 +7,22 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { UIAFlowOverlay } from './UIAFlowOverlay';
|
||||
import { OAuthStage, PasswordStage, SSOStage } from './uia-stages';
|
||||
|
||||
const SUPPORTED_IN_APP_UIA_STAGES = [AuthType.Password, AuthType.Sso, AuthType.OAuth];
|
||||
// MSC4312 unstable prefix for m.oauth.
|
||||
export const OAUTH_UNSTABLE_STAGE = 'org.matrix.cross_signing_reset';
|
||||
|
||||
const SUPPORTED_IN_APP_UIA_STAGES = [
|
||||
AuthType.Password,
|
||||
AuthType.Sso,
|
||||
AuthType.OAuth,
|
||||
OAUTH_UNSTABLE_STAGE,
|
||||
];
|
||||
|
||||
const pickUIAFlow = (uiaFlows: UIAFlow[]): UIAFlow | undefined => {
|
||||
const passwordFlow = getUIAFlowForStages(uiaFlows, [AuthType.Password]);
|
||||
if (passwordFlow) return passwordFlow;
|
||||
const oauthFlow = getUIAFlowForStages(uiaFlows, [AuthType.OAuth]);
|
||||
const oauthFlow =
|
||||
getUIAFlowForStages(uiaFlows, [AuthType.OAuth]) ??
|
||||
getUIAFlowForStages(uiaFlows, [OAUTH_UNSTABLE_STAGE]);
|
||||
if (oauthFlow) return oauthFlow;
|
||||
return getUIAFlowForStages(uiaFlows, [AuthType.Sso]);
|
||||
};
|
||||
@@ -53,9 +63,11 @@ export function ActionUIA({ authData, ongoingFlow, action, onCancel }: ActionUIA
|
||||
submitAuthDict={action}
|
||||
/>
|
||||
)}
|
||||
{stageToComplete.type === (AuthType.OAuth as string) && stageToComplete.session && (
|
||||
<OAuthStage stageData={stageToComplete} onCancel={onCancel} submitAuthDict={action} />
|
||||
)}
|
||||
{(stageToComplete.type === (AuthType.OAuth as string) ||
|
||||
stageToComplete.type === OAUTH_UNSTABLE_STAGE) &&
|
||||
stageToComplete.session && (
|
||||
<OAuthStage stageData={stageToComplete} onCancel={onCancel} submitAuthDict={action} />
|
||||
)}
|
||||
</UIAFlowOverlay>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,49 +2,82 @@ import { Box, Button, color, config, Dialog, Header, IconButton, Text } from 'fo
|
||||
import { Warning, composerIcon, sizedIcon, X } from '$components/icons/phosphor';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { AuthType } from '$types/matrix-sdk';
|
||||
import type { StageComponentProps } from './types';
|
||||
|
||||
const POLL_COOLDOWN_MS = 1500;
|
||||
|
||||
type SessionState = {
|
||||
approvalSent: boolean;
|
||||
submits: number;
|
||||
};
|
||||
|
||||
const sessionStates = new Map<string, SessionState>();
|
||||
|
||||
const getSessionState = (session: string | undefined): SessionState => {
|
||||
if (!session) return { approvalSent: false, submits: 0 };
|
||||
const state = sessionStates.get(session) ?? { approvalSent: false, submits: 0 };
|
||||
sessionStates.set(session, state);
|
||||
return state;
|
||||
};
|
||||
|
||||
export function OAuthStage({ stageData, submitAuthDict, onCancel }: StageComponentProps) {
|
||||
const { errorCode, error, session, info } = stageData;
|
||||
const { type, errorCode, error, session, info } = stageData;
|
||||
const url = (info as { url?: string } | undefined)?.url;
|
||||
const [oauthWindow, setOauthWindow] = useState<Window>();
|
||||
const [polling, setPolling] = useState(false);
|
||||
const stateRef = useRef(getSessionState(session));
|
||||
const [polling, setPolling] = useState(stateRef.current.approvalSent);
|
||||
const lastPollRef = useRef(0);
|
||||
const leftAppRef = useRef(stateRef.current.approvalSent);
|
||||
|
||||
const handleSubmit = useCallback(() => {
|
||||
submitAuthDict({
|
||||
type: AuthType.OAuth,
|
||||
session,
|
||||
});
|
||||
}, [submitAuthDict, session]);
|
||||
const state = stateRef.current;
|
||||
state.submits += 1;
|
||||
// The spec completes this stage with the session alone; continuwuity reads a
|
||||
// type-less dict as a fallback acknowledgement, so alternate both forms.
|
||||
submitAuthDict(state.submits % 2 === 1 ? { session } : { type, session });
|
||||
}, [submitAuthDict, type, session]);
|
||||
|
||||
const handleCancel = () => {
|
||||
if (session) sessionStates.delete(session);
|
||||
onCancel();
|
||||
};
|
||||
|
||||
const awaitApproval = () => {
|
||||
stateRef.current.approvalSent = true;
|
||||
setPolling(true);
|
||||
};
|
||||
|
||||
const handleContinue = () => {
|
||||
if (!url) return;
|
||||
if (isTauri()) {
|
||||
import('@tauri-apps/plugin-opener')
|
||||
.then(({ openUrl }) => openUrl(url))
|
||||
.then(() => setPolling(true))
|
||||
.then(awaitApproval)
|
||||
.catch(() => {
|
||||
const w = window.open(url, '_blank');
|
||||
setOauthWindow(w ?? undefined);
|
||||
awaitApproval();
|
||||
});
|
||||
return;
|
||||
}
|
||||
const w = window.open(url, '_blank');
|
||||
setOauthWindow(w ?? undefined);
|
||||
awaitApproval();
|
||||
};
|
||||
|
||||
const triggerPoll = useCallback(() => {
|
||||
if (!polling) return;
|
||||
if (!polling || !leftAppRef.current) return;
|
||||
const now = Date.now();
|
||||
if (now - lastPollRef.current < POLL_COOLDOWN_MS) return;
|
||||
lastPollRef.current = now;
|
||||
handleSubmit();
|
||||
}, [polling, handleSubmit]);
|
||||
|
||||
useEffect(() => {
|
||||
const state = stateRef.current;
|
||||
if (state.approvalSent && state.submits === 1) handleSubmit();
|
||||
}, [handleSubmit]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!url) return undefined;
|
||||
const handleMessage = (evt: MessageEvent) => {
|
||||
@@ -69,13 +102,19 @@ export function OAuthStage({ stageData, submitAuthDict, onCancel }: StageCompone
|
||||
|
||||
useEffect(() => {
|
||||
if (!polling) return undefined;
|
||||
const onBlur = () => {
|
||||
leftAppRef.current = true;
|
||||
};
|
||||
const onFocus = () => triggerPoll();
|
||||
const onVisibility = () => {
|
||||
if (document.visibilityState === 'visible') triggerPoll();
|
||||
else leftAppRef.current = true;
|
||||
};
|
||||
window.addEventListener('blur', onBlur);
|
||||
window.addEventListener('focus', onFocus);
|
||||
document.addEventListener('visibilitychange', onVisibility);
|
||||
return () => {
|
||||
window.removeEventListener('blur', onBlur);
|
||||
window.removeEventListener('focus', onFocus);
|
||||
document.removeEventListener('visibilitychange', onVisibility);
|
||||
};
|
||||
@@ -95,7 +134,7 @@ export function OAuthStage({ stageData, submitAuthDict, onCancel }: StageCompone
|
||||
<Box grow="Yes">
|
||||
<Text size="H4">Account Authorization</Text>
|
||||
</Box>
|
||||
<IconButton size="300" onClick={onCancel} radii="300">
|
||||
<IconButton size="300" onClick={handleCancel} radii="300">
|
||||
{composerIcon(X)}
|
||||
</IconButton>
|
||||
</Header>
|
||||
|
||||
@@ -149,6 +149,86 @@ test.describe('device verification reset', () => {
|
||||
expect(authDicts[authDicts.length - 1]).toEqual({ type: 'm.oauth', session: SESSION });
|
||||
});
|
||||
|
||||
test('resumes the m.oauth stage after a retry that ran before approval', async ({
|
||||
page,
|
||||
baseURL,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(180_000);
|
||||
const storageStatePath = testInfo.project.use.storageState as string;
|
||||
const hsBaseUrl = await homeserverBaseUrl(storageStatePath);
|
||||
await loginAsFreshUser(
|
||||
page,
|
||||
hsBaseUrl,
|
||||
`reset-oauth-race-${testInfo.project.name}-${process.pid}`
|
||||
);
|
||||
|
||||
await page.goto('/settings/devices');
|
||||
|
||||
await page.getByRole('button', { name: 'Enable' }).click({ timeout: 180_000 });
|
||||
await expect(page.getByText('Setup Device Verification')).toBeVisible();
|
||||
await page.locator('form').getByRole('button', { name: 'Continue' }).click();
|
||||
await expect(recoveryKeyShown(page)).toBeVisible({ timeout: 120_000 });
|
||||
|
||||
const ticketUrl = `${baseURL}${TICKET_PATH}`;
|
||||
const submittedDicts: (AuthDict | undefined)[] = [];
|
||||
let approved = false;
|
||||
await page.route(`**${TICKET_PATH}`, (route) =>
|
||||
route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>ticket</title>' })
|
||||
);
|
||||
await page.route(UPLOAD_ROUTE, async (route) => {
|
||||
const { auth } = route.request().postDataJSON() as { auth?: AuthDict };
|
||||
const submitted = auth?.session === SESSION;
|
||||
if (submitted) submittedDicts.push(auth);
|
||||
|
||||
if (submitted && approved) {
|
||||
await route.fulfill({ status: 200, contentType: 'application/json', body: '{}' });
|
||||
return;
|
||||
}
|
||||
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
flows: [{ stages: ['m.oauth'] }],
|
||||
params: { 'm.oauth': { url: ticketUrl } },
|
||||
session: SESSION,
|
||||
...(submitted ? { errcode: 'M_FORBIDDEN', error: 'No OAuth ticket available' } : {}),
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
await page.reload();
|
||||
await page
|
||||
.locator('#device-verification')
|
||||
.locator('button[aria-pressed]')
|
||||
.click({ timeout: 180_000 });
|
||||
await page.getByRole('button', { name: 'Reset', exact: true }).click();
|
||||
|
||||
await expect(page.getByText('Reset Device Verification')).toBeVisible();
|
||||
await page.getByRole('button', { name: 'Reset', exact: true }).last().click();
|
||||
await page.locator('form').getByRole('button', { name: 'Continue' }).click();
|
||||
|
||||
await expect(page.getByText('Account Authorization')).toBeVisible({ timeout: 120_000 });
|
||||
|
||||
const popup = page.waitForEvent('popup');
|
||||
await page.getByRole('button', { name: 'Continue in Browser' }).click();
|
||||
await (await popup).close();
|
||||
await page.getByRole('button', { name: 'Continue', exact: true, disabled: false }).click();
|
||||
|
||||
await expect(page.getByText('No OAuth ticket available')).toBeVisible({ timeout: 120_000 });
|
||||
await expect(page.getByRole('button', { name: 'Continue in Browser' })).toBeHidden();
|
||||
|
||||
await expect.poll(() => submittedDicts.length, { timeout: 30_000 }).toBeGreaterThanOrEqual(2);
|
||||
expect(submittedDicts[0]).toEqual({ session: SESSION });
|
||||
expect(submittedDicts[1]).toEqual({ type: 'm.oauth', session: SESSION });
|
||||
|
||||
approved = true;
|
||||
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
|
||||
|
||||
await expect(recoveryKeyShown(page)).toBeVisible({ timeout: 120_000 });
|
||||
await expect(page.getByText('Account Authorization')).toBeHidden();
|
||||
});
|
||||
|
||||
test('sets up verification when the session syncs over sliding sync', async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -93,7 +93,7 @@ test.describe('device verification setup', () => {
|
||||
await expect(page.getByText('Account Authorization')).toBeHidden();
|
||||
|
||||
expect(authDicts.length).toBeGreaterThanOrEqual(2);
|
||||
expect(authDicts.find((auth) => auth?.session === SESSION)).toEqual({ session: SESSION });
|
||||
expect(authDicts[authDicts.length - 1]).toEqual({ type: 'm.oauth', session: SESSION });
|
||||
expect(authDicts.filter((auth) => auth?.session && !auth.type)).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user