main.ts 5.7 KB

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