@ngrok/ngrok 0.0.6 → 0.0.8

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 (51) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/CONTRIBUTING.md +4 -4
  3. package/Cargo.toml +5 -2
  4. package/README.md +11 -11
  5. package/docs/.nojekyll +1 -0
  6. package/docs/assets/highlight.css +71 -0
  7. package/docs/assets/main.js +58 -0
  8. package/docs/assets/search.js +1 -0
  9. package/docs/assets/style.css +1280 -0
  10. package/docs/classes/NgrokHttpTunnel.html +189 -0
  11. package/docs/classes/NgrokHttpTunnelBuilder.html +440 -0
  12. package/docs/classes/NgrokLabeledTunnel.html +177 -0
  13. package/docs/classes/NgrokLabeledTunnelBuilder.html +130 -0
  14. package/docs/classes/NgrokSession.html +142 -0
  15. package/docs/classes/NgrokSessionBuilder.html +303 -0
  16. package/docs/classes/NgrokTcpTunnel.html +189 -0
  17. package/docs/classes/NgrokTcpTunnelBuilder.html +199 -0
  18. package/docs/classes/NgrokTlsTunnel.html +189 -0
  19. package/docs/classes/NgrokTlsTunnelBuilder.html +235 -0
  20. package/docs/classes/UpdateRequest.html +92 -0
  21. package/docs/functions/consoleLog.html +73 -0
  22. package/docs/functions/listen.html +74 -0
  23. package/docs/functions/listenable.html +72 -0
  24. package/docs/functions/loggingCallback.html +91 -0
  25. package/docs/index.html +129 -0
  26. package/docs/modules.html +79 -0
  27. package/examples/ngrok-http-full.js +18 -8
  28. package/examples/ngrok-http-minimum.js +1 -3
  29. package/examples/ngrok-labeled.js +2 -4
  30. package/examples/ngrok-tcp.js +4 -6
  31. package/examples/ngrok-tls.js +6 -8
  32. package/examples/ngrok-typescript.ts +64 -0
  33. package/examples/ngrok-winston.js +24 -0
  34. package/index.d.ts +193 -41
  35. package/index.js +114 -27
  36. package/package.json +25 -17
  37. package/post-build.js +23 -16
  38. package/scripts/gc-node-drop.js +42 -0
  39. package/scripts/gc-rust-drop.js +47 -0
  40. package/src/http.rs +64 -42
  41. package/src/lib.rs +10 -0
  42. package/src/logging.rs +134 -0
  43. package/src/session.rs +239 -63
  44. package/src/tcp.rs +2 -1
  45. package/src/tls.rs +10 -18
  46. package/src/tunnel.rs +146 -22
  47. package/src/tunnel_builder.rs +46 -28
  48. package/trailer.d.ts +9 -0
  49. package/trailer.js +111 -25
  50. package/tsconfig.json +6 -0
  51. package/examples/ngrok-get-socket.js +0 -13
package/src/session.rs CHANGED
@@ -1,41 +1,48 @@
1
- use std::time::Duration;
1
+ use std::{
2
+ sync::Arc,
3
+ time::Duration,
4
+ };
2
5
 
3
- use napi::bindgen_prelude::*;
6
+ use napi::{
7
+ bindgen_prelude::*,
8
+ threadsafe_function::{
9
+ ErrorStrategy,
10
+ ThreadSafeCallContext,
11
+ ThreadsafeFunction,
12
+ ThreadsafeFunctionCallMode,
13
+ },
14
+ };
4
15
  use napi_derive::napi;
5
16
  use ngrok::{
6
- session::SessionBuilder,
17
+ session::{
18
+ SessionBuilder,
19
+ Update,
20
+ },
7
21
  Session,
8
22
  };
