livekit-client 2.0.4 → 2.0.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (41) hide show
  1. package/dist/livekit-client.e2ee.worker.js +1 -1
  2. package/dist/livekit-client.e2ee.worker.js.map +1 -1
  3. package/dist/livekit-client.e2ee.worker.mjs +10 -8
  4. package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
  5. package/dist/livekit-client.esm.mjs +77 -52
  6. package/dist/livekit-client.esm.mjs.map +1 -1
  7. package/dist/livekit-client.umd.js +1 -1
  8. package/dist/livekit-client.umd.js.map +1 -1
  9. package/dist/src/api/SignalClient.d.ts +1 -1
  10. package/dist/src/api/SignalClient.d.ts.map +1 -1
  11. package/dist/src/e2ee/worker/FrameCryptor.d.ts +1 -0
  12. package/dist/src/e2ee/worker/FrameCryptor.d.ts.map +1 -1
  13. package/dist/src/logger.d.ts +2 -2
  14. package/dist/src/logger.d.ts.map +1 -1
  15. package/dist/src/room/RTCEngine.d.ts +3 -2
  16. package/dist/src/room/RTCEngine.d.ts.map +1 -1
  17. package/dist/src/room/Room.d.ts.map +1 -1
  18. package/dist/src/room/participant/Participant.d.ts +1 -2
  19. package/dist/src/room/participant/Participant.d.ts.map +1 -1
  20. package/dist/src/room/participant/RemoteParticipant.d.ts +4 -0
  21. package/dist/src/room/participant/RemoteParticipant.d.ts.map +1 -1
  22. package/dist/src/room/track/LocalVideoTrack.d.ts.map +1 -1
  23. package/dist/src/room/track/utils.d.ts.map +1 -1
  24. package/dist/src/room/utils.d.ts.map +1 -1
  25. package/dist/ts4.2/src/api/SignalClient.d.ts +1 -1
  26. package/dist/ts4.2/src/e2ee/worker/FrameCryptor.d.ts +1 -0
  27. package/dist/ts4.2/src/logger.d.ts +2 -2
  28. package/dist/ts4.2/src/room/RTCEngine.d.ts +3 -2
  29. package/dist/ts4.2/src/room/participant/Participant.d.ts +1 -2
  30. package/dist/ts4.2/src/room/participant/RemoteParticipant.d.ts +4 -0
  31. package/package.json +1 -1
  32. package/src/api/SignalClient.ts +9 -5
  33. package/src/e2ee/worker/FrameCryptor.ts +12 -6
  34. package/src/logger.ts +21 -18
  35. package/src/room/RTCEngine.ts +12 -8
  36. package/src/room/Room.ts +15 -2
  37. package/src/room/participant/Participant.ts +0 -2
  38. package/src/room/participant/RemoteParticipant.ts +8 -0
  39. package/src/room/track/LocalVideoTrack.ts +5 -1
  40. package/src/room/track/utils.ts +18 -11
  41. package/src/room/utils.ts +3 -0
