@ngrok/ngrok 0.2.0 → 0.4.0

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.
Files changed (55) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/Cargo.toml +1 -1
  3. package/README.md +17 -10
  4. package/docs/assets/highlight.css +13 -6
  5. package/docs/assets/main.js +3 -3
  6. package/docs/assets/search.js +1 -1
  7. package/docs/assets/style.css +450 -362
  8. package/docs/classes/NgrokHttpTunnelBuilder.html +232 -199
  9. package/docs/classes/NgrokLabeledTunnelBuilder.html +81 -49
  10. package/docs/classes/NgrokSession.html +96 -66
  11. package/docs/classes/NgrokSessionBuilder.html +168 -138
  12. package/docs/classes/NgrokTcpTunnelBuilder.html +112 -80
  13. package/docs/classes/NgrokTlsTunnelBuilder.html +130 -98
  14. package/docs/classes/NgrokTunnel.html +233 -0
  15. package/docs/classes/UpdateRequest.html +66 -33
  16. package/docs/functions/authtoken.html +85 -0
  17. package/docs/functions/connect.html +85 -0
  18. package/docs/functions/consoleLog.html +47 -34
  19. package/docs/functions/disconnect.html +85 -0
  20. package/docs/functions/kill.html +80 -0
  21. package/docs/functions/listen.html +51 -37
  22. package/docs/functions/listenable.html +49 -40
  23. package/docs/functions/loggingCallback.html +53 -40
  24. package/docs/index.html +91 -101
  25. package/docs/interfaces/Config.html +605 -0
  26. package/docs/modules.html +67 -46
  27. package/examples/ngrok-connect-full.js +64 -0
  28. package/examples/ngrok-connect-minimal.js +16 -0
  29. package/examples/ngrok-http-full.js +9 -11
  30. package/examples/ngrok-http-minimum.js +8 -12
  31. package/examples/ngrok-labeled.js +5 -5
  32. package/examples/ngrok-listen.js +2 -2
  33. package/examples/ngrok-tcp.js +5 -6
  34. package/examples/ngrok-tls.js +5 -5
  35. package/examples/ngrok-typescript.ts +3 -3
  36. package/examples/ngrok-windows-pipe.js +1 -1
  37. package/examples/ngrok-winston.js +2 -2
  38. package/index.d.ts +233 -124
  39. package/index.js +119 -7
  40. package/package.json +17 -16
  41. package/src/config.rs +182 -0
  42. package/src/connect.rs +328 -0
  43. package/src/http.rs +5 -4
  44. package/src/lib.rs +2 -0
  45. package/src/session.rs +59 -4
  46. package/src/tls.rs +1 -1
  47. package/src/tunnel.rs +210 -136
  48. package/src/tunnel_builder.rs +11 -2
  49. package/trailer.d.ts +11 -7
  50. package/trailer.js +113 -2
  51. package/typedoc.json +3 -0
  52. package/docs/classes/NgrokHttpTunnel.html +0 -191
  53. package/docs/classes/NgrokLabeledTunnel.html +0 -179
  54. package/docs/classes/NgrokTcpTunnel.html +0 -191
  55. package/docs/classes/NgrokTlsTunnel.html +0 -191
