summaryrefslogtreecommitdiff
path: root/cli/js/tls.ts
blob: f0506898c5a1d8825559f6ab202bf505267cd7dc (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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import * as tlsOps from "./ops/tls.ts";
import { Listener, Conn, ConnImpl, ListenerImpl } from "./net.ts";

// TODO(ry) There are many configuration options to add...
// https://docs.rs/rustls/0.16.0/rustls/struct.ClientConfig.html
interface ConnectTlsOptions {
  transport?: "tcp";
  port: number;
  hostname?: string;
  certFile?: string;
}

export async function connectTls({
  port,
  hostname = "127.0.0.1",
  transport = "tcp",
  certFile = undefined,
}: ConnectTlsOptions): Promise<Conn> {
  const res = await tlsOps.connectTls({
    port,
    hostname,
    transport,
    certFile,
  });
  return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!);
}

class TLSListenerImpl extends ListenerImpl {
  async accept(): Promise<Conn> {
    const res = await tlsOps.acceptTLS(this.rid);
    return new ConnImpl(res.rid, res.remoteAddr, res.localAddr);
  }
}

export interface ListenTlsOptions {
  port: number;
  hostname?: string;
  transport?: "tcp";
  certFile: string;
  keyFile: string;
}

export function listenTls({
  port,
  certFile,
  keyFile,
  hostname = "0.0.0.0",
  transport = "tcp",
}: ListenTlsOptions): Listener {
  const res = tlsOps.listenTls({
    port,
    certFile,
    keyFile,
    hostname,
    transport,
  });
  return new TLSListenerImpl(res.rid, res.localAddr);
}

interface StartTlsOptions {
  hostname?: string;
  certFile?: string;
}

export async function startTls(
  conn: Conn,
  { hostname = "127.0.0.1", certFile }: StartTlsOptions = {}
): Promise<Conn> {
  const res = await tlsOps.startTls({
    rid: conn.rid,
    hostname,
    certFile,
  });
  return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!);
}