@ngrok/ngrok 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/session.rs ADDED
@@ -0,0 +1,171 @@
1
+ use std::time::Duration;
2
+
3
+ use napi::bindgen_prelude::*;
4
+ use napi_derive::napi;
5
+ use ngrok::{
6
+ session::SessionBuilder,
7
+ Session,
8
+ };
9
+ use tracing::debug;
10
+ use tracing_subscriber::{
11
+ self,
12
+ fmt::format::FmtSpan,
13
+ };
14
+
15
+ use crate::tunnel_builder::{
16
+ NgrokHttpTunnelBuilder,
17
+ NgrokLabeledTunnelBuilder,
18
+ NgrokTcpTunnelBuilder,
19
+ NgrokTlsTunnelBuilder,
20
+ };
21
+
22
+ /// The builder for an ngrok session.
23
+ #[napi]
24
+ #[allow(dead_code)]
25
+ struct NgrokSessionBuilder {
26
+ raw_builder: SessionBuilder,
27
+ }
28
+
29
+ /// turn on tracing subscriber which obeys NGROK_LOG env variable, e.g.:
30
+ /// process.env.NGROK_LOG = 'ngrok=debug';
31
+ /// ngrok.tracingSubscriber();
32
+ #[napi()]
33
+ pub fn tracing_subscriber() {
34
+ tracing_subscriber::fmt()
35
+ .pretty()
36
+ .with_span_events(FmtSpan::ENTER)
37
+ .with_env_filter(std::env::var("NGROK_LOG").unwrap_or_default())
38
+ .init();
39
+ }
40
+
41
+ #[napi]
42
+ #[cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))]
43
+ #[allow(dead_code)]
44
+ impl NgrokSessionBuilder {
45
+ /// Create a new session builder
46
+ #[napi(constructor)]
47
+ pub fn new() -> Self {
48
+ NgrokSessionBuilder {
49
+ raw_builder: Session::builder(),
50
+ }
51
+ }
52
+
53
+ /// Authenticate the ngrok session with the given authtoken.
54
+ #[napi]
55
+ pub fn authtoken(&mut self, authtoken: String) -> &Self {
56
+ // can't put lifetimes or generics on napi structs, which limits our options.
57
+ // there is a Reference which can force static lifetime, but haven't figured
58
+ // out a way to make this actually helpful. so send in the clones.
59
+ // https://napi.rs/docs/concepts/reference
60
+ self.raw_builder = self.raw_builder.clone().authtoken(authtoken);
61
+ self
62
+ }
63
+
64
+ /// Authenticate using the authtoken in the `NGROK_AUTHTOKEN` environment
65
+ /// variable.
66
+ #[napi]
67
+ pub fn authtoken_from_env(&mut self) -> &Self {
68
+ self.raw_builder = self.raw_builder.clone().authtoken_from_env();
69
+ self
70
+ }
71
+
72
+ /// Set the heartbeat interval for the session.
73
+ /// This value determines how often we send application level
74
+ /// heartbeats to the server go check connection liveness.
75
+ #[napi]
76
+ pub fn heartbeat_interval(&mut self, heartbeat_interval: u32) -> &Self {
77
+ self.raw_builder = self
78
+ .raw_builder
79
+ .clone()
80
+ .heartbeat_interval(Duration::new(heartbeat_interval.into(), 0));
81
+ self
82
+ }
83
+
84
+ /// Set the heartbeat tolerance for the session.
85
+ /// If the session's heartbeats are outside of their interval by this duration,
86
+ /// the server will assume the session is dead and close it.
87
+ #[napi]
88
+ pub fn heartbeat_tolerance(&mut self, heartbeat_tolerance: u32) -> &Self {
89
+ self.raw_builder = self
90
+ .raw_builder
91
+ .clone()
92
+ .heartbeat_tolerance(Duration::new(heartbeat_tolerance.into(), 0));
93
+ self
94
+ }
95
+
96
+ /// Use the provided opaque metadata string for this session.
97
+ /// Viewable from the ngrok dashboard or API.
98
+ #[napi]
99
+ pub fn metadata(&mut self, metadata: String) -> &Self {
100
+ self.raw_builder = self.raw_builder.clone().metadata(metadata);
101
+ self
102
+ }
103
+
104
+ /// Connect to the provided ngrok server address.
105
+ #[napi]
106
+ pub fn server_addr(&mut self, addr: String) -> &Self {
107
+ self.raw_builder = self.raw_builder.clone().server_addr(addr).clone();
108
+ self
109
+ }
110
+
111
+ // Omitting these configurations:
112
+ // tls_config(&mut self, config: rustls::ClientConfig)
113
+ // with_connect_callback(&mut self, callback: ConnectCallback)
114
+
115
+ /// Attempt to establish an ngrok session using the current configuration.
116
+ #[napi]
117
+ pub async fn connect(&self) -> Result<NgrokSession> {
118
+ self.raw_builder
119
+ .connect()
120
+ .await
121
+ .map(|s| NgrokSession { raw_session: s })
122
+ .map_err(|e| {
123
+ Error::new(
124
+ Status::GenericFailure,
125
+ format!("failed to connect session, {e:?}"),
126
+ )
127
+ })
128
+ }
129
+ }
130
+
131
+ /// An ngrok session.
132
+ #[napi(custom_finalize)]
133
+ struct NgrokSession {
134
+ #[allow(dead_code)]
135
+ raw_session: Session,
136
+ }
137
+
138
+ #[napi]
139
+ #[allow(dead_code)]
140
+ impl NgrokSession {
141
+ /// Start building a tunnel backing an HTTP endpoint.
142
+ #[napi]
143
+ pub fn http_endpoint(&self) -> NgrokHttpTunnelBuilder {
144
+ NgrokHttpTunnelBuilder::new(self.raw_session.http_endpoint())
145
+ }
146
+
147
+ /// Start building a tunnel backing a TCP endpoint.
148
+ #[napi]
149
+ pub fn tcp_endpoint(&self) -> NgrokTcpTunnelBuilder {
150
+ NgrokTcpTunnelBuilder::new(self.raw_session.tcp_endpoint())
151
+ }
152
+
153
+ /// Start building a tunnel backing a TLS endpoint.
154
+ #[napi]
155
+ pub fn tls_endpoint(&self) -> NgrokTlsTunnelBuilder {
156
+ NgrokTlsTunnelBuilder::new(self.raw_session.tls_endpoint())
157
+ }
158
+
159
+ /// Start building a labeled tunnel.
160
+ #[napi]
161
+ pub fn labeled_tunnel(&self) -> NgrokLabeledTunnelBuilder {
162
+ NgrokLabeledTunnelBuilder::new(self.raw_session.labeled_tunnel())
163
+ }
164
+ }
165
+
166
+ impl ObjectFinalize for NgrokSession {
167
+ fn finalize(self, mut _env: Env) -> Result<()> {
168
+ debug!("NgrokSession finalize");
169
+ Ok(())
170
+ }
171
+ }
package/src/tcp.rs ADDED
@@ -0,0 +1,14 @@
1
+ use napi_derive::napi;
2
+
3
+ use crate::tunnel_builder::NgrokTcpTunnelBuilder;
4
+
5
+ #[napi]
6
+ #[allow(dead_code)]
7
+ impl NgrokTcpTunnelBuilder {
8
+ /// The TCP address to request for this edge.
9
+ #[napi]
10
+ pub fn remote_addr(&mut self, remote_addr: String) -> &Self {
11
+ self.tunnel_builder = self.tunnel_builder.clone().remote_addr(remote_addr);
12
+ self
13
+ }
14
+ }
package/src/tls.rs ADDED
@@ -0,0 +1,44 @@
1
+ use bytes::Bytes;
2
+ use napi::bindgen_prelude::Uint8Array;
3
+ use napi_derive::napi;
4
+
5
+ use crate::tunnel_builder::NgrokTlsTunnelBuilder;
6
+
7
+ #[napi]
8
+ #[allow(dead_code)]
9
+ impl NgrokTlsTunnelBuilder {
10
+ /// The domain to request for this edge.
11
+ #[napi]
12
+ pub fn domain(&mut self, domain: String) -> &Self {
13
+ self.tunnel_builder = self.tunnel_builder.clone().domain(domain);
14
+ self
15
+ }
16
+ /// Certificates to use for client authentication at the ngrok edge.
17
+ #[napi]
18
+ pub fn mutual_tlsca(&mut self, mutual_tlsca: Uint8Array) -> &Self {
19
+ self.tunnel_builder = self
20
+ .tunnel_builder
21
+ .clone()
22
+ .mutual_tlsca(Bytes::from(mutual_tlsca.to_vec()));
23
+ self
24
+ }
25
+ /// The key to use for TLS termination at the ngrok edge in PEM format.
26
+ #[napi]
27
+ pub fn key_pem(&mut self, key_pem: Uint8Array) -> &Self {
28
+ self.tunnel_builder = self
29
+ .tunnel_builder
30
+ .clone()
31
+ .key_pem(Bytes::from(key_pem.to_vec()));
32
+ self
33
+ }
34
+ /// The certificate to use for TLS termination at the ngrok edge in PEM
35
+ /// format.
36
+ #[napi]
37
+ pub fn cert_pem(&mut self, cert_pem: Uint8Array) -> &Self {
38
+ self.tunnel_builder = self
39
+ .tunnel_builder
40
+ .clone()
41
+ .cert_pem(Bytes::from(cert_pem.to_vec()));
42
+ self
43
+ }
44
+ }
package/src/tunnel.rs ADDED
@@ -0,0 +1,159 @@
1
+ use std::{
2
+ collections::HashMap,
3
+ sync::Arc,
4
+ };
5
+
6
+ use napi::bindgen_prelude::*;
7
+ use napi_derive::napi;
8
+ use ngrok::{
9
+ prelude::*,
10
+ tunnel::{
11
+ HttpTunnel,
12
+ LabeledTunnel,
13
+ ProtoTunnel,
14
+ TcpTunnel,
15
+ TlsTunnel,
16
+ UrlTunnel,
17
+ },
18
+ };
19
+ use tokio::sync::Mutex;
20
+ use tracing::debug;
21
+
22
+ macro_rules! make_tunnel_type {
23
+ // the common (non-labeled) branch
24
+ ($(#[$outer:meta])* $wrapper:ident, $tunnel:tt, common) => {
25
+ $(#[$outer])*
26
+ #[napi(custom_finalize)]
27
+ #[allow(dead_code)]
28
+ pub(crate) struct $wrapper {
29
+ id: String,
30
+ url: String,
31
+ proto: String,
32
+ inner: Arc<Mutex<$tunnel>>,
33
+ }
34
+
35
+ #[napi]
36
+ #[allow(dead_code)]
37
+ impl $wrapper {
38
+ pub(crate) fn new(raw_tunnel: $tunnel) -> Self {
39
+ $wrapper {
40
+ id: raw_tunnel.id().to_string(),
41
+ url: raw_tunnel.url().to_string(),
42
+ proto: raw_tunnel.proto().to_string(),
43
+ inner: Arc::new(Mutex::new(raw_tunnel)),
44
+ }
45
+ }
46
+
47
+ /// The URL that this tunnel backs.
48
+ #[napi]
49
+ pub fn url(&self) -> String {
50
+ self.url.clone()
51
+ }
52
+
53
+ /// The protocol of the endpoint that this tunnel backs.
54
+ #[napi]
55
+ pub fn proto(&self) -> String {
56
+ self.proto.clone()
57
+ }
58
+ }
59
+
60
+ make_tunnel_type!($wrapper, $tunnel);
61
+ };
62
+
63
+ // the labeled branch
64
+ ($(#[$outer:meta])* $wrapper:ident, $tunnel:tt, label) => {
65
+ $(#[$outer])*
66
+ #[napi(custom_finalize)]
67
+ #[allow(dead_code)]
68
+ pub(crate) struct $wrapper {
69
+ id: String,
70
+ labels: HashMap<String,String>,
71
+ inner: Arc<Mutex<$tunnel>>,
72
+ }
73
+
74
+ #[napi]
75
+ #[allow(dead_code)]
76
+ impl $wrapper {
77
+ pub(crate) fn new(raw_tunnel: $tunnel) -> Self {
78
+ $wrapper {
79
+ id: raw_tunnel.id().to_string(),
80
+ labels: raw_tunnel.labels().clone(),
81
+ inner: Arc::new(Mutex::new(raw_tunnel)),
82
+ }
83
+ }
84
+
85
+ /// The labels this tunnel was started with.
86
+ #[napi]
87
+ pub fn labels(&self) -> HashMap<String, String> {
88
+ self.labels.clone()
89
+ }
90
+ }
91
+
92
+ make_tunnel_type!($wrapper, $tunnel);
93
+ };
94
+
95
+ // all tunnels get these
96
+ ($wrapper:ident, $tunnel:tt) => {
97
+ #[napi]
98
+ #[allow(dead_code)]
99
+ impl $wrapper {
100
+ /// The ID of this tunnel, assigned by the remote server.
101
+ #[napi]
102
+ pub fn id(&self) -> String {
103
+ self.id.clone()
104
+ }
105
+
106
+ /// Forward incoming tunnel connections to the provided TCP address.
107
+ #[napi]
108
+ pub async fn forward_tcp(&self, addr: String) -> Result<()> {
109
+ self.inner
110
+ .lock()
111
+ .await
112
+ .forward_tcp(addr)
113
+ .await
114
+ .map_err(|e| Error::new(Status::GenericFailure, format!("cannot forward tcp: {e:?}")))
115
+ }
116
+
117
+ /// Forward incoming tunnel connections to the provided Unix socket path.
118
+ #[napi]
119
+ pub async fn forward_unix(&self, addr: String) -> Result<()> {
120
+ #[cfg(not(target_os = "windows"))]
121
+ {
122
+ self.inner
123
+ .lock()
124
+ .await
125
+ .forward_unix(addr)
126
+ .await
127
+ .map_err(|e| Error::new(Status::GenericFailure, format!("cannot forward unix: {e:?}")))
128
+ }
129
+ #[cfg(target_os = "windows")] {
130
+ Err(Error::new(Status::GenericFailure, format!("forward_unix not supported on windows")))
131
+ }
132
+ }
133
+ }
134
+
135
+ impl ObjectFinalize for $wrapper {
136
+ fn finalize(self, mut _env: Env) -> Result<()> {
137
+ debug!("$wrapper finalize");
138
+ Ok(())
139
+ }
140
+ }
141
+ };
142
+ }
143
+
144
+ make_tunnel_type! {
145
+ /// An ngrok tunnel backing an HTTP endpoint.
146
+ NgrokHttpTunnel, HttpTunnel, common
147
+ }
148
+ make_tunnel_type! {
149
+ /// An ngrok tunnel backing a TCP endpoint.
150
+ NgrokTcpTunnel, TcpTunnel, common
151
+ }
152
+ make_tunnel_type! {
153
+ /// An ngrok tunnel bcking a TLS endpoint.
154
+ NgrokTlsTunnel, TlsTunnel, common
155
+ }
156
+ make_tunnel_type! {
157
+ /// A labeled ngrok tunnel.
158
+ NgrokLabeledTunnel, LabeledTunnel, label
159
+ }
@@ -0,0 +1,141 @@
1
+ use std::str::FromStr;
2
+
3
+ use napi::bindgen_prelude::*;
4
+ use napi_derive::napi;
5
+ use ngrok::{
6
+ config::{
7
+ HttpTunnelBuilder,
8
+ LabeledTunnelBuilder,
9
+ ProxyProto,
10
+ TcpTunnelBuilder,
11
+ TlsTunnelBuilder,
12
+ },
13
+ prelude::*,
14
+ };
15
+ use tracing::debug;
16
+
17
+ use crate::tunnel::{
18
+ NgrokHttpTunnel,
19
+ NgrokLabeledTunnel,
20
+ NgrokTcpTunnel,
21
+ NgrokTlsTunnel,
22
+ };
23
+
24
+ macro_rules! make_tunnel_builder {
25
+ ($(#[$outer:meta])* $wrapper:ident, $builder:tt, $tunnel:tt, $mode:tt) => {
26
+ $(#[$outer])*
27
+ #[napi(custom_finalize)]
28
+ #[allow(dead_code)]
29
+ pub(crate) struct $wrapper {
30
+ pub(crate) tunnel_builder: $builder,
31
+ }
32
+
33
+ #[napi]
34
+ #[allow(dead_code)]
35
+ impl $wrapper {
36
+ pub(crate) fn new(raw_tunnel_builder: $builder) -> Self {
37
+ $wrapper {
38
+ tunnel_builder: raw_tunnel_builder,
39
+ }
40
+ }
41
+
42
+ /// Tunnel-specific opaque metadata. Viewable via the API.
43
+ #[napi]
44
+ pub fn metadata(&mut self, metadata: String) -> &Self {
45
+ self.tunnel_builder = self.tunnel_builder.clone().metadata(metadata);
46
+ self
47
+ }
48
+
49
+ /// Begin listening for new connections on this tunnel.
50
+ #[napi]
51
+ pub async fn listen(&self) -> Result<$tunnel> {
52
+ self.tunnel_builder
53
+ .listen()
54
+ .await
55
+ .map($tunnel::new)
56
+ .map_err(|e| {
57
+ Error::new(
58
+ Status::GenericFailure,
59
+ format!("failed to start tunnel: {e:?}")
60
+ )
61
+ })
62
+ }
63
+ }
64
+
65
+ impl ObjectFinalize for $wrapper {
66
+ fn finalize(self, mut _env: Env) -> Result<()> {
67
+ debug!("$wrapper finalize");
68
+ Ok(())
69
+ }
70
+ }
71
+
72
+ make_tunnel_builder!($mode, $wrapper);
73
+ };
74
+
75
+ (common, $wrapper:ty) => {
76
+ #[napi]
77
+ #[allow(dead_code)]
78
+ impl $wrapper {
79
+ /// Restriction placed on the origin of incoming connections to the edge to only allow these CIDR ranges.
80
+ /// Call multiple times to add additional CIDR ranges.
81
+ #[napi]
82
+ pub fn allow_cidr_string(&mut self, cidr: String) -> &Self {
83
+ self.tunnel_builder = self.tunnel_builder.clone().allow_cidr_string(cidr);
84
+ self
85
+ }
86
+ /// Restriction placed on the origin of incoming connections to the edge to deny these CIDR ranges.
87
+ /// Call multiple times to add additional CIDR ranges.
88
+ #[napi]
89
+ pub fn deny_cidr_string(&mut self, cidr: String) -> &Self {
90
+ self.tunnel_builder = self.tunnel_builder.clone().deny_cidr_string(cidr);
91
+ self
92
+ }
93
+ /// The version of PROXY protocol to use with this tunnel, None if not using.
94
+ #[napi]
95
+ pub fn proxy_proto(&mut self, proxy_proto: String) -> &Self {
96
+ self.tunnel_builder = self.tunnel_builder.clone().proxy_proto(
97
+ ProxyProto::from_str(proxy_proto.as_str())
98
+ .unwrap_or_else(|_| panic!("Unknown proxy protocol: {:?}", proxy_proto)),
99
+ );
100
+ self
101
+ }
102
+ /// Tunnel backend metadata. Viewable via the dashboard and API, but has no
103
+ /// bearing on tunnel behavior.
104
+ #[napi]
105
+ pub fn forwards_to(&mut self, forwards_to: String) -> &Self {
106
+ self.tunnel_builder = self.tunnel_builder.clone().forwards_to(forwards_to);
107
+ self
108
+ }
109
+ }
110
+ };
111
+
112
+ (label, $wrapper:ty) => {
113
+ #[napi]
114
+ #[allow(dead_code)]
115
+ impl $wrapper {
116
+ /// Add a label, value pair for this tunnel.
117
+ #[napi]
118
+ pub fn label(&mut self, label: String, value: String) -> &Self {
119
+ self.tunnel_builder = self.tunnel_builder.clone().label(label, value);
120
+ self
121
+ }
122
+ }
123
+ };
124
+ }
125
+
126
+ make_tunnel_builder! {
127
+ /// An ngrok tunnel backing an HTTP endpoint.
128
+ NgrokHttpTunnelBuilder, HttpTunnelBuilder, NgrokHttpTunnel, common
129
+ }
130
+ make_tunnel_builder! {
131
+ /// An ngrok tunnel backing a TCP endpoint.
132
+ NgrokTcpTunnelBuilder, TcpTunnelBuilder, NgrokTcpTunnel, common
133
+ }
134
+ make_tunnel_builder! {
135
+ /// An ngrok tunnel backing a TLS endpoint.
136
+ NgrokTlsTunnelBuilder, TlsTunnelBuilder, NgrokTlsTunnel, common
137
+ }
138
+ make_tunnel_builder! {
139
+ /// A labeled ngrok tunnel.
140
+ NgrokLabeledTunnelBuilder, LabeledTunnelBuilder, NgrokLabeledTunnel, label
141
+ }
package/trailer.js ADDED
@@ -0,0 +1,91 @@
1
+ //
2
+ // javascript trailer
3
+ //
4
+
5
+ const net = require('net');
6
+ const fs = require('fs');
7
+ const os = require('os');
8
+
9
+ async function defaultTunnel() {
10
+ // set up a default session and tunnel
11
+ var builder = new NgrokSessionBuilder();
12
+ builder.authtokenFromEnv();
13
+ var session = await builder.connect();
14
+ var tunnel = await session.httpEndpoint().listen();
15
+ tunnel.session = session; // surface to caller
16
+ return tunnel;
17
+ }
18
+
19
+ // get a ngrok-connect socket, optionally passing in a pre-existing tunnel
20
+ async function getSocket(tunnel) {
21
+ if (!tunnel) {
22
+ tunnel = await defaultTunnel();
23
+ }
24
+ // use tcp socket with random local port
25
+ const server = new net.Server();
26
+ server.listen(0);
27
+ // forward to this socket
28
+ tunnel.forwardTcp('localhost:' + server.address().port);
29
+ // surface to caller
30
+ server.tunnel = tunnel;
31
+ return server;
32
+ }
33
+
34
+ // bind a server to a ngrok tunnel, optionally passing in a pre-existing tunnel
35
+ async function ngrokListen(server, tunnel) {
36
+ if (!tunnel) {
37
+ tunnel = await defaultTunnel();
38
+ }
39
+ // todo: abstract socket on linux: https://stackoverflow.com/a/60014174
40
+ // todo: named pipe on windows: https://nodejs.org/api/net.html#ipc-support
41
+
42
+ // attempt unix socket
43
+ ngrokLinkUnix(tunnel, server)
44
+ .then(() => {})
45
+ .catch(function(err) {
46
+ console.debug("Using TCP socket. " + err);
47
+ // fallback to tcp socket
48
+ ngrokLinkTcp(tunnel, server);
49
+ });
50
+
51
+ server.tunnel = tunnel; // surface to caller
52
+ }
53
+
54
+ async function ngrokLinkTcp(tunnel, server) {
55
+ // random local port
56
+ server.listen(0);
57
+ // forward to socket
58
+ tunnel.forwardTcp('localhost:' + server.address().port);
59
+ }
60
+
61
+ async function ngrokLinkUnix(tunnel, server) {
62
+ const proposed = "tun-" + tunnel.id() + ".sock";
63
+ var filename;
64
+ try {
65
+ fs.accessSync(process.cwd(), fs.constants.W_OK);
66
+ filename = proposed;
67
+ } catch (err) {
68
+ console.debug("Cannot write to: " + process.cwd());
69
+ // try tmp. allow any exception to propagate
70
+ fs.accessSync(os.tmpdir(), fs.constants.W_OK);
71
+ filename = os.tmpdir() + proposed;
72
+ }
73
+
74
+ if (!filename) {
75
+ throw new Error("no writeable directory found");
76
+ }
77
+
78
+ // begin listening
79
+ server.listen({path: filename});
80
+ // tighten permissions
81
+ try {
82
+ fs.chmodSync(filename, fs.constants.S_IRWXU);
83
+ } catch (err) {
84
+ console.debug("Cannot change permissions of file: " + filename);
85
+ }
86
+ // forward tunnel
87
+ tunnel.forwardUnix(filename);
88
+ }
89
+
90
+ module.exports.getSocket = getSocket;
91
+ module.exports.listen = ngrokListen;