Add Coturn TURN server
This commit is contained in:
1 parent
752d0cf3af
commit
c3ca3e1752
13 files changed
+309
-11
No files matched your search
+17
-1
@@ -16,7 +16,8 @@ export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl =
|
||||
}
|
||||
// Credentials and URLs are ignored unless this user explicitly opts in.
|
||||
if (allowTurn) {
|
||||
if (!/^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(turnUrl) || !username || !credential) {
|
||||
const urls = Array.isArray(turnUrl) ? turnUrl : [turnUrl];
|
||||
if (!urls.length || !urls.every(url => typeof url === 'string' && /^turns?:[^\s/?#@]+(?:\?transport=(?:udp|tcp))?$/i.test(url)) || !username || !credential) {
|
||||
throw new Error('TURN opt-in requires a turn: or turns: address, username and password.');
|
||||
}
|
||||
iceServers.push({ urls: turnUrl, username, credential });
|
||||
@@ -24,6 +25,21 @@ export function iceConfiguration({ stunUrl = null, allowTurn = false, turnUrl =
|
||||
return { iceServers };
|
||||
}
|
||||
|
||||
export async function fetchTurnOptions(options, endpoint, { signal, fetchImpl = fetch } = {}) {
|
||||
if (!options.allowTurn || !options.managedTurn || !endpoint) return options;
|
||||
const response = await fetchImpl(endpoint, { credentials: 'same-origin', cache: 'no-store', signal });
|
||||
if (!response.ok) throw new Error('Could not obtain TURN credentials. Check the local dev server.');
|
||||
const { expiresAt, iceServers } = await response.json();
|
||||
const turn = iceServers?.find(server => {
|
||||
const urls = Array.isArray(server.urls) ? server.urls : [server.urls];
|
||||
return urls.length && urls.every(url => /^turns?:/i.test(url));
|
||||
});
|
||||
if (!turn || !Number.isFinite(expiresAt) || expiresAt <= Date.now() / 1000 + 30) throw new Error('Missing or expired TURN credentials.');
|
||||
const result = { ...options, turnUrl: turn.urls, username: turn.username, credential: turn.credential };
|
||||
iceConfiguration(result); // Validate before passing server-supplied data to WebRTC.
|
||||
return result;
|
||||
}
|
||||
|
||||
export function createPeerConnection(options) {
|
||||
return new RTCPeerConnection(iceConfiguration(options));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user