@@ -1 +1 @@
1
- {"version":3,"file":"livekit-client.e2ee.worker.mjs","sources":["../node_modules/.pnpm/loglevel@1.8.1/node_modules/loglevel/lib/loglevel.js","../src/logger.ts","../src/e2ee/constants.ts","../src/room/errors.ts","../src/e2ee/errors.ts","../src/e2ee/events.ts","../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js","../src/e2ee/utils.ts","../src/e2ee/worker/SifGuard.ts","../src/e2ee/worker/FrameCryptor.ts","../src/e2ee/worker/ParticipantKeyHandler.ts","../src/e2ee/worker/e2ee.worker.ts"],"sourcesContent":["/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods(level, loggerName) {\n /*jshint validthis:true */\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, loggerName);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this, level, loggerName);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, level, loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, defaultLevel, factory) {\n var self = this;\n var currentLevel;\n defaultLevel = defaultLevel == null ? \"WARN\" : defaultLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var location = cookie.indexOf(\n encodeURIComponent(storageKey) + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n function clearPersistedLevel() {\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage.removeItem(storageKey);\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n } catch (ignore) {}\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n return currentLevel;\n };\n\n self.setLevel = function (level, persist) {\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n currentLevel = level;\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(level);\n }\n replaceLoggingMethods.call(self, level, name);\n if (typeof console === undefinedType && level < self.levels.SILENT) {\n return \"No console available for logging\";\n }\n } else {\n throw \"log.setLevel() called with invalid level: \" + level;\n }\n };\n\n self.setDefaultLevel = function (level) {\n defaultLevel = level;\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.resetLevel = function () {\n self.setLevel(defaultLevel, false);\n clearPersistedLevel();\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n // Initialize with the right level\n var initialLevel = getPersistedLevel();\n if (initialLevel == null) {\n initialLevel = defaultLevel;\n }\n self.setLevel(initialLevel, false);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n var defaultLogger = new Logger();\n\n var _loggersByName = {};\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name, defaultLogger.getLevel(), defaultLogger.methodFactory);\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n","import * as log from 'loglevel';\n\nexport enum LogLevel {\n trace = 0,\n debug = 1,\n info = 2,\n warn = 3,\n error = 4,\n silent = 5,\n}\n\nexport enum LoggerNames {\n Default = 'livekit',\n Room = 'livekit-room',\n Participant = 'livekit-participant',\n Track = 'livekit-track',\n Publication = 'livekit-track-publication',\n Engine = 'livekit-engine',\n Signal = 'livekit-signal',\n PCManager = 'livekit-pc-manager',\n PCTransport = 'livekit-pc-transport',\n E2EE = 'lk-e2ee',\n}\n\ntype LogLevelString = keyof typeof LogLevel;\n\nexport type StructuredLogger = {\n trace: (msg: string, context?: object) => void;\n debug: (msg: string, context?: object) => void;\n info: (msg: string, context?: object) => void;\n warn: (msg: string, context?: object) => void;\n error: (msg: string, context?: object) => void;\n setDefaultLevel: (level: log.LogLevelDesc) => void;\n setLevel: (level: log.LogLevelDesc) => void;\n getLevel: () => number;\n};\n\nlet livekitLogger = log.getLogger('livekit');\n\nlivekitLogger.setDefaultLevel(LogLevel.info);\n\nexport default livekitLogger as StructuredLogger;\n\n/**\n * @internal\n */\nexport function getLogger(name: string) {\n const logger = log.getLogger(name);\n logger.setDefaultLevel(livekitLogger.getLevel());\n return logger as StructuredLogger;\n}\n\nexport function setLogLevel(level: LogLevel | LogLevelString, loggerName?: LoggerNames) {\n if (loggerName) {\n log.getLogger(loggerName).setLevel(level);\n }\n for (const logger of Object.entries(log.getLoggers())\n .filter(([logrName]) => logrName.startsWith('livekit'))\n .map(([, logr]) => logr)) {\n logger.setLevel(level);\n }\n}\n\nexport type LogExtension = (level: LogLevel, msg: string, context?: object) => void;\n\n/**\n * use this to hook into the logging function to allow sending internal livekit logs to third party services\n * if set, the browser logs will lose their stacktrace information (see https://github.com/pimterry/loglevel#writing-plugins)\n */\nexport function setLogExtension(extension: LogExtension, logger = livekitLogger) {\n const originalFactory = logger.methodFactory;\n\n logger.methodFactory = (methodName, configLevel, loggerName) => {\n const rawMethod = originalFactory(methodName, configLevel, loggerName);\n\n const logLevel = LogLevel[methodName as LogLevelString];\n const needLog = logLevel >= configLevel && logLevel < LogLevel.silent;\n\n return (msg, context?: [msg: string, context: object]) => {\n if (context) rawMethod(msg, context);\n else rawMethod(msg);\n if (needLog) {\n extension(logLevel, msg, context);\n }\n };\n };\n logger.setLevel(logger.getLevel()); // Be sure to call setLevel method in order to apply plugin\n}\n\nexport const workerLogger = log.getLogger('lk-e2ee') as StructuredLogger;\n","import type { KeyProviderOptions } from './types';\n\nexport const ENCRYPTION_ALGORITHM = 'AES-GCM';\n\n// We use a ringbuffer of keys so we can change them and still decode packets that were\n// encrypted with an old key. We use a size of 16 which corresponds to the four bits\n// in the frame trailer.\nexport const KEYRING_SIZE = 16;\n\n// How many consecutive frames can fail decrypting before a particular key gets marked as invalid\nexport const DECRYPTION_FAILURE_TOLERANCE = 10;\n\n// We copy the first bytes of the VP8 payload unencrypted.\n// For keyframes this is 10 bytes, for non-keyframes (delta) 3. See\n// https://tools.ietf.org/html/rfc6386#section-9.1\n// This allows the bridge to continue detecting keyframes (only one byte needed in the JVB)\n// and is also a bit easier for the VP8 decoder (i.e. it generates funny garbage pictures\n// instead of being unable to decode).\n// This is a bit for show and we might want to reduce to 1 unconditionally in the final version.\n//\n// For audio (where frame.type is not set) we do not encrypt the opus TOC byte:\n// https://tools.ietf.org/html/rfc6716#section-3.1\nexport const UNENCRYPTED_BYTES = {\n key: 10,\n delta: 3,\n audio: 1, // frame.type is not set on audio, so this is set manually\n empty: 0,\n} as const;\n\n/* We use a 12 byte bit IV. This is signalled in plain together with the\n packet. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt#parameters */\nexport const IV_LENGTH = 12;\n\n// flag set to indicate that e2ee has been setup for sender/receiver;\nexport const E2EE_FLAG = 'lk_e2ee';\n\nexport const SALT = 'LKFrameEncryptionKey';\n\nexport const KEY_PROVIDER_DEFAULTS: KeyProviderOptions = {\n sharedKey: false,\n ratchetSalt: SALT,\n ratchetWindowSize: 8,\n failureTolerance: DECRYPTION_FAILURE_TOLERANCE,\n} as const;\n\nexport const MAX_SIF_COUNT = 100;\nexport const MAX_SIF_DURATION = 2000;\n","export class LivekitError extends Error {\n code: number;\n\n constructor(code: number, message?: string) {\n super(message || 'an error has occured');\n this.code = code;\n }\n}\n\nexport const enum ConnectionErrorReason {\n NotAllowed,\n ServerUnreachable,\n InternalError,\n Cancelled,\n LeaveRequest,\n}\n\nexport class ConnectionError extends LivekitError {\n status?: number;\n\n reason?: ConnectionErrorReason;\n\n constructor(message?: string, reason?: ConnectionErrorReason, status?: number) {\n super(1, message);\n this.status = status;\n this.reason = reason;\n }\n}\n\nexport class DeviceUnsupportedError extends LivekitError {\n constructor(message?: string) {\n super(21, message ?? 'device is unsupported');\n }\n}\n\nexport class TrackInvalidError extends LivekitError {\n constructor(message?: string) {\n super(20, message ?? 'track is invalid');\n }\n}\n\nexport class UnsupportedServer extends LivekitError {\n constructor(message?: string) {\n super(10, message ?? 'unsupported server');\n }\n}\n\nexport class UnexpectedConnectionState extends LivekitError {\n constructor(message?: string) {\n super(12, message ?? 'unexpected connection state');\n }\n}\n\nexport class NegotiationError extends LivekitError {\n constructor(message?: string) {\n super(13, message ?? 'unable to negotiate');\n }\n}\n\nexport class PublishDataError extends LivekitError {\n constructor(message?: string) {\n super(13, message ?? 'unable to publish data');\n }\n}\n\nexport enum MediaDeviceFailure {\n // user rejected permissions\n PermissionDenied = 'PermissionDenied',\n // device is not available\n NotFound = 'NotFound',\n // device is in use. On Windows, only a single tab may get access to a device at a time.\n DeviceInUse = 'DeviceInUse',\n Other = 'Other',\n}\n\nexport namespace MediaDeviceFailure {\n export function getFailure(error: any): MediaDeviceFailure | undefined {\n if (error && 'name' in error) {\n if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {\n return MediaDeviceFailure.NotFound;\n }\n if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {\n return MediaDeviceFailure.PermissionDenied;\n }\n if (error.name === 'NotReadableError' || error.name === 'TrackStartError') {\n return MediaDeviceFailure.DeviceInUse;\n }\n return MediaDeviceFailure.Other;\n }\n }\n}\n","import { LivekitError } from '../room/errors';\n\nexport enum CryptorErrorReason {\n InvalidKey = 0,\n MissingKey = 1,\n InternalError = 2,\n}\n\nexport class CryptorError extends LivekitError {\n reason: CryptorErrorReason;\n\n constructor(message?: string, reason: CryptorErrorReason = CryptorErrorReason.InternalError) {\n super(40, message);\n this.reason = reason;\n }\n}\n","import type Participant from '../room/participant/Participant';\nimport type { CryptorError } from './errors';\nimport type { KeyInfo } from './types';\n\nexport enum KeyProviderEvent {\n SetKey = 'setKey',\n RatchetRequest = 'ratchetRequest',\n KeyRatcheted = 'keyRatcheted',\n}\n\nexport type KeyProviderCallbacks = {\n [KeyProviderEvent.SetKey]: (keyInfo: KeyInfo) => void;\n [KeyProviderEvent.RatchetRequest]: (participantIdentity?: string, keyIndex?: number) => void;\n [KeyProviderEvent.KeyRatcheted]: (material: CryptoKey, keyIndex?: number) => void;\n};\n\nexport enum KeyHandlerEvent {\n KeyRatcheted = 'keyRatcheted',\n}\n\nexport type ParticipantKeyHandlerCallbacks = {\n [KeyHandlerEvent.KeyRatcheted]: (\n material: CryptoKey,\n participantIdentity: string,\n keyIndex?: number,\n ) => void;\n};\n\nexport enum EncryptionEvent {\n ParticipantEncryptionStatusChanged = 'participantEncryptionStatusChanged',\n EncryptionError = 'encryptionError',\n}\n\nexport type E2EEManagerCallbacks = {\n [EncryptionEvent.ParticipantEncryptionStatusChanged]: (\n enabled: boolean,\n participant: Participant,\n ) => void;\n [EncryptionEvent.EncryptionError]: (error: Error) => void;\n};\n\nexport type CryptorCallbacks = {\n [CryptorEvent.Error]: (error: CryptorError) => void;\n};\n\nexport enum CryptorEvent {\n Error = 'cryptorError',\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","import { ENCRYPTION_ALGORITHM } from './constants';\n\nexport function isE2EESupported() {\n return isInsertableStreamSupported() || isScriptTransformSupported();\n}\n\nexport function isScriptTransformSupported() {\n // @ts-ignore\n return typeof window.RTCRtpScriptTransform !== 'undefined';\n}\n\nexport function isInsertableStreamSupported() {\n return (\n typeof window.RTCRtpSender !== 'undefined' &&\n // @ts-ignore\n typeof window.RTCRtpSender.prototype.createEncodedStreams !== 'undefined'\n );\n}\n\nexport function isVideoFrame(\n frame: RTCEncodedAudioFrame | RTCEncodedVideoFrame,\n): frame is RTCEncodedVideoFrame {\n return 'type' in frame;\n}\n\nexport async function importKey(\n keyBytes: Uint8Array | ArrayBuffer,\n algorithm: string | { name: string } = { name: ENCRYPTION_ALGORITHM },\n usage: 'derive' | 'encrypt' = 'encrypt',\n) {\n // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey\n return crypto.subtle.importKey(\n 'raw',\n keyBytes,\n algorithm,\n false,\n usage === 'derive' ? ['deriveBits', 'deriveKey'] : ['encrypt', 'decrypt'],\n );\n}\n\nexport async function createKeyMaterialFromString(password: string) {\n let enc = new TextEncoder();\n\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n enc.encode(password),\n {\n name: 'PBKDF2',\n },\n false,\n ['deriveBits', 'deriveKey'],\n );\n\n return keyMaterial;\n}\n\nexport async function createKeyMaterialFromBuffer(cryptoBuffer: ArrayBuffer) {\n const keyMaterial = await crypto.subtle.importKey('raw', cryptoBuffer, 'HKDF', false, [\n 'deriveBits',\n 'deriveKey',\n ]);\n\n return keyMaterial;\n}\n\nfunction getAlgoOptions(algorithmName: string, salt: string) {\n const textEncoder = new TextEncoder();\n const encodedSalt = textEncoder.encode(salt);\n switch (algorithmName) {\n case 'HKDF':\n return {\n name: 'HKDF',\n salt: encodedSalt,\n hash: 'SHA-256',\n info: new ArrayBuffer(128),\n };\n case 'PBKDF2': {\n return {\n name: 'PBKDF2',\n salt: encodedSalt,\n hash: 'SHA-256',\n iterations: 100000,\n };\n }\n default:\n throw new Error(`algorithm ${algorithmName} is currently unsupported`);\n }\n}\n\n/**\n * Derives a set of keys from the master key.\n * See https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.1\n */\nexport async function deriveKeys(material: CryptoKey, salt: string) {\n const algorithmOptions = getAlgoOptions(material.algorithm.name, salt);\n\n // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey#HKDF\n // https://developer.mozilla.org/en-US/docs/Web/API/HkdfParams\n const encryptionKey = await crypto.subtle.deriveKey(\n algorithmOptions,\n material,\n {\n name: ENCRYPTION_ALGORITHM,\n length: 128,\n },\n false,\n ['encrypt', 'decrypt'],\n );\n\n return { material, encryptionKey };\n}\n\nexport function createE2EEKey(): Uint8Array {\n return window.crypto.getRandomValues(new Uint8Array(32));\n}\n\n/**\n * Ratchets a key. See\n * https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.5.1\n */\nexport async function ratchet(material: CryptoKey, salt: string): Promise<ArrayBuffer> {\n const algorithmOptions = getAlgoOptions(material.algorithm.name, salt);\n\n // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveBits\n return crypto.subtle.deriveBits(algorithmOptions, material, 256);\n}\n\nexport function needsRbspUnescaping(frameData: Uint8Array) {\n for (var i = 0; i < frameData.length - 3; i++) {\n if (frameData[i] == 0 && frameData[i + 1] == 0 && frameData[i + 2] == 3) return true;\n }\n return false;\n}\n\nexport function parseRbsp(stream: Uint8Array): Uint8Array {\n const dataOut: number[] = [];\n var length = stream.length;\n for (var i = 0; i < stream.length; ) {\n // Be careful about over/underflow here. byte_length_ - 3 can underflow, and\n // i + 3 can overflow, but byte_length_ - i can't, because i < byte_length_\n // above, and that expression will produce the number of bytes left in\n // the stream including the byte at i.\n if (length - i >= 3 && !stream[i] && !stream[i + 1] && stream[i + 2] == 3) {\n // Two rbsp bytes.\n dataOut.push(stream[i++]);\n dataOut.push(stream[i++]);\n // Skip the emulation byte.\n i++;\n } else {\n // Single rbsp byte.\n dataOut.push(stream[i++]);\n }\n }\n return new Uint8Array(dataOut);\n}\n\nconst kZerosInStartSequence = 2;\nconst kEmulationByte = 3;\n\nexport function writeRbsp(data_in: Uint8Array): Uint8Array {\n const dataOut: number[] = [];\n var numConsecutiveZeros = 0;\n for (var i = 0; i < data_in.length; ++i) {\n var byte = data_in[i];\n if (byte <= kEmulationByte && numConsecutiveZeros >= kZerosInStartSequence) {\n // Need to escape.\n dataOut.push(kEmulationByte);\n numConsecutiveZeros = 0;\n }\n dataOut.push(byte);\n if (byte == 0) {\n ++numConsecutiveZeros;\n } else {\n numConsecutiveZeros = 0;\n }\n }\n return new Uint8Array(dataOut);\n}\n","import { MAX_SIF_COUNT, MAX_SIF_DURATION } from '../constants';\n\nexport class SifGuard {\n private consecutiveSifCount = 0;\n\n private sifSequenceStartedAt: number | undefined;\n\n private lastSifReceivedAt: number = 0;\n\n private userFramesSinceSif: number = 0;\n\n recordSif() {\n this.consecutiveSifCount += 1;\n this.sifSequenceStartedAt ??= Date.now();\n this.lastSifReceivedAt = Date.now();\n }\n\n recordUserFrame() {\n if (this.sifSequenceStartedAt === undefined) {\n return;\n } else {\n this.userFramesSinceSif += 1;\n }\n if (\n // reset if we received more user frames than SIFs\n this.userFramesSinceSif > this.consecutiveSifCount ||\n // also reset if we got a new user frame and the latest SIF frame hasn't been updated in a while\n Date.now() - this.lastSifReceivedAt > MAX_SIF_DURATION\n ) {\n this.reset();\n }\n }\n\n isSifAllowed() {\n return (\n this.consecutiveSifCount < MAX_SIF_COUNT &&\n (this.sifSequenceStartedAt === undefined ||\n Date.now() - this.sifSequenceStartedAt < MAX_SIF_DURATION)\n );\n }\n\n reset() {\n this.userFramesSinceSif = 0;\n this.consecutiveSifCount = 0;\n this.sifSequenceStartedAt = undefined;\n }\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n// TODO code inspired by https://github.com/webrtc/samples/blob/gh-pages/src/content/insertable-streams/endtoend-encryption/js/worker.js\nimport { EventEmitter } from 'events';\nimport type TypedEventEmitter from 'typed-emitter';\nimport { workerLogger } from '../../logger';\nimport type { VideoCodec } from '../../room/track/options';\nimport { ENCRYPTION_ALGORITHM, IV_LENGTH, UNENCRYPTED_BYTES } from '../constants';\nimport { CryptorError, CryptorErrorReason } from '../errors';\nimport { CryptorCallbacks, CryptorEvent } from '../events';\nimport type { DecodeRatchetOptions, KeyProviderOptions, KeySet } from '../types';\nimport { deriveKeys, isVideoFrame, needsRbspUnescaping, parseRbsp, writeRbsp } from '../utils';\nimport type { ParticipantKeyHandler } from './ParticipantKeyHandler';\nimport { SifGuard } from './SifGuard';\n\nexport const encryptionEnabledMap: Map<string, boolean> = new Map();\n\nexport interface FrameCryptorConstructor {\n new (opts?: unknown): BaseFrameCryptor;\n}\n\nexport interface TransformerInfo {\n readable: ReadableStream;\n writable: WritableStream;\n transformer: TransformStream;\n abortController: AbortController;\n}\n\nexport class BaseFrameCryptor extends (EventEmitter as new () => TypedEventEmitter<CryptorCallbacks>) {\n protected encodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ): Promise<any> {\n throw Error('not implemented for subclass');\n }\n\n protected decodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ): Promise<any> {\n throw Error('not implemented for subclass');\n }\n}\n\n/**\n * Cryptor is responsible for en-/decrypting media frames.\n * Each Cryptor instance is responsible for en-/decrypting a single mediaStreamTrack.\n */\nexport class FrameCryptor extends BaseFrameCryptor {\n private sendCounts: Map<number, number>;\n\n private participantIdentity: string | undefined;\n\n private trackId: string | undefined;\n\n private keys: ParticipantKeyHandler;\n\n private videoCodec?: VideoCodec;\n\n private rtpMap: Map<number, VideoCodec>;\n\n private keyProviderOptions: KeyProviderOptions;\n\n /**\n * used for detecting server injected unencrypted frames\n */\n private sifTrailer: Uint8Array;\n\n private sifGuard: SifGuard;\n\n constructor(opts: {\n keys: ParticipantKeyHandler;\n participantIdentity: string;\n keyProviderOptions: KeyProviderOptions;\n sifTrailer?: Uint8Array;\n }) {\n super();\n this.sendCounts = new Map();\n this.keys = opts.keys;\n this.participantIdentity = opts.participantIdentity;\n this.rtpMap = new Map();\n this.keyProviderOptions = opts.keyProviderOptions;\n this.sifTrailer = opts.sifTrailer ?? Uint8Array.from([]);\n this.sifGuard = new SifGuard();\n }\n\n private get logContext() {\n return {\n identity: this.participantIdentity,\n trackId: this.trackId,\n fallbackCodec: this.videoCodec,\n };\n }\n\n /**\n * Assign a different participant to the cryptor.\n * useful for transceiver re-use\n * @param id\n * @param keys\n */\n setParticipant(id: string, keys: ParticipantKeyHandler) {\n this.participantIdentity = id;\n this.keys = keys;\n this.sifGuard.reset();\n }\n\n unsetParticipant() {\n workerLogger.debug('unsetting participant', this.logContext);\n this.participantIdentity = undefined;\n }\n\n isEnabled() {\n if (this.participantIdentity) {\n return encryptionEnabledMap.get(this.participantIdentity);\n } else {\n return undefined;\n }\n }\n\n getParticipantIdentity() {\n return this.participantIdentity;\n }\n\n getTrackId() {\n return this.trackId;\n }\n\n /**\n * Update the video codec used by the mediaStreamTrack\n * @param codec\n */\n setVideoCodec(codec: VideoCodec) {\n this.videoCodec = codec;\n }\n\n /**\n * rtp payload type map used for figuring out codec of payload type when encoding\n * @param map\n */\n setRtpMap(map: Map<number, VideoCodec>) {\n this.rtpMap = map;\n }\n\n setupTransform(\n operation: 'encode' | 'decode',\n readable: ReadableStream,\n writable: WritableStream,\n trackId: string,\n codec?: VideoCodec,\n ) {\n if (codec) {\n workerLogger.info('setting codec on cryptor to', { codec });\n this.videoCodec = codec;\n }\n\n workerLogger.debug('Setting up frame cryptor transform', {\n operation,\n passedTrackId: trackId,\n codec,\n ...this.logContext,\n });\n\n const transformFn = operation === 'encode' ? this.encodeFunction : this.decodeFunction;\n const transformStream = new TransformStream({\n transform: transformFn.bind(this),\n });\n\n readable\n .pipeThrough(transformStream)\n .pipeTo(writable)\n .catch((e) => {\n workerLogger.warn(e);\n this.emit(CryptorEvent.Error, e instanceof CryptorError ? e : new CryptorError(e.message));\n });\n this.trackId = trackId;\n }\n\n setSifTrailer(trailer: Uint8Array) {\n workerLogger.debug('setting SIF trailer', { ...this.logContext, trailer });\n this.sifTrailer = trailer;\n }\n\n /**\n * Function that will be injected in a stream and will encrypt the given encoded frames.\n *\n * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.\n * @param {TransformStreamDefaultController} controller - TransportStreamController.\n *\n * The VP8 payload descriptor described in\n * https://tools.ietf.org/html/rfc7741#section-4.2\n * is part of the RTP packet and not part of the frame and is not controllable by us.\n * This is fine as the SFU keeps having access to it for routing.\n *\n * The encrypted frame is formed as follows:\n * 1) Find unencrypted byte length, depending on the codec, frame type and kind.\n * 2) Form the GCM IV for the frame as described above.\n * 3) Encrypt the rest of the frame using AES-GCM.\n * 4) Allocate space for the encrypted frame.\n * 5) Copy the unencrypted bytes to the start of the encrypted frame.\n * 6) Append the ciphertext to the encrypted frame.\n * 7) Append the IV.\n * 8) Append a single byte for the key identifier.\n * 9) Enqueue the encrypted frame for sending.\n */\n protected async encodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ) {\n if (\n !this.isEnabled() ||\n // skip for encryption for empty dtx frames\n encodedFrame.data.byteLength === 0\n ) {\n return controller.enqueue(encodedFrame);\n }\n const keySet = this.keys.getKeySet();\n if (!keySet) {\n throw new TypeError(\n `key set not found for ${\n this.participantIdentity\n } at index ${this.keys.getCurrentKeyIndex()}`,\n );\n }\n const { encryptionKey } = keySet;\n const keyIndex = this.keys.getCurrentKeyIndex();\n\n if (encryptionKey) {\n const iv = this.makeIV(\n encodedFrame.getMetadata().synchronizationSource ?? -1,\n encodedFrame.timestamp,\n );\n let frameInfo = this.getUnencryptedBytes(encodedFrame);\n workerLogger.debug('frameInfo for encoded frame', { ...frameInfo, ...this.logContext });\n\n // Thіs is not encrypted and contains the VP8 payload descriptor or the Opus TOC byte.\n const frameHeader = new Uint8Array(encodedFrame.data, 0, frameInfo.unencryptedBytes);\n\n // Frame trailer contains the R|IV_LENGTH and key index\n const frameTrailer = new Uint8Array(2);\n\n frameTrailer[0] = IV_LENGTH;\n frameTrailer[1] = keyIndex;\n\n // Construct frame trailer. Similar to the frame header described in\n // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.2\n // but we put it at the end.\n //\n // ---------+-------------------------+-+---------+----\n // payload |IV...(length = IV_LENGTH)|R|IV_LENGTH|KID |\n // ---------+-------------------------+-+---------+----\n try {\n const cipherText = await crypto.subtle.encrypt(\n {\n name: ENCRYPTION_ALGORITHM,\n iv,\n additionalData: new Uint8Array(encodedFrame.data, 0, frameHeader.byteLength),\n },\n encryptionKey,\n new Uint8Array(encodedFrame.data, frameInfo.unencryptedBytes),\n );\n\n let newDataWithoutHeader = new Uint8Array(\n cipherText.byteLength + iv.byteLength + frameTrailer.byteLength,\n );\n newDataWithoutHeader.set(new Uint8Array(cipherText)); // add ciphertext.\n newDataWithoutHeader.set(new Uint8Array(iv), cipherText.byteLength); // append IV.\n newDataWithoutHeader.set(frameTrailer, cipherText.byteLength + iv.byteLength); // append frame trailer.\n\n if (frameInfo.isH264) {\n newDataWithoutHeader = writeRbsp(newDataWithoutHeader);\n }\n\n var newData = new Uint8Array(frameHeader.byteLength + newDataWithoutHeader.byteLength);\n newData.set(frameHeader);\n newData.set(newDataWithoutHeader, frameHeader.byteLength);\n\n encodedFrame.data = newData.buffer;\n\n return controller.enqueue(encodedFrame);\n } catch (e: any) {\n // TODO: surface this to the app.\n workerLogger.error(e);\n }\n } else {\n workerLogger.debug('failed to decrypt, emitting error', this.logContext);\n this.emit(\n CryptorEvent.Error,\n new CryptorError(`encryption key missing for encoding`, CryptorErrorReason.MissingKey),\n );\n }\n }\n\n /**\n * Function that will be injected in a stream and will decrypt the given encoded frames.\n *\n * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.\n * @param {TransformStreamDefaultController} controller - TransportStreamController.\n */\n protected async decodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ) {\n if (\n !this.isEnabled() ||\n // skip for decryption for empty dtx frames\n encodedFrame.data.byteLength === 0\n ) {\n workerLogger.debug('skipping empty frame', this.logContext);\n this.sifGuard.recordUserFrame();\n return controller.enqueue(encodedFrame);\n }\n\n if (isFrameServerInjected(encodedFrame.data, this.sifTrailer)) {\n workerLogger.debug('enqueue SIF', this.logContext);\n this.sifGuard.recordSif();\n\n if (this.sifGuard.isSifAllowed()) {\n encodedFrame.data = encodedFrame.data.slice(\n 0,\n encodedFrame.data.byteLength - this.sifTrailer.byteLength,\n );\n return controller.enqueue(encodedFrame);\n } else {\n workerLogger.warn('SIF limit reached, dropping frame');\n return;\n }\n } else {\n this.sifGuard.recordUserFrame();\n }\n const data = new Uint8Array(encodedFrame.data);\n const keyIndex = data[encodedFrame.data.byteLength - 1];\n\n if (this.keys.getKeySet(keyIndex) && this.keys.hasValidKey) {\n try {\n const decodedFrame = await this.decryptFrame(encodedFrame, keyIndex);\n this.keys.decryptionSuccess();\n if (decodedFrame) {\n workerLogger.debug('enqueue decrypted frame', this.logContext);\n return controller.enqueue(decodedFrame);\n }\n } catch (error) {\n if (error instanceof CryptorError && error.reason === CryptorErrorReason.InvalidKey) {\n if (this.keys.hasValidKey) {\n this.emit(CryptorEvent.Error, error);\n this.keys.decryptionFailure();\n }\n } else {\n workerLogger.warn('decoding frame failed', { error });\n }\n }\n } else if (!this.keys.getKeySet(keyIndex) && this.keys.hasValidKey) {\n // emit an error in case the key index is out of bounds but the key handler thinks we still have a valid key\n workerLogger.warn(`skipping decryption due to missing key at index ${keyIndex}`);\n this.emit(\n CryptorEvent.Error,\n new CryptorError(\n `missing key at index ${keyIndex} for participant ${this.participantIdentity}`,\n CryptorErrorReason.MissingKey,\n ),\n );\n }\n }\n\n /**\n * Function that will decrypt the given encoded frame. If the decryption fails, it will\n * ratchet the key for up to RATCHET_WINDOW_SIZE times.\n */\n private async decryptFrame(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n keyIndex: number,\n initialMaterial: KeySet | undefined = undefined,\n ratchetOpts: DecodeRatchetOptions = { ratchetCount: 0 },\n ): Promise<RTCEncodedVideoFrame | RTCEncodedAudioFrame | undefined> {\n const keySet = this.keys.getKeySet(keyIndex);\n if (!ratchetOpts.encryptionKey && !keySet) {\n throw new TypeError(`no encryption key found for decryption of ${this.participantIdentity}`);\n }\n let frameInfo = this.getUnencryptedBytes(encodedFrame);\n workerLogger.debug('frameInfo for decoded frame', { ...frameInfo, ...this.logContext });\n\n // Construct frame trailer. Similar to the frame header described in\n // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.2\n // but we put it at the end.\n //\n // ---------+-------------------------+-+---------+----\n // payload |IV...(length = IV_LENGTH)|R|IV_LENGTH|KID |\n // ---------+-------------------------+-+---------+----\n\n try {\n const frameHeader = new Uint8Array(encodedFrame.data, 0, frameInfo.unencryptedBytes);\n var encryptedData = new Uint8Array(\n encodedFrame.data,\n frameHeader.length,\n encodedFrame.data.byteLength - frameHeader.length,\n );\n if (frameInfo.isH264 && needsRbspUnescaping(encryptedData)) {\n encryptedData = parseRbsp(encryptedData);\n const newUint8 = new Uint8Array(frameHeader.byteLength + encryptedData.byteLength);\n newUint8.set(frameHeader);\n newUint8.set(encryptedData, frameHeader.byteLength);\n encodedFrame.data = newUint8.buffer;\n }\n\n const frameTrailer = new Uint8Array(encodedFrame.data, encodedFrame.data.byteLength - 2, 2);\n\n const ivLength = frameTrailer[0];\n const iv = new Uint8Array(\n encodedFrame.data,\n encodedFrame.data.byteLength - ivLength - frameTrailer.byteLength,\n ivLength,\n );\n\n const cipherTextStart = frameHeader.byteLength;\n const cipherTextLength =\n encodedFrame.data.byteLength -\n (frameHeader.byteLength + ivLength + frameTrailer.byteLength);\n\n const plainText = await crypto.subtle.decrypt(\n {\n name: ENCRYPTION_ALGORITHM,\n iv,\n additionalData: new Uint8Array(encodedFrame.data, 0, frameHeader.byteLength),\n },\n ratchetOpts.encryptionKey ?? keySet!.encryptionKey,\n new Uint8Array(encodedFrame.data, cipherTextStart, cipherTextLength),\n );\n\n const newData = new ArrayBuffer(frameHeader.byteLength + plainText.byteLength);\n const newUint8 = new Uint8Array(newData);\n\n newUint8.set(new Uint8Array(encodedFrame.data, 0, frameHeader.byteLength));\n newUint8.set(new Uint8Array(plainText), frameHeader.byteLength);\n\n encodedFrame.data = newData;\n\n return encodedFrame;\n } catch (error: any) {\n if (this.keyProviderOptions.ratchetWindowSize > 0) {\n if (ratchetOpts.ratchetCount < this.keyProviderOptions.ratchetWindowSize) {\n workerLogger.debug(\n `ratcheting key attempt ${ratchetOpts.ratchetCount} of ${\n this.keyProviderOptions.ratchetWindowSize\n }, for kind ${encodedFrame instanceof RTCEncodedAudioFrame ? 'audio' : 'video'}`,\n );\n\n let ratchetedKeySet: KeySet | undefined;\n if ((initialMaterial ?? keySet) === this.keys.getKeySet(keyIndex)) {\n // only ratchet if the currently set key is still the same as the one used to decrypt this frame\n // if not, it might be that a different frame has already ratcheted and we try with that one first\n const newMaterial = await this.keys.ratchetKey(keyIndex, false);\n\n ratchetedKeySet = await deriveKeys(newMaterial, this.keyProviderOptions.ratchetSalt);\n }\n\n const frame = await this.decryptFrame(encodedFrame, keyIndex, initialMaterial || keySet, {\n ratchetCount: ratchetOpts.ratchetCount + 1,\n encryptionKey: ratchetedKeySet?.encryptionKey,\n });\n if (frame && ratchetedKeySet) {\n // before updating the keys, make sure that the keySet used for this frame is still the same as the currently set key\n // if it's not, a new key might have been set already, which we don't want to override\n if ((initialMaterial ?? keySet) === this.keys.getKeySet(keyIndex)) {\n this.keys.setKeySet(ratchetedKeySet, keyIndex, true);\n // decryption was successful, set the new key index to reflect the ratcheted key set\n this.keys.setCurrentKeyIndex(keyIndex);\n }\n }\n return frame;\n } else {\n /**\n * Because we only set a new key once decryption has been successful,\n * we can be sure that we don't need to reset the key to the initial material at this point\n * as the key has not been updated on the keyHandler instance\n */\n\n workerLogger.warn('maximum ratchet attempts exceeded');\n throw new CryptorError(\n `valid key missing for participant ${this.participantIdentity}`,\n CryptorErrorReason.InvalidKey,\n );\n }\n } else {\n throw new CryptorError(\n `Decryption failed: ${error.message}`,\n CryptorErrorReason.InvalidKey,\n );\n }\n }\n }\n\n /**\n * Construct the IV used for AES-GCM and sent (in plain) with the packet similar to\n * https://tools.ietf.org/html/rfc7714#section-8.1\n * It concatenates\n * - the 32 bit synchronization source (SSRC) given on the encoded frame,\n * - the 32 bit rtp timestamp given on the encoded frame,\n * - a send counter that is specific to the SSRC. Starts at a random number.\n * The send counter is essentially the pictureId but we currently have to implement this ourselves.\n * There is no XOR with a salt. Note that this IV leaks the SSRC to the receiver but since this is\n * randomly generated and SFUs may not rewrite this is considered acceptable.\n * The SSRC is used to allow demultiplexing multiple streams with the same key, as described in\n * https://tools.ietf.org/html/rfc3711#section-4.1.1\n * The RTP timestamp is 32 bits and advances by the codec clock rate (90khz for video, 48khz for\n * opus audio) every second. For video it rolls over roughly every 13 hours.\n * The send counter will advance at the frame rate (30fps for video, 50fps for 20ms opus audio)\n * every second. It will take a long time to roll over.\n *\n * See also https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams\n */\n private makeIV(synchronizationSource: number, timestamp: number) {\n const iv = new ArrayBuffer(IV_LENGTH);\n const ivView = new DataView(iv);\n\n // having to keep our own send count (similar to a picture id) is not ideal.\n if (!this.sendCounts.has(synchronizationSource)) {\n // Initialize with a random offset, similar to the RTP sequence number.\n this.sendCounts.set(synchronizationSource, Math.floor(Math.random() * 0xffff));\n }\n\n const sendCount = this.sendCounts.get(synchronizationSource) ?? 0;\n\n ivView.setUint32(0, synchronizationSource);\n ivView.setUint32(4, timestamp);\n ivView.setUint32(8, timestamp - (sendCount % 0xffff));\n\n this.sendCounts.set(synchronizationSource, sendCount + 1);\n\n return iv;\n }\n\n private getUnencryptedBytes(frame: RTCEncodedVideoFrame | RTCEncodedAudioFrame): {\n unencryptedBytes: number;\n isH264: boolean;\n } {\n var frameInfo = { unencryptedBytes: 0, isH264: false };\n if (isVideoFrame(frame)) {\n let detectedCodec = this.getVideoCodec(frame) ?? this.videoCodec;\n\n if (detectedCodec === 'av1' || detectedCodec === 'vp9') {\n throw new Error(`${detectedCodec} is not yet supported for end to end encryption`);\n }\n\n if (detectedCodec === 'vp8') {\n frameInfo.unencryptedBytes = UNENCRYPTED_BYTES[frame.type];\n return frameInfo;\n }\n\n const data = new Uint8Array(frame.data);\n try {\n const naluIndices = findNALUIndices(data);\n\n // if the detected codec is undefined we test whether it _looks_ like a h264 frame as a best guess\n frameInfo.isH264 =\n detectedCodec === 'h264' ||\n naluIndices.some((naluIndex) =>\n [NALUType.SLICE_IDR, NALUType.SLICE_NON_IDR].includes(parseNALUType(data[naluIndex])),\n );\n\n if (frameInfo.isH264) {\n for (const index of naluIndices) {\n let type = parseNALUType(data[index]);\n switch (type) {\n case NALUType.SLICE_IDR:\n case NALUType.SLICE_NON_IDR:\n frameInfo.unencryptedBytes = index + 2;\n return frameInfo;\n default:\n break;\n }\n }\n throw new TypeError('Could not find NALU');\n }\n } catch (e) {\n // no op, we just continue and fallback to vp8\n }\n\n frameInfo.unencryptedBytes = UNENCRYPTED_BYTES[frame.type];\n return frameInfo;\n } else {\n frameInfo.unencryptedBytes = UNENCRYPTED_BYTES.audio;\n return frameInfo;\n }\n }\n\n /**\n * inspects frame payloadtype if available and maps it to the codec specified in rtpMap\n */\n private getVideoCodec(frame: RTCEncodedVideoFrame): VideoCodec | undefined {\n if (this.rtpMap.size === 0) {\n return undefined;\n }\n // @ts-expect-error payloadType is not yet part of the typescript definition and currently not supported in Safari\n const payloadType = frame.getMetadata().payloadType;\n const codec = payloadType ? this.rtpMap.get(payloadType) : undefined;\n workerLogger.debug('reading codec from frame', { codec, ...this.logContext });\n return codec;\n }\n}\n\n/**\n * Slice the NALUs present in the supplied buffer, assuming it is already byte-aligned\n * code adapted from https://github.com/medooze/h264-frame-parser/blob/main/lib/NalUnits.ts to return indices only\n */\nexport function findNALUIndices(stream: Uint8Array): number[] {\n const result: number[] = [];\n let start = 0,\n pos = 0,\n searchLength = stream.length - 2;\n while (pos < searchLength) {\n // skip until end of current NALU\n while (\n pos < searchLength &&\n !(stream[pos] === 0 && stream[pos + 1] === 0 && stream[pos + 2] === 1)\n )\n pos++;\n if (pos >= searchLength) pos = stream.length;\n // remove trailing zeros from current NALU\n let end = pos;\n while (end > start && stream[end - 1] === 0) end--;\n // save current NALU\n if (start === 0) {\n if (end !== start) throw TypeError('byte stream contains leading data');\n } else {\n result.push(start);\n }\n // begin new NALU\n start = pos = pos + 3;\n }\n return result;\n}\n\nexport function parseNALUType(startByte: number): NALUType {\n return startByte & kNaluTypeMask;\n}\n\nconst kNaluTypeMask = 0x1f;\n\nexport enum NALUType {\n /** Coded slice of a non-IDR picture */\n SLICE_NON_IDR = 1,\n /** Coded slice data partition A */\n SLICE_PARTITION_A = 2,\n /** Coded slice data partition B */\n SLICE_PARTITION_B = 3,\n /** Coded slice data partition C */\n SLICE_PARTITION_C = 4,\n /** Coded slice of an IDR picture */\n SLICE_IDR = 5,\n /** Supplemental enhancement information */\n SEI = 6,\n /** Sequence parameter set */\n SPS = 7,\n /** Picture parameter set */\n PPS = 8,\n /** Access unit delimiter */\n AUD = 9,\n /** End of sequence */\n END_SEQ = 10,\n /** End of stream */\n END_STREAM = 11,\n /** Filler data */\n FILLER_DATA = 12,\n /** Sequence parameter set extension */\n SPS_EXT = 13,\n /** Prefix NAL unit */\n PREFIX_NALU = 14,\n /** Subset sequence parameter set */\n SUBSET_SPS = 15,\n /** Depth parameter set */\n DPS = 16,\n\n // 17, 18 reserved\n\n /** Coded slice of an auxiliary coded picture without partitioning */\n SLICE_AUX = 19,\n /** Coded slice extension */\n SLICE_EXT = 20,\n /** Coded slice extension for a depth view component or a 3D-AVC texture view component */\n SLICE_LAYER_EXT = 21,\n\n // 22, 23 reserved\n}\n\n/**\n * we use a magic frame trailer to detect whether a frame is injected\n * by the livekit server and thus to be treated as unencrypted\n * @internal\n */\nexport function isFrameServerInjected(frameData: ArrayBuffer, trailerBytes: Uint8Array): boolean {\n if (trailerBytes.byteLength === 0) {\n return false;\n }\n const frameTrailer = new Uint8Array(\n frameData.slice(frameData.byteLength - trailerBytes.byteLength),\n );\n return trailerBytes.every((value, index) => value === frameTrailer[index]);\n}\n","import { EventEmitter } from 'events';\nimport type TypedEventEmitter from 'typed-emitter';\nimport { workerLogger } from '../../logger';\nimport { KEYRING_SIZE } from '../constants';\nimport { KeyHandlerEvent, type ParticipantKeyHandlerCallbacks } from '../events';\nimport type { KeyProviderOptions, KeySet } from '../types';\nimport { deriveKeys, importKey, ratchet } from '../utils';\n\n// TODO ParticipantKeyHandlers currently don't get destroyed on participant disconnect\n// we could do this by having a separate worker message on participant disconnected.\n\n/**\n * ParticipantKeyHandler is responsible for providing a cryptor instance with the\n * en-/decryption key of a participant. It assumes that all tracks of a specific participant\n * are encrypted with the same key.\n * Additionally it exposes a method to ratchet a key which can be used by the cryptor either automatically\n * if decryption fails or can be triggered manually on both sender and receiver side.\n *\n */\nexport class ParticipantKeyHandler extends (EventEmitter as new () => TypedEventEmitter<ParticipantKeyHandlerCallbacks>) {\n private currentKeyIndex: number;\n\n private cryptoKeyRing: Array<KeySet | undefined>;\n\n private keyProviderOptions: KeyProviderOptions;\n\n private ratchetPromiseMap: Map<number, Promise<CryptoKey>>;\n\n private participantIdentity: string;\n\n private decryptionFailureCount = 0;\n\n private _hasValidKey: boolean = true;\n\n get hasValidKey() {\n return this._hasValidKey;\n }\n\n constructor(participantIdentity: string, keyProviderOptions: KeyProviderOptions) {\n super();\n this.currentKeyIndex = 0;\n this.cryptoKeyRing = new Array(KEYRING_SIZE).fill(undefined);\n this.keyProviderOptions = keyProviderOptions;\n this.ratchetPromiseMap = new Map();\n this.participantIdentity = participantIdentity;\n this.resetKeyStatus();\n }\n\n decryptionFailure() {\n if (this.keyProviderOptions.failureTolerance < 0) {\n return;\n }\n this.decryptionFailureCount += 1;\n\n if (this.decryptionFailureCount > this.keyProviderOptions.failureTolerance) {\n workerLogger.warn(`key for ${this.participantIdentity} is being marked as invalid`);\n this._hasValidKey = false;\n }\n }\n\n decryptionSuccess() {\n this.resetKeyStatus();\n }\n\n /**\n * Call this after user initiated ratchet or a new key has been set in order to make sure to mark potentially\n * invalid keys as valid again\n */\n resetKeyStatus() {\n this.decryptionFailureCount = 0;\n this._hasValidKey = true;\n }\n\n /**\n * Ratchets the current key (or the one at keyIndex if provided) and\n * returns the ratcheted material\n * if `setKey` is true (default), it will also set the ratcheted key directly on the crypto key ring\n * @param keyIndex\n * @param setKey\n */\n ratchetKey(keyIndex?: number, setKey = true): Promise<CryptoKey> {\n const currentKeyIndex = keyIndex ?? this.getCurrentKeyIndex();\n\n const existingPromise = this.ratchetPromiseMap.get(currentKeyIndex);\n if (typeof existingPromise !== 'undefined') {\n return existingPromise;\n }\n const ratchetPromise = new Promise<CryptoKey>(async (resolve, reject) => {\n try {\n const keySet = this.getKeySet(currentKeyIndex);\n if (!keySet) {\n throw new TypeError(\n `Cannot ratchet key without a valid keyset of participant ${this.participantIdentity}`,\n );\n }\n const currentMaterial = keySet.material;\n const newMaterial = await importKey(\n await ratchet(currentMaterial, this.keyProviderOptions.ratchetSalt),\n currentMaterial.algorithm.name,\n 'derive',\n );\n\n if (setKey) {\n this.setKeyFromMaterial(newMaterial, currentKeyIndex, true);\n this.emit(\n KeyHandlerEvent.KeyRatcheted,\n newMaterial,\n this.participantIdentity,\n currentKeyIndex,\n );\n }\n resolve(newMaterial);\n } catch (e) {\n reject(e);\n } finally {\n this.ratchetPromiseMap.delete(currentKeyIndex);\n }\n });\n this.ratchetPromiseMap.set(currentKeyIndex, ratchetPromise);\n return ratchetPromise;\n }\n\n /**\n * takes in a key material with `deriveBits` and `deriveKey` set as key usages\n * and derives encryption keys from the material and sets it on the key ring buffer\n * together with the material\n * also resets the valid key property and updates the currentKeyIndex\n */\n async setKey(material: CryptoKey, keyIndex = 0) {\n await this.setKeyFromMaterial(material, keyIndex);\n this.resetKeyStatus();\n }\n\n /**\n * takes in a key material with `deriveBits` and `deriveKey` set as key usages\n * and derives encryption keys from the material and sets it on the key ring buffers\n * together with the material\n * also updates the currentKeyIndex\n */\n async setKeyFromMaterial(material: CryptoKey, keyIndex: number, emitRatchetEvent = false) {\n const keySet = await deriveKeys(material, this.keyProviderOptions.ratchetSalt);\n const newIndex = keyIndex >= 0 ? keyIndex % this.cryptoKeyRing.length : this.currentKeyIndex;\n workerLogger.debug(`setting new key with index ${keyIndex}`, {\n usage: material.usages,\n algorithm: material.algorithm,\n ratchetSalt: this.keyProviderOptions.ratchetSalt,\n });\n this.setKeySet(keySet, newIndex, emitRatchetEvent);\n if (newIndex >= 0) this.currentKeyIndex = newIndex;\n }\n\n setKeySet(keySet: KeySet, keyIndex: number, emitRatchetEvent = false) {\n this.cryptoKeyRing[keyIndex % this.cryptoKeyRing.length] = keySet;\n\n if (emitRatchetEvent) {\n this.emit(KeyHandlerEvent.KeyRatcheted, keySet.material, this.participantIdentity, keyIndex);\n }\n }\n\n async setCurrentKeyIndex(index: number) {\n this.currentKeyIndex = index % this.cryptoKeyRing.length;\n this.resetKeyStatus();\n }\n\n getCurrentKeyIndex() {\n return this.currentKeyIndex;\n }\n\n /**\n * returns currently used KeySet or the one at `keyIndex` if provided\n * @param keyIndex\n * @returns\n */\n getKeySet(keyIndex?: number) {\n return this.cryptoKeyRing[keyIndex ?? this.currentKeyIndex];\n }\n}\n","import { workerLogger } from '../../logger';\nimport { KEY_PROVIDER_DEFAULTS } from '../constants';\nimport { CryptorErrorReason } from '../errors';\nimport { CryptorEvent, KeyHandlerEvent } from '../events';\nimport type {\n E2EEWorkerMessage,\n ErrorMessage,\n InitAck,\n KeyProviderOptions,\n RatchetMessage,\n RatchetRequestMessage,\n} from '../types';\nimport { FrameCryptor, encryptionEnabledMap } from './FrameCryptor';\nimport { ParticipantKeyHandler } from './ParticipantKeyHandler';\n\nconst participantCryptors: FrameCryptor[] = [];\nconst participantKeys: Map<string, ParticipantKeyHandler> = new Map();\nlet sharedKeyHandler: ParticipantKeyHandler | undefined;\n\nlet isEncryptionEnabled: boolean = false;\n\nlet useSharedKey: boolean = false;\n\nlet sifTrailer: Uint8Array | undefined;\n\nlet keyProviderOptions: KeyProviderOptions = KEY_PROVIDER_DEFAULTS;\n\nworkerLogger.setDefaultLevel('info');\n\nonmessage = (ev) => {\n const { kind, data }: E2EEWorkerMessage = ev.data;\n\n switch (kind) {\n case 'init':\n workerLogger.setLevel(data.loglevel);\n workerLogger.info('worker initialized');\n keyProviderOptions = data.keyProviderOptions;\n useSharedKey = !!data.keyProviderOptions.sharedKey;\n // acknowledge init successful\n const ackMsg: InitAck = {\n kind: 'initAck',\n data: { enabled: isEncryptionEnabled },\n };\n postMessage(ackMsg);\n break;\n case 'enable':\n setEncryptionEnabled(data.enabled, data.participantIdentity);\n workerLogger.info('updated e2ee enabled status');\n // acknowledge enable call successful\n postMessage(ev.data);\n break;\n case 'decode':\n let cryptor = getTrackCryptor(data.participantIdentity, data.trackId);\n cryptor.setupTransform(\n kind,\n data.readableStream,\n data.writableStream,\n data.trackId,\n data.codec,\n );\n break;\n case 'encode':\n let pubCryptor = getTrackCryptor(data.participantIdentity, data.trackId);\n pubCryptor.setupTransform(\n kind,\n data.readableStream,\n data.writableStream,\n data.trackId,\n data.codec,\n );\n break;\n case 'setKey':\n if (useSharedKey) {\n setSharedKey(data.key, data.keyIndex);\n } else if (data.participantIdentity) {\n workerLogger.info(\n `set participant sender key ${data.participantIdentity} index ${data.keyIndex}`,\n );\n getParticipantKeyHandler(data.participantIdentity).setKey(data.key, data.keyIndex);\n } else {\n workerLogger.error('no participant Id was provided and shared key usage is disabled');\n }\n break;\n case 'removeTransform':\n unsetCryptorParticipant(data.trackId, data.participantIdentity);\n break;\n case 'updateCodec':\n getTrackCryptor(data.participantIdentity, data.trackId).setVideoCodec(data.codec);\n break;\n case 'setRTPMap':\n // this is only used for the local participant\n participantCryptors.forEach((cr) => {\n if (cr.getParticipantIdentity() === data.participantIdentity) {\n cr.setRtpMap(data.map);\n }\n });\n break;\n case 'ratchetRequest':\n handleRatchetRequest(data);\n break;\n case 'setSifTrailer':\n handleSifTrailer(data.trailer);\n break;\n default:\n break;\n }\n};\n\nasync function handleRatchetRequest(data: RatchetRequestMessage['data']) {\n if (useSharedKey) {\n const keyHandler = getSharedKeyHandler();\n await keyHandler.ratchetKey(data.keyIndex);\n keyHandler.resetKeyStatus();\n } else if (data.participantIdentity) {\n const keyHandler = getParticipantKeyHandler(data.participantIdentity);\n await keyHandler.ratchetKey(data.keyIndex);\n keyHandler.resetKeyStatus();\n } else {\n workerLogger.error(\n 'no participant Id was provided for ratchet request and shared key usage is disabled',\n );\n }\n}\n\nfunction getTrackCryptor(participantIdentity: string, trackId: string) {\n let cryptor = participantCryptors.find((c) => c.getTrackId() === trackId);\n if (!cryptor) {\n workerLogger.info('creating new cryptor for', { participantIdentity });\n if (!keyProviderOptions) {\n throw Error('Missing keyProvider options');\n }\n cryptor = new FrameCryptor({\n participantIdentity,\n keys: getParticipantKeyHandler(participantIdentity),\n keyProviderOptions,\n sifTrailer,\n });\n\n setupCryptorErrorEvents(cryptor);\n participantCryptors.push(cryptor);\n } else if (participantIdentity !== cryptor.getParticipantIdentity()) {\n // assign new participant id to track cryptor and pass in correct key handler\n cryptor.setParticipant(participantIdentity, getParticipantKeyHandler(participantIdentity));\n }\n\n return cryptor;\n}\n\nfunction getParticipantKeyHandler(participantIdentity: string) {\n if (useSharedKey) {\n return getSharedKeyHandler();\n }\n let keys = participantKeys.get(participantIdentity);\n if (!keys) {\n keys = new ParticipantKeyHandler(participantIdentity, keyProviderOptions);\n keys.on(KeyHandlerEvent.KeyRatcheted, emitRatchetedKeys);\n participantKeys.set(participantIdentity, keys);\n }\n return keys;\n}\n\nfunction getSharedKeyHandler() {\n if (!sharedKeyHandler) {\n workerLogger.debug('creating new shared key handler');\n sharedKeyHandler = new ParticipantKeyHandler('shared-key', keyProviderOptions);\n }\n return sharedKeyHandler;\n}\n\nfunction unsetCryptorParticipant(trackId: string, participantIdentity: string) {\n const cryptor = participantCryptors.find(\n (c) => c.getParticipantIdentity() === participantIdentity && c.getTrackId() === trackId,\n );\n if (!cryptor) {\n workerLogger.warn('Could not unset participant on cryptor', { trackId, participantIdentity });\n } else {\n cryptor.unsetParticipant();\n }\n}\n\nfunction setEncryptionEnabled(enable: boolean, participantIdentity: string) {\n workerLogger.debug(`setting encryption enabled for all tracks of ${participantIdentity}`, {\n enable,\n });\n encryptionEnabledMap.set(participantIdentity, enable);\n}\n\nfunction setSharedKey(key: CryptoKey, index?: number) {\n workerLogger.info('set shared key', { index });\n getSharedKeyHandler().setKey(key, index);\n}\n\nfunction setupCryptorErrorEvents(cryptor: FrameCryptor) {\n cryptor.on(CryptorEvent.Error, (error) => {\n const msg: ErrorMessage = {\n kind: 'error',\n data: { error: new Error(`${CryptorErrorReason[error.reason]}: ${error.message}`) },\n };\n postMessage(msg);\n });\n}\n\nfunction emitRatchetedKeys(material: CryptoKey, participantIdentity: string, keyIndex?: number) {\n const msg: RatchetMessage = {\n kind: `ratchetKey`,\n data: {\n participantIdentity,\n keyIndex,\n material,\n },\n };\n postMessage(msg);\n}\n\nfunction handleSifTrailer(trailer: Uint8Array) {\n sifTrailer = trailer;\n participantCryptors.forEach((c) => {\n c.setSifTrailer(trailer);\n });\n}\n\n// Operations using RTCRtpScriptTransform.\n// @ts-ignore\nif (self.RTCTransformEvent) {\n workerLogger.debug('setup transform event');\n // @ts-ignore\n self.onrtctransform = (event) => {\n const transformer = event.transformer;\n workerLogger.debug('transformer', transformer);\n transformer.handled = true;\n const { kind, participantIdentity, trackId, codec } = transformer.options;\n const cryptor = getTrackCryptor(participantIdentity, trackId);\n workerLogger.debug('transform', { codec });\n cryptor.setupTransform(kind, transformer.readable, transformer.writable, trackId, codec);\n };\n}\n"],"names":["root","definition","module","exports","log","this","noop","undefinedType","isIE","window","navigator","test","userAgent","logMethods","bindMethod","obj","methodName","method","bind","Function","prototype","call","e","apply","arguments","traceForIE","console","trace","realMethod","undefined","replaceLoggingMethods","level","loggerName","i","length","methodFactory","debug","enableLoggingWhenConsoleArrives","defaultMethodFactory","Logger","name","defaultLevel","factory","self","currentLevel","storageKey","persistLevelIfPossible","levelNum","levelName","toUpperCase","localStorage","ignore","document","cookie","encodeURIComponent","getPersistedLevel","storedLevel","location","indexOf","exec","slice","levels","clearPersistedLevel","removeItem","getLevel","setLevel","persist","SILENT","setDefaultLevel","resetLevel","enableAll","TRACE","disableAll","initialLevel","defaultLogger","_loggersByName","getLogger","TypeError","logger","_log","noConflict","getLoggers","LogLevel","LoggerNames","livekitLogger","info","workerLogger","ENCRYPTION_ALGORITHM","KEYRING_SIZE","DECRYPTION_FAILURE_TOLERANCE","UNENCRYPTED_BYTES","key","delta","audio","empty","IV_LENGTH","SALT","KEY_PROVIDER_DEFAULTS","sharedKey","ratchetSalt","ratchetWindowSize","failureTolerance","MAX_SIF_COUNT","MAX_SIF_DURATION","LivekitError","Error","constructor","code","message","MediaDeviceFailure","getFailure","error","NotFound","PermissionDenied","DeviceInUse","Other","CryptorErrorReason","CryptorError","reason","InternalError","KeyProviderEvent","KeyHandlerEvent","EncryptionEvent","CryptorEvent","R","Reflect","ReflectApply","target","receiver","args","ReflectOwnKeys","ownKeys","Object","getOwnPropertySymbols","getOwnPropertyNames","concat","ProcessEmitWarning","warning","warn","NumberIsNaN","Number","isNaN","value","EventEmitter","init","eventsModule","once","_events","_eventsCount","_maxListeners","defaultMaxListeners","checkListener","listener","defineProperty","enumerable","get","set","arg","RangeError","getPrototypeOf","create","setMaxListeners","n","_getMaxListeners","that","getMaxListeners","emit","type","push","doError","events","er","err","context","handler","len","listeners","arrayClone","_addListener","prepend","m","existing","newListener","unshift","warned","w","String","emitter","count","addListener","on","prependListener","onceWrapper","fired","removeListener","wrapFn","_onceWrap","state","wrapped","prependOnceListener","list","position","originalListener","shift","spliceOne","off","removeAllListeners","keys","_listeners","unwrap","evlistener","unwrapListeners","rawListeners","listenerCount","eventNames","arr","copy","Array","index","pop","ret","Promise","resolve","reject","errorListener","resolver","eventTargetAgnosticAddListener","addErrorHandlerIfEventEmitter","flags","addEventListener","wrapListener","removeEventListener","isVideoFrame","frame","importKey","keyBytes","algorithm","usage","crypto","subtle","getAlgoOptions","algorithmName","salt","textEncoder","TextEncoder","encodedSalt","encode","hash","ArrayBuffer","iterations","deriveKeys","material","algorithmOptions","encryptionKey","deriveKey","ratchet","deriveBits","needsRbspUnescaping","frameData","parseRbsp","stream","dataOut","Uint8Array","kZerosInStartSequence","kEmulationByte","writeRbsp","data_in","numConsecutiveZeros","byte","SifGuard","consecutiveSifCount","lastSifReceivedAt","userFramesSinceSif","recordSif","_a","sifSequenceStartedAt","Date","now","recordUserFrame","reset","isSifAllowed","encryptionEnabledMap","Map","BaseFrameCryptor","encodeFunction","encodedFrame","controller","decodeFunction","FrameCryptor","opts","sendCounts","participantIdentity","rtpMap","keyProviderOptions","sifTrailer","from","sifGuard","logContext","identity","trackId","fallbackCodec","videoCodec","setParticipant","id","unsetParticipant","isEnabled","getParticipantIdentity","getTrackId","setVideoCodec","codec","setRtpMap","map","setupTransform","operation","readable","writable","assign","passedTrackId","transformFn","transformStream","TransformStream","transform","pipeThrough","pipeTo","catch","setSifTrailer","trailer","data","byteLength","enqueue","keySet","getKeySet","getCurrentKeyIndex","keyIndex","iv","makeIV","getMetadata","synchronizationSource","timestamp","frameInfo","getUnencryptedBytes","frameHeader","unencryptedBytes","frameTrailer","cipherText","encrypt","additionalData","newDataWithoutHeader","isH264","newData","buffer","MissingKey","isFrameServerInjected","hasValidKey","decodedFrame","decryptFrame","decryptionSuccess","InvalidKey","decryptionFailure","initialMaterial","ratchetOpts","ratchetCount","encryptedData","newUint8","ivLength","cipherTextStart","cipherTextLength","plainText","decrypt","RTCEncodedAudioFrame","ratchetedKeySet","newMaterial","ratchetKey","setKeySet","setCurrentKeyIndex","ivView","DataView","has","Math","floor","random","sendCount","setUint32","detectedCodec","getVideoCodec","naluIndices","findNALUIndices","some","naluIndex","NALUType","SLICE_IDR","SLICE_NON_IDR","includes","parseNALUType","size","payloadType","result","start","pos","searchLength","end","startByte","kNaluTypeMask","trailerBytes","every","ParticipantKeyHandler","_hasValidKey","decryptionFailureCount","currentKeyIndex","cryptoKeyRing","fill","ratchetPromiseMap","resetKeyStatus","setKey","existingPromise","ratchetPromise","__awaiter","currentMaterial","setKeyFromMaterial","KeyRatcheted","delete","emitRatchetEvent","newIndex","usages","participantCryptors","participantKeys","sharedKeyHandler","isEncryptionEnabled","useSharedKey","onmessage","ev","kind","loglevel","ackMsg","enabled","postMessage","setEncryptionEnabled","cryptor","getTrackCryptor","readableStream","writableStream","pubCryptor","setSharedKey","getParticipantKeyHandler","unsetCryptorParticipant","forEach","cr","handleRatchetRequest","handleSifTrailer","keyHandler","getSharedKeyHandler","find","c","setupCryptorErrorEvents","emitRatchetedKeys","enable","msg","RTCTransformEvent","onrtctransform","event","transformer","handled","options"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAMC,CAAUA,UAAAA,IAAI,EAAEC,UAAU,EAAE;;IAIlB,IAAkCC,MAAM,CAACC,OAAO,EAAE;AACrDD,MAAAA,MAAA,CAAAC,OAAA,GAAiBF,UAAU,EAAE,CAAA;AACrC,KAAK,MAAM;AACHD,MAAAA,IAAI,CAACI,GAAG,GAAGH,UAAU,EAAE,CAAA;AAC1B,KAAA;AACL,GAAC,EAACI,cAAI,EAAE,YAAY;;AAGpB;AACI,IAAA,IAAIC,IAAI,GAAG,YAAW,EAAE,CAAA;IACxB,IAAIC,aAAa,GAAG,WAAW,CAAA;IAC/B,IAAIC,IAAI,GAAI,OAAOC,MAAM,KAAKF,aAAa,IAAM,OAAOE,MAAM,CAACC,SAAS,KAAKH,aAAc,IACvF,iBAAiB,CAACI,IAAI,CAACF,MAAM,CAACC,SAAS,CAACE,SAAS,CACpD,CAAA;AAED,IAAA,IAAIC,UAAU,GAAG,CACb,OAAO,EACP,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,CACV,CAAA;;AAEL;AACI,IAAA,SAASC,UAAUA,CAACC,GAAG,EAAEC,UAAU,EAAE;AACjC,MAAA,IAAIC,MAAM,GAAGF,GAAG,CAACC,UAAU,CAAC,CAAA;AAC5B,MAAA,IAAI,OAAOC,MAAM,CAACC,IAAI,KAAK,UAAU,EAAE;AACnC,QAAA,OAAOD,MAAM,CAACC,IAAI,CAACH,GAAG,CAAC,CAAA;AACnC,OAAS,MAAM;QACH,IAAI;UACA,OAAOI,QAAQ,CAACC,SAAS,CAAC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sources":["../node_modules/.pnpm/loglevel@1.8.1/node_modules/loglevel/lib/loglevel.js","../src/logger.ts","../src/e2ee/constants.ts","../src/room/errors.ts","../src/e2ee/errors.ts","../src/e2ee/events.ts","../node_modules/.pnpm/events@3.3.0/node_modules/events/events.js","../src/e2ee/utils.ts","../src/e2ee/worker/SifGuard.ts","../src/e2ee/worker/FrameCryptor.ts","../src/e2ee/worker/ParticipantKeyHandler.ts","../src/e2ee/worker/e2ee.worker.ts"],"sourcesContent":["/*\n* loglevel - https://github.com/pimterry/loglevel\n*\n* Copyright (c) 2013 Tim Perry\n* Licensed under the MIT license.\n*/\n(function (root, definition) {\n \"use strict\";\n if (typeof define === 'function' && define.amd) {\n define(definition);\n } else if (typeof module === 'object' && module.exports) {\n module.exports = definition();\n } else {\n root.log = definition();\n }\n}(this, function () {\n \"use strict\";\n\n // Slightly dubious tricks to cut down minimized file size\n var noop = function() {};\n var undefinedType = \"undefined\";\n var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (\n /Trident\\/|MSIE /.test(window.navigator.userAgent)\n );\n\n var logMethods = [\n \"trace\",\n \"debug\",\n \"info\",\n \"warn\",\n \"error\"\n ];\n\n // Cross-browser bind equivalent that works at least back to IE6\n function bindMethod(obj, methodName) {\n var method = obj[methodName];\n if (typeof method.bind === 'function') {\n return method.bind(obj);\n } else {\n try {\n return Function.prototype.bind.call(method, obj);\n } catch (e) {\n // Missing bind shim or IE8 + Modernizr, fallback to wrapping\n return function() {\n return Function.prototype.apply.apply(method, [obj, arguments]);\n };\n }\n }\n }\n\n // Trace() doesn't print the message in IE, so for that case we need to wrap it\n function traceForIE() {\n if (console.log) {\n if (console.log.apply) {\n console.log.apply(console, arguments);\n } else {\n // In old IE, native console methods themselves don't have apply().\n Function.prototype.apply.apply(console.log, [console, arguments]);\n }\n }\n if (console.trace) console.trace();\n }\n\n // Build the best logging method possible for this env\n // Wherever possible we want to bind, not wrap, to preserve stack traces\n function realMethod(methodName) {\n if (methodName === 'debug') {\n methodName = 'log';\n }\n\n if (typeof console === undefinedType) {\n return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives\n } else if (methodName === 'trace' && isIE) {\n return traceForIE;\n } else if (console[methodName] !== undefined) {\n return bindMethod(console, methodName);\n } else if (console.log !== undefined) {\n return bindMethod(console, 'log');\n } else {\n return noop;\n }\n }\n\n // These private functions always need `this` to be set properly\n\n function replaceLoggingMethods(level, loggerName) {\n /*jshint validthis:true */\n for (var i = 0; i < logMethods.length; i++) {\n var methodName = logMethods[i];\n this[methodName] = (i < level) ?\n noop :\n this.methodFactory(methodName, level, loggerName);\n }\n\n // Define log.log as an alias for log.debug\n this.log = this.debug;\n }\n\n // In old IE versions, the console isn't present until you first open it.\n // We build realMethod() replacements here that regenerate logging methods\n function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {\n return function () {\n if (typeof console !== undefinedType) {\n replaceLoggingMethods.call(this, level, loggerName);\n this[methodName].apply(this, arguments);\n }\n };\n }\n\n // By default, we use closely bound real methods wherever possible, and\n // otherwise we wait for a console to appear, and then try again.\n function defaultMethodFactory(methodName, level, loggerName) {\n /*jshint validthis:true */\n return realMethod(methodName) ||\n enableLoggingWhenConsoleArrives.apply(this, arguments);\n }\n\n function Logger(name, defaultLevel, factory) {\n var self = this;\n var currentLevel;\n defaultLevel = defaultLevel == null ? \"WARN\" : defaultLevel;\n\n var storageKey = \"loglevel\";\n if (typeof name === \"string\") {\n storageKey += \":\" + name;\n } else if (typeof name === \"symbol\") {\n storageKey = undefined;\n }\n\n function persistLevelIfPossible(levelNum) {\n var levelName = (logMethods[levelNum] || 'silent').toUpperCase();\n\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage[storageKey] = levelName;\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=\" + levelName + \";\";\n } catch (ignore) {}\n }\n\n function getPersistedLevel() {\n var storedLevel;\n\n if (typeof window === undefinedType || !storageKey) return;\n\n try {\n storedLevel = window.localStorage[storageKey];\n } catch (ignore) {}\n\n // Fallback to cookies if local storage gives us nothing\n if (typeof storedLevel === undefinedType) {\n try {\n var cookie = window.document.cookie;\n var location = cookie.indexOf(\n encodeURIComponent(storageKey) + \"=\");\n if (location !== -1) {\n storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];\n }\n } catch (ignore) {}\n }\n\n // If the stored level is not valid, treat it as if nothing was stored.\n if (self.levels[storedLevel] === undefined) {\n storedLevel = undefined;\n }\n\n return storedLevel;\n }\n\n function clearPersistedLevel() {\n if (typeof window === undefinedType || !storageKey) return;\n\n // Use localStorage if available\n try {\n window.localStorage.removeItem(storageKey);\n return;\n } catch (ignore) {}\n\n // Use session cookie as fallback\n try {\n window.document.cookie =\n encodeURIComponent(storageKey) + \"=; expires=Thu, 01 Jan 1970 00:00:00 UTC\";\n } catch (ignore) {}\n }\n\n /*\n *\n * Public logger API - see https://github.com/pimterry/loglevel for details\n *\n */\n\n self.name = name;\n\n self.levels = { \"TRACE\": 0, \"DEBUG\": 1, \"INFO\": 2, \"WARN\": 3,\n \"ERROR\": 4, \"SILENT\": 5};\n\n self.methodFactory = factory || defaultMethodFactory;\n\n self.getLevel = function () {\n return currentLevel;\n };\n\n self.setLevel = function (level, persist) {\n if (typeof level === \"string\" && self.levels[level.toUpperCase()] !== undefined) {\n level = self.levels[level.toUpperCase()];\n }\n if (typeof level === \"number\" && level >= 0 && level <= self.levels.SILENT) {\n currentLevel = level;\n if (persist !== false) { // defaults to true\n persistLevelIfPossible(level);\n }\n replaceLoggingMethods.call(self, level, name);\n if (typeof console === undefinedType && level < self.levels.SILENT) {\n return \"No console available for logging\";\n }\n } else {\n throw \"log.setLevel() called with invalid level: \" + level;\n }\n };\n\n self.setDefaultLevel = function (level) {\n defaultLevel = level;\n if (!getPersistedLevel()) {\n self.setLevel(level, false);\n }\n };\n\n self.resetLevel = function () {\n self.setLevel(defaultLevel, false);\n clearPersistedLevel();\n };\n\n self.enableAll = function(persist) {\n self.setLevel(self.levels.TRACE, persist);\n };\n\n self.disableAll = function(persist) {\n self.setLevel(self.levels.SILENT, persist);\n };\n\n // Initialize with the right level\n var initialLevel = getPersistedLevel();\n if (initialLevel == null) {\n initialLevel = defaultLevel;\n }\n self.setLevel(initialLevel, false);\n }\n\n /*\n *\n * Top-level API\n *\n */\n\n var defaultLogger = new Logger();\n\n var _loggersByName = {};\n defaultLogger.getLogger = function getLogger(name) {\n if ((typeof name !== \"symbol\" && typeof name !== \"string\") || name === \"\") {\n throw new TypeError(\"You must supply a name when creating a logger.\");\n }\n\n var logger = _loggersByName[name];\n if (!logger) {\n logger = _loggersByName[name] = new Logger(\n name, defaultLogger.getLevel(), defaultLogger.methodFactory);\n }\n return logger;\n };\n\n // Grab the current global log variable in case of overwrite\n var _log = (typeof window !== undefinedType) ? window.log : undefined;\n defaultLogger.noConflict = function() {\n if (typeof window !== undefinedType &&\n window.log === defaultLogger) {\n window.log = _log;\n }\n\n return defaultLogger;\n };\n\n defaultLogger.getLoggers = function getLoggers() {\n return _loggersByName;\n };\n\n // ES6 default export, for compatibility\n defaultLogger['default'] = defaultLogger;\n\n return defaultLogger;\n}));\n","import * as log from 'loglevel';\n\nexport enum LogLevel {\n trace = 0,\n debug = 1,\n info = 2,\n warn = 3,\n error = 4,\n silent = 5,\n}\n\nexport enum LoggerNames {\n Default = 'livekit',\n Room = 'livekit-room',\n Participant = 'livekit-participant',\n Track = 'livekit-track',\n Publication = 'livekit-track-publication',\n Engine = 'livekit-engine',\n Signal = 'livekit-signal',\n PCManager = 'livekit-pc-manager',\n PCTransport = 'livekit-pc-transport',\n E2EE = 'lk-e2ee',\n}\n\ntype LogLevelString = keyof typeof LogLevel;\n\nexport type StructuredLogger = log.Logger & {\n trace: (msg: string, context?: object) => void;\n debug: (msg: string, context?: object) => void;\n info: (msg: string, context?: object) => void;\n warn: (msg: string, context?: object) => void;\n error: (msg: string, context?: object) => void;\n setDefaultLevel: (level: log.LogLevelDesc) => void;\n setLevel: (level: log.LogLevelDesc) => void;\n getLevel: () => number;\n};\n\nlet livekitLogger = log.getLogger('livekit');\nconst livekitLoggers = Object.values(LoggerNames).map((name) => log.getLogger(name));\n\nlivekitLogger.setDefaultLevel(LogLevel.info);\n\nexport default livekitLogger as StructuredLogger;\n\n/**\n * @internal\n */\nexport function getLogger(name: string) {\n const logger = log.getLogger(name);\n logger.setDefaultLevel(livekitLogger.getLevel());\n return logger as StructuredLogger;\n}\n\nexport function setLogLevel(level: LogLevel | LogLevelString, loggerName?: LoggerNames) {\n if (loggerName) {\n log.getLogger(loggerName).setLevel(level);\n }\n for (const logger of livekitLoggers) {\n logger.setLevel(level);\n }\n}\n\nexport type LogExtension = (level: LogLevel, msg: string, context?: object) => void;\n\n/**\n * use this to hook into the logging function to allow sending internal livekit logs to third party services\n * if set, the browser logs will lose their stacktrace information (see https://github.com/pimterry/loglevel#writing-plugins)\n */\nexport function setLogExtension(extension: LogExtension, logger?: StructuredLogger) {\n const loggers = logger ? [logger] : livekitLoggers;\n\n loggers.forEach((logR) => {\n const originalFactory = logR.methodFactory;\n\n logR.methodFactory = (methodName, configLevel, loggerName) => {\n const rawMethod = originalFactory(methodName, configLevel, loggerName);\n\n const logLevel = LogLevel[methodName as LogLevelString];\n const needLog = logLevel >= configLevel && logLevel < LogLevel.silent;\n\n return (msg, context?: [msg: string, context: object]) => {\n if (context) rawMethod(msg, context);\n else rawMethod(msg);\n if (needLog) {\n extension(logLevel, msg, context);\n }\n };\n };\n logR.setLevel(logR.getLevel());\n });\n}\n\nexport const workerLogger = log.getLogger('lk-e2ee') as StructuredLogger;\n","import type { KeyProviderOptions } from './types';\n\nexport const ENCRYPTION_ALGORITHM = 'AES-GCM';\n\n// We use a ringbuffer of keys so we can change them and still decode packets that were\n// encrypted with an old key. We use a size of 16 which corresponds to the four bits\n// in the frame trailer.\nexport const KEYRING_SIZE = 16;\n\n// How many consecutive frames can fail decrypting before a particular key gets marked as invalid\nexport const DECRYPTION_FAILURE_TOLERANCE = 10;\n\n// We copy the first bytes of the VP8 payload unencrypted.\n// For keyframes this is 10 bytes, for non-keyframes (delta) 3. See\n// https://tools.ietf.org/html/rfc6386#section-9.1\n// This allows the bridge to continue detecting keyframes (only one byte needed in the JVB)\n// and is also a bit easier for the VP8 decoder (i.e. it generates funny garbage pictures\n// instead of being unable to decode).\n// This is a bit for show and we might want to reduce to 1 unconditionally in the final version.\n//\n// For audio (where frame.type is not set) we do not encrypt the opus TOC byte:\n// https://tools.ietf.org/html/rfc6716#section-3.1\nexport const UNENCRYPTED_BYTES = {\n key: 10,\n delta: 3,\n audio: 1, // frame.type is not set on audio, so this is set manually\n empty: 0,\n} as const;\n\n/* We use a 12 byte bit IV. This is signalled in plain together with the\n packet. See https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt#parameters */\nexport const IV_LENGTH = 12;\n\n// flag set to indicate that e2ee has been setup for sender/receiver;\nexport const E2EE_FLAG = 'lk_e2ee';\n\nexport const SALT = 'LKFrameEncryptionKey';\n\nexport const KEY_PROVIDER_DEFAULTS: KeyProviderOptions = {\n sharedKey: false,\n ratchetSalt: SALT,\n ratchetWindowSize: 8,\n failureTolerance: DECRYPTION_FAILURE_TOLERANCE,\n} as const;\n\nexport const MAX_SIF_COUNT = 100;\nexport const MAX_SIF_DURATION = 2000;\n","export class LivekitError extends Error {\n code: number;\n\n constructor(code: number, message?: string) {\n super(message || 'an error has occured');\n this.code = code;\n }\n}\n\nexport const enum ConnectionErrorReason {\n NotAllowed,\n ServerUnreachable,\n InternalError,\n Cancelled,\n LeaveRequest,\n}\n\nexport class ConnectionError extends LivekitError {\n status?: number;\n\n reason?: ConnectionErrorReason;\n\n constructor(message?: string, reason?: ConnectionErrorReason, status?: number) {\n super(1, message);\n this.status = status;\n this.reason = reason;\n }\n}\n\nexport class DeviceUnsupportedError extends LivekitError {\n constructor(message?: string) {\n super(21, message ?? 'device is unsupported');\n }\n}\n\nexport class TrackInvalidError extends LivekitError {\n constructor(message?: string) {\n super(20, message ?? 'track is invalid');\n }\n}\n\nexport class UnsupportedServer extends LivekitError {\n constructor(message?: string) {\n super(10, message ?? 'unsupported server');\n }\n}\n\nexport class UnexpectedConnectionState extends LivekitError {\n constructor(message?: string) {\n super(12, message ?? 'unexpected connection state');\n }\n}\n\nexport class NegotiationError extends LivekitError {\n constructor(message?: string) {\n super(13, message ?? 'unable to negotiate');\n }\n}\n\nexport class PublishDataError extends LivekitError {\n constructor(message?: string) {\n super(13, message ?? 'unable to publish data');\n }\n}\n\nexport enum MediaDeviceFailure {\n // user rejected permissions\n PermissionDenied = 'PermissionDenied',\n // device is not available\n NotFound = 'NotFound',\n // device is in use. On Windows, only a single tab may get access to a device at a time.\n DeviceInUse = 'DeviceInUse',\n Other = 'Other',\n}\n\nexport namespace MediaDeviceFailure {\n export function getFailure(error: any): MediaDeviceFailure | undefined {\n if (error && 'name' in error) {\n if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {\n return MediaDeviceFailure.NotFound;\n }\n if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {\n return MediaDeviceFailure.PermissionDenied;\n }\n if (error.name === 'NotReadableError' || error.name === 'TrackStartError') {\n return MediaDeviceFailure.DeviceInUse;\n }\n return MediaDeviceFailure.Other;\n }\n }\n}\n","import { LivekitError } from '../room/errors';\n\nexport enum CryptorErrorReason {\n InvalidKey = 0,\n MissingKey = 1,\n InternalError = 2,\n}\n\nexport class CryptorError extends LivekitError {\n reason: CryptorErrorReason;\n\n constructor(message?: string, reason: CryptorErrorReason = CryptorErrorReason.InternalError) {\n super(40, message);\n this.reason = reason;\n }\n}\n","import type Participant from '../room/participant/Participant';\nimport type { CryptorError } from './errors';\nimport type { KeyInfo } from './types';\n\nexport enum KeyProviderEvent {\n SetKey = 'setKey',\n RatchetRequest = 'ratchetRequest',\n KeyRatcheted = 'keyRatcheted',\n}\n\nexport type KeyProviderCallbacks = {\n [KeyProviderEvent.SetKey]: (keyInfo: KeyInfo) => void;\n [KeyProviderEvent.RatchetRequest]: (participantIdentity?: string, keyIndex?: number) => void;\n [KeyProviderEvent.KeyRatcheted]: (material: CryptoKey, keyIndex?: number) => void;\n};\n\nexport enum KeyHandlerEvent {\n KeyRatcheted = 'keyRatcheted',\n}\n\nexport type ParticipantKeyHandlerCallbacks = {\n [KeyHandlerEvent.KeyRatcheted]: (\n material: CryptoKey,\n participantIdentity: string,\n keyIndex?: number,\n ) => void;\n};\n\nexport enum EncryptionEvent {\n ParticipantEncryptionStatusChanged = 'participantEncryptionStatusChanged',\n EncryptionError = 'encryptionError',\n}\n\nexport type E2EEManagerCallbacks = {\n [EncryptionEvent.ParticipantEncryptionStatusChanged]: (\n enabled: boolean,\n participant: Participant,\n ) => void;\n [EncryptionEvent.EncryptionError]: (error: Error) => void;\n};\n\nexport type CryptorCallbacks = {\n [CryptorEvent.Error]: (error: CryptorError) => void;\n};\n\nexport enum CryptorEvent {\n Error = 'cryptorError',\n}\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","import { ENCRYPTION_ALGORITHM } from './constants';\n\nexport function isE2EESupported() {\n return isInsertableStreamSupported() || isScriptTransformSupported();\n}\n\nexport function isScriptTransformSupported() {\n // @ts-ignore\n return typeof window.RTCRtpScriptTransform !== 'undefined';\n}\n\nexport function isInsertableStreamSupported() {\n return (\n typeof window.RTCRtpSender !== 'undefined' &&\n // @ts-ignore\n typeof window.RTCRtpSender.prototype.createEncodedStreams !== 'undefined'\n );\n}\n\nexport function isVideoFrame(\n frame: RTCEncodedAudioFrame | RTCEncodedVideoFrame,\n): frame is RTCEncodedVideoFrame {\n return 'type' in frame;\n}\n\nexport async function importKey(\n keyBytes: Uint8Array | ArrayBuffer,\n algorithm: string | { name: string } = { name: ENCRYPTION_ALGORITHM },\n usage: 'derive' | 'encrypt' = 'encrypt',\n) {\n // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey\n return crypto.subtle.importKey(\n 'raw',\n keyBytes,\n algorithm,\n false,\n usage === 'derive' ? ['deriveBits', 'deriveKey'] : ['encrypt', 'decrypt'],\n );\n}\n\nexport async function createKeyMaterialFromString(password: string) {\n let enc = new TextEncoder();\n\n const keyMaterial = await crypto.subtle.importKey(\n 'raw',\n enc.encode(password),\n {\n name: 'PBKDF2',\n },\n false,\n ['deriveBits', 'deriveKey'],\n );\n\n return keyMaterial;\n}\n\nexport async function createKeyMaterialFromBuffer(cryptoBuffer: ArrayBuffer) {\n const keyMaterial = await crypto.subtle.importKey('raw', cryptoBuffer, 'HKDF', false, [\n 'deriveBits',\n 'deriveKey',\n ]);\n\n return keyMaterial;\n}\n\nfunction getAlgoOptions(algorithmName: string, salt: string) {\n const textEncoder = new TextEncoder();\n const encodedSalt = textEncoder.encode(salt);\n switch (algorithmName) {\n case 'HKDF':\n return {\n name: 'HKDF',\n salt: encodedSalt,\n hash: 'SHA-256',\n info: new ArrayBuffer(128),\n };\n case 'PBKDF2': {\n return {\n name: 'PBKDF2',\n salt: encodedSalt,\n hash: 'SHA-256',\n iterations: 100000,\n };\n }\n default:\n throw new Error(`algorithm ${algorithmName} is currently unsupported`);\n }\n}\n\n/**\n * Derives a set of keys from the master key.\n * See https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.1\n */\nexport async function deriveKeys(material: CryptoKey, salt: string) {\n const algorithmOptions = getAlgoOptions(material.algorithm.name, salt);\n\n // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveKey#HKDF\n // https://developer.mozilla.org/en-US/docs/Web/API/HkdfParams\n const encryptionKey = await crypto.subtle.deriveKey(\n algorithmOptions,\n material,\n {\n name: ENCRYPTION_ALGORITHM,\n length: 128,\n },\n false,\n ['encrypt', 'decrypt'],\n );\n\n return { material, encryptionKey };\n}\n\nexport function createE2EEKey(): Uint8Array {\n return window.crypto.getRandomValues(new Uint8Array(32));\n}\n\n/**\n * Ratchets a key. See\n * https://tools.ietf.org/html/draft-omara-sframe-00#section-4.3.5.1\n */\nexport async function ratchet(material: CryptoKey, salt: string): Promise<ArrayBuffer> {\n const algorithmOptions = getAlgoOptions(material.algorithm.name, salt);\n\n // https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/deriveBits\n return crypto.subtle.deriveBits(algorithmOptions, material, 256);\n}\n\nexport function needsRbspUnescaping(frameData: Uint8Array) {\n for (var i = 0; i < frameData.length - 3; i++) {\n if (frameData[i] == 0 && frameData[i + 1] == 0 && frameData[i + 2] == 3) return true;\n }\n return false;\n}\n\nexport function parseRbsp(stream: Uint8Array): Uint8Array {\n const dataOut: number[] = [];\n var length = stream.length;\n for (var i = 0; i < stream.length; ) {\n // Be careful about over/underflow here. byte_length_ - 3 can underflow, and\n // i + 3 can overflow, but byte_length_ - i can't, because i < byte_length_\n // above, and that expression will produce the number of bytes left in\n // the stream including the byte at i.\n if (length - i >= 3 && !stream[i] && !stream[i + 1] && stream[i + 2] == 3) {\n // Two rbsp bytes.\n dataOut.push(stream[i++]);\n dataOut.push(stream[i++]);\n // Skip the emulation byte.\n i++;\n } else {\n // Single rbsp byte.\n dataOut.push(stream[i++]);\n }\n }\n return new Uint8Array(dataOut);\n}\n\nconst kZerosInStartSequence = 2;\nconst kEmulationByte = 3;\n\nexport function writeRbsp(data_in: Uint8Array): Uint8Array {\n const dataOut: number[] = [];\n var numConsecutiveZeros = 0;\n for (var i = 0; i < data_in.length; ++i) {\n var byte = data_in[i];\n if (byte <= kEmulationByte && numConsecutiveZeros >= kZerosInStartSequence) {\n // Need to escape.\n dataOut.push(kEmulationByte);\n numConsecutiveZeros = 0;\n }\n dataOut.push(byte);\n if (byte == 0) {\n ++numConsecutiveZeros;\n } else {\n numConsecutiveZeros = 0;\n }\n }\n return new Uint8Array(dataOut);\n}\n","import { MAX_SIF_COUNT, MAX_SIF_DURATION } from '../constants';\n\nexport class SifGuard {\n private consecutiveSifCount = 0;\n\n private sifSequenceStartedAt: number | undefined;\n\n private lastSifReceivedAt: number = 0;\n\n private userFramesSinceSif: number = 0;\n\n recordSif() {\n this.consecutiveSifCount += 1;\n this.sifSequenceStartedAt ??= Date.now();\n this.lastSifReceivedAt = Date.now();\n }\n\n recordUserFrame() {\n if (this.sifSequenceStartedAt === undefined) {\n return;\n } else {\n this.userFramesSinceSif += 1;\n }\n if (\n // reset if we received more user frames than SIFs\n this.userFramesSinceSif > this.consecutiveSifCount ||\n // also reset if we got a new user frame and the latest SIF frame hasn't been updated in a while\n Date.now() - this.lastSifReceivedAt > MAX_SIF_DURATION\n ) {\n this.reset();\n }\n }\n\n isSifAllowed() {\n return (\n this.consecutiveSifCount < MAX_SIF_COUNT &&\n (this.sifSequenceStartedAt === undefined ||\n Date.now() - this.sifSequenceStartedAt < MAX_SIF_DURATION)\n );\n }\n\n reset() {\n this.userFramesSinceSif = 0;\n this.consecutiveSifCount = 0;\n this.sifSequenceStartedAt = undefined;\n }\n}\n","/* eslint-disable @typescript-eslint/no-unused-vars */\n// TODO code inspired by https://github.com/webrtc/samples/blob/gh-pages/src/content/insertable-streams/endtoend-encryption/js/worker.js\nimport { EventEmitter } from 'events';\nimport type TypedEventEmitter from 'typed-emitter';\nimport { workerLogger } from '../../logger';\nimport type { VideoCodec } from '../../room/track/options';\nimport { ENCRYPTION_ALGORITHM, IV_LENGTH, UNENCRYPTED_BYTES } from '../constants';\nimport { CryptorError, CryptorErrorReason } from '../errors';\nimport { CryptorCallbacks, CryptorEvent } from '../events';\nimport type { DecodeRatchetOptions, KeyProviderOptions, KeySet } from '../types';\nimport { deriveKeys, isVideoFrame, needsRbspUnescaping, parseRbsp, writeRbsp } from '../utils';\nimport type { ParticipantKeyHandler } from './ParticipantKeyHandler';\nimport { SifGuard } from './SifGuard';\n\nexport const encryptionEnabledMap: Map<string, boolean> = new Map();\n\nexport interface FrameCryptorConstructor {\n new (opts?: unknown): BaseFrameCryptor;\n}\n\nexport interface TransformerInfo {\n readable: ReadableStream;\n writable: WritableStream;\n transformer: TransformStream;\n abortController: AbortController;\n}\n\nexport class BaseFrameCryptor extends (EventEmitter as new () => TypedEventEmitter<CryptorCallbacks>) {\n protected encodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ): Promise<any> {\n throw Error('not implemented for subclass');\n }\n\n protected decodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ): Promise<any> {\n throw Error('not implemented for subclass');\n }\n}\n\n/**\n * Cryptor is responsible for en-/decrypting media frames.\n * Each Cryptor instance is responsible for en-/decrypting a single mediaStreamTrack.\n */\nexport class FrameCryptor extends BaseFrameCryptor {\n private sendCounts: Map<number, number>;\n\n private participantIdentity: string | undefined;\n\n private trackId: string | undefined;\n\n private keys: ParticipantKeyHandler;\n\n private videoCodec?: VideoCodec;\n\n private rtpMap: Map<number, VideoCodec>;\n\n private keyProviderOptions: KeyProviderOptions;\n\n /**\n * used for detecting server injected unencrypted frames\n */\n private sifTrailer: Uint8Array;\n\n private sifGuard: SifGuard;\n\n private detectedCodec?: VideoCodec;\n\n constructor(opts: {\n keys: ParticipantKeyHandler;\n participantIdentity: string;\n keyProviderOptions: KeyProviderOptions;\n sifTrailer?: Uint8Array;\n }) {\n super();\n this.sendCounts = new Map();\n this.keys = opts.keys;\n this.participantIdentity = opts.participantIdentity;\n this.rtpMap = new Map();\n this.keyProviderOptions = opts.keyProviderOptions;\n this.sifTrailer = opts.sifTrailer ?? Uint8Array.from([]);\n this.sifGuard = new SifGuard();\n }\n\n private get logContext() {\n return {\n participant: this.participantIdentity,\n mediaTrackId: this.trackId,\n fallbackCodec: this.videoCodec,\n };\n }\n\n /**\n * Assign a different participant to the cryptor.\n * useful for transceiver re-use\n * @param id\n * @param keys\n */\n setParticipant(id: string, keys: ParticipantKeyHandler) {\n this.participantIdentity = id;\n this.keys = keys;\n this.sifGuard.reset();\n }\n\n unsetParticipant() {\n workerLogger.debug('unsetting participant', this.logContext);\n this.participantIdentity = undefined;\n }\n\n isEnabled() {\n if (this.participantIdentity) {\n return encryptionEnabledMap.get(this.participantIdentity);\n } else {\n return undefined;\n }\n }\n\n getParticipantIdentity() {\n return this.participantIdentity;\n }\n\n getTrackId() {\n return this.trackId;\n }\n\n /**\n * Update the video codec used by the mediaStreamTrack\n * @param codec\n */\n setVideoCodec(codec: VideoCodec) {\n this.videoCodec = codec;\n }\n\n /**\n * rtp payload type map used for figuring out codec of payload type when encoding\n * @param map\n */\n setRtpMap(map: Map<number, VideoCodec>) {\n this.rtpMap = map;\n }\n\n setupTransform(\n operation: 'encode' | 'decode',\n readable: ReadableStream,\n writable: WritableStream,\n trackId: string,\n codec?: VideoCodec,\n ) {\n if (codec) {\n workerLogger.info('setting codec on cryptor to', { codec });\n this.videoCodec = codec;\n }\n\n workerLogger.debug('Setting up frame cryptor transform', {\n operation,\n passedTrackId: trackId,\n codec,\n ...this.logContext,\n });\n\n const transformFn = operation === 'encode' ? this.encodeFunction : this.decodeFunction;\n const transformStream = new TransformStream({\n transform: transformFn.bind(this),\n });\n\n readable\n .pipeThrough(transformStream)\n .pipeTo(writable)\n .catch((e) => {\n workerLogger.warn(e);\n this.emit(CryptorEvent.Error, e instanceof CryptorError ? e : new CryptorError(e.message));\n });\n this.trackId = trackId;\n }\n\n setSifTrailer(trailer: Uint8Array) {\n workerLogger.debug('setting SIF trailer', { ...this.logContext, trailer });\n this.sifTrailer = trailer;\n }\n\n /**\n * Function that will be injected in a stream and will encrypt the given encoded frames.\n *\n * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.\n * @param {TransformStreamDefaultController} controller - TransportStreamController.\n *\n * The VP8 payload descriptor described in\n * https://tools.ietf.org/html/rfc7741#section-4.2\n * is part of the RTP packet and not part of the frame and is not controllable by us.\n * This is fine as the SFU keeps having access to it for routing.\n *\n * The encrypted frame is formed as follows:\n * 1) Find unencrypted byte length, depending on the codec, frame type and kind.\n * 2) Form the GCM IV for the frame as described above.\n * 3) Encrypt the rest of the frame using AES-GCM.\n * 4) Allocate space for the encrypted frame.\n * 5) Copy the unencrypted bytes to the start of the encrypted frame.\n * 6) Append the ciphertext to the encrypted frame.\n * 7) Append the IV.\n * 8) Append a single byte for the key identifier.\n * 9) Enqueue the encrypted frame for sending.\n */\n protected async encodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ) {\n if (\n !this.isEnabled() ||\n // skip for encryption for empty dtx frames\n encodedFrame.data.byteLength === 0\n ) {\n return controller.enqueue(encodedFrame);\n }\n const keySet = this.keys.getKeySet();\n if (!keySet) {\n throw new TypeError(\n `key set not found for ${\n this.participantIdentity\n } at index ${this.keys.getCurrentKeyIndex()}`,\n );\n }\n const { encryptionKey } = keySet;\n const keyIndex = this.keys.getCurrentKeyIndex();\n\n if (encryptionKey) {\n const iv = this.makeIV(\n encodedFrame.getMetadata().synchronizationSource ?? -1,\n encodedFrame.timestamp,\n );\n let frameInfo = this.getUnencryptedBytes(encodedFrame);\n\n // Thіs is not encrypted and contains the VP8 payload descriptor or the Opus TOC byte.\n const frameHeader = new Uint8Array(encodedFrame.data, 0, frameInfo.unencryptedBytes);\n\n // Frame trailer contains the R|IV_LENGTH and key index\n const frameTrailer = new Uint8Array(2);\n\n frameTrailer[0] = IV_LENGTH;\n frameTrailer[1] = keyIndex;\n\n // Construct frame trailer. Similar to the frame header described in\n // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.2\n // but we put it at the end.\n //\n // ---------+-------------------------+-+---------+----\n // payload |IV...(length = IV_LENGTH)|R|IV_LENGTH|KID |\n // ---------+-------------------------+-+---------+----\n try {\n const cipherText = await crypto.subtle.encrypt(\n {\n name: ENCRYPTION_ALGORITHM,\n iv,\n additionalData: new Uint8Array(encodedFrame.data, 0, frameHeader.byteLength),\n },\n encryptionKey,\n new Uint8Array(encodedFrame.data, frameInfo.unencryptedBytes),\n );\n\n let newDataWithoutHeader = new Uint8Array(\n cipherText.byteLength + iv.byteLength + frameTrailer.byteLength,\n );\n newDataWithoutHeader.set(new Uint8Array(cipherText)); // add ciphertext.\n newDataWithoutHeader.set(new Uint8Array(iv), cipherText.byteLength); // append IV.\n newDataWithoutHeader.set(frameTrailer, cipherText.byteLength + iv.byteLength); // append frame trailer.\n\n if (frameInfo.isH264) {\n newDataWithoutHeader = writeRbsp(newDataWithoutHeader);\n }\n\n var newData = new Uint8Array(frameHeader.byteLength + newDataWithoutHeader.byteLength);\n newData.set(frameHeader);\n newData.set(newDataWithoutHeader, frameHeader.byteLength);\n\n encodedFrame.data = newData.buffer;\n\n return controller.enqueue(encodedFrame);\n } catch (e: any) {\n // TODO: surface this to the app.\n workerLogger.error(e);\n }\n } else {\n workerLogger.debug('failed to decrypt, emitting error', this.logContext);\n this.emit(\n CryptorEvent.Error,\n new CryptorError(`encryption key missing for encoding`, CryptorErrorReason.MissingKey),\n );\n }\n }\n\n /**\n * Function that will be injected in a stream and will decrypt the given encoded frames.\n *\n * @param {RTCEncodedVideoFrame|RTCEncodedAudioFrame} encodedFrame - Encoded video frame.\n * @param {TransformStreamDefaultController} controller - TransportStreamController.\n */\n protected async decodeFunction(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n controller: TransformStreamDefaultController,\n ) {\n if (\n !this.isEnabled() ||\n // skip for decryption for empty dtx frames\n encodedFrame.data.byteLength === 0\n ) {\n workerLogger.debug('skipping empty frame', this.logContext);\n this.sifGuard.recordUserFrame();\n return controller.enqueue(encodedFrame);\n }\n\n if (isFrameServerInjected(encodedFrame.data, this.sifTrailer)) {\n workerLogger.debug('enqueue SIF', this.logContext);\n this.sifGuard.recordSif();\n\n if (this.sifGuard.isSifAllowed()) {\n encodedFrame.data = encodedFrame.data.slice(\n 0,\n encodedFrame.data.byteLength - this.sifTrailer.byteLength,\n );\n return controller.enqueue(encodedFrame);\n } else {\n workerLogger.warn('SIF limit reached, dropping frame');\n return;\n }\n } else {\n this.sifGuard.recordUserFrame();\n }\n const data = new Uint8Array(encodedFrame.data);\n const keyIndex = data[encodedFrame.data.byteLength - 1];\n\n if (this.keys.getKeySet(keyIndex) && this.keys.hasValidKey) {\n try {\n const decodedFrame = await this.decryptFrame(encodedFrame, keyIndex);\n this.keys.decryptionSuccess();\n if (decodedFrame) {\n return controller.enqueue(decodedFrame);\n }\n } catch (error) {\n if (error instanceof CryptorError && error.reason === CryptorErrorReason.InvalidKey) {\n if (this.keys.hasValidKey) {\n this.emit(CryptorEvent.Error, error);\n this.keys.decryptionFailure();\n }\n } else {\n workerLogger.warn('decoding frame failed', { error });\n }\n }\n } else if (!this.keys.getKeySet(keyIndex) && this.keys.hasValidKey) {\n // emit an error in case the key index is out of bounds but the key handler thinks we still have a valid key\n workerLogger.warn(`skipping decryption due to missing key at index ${keyIndex}`);\n this.emit(\n CryptorEvent.Error,\n new CryptorError(\n `missing key at index ${keyIndex} for participant ${this.participantIdentity}`,\n CryptorErrorReason.MissingKey,\n ),\n );\n }\n }\n\n /**\n * Function that will decrypt the given encoded frame. If the decryption fails, it will\n * ratchet the key for up to RATCHET_WINDOW_SIZE times.\n */\n private async decryptFrame(\n encodedFrame: RTCEncodedVideoFrame | RTCEncodedAudioFrame,\n keyIndex: number,\n initialMaterial: KeySet | undefined = undefined,\n ratchetOpts: DecodeRatchetOptions = { ratchetCount: 0 },\n ): Promise<RTCEncodedVideoFrame | RTCEncodedAudioFrame | undefined> {\n const keySet = this.keys.getKeySet(keyIndex);\n if (!ratchetOpts.encryptionKey && !keySet) {\n throw new TypeError(`no encryption key found for decryption of ${this.participantIdentity}`);\n }\n let frameInfo = this.getUnencryptedBytes(encodedFrame);\n\n // Construct frame trailer. Similar to the frame header described in\n // https://tools.ietf.org/html/draft-omara-sframe-00#section-4.2\n // but we put it at the end.\n //\n // ---------+-------------------------+-+---------+----\n // payload |IV...(length = IV_LENGTH)|R|IV_LENGTH|KID |\n // ---------+-------------------------+-+---------+----\n\n try {\n const frameHeader = new Uint8Array(encodedFrame.data, 0, frameInfo.unencryptedBytes);\n var encryptedData = new Uint8Array(\n encodedFrame.data,\n frameHeader.length,\n encodedFrame.data.byteLength - frameHeader.length,\n );\n if (frameInfo.isH264 && needsRbspUnescaping(encryptedData)) {\n encryptedData = parseRbsp(encryptedData);\n const newUint8 = new Uint8Array(frameHeader.byteLength + encryptedData.byteLength);\n newUint8.set(frameHeader);\n newUint8.set(encryptedData, frameHeader.byteLength);\n encodedFrame.data = newUint8.buffer;\n }\n\n const frameTrailer = new Uint8Array(encodedFrame.data, encodedFrame.data.byteLength - 2, 2);\n\n const ivLength = frameTrailer[0];\n const iv = new Uint8Array(\n encodedFrame.data,\n encodedFrame.data.byteLength - ivLength - frameTrailer.byteLength,\n ivLength,\n );\n\n const cipherTextStart = frameHeader.byteLength;\n const cipherTextLength =\n encodedFrame.data.byteLength -\n (frameHeader.byteLength + ivLength + frameTrailer.byteLength);\n\n const plainText = await crypto.subtle.decrypt(\n {\n name: ENCRYPTION_ALGORITHM,\n iv,\n additionalData: new Uint8Array(encodedFrame.data, 0, frameHeader.byteLength),\n },\n ratchetOpts.encryptionKey ?? keySet!.encryptionKey,\n new Uint8Array(encodedFrame.data, cipherTextStart, cipherTextLength),\n );\n\n const newData = new ArrayBuffer(frameHeader.byteLength + plainText.byteLength);\n const newUint8 = new Uint8Array(newData);\n\n newUint8.set(new Uint8Array(encodedFrame.data, 0, frameHeader.byteLength));\n newUint8.set(new Uint8Array(plainText), frameHeader.byteLength);\n\n encodedFrame.data = newData;\n\n return encodedFrame;\n } catch (error: any) {\n if (this.keyProviderOptions.ratchetWindowSize > 0) {\n if (ratchetOpts.ratchetCount < this.keyProviderOptions.ratchetWindowSize) {\n workerLogger.debug(\n `ratcheting key attempt ${ratchetOpts.ratchetCount} of ${\n this.keyProviderOptions.ratchetWindowSize\n }, for kind ${encodedFrame instanceof RTCEncodedAudioFrame ? 'audio' : 'video'}`,\n );\n\n let ratchetedKeySet: KeySet | undefined;\n if ((initialMaterial ?? keySet) === this.keys.getKeySet(keyIndex)) {\n // only ratchet if the currently set key is still the same as the one used to decrypt this frame\n // if not, it might be that a different frame has already ratcheted and we try with that one first\n const newMaterial = await this.keys.ratchetKey(keyIndex, false);\n\n ratchetedKeySet = await deriveKeys(newMaterial, this.keyProviderOptions.ratchetSalt);\n }\n\n const frame = await this.decryptFrame(encodedFrame, keyIndex, initialMaterial || keySet, {\n ratchetCount: ratchetOpts.ratchetCount + 1,\n encryptionKey: ratchetedKeySet?.encryptionKey,\n });\n if (frame && ratchetedKeySet) {\n // before updating the keys, make sure that the keySet used for this frame is still the same as the currently set key\n // if it's not, a new key might have been set already, which we don't want to override\n if ((initialMaterial ?? keySet) === this.keys.getKeySet(keyIndex)) {\n this.keys.setKeySet(ratchetedKeySet, keyIndex, true);\n // decryption was successful, set the new key index to reflect the ratcheted key set\n this.keys.setCurrentKeyIndex(keyIndex);\n }\n }\n return frame;\n } else {\n /**\n * Because we only set a new key once decryption has been successful,\n * we can be sure that we don't need to reset the key to the initial material at this point\n * as the key has not been updated on the keyHandler instance\n */\n\n workerLogger.warn('maximum ratchet attempts exceeded');\n throw new CryptorError(\n `valid key missing for participant ${this.participantIdentity}`,\n CryptorErrorReason.InvalidKey,\n );\n }\n } else {\n throw new CryptorError(\n `Decryption failed: ${error.message}`,\n CryptorErrorReason.InvalidKey,\n );\n }\n }\n }\n\n /**\n * Construct the IV used for AES-GCM and sent (in plain) with the packet similar to\n * https://tools.ietf.org/html/rfc7714#section-8.1\n * It concatenates\n * - the 32 bit synchronization source (SSRC) given on the encoded frame,\n * - the 32 bit rtp timestamp given on the encoded frame,\n * - a send counter that is specific to the SSRC. Starts at a random number.\n * The send counter is essentially the pictureId but we currently have to implement this ourselves.\n * There is no XOR with a salt. Note that this IV leaks the SSRC to the receiver but since this is\n * randomly generated and SFUs may not rewrite this is considered acceptable.\n * The SSRC is used to allow demultiplexing multiple streams with the same key, as described in\n * https://tools.ietf.org/html/rfc3711#section-4.1.1\n * The RTP timestamp is 32 bits and advances by the codec clock rate (90khz for video, 48khz for\n * opus audio) every second. For video it rolls over roughly every 13 hours.\n * The send counter will advance at the frame rate (30fps for video, 50fps for 20ms opus audio)\n * every second. It will take a long time to roll over.\n *\n * See also https://developer.mozilla.org/en-US/docs/Web/API/AesGcmParams\n */\n private makeIV(synchronizationSource: number, timestamp: number) {\n const iv = new ArrayBuffer(IV_LENGTH);\n const ivView = new DataView(iv);\n\n // having to keep our own send count (similar to a picture id) is not ideal.\n if (!this.sendCounts.has(synchronizationSource)) {\n // Initialize with a random offset, similar to the RTP sequence number.\n this.sendCounts.set(synchronizationSource, Math.floor(Math.random() * 0xffff));\n }\n\n const sendCount = this.sendCounts.get(synchronizationSource) ?? 0;\n\n ivView.setUint32(0, synchronizationSource);\n ivView.setUint32(4, timestamp);\n ivView.setUint32(8, timestamp - (sendCount % 0xffff));\n\n this.sendCounts.set(synchronizationSource, sendCount + 1);\n\n return iv;\n }\n\n private getUnencryptedBytes(frame: RTCEncodedVideoFrame | RTCEncodedAudioFrame): {\n unencryptedBytes: number;\n isH264: boolean;\n } {\n var frameInfo = { unencryptedBytes: 0, isH264: false };\n if (isVideoFrame(frame)) {\n let detectedCodec = this.getVideoCodec(frame) ?? this.videoCodec;\n if (detectedCodec !== this.detectedCodec) {\n workerLogger.debug('detected different codec', {\n detectedCodec,\n oldCodec: this.detectedCodec,\n ...this.logContext,\n });\n this.detectedCodec = detectedCodec;\n }\n\n if (detectedCodec === 'av1' || detectedCodec === 'vp9') {\n throw new Error(`${detectedCodec} is not yet supported for end to end encryption`);\n }\n\n if (detectedCodec === 'vp8') {\n frameInfo.unencryptedBytes = UNENCRYPTED_BYTES[frame.type];\n return frameInfo;\n }\n\n const data = new Uint8Array(frame.data);\n try {\n const naluIndices = findNALUIndices(data);\n\n // if the detected codec is undefined we test whether it _looks_ like a h264 frame as a best guess\n frameInfo.isH264 =\n detectedCodec === 'h264' ||\n naluIndices.some((naluIndex) =>\n [NALUType.SLICE_IDR, NALUType.SLICE_NON_IDR].includes(parseNALUType(data[naluIndex])),\n );\n\n if (frameInfo.isH264) {\n for (const index of naluIndices) {\n let type = parseNALUType(data[index]);\n switch (type) {\n case NALUType.SLICE_IDR:\n case NALUType.SLICE_NON_IDR:\n frameInfo.unencryptedBytes = index + 2;\n return frameInfo;\n default:\n break;\n }\n }\n throw new TypeError('Could not find NALU');\n }\n } catch (e) {\n // no op, we just continue and fallback to vp8\n }\n\n frameInfo.unencryptedBytes = UNENCRYPTED_BYTES[frame.type];\n return frameInfo;\n } else {\n frameInfo.unencryptedBytes = UNENCRYPTED_BYTES.audio;\n return frameInfo;\n }\n }\n\n /**\n * inspects frame payloadtype if available and maps it to the codec specified in rtpMap\n */\n private getVideoCodec(frame: RTCEncodedVideoFrame): VideoCodec | undefined {\n if (this.rtpMap.size === 0) {\n return undefined;\n }\n // @ts-expect-error payloadType is not yet part of the typescript definition and currently not supported in Safari\n const payloadType = frame.getMetadata().payloadType;\n const codec = payloadType ? this.rtpMap.get(payloadType) : undefined;\n return codec;\n }\n}\n\n/**\n * Slice the NALUs present in the supplied buffer, assuming it is already byte-aligned\n * code adapted from https://github.com/medooze/h264-frame-parser/blob/main/lib/NalUnits.ts to return indices only\n */\nexport function findNALUIndices(stream: Uint8Array): number[] {\n const result: number[] = [];\n let start = 0,\n pos = 0,\n searchLength = stream.length - 2;\n while (pos < searchLength) {\n // skip until end of current NALU\n while (\n pos < searchLength &&\n !(stream[pos] === 0 && stream[pos + 1] === 0 && stream[pos + 2] === 1)\n )\n pos++;\n if (pos >= searchLength) pos = stream.length;\n // remove trailing zeros from current NALU\n let end = pos;\n while (end > start && stream[end - 1] === 0) end--;\n // save current NALU\n if (start === 0) {\n if (end !== start) throw TypeError('byte stream contains leading data');\n } else {\n result.push(start);\n }\n // begin new NALU\n start = pos = pos + 3;\n }\n return result;\n}\n\nexport function parseNALUType(startByte: number): NALUType {\n return startByte & kNaluTypeMask;\n}\n\nconst kNaluTypeMask = 0x1f;\n\nexport enum NALUType {\n /** Coded slice of a non-IDR picture */\n SLICE_NON_IDR = 1,\n /** Coded slice data partition A */\n SLICE_PARTITION_A = 2,\n /** Coded slice data partition B */\n SLICE_PARTITION_B = 3,\n /** Coded slice data partition C */\n SLICE_PARTITION_C = 4,\n /** Coded slice of an IDR picture */\n SLICE_IDR = 5,\n /** Supplemental enhancement information */\n SEI = 6,\n /** Sequence parameter set */\n SPS = 7,\n /** Picture parameter set */\n PPS = 8,\n /** Access unit delimiter */\n AUD = 9,\n /** End of sequence */\n END_SEQ = 10,\n /** End of stream */\n END_STREAM = 11,\n /** Filler data */\n FILLER_DATA = 12,\n /** Sequence parameter set extension */\n SPS_EXT = 13,\n /** Prefix NAL unit */\n PREFIX_NALU = 14,\n /** Subset sequence parameter set */\n SUBSET_SPS = 15,\n /** Depth parameter set */\n DPS = 16,\n\n // 17, 18 reserved\n\n /** Coded slice of an auxiliary coded picture without partitioning */\n SLICE_AUX = 19,\n /** Coded slice extension */\n SLICE_EXT = 20,\n /** Coded slice extension for a depth view component or a 3D-AVC texture view component */\n SLICE_LAYER_EXT = 21,\n\n // 22, 23 reserved\n}\n\n/**\n * we use a magic frame trailer to detect whether a frame is injected\n * by the livekit server and thus to be treated as unencrypted\n * @internal\n */\nexport function isFrameServerInjected(frameData: ArrayBuffer, trailerBytes: Uint8Array): boolean {\n if (trailerBytes.byteLength === 0) {\n return false;\n }\n const frameTrailer = new Uint8Array(\n frameData.slice(frameData.byteLength - trailerBytes.byteLength),\n );\n return trailerBytes.every((value, index) => value === frameTrailer[index]);\n}\n","import { EventEmitter } from 'events';\nimport type TypedEventEmitter from 'typed-emitter';\nimport { workerLogger } from '../../logger';\nimport { KEYRING_SIZE } from '../constants';\nimport { KeyHandlerEvent, type ParticipantKeyHandlerCallbacks } from '../events';\nimport type { KeyProviderOptions, KeySet } from '../types';\nimport { deriveKeys, importKey, ratchet } from '../utils';\n\n// TODO ParticipantKeyHandlers currently don't get destroyed on participant disconnect\n// we could do this by having a separate worker message on participant disconnected.\n\n/**\n * ParticipantKeyHandler is responsible for providing a cryptor instance with the\n * en-/decryption key of a participant. It assumes that all tracks of a specific participant\n * are encrypted with the same key.\n * Additionally it exposes a method to ratchet a key which can be used by the cryptor either automatically\n * if decryption fails or can be triggered manually on both sender and receiver side.\n *\n */\nexport class ParticipantKeyHandler extends (EventEmitter as new () => TypedEventEmitter<ParticipantKeyHandlerCallbacks>) {\n private currentKeyIndex: number;\n\n private cryptoKeyRing: Array<KeySet | undefined>;\n\n private keyProviderOptions: KeyProviderOptions;\n\n private ratchetPromiseMap: Map<number, Promise<CryptoKey>>;\n\n private participantIdentity: string;\n\n private decryptionFailureCount = 0;\n\n private _hasValidKey: boolean = true;\n\n get hasValidKey() {\n return this._hasValidKey;\n }\n\n constructor(participantIdentity: string, keyProviderOptions: KeyProviderOptions) {\n super();\n this.currentKeyIndex = 0;\n this.cryptoKeyRing = new Array(KEYRING_SIZE).fill(undefined);\n this.keyProviderOptions = keyProviderOptions;\n this.ratchetPromiseMap = new Map();\n this.participantIdentity = participantIdentity;\n this.resetKeyStatus();\n }\n\n decryptionFailure() {\n if (this.keyProviderOptions.failureTolerance < 0) {\n return;\n }\n this.decryptionFailureCount += 1;\n\n if (this.decryptionFailureCount > this.keyProviderOptions.failureTolerance) {\n workerLogger.warn(`key for ${this.participantIdentity} is being marked as invalid`);\n this._hasValidKey = false;\n }\n }\n\n decryptionSuccess() {\n this.resetKeyStatus();\n }\n\n /**\n * Call this after user initiated ratchet or a new key has been set in order to make sure to mark potentially\n * invalid keys as valid again\n */\n resetKeyStatus() {\n this.decryptionFailureCount = 0;\n this._hasValidKey = true;\n }\n\n /**\n * Ratchets the current key (or the one at keyIndex if provided) and\n * returns the ratcheted material\n * if `setKey` is true (default), it will also set the ratcheted key directly on the crypto key ring\n * @param keyIndex\n * @param setKey\n */\n ratchetKey(keyIndex?: number, setKey = true): Promise<CryptoKey> {\n const currentKeyIndex = keyIndex ?? this.getCurrentKeyIndex();\n\n const existingPromise = this.ratchetPromiseMap.get(currentKeyIndex);\n if (typeof existingPromise !== 'undefined') {\n return existingPromise;\n }\n const ratchetPromise = new Promise<CryptoKey>(async (resolve, reject) => {\n try {\n const keySet = this.getKeySet(currentKeyIndex);\n if (!keySet) {\n throw new TypeError(\n `Cannot ratchet key without a valid keyset of participant ${this.participantIdentity}`,\n );\n }\n const currentMaterial = keySet.material;\n const newMaterial = await importKey(\n await ratchet(currentMaterial, this.keyProviderOptions.ratchetSalt),\n currentMaterial.algorithm.name,\n 'derive',\n );\n\n if (setKey) {\n this.setKeyFromMaterial(newMaterial, currentKeyIndex, true);\n this.emit(\n KeyHandlerEvent.KeyRatcheted,\n newMaterial,\n this.participantIdentity,\n currentKeyIndex,\n );\n }\n resolve(newMaterial);\n } catch (e) {\n reject(e);\n } finally {\n this.ratchetPromiseMap.delete(currentKeyIndex);\n }\n });\n this.ratchetPromiseMap.set(currentKeyIndex, ratchetPromise);\n return ratchetPromise;\n }\n\n /**\n * takes in a key material with `deriveBits` and `deriveKey` set as key usages\n * and derives encryption keys from the material and sets it on the key ring buffer\n * together with the material\n * also resets the valid key property and updates the currentKeyIndex\n */\n async setKey(material: CryptoKey, keyIndex = 0) {\n await this.setKeyFromMaterial(material, keyIndex);\n this.resetKeyStatus();\n }\n\n /**\n * takes in a key material with `deriveBits` and `deriveKey` set as key usages\n * and derives encryption keys from the material and sets it on the key ring buffers\n * together with the material\n * also updates the currentKeyIndex\n */\n async setKeyFromMaterial(material: CryptoKey, keyIndex: number, emitRatchetEvent = false) {\n const keySet = await deriveKeys(material, this.keyProviderOptions.ratchetSalt);\n const newIndex = keyIndex >= 0 ? keyIndex % this.cryptoKeyRing.length : this.currentKeyIndex;\n workerLogger.debug(`setting new key with index ${keyIndex}`, {\n usage: material.usages,\n algorithm: material.algorithm,\n ratchetSalt: this.keyProviderOptions.ratchetSalt,\n });\n this.setKeySet(keySet, newIndex, emitRatchetEvent);\n if (newIndex >= 0) this.currentKeyIndex = newIndex;\n }\n\n setKeySet(keySet: KeySet, keyIndex: number, emitRatchetEvent = false) {\n this.cryptoKeyRing[keyIndex % this.cryptoKeyRing.length] = keySet;\n\n if (emitRatchetEvent) {\n this.emit(KeyHandlerEvent.KeyRatcheted, keySet.material, this.participantIdentity, keyIndex);\n }\n }\n\n async setCurrentKeyIndex(index: number) {\n this.currentKeyIndex = index % this.cryptoKeyRing.length;\n this.resetKeyStatus();\n }\n\n getCurrentKeyIndex() {\n return this.currentKeyIndex;\n }\n\n /**\n * returns currently used KeySet or the one at `keyIndex` if provided\n * @param keyIndex\n * @returns\n */\n getKeySet(keyIndex?: number) {\n return this.cryptoKeyRing[keyIndex ?? this.currentKeyIndex];\n }\n}\n","import { workerLogger } from '../../logger';\nimport { KEY_PROVIDER_DEFAULTS } from '../constants';\nimport { CryptorErrorReason } from '../errors';\nimport { CryptorEvent, KeyHandlerEvent } from '../events';\nimport type {\n E2EEWorkerMessage,\n ErrorMessage,\n InitAck,\n KeyProviderOptions,\n RatchetMessage,\n RatchetRequestMessage,\n} from '../types';\nimport { FrameCryptor, encryptionEnabledMap } from './FrameCryptor';\nimport { ParticipantKeyHandler } from './ParticipantKeyHandler';\n\nconst participantCryptors: FrameCryptor[] = [];\nconst participantKeys: Map<string, ParticipantKeyHandler> = new Map();\nlet sharedKeyHandler: ParticipantKeyHandler | undefined;\n\nlet isEncryptionEnabled: boolean = false;\n\nlet useSharedKey: boolean = false;\n\nlet sifTrailer: Uint8Array | undefined;\n\nlet keyProviderOptions: KeyProviderOptions = KEY_PROVIDER_DEFAULTS;\n\nworkerLogger.setDefaultLevel('info');\n\nonmessage = (ev) => {\n const { kind, data }: E2EEWorkerMessage = ev.data;\n\n switch (kind) {\n case 'init':\n workerLogger.setLevel(data.loglevel);\n workerLogger.info('worker initialized');\n keyProviderOptions = data.keyProviderOptions;\n useSharedKey = !!data.keyProviderOptions.sharedKey;\n // acknowledge init successful\n const ackMsg: InitAck = {\n kind: 'initAck',\n data: { enabled: isEncryptionEnabled },\n };\n postMessage(ackMsg);\n break;\n case 'enable':\n setEncryptionEnabled(data.enabled, data.participantIdentity);\n workerLogger.info('updated e2ee enabled status');\n // acknowledge enable call successful\n postMessage(ev.data);\n break;\n case 'decode':\n let cryptor = getTrackCryptor(data.participantIdentity, data.trackId);\n cryptor.setupTransform(\n kind,\n data.readableStream,\n data.writableStream,\n data.trackId,\n data.codec,\n );\n break;\n case 'encode':\n let pubCryptor = getTrackCryptor(data.participantIdentity, data.trackId);\n pubCryptor.setupTransform(\n kind,\n data.readableStream,\n data.writableStream,\n data.trackId,\n data.codec,\n );\n break;\n case 'setKey':\n if (useSharedKey) {\n setSharedKey(data.key, data.keyIndex);\n } else if (data.participantIdentity) {\n workerLogger.info(\n `set participant sender key ${data.participantIdentity} index ${data.keyIndex}`,\n );\n getParticipantKeyHandler(data.participantIdentity).setKey(data.key, data.keyIndex);\n } else {\n workerLogger.error('no participant Id was provided and shared key usage is disabled');\n }\n break;\n case 'removeTransform':\n unsetCryptorParticipant(data.trackId, data.participantIdentity);\n break;\n case 'updateCodec':\n getTrackCryptor(data.participantIdentity, data.trackId).setVideoCodec(data.codec);\n break;\n case 'setRTPMap':\n // this is only used for the local participant\n participantCryptors.forEach((cr) => {\n if (cr.getParticipantIdentity() === data.participantIdentity) {\n cr.setRtpMap(data.map);\n }\n });\n break;\n case 'ratchetRequest':\n handleRatchetRequest(data);\n break;\n case 'setSifTrailer':\n handleSifTrailer(data.trailer);\n break;\n default:\n break;\n }\n};\n\nasync function handleRatchetRequest(data: RatchetRequestMessage['data']) {\n if (useSharedKey) {\n const keyHandler = getSharedKeyHandler();\n await keyHandler.ratchetKey(data.keyIndex);\n keyHandler.resetKeyStatus();\n } else if (data.participantIdentity) {\n const keyHandler = getParticipantKeyHandler(data.participantIdentity);\n await keyHandler.ratchetKey(data.keyIndex);\n keyHandler.resetKeyStatus();\n } else {\n workerLogger.error(\n 'no participant Id was provided for ratchet request and shared key usage is disabled',\n );\n }\n}\n\nfunction getTrackCryptor(participantIdentity: string, trackId: string) {\n let cryptor = participantCryptors.find((c) => c.getTrackId() === trackId);\n if (!cryptor) {\n workerLogger.info('creating new cryptor for', { participantIdentity });\n if (!keyProviderOptions) {\n throw Error('Missing keyProvider options');\n }\n cryptor = new FrameCryptor({\n participantIdentity,\n keys: getParticipantKeyHandler(participantIdentity),\n keyProviderOptions,\n sifTrailer,\n });\n\n setupCryptorErrorEvents(cryptor);\n participantCryptors.push(cryptor);\n } else if (participantIdentity !== cryptor.getParticipantIdentity()) {\n // assign new participant id to track cryptor and pass in correct key handler\n cryptor.setParticipant(participantIdentity, getParticipantKeyHandler(participantIdentity));\n }\n\n return cryptor;\n}\n\nfunction getParticipantKeyHandler(participantIdentity: string) {\n if (useSharedKey) {\n return getSharedKeyHandler();\n }\n let keys = participantKeys.get(participantIdentity);\n if (!keys) {\n keys = new ParticipantKeyHandler(participantIdentity, keyProviderOptions);\n keys.on(KeyHandlerEvent.KeyRatcheted, emitRatchetedKeys);\n participantKeys.set(participantIdentity, keys);\n }\n return keys;\n}\n\nfunction getSharedKeyHandler() {\n if (!sharedKeyHandler) {\n workerLogger.debug('creating new shared key handler');\n sharedKeyHandler = new ParticipantKeyHandler('shared-key', keyProviderOptions);\n }\n return sharedKeyHandler;\n}\n\nfunction unsetCryptorParticipant(trackId: string, participantIdentity: string) {\n const cryptor = participantCryptors.find(\n (c) => c.getParticipantIdentity() === participantIdentity && c.getTrackId() === trackId,\n );\n if (!cryptor) {\n workerLogger.warn('Could not unset participant on cryptor', { trackId, participantIdentity });\n } else {\n cryptor.unsetParticipant();\n }\n}\n\nfunction setEncryptionEnabled(enable: boolean, participantIdentity: string) {\n workerLogger.debug(`setting encryption enabled for all tracks of ${participantIdentity}`, {\n enable,\n });\n encryptionEnabledMap.set(participantIdentity, enable);\n}\n\nfunction setSharedKey(key: CryptoKey, index?: number) {\n workerLogger.info('set shared key', { index });\n getSharedKeyHandler().setKey(key, index);\n}\n\nfunction setupCryptorErrorEvents(cryptor: FrameCryptor) {\n cryptor.on(CryptorEvent.Error, (error) => {\n const msg: ErrorMessage = {\n kind: 'error',\n data: { error: new Error(`${CryptorErrorReason[error.reason]}: ${error.message}`) },\n };\n postMessage(msg);\n });\n}\n\nfunction emitRatchetedKeys(material: CryptoKey, participantIdentity: string, keyIndex?: number) {\n const msg: RatchetMessage = {\n kind: `ratchetKey`,\n data: {\n participantIdentity,\n keyIndex,\n material,\n },\n };\n postMessage(msg);\n}\n\nfunction handleSifTrailer(trailer: Uint8Array) {\n sifTrailer = trailer;\n participantCryptors.forEach((c) => {\n c.setSifTrailer(trailer);\n });\n}\n\n// Operations using RTCRtpScriptTransform.\n// @ts-ignore\nif (self.RTCTransformEvent) {\n workerLogger.debug('setup transform event');\n // @ts-ignore\n self.onrtctransform = (event) => {\n const transformer = event.transformer;\n workerLogger.debug('transformer', transformer);\n transformer.handled = true;\n const { kind, participantIdentity, trackId, codec } = transformer.options;\n const cryptor = getTrackCryptor(participantIdentity, trackId);\n workerLogger.debug('transform', { codec });\n cryptor.setupTransform(kind, transformer.readable, transformer.writable, trackId, codec);\n };\n}\n"],"names":["root","definition","module","exports","log","this","noop","undefinedType","isIE","window","navigator","test","userAgent","logMethods","bindMethod","obj","methodName","method","bind","Function","prototype","call","e","apply","arguments","traceForIE","console","trace","realMethod","undefined","replaceLoggingMethods","level","loggerName","i","length","methodFactory","debug","enableLoggingWhenConsoleArrives","defaultMethodFactory","Logger","name","defaultLevel","factory","self","currentLevel","storageKey","persistLevelIfPossible","levelNum","levelName","toUpperCase","localStorage","ignore","document","cookie","encodeURIComponent","getPersistedLevel","storedLevel","location","indexOf","exec","slice","levels","clearPersistedLevel","removeItem","getLevel","setLevel","persist","SILENT","setDefaultLevel","resetLevel","enableAll","TRACE","disableAll","initialLevel","defaultLogger","_loggersByName","getLogger","TypeError","logger","_log","noConflict","getLoggers","LogLevel","LoggerNames","livekitLogger","Object","values","map","info","workerLogger","ENCRYPTION_ALGORITHM","KEYRING_SIZE","DECRYPTION_FAILURE_TOLERANCE","UNENCRYPTED_BYTES","key","delta","audio","empty","IV_LENGTH","SALT","KEY_PROVIDER_DEFAULTS","sharedKey","ratchetSalt","ratchetWindowSize","failureTolerance","MAX_SIF_COUNT","MAX_SIF_DURATION","LivekitError","Error","constructor","code","message","MediaDeviceFailure","getFailure","error","NotFound","PermissionDenied","DeviceInUse","Other","CryptorErrorReason","CryptorError","reason","InternalError","KeyProviderEvent","KeyHandlerEvent","EncryptionEvent","CryptorEvent","R","Reflect","ReflectApply","target","receiver","args","ReflectOwnKeys","ownKeys","getOwnPropertySymbols","getOwnPropertyNames","concat","ProcessEmitWarning","warning","warn","NumberIsNaN","Number","isNaN","value","EventEmitter","init","eventsModule","once","_events","_eventsCount","_maxListeners","defaultMaxListeners","checkListener","listener","defineProperty","enumerable","get","set","arg","RangeError","getPrototypeOf","create","setMaxListeners","n","_getMaxListeners","that","getMaxListeners","emit","type","push","doError","events","er","err","context","handler","len","listeners","arrayClone","_addListener","prepend","m","existing","newListener","unshift","warned","w","String","emitter","count","addListener","on","prependListener","onceWrapper","fired","removeListener","wrapFn","_onceWrap","state","wrapped","prependOnceListener","list","position","originalListener","shift","spliceOne","off","removeAllListeners","keys","_listeners","unwrap","evlistener","unwrapListeners","rawListeners","listenerCount","eventNames","arr","copy","Array","index","pop","ret","Promise","resolve","reject","errorListener","resolver","eventTargetAgnosticAddListener","addErrorHandlerIfEventEmitter","flags","addEventListener","wrapListener","removeEventListener","isVideoFrame","frame","importKey","keyBytes","algorithm","usage","crypto","subtle","getAlgoOptions","algorithmName","salt","textEncoder","TextEncoder","encodedSalt","encode","hash","ArrayBuffer","iterations","deriveKeys","material","algorithmOptions","encryptionKey","deriveKey","ratchet","deriveBits","needsRbspUnescaping","frameData","parseRbsp","stream","dataOut","Uint8Array","kZerosInStartSequence","kEmulationByte","writeRbsp","data_in","numConsecutiveZeros","byte","SifGuard","consecutiveSifCount","lastSifReceivedAt","userFramesSinceSif","recordSif","_a","sifSequenceStartedAt","Date","now","recordUserFrame","reset","isSifAllowed","encryptionEnabledMap","Map","BaseFrameCryptor","encodeFunction","encodedFrame","controller","decodeFunction","FrameCryptor","opts","sendCounts","participantIdentity","rtpMap","keyProviderOptions","sifTrailer","from","sifGuard","logContext","participant","mediaTrackId","trackId","fallbackCodec","videoCodec","setParticipant","id","unsetParticipant","isEnabled","getParticipantIdentity","getTrackId","setVideoCodec","codec","setRtpMap","setupTransform","operation","readable","writable","assign","passedTrackId","transformFn","transformStream","TransformStream","transform","pipeThrough","pipeTo","catch","setSifTrailer","trailer","data","byteLength","enqueue","keySet","getKeySet","getCurrentKeyIndex","keyIndex","iv","makeIV","getMetadata","synchronizationSource","timestamp","frameInfo","getUnencryptedBytes","frameHeader","unencryptedBytes","frameTrailer","cipherText","encrypt","additionalData","newDataWithoutHeader","isH264","newData","buffer","MissingKey","isFrameServerInjected","hasValidKey","decodedFrame","decryptFrame","decryptionSuccess","InvalidKey","decryptionFailure","initialMaterial","ratchetOpts","ratchetCount","encryptedData","newUint8","ivLength","cipherTextStart","cipherTextLength","plainText","decrypt","RTCEncodedAudioFrame","ratchetedKeySet","newMaterial","ratchetKey","setKeySet","setCurrentKeyIndex","ivView","DataView","has","Math","floor","random","sendCount","setUint32","detectedCodec","getVideoCodec","oldCodec","naluIndices","findNALUIndices","some","naluIndex","NALUType","SLICE_IDR","SLICE_NON_IDR","includes","parseNALUType","size","payloadType","result","start","pos","searchLength","end","startByte","kNaluTypeMask","trailerBytes","every","ParticipantKeyHandler","_hasValidKey","decryptionFailureCount","currentKeyIndex","cryptoKeyRing","fill","ratchetPromiseMap","resetKeyStatus","setKey","existingPromise","ratchetPromise","__awaiter","currentMaterial","setKeyFromMaterial","KeyRatcheted","delete","emitRatchetEvent","newIndex","usages","participantCryptors","participantKeys","sharedKeyHandler","isEncryptionEnabled","useSharedKey","onmessage","ev","kind","loglevel","ackMsg","enabled","postMessage","setEncryptionEnabled","cryptor","getTrackCryptor","readableStream","writableStream","pubCryptor","setSharedKey","getParticipantKeyHandler","unsetCryptorParticipant","forEach","cr","handleRatchetRequest","handleSifTrailer","keyHandler","getSharedKeyHandler","find","c","setupCryptorErrorEvents","emitRatchetedKeys","enable","msg","RTCTransformEvent","onrtctransform","event","transformer","handled","options"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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