diff --git a/src/app/components/ActionUIA.tsx b/src/app/components/ActionUIA.tsx index 215cb60de..720cb8ef4 100644 --- a/src/app/components/ActionUIA.tsx +++ b/src/app/components/ActionUIA.tsx @@ -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 && ( - - )} + {(stageToComplete.type === (AuthType.OAuth as string) || + stageToComplete.type === OAUTH_UNSTABLE_STAGE) && + stageToComplete.session && ( + + )} ); } diff --git a/src/app/components/uia-stages/OAuthStage.tsx b/src/app/components/uia-stages/OAuthStage.tsx index 1603d6691..415c5f1b9 100644 --- a/src/app/components/uia-stages/OAuthStage.tsx +++ b/src/app/components/uia-stages/OAuthStage.tsx @@ -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(); + +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(); - 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 Account Authorization - + {composerIcon(X)} diff --git a/tests/e2e/device-verification-reset.spec.ts b/tests/e2e/device-verification-reset.spec.ts index 648905475..777df5b34 100644 --- a/tests/e2e/device-verification-reset.spec.ts +++ b/tests/e2e/device-verification-reset.spec.ts @@ -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: 'ticket' }) + ); + 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) => { diff --git a/tests/e2e/device-verification.spec.ts b/tests/e2e/device-verification.spec.ts index 801488a65..ddcbbe697 100644 --- a/tests/e2e/device-verification.spec.ts +++ b/tests/e2e/device-verification.spec.ts @@ -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([]); }); });