@ngrok/ngrok 0.1.1 → 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 (135) hide show
  1. package/.prettierrc.json +3 -0
  2. package/CHANGELOG.md +10 -0
  3. package/Cargo.toml +1 -1
  4. package/README.md +51 -10
  5. package/RELEASE.md +3 -3
  6. package/docs/assets/highlight.css +13 -6
  7. package/docs/assets/main.js +3 -3
  8. package/docs/assets/search.js +1 -1
  9. package/docs/assets/style.css +447 -362
  10. package/docs/classes/NgrokHttpTunnel.html +112 -77
  11. package/docs/classes/NgrokHttpTunnelBuilder.html +235 -199
  12. package/docs/classes/NgrokLabeledTunnel.html +107 -72
  13. package/docs/classes/NgrokLabeledTunnelBuilder.html +84 -49
  14. package/docs/classes/NgrokSession.html +99 -66
  15. package/docs/classes/NgrokSessionBuilder.html +171 -138
  16. package/docs/classes/NgrokTcpTunnel.html +112 -77
  17. package/docs/classes/NgrokTcpTunnelBuilder.html +115 -80
  18. package/docs/classes/NgrokTlsTunnel.html +112 -77
  19. package/docs/classes/NgrokTlsTunnelBuilder.html +133 -98
  20. package/docs/classes/UpdateRequest.html +69 -33
  21. package/docs/functions/authtoken.html +88 -0
  22. package/docs/functions/connect.html +88 -0
  23. package/docs/functions/consoleLog.html +50 -34
  24. package/docs/functions/disconnect.html +88 -0
  25. package/docs/functions/kill.html +83 -0
  26. package/docs/functions/listen.html +52 -36
  27. package/docs/functions/listenable.html +51 -35
  28. package/docs/functions/loggingCallback.html +56 -40
  29. package/docs/index.html +115 -84
  30. package/docs/interfaces/Config.html +608 -0
  31. package/docs/modules.html +74 -47
  32. package/examples/express/ngrok-express-quickstart.js +11 -0
  33. package/examples/express/ngrok-express.js +28 -0
  34. package/examples/express/package.json +7 -0
  35. package/examples/fastify/ngrok-fastify.js +26 -0
  36. package/examples/fastify/package.json +7 -0
  37. package/examples/hapi/ngrok-hapi.js +35 -0
  38. package/examples/hapi/package.json +7 -0
  39. package/examples/koa/ngrok-koa.js +12 -0
  40. package/examples/koa/package.json +7 -0
  41. package/examples/nestjs/.eslintrc.js +25 -0
  42. package/examples/nestjs/.prettierrc +4 -0
  43. package/examples/nestjs/README.md +73 -0
  44. package/examples/nestjs/nest-cli.json +8 -0
  45. package/examples/nestjs/package-lock.json +12138 -0
  46. package/examples/nestjs/package.json +70 -0
  47. package/examples/nestjs/src/app.controller.spec.ts +22 -0
  48. package/examples/nestjs/src/app.controller.ts +12 -0
  49. package/examples/nestjs/src/app.module.ts +10 -0
  50. package/examples/nestjs/src/app.service.ts +8 -0
  51. package/examples/nestjs/src/main.ts +17 -0
  52. package/examples/nestjs/test/app.e2e-spec.ts +24 -0
  53. package/examples/nestjs/test/jest-e2e.json +9 -0
  54. package/examples/nestjs/tsconfig.build.json +4 -0
  55. package/examples/nestjs/tsconfig.json +21 -0
  56. package/examples/nextjs/next.config.js +12 -0
  57. package/examples/nextjs/ngrok.config.js +23 -0
  58. package/examples/nextjs/package.json +6 -0
  59. package/examples/nextjs/pages/index.js +5 -0
  60. package/examples/ngrok-connect-full.js +64 -0
  61. package/examples/ngrok-connect-minimal.js +16 -0
  62. package/examples/ngrok-http-full.js +28 -22
  63. package/examples/ngrok-http-minimum.js +17 -13
  64. package/examples/ngrok-labeled.js +22 -18
  65. package/examples/ngrok-listen.js +6 -7
  66. package/examples/ngrok-tcp.js +22 -19
  67. package/examples/ngrok-tls.js +23 -20
  68. package/examples/ngrok-typescript.ts +32 -27
  69. package/examples/ngrok-windows-pipe.js +22 -14
  70. package/examples/ngrok-winston.js +9 -9
  71. package/examples/package.json +11 -0
  72. package/examples/remix/.eslintrc.js +4 -0
  73. package/examples/remix/README.md +53 -0
  74. package/examples/remix/app/entry.client.tsx +18 -0
  75. package/examples/remix/app/entry.server.tsx +101 -0
  76. package/examples/remix/app/root.tsx +20 -0
  77. package/examples/remix/app/routes/_index.tsx +30 -0
  78. package/examples/remix/ngrok.config.js +16 -0
  79. package/examples/remix/package.json +30 -0
  80. package/examples/remix/public/favicon.ico +0 -0
  81. package/examples/remix/remix.config.js +16 -0
  82. package/examples/remix/remix.env.d.ts +2 -0
  83. package/examples/remix/tsconfig.json +22 -0
  84. package/examples/svelte/README.md +38 -0
  85. package/examples/svelte/jsconfig.json +17 -0
  86. package/examples/svelte/ngrok.config.cjs +18 -0
  87. package/examples/svelte/package.json +22 -0
  88. package/examples/svelte/src/app.d.ts +12 -0
  89. package/examples/svelte/src/app.html +12 -0
  90. package/examples/svelte/src/routes/+page.svelte +2 -0
  91. package/examples/svelte/static/favicon.png +0 -0
  92. package/examples/svelte/svelte.config.js +14 -0
  93. package/examples/svelte/vite.config.js +6 -0
  94. package/examples/vue/.vscode/extensions.json +3 -0
  95. package/examples/vue/README.md +40 -0
  96. package/examples/vue/env.d.ts +1 -0
  97. package/examples/vue/index.html +13 -0
  98. package/examples/vue/ngrok.config.ts +18 -0
  99. package/examples/vue/package.json +25 -0
  100. package/examples/vue/public/favicon.ico +0 -0
  101. package/examples/vue/src/App.vue +47 -0
  102. package/examples/vue/src/assets/base.css +74 -0
  103. package/examples/vue/src/assets/logo.svg +1 -0
  104. package/examples/vue/src/assets/main.css +35 -0
  105. package/examples/vue/src/components/HelloWorld.vue +40 -0
  106. package/examples/vue/src/components/TheWelcome.vue +86 -0
  107. package/examples/vue/src/components/WelcomeItem.vue +86 -0
  108. package/examples/vue/src/components/icons/IconCommunity.vue +7 -0
  109. package/examples/vue/src/components/icons/IconDocumentation.vue +7 -0
  110. package/examples/vue/src/components/icons/IconEcosystem.vue +7 -0
  111. package/examples/vue/src/components/icons/IconSupport.vue +7 -0
  112. package/examples/vue/src/components/icons/IconTooling.vue +19 -0
  113. package/examples/vue/src/main.ts +6 -0
  114. package/examples/vue/tsconfig.json +16 -0
  115. package/examples/vue/tsconfig.node.json +8 -0
  116. package/examples/vue/vite.config.ts +15 -0
  117. package/flake.nix +1 -1
  118. package/index.d.ts +243 -19
  119. package/index.js +145 -29
  120. package/package.json +20 -21
  121. package/post-build.js +18 -11
  122. package/scripts/gc-node-drop.js +38 -31
  123. package/scripts/gc-rust-drop.js +44 -38
  124. package/src/config.rs +182 -0
  125. package/src/connect.rs +328 -0
  126. package/src/http.rs +5 -4
  127. package/src/lib.rs +2 -0
  128. package/src/session.rs +61 -4
  129. package/src/tls.rs +1 -1
  130. package/src/tunnel.rs +105 -37
  131. package/src/tunnel_builder.rs +8 -0
  132. package/trailer.d.ts +9 -4
  133. package/trailer.js +140 -28
  134. package/examples/ngrok-express-quickstart.js +0 -11
  135. package/examples/ngrok-express.js +0 -26
