@ngrok/ngrok 0.0.11 → 0.1.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.
package/src/session.rs CHANGED
@@ -1,8 +1,13 @@
1
1
  use std::{
2
+ io,
2
3
  sync::Arc,
3
4
  time::Duration,
4
5
  };
5
6
 
7
+ use async_rustls::rustls::{
8
+ self,
9
+ ClientConfig,
10
+ };
6
11
  use napi::{
7
12
  bindgen_prelude::*,
8
13
  threadsafe_function::{
@@ -15,12 +20,16 @@ use napi::{
15
20
  use napi_derive::napi;
16
21
  use ngrok::{
17
22
  session::{
23
+ default_connect,
24
+ ConnectError,
18
25
  SessionBuilder,
19
26
  Update,
20
27
  },
28
+ tunnel::AcceptError,
21
29
  Session,
22
30
  };
23
31
  use parking_lot::Mutex as SyncMutex;
32
+ use rustls_pemfile::Item;
24
33
  use tokio::sync::Mutex;
25
34
  use tracing::{
26
35
  debug,
@@ -41,11 +50,16 @@ use crate::{
41
50
  const CLIENT_TYPE: &str = "library/official/nodejs";
42
51
  const VERSION: &str = env!("CARGO_PKG_VERSION");
43
52
 
53
+ // appease clippy
54
+ type TsfnOption = Option<Arc<Mutex<ThreadsafeFunction<Vec<String>, ErrorStrategy::Fatal>>>>;
55
+
44
56
  /// The builder for an ngrok session.
45
57
  #[napi]
46
58
  #[allow(dead_code)]
59
+ #[derive(Default)]
47
60
  struct NgrokSessionBuilder {
48
61
  raw_builder: Arc<SyncMutex<SessionBuilder>>,
62
+ disconnect_handler: TsfnOption,
49
63
  }
50
64
 
51
65
  #[napi]
@@ -59,6 +73,7 @@ impl NgrokSessionBuilder {
59
73
  raw_builder: Arc::new(SyncMutex::new(
60
74
  Session::builder().child_client(CLIENT_TYPE, VERSION),
61
75
  )),
76
+ ..Default::default()
62
77
  }
63
78
  }
64
79
 
@@ -147,6 +162,95 @@ impl NgrokSessionBuilder {
147
162
  self
148
163
  }
149
164
 
165
+ /// Configures the TLS certificate used to connect to the ngrok service while
166
+ /// establishing the session. Use this option only if you are connecting through
167
+ /// a man-in-the-middle or deep packet inspection proxy. Pass in the bytes of the certificate
168
+ /// to be used to validate the connection, then override the address to connect to via
169
+ /// the server_addr call.
170
+ ///
171
+ /// Roughly corresponds to the [root_cas parameter in the ngrok docs].
172
+ ///
173
+ /// [root_cas parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#root_cas
174
+ #[napi]
175
+ pub fn ca_cert(&mut self, cert_bytes: Uint8Array) -> &Self {
176
+ let mut root_store = rustls::RootCertStore::empty();
177
+ let mut cert_pem = io::Cursor::new(cert_bytes);
178
+ root_store.add_parsable_certificates(
179
+ rustls_pemfile::read_all(&mut cert_pem)
180
+ .expect("a valid root certificate")
181
+ .into_iter()
182
+ .filter_map(|it| match it {
183
+ Item::X509Certificate(bs) => Some(bs),
184
+ _ => None,
185
+ })
186
+ .collect::<Vec<_>>()
187
+ .as_slice(),
188
+ );
189
+
190
+ let tls_config = rustls::ClientConfig::builder()
191
+ .with_safe_defaults()
192
+ .with_root_certificates(root_store)
193
+ .with_no_client_auth();
194
+
195
+ let mut builder = self.raw_builder.lock();
196
+ *builder = builder.clone().tls_config(tls_config);
197
+ self
198
+ }
199
+
200
+ /// Configures a function which is called to after a disconnection to the
201
+ /// ngrok service. In the event of network disruptions, it will be called each time
202
+ /// the session reconnects. The handler is given the address that will be used to
203
+ /// connect the session to, e.g. "example.com:443", and the message from the error
204
+ /// that occurred. Returning true from the handler will cause the session to
205
+ /// reconnect, returning false will cause the Session to throw an uncaught error.
206
+ #[napi(ts_args_type = "handler: (addr: string, error: string) => boolean")]
207
+ pub fn handle_disconnection(&mut self, env: Env, handler: JsFunction) -> &Self {
208
+ // create threadsafe function
209
+ let tsfn = create_tsfn(env, handler);
210
+ self.disconnect_handler = Some(tsfn);
211
+ self.update_connector()
212
+ }
213
+
214
+ /// Update the connector callback in the upstream rust sdk.
215
+ fn update_connector(&mut self) -> &Self {
216
+ // register connect handler. this needs the return value, so cannot use call_tsfn().
217
+ let mut builder = self.raw_builder.lock();
218
+ // clone for move to connector function
219
+ let disconnect_handler = self.disconnect_handler.clone();
220
+ *builder = builder.clone().connector(
221
+ move |addr: String, tls_config: Arc<ClientConfig>, err: Option<AcceptError>| {
222
+ // clone for async move out of environment
223
+ let disconn_tsfn = disconnect_handler.clone();
224
+ async move {
225
+ // call disconnect javascript handler
226
+ if let Some(handler) = disconn_tsfn {
227
+ if let Some(err) = err.clone() {
228
+ // call javascript handler
229
+ let resp: Option<bool> = handler
230
+ .clone()
231
+ .lock()
232
+ .await
233
+ .call_async(vec![addr.clone(), err.to_string()])
234
+ .await
235
+ .map_err(|_e| ConnectError::Canceled)?;
236
+
237
+ if let Some(reconnect) = resp {
238
+ if !reconnect {
239
+ info!("Aborting connection to {addr}");
240
+ println!("Aborting connection to {addr}"); // still shown if this takes down the process
241
+ return Err(ConnectError::Canceled);
242
+ }
243
+ }
244
+ };
245
+ }
246
+ // call the upstream connector
247
+ default_connect(addr, tls_config, err).await
248
+ }
249
+ },
250
+ );
251
+ self
252
+ }
253
+
150
254
  /// Configures a function which is called when the ngrok service requests that
151
255
  /// this [Session] stops. Your application may choose to interpret this callback
152
256
  /// as a request to terminate the [Session] or the entire process.
@@ -165,7 +269,7 @@ impl NgrokSessionBuilder {
165
269
  let mut builder = self.raw_builder.lock();
166
270
  *builder = builder
167
271
  .clone()
168
- .handle_stop_command(move |_req| call_tsfn(tsfn.clone(), ()));
272
+ .handle_stop_command(move |_req| call_tsfn(tsfn.clone(), vec![()]));
169
273
  self
170
274
  }
171
275
 
@@ -188,7 +292,7 @@ impl NgrokSessionBuilder {
188
292
  let mut builder = self.raw_builder.lock();
189
293
  *builder = builder
190
294
  .clone()
191
- .handle_restart_command(move |_req| call_tsfn(tsfn.clone(), ()));
295
+ .handle_restart_command(move |_req| call_tsfn(tsfn.clone(), vec![()]));
192
296
  self
193
297
  }
194
298
 
@@ -214,14 +318,33 @@ impl NgrokSessionBuilder {
214
318
  version: req.version,
215
319
  permit_major_version: req.permit_major_version,
216
320
  };
217
- call_tsfn(tsfn.clone(), update)
321
+ call_tsfn(tsfn.clone(), vec![update])
218
322
  });
219
323
  self
220
324
  }
221
325
 
222
- // Omitting these configurations:
223
- // tls_config(&mut self, config: rustls::ClientConfig)
224
- // connector(&mut self, connect: ConnectFn)
326
+ /// Call the provided handler whenever a heartbeat response is received,
327
+ /// with the latency in milliseconds.
328
+ ///
329
+ /// If the handler returns an error, the heartbeat task will exit, resulting
330
+ /// in the session eventually dying as well.
331
+ #[napi(ts_args_type = "handler: (latency: number) => void")]
332
+ pub fn handle_heartbeat(&mut self, env: Env, handler: JsFunction) -> &Self {
333
+ // create threadsafe function
334
+ let tsfn = create_tsfn(env, handler);
335
+
336
+ // register heartbeat handler
337
+ let mut builder = self.raw_builder.lock();
338
+ *builder = builder
339
+ .clone()
340
+ .handle_heartbeat(move |latency: Option<Duration>| {
341
+ call_tsfn(
342
+ tsfn.clone(),
343
+ vec![latency.map(|d| u32::try_from(d.as_millis()).ok())],
344
+ )
345
+ });
346
+ self
347
+ }
225
348
 
226
349
  /// Attempt to establish an ngrok session using the current configuration.
227
350
  #[napi]
@@ -294,6 +417,16 @@ impl NgrokSession {
294
417
  }
295
418
  res
296
419
  }
