Skip to content
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chilled-oranges-try.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-client": patch
---

Add preliminary support for data message decryption
9 changes: 5 additions & 4 deletions examples/demo/demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const state = {
decoder: new TextDecoder(),
defaultDevices: new Map<MediaDeviceKind, string>([['audioinput', 'default']]),
bitrateInterval: undefined as any,
e2eeKeyProvider: new ExternalE2EEKeyProvider(),
e2eeKeyProvider: new ExternalE2EEKeyProvider({ ratchetWindowSize: 100 }),
chatMessages: new Map<string, { text: string; participant?: Participant }>(),
};
let currentRoom: Room | undefined;
Expand Down Expand Up @@ -273,6 +273,7 @@ const appActions = {
try {
for await (const chunk of reader.withAbortSignal(streamReaderAbortController.signal)) {
message += chunk;
console.log('received message', message, participant);
handleChatMessage(
{
id: info.id,
Expand Down Expand Up @@ -434,7 +435,7 @@ const appActions = {
},

toggleE2EE: async () => {
if (!currentRoom || !currentRoom.options.e2ee) {
if (!currentRoom || !currentRoom.hasE2EESetup) {
return;
}
// read and set current key from input
Expand Down Expand Up @@ -488,7 +489,7 @@ const appActions = {
},

ratchetE2EEKey: async () => {
if (!currentRoom || !currentRoom.options.e2ee) {
if (!currentRoom || !currentRoom.hasE2EESetup) {
return;
}
await state.e2eeKeyProvider.ratchetKey();
Expand Down Expand Up @@ -1043,7 +1044,7 @@ function setButtonsForState(connected: boolean) {
'flip-video-button',
'send-button',
];
if (currentRoom && currentRoom.options.e2ee) {
if (currentRoom && currentRoom.hasE2EESetup) {
connectedSet.push('toggle-e2ee-button', 'e2ee-ratchet-button');
}
const disconnectedSet = ['connect-button'];
Expand Down
8 changes: 4 additions & 4 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

96 changes: 94 additions & 2 deletions src/e2ee/E2eeManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,19 @@ import type RemoteTrack from '../room/track/RemoteTrack';
import type { Track } from '../room/track/Track';
import type { VideoCodec } from '../room/track/options';
import { mimeTypeToVideoCodecString } from '../room/track/utils';
import { isLocalTrack } from '../room/utils';
import { Future, isLocalTrack } from '../room/utils';
import type { BaseKeyProvider } from './KeyProvider';
import { E2EE_FLAG } from './constants';
import { type E2EEManagerCallbacks, EncryptionEvent, KeyProviderEvent } from './events';
import type {
DecryptDataRequestMessage,
DecryptDataResponseMessage,
E2EEManagerOptions,
E2EEWorkerMessage,
EnableMessage,
EncodeMessage,
EncryptDataRequestMessage,
EncryptDataResponseMessage,
InitMessage,
KeyInfo,
RTPVideoMapMessage,
Expand All @@ -35,8 +39,17 @@ import { isE2EESupported, isScriptTransformSupported } from './utils';
export interface BaseE2EEManager {
setup(room: Room): void;
setupEngine(engine: RTCEngine): void;
isEnabled: boolean;
isDataChannelEncryptionEnabled: boolean;
setParticipantCryptorEnabled(enabled: boolean, participantIdentity: string): void;
setSifTrailer(trailer: Uint8Array): void;
encryptData(data: Uint8Array): Promise<EncryptDataResponseMessage['data']>;
handleEncryptedData(
payload: Uint8Array,
iv: Uint8Array,
participantIdentity: string,
keyIndex: number,
): Promise<DecryptDataResponseMessage['data'] | EncryptDataResponseMessage['data']>;
on<E extends keyof E2EEManagerCallbacks>(event: E, listener: E2EEManagerCallbacks[E]): this;
}

Expand All @@ -55,11 +68,26 @@ export class E2EEManager

private keyProvider: BaseKeyProvider;

constructor(options: E2EEManagerOptions) {
private decryptDataRequests: Map<string, Future<DecryptDataResponseMessage['data']>> = new Map();

private encryptDataRequests: Map<string, Future<EncryptDataResponseMessage['data']>> = new Map();

private dataChannelEncryptionEnabled: boolean;

constructor(options: E2EEManagerOptions, dcEncryptionEnabled: boolean) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we really need to expose dcEncryptionEnabled here, or just assign based on the type of options (old vs new)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in JS E2EEManager is an internal class, so this is not really a big concern to me.
We can of course also make it part of the E2EEManagerOptions

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, I see why I didn't do this in the first place, as the E2EEManagerOptions are actually exposed to users under an alias right now.

super();
this.keyProvider = options.keyProvider;
this.worker = options.worker;
this.encryptionEnabled = false;
this.dataChannelEncryptionEnabled = dcEncryptionEnabled;
}

get isEnabled(): boolean {
return this.encryptionEnabled;
}

get isDataChannelEncryptionEnabled(): boolean {
return this.isEnabled && this.dataChannelEncryptionEnabled;
}

/**
Expand Down Expand Up @@ -160,6 +188,19 @@ export class E2EEManager
data.keyIndex,
);
break;

case 'decryptDataResponse':
const decryptFuture = this.decryptDataRequests.get(data.uuid);
if (decryptFuture?.resolve) {
decryptFuture.resolve(data);
}
break;
case 'encryptDataResponse':
const encryptFuture = this.encryptDataRequests.get(data.uuid);
if (encryptFuture?.resolve) {
encryptFuture.resolve(data as EncryptDataResponseMessage['data']);
}
break;
default:
break;
}
Expand Down Expand Up @@ -233,6 +274,57 @@ export class E2EEManager
);
}

async encryptData(data: Uint8Array): Promise<EncryptDataResponseMessage['data']> {
if (!this.worker) {
throw Error('could not encrypt data, worker is missing');
}
const uuid = crypto.randomUUID();
const msg: EncryptDataRequestMessage = {
kind: 'encryptDataRequest',
data: {
uuid,
payload: data,
participantIdentity: this.room!.localParticipant.identity,
},
};
const future = new Future<EncryptDataResponseMessage['data']>();
future.onFinally = () => {
this.encryptDataRequests.delete(uuid);
};
this.encryptDataRequests.set(uuid, future);
this.worker.postMessage(msg);
return future!.promise!;
}

handleEncryptedData(
payload: Uint8Array,
iv: Uint8Array,
participantIdentity: string,
keyIndex: number,
) {
if (!this.worker) {
throw Error('could not handle encrypted data, worker is missing');
}
const uuid = crypto.randomUUID();
const msg: DecryptDataRequestMessage = {
kind: 'decryptDataRequest',
data: {
uuid,
payload,
iv,
participantIdentity,
keyIndex,
},
};
const future = new Future<DecryptDataResponseMessage['data']>();
future.onFinally = () => {
this.decryptDataRequests.delete(uuid);
};
this.decryptDataRequests.set(uuid, future);
this.worker.postMessage(msg);
return future.promise;
}

private postRatchetRequest(participantIdentity?: string, keyIndex?: number) {
if (!this.worker) {
throw Error('could not ratchet key, worker is missing');
Expand Down
45 changes: 44 additions & 1 deletion src/e2ee/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,44 @@ export interface InitAck extends BaseMessage {
};
}

export interface DecryptDataRequestMessage extends BaseMessage {
kind: 'decryptDataRequest';
data: {
uuid: string;
payload: Uint8Array;
iv: Uint8Array;
participantIdentity: string;
keyIndex: number;
};
}

export interface DecryptDataResponseMessage extends BaseMessage {
kind: 'decryptDataResponse';
data: {
uuid: string;
payload: Uint8Array;
};
}

export interface EncryptDataRequestMessage extends BaseMessage {
kind: 'encryptDataRequest';
data: {
uuid: string;
payload: Uint8Array;
participantIdentity: string;
};
}

export interface EncryptDataResponseMessage extends BaseMessage {
kind: 'encryptDataResponse';
data: {
uuid: string;
payload: Uint8Array;
iv: Uint8Array;
keyIndex: number;
};
}

export type E2EEWorkerMessage =
| InitMessage
| SetKeyMessage
Expand All @@ -121,7 +159,11 @@ export type E2EEWorkerMessage =
| RatchetRequestMessage
| RatchetMessage
| SifTrailerMessage
| InitAck;
| InitAck
| DecryptDataRequestMessage
| DecryptDataResponseMessage
| EncryptDataRequestMessage
| EncryptDataResponseMessage;

export type KeySet = { material: CryptoKey; encryptionKey: CryptoKey };

Expand Down Expand Up @@ -150,6 +192,7 @@ export type E2EEManagerOptions = {
keyProvider: BaseKeyProvider;
worker: Worker;
};

export type E2EEOptions =
| E2EEManagerOptions
| {
Expand Down
16 changes: 16 additions & 0 deletions src/e2ee/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { type DataPacket, EncryptedPacketPayload } from '@livekit/protocol';
import { ENCRYPTION_ALGORITHM } from './constants';

export function isE2EESupported() {
Expand Down Expand Up @@ -176,3 +177,18 @@ export function writeRbsp(data_in: Uint8Array): Uint8Array {
}
return new Uint8Array(dataOut);
}

export function asEncryptablePacket(packet: DataPacket): EncryptedPacketPayload | undefined {
if (
packet.value?.case !== 'sipDtmf' &&
packet.value?.case !== 'metrics' &&
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In theory yes, the question is how that would handled for the dashboard were you'd want to see the metrics

packet.value?.case !== 'speaker' &&
packet.value?.case !== 'transcription' &&
packet.value?.case !== 'encryptedPacket'
) {
return new EncryptedPacketPayload({
value: packet.value,
});
}
return undefined;
}
Loading
Loading