package/src/session.rs CHANGED
@@ -5,6 +5,7 @@ use std::{
5
5
 
6
6
  use async_rustls::rustls::ClientConfig;
7
7
  use bytes::Bytes;
8
+ use lazy_static::lazy_static;
8
9
  use napi::{
9
10
  bindgen_prelude::*,
10
11
  threadsafe_function::{
@@ -49,13 +50,30 @@ const VERSION: &str = env!("CARGO_PKG_VERSION");
49
50
  // appease clippy
50
51
  type TsfnOption = Option<Arc<Mutex<ThreadsafeFunction<Vec<String>, ErrorStrategy::Fatal>>>>;
51
52
 
53
+ lazy_static! {
54
+ // Allow user to store a default auth token to use for all sessions
55
+ static ref AUTH_TOKEN: Mutex<Option<String>> = Mutex::new(None);
56
+ }
57
+
58
+ /// Set the default auth token to use for any future sessions.
59
+ #[napi]
60
+ #[allow(dead_code)]
61
+ pub async fn authtoken(authtoken: String) {
62
+ let mut token = AUTH_TOKEN.lock().await;
63
+ token.replace(authtoken);
64
+ }
65
+
52
66
  /// The builder for an ngrok session.
67
+ ///
68
+ /// @group Tunnel and Sessions
53
69
  #[napi]
54
70
  #[allow(dead_code)]
55
71
  #[derive(Default)]
56
- struct NgrokSessionBuilder {
72
+ pub(crate) struct NgrokSessionBuilder {
57
73
  raw_builder: Arc<SyncMutex<SessionBuilder>>,
74
+ connect_handler: TsfnOption,
58
75
  disconnect_handler: TsfnOption,
76
+ auth_token_set: bool,
59
77
  }
60
78
 
61
79
  #[napi]
@@ -86,6 +104,7 @@ impl NgrokSessionBuilder {
86
104
  pub fn authtoken(&mut self, authtoken: String) -> &Self {
87
105
  let mut builder = self.raw_builder.lock();
88
106
  *builder = builder.clone().authtoken(authtoken);
107
+ self.auth_token_set = true;
89
108
  self
90
109
  }
91
110
 
@@ -95,6 +114,7 @@ impl NgrokSessionBuilder {
95
114
  pub fn authtoken_from_env(&mut self) -> &Self {
96
115
  let mut builder = self.raw_builder.lock();
97
116
  *builder = builder.clone().authtoken_from_env();
117
+ self.auth_token_set = true;
98
118
  self
99
119
  }
100
120
 
@@ -188,15 +208,24 @@ impl NgrokSessionBuilder {
188
208
  self.update_connector()
189
209
  }
190
210
 
211
+ pub fn handle_connection(&mut self, env: Env, handler: JsFunction) -> &Self {
212
+ // create threadsafe function
213
+ let tsfn = create_tsfn(env, handler);
214
+ self.connect_handler = Some(tsfn);
215
+ self.update_connector()
216
+ }
217
+
191
218
  /// Update the connector callback in the upstream rust sdk.
192
219
  fn update_connector(&mut self) -> &Self {
193
220
  // register connect handler. this needs the return value, so cannot use call_tsfn().
194
221
  let mut builder = self.raw_builder.lock();
195
222
  // clone for move to connector function
223
+ let connect_handler = self.connect_handler.clone();
196
224
  let disconnect_handler = self.disconnect_handler.clone();
197
225
  *builder = builder.clone().connector(
198
226
  move |addr: String, tls_config: Arc<ClientConfig>, err: Option<AcceptError>| {
199
227
  // clone for async move out of environment
228
+ let conn_tsfn = connect_handler.clone();
200
229
  let disconn_tsfn = disconnect_handler.clone();
201
230
  async move {
202
231
  // call disconnect javascript handler
@@ -221,7 +250,24 @@ impl NgrokSessionBuilder {
221
250
  };
222
251
  }
223
252
  // call the upstream connector
224
- default_connect(addr, tls_config, err).await
253
+ let res = default_connect(addr, tls_config, err).await;
254
+
255
+ // call connect handler
256
+ if let Some(handler) = conn_tsfn {
257
+ let args = match &res {
258
+ Ok(_) => vec!["connected".to_string()],
259
+ Err(err) => vec!["closed".to_string(), err.to_string()],
260
+ };
261
+ // call javascript handler
262
+ handler
263
+ .clone()
264
+ .lock()
265
+ .await
266
+ .call_async(args)
267
+ .await
268
+ .map_err(|_e| ConnectError::Canceled)?;
269
+ }
270
+ res
225
271
  }
226
272
  },
227
273
  );
@@ -326,7 +372,13 @@ impl NgrokSessionBuilder {
326
372
  /// Attempt to establish an ngrok session using the current configuration.
327
373
  #[napi]
328
374
  pub async fn connect(&self) -> Result<NgrokSession> {
329
- let builder = self.raw_builder.lock().clone();
375
+ let mut builder = self.raw_builder.lock().clone();
376
+ // set default auth token if it exists
377
+ let default_auth_token = AUTH_TOKEN.lock().await;
378
+ if default_auth_token.is_some() && !self.auth_token_set {
379
+ builder = builder.authtoken(default_auth_token.as_ref().unwrap());
380
+ }
381
+ // connect to ngrok
330
382
  builder
331
383
  .connect()
332
384
  .await
@@ -341,8 +393,10 @@ impl NgrokSessionBuilder {
341
393
  }
342
394
 
343
395
  /// An ngrok session.
396
+ ///
397
+ /// @group Tunnel and Sessions
344
398
  #[napi(custom_finalize)]
345
- struct NgrokSession {
399
+ pub(crate) struct NgrokSession {
346
400
  #[allow(dead_code)]
347
401
  raw_session: Arc<SyncMutex<Session>>,
348
402
  }
@@ -413,6 +467,7 @@ impl ObjectFinalize for NgrokSession {
413
467
  }
414
468
  }
415
469
 
470
+ /// Container for UpdateRequest information.
416
471
  #[derive(Clone)]
417
472
  #[napi]
418
473
  pub struct UpdateRequest {
package/src/tls.rs CHANGED
@@ -23,7 +23,7 @@ impl NgrokTlsTunnelBuilder {
23
23
  .mutual_tlsca(Bytes::from(mutual_tlsca.to_vec()));
24
24
  self
25
25
  }
26
- /// The key to use for TLS termination at the ngrok edge in PEM format.
26
+ /// The certificate and key to use for TLS termination at the ngrok edge in PEM format.
27
27
  #[napi]
28
28
  pub fn termination(&mut self, cert_pem: Uint8Array, key_pem: Uint8Array) -> &Self {
29
29
  let mut builder = self.tunnel_builder.lock();
package/src/tunnel.rs CHANGED
@@ -32,7 +32,14 @@ lazy_static! {
32
32
  // tunnel references to be kept until explicit close to prevent nodejs gc from dropping them.
33
33
  // the tunnel wrapper object, and the underlying tunnel, both have references to the Session
34
34
  // so the Session is safe from premature dropping.
35
- static ref GLOBAL_TUNNELS: Mutex<HashMap<String,Arc<Mutex<dyn ExtendedTunnel>>>> = Mutex::new(HashMap::new());
35
+ static ref GLOBAL_TUNNELS: Mutex<HashMap<String,Arc<Storage>>> = Mutex::new(HashMap::new());
36
+ }
37
+
38
+ /// Stores the tunnel and session references to be kept until explicit close.
39
+ struct Storage {
40
+ tunnel: Arc<Mutex<dyn ExtendedTunnel>>,
41
+ session: Arc<Mutex<Session>>,
42
+ url: Option<String>,
36
43
  }
37
44
 
38
45
  /// The TunnelExt cannot be turned into an object since it contains generics, so implementing
@@ -43,26 +50,34 @@ pub trait ExtendedTunnel: Tunnel {
43
50
  async fn fwd_pipe(&mut self, addr: String) -> core::result::Result<(), io::Error>;
44
51
  }
45
52
 
53
+ /// An ngrok tunnel.
54
+ ///
55
+ /// @group Tunnel and Sessions
56
+ #[napi(custom_finalize)]
57
+ #[allow(dead_code)]
58
+ pub(crate) struct NgrokTunnel {
59
+ id: String,
60
+ forwards_to: String,
61
+ metadata: String,
62
+ url: Option<String>,
63
+ proto: Option<String>,
64
+ session: Session,
65
+ labels: HashMap<String, String>,
66
+ }
67
+
46
68
  macro_rules! make_tunnel_type {
47
69
  // the common (non-labeled) branch
48
70
  ($(#[$outer:meta])* $wrapper:ident, $tunnel:tt, common) => {
49
71
 
50
72
  $(#[$outer])*
51
- #[napi(custom_finalize)]
52
73
  #[allow(dead_code)]
53
74
  pub(crate) struct $wrapper {
54
- id: String,
55
- forwards_to: String,
56
- metadata: String,
57
- url: String,
58
- proto: String,
59
- session: Session,
60
75
  }
61
76
 
62
77
  #[napi]
63
78
  #[allow(dead_code)]
64
79
  impl $wrapper {
65
- pub(crate) async fn new(session: Session, raw_tunnel: $tunnel) -> Self {
80
+ pub(crate) async fn new_tunnel(session: Session, raw_tunnel: $tunnel) -> NgrokTunnel {
66
81
  let id = raw_tunnel.id().to_string();
67
82
  let forwards_to = raw_tunnel.forwards_to().to_string();
68
83
  let metadata = raw_tunnel.metadata().to_string();
@@ -70,28 +85,22 @@ macro_rules! make_tunnel_type {
70
85
  let proto = raw_tunnel.proto().to_string();
71
86
  info!("Created tunnel {id:?} with url {url:?}");
72
87
  // keep a tunnel reference until an explicit call to close to prevent nodejs gc dropping it
73
- GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Mutex::new(raw_tunnel)));
74
- $wrapper {
88
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Storage {
89
+ tunnel: Arc::new(Mutex::new(raw_tunnel)),
90
+ session: Arc::new(Mutex::new(session.clone())),
91
+ url: Some(url.clone()),
92
+ }));
93
+ // create the user-facing object
94
+ NgrokTunnel {
75
95
  id,
76
96
  forwards_to,
77
97
  metadata,
78
- url,
79
- proto,
98
+ url: Some(url),
99
+ proto: Some(proto),
80
100
  session,
101
+ labels: HashMap::new(),
81
102
  }
82
103
  }
83
-
84
- /// The URL that this tunnel backs.
85
- #[napi]
86
- pub fn url(&self) -> String {
87
- self.url.clone()
88
- }
89
-
90
- /// The protocol of the endpoint that this tunnel backs.
91
- #[napi]
92
- pub fn proto(&self) -> String {
93
- self.proto.clone()
94
- }
95
104
  }
96
105
 
97
106
  make_tunnel_type!($wrapper, $tunnel);
@@ -99,42 +108,36 @@ macro_rules! make_tunnel_type {
99
108
 
100
109
  // the labeled branch
101
110
  ($(#[$outer:meta])* $wrapper:ident, $tunnel:tt, label) => {
102
- $(#[$outer])*
103
- #[napi(custom_finalize)]
104
111
  #[allow(dead_code)]
105
112
  pub(crate) struct $wrapper {
106
- id: String,
107
- forwards_to: String,
108
- metadata: String,
109
- labels: HashMap<String,String>,
110
- session: Session,
111
113
  }
112
114
 
113
115
  #[napi]
114
116
  #[allow(dead_code)]
115
117
  impl $wrapper {
116
- pub(crate) async fn new(session: Session, raw_tunnel: $tunnel) -> Self {
118
+ pub(crate) async fn new_tunnel(session: Session, raw_tunnel: $tunnel) -> NgrokTunnel {
117
119
  let id = raw_tunnel.id().to_string();
118
120
  let forwards_to = raw_tunnel.forwards_to().to_string();
119
121
  let metadata = raw_tunnel.metadata().to_string();
120
122
  let labels = raw_tunnel.labels().clone();
121
123
  info!("Created tunnel {id:?} with labels {labels:?}");
122
124
  // keep a tunnel reference until an explicit call to close to prevent nodejs gc dropping it
123
- GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Mutex::new(raw_tunnel)));
124
- $wrapper {
125
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Storage {
126
+ tunnel: Arc::new(Mutex::new(raw_tunnel)),
127
+ session: Arc::new(Mutex::new(session.clone())),
128
+ url: None,
129
+ }));
130
+ // create the user-facing object
131
+ NgrokTunnel {
125
132
  id,
126
133
  forwards_to,
127
134
  metadata,
128
- labels,
135
+ url: None,
136
+ proto: None,
129
137
  session,
138
+ labels,
130
139
  }
131
140
  }
132
-
133
- /// The labels this tunnel was started with.
134
- #[napi]
135
- pub fn labels(&self) -> HashMap<String, String> {
136
- self.labels.clone()
137
- }
138
141
  }
139
142
 
140
143
  make_tunnel_type!($wrapper, $tunnel);
@@ -151,127 +154,198 @@ macro_rules! make_tunnel_type {
151
154
  self.forward_pipe(addr).await
152
155
  }
153
156
  }
157
+ };
158
+ }
154
159
 
155
- #[napi]
156
- #[allow(dead_code)]
157
- impl $wrapper {
158
- /// Returns a tunnel's unique ID.
159
- #[napi]
160
- pub fn id(&self) -> String {
161
- self.id.clone()
162
- }
160
+ #[napi]
161
+ #[allow(dead_code)]
162
+ impl NgrokTunnel {
163
+ /// The URL that this tunnel backs.
164
+ #[napi]
165
+ pub fn url(&self) -> Option<String> {
166
+ self.url.clone()
167
+ }
163
168
 
164
- /// Returns a human-readable string presented in the ngrok dashboard
165
- /// and the Tunnels API. Use the [HttpTunnelBuilder::forwards_to],
166
- /// [TcpTunnelBuilder::forwards_to], etc. to set this value
167
- /// explicitly.
168
- #[napi]
169
- pub fn forwards_to(&self) -> String {
170
- self.forwards_to.clone()
171
- }
169
+ /// The protocol of the endpoint that this tunnel backs.
170
+ #[napi]
171
+ pub fn proto(&self) -> Option<String> {
172
+ self.proto.clone()
173
+ }
172
174
 
173
- /// Returns the arbitrary metadata string for this tunnel.
174
- #[napi]
175
- pub fn metadata(&self) -> String {
176
- self.metadata.clone()
177
- }
175
+ /// The labels this tunnel was started with.
176
+ #[napi]
177
+ pub fn labels(&self) -> HashMap<String, String> {
178
+ self.labels.clone()
179
+ }
178
180
 
179
- /// Forward incoming tunnel connections to the provided TCP address.
180
- #[napi]
181
- pub async fn forward_tcp(&self, addr: String) -> Result<()> {
182
- info!("Tunnel {:?} TCP forwarding to {addr:?}", &self.id);
183
- // we must clone the Arc before locking so we have a local reference
184
- // to the mutex to unlock if this struct is dropped.
185
- let arc = GLOBAL_TUNNELS.lock().await
186
- .get(&self.id)
187
- .ok_or(napi_err("Tunnel is no longer running"))?
188
- .clone(); // required clone
189
-
190
- // doing this as a seperate statement so the GLOBAL_TUNNELS lock is dropped
191
- let res = arc
192
- .lock()
193
- .await
194
- .fwd_tcp(addr)
195
- .await
196
- .map_err(|e| napi_err(format!("cannot forward tcp: {e:?}")));
197
- debug!("forward_tcp returning");
198
- res
199
- }
181
+ /// Returns a tunnel's unique ID.
182
+ #[napi]
183
+ pub fn id(&self) -> String {
184
+ self.id.clone()
185
+ }
200
186
 
201
- /// Forward incoming tunnel connections to the provided file socket path.
202
- /// On Linux/Darwin addr can be a unix domain socket path, e.g. "/tmp/ngrok.sock"
203
- /// On Windows addr can be a named pipe, e.e. "\\.\pipe\an_ngrok_pipe"
204
- #[napi]
205
- pub async fn forward_pipe(&self, addr: String) -> Result<()> {
206
- info!("Tunnel {:?} Pipe forwarding to {addr:?}", &self.id);
207
- // we must clone the Arc before locking so we have a local reference
208
- // to the mutex to unlock if this struct is dropped.
209
- let arc = GLOBAL_TUNNELS.lock().await
210
- .get(&self.id)
211
- .ok_or(napi_err("Tunnel is no longer running"))?
212
- .clone(); // required clone
213
-
214
- // doing this as a seperate statement so the GLOBAL_TUNNELS lock is dropped
215
- let res = arc
216
- .lock()
217
- .await
218
- .fwd_pipe(addr)
219
- .await
220
- .map_err(|e| napi_err(format!("cannot forward pipe: {e:?}")));
221
- debug!("forward_pipe returning");
222
- res
223
- }
187
+ /// Returns a human-readable string presented in the ngrok dashboard
188
+ /// and the Tunnels API. Use the [HttpTunnelBuilder::forwards_to],
189
+ /// [TcpTunnelBuilder::forwards_to], etc. to set this value
190
+ /// explicitly.
191
+ #[napi]
192
+ pub fn forwards_to(&self) -> String {
193
+ self.forwards_to.clone()
194
+ }
224
195
 
225
- /// Close the tunnel.
226
- ///
227
- /// This is an RPC call that must be `.await`ed.
228
- /// It is equivalent to calling `Session::close_tunnel` with this
229
- /// tunnel's ID.
230
- #[napi]
231
- pub async fn close(&self) -> Result<()> {
232
- debug!("{} closing, id: {}", stringify!($wrapper), self.id);
233
-
234
- // we may not be able to lock our reference to the tunnel due to the forward_* calls which
235
- // continuously accept-loop while the tunnel is active, so calling close on the Session.
236
- let res = self.session.close_tunnel(self.id.clone())
237
- .await
238
- .map_err(|e| napi_err(format!("error closing tunnel: {e:?}")));
239
-
240
- // drop our internal reference to the tunnel after awaiting close
241
- GLOBAL_TUNNELS.lock().await.remove(&self.id);
242
-
243
- res
244
- }
245
- }
196
+ /// Returns the arbitrary metadata string for this tunnel.
197
+ #[napi]
198
+ pub fn metadata(&self) -> String {
199
+ self.metadata.clone()
200
+ }
246
201
 
247
- #[allow(unused_mut)]
248
- impl ObjectFinalize for $wrapper {
249
- fn finalize(mut self, _env: Env) -> Result<()> {
250
- debug!("{} finalize, id: {}", stringify!($wrapper), self.id);
251
- Ok(())
252
- }
253
- }
254
- };
202
+ /// Forward incoming tunnel connections to the provided TCP address.
203
+ #[napi]
204
+ pub async fn forward_tcp(&self, addr: String) -> Result<()> {
205
+ forward_tcp(&self.id, addr).await
206
+ }
207
+
208
+ /// Forward incoming tunnel connections to the provided file socket path.
209
+ /// On Linux/Darwin addr can be a unix domain socket path, e.g. "/tmp/ngrok.sock"
210
+ /// On Windows addr can be a named pipe, e.e. "\\.\pipe\an_ngrok_pipe"
211
+ #[napi]
212
+ pub async fn forward_pipe(&self, addr: String) -> Result<()> {
213
+ forward_pipe(&self.id, addr).await
214
+ }
215
+
216
+ /// Close the tunnel.
217
+ ///
218
+ /// This is an RPC call that must be `.await`ed.
219
+ /// It is equivalent to calling `Session::close_tunnel` with this
220
+ /// tunnel's ID.
221
+ #[napi]
222
+ pub async fn close(&self) -> Result<()> {
223
+ debug!("{} closing, id: {}", stringify!($wrapper), self.id);
224
+
225
+ // we may not be able to lock our reference to the tunnel due to the forward_* calls which
226
+ // continuously accept-loop while the tunnel is active, so calling close on the Session.
227
+ let res = self
228
+ .session
229
+ .close_tunnel(self.id.clone())
230
+ .await
231
+ .map_err(|e| napi_err(format!("error closing tunnel: {e:?}")));
232
+
233
+ // drop our internal reference to the tunnel after awaiting close
234
+ GLOBAL_TUNNELS.lock().await.remove(&self.id);
235
+
236
+ res
237
+ }
238
+ }
239
+
240
+ #[allow(unused_mut)]
241
+ impl ObjectFinalize for NgrokTunnel {
242
+ fn finalize(mut self, _env: Env) -> Result<()> {
243
+ debug!("{} finalize, id: {}", stringify!($wrapper), self.id);
244
+ Ok(())
245
+ }
255
246
  }
256
247
 
257
248
  make_tunnel_type! {
258
249
  /// An ngrok tunnel backing an HTTP endpoint.
250
+ ///
251
+ /// @group Tunnels
259
252
  NgrokHttpTunnel, HttpTunnel, common
260
253
  }
261
254
  make_tunnel_type! {
262
255
  /// An ngrok tunnel backing a TCP endpoint.
256
+ ///
257
+ /// @group Tunnels
263
258
  NgrokTcpTunnel, TcpTunnel, common
264
259
  }
265
260
  make_tunnel_type! {
266
261
  /// An ngrok tunnel bcking a TLS endpoint.
262
+ ///
263
+ /// @group Tunnels
267
264
  NgrokTlsTunnel, TlsTunnel, common
268
265
  }
269
266
  make_tunnel_type! {
270
267
  /// A labeled ngrok tunnel.
268
+ ///
269
+ /// @group Tunnels
271
270
  NgrokLabeledTunnel, LabeledTunnel, label
272
271
  }
273
272
 
273
+ pub async fn forward_tcp(id: &String, addr: String) -> Result<()> {
274
+ info!("Tunnel {id:?} TCP forwarding to {addr:?}");
275
+ let res = get_storage_by_id(id)
276
+ .await?
277
+ .tunnel
278
+ .lock()
279
+ .await
280
+ .fwd_tcp(addr)
281
+ .await
282
+ .map_err(|e| napi_err(format!("cannot forward tcp: {e:?}")));
283
+ debug!("forward_tcp returning");
284
+ res
285
+ }
286
+
287
+ pub async fn forward_pipe(id: &String, addr: String) -> Result<()> {
288
+ info!("Tunnel {id:?} Pipe forwarding to {addr:?}");
289
+ let res = get_storage_by_id(id)
290
+ .await?
291
+ .tunnel
292
+ .lock()
293
+ .await
294
+ .fwd_pipe(addr)
295
+ .await
296
+ .map_err(|e| napi_err(format!("cannot forward pipe: {e:?}")));
297
+ debug!("forward_pipe returning");
298
+ res
299
+ }
300
+
301
+ /// Get url using the tunnel id
302
+ pub(crate) async fn get_url(id: &String) -> Option<String> {
303
+ GLOBAL_TUNNELS
304
+ .lock()
305
+ .await
306
+ .get(id)
307
+ .and_then(|s| s.url.clone())
308
+ }
309
+
310
+ async fn get_storage_by_id(id: &String) -> Result<Arc<Storage>> {
311
+ // we must clone the Arc before any locking so there is a local reference
312
+ // to the mutex to unlock if the tunnel wrapper struct is dropped.
313
+ Ok(GLOBAL_TUNNELS
314
+ .lock()
315
+ .await
316
+ .get(id)
317
+ .ok_or(napi_err("Tunnel is no longer running"))?
318
+ .clone()) // required clone
319
+ }
320
+
274
321
  /// Delete any reference to the tunnel id
275
322
  pub(crate) async fn remove_global_tunnel(id: &String) {
276
323
  GLOBAL_TUNNELS.lock().await.remove(id);
277
324
  }
325
+
326
+ /// Close a tunnel with the given url, or all tunnels if no url is defined.
327
+ pub(crate) async fn close_url(url: Option<String>) -> Result<()> {
328
+ let mut close_ids: Vec<String> = vec![];
329
+ let tunnels = GLOBAL_TUNNELS.lock().await;
330
+ for (id, storage) in tunnels.iter() {
331
+ debug!("tunnel: {}", id);
332
+ if url.as_ref().is_none() || url == storage.url {
333
+ debug!("closing tunnel: {}", id);
334
+ storage
335
+ .session
336
+ .lock()
337
+ .await
338
+ .close_tunnel(id)
339
+ .await
340
+ .map_err(|e| napi_err(format!("error closing tunnel: {e:?}")))?;
341
+ close_ids.push(id.clone());
342
+ }
343
+ }
344
+ drop(tunnels); // unlock GLOBAL_TUNNELS
345
+
346
+ // remove references entirely
347
+ for id in close_ids {
348
+ remove_global_tunnel(&id).await;
349
+ }
350
+ Ok(())
351
+ }
@@ -26,6 +26,7 @@ use crate::{
26
26
  NgrokLabeledTunnel,
27
27
  NgrokTcpTunnel,
28
28
  NgrokTlsTunnel,
29
+ NgrokTunnel,
29
30
  },
30
31
  };
31
32
 
@@ -59,7 +60,7 @@ macro_rules! make_tunnel_builder {
59
60
 
60
61
  /// Begin listening for new connections on this tunnel.
61
62
  #[napi]
62
- pub async fn listen(&self, _bind: Option<bool>) -> Result<$tunnel> {
63
+ pub async fn listen(&self, _bind: Option<bool>) -> Result<NgrokTunnel> {
63
64
  let session = self.session.lock().clone();
64
65
  let tun = self.tunnel_builder.lock().clone();
65
66
  let result = tun
@@ -69,7 +70,7 @@ macro_rules! make_tunnel_builder {
69
70
 
70
71
  // create the wrapping tunnel object via its async new()
71
72
  match result {
72
- Ok(raw_tun) => Ok($tunnel::new(session, raw_tun).await),
73
+ Ok(raw_tun) => Ok($tunnel::new_tunnel(session, raw_tun).await),
73
74
  Err(val) => Err(val),
74
75
  }
75
76
  }
@@ -143,17 +144,25 @@ macro_rules! make_tunnel_builder {
143
144
 
144
145
  make_tunnel_builder! {
145
146
  /// An ngrok tunnel backing an HTTP endpoint.
147
+ ///
148
+ /// @group Tunnel Builders
146
149
  NgrokHttpTunnelBuilder, HttpTunnelBuilder, NgrokHttpTunnel, common
147
150
  }
148
151
  make_tunnel_builder! {
149
152
  /// An ngrok tunnel backing a TCP endpoint.
153
+ ///
154
+ /// @group Tunnel Builders
150
155
  NgrokTcpTunnelBuilder, TcpTunnelBuilder, NgrokTcpTunnel, common
151
156
  }
152
157
  make_tunnel_builder! {
153
158
  /// An ngrok tunnel backing a TLS endpoint.
159
+ ///
160
+ /// @group Tunnel Builders
154
161
  NgrokTlsTunnelBuilder, TlsTunnelBuilder, NgrokTlsTunnel, common
155
162
  }
156
163
  make_tunnel_builder! {
157
164
  /// A labeled ngrok tunnel.
165
+ ///
166
+ /// @group Tunnel Builders
158
167
  NgrokLabeledTunnelBuilder, LabeledTunnelBuilder, NgrokLabeledTunnel, label
159
168
  }
package/trailer.d.ts CHANGED
@@ -1,12 +1,16 @@
1
- /** Generate, or convert a given tunnel, into one that can be passed into net.Server.listen(). */
2
- export function listenable(
3
- tunnel?: NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel
4
- ): NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel;
5
- /** Start the given net.Server listening to a generated, or passed in, tunnel. */
1
+ /**
2
+ * Get a listenable ngrok tunnel, suitable for passing to net.Server.listen().
3
+ * Uses the NGROK_AUTHTOKEN environment variable to authenticate.
4
+ */
5
+ export function listenable(): NgrokTunnel;
6
+ /**
7
+ * Start the given net.Server listening to a generated, or passed in, tunnel.
8
+ * Uses the NGROK_AUTHTOKEN environment variable to authenticate if a new tunnel is created.
9
+ */
6
10
  export function listen(
7
11
  server: import("net").Server,
8
- tunnel?: NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel
9
- ): NgrokHttpTunnel | NgrokTcpTunnel | NgrokTlsTunnel | NgrokLabeledTunnel;
12
+ tunnel?: NgrokTunnel
13
+ ): NgrokTunnel;
10
14
  /**
11
15
  * Register a console.log callback for ngrok INFO logging.
12
16
  * Optionally set the logging level to one of ERROR, WARN, INFO, DEBUG, or TRACE.