main.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. import SERVERS from './servers.json' with { type: 'json' };
  2. import { crypto } from "https://deno.land/std@0.224.0/crypto/mod.ts";
  3. import { encodeHex } from "https://deno.land/std@0.224.0/encoding/hex.ts"
  4. import { red, green, yellow } from "https://deno.land/std@0.115.1/fmt/colors.ts";
  5. const SECRET = Deno.env.get("TINYSCALE_SECRET");
  6. const _port = Deno.env.get("PORT");
  7. const PORT = _port ? parseInt(_port) : undefined;
  8. const VERSION = 'v2.0.0'
  9. if (SECRET === undefined)
  10. throw "No `TINYSCALE_SECRET` set. tinyscale will exit.";
  11. if (SERVERS.length === 0)
  12. throw "There are no servers listed in `servers.json`";
  13. class Server {
  14. host: string;
  15. #secret: string;
  16. constructor(host: string, secret: string) {
  17. this.host = host;
  18. this.#secret = secret;
  19. }
  20. static async hashCreate(params: string) {
  21. const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(params));
  22. return encodeHex(hash);
  23. }
  24. static splitURL(url: URL) {
  25. // entferne `/bigbluebutton/api/`
  26. const call = url.pathname.slice(19);
  27. const params = url.search.replace('?', '').replace(/[?&]?checksum.*$/, '');
  28. return { call, params }
  29. }
  30. static async checkAuthenticated(url: URL) {
  31. const checksum = url.searchParams.get('checksum');
  32. if (checksum === null)
  33. return false;
  34. const { call, params } = Server.splitURL(url);
  35. const hash = await Server.hashCreate(`${call}${params}${SECRET}`);
  36. return hash === checksum;
  37. }
  38. async urlCreate(call: string, params = "") {
  39. const hash = await Server.hashCreate(`${call}${params}${this.#secret}`);
  40. return new URL(`${this.host}/${call}?${params}${params === '' ? '' : '&'}checksum=${hash}`);
  41. }
  42. async getResponse(query: string, params = "") {
  43. const url = await this.urlCreate(query, params);
  44. const res = await fetch(url);
  45. if (!res.ok)
  46. throw "Connection error. Please check your host configuration";
  47. const body = await res.text();
  48. return body;
  49. }
  50. async test() {
  51. try {
  52. const res = await this.getResponse('getMeetings');
  53. const ok = res.includes('SUCCESS');
  54. if (!ok)
  55. throw Error;
  56. console.log(`${this.host} is ${green('ok')}`);
  57. } catch (_e) {
  58. console.log(`${this.host} is ${red('misconfigured. Please check your secret in servers.json')}`);
  59. Deno.exit(1)
  60. }
  61. }
  62. }
  63. const listServer: Server[] = [];
  64. const queue: Map<string, Promise<unknown>> = new Map();
  65. for (const server of SERVERS) {
  66. const s = new Server(server.host, server.secret);
  67. s.test();
  68. listServer.push(s);
  69. }
  70. let currentServerIndex = 0;
  71. function getNextServer() {
  72. currentServerIndex++;
  73. if (currentServerIndex === listServer.length)
  74. currentServerIndex = 0;
  75. return listServer[currentServerIndex];
  76. }
  77. Deno.serve({ port: PORT,
  78. onListen({ port, hostname }) {
  79. console.log(green(`Starting tinyscale ${VERSION} on Deno ${Deno.version.deno}`));
  80. console.log(`Your secret is set to ${green(SECRET)}`);
  81. console.log(`API available at ${green(`http://${hostname}:${port}/bigbluebutton/api/`)}`);
  82. console.log();
  83. console.log(`Running tests on ${SERVERS.length} host${SERVERS.length === 1 ? '':'s'}:`);
  84. }}, async (req) => {
  85. const url = new URL(req.url);
  86. const { call, params } = Server.splitURL(url);
  87. const { promise, resolve } = Promise.withResolvers();
  88. let log = "";
  89. // voicemail if just looking for a life sign from the server
  90. if (url.pathname === '/bigbluebutton/api/' || url.pathname === '/bigbluebutton/')
  91. return new Response("<response><returncode>SUCCESS</returncode><version>2.0</version></response>");
  92. // check the checksum and fail if not true
  93. const authenticated = await Server.checkAuthenticated(url);
  94. if (!authenticated) {
  95. log = red(`401: ${url.pathname}`);
  96. return new Response("<response><returncode>FAILED</returncode><messageKey>checksumError</messageKey><message>Checksums do not match</message></response>",
  97. { status: 401, headers: { "content-type": "text/xml" } });
  98. }
  99. // if there's a meeting/recording id, find the server which has it
  100. let selectedServer: Server | undefined;
  101. const meetingID = url.searchParams.get('meetingID');
  102. const recordingID = url.searchParams.get('recordingID');
  103. if (meetingID !== null) {
  104. if (call === 'create') {
  105. // if there's a request for the same room creation, wait for it
  106. if (queue.has(meetingID)) {
  107. console.log(`Race pending for meeting-ID: ${red(meetingID)}`);
  108. await queue.get(meetingID);
  109. }
  110. queue.set(meetingID, promise);
  111. }
  112. for (const server of listServer) {
  113. const meetings = await server.getResponse('getMeetings');
  114. if (meetings.includes(meetingID)) {
  115. selectedServer = server;
  116. break;
  117. }
  118. }
  119. }
  120. else if (recordingID !== null)
  121. for (const server of listServer) {
  122. const recordings = await server.getResponse('getRecordings');
  123. if (recordings.includes(recordingID)) {
  124. selectedServer = server;
  125. break
  126. }
  127. }
  128. log = `${green(`${call}`)} found, reply with`;
  129. if (call === 'create' && selectedServer === undefined && meetingID !== null) {
  130. selectedServer = getNextServer();
  131. console.log(green('create')+' '+yellow('not found')+", opening a new room on "+green(selectedServer.host));
  132. const body = await selectedServer.getResponse('create', params);
  133. resolve(meetingID);
  134. queue.delete(meetingID);
  135. return new Response(body, { headers: { "content-type": "text/xml" } });
  136. } else if (call === 'create' && meetingID !== null) {
  137. resolve(meetingID);
  138. queue.delete(meetingID);
  139. }
  140. if (selectedServer === undefined)
  141. selectedServer = listServer[currentServerIndex];
  142. log = log + ' ' + selectedServer.host;
  143. console.log(log);
  144. // return the new URL to the real BBB server
  145. const newURL = await selectedServer.urlCreate(call, params);
  146. return Response.redirect(newURL);
  147. })