summaryrefslogtreecommitdiff
path: root/ext/net/02_tls.js
blob: 00acd7c96983b04eb2df85e445761d7d19ac76bd (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
"use strict";

((window) => {
  const core = window.Deno.core;
  const { Listener, Conn } = window.__bootstrap.net;

  function opConnectTls(
    args,
  ) {
    return core.opAsync("op_tls_connect", args);
  }

  function opAcceptTLS(rid) {
    return core.opAsync("op_tls_accept", rid);
  }

  function opListenTls(args) {
    return core.opSync("op_tls_listen", args);
  }

  function opStartTls(args) {
    return core.opAsync("op_tls_start", args);
  }

  function opTlsHandshake(rid) {
    return core.opAsync("op_tls_handshake", rid);
  }

  class TlsConn extends Conn {
    handshake() {
      return opTlsHandshake(this.rid);
    }
  }

  async function connectTls({
    port,
    hostname = "127.0.0.1",
    transport = "tcp",
    certFile = undefined,
    caCerts = [],
    certChain = undefined,
    privateKey = undefined,
    alpnProtocols = undefined,
  }) {
    const res = await opConnectTls({
      port,
      hostname,
      transport,
      certFile,
      caCerts,
      certChain,
      privateKey,
      alpnProtocols,
    });
    return new TlsConn(res.rid, res.remoteAddr, res.localAddr);
  }

  class TlsListener extends Listener {
    async accept() {
      const res = await opAcceptTLS(this.rid);
      return new TlsConn(res.rid, res.remoteAddr, res.localAddr);
    }
  }

  function listenTls({
    port,
    certFile,
    keyFile,
    hostname = "0.0.0.0",
    transport = "tcp",
    alpnProtocols = undefined,
  }) {
    const res = opListenTls({
      port,
      certFile,
      keyFile,
      hostname,
      transport,
      alpnProtocols,
    });
    return new TlsListener(res.rid, res.localAddr);
  }

  async function startTls(
    conn,
    {
      hostname = "127.0.0.1",
      certFile = undefined,
      caCerts = [],
      alpnProtocols = undefined,
    } = {},
  ) {
    const res = await opStartTls({
      rid: conn.rid,
      hostname,
      certFile,
      caCerts,
      alpnProtocols,
    });
    return new TlsConn(res.rid, res.remoteAddr, res.localAddr);
  }

  window.__bootstrap.tls = {
    startTls,
    listenTls,
    connectTls,
    TlsConn,
    TlsListener,
  };
})(this);