Compare commits

..
Author SHA1 Message Date
Johannes Marbach d423d9bdcc Explain when we can drop --no-experimental-webstorage 2026-11-30 14:56:09 +01:00
Johannes Marbach fe06f6ba27 Switch to node26 2026-11-30 13:39:43 +01:00
87 changed files with 1737 additions and 3565 deletions
+1 -1
View File
@@ -1 +1 @@
24
26
-5
View File
@@ -26,10 +26,6 @@ vi.mock("../src/state/AppViewModel", () => ({
AppViewModel: class {
public mediaDevices = {};
public backgroundEffects = {};
public clientSession: unknown;
public constructor(_scope: unknown, _options: unknown, session: unknown) {
this.clientSession = session;
}
},
}));
@@ -47,7 +43,6 @@ beforeEach(() => {
_unstable_getStickyEvents: vi.fn(),
getMxcAvatarUrl: vi.fn(),
getJoinRule: vi.fn(),
hasEncryptionStateEvent: vi.fn(),
});
});
+1 -2
View File
@@ -30,7 +30,7 @@ import type { Room } from "matrix-js-sdk";
import type { UrlProperties } from "../src/UrlParams";
import type { ElementCallHandle, ElementCallHostBridge } from "./host";
import type { HostClientPart } from "./componentLocalJsClient";
import type { SuppliedClient } from "../src/state/ClientSession";
import type { SuppliedClient } from "../src/ClientContext";
import {
BackgroundStyle,
configurationForIntent,
@@ -91,7 +91,6 @@ type HostRoomPart = Pick<
| "getMxcAvatarUrl"
| "getJoinRule"
| "relations"
| "hasEncryptionStateEvent"
>;
export interface ElementCallProps {
+8 -14
View File
@@ -73,7 +73,6 @@ import {
} from "../src/UrlParams";
import { MediaDevicesContext } from "../src/MediaDevicesContext";
import { AppViewModel } from "../src/state/AppViewModel";
import { hostClientSession } from "../src/state/ClientSession";
import { ObservableScope } from "../src/state/ObservableScope";
import { BackgroundEffectsProvider } from "../src/tracks/BackgroundEffectsContext";
import { Config } from "../src/config/Config";
@@ -193,25 +192,20 @@ export const ElementCall: FC<ElementCallProps> = ({
[roomId, intent, stableConfig],
);
// Created in an effect so that the scope it lives in ends when the component
// is unmounted (or these options change), rather than keeping its device
// observers running for the rest of the page's life. Null until then, which
// is one render.
const { controlledAudioDevices, callIntent } = params;
const [vm, setVm] = useState<AppViewModel | null>(null);
useEffect(() => {
const scope = new ObservableScope();
setVm(
new AppViewModel(
scope,
{ controlledAudioDevices, callIntent },
// The host owns the client. We create a clientSession wrapping the host client.
hostClientSession(client),
// The host owns the session too, so there is nothing to manage here
null,
),
);
setVm(new AppViewModel(scope, { controlledAudioDevices, callIntent }));
return (): void => {
setVm(null);
scope.end();
};
}, [controlledAudioDevices, callIntent, client]);
}, [controlledAudioDevices, callIntent]);
const backend = useMemo(
() => createCallMatrixBackend(createComponentLocalJsClient(client), room),
@@ -253,11 +247,11 @@ export const ElementCall: FC<ElementCallProps> = ({
>
<Decoration>
<TooltipProvider>
{/* The client session: what reads it through
{/* The host's own client: what reads it through
the context (avatars, the encryption system,
rageshakes, the disconnected banner) uses only its
stable methods. */}
<ClientProvider session={vm.clientSession}>
<ClientProvider client={client}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider
effects={vm.backgroundEffects}
+1 -1
View File
@@ -82,7 +82,7 @@
"@types/grecaptcha": "^3.0.9",
"@types/jsdom": "^21.1.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^24.0.0",
"@types/node": "^26.6.11",
"@types/qrcode": "^1.5.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
+16 -66
View File
@@ -58,20 +58,20 @@ const cases: {
guestFlows: ["cs-api"],
},
{
// The client-server API is preferred wherever a transport names a url.
// Clients since 0.28.1 match such a publisher by either identity.
// Publishers keep the legacy participant identity that clients predating
// MSC4195 expect, which only the JWT service assigns.
hostShape: "url+legacy",
guestShape: "url+legacy",
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
},
{
// The MatrixRTC mode has no bearing on the choice.
hostShape: "url+legacy",
guestShape: "url+legacy",
mode: "2_0",
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
},
{
hostShape: "url",
@@ -80,12 +80,10 @@ const cases: {
guestFlows: ["service-legacy", "cs-api"],
},
{
// Both reach the SFU through the client-server API, under one identity
// each, so one connection serves the own and the other's transport.
hostShape: "url",
guestShape: "url+legacy",
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
hostFlows: ["cs-api", "service-default"],
guestFlows: ["service-legacy", "cs-api"],
},
];
@@ -162,53 +160,6 @@ test("Publisher shows an error when the homeserver lacks MSC4195", async ({
).toBeVisible();
});
test("Falls back to the JWT service for a url+legacy transport when the homeserver lacks MSC4195", async ({
browser,
page,
browserName,
}) => {
skipOnFirefox(browserName);
// The host starts the call; its C-S requests fail.
await advertiseTransport(page, shapes["url+legacy"]);
await rejectCsApiTokens(page);
const hostRequests = recordAuthRequests(page);
await page.goto("/");
await SpaHelpers.createCall(page, "Androl", "HelloCall", true);
const inviteLink = await SpaHelpers.getCallInviteLink(page);
// The guest joins, and its C-S requests fail as well.
const guestContext = await browser.newContext({ reducedMotion: "reduce" });
const guestPage = await guestContext.newPage();
await advertiseTransport(guestPage, shapes["url+legacy"]);
await rejectCsApiTokens(guestPage);
const guestRequests = recordAuthRequests(guestPage);
await SpaHelpers.joinCallFromInviteLink(guestPage, inviteLink, "Pevara");
// The call connects all the same.
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
for (const requests of [hostRequests, guestRequests]) {
// Each published through the JWT service, under the legacy identity, and
// subscribes to the other over that same connection.
expect(flowsOf(requests)).toEqual(
new Set<Flow>(["cs-api", "service-legacy"]),
);
// The homeserver is asked once. Nothing asks it again once the API is
// known to be missing.
expect(requests.filter(({ flow }) => flow === "cs-api")).toHaveLength(1);
for (const request of requests) {
if (request.flow === "cs-api") {
expect(request.status).toBe(404);
} else {
expect(request.status).toBe(200);
expect(request.identity).toMatch(legacyIdentity);
}
}
}
});
test("Group call with all possible transport shapes at once", async ({
browser,
page,
@@ -242,12 +193,13 @@ test("Group call with all possible transport shapes at once", async ({
});
/**
* Delegation follows the flow that authenticated the publisher.
* Delegation follows the flow that authenticated the publisher: the homeserver
* for a `url`-only transport, the JWT service wherever there is one.
*/
const delegationCases: { shape: Shape; via: Delegation["via"] }[] = [
{ shape: "url", via: "homeserver" },
{ shape: "legacy", via: "service" },
{ shape: "url+legacy", via: "homeserver" },
{ shape: "url+legacy", via: "service" },
];
for (const { shape, via } of delegationCases) {
@@ -276,10 +228,10 @@ for (const { shape, via } of delegationCases) {
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
// The guest handed its delayed leave over. A JWT service is first probed
// for delegation support with a bodiless request, which counts as
// supported unless it 404s. A homeserver that issued the token is not
// probed.
// The guest handed its delayed leave over, after probing for delegation
// support with bodiless requests, which count as supported unless they
// 404. The homeserver is always probed; the JWT service only when there
// is one.
await expect
.poll(() => delegations.at(-1))
.toEqual({
@@ -289,9 +241,7 @@ for (const { shape, via } of delegationCases) {
...(via === "homeserver" && { sfuUrl }),
});
const probes = delegations.slice(0, -1);
expect(probes.map((probe) => probe.via)).toEqual(
via === "service" ? ["service"] : [],
);
expect(probes.some((probe) => probe.via === via)).toBe(true);
for (const probe of probes) {
expect(probe.status).toBeGreaterThanOrEqual(400);
expect(probe.status).not.toBe(404);
+103 -103
View File
@@ -26,7 +26,7 @@ importers:
devDependencies:
'@codecov/vite-plugin':
specifier: ^2.0.0
version: 2.0.1(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 2.0.1(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@fontsource/inconsolata':
specifier: ^5.1.0
version: 5.3.0
@@ -65,7 +65,7 @@ importers:
version: 10.1.2(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@rolldown/plugin-babel':
specifier: ^0.3.0
version: 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@sentry/react':
specifier: ^8.0.0
version: 8.55.2(react@19.3.1)
@@ -80,7 +80,7 @@ importers:
version: 10.6.8(@vitest/browser-playwright@4.1.12)(@vitest/browser@4.1.12)(react@19.3.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vitest@4.1.12)
'@storybook/react-vite':
specifier: ^10.3.6
version: 10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@testing-library/dom':
specifier: ^10.1.0
version: 10.4.2
@@ -106,8 +106,8 @@ importers:
specifier: ^4.17.12
version: 4.17.12
'@types/node':
specifier: ^24.0.0
version: 24.19.2
specifier: ^26.6.11
version: 26.6.11
'@types/qrcode':
specifier: ^1.5.5
version: 1.5.6
@@ -134,10 +134,10 @@ importers:
version: 10.6.0(@fontsource/inconsolata@5.3.0)(@fontsource/inter@5.3.0)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(@vector-im/compound-design-tokens@11.3.1(@types/react@19.3.0)(react@19.3.1))(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@vitejs/plugin-react':
specifier: ^6.0.2
version: 6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/browser-playwright':
specifier: ^4.1.5
version: 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
version: 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/coverage-v8':
specifier: ^4.0.18
version: 4.1.12(@vitest/browser@4.1.12)(vitest@4.1.12)
@@ -173,13 +173,13 @@ importers:
version: 8.3.1
i18next-cli:
specifier: ^1.61.0
version: 1.91.3(@types/node@24.19.2)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3)
version: 1.91.3(@types/node@26.6.11)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3)
jsdom:
specifier: ^26.0.0
version: 26.1.0(supports-color@7.2.0)
knip:
specifier: ^5.86.0
version: 5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@24.19.2)(typescript@5.9.3)
version: 5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@26.6.11)(typescript@5.9.3)
livekit-client:
specifier: ^2.18.1
version: 2.23.0(@types/dom-mediacapture-record@1.0.22)
@@ -266,25 +266,25 @@ importers:
version: 1.1.2(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
vite:
specifier: ^8.0.0
version: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
version: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite-plugin-html:
specifier: ^3.2.2
version: 3.2.2(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 3.2.2(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-node-polyfills:
specifier: ^0.28.0
version: 0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-node-stdlib-browser:
specifier: ^0.2.1
version: 0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-svgr:
specifier: ^4.0.0
version: 4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vite-plugin-wasm:
specifier: ^3.6.0
version: 3.6.0(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 3.6.0(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest:
specifier: ^4.1.5
version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
version: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest-axe:
specifier: ^1.0.0-pre.3
version: 1.0.0-pre.5(vitest@4.1.12)
@@ -3111,8 +3111,8 @@ packages:
'@types/mdx@2.0.14':
resolution: {integrity: sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg==}
'@types/node@24.19.2':
resolution: {integrity: sha512-93d49wCWJkCyN87MxLpNN6KXPCwFw7bVUg79mGUV1OS40JGWwVCr8n61DXCSqz7CV6/VfPkb7xec7uP2M+QHWQ==}
'@types/node@26.6.11':
resolution: {integrity: sha512-uUyQ2XLEz+EXh34lmS3GhKrkqn/8FU7KUiKRpk347At2bmnMVWss45yz8b4FG/tUtmV1tV/+TVkITItPROyeeQ==}
'@types/qrcode@1.5.6':
resolution: {integrity: sha512-te7NQcV2BOvdj2b1hCAHzAoMNuj65kNBMz0KBaxM6c3VGBOhU0dURQKOtH8CFNI/dsKkwlv32p26qYQTWoB5bw==}
@@ -5706,8 +5706,8 @@ packages:
resolution: {integrity: sha512-X2wH19RAPZE3+ldGicOkoj/SIA83OIxcJ6Cuaw23hf8Xc6fQpvZXY0SftE2JgS0QhYLUG4uwodSI3R53keyh7w==}
engines: {node: '>=14'}
undici-types@7.24.6:
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
undici-types@8.9.0:
resolution: {integrity: sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==}
undici@6.29.1:
resolution: {integrity: sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==}
@@ -6308,11 +6308,11 @@ snapshots:
unplugin: 1.16.1
zod: 3.25.76
'@codecov/vite-plugin@2.0.1(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@codecov/vite-plugin@2.0.1(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@codecov/bundler-plugin-core': 2.0.1
unplugin: 1.16.1
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@croct/json5-parser@0.2.2':
dependencies:
@@ -6872,59 +6872,59 @@ snapshots:
'@inquirer/ansi@2.1.1': {}
'@inquirer/confirm@6.4.0(@types/node@24.19.2)':
'@inquirer/confirm@6.4.0(@types/node@26.6.11)':
dependencies:
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/type': 4.3.0(@types/node@24.19.2)
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/type': 4.3.0(@types/node@26.6.11)
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@inquirer/core@12.1.1(@types/node@24.19.2)':
'@inquirer/core@12.1.1(@types/node@26.6.11)':
dependencies:
'@inquirer/ansi': 2.1.1
'@inquirer/figures': 2.1.1
'@inquirer/type': 4.3.1(@types/node@24.19.2)
'@inquirer/type': 4.3.1(@types/node@26.6.11)
cli-width: 4.1.0
fast-string-width: 3.0.2
fast-wrap-ansi: 0.2.2
mute-stream: 3.0.0
signal-exit: 4.1.0
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@inquirer/figures@2.1.1': {}
'@inquirer/input@5.2.0(@types/node@24.19.2)':
'@inquirer/input@5.2.0(@types/node@26.6.11)':
dependencies:
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/type': 4.3.0(@types/node@24.19.2)
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/type': 4.3.0(@types/node@26.6.11)
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@inquirer/password@5.3.0(@types/node@24.19.2)':
'@inquirer/password@5.3.0(@types/node@26.6.11)':
dependencies:
'@inquirer/ansi': 2.1.1
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/type': 4.3.0(@types/node@24.19.2)
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/type': 4.3.0(@types/node@26.6.11)
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@inquirer/select@5.3.0(@types/node@24.19.2)':
'@inquirer/select@5.3.0(@types/node@26.6.11)':
dependencies:
'@inquirer/ansi': 2.1.1
'@inquirer/core': 12.1.1(@types/node@24.19.2)
'@inquirer/core': 12.1.1(@types/node@26.6.11)
'@inquirer/figures': 2.1.1
'@inquirer/type': 4.3.0(@types/node@24.19.2)
'@inquirer/type': 4.3.0(@types/node@26.6.11)
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@inquirer/type@4.3.0(@types/node@24.19.2)':
'@inquirer/type@4.3.0(@types/node@26.6.11)':
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@inquirer/type@4.3.1(@types/node@24.19.2)':
'@inquirer/type@4.3.1(@types/node@26.6.11)':
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@isaacs/cliui@8.0.2':
dependencies:
@@ -6937,11 +6937,11 @@ snapshots:
'@isaacs/nonrecursive-glob-match@1.1.0': {}
'@joshwooding/vite-plugin-react-docgen-typescript@0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@joshwooding/vite-plugin-react-docgen-typescript@0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
glob: 10.5.0
react-docgen-typescript: 2.4.0(typescript@5.9.3)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
optionalDependencies:
typescript: 5.9.3
@@ -7938,7 +7938,7 @@ snapshots:
'@rolldown/binding-win32-x64-msvc@1.2.19':
optional: true
'@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@babel/core': 7.29.13(supports-color@7.2.0)
artichokie: 0.4.5
@@ -7946,7 +7946,7 @@ snapshots:
rolldown: 1.2.19
optionalDependencies:
'@babel/runtime': 8.0.8
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@rolldown/pluginutils@1.1.1': {}
@@ -8180,17 +8180,17 @@ snapshots:
'@storybook/icons': 2.2.0(react@19.3.1)
storybook: 10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1)
optionalDependencies:
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
transitivePeerDependencies:
- react
'@storybook/builder-vite@10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@storybook/builder-vite@10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
storybook: 10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1)
ts-dedent: 2.3.0
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@storybook/global@5.0.0': {}
@@ -8207,11 +8207,11 @@ snapshots:
'@types/react': 19.3.0
'@types/react-dom': 19.3.0(@types/react@19.3.0)
'@storybook/react-vite@10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@storybook/react-vite@10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(rollup@4.60.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@joshwooding/vite-plugin-react-docgen-typescript': 0.7.0(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@rollup/pluginutils': 5.5.1(rollup@4.60.1)
'@storybook/builder-vite': 10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@storybook/builder-vite': 10.6.8(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@storybook/react': 10.6.8(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(storybook@10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1))(supports-color@7.2.0)(typescript@5.9.3)
empathic: 2.1.0
magic-string: 1.4.5
@@ -8221,7 +8221,7 @@ snapshots:
resolve: 1.22.14
storybook: 10.6.8(@types/react@19.3.0)(prettier@3.8.3)(react@19.3.1)
tsconfig-paths: 4.2.0
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
optionalDependencies:
typescript: 5.9.3
transitivePeerDependencies:
@@ -8479,7 +8479,7 @@ snapshots:
'@types/jsdom@21.1.7':
dependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@types/tough-cookie': 4.0.5
parse5: 7.3.0
@@ -8493,13 +8493,13 @@ snapshots:
'@types/mdx@2.0.14': {}
'@types/node@24.19.2':
'@types/node@26.6.11':
dependencies:
undici-types: 7.24.6
undici-types: 8.9.0
'@types/qrcode@1.5.6':
dependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
'@types/react-dom@19.3.0(@types/react@19.3.0)':
dependencies:
@@ -8658,37 +8658,37 @@ snapshots:
- '@types/react-dom'
- react-dom
'@vitejs/plugin-react@6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@vitejs/plugin-react@6.3.0(@rolldown/plugin-babel@0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@rolldown/pluginutils': 1.1.1
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
optionalDependencies:
'@rolldown/plugin-babel': 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@rolldown/plugin-babel': 0.3.1(@babel/core@7.29.13(supports-color@7.2.0))(@babel/runtime@8.0.8)(rolldown@1.2.19)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
babel-plugin-react-compiler: 1.0.0
'@vitest/browser-playwright@4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
'@vitest/browser-playwright@4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
dependencies:
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
playwright: 1.65.1
tinyrainbow: 3.2.0
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
transitivePeerDependencies:
- bufferutil
- msw
- utf-8-validate
- vite
'@vitest/browser@4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
'@vitest/browser@4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)':
dependencies:
'@blazediff/core': 1.9.1
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/utils': 4.1.12
magic-string: 0.30.21
pngjs: 7.0.0
sirv: 3.0.2
tinyrainbow: 3.2.0
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
ws: 8.23.0
transitivePeerDependencies:
- bufferutil
@@ -8708,9 +8708,9 @@ snapshots:
obug: 2.2.1
std-env: 4.3.0
tinyrainbow: 3.2.0
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
optionalDependencies:
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/browser': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/expect@3.2.4':
dependencies:
@@ -8729,13 +8729,13 @@ snapshots:
chai: 6.3.0
tinyrainbow: 3.2.0
'@vitest/mocker@4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
'@vitest/mocker@4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))':
dependencies:
'@vitest/spy': 4.1.12
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
'@vitest/pretty-format@3.2.4':
dependencies:
@@ -8772,7 +8772,7 @@ snapshots:
sirv: 3.0.2
tinyglobby: 0.2.17
tinyrainbow: 3.1.1
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/utils@3.2.4':
dependencies:
@@ -9747,14 +9747,14 @@ snapshots:
dependencies:
'@babel/runtime': 7.29.15
i18next-cli@1.91.3(@types/node@24.19.2)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3):
i18next-cli@1.91.3(@types/node@26.6.11)(@types/react@19.3.0)(react@19.3.1)(typescript@5.9.3):
dependencies:
'@croct/json5-parser': 0.2.2
'@formatjs/icu-messageformat-parser': 3.5.23
'@inquirer/confirm': 6.4.0(@types/node@24.19.2)
'@inquirer/input': 5.2.0(@types/node@24.19.2)
'@inquirer/password': 5.3.0(@types/node@24.19.2)
'@inquirer/select': 5.3.0(@types/node@24.19.2)
'@inquirer/confirm': 6.4.0(@types/node@26.6.11)
'@inquirer/input': 5.2.0(@types/node@26.6.11)
'@inquirer/password': 5.3.0(@types/node@26.6.11)
'@inquirer/select': 5.3.0(@types/node@26.6.11)
'@swc/core': 1.16.22
chokidar: 5.0.0
commander: 15.1.0
@@ -9985,10 +9985,10 @@ snapshots:
dependencies:
json-buffer: 3.0.1
knip@5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@24.19.2)(typescript@5.9.3):
knip@5.88.1(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)(@types/node@26.6.11)(typescript@5.9.3):
dependencies:
'@nodelib/fs.walk': 1.2.8
'@types/node': 24.19.2
'@types/node': 26.6.11
fast-glob: 3.3.3
formatly: 0.3.0
jiti: 2.6.1
@@ -11399,7 +11399,7 @@ snapshots:
unbash@2.2.0: {}
undici-types@7.24.6: {}
undici-types@8.9.0: {}
undici@6.29.1: {}
@@ -11489,7 +11489,7 @@ snapshots:
- '@types/react'
- '@types/react-dom'
vite-plugin-html@3.2.2(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-html@3.2.2(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/pluginutils': 4.2.1
colorette: 2.0.20
@@ -11503,40 +11503,40 @@ snapshots:
html-minifier-terser: 6.1.0
node-html-parser: 5.4.2
pathe: 0.2.0
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite-plugin-node-polyfills@0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-node-polyfills@0.28.0(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/plugin-inject': 5.0.5(rollup@4.60.1)
node-stdlib-browser: 1.3.1
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
transitivePeerDependencies:
- rollup
vite-plugin-node-stdlib-browser@0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-node-stdlib-browser@0.2.1(node-stdlib-browser@1.3.1)(rollup@4.60.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/plugin-inject': 5.0.5(rollup@4.60.1)
node-stdlib-browser: 1.3.1
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
transitivePeerDependencies:
- rollup
vite-plugin-svgr@4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-svgr@4.5.0(rollup@4.60.1)(supports-color@7.2.0)(typescript@5.9.3)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@rollup/pluginutils': 5.3.0(rollup@4.60.1)
'@svgr/core': 8.1.0(supports-color@7.2.0)(typescript@5.9.3)
'@svgr/plugin-jsx': 8.1.0(@svgr/core@8.1.0(supports-color@7.2.0)(typescript@5.9.3))(supports-color@7.2.0)
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
transitivePeerDependencies:
- rollup
- supports-color
- typescript
vite-plugin-wasm@3.6.0(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vite-plugin-wasm@3.6.0(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1):
vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1):
dependencies:
lightningcss: 1.33.0
picomatch: 4.0.7
@@ -11544,7 +11544,7 @@ snapshots:
rolldown: 1.2.19
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 24.19.2
'@types/node': 26.6.11
esbuild: 0.28.2
fsevents: 2.3.3
jiti: 2.7.0
@@ -11558,12 +11558,12 @@ snapshots:
axe-core: 4.11.3
chalk: 5.6.2
lodash-es: 4.18.1
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest: 4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
vitest@4.1.12(@opentelemetry/api@1.9.1)(@types/node@24.19.2)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
vitest@4.1.12(@opentelemetry/api@1.9.1)(@types/node@26.6.11)(@vitest/browser-playwright@4.1.12)(@vitest/coverage-v8@4.1.12)(@vitest/ui@4.1.12)(jsdom@26.1.0(supports-color@7.2.0))(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)):
dependencies:
'@vitest/expect': 4.1.12
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/mocker': 4.1.12(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
'@vitest/pretty-format': 4.1.12
'@vitest/runner': 4.1.12
'@vitest/snapshot': 4.1.12
@@ -11580,12 +11580,12 @@ snapshots:
tinyexec: 1.3.1
tinyglobby: 0.2.17
tinyrainbow: 3.2.0
vite: 8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
vite: 8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1)
why-is-node-running: 2.3.0
optionalDependencies:
'@opentelemetry/api': 1.9.1
'@types/node': 24.19.2
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@24.19.2)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@types/node': 26.6.11
'@vitest/browser-playwright': 4.1.12(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))(vitest@4.1.12)
'@vitest/coverage-v8': 4.1.12(@vitest/browser@4.1.12)(vitest@4.1.12)
'@vitest/ui': 4.1.12(vitest@4.1.12)
jsdom: 26.1.0(supports-color@7.2.0)
+24 -50
View File
@@ -120,10 +120,10 @@ LiveKit participants.
The session discovers the transport from the homeserver and the backend prepares
it, both before `join()`, so that the membership can name it and the first frames
go out as soon as the state event is sent. Preparing is the backend's own
business: for LiveKit the token exchange for the publisher connection, and
with it whether that service can take over the delayed leave (assumed for a homeserver,
probed for a JWT service), which picks the delayed leave timings the join uses. The
join waits for the publisher to hold its token, so that the LiveKit room exists
business: for LiveKit the token exchange for the publisher connection, and the
probe that decides whether the service that issued the token can take over the
delayed leave, which picks the delayed leave timings the join uses. The join
waits for the publisher to hold its token, so that the LiveKit room exists
before a subscriber, who lacks the permission to create it, asks for a token
of its own. The tracks are created once the membership is `joined`, with their
upstream paused until then. A lobby that wants them earlier captures them with
@@ -588,58 +588,32 @@ without one, LiveKit is built from the LiveKit-flavoured client options.
A LiveKit transport comes in three shapes while MSC4195 settles: an SFU `url`,
a JWT service `livekit_service_url`, or both. `media-backend/livekit/auth/`
fronts the two flows and chooses between them from the shape, preferring the
client-server API wherever the transport names a `url`:
fronts the two flows and chooses between them per connection, from the shape
and from the role we take on the transport:
| Transport | Publisher | Subscriber |
| -------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------ |
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
| both | client-server API, else JWT service `/sfu/get` (legacy identity) | client-server API, else JWT service `/get_token` (hashed identity) |
| Transport | Publisher | Subscriber |
| -------------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
| `url` only | client-server API `get_token`, no fallback | client-server API `get_token`, no fallback |
| `livekit_service_url` only | JWT service `/sfu/get` (legacy identity) | JWT service `/get_token` (hashed identity) |
| both | JWT service `/sfu/get` (legacy identity) | client-server API, falling back to the JWT service `/get_token` where the homeserver, or a widget host, has no MSC4195 |
A member whose transport names both is matched against either identity (since
Element Call 0.28.1), so a publisher may take either flow. On the JWT service
a publisher uses `/sfu/get`, the only endpoint that assigns the legacy
`<user_id>:<device_id>` identity. A subscriber is matched by nobody and takes
the hashed one.
The JWT service stands in only where our homeserver has no MSC4195 endpoints.
A homeserver that has them advertises a `url`, so whether the API is usable is
read off our own transport: `prepareLocalTransport` stores it with the local
transport, and it is the one input, next to a transport's shape, to
`chooseAuthFlow`. Where ours names only a JWT service, transports naming both
go through that service from the start.
A homeserver may advertise a `url` and still lack the endpoints, as may a
widget host. A token request is then answered with a 404, `M_NOT_FOUND` or
`M_UNRECOGNIZED` (`isCsApiUnavailable`) and fails with
`NoMatrix2AuthorizationService`, which the publisher connection reports to
the backend before the error surfaces. Where our transport names a JWT service
too, the backend stores the local transport again with the API ruled out; the
failed connection is stopped with its map and never shows as an error. Only
the publisher's request rules the API out: it is the first one made, and a
subscriber's 404 once we publish through the API fails that connection alone.
A transport with a `url` alone has no fallback and fails the join. The MatrixRTC mode
plays no part in the choice.
A connection is created with its flow and keeps it for life. The delayed leave
is delegated through the publisher connection's flow, the one that issued its
token, so that the service watches for the identity we publish under. A
homeserver that issued the token is assumed to delegate. Only a JWT service is
probed, before the join.
A publisher on a transport with a service URL keeps the legacy
`<user_id>:<device_id>` identity, because clients predating MSC4195 match a
membership against that and nothing else; a subscriber is matched by nobody and
takes the more private hashed identity. A publisher never falls back: a
homeserver that advertises a `url` without implementing MSC4195 is misconfigured
and fails with `NoMatrix2AuthorizationService`, so the admin hears about it.
The MatrixRTC mode plays no part in the choice. The delayed leave is delegated
through the same flow that issued the publisher's token, so that the identity
the service watches for on the SFU is the one we publish under, and the
delegation probe before the join asks only that service.
The client-server API needs the name of the homeserver the transport belongs to:
our own homeserver asks that server for the token, over federation where it is
not ours. The backend derives it from the member's user id, and from our own for
the local transport. A JWT service is reached directly, so members of several
homeservers advertising the same one share a connection.
Connections are keyed on the flow and what it authenticates against: the `url`
plus the server name for the client-server API, the service URL for the JWT
service. Transports with the same key would get us the same identity on the
same SFU, so they share a connection. A connection map is built per local
transport, so whether the API is usable is fixed for the life of a map and of
every key in it; ruling the API out replaces the map.
the local transport, and keys its connections on the transport plus the server
name where the transport has a `url`. A JWT service is reached directly, so
members of several homeservers advertising the same one share a connection.
## Media: `tracks$` and `MediaTrack`
+2 -2
View File
@@ -75,6 +75,6 @@ export {
} from "./src/media-backend/livekit/videoProcessor";
// For a developer panel to check a transport before using it
export {
authenticateWithTransport,
type AuthenticateWithTransportParams,
getSFUConfig as authenticateWithTransport,
type GetSFUConfigParams as AuthenticateWithTransportParams,
} from "./src/media-backend/livekit/auth";
@@ -42,11 +42,7 @@ import {
} from "./Connection.ts";
import { ObservableScope } from "../../reactive/ObservableScope";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
import {
LivekitConnectionError,
MatrixRTCError,
NoMatrix2AuthorizationService,
} from "../../errors";
import { LivekitConnectionError, MatrixRTCError } from "../../errors";
import { testJWTToken } from "../../utils/test-fixtures";
import { ownMemberMock } from "../../utils/test";
import { mockRemoteParticipant } from "./test";
@@ -67,15 +63,15 @@ const FIREFOX_USER_AGENT =
const CHROME_USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36";
const url = "wss://matrix-rtc.m.localhost/livekit/sfu";
const transport: UnstableLivekitTransport = { type: "livekit", url };
const transport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://matrix-rtc.m.localhost/livekit/sfu",
};
/** The options of a subscriber connection to `transport`. */
function connectionOpts(): ConnectionOpts {
return {
client,
flow: { kind: "csApi", url },
onCsApiMissing: vi.fn(),
roomId: ROOM_ID,
slotId: SLOT_ID,
role: "subscriber",
@@ -376,7 +372,6 @@ describe("Start connection states", () => {
...connectionOpts(),
role: "publisher",
transport: { type: "livekit", livekit_service_url: serviceUrl },
flow: { kind: "openID", serviceUrl },
},
logger,
);
@@ -392,61 +387,6 @@ describe("Start connection states", () => {
expect(connection.livekitAlias).toBe("!example_room_id");
});
it.each([
["reports", "publisher", 1],
// A 404 there, once we publish through the API, is not the API missing
["does not report", "subscriber", 0],
] as const)(
"%s the CS API missing as a %s where the homeserver lacks the endpoint",
async (_what, role, reports) => {
setupTest();
const opts = { ...connectionOpts(), role };
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
const connection = new Connection(opts, logger);
await expect(connection.start()).rejects.toThrow(
expect.any(NoMatrix2AuthorizationService),
);
expect(opts.onCsApiMissing).toHaveBeenCalledTimes(reports);
expect(connection.state$.value.state).toBe("error");
},
);
it("does not show as failed when reporting the CS API missing gets it stopped", async () => {
setupTest();
fakeLivekitRoom.disconnect.mockResolvedValue(undefined);
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
const connection: Connection = new Connection(
{
...connectionOpts(),
role: "publisher",
onCsApiMissing: () => void connection.stop(),
},
logger,
);
await connection.start();
await vi.waitFor(() =>
expect(connection.state$.value).toEqual({ state: "stopped" }),
);
});
it("does not report the CS API missing where the homeserver refuses the request", async () => {
setupTest();
const opts = { ...connectionOpts(), role: "publisher" as const };
client.getLivekitToken.mockRejectedValue(
new MatrixError({ errcode: "M_FORBIDDEN" }, 403),
);
const connection = new Connection(opts, logger);
await expect(connection.start()).rejects.toThrow();
expect(opts.onCsApiMissing).not.toHaveBeenCalled();
});
it("retries a join that failed on the WebSocket in Firefox", async () => {
setupTest();
mockUserAgent(FIREFOX_USER_AGENT);
+10 -41
View File
@@ -32,7 +32,6 @@ import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/En
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
type AuthFlow,
type ConnectionRole,
getSFUConfig,
type SFUConfig,
@@ -43,7 +42,6 @@ import {
MatrixRTCError,
InsufficientCapacityError,
LivekitConnectionError,
NoMatrix2AuthorizationService,
PeerConnectionTimeoutError,
SFURoomCreationRestrictedError,
UnknownRTCError,
@@ -60,13 +58,6 @@ export interface ConnectionOpts {
serverName: string;
/** The Matrix client, for the token exchange. */
client: ClientGetTokenParts & ClientOpenIDParts;
/** The flow to authenticate with. */
flow: AuthFlow;
/**
* Called when the client-server API flow finds the API missing while
* authenticating us as a publisher.
*/
onCsApiMissing: () => void;
/** The Matrix room the session is in. */
roomId: string;
/** The MatrixRTC slot the session is in. */
@@ -115,9 +106,6 @@ export class Connection {
/** The homeserver the transport belongs to. */
public readonly serverName: string;
/** The flow that issues this connection's tokens. */
public readonly flow: AuthFlow;
public readonly livekitRoom: LivekitRoom;
private scope: ObservableScope;
@@ -146,7 +134,6 @@ export class Connection {
protected stopped = false;
private readonly client: ClientGetTokenParts & ClientOpenIDParts;
private readonly onCsApiMissing: () => void;
private readonly roomId: string;
private readonly slotId: string;
private readonly logger: Logger;
@@ -174,8 +161,6 @@ export class Connection {
this.transport = transport;
this.serverName = serverName;
this.client = client;
this.flow = opts.flow;
this.onCsApiMissing = opts.onCsApiMissing;
this.remoteParticipants$ = scope.behavior(
// Only tracks remote participants
@@ -416,32 +401,16 @@ export class Connection {
}
protected async getSFUConfig(): Promise<SFUConfig> {
try {
return await getSFUConfig({
client: this.client,
membership: this.ownMembershipIdentity,
role: this.role,
flow: this.flow,
serverName: this.serverName,
roomId: this.roomId,
slotId: this.slotId,
logger: this.logger,
});
} catch (e) {
// If authenticating through the CS API failed and we are the publisher
// connection, trigger the callback before the error surfaces. If falling
// back to the OpenID flow is possible, the connection is stopped and
// replaced, so it never shows as failed.
//
// Subscriber connections are explicitly excluded here because the publishing
// connection may already have authenticated and delegated its delayed leave.
if (
e instanceof NoMatrix2AuthorizationService &&
this.role === "publisher"
)
this.onCsApiMissing();
throw e;
}
return await getSFUConfig({
client: this.client,
membership: this.ownMembershipIdentity,
role: this.role,
transport: this.transport,
serverName: this.serverName,
roomId: this.roomId,
slotId: this.slotId,
logger: this.logger,
});
}
/**
@@ -18,11 +18,7 @@ import { type PublishRequest } from "../../media-api";
import { constant } from "../../reactive/Behavior";
import { ownMemberMock, testScope } from "../../utils/test";
import { testJWTToken } from "../../utils/test-fixtures";
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
chooseAuthFlow,
} from "./auth";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
import {
LivekitConnectionFactory,
type ResolvedConnection,
@@ -54,7 +50,6 @@ function create(
): { connection: ResolvedConnection; options: RoomOptions } {
const factory = new LivekitConnectionFactory(
client(),
() => {},
"!room:example.org",
"m.call#ROOM",
publish,
@@ -67,7 +62,6 @@ function create(
"subscriber",
transport,
"example.org",
chooseAuthFlow(transport, true),
ownMemberMock,
logger,
) as ResolvedConnection;
@@ -24,7 +24,6 @@ import { type PublishRequest } from "../../media-api";
import { type Behavior } from "../../reactive/Behavior";
import { type ObservableScope } from "../../reactive/ObservableScope";
import {
type AuthFlow,
type ClientGetTokenParts,
type ClientOpenIDParts,
type ConnectionRole,
@@ -45,7 +44,6 @@ export interface ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection;
@@ -104,7 +102,6 @@ function resolvedTransport(config: SFUConfig): ResolvedTransport {
export class LivekitConnectionFactory implements ConnectionFactory {
public constructor(
private readonly client: ClientGetTokenParts & ClientOpenIDParts,
private readonly onCsApiMissing: () => void,
private readonly roomId: string,
private readonly slotId: string,
private readonly publish: PublishRequest[],
@@ -118,7 +115,6 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection {
@@ -129,9 +125,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role,
transport,
serverName,
flow,
client: this.client,
onCsApiMissing: this.onCsApiMissing,
scope,
livekitRoomFactory: () =>
new LivekitRoom(
@@ -16,7 +16,11 @@ import {
mapEpoch,
ObservableScope,
} from "../../reactive/ObservableScope";
import { createConnectionMap$, ConnectionMap } from "./ConnectionMap.ts";
import {
createConnectionMap$,
ConnectionMap,
keyFor,
} from "./ConnectionMap.ts";
import { type ConnectionFactory } from "./ConnectionFactory.ts";
import { type Connection } from "./Connection.ts";
import { ownMemberMock, withTestScheduler } from "../../utils/test";
@@ -39,33 +43,6 @@ const TRANSPORT_2: TransportLocator = {
serverName: "sample.com",
};
const SERVICE_URL_TRANSPORT: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const URL_TRANSPORT: TransportLocator = {
transport: { type: "livekit", url: "wss://sfu.example.org" },
serverName: "example.org",
};
/** Names the same SFU as URL_TRANSPORT and the same service as SERVICE_URL_TRANSPORT. */
const URL_AND_SERVICE_URL_TRANSPORT: TransportLocator = {
transport: {
type: "livekit",
url: "wss://sfu.example.org",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
/** Tells the locators used here apart; not the key the map folds them by. */
const keyFor = ({ transport, serverName }: TransportLocator): string =>
JSON.stringify([transport, serverName]);
function findConnection(
transport: TransportLocator,
connections: Connection[],
@@ -120,7 +97,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
@@ -157,7 +134,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([TRANSPORT_2], 0),
}),
@@ -173,7 +150,6 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
TRANSPORT_1.serverName,
{ kind: "openID", serviceUrl: "https://lk.example.org" },
ownMemberMock,
expect.anything(),
);
@@ -182,7 +158,6 @@ describe("connections$ stream", () => {
"subscriber",
TRANSPORT_2.transport,
TRANSPORT_2.serverName,
{ kind: "openID", serviceUrl: "https://lk.sample.com" },
ownMemberMock,
expect.anything(),
);
@@ -201,7 +176,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([sameServiceElsewhere], 0),
}),
@@ -223,7 +198,6 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
"example.org",
{ kind: "openID", serviceUrl: "https://lk.example.org" },
expect.anything(),
expect.anything(),
);
@@ -246,7 +220,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...urlTransport, csApiUsable: true },
localTransport: urlTransport,
remoteTransports$: behavior("a", {
a: new Epoch([sameUrlElsewhere], 0),
}),
@@ -269,42 +243,42 @@ describe("connections$ stream", () => {
});
});
test("Shares connection between url transport and url + livekit_service_url transport", () => {
withTestScheduler(({ expectObservable, scope }) => {
test("Shares connection between local livekit_service_url transport and remote url + livekit_service_url transport", () => {
withTestScheduler(({ behavior, expectObservable, scope }) => {
const serviceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const urlAndServiceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
url: "wss://sfu.elsewhere.org",
},
// Should pass even if local server != remote server
serverName: "elsewhere.org",
};
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...URL_AND_SERVICE_URL_TRANSPORT, csApiUsable: true },
remoteTransports$: constant(
new Epoch([URL_TRANSPORT, SERVICE_URL_TRANSPORT]),
),
localTransport: serviceUrlTransport,
remoteTransports$: constant(new Epoch([urlAndServiceUrlTransport])),
logger,
ownMembershipIdentity: ownMemberMock,
});
expectObservable(connectionMap$).toBe("a", {
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
// Both get the CS API flow, and with it the same identity on the
// same SFU. The JWT service assigns another, so it may stay apart.
expect(map.getConnections().length).toBe(2);
const shared = map.getConnectionForTransport(
URL_AND_SERVICE_URL_TRANSPORT,
);
expect(shared).not.toBeNull();
expect(map.getConnectionForTransport(URL_TRANSPORT)).toBe(shared);
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).not.toBe(
shared,
);
expect(
vi.mocked(fakeConnectionFactory).createConnection,
).toHaveBeenCalledWith(
expect.anything(),
"publisher",
URL_AND_SERVICE_URL_TRANSPORT.transport,
"example.org",
{ kind: "csApi", url: "wss://sfu.example.org" },
ownMemberMock,
expect.anything(),
expectObservable(
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
).toBe("a", {
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
// One connection total, since local and remote connections are shared
expect(cs.length).toBe(1);
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
expect(findConnection(serviceUrlTransport, cs)).toBe(
findConnection(urlAndServiceUrlTransport, cs),
);
return true;
}),
@@ -312,34 +286,44 @@ describe("connections$ stream", () => {
});
});
test("Shares connection between livekit_service_url transport and url + livekit_service_url transport without the CS API", () => {
withTestScheduler(({ expectObservable, scope }) => {
test("Shares connection between remote livekit_service_url transport and remote url + livekit_service_url transport", () => {
withTestScheduler(({ behavior, expectObservable, scope }) => {
const serviceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
},
serverName: "example.org",
};
const urlAndServiceUrlTransport: TransportLocator = {
transport: {
type: "livekit",
livekit_service_url: "https://jwt.example.org",
url: "wss://sfu.elsewhere.org",
},
// Should pass even if local server != remote server
serverName: "elsewhere.org",
};
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...SERVICE_URL_TRANSPORT, csApiUsable: false },
localTransport: TRANSPORT_2,
remoteTransports$: constant(
new Epoch([
{
...URL_AND_SERVICE_URL_TRANSPORT,
// Should pass even if local server != remote server
serverName: "elsewhere.org",
},
]),
new Epoch([serviceUrlTransport, urlAndServiceUrlTransport]),
),
logger,
ownMembershipIdentity: ownMemberMock,
});
expectObservable(connectionMap$).toBe("a", {
a: expect.toSatisfy(({ value: map }: Epoch<ConnectionMap>) => {
// One connection total, since both go through the same JWT service
expect(map.getConnections().length).toBe(1);
expect(
map.getConnectionForTransport(SERVICE_URL_TRANSPORT),
).not.toBeNull();
expect(map.getConnectionForTransport(SERVICE_URL_TRANSPORT)).toBe(
map.getConnectionForTransport(URL_AND_SERVICE_URL_TRANSPORT),
expectObservable(
connectionMap$.pipe(mapEpoch((d) => d.getConnections())),
).toBe("a", {
a: expect.toSatisfy(({ value: cs }: Epoch<Connection[]>) => {
// Two connections total: a local connection and a shared remote connection
expect(cs.length).toBe(2);
expect(findConnection(serviceUrlTransport, cs)).toBeDefined();
expect(findConnection(serviceUrlTransport, cs)).toBe(
findConnection(urlAndServiceUrlTransport, cs),
);
return true;
}),
@@ -347,35 +331,12 @@ describe("connections$ stream", () => {
});
});
test("Publishes on a url + livekit_service_url transport through the JWT service without the CS API", () => {
createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...URL_AND_SERVICE_URL_TRANSPORT, csApiUsable: false },
remoteTransports$: constant(new Epoch([])),
logger,
ownMembershipIdentity: ownMemberMock,
});
expect(
vi.mocked(fakeConnectionFactory).createConnection,
).toHaveBeenCalledExactlyOnceWith(
expect.anything(),
"publisher",
URL_AND_SERVICE_URL_TRANSPORT.transport,
"example.org",
{ kind: "openID", serviceUrl: "https://jwt.example.org" },
ownMemberMock,
expect.anything(),
);
});
test("Should start connection only once", () => {
withTestScheduler(({ behavior, expectObservable }) => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("abcdef", {
a: new Epoch([TRANSPORT_1], 0),
b: new Epoch([TRANSPORT_1], 1),
@@ -418,7 +379,7 @@ describe("connections$ stream", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("abc", {
a: new Epoch([TRANSPORT_1], 0),
b: new Epoch([TRANSPORT_1, TRANSPORT_2], 1),
@@ -461,21 +422,9 @@ describe("connections$ stream", () => {
});
describe("ConnectionMap", () => {
test("hands out the connection we publish on, if any", () => {
const connection = (role: string, locator: TransportLocator): Connection =>
({ role, ...locator }) as unknown as Connection;
const data = new ConnectionMap(true);
expect(data.getPublisherConnection()).toBeNull();
const publisher = connection("publisher", TRANSPORT_1);
data.add(connection("subscriber", TRANSPORT_2), []);
data.add(publisher, []);
expect(data.getPublisherConnection()).toBe(publisher);
});
test("warns when a second connection to the same URL is merged", () => {
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
const data = new ConnectionMap(true, logger);
const data = new ConnectionMap(logger);
const connection = TRANSPORT_1 as unknown as Connection;
const p = (identity: string): RemoteParticipant =>
({ identity }) as unknown as RemoteParticipant;
@@ -571,7 +520,7 @@ describe("connectionMap$", () => {
const connectionMap$ = createConnectionMap$({
scope: testScope,
connectionFactory: fakeConnectionFactory,
localTransport: { ...TRANSPORT_1, csApiUsable: true },
localTransport: TRANSPORT_1,
remoteTransports$: behavior("a", {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
+58 -70
View File
@@ -18,67 +18,63 @@ import {
type ObservableScope,
} from "../../reactive/ObservableScope";
import { generateItemsWithEpoch } from "../../reactive/observable";
import { chooseAuthFlow, type TransportLocator } from "./auth";
import {
chooseAuthFlow,
type ConnectionRole,
type TransportLocator,
} from "./auth";
import { type Connection } from "./Connection";
import { type ConnectionFactory } from "./ConnectionFactory";
// Branded, so that only values returned by `connectionKey` can be used as keys
type ConnectionKey = string & { __connectionKey: true };
// Branded, so that only values returned by `keyFor` can be used as keys
export type TransportKey = string & { __transportKey: true };
/**
* Converts a {@link TransportLocator} to a key suitable for identifying it in a
* map of connections.
*
* @param csApiUsable - Whether the map the key is for uses the client-server API
* where a transport leaves the choice.
*
* Note that we deliberately don't use `TransportLocatorWithCsSupport` to infer
* `csApiUsable`. That setting would be transport-specific. Instead, `csApiUsable`
* is passed in from the connection map's own setting, fixed at creation time.
*/
function connectionKey(
{ transport, serverName }: TransportLocator,
csApiUsable: boolean,
): ConnectionKey {
export function keyFor({
transport,
serverName,
}: TransportLocator): TransportKey {
// Base the key on the auth flow we would use, so that we never create two
// connections that share the same auth details. (That would be bad, as we
// might then try to connect to the same SFU twice with the same participant
// ID, resulting in only one working connection.)
const flow = chooseAuthFlow(transport, csApiUsable);
// TODO: This strategy will not work once `chooseAuthFlow` begins allowing for
// falling back from the CS API flow to the OpenID flow.
const flow = chooseAuthFlow(transport);
// Serialize the fields in a consistent order
return JSON.stringify([
flow.kind,
// With the CS API flow, we additionally need to distinguish server names
...(flow.kind === "csApi" ? [flow.url, serverName] : [flow.serviceUrl]),
]) as ConnectionKey;
]) as TransportKey;
}
/** The transport we publish on, with what is fixed for its connection map. */
export interface TransportLocatorWithCsSupport extends TransportLocator {
/**
* Whether a transport naming both a `url` and a `livekit_service_url` is
* reached through the client-server API.
*/
csApiUsable: boolean;
function removeDuplicateTransports(
transports: TransportLocator[],
): TransportLocator[] {
// The first locator wins, so the local one stays first in the list
const map = new Map<TransportKey, TransportLocator>();
for (const transport of transports) {
const key = keyFor(transport);
if (!map.has(key)) map.set(key, transport);
}
return [...map.values()];
}
/** The connections at one moment, with the remote participants seen on each. */
export class ConnectionMap {
private readonly map = new Map<
ConnectionKey,
TransportKey,
{ connection: Connection; participants: RemoteParticipant[] }
>();
/**
* @param csApiUsable - What the connections were keyed with.
*/
public constructor(
private readonly csApiUsable: boolean,
private readonly logger?: Logger,
) {}
public constructor(private readonly logger?: Logger) {}
public add(connection: Connection, participants: RemoteParticipant[]): void {
const key = connectionKey(connection, this.csApiUsable);
const key = keyFor(connection);
const existing = this.map.get(key);
if (!existing) {
this.map.set(key, { connection, participants });
@@ -96,25 +92,16 @@ export class ConnectionMap {
return Array.from(this.map.values()).map(({ connection }) => connection);
}
/** The connection we publish on or `null` if no publishing connection exists in the map. */
public getPublisherConnection(): Connection | null {
return (
this.getConnections().find(({ role }) => role === "publisher") ?? null
);
}
public getConnectionForTransport(
transport: TransportLocator,
): Connection | null {
const key = connectionKey(transport, this.csApiUsable);
return this.map.get(key)?.connection ?? null;
return this.map.get(keyFor(transport))?.connection ?? null;
}
public getParticipantsForTransport(
transport: TransportLocator,
): RemoteParticipant[] {
const key = connectionKey(transport, this.csApiUsable);
return this.map.get(key)?.participants ?? [];
return this.map.get(keyFor(transport))?.participants ?? [];
}
}
@@ -122,7 +109,7 @@ interface Props {
scope: ObservableScope;
connectionFactory: ConnectionFactory;
/** The transport we publish on; the one connection with the publisher role. */
localTransport: TransportLocatorWithCsSupport;
localTransport: TransportLocator;
/** Every transport some member is on, deduplicated against the local one. */
remoteTransports$: Behavior<Epoch<TransportLocator[]>>;
logger: Logger;
@@ -143,41 +130,42 @@ export function createConnectionMap$({
ownMembershipIdentity,
}: Props): Behavior<Epoch<ConnectionMap>> {
const logger = parentLogger.getChild("[ConnectionMap]");
const { csApiUsable } = localTransport;
const transportsByKey$ = scope.behavior(
remoteTransports$.pipe(
mapEpoch(
(remote) =>
// The last locator wins a key, so the local one goes last
new Map(
[...remote, localTransport].map((transport) => [
connectionKey(transport, csApiUsable),
transport,
]),
),
const localAndRemoteTransports$: Behavior<Epoch<TransportLocator[]>> =
scope.behavior(
remoteTransports$.pipe(
mapEpoch((remoteTransports) =>
removeDuplicateTransports([localTransport, ...remoteTransports]),
),
tap((transports) =>
logger.debug("localAndRemoteTransports$ = ", transports),
),
),
tap(({ value }) =>
logger.debug("transportsByKey$ = ", [...value.values()]),
),
),
);
);
const localTransportKey = keyFor(localTransport);
const localTransportKey = connectionKey(localTransport, csApiUsable);
const connections$ = scope.behavior(
transportsByKey$.pipe(
localAndRemoteTransports$.pipe(
generateItemsWithEpoch(
"ConnectionMap connections$",
// The locator is an object, so a stable key stands in for it
(byKey) => Array.from(byKey, ([key, data]) => ({ keys: [key], data })),
(scope, locator$, key) => {
function* (transports) {
for (const transport of transports) {
const role: ConnectionRole =
keyFor(transport) === localTransportKey
? "publisher"
: "subscriber";
// The locator is an object, so a stable key stands in for it
yield { keys: [role, keyFor(transport)], data: transport };
}
},
(scope, locator$, role, _key) => {
const { transport, serverName } = locator$.value;
const connection = connectionFactory.createConnection(
scope,
key === localTransportKey ? "publisher" : "subscriber",
role,
transport,
serverName,
chooseAuthFlow(transport, csApiUsable),
ownMembershipIdentity,
logger,
);
@@ -193,7 +181,7 @@ export function createConnectionMap$({
connections$.pipe(
switchMap(({ value: connections, epoch }) => {
if (connections.length === 0)
return of(new Epoch(new ConnectionMap(csApiUsable), epoch));
return of(new Epoch(new ConnectionMap(), epoch));
return combineLatest(
connections.map((connection) =>
connection.remoteParticipants$.pipe(
@@ -201,7 +189,7 @@ export function createConnectionMap$({
),
),
(...list) => {
const map = new ConnectionMap(csApiUsable, logger);
const map = new ConnectionMap(logger);
for (const item of list)
map.add(item.connection, item.participants);
return new Epoch(map, epoch);
@@ -54,7 +54,7 @@ function setup(connections: Connection[]): {
connections$: BehaviorSubject<Epoch<ConnectionMap>>;
sendData: (topic: string, text: string) => Promise<void>;
} {
const data = new ConnectionMap(true);
const data = new ConnectionMap();
for (const connection of connections) data.add(connection, []);
const connections$ = new BehaviorSubject(new Epoch(data));
const { data$, sendData } = createDataChannel$({
@@ -99,7 +99,7 @@ describe("data$", () => {
const second = fakeConnection("https://sfu-2");
const { received, connections$ } = setup([first.connection]);
const data = new ConnectionMap(true);
const data = new ConnectionMap();
data.add(first.connection, []);
data.add(second.connection, []);
connections$.next(new Epoch(data, 1));
@@ -148,6 +148,7 @@ describe("toMediaConnectionState", () => {
describe("createLivekitBackend", () => {
const homeserver = "https://matrix.example.org";
const homeserverEndpoint = `${homeserver}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`;
const urlTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.example.org",
@@ -168,7 +169,6 @@ describe("createLivekitBackend", () => {
participants$: BehaviorSubject<RemoteParticipant[]>;
state$: BehaviorSubject<ConnectionState>;
}[];
let onCsApiMissing: () => void;
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -177,15 +177,13 @@ describe("createLivekitBackend", () => {
/** Stands in for the factory: connections whose state and participants the test drives. */
function stubFactory(initialState: ConnectionState): void {
vi.spyOn(connectionFactory, "LivekitConnectionFactory").mockImplementation(
function (this: unknown, _client, onMissing) {
onCsApiMissing = onMissing;
function (this: unknown) {
return {
createConnection: (
scope: ObservableScope,
role: auth.ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: auth.AuthFlow,
): Connection => {
const participants$ = new BehaviorSubject<RemoteParticipant[]>([]);
const state$ = new BehaviorSubject<ConnectionState>(initialState);
@@ -193,7 +191,6 @@ describe("createLivekitBackend", () => {
role,
transport,
serverName,
flow,
state$,
remoteParticipants$: scope.behavior(participants$),
livekitRoom: fakeLivekitRoom(),
@@ -235,15 +232,17 @@ describe("createLivekitBackend", () => {
}
// Delegation goes through whichever service authenticates us as a
// publisher.
// publisher: the JWT service wherever the transport names one, the
// homeserver for a `url` alone
it.each([
["a JWT service that delegates", exampleTransport, 401, true],
["a JWT service that does not delegate", exampleTransport, 404, false],
["the homeserver over the JWT service", bothTransport, 404, true],
["the homeserver", urlTransport, 404, true],
["the JWT service", exampleTransport, 404, 401, true],
["the JWT service, and only it", bothTransport, 401, 404, false],
["the homeserver", urlTransport, 401, 404, true],
["neither", exampleTransport, 404, 404, false],
])(
"prepares the local transport for delegation through %s",
async (_name, transport, serviceStatus, expected) => {
"prepares the local transport and asks %s about delegation",
async (_name, transport, homeserverStatus, serviceStatus, expected) => {
fetchMock.post(homeserverEndpoint, homeserverStatus);
fetchMock.post(
`${exampleServiceUrl}/delegate_delayed_leave`,
serviceStatus,
@@ -252,10 +251,6 @@ describe("createLivekitBackend", () => {
const capabilities = await backend().prepareLocalTransport(transport);
expect(capabilities).toEqual({ canDelegateDelayedLeave: expected });
// Only the service that issued the publisher's token is asked.
expect(
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
).toBe(transport === exampleTransport);
expect(connections).toHaveLength(1);
expect(connections[0].connection.role).toBe("publisher");
expect(connections[0].connection.transport).toEqual(transport);
@@ -264,8 +259,9 @@ describe("createLivekitBackend", () => {
);
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
// A token through the homeserver means delegation, unless the SFU is
// another homeserver's.
// Our own homeserver would delegate, so only the SFU being remote can
// explain delegation being skipped
fetchMock.post(homeserverEndpoint, 401);
const remoteTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.sample.com",
@@ -280,6 +276,7 @@ describe("createLivekitBackend", () => {
});
it("waits for the publisher connection to hold its token before the join", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
@@ -296,6 +293,7 @@ describe("createLivekitBackend", () => {
});
it("fails the preparation with the publisher connection's error", async () => {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
stubFactory({ state: "authenticating" });
const preparing = backend().prepareLocalTransport(exampleTransport);
@@ -305,60 +303,8 @@ describe("createLivekitBackend", () => {
await expect(preparing).rejects.toBe(error);
});
it.each([
["names no JWT service", urlTransport],
["names no url", exampleTransport],
])(
"keeps its connections where the CS API is found missing and our transport %s",
async (_what, transport) => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
await backend().prepareLocalTransport(transport);
onCsApiMissing();
expect(connections).toHaveLength(1);
},
);
it("moves the publisher to the JWT service where the CS API is found missing", async () => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 401);
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
stubFactory({ state: "authenticating" });
const b = backend();
let prepared = false;
const preparing = b.prepareLocalTransport(bothTransport).then((c) => {
prepared = true;
return c;
});
await flushPromises();
expect(connections).toHaveLength(1);
expect(connections[0].connection.flow.kind).toBe("csApi");
// The publisher's token request finds no API.
onCsApiMissing();
expect(connections).toHaveLength(2);
expect(connections[1].connection.role).toBe("publisher");
expect(connections[1].connection.transport).toEqual(bothTransport);
expect(connections[1].connection.flow.kind).toBe("openID");
// The replaced connection winding down is not the preparation failing.
connections[0].state$.next({ state: "stopped" });
await flushPromises();
expect(prepared).toBe(false);
connections[1].state$.next(connected);
expect(await preparing).toEqual({ canDelegateDelayedLeave: true });
expect(
fetchMock.called(`${exampleServiceUrl}/delegate_delayed_leave`),
).toBe(true);
await b.delegateDelayedLeave("delay-1");
expect(delegate.mock.calls[0][0].flow).toEqual({
kind: "openID",
serviceUrl: exampleServiceUrl,
});
});
it("delegates the leave through the flow that authenticated the publisher", async () => {
fetchMock.post(homeserverEndpoint, 401);
const delegate = vi.spyOn(auth, "delegateDelayedLeave").mockResolvedValue();
const b = backend();
await expect(b.delegateDelayedLeave("delay-1")).rejects.toThrow(
@@ -372,7 +318,7 @@ describe("createLivekitBackend", () => {
expect.objectContaining({
client,
membership: ownMemberMock,
flow: { kind: "csApi", url: "wss://sfu.example.org" },
transport: urlTransport,
roomId: "!room:example.org",
slotId: "m.call#ROOM",
delayId: "delay-1",
@@ -414,6 +360,7 @@ describe("createLivekitBackend", () => {
async function prepared(): Promise<
ReturnType<typeof createLivekitBackend>
> {
fetchMock.post(homeserverEndpoint, 404);
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
const b = backend();
await b.prepareLocalTransport(bothTransport);
@@ -445,30 +392,6 @@ describe("createLivekitBackend", () => {
},
);
it("reaches a url + livekit_service_url member through the JWT service where our transport names no url", async () => {
fetchMock.post(`${exampleServiceUrl}/delegate_delayed_leave`, 404);
const b = backend();
await b.prepareLocalTransport(exampleTransport);
const media = b.mediaFor(
testScope(),
bob(bothTransport, [hashedId, legacyId]),
);
await flushPromises();
// Bob names our JWT service, so no connection of his own, and none
// through a client-server API our homeserver does not have
expect(connections).toHaveLength(1);
expect(connections[0].connection.flow.kind).toBe("openID");
connections[0].participants$.next([
mockRemoteParticipant({
identity: hashedId,
trackPublications: new Map(),
}),
]);
await flushPromises();
expect(media.tracks$.value).toEqual([]);
});
it("does not match a member with two candidate identities to anyone else", async () => {
const b = await prepared();
const media = b.mediaFor(
@@ -540,11 +463,10 @@ describe("createLivekitBackend", () => {
(c) => c.connection.role === "subscriber",
);
expect(remote?.connection.transport).toEqual(otherTransport);
const transports = b.connections$.value.map(({ transport }) => transport);
expect(transports).toHaveLength(2);
expect(transports).toEqual(
expect.arrayContaining([bothTransport, otherTransport]),
);
expect(b.connections$.value.map(({ transport }) => transport)).toEqual([
bothTransport,
otherTransport,
]);
transport$.next(bob(bothTransport, [legacyId]).transport$.value);
await flushPromises();
+59 -89
View File
@@ -18,7 +18,6 @@ import {
filter,
firstValueFrom,
map,
NEVER,
type Observable,
of,
switchMap,
@@ -42,12 +41,17 @@ import {
type MediaBackendContext,
type TransportCapabilities,
} from "../api";
import { delegateDelayedLeave, type TransportLocator } from "./auth";
import {
chooseAuthFlow,
delegateDelayedLeave,
type TransportLocator,
} from "./auth";
import { type Connection } from "./Connection";
import {
ConnectionMap,
createConnectionMap$,
type TransportLocatorWithCsSupport,
keyFor,
type TransportKey,
} from "./ConnectionMap";
import {
LivekitConnectionFactory,
@@ -65,7 +69,7 @@ import { createLivekitLocalMedia } from "./LocalMedia";
export interface LivekitBackendOptions {
/**
* `getOpenIdToken` for the JWT service flow, the MSC4195 methods for the
* client-server API flow, `baseUrl` for the delegation handover.
* client-server API flow, `baseUrl` for the delegation probe and handover.
*/
client: Pick<
MatrixClient,
@@ -99,20 +103,12 @@ export function createLivekitBackend(
: [requestsOrMedia.requests, requestsOrMedia];
const keyProvider = createKeyProvider(encryptionSystem, mediaKeys$, logger);
const transports = createTransportRegistry(scope);
const localTransport$ =
new BehaviorSubject<TransportLocatorWithCsSupport | null>(null);
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const connectionFactory = new LivekitConnectionFactory(
client,
// The MSC defines no unstable feature flag. If the transport names a
// JWT service too, start over without the CS API.
() => {
const local = localTransport$.value;
if (local?.csApiUsable && "livekit_service_url" in local.transport)
localTransport$.next({ ...local, csApiUsable: false });
},
roomId,
slotId,
publish,
@@ -122,8 +118,7 @@ export function createLivekitBackend(
);
// A new map, in a scope of its own, whenever the local transport changes:
// the publisher role sits on one connection, and which one is fixed per map,
// as is whether the client-server API is usable
// the publisher role sits on one connection, and which one is fixed per map
const connectionMap$ = scope.behavior<Epoch<ConnectionMap>>(
mapScoped(scope, localTransport$, (mapScope, localTransport) =>
createConnectionMap$({
@@ -134,17 +129,13 @@ export function createLivekitBackend(
logger,
ownMembershipIdentity,
}),
).pipe(
switchMap(
// Nothing is looked up in an empty map, so how it is keyed is moot.
(map$) => map$ ?? of(new Epoch(new ConnectionMap(true))),
),
),
).pipe(switchMap((map$) => map$ ?? of(new Epoch(new ConnectionMap())))),
);
const localMedia_ = createLivekitLocalMedia({
scope,
connectionMap$,
localTransport$,
publish,
media,
audioOutputDeviceId$,
@@ -152,16 +143,15 @@ export function createLivekitBackend(
logger,
});
// Probed once: the answer cannot change within a session
const homeserverSupportsDelegation = supportsDelegation(
`${client.baseUrl}/_matrix/client/unstable/io.element.msc4195/rtc/livekit/delegate_delayed_leave`,
"homeserver",
logger,
);
const ownServerName = serverNameOf(ownMembershipIdentity.userId);
/**
* Sets `localTransport$`, the transport we publish on. As a side effect,
* this creates the connection map, which lets subscribing connections start,
* too.
*
* Resolves once the publisher connection holds its token and reports
* whether the service that issued it can take over the delayed leave.
*/
const prepareLocalTransport = async (
transport: Transport,
): Promise<TransportCapabilities> => {
@@ -172,46 +162,45 @@ export function createLivekitBackend(
ownMembershipIdentity.userId,
);
const locator: TransportLocator = { transport, serverName };
// A homeserver with the client-server API advertises a `url`.
localTransport$.next({ ...locator, csApiUsable: "url" in transport });
// The membership is only sent once the publisher connection holds its
// token, so that the LiveKit room exists before anyone subscribes to it:
// a subscriber lacks the permission to create it and would fail without
// retrying
const { flow } = await authenticated(localMedia_.connection$);
let canDelegate: Promise<boolean>;
if (serverName !== ownServerName) {
// Our homeserver only takes over leaves for its own SFUs
logger.info(
`Publishing on a remote SFU of ${serverName}, delegation is not possible`,
);
return { canDelegateDelayedLeave: false };
canDelegate = Promise.resolve(false);
} else {
// Check for support using the same auth flow that we intend to use later
const flow = chooseAuthFlow(transport);
canDelegate =
flow.kind === "openID"
? supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
)
: homeserverSupportsDelegation;
}
// Now that we are authenticated, check which flow was used so that we can
// use the same flow for delegation.
if (flow.kind === "csApi") {
// If the client-server authentication endpoint is available, the delegation
// endpoint is available, too. Both have been released together in lk-jwt-service.
return { canDelegateDelayedLeave: true };
}
// The OpenID flow was used but the lk-jwt-instance may still predate delegation. Check
// if the delegation endpoint is supported.
return {
canDelegateDelayedLeave: await supportsDelegation(
`${flow.serviceUrl}/delegate_delayed_leave`,
`transport ${flow.serviceUrl}`,
logger,
),
};
localTransport$.next(locator);
// The membership is only sent once the publisher connection holds its
// token, so that the LiveKit room exists before anyone subscribes to it:
// a subscriber lacks the permission to create it and would fail without
// retrying
const [, canDelegateDelayedLeave] = await Promise.all([
authenticated(localMedia_.connection$),
canDelegate,
]);
return { canDelegateDelayedLeave };
};
const delegateLeave = async (delayId: string): Promise<void> => {
const connection = localMedia_.connection$.value;
if (connection === null)
const local = localTransport$.value;
if (local === null)
throw new MatrixRTCError("No local transport to delegate the leave to");
await delegateDelayedLeave({
client,
membership: ownMembershipIdentity,
flow: connection.flow,
transport: local.transport,
roomId,
slotId,
delayId,
@@ -236,9 +225,7 @@ export function createLivekitBackend(
}
: undefined;
}),
distinctUntilChanged(
(a, b) => (a && transportKey(a)) === (b && transportKey(b)),
),
distinctUntilChanged((a, b) => (a && keyFor(a)) === (b && keyFor(b))),
),
);
transports.follow(memberScope, locator$);
@@ -305,31 +292,27 @@ export function createLivekitBackend(
};
}
/** Resolves with the connection once it holds its token; rejects with its error otherwise. */
/** Resolves once the connection holds its token; rejects with its error otherwise. */
async function authenticated(
connection$: Behavior<Connection | null>,
): Promise<Connection> {
const { connection, state } = await firstValueFrom(
): Promise<void> {
const state = await firstValueFrom(
connection$.pipe(
switchMap(
(connection) =>
connection?.state$.pipe(map((state) => ({ connection, state }))) ??
NEVER,
),
switchMap((connection) => connection?.state$ ?? of(null)),
filter(
({ state }) =>
state.state === "authenticated" ||
state.state === "error" ||
state.state === "stopped",
(state) =>
state !== null &&
(state.state === "authenticated" ||
state.state === "error" ||
state.state === "stopped"),
),
),
);
if (state.state === "error") throw state.error;
if (state.state === "stopped")
if (state?.state === "error") throw state.error;
if (state?.state === "stopped")
throw new MatrixRTCError(
"The local connection stopped before it was authenticated",
);
return connection;
}
function backendConnection$(
@@ -348,19 +331,6 @@ function backendConnection$(
);
}
/**
* The key used for a transport locator in the transport registry.
*
* Note that this is *not* the key used for folding locators into connections.
*/
function transportKey({ transport, serverName }: TransportLocator): string {
return JSON.stringify([
"url" in transport ? transport.url : null,
"livekit_service_url" in transport ? transport.livekit_service_url : null,
serverName,
]);
}
export interface TransportRegistry {
/** Keeps a member's transport registered for as long as its scope lives. */
follow(
@@ -380,7 +350,7 @@ export function createTransportRegistry(
scope: ObservableScope,
): TransportRegistry {
const counts = new Map<
string,
TransportKey,
{ locator: TransportLocator; count: number }
>();
const transports = new BehaviorSubject<TransportLocator[]>([]);
@@ -388,7 +358,7 @@ export function createTransportRegistry(
transports.next([...counts.values()].map(({ locator }) => locator));
const register = (locator: TransportLocator): (() => void) => {
const key = transportKey(locator);
const key = keyFor(locator);
const entry = counts.get(key) ?? { locator, count: 0 };
entry.count++;
if (entry.count === 1) {
@@ -23,11 +23,16 @@ import { FailToStartLivekitConnection, MatrixRTCError } from "../../errors";
import { Epoch, type ObservableScope } from "../../reactive/ObservableScope";
import { flushPromises, mockEmitter, testScope } from "../../utils/test";
import { MediaConnectionState } from "../api";
import { type TransportLocator } from "./auth";
import { type Connection, type ConnectionState } from "./Connection";
import { ConnectionMap } from "./ConnectionMap";
import { createLivekitLocalMedia } from "./LocalMedia";
import { exampleTransport } from "./test";
const localTransport: TransportLocator = {
transport: exampleTransport,
serverName: "example.org",
};
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -64,7 +69,7 @@ function fakeConnection(state: ConnectionState = connected): FakeConnection {
}
function mapOf(...connections: Connection[]): Epoch<ConnectionMap> {
const map = new ConnectionMap(true);
const map = new ConnectionMap();
for (const connection of connections) map.add(connection, []);
return new Epoch(map);
}
@@ -75,44 +80,46 @@ function setup(
): {
media: ReturnType<typeof createLivekitLocalMedia>;
connectionMap$: BehaviorSubject<Epoch<ConnectionMap>>;
localTransport$: BehaviorSubject<TransportLocator | null>;
audioOutputDeviceId$: BehaviorSubject<string | undefined>;
} {
const connectionMap$ = new BehaviorSubject(mapOf());
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const media = createLivekitLocalMedia({
scope,
connectionMap$: scope.behavior(connectionMap$),
localTransport$: scope.behavior(localTransport$),
publish,
audioOutputDeviceId$,
encryptionSystem: { kind: E2eeType.NONE },
logger,
});
return { media, connectionMap$, audioOutputDeviceId$ };
return { media, connectionMap$, localTransport$, audioOutputDeviceId$ };
}
describe("createLivekitLocalMedia", () => {
it("takes the publisher connection from the map once there is one", () => {
const { media, connectionMap$ } = setup();
it("finds the connection to the local transport once both are known", () => {
const { media, connectionMap$, localTransport$ } = setup();
const { connection } = fakeConnection();
const subscriber = {
...fakeConnection().connection,
role: "subscriber",
transport: { type: "livekit", livekit_service_url: "https://other" },
} as unknown as Connection;
expect(media.connection$.value).toBeNull();
expect(media.connectionState$.value).toBe(MediaConnectionState.Initialized);
connectionMap$.next(mapOf(subscriber, connection));
connectionMap$.next(mapOf(connection));
expect(media.connection$.value).toBeNull();
localTransport$.next(localTransport);
expect(media.connection$.value).toBe(connection);
expect(media.connectionState$.value).toBe(MediaConnectionState.Connected);
});
it("follows the connection's state", () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, state$ } = fakeConnection({ state: "authenticating" });
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
expect(media.connectionState$.value).toBe(MediaConnectionState.Preparing);
const error = new MatrixRTCError("no token");
@@ -121,9 +128,10 @@ describe("createLivekitLocalMedia", () => {
});
it("creates the tracks on the first publish and holds them back until then", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
await flushPromises();
expect(participant.setMicrophoneEnabled).not.toHaveBeenCalled();
expect(media.tracks$.value).toEqual([]);
@@ -140,9 +148,10 @@ describe("createLivekitLocalMedia", () => {
});
it("pauses the upstream while the member is not publishing", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
@@ -160,7 +169,7 @@ describe("createLivekitLocalMedia", () => {
});
it("resolves a publish made before the connection exists once it is up", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
let published: string | undefined;
const publishing = media
.publish({ source: "camera" })
@@ -170,6 +179,7 @@ describe("createLivekitLocalMedia", () => {
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await publishing;
@@ -183,9 +193,10 @@ describe("createLivekitLocalMedia", () => {
});
it("publishes a request at once on a started publisher", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
@@ -200,9 +211,10 @@ describe("createLivekitLocalMedia", () => {
});
it("rejects a publish the device refuses, and forgets the request", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
vi.mocked(participant.setCameraEnabled).mockRejectedValueOnce(
@@ -222,9 +234,10 @@ describe("createLivekitLocalMedia", () => {
});
it("publishes again on a new connection and stops the old tracks", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const first = fakeConnection();
connectionMap$.next(mapOf(first.connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
await media.publish({ source: "camera" });
@@ -250,9 +263,10 @@ describe("createLivekitLocalMedia", () => {
});
it("remembers a mute across connections", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const first = fakeConnection();
connectionMap$.next(mapOf(first.connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
@@ -271,9 +285,10 @@ describe("createLivekitLocalMedia", () => {
});
it("unpublishes a source, the screen share audio with its video", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
await media.publish({ source: "screenShare" });
@@ -287,9 +302,10 @@ describe("createLivekitLocalMedia", () => {
});
it("keeps the first failure to publish", async () => {
const { media, connectionMap$ } = setup();
const { media, connectionMap$, localTransport$ } = setup();
const { connection, participant } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
media.setPublishing(true);
await flushPromises();
expect(media.publishError$.value).toBeNull();
@@ -310,12 +326,14 @@ describe("createLivekitLocalMedia", () => {
});
it("plays on the device given, on the current room and the rooms to come", async () => {
const { media, connectionMap$, audioOutputDeviceId$ } = setup();
const { media, connectionMap$, localTransport$, audioOutputDeviceId$ } =
setup();
await media.setAudioOutputDeviceId("speaker");
expect(audioOutputDeviceId$.value).toBe("speaker");
const { connection, room } = fakeConnection();
connectionMap$.next(mapOf(connection));
localTransport$.next(localTransport);
await flushPromises();
await media.setAudioOutputDeviceId("headset");
+8 -3
View File
@@ -40,6 +40,7 @@ import {
type ObservableScope,
} from "../../reactive/ObservableScope";
import { type LocalMediaBackend, MediaConnectionState } from "../api";
import { type TransportLocator } from "./auth";
import { type Connection } from "./Connection";
import { type ConnectionMap } from "./ConnectionMap";
import {
@@ -53,8 +54,9 @@ import { toMediaConnectionState } from "./connectionState";
interface Props {
scope: ObservableScope;
/** Holds the connection we publish on once the local transport is known. */
connectionMap$: Behavior<Epoch<ConnectionMap>>;
/** The transport we publish on; null until the session has found it. */
localTransport$: Behavior<TransportLocator | null>;
publish: PublishRequest[];
/** Tracks the host captured ahead of the join; the publisher takes them over. */
media?: LocalMedia;
@@ -78,6 +80,7 @@ export interface LivekitLocalMedia extends LocalMediaBackend {
export function createLivekitLocalMedia({
scope,
connectionMap$,
localTransport$,
publish: initialRequests,
media,
audioOutputDeviceId$,
@@ -87,8 +90,10 @@ export function createLivekitLocalMedia({
const logger = parentLogger.getChild("[LocalMedia]");
const connection$ = scope.behavior(
connectionMap$.pipe(
map(({ value: connections }) => connections.getPublisherConnection()),
combineLatest(
[connectionMap$, localTransport$],
({ value: connections }, transport) =>
transport && connections.getConnectionForTransport(transport),
),
);
@@ -14,6 +14,7 @@ import {
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
import { serverNameOfTransport } from "../../utils/serverName";
import { isCsApiUnavailable } from "./auth";
import * as csApi from "./auth/csApi";
import { decodeSFUJWTPayload } from "./auth/types";
@@ -89,7 +90,7 @@ export async function findRemotePublishLivekitTransport({
continue;
}
} catch (e) {
if (csApi.isCsApiUnavailable(e)) {
if (isCsApiUnavailable(e)) {
// Without the endpoint no further candidate can work
logger.warn(
`Cannot use the MSC4195 get_token endpoint (${e}), so no remote SFU can be used`,
+1 -63
View File
@@ -5,12 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
ConnectionError,
HTTPError,
type MatrixClient,
MatrixError,
} from "matrix-js-sdk";
import { ConnectionError, HTTPError, type MatrixClient } from "matrix-js-sdk";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
import { doNetworkOperationWithRetry } from "../../../utils/network";
@@ -25,63 +20,6 @@ function isNetworkError(e: unknown): boolean {
return e instanceof HTTPError || e instanceof ConnectionError;
}
/**
* Whether an error means the homeserver does not implement the MSC4195
* endpoints. Such a homeserver answers with whatever it uses for unknown
* routes (Synapse: 404 with `M_UNRECOGNIZED`), so any 404 counts.
*/
export function isCsApiUnavailable(e: unknown): boolean {
const answer = unwrapErrorDetails(e);
return (
answer !== undefined &&
(answer.status === 404 ||
answer.errcode === "M_NOT_FOUND" ||
answer.errcode === "M_UNRECOGNIZED")
);
}
/**
* Tries to unwrap the details from an unknown error object, regardless of whether
* it came from the Widget API or not.
*/
function unwrapErrorDetails(
e: unknown,
): { status?: number; errcode?: string } | undefined {
// If the error is an instance of `MatrixError`, take its details directly.
if (e instanceof MatrixError) {
return { status: e.httpStatus, errcode: e.errcode };
}
// If the error originated from the widget API, try to extract the bundled
// Matrix API error. We identify the widget's `WidgetApiResponseError` by
// the shape of its payload to avoid making the SDK dependent on the widget
// API. This isn't great, but we'll drop this branch anyway once we eliminate
// usage of the widget API.
if (e instanceof Error && "data" in e) {
const relayed = (
e as {
data?: {
matrix_api_error?: {
http_status?: unknown;
response?: { errcode?: unknown };
};
};
}
).data?.matrix_api_error;
if (typeof relayed === "object" && relayed !== null) {
const { http_status: status, response } = relayed;
const errcode = response?.errcode;
return {
status: typeof status === "number" ? status : undefined,
errcode: typeof errcode === "string" ? errcode : undefined,
};
}
}
// We're not able to extract any details from this error.
return undefined;
}
export type ClientGetTokenParts = Pick<MatrixClient, "getLivekitToken">;
export interface GetSFUConfigParams {
+101 -144
View File
@@ -20,13 +20,7 @@ import {
} from "../../../utils/test-fixtures";
import type * as csApi from "./csApi";
import type * as openID from "./openID";
import {
type AuthFlow,
authenticateWithTransport,
chooseAuthFlow,
delegateDelayedLeave,
getSFUConfig,
} from ".";
import { chooseAuthFlow, delegateDelayedLeave, getSFUConfig } from ".";
const aliceId = `${aliceUserId}:${aliceDeviceId}`;
const csApiJWTToken = createJWTToken(aliceId, "via CS API");
@@ -73,9 +67,6 @@ const urlAndServiceUrlTransport: UnstableLivekitTransport = {
...serviceUrlTransport,
};
const viaCsApi: AuthFlow = { kind: "csApi", url: "wss://livekit.example.org" };
const viaOpenID: AuthFlow = { kind: "openID", serviceUrl };
/** The JWT service, answering each endpoint with a token that names it. */
function mockJWTService(): void {
fetchMock.post(`${serviceUrl}/sfu/get`, {
@@ -109,9 +100,11 @@ describe("getSFUConfig", () => {
logger,
};
it("uses the CS API for the CS API flow", async () => {
it("uses CS API with url transport", async () => {
mockJWTService();
expect(await getSFUConfig({ ...defaultParams, flow: viaCsApi })).toEqual(
expect(
await getSFUConfig({ ...defaultParams, transport: urlTransport }),
).toEqual(
expect.objectContaining({
jwt: csApiJWTToken,
livekitAlias: "via CS API",
@@ -127,19 +120,21 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("reports the CS API missing where the homeserver lacks the endpoint, without falling back", async () => {
it("does not fall back to OpenID with url transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the JWT service for the OpenID flow", async () => {
it("uses OpenID with livekit_service_url transport", async () => {
mockJWTService();
expect(await getSFUConfig({ ...defaultParams, flow: viaOpenID })).toEqual(
expect(
await getSFUConfig({ ...defaultParams, transport: serviceUrlTransport }),
).toEqual(
expect.objectContaining({
jwt: defaultJWTToken,
livekitAlias: "via default endpoint",
@@ -149,141 +144,80 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
it("does not report the CS API missing where the homeserver refuses the request", async () => {
mockJWTService();
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
});
it("reports the CS API missing for another homeserver's transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(
new MatrixError({ errcode: "M_UNRECOGNIZED" }, 404),
);
await expect(
getSFUConfig({
...defaultParams,
serverName: "elsewhere.org",
flow: viaCsApi,
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(jwtServiceCalls()).toEqual([]);
});
it("reports the CS API missing where a widget host relays the homeserver's not found", async () => {
mockJWTService();
// The widget API's WidgetApiResponseError arrives in a minified build.
const relayed = Object.assign(new Error("Unrecognized request"), {
name: "n",
data: {
matrix_api_error: {
http_status: 404,
response: { errcode: "M_UNRECOGNIZED" },
},
},
});
client.getLivekitToken.mockRejectedValueOnce(relayed);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(jwtServiceCalls()).toEqual([]);
});
it.each([
["a token that does not decode", { jwt: "not a token" }],
["an error of our own", new TypeError("oops")],
])("does not judge the CS API by %s", async (_what, outcome) => {
mockJWTService();
if (outcome instanceof Error)
client.getLivekitToken.mockRejectedValueOnce(outcome);
else client.getLivekitToken.mockResolvedValueOnce(outcome);
await expect(
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.not.toBeInstanceOf(NoMatrix2AuthorizationService);
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the CS API when publishing through the CS API flow", async () => {
it("uses OpenID when subscribing with url + livekit_service_url transport", async () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
flow: viaCsApi,
transport: urlAndServiceUrlTransport,
}),
).toEqual(
expect.objectContaining({
jwt: defaultJWTToken,
livekitAlias: "via default endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
it("surfaces the widget host's refusal with url transport", async () => {
mockJWTService();
const error = new Error(
"The rtc_livekit_get_token action is not supported by the client.",
);
client.getLivekitToken.mockRejectedValueOnce(error);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(error);
expect(jwtServiceCalls()).toEqual([]);
});
it("uses CS API when publishing with url transport", async () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
transport: urlTransport,
role: "publisher",
}),
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
});
describe("authenticateWithTransport", () => {
const defaultParams = {
client,
membership,
serverName: "example.org",
role: "subscriber" as const,
roomId,
slotId,
logger,
};
it("uses CS API with url + livekit_service_url transport", async () => {
mockJWTService();
expect(
await authenticateWithTransport({
...defaultParams,
transport: urlAndServiceUrlTransport,
}),
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(jwtServiceCalls()).toEqual([]);
});
it.each([
["subscriber", "/get_token", defaultJWTToken],
["publisher", "/sfu/get", legacyJWTToken],
] as const)(
"falls back to OpenID as %s where the homeserver lacks the endpoint",
async (role, endpoint, jwt) => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
expect(
await authenticateWithTransport({
...defaultParams,
transport: urlAndServiceUrlTransport,
role,
}),
).toEqual(expect.objectContaining({ jwt }));
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(jwtServiceCalls()).toEqual([endpoint]);
},
);
it("does not fall back with url transport", async () => {
it("does not fall back to OpenID when publishing with url transport", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
authenticateWithTransport({ ...defaultParams, transport: urlTransport }),
getSFUConfig({
...defaultParams,
transport: urlTransport,
role: "publisher",
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back where the homeserver refuses the request", async () => {
it("uses the legacy OpenID endpoint when publishing with url + livekit_service_url transport", async () => {
mockJWTService();
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
authenticateWithTransport({
// Subscribers predating MSC4195 expect a legacy participant identity from
// anyone advertising a membership, which only the JWT service assigns
expect(
await getSFUConfig({
...defaultParams,
transport: urlAndServiceUrlTransport,
role: "publisher",
}),
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
).toEqual(
expect.objectContaining({
jwt: legacyJWTToken,
livekitAlias: "via legacy endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/sfu/get"]);
});
});
@@ -308,9 +242,9 @@ describe("delegateDelayedLeave", () => {
return { delay_id, delay_timeout, delay_cs_api_url };
}
it("uses the CS API for the CS API flow", async () => {
it("uses CS API with url transport", async () => {
mockJWTService();
await delegateDelayedLeave({ ...defaultParams, flow: viaCsApi });
await delegateDelayedLeave({ ...defaultParams, transport: urlTransport });
expect(client.delegateDelayedLeave).toHaveBeenCalledWith({
url: urlTransport.url,
room_id: roomId,
@@ -321,19 +255,37 @@ describe("delegateDelayedLeave", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back to the JWT service from the CS API flow", async () => {
it("does not fall back to OpenID with url transport", async () => {
mockJWTService();
client.delegateDelayedLeave.mockRejectedValueOnce(unsupportedError);
await expect(
delegateDelayedLeave({ ...defaultParams, flow: viaCsApi }),
delegateDelayedLeave({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow();
expect(client.delegateDelayedLeave).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the JWT service for the OpenID flow", async () => {
it("uses OpenID with livekit_service_url transport", async () => {
mockJWTService();
await delegateDelayedLeave({ ...defaultParams, flow: viaOpenID });
await delegateDelayedLeave({
...defaultParams,
transport: serviceUrlTransport,
});
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
delay_timeout: 3_600_000,
delay_cs_api_url: client.baseUrl,
});
});
it("uses OpenID with url + livekit_service_url transport", async () => {
mockJWTService();
// Must match the flow that got the token, so the identities line up
await delegateDelayedLeave({
...defaultParams,
transport: urlAndServiceUrlTransport,
});
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
@@ -345,16 +297,21 @@ describe("delegateDelayedLeave", () => {
describe("chooseAuthFlow", () => {
it.each([
["url", urlTransport, true, viaCsApi],
["url", urlTransport, false, viaCsApi],
["livekit_service_url", serviceUrlTransport, true, viaOpenID],
["livekit_service_url", serviceUrlTransport, false, viaOpenID],
["url + livekit_service_url", urlAndServiceUrlTransport, true, viaCsApi],
["url + livekit_service_url", urlAndServiceUrlTransport, false, viaOpenID],
["url", urlTransport, { kind: "csApi", url: urlTransport.url }],
[
"livekit_service_url",
serviceUrlTransport,
{ kind: "openID", serviceUrl },
],
[
"url + livekit_service_url",
urlAndServiceUrlTransport,
{ kind: "openID", serviceUrl },
],
] as const)(
"chooses the flow for a %s transport with the CS API usable: %s",
(_shape, transport, csApiUsable, flow) => {
expect(chooseAuthFlow(transport, csApiUsable)).toEqual(flow);
"chooses the flow for a %s transport as %s",
(_shape, transport, flow) => {
expect(chooseAuthFlow(transport)).toEqual(flow);
},
);
});
+54 -61
View File
@@ -6,9 +6,13 @@ Please see LICENSE in the repository root for full details.
*/
/**
* Authentication with a LiveKit transport.
* Authentication with a LiveKit transport: the MSC4195 client-server API
* through our homeserver for a transport with an SFU `url`, the OpenID flow
* against the JWT service for one with a `livekit_service_url`, and the
* choice between them where a transport carries both.
*/
import { ConnectionError, MatrixError } from "matrix-js-sdk";
import { type Logger } from "matrix-js-sdk/lib/logger";
import { type UnstableLivekitTransport } from "matrix-js-sdk/lib/matrixrtc";
import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/EncryptionManager";
@@ -22,11 +26,37 @@ export type { ClientOpenIDParts } from "./openID";
export type { ClientGetTokenParts, ClientDelegationParts } from "./csApi";
export type * from "./types";
/**
* Whether an error means the homeserver does not implement the MSC4195
* endpoints. The MSC says `M_NOT_FOUND`; a homeserver without support answers
* with whatever it uses for unknown routes (Synapse: 404 with
* `M_UNRECOGNIZED`), so any 404 counts.
*/
function isEndpointUnsupported(e: unknown): boolean {
return (
e instanceof MatrixError &&
(e.httpStatus === 404 ||
e.errcode === "M_NOT_FOUND" ||
e.errcode === "M_UNRECOGNIZED")
);
}
/**
* Whether an error means the MSC4195 client-server API cannot be used from
* here: the homeserver does not implement it, or the request never reached
* the homeserver because a widget host does not expose the endpoint
* (MSC4533), which the widget API reports as a plain error. A connection
* error is neither: the endpoint may well exist.
*/
export function isCsApiUnavailable(e: unknown): boolean {
if (isEndpointUnsupported(e)) return true;
return !(e instanceof MatrixError) && !(e instanceof ConnectionError);
}
export interface GetSFUConfigParams {
client: csApi.ClientGetTokenParts & openID.ClientOpenIDParts;
membership: CallMembershipIdentityParts;
/** The flow to authenticate with, as chosen by {@link chooseAuthFlow}. */
flow: AuthFlow;
transport: UnstableLivekitTransport;
/** The homeserver the transport belongs to. */
serverName: string;
roomId: string;
@@ -36,22 +66,20 @@ export interface GetSFUConfigParams {
}
/**
* Gets an {@link SFUConfig} for connecting to a transport through the given
* auth flow.
*
* @throws {@link NoMatrix2AuthorizationService} if the client-server API flow
* finds the API missing.
* Gets an {@link SFUConfig} appropriate for connecting to a given transport,
* using whichever auth flow is appropriate.
*/
export async function getSFUConfig({
client,
membership,
flow,
transport,
serverName,
roomId,
slotId,
role,
logger,
}: GetSFUConfigParams): Promise<SFUConfig> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "openID") {
return await openID.getSFUConfig({
client,
@@ -73,14 +101,10 @@ export async function getSFUConfig({
slotId,
});
} catch (e) {
if (csApi.isCsApiUnavailable(e)) {
logger.warn(
if (isEndpointUnsupported(e)) {
logger.error(
`Homeserver does not support the MSC4195 get_token endpoint, cannot get token for transport ${flow.url}`,
);
// This is our own homeserver's answer. as per MSC4195, only 403 /
// M_FORBIDDEN and 400 / M_INVALID_PARAM are forwarded from the remote
// server. Any other remote error becomes 502 / M_UNKNOWN on the
// client-server API.
throw new NoMatrix2AuthorizationService(e as Error);
}
throw e;
@@ -88,40 +112,11 @@ export async function getSFUConfig({
}
}
export type AuthenticateWithTransportParams = Omit<
GetSFUConfigParams,
"flow"
> & { transport: UnstableLivekitTransport };
/**
* Authenticates with a transport once, outside any session. This automatically
* falls back from the client-server API flow to the OpenID flow if needed and
* possible.
*
* @throws {@link NoMatrix2AuthorizationService} if the client-server API is missing
* but the transport does not allow falling back to the OpenID flow.
*/
export async function authenticateWithTransport({
transport,
...params
}: AuthenticateWithTransportParams): Promise<SFUConfig> {
try {
const flow = chooseAuthFlow(transport, true);
return await getSFUConfig({ ...params, flow });
} catch (e) {
const flow = chooseAuthFlow(transport, false);
// Nothing else to try unless the API is missing and there is a JWT service
if (!(e instanceof NoMatrix2AuthorizationService) || flow.kind !== "openID")
throw e;
return await getSFUConfig({ ...params, flow });
}
}
export interface DelegateDelayedLeaveParams {
client: csApi.ClientDelegationParts & openID.ClientOpenIDParts;
membership: CallMembershipIdentityParts;
/** The flow that issued the token we publish with. */
flow: AuthFlow;
/** The transport we publish on. */
transport: UnstableLivekitTransport;
roomId: string;
slotId: string;
delayId: string;
@@ -138,13 +133,14 @@ export interface DelegateDelayedLeaveParams {
export async function delegateDelayedLeave({
client,
membership,
flow,
transport,
roomId,
slotId,
delayId,
delayTimeoutMs,
logger,
}: DelegateDelayedLeaveParams): Promise<void> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "csApi") {
try {
await csApi.delegateDelayedLeave({
@@ -156,7 +152,7 @@ export async function delegateDelayedLeave({
delayId,
});
} catch (e) {
if (csApi.isCsApiUnavailable(e))
if (isEndpointUnsupported(e))
logger.error(
"Server misconfigured: transport contains a 'url' field but server does not support the MSC4195 delegate_delayed_leave endpoint",
);
@@ -185,21 +181,18 @@ export type AuthFlow =
| { kind: "openID"; serviceUrl: string };
/**
* Chooses which auth flow to use for a given transport.
* Chooses which auth flow to use for a given transport. For now this returns a
* single auth flow, with no provision for a fallback behavior.
*/
export function chooseAuthFlow(
transport: UnstableLivekitTransport,
csApiUsable: boolean,
): AuthFlow {
// If we only have url, we have no choice but to use the CS API.
export function chooseAuthFlow(transport: UnstableLivekitTransport): AuthFlow {
if ("url" in transport && !("livekit_service_url" in transport))
return { kind: "csApi", url: transport.url };
// If we have both url and livekit_service_url, prefer the CS API if it is usable.
if ("url" in transport && csApiUsable)
return { kind: "csApi", url: transport.url };
// If the CS API is not usable or we only have livekit_service_url, fall back
// to using the OpenID flow.
// All other transports use the OpenID flow, even if they contain a `url`.
// This is necessary since the auth flow determines the participant identity
// format, and we still have older clients out in the wild which would not yet
// know to look for a hashed participant identity in case `url` is present in
// someone else's transport.
// TODO: Once users have updated their clients, choose the CS API flow if
// available, keeping OpenID as a fallback.
return { kind: "openID", serviceUrl: transport.livekit_service_url };
}
+13 -15
View File
@@ -7,33 +7,31 @@ Please see LICENSE in the repository root for full details.
import { afterEach, expect, test, vi } from "vitest";
import { testScope } from "./utils/test";
const createStandaloneClientSession$ = vi.hoisted(() => vi.fn());
vi.mock("./state/StandaloneClientSession", () => ({
createStandaloneClientSession$,
}));
const initSPA = vi.hoisted(() => vi.fn());
vi.mock("./utils/spa", () => ({ initSPA }));
afterEach(() => {
vi.unstubAllEnvs();
vi.resetModules();
createStandaloneClientSession$.mockReset();
initSPA.mockReset();
});
test("the app restores its own session", async () => {
vi.stubEnv("VITE_PACKAGE", "full");
const { loadStandaloneClientSession } = await import("./App");
const scope = testScope();
const session = {};
createStandaloneClientSession$.mockReturnValue(session);
const { loadStandaloneClient } = await import("./App");
const loadSession = vi.fn();
const clearSession = vi.fn();
initSPA.mockResolvedValue(null);
await expect(loadStandaloneClientSession!(scope)).resolves.toBe(session);
expect(createStandaloneClientSession$).toHaveBeenCalledWith(scope);
await expect(loadStandaloneClient!(loadSession, clearSession)).resolves.toBe(
null,
);
expect(initSPA).toHaveBeenCalledWith(loadSession, clearSession);
});
test("the embedded package has no session of its own", async () => {
vi.stubEnv("VITE_PACKAGE", "embedded");
const { loadStandaloneClientSession } = await import("./App");
const { loadStandaloneClient } = await import("./App");
expect(loadStandaloneClientSession).toBeUndefined();
expect(loadStandaloneClient).toBeUndefined();
});
+33 -43
View File
@@ -23,13 +23,14 @@ import {
import * as Sentry from "@sentry/react";
import { TooltipProvider } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/lib/logger";
import { type MatrixClient } from "matrix-js-sdk";
import { I18nextProvider } from "react-i18next";
import { HomePage } from "./home/HomePage";
import { LoginPage } from "./auth/LoginPage";
import { RegisterPage } from "./auth/RegisterPage";
import { RoomPage } from "./room/RoomPage";
import { ClientProvider } from "./ClientContext";
import { type ClientLoader, ClientProvider } from "./ClientContext";
import { ErrorPage, LoadingPage } from "./FullScreenView";
import { Initializer } from "./initializer";
import { type WidgetHelpers } from "./widget";
@@ -53,26 +54,22 @@ import {
} from "./HostBridge";
import { useInitial } from "./useInitial";
import { LeaveToHomeProvider } from "./LeaveToHomeContext";
import { DisconnectedProvider } from "./DisconnectedContext";
import { type ClientManager, type ClientSession } from "./state/ClientSession";
import { type ObservableScope } from "./state/ObservableScope";
const SentryRoute = Sentry.withSentryReactRouterV7Routing(Route);
// Element Call's own session, for when no host supplies a client.
// - Imported on demand, so that a widget, which gets its client from the host,
// never downloads it.
// - Passed in here, not imported by ClientProvider: this module is only in the
// app builds, so the client setup and the store worker behind it stay out of
// the component package (see the `loadClient` prop).
// - Imported on demand, as it was before, so that a widget, which gets its
// client from the host, never downloads it.
// - Module-level, so that the provider's effect sees one stable loader.
// - None in the embedded package, which only runs as a widget: the constant
// condition lets its build drop the client setup and the store worker.
export const loadStandaloneClientSession:
| ((scope: ObservableScope) => Promise<ClientSession & ClientManager>)
| undefined =
export const loadStandaloneClient: ClientLoader | undefined =
import.meta.env.VITE_PACKAGE === "embedded"
? undefined
: async (scope) =>
(
await import("./state/StandaloneClientSession")
).createStandaloneClientSession$(scope);
: async (...args) => (await import("./utils/spa")).initSPA(...args);
interface SimpleProviderProps {
children: JSX.Element;
@@ -148,47 +145,40 @@ export const App: FC<Props> = ({ vm, widget }) => {
.catch(logger.error);
});
const content = loaded ? (
<DisconnectedProvider value={vm.disconnected$}>
<ClientProvider session={vm.clientSession}>
// As a widget, the client comes from the host over the widget API. Standalone,
// Element Call finds one itself, so there is nothing to wait for here.
const [widgetClient, setWidgetClient] = useState<MatrixClient | undefined>(
undefined,
);
useEffect(() => {
if (widget === null) return;
widget.client
.then(setWidgetClient)
.catch((e) => logger.error("Failed to obtain the host's client", e));
}, [widget]);
const clientReady = widget === null || widgetClient !== undefined;
const content =
loaded && clientReady ? (
<ClientProvider client={widgetClient} loadClient={loadStandaloneClient}>
<MediaDevicesContext value={vm.mediaDevices}>
<BackgroundEffectsProvider effects={vm.backgroundEffects}>
<Sentry.ErrorBoundary
fallback={(error) => <ErrorPage error={error} />}
>
<Routes>
<SentryRoute
path="/"
element={<HomePage clientManager={vm.clientManager} />}
/>
{/* A host's session is signed in to by the host, never here */}
{vm.clientManager !== null && (
<>
<SentryRoute
path="/login"
element={<LoginPage clientManager={vm.clientManager} />}
/>
<SentryRoute
path="/register"
element={
<RegisterPage clientManager={vm.clientManager} />
}
/>
</>
)}
<SentryRoute
path="*"
element={<RoomPage clientManager={vm.clientManager} />}
/>
<SentryRoute path="/" element={<HomePage />} />
<SentryRoute path="/login" element={<LoginPage />} />
<SentryRoute path="/register" element={<RegisterPage />} />
<SentryRoute path="*" element={<RoomPage />} />
</Routes>
</Sentry.ErrorBoundary>
</BackgroundEffectsProvider>
</MediaDevicesContext>
</ClientProvider>
</DisconnectedProvider>
) : (
<LoadingPage />
);
) : (
<LoadingPage />
);
return (
<I18nextProvider i18n={i18n}>
+16 -2
View File
@@ -12,7 +12,6 @@ import { type FC, type PropsWithChildren } from "react";
import { ClientContextProvider } from "./ClientContext";
import { Avatar } from "./Avatar";
import { hostClientSession } from "./state/ClientSession";
import { mockMatrixRoomMember, mockRtcMembership } from "./utils/test";
import {
type HostBridge,
@@ -27,7 +26,22 @@ const TestComponent: FC<
}>
> = ({ client, hostBridge = nullHostBridge, children }) => {
return (
<ClientContextProvider value={hostClientSession(client)}>
<ClientContextProvider
value={{
state: "valid",
disconnected: false,
supportedFeatures: {
reactions: true,
},
setClient: vi.fn(),
authenticated: {
client,
isPasswordlessUser: true,
changePassword: vi.fn(),
logout: vi.fn(),
},
}}
>
<HostBridgeProvider value={hostBridge}>{children}</HostBridgeProvider>
</ClientContextProvider>
);
+12 -8
View File
@@ -15,7 +15,7 @@ import {
import { Avatar as CompoundAvatar } from "@vector-im/compound-web";
import { type MatrixClient } from "matrix-js-sdk";
import { useClient } from "./ClientContext";
import { useClientState } from "./ClientContext";
import { useHostBridge } from "./HostBridge";
export enum Size {
@@ -44,7 +44,7 @@ export interface Props {
}
export function getAvatarUrl(
client: Pick<MatrixClient, "mxcUrlToHttp">,
client: MatrixClient,
mxcUrl: string | null,
avatarSize = 96,
): string | null {
@@ -74,7 +74,7 @@ export const Avatar: FC<Props> = ({
style,
...props
}) => {
const client = useClient();
const clientState = useClientState();
const hostBridge = useHostBridge();
const sizePx = useMemo(
@@ -87,7 +87,7 @@ export const Avatar: FC<Props> = ({
const [avatarUrl, setAvatarUrl] = useState<string | undefined>(undefined);
// In theory, a change in `client` or `sizePx` could run extra media
// In theory, a change in `clientState` or `sizePx` could run extra media
// downloads, but in practice they should be stable long before this code runs.
useEffect(() => {
if (!src) {
@@ -99,8 +99,12 @@ export const Avatar: FC<Props> = ({
if (hostBridge.downloadMedia) {
blob = hostBridge.downloadMedia(src);
} else if (client && sizePx) {
blob = getAvatarFromServer(client, src, sizePx);
} else if (
clientState?.state === "valid" &&
clientState.authenticated?.client &&
sizePx
) {
blob = getAvatarFromServer(clientState.authenticated.client, src, sizePx);
} else {
setAvatarUrl(undefined);
return;
@@ -129,7 +133,7 @@ export const Avatar: FC<Props> = ({
URL.revokeObjectURL(objectUrl);
}
};
}, [client, hostBridge, src, sizePx]);
}, [clientState, hostBridge, src, sizePx]);
return (
<CompoundAvatar
@@ -145,7 +149,7 @@ export const Avatar: FC<Props> = ({
};
async function getAvatarFromServer(
client: Pick<MatrixClient, "mxcUrlToHttp" | "getAccessToken">,
client: MatrixClient,
src: string,
sizePx: number,
): Promise<Blob> {
-3
View File
@@ -38,8 +38,6 @@ type CallRoomPart = Pick<
| "getJoinRule"
// Raised hands already in the room
| "relations"
// The encryption system, where no shared key is in use
| "hasEncryptionStateEvent"
>;
/**
@@ -75,6 +73,5 @@ export function createCallMatrixBackend(
get relations() {
return room.relations;
},
hasEncryptionStateEvent: room.hasEncryptionStateEvent.bind(room),
};
}
+73 -80
View File
@@ -6,23 +6,16 @@ Please see LICENSE in the repository root for full details.
*/
import { expect, test, vi } from "vitest";
import { act, render, renderHook } from "@testing-library/react";
import { render, waitFor } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { type FC } from "react";
import { BehaviorSubject } from "rxjs";
import {
type ClientLoader,
ClientProvider,
useClientSessionState,
useLoggedInSpaClient,
useClientState,
} from "./ClientContext";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
hostClientSession,
} from "./state/ClientSession";
const mockClient = (userId = "@alice:example.org"): MatrixClient =>
({
@@ -35,47 +28,67 @@ const mockClient = (userId = "@alice:example.org"): MatrixClient =>
/** Reports what the context says, so a test can assert on it. */
const ShowClientState: FC = () => {
const state = useClientSessionState();
switch (state.state) {
case "signedIn":
return <span>{state.client.getUserId()}</span>;
case "signedOut":
return <span>unauthenticated</span>;
default:
return <span>{state.state}</span>;
}
const state = useClientState();
if (state === undefined) return <span>loading</span>;
if (state.state === "error") return <span>error</span>;
return (
<span>{state.authenticated?.client.getUserId() ?? "unauthenticated"}</span>
);
};
const renderProvider = (
session: ClientSession,
children = <ShowClientState />,
): ReturnType<typeof render> =>
render(
test("uses a client supplied by the host without waiting", () => {
const client = mockClient();
const { container } = render(
<BrowserRouter>
<ClientProvider session={session}>{children}</ClientProvider>
<ClientProvider client={client}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
test("uses a client supplied by the host without waiting", () => {
const { container } = renderProvider(hostClientSession(mockClient()));
// Available on the very first render: a supplied client needs no session
// restoring, so there is no loading state to pass through.
expect(container.textContent).toBe("@alice:example.org");
});
test("does not claim exclusive use of storage when given a client", () => {
// The channel is created when the module loads, so spy on the prototype
// rather than trying to replace the global.
const postMessage = vi.spyOn(BroadcastChannel.prototype, "postMessage");
render(
<BrowserRouter>
<ClientProvider client={mockClient()}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
// The broadcast shuts down other instances to protect Element Call's own
// stores. A host's client brings its own, so there is nothing to protect.
expect(postMessage).not.toHaveBeenCalled();
postMessage.mockRestore();
});
test("follows the client when the host swaps it", () => {
const { container, rerender } = renderProvider(
hostClientSession(mockClient()),
const first = mockClient();
const second = mockClient("@bob:example.org");
const { container, rerender } = render(
<BrowserRouter>
<ClientProvider client={first}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
expect(container.textContent).toBe("@alice:example.org");
// A host that re-authenticates hands us a new client on a mounted component
rerender(
<BrowserRouter>
<ClientProvider
session={hostClientSession(mockClient("@bob:example.org"))}
>
<ClientProvider client={second}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
@@ -84,58 +97,38 @@ test("follows the client when the host swaps it", () => {
expect(container.textContent).toBe("@bob:example.org");
});
test("follows a session of its own as it is restored", () => {
const state$ = new BehaviorSubject<ClientSessionState>({ state: "loading" });
const { container } = renderProvider({ state$ });
test("finds a client of its own when the host supplies none", async () => {
const client = mockClient();
const loadClient = vi
.fn<ClientLoader>()
.mockResolvedValue({ client, passwordlessUser: true });
const { container } = render(
<BrowserRouter>
<ClientProvider loadClient={loadClient}>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
// Nothing to show until a session has been restored or created
expect(container.textContent).toBe("loading");
act(() =>
state$.next({
state: "signedIn",
client: mockClient(),
passwordlessUser: true,
}),
await waitFor(() => expect(container.textContent).toBe("@alice:example.org"));
// Given the session store to restore from and to clear on a stale session
expect(loadClient).toHaveBeenCalledWith(
expect.any(Function),
expect.any(Function),
);
expect(container.textContent).toBe("@alice:example.org");
});
test("has no one signed in when the session says so", () => {
const { container } = renderProvider({
state$: new BehaviorSubject<ClientSessionState>({ state: "signedOut" }),
});
expect(container.textContent).toBe("unauthenticated");
});
test("has no one signed in when given neither a client nor a way to load one", async () => {
const { container } = render(
<BrowserRouter>
<ClientProvider>
<ShowClientState />
</ClientProvider>
</BrowserRouter>,
);
test("shows the session's error in place of its children", () => {
const { container } = renderProvider({
state$: new BehaviorSubject<ClientSessionState>({
state: "error",
error: new Error("Opened elsewhere"),
}),
});
// The error page, not the children
expect(container.textContent).not.toContain("error");
expect(container.textContent).toContain("Something went wrong");
});
test("has no SPA client where the session is a host's", () => {
const { result } = renderHook(() => useLoggedInSpaClient(null));
expect(result.current).toBeUndefined();
});
test("gives the SPA's pages its client manager's client, whole", () => {
const client = mockClient();
const client$ = new BehaviorSubject<MatrixClient | undefined>(undefined);
const manager: ClientManager = {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$,
};
const { result } = renderHook(() => useLoggedInSpaClient(manager));
expect(result.current).toBeUndefined();
act(() => client$.next(client));
expect(result.current).toBe(client);
await waitFor(() => expect(container.textContent).toBe("unauthenticated"));
});
+416 -42
View File
@@ -5,76 +5,450 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type FC, useEffect, createContext, use, type JSX } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import {
type FC,
useCallback,
useEffect,
useState,
createContext,
use,
useRef,
useMemo,
type JSX,
} from "react";
import { logger } from "matrix-js-sdk/lib/logger";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
import { ErrorPage } from "./FullScreenView";
import { PosthogAnalytics } from "./analytics/PosthogAnalytics";
import { useBehavior } from "./useBehavior";
import { constant } from "./state/Behavior";
import { useHostBridge } from "./HostBridge";
import { useLeaveToHome } from "./LeaveToHomeContext";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
signedOutClientSession,
type SuppliedClient,
} from "./state/ClientSession";
PosthogAnalytics,
RegistrationType,
} from "./analytics/PosthogAnalytics";
import { useEventTarget } from "./useEvents";
import { OpenElsewhereError } from "./RichError";
declare global {
interface Window {
matrixclient: SuppliedClient;
matrixclient: MatrixClient;
passwordlessUser: boolean;
}
}
// Without a provider, no one is signed in
const ClientContext = createContext<ClientSession>(signedOutClientSession);
export type ClientState = ValidClientState | ErrorState;
export type ValidClientState = {
state: "valid";
authenticated?: AuthenticatedClient;
// 'Disconnected' rather than 'connected' because it tracks specifically
// whether the client is supposed to be connected but is not
disconnected: boolean;
supportedFeatures: {
reactions: boolean;
};
setClient: (client: MatrixClient, session: Session) => void;
};
export type AuthenticatedClient = {
client: MatrixClient;
isPasswordlessUser: boolean;
changePassword: (password: string) => Promise<void>;
logout: () => void;
};
export type ErrorState = {
state: "error";
error: Error;
};
const ClientContext = createContext<ClientState | undefined>(undefined);
export const ClientContextProvider = ClientContext.Provider;
export const useClientSessionState = (): ClientSessionState =>
useBehavior(use(ClientContext).state$);
export const useClientState = (): ClientState | undefined => use(ClientContext);
export function useClient(): SuppliedClient | undefined {
const state = useClientSessionState();
return state.state === "signedIn" ? state.client : undefined;
export function useClient(): {
client?: MatrixClient;
setClient?: (client: MatrixClient, session: Session) => void;
} {
let client;
let setClient;
const clientState = useClientState();
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
}
return { client, setClient };
}
const noClient$ = constant(undefined);
// Plain representation of the `ClientContext` as a helper for old components that expected an object with multiple fields.
export function useClientLegacy(): {
client?: MatrixClient;
setClient?: (client: MatrixClient, session: Session) => void;
passwordlessUser: boolean;
loading: boolean;
authenticated: boolean;
logout?: () => void;
error?: Error;
} {
const clientState = useClientState();
/**
* The SPA's whole client, for its own pages outside the call view. Undefined
* while no one is signed in, and wherever the session is a host's (no client
* manager).
*/
export function useLoggedInSpaClient(
clientManager: ClientManager | null,
): MatrixClient | undefined {
return useBehavior(clientManager?.client$ ?? noClient$);
let client;
let setClient;
let passwordlessUser = false;
let loading = true;
let error;
let authenticated = false;
let logout;
if (clientState?.state === "valid") {
client = clientState.authenticated?.client;
setClient = clientState.setClient;
passwordlessUser = clientState.authenticated?.isPasswordlessUser ?? false;
loading = false;
authenticated = client !== undefined;
logout = clientState.authenticated?.logout;
} else if (clientState?.state === "error") {
error = clientState.error;
loading = false;
}
return {
client,
setClient,
passwordlessUser,
loading,
authenticated,
logout,
error,
};
}
const loadChannel =
"BroadcastChannel" in window ? new BroadcastChannel("load") : null;
interface Props {
children: JSX.Element;
/** A session from Element Call SPA, a widget, or the host (EW). */
session: ClientSession;
/**
* The client Element Call should use.
*
* An application hosting Element Call as a component already has a client,
* and owns the user's session; supplying it here means Element Call neither
* authenticates anyone nor manages their session. Left out, Element Call finds a client
* itself — from the widget API, or by restoring or creating a session of its
* own.
*/
client?: SuppliedClient;
/**
* How Element Call finds a client when none is supplied: the standalone app
* restores or creates a session of its own. Stable, as a hook dependency.
* Left out along with the client, no one is signed in.
*
* A prop, rather than this module importing `utils/spa` itself, because:
* - This module is in the component build, and so is everything it imports,
* dynamically or not: a dynamic import becomes a chunk in the package,
* not a module left out of it.
* - Behind `utils/spa` sits `utils/initClient` and the client store worker,
* which the bundler emits as soon as it loads the import (see there).
* - `App.tsx`, which the component never imports, is where the standalone
* app passes the loader in; the component passes nothing, having the
* host's client.
*/
loadClient?: ClientLoader;
}
export const ClientProvider: FC<Props> = ({ children, session }) => {
const state = useBehavior(session.state$);
/**
* What is read of a supplied client under a call, and by this provider and
* analytics. Stable methods only, so a host's client, from the host's own copy
* of matrix-js-sdk, will do.
*/
export type SuppliedClient = Pick<
MatrixClient,
// The disconnected banner, and stopping a client opened elsewhere
| "on"
| "off"
| "stopClient"
// Analytics, through `window.matrixclient`
| "getCrypto"
| "isGuest"
| "getAccountDataFromServer"
| "setAccountData"
// The room's encryption system
| "getRoom"
// Avatars
| "mxcUrlToHttp"
| "getAccessToken"
// Rageshakes: who sends them, their crypto state, and asking others for theirs
| "getUserId"
| "getUser"
| "credentials"
| "deviceId"
| "secretStorage"
| "isKeyBackupKeyStored"
| "sendEvent"
>;
/**
* Restores or creates a session of Element Call's own, kept where the given
* functions keep it. Resolves to null when no one is signed in.
*/
export type ClientLoader = (
loadSession: () => Session | undefined,
clearSession: () => void,
) => Promise<InitResult | null>;
export const ClientProvider: FC<Props> = ({
children,
client: suppliedClient,
loadClient,
}) => {
// STOP GAP: held as a whole client, as the standalone and widget pages need
// one. A component host's client is only read through `SuppliedClient`.
const client = suppliedClient as MatrixClient | undefined;
const leaveToHome = useLeaveToHome();
const hostBridge = useHostBridge();
// null = signed out, undefined = loading
const [initClientState, setInitClientState] = useState<
InitResult | null | undefined
>(
client === undefined
? undefined
: // A supplied client belongs to the host, so there is no session of ours
// to restore and nothing to wait for.
{ client, passwordlessUser: false },
);
const initializing = useRef(false);
useEffect(() => {
if (client !== undefined) {
// Nothing to load, but a host may hand us a different client later — on
// re-authenticating, say — so follow whichever one it has given us.
setInitClientState((current) =>
current?.client === client
? current
: { client, passwordlessUser: false },
);
// Analytics still need to follow the user's choices.
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
return;
}
// In case the component is mounted, unmounted, and remounted quickly (as
// React does in strict mode), we need to make sure not to doubly initialize
// the client.
if (initializing.current) return;
if (loadClient === undefined) {
setInitClientState(null);
return;
}
initializing.current = true;
loadClient(loadSession, clearSession)
.then((initResult) => {
setInitClientState(initResult);
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
})
.catch((err) => logger.error(err))
.finally(() => (initializing.current = false));
}, [client, loadClient]);
const changePassword = useCallback(
async (password: string) => {
const session = loadSession();
if (!initClientState?.client || !session) {
return;
}
await initClientState.client.setPassword(
{
type: "m.login.password",
identifier: {
type: "m.id.user",
user: session.user_id,
},
user: session.user_id,
password: session.tempPassword,
},
password,
);
saveSession({ ...session, passwordlessUser: false });
setInitClientState({
...initClientState,
passwordlessUser: false,
});
},
[initClientState],
);
const setClient = useCallback(
(client: MatrixClient, session: Session) => {
const oldClient = initClientState?.client;
if (oldClient && oldClient !== client) {
oldClient.stopClient();
}
saveSession(session);
setInitClientState({
client,
passwordlessUser: session.passwordlessUser,
});
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
},
[initClientState?.client],
);
const logout = useCallback(async () => {
const client = initClientState?.client;
if (!client) {
return;
}
await client.logout(true);
await client.clearStores();
clearSession();
setInitClientState(null);
leaveToHome?.();
PosthogAnalytics.instance.logout();
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
}, [leaveToHome, initClientState?.client]);
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app. Element Call only has storage of its own to
// protect when it created the session itself; given a client — by a host, or
// over the widget API — it is mostly stateless.
const ownsSession = client === undefined;
useEffect(() => {
if (ownsSession) loadChannel?.postMessage({});
}, [ownsSession]);
const [alreadyOpenedErr, setAlreadyOpenedErr] = useState<Error | undefined>(
undefined,
);
useEventTarget(
loadChannel,
"message",
useCallback(() => {
initClientState?.client.stopClient();
setAlreadyOpenedErr(new OpenElsewhereError());
}, [initClientState?.client, setAlreadyOpenedErr]),
);
const [isDisconnected, setIsDisconnected] = useState(false);
const [supportsReactions, setSupportsReactions] = useState(false);
const state: ClientState | undefined = useMemo(() => {
if (alreadyOpenedErr) {
return { state: "error", error: alreadyOpenedErr };
}
if (initClientState === undefined) return undefined;
const authenticated =
initClientState === null
? undefined
: {
client: initClientState.client,
isPasswordlessUser: initClientState.passwordlessUser,
changePassword,
logout,
};
return {
state: "valid",
authenticated,
setClient,
disconnected: isDisconnected,
supportedFeatures: {
reactions: supportsReactions,
},
};
}, [
alreadyOpenedErr,
changePassword,
initClientState,
logout,
setClient,
isDisconnected,
supportsReactions,
]);
const onSync = useCallback(
(state: SyncState, _old: SyncState | null, data?: ISyncStateData) => {
setIsDisconnected(clientIsDisconnected(state, data));
},
[],
);
useEffect(() => {
if (state.state !== "signedIn") return;
window.matrixclient = state.client;
window.passwordlessUser = state.passwordlessUser;
if (!initClientState) {
return;
}
window.matrixclient = initClientState.client;
window.passwordlessUser = initClientState.passwordlessUser;
if (PosthogAnalytics.hasInstance())
PosthogAnalytics.instance.onLoginStatusChanged();
// Analytics follow the user's choices whoever the client belongs to
if (PosthogAnalytics.instance.isEnabled())
PosthogAnalytics.instance.startListeningToSettingsChanges();
}, [state]);
if (state.state === "error") return <ErrorPage error={state.error} />;
if (initClientState.client) {
initClientState.client.on(ClientEvent.Sync, onSync);
}
return <ClientContext value={session}>{children}</ClientContext>;
if (!hostBridge.supportsReactions)
logger.warn("The host does not permit reactions");
setSupportsReactions(hostBridge.supportsReactions);
return (): void => {
if (initClientState.client) {
initClientState.client.off(ClientEvent.Sync, onSync);
}
};
}, [initClientState, onSync, hostBridge]);
if (alreadyOpenedErr) {
return <ErrorPage error={alreadyOpenedErr} />;
}
return <ClientContext value={state}>{children}</ClientContext>;
};
export type InitResult = {
client: MatrixClient;
passwordlessUser: boolean;
};
export interface Session {
user_id: string;
device_id: string;
access_token: string;
passwordlessUser: boolean;
tempPassword?: string;
}
const clearSession = (): void => localStorage.removeItem("matrix-auth-store");
const saveSession = (s: Session): void =>
localStorage.setItem("matrix-auth-store", JSON.stringify(s));
const loadSession = (): Session | undefined => {
const data = localStorage.getItem("matrix-auth-store");
if (!data) {
return undefined;
}
return JSON.parse(data);
};
const clientIsDisconnected = (
syncState: SyncState,
syncData?: ISyncStateData,
): boolean =>
syncState === "ERROR" && syncData?.error?.name === "ConnectionError";
-33
View File
@@ -1,33 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "vitest";
import { act, render } from "@testing-library/react";
import { BehaviorSubject } from "rxjs";
import { DisconnectedBanner } from "./DisconnectedBanner";
import { DisconnectedProvider } from "./DisconnectedContext";
test("shows while the client is disconnected", () => {
const disconnected$ = new BehaviorSubject(false);
const { container } = render(
<DisconnectedProvider value={disconnected$}>
<DisconnectedBanner />
</DisconnectedProvider>,
);
expect(container.textContent).toBe("");
act(() => disconnected$.next(true));
expect(container.textContent).not.toBe("");
act(() => disconnected$.next(false));
expect(container.textContent).toBe("");
});
test("stays hidden without a provider", () => {
const { container } = render(<DisconnectedBanner />);
expect(container.textContent).toBe("");
});
+9 -6
View File
@@ -10,27 +10,30 @@ import { type FC, type HTMLAttributes, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import styles from "./DisconnectedBanner.module.css";
import { useDisconnected } from "./DisconnectedContext";
import { type ValidClientState, useClientState } from "./ClientContext";
interface Props extends HTMLAttributes<HTMLElement> {
children?: ReactNode;
className?: string;
}
/**
* Shown while the signed-in client is supposed to be connected but is not.
*/
export const DisconnectedBanner: FC<Props> = ({
children,
className,
...rest
}) => {
const { t } = useTranslation();
const disconnected = useDisconnected();
const clientState = useClientState();
let shouldShowBanner = false;
if (clientState?.state === "valid") {
const validClientState = clientState as ValidClientState;
shouldShowBanner = validClientState.disconnected;
}
return (
<>
{disconnected && (
{shouldShowBanner && (
<div className={classNames(styles.banner, className)} {...rest}>
{children}
{t("disconnected_banner")}
-20
View File
@@ -1,20 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { createContext, use } from "react";
import { type Behavior, constant } from "./state/Behavior";
import { useBehavior } from "./useBehavior";
// Without a provider there is no client whose connection could fail
const DisconnectedContext = createContext<Behavior<boolean>>(constant(false));
export const DisconnectedProvider = DisconnectedContext.Provider;
/** Whether the signed-in client is failing to reach its homeserver. */
export const useDisconnected = (): boolean =>
useBehavior(use(DisconnectedContext));
-101
View File
@@ -1,101 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { TooltipProvider } from "@vector-im/compound-web";
import { BehaviorSubject } from "rxjs";
import { ClientProvider } from "./ClientContext";
import { LeaveToHomeProvider } from "./LeaveToHomeContext";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
hostClientSession,
} from "./state/ClientSession";
import { constant } from "./state/Behavior";
import { UserMenuContainer } from "./UserMenuContainer";
import { flushPromises } from "./utils/test";
vi.mock("./settings/SettingsModal", () => ({
defaultSettingsTab: "audio",
SettingsModal: (): null => null,
}));
const mockClient = (): MatrixClient =>
({
on: vi.fn(),
removeListener: vi.fn(),
getUserId: () => "@alice:example.org",
getUserIdLocalpart: () => "alice",
getDeviceId: () => "AAAA",
getUser: () => null,
stopClient: vi.fn(),
}) as Partial<MatrixClient> as MatrixClient;
test("leaves for home after logging out of the session", async () => {
const logout = vi.fn().mockResolvedValue(undefined);
const leaveToHome = vi.fn();
const client = mockClient();
renderMenu(
{
state$: new BehaviorSubject<ClientSessionState>({
state: "signedIn",
client,
passwordlessUser: false,
}),
},
{
login: vi.fn(),
register: vi.fn(),
logout,
client$: constant(client),
},
leaveToHome,
);
await selectSignOut();
expect(logout).toHaveBeenCalled();
expect(leaveToHome).toHaveBeenCalled();
});
test("cannot end a session that is not ours", async () => {
const leaveToHome = vi.fn();
renderMenu(hostClientSession(mockClient()), null, leaveToHome);
await selectSignOut();
expect(leaveToHome).not.toHaveBeenCalled();
});
async function selectSignOut(): Promise<void> {
const user = userEvent.setup();
await user.click(screen.getByTestId("usermenu_open"));
await user.click(await screen.findByTestId("usermenu_logout"));
await flushPromises();
}
function renderMenu(
session: ClientSession,
manager: ClientManager | null,
leaveToHome: (() => void) | null = null,
): void {
render(
<BrowserRouter>
<TooltipProvider>
<LeaveToHomeProvider value={leaveToHome}>
<ClientProvider session={session}>
<UserMenuContainer clientManager={manager} />
</ClientProvider>
</LeaveToHomeProvider>
</TooltipProvider>
</BrowserRouter>,
);
}
+7 -28
View File
@@ -9,38 +9,19 @@ import { type FC, useCallback, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { logger } from "matrix-js-sdk/lib/logger";
import {
useClient,
useClientSessionState,
useLoggedInSpaClient,
} from "./ClientContext";
import { type ClientManager } from "./state/ClientSession";
import { useLeaveToHome } from "./LeaveToHomeContext";
import { useClientLegacy } from "./ClientContext";
import { useProfile } from "./profile/useProfile";
import { defaultSettingsTab, SettingsModal } from "./settings/SettingsModal";
import { UserMenu } from "./UserMenu";
interface Props {
preventNavigation?: boolean;
/** Null when the session is a host's, which Element Call cannot end. */
clientManager: ClientManager | null;
}
export const UserMenuContainer: FC<Props> = ({
preventNavigation = false,
clientManager,
}) => {
export const UserMenuContainer: FC<Props> = ({ preventNavigation = false }) => {
const location = useLocation();
const navigate = useNavigate();
// Who is signed in is the session's; the profile and settings need the
// SPA's whole client
const suppliedClient = useClient();
const client = useLoggedInSpaClient(clientManager);
const logout = clientManager?.logout;
const session = useClientSessionState();
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
const leaveToHome = useLeaveToHome();
const { client, logout, authenticated, passwordlessUser } = useClientLegacy();
const { displayName, avatarUrl } = useProfile(client);
const [settingsModalOpen, setSettingsModalOpen] = useState(false);
const onDismissSettingsModal = useCallback(
@@ -62,9 +43,7 @@ export const UserMenuContainer: FC<Props> = ({
setSettingsModalOpen(true);
break;
case "logout":
logout?.()
.then(() => leaveToHome?.())
.catch((e) => logger.error("Failed to log out", e));
logout?.();
break;
case "login":
navigate("/login", { state: { from: location } })?.catch((error) =>
@@ -73,7 +52,7 @@ export const UserMenuContainer: FC<Props> = ({
break;
}
},
[navigate, location, logout, leaveToHome, setSettingsModalOpen],
[navigate, location, logout, setSettingsModalOpen],
);
const userName = client?.getUserIdLocalpart() ?? "";
@@ -81,11 +60,11 @@ export const UserMenuContainer: FC<Props> = ({
<>
<UserMenu
preventNavigation={preventNavigation}
isAuthenticated={suppliedClient !== undefined}
isAuthenticated={authenticated}
isPasswordlessUser={passwordlessUser}
avatarUrl={avatarUrl}
onAction={onAction}
userId={suppliedClient?.getUserId() ?? ""}
userId={client?.getUserId() ?? ""}
displayName={displayName || (userName ? userName.replace("@", "") : "")}
/>
{client && (
+2 -1
View File
@@ -12,6 +12,7 @@ import posthog, {
type Properties,
} from "posthog-js";
import { logger } from "matrix-js-sdk/lib/logger";
import { type MatrixClient } from "matrix-js-sdk";
import { type Subscription } from "rxjs";
import {
@@ -342,7 +343,7 @@ export class PosthogAnalytics {
}
private async getAnalyticsId(): Promise<string | null> {
const client = window.matrixclient;
const client: MatrixClient = window.matrixclient;
if (this.config.matrixBackend === "embedded") {
return this.config.hostAnalyticsId ?? null;
} else {
-81
View File
@@ -1,81 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { LoginPage } from "./LoginPage";
import { type ClientManager } from "../state/ClientSession";
import { constant } from "../state/Behavior";
import { Config } from "../config/Config";
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("signs in with the session's manager and goes home", async () => {
const manager = mockManager();
vi.mocked(manager.login).mockResolvedValue({} as MatrixClient);
renderLogin(manager);
await submit("alice", "hunter2");
expect(manager.login).toHaveBeenCalledWith(
"https://hs.example.org",
"alice",
"hunter2",
);
expect(await screen.findByText("at /")).toBeVisible();
});
test("shows why signing in failed", async () => {
const manager = mockManager();
vi.mocked(manager.login).mockRejectedValue(new Error("Wrong password"));
renderLogin(manager);
await submit("alice", "hunter2");
expect(await screen.findByText("Wrong password")).toBeVisible();
expect(screen.getByText("at /login")).toBeVisible();
});
async function submit(username: string, password: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("login_username"), username);
await user.type(screen.getByTestId("login_password"), password);
await user.click(screen.getByTestId("login_login"));
}
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
const WhereAmI: FC = () => <span>at {useLocation().pathname}</span>;
function renderLogin(manager: ClientManager): void {
render(
<MemoryRouter initialEntries={["/login"]}>
<LoginPage clientManager={manager} />
<WhereAmI />
</MemoryRouter>,
);
}
+14 -9
View File
@@ -11,23 +11,21 @@ import { Trans, useTranslation } from "react-i18next";
import { Button } from "@vector-im/compound-web";
import Logo from "../icons/LogoLarge.svg?react";
import { type ClientManager } from "../state/ClientSession";
import { useClient } from "../ClientContext";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import styles from "./LoginPage.module.css";
import { useInteractiveLogin } from "./useInteractiveLogin";
import { usePageTitle } from "../usePageTitle";
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { Link } from "../button/Link";
interface Props {
clientManager: ClientManager;
}
export const LoginPage: FC<Props> = ({ clientManager }) => {
export const LoginPage: FC = () => {
const { t } = useTranslation();
usePageTitle(t("login_title"));
const { login } = clientManager;
const { client, setClient } = useClient();
const login = useInteractiveLogin(client);
const homeserver = Config.defaultHomeserverUrl(); // TODO: Make this configurable
const usernameRef = useRef<HTMLInputElement>(null);
const passwordRef = useRef<HTMLInputElement>(null);
@@ -48,8 +46,15 @@ export const LoginPage: FC<Props> = ({ clientManager }) => {
setLoading(false);
return;
}
login(homeserver, usernameRef.current.value, passwordRef.current.value)
.then(async () => {
.then(async ([client, session]) => {
if (!setClient) {
return;
}
setClient(client, session);
const locationState = location.state;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
@@ -67,7 +72,7 @@ export const LoginPage: FC<Props> = ({ clientManager }) => {
setLoading(false);
});
},
[login, location, navigate, homeserver],
[login, location, navigate, homeserver, setClient],
);
// we need to limit the length of the homserver name to not cover the whole loginview input with the string.
let shortendHomeserverName = Config.defaultServerName()?.slice(0, 25);
-137
View File
@@ -1,137 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { RegisterPage } from "./RegisterPage";
import { ClientContextProvider } from "../ClientContext";
import {
type ClientManager,
type ClientSessionState,
} from "../state/ClientSession";
import { constant } from "../state/Behavior";
vi.mock("./useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("./useRegistrationTerms", () => ({
useRegistrationTerms: () => ({ recaptchaKey: "site-key" }),
}));
const reset = vi.fn();
afterEach(() => vi.clearAllMocks());
test("waits for the session to be restored", () => {
renderRegister({ state: "loading" }, mockManager());
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("registers an account, signs in and goes home", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn,
});
renderRegister({ state: "signedOut" }, manager);
await submit("alice", "hunter2");
expect(manager.register).toHaveBeenCalledWith(
"alice",
"hunter2",
"alice",
"captcha-response",
false,
);
expect(setSignedIn).toHaveBeenCalled();
expect(await screen.findByText("at /")).toBeVisible();
});
test("upgrades a passwordless user to a full account", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn: vi.fn(),
});
renderRegister(
{
state: "signedIn",
client: { getUserId: () => "@guest:example.org" } as MatrixClient,
passwordlessUser: true,
},
manager,
);
await submit("alice", "hunter2");
expect(manager.register).toHaveBeenCalledWith(
"alice",
"hunter2",
"alice",
"captcha-response",
true,
);
});
test("shows why registering failed and resets the captcha", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Name taken"));
renderRegister({ state: "signedOut" }, manager);
await submit("alice", "hunter2");
expect(await screen.findByText("Name taken")).toBeVisible();
expect(reset).toHaveBeenCalled();
expect(screen.getByText("at /register")).toBeVisible();
});
async function submit(username: string, password: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("register_username"), username);
await user.type(screen.getByTestId("register_password"), password);
await user.type(screen.getByTestId("register_confirm_password"), password);
await user.click(screen.getByTestId("register_register"));
}
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
const WhereAmI: FC = () => <span>at {useLocation().pathname}</span>;
function renderRegister(
state: ClientSessionState,
manager: ClientManager,
): void {
render(
<MemoryRouter initialEntries={["/register"]}>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<RegisterPage clientManager={manager} />
<WhereAmI />
</ClientContextProvider>
</MemoryRouter>,
);
}
+18 -19
View File
@@ -22,9 +22,8 @@ import { logger } from "matrix-js-sdk/lib/logger";
import { Button, Text } from "@vector-im/compound-web";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import { useClientSessionState, useLoggedInSpaClient } from "../ClientContext";
import { type ClientManager } from "../state/ClientSession";
import { useRegistrationTerms } from "./useRegistrationTerms";
import { useClientLegacy } from "../ClientContext";
import { useInteractiveRegistration } from "./useInteractiveRegistration";
import styles from "./LoginPage.module.css";
import Logo from "../icons/LogoLarge.svg?react";
import { LoadingPage } from "../FullScreenView";
@@ -34,21 +33,12 @@ import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { ExternalLink, Link } from "../button/Link";
interface Props {
clientManager: ClientManager;
}
export const RegisterPage: FC<Props> = ({ clientManager }) => {
export const RegisterPage: FC = () => {
const { t } = useTranslation();
usePageTitle(t("action.register"));
const session = useClientSessionState();
const loading = session.state === "loading";
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
const client = useLoggedInSpaClient(clientManager);
const authenticated = client !== undefined;
const { register } = clientManager;
const { loading, authenticated, passwordlessUser, client, setClient } =
useClientLegacy();
const confirmPasswordRef = useRef<HTMLInputElement>(null);
const navigate = useNavigate();
@@ -57,7 +47,7 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
const [error, setError] = useState<Error>();
const [password, setPassword] = useState("");
const [passwordConfirmation, setPasswordConfirmation] = useState("");
const { recaptchaKey } = useRegistrationTerms();
const { recaptchaKey, register } = useInteractiveRegistration(client);
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const onSubmitRegisterForm = useCallback(
@@ -74,7 +64,7 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
setRegistering(true);
const recaptchaResponse = await execute();
const { client: newClient, setSignedIn } = await register(
const [newClient, session] = await register(
userName,
password,
userName,
@@ -105,7 +95,7 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
}
}
setSignedIn();
setClient?.(newClient, session);
PosthogAnalytics.instance.eventSignup.cacheSignupEnd(new Date());
};
@@ -127,7 +117,16 @@ export const RegisterPage: FC<Props> = ({ clientManager }) => {
reset();
});
},
[register, location, navigate, passwordlessUser, reset, execute, client],
[
register,
location,
navigate,
passwordlessUser,
reset,
execute,
client,
setClient,
],
);
useEffect(() => {
-104
View File
@@ -1,104 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { createClient, type MatrixClient, MatrixError } from "matrix-js-sdk";
import type * as MatrixJsSdk from "matrix-js-sdk";
import { loginWithPassword, registerWithPassword } from "./interactiveAuth";
vi.mock("matrix-js-sdk", async (importOriginal) => ({
...(await importOriginal<typeof MatrixJsSdk>()),
createClient: vi.fn(),
}));
const credentials = {
user_id: "@alice:example.org",
device_id: "AAAA",
access_token: "secret",
};
// What interactive auth asks of the client besides the request itself
const authClient = { generateClientSecret: () => "client-secret" };
afterEach(() => {
vi.clearAllMocks();
});
test("logs in with a password", async () => {
const login = vi.fn().mockResolvedValue({ ...credentials, extra: "ignored" });
vi.mocked(createClient).mockReturnValue({
...authClient,
login,
} as Partial<MatrixClient> as MatrixClient);
await expect(
loginWithPassword("https://hs.example.org", "alice", "hunter2"),
).resolves.toEqual(credentials);
expect(createClient).toHaveBeenCalledWith({
baseUrl: "https://hs.example.org",
});
expect(login).toHaveBeenCalledWith("m.login.password", {
identifier: { type: "m.id.user", user: "alice" },
password: "hunter2",
});
});
test("registers, agreeing to the terms and answering the recaptcha", async () => {
// The homeserver turns the first request away with the stages to complete
// No error in it: that is the shape of a challenge rather than a refusal
const challenge = new MatrixError(
{
session: "session",
flows: [{ stages: ["m.login.terms", "m.login.recaptcha"] }],
params: {},
completed: [],
},
401,
);
const registerRequest = vi
.fn()
.mockImplementation(({ auth }: { auth?: { type: string } }) => {
if (auth === undefined) throw challenge;
challenge.data.completed = [
...(challenge.data.completed as string[]),
auth.type,
];
if (challenge.data.completed.length < 2) throw challenge;
return credentials;
});
vi.mocked(createClient).mockReturnValue({
...authClient,
registerRequest,
} as Partial<MatrixClient> as MatrixClient);
await expect(
registerWithPassword(
"https://hs.example.org",
"alice",
"hunter2",
"captcha",
),
).resolves.toEqual(credentials);
expect(registerRequest).toHaveBeenCalledWith(
expect.objectContaining({
username: "alice",
password: "hunter2",
auth: expect.objectContaining({ type: "m.login.terms" }),
}),
);
expect(registerRequest).toHaveBeenCalledWith(
expect.objectContaining({
auth: expect.objectContaining({
type: "m.login.recaptcha",
response: "captcha",
}),
}),
);
});
-106
View File
@@ -1,106 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import {
createClient,
InteractiveAuth,
type LoginResponse,
type RegisterResponse,
} from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { type StoredSession } from "../state/ClientSession";
/** What the homeserver hands out for a new session. */
export type Credentials = Pick<
StoredSession,
"user_id" | "device_id" | "access_token"
>;
/**
* Logs in to the given homeserver with a password.
*/
export async function loginWithPassword(
homeserver: string,
username: string,
password: string,
): Promise<Credentials> {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (): Promise<LoginResponse> =>
authClient.login("m.login.password", {
identifier: {
type: "m.id.user",
user: username,
},
password,
}),
stateUpdated: (): void => {},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "" }),
});
return credentials(await interactiveAuth.attemptAuth());
}
/**
* Registers an account on the given homeserver, accepting its terms and
* answering its recaptcha challenge.
*/
export async function registerWithPassword(
homeserver: string,
username: string,
password: string,
recaptchaResponse: string,
): Promise<Credentials> {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (auth): Promise<RegisterResponse> =>
authClient.registerRequest({
username,
password,
auth: auth || undefined,
}),
stateUpdated: (nextStage, status): void => {
if (status.error) {
throw new Error(status.error);
}
if (nextStage === "m.login.terms") {
interactiveAuth
.submitAuthDict({
type: "m.login.terms",
})
.catch((e) => {
logger.error(e);
});
} else if (nextStage === "m.login.recaptcha") {
interactiveAuth
.submitAuthDict({
type: "m.login.recaptcha",
response: recaptchaResponse,
})
.catch((e) => {
logger.error(e);
});
}
},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "dummy" }),
});
return credentials(await interactiveAuth.attemptAuth());
}
// XXX: attemptAuth claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
function credentials(authData: unknown): Credentials {
/* eslint-disable camelcase */
const { user_id, access_token, device_id } = authData as Credentials;
return { user_id, access_token, device_id };
/* eslint-enable camelcase */
}
+84
View File
@@ -0,0 +1,84 @@
/*
Copyright 2022-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useCallback } from "react";
import { InteractiveAuth } from "matrix-js-sdk";
import {
createClient,
type LoginResponse,
type MatrixClient,
} from "matrix-js-sdk";
import { initClient } from "../utils/initClient";
import { type Session } from "../ClientContext";
/**
* This provides the login method to login using user credentials.
* @param oldClient If there is an already authenticated client it should be passed to this hook
* this allows the interactive login to sign out the client before logging in.
* @returns A async method that can be called/awaited to log in with the provided credentials.
*/
export function useInteractiveLogin(
oldClient?: MatrixClient,
): (
homeserver: string,
username: string,
password: string,
) => Promise<[MatrixClient, Session]> {
return useCallback<
(
homeserver: string,
username: string,
password: string,
) => Promise<[MatrixClient, Session]>
>(
async (homeserver: string, username: string, password: string) => {
const authClient = createClient({ baseUrl: homeserver });
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient,
doRequest: async (): Promise<LoginResponse> =>
authClient.login("m.login.password", {
identifier: {
type: "m.id.user",
user: username,
},
password,
}),
stateUpdated: (): void => {},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "" }),
});
// XXX: This claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
/* eslint-disable camelcase,@typescript-eslint/no-explicit-any */
const { user_id, access_token, device_id } =
(await interactiveAuth.attemptAuth()) as any;
const session = {
user_id,
access_token,
device_id,
passwordlessUser: false,
};
// To not confuse the rust crypto sessions we need to logout the old client before initializing the new one.
await oldClient?.logout(true);
const client = await initClient(
{
baseUrl: homeserver,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
},
false,
);
/* eslint-enable camelcase */
return [client, session];
},
[oldClient],
);
}
+145
View File
@@ -0,0 +1,145 @@
/*
Copyright 2022-2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useState, useEffect, useCallback, useRef } from "react";
import { InteractiveAuth } from "matrix-js-sdk";
import {
createClient,
type MatrixClient,
type RegisterResponse,
} from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { initClient } from "../utils/initClient";
import { type Session } from "../ClientContext";
import { Config } from "../config/Config";
import { useUrlParams } from "../UrlParams";
export const useInteractiveRegistration = (
oldClient?: MatrixClient,
): {
privacyPolicyUrl?: string;
recaptchaKey?: string;
register: (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
) => Promise<[MatrixClient, Session]>;
} => {
const { isWidget } = useUrlParams();
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string | undefined>(
undefined,
);
const [recaptchaKey, setRecaptchaKey] = useState<string | undefined>(
undefined,
);
const authClient = useRef<MatrixClient | undefined>(undefined);
if (!authClient.current) {
authClient.current = createClient({
baseUrl: Config.defaultHomeserverUrl()!,
});
}
useEffect(() => {
if (isWidget) return;
// An empty registerRequest is used to get the privacy policy and recaptcha key.
authClient.current!.registerRequest({}).catch((error) => {
setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en?.url,
);
setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key);
});
}, [isWidget]);
const register = useCallback(
async (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
): Promise<[MatrixClient, Session]> => {
const interactiveAuth = new InteractiveAuth({
matrixClient: authClient.current!,
doRequest: async (auth): Promise<RegisterResponse> =>
authClient.current!.registerRequest({
username,
password,
auth: auth || undefined,
}),
stateUpdated: (nextStage, status): void => {
if (status.error) {
throw new Error(status.error);
}
if (nextStage === "m.login.terms") {
interactiveAuth
.submitAuthDict({
type: "m.login.terms",
})
.catch((e) => {
logger.error(e);
});
} else if (nextStage === "m.login.recaptcha") {
interactiveAuth
.submitAuthDict({
type: "m.login.recaptcha",
response: recaptchaResponse,
})
.catch((e) => {
logger.error(e);
});
}
},
requestEmailToken: async (): Promise<{ sid: string }> =>
Promise.resolve({ sid: "dummy" }),
});
// XXX: This claims to return an IAuthData which contains none of these
// things - the js-sdk types may be wrong?
/* eslint-disable camelcase,@typescript-eslint/no-explicit-any */
const { user_id, access_token, device_id } =
(await interactiveAuth.attemptAuth()) as any;
await oldClient?.logout(true);
const client = await initClient(
{
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
},
false,
);
await client.setDisplayName(displayName);
const session: Session = {
user_id,
device_id,
access_token,
passwordlessUser,
};
/* eslint-enable camelcase */
if (passwordlessUser) {
session.tempPassword = password;
}
const user = client.getUser(client.getUserId()!)!;
user.setRawDisplayName(displayName);
user.setDisplayName(displayName);
return [client, session];
},
[oldClient],
);
return { privacyPolicyUrl, recaptchaKey, register };
};
@@ -1,116 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { renderHook } from "@testing-library/react";
import { type FC, type PropsWithChildren } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { useRegisterPasswordlessUser } from "./useRegisterPasswordlessUser";
import { type ClientManager } from "../state/ClientSession";
import { constant } from "../state/Behavior";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
vi.mock("./useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("./useRegistrationTerms", () => ({
useRegistrationTerms: () => ({
privacyPolicyUrl: "https://hs.example.org/privacy",
recaptchaKey: "site-key",
}),
}));
vi.mock("./generateRandomName", () => ({
generateRandomName: () => "Random Name",
}));
const reset = vi.fn();
afterEach(() => vi.clearAllMocks());
test("registers a user under a random name and signs them in", async () => {
const setSignedIn = vi.fn();
const manager = mockManager();
vi.mocked(manager.register).mockResolvedValue({
client: {} as MatrixClient,
setSignedIn,
});
const { result } = renderHook(() => useRegisterPasswordlessUser(manager), {
wrapper: wrapper(false),
});
await result.current.registerPasswordlessUser("Alice");
expect(manager.register).toHaveBeenCalledWith(
"Random Name",
expect.stringMatching(/^.{16}$/),
"Alice",
"captcha-response",
true,
);
expect(setSignedIn).toHaveBeenCalled();
expect(result.current.privacyPolicyUrl).toBe(
"https://hs.example.org/privacy",
);
expect(result.current.recaptchaId).toBe("recaptcha");
});
test("resets the captcha when registration fails", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Nope"));
const { result } = renderHook(() => useRegisterPasswordlessUser(manager), {
wrapper: wrapper(false),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow("Nope");
expect(reset).toHaveBeenCalled();
});
test("cannot register on a session that is not ours", async () => {
const { result } = renderHook(() => useRegisterPasswordlessUser(null), {
wrapper: wrapper(false),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow("This session cannot register");
});
test("never registers as a widget", async () => {
const manager = mockManager();
const { result } = renderHook(() => useRegisterPasswordlessUser(manager), {
wrapper: wrapper(true),
});
await expect(
result.current.registerPasswordlessUser("Alice"),
).rejects.toThrow(/embedded mode/);
expect(manager.register).not.toHaveBeenCalled();
});
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
function wrapper(isWidget: boolean): FC<PropsWithChildren> {
const params = { ...computeUrlParams(), isWidget };
return ({ children }) => (
<UrlParamsProvider value={params}>{children}</UrlParamsProvider>
);
}
+11 -15
View File
@@ -8,8 +8,8 @@ Please see LICENSE in the repository root for full details.
import { useCallback } from "react";
import { secureRandomString } from "matrix-js-sdk/lib/randomstring";
import { type ClientManager } from "../state/ClientSession";
import { useRegistrationTerms } from "../auth/useRegistrationTerms";
import { useClient } from "../ClientContext";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { generateRandomName } from "../auth/generateRandomName";
import { useRecaptcha } from "../auth/useRecaptcha";
import { useUrlParams } from "../UrlParams";
@@ -20,21 +20,17 @@ interface UseRegisterPasswordlessUserType {
recaptchaId?: string;
}
/**
* @param clientManager Null in the widget, which never registers anyone.
*/
export function useRegisterPasswordlessUser(
clientManager: ClientManager | null,
): UseRegisterPasswordlessUserType {
const register = clientManager?.register;
export function useRegisterPasswordlessUser(): UseRegisterPasswordlessUserType {
const { setClient } = useClient();
const { isWidget } = useUrlParams();
const { privacyPolicyUrl, recaptchaKey } = useRegistrationTerms();
const { privacyPolicyUrl, recaptchaKey, register } =
useInteractiveRegistration();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const registerPasswordlessUser = useCallback(
async (displayName: string) => {
if (!register) {
throw new Error("This session cannot register");
if (!setClient) {
throw new Error("No client context");
}
if (isWidget) {
throw new Error(
@@ -45,20 +41,20 @@ export function useRegisterPasswordlessUser(
try {
const recaptchaResponse = await execute();
const userName = generateRandomName();
const { setSignedIn } = await register(
const [client, session] = await register(
userName,
secureRandomString(16),
displayName,
recaptchaResponse,
true,
);
setSignedIn();
setClient(client, session);
} catch (e) {
reset();
throw e;
}
},
[execute, reset, register, isWidget],
[execute, reset, register, setClient, isWidget],
);
return { privacyPolicyUrl, registerPasswordlessUser, recaptchaId };
-98
View File
@@ -1,98 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { renderHook, waitFor } from "@testing-library/react";
import type * as MatrixJsSdk from "matrix-js-sdk";
import { createClient, type MatrixClient } from "matrix-js-sdk";
import { type FC, type PropsWithChildren } from "react";
import { useRegistrationTerms } from "./useRegistrationTerms";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import { Config } from "../config/Config";
vi.mock("matrix-js-sdk", async (importOriginal) => ({
...(await importOriginal<typeof MatrixJsSdk>()),
createClient: vi.fn(),
}));
const registerRequest = vi.fn();
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
vi.mocked(createClient).mockReturnValue({
registerRequest,
} as Partial<MatrixClient> as MatrixClient);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("reads the terms the homeserver asks for from a registration attempt", async () => {
registerRequest.mockRejectedValue({
data: {
params: {
"m.login.terms": {
policies: {
privacy_policy: { en: { url: "https://hs.example.org/privacy" } },
},
},
"m.login.recaptcha": { public_key: "site-key" },
},
},
});
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(false),
});
expect(createClient).toHaveBeenCalledWith({
baseUrl: "https://hs.example.org",
});
await waitFor(() =>
expect(result.current).toEqual({
privacyPolicyUrl: "https://hs.example.org/privacy",
recaptchaKey: "site-key",
}),
);
});
test("has nothing to agree to where the homeserver asks for nothing", async () => {
registerRequest.mockRejectedValue({ data: { params: {} } });
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(false),
});
await waitFor(() => expect(registerRequest).toHaveBeenCalled());
expect(result.current).toEqual({
privacyPolicyUrl: undefined,
recaptchaKey: undefined,
});
});
test("asks the homeserver nothing as a widget", () => {
const { result } = renderHook(() => useRegistrationTerms(), {
wrapper: wrapper(true),
});
expect(createClient).not.toHaveBeenCalled();
expect(result.current).toEqual({
privacyPolicyUrl: undefined,
recaptchaKey: undefined,
});
});
function wrapper(isWidget: boolean): FC<PropsWithChildren> {
const params = { ...computeUrlParams(), isWidget };
return ({ children }) => (
<UrlParamsProvider value={params}>{children}</UrlParamsProvider>
);
}
-46
View File
@@ -1,46 +0,0 @@
/*
Copyright 2022-2024 New Vector Ltd.
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { useEffect, useState } from "react";
import { createClient } from "matrix-js-sdk";
import { Config } from "../config/Config";
import { useUrlParams } from "../UrlParams";
/**
* What the homeserver asks of a registration: its privacy policy to agree to
* and the recaptcha key to answer a challenge with.
*/
export function useRegistrationTerms(): {
privacyPolicyUrl?: string;
recaptchaKey?: string;
} {
const { isWidget } = useUrlParams();
const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string | undefined>(
undefined,
);
const [recaptchaKey, setRecaptchaKey] = useState<string | undefined>(
undefined,
);
useEffect(() => {
if (isWidget) return;
// An empty registerRequest is used to get the privacy policy and recaptcha key.
createClient({ baseUrl: Config.defaultHomeserverUrl()! })
.registerRequest({})
.catch((error) => {
setPrivacyPolicyUrl(
error.data?.params["m.login.terms"]?.policies?.privacy_policy?.en
?.url,
);
setRecaptchaKey(error.data?.params["m.login.recaptcha"]?.public_key);
});
}, [isWidget]);
return { privacyPolicyUrl, recaptchaKey };
}
@@ -537,7 +537,9 @@ export const RemovingWithLiveSelection: Story = {
const cross = tile.parentElement!.querySelector<HTMLElement>(
"[aria-hidden]:last-child",
)!;
await expect(cross).toBeVisible();
// The menu slides in over 180ms from transparent. On a fast machine the
// hover lands before its first frame, so wait it out.
await waitFor(async () => expect(cross).toBeVisible());
await userEvent.click(cross);
await waitFor(async () =>
@@ -907,7 +909,10 @@ export const SelectionSettling: Story = {
await menu.findByRole("menuitemradio", { name: "Microphone 2" }),
);
await expect(await menu.findByLabelText("Activating…")).toBeVisible();
// The menu slides in over 180ms from transparent. On a fast machine the
// hover lands before its first frame, so wait it out.
const spinner = await menu.findByLabelText("Activating…");
await waitFor(async () => expect(spinner).toBeVisible());
for (const item of menu.getAllByRole("menuitemradio"))
await expect(item).toHaveAttribute("aria-disabled", "true");
},
+10 -14
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, describe, expect, test } from "vitest";
import { afterEach, describe, expect, test, vi } from "vitest";
import { act, renderHook } from "@testing-library/react";
import { E2eeType } from "@element-hq/matrixrtc-sdk";
@@ -15,9 +15,14 @@ import {
useRoomEncryptionSystem,
} from "./sharedKeyManagement";
vi.mock("../ClientContext", () => {
const room = { hasEncryptionStateEvent: (): boolean => false };
const client = { getRoom: (): typeof room => room };
return { useClient: (): { client: typeof client } => ({ client }) };
});
const roomId = "!room:example.org";
const otherRoomId = "!other:example.org";
const room = { roomId, hasEncryptionStateEvent: (): boolean => false };
describe("getKeyForRoom", () => {
afterEach(() => {
@@ -62,17 +67,8 @@ describe("useRoomEncryptionSystem", () => {
localStorage.clear();
});
test("encrypts per participant in an encrypted room without a key", () => {
const encryptedRoom = {
roomId,
hasEncryptionStateEvent: (): boolean => true,
};
const { result } = renderHook(() => useRoomEncryptionSystem(encryptedRoom));
expect(result.current).toEqual({ kind: E2eeType.PER_PARTICIPANT });
});
test("picks up a key saved for the room after it rendered", () => {
const { result } = renderHook(() => useRoomEncryptionSystem(room));
const { result } = renderHook(() => useRoomEncryptionSystem(roomId));
expect(result.current).toEqual({ kind: E2eeType.NONE });
act(() => saveKeyForRoom(roomId, "stored"));
@@ -86,7 +82,7 @@ describe("useRoomEncryptionSystem", () => {
test("stores a key from the parameters under the room's key only", () => {
window.location.hash = `#?roomId=${encodeURIComponent(roomId)}&password=from-the-link`;
renderHook(() => useRoomEncryptionSystem(room));
renderHook(() => useRoomEncryptionSystem(roomId));
expect(Object.keys(localStorage)).toEqual([`room-shared-key-${roomId}`]);
expect(getKeyForRoom(roomId)).toBe("from-the-link");
@@ -96,7 +92,7 @@ describe("useRoomEncryptionSystem", () => {
saveKeyForRoom(roomId, "stored");
window.location.hash = `#?roomId=${encodeURIComponent(otherRoomId)}&password=other-room`;
const { result } = renderHook(() => useRoomEncryptionSystem(room));
const { result } = renderHook(() => useRoomEncryptionSystem(roomId));
expect(result.current).toEqual({
kind: E2eeType.SHARED_KEY,
+7 -6
View File
@@ -6,7 +6,6 @@ Please see LICENSE in the repository root for full details.
*/
import { useEffect, useMemo } from "react";
import { type Room } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import {
@@ -15,6 +14,7 @@ import {
} from "../useLocalStorage";
import { getUrlParams, useUrlParams } from "../UrlParams";
import { E2eeType, type EncryptionSystem } from "@element-hq/matrixrtc-sdk";
import { useClient } from "../ClientContext";
/**
* This setter will update the state for all `useRoomSharedKey` hooks
@@ -89,17 +89,18 @@ export function getKeyForRoom(roomId: string): string | null {
export { type EncryptionSystem } from "@element-hq/matrixrtc-sdk";
export function useRoomEncryptionSystem(
room: Pick<Room, "roomId" | "hasEncryptionStateEvent">,
): EncryptionSystem {
export function useRoomEncryptionSystem(roomId: string): EncryptionSystem {
const { client } = useClient();
const { roomId: paramsRoomId, password } = useUrlParams();
const [storedPassword] = useRoomSharedKey(
room.roomId,
keyForRoom(room.roomId, paramsRoomId, password) ?? undefined,
roomId,
keyForRoom(roomId, paramsRoomId, password) ?? undefined,
);
const room = client?.getRoom(roomId);
const e2eeSystem = useMemo<EncryptionSystem>(() => {
if (!room) return { kind: E2eeType.NONE };
if (storedPassword)
return {
kind: E2eeType.SHARED_KEY,
-1
View File
@@ -29,7 +29,6 @@ describe("CallList", () => {
roomAlias: "#room-name:server.org",
room: {
roomId: "!roomId",
hasEncryptionStateEvent: () => false,
},
},
] as GroupCallRoom[];
+1 -1
View File
@@ -58,7 +58,7 @@ interface CallTileProps {
const CallTile: FC<CallTileProps> = ({ name, avatarUrl, room, client }) => {
const { t } = useTranslation();
const roomEncryptionSystem = useRoomEncryptionSystem(room);
const roomEncryptionSystem = useRoomEncryptionSystem(room.roomId);
const [isLeaving, setIsLeaving] = useState(false);
const onRemove = useCallback(
-96
View File
@@ -1,96 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { BrowserRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { HomePage } from "./HomePage";
import { ClientContextProvider } from "../ClientContext";
import { constant } from "../state/Behavior";
import {
type ClientManager,
type ClientSessionState,
} from "../state/ClientSession";
vi.mock("./RegisteredView", () => ({
RegisteredView: ({ client }: { client: MatrixClient }) => (
<span>registered as {client.getUserId()}</span>
),
}));
vi.mock("./UnauthenticatedView", () => ({
UnauthenticatedView: () => <span>unauthenticated</span>,
}));
test("waits for the session to be restored", () => {
renderHome({ state: "loading" });
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("shows the session's error", () => {
vi.spyOn(console, "error").mockImplementation(() => {});
renderHome({ state: "error", error: new Error("Opened elsewhere") });
expect(screen.getByText("Something went wrong")).toBeVisible();
});
test("welcomes a signed-in user", () => {
renderHome({
state: "signedIn",
client: { getUserId: () => "@alice:example.org" } as MatrixClient,
passwordlessUser: false,
});
expect(screen.getByText("registered as @alice:example.org")).toBeVisible();
});
test("welcomes a widget's user, who has no client manager", () => {
renderHome(
{
state: "signedIn",
client: { getUserId: () => "@bob:example.org" } as MatrixClient,
passwordlessUser: false,
},
null,
);
expect(screen.getByText("registered as @bob:example.org")).toBeVisible();
});
test("invites a signed-out user to start a call", () => {
renderHome({ state: "signedOut" });
expect(screen.getByText("unauthenticated")).toBeVisible();
});
test("cannot sign in to a host's session that is signed out", () => {
vi.spyOn(console, "error").mockImplementation(() => {});
renderHome({ state: "signedOut" }, null);
expect(screen.getByText("Something went wrong")).toBeVisible();
expect(screen.queryByText("unauthenticated")).toBeNull();
});
function renderHome(
state: ClientSessionState,
manager: ClientManager | null = {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
// The manager's client is the session's, whole
client$: constant(
state.state === "signedIn" ? (state.client as MatrixClient) : undefined,
),
},
): void {
render(
<BrowserRouter>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<HomePage clientManager={manager} />
</ClientContextProvider>
</BrowserRouter>,
);
}
+13 -36
View File
@@ -7,51 +7,28 @@ Please see LICENSE in the repository root for full details.
import { useTranslation } from "react-i18next";
import { type FC } from "react";
import { type MatrixClient } from "matrix-js-sdk";
import { useClientSessionState, useLoggedInSpaClient } from "../ClientContext";
import { useClientState } from "../ClientContext";
import { ErrorPage, LoadingPage } from "../FullScreenView";
import { UnauthenticatedView } from "./UnauthenticatedView";
import { RegisteredView } from "./RegisteredView";
import { type ClientManager } from "../state/ClientSession";
import { usePageTitle } from "../usePageTitle";
interface Props {
/** Null where the session is a host's and not ours to manage. */
clientManager: ClientManager | null;
}
export const HomePage: FC<Props> = ({ clientManager }) => {
export const HomePage: FC = () => {
const { t } = useTranslation();
usePageTitle(t("common.home"));
const session = useClientSessionState();
const spaClient = useLoggedInSpaClient(clientManager);
const clientState = useClientState();
switch (session.state) {
case "loading":
return <LoadingPage />;
case "error":
return <ErrorPage error={session.error} />;
case "signedIn": {
// STOP GAP: a widget has no client manager, but its client is a whole
// one from our own js-sdk.
const client =
clientManager !== null
? spaClient
: (session.client as MatrixClient | undefined);
return client ? (
<RegisteredView client={client} clientManager={clientManager} />
) : (
<LoadingPage />
);
}
case "signedOut":
// A host's session cannot be signed in to from here
return clientManager === null ? (
<ErrorPage error={new Error("Signed out of the host's session")} />
) : (
<UnauthenticatedView clientManager={clientManager} />
);
if (!clientState) {
return <LoadingPage />;
} else if (clientState.state === "error") {
return <ErrorPage error={clientState.error} />;
} else {
return clientState.authenticated ? (
<RegisteredView client={clientState.authenticated.client} />
) : (
<UnauthenticatedView />
);
}
};
+2 -4
View File
@@ -38,14 +38,12 @@ import { AnalyticsNotice } from "../analytics/AnalyticsNotice";
import { E2eeType } from "../e2ee/e2eeType";
import { useOptInAnalytics } from "../settings/settings";
import { useUrlParams } from "../UrlParams";
import { type ClientManager } from "../state/ClientSession";
interface Props {
client: MatrixClient;
clientManager: ClientManager | null;
}
export const RegisteredView: FC<Props> = ({ client, clientManager }) => {
export const RegisteredView: FC<Props> = ({ client }) => {
const { header } = useUrlParams();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
@@ -124,7 +122,7 @@ export const RegisteredView: FC<Props> = ({ client, clientManager }) => {
<HeaderLogo />
</LeftNav>
<RightNav>
<UserMenuContainer clientManager={clientManager} />
<UserMenuContainer />
</RightNav>
</Header>
)}
-139
View File
@@ -1,139 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { type FC } from "react";
import { MemoryRouter, useLocation } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { UnauthenticatedView } from "./UnauthenticatedView";
import { type ClientManager } from "../state/ClientSession";
import { constant } from "../state/Behavior";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import type * as matrixUtils from "../utils/matrix";
import { createRoom, getRelativeRoomUrl } from "../utils/matrix";
import { E2eeType } from "../e2ee/e2eeType";
vi.mock("../auth/useRecaptcha", () => ({
useRecaptcha: () => ({
execute: vi.fn().mockResolvedValue("captcha-response"),
reset,
recaptchaId: "recaptcha",
}),
}));
vi.mock("../auth/useRegistrationTerms", () => ({
useRegistrationTerms: () => ({ recaptchaKey: "site-key" }),
}));
vi.mock("../auth/generateRandomName", () => ({
generateRandomName: () => "Random Name",
}));
vi.mock("../utils/matrix", async (importOriginal) => ({
...(await importOriginal<typeof matrixUtils>()),
createRoom: vi.fn(),
}));
vi.mock("../UserMenuContainer", () => ({ UserMenuContainer: () => null }));
const reset = vi.fn();
const client = {} as MatrixClient;
afterEach(() => vi.clearAllMocks());
test("registers a guest, creates their call and signs them in", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({ client, setSignedIn });
vi.mocked(createRoom).mockResolvedValue({
roomId: "!call:example.org",
alias: "#my-call:example.org",
password: "secret",
});
renderView(manager);
await submit("My Call", "Alice");
expect(manager.register).toHaveBeenCalledWith(
"Random Name",
expect.stringMatching(/^.{16}$/),
"Alice",
"captcha-response",
true,
);
expect(createRoom).toHaveBeenCalledWith(
client,
"My Call",
E2eeType.SHARED_KEY,
);
expect(setSignedIn).toHaveBeenCalled();
const url = getRelativeRoomUrl(
"!call:example.org",
{ kind: E2eeType.SHARED_KEY, secret: "secret" },
"My Call",
);
expect(await screen.findByText(`at ${url}`)).toBeVisible();
});
test("signs in only once the user chooses to join a call that exists", async () => {
const manager = mockManager();
const setSignedIn = vi.fn();
vi.mocked(manager.register).mockResolvedValue({ client, setSignedIn });
vi.mocked(createRoom).mockRejectedValue({ errcode: "M_ROOM_IN_USE" });
renderView(manager);
await submit("My Call", "Alice");
const join = await screen.findByRole("button", { name: "Yes, join call" });
expect(setSignedIn).not.toHaveBeenCalled();
await userEvent.click(join);
expect(setSignedIn).toHaveBeenCalled();
expect(await screen.findByText("at /my-call")).toBeVisible();
});
test("shows why registering failed and resets the captcha", async () => {
const manager = mockManager();
vi.mocked(manager.register).mockRejectedValue(new Error("Rate limited"));
renderView(manager);
await submit("My Call", "Alice");
expect(await screen.findByText("Rate limited")).toBeVisible();
expect(reset).toHaveBeenCalled();
expect(createRoom).not.toHaveBeenCalled();
});
async function submit(callName: string, displayName: string): Promise<void> {
const user = userEvent.setup();
await user.type(screen.getByTestId("home_callName"), callName);
await user.type(screen.getByTestId("home_displayName"), displayName);
await user.click(screen.getByTestId("home_go"));
}
function mockManager(): ClientManager {
return {
login: vi.fn(),
register: vi.fn(),
logout: vi.fn(),
client$: constant(undefined),
};
}
const WhereAmI: FC = () => {
const { pathname, search, hash } = useLocation();
return <span>{`at ${pathname}${search}${hash}`}</span>;
};
function renderView(manager: ClientManager): void {
render(
<MemoryRouter initialEntries={["/"]}>
<UrlParamsProvider value={computeUrlParams()}>
<UnauthenticatedView clientManager={manager} />
<WhereAmI />
</UrlParamsProvider>
</MemoryRouter>,
);
}
+26 -18
View File
@@ -12,7 +12,7 @@ import { Button, Heading, Text } from "@vector-im/compound-web";
import { logger } from "matrix-js-sdk/lib/logger";
import { useNavigate } from "react-router-dom";
import { type ClientManager } from "../state/ClientSession";
import { useClient } from "../ClientContext";
import { Header, HeaderLogo, LeftNav, RightNav } from "../Header";
import { UserMenuContainer } from "../UserMenuContainer";
import { FieldRow, InputField, ErrorMessage } from "../input/Input";
@@ -22,7 +22,7 @@ import {
roomAliasLocalpartFromRoomName,
sanitiseRoomNameInput,
} from "../utils/matrix";
import { useRegistrationTerms } from "../auth/useRegistrationTerms";
import { useInteractiveRegistration } from "../auth/useInteractiveRegistration";
import { JoinExistingCallModal } from "./JoinExistingCallModal";
import { useRecaptcha } from "../auth/useRecaptcha";
import { Form } from "../form/Form";
@@ -36,17 +36,13 @@ import { useOptInAnalytics } from "../settings/settings";
import { ExternalLink, Link } from "../button/Link";
import { useUrlParams } from "../UrlParams";
interface Props {
clientManager: ClientManager;
}
export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
const { register } = clientManager;
export const UnauthenticatedView: FC = () => {
const { setClient } = useClient();
const { header } = useUrlParams();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
const [optInAnalytics] = useOptInAnalytics();
const { recaptchaKey } = useRegistrationTerms();
const { recaptchaKey, register } = useInteractiveRegistration();
const { execute, reset, recaptchaId } = useRecaptcha(recaptchaKey);
const [joinExistingCallModalOpen, setJoinExistingCallModalOpen] =
@@ -71,9 +67,7 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
setLoading(true);
const recaptchaResponse = await execute();
const userName = generateRandomName();
// Signed in only once the call exists too: this view is replaced the
// moment the session has a user, and the call is what they came for
const { client, setSignedIn } = await register(
const [client, session] = await register(
userName,
secureRandomString(16),
displayName,
@@ -89,12 +83,15 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
E2eeType.SHARED_KEY,
);
} catch (error) {
if (!setClient) {
throw error;
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
if (error.errcode === "M_ROOM_IN_USE") {
// Wrapped once more, as a bare function would be taken for an updater
setOnFinished(() => () => {
setSignedIn();
setOnFinished(() => {
setClient(client, session);
const aliasLocalpart = roomAliasLocalpartFromRoomName(roomName);
navigate(`/${aliasLocalpart}`)?.catch((error) => {
logger.error("Failed to navigate to alias localpart", error);
@@ -109,10 +106,14 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
}
}
// Only consider the registration successful if we managed to create the room, too
if (!setClient) {
throw new Error("setClient is undefined");
}
if (!createRoomResult.password)
throw new Error("Failed to create room with shared secret");
setSignedIn();
setClient(client, session);
await navigate(
getRelativeRoomUrl(
createRoomResult.roomId,
@@ -129,7 +130,14 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
reset();
});
},
[register, reset, execute, navigate, setJoinExistingCallModalOpen],
[
register,
reset,
execute,
navigate,
setJoinExistingCallModalOpen,
setClient,
],
);
return (
@@ -141,7 +149,7 @@ export const UnauthenticatedView: FC<Props> = ({ clientManager }) => {
<HeaderLogo />
</LeftNav>
<RightNav hideMobile>
<UserMenuContainer clientManager={clientManager} />
<UserMenuContainer />
</RightNav>
</Header>
)}
+11 -26
View File
@@ -16,14 +16,10 @@ import { createRoot } from "react-dom/client";
import "./index.css";
import { logger } from "matrix-js-sdk/lib/logger";
import { App, loadStandaloneClientSession } from "./App";
import { App } from "./App";
import { init as initRageshake } from "./settings/rageshake";
import { Initializer } from "./initializer";
import { AppViewModel } from "./state/AppViewModel";
import {
pendingHostClientSession,
signedOutClientSession,
} from "./state/ClientSession";
import { globalScope } from "./state/ObservableScope";
import { getUrlParams } from "./UrlParams";
@@ -53,30 +49,19 @@ if (fatalError !== null) {
}
Initializer.initBeforeReact()
.then(async (widget) => {
.then((widget) => {
const { controlledAudioDevices, callIntent } = getUrlParams();
// As a widget, the client comes from the host over the widget API, and
// the session is the host's. Standalone, Element Call restores or creates
// a session of its own, which it also manages.
const options = { controlledAudioDevices, callIntent };
let vm: AppViewModel;
if (widget !== null) {
vm = new AppViewModel(
globalScope,
options,
pendingHostClientSession(globalScope, widget.client),
null,
);
} else if (loadStandaloneClientSession !== undefined) {
const session = await loadStandaloneClientSession(globalScope);
vm = new AppViewModel(globalScope, options, session, session);
} else {
// The embedded package opened outside a widget: no one can sign in
vm = new AppViewModel(globalScope, options, signedOutClientSession, null);
}
root.render(
<StrictMode>
<App vm={vm} widget={widget} />
<App
vm={
new AppViewModel(globalScope, {
controlledAudioDevices,
callIntent,
})
}
widget={widget}
/>
</StrictMode>,
);
})
+4 -2
View File
@@ -21,7 +21,7 @@ import {
} from "react";
import { logger } from "matrix-js-sdk/lib/logger";
import { useHostBridge } from "../HostBridge";
import { useClientState } from "../ClientContext";
import { ElementCallReactionEventType, type ReactionOption } from ".";
import { type CallViewModel } from "../state/CallViewModel/CallViewModel";
import { useBehavior } from "../useBehavior";
@@ -72,7 +72,9 @@ export const ReactionsSenderProvider = ({
/** Our own membership, which the reactions relate to, and the current reactions. */
vm: CallViewModel;
}): JSX.Element => {
const { supportsReactions } = useHostBridge();
const clientState = useClientState();
const supportsReactions =
clientState?.state === "valid" && clientState.supportedFeatures.reactions;
const myMembershipIdentifier = `${client.getUserId()}:${client.getDeviceId()}`;
const localMember = useBehavior(vm.localMember$);
+2 -3
View File
@@ -59,7 +59,7 @@ import {
} from "../utils/errors";
import {
BackgroundEffectsProvider,
createAppBackgroundEffects$,
createAppBackgroundEffects,
} from "../tracks/BackgroundEffectsContext";
import { MediaDevicesContext } from "../MediaDevicesContext";
import { constant } from "../state/Behavior";
@@ -168,7 +168,6 @@ function createCallView(
getMembersWithMembership: () => [carol],
getMxcAvatarUrl: () => null,
getJoinRule: () => JoinRule.Invite,
hasEncryptionStateEvent: () => false,
});
const rtcSession = new MockRTCSession(room, []).withMemberships(
constant([localRtcMember]),
@@ -180,7 +179,7 @@ function createCallView(
<TooltipProvider>
<MediaDevicesContext value={mockMediaDevices({})}>
<BackgroundEffectsProvider
effects={createAppBackgroundEffects$(testScope())}
effects={createAppBackgroundEffects(testScope())}
>
<CallView
backend={
+1 -3
View File
@@ -146,7 +146,7 @@ export const CallView: FC<Props> = ({
// rebuilt.
const [joined, setJoined] = useState(false);
const muteStates = useMuteStates();
const e2eeSystem = useRoomEncryptionSystem(backend);
const e2eeSystem = useRoomEncryptionSystem(backend.roomId);
// One slot for every join of this call: leaving and joining again, to
// reconnect or from the lobby, happens on the same one
@@ -225,8 +225,6 @@ interface LoadedProps extends Omit<Props, "rtcSession" | "backend"> {
| "_unstable_getStickyEvents"
| "getLiveTimeline"
| "relations"
// The invite link's encryption system
| "hasEncryptionStateEvent"
// `on`/`off`, to listen for:
// - `RoomEvent.Name` (room name)
// - `RoomStateEvent.Update` and `RoomEvent.CurrentStateUpdated` (avatar
+3 -3
View File
@@ -50,7 +50,7 @@ import { AppBar } from "../AppBar";
import { type MatrixInfo } from "./VideoPreview";
import {
BackgroundEffectsProvider,
createAppBackgroundEffects$,
createAppBackgroundEffects,
} from "../tracks/BackgroundEffectsContext";
import { initializeWidget } from "../widget";
import { RootElementProvider } from "../RootElementContext";
@@ -233,7 +233,7 @@ function renderActiveCall(slot: RTCSlot): RenderResult {
<BrowserRouter>
<MediaDevicesContext value={mockMediaDevices({})}>
<BackgroundEffectsProvider
effects={createAppBackgroundEffects$(testScope())}
effects={createAppBackgroundEffects(testScope())}
>
<TooltipProvider>
<ActiveCall
@@ -302,7 +302,7 @@ describe("ActiveCall", () => {
<RootElementProvider value={root}>
<MediaDevicesContext value={mediaDevices}>
<BackgroundEffectsProvider
effects={createAppBackgroundEffects$(testScope())}
effects={createAppBackgroundEffects(testScope())}
>
<TooltipProvider>
<ActiveCall
-1
View File
@@ -22,7 +22,6 @@ test("InviteModal is accessible", async () => {
const room = {
roomId: "!a:example.org",
name: "Mission Control",
hasEncryptionStateEvent: () => false,
} as unknown as Room;
const onDismiss = vi.fn();
const { container } = render(
+2 -2
View File
@@ -29,14 +29,14 @@ import { useRoomEncryptionSystem } from "../e2ee/sharedKeyManagement";
import { QrCode } from "../QrCode";
interface Props {
room: Pick<Room, "roomId" | "name" | "hasEncryptionStateEvent">;
room: Pick<Room, "roomId" | "name">;
open: boolean;
onDismiss: () => void;
}
export const InviteModal: FC<Props> = ({ room, open, onDismiss }) => {
const { t } = useTranslation();
const e2eeSystem = useRoomEncryptionSystem(room);
const e2eeSystem = useRoomEncryptionSystem(room.roomId);
const url = useMemo(
() => getAbsoluteRoomUrl(room.roomId, e2eeSystem, room.name),
+3 -12
View File
@@ -17,23 +17,17 @@ import { FieldRow, InputField, ErrorMessage } from "../input/Input";
import { Form } from "../form/Form";
import { UserMenuContainer } from "../UserMenuContainer";
import { useRegisterPasswordlessUser } from "../auth/useRegisterPasswordlessUser";
import { type ClientManager } from "../state/ClientSession";
import { Config } from "../config/Config";
import { ExternalLink, Link } from "../button/Link";
import { useUrlParams } from "../UrlParams";
interface Props {
/** Null where the session is a host's and not ours to manage. */
clientManager: ClientManager | null;
}
export const RoomAuthView: FC<Props> = ({ clientManager }) => {
export const RoomAuthView: FC = () => {
const { header } = useUrlParams();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error>();
const { registerPasswordlessUser, recaptchaId } =
useRegisterPasswordlessUser(clientManager);
useRegisterPasswordlessUser();
const onSubmit = useCallback(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
@@ -67,10 +61,7 @@ export const RoomAuthView: FC<Props> = ({ clientManager }) => {
<HeaderLogo />
</LeftNav>
<RightNav>
<UserMenuContainer
preventNavigation
clientManager={clientManager}
/>
<UserMenuContainer preventNavigation />
</RightNav>
</Header>
)}
-109
View File
@@ -1,109 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, expect, test, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { type MatrixClient } from "matrix-js-sdk";
import { BehaviorSubject } from "rxjs";
import { RoomPage } from "./RoomPage";
import { ClientContextProvider } from "../ClientContext";
import { type ClientSessionState } from "../state/ClientSession";
import { computeUrlParams, UrlParamsProvider } from "../UrlParams";
import { useLoadGroupCall } from "./useLoadGroupCall";
vi.mock("./useLoadGroupCall", () => ({
useLoadGroupCall: vi.fn(() => ({ kind: "loading" })),
CallTerminatedMessage: class extends Error {},
}));
vi.mock("./useRoomName", () => ({ useRoomName: () => null }));
vi.mock("../profile/useProfile", () => ({ useProfile: () => ({}) }));
vi.mock("../auth/useRegisterPasswordlessUser", () => ({
useRegisterPasswordlessUser: () => ({ registerPasswordlessUser }),
}));
vi.mock("./RoomAuthView", () => ({
RoomAuthView: () => <span>room auth view</span>,
}));
vi.mock("../home/HomePage", () => ({
HomePage: () => <span>home page</span>,
}));
vi.mock("./CallView", () => ({
CallView: ({ isPasswordlessUser }: { isPasswordlessUser: boolean }) => (
<span>call view, passwordless: {String(isPasswordlessUser)}</span>
),
}));
vi.mock("./KnockLobbyView", () => ({ KnockLobbyView: () => null }));
vi.mock("../CallMatrixBackend", () => ({
createCallMatrixBackend: () => ({}),
}));
const registerPasswordlessUser = vi.fn().mockResolvedValue(undefined);
const room = { roomId: "!room:example.org" };
afterEach(() => vi.clearAllMocks());
test("waits for the session to be restored", () => {
renderRoom({ state: "loading" }, "/call");
expect(screen.getByRole("heading", { name: "Loading…" })).toBeVisible();
});
test("asks a signed-out user to join as a guest", () => {
renderRoom({ state: "signedOut" }, "/call");
expect(screen.getByText("room auth view")).toBeVisible();
expect(registerPasswordlessUser).not.toHaveBeenCalled();
});
test("registers a passwordless user when the URL names one", () => {
renderRoom({ state: "signedOut" }, "/call", "Alice");
expect(registerPasswordlessUser).toHaveBeenCalledWith("Alice");
});
test("falls back to the home page without a room", () => {
renderRoom(signedIn(false), "/");
expect(screen.getByText("home page")).toBeVisible();
});
test("tells the call whether its user is passwordless", () => {
vi.mocked(useLoadGroupCall).mockReturnValue({
kind: "loaded",
room,
rtcSession: {},
} as unknown as ReturnType<typeof useLoadGroupCall>);
renderRoom(signedIn(true), "/call");
expect(screen.getByText("call view, passwordless: true")).toBeVisible();
});
function signedIn(passwordlessUser: boolean): ClientSessionState {
return {
state: "signedIn",
client: {
getUserId: () => "@alice:example.org",
getRoom: () => room,
} as unknown as MatrixClient,
passwordlessUser,
};
}
function renderRoom(
state: ClientSessionState,
path: string,
displayName: string | null = null,
): void {
render(
<MemoryRouter initialEntries={[path]}>
<UrlParamsProvider value={{ ...computeUrlParams(), displayName }}>
<ClientContextProvider
value={{ state$: new BehaviorSubject<ClientSessionState>(state) }}
>
<RoomPage clientManager={null} />
</ClientContextProvider>
</UrlParamsProvider>
</MemoryRouter>,
);
}
+9 -30
View File
@@ -14,16 +14,12 @@ import {
type ReactNode,
useRef,
} from "react";
import { type MatrixClient, type MatrixError } from "matrix-js-sdk";
import { type MatrixError } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { Trans, useTranslation } from "react-i18next";
import { UnknownSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import {
useClient,
useClientSessionState,
useLoggedInSpaClient,
} from "../ClientContext";
import { useClientLegacy } from "../ClientContext";
import { ErrorPage, FullScreenView, LoadingPage } from "../FullScreenView";
import { RoomAuthView } from "./RoomAuthView";
import { CallView } from "./CallView";
@@ -38,15 +34,9 @@ import { Link } from "../button/Link";
import { ErrorView } from "../ErrorView";
import { usePageTitle } from "../usePageTitle";
import { useRoomName } from "./useRoomName";
import { type ClientManager } from "../state/ClientSession";
import { createCallMatrixBackend } from "../CallMatrixBackend";
interface Props {
/** Null where the session is a host's and not ours to manage. */
clientManager: ClientManager | null;
}
export const RoomPage: FC<Props> = ({ clientManager }): ReactNode => {
export const RoomPage: FC = (): ReactNode => {
const urlParams = useUrlParams();
const { confineToRoom, preload, header, displayName, skipLobby } = urlParams;
const { t } = useTranslation();
@@ -57,23 +47,11 @@ export const RoomPage: FC<Props> = ({ clientManager }): ReactNode => {
logger.error("No room specified");
}
const { registerPasswordlessUser } =
useRegisterPasswordlessUser(clientManager);
const { registerPasswordlessUser } = useRegisterPasswordlessUser();
const [isRegistering, setIsRegistering] = useState(false);
const spaClient = useLoggedInSpaClient(clientManager);
const suppliedClient = useClient();
// STOP GAP: a widget has no client manager, but its client is a whole one
// from our own js-sdk, which the group call loading and the backend need.
const client =
clientManager !== null
? spaClient
: (suppliedClient as MatrixClient | undefined);
const session = useClientSessionState();
const loading = session.state === "loading";
const passwordlessUser =
session.state === "signedIn" && session.passwordlessUser;
const authenticated = client !== undefined;
const { loading, authenticated, client, error, passwordlessUser } =
useClientLegacy();
const { avatarUrl, displayName: userDisplayName } = useProfile(client);
const groupCallState = useLoadGroupCall(client, roomIdOrAlias, viaServers);
@@ -231,8 +209,9 @@ export const RoomPage: FC<Props> = ({ clientManager }): ReactNode => {
};
if (loading || isRegistering) return <LoadingPage />;
if (!client) return <RoomAuthView clientManager={clientManager} />;
if (error) return <ErrorPage error={error} />;
if (!client) return <RoomAuthView />;
// TODO: This doesn't belong here, the app routes need to be reworked
if (!roomIdOrAlias) return <HomePage clientManager={clientManager} />;
if (!roomIdOrAlias) return <HomePage />;
return groupCallView();
};
+4 -4
View File
@@ -84,7 +84,7 @@ async function collectCryptoInfo(
* Collects information about secret storage and backup.
*/
async function collectRecoveryInfo(
client: Pick<MatrixClient, "secretStorage" | "isKeyBackupKeyStored">,
client: MatrixClient,
cryptoApi: CryptoApi,
body: FormData,
): Promise<void> {
@@ -142,7 +142,7 @@ export function useSubmitRageshake(
error?: Error;
available: boolean;
} {
const client = useClient();
const { client } = useClient();
const [{ sending, sent, error }, setState] = useState<{
sending: boolean;
@@ -332,7 +332,7 @@ export function useRageshakeRequest(): (
roomId: string,
rageshakeRequestId: string,
) => void {
const client = useClient();
const { client } = useClient();
const sendRageshakeRequest = useCallback(
(roomId: string, rageshakeRequestId: string) => {
@@ -355,7 +355,7 @@ export function useRageshakeRequestModal(
): ComponentProps<typeof RageshakeRequestModal> {
const [open, setOpen] = useState(false);
const onDismiss = useCallback(() => setOpen(false), [setOpen]);
const client = useClient();
const { client } = useClient();
const [rageshakeRequestId, setRageshakeRequestId] = useState<string>();
useEffect(() => {
+16 -2
View File
@@ -20,7 +20,6 @@ import { type MatrixClient } from "matrix-js-sdk/lib/client";
import { useSubmitRageshake, getRageshakeSubmitUrl } from "./submit-rageshake";
import { ClientContextProvider } from "../ClientContext";
import { hostClientSession } from "../state/ClientSession";
import { getUrlParams } from "../UrlParams";
import { mockConfig } from "../utils/test";
import { DEFAULT_CONFIG } from "../config/ConfigOptions";
@@ -75,7 +74,22 @@ function renderWithMockClient(
} as unknown as MatrixClient);
render(
<ClientContextProvider value={hostClientSession(client)}>
<ClientContextProvider
value={{
state: "valid",
disconnected: false,
supportedFeatures: {
reactions: true,
},
setClient: vi.fn(),
authenticated: {
client,
isPasswordlessUser: true,
changePassword: vi.fn(),
logout: vi.fn(),
},
}}
>
<TestComponent
sendLogs={sendLogs}
getRageshakeSubmitUrl={getRageshakeSubmitUrl}
-84
View File
@@ -1,84 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { EventEmitter } from "events";
import { expect, test, vi } from "vitest";
import { BehaviorSubject } from "rxjs";
import { ClientEvent, type MatrixClient } from "matrix-js-sdk";
import { SyncState } from "matrix-js-sdk/lib/sync";
import { AppViewModel } from "./AppViewModel";
import { type ClientSessionState } from "./ClientSession";
import { testScope } from "../utils/test";
// The devices are beside the point here, and jsdom has none to enumerate
vi.mock("./MediaDevices", () => ({ MediaDevices: class {} }));
const connectionError = Object.assign(new Error("offline"), {
name: "ConnectionError",
});
const mockClient = (): MatrixClient =>
new EventEmitter() as unknown as MatrixClient;
const failSync = (client: MatrixClient, error = connectionError): boolean =>
client.emit(ClientEvent.Sync, SyncState.Error, null, { error });
const sync = (client: MatrixClient): boolean =>
client.emit(ClientEvent.Sync, SyncState.Syncing, null);
const signedIn = (client: MatrixClient): ClientSessionState => ({
state: "signedIn",
client,
passwordlessUser: false,
});
function build(state$: BehaviorSubject<ClientSessionState>): AppViewModel {
return new AppViewModel(
testScope(),
{ controlledAudioDevices: false },
{ state$ },
null,
);
}
test("is disconnected while the client's sync fails to connect", () => {
const client = mockClient();
const vm = build(new BehaviorSubject(signedIn(client)));
const seen: boolean[] = [];
vm.disconnected$.subscribe((d) => seen.push(d));
failSync(client);
// Any other failure is not a connection problem
failSync(client, new Error("rate limited"));
failSync(client);
sync(client);
expect(seen).toEqual([false, true, false, true, false]);
});
test("starts connected again when the client changes", () => {
const first = mockClient();
const state$ = new BehaviorSubject(signedIn(first));
const vm = build(state$);
failSync(first);
expect(vm.disconnected$.value).toBe(true);
state$.next(signedIn(mockClient()));
expect(vm.disconnected$.value).toBe(false);
// The old client is no longer listened to
failSync(first);
expect(vm.disconnected$.value).toBe(false);
});
test("is not disconnected when no one is signed in", () => {
const client = mockClient();
const state$ = new BehaviorSubject(signedIn(client));
const vm = build(state$);
failSync(client);
state$.next({ state: "signedOut" });
expect(vm.disconnected$.value).toBe(false);
});
+2 -34
View File
@@ -5,15 +5,9 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { ClientEvent } from "matrix-js-sdk";
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { fromEvent, of, startWith, switchMap } from "rxjs";
import { type Behavior } from "./Behavior";
import { type ClientManager, type ClientSession } from "./ClientSession";
import { type AudioOutputOptions, MediaDevices } from "./MediaDevices";
import { type ObservableScope } from "./ObservableScope";
import { createAppBackgroundEffects$ } from "../tracks/BackgroundEffectsContext";
import { createAppBackgroundEffects } from "../tracks/BackgroundEffectsContext";
/**
* The top-level state holder for the application.
@@ -23,39 +17,13 @@ export class AppViewModel {
this.scope,
this.audioOutputOptions,
);
public readonly backgroundEffects = createAppBackgroundEffects$(this.scope);
/**
* Whether the signed-in client's sync is failing to reach the homeserver.
* False until its first sync, and whenever no one is signed in.
*/
public readonly disconnected$: Behavior<boolean> = this.scope.behavior(
this.clientSession.state$.pipe(
switchMap((state) =>
state.state === "signedIn"
? fromEvent(
state.client,
ClientEvent.Sync,
(syncState: SyncState, _old: unknown, data?: ISyncStateData) =>
syncState === "ERROR" &&
data?.error?.name === "ConnectionError",
).pipe(startWith(false))
: of(false),
),
),
);
public readonly backgroundEffects = createAppBackgroundEffects(this.scope);
// TODO: Move more application logic here. The CallViewModel, at the very
// least, ought to be accessible from this object.
/**
* @param clientSession Where the client comes from. SPA js-sdk, EW host, widget.
* @param clientManager Null where the session is a host's and not ours to manage.
*/
public constructor(
private readonly scope: ObservableScope,
private readonly audioOutputOptions: AudioOutputOptions,
public readonly clientSession: ClientSession,
public readonly clientManager: ClientManager | null,
) {}
}
+3 -3
View File
@@ -11,7 +11,7 @@ import { type BackgroundProcessorWrapper } from "@livekit/track-processors";
import {
type BackgroundEffects,
createBackgroundEffects$,
createBackgroundEffects,
type BackgroundEffectsOptions,
type BackgroundEffectsState,
} from "./BackgroundEffects";
@@ -72,7 +72,7 @@ describe("the pipeline's state", () => {
const transformer = {
onFirstFrame: undefined as (() => void) | undefined,
};
const effects = createBackgroundEffects$(testScope(), {
const effects = createBackgroundEffects(testScope(), {
supported: true,
effect$: behavior(effect, { n: "none", b: "blur" }),
clearEffect: vi.fn(),
@@ -116,7 +116,7 @@ describe("background effects", () => {
function build(
options: Partial<BackgroundEffectsOptions> = {},
): BackgroundEffects {
return createBackgroundEffects$(testScope(), {
return createBackgroundEffects(testScope(), {
supported: true,
effect$,
clearEffect,
+1 -1
View File
@@ -74,7 +74,7 @@ export interface BackgroundEffects {
}
/** Switches the pipeline as the choice changes, for as long as the scope lasts. */
export function createBackgroundEffects$(
export function createBackgroundEffects(
scope: ObservableScope,
{
supported,
-45
View File
@@ -1,45 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "vitest";
import { type MatrixClient } from "matrix-js-sdk";
import { hostClientSession, pendingHostClientSession } from "./ClientSession";
import { flushPromises, testScope } from "../utils/test";
const client = {} as MatrixClient;
test("a host's client is signed in from the start", () => {
const session = hostClientSession(client);
expect(session.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: false,
});
});
test("a pending host client is loading until it arrives", async () => {
const session = pendingHostClientSession(
testScope(),
Promise.resolve(client),
);
expect(session.state$.value).toEqual({ state: "loading" });
await flushPromises();
expect(session.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: false,
});
});
test("a pending host client that never arrives is an error", async () => {
const error = new Error("no widget API");
const session = pendingHostClientSession(testScope(), Promise.reject(error));
await flushPromises();
// An error page rather than a spinner that never ends
expect(session.state$.value).toEqual({ state: "error", error });
});
-151
View File
@@ -1,151 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { catchError, from, map, of } from "rxjs";
import { type Behavior, constant } from "./Behavior";
import { type ObservableScope } from "./ObservableScope";
/**
* What is read of a host-supplied client under a call, and by the client
* context and analytics. Stable methods only, so a host's client, from the
* host's own copy of matrix-js-sdk, will do.
*/
export type SuppliedClient = Pick<
MatrixClient,
// The disconnected banner, and stopping a client opened elsewhere
| "on"
| "off"
| "stopClient"
// Analytics, through `window.matrixclient`
| "getCrypto"
| "isGuest"
| "getAccountDataFromServer"
| "setAccountData"
// Avatars
| "mxcUrlToHttp"
| "getAccessToken"
// Rageshakes: who sends them, their crypto state, and asking others for theirs
| "getUserId"
| "getUser"
| "credentials"
| "deviceId"
| "secretStorage"
| "isKeyBackupKeyStored"
| "sendEvent"
>;
/**
* A session of Element Call's own, as the standalone app stores it.
*/
export interface StoredSession {
user_id: string;
device_id: string;
access_token: string;
passwordlessUser: boolean;
}
/**
* The client session is what every target has: the SPA, the widget and a
* component host. It is read through `useClient` and `useClientSessionState`.
*
* That is why it only holds a `SuppliedClient`. The SPA's pages outside the
* call view take the whole client from the `ClientManager` instead (see
* `useLoggedInSpaClient`).
*/
export type ClientSessionState =
| { state: "loading" }
| { state: "signedOut" }
| { state: "signedIn"; client: SuppliedClient; passwordlessUser: boolean }
| { state: "error"; error: Error };
/**
* A newly registered account, with its client started. Registering and signing
* in are separate steps, as a caller may have more to do with the account
* before the session changes hands — creating the call it was registered for,
* say.
*/
export interface Registration {
client: MatrixClient;
setSignedIn: () => void;
}
/**
* Where Element Call's client comes from. Every build has one: a session of
* Element Call's own, or one a host has supplied.
*/
export interface ClientSession {
state$: Behavior<ClientSessionState>;
}
/**
* What can be done with a client created in EC (SPA). Widget and host client
* wont have this, so views take it as a `ClientManager | null` prop.
*/
export interface ClientManager {
/** Signs in to the homeserver with a password, ending any current session. */
login: (
homeserver: string,
username: string,
password: string,
) => Promise<MatrixClient>;
/** Registers an account on the default homeserver. */
register: (
username: string,
password: string,
displayName: string,
recaptchaResponse: string,
passwordlessUser: boolean,
) => Promise<Registration>;
logout: () => Promise<void>;
/**
* The signed-in client, whole, for the SPA's own pages outside the call
* view. Undefined while no one is signed in.
*/
client$: Behavior<MatrixClient | undefined>;
}
/** No one signed in, and no session to act on. */
export const signedOutClientSession: ClientSession = {
state$: constant({ state: "signedOut" }),
};
/**
* A client supplied by the host, which owns the user's session: signed in from
* the start, nothing to restore. Used for the component target.
*/
export function hostClientSession(client: SuppliedClient): ClientSession {
return { state$: constant(signedIn(client)) };
}
/**
* A client the host is still handing over.
* Used for the embedded target, widget API.
*/
export function pendingHostClientSession(
scope: ObservableScope,
client: Promise<MatrixClient>,
): ClientSession {
return {
state$: scope.behavior<ClientSessionState>(
from(client).pipe(
map(signedIn),
catchError((e) => {
logger.error("Failed to obtain the host's client", e);
return of<ClientSessionState>({ state: "error", error: e });
}),
),
{ state: "loading" },
),
};
}
function signedIn(client: SuppliedClient): ClientSessionState {
return { state: "signedIn", client, passwordlessUser: false };
}
-269
View File
@@ -1,269 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { type MatrixClient, MatrixError, type User } from "matrix-js-sdk";
import { createStandaloneClientSession$ } from "./StandaloneClientSession";
import { type StoredSession } from "./ClientSession";
import { initClient } from "../utils/initClient";
import {
loginWithPassword,
registerWithPassword,
} from "../auth/interactiveAuth";
import { PosthogAnalytics } from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { OpenElsewhereError } from "../RichError";
import { flushPromises, testScope } from "../utils/test";
vi.mock("../utils/initClient", () => ({ initClient: vi.fn() }));
vi.mock("../auth/interactiveAuth", () => ({
loginWithPassword: vi.fn(),
registerWithPassword: vi.fn(),
}));
const SESSION_KEY = "matrix-auth-store";
const session: StoredSession = {
user_id: "@alice:example.org",
device_id: "AAAA",
access_token: "secret",
passwordlessUser: true,
};
const user = { setRawDisplayName: vi.fn(), setDisplayName: vi.fn() };
const mockClient = (): MatrixClient =>
({
stopClient: vi.fn(),
logout: vi.fn().mockResolvedValue(undefined),
clearStores: vi.fn().mockResolvedValue(undefined),
setDisplayName: vi.fn().mockResolvedValue(undefined),
getUserId: () => session.user_id,
getUser: () => user as unknown as User,
}) as Partial<MatrixClient> as MatrixClient;
const credentials = {
user_id: "@bob:example.org",
device_id: "BBBB",
access_token: "fresh",
};
const storeSession = (): void =>
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
const storedSession = (): StoredSession | null =>
JSON.parse(localStorage.getItem(SESSION_KEY) ?? "null");
beforeEach(() => {
vi.spyOn(Config, "init").mockResolvedValue(undefined);
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
localStorage.clear();
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
test("restores the stored session once the config is loaded", async () => {
storeSession();
const client = mockClient();
vi.mocked(initClient).mockResolvedValue(client);
const clientSession = createStandaloneClientSession$(testScope());
expect(clientSession.state$.value).toEqual({ state: "loading" });
await flushPromises();
expect(Config.init).toHaveBeenCalled();
expect(initClient).toHaveBeenCalledWith(
expect.objectContaining({
baseUrl: "https://hs.example.org",
accessToken: "secret",
userId: "@alice:example.org",
deviceId: "AAAA",
}),
// Restoring: the crypto store is the session's, not to be wiped
true,
);
expect(clientSession.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: true,
});
// The SPA's pages get the same client, whole
expect(clientSession.client$.value).toBe(client);
});
test("has no one signed in when there is no session to restore", async () => {
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
expect(initClient).not.toHaveBeenCalled();
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
expect(clientSession.client$.value).toBeUndefined();
});
test("drops a session the homeserver no longer knows", async () => {
storeSession();
vi.mocked(initClient).mockRejectedValue(
new MatrixError({ errcode: "M_UNKNOWN_TOKEN", error: "Unknown token" }),
);
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
expect(storedSession()).toBeNull();
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
});
test("drops the session and reports any other error", async () => {
storeSession();
const error = new Error("offline");
vi.mocked(initClient).mockRejectedValue(error);
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
expect(storedSession()).toBeNull();
// An error page rather than a spinner that never ends
expect(clientSession.state$.value).toEqual({ state: "error", error });
});
test("logs in with a password, ending the session it had", async () => {
storeSession();
const restored = mockClient();
vi.mocked(initClient).mockResolvedValueOnce(restored);
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
const client = mockClient();
vi.mocked(loginWithPassword).mockResolvedValue(credentials);
vi.mocked(initClient).mockResolvedValueOnce(client);
await expect(
clientSession.login("https://other.example.org", "bob", "hunter2"),
).resolves.toBe(client);
expect(loginWithPassword).toHaveBeenCalledWith(
"https://other.example.org",
"bob",
"hunter2",
);
// The old session is logged out before the new client starts, so that the
// crypto stores are not shared between the two
expect(restored.logout).toHaveBeenCalledWith(true);
expect(initClient).toHaveBeenLastCalledWith(
{
baseUrl: "https://other.example.org",
accessToken: "fresh",
userId: "@bob:example.org",
deviceId: "BBBB",
},
false,
);
expect(clientSession.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: false,
});
expect(storedSession()).toEqual({ ...credentials, passwordlessUser: false });
});
test("registers a passwordless account, signing in only when asked", async () => {
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
const client = mockClient();
vi.mocked(registerWithPassword).mockResolvedValue(credentials);
vi.mocked(initClient).mockResolvedValue(client);
const registration = await clientSession.register(
"bob",
"temporary",
"Bob",
"captcha",
true,
);
expect(registerWithPassword).toHaveBeenCalledWith(
"https://hs.example.org",
"bob",
"temporary",
"captcha",
);
expect(registration.client).toBe(client);
expect(client.setDisplayName).toHaveBeenCalledWith("Bob");
expect(user.setDisplayName).toHaveBeenCalledWith("Bob");
// Registered, but not yet signed in: the caller may still be setting up
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
expect(storedSession()).toBeNull();
registration.setSignedIn();
expect(clientSession.state$.value).toEqual({
state: "signedIn",
client,
passwordlessUser: true,
});
expect(storedSession()).toEqual({ ...credentials, passwordlessUser: true });
});
test("registers an account with a password of its own", async () => {
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
vi.mocked(registerWithPassword).mockResolvedValue(credentials);
vi.mocked(initClient).mockResolvedValue(mockClient());
const { setSignedIn } = await clientSession.register(
"bob",
"hunter2",
"Bob",
"captcha",
false,
);
setSignedIn();
expect(storedSession()).toEqual({ ...credentials, passwordlessUser: false });
});
test("logs out, clearing the client's stores and the stored session", async () => {
storeSession();
const client = mockClient();
vi.mocked(initClient).mockResolvedValue(client);
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
const analyticsLogout = vi.spyOn(PosthogAnalytics.instance, "logout");
await clientSession.logout();
expect(client.logout).toHaveBeenCalledWith(true);
expect(client.clearStores).toHaveBeenCalled();
expect(storedSession()).toBeNull();
expect(clientSession.state$.value).toEqual({ state: "signedOut" });
expect(clientSession.client$.value).toBeUndefined();
// Analytics forget the user along with the session
expect(analyticsLogout).toHaveBeenCalled();
});
test("claims exclusive use of storage from other instances of the app", () => {
// The channel is created with the session, so spy on the prototype rather
// than trying to replace the global.
const postMessage = vi.spyOn(BroadcastChannel.prototype, "postMessage");
createStandaloneClientSession$(testScope());
expect(postMessage).toHaveBeenCalled();
});
test("stops when another instance of the app claims storage", async () => {
storeSession();
const client = mockClient();
vi.mocked(initClient).mockResolvedValue(client);
const clientSession = createStandaloneClientSession$(testScope());
await flushPromises();
new BroadcastChannel("load").postMessage({});
await vi.waitFor(() =>
expect(clientSession.state$.value).toMatchObject({ state: "error" }),
);
expect(client.stopClient).toHaveBeenCalled();
const { value } = clientSession.state$;
expect(value.state === "error" && value.error).toBeInstanceOf(
OpenElsewhereError,
);
});
-252
View File
@@ -1,252 +0,0 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type MatrixClient, MatrixError } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import {
BehaviorSubject,
combineLatest,
fromEvent,
map,
merge,
Subject,
take,
takeUntil,
} from "rxjs";
import {
PosthogAnalytics,
RegistrationType,
} from "../analytics/PosthogAnalytics";
import { Config } from "../config/Config";
import { OpenElsewhereError } from "../RichError";
import {
loginWithPassword,
registerWithPassword,
} from "../auth/interactiveAuth";
import { initClient } from "../utils/initClient";
import { fallbackICEServerAllowed } from "../utils/matrix";
import {
type ClientManager,
type ClientSession,
type ClientSessionState,
type Registration,
type StoredSession,
} from "./ClientSession";
import { type ObservableScope } from "./ObservableScope";
const SESSION_KEY = "matrix-auth-store";
// One shared object, so that the behavior's reference check drops repeats
const LOADING: ClientSessionState = { state: "loading" };
interface ClientData {
client: MatrixClient;
passwordlessUser: boolean;
}
/**
* A client session for the SPA: restored from storage on creation, and
* signed in to, out of, or re-authenticated by the login, registration and
* account flows.
*
* To make sure we do not load/bundle the client store worker it is important
* that this is a separate file: only this module reaches `utils/initClient`,
* and therefore the client store worker, so it may only be imported on demand,
* by `loadStandaloneClientSession` in `App.tsx`.
*/
export function createStandaloneClientSession$(
scope: ObservableScope,
): ClientSession & ClientManager {
// If we have a working client
const clientData$ = new BehaviorSubject<ClientData | undefined>(undefined);
// Any hard error that will not make it possible to use the app. (reflected in state$)
const error$ = new Subject<Error>();
// To protect against multiple sessions writing to the same storage
// simultaneously, we send a broadcast message that shuts down all other
// running instances of the app.
if ("BroadcastChannel" in window) {
const loadChannel = new BroadcastChannel("load");
loadChannel.postMessage({});
fromEvent(loadChannel, "message")
.pipe(scope.bind())
.subscribe(() => {
clientData$.value?.client.stopClient();
error$.next(new OpenElsewhereError());
});
}
const restoring$ = new BehaviorSubject<boolean>(true);
restore()
.then((clientData) => clientData$.next(clientData))
.catch((e) => {
logger.error("Failed to restore the session", e);
error$.next(e);
})
.finally(() => restoring$.next(false));
const state$ = scope.behavior<ClientSessionState>(
merge(
combineLatest([restoring$, clientData$]).pipe(
map(([restoring, clientData]): ClientSessionState => {
if (restoring) {
return LOADING;
}
return clientData
? { state: "signedIn", ...clientData }
: { state: "signedOut" };
}),
takeUntil(error$),
),
error$.pipe(
take(1),
map((error): ClientSessionState => ({ state: "error", error })),
),
),
);
const client$ = scope.behavior(
clientData$.pipe(map((clientData) => clientData?.client)),
);
return {
state$,
client$,
login: async (homeserver, username, password): Promise<MatrixClient> => {
const session: StoredSession = {
...(await loginWithPassword(homeserver, username, password)),
passwordlessUser: false,
};
const client = await createClient(homeserver, session);
signIn(client, session);
return client;
},
register: async (
username,
password,
displayName,
recaptchaResponse,
passwordlessUser,
): Promise<Registration> => {
const homeserver = Config.defaultHomeserverUrl()!;
const session: StoredSession = {
...(await registerWithPassword(
homeserver,
username,
password,
recaptchaResponse,
)),
passwordlessUser,
};
const client = await createClient(homeserver, session);
await client.setDisplayName(displayName);
const user = client.getUser(client.getUserId()!)!;
user.setRawDisplayName(displayName);
user.setDisplayName(displayName);
return { client, setSignedIn: (): void => signIn(client, session) };
},
logout: async (): Promise<void> => {
const current = clientData$.value?.client;
if (!current) {
logger.warn(
"[StandaloneClientSession] Calling logout but with no current client.",
);
return;
}
await current.logout(true);
await current.clearStores();
clearSession();
clientData$.next(undefined);
PosthogAnalytics.instance.logout();
PosthogAnalytics.instance.setRegistrationType(RegistrationType.Guest);
},
};
async function restore(): Promise<ClientData | undefined> {
// The homeserver to restore against is in the config, which is loaded
// concurrently with this
await Config.init();
try {
const session = loadSession();
if (session === undefined) {
logger.log("No session stored; continuing without a client");
return;
}
logger.log("Using a standalone client");
return {
client: await initClient(
{
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: session.access_token,
userId: session.user_id,
deviceId: session.device_id,
fallbackICEServerAllowed,
livekitServiceURL: Config.get().livekit?.livekit_service_url,
},
true,
),
passwordlessUser: session.passwordlessUser,
};
} catch (e) {
// Whatever went wrong, the stored session is not to be tried again
clearSession();
if (e instanceof MatrixError && e.errcode === "M_UNKNOWN_TOKEN") {
logger.log(
"The session from local store is invalid; continuing without a client",
);
return;
}
throw e;
}
}
/**
* Starts a client for a new session, ending the current one first.
*/
async function createClient(
homeserver: string,
session: StoredSession,
): Promise<MatrixClient> {
// To not confuse the rust crypto sessions we need to log out the old
// client before initializing the new one
await clientData$.value?.client.logout(true);
return initClient(
{
baseUrl: homeserver,
accessToken: session.access_token,
userId: session.user_id,
deviceId: session.device_id,
},
false,
);
}
function signIn(client: MatrixClient, session: StoredSession): void {
saveSession(session);
clientData$.next({
client,
passwordlessUser: session.passwordlessUser,
});
}
}
function loadSession(): StoredSession | undefined {
const data = localStorage.getItem(SESSION_KEY);
return data ? JSON.parse(data) : undefined;
}
function saveSession(session: StoredSession): void {
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
}
function clearSession(): void {
localStorage.removeItem(SESSION_KEY);
}
+2 -2
View File
@@ -12,7 +12,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
BackgroundEffectsProvider,
useBackgroundEffects,
createAppBackgroundEffects$,
createAppBackgroundEffects,
} from "./BackgroundEffectsContext";
import {
type BackgroundEffects,
@@ -70,7 +70,7 @@ describe("BackgroundEffectsProvider", () => {
let effects: BackgroundEffects | undefined;
const surface = (): ReturnType<typeof createElement> =>
createElement(BackgroundEffectsProvider, {
effects: (effects ??= createAppBackgroundEffects$(testScope())),
effects: (effects ??= createAppBackgroundEffects(testScope())),
children: createElement(Surface),
});
const blur = async (on: boolean): Promise<void> => {
+3 -3
View File
@@ -22,7 +22,7 @@ import { type ObservableScope } from "../state/ObservableScope";
import {
type BackgroundEffects,
type BackgroundEffectsState,
createBackgroundEffects$,
createBackgroundEffects,
} from "../state/BackgroundEffects";
import { useBehavior } from "../useBehavior";
@@ -48,13 +48,13 @@ export function useBackgroundEffectsState$(): Behavior<BackgroundEffectsState> {
* and teardowns take their turns through the SDK, which runs one operation
* at a time on a processor.
*/
export function createAppBackgroundEffects$(
export function createAppBackgroundEffects(
scope: ObservableScope,
): BackgroundEffects {
const transformer = new BackgroundEffectTransformer({
backgroundDisabled: true,
});
return createBackgroundEffects$(scope, {
return createBackgroundEffects(scope, {
supported: supportsBackgroundProcessors(),
effect$: backgroundEffectSetting.value$,
clearEffect: () => backgroundEffectSetting.setValue("none"),
+7 -2
View File
@@ -17,8 +17,13 @@ import {
import { type ISyncStateData, type SyncState } from "matrix-js-sdk/lib/sync";
import { logger } from "matrix-js-sdk/lib/logger";
// This import pulls in many MBs of SDK code and crypto WASM which should only
// be included in full SPA builds, which is why `initClient` gets its own module.
// This import is why `initClient` has a module of its own:
// - The bundler emits the worker file (11 MB: the Matrix SDK and its crypto
// wasm) the moment it loads this import — whether or not anything ever calls
// `new IndexedDBWorker()`. Tree shaking drops the call, not the file.
// - So it may only sit in a module the component build never loads. It used
// to be in `./matrix`, which the component reaches for the room URL helpers,
// and the worker shipped in the package, unused and unusable by any host.
import IndexedDBWorker from "../IndexedDBWorker?worker";
import { getUrlParams } from "../UrlParams";
import { Config } from "../config/Config";
+5 -2
View File
@@ -5,8 +5,6 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
// *Do not* import any client stores in this module, to keep the component
// build lean.
import { ClientEvent, Preset, Visibility } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { secureRandomBase64Url } from "matrix-js-sdk/lib/randomstring";
@@ -20,6 +18,11 @@ import {
saveKeyForRoom,
} from "../e2ee/sharedKeyManagement";
// Shared with the component, which reaches this module for the room URLs. So
// nothing in here may import the client store worker: the bundler emits the
// worker file on loading the import, used or not. The one function that needs
// it, `initClient`, lives in `./initClient` for that reason.
export const fallbackICEServerAllowed =
import.meta.env.VITE_FALLBACK_STUN_ALLOWED === "true";
+83
View File
@@ -0,0 +1,83 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type MatrixClient, MatrixError } from "matrix-js-sdk";
import { initClient } from "./initClient";
import { initSPA } from "./spa";
import { Config } from "../config/Config";
import { type Session } from "../ClientContext";
vi.mock("./initClient", () => ({ initClient: vi.fn() }));
const session: Session = {
user_id: "@alice:example.org",
device_id: "AAAA",
access_token: "secret",
passwordlessUser: true,
};
const client = {} as MatrixClient;
describe("initSPA", () => {
const clearSession = vi.fn();
beforeEach(() => {
vi.spyOn(Config, "defaultHomeserverUrl").mockReturnValue(
"https://hs.example.org",
);
});
afterEach(() => {
vi.restoreAllMocks();
vi.clearAllMocks();
});
it("continues without a client when no session is stored", async () => {
await expect(initSPA(() => undefined, clearSession)).resolves.toBeNull();
expect(initClient).not.toHaveBeenCalled();
expect(clearSession).not.toHaveBeenCalled();
});
it("restores the stored session into a client", async () => {
vi.mocked(initClient).mockResolvedValue(client);
await expect(initSPA(() => session, clearSession)).resolves.toEqual({
client,
passwordlessUser: true,
});
expect(initClient).toHaveBeenCalledWith(
expect.objectContaining({
baseUrl: "https://hs.example.org",
accessToken: "secret",
userId: "@alice:example.org",
deviceId: "AAAA",
}),
// Restoring: the crypto store is the session's, not to be wiped
true,
);
});
it("drops a session the homeserver no longer knows", async () => {
vi.mocked(initClient).mockRejectedValue(
new MatrixError({ errcode: "M_UNKNOWN_TOKEN", error: "Unknown token" }),
);
await expect(initSPA(() => session, clearSession)).resolves.toBeNull();
expect(clearSession).toHaveBeenCalled();
});
it("drops the session and fails on any other error", async () => {
vi.mocked(initClient).mockRejectedValue(new Error("offline"));
await expect(initSPA(() => session, clearSession)).rejects.toThrow(
"offline",
);
expect(clearSession).toHaveBeenCalled();
});
});
+63
View File
@@ -0,0 +1,63 @@
/*
Copyright 2024 New Vector Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type ICreateClientOpts, MatrixError } from "matrix-js-sdk";
import { logger } from "matrix-js-sdk/lib/logger";
import { Config } from "../config/Config";
import { fallbackICEServerAllowed } from "./matrix";
import { initClient } from "./initClient";
import type { InitResult, Session } from "../ClientContext";
export async function initSPA(
loadSession: () => Session | undefined,
clearSession: () => void,
): Promise<InitResult | null> {
// We're running as a standalone application
try {
const session = loadSession();
if (!session) {
logger.log("No session stored; continuing without a client");
return null;
}
logger.log("Using a standalone client");
/* eslint-disable camelcase */
const { user_id, device_id, access_token, passwordlessUser } = session;
const initClientParams: ICreateClientOpts = {
baseUrl: Config.defaultHomeserverUrl()!,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
fallbackICEServerAllowed,
livekitServiceURL: Config.get().livekit?.livekit_service_url,
};
try {
const client = await initClient(initClientParams, true);
return {
client,
passwordlessUser,
};
} catch (err) {
if (err instanceof MatrixError && err.errcode === "M_UNKNOWN_TOKEN") {
// We can't use this session anymore, so let's log it out
logger.log(
"The session from local store is invalid; continuing without a client",
);
clearSession();
// returning null = "no client` pls register" (undefined = "loading" which is the current value when reaching this line)
return null;
}
throw err;
}
} catch (err) {
clearSession();
throw err;
}
}
-50
View File
@@ -75,53 +75,3 @@ for (const [property, value] of [
get: () => value,
configurable: true,
});
const storage: Record<string, string> = {};
const localStoragePolyfill = {
getItem(key: string) {
return Object.prototype.hasOwnProperty.call(storage, key)
? storage[key]
: null;
},
setItem(key: string, value: string) {
storage[key] = String(value);
},
removeItem(key: string) {
delete storage[key];
},
clear() {
for (const key in storage) {
delete storage[key];
}
},
key(index: number) {
const keys = Object.keys(storage);
return keys[index] ?? null;
},
get length() {
return Object.keys(storage).length;
},
} as unknown as Storage;
if (
typeof globalThis.localStorage === "undefined" ||
typeof globalThis.localStorage.clear !== "function"
) {
Object.defineProperty(globalThis, "localStorage", {
value: localStoragePolyfill,
writable: true,
configurable: true,
});
}
if (
typeof window !== "undefined" &&
(typeof window.localStorage === "undefined" ||
typeof window.localStorage.clear !== "function")
) {
Object.defineProperty(window, "localStorage", {
value: localStoragePolyfill,
writable: true,
configurable: true,
});
}
+4
View File
@@ -21,6 +21,10 @@ export default defineConfig((configEnv) =>
css: { include: /.+/ },
setupFiles: ["src/vitest.setup.ts"],
environment: "jsdom",
// Node's own localStorage (on by default since Node 25) is
// unusable without a file to back it and shadows jsdom's.
// We should be able to remove this once we switch to Vitest 5.
execArgv: ["--no-experimental-webstorage"],
include: [
"src/**/*.test.ts",
"src/**/*.test.tsx",