File size: 1,663 Bytes
c237e22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import axios from "axios";
import { RequestListener } from "http";
import https from "https";
import localtunnel from "localtunnel";

enum HttpsMethod {
  None = "none",
  LocalIpMedic = "local-ip.medicmobile.org",
  LocalIpCo = "local-ip.co",
  Localtunnel = "localtunnel",
}

const HTTPS_METHOD = process.env.HTTPS_METHOD || HttpsMethod.None;

export const serveHTTPS = async (app: RequestListener, port: number) => {
  if (HTTPS_METHOD === HttpsMethod.LocalIpMedic) {
    const json = (await axios.get("https://local-ip.medicmobile.org/keys"))
      .data;
    const cert = `${json.cert}\n${json.chain}`;
    const httpsServer = https.createServer({ key: json.privkey, cert }, app);
    httpsServer.listen(port);
    console.log(`HTTPS addon listening on port ${port}`);
    return httpsServer;
  }

  if (HTTPS_METHOD === HttpsMethod.LocalIpCo) {
    const key = (await axios.get("http://local-ip.co/cert/server.key")).data;
    const serverPem = (await axios.get("http://local-ip.co/cert/server.pem"))
      .data;
    const chainPem = (await axios.get("http://local-ip.co/cert/chain.pem"))
      .data;
    const cert = `${serverPem}\n${chainPem}`;
    const httpsServer = https.createServer({ key, cert }, app);
    httpsServer.listen(port);
    console.log(`HTTPS addon listening on port ${port}`);
    return httpsServer;
  }

  if (HTTPS_METHOD === HttpsMethod.Localtunnel) {
    const tunnel = await localtunnel({ port: Number(process.env.PORT) });
    console.log(`Tunnel accessible at: ${tunnel.url}`);
    const tunnelPassword = await axios.get("https://loca.lt/mytunnelpassword");
    console.log(`Tunnel password: ${tunnelPassword.data}`);
  }
};