9
- use tracing::debug;
10
- use tracing_subscriber::{
11
- self,
12
- fmt::format::FmtSpan,
23
+ use parking_lot::Mutex as SyncMutex;
24
+ use tokio::sync::Mutex;
25
+ use tracing::{
26
+ debug,
27
+ info,
13
28
  };
14
29
 
15
- use crate::tunnel_builder::{
16
- NgrokHttpTunnelBuilder,
17
- NgrokLabeledTunnelBuilder,
18
- NgrokTcpTunnelBuilder,
19
- NgrokTlsTunnelBuilder,
30
+ use crate::{
31
+ napi_err,
32
+ tunnel::remove_global_tunnel,
33
+ tunnel_builder::{
34
+ NgrokHttpTunnelBuilder,
35
+ NgrokLabeledTunnelBuilder,
36
+ NgrokTcpTunnelBuilder,
37
+ NgrokTlsTunnelBuilder,
38
+ },
20
39
  };
21
40
 
22
41
  /// The builder for an ngrok session.
23
42
  #[napi]
24
43
  #[allow(dead_code)]
25
44
  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();
45
+ raw_builder: Arc<SyncMutex<SessionBuilder>>,
39
46
  }
40
47
 
41
48
  #[napi]
@@ -46,85 +53,214 @@ impl NgrokSessionBuilder {
46
53
  #[napi(constructor)]
47
54
  pub fn new() -> Self {
48
55
  NgrokSessionBuilder {
49
- raw_builder: Session::builder(),
56
+ raw_builder: Arc::new(SyncMutex::new(Session::builder())),
50
57
  }
51
58
  }
52
59
 
53
- /// Authenticate the ngrok session with the given authtoken.
60
+ /// Configures the session to authenticate with the provided authtoken. You
61
+ /// can [find your existing authtoken] or [create a new one] in the ngrok
62
+ /// dashboard.
63
+ ///
64
+ /// See the [authtoken parameter in the ngrok docs] for additional details.
65
+ ///
66
+ /// [find your existing authtoken]: https://dashboard.ngrok.com/get-started/your-authtoken
67
+ /// [create a new one]: https://dashboard.ngrok.com/tunnels/authtokens
68
+ /// [authtoken parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#authtoken
54
69
  #[napi]
55
70
  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);
71
+ let mut builder = self.raw_builder.lock();
72
+ *builder = builder.clone().authtoken(authtoken);
61
73
  self
62
74
  }
63
75
 
64
- /// Authenticate using the authtoken in the `NGROK_AUTHTOKEN` environment
65
- /// variable.
76
+ /// Shortcut for calling [SessionBuilder::authtoken] with the value of the
77
+ /// NGROK_AUTHTOKEN environment variable.
66
78
  #[napi]
67
79
  pub fn authtoken_from_env(&mut self) -> &Self {
68
- self.raw_builder = self.raw_builder.clone().authtoken_from_env();
80
+ let mut builder = self.raw_builder.lock();
81
+ *builder = builder.clone().authtoken_from_env();
69
82
  self
70
83
  }
71
84
 
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.
85
+ /// Configures how often the session will send heartbeat messages to the ngrok
86
+ /// service to check session liveness.
87
+ ///
88
+ /// See the [heartbeat_interval parameter in the ngrok docs] for additional
89
+ /// details.
90
+ ///
91
+ /// [heartbeat_interval parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#heartbeat_interval
75
92
  #[napi]
76
93
  pub fn heartbeat_interval(&mut self, heartbeat_interval: u32) -> &Self {
77
- self.raw_builder = self
78
- .raw_builder
94
+ let mut builder = self.raw_builder.lock();
95
+ *builder = builder
79
96
  .clone()
80
97
  .heartbeat_interval(Duration::new(heartbeat_interval.into(), 0));
81
98
  self
82
99
  }
83
100
 
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.
101
+ /// Configures the duration to wait for a response to a heartbeat before
102
+ /// assuming the session connection is dead and attempting to reconnect.
103
+ ///
104
+ /// See the [heartbeat_tolerance parameter in the ngrok docs] for additional
105
+ /// details.
106
+ ///
107
+ /// [heartbeat_tolerance parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#heartbeat_tolerance
87
108
  #[napi]
88
109
  pub fn heartbeat_tolerance(&mut self, heartbeat_tolerance: u32) -> &Self {
89
- self.raw_builder = self
90
- .raw_builder
110
+ let mut builder = self.raw_builder.lock();
111
+ *builder = builder
91
112
  .clone()
92
113
  .heartbeat_tolerance(Duration::new(heartbeat_tolerance.into(), 0));
93
114
  self
94
115
  }
95
116
 
