tor-browser

The Tor Browser
git clone https://git.dasho.dev/tor-browser.git
Log | Files | Refs | README | LICENSE

file_auth_download_server.sjs (2073B)


      1 "use strict";
      2 
      3 function handleRequest(request, response) {
      4   let match;
      5 
      6   // Allow the caller to drive how authentication is processed via the query.
      7   // Eg, http://localhost:8888/authenticate.sjs?user=foo&realm=bar
      8   // The extra ? allows the user/pass/realm checks to succeed if the name is
      9   // at the beginning of the query string.
     10   let query = new URLSearchParams(request.queryString);
     11 
     12   let expected_user = query.get("user");
     13   let expected_pass = query.get("pass");
     14   let realm = query.get("realm");
     15 
     16   // Look for an authentication header, if any, in the request.
     17   //
     18   // EG: Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
     19   //
     20   // This test only supports Basic auth. The value sent by the client is
     21   // "username:password", obscured with base64 encoding.
     22 
     23   let actual_user = "",
     24     actual_pass = "",
     25     authHeader;
     26   if (request.hasHeader("Authorization")) {
     27     authHeader = request.getHeader("Authorization");
     28     match = /Basic (.+)/.exec(authHeader);
     29     if (match.length != 2) {
     30       throw new Error("Couldn't parse auth header: " + authHeader);
     31     }
     32     // Decode base64 to string
     33     let userpass = atob(match[1]);
     34     match = /(.*):(.*)/.exec(userpass);
     35     if (match.length != 3) {
     36       throw new Error("Couldn't decode auth header: " + userpass);
     37     }
     38     actual_user = match[1];
     39     actual_pass = match[2];
     40   }
     41 
     42   // Don't request authentication if the credentials we got were what we
     43   // expected.
     44   let requestAuth =
     45     expected_user != actual_user || expected_pass != actual_pass;
     46 
     47   if (requestAuth) {
     48     response.setStatusLine("1.0", 401, "Authentication required");
     49     response.setHeader("WWW-Authenticate", 'basic realm="' + realm + '"', true);
     50     response.write("Authentication required");
     51   } else {
     52     response.setStatusLine("1.0", 200, "OK");
     53     response.setHeader("Cache-Control", "no-cache", false);
     54     response.setHeader(
     55       "Content-Disposition",
     56       "attachment; filename=dummy-file.html"
     57     );
     58     response.setHeader("Content-Type", "text/html");
     59     response.write("<p id='success'>SUCCESS</p>");
     60   }
     61 }