@ngrok/ngrok 0.2.0 → 0.3.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 (52) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/Cargo.toml +1 -1
  3. package/README.md +16 -9
  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 +447 -361
  8. package/docs/classes/NgrokHttpTunnel.html +112 -77
  9. package/docs/classes/NgrokHttpTunnelBuilder.html +235 -199
  10. package/docs/classes/NgrokLabeledTunnel.html +107 -72
  11. package/docs/classes/NgrokLabeledTunnelBuilder.html +84 -49
  12. package/docs/classes/NgrokSession.html +99 -66
  13. package/docs/classes/NgrokSessionBuilder.html +171 -138
  14. package/docs/classes/NgrokTcpTunnel.html +112 -77
  15. package/docs/classes/NgrokTcpTunnelBuilder.html +115 -80
  16. package/docs/classes/NgrokTlsTunnel.html +112 -77
  17. package/docs/classes/NgrokTlsTunnelBuilder.html +133 -98
  18. package/docs/classes/UpdateRequest.html +69 -33
  19. package/docs/functions/authtoken.html +88 -0
  20. package/docs/functions/connect.html +88 -0
  21. package/docs/functions/consoleLog.html +50 -34
  22. package/docs/functions/disconnect.html +88 -0
  23. package/docs/functions/kill.html +83 -0
  24. package/docs/functions/listen.html +52 -36
  25. package/docs/functions/listenable.html +51 -35
  26. package/docs/functions/loggingCallback.html +56 -40
  27. package/docs/index.html +94 -101
  28. package/docs/interfaces/Config.html +608 -0
  29. package/docs/modules.html +74 -47
  30. package/examples/ngrok-connect-full.js +64 -0
  31. package/examples/ngrok-connect-minimal.js +16 -0
  32. package/examples/ngrok-http-full.js +9 -11
  33. package/examples/ngrok-http-minimum.js +8 -12
  34. package/examples/ngrok-labeled.js +5 -5
  35. package/examples/ngrok-listen.js +2 -2
  36. package/examples/ngrok-tcp.js +5 -6
  37. package/examples/ngrok-tls.js +5 -5
  38. package/examples/ngrok-typescript.ts +3 -3
  39. package/examples/ngrok-windows-pipe.js +1 -1
  40. package/examples/ngrok-winston.js +2 -2
  41. package/index.d.ts +234 -15
  42. package/index.js +118 -3
  43. package/package.json +16 -16
  44. package/src/config.rs +182 -0
  45. package/src/connect.rs +328 -0
  46. package/src/http.rs +5 -4
  47. package/src/lib.rs +2 -0
  48. package/src/session.rs +61 -4
  49. package/src/tls.rs +1 -1
  50. package/src/tunnel.rs +105 -37
  51. package/src/tunnel_builder.rs +8 -0
  52. package/trailer.js +113 -2
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 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 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,9 @@ impl ObjectFinalize for NgrokSession {
413
467
  }
414
468
  }
415
469
 
470
+ /// Container for UpdateRequest information.
471
+ ///
472
+ /// @group Sessions
416
473
  #[derive(Clone)]
417
474
  #[napi]
418
475
  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
