livekit-client 2.16.0 → 2.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -1
- package/dist/livekit-client.e2ee.worker.js +1 -1
- package/dist/livekit-client.e2ee.worker.js.map +1 -1
- package/dist/livekit-client.e2ee.worker.mjs +1 -0
- package/dist/livekit-client.e2ee.worker.mjs.map +1 -1
- package/dist/livekit-client.esm.mjs +1079 -1329
- package/dist/livekit-client.esm.mjs.map +1 -1
- package/dist/livekit-client.umd.js +1 -1
- package/dist/livekit-client.umd.js.map +1 -1
- package/dist/src/api/SignalClient.d.ts.map +1 -1
- package/dist/src/api/utils.d.ts +1 -0
- package/dist/src/api/utils.d.ts.map +1 -1
- package/dist/src/connectionHelper/checks/turn.d.ts.map +1 -1
- package/dist/src/connectionHelper/checks/websocket.d.ts.map +1 -1
- package/dist/src/room/PCTransportManager.d.ts.map +1 -1
- package/dist/src/room/RTCEngine.d.ts +5 -0
- package/dist/src/room/RTCEngine.d.ts.map +1 -1
- package/dist/src/room/RegionUrlProvider.d.ts.map +1 -1
- package/dist/src/room/Room.d.ts +1 -1
- package/dist/src/room/Room.d.ts.map +1 -1
- package/dist/src/room/data-stream/outgoing/OutgoingDataStreamManager.d.ts +0 -1
- package/dist/src/room/data-stream/outgoing/OutgoingDataStreamManager.d.ts.map +1 -1
- package/dist/src/room/errors.d.ts +74 -5
- package/dist/src/room/errors.d.ts.map +1 -1
- package/dist/src/room/token-source/TokenSource.d.ts +10 -2
- package/dist/src/room/token-source/TokenSource.d.ts.map +1 -1
- package/dist/src/room/track/LocalTrack.d.ts +0 -4
- package/dist/src/room/track/LocalTrack.d.ts.map +1 -1
- package/dist/src/room/track/TrackPublication.d.ts.map +1 -1
- package/dist/src/room/track/processor/types.d.ts +0 -6
- package/dist/src/room/track/processor/types.d.ts.map +1 -1
- package/dist/src/room/utils.d.ts +1 -1
- package/dist/src/room/utils.d.ts.map +1 -1
- package/dist/src/test/mocks.d.ts.map +1 -1
- package/dist/ts4.2/api/utils.d.ts +1 -0
- package/dist/ts4.2/room/RTCEngine.d.ts +5 -0
- package/dist/ts4.2/room/Room.d.ts +1 -1
- package/dist/ts4.2/room/data-stream/outgoing/OutgoingDataStreamManager.d.ts +0 -1
- package/dist/ts4.2/room/errors.d.ts +74 -5
- package/dist/ts4.2/room/token-source/TokenSource.d.ts +1 -1
- package/dist/ts4.2/room/track/LocalTrack.d.ts +0 -4
- package/dist/ts4.2/room/track/processor/types.d.ts +0 -6
- package/package.json +10 -6
- package/src/api/SignalClient.test.ts +12 -19
- package/src/api/SignalClient.ts +13 -28
- package/src/api/utils.ts +1 -1
- package/src/connectionHelper/checks/turn.ts +7 -0
- package/src/connectionHelper/checks/websocket.ts +40 -11
- package/src/room/PCTransport.ts +1 -1
- package/src/room/PCTransportManager.ts +4 -19
- package/src/room/RTCEngine.ts +56 -18
- package/src/room/RegionUrlProvider.test.ts +8 -9
- package/src/room/RegionUrlProvider.ts +13 -12
- package/src/room/Room.ts +14 -16
- package/src/room/data-stream/outgoing/OutgoingDataStreamManager.ts +0 -1
- package/src/room/errors.ts +144 -16
- package/src/room/participant/LocalParticipant.ts +1 -1
- package/src/room/token-source/TokenSource.ts +5 -1
- package/src/room/track/LocalTrack.ts +0 -4
- package/src/room/track/TrackPublication.ts +1 -1
- package/src/room/track/processor/types.ts +0 -6
- package/src/room/utils.ts +2 -1
- package/src/test/mocks.ts +0 -1
package/README.md
CHANGED
|
@@ -95,6 +95,13 @@ const room = new Room({
|
|
|
95
95
|
},
|
|
96
96
|
});
|
|
97
97
|
|
|
98
|
+
// get your url from livekit's dashboard, or point it at a self hosted livekit deployment
|
|
99
|
+
const url = "ws://localhost:7800";
|
|
100
|
+
|
|
101
|
+
// generate a token by making a request to a endpoint using the livekit server sdk or
|
|
102
|
+
// using a prebuilt TokenSource (documented below)
|
|
103
|
+
const token = "...";
|
|
104
|
+
|
|
98
105
|
// pre-warm connection, this can be called as early as your page is loaded
|
|
99
106
|
room.prepareConnection(url, token);
|
|
100
107
|
|
|
@@ -107,7 +114,7 @@ room
|
|
|
107
114
|
.on(RoomEvent.LocalTrackUnpublished, handleLocalTrackUnpublished);
|
|
108
115
|
|
|
109
116
|
// connect to room
|
|
110
|
-
await room.connect(
|
|
117
|
+
await room.connect(url, token);
|
|
111
118
|
console.log('connected to room', room.name);
|
|
112
119
|
|
|
113
120
|
// publish local camera and mic tracks
|
|
@@ -304,6 +311,103 @@ setLogExtension((level: LogLevel, msg: string, context: object) => {
|
|
|
304
311
|
});
|
|
305
312
|
```
|
|
306
313
|
|
|
314
|
+
### Generating a url/token with `TokenSource`
|
|
315
|
+
|
|
316
|
+
A TokenSource is a pre-implemented way of fetching credentials. Once a `TokenSource` is constructed, call
|
|
317
|
+
`fetch` to generate a new set of credentials.
|
|
318
|
+
|
|
319
|
+
There are two types of `TokenSource`'s - fixed and configurable. Configurable token sources can be
|
|
320
|
+
passed options as part of the generation process, allowing you to customize the token that they
|
|
321
|
+
generate. Fixed token sources generate static credentials and don't accept parameters that can
|
|
322
|
+
effect the generated token.
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
// Fixed token sources don't take any parameters as part of `fetch`:
|
|
326
|
+
const fixed: TokenSourceFixed = /* ... */;
|
|
327
|
+
const fixedResponse = await fixed.fetch();
|
|
328
|
+
room.connect(fixedResponse.serverUrl, fixedResponse.participantToken);
|
|
329
|
+
|
|
330
|
+
// Configurable token sources can optionally take parameters to change what is encoded into the token:
|
|
331
|
+
const configurable: TokenSourceConfigurable = /* ... */;
|
|
332
|
+
const configurableResponse = await configurable.fetch({ agentName: "agent to dispatch" } /* <-- here */);
|
|
333
|
+
room.connect(configurableResponse.serverUrl, configurableResponse.participantToken);
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
|Mechanism: | using pre-generated credentials | via a http request to a url | via fully custom logic |
|
|
337
|
+
|-------------|--|--|--|
|
|
338
|
+
|Fixed | [`TokenSource.literal`](#tokensourceliteral) | — | [`TokenSource.literal(async () => { /* ... */ })`](#tokensourceliteral) |
|
|
339
|
+
|Configurable | — | [`TokenSource.endpoint`](#tokensourceendpoint) or [`TokenSource.sandboxTokenServer`](#tokensourceendpoint) | [`TokenSource.custom`](#tokensourcecustom) |
|
|
340
|
+
|
|
341
|
+
#### TokenSource.Literal
|
|
342
|
+
A fixed token source which returns a static set of credentials or a computed set of credentials
|
|
343
|
+
with no external input required on each call.
|
|
344
|
+
|
|
345
|
+
Example:
|
|
346
|
+
```ts
|
|
347
|
+
const literal1 = TokenSource.literal({ serverUrl: "ws://localhost:7800", participantToken: "..." });
|
|
348
|
+
await literal1.fetch() // { serverUrl: "ws://localhost:7800", participantToken: "..." }
|
|
349
|
+
|
|
350
|
+
const literal2 = TokenSource.literal(async () => ({ serverUrl: "ws://localhost:7800", participantToken: "..." }));
|
|
351
|
+
await literal2.fetch() // { serverUrl: "ws://localhost:7800", participantToken: "..." }
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
#### TokenSource.Endpoint
|
|
355
|
+
A configurable token source which makes a request to an endpoint to generate credentials. By
|
|
356
|
+
default, a `POST` request with a `Content-Type: application/json` header is made, and the request
|
|
357
|
+
body is expected to follow the [standard token format](https://cloud.livekit.io/projects/p_/sandbox/templates/token-server). If
|
|
358
|
+
credentials generation is successful, the endpoint returns a 2xx status code with a body following
|
|
359
|
+
the [standard token response format](https://cloud.livekit.io/projects/p_/sandbox/templates/token-server).
|
|
360
|
+
|
|
361
|
+
Example:
|
|
362
|
+
```ts
|
|
363
|
+
const endpoint1 = TokenSource.endpoint("http://example.com/credentials-endpoint");
|
|
364
|
+
await endpoint1.fetch({ agentName: "agent to dispatch" }) // { serverUrl: "...", participantToken: "... token encoding agentName ..." }
|
|
365
|
+
|
|
366
|
+
const endpoint2 = TokenSource.endpoint("http://example.com/credentials-endpoint", {
|
|
367
|
+
// For all supported options below, see https://developer.mozilla.org/en-US/docs/Web/API/RequestInit
|
|
368
|
+
method: "PUT",
|
|
369
|
+
headers: {
|
|
370
|
+
"X-Custom-Header": "custom header value",
|
|
371
|
+
},
|
|
372
|
+
});
|
|
373
|
+
await endpoint2.fetch({ agentName: "agent to dispatch" }) // { serverUrl: "...", participantToken: "... token encoding agentName ..." }
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
#### TokenSource.SandboxTokenServer
|
|
377
|
+
A configurable token source which makes a request to a
|
|
378
|
+
[sandbox token server endpoint](https://cloud.livekit.io/projects/p_/sandbox/templates/token-server),
|
|
379
|
+
a LiveKit-hosted token generation mechanism.
|
|
380
|
+
|
|
381
|
+
This token generation mechanism is inherently insecure and should only be used for
|
|
382
|
+
prototyping; do NOT use in production.
|
|
383
|
+
|
|
384
|
+
One parameter is required - the sandbox id from the dashboard. This is the `token-server-xxxxxx`
|
|
385
|
+
value in `https://token-server-xxxxxx.sandbox.livekit.io`.
|
|
386
|
+
|
|
387
|
+
Example:
|
|
388
|
+
```ts
|
|
389
|
+
const sandbox = TokenSource.sandboxTokenServer("token-server-xxxxxx");
|
|
390
|
+
await sandbox.fetch({ agentName: "agent to dispatch" }); // { serverUrl: "...", participantToken: "... token encoding agentName ..." }
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
#### TokenSource.Custom
|
|
394
|
+
A fully custom configurable token source that allows you to consume any end application-specific
|
|
395
|
+
token generation mechanism. Tokens that are generated are cached and used until they expire or the
|
|
396
|
+
options passed into `fetch` change.
|
|
397
|
+
|
|
398
|
+
Note that it is expected that all options passed into `fetch` will always be encoded into the
|
|
399
|
+
output token. If you'd rather implement a fixed version of this TokenSource, see
|
|
400
|
+
`TokenSource.literal(async () => { /* ... */ })`.
|
|
401
|
+
|
|
402
|
+
Example:
|
|
403
|
+
```ts
|
|
404
|
+
const sandbox = TokenSource.custom(async (options) => {
|
|
405
|
+
// generate token info via custom means here
|
|
406
|
+
return { serverUrl: "...", participantToken: "... options encoded in here ..." };
|
|
407
|
+
});
|
|
408
|
+
await sandbox.fetch({ agentName: "agent to dispatch" });
|
|
409
|
+
```
|
|
410
|
+
|
|
307
411
|
### RPC
|
|
308
412
|
|
|
309
413
|
Perform your own predefined method calls from one participant to another.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,o,a,s,c=(t||(t=1,i=n.exports,o=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},o=null;function a(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),i=0;i<r.length;i++){var o=r[i];this[o]=i<n?e:this.methodFactory(o,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function u(r,i,o){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?a(console,r):void 0!==console.log?a(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var a,s,d,l=this,y="loglevel";function p(){var e;if(typeof window!==t&&y){try{e=window.localStorage[y]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(y),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function h(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?y+=":"+e:"symbol"==typeof e&&(y=void 0),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:a},l.setLevel=function(e,n){return d=h(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&y){try{return void(window.localStorage[y]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){s=h(e),p()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==t&&y){try{window.localStorage.removeItem(y)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(o!==l&&(a=h(o.getLevel())),c.call(l),o===l)for(var e in i)i[e].rebuild()},a=h(o?o.getLevel():"WARN");var f=p();null!=f&&(d=h(f)),c.call(l)}(o=new l).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=i[e];return t||(t=i[e]=new l(e,o.methodFactory)),t};var y=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return i},o.default=o,o},(r=n).exports?r.exports=o():i.log=o()),n.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(a||(a={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(s||(s={}));let d=c.getLogger("livekit");Object.values(s).map((e=>c.getLogger(e))),d.setDefaultLevel(a.info);const u=c.getLogger("lk-e2ee");var l,y=Object.defineProperty,p=(e,t,n)=>((e,t,n)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class h{constructor(){p(this,"_locking"),p(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(l||(l={}));const f="AES-GCM",g={key:10,delta:3,audio:1,empty:0},v={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};class m extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var I,w,b,L,_,k,E,S;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout"}(I||(I={})),function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(w||(w={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(b||(b={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(b||(b={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(L||(L={}));class A extends m{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:L.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}function T(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function R(t,n){return e(this,void 0,void 0,(function*(){const e=T(t.algorithm.name,n),r=yield crypto.subtle.deriveKey(e,t,{name:f,length:128},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(_||(_={})),function(e){e.KeyRatcheted="keyRatcheted"}(k||(k={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(E||(E={})),function(e){e.Error="cryptorError"}(S||(S={}));class C{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-C.sendCount%65535),C.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=C.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:f,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){const a=yield n.getKeySet(r);if(!a)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:f,iv:t},a.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(s){if(n.keyProviderOptions.ratchetWindowSize>0){if(o.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let s,c;u.debug("DataCryptor: ratcheting key attempt ".concat(o.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:a)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),s=yield R(c.cryptoKey,n.keyProviderOptions.ratchetSalt));const d=yield C.decrypt(e,t,n,r,i,{ratchetCount:o.ratchetCount+1,encryptionKey:null==s?void 0:s.encryptionKey});return d&&s&&(null!=i?i:a)===n.getKeySet(r)&&(n.setKeySet(s,r,c),n.setCurrentKeyIndex(r)),d}throw u.warn("DataCryptor: maximum ratchet attempts exceeded"),new A("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),L.InvalidKey,n.participantIdentity)}throw new A("DataCryptor: Decryption failed: ".concat(s.message),L.InvalidKey,n.participantIdentity)}}()}))}}C.sendCount=0;var P,N={exports:{}};var K=function(){if(P)return N.exports;P=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}N.exports=i,N.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}h(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&h(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,c,d;if(a(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),c=o[t]),void 0===c)c=o[t]=n,++e._eventsCount;else if("function"==typeof c?c=o[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):p(i,i.length)}function y(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){r.once&&e.removeEventListener(t,i),n(o)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=p(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return a(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,o,s;if(a(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):y.call(e,t)},i.prototype.listenerCount=y,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},N.exports}();const U=31;var x,O;function D(e){return e&U}function M(e){return e>>1&63}function F(e){return e===x.SLICE_IDR||e===x.SLICE_NON_IDR}function B(e){return e===O.TRAIL_N||e===O.TRAIL_R||e===O.TSA_N||e===O.TSA_R||e===O.STSA_N||e===O.STSA_R||e===O.RADL_N||e===O.RADL_R||e===O.RASL_N||e===O.RASL_R||e===O.BLA_W_LP||e===O.BLA_W_RADL||e===O.BLA_N_LP||e===O.IDR_W_RADL||e===O.IDR_N_LP||e===O.CRA_NUT}function j(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let o=r;for(;o>n&&0===e[o-1];)o--;if(0===n){if(o!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let a=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(a=4),n=r+=a}return t}(e),r=null!=t?t:function(e,t){for(const n of t){if(F(D(e[n])))return"h264";if(B(M(e[n])))return"h265"}return"unknown"}(e,n);if("unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(B(M(e[r])))return r+2}else if(F(D(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(x||(x={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(O||(O={}));const W="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",q="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",X="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",z="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",V="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function H(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case W:return"vp8";case q:case X:case z:return"h264";case V:return"opus";default:return null}}))}const G=new Map;class Y extends K.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class Q extends Y{constructor(e){var t;super(),this.isTransformActive=!1,this.lastErrorTimestamp=new Map,this.errorCounts=new Map,this.ERROR_THROTTLE_MS=1e3,this.MAX_ERRORS_PER_MINUTE=5,this.ERROR_WINDOW_MS=6e4,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){u.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{participant:e})),this.participantIdentity&&u.error("cryptor has already a participant set, participant should have been unset before",Object.assign({},this.logContext)),this.participantIdentity=e,this.keys=t}unsetParticipant(){u.debug("unsetting participant",this.logContext),this.participantIdentity=void 0,this.lastErrorTimestamp=new Map,this.errorCounts=new Map}isEnabled(){return this.participantIdentity?G.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,r,i,o){if(o&&(u.info("setting codec on cryptor to",{codec:o}),this.videoCodec=o),u.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:o},this.logContext)),i&&this.isTransformActive)return void u.debug("reuse transform",Object.assign({},this.logContext));const a="encode"===e?this.encodeFunction:this.decodeFunction,s=new TransformStream({transform:a.bind(this)});this.isTransformActive=!0,t.pipeThrough(s).pipeTo(n).catch((e=>{u.warn(e),this.emit(S.Error,e instanceof A?e:new A(e.message,void 0,this.participantIdentity))})).finally((()=>{this.isTransformActive=!1})),this.trackId=r}setSifTrailer(e){u.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}shouldEmitError(e){var t,n;const r=Date.now(),i=null!==(t=this.lastErrorTimestamp.get(e))&&void 0!==t?t:0,o=null!==(n=this.errorCounts.get(e))&&void 0!==n?n:0;return r-i>this.ERROR_WINDOW_MS?(this.errorCounts.set(e,0),this.lastErrorTimestamp.set(e,r),!0):!(r-i<this.ERROR_THROTTLE_MS)&&(o>=this.MAX_ERRORS_PER_MINUTE?(o===this.MAX_ERRORS_PER_MINUTE&&(u.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:e})),this.errorCounts.set(e,o+1)),!1):(this.lastErrorTimestamp.set(e,r),this.errorCounts.set(e,o+1),!0))}emitThrottledError(e){var t;const n="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(this.shouldEmitError(n)){const r=null!==(t=this.errorCounts.get(n))&&void 0!==t?t:0;r>1&&u.debug("Decryption error (".concat(r," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:L[e.reason]})),this.emit(S.Error,e)}}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emitThrottledError(new A("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),L.MissingKey,this.participantIdentity));const{encryptionKey:i}=r,o=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let s=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,s.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=o;try{const e=yield crypto.subtle.encrypt({name:f,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,s.unencryptedBytes));let o=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);o.set(new Uint8Array(e)),o.set(new Uint8Array(r),e.byteLength),o.set(d,e.byteLength+r.byteLength),s.requiresNALUProcessing&&(o=function(e){const t=[];for(var n=0,r=0;r<e.length;++r){var i=e[r];i<=3&&n>=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(o));var a=new Uint8Array(c.byteLength+o.byteLength);return a.set(c),a.set(o,c.byteLength),t.data=a.buffer,n.enqueue(t)}catch(e){u.error(e)}}else u.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new A("encryption key missing for encoding",L.MissingKey,this.participantIdentity))}))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield H(t.data))?(u.debug("enqueue SIF",this.logContext),n.enqueue(t)):void u.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const e=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(e))if(this.keys.getKeySet(e))try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(e),r)return n.enqueue(r)}catch(t){t instanceof A&&t.reason===L.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(t),this.keys.decryptionFailure(e)):u.warn("decoding frame failed",{error:t})}else u.warn("skipping decryption due to missing key at index ".concat(e)),this.emitThrottledError(new A("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),L.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(e)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var o;const a=n.keys.getKeySet(t);if(!i.encryptionKey&&!a)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=function(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),y=yield crypto.subtle.decrypt({name:f,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(o=i.encryptionKey)&&void 0!==o?o:a.encryptionKey,new Uint8Array(e.data,u,l)),p=new ArrayBuffer(t.byteLength+y.byteLength),h=new Uint8Array(p);return h.set(new Uint8Array(e.data,0,t.byteLength)),h.set(new Uint8Array(y),t.byteLength),e.data=p,e}catch(o){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let o,s;u.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:a)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),o=yield R(s.cryptoKey,n.keyProviderOptions.ratchetSalt));const c=yield n.decryptFrame(e,t,r||a,{ratchetCount:i.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return c&&o&&(null!=r?r:a)===n.keys.getKeySet(t)&&(n.keys.setKeySet(o,t,s),n.keys.setCurrentKeyIndex(t)),c}throw u.warn("maximum ratchet attempts exceeded"),new A("valid key missing for participant ".concat(n.participantIdentity),L.InvalidKey,n.participantIdentity)}throw new A("Decryption failed: ".concat(o.message),L.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const o=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-o%65535),this.sendCounts.set(e,o+1),r}getUnencryptedBytes(e){var t;if(!function(e){return"type"in e}(e))return{unencryptedBytes:g.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(u.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};try{const t="h264"===n||"h265"===n?n:void 0,r=j(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(e){u.debug("NALU processing failed, falling back to VP8 handling",Object.assign({error:e},this.logContext))}return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1}}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}}class J extends K.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&u.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const o=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const o=i.material,a=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=T(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(o,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:f},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(a,o.algorithm.name,"derive"),c={chainKey:a,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,o),o}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return function*(){yield t.setKeyFromMaterial(e,n),t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return function*(){const i=yield R(e,n.keyProviderOptions.ratchetSalt),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;u.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(i,o,r),o>=0&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(k.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const Z=[],$=new Map;let ee,te,ne=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new h,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:l.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=l.RUNNING,yield t()}finally{e.status=l.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},re=!1,ie=v,oe=new Map;function ae(e,t){let n=Z.filter((e=>e.getTrackId()===t));if(n.length>1){const r=n.map((e=>({participant:e.getParticipantIdentity()}))).join(",");u.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:r})}let r=n[0];if(r)e!==r.getParticipantIdentity()&&r.setParticipant(e,se(e));else{if(u.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!ie)throw Error("Missing keyProvider options");r=new Q({participantIdentity:e,keys:se(e),keyProviderOptions:ie,sifTrailer:te}),r.setRtpMap(oe),function(e){e.on(S.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(L[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(r),Z.push(r)}return r}function se(e){if(re)return ce();let t=$.get(e);return t||(t=new J(e,ie),t.on(k.KeyRatcheted,de),$.set(e,t)),t}function ce(){return ee||(u.debug("creating new shared key handler"),ee=new J("shared-key",ie)),ee}function de(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}u.setDefaultLevel("info"),onmessage=t=>{ne.run((()=>e(void 0,void 0,void 0,(function*(){const{kind:n,data:r}=t.data;switch(n){case"init":u.setLevel(r.loglevel),u.info("worker initialized"),ie=r.keyProviderOptions,re=!!r.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":o=r.enabled,a=r.participantIdentity,u.debug("setting encryption enabled for all tracks of ".concat(a),{enable:o}),G.set(a,o),u.info("updated e2ee enabled status for ".concat(r.participantIdentity," to ").concat(r.enabled)),postMessage(t.data);break;case"decode":ae(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"encode":ae(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"encryptDataRequest":const{payload:s,iv:c,keyIndex:d}=yield C.encrypt(r.payload,se(r.participantIdentity));console.log("encrypted payload",{original:r.payload,encrypted:s,iv:c}),postMessage({kind:"encryptDataResponse",data:{payload:s,iv:c,keyIndex:d,uuid:r.uuid}});break;case"decryptDataRequest":try{const{payload:e}=yield C.decrypt(r.payload,r.iv,se(r.participantIdentity),r.keyIndex);postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:r.uuid}})}catch(e){u.error("DataCryptor decryption failed",{error:e,participantIdentity:r.participantIdentity,uuid:r.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:r.uuid}})}break;case"setKey":re?yield function(t,n){return e(this,void 0,void 0,(function*(){u.info("set shared key",{index:n}),yield ce().setKey(t,n)}))}(r.key,r.keyIndex):r.participantIdentity?(u.info("set participant sender key ".concat(r.participantIdentity," index ").concat(r.keyIndex)),yield se(r.participantIdentity).setKey(r.key,r.keyIndex)):u.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=Z.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&u.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():u.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(r.trackId,r.participantIdentity);break;case"updateCodec":ae(r.participantIdentity,r.trackId).setVideoCodec(r.codec),u.info("updated codec",{participantIdentity:r.participantIdentity,trackId:r.trackId,codec:r.codec});break;case"setRTPMap":oe=r.map,Z.forEach((e=>{e.getParticipantIdentity()===r.participantIdentity&&e.setRtpMap(r.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(re){const e=ce();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=se(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else u.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(r);break;case"setSifTrailer":i=r.trailer,te=i,Z.forEach((e=>{e.setSifTrailer(i)}))}var i,o,a}))))},self.RTCTransformEvent&&(u.debug("setup transform event"),self.onrtctransform=e=>{const t=e.transformer;u.debug("transformer",t);const{kind:n,participantIdentity:r,trackId:i,codec:o}=t.options,a=ae(r,i);u.debug("transform",{codec:o}),a.setupTransform(n,t.readable,t.writable,i,!1,o)})}));
|
|
1
|
+
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,s)}c((r=r.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var t,n={exports:{}};var r,i,o,a,s,c=(t||(t=1,i=n.exports,o=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"],i={},o=null;function a(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(){for(var n=this.getLevel(),i=0;i<r.length;i++){var o=r[i];this[o]=i<n?e:this.methodFactory(o,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return"No console available for logging"}function d(e){return function(){typeof console!==t&&(c.call(this),this[e].apply(this,arguments))}}function u(r,i,o){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?a(console,r):void 0!==console.log?a(console,"log"):e)}(r)||d.apply(this,arguments)}function l(e,n){var a,s,d,l=this,y="loglevel";function p(){var e;if(typeof window!==t&&y){try{e=window.localStorage[y]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(y),i=n.indexOf(r+"=");-1!==i&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch(e){}return void 0===l.levels[e]&&(e=void 0),e}}function h(e){var t=e;if("string"==typeof t&&void 0!==l.levels[t.toUpperCase()]&&(t=l.levels[t.toUpperCase()]),"number"==typeof t&&t>=0&&t<=l.levels.SILENT)return t;throw new TypeError("log.setLevel() called with invalid level: "+e)}"string"==typeof e?y+=":"+e:"symbol"==typeof e&&(y=void 0),l.name=e,l.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},l.methodFactory=n||u,l.getLevel=function(){return null!=d?d:null!=s?s:a},l.setLevel=function(e,n){return d=h(e),!1!==n&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&y){try{return void(window.localStorage[y]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"="+n+";"}catch(e){}}}(d),c.call(l)},l.setDefaultLevel=function(e){s=h(e),p()||l.setLevel(e,!1)},l.resetLevel=function(){d=null,function(){if(typeof window!==t&&y){try{window.localStorage.removeItem(y)}catch(e){}try{window.document.cookie=encodeURIComponent(y)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}(),c.call(l)},l.enableAll=function(e){l.setLevel(l.levels.TRACE,e)},l.disableAll=function(e){l.setLevel(l.levels.SILENT,e)},l.rebuild=function(){if(o!==l&&(a=h(o.getLevel())),c.call(l),o===l)for(var e in i)i[e].rebuild()},a=h(o?o.getLevel():"WARN");var f=p();null!=f&&(d=h(f)),c.call(l)}(o=new l).getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=i[e];return t||(t=i[e]=new l(e,o.methodFactory)),t};var y=typeof window!==t?window.log:void 0;return o.noConflict=function(){return typeof window!==t&&window.log===o&&(window.log=y),o},o.getLoggers=function(){return i},o.default=o,o},(r=n).exports?r.exports=o():i.log=o()),n.exports);!function(e){e[e.trace=0]="trace",e[e.debug=1]="debug",e[e.info=2]="info",e[e.warn=3]="warn",e[e.error=4]="error",e[e.silent=5]="silent"}(a||(a={})),function(e){e.Default="livekit",e.Room="livekit-room",e.TokenSource="livekit-token-source",e.Participant="livekit-participant",e.Track="livekit-track",e.Publication="livekit-track-publication",e.Engine="livekit-engine",e.Signal="livekit-signal",e.PCManager="livekit-pc-manager",e.PCTransport="livekit-pc-transport",e.E2EE="lk-e2ee"}(s||(s={}));let d=c.getLogger("livekit");Object.values(s).map((e=>c.getLogger(e))),d.setDefaultLevel(a.info);const u=c.getLogger("lk-e2ee");var l,y=Object.defineProperty,p=(e,t,n)=>((e,t,n)=>t in e?y(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n)(e,"symbol"!=typeof t?t+"":t,n);class h{constructor(){p(this,"_locking"),p(this,"_locks"),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){let e;this._locks+=1;const t=new Promise((t=>e=()=>{this._locks-=1,t()})),n=this._locking.then((()=>e));return this._locking=this._locking.then((()=>t)),n}}!function(e){e[e.WAITING=0]="WAITING",e[e.RUNNING=1]="RUNNING",e[e.COMPLETED=2]="COMPLETED"}(l||(l={}));const f="AES-GCM",g={key:10,delta:3,audio:1,empty:0},v={sharedKey:!1,ratchetSalt:"LKFrameEncryptionKey",ratchetWindowSize:8,failureTolerance:10,keyringSize:16};class m extends Error{constructor(e,t){super(t||"an error has occured"),this.name="LiveKitError",this.code=e}}var I,w,b,L,k,_,E,S;!function(e){e[e.NotAllowed=0]="NotAllowed",e[e.ServerUnreachable=1]="ServerUnreachable",e[e.InternalError=2]="InternalError",e[e.Cancelled=3]="Cancelled",e[e.LeaveRequest=4]="LeaveRequest",e[e.Timeout=5]="Timeout",e[e.WebSocket=6]="WebSocket"}(I||(I={})),function(e){e[e.AlreadyOpened=0]="AlreadyOpened",e[e.AbnormalEnd=1]="AbnormalEnd",e[e.DecodeFailed=2]="DecodeFailed",e[e.LengthExceeded=3]="LengthExceeded",e[e.Incomplete=4]="Incomplete",e[e.HandlerAlreadyRegistered=7]="HandlerAlreadyRegistered",e[e.EncryptionTypeMismatch=8]="EncryptionTypeMismatch"}(w||(w={})),function(e){e.PermissionDenied="PermissionDenied",e.NotFound="NotFound",e.DeviceInUse="DeviceInUse",e.Other="Other"}(b||(b={})),function(e){e.getFailure=function(t){if(t&&"name"in t)return"NotFoundError"===t.name||"DevicesNotFoundError"===t.name?e.NotFound:"NotAllowedError"===t.name||"PermissionDeniedError"===t.name?e.PermissionDenied:"NotReadableError"===t.name||"TrackStartError"===t.name?e.DeviceInUse:e.Other}}(b||(b={})),function(e){e[e.InvalidKey=0]="InvalidKey",e[e.MissingKey=1]="MissingKey",e[e.InternalError=2]="InternalError"}(L||(L={}));class A extends m{constructor(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:L.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}}function T(e,t){const n=(new TextEncoder).encode(t);switch(e){case"HKDF":return{name:"HKDF",salt:n,hash:"SHA-256",info:new ArrayBuffer(128)};case"PBKDF2":return{name:"PBKDF2",salt:n,hash:"SHA-256",iterations:1e5};default:throw new Error("algorithm ".concat(e," is currently unsupported"))}}function R(t,n){return e(this,void 0,void 0,(function*(){const e=T(t.algorithm.name,n),r=yield crypto.subtle.deriveKey(e,t,{name:f,length:128},!1,["encrypt","decrypt"]);return{material:t,encryptionKey:r}}))}!function(e){e.SetKey="setKey",e.RatchetRequest="ratchetRequest",e.KeyRatcheted="keyRatcheted"}(k||(k={})),function(e){e.KeyRatcheted="keyRatcheted"}(_||(_={})),function(e){e.ParticipantEncryptionStatusChanged="participantEncryptionStatusChanged",e.EncryptionError="encryptionError"}(E||(E={})),function(e){e.Error="cryptorError"}(S||(S={}));class C{static makeIV(e){const t=new ArrayBuffer(12),n=new DataView(t),r=crypto.getRandomValues(new Uint32Array(1));return n.setUint32(0,r[0]),n.setUint32(4,e),n.setUint32(8,e-C.sendCount%65535),C.sendCount++,t}static encrypt(t,n){return e(this,void 0,void 0,(function*(){const e=C.makeIV(performance.now()),r=yield n.getKeySet();if(!r)throw new Error("No key set found");const i=yield crypto.subtle.encrypt({name:f,iv:e},r.encryptionKey,new Uint8Array(t));return{payload:new Uint8Array(i),iv:new Uint8Array(e),keyIndex:n.getCurrentKeyIndex()}}))}static decrypt(t,n,r){return e(this,arguments,void 0,(function(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=arguments.length>4?arguments[4]:void 0,o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{ratchetCount:0};return function*(){const a=yield n.getKeySet(r);if(!a)throw new Error("No key set found");try{const n=yield crypto.subtle.decrypt({name:f,iv:t},a.encryptionKey,new Uint8Array(e));return{payload:new Uint8Array(n)}}catch(s){if(n.keyProviderOptions.ratchetWindowSize>0){if(o.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let s,c;u.debug("DataCryptor: ratcheting key attempt ".concat(o.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for data packet")),(null!=i?i:a)===n.getKeySet(r)&&(c=yield n.ratchetKey(r,!1),s=yield R(c.cryptoKey,n.keyProviderOptions.ratchetSalt));const d=yield C.decrypt(e,t,n,r,i,{ratchetCount:o.ratchetCount+1,encryptionKey:null==s?void 0:s.encryptionKey});return d&&s&&(null!=i?i:a)===n.getKeySet(r)&&(n.setKeySet(s,r,c),n.setCurrentKeyIndex(r)),d}throw u.warn("DataCryptor: maximum ratchet attempts exceeded"),new A("DataCryptor: valid key missing for participant ".concat(n.participantIdentity),L.InvalidKey,n.participantIdentity)}throw new A("DataCryptor: Decryption failed: ".concat(s.message),L.InvalidKey,n.participantIdentity)}}()}))}}C.sendCount=0;var P,N={exports:{}};var K=function(){if(P)return N.exports;P=1;var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var r=Number.isNaN||function(e){return e!=e};function i(){i.init.call(this)}N.exports=i,N.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,o),r(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}h(e,t,o,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&h(e,"error",t,n)}(e,i,{once:!0})}))},i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function s(e){return void 0===e._maxListeners?i.defaultMaxListeners:e._maxListeners}function c(e,t,n,r){var i,o,c,d;if(a(n),void 0===(o=e._events)?(o=e._events=Object.create(null),e._eventsCount=0):(void 0!==o.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),o=e._events),c=o[t]),void 0===c)c=o[t]=n,++e._eventsCount;else if("function"==typeof c?c=o[t]=r?[n,c]:[c,n]:r?c.unshift(n):c.push(n),(i=s(e))>0&&c.length>i&&!c.warned){c.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+c.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=c.length,d=u,console&&console.warn&&console.warn(d)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function l(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):p(i,i.length)}function y(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(o){r.once&&e.removeEventListener(t,i),n(o)}))}}return Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),i.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},i.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||r(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},i.prototype.getMaxListeners=function(){return s(this)},i.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var a;if(t.length>0&&(a=t[0]),a instanceof Error)throw a;var s=new Error("Unhandled error."+(a?" ("+a.message+")":""));throw s.context=a,s}var c=o[e];if(void 0===c)return!1;if("function"==typeof c)n(c,this,t);else{var d=c.length,u=p(c,d);for(r=0;r<d;++r)n(u[r],this,t)}return!0},i.prototype.addListener=function(e,t){return c(this,e,t,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(e,t){return c(this,e,t,!0)},i.prototype.once=function(e,t){return a(t),this.on(e,u(this,e,t)),this},i.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,u(this,e,t)),this},i.prototype.removeListener=function(e,t){var n,r,i,o,s;if(a(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},i.prototype.listeners=function(e){return l(this,e,!0)},i.prototype.rawListeners=function(e){return l(this,e,!1)},i.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):y.call(e,t)},i.prototype.listenerCount=y,i.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]},N.exports}();const U=31;var x,O;function D(e){return e&U}function M(e){return e>>1&63}function F(e){return e===x.SLICE_IDR||e===x.SLICE_NON_IDR}function B(e){return e===O.TRAIL_N||e===O.TRAIL_R||e===O.TSA_N||e===O.TSA_R||e===O.STSA_N||e===O.STSA_R||e===O.RADL_N||e===O.RADL_R||e===O.RASL_N||e===O.RASL_R||e===O.BLA_W_LP||e===O.BLA_W_RADL||e===O.BLA_N_LP||e===O.IDR_W_RADL||e===O.IDR_N_LP||e===O.CRA_NUT}function j(e,t){const n=function(e){const t=[];let n=0,r=0,i=e.length-3;for(;r<i;){for(;r<i&&!(r<i-1&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3])&&(0!==e[r]||0!==e[r+1]||1!==e[r+2]);)r++;r>=i&&(r=e.length);let o=r;for(;o>n&&0===e[o-1];)o--;if(0===n){if(o!==n)throw TypeError("byte stream contains leading data")}else t.push(n);let a=3;r<e.length-3&&0===e[r]&&0===e[r+1]&&0===e[r+2]&&1===e[r+3]&&(a=4),n=r+=a}return t}(e),r=null!=t?t:function(e,t){for(const n of t){if(F(D(e[n])))return"h264";if(B(M(e[n])))return"h265"}return"unknown"}(e,n);if("unknown"===r)return{unencryptedBytes:0,detectedCodec:r,requiresNALUProcessing:!1};const i=function(e,t,n){for(const r of t)if("h265"===n){if(B(M(e[r])))return r+2}else if(F(D(e[r])))return r+2;return null}(e,n,r);if(null===i)throw new TypeError("Could not find NALU");return{unencryptedBytes:i,detectedCodec:r,requiresNALUProcessing:!0}}!function(e){e[e.SLICE_NON_IDR=1]="SLICE_NON_IDR",e[e.SLICE_PARTITION_A=2]="SLICE_PARTITION_A",e[e.SLICE_PARTITION_B=3]="SLICE_PARTITION_B",e[e.SLICE_PARTITION_C=4]="SLICE_PARTITION_C",e[e.SLICE_IDR=5]="SLICE_IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.END_SEQ=10]="END_SEQ",e[e.END_STREAM=11]="END_STREAM",e[e.FILLER_DATA=12]="FILLER_DATA",e[e.SPS_EXT=13]="SPS_EXT",e[e.PREFIX_NALU=14]="PREFIX_NALU",e[e.SUBSET_SPS=15]="SUBSET_SPS",e[e.DPS=16]="DPS",e[e.SLICE_AUX=19]="SLICE_AUX",e[e.SLICE_EXT=20]="SLICE_EXT",e[e.SLICE_LAYER_EXT=21]="SLICE_LAYER_EXT"}(x||(x={})),function(e){e[e.TRAIL_N=0]="TRAIL_N",e[e.TRAIL_R=1]="TRAIL_R",e[e.TSA_N=2]="TSA_N",e[e.TSA_R=3]="TSA_R",e[e.STSA_N=4]="STSA_N",e[e.STSA_R=5]="STSA_R",e[e.RADL_N=6]="RADL_N",e[e.RADL_R=7]="RADL_R",e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.BLA_W_RADL=17]="BLA_W_RADL",e[e.BLA_N_LP=18]="BLA_N_LP",e[e.IDR_W_RADL=19]="IDR_W_RADL",e[e.IDR_N_LP=20]="IDR_N_LP",e[e.CRA_NUT=21]="CRA_NUT",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.EOS_NUT=36]="EOS_NUT",e[e.EOB_NUT=37]="EOB_NUT",e[e.FD_NUT=38]="FD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(O||(O={}));const W="ef0161653d8b2b23aad46624b420af1d03ce48950e9fc85718028f91b50f9219",q="f0a0e09647d891d6d50aa898bce7108090375d0d55e50a2bb21147afee558e44",X="61d9665eed71b6d424ae9539330a3bdd5cb386d4d781c808219a6e36750493a7",z="faffc26b68a2fc09096fa20f3351e706398b6f838a7500c8063472c2e476e90d",V="aad8d31fc56b2802ca500e58c2fb9d0b29ad71bb7cb52cd6530251eade188988";function H(t){return e(this,void 0,void 0,(function*(){const n=yield function(t){return e(this,void 0,void 0,(function*(){const e=yield crypto.subtle.digest("SHA-256",t),n=new Uint8Array(e);return Array.from(n).map((e=>e.toString(16).padStart(2,"0"))).join("")}))}(t);switch(n){case W:return"vp8";case q:case X:case z:return"h264";case V:return"opus";default:return null}}))}const G=new Map;class Y extends K.EventEmitter{encodeFunction(e,t){throw Error("not implemented for subclass")}decodeFunction(e,t){throw Error("not implemented for subclass")}}class Q extends Y{constructor(e){var t;super(),this.isTransformActive=!1,this.lastErrorTimestamp=new Map,this.errorCounts=new Map,this.ERROR_THROTTLE_MS=1e3,this.MAX_ERRORS_PER_MINUTE=5,this.ERROR_WINDOW_MS=6e4,this.sendCounts=new Map,this.keys=e.keys,this.participantIdentity=e.participantIdentity,this.rtpMap=new Map,this.keyProviderOptions=e.keyProviderOptions,this.sifTrailer=null!==(t=e.sifTrailer)&&void 0!==t?t:Uint8Array.from([])}get logContext(){return{participant:this.participantIdentity,mediaTrackId:this.trackId,fallbackCodec:this.videoCodec}}setParticipant(e,t){u.debug("setting new participant on cryptor",Object.assign(Object.assign({},this.logContext),{participant:e})),this.participantIdentity&&u.error("cryptor has already a participant set, participant should have been unset before",Object.assign({},this.logContext)),this.participantIdentity=e,this.keys=t}unsetParticipant(){u.debug("unsetting participant",this.logContext),this.participantIdentity=void 0,this.lastErrorTimestamp=new Map,this.errorCounts=new Map}isEnabled(){return this.participantIdentity?G.get(this.participantIdentity):void 0}getParticipantIdentity(){return this.participantIdentity}getTrackId(){return this.trackId}setVideoCodec(e){this.videoCodec=e}setRtpMap(e){this.rtpMap=e}setupTransform(e,t,n,r,i,o){if(o&&(u.info("setting codec on cryptor to",{codec:o}),this.videoCodec=o),u.debug("Setting up frame cryptor transform",Object.assign({operation:e,passedTrackId:r,codec:o},this.logContext)),i&&this.isTransformActive)return void u.debug("reuse transform",Object.assign({},this.logContext));const a="encode"===e?this.encodeFunction:this.decodeFunction,s=new TransformStream({transform:a.bind(this)});this.isTransformActive=!0,t.pipeThrough(s).pipeTo(n).catch((e=>{u.warn(e),this.emit(S.Error,e instanceof A?e:new A(e.message,void 0,this.participantIdentity))})).finally((()=>{this.isTransformActive=!1})),this.trackId=r}setSifTrailer(e){u.debug("setting SIF trailer",Object.assign(Object.assign({},this.logContext),{trailer:e})),this.sifTrailer=e}shouldEmitError(e){var t,n;const r=Date.now(),i=null!==(t=this.lastErrorTimestamp.get(e))&&void 0!==t?t:0,o=null!==(n=this.errorCounts.get(e))&&void 0!==n?n:0;return r-i>this.ERROR_WINDOW_MS?(this.errorCounts.set(e,0),this.lastErrorTimestamp.set(e,r),!0):!(r-i<this.ERROR_THROTTLE_MS)&&(o>=this.MAX_ERRORS_PER_MINUTE?(o===this.MAX_ERRORS_PER_MINUTE&&(u.warn("Suppressing further decryption errors for ".concat(this.participantIdentity),Object.assign(Object.assign({},this.logContext),{errorKey:e})),this.errorCounts.set(e,o+1)),!1):(this.lastErrorTimestamp.set(e,r),this.errorCounts.set(e,o+1),!0))}emitThrottledError(e){var t;const n="".concat(this.participantIdentity,"-").concat(e.reason,"-decrypt");if(this.shouldEmitError(n)){const r=null!==(t=this.errorCounts.get(n))&&void 0!==t?t:0;r>1&&u.debug("Decryption error (".concat(r," occurrences in window)"),Object.assign(Object.assign({},this.logContext),{reason:L[e.reason]})),this.emit(S.Error,e)}}encodeFunction(t,n){return e(this,void 0,void 0,(function*(){var e;if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);const r=this.keys.getKeySet();if(!r)return void this.emitThrottledError(new A("key set not found for ".concat(this.participantIdentity," at index ").concat(this.keys.getCurrentKeyIndex()),L.MissingKey,this.participantIdentity));const{encryptionKey:i}=r,o=this.keys.getCurrentKeyIndex();if(i){const r=this.makeIV(null!==(e=t.getMetadata().synchronizationSource)&&void 0!==e?e:-1,t.timestamp);let s=this.getUnencryptedBytes(t);const c=new Uint8Array(t.data,0,s.unencryptedBytes),d=new Uint8Array(2);d[0]=12,d[1]=o;try{const e=yield crypto.subtle.encrypt({name:f,iv:r,additionalData:new Uint8Array(t.data,0,c.byteLength)},i,new Uint8Array(t.data,s.unencryptedBytes));let o=new Uint8Array(e.byteLength+r.byteLength+d.byteLength);o.set(new Uint8Array(e)),o.set(new Uint8Array(r),e.byteLength),o.set(d,e.byteLength+r.byteLength),s.requiresNALUProcessing&&(o=function(e){const t=[];for(var n=0,r=0;r<e.length;++r){var i=e[r];i<=3&&n>=2&&(t.push(3),n=0),t.push(i),0==i?++n:n=0}return new Uint8Array(t)}(o));var a=new Uint8Array(c.byteLength+o.byteLength);return a.set(c),a.set(o,c.byteLength),t.data=a.buffer,n.enqueue(t)}catch(e){u.error(e)}}else u.debug("failed to encrypt, emitting error",this.logContext),this.emitThrottledError(new A("encryption key missing for encoding",L.MissingKey,this.participantIdentity))}))}decodeFunction(t,n){return e(this,void 0,void 0,(function*(){if(!this.isEnabled()||0===t.data.byteLength)return n.enqueue(t);if(function(e,t){if(0===t.byteLength)return!1;const n=new Uint8Array(e.slice(e.byteLength-t.byteLength));return t.every(((e,t)=>e===n[t]))}(t.data,this.sifTrailer))return t.data=t.data.slice(0,t.data.byteLength-this.sifTrailer.byteLength),(yield H(t.data))?(u.debug("enqueue SIF",this.logContext),n.enqueue(t)):void u.warn("Unexpected SIF frame payload, dropping frame",this.logContext);const e=new Uint8Array(t.data)[t.data.byteLength-1];if(!this.keys.hasInvalidKeyAtIndex(e))if(this.keys.getKeySet(e))try{const r=yield this.decryptFrame(t,e);if(this.keys.decryptionSuccess(e),r)return n.enqueue(r)}catch(t){t instanceof A&&t.reason===L.InvalidKey?this.keys.hasValidKey&&(this.emitThrottledError(t),this.keys.decryptionFailure(e)):u.warn("decoding frame failed",{error:t})}else u.warn("skipping decryption due to missing key at index ".concat(e)),this.emitThrottledError(new A("missing key at index ".concat(e," for participant ").concat(this.participantIdentity),L.MissingKey,this.participantIdentity)),this.keys.decryptionFailure(e)}))}decryptFrame(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:void 0,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{ratchetCount:0};return function*(){var o;const a=n.keys.getKeySet(t);if(!i.encryptionKey&&!a)throw new TypeError("no encryption key found for decryption of ".concat(n.participantIdentity));let s=n.getUnencryptedBytes(e);try{const t=new Uint8Array(e.data,0,s.unencryptedBytes);var c=new Uint8Array(e.data,t.length,e.data.byteLength-t.length);if(s.requiresNALUProcessing&&function(e){for(var t=0;t<e.length-3;t++)if(0==e[t]&&0==e[t+1]&&3==e[t+2])return!0;return!1}(c)){c=function(e){const t=[];for(var n=e.length,r=0;r<e.length;)n-r>=3&&!e[r]&&!e[r+1]&&3==e[r+2]?(t.push(e[r++]),t.push(e[r++]),r++):t.push(e[r++]);return new Uint8Array(t)}(c);const n=new Uint8Array(t.byteLength+c.byteLength);n.set(t),n.set(c,t.byteLength),e.data=n.buffer}const n=new Uint8Array(e.data,e.data.byteLength-2,2),r=n[0],d=new Uint8Array(e.data,e.data.byteLength-r-n.byteLength,r),u=t.byteLength,l=e.data.byteLength-(t.byteLength+r+n.byteLength),y=yield crypto.subtle.decrypt({name:f,iv:d,additionalData:new Uint8Array(e.data,0,t.byteLength)},null!==(o=i.encryptionKey)&&void 0!==o?o:a.encryptionKey,new Uint8Array(e.data,u,l)),p=new ArrayBuffer(t.byteLength+y.byteLength),h=new Uint8Array(p);return h.set(new Uint8Array(e.data,0,t.byteLength)),h.set(new Uint8Array(y),t.byteLength),e.data=p,e}catch(o){if(n.keyProviderOptions.ratchetWindowSize>0){if(i.ratchetCount<n.keyProviderOptions.ratchetWindowSize){let o,s;u.debug("ratcheting key attempt ".concat(i.ratchetCount," of ").concat(n.keyProviderOptions.ratchetWindowSize,", for kind ").concat(e instanceof RTCEncodedAudioFrame?"audio":"video")),(null!=r?r:a)===n.keys.getKeySet(t)&&(s=yield n.keys.ratchetKey(t,!1),o=yield R(s.cryptoKey,n.keyProviderOptions.ratchetSalt));const c=yield n.decryptFrame(e,t,r||a,{ratchetCount:i.ratchetCount+1,encryptionKey:null==o?void 0:o.encryptionKey});return c&&o&&(null!=r?r:a)===n.keys.getKeySet(t)&&(n.keys.setKeySet(o,t,s),n.keys.setCurrentKeyIndex(t)),c}throw u.warn("maximum ratchet attempts exceeded"),new A("valid key missing for participant ".concat(n.participantIdentity),L.InvalidKey,n.participantIdentity)}throw new A("Decryption failed: ".concat(o.message),L.InvalidKey,n.participantIdentity)}}()}))}makeIV(e,t){var n;const r=new ArrayBuffer(12),i=new DataView(r);this.sendCounts.has(e)||this.sendCounts.set(e,Math.floor(65535*Math.random()));const o=null!==(n=this.sendCounts.get(e))&&void 0!==n?n:0;return i.setUint32(0,e),i.setUint32(4,t),i.setUint32(8,t-o%65535),this.sendCounts.set(e,o+1),r}getUnencryptedBytes(e){var t;if(!function(e){return"type"in e}(e))return{unencryptedBytes:g.audio,requiresNALUProcessing:!1};const n=null!==(t=this.getVideoCodec(e))&&void 0!==t?t:this.videoCodec;if(n!==this.detectedCodec&&(u.debug("detected different codec",Object.assign({detectedCodec:n,oldCodec:this.detectedCodec},this.logContext)),this.detectedCodec=n),"av1"===n)throw new Error("".concat(n," is not yet supported for end to end encryption"));if("vp8"===n)return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1};if("vp9"===n)return{unencryptedBytes:0,requiresNALUProcessing:!1};try{const t="h264"===n||"h265"===n?n:void 0,r=j(new Uint8Array(e.data),t);if(r.requiresNALUProcessing)return{unencryptedBytes:r.unencryptedBytes,requiresNALUProcessing:!0}}catch(e){u.debug("NALU processing failed, falling back to VP8 handling",Object.assign({error:e},this.logContext))}return{unencryptedBytes:g[e.type],requiresNALUProcessing:!1}}getVideoCodec(e){if(0===this.rtpMap.size)return;const t=e.getMetadata().payloadType;return t?this.rtpMap.get(t):void 0}}class J extends K.EventEmitter{get hasValidKey(){return!this.hasInvalidKeyAtIndex(this.currentKeyIndex)}constructor(e,t){if(super(),this.currentKeyIndex=0,t.keyringSize<1||t.keyringSize>256)throw new TypeError("Keyring size needs to be between 1 and 256");this.cryptoKeyRing=new Array(t.keyringSize).fill(void 0),this.decryptionFailureCounts=new Array(t.keyringSize).fill(0),this.keyProviderOptions=t,this.ratchetPromiseMap=new Map,this.participantIdentity=e}hasInvalidKeyAtIndex(e){return this.keyProviderOptions.failureTolerance>=0&&this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance}decryptionFailure(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.keyProviderOptions.failureTolerance<0||(this.decryptionFailureCounts[e]+=1,this.decryptionFailureCounts[e]>this.keyProviderOptions.failureTolerance&&u.warn("key for ".concat(this.participantIdentity," at index ").concat(e," is being marked as invalid")))}decryptionSuccess(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:this.currentKeyIndex;this.resetKeyStatus(e)}resetKeyStatus(e){void 0===e?this.decryptionFailureCounts.fill(0):this.decryptionFailureCounts[e]=0}ratchetKey(t){let n=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];const r=null!=t?t:this.getCurrentKeyIndex(),i=this.ratchetPromiseMap.get(r);if(void 0!==i)return i;const o=new Promise(((t,i)=>e(this,void 0,void 0,(function*(){try{const i=this.getKeySet(r);if(!i)throw new TypeError("Cannot ratchet key without a valid keyset of participant ".concat(this.participantIdentity));const o=i.material,a=yield function(t,n){return e(this,void 0,void 0,(function*(){const e=T(t.algorithm.name,n);return crypto.subtle.deriveBits(e,t,256)}))}(o,this.keyProviderOptions.ratchetSalt),s=yield function(t){return e(this,arguments,void 0,(function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{name:f},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"encrypt";return function*(){return crypto.subtle.importKey("raw",e,t,!1,"derive"===n?["deriveBits","deriveKey"]:["encrypt","decrypt"])}()}))}(a,o.algorithm.name,"derive"),c={chainKey:a,cryptoKey:s};n&&(yield this.setKeyFromMaterial(s,r,c)),t(c)}catch(e){i(e)}finally{this.ratchetPromiseMap.delete(r)}}))));return this.ratchetPromiseMap.set(r,o),o}setKey(t){return e(this,arguments,void 0,(function(e){var t=this;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return function*(){yield t.setKeyFromMaterial(e,n),t.resetKeyStatus(n)}()}))}setKeyFromMaterial(t,n){return e(this,arguments,void 0,(function(e,t){var n=this;let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;return function*(){const i=yield R(e,n.keyProviderOptions.ratchetSalt),o=t>=0?t%n.cryptoKeyRing.length:n.currentKeyIndex;u.debug("setting new key with index ".concat(t),{usage:e.usages,algorithm:e.algorithm,ratchetSalt:n.keyProviderOptions.ratchetSalt}),n.setKeySet(i,o,r),o>=0&&(n.currentKeyIndex=o)}()}))}setKeySet(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;this.cryptoKeyRing[t%this.cryptoKeyRing.length]=e,n&&this.emit(_.KeyRatcheted,n,this.participantIdentity,t)}setCurrentKeyIndex(t){return e(this,void 0,void 0,(function*(){this.currentKeyIndex=t%this.cryptoKeyRing.length,this.resetKeyStatus(t)}))}getCurrentKeyIndex(){return this.currentKeyIndex}getKeySet(e){return this.cryptoKeyRing[null!=e?e:this.currentKeyIndex]}}const Z=[],$=new Map;let ee,te,ne=new class{constructor(){this.pendingTasks=new Map,this.taskMutex=new h,this.nextTaskIndex=0}run(t){return e(this,void 0,void 0,(function*(){const e={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:l.WAITING};this.pendingTasks.set(e.id,e);const n=yield this.taskMutex.lock();try{return e.executedAt=Date.now(),e.status=l.RUNNING,yield t()}finally{e.status=l.COMPLETED,this.pendingTasks.delete(e.id),n()}}))}flush(){return e(this,void 0,void 0,(function*(){return this.run((()=>e(this,void 0,void 0,(function*(){}))))}))}snapshot(){return Array.from(this.pendingTasks.values())}},re=!1,ie=v,oe=new Map;function ae(e,t){let n=Z.filter((e=>e.getTrackId()===t));if(n.length>1){const r=n.map((e=>({participant:e.getParticipantIdentity()}))).join(",");u.error("Found multiple cryptors for the same trackID ".concat(t,". target participant: ").concat(e," "),{participants:r})}let r=n[0];if(r)e!==r.getParticipantIdentity()&&r.setParticipant(e,se(e));else{if(u.info("creating new cryptor for",{participantIdentity:e,trackId:t}),!ie)throw Error("Missing keyProvider options");r=new Q({participantIdentity:e,keys:se(e),keyProviderOptions:ie,sifTrailer:te}),r.setRtpMap(oe),function(e){e.on(S.Error,(e=>{const t={kind:"error",data:{error:new Error("".concat(L[e.reason],": ").concat(e.message)),participantIdentity:e.participantIdentity}};postMessage(t)}))}(r),Z.push(r)}return r}function se(e){if(re)return ce();let t=$.get(e);return t||(t=new J(e,ie),t.on(_.KeyRatcheted,de),$.set(e,t)),t}function ce(){return ee||(u.debug("creating new shared key handler"),ee=new J("shared-key",ie)),ee}function de(e,t,n){postMessage({kind:"ratchetKey",data:{participantIdentity:t,keyIndex:n,ratchetResult:e}})}u.setDefaultLevel("info"),onmessage=t=>{ne.run((()=>e(void 0,void 0,void 0,(function*(){const{kind:n,data:r}=t.data;switch(n){case"init":u.setLevel(r.loglevel),u.info("worker initialized"),ie=r.keyProviderOptions,re=!!r.keyProviderOptions.sharedKey;postMessage({kind:"initAck",data:{enabled:false}});break;case"enable":o=r.enabled,a=r.participantIdentity,u.debug("setting encryption enabled for all tracks of ".concat(a),{enable:o}),G.set(a,o),u.info("updated e2ee enabled status for ".concat(r.participantIdentity," to ").concat(r.enabled)),postMessage(t.data);break;case"decode":ae(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"encode":ae(r.participantIdentity,r.trackId).setupTransform(n,r.readableStream,r.writableStream,r.trackId,r.isReuse,r.codec);break;case"encryptDataRequest":const{payload:s,iv:c,keyIndex:d}=yield C.encrypt(r.payload,se(r.participantIdentity));console.log("encrypted payload",{original:r.payload,encrypted:s,iv:c}),postMessage({kind:"encryptDataResponse",data:{payload:s,iv:c,keyIndex:d,uuid:r.uuid}});break;case"decryptDataRequest":try{const{payload:e}=yield C.decrypt(r.payload,r.iv,se(r.participantIdentity),r.keyIndex);postMessage({kind:"decryptDataResponse",data:{payload:e,uuid:r.uuid}})}catch(e){u.error("DataCryptor decryption failed",{error:e,participantIdentity:r.participantIdentity,uuid:r.uuid}),postMessage({kind:"error",data:{error:e instanceof Error?e:new Error(String(e)),uuid:r.uuid}})}break;case"setKey":re?yield function(t,n){return e(this,void 0,void 0,(function*(){u.info("set shared key",{index:n}),yield ce().setKey(t,n)}))}(r.key,r.keyIndex):r.participantIdentity?(u.info("set participant sender key ".concat(r.participantIdentity," index ").concat(r.keyIndex)),yield se(r.participantIdentity).setKey(r.key,r.keyIndex)):u.error("no participant Id was provided and shared key usage is disabled");break;case"removeTransform":!function(e,t){const n=Z.filter((n=>n.getParticipantIdentity()===t&&n.getTrackId()===e));n.length>1&&u.error("Found multiple cryptors for the same participant and trackID combination",{trackId:e,participantIdentity:t});const r=n[0];r?r.unsetParticipant():u.warn("Could not unset participant on cryptor",{trackId:e,participantIdentity:t})}(r.trackId,r.participantIdentity);break;case"updateCodec":ae(r.participantIdentity,r.trackId).setVideoCodec(r.codec),u.info("updated codec",{participantIdentity:r.participantIdentity,trackId:r.trackId,codec:r.codec});break;case"setRTPMap":oe=r.map,Z.forEach((e=>{e.getParticipantIdentity()===r.participantIdentity&&e.setRtpMap(r.map)}));break;case"ratchetRequest":!function(t){e(this,void 0,void 0,(function*(){if(re){const e=ce();yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else if(t.participantIdentity){const e=se(t.participantIdentity);yield e.ratchetKey(t.keyIndex),e.resetKeyStatus()}else u.error("no participant Id was provided for ratchet request and shared key usage is disabled")}))}(r);break;case"setSifTrailer":i=r.trailer,te=i,Z.forEach((e=>{e.setSifTrailer(i)}))}var i,o,a}))))},self.RTCTransformEvent&&(u.debug("setup transform event"),self.onrtctransform=e=>{const t=e.transformer;u.debug("transformer",t);const{kind:n,participantIdentity:r,trackId:i,codec:o}=t.options,a=ae(r,i);u.debug("transform",{codec:o}),a.setupTransform(n,t.readable,t.writable,i,!1,o)})}));
|
|
2
2
|
//# sourceMappingURL=livekit-client.e2ee.worker.js.map
|