96
- /// Use the provided opaque metadata string for this session.
97
- /// Viewable from the ngrok dashboard or API.
117
+ /// Configures the opaque, machine-readable metadata string for this session.
118
+ /// Metadata is made available to you in the ngrok dashboard and the Agents API
119
+ /// resource. It is a useful way to allow you to uniquely identify sessions. We
120
+ /// suggest encoding the value in a structured format like JSON.
121
+ ///
122
+ /// See the [metdata parameter in the ngrok docs] for additional details.
123
+ ///
124
+ /// [metdata parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#metadata
98
125
  #[napi]
99
126
  pub fn metadata(&mut self, metadata: String) -> &Self {
100
- self.raw_builder = self.raw_builder.clone().metadata(metadata);
127
+ let mut builder = self.raw_builder.lock();
128
+ *builder = builder.clone().metadata(metadata);
101
129
  self
102
130
  }
103
131
 
104
- /// Connect to the provided ngrok server address.
132
+ /// Configures the network address to dial to connect to the ngrok service.
133
+ /// Use this option only if you are connecting to a custom agent ingress.
134
+ ///
135
+ /// See the [server_addr parameter in the ngrok docs] for additional details.
136
+ ///
137
+ /// [server_addr parameter in the ngrok docs]: https://ngrok.com/docs/ngrok-agent/config#server_addr
105
138
  #[napi]
106
139
  pub fn server_addr(&mut self, addr: String) -> &Self {
107
- self.raw_builder = self.raw_builder.clone().server_addr(addr).clone();
140
+ let mut builder = self.raw_builder.lock();
141
+ *builder = builder.clone().server_addr(addr);
142
+ self
143
+ }
144
+
145
+ /// Configures a function which is called when the ngrok service requests that
146
+ /// this [Session] stops. Your application may choose to interpret this callback
147
+ /// as a request to terminate the [Session] or the entire process.
148
+ ///
149
+ /// Errors returned by this function will be visible to the ngrok dashboard or
150
+ /// API as the response to the Stop operation.
151
+ ///
152
+ /// Do not block inside this callback. It will cause the Dashboard or API
153
+ /// stop operation to time out. Do not call [std::process::exit] inside this
154
+ /// callback, it will also cause the operation to time out.
155
+ #[napi(ts_args_type = "handler: () => void")]
156
+ pub fn handle_stop_command(&mut self, handler: JsFunction) -> &Self {
157
+ // create threadsafe function
158
+ let tsfn = create_no_io_tsfn(handler);
159
+ // register stop handler
160
+ let mut builder = self.raw_builder.lock();
161
+ *builder = builder.clone().handle_stop_command(move |_req| {
162
+ let tsfn = tsfn.clone();
163
+ async move {
164
+ tsfn.clone()
165
+ .lock()
166
+ .await
167
+ .call((), ThreadsafeFunctionCallMode::NonBlocking);
168
+ Ok(())
169
+ }
170
+ });
171
+ self
172
+ }
173
+
174
+ /// Configures a function which is called when the ngrok service requests
175
+ /// that this [Session] updates. Your application may choose to interpret
176
+ /// this callback as a request to restart the [Session] or the entire
177
+ /// process.
178
+ ///
179
+ /// Errors returned by this function will be visible to the ngrok dashboard or
180
+ /// API as the response to the Restart operation.
181
+ ///
182
+ /// Do not block inside this callback. It will cause the Dashboard or API
183
+ /// stop operation to time out. Do not call [std::process::exit] inside this
184
+ /// callback, it will also cause the operation to time out.
185
+ #[napi(ts_args_type = "handler: () => void")]
186
+ pub fn handle_restart_command(&mut self, handler: JsFunction) -> &Self {
187
+ // create threadsafe function
188
+ let tsfn = create_no_io_tsfn(handler);
189
+ // register restart handler
190
+ let mut builder = self.raw_builder.lock();
191
+ *builder = builder.clone().handle_restart_command(move |_req| {
192
+ let tsfn = tsfn.clone();
193
+ async move {
194
+ tsfn.clone()
195
+ .lock()
196
+ .await
197
+ .call((), ThreadsafeFunctionCallMode::NonBlocking);
198
+ Ok(())
199
+ }
200
+ });
201
+ self
202
+ }
203
+
204
+ /// Configures a function which is called when the ngrok service requests
205
+ /// that this [Session] updates. Your application may choose to interpret
206
+ /// this callback as a request to update its configuration, itself, or to
207
+ /// invoke some other application-specific behavior.
208
+ ///
209
+ /// Errors returned by this function will be visible to the ngrok dashboard or
210
+ /// API as the response to the Restart operation.
211
+ ///
212
+ /// Do not block inside this callback. It will cause the Dashboard or API
213
+ /// stop operation to time out. Do not call [std::process::exit] inside this
214
+ /// callback, it will also cause the operation to time out.
215
+ #[napi(ts_args_type = "handler: (update: UpdateRequest) => void")]
216
+ pub fn handle_update_command(&mut self, handler: JsFunction) -> &Self {
217
+ // create threadsafe function
218
+ let tsfn: Arc<Mutex<ThreadsafeFunction<UpdateRequest, ErrorStrategy::Fatal>>> =
219
+ Arc::new(Mutex::new(
220
+ handler
221
+ .create_threadsafe_function(0, |ctx: ThreadSafeCallContext<UpdateRequest>| {
222
+ Ok(vec![ctx.value])
223
+ })
224
+ .expect("Failed to create update callback function"),
225
+ ));
226
+ // register update handler
227
+ let mut builder = self.raw_builder.lock();
228
+ *builder = builder.clone().handle_update_command(move |req: Update| {
229
+ let tsfn = tsfn.clone();
230
+ let update = UpdateRequest {
231
+ version: req.version,
232
+ permit_major_version: req.permit_major_version,
233
+ };
234
+
235
+ async move {
236
+ tsfn.clone()
237
+ .lock()
238
+ .await
239
+ .call(update, ThreadsafeFunctionCallMode::NonBlocking);
240
+ Ok(())
241
+ }
242
+ });
108
243
  self
109
244
  }
