From 82effff13ededf2c5bfa2f257d68247fdb351dc5 Mon Sep 17 00:00:00 2001 From: lukasIO Date: Tue, 10 Nov 2026 11:13:46 +0100 Subject: [PATCH 1/5] fix(e2ee): track the local encryption state separately from remote participants Co-Authored-By: Claude Fable 5.2 --- .changeset/e2ee-send-local-state.md | 5 ++ src/e2ee/E2eeManager.ts | 17 ++--- src/e2ee/types.ts | 7 ++ src/e2ee/worker/FrameCryptor.race.test.ts | 3 +- src/e2ee/worker/FrameCryptor.test.ts | 46 +++++++++++- src/e2ee/worker/FrameCryptor.ts | 19 ++++- src/e2ee/worker/e2ee.worker.test.ts | 87 +++++++++++++++++++++++ src/e2ee/worker/e2ee.worker.ts | 36 ++++++---- 8 files changed, 192 insertions(+), 28 deletions(-) create mode 100644 .changeset/e2ee-send-local-state.md create mode 100644 src/e2ee/worker/e2ee.worker.test.ts diff --git a/.changeset/e2ee-send-local-state.md b/.changeset/e2ee-send-local-state.md new file mode 100644 index 0000000000..4da29e73ee --- /dev/null +++ b/.changeset/e2ee-send-local-state.md @@ -0,0 +1,5 @@ +--- +'livekit-client': patch +--- + +fix(e2ee): track the local encryption state separately from remote participants diff --git a/src/e2ee/E2eeManager.ts b/src/e2ee/E2eeManager.ts index afe3231cac..2e796b43ec 100644 --- a/src/e2ee/E2eeManager.ts +++ b/src/e2ee/E2eeManager.ts @@ -233,11 +233,12 @@ export class E2EEManager } /** + * Sets whether the local participant encrypts. * @internal */ setParticipantCryptorEnabled(enabled: boolean, participantIdentity: string) { this.log.debug(`set e2ee to ${enabled} for participant ${participantIdentity}`); - this.postEnable(enabled, participantIdentity); + this.postEnable(enabled, participantIdentity, true); } /** @@ -288,10 +289,7 @@ export class E2EEManager this.postKey(keyInfo, false); }); } - if ( - this.encryptionEnabled !== data.enabled && - data.participantIdentity === this.room?.localParticipant.identity - ) { + if (this.encryptionEnabled !== data.enabled && data.local) { this.emit( EncryptionEvent.ParticipantEncryptionStatusChanged, data.enabled, @@ -435,6 +433,7 @@ export class E2EEManager codec: mimeTypeToVideoCodecString(publication.trackInfo!.codecs[0].mimeType), participantIdentity: this.room!.localParticipant.identity, hasPacketTrailer: false, + operation: 'encode', }, }; @@ -532,13 +531,14 @@ export class E2EEManager this.worker.postMessage(msg); } - private postEnable(enabled: boolean, participantIdentity: string) { + private postEnable(enabled: boolean, participantIdentity: string, local = false) { if (this.worker) { const enableMsg: EnableMessage = { kind: 'enable', data: { enabled, participantIdentity, + local, }, }; this.worker.postMessage(enableMsg); @@ -593,10 +593,7 @@ export class E2EEManager }); return; } - this.setParticipantCryptorEnabled( - pub.trackInfo.encryption !== Encryption_Type.NONE, - participantIdentity, - ); + this.postEnable(pub.trackInfo.encryption !== Encryption_Type.NONE, participantIdentity); } private setupE2EEReceiver(track: RemoteTrack, remoteId: string, trackInfo?: TrackInfo) { diff --git a/src/e2ee/types.ts b/src/e2ee/types.ts index 756af8395f..5dfe49f7ca 100644 --- a/src/e2ee/types.ts +++ b/src/e2ee/types.ts @@ -89,6 +89,8 @@ export interface UpdateCodecMessage extends BaseMessage { */ previousTrackId?: string; hasPacketTrailer: boolean; + /** which cryptor the update is for, a receiver's ('decode') when omitted */ + operation?: 'encode' | 'decode'; }; } @@ -123,6 +125,11 @@ export interface EnableMessage extends BaseMessage { data: { participantIdentity: string; enabled: boolean; + /** + * Set when the app enables or disables encryption for the local participant. Only such a + * message changes whether local media is encrypted. + */ + local?: boolean; }; } diff --git a/src/e2ee/worker/FrameCryptor.race.test.ts b/src/e2ee/worker/FrameCryptor.race.test.ts index a07424331a..ea1a872c65 100644 --- a/src/e2ee/worker/FrameCryptor.race.test.ts +++ b/src/e2ee/worker/FrameCryptor.race.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vitest } from 'vitest'; import { KEY_PROVIDER_DEFAULTS } from '../constants'; import type { KeyProviderOptions } from '../types'; import { createKeyMaterialFromString } from '../utils'; -import { FrameCryptor, encryptionEnabledMap } from './FrameCryptor'; +import { FrameCryptor, encryptionEnabledMap, setLocalEncryptionEnabled } from './FrameCryptor'; import { ParticipantKeyHandler } from './ParticipantKeyHandler'; function mockRTCEncodedVideoFrame(data: Uint8Array): RTCEncodedVideoFrame { @@ -47,6 +47,7 @@ function createCryptor( const keyProviderOptions = { ...KEY_PROVIDER_DEFAULTS, ...partialKeyProviderOptions }; const keys = new ParticipantKeyHandler(participantIdentity, keyProviderOptions); encryptionEnabledMap.set(participantIdentity, true); + setLocalEncryptionEnabled(true); const cryptor = new FrameCryptor({ participantIdentity, diff --git a/src/e2ee/worker/FrameCryptor.test.ts b/src/e2ee/worker/FrameCryptor.test.ts index f4e415c495..e53e8e8ce9 100644 --- a/src/e2ee/worker/FrameCryptor.test.ts +++ b/src/e2ee/worker/FrameCryptor.test.ts @@ -8,7 +8,12 @@ import { IV_LENGTH, KEY_PROVIDER_DEFAULTS } from '../constants'; import { CryptorEvent } from '../events'; import type { KeyProviderOptions } from '../types'; import { createKeyMaterialFromString } from '../utils'; -import { FrameCryptor, encryptionEnabledMap, isFrameServerInjected } from './FrameCryptor'; +import { + FrameCryptor, + encryptionEnabledMap, + isFrameServerInjected, + setLocalEncryptionEnabled, +} from './FrameCryptor'; import { ParticipantKeyHandler } from './ParticipantKeyHandler'; import { parseH264IdrPpsId } from './naluUtils'; @@ -101,6 +106,7 @@ function prepareParticipantTest( const keys = new ParticipantKeyHandler(participantIdentity, keyProviderOptions); encryptionEnabledMap.set(participantIdentity, true); + setLocalEncryptionEnabled(true); const cryptor = new FrameCryptor({ participantIdentity, @@ -145,6 +151,40 @@ describe('FrameCryptor', () => { describe('encode', () => { afterEach(() => { encryptionEnabledMap.clear(); + setLocalEncryptionEnabled(undefined); + }); + + it('drops the frame and emits an error while the local state is unknown', async () => { + const { cryptor, input, output } = prepareParticipantTestEncoder(participantIdentity, {}); + setLocalEncryptionEnabled(undefined); + const errors: Error[] = []; + cryptor.on(CryptorEvent.Error, (e) => errors.push(e)); + + input.write(mockRTCEncodedVideoFrame(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))); + await vitest.waitFor(() => expect(errors).toHaveLength(1)); + + expect(output.chunks).toEqual([]); + }); + + it('encrypts independent of the participant state', async () => { + const { cryptor, keys, input, output } = prepareParticipantTestEncoder( + participantIdentity, + {}, + ); + await keys.setKey(await createKeyMaterialFromString('key1'), 1); + const plainLength = 16; + + encryptionEnabledMap.clear(); + input.write(mockRTCEncodedVideoFrame(new Uint8Array(plainLength))); + await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); + + cryptor.unsetParticipant(); + input.write(mockRTCEncodedVideoFrame(new Uint8Array(plainLength))); + await vitest.waitFor(() => expect(output.chunks).toHaveLength(2)); + + for (const frame of output.chunks) { + expect(frame.data.byteLength).toBeGreaterThan(plainLength); + } }); it('passthrough if participant encryption disabled', async () => { @@ -152,8 +192,8 @@ describe('FrameCryptor', () => { try { const { input, output } = prepareParticipantTestEncoder(participantIdentity, {}); - // disable encryption for participant - encryptionEnabledMap.set(participantIdentity, false); + // disable encryption for the local participant + setLocalEncryptionEnabled(false); const frame = mockRTCEncodedVideoFrame(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); diff --git a/src/e2ee/worker/FrameCryptor.ts b/src/e2ee/worker/FrameCryptor.ts index c3ae04a7b8..89a0b4fde8 100644 --- a/src/e2ee/worker/FrameCryptor.ts +++ b/src/e2ee/worker/FrameCryptor.ts @@ -40,6 +40,13 @@ const MAX_PPS_ID_ENCRYPT_ATTEMPTS = 16; export const encryptionEnabledMap: Map = new Map(); +let localEncryptionEnabled: boolean | undefined; + +/** Sets whether local media is encrypted. */ +export function setLocalEncryptionEnabled(enabled: boolean | undefined) { + localEncryptionEnabled = enabled; +} + export interface FrameCryptorConstructor { new (opts?: unknown): BaseFrameCryptor; } @@ -472,7 +479,17 @@ export class FrameCryptor extends BaseFrameCryptor { return controller.enqueue(encodedFrame); } - if (!this.isEnabled()) { + if (localEncryptionEnabled === undefined) { + this.emitThrottledError( + new CryptorError( + `encryption state unknown for track ${this.trackId}, dropping frame`, + CryptorErrorReason.InternalError, + this.participantIdentity, + ), + ); + return; + } + if (!localEncryptionEnabled) { this.appendFrameMetadata(encodedFrame); return controller.enqueue(encodedFrame); } diff --git a/src/e2ee/worker/e2ee.worker.test.ts b/src/e2ee/worker/e2ee.worker.test.ts new file mode 100644 index 0000000000..b5a092be84 --- /dev/null +++ b/src/e2ee/worker/e2ee.worker.test.ts @@ -0,0 +1,87 @@ +import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { KEY_PROVIDER_DEFAULTS } from '../constants'; +import type { E2EEWorkerMessage } from '../types'; +import { createKeyMaterialFromString } from '../utils'; +import { setLocalEncryptionEnabled } from './FrameCryptor'; + +function mockFrame(data: Uint8Array): RTCEncodedVideoFrame { + return { + data: data.buffer, + timestamp: 1, + type: 'key', + getMetadata: () => ({}), + } as RTCEncodedVideoFrame; +} + +describe('e2ee worker', () => { + const post = (msg: E2EEWorkerMessage) => + (globalThis.onmessage as (ev: { data: E2EEWorkerMessage }) => void)({ data: msg }); + + beforeAll(async () => { + vi.stubGlobal('postMessage', vi.fn()); + await import('./e2ee.worker'); + }); + + afterEach(() => { + setLocalEncryptionEnabled(undefined); + }); + + it('keeps sender and receiver cryptors with the same track id apart', async () => { + const sent: RTCEncodedVideoFrame[] = []; + let send: (frame: RTCEncodedVideoFrame) => void = () => {}; + const streams = () => ({ + readableStream: new ReadableStream(), + writableStream: new WritableStream(), + hasPacketTrailer: false, + }); + + post({ + kind: 'init', + data: { keyProviderOptions: { ...KEY_PROVIDER_DEFAULTS, sharedKey: false }, loglevel: 4 }, + }); + post({ kind: 'enable', data: { enabled: true, participantIdentity: 'me', local: true } }); + post({ + kind: 'setKey', + data: { + participantIdentity: 'me', + isPublisher: true, + key: await createKeyMaterialFromString('key'), + keyIndex: 0, + updateCurrentKeyIndex: true, + }, + }); + post({ + kind: 'encode', + data: { + ...streams(), + participantIdentity: 'me', + trackId: 'mic', + readableStream: new ReadableStream({ + start: (c) => { + send = (f) => c.enqueue(f); + }, + }), + writableStream: new WritableStream({ + write: (f) => { + sent.push(f); + }, + }), + }, + }); + post({ kind: 'enable', data: { enabled: false, participantIdentity: 'me' } }); + post({ + kind: 'decode', + data: { ...streams(), participantIdentity: 'remote', trackId: 'mic' }, + }); + post({ kind: 'removeTransform', data: { participantIdentity: 'remote', trackId: 'mic' } }); + + await vi.waitFor(() => expect(send).not.toBe(undefined)); + const plainLength = 16; + // let the queued messages run before the frame arrives + await new Promise((resolve) => setTimeout(resolve, 20)); + send(mockFrame(new Uint8Array(plainLength))); + + await vi.waitFor(() => expect(sent).toHaveLength(1)); + expect(sent[0].data.byteLength).toBeGreaterThan(plainLength); + }); +}); diff --git a/src/e2ee/worker/e2ee.worker.ts b/src/e2ee/worker/e2ee.worker.ts index a0ca1c5275..55f7c355af 100644 --- a/src/e2ee/worker/e2ee.worker.ts +++ b/src/e2ee/worker/e2ee.worker.ts @@ -19,10 +19,11 @@ import type { } from '../types'; import { DataCryptor } from './DataCryptor'; import { ErrorRateLimiter } from './ErrorRateLimiter'; -import { FrameCryptor, encryptionEnabledMap } from './FrameCryptor'; +import { FrameCryptor, encryptionEnabledMap, setLocalEncryptionEnabled } from './FrameCryptor'; import { ParticipantKeyHandler } from './ParticipantKeyHandler'; -const participantCryptors: FrameCryptor[] = []; +// senders and receivers have separate cryptors +const cryptorsByOperation: Record<'encode' | 'decode', FrameCryptor[]> = { encode: [], decode: [] }; const participantKeys: Map = new Map(); let sharedKeyHandler: ParticipantKeyHandler | undefined; let messageQueue = new AsyncQueue(); @@ -73,7 +74,11 @@ onmessage = (ev) => { workerLogger.setLevel(data.level); break; case 'enable': - setEncryptionEnabled(data.enabled, data.participantIdentity); + if (data.local) { + setLocalEncryptionEnabled(data.enabled); + } else { + setEncryptionEnabled(data.enabled, data.participantIdentity); + } workerLogger.info( `updated e2ee enabled status for ${data.participantIdentity} to ${data.enabled}`, ); @@ -81,7 +86,7 @@ onmessage = (ev) => { postMessage(ev.data); break; case 'decode': - let cryptor = getTrackCryptor(data.participantIdentity, data.trackId); + let cryptor = getTrackCryptor(kind, data.participantIdentity, data.trackId); cryptor.setHasFrameMetadata(data.hasPacketTrailer); cryptor.setupTransform( kind, @@ -92,7 +97,7 @@ onmessage = (ev) => { ); break; case 'encode': - let pubCryptor = getTrackCryptor(data.participantIdentity, data.trackId); + let pubCryptor = getTrackCryptor(kind, data.participantIdentity, data.trackId); pubCryptor.setHasFrameMetadata(data.hasPacketTrailer); pubCryptor.setupTransform( kind, @@ -185,6 +190,7 @@ onmessage = (ev) => { break; case 'updateCodec': const trackCryptor = getTrackCryptor( + data.operation ?? 'decode', data.participantIdentity, data.trackId, data.previousTrackId, @@ -214,10 +220,8 @@ onmessage = (ev) => { case 'setRTPMap': // this is only used for the local participant rtpMap = data.map; - participantCryptors.forEach((cr) => { - if (cr.getParticipantIdentity() === data.participantIdentity) { - cr.setRtpMap(data.map); - } + cryptorsByOperation.encode.forEach((cr) => { + cr.setRtpMap(data.map); }); break; case 'ratchetRequest': @@ -248,7 +252,13 @@ async function handleRatchetRequest(data: RatchetRequestMessage['data']) { } } -function getTrackCryptor(participantIdentity: string, trackId: string, previousTrackId?: string) { +function getTrackCryptor( + operation: 'encode' | 'decode', + participantIdentity: string, + trackId: string, + previousTrackId?: string, +) { + const participantCryptors = cryptorsByOperation[operation]; let cryptors = participantCryptors.filter((c) => c.getTrackId() === trackId); if (cryptors.length === 0 && previousTrackId !== undefined && previousTrackId !== trackId) { @@ -324,7 +334,7 @@ function getSharedKeyHandler() { } function unsetCryptorParticipant(trackId: string, participantIdentity: string) { - const cryptors = participantCryptors.filter( + const cryptors = cryptorsByOperation.decode.filter( (c) => c.getParticipantIdentity() === participantIdentity && c.getTrackId() === trackId, ); if (cryptors.length > 1) { @@ -384,7 +394,7 @@ function emitRatchetedKeys( function handleSifTrailer(trailer: NonSharedUint8Array) { sifTrailer = trailer; - participantCryptors.forEach((c) => { + cryptorsByOperation.decode.forEach((c) => { c.setSifTrailer(trailer); }); } @@ -399,7 +409,7 @@ if (self.RTCTransformEvent) { const options = transformer.options as ScriptTransformOptions; const { kind, participantIdentity, trackId, codec, hasPacketTrailer } = options; messageQueue.run(async () => { - const cryptor = getTrackCryptor(participantIdentity, trackId); + const cryptor = getTrackCryptor(kind, participantIdentity, trackId); cryptor.setHasFrameMetadata(hasPacketTrailer); workerLogger.debug('onrtctransform setup', { participantIdentity, trackId, codec }); cryptor.setupTransform( From 48137652e3bf83a944864cb8bac2c994f332460e Mon Sep 17 00:00:00 2001 From: lukasIO Date: Tue, 10 Nov 2026 14:13:11 +0100 Subject: [PATCH 2/5] fix(e2ee): add setLocalParticipantCryptorEnabled and deprecate setParticipantCryptorEnabled Co-Authored-By: Claude Fable 5.2 --- src/e2ee/E2eeManager.test.ts | 18 ++++++++++++++++++ src/e2ee/E2eeManager.ts | 31 +++++++++++++++++++++++-------- src/e2ee/extension.ts | 6 +++++- 3 files changed, 46 insertions(+), 9 deletions(-) diff --git a/src/e2ee/E2eeManager.test.ts b/src/e2ee/E2eeManager.test.ts index 729e2825b0..1e961ce905 100644 --- a/src/e2ee/E2eeManager.test.ts +++ b/src/e2ee/E2eeManager.test.ts @@ -237,3 +237,21 @@ describe('E2EEManager sender codec seeding', () => { expect(encode.data.codec).toBeUndefined(); }); }); + +describe('E2EEManager local encryption state', () => { + it('posts the local state from the new and from the deprecated method', () => { + const { room, worker, manager } = makeManager(); + manager.setup(room); + const enableMessages = () => + worker.postMessage.mock.calls.map(([m]) => m).filter((m: any) => m?.kind === 'enable'); + + manager.setLocalParticipantCryptorEnabled(true); + manager.setParticipantCryptorEnabled(false, 'someone-else'); + + expect(enableMessages().map((m: any) => m.data)).toEqual([ + expect.objectContaining({ enabled: true, local: true }), + expect.objectContaining({ enabled: false, local: true }), + ]); + manager.dispose(); + }); +}); diff --git a/src/e2ee/E2eeManager.ts b/src/e2ee/E2eeManager.ts index 2e796b43ec..ebdde6a7b2 100644 --- a/src/e2ee/E2eeManager.ts +++ b/src/e2ee/E2eeManager.ts @@ -54,8 +54,17 @@ export interface BaseE2EEManager { setupEngine(engine: RTCEngine): void; isEnabled: boolean; isDataChannelEncryptionEnabled: boolean; - /** @internal */ + /** + * @internal + * @deprecated use `setLocalParticipantCryptorEnabled` + */ setParticipantCryptorEnabled(enabled: boolean, participantIdentity: string): void; + /** + * Sets whether the local participant encrypts. Optional so that existing managers still + * satisfy the interface: without it, `setParticipantCryptorEnabled` is called. + * @internal + */ + setLocalParticipantCryptorEnabled?(enabled: boolean): void; /** @internal */ setSifTrailer(trailer: NonSharedUint8Array): void; encryptData(data: NonSharedUint8Array): Promise; @@ -236,9 +245,18 @@ export class E2EEManager * Sets whether the local participant encrypts. * @internal */ - setParticipantCryptorEnabled(enabled: boolean, participantIdentity: string) { - this.log.debug(`set e2ee to ${enabled} for participant ${participantIdentity}`); - this.postEnable(enabled, participantIdentity, true); + setLocalParticipantCryptorEnabled(enabled: boolean) { + this.log.debug(`set e2ee to ${enabled} for the local participant`); + this.postEnable(enabled, this.room?.localParticipant.identity ?? '', true); + } + + /** + * @internal + * @deprecated use `setLocalParticipantCryptorEnabled`. The identity is ignored: this always + * sets the state of the local participant. + */ + setParticipantCryptorEnabled(enabled: boolean, _participantIdentity: string) { + this.setLocalParticipantCryptorEnabled(enabled); } /** @@ -411,10 +429,7 @@ export class E2EEManager keyProvider.getKeys().forEach((keyInfo) => { this.postKey(keyInfo, latestKeyIndex === (keyInfo.keyIndex ?? 0)); }); - this.setParticipantCryptorEnabled( - this.room.localParticipant.isE2EEEnabled, - this.room.localParticipant.identity, - ); + this.setLocalParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled); }); room.localParticipant.on(ParticipantEvent.LocalSenderCreated, async (sender, track) => { diff --git a/src/e2ee/extension.ts b/src/e2ee/extension.ts index 05140ce032..987460a704 100644 --- a/src/e2ee/extension.ts +++ b/src/e2ee/extension.ts @@ -94,7 +94,11 @@ export const e2ee = /* @__PURE__ */ defineExtension( await room.localParticipant.setE2EEEnabled(enabled); if (room.localParticipant.identity !== '') { - manager.setParticipantCryptorEnabled(enabled, room.localParticipant.identity); + if (manager.setLocalParticipantCryptorEnabled) { + manager.setLocalParticipantCryptorEnabled(enabled); + } else { + manager.setParticipantCryptorEnabled(enabled, room.localParticipant.identity); + } } } } else { From c29d6749340b36c1821c953f5823989056176c3c Mon Sep 17 00:00:00 2001 From: lukasIO Date: Tue, 10 Nov 2026 14:41:59 +0100 Subject: [PATCH 3/5] refactor(e2ee): check for setLocalParticipantCryptorEnabled first Co-Authored-By: Claude Fable 5.2 --- src/e2ee/extension.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/e2ee/extension.ts b/src/e2ee/extension.ts index 987460a704..78802d2be8 100644 --- a/src/e2ee/extension.ts +++ b/src/e2ee/extension.ts @@ -93,12 +93,10 @@ export const e2ee = /* @__PURE__ */ defineExtension( if (room.isE2EEEnabled !== enabled) { await room.localParticipant.setE2EEEnabled(enabled); - if (room.localParticipant.identity !== '') { - if (manager.setLocalParticipantCryptorEnabled) { - manager.setLocalParticipantCryptorEnabled(enabled); - } else { - manager.setParticipantCryptorEnabled(enabled, room.localParticipant.identity); - } + if (manager.setLocalParticipantCryptorEnabled) { + manager.setLocalParticipantCryptorEnabled(enabled); + } else if (room.localParticipant.identity !== '') { + manager.setParticipantCryptorEnabled(enabled, room.localParticipant.identity); } } } else { From 786025de2b31da54f8beadf15839735f69869ae6 Mon Sep 17 00:00:00 2001 From: lukasIO Date: Tue, 10 Nov 2026 15:52:52 +0100 Subject: [PATCH 4/5] test(e2ee): simplify the new tests Co-Authored-By: Claude Fable 5.2 --- src/e2ee/E2eeManager.test.ts | 34 ++++++++++---- src/e2ee/worker/FrameCryptor.test.ts | 41 ++++++++++------- src/e2ee/worker/e2ee.worker.test.ts | 68 +++++++++++++++------------- 3 files changed, 86 insertions(+), 57 deletions(-) diff --git a/src/e2ee/E2eeManager.test.ts b/src/e2ee/E2eeManager.test.ts index 1e961ce905..8f65340668 100644 --- a/src/e2ee/E2eeManager.test.ts +++ b/src/e2ee/E2eeManager.test.ts @@ -239,19 +239,37 @@ describe('E2EEManager sender codec seeding', () => { }); describe('E2EEManager local encryption state', () => { - it('posts the local state from the new and from the deprecated method', () => { + it('posts the local state from setLocalParticipantCryptorEnabled', () => { + // Create a manager with a worker that records its messages const { room, worker, manager } = makeManager(); manager.setup(room); - const enableMessages = () => - worker.postMessage.mock.calls.map(([m]) => m).filter((m: any) => m?.kind === 'enable'); + // Enable encryption for the local participant manager.setLocalParticipantCryptorEnabled(true); - manager.setParticipantCryptorEnabled(false, 'someone-else'); - expect(enableMessages().map((m: any) => m.data)).toEqual([ - expect.objectContaining({ enabled: true, local: true }), - expect.objectContaining({ enabled: false, local: true }), - ]); + // The worker got an enable message that is marked as local + expect(worker.postMessage).toHaveBeenCalledWith({ + kind: 'enable', + data: { enabled: true, participantIdentity: '', local: true }, + }); + + manager.dispose(); + }); + + it('posts the local state from the deprecated setParticipantCryptorEnabled', () => { + // Create a manager with a worker that records its messages + const { room, worker, manager } = makeManager(); + manager.setup(room); + + // Enable encryption with the deprecated method, which ignores the identity + manager.setParticipantCryptorEnabled(true, 'someone-else'); /* <-- DIFFERENCE */ + + // The worker got an enable message that is marked as local + expect(worker.postMessage).toHaveBeenCalledWith({ + kind: 'enable', + data: { enabled: true, participantIdentity: '', local: true }, + }); + manager.dispose(); }); }); diff --git a/src/e2ee/worker/FrameCryptor.test.ts b/src/e2ee/worker/FrameCryptor.test.ts index e53e8e8ce9..4b7e32bd66 100644 --- a/src/e2ee/worker/FrameCryptor.test.ts +++ b/src/e2ee/worker/FrameCryptor.test.ts @@ -4,8 +4,10 @@ import type { FrameMetadataPublishOptions } from '../../frameMetadata/types'; import { workerLogger } from '../../logger'; import type { VideoCodec } from '../../room/track/options'; import type { NonSharedUint8Array } from '../../type-polyfills/non-shared-typed-arrays'; +import { subscribeToEvents } from '../../utils/subscribeToEvents'; import { IV_LENGTH, KEY_PROVIDER_DEFAULTS } from '../constants'; -import { CryptorEvent } from '../events'; +import { CryptorErrorReason } from '../errors'; +import { type CryptorCallbacks, CryptorEvent } from '../events'; import type { KeyProviderOptions } from '../types'; import { createKeyMaterialFromString } from '../utils'; import { @@ -155,36 +157,41 @@ describe('FrameCryptor', () => { }); it('drops the frame and emits an error while the local state is unknown', async () => { + // Create an encoder for the local participant const { cryptor, input, output } = prepareParticipantTestEncoder(participantIdentity, {}); + const cryptorEvents = subscribeToEvents(cryptor, [CryptorEvent.Error]); + + // The app did not say yet whether the local participant encrypts setLocalEncryptionEnabled(undefined); - const errors: Error[] = []; - cryptor.on(CryptorEvent.Error, (e) => errors.push(e)); - input.write(mockRTCEncodedVideoFrame(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]))); - await vitest.waitFor(() => expect(errors).toHaveLength(1)); + // Send a frame + input.write(mockRTCEncodedVideoFrame(new Uint8Array(16))); + + // The cryptor reports an error + const error = await cryptorEvents.waitFor(CryptorEvent.Error); + expect(error.reason).toStrictEqual(CryptorErrorReason.InternalError); - expect(output.chunks).toEqual([]); + // The frame was not sent + expect(output.chunks).toStrictEqual([]); }); - it('encrypts independent of the participant state', async () => { + it('encrypts after the participant was unset', async () => { + // Create an encoder for the local participant, with a key const { cryptor, keys, input, output } = prepareParticipantTestEncoder( participantIdentity, {}, ); await keys.setKey(await createKeyMaterialFromString('key1'), 1); - const plainLength = 16; - - encryptionEnabledMap.clear(); - input.write(mockRTCEncodedVideoFrame(new Uint8Array(plainLength))); - await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); + // Unset the participant of the cryptor cryptor.unsetParticipant(); - input.write(mockRTCEncodedVideoFrame(new Uint8Array(plainLength))); - await vitest.waitFor(() => expect(output.chunks).toHaveLength(2)); - for (const frame of output.chunks) { - expect(frame.data.byteLength).toBeGreaterThan(plainLength); - } + // Send a frame of 16 bytes + input.write(mockRTCEncodedVideoFrame(new Uint8Array(16))); + await vitest.waitFor(() => expect(output.chunks).toHaveLength(1)); + + // The sent frame is longer, because encryption appends the IV and the trailer + expect(output.chunks[0].data.byteLength).toBeGreaterThan(16); }); it('passthrough if participant encryption disabled', async () => { diff --git a/src/e2ee/worker/e2ee.worker.test.ts b/src/e2ee/worker/e2ee.worker.test.ts index b5a092be84..f2ddbbb078 100644 --- a/src/e2ee/worker/e2ee.worker.test.ts +++ b/src/e2ee/worker/e2ee.worker.test.ts @@ -1,24 +1,17 @@ -import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeAll, describe, expect, it } from 'vitest'; import { KEY_PROVIDER_DEFAULTS } from '../constants'; import type { E2EEWorkerMessage } from '../types'; import { createKeyMaterialFromString } from '../utils'; import { setLocalEncryptionEnabled } from './FrameCryptor'; -function mockFrame(data: Uint8Array): RTCEncodedVideoFrame { - return { - data: data.buffer, - timestamp: 1, - type: 'key', - getMetadata: () => ({}), - } as RTCEncodedVideoFrame; -} - describe('e2ee worker', () => { + // Sends a message to the worker, like `worker.postMessage` on the main thread const post = (msg: E2EEWorkerMessage) => (globalThis.onmessage as (ev: { data: E2EEWorkerMessage }) => void)({ data: msg }); beforeAll(async () => { - vi.stubGlobal('postMessage', vi.fn()); + // The test runs outside of a worker scope: give the worker a place to post its replies + globalThis.postMessage = () => {}; await import('./e2ee.worker'); }); @@ -27,14 +20,7 @@ describe('e2ee worker', () => { }); it('keeps sender and receiver cryptors with the same track id apart', async () => { - const sent: RTCEncodedVideoFrame[] = []; - let send: (frame: RTCEncodedVideoFrame) => void = () => {}; - const streams = () => ({ - readableStream: new ReadableStream(), - writableStream: new WritableStream(), - hasPacketTrailer: false, - }); - + // Set up the worker with encryption enabled and a key for the local participant post({ kind: 'init', data: { keyProviderOptions: { ...KEY_PROVIDER_DEFAULTS, sharedKey: false }, loglevel: 4 }, @@ -50,38 +36,56 @@ describe('e2ee worker', () => { updateCurrentKeyIndex: true, }, }); + + // Set up a sender for the local track "mic" + let senderInput!: ReadableStreamDefaultController; + const sentFrames: RTCEncodedVideoFrame[] = []; post({ kind: 'encode', data: { - ...streams(), participantIdentity: 'me', trackId: 'mic', + hasPacketTrailer: false, readableStream: new ReadableStream({ - start: (c) => { - send = (f) => c.enqueue(f); + start: (controller) => { + senderInput = controller; }, }), writableStream: new WritableStream({ - write: (f) => { - sent.push(f); + write: (frame) => { + sentFrames.push(frame); }, }), }, }); - post({ kind: 'enable', data: { enabled: false, participantIdentity: 'me' } }); + + // Set up a receiver for a remote track that is also called "mic", then remove it post({ kind: 'decode', - data: { ...streams(), participantIdentity: 'remote', trackId: 'mic' }, + data: { + participantIdentity: 'remote', + trackId: 'mic', + hasPacketTrailer: false, + readableStream: new ReadableStream(), + writableStream: new WritableStream(), + }, }); post({ kind: 'removeTransform', data: { participantIdentity: 'remote', trackId: 'mic' } }); - await vi.waitFor(() => expect(send).not.toBe(undefined)); - const plainLength = 16; - // let the queued messages run before the frame arrives + // The worker handles its messages one after the other: wait until it is through + await new Promise((resolve) => setTimeout(resolve, 20)); + + // Send a frame of 16 bytes on the local track + senderInput.enqueue({ + data: new Uint8Array(16).buffer, + timestamp: 1, + type: 'key', + getMetadata: () => ({}), + } as RTCEncodedVideoFrame); await new Promise((resolve) => setTimeout(resolve, 20)); - send(mockFrame(new Uint8Array(plainLength))); - await vi.waitFor(() => expect(sent).toHaveLength(1)); - expect(sent[0].data.byteLength).toBeGreaterThan(plainLength); + // The sent frame is longer, because encryption appends the IV and the trailer + expect(sentFrames).toHaveLength(1); + expect(sentFrames[0].data.byteLength).toBeGreaterThan(16); }); }); From 22187c1ef40392d4d2ac26ca8550e980558a2eeb Mon Sep 17 00:00:00 2001 From: lukasIO Date: Tue, 10 Nov 2026 16:47:22 +0100 Subject: [PATCH 5/5] fix(e2ee): emit the local encryption status only when it changes Co-Authored-By: Claude Fable 5.2 --- src/e2ee/E2eeManager.test.ts | 33 +++++++++++++++++++++++++++++++++ src/e2ee/E2eeManager.ts | 16 +++++++++------- src/e2ee/types.ts | 1 + 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/src/e2ee/E2eeManager.test.ts b/src/e2ee/E2eeManager.test.ts index 8f65340668..3d0e7c3b05 100644 --- a/src/e2ee/E2eeManager.test.ts +++ b/src/e2ee/E2eeManager.test.ts @@ -4,8 +4,10 @@ import { Room } from '../room/Room'; import { ParticipantEvent } from '../room/events'; import { Track } from '../room/track/Track'; import type { VideoCodec } from '../room/track/options'; +import { subscribeToEvents } from '../utils/subscribeToEvents'; import { E2EEManager } from './E2eeManager'; import { BaseKeyProvider } from './KeyProvider'; +import { type E2EEManagerCallbacks, EncryptionEvent } from './events'; /** * Install just enough of the DOM to let isE2EESupported() return true so @@ -272,4 +274,35 @@ describe('E2EEManager local encryption state', () => { manager.dispose(); }); + + it('emits the local status once when the worker confirms the same state twice', async () => { + // Create a manager with a worker that records its messages + const { room, worker, manager } = makeManager(); + manager.setup(room); + const managerEvents = subscribeToEvents(manager, [ + EncryptionEvent.ParticipantEncryptionStatusChanged, + ]); + const workerReplies = worker.onmessage as (ev: { data: unknown }) => void; + + // The worker confirms that local encryption is enabled + workerReplies({ + data: { kind: 'enable', data: { enabled: true, participantIdentity: '', local: true } }, + }); + + // The manager reports the new status + const enabled = await managerEvents.waitFor(EncryptionEvent.ParticipantEncryptionStatusChanged); + expect(enabled).toStrictEqual(true); + + // The worker confirms the same state again, as it does after the room connects + workerReplies({ + data: { kind: 'enable', data: { enabled: true, participantIdentity: 'me', local: true } }, + }); + + // The manager does not report the status a second time + expect( + managerEvents.areThereBufferedEvents(EncryptionEvent.ParticipantEncryptionStatusChanged), + ).toStrictEqual(false); + + manager.dispose(); + }); }); diff --git a/src/e2ee/E2eeManager.ts b/src/e2ee/E2eeManager.ts index ebdde6a7b2..72cc1b3a96 100644 --- a/src/e2ee/E2eeManager.ts +++ b/src/e2ee/E2eeManager.ts @@ -307,13 +307,15 @@ export class E2EEManager this.postKey(keyInfo, false); }); } - if (this.encryptionEnabled !== data.enabled && data.local) { - this.emit( - EncryptionEvent.ParticipantEncryptionStatusChanged, - data.enabled, - this.room!.localParticipant, - ); - this.encryptionEnabled = data.enabled; + if (data.local) { + if (this.encryptionEnabled !== data.enabled) { + this.emit( + EncryptionEvent.ParticipantEncryptionStatusChanged, + data.enabled, + this.room!.localParticipant, + ); + this.encryptionEnabled = data.enabled; + } } else if (data.participantIdentity) { const participant = this.room?.getParticipantByIdentity(data.participantIdentity); if (!participant) { diff --git a/src/e2ee/types.ts b/src/e2ee/types.ts index 5dfe49f7ca..307f9fb717 100644 --- a/src/e2ee/types.ts +++ b/src/e2ee/types.ts @@ -251,6 +251,7 @@ export type KeyInfo = { export type E2EEManagerOptions = { keyProvider: BaseKeyProvider; + /** The worker holds the encryption state of one room. Do not share it between rooms. */ worker: Worker; };