package/src/connect.rs ADDED
@@ -0,0 +1,328 @@
1
+ use lazy_static::lazy_static;
2
+ use napi::{
3
+ bindgen_prelude::*,
4
+ JsObject,
5
+ };
6
+ use napi_derive::napi;
7
+ use tokio::sync::Mutex;
8
+ use tracing::warn;
9
+
10
+ use crate::{
11
+ config::Config,
12
+ logging::logging_callback,
13
+ napi_err,
14
+ session::{
15
+ NgrokSession,
16
+ NgrokSessionBuilder,
17
+ },
18
+ tunnel,
19
+ };
20
+
21
+ lazy_static! {
22
+ // Save a user-facing NgrokSession to use for connect use cases
23
+ pub(crate) static ref SESSION: Mutex<Option<NgrokSession>> = Mutex::new(None);
24
+ }
25
+
26
+ /// Single string configuration
27
+ macro_rules! plumb {
28
+ ($builder:tt, $config:tt, $name:tt) => {
29
+ plumb!($builder, $config, $name, $name)
30
+ };
31
+ ($builder:tt, $config:tt, $name:tt, $config_name:tt) => {
32
+ if let Some(ref $name) = $config.$config_name {
33
+ $builder.$name($name.clone());
34
+ }
35
+ };
36
+ }
37
+
38
+ /// Boolean configuration
39
+ macro_rules! plumb_bool {
40
+ ($builder:tt, $config:tt, $name:tt) => {
41
+ plumb_bool!($builder, $config, $name, $name)
42
+ };
43
+ ($builder:tt, $config:tt, $name:tt, $config_name:tt) => {
44
+ if let Some($name) = $config.$config_name {
45
+ if $name {
46
+ $builder.$name();
47
+ }
48
+ }
49
+ };
50
+ }
51
+
52
+ /// Vector configuration
53
+ macro_rules! plumb_vec {
54
+ ($builder:tt, $config:tt, $name:tt) => {
55
+ plumb_vec!($builder, $config, $name, $name)
56
+ };
57
+ ($builder:tt, $config:tt, $name:tt, $config_name:tt) => {
58
+ if let Some(ref $name) = $config.$config_name {
59
+ for val in $name {
60
+ $builder.$name(val.clone());
61
+ }
62
+ }
63
+ };
64
+ ($builder:tt, $config:tt, $name:tt, $config_name:tt, vecu8) => {
65
+ if let Some(ref $name) = $config.$config_name {
66
+ for val in $name {
67
+ $builder.$name(Uint8Array::new(val.as_bytes().to_vec()));
68
+ }
69
+ }
70
+ };
71
+ ($builder:tt, $config:tt, $name:tt, $config_name:tt, $split:tt) => {
72
+ if let Some(ref $name) = $config.$config_name {
73
+ for val in $name {
74
+ let (a, b) = val
75
+ .split_once($split)
76
+ .expect("split of value failed: ${val}");
77
+ $builder.$name(a.to_string(), b.to_string());
78
+ }
79
+ }
80
+ };
81
+ }
82
+
83
+ /// All non-labeled tunnels have these common configuration options
84
+ macro_rules! config_common {
85
+ ($builder:tt, $config:tt) => {
86
+ plumb!($builder, $config, metadata);
87
+ plumb_vec!($builder, $config, allow_cidr);
88
+ plumb_vec!($builder, $config, deny_cidr);
89
+ plumb!($builder, $config, proxy_proto);
90
+ plumb!($builder, $config, forwards_to);
91
+ };
92
+ }
93
+
94
+ /// Transform a json object configuration into a tunnel
95
+ #[napi(
96
+ ts_args_type = "config: Config|string|number",
97
+ ts_return_type = "Promise<string>"
98
+ )]
99
+ #[allow(dead_code)]
100
+ pub fn connect(
101
+ env: Env,
102
+ mut cfg: Config,
103
+ on_log_event: Option<JsFunction>,
104
+ on_connection: Option<JsFunction>,
105
+ on_disconnection: Option<JsFunction>,
106
+ ) -> Result<JsObject> {
107
+ // do logging configuration before anything else
108
+ if on_log_event.is_some() {
109
+ logging_callback(env, on_log_event, None)?;
110
+ }
111
+ warn_unused(&cfg);
112
+ set_defaults(&mut cfg);
113
+
114
+ // session configuration
115
+ let mut s_builder = NgrokSessionBuilder::new();
116
+ plumb!(s_builder, cfg, authtoken);
117
+ plumb_bool!(s_builder, cfg, authtoken_from_env);
118
+ plumb!(s_builder, cfg, metadata, session_metadata);
119
+ if let Some(func) = on_connection {
120
+ s_builder.handle_connection(env, func);
121
+ }
122
+ if let Some(func) = on_disconnection {
123
+ s_builder.handle_disconnection(env, func);
124
+ }
125
+
126
+ // no longer need Env, hand off to async for tunnel creation, returning the promise to nodejs.
127
+ env.spawn_future(async_connect(s_builder, cfg))
128
+ }
129
+
130
+ /// Connect the session, configure and start the tunnel
131
+ async fn async_connect(s_builder: NgrokSessionBuilder, config: Config) -> Result<String> {
132
+ // Using a singleton session for connect use cases
133
+ let mut opt = SESSION.lock().await;
134
+ if opt.is_none() {
135
+ opt.replace(s_builder.connect().await?);
136
+ }
137
+ let session = opt.as_ref().unwrap();
138
+
139
+ // tunnel configuration dispatch
140
+ let proto = config.proto.as_ref().unwrap();
141
+ let id = match proto.as_str() {
142
+ "http" => http_endpoint(session, &config).await?,
143
+ "tcp" => tcp_endpoint(session, &config).await?,
144
+ "tls" => tls_endpoint(session, &config).await?,
145
+ "labeled" => labeled_tunnel(session, &config).await?,
146
+ _ => return Err(napi_err(format!("unhandled protocol {proto}"))),
147
+ };
148
+
149
+ let url = tunnel::get_url(&id).await.expect("no url found");
150
+
151
+ // move forwarding to another task
152
+ if let Some(addr) = config.addr {
153
+ tokio::spawn(async move {
154
+ if addr.starts_with("pipe:") {
155
+ tunnel::forward_pipe(&id, addr.clone().split_off(5)).await
156
+ } else {
157
+ tunnel::forward_tcp(&id, addr).await
158
+ }
159
+ });
160
+ }
161
+
162
+ Ok(url)
163
+ }
164
+
165
+ /// HTTP Tunnel configuration
166
+ async fn http_endpoint(session: &NgrokSession, cfg: &Config) -> Result<String> {
167
+ let mut bld = session.http_endpoint();
168
+ config_common!(bld, cfg);
169
+ plumb_vec!(bld, cfg, scheme, schemes);
170
+ plumb!(bld, cfg, domain, hostname); // synonym for domain
171
+ plumb!(bld, cfg, domain);
172
+ plumb_vec!(bld, cfg, mutual_tlsca, mutual_tls_cas, vecu8);
173
+ plumb_bool!(bld, cfg, compression);
174
+ plumb_bool!(bld, cfg, websocket_tcp_conversion, websocket_tcp_converter);
175
+ plumb_vec!(bld, cfg, request_header, request_header_add, ":");
176
+ plumb_vec!(bld, cfg, response_header, response_header_add, ":");
177
+ plumb_vec!(bld, cfg, remove_request_header, request_header_remove);
178
+ plumb_vec!(bld, cfg, remove_response_header, response_header_remove);
179
+ plumb_vec!(bld, cfg, basic_auth, basic_auth, ":");
180
+ // circuit breaker
181
+ if let Some(circuit_breaker) = cfg.circuit_breaker {
182
+ bld.circuit_breaker(circuit_breaker);
183
+ }
184
+ // oauth
185
+ if let Some(ref provider) = cfg.oauth_provider {
186
+ bld.oauth(
187
+ provider.clone(),
188
+ cfg.oauth_allow_emails.clone(),
189
+ cfg.oauth_allow_domains.clone(),
190
+ cfg.oauth_scopes.clone(),
191
+ );
192
+ }
193
+ // oidc
194
+ if let Some(ref issuer_url) = cfg.oidc_issuer_url {
195
+ if cfg.oidc_client_id.is_none() {
196
+ return Err(napi_err("Missing client id for oidc"));
197
+ }
198
+ if cfg.oidc_client_secret.is_none() {
199
+ return Err(napi_err("Missing client secret for oidc"));
200
+ }
201
+ bld.oidc(
202
+ issuer_url.clone(),
203
+ cfg.oidc_client_id.clone().unwrap(),
204
+ cfg.oidc_client_secret.clone().unwrap(),
205
+ cfg.oidc_allow_emails.clone(),
206
+ cfg.oidc_allow_domains.clone(),
207
+ cfg.oidc_scopes.clone(),
208
+ );
209
+ }
210
+ // webhook verification
211
+ if let Some(ref provider) = cfg.verify_webhook_provider {
212
+ if let Some(ref secret) = cfg.verify_webhook_secret {
213
+ bld.webhook_verification(provider.clone(), secret.clone());
214
+ } else {
215
+ return Err(napi_err("Missing secret for webhook verification"));
216
+ }
217
+ }
218
+ Ok(bld.listen(None).await?.id())
219
+ }
220
+
221
+ /// TCP Tunnel configuration
222
+ async fn tcp_endpoint(session: &NgrokSession, cfg: &Config) -> Result<String> {
223
+ let mut bld = session.tcp_endpoint();
224
+ config_common!(bld, cfg);
225
+ plumb!(bld, cfg, remote_addr);
226
+ Ok(bld.listen(None).await?.id())
227
+ }
228
+
229
+ /// TLS Tunnel configuration
230
+ async fn tls_endpoint(session: &NgrokSession, cfg: &Config) -> Result<String> {
231
+ let mut bld = session.tls_endpoint();
232
+ config_common!(bld, cfg);
233
+ plumb!(bld, cfg, domain, hostname); // synonym for domain
234
+ plumb!(bld, cfg, domain);
235
+ plumb_vec!(bld, cfg, mutual_tlsca, mutual_tls_cas, vecu8);
236
+ if let Some(ref crt) = cfg.crt {
237
+ if let Some(ref key) = cfg.key {
238
+ bld.termination(
239
+ Uint8Array::new(crt.as_bytes().to_vec()),
240
+ Uint8Array::new(key.as_bytes().to_vec()),
241
+ );
242
+ } else {
243
+ return Err(napi_err("Missing key for tls termination"));
244
+ }
245
+ }
246
+ Ok(bld.listen(None).await?.id())
247
+ }
248
+
249
+ /// Labeled Tunnel configuration
250
+ async fn labeled_tunnel(session: &NgrokSession, cfg: &Config) -> Result<String> {
251
+ let mut bld = session.labeled_tunnel();
252
+ plumb!(bld, cfg, metadata);
253
+ plumb_vec!(bld, cfg, label, labels, ":");
254
+ Ok(bld.listen(None).await?.id())
255
+ }
256
+
257
+ /// Set the expected defaults for configuration values
258
+ fn set_defaults(config: &mut Config) {
259
+ if config.proto.is_none() {
260
+ config.proto.replace("http".to_string());
261
+ }
262
+ if config.addr.is_none() {
263
+ if let Some(port) = &config.port {
264
+ config.addr.replace(port.to_string());
265
+ } else if let Some(host) = &config.host {
266
+ config.addr.replace(host.clone());
267
+ } else {
268
+ config.addr.replace("80".to_string());
269
+ }
270
+ }
271
+ }
272
+
273
+ /// Warn about unused configuration values
274
+ fn warn_unused(config: &Config) {
275
+ if config.bin_path.is_some() {
276
+ warn!("bin_path is unused");
277
+ }
278
+ if config.config_path.is_some() {
279
+ warn!("config_path is unused");
280
+ }
281
+ if config.host_header.is_some() {
282
+ warn!("host_header is unused");
283
+ }
284
+ if config.inspect.is_some() {
285
+ warn!("inspect is unused");
286
+ }
287
+ if config.name.is_some() {
288
+ warn!("name is unused");
289
+ }
290
+ if config.region.is_some() {
291
+ warn!("region is unused");
292
+ }
293
+ if let Some(ref schemes) = config.schemes {
294
+ if schemes.len() > 1 {
295
+ warn!("Multiple schemes set, only last one will be used");
296
+ }
297
+ }
298
+ if config.subdomain.is_some() {
299
+ warn!("subdomain is unused");
300
+ }
301
+ if config.terminate_at.is_some() {
302
+ warn!("terminate_at is unused");
303
+ }
304
+ if config.web_addr.is_some() {
305
+ warn!("web_addr is unused");
306
+ }
307
+ }
308
+
309
+ /// Close a tunnel with the given url, or all tunnels if no url is defined.
310
+ #[napi]
311
+ #[allow(dead_code)]
312
+ pub async fn disconnect(url: Option<String>) -> Result<()> {
313
+ tunnel::close_url(url.clone()).await?;
314
+
315
+ // if closing every tunnel, remove any stored session
316
+ if url.as_ref().is_none() {
317
+ SESSION.lock().await.take();
318
+ }
319
+
320
+ Ok(())
321
+ }
322
+
323
+ /// Close all tunnels.
324
+ #[napi]
325
+ #[allow(dead_code)]
326
+ pub async fn kill() -> Result<()> {
327
+ disconnect(None).await
328
+ }
package/src/http.rs CHANGED
@@ -64,28 +64,28 @@ impl NgrokHttpTunnelBuilder {
64
64
  self
65
65
  }