420
+
421
+ /// Close the ngrok session.
422
+ #[napi]
423
+ pub async fn close(&self) -> Result<()> {
424
+ let mut session = self.raw_session.lock().clone();
425
+ session
426
+ .close()
427
+ .await
428
+ .map_err(|e| napi_err(format!("failed to close tunnel, {e:?}")))
429
+ }
297
430
  }
298
431
 
299
432
  impl ObjectFinalize for NgrokSession {
@@ -312,17 +445,16 @@ pub struct UpdateRequest {
312
445
  pub permit_major_version: bool,
313
446
  }
314
447
 
315
- /// Create a threadsafe function that has the given argument type and no return value.
316
448
  pub(crate) fn create_tsfn<A>(
317
449
  env: Env,
318
450
  handler: JsFunction,
319
- ) -> Arc<Mutex<ThreadsafeFunction<A, ErrorStrategy::Fatal>>>
451
+ ) -> Arc<Mutex<ThreadsafeFunction<Vec<A>, ErrorStrategy::Fatal>>>
320
452
  where
321
453
  A: ToNapiValue,
322
454
  {
323
455
  Arc::new(Mutex::new({
324
456
  let mut tsfn = handler
325
- .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<A>| Ok(vec![ctx.value]))
457
+ .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<Vec<A>>| Ok(ctx.value))
326
458
  .expect("Failed to create update callback function");
327
459
  // tell the runtime it can exit while this callback exists
328
460
  tsfn.unref(&env).expect("Failed to unref callback function");
@@ -331,10 +463,10 @@ where
331
463
  }
332
464
 
333
465
  /// Call a threadsafe function that has the given argument type and no return value.
334
- pub(crate) async fn call_tsfn<A>(
466
+ pub(crate) async fn call_tsfn<A, E>(
335
467
  tsfn: Arc<Mutex<ThreadsafeFunction<A, ErrorStrategy::Fatal>>>,
336
468
  arg: A,
337
- ) -> core::result::Result<(), String>
469
+ ) -> core::result::Result<(), E>
338
470
  where
339
471
  A: ToNapiValue,
340
472
  {
package/trailer.js CHANGED
@@ -24,6 +24,7 @@ async function ngrokBind(bind) {
24
24
  const tunnel = await this._listen();
25
25
  if (bind !== false) {
26
26
  const socket = await randomTcpSocket();
27
+ tunnel.socket = socket;
27
28
  defineTunnelHandle(tunnel, socket);
28
29
  }
29
30
  return tunnel;
@@ -74,12 +75,18 @@ async function defaultTunnel(bind) {
74
75
  }
75
76
 
76
77
  // Get a listenable ngrok tunnel, suitable for passing to net.Server.listen().
78
+ // Uses the NGROK_AUTHTOKEN environment variable to authenticate.
77
79
  async function listenable() {
78
80
  return await defaultTunnel();
79
81
  }
80
82
 
81
- // Bind a server to a ngrok tunnel, optionally passing in a pre-existing tunnel
83
+ // Bind a server to a new ngrok tunnel, optionally passing in a pre-existing tunnel instead.
84
+ // Uses the NGROK_AUTHTOKEN environment variable to authenticate if a new tunnel is created.
82
85
  async function ngrokListen(server, tunnel) {
86
+ if (tunnel && tunnel.socket) {
87
+ // close the default bound port
88
+ tunnel.socket.close();
89
+ }
83
90
  if (!tunnel) {
84
91
  // turn off automatic bind
85
92
  tunnel = await defaultTunnel(false);