summaryrefslogtreecommitdiff
path: root/cli/js/tls.ts
blob: 2780956a16187b52385c39125d156ec41a152694 (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
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendAsync, sendSync } from "./dispatch_json.ts";
import { Listener, Transport, 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?: Transport;
  port: number;
  hostname?: string;
  certFile?: string;
}
const connectTLSDefaults = { hostname: "127.0.0.1", transport: "tcp" };

/**
 * Establishes a secure connection over TLS (transport layer security).
 */
export async function connectTLS(options: ConnectTLSOptions): Promise<Conn> {
  options = Object.assign(connectTLSDefaults, options);
  const res = await sendAsync("op_connect_tls", options);
  return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!);
}

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

export interface ListenTLSOptions {
  port: number;
  hostname?: string;
  transport?: Transport;
  certFile: string;
  keyFile: string;
}

/** Listen announces on the local transport address over TLS (transport layer security).
 *
 * @param options
 * @param options.port The port to connect to. (Required.)
 * @param options.hostname A literal IP address or host name that can be
 *   resolved to an IP address. If not specified, defaults to 0.0.0.0
 * @param options.certFile Server certificate file
 * @param options.keyFile Server public key file
 *
 * Examples:
 *
 *     Deno.listenTLS({ port: 443, certFile: "./my_server.crt", keyFile: "./my_server.key" })
 */
export function listenTLS(options: ListenTLSOptions): Listener {
  const hostname = options.hostname || "0.0.0.0";
  const transport = options.transport || "tcp";
  const res = sendSync("op_listen_tls", {
    hostname,
    port: options.port,
    transport,
    certFile: options.certFile,
    keyFile: options.keyFile
  });
  return new TLSListenerImpl(res.rid, res.localAddr);
}