A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(livekit-client): bound data stream and rpc payloads (#3882)
Hampus2840905ce3f7
diff --git a/fluxer_app/pkgs/livekit-client/src/e2ee/worker/e2ee.worker.ts b/fluxer_app/pkgs/livekit-client/src/e2ee/worker/e2ee.worker.tsindex 50914ea07..4ba39383d 100644--- a/fluxer_app/pkgs/livekit-client/src/e2ee/worker/e2ee.worker.ts+++ b/fluxer_app/pkgs/livekit-client/src/e2ee/worker/e2ee.worker.ts@@ -26,6 +26,7 @@ import {encryptionEnabledMap, FrameCryptor} from './FrameCryptor.ts';import {ParticipantKeyHandler} from './ParticipantKeyHandler.ts';const participantCryptors: Array<FrameCryptor> = [];+const scriptTransformCryptors = new WeakSet<FrameCryptor>();const participantKeys: Map<string, ParticipantKeyHandler> = new Map();let sharedKeyHandler: ParticipantKeyHandler | undefined;const messageQueue = new AsyncQueue();@@ -306,6 +307,9 @@ function unsetCryptorParticipant(trackId: string, participantIdentity: string) {workerLogger.warn('Could not unset participant on cryptor', {trackId, participantIdentity});} else {cryptor.unsetParticipant();+ if (scriptTransformCryptors.has(cryptor) || !cryptor.hasActiveTransform()) {+ participantCryptors.splice(participantCryptors.indexOf(cryptor), 1);+ }}}@@ -359,6 +363,7 @@ if (self.RTCTransformEvent) {const {kind, participantIdentity, trackId, codec, hasPacketTrailer} = options;messageQueue.run(async () => {const cryptor = getTrackCryptor(participantIdentity, trackId);+ scriptTransformCryptors.add(cryptor);cryptor.setHasFrameMetadata(hasPacketTrailer);workerLogger.debug('onrtctransform setup', {participantIdentity, trackId, codec});cryptor.setupTransform(diff --git a/fluxer_app/pkgs/livekit-client/src/room/RTCEngine.ts b/fluxer_app/pkgs/livekit-client/src/room/RTCEngine.tsindex 9ba7a1d29..8263a7111 100644--- a/fluxer_app/pkgs/livekit-client/src/room/RTCEngine.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/RTCEngine.ts@@ -1360,8 +1360,9 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmitthis.createDataChannels();}- if (res?.lastMessageSeq) {- this.resendReliableMessagesForResume(res.lastMessageSeq).catch((error) => {+ const lastMessageSeq = res?.lastMessageSeq ?? 0;+ if (lastMessageSeq > 0 || this.reliableChannel.hasUnsent()) {+ this.resendReliableMessagesForResume(lastMessageSeq).catch((error) => {this.log.warn('failed to resend reliable messages after resume', {...this.logContext,error,diff --git a/fluxer_app/pkgs/livekit-client/src/room/data-channel/ReliableDataChannel.ts b/fluxer_app/pkgs/livekit-client/src/room/data-channel/ReliableDataChannel.tsindex ad1352881..31ac1585c 100644--- a/fluxer_app/pkgs/livekit-client/src/room/data-channel/ReliableDataChannel.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/data-channel/ReliableDataChannel.ts@@ -58,6 +58,10 @@ export class ReliableDataChannel extends FlowControlledDataChannel {this.refreshBufferStatus();}+ hasUnsent(): boolean {+ return this.messageBuffer.getUnsent().length > 0;+ }+async replay(lastMessageSeq: number) {const dc = this.getChannel();if (!dc) {@@ -66,7 +70,9 @@ export class ReliableDataChannel extends FlowControlledDataChannel {this.messageBuffer.popToSequence(lastMessageSeq);const unlock = await this.lockHeadroom();try {- this.messageBuffer.markAllUnsent();+ if (lastMessageSeq > 0) {+ this.messageBuffer.markAllUnsent();+ }for (let batch = this.messageBuffer.getUnsent(); batch.length > 0; batch = this.messageBuffer.getUnsent()) {for (const item of batch) {await this.waitForHeadroomWithoutLock();diff --git a/fluxer_app/pkgs/livekit-client/src/room/data-stream/constants.ts b/fluxer_app/pkgs/livekit-client/src/room/data-stream/constants.tsindex 748abd2b1..6cd86cac7 100644--- a/fluxer_app/pkgs/livekit-client/src/room/data-stream/constants.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/data-stream/constants.ts@@ -4,3 +4,5 @@export const STREAM_CHUNK_SIZE_BYTES = 15_000;export const DEFAULT_MAX_PAYLOAD_BYTE_LENGTH = 5_000_000_000;++export const MAX_OPEN_STREAMS_PER_PARTICIPANT = 500;diff --git a/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/IncomingDataStreamManager.ts b/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/IncomingDataStreamManager.tsindex 5779987ef..8414462c9 100644--- a/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/IncomingDataStreamManager.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/IncomingDataStreamManager.ts@@ -15,7 +15,7 @@ import {DataStreamError, DataStreamErrorReason} from '../../errors.ts';import type {ByteStreamInfo, StreamController, TextStreamInfo} from '../../types.ts';import {bigIntToNumber, isCompressionStreamSupported, numberToBigInt} from '../../utils.ts';import {deflateRawDecompress, inflateRawTransform} from '../compression.ts';-import {DEFAULT_MAX_PAYLOAD_BYTE_LENGTH} from '../constants.ts';+import {DEFAULT_MAX_PAYLOAD_BYTE_LENGTH, MAX_OPEN_STREAMS_PER_PARTICIPANT} from '../constants.ts';import {type ByteStreamHandler, ByteStreamReader, type TextStreamHandler, TextStreamReader} from './StreamReader.ts';export default class IncomingDataStreamManager {@@ -124,14 +124,35 @@ export default class IncomingDataStreamManager {case 'streamHeader':return this.handleStreamHeader(packet.value.value, packet.participantIdentity, encryptionType);case 'streamChunk':- return this.handleStreamChunk(packet.value.value, encryptionType);+ return this.handleStreamChunk(packet.value.value, packet.participantIdentity, encryptionType);case 'streamTrailer':- return this.handleStreamTrailer(packet.value.value, encryptionType);+ return this.handleStreamTrailer(packet.value.value, packet.participantIdentity, encryptionType);default:throw new Error(`DataPacket of value "${packet.value.case}" is not data stream related!`);}}+ private hasReachedOpenStreamLimit(participantIdentity: string, streamId: string) {+ let openStreams = 0;+ for (const controller of this.byteStreamControllers.values()) {+ if (controller.sendingParticipantIdentity === participantIdentity) {+ openStreams += 1;+ }+ }+ for (const controller of this.textStreamControllers.values()) {+ if (controller.sendingParticipantIdentity === participantIdentity) {+ openStreams += 1;+ }+ }+ if (openStreams < MAX_OPEN_STREAMS_PER_PARTICIPANT) {+ return false;+ }+ this.log.warn(+ `Data stream ${streamId} from ${participantIdentity} dropped, ${MAX_OPEN_STREAMS_PER_PARTICIPANT} streams from this participant are already open`,+ );+ return true;+ }+private handleStreamHeader(streamHeader: DataStream_Header,participantIdentity: string,@@ -195,6 +216,10 @@ export default class IncomingDataStreamManager {return;}+ if (this.hasReachedOpenStreamLimit(participantIdentity, streamHeader.streamId)) {+ return;+ }+const stream = new ReadableStream<DataStream_Chunk>({start: (controller) => {streamController = controller;@@ -213,6 +238,11 @@ export default class IncomingDataStreamManager {sendingParticipantIdentity: participantIdentity,});},+ cancel: () => {+ if (this.byteStreamControllers.get(streamHeader.streamId)?.controller === streamController) {+ this.byteStreamControllers.delete(streamHeader.streamId);+ }+ },});streamHandlerCallback(new ByteStreamReader(@@ -283,6 +313,10 @@ export default class IncomingDataStreamManager {return;}+ if (this.hasReachedOpenStreamLimit(participantIdentity, streamHeader.streamId)) {+ return;+ }+const stream = new ReadableStream<DataStream_Chunk>({start: (controller) => {streamController = controller;@@ -301,6 +335,11 @@ export default class IncomingDataStreamManager {sendingParticipantIdentity: participantIdentity,});},+ cancel: () => {+ if (this.textStreamControllers.get(streamHeader.streamId)?.controller === streamController) {+ this.textStreamControllers.delete(streamHeader.streamId);+ }+ },});streamHandlerCallback(new TextStreamReader(@@ -317,9 +356,9 @@ export default class IncomingDataStreamManager {}}- private handleStreamChunk(chunk: DataStream_Chunk, encryptionType: Encryption_Type) {+ private handleStreamChunk(chunk: DataStream_Chunk, participantIdentity: string, encryptionType: Encryption_Type) {const fileBuffer = this.byteStreamControllers.get(chunk.streamId);- if (fileBuffer) {+ if (fileBuffer && fileBuffer.sendingParticipantIdentity === participantIdentity) {if (fileBuffer.info.encryptionType !== encryptionType) {fileBuffer.controller.error(new DataStreamError(@@ -333,7 +372,7 @@ export default class IncomingDataStreamManager {}}const textBuffer = this.textStreamControllers.get(chunk.streamId);- if (textBuffer) {+ if (textBuffer && textBuffer.sendingParticipantIdentity === participantIdentity) {if (textBuffer.info.encryptionType !== encryptionType) {textBuffer.controller.error(new DataStreamError(@@ -348,9 +387,13 @@ export default class IncomingDataStreamManager {}}- private handleStreamTrailer(trailer: DataStream_Trailer, encryptionType: Encryption_Type) {+ private handleStreamTrailer(+ trailer: DataStream_Trailer,+ participantIdentity: string,+ encryptionType: Encryption_Type,+ ) {const textBuffer = this.textStreamControllers.get(trailer.streamId);- if (textBuffer) {+ if (textBuffer && textBuffer.sendingParticipantIdentity === participantIdentity) {if (textBuffer.info.encryptionType !== encryptionType) {textBuffer.controller.error(new DataStreamError(@@ -375,7 +418,7 @@ export default class IncomingDataStreamManager {}const fileBuffer = this.byteStreamControllers.get(trailer.streamId);- if (fileBuffer) {+ if (fileBuffer && fileBuffer.sendingParticipantIdentity === participantIdentity) {if (fileBuffer.info.encryptionType !== encryptionType) {fileBuffer.controller.error(new DataStreamError(diff --git a/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/StreamReader.ts b/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/StreamReader.tsindex dac1fc224..8f22067c1 100644--- a/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/StreamReader.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/data-stream/incoming/StreamReader.ts@@ -57,6 +57,10 @@ abstract class BaseStreamReader<T extends BaseStreamInfo> {onProgress?: (progress: number | undefined) => void;+ cancel(reason?: unknown): Promise<void> {+ return this.reader.cancel(reason).catch(() => {});+ }+abstract readAll(opts?: BaseStreamReaderReadAllOpts): Promise<string | Array<Uint8Array>>;}diff --git a/fluxer_app/pkgs/livekit-client/src/room/data-track/depacketizer.ts b/fluxer_app/pkgs/livekit-client/src/room/data-track/depacketizer.tsindex 8d6dd3104..dba161e20 100644--- a/fluxer_app/pkgs/livekit-client/src/room/data-track/depacketizer.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/data-track/depacketizer.ts@@ -222,30 +222,16 @@ export default class DataTrackDepacketizer {): Throws<DataTrackFrameInternal, DataTrackDepacketizerDropError<DataTrackDepacketizerDropReason.Incomplete>> {const received = partial.payloads.size;+ const chain: Array<NonSharedUint8Array> = [];let payloadLengthBytes = 0;- for (const p of partial.payloads.values()) {- payloadLengthBytes += p.length;- }- const payload = new Uint8Array(payloadLengthBytes);-const sequencePointer = partial.startSequence.clone();- let payloadOffsetPointerBytes = 0;while (true) {const partialPayload = partial.payloads.get(sequencePointer.value);if (!partialPayload) {break;}- partial.payloads.delete(sequencePointer.value);-- const payloadRemainingBytes = payload.length - payloadOffsetPointerBytes;- if (partialPayload.length > payloadRemainingBytes) {- throw new Error(- `Depacketizer.finalize: Expected at least ${partialPayload.length} more bytes left in the payload buffer, only got ${payloadRemainingBytes} bytes.`,- );- }-- payload.set(partialPayload, payloadOffsetPointerBytes);- payloadOffsetPointerBytes += partialPayload.length;+ chain.push(partialPayload);+ payloadLengthBytes += partialPayload.length;if (sequencePointer.value !== endSequence) {sequencePointer.increment();@@ -253,6 +239,12 @@ export default class DataTrackDepacketizer {}this.partials.delete(partialFrameNumber);+ const payload = new Uint8Array(payloadLengthBytes);+ let payloadOffsetPointerBytes = 0;+ for (const chainPayload of chain) {+ payload.set(chainPayload, payloadOffsetPointerBytes);+ payloadOffsetPointerBytes += chainPayload.length;+ }return {payload, extensions: partial.extensions};}diff --git a/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/OutgoingDataTrackManager.ts b/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/OutgoingDataTrackManager.tsindex 476a70fae..ff7bbcbd0 100644--- a/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/OutgoingDataTrackManager.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/OutgoingDataTrackManager.ts@@ -263,8 +263,13 @@ export default class OutgoingDataTrackManager extends (EventEmitter as new () =>if (result.type === 'ok') {const info = result.data;log.debug(`SFU accepted publish request for handle ${handle}`, {sid: info.sid});- const e2eeManager = info.usesE2ee ? this.e2eeManager : null;- this.descriptors.set(info.pubHandle, Descriptor.active(info, e2eeManager));+ if (this.e2eeManager && !info.usesE2ee) {+ log.warn(`SFU accepted publish request for handle ${handle} without encryption`, {sid: info.sid});+ this.emit('sfuUnpublishRequest', {handle: info.pubHandle});+ descriptor.completionFuture.reject?.(DataTrackPublishError.encryptionMismatch());+ return;+ }+ this.descriptors.set(info.pubHandle, Descriptor.active(info, this.e2eeManager));descriptor.completionFuture.resolve?.();} else {diff --git a/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/errors.ts b/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/errors.tsindex 4a66fbbab..c6ddf880f 100644--- a/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/errors.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/data-track/outgoing/errors.ts@@ -20,6 +20,8 @@ export enum DataTrackPublishErrorReason {InvalidName = 6,Unknown = 7,++ EncryptionMismatch = 8,}export class DataTrackPublishError<@@ -76,6 +78,13 @@ export class DataTrackPublishError<);}+ static encryptionMismatch() {+ return new DataTrackPublishError(+ 'Server accepted the data track without the requested encryption',+ DataTrackPublishErrorReason.EncryptionMismatch,+ );+ }+static disconnected() {return new DataTrackPublishError('Room disconnected', DataTrackPublishErrorReason.Disconnected);}diff --git a/fluxer_app/pkgs/livekit-client/src/room/rpc/client/RpcClientManager.ts b/fluxer_app/pkgs/livekit-client/src/room/rpc/client/RpcClientManager.tsindex 6465add0c..35c00486c 100644--- a/fluxer_app/pkgs/livekit-client/src/room/rpc/client/RpcClientManager.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/rpc/client/RpcClientManager.ts@@ -170,14 +170,21 @@ export default class RpcClientManager extends (EventEmitter as new () => TypedEmconst associatedRequestId = attributes[RpcRequestAttrs.RPC_REQUEST_ID];if (!associatedRequestId) {this.log.warn(`RPC data stream malformed: ${RpcRequestAttrs.RPC_REQUEST_ID} not set.`);+ await reader.cancel();return;}const pending = this.pendingResponses.get(associatedRequestId);- if (pending && pending.participantIdentity !== senderIdentity) {+ if (!pending) {+ this.log.error('Response received for unexpected RPC request', associatedRequestId);+ await reader.cancel();+ return;+ }+ if (pending.participantIdentity !== senderIdentity) {this.log.warn(`RPC response stream for ${associatedRequestId} arrived from unexpected sender ${senderIdentity}, expected ${pending.participantIdentity}. Ignoring.`,);+ await reader.cancel();return;}diff --git a/fluxer_app/pkgs/livekit-client/src/room/rpc/server/RpcServerManager.ts b/fluxer_app/pkgs/livekit-client/src/room/rpc/server/RpcServerManager.tsindex 368dad6ef..c202c78d2 100644--- a/fluxer_app/pkgs/livekit-client/src/room/rpc/server/RpcServerManager.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/rpc/server/RpcServerManager.ts@@ -117,6 +117,7 @@ export default class RpcServerManager extends (EventEmitter as new () => TypedEmnull,RpcError.builtIn('APPLICATION_ERROR', 'RPC data stream malformed'),);+ await reader.cancel();return;}@@ -124,6 +125,15 @@ export default class RpcServerManager extends (EventEmitter as new () => TypedEmif (version !== RPC_VERSION_V2) {this.publishRpcResponsePacket(callerIdentity, requestId, null, RpcError.builtIn('UNSUPPORTED_VERSION'));+ await reader.cancel();+ return;+ }++ const handler = this.rpcHandlers.get(method);++ if (!handler) {+ this.publishRpcResponsePacket(callerIdentity, requestId, null, RpcError.builtIn('UNSUPPORTED_METHOD'));+ await reader.cancel();return;}@@ -141,13 +151,6 @@ export default class RpcServerManager extends (EventEmitter as new () => TypedEmreturn;}- const handler = this.rpcHandlers.get(method);-- if (!handler) {- this.publishRpcResponsePacket(callerIdentity, requestId, null, RpcError.builtIn('UNSUPPORTED_METHOD'));- return;- }-let response: Awaited<ReturnType<typeof handler>>;try {response = await handler({diff --git a/fluxer_app/pkgs/livekit-client/src/room/track/LocalVideoTrack.ts b/fluxer_app/pkgs/livekit-client/src/room/track/LocalVideoTrack.tsindex 1e6d841cf..45e664ad6 100644--- a/fluxer_app/pkgs/livekit-client/src/room/track/LocalVideoTrack.ts+++ b/fluxer_app/pkgs/livekit-client/src/room/track/LocalVideoTrack.ts@@ -151,7 +151,7 @@ export default class LocalVideoTrack extends LocalTrack<Track.Kind.Video> {override async resumeUpstream() {await super.resumeUpstream();for await (const sc of this.simulcastCodecs.values()) {- await sc.sender?.replaceTrack(sc.mediaStreamTrack);+ await sc.sender?.replaceTrack(this.processor?.processedTrack ?? sc.mediaStreamTrack);}}