110
245
 
111
246
  // Omitting these configurations:
112
247
  // tls_config(&mut self, config: rustls::ClientConfig)
113
- // with_connect_callback(&mut self, callback: ConnectCallback)
248
+ // connector(&mut self, connect: ConnectFn)
114
249
 
115
250
  /// Attempt to establish an ngrok session using the current configuration.
116
251
  #[napi]
117
252
  pub async fn connect(&self) -> Result<NgrokSession> {
118
- self.raw_builder
253
+ let builder = self.raw_builder.lock().clone();
254
+ builder
119
255
  .connect()
120
256
  .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
- )
257
+ .map(|s| {
258
+ info!("Session created");
259
+ NgrokSession {
260
+ raw_session: Arc::new(SyncMutex::new(s)),
261
+ }
127
262
  })
263
+ .map_err(|e| napi_err(format!("failed to connect session, {e:?}")))
128
264
  }
129
265
  }
130
266
 
@@ -132,7 +268,7 @@ impl NgrokSessionBuilder {
132
268
  #[napi(custom_finalize)]
133
269
  struct NgrokSession {
134
270
  #[allow(dead_code)]
135
- raw_session: Session,
271
+ raw_session: Arc<SyncMutex<Session>>,
136
272
  }
137
273
 
138
274
  #[napi]
@@ -141,25 +277,46 @@ impl NgrokSession {
141
277
  /// Start building a tunnel backing an HTTP endpoint.
142
278
  #[napi]
143
279
  pub fn http_endpoint(&self) -> NgrokHttpTunnelBuilder {
144
- NgrokHttpTunnelBuilder::new(self.raw_session.http_endpoint())
280
+ let session = self.raw_session.lock().clone();
281
+ NgrokHttpTunnelBuilder::new(session.clone(), session.http_endpoint())
145
282
  }
146
283
 
147
284
  /// Start building a tunnel backing a TCP endpoint.
148
285
  #[napi]
149
286
  pub fn tcp_endpoint(&self) -> NgrokTcpTunnelBuilder {
150
- NgrokTcpTunnelBuilder::new(self.raw_session.tcp_endpoint())
287
+ let session = self.raw_session.lock().clone();
288
+ NgrokTcpTunnelBuilder::new(session.clone(), session.tcp_endpoint())
151
289
  }
152
290
 
153
291
  /// Start building a tunnel backing a TLS endpoint.
154
292
  #[napi]
155
293
  pub fn tls_endpoint(&self) -> NgrokTlsTunnelBuilder {
156
- NgrokTlsTunnelBuilder::new(self.raw_session.tls_endpoint())
294
+ let session = self.raw_session.lock().clone();
295
+ NgrokTlsTunnelBuilder::new(session.clone(), session.tls_endpoint())
157
296
  }
158
297
 
159
298
  /// Start building a labeled tunnel.
160
299
  #[napi]
161
300
  pub fn labeled_tunnel(&self) -> NgrokLabeledTunnelBuilder {
162
- NgrokLabeledTunnelBuilder::new(self.raw_session.labeled_tunnel())
301
+ let session = self.raw_session.lock().clone();
302
+ NgrokLabeledTunnelBuilder::new(session.clone(), session.labeled_tunnel())
303
+ }
304
+
305
+ /// Close a tunnel with the given ID.
306
+ #[napi]
307
+ pub async fn close_tunnel(&self, id: String) -> Result<()> {
308
+ let session = self.raw_session.lock().clone();
309
+ // close tunnel
310
+ let res = session
311
+ .close_tunnel(id.clone())
312
+ .await
313
+ .map_err(|e| napi_err(format!("failed to close tunnel, {e:?}")));
314
+
315
+ if res.is_ok() {
316
+ // remove our reference to allow it to drop
317
+ remove_global_tunnel(&id).await;
318
+ }
319
+ res
163
320
  }
164
321
  }
165
322
 
@@ -169,3 +326,22 @@ impl ObjectFinalize for NgrokSession {
169
326
  Ok(())
170
327
  }
171
328
  }
