-
Notifications
You must be signed in to change notification settings - Fork 2
/
agora_manager_channel_encryption.js
290 lines (254 loc) · 8.28 KB
/
agora_manager_channel_encryption.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import AgoraManager from "../agora_manager/agora_manager.js";
const AgoraChannelEncryption = async (eventsCallback, config) => {
// Extend the AgoraManager by importing it
const agoraManager = await AgoraManager(eventsCallback, config);
let role = "publisher"; // set the role to "publisher" or "subscriber" as appropriate
// Fetches the token for stream channels
async function fetchToken(uid, channelName) {
if (config.serverUrl !== "") {
try {
const res = await fetch(
config.proxyUrl +
config.serverUrl +
"/rtc/" +
channelName +
"/" +
role +
"/uid/" +
uid +
"/?expiry=" +
config.tokenExpiryTime,
{
headers: {
"X-Requested-With": "XMLHttpRequest",
},
}
);
const data = await res.text();
const json = await JSON.parse(data);
console.log("Video SDK token fetched from server: ", json.rtcToken);
return json.rtcToken;
} catch (err) {
console.log(err);
}
} else {
return config.token;
}
}
if(config.product == "live")
{
createToggleSwitch();
}
function createToggleSwitch() {
const toggleContainer = document.getElementById('toggleContainer');
// Create a label
const label = document.createElement('label');
label.textContent = 'Host :';
// Create a checkbox
const toggleSwitch = document.createElement('input');
toggleSwitch.type = 'checkbox';
toggleSwitch.id = 'dynamicToggleSwitch';
// Append the label and checkbox to the container
toggleContainer.appendChild(label);
toggleContainer.appendChild(toggleSwitch);
// Add event listener for the dynamic toggle switch
toggleSwitch.addEventListener('change', function() {
if(agoraEngine == null)
{
console.log("Join a channel to change the user role");
}
if (toggleSwitch.checked) {
console.log('Host selected');
setUserRole("host")
} else {
console.log('Audience selected');
setUserRole("audience")
}
});
}
// In a production environment, you retrieve the key and salt from
// an authentication server. For this code example you generate locally.
var encryptionKey = "";
var encryptionSaltBase64 = "";
var encryptionMode = "";
function base64ToUint8Array(base64Str) {
const raw = window.atob(base64Str);
const result = new Uint8Array(new ArrayBuffer(raw.length));
for (let i = 0; i < raw.length; i += 1) {
result[i] = raw.charCodeAt(i);
}
return result;
}
function hex2ascii(hexx) {
const hex = hexx.toString(); //force conversion
let str = "";
for (let i = 0; i < hex.length; i += 2) {
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return str;
}
// Convert the encryptionSaltBase64 string to base64ToUint8Array.
encryptionSaltBase64 = base64ToUint8Array(config.salt);
// Convert the encryptionKey string to hex2ascii.
encryptionKey = hex2ascii(config.cipherKey);
// Set an encryption mode.
encryptionMode = config.encryptionMode;
agoraManager
.getAgoraEngine()
.setEncryptionConfig(encryptionMode, encryptionKey, encryptionSaltBase64);
const joinWithE2EEncryption = async (
localPlayerContainer,
channelParameters,
password,
uid
) => {
AgoraRTC.setParameter("ENABLE_ENCODED_TRANSFORM", true);
const token = await fetchToken(uid, config.channelName);
await agoraManager
.getAgoraEngine()
.join(config.appId, config.channelName, token, uid);
// Create a local audio track from the audio sampled by a microphone.
channelParameters.localAudioTrack =
await AgoraRTC.createMicrophoneAudioTrack();
// Create a local video track from the video captured by a camera.
channelParameters.localVideoTrack = await AgoraRTC.createCameraVideoTrack();
// Append the local video container to the page body.
document.body.append(localPlayerContainer);
// Publish the local audio and video tracks in the channel.
await agoraManager
.getAgoraEngine()
.publish([
channelParameters.localAudioTrack,
channelParameters.localVideoTrack,
]);
const transceiver =
channelParameters.localVideoTrack.getRTCRtpTransceiver();
if (!transceiver || !transceiver.sender) {
return;
}
const sender = transceiver.sender;
var browserName = (function (agent) {
switch (true) {
case agent.indexOf("chrome") > -1 && !!window.chrome:
return "Chrome";
default:
return "other";
}
})(window.navigator.userAgent.toLowerCase());
if (browserName === "Chrome") {
setEncryptionStream(sender, password);
}
// Play the local video track.
channelParameters.localVideoTrack.play(localPlayerContainer);
};
async function setEncryptionStream(sender, password) {
const streams = sender.createEncodedStreams();
const transformer = new TransformStream({
async transform(chunk, controller) {
// controller.enqueue(chunk);
// return;
const originView = new Uint8Array(chunk.data);
let reservedSize = 40;
const naluType = originView[4] & 0x1f;
console.log(naluType);
if (naluType !== 7) {
reservedSize = 5;
}
const payload = originView.subarray(reservedSize, originView.length);
const hashKey = await grindKey(password, 10);
const key = await window.crypto.subtle.importKey(
"raw",
hashKey,
{
name: "AES-GCM",
},
false,
["encrypt"]
);
const iv = await getIv(password);
const ciphertext = await window.crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv,
tagLength: 128,
},
key,
payload
);
const encryptedView = new Uint8Array(
ciphertext.byteLength + reservedSize + 12
);
encryptedView.set(originView.subarray(0, reservedSize));
encryptedView.set(iv, reservedSize);
encryptedView.set(new Uint8Array(ciphertext), reservedSize + 12);
chunk.data = encryptedView.buffer;
controller.enqueue(chunk);
},
});
streams.readable.pipeThrough(transformer).pipeTo(streams.writable);
}
async function setDecryptionStream(receiver, password) {
const streams = receiver.createEncodedStreams();
const transformer = new TransformStream({
async transform(chunk, controller) {
// controller.enqueue(chunk);
// return;
const originView = new Uint8Array(chunk.data);
let reservedSize = 40;
const naluType = originView[4] & 0x1f;
if (naluType !== 7) {
// controller.enqueue(chunk);
// return;
reservedSize = 5;
}
const hashKey = await grindKey(password, 10);
const key = await window.crypto.subtle.importKey(
"raw",
hashKey,
{
name: "AES-GCM",
},
false,
["decrypt"]
);
const header = originView.subarray(0, reservedSize);
const iv = originView.subarray(reservedSize, reservedSize + 12);
const payload = originView.subarray(
reservedSize + 12,
chunk.data.byteLength
);
let decrypted = null;
try {
decrypted = await window.crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv,
tagLength: 128,
},
key,
payload
);
} catch (e) {
console.log(e);
controller.enqueue(chunk);
return;
}
const decryptedView = new Uint8Array(
decrypted.byteLength + reservedSize
);
decryptedView.set(header);
decryptedView.set(new Uint8Array(decrypted), reservedSize);
chunk.data = decryptedView.buffer;
controller.enqueue(chunk);
},
});
streams.readable.pipeThrough(transformer).pipeTo(streams.writable);
}
// Return the extended agora manager
return {
...agoraManager,
joinWithE2EEncryption,
setDecryptionStream,
};
};
export default AgoraChannelEncryption;