Merge branch 'develop' of https://github.com/element-hq/matrix-react-sdk into langleyd/mobile_registeration

This commit is contained in:
David Langley 2024-09-16 13:46:33 +01:00
commit 3d89fc3bf2
14 changed files with 272 additions and 27 deletions

View file

@ -41,7 +41,12 @@ test.describe("Cryptography", function () {
}); });
}); });
test("should show the correct shield on e2e events", async ({ page, app, bot: bob, homeserver }) => { test("should show the correct shield on e2e events", async ({
page,
app,
bot: bob,
homeserver,
}, workerInfo) => {
// Bob has a second, not cross-signed, device // Bob has a second, not cross-signed, device
const bobSecondDevice = new Bot(page, homeserver, { const bobSecondDevice = new Bot(page, homeserver, {
bootstrapSecretStorage: false, bootstrapSecretStorage: false,
@ -117,7 +122,10 @@ test.describe("Cryptography", function () {
await lastTileE2eIcon.focus(); await lastTileE2eIcon.focus();
await expect(page.getByRole("tooltip")).toContainText("Encrypted by a device not verified by its owner."); await expect(page.getByRole("tooltip")).toContainText("Encrypted by a device not verified by its owner.");
/* Should show a grey padlock for a message from an unknown device */ /* In legacy crypto: should show a grey padlock for a message from a deleted device.
* In rust crypto: should show a red padlock for a message from an unverified device.
* Rust crypto remembers the verification state of the sending device, so it will know that the device was
* unverified, even if it gets deleted. */
// bob deletes his second device // bob deletes his second device
await bobSecondDevice.evaluate((cli) => cli.logout(true)); await bobSecondDevice.evaluate((cli) => cli.logout(true));
@ -148,7 +156,11 @@ test.describe("Cryptography", function () {
await expect(last).toContainText("test encrypted from unverified"); await expect(last).toContainText("test encrypted from unverified");
await expect(lastE2eIcon).toHaveClass(/mx_EventTile_e2eIcon_warning/); await expect(lastE2eIcon).toHaveClass(/mx_EventTile_e2eIcon_warning/);
await lastE2eIcon.focus(); await lastE2eIcon.focus();
await expect(page.getByRole("tooltip")).toContainText("Encrypted by an unknown or deleted device."); await expect(page.getByRole("tooltip")).toContainText(
workerInfo.project.name === "Legacy Crypto"
? "Encrypted by an unknown or deleted device."
: "Encrypted by a device not verified by its owner.",
);
}); });
test("Should show a grey padlock for a key restored from backup", async ({ test("Should show a grey padlock for a key restored from backup", async ({

View file

@ -20,7 +20,7 @@ import { randB64Bytes } from "../../utils/rand";
// Docker tag to use for synapse docker image. // Docker tag to use for synapse docker image.
// We target a specific digest as every now and then a Synapse update will break our CI. // We target a specific digest as every now and then a Synapse update will break our CI.
// This digest is updated by the playwright-image-updates.yaml workflow periodically. // This digest is updated by the playwright-image-updates.yaml workflow periodically.
const DOCKER_TAG = "develop@sha256:5f8d9e0d8c34dd3af23a3b8f2d30223710bccd657f86384803ce4c1cf2fa7263"; const DOCKER_TAG = "develop@sha256:e69f01d085a69269c892dfa899cb274a593f0fbb4c518eac2b530319fa43c7cb";
async function cfgDirFromTemplate(opts: StartHomeserverOpts): Promise<Omit<HomeserverConfig, "dockerUrl">> { async function cfgDirFromTemplate(opts: StartHomeserverOpts): Promise<Omit<HomeserverConfig, "dockerUrl">> {
const templateDir = path.join(__dirname, "templates", opts.template); const templateDir = path.join(__dirname, "templates", opts.template);

View file

@ -20,6 +20,7 @@ import { logger } from "matrix-js-sdk/src/logger";
import getEntryComponentForLoginType, { import getEntryComponentForLoginType, {
ContinueKind, ContinueKind,
CustomAuthType,
IStageComponent, IStageComponent,
} from "../views/auth/InteractiveAuthEntryComponents"; } from "../views/auth/InteractiveAuthEntryComponents";
import Spinner from "../views/elements/Spinner"; import Spinner from "../views/elements/Spinner";
@ -75,11 +76,11 @@ export interface InteractiveAuthProps<T> {
// Called when the stage changes, or the stage's phase changes. First // Called when the stage changes, or the stage's phase changes. First
// argument is the stage, second is the phase. Some stages do not have // argument is the stage, second is the phase. Some stages do not have
// phases and will be counted as 0 (numeric). // phases and will be counted as 0 (numeric).
onStagePhaseChange?(stage: AuthType | null, phase: number): void; onStagePhaseChange?(stage: AuthType | CustomAuthType | null, phase: number): void;
} }
interface IState { interface IState {
authStage?: AuthType; authStage?: CustomAuthType | AuthType;
stageState?: IStageStatus; stageState?: IStageStatus;
busy: boolean; busy: boolean;
errorText?: string; errorText?: string;

View file

@ -11,6 +11,8 @@ import { MatrixClient } from "matrix-js-sdk/src/matrix";
import { AuthType, AuthDict, IInputs, IStageStatus } from "matrix-js-sdk/src/interactive-auth"; import { AuthType, AuthDict, IInputs, IStageStatus } from "matrix-js-sdk/src/interactive-auth";
import { logger } from "matrix-js-sdk/src/logger"; import { logger } from "matrix-js-sdk/src/logger";
import React, { ChangeEvent, createRef, FormEvent, Fragment } from "react"; import React, { ChangeEvent, createRef, FormEvent, Fragment } from "react";
import { Button, Text } from "@vector-im/compound-web";
import PopOutIcon from "@vector-im/compound-design-tokens/assets/web/icons/pop-out";
import EmailPromptIcon from "../../../../res/img/element-icons/email-prompt.svg"; import EmailPromptIcon from "../../../../res/img/element-icons/email-prompt.svg";
import { _t } from "../../../languageHandler"; import { _t } from "../../../languageHandler";
@ -21,6 +23,7 @@ import AccessibleButton, { AccessibleButtonKind, ButtonEvent } from "../elements
import Field from "../elements/Field"; import Field from "../elements/Field";
import Spinner from "../elements/Spinner"; import Spinner from "../elements/Spinner";
import CaptchaForm from "./CaptchaForm"; import CaptchaForm from "./CaptchaForm";
import { Flex } from "../../utils/Flex";
/* This file contains a collection of components which are used by the /* This file contains a collection of components which are used by the
* InteractiveAuth to prompt the user to enter the information needed * InteractiveAuth to prompt the user to enter the information needed
@ -905,11 +908,11 @@ export class SSOAuthEntry extends React.Component<ISSOAuthEntryProps, ISSOAuthEn
} }
} }
export class FallbackAuthEntry extends React.Component<IAuthEntryProps> { export class FallbackAuthEntry<T = {}> extends React.Component<IAuthEntryProps & T> {
private popupWindow: Window | null; protected popupWindow: Window | null;
private fallbackButton = createRef<HTMLButtonElement>(); protected fallbackButton = createRef<HTMLButtonElement>();
public constructor(props: IAuthEntryProps) { public constructor(props: IAuthEntryProps & T) {
super(props); super(props);
// we have to make the user click a button, as browsers will block // we have to make the user click a button, as browsers will block
@ -967,6 +970,50 @@ export class FallbackAuthEntry extends React.Component<IAuthEntryProps> {
} }
} }
export enum CustomAuthType {
// Workaround for MAS requiring non-UIA authentication for resetting cross-signing.
MasCrossSigningReset = "org.matrix.cross_signing_reset",
}
export class MasUnlockCrossSigningAuthEntry extends FallbackAuthEntry<{
stageParams?: {
url?: string;
};
}> {
public static LOGIN_TYPE = CustomAuthType.MasCrossSigningReset;
private onGoToAccountClick = (): void => {
if (!this.props.stageParams?.url) return;
this.popupWindow = window.open(this.props.stageParams.url, "_blank");
};
private onRetryClick = (): void => {
this.props.submitAuthDict({});
};
public render(): React.ReactNode {
return (
<div>
<Text>{_t("auth|uia|mas_cross_signing_reset_description")}</Text>
<Flex gap="var(--cpd-space-4x)">
<Button
Icon={PopOutIcon}
onClick={this.onGoToAccountClick}
autoFocus
kind="primary"
className="mx_Dialog_nonDialogButton"
>
{_t("auth|uia|mas_cross_signing_reset_cta")}
</Button>
<Button onClick={this.onRetryClick} kind="secondary" className="mx_Dialog_nonDialogButton">
{_t("action|retry")}
</Button>
</Flex>
</div>
);
}
}
export interface IStageComponentProps extends IAuthEntryProps { export interface IStageComponentProps extends IAuthEntryProps {
stageParams?: Record<string, any>; stageParams?: Record<string, any>;
inputs?: IInputs; inputs?: IInputs;
@ -983,8 +1030,10 @@ export interface IStageComponent extends React.ComponentClass<React.PropsWithRef
focus?(): void; focus?(): void;
} }
export default function getEntryComponentForLoginType(loginType: AuthType): IStageComponent { export default function getEntryComponentForLoginType(loginType: AuthType | CustomAuthType): IStageComponent {
switch (loginType) { switch (loginType) {
case CustomAuthType.MasCrossSigningReset:
return MasUnlockCrossSigningAuthEntry;
case AuthType.Password: case AuthType.Password:
return PasswordAuthEntry; return PasswordAuthEntry;
case AuthType.Recaptcha: case AuthType.Recaptcha:

View file

@ -24,19 +24,22 @@ import { ReadPinsEventId } from "../components/views/right_panel/types";
import { useMatrixClientContext } from "../contexts/MatrixClientContext"; import { useMatrixClientContext } from "../contexts/MatrixClientContext";
import { useAsyncMemo } from "./useAsyncMemo"; import { useAsyncMemo } from "./useAsyncMemo";
import PinningUtils from "../utils/PinningUtils"; import PinningUtils from "../utils/PinningUtils";
import { batch } from "../utils/promise.ts";
/** /**
* Get the pinned event IDs from a room. * Get the pinned event IDs from a room.
* The number of pinned events is limited to 100.
* @param room * @param room
*/ */
function getPinnedEventIds(room?: Room): string[] { function getPinnedEventIds(room?: Room): string[] {
return ( const eventIds: string[] =
room room
?.getLiveTimeline() ?.getLiveTimeline()
.getState(EventTimeline.FORWARDS) .getState(EventTimeline.FORWARDS)
?.getStateEvents(EventType.RoomPinnedEvents, "") ?.getStateEvents(EventType.RoomPinnedEvents, "")
?.getContent()?.pinned ?? [] ?.getContent()?.pinned ?? [];
); // Limit the number of pinned events to 100
return eventIds.slice(0, 100);
} }
/** /**
@ -173,12 +176,11 @@ export function useFetchedPinnedEvents(room: Room, pinnedEventIds: string[]): Ar
const cli = useMatrixClientContext(); const cli = useMatrixClientContext();
return useAsyncMemo( return useAsyncMemo(
() => () => {
Promise.all( const fetchPromises = pinnedEventIds.map((eventId) => () => fetchPinnedEvent(room, eventId, cli));
pinnedEventIds.map( // Fetch the pinned events in batches of 10
async (eventId): Promise<MatrixEvent | null> => fetchPinnedEvent(room, eventId, cli), return batch(fetchPromises, 10);
), },
),
[cli, room, pinnedEventIds], [cli, room, pinnedEventIds],
null, null,
); );

View file

@ -29,7 +29,7 @@ import { MatrixClient, MatrixError } from "matrix-js-sdk/src/matrix";
*/ */
export const useUserTimezone = (cli: MatrixClient, userId: string): { timezone: string; friendly: string } | null => { export const useUserTimezone = (cli: MatrixClient, userId: string): { timezone: string; friendly: string } | null => {
const [timezone, setTimezone] = useState<string>(); const [timezone, setTimezone] = useState<string>();
const [updateInterval, setUpdateInterval] = useState<number>(); const [updateInterval, setUpdateInterval] = useState<ReturnType<typeof setTimeout>>();
const [friendly, setFriendly] = useState<string>(); const [friendly, setFriendly] = useState<string>();
const [supported, setSupported] = useState<boolean>(); const [supported, setSupported] = useState<boolean>();

View file

@ -370,6 +370,8 @@
"email_resend_prompt": "Did not receive it? <a>Resend it</a>", "email_resend_prompt": "Did not receive it? <a>Resend it</a>",
"email_resent": "Resent!", "email_resent": "Resent!",
"fallback_button": "Start authentication", "fallback_button": "Start authentication",
"mas_cross_signing_reset_cta": "Go to your account",
"mas_cross_signing_reset_description": "Reset your identity through your account provider and then come back and click “Retry”.",
"msisdn": "A text message has been sent to %(msisdn)s", "msisdn": "A text message has been sent to %(msisdn)s",
"msisdn_token_incorrect": "Token incorrect", "msisdn_token_incorrect": "Token incorrect",
"msisdn_token_prompt": "Please enter the code it contains:", "msisdn_token_prompt": "Please enter the code it contains:",

View file

@ -1968,8 +1968,6 @@
"few": "%(count)s osoby proszą o dołączenie", "few": "%(count)s osoby proszą o dołączenie",
"many": "%(count)s osób prosi o dołączenie" "many": "%(count)s osób prosi o dołączenie"
}, },
"release_announcement_description": "Ciesz się prostszym, bardziej przystosowanym nagłówkiem pokoju.",
"release_announcement_header": "Nowy design!",
"room_is_public": "Ten pokój jest publiczny", "room_is_public": "Ten pokój jest publiczny",
"show_widgets_button": "Pokaż widżety", "show_widgets_button": "Pokaż widżety",
"video_call_button_ec": "Rozmowa wideo (%(brand)s)", "video_call_button_ec": "Rozmowa wideo (%(brand)s)",

View file

@ -40,3 +40,18 @@ export async function retry<T, E extends Error>(
} }
throw lastErr; throw lastErr;
} }
/**
* Batch promises into groups of a given size.
* Execute the promises in parallel, but wait for all promises in a batch to resolve before moving to the next batch.
* @param funcs - The promises to batch
* @param batchSize - The number of promises to execute in parallel
*/
export async function batch<T>(funcs: Array<() => Promise<T>>, batchSize: number): Promise<T[]> {
const results: T[] = [];
for (let i = 0; i < funcs.length; i += batchSize) {
const batch = funcs.slice(i, i + batchSize);
results.push(...(await Promise.all(batch.map((f) => f()))));
}
return results;
}

View file

@ -7,11 +7,14 @@
*/ */
import React from "react"; import React from "react";
import { render, screen, waitFor, act } from "@testing-library/react"; import { render, screen, waitFor, act, fireEvent } from "@testing-library/react";
import { AuthType } from "matrix-js-sdk/src/interactive-auth"; import { AuthType } from "matrix-js-sdk/src/interactive-auth";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { EmailIdentityAuthEntry } from "../../../../src/components/views/auth/InteractiveAuthEntryComponents"; import {
EmailIdentityAuthEntry,
MasUnlockCrossSigningAuthEntry,
} from "../../../../src/components/views/auth/InteractiveAuthEntryComponents";
import { createTestClient } from "../../../test-utils"; import { createTestClient } from "../../../test-utils";
describe("<EmailIdentityAuthEntry/>", () => { describe("<EmailIdentityAuthEntry/>", () => {
@ -55,3 +58,44 @@ describe("<EmailIdentityAuthEntry/>", () => {
await waitFor(() => expect(screen.queryByRole("button", { name: "Resend" })).toBeInTheDocument()); await waitFor(() => expect(screen.queryByRole("button", { name: "Resend" })).toBeInTheDocument());
}); });
}); });
describe("<MasUnlockCrossSigningAuthEntry/>", () => {
const renderAuth = (props = {}) => {
const matrixClient = createTestClient();
return render(
<MasUnlockCrossSigningAuthEntry
matrixClient={matrixClient}
loginType={AuthType.Email}
onPhaseChange={jest.fn()}
submitAuthDict={jest.fn()}
fail={jest.fn()}
clientSecret="my secret"
showContinue={true}
stageParams={{ url: "https://example.com" }}
{...props}
/>,
);
};
test("should render", () => {
const { container } = renderAuth();
expect(container).toMatchSnapshot();
});
test("should open idp in new tab on click", async () => {
const spy = jest.spyOn(global.window, "open");
renderAuth();
fireEvent.click(screen.getByRole("button", { name: "Go to your account" }));
expect(spy).toHaveBeenCalledWith("https://example.com", "_blank");
});
test("should retry uia request on click", async () => {
const submitAuthDict = jest.fn();
renderAuth({ submitAuthDict });
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(submitAuthDict).toHaveBeenCalledWith({});
});
});

View file

@ -32,3 +32,53 @@ exports[`<EmailIdentityAuthEntry/> should render 1`] = `
</div> </div>
</div> </div>
`; `;
exports[`<MasUnlockCrossSigningAuthEntry/> should render 1`] = `
<div>
<div>
<p
class="_typography_yh5dq_162 _font-body-md-regular_yh5dq_59"
>
Reset your identity through your account provider and then come back and click “Retry”.
</p>
<div
class="mx_Flex"
style="--mx-flex-display: flex; --mx-flex-direction: row; --mx-flex-align: start; --mx-flex-justify: start; --mx-flex-gap: var(--cpd-space-4x);"
>
<button
class="_button_zt6rp_17 mx_Dialog_nonDialogButton _has-icon_zt6rp_61"
data-kind="primary"
data-size="lg"
role="button"
tabindex="0"
>
<svg
aria-hidden="true"
fill="currentColor"
height="20"
viewBox="0 0 24 24"
width="20"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M5 3h6a1 1 0 1 1 0 2H5v14h14v-6a1 1 0 1 1 2 0v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z"
/>
<path
d="M15 3h5a1 1 0 0 1 1 1v5a1 1 0 1 1-2 0V6.414l-6.293 6.293a1 1 0 0 1-1.414-1.414L17.586 5H15a1 1 0 1 1 0-2Z"
/>
</svg>
Go to your account
</button>
<button
class="_button_zt6rp_17 mx_Dialog_nonDialogButton"
data-kind="secondary"
data-size="lg"
role="button"
tabindex="0"
>
Retry
</button>
</div>
</div>
</div>
`;

View file

@ -196,6 +196,21 @@ describe("<PinnedMessagesCard />", () => {
expect(asFragment()).toMatchSnapshot(); expect(asFragment()).toMatchSnapshot();
}); });
it("should not show more than 100 messages", async () => {
const events = Array.from({ length: 120 }, (_, i) =>
mkMessage({
event: true,
room: "!room:example.org",
user: "@alice:example.org",
msg: `The message ${i}`,
ts: i,
}),
);
await initPinnedMessagesCard(events, []);
expect(screen.queryAllByRole("listitem")).toHaveLength(100);
});
it("should updates when messages are pinned", async () => { it("should updates when messages are pinned", async () => {
// Start with nothing pinned // Start with nothing pinned
const { addLocalPinEvent, addNonLocalPinEvent } = await initPinnedMessagesCard([], []); const { addLocalPinEvent, addNonLocalPinEvent } = await initPinnedMessagesCard([], []);

View file

@ -358,7 +358,7 @@ exports[`<PinnedMessagesCard /> unpin all should not allow to unpinall 1`] = `
aria-label="Open menu" aria-label="Open menu"
class="_icon-button_bh2qc_17" class="_icon-button_bh2qc_17"
data-state="closed" data-state="closed"
id="radix-18" id="radix-218"
role="button" role="button"
style="--cpd-icon-button-size: 24px;" style="--cpd-icon-button-size: 24px;"
tabindex="0" tabindex="0"
@ -424,7 +424,7 @@ exports[`<PinnedMessagesCard /> unpin all should not allow to unpinall 1`] = `
aria-label="Open menu" aria-label="Open menu"
class="_icon-button_bh2qc_17" class="_icon-button_bh2qc_17"
data-state="closed" data-state="closed"
id="radix-19" id="radix-219"
role="button" role="button"
style="--cpd-icon-button-size: 24px;" style="--cpd-icon-button-size: 24px;"
tabindex="0" tabindex="0"

View file

@ -0,0 +1,57 @@
/*
* Copyright 2024 New Vector Ltd.
*
* SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only
* Please see LICENSE files in the repository root for full details.
*
*/
import { batch } from "../../src/utils/promise.ts";
describe("promise.ts", () => {
describe("batch", () => {
afterEach(() => jest.useRealTimers());
it("should batch promises into groups of a given size", async () => {
const promises = [() => Promise.resolve(1), () => Promise.resolve(2), () => Promise.resolve(3)];
const batchSize = 2;
const result = await batch(promises, batchSize);
expect(result).toEqual([1, 2, 3]);
});
it("should wait for the current batch to finish to request the next one", async () => {
jest.useFakeTimers();
let promise1Called = false;
const promise1 = () =>
new Promise<number>((resolve) => {
promise1Called = true;
resolve(1);
});
let promise2Called = false;
const promise2 = () =>
new Promise<number>((resolve) => {
promise2Called = true;
setTimeout(() => {
resolve(2);
}, 10);
});
let promise3Called = false;
const promise3 = () =>
new Promise<number>((resolve) => {
promise3Called = true;
resolve(3);
});
const batchSize = 2;
const batchPromise = batch([promise1, promise2, promise3], batchSize);
expect(promise1Called).toBe(true);
expect(promise2Called).toBe(true);
expect(promise3Called).toBe(false);
jest.advanceTimersByTime(11);
expect(await batchPromise).toEqual([1, 2, 3]);
});
});
});