329
+
330
+ #[derive(Clone)]
331
+ #[napi]
332
+ pub struct UpdateRequest {
333
+ /// The version that the agent is requested to update to.
334
+ pub version: String,
335
+ /// Whether or not updating to the same major version is sufficient.
336
+ pub permit_major_version: bool,
337
+ }
338
+
339
+ pub(crate) fn create_no_io_tsfn(
340
+ js_function: JsFunction,
341
+ ) -> Arc<Mutex<ThreadsafeFunction<(), ErrorStrategy::Fatal>>> {
342
+ Arc::new(Mutex::new(
343
+ js_function
344
+ .create_threadsafe_function(0, |_ctx: ThreadSafeCallContext<()>| Ok(vec![()]))
345
+ .expect("Failed to create callback function"),
346
+ ))
347
+ }
package/src/tcp.rs CHANGED
@@ -8,7 +8,8 @@ impl NgrokTcpTunnelBuilder {
8
8
  /// The TCP address to request for this edge.
9
9
  #[napi]
10
10
  pub fn remote_addr(&mut self, remote_addr: String) -> &Self {
11
- self.tunnel_builder = self.tunnel_builder.clone().remote_addr(remote_addr);
11
+ let mut builder = self.tunnel_builder.lock();
12
+ *builder = builder.clone().remote_addr(remote_addr);
12
13
  self
13
14
  }
14
15
  }
package/src/tls.rs CHANGED
@@ -10,35 +10,27 @@ impl NgrokTlsTunnelBuilder {
10
10
  /// The domain to request for this edge.
11
11
  #[napi]
12
12
  pub fn domain(&mut self, domain: String) -> &Self {
13
- self.tunnel_builder = self.tunnel_builder.clone().domain(domain);
13
+ let mut builder = self.tunnel_builder.lock();
14
+ *builder = builder.clone().domain(domain);
14
15
  self
15
16
  }
16
17
  /// Certificates to use for client authentication at the ngrok edge.
17
18
  #[napi]
18
19
  pub fn mutual_tlsca(&mut self, mutual_tlsca: Uint8Array) -> &Self {
19
- self.tunnel_builder = self
20
- .tunnel_builder
20
+ let mut builder = self.tunnel_builder.lock();
21
+ *builder = builder
21
22
  .clone()
22
23
  .mutual_tlsca(Bytes::from(mutual_tlsca.to_vec()));
23
24
  self
24
25
  }
25
26
  /// The key to use for TLS termination at the ngrok edge in PEM format.
26
27
  #[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()));
28
+ pub fn termination(&mut self, cert_pem: Uint8Array, key_pem: Uint8Array) -> &Self {
29
+ let mut builder = self.tunnel_builder.lock();
30
+ *builder = builder.clone().termination(
31
+ Bytes::from(cert_pem.to_vec()),
32
+ Bytes::from(key_pem.to_vec()),
33
+ );
42
34
  self
43
35
  }
44
36
  }