66
66
 
67
- /// with_request_header adds a header to all requests to this edge.
67
+ /// request_header adds a header to all requests to this edge.
68
68
  #[napi]
69
69
  pub fn request_header(&mut self, name: String, value: String) -> &Self {
70
70
  let mut builder = self.tunnel_builder.lock();
71
71
  *builder = builder.clone().request_header(name, value);
72
72
  self
73
73
  }
74
- /// with_response_header adds a header to all responses coming from this edge.
74
+ /// response_header adds a header to all responses coming from this edge.
75
75
  #[napi]
76
76
  pub fn response_header(&mut self, name: String, value: String) -> &Self {
77
77
  let mut builder = self.tunnel_builder.lock();
78
78
  *builder = builder.clone().response_header(name, value);
79
79
  self
80
80
  }
81
- /// with_remove_request_header removes a header from requests to this edge.
81
+ /// remove_request_header removes a header from requests to this edge.
82
82
  #[napi]
83
83
  pub fn remove_request_header(&mut self, name: String) -> &Self {
84
84
  let mut builder = self.tunnel_builder.lock();
85
85
  *builder = builder.clone().remove_request_header(name);
86
86
  self
87
87
  }
88
- /// with_remove_response_header removes a header from responses from this edge.
88
+ /// remove_response_header removes a header from responses from this edge.
89
89
  #[napi]
90
90
  pub fn remove_response_header(&mut self, name: String) -> &Self {
91
91
  let mut builder = self.tunnel_builder.lock();
@@ -104,6 +104,7 @@ impl NgrokHttpTunnelBuilder {
104
104
 
105
105
  /// OAuth configuration.
106
106
  /// If not called, OAuth is disabled.
107
+ /// https://ngrok.com/docs/cloud-edge/modules/oauth/
107
108
  #[napi]
108
109
  pub fn oauth(
109
110
  &mut self,
package/src/lib.rs CHANGED
@@ -3,6 +3,8 @@ use napi::{
3
3
  Status,
4
4
  };
5
5
 
6
+ pub mod config;
7
+ pub mod connect;
6
8
  pub mod http;
7
9
  pub mod logging;
8
10
  pub mod session;
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();