Compare commits

..
Author SHA1 Message Date
Timo K. e2be80b91b temp review proposal 2026-11-27 18:44:11 +01:00
Johannes Marbach 7148d5f2d6 Prefer the CS API for transports with both url and livekit_service_url 2026-11-25 12:03:59 +01:00
Johannes Marbach 753c7ccd0c Key the transport registry independently of the auth flow to allow the connection map to re-key later 2026-11-25 12:02:57 +01:00
Johannes Marbach 1d982467f7 Stop probing the homeserver when using the CS API which always includes the delegation endpoint 2026-11-25 12:02:02 +01:00
Johannes Marbach 511848ccdd Correctly recognise homeserver errors relayed by a widget host instead of special-casing ConnectionError 2026-11-25 11:59:43 +01:00
Timo 6be739f168 Merge pull request #4489 from element-hq/toger5/lint-externals-ci
Add the externals check to our CI and add the missing external js-sdk dep
2026-11-23 10:44:59 +01:00
renovate[bot] 382c688a2f Update ghcr.io/element-hq/element-web:develop Docker digest to b355371 (#4492)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-23 02:11:37 +00:00
renovate[bot] b480f7ebb4 Update ghcr.io/element-hq/element-web:develop Docker digest to 3a518f4 (#4491)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-22 01:52:16 +00:00
renovate[bot] b2f7fccc6e Update ghcr.io/element-hq/element-web:develop Docker digest to 2f9e5d9 (#4490)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-21 02:07:47 +00:00
Timo K. eb5c4b8633 Add the externals check to our CI and add the missing external js-sdk
dep
2026-11-20 18:15:57 +01:00
TimoandClaude Fable 5.2 f9dafcd5ea Publish late device (#4485)
* Publish a camera or microphone listed after the call view opened

Without a lobby the call decides what to publish once, as its view
mounts. A device the browser listed a moment later switched to its
default "on" without the mute handler being asked, so the button showed
on and nothing was published: the other side kept waiting for media.

The default is now asked of the handler like any other request where one
is set, so the call publishes the device. A device that comes back while
a handler is set stays off, since the user may have turned it off; the
button used to show it as on there too. Without a handler, as in the
lobby, the default is assumed at once as before.

Follows the patch tiran133 posted on the issue. A stop-gap until one
reconciler owns the local media.

Fixes https://github.com/element-hq/element-call/issues/4403

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 17:07:51 +00:00
Timo ded4471525 Merge pull request #4486 from element-hq/toger5/4479-exact-device-constraint
Exact device constraint (fixes chrome device switches)
2026-11-20 17:57:43 +01:00
Timo K. e74e83ab08 comments on what fixes the chrome issue 2026-11-20 17:15:41 +01:00
Johannes Marbach 3917bbb8f2 Merge pull request #4484 from ciefa/ciefa/fullscreen-button-clear-of-footer
Keep the tile buttons clear of the footer when it overlays the video
2026-11-20 15:33:43 +01:00
Timo K.andClaude Fable 5.2 4c66fe6f7d Ask the browser for the exact camera and microphone picked
Chromium hands back its default device for a deviceId that is only
preferred, so picking another camera reopened the same one: the preview
flashed and nothing changed. The lobby's own capture and the in-call
switch both passed the id as a preference since they stopped going
through LiveKit's track creation, which made it exact.

- The lobby media asks for the exact device, and falls back to the
  browser's choice only where the remembered device is gone.
- A track handed over to the call keeps the exact device, so that LiveKit
  reopens the same one after a mute.
- Switching the facing mode lets go of the pinned device.
- setDevice rejects where the track did not end up on the device, in the
  lobby and in the call, and keeps the track it had.

Fixes https://github.com/element-hq/element-call/issues/4479

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-20 14:07:17 +01:00
Johannes Marbach ffd6360277 Merge pull request #4472 from element-hq/johannes/stable-rtc-device
Request capability to receive m.rtc.encryption_key events
2026-11-20 11:37:20 +01:00
Johannes Marbach eabc6c0823 Merge branch 'main' into johannes/stable-rtc-device 2026-11-20 10:53:09 +01:00
renovate[bot] 7d6fbd336d Update ghcr.io/element-hq/element-web:develop Docker digest to dd8dbe3 (#4482)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-11-20 09:52:33 +00:00
Johannes Marbach f9fb566f41 Merge branch 'main' into johannes/stable-rtc-device 2026-11-20 09:21:20 +01:00
Robin ef1f69e085 Merge pull request #4342 from element-hq/valere/cleanup_sound_licence_listing
Sound listing clean-up
2026-11-19 14:42:58 -05:00
Santino Wagner 95a646b3bc Keep the tile buttons clear of the footer when it overlays the video
In a call view at most 600px high, and in a one-on-one call in a view
at most 600px wide, the footer is drawn over the video. The spotlight
tile's bottom-right buttons (full screen, expand, screen share volume)
stayed pinned to the tile's bottom edge, underneath the footer, so a
click on them landed on the footer instead.

Offset the buttons by --call-view-safe-area-inset-bottom, which the call
view already sets to the footer's height while the footer overlays the
tiles. The media foreground of a maximised tile uses the same inset. The
variable is unset in every other layout, so nothing moves there.

The rule is not limited to maximised tiles: with the layout switch on
"grid", a short window shows a spotlight tile that is not maximised but
still reaches the bottom edge.
2026-11-19 16:35:00 +01:00
Robin 86ad9bcb28 Merge pull request #4475 from element-hq/robin/clean-release-notes
Hide Docker and Actions updates from release notes
2026-11-19 09:42:41 -05:00
Johannes Marbach 7cd9ed8022 Merge pull request #4477 from element-hq/johannes/stable-rtc-member
Request capability to receive m.rtc.member events
2026-11-19 15:34:10 +01:00
Johannes Marbach 6cdcd5e83e Merge branch 'main' into johannes/stable-rtc-device 2026-11-19 09:16:01 +01:00
Johannes Marbach 29b80b62c9 Request capability to receive m.rtc.member events 2026-11-19 08:49:25 +01:00
Johannes Marbach 1cdcb62791 Request capability to receive m.rtc.encryption_key events 2026-11-18 11:16:41 +01:00
Valere 25c4f14d8f Sound listing clean-up 2026-10-09 16:06:19 +02:00
31 changed files with 1360 additions and 444 deletions
+2
View File
@@ -41,3 +41,5 @@ jobs:
run: "pnpm run lint:types"
- name: Dead code analysis
run: "pnpm run lint:knip"
- name: Component externals
run: "pnpm run lint:externals"
+2 -2
View File
@@ -19,10 +19,10 @@ services:
- ./backend/playwright_homeserver-othersite.yaml:/data/cfg/homeserver.yaml:Z
element-web:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
image: ghcr.io/element-hq/element-web:develop@sha256:b355371adc13161afc7e3c436b533f99e26bd6482e9b53e9572501821f8ddb21
element-web-1:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:f85350f2b31a7521a800d9050e9f5c0676d04cfb60675242ccc0c6e25cad7d04
image: ghcr.io/element-hq/element-web:develop@sha256:b355371adc13161afc7e3c436b533f99e26bd6482e9b53e9572501821f8ddb21
volumes:
# The other site opens the embedded package under test in place of the
# copy its image bundles (the first site opens the dev server's app.
+78
View File
@@ -0,0 +1,78 @@
/*
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, type Page } from "@playwright/test";
import { SpaHelpers } from "./spa-helpers.ts";
test.use({
launchOptions: {
args: [
"--use-fake-ui-for-media-stream",
"--use-fake-device-for-media-stream=device-count=2",
"--mute-audio",
],
},
});
test.describe("the camera menu", () => {
test.skip(
({ browserName }) => browserName !== "chromium",
"Only Chromium offers a second fake camera",
);
test("moves the preview to the camera picked, and the call after it", async ({
page,
}) => {
await page.goto("/");
await SpaHelpers.createCall(page, "Camera user", "Camera switch");
await expectCamera(page, "fake_device_0");
await selectCamera(page, "fake_device_1");
await expectCamera(page, "fake_device_1");
await page.getByTestId("lobby_joinCall").click();
await expect(page.getByTestId("name_tag")).toContainText("Camera user");
await expectCamera(page, "fake_device_1");
await selectCamera(page, "fake_device_0");
await expectCamera(page, "fake_device_0");
// Turning the camera on again opens it anew
const camera = page.getByTestId("incall_videomute");
await camera.click();
await expect(camera).toHaveAttribute("aria-checked", "false");
await camera.click();
await expect(camera).toHaveAttribute("aria-checked", "true");
await expectCamera(page, "fake_device_0");
});
});
async function selectCamera(page: Page, name: string): Promise<void> {
await page.getByRole("button", { name: "Camera", exact: true }).click();
await page.getByRole("menuitemradio", { name }).click();
// Selecting doesn't close the menu, so dismiss it.
await page.keyboard.press("Escape");
await expect(page.getByRole("menu")).not.toBeVisible();
}
/** Every video on the page shows this camera, and there is one that does. */
async function expectCamera(page: Page, label: string): Promise<void> {
await expect
.poll(async () =>
page.evaluate(() => [
...new Set(
[...document.querySelectorAll("video")].flatMap((video) =>
video.srcObject instanceof MediaStream
? video.srcObject.getVideoTracks().map((track) => track.label)
: [],
),
),
]),
)
.toEqual([label]);
}
+36
View File
@@ -0,0 +1,36 @@
/*
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 "@playwright/test";
import { SpaHelpers } from "./spa-helpers.ts";
test("The full screen button can be clicked while the footer overlays the video", async ({
page,
}) => {
await page.goto("/");
await SpaHelpers.createCall(page, "John Doe", "ShortWindow", true);
await SpaHelpers.expectVideoTilesCount(page, 1);
const fullScreenButton = page.getByRole("button", { name: "maximise" });
const footer = page.getByTestId("footer-container");
// Short enough for the footer to be drawn over the video
await page.setViewportSize({ width: 1000, height: 500 });
await expect(fullScreenButton).toBeVisible();
await page.getByTestId("videoTile").first().hover();
await expect(footer).toHaveCSS("opacity", "1");
const buttonBox = (await fullScreenButton.boundingBox())!;
const footerBox = (await footer.boundingBox())!;
expect(buttonBox.y + buttonBox.height).toBeLessThanOrEqual(footerBox.y);
await fullScreenButton.click();
await expect
.poll(async () => page.evaluate(() => document.fullscreenElement !== null))
.toBe(true);
});
+62 -16
View File
@@ -58,20 +58,20 @@ const cases: {
guestFlows: ["cs-api"],
},
{
// Publishers keep the legacy participant identity that clients predating
// MSC4195 expect, which only the JWT service assigns.
// The client-server API is preferred wherever a transport names a url.
// Clients since 0.28.1 match such a publisher by either identity.
hostShape: "url+legacy",
guestShape: "url+legacy",
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
},
{
// The MatrixRTC mode has no bearing on the choice.
hostShape: "url+legacy",
guestShape: "url+legacy",
mode: "2_0",
hostFlows: ["service-legacy"],
guestFlows: ["service-legacy"],
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
},
{
hostShape: "url",
@@ -80,10 +80,12 @@ 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", "service-default"],
guestFlows: ["service-legacy", "cs-api"],
hostFlows: ["cs-api"],
guestFlows: ["cs-api"],
},
];
@@ -160,6 +162,50 @@ 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"]),
);
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,
@@ -193,13 +239,12 @@ test("Group call with all possible transport shapes at once", async ({
});
/**
* Delegation follows the flow that authenticated the publisher: the homeserver
* for a `url`-only transport, the JWT service wherever there is one.
* Delegation follows the flow that authenticated the publisher.
*/
const delegationCases: { shape: Shape; via: Delegation["via"] }[] = [
{ shape: "url", via: "homeserver" },
{ shape: "legacy", via: "service" },
{ shape: "url+legacy", via: "service" },
{ shape: "url+legacy", via: "homeserver" },
];
for (const { shape, via } of delegationCases) {
@@ -228,10 +273,9 @@ for (const { shape, via } of delegationCases) {
await SpaHelpers.expectVideoTilesCount(page, 2);
await SpaHelpers.expectVideoTilesCount(guestPage, 2);
// 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.
// 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.
await expect
.poll(() => delegations.at(-1))
.toEqual({
@@ -241,7 +285,9 @@ for (const { shape, via } of delegationCases) {
...(via === "homeserver" && { sfuUrl }),
});
const probes = delegations.slice(0, -1);
expect(probes.some((probe) => probe.via === via)).toBe(true);
expect(probes.map((probe) => probe.via)).toEqual(
via === "service" ? ["service"] : [],
);
for (const probe of probes) {
expect(probe.status).toBeGreaterThanOrEqual(400);
expect(probe.status).not.toBe(404);
+95
View File
@@ -0,0 +1,95 @@
/*
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, type Page } from "@playwright/test";
import { widgetTest } from "../fixtures/widget-user.ts";
import { TestHelpers } from "./test-helpers.ts";
widgetTest.use({ callType: "dm" });
// The bug from issue #4403, in a real call between two users in Element Web.
// 1. Brooks' browser is made slow: it lists its camera and microphone only
// after the call is on screen.
// 2. Brooks starts a video call in a DM. A DM call has no lobby.
// 3. Whistler picks up.
// 4. Brooks' camera button shows "on".
// 5. Whistler must see two videos: their own and the one brooks sends.
// Before the fix whistler saw only their own video.
//
// What it guards: the unit tests only check the mute button's own logic. This
// test checks the whole chain: button, call, SFU, and what the other person
// really sees. The bug depends on timing (camera listed before or after the
// call opens), so the normal DM call tests pass by luck most of the time.
// This test forces the bad timing every run, so a regression shows up always
// and not only sometimes.
widgetTest(
"Publishes a camera the browser lists only once the call is on screen",
async ({ asWidget, browserName }) => {
test.skip(
browserName === "firefox",
"The is test is not working on firefox CI environment. No mic/audio device inputs so cam/mic are disabled",
);
// Two Element Webs and a real call.
test.slow();
const { brooks, whistler } = asWidget;
await listDevicesOnlyInTheCall(brooks.page);
await TestHelpers.startCallInCurrentRoom(brooks.page, false);
await expect(whistler.page.getByText("Incoming video call")).toBeVisible();
await whistler.page
.getByRole("alert")
.getByRole("button", { name: "Join" })
.click();
const brooksFrame = brooks.page
.locator('iframe[title="Element Call"]')
.contentFrame();
await expect(
brooksFrame.getByRole("switch", { name: "Stop video", checked: true }),
).toBeVisible();
// Whistler's own camera and the one brooks sends
const whistlerFrame = whistler.page
.locator('iframe[title="Element Call"]')
.contentFrame();
await TestHelpers.expectVisibleVideoCount(whistlerFrame, 2);
await expect(whistlerFrame.getByText("Waiting for media...")).toHaveCount(
0,
);
},
);
/**
* Holds the device list back in the widget until the call view shows a tile,
* as a browser that is slow to answer does. Call before the widget loads.
*
* How: it replaces the browser's `enumerateDevices` with one that waits. It
* checks every 50ms whether a video tile is on the page, waits half a second
* more, and only then gives the real list. Element Web itself (the outer
* page) is left alone; only the call inside the iframe is slowed down.
*/
async function listDevicesOnlyInTheCall(page: Page): Promise<void> {
await page.addInitScript(() => {
if (window.parent === window) return;
const devices = navigator.mediaDevices;
const enumerate = devices.enumerateDevices.bind(devices);
const inTheCall = new Promise<void>((resolve) => {
const poll = setInterval(() => {
if (document.querySelector("[data-testid='videoTile']") === null)
return;
clearInterval(poll);
setTimeout(resolve, 500);
}, 50);
});
devices.enumerateDevices = async (): Promise<MediaDeviceInfo[]> => {
await inTheCall;
return enumerate();
};
});
}
+48 -24
View File
@@ -121,10 +121,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 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
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
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
@@ -586,32 +586,56 @@ 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 per connection, from the shape
and from the role we take on the transport:
fronts the two flows and chooses between them from the shape, preferring the
client-server API wherever the transport names a `url`:
| 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 |
| 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) |
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.
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 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. 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.
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, 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.
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.
## Media: `tracks$` and `MediaTrack`
+2 -2
View File
@@ -70,6 +70,6 @@ export {
} from "./src/media-backend/livekit/videoProcessor";
// For a developer panel to check a transport before using it
export {
getSFUConfig as authenticateWithTransport,
type GetSFUConfigParams as AuthenticateWithTransportParams,
authenticateWithTransport,
type AuthenticateWithTransportParams,
} from "./src/media-backend/livekit/auth";
+53 -3
View File
@@ -24,7 +24,7 @@ describe("createLocalMedia", () => {
]);
expect(getUserMedia).toHaveBeenCalledExactlyOnceWith({
audio: { deviceId: "mic" },
audio: { deviceId: { exact: "mic" } },
video: { width: 640, height: 480, frameRate: undefined },
});
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
@@ -124,7 +124,7 @@ describe("createLocalMedia", () => {
await camera.setDevice("other");
expect(getUserMedia).toHaveBeenLastCalledWith({
video: { deviceId: "other" },
video: { deviceId: { exact: "other" } },
});
expect(first.stop).toHaveBeenCalled();
expect(processor.restart).toHaveBeenCalledOnce();
@@ -133,7 +133,53 @@ describe("createLocalMedia", () => {
expect(input).toBe(vi.mocked(processor.init).mock.calls[0][1]);
expect(tracksOn(element)).toEqual([processor.output]);
expect(media.takeTracks().get("camera")?.constraints).toEqual({
deviceId: "other",
deviceId: { exact: "other" },
});
});
it("opens the browser's choice where the device asked for is gone", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
getUserMedia.mockRejectedValueOnce(overconstrained());
const media = createLocalMedia(getUserMedia);
const tracks = await media.capture([
{ source: "microphone", deviceId: "unplugged" },
{ source: "camera", deviceId: "cam" },
]);
expect(getUserMedia).toHaveBeenLastCalledWith({ audio: {}, video: {} });
expect(tracks.map((t) => t.source)).toEqual(["microphone", "camera"]);
});
it("keeps the camera it has where another cannot be opened", async () => {
const getUserMedia = vi.mocked(fakeGetUserMedia());
const media = createLocalMedia(getUserMedia);
const [camera] = await media.capture([
{ source: "camera", deviceId: "cam" },
]);
const first = trackBehind(camera);
getUserMedia.mockRejectedValueOnce(overconstrained());
await expect(camera.setDevice("unplugged")).rejects.toThrow();
expect(first.stop).not.toHaveBeenCalled();
expect(media.takeTracks().get("camera")).toMatchObject({
track: first,
constraints: { deviceId: { exact: "cam" } },
});
});
it("lets go of the device it was opened on to face the other way", async () => {
const getUserMedia = fakeGetUserMedia({ facingMode: "user" });
const media = createLocalMedia(getUserMedia);
const [camera] = (await media.capture([
{ source: "camera", deviceId: "front" },
])) as [LocalVideoMediaTrack];
await camera.switchFacingMode();
expect(getUserMedia).toHaveBeenLastCalledWith({
video: { facingMode: "environment" },
});
});
@@ -227,6 +273,10 @@ function fakeGetUserMedia(videoSettings?: MediaTrackSettings): GetUserMedia {
});
}
function overconstrained(): Error {
return Object.assign(new Error("deviceId"), { name: "OverconstrainedError" });
}
function fakeProcessor(): VideoProcessor & { output: MediaStreamTrack } {
const output = fakeTrack("video");
return {
+83 -14
View File
@@ -78,11 +78,14 @@ export function createLocalMedia(
);
bySource.set(request.source, request);
}
const constraints: MediaStreamConstraints = {};
for (const request of bySource.values())
constraints[request.source === "microphone" ? "audio" : "video"] =
trackConstraints(request);
const stream = await getUserMedia(constraints);
const { stream, constraints } = await open(getUserMedia, {
microphone: bySource.has("microphone")
? trackConstraints(bySource.get("microphone")!)
: undefined,
camera: bySource.has("camera")
? trackConstraints(bySource.get("camera")!)
: undefined,
});
const captured: CapturedTrack[] = [];
for (const track of stream.getTracks()) {
const source: Source = track.kind === "audio" ? "microphone" : "camera";
@@ -91,7 +94,7 @@ export function createLocalMedia(
const captured_ = new CapturedTrack(
source,
track,
trackConstraints(request),
constraints[source]!,
getUserMedia,
);
capturedTracks.set(source, captured_);
@@ -139,9 +142,50 @@ export function createLocalMedia(
};
}
type SourceConstraints = Partial<Record<Source, MediaTrackConstraints>>;
/**
* Opens the devices asked for. Where one of them is gone, as a remembered
* choice that was unplugged, the browser picks instead.
*
* This is needed because we use `exact` device ids: an exact request for a
* device that no longer exists fails, where a preferred one would have opened
* another device. Without the retry here a stale choice would open nothing.
*/
async function open(
getUserMedia: GetUserMedia,
constraints: SourceConstraints,
): Promise<{ stream: MediaStream; constraints: SourceConstraints }> {
const streamOf = async (wanted: SourceConstraints): Promise<MediaStream> =>
getUserMedia({
...(wanted.microphone && { audio: wanted.microphone }),
...(wanted.camera && { video: wanted.camera }),
});
try {
return { stream: await streamOf(constraints), constraints };
} catch (e) {
if (!(e instanceof Error) || e.name !== "OverconstrainedError") throw e;
const anyDevice: SourceConstraints = {
...(constraints.microphone && {
microphone: { ...constraints.microphone, deviceId: undefined },
}),
...(constraints.camera && {
camera: { ...constraints.camera, deviceId: undefined },
}),
};
return { stream: await streamOf(anyDevice), constraints: anyDevice };
}
}
/** The constraints a request means to the browser. */
function trackConstraints(request: Request): MediaTrackConstraints {
const device = request.deviceId && { deviceId: request.deviceId };
// THE FIX for "cannot switch cameras in Chrome" (#4479), first capture.
// `exact` makes the browser open this device or fail. A plain
// `deviceId: "abc"` is only a wish, and Chromium ignores the wish and
// opens its default device.
const device = request.deviceId && {
deviceId: { exact: request.deviceId },
};
if (request.source === "microphone") return { ...device, ...request.capture };
const resolution = request.capture?.resolution;
return {
@@ -184,7 +228,12 @@ class CapturedTrack {
// The device actually in use, so that a backend asked for it again
// recognises it rather than restarting the track
const { deviceId } = track.getSettings();
const constraints = { ...this.constraints, ...(deviceId && { deviceId }) };
// `exact` here too: the call reopens the camera with these constraints
// after a mute, and must get the same device again, not the default one
const constraints = {
...this.constraints,
...(deviceId && { deviceId: { exact: deviceId } }),
};
this.finish();
return { track, constraints, muted: this.muted$.value, processor };
}
@@ -245,12 +294,28 @@ class CapturedTrack {
for (const element of this.elements) play(element, this.shown());
}
private async reacquire(constraints: MediaTrackConstraints): Promise<void> {
/**
* Replace the current with the one from the selector. On fail, keep current.
*
* The old `deviceId` and `facingMode` are removed before the new selector
* is applied. This is needed because we use `exact` device ids: if the old
* exact id stayed, asking for a new facing mode could not leave the deviceId.
* "flip camera" would do nothing.
*/
private async reacquire(
selector: Pick<MediaTrackConstraints, "deviceId" | "facingMode">,
): Promise<void> {
this.live();
this.constraints = { ...this.constraints, ...constraints };
const stream = await this.getUserMedia({
[this.track.kind]: this.constraints,
});
const constraints = {
...this.constraints,
// One selects the device at a time: a facing mode cannot move a track
// off a device it is pinned to
deviceId: undefined,
facingMode: undefined,
...selector,
};
const stream = await this.getUserMedia({ [this.track.kind]: constraints });
this.constraints = constraints;
this.track.stop();
this.track = stream.getTracks()[0];
this.track.enabled = !this.muted$.value;
@@ -288,7 +353,11 @@ class CapturedTrack {
},
setDevice: async (deviceId: string): Promise<void> => {
if (this.track.getSettings().deviceId === deviceId) return;
await this.reacquire({ deviceId });
// THE FIX for "cannot switch cameras in Chrome" (#4479), switching in
// the lobby. With a plain `{ deviceId }` Chromium reopened the same
// camera, so the preview only flashed. `exact` opens the one picked,
// or rejects and leaves the current camera running.
await this.reacquire({ deviceId: { exact: deviceId } });
},
};
if (this.source === "microphone")
+4 -1
View File
@@ -143,7 +143,10 @@ export interface LocalMediaTrack {
* from the request where the device could not be used.
*/
setEnabled(enabled: boolean): Promise<boolean>;
/** Captures from another device. Rejects for a screen share, which has none. */
/**
* Captures from another device. Rejects where that device cannot be opened,
* leaving the track on the one it had, and for a screen share, which has none.
*/
setDevice(deviceId: string): Promise<void>;
}
@@ -42,7 +42,11 @@ import {
} from "./Connection.ts";
import { ObservableScope } from "../../reactive/ObservableScope";
import { type ClientGetTokenParts, type ClientOpenIDParts } from "./auth";
import { LivekitConnectionError, MatrixRTCError } from "../../errors";
import {
LivekitConnectionError,
MatrixRTCError,
NoMatrix2AuthorizationService,
} from "../../errors";
import { testJWTToken } from "../../utils/test-fixtures";
import { ownMemberMock } from "../../utils/test";
import { mockRemoteParticipant } from "./test";
@@ -63,15 +67,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 transport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://matrix-rtc.m.localhost/livekit/sfu",
};
const url = "wss://matrix-rtc.m.localhost/livekit/sfu";
const transport: UnstableLivekitTransport = { type: "livekit", url };
/** 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",
@@ -372,6 +376,7 @@ describe("Start connection states", () => {
...connectionOpts(),
role: "publisher",
transport: { type: "livekit", livekit_service_url: serviceUrl },
flow: { kind: "openID", serviceUrl },
},
logger,
);
@@ -387,6 +392,49 @@ describe("Start connection states", () => {
expect(connection.livekitAlias).toBe("!example_room_id");
});
it("reports the CS API missing where the homeserver lacks the endpoint", async () => {
setupTest();
const opts = connectionOpts();
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).toHaveBeenCalledOnce();
});
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(), 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();
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);
+29 -10
View File
@@ -32,6 +32,7 @@ import { type CallMembershipIdentityParts } from "matrix-js-sdk/lib/matrixrtc/En
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
type AuthFlow,
type ConnectionRole,
getSFUConfig,
type SFUConfig,
@@ -42,6 +43,7 @@ import {
MatrixRTCError,
InsufficientCapacityError,
LivekitConnectionError,
NoMatrix2AuthorizationService,
PeerConnectionTimeoutError,
SFURoomCreationRestrictedError,
UnknownRTCError,
@@ -58,6 +60,10 @@ export interface ConnectionOpts {
serverName: string;
/** The Matrix client, for the token exchange. */
client: ClientGetTokenParts & ClientOpenIDParts;
/** The flow to authenticate with, for as long as the connection lives. */
flow: AuthFlow;
/** Called when the client-server API flow finds the API missing. */
onCsApiMissing: () => void;
/** The Matrix room the session is in. */
roomId: string;
/** The MatrixRTC slot the session is in. */
@@ -106,6 +112,9 @@ 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;
@@ -134,6 +143,7 @@ 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;
@@ -161,6 +171,8 @@ 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
@@ -401,16 +413,23 @@ export class Connection {
}
protected async getSFUConfig(): Promise<SFUConfig> {
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,
});
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) {
// Reported before the error surfaces: where there is a fallback, this
// connection is stopped and replaced, so it never shows as failed
if (e instanceof NoMatrix2AuthorizationService) this.onCsApiMissing();
throw e;
}
}
/**
@@ -18,7 +18,11 @@ 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 } from "./auth";
import {
type ClientGetTokenParts,
type ClientOpenIDParts,
chooseAuthFlow,
} from "./auth";
import {
LivekitConnectionFactory,
type ResolvedConnection,
@@ -50,6 +54,7 @@ function create(
): { connection: ResolvedConnection; options: RoomOptions } {
const factory = new LivekitConnectionFactory(
client(),
() => {},
"!room:example.org",
"m.call#ROOM",
publish,
@@ -62,6 +67,7 @@ function create(
"subscriber",
transport,
"example.org",
chooseAuthFlow(transport, true),
ownMemberMock,
logger,
) as ResolvedConnection;
@@ -24,6 +24,7 @@ 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,
@@ -44,6 +45,7 @@ export interface ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection;
@@ -102,6 +104,7 @@ 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[],
@@ -115,6 +118,7 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role: ConnectionRole,
transport: UnstableLivekitTransport,
serverName: string,
flow: AuthFlow,
ownMembershipIdentity: CallMembershipIdentityParts,
logger: Logger,
): Connection {
@@ -125,7 +129,9 @@ export class LivekitConnectionFactory implements ConnectionFactory {
role,
transport,
serverName,
flow,
client: this.client,
onCsApiMissing: this.onCsApiMissing,
scope,
livekitRoomFactory: () =>
new LivekitRoom(
@@ -16,11 +16,7 @@ import {
mapEpoch,
ObservableScope,
} from "../../reactive/ObservableScope";
import {
createConnectionMap$,
ConnectionMap,
keyFor,
} from "./ConnectionMap.ts";
import { createConnectionMap$, ConnectionMap } from "./ConnectionMap.ts";
import { type ConnectionFactory } from "./ConnectionFactory.ts";
import { type Connection } from "./Connection.ts";
import { ownMemberMock, withTestScheduler } from "../../utils/test";
@@ -43,6 +39,33 @@ 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[],
@@ -102,6 +125,7 @@ describe("connections$ stream", () => {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -139,6 +163,7 @@ describe("connections$ stream", () => {
a: new Epoch([TRANSPORT_2], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -150,6 +175,7 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
TRANSPORT_1.serverName,
{ kind: "openID", serviceUrl: "https://lk.example.org" },
ownMemberMock,
expect.anything(),
);
@@ -158,6 +184,7 @@ describe("connections$ stream", () => {
"subscriber",
TRANSPORT_2.transport,
TRANSPORT_2.serverName,
{ kind: "openID", serviceUrl: "https://lk.sample.com" },
ownMemberMock,
expect.anything(),
);
@@ -181,6 +208,7 @@ describe("connections$ stream", () => {
a: new Epoch([sameServiceElsewhere], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -198,6 +226,7 @@ describe("connections$ stream", () => {
"publisher",
TRANSPORT_1.transport,
"example.org",
{ kind: "openID", serviceUrl: "https://lk.example.org" },
expect.anything(),
expect.anything(),
);
@@ -225,6 +254,7 @@ describe("connections$ stream", () => {
a: new Epoch([sameUrlElsewhere], 0),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -243,42 +273,43 @@ describe("connections$ stream", () => {
});
});
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",
};
test("Shares connection between url transport and url + livekit_service_url transport", () => {
withTestScheduler(({ expectObservable, scope }) => {
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: serviceUrlTransport,
remoteTransports$: constant(new Epoch([urlAndServiceUrlTransport])),
localTransport: URL_AND_SERVICE_URL_TRANSPORT,
remoteTransports$: constant(
new Epoch([URL_TRANSPORT, SERVICE_URL_TRANSPORT]),
),
csApiUsable: true,
logger,
ownMembershipIdentity: ownMemberMock,
});
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),
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(),
);
return true;
}),
@@ -286,44 +317,35 @@ describe("connections$ stream", () => {
});
});
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",
};
test("Shares connection between livekit_service_url transport and url + livekit_service_url transport without the CS API", () => {
withTestScheduler(({ expectObservable, scope }) => {
const connectionMap$ = createConnectionMap$({
scope,
connectionFactory: fakeConnectionFactory,
localTransport: TRANSPORT_2,
localTransport: SERVICE_URL_TRANSPORT,
remoteTransports$: constant(
new Epoch([serviceUrlTransport, urlAndServiceUrlTransport]),
new Epoch([
{
...URL_AND_SERVICE_URL_TRANSPORT,
// Should pass even if local server != remote server
serverName: "elsewhere.org",
},
]),
),
csApiUsable: false,
logger,
ownMembershipIdentity: ownMemberMock,
});
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),
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),
);
return true;
}),
@@ -331,6 +353,30 @@ 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,
remoteTransports$: constant(new Epoch([])),
csApiUsable: false,
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$({
@@ -346,6 +392,7 @@ describe("connections$ stream", () => {
f: new Epoch([TRANSPORT_1, TRANSPORT_2], 5),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -386,6 +433,7 @@ describe("connections$ stream", () => {
c: new Epoch([TRANSPORT_1], 2),
}),
logger: logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
@@ -424,7 +472,7 @@ describe("connections$ stream", () => {
describe("ConnectionMap", () => {
test("warns when a second connection to the same URL is merged", () => {
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
const data = new ConnectionMap(logger);
const data = new ConnectionMap(true, logger);
const connection = TRANSPORT_1 as unknown as Connection;
const p = (identity: string): RemoteParticipant =>
({ identity }) as unknown as RemoteParticipant;
@@ -525,6 +573,7 @@ describe("connectionMap$", () => {
a: new Epoch([TRANSPORT_1, TRANSPORT_2], 0),
}),
logger,
csApiUsable: true,
ownMembershipIdentity: ownMemberMock,
});
+53 -56
View File
@@ -18,32 +18,29 @@ import {
type ObservableScope,
} from "../../reactive/ObservableScope";
import { generateItemsWithEpoch } from "../../reactive/observable";
import {
chooseAuthFlow,
type ConnectionRole,
type TransportLocator,
} from "./auth";
import { chooseAuthFlow, type TransportLocator } from "./auth";
import { type Connection } from "./Connection";
import { type ConnectionFactory } from "./ConnectionFactory";
// Branded, so that only values returned by `keyFor` can be used as keys
export type TransportKey = string & { __transportKey: true };
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 it is for uses the client-server API
* where a transport leaves the choice.
*/
export function keyFor({
transport,
serverName,
}: TransportLocator): TransportKey {
function keyFor(
{ transport, serverName }: TransportLocator,
csApiUsable: boolean,
): 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.)
// 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);
const flow = chooseAuthFlow(transport, csApiUsable);
// Serialize the fields in a consistent order
return JSON.stringify([
flow.kind,
@@ -52,18 +49,6 @@ export function keyFor({
]) as TransportKey;
}
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<
@@ -71,10 +56,16 @@ export class ConnectionMap {
{ connection: Connection; participants: RemoteParticipant[] }
>();
public constructor(private readonly logger?: Logger) {}
/**
* @param csApiUsable - What the connections were keyed with.
*/
public constructor(
private readonly csApiUsable = true,
private readonly logger?: Logger,
) {}
public add(connection: Connection, participants: RemoteParticipant[]): void {
const key = keyFor(connection);
const key = keyFor(connection, this.csApiUsable);
const existing = this.map.get(key);
if (!existing) {
this.map.set(key, { connection, participants });
@@ -95,13 +86,15 @@ export class ConnectionMap {
public getConnectionForTransport(
transport: TransportLocator,
): Connection | null {
return this.map.get(keyFor(transport))?.connection ?? null;
const key = keyFor(transport, this.csApiUsable);
return this.map.get(key)?.connection ?? null;
}
public getParticipantsForTransport(
transport: TransportLocator,
): RemoteParticipant[] {
return this.map.get(keyFor(transport))?.participants ?? [];
const key = keyFor(transport, this.csApiUsable);
return this.map.get(key)?.participants ?? [];
}
}
@@ -112,6 +105,11 @@ interface Props {
localTransport: TransportLocator;
/** Every transport some member is on, deduplicated against the local one. */
remoteTransports$: Behavior<Epoch<TransportLocator[]>>;
/**
* Whether a transport naming both a `url` and a `livekit_service_url` is
* reached through the client-server API. Fixed for the life of the map.
*/
csApiUsable: boolean;
logger: Logger;
ownMembershipIdentity: CallMembershipIdentityParts;
}
@@ -126,46 +124,45 @@ export function createConnectionMap$({
connectionFactory,
localTransport,
remoteTransports$,
csApiUsable,
logger: parentLogger,
ownMembershipIdentity,
}: Props): Behavior<Epoch<ConnectionMap>> {
const logger = parentLogger.getChild("[ConnectionMap]");
const localAndRemoteTransports$: Behavior<Epoch<TransportLocator[]>> =
scope.behavior(
remoteTransports$.pipe(
mapEpoch((remoteTransports) =>
removeDuplicateTransports([localTransport, ...remoteTransports]),
),
tap((transports) =>
logger.debug("localAndRemoteTransports$ = ", transports),
),
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) => [
keyFor(transport, csApiUsable),
transport,
]),
),
),
);
const localTransportKey = keyFor(localTransport);
tap(({ value }) =>
logger.debug("transportsByKey$ = ", [...value.values()]),
),
),
);
const localTransportKey = keyFor(localTransport, csApiUsable);
const connections$ = scope.behavior(
localAndRemoteTransports$.pipe(
transportsByKey$.pipe(
generateItemsWithEpoch(
"ConnectionMap connections$",
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) => {
// 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) => {
const { transport, serverName } = locator$.value;
const connection = connectionFactory.createConnection(
scope,
role,
key === localTransportKey ? "publisher" : "subscriber",
transport,
serverName,
chooseAuthFlow(transport, csApiUsable),
ownMembershipIdentity,
logger,
);
@@ -181,7 +178,7 @@ export function createConnectionMap$({
connections$.pipe(
switchMap(({ value: connections, epoch }) => {
if (connections.length === 0)
return of(new Epoch(new ConnectionMap(), epoch));
return of(new Epoch(new ConnectionMap(csApiUsable), epoch));
return combineLatest(
connections.map((connection) =>
connection.remoteParticipants$.pipe(
@@ -189,7 +186,7 @@ export function createConnectionMap$({
),
),
(...list) => {
const map = new ConnectionMap(logger);
const map = new ConnectionMap(csApiUsable, logger);
for (const item of list)
map.add(item.connection, item.participants);
return new Epoch(map, epoch);
@@ -148,7 +148,6 @@ 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",
@@ -169,6 +168,7 @@ describe("createLivekitBackend", () => {
participants$: BehaviorSubject<RemoteParticipant[]>;
state$: BehaviorSubject<ConnectionState>;
}[];
let onCsApiMissing: () => void;
const connected: ConnectionState = {
state: "authenticated",
livekitState: LivekitConnectionState.Connected,
@@ -177,13 +177,15 @@ 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) {
function (this: unknown, _client, onMissing) {
onCsApiMissing = onMissing;
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);
@@ -191,6 +193,7 @@ describe("createLivekitBackend", () => {
role,
transport,
serverName,
flow,
state$,
remoteParticipants$: scope.behavior(participants$),
livekitRoom: fakeLivekitRoom(),
@@ -232,17 +235,15 @@ describe("createLivekitBackend", () => {
}
// Delegation goes through whichever service authenticates us as a
// publisher: the JWT service wherever the transport names one, the
// homeserver for a `url` alone
// publisher.
it.each([
["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],
["a JWT service that delegates", exampleTransport, 401, true],
["a JWT service that does not", exampleTransport, 404, false],
["the homeserver over the JWT service", bothTransport, 404, true],
["the homeserver", urlTransport, 404, true],
])(
"prepares the local transport and asks %s about delegation",
async (_name, transport, homeserverStatus, serviceStatus, expected) => {
fetchMock.post(homeserverEndpoint, homeserverStatus);
"prepares the local transport for delegation through %s",
async (_name, transport, serviceStatus, expected) => {
fetchMock.post(
`${exampleServiceUrl}/delegate_delayed_leave`,
serviceStatus,
@@ -251,6 +252,10 @@ 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);
@@ -259,9 +264,8 @@ describe("createLivekitBackend", () => {
);
it("prepares a remote SFU's transport on its homeserver, where delegation is not possible", async () => {
// Our own homeserver would delegate, so only the SFU being remote can
// explain delegation being skipped
fetchMock.post(homeserverEndpoint, 401);
// A token through the homeserver means delegation, unless the SFU is
// another homeserver's.
const remoteTransport: UnstableLivekitTransport = {
type: "livekit",
url: "wss://sfu.sample.com",
@@ -276,7 +280,6 @@ 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" });
@@ -293,7 +296,6 @@ 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);
@@ -303,8 +305,60 @@ 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(
@@ -318,7 +372,7 @@ describe("createLivekitBackend", () => {
expect.objectContaining({
client,
membership: ownMemberMock,
transport: urlTransport,
flow: { kind: "csApi", url: "wss://sfu.example.org" },
roomId: "!room:example.org",
slotId: "m.call#ROOM",
delayId: "delay-1",
@@ -359,7 +413,6 @@ 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);
@@ -391,6 +444,30 @@ 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(
@@ -462,10 +539,11 @@ describe("createLivekitBackend", () => {
(c) => c.connection.role === "subscriber",
);
expect(remote?.connection.transport).toEqual(otherTransport);
expect(b.connections$.value.map(({ transport }) => transport)).toEqual([
bothTransport,
otherTransport,
]);
const transports = b.connections$.value.map(({ transport }) => transport);
expect(transports).toHaveLength(2);
expect(transports).toEqual(
expect.arrayContaining([bothTransport, otherTransport]),
);
transport$.next(bob(bothTransport, [legacyId]).transport$.value);
await flushPromises();
+85 -61
View File
@@ -18,6 +18,7 @@ import {
filter,
firstValueFrom,
map,
NEVER,
type Observable,
of,
switchMap,
@@ -41,18 +42,9 @@ import {
type MediaBackendContext,
type TransportCapabilities,
} from "../api";
import {
chooseAuthFlow,
delegateDelayedLeave,
type TransportLocator,
} from "./auth";
import { delegateDelayedLeave, type TransportLocator } from "./auth";
import { type Connection } from "./Connection";
import {
ConnectionMap,
createConnectionMap$,
keyFor,
type TransportKey,
} from "./ConnectionMap";
import { ConnectionMap, createConnectionMap$ } from "./ConnectionMap";
import {
LivekitConnectionFactory,
ResolvedConnection,
@@ -66,10 +58,20 @@ import {
} from "./LivekitMemberMedia";
import { createLivekitLocalMedia } from "./LocalMedia";
/** The transport we publish on, with what is fixed for its connection map. */
interface LocalTransport extends TransportLocator {
/**
* Whether a transport naming both a `url` and a `livekit_service_url` is
* reached through the client-server API: where ours names a `url`, until
* a connection finds the API missing.
*/
csApiUsable: boolean;
}
export interface LivekitBackendOptions {
/**
* `getOpenIdToken` for the JWT service flow, the MSC4195 methods for the
* client-server API flow, `baseUrl` for the delegation probe and handover.
* client-server API flow, `baseUrl` for the delegation handover.
*/
client: Pick<
MatrixClient,
@@ -103,12 +105,20 @@ export function createLivekitBackend(
: [requestsOrMedia.requests, requestsOrMedia];
const keyProvider = createKeyProvider(encryptionSystem, mediaKeys$, logger);
const transports = createTransportRegistry(scope);
const localTransport$ = new BehaviorSubject<TransportLocator | null>(null);
const localTransport$ = new BehaviorSubject<LocalTransport | null>(null);
const audioOutputDeviceId$ = new BehaviorSubject<string | undefined>(
undefined,
);
const connectionFactory = new LivekitConnectionFactory(
client,
// The MSC defines no unstable feature flag, so a homeserver that
// advertises a `url` without the API shows in a token request. Where our
// transport names a JWT service too, start over without the API.
() => {
const local = localTransport$.value;
if (local?.csApiUsable && "livekit_service_url" in local.transport)
localTransport$.next({ ...local, csApiUsable: false });
},
roomId,
slotId,
publish,
@@ -118,7 +128,8 @@ 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
// the publisher role sits on one connection, and which one is fixed per map,
// as is whether the client-server API is usable
const connectionMap$ = scope.behavior<Epoch<ConnectionMap>>(
mapScoped(scope, localTransport$, (mapScope, localTransport) =>
createConnectionMap$({
@@ -126,6 +137,7 @@ export function createLivekitBackend(
connectionFactory,
localTransport,
remoteTransports$: transports.transports$,
csApiUsable: localTransport.csApiUsable,
logger,
ownMembershipIdentity,
}),
@@ -143,13 +155,6 @@ 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);
const prepareLocalTransport = async (
@@ -162,45 +167,45 @@ export function createLivekitBackend(
ownMembershipIdentity.userId,
);
const locator: TransportLocator = { transport, serverName };
let canDelegate: Promise<boolean>;
// 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$);
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`,
);
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;
return { canDelegateDelayedLeave: false };
}
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 };
// Delegation goes through the flow that authenticated us
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,
),
};
};
const delegateLeave = async (delayId: string): Promise<void> => {
const local = localTransport$.value;
if (local === null)
const connection = localMedia_.connection$.value;
if (connection === null)
throw new MatrixRTCError("No local transport to delegate the leave to");
await delegateDelayedLeave({
client,
membership: ownMembershipIdentity,
transport: local.transport,
flow: connection.flow,
roomId,
slotId,
delayId,
@@ -225,7 +230,9 @@ export function createLivekitBackend(
}
: undefined;
}),
distinctUntilChanged((a, b) => (a && keyFor(a)) === (b && keyFor(b))),
distinctUntilChanged(
(a, b) => (a && registryKeyFor(a)) === (b && registryKeyFor(b)),
),
),
);
transports.follow(memberScope, locator$);
@@ -292,27 +299,31 @@ export function createLivekitBackend(
};
}
/** Resolves once the connection holds its token; rejects with its error otherwise. */
/** Resolves with the connection once it holds its token; rejects with its error otherwise. */
async function authenticated(
connection$: Behavior<Connection | null>,
): Promise<void> {
const state = await firstValueFrom(
): Promise<Connection> {
const { connection, state } = await firstValueFrom(
connection$.pipe(
switchMap((connection) => connection?.state$ ?? of(null)),
switchMap(
(connection) =>
connection?.state$.pipe(map((state) => ({ connection, state }))) ??
NEVER,
),
filter(
(state) =>
state !== null &&
(state.state === "authenticated" ||
state.state === "error" ||
state.state === "stopped"),
({ state }) =>
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$(
@@ -331,6 +342,19 @@ 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 registryKeyFor({ 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(
@@ -350,7 +374,7 @@ export function createTransportRegistry(
scope: ObservableScope,
): TransportRegistry {
const counts = new Map<
TransportKey,
string,
{ locator: TransportLocator; count: number }
>();
const transports = new BehaviorSubject<TransportLocator[]>([]);
@@ -358,7 +382,7 @@ export function createTransportRegistry(
transports.next([...counts.values()].map(({ locator }) => locator));
const register = (locator: TransportLocator): (() => void) => {
const key = keyFor(locator);
const key = registryKeyFor(locator);
const entry = counts.get(key) ?? { locator, count: 0 };
entry.count++;
if (entry.count === 1) {
@@ -210,11 +210,7 @@ describe("createLivekitMediaTrack", () => {
await expect(track.setEnabled(false)).resolves.toBe(false);
expect(setEnabled).toHaveBeenCalledWith("microphone", false);
await track.setDevice("mic-2");
expect(switchActiveDevice).toHaveBeenCalledWith(
"audioinput",
"mic-2",
false,
);
expect(switchActiveDevice).toHaveBeenCalledWith("audioinput", "mic-2");
});
// LiveKit's media stream track is the processed one while a processor runs,
@@ -225,19 +221,23 @@ describe("createLivekitMediaTrack", () => {
])(
"leaves a processed camera alone unless its device changes: $deviceId",
async ({ deviceId, switches }) => {
let openDevice = "cam-1";
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: {
readyState: "live",
label: "",
getSettings: () => ({ deviceId: "cam-1" }),
getSettings: () => ({ deviceId: openDevice }),
},
// What LiveKit shows as the track, with no device of its own
processor: {
processedTrack: { label: "", getSettings: () => ({}) },
},
}) as LocalVideoTrack;
const switchActiveDevice = vi.fn().mockResolvedValue(true);
const switchActiveDevice = vi.fn(async (_kind: string, id: string) => {
openDevice = id;
return Promise.resolve(true);
});
const { participant, publication, room } = fakes({
track: camera as unknown as FakeTrack,
});
@@ -253,11 +253,38 @@ describe("createLivekitMediaTrack", () => {
await track.setDevice(deviceId);
expect(switchActiveDevice.mock.calls).toEqual(
switches ? [["videoinput", deviceId, false]] : [],
switches ? [["videoinput", deviceId]] : [],
);
},
);
it("rejects where the camera did not move to the device asked for", async () => {
const camera = Object.assign(Object.create(LocalVideoTrack.prototype), {
source: Track.Source.Camera,
_mediaStreamTrack: {
readyState: "live",
label: "",
getSettings: () => ({ deviceId: "cam-1" }),
},
}) as LocalVideoTrack;
const { participant, publication, room } = fakes({
track: camera as unknown as FakeTrack,
});
const track = createLocalLivekitMediaTrack(
scope,
Object.assign(participant, {
isLocal: true,
}) as unknown as LocalParticipant,
publication as unknown as TrackPublication,
Object.assign(room, {
switchActiveDevice: vi.fn().mockResolvedValue(true),
}),
vi.fn(),
);
await expect(track.setDevice("cam-2")).rejects.toThrow("another device");
});
it("takes the facing mode of a processed camera from the camera", async () => {
const source = {
readyState: "live",
@@ -208,11 +208,27 @@ export function createLocalLivekitMediaTrack(
(await current.getDeviceId(false)) === deviceId
)
return;
// THE FIX for "cannot switch cameras in Chrome" (#4479), switching in
// the call. No third argument: LiveKit then asks for the device with
// `exact`. Passing `false` there made it a wish, which Chromium ignores
// by reopening its default device.
await room.switchActiveDevice(
base.kind === "audio" ? "audioinput" : "videoinput",
deviceId,
false,
);
// A check that the switch really happened, so that a failure is an
// error and not silence. Asked of the track again rather than taken
// from LiveKit's answer, which compares against the processed track
// too. A muted track is stopped and takes the device on turning on again
const now = publication.track;
const deviceNow =
now instanceof LocalTrack && !now.isMuted
? await now.getDeviceId(false)
: undefined;
if (deviceNow !== undefined && deviceNow !== deviceId)
throw new MatrixRTCError(
`The ${base.source} is on another device than the one asked for`,
);
},
};
if (base.kind === "audio") return { ...base, ...local };
+140 -97
View File
@@ -20,7 +20,13 @@ import {
} from "../../../utils/test-fixtures";
import type * as csApi from "./csApi";
import type * as openID from "./openID";
import { chooseAuthFlow, delegateDelayedLeave, getSFUConfig } from ".";
import {
type AuthFlow,
authenticateWithTransport,
chooseAuthFlow,
delegateDelayedLeave,
getSFUConfig,
} from ".";
const aliceId = `${aliceUserId}:${aliceDeviceId}`;
const csApiJWTToken = createJWTToken(aliceId, "via CS API");
@@ -67,6 +73,9 @@ 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`, {
@@ -100,11 +109,9 @@ describe("getSFUConfig", () => {
logger,
};
it("uses CS API with url transport", async () => {
it("uses the CS API for the CS API flow", async () => {
mockJWTService();
expect(
await getSFUConfig({ ...defaultParams, transport: urlTransport }),
).toEqual(
expect(await getSFUConfig({ ...defaultParams, flow: viaCsApi })).toEqual(
expect.objectContaining({
jwt: csApiJWTToken,
livekitAlias: "via CS API",
@@ -120,21 +127,19 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back to OpenID with url transport", async () => {
it("reports the CS API missing where the homeserver lacks the endpoint, without falling back", async () => {
mockJWTService();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses OpenID with livekit_service_url transport", async () => {
it("uses the JWT service for the OpenID flow", async () => {
mockJWTService();
expect(
await getSFUConfig({ ...defaultParams, transport: serviceUrlTransport }),
).toEqual(
expect(await getSFUConfig({ ...defaultParams, flow: viaOpenID })).toEqual(
expect.objectContaining({
jwt: defaultJWTToken,
livekitAlias: "via default endpoint",
@@ -144,80 +149,141 @@ describe("getSFUConfig", () => {
expect(jwtServiceCalls()).toEqual(["/get_token"]);
});
it("uses OpenID when subscribing with url + livekit_service_url transport", async () => {
it("does not report the CS API missing where the homeserver refuses the request", async () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
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);
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
getSFUConfig({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(error);
getSFUConfig({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
});
it("uses CS API when publishing with url transport", async () => {
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 () => {
mockJWTService();
expect(
await getSFUConfig({
...defaultParams,
transport: urlTransport,
flow: viaCsApi,
role: "publisher",
}),
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(client.getLivekitToken).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
});
it("does not fall back to OpenID when publishing with url transport", async () => {
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();
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
getSFUConfig({
expect(
await authenticateWithTransport({
...defaultParams,
transport: urlTransport,
role: "publisher",
transport: urlAndServiceUrlTransport,
}),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalled();
).toEqual(expect.objectContaining({ jwt: csApiJWTToken }));
expect(jwtServiceCalls()).toEqual([]);
});
it("uses the legacy OpenID endpoint when publishing with url + livekit_service_url transport", async () => {
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 () => {
mockJWTService();
// Subscribers predating MSC4195 expect a legacy participant identity from
// anyone advertising a membership, which only the JWT service assigns
expect(
await getSFUConfig({
client.getLivekitToken.mockRejectedValueOnce(unsupportedError);
await expect(
authenticateWithTransport({ ...defaultParams, transport: urlTransport }),
).rejects.toThrow(expect.any(NoMatrix2AuthorizationService));
expect(client.getLivekitToken).toHaveBeenCalledTimes(1);
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back where the homeserver refuses the request", async () => {
mockJWTService();
const forbidden = new MatrixError({ errcode: "M_FORBIDDEN" }, 403);
client.getLivekitToken.mockRejectedValueOnce(forbidden);
await expect(
authenticateWithTransport({
...defaultParams,
transport: urlAndServiceUrlTransport,
role: "publisher",
}),
).toEqual(
expect.objectContaining({
jwt: legacyJWTToken,
livekitAlias: "via legacy endpoint",
}),
);
expect(client.getLivekitToken).not.toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual(["/sfu/get"]);
).rejects.toThrow(forbidden);
expect(jwtServiceCalls()).toEqual([]);
});
});
@@ -242,9 +308,9 @@ describe("delegateDelayedLeave", () => {
return { delay_id, delay_timeout, delay_cs_api_url };
}
it("uses CS API with url transport", async () => {
it("uses the CS API for the CS API flow", async () => {
mockJWTService();
await delegateDelayedLeave({ ...defaultParams, transport: urlTransport });
await delegateDelayedLeave({ ...defaultParams, flow: viaCsApi });
expect(client.delegateDelayedLeave).toHaveBeenCalledWith({
url: urlTransport.url,
room_id: roomId,
@@ -255,37 +321,19 @@ describe("delegateDelayedLeave", () => {
expect(jwtServiceCalls()).toEqual([]);
});
it("does not fall back to OpenID with url transport", async () => {
it("does not fall back to the JWT service from the CS API flow", async () => {
mockJWTService();
client.delegateDelayedLeave.mockRejectedValueOnce(unsupportedError);
await expect(
delegateDelayedLeave({ ...defaultParams, transport: urlTransport }),
delegateDelayedLeave({ ...defaultParams, flow: viaCsApi }),
).rejects.toThrow();
expect(client.delegateDelayedLeave).toHaveBeenCalled();
expect(jwtServiceCalls()).toEqual([]);
});
it("uses OpenID with livekit_service_url transport", async () => {
it("uses the JWT service for the OpenID flow", async () => {
mockJWTService();
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,
});
await delegateDelayedLeave({ ...defaultParams, flow: viaOpenID });
expect(client.delegateDelayedLeave).not.toHaveBeenCalled();
expect(delegationViaJWTService()).toEqual({
delay_id: "delay123",
@@ -297,21 +345,16 @@ describe("delegateDelayedLeave", () => {
describe("chooseAuthFlow", () => {
it.each([
["url", urlTransport, { kind: "csApi", url: urlTransport.url }],
[
"livekit_service_url",
serviceUrlTransport,
{ kind: "openID", serviceUrl },
],
[
"url + livekit_service_url",
urlAndServiceUrlTransport,
{ kind: "openID", serviceUrl },
],
["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],
] as const)(
"chooses the flow for a %s transport as %s",
(_shape, transport, flow) => {
expect(chooseAuthFlow(transport)).toEqual(flow);
"chooses the flow for a %s transport with the CS API usable: %s",
(_shape, transport, csApiUsable, flow) => {
expect(chooseAuthFlow(transport, csApiUsable)).toEqual(flow);
},
);
});
+109 -43
View File
@@ -6,13 +6,10 @@ Please see LICENSE in the repository root for full details.
*/
/**
* 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.
* Authentication with a LiveKit transport.
*/
import { ConnectionError, MatrixError } from "matrix-js-sdk";
import { 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";
@@ -28,35 +25,66 @@ 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.
* endpoints. Such a homeserver answers with whatever it uses for unknown
* routes (Synapse: 404 with `M_UNRECOGNIZED`), so any 404 counts.
*/
function isEndpointUnsupported(e: unknown): boolean {
export function isCsApiUnavailable(e: unknown): boolean {
const answer = unwrapErrorDetails(e);
return (
e instanceof MatrixError &&
(e.httpStatus === 404 ||
e.errcode === "M_NOT_FOUND" ||
e.errcode === "M_UNRECOGNIZED")
answer !== undefined &&
(answer.status === 404 ||
answer.errcode === "M_NOT_FOUND" ||
answer.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.
* Tries to unwrap the details from an unknown error object, regardless of whether
* it came from the Widget API or not.
*/
export function isCsApiUnavailable(e: unknown): boolean {
if (isEndpointUnsupported(e)) return true;
return !(e instanceof MatrixError) && !(e instanceof ConnectionError);
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.
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 interface GetSFUConfigParams {
client: csApi.ClientGetTokenParts & openID.ClientOpenIDParts;
membership: CallMembershipIdentityParts;
transport: UnstableLivekitTransport;
/** The flow to authenticate with, as chosen by {@link chooseAuthFlow}. */
flow: AuthFlow;
/** The homeserver the transport belongs to. */
serverName: string;
roomId: string;
@@ -66,20 +94,23 @@ export interface GetSFUConfigParams {
}
/**
* Gets an {@link SFUConfig} appropriate for connecting to a given transport,
* using whichever auth flow is appropriate.
* 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. The MSC defines no unstable feature flag, so this is
* how a caller learns to choose its flows without the API from then on.
*/
export async function getSFUConfig({
client,
membership,
transport,
flow,
serverName,
roomId,
slotId,
role,
logger,
}: GetSFUConfigParams): Promise<SFUConfig> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "openID") {
return await openID.getSFUConfig({
client,
@@ -101,10 +132,14 @@ export async function getSFUConfig({
slotId,
});
} catch (e) {
if (isEndpointUnsupported(e)) {
logger.error(
if (isCsApiUnavailable(e)) {
logger.warn(
`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;
@@ -112,11 +147,40 @@ 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 transport we publish on. */
transport: UnstableLivekitTransport;
/** The flow that issued the token we publish with. */
flow: AuthFlow;
roomId: string;
slotId: string;
delayId: string;
@@ -133,14 +197,13 @@ export interface DelegateDelayedLeaveParams {
export async function delegateDelayedLeave({
client,
membership,
transport,
flow,
roomId,
slotId,
delayId,
delayTimeoutMs,
logger,
}: DelegateDelayedLeaveParams): Promise<void> {
const flow = chooseAuthFlow(transport);
if (flow.kind === "csApi") {
try {
await csApi.delegateDelayedLeave({
@@ -152,7 +215,7 @@ export async function delegateDelayedLeave({
delayId,
});
} catch (e) {
if (isEndpointUnsupported(e))
if (isCsApiUnavailable(e))
logger.error(
"Server misconfigured: transport contains a 'url' field but server does not support the MSC4195 delegate_delayed_leave endpoint",
);
@@ -181,18 +244,21 @@ export type AuthFlow =
| { kind: "openID"; serviceUrl: string };
/**
* 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.
* Chooses which auth flow to use for a given transport.
*/
export function chooseAuthFlow(transport: UnstableLivekitTransport): AuthFlow {
export function chooseAuthFlow(
transport: UnstableLivekitTransport,
csApiUsable: boolean,
): AuthFlow {
// If we only have url, we have no choice but to use the CS API.
if ("url" in transport && !("livekit_service_url" in transport))
return { kind: "csApi", url: transport.url };
// 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.
// 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.
return { kind: "openID", serviceUrl: transport.livekit_service_url };
}
+6 -2
View File
@@ -16,12 +16,16 @@ The following sound effects have been licensed from Pixabay, under https://pixab
The following sound effects have been originally created by Element.
- `blocked`
- `end_talk`
- `start_talk_local`
- `start_talk_remote`
- `join_call`
- `end_call`
- `left_call`
- `screen_share_started`
- `ringtone`
- `call_declined`
- `call_timeout`
- `reactions/rock`
- `reactions/wave`
- `reactions/baduntss`
- `reactions/deer`
+105
View File
@@ -169,6 +169,111 @@ describe("MuteState", () => {
expect(syncingValues).toContain(true);
expect(syncingValues.at(-1)).toBe(false);
});
// The bug from issue #4403: we join a call without a lobby, and the browser
// tells us about the camera only after the call has started.
// 1. Start with no camera, with the camera set to be on by default.
// 2. Set a handler, like the call does when it starts.
// 3. The camera shows up.
// The handler must be called with "on", so the call publishes the camera,
// and the button must show "on" only after the handler is done.
//
// What it guards: the button and the real camera must never disagree. In
// the bug the button jumped to "on" by itself and nobody told the call, so
// the other side saw "Waiting for media". If someone changes how the
// default is applied and forgets the handler again, this test fails.
test("asks the handler for the default of a device listed after it was set", async () => {
const available$ = new BehaviorSubject(new Map<string, DeviceLabel>());
const muteState = new MuteState(
testScope,
aDevice(available$),
true,
constant(false),
);
const handler = vi.fn(async (desired: boolean) => Promise.resolve(desired));
muteState.setHandler(handler);
expect(muteState.enabled$.value).toBe(false);
available$.next(aCamera);
// On only once the handler has acted on it
expect(muteState.enabled$.value).toBe(false);
await flushPromises();
expect(handler).toHaveBeenLastCalledWith(true);
expect(muteState.enabled$.value).toBe(true);
expect(muteState.syncing$.value).toBe(false);
});
// A camera that is unplugged and plugged back in during a call.
// 1. Start with a camera, on by default, and set a handler.
// 2. The camera goes away, then comes back.
// The handler is told "off" when the camera goes away and is not called
// again. The camera stays off: we must not turn on a camera that the user
// may have turned off before.
//
// What it guards: a privacy problem the fix for #4403 could cause. The fix
// sends the default "on" to the handler. If it did that every time a
// camera shows up, replugging a camera (or leaving earpiece mode) would
// start sending video without the user asking. This test fails if the
// default is ever applied a second time during a call.
test("leaves a device that comes back under a handler off", async () => {
const available$ = new BehaviorSubject(aCamera);
const muteState = new MuteState(
testScope,
aDevice(available$),
true,
constant(false),
);
expect(muteState.enabled$.value).toBe(true);
const handler = vi.fn(async (desired: boolean) => Promise.resolve(desired));
muteState.setHandler(handler);
available$.next(new Map());
available$.next(aCamera);
await flushPromises();
expect(handler.mock.calls).toEqual([[false]]);
expect(muteState.enabled$.value).toBe(false);
});
// The lobby case, which must keep working as before: no handler is set.
// 1. Start with no camera, with the camera set to be on by default.
// 2. The camera shows up.
// The button shows "on" right away, with no waiting.
//
// What it guards: the lobby and the join read the button's value at once
// to decide which devices to open. If the fix for #4403 made the default
// wait for a handler here too, the value would be "off" for a moment and
// the lobby would open no camera. This test fails if that happens.
test("assumes the default at once where no handler is set", () => {
const available$ = new BehaviorSubject(new Map<string, DeviceLabel>());
const muteState = new MuteState(
testScope,
aDevice(available$),
true,
constant(false),
);
available$.next(aCamera);
expect(muteState.enabled$.value).toBe(true);
});
// A device list with one camera in it.
const aCamera = new Map<string, DeviceLabel>([
["fbac11", { type: "name", name: "HD Camera" }],
]);
// A fake camera whose device list the test can change while it runs.
function aDevice(
available$: BehaviorSubject<Map<string, DeviceLabel>>,
): MediaDevice<DeviceLabel, SelectedDevice> {
return {
available$,
selected$: constant({ id: "fbac11" }),
select(): void {},
} as unknown as MediaDevice<DeviceLabel, SelectedDevice>;
}
});
describe("MuteStates", () => {
+26 -10
View File
@@ -53,6 +53,8 @@ export class MuteState<Label, Selected> {
this.handler$.next(defaultHandler);
}
private devicesConnectedBefore = false;
private readonly canControlDevices$ = combineLatest([
this.device.available$,
this.forceMute$,
@@ -86,15 +88,26 @@ export class MuteState<Label, Selected> {
};
}
// Assume the default value only once devices are actually connected
let enabled = this.enabledByDefault;
// defaultHander = no-op hanlder = "no actual device handler available"
const handlerAttached = this.handler$.value !== defaultHandler;
const deviceCameBackInCall =
handlerAttached && this.devicesConnectedBefore;
// Set the flag. A marker, that we reached this code before.
this.devicesConnectedBefore = true;
const initialWanted = deviceCameBackInCall
? false
: this.enabledByDefault;
// With a handler attached we start off and let the sync below actually call
// the handler, so the switch shows "on" only once the track is really there.
// Without one (lobby) enabled = initialWanted -> no call to handler.
let enabled = handlerAttached ? false : initialWanted;
const set$ = new Subject<boolean>();
const toggle$ = new Subject<void>();
const syncing$ = new BehaviorSubject(false);
const desired$ = merge(set$, toggle$.pipe(map(() => !enabled)));
const enabled$ = new Observable<boolean>((subscriber) => {
subscriber.next(enabled);
let latestDesired = this.enabledByDefault;
let latestDesired = initialWanted;
const sync = async (): Promise<void> => {
if (enabled === latestDesired) {
@@ -120,16 +133,19 @@ export class MuteState<Label, Selected> {
}
};
const startSync = (): void => {
syncing$.next(true);
sync().catch((err) => {
// TODO: better error handling
logger.error("MuteState: handler error", err);
});
};
const s = desired$.subscribe((desired) => {
latestDesired = desired;
if (syncing$.value === false) {
syncing$.next(true);
sync().catch((err) => {
// TODO: better error handling
logger.error("MuteState: handler error", err);
});
}
if (syncing$.value === false) startSync();
});
if (enabled !== latestDesired) startSync();
return (): void => {
s.unsubscribe();
syncing$.complete();
+4 -1
View File
@@ -111,7 +111,10 @@ Please see LICENSE in the repository root for full details.
display: flex;
gap: var(--cpd-space-2x);
position: absolute;
inset-block-end: var(--cpd-space-1x);
/* Ensure that the buttons lie within the safe area */
inset-block-end: calc(
var(--call-view-safe-area-inset-bottom, 0px) + var(--cpd-space-1x)
);
inset-inline-end: var(--cpd-space-1x);
z-index: 1;
}
+2
View File
@@ -67,6 +67,7 @@ describe("widget", () => {
ElementCallReactionEventType,
EventType.RTCDecline,
EventType.RTCMembership,
"m.rtc.member",
];
const sendState = [
@@ -100,6 +101,7 @@ describe("widget", () => {
EventType.CallSDPStreamMetadataChangedPrefix,
EventType.CallReplaces,
EventType.CallEncryptionKeysPrefix,
"m.rtc.encryption_key",
];
expect(createRoomWidgetClientSpy.mock.calls[0][1]).toStrictEqual({
+2
View File
@@ -132,6 +132,7 @@ export const initializeWidget = (
ElementCallReactionEventType,
EventType.RTCDecline,
EventType.RTCMembership,
"m.rtc.member",
];
const sendState = [
@@ -162,6 +163,7 @@ export const initializeWidget = (
EventType.CallSDPStreamMetadataChangedPrefix,
EventType.CallReplaces,
EventType.CallEncryptionKeysPrefix,
"m.rtc.encryption_key",
];
const client = createRoomWidgetClient(
+1
View File
@@ -133,6 +133,7 @@ export default defineConfig(({ mode }) => {
"matrix-js-sdk/lib/models/relations-container",
"matrix-js-sdk/lib/models/room",
"matrix-js-sdk/lib/models/room-state",
"matrix-js-sdk/lib/models/room-sticky-events",
"matrix-js-sdk/lib/models/typed-event-emitter",
"matrix-js-sdk/lib/randomstring",
"matrix-js-sdk/lib/sync",
+1
View File
@@ -54,6 +54,7 @@ export default defineConfig(({ mode }) => {
"matrix-js-sdk/lib/models/relations-container",
"matrix-js-sdk/lib/models/room",
"matrix-js-sdk/lib/models/room-state",
"matrix-js-sdk/lib/models/room-sticky-events",
"matrix-js-sdk/lib/models/typed-event-emitter",
"matrix-js-sdk/lib/randomstring",
"matrix-js-sdk/lib/sync",