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.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. SERVERS.forEach(server => new Server(server.host, server.secret));
  14. const date = () => new Date().toLocaleTimeString('de');
  15. const queue: Map<string, Promise<unknown>> = new Map();
  16. class Server {
  17. host: string;
  18. #secret: string;
  19. static listServer: Server[] = [];
  20. static #currentServerIndex = 0;
  21. static get currentServer() {
  22. return Server.listServer[Server.#currentServerIndex];
  23. }
  24. constructor(host: string, secret: string) {
  25. this.host = host;
  26. this.#secret = secret;
  27. this.test().then(_ => Server.listServer.push(this)).catch(_ => Deno.exit(1));
  28. }
  29. static getNextServer() {
  30. Server.#currentServerIndex++;
  31. if (Server.#currentServerIndex === Server.listServer.length)
  32. Server.#currentServerIndex = 0;
  33. return Server.listServer[Server.#currentServerIndex];
  34. }
  35. static async hashCreate(params: string) {
  36. const hash = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(params));
  37. return encodeHex(hash);
  38. }
  39. static splitURL(url: URL) {
  40. // entferne `/bigbluebutton/api/`
  41. const call = url.pathname.slice(19);
  42. const params = url.search.replace('?', '').replace(/[?&]?checksum.*$/, '');
  43. return { call, params };
  44. }
  45. static async checkAuthenticated(url: URL) {
  46. const checksum = url.searchParams.get('checksum');
  47. if (checksum === null)
  48. return false;
  49. const { call, params } = Server.splitURL(url);
  50. const hash = await Server.hashCreate(`${call}${params}${SECRET}`);
  51. return hash === checksum;
  52. }
  53. async urlCreate(call: string, params = "") {
  54. const hash = await Server.hashCreate(`${call}${params}${this.#secret}`);
  55. return new URL(`${this.host}/${call}?${params}${params === '' ? '' : '&'}checksum=${hash}`);
  56. }
  57. async getResponse(query: string, params = "") {
  58. const url = await this.urlCreate(query, params);
  59. const res = await fetch(url);
  60. if (!res.ok)
  61. throw "Connection error. Please check your host configuration";
  62. const body = await res.text();
  63. return body;
  64. }
  65. async test() {
  66. try {
  67. const res = await this.getResponse('getMeetings');
  68. const ok = res.includes('SUCCESS');
  69. if (!ok)
  70. throw Error;
  71. console.log(`${this.host} is ${green('ok')}`);
  72. } catch (e) {
  73. console.log(`${this.host} is ${red('misconfigured. Please check your secret in servers.json')}`);
  74. throw e;
  75. }
  76. }
  77. }
  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. })