@@ -70,7 +77,12 @@ macro_rules! make_tunnel_type {
70
77
  let proto = raw_tunnel.proto().to_string();
71
78
  info!("Created tunnel {id:?} with url {url:?}");
72
79
  // 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)));
80
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Storage {
81
+ tunnel: Arc::new(Mutex::new(raw_tunnel)),
82
+ session: Arc::new(Mutex::new(session.clone())),
83
+ url: Some(url.clone()),
84
+ }));
85
+ // create the user-facing object
74
86
  $wrapper {
75
87
  id,
76
88
  forwards_to,
@@ -120,7 +132,12 @@ macro_rules! make_tunnel_type {
120
132
  let labels = raw_tunnel.labels().clone();
121
133
  info!("Created tunnel {id:?} with labels {labels:?}");
122
134
  // 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)));
135
+ GLOBAL_TUNNELS.lock().await.insert(id.clone(), Arc::new(Storage {
136
+ tunnel: Arc::new(Mutex::new(raw_tunnel)),
137
+ session: Arc::new(Mutex::new(session.clone())),
138
+ url: None,
139
+ }));
140
+ // create the user-facing object
124
141
  $wrapper {
125
142
  id,
126
143
  forwards_to,
@@ -179,23 +196,7 @@ macro_rules! make_tunnel_type {
179
196
  /// Forward incoming tunnel connections to the provided TCP address.
180
197
  #[napi]
181
198
  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
+ forward_tcp(&self.id, addr).await
199
200
  }
200
201
 
201
202
  /// Forward incoming tunnel connections to the provided file socket path.
@@ -203,23 +204,7 @@ macro_rules! make_tunnel_type {
203
204
  /// On Windows addr can be a named pipe, e.e. "\\.\pipe\an_ngrok_pipe"
204
205
  #[napi]
205
206
  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
207
+ forward_pipe(&self.id, addr).await
223
208
  }
224
209
 
225
210
  /// Close the tunnel.
@@ -256,22 +241,105 @@ macro_rules! make_tunnel_type {
256
241
 
257
242
  make_tunnel_type! {
258
243
  /// An ngrok tunnel backing an HTTP endpoint.
244
+ ///
245
+ /// @group Tunnels
259
246
  NgrokHttpTunnel, HttpTunnel, common
260
247
  }
261
248
  make_tunnel_type! {
262
249
  /// An ngrok tunnel backing a TCP endpoint.
250
+ ///
251
+ /// @group Tunnels
263
252
  NgrokTcpTunnel, TcpTunnel, common
264
253
  }
265
254
  make_tunnel_type! {
266
255
  /// An ngrok tunnel bcking a TLS endpoint.
256
+ ///
257
+ /// @group Tunnels
267
258
  NgrokTlsTunnel, TlsTunnel, common
268
259
  }
269
260
  make_tunnel_type! {
270
261
  /// A labeled ngrok tunnel.
262
+ ///
263
+ /// @group Tunnels
271
264
  NgrokLabeledTunnel, LabeledTunnel, label
272
265
  }
273
266
 
267
+ pub async fn forward_tcp(id: &String, addr: String) -> Result<()> {
268
+ info!("Tunnel {id:?} TCP forwarding to {addr:?}");
269
+ let res = get_storage_by_id(id)
270
+ .await?
271
+ .tunnel
272
+ .lock()
273
+ .await
274
+ .fwd_tcp(addr)
275
+ .await
276
+ .map_err(|e| napi_err(format!("cannot forward tcp: {e:?}")));
277
+ debug!("forward_tcp returning");
278
+ res
279
+ }
280
+
281
+ pub async fn forward_pipe(id: &String, addr: String) -> Result<()> {
282
+ info!("Tunnel {id:?} Pipe forwarding to {addr:?}");
283
+ let res = get_storage_by_id(id)
284
+ .await?
285
+ .tunnel
286
+ .lock()
287
+ .await
288
+ .fwd_pipe(addr)
289
+ .await
290
+ .map_err(|e| napi_err(format!("cannot forward pipe: {e:?}")));
291
+ debug!("forward_pipe returning");
292
+ res
293
+ }
294
+
295
+ /// Delete any reference to the tunnel id
296
+ pub(crate) async fn get_url(id: &String) -> Option<String> {
297
+ GLOBAL_TUNNELS
298
+ .lock()
299
+ .await
300
+ .get(id)
301
+ .and_then(|s| s.url.clone())
302
+ }
303
+
304
+ async fn get_storage_by_id(id: &String) -> Result<Arc<Storage>> {
305
+ // we must clone the Arc before any locking so there is a local reference
306
+ // to the mutex to unlock if the tunnel wrapper struct is dropped.
307
+ Ok(GLOBAL_TUNNELS
308
+ .lock()
309
+ .await
310
+ .get(id)
311
+ .ok_or(napi_err("Tunnel is no longer running"))?
312
+ .clone()) // required clone
313
+ }
314
+
274
315
  /// Delete any reference to the tunnel id
275
316
  pub(crate) async fn remove_global_tunnel(id: &String) {
276
317
  GLOBAL_TUNNELS.lock().await.remove(id);
277
318
  }
319
+
320
+ /// Close a tunnel with the given url, or all tunnels if no url is defined.
321
+ pub(crate) async fn close_url(url: Option<String>) -> Result<()> {
322
+ let mut close_ids: Vec<String> = vec![];
323
+ let tunnels = GLOBAL_TUNNELS.lock().await;
324
+ for (id, storage) in tunnels.iter() {
325
+ debug!("tunnel: {}", id);
326
+ if url.as_ref().is_none() || url == storage.url {
327
+ debug!("closing tunnel: {}", id);
328
+ storage
329
+ .session
330
+ .lock()
331
+ .await
332
+ .close_tunnel(id)
333
+ .await
334
+ .map_err(|e| napi_err(format!("error closing tunnel: {e:?}")))?;
335
+ close_ids.push(id.clone());
336
+ }
337
+ }
338
+ drop(tunnels); // unlock GLOBAL_TUNNELS
339
+
340
+ // remove references entirely
341
+ for id in close_ids {
342
+ remove_global_tunnel(&id).await;
343
+ }
344
+ Ok(())
345
+ }
@@ -143,17 +143,25 @@ macro_rules! make_tunnel_builder {
143
143
 
144
144
  make_tunnel_builder! {
145
145
  /// An ngrok tunnel backing an HTTP endpoint.
146
+ ///
147
+ /// @group Tunnel Builders
146
148
  NgrokHttpTunnelBuilder, HttpTunnelBuilder, NgrokHttpTunnel, common
147
149
  }
148
150
  make_tunnel_builder! {
149
151
  /// An ngrok tunnel backing a TCP endpoint.
152
+ ///
153
+ /// @group Tunnel Builders
150
154
  NgrokTcpTunnelBuilder, TcpTunnelBuilder, NgrokTcpTunnel, common
151
155
  }
152
156
  make_tunnel_builder! {
153
157
  /// An ngrok tunnel backing a TLS endpoint.
158
+ ///
159
+ /// @group Tunnel Builders
154
160
  NgrokTlsTunnelBuilder, TlsTunnelBuilder, NgrokTlsTunnel, common
155
161
  }
156
162
  make_tunnel_builder! {
157
163
  /// A labeled ngrok tunnel.
164
+ ///
165
+ /// @group Tunnel Builders
158
166
  NgrokLabeledTunnelBuilder, LabeledTunnelBuilder, NgrokLabeledTunnel, label
159
167
  }
package/trailer.js CHANGED
@@ -183,6 +183,117 @@ function consoleLog(level) {
183
183
  }, level);
184
184
  }
185
185
 
186
- module.exports.listenable = listenable;
187
- module.exports.listen = ngrokListen;
186
+ // wrap connect with code to vectorize and split out functions
187
+ const _connect = connect;
188
+ async function ngrokConnect(config) {
189
+ if (Number.isInteger(config) || typeof config === "string" || config instanceof String) {
190
+ address = String(config);
191
+ if (!address.includes(":")) {
192
+ address = `localhost:${address}`;
193
+ }
194
+ config = { addr: address };
195
+ }
196
+ // Convert addr to string to allow for numeric port numbers
197
+ const addr = config["addr"];
198
+ if (Number.isInteger(addr)) config["addr"] = "localhost:" + String(config["addr"]);
199
+ // convert scalar values to arrays to meet what napi-rs expects
200
+ [
201
+ "auth",
202
+ "basic_auth",
203
+ "ip_restriction.allow_cidrs",
204
+ "ip_restriction.deny_cidrs",
205
+ "labels",
206
+ "oauth.allow_domains",
207
+ "oauth.allow_emails",
208
+ "oauth.scopes",
209
+ "oidc.scopes",
210
+ "oidc.allow_domains",
211
+ "oidc.allow_emails",
212
+ "request_header.add",
213
+ "request_header.remove",
214
+ "response_header.add",
215
+ "response_header.remove",
216
+ "schemes",
217
+ ].forEach((key) => {
218
+ vectorize(config, key);
219
+ });
220
+ // convert dotted values to underscores for backwards compatibility
221
+ [
222
+ "ip_restriction.allow_cidrs",
223
+ "ip_restriction.deny_cidrs",
224
+ "oauth.allow_domains",
225
+ "oauth.allow_emails",
226
+ "oauth.scopes",
227
+ "oauth.provider",
228
+ "oidc.client_id",
229
+ "oidc.client_secret",
230
+ "oidc.scopes",
231
+ "oidc.issuer_url",
232
+ "oidc.allow_domains",
233
+ "oidc.allow_emails",
234
+ "request_header.add",
235
+ "request_header.remove",
236
+ "response_header.add",
237
+ "response_header.remove",
238
+ "verify_webhook.provider",
239
+ "verify_webhook.secret",
240
+ ].forEach((key) => {
241
+ undot(config, key);
242
+ });
243
+ // break out the logging callback function to meet what napi-rs expects
244
+ var on_log_event;
245
+ if (config["onLogEvent"]) {
246
+ const onLogEvent = config.onLogEvent;
247
+ on_log_event = (level, target, message) => {
248
+ onLogEvent(`${level} ${target} - ${message}`);
249
+ };
250
+ config["onLogEvent"] = true;
251
+ }
252
+ // break out the status change callback functions to what napi-rs expects
253
+ var on_connection, on_disconnection;
254
+ if (config["onStatusChange"]) {
255
+ const onStatusChange = config.onStatusChange;
256
+ on_connection = (status, err) => {
257
+ onStatusChange(status);
258
+ };
259
+ on_disconnection = (addr, err) => {
260
+ onStatusChange("closed");
261
+ };
262
+ config["onStatusChange"] = true;
263
+ }
264
+ // call into rust
265
+ return await _connect(config, on_log_event, on_connection, on_disconnection);
266
+ }
267
+
268
+ function undot(config, dotKey) {
269
+ const noDotKey = dotKey.replace(".", "_");
270
+ if (config[dotKey] == null) return; // no dotKey value, done
271
+ if (config[noDotKey] == null) {
272
+ // nothing at destination, just set and be done
273
+ config[noDotKey] = config[dotKey];
274
+ return;
275
+ }
276
+ if (config[dotKey] instanceof Array && config[noDotKey] instanceof Array) {
277
+ // merge arrays
278
+ for (const obj of config[dotKey]) {
279
+ config[noDotKey].push(obj);
280
+ }
281
+ }
282
+ // destination exists and is not an array, do nothing so noDotKey can take precedence
283
+ }
284
+
285
+ function vectorize(config, key) {
286
+ // backwards compatible keys are passed in, check the new style as well
287
+ const noDotKey = key.replace(".", "_");
288
+ if (key != noDotKey) vectorize(config, noDotKey);
289
+
290
+ if (config[key] == null) return; // no value, done
291
+ if (!(config[key] instanceof Array)) {
292
+ config[key] = [config[key]];
293
+ }
294
+ }
295
+
296
+ module.exports.connect = ngrokConnect;
188
297
  module.exports.consoleLog = consoleLog;
298
+ module.exports.listen = ngrokListen;
299
+ module.exports.listenable = listenable;